@zergai/ztc 0.11.1-dev.202611072103 → 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.
Files changed (45) hide show
  1. package/README.md +36 -1
  2. package/bin/zmux-darwin-arm64 +0 -0
  3. package/bin/ztc-audio-darwin-arm64 +0 -0
  4. package/bin/ztc-capture-darwin-arm64 +0 -0
  5. package/bin/ztc-computer-darwin-arm64 +0 -0
  6. package/bin/ztc-llm-darwin-arm64 +0 -0
  7. package/bin/ztc-tts-darwin-arm64 +0 -0
  8. package/bin/ztc-tui-darwin-arm64 +0 -0
  9. package/bin/zterm-darwin-arm64 +0 -0
  10. package/dist/App.js +27 -3
  11. package/dist/agent/agent.d.ts +8 -1
  12. package/dist/agent/agent.js +36 -15
  13. package/dist/agent/backends/http_error.d.ts +6 -0
  14. package/dist/agent/backends/http_error.js +31 -18
  15. package/dist/agent/backends/router_gate.d.ts +81 -0
  16. package/dist/agent/backends/router_gate.js +133 -0
  17. package/dist/agent/backends/router_refusal.d.ts +103 -0
  18. package/dist/agent/backends/router_refusal.js +262 -0
  19. package/dist/agent/backends/router_refusal_record.d.ts +22 -0
  20. package/dist/agent/backends/router_refusal_record.js +142 -0
  21. package/dist/agent/backends/router_requests.d.ts +15 -0
  22. package/dist/agent/backends/router_requests.js +41 -0
  23. package/dist/agent/backends/types.d.ts +5 -0
  24. package/dist/agent/backends/zrouter_stream.d.ts +7 -0
  25. package/dist/agent/backends/zrouter_stream.js +95 -14
  26. package/dist/agent/commands/usage.js +7 -2
  27. package/dist/cli_ratatui.d.ts +23 -0
  28. package/dist/cli_ratatui.js +102 -15
  29. package/dist/config.d.ts +8 -0
  30. package/dist/config.js +10 -0
  31. package/dist/headless.d.ts +28 -0
  32. package/dist/headless.js +102 -12
  33. package/dist/router_budget.d.ts +55 -0
  34. package/dist/router_budget.js +212 -0
  35. package/dist/simulation/llm.js +4 -0
  36. package/dist/simulation/memory/embedding.d.ts +3 -1
  37. package/dist/simulation/memory/embedding.js +35 -2
  38. package/dist/ui/views/app.d.ts +3 -1
  39. package/dist/ui/views/app.js +2 -1
  40. package/dist/ui/views/status_bar.d.ts +2 -0
  41. package/dist/ui/views/status_bar.js +5 -0
  42. package/dist/web/mirror_stream.d.ts +2 -0
  43. package/dist/web/mirror_stream.js +2 -1
  44. package/dist/zlm-embed.mjs +649 -236
  45. package/package.json +11 -6
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Zerg Router's refusals that come before any provider is called (`provider_dispatched: false`), read from Router's
3
+ * two error envelopes and from the ZergAI platform proxy's own answers, and the words ZTC shows for them.
4
+ *
5
+ * Router (zapps/zergrouter shared/usage-controls.ts): a usage refusal's error data carries `code` and
6
+ * `provider_dispatched: false`; current builds add `period`, `resets_at` (null when waiting will not help), `scope`
7
+ * and `help_url`, and word the message so a person can act on it. A platform key out of credit is a 429
8
+ * `insufficient_quota` / `credit_balance_exhausted`, a provider still cooling down `provider_rate_limit_cooldown`
9
+ * with `retryAfterSeconds`. These sit in `data` in the H3 envelope (a resumable turn's router_error frame and non-/v1
10
+ * routes) and under `error` on the /v1 routes. The platform proxy (zergai/api/zrouter/proxy.py) passes Router's status
11
+ * and body through but drops its headers, so retry timing is read from the body; its own workspace quota and request
12
+ * throttles answer in their own shapes.
13
+ */
14
+ import { RequestRefusedError } from './types.js';
15
+ export type RouterRefusalKind =
16
+ /** Lasts until a reset or a change: the turn ends at once. */
17
+ 'lasting'
18
+ /** A full concurrency limit: clears as running requests finish, so it is a bounded retry. */
19
+ | 'concurrency'
20
+ /** No provider key can serve until a cooldown ends: wait it out, never retry sooner. */
21
+ | 'cooldown'
22
+ /** A request-rate limit on Router's or the platform's admission: a bounded wait. */
23
+ | 'throttle';
24
+ export type RouterRefusalPeriod = 'day' | 'week' | 'month';
25
+ export interface RouterRefusal {
26
+ kind: RouterRefusalKind;
27
+ /** Router's code, or one of ZTC's names for the platform proxy's own answers. */
28
+ code: string;
29
+ status: number;
30
+ /** Router's sentence, cleaned for a terminal. */
31
+ message: string;
32
+ period?: RouterRefusalPeriod | null;
33
+ /** When waiting clears it (ISO); null when waiting will not help; absent when an older Router does not say. */
34
+ resetsAt?: string | null;
35
+ scope?: 'user' | 'app';
36
+ /** Where the person reads their limits: https on Router's own domain only. */
37
+ helpUrl?: string;
38
+ /** How long until another attempt can succeed. */
39
+ retryAfterSeconds?: number;
40
+ }
41
+ /**
42
+ * The longest provider cooldown a turn waits out. Router cools a rate-limited key for 60 seconds unless the provider
43
+ * names a longer wait (provider-credentials.ts DEFAULT_RATE_LIMIT_COOLDOWN_MS), so this rides out Router's own cooldown;
44
+ * a longer one is the provider's, often a daily cap, and a turn blocked that long with nothing to show looks hung, so
45
+ * the turn ends with the time it clears.
46
+ */
47
+ export declare const ROUTER_COOLDOWN_TURN_WAIT_SECONDS = 60;
48
+ /** The code an agent error carries when Zerg Router refused the turn's request (or ZTC refused it for Router). */
49
+ export declare const ROUTER_USAGE_REFUSED = "ROUTER_USAGE_REFUSED";
50
+ /**
51
+ * A request Zerg Router refused before calling any provider, or one ZTC refused locally because Router had refused it.
52
+ * Its message is shown as written. `status` is Router's, so the worker pool treats it as it would the response.
53
+ */
54
+ export declare class RouterRefusalError extends RequestRefusedError {
55
+ readonly refusal: RouterRefusal;
56
+ /** True when ZTC refused it without contacting Router. */ readonly local: boolean;
57
+ /** When a provider cooldown that ended the turn clears (epoch ms). */ readonly retryAt?: number | undefined;
58
+ constructor(message: string, refusal: RouterRefusal,
59
+ /** True when ZTC refused it without contacting Router. */ local?: boolean,
60
+ /** When a provider cooldown that ended the turn clears (epoch ms). */ retryAt?: number | undefined);
61
+ get status(): number;
62
+ }
63
+ /**
64
+ * The error that ends a request on this refusal, or null when the refusal is a wait the request rides out: a lasting
65
+ * refusal ends it at once, and so does a provider cooldown longer than ROUTER_COOLDOWN_TURN_WAIT_SECONDS, carrying
66
+ * when it clears so the gate holds the route until then.
67
+ */
68
+ export declare function endingRouterRefusal(refusal: RouterRefusal, now?: number): RouterRefusalError | null;
69
+ /** The Router refusal an error is, or wraps (an agent error keeps it as its cause); null for any other error. */
70
+ export declare function routerRefusalOf(error: unknown): RouterRefusalError | null;
71
+ /** Whether an error, or one it wraps, is a Router refusal that ended the request. */
72
+ export declare function isRouterRefusal(error: unknown): boolean;
73
+ /**
74
+ * Router's usage-control refusals a client may be told about (PUBLIC_USAGE_DENIALS) and the monthly token quota
75
+ * (USAGE_DENIAL_TEXT), with their fixed text: all an older Router sends. None carries request data.
76
+ */
77
+ export declare const ROUTER_USAGE_DENIALS: Readonly<Record<string, string>>;
78
+ /** The platform proxy's own refusal: its workspace token quota cannot hold the request. */
79
+ export declare const PLATFORM_TOKEN_QUOTA = "platform_token_quota_exceeded";
80
+ /** The platform proxy's own request-rate or concurrency throttle for a CLI machine credential. */
81
+ export declare const PLATFORM_THROTTLE = "platform_throttled";
82
+ /**
83
+ * The refusal an error response describes, or null for any other error. `status` is the HTTP status (or a router_error
84
+ * frame's), `body` the error body as text.
85
+ */
86
+ export declare function readRouterRefusal(status: number, body: string): RouterRefusal | null;
87
+ /**
88
+ * Router's words as a terminal can show them: escape sequences removed, control characters made spaces, everything
89
+ * else in Unicode's Other category (format characters such as bidi controls, zero-width and tag characters; lone
90
+ * surrogates; private-use and unassigned code points) removed, whitespace collapsed to single spaces, and at most
91
+ * `max` characters.
92
+ */
93
+ export declare function cleanRouterText(text: string, max?: number): string;
94
+ /** A help link Router gave, when it is https on zergrouter.com or one of its subdomains and carries no credentials. */
95
+ export declare function routerHelpUrl(value: unknown): string | undefined;
96
+ /** A moment in the person's own time zone, named: "Sun, Nov 8, 4:00 PM PST". */
97
+ export declare function localRouterTime(at: number): string;
98
+ /**
99
+ * What ZTC shows for a refusal: Router's words, then the reset in the person's local time when Router gives one (and
100
+ * nothing about waiting when waiting will not help), then the help link unless Router's words already hold it.
101
+ * `retryAt` is when a cooldown that ended the turn clears.
102
+ */
103
+ export declare function formatRouterRefusal(refusal: RouterRefusal, now?: number, retryAt?: number): string;
@@ -0,0 +1,262 @@
1
+ /**
2
+ * Zerg Router's refusals that come before any provider is called (`provider_dispatched: false`), read from Router's
3
+ * two error envelopes and from the ZergAI platform proxy's own answers, and the words ZTC shows for them.
4
+ *
5
+ * Router (zapps/zergrouter shared/usage-controls.ts): a usage refusal's error data carries `code` and
6
+ * `provider_dispatched: false`; current builds add `period`, `resets_at` (null when waiting will not help), `scope`
7
+ * and `help_url`, and word the message so a person can act on it. A platform key out of credit is a 429
8
+ * `insufficient_quota` / `credit_balance_exhausted`, a provider still cooling down `provider_rate_limit_cooldown`
9
+ * with `retryAfterSeconds`. These sit in `data` in the H3 envelope (a resumable turn's router_error frame and non-/v1
10
+ * routes) and under `error` on the /v1 routes. The platform proxy (zergai/api/zrouter/proxy.py) passes Router's status
11
+ * and body through but drops its headers, so retry timing is read from the body; its own workspace quota and request
12
+ * throttles answer in their own shapes.
13
+ */
14
+ import { RequestRefusedError } from './types.js';
15
+ /**
16
+ * The longest provider cooldown a turn waits out. Router cools a rate-limited key for 60 seconds unless the provider
17
+ * names a longer wait (provider-credentials.ts DEFAULT_RATE_LIMIT_COOLDOWN_MS), so this rides out Router's own cooldown;
18
+ * a longer one is the provider's, often a daily cap, and a turn blocked that long with nothing to show looks hung, so
19
+ * the turn ends with the time it clears.
20
+ */
21
+ export const ROUTER_COOLDOWN_TURN_WAIT_SECONDS = 60;
22
+ /** The code an agent error carries when Zerg Router refused the turn's request (or ZTC refused it for Router). */
23
+ export const ROUTER_USAGE_REFUSED = 'ROUTER_USAGE_REFUSED';
24
+ /**
25
+ * A request Zerg Router refused before calling any provider, or one ZTC refused locally because Router had refused it.
26
+ * Its message is shown as written. `status` is Router's, so the worker pool treats it as it would the response.
27
+ */
28
+ export class RouterRefusalError extends RequestRefusedError {
29
+ refusal;
30
+ local;
31
+ retryAt;
32
+ constructor(message, refusal,
33
+ /** True when ZTC refused it without contacting Router. */ local = false,
34
+ /** When a provider cooldown that ended the turn clears (epoch ms). */ retryAt) {
35
+ super(message);
36
+ this.refusal = refusal;
37
+ this.local = local;
38
+ this.retryAt = retryAt;
39
+ }
40
+ get status() { return this.refusal.status; }
41
+ }
42
+ /**
43
+ * The error that ends a request on this refusal, or null when the refusal is a wait the request rides out: a lasting
44
+ * refusal ends it at once, and so does a provider cooldown longer than ROUTER_COOLDOWN_TURN_WAIT_SECONDS, carrying
45
+ * when it clears so the gate holds the route until then.
46
+ */
47
+ export function endingRouterRefusal(refusal, now = Date.now()) {
48
+ if (refusal.kind === 'lasting')
49
+ return new RouterRefusalError(formatRouterRefusal(refusal, now), refusal);
50
+ if (refusal.kind === 'cooldown' && refusal.retryAfterSeconds !== undefined && refusal.retryAfterSeconds > ROUTER_COOLDOWN_TURN_WAIT_SECONDS) {
51
+ const retryAt = now + refusal.retryAfterSeconds * 1000;
52
+ return new RouterRefusalError(formatRouterRefusal(refusal, now, retryAt), refusal, false, retryAt);
53
+ }
54
+ return null;
55
+ }
56
+ /** The Router refusal an error is, or wraps (an agent error keeps it as its cause); null for any other error. */
57
+ export function routerRefusalOf(error) {
58
+ for (let current = error, depth = 0; current instanceof Error && depth < 4; current = current.cause, depth++) {
59
+ if (current instanceof RouterRefusalError)
60
+ return current;
61
+ }
62
+ return null;
63
+ }
64
+ /** Whether an error, or one it wraps, is a Router refusal that ended the request. */
65
+ export function isRouterRefusal(error) {
66
+ for (let current = error, depth = 0; current instanceof Error && depth < 4; current = current.cause, depth++) {
67
+ if (current instanceof RouterRefusalError || current.code === ROUTER_USAGE_REFUSED)
68
+ return true;
69
+ }
70
+ return false;
71
+ }
72
+ /**
73
+ * Router's usage-control refusals a client may be told about (PUBLIC_USAGE_DENIALS) and the monthly token quota
74
+ * (USAGE_DENIAL_TEXT), with their fixed text: all an older Router sends. None carries request data.
75
+ */
76
+ export const ROUTER_USAGE_DENIALS = Object.freeze({
77
+ router_usage_application_disabled: 'Application is disabled',
78
+ router_usage_actor_required: 'Application inference requires an attributed user token',
79
+ router_usage_actor_invalid: 'Application user account is unavailable',
80
+ router_usage_model_denied: 'Model is outside this application policy',
81
+ router_usage_disabled: 'Inference is disabled for this provider/model',
82
+ router_usage_unpriced: 'This spending limit requires a reliable request cost bound',
83
+ router_usage_unpriced_history: 'This spending limit has earlier usage with unknown cost',
84
+ router_usage_budget_exceeded: 'Inference spending limit reached',
85
+ router_usage_token_limit_exceeded: 'Token usage limit reached',
86
+ router_usage_concurrency_exceeded: 'Concurrent inference request limit reached',
87
+ personal_token_quota_exceeded: 'Monthly token quota reached',
88
+ });
89
+ const CONCURRENCY = 'router_usage_concurrency_exceeded';
90
+ /** Limits a period's end clears: waiting helps even when an older Router does not say when. */
91
+ const PERIOD_LIMITS = new Set(['router_usage_budget_exceeded', 'router_usage_token_limit_exceeded', 'personal_token_quota_exceeded']);
92
+ const CREDIT = new Set(['insufficient_quota', 'credit_balance_exhausted']);
93
+ const COOLDOWN = 'provider_rate_limit_cooldown';
94
+ /** The platform proxy's own refusal: its workspace token quota cannot hold the request. */
95
+ export const PLATFORM_TOKEN_QUOTA = 'platform_token_quota_exceeded';
96
+ /** The platform proxy's own request-rate or concurrency throttle for a CLI machine credential. */
97
+ export const PLATFORM_THROTTLE = 'platform_throttled';
98
+ const PERIODS = ['day', 'week', 'month'];
99
+ /** Router's longest worded refusals run to about 300 characters; anything longer is cut. */
100
+ const ROUTER_TEXT_CHARS = 360;
101
+ const WAIT_GUIDANCE = 'Wait for the limit to reset, or ask a Zerg Router admin to raise it.';
102
+ function record(value) {
103
+ return value !== null && typeof value === 'object' && !Array.isArray(value) ? value : null;
104
+ }
105
+ /** The fields and sentence of one error body, from whichever envelope it uses. */
106
+ function envelopeOf(parsed) {
107
+ const nested = record(parsed.error);
108
+ // /v1 routes, the platform proxy's own answers and Router's older frames: the details sit under `error`.
109
+ if (nested)
110
+ return { fields: nested, message: nested.message ?? parsed.statusMessage, type: nested.type };
111
+ // H3: a boolean `error`, the details in `data`, the sentence in `message`.
112
+ if (parsed.error === true || (parsed.error === undefined && typeof parsed.statusCode === 'number')) {
113
+ return { fields: record(parsed.data) ?? {}, message: typeof parsed.message === 'string' && parsed.message ? parsed.message : parsed.statusMessage };
114
+ }
115
+ // Django REST framework's throttles, as the platform proxy sends them.
116
+ if (typeof parsed.detail === 'string')
117
+ return { fields: {}, message: parsed.detail, detail: true };
118
+ return null;
119
+ }
120
+ /**
121
+ * The refusal an error response describes, or null for any other error. `status` is the HTTP status (or a router_error
122
+ * frame's), `body` the error body as text.
123
+ */
124
+ export function readRouterRefusal(status, body) {
125
+ if (!Number.isInteger(status) || status < 400)
126
+ return null;
127
+ let parsed;
128
+ try {
129
+ parsed = JSON.parse(body);
130
+ }
131
+ catch {
132
+ return null;
133
+ }
134
+ const top = record(parsed);
135
+ const envelope = top && envelopeOf(top);
136
+ if (!envelope)
137
+ return null;
138
+ const { fields } = envelope;
139
+ const code = typeof fields.code === 'string' ? fields.code : undefined;
140
+ const dispatched = fields.provider_dispatched;
141
+ const said = typeof envelope.message === 'string' ? cleanRouterText(envelope.message) : '';
142
+ let kind;
143
+ let name = code ?? '';
144
+ let fallback;
145
+ let retryAfterSeconds;
146
+ if (code && Object.hasOwn(ROUTER_USAGE_DENIALS, code) && dispatched !== true) {
147
+ kind = code === CONCURRENCY ? 'concurrency' : 'lasting';
148
+ fallback = ROUTER_USAGE_DENIALS[code];
149
+ }
150
+ else if (code && CREDIT.has(code) && dispatched === false) {
151
+ kind = 'lasting';
152
+ fallback = 'The provider\'s credit is exhausted. Funding or a replacement key is required.';
153
+ }
154
+ else if (code === COOLDOWN && dispatched === false) {
155
+ kind = 'cooldown';
156
+ fallback = 'The provider is temporarily rate limited.';
157
+ retryAfterSeconds = wholeSeconds(fields.retryAfterSeconds, 86_400);
158
+ }
159
+ else if (code === 'router_key_rate_limit' && fields.source === 'router_admission') {
160
+ kind = 'throttle';
161
+ fallback = 'Zerg Router request rate limit reached.';
162
+ retryAfterSeconds = wholeSeconds(fields.resetSeconds, 60);
163
+ }
164
+ else if (status === 429 && !code && dispatched === undefined && envelope.type === 'rate_limit_error' && /^Token quota exceeded\b/i.test(said)) {
165
+ // The proxy's own answer carries only a message and a type; a body saying whether a provider was called is Router's.
166
+ kind = 'lasting';
167
+ name = PLATFORM_TOKEN_QUOTA;
168
+ fallback = 'Token quota exceeded.';
169
+ }
170
+ else if (status === 429 && envelope.detail && /^(?:Request was throttled|Too many concurrent ZLM requests)\b/.test(said)) {
171
+ kind = 'throttle';
172
+ name = PLATFORM_THROTTLE;
173
+ fallback = 'Request was throttled.';
174
+ const wait = /Expected available in (\d{1,6}) seconds?/.exec(said);
175
+ retryAfterSeconds = wait ? wholeSeconds(Number(wait[1]), 86_400) : undefined;
176
+ }
177
+ else {
178
+ return null;
179
+ }
180
+ const refusal = { kind, code: name, status, message: said || fallback };
181
+ if (fields.period === null || (typeof fields.period === 'string' && PERIODS.includes(fields.period)))
182
+ refusal.period = fields.period;
183
+ if (fields.resets_at === null)
184
+ refusal.resetsAt = null;
185
+ else if (typeof fields.resets_at === 'string' && /^\d{4}-\d{2}-\d{2}T[\d:.]+Z$/.test(fields.resets_at) && Number.isFinite(Date.parse(fields.resets_at))) {
186
+ refusal.resetsAt = fields.resets_at;
187
+ }
188
+ if (fields.scope === 'user' || fields.scope === 'app')
189
+ refusal.scope = fields.scope;
190
+ const help = routerHelpUrl(fields.help_url);
191
+ if (help)
192
+ refusal.helpUrl = help;
193
+ if (retryAfterSeconds !== undefined)
194
+ refusal.retryAfterSeconds = retryAfterSeconds;
195
+ return refusal;
196
+ }
197
+ function wholeSeconds(value, max) {
198
+ return typeof value === 'number' && Number.isInteger(value) && value >= 1 && value <= max ? value : undefined;
199
+ }
200
+ /**
201
+ * Router's words as a terminal can show them: escape sequences removed, control characters made spaces, everything
202
+ * else in Unicode's Other category (format characters such as bidi controls, zero-width and tag characters; lone
203
+ * surrogates; private-use and unassigned code points) removed, whitespace collapsed to single spaces, and at most
204
+ * `max` characters.
205
+ */
206
+ export function cleanRouterText(text, max = ROUTER_TEXT_CHARS) {
207
+ const printable = text
208
+ // eslint-disable-next-line no-control-regex
209
+ .replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, '')
210
+ // eslint-disable-next-line no-control-regex
211
+ .replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)?/g, '')
212
+ // eslint-disable-next-line no-control-regex
213
+ .replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ')
214
+ .replace(/\p{C}/gu, '')
215
+ .replace(/\s+/g, ' ')
216
+ .trim();
217
+ const characters = Array.from(printable);
218
+ return characters.length > max ? `${characters.slice(0, max - 1).join('').trimEnd()}…` : printable;
219
+ }
220
+ /** A help link Router gave, when it is https on zergrouter.com or one of its subdomains and carries no credentials. */
221
+ export function routerHelpUrl(value) {
222
+ if (typeof value !== 'string' || value.length > 512)
223
+ return undefined;
224
+ let url;
225
+ try {
226
+ url = new URL(value);
227
+ }
228
+ catch {
229
+ return undefined;
230
+ }
231
+ const host = url.hostname.toLowerCase();
232
+ if (url.protocol !== 'https:' || url.username || url.password || (host !== 'zergrouter.com' && !host.endsWith('.zergrouter.com')))
233
+ return undefined;
234
+ // eslint-disable-next-line no-control-regex
235
+ return /[\s\u0000-\u001f\u007f]/.test(url.href) ? undefined : url.href;
236
+ }
237
+ /** A moment in the person's own time zone, named: "Sun, Nov 8, 4:00 PM PST". */
238
+ export function localRouterTime(at) {
239
+ return new Intl.DateTimeFormat('en-US', { weekday: 'short', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit',
240
+ timeZoneName: 'short' }).format(new Date(at));
241
+ }
242
+ function sentence(text) {
243
+ return /[.!?…]$/.test(text) ? text : `${text}.`;
244
+ }
245
+ /**
246
+ * What ZTC shows for a refusal: Router's words, then the reset in the person's local time when Router gives one (and
247
+ * nothing about waiting when waiting will not help), then the help link unless Router's words already hold it.
248
+ * `retryAt` is when a cooldown that ended the turn clears.
249
+ */
250
+ export function formatRouterRefusal(refusal, now = Date.now(), retryAt) {
251
+ let text = sentence(refusal.message);
252
+ const resets = typeof refusal.resetsAt === 'string' ? Date.parse(refusal.resetsAt) : NaN;
253
+ if (retryAt !== undefined)
254
+ text += ` Try again after ${localRouterTime(retryAt)}.`;
255
+ else if (resets > now)
256
+ text += ` Local reset: ${localRouterTime(resets)}.`;
257
+ else if (refusal.resetsAt === undefined && PERIOD_LIMITS.has(refusal.code))
258
+ text += ` ${WAIT_GUIDANCE}`;
259
+ if (refusal.helpUrl && !text.includes(refusal.helpUrl))
260
+ text += ` See ${refusal.helpUrl}.`;
261
+ return text;
262
+ }
@@ -0,0 +1,22 @@
1
+ import { type RouterHold } from './router_gate.js';
2
+ /**
3
+ * How long a refusal Router gives no reset for stays recorded after it was last met. Router counts such a refusal as
4
+ * still in force for 15 minutes after a client last met it (usage-denial-log.ts STANDING_WINDOW_MINUTES); each refused
5
+ * attempt records it again, so a loop keeps it while Router keeps refusing, and a record nobody re-tries lapses soon
6
+ * after the problem is fixed.
7
+ */
8
+ export declare const UNRESET_REFUSAL_RECORD_MS: number;
9
+ export declare function routerRefusalRecordPath(): string;
10
+ /** The record's entries in force at `now`. A missing or unreadable record holds nothing. */
11
+ export declare function readRouterRefusalRecord(path?: string, now?: number): RouterHold[];
12
+ /**
13
+ * Take the profile's recorded refusals into this process's gate. An unattended run records its own refusals and
14
+ * claims its attempts in the record; an interactive one only clears an entry a success shows is over. Returns what is
15
+ * recorded, for a launch to show.
16
+ */
17
+ export declare function adoptRouterRefusalRecord(mode: 'unattended' | 'interactive', path?: string): RouterHold[];
18
+ /**
19
+ * What an interactive launch says about a recorded refusal. A provider cooldown's words already say when to try again,
20
+ * and nothing is sent before then; for anything else the person's next message still gets its attempt.
21
+ */
22
+ export declare function formatRecordedRouterRefusal(hold: RouterHold): string;
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Zerg Router refusals recorded beside ZTC's config, so a shell or cron loop relaunching ZTC cannot hammer Router.
3
+ *
4
+ * A refused unattended run records the refusal with its expiry in `router-refusals.json` in the profile's config
5
+ * directory. Later unattended runs take it into their gate and honour it the same way: requests for the held route and
6
+ * model fail locally, and one real attempt every five minutes goes through, claimed in the record before it is sent so
7
+ * runs launched together make one between them. A success removes the entry. An interactive launch shows what is
8
+ * recorded and holds it for its own background work (heartbeats, routines, workers), but every new message from the
9
+ * person still gets one real attempt, since they may have just raised the limit (a provider cooldown excepted: nothing
10
+ * is tried before it clears); it records nothing of its own, and a success there removes the entry too.
11
+ *
12
+ * The record holds the route, a one-way fingerprint of the account, the provider, the model and Router's public words
13
+ * and fields for the refusal: no credential and nothing of the request. Every write replaces the file atomically
14
+ * (write a private temporary file, then rename it over the record).
15
+ */
16
+ import { randomUUID } from 'node:crypto';
17
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
18
+ import { join } from 'node:path';
19
+ import { profileConfigDir } from '../../config/profiles.js';
20
+ import { ROUTER_REFUSAL_RETRY_MS, routerRefusalGate } from './router_gate.js';
21
+ import { localRouterTime } from './router_refusal.js';
22
+ /**
23
+ * How long a refusal Router gives no reset for stays recorded after it was last met. Router counts such a refusal as
24
+ * still in force for 15 minutes after a client last met it (usage-denial-log.ts STANDING_WINDOW_MINUTES); each refused
25
+ * attempt records it again, so a loop keeps it while Router keeps refusing, and a record nobody re-tries lapses soon
26
+ * after the problem is fixed.
27
+ */
28
+ export const UNRESET_REFUSAL_RECORD_MS = 15 * 60_000;
29
+ const RECORD_FILE = 'router-refusals.json';
30
+ const MAX_RECORDS = 32;
31
+ const KINDS = ['lasting', 'concurrency', 'cooldown', 'throttle'];
32
+ export function routerRefusalRecordPath() {
33
+ return join(profileConfigDir(), RECORD_FILE);
34
+ }
35
+ const text = (value, max) => typeof value === 'string' && value.length > 0 && value.length <= max;
36
+ const instant = (value) => (typeof value === 'string' ? Date.parse(value) : NaN);
37
+ /** One entry as the gate holds it, or null for anything malformed. */
38
+ function holdOf(value) {
39
+ if (!value || typeof value !== 'object')
40
+ return null;
41
+ const entry = value;
42
+ const refusal = entry.refusal;
43
+ if (!text(entry.route, 2048) || !text(entry.account, 128) || !text(entry.provider, 80) || !text(entry.model, 260) || !text(entry.message, 2000)
44
+ || !refusal || !KINDS.includes(refusal.kind) || !text(refusal.code, 80) || !text(refusal.message, 2000)
45
+ || !Number.isInteger(refusal.status) || typeof entry.waitOut !== 'boolean')
46
+ return null;
47
+ const expires = instant(entry.expiresAt);
48
+ const until = entry.until === null ? null : instant(entry.until);
49
+ const refusedAt = instant(entry.refusedAt);
50
+ const lastAttemptAt = instant(entry.lastAttemptAt);
51
+ if (![expires, refusedAt, lastAttemptAt].every(Number.isFinite) || (until !== null && !Number.isFinite(until)))
52
+ return null;
53
+ // Held until the entry expires: a reset where Router gave one, else a while after the refusal was last met.
54
+ return { route: entry.route, account: entry.account, provider: entry.provider, model: entry.model, refusal: refusal,
55
+ message: entry.message, until: until === null ? expires : Math.min(until, expires), waitOut: entry.waitOut, refusedAt, lastAttemptAt };
56
+ }
57
+ function entryOf(hold) {
58
+ const expires = hold.until ?? hold.lastAttemptAt + UNRESET_REFUSAL_RECORD_MS;
59
+ return { route: hold.route, account: hold.account, provider: hold.provider, model: hold.model, refusal: hold.refusal, message: hold.message,
60
+ until: hold.until === null ? null : new Date(hold.until).toISOString(), waitOut: hold.waitOut,
61
+ refusedAt: new Date(hold.refusedAt).toISOString(), lastAttemptAt: new Date(hold.lastAttemptAt).toISOString(),
62
+ expiresAt: new Date(expires).toISOString() };
63
+ }
64
+ const sameKey = (a, b) => a.route === b.route && a.account === b.account && a.provider === b.provider && a.model === b.model;
65
+ /** The record's entries in force at `now`. A missing or unreadable record holds nothing. */
66
+ export function readRouterRefusalRecord(path = routerRefusalRecordPath(), now = Date.now()) {
67
+ try {
68
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
69
+ if (parsed.version !== 1 || !Array.isArray(parsed.refusals))
70
+ return [];
71
+ return parsed.refusals.slice(0, MAX_RECORDS).map(holdOf).filter((hold) => hold !== null && (hold.until === null || hold.until > now));
72
+ }
73
+ catch {
74
+ return [];
75
+ }
76
+ }
77
+ function writeRecord(path, holds) {
78
+ try {
79
+ if (holds.length === 0) {
80
+ rmSync(path, { force: true });
81
+ return;
82
+ }
83
+ mkdirSync(join(path, '..'), { recursive: true });
84
+ const temporary = `${path}.${process.pid}.${randomUUID()}.tmp`;
85
+ writeFileSync(temporary, `${JSON.stringify({ version: 1, refusals: holds.slice(-MAX_RECORDS).map(entryOf) }, null, 2)}\n`, { mode: 0o600 });
86
+ renameSync(temporary, path);
87
+ }
88
+ catch {
89
+ // The record only spares Router a relaunch's requests; the process gate still holds.
90
+ }
91
+ }
92
+ /** The record as the gate's store: an unattended run records and claims; an interactive one only clears. */
93
+ class RouterRefusalRecord {
94
+ path;
95
+ unattended;
96
+ constructor(path, unattended) {
97
+ this.path = path;
98
+ this.unattended = unattended;
99
+ }
100
+ update(change) {
101
+ const now = Date.now();
102
+ writeRecord(this.path, change(readRouterRefusalRecord(this.path, now), now));
103
+ }
104
+ claimAttempt(hold, now) {
105
+ if (!this.unattended)
106
+ return true;
107
+ const recorded = readRouterRefusalRecord(this.path, now).find(entry => sameKey(entry, hold));
108
+ // Another run made the attempt meanwhile: take its time, and stay local.
109
+ if (recorded && now - recorded.lastAttemptAt < ROUTER_REFUSAL_RETRY_MS) {
110
+ hold.lastAttemptAt = recorded.lastAttemptAt;
111
+ return false;
112
+ }
113
+ this.update(holds => [...holds.filter(entry => !sameKey(entry, hold)), { ...hold, lastAttemptAt: now }]);
114
+ return true;
115
+ }
116
+ held(hold) {
117
+ if (this.unattended)
118
+ this.update(holds => [...holds.filter(entry => !sameKey(entry, hold)), hold]);
119
+ }
120
+ released(hold) {
121
+ if (readRouterRefusalRecord(this.path).some(entry => sameKey(entry, hold)))
122
+ this.update(holds => holds.filter(entry => !sameKey(entry, hold)));
123
+ }
124
+ }
125
+ /**
126
+ * Take the profile's recorded refusals into this process's gate. An unattended run records its own refusals and
127
+ * claims its attempts in the record; an interactive one only clears an entry a success shows is over. Returns what is
128
+ * recorded, for a launch to show.
129
+ */
130
+ export function adoptRouterRefusalRecord(mode, path = routerRefusalRecordPath()) {
131
+ const recorded = readRouterRefusalRecord(path);
132
+ routerRefusalGate.attach(new RouterRefusalRecord(path, mode === 'unattended'), recorded);
133
+ return recorded;
134
+ }
135
+ /**
136
+ * What an interactive launch says about a recorded refusal. A provider cooldown's words already say when to try again,
137
+ * and nothing is sent before then; for anything else the person's next message still gets its attempt.
138
+ */
139
+ export function formatRecordedRouterRefusal(hold) {
140
+ const refused = `Zerg Router refused ${hold.provider}/${hold.model} for an unattended run at ${localRouterTime(hold.refusedAt)}: ${hold.message}`;
141
+ return hold.waitOut ? refused : `${refused} Your next message still goes to Router, in case the limit has changed.`;
142
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * How many inference requests this process sent to Zerg Router (each HTTP attempt: retries and stream resumes count),
3
+ * and a warning when more than BURST_REQUESTS go out in one minute, at most once every BURST_NOTICE_MS. Unattended
4
+ * runs print both on stderr; there is no client-side cap, Router enforces budgets.
5
+ */
6
+ /** More than this many requests in one minute is a burst worth saying so about. */
7
+ export declare const BURST_REQUESTS = 60;
8
+ /** One request is going out to Router now. */
9
+ export declare function noteRouterRequest(now?: number): void;
10
+ /** Inference requests this process sent to Router so far. */
11
+ export declare function routerRequestsThisRun(): number;
12
+ /** Called with the minute's count when a burst starts, at most once every ten minutes. Returns the unsubscribe. */
13
+ export declare function onRouterRequestBurst(listener: (count: number) => void): () => void;
14
+ /** A fetch that counts each call as a Router request. */
15
+ export declare function countRouterRequests(fetcher: typeof fetch): typeof fetch;
@@ -0,0 +1,41 @@
1
+ /**
2
+ * How many inference requests this process sent to Zerg Router (each HTTP attempt: retries and stream resumes count),
3
+ * and a warning when more than BURST_REQUESTS go out in one minute, at most once every BURST_NOTICE_MS. Unattended
4
+ * runs print both on stderr; there is no client-side cap, Router enforces budgets.
5
+ */
6
+ /** More than this many requests in one minute is a burst worth saying so about. */
7
+ export const BURST_REQUESTS = 60;
8
+ const BURST_WINDOW_MS = 60_000;
9
+ const BURST_NOTICE_MS = 10 * 60_000;
10
+ let total = 0;
11
+ const recent = [];
12
+ let lastNoticeAt = Number.NEGATIVE_INFINITY;
13
+ const listeners = new Set();
14
+ /** One request is going out to Router now. */
15
+ export function noteRouterRequest(now = Date.now()) {
16
+ total += 1;
17
+ recent.push(now);
18
+ while (recent.length > 0 && recent[0] <= now - BURST_WINDOW_MS)
19
+ recent.shift();
20
+ if (recent.length > BURST_REQUESTS && now - lastNoticeAt >= BURST_NOTICE_MS) {
21
+ lastNoticeAt = now;
22
+ for (const listener of listeners)
23
+ listener(recent.length);
24
+ }
25
+ }
26
+ /** Inference requests this process sent to Router so far. */
27
+ export function routerRequestsThisRun() {
28
+ return total;
29
+ }
30
+ /** Called with the minute's count when a burst starts, at most once every ten minutes. Returns the unsubscribe. */
31
+ export function onRouterRequestBurst(listener) {
32
+ listeners.add(listener);
33
+ return () => listeners.delete(listener);
34
+ }
35
+ /** A fetch that counts each call as a Router request. */
36
+ export function countRouterRequests(fetcher) {
37
+ return (input, init) => {
38
+ noteRouterRequest();
39
+ return fetcher(input, init);
40
+ };
41
+ }
@@ -194,6 +194,11 @@ export interface BackendRequest {
194
194
  };
195
195
  /** Stable id for one logical LLM turn across transport reconnects. */
196
196
  transportTurnId?: string;
197
+ /**
198
+ * The first request of a turn the person's own new message started. It gets one real attempt even while Zerg
199
+ * Router's refusal holds the route: they may have just raised the limit.
200
+ */
201
+ personInitiated?: boolean;
197
202
  /** Optional AbortSignal — when aborted, the in-flight HTTP request is cancelled.
198
203
  * The agent aborts this for BOTH a user cancel AND a per-attempt inactivity
199
204
  * timeout, so its aborted-ness alone can't tell the two apart. */
@@ -81,9 +81,16 @@ export declare class ZRouterStreamBackend implements AgentBackend {
81
81
  * bare pin, and an undecorated turn stays the common case it was.
82
82
  */
83
83
  private conversationPin;
84
+ /**
85
+ * What the process gate keys this request by. A host's token provider rotates short-lived tokens, so its account is
86
+ * the host-selected workspace; a fixed key is its own fingerprint.
87
+ */
88
+ private gateTarget;
84
89
  generate(request: BackendRequest): Promise<BackendResponse>;
85
90
  private generateResponse;
86
91
  private parseOpenAIResponse;
87
92
  generateStream(request: BackendRequest): AsyncIterable<StreamEvent>;
93
+ /** A stream the process gate admits; Router answering with output clears whatever held it. */
94
+ private gatedStream;
88
95
  private streamResponse;
89
96
  }