dsh-codex-subscription 3.2.21 → 3.2.22

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/lib/index.js CHANGED
@@ -445,6 +445,14 @@ const COMPOSER_MODEL_PICKER_MODES = Object.freeze([
445
445
  "legacy"
446
446
  ]);
447
447
  const normalizeComposerModelPicker = (value) => COMPOSER_MODEL_PICKER_MODES.includes(value) ? value : "auto";
448
+ const SPEED_SHORTCUT_FIELD = "speedShortcut";
449
+ const SPEED_SHORTCUT_STYLES = Object.freeze([
450
+ "off",
451
+ "icon",
452
+ "hover",
453
+ "label"
454
+ ]);
455
+ const normalizeSpeedShortcut = (value) => SPEED_SHORTCUT_STYLES.includes(value) ? value : "off";
448
456
  const SPEED_MODE_FIELD = "speedMode";
449
457
  const SPEED_MODE_STANDARD = "standard";
450
458
  const SPEED_MODE_FAST = "fast";
@@ -874,6 +882,11 @@ const PREFERENCE_FIELDS = Object.freeze({
874
882
  default: "dsh",
875
883
  error: "Invalid fetch provider preference"
876
884
  },
885
+ [SPEED_SHORTCUT_FIELD]: {
886
+ choices: SPEED_SHORTCUT_STYLES,
887
+ default: "off",
888
+ error: "Invalid speed shortcut style"
889
+ },
877
890
  [SPEED_MODE_FIELD]: {
878
891
  choices: [
879
892
  SPEED_MODE_STANDARD,
@@ -1184,6 +1197,42 @@ const elapsedBuckets$1 = /* @__PURE__ */ new Set([
1184
1197
  "5-15s",
1185
1198
  "over-15s"
1186
1199
  ]);
1200
+ const milestones = [
1201
+ "pre-connect",
1202
+ "connected",
1203
+ "request-sent",
1204
+ "headers",
1205
+ "first-event",
1206
+ "text",
1207
+ "tool-args",
1208
+ "tool-complete"
1209
+ ];
1210
+ const selectionReasons = /* @__PURE__ */ new Set([
1211
+ "configured-sse",
1212
+ "forced-sse",
1213
+ "no-session",
1214
+ "capacity",
1215
+ "websocket-preferred",
1216
+ "probe-busy",
1217
+ "ws-cooldown",
1218
+ "ws-probe"
1219
+ ]);
1220
+ const counters = [
1221
+ "textDeltaCount",
1222
+ "reasoningDeltaCount",
1223
+ "toolCallsStarted",
1224
+ "toolCallsArgsComplete",
1225
+ "msToHeaders",
1226
+ "msToFirstEvent",
1227
+ "msSinceLastEvent"
1228
+ ];
1229
+ const terminalStates = /* @__PURE__ */ new Set([
1230
+ "done",
1231
+ "error",
1232
+ "user-abort",
1233
+ "network",
1234
+ "timeout"
1235
+ ]);
1187
1236
  const MODEL_OUTCOMES = /* @__PURE__ */ new Set([
1188
1237
  "ok",
1189
1238
  "failed",
@@ -1200,6 +1249,12 @@ function safeAttempt(value = {}) {
1200
1249
  ...typeof value.attemptId === "string" && /^[a-f0-9-]{36}$/.test(value.attemptId) ? { attemptId: value.attemptId } : {},
1201
1250
  ...choices.has(value.preference) ? { preference: value.preference } : {},
1202
1251
  ...choices.has(value.requestedTransport) ? { requestedTransport: value.requestedTransport } : {},
1252
+ ...milestones.includes(value.phase) ? { phase: value.phase } : {},
1253
+ ...selectionReasons.has(value.selectionReason) ? { selectionReason: value.selectionReason } : {},
1254
+ ...terminalStates.has(value.terminal) ? { terminal: value.terminal } : {},
1255
+ ...typeof value.oversizeRejected === "boolean" ? { oversizeRejected: value.oversizeRejected } : {},
1256
+ ...Number.isSafeInteger(value.requestBytesBucket) && value.requestBytesBucket > 0 && value.requestBytesBucket <= 2 ** 31 && Number.isInteger(Math.log2(value.requestBytesBucket)) ? { requestBytesBucket: value.requestBytesBucket } : {},
1257
+ ...Object.fromEntries(counters.filter((key) => Number.isSafeInteger(value[key]) && value[key] >= 0).map((key) => [key, value[key]])),
1203
1258
  ...typeof value.model === "string" && /^gpt-[a-z0-9][a-z0-9.-]{0,63}$/u.test(value.model) ? { model: value.model } : {},
1204
1259
  ...fetchPaths.has(value.fetchPath) ? { fetchPath: value.fetchPath } : {},
1205
1260
  ...value.requestCompression === "zstd-decoded" ? { requestCompression: value.requestCompression } : {},
@@ -1220,10 +1275,19 @@ function createModelAttempt({ now = Date.now, publish = () => {} } = {}) {
1220
1275
  attemptId: randomUUID(),
1221
1276
  route: "unknown",
1222
1277
  transports: [],
1278
+ phase: "pre-connect",
1223
1279
  headersReceived: false,
1224
1280
  eventDelivered: false,
1225
1281
  contentDelivered: false
1226
1282
  };
1283
+ let lastEventAt;
1284
+ const advance = (phase) => {
1285
+ if (milestones.indexOf(phase) > milestones.indexOf(data.phase)) data.phase = phase;
1286
+ };
1287
+ const elapsed = (from) => Math.max(0, Math.round(now() - from));
1288
+ const count = (key) => {
1289
+ data[key] = (data[key] ?? 0) + 1;
1290
+ };
1227
1291
  let finished = false;
1228
1292
  return {
1229
1293
  configure(value) {
@@ -1235,28 +1299,69 @@ function createModelAttempt({ now = Date.now, publish = () => {} } = {}) {
1235
1299
  transport(value) {
1236
1300
  if (!finished && transports.has(value) && data.transports.at(-1) !== value && data.transports.length < 8) data.transports.push(value);
1237
1301
  },
1302
+ connected() {
1303
+ if (!finished) advance("connected");
1304
+ },
1305
+ sent() {
1306
+ if (!finished) advance("request-sent");
1307
+ },
1238
1308
  response(status) {
1239
- if (!finished) {
1240
- data.headersReceived = true;
1241
- if (Number.isInteger(status)) data.httpStatus = status;
1242
- }
1309
+ if (finished) return;
1310
+ data.headersReceived = true;
1311
+ data.msToHeaders ??= elapsed(started);
1312
+ advance("headers");
1313
+ if (Number.isInteger(status)) data.httpStatus = status;
1243
1314
  },
1244
1315
  fetchFailure(error) {
1245
1316
  if (!finished) data.networkFailure = safeFetchFailure(error);
1246
1317
  },
1247
1318
  event(event) {
1248
- if (finished || !event || ["error", "done"].includes(event.type)) return;
1319
+ if (finished || !event || [
1320
+ "start",
1321
+ "error",
1322
+ "done"
1323
+ ].includes(event.type)) return;
1249
1324
  data.eventDelivered = true;
1250
- if (/_delta$|_end$/.test(event.type)) data.contentDelivered = true;
1325
+ data.msToFirstEvent ??= elapsed(started);
1326
+ lastEventAt = now();
1327
+ advance("first-event");
1328
+ switch (event.type) {
1329
+ case "text_delta":
1330
+ count("textDeltaCount");
1331
+ advance("text");
1332
+ data.contentDelivered = true;
1333
+ break;
1334
+ case "text_end":
1335
+ advance("text");
1336
+ data.contentDelivered = true;
1337
+ break;
1338
+ case "thinking_delta":
1339
+ count("reasoningDeltaCount");
1340
+ break;
1341
+ case "toolcall_start":
1342
+ count("toolCallsStarted");
1343
+ advance("tool-args");
1344
+ break;
1345
+ case "toolcall_delta":
1346
+ advance("tool-args");
1347
+ break;
1348
+ case "toolcall_end":
1349
+ count("toolCallsArgsComplete");
1350
+ advance("tool-complete");
1351
+ data.contentDelivered = true;
1352
+ break;
1353
+ }
1251
1354
  },
1252
1355
  finish(status, stage) {
1253
1356
  if (finished || !MODEL_OUTCOMES.has(status)) return;
1254
1357
  finished = true;
1255
- const elapsed = Math.max(0, now() - started);
1358
+ data.terminal ??= status === "ok" ? "done" : status === "cancelled" || status === "abandoned" ? "user-abort" : data.networkFailure ? "network" : "error";
1359
+ if (lastEventAt !== void 0) data.msSinceLastEvent = elapsed(lastEventAt);
1360
+ const duration = elapsed(started);
1256
1361
  Object.assign(data, {
1257
1362
  status,
1258
1363
  stage,
1259
- elapsed: elapsed < 1e3 ? "under-1s" : elapsed < 5e3 ? "1-5s" : elapsed < 15e3 ? "5-15s" : "over-15s"
1364
+ elapsed: duration < 1e3 ? "under-1s" : duration < 5e3 ? "1-5s" : duration < 15e3 ? "5-15s" : "over-15s"
1260
1365
  });
1261
1366
  try {
1262
1367
  publish({
@@ -1493,6 +1598,12 @@ const CODEX_SUBSCRIPTION_HOST = "chatgpt.com";
1493
1598
  const CODEX_MODEL_SSE_PATH = "/backend-api/codex/responses";
1494
1599
  const CODEX_WEBSOCKET_LIMIT_HEADER = "x-codex-websocket-max-message-bytes";
1495
1600
  const CODEX_WEBSOCKET_MESSAGE_TOO_LARGE = "WebSocket request exceeds the advertised message size limit";
1601
+ const wireBytes = (message) => {
1602
+ if (typeof message === "string") return Buffer.byteLength(message);
1603
+ if (ArrayBuffer.isView(message) || message instanceof ArrayBuffer) return message.byteLength;
1604
+ if (Array.isArray(message) && message.every(Buffer.isBuffer)) return message.reduce((total, part) => total + part.byteLength, 0);
1605
+ if (message instanceof Blob) return message.size;
1606
+ };
1496
1607
  const MODEL_SSE_PROXY_ENV = "DSH_CODEX_SSE_PROXY";
1497
1608
  const CODEX_HOSTS = /* @__PURE__ */ new Set([CODEX_AUTH_HOST, CODEX_SUBSCRIPTION_HOST]);
1498
1609
  const OAUTH_HOSTS = /* @__PURE__ */ new Set([CODEX_AUTH_HOST]);
@@ -1752,6 +1863,7 @@ async function fetchInCodexScope(scope, fetchBeforeScope, input, init) {
1752
1863
  let response;
1753
1864
  try {
1754
1865
  if (scopedOptions.requestFetch && target.origin === `https://${CODEX_SUBSCRIPTION_HOST}` && target.pathname === CODEX_MODEL_SSE_PATH) {
1866
+ scopedOptions.onModelRequestBytes?.(wireBytes(init?.body));
1755
1867
  const decoded = await uncompressedModelRequest(input, init);
1756
1868
  if (decoded !== init) scopedOptions.onModelRequestCompression?.("zstd-decoded");
1757
1869
  init = decoded;
@@ -1814,6 +1926,7 @@ async function withCodexNetwork(run, options = {}) {
1814
1926
  ...args[1],
1815
1927
  ...proxy ? { agent: new HttpsProxyAgent(proxy) } : {}
1816
1928
  });
1929
+ socket.once?.("open", () => scope.options.onModelWebSocketConnect?.());
1817
1930
  let maxMessageBytes;
1818
1931
  if (url.pathname === CODEX_MODEL_SSE_PATH) socket.once?.("upgrade", (response) => {
1819
1932
  const header = response.headers?.[CODEX_WEBSOCKET_LIMIT_HEADER];
@@ -1824,9 +1937,17 @@ async function withCodexNetwork(run, options = {}) {
1824
1937
  const send = socket.send;
1825
1938
  socket.send = function(...values) {
1826
1939
  const message = values[0];
1827
- if (maxMessageBytes !== void 0 && typeof message === "string" && Buffer.byteLength(message) > maxMessageBytes) throw new Error(CODEX_WEBSOCKET_MESSAGE_TOO_LARGE);
1940
+ const bytes = wireBytes(message);
1941
+ const current = networkScope.getStore()?.options;
1942
+ current?.onModelRequestBytes?.(bytes);
1943
+ if (maxMessageBytes !== void 0 && bytes > maxMessageBytes) {
1944
+ current?.onModelOversize?.();
1945
+ throw new Error(CODEX_WEBSOCKET_MESSAGE_TOO_LARGE);
1946
+ }
1828
1947
  observe();
1829
- return Reflect.apply(send, this, values);
1948
+ const result = Reflect.apply(send, this, values);
1949
+ current?.onModelWebSocketSend?.();
1950
+ return result;
1830
1951
  };
1831
1952
  return socket;
1832
1953
  } });
@@ -1999,7 +2120,7 @@ const zero = () => Object.fromEntries(COUNTERS.map((key) => [key, 0]));
1999
2120
  /** Policy owns only recovery timing. SDK owns sockets, fallback and continuation. */
2000
2121
  function createSubscriptionConnection({ resolveMode = () => "sse", resolveProxy = resolveCodexOAuthProxy, sdk = defaultSdk, now = () => performance.now(), random = Math.random, cooldownMs = 3e4, maxCooldownMs = 3e5, maxSessions = 256, idleMs = 30 * 6e4 } = {}) {
2001
2122
  let namespace = randomUUID(), epoch = 0;
2002
- const sessions = /* @__PURE__ */ new Map(), retired = /* @__PURE__ */ new Set(), probes = /* @__PURE__ */ new Set();
2123
+ const sessions = /* @__PURE__ */ new Map(), retired = /* @__PURE__ */ new Set(), groups = /* @__PURE__ */ new Map();
2003
2124
  const totals = zero();
2004
2125
  const recovery = {
2005
2126
  recoveryAttempts: 0,
@@ -2016,10 +2137,11 @@ function createSubscriptionConnection({ resolveMode = () => "sse", resolveProxy
2016
2137
  totals[key] = Math.min(Number.MAX_SAFE_INTEGER, totals[key] + Math.max(0, count - entry.seen[key]));
2017
2138
  entry.seen[key] = count;
2018
2139
  }
2019
- if (!entry.retired && stats.websocketFallbackActive === true && stats.lastWebSocketError !== "WebSocket request exceeds the advertised message size limit" && (!entry.cooling || failures > 0)) {
2020
- entry.streak = Math.min(20, entry.streak + Math.max(1, failures));
2021
- entry.cooling = true;
2022
- entry.retryAt = now() + delay(entry.streak);
2140
+ if (!entry.retired && stats.websocketFallbackActive === true && stats.lastWebSocketError !== "WebSocket request exceeds the advertised message size limit" && (!entry.needsReset || failures > 0)) {
2141
+ entry.needsReset = true;
2142
+ const circuit = entry.circuit;
2143
+ circuit.streak = Math.min(20, circuit.streak + Math.max(1, failures));
2144
+ circuit.retryAt = now() + delay(circuit.streak);
2023
2145
  }
2024
2146
  return stats;
2025
2147
  };
@@ -2028,10 +2150,12 @@ function createSubscriptionConnection({ resolveMode = () => "sse", resolveProxy
2028
2150
  sdk.close(entry.key);
2029
2151
  sdk.reset(entry.key);
2030
2152
  entry.seen = zero();
2153
+ entry.needsReset = false;
2031
2154
  };
2032
2155
  const evict = (entry) => {
2033
2156
  clear(entry);
2034
2157
  sessions.delete(entry.key);
2158
+ if (--entry.circuit.sessions === 0) groups.delete(entry.group);
2035
2159
  };
2036
2160
  const sse = (options, preference, selectionReason) => ({
2037
2161
  options: {
@@ -2060,9 +2184,9 @@ function createSubscriptionConnection({ resolveMode = () => "sse", resolveProxy
2060
2184
  observe(entry);
2061
2185
  return {
2062
2186
  scope: entry.key,
2063
- state: entry.probe ? "probing" : entry.cooling ? "cooldown" : "preferred",
2187
+ state: entry.circuit.probing ? "probing" : entry.circuit.streak ? "cooldown" : "preferred",
2064
2188
  active: entry.active,
2065
- cooldownMs: Math.max(0, Math.ceil(entry.retryAt - time))
2189
+ cooldownMs: Math.max(0, Math.ceil(entry.circuit.retryAt - time))
2066
2190
  };
2067
2191
  })
2068
2192
  };
@@ -2102,49 +2226,56 @@ function createSubscriptionConnection({ resolveMode = () => "sse", resolveProxy
2102
2226
  if (oldest) evict(oldest);
2103
2227
  else return sse(options, preference, "capacity");
2104
2228
  }
2229
+ let circuit = groups.get(group);
2230
+ if (!circuit) groups.set(group, circuit = {
2231
+ sessions: 0,
2232
+ active: 0,
2233
+ streak: 0,
2234
+ retryAt: 0,
2235
+ probing: false
2236
+ });
2237
+ circuit.sessions++;
2105
2238
  entry = {
2106
2239
  key,
2107
2240
  group,
2241
+ circuit,
2108
2242
  active: 0,
2109
2243
  used: time,
2110
2244
  seen: zero(),
2111
- streak: 0,
2112
- retryAt: 0,
2113
- cooling: false,
2114
- probe: false,
2115
- retired: false
2245
+ retired: false,
2246
+ needsReset: false
2116
2247
  };
2117
2248
  sessions.set(key, entry);
2118
2249
  }
2119
2250
  observe(entry);
2251
+ const circuit = entry.circuit;
2120
2252
  let transport = "websocket-cached", selectionReason = "websocket-preferred", probe = false;
2121
- if (entry.probe) {
2253
+ if (circuit.probing) {
2122
2254
  transport = "sse";
2123
2255
  selectionReason = "probe-busy";
2124
- } else if (entry.cooling) if (time < entry.retryAt) {
2256
+ recovery.recoveryDeferrals++;
2257
+ } else if (circuit.streak) if (time < circuit.retryAt) {
2125
2258
  transport = "sse";
2126
2259
  selectionReason = "ws-cooldown";
2127
2260
  recovery.cooldownRequests++;
2128
- } else if (entry.active || probes.has(group)) {
2261
+ } else if (circuit.active) {
2129
2262
  transport = "sse";
2130
2263
  selectionReason = "probe-busy";
2131
2264
  recovery.recoveryDeferrals++;
2132
2265
  } else {
2133
- probes.add(group);
2134
- entry.probe = probe = true;
2135
- try {
2136
- clear(entry);
2137
- } catch (error) {
2138
- probes.delete(group);
2139
- entry.probe = false;
2140
- throw error;
2141
- }
2142
- entry.cooling = false;
2266
+ clear(entry);
2267
+ circuit.probing = probe = true;
2143
2268
  selectionReason = "ws-probe";
2144
2269
  recovery.recoveryAttempts++;
2145
2270
  }
2271
+ else if (entry.needsReset) if (entry.active) {
2272
+ transport = "sse";
2273
+ selectionReason = "probe-busy";
2274
+ } else clear(entry);
2146
2275
  entry.active++;
2276
+ circuit.active++;
2147
2277
  entry.used = time;
2278
+ const streak = circuit.streak;
2148
2279
  let finished = false;
2149
2280
  return {
2150
2281
  options: {
@@ -2162,31 +2293,27 @@ function createSubscriptionConnection({ resolveMode = () => "sse", resolveProxy
2162
2293
  preference,
2163
2294
  scope: key,
2164
2295
  selectionReason,
2165
- cooldownMs: Math.max(0, Math.ceil(entry.retryAt - time))
2296
+ cooldownMs: Math.max(0, Math.ceil(circuit.retryAt - time))
2166
2297
  },
2167
2298
  finish(outcome = {}) {
2168
2299
  if (finished) return;
2169
2300
  finished = true;
2170
2301
  const stats = observe(entry);
2171
2302
  entry.active--;
2303
+ circuit.active--;
2172
2304
  entry.used = now();
2173
- const skippedForSize = stats.lastWebSocketError === CODEX_WEBSOCKET_MESSAGE_TOO_LARGE;
2174
- if (skippedForSize && !entry.active && !entry.retired) {
2305
+ if ((outcome.oversizeRejected || stats.lastWebSocketError === "WebSocket request exceeds the advertised message size limit") && !entry.active && !entry.retired) {
2175
2306
  sdk.reset(entry.key);
2176
2307
  entry.seen = zero();
2308
+ entry.needsReset = false;
2177
2309
  }
2178
2310
  if (probe) {
2179
- probes.delete(group);
2180
- entry.probe = false;
2311
+ circuit.probing = false;
2181
2312
  if (!entry.retired && outcome.status === "ok" && outcome.transports?.at(-1) === "websocket" && !outcome.transports.includes("sse") && stats.websocketFallbackActive !== true) {
2182
- entry.streak = 0;
2183
- entry.retryAt = 0;
2184
- entry.cooling = false;
2313
+ circuit.streak = 0;
2314
+ circuit.retryAt = 0;
2185
2315
  recovery.recoverySuccesses++;
2186
- } else if (!skippedForSize && !entry.retired && !entry.cooling) {
2187
- entry.cooling = true;
2188
- entry.retryAt = now() + delay(entry.streak);
2189
- }
2316
+ } else if (!entry.retired && circuit.streak === streak) circuit.retryAt = now() + delay(streak);
2190
2317
  }
2191
2318
  if (entry.retired && !entry.active) {
2192
2319
  clear(entry);
@@ -2206,7 +2333,7 @@ function createSubscriptionConnection({ resolveMode = () => "sse", resolveProxy
2206
2333
  else clear(entry);
2207
2334
  }
2208
2335
  sessions.clear();
2209
- probes.clear();
2336
+ groups.clear();
2210
2337
  }
2211
2338
  };
2212
2339
  }
@@ -3063,13 +3190,15 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
3063
3190
  })) attempt.configure({ failure: "context-overflow" });
3064
3191
  noteStreamFailure(stage, error, effectiveSource, networkFailure, attempt.snapshot().attemptId);
3065
3192
  }
3193
+ if (signal.reason?.name === "TimeoutError" || error?.name === "TimeoutError") attempt.configure({ terminal: "timeout" });
3066
3194
  attempt.finish(status, stage);
3067
3195
  };
3068
3196
  const finish = () => {
3069
- const { status, transports } = attempt.snapshot();
3197
+ const { status, transports, oversizeRejected } = attempt.snapshot();
3070
3198
  request?.finish?.({
3071
3199
  status,
3072
- transports
3200
+ transports,
3201
+ oversizeRejected
3073
3202
  });
3074
3203
  };
3075
3204
  const initialize = async () => {
@@ -3091,7 +3220,8 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
3091
3220
  attempt.configure({
3092
3221
  preference: request.diagnostic?.preference ?? request.options?.transport ?? "auto",
3093
3222
  requestedTransport: next.transport ?? "auto",
3094
- model: source?.model?.id
3223
+ model: source?.model?.id,
3224
+ selectionReason: request.diagnostic?.selectionReason
3095
3225
  });
3096
3226
  effectiveSource = {
3097
3227
  ...source,
@@ -3119,6 +3249,18 @@ function openaiCodexSubscriptionProvider({ resolveSpeedMode = () => void 0, reso
3119
3249
  onModelRequestCompression(requestCompression) {
3120
3250
  attempt.configure({ requestCompression });
3121
3251
  },
3252
+ onModelRequestBytes(bytes) {
3253
+ if (bytes >= 0) attempt.configure({ requestBytesBucket: 2 ** Math.ceil(Math.log2(Math.max(1, bytes))) });
3254
+ },
3255
+ onModelWebSocketConnect() {
3256
+ attempt.connected();
3257
+ },
3258
+ onModelWebSocketSend() {
3259
+ attempt.sent();
3260
+ },
3261
+ onModelOversize() {
3262
+ attempt.configure({ oversizeRejected: true });
3263
+ },
3122
3264
  onModelHttpStatus(status) {
3123
3265
  attempt.response(status);
3124
3266
  },
@@ -4916,7 +5058,7 @@ function inheritedOriginalImageRef(session, assetId) {
4916
5058
  }
4917
5059
  //#endregion
4918
5060
  //#region src/version.js
4919
- const PACKAGE_VERSION = "3.2.21";
5061
+ const PACKAGE_VERSION = "3.2.22";
4920
5062
  const USER_AGENT = `dsh-codex-subscription/${PACKAGE_VERSION}`;
4921
5063
  //#endregion
4922
5064
  //#region src/image-original-store.js
@@ -7643,16 +7785,16 @@ function createVoiceQuestions({ speak, now = Date.now, deliveryMs = 15e3 }) {
7643
7785
  };
7644
7786
  return questions;
7645
7787
  }
7646
- const validId = (value) => typeof value === "string" && /^[a-f0-9-]{36}$/u.test(value);
7647
- const valid = (value) => validId(value?.id) && Array.isArray(value.entries) && value.entries.length <= 200 && value.entries.every((entry) => validId(entry?.callId) && ["user", "assistant"].includes(entry.role) && typeof entry.text === "string" && entry.text.length <= 4096);
7788
+ const validId$1 = (value) => typeof value === "string" && /^[a-f0-9-]{36}$/u.test(value);
7789
+ const valid$1 = (value) => validId$1(value?.id) && Array.isArray(value.entries) && value.entries.length <= 200 && value.entries.every((entry) => validId$1(entry?.callId) && ["user", "assistant"].includes(entry.role) && typeof entry.text === "string" && entry.text.length <= 4096);
7648
7790
  /** Temporary recovery data, removed once the native session has durably recorded it. */
7649
- function createVoiceTranscriptRecovery(directory) {
7791
+ function createVoiceTranscriptRecovery(directory, validate = valid$1) {
7650
7792
  const pending = /* @__PURE__ */ new Map();
7651
7793
  const filename = (id) => join(directory, createHash("sha256").update(id).digest("hex") + ".json");
7652
7794
  const read = async (threadId) => {
7653
7795
  try {
7654
7796
  const value = JSON.parse(await readFile(filename(threadId), "utf8"));
7655
- return valid(value) ? value : void 0;
7797
+ return validate(value) ? value : void 0;
7656
7798
  } catch (error) {
7657
7799
  if (error.code !== "ENOENT" && !(error instanceof SyntaxError)) throw error;
7658
7800
  }
@@ -7707,6 +7849,80 @@ function createVoiceTranscriptRecovery(directory) {
7707
7849
  };
7708
7850
  }
7709
7851
  //#endregion
7852
+ //#region src/voice-result-delivery.js
7853
+ const WINDOW = 30 * 6e4;
7854
+ const states$1 = /* @__PURE__ */ new Set([
7855
+ "pending",
7856
+ "offered",
7857
+ "announcing",
7858
+ "heard",
7859
+ "screen-only"
7860
+ ]);
7861
+ const validId = (value) => typeof value === "string" && value.length > 0 && value.length <= 128;
7862
+ const valid = (value) => value?.id === "voice-results" && Array.isArray(value.entries) && value.entries.length <= 16 && value.entries.every((entry) => validId(entry?.requestId) && validId(entry.messageId) && states$1.has(entry.state) && [
7863
+ 0,
7864
+ 1,
7865
+ 2
7866
+ ].includes(entry.attempts) && Number.isFinite(entry.completedAt));
7867
+ const createVoiceResultStore = (directory) => createVoiceTranscriptRecovery(directory, valid);
7868
+ function createVoiceResultDelivery({ store, warn = () => {}, now = Date.now } = {}) {
7869
+ const threads = /* @__PURE__ */ new Map();
7870
+ const thread = (id) => {
7871
+ let result = threads.get(id);
7872
+ if (!result) threads.set(id, result = {
7873
+ entries: /* @__PURE__ */ new Map(),
7874
+ queued: /* @__PURE__ */ new Map()
7875
+ });
7876
+ for (const [key, entry] of result.entries) if (now() - entry.completedAt > WINDOW) result.entries.delete(key);
7877
+ return result;
7878
+ };
7879
+ const persist = (id) => {
7880
+ if (!store) return;
7881
+ store.save(id, {
7882
+ id: "voice-results",
7883
+ entries: [...thread(id).entries.values()].map((entry) => ({ ...entry }))
7884
+ }).catch(warn);
7885
+ };
7886
+ return {
7887
+ thread,
7888
+ tracks(id) {
7889
+ const current = threads.get(id);
7890
+ return Boolean(current?.queued.size || current?.running);
7891
+ },
7892
+ async restore(id) {
7893
+ const value = await store?.load(id);
7894
+ const current = thread(id);
7895
+ for (const entry of value?.entries ?? []) if (now() - entry.completedAt <= WINDOW && !current.entries.has(entry.requestId)) {
7896
+ if (entry.state === "announcing") entry.state = entry.attempts >= 2 ? "screen-only" : "pending";
7897
+ current.entries.set(entry.requestId, entry);
7898
+ }
7899
+ while (current.entries.size > 16) current.entries.delete(current.entries.keys().next().value);
7900
+ },
7901
+ complete(id, requestId, messageId) {
7902
+ const current = thread(id);
7903
+ const prior = current.entries.get(requestId);
7904
+ if (prior) return prior;
7905
+ if (!validId(requestId) || !validId(messageId)) return;
7906
+ const entry = {
7907
+ requestId,
7908
+ messageId,
7909
+ state: "pending",
7910
+ attempts: 0,
7911
+ completedAt: now()
7912
+ };
7913
+ current.entries.set(requestId, entry);
7914
+ if (current.entries.size > 16) current.entries.delete(current.entries.keys().next().value);
7915
+ persist(id);
7916
+ return entry;
7917
+ },
7918
+ update(id, entry, state) {
7919
+ entry.state = state;
7920
+ if (state === "announcing") entry.attempts++;
7921
+ persist(id);
7922
+ }
7923
+ };
7924
+ }
7925
+ //#endregion
7710
7926
  //#region src/remote-control-realtime.js
7711
7927
  const SIDEBAND_BASES = ["wss://api.openai.com/v1/live", "wss://realtime.chatgpt.com/v1/live"];
7712
7928
  const ACTIVATION_RETRY_MS = [
@@ -7907,6 +8123,11 @@ function createRealtimeVoice(options) {
7907
8123
  const sessions = /* @__PURE__ */ new Map();
7908
8124
  const starts = /* @__PURE__ */ new Map();
7909
8125
  const savingNotes = /* @__PURE__ */ new Map();
8126
+ const delivery = createVoiceResultDelivery({
8127
+ store: options.resultStore,
8128
+ warn: () => log.warn("voice", "could not save the voice result state")
8129
+ });
8130
+ const desktopWorkFor = delivery.thread;
7910
8131
  const flow = (session, event, detail) => {
7911
8132
  const elapsed = Math.round(performance.now() - session.openedAt);
7912
8133
  log.info("voice-flow", event, `call=${session.flowId} elapsed_ms=${elapsed}${detail ? ` ${detail}` : ""}`);
@@ -8036,6 +8257,7 @@ function createRealtimeVoice(options) {
8036
8257
  clearTimeout(session.goodbye);
8037
8258
  clearTimeout(session.unhandledTimer);
8038
8259
  clearTimeout(session.closeTimer);
8260
+ session.stopDelivery?.();
8039
8261
  session.questions?.close();
8040
8262
  flushTail(threadId, session);
8041
8263
  try {
@@ -8068,6 +8290,11 @@ function createRealtimeVoice(options) {
8068
8290
  const recoverable = desktop && params.silentTailRecord === true && params.flushTranscriptTailOnSessionEnd !== false && options.recovery && options.record;
8069
8291
  try {
8070
8292
  lifetime.throwIfAborted();
8293
+ if (desktop) try {
8294
+ await delivery.restore(threadId);
8295
+ } catch {
8296
+ log.warn("voice", "could not restore voice result state");
8297
+ }
8071
8298
  if (recoverable) try {
8072
8299
  const checkpoint = await options.recovery.load(threadId);
8073
8300
  if (checkpoint) {
@@ -8135,7 +8362,7 @@ function createRealtimeVoice(options) {
8135
8362
  session.flowId = crypto.randomUUID().slice(0, 8);
8136
8363
  session.openedAt = performance.now();
8137
8364
  session.desktop = desktop;
8138
- if (desktop) session.queuedDelegations = /* @__PURE__ */ new Map();
8365
+ if (desktop) session.queuedDelegations = desktopWorkFor(threadId).queued;
8139
8366
  sessions.set(threadId, session);
8140
8367
  flow(session, "call connected", `mode=${desktop ? "desktop" : "phone"}`);
8141
8368
  const send = (message) => {
@@ -8159,10 +8386,97 @@ function createRealtimeVoice(options) {
8159
8386
  };
8160
8387
  session.speak = speak;
8161
8388
  const prefixes = params.codexResponseHandoffChannelPrefixes ?? CHANNEL_PREFIXES;
8389
+ const idleMs = options.deliveryIdleMs ?? 1200;
8390
+ let deliveryTimer, announcement, lastUserSpeech = performance.now();
8391
+ const finishAnnouncement = (heard = false) => {
8392
+ if (!announcement) return;
8393
+ delivery.update(threadId, announcement.entry, heard ? "heard" : announcement.entry.attempts >= 2 ? "screen-only" : "offered");
8394
+ announcement = void 0;
8395
+ };
8396
+ session.stopDelivery = () => {
8397
+ clearTimeout(deliveryTimer);
8398
+ finishAnnouncement();
8399
+ };
8400
+ const planDelivery = () => {
8401
+ if (!desktop || session.ended || session.closing || session.speaking || session.screenQuestions) return;
8402
+ clearTimeout(deliveryTimer);
8403
+ deliveryTimer = setTimeout(() => {
8404
+ deliver().catch(() => log.warn("voice", "could not offer a voice result"));
8405
+ }, idleMs);
8406
+ deliveryTimer.unref?.();
8407
+ };
8408
+ const canAnnounce = () => !session.ended && !session.closing && !session.speaking && !session.screenQuestions && !session.voiceResponding && (!session.awaitingVoiceReply || performance.now() - lastUserSpeech >= 5e3) && performance.now() - Math.max(lastUserSpeech, session.lastOutputAudioAt ?? 0, session.interruptedAt ?? 0) >= idleMs;
8409
+ const deliver = async () => {
8410
+ if (session.ended || session.speaking || session.screenQuestions) return;
8411
+ if (announcement) if (announcement.output && announcement.transcriptDone && canAnnounce()) finishAnnouncement(true);
8412
+ else if (performance.now() - announcement.started >= 15e3) finishAnnouncement();
8413
+ else {
8414
+ planDelivery();
8415
+ return;
8416
+ }
8417
+ const entry = [...desktopWorkFor(threadId).entries.values()].find((item) => ["pending", "offered"].includes(item.state));
8418
+ if (!entry) return;
8419
+ if (!canAnnounce()) {
8420
+ planDelivery();
8421
+ return;
8422
+ }
8423
+ if (!session.offeredResults?.has(entry.requestId)) {
8424
+ const text = await options.readResult?.(threadId, entry.messageId);
8425
+ if (!canAnnounce() || announcement) {
8426
+ planDelivery();
8427
+ return;
8428
+ }
8429
+ if (!text) {
8430
+ delivery.update(threadId, entry, "screen-only");
8431
+ planDelivery();
8432
+ return;
8433
+ }
8434
+ if (!session.offerResult(entry, void 0, text)) {
8435
+ delivery.update(threadId, entry, "announcing");
8436
+ delivery.update(threadId, entry, entry.attempts >= 2 ? "screen-only" : "pending");
8437
+ planDelivery();
8438
+ return;
8439
+ }
8440
+ }
8441
+ delivery.update(threadId, entry, "announcing");
8442
+ announcement = {
8443
+ entry,
8444
+ started: performance.now(),
8445
+ output: false,
8446
+ transcriptDone: false
8447
+ };
8448
+ if (!send(outbound.sessionAppend("[BACKGROUND_RESULT_READY] At this natural pause, briefly tell the user in their current language that the background result is ready. Give at most one sentence about the result. If you already mentioned it, stay silent.", "speakable"))) finishAnnouncement();
8449
+ planDelivery();
8450
+ };
8451
+ session.offerResult = (entry, delegationId, text) => {
8452
+ if (session.ended) return false;
8453
+ const result = text.trim();
8454
+ const [excerpt] = appendChunks(result.slice(0, VOICE_RESULT_CONTEXT_BYTES), VOICE_RESULT_CONTEXT_BYTES);
8455
+ if (!excerpt) return false;
8456
+ const header = "[BACKGROUND_RESULT] DSH posted this result in chat. Keep it as context until there is a pause.\n";
8457
+ const tail = excerpt === result ? "" : "\nSee the written answer for remaining details.";
8458
+ const sent = appendChunks(header + excerpt + tail).every((piece) => send(delegationId ? outbound.delegationAppend(delegationId, piece, "commentary") : outbound.sessionAppend(piece, "commentary")));
8459
+ flow(session, "background result shared as context", `sent=${sent} truncated=${excerpt !== result} user_speaking=${Boolean(session.speaking)} voice_responding=${Boolean(session.voiceResponding)}`);
8460
+ if (entry && sent) {
8461
+ session.offeredResults ??= /* @__PURE__ */ new Set();
8462
+ session.offeredResults.add(entry.requestId);
8463
+ if (session.offeredResults.size > 16) session.offeredResults.delete(session.offeredResults.values().next().value);
8464
+ delivery.update(threadId, entry, "offered");
8465
+ }
8466
+ return sent;
8467
+ };
8468
+ session.planDelivery = planDelivery;
8469
+ session.interruptDelivery = () => {
8470
+ session.interruptedAt = performance.now();
8471
+ finishAnnouncement();
8472
+ planDelivery();
8473
+ };
8162
8474
  session.reply = (delegationId, text) => {
8163
8475
  if (session.ended) return;
8164
- if (channelOf(text, prefixes) !== "speakable") {
8165
- speak(delegationId, text);
8476
+ const channel = channelOf(text, prefixes);
8477
+ if (channel !== "speakable") {
8478
+ if (channel === "commentary" && desktop) send(outbound.sessionAppend(text, channel));
8479
+ else speak(delegationId, text);
8166
8480
  return;
8167
8481
  }
8168
8482
  const result = text.trim();
@@ -8171,12 +8485,7 @@ function createRealtimeVoice(options) {
8171
8485
  speak(delegationId, text);
8172
8486
  return;
8173
8487
  }
8174
- const [excerpt] = appendChunks(result.slice(0, VOICE_RESULT_CONTEXT_BYTES), VOICE_RESULT_CONTEXT_BYTES);
8175
- if (!excerpt) return;
8176
- const header = "[BACKGROUND_RESULT] DSH posted this result in chat. Use it when relevant to what the user says.\n";
8177
- const tail = excerpt === result ? "" : "\nSee the written answer for remaining details.";
8178
- const sent = appendChunks(header + excerpt + tail).every((piece) => send(delegationId ? outbound.delegationAppend(delegationId, piece, "commentary") : outbound.sessionAppend(piece, "commentary")));
8179
- flow(session, "background result shared as context", `sent=${sent} truncated=${excerpt !== result} user_speaking=${Boolean(session.speaking)} voice_responding=${Boolean(session.voiceResponding)}`);
8488
+ session.offerResult(void 0, delegationId, result);
8180
8489
  };
8181
8490
  const isCurrent = () => !session.ended;
8182
8491
  const classifySpokenHangup = session.desktop && session.hangUp && typeof options.classifyHangUp === "function";
@@ -8228,6 +8537,7 @@ function createRealtimeVoice(options) {
8228
8537
  } });
8229
8538
  session.waitForScreenAnswer = () => {
8230
8539
  if (!session.screenQuestions) {
8540
+ session.interruptDelivery();
8231
8541
  clearTimeout(session.unhandledTimer);
8232
8542
  session.unhandled = [];
8233
8543
  session.awaitingAnswer = false;
@@ -8242,6 +8552,7 @@ function createRealtimeVoice(options) {
8242
8552
  flow(session, "screen answer returned", `outcome=${answer ? labels.length ? "selected" : "no-selection" : "closed"} selected_count=${labels.length}`);
8243
8553
  const status = labels.length ? `[STATUS] The user chose on screen: ${JSON.stringify(labels)}. The task can continue.` : "[STATUS] The question is no longer waiting for a screen answer.";
8244
8554
  for (const part of appendChunks(status)) questionContext(part, "commentary");
8555
+ planDelivery();
8245
8556
  };
8246
8557
  };
8247
8558
  const reportFailure = (delegationId, error) => {
@@ -8268,7 +8579,8 @@ function createRealtimeVoice(options) {
8268
8579
  const runRequest = (input, delegationId) => {
8269
8580
  const text = delegationText(input);
8270
8581
  if (!text) return;
8271
- const questionPending = Boolean(session.screenQuestions) || session.questions.consume(input, { delegation: true });
8582
+ const screenQuestion = Boolean(session.screenQuestions);
8583
+ const questionPending = screenQuestion || session.questions.consume(input, { delegation: true });
8272
8584
  if (!session.desktop || !options.queue) {
8273
8585
  if (!questionPending) enqueueRequest(text, delegationId);
8274
8586
  return;
@@ -8277,8 +8589,15 @@ function createRealtimeVoice(options) {
8277
8589
  const decision = hangupDecisionFor(text);
8278
8590
  const requestId = crypto.randomUUID();
8279
8591
  session.admission = session.admission.then(async () => {
8280
- if (await decision || questionPending) return;
8281
- if (delegationId && !session.ended) session.queuedDelegations.set(requestId, delegationId);
8592
+ if (await decision) return;
8593
+ if (questionPending) {
8594
+ if (screenQuestion && !session.ended) send(outbound.sessionAppend("[SCREEN_CHOICE] The request was not queued because a question is waiting on screen. Let the user know they can continue after answering it.", "commentary"));
8595
+ return;
8596
+ }
8597
+ session.queuedDelegations.set(requestId, {
8598
+ delegation: delegationId,
8599
+ call: session.flowId
8600
+ });
8282
8601
  try {
8283
8602
  await options.queue(threadId, text, requestId);
8284
8603
  } catch (error) {
@@ -8288,6 +8607,8 @@ function createRealtimeVoice(options) {
8288
8607
  }
8289
8608
  flow(session, "background request accepted by DSH queue");
8290
8609
  if (!session.ended && session.queuedDelegations.has(requestId)) speak(delegationId, "[STATUS] DSH accepted this request into its task queue.");
8610
+ }).catch((error) => {
8611
+ reportFailure(delegationId, error);
8291
8612
  });
8292
8613
  };
8293
8614
  session.unhandled = [];
@@ -8322,6 +8643,7 @@ function createRealtimeVoice(options) {
8322
8643
  const at = performance.now();
8323
8644
  if (session.lastOutputAudioAt === void 0 || at - session.lastOutputAudioAt >= 700) flow(session, "service audio output began", `reply_epoch=${session.replyEpoch}`);
8324
8645
  session.lastOutputAudioAt = at;
8646
+ if (announcement) announcement.output = true;
8325
8647
  }
8326
8648
  const id = value.client_event_id ?? value.error?.event_id;
8327
8649
  if (id && session.controls.delete(id)) {
@@ -8341,6 +8663,7 @@ function createRealtimeVoice(options) {
8341
8663
  if (event.kind === "delta") {
8342
8664
  if (event.role === "user") {
8343
8665
  if (!session.speaking) {
8666
+ session.interruptDelivery();
8344
8667
  flow(session, "user transcript started");
8345
8668
  if (classifySpokenHangup) {
8346
8669
  finalSpeech = void 0;
@@ -8366,6 +8689,7 @@ function createRealtimeVoice(options) {
8366
8689
  flow(session, "voice transcript finished", `role=${event.role} has_text=${Boolean(event.text.trim())}`);
8367
8690
  if (event.role === "user") {
8368
8691
  session.speaking = false;
8692
+ lastUserSpeech = performance.now();
8369
8693
  if (event.text.trim()) session.awaitingVoiceReply = true;
8370
8694
  }
8371
8695
  if (event.text.trim() !== "") {
@@ -8384,30 +8708,32 @@ function createRealtimeVoice(options) {
8384
8708
  });
8385
8709
  if (session.lines.length > 12) session.lines.shift();
8386
8710
  }
8387
- const complete = () => notify("thread/realtime/transcript/done", {
8388
- threadId,
8389
- role: event.role,
8390
- text: event.text
8391
- });
8392
- if (session.checkpointId && event.text.trim() !== "") {
8393
- const entries = [...session.recovered?.entries ?? [], ...session.tail].slice(-200);
8394
- const save = options.recovery.save(threadId, {
8395
- id: session.checkpointId,
8396
- entries
8397
- });
8398
- session.transcriptWrite = save.catch(() => {
8711
+ const entries = session.checkpointId && event.text.trim() !== "" ? [...session.recovered?.entries ?? [], ...session.tail].slice(-200) : void 0;
8712
+ session.transcriptWrite = Promise.resolve(session.transcriptWrite).then(async () => {
8713
+ let persisted;
8714
+ if (entries) try {
8715
+ await options.recovery.save(threadId, {
8716
+ id: session.checkpointId,
8717
+ entries
8718
+ });
8719
+ persisted = true;
8720
+ } catch {
8721
+ persisted = false;
8399
8722
  log.warn("voice", "could not save the voice recovery checkpoint");
8400
- });
8401
- save.then(complete, () => notify("thread/realtime/error", {
8723
+ }
8724
+ await notify("thread/realtime/transcript/done", {
8402
8725
  threadId,
8403
- message: "The voice transcript could not be saved."
8404
- })).catch(() => {});
8405
- } else complete().catch(() => {});
8726
+ role: event.role,
8727
+ text: event.text,
8728
+ ...persisted === false ? { persisted } : {}
8729
+ });
8730
+ }).catch(() => {});
8406
8731
  const spoken = event.text.trim();
8407
8732
  const said = Date.now();
8408
8733
  const endsCall = event.role === "user" && classifySpokenHangup ? checkFinalSpeech(spoken, said) : void 0;
8409
8734
  const legacyGoodbye = !session.desktop && session.hangUp && event.role === "user" && isGoodbye(event.text);
8410
8735
  if (event.role !== "user") {
8736
+ if (announcement && event.text.trim()) announcement.transcriptDone = true;
8411
8737
  session.voiceResponding = false;
8412
8738
  session.awaitingVoiceReply = false;
8413
8739
  if (event.text.trim()) {
@@ -8417,7 +8743,9 @@ function createRealtimeVoice(options) {
8417
8743
  };
8418
8744
  session.questions.heardReply(event.text);
8419
8745
  }
8420
- } else if (spoken && !legacyGoodbye) {
8746
+ }
8747
+ planDelivery();
8748
+ if (event.role === "user" && spoken && !legacyGoodbye) {
8421
8749
  if (session.screenQuestions) return;
8422
8750
  if (endsCall && session.questions.active) {
8423
8751
  const answer = session.questions.captureAnswer(spoken);
@@ -8465,6 +8793,7 @@ function createRealtimeVoice(options) {
8465
8793
  sessions.delete(threadId);
8466
8794
  session.ended = true;
8467
8795
  clearTimeout(session.closeTimer);
8796
+ session.stopDelivery();
8468
8797
  flow(session, "call closed", "reason=transport-closed");
8469
8798
  session.questions.close();
8470
8799
  flushTail(threadId, session);
@@ -8487,6 +8816,7 @@ function createRealtimeVoice(options) {
8487
8816
  version: params.version ?? "v3",
8488
8817
  realtimeSessionId: params.realtimeSessionId ?? null
8489
8818
  }).catch(() => {});
8819
+ planDelivery();
8490
8820
  return {};
8491
8821
  }
8492
8822
  const append = (threadId, text, channel) => {
@@ -8501,24 +8831,40 @@ function createRealtimeVoice(options) {
8501
8831
  };
8502
8832
  return {
8503
8833
  isDesktop: (threadId) => sessions.get(threadId)?.desktop === true,
8504
- tracksNativeWork: (threadId) => sessions.get(threadId)?.liveFollowups === true,
8834
+ tracksNativeWork: (threadId) => sessions.get(threadId)?.liveFollowups === true || delivery.tracks(threadId),
8505
8835
  nativeInput(threadId, requestId) {
8506
8836
  const session = sessions.get(threadId);
8507
- const delegation = session?.queuedDelegations?.get(requestId);
8508
- if (!delegation) return;
8509
- session.queuedDelegations.delete(requestId);
8510
- session.activeDelegation = delegation;
8837
+ if (!delivery.tracks(threadId)) return;
8838
+ const work = desktopWorkFor(threadId);
8839
+ if (!work.queued.has(requestId)) return;
8840
+ const queued = work.queued.get(requestId);
8841
+ work.queued.delete(requestId);
8842
+ work.running = {
8843
+ requestId,
8844
+ ...queued
8845
+ };
8846
+ if (session) session.activeDelegation = queued.call === session.flowId ? queued.delegation : void 0;
8511
8847
  },
8512
8848
  nativeWork(threadId, working) {
8513
8849
  const session = sessions.get(threadId);
8850
+ if (!working && delivery.tracks(threadId)) desktopWorkFor(threadId).running = void 0;
8514
8851
  if (!session?.liveFollowups || Boolean(session.nativeWorking) === working) return;
8515
8852
  session.nativeWorking = working;
8516
8853
  if (!working && session.desktop) session.activeDelegation = void 0;
8517
8854
  flow(session, "DSH turn state changed", `working=${working}`);
8518
- session.speak(void 0, working ? "[STATUS] DSH is working on the current turn." : "[STATUS] The current DSH turn is no longer running.");
8855
+ session.reply(void 0, working ? "[STATUS] DSH is working on the current turn." : "[STATUS] The current DSH turn is no longer running.");
8519
8856
  },
8520
- nativeMessage(threadId, text) {
8857
+ nativeMessage(threadId, text, messageId) {
8521
8858
  const session = sessions.get(threadId);
8859
+ const work = delivery.tracks(threadId) ? desktopWorkFor(threadId).running : void 0;
8860
+ if (work && messageId && channelOf(text) === "speakable") {
8861
+ const entry = delivery.complete(threadId, work.requestId, messageId);
8862
+ if (entry && session?.desktop && entry.state === "pending") {
8863
+ session.offerResult(entry, work.call === session.flowId ? work.delegation : void 0, text);
8864
+ session.planDelivery();
8865
+ }
8866
+ return;
8867
+ }
8522
8868
  if (session?.liveFollowups) session.reply(session.desktop ? session.activeDelegation : void 0, text);
8523
8869
  },
8524
8870
  askQuestion(threadId, request) {
@@ -8529,6 +8875,7 @@ function createRealtimeVoice(options) {
8529
8875
  interrupt(threadId) {
8530
8876
  const session = sessions.get(threadId);
8531
8877
  if (!session) return false;
8878
+ session.interruptDelivery();
8532
8879
  const event_id = crypto.randomUUID();
8533
8880
  if (session.controls.size > 20) session.controls.delete(session.controls.values().next().value);
8534
8881
  session.controls.add(event_id);
@@ -8549,6 +8896,7 @@ function createRealtimeVoice(options) {
8549
8896
  const session = sessions.get(threadId);
8550
8897
  if (session?.desktop && session.lastPlaybackState !== state && ["playing", "waiting"].includes(state)) {
8551
8898
  session.lastPlaybackState = state;
8899
+ if (state === "waiting") session.planDelivery();
8552
8900
  flow(session, "browser playback changed", `state=${state} reply_epoch=${session.replyEpoch}`);
8553
8901
  }
8554
8902
  },
@@ -8711,20 +9059,21 @@ const scopeParts = (scope) => {
8711
9059
  };
8712
9060
  const scopeKey = (scope) => {
8713
9061
  const parts = scopeParts(scope);
8714
- return parts[1] === "items" ? JSON.stringify(parts.slice(0, 2)) : scope;
9062
+ return parts[1] === "items" && parts.length === 3 ? JSON.stringify(parts.slice(0, 2)) : scope;
8715
9063
  };
8716
- const anchorCursor = (id, scope, direction, inclusive) => encode({
8717
- v: 2,
9064
+ const anchorCursor = (id, scope, direction, inclusive, lineage) => encode({
9065
+ v: lineage ? 3 : 2,
8718
9066
  s: scopeKey(scope),
8719
9067
  d: direction,
8720
9068
  a: id,
8721
- i: inclusive
9069
+ i: inclusive,
9070
+ ...lineage ? { l: lineage.current } : {}
8722
9071
  });
8723
- function initialHistoryCursor(list, scope) {
9072
+ function initialHistoryCursor(list, scope, lineage) {
8724
9073
  const anchor = list.at(-1)?.id;
8725
- return anchor === void 0 ? null : anchorCursor(anchor, scope, "desc", true);
9074
+ return anchor === void 0 ? null : anchorCursor(anchor, scope, "desc", true, lineage);
8726
9075
  }
8727
- function historyPage(list, params, scope, defaultDirection = "desc", accept = () => true) {
9076
+ function historyPage(list, params, scope, defaultDirection = "desc", accept = () => true, { lineage, offsetAnchor } = {}) {
8728
9077
  const cursor = params?.cursor;
8729
9078
  const legacyOffset = typeof cursor === "string" && /^\d+$/u.test(cursor);
8730
9079
  const saved = cursor == null || legacyOffset ? void 0 : decode(cursor);
@@ -8732,7 +9081,11 @@ function historyPage(list, params, scope, defaultDirection = "desc", accept = ()
8732
9081
  if (!["asc", "desc"].includes(direction)) throw invalidParams("Invalid history sort direction");
8733
9082
  const limit = params?.limit ?? 50;
8734
9083
  if (!Number.isInteger(limit) || limit < 1 || limit > 100) throw invalidParams("History page limit must be between 1 and 100");
8735
- if (saved && (![1, 2].includes(saved.v) || scopeKey(saved.s) !== scopeKey(scope) || typeof saved.a !== "string" || saved.v === 2 && typeof saved.i !== "boolean")) {
9084
+ if (saved && (![
9085
+ 1,
9086
+ 2,
9087
+ 3
9088
+ ].includes(saved.v) || scopeKey(saved.s) !== scopeKey(scope) || typeof saved.a !== "string" || saved.v >= 2 && typeof saved.i !== "boolean" || saved.v === 3 && typeof saved.l !== "string")) {
8736
9089
  const currentScope = scopeParts(scope), cursorScope = scopeParts(saved.s);
8737
9090
  const view = (value) => ["turns", "items"].includes(value) ? value : "unknown";
8738
9091
  phoneLog("history cursor rejected", {
@@ -8747,25 +9100,43 @@ function historyPage(list, params, scope, defaultDirection = "desc", accept = ()
8747
9100
  }, "warn");
8748
9101
  throw invalidParams("History cursor belongs to another view");
8749
9102
  }
9103
+ if (saved?.v === 3 && saved.l !== lineage?.current) throw invalidParams("History has changed. Resume the thread before requesting more items.");
8750
9104
  const ordered = direction === "asc" ? list : list.toReversed();
8751
- const start = legacyOffset ? Number(cursor) : saved ? ordered.findIndex((item) => item.id === saved.a) : 0;
9105
+ const filtered = legacyOffset ? ordered.filter(accept) : void 0;
9106
+ const relativeTo = legacyOffset && offsetAnchor !== void 0 ? filtered.findIndex((item) => item.id === offsetAnchor) : 0;
9107
+ const start = legacyOffset ? relativeTo + Number(cursor) : saved ? ordered.findIndex((item) => item.id === saved.a) : 0;
8752
9108
  if (!Number.isSafeInteger(start) || start < 0) throw invalidParams("History cursor is no longer available");
8753
- const candidates = legacyOffset ? ordered.filter(accept).slice(start) : ordered.slice(start + (saved?.v === 2 && !saved.i ? 1 : 0)).filter(accept);
9109
+ if (relativeTo < 0) throw invalidParams("History has changed. Resume the thread before requesting more items.");
9110
+ const candidates = legacyOffset ? filtered.slice(start) : ordered.slice(start + (saved?.v >= 2 && !saved.i ? 1 : 0)).filter(accept);
8754
9111
  const data = candidates.slice(0, limit);
8755
9112
  return {
8756
9113
  data,
8757
- nextCursor: candidates.length > data.length ? anchorCursor(data.at(-1).id, scope, direction, false) : null,
8758
- backwardsCursor: data.length ? anchorCursor(data[0].id, scope, direction === "asc" ? "desc" : "asc", true) : null
9114
+ nextCursor: candidates.length > data.length ? anchorCursor(data.at(-1).id, scope, direction, false, lineage) : null,
9115
+ backwardsCursor: data.length ? anchorCursor(data[0].id, scope, direction === "asc" ? "desc" : "asc", true, lineage) : null
9116
+ };
9117
+ }
9118
+ function historySummaryItem(item) {
9119
+ if (item.type === "userMessage") return {
9120
+ ...item,
9121
+ content: item.content.filter((block) => block.type === "text").map((block) => ({
9122
+ ...block,
9123
+ text: block.text.slice(0, 320)
9124
+ }))
9125
+ };
9126
+ if (item.type === "agentMessage") return {
9127
+ ...item,
9128
+ text: item.text.slice(0, 320)
9129
+ };
9130
+ return {
9131
+ id: item.id,
9132
+ type: item.type
8759
9133
  };
8760
9134
  }
8761
9135
  function historyIndex(messages, turns) {
8762
9136
  const positions = new Map(messages.map((message, index) => [message.id, index]));
8763
9137
  const ranges = turns.map((turn) => ({
8764
9138
  ...turn,
8765
- items: turn.items.map((item) => item.type === "userMessage" ? item : {
8766
- id: item.id,
8767
- type: item.type
8768
- }),
9139
+ items: turn.items.map(historySummaryItem),
8769
9140
  from: positions.get(turn.id) ?? 0
8770
9141
  }));
8771
9142
  for (let i = 0; i < ranges.length; i++) ranges[i].to = ranges[i + 1]?.from ?? messages.length;
@@ -9825,6 +10196,30 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
9825
10196
  return result;
9826
10197
  };
9827
10198
  const historyIndexes = /* @__PURE__ */ new WeakMap();
10199
+ const historyBranches = /* @__PURE__ */ new Map();
10200
+ const peerOffsets = /* @__PURE__ */ new WeakMap();
10201
+ const initialBranch = randomUUID();
10202
+ const branchOf = (id) => historyBranches.get(id) ?? initialBranch;
10203
+ const historyLineage = (id) => ({ current: branchOf(id) });
10204
+ const pageOffsets = (peer, key, params, page, branch) => {
10205
+ if (!peer) return;
10206
+ let offsets = peerOffsets.get(peer);
10207
+ if (!offsets) peerOffsets.set(peer, offsets = /* @__PURE__ */ new Map());
10208
+ if (page) {
10209
+ if (params.cursor == null && page[0]) {
10210
+ offsets.set(key, {
10211
+ id: page[0].id,
10212
+ branch
10213
+ });
10214
+ if (offsets.size > 100) offsets.delete(offsets.keys().next().value);
10215
+ }
10216
+ return;
10217
+ }
10218
+ if (!/^\d+$/u.test(params.cursor ?? "")) return;
10219
+ const anchor = offsets.get(key);
10220
+ if (anchor && anchor.branch !== branch) throw invalidParams("History has changed. Resume the thread before requesting more items.");
10221
+ return anchor?.id;
10222
+ };
9828
10223
  const historySnapshot = async (id, signal) => {
9829
10224
  signal?.throwIfAborted();
9830
10225
  let source;
@@ -9857,7 +10252,8 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
9857
10252
  messages,
9858
10253
  cwd,
9859
10254
  ranges: cached.ranges,
9860
- outline
10255
+ outline,
10256
+ lineage: historyLineage(id)
9861
10257
  };
9862
10258
  };
9863
10259
  const renderHistory = async (id, snapshot, selected, signal) => {
@@ -9868,27 +10264,39 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
9868
10264
  const { urls, assets } = await imageUrlsOf(messages, signal);
9869
10265
  signal?.throwIfAborted();
9870
10266
  const turns = ranges.flatMap((range) => projectTurns(snapshot.messages.slice(range.from, range.to), snapshot.meta?.createdAt, urls, snapshot.cwd, assets, true));
10267
+ if (snapshot.lineage && snapshot.lineage.current !== branchOf(id)) throw invalidParams("History has changed. Resume the thread before requesting more items.");
9871
10268
  const visible = wanted.has(active.get(id)?.turn.id) ? withLiveTurn(id, turns) : withShownIds(id, turns);
9872
10269
  const byId = new Map(visible.map((turn) => [turn.id, turn]));
9873
10270
  return selected.map((turn) => byId.get(turn.id)).filter(Boolean);
9874
10271
  };
9875
- const listHistoryTurns = async (params, signal) => {
10272
+ const listHistoryTurns = async (params, signal, peer) => {
9876
10273
  if (params?.itemsView != null && ![
9877
10274
  "full",
9878
10275
  "summary",
9879
10276
  "notLoaded"
9880
10277
  ].includes(params.itemsView)) throw invalidParams("Invalid turn items view");
9881
- return renderTurnPage(params, await historySnapshot(params?.threadId, signal), signal);
10278
+ return renderTurnPage(params, await historySnapshot(params?.threadId, signal), signal, peer);
9882
10279
  };
9883
- const renderTurnPage = async (params, snapshot, signal) => {
10280
+ const renderTurnPage = async (params, snapshot, signal, peer) => {
9884
10281
  const id = params.threadId;
9885
- const result = historyPage(snapshot.outline, params, JSON.stringify([id, "turns"]));
10282
+ const key = JSON.stringify([
10283
+ id,
10284
+ "turns",
10285
+ params.sortDirection ?? "desc"
10286
+ ]);
10287
+ const branch = snapshot.lineage?.current;
10288
+ const result = historyPage(snapshot.outline, params, JSON.stringify([id, "turns"]), "desc", void 0, {
10289
+ lineage: snapshot.lineage,
10290
+ offsetAnchor: pageOffsets(peer, key, params, void 0, branch)
10291
+ });
9886
10292
  const full = params?.itemsView == null || params.itemsView === "full";
9887
- const data = (full ? await renderHistory(id, snapshot, result.data, signal) : result.data.map((turn) => ({
10293
+ const turns = full ? await renderHistory(id, snapshot, result.data, signal) : result.data.map((turn) => ({
9888
10294
  ...turn,
9889
- items: [],
9890
- itemsView: "notLoaded"
9891
- }))).map(({ from, to, ...turn }) => turn);
10295
+ items: params.itemsView === "summary" ? turn.items.filter((item) => item.type === "userMessage" || item.type === "agentMessage").map(historySummaryItem) : [],
10296
+ itemsView: params.itemsView
10297
+ }));
10298
+ pageOffsets(peer, key, params, result.data, branch);
10299
+ const data = turns.map(({ from, to, ...turn }) => turn);
9892
10300
  phoneLog("history page completed", {
9893
10301
  threadId: id,
9894
10302
  type: full ? "full" : "notLoaded",
@@ -9934,20 +10342,22 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
9934
10342
  const live = active.get(id);
9935
10343
  if (live?.userItem) for (const message of messages) reconcileUser(id, live, message);
9936
10344
  const ranges = historyIndex(messages, projectTurns(messages, meta?.createdAt, /* @__PURE__ */ new Map(), cwd, /* @__PURE__ */ new Map(), true));
9937
- const outline = withLiveTurn(id, ranges);
9938
- const last = outline.at(-1);
10345
+ const snapshot = options?.sortDirection === "asc" ? await historySnapshot(id, signal) : {
10346
+ meta,
10347
+ messages,
10348
+ cwd,
10349
+ ranges,
10350
+ outline: withLiveTurn(id, ranges),
10351
+ lineage: historyLineage(id)
10352
+ };
10353
+ const { outline, lineage } = snapshot;
10354
+ const last = outline.findLast((turn) => turn.status !== "inProgress");
9939
10355
  const lastItem = last?.items.at(-1);
9940
10356
  const itemAnchors = lastItem ? [{ id: JSON.stringify([last.id, lastItem.id]) }] : [];
9941
10357
  const initialTurnsPage = options ? await renderTurnPage({
9942
10358
  ...options,
9943
10359
  threadId: id
9944
- }, options.sortDirection === "asc" ? await historySnapshot(id, signal) : {
9945
- meta,
9946
- messages,
9947
- cwd,
9948
- ranges,
9949
- outline
9950
- }, signal) : null;
10360
+ }, snapshot, signal, notify) : null;
9951
10361
  return {
9952
10362
  ...settings(agent, cwd),
9953
10363
  thread: {
@@ -9955,11 +10365,11 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
9955
10365
  cwd
9956
10366
  },
9957
10367
  initialTurnsPage,
9958
- turnsBackwardsCursor: initialHistoryCursor(outline, JSON.stringify([id, "turns"])),
9959
- itemsBackwardsCursor: initialHistoryCursor(itemAnchors, JSON.stringify([id, "items"]))
10368
+ turnsBackwardsCursor: initialHistoryCursor(last ? [last] : [], JSON.stringify([id, "turns"]), lineage),
10369
+ itemsBackwardsCursor: initialHistoryCursor(itemAnchors, JSON.stringify([id, "items"]), lineage)
9960
10370
  };
9961
10371
  };
9962
- const listHistoryItems = async (params, signal) => {
10372
+ const listHistoryItems = async (params, signal, peer) => {
9963
10373
  const id = params?.threadId;
9964
10374
  if (params?.turnId != null && (typeof params.turnId !== "string" || params.turnId === "")) throw invalidParams("turnId must be nonempty");
9965
10375
  const snapshot = await historySnapshot(id, signal);
@@ -9984,12 +10394,23 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
9984
10394
  direction: ["asc", "desc"].includes(params?.sortDirection) ? params.sortDirection : "default",
9985
10395
  type: params?.cursor && typeof params.cursor === "object" ? "itemAnchor" : params?.cursor ? "opaqueCursor" : "firstPage"
9986
10396
  });
10397
+ const key = JSON.stringify([
10398
+ id,
10399
+ "items",
10400
+ params.sortDirection ?? "asc",
10401
+ params.turnId ?? ""
10402
+ ]);
10403
+ const branch = snapshot.lineage.current;
9987
10404
  const result = historyPage(items, {
9988
10405
  ...params,
9989
10406
  cursor
9990
- }, JSON.stringify([id, "items"]), "asc", (item) => !params?.turnId || item.turnId === params.turnId);
10407
+ }, JSON.stringify([id, "items"]), "asc", (item) => !params?.turnId || item.turnId === params.turnId, {
10408
+ lineage: snapshot.lineage,
10409
+ offsetAnchor: pageOffsets(peer, key, params, void 0, branch)
10410
+ });
9991
10411
  const wanted = new Set(result.data.map((item) => item.turnId));
9992
10412
  const rendered = await renderHistory(id, snapshot, turns.filter((turn) => wanted.has(turn.id)), signal);
10413
+ pageOffsets(peer, key, params, result.data, branch);
9993
10414
  const byTurn = new Map(rendered.map((turn) => [turn.id, new Map(turn.items.map((item) => [item.id, item]))]));
9994
10415
  return {
9995
10416
  ...result,
@@ -10509,6 +10930,10 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
10509
10930
  source: { kind: "user" }
10510
10931
  });
10511
10932
  };
10933
+ const readVoiceResult = async (threadId, messageId) => {
10934
+ const { session } = await agentFor(threadId);
10935
+ return session.deriveMessages().find((item) => item.id === messageId && item.role === "assistant")?.content.filter((block) => block.type === "text").map((block) => block.text).join("\n").trim();
10936
+ };
10512
10937
  const realtimeVoice = voice ? createRealtimeVoice({
10513
10938
  ...voice,
10514
10939
  userAgent,
@@ -10516,7 +10941,8 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
10516
10941
  delegate: delegateToAgent,
10517
10942
  queue: queueVoiceWork,
10518
10943
  record: recordToAgent,
10519
- recordedIds
10944
+ recordedIds,
10945
+ readResult: readVoiceResult
10520
10946
  }) : void 0;
10521
10947
  const phoneConfig = createPhoneConfig(configFile);
10522
10948
  const methods = {
@@ -10789,8 +11215,8 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
10789
11215
  },
10790
11216
  "currentTime/read": () => ({ currentTimeAt: seconds(Date.now()) }),
10791
11217
  "account/rateLimits/read": async () => phoneRateLimits(await usage()?.read?.().catch(() => void 0)),
10792
- "thread/turns/list": (params, { signal } = {}) => listHistoryTurns(params, signal),
10793
- "thread/items/list": (params, { signal } = {}) => listHistoryItems(params, signal),
11218
+ "thread/turns/list": (params, { signal, notify } = {}) => listHistoryTurns(params, signal, notify),
11219
+ "thread/items/list": (params, { signal, notify } = {}) => listHistoryItems(params, signal, notify),
10794
11220
  "thread/fork": async (params, { notify }) => {
10795
11221
  const forked = await service().fork({ sessionId: params?.threadId });
10796
11222
  const agent = await agentFor(forked.sessionId);
@@ -11356,6 +11782,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
11356
11782
  };
11357
11783
  /** Forward committed assistant and tool events of a phone-started turn as items. */
11358
11784
  const onSessionEvent = (session, event) => {
11785
+ if (event.surfaceOp?.op === "replace" || event.type === "compaction/end") historyBranches.set(session.id, randomUUID());
11359
11786
  if (realtimeVoice?.tracksNativeWork(session.id)) {
11360
11787
  if (event.type === "turn/start" || event.type === "turn/end") realtimeVoice.nativeWork(session.id, event.type === "turn/start");
11361
11788
  if (event.type === "user/message" && event.data?.source?.kind === "user") realtimeVoice.nativeInput(session.id, event.data.source.rpcId);
@@ -11363,7 +11790,7 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
11363
11790
  const message = event.data?.message ?? session.deriveMessages().at(-1);
11364
11791
  if (message?.role === "assistant") {
11365
11792
  const text = message.content.filter((block) => block.type === "text").map((block) => block.text).join("\n").trim();
11366
- if (text) realtimeVoice.nativeMessage(session.id, message.content.some((block) => block.type === "tool-call") ? `[STATUS] ${text}` : text);
11793
+ if (text) realtimeVoice.nativeMessage(session.id, message.content.some((block) => block.type === "tool-call") ? `[STATUS] ${text}` : text, message.id);
11367
11794
  }
11368
11795
  }
11369
11796
  }
@@ -11415,7 +11842,11 @@ function createDshRemoteControl({ controller, agents, permissions = () => void 0
11415
11842
  if (message?.role === "tool") {
11416
11843
  const item = running.turn.items.find((entry) => entry.id === message.toolCallId && entry.type !== "agentMessage");
11417
11844
  if (item) {
11845
+ const branch = branchOf(session.id);
11846
+ const revision = (running.imageRevisions ??= /* @__PURE__ */ new WeakMap()).get(item) ?? 0;
11847
+ running.imageRevisions.set(item, revision + 1);
11418
11848
  const finish = ({ urls, assets }) => {
11849
+ if (active.get(session.id) !== running || running.abort.signal.aborted || branch !== branchOf(session.id) || running.imageRevisions.get(item) !== revision + 1) return;
11419
11850
  finishTool(item, message, urls, assets);
11420
11851
  emit(session.id, "item/completed", {
11421
11852
  threadId: session.id,
@@ -12050,8 +12481,11 @@ function createRemoteImageAssets({ credentials, fetch: request = globalThis.fetc
12050
12481
  const finalize = async (fileId) => {
12051
12482
  for (let attempt = 0; attempt < 8; attempt++) {
12052
12483
  const completed = await api("POST", `files/${encodeURIComponent(fileId)}/uploaded`, {});
12053
- if (completed.status === "success") return signedUrl(completed.download_url);
12054
- if (completed.status !== "retry") throw new Error("Remote image finalization failed");
12484
+ if (completed.status === "success") {
12485
+ const value = signedUrl(completed.download_url);
12486
+ const expiry = Date.parse(new URL(value).searchParams.get("se") ?? "");
12487
+ if (!Number.isFinite(expiry) || expiry - Date.now() > 6e4) return value;
12488
+ } else if (completed.status !== "retry") throw new Error("Remote image finalization failed");
12055
12489
  if (attempt < 7) await setTimeout$1(250, void 0, { signal });
12056
12490
  }
12057
12491
  throw new Error("Remote image finalization did not complete");
@@ -16219,9 +16653,39 @@ function historicalForecast(samples, window, common) {
16219
16653
  rateMethod: "historical",
16220
16654
  pacePerHour,
16221
16655
  runwaySeconds: clampPercent(window.remainingPercent) / pacePerHour * 3600,
16222
- survivesReset: false
16656
+ survivesReset: "unknown"
16223
16657
  };
16224
16658
  }
16659
+ function validatedCyclePace(samples, epochStart, windowSeconds) {
16660
+ if (!(windowSeconds >= 86400)) return;
16661
+ const cycles = [];
16662
+ let cycle;
16663
+ for (const sample of samples) {
16664
+ if (sample.at >= epochStart) break;
16665
+ if (sample.reset) cycles.push(cycle = []);
16666
+ if (cycle) cycle.push(sample);
16667
+ }
16668
+ const hours = (a, b) => (b.at - a.at) / HOUR_MS;
16669
+ const usable = cycles.filter((points) => points.length >= 4 && hours(points[0], points.at(-1)) >= windowSeconds / 3600 * .75);
16670
+ const paces = usable.map((points) => Math.max(0, (points[0].remainingPercent - points.at(-1).remainingPercent) / hours(points[0], points.at(-1))));
16671
+ const mean = (values) => values.reduce((sum, value) => sum + value, 0) / values.length;
16672
+ let currentError = 0, blendedError = 0, comparisons = 0;
16673
+ for (let i = 2; i < usable.length; i++) {
16674
+ const points = usable[i], prior = mean(paces.slice(0, i));
16675
+ for (let j = 1; j < points.length - 1; j++) {
16676
+ const start = points[0], known = points[j], future = points.at(-1);
16677
+ const horizon = hours(known, future);
16678
+ if (horizon < 6) continue;
16679
+ const recent = Math.max(0, (start.remainingPercent - known.remainingPercent) / hours(start, known));
16680
+ const actual = known.remainingPercent - future.remainingPercent;
16681
+ const loss = (pace) => Math.max(0, Math.abs(Math.min(known.remainingPercent, pace * horizon) - actual) - 1);
16682
+ currentError += loss(recent);
16683
+ blendedError += loss((recent + prior) / 2);
16684
+ comparisons++;
16685
+ }
16686
+ }
16687
+ if (comparisons >= 4 && blendedError < currentError) return mean(paces);
16688
+ }
16225
16689
  function observeQuotaForecast(state, windows, now = Date.now(), context = {}) {
16226
16690
  const next = { windows: { ...state?.windows ?? {} } };
16227
16691
  let changed = false;
@@ -16233,7 +16697,7 @@ function observeQuotaForecast(state, windows, now = Date.now(), context = {}) {
16233
16697
  const previous = next.windows[key];
16234
16698
  const resetChanged = previous !== void 0 && (previous.resetsAt === null !== (resetsAt === null) || previous.resetsAt !== null && Math.abs(previous.resetsAt - resetsAt) > 300);
16235
16699
  const last = previous?.samples?.at(-1);
16236
- const quotaIncreased = last !== void 0 && remainingPercent > last.remainingPercent + .5;
16700
+ const quotaIncreased = last !== void 0 && remainingPercent >= last.remainingPercent + 2;
16237
16701
  if (last !== void 0 && now <= last.at) continue;
16238
16702
  const epochStart = resetChanged || quotaIncreased ? now : previous?.epochStart ?? previous?.samples?.[0]?.at ?? now;
16239
16703
  const sample = {
@@ -16271,12 +16735,33 @@ function estimateQuotaForecast(state, window, now = Date.now(), context = {}) {
16271
16735
  reason: "stale"
16272
16736
  };
16273
16737
  let samples = history.filter((sample) => sample.at >= newest.at - RECENT_MS);
16738
+ const longEstimate = (common) => {
16739
+ const current = historicalForecast(history, window, common);
16740
+ const prior = current && validatedCyclePace(record.samples, record.epochStart, window.windowSeconds);
16741
+ if (!(prior > 0)) return current;
16742
+ const pacePerHour = (current.pacePerHour + prior) / 2;
16743
+ return {
16744
+ ...current,
16745
+ rateMethod: "validated-cycles",
16746
+ pacePerHour,
16747
+ runwaySeconds: clampPercent(window.remainingPercent) / pacePerHour * 3600
16748
+ };
16749
+ };
16274
16750
  const lastGap = samples.findLastIndex((sample, index) => index > 0 && sample.at - samples[index - 1].at > OBSERVATION_GAP_MS);
16275
16751
  if (lastGap > 0) samples = samples.slice(lastGap);
16276
16752
  const recentChange = samples.findLastIndex((sample) => sample.remainingPercent !== newest.remainingPercent);
16277
16753
  const flat = samples.slice(recentChange + 1);
16278
- if (flat.length >= 3 && newest.at - flat[0].at >= 30 * 6e4) return { status: "idle" };
16279
- if (samples.length < 2) return historicalForecast(history, window, { sampleCount: history.length }) ?? {
16754
+ if (flat.length >= 2 && newest.at - flat[0].at >= 30 * 6e4) {
16755
+ const observedSpanMs = newest.at - flat[0].at;
16756
+ return {
16757
+ status: "flat",
16758
+ activity: "unknown",
16759
+ sampleCount: flat.length,
16760
+ observedSpanMs,
16761
+ upperPacePerHour: quotaRateInterval(flat).max * 60
16762
+ };
16763
+ }
16764
+ if (samples.length < 2) return longEstimate({ sampleCount: history.length }) ?? {
16280
16765
  status: "calibrating",
16281
16766
  sampleCount: samples.length
16282
16767
  };
@@ -16299,18 +16784,16 @@ function estimateQuotaForecast(state, window, now = Date.now(), context = {}) {
16299
16784
  changedIntensity,
16300
16785
  rateMethod: bounds.method ?? "conservative"
16301
16786
  };
16787
+ const drops = samples.filter((sample, i) => i > 0 && sample.remainingPercent < samples[i - 1].remainingPercent).length;
16788
+ const recurring = drops >= 2 || common.consumedPercent >= 2;
16302
16789
  const integerReports = samples.every((sample) => Number.isInteger(sample.remainingPercent));
16303
- if (contradicted(bounds) || changedIntensity && (samples.length < 4 || spanMs < 20 * 6e4 || integerReports && bounds.steadyHypothesisFailed !== false)) return {
16790
+ const confirmedBurst = changedIntensity && drops >= 2 && flat.length === 1 && common.consumedPercent >= 4 && bounds.min > 1e-9;
16791
+ if (contradicted(bounds) || changedIntensity && (samples.length < 4 || spanMs < 20 * 6e4 || integerReports && bounds.steadyHypothesisFailed !== false) && !confirmedBurst) return {
16304
16792
  ...common,
16305
16793
  status: "calibrating",
16306
16794
  reason: "changing-pace"
16307
16795
  };
16308
- if (resetsAt !== null && resetsAt <= now / 1e3) return {
16309
- ...common,
16310
- status: "calibrating",
16311
- reason: "stale"
16312
- };
16313
- if (spanMs >= 5 * 6e4 && samples.length >= 3 && (changedIntensity || bounds.min <= 1e-9) && common.consumedPercent >= 1) {
16796
+ if (!confirmedBurst && spanMs >= 5 * 6e4 && samples.length >= 3 && (changedIntensity || bounds.min <= 1e-9) && recurring && common.consumedPercent >= 1) {
16314
16797
  const pacePerHour = common.consumedPercent / (spanMs / HOUR_MS);
16315
16798
  const runwaySeconds = clampPercent(window.remainingPercent) / pacePerHour * 3600;
16316
16799
  return {
@@ -16319,10 +16802,10 @@ function estimateQuotaForecast(state, window, now = Date.now(), context = {}) {
16319
16802
  provisional: true,
16320
16803
  pacePerHour,
16321
16804
  runwaySeconds,
16322
- survivesReset: false
16805
+ survivesReset: "unknown"
16323
16806
  };
16324
16807
  }
16325
- if (spanMs < 6e4 || bounds.min <= 1e-9) return historicalForecast(history, window, common) ?? {
16808
+ if (spanMs < 6e4 || bounds.min <= 1e-9) return longEstimate(common) ?? {
16326
16809
  ...common,
16327
16810
  status: "calibrating",
16328
16811
  reason: "resolution"
@@ -16331,12 +16814,8 @@ function estimateQuotaForecast(state, window, now = Date.now(), context = {}) {
16331
16814
  const remaining = clampPercent(window.remainingPercent);
16332
16815
  const runwayMinSeconds = Math.max(0, remaining - 1) / common.upperPacePerHour * 3600;
16333
16816
  const runwayMaxSeconds = Math.min(100, remaining + 1) / common.lowerPacePerHour * 3600;
16334
- const resetSeconds = resetsAt === null ? null : resetsAt - now / 1e3;
16335
- if (resetSeconds !== null && resetSeconds <= 0) return {
16336
- ...common,
16337
- status: "calibrating",
16338
- reason: "stale"
16339
- };
16817
+ const resetSeconds = resetsAt === null ? null : resetsAt - newest.at / 1e3;
16818
+ const survivesReset = confirmedBurst || resetSeconds === null ? "unknown" : runwayMinSeconds >= resetSeconds ? "yes" : runwayMaxSeconds < resetSeconds ? "no" : "unknown";
16340
16819
  return {
16341
16820
  ...common,
16342
16821
  status: "ready",
@@ -16344,7 +16823,8 @@ function estimateQuotaForecast(state, window, now = Date.now(), context = {}) {
16344
16823
  runwaySeconds: remaining / pacePerHour * 3600,
16345
16824
  runwayMinSeconds,
16346
16825
  runwayMaxSeconds,
16347
- survivesReset: resetSeconds !== null && runwayMinSeconds >= resetSeconds
16826
+ ...confirmedBurst ? { trace: "burst" } : {},
16827
+ survivesReset
16348
16828
  };
16349
16829
  }
16350
16830
  function forecastUsage(usage, state = { windows: {} }, now = Date.now(), options = {}) {
@@ -17724,9 +18204,9 @@ function withEndCallTool(desktopVoice, register) {
17724
18204
  //#endregion
17725
18205
  //#region src/voice-barge-in.js
17726
18206
  /** Mute interrupted speech, then resume when the old audio drains or a new reply begins. */
17727
- function createBargeInGate({ interrupt, changed, speechMs = 120, silenceMs = 400, outputTailMs = 0 }) {
18207
+ function createBargeInGate({ interrupt, changed, speechMs = 120, silenceMs = 400, outputTailMs = 0, drainTimeoutMs = 2400 }) {
17728
18208
  let speakingAt, quietAt, outputQuietAt, suppressed = false, drained = false;
17729
- let outputActiveAt, interruptionEpoch;
18209
+ let outputActiveAt, interruptionEpoch, suppressedAt;
17730
18210
  return { sample({ mic, output, now, replyEpoch }) {
17731
18211
  if (mic > .12) {
17732
18212
  speakingAt ??= now;
@@ -17743,11 +18223,13 @@ function createBargeInGate({ interrupt, changed, speechMs = 120, silenceMs = 400
17743
18223
  suppressed = true;
17744
18224
  drained = false;
17745
18225
  interruptionEpoch = replyEpoch;
18226
+ suppressedAt = now;
17746
18227
  changed(true);
17747
18228
  interrupt();
17748
18229
  }
17749
18230
  if (suppressed && outputQuietAt !== void 0 && now - outputQuietAt >= 250) drained = true;
17750
- if (suppressed && quietAt !== void 0 && (Number.isInteger(interruptionEpoch) && replyEpoch > interruptionEpoch && now - quietAt >= speechMs || drained && now - quietAt >= silenceMs)) {
18231
+ const freshReply = Number.isInteger(interruptionEpoch) && replyEpoch > interruptionEpoch;
18232
+ if (suppressed && quietAt !== void 0 && now - quietAt >= silenceMs && (freshReply || drained || now - suppressedAt >= drainTimeoutMs)) {
17751
18233
  suppressed = false;
17752
18234
  speakingAt = void 0;
17753
18235
  interruptionEpoch = void 0;
@@ -18592,6 +19074,7 @@ function apply(ctx, config = {}) {
18592
19074
  } : {},
18593
19075
  fetchRoutingAvailable: fetchRouted,
18594
19076
  [SPEED_MODE_FIELD]: settings.get()[SPEED_MODE_FIELD],
19077
+ [SPEED_SHORTCUT_FIELD]: normalizeSpeedShortcut(settings.get()[SPEED_SHORTCUT_FIELD]),
18595
19078
  [OUTPUT_VERBOSITY_FIELD]: normalizeOutputVerbosity(settings.get()[OUTPUT_VERBOSITY_FIELD]),
18596
19079
  [INPUT_IMAGE_DETAIL_FIELD]: normalizeInputImageDetail(settings.get()[INPUT_IMAGE_DETAIL_FIELD]),
18597
19080
  [REASONING_SUMMARY_FIELD]: normalizeReasoningSummary(settings.get()[REASONING_SUMMARY_FIELD]),
@@ -19040,6 +19523,7 @@ function apply(ctx, config = {}) {
19040
19523
  voice: {
19041
19524
  WebSocket,
19042
19525
  recovery: createVoiceTranscriptRecovery(dshHomePath("state", "codex-subscription", "voice-transcript-recovery")),
19526
+ resultStore: createVoiceResultStore(dshHomePath("state", "codex-subscription", "voice-results")),
19043
19527
  flushSession: (session) => ctx.get?.("sessions")?.flush?.(session),
19044
19528
  resolveProxy: resolveCodexOAuthProxy,
19045
19529
  fetch: (input, init) => network.fetch("voice", input, init),