@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.
Files changed (43) hide show
  1. package/README.md +43 -5
  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-tui-darwin-arm64 +0 -0
  6. package/bin/zterm-darwin-arm64 +0 -0
  7. package/dist/App.js +27 -3
  8. package/dist/agent/agent.d.ts +8 -1
  9. package/dist/agent/agent.js +36 -15
  10. package/dist/agent/backends/codex_auth.js +4 -4
  11. package/dist/agent/backends/http_error.d.ts +6 -0
  12. package/dist/agent/backends/http_error.js +31 -18
  13. package/dist/agent/backends/router_gate.d.ts +81 -0
  14. package/dist/agent/backends/router_gate.js +133 -0
  15. package/dist/agent/backends/router_refusal.d.ts +103 -0
  16. package/dist/agent/backends/router_refusal.js +262 -0
  17. package/dist/agent/backends/router_refusal_record.d.ts +22 -0
  18. package/dist/agent/backends/router_refusal_record.js +142 -0
  19. package/dist/agent/backends/router_requests.d.ts +15 -0
  20. package/dist/agent/backends/router_requests.js +41 -0
  21. package/dist/agent/backends/types.d.ts +5 -0
  22. package/dist/agent/backends/zrouter_stream.d.ts +7 -0
  23. package/dist/agent/backends/zrouter_stream.js +95 -14
  24. package/dist/agent/commands/usage.js +7 -2
  25. package/dist/cli_ratatui.d.ts +23 -0
  26. package/dist/cli_ratatui.js +102 -15
  27. package/dist/config.d.ts +8 -0
  28. package/dist/config.js +10 -0
  29. package/dist/headless.d.ts +28 -0
  30. package/dist/headless.js +102 -12
  31. package/dist/router_budget.d.ts +55 -0
  32. package/dist/router_budget.js +212 -0
  33. package/dist/simulation/llm.js +4 -0
  34. package/dist/simulation/memory/embedding.d.ts +3 -1
  35. package/dist/simulation/memory/embedding.js +35 -2
  36. package/dist/ui/views/app.d.ts +3 -1
  37. package/dist/ui/views/app.js +2 -1
  38. package/dist/ui/views/status_bar.d.ts +2 -0
  39. package/dist/ui/views/status_bar.js +5 -0
  40. package/dist/web/mirror_stream.d.ts +2 -0
  41. package/dist/web/mirror_stream.js +2 -1
  42. package/dist/zlm-embed.mjs +6393 -40056
  43. package/package.json +16 -3
@@ -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
  }
@@ -14,6 +14,9 @@ import { clampCompletionTokens } from '../../utils/deepseek.js';
14
14
  import { getVersion } from '../../utils/version.js';
15
15
  import { IncompleteStreamError, isTransportError } from './transport_errors.js';
16
16
  import { OpenAIResponsesBackend } from './openai_responses.js';
17
+ import { endingRouterRefusal, readRouterRefusal, RouterRefusalError } from './router_refusal.js';
18
+ import { routerAccount, routerRefusalGate } from './router_gate.js';
19
+ import { countRouterRequests } from './router_requests.js';
17
20
  const ZROUTER_HEADERS_TIMEOUT_MS = 90_000;
18
21
  // A process session is descriptive telemetry, never a registered machine identity.
19
22
  const routerClientSession = randomUUID();
@@ -335,9 +338,32 @@ export class ZRouterStreamBackend {
335
338
  const composed = [this.conversationId, ...decorations].join(':');
336
339
  return composed.length <= ROUTER_PIN_MAX_LENGTH ? composed : this.conversationId;
337
340
  }
341
+ /**
342
+ * What the process gate keys this request by. A host's token provider rotates short-lived tokens, so its account is
343
+ * the host-selected workspace; a fixed key is its own fingerprint.
344
+ */
345
+ gateTarget(request) {
346
+ return { route: this.proxyUrl, provider: this.provider, model: request.model,
347
+ account: this.authTokenProvider ? `host:${this.workspaceId ?? ''}` : routerAccount(this.apiKey) };
348
+ }
338
349
  generate(request) {
339
350
  const routedRequest = withTransportTurn(request);
340
- return measureResponse(routedRequest, fetcher => this.generateResponse(routedRequest, fetcher));
351
+ return measureResponse(routedRequest, async (fetcher) => {
352
+ const target = this.gateTarget(routedRequest);
353
+ const held = routerRefusalGate.admit(target, { person: routedRequest.personInitiated === true });
354
+ if (held)
355
+ throw held;
356
+ try {
357
+ const response = await this.generateResponse(routedRequest, countRouterRequests(fetcher));
358
+ routerRefusalGate.succeed(target);
359
+ return response;
360
+ }
361
+ catch (error) {
362
+ if (error instanceof RouterRefusalError)
363
+ routerRefusalGate.refuse(target, error);
364
+ throw error;
365
+ }
366
+ });
341
367
  }
342
368
  async generateResponse(request, fetcher) {
343
369
  if (this.usesNativeResponses(request)) {
@@ -345,6 +371,9 @@ export class ZRouterStreamBackend {
345
371
  try {
346
372
  return await native.backend.generate(native.request);
347
373
  }
374
+ catch (error) {
375
+ throw nativeRouterFailure(error);
376
+ }
348
377
  finally {
349
378
  native.dispose();
350
379
  }
@@ -366,11 +395,7 @@ export class ZRouterStreamBackend {
366
395
  });
367
396
  if (!response.ok) {
368
397
  const failure = await readHttpErrorBody(response, request.signal);
369
- const error = new BackendHttpError(response.status, failure.body, { prefix: 'ZRouter API', headers,
370
- bodyReadState: failure.bodyReadState, retryAfter: response.headers.get('retry-after'),
371
- rateLimitReset: response.headers.get('x-ratelimit-reset') });
372
- error.message += failureHeaderSuffix(response);
373
- throw error;
398
+ throw routerFailure(response.status, failure.body, { headers, response, bodyReadState: failure.bodyReadState });
374
399
  }
375
400
  const data = await response.json();
376
401
  const parsed = this.parseOpenAIResponse(data);
@@ -419,7 +444,29 @@ export class ZRouterStreamBackend {
419
444
  }
420
445
  generateStream(request) {
421
446
  const routedRequest = withTransportTurn(request);
422
- return measureStream(routedRequest, fetcher => this.streamResponse(routedRequest, fetcher));
447
+ return measureStream(routedRequest, fetcher => this.gatedStream(routedRequest, fetcher));
448
+ }
449
+ /** A stream the process gate admits; Router answering with output clears whatever held it. */
450
+ async *gatedStream(request, fetcher) {
451
+ const target = this.gateTarget(request);
452
+ const held = routerRefusalGate.admit(target, { person: request.personInitiated === true });
453
+ if (held)
454
+ throw held;
455
+ let answered = false;
456
+ try {
457
+ for await (const event of this.streamResponse(request, countRouterRequests(fetcher))) {
458
+ if (!answered && event.type !== 'heartbeat') {
459
+ answered = true;
460
+ routerRefusalGate.succeed(target);
461
+ }
462
+ yield event;
463
+ }
464
+ }
465
+ catch (error) {
466
+ if (error instanceof RouterRefusalError)
467
+ routerRefusalGate.refuse(target, error);
468
+ throw error;
469
+ }
423
470
  }
424
471
  async *streamResponse(request, fetcher) {
425
472
  if (this.usesNativeResponses(request)) {
@@ -427,6 +474,9 @@ export class ZRouterStreamBackend {
427
474
  try {
428
475
  yield* native.backend.generateStream(native.request);
429
476
  }
477
+ catch (error) {
478
+ throw nativeRouterFailure(error);
479
+ }
430
480
  finally {
431
481
  native.dispose();
432
482
  }
@@ -458,11 +508,7 @@ export class ZRouterStreamBackend {
458
508
  }, Math.min(ZROUTER_HEADERS_TIMEOUT_MS, Math.max(1, remaining())));
459
509
  if (!response.ok) {
460
510
  const failure = await readHttpErrorBody(response, request.signal);
461
- const error = new BackendHttpError(response.status, routerErrorFrameBody(failure.body), { prefix: 'ZRouter API', headers,
462
- bodyReadState: failure.bodyReadState, retryAfter: response.headers.get('retry-after'),
463
- rateLimitReset: response.headers.get('x-ratelimit-reset') });
464
- error.message += failureHeaderSuffix(response);
465
- throw error;
511
+ throw routerFailure(response.status, routerErrorFrameBody(failure.body), { headers, response, bodyReadState: failure.bodyReadState });
466
512
  }
467
513
  if (!response.body) {
468
514
  throw new Error('ZRouter API error: no response body for streaming request');
@@ -491,7 +537,7 @@ export class ZRouterStreamBackend {
491
537
  ? suppliedStatus
492
538
  : 502;
493
539
  routerTurnEnded = true;
494
- throw new BackendHttpError(status, JSON.stringify(ev.body ?? {}), { prefix: 'ZRouter API', headers });
540
+ throw routerFailure(status, JSON.stringify(ev.body ?? {}), { headers, turnEnded: true });
495
541
  }
496
542
  const mapped = mapEvent(ev);
497
543
  if (this.getModelCapabilities(request.model)?.tools === false && mapped.some(event => event.type.startsWith('tool_use'))) {
@@ -521,7 +567,8 @@ export class ZRouterStreamBackend {
521
567
  // emitted output. So a transient HTTP failure on a resume (the Router's
522
568
  // coordination 503 while its shared store blips, a gateway 502/504) is
523
569
  // retryable here, not just a raw socket error.
524
- const retryable = !routerTurnEnded && (error instanceof BackendHttpError
570
+ // A refusal is never resumed: Router would only refuse it again.
571
+ const retryable = !routerTurnEnded && !(error instanceof RouterRefusalError) && (error instanceof BackendHttpError
525
572
  ? resumeAfter !== undefined && isRetryableResumeStatus(error)
526
573
  : isTransportError(error));
527
574
  if (request.signal?.aborted
@@ -621,6 +668,40 @@ function failureHeaderSuffix(response) {
621
668
  }
622
669
  return parts.length > 0 ? ` [${parts.join(' ')}]` : '';
623
670
  }
671
+ /**
672
+ * The error a failed Router response, or a router_error frame, throws. A lasting refusal (a spending, token or access
673
+ * limit, the monthly quota, a platform key out of credit, the platform proxy's own quota) or a provider cooldown
674
+ * longer than a turn waits becomes a RouterRefusalError, which nothing retries. Any other failure stays a
675
+ * BackendHttpError, carrying the wait a refusal's body names when no Retry-After header did: the platform proxy drops
676
+ * Router's headers, and a frame has none.
677
+ */
678
+ function routerFailure(status, body, options) {
679
+ const header = options.response?.headers.get('retry-after') ?? null;
680
+ const httpError = (retryAfter) => {
681
+ const error = new BackendHttpError(status, body, { prefix: 'ZRouter API', headers: options.headers, bodyReadState: options.bodyReadState,
682
+ retryAfter, rateLimitReset: options.response?.headers.get('x-ratelimit-reset'), turnEnded: options.turnEnded });
683
+ if (options.response)
684
+ error.message += failureHeaderSuffix(options.response);
685
+ return error;
686
+ };
687
+ const error = httpError(header);
688
+ // Read from the redacted body: only its fixed fields and cleaned sentence are used.
689
+ const refusal = readRouterRefusal(error.status, error.body);
690
+ if (!refusal)
691
+ return error;
692
+ const ending = endingRouterRefusal(refusal);
693
+ if (ending)
694
+ return ending;
695
+ return header === null && refusal.retryAfterSeconds !== undefined ? httpError(String(refusal.retryAfterSeconds)) : error;
696
+ }
697
+ /** Router's refusal of a native Responses request, which that transport reports as `API error (NNN): body`. */
698
+ function nativeRouterFailure(error) {
699
+ const failure = error instanceof Error ? /^API error \((\d{3})\): ([\s\S]*)$/.exec(error.message) : null;
700
+ if (!failure)
701
+ return error;
702
+ const converted = routerFailure(Number(failure[1]), failure[2], { headers: {} });
703
+ return converted instanceof RouterRefusalError ? converted : error;
704
+ }
624
705
  /**
625
706
  * A failed streamed turn can answer with an SSE router_error frame instead of a JSON body. Its body is the same error
626
707
  * the stream path reports, so callers read Router's code and message either way: the frame alone left only "Rate
@@ -1,8 +1,13 @@
1
1
  import { collectUsageViews, formatUsageViews } from '../../usage_projection.js';
2
+ import { configStore } from '../../config.js';
3
+ import { formatRouterBudget, readRouterBudget, readRouterStanding } from '../../router_budget.js';
2
4
  export const usageCommand = {
3
- name: 'usage', description: 'Show retained session, project and UTC-day request usage', usage: '/usage',
5
+ name: 'usage', description: 'Show retained session, project and UTC-day request usage, and your Zerg Router limits', usage: '/usage',
4
6
  handler: async (_args, ctx) => {
5
7
  const views = await collectUsageViews(ctx.shell.getCwd(), ctx.getSessionId?.() ?? '', ctx.getUsageSnapshot?.());
6
- ctx.addMessage({ role: 'system', content: formatUsageViews(views) });
8
+ // The person's own limits, read from Router itself with their sign-in; left out when Router does not give them.
9
+ const credential = configStore.getPersonalRouterCredential();
10
+ const [budget, standing] = credential ? await Promise.all([readRouterBudget(credential), readRouterStanding(credential)]) : [null, null];
11
+ ctx.addMessage({ role: 'system', content: [formatUsageViews(views), ...(budget ? [formatRouterBudget(budget, standing)] : [])].join('\n\n') });
7
12
  },
8
13
  };
@@ -922,6 +922,17 @@ export declare class RatatuiApp {
922
922
  * Used by completion (slash / path / @-mention) which operates on plain text.
923
923
  */
924
924
  private setInputToText;
925
+ /**
926
+ * Submit what the person entered themselves (typed, dictated, sent from the browser mirror, or given on the command
927
+ * line). It gets one real attempt even while a Zerg Router refusal holds the route, since they may have just raised
928
+ * the limit.
929
+ */
930
+ private submitPersonInput;
931
+ /**
932
+ * `person`: the person entered this input themselves (see submitPersonInput). A /loop tick, a goal continuation,
933
+ * another pane's or the coordinator's message, a pane's initial task and a queued entry never are, so none of them
934
+ * passes a Zerg Router refusal the process holds.
935
+ */
925
936
  private handleSubmit;
926
937
  /**
927
938
  * Whether a typed message can reach a model, judged by the route the agent
@@ -957,6 +968,18 @@ export declare class RatatuiApp {
957
968
  private showLaunchConnectPrompt;
958
969
  /** Launch notices held until the launch connect flow ends; null when none are held. */
959
970
  private heldLaunchNotices;
971
+ /** The person's Zerg Router budget and standing, read from Router itself; null when unavailable or not theirs. */
972
+ private routerBudget;
973
+ private routerStanding;
974
+ private routerBudgetReadAt;
975
+ private routerStandingTimer;
976
+ /**
977
+ * Read the person's Router budget again, at most once a minute, while this session's model goes through their own
978
+ * Router sign-in. Any failure leaves the status bar without a budget.
979
+ */
980
+ private refreshRouterBudget;
981
+ /** A device's standing (the refusals in force for its person), read now and then once a minute. */
982
+ private startRouterStandingPoll;
960
983
  /** Show a launch notice (saved work, a task handoff), or hold it while the launch choice runs. */
961
984
  private showLaunchNotice;
962
985
  private releaseLaunchNotices;
@@ -56,6 +56,8 @@ import { computeLayout } from './ui/core/layout_yoga.js';
56
56
  import { frameTextLines } from './ui/core/frame_text.js';
57
57
  import { formatTranscriptTime } from './ui/core/time_format.js';
58
58
  import { buildStatusBarView } from './ui/views/status_bar.js';
59
+ import { adoptRouterRefusalRecord, formatRecordedRouterRefusal } from './agent/backends/router_refusal_record.js';
60
+ import { personalRouterRoute, readRouterBudget, readRouterStanding, routerStatusBudget } from './router_budget.js';
59
61
  import { compactStatusLineVariants, resolveStatusLineSettings, statusLineSettingsForStorage } from './ui/status_line_config.js';
60
62
  import { createAppController, MAX_QUEUE } from './app/controller.js';
61
63
  import { queueEditIndexAfterRemoval, queueEditNavigationTarget, } from './app/queue_edit.js';
@@ -108,7 +110,7 @@ import { generateSessionId, bindToolResponseStoreToSession, findRecentSessionSum
108
110
  import { awaitStartupGitSnapshot, getRuntimeInfo, getStartupGitSnapshot } from './runtime_info.js';
109
111
  import { ContextOverflowError, isContextOverflowMessage } from './agent/agent.js';
110
112
  import { dumpContextOverflow } from './agent/contextDump.js';
111
- import { createMirrorStreamServer, startMirrorStreamServer, stopMirrorStreamServer, } from './web/mirror_stream.js';
113
+ import { BROWSER_BUS_MEMBER_ID, createMirrorStreamServer, startMirrorStreamServer, stopMirrorStreamServer, } from './web/mirror_stream.js';
112
114
  import { initMirrorClient } from './web/mirror_client.js';
113
115
  import { PaneRelayServer, PaneRelayClient, generateRelaySocketPath } from './ui/ratatui/pane_relay.js';
114
116
  import { perfBeginKeystroke, perfStage, perfEndKeystroke } from './debug/perf_trace.js';
@@ -1485,7 +1487,7 @@ export class RatatuiApp {
1485
1487
  // Handle input from browser mirror (single-pane mode fallback)
1486
1488
  this.mirrorServer.onInput((input) => {
1487
1489
  debugLog(`[Mirror] Received input from browser: length=${input.text.length}`);
1488
- this.handleSubmit(input);
1490
+ this.submitPersonInput(input);
1489
1491
  });
1490
1492
  this.mirrorServer.onCancel((paneId) => {
1491
1493
  debugLog(`[Mirror] Cancel requested from browser: pane=${paneId}`);
@@ -3324,7 +3326,7 @@ export class RatatuiApp {
3324
3326
  }
3325
3327
  this.mirrorServer.onInput((input) => {
3326
3328
  debugLog(`[Mirror] Received input from browser: length=${input.text.length}`);
3327
- this.handleSubmit(input);
3329
+ this.submitPersonInput(input);
3328
3330
  });
3329
3331
  this.mirrorServer.onCancel((paneId) => {
3330
3332
  debugLog(`[Mirror] Cancel requested from browser: pane=${paneId}`);
@@ -3459,7 +3461,7 @@ export class RatatuiApp {
3459
3461
  const filtered = this.dictationFilterModule?.maybeFilterFillers(event.content) ?? event.content;
3460
3462
  if (filtered.trim()) {
3461
3463
  // Submit the transcribed text directly
3462
- this.handleSubmit(filtered.trim());
3464
+ this.submitPersonInput(filtered.trim());
3463
3465
  }
3464
3466
  }
3465
3467
  break;
@@ -3627,7 +3629,7 @@ export class RatatuiApp {
3627
3629
  if (result.text) {
3628
3630
  const filtered = dictation.filter.maybeFilterFillers(result.text);
3629
3631
  if (filtered.trim()) {
3630
- this.handleSubmit(filtered.trim());
3632
+ this.submitPersonInput(filtered.trim());
3631
3633
  }
3632
3634
  }
3633
3635
  }
@@ -4510,6 +4512,9 @@ export class RatatuiApp {
4510
4512
  // only the readout's Recent line, which points to /resume.
4511
4513
  if (this.launchConnectPromptWanted() && !this.composerHasDraft())
4512
4514
  this.heldLaunchNotices = [];
4515
+ // A refusal an unattended run recorded holds this session's background work; the person's messages still try.
4516
+ for (const hold of adoptRouterRefusalRecord('interactive'))
4517
+ this.showLaunchNotice(formatRecordedRouterRefusal(hold));
4513
4518
  if (this.taskHandoff) {
4514
4519
  this.showLaunchNotice(formatTaskHandoffNotice(this.taskHandoff.snapshot));
4515
4520
  this.publishTaskHandoff(this.taskHandoff);
@@ -4538,6 +4543,8 @@ export class RatatuiApp {
4538
4543
  this.stopFollowingLogin ??= onZergAILoginWaitChange(() => { this.refreshConnectedState(); this.render(); });
4539
4544
  this.refreshConnectedState();
4540
4545
  this.resolveStartupReady();
4546
+ this.refreshRouterBudget(true);
4547
+ this.startRouterStandingPoll();
4541
4548
  // Ask how to connect until the user logs in with ZergAI or chooses local
4542
4549
  // API keys, and again when a ZergAI login expired (askHowToConnectAtLaunch).
4543
4550
  // Only a person at a terminal or in the desktop app is asked: automated
@@ -4962,7 +4969,7 @@ export class RatatuiApp {
4962
4969
  else if (this.initialPrompt && this.initialPrompt.trim()) {
4963
4970
  const prompt = this.initialPrompt;
4964
4971
  setTimeout(() => {
4965
- void this.handleSubmit(prompt);
4972
+ void this.submitPersonInput(prompt);
4966
4973
  }, 0);
4967
4974
  }
4968
4975
  // `ztc resume` with no target opens the picker instead of silently taking
@@ -7198,7 +7205,7 @@ export class RatatuiApp {
7198
7205
  if (selection.text !== undefined) {
7199
7206
  if (selection.submit && !this.queueEdit) {
7200
7207
  this.clearComposerAfterSubmit(selection.text);
7201
- void this.handleSubmit(selection.text);
7208
+ void this.submitPersonInput(selection.text);
7202
7209
  }
7203
7210
  else {
7204
7211
  this.setInputToText(selection.text, selection.text.length);
@@ -7342,7 +7349,7 @@ export class RatatuiApp {
7342
7349
  const capturedInput = serializeMessageInput(this.inputState.segments);
7343
7350
  if (isMeaningfulUserInput(capturedInput.text) || capturedInput.attachments.length > 0) {
7344
7351
  this.clearComposerAfterSubmit(plainText);
7345
- this.handleSubmit(capturedInput);
7352
+ this.submitPersonInput(capturedInput);
7346
7353
  }
7347
7354
  else {
7348
7355
  this.controller.setInputState(this.inputState);
@@ -8439,8 +8446,9 @@ export class RatatuiApp {
8439
8446
  approxTokens,
8440
8447
  }));
8441
8448
  }
8442
- // From browser user — treat as normal user input
8443
- this.handleSubmit({ text: msg.text, attachments: msg.attachments || [] });
8449
+ // Normal input. Only the person in the browser mirror speaks as "User"; another pane or the coordinator is not
8450
+ // the person, so its message never takes their attempt past a Zerg Router refusal.
8451
+ this.handleSubmit({ text: msg.text, attachments: msg.attachments || [] }, undefined, undefined, false, false, msg.from.id === BROWSER_BUS_MEMBER_ID);
8444
8452
  }
8445
8453
  else if (msg.type === 'ztc_message') {
8446
8454
  // Intercept structured control commands from parent (model hot-swap, widget answers).
@@ -8583,7 +8591,20 @@ export class RatatuiApp {
8583
8591
  };
8584
8592
  this.controller.setInputState(this.inputState);
8585
8593
  }
8586
- async handleSubmit(rawInput, queuedEntryId, queuedAdmission, literalInput = false, credentialPrompted = false) {
8594
+ /**
8595
+ * Submit what the person entered themselves (typed, dictated, sent from the browser mirror, or given on the command
8596
+ * line). It gets one real attempt even while a Zerg Router refusal holds the route, since they may have just raised
8597
+ * the limit.
8598
+ */
8599
+ submitPersonInput(rawInput) {
8600
+ return this.handleSubmit(rawInput, undefined, undefined, false, false, true);
8601
+ }
8602
+ /**
8603
+ * `person`: the person entered this input themselves (see submitPersonInput). A /loop tick, a goal continuation,
8604
+ * another pane's or the coordinator's message, a pane's initial task and a queued entry never are, so none of them
8605
+ * passes a Zerg Router refusal the process holds.
8606
+ */
8607
+ async handleSubmit(rawInput, queuedEntryId, queuedAdmission, literalInput = false, credentialPrompted = false, person = false) {
8587
8608
  if (this.exiting)
8588
8609
  return;
8589
8610
  const input = parseStructuredSubmitInput(rawInput);
@@ -8697,7 +8718,7 @@ export class RatatuiApp {
8697
8718
  const sendRoute = this.resolveSendRoute();
8698
8719
  if (!sendRoute.ready) {
8699
8720
  if (!credentialPrompted && sendRoute.route
8700
- && this.askForSendCredential(sendRoute.route, input, queuedEntryId, literalInput))
8721
+ && this.askForSendCredential(sendRoute.route, input, queuedEntryId, literalInput, person))
8701
8722
  return;
8702
8723
  this.controller.addMessage({
8703
8724
  role: 'user',
@@ -8774,6 +8795,9 @@ export class RatatuiApp {
8774
8795
  // Publish user message to observer (with attachments so thumbnails survive a refresh).
8775
8796
  this.mirror?.publishMessage('user', text, attachments.length > 0 ? { attachments } : undefined);
8776
8797
  queuedAdmission?.onQueuedAdmission();
8798
+ // A message the person just entered gets one real attempt even while Zerg Router's refusal holds the route.
8799
+ if (person)
8800
+ this.agent.admitPersonRequest();
8777
8801
  // Run the agent on current messages
8778
8802
  await this.runAgent();
8779
8803
  }
@@ -8854,6 +8878,60 @@ export class RatatuiApp {
8854
8878
  }
8855
8879
  /** Launch notices held until the launch connect flow ends; null when none are held. */
8856
8880
  heldLaunchNotices = null;
8881
+ /** The person's Zerg Router budget and standing, read from Router itself; null when unavailable or not theirs. */
8882
+ routerBudget = null;
8883
+ routerStanding = null;
8884
+ routerBudgetReadAt = 0;
8885
+ routerStandingTimer = null;
8886
+ /**
8887
+ * Read the person's Router budget again, at most once a minute, while this session's model goes through their own
8888
+ * Router sign-in. Any failure leaves the status bar without a budget.
8889
+ */
8890
+ refreshRouterBudget(force = false) {
8891
+ const credential = personalRouterRoute();
8892
+ if (!credential) {
8893
+ if (this.routerBudget || this.routerStanding) {
8894
+ this.routerBudget = null;
8895
+ this.routerStanding = null;
8896
+ this.render();
8897
+ }
8898
+ return;
8899
+ }
8900
+ const now = Date.now();
8901
+ if (!force && now - this.routerBudgetReadAt < 60_000)
8902
+ return;
8903
+ this.routerBudgetReadAt = now;
8904
+ void readRouterBudget(credential).then(budget => {
8905
+ if (this.exiting)
8906
+ return;
8907
+ this.routerBudget = budget;
8908
+ this.render();
8909
+ });
8910
+ }
8911
+ /** A device's standing (the refusals in force for its person), read now and then once a minute. */
8912
+ startRouterStandingPoll() {
8913
+ if (this.routerStandingTimer)
8914
+ return;
8915
+ const poll = () => {
8916
+ const credential = personalRouterRoute();
8917
+ if (!credential) {
8918
+ if (this.routerStanding) {
8919
+ this.routerStanding = null;
8920
+ this.render();
8921
+ }
8922
+ return;
8923
+ }
8924
+ void readRouterStanding(credential).then(standing => {
8925
+ if (this.exiting)
8926
+ return;
8927
+ this.routerStanding = standing;
8928
+ this.render();
8929
+ });
8930
+ };
8931
+ poll();
8932
+ this.routerStandingTimer = setInterval(poll, 60_000);
8933
+ this.routerStandingTimer.unref?.();
8934
+ }
8857
8935
  /** Show a launch notice (saved work, a task handoff), or hold it while the launch choice runs. */
8858
8936
  showLaunchNotice(text) {
8859
8937
  if (this.heldLaunchNotices) {
@@ -8875,14 +8953,14 @@ export class RatatuiApp {
8875
8953
  * terminal or its mirror asks: queued input and pane children keep the setup
8876
8954
  * message, and an open widget is never replaced.
8877
8955
  */
8878
- askForSendCredential(route, input, queuedEntryId, literalInput) {
8956
+ askForSendCredential(route, input, queuedEntryId, literalInput, person) {
8879
8957
  if (queuedEntryId || this.paneMode || this.routingInteractionOccupied())
8880
8958
  return false;
8881
8959
  const ctx = this.buildCommandContext(message => this.controller.addMessage(message));
8882
8960
  return promptForMissingDirectKey(route, ctx, async () => {
8883
8961
  // A live agent was built without this key; the send builds a fresh one.
8884
8962
  this.reloadAgentInPlace(true);
8885
- await this.handleSubmit(input, undefined, undefined, literalInput, true);
8963
+ await this.handleSubmit(input, undefined, undefined, literalInput, true, person);
8886
8964
  }, {
8887
8965
  onCancel: () => {
8888
8966
  this.restoreBusyDraft(input);
@@ -9544,6 +9622,9 @@ export class RatatuiApp {
9544
9622
  if (!this.exiting && !this.isHostedRuntime()) {
9545
9623
  await this.localWorkspace().setActivity(this.workspacePaused ? 'paused' : 'idle');
9546
9624
  }
9625
+ // A turn spends budget: read it again (at most once a minute).
9626
+ if (!this.exiting)
9627
+ this.refreshRouterBudget();
9547
9628
  this.dispatchPendingAgentWork();
9548
9629
  }
9549
9630
  }
@@ -10841,7 +10922,7 @@ export class RatatuiApp {
10841
10922
  // handoff. A key command must never be kept, so it runs now, as Enter would.
10842
10923
  if (redactCredentialCommand(capturedInput.text) !== capturedInput.text) {
10843
10924
  this.clearComposerAfterSubmit(plainText);
10844
- void this.handleSubmit(capturedInput);
10925
+ void this.submitPersonInput(capturedInput);
10845
10926
  return;
10846
10927
  }
10847
10928
  if (this.controller.getQueue().length + this.handoffQueueReservedSlots >= MAX_QUEUE) {
@@ -12669,6 +12750,7 @@ export class RatatuiApp {
12669
12750
  // Auth info
12670
12751
  authEmail: configStore.isAuthenticated() ? configStore.get().auth?.email : undefined,
12671
12752
  authWorkspace: configStore.getActiveWorkspace()?.name,
12753
+ routerBudget: routerStatusBudget(this.routerBudget, this.routerStanding),
12672
12754
  backgroundRunning: getBackgroundRegistry()?.getRunningCount() ?? 0,
12673
12755
  // Full texts: the panel windows them so an edited entry stays visible.
12674
12756
  queuePreview: state.queue.map(formatQueuedMessagePreview),
@@ -13386,6 +13468,10 @@ export class RatatuiApp {
13386
13468
  clearInterval(this.intakePollTimer);
13387
13469
  this.intakePollTimer = null;
13388
13470
  }
13471
+ if (this.routerStandingTimer) {
13472
+ clearInterval(this.routerStandingTimer);
13473
+ this.routerStandingTimer = null;
13474
+ }
13389
13475
  const stoppedAt = Date.now();
13390
13476
  this.controller.setMessages(this.controller.getState().messages.map(message => message.turn && message.turn.finishedAt === undefined
13391
13477
  ? { ...message, turn: { ...message.turn, finishedAt: stoppedAt } } : message));
@@ -13786,6 +13872,7 @@ export class RatatuiApp {
13786
13872
  mode: state.mode,
13787
13873
  authEmail: configStore.isAuthenticated() ? configStore.get().auth?.email : undefined,
13788
13874
  authWorkspace: configStore.getActiveWorkspace()?.name,
13875
+ routerBudget: routerStatusBudget(this.routerBudget, this.routerStanding),
13789
13876
  backgroundRunning: getBackgroundRegistry()?.getRunningCount() ?? 0,
13790
13877
  queueTotal: state.queue.length,
13791
13878
  cols: width,
package/dist/config.d.ts CHANGED
@@ -254,6 +254,14 @@ export declare class ConfigStore {
254
254
  routerOrigin?: string;
255
255
  configProfile?: string;
256
256
  }): void;
257
+ /**
258
+ * The person's own Zerg Router credential: this profile's Router sign-in (a CLI device key), while it is valid. The
259
+ * legacy platform login is not one: it is the platform's, scoped to its /api/zrouter proxy.
260
+ */
261
+ getPersonalRouterCredential(): {
262
+ origin: string;
263
+ token: string;
264
+ } | undefined;
257
265
  getRouterCatalogConnection(destination?: string | undefined): RouterCatalogConnection | undefined;
258
266
  /** New children use configured routing, not a parent's restored inference route. */
259
267
  getChildAuthMode(): ZTCAuthMode;
package/dist/config.js CHANGED
@@ -1547,6 +1547,16 @@ export class ConfigStore {
1547
1547
  if (metadata.authMode !== 'direct' && metadata.routerOrigin && !routerOriginFromEnvironment())
1548
1548
  this.sessionOverrides.zergProxyUrl = metadata.routerOrigin;
1549
1549
  }
1550
+ /**
1551
+ * The person's own Zerg Router credential: this profile's Router sign-in (a CLI device key), while it is valid. The
1552
+ * legacy platform login is not one: it is the platform's, scoped to its /api/zrouter proxy.
1553
+ */
1554
+ getPersonalRouterCredential() {
1555
+ const credentials = this.routerCredentials;
1556
+ if (!credentials || this.routerCredentialsError || !(Date.parse(credentials.expiresAt) > Date.now()))
1557
+ return undefined;
1558
+ return { origin: credentials.origin, token: credentials.token };
1559
+ }
1550
1560
  getRouterCatalogConnection(destination = this.get().zergProxyUrl) {
1551
1561
  const origin = normalizedOrigin(destination);
1552
1562
  if (!origin)