@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
package/src/snapshot.ts
ADDED
|
@@ -0,0 +1,614 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 成员快照:`<dataDir>/agents/<tenant>.json`(0600 原子写)。
|
|
3
|
+
*
|
|
4
|
+
* 快照只含成员状态,不含消息队列(重启后未处理消息丢失)。
|
|
5
|
+
* 文件损坏时先隔离为 `<path>.corrupt-<timestamp>` 再按空列表加载:
|
|
6
|
+
* 不阻塞启动,也不让下一次状态写覆盖唯一恢复副本。
|
|
7
|
+
*
|
|
8
|
+
* @module @vessel-agent/agent
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { access, copyFile, mkdir, readFile, rename } from 'node:fs/promises';
|
|
12
|
+
import { dirname, join } from 'node:path';
|
|
13
|
+
import { atomicWrite, type Logger, noopLogger } from '@vessel-agent/core';
|
|
14
|
+
import {
|
|
15
|
+
type AgentRole,
|
|
16
|
+
type BindingHistoryEntry,
|
|
17
|
+
type BindingPointer,
|
|
18
|
+
MAX_BINDING_HISTORY,
|
|
19
|
+
type MemberMembership,
|
|
20
|
+
type MemberState,
|
|
21
|
+
type MemberVisibility,
|
|
22
|
+
type PersistedAgentRecord,
|
|
23
|
+
type PersistedBindingRecord,
|
|
24
|
+
} from './types.js';
|
|
25
|
+
|
|
26
|
+
/** 快照文件版本;当前写入 5,读取兼容 1 / 2 / 3 / 4 */
|
|
27
|
+
export const AGENT_SNAPSHOT_VERSION = 5;
|
|
28
|
+
|
|
29
|
+
/** 快照文件形状(v5;v1 / v2 的 members 读时按 owner 推断 role) */
|
|
30
|
+
export interface AgentSnapshotFile {
|
|
31
|
+
version: number;
|
|
32
|
+
updated_at: number;
|
|
33
|
+
members: PersistedAgentRecord[];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** 旧版本备份后缀(首次写新版前创建,供旧二进制回滚) */
|
|
37
|
+
const V1_BACKUP_SUFFIX = '.v1.bak';
|
|
38
|
+
const V2_BACKUP_SUFFIX = '.v2.bak';
|
|
39
|
+
const V3_BACKUP_SUFFIX = '.v3.bak';
|
|
40
|
+
const V4_BACKUP_SUFFIX = '.v4.bak';
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* 快照里合法的 role 字面量。
|
|
44
|
+
*
|
|
45
|
+
* `single` 只用于**读取**存量数据:0.27 及更早写出的 `main` 是 `role:'single'`,
|
|
46
|
+
* 0.28 起该角色不存在,读到即降级为 `member`(见 `parseMember`)。新写入永远是
|
|
47
|
+
* `member` / `temporary` 之一,所以这里不把它加进 `AgentRole`。
|
|
48
|
+
*/
|
|
49
|
+
const READABLE_ROLES: readonly (AgentRole | 'single')[] = ['single', 'member', 'temporary'];
|
|
50
|
+
|
|
51
|
+
/** 存量 `single` → `member`:所有 agent 都归某个 Team,不再有独立 agent。 */
|
|
52
|
+
const LEGACY_SINGLE_ROLE = 'single';
|
|
53
|
+
|
|
54
|
+
const MEMBER_STATES: readonly MemberState[] = [
|
|
55
|
+
'created',
|
|
56
|
+
'idle',
|
|
57
|
+
'running',
|
|
58
|
+
'waiting_permission',
|
|
59
|
+
'completed',
|
|
60
|
+
'failed',
|
|
61
|
+
'cancelled',
|
|
62
|
+
'closed',
|
|
63
|
+
'stale',
|
|
64
|
+
];
|
|
65
|
+
|
|
66
|
+
const VISIBILITIES: readonly MemberVisibility[] = ['private', 'team', 'tenant'];
|
|
67
|
+
|
|
68
|
+
/** 快照路径 */
|
|
69
|
+
export function snapshotPath(dataDir: string, tenantId: string): string {
|
|
70
|
+
return join(dataDir, 'agents', `${tenantId}.json`);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
74
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function nonEmptyString(value: unknown): value is string {
|
|
78
|
+
return typeof value === 'string' && value !== '';
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function optionalString(value: unknown): string | undefined {
|
|
82
|
+
return nonEmptyString(value) ? value : undefined;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function fileExists(path: string): Promise<boolean> {
|
|
86
|
+
try {
|
|
87
|
+
await access(path);
|
|
88
|
+
return true;
|
|
89
|
+
} catch {
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** current_body:session_id 非空、epoch 为 >=0 整数、started_at 为有限数字才保留 */
|
|
95
|
+
function parseBindingPointer(value: unknown): BindingPointer | undefined {
|
|
96
|
+
if (!isRecord(value)) return undefined;
|
|
97
|
+
if (!nonEmptyString(value.session_id)) return undefined;
|
|
98
|
+
if (typeof value.epoch !== 'number' || !Number.isInteger(value.epoch) || value.epoch < 0) {
|
|
99
|
+
return undefined;
|
|
100
|
+
}
|
|
101
|
+
if (typeof value.started_at !== 'number' || !Number.isFinite(value.started_at)) return undefined;
|
|
102
|
+
return { session_id: value.session_id, epoch: value.epoch, started_at: value.started_at };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* body_history:逐条校验(Binding 指针 + 有限 retired_at),非法条目单独跳过;
|
|
107
|
+
* 最多保留最后 MAX_BINDING_HISTORY 条。无有效条目返回 undefined。
|
|
108
|
+
*/
|
|
109
|
+
function parseBindingHistory(value: unknown): BindingHistoryEntry[] | undefined {
|
|
110
|
+
if (!Array.isArray(value)) return undefined;
|
|
111
|
+
const entries: BindingHistoryEntry[] = [];
|
|
112
|
+
for (const item of value) {
|
|
113
|
+
if (!isRecord(item)) continue;
|
|
114
|
+
const body = parseBindingPointer(item);
|
|
115
|
+
if (body === undefined) continue;
|
|
116
|
+
if (typeof item.retired_at !== 'number' || !Number.isFinite(item.retired_at)) continue;
|
|
117
|
+
entries.push({ ...body, retired_at: item.retired_at });
|
|
118
|
+
}
|
|
119
|
+
if (entries.length === 0) return undefined;
|
|
120
|
+
return entries.slice(-MAX_BINDING_HISTORY);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function parsePersistedBinding(value: unknown): PersistedBindingRecord | undefined {
|
|
124
|
+
if (!isRecord(value)) return undefined;
|
|
125
|
+
const bindingId = optionalString(value.body_id) ?? optionalString(value.session_id);
|
|
126
|
+
if (bindingId === undefined) return undefined;
|
|
127
|
+
const epoch =
|
|
128
|
+
typeof value.epoch === 'number' && Number.isInteger(value.epoch) && value.epoch >= 0
|
|
129
|
+
? value.epoch
|
|
130
|
+
: 0;
|
|
131
|
+
const createdAt =
|
|
132
|
+
typeof value.created_at === 'number' && Number.isFinite(value.created_at)
|
|
133
|
+
? value.created_at
|
|
134
|
+
: typeof value.last_active_at === 'number' && Number.isFinite(value.last_active_at)
|
|
135
|
+
? value.last_active_at
|
|
136
|
+
: 0;
|
|
137
|
+
const lastActiveAt =
|
|
138
|
+
typeof value.last_active_at === 'number' && Number.isFinite(value.last_active_at)
|
|
139
|
+
? value.last_active_at
|
|
140
|
+
: createdAt;
|
|
141
|
+
const record: PersistedBindingRecord = {
|
|
142
|
+
body_id: bindingId,
|
|
143
|
+
epoch,
|
|
144
|
+
created_at: createdAt,
|
|
145
|
+
last_active_at: lastActiveAt,
|
|
146
|
+
};
|
|
147
|
+
if (typeof value.retired_at === 'number' && Number.isFinite(value.retired_at)) {
|
|
148
|
+
record.retired_at = value.retired_at;
|
|
149
|
+
}
|
|
150
|
+
if (value.primary === true) record.primary = true;
|
|
151
|
+
return record;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function parsePersistedBodies(value: unknown): PersistedBindingRecord[] | undefined {
|
|
155
|
+
if (!Array.isArray(value)) return undefined;
|
|
156
|
+
const bodies: PersistedBindingRecord[] = [];
|
|
157
|
+
const seen = new Set<string>();
|
|
158
|
+
for (const item of value) {
|
|
159
|
+
const body = parsePersistedBinding(item);
|
|
160
|
+
if (body === undefined || seen.has(body.body_id)) continue;
|
|
161
|
+
seen.add(body.body_id);
|
|
162
|
+
bodies.push(body);
|
|
163
|
+
}
|
|
164
|
+
return bodies.length > 0 ? bodies : undefined;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* v1–v3 → v4:`current_body` 变成唯一 live binding + primary;旧 `body_history`
|
|
169
|
+
* 迁入 `bodies[]`(已退役)。v4 只读新字段。`bodies[]` 是唯一真相。
|
|
170
|
+
*/
|
|
171
|
+
function migrateBodies(
|
|
172
|
+
version: number,
|
|
173
|
+
currentBinding: BindingPointer | undefined,
|
|
174
|
+
bindingHistory: BindingHistoryEntry[] | undefined,
|
|
175
|
+
explicitBodies: PersistedBindingRecord[] | undefined,
|
|
176
|
+
explicitPrimary: string | undefined,
|
|
177
|
+
fallbackSessionId: string,
|
|
178
|
+
lastSeen: number | undefined,
|
|
179
|
+
): { bodies: PersistedBindingRecord[]; primary?: string } {
|
|
180
|
+
if (version >= 4 && explicitBodies !== undefined) {
|
|
181
|
+
return {
|
|
182
|
+
bodies: explicitBodies,
|
|
183
|
+
...(explicitPrimary !== undefined ? { primary: explicitPrimary } : {}),
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
const bodies: PersistedBindingRecord[] = [];
|
|
187
|
+
const seen = new Set<string>();
|
|
188
|
+
for (const entry of bindingHistory ?? []) {
|
|
189
|
+
if (seen.has(entry.session_id)) continue;
|
|
190
|
+
seen.add(entry.session_id);
|
|
191
|
+
bodies.push({
|
|
192
|
+
body_id: entry.session_id,
|
|
193
|
+
epoch: entry.epoch,
|
|
194
|
+
created_at: entry.started_at,
|
|
195
|
+
last_active_at: entry.retired_at,
|
|
196
|
+
retired_at: entry.retired_at,
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
const live = currentBinding ?? {
|
|
200
|
+
session_id: fallbackSessionId,
|
|
201
|
+
epoch: 0,
|
|
202
|
+
started_at: lastSeen ?? 0,
|
|
203
|
+
};
|
|
204
|
+
if (!seen.has(live.session_id)) {
|
|
205
|
+
bodies.push({
|
|
206
|
+
body_id: live.session_id,
|
|
207
|
+
epoch: live.epoch,
|
|
208
|
+
created_at: live.started_at,
|
|
209
|
+
last_active_at: lastSeen ?? live.started_at,
|
|
210
|
+
primary: true,
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
return { bodies, primary: live.session_id };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* 单条成员校验;字段非法返回 undefined(整条丢弃)。
|
|
218
|
+
* v1 / v2 按 owner 推断 role;v3 使用显式 role。membership 缺省按
|
|
219
|
+
* state === 'closed' 推断;presence / rotation 不读。
|
|
220
|
+
*/
|
|
221
|
+
function parseMember(value: unknown, version: number): PersistedAgentRecord | undefined {
|
|
222
|
+
if (!isRecord(value)) return undefined;
|
|
223
|
+
if (!nonEmptyString(value.id) || !nonEmptyString(value.session_id)) return undefined;
|
|
224
|
+
// 显式 owner 必须是非空字符串;v1 / v2 可缺省(推断为 member)。
|
|
225
|
+
const rawOwner = optionalString(value.owner);
|
|
226
|
+
if (value.owner !== undefined && rawOwner === undefined) return undefined;
|
|
227
|
+
if (!nonEmptyString(value.visibility)) return undefined;
|
|
228
|
+
if (!nonEmptyString(value.state)) return undefined;
|
|
229
|
+
if (!VISIBILITIES.includes(value.visibility as MemberVisibility)) return undefined;
|
|
230
|
+
if (!MEMBER_STATES.includes(value.state as MemberState)) return undefined;
|
|
231
|
+
|
|
232
|
+
// v3 才信任显式 role;旧快照一律按 owner 推断。
|
|
233
|
+
const explicitRole =
|
|
234
|
+
version >= 3 && READABLE_ROLES.includes(value.role as AgentRole | 'single')
|
|
235
|
+
? (value.role as AgentRole | 'single')
|
|
236
|
+
: undefined;
|
|
237
|
+
// 推断阶梯:无 owner → member;owner === id → 存量 single(降级为 member);
|
|
238
|
+
// 其余 → temporary。**绝不在 parse 阶段 reject**:丢一条记录等于把它全部会话变不可见。
|
|
239
|
+
const inferredRole: AgentRole | 'single' =
|
|
240
|
+
rawOwner === undefined ? 'member' : rawOwner === value.id ? LEGACY_SINGLE_ROLE : 'temporary';
|
|
241
|
+
const declaredRole = explicitRole ?? inferredRole;
|
|
242
|
+
// 0.28 迁移:`single` 降级为 `member`,可见性保持原值(private 仍按 owner 判定,
|
|
243
|
+
// owner 恒为 self 所以升级后成员对自己可见、可寻址)。降级只发生一次,写回即 member。
|
|
244
|
+
const role: AgentRole =
|
|
245
|
+
declaredRole === LEGACY_SINGLE_ROLE ? 'member' : (declaredRole as AgentRole);
|
|
246
|
+
// member 的 owner 恒为 self;temporary 保留雇佣者(v3 必填,缺失视为损坏)。
|
|
247
|
+
if (role === 'temporary' && rawOwner === undefined) return undefined;
|
|
248
|
+
const owner = role === 'temporary' ? (rawOwner as string) : value.id;
|
|
249
|
+
|
|
250
|
+
const state = value.state as MemberState;
|
|
251
|
+
const membership: MemberMembership =
|
|
252
|
+
value.membership === 'present' || value.membership === 'left'
|
|
253
|
+
? value.membership
|
|
254
|
+
: state === 'closed'
|
|
255
|
+
? 'left'
|
|
256
|
+
: 'present';
|
|
257
|
+
|
|
258
|
+
const record: PersistedAgentRecord = {
|
|
259
|
+
id: value.id,
|
|
260
|
+
session_id: value.session_id,
|
|
261
|
+
role,
|
|
262
|
+
owner,
|
|
263
|
+
visibility: value.visibility as MemberVisibility,
|
|
264
|
+
state,
|
|
265
|
+
membership,
|
|
266
|
+
};
|
|
267
|
+
const name = optionalString(value.name);
|
|
268
|
+
if (name !== undefined) record.name = name;
|
|
269
|
+
// 0.19 S3:additive 字段;仍写 version 2(旧二进制忽略未知键)
|
|
270
|
+
const teamId = optionalString(value.team_id);
|
|
271
|
+
if (teamId !== undefined) record.team_id = teamId;
|
|
272
|
+
const parentId = optionalString(value.parent_id);
|
|
273
|
+
if (parentId !== undefined) record.parent_id = parentId;
|
|
274
|
+
// model 仅在显式 pin 时存在(v5 语义)。v1–v4 把「有效 model」烧进记录,无法区分
|
|
275
|
+
// 显式 pin 与旧默认值 → 读侧一次性全清(D2 批准);写回即 v5,之后不再丢。
|
|
276
|
+
const model = version >= AGENT_SNAPSHOT_VERSION ? optionalString(value.model) : undefined;
|
|
277
|
+
if (model !== undefined) record.model = model;
|
|
278
|
+
// thinkingLevel(q-thinking-agent-level-b2 additive):新键,旧快照从未写过 ⇒ 无需
|
|
279
|
+
// 版本闸(不存在 model 那种 v1–v4 烧默认值问题);缺省 = 未设,跟随默认链。
|
|
280
|
+
const thinkingLevel = optionalString(value.thinkingLevel);
|
|
281
|
+
if (thinkingLevel !== undefined) record.thinkingLevel = thinkingLevel;
|
|
282
|
+
const systemPrompt = optionalString(value.system_prompt);
|
|
283
|
+
if (systemPrompt !== undefined) record.system_prompt = systemPrompt;
|
|
284
|
+
// 0.51:成员 cwd 快照(additive;旧快照没有这个键 = 没有成员 cwd)
|
|
285
|
+
const cwd = optionalString(value.cwd);
|
|
286
|
+
if (cwd !== undefined) record.cwd = cwd;
|
|
287
|
+
// 0.53:释放时刻 / 原因(additive;旧快照没有 = 释放时刻未知,历史视图不补默认值)
|
|
288
|
+
const closedAt =
|
|
289
|
+
typeof value.closed_at === 'number' && Number.isFinite(value.closed_at)
|
|
290
|
+
? value.closed_at
|
|
291
|
+
: undefined;
|
|
292
|
+
if (closedAt !== undefined) record.closed_at = closedAt;
|
|
293
|
+
const closeReason = optionalString(value.close_reason);
|
|
294
|
+
if (closeReason !== undefined) record.close_reason = closeReason;
|
|
295
|
+
const currentBinding = parseBindingPointer(value.current_body);
|
|
296
|
+
if (currentBinding !== undefined) record.current_body = currentBinding;
|
|
297
|
+
const bindingHistory = parseBindingHistory(value.body_history);
|
|
298
|
+
if (bindingHistory !== undefined) record.body_history = bindingHistory;
|
|
299
|
+
const lastSeen =
|
|
300
|
+
typeof value.last_seen === 'number' && Number.isFinite(value.last_seen)
|
|
301
|
+
? value.last_seen
|
|
302
|
+
: undefined;
|
|
303
|
+
const explicitBodies = parsePersistedBodies(value.bodies);
|
|
304
|
+
const explicitPrimary = optionalString(value.primary_body_id);
|
|
305
|
+
const migrated = migrateBodies(
|
|
306
|
+
version,
|
|
307
|
+
currentBinding,
|
|
308
|
+
bindingHistory,
|
|
309
|
+
explicitBodies,
|
|
310
|
+
explicitPrimary,
|
|
311
|
+
value.session_id,
|
|
312
|
+
lastSeen,
|
|
313
|
+
);
|
|
314
|
+
record.bodies = migrated.bodies;
|
|
315
|
+
if (migrated.primary !== undefined) record.primary_body_id = migrated.primary;
|
|
316
|
+
// CREATE-0.39:只识别新键;旧 `forked_from` 不读、不迁移、不报错。
|
|
317
|
+
const sourceAgentId = optionalString(value.source_agent_id);
|
|
318
|
+
if (sourceAgentId !== undefined) record.source_agent_id = sourceAgentId;
|
|
319
|
+
const currentTool = optionalString(value.current_tool);
|
|
320
|
+
if (currentTool !== undefined) record.current_tool = currentTool;
|
|
321
|
+
if (lastSeen !== undefined) record.last_seen = lastSeen;
|
|
322
|
+
if (isRecord(value.usage)) record.usage = value.usage;
|
|
323
|
+
return record;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** 快照读写;写失败只记录不抛出 */
|
|
327
|
+
export class AgentSnapshotStore {
|
|
328
|
+
private readonly logger: Logger;
|
|
329
|
+
private readonly throttleMs: number;
|
|
330
|
+
private readonly mode: number;
|
|
331
|
+
private readonly now: () => number;
|
|
332
|
+
private timer: ReturnType<typeof setTimeout> | undefined;
|
|
333
|
+
private pending: (() => PersistedAgentRecord[]) | undefined;
|
|
334
|
+
/** 写入串行链;值表示该次 write 是否成功 */
|
|
335
|
+
private chain: Promise<boolean> = Promise.resolve(true);
|
|
336
|
+
/** 读到旧版且尚未成功备份时置位;write 前必须补做,否则放弃写入(避免无回滚) */
|
|
337
|
+
private backupPendingFor: 1 | 2 | 3 | 4 | undefined;
|
|
338
|
+
/** 是否已探测过现有文件版本(未 load 直接 write 时也要补备份) */
|
|
339
|
+
private backupChecked = false;
|
|
340
|
+
/** 损坏文件隔离失败时置位:write 直接放弃,避免覆盖唯一恢复副本 */
|
|
341
|
+
private writeBlocked = false;
|
|
342
|
+
|
|
343
|
+
constructor(
|
|
344
|
+
private readonly filePath: string,
|
|
345
|
+
options: {
|
|
346
|
+
throttleMs?: number;
|
|
347
|
+
mode?: number;
|
|
348
|
+
logger?: Logger;
|
|
349
|
+
now?: () => number;
|
|
350
|
+
} = {},
|
|
351
|
+
) {
|
|
352
|
+
this.throttleMs = Math.max(0, options.throttleMs ?? 0);
|
|
353
|
+
this.mode = options.mode ?? 0o600;
|
|
354
|
+
this.logger = options.logger ?? noopLogger;
|
|
355
|
+
this.now = options.now ?? Date.now;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
get path(): string {
|
|
359
|
+
return this.filePath;
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** 读取;缺失返回空列表;损坏 / 版本不符先隔离再返回空列表;v1–v4 可读并在首次写 v5 前备份 */
|
|
363
|
+
async load(): Promise<PersistedAgentRecord[]> {
|
|
364
|
+
let raw: string;
|
|
365
|
+
try {
|
|
366
|
+
raw = await readFile(this.filePath, 'utf8');
|
|
367
|
+
} catch (error) {
|
|
368
|
+
if ((error as NodeJS.ErrnoException)?.code !== 'ENOENT') {
|
|
369
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
370
|
+
this.logger.error('agent.snapshot.load_failed', {
|
|
371
|
+
path: this.filePath,
|
|
372
|
+
error: detail,
|
|
373
|
+
});
|
|
374
|
+
await this.quarantine(detail);
|
|
375
|
+
}
|
|
376
|
+
return [];
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
let parsed: unknown;
|
|
380
|
+
try {
|
|
381
|
+
parsed = JSON.parse(raw);
|
|
382
|
+
} catch (error) {
|
|
383
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
384
|
+
this.logger.error('agent.snapshot.load_failed', {
|
|
385
|
+
path: this.filePath,
|
|
386
|
+
error: detail,
|
|
387
|
+
});
|
|
388
|
+
await this.quarantine(detail);
|
|
389
|
+
return [];
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
if (
|
|
393
|
+
!isRecord(parsed) ||
|
|
394
|
+
(parsed.version !== 1 &&
|
|
395
|
+
parsed.version !== 2 &&
|
|
396
|
+
parsed.version !== 3 &&
|
|
397
|
+
parsed.version !== 4 &&
|
|
398
|
+
parsed.version !== AGENT_SNAPSHOT_VERSION)
|
|
399
|
+
) {
|
|
400
|
+
const detail = `unsupported snapshot version: ${String(isRecord(parsed) ? parsed.version : 'n/a')}`;
|
|
401
|
+
this.logger.error('agent.snapshot.load_failed', {
|
|
402
|
+
path: this.filePath,
|
|
403
|
+
error: detail,
|
|
404
|
+
});
|
|
405
|
+
await this.quarantine(detail);
|
|
406
|
+
return [];
|
|
407
|
+
}
|
|
408
|
+
this.backupChecked = true;
|
|
409
|
+
|
|
410
|
+
if (!Array.isArray(parsed.members)) {
|
|
411
|
+
this.logger.error('agent.snapshot.load_failed', {
|
|
412
|
+
path: this.filePath,
|
|
413
|
+
error: 'members is not an array',
|
|
414
|
+
});
|
|
415
|
+
await this.quarantine('members is not an array');
|
|
416
|
+
return [];
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
// 旧二进制无法读 v5;首次写 v5 前先留一份对应版本的备份。
|
|
420
|
+
if (
|
|
421
|
+
parsed.version === 1 ||
|
|
422
|
+
parsed.version === 2 ||
|
|
423
|
+
parsed.version === 3 ||
|
|
424
|
+
parsed.version === 4
|
|
425
|
+
) {
|
|
426
|
+
this.backupPendingFor = parsed.version;
|
|
427
|
+
await this.ensureBackup(parsed.version);
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
const members: PersistedAgentRecord[] = [];
|
|
431
|
+
let skipped = 0;
|
|
432
|
+
let modelFollowMigrated = 0;
|
|
433
|
+
for (const entry of parsed.members) {
|
|
434
|
+
const member = parseMember(entry, parsed.version);
|
|
435
|
+
if (member === undefined) {
|
|
436
|
+
skipped += 1;
|
|
437
|
+
continue;
|
|
438
|
+
}
|
|
439
|
+
// v5 迁移计数:旧快照里带 model 的条目(parseMember 已按版本丢弃)。
|
|
440
|
+
if (
|
|
441
|
+
parsed.version < AGENT_SNAPSHOT_VERSION &&
|
|
442
|
+
isRecord(entry) &&
|
|
443
|
+
optionalString(entry.model) !== undefined
|
|
444
|
+
) {
|
|
445
|
+
modelFollowMigrated += 1;
|
|
446
|
+
}
|
|
447
|
+
members.push(member);
|
|
448
|
+
}
|
|
449
|
+
if (skipped > 0) {
|
|
450
|
+
this.logger.warn('agent.snapshot.members_skipped', { path: this.filePath, count: skipped });
|
|
451
|
+
}
|
|
452
|
+
if (modelFollowMigrated > 0) {
|
|
453
|
+
this.logger.warn('agent.snapshot.model_follow_migrated', {
|
|
454
|
+
path: this.filePath,
|
|
455
|
+
count: modelFollowMigrated,
|
|
456
|
+
});
|
|
457
|
+
}
|
|
458
|
+
return members;
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* 把损坏文件移到 `<path>.corrupt-<timestamp>`;隔离失败时禁止后续写入。
|
|
463
|
+
* 隔离是保留唯一恢复副本的手段,不是修复:不删除、不改写原字节。
|
|
464
|
+
*/
|
|
465
|
+
private async quarantine(reason: string): Promise<void> {
|
|
466
|
+
const base = `${this.filePath}.corrupt-${this.now()}`;
|
|
467
|
+
let target = base;
|
|
468
|
+
let suffix = 1;
|
|
469
|
+
while (await fileExists(target)) {
|
|
470
|
+
target = `${base}-${suffix}`;
|
|
471
|
+
suffix += 1;
|
|
472
|
+
}
|
|
473
|
+
try {
|
|
474
|
+
await rename(this.filePath, target);
|
|
475
|
+
this.logger.error('agent.snapshot.corrupt_quarantined', {
|
|
476
|
+
path: this.filePath,
|
|
477
|
+
quarantine_path: target,
|
|
478
|
+
error: reason,
|
|
479
|
+
});
|
|
480
|
+
} catch (error) {
|
|
481
|
+
// 已被其它进程移走:恢复副本仍在,允许后续写入新文件。
|
|
482
|
+
if ((error as NodeJS.ErrnoException)?.code === 'ENOENT') return;
|
|
483
|
+
this.writeBlocked = true;
|
|
484
|
+
this.logger.error('agent.snapshot.corrupt_quarantine_failed', {
|
|
485
|
+
path: this.filePath,
|
|
486
|
+
error: error instanceof Error ? error.message : String(error),
|
|
487
|
+
});
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
/**
|
|
492
|
+
* 确保旧版本备份存在。返回 false 表示备份失败;调用方据此决定是否放弃写新版。
|
|
493
|
+
* 备份已存在视为完成(幂等)。
|
|
494
|
+
*/
|
|
495
|
+
private async ensureBackup(version: 1 | 2 | 3 | 4): Promise<boolean> {
|
|
496
|
+
if (this.backupPendingFor !== version) return true;
|
|
497
|
+
const suffix =
|
|
498
|
+
version === 1
|
|
499
|
+
? V1_BACKUP_SUFFIX
|
|
500
|
+
: version === 2
|
|
501
|
+
? V2_BACKUP_SUFFIX
|
|
502
|
+
: version === 3
|
|
503
|
+
? V3_BACKUP_SUFFIX
|
|
504
|
+
: V4_BACKUP_SUFFIX;
|
|
505
|
+
const backupPath = `${this.filePath}${suffix}`;
|
|
506
|
+
try {
|
|
507
|
+
if (!(await fileExists(backupPath))) {
|
|
508
|
+
await copyFile(this.filePath, backupPath);
|
|
509
|
+
}
|
|
510
|
+
this.backupPendingFor = undefined;
|
|
511
|
+
return true;
|
|
512
|
+
} catch (error) {
|
|
513
|
+
this.logger.error('agent.snapshot.backup_failed', {
|
|
514
|
+
path: this.filePath,
|
|
515
|
+
backup_path: backupPath,
|
|
516
|
+
error: error instanceof Error ? error.message : String(error),
|
|
517
|
+
});
|
|
518
|
+
return false;
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/**
|
|
523
|
+
* 未调用 load 直接 write 时,探测现有文件版本并补做备份。
|
|
524
|
+
* 损坏 / 不可读的文件已在 load 或 quarantine 中处理,这里不阻塞新文件写入。
|
|
525
|
+
*/
|
|
526
|
+
private async ensureSourceBackup(): Promise<boolean> {
|
|
527
|
+
if (this.backupPendingFor !== undefined) return this.ensureBackup(this.backupPendingFor);
|
|
528
|
+
if (this.backupChecked) return true;
|
|
529
|
+
this.backupChecked = true;
|
|
530
|
+
let version: number | undefined;
|
|
531
|
+
try {
|
|
532
|
+
const parsed: unknown = JSON.parse(await readFile(this.filePath, 'utf8'));
|
|
533
|
+
if (isRecord(parsed) && typeof parsed.version === 'number') version = parsed.version;
|
|
534
|
+
} catch {
|
|
535
|
+
return true;
|
|
536
|
+
}
|
|
537
|
+
if (version !== 1 && version !== 2 && version !== 3 && version !== 4) return true;
|
|
538
|
+
this.backupPendingFor = version;
|
|
539
|
+
return this.ensureBackup(version);
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
/** 原子写;任何失败返回 false,不向上抛 */
|
|
543
|
+
async write(members: PersistedAgentRecord[]): Promise<boolean> {
|
|
544
|
+
// 损坏文件没能隔离:写入会覆盖唯一恢复副本,放弃本次写并记录失败。
|
|
545
|
+
if (this.writeBlocked) {
|
|
546
|
+
this.logger.error('agent.snapshot.write_failed', {
|
|
547
|
+
path: this.filePath,
|
|
548
|
+
error: 'quarantine_failed',
|
|
549
|
+
});
|
|
550
|
+
return false;
|
|
551
|
+
}
|
|
552
|
+
// 读到旧版本但备份失败过:写入会失去回滚点,放弃本次写。
|
|
553
|
+
if (!(await this.ensureSourceBackup())) return false;
|
|
554
|
+
const file: AgentSnapshotFile = {
|
|
555
|
+
version: AGENT_SNAPSHOT_VERSION,
|
|
556
|
+
updated_at: this.now(),
|
|
557
|
+
members,
|
|
558
|
+
};
|
|
559
|
+
try {
|
|
560
|
+
await mkdir(dirname(this.filePath), { recursive: true });
|
|
561
|
+
await atomicWrite(this.filePath, `${JSON.stringify(file, null, 2)}\n`, {
|
|
562
|
+
mode: this.mode,
|
|
563
|
+
});
|
|
564
|
+
return true;
|
|
565
|
+
} catch (error) {
|
|
566
|
+
this.logger.error('agent.snapshot.write_failed', {
|
|
567
|
+
path: this.filePath,
|
|
568
|
+
error: error instanceof Error ? error.message : String(error),
|
|
569
|
+
});
|
|
570
|
+
return false;
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
/** 合并写入;同一窗口内多次调用只落最后一次快照 */
|
|
575
|
+
schedule(getMembers: () => PersistedAgentRecord[]): void {
|
|
576
|
+
this.pending = getMembers;
|
|
577
|
+
if (this.timer !== undefined) return;
|
|
578
|
+
this.timer = setTimeout(() => {
|
|
579
|
+
this.timer = undefined;
|
|
580
|
+
void this.flush();
|
|
581
|
+
}, this.throttleMs);
|
|
582
|
+
this.timer.unref?.();
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
/**
|
|
586
|
+
* 立即写入待写快照;写入串行,失败不抛。
|
|
587
|
+
* 无待写时返回 true(不返回上一次写入的结果),有待写时返回本次 write 的结果。
|
|
588
|
+
*/
|
|
589
|
+
async flush(): Promise<boolean> {
|
|
590
|
+
if (this.timer !== undefined) {
|
|
591
|
+
clearTimeout(this.timer);
|
|
592
|
+
this.timer = undefined;
|
|
593
|
+
}
|
|
594
|
+
const getMembers = this.pending;
|
|
595
|
+
this.pending = undefined;
|
|
596
|
+
if (getMembers === undefined) {
|
|
597
|
+
await this.chain;
|
|
598
|
+
return true;
|
|
599
|
+
}
|
|
600
|
+
const members = getMembers();
|
|
601
|
+
const write = this.chain.then(() => this.write(members));
|
|
602
|
+
this.chain = write;
|
|
603
|
+
return write;
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/** 取消待写快照(进程退出用;不落盘) */
|
|
607
|
+
dispose(): void {
|
|
608
|
+
if (this.timer !== undefined) {
|
|
609
|
+
clearTimeout(this.timer);
|
|
610
|
+
this.timer = undefined;
|
|
611
|
+
}
|
|
612
|
+
this.pending = undefined;
|
|
613
|
+
}
|
|
614
|
+
}
|