@kiturone/kapibala 0.0.2 → 0.0.4

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/dist/index.d.cts CHANGED
@@ -1,16 +1,264 @@
1
+ /** 内置适配器的实际请求目标;用于拒绝模型、协议或端点错配的绑定。 */
2
+ interface ModelProviderBinding {
3
+ protocol: ModelProtocol;
4
+ modelName: string;
5
+ baseURL: string;
6
+ workspaceId?: string;
7
+ }
8
+ /** 协议适配器:把 canonical 请求翻译为 wire 协议并流式返回事件。 */
9
+ interface ModelProvider {
10
+ /** 用于诊断与脱敏说明的稳定名称。 */
11
+ readonly name: string;
12
+ readonly binding?: ModelProviderBinding;
13
+ /** 内置 Provider 凭据是否可用;自定义无需鉴权的 Provider 可省略。 */
14
+ readonly credentialsReady?: boolean;
15
+ /** 发起一次模型调用;signal 取消时立即停止,实现负责协议翻译、私有状态校验与流清理。 */
16
+ create(req: ModelRequest): AsyncIterable<ModelEvent>;
17
+ /** 返回统一 canonical tool 消息;wire 角色转换仅发生在请求翻译阶段。 */
18
+ assembleToolResults(results: ToolResultBlock[]): CanonicalMessage[];
19
+ }
20
+ /** 按消息级事务装配工具结果;任何协议都不得把 wire user/Item 写为历史角色。 */
21
+ declare function assembleCanonicalToolResults(results: ToolResultBlock[]): CanonicalMessage[];
22
+
23
+ /** 逻辑模型角色:default 为回退绑定,planning / execution / fast 是主任务可选场景,summary 仅用于独立的上下文压缩。 */
24
+ type ModelRole = 'default' | 'planning' | 'execution' | 'summary' | 'fast';
25
+ /** 主任务可显式选择的场景;summary 只用于独立的上下文压缩。 */
26
+ type PrimaryModelRole = Exclude<ModelRole, 'summary'>;
27
+ /** wire 协议族;决定适配器实现、私有状态格式与错误解析方式。 */
28
+ type ModelProtocol = 'openai-compatible' | 'anthropic' | 'openai-responses';
29
+ /** 兼容 Chat 端点的显式参数/完成能力;缺省保持既有参数并要求完整 DONE。 */
30
+ interface ChatCapabilities {
31
+ maxTokensField?: 'max_tokens' | 'max_completion_tokens';
32
+ supportsStreamingUsage?: boolean;
33
+ supportsTemperature?: boolean;
34
+ requiresDone?: boolean;
35
+ replayReasoningContent?: boolean;
36
+ }
37
+ /** 配置侧窗口值:正整数 Token 数,或十进制 K / M 简写(如 '200K');解析规则见 resolveContextWindow。 */
38
+ type ContextWindowValue = number | `${number}${'K' | 'k' | 'M' | 'm'}`;
39
+ /** 解析后的窗口;estimated 为 true 时数值来自默认估算,不能当作模型的精确保证。 */
40
+ interface ResolvedContextWindow {
41
+ tokens: number;
42
+ /** true 表示模型未声明窗口,当前值来自 Kapibala 的默认估算。 */
43
+ estimated: boolean;
44
+ }
45
+ /** 模型未声明 contextWindow 时的默认窗口估算值。 */
46
+ declare const DEFAULT_CONTEXT_WINDOW_TOKENS = 1000000;
47
+ /**
48
+ * 将模型上下文窗口统一解析为整数 Token 数。
49
+ *
50
+ * 配置允许直接填写整数,或使用十进制 K/M 简写;未填写时返回默认 1M,并标记为估算值。
51
+ */
52
+ declare function resolveContextWindow(value?: ContextWindowValue): ResolvedContextWindow;
53
+ /** 模型配置档案;provider 是 wire 协议族而非厂商名,绑定必须与适配器声明一致(见 validateModelBinding)。 */
54
+ interface ModelProfile {
55
+ id: string;
56
+ name: string;
57
+ provider: ModelProtocol;
58
+ baseURL: string;
59
+ /** 承载密钥的环境变量名;core 不直接读取,由宿主解析后注入 Provider。 */
60
+ apiKeyEnv: string;
61
+ apiKey?: string;
62
+ modelName: string;
63
+ /** 未声明时按 DEFAULT_CONTEXT_WINDOW_TOKENS 估算;解析规则见 resolveContextWindow。 */
64
+ contextWindow?: ContextWindowValue;
65
+ supportsThinking?: boolean;
66
+ /** 单次输出上限;参与上下文预算推导,缺省按 4096 预留。 */
67
+ maxOutputTokens?: number;
68
+ chatCapabilities?: ChatCapabilities;
69
+ /** Anthropic 请求携带的 workspace;参与绑定一致性校验。 */
70
+ anthropicWorkspaceId?: string;
71
+ }
72
+ /** 角色到 Profile / Provider 配对的解析接口;实现必须保证配对一致且 profile 以副本返回。 */
73
+ interface ModelRouter {
74
+ resolve(role?: ModelRole): ModelProvider;
75
+ getProfile(role?: ModelRole): ModelProfile;
76
+ }
77
+ /** 校验内置适配器的实际请求目标;旧自定义 Provider 由宿主显式提供绑定。 */
78
+ declare function validateModelBinding(profile: ModelProfile, provider: ModelProvider): void;
79
+ /** 保存原子 Profile/Provider 配对;普通与摘要查询可回退 default,显式任务严格解析。 */
80
+ declare class SimpleModelRouter implements ModelRouter {
81
+ private readonly providers;
82
+ private readonly profiles;
83
+ private defaultRole;
84
+ constructor(defaultProfile: ModelProfile, defaultProvider: ModelProvider);
85
+ /** 校验配对后同时替换两者并保存配置副本,校验失败不污染既有绑定。 */
86
+ setRole(role: ModelRole, profile: ModelProfile, provider: ModelProvider): void;
87
+ /** 显式场景要求存在绑定;只有普通查询和摘要允许既有默认回退。 */
88
+ getBinding(role?: ModelRole, strict?: boolean): {
89
+ profile: ModelProfile;
90
+ provider: ModelProvider;
91
+ };
92
+ resolve(role?: ModelRole): ModelProvider;
93
+ /** 返回指定角色或默认模型的独立副本,调用方不能改写在途绑定。 */
94
+ getProfile(role?: ModelRole): ModelProfile;
95
+ }
96
+
97
+ /**
98
+ * Error Taxonomy for Kapibala Agent Harness
99
+ */
100
+
101
+ /** 模型失败的安全分类;由明确状态码与受控错误码推导,不基于自然语言猜测根因。 */
102
+ type ModelErrorCategory = 'authentication' | 'quota' | 'rate_limit' | 'context' | 'service' | 'network' | 'timeout' | 'invalid_request' | 'invalid_response' | 'unknown';
103
+ /** ModelError 的受控输入;仅这些字段会进入错误对象,原始响应体与密钥不得携带。 */
104
+ interface ModelErrorOptions {
105
+ status?: number;
106
+ retryable?: boolean;
107
+ code?: string;
108
+ transportCode?: string;
109
+ providerCode?: string;
110
+ providerType?: string;
111
+ stage?: 'connect' | 'response' | 'stream' | 'request';
112
+ }
113
+ /** 跨协议模型失败的脱敏说明;适用于主任务和摘要,不代表自动重试授权。 */
114
+ interface ModelErrorInfo {
115
+ category: ModelErrorCategory;
116
+ code: string;
117
+ message: string;
118
+ status?: number;
119
+ providerCode?: string;
120
+ providerType?: string;
121
+ transportCode?: string;
122
+ stage?: ModelErrorOptions['stage'];
123
+ operation?: 'primary' | 'summary';
124
+ /** type-only 引用协议层角色类型;运行时无循环依赖。 */
125
+ modelRole?: PrimaryModelRole;
126
+ modelId?: string;
127
+ provider?: string;
128
+ retryPolicy: KapibalaError['retryPolicy'];
129
+ suggestion: string;
130
+ }
131
+ /** 清理服务端报错中的终端控制符、常见凭据及带凭据的 URL,限制长度;不展示完整响应或请求头。 */
132
+ declare function sanitizeModelErrorMessage(value: string): string;
133
+ /** 生成统一脱敏说明;上下文补充调用场景,不携带原始异常、请求正文或密钥。 */
134
+ declare function describeModelError(error: ModelError, context?: Pick<ModelErrorInfo, 'modelId' | 'provider' | 'operation' | 'modelRole'>): ModelErrorInfo;
135
+ /** 错误体系基类:code 供机器判定,retryPolicy 是处理建议而非重试授权,safeMessage 是可对外展示的固定文案。 */
136
+ declare class KapibalaError extends Error {
137
+ readonly code: string;
138
+ readonly retryPolicy: 'never' | 'immediate' | 'backoff' | 'after_user_action';
139
+ readonly safeMessage: string;
140
+ constructor(message: string, options?: {
141
+ code?: string;
142
+ retryPolicy?: 'never' | 'immediate' | 'backoff' | 'after_user_action';
143
+ safeMessage?: string;
144
+ });
145
+ }
146
+ /** 模型调用失败;message 已脱敏,对外诊断统一经 describeModelError 产出,retryPolicy 仅为处理建议。 */
147
+ declare class ModelError extends KapibalaError {
148
+ readonly status?: number;
149
+ /** 属于可退避重试的瞬态类别(限流/服务/超时/网络);不等于自动重试授权。 */
150
+ readonly retryable: boolean;
151
+ /** 可选的受控底层连接错误码,不包含原始传输异常文本。 */
152
+ readonly transportCode?: string;
153
+ readonly providerCode?: string;
154
+ readonly providerType?: string;
155
+ readonly stage?: ModelErrorOptions['stage'];
156
+ readonly category: ModelErrorCategory;
157
+ /** 构建模型错误,清理服务端原因并按明确状态/错误码分类;重试策略仅为建议,不授权重放。 */
158
+ constructor(message: string, options?: ModelErrorOptions);
159
+ }
160
+ /** Provider 明确拒绝上下文长度;仅无输出请求允许预算处理后重发一次。 */
161
+ declare class ContextOverflowError extends ModelError {
162
+ /** 保留明确上下文错误的脱敏服务端原因;只允许尚无输出的请求进入一次预算处理。 */
163
+ constructor(status?: number, details?: Pick<ModelErrorOptions, 'providerCode' | 'providerType' | 'stage'> & {
164
+ message?: string;
165
+ });
166
+ }
167
+ /** 模型 API 语义之外的传输失败;retryable 表示属于可立即重试的网络类错误。 */
168
+ declare class TransportError extends KapibalaError {
169
+ readonly retryable: boolean;
170
+ constructor(message: string, retryable?: boolean);
171
+ }
172
+ /** 工具执行失败的通用错误;retryPolicy 固定 never,后续处理由调用方决定。 */
173
+ declare class ToolError extends KapibalaError {
174
+ constructor(message: string);
175
+ }
176
+ /** 请求的工具在注册表中不存在;message 回显工具名与可用列表,对外展示用 safeMessage。 */
177
+ declare class ToolNotFound extends KapibalaError {
178
+ readonly toolName: string;
179
+ readonly availableTools: string[];
180
+ constructor(toolName: string, availableTools?: string[]);
181
+ }
182
+ /** 用户主动中止;不属于失败,恢复需要用户重新发起操作。 */
183
+ declare class AbortError extends KapibalaError {
184
+ constructor(message?: string);
185
+ }
186
+ /** 无受控分类的致命错误(code 固定 INTERNAL_ERROR、不可重试);终止策略由宿主决定。 */
187
+ declare class FatalError extends KapibalaError {
188
+ constructor(message: string);
189
+ }
190
+ /** 会话正在执行任务时拒绝新的排他操作(切换模型、挂载插件等),operation 描述被拒绝的动作。 */
191
+ declare class SessionBusyError extends KapibalaError {
192
+ constructor(operation: string);
193
+ }
194
+ /** 请求硬预算不足;需用户缩小任务或选择更大窗口,不允许切掉当前任务继续。 */
195
+ declare class ContextBudgetError extends KapibalaError {
196
+ readonly usedTokens: number;
197
+ readonly inputBudget: number;
198
+ constructor(usedTokens: number, inputBudget: number);
199
+ }
200
+ /** 压缩状态持久提交失败,与模型预算或生成失败分别处理,不允许未落盘候选生效。 */
201
+ declare class ContextStorageError extends KapibalaError {
202
+ constructor(message: string);
203
+ }
204
+
1
205
  /**
2
206
  * Canonical Message & Event Types for Kapibala
3
207
  */
4
- type ContentBlock = TextBlock | ToolUseBlock | ToolResultBlock | ThinkingBlock | RedactedThinkingBlock;
208
+
209
+ /** 原生协议内容的来源;仅同一次运行、同模型和端点允许回传私有状态。 */
210
+ interface ProtocolOrigin {
211
+ version: 1;
212
+ protocol: 'anthropic' | 'openai-responses';
213
+ modelName: string;
214
+ modelId?: string;
215
+ runId: string;
216
+ endpointScope: string;
217
+ }
218
+ /** Responses Item 与 canonical 块的对应关系;调用 Item 身份独立于业务 call_id。 */
219
+ interface ProtocolItemMetadata {
220
+ origin: ProtocolOrigin;
221
+ itemIndex: number;
222
+ itemId?: string;
223
+ contentIndex?: number;
224
+ phase?: 'commentary' | 'final_answer';
225
+ contentType?: 'output_text' | 'refusal';
226
+ arguments?: string;
227
+ }
228
+ /** 只保存受控 reasoning Item;密文不进入展示或摘要源。 */
229
+ interface ProviderStateBlock {
230
+ type: 'provider_state';
231
+ origin: ProtocolOrigin;
232
+ item: {
233
+ type: 'reasoning';
234
+ id: string;
235
+ encrypted_content?: string;
236
+ summary: {
237
+ type: 'summary_text';
238
+ text: string;
239
+ }[];
240
+ status?: 'in_progress' | 'completed' | 'incomplete';
241
+ };
242
+ }
243
+ /** canonical 历史的内容块联合;provider_state 等私有块只在同 run、同模型与端点续答回传。 */
244
+ type ContentBlock = TextBlock | ToolUseBlock | ToolResultBlock | ThinkingBlock | RedactedThinkingBlock | ProviderStateBlock;
5
245
  interface TextBlock {
6
246
  type: 'text';
7
247
  text: string;
248
+ /** 源 wire Item 元数据;正文被改写后由调用方清除,不作为业务身份。 */
249
+ protocolMeta?: ProtocolItemMetadata;
8
250
  }
9
251
  interface ToolUseBlock {
252
+ /** 工具执行语义来源;新运行记录,旧历史可缺省。未知插件不按内置只读工具剪裁。 */
253
+ source?: string;
254
+ /** 执行器记录的绝对工具根目录;仅作历史路径依据,不改变参数或恢复旧授权。旧历史可缺省。 */
255
+ executionRoot?: string;
10
256
  type: 'tool_use';
11
257
  id: string;
12
258
  name: string;
13
259
  input: Record<string, unknown>;
260
+ /** 源 wire Item 元数据;内容被改写后由调用方清除,不作为业务身份。 */
261
+ protocolMeta?: ProtocolItemMetadata;
14
262
  }
15
263
  interface ToolResultBlock {
16
264
  type: 'tool_result';
@@ -27,27 +275,54 @@ interface ToolResultBlock {
27
275
  interface ThinkingBlock {
28
276
  type: 'thinking';
29
277
  thinking: string;
278
+ /** 存在签名或来源时属于私有输出,改写内容会被整批拒绝。 */
30
279
  signature?: string;
280
+ origin?: ProtocolOrigin;
31
281
  }
282
+ /** Provider 提供的密文占位;仅按原样回传用于续答,不进入展示或摘要源。 */
32
283
  interface RedactedThinkingBlock {
33
284
  type: 'redacted_thinking';
34
285
  data: string;
286
+ origin?: ProtocolOrigin;
35
287
  }
288
+ /** 单次模型请求的 token 用量;由 Provider 上报,缺失的字段不能按零推断。 */
36
289
  interface Usage {
37
290
  promptTokens: number;
38
291
  completionTokens: number;
39
292
  totalTokens: number;
293
+ /** Provider 明确提供的缓存命中输入量;缺失表示未知,不能按零推断。 */
294
+ cachedPromptTokens?: number;
40
295
  }
296
+ /** canonical 消息角色;'tool' 仅用于工具结果消息,wire 角色转换只发生在请求投影阶段。 */
41
297
  type MessageRole = 'user' | 'assistant' | 'system' | 'tool';
298
+ /**
299
+ * 协议无关的历史真源;wire 格式只在请求投影时出现。
300
+ * 不变量:assistant 消息中的 tool_use 进入历史后,对应 tool_result 消息必须紧跟其后。
301
+ */
42
302
  interface CanonicalMessage {
303
+ /** 派生背景锚点独立于真实用户输入,避免合并后丢失受保护原消息的来源身份。 */
304
+ contextSummary?: {
305
+ checkpointId: string;
306
+ };
307
+ /** 稳定消息身份;旧 SDK 消息可省略,在进入受管历史时补齐。 */
308
+ id?: string;
309
+ /** 用户交互身份,与内部模型步骤及进程运行实例分别记录。 */
310
+ interactionId?: string;
311
+ /** 未完成正文不会进入模型请求视图。省略表示旧版已落盘正文。 */
312
+ state?: 'completed' | 'draft' | 'failed' | 'interrupted';
43
313
  role: MessageRole;
44
314
  content: ContentBlock[];
45
315
  timestamp?: number;
46
316
  }
317
+ /** 判别并收窄为文本块。 */
47
318
  declare function isTextBlock(block: ContentBlock): block is TextBlock;
319
+ /** 判别并收窄为工具调用块。 */
48
320
  declare function isToolUseBlock(block: ContentBlock): block is ToolUseBlock;
321
+ /** 判别并收窄为工具结果块。 */
49
322
  declare function isToolResultBlock(block: ContentBlock): block is ToolResultBlock;
323
+ /** 判别并收窄为思考块。 */
50
324
  declare function isThinkingBlock(block: ContentBlock): block is ThinkingBlock;
325
+ /** 单个 turn 的指标快照;错误与熔断路径也以统一构造产出(工具字段为零),保证结构一致。 */
51
326
  interface TurnMetrics {
52
327
  turn: number;
53
328
  startTime: number;
@@ -61,6 +336,7 @@ interface TurnMetrics {
61
336
  totalTokens: number;
62
337
  toolCallsCount: number;
63
338
  }
339
+ /** 一次完整 run 的累计指标;token 数为各轮请求之和,上下文占用单独见 contextUsage。 */
64
340
  interface RunMetrics {
65
341
  startTime: number;
66
342
  endTime: number;
@@ -74,16 +350,23 @@ interface RunMetrics {
74
350
  turns: number;
75
351
  toolCalls: number;
76
352
  status: 'completed' | 'failed' | 'aborted';
353
+ /** 模型失败的脱敏汇总;保留具体阶段与原因,不携带请求或响应正文。 */
354
+ failure?: ModelErrorInfo;
77
355
  /** 最近一次内部模型请求占用的上下文;不使用 run 累计 promptTokens。 */
78
356
  contextUsage?: ContextUsage;
79
357
  }
358
+ /** 供宿主展示的上下文占用快照;估算值不能用于计费或精确预算。 */
80
359
  interface ContextUsage {
81
360
  usedTokens?: number;
361
+ /** true 表示未收到当前请求 usage,输入占用使用预算估算,不能用于计费。 */
362
+ estimatedUsage?: boolean;
82
363
  limitTokens: number;
83
364
  percent?: number;
84
365
  estimatedLimit: boolean;
85
366
  }
367
+ /** 单 turn 内关键阶段的进度标记;顺序与 AgentLoop 的实际派发时序一致,供展示与诊断。 */
86
368
  type StepLogStage = 'model_request_start' | 'first_token' | 'model_stream_finish' | 'tool_execution_start' | 'tool_execution_finish' | 'turn_finish';
369
+ /** 面向宿主的步骤日志;message 可直接展示,结构化数值放在 metadata 中。 */
87
370
  interface StepLogEntry {
88
371
  timestamp: number;
89
372
  turn: number;
@@ -100,6 +383,56 @@ interface StepLogEntry {
100
383
  * 不应直接把本类型当作长期兼容的网络协议。
101
384
  */
102
385
  type SessionEvent = {
386
+ type: 'session_resumed';
387
+ conversationId: string;
388
+ runtimeSessionId: string;
389
+ messageCount: number;
390
+ } | {
391
+ type: 'session_switched';
392
+ conversationId: string;
393
+ previousConversationId: string;
394
+ } | {
395
+ type: 'compaction_start';
396
+ conversationId: string;
397
+ runId?: string;
398
+ kind: 'prune' | 'summary';
399
+ reason: 'threshold' | 'manual' | 'overflow';
400
+ persistence: 'disk' | 'memory';
401
+ beforeTokens: number;
402
+ } | {
403
+ type: 'compaction_finish';
404
+ conversationId: string;
405
+ runId?: string;
406
+ kind: 'prune' | 'summary';
407
+ reason: 'threshold' | 'manual' | 'overflow';
408
+ persistence: 'disk' | 'memory';
409
+ beforeTokens: number;
410
+ afterTokens: number;
411
+ checkpointId?: string;
412
+ coveredEndMessageId?: string;
413
+ prunedResults?: number;
414
+ modelId?: string;
415
+ durationMs: number;
416
+ } | {
417
+ type: 'compaction_failed';
418
+ conversationId: string;
419
+ runId?: string;
420
+ kind: 'prune' | 'summary';
421
+ reason: 'threshold' | 'manual' | 'overflow';
422
+ persistence: 'disk' | 'memory';
423
+ error: string;
424
+ /** 脱敏失败分类,不包含 Provider 响应正文或历史内容。 */
425
+ errorCode?: string;
426
+ /** 摘要模型失败采用与主任务相同的脱敏说明;验证失败不回显摘要正文。 */
427
+ modelError?: ModelErrorInfo;
428
+ consecutiveFailures: number;
429
+ } | {
430
+ type: 'context_budget_exceeded';
431
+ conversationId: string;
432
+ runId?: string;
433
+ usedTokens: number;
434
+ inputBudget: number;
435
+ } | {
103
436
  type: 'turn_start';
104
437
  turn: number;
105
438
  } | {
@@ -108,9 +441,16 @@ type SessionEvent = {
108
441
  } | {
109
442
  type: 'text_delta';
110
443
  text: string;
444
+ } | {
445
+ type: 'thinking_block_start';
446
+ blockId: string;
111
447
  } | {
112
448
  type: 'thinking_delta';
113
449
  thinking: string;
450
+ blockId?: string;
451
+ } | {
452
+ type: 'thinking_block_stop';
453
+ blockId: string;
114
454
  } | {
115
455
  type: 'tool_start';
116
456
  id: string;
@@ -155,13 +495,21 @@ type SessionEvent = {
155
495
  } | {
156
496
  type: 'error';
157
497
  error: Error;
498
+ modelError?: ModelErrorInfo;
158
499
  };
159
500
  type ModelEvent = {
160
501
  type: 'text_delta';
161
502
  text: string;
503
+ } | {
504
+ type: 'thinking_block_start';
505
+ blockId: string;
162
506
  } | {
163
507
  type: 'thinking_delta';
164
508
  thinking: string;
509
+ blockId?: string;
510
+ } | {
511
+ type: 'thinking_block_stop';
512
+ blockId: string;
165
513
  } | {
166
514
  type: 'tool_call_start';
167
515
  id: string;
@@ -182,66 +530,608 @@ type ModelEvent = {
182
530
  usage?: Usage;
183
531
  ttftMs?: number;
184
532
  durationMs?: number;
533
+ finishReason?: string;
534
+ /** 完整且有序的最终内容;有此字段时增量只供展示,不重复装配或执行工具。 */
535
+ finalContent?: ContentBlock[];
536
+ refusal?: boolean;
185
537
  };
538
+ /** 投影给模型的工具描述;由注册表条目转换而来,仅暴露名称、描述与参数 Schema。 */
186
539
  interface ToolDefinition {
187
540
  name: string;
188
541
  description: string;
189
542
  parameters: Record<string, unknown>;
190
543
  }
544
+ /** 协议无关的模型请求;messages 是 canonical 真源的克隆,wire 翻译只发生在 Provider 内。 */
191
545
  interface ModelRequest {
192
546
  systemPrompt?: string;
193
547
  messages: CanonicalMessage[];
194
548
  tools?: ToolDefinition[];
195
549
  signal?: AbortSignal;
550
+ /** 以下两项可选覆盖采样温度与单次输出上限;未设置时由适配器按协议与能力决定。 */
196
551
  temperature?: number;
197
552
  maxTokens?: number;
553
+ /** 宿主提供的本次运行来源;缺省时原生适配器不回传来源未知的私有状态。 */
554
+ context?: {
555
+ runId: string;
556
+ modelId?: string;
557
+ };
558
+ }
559
+ /** runtime 通用请求准备契约;实现可以预算或投影,Loop 不依赖具体上下文管理器。 */
560
+ type RequestPreparation = (request: ModelRequest, history: readonly CanonicalMessage[], reason?: 'threshold' | 'overflow') => AsyncGenerator<SessionEvent, ModelRequest>;
561
+
562
+ /** 生成进程内单调递增的 UUIDv7;时钟回拨时沿用逻辑时间,序列耗尽才推进时间。 */
563
+ declare function createMessageId(): string;
564
+
565
+ /** 按来源及原始位置生成旧消息身份;复制输入,不改变调用者持有的正文或已有身份。 */
566
+ declare function identifyHistory(messages: readonly CanonicalMessage[], source: string): CanonicalMessage[];
567
+ /**
568
+ * 一次缺失工具结果的补齐:result 为 OUTCOME_UNKNOWN 占位,只用于闭合历史事务。
569
+ * 持久化为 history_repair 记录后,恢复时叠加到原工具事务;不重放工具。
570
+ */
571
+ interface HistoryRepair {
572
+ assistantId: string;
573
+ toolCallId: string;
574
+ result: ToolResultBlock;
198
575
  }
576
+ /** normalizeHistory 的产物:合法请求视图、来源追踪与修复/丢弃审计。 */
577
+ interface NormalizedHistory {
578
+ messages: CanonicalMessage[];
579
+ /** 与 messages 同序的原始消息 ID 集合;修复结果关联原始 assistant。 */
580
+ sources: string[][];
581
+ /** 已注入 messages 的缺失结果占位;结构与 history_repair 持久记录一致。 */
582
+ repairs: HistoryRepair[];
583
+ /** 被忽略的孤儿、迟到或重复工具结果提示;只诊断,不回写调用方输入。 */
584
+ diagnostics: string[];
585
+ }
586
+ /**
587
+ * 构造合法且独立的请求视图:只接受紧邻事务的结果,缺失结果标为未知;重复调用身份明确失败。
588
+ * 合并仅适用于纯文本的同角色消息,失败正文不重放,所有来源均可追踪。
589
+ */
590
+ declare function normalizeHistory(input: readonly CanonicalMessage[]): NormalizedHistory;
591
+ /** 以用户输入为界划分的一次交互及其终态;保护范围与摘要资格都以它为单位。 */
592
+ interface InteractionBoundary {
593
+ interactionId: string;
594
+ /** completed 需显式终态或推断成功;failed 只来自显式终态,缺省 interrupted。 */
595
+ status: 'completed' | 'failed' | 'interrupted';
596
+ /** 该交互按历史顺序覆盖的原始消息 ID。 */
597
+ messageIds: string[];
598
+ }
599
+ /** 运行收尾时记录的交互终态;有 start 无 finish 的运行恢复后保持 interrupted。 */
600
+ interface InteractionTerminal {
601
+ interactionId: string;
602
+ status: InteractionBoundary['status'];
603
+ }
604
+ /**
605
+ * 以显式终态为准恢复用户交互;旧历史仅在完整工具事务之后存在非空最终答复时推断成功。
606
+ * 保护最近成功交互及其后的所有交互,没有成功证据时保护全部历史。
607
+ */
608
+ declare function indexInteractions(input: readonly CanonicalMessage[], terminals?: readonly InteractionTerminal[]): {
609
+ interactions: InteractionBoundary[];
610
+ protectedMessageIds: string[];
611
+ };
199
612
 
200
613
  /**
201
- * Error Taxonomy for Kapibala Agent Harness
614
+ * 旧版单文件 JSONL MessageStore:每行一条消息,无版本化状态能力。
615
+ * 写入为同步追加,不做 fsync 或单写者保护;恢复时容错跳过损坏行并闭合悬挂事务。
202
616
  */
203
- declare class KapibalaError extends Error {
204
- readonly code: string;
205
- readonly retryPolicy: 'never' | 'immediate' | 'backoff' | 'after_user_action';
206
- readonly safeMessage: string;
207
- constructor(message: string, options?: {
208
- code?: string;
209
- retryPolicy?: 'never' | 'immediate' | 'backoff' | 'after_user_action';
210
- safeMessage?: string;
211
- });
617
+ declare class JSONLMessageStore implements MessageStore {
618
+ readonly filePath: string;
619
+ constructor(filePath: string);
620
+ /** 校验协议内容后追加一行 JSON;不补身份、不查重、不 fsync。 */
621
+ append(message: CanonicalMessage): Promise<void>;
622
+ /** 读取全部消息;半截损坏行忽略,悬挂 tool_use 就地补 OUTCOME_UNKNOWN 结果。 */
623
+ load(): Promise<CanonicalMessage[]>;
624
+ /** 删除整个文件;文件不存在时静默成功。 */
625
+ clear(): Promise<void>;
626
+ /**
627
+ * 历史自愈(设计文档 §4.4):逐条扫描 assistant 的 tool_use,
628
+ * 若其后的 tool 消息未完整覆盖这些 tool_use,就地补一条 is_error 的 tool_result。
629
+ *
630
+ * 之所以做**全历史扫描**而非只看末条:崩溃可能发生在任意一轮工具执行中途,
631
+ * 悬挂的 tool_use 未必位于历史末尾(例如中断后用户又继续提了问)。
632
+ * 只看末条会漏掉夹在中间的悬挂,下一次请求仍会因上下文非法而 400。
633
+ */
634
+ private healDanglingToolCalls;
212
635
  }
213
- declare class ModelError extends KapibalaError {
214
- readonly status?: number;
215
- readonly retryable: boolean;
216
- constructor(message: string, options?: {
217
- status?: number;
218
- retryable?: boolean;
219
- });
636
+
637
+ /**
638
+ * 消息级持久化最小契约:user、assistant、tool 三类消息逐条经 append 落盘,
639
+ * load 恢复原始正文(而非模型请求投影),clear 实现 SDK 清空语义。
640
+ * 需要持久压缩、交互终态等能力的宿主另实现 StatefulMessageStore。
641
+ */
642
+ interface MessageStore {
643
+ append(message: CanonicalMessage): Promise<void>;
644
+ load(): Promise<CanonicalMessage[]>;
645
+ clear(): Promise<void>;
220
646
  }
221
- declare class TransportError extends KapibalaError {
222
- readonly retryable: boolean;
223
- constructor(message: string, retryable?: boolean);
647
+
648
+ /** 会话正文 schema 版本;读取时不匹配即拒绝恢复,不做跨版本猜测。 */
649
+ declare const SESSION_SCHEMA_VERSION = 1;
650
+ /** 会话记录类型:header 只出现一次,message 承载正文,其余为状态记录。 */
651
+ type SessionRecordType = 'header' | 'message' | 'run_started' | 'run_finished' | 'message_state' | 'history_repair' | 'usage' | 'checkpoint' | 'context_pruned' | 'compaction_state' | 'title' | 'reset' | 'legacy_import';
652
+ /** 会话文件首条记录:身份与创建环境快照;conversationId 与文件名强绑定。 */
653
+ interface SessionHeader {
654
+ conversationId: string;
655
+ projectRoot: string;
656
+ initialCwd: string;
657
+ createdAt?: number;
658
+ gitBranch?: string;
659
+ /** 旧历史导入的幂等身份;存在时同一来源只导入一次。 */
660
+ importIdentity?: string;
661
+ }
662
+ /** 单条 JSONL 记录封装;parentId 链接前驱,恢复时校验追加次序。 */
663
+ interface SessionRecord {
664
+ schemaVersion: number;
665
+ type: SessionRecordType;
666
+ recordId: string;
667
+ timestamp: number;
668
+ parentId: string | null;
669
+ payload: Record<string, unknown>;
670
+ }
671
+ /** loadState 返回的版本化状态视图;记录自最近 reset 起有效。 */
672
+ interface SessionState {
673
+ header: SessionHeader;
674
+ /** 最近 reset 之后的记录;包含正文及状态,不包含头部。 */
675
+ records: SessionRecord[];
676
+ /** 只随正文、修复与 reset 改变,不因 usage 或缓存写入失效。 */
677
+ contentRevision: string;
678
+ }
679
+ /** MessageStore 的可选状态能力;旧 SDK Store 不需要实现,宿主据此降级持久压缩。 */
680
+ interface StatefulMessageStore extends MessageStore {
681
+ appendRecord(type: Exclude<SessionRecordType, 'header' | 'message'>, payload: Record<string, unknown>): Promise<SessionRecord>;
682
+ loadState(): Promise<SessionState>;
683
+ }
684
+ /** 判断 Store 是否支持版本化状态;不读取数据或改变旧 Store。 */
685
+ declare function supportsSessionState(store: MessageStore): store is StatefulMessageStore;
686
+ /**
687
+ * 版本化消息与上下文状态的单文件存储。所有写入串行并 fsync,失败后拒绝继续写入。
688
+ * 调用者须在打开前取得单写者锁;本类不允许静默跳过中部损坏或重复身份。
689
+ */
690
+ declare class SessionStore implements StatefulMessageStore {
691
+ readonly filePath: string;
692
+ private queue;
693
+ private records;
694
+ private observer?;
695
+ private onDiagnostic?;
696
+ private stamp?;
697
+ private constructor();
698
+ /** 注册可重建缓存的写后通知;缓存失败只诊断,不撤销或毒化已 fsync 的正文。 */
699
+ setAppendObserver(observer: (record: SessionRecord) => void, onDiagnostic?: (message: string) => void): void;
700
+ /** 以独占创建方式安装新头部,已有文件明确失败,绝不覆盖其它会话。 */
701
+ static create(filePath: string, header: SessionHeader): Promise<SessionStore>;
702
+ /** 打开并验证已有会话;尾部残片先保存到隔离文件,中部损坏与未知版本拒绝恢复。 */
703
+ static open(filePath: string): Promise<SessionStore>;
704
+ /** 获取完整记录快照,等候已排队写入后读取;调用者不能借此修改内部记录。 */
705
+ readRecords(): Promise<SessionRecord[]>;
706
+ /** 消息级持久化,补稳定身份并保留所有终态字段,成功后方可进入下一次写入。 */
707
+ append(message: CanonicalMessage): Promise<void>;
708
+ /** 持久化状态记录,fsync 成功才返回;失败会毒化当前写者,要求重新验证后恢复。 */
709
+ appendRecord(type: Exclude<SessionRecordType, 'header' | 'message'>, payload: Record<string, unknown>): Promise<SessionRecord>;
710
+ /** 重建 reset 后的状态;统计记录和检查点不会推进正文 revision。 */
711
+ loadState(): Promise<SessionState>;
712
+ /**
713
+ * 恢复原始正文,并将幂等修复叠加到原工具事务;不合并连续消息,也不执行工具。
714
+ * 缺失结果用 history_repair 落盘,独立于实际工具结果和正文,不伪造成功。
715
+ */
716
+ load(): Promise<CanonicalMessage[]>;
717
+ /** SDK 清空语义通过持久边界实现;此前摘要、剪裁及失败状态不再参与恢复。 */
718
+ clear(): Promise<void>;
719
+ /** 生成前驱关联的 Envelope,前驱仅表达追加次序,未来 DAG 不改变当前恢复规则。 */
720
+ private makeRecord;
721
+ /** 单写者队列不吞异常;后续写入依赖同一失败 Promise,防止继续污染正文。 */
722
+ private enqueue;
723
+ /** 保存当前写者的正文版本,拒绝未经锁保护的第二写者继续追加。 */
724
+ private refreshStamp;
725
+ /** 校验每个完整记录,只有最后非空行的 JSON 残片可隔离,语义损坏绝不作为残片吞掉。 */
726
+ private readFile;
224
727
  }
225
- declare class ToolError extends KapibalaError {
226
- constructor(message: string);
728
+
729
+ /** 基于目录独占创建的单写者锁;只有能确认死亡的进程才允许保守回收,不按年龄抢占。 */
730
+ declare class SessionLock {
731
+ readonly lockPath: string;
732
+ private readonly owner;
733
+ private released;
734
+ private constructor();
735
+ /** 获取写入权,存活、无权限探测、损坏 owner 或正在回收均明确失败。 */
736
+ static acquire(lockPath: string): Promise<SessionLock>;
737
+ /** 仅释放本 nonce 的锁;调用者必须先等待在途工具、摘要及存储结束。 */
738
+ release(): Promise<void>;
739
+ /** 只认格式完整的 owner,缺失与损坏时保持锁而非猜测安全。 */
740
+ private static readOwner;
741
+ /**
742
+ * 清除上次回收崩溃的残留:无身份标记或标记进程已死亡的 recovery 目录可安全移除;
743
+ * 身份确认存活的回收进行中则保留。清不掉时视为回收进行中,由后续获取者再试。
744
+ */
745
+ private static clearAbandonedRecovery;
746
+ /** 无残留或残留进程已死亡时放行;确认存活的回收进行中则明确失败。 */
747
+ private static ensureNoLiveRecovery;
748
+ /** 仅 ESRCH 表示确定死亡;PID 复用或 EPERM 均保持原锁。 */
749
+ private static isDead;
227
750
  }
228
- declare class ToolNotFound extends KapibalaError {
229
- readonly toolName: string;
230
- readonly availableTools: string[];
231
- constructor(toolName: string, availableTools?: string[]);
751
+
752
+ /** 会话桶的项目身份:会话按工作树根隔离存储在项目桶目录下。 */
753
+ interface ProjectIdentity {
754
+ /** 真实工作树根(非 Git 目录时为真实 cwd),作为会话归属与来源基准。 */
755
+ projectRoot: string;
756
+ /** 解析符号链接后的真实 cwd。 */
757
+ cwd: string;
758
+ /** 规范化根目录的 SHA-256,决定 ~/.kapibala/sessions 下的桶目录。 */
759
+ projectKey: string;
760
+ /** detached HEAD 或非 Git 目录时缺省。 */
761
+ gitBranch?: string;
762
+ /** true 表示 cwd 位于 Git 工作树内;同工作树子目录共用同一桶。 */
763
+ gitWorktree?: boolean;
764
+ }
765
+ /** 解析真实工作树根;同工作树子目录共用桶,非 Git 目录和不同 worktree 独立。不会改变 cwd。 */
766
+ declare function resolveSessionProject(cwd: string): ProjectIdentity;
767
+ /**
768
+ * 会话 sidecar 缓存元数据;可随时从正文重建,校验失败即丢弃,不是恢复依据。
769
+ * 正文 JSONL 始终是唯一真源。
770
+ */
771
+ interface SessionMetadata {
772
+ schemaVersion: 1;
773
+ conversationId: string;
774
+ fileName: string;
775
+ projectRoot: string;
776
+ createdAt: number;
777
+ /** 最后一次正文、用户 run 或 reset 的时间;usage 与标题不影响排序。 */
778
+ lastActivityAt: number;
779
+ messageCount: number;
780
+ title: string;
781
+ /** 用户显式重命名的标题;存在时 reset 不再回退为默认标题。 */
782
+ customTitle?: string;
783
+ gitBranch?: string;
784
+ lastActivityGitBranch?: string;
785
+ lastModelId?: string;
786
+ /** 旧历史导入的幂等身份(来源路径 + 内容哈希);重复导入据此跳过。 */
787
+ importIdentity?: string;
788
+ size: number;
789
+ mtimeMs: number;
790
+ /** 最后计入的记录 ID;与正文 stat 一同用于增量校验。 */
791
+ revision: string;
792
+ }
793
+ /** 打开的会话句柄:持有单写者锁与 Store,宿主用毕必须 release。 */
794
+ interface ManagedSession {
795
+ conversationId: string;
796
+ store: SessionStore;
797
+ metadataPath: string;
798
+ /** 可丢弃缓存的只读快照;缺失时为 undefined,不代表正文丢失。 */
799
+ readonly metadata?: SessionMetadata;
800
+ header: SessionHeader;
801
+ /** 环境提示,不执行 checkout,也不把旧授权或模型配置带入当前运行。 */
802
+ branchDrift?: {
803
+ createdBranch?: string;
804
+ currentBranch?: string;
805
+ };
806
+ /** 释放单写者锁并移除句柄;宿主须先结束 AgentSession 的工具/摘要清理。 */
807
+ release(): Promise<void>;
808
+ }
809
+ /** SessionManager 配置;cwd 决定项目桶,homeDirectory 便于测试隔离。 */
810
+ interface SessionManagerOptions {
811
+ cwd?: string;
812
+ homeDirectory?: string;
813
+ onDiagnostic?: (message: string) => void;
232
814
  }
233
- declare class AbortError extends KapibalaError {
234
- constructor(message?: string);
815
+ /** 将终端控制字符转成可见转义,并按 Unicode code point 限长。 */
816
+ declare function sanitizeSessionTitle(title: string, maximum?: number): string;
817
+ /** 按项目发现、创建和打开独立会话;缓存可丢弃,JSONL 是唯一恢复依据。 */
818
+ declare class SessionManager {
819
+ readonly project: ProjectIdentity;
820
+ readonly directory: string;
821
+ private readonly handles;
822
+ private readonly diagnostic?;
823
+ constructor(options?: SessionManagerOptions);
824
+ /** 默认新建独立空会话,写入头部并持有单写者锁;不读取其它正文。 */
825
+ create(): Promise<ManagedSession>;
826
+ /** 每页 20 项按正文活动排序;有效 sidecar 只读元数据,不读取完整 JSONL。 */
827
+ list(page?: number): Promise<{
828
+ items: SessionMetadata[];
829
+ total: number;
830
+ page: number;
831
+ pages: number;
832
+ }>;
833
+ /** 一次扫描建立排序目录,分页和继续最近会话共用;有效缓存不读取正文。 */
834
+ private allMetadata;
835
+ /** 打开完整 ID 或唯一前缀;跨桶、缺失与歧义均失败,同一 Manager 已持有的目标直接返回。 */
836
+ open(id: string): Promise<ManagedSession>;
837
+ /** 继续最近有正文的会话;没有历史才新建,显式打开失败绝不回退为空会话。 */
838
+ continueRecent(): Promise<ManagedSession>;
839
+ /** 标题作为独立耐久记录;标题或浏览不改变正文活动排序。 */
840
+ rename(id: string, title: string): Promise<void>;
841
+ /** 等候所有存储队列后释放句柄;宿主必须先结束 AgentSession 的工具/摘要清理。 */
842
+ close(): Promise<void>;
843
+ /**
844
+ * 只发现 cwd 和工作树根的旧文件;来源快照 hash 幂等,完整临时文件 fsync 后独占安装。
845
+ * 保留源文件,安装身份写入头部,缓存丢失或进程退出后仍不会重复导入。
846
+ */
847
+ importLegacy(): Promise<string[]>;
848
+ /** 绑定写后缓存与锁生命周期;正文优先,缓存失败不使保存成功的消息消失。 */
849
+ private attach;
850
+ /** 缓存通过文件名、身份、统计与正文 stat 校验;失败交由正文重建。 */
851
+ private readMetadata;
852
+ /** 浏览仅解析完整记录;严格打开由 SessionStore 验证,浏览不能改写残片。 */
853
+ private readDiscoveryRecords;
854
+ /** 从正文重建元数据,标题和上下文事件不改变内容活动时间。 */
855
+ private buildMetadata;
856
+ /** 只由正文、用户 run 与 reset 更新活动;usage、标题、摘要均不能把浏览对象置顶。 */
857
+ private applyRecord;
858
+ /** 临时 sidecar 完整写入后替换,可重建缓存不承担正文提交职责。 */
859
+ private writeMetadata;
860
+ private metadataPath;
861
+ private lockPath;
862
+ private report;
235
863
  }
236
- declare class FatalError extends KapibalaError {
237
- constructor(message: string);
864
+
865
+ /** 对对象 key 确定性排序,保证摘要、工具 schema 与 fingerprint 不受插入顺序影响。 */
866
+ declare function stableSerialize(value: unknown): string;
867
+
868
+ /** 由生效窗口推导的请求预算;实际请求与只读展示必须共用同一份推导。 */
869
+ interface ContextBudget {
870
+ contextWindow: number;
871
+ /** 窗口来自保守估算(未知按 32K 推导)时为 true。 */
872
+ estimatedWindow: boolean;
873
+ /** 输出预留(含私有推理消耗),同时作为实际请求的 maxTokens。 */
874
+ outputReserve: number;
875
+ /** 至少 128 的窗口安全余量,防止输入预算顶满窗口。 */
876
+ safetyReserve: number;
877
+ /** 输入预算 = 窗口 − 输出预留 − 安全余量;超限请求在 Provider 调用前失败。 */
878
+ inputBudget: number;
879
+ /** 触发阈值 0.85B:超过才启动一级剪裁/二级摘要(迁移文档:剪裁后低于触发阈值则不调用摘要模型)。 */
880
+ trigger: number;
881
+ /**
882
+ * 目标 0.65B:压缩后期望达到的占用水平,随 ContextSnapshot 暴露给 /context 展示。
883
+ * 当前算法的启停条件是 trigger;设计文档未定义向该目标迭代收敛的机制,
884
+ * 故不作为候选接受条件或强制收敛线使用。
885
+ */
886
+ target: number;
887
+ }
888
+ /** 单次请求的 token 占用分解;total 与各部分独立取整,不保证严格相加。 */
889
+ interface TokenEstimate {
890
+ total: number;
891
+ system: number;
892
+ tools: number;
893
+ history: number;
894
+ overhead: number;
895
+ /** calibrated 表示该请求指纹已有实测校准;估算结果仍非计费依据。 */
896
+ source: 'estimated' | 'calibrated';
897
+ }
898
+ /** 可替换估算器;不得执行 Provider、Hook 或改写传入请求。 */
899
+ interface TokenEstimator {
900
+ estimate(request: ModelRequest, modelFingerprint?: string): TokenEstimate;
901
+ observe?(request: ModelRequest, actualPromptTokens: number, modelFingerprint?: string): void;
238
902
  }
239
- declare class SessionBusyError extends KapibalaError {
240
- constructor(operation: string);
903
+ /**
904
+ * 计算一次有效输出预留及输入预算;输出上限须为正安全整数,缺省沿用 4096。
905
+ * 未知窗口以 32K 控制,输出最多占窗口 12.5%,另留至少 128 的 5% 安全余量。
906
+ * 输出预留包含思考/推理;不能把 Profile 的较低覆盖重新放大为默认值。
907
+ * @param window 模型声明的上下文窗口;缺省采用保守估算。
908
+ * @param maxOutputTokens 当前目的的输出上限,包含可见文字及私有推理消耗。
909
+ * @returns 实际请求与上下文展示共用的预算。
910
+ * @throws {ModelError} 输出上限不是正安全整数或窗口过小;错误纳入统一脱敏诊断通道。
911
+ */
912
+ declare function createContextBudget(window?: ContextWindowValue, maxOutputTokens?: number): ContextBudget;
913
+ /** 请求 fingerprint 不包含 AbortSignal 等宿主对象,包含实际指令、schema、正文和输出配置。 */
914
+ declare function requestFingerprint(request: ModelRequest, modelFingerprint?: string): string;
915
+ /**
916
+ * 无依赖 Unicode 分类估算器;非 ASCII 按 code point 保守计数,ASCII 按四字符估算。
917
+ * 观测 usage 仅校准相同最终请求与模型,改变指令或工具会自然失效;未知值不伪造为实测。
918
+ */
919
+ declare class UnicodeTokenEstimator implements TokenEstimator {
920
+ private readonly calibration;
921
+ /** 计算系统、工具、历史和协议开销,返回估算/校准来源,保持请求不变。 */
922
+ estimate(request: ModelRequest, modelFingerprint?: string): TokenEstimate;
923
+ /** 仅接受真实正整数 prompt usage,校准不会降低原保守估算;缓存最多 64 个最终请求。 */
924
+ observe(request: ModelRequest, actualPromptTokens: number, modelFingerprint?: string): void;
241
925
  }
242
926
 
927
+ type CompactionReason = 'threshold' | 'manual' | 'overflow';
928
+ /**
929
+ * 最近一次请求准备或只读检查发布的上下文快照,供宿主展示与诊断。
930
+ * 反映原始历史与实际请求两侧状态;不代表工具执行结果,也不承诺下次压缩行为。
931
+ */
932
+ interface ContextSnapshot {
933
+ conversationId: string;
934
+ modelId: string;
935
+ /** 最终请求指纹;observe 只对匹配指纹的请求回填实测 usage。 */
936
+ fingerprint: string;
937
+ budget: ContextBudget;
938
+ estimate: TokenEstimate;
939
+ /** 最近成功交互及其后全部交互的原始消息 ID;剪裁与摘要不得越过。 */
940
+ protectedMessageIds: string[];
941
+ /** 原始历史条数;与 projectedMessageCount 的差值来自摘要覆盖与压缩投影。 */
942
+ rawMessageCount: number;
943
+ projectedMessageCount: number;
944
+ /** 模型或请求配置变化后为 true,直到下一次准备成功。 */
945
+ stale: boolean;
946
+ /** 匹配指纹请求的实测 usage;缺失表示尚未观测,不按零推断。 */
947
+ actualPromptTokens?: number;
948
+ actualCachedPromptTokens?: number;
949
+ /** false 表示只读静态估算,尚未执行下一请求的动态 Hook。 */
950
+ dynamicKnown: boolean;
951
+ /** 当前检查点摘要消息的估算占用;无检查点为 0。 */
952
+ summaryTokens: number;
953
+ checkpointId?: string;
954
+ /** 累计被替换为占位描述的成功工具结果数。 */
955
+ prunedResults: number;
956
+ /** 已提交(含恢复自持久状态)的摘要检查点次数。 */
957
+ summaryCount: number;
958
+ /** 当前配置纪元内连续摘要失败次数;达到 3 次暂停自动摘要。 */
959
+ consecutiveFailures: number;
960
+ /** 熔断生效标志;阈值触发的压缩被暂停,手动压缩仍可重试。 */
961
+ automaticSummaryPaused: boolean;
962
+ /** disk 有版本化 Store 支撑;memory 只在内存,unsupported 禁用剪裁与摘要。 */
963
+ persistence: 'disk' | 'memory' | 'unsupported';
964
+ }
965
+ /** ContextManager 的宿主注入;除 conversationId 外均可缺省,缺省时按保守方式降级。 */
966
+ interface ContextManagerOptions {
967
+ /** 提供状态能力时启用持久剪裁与摘要;旧 Store 降级为仅内存并给出诊断。 */
968
+ store?: MessageStore;
969
+ estimator?: TokenEstimator;
970
+ conversationId: string;
971
+ /** 存储降级、无效状态记录等非致命事件的脱敏诊断通道。 */
972
+ onDiagnostic?: (message: string) => void;
973
+ /** 摘要角色绑定来源;缺省时跳过二级摘要,仅保留一级剪裁。 */
974
+ router?: ModelRouter;
975
+ /** 转发给文件观察提取;项目根不作为历史工具相对路径的推断依据。 */
976
+ projectRoot?: string;
977
+ /** 当前已注册的内置工具名集合;剪裁白名单只认可其中的内置只读工具。 */
978
+ builtInToolNames?: () => ReadonlySet<string>;
979
+ /** 每个摘要 attempt 的使用量回调;在候选校验前触发,失败摘要仍计消耗。 */
980
+ onSummaryUsage?: (attemptId: string, usage: Usage | undefined, modelId: string) => Promise<void>;
981
+ }
982
+ /** 原始历史与请求视图之间的协调器;不执行工具、Hook 或任何终端操作。 */
983
+ declare class ContextManager {
984
+ private readonly options;
985
+ private readonly estimator;
986
+ private snapshot?;
987
+ private terminals;
988
+ private checkpoint?;
989
+ private pruning;
990
+ private failure;
991
+ private summaryCount;
992
+ private readonly persistence;
993
+ constructor(options: ContextManagerOptions);
994
+ /** 恢复交互终态;有 start 无 finish 的运行保持 interrupted,不根据部分输出伪造成功。 */
995
+ restore(history?: readonly CanonicalMessage[]): Promise<void>;
996
+ /** 输出合法独立视图;原始消息和工具结果绝不被 Hook 共享引用修改。 */
997
+ project(history: readonly CanonicalMessage[]): CanonicalMessage[];
998
+ /** 添加本次交互终态,使下一次准备的保护范围与恢复后的边界一致。 */
999
+ finishInteraction(terminal: InteractionTerminal): void;
1000
+ /**
1001
+ * 最终 Hook 之后统一预算;Profile 与请求的更低覆盖同时约束输出预留和实际 maxTokens。
1002
+ * 非法输出配置或输入超限在 Provider 调用前失败;不使用固定 4096 覆盖原生模型上限。
1003
+ * 签名或加密续答可禁止压缩;此时仍估算并拒绝超预算请求,不剪裁历史或调用摘要网络。
1004
+ * @param allowCompaction 是否允许当前请求剪裁/摘要;冻结私有续答前缀时传 false。
1005
+ * @returns 语义事件及准备完成的请求,不改变持久历史。
1006
+ */
1007
+ prepare(history: readonly CanonicalMessage[], request: ModelRequest, profile: ModelProfile, runId?: string, reason?: CompactionReason, allowCompaction?: boolean): AsyncGenerator<SessionEvent, ModelRequest>;
1008
+ /** 观测真实使用量只作用于对应最终请求,不把累计 usage 当成当前窗口占用。 */
1009
+ observe(request: ModelRequest, usage: Usage, profile: ModelProfile): void;
1010
+ /** 查询已发布快照,不运行 Hook/Provider;配置变化后明确标记 stale。 */
1011
+ getSnapshot(): ContextSnapshot | undefined;
1012
+ /**
1013
+ * 从当前静态投影估算,不执行 Hook/Provider 或更新状态;恢复后即可查看检查点。
1014
+ * 输出预留与准备请求使用同一 Profile/请求覆盖规则;非法覆盖也在只读检查时失败。
1015
+ */
1016
+ inspect(history: readonly CanonicalMessage[], request: ModelRequest, profile: ModelProfile): ContextSnapshot;
1017
+ /** 模型或指令发生变化后使已有预算快照过期,直到下一最终请求准备成功。 */
1018
+ invalidate(): void;
1019
+ /** reset 同时废弃投影与交互终态。 */
1020
+ reset(): void;
1021
+ /** 发布实际准备请求的独立快照,查询不会触发重新压缩。 */
1022
+ private publishSnapshot;
1023
+ /** 最终请求与只读估算共用来源和状态计数。 */
1024
+ private buildSnapshot;
1025
+ /** 摘要以用户历史背景注入,不升级为系统指令或恢复旧授权。 */
1026
+ private summaryMessage;
1027
+ /**
1028
+ * 旧轮次仅在工具事务闭合时可摘要;成功可由旧记录推断,失败或中断必须有运行终态来源。
1029
+ * 该判断不代表执行成功,也不解除最近成功轮次及其后失败尾部的保护。
1030
+ */
1031
+ private isClosedInteraction;
1032
+ /** 严格检查覆盖来源、前驱链、完整终态轮次及保护集合;未知工具结果不能被冒充为成功。 */
1033
+ private validCheckpoint;
1034
+ /** 仅成功完成旧轮次中的白名单内置成功结果可剪裁;失败或中断轮次只参与二级摘要。 */
1035
+ private pruningTargets;
1036
+ /** 用候选描述替换对应结果正文,工具事务、失败标记及全部其它动态内容不变。 */
1037
+ private applyPruningRequest;
1038
+ /** 恢复剪裁必须满足当前来源、策略、前驱与保护范围,摘要覆盖的旧剪裁不会再次使用。 */
1039
+ private validPruning;
1040
+ /** 状态提交失败独立于摘要熔断;内存模式只更新内存,旧 Store 不假称可恢复。 */
1041
+ private commit;
1042
+ private report;
1043
+ }
1044
+
1045
+ /** 摘要模型的 JSON 输出契约;只有通过 validateSummary 的实例可进入检查点。 */
1046
+ interface ContextSummary {
1047
+ schemaVersion: 1;
1048
+ goal: string;
1049
+ constraints: string[];
1050
+ decisions: string[];
1051
+ completedWork: string[];
1052
+ pendingWork: string[];
1053
+ /** 原消息身份,不接受模型虚构来源或把旧摘要当成授权。 */
1054
+ references: string[];
1055
+ /** 结果未知的副作用记录;保留不确定性,不冒充成功或失败。 */
1056
+ unknownEffects: string[];
1057
+ }
1058
+ /** 一次文件操作的历史观察;只描述曾经发生,不描述文件当前状态。 */
1059
+ interface FileObservation {
1060
+ /** 有执行目录证据时为绝对路径;旧记录缺少依据时为原相对路径,基目录未知。 */
1061
+ path: string;
1062
+ sourceMessageId: string;
1063
+ toolCallId: string;
1064
+ operation: string;
1065
+ }
1066
+ /** 检查点携带的文件事实:按结果分类的观察列表,每类上限 500 条。 */
1067
+ interface FileDetails {
1068
+ readFiles: FileObservation[];
1069
+ modifiedFiles: FileObservation[];
1070
+ failedFileOperations: FileObservation[];
1071
+ /** 工具结果缺失或 OUTCOME_UNKNOWN 时的操作记录。 */
1072
+ unknownFileOperations: FileObservation[];
1073
+ /** 超出 500 上限被丢弃的观察总数;渲染时与列表截断数合并展示。 */
1074
+ omitted: number;
1075
+ }
1076
+ /** 对超长结果保留总计 2000 code point 首尾正文,省略说明不冒充原始结果。 */
1077
+ declare function truncateToolOutput(text: string, maximum?: number): string;
1078
+ /**
1079
+ * 从紧邻工具结果确定性提取文件事实;只认内置文件读写,不猜测命令/插件的磁盘变化。
1080
+ * 原始成功、失败和结果未知分别记录,列表表示历史观察,不表示当前文件状态。
1081
+ * 相对路径只按调用记录的执行根目录解析;旧历史缺少目录时保留原相对路径,位置未知。
1082
+ * @param history 原始工具调用及紧邻结果,不执行工具或修改历史。
1083
+ * @param _projectRoot 保留旧 API 参数;项目根不作为历史工具相对路径的推断依据。
1084
+ * @param previous 先前检查点中的文件观察,独立复制后增量合并。
1085
+ * @returns 有界的成功、失败和结果未知文件观察。
1086
+ */
1087
+ declare function extractFileDetails(history: readonly CanonicalMessage[], _projectRoot: string, previous?: FileDetails): FileDetails;
1088
+ /** 有界渲染唯一文件详情,不将模型生成的文本文件列表当作成功写入证据。 */
1089
+ declare function renderFileDetails(details: FileDetails): string;
1090
+ /** 校验结构与来源;空、超长、未知字段及虚构消息引用不能进入检查点。 */
1091
+ declare function validateSummary(value: unknown, sourceIds: ReadonlySet<string>): ContextSummary;
1092
+ /** 摘要服务配置;router 提供摘要角色绑定,全部 attempt 共享总时限。 */
1093
+ interface SummaryServiceOptions {
1094
+ router: ModelRouter;
1095
+ /** 保留旧 API 形参;项目根不作为历史工具相对路径的推断依据。 */
1096
+ projectRoot: string;
1097
+ estimator?: TokenEstimator;
1098
+ /** 真实使用量在候选校验前记账,失败摘要仍保留消耗;不得包含主任务 TTFT。 */
1099
+ onUsage?: (attemptId: string, usage: Usage | undefined, modelId: string) => Promise<void>;
1100
+ /** 单次 generate 的总时限,生效值不超过 120 秒;超时按摘要失败处理。 */
1101
+ timeoutMs?: number;
1102
+ }
1103
+ /** 一次成功摘要的产出与计量;usage 为本次 generate 全部 attempt 的累计值。 */
1104
+ interface SummaryCandidate {
1105
+ summary: ContextSummary;
1106
+ details: FileDetails;
1107
+ /** 实际发起的摘要模型调用次数;上限 4。 */
1108
+ calls: number;
1109
+ modelId: string;
1110
+ durationMs: number;
1111
+ usage: Usage;
1112
+ /** 任一 attempt 缺失 usage 时为 false,不将缺失消耗伪装为零。 */
1113
+ usageKnown: boolean;
1114
+ }
1115
+ /** 摘要单次流式输出文本最大防御倍数;防止模型无限输出耗尽内存。 */
1116
+ declare const SUMMARY_OUTPUT_BUFFER_MULTIPLIER = 16;
1117
+ /** Pi 式滚动摘要服务;无主 Loop/Hook/工具,整次操作最多四调用且总时限 120 秒。 */
1118
+ declare class SummaryService {
1119
+ private readonly options;
1120
+ private readonly estimator;
1121
+ constructor(options: SummaryServiceOptions);
1122
+ /**
1123
+ * 按完整用户交互分批,以旧摘要和新增原始前缀取材;中间结果只是局部候选,不激活。
1124
+ * 单个不可拆分输入超预算、无终态、截断或非法来源均失败,取消先关闭 Provider 迭代。
1125
+ * 摘要输出独立限制为 4096,并受 Profile 更低覆盖及窗口约束;非法 Profile 预算先失败。
1126
+ */
1127
+ generate(history: readonly CanonicalMessage[], previous?: Pick<SummaryCandidate, 'summary' | 'details'>, signal?: AbortSignal): Promise<SummaryCandidate>;
1128
+ }
1129
+
1130
+ /** 事件严重度;debug / trace 仅在 StructuredLogger 显式开启 debug 时写入。 */
243
1131
  type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error';
1132
+ /** 事件通道:operation 为运行日志,audit 为审批与操作审计;两者持久化保证与保留策略不同。 */
244
1133
  type LogChannel = 'operation' | 'audit';
1134
+ /** 允许落盘的字段值类型;复杂结构必须先降维为标量或受控摘要。 */
245
1135
  type LogField = string | number | boolean | null;
246
1136
  /** 单条可持久化的脱敏运行或审计事件。 */
247
1137
  interface LogEvent {
@@ -251,6 +1141,7 @@ interface LogEvent {
251
1141
  channel: LogChannel;
252
1142
  event: string;
253
1143
  sessionId: string;
1144
+ conversationId?: string;
254
1145
  runId?: string;
255
1146
  operationId?: string;
256
1147
  toolUseId?: string;
@@ -260,10 +1151,12 @@ interface LogEvent {
260
1151
  interface LogSink {
261
1152
  write(event: LogEvent): Promise<void>;
262
1153
  }
1154
+ /** 调用方提供的宽松输入;fields 仅白名单字段经脱敏校验后进入 LogEvent。 */
263
1155
  interface LogInput {
264
1156
  level: LogLevel;
265
1157
  event: string;
266
1158
  sessionId: string;
1159
+ conversationId?: string;
267
1160
  runId?: string;
268
1161
  operationId?: string;
269
1162
  toolUseId?: string;
@@ -315,11 +1208,17 @@ declare class StructuredLogger implements EventLogger {
315
1208
  private format;
316
1209
  }
317
1210
 
1211
+ /** FileLogSink 的构造项;保留与落盘策略按通道强制,调用方传值不能放宽。 */
318
1212
  interface FileLogSinkOptions {
1213
+ /** 日志目录;不存在时按 0o700 创建。 */
319
1214
  directory: string;
1215
+ /** 通道前缀,同时决定文件名与保留、同步策略。 */
320
1216
  prefix: 'operation' | 'audit';
1217
+ /** 单文件字节上限,超出后换下一个序号文件;缺省 10MB。 */
321
1218
  maxBytes?: number;
1219
+ /** 按天保留的天数;仅 operation 通道生效,audit 恒为长期保留。 */
322
1220
  retentionDays?: number;
1221
+ /** 每条写入后强制 fsync;audit 通道强制开启。 */
323
1222
  sync?: boolean;
324
1223
  }
325
1224
  /** 将每条 JSONL 事件完整追加到本地文件,并按日期及文件大小轮转。 */
@@ -333,7 +1232,9 @@ declare class FileLogSink implements LogSink {
333
1232
  write(event: LogEvent): Promise<void>;
334
1233
  /** 返回该通道已占用的字节数,供宿主提示长期保留的审计用量。 */
335
1234
  getUsageBytes(): number;
1235
+ /** 优先写入当天未满的最后一个序号文件,超限或无同名文件时开下一个序号。 */
336
1236
  private chooseFile;
1237
+ /** 按文件名中的日期删除早于保留期的自有文件;删除依据文件名而非文件 mtime。 */
337
1238
  private cleanupExpired;
338
1239
  private isOwnedFile;
339
1240
  }
@@ -345,25 +1246,38 @@ declare function createDefaultLogSinks(baseDirectory?: string): {
345
1246
  /** 启动时保守关闭上次进程未完成的审计事务,绝不将其当作未执行或自动重试。 */
346
1247
  declare function recoverIncompleteAudit(directory: string): Promise<number>;
347
1248
 
1249
+ /** 单个通过全部校验的指令文件;path 为去重后的候选路径,content 是严格 UTF-8 解码的全文。 */
348
1250
  interface InstructionSource {
349
1251
  path: string;
350
1252
  content: string;
351
1253
  }
1254
+ /** 一次成功加载的完整结果;sources 按「用户层 → 项目根 → 逐级子目录」顺序排列。 */
352
1255
  interface InstructionSnapshot {
353
1256
  sources: readonly InstructionSource[];
1257
+ /** 全部来源实际字节数之和(以读取结果为准),供调用方审计体积预算。 */
354
1258
  totalBytes: number;
355
1259
  }
356
1260
  interface InstructionLoadOptions {
1261
+ /** 目录链上界;cwd 必须位于其内,越界直接失败而不是静默截断链。 */
357
1262
  projectRoot: string;
1263
+ /** 指令收集的终点目录;相对 projectRoot 的每一层都会尝试读取 AGENTS.md。 */
358
1264
  cwd: string;
1265
+ /** 用户层指令文件;缺省为 ~/.kapibala/AGENTS.md,与项目层同路径时去重。 */
359
1266
  userFile?: string;
360
1267
  }
361
- /** 按用户层和项目根至 cwd 的目录链读取指令,全部成功后才返回快照。 */
1268
+ /**
1269
+ * 按用户层和项目根至 cwd 的目录链读取指令,全部成功后才返回快照。
1270
+ * 所有路径统一用 native 语义解析(与 resolveSessionProject 的 projectRoot 对齐):JS realpath
1271
+ * 不展开 Windows 8.3 短名(CI 临时目录形如 RUNNER~1),混用会让包含性检查把同一目录误判越界、
1272
+ * 让去重错过同一文件;返回的 source 路径因此是 canonical 形式,调用方按 canonical 比较。
1273
+ */
362
1274
  declare function loadInstructions(options: InstructionLoadOptions): InstructionSnapshot;
363
1275
 
1276
+ /** 受支持的解释器家族;wsl 是 Windows 上的 WSL bash launcher,路径与输出语义与 native bash 不同。 */
364
1277
  type ShellKind = 'bash' | 'wsl' | 'pwsh' | 'powershell';
365
1278
  /** auto / 具名解释器,或用户显式提供的解释器可执行文件全路径。 */
366
1279
  type ShellPreference = 'auto' | ShellKind | (string & {});
1280
+ /** 探测成功后固定的解释器身份;executableDigest 参与命令审批指纹,解释器被替换即失配。 */
367
1281
  interface ShellEnvironment {
368
1282
  kind: ShellKind;
369
1283
  executable: string;
@@ -371,8 +1285,11 @@ interface ShellEnvironment {
371
1285
  cwd: string;
372
1286
  }
373
1287
  interface ShellDetectOptions {
1288
+ /** 'auto'、具名解释器,或解释器可执行文件全路径;含路径分隔符或 .exe 后缀按显式路径处理。 */
374
1289
  preference?: ShellPreference;
1290
+ /** 探测与后续执行的基准目录;探测前先取 realpath,符号链接会被展开。 */
375
1291
  cwd: string;
1292
+ /** 以下两项供测试注入平台与 PATH;缺省取当前进程的值。 */
376
1293
  platform?: NodeJS.Platform;
377
1294
  pathEnv?: string;
378
1295
  }
@@ -390,57 +1307,81 @@ declare function detectShell(options: ShellDetectOptions): ShellEnvironment;
390
1307
 
391
1308
  /** 本次会话的自动执行边界;FullAccess 只能由宿主为本次会话显式选择。 */
392
1309
  type SessionMode = 'Approval' | 'Plan' | 'Auto' | 'FullAccess';
1310
+ /** 规则动作与裁决结果共用同一词表;ask 表示交人工审批,不是放行。 */
393
1311
  type PermissionAction = 'allow' | 'ask' | 'deny';
1312
+ /** 一次 Shell 执行的精确目标;字段组合构成审批与缓存命中的身份,任何维度都不允许通配。 */
394
1313
  interface ShellScope {
395
1314
  command: string;
396
1315
  interpreter: string;
397
1316
  executablePath?: string;
398
1317
  cwd: string;
1318
+ /** 解释器身份摘要(路径、大小、mtime 推导);解释器被替换后规则与缓存即失配。 */
399
1319
  executableDigest?: string;
1320
+ /** 命令直接引用的工作目录内脚本的内容摘要;仅单脚本命令可计算,组合命令缺省。 */
400
1321
  scriptDigest?: string;
1322
+ /** 执行前复核用指纹;审批后重新推导不一致时按目标漂移拒绝执行。 */
401
1323
  executionFingerprint?: string;
402
1324
  }
1325
+ /** 宿主提供的显式规则;tool / capability / shell 三种范围必须恰好声明一个。 */
403
1326
  interface PermissionRule {
404
1327
  action: PermissionAction;
405
1328
  tool?: string;
406
1329
  capability?: Capability;
407
1330
  shell?: ShellScope;
408
1331
  }
1332
+ /** 权限裁决的全部输入;硬限制与缓存命中由宿主查询后以标志位传入,策略本身不持有状态。 */
409
1333
  interface PermissionRequest {
410
1334
  mode: SessionMode;
411
1335
  toolName: string;
412
1336
  capabilities: readonly Capability[];
1337
+ /** 危险性来自工具元数据;未命中 allow 规则时,非 FullAccess 模式一律降级为 ask。 */
413
1338
  dangerous?: boolean;
1339
+ /** 宿主硬限制;命中即拒绝,优先级高于一切规则与缓存。 */
414
1340
  hardDenied?: boolean;
415
1341
  shell?: ShellScope;
1342
+ /** 规则表须先经 validatePermissionRules 校验;同动作规则按声明顺序取首个命中。 */
416
1343
  rules?: readonly PermissionRule[];
1344
+ /** 会话缓存命中标志(来自 SessionApprovalCache);仅在 deny / ask 规则都未命中时生效。 */
417
1345
  cachedApproval?: boolean;
1346
+ /** 会话缓存拒绝标志;在 deny 规则之后、ask 规则之前生效。 */
418
1347
  cachedDenial?: boolean;
419
1348
  }
1349
+ /** 裁决结果及其来源;source 供审计区分硬限制、Plan、规则、缓存与模式默认。 */
420
1350
  interface PermissionDecision {
421
1351
  decision: PermissionAction;
422
1352
  source: 'hard_limit' | 'plan' | 'explicit_rule' | 'session_cache' | 'mode_default';
1353
+ /** 命中规则在 rules 中的下标;仅 source 为 explicit_rule 时存在。 */
423
1354
  ruleIndex?: number;
424
1355
  }
425
1356
  /** 拒绝含糊的 Shell 前缀/通配符和结构不完整的规则。 */
426
1357
  declare function validatePermissionRules(rules: readonly PermissionRule[]): void;
427
1358
  /** 纯策略裁决;宿主硬限制和 Plan 始终先于任何规则或会话缓存。 */
428
1359
  declare class PermissionPolicy {
1360
+ /**
1361
+ * 裁决顺序固定:硬限制 → Plan 收窄 → deny 规则 → 会话缓存拒绝 → ask 规则 →
1362
+ * 会话缓存允许 → allow 规则(run_command 必须带 shell 范围,工具级 allow 不能放行命令)
1363
+ * → 模式默认。同一输入总是得到同一裁决,不读取任何外部状态。
1364
+ */
429
1365
  decide(request: PermissionRequest): PermissionDecision;
430
1366
  }
431
1367
  /** 只向模型展示当前模式与整项拒绝规则允许请求的工具。 */
432
1368
  declare function visibleTools(tools: readonly Tool[], mode: SessionMode, rules?: readonly PermissionRule[]): Tool[];
433
1369
 
1370
+ /** 执行能力的最小分类;权限规则、模式裁决与工具元数据声明共用这一词汇表。 */
434
1371
  type Capability = 'fs:read' | 'fs:write' | 'exec' | 'net:outbound' | 'env:read' | 'agent:spawn';
435
1372
  interface ToolMetadata {
1373
+ /** 注册来源标记(如 'builtin');注册表据此执行冲突策略并支持按源注销。 */
436
1374
  source?: string;
1375
+ /** 标记危险工具;未命中 allow 规则时,非 FullAccess 模式一律降级为 ask 而非按模式默认放行。 */
437
1376
  dangerous?: boolean;
438
1377
  /** 所需能力的声明;v0.0.1 不据此授权,v0.0.2 的执行前权限决策才会消费。 */
439
1378
  permissions?: Capability[];
440
1379
  /** 工具自身等待进程资源回收,执行器不可再使用通用 Promise.race 超时。 */
441
1380
  managesTimeout?: boolean;
442
1381
  }
1382
+ /** 工具执行期由宿主注入的运行环境;信号取消后工具应尽快清理在途资源再返回。 */
443
1383
  interface ToolContext {
1384
+ /** 本次执行的沙箱根目录;文件类工具以此为界解析相对路径并拒绝越界。 */
444
1385
  rootDir: string;
445
1386
  signal?: AbortSignal;
446
1387
  logger?: (message: string) => void;
@@ -451,29 +1392,41 @@ interface ToolContext {
451
1392
  outputBytes: number;
452
1393
  }) => void;
453
1394
  }
1395
+ /** 工具契约;parameters 是 JSON Schema,模型只能看到经 toToolDefinition 投影后的三个字段。 */
454
1396
  interface Tool<TInput = Record<string, unknown>, TOutput = unknown> {
455
1397
  readonly name: string;
456
1398
  readonly description: string;
457
1399
  readonly parameters: Record<string, unknown>;
458
1400
  readonly metadata?: ToolMetadata;
1401
+ /** 声明本次输入的精确执行目标,供审批展示与执行前指纹复核;无固定执行目标的工具不实现。 */
459
1402
  approvalScope?(input: TInput, rootDir: string): ShellScope;
460
1403
  execute(input: TInput, ctx: ToolContext): Promise<TOutput>;
461
1404
  }
1405
+ /** 恒等构造器:只为工具实现提供类型推断与统一书写形式,不产生任何运行时包装。 */
462
1406
  declare function defineTool<TInput = Record<string, unknown>, TOutput = unknown>(tool: Tool<TInput, TOutput>): Tool<TInput, TOutput>;
1407
+ /** 投影为模型可见的工具描述;刻意丢弃 metadata 与 approvalScope,执行侧信息不进入协议。 */
463
1408
  declare function toToolDefinition(tool: Tool): ToolDefinition;
464
1409
 
1410
+ /** run_command 的输入;cwd 相对工作区根解析,timeout_ms 合法区间 1..600000,越界在执行前失败。 */
465
1411
  interface RunCommandInput {
466
1412
  [key: string]: unknown;
467
1413
  command: string;
468
1414
  cwd?: string;
469
1415
  timeout_ms?: number;
470
1416
  }
1417
+ /** 命令执行结果;output 只是内联前缀,完整输出超过内联上限的部分落盘为受管结果文件。 */
471
1418
  interface CommandResult {
1419
+ /** 进程正常退出时的退出码;被信号终止时为 null。 */
472
1420
  exitCode: number | null;
1421
+ /** stdout 与 stderr 交错合并的文本,最多前 64 KiB(按 UTF-8 字符边界截断)。 */
473
1422
  output: string;
1423
+ /** output 并非全部输出的标志;超出内联上限的完整内容写入 outputFile。 */
474
1424
  outputTruncated: boolean;
1425
+ /** 受管结果文件路径(工作区内 .kapibala/tool-results/),仅输出超过内联上限时存在。 */
475
1426
  outputFile?: string;
1427
+ /** 结果文件触及 16 MiB 上限后被截断的标志。 */
476
1428
  outputFileTruncated: boolean;
1429
+ /** 两个流产生的原始字节总数(不受截断影响),供进度与审计使用。 */
477
1430
  outputBytes: number;
478
1431
  shell: ShellEnvironment['kind'];
479
1432
  }
@@ -482,6 +1435,7 @@ declare function cleanupCommandResults(rootDir: string, now?: number): void;
482
1435
  /** 使用固定解释器执行命令;超时和中止必须先处理进程树再返回。 */
483
1436
  declare function createRunCommandTool(environment: ShellEnvironment): Tool<RunCommandInput, CommandResult>;
484
1437
 
1438
+ /** 路径沙箱配置;rootDir 是所有文件访问的词法与物理边界。 */
485
1439
  interface SandboxConfig {
486
1440
  rootDir: string;
487
1441
  /**
@@ -490,6 +1444,10 @@ interface SandboxConfig {
490
1444
  */
491
1445
  allowSymlinks?: boolean;
492
1446
  }
1447
+ /**
1448
+ * 把文件访问限制在 rootDir 内:先做词法归一化检查,再展开符号链接做物理检查,两层都通过才放行。
1449
+ * 实例会缓存 rootDir 的物理路径,应按 rootDir 复用实例,而不是每次调用新建。
1450
+ */
493
1451
  declare class PathSandbox {
494
1452
  readonly rootDir: string;
495
1453
  readonly allowSymlinks: boolean;
@@ -519,6 +1477,11 @@ declare class PathSandbox {
519
1477
  private toPhysicalPath;
520
1478
  }
521
1479
 
1480
+ /**
1481
+ * 人工审批的五选一结果。allow_once / deny_once 只作用于本次执行;
1482
+ * allow_session / deny_session 由执行器按精确调用范围写入会话缓存(allow_session 还要求请求允许会话级缓存);
1483
+ * cancel 表示放弃审批,一律拒绝且绝不进入缓存。
1484
+ */
522
1485
  type ApprovalChoice = 'allow_once' | 'allow_session' | 'deny_once' | 'deny_session' | 'cancel';
523
1486
  /** 宿主展示实际执行目标并取得人工选择;无通道视为非交互拒绝。 */
524
1487
  interface ApprovalRequest {
@@ -527,8 +1490,10 @@ interface ApprovalRequest {
527
1490
  input: Record<string, unknown>;
528
1491
  rootDir: string;
529
1492
  shell?: ShellScope;
1493
+ /** 宿主是否允许本次请求写入会话级允许缓存;deny_session 的缓存不受此限制。 */
530
1494
  sessionAllowed: boolean;
531
1495
  }
1496
+ /** 宿主实现的审批入口;未提供通道时执行器按非交互直接拒绝,通道抛错视同 cancel。 */
532
1497
  interface ApprovalChannel {
533
1498
  requestApproval(request: ApprovalRequest, signal?: AbortSignal): Promise<ApprovalChoice>;
534
1499
  }
@@ -542,7 +1507,12 @@ declare class SessionApprovalCache {
542
1507
  set(request: ApprovalRequest, choice: 'allow' | 'deny'): void;
543
1508
  }
544
1509
 
1510
+ /** 同名工具冲突策略:error 直接抛错;prefer-builtin 保留既有内置注册;prefer-last 后到者覆盖。 */
545
1511
  type ConflictPolicy = 'error' | 'prefer-builtin' | 'prefer-last';
1512
+ /**
1513
+ * 按名称索引的工具注册表。冲突按构造时给定的策略处理,胜出条目的来源标签保持不变;
1514
+ * 来源标签支持按源批量注册与注销,注销只移除以该标签注册的工具,不回收冲突中保留的内置实现。
1515
+ */
546
1516
  declare class ToolRegistry {
547
1517
  private readonly tools;
548
1518
  private readonly toolSources;
@@ -556,6 +1526,7 @@ declare class ToolRegistry {
556
1526
  registerSource(source: string, tools: Tool[]): void;
557
1527
  unregisterSource(source: string): void;
558
1528
  get(name: string): Tool | undefined;
1529
+ /** 未命中时抛 ToolNotFound,并携带当前全部可用名称辅助模型自纠。 */
559
1530
  resolve(name: string): Tool;
560
1531
  list(): Tool[];
561
1532
  definitions(): ToolDefinition[];
@@ -583,6 +1554,7 @@ declare const grepTool: Tool<{
583
1554
  pattern: string;
584
1555
  path?: string;
585
1556
  }, string>;
1557
+ /** 五个内置文件工具的聚合;全部经 PathSandbox 校验,路径越界或符号链接穿透一律拒绝。 */
586
1558
  declare const builtinTools: (Tool<{
587
1559
  path: string;
588
1560
  startLine?: number;
@@ -602,11 +1574,22 @@ declare const builtinTools: (Tool<{
602
1574
  path?: string;
603
1575
  }, string>)[];
604
1576
 
1577
+ /**
1578
+ * 运行时钩子契约:宿主与插件在固定切点观察或调整流程。
1579
+ * 通知型切点由 HookRegistry.emit 串行触发;需要返回值的 model:before / tool:before
1580
+ * 由执行方(AgentLoop / ToolExecutor)自行遍历并消费返回值。
1581
+ */
1582
+ /** 钩子切点;session:start / session:end 由会话初始化与销毁触发,其余在单次交互流程内触发。 */
605
1583
  type HookPoint = 'session:start' | 'session:end' | 'model:before' | 'model:after' | 'tool:before' | 'tool:after' | 'error';
1584
+ /** 传给每个钩子的运行上下文;signal 与当前执行的取消联动,未提供表示该切点不可取消。 */
606
1585
  interface HookContext {
607
1586
  readonly signal?: AbortSignal;
608
1587
  readonly logger?: (msg: string) => void;
609
1588
  }
1589
+ /**
1590
+ * tool:before 的裁决结果:continue 放行;skip 不执行工具,以 result 作为工具结果落盘;
1591
+ * modify 用替换后的入参继续(仍会经过后续权限裁决,不构成绕过审批的通道)。
1592
+ */
610
1593
  type ToolDecision = {
611
1594
  action: 'continue';
612
1595
  } | {
@@ -617,10 +1600,12 @@ type ToolDecision = {
617
1600
  action: 'modify';
618
1601
  input: Record<string, unknown>;
619
1602
  };
1603
+ /** 各切点的处理器签名;未注册的切点直接跳过,处理器抛出的异常向上传播。 */
620
1604
  interface HookHandlers {
621
1605
  'session:start'?: (ctx: HookContext) => void | Promise<void>;
622
1606
  'session:end'?: (ctx: HookContext) => void | Promise<void>;
623
1607
  'model:before'?: (ctx: HookContext, req: ModelRequest) => ModelRequest | Promise<ModelRequest>;
1608
+ /** 收到的是即将进入历史的完整 assistant 消息;执行方会校验钩子未改动身份与受保护内容。 */
624
1609
  'model:after'?: (ctx: HookContext, res: {
625
1610
  message: CanonicalMessage;
626
1611
  }) => void | Promise<void>;
@@ -640,30 +1625,44 @@ interface HookHandlers {
640
1625
  error?: (ctx: HookContext, err: Error) => void | Promise<void>;
641
1626
  }
642
1627
 
1628
+ /** 按切点收集钩子的有序注册表;同一处理器可注册多次,触发时按注册顺序执行。 */
643
1629
  declare class HookRegistry {
644
1630
  private readonly hooks;
1631
+ /** 注册到指定切点;不查重,触发顺序即注册顺序。 */
645
1632
  on<K extends HookPoint>(point: K, handler: NonNullable<HookHandlers[K]>): void;
1633
+ /** 返回该切点的处理器列表(无注册时为空数组);数组为内部引用,调用方不应修改。 */
646
1634
  get<K extends HookPoint>(point: K): Array<NonNullable<HookHandlers[K]>>;
1635
+ /**
1636
+ * 串行 await 通知型切点的全部处理器;任一抛错立即中断并向调用方传播。
1637
+ * 需要返回值的 model:before / tool:before 不经 emit,由执行方自行遍历。
1638
+ */
647
1639
  emit<K extends 'session:start' | 'session:end' | 'model:after' | 'tool:after' | 'error'>(point: K, ctx: HookContext, ...args: any[]): Promise<void>;
648
1640
  }
649
1641
 
1642
+ /** setup 收到的能力入口;tools / hooks 是会话共享的注册表,注册的条目影响后续所有执行。 */
650
1643
  interface PluginContext {
651
1644
  readonly tools: ToolRegistry;
652
1645
  readonly hooks: HookRegistry;
1646
+ /** 本次会话的绝对工具根目录;工具的路径解析与审批都以此为基准。 */
653
1647
  readonly rootDir: string;
654
1648
  readonly logger?: (msg: string) => void;
655
1649
  }
1650
+ /** 插件生命周期:setup 在会话空闲时挂载执行一次,teardown 在会话销毁时逐个调用以回收资源。 */
656
1651
  interface AgentPlugin {
1652
+ /** 用于挂载失败与 teardown 的诊断信息。 */
657
1653
  readonly name: string;
658
1654
  readonly version?: string;
659
1655
  setup(ctx: PluginContext): void | Promise<void>;
660
1656
  teardown?(): void | Promise<void>;
661
1657
  }
662
1658
 
1659
+ /** ToolExecutor 的构造项;审计写入需要 eventLogger 与 sessionId 同时提供,否则不产生审计。 */
663
1660
  interface ExecutorOptions {
664
1661
  tools: ToolRegistry;
665
1662
  hooks: HookRegistry;
1663
+ /** 工具执行的绝对根目录;路径解析与审批均以此为基准。 */
666
1664
  rootDir: string;
1665
+ /** 会话级取消信号;与 cancel() 的内部信号合并生效。 */
667
1666
  signal?: AbortSignal;
668
1667
  logger?: (msg: string) => void;
669
1668
  /** 单次工具执行超时(毫秒)。异步挂起的工具超时后返回 isError 结果,避免永久卡死会话循环 */
@@ -671,11 +1670,19 @@ interface ExecutorOptions {
671
1670
  eventLogger?: EventLogger;
672
1671
  sessionId?: string;
673
1672
  runId?: string;
1673
+ /** 固定模式或每次裁决时读取的取值函数;宿主可中途切换。 */
674
1674
  mode?: SessionMode | (() => SessionMode);
675
1675
  permissionRules?: readonly PermissionRule[];
1676
+ /** 审批入口;缺省视为非交互环境,需要询问的调用一律拒绝。 */
676
1677
  approvalChannel?: ApprovalChannel;
1678
+ /** 会话内 allow_session / deny_session 审批缓存;缺省使用实例私有缓存。 */
677
1679
  approvalCache?: SessionApprovalCache;
678
1680
  }
1681
+ /**
1682
+ * 工具执行器:按「审计 → 钩子裁决 → 权限裁决 → 执行 → 结果闭合」处理单次调用。
1683
+ * 所有拒绝与异常都闭合为 isError 的工具结果,不向调用方抛出;
1684
+ * 同一 run 内参数完全相同的 never 失败会被拒绝重复执行。
1685
+ */
679
1686
  declare class ToolExecutor {
680
1687
  private readonly tools;
681
1688
  private readonly hooks;
@@ -696,13 +1703,17 @@ declare class ToolExecutor {
696
1703
  constructor(options: ExecutorOptions);
697
1704
  /** 中止本轮正在等待或执行的工具;调用方仍须等待 runAll 完成资源回收及结果审计。 */
698
1705
  cancel(): void;
1706
+ /** 串行执行全部调用并返回与入参顺序一致的结果;某个结果要求用户介入后,其余调用直接拒绝。 */
699
1707
  runAll(calls: ToolUseBlock[], onProgress?: (event: {
700
1708
  id: string;
701
1709
  name: string;
702
1710
  elapsedMs: number;
703
1711
  outputBytes: number;
704
1712
  }) => void): Promise<ToolResultBlock[]>;
705
- /** 在最终参数上裁决并审计一次调用,所有拒绝和异常均闭合为工具结果。 */
1713
+ /**
1714
+ * 在最终参数上裁决并审计一次调用,所有拒绝和异常均闭合为工具结果。
1715
+ * 为调用记录本次绝对工具根目录,供跨目录恢复后的文件事实解析;不使用历史目录授权。
1716
+ */
706
1717
  executeOne(call: ToolUseBlock, onProgress?: (event: {
707
1718
  id: string;
708
1719
  name: string;
@@ -720,104 +1731,158 @@ declare class ToolExecutor {
720
1731
  private withTimeout;
721
1732
  }
722
1733
 
723
- type ModelRole = 'default' | 'planning' | 'execution' | 'summary' | 'fast';
724
- type ContextWindowValue = number | `${number}${'K' | 'k' | 'M' | 'm'}`;
725
- interface ResolvedContextWindow {
726
- tokens: number;
727
- /** true 表示模型未声明窗口,当前值来自 Kapibala 的默认估算。 */
728
- estimated: boolean;
729
- }
730
- declare const DEFAULT_CONTEXT_WINDOW_TOKENS = 1000000;
731
- /**
732
- * 将模型上下文窗口统一解析为整数 Token 数。
733
- *
734
- * 配置允许直接填写整数,或使用十进制 K/M 简写;未填写时返回默认 1M,并标记为估算值。
735
- */
736
- declare function resolveContextWindow(value?: ContextWindowValue): ResolvedContextWindow;
737
- interface ModelProfile {
738
- id: string;
739
- name: string;
740
- provider: 'openai-compatible';
741
- baseURL: string;
742
- apiKeyEnv: string;
743
- apiKey?: string;
744
- modelName: string;
745
- contextWindow?: ContextWindowValue;
746
- supportsThinking?: boolean;
747
- }
748
- interface ModelRouter {
749
- resolve(role?: ModelRole): ModelProvider;
750
- getProfile(role?: ModelRole): ModelProfile;
751
- }
752
- declare class SimpleModelRouter implements ModelRouter {
753
- private readonly providers;
754
- private readonly profiles;
755
- private defaultRole;
756
- constructor(defaultProfile: ModelProfile, defaultProvider: ModelProvider);
757
- setRole(role: ModelRole, profile: ModelProfile, provider: ModelProvider): void;
758
- resolve(role?: ModelRole): ModelProvider;
759
- getProfile(role?: ModelRole): ModelProfile;
760
- }
761
-
762
- interface ModelProvider {
763
- readonly name: string;
764
- create(req: ModelRequest): AsyncIterable<ModelEvent>;
765
- /** 把一批工具结果装配成符合本协议的 canonical 消息序列 */
766
- assembleToolResults(results: ToolResultBlock[]): CanonicalMessage[];
767
- }
768
-
1734
+ /** Chat 端点配置;能力覆盖只改变请求字段和完成边界,不改变协议身份。 */
769
1735
  interface OpenAIProviderOptions {
770
1736
  baseURL: string;
771
1737
  apiKey: string;
772
1738
  modelName: string;
773
1739
  supportsThinking?: boolean;
1740
+ /** 回传 assistant 思考历史;默认仅为 DeepSeek 官方端点启用,自建兼容网关可显式开启。 */
1741
+ replayReasoningContent?: boolean;
1742
+ /** 显式端点能力;缺省保留 max_tokens、usage 和 temperature 请求基线,要求 DONE。 */
1743
+ chatCapabilities?: ChatCapabilities;
774
1744
  /** 建立 HTTP 连接(收到响应头)的超时毫秒数;仅约束建连阶段,不限制流式读取总时长 */
775
1745
  connectTimeoutMs?: number;
776
1746
  }
1747
+ /** 将 canonical 历史投影为 Chat 请求,在完整终态和全部工具验证后交付可执行结果。 */
777
1748
  declare class OpenAICompatibleProvider implements ModelProvider {
778
1749
  readonly name = "openai-compatible";
779
1750
  readonly baseURL: string;
780
1751
  readonly apiKey: string;
1752
+ /** 未提供凭据时由 Session 在记录用户消息前拒绝请求。 */
1753
+ get credentialsReady(): boolean;
781
1754
  readonly modelName: string;
782
1755
  readonly supportsThinking: boolean;
1756
+ readonly replayReasoningContent: boolean;
783
1757
  readonly connectTimeoutMs: number;
1758
+ readonly chatCapabilities: Readonly<ChatCapabilities>;
1759
+ /** 暴露实际请求目标供原子绑定校验,不包含凭据。 */
1760
+ get binding(): {
1761
+ protocol: "openai-compatible";
1762
+ baseURL: string;
1763
+ modelName: string;
1764
+ };
1765
+ /**
1766
+ * 初始化 Chat 协议适配;显式端点能力优先,思考回传独立于模型 supportsThinking 标签。
1767
+ * @param options 请求目标、凭据和能力配置;缺省只有 DeepSeek 官方端点回传可见思考。
1768
+ */
784
1769
  constructor(options: OpenAIProviderOptions);
1770
+ /**
1771
+ * 发送 Chat 流式请求;默认同时要求合法 finish_reason 和 DONE,只有显式例外允许完整 EOF。
1772
+ * 全部工具的 ID、名称和对象参数在任何完成事件之前校验;截断、过滤或中断不交付工具。
1773
+ * @param req canonical 历史、工具、预算与取消信号;能力覆盖来自端点配置。
1774
+ * @returns 文本、可见思考和工具增量,完整响应最后产生 message_stop。
1775
+ * @throws ModelError 响应缺少合法终态、工具身份或完整对象参数时失败,不自动重放请求。
1776
+ */
785
1777
  create(req: ModelRequest): AsyncIterable<ModelEvent>;
1778
+ /**
1779
+ * 将工具结果装配为 canonical tool 消息,wire 角色仅在下一请求投影时转换。
1780
+ * @param results 已完成的工具结果,保持调用 ID 与内容,不重放工具。
1781
+ * @returns 逐条克隆的 canonical tool 消息,允许消息级落盘。
1782
+ */
786
1783
  assembleToolResults(results: ToolResultBlock[]): CanonicalMessage[];
1784
+ /**
1785
+ * 将历史投影为 Chat 消息;合并连续 user,剔除空 assistant,保持工具调用与结果身份。
1786
+ * 仅显式允许的端点回传可见思考;签名、脱敏思考和原生私有 Item 不适用于 Chat。
1787
+ * @param messages canonical 历史;只投影文本、可选可见思考和工具语义。
1788
+ * @param systemPrompt 可选全局提示词,去除首尾空白后作为首条 system。
1789
+ * @returns 与输入历史独立的 Chat wire 消息数组。
1790
+ */
787
1791
  private translateMessagesToWire;
788
1792
  }
789
1793
 
790
- declare class JSONLMessageStore implements MessageStore {
791
- readonly filePath: string;
792
- constructor(filePath: string);
793
- append(message: CanonicalMessage): Promise<void>;
794
- load(): Promise<CanonicalMessage[]>;
795
- clear(): Promise<void>;
1794
+ /** Messages 原生连接配置;baseURL 包含版本前缀,workspaceId 仅选择请求工作区。 */
1795
+ interface AnthropicProviderOptions {
1796
+ baseURL: string;
1797
+ apiKey: string;
1798
+ modelName: string;
1799
+ connectTimeoutMs?: number;
1800
+ workspaceId?: string;
1801
+ }
1802
+ /** 独立 Messages 适配器;复用 canonical 工具事务及来源校验,不拥有工具执行权限。 */
1803
+ declare class AnthropicProvider implements ModelProvider {
1804
+ readonly name = "anthropic";
1805
+ readonly baseURL: string;
1806
+ readonly modelName: string;
1807
+ readonly workspaceId?: string;
1808
+ readonly connectTimeoutMs: number;
1809
+ private readonly apiKey;
1810
+ /** 表明该适配器已装载非空凭据,不暴露凭据内容。 */
1811
+ get credentialsReady(): boolean;
1812
+ /** 暴露不含凭据的请求目标;用于宿主校验 Profile 与 Provider 的原子绑定。 */
1813
+ get binding(): {
1814
+ protocol: "anthropic";
1815
+ baseURL: string;
1816
+ modelName: string;
1817
+ workspaceId: string | undefined;
1818
+ };
1819
+ /** 初始化连接;无效 URL/凭据/超时在请求前失败,错误不回显配置值。 */
1820
+ constructor(options: AnthropicProviderOptions);
1821
+ /** 装配统一 tool 历史;Messages 的 user/tool_result 转换只作用于请求视图。 */
1822
+ assembleToolResults(results: ToolResultBlock[]): CanonicalMessage[];
796
1823
  /**
797
- * 历史自愈(设计文档 §4.4):逐条扫描 assistant 的 tool_use,
798
- * 若其后的 tool 消息未完整覆盖这些 tool_use,就地补一条 is_error 的 tool_result。
799
- *
800
- * 之所以做**全历史扫描**而非只看末条:崩溃可能发生在任意一轮工具执行中途,
801
- * 悬挂的 tool_use 未必位于历史末尾(例如中断后用户又继续提了问)。
802
- * 只看末条会漏掉夹在中间的悬挂,下一次请求仍会因上下文非法而 400。
1824
+ * 发送 Messages 流并按索引组装完整内容;增量仅供展示,终态提供有序落盘来源。
1825
+ * maxTokens 包含思考消耗,缺省为 4096;缺终态、坏参数与服务端流错误均抛错。
1826
+ * pause_turn 表示服务端工具暂停;当前不支持其续答,明确失败而非报告完成或调度客户端工具。
1827
+ * 同 run/模型/端点的来源校验允许私有续答;来源不匹配的可见思考降为普通文字。
1828
+ * 取消或消费者提前结束会等待 reader 清理并解除 HTTP 取消监听,不自动重发请求。
803
1829
  */
804
- private healDanglingToolCalls;
1830
+ create(req: ModelRequest): AsyncIterable<ModelEvent>;
1831
+ /**
1832
+ * 投影 system、普通内容与工具结果;连续结果合并为下一 user 内容并置于文字之前。
1833
+ * 私有块由共享来源规则筛选,原始消息和工具 ID 不被改写;不发送能力标签推测的思考参数。
1834
+ */
1835
+ private createPayload;
805
1836
  }
806
1837
 
807
- interface MessageStore {
808
- append(message: CanonicalMessage): Promise<void>;
809
- load(): Promise<CanonicalMessage[]>;
810
- clear(): Promise<void>;
1838
+ /** 原生 Responses 的端点、模型及建连配置;输出预算由每次请求指定。 */
1839
+ interface OpenAIResponsesProviderOptions {
1840
+ baseURL: string;
1841
+ apiKey: string;
1842
+ modelName: string;
1843
+ supportsThinking?: boolean;
1844
+ connectTimeoutMs?: number;
1845
+ }
1846
+ /** 原生 Responses 适配器拥有手动无状态历史,完成边界与 Agent 的 canonical 工具事务一致。 */
1847
+ declare class OpenAIResponsesProvider implements ModelProvider {
1848
+ readonly name = "openai-responses";
1849
+ readonly binding: {
1850
+ protocol: 'openai-responses';
1851
+ modelName: string;
1852
+ baseURL: string;
1853
+ };
1854
+ private readonly options;
1855
+ /** 表明该适配器已装载非空凭据,不暴露凭据内容。 */
1856
+ get credentialsReady(): boolean;
1857
+ /** 绑定明确模型与端点;不从模型名推断协议,也不在失败后自动切换协议。非法配置在请求前失败。 */
1858
+ constructor(options: OpenAIResponsesProviderOptions);
1859
+ /** 消费完整 Responses 流,增量仅用于展示;终态与全部 Item 合法后才交付工具完成和最终内容。 */
1860
+ create(request: ModelRequest): AsyncIterable<ModelEvent>;
1861
+ /** 保持消息级 canonical tool 落盘,Responses function_call_output 仅存在于请求投影。 */
1862
+ assembleToolResults(results: ToolResultBlock[]): CanonicalMessage[];
1863
+ /** 服务端错误仅保留明确标识,不回显请求、输出正文、签名或加密 reasoning。 */
1864
+ private throwWireError;
1865
+ /** 只接受真实且合法的计数;缺失 usage 保持未知,推理 token 已包含在 output_tokens 中。 */
1866
+ private toUsage;
811
1867
  }
812
1868
 
813
1869
  interface PromptAssemblerOptions {
1870
+ /** 提供时才生成 L2 工具清单段;缺省表示本次运行不向模型展示任何工具。 */
814
1871
  tools?: ToolRegistry;
1872
+ /** L3 环境段展示的工作区根目录;文件工具的沙箱边界与其保持一致。 */
815
1873
  rootDir: string;
816
1874
  agentName?: string;
1875
+ /** 宿主自定义提示词,插在环境段与 L4 指令之间;纯空白视为未提供。 */
817
1876
  customInstructions?: string;
1877
+ /** L4 项目指令段的内容,来自 loadInstructions 快照;为空时整段省略。 */
818
1878
  instructionSources?: readonly InstructionSource[];
1879
+ /** 覆盖 tools.list() 作为 L2 清单来源;通常传入按权限过滤后的可见工具。 */
819
1880
  visibleTools?: readonly Tool[];
820
1881
  }
1882
+ /**
1883
+ * 把行为规则(L1)、工具清单(L2)、环境(L3)与项目指令(L4)拼装为系统提示词。
1884
+ * 各段之间以 `\n\n---\n\n` 分隔;不提供的内容整段跳过,不做占位填充。
1885
+ */
821
1886
  declare class PromptAssembler {
822
1887
  private readonly tools?;
823
1888
  private readonly rootDir;
@@ -826,6 +1891,7 @@ declare class PromptAssembler {
826
1891
  private readonly instructionSources;
827
1892
  private readonly visibleTools?;
828
1893
  constructor(options: PromptAssemblerOptions);
1894
+ /** 按固定层级拼装系统提示词;同一选项集总是产出相同文本,便于审计与缓存。 */
829
1895
  assemble(): string;
830
1896
  private getL1Behavior;
831
1897
  private getL2Tools;
@@ -833,21 +1899,46 @@ declare class PromptAssembler {
833
1899
  }
834
1900
 
835
1901
  interface AgentLoopOptions {
1902
+ /** 本次交互身份,内部步骤仍独立编号。 */
1903
+ interactionId?: string;
1904
+ /** 仅用于诊断、用量归因与脱敏说明,不参与请求构造。 */
1905
+ modelId?: string;
1906
+ modelRole?: PrimaryModelRole;
1907
+ /** 请求视图投影:只允许变换克隆出的请求消息,不得改动真实历史。 */
1908
+ projectHistory?: (history: readonly CanonicalMessage[]) => CanonicalMessage[];
1909
+ /** 请求准备契约;可在请求前产出事件,并在上下文溢出时参与一次预算重试。 */
1910
+ prepareRequest?: RequestPreparation;
1911
+ /** 每次收到 usage 后回调;attemptId 标识 run:step:attempt,便于按尝试归因。 */
1912
+ onUsage?: (request: ModelRequest, usage: Usage, attemptId: string) => Promise<void>;
836
1913
  provider: ModelProvider;
837
1914
  executor: ToolExecutor;
838
1915
  tools: ToolRegistry;
839
1916
  hooks: HookRegistry;
840
1917
  systemPrompt?: string;
1918
+ /** 单次 run 的最大 turn 数,耗尽时以 error 事件收尾;缺省 20。 */
841
1919
  maxSteps?: number;
1920
+ /** 连续工具失败达到该阈值即熔断终止本轮 run;缺省 3。 */
842
1921
  maxConsecutiveErrors?: number;
843
1922
  signal?: AbortSignal;
844
1923
  eventLogger?: EventLogger;
845
1924
  sessionId?: string;
846
1925
  runId?: string;
1926
+ /** 每轮开始时读取;工具可见性与权限模式可随宿主状态变化。 */
847
1927
  getMode?: () => SessionMode;
848
1928
  permissionRules?: readonly PermissionRule[];
849
1929
  }
1930
+ /**
1931
+ * 主执行循环:按 turn 推进「模型请求 → 整批校验 → 工具调度 → 历史闭合」。
1932
+ * run 会就地追加传入的 history,assistant 与全部 tool_result 在同一同步临界段落入,
1933
+ * 消费方在任何对外事件后停止迭代都不会看到半闭合历史(设计文档 §4.3 / §4.4)。
1934
+ */
850
1935
  declare class AgentLoop {
1936
+ private readonly interactionId?;
1937
+ private readonly modelId?;
1938
+ private readonly modelRole?;
1939
+ private readonly projectHistory?;
1940
+ private readonly prepareRequest?;
1941
+ private readonly onUsage?;
851
1942
  private readonly provider;
852
1943
  private readonly executor;
853
1944
  private readonly tools;
@@ -862,39 +1953,86 @@ declare class AgentLoop {
862
1953
  private readonly getMode;
863
1954
  private readonly permissionRules;
864
1955
  constructor(options: AgentLoopOptions);
1956
+ /**
1957
+ * 执行一次交互并流式产出事件。
1958
+ *
1959
+ * 语义要点:
1960
+ * - message_stop 携带完整 canonical 消息,是唯一落盘来源;text / thinking 增量仅供展示。
1961
+ * - 模型失败以 error + turn_finish 事件收尾并结束 run(不抛出);用户中止抛 AbortError。
1962
+ * - turn_start / turn_finish 严格配对,错误、熔断与步数耗尽路径均保证收口。
1963
+ */
865
1964
  run(history: CanonicalMessage[]): AsyncIterable<SessionEvent>;
866
1965
  }
867
1966
 
1967
+ /** AgentSession 的构造配置;除主任务绑定外均可缺省,缺省行为见各字段。 */
868
1968
  interface SessionConfig {
1969
+ /** 持久会话身份;有版本化 Store 时须与头部一致,日志实例身份保持独立。 */
1970
+ conversationId?: string;
1971
+ tokenEstimator?: TokenEstimator;
1972
+ /** 无 Git 工作树时随 run_started 记录的分支回退值。 */
1973
+ gitBranch?: string;
1974
+ /** 主任务默认模型绑定;恢复历史及未显式选择角色时使用。 */
869
1975
  defaultProfile: ModelProfile;
1976
+ /** 与 defaultProfile 匹配的协议适配器。 */
870
1977
  defaultProvider: ModelProvider;
1978
+ /** 消息级落盘通道;支持状态能力的 Store 额外启用持久压缩与交互终态。 */
871
1979
  store?: MessageStore;
1980
+ /** 工具执行与会话基目录;projectRoot/cwd 缺省沿用此值。 */
872
1981
  rootDir?: string;
873
1982
  systemPrompt?: string;
874
1983
  maxSteps?: number;
875
1984
  logger?: (msg: string) => void;
876
1985
  eventLogger?: EventLogger;
877
1986
  loggingDirectory?: string;
1987
+ /** 初始权限模式,缺省 Approval;仅空闲时可切换。 */
878
1988
  mode?: SessionMode;
879
1989
  permissionRules?: readonly PermissionRule[];
880
1990
  approvalChannel?: ApprovalChannel;
881
1991
  projectRoot?: string;
882
1992
  cwd?: string;
883
1993
  userInstructionsPath?: string;
1994
+ /** 未提供时使用默认日志 sink 的审计目录;init 时恢复不完整审计。 */
884
1995
  auditRecoveryDirectory?: string;
885
1996
  /** 接收普通运行日志失败的脱敏诊断;诊断失败也不得中断问答或替代审计。 */
886
1997
  onDiagnostic?: (message: string) => void;
887
1998
  }
1999
+ /** getStats 返回的统计快照;全部字段为独立副本,宿主修改不影响会话内部状态。 */
888
2000
  interface SessionStats {
2001
+ conversationId?: string;
2002
+ /** 历史存在无 usage 的模型步骤时为 false,不将旧消耗伪装为精确零。 */
2003
+ usageKnown?: boolean;
2004
+ /** 摘要 attempt 的累计消耗;独立于主任务指标。 */
2005
+ summaryUsage?: Usage;
2006
+ summaryUsageKnown?: boolean;
2007
+ contextSnapshot?: ContextSnapshot;
2008
+ /** 累计用户任务次数,含恢复自持久状态的 run_started 记录。 */
889
2009
  totalTurns: number;
2010
+ /** 主任务累计消耗;摘要消耗在 summaryUsage 单独统计。 */
890
2011
  totalTokens: Usage;
891
2012
  activeModel: string;
892
2013
  loadedToolsCount: number;
893
2014
  lastMetrics?: TurnMetrics;
894
2015
  lastRunMetrics?: RunMetrics;
2016
+ /** 最近一次内部模型请求的窗口占用;无实测时仅提供窗口上限。 */
895
2017
  contextUsage: ContextUsage;
896
2018
  }
2019
+ /**
2020
+ * 宿主无关的 Agent 会话门面:统一模型路由、工具执行、权限与上下文压缩。
2021
+ * 每次用户输入产生一个 run;历史与状态经 MessageStore 持久化,恢复后语义连续。
2022
+ * 运行或清理进行中,改变状态的公开方法一律被拒绝;Core 不承担任何界面职责。
2023
+ */
897
2024
  declare class AgentSession {
2025
+ private persistentId;
2026
+ private readonly configuredConversationId?;
2027
+ private readonly estimator?;
2028
+ private readonly onDiagnostic?;
2029
+ private readonly gitBranch?;
2030
+ private context;
2031
+ private usageKnown;
2032
+ private summaryUsageKnown;
2033
+ private summaryUsage;
2034
+ private readonly summaryAttempts;
2035
+ private readonly accountedAttempts;
898
2036
  readonly rootDir: string;
899
2037
  readonly tools: ToolRegistry;
900
2038
  readonly hooks: HookRegistry;
@@ -920,23 +2058,60 @@ declare class AgentSession {
920
2058
  private lastMetrics?;
921
2059
  private lastRunMetrics?;
922
2060
  private initialized;
2061
+ private pendingResume;
923
2062
  private destroyed;
2063
+ private cleanupStarted;
2064
+ private cleanupPromise?;
2065
+ private sessionEndFinished;
924
2066
  private activeRun;
2067
+ private primaryRole;
2068
+ private lastPrimaryProfile?;
2069
+ private lastPrimaryProvider?;
925
2070
  private readonly plugins;
926
2071
  constructor(config: SessionConfig);
2072
+ /** 幂等初始化:恢复审计残留、指令快照与持久历史,校验会话身份并回放 usage。 */
927
2073
  init(): Promise<void>;
2074
+ /** 挂载插件并执行 setup;销毁后或运行中拒绝,setup 失败的插件不进入已装列表。 */
928
2075
  use(plugin: AgentPlugin): Promise<void>;
2076
+ /**
2077
+ * 空闲时原子替换角色的模型绑定;本方法不改变当前角色或工具权限。
2078
+ * @param profile 模型协议、请求目标和输出预算。
2079
+ * @param role 被配置的主任务或摘要角色。
2080
+ * @param provider 与目标匹配的适配器;省略时只允许复用相同目标。
2081
+ * @throws {ModelError} 协议、模型、端点或 workspace 与适配器错配,旧绑定保留。
2082
+ * @throws {SessionBusyError} 正在执行或清理当前任务。
2083
+ */
929
2084
  switchModel(profile: ModelProfile, role?: ModelRole, provider?: ModelProvider): void;
2085
+ /** 查询指定绑定或当前明确选择的主任务模型,返回独立配置副本。 */
930
2086
  getActiveProfile(role?: ModelRole): ModelProfile;
2087
+ /** 空闲时显式选择场景;缺少映射或凭据时拒绝,不回退默认模型、不修改权限。 */
2088
+ selectModelRole(role: PrimaryModelRole): void;
2089
+ /** 返回本进程明确选择的场景,历史恢复不改变此状态。 */
2090
+ getModelRole(): PrimaryModelRole;
2091
+ /** 严格解析主任务快照,在输入落盘与网络调用之前检查角色、凭据与预算。 */
2092
+ private resolvePrimaryBinding;
931
2093
  /** 只在空闲时切换本次会话模式;宿主负责 FullAccess 的显式选择交互。 */
932
2094
  switchMode(mode: SessionMode): void;
933
2095
  getMode(): SessionMode;
934
2096
  /** 返回最近一次成功装载的来源路径,不暴露指令正文。 */
935
2097
  getInstructionSources(): string[];
2098
+ /** 稳定会话身份,独立于当前进程日志实例和每次用户交互。 */
2099
+ get conversationId(): string;
2100
+ /** 返回原始历史独立快照,外部修改不会改变落盘事实或当前工具事务。 */
936
2101
  getHistory(): CanonicalMessage[];
2102
+ /** 返回当前投影视图,区别于原始历史;不执行模型或 Hook。 */
2103
+ getContextHistory(): CanonicalMessage[];
2104
+ /** 查询最近最终请求的预算快照,尚未准备请求时返回 undefined。 */
2105
+ getContextSnapshot(): ContextSnapshot | undefined;
2106
+ /** 执行中止后的工具/摘要与存储收口期间仍返回 true。 */
2107
+ isBusy(): boolean;
2108
+ /** 返回独立统计快照,宿主修改嵌套指标不会改变会话状态或预算展示。 */
937
2109
  getStats(): SessionStats;
2110
+ /** 返回最近请求指标的独立副本;尚无完成请求时返回 undefined。 */
938
2111
  getLastMetrics(): TurnMetrics | undefined;
2112
+ /** 返回最近用户任务指标的独立副本;恢复的 usage 不伪造实时任务指标。 */
939
2113
  getLastRunMetrics(): RunMetrics | undefined;
2114
+ /** 空闲时清空存储与全部内存状态;conversationId 不变,恢复语义等同全新会话。 */
940
2115
  reset(): Promise<void>;
941
2116
  /**
942
2117
  * 执行一次用户输入,并以宿主无关的语义事件流返回全过程。
@@ -945,24 +2120,48 @@ declare class AgentSession {
945
2120
  * {@link SessionEvent},分别完成展示、交互和中止控制。
946
2121
  *
947
2122
  * @param userInput 用户本轮输入。
948
- * @param options 可选的中止信号。
2123
+ * @param options 可选中止信号与显式主任务角色;角色在整个工具任务内固定。
949
2124
  * @returns 文本、思考、工具、指标和错误等结构化事件的异步流。
950
2125
  * @throws {SessionBusyError} 当前会话已有正在执行的 run 时抛出。
2126
+ * @throws {ModelError} 显式角色缺少绑定或凭据时,在输入落盘和网络调用前抛出。
951
2127
  */
952
2128
  run(userInput: string, options?: {
953
2129
  signal?: AbortSignal;
2130
+ role?: PrimaryModelRole;
954
2131
  }): AsyncIterable<SessionEvent>;
2132
+ /** 单次任务执行主体;调用方 return 的中止与 finally 清理由外层统一协调。 */
2133
+ private runOperation;
2134
+ /** 幂等销毁:卸载插件后发出 session:end;运行中拒绝,teardown 失败聚合抛出且不完成销毁。 */
955
2135
  destroy(): Promise<void>;
956
2136
  private assertIdle;
957
2137
  /**
958
- * 计算最近一次内部模型请求的上下文占用。
2138
+ * 计算最近一次内部模型请求的上下文占用;无 usage 时显式标注预算估算。
959
2139
  * run 累计 promptTokens 会重复计算每一步都重发的历史,不能用于窗口占用率。
960
2140
  */
961
2141
  private createContextUsage;
962
2142
  private persistAssistant;
2143
+ /** 创建上下文协调器并注入当前路由;摘要不经过主任务 Loop,插件结果不默认为可剪裁。 */
2144
+ private createContextManager;
2145
+ /** 摘要实际消耗按 attempt 身份独立累加;缺失消耗保留未知,不计入主任务指标。 */
2146
+ private accountSummaryUsage;
2147
+ /**
2148
+ * 空闲时手动摘要旧完整前缀,不创建用户任务、不执行工具,不突破当前与最近成功交互。
2149
+ * 迭代结束或取消后等候摘要与提交收口,再释放执行状态;已提交检查点保持有效。
2150
+ */
2151
+ compact(options?: {
2152
+ signal?: AbortSignal;
2153
+ }): AsyncGenerator<SessionEvent>;
2154
+ /** 手动压缩按主任务协议投影旧历史,不复用旧 run 私有状态;原始历史与落盘内容保持不变。 */
2155
+ private compactOperation;
2156
+ /** 压缩与预算超限事件写入操作日志并携带 runId;其他事件不落日志。 */
2157
+ private logContextEvent;
2158
+ /** 以模型 attempt 身份幂等累加真实消耗;非法或缺失 usage 保持未知。 */
2159
+ private accountUsage;
963
2160
  private persistToolMessages;
2161
+ /** 中止时为缓冲 assistant 的每个 tool_use 生成 OUTCOME_UNKNOWN 结果并入历史,保持事务闭合。 */
964
2162
  private closeInterruptedToolCalls;
2163
+ /** 收集历史中紧跟该 assistant 的连续 tool 消息;仅当覆盖全部 tool_use 时视为已闭合。 */
965
2164
  private findClosedToolMessages;
966
2165
  }
967
2166
 
968
- export { AbortError, AgentLoop, type AgentLoopOptions, type AgentPlugin, AgentSession, type ApprovalChannel, type ApprovalChoice, type ApprovalRequest, type CanonicalMessage, type Capability, type CommandResult, type ConflictPolicy, type ContentBlock, type ContextUsage, type ContextWindowValue, DEFAULT_CONTEXT_WINDOW_TOKENS, type EventLogger, type ExecutorOptions, FatalError, FileLogSink, type FileLogSinkOptions, type HookContext, type HookHandlers, type HookPoint, HookRegistry, type InstructionLoadOptions, type InstructionSnapshot, type InstructionSource, JSONLMessageStore, KapibalaError, type LogChannel, type LogEvent, type LogField, type LogInput, type LogLevel, type LogSink, type MessageRole, type MessageStore, ModelError, type ModelEvent, type ModelProfile, type ModelProvider, type ModelRequest, type ModelRole, type ModelRouter, OpenAICompatibleProvider, type OpenAIProviderOptions, PathSandbox, type PermissionAction, type PermissionDecision, PermissionPolicy, type PermissionRequest, type PermissionRule, type PluginContext, PromptAssembler, type PromptAssemblerOptions, type RedactedThinkingBlock, type ResolvedContextWindow, type RunCommandInput, type RunMetrics, type SandboxConfig, SessionApprovalCache, SessionBusyError, type SessionConfig, type SessionEvent, type SessionMode, type SessionStats, type ShellDetectOptions, type ShellEnvironment, type ShellKind, type ShellPreference, type ShellScope, SimpleModelRouter, type StepLogEntry, type StepLogStage, StructuredLogger, type TextBlock, type ThinkingBlock, type Tool, type ToolContext, type ToolDecision, type ToolDefinition, ToolError, ToolExecutor, type ToolMetadata, ToolNotFound, ToolRegistry, type ToolResultBlock, type ToolUseBlock, TransportError, type TurnMetrics, type Usage, builtinTools, classifyBashOutput, cleanupCommandResults, commandAuditSummary, createDefaultLogSinks, createLogId, createRunCommandTool, defineTool, detectShell, editFileTool, executionFingerprint, globTool, grepTool, isTextBlock, isThinkingBlock, isToolResultBlock, isToolUseBlock, loadInstructions, projectSafeFields, readFileTool, recoverIncompleteAudit, resolveContextWindow, stableJsonStringify, toToolDefinition, validatePermissionRules, visibleTools, writeFileTool };
2167
+ export { AbortError, AgentLoop, type AgentLoopOptions, type AgentPlugin, AgentSession, AnthropicProvider, type AnthropicProviderOptions, type ApprovalChannel, type ApprovalChoice, type ApprovalRequest, type CanonicalMessage, type Capability, type ChatCapabilities, type CommandResult, type ConflictPolicy, type ContentBlock, type ContextBudget, ContextBudgetError, ContextManager, type ContextManagerOptions, ContextOverflowError, type ContextSnapshot, ContextStorageError, type ContextSummary, type ContextUsage, type ContextWindowValue, DEFAULT_CONTEXT_WINDOW_TOKENS, type EventLogger, type ExecutorOptions, FatalError, type FileDetails, FileLogSink, type FileLogSinkOptions, type FileObservation, type HistoryRepair, type HookContext, type HookHandlers, type HookPoint, HookRegistry, type InstructionLoadOptions, type InstructionSnapshot, type InstructionSource, type InteractionBoundary, type InteractionTerminal, JSONLMessageStore, KapibalaError, type LogChannel, type LogEvent, type LogField, type LogInput, type LogLevel, type LogSink, type ManagedSession, type MessageRole, type MessageStore, ModelError, type ModelErrorCategory, type ModelErrorInfo, type ModelErrorOptions, type ModelEvent, type ModelProfile, type ModelProtocol, type ModelProvider, type ModelProviderBinding, type ModelRequest, type ModelRole, type ModelRouter, type NormalizedHistory, OpenAICompatibleProvider, type OpenAIProviderOptions, OpenAIResponsesProvider, type OpenAIResponsesProviderOptions, PathSandbox, type PermissionAction, type PermissionDecision, PermissionPolicy, type PermissionRequest, type PermissionRule, type PluginContext, type PrimaryModelRole, type ProjectIdentity, PromptAssembler, type PromptAssemblerOptions, type ProtocolItemMetadata, type ProtocolOrigin, type ProviderStateBlock, type RedactedThinkingBlock, type RequestPreparation, type ResolvedContextWindow, type RunCommandInput, type RunMetrics, SESSION_SCHEMA_VERSION, SUMMARY_OUTPUT_BUFFER_MULTIPLIER, type SandboxConfig, SessionApprovalCache, SessionBusyError, type SessionConfig, type SessionEvent, type SessionHeader, SessionLock, SessionManager, type SessionManagerOptions, type SessionMetadata, type SessionMode, type SessionRecord, type SessionRecordType, type SessionState, type SessionStats, SessionStore, type ShellDetectOptions, type ShellEnvironment, type ShellKind, type ShellPreference, type ShellScope, SimpleModelRouter, type StatefulMessageStore, type StepLogEntry, type StepLogStage, StructuredLogger, type SummaryCandidate, SummaryService, type SummaryServiceOptions, type TextBlock, type ThinkingBlock, type TokenEstimate, type TokenEstimator, type Tool, type ToolContext, type ToolDecision, type ToolDefinition, ToolError, ToolExecutor, type ToolMetadata, ToolNotFound, ToolRegistry, type ToolResultBlock, type ToolUseBlock, TransportError, type TurnMetrics, UnicodeTokenEstimator, type Usage, assembleCanonicalToolResults, builtinTools, classifyBashOutput, cleanupCommandResults, commandAuditSummary, createContextBudget, createDefaultLogSinks, createLogId, createMessageId, createRunCommandTool, defineTool, describeModelError, detectShell, editFileTool, executionFingerprint, extractFileDetails, globTool, grepTool, identifyHistory, indexInteractions, isTextBlock, isThinkingBlock, isToolResultBlock, isToolUseBlock, loadInstructions, normalizeHistory, projectSafeFields, readFileTool, recoverIncompleteAudit, renderFileDetails, requestFingerprint, resolveContextWindow, resolveSessionProject, sanitizeModelErrorMessage, sanitizeSessionTitle, stableJsonStringify, stableSerialize, supportsSessionState, toToolDefinition, truncateToolOutput, validateModelBinding, validatePermissionRules, validateSummary, visibleTools, writeFileTool };