@ykurilov/agent-chat-core 0.107.1 → 0.108.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,24 @@
1
1
  # @ykurilov/agent-chat-core
2
2
 
3
+ ## 0.108.0
4
+
5
+ ### Minor Changes
6
+
7
+ - b951be1: «Стоп», нажатый сразу после отправки, останавливает именно этот ход — как бы ни легли запросы. Раньше «Стоп», дошедший до сервера раньше начала хода (маршрут, вход, чтение базы) или попавший на другую копию сервера, получал «нечего останавливать», и ответ дописывался до конца.
8
+
9
+ - Каждый запрос, начинающий ход (отправка, правка, переделка, повтор, решение по подтверждению, ответ на виджет, поправка, начавшая ход), несёт новый `turnRequestId` (`TurnRequestContext.turnRequestId`). Экран SDK шлёт его сам и называет в теле `POST /stop` (`{ turnRequestId }`).
10
+ - Сервер: ход этого запроса идёт на копии — останавливается сразу; ещё не начался или идёт на другой копии — «Стоп» запоминается (`202`), ход останавливается сразу после старта или на сверке с базой раз в 2 с (`STOP_REQUESTS_CHECK_EVERY_MS`). Ход другого запроса такой «Стоп» не трогает: запоздавший «Стоп» не остановит следующий вопрос. `service.stop(userId, chatId, { turnRequestId })`.
11
+ - Ответ на поправки — новый ход с id последней поправки: «Стоп» прежнего ответа его не трогает (на любой копии), «Стоп» с id поправки останавливает.
12
+ - `POST /stop` с `turnRequestId` всегда отвечает `202` (остановлено или запомнено), даже если хода с этим id так и не будет. Без id — как раньше: `202` или `204`.
13
+ - Хранилища: необязательные `saveStopRequest(request, { keepPerOwner })` / `hasStopRequest`. Запись несёт `ownerId`, живёт час; у человека не больше `keepPerOwner` (служба передаёт 100) живых записей — сверх уходят его самые ранние, чужие не трогаются. Тот же предел — в памяти копии. SQLite и PostgreSQL — таблица `stop_requests`, миграция применяется сама. Свои хранилища без этих методов работают как раньше: ранний «Стоп» держится в памяти копии.
14
+ - «Стоп» без `turnRequestId` (свои клиенты, ход, к которому экран только подключился) работает как раньше.
15
+
16
+ ## 0.107.2
17
+
18
+ ### Patch Changes
19
+
20
+ - 4430082: Хранилища SQLite и PostgreSQL собираются бандлером Next.js (Turbopack и webpack, `next dev`, `next build`, `output: "standalone"`) без `serverExternalPackages` и без настройки трассировки. Раньше сборка падала с «Module not found: Can't resolve '../drizzle'» (путь к папке миграций бандлер принимал за импорт), а standalone-сервер — с «Can't find meta/_journal.json» (папку миграций Next не копировал). Теперь миграции вшиты в код пакетов (`applyEmbeddedMigrations` и тип `EmbeddedMigration` в ядре), журнал и хеши миграций прежние: существующие базы ничего не применяют заново.
21
+
3
22
  ## 0.107.1
4
23
 
5
24
  No changes in this release.
@@ -2902,6 +2902,9 @@ async function hasChatMessages(storage, chatId) {
2902
2902
  }
2903
2903
 
2904
2904
  // src/page-context/page-context.ts
2905
+ function isTurnRequestId(value) {
2906
+ return typeof value === "string" && /^[A-Za-z0-9_.:-]{1,100}$/.test(value);
2907
+ }
2905
2908
  function continuationRequestContext(start, corrections) {
2906
2909
  const last = corrections.at(-1) ?? start;
2907
2910
  if (last === void 0) return void 0;
@@ -2909,7 +2912,10 @@ function continuationRequestContext(start, corrections) {
2909
2912
  return {
2910
2913
  ...place !== void 0 && { place },
2911
2914
  ...last.tabId !== void 0 && { tabId: last.tabId },
2912
- ...last.timeZone !== void 0 && { timeZone: last.timeZone }
2915
+ ...last.timeZone !== void 0 && { timeZone: last.timeZone },
2916
+ // Продолжение — новый ответ, на последнюю поправку: id её запроса. «Стоп» прежнего ответа его не трогает (на любой
2917
+ // копии сервера), «Стоп» с id поправки — останавливает.
2918
+ ...corrections.at(-1)?.turnRequestId !== void 0 && { turnRequestId: corrections.at(-1).turnRequestId }
2913
2919
  };
2914
2920
  }
2915
2921
  var APP_CHANGE_PART_TYPE = "data-app-change";
@@ -10573,6 +10579,102 @@ function createRunningAnswerRegistry() {
10573
10579
  };
10574
10580
  }
10575
10581
 
10582
+ // src/running-answers/stop-requests.ts
10583
+ var STOP_REQUESTS_CHECK_EVERY_MS = 2e3;
10584
+ var STOP_REQUEST_KEEP_MS = 60 * 60 * 1e3;
10585
+ var STOP_REQUESTS_PER_OWNER = 100;
10586
+ function createStopRequests(input) {
10587
+ const { storage, now, logError } = input;
10588
+ const remembered = /* @__PURE__ */ new Map();
10589
+ const byOwner = /* @__PURE__ */ new Map();
10590
+ const watched = /* @__PURE__ */ new Map();
10591
+ const keyOf = (chatId, turnRequestId) => JSON.stringify([chatId, turnRequestId]);
10592
+ function forget(key) {
10593
+ const entry = remembered.get(key);
10594
+ if (!entry) return;
10595
+ remembered.delete(key);
10596
+ const keys = byOwner.get(entry.ownerId);
10597
+ keys.splice(keys.indexOf(key), 1);
10598
+ if (keys.length === 0) byOwner.delete(entry.ownerId);
10599
+ }
10600
+ function forgetExpired(at) {
10601
+ for (const [key, { until }] of remembered) {
10602
+ if (until > at) return;
10603
+ forget(key);
10604
+ }
10605
+ }
10606
+ return {
10607
+ stopRunning(chatId, turnRequestId) {
10608
+ const running = watched.get(keyOf(chatId, turnRequestId));
10609
+ running?.();
10610
+ return running !== void 0;
10611
+ },
10612
+ async remember(ownerId, chatId, turnRequestId) {
10613
+ const stoppedAt = now();
10614
+ const expiresAt = stoppedAt.getTime() + STOP_REQUEST_KEEP_MS;
10615
+ const key = keyOf(chatId, turnRequestId);
10616
+ forgetExpired(stoppedAt.getTime());
10617
+ forget(key);
10618
+ const keys = byOwner.get(ownerId) ?? [];
10619
+ while (keys.length >= STOP_REQUESTS_PER_OWNER) forget(keys[0]);
10620
+ remembered.set(key, { ownerId, until: expiresAt });
10621
+ keys.push(key);
10622
+ byOwner.set(ownerId, keys);
10623
+ if (!storage.saveStopRequest) return;
10624
+ await storage.saveStopRequest(
10625
+ { ownerId, chatId, turnRequestId, stoppedAt: stoppedAt.toISOString(), expiresAt: new Date(expiresAt).toISOString() },
10626
+ { keepPerOwner: STOP_REQUESTS_PER_OWNER }
10627
+ ).catch((error) => logError(`\xAB\u0421\u0442\u043E\u043F\xBB \u0445\u043E\u0434\u0430 \u0447\u0430\u0442\u0430 ${chatId} \u043D\u0435 \u0437\u0430\u043F\u0438\u0441\u0430\u043D \u0432 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0435: ${error instanceof Error ? error.message : String(error)}`, error));
10628
+ },
10629
+ watch(chatId, turnRequestId, abort) {
10630
+ const key = keyOf(chatId, turnRequestId);
10631
+ let ended = false;
10632
+ let timer;
10633
+ let failed = false;
10634
+ const end = () => {
10635
+ if (ended) return;
10636
+ ended = true;
10637
+ clearInterval(timer);
10638
+ if (watched.get(key) === fire) watched.delete(key);
10639
+ };
10640
+ const fire = () => {
10641
+ if (ended) return;
10642
+ end();
10643
+ forget(key);
10644
+ abort();
10645
+ };
10646
+ if (remembered.has(key)) {
10647
+ fire();
10648
+ return end;
10649
+ }
10650
+ watched.set(key, fire);
10651
+ const hasStopRequest = storage.hasStopRequest?.bind(storage);
10652
+ if (!hasStopRequest) return end;
10653
+ let checking = false;
10654
+ const check = () => {
10655
+ if (ended || checking) return;
10656
+ checking = true;
10657
+ void hasStopRequest(chatId, turnRequestId).then(
10658
+ (stopped) => {
10659
+ if (stopped) fire();
10660
+ },
10661
+ (error) => {
10662
+ if (failed) return;
10663
+ failed = true;
10664
+ logError(`\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043F\u0440\u043E\u0432\u0435\u0440\u0438\u0442\u044C \xAB\u0421\u0442\u043E\u043F\xBB \u0445\u043E\u0434\u0430 \u0447\u0430\u0442\u0430 ${chatId}: ${error instanceof Error ? error.message : String(error)}`, error);
10665
+ }
10666
+ ).finally(() => {
10667
+ checking = false;
10668
+ });
10669
+ };
10670
+ check();
10671
+ timer = setInterval(check, STOP_REQUESTS_CHECK_EVERY_MS);
10672
+ timer.unref?.();
10673
+ return end;
10674
+ }
10675
+ };
10676
+ }
10677
+
10576
10678
  // src/transient-chat.ts
10577
10679
  var checkpoints = /* @__PURE__ */ new WeakMap();
10578
10680
  function registerTransientCheckpoint(service, checkpoint) {
@@ -13448,6 +13550,7 @@ function createChatService(input) {
13448
13550
  const startingSlots = /* @__PURE__ */ new Map();
13449
13551
  const admittingTurns = /* @__PURE__ */ new Map();
13450
13552
  const stopsWhileStarting = /* @__PURE__ */ new Set();
13553
+ const stopRequests = createStopRequests({ storage, now, logError });
13451
13554
  const deleting = /* @__PURE__ */ new Set();
13452
13555
  const pendingClosures = /* @__PURE__ */ new Map();
13453
13556
  const writingClosures = /* @__PURE__ */ new Set();
@@ -14330,6 +14433,8 @@ function createChatService(input) {
14330
14433
  const { finished } = started;
14331
14434
  steeringTurn = steering.begin(chatId, answerId);
14332
14435
  if (stopsWhileStarting.delete(chatId)) registry.abort(chatId);
14436
+ const turnRequestId = launch.page?.turnRequestId;
14437
+ const endStopWatch = turnRequestId === void 0 ? void 0 : stopRequests.watch(chatId, turnRequestId, () => registry.runningMessageId(chatId) === answerId && registry.abort(chatId));
14333
14438
  const turnEvent = { ownerId: chat.ownerId, chatId, messageId: answerId, trigger, channel };
14334
14439
  chatEvents.emit({
14335
14440
  type: "turn-started",
@@ -14345,6 +14450,7 @@ function createChatService(input) {
14345
14450
  const slot = startingSlots.get(chatId);
14346
14451
  startingSlots.delete(chatId);
14347
14452
  void finished.then(() => {
14453
+ endStopWatch?.();
14348
14454
  steeringTurn?.close();
14349
14455
  liveTurn.end();
14350
14456
  void toolQueue.whenIdle().then(() => {
@@ -15399,10 +15505,16 @@ function createChatService(input) {
15399
15505
  const stream = registry.subscribe(chatId);
15400
15506
  return stream && visibility.visibleChunks(stream);
15401
15507
  },
15402
- async stop(userId, chatId) {
15508
+ async stop(userId, chatId, stopOptions) {
15403
15509
  await ownChat(userId, chatId);
15404
15510
  const check = widgetChecks.get(chatId);
15405
15511
  check?.abort();
15512
+ const turnRequestId = stopOptions?.turnRequestId;
15513
+ if (turnRequestId !== void 0) {
15514
+ if (stopRequests.stopRunning(chatId, turnRequestId)) return true;
15515
+ await stopRequests.remember(userId, chatId, turnRequestId);
15516
+ return true;
15517
+ }
15406
15518
  if (registry.abort(chatId) || check !== void 0) return true;
15407
15519
  if (handOffs.has(chatId)) return true;
15408
15520
  if (await stoppingPendingBurst(userId, chatId)) return true;
@@ -15857,6 +15969,7 @@ export {
15857
15969
  UnsupportedFormatVersionError,
15858
15970
  assertKnownFormatVersion,
15859
15971
  hasChatMessages,
15972
+ isTurnRequestId,
15860
15973
  APP_CHANGE_PART_TYPE,
15861
15974
  BROWSER_CALL_PART_TYPE,
15862
15975
  BrowserCallNotPendingError,
@@ -15919,6 +16032,7 @@ export {
15919
16032
  TooManyTurnsError,
15920
16033
  ChatBusyError,
15921
16034
  createRunningAnswerRegistry,
16035
+ STOP_REQUESTS_CHECK_EVERY_MS,
15922
16036
  checkpointTransientChat,
15923
16037
  getTransientChatHistory,
15924
16038
  splitVoiceTags,
@@ -15958,4 +16072,4 @@ export {
15958
16072
  InvalidWidgetAnswerError,
15959
16073
  createChatService
15960
16074
  };
15961
- //# sourceMappingURL=chunk-D3PW7DT4.js.map
16075
+ //# sourceMappingURL=chunk-FUIPWUAH.js.map