@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
@@ -11,6 +11,9 @@
11
11
  */
12
12
  import { configStore } from '../../config.js';
13
13
  import { resolveSimulationInference } from '../inference.js';
14
+ import { routerAccount, routerRefusalGate } from '../../agent/backends/router_gate.js';
15
+ import { endingRouterRefusal, readRouterRefusal } from '../../agent/backends/router_refusal.js';
16
+ import { noteRouterRequest } from '../../agent/backends/router_requests.js';
14
17
  const EMBEDDING_MODEL = 'text-embedding-3-small';
15
18
  /** Fallback zero vector for when embedding API is unavailable (1536 dims for text-embedding-3-small) */
16
19
  const ZERO_VEC = new Array(1536).fill(0);
@@ -22,10 +25,14 @@ export class OpenAIEmbeddingProvider {
22
25
  apiKey;
23
26
  baseUrl;
24
27
  model;
25
- constructor(apiKey, baseUrl = 'https://api.openai.com/v1', model = EMBEDDING_MODEL) {
28
+ /** Set when embeddings go through Zerg Router: its refusals are not retried and hold the process's gate. */
29
+ router;
30
+ constructor(apiKey, baseUrl = 'https://api.openai.com/v1', model = EMBEDDING_MODEL, routerRoute) {
26
31
  this.apiKey = apiKey;
27
32
  this.baseUrl = baseUrl.replace(/\/$/, '');
28
33
  this.model = model;
34
+ if (routerRoute)
35
+ this.router = { route: routerRoute, account: routerAccount(apiKey), provider: 'openai', model };
29
36
  }
30
37
  async embed(text) {
31
38
  const [vec] = await this.embedBatch([text]);
@@ -34,12 +41,17 @@ export class OpenAIEmbeddingProvider {
34
41
  async embedBatch(texts) {
35
42
  if (texts.length === 0)
36
43
  return [];
44
+ const held = this.router && routerRefusalGate.admit(this.router);
45
+ if (held)
46
+ throw held;
37
47
  const MAX_ATTEMPTS = 4;
38
48
  for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
39
49
  // T1: AbortController with 15s timeout prevents hung API calls from blocking forever
40
50
  const controller = new AbortController();
41
51
  const timeout = setTimeout(() => controller.abort(), 15_000);
42
52
  let response;
53
+ if (this.router)
54
+ noteRouterRequest();
43
55
  try {
44
56
  response = await fetch(`${this.baseUrl}/embeddings`, {
45
57
  method: 'POST',
@@ -56,8 +68,27 @@ export class OpenAIEmbeddingProvider {
56
68
  }
57
69
  if (response.ok) {
58
70
  const data = (await response.json());
71
+ if (this.router)
72
+ routerRefusalGate.succeed(this.router);
59
73
  return data.data.sort((a, b) => a.index - b.index).map(d => d.embedding);
60
74
  }
75
+ // Zerg Router refused before calling any provider. A lasting refusal, or a provider cooldown longer than a turn
76
+ // waits, ends the call as it ends a turn, and holds the route; a shorter wait is ridden out.
77
+ if (this.router && (response.status === 403 || response.status === 429)) {
78
+ const body = await response.text().catch(() => '');
79
+ const refusal = readRouterRefusal(response.status, body);
80
+ const ending = refusal && endingRouterRefusal(refusal);
81
+ if (ending) {
82
+ routerRefusalGate.refuse(this.router, ending);
83
+ throw ending;
84
+ }
85
+ if (response.status === 429 && attempt < MAX_ATTEMPTS) {
86
+ const delay = Math.max(1000 * Math.pow(2, attempt - 1) * (0.75 + Math.random() * 0.5), (refusal?.retryAfterSeconds ?? 0) * 1000);
87
+ await new Promise(r => setTimeout(r, delay));
88
+ continue;
89
+ }
90
+ throw new Error(`Embedding API error ${response.status}: ${body.slice(0, 200)}`);
91
+ }
61
92
  // Retry on 429 (rate limit) and 5xx (transient server errors)
62
93
  if ((response.status === 429 || response.status >= 500) && attempt < MAX_ATTEMPTS) {
63
94
  const delay = 1000 * Math.pow(2, attempt - 1) * (0.75 + Math.random() * 0.5);
@@ -160,6 +191,7 @@ export function createEmbeddingProvider(cache, sessionProvider) {
160
191
  const cfg = configStore.get();
161
192
  let apiKey;
162
193
  let baseUrl;
194
+ let routerRoute;
163
195
  let model = inference.embeddingModel ?? EMBEDDING_MODEL;
164
196
  // If a proxy URL is configured and the user is authenticated, route embeddings
165
197
  // through the proxy — same infrastructure the LLM completions use.
@@ -172,6 +204,7 @@ export function createEmbeddingProvider(cache, sessionProvider) {
172
204
  else if (proxyUrl && authToken) {
173
205
  baseUrl = `${proxyUrl}/v1`;
174
206
  apiKey = authToken;
207
+ routerRoute = proxyUrl;
175
208
  }
176
209
  else if (provider === 'openai') {
177
210
  apiKey = configStore.getApiKey('openai');
@@ -188,5 +221,5 @@ export function createEmbeddingProvider(cache, sessionProvider) {
188
221
  throw new Error('OpenAI API key required for embeddings. ' +
189
222
  'Set OPENAI_API_KEY environment variable, or use an OpenAI provider.');
190
223
  }
191
- return new CachedEmbeddingProvider(new OpenAIEmbeddingProvider(apiKey, baseUrl, model), cache);
224
+ return new CachedEmbeddingProvider(new OpenAIEmbeddingProvider(apiKey, baseUrl, model, routerRoute), cache);
192
225
  }
@@ -60,6 +60,8 @@ interface AppViewProps {
60
60
  mode?: AgentMode;
61
61
  authEmail?: string;
62
62
  authWorkspace?: string;
63
+ /** The person's Zerg Router budget in short ("Router $812 / $1,000 week"), when a limit is set. */
64
+ routerBudget?: string;
63
65
  backgroundRunning?: number;
64
66
  queuePreview?: string[];
65
67
  queueTotal?: number;
@@ -113,5 +115,5 @@ export declare function getAppLayoutMetrics({ rows, cols, inputState, commands,
113
115
  widgetHeight: number;
114
116
  transcriptHeight: number;
115
117
  };
116
- export declare function buildAppView({ messages, agentState, inputState, sessionId, sessionName, cols, rows, commands, completion, hasApiKey, version, contextLength, contextEstimated, contextStatus, provider, model, emulationId, inputMode, escapeHint, toast, spinnerLabel, spinnerFrame, lastEventAt, stallHintMs, debug, expandToolOutputs, showThinking, showTurnMetadata, renderer, showHeader, showMessages, isRecording, recordingDevice, audioLevel, partialTranscript, todos, showTodos, activeTask, taskStartedAt, mode, authEmail, authWorkspace, backgroundRunning, widgetContent, widgetView: providedWidgetView, queuePreview, queueTotal, queueSelectedIndex, externalTranscript, transcriptAnchor, compactWidget, transcriptRows, agentActive, statusLine, effort, unsupportedEffort, }: AppViewProps): LayoutNode;
118
+ export declare function buildAppView({ messages, agentState, inputState, sessionId, sessionName, cols, rows, commands, completion, hasApiKey, version, contextLength, contextEstimated, contextStatus, provider, model, emulationId, inputMode, escapeHint, toast, spinnerLabel, spinnerFrame, lastEventAt, stallHintMs, debug, expandToolOutputs, showThinking, showTurnMetadata, renderer, showHeader, showMessages, isRecording, recordingDevice, audioLevel, partialTranscript, todos, showTodos, activeTask, taskStartedAt, mode, authEmail, authWorkspace, routerBudget, backgroundRunning, widgetContent, widgetView: providedWidgetView, queuePreview, queueTotal, queueSelectedIndex, externalTranscript, transcriptAnchor, compactWidget, transcriptRows, agentActive, statusLine, effort, unsupportedEffort, }: AppViewProps): LayoutNode;
117
119
  export {};
@@ -152,7 +152,7 @@ export function getAppLayoutMetrics({ rows, cols, inputState, commands = [], com
152
152
  transcriptHeight,
153
153
  };
154
154
  }
155
- export function buildAppView({ messages, agentState, inputState, sessionId, sessionName, cols, rows, commands, completion, hasApiKey, version = '0.1.0', contextLength, contextEstimated, contextStatus, provider, model, emulationId, inputMode = 'steer', escapeHint, toast, spinnerLabel, spinnerFrame, lastEventAt, stallHintMs, debug = false, expandToolOutputs = false, showThinking = true, showTurnMetadata = true, renderer, showHeader = true, showMessages = true, isRecording = false, recordingDevice, audioLevel = -60, partialTranscript = '', todos = [], showTodos = true, activeTask = null, taskStartedAt = null, mode = 'normal', authEmail, authWorkspace, backgroundRunning = 0, widgetContent = null, widgetView: providedWidgetView = null, queuePreview = [], queueTotal = 0, queueSelectedIndex = null, externalTranscript = false, transcriptAnchor = 'bottom', compactWidget = false, transcriptRows, agentActive = agentState.status === 'thinking'
155
+ export function buildAppView({ messages, agentState, inputState, sessionId, sessionName, cols, rows, commands, completion, hasApiKey, version = '0.1.0', contextLength, contextEstimated, contextStatus, provider, model, emulationId, inputMode = 'steer', escapeHint, toast, spinnerLabel, spinnerFrame, lastEventAt, stallHintMs, debug = false, expandToolOutputs = false, showThinking = true, showTurnMetadata = true, renderer, showHeader = true, showMessages = true, isRecording = false, recordingDevice, audioLevel = -60, partialTranscript = '', todos = [], showTodos = true, activeTask = null, taskStartedAt = null, mode = 'normal', authEmail, authWorkspace, routerBudget, backgroundRunning = 0, widgetContent = null, widgetView: providedWidgetView = null, queuePreview = [], queueTotal = 0, queueSelectedIndex = null, externalTranscript = false, transcriptAnchor = 'bottom', compactWidget = false, transcriptRows, agentActive = agentState.status === 'thinking'
156
156
  || agentState.status === 'streaming'
157
157
  || agentState.status === 'tool_use', statusLine, effort, unsupportedEffort, }) {
158
158
  // A compact widget (the question form) sizes to its own content. Deriving the
@@ -294,6 +294,7 @@ export function buildAppView({ messages, agentState, inputState, sessionId, sess
294
294
  mode,
295
295
  authEmail,
296
296
  authWorkspace,
297
+ routerBudget,
297
298
  backgroundRunning,
298
299
  queueTotal,
299
300
  cols,
@@ -29,6 +29,8 @@ interface StatusBarProps {
29
29
  mode?: AgentMode;
30
30
  authEmail?: string;
31
31
  authWorkspace?: string;
32
+ /** The person's Zerg Router budget in short, or that Router is refusing them now. */
33
+ routerBudget?: string;
32
34
  backgroundRunning?: number;
33
35
  queueTotal?: number;
34
36
  cols?: number;
@@ -328,6 +328,11 @@ export function buildStatusBarView(rawProps) {
328
328
  let right = settings.right
329
329
  .map(item => statusItemSegment(item, props, settings.variants[item]))
330
330
  .filter((segment) => segment !== null);
331
+ if (props.routerBudget) {
332
+ // Gives way before the model and context fields when the line is narrow.
333
+ right.unshift({ value: ellipsize(props.routerBudget, 40), priority: 50,
334
+ color: /^Router limit reached/.test(props.routerBudget) ? TERMINAL_THEME.attention : TERMINAL_THEME.muted });
335
+ }
331
336
  if (props.escapeHint) {
332
337
  right.push({ value: props.escapeHint, color: TERMINAL_THEME.muted, priority: 900, protected: true });
333
338
  }
@@ -13,6 +13,8 @@ import { type PaneStateUpdate } from './pane_registry.js';
13
13
  import { type WorkspaceRuntimeSnapshot, type WorkspaceTodo } from '../workspace_runtime.js';
14
14
  import type { UsageSnapshot } from '../usage_snapshot.js';
15
15
  import { type AccountOpResult } from './accounts_mirror.js';
16
+ /** The bus member a person in the browser mirror speaks as ("User"); panes and the coordinator are 0 and up. */
17
+ export declare const BROWSER_BUS_MEMBER_ID = -1;
16
18
  export type MirrorEventType = 'message' | 'stream_start' | 'reasoning_delta' | 'stream_delta' | 'stream_end' | 'tool_call' | 'tool_result' | 'status' | 'token_usage' | 'error' | 'cancel' | 'mode_change' | 'pane_info' | 'pane_output' | 'zde_lite_state' | 'session_end' | 'reload' | 'clear' | 'todo_list' | 'prompt_entry' | 'ask_user' | 'queue_state' | 'command_pane' | 'command_jobs' | 'evidence' | 'goal' | 'task_handoff' | 'accounts' | 'open_accounts' | 'hook_approval_request' | 'widget_prompt' | 'widget_select' | 'widget_questionnaire' | 'widget_dismiss' | 'widget_settings' | 'context_progress_bar_config' | 'zlicky_cursor' | 'zlicky_highlight' | 'zlicky_clear' | 'zlicky_status' | 'zlicky_capture_request' | 'cv_run_start' | 'cv_run_tick' | 'cv_run_end' | 'cv_diagnose_start' | 'cv_diagnose_classification' | 'cv_diagnose_proposal' | 'cv_diagnose_pr_opened' | 'cv_diagnose_end' | (string & {});
17
19
  export interface MirrorEvent {
18
20
  type: MirrorEventType;
@@ -59,7 +59,8 @@ const MAX_INTERNAL_TOOL_RESULT_BYTES = 12 * 1024 * 1024;
59
59
  const MAX_INTERNAL_TOOL_CONTENT_ITEMS = 16;
60
60
  const MAX_INTERNAL_TOOL_IMAGES = 4;
61
61
  const MIRROR_MEDIA_TTL_MS = 24 * 60 * 60 * 1000;
62
- const BROWSER_BUS_MEMBER_ID = -1;
62
+ /** The bus member a person in the browser mirror speaks as ("User"); panes and the coordinator are 0 and up. */
63
+ export const BROWSER_BUS_MEMBER_ID = -1;
63
64
  const MIN_PANE_BUS_MEMBER_ID = 0;
64
65
  const MAX_BUS_MEMBER_ID = 100_000;
65
66
  const MAX_BUS_QUEUE_TARGETS = 256;