@yourstandby/fabric 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,459 @@
1
+ /**
2
+ * 派活:选机器(硬规则)+ 任务台账(落盘状态机)。
3
+ *
4
+ * 决策权在宿主侧,不交给 LLM:peer 表、心跳、负载、能力标签一律不进 prompt,
5
+ * 模型只看到一个 dispatch_remote 工具。省 token 的全部收益都来自这一条。
6
+ */
7
+ import { createHash } from "node:crypto";
8
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
9
+ import { dirname, join } from "node:path";
10
+ import {
11
+ FABRIC_DEADLINE_MS,
12
+ type FabricDeadlineClass,
13
+ type FabricGrant,
14
+ } from "../../../contract/domains/fabric.ts";
15
+ import { type ArtifactRef, isArtifactRef } from "./artifacts.ts";
16
+
17
+ /** 预计时长低于这个值就留在本地:跨机往返 + 排队比本地跑还贵。 */
18
+ export const REMOTE_MIN_ESTIMATE_MS = 60_000;
19
+ /** 心跳超过这个年龄就当离线(HEARTBEAT_TIMEOUT_MS 60s 太慢,局域网不需要等那么久)。 */
20
+ export const PEER_ONLINE_HB_MS = 5_000;
21
+ /** 队列深度上限:有活在跑就不接新活,避免「派过去排队」变成隐性超时。 */
22
+ /**
23
+ * 一台机器同时接几个远端任务。
24
+ * 0 太紧:它手上有一个 5 分钟的活,你就完全派不进去,而「钉住某台」后排队等它才是本意。
25
+ * 2 是上限:再多就会把它自己的交互会话拖垮。
26
+ */
27
+ export const PEER_MAX_QUEUE = 2;
28
+
29
+ const GRANT_RANK: Record<FabricGrant, number> = {
30
+ "read-only": 0,
31
+ "workspace-rw": 1,
32
+ "workspace-rw+bash": 2,
33
+ };
34
+
35
+ export interface PeerCandidate {
36
+ nodeId: string;
37
+ name: string;
38
+ online: boolean;
39
+ hbAgeMs: number | null;
40
+ queueDepth: number;
41
+ labels: readonly string[];
42
+ grants: FabricGrant;
43
+ /** 对端自报的 CPU 负载 0–1;没上报就是 null(按中性值打分,不假装空闲)。 */
44
+ cpuLoad?: number | null;
45
+ /** 同类任务在这台机器上的历史中位耗时;null 表示还没跑过。 */
46
+ historyP50Ms?: number | null;
47
+ }
48
+
49
+ export interface DispatchNeed {
50
+ labels: readonly string[];
51
+ estimatedMs: number;
52
+ /** 任务要求的最低档位;缺省 read-only。 */
53
+ grant?: FabricGrant;
54
+ /** 人钉住的机器:跳过打分直接给它,它忙也排队。 */
55
+ pin?: string | null;
56
+ }
57
+
58
+ export type DispatchRejection =
59
+ | "E_LOCAL_FASTER"
60
+ | "E_NO_PEERS"
61
+ | "E_PEER_OFFLINE"
62
+ | "E_PEER_BUSY"
63
+ | "E_NO_LABEL"
64
+ | "E_GRANT_TOO_LOW";
65
+
66
+ export type DispatchDecision =
67
+ | { ok: true; peerId: string; reason: string; considered: number }
68
+ | { ok: false; code: DispatchRejection; reason: string; considered: number };
69
+
70
+ /**
71
+ * 硬门槛全满足才派:
72
+ * 1. 在线且心跳新鲜;2. 能力标签齐全;3. 权限档位够;4. 队列没超过 PEER_MAX_QUEUE;
73
+ * 5. 预计时长够长(短活本地更快)。
74
+ * 过了门槛再打分(队列 / CPU / 心跳 / 历史耗时),命中钉住的那台则直接给它。
75
+ * 同分按名字排序,保证同一输入永远派到同一台。
76
+ */
77
+ export function choosePeer(
78
+ candidates: readonly PeerCandidate[],
79
+ need: DispatchNeed,
80
+ ): DispatchDecision {
81
+ const considered = candidates.length;
82
+ if (considered === 0) {
83
+ return { ok: false, code: "E_NO_PEERS", reason: "还没有已配对机器", considered };
84
+ }
85
+ if (!(need.estimatedMs >= REMOTE_MIN_ESTIMATE_MS)) {
86
+ return {
87
+ ok: false,
88
+ code: "E_LOCAL_FASTER",
89
+ reason: `预计 ${need.estimatedMs}ms < ${REMOTE_MIN_ESTIMATE_MS}ms,本地跑更快`,
90
+ considered,
91
+ };
92
+ }
93
+ const required = need.grant ?? "read-only";
94
+ const online = candidates.filter(
95
+ (peer) => peer.online && peer.hbAgeMs !== null && peer.hbAgeMs <= PEER_ONLINE_HB_MS,
96
+ );
97
+ if (online.length === 0) {
98
+ return { ok: false, code: "E_PEER_OFFLINE", reason: "已配对机器都不在线", considered };
99
+ }
100
+ const labelled = online.filter((peer) =>
101
+ need.labels.every((label) => peer.labels.includes(label)),
102
+ );
103
+ if (labelled.length === 0) {
104
+ return {
105
+ ok: false,
106
+ code: "E_NO_LABEL",
107
+ reason: `没有机器具备能力标签 ${need.labels.join(",") || "(空)"}`,
108
+ considered,
109
+ };
110
+ }
111
+ const allowed = labelled.filter((peer) => GRANT_RANK[peer.grants] >= GRANT_RANK[required]);
112
+ if (allowed.length === 0) {
113
+ return {
114
+ ok: false,
115
+ code: "E_GRANT_TOO_LOW",
116
+ reason: `拥有该能力的机器权限档位低于 ${required}`,
117
+ considered,
118
+ };
119
+ }
120
+ // 人钉住的机器优先:机器只看得到队列和负载,看不到「这活只有那台有数据」。
121
+ const pinned = need.pin ? allowed.find((peer) => peer.nodeId === need.pin) : undefined;
122
+ if (pinned) {
123
+ return {
124
+ ok: true,
125
+ peerId: pinned.nodeId,
126
+ reason: `按你钉住的选择派给 ${pinned.name}(队列 ${pinned.queueDepth})`,
127
+ considered,
128
+ };
129
+ }
130
+ const idle = allowed.filter((peer) => peer.queueDepth <= PEER_MAX_QUEUE);
131
+ if (idle.length === 0) {
132
+ return { ok: false, code: "E_PEER_BUSY", reason: "拥有该能力的机器都在忙", considered };
133
+ }
134
+ const ranked = idle
135
+ .map((peer) => ({ peer, score: scorePeer(peer) }))
136
+ .sort((a, b) => (a.score !== b.score ? a.score - b.score : a.peer.name.localeCompare(b.peer.name)));
137
+ const best = ranked[0];
138
+ if (!best) {
139
+ return { ok: false, code: "E_PEER_BUSY", reason: "拥有该能力的机器都在忙", considered };
140
+ }
141
+ return {
142
+ ok: true,
143
+ peerId: best.peer.nodeId,
144
+ reason: describeChoice(best.peer, best.score),
145
+ considered,
146
+ };
147
+ }
148
+
149
+ /**
150
+ * 打分(越小越好):队列最贵,其次 CPU,再是心跳新鲜度,最后才是历史耗时。
151
+ * 权重写成整数常量,保证「同一份心跳快照永远算出同一个结果」——可复现优先于最优。
152
+ */
153
+ export function scorePeer(peer: PeerCandidate): number {
154
+ const cpu =
155
+ typeof peer.cpuLoad === "number" && peer.cpuLoad >= 0 && peer.cpuLoad <= 1 ? peer.cpuLoad : 0.5;
156
+ const hb = Math.min(peer.hbAgeMs ?? PEER_ONLINE_HB_MS, PEER_ONLINE_HB_MS);
157
+ // 历史耗时折算成分钟:没跑过按 10 分钟算,避免「没历史」被当成最快。
158
+ const history =
159
+ typeof peer.historyP50Ms === "number" && peer.historyP50Ms > 0
160
+ ? Math.min(peer.historyP50Ms, 3_600_000) / 60_000
161
+ : 10;
162
+ return peer.queueDepth * 100 + cpu * 50 + (hb / PEER_ONLINE_HB_MS) * 10 + history;
163
+ }
164
+
165
+ /** 派给谁、凭什么——这句会原样显示在任务卡片上,必须是人话。 */
166
+ export function describeChoice(peer: PeerCandidate, score: number): string {
167
+ const parts = [
168
+ `队列 ${peer.queueDepth}`,
169
+ `负载 ${Math.round((peer.cpuLoad ?? 0.5) * 100)}%`,
170
+ ];
171
+ if (typeof peer.historyP50Ms === "number" && peer.historyP50Ms > 0) {
172
+ parts.push(`同类活历史中位 ${Math.round(peer.historyP50Ms / 60_000)} 分钟`);
173
+ }
174
+ return `派给 ${peer.name}:${parts.join(",")}(分 ${Math.round(score)})`;
175
+ }
176
+
177
+ export type TaskState =
178
+ | "submitted"
179
+ | "accepted"
180
+ | "running"
181
+ | "done"
182
+ | "failed"
183
+ | "lost"
184
+ | "cancelled";
185
+
186
+ export type TaskDirection = "outbound" | "inbound";
187
+
188
+ export interface TaskRecord {
189
+ taskId: string;
190
+ direction: TaskDirection;
191
+ peerId: string;
192
+ state: TaskState;
193
+ deadlineClass: FabricDeadlineClass;
194
+ deadlineAt: number;
195
+ createdAt: number;
196
+ updatedAt: number;
197
+ startedAt: number | null;
198
+ finishedAt: number | null;
199
+ inputRef: ArtifactRef | null;
200
+ resultRef: ArtifactRef | null;
201
+ diffRef: ArtifactRef | null;
202
+ workspaceHint: string;
203
+ summary: string;
204
+ /** 最近一次进度说明(running 期间有用;终态后保留最后一次)。 */
205
+ progress: string;
206
+ /** 结构化的进度代码与参数:接收方按自己的语言渲染,不用产生方的文案。 */
207
+ progressCode: string;
208
+ progressParams: Record<string, string | number> | null;
209
+ progressAt: number | null;
210
+ files: string[];
211
+ exitCode: number | null;
212
+ error: string | null;
213
+ /** 干活方 journal:重启后能回答「我上次有没有接这个活」,否则 A 只能盲目重派。 */
214
+ pid: number | null;
215
+ }
216
+
217
+ export class TaskLedgerError extends Error {
218
+ code: string;
219
+ constructor(code: string, message: string) {
220
+ super(message);
221
+ this.name = "TaskLedgerError";
222
+ this.code = code;
223
+ }
224
+ }
225
+
226
+ const TERMINAL: ReadonlySet<TaskState> = new Set(["done", "failed", "lost", "cancelled"]);
227
+
228
+ export function isTerminalState(state: TaskState): boolean {
229
+ return TERMINAL.has(state);
230
+ }
231
+
232
+ /** 内容寻址的任务 id:同一份任务(同样的 need + 输入)重复派发只有一个 id。 */
233
+ export function taskIdFor(input: {
234
+ peerId?: string;
235
+ prompt: string;
236
+ inputSha256?: string | null;
237
+ deadlineClass: FabricDeadlineClass;
238
+ }): string {
239
+ return createHash("sha256")
240
+ .update(input.prompt)
241
+ .update("\u0000")
242
+ .update(input.inputSha256 ?? "")
243
+ .update("\u0000")
244
+ .update(input.deadlineClass)
245
+ .digest("hex")
246
+ .slice(0, 16);
247
+ }
248
+
249
+ export function taskLedgerDir(agentDir: string, direction: TaskDirection): string {
250
+ return join(agentDir, "fabric", "tasks", direction);
251
+ }
252
+
253
+ function isRecord(value: unknown): value is Record<string, unknown> {
254
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
255
+ }
256
+
257
+ function validate(record: unknown): TaskRecord {
258
+ if (!isRecord(record)) throw new TaskLedgerError("E_INVALID_PARAMS", "task must be an object");
259
+ const taskId = typeof record.taskId === "string" ? record.taskId : "";
260
+ if (!/^[0-9a-f]{16}$/.test(taskId)) {
261
+ throw new TaskLedgerError("E_INVALID_PARAMS", "taskId must be 16 hex characters");
262
+ }
263
+ const state = record.state;
264
+ if (
265
+ typeof state !== "string" ||
266
+ ![
267
+ "submitted",
268
+ "accepted",
269
+ "running",
270
+ "done",
271
+ "failed",
272
+ "lost",
273
+ "cancelled",
274
+ ].includes(state)
275
+ ) {
276
+ throw new TaskLedgerError("E_INVALID_PARAMS", "unknown task state");
277
+ }
278
+ const deadlineClass = record.deadlineClass;
279
+ if (
280
+ typeof deadlineClass !== "string" ||
281
+ !["quick", "build", "long"].includes(deadlineClass)
282
+ ) {
283
+ throw new TaskLedgerError("E_INVALID_PARAMS", "unknown deadline class");
284
+ }
285
+ return {
286
+ taskId,
287
+ direction: record.direction === "inbound" ? "inbound" : "outbound",
288
+ peerId: typeof record.peerId === "string" ? record.peerId : "",
289
+ state: state as TaskState,
290
+ deadlineClass: deadlineClass as FabricDeadlineClass,
291
+ deadlineAt: typeof record.deadlineAt === "number" ? record.deadlineAt : 0,
292
+ createdAt: typeof record.createdAt === "number" ? record.createdAt : 0,
293
+ updatedAt: typeof record.updatedAt === "number" ? record.updatedAt : 0,
294
+ startedAt: typeof record.startedAt === "number" ? record.startedAt : null,
295
+ finishedAt: typeof record.finishedAt === "number" ? record.finishedAt : null,
296
+ inputRef: isArtifactRef(record.inputRef) ? (record.inputRef as ArtifactRef) : null,
297
+ resultRef: isArtifactRef(record.resultRef) ? (record.resultRef as ArtifactRef) : null,
298
+ diffRef: isArtifactRef(record.diffRef) ? (record.diffRef as ArtifactRef) : null,
299
+ workspaceHint: typeof record.workspaceHint === "string" ? record.workspaceHint : "",
300
+ summary: typeof record.summary === "string" ? record.summary.slice(0, 2_000) : "",
301
+ progress: typeof record.progress === "string" ? record.progress.slice(0, 200) : "",
302
+ progressCode: typeof record.progressCode === "string" ? record.progressCode.slice(0, 40) : "",
303
+ progressParams:
304
+ record.progressParams && typeof record.progressParams === "object"
305
+ ? (record.progressParams as Record<string, string | number>)
306
+ : null,
307
+ progressAt: typeof record.progressAt === "number" ? record.progressAt : null,
308
+ files: Array.isArray(record.files)
309
+ ? record.files.filter((item): item is string => typeof item === "string").slice(0, 200)
310
+ : [],
311
+ exitCode: typeof record.exitCode === "number" ? record.exitCode : null,
312
+ error: typeof record.error === "string" ? record.error : null,
313
+ pid: typeof record.pid === "number" ? record.pid : null,
314
+ };
315
+ }
316
+
317
+ export class TaskLedger {
318
+ readonly direction: TaskDirection;
319
+ private readonly dir: string;
320
+
321
+ constructor(agentDir: string, direction: TaskDirection, overrideDir?: string) {
322
+ this.direction = direction;
323
+ this.dir = overrideDir ?? taskLedgerDir(agentDir, direction);
324
+ }
325
+
326
+ private fileFor(taskId: string): string {
327
+ return join(this.dir, `${taskId}.json`);
328
+ }
329
+
330
+ create(input: {
331
+ taskId: string;
332
+ peerId: string;
333
+ deadlineClass: FabricDeadlineClass;
334
+ workspaceHint?: string;
335
+ inputRef?: ArtifactRef | null;
336
+ now?: number;
337
+ }): TaskRecord {
338
+ const now = input.now ?? Date.now();
339
+ const existing = this.get(input.taskId);
340
+ if (existing) return existing;
341
+ const record: TaskRecord = {
342
+ taskId: input.taskId,
343
+ direction: this.direction,
344
+ peerId: input.peerId,
345
+ state: "submitted",
346
+ deadlineClass: input.deadlineClass,
347
+ deadlineAt: now + FABRIC_DEADLINE_MS[input.deadlineClass],
348
+ createdAt: now,
349
+ updatedAt: now,
350
+ startedAt: null,
351
+ finishedAt: null,
352
+ inputRef: input.inputRef ?? null,
353
+ resultRef: null,
354
+ diffRef: null,
355
+ workspaceHint: input.workspaceHint ?? "",
356
+ summary: "",
357
+ progress: "",
358
+ progressCode: "",
359
+ progressParams: null,
360
+ progressAt: null,
361
+ files: [],
362
+ exitCode: null,
363
+ error: null,
364
+ pid: null,
365
+ };
366
+ this.write(record);
367
+ return record;
368
+ }
369
+
370
+ get(taskId: string): TaskRecord | null {
371
+ const file = this.fileFor(taskId);
372
+ if (!existsSync(file)) return null;
373
+ try {
374
+ return validate(JSON.parse(readFileSync(file, "utf8")) as unknown);
375
+ } catch {
376
+ return null;
377
+ }
378
+ }
379
+
380
+ list(): TaskRecord[] {
381
+ if (!existsSync(this.dir)) return [];
382
+ const records: TaskRecord[] = [];
383
+ for (const name of readdirSync(this.dir)) {
384
+ if (!/^[0-9a-f]{16}\.json$/.test(name)) continue;
385
+ const record = this.get(name.slice(0, 16));
386
+ if (record) records.push(record);
387
+ }
388
+ return records.sort((a, b) => b.updatedAt - a.updatedAt);
389
+ }
390
+
391
+ update(taskId: string, patch: Partial<TaskRecord> & { state?: TaskState }, now = Date.now()): TaskRecord {
392
+ const current = this.get(taskId);
393
+ if (!current) throw new TaskLedgerError("E_TASK_UNKNOWN", `unknown task ${taskId}`);
394
+ const state = patch.state ?? current.state;
395
+ if (isTerminalState(current.state) && current.state !== state) {
396
+ throw new TaskLedgerError("E_TASK_TERMINAL", `task ${taskId} already ${current.state}`);
397
+ }
398
+ const next: TaskRecord = {
399
+ ...current,
400
+ ...patch,
401
+ taskId: current.taskId,
402
+ direction: current.direction,
403
+ state,
404
+ updatedAt: now,
405
+ startedAt:
406
+ patch.startedAt ?? (state === "running" && current.startedAt === null ? now : current.startedAt),
407
+ finishedAt: isTerminalState(state) ? (patch.finishedAt ?? now) : current.finishedAt,
408
+ };
409
+ this.write(next);
410
+ return next;
411
+ }
412
+
413
+ /** 断线对账:超过 deadline 还没进终态就是 lost。只判「超时」,不判「网络抖动」。 */
414
+ reconcile(now = Date.now()): { lost: string[] } {
415
+ const lost: string[] = [];
416
+ for (const record of this.list()) {
417
+ if (isTerminalState(record.state)) continue;
418
+ if (now <= record.deadlineAt) continue;
419
+ this.update(
420
+ record.taskId,
421
+ { state: "lost", error: `deadline exceeded (${record.deadlineClass})` },
422
+ now,
423
+ );
424
+ lost.push(record.taskId);
425
+ }
426
+ return { lost };
427
+ }
428
+
429
+ /** 所有被任务引用的对象 sha256:artifact 的 TTL 清理靠它区分「有主」和「无主」。 */
430
+ references(): string[] {
431
+ const refs = new Set<string>();
432
+ for (const record of this.list()) {
433
+ for (const ref of [record.inputRef, record.resultRef, record.diffRef]) {
434
+ if (ref) refs.add(ref.sha256);
435
+ }
436
+ }
437
+ return [...refs];
438
+ }
439
+
440
+ /** 只清终态任务记录,避免把正在跑的对账信息删掉。 */
441
+ prune(olderThanMs: number, now = Date.now()): number {
442
+ let removed = 0;
443
+ for (const record of this.list()) {
444
+ if (!isTerminalState(record.state)) continue;
445
+ if (now - record.updatedAt <= olderThanMs) continue;
446
+ rmSync(this.fileFor(record.taskId), { force: true });
447
+ removed += 1;
448
+ }
449
+ return removed;
450
+ }
451
+
452
+ private write(record: TaskRecord): void {
453
+ mkdirSync(dirname(this.fileFor(record.taskId)), { recursive: true });
454
+ const file = this.fileFor(record.taskId);
455
+ const temp = `${file}.tmp`;
456
+ writeFileSync(temp, `${JSON.stringify(record, null, 2)}\n`, "utf8");
457
+ renameSync(temp, file);
458
+ }
459
+ }