@kiturone/kapibala 0.0.1 → 0.0.3
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/README.md +7 -1
- package/dist/index.cjs +4764 -301
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1093 -115
- package/dist/index.d.ts +1093 -115
- package/dist/index.js +4719 -301
- package/dist/index.js.map +1 -1
- package/package.json +4 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,12 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Error Taxonomy for Kapibala Agent Harness
|
|
3
|
+
*/
|
|
4
|
+
type ModelErrorCategory = 'authentication' | 'quota' | 'rate_limit' | 'context' | 'service' | 'network' | 'timeout' | 'invalid_request' | 'invalid_response' | 'unknown';
|
|
5
|
+
interface ModelErrorOptions {
|
|
6
|
+
status?: number;
|
|
7
|
+
retryable?: boolean;
|
|
8
|
+
code?: string;
|
|
9
|
+
transportCode?: string;
|
|
10
|
+
providerCode?: string;
|
|
11
|
+
providerType?: string;
|
|
12
|
+
stage?: 'connect' | 'response' | 'stream' | 'request';
|
|
13
|
+
}
|
|
14
|
+
/** 跨协议模型失败的脱敏说明;适用于主任务和摘要,不代表自动重试授权。 */
|
|
15
|
+
interface ModelErrorInfo {
|
|
16
|
+
category: ModelErrorCategory;
|
|
17
|
+
code: string;
|
|
18
|
+
message: string;
|
|
19
|
+
status?: number;
|
|
20
|
+
providerCode?: string;
|
|
21
|
+
providerType?: string;
|
|
22
|
+
transportCode?: string;
|
|
23
|
+
stage?: ModelErrorOptions['stage'];
|
|
24
|
+
operation?: 'primary' | 'summary';
|
|
25
|
+
modelId?: string;
|
|
26
|
+
provider?: string;
|
|
27
|
+
retryPolicy: KapibalaError['retryPolicy'];
|
|
28
|
+
suggestion: string;
|
|
29
|
+
}
|
|
30
|
+
/** 清理服务端报错中的终端控制符、常见凭据及带凭据的 URL,限制长度;不展示完整响应或请求头。 */
|
|
31
|
+
declare function sanitizeModelErrorMessage(value: string): string;
|
|
32
|
+
/** 生成统一脱敏说明;上下文补充调用场景,不携带原始异常、请求正文或密钥。 */
|
|
33
|
+
declare function describeModelError(error: ModelError, context?: Pick<ModelErrorInfo, 'modelId' | 'provider' | 'operation'>): ModelErrorInfo;
|
|
34
|
+
declare class KapibalaError extends Error {
|
|
35
|
+
readonly code: string;
|
|
36
|
+
readonly retryPolicy: 'never' | 'immediate' | 'backoff' | 'after_user_action';
|
|
37
|
+
readonly safeMessage: string;
|
|
38
|
+
constructor(message: string, options?: {
|
|
39
|
+
code?: string;
|
|
40
|
+
retryPolicy?: 'never' | 'immediate' | 'backoff' | 'after_user_action';
|
|
41
|
+
safeMessage?: string;
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
declare class ModelError extends KapibalaError {
|
|
45
|
+
readonly status?: number;
|
|
46
|
+
readonly retryable: boolean;
|
|
47
|
+
/** 可选的受控底层连接错误码,不包含原始传输异常文本。 */
|
|
48
|
+
readonly transportCode?: string;
|
|
49
|
+
readonly providerCode?: string;
|
|
50
|
+
readonly providerType?: string;
|
|
51
|
+
readonly stage?: ModelErrorOptions['stage'];
|
|
52
|
+
readonly category: ModelErrorCategory;
|
|
53
|
+
/** 构建模型错误,清理服务端原因并按明确状态/错误码分类;重试策略仅为建议,不授权重放。 */
|
|
54
|
+
constructor(message: string, options?: ModelErrorOptions);
|
|
55
|
+
}
|
|
56
|
+
/** Provider 明确拒绝上下文长度;仅无输出请求允许预算处理后重发一次。 */
|
|
57
|
+
declare class ContextOverflowError extends ModelError {
|
|
58
|
+
/** 保留明确上下文错误的脱敏服务端原因;只允许尚无输出的请求进入一次预算处理。 */
|
|
59
|
+
constructor(status?: number, details?: Pick<ModelErrorOptions, 'providerCode' | 'providerType' | 'stage'> & {
|
|
60
|
+
message?: string;
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
declare class TransportError extends KapibalaError {
|
|
64
|
+
readonly retryable: boolean;
|
|
65
|
+
constructor(message: string, retryable?: boolean);
|
|
66
|
+
}
|
|
67
|
+
declare class ToolError extends KapibalaError {
|
|
68
|
+
constructor(message: string);
|
|
69
|
+
}
|
|
70
|
+
declare class ToolNotFound extends KapibalaError {
|
|
71
|
+
readonly toolName: string;
|
|
72
|
+
readonly availableTools: string[];
|
|
73
|
+
constructor(toolName: string, availableTools?: string[]);
|
|
74
|
+
}
|
|
75
|
+
declare class AbortError extends KapibalaError {
|
|
76
|
+
constructor(message?: string);
|
|
77
|
+
}
|
|
78
|
+
declare class FatalError extends KapibalaError {
|
|
79
|
+
constructor(message: string);
|
|
80
|
+
}
|
|
81
|
+
declare class SessionBusyError extends KapibalaError {
|
|
82
|
+
constructor(operation: string);
|
|
83
|
+
}
|
|
84
|
+
/** 请求硬预算不足;需用户缩小任务或选择更大窗口,不允许切掉当前任务继续。 */
|
|
85
|
+
declare class ContextBudgetError extends KapibalaError {
|
|
86
|
+
readonly usedTokens: number;
|
|
87
|
+
readonly inputBudget: number;
|
|
88
|
+
constructor(usedTokens: number, inputBudget: number);
|
|
89
|
+
}
|
|
90
|
+
/** 压缩状态持久提交失败,与模型预算或生成失败分别处理,不允许未落盘候选生效。 */
|
|
91
|
+
declare class ContextStorageError extends KapibalaError {
|
|
92
|
+
constructor(message: string);
|
|
93
|
+
}
|
|
94
|
+
|
|
1
95
|
/**
|
|
2
96
|
* Canonical Message & Event Types for Kapibala
|
|
3
97
|
*/
|
|
98
|
+
|
|
4
99
|
type ContentBlock = TextBlock | ToolUseBlock | ToolResultBlock | ThinkingBlock | RedactedThinkingBlock;
|
|
5
100
|
interface TextBlock {
|
|
6
101
|
type: 'text';
|
|
7
102
|
text: string;
|
|
8
103
|
}
|
|
9
104
|
interface ToolUseBlock {
|
|
105
|
+
/** 工具执行语义来源;新运行记录,旧历史可缺省。未知插件不按内置只读工具剪裁。 */
|
|
106
|
+
source?: string;
|
|
107
|
+
/** 执行器记录的绝对工具根目录;仅作历史路径依据,不改变参数或恢复旧授权。旧历史可缺省。 */
|
|
108
|
+
executionRoot?: string;
|
|
10
109
|
type: 'tool_use';
|
|
11
110
|
id: string;
|
|
12
111
|
name: string;
|
|
@@ -19,6 +118,10 @@ interface ToolResultBlock {
|
|
|
19
118
|
isError?: boolean;
|
|
20
119
|
/** 单次工具调用总耗时,包含 tool hooks 与实际执行。 */
|
|
21
120
|
durationMs?: number;
|
|
121
|
+
/** 稳定错误类别;旧历史中的该字段可缺省。 */
|
|
122
|
+
errorCode?: string;
|
|
123
|
+
/** 不代表自动重试,只描述调用方应如何处理该错误。 */
|
|
124
|
+
retryPolicy?: 'never' | 'immediate' | 'backoff' | 'after_user_action';
|
|
22
125
|
}
|
|
23
126
|
interface ThinkingBlock {
|
|
24
127
|
type: 'thinking';
|
|
@@ -33,9 +136,21 @@ interface Usage {
|
|
|
33
136
|
promptTokens: number;
|
|
34
137
|
completionTokens: number;
|
|
35
138
|
totalTokens: number;
|
|
139
|
+
/** Provider 明确提供的缓存命中输入量;缺失表示未知,不能按零推断。 */
|
|
140
|
+
cachedPromptTokens?: number;
|
|
36
141
|
}
|
|
37
142
|
type MessageRole = 'user' | 'assistant' | 'system' | 'tool';
|
|
38
143
|
interface CanonicalMessage {
|
|
144
|
+
/** 派生背景锚点独立于真实用户输入,避免合并后丢失受保护原消息的来源身份。 */
|
|
145
|
+
contextSummary?: {
|
|
146
|
+
checkpointId: string;
|
|
147
|
+
};
|
|
148
|
+
/** 稳定消息身份;旧 SDK 消息可省略,在进入受管历史时补齐。 */
|
|
149
|
+
id?: string;
|
|
150
|
+
/** 用户交互身份,与内部模型步骤及进程运行实例分别记录。 */
|
|
151
|
+
interactionId?: string;
|
|
152
|
+
/** 未完成正文不会进入模型请求视图。省略表示旧版已落盘正文。 */
|
|
153
|
+
state?: 'completed' | 'draft' | 'failed' | 'interrupted';
|
|
39
154
|
role: MessageRole;
|
|
40
155
|
content: ContentBlock[];
|
|
41
156
|
timestamp?: number;
|
|
@@ -70,11 +185,15 @@ interface RunMetrics {
|
|
|
70
185
|
turns: number;
|
|
71
186
|
toolCalls: number;
|
|
72
187
|
status: 'completed' | 'failed' | 'aborted';
|
|
188
|
+
/** 模型失败的脱敏汇总;保留具体阶段与原因,不携带请求或响应正文。 */
|
|
189
|
+
failure?: ModelErrorInfo;
|
|
73
190
|
/** 最近一次内部模型请求占用的上下文;不使用 run 累计 promptTokens。 */
|
|
74
191
|
contextUsage?: ContextUsage;
|
|
75
192
|
}
|
|
76
193
|
interface ContextUsage {
|
|
77
194
|
usedTokens?: number;
|
|
195
|
+
/** true 表示未收到当前请求 usage,输入占用使用预算估算,不能用于计费。 */
|
|
196
|
+
estimatedUsage?: boolean;
|
|
78
197
|
limitTokens: number;
|
|
79
198
|
percent?: number;
|
|
80
199
|
estimatedLimit: boolean;
|
|
@@ -96,6 +215,56 @@ interface StepLogEntry {
|
|
|
96
215
|
* 不应直接把本类型当作长期兼容的网络协议。
|
|
97
216
|
*/
|
|
98
217
|
type SessionEvent = {
|
|
218
|
+
type: 'session_resumed';
|
|
219
|
+
conversationId: string;
|
|
220
|
+
runtimeSessionId: string;
|
|
221
|
+
messageCount: number;
|
|
222
|
+
} | {
|
|
223
|
+
type: 'session_switched';
|
|
224
|
+
conversationId: string;
|
|
225
|
+
previousConversationId: string;
|
|
226
|
+
} | {
|
|
227
|
+
type: 'compaction_start';
|
|
228
|
+
conversationId: string;
|
|
229
|
+
runId?: string;
|
|
230
|
+
kind: 'prune' | 'summary';
|
|
231
|
+
reason: 'threshold' | 'manual' | 'overflow';
|
|
232
|
+
persistence: 'disk' | 'memory';
|
|
233
|
+
beforeTokens: number;
|
|
234
|
+
} | {
|
|
235
|
+
type: 'compaction_finish';
|
|
236
|
+
conversationId: string;
|
|
237
|
+
runId?: string;
|
|
238
|
+
kind: 'prune' | 'summary';
|
|
239
|
+
reason: 'threshold' | 'manual' | 'overflow';
|
|
240
|
+
persistence: 'disk' | 'memory';
|
|
241
|
+
beforeTokens: number;
|
|
242
|
+
afterTokens: number;
|
|
243
|
+
checkpointId?: string;
|
|
244
|
+
coveredEndMessageId?: string;
|
|
245
|
+
prunedResults?: number;
|
|
246
|
+
modelId?: string;
|
|
247
|
+
durationMs: number;
|
|
248
|
+
} | {
|
|
249
|
+
type: 'compaction_failed';
|
|
250
|
+
conversationId: string;
|
|
251
|
+
runId?: string;
|
|
252
|
+
kind: 'prune' | 'summary';
|
|
253
|
+
reason: 'threshold' | 'manual' | 'overflow';
|
|
254
|
+
persistence: 'disk' | 'memory';
|
|
255
|
+
error: string;
|
|
256
|
+
/** 脱敏失败分类,不包含 Provider 响应正文或历史内容。 */
|
|
257
|
+
errorCode?: string;
|
|
258
|
+
/** 摘要模型失败采用与主任务相同的脱敏说明;验证失败不回显摘要正文。 */
|
|
259
|
+
modelError?: ModelErrorInfo;
|
|
260
|
+
consecutiveFailures: number;
|
|
261
|
+
} | {
|
|
262
|
+
type: 'context_budget_exceeded';
|
|
263
|
+
conversationId: string;
|
|
264
|
+
runId?: string;
|
|
265
|
+
usedTokens: number;
|
|
266
|
+
inputBudget: number;
|
|
267
|
+
} | {
|
|
99
268
|
type: 'turn_start';
|
|
100
269
|
turn: number;
|
|
101
270
|
} | {
|
|
@@ -112,6 +281,12 @@ type SessionEvent = {
|
|
|
112
281
|
id: string;
|
|
113
282
|
name: string;
|
|
114
283
|
input: Record<string, unknown>;
|
|
284
|
+
} | {
|
|
285
|
+
type: 'tool_progress';
|
|
286
|
+
id: string;
|
|
287
|
+
name: string;
|
|
288
|
+
elapsedMs: number;
|
|
289
|
+
outputBytes: number;
|
|
115
290
|
} | {
|
|
116
291
|
type: 'tool_finish';
|
|
117
292
|
id: string;
|
|
@@ -145,6 +320,7 @@ type SessionEvent = {
|
|
|
145
320
|
} | {
|
|
146
321
|
type: 'error';
|
|
147
322
|
error: Error;
|
|
323
|
+
modelError?: ModelErrorInfo;
|
|
148
324
|
};
|
|
149
325
|
type ModelEvent = {
|
|
150
326
|
type: 'text_delta';
|
|
@@ -172,6 +348,7 @@ type ModelEvent = {
|
|
|
172
348
|
usage?: Usage;
|
|
173
349
|
ttftMs?: number;
|
|
174
350
|
durationMs?: number;
|
|
351
|
+
finishReason?: string;
|
|
175
352
|
};
|
|
176
353
|
interface ToolDefinition {
|
|
177
354
|
name: string;
|
|
@@ -186,42 +363,763 @@ interface ModelRequest {
|
|
|
186
363
|
temperature?: number;
|
|
187
364
|
maxTokens?: number;
|
|
188
365
|
}
|
|
366
|
+
/** runtime 通用请求准备契约;实现可以预算或投影,Loop 不依赖具体上下文管理器。 */
|
|
367
|
+
type RequestPreparation = (request: ModelRequest, history: readonly CanonicalMessage[], reason?: 'threshold' | 'overflow') => AsyncGenerator<SessionEvent, ModelRequest>;
|
|
368
|
+
|
|
369
|
+
/** 生成进程内单调递增的 UUIDv7;时钟回拨时沿用逻辑时间,序列耗尽才推进时间。 */
|
|
370
|
+
declare function createMessageId(): string;
|
|
189
371
|
|
|
372
|
+
/** 按来源及原始位置生成旧消息身份;复制输入,不改变调用者持有的正文或已有身份。 */
|
|
373
|
+
declare function identifyHistory(messages: readonly CanonicalMessage[], source: string): CanonicalMessage[];
|
|
374
|
+
interface HistoryRepair {
|
|
375
|
+
assistantId: string;
|
|
376
|
+
toolCallId: string;
|
|
377
|
+
result: ToolResultBlock;
|
|
378
|
+
}
|
|
379
|
+
interface NormalizedHistory {
|
|
380
|
+
messages: CanonicalMessage[];
|
|
381
|
+
/** 与 messages 同序的原始消息 ID 集合;修复结果关联原始 assistant。 */
|
|
382
|
+
sources: string[][];
|
|
383
|
+
repairs: HistoryRepair[];
|
|
384
|
+
diagnostics: string[];
|
|
385
|
+
}
|
|
190
386
|
/**
|
|
191
|
-
*
|
|
387
|
+
* 构造合法且独立的请求视图:只接受紧邻事务的结果,缺失结果标为未知;重复调用身份明确失败。
|
|
388
|
+
* 合并仅适用于纯文本的同角色消息,失败正文不重放,所有来源均可追踪。
|
|
192
389
|
*/
|
|
193
|
-
declare
|
|
194
|
-
|
|
390
|
+
declare function normalizeHistory(input: readonly CanonicalMessage[]): NormalizedHistory;
|
|
391
|
+
interface InteractionBoundary {
|
|
392
|
+
interactionId: string;
|
|
393
|
+
status: 'completed' | 'failed' | 'interrupted';
|
|
394
|
+
messageIds: string[];
|
|
195
395
|
}
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
396
|
+
interface InteractionTerminal {
|
|
397
|
+
interactionId: string;
|
|
398
|
+
status: InteractionBoundary['status'];
|
|
399
|
+
}
|
|
400
|
+
/**
|
|
401
|
+
* 以显式终态为准恢复用户交互;旧历史仅在完整工具事务之后存在非空最终答复时推断成功。
|
|
402
|
+
* 保护最近成功交互及其后的所有交互,没有成功证据时保护全部历史。
|
|
403
|
+
*/
|
|
404
|
+
declare function indexInteractions(input: readonly CanonicalMessage[], terminals?: readonly InteractionTerminal[]): {
|
|
405
|
+
interactions: InteractionBoundary[];
|
|
406
|
+
protectedMessageIds: string[];
|
|
407
|
+
};
|
|
408
|
+
|
|
409
|
+
declare class JSONLMessageStore implements MessageStore {
|
|
410
|
+
readonly filePath: string;
|
|
411
|
+
constructor(filePath: string);
|
|
412
|
+
append(message: CanonicalMessage): Promise<void>;
|
|
413
|
+
load(): Promise<CanonicalMessage[]>;
|
|
414
|
+
clear(): Promise<void>;
|
|
415
|
+
/**
|
|
416
|
+
* 历史自愈(设计文档 §4.4):逐条扫描 assistant 的 tool_use,
|
|
417
|
+
* 若其后的 tool 消息未完整覆盖这些 tool_use,就地补一条 is_error 的 tool_result。
|
|
418
|
+
*
|
|
419
|
+
* 之所以做**全历史扫描**而非只看末条:崩溃可能发生在任意一轮工具执行中途,
|
|
420
|
+
* 悬挂的 tool_use 未必位于历史末尾(例如中断后用户又继续提了问)。
|
|
421
|
+
* 只看末条会漏掉夹在中间的悬挂,下一次请求仍会因上下文非法而 400。
|
|
422
|
+
*/
|
|
423
|
+
private healDanglingToolCalls;
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
interface MessageStore {
|
|
427
|
+
append(message: CanonicalMessage): Promise<void>;
|
|
428
|
+
load(): Promise<CanonicalMessage[]>;
|
|
429
|
+
clear(): Promise<void>;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
declare const SESSION_SCHEMA_VERSION = 1;
|
|
433
|
+
type SessionRecordType = 'header' | 'message' | 'run_started' | 'run_finished' | 'message_state' | 'history_repair' | 'usage' | 'checkpoint' | 'context_pruned' | 'compaction_state' | 'title' | 'reset' | 'legacy_import';
|
|
434
|
+
interface SessionHeader {
|
|
435
|
+
conversationId: string;
|
|
436
|
+
projectRoot: string;
|
|
437
|
+
initialCwd: string;
|
|
438
|
+
createdAt?: number;
|
|
439
|
+
gitBranch?: string;
|
|
440
|
+
importIdentity?: string;
|
|
441
|
+
}
|
|
442
|
+
interface SessionRecord {
|
|
443
|
+
schemaVersion: number;
|
|
444
|
+
type: SessionRecordType;
|
|
445
|
+
recordId: string;
|
|
446
|
+
timestamp: number;
|
|
447
|
+
parentId: string | null;
|
|
448
|
+
payload: Record<string, unknown>;
|
|
449
|
+
}
|
|
450
|
+
interface SessionState {
|
|
451
|
+
header: SessionHeader;
|
|
452
|
+
/** 最近 reset 之后的记录;包含正文及状态,不包含头部。 */
|
|
453
|
+
records: SessionRecord[];
|
|
454
|
+
/** 只随正文、修复与 reset 改变,不因 usage 或缓存写入失效。 */
|
|
455
|
+
contentRevision: string;
|
|
456
|
+
}
|
|
457
|
+
/** MessageStore 的可选状态能力;旧 SDK Store 不需要实现,宿主据此降级持久压缩。 */
|
|
458
|
+
interface StatefulMessageStore extends MessageStore {
|
|
459
|
+
appendRecord(type: Exclude<SessionRecordType, 'header' | 'message'>, payload: Record<string, unknown>): Promise<SessionRecord>;
|
|
460
|
+
loadState(): Promise<SessionState>;
|
|
461
|
+
}
|
|
462
|
+
/** 判断 Store 是否支持版本化状态;不读取数据或改变旧 Store。 */
|
|
463
|
+
declare function supportsSessionState(store: MessageStore): store is StatefulMessageStore;
|
|
464
|
+
/**
|
|
465
|
+
* 版本化消息与上下文状态的单文件存储。所有写入串行并 fsync,失败后拒绝继续写入。
|
|
466
|
+
* 调用者须在打开前取得单写者锁;本类不允许静默跳过中部损坏或重复身份。
|
|
467
|
+
*/
|
|
468
|
+
declare class SessionStore implements StatefulMessageStore {
|
|
469
|
+
readonly filePath: string;
|
|
470
|
+
private queue;
|
|
471
|
+
private records;
|
|
472
|
+
private observer?;
|
|
473
|
+
private onDiagnostic?;
|
|
474
|
+
private stamp?;
|
|
475
|
+
private constructor();
|
|
476
|
+
/** 注册可重建缓存的写后通知;缓存失败只诊断,不撤销或毒化已 fsync 的正文。 */
|
|
477
|
+
setAppendObserver(observer: (record: SessionRecord) => void, onDiagnostic?: (message: string) => void): void;
|
|
478
|
+
/** 以独占创建方式安装新头部,已有文件明确失败,绝不覆盖其它会话。 */
|
|
479
|
+
static create(filePath: string, header: SessionHeader): Promise<SessionStore>;
|
|
480
|
+
/** 打开并验证已有会话;尾部残片先保存到隔离文件,中部损坏与未知版本拒绝恢复。 */
|
|
481
|
+
static open(filePath: string): Promise<SessionStore>;
|
|
482
|
+
/** 获取完整记录快照,等候已排队写入后读取;调用者不能借此修改内部记录。 */
|
|
483
|
+
readRecords(): Promise<SessionRecord[]>;
|
|
484
|
+
/** 消息级持久化,补稳定身份并保留所有终态字段,成功后方可进入下一次写入。 */
|
|
485
|
+
append(message: CanonicalMessage): Promise<void>;
|
|
486
|
+
/** 持久化状态记录,fsync 成功才返回;失败会毒化当前写者,要求重新验证后恢复。 */
|
|
487
|
+
appendRecord(type: Exclude<SessionRecordType, 'header' | 'message'>, payload: Record<string, unknown>): Promise<SessionRecord>;
|
|
488
|
+
/** 重建 reset 后的状态;统计记录和检查点不会推进正文 revision。 */
|
|
489
|
+
loadState(): Promise<SessionState>;
|
|
490
|
+
/**
|
|
491
|
+
* 恢复原始正文,并将幂等修复叠加到原工具事务;不合并连续消息,也不执行工具。
|
|
492
|
+
* 缺失结果用 history_repair 落盘,独立于实际工具结果和正文,不伪造成功。
|
|
493
|
+
*/
|
|
494
|
+
load(): Promise<CanonicalMessage[]>;
|
|
495
|
+
/** SDK 清空语义通过持久边界实现;此前摘要、剪裁及失败状态不再参与恢复。 */
|
|
496
|
+
clear(): Promise<void>;
|
|
497
|
+
/** 生成前驱关联的 Envelope,前驱仅表达追加次序,未来 DAG 不改变当前恢复规则。 */
|
|
498
|
+
private makeRecord;
|
|
499
|
+
/** 单写者队列不吞异常;后续写入依赖同一失败 Promise,防止继续污染正文。 */
|
|
500
|
+
private enqueue;
|
|
501
|
+
/** 保存当前写者的正文版本,拒绝未经锁保护的第二写者继续追加。 */
|
|
502
|
+
private refreshStamp;
|
|
503
|
+
/** 校验每个完整记录,只有最后非空行的 JSON 残片可隔离,语义损坏绝不作为残片吞掉。 */
|
|
504
|
+
private readFile;
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/** 基于目录独占创建的单写者锁;只有能确认死亡的进程才允许保守回收,不按年龄抢占。 */
|
|
508
|
+
declare class SessionLock {
|
|
509
|
+
readonly lockPath: string;
|
|
510
|
+
private readonly owner;
|
|
511
|
+
private released;
|
|
512
|
+
private constructor();
|
|
513
|
+
/** 获取写入权,存活、无权限探测、损坏 owner 或正在回收均明确失败。 */
|
|
514
|
+
static acquire(lockPath: string): Promise<SessionLock>;
|
|
515
|
+
/** 仅释放本 nonce 的锁;调用者必须先等待在途工具、摘要及存储结束。 */
|
|
516
|
+
release(): Promise<void>;
|
|
517
|
+
/** 只认格式完整的 owner,缺失与损坏时保持锁而非猜测安全。 */
|
|
518
|
+
private static readOwner;
|
|
519
|
+
/**
|
|
520
|
+
* 清除上次回收崩溃的残留:无身份标记或标记进程已死亡的 recovery 目录可安全移除;
|
|
521
|
+
* 身份确认存活的回收进行中则保留。清不掉时视为回收进行中,由后续获取者再试。
|
|
522
|
+
*/
|
|
523
|
+
private static clearAbandonedRecovery;
|
|
524
|
+
/** 无残留或残留进程已死亡时放行;确认存活的回收进行中则明确失败。 */
|
|
525
|
+
private static ensureNoLiveRecovery;
|
|
526
|
+
/** 仅 ESRCH 表示确定死亡;PID 复用或 EPERM 均保持原锁。 */
|
|
527
|
+
private static isDead;
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
interface ProjectIdentity {
|
|
531
|
+
projectRoot: string;
|
|
532
|
+
cwd: string;
|
|
533
|
+
projectKey: string;
|
|
534
|
+
gitBranch?: string;
|
|
535
|
+
gitWorktree?: boolean;
|
|
536
|
+
}
|
|
537
|
+
/** 解析真实工作树根;同工作树子目录共用桶,非 Git 目录和不同 worktree 独立。不会改变 cwd。 */
|
|
538
|
+
declare function resolveSessionProject(cwd: string): ProjectIdentity;
|
|
539
|
+
interface SessionMetadata {
|
|
540
|
+
schemaVersion: 1;
|
|
541
|
+
conversationId: string;
|
|
542
|
+
fileName: string;
|
|
543
|
+
projectRoot: string;
|
|
544
|
+
createdAt: number;
|
|
545
|
+
lastActivityAt: number;
|
|
546
|
+
messageCount: number;
|
|
547
|
+
title: string;
|
|
548
|
+
customTitle?: string;
|
|
549
|
+
gitBranch?: string;
|
|
550
|
+
lastActivityGitBranch?: string;
|
|
551
|
+
lastModelId?: string;
|
|
552
|
+
importIdentity?: string;
|
|
553
|
+
size: number;
|
|
554
|
+
mtimeMs: number;
|
|
555
|
+
revision: string;
|
|
556
|
+
}
|
|
557
|
+
interface ManagedSession {
|
|
558
|
+
conversationId: string;
|
|
559
|
+
store: SessionStore;
|
|
560
|
+
metadataPath: string;
|
|
561
|
+
/** 可丢弃缓存的只读快照;缺失时为 undefined,不代表正文丢失。 */
|
|
562
|
+
readonly metadata?: SessionMetadata;
|
|
563
|
+
header: SessionHeader;
|
|
564
|
+
/** 环境提示,不执行 checkout,也不把旧授权或模型配置带入当前运行。 */
|
|
565
|
+
branchDrift?: {
|
|
566
|
+
createdBranch?: string;
|
|
567
|
+
currentBranch?: string;
|
|
568
|
+
};
|
|
569
|
+
release(): Promise<void>;
|
|
570
|
+
}
|
|
571
|
+
interface SessionManagerOptions {
|
|
572
|
+
cwd?: string;
|
|
573
|
+
homeDirectory?: string;
|
|
574
|
+
onDiagnostic?: (message: string) => void;
|
|
575
|
+
}
|
|
576
|
+
/** 将终端控制字符转成可见转义,并按 Unicode code point 限长。 */
|
|
577
|
+
declare function sanitizeSessionTitle(title: string, maximum?: number): string;
|
|
578
|
+
/** 按项目发现、创建和打开独立会话;缓存可丢弃,JSONL 是唯一恢复依据。 */
|
|
579
|
+
declare class SessionManager {
|
|
580
|
+
readonly project: ProjectIdentity;
|
|
581
|
+
readonly directory: string;
|
|
582
|
+
private readonly handles;
|
|
583
|
+
private readonly diagnostic?;
|
|
584
|
+
constructor(options?: SessionManagerOptions);
|
|
585
|
+
/** 默认新建独立空会话,写入头部并持有单写者锁;不读取其它正文。 */
|
|
586
|
+
create(): Promise<ManagedSession>;
|
|
587
|
+
/** 每页 20 项按正文活动排序;有效 sidecar 只读元数据,不读取完整 JSONL。 */
|
|
588
|
+
list(page?: number): Promise<{
|
|
589
|
+
items: SessionMetadata[];
|
|
590
|
+
total: number;
|
|
591
|
+
page: number;
|
|
592
|
+
pages: number;
|
|
593
|
+
}>;
|
|
594
|
+
/** 一次扫描建立排序目录,分页和继续最近会话共用;有效缓存不读取正文。 */
|
|
595
|
+
private allMetadata;
|
|
596
|
+
/** 打开完整 ID 或唯一前缀;跨桶、缺失与歧义均失败,同一 Manager 已持有的目标直接返回。 */
|
|
597
|
+
open(id: string): Promise<ManagedSession>;
|
|
598
|
+
/** 继续最近有正文的会话;没有历史才新建,显式打开失败绝不回退为空会话。 */
|
|
599
|
+
continueRecent(): Promise<ManagedSession>;
|
|
600
|
+
/** 标题作为独立耐久记录;标题或浏览不改变正文活动排序。 */
|
|
601
|
+
rename(id: string, title: string): Promise<void>;
|
|
602
|
+
/** 等候所有存储队列后释放句柄;宿主必须先结束 AgentSession 的工具/摘要清理。 */
|
|
603
|
+
close(): Promise<void>;
|
|
604
|
+
/**
|
|
605
|
+
* 只发现 cwd 和工作树根的旧文件;来源快照 hash 幂等,完整临时文件 fsync 后独占安装。
|
|
606
|
+
* 保留源文件,安装身份写入头部,缓存丢失或进程退出后仍不会重复导入。
|
|
607
|
+
*/
|
|
608
|
+
importLegacy(): Promise<string[]>;
|
|
609
|
+
/** 绑定写后缓存与锁生命周期;正文优先,缓存失败不使保存成功的消息消失。 */
|
|
610
|
+
private attach;
|
|
611
|
+
/** 缓存通过文件名、身份、统计与正文 stat 校验;失败交由正文重建。 */
|
|
612
|
+
private readMetadata;
|
|
613
|
+
/** 浏览仅解析完整记录;严格打开由 SessionStore 验证,浏览不能改写残片。 */
|
|
614
|
+
private readDiscoveryRecords;
|
|
615
|
+
/** 从正文重建元数据,标题和上下文事件不改变内容活动时间。 */
|
|
616
|
+
private buildMetadata;
|
|
617
|
+
/** 只由正文、用户 run 与 reset 更新活动;usage、标题、摘要均不能把浏览对象置顶。 */
|
|
618
|
+
private applyRecord;
|
|
619
|
+
/** 临时 sidecar 完整写入后替换,可重建缓存不承担正文提交职责。 */
|
|
620
|
+
private writeMetadata;
|
|
621
|
+
private metadataPath;
|
|
622
|
+
private lockPath;
|
|
623
|
+
private report;
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
interface ModelProvider {
|
|
627
|
+
readonly name: string;
|
|
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
|
+
}
|
|
671
|
+
|
|
672
|
+
interface ContextBudget {
|
|
673
|
+
contextWindow: number;
|
|
674
|
+
estimatedWindow: boolean;
|
|
675
|
+
outputReserve: number;
|
|
676
|
+
safetyReserve: number;
|
|
677
|
+
inputBudget: number;
|
|
678
|
+
/** 触发阈值 0.85B:超过才启动一级剪裁/二级摘要(迁移文档:剪裁后低于触发阈值则不调用摘要模型)。 */
|
|
679
|
+
trigger: number;
|
|
680
|
+
/**
|
|
681
|
+
* 目标 0.65B:压缩后期望达到的占用水平,随 ContextSnapshot 暴露给 /context 展示。
|
|
682
|
+
* 当前算法的启停条件是 trigger;设计文档未定义向该目标迭代收敛的机制,
|
|
683
|
+
* 故不作为候选接受条件或强制收敛线使用。
|
|
684
|
+
*/
|
|
685
|
+
target: number;
|
|
686
|
+
}
|
|
687
|
+
interface TokenEstimate {
|
|
688
|
+
total: number;
|
|
689
|
+
system: number;
|
|
690
|
+
tools: number;
|
|
691
|
+
history: number;
|
|
692
|
+
overhead: number;
|
|
693
|
+
source: 'estimated' | 'calibrated';
|
|
694
|
+
}
|
|
695
|
+
/** 可替换估算器;不得执行 Provider、Hook 或改写传入请求。 */
|
|
696
|
+
interface TokenEstimator {
|
|
697
|
+
estimate(request: ModelRequest, modelFingerprint?: string): TokenEstimate;
|
|
698
|
+
observe?(request: ModelRequest, actualPromptTokens: number, modelFingerprint?: string): void;
|
|
699
|
+
}
|
|
700
|
+
/** 未知窗口以 32K 控制,保留 12.5%(最多 4096)输出与至少 128 的 5% 安全余量。 */
|
|
701
|
+
declare function createContextBudget(window?: ContextWindowValue): ContextBudget;
|
|
702
|
+
/** 对对象 key 确定性排序,保证摘要、工具 schema 与 fingerprint 不受插入顺序影响。 */
|
|
703
|
+
declare function stableSerialize(value: unknown): string;
|
|
704
|
+
/** 请求 fingerprint 不包含 AbortSignal 等宿主对象,包含实际指令、schema、正文和输出配置。 */
|
|
705
|
+
declare function requestFingerprint(request: ModelRequest, modelFingerprint?: string): string;
|
|
706
|
+
/**
|
|
707
|
+
* 无依赖 Unicode 分类估算器;非 ASCII 按 code point 保守计数,ASCII 按四字符估算。
|
|
708
|
+
* 观测 usage 仅校准相同最终请求与模型,改变指令或工具会自然失效;未知值不伪造为实测。
|
|
709
|
+
*/
|
|
710
|
+
declare class UnicodeTokenEstimator implements TokenEstimator {
|
|
711
|
+
private readonly calibration;
|
|
712
|
+
/** 计算系统、工具、历史和协议开销,返回估算/校准来源,保持请求不变。 */
|
|
713
|
+
estimate(request: ModelRequest, modelFingerprint?: string): TokenEstimate;
|
|
714
|
+
/** 仅接受真实正整数 prompt usage,校准不会降低原保守估算;缓存最多 64 个最终请求。 */
|
|
715
|
+
observe(request: ModelRequest, actualPromptTokens: number, modelFingerprint?: string): void;
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
type CompactionReason = 'threshold' | 'manual' | 'overflow';
|
|
719
|
+
interface ContextSnapshot {
|
|
720
|
+
conversationId: string;
|
|
721
|
+
modelId: string;
|
|
722
|
+
fingerprint: string;
|
|
723
|
+
budget: ContextBudget;
|
|
724
|
+
estimate: TokenEstimate;
|
|
725
|
+
protectedMessageIds: string[];
|
|
726
|
+
rawMessageCount: number;
|
|
727
|
+
projectedMessageCount: number;
|
|
728
|
+
stale: boolean;
|
|
729
|
+
actualPromptTokens?: number;
|
|
730
|
+
actualCachedPromptTokens?: number;
|
|
731
|
+
/** false 表示只读静态估算,尚未执行下一请求的动态 Hook。 */
|
|
732
|
+
dynamicKnown: boolean;
|
|
733
|
+
summaryTokens: number;
|
|
734
|
+
checkpointId?: string;
|
|
735
|
+
prunedResults: number;
|
|
736
|
+
summaryCount: number;
|
|
737
|
+
consecutiveFailures: number;
|
|
738
|
+
automaticSummaryPaused: boolean;
|
|
739
|
+
persistence: 'disk' | 'memory' | 'unsupported';
|
|
740
|
+
}
|
|
741
|
+
interface ContextManagerOptions {
|
|
742
|
+
store?: MessageStore;
|
|
743
|
+
estimator?: TokenEstimator;
|
|
744
|
+
conversationId: string;
|
|
745
|
+
onDiagnostic?: (message: string) => void;
|
|
746
|
+
router?: ModelRouter;
|
|
747
|
+
projectRoot?: string;
|
|
748
|
+
builtInToolNames?: () => ReadonlySet<string>;
|
|
749
|
+
onSummaryUsage?: (attemptId: string, usage: Usage | undefined, modelId: string) => Promise<void>;
|
|
750
|
+
}
|
|
751
|
+
/** 原始历史与请求视图之间的协调器;不执行工具、Hook 或任何终端操作。 */
|
|
752
|
+
declare class ContextManager {
|
|
753
|
+
private readonly options;
|
|
754
|
+
private readonly estimator;
|
|
755
|
+
private snapshot?;
|
|
756
|
+
private terminals;
|
|
757
|
+
private checkpoint?;
|
|
758
|
+
private pruning;
|
|
759
|
+
private failure;
|
|
760
|
+
private summaryCount;
|
|
761
|
+
private readonly persistence;
|
|
762
|
+
constructor(options: ContextManagerOptions);
|
|
763
|
+
/** 恢复交互终态;有 start 无 finish 的运行保持 interrupted,不根据部分输出伪造成功。 */
|
|
764
|
+
restore(history?: readonly CanonicalMessage[]): Promise<void>;
|
|
765
|
+
/** 输出合法独立视图;原始消息和工具结果绝不被 Hook 共享引用修改。 */
|
|
766
|
+
project(history: readonly CanonicalMessage[]): CanonicalMessage[];
|
|
767
|
+
/** 添加本次交互终态,使下一次准备的保护范围与恢复后的边界一致。 */
|
|
768
|
+
finishInteraction(terminal: InteractionTerminal): void;
|
|
769
|
+
/**
|
|
770
|
+
* 最终 Hook 之后统一预算;输出 reserve 同时约束实际 maxTokens,超限零 Provider 调用。
|
|
771
|
+
* @returns 语义事件及准备完成的请求,不改变持久历史。
|
|
772
|
+
*/
|
|
773
|
+
prepare(history: readonly CanonicalMessage[], request: ModelRequest, profile: ModelProfile, runId?: string, reason?: CompactionReason): AsyncGenerator<SessionEvent, ModelRequest>;
|
|
774
|
+
/** 观测真实使用量只作用于对应最终请求,不把累计 usage 当成当前窗口占用。 */
|
|
775
|
+
observe(request: ModelRequest, usage: Usage, profile: ModelProfile): void;
|
|
776
|
+
/** 查询已发布快照,不运行 Hook/Provider;配置变化后明确标记 stale。 */
|
|
777
|
+
getSnapshot(): ContextSnapshot | undefined;
|
|
778
|
+
/** 从当前静态投影估算,不执行 Hook/Provider 或更新状态;恢复后即可查看检查点。 */
|
|
779
|
+
inspect(history: readonly CanonicalMessage[], request: ModelRequest, profile: ModelProfile): ContextSnapshot;
|
|
780
|
+
/** 模型或指令发生变化后使已有预算快照过期,直到下一最终请求准备成功。 */
|
|
781
|
+
invalidate(): void;
|
|
782
|
+
/** reset 同时废弃投影与交互终态。 */
|
|
783
|
+
reset(): void;
|
|
784
|
+
/** 发布实际准备请求的独立快照,查询不会触发重新压缩。 */
|
|
785
|
+
private publishSnapshot;
|
|
786
|
+
/** 最终请求与只读估算共用来源和状态计数。 */
|
|
787
|
+
private buildSnapshot;
|
|
788
|
+
/** 摘要以用户历史背景注入,不升级为系统指令或恢复旧授权。 */
|
|
789
|
+
private summaryMessage;
|
|
790
|
+
/**
|
|
791
|
+
* 旧轮次仅在工具事务闭合时可摘要;成功可由旧记录推断,失败或中断必须有运行终态来源。
|
|
792
|
+
* 该判断不代表执行成功,也不解除最近成功轮次及其后失败尾部的保护。
|
|
793
|
+
*/
|
|
794
|
+
private isClosedInteraction;
|
|
795
|
+
/** 严格检查覆盖来源、前驱链、完整终态轮次及保护集合;未知工具结果不能被冒充为成功。 */
|
|
796
|
+
private validCheckpoint;
|
|
797
|
+
/** 仅成功完成旧轮次中的白名单内置成功结果可剪裁;失败或中断轮次只参与二级摘要。 */
|
|
798
|
+
private pruningTargets;
|
|
799
|
+
/** 用候选描述替换对应结果正文,工具事务、失败标记及全部其它动态内容不变。 */
|
|
800
|
+
private applyPruningRequest;
|
|
801
|
+
/** 恢复剪裁必须满足当前来源、策略、前驱与保护范围,摘要覆盖的旧剪裁不会再次使用。 */
|
|
802
|
+
private validPruning;
|
|
803
|
+
/** 状态提交失败独立于摘要熔断;内存模式只更新内存,旧 Store 不假称可恢复。 */
|
|
804
|
+
private commit;
|
|
805
|
+
private report;
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
interface ContextSummary {
|
|
809
|
+
schemaVersion: 1;
|
|
810
|
+
goal: string;
|
|
811
|
+
constraints: string[];
|
|
812
|
+
decisions: string[];
|
|
813
|
+
completedWork: string[];
|
|
814
|
+
pendingWork: string[];
|
|
815
|
+
/** 原消息身份,不接受模型虚构来源或把旧摘要当成授权。 */
|
|
816
|
+
references: string[];
|
|
817
|
+
unknownEffects: string[];
|
|
818
|
+
}
|
|
819
|
+
interface FileObservation {
|
|
820
|
+
/** 有执行目录证据时为绝对路径;旧记录缺少依据时为原相对路径,基目录未知。 */
|
|
821
|
+
path: string;
|
|
822
|
+
sourceMessageId: string;
|
|
823
|
+
toolCallId: string;
|
|
824
|
+
operation: string;
|
|
825
|
+
}
|
|
826
|
+
interface FileDetails {
|
|
827
|
+
readFiles: FileObservation[];
|
|
828
|
+
modifiedFiles: FileObservation[];
|
|
829
|
+
failedFileOperations: FileObservation[];
|
|
830
|
+
unknownFileOperations: FileObservation[];
|
|
831
|
+
omitted: number;
|
|
832
|
+
}
|
|
833
|
+
/** 对超长结果保留总计 2000 code point 首尾正文,省略说明不冒充原始结果。 */
|
|
834
|
+
declare function truncateToolOutput(text: string, maximum?: number): string;
|
|
835
|
+
/**
|
|
836
|
+
* 从紧邻工具结果确定性提取文件事实;只认内置文件读写,不猜测命令/插件的磁盘变化。
|
|
837
|
+
* 原始成功、失败和结果未知分别记录,列表表示历史观察,不表示当前文件状态。
|
|
838
|
+
* 相对路径只按调用记录的执行根目录解析;旧历史缺少目录时保留原相对路径,位置未知。
|
|
839
|
+
* @param history 原始工具调用及紧邻结果,不执行工具或修改历史。
|
|
840
|
+
* @param _projectRoot 保留旧 API 参数;项目根不作为历史工具相对路径的推断依据。
|
|
841
|
+
* @param previous 先前检查点中的文件观察,独立复制后增量合并。
|
|
842
|
+
* @returns 有界的成功、失败和结果未知文件观察。
|
|
843
|
+
*/
|
|
844
|
+
declare function extractFileDetails(history: readonly CanonicalMessage[], _projectRoot: string, previous?: FileDetails): FileDetails;
|
|
845
|
+
/** 有界渲染唯一文件详情,不将模型生成的文本文件列表当作成功写入证据。 */
|
|
846
|
+
declare function renderFileDetails(details: FileDetails): string;
|
|
847
|
+
/** 校验结构与来源;空、超长、未知字段及虚构消息引用不能进入检查点。 */
|
|
848
|
+
declare function validateSummary(value: unknown, sourceIds: ReadonlySet<string>): ContextSummary;
|
|
849
|
+
interface SummaryServiceOptions {
|
|
850
|
+
router: ModelRouter;
|
|
851
|
+
projectRoot: string;
|
|
852
|
+
estimator?: TokenEstimator;
|
|
853
|
+
/** 真实使用量在候选校验前记账,失败摘要仍保留消耗;不得包含主任务 TTFT。 */
|
|
854
|
+
onUsage?: (attemptId: string, usage: Usage | undefined, modelId: string) => Promise<void>;
|
|
855
|
+
timeoutMs?: number;
|
|
856
|
+
}
|
|
857
|
+
interface SummaryCandidate {
|
|
858
|
+
summary: ContextSummary;
|
|
859
|
+
details: FileDetails;
|
|
860
|
+
calls: number;
|
|
861
|
+
modelId: string;
|
|
862
|
+
durationMs: number;
|
|
863
|
+
usage: Usage;
|
|
864
|
+
usageKnown: boolean;
|
|
865
|
+
}
|
|
866
|
+
/** 摘要单次流式输出文本最大防御倍数;防止模型无限输出耗尽内存。 */
|
|
867
|
+
declare const SUMMARY_OUTPUT_BUFFER_MULTIPLIER = 16;
|
|
868
|
+
/** Pi 式滚动摘要服务;无主 Loop/Hook/工具,整次操作最多四调用且总时限 120 秒。 */
|
|
869
|
+
declare class SummaryService {
|
|
870
|
+
private readonly options;
|
|
871
|
+
private readonly estimator;
|
|
872
|
+
constructor(options: SummaryServiceOptions);
|
|
873
|
+
/**
|
|
874
|
+
* 按完整用户交互分批,以旧摘要和新增原始前缀取材;中间结果只是局部候选,不激活。
|
|
875
|
+
* 单个不可拆分输入超预算、无终态、截断或非法来源均失败,取消先关闭 Provider 迭代。
|
|
876
|
+
*/
|
|
877
|
+
generate(history: readonly CanonicalMessage[], previous?: Pick<SummaryCandidate, 'summary' | 'details'>, signal?: AbortSignal): Promise<SummaryCandidate>;
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error';
|
|
881
|
+
type LogChannel = 'operation' | 'audit';
|
|
882
|
+
type LogField = string | number | boolean | null;
|
|
883
|
+
/** 单条可持久化的脱敏运行或审计事件。 */
|
|
884
|
+
interface LogEvent {
|
|
885
|
+
schemaVersion: 1;
|
|
886
|
+
timestamp: string;
|
|
887
|
+
level: LogLevel;
|
|
888
|
+
channel: LogChannel;
|
|
889
|
+
event: string;
|
|
890
|
+
sessionId: string;
|
|
891
|
+
conversationId?: string;
|
|
892
|
+
runId?: string;
|
|
893
|
+
operationId?: string;
|
|
894
|
+
toolUseId?: string;
|
|
895
|
+
fields: Record<string, LogField>;
|
|
896
|
+
}
|
|
897
|
+
/** 宿主提供的事件存储入口;审计 Sink 的写入完成代表已持久化。 */
|
|
898
|
+
interface LogSink {
|
|
899
|
+
write(event: LogEvent): Promise<void>;
|
|
900
|
+
}
|
|
901
|
+
interface LogInput {
|
|
902
|
+
level: LogLevel;
|
|
903
|
+
event: string;
|
|
904
|
+
sessionId: string;
|
|
905
|
+
conversationId?: string;
|
|
906
|
+
runId?: string;
|
|
907
|
+
operationId?: string;
|
|
908
|
+
toolUseId?: string;
|
|
909
|
+
fields?: Record<string, unknown>;
|
|
910
|
+
}
|
|
911
|
+
/** Core 与宿主共同使用的运行日志和审批审计入口。 */
|
|
912
|
+
interface EventLogger {
|
|
913
|
+
record(event: LogInput): Promise<void>;
|
|
914
|
+
recordAudit(event: LogInput): Promise<void>;
|
|
915
|
+
}
|
|
916
|
+
/** 将任意来源的字段缩减为可写入日志的固定集合。 */
|
|
917
|
+
declare function projectSafeFields(fields: Record<string, unknown>): Record<string, LogField>;
|
|
918
|
+
/** 生成不依赖模型工具调用 ID 的内部关联标识。 */
|
|
919
|
+
declare function createLogId(): string;
|
|
920
|
+
/** 只暴露固定命令类别与参数数目,避免把自由文本写入审计。 */
|
|
921
|
+
declare function commandAuditSummary(command: string): {
|
|
922
|
+
commandDigest: string;
|
|
923
|
+
commandPreview: string;
|
|
924
|
+
commandLength: number;
|
|
925
|
+
argumentCount: number;
|
|
926
|
+
};
|
|
927
|
+
/** 将批准范围绑定到最终命令、解释器、目录与执行选项。 */
|
|
928
|
+
declare function executionFingerprint(input: {
|
|
929
|
+
command: string;
|
|
930
|
+
shell: string;
|
|
931
|
+
executable: string;
|
|
932
|
+
cwd: string;
|
|
933
|
+
environmentDigest: string;
|
|
934
|
+
timeoutMs: number;
|
|
935
|
+
outputLimitBytes: number;
|
|
936
|
+
targetDigest?: string;
|
|
937
|
+
}): string;
|
|
938
|
+
/** 统一筛选和脱敏日志;运行日志失败只报告安全诊断,审计失败仍向调用方传播。 */
|
|
939
|
+
declare class StructuredLogger implements EventLogger {
|
|
940
|
+
private readonly operationSink;
|
|
941
|
+
private readonly auditSink;
|
|
942
|
+
private readonly debug;
|
|
943
|
+
private readonly onDiagnostic?;
|
|
944
|
+
constructor(options: {
|
|
945
|
+
operationSink: LogSink;
|
|
946
|
+
auditSink: LogSink;
|
|
947
|
+
debug?: boolean;
|
|
948
|
+
onDiagnostic?: (message: string) => void;
|
|
202
949
|
});
|
|
950
|
+
/** 普通日志写入失败不阻断业务,也不声称持久化成功;诊断不携带原始异常内容。 */
|
|
951
|
+
record(event: LogInput): Promise<void>;
|
|
952
|
+
/** 审计必须成功持久化;异常交由执行器拒绝启动工具或报告已执行操作的结果未知。 */
|
|
953
|
+
recordAudit(event: LogInput): Promise<void>;
|
|
954
|
+
private format;
|
|
203
955
|
}
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
956
|
+
|
|
957
|
+
interface FileLogSinkOptions {
|
|
958
|
+
directory: string;
|
|
959
|
+
prefix: 'operation' | 'audit';
|
|
960
|
+
maxBytes?: number;
|
|
961
|
+
retentionDays?: number;
|
|
962
|
+
sync?: boolean;
|
|
207
963
|
}
|
|
208
|
-
|
|
209
|
-
|
|
964
|
+
/** 将每条 JSONL 事件完整追加到本地文件,并按日期及文件大小轮转。 */
|
|
965
|
+
declare class FileLogSink implements LogSink {
|
|
966
|
+
readonly directory: string;
|
|
967
|
+
readonly prefix: 'operation' | 'audit';
|
|
968
|
+
private readonly maxBytes;
|
|
969
|
+
private readonly retentionDays?;
|
|
970
|
+
private readonly sync;
|
|
971
|
+
constructor(options: FileLogSinkOptions);
|
|
972
|
+
write(event: LogEvent): Promise<void>;
|
|
973
|
+
/** 返回该通道已占用的字节数,供宿主提示长期保留的审计用量。 */
|
|
974
|
+
getUsageBytes(): number;
|
|
975
|
+
private chooseFile;
|
|
976
|
+
private cleanupExpired;
|
|
977
|
+
private isOwnedFile;
|
|
210
978
|
}
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
979
|
+
/** 构造 CLI 与默认 SDK 使用的用户级运行及审计 Sink。 */
|
|
980
|
+
declare function createDefaultLogSinks(baseDirectory?: string): {
|
|
981
|
+
operationSink: FileLogSink;
|
|
982
|
+
auditSink: FileLogSink;
|
|
983
|
+
};
|
|
984
|
+
/** 启动时保守关闭上次进程未完成的审计事务,绝不将其当作未执行或自动重试。 */
|
|
985
|
+
declare function recoverIncompleteAudit(directory: string): Promise<number>;
|
|
986
|
+
|
|
987
|
+
interface InstructionSource {
|
|
988
|
+
path: string;
|
|
989
|
+
content: string;
|
|
215
990
|
}
|
|
216
|
-
|
|
217
|
-
|
|
991
|
+
interface InstructionSnapshot {
|
|
992
|
+
sources: readonly InstructionSource[];
|
|
993
|
+
totalBytes: number;
|
|
218
994
|
}
|
|
219
|
-
|
|
220
|
-
|
|
995
|
+
interface InstructionLoadOptions {
|
|
996
|
+
projectRoot: string;
|
|
997
|
+
cwd: string;
|
|
998
|
+
userFile?: string;
|
|
221
999
|
}
|
|
222
|
-
|
|
223
|
-
|
|
1000
|
+
/** 按用户层和项目根至 cwd 的目录链读取指令,全部成功后才返回快照。 */
|
|
1001
|
+
declare function loadInstructions(options: InstructionLoadOptions): InstructionSnapshot;
|
|
1002
|
+
|
|
1003
|
+
type ShellKind = 'bash' | 'wsl' | 'pwsh' | 'powershell';
|
|
1004
|
+
/** auto / 具名解释器,或用户显式提供的解释器可执行文件全路径。 */
|
|
1005
|
+
type ShellPreference = 'auto' | ShellKind | (string & {});
|
|
1006
|
+
interface ShellEnvironment {
|
|
1007
|
+
kind: ShellKind;
|
|
1008
|
+
executable: string;
|
|
1009
|
+
executableDigest: string;
|
|
1010
|
+
cwd: string;
|
|
1011
|
+
}
|
|
1012
|
+
interface ShellDetectOptions {
|
|
1013
|
+
preference?: ShellPreference;
|
|
1014
|
+
cwd: string;
|
|
1015
|
+
platform?: NodeJS.Platform;
|
|
1016
|
+
pathEnv?: string;
|
|
224
1017
|
}
|
|
1018
|
+
/**
|
|
1019
|
+
* 按 uname 输出分类 bash 家族:Git Bash/MSYS2/Cygwin 归 native bash,
|
|
1020
|
+
* Windows 上报告 Linux 的是 WSL launcher(独立 kind,路径语义不同)。
|
|
1021
|
+
*/
|
|
1022
|
+
declare function classifyBashOutput(unameOutput: string, platform: NodeJS.Platform): ShellKind | undefined;
|
|
1023
|
+
/**
|
|
1024
|
+
* 发现并固定实际解释器:只用 PATH 与用户显式给出的路径,不写死任何安装目录。
|
|
1025
|
+
* auto 在 Windows 上按 native Bash → WSL → pwsh → powershell 依次兜底,
|
|
1026
|
+
* bash 家族用运行时 uname 探针区分 Git Bash 与 WSL launcher。
|
|
1027
|
+
*/
|
|
1028
|
+
declare function detectShell(options: ShellDetectOptions): ShellEnvironment;
|
|
1029
|
+
|
|
1030
|
+
/** 本次会话的自动执行边界;FullAccess 只能由宿主为本次会话显式选择。 */
|
|
1031
|
+
type SessionMode = 'Approval' | 'Plan' | 'Auto' | 'FullAccess';
|
|
1032
|
+
type PermissionAction = 'allow' | 'ask' | 'deny';
|
|
1033
|
+
interface ShellScope {
|
|
1034
|
+
command: string;
|
|
1035
|
+
interpreter: string;
|
|
1036
|
+
executablePath?: string;
|
|
1037
|
+
cwd: string;
|
|
1038
|
+
executableDigest?: string;
|
|
1039
|
+
scriptDigest?: string;
|
|
1040
|
+
executionFingerprint?: string;
|
|
1041
|
+
}
|
|
1042
|
+
interface PermissionRule {
|
|
1043
|
+
action: PermissionAction;
|
|
1044
|
+
tool?: string;
|
|
1045
|
+
capability?: Capability;
|
|
1046
|
+
shell?: ShellScope;
|
|
1047
|
+
}
|
|
1048
|
+
interface PermissionRequest {
|
|
1049
|
+
mode: SessionMode;
|
|
1050
|
+
toolName: string;
|
|
1051
|
+
capabilities: readonly Capability[];
|
|
1052
|
+
dangerous?: boolean;
|
|
1053
|
+
hardDenied?: boolean;
|
|
1054
|
+
shell?: ShellScope;
|
|
1055
|
+
rules?: readonly PermissionRule[];
|
|
1056
|
+
cachedApproval?: boolean;
|
|
1057
|
+
cachedDenial?: boolean;
|
|
1058
|
+
}
|
|
1059
|
+
interface PermissionDecision {
|
|
1060
|
+
decision: PermissionAction;
|
|
1061
|
+
source: 'hard_limit' | 'plan' | 'explicit_rule' | 'session_cache' | 'mode_default';
|
|
1062
|
+
ruleIndex?: number;
|
|
1063
|
+
}
|
|
1064
|
+
/** 拒绝含糊的 Shell 前缀/通配符和结构不完整的规则。 */
|
|
1065
|
+
declare function validatePermissionRules(rules: readonly PermissionRule[]): void;
|
|
1066
|
+
/** 纯策略裁决;宿主硬限制和 Plan 始终先于任何规则或会话缓存。 */
|
|
1067
|
+
declare class PermissionPolicy {
|
|
1068
|
+
decide(request: PermissionRequest): PermissionDecision;
|
|
1069
|
+
}
|
|
1070
|
+
/** 只向模型展示当前模式与整项拒绝规则允许请求的工具。 */
|
|
1071
|
+
declare function visibleTools(tools: readonly Tool[], mode: SessionMode, rules?: readonly PermissionRule[]): Tool[];
|
|
1072
|
+
|
|
1073
|
+
type Capability = 'fs:read' | 'fs:write' | 'exec' | 'net:outbound' | 'env:read' | 'agent:spawn';
|
|
1074
|
+
interface ToolMetadata {
|
|
1075
|
+
source?: string;
|
|
1076
|
+
dangerous?: boolean;
|
|
1077
|
+
/** 所需能力的声明;v0.0.1 不据此授权,v0.0.2 的执行前权限决策才会消费。 */
|
|
1078
|
+
permissions?: Capability[];
|
|
1079
|
+
/** 工具自身等待进程资源回收,执行器不可再使用通用 Promise.race 超时。 */
|
|
1080
|
+
managesTimeout?: boolean;
|
|
1081
|
+
}
|
|
1082
|
+
interface ToolContext {
|
|
1083
|
+
rootDir: string;
|
|
1084
|
+
signal?: AbortSignal;
|
|
1085
|
+
logger?: (message: string) => void;
|
|
1086
|
+
/** 命令工具在真实进程创建后调用;审计失败时须先回收进程再报告结果未知。 */
|
|
1087
|
+
onProcessSpawned?: () => Promise<void>;
|
|
1088
|
+
onProgress?: (progress: {
|
|
1089
|
+
elapsedMs: number;
|
|
1090
|
+
outputBytes: number;
|
|
1091
|
+
}) => void;
|
|
1092
|
+
}
|
|
1093
|
+
interface Tool<TInput = Record<string, unknown>, TOutput = unknown> {
|
|
1094
|
+
readonly name: string;
|
|
1095
|
+
readonly description: string;
|
|
1096
|
+
readonly parameters: Record<string, unknown>;
|
|
1097
|
+
readonly metadata?: ToolMetadata;
|
|
1098
|
+
approvalScope?(input: TInput, rootDir: string): ShellScope;
|
|
1099
|
+
execute(input: TInput, ctx: ToolContext): Promise<TOutput>;
|
|
1100
|
+
}
|
|
1101
|
+
declare function defineTool<TInput = Record<string, unknown>, TOutput = unknown>(tool: Tool<TInput, TOutput>): Tool<TInput, TOutput>;
|
|
1102
|
+
declare function toToolDefinition(tool: Tool): ToolDefinition;
|
|
1103
|
+
|
|
1104
|
+
interface RunCommandInput {
|
|
1105
|
+
[key: string]: unknown;
|
|
1106
|
+
command: string;
|
|
1107
|
+
cwd?: string;
|
|
1108
|
+
timeout_ms?: number;
|
|
1109
|
+
}
|
|
1110
|
+
interface CommandResult {
|
|
1111
|
+
exitCode: number | null;
|
|
1112
|
+
output: string;
|
|
1113
|
+
outputTruncated: boolean;
|
|
1114
|
+
outputFile?: string;
|
|
1115
|
+
outputFileTruncated: boolean;
|
|
1116
|
+
outputBytes: number;
|
|
1117
|
+
shell: ShellEnvironment['kind'];
|
|
1118
|
+
}
|
|
1119
|
+
/** 仅清理受管 UUID 文件,避免删除用户在同目录保存的结果。 */
|
|
1120
|
+
declare function cleanupCommandResults(rootDir: string, now?: number): void;
|
|
1121
|
+
/** 使用固定解释器执行命令;超时和中止必须先处理进程树再返回。 */
|
|
1122
|
+
declare function createRunCommandTool(environment: ShellEnvironment): Tool<RunCommandInput, CommandResult>;
|
|
225
1123
|
|
|
226
1124
|
interface SandboxConfig {
|
|
227
1125
|
rootDir: string;
|
|
@@ -260,27 +1158,28 @@ declare class PathSandbox {
|
|
|
260
1158
|
private toPhysicalPath;
|
|
261
1159
|
}
|
|
262
1160
|
|
|
263
|
-
type
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
}
|
|
270
|
-
interface ToolContext {
|
|
1161
|
+
type ApprovalChoice = 'allow_once' | 'allow_session' | 'deny_once' | 'deny_session' | 'cancel';
|
|
1162
|
+
/** 宿主展示实际执行目标并取得人工选择;无通道视为非交互拒绝。 */
|
|
1163
|
+
interface ApprovalRequest {
|
|
1164
|
+
toolName: string;
|
|
1165
|
+
capabilities: readonly Capability[];
|
|
1166
|
+
input: Record<string, unknown>;
|
|
271
1167
|
rootDir: string;
|
|
272
|
-
|
|
273
|
-
|
|
1168
|
+
shell?: ShellScope;
|
|
1169
|
+
sessionAllowed: boolean;
|
|
274
1170
|
}
|
|
275
|
-
interface
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
1171
|
+
interface ApprovalChannel {
|
|
1172
|
+
requestApproval(request: ApprovalRequest, signal?: AbortSignal): Promise<ApprovalChoice>;
|
|
1173
|
+
}
|
|
1174
|
+
/** 规范化 JSON 序列化:递归对对象键按字典序排序,保证相同的输入结构产生一致的字符串和 Hash。 */
|
|
1175
|
+
declare function stableJsonStringify(value: unknown): string;
|
|
1176
|
+
/** 只在当前 Session 内复用精确调用范围,不存储原始工具参数。 */
|
|
1177
|
+
declare class SessionApprovalCache {
|
|
1178
|
+
private readonly choices;
|
|
1179
|
+
key(request: ApprovalRequest): string;
|
|
1180
|
+
get(request: ApprovalRequest): 'allow' | 'deny' | undefined;
|
|
1181
|
+
set(request: ApprovalRequest, choice: 'allow' | 'deny'): void;
|
|
281
1182
|
}
|
|
282
|
-
declare function defineTool<TInput = Record<string, unknown>, TOutput = unknown>(tool: Tool<TInput, TOutput>): Tool<TInput, TOutput>;
|
|
283
|
-
declare function toToolDefinition(tool: Tool): ToolDefinition;
|
|
284
1183
|
|
|
285
1184
|
type ConflictPolicy = 'error' | 'prefer-builtin' | 'prefer-last';
|
|
286
1185
|
declare class ToolRegistry {
|
|
@@ -408,6 +1307,13 @@ interface ExecutorOptions {
|
|
|
408
1307
|
logger?: (msg: string) => void;
|
|
409
1308
|
/** 单次工具执行超时(毫秒)。异步挂起的工具超时后返回 isError 结果,避免永久卡死会话循环 */
|
|
410
1309
|
toolTimeoutMs?: number;
|
|
1310
|
+
eventLogger?: EventLogger;
|
|
1311
|
+
sessionId?: string;
|
|
1312
|
+
runId?: string;
|
|
1313
|
+
mode?: SessionMode | (() => SessionMode);
|
|
1314
|
+
permissionRules?: readonly PermissionRule[];
|
|
1315
|
+
approvalChannel?: ApprovalChannel;
|
|
1316
|
+
approvalCache?: SessionApprovalCache;
|
|
411
1317
|
}
|
|
412
1318
|
declare class ToolExecutor {
|
|
413
1319
|
private readonly tools;
|
|
@@ -416,9 +1322,36 @@ declare class ToolExecutor {
|
|
|
416
1322
|
private readonly signal?;
|
|
417
1323
|
private readonly logger?;
|
|
418
1324
|
private readonly toolTimeoutMs;
|
|
1325
|
+
private readonly eventLogger?;
|
|
1326
|
+
private readonly sessionId?;
|
|
1327
|
+
private readonly runId?;
|
|
1328
|
+
private readonly mode;
|
|
1329
|
+
private readonly permissionRules;
|
|
1330
|
+
private readonly approvalChannel?;
|
|
1331
|
+
private readonly approvalCache;
|
|
1332
|
+
private readonly policy;
|
|
1333
|
+
private readonly neverFailures;
|
|
1334
|
+
private readonly cancellation;
|
|
419
1335
|
constructor(options: ExecutorOptions);
|
|
420
|
-
runAll
|
|
421
|
-
|
|
1336
|
+
/** 中止本轮正在等待或执行的工具;调用方仍须等待 runAll 完成资源回收及结果审计。 */
|
|
1337
|
+
cancel(): void;
|
|
1338
|
+
runAll(calls: ToolUseBlock[], onProgress?: (event: {
|
|
1339
|
+
id: string;
|
|
1340
|
+
name: string;
|
|
1341
|
+
elapsedMs: number;
|
|
1342
|
+
outputBytes: number;
|
|
1343
|
+
}) => void): Promise<ToolResultBlock[]>;
|
|
1344
|
+
/**
|
|
1345
|
+
* 在最终参数上裁决并审计一次调用,所有拒绝和异常均闭合为工具结果。
|
|
1346
|
+
* 为调用记录本次绝对工具根目录,供跨目录恢复后的文件事实解析;不使用历史目录授权。
|
|
1347
|
+
*/
|
|
1348
|
+
executeOne(call: ToolUseBlock, onProgress?: (event: {
|
|
1349
|
+
id: string;
|
|
1350
|
+
name: string;
|
|
1351
|
+
elapsedMs: number;
|
|
1352
|
+
outputBytes: number;
|
|
1353
|
+
}) => void, forcedDeny?: boolean): Promise<ToolResultBlock>;
|
|
1354
|
+
private executeResolved;
|
|
422
1355
|
/**
|
|
423
1356
|
* 给工具执行加超时护栏:Promise.race 在超时后reject,循环拿到 isError 结果继续运转,
|
|
424
1357
|
* 不会因某个异步工具(如未来接入的网络/exec 工具)挂起而永久卡死。
|
|
@@ -429,57 +1362,13 @@ declare class ToolExecutor {
|
|
|
429
1362
|
private withTimeout;
|
|
430
1363
|
}
|
|
431
1364
|
|
|
432
|
-
type ModelRole = 'default' | 'planning' | 'execution' | 'summary' | 'fast';
|
|
433
|
-
type ContextWindowValue = number | `${number}${'K' | 'k' | 'M' | 'm'}`;
|
|
434
|
-
interface ResolvedContextWindow {
|
|
435
|
-
tokens: number;
|
|
436
|
-
/** true 表示模型未声明窗口,当前值来自 Kapibala 的默认估算。 */
|
|
437
|
-
estimated: boolean;
|
|
438
|
-
}
|
|
439
|
-
declare const DEFAULT_CONTEXT_WINDOW_TOKENS = 1000000;
|
|
440
|
-
/**
|
|
441
|
-
* 将模型上下文窗口统一解析为整数 Token 数。
|
|
442
|
-
*
|
|
443
|
-
* 配置允许直接填写整数,或使用十进制 K/M 简写;未填写时返回默认 1M,并标记为估算值。
|
|
444
|
-
*/
|
|
445
|
-
declare function resolveContextWindow(value?: ContextWindowValue): ResolvedContextWindow;
|
|
446
|
-
interface ModelProfile {
|
|
447
|
-
id: string;
|
|
448
|
-
name: string;
|
|
449
|
-
provider: 'openai-compatible';
|
|
450
|
-
baseURL: string;
|
|
451
|
-
apiKeyEnv: string;
|
|
452
|
-
apiKey?: string;
|
|
453
|
-
modelName: string;
|
|
454
|
-
contextWindow?: ContextWindowValue;
|
|
455
|
-
supportsThinking?: boolean;
|
|
456
|
-
}
|
|
457
|
-
interface ModelRouter {
|
|
458
|
-
resolve(role?: ModelRole): ModelProvider;
|
|
459
|
-
getProfile(role?: ModelRole): ModelProfile;
|
|
460
|
-
}
|
|
461
|
-
declare class SimpleModelRouter implements ModelRouter {
|
|
462
|
-
private readonly providers;
|
|
463
|
-
private readonly profiles;
|
|
464
|
-
private defaultRole;
|
|
465
|
-
constructor(defaultProfile: ModelProfile, defaultProvider: ModelProvider);
|
|
466
|
-
setRole(role: ModelRole, profile: ModelProfile, provider: ModelProvider): void;
|
|
467
|
-
resolve(role?: ModelRole): ModelProvider;
|
|
468
|
-
getProfile(role?: ModelRole): ModelProfile;
|
|
469
|
-
}
|
|
470
|
-
|
|
471
|
-
interface ModelProvider {
|
|
472
|
-
readonly name: string;
|
|
473
|
-
create(req: ModelRequest): AsyncIterable<ModelEvent>;
|
|
474
|
-
/** 把一批工具结果装配成符合本协议的 canonical 消息序列 */
|
|
475
|
-
assembleToolResults(results: ToolResultBlock[]): CanonicalMessage[];
|
|
476
|
-
}
|
|
477
|
-
|
|
478
1365
|
interface OpenAIProviderOptions {
|
|
479
1366
|
baseURL: string;
|
|
480
1367
|
apiKey: string;
|
|
481
1368
|
modelName: string;
|
|
482
1369
|
supportsThinking?: boolean;
|
|
1370
|
+
/** 回传 assistant 思考历史;默认仅为 DeepSeek 官方端点启用,自建兼容网关可显式开启。 */
|
|
1371
|
+
replayReasoningContent?: boolean;
|
|
483
1372
|
/** 建立 HTTP 连接(收到响应头)的超时毫秒数;仅约束建连阶段,不限制流式读取总时长 */
|
|
484
1373
|
connectTimeoutMs?: number;
|
|
485
1374
|
}
|
|
@@ -489,47 +1378,32 @@ declare class OpenAICompatibleProvider implements ModelProvider {
|
|
|
489
1378
|
readonly apiKey: string;
|
|
490
1379
|
readonly modelName: string;
|
|
491
1380
|
readonly supportsThinking: boolean;
|
|
1381
|
+
readonly replayReasoningContent: boolean;
|
|
492
1382
|
readonly connectTimeoutMs: number;
|
|
1383
|
+
/** 初始化协议适配;思考历史回传独立于模型能力标签,仅对兼容端点启用。 */
|
|
493
1384
|
constructor(options: OpenAIProviderOptions);
|
|
1385
|
+
/** 发送流式请求,兼容端点原样回传思考历史;中断仅报告错误,不自动重放工具或请求。 */
|
|
494
1386
|
create(req: ModelRequest): AsyncIterable<ModelEvent>;
|
|
495
1387
|
assembleToolResults(results: ToolResultBlock[]): CanonicalMessage[];
|
|
1388
|
+
/** 将历史投影为协议消息;兼容端点完整回传思考片段,普通端点不发送该扩展字段。 */
|
|
496
1389
|
private translateMessagesToWire;
|
|
497
1390
|
}
|
|
498
1391
|
|
|
499
|
-
declare class JSONLMessageStore implements MessageStore {
|
|
500
|
-
readonly filePath: string;
|
|
501
|
-
constructor(filePath: string);
|
|
502
|
-
append(message: CanonicalMessage): Promise<void>;
|
|
503
|
-
load(): Promise<CanonicalMessage[]>;
|
|
504
|
-
clear(): Promise<void>;
|
|
505
|
-
/**
|
|
506
|
-
* 历史自愈(设计文档 §4.4):逐条扫描 assistant 的 tool_use,
|
|
507
|
-
* 若其后的 tool 消息未完整覆盖这些 tool_use,就地补一条 is_error 的 tool_result。
|
|
508
|
-
*
|
|
509
|
-
* 之所以做**全历史扫描**而非只看末条:崩溃可能发生在任意一轮工具执行中途,
|
|
510
|
-
* 悬挂的 tool_use 未必位于历史末尾(例如中断后用户又继续提了问)。
|
|
511
|
-
* 只看末条会漏掉夹在中间的悬挂,下一次请求仍会因上下文非法而 400。
|
|
512
|
-
*/
|
|
513
|
-
private healDanglingToolCalls;
|
|
514
|
-
}
|
|
515
|
-
|
|
516
|
-
interface MessageStore {
|
|
517
|
-
append(message: CanonicalMessage): Promise<void>;
|
|
518
|
-
load(): Promise<CanonicalMessage[]>;
|
|
519
|
-
clear(): Promise<void>;
|
|
520
|
-
}
|
|
521
|
-
|
|
522
1392
|
interface PromptAssemblerOptions {
|
|
523
1393
|
tools?: ToolRegistry;
|
|
524
1394
|
rootDir: string;
|
|
525
1395
|
agentName?: string;
|
|
526
1396
|
customInstructions?: string;
|
|
1397
|
+
instructionSources?: readonly InstructionSource[];
|
|
1398
|
+
visibleTools?: readonly Tool[];
|
|
527
1399
|
}
|
|
528
1400
|
declare class PromptAssembler {
|
|
529
1401
|
private readonly tools?;
|
|
530
1402
|
private readonly rootDir;
|
|
531
1403
|
private readonly agentName;
|
|
532
1404
|
private readonly customInstructions?;
|
|
1405
|
+
private readonly instructionSources;
|
|
1406
|
+
private readonly visibleTools?;
|
|
533
1407
|
constructor(options: PromptAssemblerOptions);
|
|
534
1408
|
assemble(): string;
|
|
535
1409
|
private getL1Behavior;
|
|
@@ -538,6 +1412,12 @@ declare class PromptAssembler {
|
|
|
538
1412
|
}
|
|
539
1413
|
|
|
540
1414
|
interface AgentLoopOptions {
|
|
1415
|
+
/** 本次交互身份,内部步骤仍独立编号。 */
|
|
1416
|
+
interactionId?: string;
|
|
1417
|
+
modelId?: string;
|
|
1418
|
+
projectHistory?: (history: readonly CanonicalMessage[]) => CanonicalMessage[];
|
|
1419
|
+
prepareRequest?: RequestPreparation;
|
|
1420
|
+
onUsage?: (request: ModelRequest, usage: Usage, attemptId: string) => Promise<void>;
|
|
541
1421
|
provider: ModelProvider;
|
|
542
1422
|
executor: ToolExecutor;
|
|
543
1423
|
tools: ToolRegistry;
|
|
@@ -546,8 +1426,18 @@ interface AgentLoopOptions {
|
|
|
546
1426
|
maxSteps?: number;
|
|
547
1427
|
maxConsecutiveErrors?: number;
|
|
548
1428
|
signal?: AbortSignal;
|
|
1429
|
+
eventLogger?: EventLogger;
|
|
1430
|
+
sessionId?: string;
|
|
1431
|
+
runId?: string;
|
|
1432
|
+
getMode?: () => SessionMode;
|
|
1433
|
+
permissionRules?: readonly PermissionRule[];
|
|
549
1434
|
}
|
|
550
1435
|
declare class AgentLoop {
|
|
1436
|
+
private readonly interactionId?;
|
|
1437
|
+
private readonly modelId?;
|
|
1438
|
+
private readonly projectHistory?;
|
|
1439
|
+
private readonly prepareRequest?;
|
|
1440
|
+
private readonly onUsage?;
|
|
551
1441
|
private readonly provider;
|
|
552
1442
|
private readonly executor;
|
|
553
1443
|
private readonly tools;
|
|
@@ -556,11 +1446,20 @@ declare class AgentLoop {
|
|
|
556
1446
|
private readonly maxSteps;
|
|
557
1447
|
private readonly maxConsecutiveErrors;
|
|
558
1448
|
private readonly signal?;
|
|
1449
|
+
private readonly eventLogger?;
|
|
1450
|
+
private readonly sessionId?;
|
|
1451
|
+
private readonly runId?;
|
|
1452
|
+
private readonly getMode;
|
|
1453
|
+
private readonly permissionRules;
|
|
559
1454
|
constructor(options: AgentLoopOptions);
|
|
560
1455
|
run(history: CanonicalMessage[]): AsyncIterable<SessionEvent>;
|
|
561
1456
|
}
|
|
562
1457
|
|
|
563
1458
|
interface SessionConfig {
|
|
1459
|
+
/** 持久会话身份;有版本化 Store 时须与头部一致,日志实例身份保持独立。 */
|
|
1460
|
+
conversationId?: string;
|
|
1461
|
+
tokenEstimator?: TokenEstimator;
|
|
1462
|
+
gitBranch?: string;
|
|
564
1463
|
defaultProfile: ModelProfile;
|
|
565
1464
|
defaultProvider: ModelProvider;
|
|
566
1465
|
store?: MessageStore;
|
|
@@ -568,8 +1467,25 @@ interface SessionConfig {
|
|
|
568
1467
|
systemPrompt?: string;
|
|
569
1468
|
maxSteps?: number;
|
|
570
1469
|
logger?: (msg: string) => void;
|
|
1470
|
+
eventLogger?: EventLogger;
|
|
1471
|
+
loggingDirectory?: string;
|
|
1472
|
+
mode?: SessionMode;
|
|
1473
|
+
permissionRules?: readonly PermissionRule[];
|
|
1474
|
+
approvalChannel?: ApprovalChannel;
|
|
1475
|
+
projectRoot?: string;
|
|
1476
|
+
cwd?: string;
|
|
1477
|
+
userInstructionsPath?: string;
|
|
1478
|
+
auditRecoveryDirectory?: string;
|
|
1479
|
+
/** 接收普通运行日志失败的脱敏诊断;诊断失败也不得中断问答或替代审计。 */
|
|
1480
|
+
onDiagnostic?: (message: string) => void;
|
|
571
1481
|
}
|
|
572
1482
|
interface SessionStats {
|
|
1483
|
+
conversationId?: string;
|
|
1484
|
+
/** 历史存在无 usage 的模型步骤时为 false,不将旧消耗伪装为精确零。 */
|
|
1485
|
+
usageKnown?: boolean;
|
|
1486
|
+
summaryUsage?: Usage;
|
|
1487
|
+
summaryUsageKnown?: boolean;
|
|
1488
|
+
contextSnapshot?: ContextSnapshot;
|
|
573
1489
|
totalTurns: number;
|
|
574
1490
|
totalTokens: Usage;
|
|
575
1491
|
activeModel: string;
|
|
@@ -579,6 +1495,17 @@ interface SessionStats {
|
|
|
579
1495
|
contextUsage: ContextUsage;
|
|
580
1496
|
}
|
|
581
1497
|
declare class AgentSession {
|
|
1498
|
+
private persistentId;
|
|
1499
|
+
private readonly configuredConversationId?;
|
|
1500
|
+
private readonly estimator?;
|
|
1501
|
+
private readonly onDiagnostic?;
|
|
1502
|
+
private readonly gitBranch?;
|
|
1503
|
+
private context;
|
|
1504
|
+
private usageKnown;
|
|
1505
|
+
private summaryUsageKnown;
|
|
1506
|
+
private summaryUsage;
|
|
1507
|
+
private readonly summaryAttempts;
|
|
1508
|
+
private readonly accountedAttempts;
|
|
582
1509
|
readonly rootDir: string;
|
|
583
1510
|
readonly tools: ToolRegistry;
|
|
584
1511
|
readonly hooks: HookRegistry;
|
|
@@ -587,13 +1514,28 @@ declare class AgentSession {
|
|
|
587
1514
|
private readonly customSystemPrompt?;
|
|
588
1515
|
private readonly maxSteps;
|
|
589
1516
|
private readonly logger?;
|
|
1517
|
+
private readonly eventLogger;
|
|
1518
|
+
private readonly sessionId;
|
|
1519
|
+
private mode;
|
|
1520
|
+
private readonly permissionRules;
|
|
1521
|
+
private readonly approvalChannel?;
|
|
1522
|
+
private readonly approvalCache;
|
|
1523
|
+
private readonly projectRoot;
|
|
1524
|
+
private readonly cwd;
|
|
1525
|
+
private readonly userInstructionsPath?;
|
|
1526
|
+
private instructionSnapshot?;
|
|
1527
|
+
private readonly auditRecoveryDirectory?;
|
|
590
1528
|
private history;
|
|
591
1529
|
private totalTurns;
|
|
592
1530
|
private usageStats;
|
|
593
1531
|
private lastMetrics?;
|
|
594
1532
|
private lastRunMetrics?;
|
|
595
1533
|
private initialized;
|
|
1534
|
+
private pendingResume;
|
|
596
1535
|
private destroyed;
|
|
1536
|
+
private cleanupStarted;
|
|
1537
|
+
private cleanupPromise?;
|
|
1538
|
+
private sessionEndFinished;
|
|
597
1539
|
private activeRun;
|
|
598
1540
|
private readonly plugins;
|
|
599
1541
|
constructor(config: SessionConfig);
|
|
@@ -601,9 +1543,26 @@ declare class AgentSession {
|
|
|
601
1543
|
use(plugin: AgentPlugin): Promise<void>;
|
|
602
1544
|
switchModel(profile: ModelProfile, role?: ModelRole, provider?: ModelProvider): void;
|
|
603
1545
|
getActiveProfile(role?: ModelRole): ModelProfile;
|
|
1546
|
+
/** 只在空闲时切换本次会话模式;宿主负责 FullAccess 的显式选择交互。 */
|
|
1547
|
+
switchMode(mode: SessionMode): void;
|
|
1548
|
+
getMode(): SessionMode;
|
|
1549
|
+
/** 返回最近一次成功装载的来源路径,不暴露指令正文。 */
|
|
1550
|
+
getInstructionSources(): string[];
|
|
1551
|
+
/** 稳定会话身份,独立于当前进程日志实例和每次用户交互。 */
|
|
1552
|
+
get conversationId(): string;
|
|
1553
|
+
/** 返回原始历史独立快照,外部修改不会改变落盘事实或当前工具事务。 */
|
|
604
1554
|
getHistory(): CanonicalMessage[];
|
|
1555
|
+
/** 返回当前投影视图,区别于原始历史;不执行模型或 Hook。 */
|
|
1556
|
+
getContextHistory(): CanonicalMessage[];
|
|
1557
|
+
/** 查询最近最终请求的预算快照,尚未准备请求时返回 undefined。 */
|
|
1558
|
+
getContextSnapshot(): ContextSnapshot | undefined;
|
|
1559
|
+
/** 执行中止后的工具/摘要与存储收口期间仍返回 true。 */
|
|
1560
|
+
isBusy(): boolean;
|
|
1561
|
+
/** 返回独立统计快照,宿主修改嵌套指标不会改变会话状态或预算展示。 */
|
|
605
1562
|
getStats(): SessionStats;
|
|
1563
|
+
/** 返回最近请求指标的独立副本;尚无完成请求时返回 undefined。 */
|
|
606
1564
|
getLastMetrics(): TurnMetrics | undefined;
|
|
1565
|
+
/** 返回最近用户任务指标的独立副本;恢复的 usage 不伪造实时任务指标。 */
|
|
607
1566
|
getLastRunMetrics(): RunMetrics | undefined;
|
|
608
1567
|
reset(): Promise<void>;
|
|
609
1568
|
/**
|
|
@@ -620,17 +1579,36 @@ declare class AgentSession {
|
|
|
620
1579
|
run(userInput: string, options?: {
|
|
621
1580
|
signal?: AbortSignal;
|
|
622
1581
|
}): AsyncIterable<SessionEvent>;
|
|
1582
|
+
/** 单次任务执行主体;调用方 return 的中止与 finally 清理由外层统一协调。 */
|
|
1583
|
+
private runOperation;
|
|
623
1584
|
destroy(): Promise<void>;
|
|
624
1585
|
private assertIdle;
|
|
625
1586
|
/**
|
|
626
|
-
*
|
|
1587
|
+
* 计算最近一次内部模型请求的上下文占用;无 usage 时显式标注预算估算。
|
|
627
1588
|
* run 累计 promptTokens 会重复计算每一步都重发的历史,不能用于窗口占用率。
|
|
628
1589
|
*/
|
|
629
1590
|
private createContextUsage;
|
|
630
1591
|
private persistAssistant;
|
|
1592
|
+
/** 创建上下文协调器并注入当前路由;摘要不经过主任务 Loop,插件结果不默认为可剪裁。 */
|
|
1593
|
+
private createContextManager;
|
|
1594
|
+
/** 摘要实际消耗按 attempt 身份独立累加;缺失消耗保留未知,不计入主任务指标。 */
|
|
1595
|
+
private accountSummaryUsage;
|
|
1596
|
+
/**
|
|
1597
|
+
* 空闲时手动摘要旧完整前缀,不创建用户任务、不执行工具,不突破当前与最近成功交互。
|
|
1598
|
+
* 迭代结束或取消后等候摘要与提交收口,再释放执行状态;已提交检查点保持有效。
|
|
1599
|
+
*/
|
|
1600
|
+
compact(options?: {
|
|
1601
|
+
signal?: AbortSignal;
|
|
1602
|
+
}): AsyncGenerator<SessionEvent>;
|
|
1603
|
+
/** 手动压缩执行主体,接收由消费者生命周期拥有的中止信号。 */
|
|
1604
|
+
private compactOperation;
|
|
1605
|
+
/** 以模型 attempt 身份幂等累加真实消耗;非法或缺失 usage 保持未知。 */
|
|
1606
|
+
private logContextEvent;
|
|
1607
|
+
/** 以模型 attempt 身份幂等累加真实消耗;非法或缺失 usage 保持未知。 */
|
|
1608
|
+
private accountUsage;
|
|
631
1609
|
private persistToolMessages;
|
|
632
1610
|
private closeInterruptedToolCalls;
|
|
633
1611
|
private findClosedToolMessages;
|
|
634
1612
|
}
|
|
635
1613
|
|
|
636
|
-
export { AbortError, AgentLoop, type AgentLoopOptions, type AgentPlugin, AgentSession, type CanonicalMessage, type Capability, type ConflictPolicy, type ContentBlock, type ContextUsage, type ContextWindowValue, DEFAULT_CONTEXT_WINDOW_TOKENS, type ExecutorOptions, FatalError, type HookContext, type HookHandlers, type HookPoint, HookRegistry, JSONLMessageStore, KapibalaError, type MessageRole, type MessageStore, ModelError, type ModelEvent, type ModelProfile, type ModelProvider, type ModelRequest, type ModelRole, type ModelRouter, OpenAICompatibleProvider, type OpenAIProviderOptions, PathSandbox, type PluginContext, PromptAssembler, type PromptAssemblerOptions, type RedactedThinkingBlock, type ResolvedContextWindow, type RunMetrics, type SandboxConfig, SessionBusyError, type SessionConfig, type SessionEvent, type SessionStats, SimpleModelRouter, type StepLogEntry, type StepLogStage, 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, defineTool, editFileTool, globTool, grepTool, isTextBlock, isThinkingBlock, isToolResultBlock, isToolUseBlock, readFileTool, resolveContextWindow, toToolDefinition, writeFileTool };
|
|
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 };
|