@zergai/ztc 0.13.1-dev.202611081058 → 0.14.1-dev.202611082047

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.
Binary file
Binary file
Binary file
Binary file
Binary file
@@ -216,7 +216,8 @@ export declare class Agent {
216
216
  /** One-shot: the next request carries the output-limit note at this effort. */
217
217
  /** The next request retries a discarded response: a note for the model, and lower effort when offered. */
218
218
  private responseRetry;
219
- /** One-shot: the next request starts a turn the person's own new message began (see admitPersonRequest). */
219
+ /** The person's attempt (admitPersonRequest), waiting for the run that takes it: the next to start, or the one whose
220
+ * steering admitted it. */
220
221
  private personRequestPending;
221
222
  /** Fast mode — request the priority service tier from the Codex/GPT backend. */
222
223
  private _codexFastMode;
@@ -420,6 +421,9 @@ export declare class Agent {
420
421
  /**
421
422
  * The person just sent a new message: the next request this agent builds is theirs, and gets one real attempt even
422
423
  * while Zerg Router's refusal holds its route (they may have just raised the limit). Background turns never call it.
424
+ * Called before a run, it is that run's; called from a run's takeSteering, it is the running one's. A run that ends
425
+ * before the request that carries the message (a cancel, a failed steering admission, an error first) drops it, so a
426
+ * later turn nobody started never gets it.
423
427
  */
424
428
  admitPersonRequest(): void;
425
429
  /** Execute a host-bound or standalone turn through the same core loop. */
@@ -208,7 +208,8 @@ export class Agent {
208
208
  /** One-shot: the next request carries the output-limit note at this effort. */
209
209
  /** The next request retries a discarded response: a note for the model, and lower effort when offered. */
210
210
  responseRetry = null;
211
- /** One-shot: the next request starts a turn the person's own new message began (see admitPersonRequest). */
211
+ /** The person's attempt (admitPersonRequest), waiting for the run that takes it: the next to start, or the one whose
212
+ * steering admitted it. */
212
213
  personRequestPending = false;
213
214
  /** Fast mode — request the priority service tier from the Codex/GPT backend. */
214
215
  _codexFastMode;
@@ -1617,6 +1618,9 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1617
1618
  /**
1618
1619
  * The person just sent a new message: the next request this agent builds is theirs, and gets one real attempt even
1619
1620
  * while Zerg Router's refusal holds its route (they may have just raised the limit). Background turns never call it.
1621
+ * Called before a run, it is that run's; called from a run's takeSteering, it is the running one's. A run that ends
1622
+ * before the request that carries the message (a cancel, a failed steering admission, an error first) drops it, so a
1623
+ * later turn nobody started never gets it.
1620
1624
  */
1621
1625
  admitPersonRequest() {
1622
1626
  this.personRequestPending = true;
@@ -1629,12 +1633,31 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1629
1633
  const onInterrupt = () => { if (this.config.execution.interruptBackgroundJobs)
1630
1634
  void interruptCommandJobs(this.config.sessionId); };
1631
1635
  signal?.addEventListener('abort', onInterrupt, { once: true });
1636
+ // The person's attempt is this run's from here on, and ends with it. A run another starts while this one unwinds
1637
+ // (a cancel lets the next turn begin at once) keeps its own.
1638
+ const attempt = { pending: this.personRequestPending };
1639
+ this.personRequestPending = false;
1640
+ // Only an admission the take itself makes (the person's steering it hands over) is this run's. One already
1641
+ // pending belongs to the person's next message: a cancelled run still takes steering as it unwinds.
1642
+ const take = takeSteering && (() => {
1643
+ const pending = this.personRequestPending;
1644
+ this.personRequestPending = false;
1645
+ try {
1646
+ const taken = takeSteering();
1647
+ if (this.personRequestPending)
1648
+ attempt.pending = true;
1649
+ return taken;
1650
+ }
1651
+ finally {
1652
+ this.personRequestPending = pending;
1653
+ }
1654
+ });
1632
1655
  try {
1633
1656
  await this.recoverToolCheckpoint();
1634
1657
  await this.nativeEvidencePending;
1635
1658
  if (this.nativeEvidenceFailure)
1636
1659
  throw this.nativeEvidenceFailure;
1637
- result = await this.runBound(messages, signal, takeSteering, toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage);
1660
+ result = await this.runBound(messages, signal, take, toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage, attempt);
1638
1661
  return result;
1639
1662
  }
1640
1663
  catch (error) {
@@ -1666,10 +1689,10 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1666
1689
  }
1667
1690
  }
1668
1691
  }
1669
- async runBound(messages, signal, takeSteering, toolCheckpoint = this.toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage) {
1692
+ async runBound(messages, signal, takeSteering, toolCheckpoint = this.toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage, attempt = { pending: false }) {
1670
1693
  const binding = this.#conversationBinding;
1671
1694
  if (!binding)
1672
- return this.runCore(messages, signal, takeSteering, toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage);
1695
+ return this.runCore(messages, signal, takeSteering, toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage, attempt);
1673
1696
  const userMessage = [...messages].reverse().find((message) => message.role === 'user'
1674
1697
  && !message.metadata?.synthetic
1675
1698
  && !message.metadata?.toolResult);
@@ -1701,7 +1724,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1701
1724
  // The host driver publishes only the initial user and final assistant
1702
1725
  // for this turn. Leave busy input pending for a new hosted turn so the
1703
1726
  // authoritative conversation cannot silently omit it.
1704
- const result = await this.runCore(workingMessages, signal, undefined, toolCheckpoint, undefined, diagnosticTurn, onUsage);
1727
+ const result = await this.runCore(workingMessages, signal, undefined, toolCheckpoint, undefined, diagnosticTurn, onUsage, attempt);
1705
1728
  const assistantMessage = {
1706
1729
  id: `host_assistant_${randomUUID()}`,
1707
1730
  role: 'assistant',
@@ -1748,7 +1771,7 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1748
1771
  }
1749
1772
  }
1750
1773
  // Main execution loop shared by hosted and standalone turns.
1751
- async runCore(messages, signal, takeSteering, toolCheckpoint = this.toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage) {
1774
+ async runCore(messages, signal, takeSteering, toolCheckpoint = this.toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage, attempt = { pending: false }) {
1752
1775
  if (!this.hasApiKey()) {
1753
1776
  throw new AgentError('No API key configured. Use /config key <key> to set one.', 'NO_API_KEY');
1754
1777
  }
@@ -1833,8 +1856,8 @@ INVESTIGATION STRATEGY — before making tool calls to explore or debug, follow
1833
1856
  }
1834
1857
  const request = this.buildRequest(messages, availableTools);
1835
1858
  request.signal = signal;
1836
- if (this.personRequestPending) {
1837
- this.personRequestPending = false;
1859
+ if (attempt.pending) {
1860
+ attempt.pending = false;
1838
1861
  request.personInitiated = true;
1839
1862
  }
1840
1863
  request.onMetrics = metrics => {
@@ -55,9 +55,20 @@ export declare class CodexAuthManager {
55
55
  getAccountId(): string | undefined;
56
56
  /** Get a valid access token, refreshing if needed */
57
57
  getAccessToken(signal?: AbortSignal): Promise<string>;
58
- /** Serialize rotating-token updates within this process and across file-sharing processes. */
58
+ /**
59
+ * Serialize rotating-token updates within this process and across file-sharing processes. Concurrent callers (a
60
+ * simulation's actors on one account, say) share one refresh. A caller's cancel or deadline ends only its own wait,
61
+ * so one request never fails another's. Once every caller waiting on it has been cancelled, the refresh stops if it
62
+ * has not sent its request yet; one already sent runs to completion and saves its tokens (see performOAuthRefresh).
63
+ */
59
64
  refreshToken(signal?: AbortSignal | boolean, force?: boolean): Promise<void>;
65
+ private startRefresh;
60
66
  private refreshTokenWithLock;
67
+ /**
68
+ * SIGNAL can stop the refresh only up to here. OpenAI rotates the refresh token once it has the request and refuses
69
+ * the old one from then on, so the answer is the only copy of the new tokens: the request runs to completion (or its
70
+ * timeout) and they are saved, even when every caller has stopped waiting.
71
+ */
61
72
  private performOAuthRefresh;
62
73
  /** Decode JWT payload without a library (local trust boundary) */
63
74
  private decodeJwtPayload;
@@ -97,6 +97,20 @@ function throwIfRefreshAborted(signal) {
97
97
  throw new Error('Codex token refresh cancelled.');
98
98
  }
99
99
  }
100
+ /** REFRESH as one caller waits for it: when SIGNAL aborts, that caller alone stops waiting. */
101
+ function awaitRefresh(refresh, signal) {
102
+ if (!signal)
103
+ return refresh;
104
+ return new Promise((resolve, reject) => {
105
+ const cancelled = () => reject(new Error('Codex token refresh cancelled.'));
106
+ if (signal.aborted) {
107
+ cancelled();
108
+ return;
109
+ }
110
+ signal.addEventListener('abort', cancelled, { once: true });
111
+ void refresh.then(resolve, reject).finally(() => signal.removeEventListener('abort', cancelled));
112
+ });
113
+ }
100
114
  function parseCodexAuthData(data) {
101
115
  const authModePresent = data.auth_mode !== undefined;
102
116
  if (authModePresent && data.auth_mode !== 'chatgpt') {
@@ -219,7 +233,12 @@ export class CodexAuthManager {
219
233
  await this.refreshToken(signal);
220
234
  return this.credentials.access_token;
221
235
  }
222
- /** Serialize rotating-token updates within this process and across file-sharing processes. */
236
+ /**
237
+ * Serialize rotating-token updates within this process and across file-sharing processes. Concurrent callers (a
238
+ * simulation's actors on one account, say) share one refresh. A caller's cancel or deadline ends only its own wait,
239
+ * so one request never fails another's. Once every caller waiting on it has been cancelled, the refresh stops if it
240
+ * has not sent its request yet; one already sent runs to completion and saves its tokens (see performOAuthRefresh).
241
+ */
223
242
  async refreshToken(signal, force = false) {
224
243
  if (signal === true) {
225
244
  force = true;
@@ -230,18 +249,32 @@ export class CodexAuthManager {
230
249
  throwIfRefreshAborted(signal);
231
250
  if (!this.credentials)
232
251
  throw new Error('No credentials loaded');
233
- if (this.refreshInFlight)
234
- return this.refreshInFlight;
235
- const refresh = this.refreshTokenWithLock(signal, force);
236
- this.refreshInFlight = refresh;
252
+ let flight = this.refreshInFlight;
253
+ // A refresh all its callers gave up on is stopping, or finishing a request it already sent: let it settle first.
254
+ while (flight?.controller.signal.aborted) {
255
+ await awaitRefresh(flight.done.catch(() => undefined), signal);
256
+ flight = this.refreshInFlight;
257
+ }
258
+ flight ??= this.startRefresh(force);
259
+ flight.waiting += 1;
237
260
  try {
238
- await refresh;
261
+ await awaitRefresh(flight.done, signal);
239
262
  }
240
263
  finally {
241
- if (this.refreshInFlight === refresh)
242
- this.refreshInFlight = null;
264
+ flight.waiting -= 1;
265
+ if (flight.waiting === 0 && signal?.aborted)
266
+ flight.controller.abort(signal.reason);
243
267
  }
244
268
  }
269
+ startRefresh(force) {
270
+ const controller = new AbortController();
271
+ const flight = { done: this.refreshTokenWithLock(controller.signal, force), controller, waiting: 0 };
272
+ this.refreshInFlight = flight;
273
+ const settled = () => { if (this.refreshInFlight === flight)
274
+ this.refreshInFlight = null; };
275
+ flight.done.then(settled, settled);
276
+ return flight;
277
+ }
245
278
  async refreshTokenWithLock(signal, force) {
246
279
  const observed = { ...this.credentials };
247
280
  const lockfile = await loadFileLock();
@@ -262,13 +295,16 @@ export class CodexAuthManager {
262
295
  await release();
263
296
  }
264
297
  }
298
+ /**
299
+ * SIGNAL can stop the refresh only up to here. OpenAI rotates the refresh token once it has the request and refuses
300
+ * the old one from then on, so the answer is the only copy of the new tokens: the request runs to completion (or its
301
+ * timeout) and they are saved, even when every caller has stopped waiting.
302
+ */
265
303
  async performOAuthRefresh(signal) {
266
304
  if (!this.credentials)
267
305
  throw new Error('No credentials loaded');
306
+ throwIfRefreshAborted(signal);
268
307
  const timeoutSignal = AbortSignal.timeout(CODEX_OAUTH_TIMEOUT_MS);
269
- const requestSignal = signal
270
- ? AbortSignal.any([signal, timeoutSignal])
271
- : timeoutSignal;
272
308
  let res;
273
309
  try {
274
310
  res = await fetch(OAUTH_TOKEN_URL, {
@@ -279,13 +315,10 @@ export class CodexAuthManager {
279
315
  refresh_token: this.credentials.refresh_token,
280
316
  client_id: resolveClientId(this.credentials.client_id),
281
317
  }),
282
- signal: requestSignal,
318
+ signal: timeoutSignal,
283
319
  });
284
320
  }
285
321
  catch (e) {
286
- if (signal?.aborted) {
287
- throw new Error('Codex token refresh cancelled.');
288
- }
289
322
  if (timeoutSignal.aborted) {
290
323
  throw new Error('Codex token refresh timed out. Run \'codex\' to re-authenticate.');
291
324
  }
@@ -301,9 +334,6 @@ export class CodexAuthManager {
301
334
  rawData = JSON.parse(body);
302
335
  }
303
336
  catch (error) {
304
- if (signal?.aborted) {
305
- throw new Error('Codex token refresh cancelled.');
306
- }
307
337
  if (timeoutSignal.aborted) {
308
338
  throw new Error('Codex token refresh timed out. Run \'codex\' to re-authenticate.');
309
339
  }
@@ -317,10 +347,6 @@ export class CodexAuthManager {
317
347
  const accessToken = requiredTokenField(rawData, 'access_token');
318
348
  const refreshToken = optionalTokenField(rawData, 'refresh_token');
319
349
  const idToken = optionalTokenField(rawData, 'id_token');
320
- throwIfRefreshAborted(signal);
321
- if (timeoutSignal.aborted) {
322
- throw new Error('Codex token refresh timed out. Run \'codex\' to re-authenticate.');
323
- }
324
350
  const nextCredentials = {
325
351
  ...this.credentials,
326
352
  access_token: accessToken,
@@ -236,6 +236,17 @@ export declare class RatatuiApp {
236
236
  private dictationFilterModule;
237
237
  /** Busy Enter prompts waiting for the next completed tool batch. */
238
238
  private pendingSteering;
239
+ /**
240
+ * Steering the person entered (see submitPersonInput) that no request has carried yet. The first request that
241
+ * carries one is theirs: it gets their one attempt past a Zerg Router refusal, as their message would when idle.
242
+ */
243
+ private personSteeringIds;
244
+ /**
245
+ * The person entered a message (see submitPersonInput) that the next turn to start carries. That turn takes it as it
246
+ * starts and, once started, admits it on the agent that runs it (rebuilt meanwhile when the mode changed), so the
247
+ * request carrying the message gets their one attempt past a Zerg Router refusal. A turn that fails to start drops it.
248
+ */
249
+ private personMessagePending;
239
250
  private nativeSteeringInFlight;
240
251
  private steeringAdmissionCount;
241
252
  private nativeSteeringTail;
@@ -1076,6 +1087,8 @@ export declare class RatatuiApp {
1076
1087
  private maybeFlushQueue;
1077
1088
  /** Publish each accepted source once, at its actual admission boundary. */
1078
1089
  private revealAdmittedSteering;
1090
+ /** MESSAGES now go to the agent: when one is the person's own steering, the request that carries it is theirs. */
1091
+ private admitPersonSteering;
1079
1092
  /** Put steering that missed a tool boundary after the finished answer. */
1080
1093
  private movePendingSteeringToEnd;
1081
1094
  /** True while an agent turn is active (same definition as handleSubmit's busy check). */
@@ -541,6 +541,17 @@ export class RatatuiApp {
541
541
  dictationFilterModule = null;
542
542
  /** Busy Enter prompts waiting for the next completed tool batch. */
543
543
  pendingSteering = [];
544
+ /**
545
+ * Steering the person entered (see submitPersonInput) that no request has carried yet. The first request that
546
+ * carries one is theirs: it gets their one attempt past a Zerg Router refusal, as their message would when idle.
547
+ */
548
+ personSteeringIds = new Set();
549
+ /**
550
+ * The person entered a message (see submitPersonInput) that the next turn to start carries. That turn takes it as it
551
+ * starts and, once started, admits it on the agent that runs it (rebuilt meanwhile when the mode changed), so the
552
+ * request carrying the message gets their one attempt past a Zerg Router refusal. A turn that fails to start drops it.
553
+ */
554
+ personMessagePending = false;
544
555
  nativeSteeringInFlight = [];
545
556
  steeringAdmissionCount = 0;
546
557
  nativeSteeringTail = Promise.resolve();
@@ -2444,6 +2455,7 @@ export class RatatuiApp {
2444
2455
  this.taskHandoff = null;
2445
2456
  this.restoredHandoffCorrections = [];
2446
2457
  this.pendingSteering = [];
2458
+ this.personSteeringIds.clear();
2447
2459
  this.agent?.setTaskHandoff(null);
2448
2460
  this.publishTaskHandoff(null);
2449
2461
  this.mirror?.publishClear();
@@ -8739,7 +8751,7 @@ export class RatatuiApp {
8739
8751
  const inputMode = state.inputMode;
8740
8752
  if (busy) {
8741
8753
  if (inputMode === 'steer') {
8742
- await this.routeBusyInput(input);
8754
+ await this.routeBusyInput(input, person);
8743
8755
  return;
8744
8756
  }
8745
8757
  // Opt-in interruption retires the old owner before the replacement can
@@ -8798,7 +8810,7 @@ export class RatatuiApp {
8798
8810
  queuedAdmission?.onQueuedAdmission();
8799
8811
  // A message the person just entered gets one real attempt even while Zerg Router's refusal holds the route.
8800
8812
  if (person)
8801
- this.agent.admitPersonRequest();
8813
+ this.personMessagePending = true;
8802
8814
  // Run the agent on current messages
8803
8815
  await this.runAgent();
8804
8816
  }
@@ -9304,7 +9316,7 @@ export class RatatuiApp {
9304
9316
  }
9305
9317
  }
9306
9318
  /** Classify independently; admission decisions retain submission FIFO. */
9307
- async routeBusyInput(rawInput) {
9319
+ async routeBusyInput(rawInput, person = false) {
9308
9320
  const input = { ...rawInput, attachments: rawInput.attachments.map(attachment => ({ ...attachment })) };
9309
9321
  if (this.busyInputControllers.size >= MAX_QUEUE) {
9310
9322
  this.restoreBusyDraft(input);
@@ -9413,7 +9425,7 @@ export class RatatuiApp {
9413
9425
  this.restoreBusyDraft(input);
9414
9426
  return;
9415
9427
  }
9416
- await this.admitBusySteering(input, epoch);
9428
+ await this.admitBusySteering(input, epoch, undefined, person);
9417
9429
  }).catch(error => {
9418
9430
  if (!this.exiting) {
9419
9431
  this.restoreBusyDraft(input);
@@ -9491,7 +9503,7 @@ export class RatatuiApp {
9491
9503
  }
9492
9504
  this.render();
9493
9505
  }
9494
- async admitBusySteering(input, epoch, queuedSource) {
9506
+ async admitBusySteering(input, epoch, queuedSource, person = false) {
9495
9507
  const { text, attachments } = input;
9496
9508
  if (queuedSource) {
9497
9509
  const stillQueued = this.controller.getQueue().find(entry => entry.id === queuedSource.entry.id);
@@ -9554,6 +9566,8 @@ export class RatatuiApp {
9554
9566
  if (queuedSource)
9555
9567
  this.controller.removeQueueEntry(queuedSource.entry.id);
9556
9568
  this.pendingSteering.push(message);
9569
+ if (person)
9570
+ this.personSteeringIds.add(message.id);
9557
9571
  if (this.agent) {
9558
9572
  const activeAgent = this.agent;
9559
9573
  // Serial requests preserve the submitted order on a provider-owned
@@ -9561,6 +9575,7 @@ export class RatatuiApp {
9561
9575
  const attempt = this.nativeSteeringTail.then(() => (this.exiting || epoch !== this.busyInputEpoch) ? false : activeAgent.steerUserMessage(message)).then(accepted => {
9562
9576
  if (accepted && !this.exiting && epoch === this.busyInputEpoch) {
9563
9577
  this.pendingSteering = this.pendingSteering.filter(pending => pending.id !== message.id);
9578
+ this.personSteeringIds.delete(message.id);
9564
9579
  // The native acknowledgement owns this admission. Close the
9565
9580
  // preceding stream before exposing the correction's anchor.
9566
9581
  this.flushLocalStreamDelta();
@@ -9756,6 +9771,9 @@ export class RatatuiApp {
9756
9771
  }
9757
9772
  async runAgentTurn(isRetry, owner) {
9758
9773
  debugLog(`[runAgent] START isRetry=${isRetry}, pendingAskUser=${this.pendingAskUser}, askUserData=${this.askUserData?.questions.length ?? 'null'}`);
9774
+ // The person's message is this turn's from here on: admitted below if the turn starts, dropped if it does not.
9775
+ const personMessage = this.personMessagePending;
9776
+ this.personMessagePending = false;
9759
9777
  let initialMessageCount;
9760
9778
  let admittedMessages;
9761
9779
  try {
@@ -9853,6 +9871,10 @@ export class RatatuiApp {
9853
9871
  // pre-run write, so there's only one producer.
9854
9872
  this.startSpinner();
9855
9873
  this.revealAdmittedSteering(new Set(admittedMessages.map(message => message.id)));
9874
+ // On the agent that runs this turn: ensureAgentMatchesMode above may have replaced the one that held the message.
9875
+ if (personMessage)
9876
+ this.agent.admitPersonRequest();
9877
+ this.admitPersonSteering(admittedMessages);
9856
9878
  this.currentRunStreamed = false;
9857
9879
  this.finishLocalStreamingMessages();
9858
9880
  if (!isRetry) {
@@ -10166,13 +10188,15 @@ export class RatatuiApp {
10166
10188
  const steering = this.pendingSteering.splice(0);
10167
10189
  this.markHandoffDelivery(steering.map(message => message.id), 'unknown');
10168
10190
  const sources = new Map(this.controller.getState().messages.map(message => [message.id, message]));
10169
- return steering.flatMap(message => {
10191
+ const supplied = steering.flatMap(message => {
10170
10192
  const source = sources.get(message.id);
10171
10193
  if (!source)
10172
10194
  return [];
10173
10195
  suppliedSteeringIds.add(source.id);
10174
10196
  return [source];
10175
10197
  });
10198
+ this.admitPersonSteering(supplied);
10199
+ return supplied;
10176
10200
  }, checkpointHandler, async (checkpoint) => {
10177
10201
  const ownsAdmission = () => this.agentTurnOwner === owner
10178
10202
  && this.activeToolCheckpointHandler === checkpointHandler
@@ -10241,7 +10265,10 @@ export class RatatuiApp {
10241
10265
  this.pendingPlanApproval = false;
10242
10266
  this.pendingAskUser = false;
10243
10267
  this.askUserData = null;
10244
- this.movePendingSteeringToEnd();
10268
+ // A message entered during the turn steers it; one the failed turn never reached gets a turn of its own once
10269
+ // the error has shown, as it does after an answer.
10270
+ if (this.movePendingSteeringToEnd())
10271
+ this.pendingAgentTurn = true;
10245
10272
  this.controller.setAgentState({ status: 'error', error: errorMsg });
10246
10273
  this.stopSpinner();
10247
10274
  this.mirror?.publishStreamEnd();
@@ -10825,6 +10852,15 @@ export class RatatuiApp {
10825
10852
  this.mirror?.publishMessage('user', message.content, message.attachments?.length ? { attachments: message.attachments } : undefined);
10826
10853
  }
10827
10854
  }
10855
+ /** MESSAGES now go to the agent: when one is the person's own steering, the request that carries it is theirs. */
10856
+ admitPersonSteering(messages) {
10857
+ let person = false;
10858
+ for (const message of messages)
10859
+ if (this.personSteeringIds.delete(message.id))
10860
+ person = true;
10861
+ if (person)
10862
+ this.agent?.admitPersonRequest();
10863
+ }
10828
10864
  /** Put steering that missed a tool boundary after the finished answer. */
10829
10865
  movePendingSteeringToEnd() {
10830
10866
  if (this.pendingSteering.length === 0)
@@ -3637,6 +3637,18 @@ function throwIfRefreshAborted(signal) {
3637
3637
  throw new Error("Codex token refresh cancelled.");
3638
3638
  }
3639
3639
  }
3640
+ function awaitRefresh(refresh, signal) {
3641
+ if (!signal) return refresh;
3642
+ return new Promise((resolve20, reject) => {
3643
+ const cancelled = () => reject(new Error("Codex token refresh cancelled."));
3644
+ if (signal.aborted) {
3645
+ cancelled();
3646
+ return;
3647
+ }
3648
+ signal.addEventListener("abort", cancelled, { once: true });
3649
+ void refresh.then(resolve20, reject).finally(() => signal.removeEventListener("abort", cancelled));
3650
+ });
3651
+ }
3640
3652
  function parseCodexAuthData(data) {
3641
3653
  const authModePresent = data.auth_mode !== void 0;
3642
3654
  if (authModePresent && data.auth_mode !== "chatgpt") {
@@ -3773,7 +3785,12 @@ var init_codex_auth = __esm({
3773
3785
  await this.refreshToken(signal);
3774
3786
  return this.credentials.access_token;
3775
3787
  }
3776
- /** Serialize rotating-token updates within this process and across file-sharing processes. */
3788
+ /**
3789
+ * Serialize rotating-token updates within this process and across file-sharing processes. Concurrent callers (a
3790
+ * simulation's actors on one account, say) share one refresh. A caller's cancel or deadline ends only its own wait,
3791
+ * so one request never fails another's. Once every caller waiting on it has been cancelled, the refresh stops if it
3792
+ * has not sent its request yet; one already sent runs to completion and saves its tokens (see performOAuthRefresh).
3793
+ */
3777
3794
  async refreshToken(signal, force = false) {
3778
3795
  if (signal === true) {
3779
3796
  force = true;
@@ -3782,15 +3799,30 @@ var init_codex_auth = __esm({
3782
3799
  if (signal === false) signal = void 0;
3783
3800
  throwIfRefreshAborted(signal);
3784
3801
  if (!this.credentials) throw new Error("No credentials loaded");
3785
- if (this.refreshInFlight) return this.refreshInFlight;
3786
- const refresh = this.refreshTokenWithLock(signal, force);
3787
- this.refreshInFlight = refresh;
3802
+ let flight = this.refreshInFlight;
3803
+ while (flight?.controller.signal.aborted) {
3804
+ await awaitRefresh(flight.done.catch(() => void 0), signal);
3805
+ flight = this.refreshInFlight;
3806
+ }
3807
+ flight ??= this.startRefresh(force);
3808
+ flight.waiting += 1;
3788
3809
  try {
3789
- await refresh;
3810
+ await awaitRefresh(flight.done, signal);
3790
3811
  } finally {
3791
- if (this.refreshInFlight === refresh) this.refreshInFlight = null;
3812
+ flight.waiting -= 1;
3813
+ if (flight.waiting === 0 && signal?.aborted) flight.controller.abort(signal.reason);
3792
3814
  }
3793
3815
  }
3816
+ startRefresh(force) {
3817
+ const controller = new AbortController();
3818
+ const flight = { done: this.refreshTokenWithLock(controller.signal, force), controller, waiting: 0 };
3819
+ this.refreshInFlight = flight;
3820
+ const settled = () => {
3821
+ if (this.refreshInFlight === flight) this.refreshInFlight = null;
3822
+ };
3823
+ flight.done.then(settled, settled);
3824
+ return flight;
3825
+ }
3794
3826
  async refreshTokenWithLock(signal, force) {
3795
3827
  const observed2 = { ...this.credentials };
3796
3828
  const lockfile = await loadFileLock();
@@ -3812,10 +3844,15 @@ var init_codex_auth = __esm({
3812
3844
  await release2();
3813
3845
  }
3814
3846
  }
3847
+ /**
3848
+ * SIGNAL can stop the refresh only up to here. OpenAI rotates the refresh token once it has the request and refuses
3849
+ * the old one from then on, so the answer is the only copy of the new tokens: the request runs to completion (or its
3850
+ * timeout) and they are saved, even when every caller has stopped waiting.
3851
+ */
3815
3852
  async performOAuthRefresh(signal) {
3816
3853
  if (!this.credentials) throw new Error("No credentials loaded");
3854
+ throwIfRefreshAborted(signal);
3817
3855
  const timeoutSignal = AbortSignal.timeout(CODEX_OAUTH_TIMEOUT_MS);
3818
- const requestSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
3819
3856
  let res;
3820
3857
  try {
3821
3858
  res = await fetch(OAUTH_TOKEN_URL, {
@@ -3826,12 +3863,9 @@ var init_codex_auth = __esm({
3826
3863
  refresh_token: this.credentials.refresh_token,
3827
3864
  client_id: resolveClientId(this.credentials.client_id)
3828
3865
  }),
3829
- signal: requestSignal
3866
+ signal: timeoutSignal
3830
3867
  });
3831
3868
  } catch (e) {
3832
- if (signal?.aborted) {
3833
- throw new Error("Codex token refresh cancelled.");
3834
- }
3835
3869
  if (timeoutSignal.aborted) {
3836
3870
  throw new Error("Codex token refresh timed out. Run 'codex' to re-authenticate.");
3837
3871
  }
@@ -3850,9 +3884,6 @@ var init_codex_auth = __esm({
3850
3884
  const body = await readBoundedResponsesText(res, CODEX_OAUTH_RESPONSE_BYTES);
3851
3885
  rawData = JSON.parse(body);
3852
3886
  } catch (error62) {
3853
- if (signal?.aborted) {
3854
- throw new Error("Codex token refresh cancelled.");
3855
- }
3856
3887
  if (timeoutSignal.aborted) {
3857
3888
  throw new Error("Codex token refresh timed out. Run 'codex' to re-authenticate.");
3858
3889
  }
@@ -3865,10 +3896,6 @@ var init_codex_auth = __esm({
3865
3896
  const accessToken = requiredTokenField(rawData, "access_token");
3866
3897
  const refreshToken = optionalTokenField(rawData, "refresh_token");
3867
3898
  const idToken = optionalTokenField(rawData, "id_token");
3868
- throwIfRefreshAborted(signal);
3869
- if (timeoutSignal.aborted) {
3870
- throw new Error("Codex token refresh timed out. Run 'codex' to re-authenticate.");
3871
- }
3872
3899
  const nextCredentials = {
3873
3900
  ...this.credentials,
3874
3901
  access_token: accessToken,
@@ -41430,7 +41457,8 @@ var Agent = class _Agent {
41430
41457
  /** One-shot: the next request carries the output-limit note at this effort. */
41431
41458
  /** The next request retries a discarded response: a note for the model, and lower effort when offered. */
41432
41459
  responseRetry = null;
41433
- /** One-shot: the next request starts a turn the person's own new message began (see admitPersonRequest). */
41460
+ /** The person's attempt (admitPersonRequest), waiting for the run that takes it: the next to start, or the one whose
41461
+ * steering admitted it. */
41434
41462
  personRequestPending = false;
41435
41463
  /** Fast mode — request the priority service tier from the Codex/GPT backend. */
41436
41464
  _codexFastMode;
@@ -42767,6 +42795,9 @@ ${this.runtimeContext}` : this.config.systemPrompt;
42767
42795
  /**
42768
42796
  * The person just sent a new message: the next request this agent builds is theirs, and gets one real attempt even
42769
42797
  * while Zerg Router's refusal holds its route (they may have just raised the limit). Background turns never call it.
42798
+ * Called before a run, it is that run's; called from a run's takeSteering, it is the running one's. A run that ends
42799
+ * before the request that carries the message (a cancel, a failed steering admission, an error first) drops it, so a
42800
+ * later turn nobody started never gets it.
42770
42801
  */
42771
42802
  admitPersonRequest() {
42772
42803
  this.personRequestPending = true;
@@ -42780,11 +42811,24 @@ ${this.runtimeContext}` : this.config.systemPrompt;
42780
42811
  if (this.config.execution.interruptBackgroundJobs) void interruptCommandJobs(this.config.sessionId);
42781
42812
  };
42782
42813
  signal?.addEventListener("abort", onInterrupt, { once: true });
42814
+ const attempt = { pending: this.personRequestPending };
42815
+ this.personRequestPending = false;
42816
+ const take = takeSteering && (() => {
42817
+ const pending2 = this.personRequestPending;
42818
+ this.personRequestPending = false;
42819
+ try {
42820
+ const taken = takeSteering();
42821
+ if (this.personRequestPending) attempt.pending = true;
42822
+ return taken;
42823
+ } finally {
42824
+ this.personRequestPending = pending2;
42825
+ }
42826
+ });
42783
42827
  try {
42784
42828
  await this.recoverToolCheckpoint();
42785
42829
  await this.nativeEvidencePending;
42786
42830
  if (this.nativeEvidenceFailure) throw this.nativeEvidenceFailure;
42787
- result = await this.runBound(messages, signal, takeSteering, toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage);
42831
+ result = await this.runBound(messages, signal, take, toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage, attempt);
42788
42832
  return result;
42789
42833
  } catch (error62) {
42790
42834
  failure2 = error62;
@@ -42807,9 +42851,9 @@ ${this.runtimeContext}` : this.config.systemPrompt;
42807
42851
  }
42808
42852
  }
42809
42853
  }
42810
- async runBound(messages, signal, takeSteering, toolCheckpoint = this.toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage) {
42854
+ async runBound(messages, signal, takeSteering, toolCheckpoint = this.toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage, attempt = { pending: false }) {
42811
42855
  const binding2 = this.#conversationBinding;
42812
- if (!binding2) return this.runCore(messages, signal, takeSteering, toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage);
42856
+ if (!binding2) return this.runCore(messages, signal, takeSteering, toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage, attempt);
42813
42857
  const userMessage = [...messages].reverse().find(
42814
42858
  (message) => message.role === "user" && !message.metadata?.synthetic && !message.metadata?.toolResult
42815
42859
  );
@@ -42844,7 +42888,7 @@ ${this.runtimeContext}` : this.config.systemPrompt;
42844
42888
  if (!workingMessages.some((message) => message.id === userMessage.id)) {
42845
42889
  workingMessages.push({ ...userMessage });
42846
42890
  }
42847
- const result = await this.runCore(workingMessages, signal, void 0, toolCheckpoint, void 0, diagnosticTurn, onUsage);
42891
+ const result = await this.runCore(workingMessages, signal, void 0, toolCheckpoint, void 0, diagnosticTurn, onUsage, attempt);
42848
42892
  const assistantMessage = {
42849
42893
  id: `host_assistant_${randomUUID14()}`,
42850
42894
  role: "assistant",
@@ -42882,7 +42926,7 @@ ${this.runtimeContext}` : this.config.systemPrompt;
42882
42926
  }
42883
42927
  }
42884
42928
  // Main execution loop shared by hosted and standalone turns.
42885
- async runCore(messages, signal, takeSteering, toolCheckpoint = this.toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage) {
42929
+ async runCore(messages, signal, takeSteering, toolCheckpoint = this.toolCheckpoint, steeringAdmission, diagnosticTurn, onUsage, attempt = { pending: false }) {
42886
42930
  if (!this.hasApiKey()) {
42887
42931
  throw new AgentError("No API key configured. Use /config key <key> to set one.", "NO_API_KEY");
42888
42932
  }
@@ -42960,8 +43004,8 @@ ${this.runtimeContext}` : this.config.systemPrompt;
42960
43004
  }
42961
43005
  const request2 = this.buildRequest(messages, availableTools);
42962
43006
  request2.signal = signal;
42963
- if (this.personRequestPending) {
42964
- this.personRequestPending = false;
43007
+ if (attempt.pending) {
43008
+ attempt.pending = false;
42965
43009
  request2.personInitiated = true;
42966
43010
  }
42967
43011
  request2.onMetrics = (metrics) => {
@@ -44865,7 +44909,7 @@ var invokeSkillTool = makeInvokeSkillTool(resolveAmbientSkills);
44865
44909
  // src/zlm.ts
44866
44910
  var ZLM_EMBED_API_VERSION = "zerglang.ztc-embed/1";
44867
44911
  var ZLM_STDIO_PROTOCOL = "zerglang.ztc-host/1";
44868
- var ZLM_ZTC_VERSION = true ? "0.13.1-dev.202611081058" : "development";
44912
+ var ZLM_ZTC_VERSION = true ? "0.14.1-dev.202611082047" : "development";
44869
44913
  var ZLM_MAX_HOST_TOOLS = 64;
44870
44914
  var ZLM_MAX_SYSTEM_PROMPT_BYTES = 128 * 1024;
44871
44915
  var ZLM_HOST_APPROVAL_CAPABILITIES = Object.freeze([
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zergai/ztc",
3
- "version": "0.13.1-dev.202611081058",
3
+ "version": "0.14.1-dev.202611082047",
4
4
  "description": "Zerg Terminal Client - CLI agent for continual AI systems",
5
5
  "license": "SEE LICENSE IN LICENSE.md",
6
6
  "homepage": "https://zergai.com/docs/ztc",
@@ -277,7 +277,7 @@
277
277
  "zergRelease": {
278
278
  "branch": "development",
279
279
  "channel": "dev",
280
- "sourceCommit": "3a5777b4ec677c44f8ce352d9a847aabfa98cc7c",
280
+ "sourceCommit": "8a32c6583bcbe05b8b9f2b2c1a9714892b44db3d",
281
281
  "sourceVersion": "0.2.0-canary.2",
282
282
  "whatsNew": [
283
283
  "Fixes and improvements."