@kiturone/kapibala 0.0.2 → 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 +5 -1
- package/dist/index.cjs +3068 -347
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +750 -104
- package/dist/index.d.ts +750 -104
- package/dist/index.js +3032 -338
- package/dist/index.js.map +1 -1
- package/package.json +4 -1
package/dist/index.d.ts
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;
|
|
@@ -37,9 +136,21 @@ interface Usage {
|
|
|
37
136
|
promptTokens: number;
|
|
38
137
|
completionTokens: number;
|
|
39
138
|
totalTokens: number;
|
|
139
|
+
/** Provider 明确提供的缓存命中输入量;缺失表示未知,不能按零推断。 */
|
|
140
|
+
cachedPromptTokens?: number;
|
|
40
141
|
}
|
|
41
142
|
type MessageRole = 'user' | 'assistant' | 'system' | 'tool';
|
|
42
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';
|
|
43
154
|
role: MessageRole;
|
|
44
155
|
content: ContentBlock[];
|
|
45
156
|
timestamp?: number;
|
|
@@ -74,11 +185,15 @@ interface RunMetrics {
|
|
|
74
185
|
turns: number;
|
|
75
186
|
toolCalls: number;
|
|
76
187
|
status: 'completed' | 'failed' | 'aborted';
|
|
188
|
+
/** 模型失败的脱敏汇总;保留具体阶段与原因,不携带请求或响应正文。 */
|
|
189
|
+
failure?: ModelErrorInfo;
|
|
77
190
|
/** 最近一次内部模型请求占用的上下文;不使用 run 累计 promptTokens。 */
|
|
78
191
|
contextUsage?: ContextUsage;
|
|
79
192
|
}
|
|
80
193
|
interface ContextUsage {
|
|
81
194
|
usedTokens?: number;
|
|
195
|
+
/** true 表示未收到当前请求 usage,输入占用使用预算估算,不能用于计费。 */
|
|
196
|
+
estimatedUsage?: boolean;
|
|
82
197
|
limitTokens: number;
|
|
83
198
|
percent?: number;
|
|
84
199
|
estimatedLimit: boolean;
|
|
@@ -100,6 +215,56 @@ interface StepLogEntry {
|
|
|
100
215
|
* 不应直接把本类型当作长期兼容的网络协议。
|
|
101
216
|
*/
|
|
102
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
|
+
} | {
|
|
103
268
|
type: 'turn_start';
|
|
104
269
|
turn: number;
|
|
105
270
|
} | {
|
|
@@ -155,6 +320,7 @@ type SessionEvent = {
|
|
|
155
320
|
} | {
|
|
156
321
|
type: 'error';
|
|
157
322
|
error: Error;
|
|
323
|
+
modelError?: ModelErrorInfo;
|
|
158
324
|
};
|
|
159
325
|
type ModelEvent = {
|
|
160
326
|
type: 'text_delta';
|
|
@@ -182,6 +348,7 @@ type ModelEvent = {
|
|
|
182
348
|
usage?: Usage;
|
|
183
349
|
ttftMs?: number;
|
|
184
350
|
durationMs?: number;
|
|
351
|
+
finishReason?: string;
|
|
185
352
|
};
|
|
186
353
|
interface ToolDefinition {
|
|
187
354
|
name: string;
|
|
@@ -196,48 +363,518 @@ interface ModelRequest {
|
|
|
196
363
|
temperature?: number;
|
|
197
364
|
maxTokens?: number;
|
|
198
365
|
}
|
|
366
|
+
/** runtime 通用请求准备契约;实现可以预算或投影,Loop 不依赖具体上下文管理器。 */
|
|
367
|
+
type RequestPreparation = (request: ModelRequest, history: readonly CanonicalMessage[], reason?: 'threshold' | 'overflow') => AsyncGenerator<SessionEvent, ModelRequest>;
|
|
199
368
|
|
|
369
|
+
/** 生成进程内单调递增的 UUIDv7;时钟回拨时沿用逻辑时间,序列耗尽才推进时间。 */
|
|
370
|
+
declare function createMessageId(): string;
|
|
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
|
+
}
|
|
200
386
|
/**
|
|
201
|
-
*
|
|
387
|
+
* 构造合法且独立的请求视图:只接受紧邻事务的结果,缺失结果标为未知;重复调用身份明确失败。
|
|
388
|
+
* 合并仅适用于纯文本的同角色消息,失败正文不重放,所有来源均可追踪。
|
|
202
389
|
*/
|
|
203
|
-
declare
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
code?: string;
|
|
209
|
-
retryPolicy?: 'never' | 'immediate' | 'backoff' | 'after_user_action';
|
|
210
|
-
safeMessage?: string;
|
|
211
|
-
});
|
|
390
|
+
declare function normalizeHistory(input: readonly CanonicalMessage[]): NormalizedHistory;
|
|
391
|
+
interface InteractionBoundary {
|
|
392
|
+
interactionId: string;
|
|
393
|
+
status: 'completed' | 'failed' | 'interrupted';
|
|
394
|
+
messageIds: string[];
|
|
212
395
|
}
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
constructor(message: string, options?: {
|
|
217
|
-
status?: number;
|
|
218
|
-
retryable?: boolean;
|
|
219
|
-
});
|
|
396
|
+
interface InteractionTerminal {
|
|
397
|
+
interactionId: string;
|
|
398
|
+
status: InteractionBoundary['status'];
|
|
220
399
|
}
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
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;
|
|
224
424
|
}
|
|
225
|
-
|
|
226
|
-
|
|
425
|
+
|
|
426
|
+
interface MessageStore {
|
|
427
|
+
append(message: CanonicalMessage): Promise<void>;
|
|
428
|
+
load(): Promise<CanonicalMessage[]>;
|
|
429
|
+
clear(): Promise<void>;
|
|
227
430
|
}
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
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;
|
|
232
505
|
}
|
|
233
|
-
|
|
234
|
-
|
|
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;
|
|
235
528
|
}
|
|
236
|
-
|
|
237
|
-
|
|
529
|
+
|
|
530
|
+
interface ProjectIdentity {
|
|
531
|
+
projectRoot: string;
|
|
532
|
+
cwd: string;
|
|
533
|
+
projectKey: string;
|
|
534
|
+
gitBranch?: string;
|
|
535
|
+
gitWorktree?: boolean;
|
|
238
536
|
}
|
|
239
|
-
|
|
240
|
-
|
|
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>;
|
|
241
878
|
}
|
|
242
879
|
|
|
243
880
|
type LogLevel = 'trace' | 'debug' | 'info' | 'warn' | 'error';
|
|
@@ -251,6 +888,7 @@ interface LogEvent {
|
|
|
251
888
|
channel: LogChannel;
|
|
252
889
|
event: string;
|
|
253
890
|
sessionId: string;
|
|
891
|
+
conversationId?: string;
|
|
254
892
|
runId?: string;
|
|
255
893
|
operationId?: string;
|
|
256
894
|
toolUseId?: string;
|
|
@@ -264,6 +902,7 @@ interface LogInput {
|
|
|
264
902
|
level: LogLevel;
|
|
265
903
|
event: string;
|
|
266
904
|
sessionId: string;
|
|
905
|
+
conversationId?: string;
|
|
267
906
|
runId?: string;
|
|
268
907
|
operationId?: string;
|
|
269
908
|
toolUseId?: string;
|
|
@@ -702,7 +1341,10 @@ declare class ToolExecutor {
|
|
|
702
1341
|
elapsedMs: number;
|
|
703
1342
|
outputBytes: number;
|
|
704
1343
|
}) => void): Promise<ToolResultBlock[]>;
|
|
705
|
-
/**
|
|
1344
|
+
/**
|
|
1345
|
+
* 在最终参数上裁决并审计一次调用,所有拒绝和异常均闭合为工具结果。
|
|
1346
|
+
* 为调用记录本次绝对工具根目录,供跨目录恢复后的文件事实解析;不使用历史目录授权。
|
|
1347
|
+
*/
|
|
706
1348
|
executeOne(call: ToolUseBlock, onProgress?: (event: {
|
|
707
1349
|
id: string;
|
|
708
1350
|
name: string;
|
|
@@ -720,57 +1362,13 @@ declare class ToolExecutor {
|
|
|
720
1362
|
private withTimeout;
|
|
721
1363
|
}
|
|
722
1364
|
|
|
723
|
-
type ModelRole = 'default' | 'planning' | 'execution' | 'summary' | 'fast';
|
|
724
|
-
type ContextWindowValue = number | `${number}${'K' | 'k' | 'M' | 'm'}`;
|
|
725
|
-
interface ResolvedContextWindow {
|
|
726
|
-
tokens: number;
|
|
727
|
-
/** true 表示模型未声明窗口,当前值来自 Kapibala 的默认估算。 */
|
|
728
|
-
estimated: boolean;
|
|
729
|
-
}
|
|
730
|
-
declare const DEFAULT_CONTEXT_WINDOW_TOKENS = 1000000;
|
|
731
|
-
/**
|
|
732
|
-
* 将模型上下文窗口统一解析为整数 Token 数。
|
|
733
|
-
*
|
|
734
|
-
* 配置允许直接填写整数,或使用十进制 K/M 简写;未填写时返回默认 1M,并标记为估算值。
|
|
735
|
-
*/
|
|
736
|
-
declare function resolveContextWindow(value?: ContextWindowValue): ResolvedContextWindow;
|
|
737
|
-
interface ModelProfile {
|
|
738
|
-
id: string;
|
|
739
|
-
name: string;
|
|
740
|
-
provider: 'openai-compatible';
|
|
741
|
-
baseURL: string;
|
|
742
|
-
apiKeyEnv: string;
|
|
743
|
-
apiKey?: string;
|
|
744
|
-
modelName: string;
|
|
745
|
-
contextWindow?: ContextWindowValue;
|
|
746
|
-
supportsThinking?: boolean;
|
|
747
|
-
}
|
|
748
|
-
interface ModelRouter {
|
|
749
|
-
resolve(role?: ModelRole): ModelProvider;
|
|
750
|
-
getProfile(role?: ModelRole): ModelProfile;
|
|
751
|
-
}
|
|
752
|
-
declare class SimpleModelRouter implements ModelRouter {
|
|
753
|
-
private readonly providers;
|
|
754
|
-
private readonly profiles;
|
|
755
|
-
private defaultRole;
|
|
756
|
-
constructor(defaultProfile: ModelProfile, defaultProvider: ModelProvider);
|
|
757
|
-
setRole(role: ModelRole, profile: ModelProfile, provider: ModelProvider): void;
|
|
758
|
-
resolve(role?: ModelRole): ModelProvider;
|
|
759
|
-
getProfile(role?: ModelRole): ModelProfile;
|
|
760
|
-
}
|
|
761
|
-
|
|
762
|
-
interface ModelProvider {
|
|
763
|
-
readonly name: string;
|
|
764
|
-
create(req: ModelRequest): AsyncIterable<ModelEvent>;
|
|
765
|
-
/** 把一批工具结果装配成符合本协议的 canonical 消息序列 */
|
|
766
|
-
assembleToolResults(results: ToolResultBlock[]): CanonicalMessage[];
|
|
767
|
-
}
|
|
768
|
-
|
|
769
1365
|
interface OpenAIProviderOptions {
|
|
770
1366
|
baseURL: string;
|
|
771
1367
|
apiKey: string;
|
|
772
1368
|
modelName: string;
|
|
773
1369
|
supportsThinking?: boolean;
|
|
1370
|
+
/** 回传 assistant 思考历史;默认仅为 DeepSeek 官方端点启用,自建兼容网关可显式开启。 */
|
|
1371
|
+
replayReasoningContent?: boolean;
|
|
774
1372
|
/** 建立 HTTP 连接(收到响应头)的超时毫秒数;仅约束建连阶段,不限制流式读取总时长 */
|
|
775
1373
|
connectTimeoutMs?: number;
|
|
776
1374
|
}
|
|
@@ -780,36 +1378,17 @@ declare class OpenAICompatibleProvider implements ModelProvider {
|
|
|
780
1378
|
readonly apiKey: string;
|
|
781
1379
|
readonly modelName: string;
|
|
782
1380
|
readonly supportsThinking: boolean;
|
|
1381
|
+
readonly replayReasoningContent: boolean;
|
|
783
1382
|
readonly connectTimeoutMs: number;
|
|
1383
|
+
/** 初始化协议适配;思考历史回传独立于模型能力标签,仅对兼容端点启用。 */
|
|
784
1384
|
constructor(options: OpenAIProviderOptions);
|
|
1385
|
+
/** 发送流式请求,兼容端点原样回传思考历史;中断仅报告错误,不自动重放工具或请求。 */
|
|
785
1386
|
create(req: ModelRequest): AsyncIterable<ModelEvent>;
|
|
786
1387
|
assembleToolResults(results: ToolResultBlock[]): CanonicalMessage[];
|
|
1388
|
+
/** 将历史投影为协议消息;兼容端点完整回传思考片段,普通端点不发送该扩展字段。 */
|
|
787
1389
|
private translateMessagesToWire;
|
|
788
1390
|
}
|
|
789
1391
|
|
|
790
|
-
declare class JSONLMessageStore implements MessageStore {
|
|
791
|
-
readonly filePath: string;
|
|
792
|
-
constructor(filePath: string);
|
|
793
|
-
append(message: CanonicalMessage): Promise<void>;
|
|
794
|
-
load(): Promise<CanonicalMessage[]>;
|
|
795
|
-
clear(): Promise<void>;
|
|
796
|
-
/**
|
|
797
|
-
* 历史自愈(设计文档 §4.4):逐条扫描 assistant 的 tool_use,
|
|
798
|
-
* 若其后的 tool 消息未完整覆盖这些 tool_use,就地补一条 is_error 的 tool_result。
|
|
799
|
-
*
|
|
800
|
-
* 之所以做**全历史扫描**而非只看末条:崩溃可能发生在任意一轮工具执行中途,
|
|
801
|
-
* 悬挂的 tool_use 未必位于历史末尾(例如中断后用户又继续提了问)。
|
|
802
|
-
* 只看末条会漏掉夹在中间的悬挂,下一次请求仍会因上下文非法而 400。
|
|
803
|
-
*/
|
|
804
|
-
private healDanglingToolCalls;
|
|
805
|
-
}
|
|
806
|
-
|
|
807
|
-
interface MessageStore {
|
|
808
|
-
append(message: CanonicalMessage): Promise<void>;
|
|
809
|
-
load(): Promise<CanonicalMessage[]>;
|
|
810
|
-
clear(): Promise<void>;
|
|
811
|
-
}
|
|
812
|
-
|
|
813
1392
|
interface PromptAssemblerOptions {
|
|
814
1393
|
tools?: ToolRegistry;
|
|
815
1394
|
rootDir: string;
|
|
@@ -833,6 +1412,12 @@ declare class PromptAssembler {
|
|
|
833
1412
|
}
|
|
834
1413
|
|
|
835
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>;
|
|
836
1421
|
provider: ModelProvider;
|
|
837
1422
|
executor: ToolExecutor;
|
|
838
1423
|
tools: ToolRegistry;
|
|
@@ -848,6 +1433,11 @@ interface AgentLoopOptions {
|
|
|
848
1433
|
permissionRules?: readonly PermissionRule[];
|
|
849
1434
|
}
|
|
850
1435
|
declare class AgentLoop {
|
|
1436
|
+
private readonly interactionId?;
|
|
1437
|
+
private readonly modelId?;
|
|
1438
|
+
private readonly projectHistory?;
|
|
1439
|
+
private readonly prepareRequest?;
|
|
1440
|
+
private readonly onUsage?;
|
|
851
1441
|
private readonly provider;
|
|
852
1442
|
private readonly executor;
|
|
853
1443
|
private readonly tools;
|
|
@@ -866,6 +1456,10 @@ declare class AgentLoop {
|
|
|
866
1456
|
}
|
|
867
1457
|
|
|
868
1458
|
interface SessionConfig {
|
|
1459
|
+
/** 持久会话身份;有版本化 Store 时须与头部一致,日志实例身份保持独立。 */
|
|
1460
|
+
conversationId?: string;
|
|
1461
|
+
tokenEstimator?: TokenEstimator;
|
|
1462
|
+
gitBranch?: string;
|
|
869
1463
|
defaultProfile: ModelProfile;
|
|
870
1464
|
defaultProvider: ModelProvider;
|
|
871
1465
|
store?: MessageStore;
|
|
@@ -886,6 +1480,12 @@ interface SessionConfig {
|
|
|
886
1480
|
onDiagnostic?: (message: string) => void;
|
|
887
1481
|
}
|
|
888
1482
|
interface SessionStats {
|
|
1483
|
+
conversationId?: string;
|
|
1484
|
+
/** 历史存在无 usage 的模型步骤时为 false,不将旧消耗伪装为精确零。 */
|
|
1485
|
+
usageKnown?: boolean;
|
|
1486
|
+
summaryUsage?: Usage;
|
|
1487
|
+
summaryUsageKnown?: boolean;
|
|
1488
|
+
contextSnapshot?: ContextSnapshot;
|
|
889
1489
|
totalTurns: number;
|
|
890
1490
|
totalTokens: Usage;
|
|
891
1491
|
activeModel: string;
|
|
@@ -895,6 +1495,17 @@ interface SessionStats {
|
|
|
895
1495
|
contextUsage: ContextUsage;
|
|
896
1496
|
}
|
|
897
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;
|
|
898
1509
|
readonly rootDir: string;
|
|
899
1510
|
readonly tools: ToolRegistry;
|
|
900
1511
|
readonly hooks: HookRegistry;
|
|
@@ -920,7 +1531,11 @@ declare class AgentSession {
|
|
|
920
1531
|
private lastMetrics?;
|
|
921
1532
|
private lastRunMetrics?;
|
|
922
1533
|
private initialized;
|
|
1534
|
+
private pendingResume;
|
|
923
1535
|
private destroyed;
|
|
1536
|
+
private cleanupStarted;
|
|
1537
|
+
private cleanupPromise?;
|
|
1538
|
+
private sessionEndFinished;
|
|
924
1539
|
private activeRun;
|
|
925
1540
|
private readonly plugins;
|
|
926
1541
|
constructor(config: SessionConfig);
|
|
@@ -933,9 +1548,21 @@ declare class AgentSession {
|
|
|
933
1548
|
getMode(): SessionMode;
|
|
934
1549
|
/** 返回最近一次成功装载的来源路径,不暴露指令正文。 */
|
|
935
1550
|
getInstructionSources(): string[];
|
|
1551
|
+
/** 稳定会话身份,独立于当前进程日志实例和每次用户交互。 */
|
|
1552
|
+
get conversationId(): string;
|
|
1553
|
+
/** 返回原始历史独立快照,外部修改不会改变落盘事实或当前工具事务。 */
|
|
936
1554
|
getHistory(): CanonicalMessage[];
|
|
1555
|
+
/** 返回当前投影视图,区别于原始历史;不执行模型或 Hook。 */
|
|
1556
|
+
getContextHistory(): CanonicalMessage[];
|
|
1557
|
+
/** 查询最近最终请求的预算快照,尚未准备请求时返回 undefined。 */
|
|
1558
|
+
getContextSnapshot(): ContextSnapshot | undefined;
|
|
1559
|
+
/** 执行中止后的工具/摘要与存储收口期间仍返回 true。 */
|
|
1560
|
+
isBusy(): boolean;
|
|
1561
|
+
/** 返回独立统计快照,宿主修改嵌套指标不会改变会话状态或预算展示。 */
|
|
937
1562
|
getStats(): SessionStats;
|
|
1563
|
+
/** 返回最近请求指标的独立副本;尚无完成请求时返回 undefined。 */
|
|
938
1564
|
getLastMetrics(): TurnMetrics | undefined;
|
|
1565
|
+
/** 返回最近用户任务指标的独立副本;恢复的 usage 不伪造实时任务指标。 */
|
|
939
1566
|
getLastRunMetrics(): RunMetrics | undefined;
|
|
940
1567
|
reset(): Promise<void>;
|
|
941
1568
|
/**
|
|
@@ -952,17 +1579,36 @@ declare class AgentSession {
|
|
|
952
1579
|
run(userInput: string, options?: {
|
|
953
1580
|
signal?: AbortSignal;
|
|
954
1581
|
}): AsyncIterable<SessionEvent>;
|
|
1582
|
+
/** 单次任务执行主体;调用方 return 的中止与 finally 清理由外层统一协调。 */
|
|
1583
|
+
private runOperation;
|
|
955
1584
|
destroy(): Promise<void>;
|
|
956
1585
|
private assertIdle;
|
|
957
1586
|
/**
|
|
958
|
-
*
|
|
1587
|
+
* 计算最近一次内部模型请求的上下文占用;无 usage 时显式标注预算估算。
|
|
959
1588
|
* run 累计 promptTokens 会重复计算每一步都重发的历史,不能用于窗口占用率。
|
|
960
1589
|
*/
|
|
961
1590
|
private createContextUsage;
|
|
962
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;
|
|
963
1609
|
private persistToolMessages;
|
|
964
1610
|
private closeInterruptedToolCalls;
|
|
965
1611
|
private findClosedToolMessages;
|
|
966
1612
|
}
|
|
967
1613
|
|
|
968
|
-
export { AbortError, AgentLoop, type AgentLoopOptions, type AgentPlugin, AgentSession, type ApprovalChannel, type ApprovalChoice, type ApprovalRequest, type CanonicalMessage, type Capability, type CommandResult, type ConflictPolicy, type ContentBlock, type ContextUsage, type ContextWindowValue, DEFAULT_CONTEXT_WINDOW_TOKENS, type EventLogger, type ExecutorOptions, FatalError, FileLogSink, type FileLogSinkOptions, type HookContext, type HookHandlers, type HookPoint, HookRegistry, type InstructionLoadOptions, type InstructionSnapshot, type InstructionSource, JSONLMessageStore, KapibalaError, type LogChannel, type LogEvent, type LogField, type LogInput, type LogLevel, type LogSink, type MessageRole, type MessageStore, ModelError, type ModelEvent, type ModelProfile, type ModelProvider, type ModelRequest, type ModelRole, type ModelRouter, OpenAICompatibleProvider, type OpenAIProviderOptions, PathSandbox, type PermissionAction, type PermissionDecision, PermissionPolicy, type PermissionRequest, type PermissionRule, type PluginContext, PromptAssembler, type PromptAssemblerOptions, type RedactedThinkingBlock, type ResolvedContextWindow, type RunCommandInput, type RunMetrics, type SandboxConfig, SessionApprovalCache, SessionBusyError, type SessionConfig, type SessionEvent, type SessionMode, type SessionStats, type ShellDetectOptions, type ShellEnvironment, type ShellKind, type ShellPreference, type ShellScope, SimpleModelRouter, type StepLogEntry, type StepLogStage, StructuredLogger, type TextBlock, type ThinkingBlock, type Tool, type ToolContext, type ToolDecision, type ToolDefinition, ToolError, ToolExecutor, type ToolMetadata, ToolNotFound, ToolRegistry, type ToolResultBlock, type ToolUseBlock, TransportError, type TurnMetrics, type Usage, builtinTools, classifyBashOutput, cleanupCommandResults, commandAuditSummary, createDefaultLogSinks, createLogId, createRunCommandTool, defineTool, detectShell, editFileTool, executionFingerprint, globTool, grepTool, isTextBlock, isThinkingBlock, isToolResultBlock, isToolUseBlock, loadInstructions, projectSafeFields, readFileTool, recoverIncompleteAudit, resolveContextWindow, stableJsonStringify, toToolDefinition, validatePermissionRules, visibleTools, writeFileTool };
|
|
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 };
|