@ykurilov/agent-chat-core 0.55.0 → 0.56.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.
@@ -0,0 +1,60 @@
1
+ import type { AgentAudience, AgentChannel, ChatSubject } from "../conversation/types.js";
2
+ import type { StaffActor } from "../turn-hooks/turn-hooks.js";
3
+ /**
4
+ * Кто смотрит на ход: права и признаки человека, которые приложение берёт из своей базы (`agent.viewer`). Ядро его не
5
+ * читает, только передаёт. `isAdmin` — общий признак для пакетов (серверы MCP, навыки): «только админы» видны, когда он
6
+ * `true`. Остальные поля — свои у приложения.
7
+ */
8
+ export interface AgentViewer {
9
+ isAdmin?: boolean;
10
+ readonly [key: string]: unknown;
11
+ }
12
+ /** Что видит `agent.viewer` в начале хода. */
13
+ export interface AgentViewerInput {
14
+ /** Кто делает ход: сотрудник в копии чата человека, иначе владелец чата. */
15
+ userId: string;
16
+ chatId: string;
17
+ /** Владелец чата. */
18
+ ownerId: string;
19
+ /** Ответ агента, который строит этот ход; у фонового помощника — пустая строка. */
20
+ messageId: string;
21
+ chat: {
22
+ data?: Record<string, unknown>;
23
+ };
24
+ subject?: ChatSubject;
25
+ channel: AgentChannel;
26
+ audience: AgentAudience;
27
+ staff?: StaffActor;
28
+ /** «Стоп» и срок хода. */
29
+ abortSignal: AbortSignal;
30
+ }
31
+ /**
32
+ * Права человека на ход: зовётся один раз в начале хода (повторная попытка и запасной провайдер не зовут снова), до
33
+ * блоков контекста и сборки инструментов. Итог идёт полем `viewer` в `contextBlocks` и в `AgentToolsModel`; в запрос к
34
+ * модели сам не попадает. Бросила или вернула не объект — ход кончается ошибкой.
35
+ */
36
+ export type AgentViewerSource = (input: AgentViewerInput) => AgentViewer | Promise<AgentViewer>;
37
+ /** `agent.viewer` бросила или вернула не объект: ход кончается ошибкой, в журнал сервера — причина. */
38
+ export declare class AgentViewerError extends Error {
39
+ constructor(message: string, options?: {
40
+ cause?: unknown;
41
+ });
42
+ }
43
+ /** Зовёт `agent.viewer`: итог заморожен (правка не доходит до хода), «Стоп» обрывает ожидание. */
44
+ export declare function resolveAgentViewer(source: AgentViewerSource, input: AgentViewerInput): Promise<AgentViewer>;
45
+ /** Вход `agent.viewer` из полей хода. */
46
+ export declare function viewerInput(turn: {
47
+ chatId: string;
48
+ ownerId?: string;
49
+ messageId: string;
50
+ chatData?: Record<string, unknown>;
51
+ subject?: ChatSubject;
52
+ channel?: AgentChannel;
53
+ audience: AgentAudience;
54
+ staff?: StaffActor;
55
+ abortSignal: AbortSignal;
56
+ }): AgentViewerInput;
57
+ /** Срок `agent.viewer` вне хода человека (сжатие истории, фоновый помощник): «Стопа» там нет, зависание не держит работу. */
58
+ export declare const VIEWER_OUTSIDE_TURN_TIMEOUT_MS = 10000;
59
+ /** `agent.viewer` для сжатия и фонового помощника: те же правила, что в ходе, плюс срок ответа. */
60
+ export declare function resolveViewerOutsideTurn(source: AgentViewerSource, turn: Omit<Parameters<typeof viewerInput>[0], "abortSignal">, signal?: AbortSignal): Promise<AgentViewer>;
@@ -24,6 +24,7 @@ import type { PreparedTurn } from "../turn-hooks/turn-preparation.js";
24
24
  import type { ChatClosure } from "../access/chat-closure.js";
25
25
  import type { HiddenStateKey } from "../app-state/state-messages.js";
26
26
  import type { ContextBlocksSource } from "../frozen-context/context-blocks.js";
27
+ import type { AgentViewer, AgentViewerSource } from "./agent-viewer.js";
27
28
  import type { AppStateAccess, AppStateValues } from "../app-state/app-state.js";
28
29
  /** Выбранная модель: по ней приложение решает, какие инструменты ей дать. */
29
30
  export interface AgentToolsModel {
@@ -89,6 +90,11 @@ export interface AgentToolsModel {
89
90
  * Нет — вызов вне хода (сжатие, фоновая задача): вне хода приложение пишет в данные чата.
90
91
  */
91
92
  state?: AppStateAccess;
93
+ /**
94
+ * Права человека на ход (`agent.viewer`): один объект на все попытки и шаги хода, тот же, что у `contextBlocks`.
95
+ * Нет `agent.viewer` (или модель собрана вне хода) — поля нет.
96
+ */
97
+ viewer?: AgentViewer;
92
98
  }
93
99
  /** Инструменты агента: один набор для всех моделей или набор, зависящий от выбранной модели. */
94
100
  export type AgentToolsSource = ToolSet | ((model: AgentToolsModel) => ToolSet);
@@ -174,6 +180,8 @@ export interface AgentTurnInput {
174
180
  stepContext?: StepContext;
175
181
  /** Срок ответа `stepContext`, мс, уже проверенный; `Infinity` — без срока. Нет — 5 с. */
176
182
  stepContextTimeoutMs?: number;
183
+ /** Права человека: один вызов в начале хода, до блоков и инструментов (`agent.viewer`). */
184
+ viewer?: AgentViewerSource;
177
185
  /** Блоки приложения для вопроса хода: один опрос в начале хода, дальше застывают в ответе (`agent.contextBlocks`). */
178
186
  contextBlocks?: ContextBlocksSource;
179
187
  /** Срок ответа `contextBlocks`, мс, уже проверенный; `Infinity` — без срока. Нет — 5 с. */
@@ -45,6 +45,7 @@ import type { BeforeCreateChatHandler } from "./access/chat-creation.js";
45
45
  import type { AskModel, PrepareTurn, RecordUsage } from "./turn-hooks/prepare-turn.js";
46
46
  import type { AfterTurnHandler, AppEvent, BeforeTurnHandler, StaffActor, TurnAction, TurnNotStartedHandler } from "./turn-hooks/turn-hooks.js";
47
47
  import type { AgentWidgetSettings } from "./widgets/widget-types.js";
48
+ import type { AgentViewerSource } from "./agent-run/agent-viewer.js";
48
49
  import type { TurnFinishedHandler } from "./agent-run/turn-finished.js";
49
50
  export { DEFAULT_TEXT_MODE_NOTE, DEFAULT_VOICE_MODE_HINT };
50
51
  /**
@@ -203,6 +204,16 @@ export interface AgentSettings {
203
204
  * `private: true` — блок не показывается в групповом ходе. Не задано — запрос побайтно прежний.
204
205
  */
205
206
  contextBlocks?: ContextBlocksSource;
207
+ /**
208
+ * Права человека из базы приложения (админ ли, тариф): зовётся один раз в начале хода, до `contextBlocks` и сборки
209
+ * инструментов; повторная попытка и запасной провайдер не зовут снова. Итог — полем `viewer` в `contextBlocks` и в
210
+ * модели инструментов (`AgentToolsModel.viewer`), в запрос к модели не идёт. Ещё зовётся перед сжатием истории и
211
+ * запуском фонового помощника: их инструменты те же (канал и группа — по последнему сообщению человека; срок ответа
212
+ * 10 с). Бросила или вернула не объект — ход кончается ошибкой
213
+ * (`other`), в журнал сервера — `[agent.viewer] …`. `isAdmin` читают пакеты (серверы MCP, навыки). Не задано —
214
+ * поля `viewer` нет.
215
+ */
216
+ viewer?: AgentViewerSource;
206
217
  /**
207
218
  * Срок ответа `contextBlocks`, мс. Не ответила или бросила — блоки приложения берутся из прошлого ответа чата, в
208
219
  * журнал сервера — строка `[блоки контекста] …`; функция получает отмену через `abortSignal`. «Стоп» отменяет её
@@ -1,5 +1,6 @@
1
1
  import type { MessageAttachments } from "../attachments/message-attachments.js";
2
2
  import type { AgentToolsSource } from "../agent-run/run-agent-turn.js";
3
+ import type { AgentViewerSource } from "../agent-run/agent-viewer.js";
3
4
  import type { TurnObserver } from "../agent-run/turn-observer.js";
4
5
  import type { AgentChatMessage, Chat, StoredMessage } from "../conversation/types.js";
5
6
  import type { ModelCatalog } from "../models/model-catalog.js";
@@ -92,9 +93,11 @@ export interface CompactionServiceOptions {
92
93
  storage: ChatStorage;
93
94
  catalog: ModelCatalog;
94
95
  env: Record<string, string | undefined>;
96
+ /** `viewer` — права человека: инструменты сжатия те же, что у хода (кэш). */
95
97
  agent: {
96
98
  instructions: string;
97
99
  tools?: AgentToolsSource;
100
+ viewer?: AgentViewerSource;
98
101
  };
99
102
  attachments?: MessageAttachments;
100
103
  /** `null` — автосжатие выключено; записи, уже сделанные, всё равно применяются к истории. */
@@ -188,8 +188,10 @@ export interface StoredBranchSelection {
188
188
  * `first_message` — ход, в котором агент пишет первым (касание, утро сценария): `deliverNotices({ usageSource })`.
189
189
  * `voice_input` — диктовка через сервер (`@ykurilov/agent-chat-voice`, режим `relay`): `inputTokens` — секунды звука,
190
190
  * `modelId` — модель распознавания. `voice_polish` — чистка надиктованного текста моделью.
191
+ * `mcp_tool` — вызов инструмента сервера MCP (`@ykurilov/agent-chat-mcp`), если сервер сообщил стоимость: `modelId` —
192
+ * имя инструмента `<префикс>__<имя>`, `providerId` — `mcp`, токенов нет.
191
193
  */
192
- export declare const BUILT_IN_USAGE_SOURCES: readonly ["answer", "answer_correction", "compaction", "memory", "speech", "sounds", "web_tools", "images", "helper", "background", "judge", "first_message", "voice_input", "voice_polish"];
194
+ export declare const BUILT_IN_USAGE_SOURCES: readonly ["answer", "answer_correction", "compaction", "memory", "speech", "sounds", "web_tools", "images", "helper", "background", "judge", "first_message", "voice_input", "voice_polish", "mcp_tool"];
193
195
  /** Штатные виды расхода SDK. */
194
196
  export type BuiltInUsageSource = (typeof BUILT_IN_USAGE_SOURCES)[number];
195
197
  /**
@@ -2,6 +2,7 @@ import type { AgentAudience, AgentChannel, ChatSubject } from "../conversation/t
2
2
  import type { AppStateValues } from "../app-state/app-state.js";
3
3
  import type { AgentNotice } from "../notices/agent-notice.js";
4
4
  import type { StaffActor } from "../turn-hooks/turn-hooks.js";
5
+ import type { AgentViewer } from "../agent-run/agent-viewer.js";
5
6
  /** Тип служебной части ответа с застывшими блоками хода. Клиенту не уходит, модели — только текстом блоков. */
6
7
  export declare const FROZEN_CONTEXT_PART_TYPE = "data-frozen-context";
7
8
  /** Блок контекста: ключ уникален в наборе, текст идёт модели как есть. Личный блок не показывается в групповом ходе. */
@@ -44,6 +45,8 @@ export interface ContextBlocksInput {
44
45
  audience: AgentAudience;
45
46
  /** Сотрудник, который делает ход в копии чата человека; нет — ход делает сам владелец. */
46
47
  staff?: StaffActor;
48
+ /** Права человека на ход (`agent.viewer`), тот же объект, что у инструментов. Нет `agent.viewer` — поля нет. */
49
+ viewer?: AgentViewer;
47
50
  modelId: string;
48
51
  providerId: string;
49
52
  /** Отмена: «Стоп», срок функции (`agent.contextBlocksTimeoutMs`), срок хода. */
@@ -1,4 +1,5 @@
1
1
  import type { AgentTurnInput } from "../agent-run/run-agent-turn.js";
2
+ import type { AgentViewer } from "../agent-run/agent-viewer.js";
2
3
  import type { AppStateValues } from "../app-state/app-state.js";
3
4
  import type { AgentChatMessage } from "../conversation/types.js";
4
5
  import type { FrozenContextData } from "./context-blocks.js";
@@ -10,6 +11,7 @@ export declare function frozenContextForTurn(input: AgentTurnInput, turn: {
10
11
  history: readonly AgentChatMessage[];
11
12
  answer?: AgentChatMessage;
12
13
  state: AppStateValues;
14
+ viewer?: AgentViewer;
13
15
  }): Promise<{
14
16
  data: FrozenContextData;
15
17
  fresh: boolean;
@@ -23,4 +25,5 @@ export declare function resumeNoteForTurn(input: AgentTurnInput, turn: {
23
25
  history: readonly AgentChatMessage[];
24
26
  answer: AgentChatMessage;
25
27
  state: AppStateValues;
28
+ viewer?: AgentViewer;
26
29
  }): Promise<FrozenContextData | undefined>;
@@ -78,6 +78,8 @@ export type { ChatGreeting, ImportChatInput, ImportedImagePart, ImportedMessageI
78
78
  export { AttachmentRejectedError, withoutFileParts } from "./attachments/message-attachments.js";
79
79
  export type { IncomingFilePart, MessageAttachments, StoredFilePart } from "./attachments/message-attachments.js";
80
80
  export type { AgentToolsModel, AgentToolsSource } from "./agent-run/run-agent-turn.js";
81
+ export { AgentViewerError } from "./agent-run/agent-viewer.js";
82
+ export type { AgentViewer, AgentViewerInput, AgentViewerSource } from "./agent-run/agent-viewer.js";
81
83
  export type { StepContext, StepContextInput } from "./agent-run/step-context.js";
82
84
  export type { ContextBlock, ContextBlockEntry, ContextBlocksInput, ContextBlocksSource, HiddenContextBlock } from "./frozen-context/context-blocks.js";
83
85
  export { FROZEN_CONTEXT_PART_TYPE } from "./frozen-context/context-blocks.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ykurilov/agent-chat-core",
3
- "version": "0.55.0",
3
+ "version": "0.56.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "sideEffects": false,