@kiturone/kapibala 0.0.3 → 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.cjs +2678 -1095
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +615 -62
- package/dist/index.d.ts +615 -62
- package/dist/index.js +2282 -703
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,7 +1,106 @@
|
|
|
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
|
+
|
|
1
97
|
/**
|
|
2
98
|
* Error Taxonomy for Kapibala Agent Harness
|
|
3
99
|
*/
|
|
100
|
+
|
|
101
|
+
/** 模型失败的安全分类;由明确状态码与受控错误码推导,不基于自然语言猜测根因。 */
|
|
4
102
|
type ModelErrorCategory = 'authentication' | 'quota' | 'rate_limit' | 'context' | 'service' | 'network' | 'timeout' | 'invalid_request' | 'invalid_response' | 'unknown';
|
|
103
|
+
/** ModelError 的受控输入;仅这些字段会进入错误对象,原始响应体与密钥不得携带。 */
|
|
5
104
|
interface ModelErrorOptions {
|
|
6
105
|
status?: number;
|
|
7
106
|
retryable?: boolean;
|
|
@@ -22,6 +121,8 @@ interface ModelErrorInfo {
|
|
|
22
121
|
transportCode?: string;
|
|
23
122
|
stage?: ModelErrorOptions['stage'];
|
|
24
123
|
operation?: 'primary' | 'summary';
|
|
124
|
+
/** type-only 引用协议层角色类型;运行时无循环依赖。 */
|
|
125
|
+
modelRole?: PrimaryModelRole;
|
|
25
126
|
modelId?: string;
|
|
26
127
|
provider?: string;
|
|
27
128
|
retryPolicy: KapibalaError['retryPolicy'];
|
|
@@ -30,7 +131,8 @@ interface ModelErrorInfo {
|
|
|
30
131
|
/** 清理服务端报错中的终端控制符、常见凭据及带凭据的 URL,限制长度;不展示完整响应或请求头。 */
|
|
31
132
|
declare function sanitizeModelErrorMessage(value: string): string;
|
|
32
133
|
/** 生成统一脱敏说明;上下文补充调用场景,不携带原始异常、请求正文或密钥。 */
|
|
33
|
-
declare function describeModelError(error: ModelError, context?: Pick<ModelErrorInfo, 'modelId' | 'provider' | 'operation'>): ModelErrorInfo;
|
|
134
|
+
declare function describeModelError(error: ModelError, context?: Pick<ModelErrorInfo, 'modelId' | 'provider' | 'operation' | 'modelRole'>): ModelErrorInfo;
|
|
135
|
+
/** 错误体系基类:code 供机器判定,retryPolicy 是处理建议而非重试授权,safeMessage 是可对外展示的固定文案。 */
|
|
34
136
|
declare class KapibalaError extends Error {
|
|
35
137
|
readonly code: string;
|
|
36
138
|
readonly retryPolicy: 'never' | 'immediate' | 'backoff' | 'after_user_action';
|
|
@@ -41,8 +143,10 @@ declare class KapibalaError extends Error {
|
|
|
41
143
|
safeMessage?: string;
|
|
42
144
|
});
|
|
43
145
|
}
|
|
146
|
+
/** 模型调用失败;message 已脱敏,对外诊断统一经 describeModelError 产出,retryPolicy 仅为处理建议。 */
|
|
44
147
|
declare class ModelError extends KapibalaError {
|
|
45
148
|
readonly status?: number;
|
|
149
|
+
/** 属于可退避重试的瞬态类别(限流/服务/超时/网络);不等于自动重试授权。 */
|
|
46
150
|
readonly retryable: boolean;
|
|
47
151
|
/** 可选的受控底层连接错误码,不包含原始传输异常文本。 */
|
|
48
152
|
readonly transportCode?: string;
|
|
@@ -60,24 +164,30 @@ declare class ContextOverflowError extends ModelError {
|
|
|
60
164
|
message?: string;
|
|
61
165
|
});
|
|
62
166
|
}
|
|
167
|
+
/** 模型 API 语义之外的传输失败;retryable 表示属于可立即重试的网络类错误。 */
|
|
63
168
|
declare class TransportError extends KapibalaError {
|
|
64
169
|
readonly retryable: boolean;
|
|
65
170
|
constructor(message: string, retryable?: boolean);
|
|
66
171
|
}
|
|
172
|
+
/** 工具执行失败的通用错误;retryPolicy 固定 never,后续处理由调用方决定。 */
|
|
67
173
|
declare class ToolError extends KapibalaError {
|
|
68
174
|
constructor(message: string);
|
|
69
175
|
}
|
|
176
|
+
/** 请求的工具在注册表中不存在;message 回显工具名与可用列表,对外展示用 safeMessage。 */
|
|
70
177
|
declare class ToolNotFound extends KapibalaError {
|
|
71
178
|
readonly toolName: string;
|
|
72
179
|
readonly availableTools: string[];
|
|
73
180
|
constructor(toolName: string, availableTools?: string[]);
|
|
74
181
|
}
|
|
182
|
+
/** 用户主动中止;不属于失败,恢复需要用户重新发起操作。 */
|
|
75
183
|
declare class AbortError extends KapibalaError {
|
|
76
184
|
constructor(message?: string);
|
|
77
185
|
}
|
|
186
|
+
/** 无受控分类的致命错误(code 固定 INTERNAL_ERROR、不可重试);终止策略由宿主决定。 */
|
|
78
187
|
declare class FatalError extends KapibalaError {
|
|
79
188
|
constructor(message: string);
|
|
80
189
|
}
|
|
190
|
+
/** 会话正在执行任务时拒绝新的排他操作(切换模型、挂载插件等),operation 描述被拒绝的动作。 */
|
|
81
191
|
declare class SessionBusyError extends KapibalaError {
|
|
82
192
|
constructor(operation: string);
|
|
83
193
|
}
|
|
@@ -96,10 +206,47 @@ declare class ContextStorageError extends KapibalaError {
|
|
|
96
206
|
* Canonical Message & Event Types for Kapibala
|
|
97
207
|
*/
|
|
98
208
|
|
|
99
|
-
|
|
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;
|
|
100
245
|
interface TextBlock {
|
|
101
246
|
type: 'text';
|
|
102
247
|
text: string;
|
|
248
|
+
/** 源 wire Item 元数据;正文被改写后由调用方清除,不作为业务身份。 */
|
|
249
|
+
protocolMeta?: ProtocolItemMetadata;
|
|
103
250
|
}
|
|
104
251
|
interface ToolUseBlock {
|
|
105
252
|
/** 工具执行语义来源;新运行记录,旧历史可缺省。未知插件不按内置只读工具剪裁。 */
|
|
@@ -110,6 +257,8 @@ interface ToolUseBlock {
|
|
|
110
257
|
id: string;
|
|
111
258
|
name: string;
|
|
112
259
|
input: Record<string, unknown>;
|
|
260
|
+
/** 源 wire Item 元数据;内容被改写后由调用方清除,不作为业务身份。 */
|
|
261
|
+
protocolMeta?: ProtocolItemMetadata;
|
|
113
262
|
}
|
|
114
263
|
interface ToolResultBlock {
|
|
115
264
|
type: 'tool_result';
|
|
@@ -126,12 +275,17 @@ interface ToolResultBlock {
|
|
|
126
275
|
interface ThinkingBlock {
|
|
127
276
|
type: 'thinking';
|
|
128
277
|
thinking: string;
|
|
278
|
+
/** 存在签名或来源时属于私有输出,改写内容会被整批拒绝。 */
|
|
129
279
|
signature?: string;
|
|
280
|
+
origin?: ProtocolOrigin;
|
|
130
281
|
}
|
|
282
|
+
/** Provider 提供的密文占位;仅按原样回传用于续答,不进入展示或摘要源。 */
|
|
131
283
|
interface RedactedThinkingBlock {
|
|
132
284
|
type: 'redacted_thinking';
|
|
133
285
|
data: string;
|
|
286
|
+
origin?: ProtocolOrigin;
|
|
134
287
|
}
|
|
288
|
+
/** 单次模型请求的 token 用量;由 Provider 上报,缺失的字段不能按零推断。 */
|
|
135
289
|
interface Usage {
|
|
136
290
|
promptTokens: number;
|
|
137
291
|
completionTokens: number;
|
|
@@ -139,7 +293,12 @@ interface Usage {
|
|
|
139
293
|
/** Provider 明确提供的缓存命中输入量;缺失表示未知,不能按零推断。 */
|
|
140
294
|
cachedPromptTokens?: number;
|
|
141
295
|
}
|
|
296
|
+
/** canonical 消息角色;'tool' 仅用于工具结果消息,wire 角色转换只发生在请求投影阶段。 */
|
|
142
297
|
type MessageRole = 'user' | 'assistant' | 'system' | 'tool';
|
|
298
|
+
/**
|
|
299
|
+
* 协议无关的历史真源;wire 格式只在请求投影时出现。
|
|
300
|
+
* 不变量:assistant 消息中的 tool_use 进入历史后,对应 tool_result 消息必须紧跟其后。
|
|
301
|
+
*/
|
|
143
302
|
interface CanonicalMessage {
|
|
144
303
|
/** 派生背景锚点独立于真实用户输入,避免合并后丢失受保护原消息的来源身份。 */
|
|
145
304
|
contextSummary?: {
|
|
@@ -155,10 +314,15 @@ interface CanonicalMessage {
|
|
|
155
314
|
content: ContentBlock[];
|
|
156
315
|
timestamp?: number;
|
|
157
316
|
}
|
|
317
|
+
/** 判别并收窄为文本块。 */
|
|
158
318
|
declare function isTextBlock(block: ContentBlock): block is TextBlock;
|
|
319
|
+
/** 判别并收窄为工具调用块。 */
|
|
159
320
|
declare function isToolUseBlock(block: ContentBlock): block is ToolUseBlock;
|
|
321
|
+
/** 判别并收窄为工具结果块。 */
|
|
160
322
|
declare function isToolResultBlock(block: ContentBlock): block is ToolResultBlock;
|
|
323
|
+
/** 判别并收窄为思考块。 */
|
|
161
324
|
declare function isThinkingBlock(block: ContentBlock): block is ThinkingBlock;
|
|
325
|
+
/** 单个 turn 的指标快照;错误与熔断路径也以统一构造产出(工具字段为零),保证结构一致。 */
|
|
162
326
|
interface TurnMetrics {
|
|
163
327
|
turn: number;
|
|
164
328
|
startTime: number;
|
|
@@ -172,6 +336,7 @@ interface TurnMetrics {
|
|
|
172
336
|
totalTokens: number;
|
|
173
337
|
toolCallsCount: number;
|
|
174
338
|
}
|
|
339
|
+
/** 一次完整 run 的累计指标;token 数为各轮请求之和,上下文占用单独见 contextUsage。 */
|
|
175
340
|
interface RunMetrics {
|
|
176
341
|
startTime: number;
|
|
177
342
|
endTime: number;
|
|
@@ -190,6 +355,7 @@ interface RunMetrics {
|
|
|
190
355
|
/** 最近一次内部模型请求占用的上下文;不使用 run 累计 promptTokens。 */
|
|
191
356
|
contextUsage?: ContextUsage;
|
|
192
357
|
}
|
|
358
|
+
/** 供宿主展示的上下文占用快照;估算值不能用于计费或精确预算。 */
|
|
193
359
|
interface ContextUsage {
|
|
194
360
|
usedTokens?: number;
|
|
195
361
|
/** true 表示未收到当前请求 usage,输入占用使用预算估算,不能用于计费。 */
|
|
@@ -198,7 +364,9 @@ interface ContextUsage {
|
|
|
198
364
|
percent?: number;
|
|
199
365
|
estimatedLimit: boolean;
|
|
200
366
|
}
|
|
367
|
+
/** 单 turn 内关键阶段的进度标记;顺序与 AgentLoop 的实际派发时序一致,供展示与诊断。 */
|
|
201
368
|
type StepLogStage = 'model_request_start' | 'first_token' | 'model_stream_finish' | 'tool_execution_start' | 'tool_execution_finish' | 'turn_finish';
|
|
369
|
+
/** 面向宿主的步骤日志;message 可直接展示,结构化数值放在 metadata 中。 */
|
|
202
370
|
interface StepLogEntry {
|
|
203
371
|
timestamp: number;
|
|
204
372
|
turn: number;
|
|
@@ -273,9 +441,16 @@ type SessionEvent = {
|
|
|
273
441
|
} | {
|
|
274
442
|
type: 'text_delta';
|
|
275
443
|
text: string;
|
|
444
|
+
} | {
|
|
445
|
+
type: 'thinking_block_start';
|
|
446
|
+
blockId: string;
|
|
276
447
|
} | {
|
|
277
448
|
type: 'thinking_delta';
|
|
278
449
|
thinking: string;
|
|
450
|
+
blockId?: string;
|
|
451
|
+
} | {
|
|
452
|
+
type: 'thinking_block_stop';
|
|
453
|
+
blockId: string;
|
|
279
454
|
} | {
|
|
280
455
|
type: 'tool_start';
|
|
281
456
|
id: string;
|
|
@@ -325,9 +500,16 @@ type SessionEvent = {
|
|
|
325
500
|
type ModelEvent = {
|
|
326
501
|
type: 'text_delta';
|
|
327
502
|
text: string;
|
|
503
|
+
} | {
|
|
504
|
+
type: 'thinking_block_start';
|
|
505
|
+
blockId: string;
|
|
328
506
|
} | {
|
|
329
507
|
type: 'thinking_delta';
|
|
330
508
|
thinking: string;
|
|
509
|
+
blockId?: string;
|
|
510
|
+
} | {
|
|
511
|
+
type: 'thinking_block_stop';
|
|
512
|
+
blockId: string;
|
|
331
513
|
} | {
|
|
332
514
|
type: 'tool_call_start';
|
|
333
515
|
id: string;
|
|
@@ -349,19 +531,30 @@ type ModelEvent = {
|
|
|
349
531
|
ttftMs?: number;
|
|
350
532
|
durationMs?: number;
|
|
351
533
|
finishReason?: string;
|
|
534
|
+
/** 完整且有序的最终内容;有此字段时增量只供展示,不重复装配或执行工具。 */
|
|
535
|
+
finalContent?: ContentBlock[];
|
|
536
|
+
refusal?: boolean;
|
|
352
537
|
};
|
|
538
|
+
/** 投影给模型的工具描述;由注册表条目转换而来,仅暴露名称、描述与参数 Schema。 */
|
|
353
539
|
interface ToolDefinition {
|
|
354
540
|
name: string;
|
|
355
541
|
description: string;
|
|
356
542
|
parameters: Record<string, unknown>;
|
|
357
543
|
}
|
|
544
|
+
/** 协议无关的模型请求;messages 是 canonical 真源的克隆,wire 翻译只发生在 Provider 内。 */
|
|
358
545
|
interface ModelRequest {
|
|
359
546
|
systemPrompt?: string;
|
|
360
547
|
messages: CanonicalMessage[];
|
|
361
548
|
tools?: ToolDefinition[];
|
|
362
549
|
signal?: AbortSignal;
|
|
550
|
+
/** 以下两项可选覆盖采样温度与单次输出上限;未设置时由适配器按协议与能力决定。 */
|
|
363
551
|
temperature?: number;
|
|
364
552
|
maxTokens?: number;
|
|
553
|
+
/** 宿主提供的本次运行来源;缺省时原生适配器不回传来源未知的私有状态。 */
|
|
554
|
+
context?: {
|
|
555
|
+
runId: string;
|
|
556
|
+
modelId?: string;
|
|
557
|
+
};
|
|
365
558
|
}
|
|
366
559
|
/** runtime 通用请求准备契约;实现可以预算或投影,Loop 不依赖具体上下文管理器。 */
|
|
367
560
|
type RequestPreparation = (request: ModelRequest, history: readonly CanonicalMessage[], reason?: 'threshold' | 'overflow') => AsyncGenerator<SessionEvent, ModelRequest>;
|
|
@@ -371,16 +564,23 @@ declare function createMessageId(): string;
|
|
|
371
564
|
|
|
372
565
|
/** 按来源及原始位置生成旧消息身份;复制输入,不改变调用者持有的正文或已有身份。 */
|
|
373
566
|
declare function identifyHistory(messages: readonly CanonicalMessage[], source: string): CanonicalMessage[];
|
|
567
|
+
/**
|
|
568
|
+
* 一次缺失工具结果的补齐:result 为 OUTCOME_UNKNOWN 占位,只用于闭合历史事务。
|
|
569
|
+
* 持久化为 history_repair 记录后,恢复时叠加到原工具事务;不重放工具。
|
|
570
|
+
*/
|
|
374
571
|
interface HistoryRepair {
|
|
375
572
|
assistantId: string;
|
|
376
573
|
toolCallId: string;
|
|
377
574
|
result: ToolResultBlock;
|
|
378
575
|
}
|
|
576
|
+
/** normalizeHistory 的产物:合法请求视图、来源追踪与修复/丢弃审计。 */
|
|
379
577
|
interface NormalizedHistory {
|
|
380
578
|
messages: CanonicalMessage[];
|
|
381
579
|
/** 与 messages 同序的原始消息 ID 集合;修复结果关联原始 assistant。 */
|
|
382
580
|
sources: string[][];
|
|
581
|
+
/** 已注入 messages 的缺失结果占位;结构与 history_repair 持久记录一致。 */
|
|
383
582
|
repairs: HistoryRepair[];
|
|
583
|
+
/** 被忽略的孤儿、迟到或重复工具结果提示;只诊断,不回写调用方输入。 */
|
|
384
584
|
diagnostics: string[];
|
|
385
585
|
}
|
|
386
586
|
/**
|
|
@@ -388,11 +588,15 @@ interface NormalizedHistory {
|
|
|
388
588
|
* 合并仅适用于纯文本的同角色消息,失败正文不重放,所有来源均可追踪。
|
|
389
589
|
*/
|
|
390
590
|
declare function normalizeHistory(input: readonly CanonicalMessage[]): NormalizedHistory;
|
|
591
|
+
/** 以用户输入为界划分的一次交互及其终态;保护范围与摘要资格都以它为单位。 */
|
|
391
592
|
interface InteractionBoundary {
|
|
392
593
|
interactionId: string;
|
|
594
|
+
/** completed 需显式终态或推断成功;failed 只来自显式终态,缺省 interrupted。 */
|
|
393
595
|
status: 'completed' | 'failed' | 'interrupted';
|
|
596
|
+
/** 该交互按历史顺序覆盖的原始消息 ID。 */
|
|
394
597
|
messageIds: string[];
|
|
395
598
|
}
|
|
599
|
+
/** 运行收尾时记录的交互终态;有 start 无 finish 的运行恢复后保持 interrupted。 */
|
|
396
600
|
interface InteractionTerminal {
|
|
397
601
|
interactionId: string;
|
|
398
602
|
status: InteractionBoundary['status'];
|
|
@@ -406,11 +610,18 @@ declare function indexInteractions(input: readonly CanonicalMessage[], terminals
|
|
|
406
610
|
protectedMessageIds: string[];
|
|
407
611
|
};
|
|
408
612
|
|
|
613
|
+
/**
|
|
614
|
+
* 旧版单文件 JSONL MessageStore:每行一条消息,无版本化状态能力。
|
|
615
|
+
* 写入为同步追加,不做 fsync 或单写者保护;恢复时容错跳过损坏行并闭合悬挂事务。
|
|
616
|
+
*/
|
|
409
617
|
declare class JSONLMessageStore implements MessageStore {
|
|
410
618
|
readonly filePath: string;
|
|
411
619
|
constructor(filePath: string);
|
|
620
|
+
/** 校验协议内容后追加一行 JSON;不补身份、不查重、不 fsync。 */
|
|
412
621
|
append(message: CanonicalMessage): Promise<void>;
|
|
622
|
+
/** 读取全部消息;半截损坏行忽略,悬挂 tool_use 就地补 OUTCOME_UNKNOWN 结果。 */
|
|
413
623
|
load(): Promise<CanonicalMessage[]>;
|
|
624
|
+
/** 删除整个文件;文件不存在时静默成功。 */
|
|
414
625
|
clear(): Promise<void>;
|
|
415
626
|
/**
|
|
416
627
|
* 历史自愈(设计文档 §4.4):逐条扫描 assistant 的 tool_use,
|
|
@@ -423,22 +634,32 @@ declare class JSONLMessageStore implements MessageStore {
|
|
|
423
634
|
private healDanglingToolCalls;
|
|
424
635
|
}
|
|
425
636
|
|
|
637
|
+
/**
|
|
638
|
+
* 消息级持久化最小契约:user、assistant、tool 三类消息逐条经 append 落盘,
|
|
639
|
+
* load 恢复原始正文(而非模型请求投影),clear 实现 SDK 清空语义。
|
|
640
|
+
* 需要持久压缩、交互终态等能力的宿主另实现 StatefulMessageStore。
|
|
641
|
+
*/
|
|
426
642
|
interface MessageStore {
|
|
427
643
|
append(message: CanonicalMessage): Promise<void>;
|
|
428
644
|
load(): Promise<CanonicalMessage[]>;
|
|
429
645
|
clear(): Promise<void>;
|
|
430
646
|
}
|
|
431
647
|
|
|
648
|
+
/** 会话正文 schema 版本;读取时不匹配即拒绝恢复,不做跨版本猜测。 */
|
|
432
649
|
declare const SESSION_SCHEMA_VERSION = 1;
|
|
650
|
+
/** 会话记录类型:header 只出现一次,message 承载正文,其余为状态记录。 */
|
|
433
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 与文件名强绑定。 */
|
|
434
653
|
interface SessionHeader {
|
|
435
654
|
conversationId: string;
|
|
436
655
|
projectRoot: string;
|
|
437
656
|
initialCwd: string;
|
|
438
657
|
createdAt?: number;
|
|
439
658
|
gitBranch?: string;
|
|
659
|
+
/** 旧历史导入的幂等身份;存在时同一来源只导入一次。 */
|
|
440
660
|
importIdentity?: string;
|
|
441
661
|
}
|
|
662
|
+
/** 单条 JSONL 记录封装;parentId 链接前驱,恢复时校验追加次序。 */
|
|
442
663
|
interface SessionRecord {
|
|
443
664
|
schemaVersion: number;
|
|
444
665
|
type: SessionRecordType;
|
|
@@ -447,6 +668,7 @@ interface SessionRecord {
|
|
|
447
668
|
parentId: string | null;
|
|
448
669
|
payload: Record<string, unknown>;
|
|
449
670
|
}
|
|
671
|
+
/** loadState 返回的版本化状态视图;记录自最近 reset 起有效。 */
|
|
450
672
|
interface SessionState {
|
|
451
673
|
header: SessionHeader;
|
|
452
674
|
/** 最近 reset 之后的记录;包含正文及状态,不包含头部。 */
|
|
@@ -527,33 +749,48 @@ declare class SessionLock {
|
|
|
527
749
|
private static isDead;
|
|
528
750
|
}
|
|
529
751
|
|
|
752
|
+
/** 会话桶的项目身份:会话按工作树根隔离存储在项目桶目录下。 */
|
|
530
753
|
interface ProjectIdentity {
|
|
754
|
+
/** 真实工作树根(非 Git 目录时为真实 cwd),作为会话归属与来源基准。 */
|
|
531
755
|
projectRoot: string;
|
|
756
|
+
/** 解析符号链接后的真实 cwd。 */
|
|
532
757
|
cwd: string;
|
|
758
|
+
/** 规范化根目录的 SHA-256,决定 ~/.kapibala/sessions 下的桶目录。 */
|
|
533
759
|
projectKey: string;
|
|
760
|
+
/** detached HEAD 或非 Git 目录时缺省。 */
|
|
534
761
|
gitBranch?: string;
|
|
762
|
+
/** true 表示 cwd 位于 Git 工作树内;同工作树子目录共用同一桶。 */
|
|
535
763
|
gitWorktree?: boolean;
|
|
536
764
|
}
|
|
537
765
|
/** 解析真实工作树根;同工作树子目录共用桶,非 Git 目录和不同 worktree 独立。不会改变 cwd。 */
|
|
538
766
|
declare function resolveSessionProject(cwd: string): ProjectIdentity;
|
|
767
|
+
/**
|
|
768
|
+
* 会话 sidecar 缓存元数据;可随时从正文重建,校验失败即丢弃,不是恢复依据。
|
|
769
|
+
* 正文 JSONL 始终是唯一真源。
|
|
770
|
+
*/
|
|
539
771
|
interface SessionMetadata {
|
|
540
772
|
schemaVersion: 1;
|
|
541
773
|
conversationId: string;
|
|
542
774
|
fileName: string;
|
|
543
775
|
projectRoot: string;
|
|
544
776
|
createdAt: number;
|
|
777
|
+
/** 最后一次正文、用户 run 或 reset 的时间;usage 与标题不影响排序。 */
|
|
545
778
|
lastActivityAt: number;
|
|
546
779
|
messageCount: number;
|
|
547
780
|
title: string;
|
|
781
|
+
/** 用户显式重命名的标题;存在时 reset 不再回退为默认标题。 */
|
|
548
782
|
customTitle?: string;
|
|
549
783
|
gitBranch?: string;
|
|
550
784
|
lastActivityGitBranch?: string;
|
|
551
785
|
lastModelId?: string;
|
|
786
|
+
/** 旧历史导入的幂等身份(来源路径 + 内容哈希);重复导入据此跳过。 */
|
|
552
787
|
importIdentity?: string;
|
|
553
788
|
size: number;
|
|
554
789
|
mtimeMs: number;
|
|
790
|
+
/** 最后计入的记录 ID;与正文 stat 一同用于增量校验。 */
|
|
555
791
|
revision: string;
|
|
556
792
|
}
|
|
793
|
+
/** 打开的会话句柄:持有单写者锁与 Store,宿主用毕必须 release。 */
|
|
557
794
|
interface ManagedSession {
|
|
558
795
|
conversationId: string;
|
|
559
796
|
store: SessionStore;
|
|
@@ -566,8 +803,10 @@ interface ManagedSession {
|
|
|
566
803
|
createdBranch?: string;
|
|
567
804
|
currentBranch?: string;
|
|
568
805
|
};
|
|
806
|
+
/** 释放单写者锁并移除句柄;宿主须先结束 AgentSession 的工具/摘要清理。 */
|
|
569
807
|
release(): Promise<void>;
|
|
570
808
|
}
|
|
809
|
+
/** SessionManager 配置;cwd 决定项目桶,homeDirectory 便于测试隔离。 */
|
|
571
810
|
interface SessionManagerOptions {
|
|
572
811
|
cwd?: string;
|
|
573
812
|
homeDirectory?: string;
|
|
@@ -623,57 +862,19 @@ declare class SessionManager {
|
|
|
623
862
|
private report;
|
|
624
863
|
}
|
|
625
864
|
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
create(req: ModelRequest): AsyncIterable<ModelEvent>;
|
|
629
|
-
/** 把一批工具结果装配成符合本协议的 canonical 消息序列 */
|
|
630
|
-
assembleToolResults(results: ToolResultBlock[]): CanonicalMessage[];
|
|
631
|
-
}
|
|
632
|
-
|
|
633
|
-
type ModelRole = 'default' | 'planning' | 'execution' | 'summary' | 'fast';
|
|
634
|
-
type ContextWindowValue = number | `${number}${'K' | 'k' | 'M' | 'm'}`;
|
|
635
|
-
interface ResolvedContextWindow {
|
|
636
|
-
tokens: number;
|
|
637
|
-
/** true 表示模型未声明窗口,当前值来自 Kapibala 的默认估算。 */
|
|
638
|
-
estimated: boolean;
|
|
639
|
-
}
|
|
640
|
-
declare const DEFAULT_CONTEXT_WINDOW_TOKENS = 1000000;
|
|
641
|
-
/**
|
|
642
|
-
* 将模型上下文窗口统一解析为整数 Token 数。
|
|
643
|
-
*
|
|
644
|
-
* 配置允许直接填写整数,或使用十进制 K/M 简写;未填写时返回默认 1M,并标记为估算值。
|
|
645
|
-
*/
|
|
646
|
-
declare function resolveContextWindow(value?: ContextWindowValue): ResolvedContextWindow;
|
|
647
|
-
interface ModelProfile {
|
|
648
|
-
id: string;
|
|
649
|
-
name: string;
|
|
650
|
-
provider: 'openai-compatible';
|
|
651
|
-
baseURL: string;
|
|
652
|
-
apiKeyEnv: string;
|
|
653
|
-
apiKey?: string;
|
|
654
|
-
modelName: string;
|
|
655
|
-
contextWindow?: ContextWindowValue;
|
|
656
|
-
supportsThinking?: boolean;
|
|
657
|
-
}
|
|
658
|
-
interface ModelRouter {
|
|
659
|
-
resolve(role?: ModelRole): ModelProvider;
|
|
660
|
-
getProfile(role?: ModelRole): ModelProfile;
|
|
661
|
-
}
|
|
662
|
-
declare class SimpleModelRouter implements ModelRouter {
|
|
663
|
-
private readonly providers;
|
|
664
|
-
private readonly profiles;
|
|
665
|
-
private defaultRole;
|
|
666
|
-
constructor(defaultProfile: ModelProfile, defaultProvider: ModelProvider);
|
|
667
|
-
setRole(role: ModelRole, profile: ModelProfile, provider: ModelProvider): void;
|
|
668
|
-
resolve(role?: ModelRole): ModelProvider;
|
|
669
|
-
getProfile(role?: ModelRole): ModelProfile;
|
|
670
|
-
}
|
|
865
|
+
/** 对对象 key 确定性排序,保证摘要、工具 schema 与 fingerprint 不受插入顺序影响。 */
|
|
866
|
+
declare function stableSerialize(value: unknown): string;
|
|
671
867
|
|
|
868
|
+
/** 由生效窗口推导的请求预算;实际请求与只读展示必须共用同一份推导。 */
|
|
672
869
|
interface ContextBudget {
|
|
673
870
|
contextWindow: number;
|
|
871
|
+
/** 窗口来自保守估算(未知按 32K 推导)时为 true。 */
|
|
674
872
|
estimatedWindow: boolean;
|
|
873
|
+
/** 输出预留(含私有推理消耗),同时作为实际请求的 maxTokens。 */
|
|
675
874
|
outputReserve: number;
|
|
875
|
+
/** 至少 128 的窗口安全余量,防止输入预算顶满窗口。 */
|
|
676
876
|
safetyReserve: number;
|
|
877
|
+
/** 输入预算 = 窗口 − 输出预留 − 安全余量;超限请求在 Provider 调用前失败。 */
|
|
677
878
|
inputBudget: number;
|
|
678
879
|
/** 触发阈值 0.85B:超过才启动一级剪裁/二级摘要(迁移文档:剪裁后低于触发阈值则不调用摘要模型)。 */
|
|
679
880
|
trigger: number;
|
|
@@ -684,12 +885,14 @@ interface ContextBudget {
|
|
|
684
885
|
*/
|
|
685
886
|
target: number;
|
|
686
887
|
}
|
|
888
|
+
/** 单次请求的 token 占用分解;total 与各部分独立取整,不保证严格相加。 */
|
|
687
889
|
interface TokenEstimate {
|
|
688
890
|
total: number;
|
|
689
891
|
system: number;
|
|
690
892
|
tools: number;
|
|
691
893
|
history: number;
|
|
692
894
|
overhead: number;
|
|
895
|
+
/** calibrated 表示该请求指纹已有实测校准;估算结果仍非计费依据。 */
|
|
693
896
|
source: 'estimated' | 'calibrated';
|
|
694
897
|
}
|
|
695
898
|
/** 可替换估算器;不得执行 Provider、Hook 或改写传入请求。 */
|
|
@@ -697,10 +900,16 @@ interface TokenEstimator {
|
|
|
697
900
|
estimate(request: ModelRequest, modelFingerprint?: string): TokenEstimate;
|
|
698
901
|
observe?(request: ModelRequest, actualPromptTokens: number, modelFingerprint?: string): void;
|
|
699
902
|
}
|
|
700
|
-
/**
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
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;
|
|
704
913
|
/** 请求 fingerprint 不包含 AbortSignal 等宿主对象,包含实际指令、schema、正文和输出配置。 */
|
|
705
914
|
declare function requestFingerprint(request: ModelRequest, modelFingerprint?: string): string;
|
|
706
915
|
/**
|
|
@@ -716,36 +925,58 @@ declare class UnicodeTokenEstimator implements TokenEstimator {
|
|
|
716
925
|
}
|
|
717
926
|
|
|
718
927
|
type CompactionReason = 'threshold' | 'manual' | 'overflow';
|
|
928
|
+
/**
|
|
929
|
+
* 最近一次请求准备或只读检查发布的上下文快照,供宿主展示与诊断。
|
|
930
|
+
* 反映原始历史与实际请求两侧状态;不代表工具执行结果,也不承诺下次压缩行为。
|
|
931
|
+
*/
|
|
719
932
|
interface ContextSnapshot {
|
|
720
933
|
conversationId: string;
|
|
721
934
|
modelId: string;
|
|
935
|
+
/** 最终请求指纹;observe 只对匹配指纹的请求回填实测 usage。 */
|
|
722
936
|
fingerprint: string;
|
|
723
937
|
budget: ContextBudget;
|
|
724
938
|
estimate: TokenEstimate;
|
|
939
|
+
/** 最近成功交互及其后全部交互的原始消息 ID;剪裁与摘要不得越过。 */
|
|
725
940
|
protectedMessageIds: string[];
|
|
941
|
+
/** 原始历史条数;与 projectedMessageCount 的差值来自摘要覆盖与压缩投影。 */
|
|
726
942
|
rawMessageCount: number;
|
|
727
943
|
projectedMessageCount: number;
|
|
944
|
+
/** 模型或请求配置变化后为 true,直到下一次准备成功。 */
|
|
728
945
|
stale: boolean;
|
|
946
|
+
/** 匹配指纹请求的实测 usage;缺失表示尚未观测,不按零推断。 */
|
|
729
947
|
actualPromptTokens?: number;
|
|
730
948
|
actualCachedPromptTokens?: number;
|
|
731
949
|
/** false 表示只读静态估算,尚未执行下一请求的动态 Hook。 */
|
|
732
950
|
dynamicKnown: boolean;
|
|
951
|
+
/** 当前检查点摘要消息的估算占用;无检查点为 0。 */
|
|
733
952
|
summaryTokens: number;
|
|
734
953
|
checkpointId?: string;
|
|
954
|
+
/** 累计被替换为占位描述的成功工具结果数。 */
|
|
735
955
|
prunedResults: number;
|
|
956
|
+
/** 已提交(含恢复自持久状态)的摘要检查点次数。 */
|
|
736
957
|
summaryCount: number;
|
|
958
|
+
/** 当前配置纪元内连续摘要失败次数;达到 3 次暂停自动摘要。 */
|
|
737
959
|
consecutiveFailures: number;
|
|
960
|
+
/** 熔断生效标志;阈值触发的压缩被暂停,手动压缩仍可重试。 */
|
|
738
961
|
automaticSummaryPaused: boolean;
|
|
962
|
+
/** disk 有版本化 Store 支撑;memory 只在内存,unsupported 禁用剪裁与摘要。 */
|
|
739
963
|
persistence: 'disk' | 'memory' | 'unsupported';
|
|
740
964
|
}
|
|
965
|
+
/** ContextManager 的宿主注入;除 conversationId 外均可缺省,缺省时按保守方式降级。 */
|
|
741
966
|
interface ContextManagerOptions {
|
|
967
|
+
/** 提供状态能力时启用持久剪裁与摘要;旧 Store 降级为仅内存并给出诊断。 */
|
|
742
968
|
store?: MessageStore;
|
|
743
969
|
estimator?: TokenEstimator;
|
|
744
970
|
conversationId: string;
|
|
971
|
+
/** 存储降级、无效状态记录等非致命事件的脱敏诊断通道。 */
|
|
745
972
|
onDiagnostic?: (message: string) => void;
|
|
973
|
+
/** 摘要角色绑定来源;缺省时跳过二级摘要,仅保留一级剪裁。 */
|
|
746
974
|
router?: ModelRouter;
|
|
975
|
+
/** 转发给文件观察提取;项目根不作为历史工具相对路径的推断依据。 */
|
|
747
976
|
projectRoot?: string;
|
|
977
|
+
/** 当前已注册的内置工具名集合;剪裁白名单只认可其中的内置只读工具。 */
|
|
748
978
|
builtInToolNames?: () => ReadonlySet<string>;
|
|
979
|
+
/** 每个摘要 attempt 的使用量回调;在候选校验前触发,失败摘要仍计消耗。 */
|
|
749
980
|
onSummaryUsage?: (attemptId: string, usage: Usage | undefined, modelId: string) => Promise<void>;
|
|
750
981
|
}
|
|
751
982
|
/** 原始历史与请求视图之间的协调器;不执行工具、Hook 或任何终端操作。 */
|
|
@@ -767,15 +998,21 @@ declare class ContextManager {
|
|
|
767
998
|
/** 添加本次交互终态,使下一次准备的保护范围与恢复后的边界一致。 */
|
|
768
999
|
finishInteraction(terminal: InteractionTerminal): void;
|
|
769
1000
|
/**
|
|
770
|
-
* 最终 Hook
|
|
1001
|
+
* 最终 Hook 之后统一预算;Profile 与请求的更低覆盖同时约束输出预留和实际 maxTokens。
|
|
1002
|
+
* 非法输出配置或输入超限在 Provider 调用前失败;不使用固定 4096 覆盖原生模型上限。
|
|
1003
|
+
* 签名或加密续答可禁止压缩;此时仍估算并拒绝超预算请求,不剪裁历史或调用摘要网络。
|
|
1004
|
+
* @param allowCompaction 是否允许当前请求剪裁/摘要;冻结私有续答前缀时传 false。
|
|
771
1005
|
* @returns 语义事件及准备完成的请求,不改变持久历史。
|
|
772
1006
|
*/
|
|
773
|
-
prepare(history: readonly CanonicalMessage[], request: ModelRequest, profile: ModelProfile, runId?: string, reason?: CompactionReason): AsyncGenerator<SessionEvent, ModelRequest>;
|
|
1007
|
+
prepare(history: readonly CanonicalMessage[], request: ModelRequest, profile: ModelProfile, runId?: string, reason?: CompactionReason, allowCompaction?: boolean): AsyncGenerator<SessionEvent, ModelRequest>;
|
|
774
1008
|
/** 观测真实使用量只作用于对应最终请求,不把累计 usage 当成当前窗口占用。 */
|
|
775
1009
|
observe(request: ModelRequest, usage: Usage, profile: ModelProfile): void;
|
|
776
1010
|
/** 查询已发布快照,不运行 Hook/Provider;配置变化后明确标记 stale。 */
|
|
777
1011
|
getSnapshot(): ContextSnapshot | undefined;
|
|
778
|
-
/**
|
|
1012
|
+
/**
|
|
1013
|
+
* 从当前静态投影估算,不执行 Hook/Provider 或更新状态;恢复后即可查看检查点。
|
|
1014
|
+
* 输出预留与准备请求使用同一 Profile/请求覆盖规则;非法覆盖也在只读检查时失败。
|
|
1015
|
+
*/
|
|
779
1016
|
inspect(history: readonly CanonicalMessage[], request: ModelRequest, profile: ModelProfile): ContextSnapshot;
|
|
780
1017
|
/** 模型或指令发生变化后使已有预算快照过期,直到下一最终请求准备成功。 */
|
|
781
1018
|
invalidate(): void;
|
|
@@ -805,6 +1042,7 @@ declare class ContextManager {
|
|
|
805
1042
|
private report;
|
|
806
1043
|
}
|
|
807
1044
|
|
|
1045
|
+
/** 摘要模型的 JSON 输出契约;只有通过 validateSummary 的实例可进入检查点。 */
|
|
808
1046
|
interface ContextSummary {
|
|
809
1047
|
schemaVersion: 1;
|
|
810
1048
|
goal: string;
|
|
@@ -814,8 +1052,10 @@ interface ContextSummary {
|
|
|
814
1052
|
pendingWork: string[];
|
|
815
1053
|
/** 原消息身份,不接受模型虚构来源或把旧摘要当成授权。 */
|
|
816
1054
|
references: string[];
|
|
1055
|
+
/** 结果未知的副作用记录;保留不确定性,不冒充成功或失败。 */
|
|
817
1056
|
unknownEffects: string[];
|
|
818
1057
|
}
|
|
1058
|
+
/** 一次文件操作的历史观察;只描述曾经发生,不描述文件当前状态。 */
|
|
819
1059
|
interface FileObservation {
|
|
820
1060
|
/** 有执行目录证据时为绝对路径;旧记录缺少依据时为原相对路径,基目录未知。 */
|
|
821
1061
|
path: string;
|
|
@@ -823,11 +1063,14 @@ interface FileObservation {
|
|
|
823
1063
|
toolCallId: string;
|
|
824
1064
|
operation: string;
|
|
825
1065
|
}
|
|
1066
|
+
/** 检查点携带的文件事实:按结果分类的观察列表,每类上限 500 条。 */
|
|
826
1067
|
interface FileDetails {
|
|
827
1068
|
readFiles: FileObservation[];
|
|
828
1069
|
modifiedFiles: FileObservation[];
|
|
829
1070
|
failedFileOperations: FileObservation[];
|
|
1071
|
+
/** 工具结果缺失或 OUTCOME_UNKNOWN 时的操作记录。 */
|
|
830
1072
|
unknownFileOperations: FileObservation[];
|
|
1073
|
+
/** 超出 500 上限被丢弃的观察总数;渲染时与列表截断数合并展示。 */
|
|
831
1074
|
omitted: number;
|
|
832
1075
|
}
|
|
833
1076
|
/** 对超长结果保留总计 2000 code point 首尾正文,省略说明不冒充原始结果。 */
|
|
@@ -846,21 +1089,27 @@ declare function extractFileDetails(history: readonly CanonicalMessage[], _proje
|
|
|
846
1089
|
declare function renderFileDetails(details: FileDetails): string;
|
|
847
1090
|
/** 校验结构与来源;空、超长、未知字段及虚构消息引用不能进入检查点。 */
|
|
848
1091
|
declare function validateSummary(value: unknown, sourceIds: ReadonlySet<string>): ContextSummary;
|
|
1092
|
+
/** 摘要服务配置;router 提供摘要角色绑定,全部 attempt 共享总时限。 */
|
|
849
1093
|
interface SummaryServiceOptions {
|
|
850
1094
|
router: ModelRouter;
|
|
1095
|
+
/** 保留旧 API 形参;项目根不作为历史工具相对路径的推断依据。 */
|
|
851
1096
|
projectRoot: string;
|
|
852
1097
|
estimator?: TokenEstimator;
|
|
853
1098
|
/** 真实使用量在候选校验前记账,失败摘要仍保留消耗;不得包含主任务 TTFT。 */
|
|
854
1099
|
onUsage?: (attemptId: string, usage: Usage | undefined, modelId: string) => Promise<void>;
|
|
1100
|
+
/** 单次 generate 的总时限,生效值不超过 120 秒;超时按摘要失败处理。 */
|
|
855
1101
|
timeoutMs?: number;
|
|
856
1102
|
}
|
|
1103
|
+
/** 一次成功摘要的产出与计量;usage 为本次 generate 全部 attempt 的累计值。 */
|
|
857
1104
|
interface SummaryCandidate {
|
|
858
1105
|
summary: ContextSummary;
|
|
859
1106
|
details: FileDetails;
|
|
1107
|
+
/** 实际发起的摘要模型调用次数;上限 4。 */
|
|
860
1108
|
calls: number;
|
|
861
1109
|
modelId: string;
|
|
862
1110
|
durationMs: number;
|
|
863
1111
|
usage: Usage;
|
|
1112
|
+
/** 任一 attempt 缺失 usage 时为 false,不将缺失消耗伪装为零。 */
|
|
864
1113
|
usageKnown: boolean;
|
|
865
1114
|
}
|
|
866
1115
|
/** 摘要单次流式输出文本最大防御倍数;防止模型无限输出耗尽内存。 */
|
|
@@ -873,12 +1122,16 @@ declare class SummaryService {
|
|
|
873
1122
|
/**
|
|
874
1123
|
* 按完整用户交互分批,以旧摘要和新增原始前缀取材;中间结果只是局部候选,不激活。
|
|
875
1124
|
* 单个不可拆分输入超预算、无终态、截断或非法来源均失败,取消先关闭 Provider 迭代。
|
|
1125
|
+
* 摘要输出独立限制为 4096,并受 Profile 更低覆盖及窗口约束;非法 Profile 预算先失败。
|
|
876
1126
|
*/
|
|
877
1127
|
generate(history: readonly CanonicalMessage[], previous?: Pick<SummaryCandidate, 'summary' | 'details'>, signal?: AbortSignal): Promise<SummaryCandidate>;
|
|
878
1128
|
}
|
|
879
1129
|
|
|
1130
|
+
/** 事件严重度;debug / trace 仅在 StructuredLogger 显式开启 debug 时写入。 */
|
|
880
1131
|
type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error';
|
|
1132
|
+
/** 事件通道:operation 为运行日志,audit 为审批与操作审计;两者持久化保证与保留策略不同。 */
|
|
881
1133
|
type LogChannel = 'operation' | 'audit';
|
|
1134
|
+
/** 允许落盘的字段值类型;复杂结构必须先降维为标量或受控摘要。 */
|
|
882
1135
|
type LogField = string | number | boolean | null;
|
|
883
1136
|
/** 单条可持久化的脱敏运行或审计事件。 */
|
|
884
1137
|
interface LogEvent {
|
|
@@ -898,6 +1151,7 @@ interface LogEvent {
|
|
|
898
1151
|
interface LogSink {
|
|
899
1152
|
write(event: LogEvent): Promise<void>;
|
|
900
1153
|
}
|
|
1154
|
+
/** 调用方提供的宽松输入;fields 仅白名单字段经脱敏校验后进入 LogEvent。 */
|
|
901
1155
|
interface LogInput {
|
|
902
1156
|
level: LogLevel;
|
|
903
1157
|
event: string;
|
|
@@ -954,11 +1208,17 @@ declare class StructuredLogger implements EventLogger {
|
|
|
954
1208
|
private format;
|
|
955
1209
|
}
|
|
956
1210
|
|
|
1211
|
+
/** FileLogSink 的构造项;保留与落盘策略按通道强制,调用方传值不能放宽。 */
|
|
957
1212
|
interface FileLogSinkOptions {
|
|
1213
|
+
/** 日志目录;不存在时按 0o700 创建。 */
|
|
958
1214
|
directory: string;
|
|
1215
|
+
/** 通道前缀,同时决定文件名与保留、同步策略。 */
|
|
959
1216
|
prefix: 'operation' | 'audit';
|
|
1217
|
+
/** 单文件字节上限,超出后换下一个序号文件;缺省 10MB。 */
|
|
960
1218
|
maxBytes?: number;
|
|
1219
|
+
/** 按天保留的天数;仅 operation 通道生效,audit 恒为长期保留。 */
|
|
961
1220
|
retentionDays?: number;
|
|
1221
|
+
/** 每条写入后强制 fsync;audit 通道强制开启。 */
|
|
962
1222
|
sync?: boolean;
|
|
963
1223
|
}
|
|
964
1224
|
/** 将每条 JSONL 事件完整追加到本地文件,并按日期及文件大小轮转。 */
|
|
@@ -972,7 +1232,9 @@ declare class FileLogSink implements LogSink {
|
|
|
972
1232
|
write(event: LogEvent): Promise<void>;
|
|
973
1233
|
/** 返回该通道已占用的字节数,供宿主提示长期保留的审计用量。 */
|
|
974
1234
|
getUsageBytes(): number;
|
|
1235
|
+
/** 优先写入当天未满的最后一个序号文件,超限或无同名文件时开下一个序号。 */
|
|
975
1236
|
private chooseFile;
|
|
1237
|
+
/** 按文件名中的日期删除早于保留期的自有文件;删除依据文件名而非文件 mtime。 */
|
|
976
1238
|
private cleanupExpired;
|
|
977
1239
|
private isOwnedFile;
|
|
978
1240
|
}
|
|
@@ -984,25 +1246,38 @@ declare function createDefaultLogSinks(baseDirectory?: string): {
|
|
|
984
1246
|
/** 启动时保守关闭上次进程未完成的审计事务,绝不将其当作未执行或自动重试。 */
|
|
985
1247
|
declare function recoverIncompleteAudit(directory: string): Promise<number>;
|
|
986
1248
|
|
|
1249
|
+
/** 单个通过全部校验的指令文件;path 为去重后的候选路径,content 是严格 UTF-8 解码的全文。 */
|
|
987
1250
|
interface InstructionSource {
|
|
988
1251
|
path: string;
|
|
989
1252
|
content: string;
|
|
990
1253
|
}
|
|
1254
|
+
/** 一次成功加载的完整结果;sources 按「用户层 → 项目根 → 逐级子目录」顺序排列。 */
|
|
991
1255
|
interface InstructionSnapshot {
|
|
992
1256
|
sources: readonly InstructionSource[];
|
|
1257
|
+
/** 全部来源实际字节数之和(以读取结果为准),供调用方审计体积预算。 */
|
|
993
1258
|
totalBytes: number;
|
|
994
1259
|
}
|
|
995
1260
|
interface InstructionLoadOptions {
|
|
1261
|
+
/** 目录链上界;cwd 必须位于其内,越界直接失败而不是静默截断链。 */
|
|
996
1262
|
projectRoot: string;
|
|
1263
|
+
/** 指令收集的终点目录;相对 projectRoot 的每一层都会尝试读取 AGENTS.md。 */
|
|
997
1264
|
cwd: string;
|
|
1265
|
+
/** 用户层指令文件;缺省为 ~/.kapibala/AGENTS.md,与项目层同路径时去重。 */
|
|
998
1266
|
userFile?: string;
|
|
999
1267
|
}
|
|
1000
|
-
/**
|
|
1268
|
+
/**
|
|
1269
|
+
* 按用户层和项目根至 cwd 的目录链读取指令,全部成功后才返回快照。
|
|
1270
|
+
* 所有路径统一用 native 语义解析(与 resolveSessionProject 的 projectRoot 对齐):JS realpath
|
|
1271
|
+
* 不展开 Windows 8.3 短名(CI 临时目录形如 RUNNER~1),混用会让包含性检查把同一目录误判越界、
|
|
1272
|
+
* 让去重错过同一文件;返回的 source 路径因此是 canonical 形式,调用方按 canonical 比较。
|
|
1273
|
+
*/
|
|
1001
1274
|
declare function loadInstructions(options: InstructionLoadOptions): InstructionSnapshot;
|
|
1002
1275
|
|
|
1276
|
+
/** 受支持的解释器家族;wsl 是 Windows 上的 WSL bash launcher,路径与输出语义与 native bash 不同。 */
|
|
1003
1277
|
type ShellKind = 'bash' | 'wsl' | 'pwsh' | 'powershell';
|
|
1004
1278
|
/** auto / 具名解释器,或用户显式提供的解释器可执行文件全路径。 */
|
|
1005
1279
|
type ShellPreference = 'auto' | ShellKind | (string & {});
|
|
1280
|
+
/** 探测成功后固定的解释器身份;executableDigest 参与命令审批指纹,解释器被替换即失配。 */
|
|
1006
1281
|
interface ShellEnvironment {
|
|
1007
1282
|
kind: ShellKind;
|
|
1008
1283
|
executable: string;
|
|
@@ -1010,8 +1285,11 @@ interface ShellEnvironment {
|
|
|
1010
1285
|
cwd: string;
|
|
1011
1286
|
}
|
|
1012
1287
|
interface ShellDetectOptions {
|
|
1288
|
+
/** 'auto'、具名解释器,或解释器可执行文件全路径;含路径分隔符或 .exe 后缀按显式路径处理。 */
|
|
1013
1289
|
preference?: ShellPreference;
|
|
1290
|
+
/** 探测与后续执行的基准目录;探测前先取 realpath,符号链接会被展开。 */
|
|
1014
1291
|
cwd: string;
|
|
1292
|
+
/** 以下两项供测试注入平台与 PATH;缺省取当前进程的值。 */
|
|
1015
1293
|
platform?: NodeJS.Platform;
|
|
1016
1294
|
pathEnv?: string;
|
|
1017
1295
|
}
|
|
@@ -1029,57 +1307,81 @@ declare function detectShell(options: ShellDetectOptions): ShellEnvironment;
|
|
|
1029
1307
|
|
|
1030
1308
|
/** 本次会话的自动执行边界;FullAccess 只能由宿主为本次会话显式选择。 */
|
|
1031
1309
|
type SessionMode = 'Approval' | 'Plan' | 'Auto' | 'FullAccess';
|
|
1310
|
+
/** 规则动作与裁决结果共用同一词表;ask 表示交人工审批,不是放行。 */
|
|
1032
1311
|
type PermissionAction = 'allow' | 'ask' | 'deny';
|
|
1312
|
+
/** 一次 Shell 执行的精确目标;字段组合构成审批与缓存命中的身份,任何维度都不允许通配。 */
|
|
1033
1313
|
interface ShellScope {
|
|
1034
1314
|
command: string;
|
|
1035
1315
|
interpreter: string;
|
|
1036
1316
|
executablePath?: string;
|
|
1037
1317
|
cwd: string;
|
|
1318
|
+
/** 解释器身份摘要(路径、大小、mtime 推导);解释器被替换后规则与缓存即失配。 */
|
|
1038
1319
|
executableDigest?: string;
|
|
1320
|
+
/** 命令直接引用的工作目录内脚本的内容摘要;仅单脚本命令可计算,组合命令缺省。 */
|
|
1039
1321
|
scriptDigest?: string;
|
|
1322
|
+
/** 执行前复核用指纹;审批后重新推导不一致时按目标漂移拒绝执行。 */
|
|
1040
1323
|
executionFingerprint?: string;
|
|
1041
1324
|
}
|
|
1325
|
+
/** 宿主提供的显式规则;tool / capability / shell 三种范围必须恰好声明一个。 */
|
|
1042
1326
|
interface PermissionRule {
|
|
1043
1327
|
action: PermissionAction;
|
|
1044
1328
|
tool?: string;
|
|
1045
1329
|
capability?: Capability;
|
|
1046
1330
|
shell?: ShellScope;
|
|
1047
1331
|
}
|
|
1332
|
+
/** 权限裁决的全部输入;硬限制与缓存命中由宿主查询后以标志位传入,策略本身不持有状态。 */
|
|
1048
1333
|
interface PermissionRequest {
|
|
1049
1334
|
mode: SessionMode;
|
|
1050
1335
|
toolName: string;
|
|
1051
1336
|
capabilities: readonly Capability[];
|
|
1337
|
+
/** 危险性来自工具元数据;未命中 allow 规则时,非 FullAccess 模式一律降级为 ask。 */
|
|
1052
1338
|
dangerous?: boolean;
|
|
1339
|
+
/** 宿主硬限制;命中即拒绝,优先级高于一切规则与缓存。 */
|
|
1053
1340
|
hardDenied?: boolean;
|
|
1054
1341
|
shell?: ShellScope;
|
|
1342
|
+
/** 规则表须先经 validatePermissionRules 校验;同动作规则按声明顺序取首个命中。 */
|
|
1055
1343
|
rules?: readonly PermissionRule[];
|
|
1344
|
+
/** 会话缓存命中标志(来自 SessionApprovalCache);仅在 deny / ask 规则都未命中时生效。 */
|
|
1056
1345
|
cachedApproval?: boolean;
|
|
1346
|
+
/** 会话缓存拒绝标志;在 deny 规则之后、ask 规则之前生效。 */
|
|
1057
1347
|
cachedDenial?: boolean;
|
|
1058
1348
|
}
|
|
1349
|
+
/** 裁决结果及其来源;source 供审计区分硬限制、Plan、规则、缓存与模式默认。 */
|
|
1059
1350
|
interface PermissionDecision {
|
|
1060
1351
|
decision: PermissionAction;
|
|
1061
1352
|
source: 'hard_limit' | 'plan' | 'explicit_rule' | 'session_cache' | 'mode_default';
|
|
1353
|
+
/** 命中规则在 rules 中的下标;仅 source 为 explicit_rule 时存在。 */
|
|
1062
1354
|
ruleIndex?: number;
|
|
1063
1355
|
}
|
|
1064
1356
|
/** 拒绝含糊的 Shell 前缀/通配符和结构不完整的规则。 */
|
|
1065
1357
|
declare function validatePermissionRules(rules: readonly PermissionRule[]): void;
|
|
1066
1358
|
/** 纯策略裁决;宿主硬限制和 Plan 始终先于任何规则或会话缓存。 */
|
|
1067
1359
|
declare class PermissionPolicy {
|
|
1360
|
+
/**
|
|
1361
|
+
* 裁决顺序固定:硬限制 → Plan 收窄 → deny 规则 → 会话缓存拒绝 → ask 规则 →
|
|
1362
|
+
* 会话缓存允许 → allow 规则(run_command 必须带 shell 范围,工具级 allow 不能放行命令)
|
|
1363
|
+
* → 模式默认。同一输入总是得到同一裁决,不读取任何外部状态。
|
|
1364
|
+
*/
|
|
1068
1365
|
decide(request: PermissionRequest): PermissionDecision;
|
|
1069
1366
|
}
|
|
1070
1367
|
/** 只向模型展示当前模式与整项拒绝规则允许请求的工具。 */
|
|
1071
1368
|
declare function visibleTools(tools: readonly Tool[], mode: SessionMode, rules?: readonly PermissionRule[]): Tool[];
|
|
1072
1369
|
|
|
1370
|
+
/** 执行能力的最小分类;权限规则、模式裁决与工具元数据声明共用这一词汇表。 */
|
|
1073
1371
|
type Capability = 'fs:read' | 'fs:write' | 'exec' | 'net:outbound' | 'env:read' | 'agent:spawn';
|
|
1074
1372
|
interface ToolMetadata {
|
|
1373
|
+
/** 注册来源标记(如 'builtin');注册表据此执行冲突策略并支持按源注销。 */
|
|
1075
1374
|
source?: string;
|
|
1375
|
+
/** 标记危险工具;未命中 allow 规则时,非 FullAccess 模式一律降级为 ask 而非按模式默认放行。 */
|
|
1076
1376
|
dangerous?: boolean;
|
|
1077
1377
|
/** 所需能力的声明;v0.0.1 不据此授权,v0.0.2 的执行前权限决策才会消费。 */
|
|
1078
1378
|
permissions?: Capability[];
|
|
1079
1379
|
/** 工具自身等待进程资源回收,执行器不可再使用通用 Promise.race 超时。 */
|
|
1080
1380
|
managesTimeout?: boolean;
|
|
1081
1381
|
}
|
|
1382
|
+
/** 工具执行期由宿主注入的运行环境;信号取消后工具应尽快清理在途资源再返回。 */
|
|
1082
1383
|
interface ToolContext {
|
|
1384
|
+
/** 本次执行的沙箱根目录;文件类工具以此为界解析相对路径并拒绝越界。 */
|
|
1083
1385
|
rootDir: string;
|
|
1084
1386
|
signal?: AbortSignal;
|
|
1085
1387
|
logger?: (message: string) => void;
|
|
@@ -1090,29 +1392,41 @@ interface ToolContext {
|
|
|
1090
1392
|
outputBytes: number;
|
|
1091
1393
|
}) => void;
|
|
1092
1394
|
}
|
|
1395
|
+
/** 工具契约;parameters 是 JSON Schema,模型只能看到经 toToolDefinition 投影后的三个字段。 */
|
|
1093
1396
|
interface Tool<TInput = Record<string, unknown>, TOutput = unknown> {
|
|
1094
1397
|
readonly name: string;
|
|
1095
1398
|
readonly description: string;
|
|
1096
1399
|
readonly parameters: Record<string, unknown>;
|
|
1097
1400
|
readonly metadata?: ToolMetadata;
|
|
1401
|
+
/** 声明本次输入的精确执行目标,供审批展示与执行前指纹复核;无固定执行目标的工具不实现。 */
|
|
1098
1402
|
approvalScope?(input: TInput, rootDir: string): ShellScope;
|
|
1099
1403
|
execute(input: TInput, ctx: ToolContext): Promise<TOutput>;
|
|
1100
1404
|
}
|
|
1405
|
+
/** 恒等构造器:只为工具实现提供类型推断与统一书写形式,不产生任何运行时包装。 */
|
|
1101
1406
|
declare function defineTool<TInput = Record<string, unknown>, TOutput = unknown>(tool: Tool<TInput, TOutput>): Tool<TInput, TOutput>;
|
|
1407
|
+
/** 投影为模型可见的工具描述;刻意丢弃 metadata 与 approvalScope,执行侧信息不进入协议。 */
|
|
1102
1408
|
declare function toToolDefinition(tool: Tool): ToolDefinition;
|
|
1103
1409
|
|
|
1410
|
+
/** run_command 的输入;cwd 相对工作区根解析,timeout_ms 合法区间 1..600000,越界在执行前失败。 */
|
|
1104
1411
|
interface RunCommandInput {
|
|
1105
1412
|
[key: string]: unknown;
|
|
1106
1413
|
command: string;
|
|
1107
1414
|
cwd?: string;
|
|
1108
1415
|
timeout_ms?: number;
|
|
1109
1416
|
}
|
|
1417
|
+
/** 命令执行结果;output 只是内联前缀,完整输出超过内联上限的部分落盘为受管结果文件。 */
|
|
1110
1418
|
interface CommandResult {
|
|
1419
|
+
/** 进程正常退出时的退出码;被信号终止时为 null。 */
|
|
1111
1420
|
exitCode: number | null;
|
|
1421
|
+
/** stdout 与 stderr 交错合并的文本,最多前 64 KiB(按 UTF-8 字符边界截断)。 */
|
|
1112
1422
|
output: string;
|
|
1423
|
+
/** output 并非全部输出的标志;超出内联上限的完整内容写入 outputFile。 */
|
|
1113
1424
|
outputTruncated: boolean;
|
|
1425
|
+
/** 受管结果文件路径(工作区内 .kapibala/tool-results/),仅输出超过内联上限时存在。 */
|
|
1114
1426
|
outputFile?: string;
|
|
1427
|
+
/** 结果文件触及 16 MiB 上限后被截断的标志。 */
|
|
1115
1428
|
outputFileTruncated: boolean;
|
|
1429
|
+
/** 两个流产生的原始字节总数(不受截断影响),供进度与审计使用。 */
|
|
1116
1430
|
outputBytes: number;
|
|
1117
1431
|
shell: ShellEnvironment['kind'];
|
|
1118
1432
|
}
|
|
@@ -1121,6 +1435,7 @@ declare function cleanupCommandResults(rootDir: string, now?: number): void;
|
|
|
1121
1435
|
/** 使用固定解释器执行命令;超时和中止必须先处理进程树再返回。 */
|
|
1122
1436
|
declare function createRunCommandTool(environment: ShellEnvironment): Tool<RunCommandInput, CommandResult>;
|
|
1123
1437
|
|
|
1438
|
+
/** 路径沙箱配置;rootDir 是所有文件访问的词法与物理边界。 */
|
|
1124
1439
|
interface SandboxConfig {
|
|
1125
1440
|
rootDir: string;
|
|
1126
1441
|
/**
|
|
@@ -1129,6 +1444,10 @@ interface SandboxConfig {
|
|
|
1129
1444
|
*/
|
|
1130
1445
|
allowSymlinks?: boolean;
|
|
1131
1446
|
}
|
|
1447
|
+
/**
|
|
1448
|
+
* 把文件访问限制在 rootDir 内:先做词法归一化检查,再展开符号链接做物理检查,两层都通过才放行。
|
|
1449
|
+
* 实例会缓存 rootDir 的物理路径,应按 rootDir 复用实例,而不是每次调用新建。
|
|
1450
|
+
*/
|
|
1132
1451
|
declare class PathSandbox {
|
|
1133
1452
|
readonly rootDir: string;
|
|
1134
1453
|
readonly allowSymlinks: boolean;
|
|
@@ -1158,6 +1477,11 @@ declare class PathSandbox {
|
|
|
1158
1477
|
private toPhysicalPath;
|
|
1159
1478
|
}
|
|
1160
1479
|
|
|
1480
|
+
/**
|
|
1481
|
+
* 人工审批的五选一结果。allow_once / deny_once 只作用于本次执行;
|
|
1482
|
+
* allow_session / deny_session 由执行器按精确调用范围写入会话缓存(allow_session 还要求请求允许会话级缓存);
|
|
1483
|
+
* cancel 表示放弃审批,一律拒绝且绝不进入缓存。
|
|
1484
|
+
*/
|
|
1161
1485
|
type ApprovalChoice = 'allow_once' | 'allow_session' | 'deny_once' | 'deny_session' | 'cancel';
|
|
1162
1486
|
/** 宿主展示实际执行目标并取得人工选择;无通道视为非交互拒绝。 */
|
|
1163
1487
|
interface ApprovalRequest {
|
|
@@ -1166,8 +1490,10 @@ interface ApprovalRequest {
|
|
|
1166
1490
|
input: Record<string, unknown>;
|
|
1167
1491
|
rootDir: string;
|
|
1168
1492
|
shell?: ShellScope;
|
|
1493
|
+
/** 宿主是否允许本次请求写入会话级允许缓存;deny_session 的缓存不受此限制。 */
|
|
1169
1494
|
sessionAllowed: boolean;
|
|
1170
1495
|
}
|
|
1496
|
+
/** 宿主实现的审批入口;未提供通道时执行器按非交互直接拒绝,通道抛错视同 cancel。 */
|
|
1171
1497
|
interface ApprovalChannel {
|
|
1172
1498
|
requestApproval(request: ApprovalRequest, signal?: AbortSignal): Promise<ApprovalChoice>;
|
|
1173
1499
|
}
|
|
@@ -1181,7 +1507,12 @@ declare class SessionApprovalCache {
|
|
|
1181
1507
|
set(request: ApprovalRequest, choice: 'allow' | 'deny'): void;
|
|
1182
1508
|
}
|
|
1183
1509
|
|
|
1510
|
+
/** 同名工具冲突策略:error 直接抛错;prefer-builtin 保留既有内置注册;prefer-last 后到者覆盖。 */
|
|
1184
1511
|
type ConflictPolicy = 'error' | 'prefer-builtin' | 'prefer-last';
|
|
1512
|
+
/**
|
|
1513
|
+
* 按名称索引的工具注册表。冲突按构造时给定的策略处理,胜出条目的来源标签保持不变;
|
|
1514
|
+
* 来源标签支持按源批量注册与注销,注销只移除以该标签注册的工具,不回收冲突中保留的内置实现。
|
|
1515
|
+
*/
|
|
1185
1516
|
declare class ToolRegistry {
|
|
1186
1517
|
private readonly tools;
|
|
1187
1518
|
private readonly toolSources;
|
|
@@ -1195,6 +1526,7 @@ declare class ToolRegistry {
|
|
|
1195
1526
|
registerSource(source: string, tools: Tool[]): void;
|
|
1196
1527
|
unregisterSource(source: string): void;
|
|
1197
1528
|
get(name: string): Tool | undefined;
|
|
1529
|
+
/** 未命中时抛 ToolNotFound,并携带当前全部可用名称辅助模型自纠。 */
|
|
1198
1530
|
resolve(name: string): Tool;
|
|
1199
1531
|
list(): Tool[];
|
|
1200
1532
|
definitions(): ToolDefinition[];
|
|
@@ -1222,6 +1554,7 @@ declare const grepTool: Tool<{
|
|
|
1222
1554
|
pattern: string;
|
|
1223
1555
|
path?: string;
|
|
1224
1556
|
}, string>;
|
|
1557
|
+
/** 五个内置文件工具的聚合;全部经 PathSandbox 校验,路径越界或符号链接穿透一律拒绝。 */
|
|
1225
1558
|
declare const builtinTools: (Tool<{
|
|
1226
1559
|
path: string;
|
|
1227
1560
|
startLine?: number;
|
|
@@ -1241,11 +1574,22 @@ declare const builtinTools: (Tool<{
|
|
|
1241
1574
|
path?: string;
|
|
1242
1575
|
}, string>)[];
|
|
1243
1576
|
|
|
1577
|
+
/**
|
|
1578
|
+
* 运行时钩子契约:宿主与插件在固定切点观察或调整流程。
|
|
1579
|
+
* 通知型切点由 HookRegistry.emit 串行触发;需要返回值的 model:before / tool:before
|
|
1580
|
+
* 由执行方(AgentLoop / ToolExecutor)自行遍历并消费返回值。
|
|
1581
|
+
*/
|
|
1582
|
+
/** 钩子切点;session:start / session:end 由会话初始化与销毁触发,其余在单次交互流程内触发。 */
|
|
1244
1583
|
type HookPoint = 'session:start' | 'session:end' | 'model:before' | 'model:after' | 'tool:before' | 'tool:after' | 'error';
|
|
1584
|
+
/** 传给每个钩子的运行上下文;signal 与当前执行的取消联动,未提供表示该切点不可取消。 */
|
|
1245
1585
|
interface HookContext {
|
|
1246
1586
|
readonly signal?: AbortSignal;
|
|
1247
1587
|
readonly logger?: (msg: string) => void;
|
|
1248
1588
|
}
|
|
1589
|
+
/**
|
|
1590
|
+
* tool:before 的裁决结果:continue 放行;skip 不执行工具,以 result 作为工具结果落盘;
|
|
1591
|
+
* modify 用替换后的入参继续(仍会经过后续权限裁决,不构成绕过审批的通道)。
|
|
1592
|
+
*/
|
|
1249
1593
|
type ToolDecision = {
|
|
1250
1594
|
action: 'continue';
|
|
1251
1595
|
} | {
|
|
@@ -1256,10 +1600,12 @@ type ToolDecision = {
|
|
|
1256
1600
|
action: 'modify';
|
|
1257
1601
|
input: Record<string, unknown>;
|
|
1258
1602
|
};
|
|
1603
|
+
/** 各切点的处理器签名;未注册的切点直接跳过,处理器抛出的异常向上传播。 */
|
|
1259
1604
|
interface HookHandlers {
|
|
1260
1605
|
'session:start'?: (ctx: HookContext) => void | Promise<void>;
|
|
1261
1606
|
'session:end'?: (ctx: HookContext) => void | Promise<void>;
|
|
1262
1607
|
'model:before'?: (ctx: HookContext, req: ModelRequest) => ModelRequest | Promise<ModelRequest>;
|
|
1608
|
+
/** 收到的是即将进入历史的完整 assistant 消息;执行方会校验钩子未改动身份与受保护内容。 */
|
|
1263
1609
|
'model:after'?: (ctx: HookContext, res: {
|
|
1264
1610
|
message: CanonicalMessage;
|
|
1265
1611
|
}) => void | Promise<void>;
|
|
@@ -1279,30 +1625,44 @@ interface HookHandlers {
|
|
|
1279
1625
|
error?: (ctx: HookContext, err: Error) => void | Promise<void>;
|
|
1280
1626
|
}
|
|
1281
1627
|
|
|
1628
|
+
/** 按切点收集钩子的有序注册表;同一处理器可注册多次,触发时按注册顺序执行。 */
|
|
1282
1629
|
declare class HookRegistry {
|
|
1283
1630
|
private readonly hooks;
|
|
1631
|
+
/** 注册到指定切点;不查重,触发顺序即注册顺序。 */
|
|
1284
1632
|
on<K extends HookPoint>(point: K, handler: NonNullable<HookHandlers[K]>): void;
|
|
1633
|
+
/** 返回该切点的处理器列表(无注册时为空数组);数组为内部引用,调用方不应修改。 */
|
|
1285
1634
|
get<K extends HookPoint>(point: K): Array<NonNullable<HookHandlers[K]>>;
|
|
1635
|
+
/**
|
|
1636
|
+
* 串行 await 通知型切点的全部处理器;任一抛错立即中断并向调用方传播。
|
|
1637
|
+
* 需要返回值的 model:before / tool:before 不经 emit,由执行方自行遍历。
|
|
1638
|
+
*/
|
|
1286
1639
|
emit<K extends 'session:start' | 'session:end' | 'model:after' | 'tool:after' | 'error'>(point: K, ctx: HookContext, ...args: any[]): Promise<void>;
|
|
1287
1640
|
}
|
|
1288
1641
|
|
|
1642
|
+
/** setup 收到的能力入口;tools / hooks 是会话共享的注册表,注册的条目影响后续所有执行。 */
|
|
1289
1643
|
interface PluginContext {
|
|
1290
1644
|
readonly tools: ToolRegistry;
|
|
1291
1645
|
readonly hooks: HookRegistry;
|
|
1646
|
+
/** 本次会话的绝对工具根目录;工具的路径解析与审批都以此为基准。 */
|
|
1292
1647
|
readonly rootDir: string;
|
|
1293
1648
|
readonly logger?: (msg: string) => void;
|
|
1294
1649
|
}
|
|
1650
|
+
/** 插件生命周期:setup 在会话空闲时挂载执行一次,teardown 在会话销毁时逐个调用以回收资源。 */
|
|
1295
1651
|
interface AgentPlugin {
|
|
1652
|
+
/** 用于挂载失败与 teardown 的诊断信息。 */
|
|
1296
1653
|
readonly name: string;
|
|
1297
1654
|
readonly version?: string;
|
|
1298
1655
|
setup(ctx: PluginContext): void | Promise<void>;
|
|
1299
1656
|
teardown?(): void | Promise<void>;
|
|
1300
1657
|
}
|
|
1301
1658
|
|
|
1659
|
+
/** ToolExecutor 的构造项;审计写入需要 eventLogger 与 sessionId 同时提供,否则不产生审计。 */
|
|
1302
1660
|
interface ExecutorOptions {
|
|
1303
1661
|
tools: ToolRegistry;
|
|
1304
1662
|
hooks: HookRegistry;
|
|
1663
|
+
/** 工具执行的绝对根目录;路径解析与审批均以此为基准。 */
|
|
1305
1664
|
rootDir: string;
|
|
1665
|
+
/** 会话级取消信号;与 cancel() 的内部信号合并生效。 */
|
|
1306
1666
|
signal?: AbortSignal;
|
|
1307
1667
|
logger?: (msg: string) => void;
|
|
1308
1668
|
/** 单次工具执行超时(毫秒)。异步挂起的工具超时后返回 isError 结果,避免永久卡死会话循环 */
|
|
@@ -1310,11 +1670,19 @@ interface ExecutorOptions {
|
|
|
1310
1670
|
eventLogger?: EventLogger;
|
|
1311
1671
|
sessionId?: string;
|
|
1312
1672
|
runId?: string;
|
|
1673
|
+
/** 固定模式或每次裁决时读取的取值函数;宿主可中途切换。 */
|
|
1313
1674
|
mode?: SessionMode | (() => SessionMode);
|
|
1314
1675
|
permissionRules?: readonly PermissionRule[];
|
|
1676
|
+
/** 审批入口;缺省视为非交互环境,需要询问的调用一律拒绝。 */
|
|
1315
1677
|
approvalChannel?: ApprovalChannel;
|
|
1678
|
+
/** 会话内 allow_session / deny_session 审批缓存;缺省使用实例私有缓存。 */
|
|
1316
1679
|
approvalCache?: SessionApprovalCache;
|
|
1317
1680
|
}
|
|
1681
|
+
/**
|
|
1682
|
+
* 工具执行器:按「审计 → 钩子裁决 → 权限裁决 → 执行 → 结果闭合」处理单次调用。
|
|
1683
|
+
* 所有拒绝与异常都闭合为 isError 的工具结果,不向调用方抛出;
|
|
1684
|
+
* 同一 run 内参数完全相同的 never 失败会被拒绝重复执行。
|
|
1685
|
+
*/
|
|
1318
1686
|
declare class ToolExecutor {
|
|
1319
1687
|
private readonly tools;
|
|
1320
1688
|
private readonly hooks;
|
|
@@ -1335,6 +1703,7 @@ declare class ToolExecutor {
|
|
|
1335
1703
|
constructor(options: ExecutorOptions);
|
|
1336
1704
|
/** 中止本轮正在等待或执行的工具;调用方仍须等待 runAll 完成资源回收及结果审计。 */
|
|
1337
1705
|
cancel(): void;
|
|
1706
|
+
/** 串行执行全部调用并返回与入参顺序一致的结果;某个结果要求用户介入后,其余调用直接拒绝。 */
|
|
1338
1707
|
runAll(calls: ToolUseBlock[], onProgress?: (event: {
|
|
1339
1708
|
id: string;
|
|
1340
1709
|
name: string;
|
|
@@ -1362,6 +1731,7 @@ declare class ToolExecutor {
|
|
|
1362
1731
|
private withTimeout;
|
|
1363
1732
|
}
|
|
1364
1733
|
|
|
1734
|
+
/** Chat 端点配置;能力覆盖只改变请求字段和完成边界,不改变协议身份。 */
|
|
1365
1735
|
interface OpenAIProviderOptions {
|
|
1366
1736
|
baseURL: string;
|
|
1367
1737
|
apiKey: string;
|
|
@@ -1369,34 +1739,150 @@ interface OpenAIProviderOptions {
|
|
|
1369
1739
|
supportsThinking?: boolean;
|
|
1370
1740
|
/** 回传 assistant 思考历史;默认仅为 DeepSeek 官方端点启用,自建兼容网关可显式开启。 */
|
|
1371
1741
|
replayReasoningContent?: boolean;
|
|
1742
|
+
/** 显式端点能力;缺省保留 max_tokens、usage 和 temperature 请求基线,要求 DONE。 */
|
|
1743
|
+
chatCapabilities?: ChatCapabilities;
|
|
1372
1744
|
/** 建立 HTTP 连接(收到响应头)的超时毫秒数;仅约束建连阶段,不限制流式读取总时长 */
|
|
1373
1745
|
connectTimeoutMs?: number;
|
|
1374
1746
|
}
|
|
1747
|
+
/** 将 canonical 历史投影为 Chat 请求,在完整终态和全部工具验证后交付可执行结果。 */
|
|
1375
1748
|
declare class OpenAICompatibleProvider implements ModelProvider {
|
|
1376
1749
|
readonly name = "openai-compatible";
|
|
1377
1750
|
readonly baseURL: string;
|
|
1378
1751
|
readonly apiKey: string;
|
|
1752
|
+
/** 未提供凭据时由 Session 在记录用户消息前拒绝请求。 */
|
|
1753
|
+
get credentialsReady(): boolean;
|
|
1379
1754
|
readonly modelName: string;
|
|
1380
1755
|
readonly supportsThinking: boolean;
|
|
1381
1756
|
readonly replayReasoningContent: boolean;
|
|
1382
1757
|
readonly connectTimeoutMs: number;
|
|
1383
|
-
|
|
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
|
+
*/
|
|
1384
1769
|
constructor(options: OpenAIProviderOptions);
|
|
1385
|
-
/**
|
|
1770
|
+
/**
|
|
1771
|
+
* 发送 Chat 流式请求;默认同时要求合法 finish_reason 和 DONE,只有显式例外允许完整 EOF。
|
|
1772
|
+
* 全部工具的 ID、名称和对象参数在任何完成事件之前校验;截断、过滤或中断不交付工具。
|
|
1773
|
+
* @param req canonical 历史、工具、预算与取消信号;能力覆盖来自端点配置。
|
|
1774
|
+
* @returns 文本、可见思考和工具增量,完整响应最后产生 message_stop。
|
|
1775
|
+
* @throws ModelError 响应缺少合法终态、工具身份或完整对象参数时失败,不自动重放请求。
|
|
1776
|
+
*/
|
|
1386
1777
|
create(req: ModelRequest): AsyncIterable<ModelEvent>;
|
|
1778
|
+
/**
|
|
1779
|
+
* 将工具结果装配为 canonical tool 消息,wire 角色仅在下一请求投影时转换。
|
|
1780
|
+
* @param results 已完成的工具结果,保持调用 ID 与内容,不重放工具。
|
|
1781
|
+
* @returns 逐条克隆的 canonical tool 消息,允许消息级落盘。
|
|
1782
|
+
*/
|
|
1387
1783
|
assembleToolResults(results: ToolResultBlock[]): CanonicalMessage[];
|
|
1388
|
-
/**
|
|
1784
|
+
/**
|
|
1785
|
+
* 将历史投影为 Chat 消息;合并连续 user,剔除空 assistant,保持工具调用与结果身份。
|
|
1786
|
+
* 仅显式允许的端点回传可见思考;签名、脱敏思考和原生私有 Item 不适用于 Chat。
|
|
1787
|
+
* @param messages canonical 历史;只投影文本、可选可见思考和工具语义。
|
|
1788
|
+
* @param systemPrompt 可选全局提示词,去除首尾空白后作为首条 system。
|
|
1789
|
+
* @returns 与输入历史独立的 Chat wire 消息数组。
|
|
1790
|
+
*/
|
|
1389
1791
|
private translateMessagesToWire;
|
|
1390
1792
|
}
|
|
1391
1793
|
|
|
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[];
|
|
1823
|
+
/**
|
|
1824
|
+
* 发送 Messages 流并按索引组装完整内容;增量仅供展示,终态提供有序落盘来源。
|
|
1825
|
+
* maxTokens 包含思考消耗,缺省为 4096;缺终态、坏参数与服务端流错误均抛错。
|
|
1826
|
+
* pause_turn 表示服务端工具暂停;当前不支持其续答,明确失败而非报告完成或调度客户端工具。
|
|
1827
|
+
* 同 run/模型/端点的来源校验允许私有续答;来源不匹配的可见思考降为普通文字。
|
|
1828
|
+
* 取消或消费者提前结束会等待 reader 清理并解除 HTTP 取消监听,不自动重发请求。
|
|
1829
|
+
*/
|
|
1830
|
+
create(req: ModelRequest): AsyncIterable<ModelEvent>;
|
|
1831
|
+
/**
|
|
1832
|
+
* 投影 system、普通内容与工具结果;连续结果合并为下一 user 内容并置于文字之前。
|
|
1833
|
+
* 私有块由共享来源规则筛选,原始消息和工具 ID 不被改写;不发送能力标签推测的思考参数。
|
|
1834
|
+
*/
|
|
1835
|
+
private createPayload;
|
|
1836
|
+
}
|
|
1837
|
+
|
|
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;
|
|
1867
|
+
}
|
|
1868
|
+
|
|
1392
1869
|
interface PromptAssemblerOptions {
|
|
1870
|
+
/** 提供时才生成 L2 工具清单段;缺省表示本次运行不向模型展示任何工具。 */
|
|
1393
1871
|
tools?: ToolRegistry;
|
|
1872
|
+
/** L3 环境段展示的工作区根目录;文件工具的沙箱边界与其保持一致。 */
|
|
1394
1873
|
rootDir: string;
|
|
1395
1874
|
agentName?: string;
|
|
1875
|
+
/** 宿主自定义提示词,插在环境段与 L4 指令之间;纯空白视为未提供。 */
|
|
1396
1876
|
customInstructions?: string;
|
|
1877
|
+
/** L4 项目指令段的内容,来自 loadInstructions 快照;为空时整段省略。 */
|
|
1397
1878
|
instructionSources?: readonly InstructionSource[];
|
|
1879
|
+
/** 覆盖 tools.list() 作为 L2 清单来源;通常传入按权限过滤后的可见工具。 */
|
|
1398
1880
|
visibleTools?: readonly Tool[];
|
|
1399
1881
|
}
|
|
1882
|
+
/**
|
|
1883
|
+
* 把行为规则(L1)、工具清单(L2)、环境(L3)与项目指令(L4)拼装为系统提示词。
|
|
1884
|
+
* 各段之间以 `\n\n---\n\n` 分隔;不提供的内容整段跳过,不做占位填充。
|
|
1885
|
+
*/
|
|
1400
1886
|
declare class PromptAssembler {
|
|
1401
1887
|
private readonly tools?;
|
|
1402
1888
|
private readonly rootDir;
|
|
@@ -1405,6 +1891,7 @@ declare class PromptAssembler {
|
|
|
1405
1891
|
private readonly instructionSources;
|
|
1406
1892
|
private readonly visibleTools?;
|
|
1407
1893
|
constructor(options: PromptAssemblerOptions);
|
|
1894
|
+
/** 按固定层级拼装系统提示词;同一选项集总是产出相同文本,便于审计与缓存。 */
|
|
1408
1895
|
assemble(): string;
|
|
1409
1896
|
private getL1Behavior;
|
|
1410
1897
|
private getL2Tools;
|
|
@@ -1414,27 +1901,41 @@ declare class PromptAssembler {
|
|
|
1414
1901
|
interface AgentLoopOptions {
|
|
1415
1902
|
/** 本次交互身份,内部步骤仍独立编号。 */
|
|
1416
1903
|
interactionId?: string;
|
|
1904
|
+
/** 仅用于诊断、用量归因与脱敏说明,不参与请求构造。 */
|
|
1417
1905
|
modelId?: string;
|
|
1906
|
+
modelRole?: PrimaryModelRole;
|
|
1907
|
+
/** 请求视图投影:只允许变换克隆出的请求消息,不得改动真实历史。 */
|
|
1418
1908
|
projectHistory?: (history: readonly CanonicalMessage[]) => CanonicalMessage[];
|
|
1909
|
+
/** 请求准备契约;可在请求前产出事件,并在上下文溢出时参与一次预算重试。 */
|
|
1419
1910
|
prepareRequest?: RequestPreparation;
|
|
1911
|
+
/** 每次收到 usage 后回调;attemptId 标识 run:step:attempt,便于按尝试归因。 */
|
|
1420
1912
|
onUsage?: (request: ModelRequest, usage: Usage, attemptId: string) => Promise<void>;
|
|
1421
1913
|
provider: ModelProvider;
|
|
1422
1914
|
executor: ToolExecutor;
|
|
1423
1915
|
tools: ToolRegistry;
|
|
1424
1916
|
hooks: HookRegistry;
|
|
1425
1917
|
systemPrompt?: string;
|
|
1918
|
+
/** 单次 run 的最大 turn 数,耗尽时以 error 事件收尾;缺省 20。 */
|
|
1426
1919
|
maxSteps?: number;
|
|
1920
|
+
/** 连续工具失败达到该阈值即熔断终止本轮 run;缺省 3。 */
|
|
1427
1921
|
maxConsecutiveErrors?: number;
|
|
1428
1922
|
signal?: AbortSignal;
|
|
1429
1923
|
eventLogger?: EventLogger;
|
|
1430
1924
|
sessionId?: string;
|
|
1431
1925
|
runId?: string;
|
|
1926
|
+
/** 每轮开始时读取;工具可见性与权限模式可随宿主状态变化。 */
|
|
1432
1927
|
getMode?: () => SessionMode;
|
|
1433
1928
|
permissionRules?: readonly PermissionRule[];
|
|
1434
1929
|
}
|
|
1930
|
+
/**
|
|
1931
|
+
* 主执行循环:按 turn 推进「模型请求 → 整批校验 → 工具调度 → 历史闭合」。
|
|
1932
|
+
* run 会就地追加传入的 history,assistant 与全部 tool_result 在同一同步临界段落入,
|
|
1933
|
+
* 消费方在任何对外事件后停止迭代都不会看到半闭合历史(设计文档 §4.3 / §4.4)。
|
|
1934
|
+
*/
|
|
1435
1935
|
declare class AgentLoop {
|
|
1436
1936
|
private readonly interactionId?;
|
|
1437
1937
|
private readonly modelId?;
|
|
1938
|
+
private readonly modelRole?;
|
|
1438
1939
|
private readonly projectHistory?;
|
|
1439
1940
|
private readonly prepareRequest?;
|
|
1440
1941
|
private readonly onUsage?;
|
|
@@ -1452,48 +1953,74 @@ declare class AgentLoop {
|
|
|
1452
1953
|
private readonly getMode;
|
|
1453
1954
|
private readonly permissionRules;
|
|
1454
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
|
+
*/
|
|
1455
1964
|
run(history: CanonicalMessage[]): AsyncIterable<SessionEvent>;
|
|
1456
1965
|
}
|
|
1457
1966
|
|
|
1967
|
+
/** AgentSession 的构造配置;除主任务绑定外均可缺省,缺省行为见各字段。 */
|
|
1458
1968
|
interface SessionConfig {
|
|
1459
1969
|
/** 持久会话身份;有版本化 Store 时须与头部一致,日志实例身份保持独立。 */
|
|
1460
1970
|
conversationId?: string;
|
|
1461
1971
|
tokenEstimator?: TokenEstimator;
|
|
1972
|
+
/** 无 Git 工作树时随 run_started 记录的分支回退值。 */
|
|
1462
1973
|
gitBranch?: string;
|
|
1974
|
+
/** 主任务默认模型绑定;恢复历史及未显式选择角色时使用。 */
|
|
1463
1975
|
defaultProfile: ModelProfile;
|
|
1976
|
+
/** 与 defaultProfile 匹配的协议适配器。 */
|
|
1464
1977
|
defaultProvider: ModelProvider;
|
|
1978
|
+
/** 消息级落盘通道;支持状态能力的 Store 额外启用持久压缩与交互终态。 */
|
|
1465
1979
|
store?: MessageStore;
|
|
1980
|
+
/** 工具执行与会话基目录;projectRoot/cwd 缺省沿用此值。 */
|
|
1466
1981
|
rootDir?: string;
|
|
1467
1982
|
systemPrompt?: string;
|
|
1468
1983
|
maxSteps?: number;
|
|
1469
1984
|
logger?: (msg: string) => void;
|
|
1470
1985
|
eventLogger?: EventLogger;
|
|
1471
1986
|
loggingDirectory?: string;
|
|
1987
|
+
/** 初始权限模式,缺省 Approval;仅空闲时可切换。 */
|
|
1472
1988
|
mode?: SessionMode;
|
|
1473
1989
|
permissionRules?: readonly PermissionRule[];
|
|
1474
1990
|
approvalChannel?: ApprovalChannel;
|
|
1475
1991
|
projectRoot?: string;
|
|
1476
1992
|
cwd?: string;
|
|
1477
1993
|
userInstructionsPath?: string;
|
|
1994
|
+
/** 未提供时使用默认日志 sink 的审计目录;init 时恢复不完整审计。 */
|
|
1478
1995
|
auditRecoveryDirectory?: string;
|
|
1479
1996
|
/** 接收普通运行日志失败的脱敏诊断;诊断失败也不得中断问答或替代审计。 */
|
|
1480
1997
|
onDiagnostic?: (message: string) => void;
|
|
1481
1998
|
}
|
|
1999
|
+
/** getStats 返回的统计快照;全部字段为独立副本,宿主修改不影响会话内部状态。 */
|
|
1482
2000
|
interface SessionStats {
|
|
1483
2001
|
conversationId?: string;
|
|
1484
2002
|
/** 历史存在无 usage 的模型步骤时为 false,不将旧消耗伪装为精确零。 */
|
|
1485
2003
|
usageKnown?: boolean;
|
|
2004
|
+
/** 摘要 attempt 的累计消耗;独立于主任务指标。 */
|
|
1486
2005
|
summaryUsage?: Usage;
|
|
1487
2006
|
summaryUsageKnown?: boolean;
|
|
1488
2007
|
contextSnapshot?: ContextSnapshot;
|
|
2008
|
+
/** 累计用户任务次数,含恢复自持久状态的 run_started 记录。 */
|
|
1489
2009
|
totalTurns: number;
|
|
2010
|
+
/** 主任务累计消耗;摘要消耗在 summaryUsage 单独统计。 */
|
|
1490
2011
|
totalTokens: Usage;
|
|
1491
2012
|
activeModel: string;
|
|
1492
2013
|
loadedToolsCount: number;
|
|
1493
2014
|
lastMetrics?: TurnMetrics;
|
|
1494
2015
|
lastRunMetrics?: RunMetrics;
|
|
2016
|
+
/** 最近一次内部模型请求的窗口占用;无实测时仅提供窗口上限。 */
|
|
1495
2017
|
contextUsage: ContextUsage;
|
|
1496
2018
|
}
|
|
2019
|
+
/**
|
|
2020
|
+
* 宿主无关的 Agent 会话门面:统一模型路由、工具执行、权限与上下文压缩。
|
|
2021
|
+
* 每次用户输入产生一个 run;历史与状态经 MessageStore 持久化,恢复后语义连续。
|
|
2022
|
+
* 运行或清理进行中,改变状态的公开方法一律被拒绝;Core 不承担任何界面职责。
|
|
2023
|
+
*/
|
|
1497
2024
|
declare class AgentSession {
|
|
1498
2025
|
private persistentId;
|
|
1499
2026
|
private readonly configuredConversationId?;
|
|
@@ -1537,12 +2064,32 @@ declare class AgentSession {
|
|
|
1537
2064
|
private cleanupPromise?;
|
|
1538
2065
|
private sessionEndFinished;
|
|
1539
2066
|
private activeRun;
|
|
2067
|
+
private primaryRole;
|
|
2068
|
+
private lastPrimaryProfile?;
|
|
2069
|
+
private lastPrimaryProvider?;
|
|
1540
2070
|
private readonly plugins;
|
|
1541
2071
|
constructor(config: SessionConfig);
|
|
2072
|
+
/** 幂等初始化:恢复审计残留、指令快照与持久历史,校验会话身份并回放 usage。 */
|
|
1542
2073
|
init(): Promise<void>;
|
|
2074
|
+
/** 挂载插件并执行 setup;销毁后或运行中拒绝,setup 失败的插件不进入已装列表。 */
|
|
1543
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
|
+
*/
|
|
1544
2084
|
switchModel(profile: ModelProfile, role?: ModelRole, provider?: ModelProvider): void;
|
|
2085
|
+
/** 查询指定绑定或当前明确选择的主任务模型,返回独立配置副本。 */
|
|
1545
2086
|
getActiveProfile(role?: ModelRole): ModelProfile;
|
|
2087
|
+
/** 空闲时显式选择场景;缺少映射或凭据时拒绝,不回退默认模型、不修改权限。 */
|
|
2088
|
+
selectModelRole(role: PrimaryModelRole): void;
|
|
2089
|
+
/** 返回本进程明确选择的场景,历史恢复不改变此状态。 */
|
|
2090
|
+
getModelRole(): PrimaryModelRole;
|
|
2091
|
+
/** 严格解析主任务快照,在输入落盘与网络调用之前检查角色、凭据与预算。 */
|
|
2092
|
+
private resolvePrimaryBinding;
|
|
1546
2093
|
/** 只在空闲时切换本次会话模式;宿主负责 FullAccess 的显式选择交互。 */
|
|
1547
2094
|
switchMode(mode: SessionMode): void;
|
|
1548
2095
|
getMode(): SessionMode;
|
|
@@ -1564,6 +2111,7 @@ declare class AgentSession {
|
|
|
1564
2111
|
getLastMetrics(): TurnMetrics | undefined;
|
|
1565
2112
|
/** 返回最近用户任务指标的独立副本;恢复的 usage 不伪造实时任务指标。 */
|
|
1566
2113
|
getLastRunMetrics(): RunMetrics | undefined;
|
|
2114
|
+
/** 空闲时清空存储与全部内存状态;conversationId 不变,恢复语义等同全新会话。 */
|
|
1567
2115
|
reset(): Promise<void>;
|
|
1568
2116
|
/**
|
|
1569
2117
|
* 执行一次用户输入,并以宿主无关的语义事件流返回全过程。
|
|
@@ -1572,15 +2120,18 @@ declare class AgentSession {
|
|
|
1572
2120
|
* {@link SessionEvent},分别完成展示、交互和中止控制。
|
|
1573
2121
|
*
|
|
1574
2122
|
* @param userInput 用户本轮输入。
|
|
1575
|
-
* @param options
|
|
2123
|
+
* @param options 可选中止信号与显式主任务角色;角色在整个工具任务内固定。
|
|
1576
2124
|
* @returns 文本、思考、工具、指标和错误等结构化事件的异步流。
|
|
1577
2125
|
* @throws {SessionBusyError} 当前会话已有正在执行的 run 时抛出。
|
|
2126
|
+
* @throws {ModelError} 显式角色缺少绑定或凭据时,在输入落盘和网络调用前抛出。
|
|
1578
2127
|
*/
|
|
1579
2128
|
run(userInput: string, options?: {
|
|
1580
2129
|
signal?: AbortSignal;
|
|
2130
|
+
role?: PrimaryModelRole;
|
|
1581
2131
|
}): AsyncIterable<SessionEvent>;
|
|
1582
2132
|
/** 单次任务执行主体;调用方 return 的中止与 finally 清理由外层统一协调。 */
|
|
1583
2133
|
private runOperation;
|
|
2134
|
+
/** 幂等销毁:卸载插件后发出 session:end;运行中拒绝,teardown 失败聚合抛出且不完成销毁。 */
|
|
1584
2135
|
destroy(): Promise<void>;
|
|
1585
2136
|
private assertIdle;
|
|
1586
2137
|
/**
|
|
@@ -1600,15 +2151,17 @@ declare class AgentSession {
|
|
|
1600
2151
|
compact(options?: {
|
|
1601
2152
|
signal?: AbortSignal;
|
|
1602
2153
|
}): AsyncGenerator<SessionEvent>;
|
|
1603
|
-
/**
|
|
2154
|
+
/** 手动压缩按主任务协议投影旧历史,不复用旧 run 私有状态;原始历史与落盘内容保持不变。 */
|
|
1604
2155
|
private compactOperation;
|
|
1605
|
-
/**
|
|
2156
|
+
/** 压缩与预算超限事件写入操作日志并携带 runId;其他事件不落日志。 */
|
|
1606
2157
|
private logContextEvent;
|
|
1607
2158
|
/** 以模型 attempt 身份幂等累加真实消耗;非法或缺失 usage 保持未知。 */
|
|
1608
2159
|
private accountUsage;
|
|
1609
2160
|
private persistToolMessages;
|
|
2161
|
+
/** 中止时为缓冲 assistant 的每个 tool_use 生成 OUTCOME_UNKNOWN 结果并入历史,保持事务闭合。 */
|
|
1610
2162
|
private closeInterruptedToolCalls;
|
|
2163
|
+
/** 收集历史中紧跟该 assistant 的连续 tool 消息;仅当覆盖全部 tool_use 时视为已闭合。 */
|
|
1611
2164
|
private findClosedToolMessages;
|
|
1612
2165
|
}
|
|
1613
2166
|
|
|
1614
|
-
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 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 ModelProvider, type ModelRequest, type ModelRole, type ModelRouter, type NormalizedHistory, OpenAICompatibleProvider, type OpenAIProviderOptions, PathSandbox, type PermissionAction, type PermissionDecision, PermissionPolicy, type PermissionRequest, type PermissionRule, type PluginContext, type ProjectIdentity, PromptAssembler, type PromptAssemblerOptions, 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, 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, validatePermissionRules, validateSummary, 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 };
|