@ykurilov/agent-chat-core 0.96.0 → 0.97.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,17 @@
1
1
  # @ykurilov/agent-chat-core
2
2
 
3
+ ## 0.97.0
4
+
5
+ ### Minor Changes
6
+
7
+ - ed2b0d0: Штатная правка текста готового ответа в обычном чате Next/Hono и «Одуванчика», включаемая приложением. Дополнительные поля передаются как JSON data; onAnswerEdited получает прежний/новый текст, оба id, владельца и чат. Происхождение правки сохраняется без передачи аннотации модели или браузеру.
8
+
9
+ Как обновить приложение: включить серверный answerEditing: true и право chatCapabilities.answerEditing, передать AgentChat.answerEditor; для своих полей - renderFields, для журнала - onAnswerEdited. Старый пользовательский answerEditing совместим. Подробнее docs/answer-editing.md; хук повторяется в процессе, долговечная запись доступна для сверки после аварии.
10
+
11
+ ## 0.96.1
12
+
13
+ No changes in this release.
14
+
3
15
  ## 0.96.0
4
16
 
5
17
  ### Minor Changes
package/README.md CHANGED
@@ -170,3 +170,8 @@ docs/getting-started.md, «Значки шагов и заголовки раз
170
170
  ошибка попадает в `logError(message, error)` и не отменяет запись. Встроенный плагин предоставляет
171
171
  приложению `createAttachments.onFilesAttached` с проверенными записями `StoredAttachment[]`.
172
172
  Это фоновое уведомление без долговечной очереди. [Контракт](../../docs/composer-attachments.md).
173
+
174
+
175
+ ### Правка ответа в обычном чате (с 0.97.0)
176
+
177
+ Серверный `answerEditing: true` и право `chatCapabilities.answerEditing` включают адрес правки ответа для Next/Hono. В `AgentChat` со скином «Одуванчик» передайте `answerEditor={true}` либо объект с `renderFields({ data, setData, disabled, message })` для своих полей. `onAnswerEdited` получает id исходного и нового ответа, оба текста, владельца, чат и JSON `data` приложения. Прежний пользовательский `answerEditing={{ edits, renderEditor }}` совместим и имеет приоритет. [Контракт, пределы доставки хука и обновление приложения](../../docs/answer-editing.md).
@@ -8877,6 +8877,44 @@ function sameOutput(part, output) {
8877
8877
  return call.state === "output-available" && JSON.stringify(call.output) === JSON.stringify(output);
8878
8878
  }
8879
8879
 
8880
+ // src/conversation/answer-edit-record.ts
8881
+ var PART = "data-answer-edit";
8882
+ function answerEditOf(parts) {
8883
+ const part = parts.find((p) => p.type === PART);
8884
+ if (!part || !("data" in part) || !part.data || typeof part.data !== "object") return void 0;
8885
+ const value = part.data;
8886
+ return typeof value.sourceMessageId === "string" && typeof value.ownerId === "string" && typeof value.editedAt === "string" ? value : void 0;
8887
+ }
8888
+ function withoutAnswerEdit(parts) {
8889
+ return parts.filter((p) => p.type !== PART);
8890
+ }
8891
+ function withAnswerEdit(parts, record) {
8892
+ return [...withoutAnswerEdit(parts), { type: PART, data: record }];
8893
+ }
8894
+ function checkedAnswerEditData(data) {
8895
+ if (data === void 0) return void 0;
8896
+ const ancestors = /* @__PURE__ */ new Set();
8897
+ function json(value, depth) {
8898
+ if (depth > 32) return false;
8899
+ if (value === null || typeof value === "string" || typeof value === "boolean") return true;
8900
+ if (typeof value === "number") return Number.isFinite(value);
8901
+ if (typeof value !== "object" || ancestors.has(value)) return false;
8902
+ if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) return false;
8903
+ ancestors.add(value);
8904
+ const ok = Object.values(value).every((v) => json(v, depth + 1));
8905
+ ancestors.delete(value);
8906
+ return ok;
8907
+ }
8908
+ try {
8909
+ if (data === null || typeof data !== "object" || Array.isArray(data) || !json(data, 0)) throw new Error();
8910
+ const encoded = JSON.stringify(data);
8911
+ if (new TextEncoder().encode(encoded).length > 16 * 1024) throw new Error();
8912
+ return JSON.parse(encoded);
8913
+ } catch {
8914
+ throw new AnswerEditError("invalid_data");
8915
+ }
8916
+ }
8917
+
8880
8918
  // src/conversation/deliverable-parts.ts
8881
8919
  function deliverableParts(parts) {
8882
8920
  return parts.filter((part) => part.type !== "reasoning" && part.type !== "step-start" && !part.type.startsWith("data-"));
@@ -11690,14 +11728,16 @@ function withRetries(model, context) {
11690
11728
  function toAgentChatMessage(message) {
11691
11729
  if (message.role === "user") return { id: message.id, role: "user", parts: message.parts };
11692
11730
  const { pendingSteps: _steps, ...usage } = message.usage ?? {};
11731
+ const answerEdit = answerEditOf(message.parts);
11693
11732
  const reasoningLevel = answerReasoningOf(message.parts);
11694
11733
  const thoughtTitles = thoughtTitlesOfParts(message.parts);
11695
11734
  return {
11696
11735
  id: message.id,
11697
11736
  role: "assistant",
11698
- parts: withoutAnswerReasoning(message.parts),
11737
+ parts: withoutAnswerEdit(withoutAnswerReasoning(message.parts)),
11699
11738
  metadata: {
11700
11739
  status: message.status,
11740
+ ...answerEdit && { answerEdit: { sourceMessageId: answerEdit.sourceMessageId, editedAt: answerEdit.editedAt } },
11701
11741
  ...reasoningLevel !== void 0 && { reasoningLevel },
11702
11742
  reasoningDurationsMs: message.reasoningDurationsMs,
11703
11743
  ...Object.keys(thoughtTitles).length > 0 && { thoughtTitles },
@@ -12193,6 +12233,33 @@ function branchStateOf(messages, selections) {
12193
12233
  };
12194
12234
  }
12195
12235
 
12236
+ // src/conversation/answer-edited.ts
12237
+ function createAnswerEdited(handler, logError) {
12238
+ const running = /* @__PURE__ */ new Set();
12239
+ const queues = /* @__PURE__ */ new Map();
12240
+ return {
12241
+ notify(input) {
12242
+ if (!handler) return;
12243
+ const captured = structuredClone(input);
12244
+ const work = (queues.get(input.chatId) ?? Promise.resolve()).then(async () => {
12245
+ const failure = await callWithRetries2(handler, captured, 3e4, 3);
12246
+ if (failure) logError(`onAnswerEdited \u043D\u0435 \u043E\u0442\u0440\u0430\u0431\u043E\u0442\u0430\u043B (\u0447\u0430\u0442 ${input.chatId}, \u043E\u0442\u0432\u0435\u0442 ${input.messageId}): ${failure.reason}`, failure.error);
12247
+ }).catch((error) => {
12248
+ logError(`onAnswerEdited: ${input.messageId}`, error);
12249
+ });
12250
+ queues.set(input.chatId, work);
12251
+ running.add(work);
12252
+ void work.finally(() => {
12253
+ running.delete(work);
12254
+ if (queues.get(input.chatId) === work) queues.delete(input.chatId);
12255
+ });
12256
+ },
12257
+ async drain() {
12258
+ while (running.size) await Promise.allSettled([...running]);
12259
+ }
12260
+ };
12261
+ }
12262
+
12196
12263
  // src/usage/cache-miss-watch.ts
12197
12264
  var NOISE_FLOOR_TOKENS = 1024;
12198
12265
  var MAX_REMEMBERED_CHATS = 500;
@@ -13160,6 +13227,7 @@ function createChatService(input) {
13160
13227
  logError,
13161
13228
  ...options2.staffOfChat && { staffOf: options2.staffOfChat }
13162
13229
  });
13230
+ const answerEdited = createAnswerEdited(options2.onAnswerEdited, logError);
13163
13231
  const stateChanged = createStateChanged({
13164
13232
  ...options2.onStateChanged && { handler: options2.onStateChanged },
13165
13233
  ...options2.onStateChangedTimeoutMs !== void 0 && { timeoutMs: options2.onStateChangedTimeoutMs },
@@ -14973,6 +15041,8 @@ function createChatService(input) {
14973
15041
  await assertChatRules(userId, chat, { capabilities: ["answerEditing"] });
14974
15042
  if (starting.has(chatId) || registry.isRunning(chatId)) throw new AnswerEditError("answer_busy");
14975
15043
  let before = {};
15044
+ const data = checkedAnswerEditData(edit.data);
15045
+ let editEvent;
14976
15046
  const replaced = await holdingChat(chatId, async () => {
14977
15047
  await carryLegacyClosure(chatId);
14978
15048
  const { messages, selections, branch } = await loadTree(chatId);
@@ -14990,15 +15060,18 @@ function createChatService(input) {
14990
15060
  chatId,
14991
15061
  parentId: answer.parentId,
14992
15062
  role: "assistant",
14993
- parts: edited.parts,
15063
+ parts: withAnswerEdit(edited.parts, { sourceMessageId: answer.id, ownerId: chat.ownerId, editedAt: createdAt, ...data !== void 0 && { data } }),
14994
15064
  modelId: answer.modelId,
14995
15065
  providerId: answer.providerId,
14996
15066
  createdAt
14997
15067
  });
14998
15068
  await storage.insertMessage(replacement);
14999
15069
  await storage.insertBranchSelection({ id: crypto.randomUUID(), chatId, messageId: replacement.id, selectedAt: createdAt });
15070
+ editEvent = { ownerId: chat.ownerId, chatId, sourceMessageId: answer.id, messageId: replacement.id, editedAt: createdAt, sourceText: answerText(answer.parts), text: edit.text, ...data !== void 0 && { data } };
15000
15071
  return replacement;
15001
15072
  });
15073
+ answerEdited.notify(editEvent);
15074
+ chatEvents.emit({ type: "answer-edited", ownerId: chat.ownerId, chatId, sourceMessageId: messageId, messageId: replaced.id });
15002
15075
  await branchChanged(chat.ownerId, chatId, "editAnswer", before);
15003
15076
  return replaced;
15004
15077
  },
@@ -15201,6 +15274,7 @@ function createChatService(input) {
15201
15274
  await afterTurn?.drain();
15202
15275
  while (afterTurnWork.size > 0) await Promise.allSettled([...afterTurnWork]);
15203
15276
  await stateChanged.drain();
15277
+ await answerEdited.drain();
15204
15278
  await Promise.all([
15205
15279
  // Ходы уже записаны; запись, если где-то ещё идёт, дописывает остаток.
15206
15280
  ...[...flushers].map((flushAnswer) => flushAnswer()),
@@ -15611,6 +15685,7 @@ export {
15611
15685
  AnswerEditError,
15612
15686
  EDITED_TOOL_OUTPUT_MAX_BYTES,
15613
15687
  answerText,
15688
+ answerEditOf,
15614
15689
  deliverableParts,
15615
15690
  activeCompaction,
15616
15691
  extendCatalog,
@@ -15681,4 +15756,4 @@ export {
15681
15756
  InvalidWidgetAnswerError,
15682
15757
  createChatService
15683
15758
  };
15684
- //# sourceMappingURL=chunk-THL3LUXH.js.map
15759
+ //# sourceMappingURL=chunk-OKZDW7G3.js.map