@zergai/ztc 0.11.0-beta.1 → 0.12.0-beta.1
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 +43 -5
- 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/codex_auth.js +4 -4
- 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 +6393 -40056
- package/package.json +16 -3
package/dist/headless.d.ts
CHANGED
|
@@ -48,6 +48,12 @@ export interface HeadlessSinks {
|
|
|
48
48
|
export declare const HEADLESS_EXIT_OUTPUT_SCHEMA = 3;
|
|
49
49
|
/** Exit status for an unusable --output-schema or --trajectory-jsonl, before any inference. */
|
|
50
50
|
export declare const HEADLESS_EXIT_USAGE = 2;
|
|
51
|
+
/**
|
|
52
|
+
* Exit status when Zerg Router refused a turn before calling any provider (a spending, token or access limit, the
|
|
53
|
+
* quota, a platform key out of credit, a long provider cooldown), or ZTC held a refusal Router had given. Its words
|
|
54
|
+
* are on stderr. 2 is taken by usage errors and the retired-route refusal, 3 by --output-schema.
|
|
55
|
+
*/
|
|
56
|
+
export declare const HEADLESS_EXIT_ROUTER_REFUSED = 4;
|
|
51
57
|
export type PaneChildLineClassification = {
|
|
52
58
|
kind: 'prompt';
|
|
53
59
|
text: string;
|
|
@@ -155,6 +161,12 @@ export declare class HeadlessApp {
|
|
|
155
161
|
private batchEventUnsub;
|
|
156
162
|
private batchFailed;
|
|
157
163
|
private hadHeadlessError;
|
|
164
|
+
/** Zerg Router's words for the last refusal that ended a turn; the run exits HEADLESS_EXIT_ROUTER_REFUSED. */
|
|
165
|
+
private routerRefusal;
|
|
166
|
+
/** The turn now running ended on a Router refusal: the goal and Voyager loops stop on it. */
|
|
167
|
+
private routerRefusedTurn;
|
|
168
|
+
/** Burst notices still being written; the run waits for them before it exits. */
|
|
169
|
+
private routerNotices;
|
|
158
170
|
private fatalTurnReached;
|
|
159
171
|
private readonly outputSchema;
|
|
160
172
|
private trajectory;
|
|
@@ -337,6 +349,22 @@ export declare class HeadlessApp {
|
|
|
337
349
|
private waitForActiveWorkflows;
|
|
338
350
|
private operationTimeoutMs;
|
|
339
351
|
private markHeadlessError;
|
|
352
|
+
/**
|
|
353
|
+
* A turn that ended on Zerg Router's refusal: the run exits HEADLESS_EXIT_ROUTER_REFUSED with Router's words on
|
|
354
|
+
* stderr, and loops stop. `shown` is the error event's message: in --json mode that event is on stdout, and a
|
|
355
|
+
* failure in other words (a workflow's) may not carry Router's, so they are written to stderr then, once for each
|
|
356
|
+
* new refusal. Returns the error event's extra fields.
|
|
357
|
+
*/
|
|
358
|
+
private noteRouterRefusal;
|
|
359
|
+
/**
|
|
360
|
+
* Zerg Router reporting for an unattended run: one budget line on stderr at start when a limit is set or the
|
|
361
|
+
* quota is over 80% (read from Router itself with the person's own credential, never through the platform proxy;
|
|
362
|
+
* left out when Router will not give it, or when Router's recorded refusal already holds this route), and a line
|
|
363
|
+
* when more than 60 Router requests go out in a minute, at most once every ten minutes.
|
|
364
|
+
*/
|
|
365
|
+
startRouterReporting(): Promise<void>;
|
|
366
|
+
/** End the run: finish any Router notice, say how many Router requests it made, and exit with its status. */
|
|
367
|
+
private exitRun;
|
|
340
368
|
private getExitCode;
|
|
341
369
|
private recordTrajectory;
|
|
342
370
|
/**
|
package/dist/headless.js
CHANGED
|
@@ -28,6 +28,11 @@ import { existsSync, truncateSync } from 'node:fs';
|
|
|
28
28
|
import { configStore } from './config.js';
|
|
29
29
|
import { formatTaskHandoffContext, projectTaskHandoff } from './session_handoff_contract.js';
|
|
30
30
|
import { RouterConfigurationError } from './router_auth.js';
|
|
31
|
+
import { routerRefusalOf } from './agent/backends/router_refusal.js';
|
|
32
|
+
import { adoptRouterRefusalRecord } from './agent/backends/router_refusal_record.js';
|
|
33
|
+
import { routerAccount, routerRefusalGate } from './agent/backends/router_gate.js';
|
|
34
|
+
import { onRouterRequestBurst, routerRequestsThisRun } from './agent/backends/router_requests.js';
|
|
35
|
+
import { personalRouterRoute, readRouterBudget, routerBudgetLine } from './router_budget.js';
|
|
31
36
|
import { registerInstance, deregisterInstance } from './instance_registry.js';
|
|
32
37
|
import { ContextOverflowError, isContextOverflowMessage } from './agent/agent.js';
|
|
33
38
|
import { dumpContextOverflow } from './agent/contextDump.js';
|
|
@@ -80,6 +85,12 @@ import { workflowsEnabled, workflowNaturalLanguageTriggerEnabled } from './workf
|
|
|
80
85
|
export const HEADLESS_EXIT_OUTPUT_SCHEMA = 3;
|
|
81
86
|
/** Exit status for an unusable --output-schema or --trajectory-jsonl, before any inference. */
|
|
82
87
|
export const HEADLESS_EXIT_USAGE = 2;
|
|
88
|
+
/**
|
|
89
|
+
* Exit status when Zerg Router refused a turn before calling any provider (a spending, token or access limit, the
|
|
90
|
+
* quota, a platform key out of credit, a long provider cooldown), or ZTC held a refusal Router had given. Its words
|
|
91
|
+
* are on stderr. 2 is taken by usage errors and the retired-route refusal, 3 by --output-schema.
|
|
92
|
+
*/
|
|
93
|
+
export const HEADLESS_EXIT_ROUTER_REFUSED = 4;
|
|
83
94
|
export function classifyPaneChildLine(line) {
|
|
84
95
|
const trimmed = line.trim();
|
|
85
96
|
// A control command is ONLY a BARE {"__ztc_cmd":...} line — the parent's
|
|
@@ -380,6 +391,12 @@ export class HeadlessApp {
|
|
|
380
391
|
batchEventUnsub = null;
|
|
381
392
|
batchFailed = false;
|
|
382
393
|
hadHeadlessError = false;
|
|
394
|
+
/** Zerg Router's words for the last refusal that ended a turn; the run exits HEADLESS_EXIT_ROUTER_REFUSED. */
|
|
395
|
+
routerRefusal = null;
|
|
396
|
+
/** The turn now running ended on a Router refusal: the goal and Voyager loops stop on it. */
|
|
397
|
+
routerRefusedTurn = false;
|
|
398
|
+
/** Burst notices still being written; the run waits for them before it exits. */
|
|
399
|
+
routerNotices = Promise.resolve();
|
|
383
400
|
fatalTurnReached = false;
|
|
384
401
|
outputSchema;
|
|
385
402
|
trajectory;
|
|
@@ -1477,9 +1494,12 @@ export class HeadlessApp {
|
|
|
1477
1494
|
if (!this.options.deferJsonStdinStartup) {
|
|
1478
1495
|
this.outputHeadlessShellMode();
|
|
1479
1496
|
}
|
|
1480
|
-
// Discover current Router controls before the first backend snapshots them
|
|
1497
|
+
// Discover current Router controls before the first backend snapshots them, unless a refusal Router gave is
|
|
1498
|
+
// holding this route and account: the run is refused locally anyway, and a relaunch must not contact Router.
|
|
1481
1499
|
try {
|
|
1482
|
-
|
|
1500
|
+
const route = configStore.resolveLLMBackendConfig();
|
|
1501
|
+
if (route.useProxy && !(route.proxyUrl && route.authToken
|
|
1502
|
+
&& routerRefusalGate.wouldRefuse({ route: route.proxyUrl, account: routerAccount(route.authToken) }))) {
|
|
1483
1503
|
void buildModelsController(configStore).catalog(this.startupCatalogController.signal, { refresh: 'startup' }).catch(() => { });
|
|
1484
1504
|
}
|
|
1485
1505
|
}
|
|
@@ -2212,6 +2232,7 @@ export class HeadlessApp {
|
|
|
2212
2232
|
* Run a single prompt through the agent
|
|
2213
2233
|
*/
|
|
2214
2234
|
async runPrompt(prompt, opts = {}) {
|
|
2235
|
+
this.routerRefusedTurn = false;
|
|
2215
2236
|
if (process.env.ZTC_DISABLE_SLASH_COMMANDS !== '1' && routeUserInput(prompt).type === 'command') {
|
|
2216
2237
|
await this.runPromptAdmitted(prompt, opts);
|
|
2217
2238
|
return;
|
|
@@ -2497,7 +2518,7 @@ export class HeadlessApp {
|
|
|
2497
2518
|
this.output({
|
|
2498
2519
|
type: 'error',
|
|
2499
2520
|
timestamp: new Date().toISOString(),
|
|
2500
|
-
data: { message }
|
|
2521
|
+
data: { message, ...this.noteRouterRefusal(err, message) }
|
|
2501
2522
|
});
|
|
2502
2523
|
// Persist the user message even when the turn failed, so embedders
|
|
2503
2524
|
// that read the session file back see the conversation tail.
|
|
@@ -2538,6 +2559,8 @@ export class HeadlessApp {
|
|
|
2538
2559
|
timestamp: new Date().toISOString(),
|
|
2539
2560
|
data: { role: 'user', content: prompt },
|
|
2540
2561
|
});
|
|
2562
|
+
// The workflow reports a failure in its own words; the gate tells whether Router refused its requests meanwhile.
|
|
2563
|
+
const refusalsBefore = routerRefusalGate.refusalsMet();
|
|
2541
2564
|
try {
|
|
2542
2565
|
const cwd = this.shellCwd || process.cwd();
|
|
2543
2566
|
const { runTriggeredWorkflowTool } = await import('./headless_workflow_trigger.js');
|
|
@@ -2556,7 +2579,8 @@ export class HeadlessApp {
|
|
|
2556
2579
|
this.output({
|
|
2557
2580
|
type: 'error',
|
|
2558
2581
|
timestamp: new Date().toISOString(),
|
|
2559
|
-
data: { message: toolResult.content
|
|
2582
|
+
data: { message: toolResult.content,
|
|
2583
|
+
...this.noteRouterRefusal(routerRefusalGate.refusalMetSince(refusalsBefore), toolResult.content) },
|
|
2560
2584
|
});
|
|
2561
2585
|
await this.saveCurrentSession();
|
|
2562
2586
|
return;
|
|
@@ -2585,7 +2609,7 @@ export class HeadlessApp {
|
|
|
2585
2609
|
this.output({
|
|
2586
2610
|
type: 'error',
|
|
2587
2611
|
timestamp: new Date().toISOString(),
|
|
2588
|
-
data: { message },
|
|
2612
|
+
data: { message, ...this.noteRouterRefusal(routerRefusalOf(error) ?? routerRefusalGate.refusalMetSince(refusalsBefore), message) },
|
|
2589
2613
|
});
|
|
2590
2614
|
await this.saveCurrentSession();
|
|
2591
2615
|
}
|
|
@@ -2765,10 +2789,11 @@ export class HeadlessApp {
|
|
|
2765
2789
|
await this.saveCurrentSession();
|
|
2766
2790
|
}
|
|
2767
2791
|
else {
|
|
2792
|
+
const message = err instanceof Error ? err.message : 'Unknown error';
|
|
2768
2793
|
this.output({
|
|
2769
2794
|
type: 'error',
|
|
2770
2795
|
timestamp: new Date().toISOString(),
|
|
2771
|
-
data: { message
|
|
2796
|
+
data: { message, ...this.noteRouterRefusal(err, message) }
|
|
2772
2797
|
});
|
|
2773
2798
|
}
|
|
2774
2799
|
}
|
|
@@ -2894,7 +2919,62 @@ export class HeadlessApp {
|
|
|
2894
2919
|
data: { message },
|
|
2895
2920
|
});
|
|
2896
2921
|
}
|
|
2922
|
+
/**
|
|
2923
|
+
* A turn that ended on Zerg Router's refusal: the run exits HEADLESS_EXIT_ROUTER_REFUSED with Router's words on
|
|
2924
|
+
* stderr, and loops stop. `shown` is the error event's message: in --json mode that event is on stdout, and a
|
|
2925
|
+
* failure in other words (a workflow's) may not carry Router's, so they are written to stderr then, once for each
|
|
2926
|
+
* new refusal. Returns the error event's extra fields.
|
|
2927
|
+
*/
|
|
2928
|
+
noteRouterRefusal(error, shown) {
|
|
2929
|
+
const refusal = routerRefusalOf(error);
|
|
2930
|
+
if (!refusal)
|
|
2931
|
+
return {};
|
|
2932
|
+
this.routerRefusedTurn = true;
|
|
2933
|
+
if ((this.options.json || !shown.includes(refusal.message)) && this.routerRefusal !== refusal.message) {
|
|
2934
|
+
process.stderr.write(`${refusal.message}\n`);
|
|
2935
|
+
}
|
|
2936
|
+
this.routerRefusal = refusal.message;
|
|
2937
|
+
return { error: 'router_usage_refused', code: refusal.refusal.code };
|
|
2938
|
+
}
|
|
2939
|
+
/**
|
|
2940
|
+
* Zerg Router reporting for an unattended run: one budget line on stderr at start when a limit is set or the
|
|
2941
|
+
* quota is over 80% (read from Router itself with the person's own credential, never through the platform proxy;
|
|
2942
|
+
* left out when Router will not give it, or when Router's recorded refusal already holds this route), and a line
|
|
2943
|
+
* when more than 60 Router requests go out in a minute, at most once every ten minutes.
|
|
2944
|
+
*/
|
|
2945
|
+
async startRouterReporting() {
|
|
2946
|
+
onRouterRequestBurst(count => {
|
|
2947
|
+
this.routerNotices = this.routerNotices.then(async () => {
|
|
2948
|
+
const credential = personalRouterRoute();
|
|
2949
|
+
const budget = credential ? await readRouterBudget(credential) : null;
|
|
2950
|
+
const line = budget ? routerBudgetLine(budget) : null;
|
|
2951
|
+
process.stderr.write(`ZTC sent ${count} Zerg Router requests in the last minute.${line ? ` Zerg Router budget: ${line}.` : ''}\n`);
|
|
2952
|
+
}).catch(() => { });
|
|
2953
|
+
});
|
|
2954
|
+
const credential = personalRouterRoute();
|
|
2955
|
+
if (!credential || routerRefusalGate.wouldRefuse({ route: credential.origin, account: routerAccount(credential.token) }))
|
|
2956
|
+
return;
|
|
2957
|
+
const budget = await readRouterBudget(credential);
|
|
2958
|
+
const line = budget ? routerBudgetLine(budget) : null;
|
|
2959
|
+
if (line)
|
|
2960
|
+
process.stderr.write(`Zerg Router budget: ${line}\n`);
|
|
2961
|
+
}
|
|
2962
|
+
/** End the run: finish any Router notice, say how many Router requests it made, and exit with its status. */
|
|
2963
|
+
async exitRun() {
|
|
2964
|
+
await Promise.race([this.routerNotices, new Promise(resolve => setTimeout(resolve, 3000).unref())]);
|
|
2965
|
+
let routed = false;
|
|
2966
|
+
try {
|
|
2967
|
+
routed = configStore.resolveLLMBackendConfig().useProxy;
|
|
2968
|
+
}
|
|
2969
|
+
catch { /* An unbuildable route is not routed. */ }
|
|
2970
|
+
const requests = routerRequestsThisRun();
|
|
2971
|
+
if (routed || requests > 0)
|
|
2972
|
+
process.stderr.write(`Zerg Router requests this run: ${requests}\n`);
|
|
2973
|
+
process.exit(this.getExitCode());
|
|
2974
|
+
}
|
|
2897
2975
|
getExitCode() {
|
|
2976
|
+
if (this.routerRefusal !== null)
|
|
2977
|
+
return HEADLESS_EXIT_ROUTER_REFUSED;
|
|
2898
2978
|
if (this.batchFailed || this.hadHeadlessError)
|
|
2899
2979
|
return 1;
|
|
2900
2980
|
return this.outputSchemaFailures > 0 ? HEADLESS_EXIT_OUTPUT_SCHEMA : 0;
|
|
@@ -3087,7 +3167,7 @@ export class HeadlessApp {
|
|
|
3087
3167
|
this.outputInvalidJson(error);
|
|
3088
3168
|
}
|
|
3089
3169
|
await this.shutdownBackgroundAgents();
|
|
3090
|
-
|
|
3170
|
+
await this.exitRun();
|
|
3091
3171
|
return;
|
|
3092
3172
|
}
|
|
3093
3173
|
this.outputHeadlessShellMode();
|
|
@@ -3280,7 +3360,7 @@ export class HeadlessApp {
|
|
|
3280
3360
|
});
|
|
3281
3361
|
// Shut down background agents then exit
|
|
3282
3362
|
await this.shutdownBackgroundAgents();
|
|
3283
|
-
|
|
3363
|
+
await this.exitRun();
|
|
3284
3364
|
}
|
|
3285
3365
|
/**
|
|
3286
3366
|
* Run a single prompt and exit
|
|
@@ -3353,7 +3433,7 @@ export class HeadlessApp {
|
|
|
3353
3433
|
});
|
|
3354
3434
|
// Shut down background agents then exit
|
|
3355
3435
|
await this.shutdownBackgroundAgents();
|
|
3356
|
-
|
|
3436
|
+
await this.exitRun();
|
|
3357
3437
|
}
|
|
3358
3438
|
/**
|
|
3359
3439
|
* Apply a resumed session's identity + messages and restore its persisted
|
|
@@ -3494,6 +3574,13 @@ export class HeadlessApp {
|
|
|
3494
3574
|
// This turn is launched by the goal loop, so it counts as `automatic` for the
|
|
3495
3575
|
// no-progress streak. Every other runPrompt caller (user input) leaves it false.
|
|
3496
3576
|
await this.runPrompt(nextPrompt, { automaticGoalTurn: true });
|
|
3577
|
+
// Zerg Router refused the turn: every further turn would meet the same refusal, so the goal waits for it.
|
|
3578
|
+
if (this.routerRefusedTurn) {
|
|
3579
|
+
const blocked = goalManager.block(`Zerg Router refused the request: ${this.routerRefusal ?? 'see the error above'}`, { turnTokens: this.lastTurnTokens });
|
|
3580
|
+
if (blocked)
|
|
3581
|
+
this.emitGoalNote(goalFinalNote(blocked));
|
|
3582
|
+
break;
|
|
3583
|
+
}
|
|
3497
3584
|
// Parity with the TUI, which pauses an active goal when the user interrupts:
|
|
3498
3585
|
// a cancel stops the autonomous loop instead of silently driving the next
|
|
3499
3586
|
// turn. The cancelled turn is deliberately NOT accounted — runPrompt already
|
|
@@ -3590,8 +3677,8 @@ export class HeadlessApp {
|
|
|
3590
3677
|
// Round 1: initial prompt
|
|
3591
3678
|
await this.runPrompt(prompt);
|
|
3592
3679
|
let round = 1;
|
|
3593
|
-
// Continuation rounds
|
|
3594
|
-
while (!this.taskCompleted && round < maxRounds) {
|
|
3680
|
+
// Continuation rounds; a Zerg Router refusal ends them, since every round would meet it again.
|
|
3681
|
+
while (!this.taskCompleted && round < maxRounds && !this.routerRefusedTurn) {
|
|
3595
3682
|
const elapsed = Date.now() - startTime;
|
|
3596
3683
|
if (elapsed >= totalTimeout) {
|
|
3597
3684
|
this.output({
|
|
@@ -3629,7 +3716,7 @@ export class HeadlessApp {
|
|
|
3629
3716
|
}
|
|
3630
3717
|
});
|
|
3631
3718
|
await this.shutdownBackgroundAgents();
|
|
3632
|
-
|
|
3719
|
+
await this.exitRun();
|
|
3633
3720
|
}
|
|
3634
3721
|
}
|
|
3635
3722
|
/**
|
|
@@ -3705,6 +3792,8 @@ export async function runHeadless(options, initialPrompt) {
|
|
|
3705
3792
|
process.exitCode = HEADLESS_EXIT_USAGE;
|
|
3706
3793
|
return;
|
|
3707
3794
|
}
|
|
3795
|
+
// A refusal an earlier unattended run recorded holds this one too, so a relaunch loop cannot hammer Zerg Router.
|
|
3796
|
+
adoptRouterRefusalRecord('unattended');
|
|
3708
3797
|
const deferJsonStdinStartup = !!options.json
|
|
3709
3798
|
&& !options.jsonStream
|
|
3710
3799
|
&& !initialPrompt
|
|
@@ -3769,6 +3858,7 @@ export async function runHeadless(options, initialPrompt) {
|
|
|
3769
3858
|
if (!initialized) {
|
|
3770
3859
|
process.exit(1);
|
|
3771
3860
|
}
|
|
3861
|
+
await app.startRouterReporting();
|
|
3772
3862
|
if (initialPrompt) {
|
|
3773
3863
|
if (options.voyagerLoop) {
|
|
3774
3864
|
await app.runVoyagerLoop(initialPrompt);
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
export interface RouterCredential {
|
|
2
|
+
origin: string;
|
|
3
|
+
token: string;
|
|
4
|
+
}
|
|
5
|
+
export type BudgetPeriod = 'day' | 'week' | 'month';
|
|
6
|
+
/** One limit and its usage in its period. */
|
|
7
|
+
export interface RouterBudgetLimit {
|
|
8
|
+
/** What it limits: "All models", a model, or a provider's models. */
|
|
9
|
+
label: string;
|
|
10
|
+
period: BudgetPeriod;
|
|
11
|
+
unit: 'usd' | 'tokens';
|
|
12
|
+
used: number;
|
|
13
|
+
limit: number;
|
|
14
|
+
}
|
|
15
|
+
export interface RouterBudget {
|
|
16
|
+
limits: RouterBudgetLimit[];
|
|
17
|
+
/** The monthly token quota; null when unlimited or not reported. */
|
|
18
|
+
quota: {
|
|
19
|
+
limit: number;
|
|
20
|
+
consumed: number;
|
|
21
|
+
} | null;
|
|
22
|
+
/** Refusals over the last 7 UTC days, by Router's code. */
|
|
23
|
+
refusals: Array<{
|
|
24
|
+
code: string;
|
|
25
|
+
count: number;
|
|
26
|
+
}>;
|
|
27
|
+
helpUrl?: string;
|
|
28
|
+
}
|
|
29
|
+
/** A refusal Router counts as in force for the person now. */
|
|
30
|
+
export interface RouterStanding {
|
|
31
|
+
blocked: Array<{
|
|
32
|
+
code: string;
|
|
33
|
+
period: BudgetPeriod | null;
|
|
34
|
+
resetsAt: string | null;
|
|
35
|
+
}>;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* The person's own Router credential when this session's model goes through it; undefined on any other route,
|
|
39
|
+
* including the legacy platform proxy, where ZTC holds no Router credential of the person's own.
|
|
40
|
+
*/
|
|
41
|
+
export declare function personalRouterRoute(): RouterCredential | undefined;
|
|
42
|
+
/** The budget in a UserUsageLimitsResponse, or null when the body is not one. */
|
|
43
|
+
export declare function routerBudgetOf(body: unknown): RouterBudget | null;
|
|
44
|
+
/** The person's budget from Router itself, or null when Router does not give it (any failure, quietly). */
|
|
45
|
+
export declare function readRouterBudget(credential: RouterCredential, timeoutMs?: number): Promise<RouterBudget | null>;
|
|
46
|
+
/** A device's standing: the refusals Router counts as in force for its person now; null when unavailable. */
|
|
47
|
+
export declare function readRouterStanding(credential: RouterCredential, timeoutMs?: number): Promise<RouterStanding | null>;
|
|
48
|
+
/** The short form of the binding limit, for the status bar: "$812 / $1,000 week". Null when no limit is set. */
|
|
49
|
+
export declare function routerBudgetShort(budget: RouterBudget): string | null;
|
|
50
|
+
/** One line when a limit is set or the quota is over 80%: "$812 / $1,000 week; quota 4.2M / 5M tokens (84%)". */
|
|
51
|
+
export declare function routerBudgetLine(budget: RouterBudget): string | null;
|
|
52
|
+
/** What /usage shows of the budget: each limit and its usage, the quota, and recent and current refusals. */
|
|
53
|
+
export declare function formatRouterBudget(budget: RouterBudget, standing?: RouterStanding | null): string;
|
|
54
|
+
/** The status bar's budget: the binding limit, or that Router is refusing now. Undefined when there is nothing to show. */
|
|
55
|
+
export declare function routerStatusBudget(budget: RouterBudget | null, standing: RouterStanding | null): string | undefined;
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The person's own Zerg Router budget: their limits, usage, monthly token quota and recent refusals.
|
|
3
|
+
*
|
|
4
|
+
* Read from Router itself (GET /api/usage/limits, UserUsageLimitsResponse in zergrouter shared/usage-controls.ts)
|
|
5
|
+
* with the person's own Router credential: their sign-in, a CLI device key. Never through the ZergAI platform
|
|
6
|
+
* proxy, which forwards the platform's own Router token for machine-access callers and would read another account;
|
|
7
|
+
* on the legacy platform route ZTC holds no Router credential of the person's own and shows no budget. A device also
|
|
8
|
+
* reads its person's standing (GET /api/cli/usage/standing: the refusals in force now), at most once a minute.
|
|
9
|
+
* Router answers 401 or 403 for credentials it will not tell (application keys, shared accounts, revoked devices),
|
|
10
|
+
* and any failure means the budget is unavailable: it is left out quietly, never a reason to refuse inference.
|
|
11
|
+
* There is no client-side cap; Router enforces budgets.
|
|
12
|
+
*/
|
|
13
|
+
import { configStore } from './config.js';
|
|
14
|
+
import { routerRoute } from './agent/backends/router_gate.js';
|
|
15
|
+
import { localRouterTime, ROUTER_USAGE_DENIALS, routerHelpUrl } from './agent/backends/router_refusal.js';
|
|
16
|
+
const BUDGET_TIMEOUT_MS = 3000;
|
|
17
|
+
/**
|
|
18
|
+
* The person's own Router credential when this session's model goes through it; undefined on any other route,
|
|
19
|
+
* including the legacy platform proxy, where ZTC holds no Router credential of the person's own.
|
|
20
|
+
*/
|
|
21
|
+
export function personalRouterRoute() {
|
|
22
|
+
const credential = configStore.getPersonalRouterCredential();
|
|
23
|
+
if (!credential)
|
|
24
|
+
return undefined;
|
|
25
|
+
try {
|
|
26
|
+
const route = configStore.resolveLLMBackendConfig();
|
|
27
|
+
return route.useProxy && route.authToken === credential.token && routerRoute(route.proxyUrl ?? '') === routerRoute(credential.origin)
|
|
28
|
+
? credential : undefined;
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return undefined;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
const PERIOD_FIELDS = [
|
|
35
|
+
['dailyUsdLimit', 'day', 'usd', 'dailyUsd'], ['weeklyUsdLimit', 'week', 'usd', 'weeklyUsd'], ['monthlyUsdLimit', 'month', 'usd', 'monthlyUsd'],
|
|
36
|
+
['dailyTokenLimit', 'day', 'tokens', 'dailyTokens'], ['monthlyTokenLimit', 'month', 'tokens', 'monthlyTokens'],
|
|
37
|
+
];
|
|
38
|
+
function record(value) {
|
|
39
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : null;
|
|
40
|
+
}
|
|
41
|
+
/** A Router amount: an exact decimal or whole-count string, or a number. NaN for anything else. */
|
|
42
|
+
function amount(value) {
|
|
43
|
+
if (typeof value === 'number')
|
|
44
|
+
return Number.isFinite(value) && value >= 0 ? value : NaN;
|
|
45
|
+
return typeof value === 'string' && /^\d{1,20}(\.\d{1,12})?$/.test(value) ? Number(value) : NaN;
|
|
46
|
+
}
|
|
47
|
+
async function getJson(credential, path, timeoutMs) {
|
|
48
|
+
try {
|
|
49
|
+
const response = await fetch(`${credential.origin.replace(/\/+$/, '')}${path}`, {
|
|
50
|
+
headers: { Authorization: `Bearer ${credential.token}`, Accept: 'application/json' },
|
|
51
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
52
|
+
});
|
|
53
|
+
if (response.status !== 200) {
|
|
54
|
+
await response.body?.cancel().catch(() => undefined);
|
|
55
|
+
return undefined;
|
|
56
|
+
}
|
|
57
|
+
return await response.json();
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
return undefined;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function scopeLabel(provider, model) {
|
|
64
|
+
if (provider === '*' && model === '*')
|
|
65
|
+
return 'All models';
|
|
66
|
+
if (provider === '*')
|
|
67
|
+
return model;
|
|
68
|
+
if (model === '*')
|
|
69
|
+
return `All ${provider} models`;
|
|
70
|
+
return `${provider}/${model}`;
|
|
71
|
+
}
|
|
72
|
+
/** The budget in a UserUsageLimitsResponse, or null when the body is not one. */
|
|
73
|
+
export function routerBudgetOf(body) {
|
|
74
|
+
const response = record(body);
|
|
75
|
+
if (!response || !Array.isArray(response.policies))
|
|
76
|
+
return null;
|
|
77
|
+
const totals = response.totals === null ? null : record(response.totals);
|
|
78
|
+
if (response.totals !== null && !totals)
|
|
79
|
+
return null;
|
|
80
|
+
const usageOf = (policy) => {
|
|
81
|
+
const rows = Array.isArray(totals?.policies) ? totals.policies.map(record) : [];
|
|
82
|
+
const own = rows.find(row => row !== null && typeof policy.id === 'string' && row.id === policy.id);
|
|
83
|
+
if (own)
|
|
84
|
+
return own;
|
|
85
|
+
// A policy over every model counts the scope's whole usage, which older instances serve alone.
|
|
86
|
+
return policy.provider === '*' && policy.model === '*' ? record(totals?.usage) : null;
|
|
87
|
+
};
|
|
88
|
+
const limits = [];
|
|
89
|
+
for (const entry of response.policies) {
|
|
90
|
+
const policy = record(entry);
|
|
91
|
+
if (!policy || policy.enabled === false || typeof policy.provider !== 'string' || typeof policy.model !== 'string')
|
|
92
|
+
continue;
|
|
93
|
+
const usage = usageOf(policy);
|
|
94
|
+
if (!usage)
|
|
95
|
+
continue;
|
|
96
|
+
for (const [field, period, unit, usedField] of PERIOD_FIELDS) {
|
|
97
|
+
if (policy[field] === null || policy[field] === undefined)
|
|
98
|
+
continue;
|
|
99
|
+
const limit = amount(policy[field]);
|
|
100
|
+
const used = amount(usage[usedField]);
|
|
101
|
+
if (Number.isFinite(limit) && limit > 0 && Number.isFinite(used)) {
|
|
102
|
+
limits.push({ label: scopeLabel(policy.provider, policy.model), period, unit, used, limit });
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const reported = record(totals?.quota);
|
|
107
|
+
const quotaLimit = amount(reported?.limit);
|
|
108
|
+
const quotaUsed = amount(reported?.consumed);
|
|
109
|
+
const counts = new Map();
|
|
110
|
+
for (const entry of Array.isArray(totals?.denials) ? totals.denials : []) {
|
|
111
|
+
const denial = record(entry);
|
|
112
|
+
if (denial && typeof denial.code === 'string' && Number.isInteger(denial.count)) {
|
|
113
|
+
counts.set(denial.code, (counts.get(denial.code) ?? 0) + denial.count);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
const helpUrl = routerHelpUrl(response.helpUrl);
|
|
117
|
+
return { limits,
|
|
118
|
+
quota: quotaLimit > 0 && Number.isFinite(quotaUsed) ? { limit: quotaLimit, consumed: quotaUsed } : null,
|
|
119
|
+
refusals: [...counts].map(([code, count]) => ({ code, count })),
|
|
120
|
+
...(helpUrl ? { helpUrl } : {}) };
|
|
121
|
+
}
|
|
122
|
+
/** The person's budget from Router itself, or null when Router does not give it (any failure, quietly). */
|
|
123
|
+
export async function readRouterBudget(credential, timeoutMs = BUDGET_TIMEOUT_MS) {
|
|
124
|
+
return routerBudgetOf(await getJson(credential, '/api/usage/limits', timeoutMs));
|
|
125
|
+
}
|
|
126
|
+
/** A device's standing: the refusals Router counts as in force for its person now; null when unavailable. */
|
|
127
|
+
export async function readRouterStanding(credential, timeoutMs = BUDGET_TIMEOUT_MS) {
|
|
128
|
+
const body = record(await getJson(credential, '/api/cli/usage/standing', timeoutMs));
|
|
129
|
+
if (!body || !Array.isArray(body.blocked))
|
|
130
|
+
return null;
|
|
131
|
+
const periodOf = (value) => value === 'day' || value === 'week' || value === 'month' ? value : null;
|
|
132
|
+
const blocked = body.blocked.map(record).flatMap(entry => entry && typeof entry.code === 'string' ? [{ code: entry.code,
|
|
133
|
+
period: periodOf(entry.period),
|
|
134
|
+
resetsAt: typeof entry.resets_at === 'string' && Number.isFinite(Date.parse(entry.resets_at)) ? entry.resets_at : null }] : []);
|
|
135
|
+
return { blocked };
|
|
136
|
+
}
|
|
137
|
+
/** "$812", "$1,000", "$3.13": whole dollars from $100, cents below. */
|
|
138
|
+
function shortUsd(value) {
|
|
139
|
+
if (value >= 100)
|
|
140
|
+
return `$${Math.round(value).toLocaleString('en-US')}`;
|
|
141
|
+
return Number.isInteger(value) ? `$${value}` : `$${value.toFixed(2)}`;
|
|
142
|
+
}
|
|
143
|
+
/** "812K", "4.2M", "5M". */
|
|
144
|
+
function shortCount(value) {
|
|
145
|
+
for (const [unit, suffix] of [[1e9, 'B'], [1e6, 'M'], [1e3, 'K']]) {
|
|
146
|
+
if (value >= unit) {
|
|
147
|
+
const scaled = value / unit;
|
|
148
|
+
return `${scaled >= 100 ? Math.round(scaled) : Math.round(scaled * 10) / 10}${suffix}`;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return String(Math.round(value));
|
|
152
|
+
}
|
|
153
|
+
/** The limit nearest its end: the one that would refuse first. */
|
|
154
|
+
function bindingLimit(budget) {
|
|
155
|
+
return [...budget.limits].sort((a, b) => b.used / b.limit - a.used / a.limit)[0];
|
|
156
|
+
}
|
|
157
|
+
/** The short form of the binding limit, for the status bar: "$812 / $1,000 week". Null when no limit is set. */
|
|
158
|
+
export function routerBudgetShort(budget) {
|
|
159
|
+
const limit = bindingLimit(budget);
|
|
160
|
+
if (!limit)
|
|
161
|
+
return null;
|
|
162
|
+
return limit.unit === 'usd' ? `${shortUsd(limit.used)} / ${shortUsd(limit.limit)} ${limit.period}`
|
|
163
|
+
: `${shortCount(limit.used)} / ${shortCount(limit.limit)} tokens ${limit.period}`;
|
|
164
|
+
}
|
|
165
|
+
/** One line when a limit is set or the quota is over 80%: "$812 / $1,000 week; quota 4.2M / 5M tokens (84%)". */
|
|
166
|
+
export function routerBudgetLine(budget) {
|
|
167
|
+
const parts = [routerBudgetShort(budget)];
|
|
168
|
+
const quota = budget.quota;
|
|
169
|
+
if (quota && quota.consumed / quota.limit > 0.8) {
|
|
170
|
+
parts.push(`quota ${shortCount(quota.consumed)} / ${shortCount(quota.limit)} tokens (${Math.round(quota.consumed / quota.limit * 100)}%)`);
|
|
171
|
+
}
|
|
172
|
+
const shown = parts.filter((part) => part !== null);
|
|
173
|
+
return shown.length > 0 ? shown.join('; ') : null;
|
|
174
|
+
}
|
|
175
|
+
const fullUsd = (value) => `$${value.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
|
|
176
|
+
const PERIOD_WORDS = { day: 'today', week: 'this week', month: 'this month' };
|
|
177
|
+
const refusalName = (code) => ROUTER_USAGE_DENIALS[code] ?? code;
|
|
178
|
+
/** What /usage shows of the budget: each limit and its usage, the quota, and recent and current refusals. */
|
|
179
|
+
export function formatRouterBudget(budget, standing = null) {
|
|
180
|
+
const lines = [budget.helpUrl ? `Zerg Router limits (${budget.helpUrl})` : 'Zerg Router limits'];
|
|
181
|
+
const byLabel = new Map();
|
|
182
|
+
for (const limit of budget.limits) {
|
|
183
|
+
const used = limit.unit === 'usd' ? `${fullUsd(limit.used)} of ${fullUsd(limit.limit)}`
|
|
184
|
+
: `${Math.round(limit.used).toLocaleString('en-US')} of ${Math.round(limit.limit).toLocaleString('en-US')} tokens`;
|
|
185
|
+
byLabel.set(limit.label, [...(byLabel.get(limit.label) ?? []), `${used} ${PERIOD_WORDS[limit.period]}`]);
|
|
186
|
+
}
|
|
187
|
+
for (const [label, parts] of byLabel)
|
|
188
|
+
lines.push(`${label}: ${parts.join('; ')}`);
|
|
189
|
+
if (byLabel.size === 0)
|
|
190
|
+
lines.push('No spending or token limits are set.');
|
|
191
|
+
if (budget.quota) {
|
|
192
|
+
lines.push(`Monthly token quota: ${Math.round(budget.quota.consumed).toLocaleString('en-US')} of ${Math.round(budget.quota.limit).toLocaleString('en-US')} tokens `
|
|
193
|
+
+ `(${Math.round(budget.quota.consumed / budget.quota.limit * 100)}%)`);
|
|
194
|
+
}
|
|
195
|
+
if (budget.refusals.length > 0) {
|
|
196
|
+
lines.push(`Refused in the last 7 days: ${budget.refusals.map(refusal => `${refusalName(refusal.code)} ×${refusal.count}`).join('; ')}`);
|
|
197
|
+
}
|
|
198
|
+
for (const blocked of standing?.blocked ?? []) {
|
|
199
|
+
const resets = blocked.resetsAt ? `, resets ${localRouterTime(Date.parse(blocked.resetsAt))}` : '';
|
|
200
|
+
lines.push(`Refused now: ${refusalName(blocked.code)}${blocked.period ? ` (${blocked.period})` : ''}${resets}`);
|
|
201
|
+
}
|
|
202
|
+
return lines.join('\n');
|
|
203
|
+
}
|
|
204
|
+
/** The status bar's budget: the binding limit, or that Router is refusing now. Undefined when there is nothing to show. */
|
|
205
|
+
export function routerStatusBudget(budget, standing) {
|
|
206
|
+
if (standing && standing.blocked.length > 0) {
|
|
207
|
+
const first = standing.blocked[0];
|
|
208
|
+
return `Router limit reached${first.period ? ` (${first.period})` : ''}`;
|
|
209
|
+
}
|
|
210
|
+
const short = budget && routerBudgetShort(budget);
|
|
211
|
+
return short ? `Router ${short}` : undefined;
|
|
212
|
+
}
|
package/dist/simulation/llm.js
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
import { configStore } from '../config.js';
|
|
8
8
|
import { createBackendForProvider } from '../agent/backends/index.js';
|
|
9
9
|
import { CodexBufferedDeadlineError } from '../agent/backends/codex_buffered_recovery.js';
|
|
10
|
+
import { isRouterRefusal } from '../agent/backends/router_refusal.js';
|
|
10
11
|
import { jsonrepair } from 'jsonrepair';
|
|
11
12
|
import { simSwarmExtractFirstJson as extractFirstJson } from '@ztc/sim-swarm';
|
|
12
13
|
import { resolveSimulationInference, } from './inference.js';
|
|
@@ -208,6 +209,9 @@ export async function withBackoff(fn, maxAttempts = 3, baseDelayMs = 1000) {
|
|
|
208
209
|
}
|
|
209
210
|
catch (err) {
|
|
210
211
|
lastError = err;
|
|
212
|
+
// Zerg Router refused it (or ZTC is holding Router's refusal): a retry only meets the same refusal.
|
|
213
|
+
if (isRouterRefusal(err))
|
|
214
|
+
throw err;
|
|
211
215
|
if (attempt < maxAttempts) {
|
|
212
216
|
const delay = baseDelayMs * Math.pow(2, attempt - 1);
|
|
213
217
|
const jitter = delay * (0.75 + Math.random() * 0.5);
|
|
@@ -21,7 +21,9 @@ export declare class OpenAIEmbeddingProvider implements EmbeddingProvider {
|
|
|
21
21
|
private apiKey;
|
|
22
22
|
private baseUrl;
|
|
23
23
|
private model;
|
|
24
|
-
|
|
24
|
+
/** Set when embeddings go through Zerg Router: its refusals are not retried and hold the process's gate. */
|
|
25
|
+
private readonly router?;
|
|
26
|
+
constructor(apiKey: string, baseUrl?: string, model?: string, routerRoute?: string);
|
|
25
27
|
embed(text: string): Promise<number[]>;
|
|
26
28
|
embedBatch(texts: string[]): Promise<number[][]>;
|
|
27
29
|
}
|