@ouro.bot/cli 0.1.0-alpha.1139 → 0.1.0-alpha.1140
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/changelog.json +7 -0
- package/deploy/unraid/sanctuary.ouro/agent.json +6 -0
- package/deploy/unraid/sanctuary.ouro/bundle-meta.json +1 -1
- package/deploy/unraid/sanctuary.xml +1 -1
- package/dist/heart/core.js +99 -2
- package/dist/heart/identity.js +18 -0
- package/dist/heart/provider-attempt.js +1 -1
- package/dist/heart/provider-fallback.js +228 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
package/changelog.json
CHANGED
|
@@ -1,6 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"_note": "This changelog is maintained as part of the PR/version-bump workflow. Agent-curated, not auto-generated. Agents read this file directly via read_file to understand what changed between versions.",
|
|
3
3
|
"versions": [
|
|
4
|
+
{
|
|
5
|
+
"version": "0.1.0-alpha.1140",
|
|
6
|
+
"changes": [
|
|
7
|
+
"When an agent opts in with providerFallback in agent.json, a turn whose provider fails with credit, auth, rate-limit, outage or network errors carries on with the next provider (the Butler goes from Claude to MiniMax) instead of asking anyone to switch.",
|
|
8
|
+
"When an agent opts in with providerFallback in agent.json, a turn whose provider fails with credit, auth, rate-limit, outage or network errors carries on with the next provider (the Butler goes from Claude to MiniMax) instead of asking anyone to switch, and the owner hears once that a backup took over."
|
|
9
|
+
]
|
|
10
|
+
},
|
|
4
11
|
{
|
|
5
12
|
"version": "0.1.0-alpha.1139",
|
|
6
13
|
"changes": [
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
<?xml version="1.0"?>
|
|
2
2
|
<Container version="2">
|
|
3
3
|
<Name>ouro-butler</Name>
|
|
4
|
-
<Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.
|
|
4
|
+
<Repository>ghcr.io/ourostack/ouroboros-butler:0.1.0-alpha.1140</Repository>
|
|
5
5
|
<Registry>https://github.com/ourostack/ouroboros/pkgs/container/ouroboros-butler</Registry>
|
|
6
6
|
<Network>host</Network>
|
|
7
7
|
<Shell>sh</Shell>
|
package/dist/heart/core.js
CHANGED
|
@@ -70,6 +70,7 @@ const tool_output_budget_1 = require("./tool-output-budget");
|
|
|
70
70
|
const delegated_command_1 = require("../a2a/delegated-command");
|
|
71
71
|
const provider_models_1 = require("./provider-models");
|
|
72
72
|
const provider_credentials_1 = require("./provider-credentials");
|
|
73
|
+
const provider_fallback_1 = require("./provider-fallback");
|
|
73
74
|
const habit_session_1 = require("./habits/habit-session");
|
|
74
75
|
const provider_attempt_1 = require("./provider-attempt");
|
|
75
76
|
const openai_codex_token_1 = require("./providers/openai-codex-token");
|
|
@@ -190,6 +191,23 @@ async function getProviderRuntime(facing = "human", owner) {
|
|
|
190
191
|
// The shared tool loop supplies approval continuation to every provider adapter.
|
|
191
192
|
return { ...runtime, capabilities: new Set([...runtime.capabilities, "approval-continuation"]) };
|
|
192
193
|
}
|
|
194
|
+
/** A runtime for one entry of an agent's provider fallback chain, built fresh from its vault credentials. */
|
|
195
|
+
async function getChainEntryRuntime(entry, owner) {
|
|
196
|
+
const agentName = owner?.agentName ?? (0, identity_2.getAgentName)();
|
|
197
|
+
const credential = await (0, provider_credentials_1.readProviderCredentialRecord)(agentName, entry.provider);
|
|
198
|
+
if (!credential.ok)
|
|
199
|
+
throw new Error(`${entry.provider} (${entry.model}) has no credentials for ${agentName}: ${credential.error}`);
|
|
200
|
+
const runtimeOwner = { agentName, agentRoot: owner?.agentRoot ?? (0, identity_2.getAgentRoot)(agentName) };
|
|
201
|
+
const runtime = createProviderRegistry().resolve(entry.provider, entry.model, credential.record, runtimeOwner);
|
|
202
|
+
/* v8 ignore next -- defensive: the registry resolves every provider id @preserve */
|
|
203
|
+
if (!runtime)
|
|
204
|
+
throw new Error(`${entry.provider} (${entry.model}) runtime could not be initialized.`);
|
|
205
|
+
return { ...runtime, capabilities: new Set([...runtime.capabilities, "approval-continuation"]) };
|
|
206
|
+
}
|
|
207
|
+
// Called after getProviderRuntime has loaded the same agent.json, so a bad config has already failed the turn.
|
|
208
|
+
function resolveTurnFallbackChain(facing, owner) {
|
|
209
|
+
return (0, provider_fallback_1.providerFallbackChain)((0, identity_1.loadAgentConfig)(owner), providerLaneForFacing(facing));
|
|
210
|
+
}
|
|
193
211
|
/**
|
|
194
212
|
* Clear cached provider construction inputs so the next access re-reads them
|
|
195
213
|
* from current config. Runtime instances are always per-caller and are never
|
|
@@ -1060,7 +1078,64 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
1060
1078
|
const owner = options?.toolContext?.agentName && options.toolContext.agentRoot
|
|
1061
1079
|
? { agentName: options.toolContext.agentName, agentRoot: options.toolContext.agentRoot }
|
|
1062
1080
|
: undefined;
|
|
1081
|
+
// Automatic fallback (opt-in via agent.json providerFallback): start on the first chain entry not cooling down.
|
|
1063
1082
|
let providerRuntime = options?.providerRuntimeOverride ?? await getProviderRuntime(facing, owner);
|
|
1083
|
+
const fallbackChain = options?.providerRuntimeOverride ? [] : resolveTurnFallbackChain(facing, owner);
|
|
1084
|
+
let chainIndex = 0;
|
|
1085
|
+
const switchToChainEntry = async (from, firstCandidate, reason) => {
|
|
1086
|
+
for (let candidate = firstCandidate; candidate !== null; candidate = (0, provider_fallback_1.nextReadyChainIndex)(fallbackChain, candidate)) {
|
|
1087
|
+
try {
|
|
1088
|
+
providerRuntime = await getChainEntryRuntime(fallbackChain[candidate], owner);
|
|
1089
|
+
chainIndex = candidate;
|
|
1090
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1091
|
+
level: "warn",
|
|
1092
|
+
component: "engine",
|
|
1093
|
+
event: "engine.provider_fallback",
|
|
1094
|
+
message: reason ? "provider failed with an error the agent cannot fix; the turn carries on with the next provider" : "turn starts on a fallback provider while the primary cools down",
|
|
1095
|
+
meta: {
|
|
1096
|
+
lane: providerLaneForFacing(facing),
|
|
1097
|
+
fromProvider: fallbackChain[from].provider,
|
|
1098
|
+
fromModel: fallbackChain[from].model,
|
|
1099
|
+
toProvider: fallbackChain[candidate].provider,
|
|
1100
|
+
toModel: fallbackChain[candidate].model,
|
|
1101
|
+
classification: reason?.classification ?? "cooling-down",
|
|
1102
|
+
...(reason ? { error: reason.error.message.slice(0, 200) } : {}),
|
|
1103
|
+
},
|
|
1104
|
+
});
|
|
1105
|
+
return true;
|
|
1106
|
+
}
|
|
1107
|
+
catch (error) {
|
|
1108
|
+
(0, provider_fallback_1.coolDownProviderEntry)(fallbackChain[candidate], "auth-failure", error instanceof Error ? error : /* v8 ignore next @preserve */ new Error(String(error)));
|
|
1109
|
+
(0, runtime_1.emitNervesEvent)({
|
|
1110
|
+
level: "warn",
|
|
1111
|
+
component: "engine",
|
|
1112
|
+
event: "engine.provider_fallback_unavailable",
|
|
1113
|
+
message: "fallback provider could not be built; trying the next one",
|
|
1114
|
+
meta: { provider: fallbackChain[candidate].provider, model: fallbackChain[candidate].model, error: error instanceof Error ? error.message : /* v8 ignore next @preserve */ String(error) },
|
|
1115
|
+
});
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
return false;
|
|
1119
|
+
};
|
|
1120
|
+
if (fallbackChain.length > 0) {
|
|
1121
|
+
const startIndex = (0, provider_fallback_1.firstReadyChainIndex)(fallbackChain);
|
|
1122
|
+
if (startIndex > 0)
|
|
1123
|
+
await switchToChainEntry(0, startIndex, null);
|
|
1124
|
+
}
|
|
1125
|
+
const rebuildCurrentRuntime = () => chainIndex === 0
|
|
1126
|
+
? getProviderRuntime(facing, owner)
|
|
1127
|
+
: getChainEntryRuntime(fallbackChain[chainIndex], owner);
|
|
1128
|
+
const fallBackAfterTerminalError = async (error, classification) => {
|
|
1129
|
+
if (fallbackChain.length === 0 || !(0, provider_fallback_1.fallsBackOn)(classification))
|
|
1130
|
+
return false;
|
|
1131
|
+
(0, provider_fallback_1.coolDownProviderEntry)(fallbackChain[chainIndex], classification, error);
|
|
1132
|
+
const from = chainIndex;
|
|
1133
|
+
if (!await switchToChainEntry(from, (0, provider_fallback_1.nextReadyChainIndex)(fallbackChain, from), { classification, error }))
|
|
1134
|
+
return false;
|
|
1135
|
+
providerRuntime.resetTurnState(messages);
|
|
1136
|
+
return true;
|
|
1137
|
+
};
|
|
1138
|
+
let servedByProvider = false;
|
|
1064
1139
|
const provider = providerRuntime.id;
|
|
1065
1140
|
const toolChoiceRequired = options?.hardDisableTools ? false : options?.toolChoiceRequired ?? true;
|
|
1066
1141
|
const traceId = options?.traceId;
|
|
@@ -1593,7 +1668,8 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
1593
1668
|
callbacks.onError(new Error("context trimmed, retrying..."), "transient");
|
|
1594
1669
|
return callProviderTurn();
|
|
1595
1670
|
}
|
|
1596
|
-
|
|
1671
|
+
// A 400 for spent credit is not a malformed request: correcting history cannot fix it.
|
|
1672
|
+
if (isRejectedRequest(error) && !rejectedRequestRetried && providerRuntime.classifyError(error) !== "usage-limit") {
|
|
1597
1673
|
// Never leave the agent unable to answer: correct what the runtime sent, tell the agent why, and let it carry on.
|
|
1598
1674
|
rejectedRequestRetried = true;
|
|
1599
1675
|
replayedReasoningDropped = true;
|
|
@@ -1618,6 +1694,8 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
1618
1694
|
model: providerRuntime.model,
|
|
1619
1695
|
run: callProviderTurnWithOverflowRecovery,
|
|
1620
1696
|
classifyError: (error) => providerRuntime.classifyError(error),
|
|
1697
|
+
// Spent credit will not come back in seconds: move straight to the next provider when one is ready.
|
|
1698
|
+
shouldRetry: (classification) => classification !== "usage-limit" || (0, provider_fallback_1.nextReadyChainIndex)(fallbackChain, chainIndex) === null,
|
|
1621
1699
|
onRetry: async (record, maxAttempts) => {
|
|
1622
1700
|
const delayMs = record.delayMs;
|
|
1623
1701
|
const seconds = delayMs / 1000;
|
|
@@ -1635,7 +1713,7 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
1635
1713
|
providers: [record.provider],
|
|
1636
1714
|
});
|
|
1637
1715
|
_providerRuntimeFactories[facing] = null;
|
|
1638
|
-
providerRuntime = await
|
|
1716
|
+
providerRuntime = await rebuildCurrentRuntime();
|
|
1639
1717
|
providerRuntime.resetTurnState(attemptMessages);
|
|
1640
1718
|
}
|
|
1641
1719
|
catch (refreshError) {
|
|
@@ -1655,10 +1733,13 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
1655
1733
|
},
|
|
1656
1734
|
});
|
|
1657
1735
|
if (!attempt.ok) {
|
|
1736
|
+
if (await fallBackAfterTerminalError(attempt.error, attempt.classification))
|
|
1737
|
+
continue;
|
|
1658
1738
|
finishTerminalProviderError(attempt.error, attempt.classification);
|
|
1659
1739
|
continue;
|
|
1660
1740
|
}
|
|
1661
1741
|
const result = attempt.value;
|
|
1742
|
+
servedByProvider = true;
|
|
1662
1743
|
nextAttemptControls = [];
|
|
1663
1744
|
providerIterations += 1;
|
|
1664
1745
|
if (stepReportIteration !== null) {
|
|
@@ -2743,6 +2824,22 @@ async function runAgent(messages, callbacks, channel, signal, options) {
|
|
|
2743
2824
|
providerRuntime.resetTurnState(messages);
|
|
2744
2825
|
}
|
|
2745
2826
|
options?.captureGeneratedMessages?.(structuredClone(generatedMessages));
|
|
2827
|
+
if (servedByProvider && !terminalError) {
|
|
2828
|
+
const chain = fallbackChain.length > 0 ? fallbackChain : [{ provider: providerRuntime.id, model: providerRuntime.model }];
|
|
2829
|
+
try {
|
|
2830
|
+
(0, provider_fallback_1.noteProviderServed)({
|
|
2831
|
+
agentName: owner?.agentName ?? (0, identity_2.getAgentName)(),
|
|
2832
|
+
agentRoot: owner?.agentRoot ?? (0, identity_2.getAgentRoot)(),
|
|
2833
|
+
lane: providerLaneForFacing(facing),
|
|
2834
|
+
chain,
|
|
2835
|
+
index: fallbackChain.length > 0 ? chainIndex : 0,
|
|
2836
|
+
});
|
|
2837
|
+
/* v8 ignore next 3 -- defensive: attribution must never fail a turn that already answered @preserve */
|
|
2838
|
+
}
|
|
2839
|
+
catch {
|
|
2840
|
+
// The answer stands; attribution is best effort.
|
|
2841
|
+
}
|
|
2842
|
+
}
|
|
2746
2843
|
(0, runtime_1.emitNervesEvent)({
|
|
2747
2844
|
event: "engine.turn_end",
|
|
2748
2845
|
trace_id: traceId,
|
package/dist/heart/identity.js
CHANGED
|
@@ -497,6 +497,23 @@ function validateFacingConfig(parsed, facingName, configFile) {
|
|
|
497
497
|
}
|
|
498
498
|
return { provider: facing.provider, model: facing.model };
|
|
499
499
|
}
|
|
500
|
+
function validateProviderFallback(raw, configFile) {
|
|
501
|
+
const entries = Array.isArray(raw) ? raw : null;
|
|
502
|
+
const valid = entries?.every((entry) => entry && typeof entry === "object" && !Array.isArray(entry)
|
|
503
|
+
&& isValidProvider(entry.provider)
|
|
504
|
+
&& typeof entry.model === "string");
|
|
505
|
+
if (!entries || !valid) {
|
|
506
|
+
(0, runtime_1.emitNervesEvent)({
|
|
507
|
+
level: "error",
|
|
508
|
+
event: "config_identity.error",
|
|
509
|
+
component: "config/identity",
|
|
510
|
+
message: "agent config has invalid providerFallback",
|
|
511
|
+
meta: { path: configFile, providerFallback: raw },
|
|
512
|
+
});
|
|
513
|
+
throw new Error(`agent.json at ${configFile} providerFallback must be a list of { provider, model } with provider one of: ${VALID_PROVIDERS.join(", ")}.`);
|
|
514
|
+
}
|
|
515
|
+
return entries.map((entry) => ({ provider: entry.provider, model: entry.model }));
|
|
516
|
+
}
|
|
500
517
|
/**
|
|
501
518
|
* Load and parse `<agentRoot>/agent.json`.
|
|
502
519
|
* Reads the explicit owner's file fresh, or preserves the legacy ambient override when no owner is supplied.
|
|
@@ -599,6 +616,7 @@ function loadAgentConfig(owner) {
|
|
|
599
616
|
enabled,
|
|
600
617
|
humanFacing,
|
|
601
618
|
agentFacing,
|
|
619
|
+
...(parsed.providerFallback !== undefined ? { providerFallback: validateProviderFallback(parsed.providerFallback, configFile) } : {}),
|
|
602
620
|
habitPaidTurnsPerDay: (0, autonomy_budget_1.normalizeHabitPaidTurnsPerDay)(owner === undefined ? getAgentName() : owner.agentName, parsed.habitPaidTurnsPerDay, configFile),
|
|
603
621
|
senses: normalizeSenses(parsed.senses, configFile),
|
|
604
622
|
phrases: parsed.phrases,
|
|
@@ -77,7 +77,7 @@ async function runProviderAttempt(input) {
|
|
|
77
77
|
throw caught;
|
|
78
78
|
const error = toError(caught);
|
|
79
79
|
const classification = classify(caught, input.classifyError);
|
|
80
|
-
const willRetry = isRetryable(error) && attempt < maxAttempts;
|
|
80
|
+
const willRetry = isRetryable(error) && attempt < maxAttempts && (input.shouldRetry?.(classification) ?? true);
|
|
81
81
|
const delayMs = willRetry ? delayForAttempt(policy, attempt) : undefined;
|
|
82
82
|
const record = {
|
|
83
83
|
attempt,
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.setProviderFallbackOwnerNotifier = setProviderFallbackOwnerNotifier;
|
|
37
|
+
exports.resetProviderFallbackState = resetProviderFallbackState;
|
|
38
|
+
exports.providerFallbackChain = providerFallbackChain;
|
|
39
|
+
exports.fallsBackOn = fallsBackOn;
|
|
40
|
+
exports.providerCooldownUntil = providerCooldownUntil;
|
|
41
|
+
exports.coolDownProviderEntry = coolDownProviderEntry;
|
|
42
|
+
exports.clearProviderEntryCooldown = clearProviderEntryCooldown;
|
|
43
|
+
exports.providerEntryCoolingDown = providerEntryCoolingDown;
|
|
44
|
+
exports.firstReadyChainIndex = firstReadyChainIndex;
|
|
45
|
+
exports.nextReadyChainIndex = nextReadyChainIndex;
|
|
46
|
+
exports.noteProviderServed = noteProviderServed;
|
|
47
|
+
const runtime_1 = require("../nerves/runtime");
|
|
48
|
+
const FALLBACK_CLASSIFICATIONS = new Set([
|
|
49
|
+
"auth-failure",
|
|
50
|
+
"usage-limit",
|
|
51
|
+
"rate-limit",
|
|
52
|
+
"server-error",
|
|
53
|
+
"network-error",
|
|
54
|
+
]);
|
|
55
|
+
const MINUTE_MS = 60_000;
|
|
56
|
+
const HOUR_MS = 60 * MINUTE_MS;
|
|
57
|
+
const NOTICE_INTERVAL_MS = 24 * HOUR_MS;
|
|
58
|
+
const REASON_TEXT = {
|
|
59
|
+
"auth-failure": "rejecting its key",
|
|
60
|
+
"usage-limit": "out of credit or over its usage limit",
|
|
61
|
+
"rate-limit": "rate limited",
|
|
62
|
+
"server-error": "having an outage",
|
|
63
|
+
"network-error": "unreachable",
|
|
64
|
+
"unknown": "failing",
|
|
65
|
+
};
|
|
66
|
+
const PROVIDER_NAMES = {
|
|
67
|
+
anthropic: "Claude",
|
|
68
|
+
minimax: "MiniMax",
|
|
69
|
+
};
|
|
70
|
+
const cooldowns = new Map();
|
|
71
|
+
const episodes = new Map();
|
|
72
|
+
const lastNoticeAt = new Map();
|
|
73
|
+
let ownerNotifier = null;
|
|
74
|
+
/** Replace how the owner is told a backup took over. Null restores the shared owner notice path. */
|
|
75
|
+
function setProviderFallbackOwnerNotifier(notifier) {
|
|
76
|
+
ownerNotifier = notifier;
|
|
77
|
+
}
|
|
78
|
+
/** Forget cooldowns and backup episodes (tests, and a fresh process). */
|
|
79
|
+
function resetProviderFallbackState() {
|
|
80
|
+
cooldowns.clear();
|
|
81
|
+
episodes.clear();
|
|
82
|
+
lastNoticeAt.clear();
|
|
83
|
+
}
|
|
84
|
+
function sameEntry(a, b) {
|
|
85
|
+
return a.provider === b.provider && a.model === b.model;
|
|
86
|
+
}
|
|
87
|
+
function providerFallbackChain(config, lane) {
|
|
88
|
+
const fallbacks = config.providerFallback ?? [];
|
|
89
|
+
if (fallbacks.length === 0)
|
|
90
|
+
return [];
|
|
91
|
+
const own = lane === "outward" ? config.humanFacing : config.agentFacing;
|
|
92
|
+
const other = lane === "outward" ? config.agentFacing : config.humanFacing;
|
|
93
|
+
const chain = [];
|
|
94
|
+
for (const entry of [own, other, ...fallbacks]) {
|
|
95
|
+
const candidate = { provider: entry.provider, model: entry.model };
|
|
96
|
+
if (!chain.some((existing) => sameEntry(existing, candidate)))
|
|
97
|
+
chain.push(candidate);
|
|
98
|
+
}
|
|
99
|
+
return chain;
|
|
100
|
+
}
|
|
101
|
+
function fallsBackOn(classification) {
|
|
102
|
+
return FALLBACK_CLASSIFICATIONS.has(classification);
|
|
103
|
+
}
|
|
104
|
+
function retryAfterSeconds(error) {
|
|
105
|
+
const headers = error.headers;
|
|
106
|
+
if (!headers)
|
|
107
|
+
return null;
|
|
108
|
+
const raw = typeof headers.get === "function"
|
|
109
|
+
? headers.get("retry-after")
|
|
110
|
+
: headers["retry-after"];
|
|
111
|
+
const seconds = Number(raw);
|
|
112
|
+
return raw && Number.isFinite(seconds) && seconds > 0 ? seconds : null;
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Until when a failed entry is skipped: Retry-After when the provider gives one; an hour for spent credit or a rejected
|
|
116
|
+
* key, so a dead entry costs one probe an hour rather than one a turn and comes back by itself after a top-up, a new
|
|
117
|
+
* billing cycle or a re-stored key; five minutes for a throttle, an outage or the network.
|
|
118
|
+
*/
|
|
119
|
+
function providerCooldownUntil(classification, error, now) {
|
|
120
|
+
const retryAfter = retryAfterSeconds(error);
|
|
121
|
+
if (retryAfter !== null)
|
|
122
|
+
return now + retryAfter * 1000;
|
|
123
|
+
if (classification === "usage-limit" || classification === "auth-failure")
|
|
124
|
+
return now + HOUR_MS;
|
|
125
|
+
return now + 5 * MINUTE_MS;
|
|
126
|
+
}
|
|
127
|
+
function providerKey(entry) {
|
|
128
|
+
return entry.provider;
|
|
129
|
+
}
|
|
130
|
+
function modelKey(entry) {
|
|
131
|
+
return `${entry.provider}/${entry.model}`;
|
|
132
|
+
}
|
|
133
|
+
/** Credit and keys belong to the provider account, so those bench every model on it; throttles and outages bench one model. */
|
|
134
|
+
function coolDownProviderEntry(entry, classification, error, now = Date.now()) {
|
|
135
|
+
const until = providerCooldownUntil(classification, error, now);
|
|
136
|
+
const scope = classification === "usage-limit" || classification === "auth-failure" ? "provider" : "model";
|
|
137
|
+
cooldowns.set(scope === "provider" ? providerKey(entry) : modelKey(entry), { until, classification });
|
|
138
|
+
(0, runtime_1.emitNervesEvent)({
|
|
139
|
+
level: "warn",
|
|
140
|
+
component: "engine",
|
|
141
|
+
event: "engine.provider_cooldown",
|
|
142
|
+
message: "provider entry benched after an error the agent cannot fix",
|
|
143
|
+
meta: { provider: entry.provider, model: entry.model, classification, scope, until: new Date(until).toISOString() },
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
function clearProviderEntryCooldown(entry) {
|
|
147
|
+
cooldowns.delete(providerKey(entry));
|
|
148
|
+
cooldowns.delete(modelKey(entry));
|
|
149
|
+
}
|
|
150
|
+
function activeCooldown(entry, now) {
|
|
151
|
+
for (const key of [modelKey(entry), providerKey(entry)]) {
|
|
152
|
+
const cooldown = cooldowns.get(key);
|
|
153
|
+
if (cooldown && cooldown.until > now)
|
|
154
|
+
return cooldown;
|
|
155
|
+
}
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
function providerEntryCoolingDown(entry, now = Date.now()) {
|
|
159
|
+
return activeCooldown(entry, now) !== null;
|
|
160
|
+
}
|
|
161
|
+
/** The entry a turn starts on: the first one not cooling down, else the primary (a probe beats giving up). */
|
|
162
|
+
function firstReadyChainIndex(chain, now = Date.now()) {
|
|
163
|
+
const index = chain.findIndex((entry) => !providerEntryCoolingDown(entry, now));
|
|
164
|
+
return index === -1 ? 0 : index;
|
|
165
|
+
}
|
|
166
|
+
function nextReadyChainIndex(chain, after, now = Date.now()) {
|
|
167
|
+
for (let index = after + 1; index < chain.length; index += 1) {
|
|
168
|
+
if (!providerEntryCoolingDown(chain[index], now))
|
|
169
|
+
return index;
|
|
170
|
+
}
|
|
171
|
+
return null;
|
|
172
|
+
}
|
|
173
|
+
function providerName(provider) {
|
|
174
|
+
return PROVIDER_NAMES[provider] ?? provider;
|
|
175
|
+
}
|
|
176
|
+
function entryLabel(entry) {
|
|
177
|
+
return entry.model ? `${providerName(entry.provider)} (${entry.model})` : providerName(entry.provider);
|
|
178
|
+
}
|
|
179
|
+
function backupNoticeText(primary, backup, now) {
|
|
180
|
+
const cooldown = activeCooldown(primary, now);
|
|
181
|
+
const reason = cooldown ? `is ${REASON_TEXT[cooldown.classification]}` : "hit a provider problem";
|
|
182
|
+
return `${providerName(primary.provider)} ${reason}, so I'm answering on ${entryLabel(backup)} as a backup. Nothing for you to do: I'll move back by myself once it recovers.`;
|
|
183
|
+
}
|
|
184
|
+
function notifyOwner(agentRoot, agentName, notice) {
|
|
185
|
+
if (ownerNotifier) {
|
|
186
|
+
ownerNotifier(agentRoot, agentName, notice);
|
|
187
|
+
return;
|
|
188
|
+
}
|
|
189
|
+
void Promise.resolve().then(() => __importStar(require("./sync"))).then(({ tellOwner }) => tellOwner(agentRoot, agentName, notice));
|
|
190
|
+
}
|
|
191
|
+
/** Record which entry served a turn; tell the owner once when a backup takes over, at most once a day. */
|
|
192
|
+
function noteProviderServed(input) {
|
|
193
|
+
const now = input.now ?? Date.now();
|
|
194
|
+
const served = input.chain[input.index];
|
|
195
|
+
const primary = input.chain[0];
|
|
196
|
+
const fallback = input.index > 0;
|
|
197
|
+
(0, runtime_1.emitNervesEvent)({
|
|
198
|
+
component: "engine",
|
|
199
|
+
event: "engine.provider_served",
|
|
200
|
+
message: "provider served the turn",
|
|
201
|
+
meta: { provider: served.provider, model: served.model, lane: input.lane, fallback, primaryProvider: primary.provider, primaryModel: primary.model },
|
|
202
|
+
});
|
|
203
|
+
const episode = episodes.get(input.agentName);
|
|
204
|
+
if (!fallback) {
|
|
205
|
+
clearProviderEntryCooldown(served);
|
|
206
|
+
if (episode) {
|
|
207
|
+
episodes.delete(input.agentName);
|
|
208
|
+
(0, runtime_1.emitNervesEvent)({
|
|
209
|
+
component: "engine",
|
|
210
|
+
event: "engine.provider_fallback_recovered",
|
|
211
|
+
message: "primary provider is serving again",
|
|
212
|
+
meta: { agentName: input.agentName, provider: served.provider, model: served.model, lane: input.lane, backupSince: new Date(episode.since).toISOString() },
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
if (episode)
|
|
218
|
+
return;
|
|
219
|
+
episodes.set(input.agentName, { since: now });
|
|
220
|
+
const last = lastNoticeAt.get(input.agentName);
|
|
221
|
+
if (last !== undefined && now - last < NOTICE_INTERVAL_MS)
|
|
222
|
+
return;
|
|
223
|
+
lastNoticeAt.set(input.agentName, now);
|
|
224
|
+
notifyOwner(input.agentRoot, input.agentName, {
|
|
225
|
+
noticeId: `provider-fallback:${input.agentName}:${now}`,
|
|
226
|
+
text: backupNoticeText(primary, served, now),
|
|
227
|
+
});
|
|
228
|
+
}
|
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ouro.bot/cli",
|
|
3
|
-
"version": "0.1.0-alpha.
|
|
3
|
+
"version": "0.1.0-alpha.1140",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@ouro.bot/cli",
|
|
9
|
-
"version": "0.1.0-alpha.
|
|
9
|
+
"version": "0.1.0-alpha.1140",
|
|
10
10
|
"dependencies": {
|
|
11
11
|
"@anthropic-ai/sdk": "^0.78.0",
|
|
12
12
|
"@ouro.bot/friends": "0.1.0-alpha.18",
|