@zergai/ztc 0.11.1-dev.202611072103 → 0.12.1-dev.202611080256
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/README.md +36 -1
- package/bin/zmux-darwin-arm64 +0 -0
- package/bin/ztc-audio-darwin-arm64 +0 -0
- package/bin/ztc-capture-darwin-arm64 +0 -0
- package/bin/ztc-tui-darwin-arm64 +0 -0
- package/bin/zterm-darwin-arm64 +0 -0
- package/dist/App.js +27 -3
- package/dist/agent/agent.d.ts +8 -1
- package/dist/agent/agent.js +36 -15
- package/dist/agent/backends/http_error.d.ts +6 -0
- package/dist/agent/backends/http_error.js +31 -18
- package/dist/agent/backends/router_gate.d.ts +81 -0
- package/dist/agent/backends/router_gate.js +133 -0
- package/dist/agent/backends/router_refusal.d.ts +103 -0
- package/dist/agent/backends/router_refusal.js +262 -0
- package/dist/agent/backends/router_refusal_record.d.ts +22 -0
- package/dist/agent/backends/router_refusal_record.js +142 -0
- package/dist/agent/backends/router_requests.d.ts +15 -0
- package/dist/agent/backends/router_requests.js +41 -0
- package/dist/agent/backends/types.d.ts +5 -0
- package/dist/agent/backends/zrouter_stream.d.ts +7 -0
- package/dist/agent/backends/zrouter_stream.js +95 -14
- package/dist/agent/commands/usage.js +7 -2
- package/dist/cli_ratatui.d.ts +23 -0
- package/dist/cli_ratatui.js +102 -15
- package/dist/config.d.ts +8 -0
- package/dist/config.js +10 -0
- package/dist/headless.d.ts +28 -0
- package/dist/headless.js +102 -12
- package/dist/router_budget.d.ts +55 -0
- package/dist/router_budget.js +212 -0
- package/dist/simulation/llm.js +4 -0
- package/dist/simulation/memory/embedding.d.ts +3 -1
- package/dist/simulation/memory/embedding.js +35 -2
- package/dist/ui/views/app.d.ts +3 -1
- package/dist/ui/views/app.js +2 -1
- package/dist/ui/views/status_bar.d.ts +2 -0
- package/dist/ui/views/status_bar.js +5 -0
- package/dist/web/mirror_stream.d.ts +2 -0
- package/dist/web/mirror_stream.js +2 -1
- package/dist/zlm-embed.mjs +649 -236
- package/package.json +4 -8
package/README.md
CHANGED
|
@@ -69,7 +69,8 @@ For browser login at **zergrouter.com**, run `ztc auth login` in your shell or
|
|
|
69
69
|
`/auth login` inside ZTC. Both use the same flow and credentials. `/auth cancel`
|
|
70
70
|
(or Esc) stops a login still waiting for approval; in the shell, Ctrl+C does. See
|
|
71
71
|
[Zerg Router and DeepSeek setup](docs/zerg-router.md) for model selection,
|
|
72
|
-
Claude Code/Codex emulation, and `ztc "prompt"` or `ztc -p "prompt"` usage
|
|
72
|
+
Claude Code/Codex emulation, and `ztc "prompt"` or `ztc -p "prompt"` usage, and
|
|
73
|
+
[Zerg Router limits](#zerg-router-limits) for what ZTC does when Router refuses a request.
|
|
73
74
|
|
|
74
75
|
Use `/model openai [model]` or `/model deepseek [model]` for direct API calls with your
|
|
75
76
|
local keys. Use `/model zergrouter <upstream-provider> [model]` to route through your
|
|
@@ -99,6 +100,40 @@ Inside ZTC, `/sessions` resumes prior work and `/permissions` shows the active
|
|
|
99
100
|
safety profile. Add `--mirror` when you want to observe a longer terminal run
|
|
100
101
|
in the browser mirror. Run `/help` for the full command list.
|
|
101
102
|
|
|
103
|
+
### Zerg Router limits
|
|
104
|
+
|
|
105
|
+
Zerg Router enforces the spending, token and access limits on your account and your
|
|
106
|
+
monthly token quota. When it refuses a request before calling any provider, ZTC ends the
|
|
107
|
+
turn at once with Router's own words, when the limit resets in your local time, and the
|
|
108
|
+
link to your limits. It doesn't retry: the refusal holds that route, account and model for
|
|
109
|
+
the whole ZTC process, so subagents, workers, heartbeats, `/loop` routines, goal loops and
|
|
110
|
+
messages from other panes get the same message without contacting Router. One real request
|
|
111
|
+
every five minutes still goes through, so a raised limit works within minutes, and a
|
|
112
|
+
successful answer for that model lifts the hold. A message you send yourself (typed,
|
|
113
|
+
dictated, from the browser mirror, or given on the command line) gets one real attempt.
|
|
114
|
+
A full concurrency limit is retried a few times, and a provider cooldown is waited out;
|
|
115
|
+
one longer than a minute ends the turn with the time it clears, and nothing, not even
|
|
116
|
+
your own message, is sent to that model before then.
|
|
117
|
+
|
|
118
|
+
Unattended runs (`--headless`, `-p`, `--json`, `--json-stream`) end with **exit status 4**
|
|
119
|
+
on such a refusal, with Router's words on stderr; 2 is a usage error and 3 an
|
|
120
|
+
`--output-schema` failure. That includes a run whose prompt starts a workflow, and a
|
|
121
|
+
`/goal` or `--voyager-loop` run stops at the refusal. The refusal is recorded in
|
|
122
|
+
`router-refusals.json` in ZTC's config directory, with no credentials and nothing of your
|
|
123
|
+
request, so a shell or cron loop that starts ZTC again is refused locally for five minutes
|
|
124
|
+
at a time instead of calling Router. A refusal Router gives no reset for is kept 15
|
|
125
|
+
minutes after it was last met. An interactive launch shows what was recorded and lets you
|
|
126
|
+
try.
|
|
127
|
+
|
|
128
|
+
Signed in with Zerg Router, `/usage` shows your limits and usage, your monthly token
|
|
129
|
+
quota and recent refusals, read from zergrouter.com with your own sign-in, and the status
|
|
130
|
+
bar shows the limit you are closest to, such as `Router $812 / $1,000 week`, or `Router
|
|
131
|
+
limit reached (week)` while Router is refusing you. Unattended runs print one budget line
|
|
132
|
+
on stderr at start when a limit is set or the quota is over 80%, the number of Router
|
|
133
|
+
requests they made at exit, and a warning if they send more than 60 Router requests in a
|
|
134
|
+
minute. On the legacy ZergAI platform login ZTC holds no Router
|
|
135
|
+
credential of yours, so it shows no budget. ZTC doesn't cap requests itself; Router does.
|
|
136
|
+
|
|
102
137
|
## Develop from source
|
|
103
138
|
|
|
104
139
|
```bash
|
package/bin/zmux-darwin-arm64
CHANGED
|
Binary file
|
|
Binary file
|
|
Binary file
|
package/bin/ztc-tui-darwin-arm64
CHANGED
|
Binary file
|
package/bin/zterm-darwin-arm64
CHANGED
|
Binary file
|
package/dist/App.js
CHANGED
|
@@ -28,6 +28,8 @@ import { formatToolStart, formatToolError, buildToolOutputMessage } from './util
|
|
|
28
28
|
import { autoActivateSkills, buildSkillPrompt } from './skills/index.js';
|
|
29
29
|
import { getSkills } from './skills/registry.js';
|
|
30
30
|
import { createAgentFromConfig } from './agent/factory.js';
|
|
31
|
+
import { adoptRouterRefusalRecord, formatRecordedRouterRefusal } from './agent/backends/router_refusal_record.js';
|
|
32
|
+
import { isRouterRefusal } from './agent/backends/router_refusal.js';
|
|
31
33
|
import { hasWorkspaceCollisionRisk, LocalWorkspaceCoordinator, inspectWorkspaceSessions, prepareWorkspaceIsolation, WorkspaceIsolationError } from './workspace_collision.js';
|
|
32
34
|
import { generateSessionId, saveSession } from './session.js';
|
|
33
35
|
import { prepareSessionMessages } from './app/session_messages.js';
|
|
@@ -279,6 +281,15 @@ export const App = () => {
|
|
|
279
281
|
React.useEffect(() => {
|
|
280
282
|
let active = true;
|
|
281
283
|
let runtimeTimer;
|
|
284
|
+
// A refusal an unattended run recorded holds this session's background work; the person's messages still try.
|
|
285
|
+
const recordedRefusals = adoptRouterRefusalRecord('interactive');
|
|
286
|
+
// Shown after the launch readout settles: a second message would keep the readout from refreshing.
|
|
287
|
+
const showRecordedRefusals = () => {
|
|
288
|
+
if (!active || recordedRefusals.length === 0)
|
|
289
|
+
return;
|
|
290
|
+
setMessages(prev => [...prev, ...recordedRefusals.map(hold => ({ id: generateId(), role: 'system',
|
|
291
|
+
content: formatRecordedRouterRefusal(hold), timestamp: new Date() }))]);
|
|
292
|
+
};
|
|
282
293
|
const refreshUntouchedWelcome = (runtime) => {
|
|
283
294
|
if (!active)
|
|
284
295
|
return;
|
|
@@ -302,10 +313,15 @@ export const App = () => {
|
|
|
302
313
|
runtimeTimer = setTimeout(() => {
|
|
303
314
|
const runtime = getRuntimeInfo({ cwd: process.cwd(), includeDirtyHash: false });
|
|
304
315
|
refreshUntouchedWelcome(runtime);
|
|
316
|
+
showRecordedRefusals();
|
|
305
317
|
}, 0);
|
|
306
318
|
}
|
|
319
|
+
else {
|
|
320
|
+
showRecordedRefusals();
|
|
321
|
+
}
|
|
307
322
|
}).catch((error) => {
|
|
308
323
|
debugLog(`[configStore.load] failed while refreshing launch readout: ${String(error)}`);
|
|
324
|
+
showRecordedRefusals();
|
|
309
325
|
});
|
|
310
326
|
return () => {
|
|
311
327
|
active = false;
|
|
@@ -1317,7 +1333,9 @@ export const App = () => {
|
|
|
1317
1333
|
return;
|
|
1318
1334
|
if (isActive && !isActive())
|
|
1319
1335
|
return;
|
|
1320
|
-
|
|
1336
|
+
// Zerg Router refused it (or ZTC holds Router's refusal): its words may mention a rate limit, but a retry only
|
|
1337
|
+
// meets the same refusal.
|
|
1338
|
+
if (isRouterRefusal(err) || !isRetryableError(errorMsg) || attempt >= maxRetries) {
|
|
1321
1339
|
throw err;
|
|
1322
1340
|
}
|
|
1323
1341
|
const delayMs = 500 * Math.pow(2, attempt - 1);
|
|
@@ -1362,6 +1380,8 @@ export const App = () => {
|
|
|
1362
1380
|
queuePausedRef.current = false;
|
|
1363
1381
|
abortControllerRef.current = retryController;
|
|
1364
1382
|
await workspaceCoordinator.setActivity('running');
|
|
1383
|
+
// The person asked for the request again: it gets one real attempt past a Zerg Router refusal, like a new message.
|
|
1384
|
+
last.agent.admitPersonRequest();
|
|
1365
1385
|
try {
|
|
1366
1386
|
await runWithRetry(last.messages, last.agent, true, isActive, retryController.signal);
|
|
1367
1387
|
}
|
|
@@ -1370,7 +1390,7 @@ export const App = () => {
|
|
|
1370
1390
|
if (!isActive())
|
|
1371
1391
|
return;
|
|
1372
1392
|
addMessage({ role: 'system', content: `Error: ${message}` });
|
|
1373
|
-
if (isRetryableError(message)) {
|
|
1393
|
+
if (isRetryableError(message) && !isRouterRefusal(err)) {
|
|
1374
1394
|
addMessage({ role: 'system', content: 'Retries exhausted. Use /retry to try again.' });
|
|
1375
1395
|
setRetryAvailable(true);
|
|
1376
1396
|
}
|
|
@@ -1987,6 +2007,10 @@ export const App = () => {
|
|
|
1987
2007
|
break;
|
|
1988
2008
|
}
|
|
1989
2009
|
});
|
|
2010
|
+
// A message the person just typed gets one real attempt even while Zerg Router's refusal holds the route; a
|
|
2011
|
+
// queued entry never does.
|
|
2012
|
+
if (!queuedEntry)
|
|
2013
|
+
currentAgent.admitPersonRequest();
|
|
1990
2014
|
try {
|
|
1991
2015
|
await runWithRetry(requestMessages, currentAgent, false, isActive, controller.signal, () => {
|
|
1992
2016
|
if (!isActive())
|
|
@@ -2018,7 +2042,7 @@ export const App = () => {
|
|
|
2018
2042
|
role: 'system',
|
|
2019
2043
|
content: `Error: ${errorMsg}`
|
|
2020
2044
|
});
|
|
2021
|
-
if (isRetryableError(errorMsg)) {
|
|
2045
|
+
if (isRetryableError(errorMsg) && !isRouterRefusal(err)) {
|
|
2022
2046
|
addMessage({
|
|
2023
2047
|
role: 'system',
|
|
2024
2048
|
content: 'Retries exhausted. Use /retry to try again.'
|
package/dist/agent/agent.d.ts
CHANGED
|
@@ -195,7 +195,7 @@ export interface HarnessToolCallOptions {
|
|
|
195
195
|
}
|
|
196
196
|
export declare class AgentError extends Error {
|
|
197
197
|
code?: string | undefined;
|
|
198
|
-
constructor(message: string, code?: string | undefined);
|
|
198
|
+
constructor(message: string, code?: string | undefined, options?: ErrorOptions);
|
|
199
199
|
}
|
|
200
200
|
export declare class ContextOverflowError extends AgentError {
|
|
201
201
|
request: BackendRequest;
|
|
@@ -216,6 +216,8 @@ export declare class Agent {
|
|
|
216
216
|
/** One-shot: the next request carries the output-limit note at this effort. */
|
|
217
217
|
/** The next request retries a discarded response: a note for the model, and lower effort when offered. */
|
|
218
218
|
private responseRetry;
|
|
219
|
+
/** One-shot: the next request starts a turn the person's own new message began (see admitPersonRequest). */
|
|
220
|
+
private personRequestPending;
|
|
219
221
|
/** Fast mode — request the priority service tier from the Codex/GPT backend. */
|
|
220
222
|
private _codexFastMode;
|
|
221
223
|
private eventHandlers;
|
|
@@ -415,6 +417,11 @@ export declare class Agent {
|
|
|
415
417
|
private checkpointPersistenceError;
|
|
416
418
|
/** Retry persistence only, before a new public invocation can admit effects. */
|
|
417
419
|
private recoverToolCheckpoint;
|
|
420
|
+
/**
|
|
421
|
+
* The person just sent a new message: the next request this agent builds is theirs, and gets one real attempt even
|
|
422
|
+
* while Zerg Router's refusal holds its route (they may have just raised the limit). Background turns never call it.
|
|
423
|
+
*/
|
|
424
|
+
admitPersonRequest(): void;
|
|
418
425
|
/** Execute a host-bound or standalone turn through the same core loop. */
|
|
419
426
|
run(messages: Message[], signal?: AbortSignal, takeSteering?: () => Message[], toolCheckpoint?: ToolCheckpointHandler | undefined, steeringAdmission?: SteeringAdmissionCheckpointHandler, onUsage?: ModelUsageObserver): Promise<AgentRunResult>;
|
|
420
427
|
private runBound;
|
package/dist/agent/agent.js
CHANGED
|
@@ -10,6 +10,7 @@ import { mergeTokenUsage } from './backends/token_usage.js';
|
|
|
10
10
|
import { createUsageSnapshot, mergeUsageSnapshots, parseUsageSnapshot, recordUsageReceipt } from '../usage_snapshot.js';
|
|
11
11
|
import { IncompleteStreamError, isIncompleteStreamError, isTransportCodeError, isTransportMessageError } from './backends/transport_errors.js';
|
|
12
12
|
import { BackendHttpError, redactErrorText, retryAfterDelayMs } from './backends/http_error.js';
|
|
13
|
+
import { formatRouterRefusal, readRouterRefusal, ROUTER_USAGE_REFUSED, RouterRefusalError } from './backends/router_refusal.js';
|
|
13
14
|
import { inferDefaultProvider, getDefaultApiKeyForProvider, getDefaultModelForProvider } from '../config/defaults.js';
|
|
14
15
|
import { apiRetryDelayMs, resolveApiRetrySettings } from '../config/api_retry.js';
|
|
15
16
|
import { resolveExecutionSettings } from '../config/execution.js';
|
|
@@ -69,8 +70,8 @@ function getTool(name, tools) {
|
|
|
69
70
|
}
|
|
70
71
|
export class AgentError extends Error {
|
|
71
72
|
code;
|
|
72
|
-
constructor(message, code) {
|
|
73
|
-
super(message);
|
|
73
|
+
constructor(message, code, options) {
|
|
74
|
+
super(message, options);
|
|
74
75
|
this.code = code;
|
|
75
76
|
this.name = 'AgentError';
|
|
76
77
|
}
|
|
@@ -100,9 +101,6 @@ export function isContextOverflowMessage(message) {
|
|
|
100
101
|
const haystack = message.toLowerCase();
|
|
101
102
|
return CONTEXT_OVERFLOW_SUBSTRINGS.some(s => haystack.includes(s));
|
|
102
103
|
}
|
|
103
|
-
// Router usage-control refusals (zergrouter usage-denials.ts) that last until
|
|
104
|
-
// their daily, weekly or monthly window resets.
|
|
105
|
-
const LASTING_ROUTER_USAGE_LIMITS = new Set(['router_usage_budget_exceeded', 'router_usage_token_limit_exceeded']);
|
|
106
104
|
const ROUTER_RATE_LIMIT_CODES = new Set(['rate_limit_exceeded', 'free_model_daily_limit']);
|
|
107
105
|
/**
|
|
108
106
|
* Continuous recovery rides out an outage, but a provider that keeps refusing for its rate limit is not recovering:
|
|
@@ -210,6 +208,8 @@ export class Agent {
|
|
|
210
208
|
/** One-shot: the next request carries the output-limit note at this effort. */
|
|
211
209
|
/** The next request retries a discarded response: a note for the model, and lower effort when offered. */
|
|
212
210
|
responseRetry = null;
|
|
211
|
+
/** One-shot: the next request starts a turn the person's own new message began (see admitPersonRequest). */
|
|
212
|
+
personRequestPending = false;
|
|
213
213
|
/** Fast mode — request the priority service tier from the Codex/GPT backend. */
|
|
214
214
|
_codexFastMode;
|
|
215
215
|
eventHandlers = new Set();
|
|
@@ -1337,9 +1337,10 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
|
|
|
1337
1337
|
}
|
|
1338
1338
|
}
|
|
1339
1339
|
catch (error) {
|
|
1340
|
+
// A refusal is an answer, not a broken stream: it is never retried as one.
|
|
1340
1341
|
if (streamStarted && error instanceof Error
|
|
1341
1342
|
&& !(error instanceof AgentError) && !(error instanceof RunawayOutputError)
|
|
1342
|
-
&& !(error instanceof NativeObservationLimitError)
|
|
1343
|
+
&& !(error instanceof NativeObservationLimitError) && !(error instanceof RequestRefusedError)
|
|
1343
1344
|
&& !isIncompleteStreamError(error) && !(error instanceof BackendHttpError)) {
|
|
1344
1345
|
throw new IncompleteStreamError(error.message);
|
|
1345
1346
|
}
|
|
@@ -1613,6 +1614,13 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
|
|
|
1613
1614
|
this.toolCheckpointTail = pending.catch(() => { });
|
|
1614
1615
|
await pending;
|
|
1615
1616
|
}
|
|
1617
|
+
/**
|
|
1618
|
+
* The person just sent a new message: the next request this agent builds is theirs, and gets one real attempt even
|
|
1619
|
+
* while Zerg Router's refusal holds its route (they may have just raised the limit). Background turns never call it.
|
|
1620
|
+
*/
|
|
1621
|
+
admitPersonRequest() {
|
|
1622
|
+
this.personRequestPending = true;
|
|
1623
|
+
}
|
|
1616
1624
|
/** Execute a host-bound or standalone turn through the same core loop. */
|
|
1617
1625
|
async run(messages, signal, takeSteering, toolCheckpoint = this.toolCheckpoint, steeringAdmission, onUsage) {
|
|
1618
1626
|
const diagnosticTurn = { id: `turn_${randomUUID()}`, iterations: 0 };
|
|
@@ -1825,6 +1833,10 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
|
|
|
1825
1833
|
}
|
|
1826
1834
|
const request = this.buildRequest(messages, availableTools);
|
|
1827
1835
|
request.signal = signal;
|
|
1836
|
+
if (this.personRequestPending) {
|
|
1837
|
+
this.personRequestPending = false;
|
|
1838
|
+
request.personInitiated = true;
|
|
1839
|
+
}
|
|
1828
1840
|
request.onMetrics = metrics => {
|
|
1829
1841
|
this.tracer.event({ type: 'request_metrics', timestamp: new Date(), data: { ...metrics, model: request.model } });
|
|
1830
1842
|
this.emit({ type: 'request_metrics', metrics });
|
|
@@ -3034,6 +3046,9 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
|
|
|
3034
3046
|
}
|
|
3035
3047
|
if (err instanceof RunawayOutputError)
|
|
3036
3048
|
throw err;
|
|
3049
|
+
// Router refused before any provider was called: nothing a retry can change, and the words are its own.
|
|
3050
|
+
if (err instanceof RouterRefusalError)
|
|
3051
|
+
throw new AgentError(err.message, ROUTER_USAGE_REFUSED, { cause: err });
|
|
3037
3052
|
const error = err;
|
|
3038
3053
|
if (effectObserved || !canRegenerate() || timedOut && !streamingAttempt) {
|
|
3039
3054
|
if (isIncompleteStreamError(error)) {
|
|
@@ -3042,7 +3057,8 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
|
|
|
3042
3057
|
if (timedOut) {
|
|
3043
3058
|
throw new AgentError('LLM request timed out. Try again, reduce tool output, or raise ZTC_LLM_REQUEST_TIMEOUT_MS if this model needs longer.', 'API_TIMEOUT');
|
|
3044
3059
|
}
|
|
3045
|
-
|
|
3060
|
+
const failure = this.parseAPIError(error);
|
|
3061
|
+
throw new AgentError(failure.reason, failure.kind === 'router_refusal' ? ROUTER_USAGE_REFUSED : 'API_ERROR');
|
|
3046
3062
|
}
|
|
3047
3063
|
if (useStream && answerOutputEmitted) {
|
|
3048
3064
|
this.emit({ type: 'stream_reset' });
|
|
@@ -3077,9 +3093,10 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
|
|
|
3077
3093
|
if (isIncompleteStreamError(error)) {
|
|
3078
3094
|
throw new AgentError(INCOMPLETE_MODEL_RESPONSE_MESSAGE, INCOMPLETE_MODEL_RESPONSE_CODE);
|
|
3079
3095
|
}
|
|
3080
|
-
throw new AgentError(reason, 'API_ERROR');
|
|
3096
|
+
throw new AgentError(reason, kind === 'router_refusal' ? ROUTER_USAGE_REFUSED : 'API_ERROR');
|
|
3081
3097
|
}
|
|
3082
|
-
|
|
3098
|
+
// Router ended the turn with this error (a router_error frame), so resuming its turn id would replay it.
|
|
3099
|
+
if ((isIncompleteStreamError(error) || (error instanceof BackendHttpError && error.turnEnded)) && request.transportTurnId !== undefined) {
|
|
3083
3100
|
request = { ...request, transportTurnId: randomUUID() };
|
|
3084
3101
|
}
|
|
3085
3102
|
rateLimitedAttempts = kind === 'rate_limit' ? rateLimitedAttempts + 1 : 0;
|
|
@@ -3129,6 +3146,8 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
|
|
|
3129
3146
|
if (isIncompleteStreamError(error)) {
|
|
3130
3147
|
return { retryable: true, reason: error.message, kind: 'stream_lost' };
|
|
3131
3148
|
}
|
|
3149
|
+
if (error instanceof RouterRefusalError)
|
|
3150
|
+
return { retryable: false, reason: error.message, kind: 'router_refusal' };
|
|
3132
3151
|
// ZTC refused the request before sending it, in words meant for the person.
|
|
3133
3152
|
if (error instanceof RequestRefusedError)
|
|
3134
3153
|
return { retryable: false, reason: error.message };
|
|
@@ -3224,12 +3243,14 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
|
|
|
3224
3243
|
if (statusCode === 529 || errorType === 'overloaded_error') {
|
|
3225
3244
|
return { retryable: true, reason: 'API is overloaded' };
|
|
3226
3245
|
}
|
|
3227
|
-
// Router
|
|
3228
|
-
//
|
|
3229
|
-
//
|
|
3230
|
-
|
|
3231
|
-
|
|
3232
|
-
|
|
3246
|
+
// Zerg Router refused before calling any provider, in either of its envelopes, directly or through the platform
|
|
3247
|
+
// proxy. A lasting refusal ends the turn with Router's words; a full concurrency limit, a provider cooldown or an
|
|
3248
|
+
// admission throttle is a bounded rate-limit retry that waits as long as the body says.
|
|
3249
|
+
const routerRefusal = error instanceof BackendHttpError && message.startsWith('ZRouter API error (')
|
|
3250
|
+
? readRouterRefusal(error.status, error.body) : null;
|
|
3251
|
+
if (routerRefusal) {
|
|
3252
|
+
const reason = formatRouterRefusal(routerRefusal);
|
|
3253
|
+
return routerRefusal.kind === 'lasting' ? { retryable: false, reason, kind: 'router_refusal' } : { retryable: true, reason, kind: 'rate_limit' };
|
|
3233
3254
|
}
|
|
3234
3255
|
// Router words every OpenRouter rate limit itself, so its message is public. A used-up daily
|
|
3235
3256
|
// free-model quota lasts until the day resets; retrying only spends what is left of it.
|
|
@@ -7,6 +7,11 @@ export declare class BackendHttpError extends Error {
|
|
|
7
7
|
readonly httpError: HttpErrorDiagnostic;
|
|
8
8
|
/** Transport control only; never copied into the public body diagnostic. */
|
|
9
9
|
readonly retryAtMs?: number;
|
|
10
|
+
/**
|
|
11
|
+
* Router ended the turn with this error (a router_error frame): resuming the same turn id replays it, so another
|
|
12
|
+
* attempt must start a new turn.
|
|
13
|
+
*/
|
|
14
|
+
readonly turnEnded: boolean;
|
|
10
15
|
constructor(status: number, body: string, options?: {
|
|
11
16
|
prefix?: string;
|
|
12
17
|
headers?: RequestInit['headers'];
|
|
@@ -14,6 +19,7 @@ export declare class BackendHttpError extends Error {
|
|
|
14
19
|
retryAfter?: string | null;
|
|
15
20
|
/** Router defines x-ratelimit-reset as relative seconds, not an epoch. */
|
|
16
21
|
rateLimitReset?: string | null;
|
|
22
|
+
turnEnded?: boolean;
|
|
17
23
|
});
|
|
18
24
|
}
|
|
19
25
|
/** Respect a server's minimum wait, then spread concurrent callers by up to one second. */
|
|
@@ -13,6 +13,11 @@ export class BackendHttpError extends Error {
|
|
|
13
13
|
httpError;
|
|
14
14
|
/** Transport control only; never copied into the public body diagnostic. */
|
|
15
15
|
retryAtMs;
|
|
16
|
+
/**
|
|
17
|
+
* Router ended the turn with this error (a router_error frame): resuming the same turn id replays it, so another
|
|
18
|
+
* attempt must start a new turn.
|
|
19
|
+
*/
|
|
20
|
+
turnEnded;
|
|
16
21
|
constructor(status, body, options = {}) {
|
|
17
22
|
const raw = boundedText(body, BODY_BYTES);
|
|
18
23
|
const state = options.bodyReadState ?? (raw.truncated ? 'truncated' : 'complete');
|
|
@@ -21,6 +26,7 @@ export class BackendHttpError extends Error {
|
|
|
21
26
|
this.name = 'BackendHttpError';
|
|
22
27
|
this.status = status;
|
|
23
28
|
this.body = safe.text;
|
|
29
|
+
this.turnEnded = options.turnEnded === true;
|
|
24
30
|
if (status === 429) {
|
|
25
31
|
const now = Date.now();
|
|
26
32
|
this.retryAtMs = parseRetryDeadline(options.retryAfter, now, true)
|
|
@@ -132,24 +138,31 @@ function boundedCanonicalBody(text) {
|
|
|
132
138
|
const source = value;
|
|
133
139
|
// Redaction can expand a complete body. Retain the small canonical fields
|
|
134
140
|
// used by admission and Kimi rate-limit parsing instead of cutting JSON.
|
|
135
|
-
const
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
141
|
+
const canonical = ['type', 'status', 'statusCode', 'code', 'message', 'detail', 'statusMessage', 'retry_after', 'resets_at', 'provider_dispatched', 'source', 'limit', 'resetSeconds'];
|
|
142
|
+
// A Router refusal's details, kept while they fit: they never displace the canonical fields' bound.
|
|
143
|
+
const refusal = ['period', 'scope', 'help_url', 'retryAfterSeconds', 'providerErrorType'];
|
|
144
|
+
const projection = (keys) => {
|
|
145
|
+
const project = (record) => Object.fromEntries(keys.flatMap(key => {
|
|
146
|
+
const item = record[key];
|
|
147
|
+
// 39 canonical strings × 64 bytes × worst-case JSON escaping stays below 16 KiB.
|
|
148
|
+
return typeof item === 'string' ? [[key, boundedText(item, 64).text]]
|
|
149
|
+
: typeof item === 'number' || typeof item === 'boolean' ? [[key, item]] : [];
|
|
150
|
+
}));
|
|
151
|
+
const result = project(source);
|
|
152
|
+
for (const key of ['error', 'data']) {
|
|
153
|
+
const item = source[key];
|
|
154
|
+
if (item && typeof item === 'object' && !Array.isArray(item))
|
|
155
|
+
result[key] = project(item);
|
|
156
|
+
else if (typeof item === 'string')
|
|
157
|
+
result[key] = boundedText(item, 64).text;
|
|
158
|
+
else if (typeof item === 'boolean')
|
|
159
|
+
result[key] = item;
|
|
160
|
+
}
|
|
161
|
+
return result;
|
|
162
|
+
};
|
|
163
|
+
const detailed = JSON.stringify(projection([...canonical, ...refusal]));
|
|
164
|
+
const result = Buffer.byteLength(detailed) <= BODY_BYTES ? detailed : JSON.stringify(projection(canonical));
|
|
165
|
+
return { text: result, truncated: true };
|
|
153
166
|
}
|
|
154
167
|
catch {
|
|
155
168
|
return bounded;
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import type { RouterRefusal } from './router_refusal.js';
|
|
2
|
+
import { RouterRefusalError } from './router_refusal.js';
|
|
3
|
+
/** At most one real attempt per held route and model in this long. */
|
|
4
|
+
export declare const ROUTER_REFUSAL_RETRY_MS: number;
|
|
5
|
+
/** What Router was asked: the gate's key. */
|
|
6
|
+
export interface RouterGateTarget {
|
|
7
|
+
/** The Router or platform proxy URL requests go to. */
|
|
8
|
+
route: string;
|
|
9
|
+
/** A one-way fingerprint of the account's credential (see routerAccount). */
|
|
10
|
+
account: string;
|
|
11
|
+
provider: string;
|
|
12
|
+
model: string;
|
|
13
|
+
}
|
|
14
|
+
/** A refusal the gate holds, as the record and the launch notice see it. */
|
|
15
|
+
export interface RouterHold extends RouterGateTarget {
|
|
16
|
+
refusal: RouterRefusal;
|
|
17
|
+
message: string;
|
|
18
|
+
/** When it lifts by itself (epoch ms); null until something changes. */
|
|
19
|
+
until: number | null;
|
|
20
|
+
/** No real attempt before `until`: a provider cooldown is never retried sooner than Router asked. */
|
|
21
|
+
waitOut: boolean;
|
|
22
|
+
lastAttemptAt: number;
|
|
23
|
+
refusedAt: number;
|
|
24
|
+
}
|
|
25
|
+
/** Where holds are kept beyond this process: an unattended run's record (router_refusal_record.ts). */
|
|
26
|
+
export interface RouterHoldStore {
|
|
27
|
+
/** May the five-minute attempt go out now? A store shared by processes answers for all of them and claims it. */
|
|
28
|
+
claimAttempt(hold: RouterHold, now: number): boolean;
|
|
29
|
+
held(hold: RouterHold): void;
|
|
30
|
+
released(hold: RouterHold): void;
|
|
31
|
+
}
|
|
32
|
+
/** A credential's fingerprint: enough to tell accounts apart, never usable as the credential. */
|
|
33
|
+
export declare function routerAccount(credential: string): string;
|
|
34
|
+
/** One route spelled one way: no trailing slash. */
|
|
35
|
+
export declare function routerRoute(url: string): string;
|
|
36
|
+
export declare class RouterRefusalGate {
|
|
37
|
+
private readonly holds;
|
|
38
|
+
private store;
|
|
39
|
+
/** Refusals requests in this process have met, from Router or held locally, and the last of them. */
|
|
40
|
+
private met;
|
|
41
|
+
private lastMet;
|
|
42
|
+
private meet;
|
|
43
|
+
/**
|
|
44
|
+
* Before a request goes to Router: undefined to send it (possibly as the one real attempt), or the error that
|
|
45
|
+
* refuses it locally. `person` is the person's own new message, which gets one real attempt unless a provider
|
|
46
|
+
* cooldown is still running.
|
|
47
|
+
*/
|
|
48
|
+
admit(target: RouterGateTarget, options?: {
|
|
49
|
+
person?: boolean;
|
|
50
|
+
}): RouterRefusalError | undefined;
|
|
51
|
+
/** Router refused a request: hold its route and model. */
|
|
52
|
+
refuse(target: RouterGateTarget, error: RouterRefusalError): void;
|
|
53
|
+
/** Router answered: whatever held this route and model is over. */
|
|
54
|
+
succeed(target: RouterGateTarget): void;
|
|
55
|
+
/**
|
|
56
|
+
* Would a request for this route and account (and provider and model, when given) be refused locally now? Asks
|
|
57
|
+
* without taking the five-minute attempt, so a run can skip Router work it already knows is refused.
|
|
58
|
+
*/
|
|
59
|
+
wouldRefuse(filter: {
|
|
60
|
+
route: string;
|
|
61
|
+
account: string;
|
|
62
|
+
provider?: string;
|
|
63
|
+
model?: string;
|
|
64
|
+
}): boolean;
|
|
65
|
+
/** Holds in force now, for this route and account when given. */
|
|
66
|
+
current(filter?: {
|
|
67
|
+
route?: string;
|
|
68
|
+
account?: string;
|
|
69
|
+
}): RouterHold[];
|
|
70
|
+
/** How many refusals requests in this process have met so far, from Router or held locally. */
|
|
71
|
+
refusalsMet(): number;
|
|
72
|
+
/**
|
|
73
|
+
* The last refusal a request met once `since` (a refusalsMet count) had been met, or null when none has since. Work
|
|
74
|
+
* that reports a failure in its own words, such as a workflow, asks this to tell whether Router refused it.
|
|
75
|
+
*/
|
|
76
|
+
refusalMetSince(since: number): RouterRefusalError | null;
|
|
77
|
+
/** Keep holds beyond this process too, and take the ones already recorded. */
|
|
78
|
+
attach(store: RouterHoldStore, holds: readonly RouterHold[]): void;
|
|
79
|
+
}
|
|
80
|
+
/** The process's one gate. */
|
|
81
|
+
export declare const routerRefusalGate: RouterRefusalGate;
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One Zerg Router refusal stops the whole process, not one turn.
|
|
3
|
+
*
|
|
4
|
+
* A refused turn did not stop the next one: every agent, worker and loop in the process went on sending the request
|
|
5
|
+
* Router had just refused. The gate holds a route, account, provider and model Router refused, and every later request
|
|
6
|
+
* for it in this process (subagents, workers, swarms, simulations, routines, heartbeats) fails locally with the same
|
|
7
|
+
* message, without contacting Router. It holds until the refusal's reset, or, when Router gives none, until something
|
|
8
|
+
* changes (another model, account or route is another key). At most one real attempt every five minutes goes
|
|
9
|
+
* through, so a raised limit takes effect within minutes, and a success for that route, account, provider and model
|
|
10
|
+
* clears its hold. The person's own new message always gets one real attempt, since they may have just raised the
|
|
11
|
+
* limit. A provider cooldown that ended a turn is the exception: nothing the person can change shortens it, so no
|
|
12
|
+
* request, theirs included, is tried before it clears.
|
|
13
|
+
*
|
|
14
|
+
* The hold is keyed by the route (the Router or platform proxy URL), the account (a one-way fingerprint of the
|
|
15
|
+
* credential, never the credential), the provider and the model. Keying every refusal by account, not only the credit
|
|
16
|
+
* and quota ones, means another account on the same route is never held by this one's refusal, and a new sign-in gets
|
|
17
|
+
* its own real attempt.
|
|
18
|
+
*/
|
|
19
|
+
import { createHash } from 'node:crypto';
|
|
20
|
+
import { RouterRefusalError } from './router_refusal.js';
|
|
21
|
+
/** At most one real attempt per held route and model in this long. */
|
|
22
|
+
export const ROUTER_REFUSAL_RETRY_MS = 5 * 60_000;
|
|
23
|
+
/** A credential's fingerprint: enough to tell accounts apart, never usable as the credential. */
|
|
24
|
+
export function routerAccount(credential) {
|
|
25
|
+
return createHash('sha256').update(`ztc-router-refusal\0${credential}`).digest('hex').slice(0, 16);
|
|
26
|
+
}
|
|
27
|
+
/** One route spelled one way: no trailing slash. */
|
|
28
|
+
export function routerRoute(url) {
|
|
29
|
+
return url.replace(/\/+$/, '');
|
|
30
|
+
}
|
|
31
|
+
function keyOf(target) {
|
|
32
|
+
return [routerRoute(target.route), target.account, target.provider, target.model].join('\n');
|
|
33
|
+
}
|
|
34
|
+
export class RouterRefusalGate {
|
|
35
|
+
holds = new Map();
|
|
36
|
+
store = null;
|
|
37
|
+
/** Refusals requests in this process have met, from Router or held locally, and the last of them. */
|
|
38
|
+
met = 0;
|
|
39
|
+
lastMet = null;
|
|
40
|
+
meet(error) {
|
|
41
|
+
this.met += 1;
|
|
42
|
+
this.lastMet = error;
|
|
43
|
+
return error;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Before a request goes to Router: undefined to send it (possibly as the one real attempt), or the error that
|
|
47
|
+
* refuses it locally. `person` is the person's own new message, which gets one real attempt unless a provider
|
|
48
|
+
* cooldown is still running.
|
|
49
|
+
*/
|
|
50
|
+
admit(target, options = {}) {
|
|
51
|
+
const key = keyOf(target);
|
|
52
|
+
const hold = this.holds.get(key);
|
|
53
|
+
if (!hold)
|
|
54
|
+
return undefined;
|
|
55
|
+
const now = Date.now();
|
|
56
|
+
if (hold.until !== null && now >= hold.until) {
|
|
57
|
+
this.holds.delete(key);
|
|
58
|
+
this.store?.released(hold);
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
|
61
|
+
// A cooldown's hold always has its end, which the check above found still ahead.
|
|
62
|
+
if (hold.waitOut)
|
|
63
|
+
return this.meet(new RouterRefusalError(hold.message, hold.refusal, true));
|
|
64
|
+
if (options.person) {
|
|
65
|
+
hold.lastAttemptAt = now;
|
|
66
|
+
return undefined;
|
|
67
|
+
}
|
|
68
|
+
if (now - hold.lastAttemptAt >= ROUTER_REFUSAL_RETRY_MS && (this.store?.claimAttempt(hold, now) ?? true)) {
|
|
69
|
+
// Claimed before it is sent, so requests made while it is out stay local.
|
|
70
|
+
hold.lastAttemptAt = now;
|
|
71
|
+
return undefined;
|
|
72
|
+
}
|
|
73
|
+
return this.meet(new RouterRefusalError(hold.message, hold.refusal, true));
|
|
74
|
+
}
|
|
75
|
+
/** Router refused a request: hold its route and model. */
|
|
76
|
+
refuse(target, error) {
|
|
77
|
+
if (error.local)
|
|
78
|
+
return;
|
|
79
|
+
this.meet(error);
|
|
80
|
+
const now = Date.now();
|
|
81
|
+
const resets = typeof error.refusal.resetsAt === 'string' ? Date.parse(error.refusal.resetsAt) : NaN;
|
|
82
|
+
const until = error.retryAt ?? (Number.isFinite(resets) && resets > now ? resets : null);
|
|
83
|
+
const hold = { ...target, route: routerRoute(target.route), refusal: error.refusal, message: error.message, until,
|
|
84
|
+
waitOut: error.retryAt !== undefined, lastAttemptAt: now, refusedAt: now };
|
|
85
|
+
this.holds.set(keyOf(target), hold);
|
|
86
|
+
this.store?.held(hold);
|
|
87
|
+
}
|
|
88
|
+
/** Router answered: whatever held this route and model is over. */
|
|
89
|
+
succeed(target) {
|
|
90
|
+
const key = keyOf(target);
|
|
91
|
+
const hold = this.holds.get(key);
|
|
92
|
+
if (!hold)
|
|
93
|
+
return;
|
|
94
|
+
this.holds.delete(key);
|
|
95
|
+
this.store?.released(hold);
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Would a request for this route and account (and provider and model, when given) be refused locally now? Asks
|
|
99
|
+
* without taking the five-minute attempt, so a run can skip Router work it already knows is refused.
|
|
100
|
+
*/
|
|
101
|
+
wouldRefuse(filter) {
|
|
102
|
+
const now = Date.now();
|
|
103
|
+
return this.current(filter).some(hold => (filter.provider === undefined || hold.provider === filter.provider)
|
|
104
|
+
&& (filter.model === undefined || hold.model === filter.model)
|
|
105
|
+
&& (hold.waitOut || now - hold.lastAttemptAt < ROUTER_REFUSAL_RETRY_MS));
|
|
106
|
+
}
|
|
107
|
+
/** Holds in force now, for this route and account when given. */
|
|
108
|
+
current(filter = {}) {
|
|
109
|
+
const now = Date.now();
|
|
110
|
+
return [...this.holds.values()].filter(hold => (hold.until === null || now < hold.until)
|
|
111
|
+
&& (filter.route === undefined || hold.route === routerRoute(filter.route))
|
|
112
|
+
&& (filter.account === undefined || hold.account === filter.account));
|
|
113
|
+
}
|
|
114
|
+
/** How many refusals requests in this process have met so far, from Router or held locally. */
|
|
115
|
+
refusalsMet() {
|
|
116
|
+
return this.met;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* The last refusal a request met once `since` (a refusalsMet count) had been met, or null when none has since. Work
|
|
120
|
+
* that reports a failure in its own words, such as a workflow, asks this to tell whether Router refused it.
|
|
121
|
+
*/
|
|
122
|
+
refusalMetSince(since) {
|
|
123
|
+
return this.met > since ? this.lastMet : null;
|
|
124
|
+
}
|
|
125
|
+
/** Keep holds beyond this process too, and take the ones already recorded. */
|
|
126
|
+
attach(store, holds) {
|
|
127
|
+
this.store = store;
|
|
128
|
+
for (const hold of holds)
|
|
129
|
+
this.holds.set(keyOf(hold), { ...hold });
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/** The process's one gate. */
|
|
133
|
+
export const routerRefusalGate = new RouterRefusalGate();
|