@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/README.md CHANGED
@@ -1312,7 +1312,7 @@ Argument syntax appears as one short usage line instead of selectable chips.
1312
1312
 
1313
1313
  ### File System
1314
1314
  - **read_file** — Read file contents
1315
- - **write_file** — Write/modify files (with diff display)
1315
+ - **write_file** — Write/modify files (with diff display); a file it, `edit_file` or `apply_patch` rewrites keeps its permission mode
1316
1316
  - **list_directory** — List directory contents
1317
1317
  - **search** — Regex code search (ripgrep-style)
1318
1318
 
@@ -1368,7 +1368,17 @@ seconds. The retry fields in `/settings` → Behavior can cap the recovery windo
1368
1368
  `0` for the previous attempt limit, or set Request attempts to `1` to disable
1369
1369
  Agent-level retries and sustained recovery. Backend transport reconnects retain
1370
1370
  their separate policy. Permanent errors and inactivity timeouts still stop the request.
1371
- Partial answer output and dispatched native harness turns are not regenerated.
1371
+ Dispatched native harness turns are not regenerated. A stream that breaks after answer
1372
+ text is asked for again, and the new try's answer replaces the cut one in the pane and
1373
+ the browser mirror. When Zerg Router loses a model's stream partway through, ZTC asks
1374
+ again in the same turn as a fresh Router turn, up to the attempt limit. If every try is
1375
+ cut off, the pane keeps what arrived (what the last try showed or, when it was cut off
1376
+ before any text, what the latest try before it showed) and says a message continues from
1377
+ there: your next message carries it as the model's answer so far, and the saved session
1378
+ keeps it. A `--headless` run reports such a turn as `status: interrupted` with
1379
+ `resumable: true` and its known usage, sends the same answer as its message and to
1380
+ `--output`, and ends with error code `ROUTER_STREAM_LOST` and a non-zero exit, with the
1381
+ session saved without that answer, so another message has the model answer again.
1372
1382
  The activity line shows when ZTC is waiting for the endpoint; request diagnostics
1373
1383
  include HTTP status and bounded, redacted response details.
1374
1384
 
@@ -1737,7 +1747,13 @@ A pane the agent opens with `open_pane` starts as one you open yourself, by
1737
1747
  ZTC's settings as saved at that moment: the profile new Claude Code and Codex
1738
1748
  panes start on, MotSi's remote view, the route a ZTC pane starts on and, in
1739
1749
  the desktop app, Claude Code badges. Only the permission prompts differ: a
1740
- Claude Code or Codex pane an agent opens asks before running commands.
1750
+ Claude Code or Codex pane an agent opens asks before running commands. A ZTC
1751
+ pane an agent opens gets the agent's task as a message to its own agent, never
1752
+ as a command it runs as yours, whether the task comes from `open_pane` or as
1753
+ words among the pane's arguments to ZTC's own `create_ztc_pane`,
1754
+ `create_supervised_ztc_pane` or `create_terminal_pane`, after a `--` there or
1755
+ not. Words after a `--` are only the task, which follows every flag of the
1756
+ pane's launch.
1741
1757
 
1742
1758
  A ZTC agent can be given its own route: `open_pane` with `kind: "ztc"` takes
1743
1759
  `provider` (a name `/provider` lists, or `zergrouter:openai` for Zerg Router
@@ -1750,7 +1766,11 @@ starts with `-`, or an effort the model doesn't take. The worker starts on that
1750
1766
  route through its own launch flags; the default for new panes doesn't change.
1751
1767
  Named alone, a provider starts on the model you last used with it, else its
1752
1768
  default. ZTC's own `create_ztc_pane` refuses a Router route with no key the
1753
- same way.
1769
+ same way. On the route new panes start on, both check Router's list for the
1770
+ sign-in ZTC uses now: after a login in another pane, they read it once first,
1771
+ as `/ztc` does, so a model the new account has no key for opens nothing. With
1772
+ this ZTC's Router sign-in expired, or none, a ZTC worker on a Router route
1773
+ opens nothing, and both say to run `/auth login`.
1754
1774
 
1755
1775
  In the desktop app, `Shift+Enter` and `Option+Enter` start a new line in
1756
1776
  Claude Code's and Codex's prompts: the panes speak the kitty keyboard
Binary file
Binary file
Binary file
Binary file
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/bin/zterm-darwin-arm64
3
3
  size: 33976912 bytes
4
- sha256: e0e1d30f23d40f7b83ad425fc176fb2eaa1588369e2bbc5c6d3ac360d50ea0a7
4
+ sha256: 4a355af139ce60e357cd23ca97500c8c0a69c1689b56dc9a19f1c2a4d1a5017c
@@ -208,6 +208,11 @@ export declare class AgentError extends Error {
208
208
  code?: string | undefined;
209
209
  constructor(message: string, code?: string | undefined, options?: ErrorOptions);
210
210
  }
211
+ export declare const ROUTER_STREAM_LOST_CODE = "ROUTER_STREAM_LOST";
212
+ export declare class StreamLostError extends AgentError {
213
+ readonly partialMessage: string;
214
+ constructor(message: string, partialMessage: string, options?: ErrorOptions);
215
+ }
211
216
  export declare class ContextOverflowError extends AgentError {
212
217
  request: BackendRequest;
213
218
  originalMessage: string;
@@ -78,6 +78,15 @@ export class AgentError extends Error {
78
78
  this.name = 'AgentError';
79
79
  }
80
80
  }
81
+ export const ROUTER_STREAM_LOST_CODE = 'ROUTER_STREAM_LOST';
82
+ export class StreamLostError extends AgentError {
83
+ partialMessage;
84
+ constructor(message, partialMessage, options) {
85
+ super(message, ROUTER_STREAM_LOST_CODE, options);
86
+ this.partialMessage = partialMessage;
87
+ this.name = 'StreamLostError';
88
+ }
89
+ }
81
90
  // Carries the offending request so hosts can dump it for post-mortem analysis.
82
91
  // Do not retain instances long-term — `request` can hold MBs of tools/messages.
83
92
  export class ContextOverflowError extends AgentError {
@@ -1280,7 +1289,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1280
1289
  * visible text, so an empty or whitespace-only response emits no stream
1281
1290
  * events (EPO-622), matching emitStreamText.
1282
1291
  */
1283
- async streamAndAssemble(backend, request, signal, onAnswerOutput, onUsage) {
1292
+ async streamAndAssemble(backend, request, signal, onAnswerOutput, onUsage, onAnswerText) {
1284
1293
  let text = '';
1285
1294
  let reasoning = '';
1286
1295
  const toolUses = [];
@@ -1329,10 +1338,12 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1329
1338
  if (ev.text) {
1330
1339
  if (this.remoteResourceSession) {
1331
1340
  text += ev.text;
1341
+ onAnswerText?.(text);
1332
1342
  break;
1333
1343
  }
1334
1344
  if (streamOpen) {
1335
1345
  text += ev.text;
1346
+ onAnswerText?.(text);
1336
1347
  onAnswerOutput();
1337
1348
  this.emit({ type: 'stream_delta', content: ev.text });
1338
1349
  break;
@@ -1345,6 +1356,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1345
1356
  this.emit({ type: 'stream_start' });
1346
1357
  streamOpen = true;
1347
1358
  text += pendingWhitespace;
1359
+ onAnswerText?.(text);
1348
1360
  this.emit({ type: 'stream_delta', content: pendingWhitespace });
1349
1361
  pendingWhitespace = '';
1350
1362
  onAnswerOutput();
@@ -1882,6 +1894,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1882
1894
  let finalResponseItems;
1883
1895
  let finalResponseModel;
1884
1896
  let lastToolTurnText = '';
1897
+ let lastCompletedAnswerText = '';
1885
1898
  let totalUsage = null;
1886
1899
  let runError = null;
1887
1900
  // Default to max_iterations: the loop only reaches a clean exit via an
@@ -2032,6 +2045,9 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2032
2045
  reason: 'The response kept repeating the same text and was stopped; retrying' });
2033
2046
  continue;
2034
2047
  }
2048
+ if (error instanceof StreamLostError && !error.partialMessage.trim() && lastCompletedAnswerText.trim()) {
2049
+ throw new StreamLostError(error.message, lastCompletedAnswerText, { cause: error });
2050
+ }
2035
2051
  throw error;
2036
2052
  }
2037
2053
  // Retain returned accounting before a later cancellation/checkpoint guard can discard the answer.
@@ -2163,6 +2179,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2163
2179
  // (ZTC-28). Mirrors the tool-branch lastToolTurnText guard below.
2164
2180
  if (iterationText.trim()) {
2165
2181
  finalContent = iterationText;
2182
+ lastCompletedAnswerText = iterationText;
2166
2183
  finalReasoning = this.remoteResourceSession ? undefined : response.reasoning;
2167
2184
  finalReasoningModel = finalReasoning ? request.model : undefined;
2168
2185
  }
@@ -2582,6 +2599,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
2582
2599
  // Last non-empty text wins — empty iterations preserve the prior value
2583
2600
  // so maxIterations exhaustion still has something to return.
2584
2601
  lastToolTurnText = textContent;
2602
+ lastCompletedAnswerText = textContent;
2585
2603
  }
2586
2604
  // Recorded IDs were reconciled above; the scheduler receives only new
2587
2605
  // calls. Add one host notice after retaining every refused result pair.
@@ -3029,7 +3047,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
3029
3047
  const useStream = process.env.ZTC_NO_STREAM !== '1' && !backend.streamsSyntheticallyFor?.(request);
3030
3048
  let answerOutputEmitted = false;
3031
3049
  let effectObserved = false;
3032
- let freshTurnRetried = false;
3050
+ let partialAnswer = '';
3033
3051
  let recoveryStartedAt;
3034
3052
  let rateLimitedAttempts = 0;
3035
3053
  let lastReason = 'Server temporarily unavailable';
@@ -3135,7 +3153,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
3135
3153
  this._lastResponseStreamed = true;
3136
3154
  try {
3137
3155
  return await Promise.race([
3138
- this.streamAndAssemble(backend, guardedRequest, signal, () => { answerOutputEmitted = true; }, onUsage).then(returned),
3156
+ this.streamAndAssemble(backend, guardedRequest, signal, () => { answerOutputEmitted = true; }, onUsage, text => { partialAnswer = text; }).then(returned),
3139
3157
  guardPromise,
3140
3158
  ]);
3141
3159
  }
@@ -3221,11 +3239,17 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
3221
3239
  const { retryable, reason, kind } = stalled
3222
3240
  ? { retryable: true, reason: 'LLM request stalled without activity', kind: undefined }
3223
3241
  : this.parseAPIError(error);
3224
- // The Router lost this turn's producer before any answer text: nothing ran and nothing was
3225
- // shown, so ask once more under a new turn id (resuming the lost turn cannot work).
3226
- if (kind === 'stream_lost' && !isIncompleteStreamError(error) && attempt < maxAttempts && !freshTurnRetried && request.transportTurnId !== undefined) {
3227
- freshTurnRetried = true;
3242
+ if (kind === 'stream_lost' && !isIncompleteStreamError(error) && request.transportTurnId !== undefined) {
3243
+ if (attempt >= maxAttempts) {
3244
+ throw new StreamLostError(reason, partialAnswer, { cause: error });
3245
+ }
3228
3246
  request = { ...request, transportTurnId: randomUUID() };
3247
+ const delay = apiRetryDelayMs(attempt, this.config.apiRetry);
3248
+ this.emit({ type: 'api_retry', attempt, maxAttempts, delay, reason: 'The Router stream was interrupted',
3249
+ phase: 'retry', elapsedMs: 0 });
3250
+ removeAbortListener?.();
3251
+ removeAbortListener = undefined;
3252
+ await waitForRetryDelay(delay, signal);
3229
3253
  continue;
3230
3254
  }
3231
3255
  // Transport failures deliberately fall through to the normal retryable
@@ -56,6 +56,8 @@ export declare function waitForPaneCreatedOrError(tui: PaneCommandTransport, exp
56
56
  requestId?: string;
57
57
  }, timeoutMs?: number): Promise<RustEvent>;
58
58
  export declare function paneLimitReached(): boolean;
59
+ /** ARGS, a ZTC pane's arguments, with FLAGS among its launch flags: before a `--`, after which come only its task's words. */
60
+ export declare function withChildZtcFlags(args: readonly string[], flags: readonly string[]): string[];
59
61
  /**
60
62
  * Environment a ZTC child pane needs to join this workspace (relay, mirror bus, PATH). Its mirror credential is its
61
63
  * own, which the pane transport hands it as it creates the pane, in a one-time file its command line names
@@ -63,6 +65,12 @@ export declare function paneLimitReached(): boolean;
63
65
  * are never passed on.
64
66
  */
65
67
  export declare function childZtcPaneEnv(): Record<string, string>;
68
+ /**
69
+ * The environment of a ZTC pane an agent opens: childZtcPaneEnv's, and the pane's launch task, when its arguments carry
70
+ * one, is the agent's, so the pane sends it to its own agent as a message and never runs it as the person's command
71
+ * (PANE_TASK_AS_MESSAGE_ENV), as an agent's /ztc task.
72
+ */
73
+ export declare function agentZtcPaneEnv(): Record<string, string>;
66
74
  export declare function buildChildZtcPaneLaunch(extraArgs?: string[], childSessionId?: string, options?: {
67
75
  mirrorPort?: number;
68
76
  entrypoint?: string;
@@ -16,7 +16,8 @@ import { CAPABILITY_PANE_DELIVERY_ACK } from '../../ui/ratatui/protocol.js';
16
16
  import { generateSessionId } from '../../session.js';
17
17
  import { isPaneProvider, resolveModelAndProvider } from '../../panes/model_catalog.js';
18
18
  import { buildZtcPaneLaunchCommand, createZtcLaunchSpec } from '../../panes/ztc_launch.js';
19
- import { keylessZtcPaneRoute } from '../../panes/worker_route.js';
19
+ import { PANE_TASK_AS_MESSAGE_ENV } from '../../panes/initial_input.js';
20
+ import { keylessZtcPaneRoute, ztcPaneSignInNeeded } from '../../panes/worker_route.js';
20
21
  import { newPaneRoute } from '../commands/runtime_model.js';
21
22
  import { buildUserSubprocessEnvOverrides } from '../../utils/subprocess_env.js';
22
23
  export { resolveModelAndProvider };
@@ -425,6 +426,9 @@ function filterChildZtcArgs(args) {
425
426
  const filtered = [];
426
427
  for (let i = 0; i < args.length; i++) {
427
428
  const arg = args[i];
429
+ // What follows a `--` is a task, never a launch flag: a pane's recorded launch stays without it.
430
+ if (arg === '--')
431
+ break;
428
432
  if (i === 0 && arg === 'resume') {
429
433
  if (args[i + 1] && !args[i + 1].startsWith('-')) {
430
434
  i++;
@@ -445,6 +449,16 @@ function filterChildZtcArgs(args) {
445
449
  }
446
450
  return filtered;
447
451
  }
452
+ /** A ZTC pane's arguments split at their first `--`: its launch flags before it, and after it only its task's words. */
453
+ function splitChildZtcTask(args) {
454
+ const end = args.indexOf('--');
455
+ return end < 0 ? { flags: [...args], task: [] } : { flags: args.slice(0, end), task: args.slice(end + 1) };
456
+ }
457
+ /** ARGS, a ZTC pane's arguments, with FLAGS among its launch flags: before a `--`, after which come only its task's words. */
458
+ export function withChildZtcFlags(args, flags) {
459
+ const { flags: own, task } = splitChildZtcTask(args);
460
+ return args.includes('--') ? [...own, ...flags, '--', ...task] : [...own, ...flags];
461
+ }
448
462
  /**
449
463
  * Environment a ZTC child pane needs to join this workspace (relay, mirror bus, PATH). Its mirror credential is its
450
464
  * own, which the pane transport hands it as it creates the pane, in a one-time file its command line names
@@ -468,6 +482,14 @@ export function childZtcPaneEnv() {
468
482
  copyEnvIfPresent(env, 'PATH');
469
483
  return env;
470
484
  }
485
+ /**
486
+ * The environment of a ZTC pane an agent opens: childZtcPaneEnv's, and the pane's launch task, when its arguments carry
487
+ * one, is the agent's, so the pane sends it to its own agent as a message and never runs it as the person's command
488
+ * (PANE_TASK_AS_MESSAGE_ENV), as an agent's /ztc task.
489
+ */
490
+ export function agentZtcPaneEnv() {
491
+ return { ...childZtcPaneEnv(), [PANE_TASK_AS_MESSAGE_ENV]: '1' };
492
+ }
471
493
  function isLegacyChildZtcLaunch(command, args) {
472
494
  const commandName = command.split(/[\\/]/).pop()?.toLowerCase() || command.toLowerCase();
473
495
  if (commandName !== 'node' && commandName !== 'node.exe' && commandName !== 'npx') {
@@ -483,7 +505,11 @@ export function buildChildZtcPaneLaunch(extraArgs = [], childSessionId = generat
483
505
  if (!scriptPath) {
484
506
  return new Error('Error: Unable to determine the current ZTC entrypoint for child pane launch.');
485
507
  }
486
- const passthroughArgs = filterChildZtcArgs(extraArgs);
508
+ // Words after a `--` among the pane's arguments are only its task: it follows every flag of the launch, as /ztc and
509
+ // open_pane give one, so the pane starts in pane mode, under the session it is given and on its route, and its agent
510
+ // gets the task and nothing of the launch.
511
+ const { flags: launchArgs, task } = splitChildZtcTask(extraArgs);
512
+ const passthroughArgs = filterChildZtcArgs(launchArgs);
487
513
  let provider;
488
514
  let model;
489
515
  // Pull provider/model into local vars (so we can resolve them through the
@@ -491,17 +517,17 @@ export function buildChildZtcPaneLaunch(extraArgs = [], childSessionId = generat
491
517
  // fallback args — filterChildZtcArgs strips both, but child launch needs
492
518
  // them when the caller asked for a specific working dir or session resume.
493
519
  const cwdResumeArgs = [];
494
- for (let i = 0; i < extraArgs.length; i++) {
495
- const arg = extraArgs[i];
496
- if ((arg === '--provider' || arg === '--model') && extraArgs[i + 1] && !extraArgs[i + 1].startsWith('-')) {
520
+ for (let i = 0; i < launchArgs.length; i++) {
521
+ const arg = launchArgs[i];
522
+ if ((arg === '--provider' || arg === '--model') && launchArgs[i + 1] && !launchArgs[i + 1].startsWith('-')) {
497
523
  if (arg === '--provider')
498
- provider = extraArgs[i + 1];
524
+ provider = launchArgs[i + 1];
499
525
  if (arg === '--model')
500
- model = extraArgs[i + 1];
526
+ model = launchArgs[i + 1];
501
527
  i++;
502
528
  }
503
- else if ((arg === '--cwd' || arg === '--resume') && extraArgs[i + 1] && !extraArgs[i + 1].startsWith('-')) {
504
- cwdResumeArgs.push(arg, extraArgs[i + 1]);
529
+ else if ((arg === '--cwd' || arg === '--resume') && launchArgs[i + 1] && !launchArgs[i + 1].startsWith('-')) {
530
+ cwdResumeArgs.push(arg, launchArgs[i + 1]);
505
531
  i++;
506
532
  }
507
533
  }
@@ -539,6 +565,9 @@ export function buildChildZtcPaneLaunch(extraArgs = [], childSessionId = generat
539
565
  const stripped = finalArgs.filter((a) => a !== '--pane');
540
566
  finalArgs = [...stripped, '--mirror', '--mux', '--mirror-port', String(options.mirrorPort), '--no-browser-open'];
541
567
  }
568
+ // A task of blanks alone is none.
569
+ if (task.join(' ').trim())
570
+ finalArgs = [...finalArgs, '--', ...task];
542
571
  return {
543
572
  command: built.command,
544
573
  args: finalArgs,
@@ -664,7 +693,7 @@ Returns the pane ID which you can use with read_terminal_pane, write_terminal_pa
664
693
  ratio,
665
694
  target,
666
695
  pane_type: paneType,
667
- env: paneType === 'ztc' ? childZtcPaneEnv() : buildUserSubprocessEnvOverrides(),
696
+ env: paneType === 'ztc' ? agentZtcPaneEnv() : buildUserSubprocessEnvOverrides(),
668
697
  });
669
698
  if (!sent) {
670
699
  eventPromise.catch(() => { }); // prevent unhandled rejection from dangling timeout
@@ -760,6 +789,7 @@ export const createZtcPaneTool = {
760
789
  if (isRetiredProvider(provider) || isRetiredModel(model)) {
761
790
  return `Error: ${retiredProviderMessage(provider ?? model ?? 'claude_code')} Leave provider unset to use this session's model.`;
762
791
  }
792
+ const named = { provider, model };
763
793
  if (model) {
764
794
  const resolved = resolveModelAndProvider(model, provider, configStore.getResolvedAuthMode());
765
795
  model = resolved.model;
@@ -776,18 +806,23 @@ export const createZtcPaneTool = {
776
806
  return `Error: No API key configured for provider "${provider}". Set it with /config key ${provider} <key> or the appropriate environment variable.`;
777
807
  }
778
808
  }
809
+ // Through Zerg Router with no current sign-in (expired, or none), the pane would hold its task unsent, as a message
810
+ // no one typed: nothing opens, as open_pane's worker doesn't, and Router is asked nothing.
811
+ const signIn = ztcPaneSignInNeeded(named.provider, named.model);
812
+ if (signIn)
813
+ return `Error: No ZTC pane was opened: ${signIn}`;
779
814
  // A route Zerg Router has no key for fails on its first message, the route new panes start on included: it is
780
815
  // refused before anything opens, with where the key goes (Router asked once more first).
781
816
  const keyless = await keylessZtcPaneRoute(provider, model);
782
817
  if (keyless)
783
818
  return `Error: No ZTC pane was opened: ${provider || model ? '' : 'new ZTC panes start on Zerg Router. '}${keyless}`;
784
- // Inject --provider/--model into child args
819
+ // Inject --provider/--model into child args, among its launch flags (before any task after a `--`)
785
820
  const modelArgs = [];
786
821
  if (provider)
787
822
  modelArgs.push('--provider', provider);
788
823
  if (model)
789
824
  modelArgs.push('--model', model);
790
- const allExtraArgs = [...extraArgs, ...modelArgs];
825
+ const allExtraArgs = withChildZtcFlags(extraArgs, modelArgs);
791
826
  const direction = parseOptionalSplitDirection(args.direction);
792
827
  if (direction instanceof Error) {
793
828
  return direction.message;
@@ -831,7 +866,7 @@ export const createZtcPaneTool = {
831
866
  ratio,
832
867
  target,
833
868
  pane_type: 'ztc',
834
- env: childZtcPaneEnv(),
869
+ env: agentZtcPaneEnv(),
835
870
  persona,
836
871
  });
837
872
  if (!sent) {
@@ -1,9 +1,10 @@
1
1
  import { request } from 'http';
2
2
  import { configStore } from '../../config.js';
3
3
  import { ROUTE_AWAITS_A_CHOICE } from '../../config/retired_routes.js';
4
+ import { PANE_TASK_AS_MESSAGE_ENV } from '../../panes/initial_input.js';
4
5
  import { generateSessionId } from '../../session.js';
5
6
  import { getBusTransport } from './bus_message.js';
6
- import { buildChildZtcPaneLaunch, getMuxTransport, paneLimitReached, resolveModelAndProvider, } from './pane.js';
7
+ import { buildChildZtcPaneLaunch, getMuxTransport, paneLimitReached, resolveModelAndProvider, withChildZtcFlags, } from './pane.js';
7
8
  let supervisionManagerRef = null;
8
9
  export function setSupervisionManager(manager) {
9
10
  supervisionManagerRef = manager;
@@ -246,7 +247,8 @@ export const createSupervisedZtcPaneTool = {
246
247
  if (model)
247
248
  modelArgs.push('--model', model);
248
249
  const childSessionId = generateSessionId();
249
- const childLaunch = buildChildZtcPaneLaunch([...extraArgs, ...modelArgs], childSessionId);
250
+ // The provider and model are launch flags: they go before any task after a `--`.
251
+ const childLaunch = buildChildZtcPaneLaunch(withChildZtcFlags(extraArgs, modelArgs), childSessionId);
250
252
  if (childLaunch instanceof Error) {
251
253
  return childLaunch.message;
252
254
  }
@@ -263,6 +265,8 @@ export const createSupervisedZtcPaneTool = {
263
265
  ratio,
264
266
  target,
265
267
  pane_type: 'ztc',
268
+ // Words among the child's arguments are its launch task, the agent's: a message, never the person's command.
269
+ env: { [PANE_TASK_AS_MESSAGE_ENV]: '1' },
266
270
  }, childTitle, 'ztc');
267
271
  const feedTitle = args.feed_title
268
272
  ? String(args.feed_title)
@@ -1,6 +1,9 @@
1
1
  import type { Message } from '../types.js';
2
2
  export declare const INTERRUPTED_TURN_MARKER: string;
3
- export declare function interruptedTurnMarker(): Message;
3
+ /** The same note for a turn that ended because Zerg Router lost the model's answer on every attempt. */
4
+ export declare const ROUTER_CUT_TURN_MARKER: string;
5
+ /** What ended the turn: the person stopped it, or Zerg Router lost its answer on every attempt. */
6
+ export declare function interruptedTurnMarker(cause?: 'person' | 'router_stream_lost'): Message;
4
7
  export declare function isInterruptedTurnMarker(message: Message): boolean;
5
8
  /** Preserve authored sources while bounding historical tool-result copies. */
6
9
  export declare function prepareSessionMessages(messages: readonly Message[]): Message[];
@@ -2,11 +2,15 @@ import { describeDiagnosticTruncation, redactDiagnosticValue } from '../diagnost
2
2
  import { stripEphemeralMessages } from '../utils/ephemeral.js';
3
3
  export const INTERRUPTED_TURN_MARKER = 'The previous turn was interrupted by the user before it finished. '
4
4
  + 'Its partial output is context, not a completed result; continue the task or ask what to do next.';
5
- export function interruptedTurnMarker() {
5
+ /** The same note for a turn that ended because Zerg Router lost the model's answer on every attempt. */
6
+ export const ROUTER_CUT_TURN_MARKER = 'The previous turn was cut off before it finished: Zerg Router lost the model\'s answer '
7
+ + 'partway through. Its partial output is context, not a completed result; continue from where it stopped, or ask what to do next.';
8
+ /** What ended the turn: the person stopped it, or Zerg Router lost its answer on every attempt. */
9
+ export function interruptedTurnMarker(cause = 'person') {
6
10
  return {
7
11
  id: `interrupted_turn_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`,
8
12
  role: 'user',
9
- content: INTERRUPTED_TURN_MARKER,
13
+ content: cause === 'router_stream_lost' ? ROUTER_CUT_TURN_MARKER : INTERRUPTED_TURN_MARKER,
10
14
  timestamp: new Date(),
11
15
  metadata: { interruptedTurn: true, synthetic: true, hostContext: true, preserveUserBoundary: true },
12
16
  };
@@ -556,7 +556,17 @@ export declare class RatatuiApp {
556
556
  private flushLocalStreamDelta;
557
557
  /** Close the displayed phase before another kind of output starts. */
558
558
  private finishLocalStreamingMessages;
559
- private dropStreamingMessages;
559
+ /** The answer the attempt that just ended showed: its messages since that attempt's stream began. */
560
+ private streamedAnswerIds;
561
+ /** An answer the agent withdrew goes from the transcript, and from the mirror, which streamed it too. Returns what went. */
562
+ private dropWithdrawnAnswer;
563
+ /**
564
+ * A turn Zerg Router cut off on every attempt whose last attempt showed nothing: the answer an earlier attempt showed,
565
+ * DROPPED when ZTC asked again, comes back, finished, after what the turn shows, when it is the answer so far the agent
566
+ * reports (PARTIAL), the one a --headless run reports; and to the mirror, which dropped it too. An answer of another
567
+ * request, or none, never does.
568
+ */
569
+ private restoreDroppedAnswer;
560
570
  private clearLocalStreamDelta;
561
571
  private rememberToolOutputFull;
562
572
  private makeToolOutputMetadata;
@@ -122,7 +122,7 @@ import { formatDuration, shortenPath } from './utils/path_format.js';
122
122
  import { getModeRegistry } from './modes/index.js';
123
123
  import { generateSessionId, bindToolResponseStoreToSession, findRecentSessionSummary, findSessionHandoffOffers, getProjectHash, getSessionPathForCwd, setSessionLabels, saveSessionToFile, loadSessionFromFile, listAllSessions, listWorkspaceSessions, } from './session.js';
124
124
  import { awaitStartupGitSnapshot, getRuntimeInfo, getStartupGitSnapshot } from './runtime_info.js';
125
- import { ContextOverflowError, isContextOverflowMessage } from './agent/agent.js';
125
+ import { ContextOverflowError, isContextOverflowMessage, StreamLostError } from './agent/agent.js';
126
126
  import { dumpContextOverflow } from './agent/contextDump.js';
127
127
  import { BROWSER_BUS_MEMBER_ID, OVERSEER_BUS_MEMBER_ID, createMirrorStreamServer, startMirrorStreamServer, stopMirrorStreamServer, } from './web/mirror_stream.js';
128
128
  import { initMirrorClient } from './web/mirror_client.js';
@@ -287,6 +287,8 @@ const GENERATION_CANCELLED_NOTICE = 'Stopped by you';
287
287
  * answer with a correction, or rewind the exchange out of context.
288
288
  */
289
289
  const INTERRUPT_NOTICE = 'Interrupted. Tell me what to do next, or use /rewind to choose an earlier prompt.';
290
+ /** A turn Zerg Router cut off on every attempt: the answer so far stays, and a message continues it. */
291
+ const ROUTER_STREAM_LOST_NOTICE = 'Zerg Router lost the answer partway through. Send a message to continue from there.';
290
292
  const ESCAPE_STOP_NOTICE = 'Esc again to stop';
291
293
  /** What the browser mirror shows for a select. */
292
294
  function mirrorSelectOptions(options) {
@@ -1087,13 +1089,36 @@ export class RatatuiApp {
1087
1089
  return;
1088
1090
  this.controller.setMessages(messages.map(message => message.isStreaming ? { ...message, isStreaming: false } : message));
1089
1091
  }
1090
- dropStreamingMessages() {
1092
+ /** The answer the attempt that just ended showed: its messages since that attempt's stream began. */
1093
+ streamedAnswerIds() {
1094
+ return new Set(this.controller.getState().messages.slice(this.streamAttemptStart)
1095
+ .filter(message => message.role === 'assistant' && message.metadata?.reasoning !== true).map(message => message.id));
1096
+ }
1097
+ /** An answer the agent withdrew goes from the transcript, and from the mirror, which streamed it too. Returns what went. */
1098
+ dropWithdrawnAnswer(discardedIds) {
1099
+ if (discardedIds.size === 0)
1100
+ return [];
1091
1101
  const messages = this.controller.getState().messages;
1092
- const discarded = messages.slice(this.streamAttemptStart).filter(message => message.role === 'assistant' && message.metadata?.reasoning !== true);
1093
- const discardedIds = new Set(discarded.map(message => message.id));
1094
1102
  this.controller.setMessages(messages.filter(message => !discardedIds.has(message.id)));
1095
1103
  for (const id of discardedIds)
1096
1104
  this.streamTypewriters.delete(id);
1105
+ this.markTranscriptDirty();
1106
+ this.mirror?.publishStreamReset();
1107
+ return messages.filter(message => discardedIds.has(message.id));
1108
+ }
1109
+ /**
1110
+ * A turn Zerg Router cut off on every attempt whose last attempt showed nothing: the answer an earlier attempt showed,
1111
+ * DROPPED when ZTC asked again, comes back, finished, after what the turn shows, when it is the answer so far the agent
1112
+ * reports (PARTIAL), the one a --headless run reports; and to the mirror, which dropped it too. An answer of another
1113
+ * request, or none, never does.
1114
+ */
1115
+ restoreDroppedAnswer(dropped, partial) {
1116
+ const content = dropped.map(message => message.content).join('');
1117
+ if (!content.trim() || content !== partial)
1118
+ return;
1119
+ this.controller.setMessages([...this.controller.getState().messages, { ...dropped[0], content, isStreaming: false }]);
1120
+ this.markTranscriptDirty();
1121
+ this.mirror?.publishMessage('assistant', content, { streamed: true });
1097
1122
  }
1098
1123
  clearLocalStreamDelta() {
1099
1124
  if (this.streamDeltaFlushTimer) {
@@ -1297,8 +1322,9 @@ export class RatatuiApp {
1297
1322
  this.startupZergEndpoint = options?.startupZergEndpoint;
1298
1323
  this.maxIterations = options?.maxIterations;
1299
1324
  this.initialPrompt = options?.initialPrompt;
1300
- // Read once, and kept from everything this pane starts.
1301
- this.initialPromptAsMessage = options?.pane === true && process.env[PANE_TASK_AS_MESSAGE_ENV] === '1';
1325
+ // Only an agent's launch sets the mark, so its task is a message in pane mode or not. Read once, and kept from
1326
+ // everything this ZTC starts.
1327
+ this.initialPromptAsMessage = process.env[PANE_TASK_AS_MESSAGE_ENV] === '1';
1302
1328
  delete process.env[PANE_TASK_AS_MESSAGE_ENV];
1303
1329
  this.sessionFile = options?.sessionFile;
1304
1330
  this.instanceTitleProvider = options?.instanceTitleProvider ?? resolveNavigatorInstanceTitle;
@@ -4593,7 +4619,9 @@ export class RatatuiApp {
4593
4619
  // second tab / --resume shows the child pane's model turn blank
4594
4620
  // (the overseer stores its finalized reply the same way, via
4595
4621
  // storeEvent). Every other event publishes normally.
4596
- if (event.event_type === 'stream_start') {
4622
+ // A child that withdraws the answer its last stream showed (stream_reset: it asks Zerg Router again, or keeps an
4623
+ // answer it reports next, #875) leaves live clients without it, so its next assistant message is published.
4624
+ if (event.event_type === 'stream_start' || event.event_type === 'stream_reset') {
4597
4625
  this.childPaneStreamed.delete(event.pane_id);
4598
4626
  }
4599
4627
  else if (event.event_type === 'stream_end') {
@@ -11049,6 +11077,13 @@ export class RatatuiApp {
11049
11077
  const preRunMessageCount = this.controller.getState().messages.length;
11050
11078
  const checkpointTurn = ++this.toolCheckpointTurn;
11051
11079
  let historyCheckpoint = [];
11080
+ // The answer an attempt showed before the agent withdrew it (stream_reset). It stays shown until the agent says what
11081
+ // follows: a retry drops it (api_retry), so a retried answer never appends to it; a turn that ends because Zerg
11082
+ // Router lost the stream on every attempt keeps it, where it streamed; any other error drops it.
11083
+ let withdrawnAnswer = new Set();
11084
+ // The latest answer a retry dropped: a turn Zerg Router cuts off on every attempt, the last of which showed nothing,
11085
+ // keeps it when it is the answer so far the agent reports (restoreDroppedAnswer).
11086
+ let droppedAnswer = [];
11052
11087
  const checkpointBaseIds = new Set();
11053
11088
  const transcriptIterations = [];
11054
11089
  const toolIterations = new Map();
@@ -11232,9 +11267,8 @@ export class RatatuiApp {
11232
11267
  break;
11233
11268
  case 'stream_reset': {
11234
11269
  this.clearLocalStreamDelta();
11235
- this.dropStreamingMessages();
11270
+ withdrawnAnswer = this.streamedAnswerIds();
11236
11271
  this.controller.setAgentState(applyAgentEventToState(this.controller.getState().agentState, event));
11237
- this.markTranscriptDirty();
11238
11272
  break;
11239
11273
  }
11240
11274
  case 'stream_end': {
@@ -11333,6 +11367,11 @@ export class RatatuiApp {
11333
11367
  });
11334
11368
  break;
11335
11369
  case 'api_retry': {
11370
+ // The request is asked again: an answer its last attempt showed, which the agent withdrew, goes first.
11371
+ const dropped = this.dropWithdrawnAnswer(withdrawnAnswer);
11372
+ if (dropped.length > 0)
11373
+ droppedAnswer = dropped;
11374
+ withdrawnAnswer = new Set();
11336
11375
  this.controller.setAgentState(applyAgentEventToState(this.controller.getState().agentState, event));
11337
11376
  const retryMsg = formatApiRetryNotice(event);
11338
11377
  // Retries of one request update one notice instead of adding a line per attempt.
@@ -11397,11 +11436,16 @@ export class RatatuiApp {
11397
11436
  catch (err) {
11398
11437
  if (this.agentTurnOwner !== owner || this.activeToolCheckpointHandler !== checkpointHandler)
11399
11438
  return;
11439
+ // Zerg Router lost the stream on every attempt: the answer the last one showed stays, finished, where it streamed,
11440
+ // and the next message continues from it. Any other error withdraws it, as a retry would have.
11441
+ const lostStream = err instanceof StreamLostError;
11442
+ if (!lostStream)
11443
+ this.dropWithdrawnAnswer(withdrawnAnswer);
11400
11444
  retainCheckpoint();
11401
11445
  this.flushLocalStreamDelta();
11402
11446
  this.finishLocalStreamingMessages();
11403
11447
  this.finishToolGroups(err.message);
11404
- const errorMsg = err.message;
11448
+ const errorMsg = lostStream ? ROUTER_STREAM_LOST_NOTICE : err.message;
11405
11449
  if (err instanceof ContextOverflowError) {
11406
11450
  const dumpPath = await dumpContextOverflow(err, this.sessionId);
11407
11451
  if (dumpPath) {
@@ -11418,8 +11462,20 @@ export class RatatuiApp {
11418
11462
  return this.runAgentTurn(true, owner);
11419
11463
  }
11420
11464
  }
11421
- promptTurn.setOutcome('failed');
11422
- this.addErrorMessage(`Error: ${errorMsg}`);
11465
+ if (lostStream) {
11466
+ // The last attempt showed nothing: the answer so far is the one an earlier attempt showed, as headless reports.
11467
+ if (withdrawnAnswer.size === 0)
11468
+ this.restoreDroppedAnswer(droppedAnswer, err.partialMessage);
11469
+ // Marked as a stopped turn is: it ended before it finished, its answer so far is context for the model, and a
11470
+ // message continues it.
11471
+ promptTurn.setOutcome('interrupted');
11472
+ this.addSystemMessage(ROUTER_STREAM_LOST_NOTICE, { interrupted: true });
11473
+ this.controller.addMessage(interruptedTurnMarker('router_stream_lost'));
11474
+ }
11475
+ else {
11476
+ promptTurn.setOutcome('failed');
11477
+ this.addErrorMessage(`Error: ${errorMsg}`);
11478
+ }
11423
11479
  let routedTurn = false;
11424
11480
  try {
11425
11481
  routedTurn = configStore.resolveLLMBackendConfig().useProxy;
@@ -168,6 +168,7 @@ export declare class HeadlessApp {
168
168
  private batchEventUnsub;
169
169
  private batchFailed;
170
170
  private hadHeadlessError;
171
+ private turnUsageReceipts;
171
172
  /** Zerg Router's words for the last refusal that ended a turn; the run exits HEADLESS_EXIT_ROUTER_REFUSED. */
172
173
  private routerRefusal;
173
174
  /** The turn now running ended on a Router refusal: the goal and Voyager loops stop on it. */