@zergai/ztc 0.16.0-beta.1 → 0.16.2-dev.202611091056

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.
@@ -367,6 +367,26 @@ function parseStructuredSubmitInput(rawInput) {
367
367
  catch { /* malformed envelope — fall through to plain text */ }
368
368
  return { text: rawInput, attachments: [] };
369
369
  }
370
+ /** Whether a slash command changes the agent's mode or model: handleSubmit refuses one while a turn is active. */
371
+ function changesRuntimeMode(cmd, args) {
372
+ const subcommand = args[0]?.toLowerCase();
373
+ const modeConfigRead = cmd === 'mode'
374
+ && (args.length === 0
375
+ || subcommand === 'list'
376
+ || args[1]?.toLowerCase() === 'config');
377
+ return cmd === 'model' || cmd === 'plan'
378
+ || cmd === 'execute'
379
+ || cmd === 'exit-mode'
380
+ || (cmd === 'mode' && !modeConfigRead);
381
+ }
382
+ /**
383
+ * Whether a slash command can't run while an agent turn is active: it changes the mode or model, or it refuses until the
384
+ * turn ends (Command.waitsForTurnEnd).
385
+ */
386
+ function waitsForTurnEnd(cmd, args) {
387
+ return changesRuntimeMode(cmd, args)
388
+ || commands.find(command => command.name === cmd.toLowerCase())?.waitsForTurnEnd?.(args) === true;
389
+ }
370
390
  /**
371
391
  * Main Ratatui-based CLI application
372
392
  */
@@ -1767,6 +1787,9 @@ export class RatatuiApp {
1767
1787
  desktopTaskBlockedReason(allowSettingsPanel = false) {
1768
1788
  if (this.exiting)
1769
1789
  return 'Session is closing';
1790
+ // An account or model change blocks only Send now (handleDesktopTaskAction): moving, editing and removing a queued
1791
+ // line run nothing, as with the terminal's queue editor, and the desktop app greys out every queue control while
1792
+ // this reason is set.
1770
1793
  if (this.handoffQueueSaveInFlight || this.steeringAdmissionCount > 0)
1771
1794
  return 'Saving queued work';
1772
1795
  if (this.workspacePaused || this.workspaceResuming || this.workspaceChoice)
@@ -1792,6 +1815,7 @@ export class RatatuiApp {
1792
1815
  return;
1793
1816
  }
1794
1817
  this.runtimeMutationInFlight = true;
1818
+ this.syncOwnPaneTaskControls();
1795
1819
  try {
1796
1820
  this.reloadAgentInPlace();
1797
1821
  await this.awaitAgentBind();
@@ -1809,6 +1833,8 @@ export class RatatuiApp {
1809
1833
  if (this.isHostedRuntime())
1810
1834
  return { ok: false, error: 'Hosted accounts are managed by the host.' };
1811
1835
  this.runtimeMutationInFlight = true;
1836
+ // The desktop app's runtime controls show the change in progress while it runs (runtimeSwitchBlockedReason).
1837
+ this.syncOwnPaneTaskControls();
1812
1838
  let operationOpen = true;
1813
1839
  try {
1814
1840
  const result = await applyAccountOp(body, configStore, async () => {
@@ -1928,6 +1954,7 @@ export class RatatuiApp {
1928
1954
  }
1929
1955
  else {
1930
1956
  this.runtimeMutationInFlight = true;
1957
+ this.syncOwnPaneTaskControls();
1931
1958
  try {
1932
1959
  await this.openDesktopModelPicker();
1933
1960
  reply('applied', 'Model palette completed.');
@@ -2196,6 +2223,12 @@ export class RatatuiApp {
2196
2223
  return;
2197
2224
  }
2198
2225
  if (event.action === 'send_now') {
2226
+ // The change holds the queue until it ends (handleSubmit): a line sent into it would be held again as a copy, and
2227
+ // both would run after it. It waits in the queue, once, for the change to end.
2228
+ if (this.runtimeMutationInFlight) {
2229
+ reply('blocked', 'Account or model change in progress');
2230
+ return;
2231
+ }
2199
2232
  const queued = this.controller.getQueue().find(candidate => candidate.id === entry.id);
2200
2233
  const correction = this.captureHandoffCorrections().find(candidate => candidate.id === entry.id);
2201
2234
  const source = correction?.sourceMessageId
@@ -2204,9 +2237,13 @@ export class RatatuiApp {
2204
2237
  reply('not_queued', 'This accepted task source is no longer queued.');
2205
2238
  return;
2206
2239
  }
2240
+ // A slash or shell command runs at once when the person types it, during a run too (handleSubmit takes it
2241
+ // before its busy branch). Send now runs a queued one the same way, as whoever queued it: it never becomes a
2242
+ // message for the model, so it never steers a run.
2243
+ const route = routeUserInput(queued.text);
2244
+ const command = route.type === 'command' || route.type === 'shell';
2207
2245
  if (!this.isAgentBusy()) {
2208
- const ids = [queued.id, ...this.controller.getQueue().filter(candidate => candidate.id !== queued.id).map(candidate => candidate.id)];
2209
- const ordered = await this.persistQueuedCorrectionOrder(ids);
2246
+ const ordered = await this.persistQueuedCorrectionOrder(this.queueIdsWithFirst(queued.id));
2210
2247
  if (ordered !== 'saved') {
2211
2248
  reply(ordered === 'failed' ? 'persistence_failed' : 'not_queued', 'Queued task was not sent; its original source is retained.');
2212
2249
  return;
@@ -2215,8 +2252,10 @@ export class RatatuiApp {
2215
2252
  // The admission callback acknowledges that boundary, not completion of the provider turn.
2216
2253
  this.flushingQueue = true;
2217
2254
  this.queuePaused = false;
2255
+ const before = new Set(this.controller.getState().messages.map(message => message.id));
2218
2256
  const accepted = await new Promise(resolve => {
2219
- void this.handleSubmit({ text: queued.text, attachments: queued.attachments ?? [] }, queued.id, { preserveQueuedSource: true, onQueuedAdmission: () => resolve(true) })
2257
+ // Sent as whoever queued it: choosing Send now doesn't make another pane's line the person's.
2258
+ void this.handleSubmit({ text: queued.text, attachments: queued.attachments ?? [] }, queued.id, { preserveQueuedSource: true, onQueuedAdmission: () => resolve(true) }, false, false, queued.person === true, queued.via ?? 'terminal')
2220
2259
  .then(() => resolve(false), error => {
2221
2260
  this.addErrorMessage(`Queued task could not start: ${String(error)}`);
2222
2261
  resolve(false);
@@ -2226,13 +2265,52 @@ export class RatatuiApp {
2226
2265
  this.syncOwnPaneTaskControls();
2227
2266
  });
2228
2267
  });
2229
- reply(accepted ? 'applied' : 'blocked', accepted
2230
- ? 'Selected queued task admitted.' : 'Queued task is retained. Resolve the current admission before sending it.');
2268
+ // A command admits no turn: it has run once handleSubmit took it off the queue.
2269
+ const ran = command && !accepted && !this.controller.getQueue().some(candidate => candidate.id === queued.id);
2270
+ reply(accepted || ran ? 'applied' : 'blocked', accepted ? 'Selected queued task admitted.'
2271
+ : ran ? this.queuedCommandOutcome(before)
2272
+ : 'Queued task is retained. Resolve the current admission before sending it.');
2273
+ return;
2274
+ }
2275
+ if (command) {
2276
+ // One that can't run during a turn would be refused now and lost from the queue. It stays queued instead, moved
2277
+ // to the front as the idle Send now moves it, so it is the first to run when the turn ends, as whoever queued it.
2278
+ if (route.type === 'command' && waitsForTurnEnd(route.cmd, route.args)) {
2279
+ const ordered = await this.persistQueuedCorrectionOrder(this.queueIdsWithFirst(queued.id));
2280
+ this.dispatchPendingAgentWork();
2281
+ if (ordered !== 'saved') {
2282
+ reply(ordered === 'failed' ? 'persistence_failed' : 'not_queued', ordered === 'failed'
2283
+ ? "Queued command can't run during a turn, and it was not moved to the front of the queue because its checkpoint could not be saved."
2284
+ : 'The queue changed before this move.');
2285
+ return;
2286
+ }
2287
+ // Stop pauses the queue, and then nothing in it runs when the turn ends.
2288
+ reply('blocked', this.queuePaused
2289
+ ? "Queued command can't run during a turn. It is now first in the queue, which is paused: it runs when you send it again or resume the queue."
2290
+ : "Queued command can't run during a turn. It is now first in the queue and runs when the turn ends.");
2291
+ return;
2292
+ }
2293
+ // Taken off the queue as its idle flush takes it, then run as it would be if typed now.
2294
+ this.markHandoffDelivery([queued.id], 'unknown');
2295
+ this.controller.removeQueueEntry(queued.id);
2296
+ this.reconcileQueueEdit();
2297
+ const before = new Set(this.controller.getState().messages.map(message => message.id));
2298
+ try {
2299
+ await this.handleSubmit({ text: queued.text, attachments: queued.attachments ?? [] }, undefined, undefined, false, false, queued.person === true, queued.via ?? 'terminal');
2300
+ reply('applied', this.queuedCommandOutcome(before));
2301
+ }
2302
+ catch (error) {
2303
+ this.addErrorMessage(`Queued command could not run: ${String(error)}`);
2304
+ reply('invalid', `Queued command could not run: ${error instanceof Error ? error.message : String(error)}`);
2305
+ }
2306
+ finally {
2307
+ this.dispatchPendingAgentWork();
2308
+ }
2231
2309
  return;
2232
2310
  }
2233
2311
  this.handoffQueueSaveInFlight = true;
2234
2312
  try {
2235
- const accepted = await this.admitBusySteering({ text: queued.text, attachments: queued.attachments ?? [] }, this.busyInputEpoch, { entry: queued, correction, source });
2313
+ const accepted = await this.admitBusySteering({ text: queued.text, attachments: queued.attachments ?? [] }, this.busyInputEpoch, { entry: queued, correction, source }, queued.person === true);
2236
2314
  reply(accepted ? 'applied' : 'persistence_failed', accepted
2237
2315
  ? 'Queued task will steer the current run at its next admission boundary.'
2238
2316
  : 'Queued task was not sent; its original source is retained.');
@@ -2259,6 +2337,25 @@ export class RatatuiApp {
2259
2337
  reply(saved === 'saved' ? 'applied' : saved === 'failed' ? 'persistence_failed' : 'not_queued', saved === 'saved' ? 'Queued task updated.' : saved === 'failed'
2260
2338
  ? 'Queued task was not changed because its checkpoint could not be saved.' : 'This task is no longer queued.');
2261
2339
  }
2340
+ /** The queue's entry ids with ID first and the rest in their order: where Send now puts the entry it sends or keeps. */
2341
+ queueIdsWithFirst(id) {
2342
+ return [id, ...this.controller.getQueue().filter(candidate => candidate.id !== id).map(candidate => candidate.id)];
2343
+ }
2344
+ /**
2345
+ * What a command Send now ran says, for the desktop app: the last system line it added to the transcript, a refusal
2346
+ * included, in at most the 1 KiB of whole characters the app shows, or that it ran when it said nothing. BEFORE: the
2347
+ * transcript's message ids before it ran.
2348
+ */
2349
+ queuedCommandOutcome(before) {
2350
+ const said = this.controller.getState().messages
2351
+ .filter(message => message.role === 'system' && !before.has(message.id)).at(-1);
2352
+ if (!said)
2353
+ return 'Queued command ran.';
2354
+ const text = String(said.content);
2355
+ const bytes = Buffer.from(text, 'utf8');
2356
+ return bytes.length <= 1024 ? text
2357
+ : new TextDecoder('utf-8', { ignoreBOM: true }).decode(bytes.subarray(0, 1024), { stream: true });
2358
+ }
2262
2359
  /**
2263
2360
  * Recreate the live agent in place (new backend resolved from current config)
2264
2361
  * and re-arm the hook watcher. Shared by /accounts use — both the CLI command
@@ -8664,10 +8761,19 @@ export class RatatuiApp {
8664
8761
  submitPersonInput(rawInput, via = 'terminal') {
8665
8762
  return this.handleSubmit(rawInput, undefined, undefined, false, false, true, via);
8666
8763
  }
8764
+ /**
8765
+ * Who entered input the queue holds for later, kept with its entry: handleSubmit's `person` and `via`. Each place
8766
+ * that sends a queued entry passes them back (`entry.person === true`, `entry.via ?? 'terminal'`), so the person's
8767
+ * line runs as theirs and relayed input stays relayed.
8768
+ */
8769
+ queueOrigin(person, via) {
8770
+ return person ? { person: true, ...(via === 'terminal' ? {} : { via }) } : {};
8771
+ }
8667
8772
  /**
8668
8773
  * `person`: the person entered this input themselves (see submitPersonInput). A /loop tick, a goal continuation,
8669
- * another pane's or the coordinator's message, a pane's initial task and a queued entry never are, so none of them
8670
- * passes a Zerg Router refusal the process holds. `via`: where the person entered it, this ZTC's terminal or the
8774
+ * another pane's or the coordinator's message and a pane's initial task never are, so none of them passes a Zerg
8775
+ * Router refusal the process holds; a queued entry is whoever queued it (QueueEntry.person and QueueEntry.via, which
8776
+ * the queue passes back here). `via`: where the person entered it, this ZTC's terminal or the
8671
8777
  * browser mirror, or else the mirror's /broadcast, which only colony's AgentBridge posts to (the overseer's
8672
8778
  * send_to_worktree tool and the colony dashboard's send). In a ZTC another ZTC launched into one of its panes, what
8673
8779
  * the terminal gives it isn't only the person's, and what /broadcast gives any ZTC never is (see the origin below).
@@ -8705,10 +8811,22 @@ export class RatatuiApp {
8705
8811
  this.addSystemMessage('Account or model change in progress; run the key command again when it finishes.');
8706
8812
  return;
8707
8813
  }
8708
- // Preserve ingress while settings/reload owns admission; do not interrupt a disposed backend.
8709
- const retained = this.controller.enqueueMessage(input, 'end-of-turn');
8710
- this.addSystemMessage(retained ? 'Account or model change in progress; input retained in the queue.'
8711
- : 'Account or model change in progress; queue is full. Retry this input when the change finishes.');
8814
+ // Preserve ingress while settings/reload owns admission; do not interrupt a disposed backend. The entry keeps
8815
+ // who entered it, so it runs as theirs once the change ends.
8816
+ if (!this.controller.enqueueMessage(input, 'end-of-turn', this.queueOrigin(person, via))) {
8817
+ this.addSystemMessage('Account or model change in progress; queue is full. Retry this input when the change finishes.');
8818
+ return;
8819
+ }
8820
+ // Its notice is its source in the transcript, images included, as Tab's breadcrumb is a Tab-queued line's, so the
8821
+ // queue controls move, edit, remove and send it like any other queued line, the desktop app's during the change
8822
+ // too. The session's checkpoint keeps an image sent with no text only with its image.
8823
+ const notice = 'Account or model change in progress; input retained in the queue.';
8824
+ this.controller.addMessage({ role: 'system', content: notice, ...(attachments.length ? { attachments } : {}) });
8825
+ this.mirror?.publishMessage('system', notice, attachments.length ? { attachments } : undefined);
8826
+ const entry = this.controller.getQueue().at(-1);
8827
+ const source = this.controller.getState().messages.at(-1);
8828
+ this.recordHandoffCorrection(source.id, { id: entry.id, text: entry.text, delivery: 'end-of-turn',
8829
+ deliveryState: 'pending', queuedAt: entry.queuedAt.toISOString(), sourceMessageId: source.id });
8712
8830
  return;
8713
8831
  }
8714
8832
  // If a recap from the previous turn is still pending, cancel it — otherwise
@@ -8725,19 +8843,10 @@ export class RatatuiApp {
8725
8843
  return;
8726
8844
  }
8727
8845
  if (route.type === 'command') {
8728
- const subcommand = route.args[0]?.toLowerCase();
8729
- const modeConfigRead = route.cmd === 'mode'
8730
- && (route.args.length === 0
8731
- || subcommand === 'list'
8732
- || route.args[1]?.toLowerCase() === 'config');
8733
- const changesRuntimeMode = route.cmd === 'model' || route.cmd === 'plan'
8734
- || route.cmd === 'execute'
8735
- || route.cmd === 'exit-mode'
8736
- || (route.cmd === 'mode' && !modeConfigRead);
8737
8846
  const agentStatus = this.controller.getState().agentState.status;
8738
8847
  const agentBusy = this.isAgentBusy()
8739
8848
  || (agentStatus !== 'idle' && agentStatus !== 'error');
8740
- if (changesRuntimeMode && agentBusy) {
8849
+ if (changesRuntimeMode(route.cmd, route.args) && agentBusy) {
8741
8850
  this.addSystemMessage('Cannot change modes while an agent turn is active. Cancel it or wait for completion.');
8742
8851
  return;
8743
8852
  }
@@ -8773,7 +8882,7 @@ export class RatatuiApp {
8773
8882
  this.reconcileQueueEdit();
8774
8883
  }
8775
8884
  // A command the person didn't enter themselves (another pane's or the coordinator's message, a pane's stdin,
8776
- // a /loop tick, a queued entry) runs as relayed input: choices only the person makes refuse it. So does what a
8885
+ // a /loop tick) runs as relayed input, queued or not: choices only the person makes refuse it. So does what a
8777
8886
  // ZTC that another ZTC launched into one of its panes reads from its terminal, whatever its flags: a ZTC pane's
8778
8887
  // ztc-tui, or a colony cell's own zmux, reads a PTY that the overseer's write_terminal_pane and other panes type
8779
8888
  // into too, so the person's typing there can't be told from theirs. A colony cell's own browser mirror is still
@@ -10694,7 +10803,7 @@ export class RatatuiApp {
10694
10803
  // Flushing is also subscribed to idle transitions in start().
10695
10804
  const processedQueue = this.controller.getQueue().length > 0 || this.maybeFlushQueue();
10696
10805
  if (strandedSubturn) {
10697
- void this.handleSubmit({ text: strandedSubturn.text, attachments: strandedSubturn.attachments || [] });
10806
+ void this.handleSubmit({ text: strandedSubturn.text, attachments: strandedSubturn.attachments || [] }, undefined, undefined, false, false, strandedSubturn.person === true, strandedSubturn.via ?? 'terminal');
10698
10807
  return;
10699
10808
  }
10700
10809
  // If nothing the user queued is taking the next turn, let an active /goal
@@ -10914,6 +11023,11 @@ export class RatatuiApp {
10914
11023
  maybeFlushQueue() {
10915
11024
  if (this.exiting)
10916
11025
  return false;
11026
+ // An account or model change holds the queue until it ends, and its end dispatches pending work, this flush
11027
+ // included. An idle edge meanwhile (an error's idle flip) sent the head into the change, which held it again as a
11028
+ // new entry, and again, in a loop that never yielded.
11029
+ if (this.runtimeMutationInFlight)
11030
+ return false;
10917
11031
  if (this.agentTurnOwner || this.waitingInteraction || this.pendingAgentTurn
10918
11032
  || this.pendingPlanApproval || this.pendingAskUser || this.queuePaused || this.workspacePaused || this.workspaceResuming)
10919
11033
  return false;
@@ -10947,7 +11061,7 @@ export class RatatuiApp {
10947
11061
  return false;
10948
11062
  }
10949
11063
  const next = this.controller.getQueue()[index];
10950
- void this.handleSubmit({ text: next.text, attachments: next.attachments || [] }, next.id).finally(() => {
11064
+ void this.handleSubmit({ text: next.text, attachments: next.attachments || [] }, next.id, undefined, false, false, next.person === true, next.via ?? 'terminal').finally(() => {
10951
11065
  this.flushingQueue = false;
10952
11066
  this.maybeFlushQueue();
10953
11067
  });
@@ -11117,8 +11231,9 @@ export class RatatuiApp {
11117
11231
  // `end-of-turn`: a Tab-queued prompt waits for the WHOLE turn to finish.
11118
11232
  // Marking the intent on the entry (instead of relying on the busy-state
11119
11233
  // `inputMode` at flush time) keeps the promise even if the user later runs
11120
- // /inputmode interrupt, which only governs what Enter does.
11121
- if (this.controller.enqueueMessage(capturedInput, 'end-of-turn')) {
11234
+ // /inputmode interrupt, which only governs what Enter does. The composer's
11235
+ // line is the person's, as it would be on Enter: it runs as theirs.
11236
+ if (this.controller.enqueueMessage(capturedInput, 'end-of-turn', this.queueOrigin(true, 'terminal'))) {
11122
11237
  const entry = this.controller.getQueue().at(-1);
11123
11238
  const breadcrumb = `Queued (${this.controller.getQueue().length}) — sends when the turn finishes`;
11124
11239
  // The exact text is part of the transcript source, not a queue side
@@ -11343,6 +11458,11 @@ export class RatatuiApp {
11343
11458
  this.controller.setToast("Not saved: a key command can't wait in the queue. Run it from the composer.");
11344
11459
  return 'failed';
11345
11460
  }
11461
+ // The editor shows a queued line's text only, so a line left as it was stays as it is: an image queued with no text
11462
+ // isn't a prompt emptied here, and walking over it keeps it.
11463
+ const entry = this.controller.getQueue().find(candidate => candidate.id === entryId);
11464
+ if (entry && text === entry.text)
11465
+ return 'saved';
11346
11466
  return this.persistQueuedCorrectionEdit(entryId, text.trim() ? text : null);
11347
11467
  }
11348
11468
  /**
package/dist/config.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { modelContract } from '@zerg/model-contracts';
2
2
  import { isLocalSubscriptionProvider } from './agent/backends/provider_ids.js';
3
3
  import { resolveRouterModel, readRouterCatalog } from './utils/router_catalog.js';
4
- import { dirname, join } from 'path';
5
- import { stat, readFile, writeFile, mkdir, chmod, rm, unlink, rename, realpath } from 'fs/promises';
4
+ import { dirname, join, resolve } from 'path';
5
+ import { stat, readFile, readlink, writeFile, mkdir, rm, unlink, rename, realpath } from 'fs/promises';
6
6
  import { statSync } from 'fs';
7
7
  import { homedir } from 'os';
8
8
  import { randomUUID } from 'crypto';
@@ -418,19 +418,15 @@ function migrateSettingsDefaults(saved) {
418
418
  return migrated;
419
419
  }
420
420
  /**
421
- * Replace a settings file's contents atomically. A symlinked config (dotfiles
422
- * setups) is written at its target, so the link keeps pointing at the file ZTC
423
- * reads instead of being replaced by a copy.
421
+ * Replace a settings file's contents atomically: the text is written whole to
422
+ * a new owner-only (0600) file beside it, which then takes its place, so a
423
+ * reader in another process sees the old file or the new one, never part of
424
+ * one. A symlinked config (dotfiles setups) is written at its target, made if
425
+ * it doesn't exist yet, so the link keeps pointing at the file ZTC reads
426
+ * instead of being replaced by a copy.
424
427
  */
425
428
  async function replaceSettingsFile(path, text) {
426
- let target = path;
427
- try {
428
- target = await realpath(path);
429
- }
430
- catch (error) {
431
- if (error.code !== 'ENOENT')
432
- throw error;
433
- }
429
+ const target = await settingsFileTarget(path);
434
430
  const temporary = `${target}.${process.pid}.${randomUUID()}.tmp`;
435
431
  try {
436
432
  await writeFile(temporary, text, { encoding: 'utf-8', mode: 0o600, flag: 'wx' });
@@ -446,6 +442,35 @@ async function replaceSettingsFile(path, text) {
446
442
  }
447
443
  }
448
444
  }
445
+ /**
446
+ * Where a write to PATH lands: the file at the end of its symlinks, which may
447
+ * not exist yet (a link made before its file), or PATH itself.
448
+ */
449
+ async function settingsFileTarget(path) {
450
+ try {
451
+ return await realpath(path);
452
+ }
453
+ catch (error) {
454
+ if (error.code !== 'ENOENT')
455
+ throw error;
456
+ }
457
+ let target = path;
458
+ for (let links = 0; links < 32; links += 1) {
459
+ let link;
460
+ try {
461
+ link = await readlink(target);
462
+ }
463
+ catch (error) {
464
+ // Missing (ENOENT) or not a link (EINVAL): the write makes this file.
465
+ const code = error.code;
466
+ if (code === 'ENOENT' || code === 'EINVAL')
467
+ return target;
468
+ throw error;
469
+ }
470
+ target = resolve(dirname(target), link);
471
+ }
472
+ throw Object.assign(new Error(`Too many symbolic links: ${path}`), { code: 'ELOOP' });
473
+ }
449
474
  /** Write a backup once; an existing file of that name is never overwritten. */
450
475
  async function writeBackupOnce(path, text) {
451
476
  try {
@@ -1106,10 +1131,11 @@ export class ConfigStore {
1106
1131
  record[key] = saved;
1107
1132
  }
1108
1133
  // config.json holds secrets (apiKey, apiKeys, auth.token) — keep it owner-
1109
- // only. writeFile's mode applies only when it CREATES the file, so also
1110
- // chmod to tighten an existing 0644 file left by an earlier ZTC.
1111
- await writeFile(path, JSON.stringify(toSave, null, 2), { encoding: 'utf-8', mode: 0o600 });
1112
- await chmod(path, 0o600);
1134
+ // only. Another ZTC may read it at any moment (one launching starts from
1135
+ // the defaults if it can't parse it), so it is never rewritten in place:
1136
+ // the new file is made whole at 0600 and takes the old one's place, which
1137
+ // also replaces a 0644 file left by an earlier ZTC.
1138
+ await replaceSettingsFile(path, JSON.stringify(toSave, null, 2));
1113
1139
  }
1114
1140
  catch (err) {
1115
1141
  runtimeDiag('error', `Failed to save config: ${err?.message ?? err}`);
@@ -305,10 +305,13 @@ export declare class HeadlessApp {
305
305
  private cancelActiveRun;
306
306
  private executeCommand;
307
307
  /**
308
- * Run a single prompt through the agent
308
+ * Run a single prompt through the agent. `relayed`: nobody typed the prompt (a /loop tick, which
309
+ * CommandContext.submitUserPrompt submits), so a command in it runs as relayed input, which choices only the person
310
+ * makes refuse (see CommandContext.commandOrigin).
309
311
  */
310
312
  runPrompt(prompt: string, opts?: {
311
313
  automaticGoalTurn?: boolean;
314
+ relayed?: boolean;
312
315
  }): Promise<void>;
313
316
  private runPromptAdmitted;
314
317
  private buildTriggeredWorkflow;
package/dist/headless.js CHANGED
@@ -2188,11 +2188,12 @@ export class HeadlessApp {
2188
2188
  submitUserPrompt: (text) => {
2189
2189
  // Defer so a /loop tick never re-enters runPrompt synchronously; drop a
2190
2190
  // tick if the previous submission is still running to avoid overlap.
2191
+ // Nobody typed it, so it runs as relayed input, as in the TUI.
2191
2192
  setTimeout(() => {
2192
2193
  if (this.loopSubmitInFlight)
2193
2194
  return;
2194
2195
  this.loopSubmitInFlight = true;
2195
- void this.runPrompt(text).finally(() => { this.loopSubmitInFlight = false; });
2196
+ void this.runPrompt(text, { relayed: true }).finally(() => { this.loopSubmitInFlight = false; });
2196
2197
  }, 0);
2197
2198
  },
2198
2199
  getHooksStatus: () => this.hookLifecycle.getStatus(),
@@ -2241,7 +2242,9 @@ export class HeadlessApp {
2241
2242
  return `Unknown command: /${cmd}`;
2242
2243
  }
2243
2244
  /**
2244
- * Run a single prompt through the agent
2245
+ * Run a single prompt through the agent. `relayed`: nobody typed the prompt (a /loop tick, which
2246
+ * CommandContext.submitUserPrompt submits), so a command in it runs as relayed input, which choices only the person
2247
+ * makes refuse (see CommandContext.commandOrigin).
2245
2248
  */
2246
2249
  async runPrompt(prompt, opts = {}) {
2247
2250
  this.routerRefusedTurn = false;
@@ -2266,8 +2269,9 @@ export class HeadlessApp {
2266
2269
  // A pane child's prompts arrive on stdin from its parent: the overseer's write_terminal_pane, another pane or
2267
2270
  // the mux, never only the person typing. So do the prompts of any run another ZTC launched (ZTC_PARENT_PID or
2268
2271
  // ZTC_COLONY_CHILD), whatever its flags: its prompt and stdin are the launcher's. Their commands run as relayed
2269
- // input, which choices only the person makes refuse (see CommandContext.commandOrigin).
2270
- const relayed = this.options.paneChild || launchedByAnotherZtc();
2272
+ // input, which choices only the person makes refuse (see CommandContext.commandOrigin), and so do a /loop's
2273
+ // ticks in any run.
2274
+ const relayed = opts.relayed === true || this.options.paneChild || launchedByAnotherZtc();
2271
2275
  const output = await this.executeCommand(route.cmd, route.args, relayed ? 'relayed' : 'user');
2272
2276
  await this.saveCurrentSession();
2273
2277
  if (isCommandRefusal(output)) {
@@ -285,7 +285,10 @@ export async function prepareSessionMedia(options) {
285
285
  const byBlob = new Map();
286
286
  for (const asset of physical)
287
287
  byBlob.set(basename(asset.file), asset.file);
288
- for (const attachment of applicable) {
288
+ // One attachment can stand in two messages (a queued input's notice and the message it runs as), cloned as one
289
+ // object: it is adopted once, and both refer to that copy. A second pass would find it already durable and look
290
+ // for that reference in the checkpoint on disk, which this save has yet to write.
291
+ for (const attachment of new Set(applicable)) {
289
292
  let source;
290
293
  try {
291
294
  if (attachment.durable !== undefined) {
package/dist/types.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { RequestContentBlock, RequestMetrics, TokenUsage } from './agent/backends/types.js';
2
2
  import type { EvidenceSnapshot } from './agent/runtime/evidence.js';
3
+ import type { MirrorInputVia } from './web/mirror_stream.js';
3
4
  export type MessageRole = 'user' | 'assistant' | 'tool' | 'system';
4
5
  export type ToolStatus = 'pending' | 'running' | 'complete' | 'error';
5
6
  export type AgentStatus = 'idle' | 'thinking' | 'tool_use' | 'streaming' | 'error';
@@ -39,7 +40,22 @@ export interface QueueEntry {
39
40
  * `end-of-turn` (the conservative "wait for the whole turn" behavior).
40
41
  */
41
42
  delivery?: DeliveryIntent;
43
+ /**
44
+ * The person entered this entry themselves (typed, dictated, or sent from
45
+ * the browser mirror), so it runs as theirs when it is sent: with the
46
+ * choices only they make, such as where dictation transcribes, and one real
47
+ * attempt past a Zerg Router refusal. Absent: input relayed to this ZTC (a
48
+ * /loop tick, another pane's message), which stays relayed when queued.
49
+ */
50
+ person?: boolean;
51
+ /**
52
+ * Where the person entered it, when not at this ZTC's own terminal: the
53
+ * browser mirror, or a mirror's /broadcast (see the TUI's handleSubmit).
54
+ */
55
+ via?: MirrorInputVia;
42
56
  }
57
+ /** Who entered a queued entry, kept with it until it is sent (see QueueEntry.person). */
58
+ export type QueueEntryOrigin = Pick<QueueEntry, 'person' | 'via'>;
43
59
  export interface ToolCall {
44
60
  id: string;
45
61
  name: string;
@@ -272,10 +272,13 @@ export function getDictationUnavailableReason() {
272
272
  const macos = macOSNotUsedReason(choice);
273
273
  return macos ? `${NO_ENGINE} ${macos}` : NO_ENGINE;
274
274
  }
275
- /** Where the person chooses where dictation transcribes, in the words ZTC's UI uses, and what can't choose it. */
275
+ /**
276
+ * Where the person chooses where dictation transcribes, in the words ZTC's UI uses, and what can't choose it. The
277
+ * queue isn't among them: a choice the person queues is still theirs when it runs, and relayed input stays relayed.
278
+ */
276
279
  const ONLY_THE_PERSON_CHOOSES = 'in ZTC\'s main session (the Main pane in --mux, the desktop app and the browser mirror) or in a '
277
280
  + 'ztc you run yourself. Typing in a ZTC pane or a colony cell can\'t choose it, since ZTC can\'t tell your typing there from '
278
- + 'what the overseer\'s write_terminal_pane or another pane types in, and neither can a bus message, a /loop or the queue.';
281
+ + 'what the overseer\'s write_terminal_pane or another pane types in, and neither can a bus message or a /loop.';
279
282
  /**
280
283
  * What choosing where dictation transcribes says to input that isn't the person's own (a command or settings panel
281
284
  * whose CommandContext.commandOrigin is 'relayed'): nothing was saved, and where the person makes the choice, `how`