@zergai/ztc 0.22.0-beta.1 → 0.23.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/dist/headless.js CHANGED
@@ -39,7 +39,7 @@ import { routerAccount, routerRefusalGate } from './agent/backends/router_gate.j
39
39
  import { onRouterRequestBurst, routerRequestsThisRun } from './agent/backends/router_requests.js';
40
40
  import { personalRouterRoute, readRouterBudget, routerBudgetLine } from './router_budget.js';
41
41
  import { registerInstance, deregisterInstance } from './instance_registry.js';
42
- import { ContextOverflowError, isContextOverflowMessage } from './agent/agent.js';
42
+ import { ContextOverflowError, isContextOverflowMessage, StreamLostError } from './agent/agent.js';
43
43
  import { dumpContextOverflow } from './agent/contextDump.js';
44
44
  import { registerToolCallbacks } from './app/tool_callbacks.js';
45
45
  import { createAgentWithConfig } from './app/agent_runner.js';
@@ -425,6 +425,7 @@ export class HeadlessApp {
425
425
  batchEventUnsub = null;
426
426
  batchFailed = false;
427
427
  hadHeadlessError = false;
428
+ turnUsageReceipts = [];
428
429
  /** Zerg Router's words for the last refusal that ended a turn; the run exits HEADLESS_EXIT_ROUTER_REFUSED. */
429
430
  routerRefusal = null;
430
431
  /** The turn now running ended on a Router refusal: the goal and Voyager loops stop on it. */
@@ -742,6 +743,7 @@ export class HeadlessApp {
742
743
  this.activityState = applyAgentEventToState(this.activityState, event);
743
744
  switch (event.type) {
744
745
  case 'request_usage':
746
+ this.turnUsageReceipts.push(event.receipt);
745
747
  this.output({ type: 'request_usage', timestamp: new Date().toISOString(), data: { session_id: this.sessionId, receipt: event.receipt } });
746
748
  this.autoMirror?.publish({ type: 'request_usage', data: { sessionId: this.sessionId, receipt: event.receipt } });
747
749
  break;
@@ -2421,6 +2423,7 @@ export class HeadlessApp {
2421
2423
  return;
2422
2424
  }
2423
2425
  this.promptTurn += 1;
2426
+ this.turnUsageReceipts = [];
2424
2427
  // A schema-bound prompt always takes the validated agent path below.
2425
2428
  const triggeredWorkflow = !this.options.closedExtensions && !this.outputSchema && this.workflowToolAvailableInCurrentMode()
2426
2429
  && workflowsEnabled(configStore.get()) && workflowNaturalLanguageTriggerEnabled(configStore.get())
@@ -2657,6 +2660,55 @@ export class HeadlessApp {
2657
2660
  }
2658
2661
  }
2659
2662
  }
2663
+ if (err instanceof StreamLostError) {
2664
+ this.hadHeadlessError = true;
2665
+ let reportedInputTokens = 0;
2666
+ let reportedOutputTokens = 0;
2667
+ let reportedTotalTokens = 0;
2668
+ let reportedRequests = 0;
2669
+ for (const receipt of this.turnUsageReceipts) {
2670
+ if (receipt.source !== 'reported' || receipt.usage === null)
2671
+ continue;
2672
+ reportedRequests += 1;
2673
+ reportedInputTokens += receipt.usage.inputTokens;
2674
+ reportedOutputTokens += receipt.usage.outputTokens;
2675
+ reportedTotalTokens += receipt.usage.totalTokens;
2676
+ }
2677
+ const unavailableUsage = this.turnUsageReceipts.filter(receipt => receipt.source === 'unavailable').length;
2678
+ // Requests the provider answered without usage carry ZTC's estimate: neither reported nor unknown.
2679
+ const estimatedUsage = this.turnUsageReceipts.filter(receipt => receipt.source === 'estimated').length;
2680
+ this.output({
2681
+ type: 'status',
2682
+ timestamp: new Date().toISOString(),
2683
+ data: {
2684
+ status: 'interrupted',
2685
+ resumable: true,
2686
+ reason: err.message,
2687
+ usage: reportedRequests > 0
2688
+ ? { inputTokens: reportedInputTokens, outputTokens: reportedOutputTokens, totalTokens: reportedTotalTokens }
2689
+ : null,
2690
+ usage_unavailable: unavailableUsage,
2691
+ usage_estimated: estimatedUsage
2692
+ }
2693
+ });
2694
+ if (err.partialMessage.trim()) {
2695
+ this.lastResponse = err.partialMessage;
2696
+ this.output({
2697
+ type: 'message',
2698
+ timestamp: new Date().toISOString(),
2699
+ data: { role: 'assistant', content: err.partialMessage }
2700
+ });
2701
+ if (!this.outputSchema)
2702
+ await this.writeFinalOutputFile(err.partialMessage);
2703
+ }
2704
+ this.output({
2705
+ type: 'error',
2706
+ timestamp: new Date().toISOString(),
2707
+ data: { message, code: err.code, ...this.noteRouterRefusal(err, message) }
2708
+ });
2709
+ await this.saveCurrentSession();
2710
+ break;
2711
+ }
2660
2712
  // Either not a retryable error, or we've exhausted retries
2661
2713
  this.hadHeadlessError = true;
2662
2714
  this.output({
@@ -19,7 +19,7 @@ import { randomUUID } from 'node:crypto';
19
19
  import { Server } from '@modelcontextprotocol/sdk/server/index.js';
20
20
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
21
21
  import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
22
- import { childZtcPaneEnv, closeTerminalPaneTool, listWorkspacePanes, readTerminalPaneTool, setPaneToolsOwnId, setPaneToolsTuiProcess, waitForPaneCreatedOrError, writeTerminalPaneTool, } from '../agent/tools/pane.js';
22
+ import { agentZtcPaneEnv, closeTerminalPaneTool, listWorkspacePanes, readTerminalPaneTool, setPaneToolsOwnId, setPaneToolsTuiProcess, waitForPaneCreatedOrError, writeTerminalPaneTool, } from '../agent/tools/pane.js';
23
23
  import { AGENT_CLIS, findAgentCli, nextPaneTitle, workspaceMcpProgram } from '../panes/agent_cli.js';
24
24
  import { TYPED_ENTER_DELAY_MS, formatAgentPaneMessage, openAgentPane } from '../panes/agent_panes.js';
25
25
  import { sessionNamePaneTitle } from '../panes/labels.js';
@@ -234,7 +234,8 @@ export function createWorkspaceMcpServer(options) {
234
234
  ...(placement.direction ? { direction: placement.direction, ratio: 0.5 } : {}),
235
235
  ...(placement.target !== undefined ? { target: placement.target } : {}),
236
236
  ...(placement.newWindow ? { new_window: true } : {}),
237
- env: { ...childZtcPaneEnv(), ...(motsi ? MOTSI_PANE_ENV : {}) },
237
+ // The task is the agent's: the new pane sends it to its own agent as a message, never runs it as a command.
238
+ env: { ...agentZtcPaneEnv(), ...(motsi ? MOTSI_PANE_ENV : {}) },
238
239
  });
239
240
  if (!sent) {
240
241
  created.catch(() => { });
@@ -8,7 +8,8 @@ export interface PaneInitialInput {
8
8
  /**
9
9
  * Set to '1' in a ZTC pane's environment when its launch task (the text after its flags' `--`) is an agent's: the pane
10
10
  * sends it to its own agent as a message, word for word, and never runs it as a command or a shell line, which a pane's
11
- * relayed input could otherwise do as the person's. The pane drops it from its environment as it starts.
11
+ * relayed input could otherwise do as the person's. A ZTC with the mark does so in pane mode or not. The pane drops it
12
+ * from its environment as it starts.
12
13
  */
13
14
  export declare const PANE_TASK_AS_MESSAGE_ENV = "ZTC_PANE_TASK_AS_MESSAGE";
14
15
  /** Capture immutable image bytes before handing the launch to the renderer. */
@@ -11,7 +11,8 @@ import { writeFileAtomic } from '../utils/atomic_write.js';
11
11
  /**
12
12
  * Set to '1' in a ZTC pane's environment when its launch task (the text after its flags' `--`) is an agent's: the pane
13
13
  * sends it to its own agent as a message, word for word, and never runs it as a command or a shell line, which a pane's
14
- * relayed input could otherwise do as the person's. The pane drops it from its environment as it starts.
14
+ * relayed input could otherwise do as the person's. A ZTC with the mark does so in pane mode or not. The pane drops it
15
+ * from its environment as it starts.
15
16
  */
16
17
  export const PANE_TASK_AS_MESSAGE_ENV = 'ZTC_PANE_TASK_AS_MESSAGE';
17
18
  const MAX_INPUT_BYTES = 64 * 1024;
@@ -92,14 +92,24 @@ export interface WorkerLaunchRoute {
92
92
  /**
93
93
  * Why a ZTC pane opened now on PROVIDER's MODEL (or the provider's default model), or on the route new panes start on
94
94
  * when it names neither, would fail on its first message: Zerg Router, its route, has no key for its provider (Router
95
- * asked once more first). Undefined when it can run, Router is not its route, or ZTC can't tell which model it runs.
95
+ * asked once more first, or once when no list is read yet for the sign-in as it is now). Undefined when it can run,
96
+ * Router is not its route, or ZTC can't tell which model it runs.
96
97
  */
97
98
  export declare function keylessZtcPaneRoute(provider: string | undefined, model: string | undefined): Promise<string | undefined>;
99
+ /**
100
+ * Why no ZTC pane an agent asks for opens now on the route its PROVIDER and MODEL name (as it named them), or on the route
101
+ * new panes start on when it names neither: that route goes through Zerg Router, and this profile has no current Router
102
+ * sign-in to send with (an expired one, or none). The pane would hold the agent's task unsent, as a message no one
103
+ * typed, until someone signs in. Worded to follow "No ZTC pane was opened: ", as a Router route a worker names is
104
+ * (workerSignInNeeded). Undefined when the route has a sign-in to go with or doesn't go through Router.
105
+ */
106
+ export declare function ztcPaneSignInNeeded(provider: string | undefined, model: string | undefined): string | undefined;
98
107
  /**
99
108
  * The route a worker starts on (workspace spec §7.5): the provider, model and effort REQUEST names, checked by
100
109
  * checkWorkerRoute against Router's catalog (asked again when older than 30 s, and once more before a missing key or
101
110
  * an unknown model is believed) and the provider list; or, when it names neither a provider nor a model, the route new
102
- * panes start on, refused as Phase 0 refuses one Router has no key for. A model alone is the Router model of that id,
111
+ * panes start on, refused as Phase 0 refuses one Router has no key for, and when it goes through Router with no current
112
+ * sign-in (ztcPaneSignInNeeded). A model alone is the Router model of that id,
103
113
  * else a model of the provider ZTC knows it by, else of the provider new panes start on. Nothing is saved.
104
114
  */
105
115
  export declare function resolveWorkerRoute(request: WorkerRouteRequest, options?: Pick<WorkerRouteOptions, 'codexItself' | 'opens' | 'signInNeeded'>): Promise<WorkerLaunchRoute | WorkerRouteRefusal>;
@@ -173,7 +173,8 @@ function effortArgs(effort, catalog, route) {
173
173
  /**
174
174
  * Why a ZTC pane opened now on PROVIDER's MODEL (or the provider's default model), or on the route new panes start on
175
175
  * when it names neither, would fail on its first message: Zerg Router, its route, has no key for its provider (Router
176
- * asked once more first). Undefined when it can run, Router is not its route, or ZTC can't tell which model it runs.
176
+ * asked once more first, or once when no list is read yet for the sign-in as it is now). Undefined when it can run,
177
+ * Router is not its route, or ZTC can't tell which model it runs.
177
178
  */
178
179
  export async function keylessZtcPaneRoute(provider, model) {
179
180
  const started = configStore.getNewPaneRoute();
@@ -189,7 +190,13 @@ export async function keylessZtcPaneRoute(provider, model) {
189
190
  let route = newPaneRoute(configStore, chosen ? { ...started, provider: chosen, model: named?.model ?? started.model } : started);
190
191
  if (!route.routed)
191
192
  return undefined;
192
- const catalog = configStore.getRouterCatalog();
193
+ // No list of Router's read yet for the sign-in as it is now (a login in another pane since): with a current sign-in to
194
+ // ask with, Router is asked once, so the route is checked, and named, on the list of the account this ZTC is signed in
195
+ // to, as /ztc checks its own (resolveSiblingRoute). A list Router can't send leaves the route unchecked.
196
+ let catalog = configStore.getRouterCatalog();
197
+ const unread = catalog === undefined && routerCredential() === 'current';
198
+ if (unread)
199
+ catalog = await refreshRouterCatalog().catch(() => undefined);
193
200
  if (chosen && !named && normalizeProviderId(chosen) !== normalizeProviderId(started.provider)) {
194
201
  // A provider named alone starts on its model Router lands on.
195
202
  const row = catalog ? routerModelForSwitch(catalog, route.provider, '', '') : undefined;
@@ -198,13 +205,43 @@ export async function keylessZtcPaneRoute(provider, model) {
198
205
  route = { ...route, model: row.id };
199
206
  }
200
207
  const origin = configStore.getPersonalRouterCredential()?.origin;
201
- return keylessRouterModelRefusal(route.provider, route.model, { catalog, refresh: refreshRouterCatalog, ...(origin ? { origin } : {}) });
208
+ return keylessRouterModelRefusal(route.provider, route.model, { catalog,
209
+ ...(unread ? {} : { refresh: refreshRouterCatalog }), ...(origin ? { origin } : {}) });
210
+ }
211
+ /**
212
+ * Why no ZTC pane an agent asks for opens now on the route its PROVIDER and MODEL name (as it named them), or on the route
213
+ * new panes start on when it names neither: that route goes through Zerg Router, and this profile has no current Router
214
+ * sign-in to send with (an expired one, or none). The pane would hold the agent's task unsent, as a message no one
215
+ * typed, until someone signs in. Worded to follow "No ZTC pane was opened: ", as a Router route a worker names is
216
+ * (workerSignInNeeded). Undefined when the route has a sign-in to go with or doesn't go through Router.
217
+ */
218
+ export function ztcPaneSignInNeeded(provider, model) {
219
+ const started = configStore.getNewPaneRoute();
220
+ let named;
221
+ // A model that names no single provider is refused as the pane is built, in its own words.
222
+ try {
223
+ named = model ? resolveModelAndProvider(model, provider, started.authMode) : undefined;
224
+ }
225
+ catch {
226
+ return undefined;
227
+ }
228
+ const chosen = named?.provider || provider;
229
+ const route = newPaneRoute(configStore, chosen ? { ...started, provider: chosen, model: named?.model ?? started.model } : started);
230
+ const credential = routerCredential();
231
+ if (!route.routed || credential === 'current')
232
+ return undefined;
233
+ const expired = credential === 'expired';
234
+ if (provider !== undefined || model !== undefined)
235
+ return workerSignInNeeded(expired, { provider, model });
236
+ return expired ? 'new ZTC panes start on Zerg Router, and this ZTC\'s sign-in to it expired: /auth login, then try again.'
237
+ : 'new ZTC panes start on Zerg Router, which this ZTC isn\'t signed in to: /auth login, then try again.';
202
238
  }
203
239
  /**
204
240
  * The route a worker starts on (workspace spec §7.5): the provider, model and effort REQUEST names, checked by
205
241
  * checkWorkerRoute against Router's catalog (asked again when older than 30 s, and once more before a missing key or
206
242
  * an unknown model is believed) and the provider list; or, when it names neither a provider nor a model, the route new
207
- * panes start on, refused as Phase 0 refuses one Router has no key for. A model alone is the Router model of that id,
243
+ * panes start on, refused as Phase 0 refuses one Router has no key for, and when it goes through Router with no current
244
+ * sign-in (ztcPaneSignInNeeded). A model alone is the Router model of that id,
208
245
  * else a model of the provider ZTC knows it by, else of the provider new panes start on. Nothing is saved.
209
246
  */
210
247
  export async function resolveWorkerRoute(request, options = {}) {
@@ -223,6 +260,11 @@ export async function resolveWorkerRoute(request, options = {}) {
223
260
  const started = configStore.getNewPaneRoute();
224
261
  const startedRoute = newPaneRoute(configStore, started);
225
262
  if (provider === undefined && model === undefined) {
263
+ // Through Zerg Router with no current sign-in (expired, or none), the worker would hold its task unsent: nothing
264
+ // opens, as for a Router route a worker names, and Router is asked nothing.
265
+ const signIn = ztcPaneSignInNeeded(undefined, undefined);
266
+ if (signIn)
267
+ return refused('route_unavailable', signIn);
226
268
  const keyless = await keylessZtcPaneRoute(undefined, undefined);
227
269
  // Worded to follow "No ZTC pane was opened: ", as every caller says it.
228
270
  if (keyless)
@@ -77,6 +77,7 @@ export declare class MirrorClient implements MirrorPublisher {
77
77
  /** Ask the parent mirror's clients to open the full settings page. */
78
78
  publishSettingsPage(data?: Record<string, unknown>): void;
79
79
  publishStreamEnd(finalMessage?: string, metadata?: Record<string, unknown>): void;
80
+ publishStreamReset(): void;
80
81
  publishToolCall(tool: string, args: Record<string, unknown>, toolCallId: string): void;
81
82
  publishEvidenceSnapshot(snapshot: EvidenceSnapshot, sessionId: string): void;
82
83
  publishTaskHandoff(projection: TaskHandoffProjection | null, sessionId: string): void;
@@ -342,6 +342,9 @@ export class MirrorClient {
342
342
  if (finalMessage)
343
343
  this.publishLastTokenUsage();
344
344
  }
345
+ publishStreamReset() {
346
+ this.postEvent({ type: 'stream_reset', data: {} });
347
+ }
345
348
  publishToolCall(tool, args, toolCallId) {
346
349
  this.postEvent({ type: 'tool_call', data: { tool, args, toolCallId } });
347
350
  }
@@ -18,7 +18,7 @@ import { type AccountOpResult } from './accounts_mirror.js';
18
18
  export declare const BROWSER_BUS_MEMBER_ID = -1;
19
19
  /** The bus member of the ZTC that runs the mirror ("Overseer", or a sim's coordinator): the parent of every pane on it. */
20
20
  export declare const OVERSEER_BUS_MEMBER_ID = 0;
21
- 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 & {});
21
+ export type MirrorEventType = 'message' | 'stream_start' | 'reasoning_delta' | 'stream_delta' | 'stream_end' | 'stream_reset' | '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 & {});
22
22
  export interface MirrorEvent {
23
23
  type: MirrorEventType;
24
24
  timestamp: string;
@@ -290,6 +290,11 @@ export interface MirrorPublisher {
290
290
  publishReasoningDelta(content: string): void;
291
291
  publishStreamDelta(content: string): void;
292
292
  publishStreamEnd(finalMessage?: string, metadata?: Record<string, unknown>): void;
293
+ /**
294
+ * The answer the last stream showed is withdrawn (ZTC asks the model again, so another answer replaces it): it leaves
295
+ * the mirror's history, and live clients drop it.
296
+ */
297
+ publishStreamReset(): void;
293
298
  publishToolCall(tool: string, args: Record<string, unknown>, toolCallId: string): void;
294
299
  publishToolResult(tool: string, result: string, success: boolean, toolCallId: string): void;
295
300
  publishStatus(status: string, verb?: string, waiting?: import('../types.js').CommandWaitingState, toolProgress?: import('../types.js').AgentState['toolProgress']): void;
@@ -534,6 +539,10 @@ export declare class MirrorStreamServer implements MirrorPublisher {
534
539
  private busMembers;
535
540
  private busObservers;
536
541
  private eventObservers;
542
+ /** Each pane's answer its current stream stored for later clients (its history seq), until a new stream starts. */
543
+ private readonly streamedAnswers;
544
+ /** Each pane's latest answer stream, by the seq of its stream_start: the stream a stream_reset for that pane withdraws. */
545
+ private readonly latestStreams;
537
546
  constructor(port?: number, host?: string, persistEvents?: boolean, persistenceKey?: string, primarySessionId?: string);
538
547
  /** Broadcast the display-only active-account summary to mirror clients. */
539
548
  publishAccounts(): void;
@@ -862,11 +871,20 @@ export declare class MirrorStreamServer implements MirrorPublisher {
862
871
  private publishLastTokenUsage;
863
872
  private retireQuestion;
864
873
  private admitQuestionLifecycle;
865
- storeEvent(event: Omit<MirrorEvent, 'timestamp'>): void;
874
+ /** Returns the event as stored, or nothing when it was not admitted. */
875
+ storeEvent(event: Omit<MirrorEvent, 'timestamp'>): MirrorEvent | undefined;
876
+ /** PANE's stream ended with ANSWER (message DATA): stored for clients that connect later, until it is withdrawn. */
877
+ private storeStreamedAnswer;
878
+ /**
879
+ * PANE's last stream is withdrawn: the answer it stored leaves the history, the saved one included, so a client that
880
+ * connects later or a mirror started again doesn't show it, and live clients are told to drop it.
881
+ */
882
+ private withdrawStreamedAnswer;
866
883
  publishStreamStart(): void;
867
884
  publishStreamDelta(content: string): void;
868
885
  publishReasoningDelta(content: string): void;
869
886
  publishStreamEnd(finalMessage?: string, metadata?: Record<string, unknown>): void;
887
+ publishStreamReset(): void;
870
888
  publishToolCall(tool: string, args: Record<string, unknown>, toolCallId: string): void;
871
889
  publishEvidenceSnapshot(snapshot: EvidenceSnapshot, sessionId: string): void;
872
890
  private admitGoalEvent;
@@ -85,7 +85,7 @@ function loadNativeDictation() {
85
85
  }
86
86
  // Observation exposes terminal activity, never operator settings or plugin-specific state.
87
87
  const OBSERVER_EVENT_TYPES = new Set([
88
- 'message', 'stream_start', 'stream_delta', 'stream_end', 'reasoning_delta', 'reasoning',
88
+ 'message', 'stream_start', 'stream_delta', 'stream_end', 'stream_reset', 'reasoning_delta', 'reasoning',
89
89
  'tool_call', 'tool_result', 'status', 'token_usage', 'error', 'cancel', 'mode_change',
90
90
  'pane_info', 'pane_output', 'session_end', 'reload', 'clear', 'todo_list', 'ask_user',
91
91
  'queue_state', 'command_jobs', 'command_pane', 'hook_approval_request', 'widget_prompt', 'widget_select',
@@ -380,6 +380,10 @@ export class MirrorStreamServer {
380
380
  busObservers = [];
381
381
  // Global observers that see every published mirror event.
382
382
  eventObservers = [];
383
+ /** Each pane's answer its current stream stored for later clients (its history seq), until a new stream starts. */
384
+ streamedAnswers = new Map();
385
+ /** Each pane's latest answer stream, by the seq of its stream_start: the stream a stream_reset for that pane withdraws. */
386
+ latestStreams = new Map();
383
387
  constructor(port = 3940, host, persistEvents = true, persistenceKey, primarySessionId) {
384
388
  this.port = port;
385
389
  this.host = host ?? defaultMirrorHost();
@@ -1148,7 +1152,21 @@ export class MirrorStreamServer {
1148
1152
  return;
1149
1153
  event = { ...event, data: { ...event.data, snapshot, session_id: sessionId } };
1150
1154
  }
1155
+ // A withdrawal names the stream it takes, the pane's latest, by its stream_start's seq: stream events are never
1156
+ // replayed, so a client that missed that start (it reconnected while the stream ran) has no block of it to drop.
1157
+ if (event.type === 'stream_reset') {
1158
+ const started = this.latestStreams.get(typeof event.data.pane_id === 'number' ? event.data.pane_id : 0);
1159
+ if (started !== undefined)
1160
+ event = { ...event, data: { ...event.data, stream_seq: started } };
1161
+ }
1151
1162
  const fullEvent = this.stampEvent(event);
1163
+ // A new stream's answer is the one a withdrawal would take.
1164
+ if (event.type === 'stream_start') {
1165
+ const paneId = typeof fullEvent.data.pane_id === 'number' ? fullEvent.data.pane_id : 0;
1166
+ this.streamedAnswers.delete(paneId);
1167
+ if (fullEvent.seq !== undefined)
1168
+ this.latestStreams.set(paneId, fullEvent.seq);
1169
+ }
1152
1170
  // Project once before broadcasting, even with no observers connected yet.
1153
1171
  // A later observer must not see the continuation of a split token.
1154
1172
  this.observerEvent(fullEvent);
@@ -1168,6 +1186,7 @@ export class MirrorStreamServer {
1168
1186
  && event.type !== 'reasoning_delta'
1169
1187
  && event.type !== 'stream_start'
1170
1188
  && event.type !== 'stream_end'
1189
+ && event.type !== 'stream_reset'
1171
1190
  && event.type !== 'pane_info'
1172
1191
  && event.type !== 'session_end'
1173
1192
  && event.type !== 'clear'
@@ -1459,25 +1478,26 @@ export class MirrorStreamServer {
1459
1478
  this.retireQuestion(paneId);
1460
1479
  }
1461
1480
  }
1481
+ /** Returns the event as stored, or nothing when it was not admitted. */
1462
1482
  storeEvent(event) {
1463
1483
  event = this.registerDurableMessageMedia(event);
1464
1484
  if (event.type === 'goal') {
1465
1485
  const data = this.admitGoalEvent(event.data);
1466
1486
  if (!data)
1467
- return;
1487
+ return undefined;
1468
1488
  event = { ...event, data };
1469
1489
  }
1470
1490
  if (event.type === 'task_handoff') {
1471
1491
  const data = this.admitTaskHandoffEvent(event.data);
1472
1492
  if (!data)
1473
- return;
1493
+ return undefined;
1474
1494
  event = { ...event, data };
1475
1495
  }
1476
1496
  if (event.type === 'evidence') {
1477
1497
  const snapshot = parseEvidenceSnapshot(event.data.snapshot);
1478
1498
  const sessionId = event.data.session_id;
1479
1499
  if (!snapshot || typeof sessionId !== 'string' || !sessionId || Buffer.byteLength(sessionId) > 1024)
1480
- return;
1500
+ return undefined;
1481
1501
  event = { ...event, data: { ...event.data, snapshot, session_id: sessionId } };
1482
1502
  }
1483
1503
  const fullEvent = this.stampEvent(event);
@@ -1495,6 +1515,24 @@ export class MirrorStreamServer {
1495
1515
  if (plugin.onEvent)
1496
1516
  plugin.onEvent(fullEvent);
1497
1517
  }
1518
+ return fullEvent;
1519
+ }
1520
+ /** PANE's stream ended with ANSWER (message DATA): stored for clients that connect later, until it is withdrawn. */
1521
+ storeStreamedAnswer(paneId, data) {
1522
+ const stored = this.storeEvent({ type: 'message', data });
1523
+ if (stored?.seq !== undefined)
1524
+ this.streamedAnswers.set(paneId, stored.seq);
1525
+ }
1526
+ /**
1527
+ * PANE's last stream is withdrawn: the answer it stored leaves the history, the saved one included, so a client that
1528
+ * connects later or a mirror started again doesn't show it, and live clients are told to drop it.
1529
+ */
1530
+ withdrawStreamedAnswer(paneId, data) {
1531
+ const seq = this.streamedAnswers.get(paneId);
1532
+ this.streamedAnswers.delete(paneId);
1533
+ if (seq !== undefined)
1534
+ this.history.removeByPredicate(event => event.seq === seq, true);
1535
+ this.publish({ type: 'stream_reset', data });
1498
1536
  }
1499
1537
  publishStreamStart() {
1500
1538
  this.publish({
@@ -1520,17 +1558,17 @@ export class MirrorStreamServer {
1520
1558
  data: {},
1521
1559
  });
1522
1560
  if (finalMessage) {
1523
- this.storeEvent({
1524
- type: 'message',
1525
- data: {
1526
- role: 'assistant',
1527
- content: finalMessage,
1528
- ...(metadata ? { metadata } : {}),
1529
- },
1561
+ this.storeStreamedAnswer(0, {
1562
+ role: 'assistant',
1563
+ content: finalMessage,
1564
+ ...(metadata ? { metadata } : {}),
1530
1565
  });
1531
1566
  }
1532
1567
  this.publishLastTokenUsage();
1533
1568
  }
1569
+ publishStreamReset() {
1570
+ this.withdrawStreamedAnswer(0, {});
1571
+ }
1534
1572
  publishToolCall(tool, args, toolCallId) {
1535
1573
  // Truncate large string args (e.g. write_file content) to avoid SSE bloat
1536
1574
  const safeArgs = { ...args };
@@ -4291,6 +4329,9 @@ export class MirrorStreamServer {
4291
4329
  // event history (same treatment as publishPromptEntry).
4292
4330
  this.publishPromptEntry(taggedEventData);
4293
4331
  }
4332
+ else if (event.type === 'stream_reset') {
4333
+ this.withdrawStreamedAnswer(parsed.pane_id, taggedEventData);
4334
+ }
4294
4335
  else if (parsed.store_only) {
4295
4336
  this.storeEvent({
4296
4337
  type: event.type,
@@ -4303,15 +4344,12 @@ export class MirrorStreamServer {
4303
4344
  data: taggedEventData,
4304
4345
  });
4305
4346
  if (event.type === 'stream_end' && finalMessage) {
4306
- this.storeEvent({
4307
- type: 'message',
4308
- data: {
4309
- pane_id: parsed.pane_id,
4310
- origin_session_id: taggedEventData.origin_session_id,
4311
- role: 'assistant',
4312
- content: finalMessage,
4313
- ...(finalMessageMetadata ? { metadata: finalMessageMetadata } : {}),
4314
- },
4347
+ this.storeStreamedAnswer(parsed.pane_id, {
4348
+ pane_id: parsed.pane_id,
4349
+ origin_session_id: taggedEventData.origin_session_id,
4350
+ role: 'assistant',
4351
+ content: finalMessage,
4352
+ ...(finalMessageMetadata ? { metadata: finalMessageMetadata } : {}),
4315
4353
  });
4316
4354
  }
4317
4355
  }
@@ -42556,6 +42556,15 @@ var AgentError = class extends Error {
42556
42556
  }
42557
42557
  code;
42558
42558
  };
42559
+ var ROUTER_STREAM_LOST_CODE = "ROUTER_STREAM_LOST";
42560
+ var StreamLostError = class extends AgentError {
42561
+ constructor(message, partialMessage, options) {
42562
+ super(message, ROUTER_STREAM_LOST_CODE, options);
42563
+ this.partialMessage = partialMessage;
42564
+ this.name = "StreamLostError";
42565
+ }
42566
+ partialMessage;
42567
+ };
42559
42568
  var ContextOverflowError = class extends AgentError {
42560
42569
  constructor(message, request2, originalMessage) {
42561
42570
  super(message, "CONTEXT_OVERFLOW");
@@ -43665,7 +43674,7 @@ ${currentCoverage.length - rows.length} additional applicability checks omitted.
43665
43674
  * visible text, so an empty or whitespace-only response emits no stream
43666
43675
  * events (EPO-622), matching emitStreamText.
43667
43676
  */
43668
- async streamAndAssemble(backend, request2, signal, onAnswerOutput, onUsage) {
43677
+ async streamAndAssemble(backend, request2, signal, onAnswerOutput, onUsage, onAnswerText) {
43669
43678
  let text5 = "";
43670
43679
  let reasoning = "";
43671
43680
  const toolUses = [];
@@ -43705,10 +43714,12 @@ ${currentCoverage.length - rows.length} additional applicability checks omitted.
43705
43714
  if (ev.text) {
43706
43715
  if (this.remoteResourceSession) {
43707
43716
  text5 += ev.text;
43717
+ onAnswerText?.(text5);
43708
43718
  break;
43709
43719
  }
43710
43720
  if (streamOpen) {
43711
43721
  text5 += ev.text;
43722
+ onAnswerText?.(text5);
43712
43723
  onAnswerOutput();
43713
43724
  this.emit({ type: "stream_delta", content: ev.text });
43714
43725
  break;
@@ -43718,6 +43729,7 @@ ${currentCoverage.length - rows.length} additional applicability checks omitted.
43718
43729
  this.emit({ type: "stream_start" });
43719
43730
  streamOpen = true;
43720
43731
  text5 += pendingWhitespace;
43732
+ onAnswerText?.(text5);
43721
43733
  this.emit({ type: "stream_delta", content: pendingWhitespace });
43722
43734
  pendingWhitespace = "";
43723
43735
  onAnswerOutput();
@@ -44210,6 +44222,7 @@ ${this.runtimeContext}` : this.config.systemPrompt;
44210
44222
  let finalResponseItems;
44211
44223
  let finalResponseModel;
44212
44224
  let lastToolTurnText = "";
44225
+ let lastCompletedAnswerText = "";
44213
44226
  let totalUsage = null;
44214
44227
  let runError = null;
44215
44228
  let stopReason = "max_iterations";
@@ -44389,6 +44402,9 @@ ${this.runtimeContext}` : this.config.systemPrompt;
44389
44402
  });
44390
44403
  continue;
44391
44404
  }
44405
+ if (error62 instanceof StreamLostError && !error62.partialMessage.trim() && lastCompletedAnswerText.trim()) {
44406
+ throw new StreamLostError(error62.message, lastCompletedAnswerText, { cause: error62 });
44407
+ }
44392
44408
  throw error62;
44393
44409
  }
44394
44410
  const usage = retainReturnedAccounting(response);
@@ -44502,6 +44518,7 @@ ${this.runtimeContext}` : this.config.systemPrompt;
44502
44518
  const iterationText = this.remoteResourceSession ? allToolCalls.filter((call) => call.name === "remote_resource" && call.status === "complete").flatMap((call) => remoteDeletionReport(call.result ?? "") ?? []).join("\n") || NO_VERIFIED_DELETION_REPORT : textBlocks.map((b) => b.text).join("\n");
44503
44519
  if (iterationText.trim()) {
44504
44520
  finalContent = iterationText;
44521
+ lastCompletedAnswerText = iterationText;
44505
44522
  finalReasoning = this.remoteResourceSession ? void 0 : response.reasoning;
44506
44523
  finalReasoningModel = finalReasoning ? request2.model : void 0;
44507
44524
  } else if (!this.remoteResourceSession && response.reasoning?.trim()) {
@@ -44902,6 +44919,7 @@ ${this.runtimeContext}` : this.config.systemPrompt;
44902
44919
  if (textContent && textContent.trim() && !signal?.aborted) {
44903
44920
  if (this.remoteResourceSession || !this._lastResponseStreamed) await this.emitStreamText(textContent, signal);
44904
44921
  lastToolTurnText = textContent;
44922
+ lastCompletedAnswerText = textContent;
44905
44923
  }
44906
44924
  const batchLimit = resolveExecutionSettings(this.config.execution).maxCallsPerResponse;
44907
44925
  if (toolUseBlocks.length > batchLimit) {
@@ -45352,7 +45370,7 @@ ${this.runtimeContext}` : this.config.systemPrompt;
45352
45370
  const useStream = process.env.ZTC_NO_STREAM !== "1" && !backend.streamsSyntheticallyFor?.(request2);
45353
45371
  let answerOutputEmitted = false;
45354
45372
  let effectObserved = false;
45355
- let freshTurnRetried = false;
45373
+ let partialAnswer = "";
45356
45374
  let recoveryStartedAt;
45357
45375
  let rateLimitedAttempts = 0;
45358
45376
  let lastReason = "Server temporarily unavailable";
@@ -45451,9 +45469,18 @@ ${this.runtimeContext}` : this.config.systemPrompt;
45451
45469
  this._lastResponseStreamed = true;
45452
45470
  try {
45453
45471
  return await Promise.race([
45454
- this.streamAndAssemble(backend, guardedRequest, signal, () => {
45455
- answerOutputEmitted = true;
45456
- }, onUsage).then(returned),
45472
+ this.streamAndAssemble(
45473
+ backend,
45474
+ guardedRequest,
45475
+ signal,
45476
+ () => {
45477
+ answerOutputEmitted = true;
45478
+ },
45479
+ onUsage,
45480
+ (text5) => {
45481
+ partialAnswer = text5;
45482
+ }
45483
+ ).then(returned),
45457
45484
  guardPromise
45458
45485
  ]);
45459
45486
  } catch (streamErr) {
@@ -45520,9 +45547,24 @@ ${this.runtimeContext}` : this.config.systemPrompt;
45520
45547
  }
45521
45548
  const stalled = timedOut;
45522
45549
  const { retryable, reason, kind } = stalled ? { retryable: true, reason: "LLM request stalled without activity", kind: void 0 } : this.parseAPIError(error62);
45523
- if (kind === "stream_lost" && !isIncompleteStreamError(error62) && attempt < maxAttempts && !freshTurnRetried && request2.transportTurnId !== void 0) {
45524
- freshTurnRetried = true;
45550
+ if (kind === "stream_lost" && !isIncompleteStreamError(error62) && request2.transportTurnId !== void 0) {
45551
+ if (attempt >= maxAttempts) {
45552
+ throw new StreamLostError(reason, partialAnswer, { cause: error62 });
45553
+ }
45525
45554
  request2 = { ...request2, transportTurnId: randomUUID13() };
45555
+ const delay2 = apiRetryDelayMs(attempt, this.config.apiRetry);
45556
+ this.emit({
45557
+ type: "api_retry",
45558
+ attempt,
45559
+ maxAttempts,
45560
+ delay: delay2,
45561
+ reason: "The Router stream was interrupted",
45562
+ phase: "retry",
45563
+ elapsedMs: 0
45564
+ });
45565
+ removeAbortListener?.();
45566
+ removeAbortListener = void 0;
45567
+ await waitForRetryDelay(delay2, signal);
45526
45568
  continue;
45527
45569
  }
45528
45570
  if (!retryable || maxAttempts === 1 || attempt >= maxAttempts && (recoveryWindowMs === 0 || stalled || isIncompleteStreamError(error62))) {
@@ -46238,7 +46280,7 @@ var invokeSkillTool = makeInvokeSkillTool(resolveAmbientSkills);
46238
46280
  // src/zlm.ts
46239
46281
  var ZLM_EMBED_API_VERSION = "zerglang.ztc-embed/1";
46240
46282
  var ZLM_STDIO_PROTOCOL = "zerglang.ztc-host/1";
46241
- var ZLM_ZTC_VERSION = true ? "0.22.0-beta.1" : "development";
46283
+ var ZLM_ZTC_VERSION = true ? "0.23.0-beta.1" : "development";
46242
46284
  var ZLM_MAX_HOST_TOOLS = 64;
46243
46285
  var ZLM_MAX_SYSTEM_PROMPT_BYTES = 128 * 1024;
46244
46286
  var ZLM_HOST_APPROVAL_CAPABILITIES = Object.freeze([