@ykurilov/agent-chat-core 0.82.1 → 0.83.0

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.
@@ -2855,6 +2855,14 @@ var DuplicateChatSubjectError = class extends Error {
2855
2855
  ownerId;
2856
2856
  subjectKey;
2857
2857
  };
2858
+ var ChatTurnLeaseLostError = class extends Error {
2859
+ constructor(messageId) {
2860
+ super(`\u0417\u0430\u043F\u0438\u0441\u044C \u043E\u0442\u0432\u0435\u0442\u0430 ${messageId} \u043E\u0442\u043A\u043B\u043E\u043D\u0435\u043D\u0430: \u0430\u0440\u0435\u043D\u0434\u0430 \u0445\u043E\u0434\u0430 \u0443\u0442\u0440\u0430\u0447\u0435\u043D\u0430`);
2861
+ this.messageId = messageId;
2862
+ this.name = "ChatTurnLeaseLostError";
2863
+ }
2864
+ messageId;
2865
+ };
2858
2866
  var MessageAlreadyFinishedError = class extends Error {
2859
2867
  constructor(messageId) {
2860
2868
  super(`\u0421\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435 ${messageId} \u0443\u0436\u0435 \u0432 \u043A\u043E\u043D\u0435\u0447\u043D\u043E\u043C \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0438 \u0438 \u043D\u0435 \u043C\u0435\u043D\u044F\u0435\u0442\u0441\u044F`);
@@ -5401,18 +5409,26 @@ function gateToolCalls(tools, gate) {
5401
5409
  const refuseIfClosed = () => {
5402
5410
  if (gate.closed()) throw new Error(LAST_STEP_TOOL_REFUSAL);
5403
5411
  };
5412
+ const readyToExecute = (callOptions) => {
5413
+ refuseIfClosed();
5414
+ callOptions.abortSignal?.throwIfAborted();
5415
+ };
5404
5416
  const saved = (callOptions) => gate.callSaved ? withinWait(gate.callSaved(callOptions.toolCallId)) : Promise.resolve();
5405
5417
  gated[name] = {
5406
5418
  ...original,
5407
5419
  execute: isAsyncGeneratorFunction(gate.kindsFrom?.[name]?.execute ?? execute) ? (input, callOptions) => {
5408
- refuseIfClosed();
5420
+ readyToExecute(callOptions);
5409
5421
  return (async function* () {
5410
5422
  await saved(callOptions);
5423
+ readyToExecute(callOptions);
5411
5424
  yield* execute(input, callOptions);
5412
5425
  })();
5413
5426
  } : (input, callOptions) => {
5414
- refuseIfClosed();
5415
- return saved(callOptions).then(() => execute(input, callOptions));
5427
+ readyToExecute(callOptions);
5428
+ return saved(callOptions).then(() => {
5429
+ readyToExecute(callOptions);
5430
+ return execute(input, callOptions);
5431
+ });
5416
5432
  }
5417
5433
  };
5418
5434
  }
@@ -5423,9 +5439,11 @@ function gateToolApproval(toolApproval, closed) {
5423
5439
  }
5424
5440
  function withinWait(saved) {
5425
5441
  let timer;
5426
- const cap = new Promise((resolve) => timer = setTimeout(resolve, CALL_SAVE_WAIT_MS));
5427
- return Promise.race([saved.catch(() => {
5428
- }), cap]).finally(() => clearTimeout(timer));
5442
+ const refusal = () => new Error("\u0414\u0435\u0439\u0441\u0442\u0432\u0438\u0435 \u043D\u0435 \u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u043E: \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435 \u043D\u0435 \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0434\u0438\u043B\u043E \u0437\u0430\u043F\u0438\u0441\u044C \u0432\u044B\u0437\u043E\u0432\u0430 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u0430");
5443
+ const cap = new Promise((_resolve, reject) => timer = setTimeout(() => reject(refusal()), CALL_SAVE_WAIT_MS));
5444
+ return Promise.race([saved, cap]).catch(() => {
5445
+ throw refusal();
5446
+ }).finally(() => clearTimeout(timer));
5429
5447
  }
5430
5448
 
5431
5449
  // src/agent-run/next-attempt.ts
@@ -5822,7 +5840,7 @@ var STALE_ANSWERS_SWEEP_EVERY_MS = 5e3;
5822
5840
  // src/agent-run/answer-saver.ts
5823
5841
  var SAVE_INTERVAL_MS = 500;
5824
5842
  var isFinalToolResult = (chunk) => chunk.type === "tool-output-error" || chunk.type === "tool-output-available" && !chunk.preliminary;
5825
- var callIdsOf = (parts) => parts.flatMap((part) => "toolCallId" in part && typeof part.toolCallId === "string" ? [part.toolCallId] : []);
5843
+ var callIdsOf = (parts) => parts.flatMap((part) => "toolCallId" in part && typeof part.toolCallId === "string" && "state" in part && typeof part.state === "string" && part.state !== "input-streaming" ? [part.toolCallId] : []);
5826
5844
  function createAnswerSaver(storage, messageId, durations, usage, onTakenOver, existing, decorateParts = (parts) => parts) {
5827
5845
  let feed;
5828
5846
  let latest = existing?.parts ?? [];
@@ -5845,10 +5863,21 @@ function createAnswerSaver(storage, messageId, durations, usage, onTakenOver, ex
5845
5863
  let released = false;
5846
5864
  const writtenCalls = new Set(callIdsOf(latest));
5847
5865
  const callWaiters = /* @__PURE__ */ new Map();
5848
- function callsWritten(parts) {
5849
- for (const id of callIdsOf(parts)) {
5866
+ const failedCalls = /* @__PURE__ */ new Map();
5867
+ const callNotSaved = () => new Error("\u0414\u0435\u0439\u0441\u0442\u0432\u0438\u0435 \u043D\u0435 \u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D\u043E: \u0432\u044B\u0437\u043E\u0432 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u0430 \u043D\u0435 \u0437\u0430\u043F\u0438\u0441\u0430\u043D \u0432 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435");
5868
+ function callsWritten(ids) {
5869
+ for (const id of ids) {
5850
5870
  writtenCalls.add(id);
5851
- for (const release of callWaiters.get(id) ?? []) release();
5871
+ for (const waiter of callWaiters.get(id) ?? []) waiter.resolve();
5872
+ callWaiters.delete(id);
5873
+ }
5874
+ }
5875
+ function callsFailed(ids) {
5876
+ for (const id of ids) {
5877
+ if (writtenCalls.has(id)) continue;
5878
+ const error = failedCalls.get(id) ?? callNotSaved();
5879
+ failedCalls.set(id, error);
5880
+ for (const waiter of callWaiters.get(id) ?? []) waiter.reject(error);
5852
5881
  callWaiters.delete(id);
5853
5882
  }
5854
5883
  }
@@ -5858,6 +5887,7 @@ function createAnswerSaver(storage, messageId, durations, usage, onTakenOver, ex
5858
5887
  lastWriteAt = Date.now();
5859
5888
  lastSignAt = lastWriteAt;
5860
5889
  const parts = decorateParts(latest);
5890
+ const completeCalls = callIdsOf(parts);
5861
5891
  try {
5862
5892
  await storage.updateStreamingMessage(messageId, {
5863
5893
  parts,
@@ -5865,11 +5895,12 @@ function createAnswerSaver(storage, messageId, durations, usage, onTakenOver, ex
5865
5895
  usage: usage(),
5866
5896
  alive: released ? "released" : "now"
5867
5897
  });
5898
+ callsWritten(completeCalls);
5868
5899
  } catch (failure) {
5900
+ callsFailed(completeCalls);
5869
5901
  noteFailure(failure);
5870
5902
  }
5871
5903
  savedChanges = Math.max(savedChanges, writtenChanges);
5872
- callsWritten(parts);
5873
5904
  }
5874
5905
  async function markAlive() {
5875
5906
  lastSignAt = Date.now();
@@ -5880,14 +5911,14 @@ function createAnswerSaver(storage, messageId, durations, usage, onTakenOver, ex
5880
5911
  }
5881
5912
  }
5882
5913
  function noteFailure(failure) {
5883
- if (failure instanceof MessageAlreadyFinishedError) {
5914
+ if (failure instanceof MessageAlreadyFinishedError || failure instanceof ChatTurnLeaseLostError) {
5884
5915
  stop();
5885
5916
  onTakenOver();
5886
5917
  }
5887
5918
  }
5888
5919
  function stop() {
5889
5920
  closed = true;
5890
- for (const waiters of callWaiters.values()) for (const release of waiters) release();
5921
+ for (const waiters of callWaiters.values()) for (const waiter of waiters) waiter.reject(callNotSaved());
5891
5922
  callWaiters.clear();
5892
5923
  clearTimeout(timer);
5893
5924
  timer = void 0;
@@ -5986,10 +6017,13 @@ function createAnswerSaver(storage, messageId, durations, usage, onTakenOver, ex
5986
6017
  push(chunk);
5987
6018
  if ((isFinalToolResult(chunk) || chunk.type === "tool-input-available") && !closed) void settleAssembly().then(writeNow);
5988
6019
  },
5989
- /** Ждёт, пока начатый вызов попадёт в хранилище; записи больше не будет (ход кончен, ответ закрыт) — сразу. */
6020
+ /** Ждёт подтверждённую запись; сбой или остановка до неё — отказ, включая позднего ожидающего. */
5990
6021
  whenCallSaved(toolCallId) {
5991
- if (closed || writtenCalls.has(toolCallId)) return Promise.resolve();
5992
- return new Promise((resolve) => callWaiters.set(toolCallId, [...callWaiters.get(toolCallId) ?? [], resolve]));
6022
+ const failure = failedCalls.get(toolCallId);
6023
+ if (failure) return Promise.reject(failure);
6024
+ if (writtenCalls.has(toolCallId)) return Promise.resolve();
6025
+ if (closed) return Promise.reject(callNotSaved());
6026
+ return new Promise((resolve, reject) => callWaiters.set(toolCallId, [...callWaiters.get(toolCallId) ?? [], { resolve, reject }]));
5993
6027
  },
5994
6028
  /**
5995
6029
  * Стирает части ответа с номера `keep`: сборка начинается заново с оставшихся, запись — сразу, без окна: упади
@@ -6040,12 +6074,26 @@ function createAnswerSaver(storage, messageId, durations, usage, onTakenOver, ex
6040
6074
  return latest;
6041
6075
  },
6042
6076
  /** Ждёт сборку и идущую запись; возвращает итоговые части — их запишет конечная запись хода. */
6043
- async finish() {
6077
+ async finish(lostOwnership) {
6044
6078
  stop();
6045
6079
  feed.close();
6046
6080
  await assembling.catch(() => {
6047
6081
  });
6048
- await writing;
6082
+ if (writing && lostOwnership) {
6083
+ const pending = writing;
6084
+ await new Promise((resolve, reject) => {
6085
+ const done = () => {
6086
+ lostOwnership.removeEventListener("abort", done);
6087
+ resolve();
6088
+ };
6089
+ if (lostOwnership.aborted) return done();
6090
+ lostOwnership.addEventListener("abort", done, { once: true });
6091
+ pending.then(done, (error) => {
6092
+ lostOwnership.removeEventListener("abort", done);
6093
+ reject(error);
6094
+ });
6095
+ });
6096
+ } else await writing;
6049
6097
  return latest;
6050
6098
  },
6051
6099
  /** Ход кончился, в том числе исключением: таймеров записи и знака жизни больше нет. */
@@ -7107,7 +7155,7 @@ async function runTurn(turnInput, emitRaw) {
7107
7155
  };
7108
7156
  const takeover = new AbortController();
7109
7157
  const noNewAttempts = new AbortController();
7110
- const input = { ...turnInput, abortSignal: AbortSignal.any([turnInput.abortSignal, takeover.signal, noNewAttempts.signal]) };
7158
+ const input = { ...turnInput, abortSignal: AbortSignal.any([turnInput.abortSignal, takeover.signal, noNewAttempts.signal, ...turnInput.leaseSignal ? [turnInput.leaseSignal] : []]) };
7111
7159
  const { storage, messageId, modelId, resume } = input;
7112
7160
  const logError = input.logError ?? console.error;
7113
7161
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
@@ -7172,6 +7220,12 @@ async function runTurn(turnInput, emitRaw) {
7172
7220
  resume?.message,
7173
7221
  thoughtTitles && ((parts) => withThoughtTitles(parts, thoughtTitles.titles(), new Set(thoughtTitles.askedKeys())))
7174
7222
  );
7223
+ const onLeaseLost = () => {
7224
+ takeover.abort();
7225
+ saver.stop();
7226
+ };
7227
+ if (input.leaseSignal?.aborted) onLeaseLost();
7228
+ else input.leaseSignal?.addEventListener("abort", onLeaseLost, { once: true });
7175
7229
  emitTitles = (titles) => {
7176
7230
  const metadata = { thoughtTitles: titles };
7177
7231
  saver.observe({ type: "message-metadata", messageMetadata: metadata });
@@ -7590,8 +7644,9 @@ async function runTurn(turnInput, emitRaw) {
7590
7644
  if (!input.abortSignal.aborted && errors.length === 0) await thoughtTitles.settle(input.thoughtTitles.settleMs ?? THOUGHT_TITLES_SETTLE_MS);
7591
7645
  thoughtTitles.close();
7592
7646
  }
7593
- const savedParts = await saver.finish();
7647
+ const savedParts = await saver.finish(takeover.signal);
7594
7648
  const reasoningDurationsMs = timer.finalize();
7649
+ if (input.leaseSignal?.aborted) return await finishTakenOverTurn(reasoningDurationsMs);
7595
7650
  const failed = input.abortSignal.aborted || errors.length > 0;
7596
7651
  const closing = !failed && pendingHumanInput(savedParts, input.waitingWidgets).length > 0 && (closure !== void 0 || await chatClosedNow());
7597
7652
  const titledParts = thoughtTitles ? withThoughtTitles(savedParts, thoughtTitles.titles(), new Set(thoughtTitles.askedKeys())) : savedParts;
@@ -7648,12 +7703,12 @@ async function runTurn(turnInput, emitRaw) {
7648
7703
  logError
7649
7704
  );
7650
7705
  } catch (failure) {
7651
- if (!(failure instanceof MessageAlreadyFinishedError)) throw failure;
7706
+ if (!(failure instanceof MessageAlreadyFinishedError) && !(failure instanceof ChatTurnLeaseLostError)) throw failure;
7652
7707
  takeover.abort();
7653
7708
  }
7654
7709
  }
7655
7710
  if (closure) await applyChatClosure(closure);
7656
- if (takeover.signal.aborted) return await finishTakenOverTurn(reasoningDurationsMs);
7711
+ if (takeover.signal.aborted && !finished) return await finishTakenOverTurn(reasoningDurationsMs);
7657
7712
  if (!finished) {
7658
7713
  await storage.updateStreamingMessage(messageId, { parts, reasoningDurationsMs, usage: streamingUsage(), alive: "released" }).catch(() => {
7659
7714
  });
@@ -7727,9 +7782,10 @@ async function runTurn(turnInput, emitRaw) {
7727
7782
  async function finishTakenOverTurn(reasoningDurationsMs2) {
7728
7783
  turnUsage.closeAttempt();
7729
7784
  const usage2 = messageUsage();
7730
- if (input.ownerId && usage2) {
7785
+ if (input.ownerId && usage2 && !input.leaseSignal?.aborted) {
7731
7786
  const taken = await storage.getMessage(messageId).then(
7732
- (closed) => [closed?.usage ?? {}],
7787
+ // Потеря аренды ещё не значит, что чужая копия закрыла ответ. Идущий снимок учтёт recovery.
7788
+ (closed) => closed?.status === "streaming" ? null : [closed?.usage ?? {}],
7733
7789
  (failure) => {
7734
7790
  logError(`\u0420\u0430\u0441\u0445\u043E\u0434 \u043F\u0435\u0440\u0435\u0445\u0432\u0430\u0447\u0435\u043D\u043D\u043E\u0433\u043E \u043E\u0442\u0432\u0435\u0442\u0430 ${messageId} \u043D\u0435 \u0437\u0430\u043F\u0438\u0441\u0430\u043D: ${failure instanceof Error ? failure.message : "\u043D\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043D\u0430\u044F \u043E\u0448\u0438\u0431\u043A\u0430"}`);
7735
7791
  return null;
@@ -7758,6 +7814,7 @@ async function runTurn(turnInput, emitRaw) {
7758
7814
  }
7759
7815
  } finally {
7760
7816
  saver.stop();
7817
+ input.leaseSignal?.removeEventListener("abort", onLeaseLost);
7761
7818
  thoughtTitles?.close();
7762
7819
  input.flushers?.delete(saver.flush);
7763
7820
  }
@@ -8305,6 +8362,10 @@ async function finishWithRetries(storage, messageId, final, logError) {
8305
8362
  } catch (caught) {
8306
8363
  failure = caught;
8307
8364
  }
8365
+ if (failure instanceof ChatTurnLeaseLostError) {
8366
+ if (attempt > 0 && await isOurFinal(storage, messageId, final).catch(() => false)) return true;
8367
+ throw failure;
8368
+ }
8308
8369
  if (failure instanceof MessageAlreadyFinishedError) {
8309
8370
  if (attempt === 0) throw failure;
8310
8371
  const finished = failure;
@@ -12135,33 +12196,92 @@ var CHAT_TURN_LEASE_MS = ANSWER_STALE_AFTER_MS;
12135
12196
  var CHAT_TURN_RENEW_EVERY_MS = ANSWER_ALIVE_EVERY_MS;
12136
12197
  function createChatTurnLeases(input) {
12137
12198
  const { storage, holder, logError } = input;
12138
- if (!storage.claimChatTurn || !storage.releaseChatTurn) return { enter: async () => true, leave: () => {
12199
+ if (!storage.claimChatTurn || !storage.releaseChatTurn) return { enter: async () => true, signal: () => void 0, holder: () => void 0, invalidate: () => {
12200
+ }, leave: () => {
12139
12201
  }, releaseAll: async () => {
12140
12202
  }, clearForeign: async () => {
12141
12203
  } };
12142
12204
  const claim = storage.claimChatTurn.bind(storage);
12143
12205
  const release = storage.releaseChatTurn.bind(storage);
12144
12206
  const held = /* @__PURE__ */ new Map();
12207
+ let generation = 0;
12145
12208
  const claiming = /* @__PURE__ */ new Map();
12146
12209
  const releasing = /* @__PURE__ */ new Map();
12210
+ function lose(chatId, lease, reason) {
12211
+ if (held.get(chatId) !== lease || lease.lost) return;
12212
+ lease.lost = true;
12213
+ clearInterval(lease.renew);
12214
+ clearTimeout(lease.expiry);
12215
+ lease.controller.abort(new Error("\u0410\u0440\u0435\u043D\u0434\u0430 \u0445\u043E\u0434\u0430 \u0443\u0442\u0440\u0430\u0447\u0435\u043D\u0430"));
12216
+ logError(`\u0410\u0440\u0435\u043D\u0434\u0430 \u0445\u043E\u0434\u0430 \u0447\u0430\u0442\u0430 ${chatId} \u0443\u0442\u0440\u0430\u0447\u0435\u043D\u0430: ${reason}; \u0445\u043E\u0434 \u043E\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D`);
12217
+ input.onLost?.(chatId);
12218
+ }
12219
+ function confirmedUntil(chatId, lease, claimStarted) {
12220
+ if (held.get(chatId) !== lease || lease.lost) return;
12221
+ if (lease.until <= Date.now()) return lose(chatId, lease, "\u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0451\u043D\u043D\u044B\u0439 \u0441\u0440\u043E\u043A \u0443\u0436\u0435 \u0438\u0441\u0442\u0451\u043A");
12222
+ clearTimeout(lease.expiry);
12223
+ lease.until = claimStarted + CHAT_TURN_LEASE_MS;
12224
+ const left = lease.until - Date.now();
12225
+ if (left <= 0) return lose(chatId, lease, "\u0438\u0441\u0442\u0451\u043A \u0441\u0440\u043E\u043A \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0451\u043D\u043D\u043E\u0439 \u0430\u0440\u0435\u043D\u0434\u044B");
12226
+ const checkExpiry = () => {
12227
+ if (held.get(chatId) !== lease || lease.lost) return;
12228
+ const remaining = lease.until - Date.now();
12229
+ if (remaining <= 0) return lose(chatId, lease, "\u043F\u0440\u043E\u0434\u043B\u0435\u043D\u0438\u0435 \u043D\u0435 \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u043E \u0434\u043E \u0438\u0441\u0442\u0435\u0447\u0435\u043D\u0438\u044F \u0441\u0440\u043E\u043A\u0430");
12230
+ lease.expiry = setTimeout(checkExpiry, remaining);
12231
+ lease.expiry.unref?.();
12232
+ };
12233
+ lease.expiry = setTimeout(checkExpiry, left);
12234
+ lease.expiry.unref?.();
12235
+ }
12147
12236
  const renewing = (chatId) => setInterval(() => {
12148
12237
  const lease = held.get(chatId);
12149
- if (!lease || lease.renewing) return;
12150
- lease.renewing = claim(chatId, holder, CHAT_TURN_LEASE_MS).then(
12238
+ if (!lease || lease.lost || lease.renewing) return;
12239
+ if (lease.until <= Date.now()) return lose(chatId, lease, "\u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0451\u043D\u043D\u044B\u0439 \u0441\u0440\u043E\u043A \u0438\u0441\u0442\u0451\u043A \u0434\u043E \u043F\u0440\u043E\u0434\u043B\u0435\u043D\u0438\u044F");
12240
+ const started = Date.now();
12241
+ lease.renewing = Promise.resolve().then(() => lease.lost || held.get(chatId) !== lease ? false : claim(chatId, lease.token, CHAT_TURN_LEASE_MS)).then(
12151
12242
  (kept) => {
12152
- if (!kept && held.has(chatId)) logError(`\u0410\u0440\u0435\u043D\u0434\u0430 \u0445\u043E\u0434\u0430 \u0447\u0430\u0442\u0430 ${chatId} \u0443\u0448\u043B\u0430 \u043A \u0434\u0440\u0443\u0433\u043E\u0439 \u043A\u043E\u043F\u0438\u0438 \u043F\u043E\u0441\u0440\u0435\u0434\u0438 \u0445\u043E\u0434\u0430: \u043F\u0440\u043E\u0434\u043B\u0435\u043D\u0438\u0435 \u043E\u043F\u043E\u0437\u0434\u0430\u043B\u043E`);
12243
+ if (held.get(chatId) !== lease || lease.lost) return;
12244
+ if (!kept) lose(chatId, lease, "\u0434\u0440\u0443\u0433\u043E\u0439 \u0434\u0435\u0440\u0436\u0430\u0442\u0435\u043B\u044C");
12245
+ else confirmedUntil(chatId, lease, started);
12153
12246
  },
12154
- (error) => logError(`\u0410\u0440\u0435\u043D\u0434\u0430 \u0445\u043E\u0434\u0430 \u0447\u0430\u0442\u0430 ${chatId} \u043D\u0435 \u043F\u0440\u043E\u0434\u043B\u0438\u043B\u0430\u0441\u044C: ${error instanceof Error ? error.message : String(error)}`)
12247
+ () => lose(chatId, lease, "\u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435 \u043D\u0435 \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0434\u0438\u043B\u043E \u043F\u0440\u043E\u0434\u043B\u0435\u043D\u0438\u0435")
12155
12248
  ).finally(() => {
12156
12249
  lease.renewing = void 0;
12157
12250
  });
12158
12251
  }, CHAT_TURN_RENEW_EVERY_MS);
12252
+ function renewalBarrier(chatId, lease) {
12253
+ const pending = lease.renewing;
12254
+ if (!pending) return void 0;
12255
+ return new Promise((resolve) => {
12256
+ let settled2 = false;
12257
+ let timer;
12258
+ const finish = (expired) => {
12259
+ if (settled2) return;
12260
+ settled2 = true;
12261
+ clearTimeout(timer);
12262
+ if (expired) {
12263
+ void pending.then(() => release(chatId, lease.token), () => release(chatId, lease.token)).catch((error) => {
12264
+ logError(`\u041F\u043E\u0437\u0434\u043D\u0435\u0435 \u0441\u043D\u044F\u0442\u0438\u0435 \u0430\u0440\u0435\u043D\u0434\u044B \u0447\u0430\u0442\u0430 ${chatId} \u043D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C: ${error instanceof Error ? error.message : String(error)}`);
12265
+ });
12266
+ }
12267
+ resolve();
12268
+ };
12269
+ pending.then(() => finish(false), () => finish(false));
12270
+ const remaining = lease.until - Date.now();
12271
+ if (lease.lost || remaining <= 0) finish(true);
12272
+ else {
12273
+ timer = setTimeout(() => finish(true), remaining);
12274
+ timer.unref?.();
12275
+ }
12276
+ });
12277
+ }
12159
12278
  function releasingLease(chatId, lease) {
12160
12279
  clearInterval(lease.renew);
12280
+ clearTimeout(lease.expiry);
12161
12281
  held.delete(chatId);
12162
12282
  const previous = releasing.get(chatId);
12163
- const after = [previous, lease.renewing].filter((step) => step !== void 0);
12164
- const done = (after.length > 0 ? Promise.all(after).then(() => release(chatId, holder)) : release(chatId, holder)).catch((error) => {
12283
+ const after = [previous, renewalBarrier(chatId, lease)].filter((step) => step !== void 0);
12284
+ const done = (after.length > 0 ? Promise.all(after).then(() => release(chatId, lease.token)) : release(chatId, lease.token)).catch((error) => {
12165
12285
  logError(`\u0410\u0440\u0435\u043D\u0434\u0430 \u0445\u043E\u0434\u0430 \u0447\u0430\u0442\u0430 ${chatId} \u043D\u0435 \u0441\u043D\u044F\u043B\u0430\u0441\u044C: ${error instanceof Error ? error.message : String(error)}`);
12166
12286
  }).finally(() => {
12167
12287
  if (releasing.get(chatId) === done) releasing.delete(chatId);
@@ -12173,6 +12293,7 @@ function createChatTurnLeases(input) {
12173
12293
  for (; ; ) {
12174
12294
  const lease = held.get(chatId);
12175
12295
  if (lease) {
12296
+ if (lease.lost) throw new ChatBusyError(chatId);
12176
12297
  lease.count += 1;
12177
12298
  return true;
12178
12299
  }
@@ -12182,8 +12303,16 @@ function createChatTurnLeases(input) {
12182
12303
  });
12183
12304
  }
12184
12305
  const taking = (async () => {
12185
- if (!await claim(chatId, holder, CHAT_TURN_LEASE_MS)) throw new ChatBusyError(chatId);
12186
- held.set(chatId, { count: 1, renew: renewing(chatId) });
12306
+ const started = Date.now();
12307
+ const token = `${holder}:${++generation}`;
12308
+ if (!await claim(chatId, token, CHAT_TURN_LEASE_MS)) throw new ChatBusyError(chatId);
12309
+ if (started + CHAT_TURN_LEASE_MS <= Date.now()) {
12310
+ await release(chatId, token);
12311
+ throw new ChatBusyError(chatId);
12312
+ }
12313
+ const lease = { count: 1, renew: renewing(chatId), controller: new AbortController(), lost: false, token, until: started + CHAT_TURN_LEASE_MS };
12314
+ held.set(chatId, lease);
12315
+ confirmedUntil(chatId, lease, started);
12187
12316
  })();
12188
12317
  claiming.set(chatId, taking);
12189
12318
  try {
@@ -12196,6 +12325,16 @@ function createChatTurnLeases(input) {
12196
12325
  claiming.delete(chatId);
12197
12326
  }
12198
12327
  },
12328
+ signal(chatId) {
12329
+ return held.get(chatId)?.controller.signal;
12330
+ },
12331
+ holder(chatId) {
12332
+ return held.get(chatId)?.token;
12333
+ },
12334
+ invalidate(chatId, token) {
12335
+ const lease = held.get(chatId);
12336
+ if (lease?.token === token) lose(chatId, lease, "\u0437\u0430\u043F\u0438\u0441\u044C \u043E\u0442\u043A\u043B\u043E\u043D\u0435\u043D\u0430 \u0430\u0442\u043E\u043C\u0430\u0440\u043D\u043E\u0439 \u043E\u0433\u0440\u0430\u0434\u043E\u0439 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430");
12337
+ },
12199
12338
  leave(chatId) {
12200
12339
  const lease = held.get(chatId);
12201
12340
  if (!lease) return;
@@ -12210,11 +12349,52 @@ function createChatTurnLeases(input) {
12210
12349
  async clearForeign() {
12211
12350
  if (!storage.clearChatTurnLeases) return;
12212
12351
  await storage.clearChatTurnLeases();
12213
- await Promise.all([...held.keys()].map((chatId) => claim(chatId, holder, CHAT_TURN_LEASE_MS)));
12352
+ await Promise.all([...held].filter(([, lease]) => !lease.lost).map(async ([chatId, lease]) => {
12353
+ const started = Date.now();
12354
+ try {
12355
+ if (!await claim(chatId, lease.token, CHAT_TURN_LEASE_MS)) return lose(chatId, lease, "\u043D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0432\u0435\u0440\u043D\u0443\u0442\u044C \u0441\u043E\u0431\u0441\u0442\u0432\u0435\u043D\u043D\u0443\u044E \u0430\u0440\u0435\u043D\u0434\u0443 \u043F\u043E\u0441\u043B\u0435 startup recovery");
12356
+ confirmedUntil(chatId, lease, started);
12357
+ } catch (error) {
12358
+ lose(chatId, lease, "\u043D\u0435 \u043F\u043E\u0434\u0442\u0432\u0435\u0440\u0436\u0434\u0435\u043D\u043E \u0432\u043B\u0430\u0434\u0435\u043D\u0438\u0435 \u043F\u043E\u0441\u043B\u0435 startup recovery");
12359
+ throw error;
12360
+ }
12361
+ }));
12214
12362
  }
12215
12363
  };
12216
12364
  }
12217
12365
 
12366
+ // src/chat-turn-storage.ts
12367
+ function guardedTurnStorage(storage, input) {
12368
+ const guard = { expectedTurnHolder: input.holder };
12369
+ const check = (messageId) => {
12370
+ if (input.signal.aborted) throw new ChatTurnLeaseLostError(messageId);
12371
+ };
12372
+ async function writing(messageId, work, committedFinal = false) {
12373
+ check(messageId);
12374
+ try {
12375
+ await work();
12376
+ if (!committedFinal) check(messageId);
12377
+ } catch (error) {
12378
+ if (error instanceof ChatTurnLeaseLostError) input.onLost();
12379
+ throw error;
12380
+ }
12381
+ }
12382
+ const guarded = {
12383
+ insertMessage: (message) => writing(message.id, () => storage.insertMessage(message, guard)),
12384
+ updateStreamingMessage: (id, patch) => writing(id, () => storage.updateStreamingMessage(id, { ...patch, ...guard })),
12385
+ finishMessage: (id, patch) => writing(id, () => storage.finishMessage(id, { ...patch, ...guard }), true),
12386
+ updateAwaitingMessage: (id, patch) => writing(id, () => storage.updateAwaitingMessage(id, { ...patch, ...guard })),
12387
+ ...storage.markAnswerAlive && { markAnswerAlive: (id) => writing(id, () => storage.markAnswerAlive(id, guard)) }
12388
+ };
12389
+ return new Proxy(storage, {
12390
+ get(target, key) {
12391
+ if (Object.hasOwn(guarded, key)) return Reflect.get(guarded, key);
12392
+ const value = Reflect.get(target, key, target);
12393
+ return typeof value === "function" ? value.bind(target) : value;
12394
+ }
12395
+ });
12396
+ }
12397
+
12218
12398
  // src/running-answers/live-turns.ts
12219
12399
  var TurnStop = class extends Error {
12220
12400
  constructor(reason) {
@@ -13020,11 +13200,30 @@ function createChatService(input) {
13020
13200
  const startingByChat = /* @__PURE__ */ new Map();
13021
13201
  const burstWaits = createBurstWaits();
13022
13202
  const copyId = crypto.randomUUID();
13023
- const turnLeases = createChatTurnLeases({ storage, holder: copyId, logError });
13203
+ if (storage.claimChatTurn && storage.releaseChatTurn && storage.guardedTurnWrites !== true) {
13204
+ throw new TypeError("ChatStorage \u0441 \u0430\u0440\u0435\u043D\u0434\u043E\u0439 \u0445\u043E\u0434\u0430 \u0434\u043E\u043B\u0436\u0435\u043D \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u0430\u0442\u044C guardedTurnWrites \u0438 \u0430\u0442\u043E\u043C\u0430\u0440\u043D\u044B\u0439 ChatTurnWriteGuard. \u0421\u043C. docs/turn-durability.md");
13205
+ }
13206
+ const turnLeases = createChatTurnLeases({ storage, holder: copyId, logError, onLost: (chatId) => {
13207
+ registry.abort(chatId);
13208
+ widgetChecks.get(chatId)?.abort();
13209
+ } });
13210
+ function ownedTurnSignal(chatId) {
13211
+ const signal = turnLeases.signal(chatId);
13212
+ if (storage.claimChatTurn && storage.releaseChatTurn && (!turnLeases.holder(chatId) || !signal || signal.aborted)) {
13213
+ throw new ChatBusyError(chatId);
13214
+ }
13215
+ return signal;
13216
+ }
13217
+ function turnStorage(chatId) {
13218
+ const signal = turnLeases.signal(chatId);
13219
+ const holder = turnLeases.holder(chatId);
13220
+ return signal && holder !== void 0 ? guardedTurnStorage(storage, { holder, signal, onLost: () => turnLeases.invalidate(chatId, holder) }) : storage;
13221
+ }
13024
13222
  const burstSweeps = /* @__PURE__ */ new Set();
13025
13223
  const burstWrites = /* @__PURE__ */ new Map();
13026
13224
  const chatToolQueues = /* @__PURE__ */ new Map();
13027
13225
  let staleSweep = null;
13226
+ let recoverBurstsOnSweep = false;
13028
13227
  const resumeBases = /* @__PURE__ */ new Map();
13029
13228
  const compaction = createCompactionService({
13030
13229
  storage,
@@ -13109,7 +13308,7 @@ function createChatService(input) {
13109
13308
  if (OPEN_CHAT_ACTIONS.has(input2.action)) await assertStillOpen(chatId);
13110
13309
  else await carryLegacyClosure(chatId);
13111
13310
  return start(pass);
13112
- }, input2.action === "widget" || input2.action === "approval" ? "optional" : "required");
13311
+ }, input2.action === "widget" || input2.action === "approval" ? false : "required");
13113
13312
  }
13114
13313
  async function finalAnswerOf(answerId) {
13115
13314
  const answer = await storage.getMessage(answerId);
@@ -13491,7 +13690,7 @@ function createChatService(input) {
13491
13690
  }
13492
13691
  async function whileStarting(chatId, start, lease = "required") {
13493
13692
  if (closing || starting.has(chatId) || registry.isRunning(chatId)) throw new ChatBusyError(chatId);
13494
- return holdingChat(chatId, start, { lease });
13693
+ return holdingChat(chatId, start, lease === false ? {} : { lease });
13495
13694
  }
13496
13695
  async function holdingChat(chatId, work, holding = {}) {
13497
13696
  starting.add(chatId);
@@ -13510,10 +13709,30 @@ function createChatService(input) {
13510
13709
  writePendingRecords(chatId);
13511
13710
  }
13512
13711
  }
13712
+ async function withAwaitingLease(chatId, work) {
13713
+ let leased = false;
13714
+ try {
13715
+ return await work(async () => {
13716
+ if (!leased) {
13717
+ await turnLeases.enter(chatId);
13718
+ leased = true;
13719
+ }
13720
+ });
13721
+ } catch (error) {
13722
+ if (error instanceof ChatTurnLeaseLostError) throw new ChatBusyError(chatId);
13723
+ throw error;
13724
+ } finally {
13725
+ if (leased && registry.isRunning(chatId)) void registry.finished(chatId).finally(() => turnLeases.leave(chatId));
13726
+ else if (leased) turnLeases.leave(chatId);
13727
+ }
13728
+ }
13513
13729
  async function leasedWork(chatId, work, lease) {
13514
13730
  const leased = await turnLeases.enter(chatId, { optional: lease === "optional" });
13515
13731
  try {
13516
13732
  return await work();
13733
+ } catch (error) {
13734
+ if (error instanceof ChatTurnLeaseLostError) throw new ChatBusyError(chatId);
13735
+ throw error;
13517
13736
  } finally {
13518
13737
  if (leased && registry.isRunning(chatId)) void registry.finished(chatId).finally(() => turnLeases.leave(chatId));
13519
13738
  else if (leased) turnLeases.leave(chatId);
@@ -13574,12 +13793,22 @@ function createChatService(input) {
13574
13793
  });
13575
13794
  if (written) await writeClosureCopy(chat.ownerId, chatId, closed);
13576
13795
  }
13577
- async function writeToWaiting(waiting, build) {
13796
+ async function writeToWaiting(waiting, build, beforeResume) {
13578
13797
  let current = waiting;
13798
+ if (beforeResume) {
13799
+ const fresh = await storage.getMessage(waiting.id);
13800
+ if (fresh?.status !== "awaiting_approval") throw new MessageNotAwaitingError(waiting.id);
13801
+ current = fresh;
13802
+ }
13579
13803
  for (let attempt = 1; ; attempt++) {
13580
13804
  const patch = build(current);
13581
13805
  try {
13582
- await storage.updateAwaitingMessage(current.id, { ...patch, expectedParts: current.parts });
13806
+ if (patch.status === "streaming" && beforeResume) {
13807
+ await beforeResume();
13808
+ ownedTurnSignal(current.chatId);
13809
+ if (!(await currentBranch(current.chatId)).some((message) => message.id === current.id)) throw new MessageNotAwaitingError(current.id);
13810
+ }
13811
+ await turnStorage(current.chatId).updateAwaitingMessage(current.id, { ...patch, expectedParts: current.parts });
13583
13812
  return { ...current, parts: patch.parts, ...patch.status && { status: patch.status } };
13584
13813
  } catch (error) {
13585
13814
  if (!(error instanceof MessageNotAwaitingError) || attempt >= WAITING_WRITE_ATTEMPTS) throw error;
@@ -13640,6 +13869,7 @@ function createChatService(input) {
13640
13869
  return stream;
13641
13870
  }
13642
13871
  async function launchTurn(userId, chatId, branch, launch) {
13872
+ ownedTurnSignal(chatId);
13643
13873
  const chat = await ownChat(userId, chatId);
13644
13874
  const stateBefore = launch.stateBefore ?? foldAppState(branch);
13645
13875
  const { channel, group } = turnChannelOf(branch);
@@ -13663,6 +13893,7 @@ function createChatService(input) {
13663
13893
  chatToolQueues.set(chatId, toolQueue);
13664
13894
  const turnThoughtTitles = await thoughtTitlesForTurn(chat.ownerId, chatId, answerId, branch);
13665
13895
  const limits = turnLimits.forModel(model.modelId);
13896
+ const leaseSignal = ownedTurnSignal(chatId);
13666
13897
  const liveTurn = liveTurns.begin(limits.timeoutMs);
13667
13898
  let started;
13668
13899
  let steeringTurn;
@@ -13670,7 +13901,8 @@ function createChatService(input) {
13670
13901
  started = registry.start(chatId, answerId, (stopSignal) => {
13671
13902
  const abortSignal = AbortSignal.any([stopSignal, liveTurn.signal]);
13672
13903
  return runAgentTurn({
13673
- storage,
13904
+ storage: turnStorage(chatId),
13905
+ ...leaseSignal && { leaseSignal },
13674
13906
  now,
13675
13907
  liveDemos: input.agent.liveDemos === true,
13676
13908
  hiddenStateKey,
@@ -14728,7 +14960,7 @@ function createChatService(input) {
14728
14960
  async answerApproval(userId, chatId, approvalId, answer, page) {
14729
14961
  const chat = await ownChat(userId, chatId);
14730
14962
  await assertChatRules(userId, chat, { open: true });
14731
- return startingTurn({ userId, chat, action: "approval" }, async () => {
14963
+ return startingTurn({ userId, chat, action: "approval" }, () => withAwaitingLease(chatId, async (ensureResumeLease) => {
14732
14964
  const branch = await currentBranch(chatId);
14733
14965
  const waiting = branch.at(-1);
14734
14966
  if (waiting?.status !== "awaiting_approval") throw new ApprovalNotPendingError(approvalId);
@@ -14740,7 +14972,7 @@ function createChatService(input) {
14740
14972
  const parts2 = recordDecision(current.parts, approvalId, decisionOf(answer === "always" && !offersAlways(asked) ? "allow" : answer));
14741
14973
  if (!parts2) throw new ApprovalNotPendingError(approvalId);
14742
14974
  return resumingPatch(userId, chatId, parts2);
14743
- });
14975
+ }, ensureResumeLease);
14744
14976
  } catch (error) {
14745
14977
  if (error instanceof MessageNotAwaitingError) throw new ApprovalNotPendingError(approvalId);
14746
14978
  throw error;
@@ -14756,17 +14988,17 @@ function createChatService(input) {
14756
14988
  });
14757
14989
  } catch (error) {
14758
14990
  resumeBases.delete(chatId);
14759
- await storage.finishMessage(waiting.id, { status: "interrupted", parts: denyPendingApprovals(parts, INTERRUPTED_REASON) });
14991
+ await turnStorage(chatId).finishMessage(waiting.id, { status: "interrupted", parts: denyPendingApprovals(parts, INTERRUPTED_REASON) });
14760
14992
  throw error;
14761
14993
  }
14762
14994
  return { resumed: true };
14763
- }, unlessResumed);
14995
+ }), unlessResumed);
14764
14996
  },
14765
14997
  async answerWidget({ chatId, ownerId, toolCallId, answer, page }) {
14766
14998
  return loggingWidgetRefusal(chatId, toolCallId, async () => {
14767
14999
  const chat = await ownChat(ownerId, chatId);
14768
15000
  await assertChatRules(ownerId, chat, { open: true });
14769
- return startingTurn({ userId: ownerId, chat, action: "widget" }, async () => {
15001
+ return startingTurn({ userId: ownerId, chat, action: "widget" }, () => withAwaitingLease(chatId, async (ensureResumeLease) => {
14770
15002
  const branch = await currentBranch(chatId);
14771
15003
  const waiting = branch.at(-1);
14772
15004
  const call = waiting?.status === "awaiting_approval" ? pendingWidgetCall(waiting.parts, toolCallId, widgets.waiting) : void 0;
@@ -14790,7 +15022,7 @@ function createChatService(input) {
14790
15022
  resuming = await writeToWaiting(waiting, (current) => {
14791
15023
  if (!pendingWidgetCall(current.parts, toolCallId, widgets.waiting)) throw new WidgetNotPendingError(toolCallId);
14792
15024
  return resumingPatch(ownerId, chatId, [...recordWidgetAnswer(current.parts, toolCallId, byApp.output), ...announced]);
14793
- });
15025
+ }, ensureResumeLease);
14794
15026
  } catch (error) {
14795
15027
  if (error instanceof MessageNotAwaitingError) throw new WidgetNotPendingError(toolCallId);
14796
15028
  throw error;
@@ -14814,11 +15046,11 @@ function createChatService(input) {
14814
15046
  await launchTurn(ownerId, chatId, [...branch.slice(0, -1), resuming], { parentId: waiting.parentId ?? "", resume: resuming, page, action: "widget", announced });
14815
15047
  } catch (error) {
14816
15048
  resumeBases.delete(chatId);
14817
- await storage.finishMessage(waiting.id, { status: "interrupted", parts: denyPendingApprovals(parts, INTERRUPTED_REASON) });
15049
+ await turnStorage(chatId).finishMessage(waiting.id, { status: "interrupted", parts: denyPendingApprovals(parts, INTERRUPTED_REASON) });
14818
15050
  throw error;
14819
15051
  }
14820
15052
  return { resumed: true };
14821
- }, unlessResumed);
15053
+ }), unlessResumed);
14822
15054
  });
14823
15055
  },
14824
15056
  async answerBrowserCall(userId, chatId, toolCallId, answer) {
@@ -14844,6 +15076,7 @@ function createChatService(input) {
14844
15076
  return true;
14845
15077
  },
14846
15078
  async recoverInterruptedAnswers(recoverOptions) {
15079
+ recoverBurstsOnSweep = true;
14847
15080
  await afterTurn?.recoverPending(liveAnswerIds);
14848
15081
  const soleServer = recoverOptions?.soleServer === true;
14849
15082
  const [count] = await Promise.all([recoverAnswersOnStart(soleServer), options2.background?.recover()]);
@@ -14907,20 +15140,15 @@ function createChatService(input) {
14907
15140
  }
14908
15141
  }
14909
15142
  };
14910
- async function recoverAnswersOnStart(soleServer) {
14911
- if (!storage.listSilentAnswerIds) {
14912
- logError(
14913
- "\u0425\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435 \u0431\u0435\u0437 listSilentAnswerIds \u0438 \u0437\u043D\u0430\u043A\u0430 \u0436\u0438\u0437\u043D\u0438 \u043E\u0442\u0432\u0435\u0442\u0430: \u043F\u0440\u0438 \u0441\u0442\u0430\u0440\u0442\u0435 \u043F\u0440\u0435\u0440\u0432\u0430\u043D\u044B \u0432\u0441\u0435 \u0438\u0434\u0443\u0449\u0438\u0435 \u043E\u0442\u0432\u0435\u0442\u044B, \u043F\u0440\u043E\u0432\u0435\u0440\u043A\u0438 \u0431\u0440\u043E\u0448\u0435\u043D\u043D\u044B\u0445 \u043E\u0442\u0432\u0435\u0442\u043E\u0432 \u043D\u0435\u0442. \u0421 \u043D\u0435\u0441\u043A\u043E\u043B\u044C\u043A\u0438\u043C\u0438 \u043A\u043E\u043F\u0438\u044F\u043C\u0438 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 \u043D\u0430 \u043E\u0434\u043D\u043E\u0439 \u0431\u0430\u0437\u0435 \u0442\u0430\u043A \u043D\u0435\u043B\u044C\u0437\u044F \u2014 \u043E\u0431\u043D\u043E\u0432\u0438\u0442\u0435 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435 (FR-060)."
14914
- );
14915
- return interruptAnswers(await storage.listStreamingMessageIds());
14916
- }
15143
+ function startStaleSweep() {
15144
+ if (!storage.listSilentAnswerIds) return;
14917
15145
  if (!staleSweep) {
14918
15146
  const sweep = { stopped: false };
14919
15147
  staleSweep = sweep;
14920
15148
  const next = () => {
14921
15149
  if (sweep.stopped) return;
14922
15150
  sweep.timer = setTimeout(() => {
14923
- sweep.running = Promise.all([recoverStaleAnswers(), afterTurn?.recoverPending(liveAnswerIds), sweepingBursts({ abandonedBefore: now().toISOString() })]).then(() => void 0).catch(
15151
+ sweep.running = Promise.all([recoverStaleAnswers(), afterTurn?.recoverPending(liveAnswerIds), ...recoverBurstsOnSweep ? [sweepingBursts({ abandonedBefore: now().toISOString() })] : []]).then(() => void 0).catch(
14924
15152
  (failure) => logError(`\u041F\u0440\u043E\u0432\u0435\u0440\u043A\u0430 \u0431\u0440\u043E\u0448\u0435\u043D\u043D\u044B\u0445 \u043E\u0442\u0432\u0435\u0442\u043E\u0432 \u043D\u0435 \u0443\u0434\u0430\u043B\u0430\u0441\u044C: ${failure instanceof Error ? failure.message : "\u043D\u0435\u0438\u0437\u0432\u0435\u0441\u0442\u043D\u0430\u044F \u043E\u0448\u0438\u0431\u043A\u0430"}`)
14925
15153
  ).finally(() => {
14926
15154
  sweep.running = void 0;
@@ -14931,6 +15159,15 @@ function createChatService(input) {
14931
15159
  };
14932
15160
  next();
14933
15161
  }
15162
+ }
15163
+ async function recoverAnswersOnStart(soleServer) {
15164
+ if (!storage.listSilentAnswerIds) {
15165
+ logError(
15166
+ "\u0425\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435 \u0431\u0435\u0437 listSilentAnswerIds \u0438 \u0437\u043D\u0430\u043A\u0430 \u0436\u0438\u0437\u043D\u0438 \u043E\u0442\u0432\u0435\u0442\u0430: \u043F\u0440\u0438 \u0441\u0442\u0430\u0440\u0442\u0435 \u043F\u0440\u0435\u0440\u0432\u0430\u043D\u044B \u0432\u0441\u0435 \u0438\u0434\u0443\u0449\u0438\u0435 \u043E\u0442\u0432\u0435\u0442\u044B, \u043F\u0440\u043E\u0432\u0435\u0440\u043A\u0438 \u0431\u0440\u043E\u0448\u0435\u043D\u043D\u044B\u0445 \u043E\u0442\u0432\u0435\u0442\u043E\u0432 \u043D\u0435\u0442. \u0421 \u043D\u0435\u0441\u043A\u043E\u043B\u044C\u043A\u0438\u043C\u0438 \u043A\u043E\u043F\u0438\u044F\u043C\u0438 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 \u043D\u0430 \u043E\u0434\u043D\u043E\u0439 \u0431\u0430\u0437\u0435 \u0442\u0430\u043A \u043D\u0435\u043B\u044C\u0437\u044F \u2014 \u043E\u0431\u043D\u043E\u0432\u0438\u0442\u0435 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435 (FR-060)."
15167
+ );
15168
+ return interruptAnswers(await storage.listStreamingMessageIds());
15169
+ }
15170
+ startStaleSweep();
14934
15171
  if (!soleServer) return recoverStaleAnswers();
14935
15172
  await turnLeases.clearForeign();
14936
15173
  return interruptAnswers(await storage.listStreamingMessageIds());
@@ -15086,6 +15323,8 @@ function createChatService(input) {
15086
15323
  throw error;
15087
15324
  }
15088
15325
  });
15326
+ if (storage.listSilentAnswerIds) startStaleSweep();
15327
+ else logError("\u0410\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u043E\u0435 \u0432\u043E\u0441\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0435 \u043E\u0442\u0432\u0435\u0442\u043E\u0432 \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u043D\u043E: \u0443 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430 \u043D\u0435\u0442 listSilentAnswerIds. \u041E\u0431\u043D\u043E\u0432\u0438\u0442\u0435 \u0430\u0434\u0430\u043F\u0442\u0435\u0440; \u0434\u043B\u044F \u0435\u0434\u0438\u043D\u0441\u0442\u0432\u0435\u043D\u043D\u043E\u0439 \u043A\u043E\u043F\u0438\u0438 \u0441\u0435\u0440\u0432\u0435\u0440\u0430 \u044F\u0432\u043D\u043E \u0432\u044B\u0437\u043E\u0432\u0438\u0442\u0435 recoverInterruptedAnswers \u043F\u0440\u0438 \u0437\u0430\u043F\u0443\u0441\u043A\u0435.");
15089
15328
  return service;
15090
15329
  function isDetachedAnswer(last, runningId) {
15091
15330
  return runningId === null && last?.status === "streaming" && !liveAnswerIds.has(last.id);
@@ -15264,6 +15503,7 @@ export {
15264
15503
  DuplicateMessageError,
15265
15504
  ChatAlreadyExistsError,
15266
15505
  DuplicateChatSubjectError,
15506
+ ChatTurnLeaseLostError,
15267
15507
  MessageAlreadyFinishedError,
15268
15508
  sameMessageParts,
15269
15509
  MessageNotAwaitingError,
@@ -15366,4 +15606,4 @@ export {
15366
15606
  InvalidWidgetAnswerError,
15367
15607
  createChatService
15368
15608
  };
15369
- //# sourceMappingURL=chunk-YGHGURNF.js.map
15609
+ //# sourceMappingURL=chunk-GXJNYXC5.js.map