@vessel-agent/agent 0.0.0-stage → 2.3.0-beta.2
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/package.json +30 -4
- package/src/address-display.ts +141 -0
- package/src/conversation-budget.ts +651 -0
- package/src/conversation-store.ts +351 -0
- package/src/distress.ts +161 -0
- package/src/env-info-scope.ts +153 -0
- package/src/error-text.ts +28 -0
- package/src/inbox-source.ts +73 -0
- package/src/inbox.ts +2335 -0
- package/src/index.ts +273 -0
- package/src/member-cwd.ts +128 -0
- package/src/member-ports.ts +162 -0
- package/src/refs.ts +51 -0
- package/src/registry.ts +741 -0
- package/src/runtime.ts +2501 -0
- package/src/self-card-delta.ts +428 -0
- package/src/service.ts +9212 -0
- package/src/snapshot.ts +614 -0
- package/src/team-address.ts +96 -0
- package/src/team-log.ts +487 -0
- package/src/team-service.ts +1966 -0
- package/src/team-slug.ts +167 -0
- package/src/team-store.ts +619 -0
- package/src/tool.ts +1306 -0
- package/src/types/budget.ts +168 -0
- package/src/types/constants.ts +17 -0
- package/src/types/dispatch.ts +133 -0
- package/src/types/events.ts +132 -0
- package/src/types/execution.ts +289 -0
- package/src/types/lifecycle.ts +372 -0
- package/src/types/member.ts +221 -0
- package/src/types/message.ts +113 -0
- package/src/types/results.ts +64 -0
- package/src/types/roster.ts +137 -0
- package/src/types/service.ts +702 -0
- package/src/types/session.ts +102 -0
- package/src/types/team.ts +558 -0
- package/src/types.ts +22 -0
- package/README.md +0 -3
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Conversation 预算状态(`<dataDir>/conversations/<tenant>.json`,0.19 S4)。
|
|
3
|
+
*
|
|
4
|
+
* - 构造时同步加载;缺失 = 空,损坏 = unavailable(不覆盖文件);
|
|
5
|
+
* - 有界:最多 1000 条按 last_activity 淘汰,带 override / blocked 的额外保留 ≤ 50;
|
|
6
|
+
* - `atomicWrite` + 0600;hop / activity 变更 debounce,turn 完成 / block / override 强制写;
|
|
7
|
+
* - 单写者:一个 AgentService / 一个 dataDir;不做跨进程监听。
|
|
8
|
+
*
|
|
9
|
+
* @module @vessel-agent/agent
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { readFileSync } from 'node:fs';
|
|
13
|
+
import { join } from 'node:path';
|
|
14
|
+
import { atomicWrite, type Logger, noopLogger } from '@vessel-agent/core';
|
|
15
|
+
import { errorText } from './error-text.js';
|
|
16
|
+
import type { BudgetBlockReason, BudgetDimension } from './types.js';
|
|
17
|
+
|
|
18
|
+
export const CONVERSATION_STORE_VERSION = 1;
|
|
19
|
+
export const MAX_CONVERSATIONS = 1000;
|
|
20
|
+
export const MAX_PROTECTED_CONVERSATIONS = 50;
|
|
21
|
+
export const MAX_CONVERSATION_EDGES = 32;
|
|
22
|
+
export const CONVERSATION_WRITE_DEBOUNCE_MS = 50;
|
|
23
|
+
|
|
24
|
+
const DIMENSIONS: readonly BudgetDimension[] = ['hops', 'turns', 'tokens', 'wall_clock', 'cycle'];
|
|
25
|
+
const BLOCK_REASONS: readonly BudgetBlockReason[] = [
|
|
26
|
+
'budget_exceeded',
|
|
27
|
+
'cycle_detected',
|
|
28
|
+
'budget_unavailable',
|
|
29
|
+
];
|
|
30
|
+
|
|
31
|
+
export interface StoredConversationEdge {
|
|
32
|
+
from: string;
|
|
33
|
+
to: string;
|
|
34
|
+
count: number;
|
|
35
|
+
last_ts: number;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface StoredConversationOverride {
|
|
39
|
+
max: number;
|
|
40
|
+
by: 'human';
|
|
41
|
+
via: 'cli' | 'api';
|
|
42
|
+
at: number;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface StoredConversation {
|
|
46
|
+
conversation_id: string;
|
|
47
|
+
team_id?: string;
|
|
48
|
+
created_at: number;
|
|
49
|
+
last_activity: number;
|
|
50
|
+
hops: number;
|
|
51
|
+
turns: number;
|
|
52
|
+
total_tokens: number;
|
|
53
|
+
edges: StoredConversationEdge[];
|
|
54
|
+
overrides: Partial<Record<BudgetDimension, StoredConversationOverride>>;
|
|
55
|
+
blocked?: { dimension: BudgetDimension; reason: BudgetBlockReason; at: number };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export interface ConversationStoreFile {
|
|
59
|
+
v: 1;
|
|
60
|
+
conversations: StoredConversation[];
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface ConversationStoreOptions {
|
|
64
|
+
dataDir: string;
|
|
65
|
+
tenantId: string;
|
|
66
|
+
logger?: Logger;
|
|
67
|
+
now?: () => number;
|
|
68
|
+
/** 写入合并窗口;缺省 50ms */
|
|
69
|
+
debounceMs?: number;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function conversationsPath(dataDir: string, tenantId: string): string {
|
|
73
|
+
return join(dataDir, 'conversations', `${tenantId}.json`);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
77
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function isFiniteNumber(value: unknown): value is number {
|
|
81
|
+
return typeof value === 'number' && Number.isFinite(value);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function isEdge(value: unknown): value is StoredConversationEdge {
|
|
85
|
+
if (!isRecord(value)) return false;
|
|
86
|
+
return (
|
|
87
|
+
typeof value.from === 'string' &&
|
|
88
|
+
typeof value.to === 'string' &&
|
|
89
|
+
isFiniteNumber(value.count) &&
|
|
90
|
+
isFiniteNumber(value.last_ts)
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function isOverride(value: unknown): value is StoredConversationOverride {
|
|
95
|
+
if (!isRecord(value)) return false;
|
|
96
|
+
return (
|
|
97
|
+
isFiniteNumber(value.max) &&
|
|
98
|
+
value.by === 'human' &&
|
|
99
|
+
(value.via === 'cli' || value.via === 'api') &&
|
|
100
|
+
isFiniteNumber(value.at)
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function isBlocked(value: unknown): value is NonNullable<StoredConversation['blocked']> {
|
|
105
|
+
if (!isRecord(value)) return false;
|
|
106
|
+
return (
|
|
107
|
+
DIMENSIONS.includes(value.dimension as BudgetDimension) &&
|
|
108
|
+
BLOCK_REASONS.includes(value.reason as BudgetBlockReason) &&
|
|
109
|
+
isFiniteNumber(value.at)
|
|
110
|
+
);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** 严格校验:任何一条非法都按损坏处理(fail-closed,不静默重置) */
|
|
114
|
+
function isStoredConversation(value: unknown): value is StoredConversation {
|
|
115
|
+
if (!isRecord(value)) return false;
|
|
116
|
+
if (typeof value.conversation_id !== 'string' || value.conversation_id === '') return false;
|
|
117
|
+
if (value.team_id !== undefined && typeof value.team_id !== 'string') return false;
|
|
118
|
+
if (
|
|
119
|
+
!isFiniteNumber(value.created_at) ||
|
|
120
|
+
!isFiniteNumber(value.last_activity) ||
|
|
121
|
+
!isFiniteNumber(value.hops) ||
|
|
122
|
+
!isFiniteNumber(value.turns) ||
|
|
123
|
+
!isFiniteNumber(value.total_tokens)
|
|
124
|
+
) {
|
|
125
|
+
return false;
|
|
126
|
+
}
|
|
127
|
+
if (!Array.isArray(value.edges) || !value.edges.every(isEdge)) return false;
|
|
128
|
+
if (value.overrides === undefined) return false;
|
|
129
|
+
if (!isRecord(value.overrides)) return false;
|
|
130
|
+
for (const [key, override] of Object.entries(value.overrides)) {
|
|
131
|
+
if (!DIMENSIONS.includes(key as BudgetDimension) || !isOverride(override)) return false;
|
|
132
|
+
}
|
|
133
|
+
if (value.blocked !== undefined && !isBlocked(value.blocked)) return false;
|
|
134
|
+
return true;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function isStoreFile(value: unknown): value is ConversationStoreFile {
|
|
138
|
+
if (!isRecord(value)) return false;
|
|
139
|
+
if (value.v !== CONVERSATION_STORE_VERSION) return false;
|
|
140
|
+
if (!Array.isArray(value.conversations)) return false;
|
|
141
|
+
return value.conversations.every(isStoredConversation);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function hasProtection(conversation: StoredConversation): boolean {
|
|
145
|
+
return conversation.blocked !== undefined || Object.keys(conversation.overrides).length > 0;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function cloneConversation(conversation: StoredConversation): StoredConversation {
|
|
149
|
+
return {
|
|
150
|
+
conversation_id: conversation.conversation_id,
|
|
151
|
+
...(conversation.team_id !== undefined ? { team_id: conversation.team_id } : {}),
|
|
152
|
+
created_at: conversation.created_at,
|
|
153
|
+
last_activity: conversation.last_activity,
|
|
154
|
+
hops: conversation.hops,
|
|
155
|
+
turns: conversation.turns,
|
|
156
|
+
total_tokens: conversation.total_tokens,
|
|
157
|
+
edges: conversation.edges.map((edge) => ({ ...edge })),
|
|
158
|
+
overrides: Object.fromEntries(
|
|
159
|
+
Object.entries(conversation.overrides).map(([key, value]) => [key, { ...value }]),
|
|
160
|
+
) as StoredConversation['overrides'],
|
|
161
|
+
...(conversation.blocked !== undefined ? { blocked: { ...conversation.blocked } } : {}),
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export class ConversationStore {
|
|
166
|
+
readonly path: string;
|
|
167
|
+
/** 损坏或不可读时为 false;此后不写文件,判定返回 budget_unavailable */
|
|
168
|
+
readonly available: boolean;
|
|
169
|
+
|
|
170
|
+
private readonly logger: Logger;
|
|
171
|
+
private readonly debounceMs: number;
|
|
172
|
+
private readonly conversations = new Map<string, StoredConversation>();
|
|
173
|
+
private dirty = false;
|
|
174
|
+
private timer: ReturnType<typeof setTimeout> | undefined;
|
|
175
|
+
/** 永不 reject 的串行写链 */
|
|
176
|
+
private writeChain: Promise<void> = Promise.resolve();
|
|
177
|
+
|
|
178
|
+
constructor(options: ConversationStoreOptions) {
|
|
179
|
+
if (typeof options.dataDir !== 'string' || options.dataDir === '') {
|
|
180
|
+
throw new Error('ConversationStore requires a non-empty dataDir');
|
|
181
|
+
}
|
|
182
|
+
if (typeof options.tenantId !== 'string' || options.tenantId === '') {
|
|
183
|
+
throw new Error('ConversationStore requires a non-empty tenantId');
|
|
184
|
+
}
|
|
185
|
+
this.logger = options.logger ?? noopLogger;
|
|
186
|
+
this.debounceMs = options.debounceMs ?? CONVERSATION_WRITE_DEBOUNCE_MS;
|
|
187
|
+
this.path = conversationsPath(options.dataDir, options.tenantId);
|
|
188
|
+
this.available = this.loadSync();
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
get(conversationId: string): StoredConversation | undefined {
|
|
192
|
+
return this.conversations.get(conversationId);
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* 取或创建一条 conversation。`team_id` 只在缺失时写入(origin team 不可改写)。
|
|
197
|
+
*/
|
|
198
|
+
ensure(conversationId: string, teamId: string | undefined, now: number): StoredConversation {
|
|
199
|
+
let conversation = this.conversations.get(conversationId);
|
|
200
|
+
if (conversation === undefined) {
|
|
201
|
+
conversation = {
|
|
202
|
+
conversation_id: conversationId,
|
|
203
|
+
created_at: now,
|
|
204
|
+
last_activity: now,
|
|
205
|
+
hops: 0,
|
|
206
|
+
turns: 0,
|
|
207
|
+
total_tokens: 0,
|
|
208
|
+
edges: [],
|
|
209
|
+
overrides: {},
|
|
210
|
+
...(teamId !== undefined ? { team_id: teamId } : {}),
|
|
211
|
+
};
|
|
212
|
+
this.conversations.set(conversationId, conversation);
|
|
213
|
+
} else if (teamId !== undefined && conversation.team_id === undefined) {
|
|
214
|
+
conversation.team_id = teamId;
|
|
215
|
+
}
|
|
216
|
+
return conversation;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
all(): StoredConversation[] {
|
|
220
|
+
return [...this.conversations.values()];
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** 合并写入:defer 到下一个窗口;同一窗口内多次调用只写一次 */
|
|
224
|
+
markDirty(): void {
|
|
225
|
+
if (!this.available) return;
|
|
226
|
+
this.dirty = true;
|
|
227
|
+
if (this.timer !== undefined) return;
|
|
228
|
+
const timer = setTimeout(() => {
|
|
229
|
+
this.timer = undefined;
|
|
230
|
+
if (!this.available || !this.dirty) return;
|
|
231
|
+
this.dirty = false;
|
|
232
|
+
void this.enqueueWrite();
|
|
233
|
+
}, this.debounceMs);
|
|
234
|
+
timer.unref?.();
|
|
235
|
+
this.timer = timer;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** 立即落盘(turn 完成 / block / override) */
|
|
239
|
+
force(): Promise<void> {
|
|
240
|
+
if (!this.available) return Promise.resolve();
|
|
241
|
+
this.clearTimer();
|
|
242
|
+
this.dirty = false;
|
|
243
|
+
return this.enqueueWrite();
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** 等待已入队写入(含尚未触发的 debounce) */
|
|
247
|
+
async flush(): Promise<void> {
|
|
248
|
+
if (!this.available) return;
|
|
249
|
+
if (this.timer !== undefined || this.dirty) {
|
|
250
|
+
this.clearTimer();
|
|
251
|
+
this.dirty = false;
|
|
252
|
+
void this.enqueueWrite();
|
|
253
|
+
}
|
|
254
|
+
await this.writeChain;
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
private clearTimer(): void {
|
|
258
|
+
if (this.timer === undefined) return;
|
|
259
|
+
clearTimeout(this.timer);
|
|
260
|
+
this.timer = undefined;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
private enqueueWrite(): Promise<void> {
|
|
264
|
+
if (!this.available) return Promise.resolve();
|
|
265
|
+
// 序列化在入队时同步完成,避免异步窗口里继续改 Map 导致半新半旧。
|
|
266
|
+
let data: string;
|
|
267
|
+
try {
|
|
268
|
+
this.prune();
|
|
269
|
+
data = JSON.stringify(this.snapshotFile());
|
|
270
|
+
} catch (error) {
|
|
271
|
+
this.logger.error('conversation_budget.serialize_failed', {
|
|
272
|
+
path: this.path,
|
|
273
|
+
error: errorText(error),
|
|
274
|
+
});
|
|
275
|
+
return Promise.resolve();
|
|
276
|
+
}
|
|
277
|
+
const run = async (): Promise<void> => {
|
|
278
|
+
try {
|
|
279
|
+
await atomicWrite(this.path, data, { mode: 0o600, ensureDir: true });
|
|
280
|
+
} catch (error) {
|
|
281
|
+
this.logger.error('conversation_budget.write_failed', {
|
|
282
|
+
path: this.path,
|
|
283
|
+
error: errorText(error),
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
};
|
|
287
|
+
const task = this.writeChain.then(run, run);
|
|
288
|
+
this.writeChain = task;
|
|
289
|
+
return task;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
private snapshotFile(): ConversationStoreFile {
|
|
293
|
+
return {
|
|
294
|
+
v: CONVERSATION_STORE_VERSION,
|
|
295
|
+
conversations: [...this.conversations.values()].map(cloneConversation),
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** LRU 淘汰:先淘汰无 override / blocked 的最旧条目,受保护条目最多额外保留 50 条 */
|
|
300
|
+
private prune(): void {
|
|
301
|
+
if (this.conversations.size <= MAX_CONVERSATIONS) return;
|
|
302
|
+
const oldest = [...this.conversations.values()].sort(
|
|
303
|
+
(left, right) => left.last_activity - right.last_activity,
|
|
304
|
+
);
|
|
305
|
+
let total = oldest.length;
|
|
306
|
+
for (const conversation of oldest) {
|
|
307
|
+
if (total <= MAX_CONVERSATIONS) break;
|
|
308
|
+
if (hasProtection(conversation)) continue;
|
|
309
|
+
if (this.conversations.delete(conversation.conversation_id)) total -= 1;
|
|
310
|
+
}
|
|
311
|
+
for (const conversation of oldest) {
|
|
312
|
+
if (total <= MAX_CONVERSATIONS + MAX_PROTECTED_CONVERSATIONS) break;
|
|
313
|
+
if (this.conversations.delete(conversation.conversation_id)) total -= 1;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** 同步加载;返回 available */
|
|
318
|
+
private loadSync(): boolean {
|
|
319
|
+
let raw: string;
|
|
320
|
+
try {
|
|
321
|
+
raw = readFileSync(this.path, 'utf8');
|
|
322
|
+
} catch (error) {
|
|
323
|
+
if ((error as NodeJS.ErrnoException).code === 'ENOENT') return true;
|
|
324
|
+
this.logger.error('conversation_budget.load_failed', {
|
|
325
|
+
path: this.path,
|
|
326
|
+
error: errorText(error),
|
|
327
|
+
});
|
|
328
|
+
return false;
|
|
329
|
+
}
|
|
330
|
+
let parsed: unknown;
|
|
331
|
+
try {
|
|
332
|
+
parsed = JSON.parse(raw);
|
|
333
|
+
} catch (error) {
|
|
334
|
+
this.logger.error('conversation_budget.corrupt', {
|
|
335
|
+
path: this.path,
|
|
336
|
+
error: errorText(error),
|
|
337
|
+
});
|
|
338
|
+
return false;
|
|
339
|
+
}
|
|
340
|
+
if (!isStoreFile(parsed)) {
|
|
341
|
+
this.logger.error('conversation_budget.corrupt', { path: this.path });
|
|
342
|
+
return false;
|
|
343
|
+
}
|
|
344
|
+
for (const conversation of parsed.conversations) {
|
|
345
|
+
// 文件内重复 id:后者覆盖,保持加载而不是因重复拒绝整个文件。
|
|
346
|
+
this.conversations.set(conversation.conversation_id, cloneConversation(conversation));
|
|
347
|
+
}
|
|
348
|
+
this.prune();
|
|
349
|
+
return true;
|
|
350
|
+
}
|
|
351
|
+
}
|
package/src/distress.ts
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 遇难求救消息(q-distress-message):run 致命错误时,node 以遇难 agent 自身身份
|
|
3
|
+
* 向 parent/创建者(fallback 最近发送者)发一条**普通 inbox 消息**,让故障可见可救援。
|
|
4
|
+
*
|
|
5
|
+
* 灵感来自 lead 超窗卡死双向哑火事件:`run.failed` 只写一行 Team 日志,父级与
|
|
6
|
+
* 协作方都看不到「这具 body 已经跑不动了」;0.55 硬错误闸让它停止自动接单,但
|
|
7
|
+
* 停止本身是静默的。求救消息是闸的**通信兜底**:把「谁遇难 / 在哪 / 为什么 /
|
|
8
|
+
* 怎么救」写成一条可回复的消息。
|
|
9
|
+
*
|
|
10
|
+
* 本模块只做**纯函数**:触发码表、错误分类、建议处置、正文渲染。收件人解析 /
|
|
11
|
+
* 限流 / 防循环 / 投递在 `AgentService`(需要 registry / inbox / admit)。
|
|
12
|
+
*
|
|
13
|
+
* @module @vessel-agent/agent
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { toErrorEnvelope } from '@vessel-agent/core';
|
|
17
|
+
|
|
18
|
+
/** 每 agent 求救冷却:窗口内至多一条(去重 / 防风暴)。 */
|
|
19
|
+
export const DISTRESS_COOLDOWN_MS = 5 * 60_000;
|
|
20
|
+
|
|
21
|
+
/** 解析「最近发送者」时扫描 inbox 历史的条数上限(newest-first)。 */
|
|
22
|
+
export const DISTRESS_HISTORY_SCAN = 50;
|
|
23
|
+
|
|
24
|
+
/** 正文里错误消息的长度上限(与硬错误闸 `singleLineReason` 同口径)。 */
|
|
25
|
+
const MAX_DISTRESS_ERROR_CHARS = 500;
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* 触发码表:只覆盖**致命 / 终态** run 错误 —— 同一份请求重发必然再失败、或
|
|
29
|
+
* body 已无法继续,需要外部(parent / 人)介入的那一类。
|
|
30
|
+
*
|
|
31
|
+
* 刻意**不含**:
|
|
32
|
+
* - 瞬态可重试错误(`provider_rate_limit` / `provider_timeout` / `provider_network` /
|
|
33
|
+
* `provider_unavailable` / `checkpoint_failed` / `atomic_write_failed` /
|
|
34
|
+
* `run_already_running`)—— core 自己会重试或调用方可安全重发;
|
|
35
|
+
* - 权限流错误(`permission_denied` / `permission_cancelled` / `permission_timeout`)
|
|
36
|
+
* —— 用户动作的结果,已有各自的可见通知,不是「遇难」;
|
|
37
|
+
* - 工具 / PII 动作错误(`tool_*` / `pii_*`)—— 失败结果回喂模型,run 通常继续;
|
|
38
|
+
* - 预算阻塞(`limit_blocked`)—— 已有 `team.budget.blocked` 事件与 override 路径;
|
|
39
|
+
* - 输入类错误(`run_not_found` / `agent_not_found` / `conflict` 等)—— 调用方
|
|
40
|
+
* 直接收到错误,不存在「静默卡死」。
|
|
41
|
+
*
|
|
42
|
+
* `internal_error` 是引擎崩溃的兜底档(未分类内部错误一律落它,retryable=false)。
|
|
43
|
+
*/
|
|
44
|
+
export const DISTRESS_TRIGGER_CODES: ReadonlySet<string> = new Set([
|
|
45
|
+
// 本地发送前闸拦下的超窗(请求根本没出去)—— lead 事故的直接形态。
|
|
46
|
+
'context_window_exceeded',
|
|
47
|
+
// provider 说超了(400 + 超限文本)。
|
|
48
|
+
'provider_context_overflow',
|
|
49
|
+
// 401 / 403:密钥 / 权限配置错,重发必然再失败。
|
|
50
|
+
'provider_auth',
|
|
51
|
+
// 402:余额 / 配额耗尽。
|
|
52
|
+
'provider_quota_exceeded',
|
|
53
|
+
// 其它 4xx(如 404 模型不存在):请求本身被拒。
|
|
54
|
+
'provider_http_error',
|
|
55
|
+
// 无状态码的 provider 错误且不可重试。
|
|
56
|
+
'provider_error',
|
|
57
|
+
// 会话数据损坏:历史读不回来,body 起不来。
|
|
58
|
+
'session_corrupt',
|
|
59
|
+
// 引擎 / 内部崩溃兜底档。
|
|
60
|
+
'internal_error',
|
|
61
|
+
// 空响应兜底耗尽(seamless + nudge 仍空):需要 parent 催续 / 人介入。
|
|
62
|
+
'empty_response_exhausted',
|
|
63
|
+
]);
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* 服务层触发码:body spawn 失败。错误对象本身可能没有稳定 code(模型解析 /
|
|
67
|
+
* 插件安装 / 文件系统各种来源),但「body 起不来」对投递而言就是终态 ——
|
|
68
|
+
* 消息留在 inbox 反复重投反复失败,正是要求救的静默故障。
|
|
69
|
+
*/
|
|
70
|
+
export const DISTRESS_SPAWN_FAILED = 'spawn_failed';
|
|
71
|
+
|
|
72
|
+
export interface DistressClassification {
|
|
73
|
+
code: string;
|
|
74
|
+
/** 原始错误文本(渲染时折单行 + 截断)。 */
|
|
75
|
+
message: string;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* 致命错误分类:envelope 的 `error_code` 命中触发码表才返回。
|
|
80
|
+
* 不传 phase 提示 —— 让 envelope 自己按错误对象 / 文本判(与 `hardProviderFailure`
|
|
81
|
+
* 同一口径:强行传 phase 会把别的 category 误判进来)。
|
|
82
|
+
*/
|
|
83
|
+
export function classifyDistress(error: unknown): DistressClassification | undefined {
|
|
84
|
+
const envelope = toErrorEnvelope(error);
|
|
85
|
+
if (!DISTRESS_TRIGGER_CODES.has(envelope.error_code)) return undefined;
|
|
86
|
+
return {
|
|
87
|
+
code: envelope.error_code,
|
|
88
|
+
message: error instanceof Error ? error.message : String(error),
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** 按错误码给可操作的处置建议(收件人一看就知道下一步做什么)。 */
|
|
93
|
+
const DISTRESS_ADVICE: Readonly<Record<string, string>> = {
|
|
94
|
+
context_window_exceeded:
|
|
95
|
+
'上下文超窗(本地闸拦下,请求未发出):让它 rotate(写交接嘱托)或开新会话;不要直接重发原消息。',
|
|
96
|
+
provider_context_overflow:
|
|
97
|
+
'上下文超窗(provider 拒绝):让它 rotate(写交接嘱托)或开新会话;不要直接重发原消息。',
|
|
98
|
+
provider_auth: 'provider 认证失败(401/403):检查 API key / 模型配置,修复后再让它重试。',
|
|
99
|
+
provider_quota_exceeded: 'provider 配额耗尽(402):检查余额 / 配额,充值后再让它重试。',
|
|
100
|
+
provider_http_error: 'provider 拒绝请求(4xx):检查模型名与请求参数,修复后再让它重试。',
|
|
101
|
+
provider_error: 'provider 错误且不可重试:检查模型服务状态与配置。',
|
|
102
|
+
session_corrupt: '会话数据损坏:可能需要开新会话,或从事件日志重建历史。',
|
|
103
|
+
internal_error: '引擎 / 内部错误:检查节点日志,尝试让它 rotate 或重建 body。',
|
|
104
|
+
empty_response_exhausted: '模型连续空响应:尝试催续、换模型或人介入。',
|
|
105
|
+
spawn_failed: 'body 启动失败:检查模型配置 / 节点日志,修复后重投消息。',
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
export function distressAdvice(code: string): string {
|
|
109
|
+
return DISTRESS_ADVICE[code] ?? '致命 run 错误:检查节点日志并介入处置。';
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** 失败原因折单行并截断(与硬错误闸同口径:一条消息不该被多行正文撑开)。 */
|
|
113
|
+
function singleLineError(value: string): string {
|
|
114
|
+
const flat = value.replace(/\s+/g, ' ').trim();
|
|
115
|
+
return flat.length > MAX_DISTRESS_ERROR_CHARS
|
|
116
|
+
? `${flat.slice(0, MAX_DISTRESS_ERROR_CHARS)}...`
|
|
117
|
+
: flat;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export interface DistressContentInput {
|
|
121
|
+
memberId: string;
|
|
122
|
+
memberName?: string;
|
|
123
|
+
/** 遇难 body 的 session(binding id):救援者据此定位现场。 */
|
|
124
|
+
sessionId: string;
|
|
125
|
+
teamId?: string;
|
|
126
|
+
code: string;
|
|
127
|
+
message: string;
|
|
128
|
+
/**
|
|
129
|
+
* 受众 = 人类(顶层 fallback 投 Team 日志):回信指引换成 Web Team 面板 / CLI,
|
|
130
|
+
* 而非 agent 工具。缺省 = agent 收件人。
|
|
131
|
+
*/
|
|
132
|
+
human?: boolean;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* 渲染求救正文:汇报地址(可回信)+ 报错(code + message)+ 建议处置 + 防循环说明。
|
|
137
|
+
* 普通消息正文(不是系统事件):agent 收件人可直接回复或 `agent send to=<memberId>`;
|
|
138
|
+
* 人类收件人(顶层 fallback)在 Web Team 面板回信。
|
|
139
|
+
*/
|
|
140
|
+
export function renderDistressContent(input: DistressContentInput): string {
|
|
141
|
+
const who =
|
|
142
|
+
input.memberName !== undefined && input.memberName !== ''
|
|
143
|
+
? `"${input.memberName}" (${input.memberId})`
|
|
144
|
+
: input.memberId;
|
|
145
|
+
const team = input.teamId !== undefined ? ` team=${input.teamId}` : '';
|
|
146
|
+
const reply =
|
|
147
|
+
input.human === true
|
|
148
|
+
? `回信/救援: 在本 Team 面板回复并 @ 该成员,或 vessel agent send to=${input.memberId}`
|
|
149
|
+
: `回信/救援: agent send to=${input.memberId}`;
|
|
150
|
+
const tail =
|
|
151
|
+
input.human === true
|
|
152
|
+
? '本条为顶层/无 parent agent 的遇难求救(人类兜底):该 agent 没有可报的成员收件人,故报给本节点人类。每 agent 每 5 分钟至多一条。'
|
|
153
|
+
: '本消息带 distress:true 标记:你处理这条求救时若也报错,node 不会再替你发求救(防级联);每 agent 每 5 分钟至多一条求救。';
|
|
154
|
+
return [
|
|
155
|
+
`[distress] agent ${who} 的 run 遇到致命错误,node 以它的身份代发求救。`,
|
|
156
|
+
`遇难地址: member_id=${input.memberId} session_id=${input.sessionId}${team}(${reply})`,
|
|
157
|
+
`错误: ${input.code} — ${singleLineError(input.message)}`,
|
|
158
|
+
`建议处置: ${distressAdvice(input.code)}`,
|
|
159
|
+
tail,
|
|
160
|
+
].join('\n');
|
|
161
|
+
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 「环境信息」的 scope 词表与线格式(**唯一真相**)。
|
|
3
|
+
*
|
|
4
|
+
* 用户裁定(0.52):模型上下文里不需要第二种卡片。身份 / 工具 / 模型 / 提示词 / 系统重启
|
|
5
|
+
* 这些「模型需要知道的改变」全部是**同一类东西**——环境信息:同一条通道
|
|
6
|
+
* (`role: 'user'` + `name: 'vessel:notice'` 的尾消息)、同一个渲染入口
|
|
7
|
+
* (Web 的 `env-notice.ts` → `EnvCard`),只用 **scope** 区分种类。
|
|
8
|
+
*
|
|
9
|
+
* 为什么词表要收在一个零依赖的叶模块里:
|
|
10
|
+
* - 生产者有三个(`self-card-delta` / core EU 的工具面快照卡 / 以后的 restart),各自拼字符串
|
|
11
|
+
* 就会各自拼出不同的首词 —— Web 的 scope 判定按**行首 token** 做,一个词对不上,那条卡
|
|
12
|
+
* 静默掉回兜底的「上下文」,正文看着正常、标签是错的(最难发现的那种坏)。
|
|
13
|
+
* - Web 侧(`apps/web/src/domains/chat/env-notice.ts`)必须认得这里的每一个词。两边分属
|
|
14
|
+
* packages 与应用层,不能互相 import;R-10 单源后 Web 两处词表(env-notice /
|
|
15
|
+
* settings-registry)均派生 config `DEFAULT_ENV_CADENCE`,自动跟随。加词时同步
|
|
16
|
+
* agent 词表(本数组)、config `DEFAULT_ENV_CADENCE`、i18n 标签(`chat.env.scope.*`)
|
|
17
|
+
* 与插件字面量副本(旧 C3/parity 脚本已按宪法删除,不重建)。生产者加了词而
|
|
18
|
+
* config 表没加,卡头会静默退化成「上下文」。
|
|
19
|
+
* - 还有一类生产者在**插件包**里(`plugins/context/doc-subscription`):插件依赖 core、
|
|
20
|
+
* 不依赖本包(依赖方向反了),因此它的首词只能是**字面量副本**
|
|
21
|
+
* (`plugins/context/doc-subscription/src/notice.ts`)。那份副本同样在人工对拍范围内。
|
|
22
|
+
*
|
|
23
|
+
* 词义(决定卡头标签,不决定可见性):
|
|
24
|
+
* - `restart`:系统 / body 重启(换了一具 body,之前的上下文不再是「现在」);
|
|
25
|
+
* - `tools`:工具面变更(增减工具、权限档切换导致的可用工具变化);
|
|
26
|
+
* - `lock`:工作区写锁争用 / 超时(basic-tools 产);
|
|
27
|
+
* - `conflict`:expected_content 并发修改冲突(文件被他人改动导致写入拒绝,basic-tools 产);
|
|
28
|
+
* - `model`:模型变更;
|
|
29
|
+
* - `identity`:身份变更(改名 / Team / parent);
|
|
30
|
+
* - `fields`:其它基础字段变更(**历史词,零活生产者**:`FIELD_SCOPE` 值域仅
|
|
31
|
+
* identity/model/context/tools,保留供历史落盘消息解析,peer retired 先例同口径);
|
|
32
|
+
* - `files`:文件变更(doc-subscription 的订阅文件被改动,只报元数据、不报正文);
|
|
33
|
+
* - `health`:node 健康变更(doc-subscription 的 health 源订阅:可达性翻转 / 版本 /
|
|
34
|
+
* 重启 started_at;q-health-subscription,只报元数据,快照在 inspect);
|
|
35
|
+
* - `agent`:成员活动(★D5 统一词,subscription-unify errata 用户裁定)——两类实例
|
|
36
|
+
* 同卡:显式活动订阅(doc-subscription agent 源,活动快照签名变化)+ 隐式实例
|
|
37
|
+
* (peer 停下通知,target=子成员、定向父 session;原 `peer` 词废,历史消息 Web
|
|
38
|
+
* legacy 解析保留);
|
|
39
|
+
* - `script`:订阅脚本检测结果(doc-subscription 的 script 源订阅:用户配置 allowlist
|
|
40
|
+
* 的检测命令异步跑,stdout 差异/清单投递;q-subscription-script,空输出不出卡,
|
|
41
|
+
* 全文在 inspect);
|
|
42
|
+
* - `doc-lag`:文档滞后检测(内置订阅脚本 doc-sync --quiet 的专词;q-subscription-script-p1,
|
|
43
|
+
* 案 B 注册制:内置检测器精确卡头 + per-scope 节奏/通道,用户任意脚本仍共享 script);
|
|
44
|
+
* - `code-heaviness`:代码厚重检测(内置订阅脚本 code-size 的专词;同上案 B 注册制);
|
|
45
|
+
* - `context`:系统提示词 / Self Card 本身变了(可展开看完整快照);上下文窗口事实也归它:
|
|
46
|
+
* 超限 / 发送前闸「没发」卡,以及 50% 压力提醒卡(q-env-rotate-hint,建议 `agent(rotate)`,
|
|
47
|
+
* 经 EU `appendNotice` 遵守 env_injection 的 off / ui-only 档位);
|
|
48
|
+
* - `trim`:工具结果被换成占位符(上下文上限;只报条数与 call id,不含工具输出正文)
|
|
49
|
+
* —— 0.52 起由 core 的 `context/cleared-tool-result.ts` 发同一形状的 `trim: …` 尾消息;
|
|
50
|
+
* - `pii`:PII 句柄整批失效(内存 broker 重启)—— 0.52 起由 core 的 `pii/notice.ts`
|
|
51
|
+
* 发同一形状的 `pii: …` 尾消息(首词即 scope;逐调用的句柄失败**不**发卡,只落到那次工具调用)。
|
|
52
|
+
*
|
|
53
|
+
* @module @vessel-agent/agent
|
|
54
|
+
*/
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* scope 词表。
|
|
58
|
+
*
|
|
59
|
+
* 顺序有两个用处,都必须稳定:
|
|
60
|
+
* - 同轮多条环境信息的**落盘顺序**(一批变更跨种类时按它依次注入);
|
|
61
|
+
* - 一条消息里明细行的分组顺序(`formatSelfCardDeltas`)。
|
|
62
|
+
*
|
|
63
|
+
* 排列按「模型最该先知道」而非字母序:重启 → 身份 → 其它字段 → 模型 → 工具 →
|
|
64
|
+
* 写协调(lock/conflict)→ 文件 → 上下文。lock/conflict 在 tools 后、files 前:
|
|
65
|
+
* 写协调事实(锁争用 / 并发冲突)先于文件变更本身。
|
|
66
|
+
*/
|
|
67
|
+
export const ENV_INFO_SCOPES = [
|
|
68
|
+
'restart',
|
|
69
|
+
'identity',
|
|
70
|
+
'fields',
|
|
71
|
+
'model',
|
|
72
|
+
'tools',
|
|
73
|
+
'lock',
|
|
74
|
+
'conflict',
|
|
75
|
+
'files',
|
|
76
|
+
'health',
|
|
77
|
+
'agent',
|
|
78
|
+
'script',
|
|
79
|
+
'doc-lag',
|
|
80
|
+
'code-heaviness',
|
|
81
|
+
'team-log',
|
|
82
|
+
'context',
|
|
83
|
+
'trim',
|
|
84
|
+
'pii',
|
|
85
|
+
] as const;
|
|
86
|
+
|
|
87
|
+
export type EnvInfoScope = (typeof ENV_INFO_SCOPES)[number];
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* 注入消息的 `name`:与 `runtime-notice-hook` / `refs-notice-hook` / inbox 提示同一条通道。
|
|
91
|
+
*
|
|
92
|
+
* Web 按 `name === 'vessel:notice'` 认出「这是环境信息」(`runtimeMessageKind` → `notice`),
|
|
93
|
+
* 再按正文首行的 scope 词决定卡头标签。**不新造事件类型**:这条通道已经有人看、有人测、
|
|
94
|
+
* 有人渲染。
|
|
95
|
+
*/
|
|
96
|
+
export const ENV_INFO_MESSAGE_NAME = 'vessel:notice';
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* details 行的线格式前缀:两个空格 + `·`。
|
|
100
|
+
*
|
|
101
|
+
* **必须**与 `src/runtime/runtime-notice-hook.ts` 的 `NOTICE_DETAIL_MARK` 逐字相同 —— Web 的
|
|
102
|
+
* `env-notice.ts` 按这个标记认「这一行是明细」;对不上时整条消息会被读成一整行(明细全挤进
|
|
103
|
+
* 卡头的单行 ellipsis,展开区空着)。两边分属 packages 与应用层,不能互相 import,
|
|
104
|
+
* 改动任一侧时人工核对另一侧逐字相同,防止哪天单边改动。
|
|
105
|
+
*/
|
|
106
|
+
export const ENV_INFO_DETAIL_MARK = ' · ';
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* 一条环境信息最多带多少行明细。
|
|
110
|
+
*
|
|
111
|
+
* 10 + 1 行摘要 = 11 = Web 卡片的渲染上限(`ENV_NOTICE_DETAILS_MAX`):多出来的行会被卡片
|
|
112
|
+
* 折成「还有 N 行未显示」。与其让用户点开只看到被截断的清单,不如生产者先把长清单收口成
|
|
113
|
+
* 「… 还有 N 项」—— 决定权(报什么、舍什么)应该在知道语义的这一侧。
|
|
114
|
+
*/
|
|
115
|
+
export const ENV_INFO_DETAILS_MAX = 10;
|
|
116
|
+
|
|
117
|
+
export interface EnvInfoOptions {
|
|
118
|
+
readonly scope: EnvInfoScope;
|
|
119
|
+
/** 摘要(**不含** scope 词,由本函数统一加前缀)。 */
|
|
120
|
+
readonly summary: string;
|
|
121
|
+
/** 明细行(每条会被加上线格式标记;超长由本函数收口)。 */
|
|
122
|
+
readonly details: readonly string[];
|
|
123
|
+
/** 被收口的明细条数文案(可选:默认英文,见 `formatEnvInfo`)。 */
|
|
124
|
+
readonly moreLabel?: (dropped: number) => string;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* 一批明细 → 一条环境信息正文(首行 `scope: summary`,之后每行 ` · detail`)。
|
|
129
|
+
*
|
|
130
|
+
* 形状是**契约**(Web 的解析器就认这个形状):首行必须是 `scope: ` 开头,明细行必须以
|
|
131
|
+
* `ENV_INFO_DETAIL_MARK` 开头。空明细也允许(只有摘要的环境信息)。
|
|
132
|
+
*/
|
|
133
|
+
export function formatEnvInfo(options: EnvInfoOptions): string {
|
|
134
|
+
const head = `${options.scope}: ${options.summary}`;
|
|
135
|
+
const kept = options.details.slice(0, ENV_INFO_DETAILS_MAX);
|
|
136
|
+
const dropped = options.details.length - kept.length;
|
|
137
|
+
const lines = kept.map((detail) => `${ENV_INFO_DETAIL_MARK}${detail}`);
|
|
138
|
+
if (dropped > 0) {
|
|
139
|
+
const label = options.moreLabel?.(dropped) ?? `and ${String(dropped)} more`;
|
|
140
|
+
lines.push(`${ENV_INFO_DETAIL_MARK}${label}`);
|
|
141
|
+
}
|
|
142
|
+
return [head, ...lines].join('\n');
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* 名字集合的稳定形式(新增 / 删除工具的 diff 用)。
|
|
147
|
+
*
|
|
148
|
+
* 排序是去重与测试的前提,不是美观:同一批变更在任何一轮里都必须拼出同一个字符串,
|
|
149
|
+
* 否则「只报一次」就变成看运气。
|
|
150
|
+
*/
|
|
151
|
+
export function sortedNames(names: readonly string[]): string[] {
|
|
152
|
+
return [...new Set(names)].sort((left, right) => (left < right ? -1 : left > right ? 1 : 0));
|
|
153
|
+
}
|