@yourstandby/fabric 0.0.0-stage → 0.1.1
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 +24 -2
- package/dist/daemon.js +3797 -0
- package/dist/index.js +3916 -0
- package/package.json +30 -4
- package/src/artifacts.test.ts +148 -0
- package/src/artifacts.ts +247 -0
- package/src/daemon-runner.ts +218 -0
- package/src/daemon.ts +524 -0
- package/src/discovery.ts +332 -0
- package/src/dispatch.test.ts +154 -0
- package/src/dispatch.ts +459 -0
- package/src/dispatcher.test.ts +321 -0
- package/src/dispatcher.ts +794 -0
- package/src/fabric-apply.test.ts +115 -0
- package/src/fabric-apply.ts +137 -0
- package/src/fabric-avatar.test.ts +51 -0
- package/src/fabric-discovery.test.ts +100 -0
- package/src/fabric-history.test.ts +68 -0
- package/src/fabric-keepalive.test.ts +112 -0
- package/src/fabric-notify.test.ts +269 -0
- package/src/fabric-pairing.test.ts +164 -0
- package/src/fabric-runner.test.ts +113 -0
- package/src/fabric-runner.ts +167 -0
- package/src/fabric-score.test.ts +74 -0
- package/src/fabric-server.ts +101 -0
- package/src/fabric-service.test.ts +279 -0
- package/src/fabric-service.ts +745 -0
- package/src/fabric-view.test.ts +118 -0
- package/src/fabric-view.ts +182 -0
- package/src/fabric-worktree.test.ts +139 -0
- package/src/fabric-worktree.ts +232 -0
- package/src/history.ts +127 -0
- package/src/host-load.ts +18 -0
- package/src/index.ts +27 -0
- package/src/pairing.test.ts +212 -0
- package/src/pairing.ts +342 -0
- package/src/peer-store.test.ts +212 -0
- package/src/peer-store.ts +243 -0
- package/src/transport.test.ts +247 -0
- package/src/transport.ts +709 -0
|
@@ -0,0 +1,794 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 派活调度:把「选机器 -> 推输入 -> 交给对端跑 -> 取回结果」串成一条链。
|
|
3
|
+
*
|
|
4
|
+
* 所有对外副作用都从这里过,好处是「谁派的活、改了什么、跑没跑完」只有一处可查,
|
|
5
|
+
* 也让单测可以注入假链路,不必真的起两台机器。
|
|
6
|
+
*/
|
|
7
|
+
import { createHash } from "node:crypto";
|
|
8
|
+
import {
|
|
9
|
+
FABRIC_DEADLINE_MS,
|
|
10
|
+
FABRIC_TOOLS_BY_GRANT,
|
|
11
|
+
type FabricProgressNote,
|
|
12
|
+
grantAllows,
|
|
13
|
+
type FabricDeadlineClass,
|
|
14
|
+
type FabricFeature,
|
|
15
|
+
type FabricGrant,
|
|
16
|
+
type FabricPeer,
|
|
17
|
+
} from "../../../contract/domains/fabric.ts";
|
|
18
|
+
import {
|
|
19
|
+
ArtifactStore,
|
|
20
|
+
isArtifactRef,
|
|
21
|
+
type ArtifactRef,
|
|
22
|
+
} from "./artifacts.ts";
|
|
23
|
+
import {
|
|
24
|
+
REMOTE_MIN_ESTIMATE_MS,
|
|
25
|
+
TaskLedger,
|
|
26
|
+
choosePeer,
|
|
27
|
+
isTerminalState,
|
|
28
|
+
taskIdFor,
|
|
29
|
+
type PeerCandidate,
|
|
30
|
+
type TaskRecord,
|
|
31
|
+
} from "./dispatch.ts";
|
|
32
|
+
import { FabricPeerConnection, type FabricConnState, type FabricLink } from "./transport.ts";
|
|
33
|
+
import { type FabricIdentity } from "./pairing.ts";
|
|
34
|
+
import { listPeers, peersStorePath, touchPeer } from "./peer-store.ts";
|
|
35
|
+
import { FabricHistory, historyKey } from "./history.ts";
|
|
36
|
+
import { cpuLoad, memAvailableMb } from "./host-load.ts";
|
|
37
|
+
|
|
38
|
+
/** 对端上报的运行时状态:不落盘,进 prompt 更是禁区。 */
|
|
39
|
+
export interface PeerLoad {
|
|
40
|
+
nodeId: string;
|
|
41
|
+
online: boolean;
|
|
42
|
+
queueDepth: number;
|
|
43
|
+
hbAgeMs: number | null;
|
|
44
|
+
labels: string[];
|
|
45
|
+
/** 对端自报的 CPU 负载 0–1;null = 对端报不出来(Windows 的 loadavg 恒为 0)。 */
|
|
46
|
+
cpuLoad?: number | null;
|
|
47
|
+
memAvailableMb?: number | null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** B 侧真正干活的那段代码;接 spawnSubagent 还是别的执行器由调用方决定。 */
|
|
51
|
+
export interface FabricRemoteRunner {
|
|
52
|
+
run(input: {
|
|
53
|
+
taskId: string;
|
|
54
|
+
prompt: string;
|
|
55
|
+
workspaceHint: string;
|
|
56
|
+
grant: FabricGrant;
|
|
57
|
+
tools: readonly string[];
|
|
58
|
+
input: Buffer | null;
|
|
59
|
+
signal: AbortSignal;
|
|
60
|
+
/** 真实进度:结构化 code + 参数 + 兜底文案,宿主按 2 秒节流再推给发起方。 */
|
|
61
|
+
onProgress: (note: FabricProgressNote) => void;
|
|
62
|
+
}): Promise<{
|
|
63
|
+
summary: string;
|
|
64
|
+
files?: string[];
|
|
65
|
+
exitCode?: number;
|
|
66
|
+
result?: Buffer;
|
|
67
|
+
/** 改动差异(worktree 才有);回传成 diff 产物,发起方据此决定合不合。 */
|
|
68
|
+
diff?: Buffer | null;
|
|
69
|
+
}>;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface FabricDispatcherOptions {
|
|
73
|
+
agentDir: string;
|
|
74
|
+
identity: FabricIdentity;
|
|
75
|
+
runner?: FabricRemoteRunner;
|
|
76
|
+
artifacts?: ArtifactStore;
|
|
77
|
+
outbound?: TaskLedger;
|
|
78
|
+
inbound?: TaskLedger;
|
|
79
|
+
/** 建立链路;默认走 dialFabricLink,测试注入内存链路。 */
|
|
80
|
+
connect?: (peer: FabricPeer) => Promise<FabricLink>;
|
|
81
|
+
now?: () => number;
|
|
82
|
+
log?: (message: string) => void;
|
|
83
|
+
/** 本端应用版本,给对端 UI 显示用。 */
|
|
84
|
+
appVersion?: string;
|
|
85
|
+
/** 任务结束时通知发起方(有常驻连接就推事件,没连上就靠它自己来对账)。 */
|
|
86
|
+
notify?: (nodeId: string, frame: Record<string, unknown>) => boolean;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export interface SubmitInput {
|
|
90
|
+
prompt: string;
|
|
91
|
+
labels?: string[];
|
|
92
|
+
estimatedMs: number;
|
|
93
|
+
deadlineClass: FabricDeadlineClass;
|
|
94
|
+
grant?: FabricGrant;
|
|
95
|
+
/** 人钉住的那台机器:跳过打分直接给它,忙也排队。 */
|
|
96
|
+
pin?: string | null;
|
|
97
|
+
workspaceHint?: string;
|
|
98
|
+
input?: Buffer | null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export type SubmitResult =
|
|
102
|
+
| { ok: true; taskId: string; peerId: string; reason: string }
|
|
103
|
+
| { ok: false; code: string; reason: string };
|
|
104
|
+
|
|
105
|
+
const LABEL_MAX = 8;
|
|
106
|
+
const LABEL_CHARS = 24;
|
|
107
|
+
|
|
108
|
+
export function sanitizeLabels(raw: unknown): string[] {
|
|
109
|
+
if (!Array.isArray(raw)) return [];
|
|
110
|
+
const labels = raw
|
|
111
|
+
.filter((item): item is string => typeof item === "string")
|
|
112
|
+
.map((item) => item.trim().toLowerCase())
|
|
113
|
+
.filter((item) => item && item.length <= LABEL_CHARS);
|
|
114
|
+
return [...new Set(labels)].slice(0, LABEL_MAX);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export class FabricDispatcher {
|
|
118
|
+
readonly artifacts: ArtifactStore;
|
|
119
|
+
readonly outbound: TaskLedger;
|
|
120
|
+
readonly inbound: TaskLedger;
|
|
121
|
+
private readonly options: FabricDispatcherOptions;
|
|
122
|
+
private readonly links = new Map<string, FabricLink>();
|
|
123
|
+
private readonly loads = new Map<string, PeerLoad>();
|
|
124
|
+
/** 常驻连接:配对即连,不手动取消就一直连着(指数退避,永不放弃)。 */
|
|
125
|
+
private readonly connections = new Map<string, FabricPeerConnection>();
|
|
126
|
+
private readonly inflight = new Map<string, AbortController>();
|
|
127
|
+
|
|
128
|
+
private historyStore: FabricHistory | null = null;
|
|
129
|
+
/** taskId -> 历史标签键:任务落终态时才知道耗时,靠这张表把两边对上。 */
|
|
130
|
+
private readonly historyKeyByTask = new Map<string, string>();
|
|
131
|
+
|
|
132
|
+
private history(): FabricHistory {
|
|
133
|
+
this.historyStore ??= new FabricHistory(this.options.agentDir);
|
|
134
|
+
return this.historyStore;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** 任务终态时写一条历史;没有标签键就不记(测试注入的假任务没有标签)。 */
|
|
138
|
+
private recordOutcome(taskId: string, ok: boolean): void {
|
|
139
|
+
const key = this.historyKeyByTask.get(taskId);
|
|
140
|
+
this.historyKeyByTask.delete(taskId);
|
|
141
|
+
if (!key) return;
|
|
142
|
+
const startedAt = this.outbound.get(taskId)?.startedAt ?? null;
|
|
143
|
+
const duration = startedAt === null ? 0 : Math.max(0, this.now() - startedAt);
|
|
144
|
+
this.history().record(key, duration, ok, this.now());
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
constructor(options: FabricDispatcherOptions) {
|
|
148
|
+
this.options = options;
|
|
149
|
+
this.artifacts = options.artifacts ?? new ArtifactStore(options.agentDir);
|
|
150
|
+
this.outbound = options.outbound ?? new TaskLedger(options.agentDir, "outbound");
|
|
151
|
+
this.inbound = options.inbound ?? new TaskLedger(options.agentDir, "inbound");
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
private now(): number {
|
|
155
|
+
return this.options.now?.() ?? Date.now();
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** 已配对的机器从这里进;连接失败只记日志,不抛(断线是常态,不是异常)。 */
|
|
159
|
+
private async linkFor(peer: FabricPeer): Promise<FabricLink | null> {
|
|
160
|
+
// 常驻连接优先:它自己负责重连,这里不要另开一条(否则两台机器之间会堆连接)。
|
|
161
|
+
const persistent = this.connections.get(peer.nodeId)?.current();
|
|
162
|
+
if (persistent?.connected) {
|
|
163
|
+
this.links.set(peer.nodeId, persistent);
|
|
164
|
+
return persistent;
|
|
165
|
+
}
|
|
166
|
+
const existing = this.links.get(peer.nodeId);
|
|
167
|
+
if (existing?.connected) return existing;
|
|
168
|
+
try {
|
|
169
|
+
const connect =
|
|
170
|
+
this.options.connect ??
|
|
171
|
+
(async (target: FabricPeer) => {
|
|
172
|
+
const { dialFabricLink } = await import("./transport.ts");
|
|
173
|
+
return dialFabricLink({
|
|
174
|
+
identity: this.options.identity,
|
|
175
|
+
peer: { nodeId: target.nodeId, address: target.address, port: target.port },
|
|
176
|
+
appVersion: this.options.appVersion ?? "",
|
|
177
|
+
log: this.options.log,
|
|
178
|
+
});
|
|
179
|
+
});
|
|
180
|
+
const link = await connect(peer);
|
|
181
|
+
this.links.set(peer.nodeId, link);
|
|
182
|
+
return link;
|
|
183
|
+
} catch (error) {
|
|
184
|
+
this.options.log?.(
|
|
185
|
+
`fabric connect failed (${peer.nodeId}): ${error instanceof Error ? error.message : String(error)}`,
|
|
186
|
+
);
|
|
187
|
+
this.links.delete(peer.nodeId);
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** 刷新每台机器「在不在 / 忙不忙 / 会什么」——这些信息只在宿主内存里。 */
|
|
193
|
+
async refreshLoads(peers = listPeers(this.options.agentDir)): Promise<PeerLoad[]> {
|
|
194
|
+
const result: PeerLoad[] = [];
|
|
195
|
+
for (const peer of peers) {
|
|
196
|
+
const link = await this.linkFor(peer);
|
|
197
|
+
if (!link) {
|
|
198
|
+
result.push({ nodeId: peer.nodeId, online: false, queueDepth: 9, hbAgeMs: null, labels: [] });
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
try {
|
|
202
|
+
const raw = (await link.call("peer.status", {})) as Record<string, unknown>;
|
|
203
|
+
const load: PeerLoad = {
|
|
204
|
+
nodeId: peer.nodeId,
|
|
205
|
+
online: raw.online !== false,
|
|
206
|
+
queueDepth: typeof raw.queueDepth === "number" ? raw.queueDepth : 0,
|
|
207
|
+
hbAgeMs: typeof raw.hbAgeMs === "number" ? raw.hbAgeMs : 0,
|
|
208
|
+
labels: sanitizeLabels(raw.labels),
|
|
209
|
+
cpuLoad: typeof raw.cpuLoad === "number" ? raw.cpuLoad : null,
|
|
210
|
+
memAvailableMb: typeof raw.memAvailableMb === "number" ? raw.memAvailableMb : null,
|
|
211
|
+
};
|
|
212
|
+
this.loads.set(peer.nodeId, load);
|
|
213
|
+
result.push(load);
|
|
214
|
+
touchPeer(this.options.agentDir, peer.nodeId, this.now());
|
|
215
|
+
} catch {
|
|
216
|
+
result.push({ nodeId: peer.nodeId, online: false, queueDepth: 9, hbAgeMs: null, labels: [] });
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
return result;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
candidates(loads: readonly PeerLoad[], peers = listPeers(this.options.agentDir)): PeerCandidate[] {
|
|
223
|
+
return loads.map((load) => {
|
|
224
|
+
const peer = peers.find((item) => item.nodeId === load.nodeId);
|
|
225
|
+
return {
|
|
226
|
+
nodeId: load.nodeId,
|
|
227
|
+
name: peer?.name ?? load.nodeId,
|
|
228
|
+
online: load.online,
|
|
229
|
+
hbAgeMs: load.hbAgeMs,
|
|
230
|
+
queueDepth: load.queueDepth,
|
|
231
|
+
labels: load.labels,
|
|
232
|
+
grants: peer?.grants ?? "read-only",
|
|
233
|
+
cpuLoad: load.cpuLoad ?? null,
|
|
234
|
+
historyP50Ms: this.history().p50(load.labels),
|
|
235
|
+
};
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/** 派活:选机器 -> 存输入 -> 记账 -> 发给对端。 */
|
|
240
|
+
async submit(input: SubmitInput): Promise<SubmitResult> {
|
|
241
|
+
// 先在本地判一次「值不值得派」:连都不该连,省一次心跳和一次失败日志。
|
|
242
|
+
if (!(input.estimatedMs >= REMOTE_MIN_ESTIMATE_MS)) {
|
|
243
|
+
return {
|
|
244
|
+
ok: false,
|
|
245
|
+
code: "E_LOCAL_FASTER",
|
|
246
|
+
reason: `预计 ${input.estimatedMs}ms < ${REMOTE_MIN_ESTIMATE_MS}ms,本地跑更快`,
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
const peers = listPeers(this.options.agentDir);
|
|
250
|
+
const loads = await this.refreshLoads(peers);
|
|
251
|
+
const needLabels = sanitizeLabels(input.labels ?? []);
|
|
252
|
+
const decision = choosePeer(this.candidates(loads, peers), {
|
|
253
|
+
labels: needLabels,
|
|
254
|
+
estimatedMs: input.estimatedMs,
|
|
255
|
+
grant: input.grant,
|
|
256
|
+
pin: input.pin ?? null,
|
|
257
|
+
});
|
|
258
|
+
if (decision.ok === false) {
|
|
259
|
+
return { ok: false, code: decision.code, reason: decision.reason };
|
|
260
|
+
}
|
|
261
|
+
const peer = peers.find((item) => item.nodeId === decision.peerId);
|
|
262
|
+
if (!peer) return { ok: false, code: "E_PEER_UNKNOWN", reason: "peer record disappeared" };
|
|
263
|
+
const inputRef = input.input ? this.artifacts.put(input.input, "input") : null;
|
|
264
|
+
const taskId = taskIdFor({
|
|
265
|
+
prompt: input.prompt,
|
|
266
|
+
deadlineClass: input.deadlineClass,
|
|
267
|
+
inputSha256: inputRef?.sha256 ?? null,
|
|
268
|
+
});
|
|
269
|
+
this.historyKeyByTask.set(taskId, historyKey(needLabels));
|
|
270
|
+
const record = this.outbound.create({
|
|
271
|
+
taskId,
|
|
272
|
+
peerId: peer.nodeId,
|
|
273
|
+
deadlineClass: input.deadlineClass,
|
|
274
|
+
workspaceHint: input.workspaceHint ?? "",
|
|
275
|
+
inputRef,
|
|
276
|
+
now: this.now(),
|
|
277
|
+
});
|
|
278
|
+
if (record.state === "done" || record.state === "running") {
|
|
279
|
+
return { ok: true, taskId, peerId: peer.nodeId, reason: "already dispatched (idempotent)" };
|
|
280
|
+
}
|
|
281
|
+
const link = await this.linkFor(peer);
|
|
282
|
+
if (!link) return { ok: false, code: "E_PEER_OFFLINE", reason: `${peer.name} 连不上` };
|
|
283
|
+
try {
|
|
284
|
+
// 先完整推送输入再开工(Q7 选 A):失败语义唯一确定,「B 上没开始就丢弃」。
|
|
285
|
+
if (inputRef && input.input) {
|
|
286
|
+
await link.call("artifact.put", {
|
|
287
|
+
sha256: inputRef.sha256,
|
|
288
|
+
len: inputRef.len,
|
|
289
|
+
kind: inputRef.kind,
|
|
290
|
+
data: input.input.toString("base64"),
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
await link.call("task.submit", {
|
|
294
|
+
taskId,
|
|
295
|
+
prompt: input.prompt,
|
|
296
|
+
deadlineClass: input.deadlineClass,
|
|
297
|
+
grant: peer.grants,
|
|
298
|
+
workspaceHint: input.workspaceHint ?? "",
|
|
299
|
+
inputRef,
|
|
300
|
+
});
|
|
301
|
+
// 对端可能在我们收到应答之前就跑完并推了 task_done(本地任务只有几十毫秒),
|
|
302
|
+
// 所以这里只能「往前推」:已经是终态就不要再改,否则会把 done 覆盖成 accepted。
|
|
303
|
+
this.advance(taskId, { state: "accepted" });
|
|
304
|
+
return { ok: true, taskId, peerId: peer.nodeId, reason: decision.reason };
|
|
305
|
+
} catch (error) {
|
|
306
|
+
this.advance(taskId, {
|
|
307
|
+
state: "failed",
|
|
308
|
+
error: error instanceof Error ? error.message : String(error),
|
|
309
|
+
});
|
|
310
|
+
return { ok: false, code: "E_DISPATCH_FAILED", reason: "投递失败(任务已记账,可重试同一 taskId)" };
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* 对账:先把超时的判 lost,再向对端要状态。
|
|
316
|
+
* 断线期间对端可能已经干完了——所以「问」永远优先于「重派」。
|
|
317
|
+
*/
|
|
318
|
+
async reconcile(): Promise<{ lost: string[]; done: string[] }> {
|
|
319
|
+
const { lost } = this.outbound.reconcile(this.now());
|
|
320
|
+
const done: string[] = [];
|
|
321
|
+
const peers = listPeers(this.options.agentDir);
|
|
322
|
+
for (const record of this.outbound.list()) {
|
|
323
|
+
if (record.state === "done" || record.state === "failed" || record.state === "lost") continue;
|
|
324
|
+
const peer = peers.find((item) => item.nodeId === record.peerId);
|
|
325
|
+
if (!peer) continue;
|
|
326
|
+
const link = await this.linkFor(peer);
|
|
327
|
+
if (!link) continue;
|
|
328
|
+
try {
|
|
329
|
+
const status = (await link.call("task.status", { taskId: record.taskId })) as Record<string, unknown>;
|
|
330
|
+
const state = typeof status.state === "string" ? status.state : "";
|
|
331
|
+
if (state === "done") {
|
|
332
|
+
// 先拉字节(结果是给人看的东西),拉不到就保留引用待按需再取。
|
|
333
|
+
const resultRef = await this.pullResult(link, record, status);
|
|
334
|
+
// patch 同样是「只带引用」的产物:不在这里拉一次,发起方永远 diffFor()===null,
|
|
335
|
+
// 看起来就像对端什么也没改。
|
|
336
|
+
const diffRef = await this.pullArtifact(link, status.diffRef);
|
|
337
|
+
this.outbound.update(
|
|
338
|
+
record.taskId,
|
|
339
|
+
{
|
|
340
|
+
state: "done",
|
|
341
|
+
resultRef,
|
|
342
|
+
...(diffRef ? { diffRef } : {}),
|
|
343
|
+
summary: typeof status.summary === "string" ? status.summary : "",
|
|
344
|
+
files: Array.isArray(status.files)
|
|
345
|
+
? status.files.filter((item): item is string => typeof item === "string")
|
|
346
|
+
: [],
|
|
347
|
+
exitCode: typeof status.exitCode === "number" ? status.exitCode : null,
|
|
348
|
+
},
|
|
349
|
+
this.now(),
|
|
350
|
+
);
|
|
351
|
+
this.recordOutcome(record.taskId, true);
|
|
352
|
+
done.push(record.taskId);
|
|
353
|
+
} else if (state === "failed") {
|
|
354
|
+
this.outbound.update(
|
|
355
|
+
record.taskId,
|
|
356
|
+
{ state: "failed", error: typeof status.error === "string" ? status.error : "remote failure" },
|
|
357
|
+
this.now(),
|
|
358
|
+
);
|
|
359
|
+
this.recordOutcome(record.taskId, false);
|
|
360
|
+
} else if (state === "running" && record.state !== "running") {
|
|
361
|
+
this.outbound.update(record.taskId, { state: "running" }, this.now());
|
|
362
|
+
}
|
|
363
|
+
} catch {
|
|
364
|
+
// 链路没问题但方法不认识 / 对端重启丢了状态:留给 deadline 判 lost。
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
return { lost, done };
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** 只允许把任务往前推:终态不可回退,也不会被迟到的 accepted/failed 覆盖。 */
|
|
371
|
+
private advance(taskId: string, patch: Partial<TaskRecord> & { state?: TaskRecord["state"] }): void {
|
|
372
|
+
const current = this.outbound.get(taskId);
|
|
373
|
+
if (!current || isTerminalState(current.state)) return;
|
|
374
|
+
this.outbound.update(taskId, patch, this.now());
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
private pullResult(
|
|
378
|
+
link: FabricLink,
|
|
379
|
+
record: TaskRecord,
|
|
380
|
+
status: Record<string, unknown>,
|
|
381
|
+
): Promise<ArtifactRef | null> {
|
|
382
|
+
void record;
|
|
383
|
+
return this.pullArtifact(link, status.resultRef);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
/** 按引用把产物拉到本机;拉不到就保留引用(下次对账/按需再取,不把已完成的任务判死)。 */
|
|
387
|
+
private async pullArtifact(link: FabricLink, raw: unknown): Promise<ArtifactRef | null> {
|
|
388
|
+
const ref = raw;
|
|
389
|
+
if (!ref || typeof ref !== "object") return null;
|
|
390
|
+
const candidate = ref as ArtifactRef;
|
|
391
|
+
if (typeof candidate.sha256 !== "string") return null;
|
|
392
|
+
if (this.artifacts.has(candidate.sha256)) return candidate;
|
|
393
|
+
try {
|
|
394
|
+
const pulled = (await link.call("artifact.get", {
|
|
395
|
+
sha256: candidate.sha256,
|
|
396
|
+
len: candidate.len,
|
|
397
|
+
kind: candidate.kind,
|
|
398
|
+
})) as Record<string, unknown>;
|
|
399
|
+
if (typeof pulled.data !== "string") return candidate;
|
|
400
|
+
const stored = this.artifacts.put(Buffer.from(pulled.data, "base64"), candidate.kind ?? "result");
|
|
401
|
+
return stored.sha256 === candidate.sha256 ? stored : candidate;
|
|
402
|
+
} catch {
|
|
403
|
+
return candidate;
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/** A 侧收到的事件:对端说它干完了 / 干挂了,直接落台账。 */
|
|
408
|
+
async applyEvent(frame: Record<string, unknown>): Promise<void> {
|
|
409
|
+
const taskId = typeof frame.taskId === "string" ? frame.taskId : "";
|
|
410
|
+
const record = this.outbound.get(taskId);
|
|
411
|
+
if (!record) return;
|
|
412
|
+
if (frame.type === "task_done") {
|
|
413
|
+
// 推送里只有引用:先把 patch 拉到本机,再落台账,否则 UI/CLI 看到的是空 diff。
|
|
414
|
+
const link = this.links.get(record.peerId);
|
|
415
|
+
const diffRef = link ? await this.pullArtifact(link, frame.diffRef) : isArtifactRef(frame.diffRef) ? frame.diffRef : null;
|
|
416
|
+
this.outbound.update(
|
|
417
|
+
taskId,
|
|
418
|
+
{
|
|
419
|
+
state: "done",
|
|
420
|
+
diffRef,
|
|
421
|
+
summary: typeof frame.summary === "string" ? frame.summary : "",
|
|
422
|
+
exitCode: typeof frame.exitCode === "number" ? frame.exitCode : null,
|
|
423
|
+
files: Array.isArray(frame.files)
|
|
424
|
+
? frame.files.filter((item): item is string => typeof item === "string")
|
|
425
|
+
: [],
|
|
426
|
+
},
|
|
427
|
+
this.now(),
|
|
428
|
+
);
|
|
429
|
+
this.recordOutcome(taskId, true);
|
|
430
|
+
return;
|
|
431
|
+
}
|
|
432
|
+
if (frame.type === "task_progress") {
|
|
433
|
+
this.advance(taskId, {
|
|
434
|
+
progress: typeof frame.text === "string" ? frame.text.slice(0, 200) : "",
|
|
435
|
+
progressCode: typeof frame.code === "string" ? frame.code.slice(0, 40) : "",
|
|
436
|
+
progressParams:
|
|
437
|
+
frame.params && typeof frame.params === "object"
|
|
438
|
+
? (frame.params as Record<string, string | number>)
|
|
439
|
+
: null,
|
|
440
|
+
progressAt: this.now(),
|
|
441
|
+
});
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
if (frame.type === "task_failed") {
|
|
445
|
+
this.outbound.update(
|
|
446
|
+
taskId,
|
|
447
|
+
{ state: "failed", error: typeof frame.error === "string" ? frame.error : "remote failure" },
|
|
448
|
+
this.now(),
|
|
449
|
+
);
|
|
450
|
+
this.recordOutcome(taskId, false);
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/**
|
|
455
|
+
* B 侧入口:所有入站方法都在这里。
|
|
456
|
+
* 未配对的调用根本到不了这一层(握手阶段已拒绝),这里只做档位与参数校验。
|
|
457
|
+
*/
|
|
458
|
+
async handleInbound(
|
|
459
|
+
method: string,
|
|
460
|
+
params: Record<string, unknown>,
|
|
461
|
+
caller: { nodeId: string; grants: FabricGrant } = { nodeId: "", grants: "read-only" },
|
|
462
|
+
): Promise<unknown> {
|
|
463
|
+
switch (method) {
|
|
464
|
+
case "peer.status":
|
|
465
|
+
return {
|
|
466
|
+
online: true,
|
|
467
|
+
queueDepth: this.inflight.size,
|
|
468
|
+
hbAgeMs: 0,
|
|
469
|
+
labels: this.labels?.() ?? [],
|
|
470
|
+
// 真实负载:选机打分用。报不出来就是 null,调用方会按中性值处理。
|
|
471
|
+
cpuLoad: cpuLoad(),
|
|
472
|
+
memAvailableMb: memAvailableMb(),
|
|
473
|
+
features: this.options.identity.nodeId ? ["fabric.task.v1"] : [],
|
|
474
|
+
};
|
|
475
|
+
case "artifact.put": {
|
|
476
|
+
const data = typeof params.data === "string" ? Buffer.from(params.data, "base64") : null;
|
|
477
|
+
if (!data) throw new FabricDispatchError("E_INVALID_PARAMS", "artifact data is required");
|
|
478
|
+
const stored = this.artifacts.put(data, (params.kind as ArtifactRef["kind"]) ?? "input");
|
|
479
|
+
if (typeof params.sha256 === "string" && params.sha256 !== stored.sha256) {
|
|
480
|
+
throw new FabricDispatchError("E_ARTIFACT_CORRUPT", "pushed artifact does not match its sha256");
|
|
481
|
+
}
|
|
482
|
+
return { stored: true, sha256: stored.sha256, len: stored.len };
|
|
483
|
+
}
|
|
484
|
+
case "artifact.get": {
|
|
485
|
+
const sha256 = typeof params.sha256 === "string" ? params.sha256 : "";
|
|
486
|
+
if (!/^[0-9a-f]{64}$/.test(sha256)) {
|
|
487
|
+
throw new FabricDispatchError("E_INVALID_PARAMS", "bad sha256");
|
|
488
|
+
}
|
|
489
|
+
const data = this.artifacts.read({
|
|
490
|
+
sha256,
|
|
491
|
+
len: typeof params.len === "number" ? params.len : 0,
|
|
492
|
+
kind: (params.kind as ArtifactRef["kind"]) ?? "result",
|
|
493
|
+
});
|
|
494
|
+
return { sha256, len: data.length, data: data.toString("base64") };
|
|
495
|
+
}
|
|
496
|
+
case "task.submit":
|
|
497
|
+
return this.acceptTask(params, caller);
|
|
498
|
+
case "task.status": {
|
|
499
|
+
const taskId = typeof params.taskId === "string" ? params.taskId : "";
|
|
500
|
+
const record = this.inbound.get(taskId);
|
|
501
|
+
if (!record) return { state: "unknown" };
|
|
502
|
+
return {
|
|
503
|
+
state: record.state,
|
|
504
|
+
summary: record.summary,
|
|
505
|
+
files: record.files,
|
|
506
|
+
exitCode: record.exitCode,
|
|
507
|
+
error: record.error,
|
|
508
|
+
resultRef: record.resultRef,
|
|
509
|
+
diffRef: record.diffRef,
|
|
510
|
+
};
|
|
511
|
+
}
|
|
512
|
+
case "task.cancel": {
|
|
513
|
+
const taskId = typeof params.taskId === "string" ? params.taskId : "";
|
|
514
|
+
const controller = this.inflight.get(taskId);
|
|
515
|
+
if (controller) {
|
|
516
|
+
controller.abort();
|
|
517
|
+
this.inflight.delete(taskId);
|
|
518
|
+
}
|
|
519
|
+
const record = this.inbound.get(taskId);
|
|
520
|
+
if (record && record.state !== "done") {
|
|
521
|
+
this.inbound.update(taskId, { state: "cancelled" }, this.now());
|
|
522
|
+
}
|
|
523
|
+
return { cancelled: Boolean(controller) };
|
|
524
|
+
}
|
|
525
|
+
default:
|
|
526
|
+
throw new FabricDispatchError("E_PROTOCOL", `unknown fabric method: ${method}`);
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/** B 侧上报的能力标签(例如 gpu / build / long-running)。 */
|
|
531
|
+
labels: (() => string[]) | null = null;
|
|
532
|
+
|
|
533
|
+
private async acceptTask(
|
|
534
|
+
params: Record<string, unknown>,
|
|
535
|
+
caller: { nodeId: string; grants: FabricGrant },
|
|
536
|
+
): Promise<unknown> {
|
|
537
|
+
const taskId = typeof params.taskId === "string" ? params.taskId : "";
|
|
538
|
+
if (!/^[0-9a-f]{16}$/.test(taskId)) {
|
|
539
|
+
throw new FabricDispatchError("E_INVALID_PARAMS", "bad taskId");
|
|
540
|
+
}
|
|
541
|
+
const prompt = typeof params.prompt === "string" ? params.prompt : "";
|
|
542
|
+
if (!prompt.trim()) throw new FabricDispatchError("E_INVALID_PARAMS", "prompt is required");
|
|
543
|
+
const deadlineClass = params.deadlineClass;
|
|
544
|
+
if (
|
|
545
|
+
typeof deadlineClass !== "string" ||
|
|
546
|
+
!(deadlineClass in FABRIC_DEADLINE_MS)
|
|
547
|
+
) {
|
|
548
|
+
throw new FabricDispatchError("E_INVALID_PARAMS", "unknown deadlineClass");
|
|
549
|
+
}
|
|
550
|
+
const existing = this.inbound.get(taskId);
|
|
551
|
+
// 幂等:同一个 taskId 再来一次(对端重连重发)绝不能跑第二遍。
|
|
552
|
+
if (existing && existing.state !== "lost" && existing.state !== "failed") {
|
|
553
|
+
return { accepted: true, state: existing.state, idempotent: true };
|
|
554
|
+
}
|
|
555
|
+
const grant = caller.grants;
|
|
556
|
+
const tools = FABRIC_TOOLS_BY_GRANT[grant];
|
|
557
|
+
const inputRef = params.inputRef && typeof params.inputRef === "object" ? (params.inputRef as ArtifactRef) : null;
|
|
558
|
+
const record = this.inbound.create({
|
|
559
|
+
taskId,
|
|
560
|
+
peerId: caller.nodeId,
|
|
561
|
+
deadlineClass: deadlineClass as FabricDeadlineClass,
|
|
562
|
+
workspaceHint: typeof params.workspaceHint === "string" ? params.workspaceHint : "",
|
|
563
|
+
inputRef,
|
|
564
|
+
now: this.now(),
|
|
565
|
+
});
|
|
566
|
+
const runner = this.options.runner;
|
|
567
|
+
if (!runner) {
|
|
568
|
+
this.inbound.update(taskId, { state: "failed", error: "E_UNSUPPORTED: no remote runner" }, this.now());
|
|
569
|
+
throw new FabricDispatchError("E_UNSUPPORTED", "E_UNSUPPORTED: this host has no remote runner");
|
|
570
|
+
}
|
|
571
|
+
const controller = new AbortController();
|
|
572
|
+
this.inflight.set(taskId, controller);
|
|
573
|
+
this.inbound.update(taskId, { state: "running", pid: process.pid }, this.now());
|
|
574
|
+
void (async () => {
|
|
575
|
+
try {
|
|
576
|
+
const input = inputRef ? this.artifacts.read(inputRef) : null;
|
|
577
|
+
let lastProgressAt = 0;
|
|
578
|
+
let lastProgressText = "";
|
|
579
|
+
const onProgress = (note: FabricProgressNote) => {
|
|
580
|
+
const value = note.text.trim().slice(0, 200);
|
|
581
|
+
if (!value || value === lastProgressText) return;
|
|
582
|
+
const now = this.now();
|
|
583
|
+
// 节流 2 秒:进度是控制帧,不是日志流;两条之间太密只会挤占心跳。
|
|
584
|
+
if (lastProgressAt !== 0 && now - lastProgressAt < FABRIC_PROGRESS_THROTTLE_MS) return;
|
|
585
|
+
lastProgressAt = now;
|
|
586
|
+
lastProgressText = value;
|
|
587
|
+
this.inbound.update(
|
|
588
|
+
taskId,
|
|
589
|
+
{
|
|
590
|
+
progress: value,
|
|
591
|
+
progressCode: note.code,
|
|
592
|
+
progressParams: note.params ?? null,
|
|
593
|
+
progressAt: now,
|
|
594
|
+
},
|
|
595
|
+
now,
|
|
596
|
+
);
|
|
597
|
+
this.options.notify?.(record.peerId, {
|
|
598
|
+
type: "task_progress",
|
|
599
|
+
taskId,
|
|
600
|
+
text: value,
|
|
601
|
+
code: note.code,
|
|
602
|
+
...(note.params ? { params: note.params } : {}),
|
|
603
|
+
});
|
|
604
|
+
};
|
|
605
|
+
const result = await runner.run({
|
|
606
|
+
taskId,
|
|
607
|
+
prompt,
|
|
608
|
+
workspaceHint: record.workspaceHint,
|
|
609
|
+
grant,
|
|
610
|
+
tools,
|
|
611
|
+
input,
|
|
612
|
+
signal: controller.signal,
|
|
613
|
+
onProgress,
|
|
614
|
+
});
|
|
615
|
+
const resultRef = result.result ? this.artifacts.put(result.result, "result") : null;
|
|
616
|
+
const diffRef = result.diff ? this.artifacts.put(result.diff, "diff") : null;
|
|
617
|
+
this.inbound.update(
|
|
618
|
+
taskId,
|
|
619
|
+
{
|
|
620
|
+
state: "done",
|
|
621
|
+
summary: result.summary,
|
|
622
|
+
files: result.files ?? [],
|
|
623
|
+
exitCode: result.exitCode ?? 0,
|
|
624
|
+
resultRef,
|
|
625
|
+
diffRef,
|
|
626
|
+
},
|
|
627
|
+
this.now(),
|
|
628
|
+
);
|
|
629
|
+
this.options.notify?.(record.peerId, {
|
|
630
|
+
type: "task_done",
|
|
631
|
+
taskId,
|
|
632
|
+
summary: result.summary,
|
|
633
|
+
files: result.files ?? [],
|
|
634
|
+
exitCode: result.exitCode ?? 0,
|
|
635
|
+
resultRef,
|
|
636
|
+
diffRef,
|
|
637
|
+
});
|
|
638
|
+
} catch (error) {
|
|
639
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
640
|
+
this.inbound.update(
|
|
641
|
+
taskId,
|
|
642
|
+
{
|
|
643
|
+
state: controller.signal.aborted ? "cancelled" : "failed",
|
|
644
|
+
error: message,
|
|
645
|
+
},
|
|
646
|
+
this.now(),
|
|
647
|
+
);
|
|
648
|
+
this.options.notify?.(record.peerId, { type: "task_failed", taskId, error: message });
|
|
649
|
+
} finally {
|
|
650
|
+
this.inflight.delete(taskId);
|
|
651
|
+
}
|
|
652
|
+
})();
|
|
653
|
+
return { accepted: true, state: "running", grant, tools };
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
/**
|
|
657
|
+
* 为每台已配对机器维持一条常驻连接:配对即连、断线自动重连、取消配对才断。
|
|
658
|
+
* 这是「不手动取消就一直连着」的落点;返回本次新增/移除的 nodeId 便于记日志。
|
|
659
|
+
*/
|
|
660
|
+
keepAlive(peers = listPeers(this.options.agentDir)): { started: string[]; stopped: string[] } {
|
|
661
|
+
const wanted = new Set(peers.map((peer) => peer.nodeId));
|
|
662
|
+
const stopped: string[] = [];
|
|
663
|
+
for (const [nodeId, connection] of this.connections) {
|
|
664
|
+
if (wanted.has(nodeId)) continue;
|
|
665
|
+
connection.stop();
|
|
666
|
+
this.connections.delete(nodeId);
|
|
667
|
+
this.links.delete(nodeId);
|
|
668
|
+
stopped.push(nodeId);
|
|
669
|
+
}
|
|
670
|
+
const started: string[] = [];
|
|
671
|
+
for (const peer of peers) {
|
|
672
|
+
if (this.connections.has(peer.nodeId)) continue;
|
|
673
|
+
const connection = new FabricPeerConnection({
|
|
674
|
+
identity: this.options.identity,
|
|
675
|
+
peer: { nodeId: peer.nodeId, address: peer.address, port: peer.port },
|
|
676
|
+
appVersion: this.options.appVersion,
|
|
677
|
+
log: this.options.log,
|
|
678
|
+
});
|
|
679
|
+
// 对端推来的完成事件直接落台账:不用等下一次面板轮询。
|
|
680
|
+
connection.onEvent((frame) => {
|
|
681
|
+
void this.applyEvent(frame);
|
|
682
|
+
});
|
|
683
|
+
connection.start();
|
|
684
|
+
this.connections.set(peer.nodeId, connection);
|
|
685
|
+
started.push(peer.nodeId);
|
|
686
|
+
}
|
|
687
|
+
return { started, stopped };
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
/**
|
|
691
|
+
* 强制重建某台机器的连接。
|
|
692
|
+
*
|
|
693
|
+
* 配对状态变化时必须重建:配对前建立的连接是「受限会话」(只放行 pair.request),
|
|
694
|
+
* 它会一直连着,不重建就永远派不出活——这个 bug 只有真的跑一遍才看得出来。
|
|
695
|
+
*/
|
|
696
|
+
/**
|
|
697
|
+
* 按引用去对端拉一个产物。
|
|
698
|
+
*
|
|
699
|
+
* 为什么需要它:帧里只带 {sha256,len,kind} 引用(大帧会把心跳挤掉、逼对端误判离线),
|
|
700
|
+
* 而 ArtifactStore 是本机的——所以「对端任务回传的 patch」必须显式拉一次才落地。
|
|
701
|
+
* 少了这一步,发起方那边永远 diffFor()===null,看起来像对端没产出改动。
|
|
702
|
+
*/
|
|
703
|
+
async fetchArtifact(nodeId: string, ref: ArtifactRef): Promise<Buffer | null> {
|
|
704
|
+
const peer = listPeers(this.options.agentDir).find((item) => item.nodeId === nodeId);
|
|
705
|
+
if (!peer) return null;
|
|
706
|
+
const link = await this.linkFor(peer);
|
|
707
|
+
if (!link) return null;
|
|
708
|
+
try {
|
|
709
|
+
const reply = (await link.call("artifact.get", {
|
|
710
|
+
sha256: ref.sha256,
|
|
711
|
+
len: ref.len,
|
|
712
|
+
kind: ref.kind,
|
|
713
|
+
})) as Record<string, unknown>;
|
|
714
|
+
if (typeof reply?.data !== "string") return null;
|
|
715
|
+
const data = Buffer.from(reply.data, "base64");
|
|
716
|
+
if (data.length === 0) return null;
|
|
717
|
+
// 引用自称的 sha256 必须与内容对得上,否则等于接受对端塞来的任意字节。
|
|
718
|
+
const digest = createHash("sha256").update(data).digest("hex");
|
|
719
|
+
if (digest !== ref.sha256) {
|
|
720
|
+
this.options.log?.(`fabric artifact rejected: sha256 mismatch (${ref.sha256.slice(0, 12)})`);
|
|
721
|
+
return null;
|
|
722
|
+
}
|
|
723
|
+
this.artifacts.put(data, ref.kind);
|
|
724
|
+
return data;
|
|
725
|
+
} catch (error) {
|
|
726
|
+
this.options.log?.(
|
|
727
|
+
`fabric artifact.get failed (${nodeId}): ${error instanceof Error ? error.message : String(error)}`,
|
|
728
|
+
);
|
|
729
|
+
return null;
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
resetConnection(nodeId: string): void {
|
|
734
|
+
const connection = this.connections.get(nodeId);
|
|
735
|
+
if (connection) {
|
|
736
|
+
connection.stop();
|
|
737
|
+
this.connections.delete(nodeId);
|
|
738
|
+
this.links.delete(nodeId);
|
|
739
|
+
}
|
|
740
|
+
this.keepAlive();
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
/** 每台机器的连接状态,给面板与排障用。 */
|
|
744
|
+
connectionStates(): Record<string, FabricConnState> {
|
|
745
|
+
const states: Record<string, FabricConnState> = {};
|
|
746
|
+
for (const [nodeId, connection] of this.connections) states[nodeId] = connection.state;
|
|
747
|
+
return states;
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
/** 关掉所有链路(Host 退出时)。 */
|
|
751
|
+
close(): void {
|
|
752
|
+
for (const connection of this.connections.values()) connection.stop();
|
|
753
|
+
this.connections.clear();
|
|
754
|
+
for (const link of this.links.values()) link.close();
|
|
755
|
+
this.links.clear();
|
|
756
|
+
for (const controller of this.inflight.values()) controller.abort();
|
|
757
|
+
this.inflight.clear();
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
/** 供 UI 展示:已配对机器 + 当前推断的负载。 */
|
|
761
|
+
snapshot(): { peers: FabricPeer[]; loads: PeerLoad[]; tasks: TaskRecord[] } {
|
|
762
|
+
return {
|
|
763
|
+
peers: listPeers(this.options.agentDir),
|
|
764
|
+
loads: [...this.loads.values()],
|
|
765
|
+
tasks: this.outbound.list(),
|
|
766
|
+
};
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
|
|
770
|
+
/** 进度推送节流窗口:2 秒一条够看了,再密就是把控制帧当日志刷。 */
|
|
771
|
+
export const FABRIC_PROGRESS_THROTTLE_MS = 2_000;
|
|
772
|
+
|
|
773
|
+
export class FabricDispatchError extends Error {
|
|
774
|
+
code: string;
|
|
775
|
+
constructor(code: string, message: string) {
|
|
776
|
+
super(message);
|
|
777
|
+
this.name = "FabricDispatchError";
|
|
778
|
+
this.code = code;
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
export function grantToolList(grant: FabricGrant): readonly string[] {
|
|
783
|
+
return FABRIC_TOOLS_BY_GRANT[grant];
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
export function grantCovers(grant: FabricGrant, tool: string): boolean {
|
|
787
|
+
return grantAllows(grant, tool);
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
export function peerStorePathFor(agentDir: string): string {
|
|
791
|
+
return peersStorePath(agentDir);
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
export type { FabricFeature };
|