@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
package/dist/daemon.js
ADDED
|
@@ -0,0 +1,3797 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
3
|
+
var __esm = (fn, res, err) => function __init() {
|
|
4
|
+
if (err) throw err[0];
|
|
5
|
+
try {
|
|
6
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
7
|
+
} catch (e) {
|
|
8
|
+
throw err = [e], e;
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
var __export = (target, all) => {
|
|
12
|
+
for (var name in all)
|
|
13
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
// ../../contract/domains/fabric.ts
|
|
17
|
+
function checkProtocolVersion(raw) {
|
|
18
|
+
const version = typeof raw === "number" ? raw : Number.parseInt(String(raw ?? ""), 10);
|
|
19
|
+
if (!Number.isInteger(version) || version <= 0) {
|
|
20
|
+
return { ok: false, reason: `\u5BF9\u7AEF\u6CA1\u6709\u58F0\u660E\u534F\u8BAE\u7248\u672C\uFF08\u672C\u673A\u652F\u6301 v${FABRIC_PROTOCOL_MIN}~v${FABRIC_PROTOCOL_MAX}\uFF09` };
|
|
21
|
+
}
|
|
22
|
+
if (version < FABRIC_PROTOCOL_MIN) {
|
|
23
|
+
return { ok: false, reason: `\u5BF9\u7AEF\u534F\u8BAE v${version} \u592A\u65E7\uFF0C\u672C\u673A\u6700\u4F4E\u652F\u6301 v${FABRIC_PROTOCOL_MIN}\uFF0C\u8BF7\u5347\u7EA7\u5BF9\u7AEF` };
|
|
24
|
+
}
|
|
25
|
+
if (version > FABRIC_PROTOCOL_MAX) {
|
|
26
|
+
return { ok: false, reason: `\u5BF9\u7AEF\u534F\u8BAE v${version} \u6BD4\u672C\u673A\u65B0\uFF0C\u672C\u673A\u6700\u9AD8\u652F\u6301 v${FABRIC_PROTOCOL_MAX}\uFF0C\u8BF7\u5347\u7EA7\u672C\u673A` };
|
|
27
|
+
}
|
|
28
|
+
return { ok: true, version };
|
|
29
|
+
}
|
|
30
|
+
function progressNote(code, params, text) {
|
|
31
|
+
return params ? { code, params, text } : { code, text };
|
|
32
|
+
}
|
|
33
|
+
var FABRIC_CTX_MAX_CHARS, FABRIC_DEFAULT_PORT, FABRIC_PROTOCOL_VERSION, FABRIC_PROTOCOL_MIN, FABRIC_PROTOCOL_MAX, FABRIC_FEATURES, FABRIC_GRANTS, FABRIC_TOOLS_BY_GRANT, FABRIC_DEADLINE_MS;
|
|
34
|
+
var init_fabric = __esm({
|
|
35
|
+
"../../contract/domains/fabric.ts"() {
|
|
36
|
+
"use strict";
|
|
37
|
+
FABRIC_CTX_MAX_CHARS = 64;
|
|
38
|
+
FABRIC_DEFAULT_PORT = 7788;
|
|
39
|
+
FABRIC_PROTOCOL_VERSION = 1;
|
|
40
|
+
FABRIC_PROTOCOL_MIN = 1;
|
|
41
|
+
FABRIC_PROTOCOL_MAX = 1;
|
|
42
|
+
FABRIC_FEATURES = [
|
|
43
|
+
"fabric.pair.v1",
|
|
44
|
+
"fabric.task.v1",
|
|
45
|
+
"fabric.artifact.v1"
|
|
46
|
+
];
|
|
47
|
+
FABRIC_GRANTS = [
|
|
48
|
+
"read-only",
|
|
49
|
+
"workspace-rw",
|
|
50
|
+
"workspace-rw+bash"
|
|
51
|
+
];
|
|
52
|
+
FABRIC_TOOLS_BY_GRANT = {
|
|
53
|
+
"read-only": ["find", "grep", "ls", "read"],
|
|
54
|
+
"workspace-rw": ["edit", "find", "grep", "ls", "read", "write"],
|
|
55
|
+
"workspace-rw+bash": ["bash", "edit", "find", "grep", "ls", "read", "write"]
|
|
56
|
+
};
|
|
57
|
+
FABRIC_DEADLINE_MS = {
|
|
58
|
+
quick: 6e4,
|
|
59
|
+
build: 6e5,
|
|
60
|
+
long: 18e5
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
// ../../contract/protocol.ts
|
|
66
|
+
function negotiateCapabilities(remote, local) {
|
|
67
|
+
if (!Array.isArray(remote)) return [];
|
|
68
|
+
const theirs = /* @__PURE__ */ new Set();
|
|
69
|
+
for (const item of remote) {
|
|
70
|
+
if (typeof item === "string") theirs.add(item);
|
|
71
|
+
}
|
|
72
|
+
return local.filter((feature) => theirs.has(feature));
|
|
73
|
+
}
|
|
74
|
+
var MAX_FRAME_BYTES;
|
|
75
|
+
var init_protocol = __esm({
|
|
76
|
+
"../../contract/protocol.ts"() {
|
|
77
|
+
"use strict";
|
|
78
|
+
MAX_FRAME_BYTES = 8 * 1024 * 1024;
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
// src/pairing.ts
|
|
83
|
+
import {
|
|
84
|
+
createHash as createHash3,
|
|
85
|
+
createHmac,
|
|
86
|
+
createPrivateKey,
|
|
87
|
+
createPublicKey,
|
|
88
|
+
diffieHellman,
|
|
89
|
+
generateKeyPairSync,
|
|
90
|
+
hkdfSync,
|
|
91
|
+
randomBytes,
|
|
92
|
+
timingSafeEqual
|
|
93
|
+
} from "node:crypto";
|
|
94
|
+
import { chmodSync, existsSync as existsSync3, mkdirSync as mkdirSync4, readFileSync as readFileSync3, renameSync as renameSync3, writeFileSync as writeFileSync3 } from "node:fs";
|
|
95
|
+
import { dirname as dirname3, join as join3 } from "node:path";
|
|
96
|
+
function identityPath(agentDir) {
|
|
97
|
+
return join3(agentDir, "fabric", "identity.json");
|
|
98
|
+
}
|
|
99
|
+
function resolvePath(agentDir) {
|
|
100
|
+
return overridePath ?? identityPath(agentDir);
|
|
101
|
+
}
|
|
102
|
+
function isRecord2(value) {
|
|
103
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
104
|
+
}
|
|
105
|
+
function nodeIdOf(publicKeyBase64) {
|
|
106
|
+
return createHash3("sha256").update(Buffer.from(publicKeyBase64, "base64")).digest("hex").slice(0, NODE_ID_LEN);
|
|
107
|
+
}
|
|
108
|
+
function validateIdentity(raw) {
|
|
109
|
+
if (!isRecord2(raw)) throw new PairingError("E_INVALID_PARAMS", "identity must be an object");
|
|
110
|
+
const publicKey = typeof raw.publicKey === "string" ? raw.publicKey : "";
|
|
111
|
+
const privateKey = typeof raw.privateKey === "string" ? raw.privateKey : "";
|
|
112
|
+
if (!publicKey || !privateKey) {
|
|
113
|
+
throw new PairingError("E_INVALID_PARAMS", "identity is missing key material");
|
|
114
|
+
}
|
|
115
|
+
const derived = createPublicKey(
|
|
116
|
+
createPrivateKey({ key: Buffer.from(privateKey, "base64"), format: "der", type: "pkcs8" })
|
|
117
|
+
).export({ type: "spki", format: "der" }).toString("base64");
|
|
118
|
+
if (derived !== publicKey) {
|
|
119
|
+
throw new PairingError("E_INVALID_PARAMS", "identity key pair mismatch");
|
|
120
|
+
}
|
|
121
|
+
const nodeId = nodeIdOf(publicKey);
|
|
122
|
+
if (typeof raw.nodeId === "string" && raw.nodeId !== nodeId) {
|
|
123
|
+
throw new PairingError("E_INVALID_PARAMS", "identity nodeId does not match its public key");
|
|
124
|
+
}
|
|
125
|
+
return {
|
|
126
|
+
nodeId,
|
|
127
|
+
publicKey,
|
|
128
|
+
privateKey,
|
|
129
|
+
createdAt: typeof raw.createdAt === "number" ? raw.createdAt : Date.now()
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
function createIdentity(now = Date.now()) {
|
|
133
|
+
const { publicKey, privateKey } = generateKeyPairSync("x25519");
|
|
134
|
+
const publicDer = publicKey.export({ type: "spki", format: "der" }).toString("base64");
|
|
135
|
+
const privateDer = privateKey.export({ type: "pkcs8", format: "der" }).toString("base64");
|
|
136
|
+
return { nodeId: nodeIdOf(publicDer), publicKey: publicDer, privateKey: privateDer, createdAt: now };
|
|
137
|
+
}
|
|
138
|
+
function loadOrCreateIdentity(agentDir, now = Date.now()) {
|
|
139
|
+
const file = resolvePath(agentDir);
|
|
140
|
+
if (existsSync3(file)) {
|
|
141
|
+
try {
|
|
142
|
+
return validateIdentity(JSON.parse(readFileSync3(file, "utf8")));
|
|
143
|
+
} catch {
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
const identity = createIdentity(now);
|
|
147
|
+
mkdirSync4(dirname3(file), { recursive: true });
|
|
148
|
+
const temp = `${file}.tmp`;
|
|
149
|
+
writeFileSync3(temp, `${JSON.stringify(identity, null, 2)}
|
|
150
|
+
`, { encoding: "utf8", mode: 384 });
|
|
151
|
+
renameSync3(temp, file);
|
|
152
|
+
if (process.platform !== "win32") {
|
|
153
|
+
try {
|
|
154
|
+
chmodSync(file, 384);
|
|
155
|
+
} catch {
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return identity;
|
|
159
|
+
}
|
|
160
|
+
function deriveSharedSecret(identity, peerPublicKeyBase64) {
|
|
161
|
+
let secret;
|
|
162
|
+
try {
|
|
163
|
+
secret = diffieHellman({
|
|
164
|
+
privateKey: createPrivateKey({
|
|
165
|
+
key: Buffer.from(identity.privateKey, "base64"),
|
|
166
|
+
format: "der",
|
|
167
|
+
type: "pkcs8"
|
|
168
|
+
}),
|
|
169
|
+
publicKey: createPublicKey({
|
|
170
|
+
key: Buffer.from(peerPublicKeyBase64, "base64"),
|
|
171
|
+
format: "der",
|
|
172
|
+
type: "spki"
|
|
173
|
+
})
|
|
174
|
+
});
|
|
175
|
+
} catch {
|
|
176
|
+
throw new PairingError("E_INVALID_PARAMS", "peer public key is not a valid X25519 SPKI key");
|
|
177
|
+
}
|
|
178
|
+
if (secret.length !== 32 || secret.every((byte) => byte === 0)) {
|
|
179
|
+
throw new PairingError("E_INVALID_PARAMS", "peer public key produces a degenerate shared secret");
|
|
180
|
+
}
|
|
181
|
+
return secret;
|
|
182
|
+
}
|
|
183
|
+
function sortedPair(nodeIdA, nodeIdB) {
|
|
184
|
+
return nodeIdA <= nodeIdB ? [nodeIdA, nodeIdB] : [nodeIdB, nodeIdA];
|
|
185
|
+
}
|
|
186
|
+
function deriveSas(sharedSecret, nodeIdA, nodeIdB) {
|
|
187
|
+
const [lo, hi] = sortedPair(nodeIdA, nodeIdB);
|
|
188
|
+
const digest = createHash3("sha256").update(sharedSecret).update(lo).update(hi).digest();
|
|
189
|
+
const value = digest.readUInt32BE(0) % 1e6;
|
|
190
|
+
return String(value).padStart(6, "0");
|
|
191
|
+
}
|
|
192
|
+
function deriveSessionKeys(sharedSecret, nodeIdA, nodeIdB) {
|
|
193
|
+
const [lo, hi] = sortedPair(nodeIdA, nodeIdB);
|
|
194
|
+
const salt = Buffer.from(`${lo}:${hi}`, "utf8");
|
|
195
|
+
const aToB = Buffer.from(hkdfSync("sha256", sharedSecret, salt, Buffer.from("fabric/a2b", "utf8"), 32));
|
|
196
|
+
const bToA = Buffer.from(hkdfSync("sha256", sharedSecret, salt, Buffer.from("fabric/b2a", "utf8"), 32));
|
|
197
|
+
return { aToB, bToA };
|
|
198
|
+
}
|
|
199
|
+
function challengeMac(key, nonce, nodeId) {
|
|
200
|
+
return createHmac("sha256", key).update(nonce).update(nodeId).digest("hex");
|
|
201
|
+
}
|
|
202
|
+
function verifyChallengeMac(key, nonce, nodeId, mac) {
|
|
203
|
+
const expected = Buffer.from(challengeMac(key, nonce, nodeId), "hex");
|
|
204
|
+
const actual = Buffer.from(typeof mac === "string" ? mac : "", "hex");
|
|
205
|
+
if (actual.length !== expected.length) return false;
|
|
206
|
+
return timingSafeEqual(expected, actual);
|
|
207
|
+
}
|
|
208
|
+
var NODE_ID_LEN, PAIRING_WINDOW_MS, PAIRING_MAX_FAILURES, PAIRING_LOCKOUT_MS, PAIRING_STATE_TTL_MS, PairingError, overridePath, PairingSession, PairingGuard;
|
|
209
|
+
var init_pairing = __esm({
|
|
210
|
+
"src/pairing.ts"() {
|
|
211
|
+
"use strict";
|
|
212
|
+
NODE_ID_LEN = 16;
|
|
213
|
+
PAIRING_WINDOW_MS = 6e5;
|
|
214
|
+
PAIRING_MAX_FAILURES = 3;
|
|
215
|
+
PAIRING_LOCKOUT_MS = 5 * 6e4;
|
|
216
|
+
PAIRING_STATE_TTL_MS = 30 * 6e4;
|
|
217
|
+
PairingError = class extends Error {
|
|
218
|
+
constructor(code, message) {
|
|
219
|
+
super(message);
|
|
220
|
+
this.name = "PairingError";
|
|
221
|
+
this.code = code;
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
overridePath = null;
|
|
225
|
+
PairingSession = class {
|
|
226
|
+
constructor(identity, remoteNodeId, remotePublicKey, now = Date.now(), options = {}) {
|
|
227
|
+
this.failures = 0;
|
|
228
|
+
this.closed = false;
|
|
229
|
+
const window = options.windowMs ?? PAIRING_WINDOW_MS;
|
|
230
|
+
this.remoteNodeId = remoteNodeId;
|
|
231
|
+
this.remotePublicKey = remotePublicKey;
|
|
232
|
+
this.sharedSecret = deriveSharedSecret(identity, remotePublicKey);
|
|
233
|
+
this.sas = deriveSas(this.sharedSecret, identity.nodeId, remoteNodeId);
|
|
234
|
+
this.keys = deriveSessionKeys(this.sharedSecret, identity.nodeId, remoteNodeId);
|
|
235
|
+
this.expiresAt = now + window;
|
|
236
|
+
}
|
|
237
|
+
sessionKeys() {
|
|
238
|
+
return this.keys;
|
|
239
|
+
}
|
|
240
|
+
isExpired(now = Date.now()) {
|
|
241
|
+
return now > this.expiresAt;
|
|
242
|
+
}
|
|
243
|
+
/** 会话已被烧掉:确认成功、被拒绝、或失败次数用尽。 */
|
|
244
|
+
isClosed() {
|
|
245
|
+
return this.closed;
|
|
246
|
+
}
|
|
247
|
+
/** 用户点了「允许」并(可选)比对过 SAS。 */
|
|
248
|
+
confirm(input, now = Date.now()) {
|
|
249
|
+
if (this.closed) return { ok: false, code: "E_PAIR_WINDOW_CLOSED" };
|
|
250
|
+
if (this.isExpired(now)) return { ok: false, code: "E_PAIR_WINDOW_CLOSED" };
|
|
251
|
+
const expected = input.sas == null ? null : String(input.sas).replace(/\s+/g, "");
|
|
252
|
+
if (expected !== null && expected !== this.sas) {
|
|
253
|
+
this.failures += 1;
|
|
254
|
+
if (this.failures >= PAIRING_MAX_FAILURES) {
|
|
255
|
+
this.closed = true;
|
|
256
|
+
return { ok: false, code: "E_PAIR_LOCKED" };
|
|
257
|
+
}
|
|
258
|
+
return { ok: false, code: "E_PAIR_SAS_MISMATCH" };
|
|
259
|
+
}
|
|
260
|
+
this.closed = true;
|
|
261
|
+
return { ok: true, sharedSecret: this.sharedSecret, keys: this.keys };
|
|
262
|
+
}
|
|
263
|
+
reject() {
|
|
264
|
+
this.closed = true;
|
|
265
|
+
this.failures = 0;
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
PairingGuard = class {
|
|
269
|
+
constructor() {
|
|
270
|
+
this.state = /* @__PURE__ */ new Map();
|
|
271
|
+
}
|
|
272
|
+
lockedUntil(nodeId) {
|
|
273
|
+
return this.state.get(nodeId)?.lockedUntil ?? 0;
|
|
274
|
+
}
|
|
275
|
+
recordFailure(nodeId, now = Date.now()) {
|
|
276
|
+
const current = this.state.get(nodeId) ?? { failures: 0, lockedUntil: 0, updatedAt: now };
|
|
277
|
+
const failures = current.failures + 1;
|
|
278
|
+
this.state.set(nodeId, {
|
|
279
|
+
failures,
|
|
280
|
+
lockedUntil: failures >= PAIRING_MAX_FAILURES ? now + PAIRING_LOCKOUT_MS : 0,
|
|
281
|
+
updatedAt: now
|
|
282
|
+
});
|
|
283
|
+
this.prune(now);
|
|
284
|
+
}
|
|
285
|
+
reset(nodeId) {
|
|
286
|
+
this.state.delete(nodeId);
|
|
287
|
+
}
|
|
288
|
+
prune(now) {
|
|
289
|
+
for (const [nodeId, value] of this.state) {
|
|
290
|
+
if (now - value.updatedAt > PAIRING_STATE_TTL_MS && value.lockedUntil < now) {
|
|
291
|
+
this.state.delete(nodeId);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
});
|
|
298
|
+
|
|
299
|
+
// src/transport.ts
|
|
300
|
+
var transport_exports = {};
|
|
301
|
+
__export(transport_exports, {
|
|
302
|
+
FABRIC_CALL_TIMEOUT_MS: () => FABRIC_CALL_TIMEOUT_MS,
|
|
303
|
+
FABRIC_HELLO_TIMEOUT_MS: () => FABRIC_HELLO_TIMEOUT_MS,
|
|
304
|
+
FABRIC_MAX_FRAME_BYTES: () => FABRIC_MAX_FRAME_BYTES,
|
|
305
|
+
FABRIC_PAIR_METHOD: () => FABRIC_PAIR_METHOD,
|
|
306
|
+
FABRIC_RECONNECT_BASE_MS: () => FABRIC_RECONNECT_BASE_MS,
|
|
307
|
+
FABRIC_RECONNECT_MAX_MS: () => FABRIC_RECONNECT_MAX_MS,
|
|
308
|
+
FabricPeerConnection: () => FabricPeerConnection,
|
|
309
|
+
FabricTransportError: () => FabricTransportError,
|
|
310
|
+
acceptFabricLink: () => acceptFabricLink,
|
|
311
|
+
createChannel: () => createChannel,
|
|
312
|
+
dialFabricLink: () => dialFabricLink,
|
|
313
|
+
requestPairing: () => requestPairing
|
|
314
|
+
});
|
|
315
|
+
import { randomBytes as randomBytes2 } from "node:crypto";
|
|
316
|
+
import { connect as netConnect } from "node:net";
|
|
317
|
+
function isFrame(value) {
|
|
318
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
319
|
+
}
|
|
320
|
+
function createChannel(socket, onFrame, log, maxFrameBytes = FABRIC_MAX_FRAME_BYTES) {
|
|
321
|
+
let buffer = Buffer.alloc(0);
|
|
322
|
+
let closed = false;
|
|
323
|
+
const closeListeners = [];
|
|
324
|
+
const die = (reason) => {
|
|
325
|
+
if (closed) return;
|
|
326
|
+
closed = true;
|
|
327
|
+
socket.destroy();
|
|
328
|
+
for (const listener of closeListeners) listener(reason);
|
|
329
|
+
};
|
|
330
|
+
socket.on("data", (chunk) => {
|
|
331
|
+
if (closed) return;
|
|
332
|
+
buffer = buffer.length === 0 ? chunk : Buffer.concat([buffer, chunk]);
|
|
333
|
+
for (; ; ) {
|
|
334
|
+
const index = buffer.indexOf(10);
|
|
335
|
+
if (index < 0) {
|
|
336
|
+
if (buffer.length > maxFrameBytes) {
|
|
337
|
+
log?.("fabric frame too large, closing");
|
|
338
|
+
die("frame too large");
|
|
339
|
+
}
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
if (index > maxFrameBytes) {
|
|
343
|
+
die("frame too large");
|
|
344
|
+
return;
|
|
345
|
+
}
|
|
346
|
+
const line = buffer.subarray(0, index).toString("utf8");
|
|
347
|
+
buffer = buffer.subarray(index + 1);
|
|
348
|
+
if (!line.trim()) continue;
|
|
349
|
+
let parsed;
|
|
350
|
+
try {
|
|
351
|
+
parsed = JSON.parse(line);
|
|
352
|
+
} catch {
|
|
353
|
+
continue;
|
|
354
|
+
}
|
|
355
|
+
if (isFrame(parsed)) onFrame(parsed);
|
|
356
|
+
}
|
|
357
|
+
});
|
|
358
|
+
socket.on("close", () => die("socket closed"));
|
|
359
|
+
socket.on("error", (error) => die(error.message));
|
|
360
|
+
return {
|
|
361
|
+
write(frame) {
|
|
362
|
+
if (closed) return;
|
|
363
|
+
socket.write(`${JSON.stringify(frame)}
|
|
364
|
+
`);
|
|
365
|
+
},
|
|
366
|
+
close() {
|
|
367
|
+
die("closed locally");
|
|
368
|
+
},
|
|
369
|
+
onClose(callback) {
|
|
370
|
+
if (closed) {
|
|
371
|
+
callback("already closed");
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
closeListeners.push(callback);
|
|
375
|
+
}
|
|
376
|
+
};
|
|
377
|
+
}
|
|
378
|
+
function nonceOf(frame) {
|
|
379
|
+
const nonce = typeof frame.nonce === "string" ? Buffer.from(frame.nonce, "base64") : Buffer.alloc(0);
|
|
380
|
+
if (nonce.length !== 32) throw new FabricTransportError("E_PROTOCOL", "bad nonce");
|
|
381
|
+
return nonce;
|
|
382
|
+
}
|
|
383
|
+
function featuresOf(frame) {
|
|
384
|
+
return Array.isArray(frame.features) ? frame.features.filter((item) => typeof item === "string") : [];
|
|
385
|
+
}
|
|
386
|
+
async function acceptFabricLink(options) {
|
|
387
|
+
const caller = {
|
|
388
|
+
nodeId: "",
|
|
389
|
+
publicKey: "",
|
|
390
|
+
restricted: false,
|
|
391
|
+
address: options.socket.remoteAddress ?? "",
|
|
392
|
+
port: options.socket.remotePort ?? 0
|
|
393
|
+
};
|
|
394
|
+
const core = new LinkCore(
|
|
395
|
+
options.socket,
|
|
396
|
+
(method, params) => {
|
|
397
|
+
if (caller.restricted) {
|
|
398
|
+
if (method === "peer.status" && options.onRestrictedCall) {
|
|
399
|
+
return options.onRestrictedCall(method, params, caller);
|
|
400
|
+
}
|
|
401
|
+
if (method !== FABRIC_PAIR_METHOD) {
|
|
402
|
+
throw new FabricTransportError("E_UNAUTHORIZED", "only pair.request is allowed before pairing");
|
|
403
|
+
}
|
|
404
|
+
if (!options.onPairRequest) {
|
|
405
|
+
throw new FabricTransportError("E_UNAUTHORIZED", "pairing requests are disabled");
|
|
406
|
+
}
|
|
407
|
+
return options.onPairRequest({
|
|
408
|
+
nodeId: caller.nodeId,
|
|
409
|
+
publicKey: caller.publicKey,
|
|
410
|
+
name: typeof params.name === "string" ? params.name.slice(0, 60) : "",
|
|
411
|
+
address: caller.address,
|
|
412
|
+
port: caller.port,
|
|
413
|
+
claimedPort: typeof params.port === "number" && Number.isInteger(params.port) ? params.port : 0
|
|
414
|
+
});
|
|
415
|
+
}
|
|
416
|
+
return options.onCall(method, params, caller);
|
|
417
|
+
},
|
|
418
|
+
options.log
|
|
419
|
+
);
|
|
420
|
+
try {
|
|
421
|
+
const hello = await core.next((frame) => frame.type === "hello", FABRIC_HELLO_TIMEOUT_MS, "hello");
|
|
422
|
+
const remoteNodeId = typeof hello.nodeId === "string" ? hello.nodeId : "";
|
|
423
|
+
const remotePublicKey = typeof hello.publicKey === "string" ? hello.publicKey : "";
|
|
424
|
+
if (!/^[0-9a-f]{16}$/.test(remoteNodeId) || nodeIdOf(remotePublicKey) !== remoteNodeId) {
|
|
425
|
+
core.channel.write({ type: "hello_error", code: "E_PROTOCOL", message: "nodeId does not match public key" });
|
|
426
|
+
core.channel.close();
|
|
427
|
+
throw new FabricTransportError("E_PROTOCOL", "nodeId does not match public key");
|
|
428
|
+
}
|
|
429
|
+
const protocol = checkProtocolVersion(hello.protocolVersion);
|
|
430
|
+
if (!protocol.ok) {
|
|
431
|
+
core.channel.write({ type: "hello_error", code: "E_PROTOCOL_VERSION", message: protocol.reason });
|
|
432
|
+
core.channel.close();
|
|
433
|
+
throw new FabricTransportError("E_PROTOCOL_VERSION", protocol.reason);
|
|
434
|
+
}
|
|
435
|
+
const paired = options.isPaired(remoteNodeId);
|
|
436
|
+
if (!paired && !options.onPairRequest) {
|
|
437
|
+
core.channel.write({ type: "hello_error", code: "E_PEER_UNKNOWN", message: "peer is not paired" });
|
|
438
|
+
core.channel.close();
|
|
439
|
+
throw new FabricTransportError("E_PEER_UNKNOWN", "peer is not paired");
|
|
440
|
+
}
|
|
441
|
+
const clientNonce = nonceOf(hello);
|
|
442
|
+
const secret = deriveSharedSecret(options.identity, remotePublicKey);
|
|
443
|
+
const keys = deriveSessionKeys(secret, remoteNodeId, options.identity.nodeId);
|
|
444
|
+
const serverNonce = randomBytes2(32);
|
|
445
|
+
core.channel.write({
|
|
446
|
+
type: "hello_ok",
|
|
447
|
+
nodeId: options.identity.nodeId,
|
|
448
|
+
publicKey: options.identity.publicKey,
|
|
449
|
+
nonce: serverNonce.toString("base64"),
|
|
450
|
+
mac: challengeMac(keys.bToA, clientNonce, options.identity.nodeId),
|
|
451
|
+
protocolVersion: FABRIC_PROTOCOL_VERSION,
|
|
452
|
+
appVersion: options.appVersion ?? "",
|
|
453
|
+
features: FABRIC_FEATURES
|
|
454
|
+
});
|
|
455
|
+
const auth = await core.next((frame) => frame.type === "auth", FABRIC_HELLO_TIMEOUT_MS, "auth");
|
|
456
|
+
const mac = typeof auth.mac === "string" ? auth.mac : "";
|
|
457
|
+
if (!verifyChallengeMac(keys.aToB, serverNonce, remoteNodeId, mac)) {
|
|
458
|
+
core.channel.write({ type: "hello_error", code: "E_UNAUTHORIZED", message: "bad challenge response" });
|
|
459
|
+
core.channel.close();
|
|
460
|
+
throw new FabricTransportError("E_UNAUTHORIZED", "bad challenge response");
|
|
461
|
+
}
|
|
462
|
+
caller.nodeId = remoteNodeId;
|
|
463
|
+
caller.publicKey = remotePublicKey;
|
|
464
|
+
caller.restricted = !paired;
|
|
465
|
+
core.nodeId = remoteNodeId;
|
|
466
|
+
core.features = negotiateCapabilities(featuresOf(hello), FABRIC_FEATURES);
|
|
467
|
+
core.appVersion = typeof hello.appVersion === "string" ? hello.appVersion : "";
|
|
468
|
+
core.channel.write({ type: "auth_ok", features: core.features });
|
|
469
|
+
return core.link();
|
|
470
|
+
} catch (error) {
|
|
471
|
+
core.channel.close();
|
|
472
|
+
throw error;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
async function dialFabricLink(options) {
|
|
476
|
+
const timeoutMs = options.timeoutMs ?? FABRIC_HELLO_TIMEOUT_MS;
|
|
477
|
+
const socket = netConnect({ host: options.peer.address, port: options.peer.port });
|
|
478
|
+
const core = new LinkCore(socket, async () => {
|
|
479
|
+
throw new FabricTransportError("E_UNSUPPORTED", "this side does not accept inbound calls");
|
|
480
|
+
}, options.log);
|
|
481
|
+
await new Promise((resolve2, reject) => {
|
|
482
|
+
const timer = setTimeout(() => {
|
|
483
|
+
socket.destroy();
|
|
484
|
+
reject(new FabricTransportError("E_PEER_OFFLINE", "connect timeout"));
|
|
485
|
+
}, timeoutMs);
|
|
486
|
+
timer.unref?.();
|
|
487
|
+
socket.once("connect", () => {
|
|
488
|
+
clearTimeout(timer);
|
|
489
|
+
resolve2();
|
|
490
|
+
});
|
|
491
|
+
socket.once("error", (error) => {
|
|
492
|
+
clearTimeout(timer);
|
|
493
|
+
reject(new FabricTransportError("E_PEER_OFFLINE", error.message));
|
|
494
|
+
});
|
|
495
|
+
});
|
|
496
|
+
try {
|
|
497
|
+
const clientNonce = randomBytes2(32);
|
|
498
|
+
core.channel.write({
|
|
499
|
+
type: "hello",
|
|
500
|
+
nodeId: options.identity.nodeId,
|
|
501
|
+
publicKey: options.identity.publicKey,
|
|
502
|
+
nonce: clientNonce.toString("base64"),
|
|
503
|
+
protocolVersion: FABRIC_PROTOCOL_VERSION,
|
|
504
|
+
appVersion: options.appVersion ?? "",
|
|
505
|
+
features: FABRIC_FEATURES
|
|
506
|
+
});
|
|
507
|
+
const reply = await core.next(
|
|
508
|
+
(frame) => frame.type === "hello_ok" || frame.type === "hello_error",
|
|
509
|
+
timeoutMs,
|
|
510
|
+
"hello_ok"
|
|
511
|
+
);
|
|
512
|
+
if (reply.type === "hello_error") {
|
|
513
|
+
throw new FabricTransportError(
|
|
514
|
+
typeof reply.code === "string" ? reply.code : "E_PROTOCOL",
|
|
515
|
+
typeof reply.message === "string" ? reply.message : "handshake rejected"
|
|
516
|
+
);
|
|
517
|
+
}
|
|
518
|
+
const serverNodeId = typeof reply.nodeId === "string" ? reply.nodeId : "";
|
|
519
|
+
const serverPublicKey = typeof reply.publicKey === "string" ? reply.publicKey : "";
|
|
520
|
+
if (nodeIdOf(serverPublicKey) !== serverNodeId) {
|
|
521
|
+
throw new FabricTransportError("E_PEER_MISMATCH", "server public key does not match its nodeId");
|
|
522
|
+
}
|
|
523
|
+
if (options.peer.nodeId && serverNodeId !== options.peer.nodeId) {
|
|
524
|
+
throw new FabricTransportError("E_PEER_MISMATCH", "server identity does not match the paired peer");
|
|
525
|
+
}
|
|
526
|
+
const protocol = checkProtocolVersion(reply.protocolVersion);
|
|
527
|
+
if (!protocol.ok) {
|
|
528
|
+
throw new FabricTransportError("E_PROTOCOL_VERSION", protocol.reason);
|
|
529
|
+
}
|
|
530
|
+
const serverNonce = nonceOf(reply);
|
|
531
|
+
const secret = deriveSharedSecret(options.identity, serverPublicKey);
|
|
532
|
+
const keys = deriveSessionKeys(secret, options.identity.nodeId, serverNodeId);
|
|
533
|
+
const mac = typeof reply.mac === "string" ? reply.mac : "";
|
|
534
|
+
if (!verifyChallengeMac(keys.bToA, clientNonce, serverNodeId, mac)) {
|
|
535
|
+
throw new FabricTransportError("E_PEER_MISMATCH", "server failed the challenge");
|
|
536
|
+
}
|
|
537
|
+
core.channel.write({ type: "auth", mac: challengeMac(keys.aToB, serverNonce, options.identity.nodeId) });
|
|
538
|
+
const ok = await core.next((frame) => frame.type === "auth_ok", timeoutMs, "auth_ok");
|
|
539
|
+
core.nodeId = serverNodeId;
|
|
540
|
+
core.features = negotiateCapabilities(featuresOf(ok), FABRIC_FEATURES);
|
|
541
|
+
core.appVersion = typeof reply.appVersion === "string" ? reply.appVersion : "";
|
|
542
|
+
return core.link();
|
|
543
|
+
} catch (error) {
|
|
544
|
+
core.channel.close();
|
|
545
|
+
throw error;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
async function requestPairing(options) {
|
|
549
|
+
const link = await dialFabricLink({
|
|
550
|
+
identity: options.identity,
|
|
551
|
+
peer: { address: options.address, port: options.port },
|
|
552
|
+
timeoutMs: options.timeoutMs,
|
|
553
|
+
log: options.log
|
|
554
|
+
});
|
|
555
|
+
try {
|
|
556
|
+
const reply = await link.call(FABRIC_PAIR_METHOD, {
|
|
557
|
+
name: options.name,
|
|
558
|
+
port: options.listenPort
|
|
559
|
+
});
|
|
560
|
+
return {
|
|
561
|
+
nodeId: link.nodeId,
|
|
562
|
+
publicKey: reply.publicKey && typeof reply.publicKey === "string" ? reply.publicKey : "",
|
|
563
|
+
accepted: reply.pending === true
|
|
564
|
+
};
|
|
565
|
+
} finally {
|
|
566
|
+
link.close();
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
var FABRIC_HELLO_TIMEOUT_MS, FABRIC_MAX_FRAME_BYTES, FABRIC_CALL_TIMEOUT_MS, FABRIC_RECONNECT_BASE_MS, FABRIC_RECONNECT_MAX_MS, FabricTransportError, LinkCore, FABRIC_PAIR_METHOD, FabricPeerConnection;
|
|
570
|
+
var init_transport = __esm({
|
|
571
|
+
"src/transport.ts"() {
|
|
572
|
+
"use strict";
|
|
573
|
+
init_fabric();
|
|
574
|
+
init_protocol();
|
|
575
|
+
init_pairing();
|
|
576
|
+
FABRIC_HELLO_TIMEOUT_MS = 5e3;
|
|
577
|
+
FABRIC_MAX_FRAME_BYTES = 8 * 1024 * 1024;
|
|
578
|
+
FABRIC_CALL_TIMEOUT_MS = 3e4;
|
|
579
|
+
FABRIC_RECONNECT_BASE_MS = 500;
|
|
580
|
+
FABRIC_RECONNECT_MAX_MS = 1e4;
|
|
581
|
+
FabricTransportError = class extends Error {
|
|
582
|
+
constructor(code, message) {
|
|
583
|
+
super(message);
|
|
584
|
+
this.name = "FabricTransportError";
|
|
585
|
+
this.code = code;
|
|
586
|
+
}
|
|
587
|
+
};
|
|
588
|
+
LinkCore = class {
|
|
589
|
+
// 注意:不用参数属性(constructor(private x))——node 的类型擦除模式不支持。
|
|
590
|
+
constructor(socket, onInboundCall, log) {
|
|
591
|
+
this.pending = /* @__PURE__ */ new Map();
|
|
592
|
+
this.inbox = [];
|
|
593
|
+
this.waiters = [];
|
|
594
|
+
this.closeHandlers = [];
|
|
595
|
+
this.seq = 0;
|
|
596
|
+
this.eventHandlers = /* @__PURE__ */ new Set();
|
|
597
|
+
this.closed = false;
|
|
598
|
+
this.nodeId = "";
|
|
599
|
+
this.features = [];
|
|
600
|
+
this.appVersion = "";
|
|
601
|
+
this.onInboundCall = onInboundCall;
|
|
602
|
+
this.channel = createChannel(socket, (frame) => void this.dispatch(frame), log);
|
|
603
|
+
this.channel.onClose((reason) => {
|
|
604
|
+
this.closed = true;
|
|
605
|
+
for (const [, waiter] of this.pending) {
|
|
606
|
+
clearTimeout(waiter.timer);
|
|
607
|
+
waiter.reject(new FabricTransportError("E_PEER_OFFLINE", `link lost: ${reason}`));
|
|
608
|
+
}
|
|
609
|
+
this.pending.clear();
|
|
610
|
+
for (const handler of this.closeHandlers) handler(reason);
|
|
611
|
+
});
|
|
612
|
+
}
|
|
613
|
+
onClose(callback) {
|
|
614
|
+
this.closeHandlers.push(callback);
|
|
615
|
+
}
|
|
616
|
+
async dispatch(frame) {
|
|
617
|
+
if (frame.type === "call_result") {
|
|
618
|
+
const id = typeof frame.id === "string" ? frame.id : "";
|
|
619
|
+
const waiter2 = this.pending.get(id);
|
|
620
|
+
if (!waiter2) return;
|
|
621
|
+
this.pending.delete(id);
|
|
622
|
+
clearTimeout(waiter2.timer);
|
|
623
|
+
if (frame.ok === true) {
|
|
624
|
+
waiter2.resolve(frame.result ?? null);
|
|
625
|
+
} else {
|
|
626
|
+
const error = isFrame(frame.error) ? frame.error : {};
|
|
627
|
+
waiter2.reject(
|
|
628
|
+
new FabricTransportError(
|
|
629
|
+
typeof error.code === "string" ? error.code : "E_CALL_FAILED",
|
|
630
|
+
typeof error.message === "string" ? error.message : "call failed"
|
|
631
|
+
)
|
|
632
|
+
);
|
|
633
|
+
}
|
|
634
|
+
return;
|
|
635
|
+
}
|
|
636
|
+
if (frame.type === "call") {
|
|
637
|
+
const id = typeof frame.id === "string" ? frame.id : "";
|
|
638
|
+
const method = typeof frame.method === "string" ? frame.method : "";
|
|
639
|
+
const params = isFrame(frame.params) ? frame.params : {};
|
|
640
|
+
try {
|
|
641
|
+
const result = await this.onInboundCall(method, params);
|
|
642
|
+
this.channel.write({ type: "call_result", id, ok: true, result: result ?? null });
|
|
643
|
+
} catch (error) {
|
|
644
|
+
this.channel.write({
|
|
645
|
+
type: "call_result",
|
|
646
|
+
id,
|
|
647
|
+
ok: false,
|
|
648
|
+
error: {
|
|
649
|
+
code: error instanceof FabricTransportError ? error.code : "E_CALL_FAILED",
|
|
650
|
+
message: error instanceof Error ? error.message : String(error)
|
|
651
|
+
}
|
|
652
|
+
});
|
|
653
|
+
}
|
|
654
|
+
return;
|
|
655
|
+
}
|
|
656
|
+
if (frame.type === "ping") {
|
|
657
|
+
this.channel.write({ type: "pong", nonce: frame.nonce });
|
|
658
|
+
return;
|
|
659
|
+
}
|
|
660
|
+
if (frame.type === "event") {
|
|
661
|
+
const payload = isFrame(frame.event) ? frame.event : frame;
|
|
662
|
+
for (const handler of this.eventHandlers) handler(payload);
|
|
663
|
+
return;
|
|
664
|
+
}
|
|
665
|
+
const waiter = this.waiters.shift();
|
|
666
|
+
if (waiter) {
|
|
667
|
+
waiter(frame);
|
|
668
|
+
return;
|
|
669
|
+
}
|
|
670
|
+
this.inbox.push(frame);
|
|
671
|
+
}
|
|
672
|
+
next(predicate, timeoutMs, label) {
|
|
673
|
+
for (let index = 0; index < this.inbox.length; index += 1) {
|
|
674
|
+
if (predicate(this.inbox[index])) return Promise.resolve(this.inbox.splice(index, 1)[0]);
|
|
675
|
+
}
|
|
676
|
+
return new Promise((resolve2, reject) => {
|
|
677
|
+
const timer = setTimeout(() => {
|
|
678
|
+
const position = this.waiters.indexOf(waiter);
|
|
679
|
+
if (position >= 0) this.waiters.splice(position, 1);
|
|
680
|
+
reject(new FabricTransportError("E_HELLO_TIMEOUT", `timed out waiting for ${label}`));
|
|
681
|
+
}, timeoutMs);
|
|
682
|
+
timer.unref?.();
|
|
683
|
+
const waiter = (frame) => {
|
|
684
|
+
if (!predicate(frame)) {
|
|
685
|
+
this.inbox.push(frame);
|
|
686
|
+
this.waiters.push(waiter);
|
|
687
|
+
return;
|
|
688
|
+
}
|
|
689
|
+
clearTimeout(timer);
|
|
690
|
+
resolve2(frame);
|
|
691
|
+
};
|
|
692
|
+
this.waiters.push(waiter);
|
|
693
|
+
});
|
|
694
|
+
}
|
|
695
|
+
call(method, params, timeoutMs) {
|
|
696
|
+
if (this.closed) {
|
|
697
|
+
return Promise.reject(new FabricTransportError("E_PEER_OFFLINE", "link closed"));
|
|
698
|
+
}
|
|
699
|
+
this.seq += 1;
|
|
700
|
+
const id = String(this.seq);
|
|
701
|
+
return new Promise((resolve2, reject) => {
|
|
702
|
+
const timer = setTimeout(() => {
|
|
703
|
+
this.pending.delete(id);
|
|
704
|
+
reject(new FabricTransportError("E_CALL_TIMEOUT", `call ${method} timed out`));
|
|
705
|
+
}, timeoutMs);
|
|
706
|
+
timer.unref?.();
|
|
707
|
+
this.pending.set(id, { resolve: resolve2, reject, timer });
|
|
708
|
+
this.channel.write({ type: "call", id, method, params });
|
|
709
|
+
});
|
|
710
|
+
}
|
|
711
|
+
link() {
|
|
712
|
+
const self = this;
|
|
713
|
+
return {
|
|
714
|
+
get nodeId() {
|
|
715
|
+
return self.nodeId;
|
|
716
|
+
},
|
|
717
|
+
get features() {
|
|
718
|
+
return self.features;
|
|
719
|
+
},
|
|
720
|
+
get appVersion() {
|
|
721
|
+
return self.appVersion;
|
|
722
|
+
},
|
|
723
|
+
get connected() {
|
|
724
|
+
return !self.closed;
|
|
725
|
+
},
|
|
726
|
+
call: (method, params = {}) => self.call(method, params, FABRIC_CALL_TIMEOUT_MS),
|
|
727
|
+
send: (frame) => self.channel.write(frame),
|
|
728
|
+
onEvent: (handler) => {
|
|
729
|
+
self.eventHandlers.add(handler);
|
|
730
|
+
return () => self.eventHandlers.delete(handler);
|
|
731
|
+
},
|
|
732
|
+
close: () => self.channel.close()
|
|
733
|
+
};
|
|
734
|
+
}
|
|
735
|
+
};
|
|
736
|
+
FABRIC_PAIR_METHOD = "pair.request";
|
|
737
|
+
FabricPeerConnection = class {
|
|
738
|
+
constructor(options) {
|
|
739
|
+
this.state = "idle";
|
|
740
|
+
this.link = null;
|
|
741
|
+
this.stopped = true;
|
|
742
|
+
this.timer = null;
|
|
743
|
+
this.attempts = 0;
|
|
744
|
+
this.generation = 0;
|
|
745
|
+
this.listeners = /* @__PURE__ */ new Set();
|
|
746
|
+
this.eventListeners = /* @__PURE__ */ new Set();
|
|
747
|
+
this.unsubscribeEvents = null;
|
|
748
|
+
this.options = options;
|
|
749
|
+
}
|
|
750
|
+
onStateChange(listener) {
|
|
751
|
+
this.listeners.add(listener);
|
|
752
|
+
return () => this.listeners.delete(listener);
|
|
753
|
+
}
|
|
754
|
+
/** 订阅对端推来的事件:重连之后自动重新订阅(否则第一次断线就永久收不到通知)。 */
|
|
755
|
+
onEvent(listener) {
|
|
756
|
+
this.eventListeners.add(listener);
|
|
757
|
+
return () => this.eventListeners.delete(listener);
|
|
758
|
+
}
|
|
759
|
+
setState(state) {
|
|
760
|
+
if (this.state === state) return;
|
|
761
|
+
this.state = state;
|
|
762
|
+
for (const listener of this.listeners) listener(state);
|
|
763
|
+
}
|
|
764
|
+
start() {
|
|
765
|
+
if (!this.stopped) return;
|
|
766
|
+
this.stopped = false;
|
|
767
|
+
this.attempts = 0;
|
|
768
|
+
void this.connect();
|
|
769
|
+
}
|
|
770
|
+
stop() {
|
|
771
|
+
this.stopped = true;
|
|
772
|
+
this.setState("manual-off");
|
|
773
|
+
if (this.timer) {
|
|
774
|
+
clearTimeout(this.timer);
|
|
775
|
+
this.timer = null;
|
|
776
|
+
}
|
|
777
|
+
this.link?.close();
|
|
778
|
+
this.link = null;
|
|
779
|
+
}
|
|
780
|
+
current() {
|
|
781
|
+
return this.link && this.link.connected ? this.link : null;
|
|
782
|
+
}
|
|
783
|
+
async call(method, params = {}) {
|
|
784
|
+
const link = this.current();
|
|
785
|
+
if (!link) throw new FabricTransportError("E_PEER_OFFLINE", "peer is not connected");
|
|
786
|
+
return link.call(method, params);
|
|
787
|
+
}
|
|
788
|
+
async connect() {
|
|
789
|
+
if (this.stopped) return;
|
|
790
|
+
const generation = ++this.generation;
|
|
791
|
+
try {
|
|
792
|
+
const link = await dialFabricLink({
|
|
793
|
+
identity: this.options.identity,
|
|
794
|
+
peer: this.options.peer,
|
|
795
|
+
appVersion: this.options.appVersion,
|
|
796
|
+
log: this.options.log
|
|
797
|
+
});
|
|
798
|
+
if (this.stopped || generation !== this.generation) {
|
|
799
|
+
link.close();
|
|
800
|
+
return;
|
|
801
|
+
}
|
|
802
|
+
this.link = link;
|
|
803
|
+
this.attempts = 0;
|
|
804
|
+
this.setState("online");
|
|
805
|
+
this.unsubscribeEvents?.();
|
|
806
|
+
this.unsubscribeEvents = link.onEvent((frame) => {
|
|
807
|
+
for (const listener of this.eventListeners) listener(frame);
|
|
808
|
+
});
|
|
809
|
+
this.options.log?.(`fabric link up: ${this.options.peer.nodeId}`);
|
|
810
|
+
const check = setInterval(() => {
|
|
811
|
+
if (!link.connected) {
|
|
812
|
+
clearInterval(check);
|
|
813
|
+
if (this.link === link) this.link = null;
|
|
814
|
+
if (!this.stopped) this.schedule();
|
|
815
|
+
}
|
|
816
|
+
}, 500);
|
|
817
|
+
check.unref?.();
|
|
818
|
+
} catch (error) {
|
|
819
|
+
this.options.log?.(
|
|
820
|
+
`fabric link failed: ${error instanceof Error ? error.message : String(error)}`
|
|
821
|
+
);
|
|
822
|
+
if (!this.stopped && generation === this.generation) this.schedule();
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
schedule() {
|
|
826
|
+
if (this.stopped || this.timer) return;
|
|
827
|
+
this.setState("reconnecting");
|
|
828
|
+
const base = this.options.baseMs ?? FABRIC_RECONNECT_BASE_MS;
|
|
829
|
+
const max = this.options.maxMs ?? FABRIC_RECONNECT_MAX_MS;
|
|
830
|
+
const delay = Math.min(max, base * 2 ** this.attempts);
|
|
831
|
+
this.attempts += 1;
|
|
832
|
+
this.timer = setTimeout(() => {
|
|
833
|
+
this.timer = null;
|
|
834
|
+
void this.connect();
|
|
835
|
+
}, delay);
|
|
836
|
+
this.timer.unref?.();
|
|
837
|
+
}
|
|
838
|
+
};
|
|
839
|
+
}
|
|
840
|
+
});
|
|
841
|
+
|
|
842
|
+
// src/daemon.ts
|
|
843
|
+
import { createHash as createHash6 } from "node:crypto";
|
|
844
|
+
import { existsSync as existsSync7, readFileSync as readFileSync6, rmSync as rmSync6 } from "node:fs";
|
|
845
|
+
import { connect as netConnect2, createServer as createServer2 } from "node:net";
|
|
846
|
+
import { homedir } from "node:os";
|
|
847
|
+
import path2 from "node:path";
|
|
848
|
+
import process2 from "node:process";
|
|
849
|
+
|
|
850
|
+
// src/daemon-runner.ts
|
|
851
|
+
init_fabric();
|
|
852
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
853
|
+
import { appendFileSync, mkdirSync, rmSync } from "node:fs";
|
|
854
|
+
import path from "node:path";
|
|
855
|
+
var DEFAULT_TASK_TIMEOUT_MS = 30 * 60 * 1e3;
|
|
856
|
+
var DEFAULT_MAX_OUTPUT_BYTES = 4 * 1024 * 1024;
|
|
857
|
+
function quotePrompt(text, platform = process.platform) {
|
|
858
|
+
if (platform === "win32") return `"${text.replace(/"/g, '\\"')}"`;
|
|
859
|
+
return `'${text.replace(/'/g, "'\\''")}'`;
|
|
860
|
+
}
|
|
861
|
+
function buildCommand(template, prompt, platform = process.platform) {
|
|
862
|
+
const quoted = quotePrompt(prompt, platform);
|
|
863
|
+
return template.includes("{prompt}") ? template.split("{prompt}").join(quoted) : `${template} ${quoted}`;
|
|
864
|
+
}
|
|
865
|
+
function runShell(command, cwd, timeoutMs, maxBytes) {
|
|
866
|
+
return new Promise((resolve2) => {
|
|
867
|
+
const child = spawn(command, {
|
|
868
|
+
cwd,
|
|
869
|
+
shell: true,
|
|
870
|
+
windowsHide: true,
|
|
871
|
+
env: { ...process.env, FABRIC_WORKDIR: cwd },
|
|
872
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
873
|
+
});
|
|
874
|
+
let stdout = "";
|
|
875
|
+
let stderr = "";
|
|
876
|
+
let timedOut = false;
|
|
877
|
+
const cap = (current, chunk) => current.length >= maxBytes ? current : current + chunk.toString("utf8").slice(0, maxBytes - current.length);
|
|
878
|
+
child.stdout.on("data", (chunk) => {
|
|
879
|
+
stdout = cap(stdout, chunk);
|
|
880
|
+
});
|
|
881
|
+
child.stderr.on("data", (chunk) => {
|
|
882
|
+
stderr = cap(stderr, chunk);
|
|
883
|
+
});
|
|
884
|
+
const timer = setTimeout(() => {
|
|
885
|
+
timedOut = true;
|
|
886
|
+
if (process.platform === "win32" && child.pid) {
|
|
887
|
+
spawnSync("taskkill", ["/T", "/F", "/PID", String(child.pid)], { windowsHide: true });
|
|
888
|
+
} else {
|
|
889
|
+
child.kill("SIGKILL");
|
|
890
|
+
}
|
|
891
|
+
}, Math.max(1e3, timeoutMs));
|
|
892
|
+
child.on("error", (error) => {
|
|
893
|
+
clearTimeout(timer);
|
|
894
|
+
resolve2({ code: 1, stdout, stderr: `${stderr}
|
|
895
|
+
${error.message}`, timedOut });
|
|
896
|
+
});
|
|
897
|
+
child.on("close", (code) => {
|
|
898
|
+
clearTimeout(timer);
|
|
899
|
+
resolve2({ code, stdout, stderr, timedOut });
|
|
900
|
+
});
|
|
901
|
+
});
|
|
902
|
+
}
|
|
903
|
+
function git(args, cwd) {
|
|
904
|
+
const result = spawnSync("git", args, { cwd, encoding: "utf8", windowsHide: true });
|
|
905
|
+
return {
|
|
906
|
+
ok: result.status === 0,
|
|
907
|
+
stdout: result.stdout ?? "",
|
|
908
|
+
stderr: result.stderr ?? result.error?.message ?? ""
|
|
909
|
+
};
|
|
910
|
+
}
|
|
911
|
+
function prepareWorkspace(options, taskId) {
|
|
912
|
+
const repo = options.repo?.trim();
|
|
913
|
+
if (!repo) {
|
|
914
|
+
const cwd2 = path.join(options.agentDir, "fabric", "scratch", taskId);
|
|
915
|
+
mkdirSync(cwd2, { recursive: true });
|
|
916
|
+
return {
|
|
917
|
+
cwd: cwd2,
|
|
918
|
+
cleanup: async () => {
|
|
919
|
+
rmSync(cwd2, { recursive: true, force: true });
|
|
920
|
+
}
|
|
921
|
+
};
|
|
922
|
+
}
|
|
923
|
+
const cwd = path.join(options.agentDir, "fabric", "worktrees", taskId);
|
|
924
|
+
mkdirSync(path.dirname(cwd), { recursive: true });
|
|
925
|
+
const added = git(["worktree", "add", "--detach", cwd, "HEAD"], repo);
|
|
926
|
+
if (!added.ok) {
|
|
927
|
+
throw new Error(`E_WORKSPACE: git worktree add failed: ${added.stderr.trim() || added.stdout.trim()}`);
|
|
928
|
+
}
|
|
929
|
+
return {
|
|
930
|
+
cwd,
|
|
931
|
+
diff: async () => {
|
|
932
|
+
git(["add", "-A"], cwd);
|
|
933
|
+
const result = git(["diff", "--cached", "--binary", "--no-color"], cwd);
|
|
934
|
+
if (!result.ok) {
|
|
935
|
+
options.log?.(`fabric diff failed: ${result.stderr.trim()}`);
|
|
936
|
+
return null;
|
|
937
|
+
}
|
|
938
|
+
return result.stdout.trim() ? Buffer.from(result.stdout, "utf8") : null;
|
|
939
|
+
},
|
|
940
|
+
cleanup: async () => {
|
|
941
|
+
git(["worktree", "remove", "--force", cwd], repo);
|
|
942
|
+
rmSync(cwd, { recursive: true, force: true });
|
|
943
|
+
}
|
|
944
|
+
};
|
|
945
|
+
}
|
|
946
|
+
function audit(options, record) {
|
|
947
|
+
if (!options.auditPath) return;
|
|
948
|
+
try {
|
|
949
|
+
mkdirSync(path.dirname(options.auditPath), { recursive: true });
|
|
950
|
+
appendFileSync(options.auditPath, `${JSON.stringify(record)}
|
|
951
|
+
`, "utf8");
|
|
952
|
+
} catch (error) {
|
|
953
|
+
options.log?.(`fabric audit append failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
function createShellRunner(options) {
|
|
957
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TASK_TIMEOUT_MS;
|
|
958
|
+
const maxBytes = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
|
959
|
+
return {
|
|
960
|
+
async run(input) {
|
|
961
|
+
const startedAt = Date.now();
|
|
962
|
+
const workspace = prepareWorkspace(options, input.taskId);
|
|
963
|
+
input.onProgress(progressNote("workspace_ready", void 0, `\u5DF2\u5728 ${workspace.cwd} \u5C31\u7EEA`));
|
|
964
|
+
const prompt = [
|
|
965
|
+
input.prompt,
|
|
966
|
+
"",
|
|
967
|
+
"---",
|
|
968
|
+
"\u8FDC\u7A0B\u6D3E\u6D3B\u8BF4\u660E\uFF1A\u4E0A\u9762\u7684\u4EFB\u52A1\u6765\u81EA\u53E6\u4E00\u53F0\u5DF2\u914D\u5BF9\u673A\u5668\uFF0C\u8BF7\u5728\u5F53\u524D\u5DE5\u4F5C\u76EE\u5F55\u5185\u5B8C\u6210\uFF1B",
|
|
969
|
+
"\u7ED3\u675F\u65F6\u7528\u4E0D\u8D85\u8FC7 8 \u884C\u8BF4\u660E\uFF1A\u505A\u4E86\u4EC0\u4E48\u3001\u6539\u4E86\u54EA\u4E9B\u6587\u4EF6\u3001\u6709\u6CA1\u6709\u98CE\u9669\u3002"
|
|
970
|
+
].join("\n");
|
|
971
|
+
const command = buildCommand(options.exec, prompt);
|
|
972
|
+
options.log?.(`fabric task ${input.taskId} start in ${workspace.cwd}`);
|
|
973
|
+
let result;
|
|
974
|
+
try {
|
|
975
|
+
result = await runShell(command, workspace.cwd, timeoutMs, maxBytes);
|
|
976
|
+
const diff = workspace.diff ? await workspace.diff().catch(() => null) : null;
|
|
977
|
+
audit(options, {
|
|
978
|
+
at: new Date(startedAt).toISOString(),
|
|
979
|
+
taskId: input.taskId,
|
|
980
|
+
grant: input.grant,
|
|
981
|
+
command: options.exec,
|
|
982
|
+
cwd: workspace.cwd,
|
|
983
|
+
exitCode: result.code,
|
|
984
|
+
timedOut: result.timedOut,
|
|
985
|
+
ms: Date.now() - startedAt,
|
|
986
|
+
diffBytes: diff?.length ?? 0,
|
|
987
|
+
stdout: result.stdout.slice(-4e3),
|
|
988
|
+
stderr: result.stderr.slice(-2e3)
|
|
989
|
+
});
|
|
990
|
+
if (result.timedOut) throw new Error(`E_TIMEOUT: \u8D85\u8FC7 ${timeoutMs} ms \u672A\u7ED3\u675F\uFF0C\u5DF2\u6740\u6389\u8FDB\u7A0B\u6811`);
|
|
991
|
+
return {
|
|
992
|
+
summary: (result.stdout || result.stderr || "(\u65E0\u8F93\u51FA)").replace(/\r\n/g, "\n").trim().slice(0, 1200),
|
|
993
|
+
files: [],
|
|
994
|
+
exitCode: result.code ?? 0,
|
|
995
|
+
result: Buffer.from(`${result.stdout}
|
|
996
|
+
${result.stderr}`.trim(), "utf8"),
|
|
997
|
+
diff
|
|
998
|
+
};
|
|
999
|
+
} catch (error) {
|
|
1000
|
+
audit(options, {
|
|
1001
|
+
at: new Date(startedAt).toISOString(),
|
|
1002
|
+
taskId: input.taskId,
|
|
1003
|
+
grant: input.grant,
|
|
1004
|
+
command: options.exec,
|
|
1005
|
+
cwd: workspace.cwd,
|
|
1006
|
+
error: error instanceof Error ? error.message : String(error),
|
|
1007
|
+
ms: Date.now() - startedAt
|
|
1008
|
+
});
|
|
1009
|
+
throw error;
|
|
1010
|
+
} finally {
|
|
1011
|
+
await workspace.cleanup?.().catch(() => void 0);
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
};
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
// src/discovery.ts
|
|
1018
|
+
init_fabric();
|
|
1019
|
+
import { createSocket } from "node:dgram";
|
|
1020
|
+
import { networkInterfaces } from "node:os";
|
|
1021
|
+
var DISC_PORT_BASE = 7800;
|
|
1022
|
+
var DISC_SPAN = 100;
|
|
1023
|
+
var DISC_TIMEOUT_MS = 1200;
|
|
1024
|
+
var MAX_PACKET_BYTES = 512;
|
|
1025
|
+
function fnv1a(text) {
|
|
1026
|
+
let hash = 2166136261;
|
|
1027
|
+
for (let index = 0; index < text.length; index += 1) {
|
|
1028
|
+
hash ^= text.charCodeAt(index);
|
|
1029
|
+
hash = Math.imul(hash, 16777619) >>> 0;
|
|
1030
|
+
}
|
|
1031
|
+
return hash >>> 0;
|
|
1032
|
+
}
|
|
1033
|
+
function discoveryPort(nodeName, base = DISC_PORT_BASE, span = DISC_SPAN) {
|
|
1034
|
+
return base + fnv1a(nodeName) % Math.max(1, span);
|
|
1035
|
+
}
|
|
1036
|
+
function sanitizeCtx(ctx) {
|
|
1037
|
+
return ctx.trim().slice(0, FABRIC_CTX_MAX_CHARS);
|
|
1038
|
+
}
|
|
1039
|
+
async function startResponder(options) {
|
|
1040
|
+
const port = discoveryPort(options.nodeName, options.base, options.span);
|
|
1041
|
+
const ctx = sanitizeCtx(options.ctx);
|
|
1042
|
+
const socket = createSocket({ type: "udp4", reuseAddr: true });
|
|
1043
|
+
await new Promise((resolve2, reject) => {
|
|
1044
|
+
socket.once("error", reject);
|
|
1045
|
+
socket.bind(port, "0.0.0.0", () => {
|
|
1046
|
+
socket.removeListener("error", reject);
|
|
1047
|
+
resolve2();
|
|
1048
|
+
});
|
|
1049
|
+
});
|
|
1050
|
+
socket.on("message", (packet, from) => {
|
|
1051
|
+
if (packet.length > MAX_PACKET_BYTES) return;
|
|
1052
|
+
const text = packet.toString("utf8");
|
|
1053
|
+
const parts = text.split("|");
|
|
1054
|
+
if (parts.length !== 4 || parts[0] !== "SBF1") return;
|
|
1055
|
+
if (parts[1] !== ctx) return;
|
|
1056
|
+
if (parts[2] !== options.nodeName) return;
|
|
1057
|
+
const protocol = checkProtocolVersion(parts[3]);
|
|
1058
|
+
if (!protocol.ok) {
|
|
1059
|
+
options.log?.(`disc probe from ${from.address} rejected: ${protocol.reason}`);
|
|
1060
|
+
return;
|
|
1061
|
+
}
|
|
1062
|
+
const reply = `SBF2|${options.nodeName}|${options.tcpPort}|${FABRIC_PROTOCOL_VERSION}`;
|
|
1063
|
+
socket.send(Buffer.from(reply, "utf8"), from.port, from.address, () => {
|
|
1064
|
+
options.log?.(`disc answered ${from.address} -> ${reply}`);
|
|
1065
|
+
});
|
|
1066
|
+
});
|
|
1067
|
+
socket.on("error", (error) => options.log?.(`disc socket error: ${error.message}`));
|
|
1068
|
+
return {
|
|
1069
|
+
port,
|
|
1070
|
+
close: () => new Promise((resolve2) => {
|
|
1071
|
+
try {
|
|
1072
|
+
socket.close(() => resolve2());
|
|
1073
|
+
} catch {
|
|
1074
|
+
resolve2();
|
|
1075
|
+
}
|
|
1076
|
+
})
|
|
1077
|
+
};
|
|
1078
|
+
}
|
|
1079
|
+
async function discoverPeer(options) {
|
|
1080
|
+
const port = discoveryPort(options.wantNode, options.base, options.span);
|
|
1081
|
+
const ctx = sanitizeCtx(options.ctx);
|
|
1082
|
+
const socket = createSocket({ type: "udp4" });
|
|
1083
|
+
await new Promise((resolve2, reject) => {
|
|
1084
|
+
socket.once("error", reject);
|
|
1085
|
+
socket.bind(0, "0.0.0.0", () => {
|
|
1086
|
+
socket.removeListener("error", reject);
|
|
1087
|
+
resolve2();
|
|
1088
|
+
});
|
|
1089
|
+
});
|
|
1090
|
+
const probe = Buffer.from(`SBF1|${ctx}|${options.wantNode}|${FABRIC_PROTOCOL_VERSION}`, "utf8");
|
|
1091
|
+
return new Promise((resolve2) => {
|
|
1092
|
+
let settled = false;
|
|
1093
|
+
const finish = (value) => {
|
|
1094
|
+
if (settled) return;
|
|
1095
|
+
settled = true;
|
|
1096
|
+
clearTimeout(timer);
|
|
1097
|
+
try {
|
|
1098
|
+
socket.close();
|
|
1099
|
+
} catch {
|
|
1100
|
+
}
|
|
1101
|
+
resolve2(value);
|
|
1102
|
+
};
|
|
1103
|
+
const timer = setTimeout(() => finish(null), options.timeoutMs ?? DISC_TIMEOUT_MS);
|
|
1104
|
+
timer.unref?.();
|
|
1105
|
+
socket.on("message", (packet, from) => {
|
|
1106
|
+
if (packet.length > MAX_PACKET_BYTES) return;
|
|
1107
|
+
const parts = packet.toString("utf8").split("|");
|
|
1108
|
+
if (parts.length !== 4 || parts[0] !== "SBF2") return;
|
|
1109
|
+
if (parts[1] !== options.wantNode) return;
|
|
1110
|
+
const protocol = checkProtocolVersion(parts[3]);
|
|
1111
|
+
if (!protocol.ok) {
|
|
1112
|
+
options.log?.(`disc reply from ${from.address} rejected: ${protocol.reason}`);
|
|
1113
|
+
return;
|
|
1114
|
+
}
|
|
1115
|
+
const tcpPort = Number.parseInt(parts[2], 10);
|
|
1116
|
+
if (!Number.isInteger(tcpPort) || tcpPort < 1 || tcpPort > 65535) return;
|
|
1117
|
+
options.log?.(`disc discovered ${parts[1]} at ${from.address}:${tcpPort}`);
|
|
1118
|
+
finish(`${from.address}:${tcpPort}`);
|
|
1119
|
+
});
|
|
1120
|
+
socket.send(probe, port, "127.0.0.1", () => {
|
|
1121
|
+
});
|
|
1122
|
+
socket.send(probe, port, "255.255.255.255", () => {
|
|
1123
|
+
});
|
|
1124
|
+
});
|
|
1125
|
+
}
|
|
1126
|
+
var DISC_ANNOUNCE_PORT = 7799;
|
|
1127
|
+
var ANNOUNCE_PROBE = "SBF3";
|
|
1128
|
+
var ANNOUNCE_REPLY = "SBF4";
|
|
1129
|
+
var SCAN_RESEND_MS = 400;
|
|
1130
|
+
function sanitizeVersion(raw) {
|
|
1131
|
+
return (raw ?? "").replace(/[|\s]/g, "").slice(0, 24);
|
|
1132
|
+
}
|
|
1133
|
+
function closeQuietly(socket) {
|
|
1134
|
+
return new Promise((resolve2) => {
|
|
1135
|
+
try {
|
|
1136
|
+
socket.close(() => resolve2());
|
|
1137
|
+
} catch {
|
|
1138
|
+
resolve2();
|
|
1139
|
+
}
|
|
1140
|
+
});
|
|
1141
|
+
}
|
|
1142
|
+
async function startAnnouncer(options) {
|
|
1143
|
+
let port = options.port ?? DISC_ANNOUNCE_PORT;
|
|
1144
|
+
const version = sanitizeVersion(options.appVersion);
|
|
1145
|
+
const socket = createSocket({ type: "udp4", reuseAddr: true });
|
|
1146
|
+
await new Promise((resolve2, reject) => {
|
|
1147
|
+
socket.once("error", reject);
|
|
1148
|
+
socket.bind(port, "0.0.0.0", () => {
|
|
1149
|
+
socket.removeListener("error", reject);
|
|
1150
|
+
resolve2();
|
|
1151
|
+
});
|
|
1152
|
+
});
|
|
1153
|
+
const bound = socket.address();
|
|
1154
|
+
if (bound && typeof bound === "object") port = bound.port;
|
|
1155
|
+
socket.on("message", (packet, from) => {
|
|
1156
|
+
if (packet.length > MAX_PACKET_BYTES) return;
|
|
1157
|
+
const parts = packet.toString("utf8").split("|");
|
|
1158
|
+
if (parts.length !== 3 || parts[0] !== ANNOUNCE_PROBE) return;
|
|
1159
|
+
if (options.enabled && !options.enabled()) return;
|
|
1160
|
+
const protocol = checkProtocolVersion(parts[2]);
|
|
1161
|
+
if (!protocol.ok) {
|
|
1162
|
+
options.log?.(`fabric announce ignored ${from.address}: ${protocol.reason}`);
|
|
1163
|
+
return;
|
|
1164
|
+
}
|
|
1165
|
+
const reply = `${ANNOUNCE_REPLY}|${options.nodeId}|${options.tcpPort}|${FABRIC_PROTOCOL_VERSION}|${version}`;
|
|
1166
|
+
socket.send(Buffer.from(reply, "utf8"), from.port, from.address, (error) => {
|
|
1167
|
+
if (error) options.log?.(`fabric announce reply failed: ${error.message}`);
|
|
1168
|
+
});
|
|
1169
|
+
});
|
|
1170
|
+
socket.on("error", (error) => options.log?.(`fabric announce socket error: ${error.message}`));
|
|
1171
|
+
return {
|
|
1172
|
+
port,
|
|
1173
|
+
close: () => closeQuietly(socket)
|
|
1174
|
+
};
|
|
1175
|
+
}
|
|
1176
|
+
function broadcastAddresses() {
|
|
1177
|
+
const targets = /* @__PURE__ */ new Set(["255.255.255.255", "127.0.0.1"]);
|
|
1178
|
+
for (const list of Object.values(networkInterfaces())) {
|
|
1179
|
+
for (const info of list ?? []) {
|
|
1180
|
+
if (info.family !== "IPv4" || info.internal) continue;
|
|
1181
|
+
targets.add(broadcastOf(info.address, info.netmask));
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
return [...targets];
|
|
1185
|
+
}
|
|
1186
|
+
function broadcastOf(address, netmask) {
|
|
1187
|
+
const ip = address.split(".").map((part) => Number.parseInt(part, 10));
|
|
1188
|
+
const mask = (netmask ?? "255.255.255.255").split(".").map((part) => Number.parseInt(part, 10));
|
|
1189
|
+
if (ip.length !== 4 || mask.length !== 4 || mask.some((part) => !Number.isInteger(part))) {
|
|
1190
|
+
return "255.255.255.255";
|
|
1191
|
+
}
|
|
1192
|
+
return ip.map((part, index) => (part | ~(mask[index] ?? 255) & 255) & 255).join(".");
|
|
1193
|
+
}
|
|
1194
|
+
async function scanLan(options = {}) {
|
|
1195
|
+
const port = options.port ?? DISC_ANNOUNCE_PORT;
|
|
1196
|
+
const socket = createSocket({ type: "udp4", reuseAddr: true });
|
|
1197
|
+
try {
|
|
1198
|
+
socket.setBroadcast(true);
|
|
1199
|
+
} catch {
|
|
1200
|
+
}
|
|
1201
|
+
const found = /* @__PURE__ */ new Map();
|
|
1202
|
+
await new Promise((resolve2, reject) => {
|
|
1203
|
+
socket.once("error", reject);
|
|
1204
|
+
socket.bind(0, () => {
|
|
1205
|
+
socket.removeListener("error", reject);
|
|
1206
|
+
resolve2();
|
|
1207
|
+
});
|
|
1208
|
+
});
|
|
1209
|
+
socket.on("message", (packet, from) => {
|
|
1210
|
+
if (packet.length > MAX_PACKET_BYTES) return;
|
|
1211
|
+
const parts = packet.toString("utf8").split("|");
|
|
1212
|
+
if (parts.length < 4 || parts[0] !== ANNOUNCE_REPLY) return;
|
|
1213
|
+
const nodeId = parts[1] ?? "";
|
|
1214
|
+
if (!/^[0-9a-f]{8,64}$/i.test(nodeId)) return;
|
|
1215
|
+
const tcpPort = Number.parseInt(parts[2] ?? "", 10);
|
|
1216
|
+
if (!Number.isInteger(tcpPort) || tcpPort < 1 || tcpPort > 65535) return;
|
|
1217
|
+
const protocol = checkProtocolVersion(parts[3]);
|
|
1218
|
+
if (!protocol.ok) {
|
|
1219
|
+
options.log?.(`fabric scan ignored ${from.address}: ${protocol.reason}`);
|
|
1220
|
+
return;
|
|
1221
|
+
}
|
|
1222
|
+
found.set(nodeId, {
|
|
1223
|
+
nodeId,
|
|
1224
|
+
shortId: nodeId.slice(0, 4),
|
|
1225
|
+
tcpPort,
|
|
1226
|
+
appVersion: parts[4] ?? "",
|
|
1227
|
+
protocolVersion: protocol.version,
|
|
1228
|
+
address: from.address
|
|
1229
|
+
});
|
|
1230
|
+
});
|
|
1231
|
+
socket.on("error", (error) => options.log?.(`fabric scan socket error: ${error.message}`));
|
|
1232
|
+
const targets = broadcastAddresses();
|
|
1233
|
+
const probe = Buffer.from(`${ANNOUNCE_PROBE}|${Date.now().toString(36)}|${FABRIC_PROTOCOL_VERSION}`, "utf8");
|
|
1234
|
+
const sendAll = () => {
|
|
1235
|
+
for (const target of targets) socket.send(probe, port, target, () => {
|
|
1236
|
+
});
|
|
1237
|
+
};
|
|
1238
|
+
sendAll();
|
|
1239
|
+
await new Promise((resolve2) => {
|
|
1240
|
+
const resend = setTimeout(sendAll, SCAN_RESEND_MS);
|
|
1241
|
+
const end = setTimeout(resolve2, options.timeoutMs ?? DISC_TIMEOUT_MS);
|
|
1242
|
+
resend.unref?.();
|
|
1243
|
+
end.unref?.();
|
|
1244
|
+
});
|
|
1245
|
+
await closeQuietly(socket);
|
|
1246
|
+
return [...found.values()];
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
// src/fabric-service.ts
|
|
1250
|
+
init_fabric();
|
|
1251
|
+
|
|
1252
|
+
// src/artifacts.ts
|
|
1253
|
+
import { createHash } from "node:crypto";
|
|
1254
|
+
import {
|
|
1255
|
+
createReadStream,
|
|
1256
|
+
existsSync,
|
|
1257
|
+
mkdirSync as mkdirSync2,
|
|
1258
|
+
readdirSync,
|
|
1259
|
+
readFileSync,
|
|
1260
|
+
renameSync,
|
|
1261
|
+
rmSync as rmSync2,
|
|
1262
|
+
statSync,
|
|
1263
|
+
utimesSync,
|
|
1264
|
+
writeFileSync
|
|
1265
|
+
} from "node:fs";
|
|
1266
|
+
import { dirname, join } from "node:path";
|
|
1267
|
+
var ARTIFACT_MAX_BYTES = 512 * 1024 * 1024;
|
|
1268
|
+
var ARTIFACT_MAX_OBJECTS = 1e3;
|
|
1269
|
+
var ARTIFACT_UNREFERENCED_TTL_MS = 24 * 60 * 60 * 1e3;
|
|
1270
|
+
var ARTIFACT_REFERENCED_TTL_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
1271
|
+
var ARTIFACT_MAX_OBJECT_BYTES = 256 * 1024 * 1024;
|
|
1272
|
+
var ArtifactError = class extends Error {
|
|
1273
|
+
constructor(code, message) {
|
|
1274
|
+
super(message);
|
|
1275
|
+
this.name = "ArtifactError";
|
|
1276
|
+
this.code = code;
|
|
1277
|
+
}
|
|
1278
|
+
};
|
|
1279
|
+
var SHA256_RE = /^[0-9a-f]{64}$/;
|
|
1280
|
+
function artifactsRoot(agentDir) {
|
|
1281
|
+
return join(agentDir, "fabric", "artifacts");
|
|
1282
|
+
}
|
|
1283
|
+
function isArtifactRef(value) {
|
|
1284
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
1285
|
+
const ref = value;
|
|
1286
|
+
return typeof ref.sha256 === "string" && SHA256_RE.test(ref.sha256) && typeof ref.len === "number" && Number.isInteger(ref.len) && ref.len >= 0 && typeof ref.kind === "string";
|
|
1287
|
+
}
|
|
1288
|
+
function sanitizeRef(value) {
|
|
1289
|
+
if (!isArtifactRef(value)) throw new ArtifactError("E_INVALID_PARAMS", "invalid artifact ref");
|
|
1290
|
+
if (value.len > ARTIFACT_MAX_OBJECT_BYTES) {
|
|
1291
|
+
throw new ArtifactError("E_ARTIFACT_TOO_LARGE", "artifact exceeds the single-object limit");
|
|
1292
|
+
}
|
|
1293
|
+
return { sha256: value.sha256, len: value.len, kind: value.kind };
|
|
1294
|
+
}
|
|
1295
|
+
var ArtifactStore = class {
|
|
1296
|
+
constructor(agentDir, options = {}) {
|
|
1297
|
+
/** LRU 逻辑时钟(毫秒),保证连续触碰拿到严格递增的 mtime。 */
|
|
1298
|
+
this.clock = 0;
|
|
1299
|
+
this.root = options.root ?? artifactsRoot(agentDir);
|
|
1300
|
+
this.maxBytes = options.maxBytes ?? ARTIFACT_MAX_BYTES;
|
|
1301
|
+
this.maxObjects = options.maxObjects ?? ARTIFACT_MAX_OBJECTS;
|
|
1302
|
+
}
|
|
1303
|
+
/** 幂等:同样的内容写两次只有一个对象(sha256 就是幂等键)。 */
|
|
1304
|
+
put(data, kind = "input") {
|
|
1305
|
+
if (data.length > ARTIFACT_MAX_OBJECT_BYTES) {
|
|
1306
|
+
throw new ArtifactError("E_ARTIFACT_TOO_LARGE", "artifact exceeds the single-object limit");
|
|
1307
|
+
}
|
|
1308
|
+
const sha256 = createHash("sha256").update(data).digest("hex");
|
|
1309
|
+
const file = this.pathFor(sha256);
|
|
1310
|
+
if (!existsSync(file)) {
|
|
1311
|
+
mkdirSync2(dirname(file), { recursive: true });
|
|
1312
|
+
const temp = file + ".tmp";
|
|
1313
|
+
writeFileSync(temp, data);
|
|
1314
|
+
renameSync(temp, file);
|
|
1315
|
+
}
|
|
1316
|
+
this.touch(sha256);
|
|
1317
|
+
this.enforceQuota();
|
|
1318
|
+
return { sha256, len: data.length, kind };
|
|
1319
|
+
}
|
|
1320
|
+
/** 读取并校验:内容被改过或截断一律报 E_ARTIFACT_CORRUPT,不把坏数据交给任务。 */
|
|
1321
|
+
read(ref) {
|
|
1322
|
+
const safe = sanitizeRef(ref);
|
|
1323
|
+
const file = this.pathFor(safe.sha256);
|
|
1324
|
+
if (!existsSync(file)) throw new ArtifactError("E_ARTIFACT_MISSING", "artifact not found");
|
|
1325
|
+
const data = readFileSync(file);
|
|
1326
|
+
const digest = createHash("sha256").update(data).digest("hex");
|
|
1327
|
+
if (digest !== safe.sha256) {
|
|
1328
|
+
throw new ArtifactError("E_ARTIFACT_CORRUPT", "artifact content does not match its sha256");
|
|
1329
|
+
}
|
|
1330
|
+
if (safe.len !== data.length) {
|
|
1331
|
+
throw new ArtifactError("E_ARTIFACT_CORRUPT", "artifact length does not match its ref");
|
|
1332
|
+
}
|
|
1333
|
+
this.touch(safe.sha256);
|
|
1334
|
+
return data;
|
|
1335
|
+
}
|
|
1336
|
+
stream(ref) {
|
|
1337
|
+
const safe = sanitizeRef(ref);
|
|
1338
|
+
const file = this.pathFor(safe.sha256);
|
|
1339
|
+
if (!existsSync(file)) throw new ArtifactError("E_ARTIFACT_MISSING", "artifact not found");
|
|
1340
|
+
this.touch(safe.sha256);
|
|
1341
|
+
return createReadStream(file);
|
|
1342
|
+
}
|
|
1343
|
+
has(sha256) {
|
|
1344
|
+
return SHA256_RE.test(sha256) && existsSync(this.pathFor(sha256));
|
|
1345
|
+
}
|
|
1346
|
+
stats() {
|
|
1347
|
+
let bytes = 0;
|
|
1348
|
+
let objects = 0;
|
|
1349
|
+
for (const entry of this.entries()) {
|
|
1350
|
+
bytes += entry.size;
|
|
1351
|
+
objects += 1;
|
|
1352
|
+
}
|
|
1353
|
+
return { bytes, objects };
|
|
1354
|
+
}
|
|
1355
|
+
/** 按 LRU(mtime)淘汰到配额以内。写得进来但永远删不掉,最终会把磁盘吃满。 */
|
|
1356
|
+
enforceQuota(now = Date.now()) {
|
|
1357
|
+
const entries = this.entries();
|
|
1358
|
+
let bytes = entries.reduce((sum, entry) => sum + entry.size, 0);
|
|
1359
|
+
let objects = entries.length;
|
|
1360
|
+
let removed = 0;
|
|
1361
|
+
let bytesFreed = 0;
|
|
1362
|
+
for (const entry of entries) {
|
|
1363
|
+
if (bytes <= this.maxBytes && objects <= this.maxObjects) break;
|
|
1364
|
+
rmSync2(entry.file, { force: true });
|
|
1365
|
+
bytes -= entry.size;
|
|
1366
|
+
objects -= 1;
|
|
1367
|
+
bytesFreed += entry.size;
|
|
1368
|
+
removed += 1;
|
|
1369
|
+
}
|
|
1370
|
+
void now;
|
|
1371
|
+
return { removed, bytesFreed };
|
|
1372
|
+
}
|
|
1373
|
+
/** TTL 清理:被引用的留一周,没被引用的留一天。 */
|
|
1374
|
+
sweep(referenced = [], now = Date.now()) {
|
|
1375
|
+
const keep = new Set(referenced);
|
|
1376
|
+
const referencedTtl = ARTIFACT_REFERENCED_TTL_MS;
|
|
1377
|
+
const unreferencedTtl = ARTIFACT_UNREFERENCED_TTL_MS;
|
|
1378
|
+
let removed = 0;
|
|
1379
|
+
let bytesFreed = 0;
|
|
1380
|
+
for (const entry of this.entries()) {
|
|
1381
|
+
const ttl = keep.has(entry.sha256) ? referencedTtl : unreferencedTtl;
|
|
1382
|
+
if (now - entry.mtime <= ttl) continue;
|
|
1383
|
+
rmSync2(entry.file, { force: true });
|
|
1384
|
+
removed += 1;
|
|
1385
|
+
bytesFreed += entry.size;
|
|
1386
|
+
}
|
|
1387
|
+
return { removed, bytesFreed };
|
|
1388
|
+
}
|
|
1389
|
+
pathFor(sha256) {
|
|
1390
|
+
if (!SHA256_RE.test(sha256)) throw new ArtifactError("E_INVALID_PARAMS", "bad sha256");
|
|
1391
|
+
return join(this.root, sha256.slice(0, 2), sha256);
|
|
1392
|
+
}
|
|
1393
|
+
/**
|
|
1394
|
+
* 单调递增的毫秒时间戳:同一毫秒(Windows 上甚至是同一 15.6ms 时钟拍)里的连续
|
|
1395
|
+
* 操作也必须分得出先后,否则 mtime 打平后 LRU 淘汰顺序退化成 readdir 顺序。
|
|
1396
|
+
* 只能按整毫秒推进——stat().mtimeMs 是 double,毫秒以下在今天的时间戳量级上根本存不下。
|
|
1397
|
+
*/
|
|
1398
|
+
nextStamp() {
|
|
1399
|
+
const now = Date.now();
|
|
1400
|
+
this.clock = now > this.clock ? now : this.clock + 1;
|
|
1401
|
+
return this.clock;
|
|
1402
|
+
}
|
|
1403
|
+
touch(sha256) {
|
|
1404
|
+
const at = new Date(this.nextStamp());
|
|
1405
|
+
try {
|
|
1406
|
+
utimesSync(this.pathFor(sha256), at, at);
|
|
1407
|
+
} catch {
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1410
|
+
entries() {
|
|
1411
|
+
if (!existsSync(this.root)) return [];
|
|
1412
|
+
const collected = [];
|
|
1413
|
+
for (const bucket of readdirSync(this.root)) {
|
|
1414
|
+
if (!/^[0-9a-f]{2}$/.test(bucket)) continue;
|
|
1415
|
+
const bucketDir = join(this.root, bucket);
|
|
1416
|
+
let names;
|
|
1417
|
+
try {
|
|
1418
|
+
names = readdirSync(bucketDir);
|
|
1419
|
+
} catch {
|
|
1420
|
+
continue;
|
|
1421
|
+
}
|
|
1422
|
+
for (const name of names) {
|
|
1423
|
+
if (!SHA256_RE.test(name)) continue;
|
|
1424
|
+
const file = join(bucketDir, name);
|
|
1425
|
+
try {
|
|
1426
|
+
const stat = statSync(file);
|
|
1427
|
+
if (!stat.isFile()) continue;
|
|
1428
|
+
collected.push({ sha256: name, file, size: stat.size, mtime: stat.mtimeMs });
|
|
1429
|
+
} catch {
|
|
1430
|
+
}
|
|
1431
|
+
}
|
|
1432
|
+
}
|
|
1433
|
+
return collected.sort((a, b) => a.mtime - b.mtime);
|
|
1434
|
+
}
|
|
1435
|
+
};
|
|
1436
|
+
|
|
1437
|
+
// src/dispatcher.ts
|
|
1438
|
+
init_fabric();
|
|
1439
|
+
import { createHash as createHash4 } from "node:crypto";
|
|
1440
|
+
|
|
1441
|
+
// src/dispatch.ts
|
|
1442
|
+
init_fabric();
|
|
1443
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
1444
|
+
import { existsSync as existsSync2, mkdirSync as mkdirSync3, readdirSync as readdirSync2, readFileSync as readFileSync2, renameSync as renameSync2, rmSync as rmSync3, writeFileSync as writeFileSync2 } from "node:fs";
|
|
1445
|
+
import { dirname as dirname2, join as join2 } from "node:path";
|
|
1446
|
+
var REMOTE_MIN_ESTIMATE_MS = 6e4;
|
|
1447
|
+
var PEER_ONLINE_HB_MS = 5e3;
|
|
1448
|
+
var PEER_MAX_QUEUE = 2;
|
|
1449
|
+
var GRANT_RANK = {
|
|
1450
|
+
"read-only": 0,
|
|
1451
|
+
"workspace-rw": 1,
|
|
1452
|
+
"workspace-rw+bash": 2
|
|
1453
|
+
};
|
|
1454
|
+
function choosePeer(candidates, need) {
|
|
1455
|
+
const considered = candidates.length;
|
|
1456
|
+
if (considered === 0) {
|
|
1457
|
+
return { ok: false, code: "E_NO_PEERS", reason: "\u8FD8\u6CA1\u6709\u5DF2\u914D\u5BF9\u673A\u5668", considered };
|
|
1458
|
+
}
|
|
1459
|
+
if (!(need.estimatedMs >= REMOTE_MIN_ESTIMATE_MS)) {
|
|
1460
|
+
return {
|
|
1461
|
+
ok: false,
|
|
1462
|
+
code: "E_LOCAL_FASTER",
|
|
1463
|
+
reason: `\u9884\u8BA1 ${need.estimatedMs}ms < ${REMOTE_MIN_ESTIMATE_MS}ms\uFF0C\u672C\u5730\u8DD1\u66F4\u5FEB`,
|
|
1464
|
+
considered
|
|
1465
|
+
};
|
|
1466
|
+
}
|
|
1467
|
+
const required = need.grant ?? "read-only";
|
|
1468
|
+
const online = candidates.filter(
|
|
1469
|
+
(peer) => peer.online && peer.hbAgeMs !== null && peer.hbAgeMs <= PEER_ONLINE_HB_MS
|
|
1470
|
+
);
|
|
1471
|
+
if (online.length === 0) {
|
|
1472
|
+
return { ok: false, code: "E_PEER_OFFLINE", reason: "\u5DF2\u914D\u5BF9\u673A\u5668\u90FD\u4E0D\u5728\u7EBF", considered };
|
|
1473
|
+
}
|
|
1474
|
+
const labelled = online.filter(
|
|
1475
|
+
(peer) => need.labels.every((label) => peer.labels.includes(label))
|
|
1476
|
+
);
|
|
1477
|
+
if (labelled.length === 0) {
|
|
1478
|
+
return {
|
|
1479
|
+
ok: false,
|
|
1480
|
+
code: "E_NO_LABEL",
|
|
1481
|
+
reason: `\u6CA1\u6709\u673A\u5668\u5177\u5907\u80FD\u529B\u6807\u7B7E ${need.labels.join(",") || "(\u7A7A)"}`,
|
|
1482
|
+
considered
|
|
1483
|
+
};
|
|
1484
|
+
}
|
|
1485
|
+
const allowed = labelled.filter((peer) => GRANT_RANK[peer.grants] >= GRANT_RANK[required]);
|
|
1486
|
+
if (allowed.length === 0) {
|
|
1487
|
+
return {
|
|
1488
|
+
ok: false,
|
|
1489
|
+
code: "E_GRANT_TOO_LOW",
|
|
1490
|
+
reason: `\u62E5\u6709\u8BE5\u80FD\u529B\u7684\u673A\u5668\u6743\u9650\u6863\u4F4D\u4F4E\u4E8E ${required}`,
|
|
1491
|
+
considered
|
|
1492
|
+
};
|
|
1493
|
+
}
|
|
1494
|
+
const pinned = need.pin ? allowed.find((peer) => peer.nodeId === need.pin) : void 0;
|
|
1495
|
+
if (pinned) {
|
|
1496
|
+
return {
|
|
1497
|
+
ok: true,
|
|
1498
|
+
peerId: pinned.nodeId,
|
|
1499
|
+
reason: `\u6309\u4F60\u9489\u4F4F\u7684\u9009\u62E9\u6D3E\u7ED9 ${pinned.name}\uFF08\u961F\u5217 ${pinned.queueDepth}\uFF09`,
|
|
1500
|
+
considered
|
|
1501
|
+
};
|
|
1502
|
+
}
|
|
1503
|
+
const idle = allowed.filter((peer) => peer.queueDepth <= PEER_MAX_QUEUE);
|
|
1504
|
+
if (idle.length === 0) {
|
|
1505
|
+
return { ok: false, code: "E_PEER_BUSY", reason: "\u62E5\u6709\u8BE5\u80FD\u529B\u7684\u673A\u5668\u90FD\u5728\u5FD9", considered };
|
|
1506
|
+
}
|
|
1507
|
+
const ranked = idle.map((peer) => ({ peer, score: scorePeer(peer) })).sort((a, b) => a.score !== b.score ? a.score - b.score : a.peer.name.localeCompare(b.peer.name));
|
|
1508
|
+
const best = ranked[0];
|
|
1509
|
+
if (!best) {
|
|
1510
|
+
return { ok: false, code: "E_PEER_BUSY", reason: "\u62E5\u6709\u8BE5\u80FD\u529B\u7684\u673A\u5668\u90FD\u5728\u5FD9", considered };
|
|
1511
|
+
}
|
|
1512
|
+
return {
|
|
1513
|
+
ok: true,
|
|
1514
|
+
peerId: best.peer.nodeId,
|
|
1515
|
+
reason: describeChoice(best.peer, best.score),
|
|
1516
|
+
considered
|
|
1517
|
+
};
|
|
1518
|
+
}
|
|
1519
|
+
function scorePeer(peer) {
|
|
1520
|
+
const cpu = typeof peer.cpuLoad === "number" && peer.cpuLoad >= 0 && peer.cpuLoad <= 1 ? peer.cpuLoad : 0.5;
|
|
1521
|
+
const hb = Math.min(peer.hbAgeMs ?? PEER_ONLINE_HB_MS, PEER_ONLINE_HB_MS);
|
|
1522
|
+
const history = typeof peer.historyP50Ms === "number" && peer.historyP50Ms > 0 ? Math.min(peer.historyP50Ms, 36e5) / 6e4 : 10;
|
|
1523
|
+
return peer.queueDepth * 100 + cpu * 50 + hb / PEER_ONLINE_HB_MS * 10 + history;
|
|
1524
|
+
}
|
|
1525
|
+
function describeChoice(peer, score) {
|
|
1526
|
+
const parts = [
|
|
1527
|
+
`\u961F\u5217 ${peer.queueDepth}`,
|
|
1528
|
+
`\u8D1F\u8F7D ${Math.round((peer.cpuLoad ?? 0.5) * 100)}%`
|
|
1529
|
+
];
|
|
1530
|
+
if (typeof peer.historyP50Ms === "number" && peer.historyP50Ms > 0) {
|
|
1531
|
+
parts.push(`\u540C\u7C7B\u6D3B\u5386\u53F2\u4E2D\u4F4D ${Math.round(peer.historyP50Ms / 6e4)} \u5206\u949F`);
|
|
1532
|
+
}
|
|
1533
|
+
return `\u6D3E\u7ED9 ${peer.name}\uFF1A${parts.join("\uFF0C")}\uFF08\u5206 ${Math.round(score)}\uFF09`;
|
|
1534
|
+
}
|
|
1535
|
+
var TaskLedgerError = class extends Error {
|
|
1536
|
+
constructor(code, message) {
|
|
1537
|
+
super(message);
|
|
1538
|
+
this.name = "TaskLedgerError";
|
|
1539
|
+
this.code = code;
|
|
1540
|
+
}
|
|
1541
|
+
};
|
|
1542
|
+
var TERMINAL = /* @__PURE__ */ new Set(["done", "failed", "lost", "cancelled"]);
|
|
1543
|
+
function isTerminalState(state) {
|
|
1544
|
+
return TERMINAL.has(state);
|
|
1545
|
+
}
|
|
1546
|
+
function taskIdFor(input) {
|
|
1547
|
+
return createHash2("sha256").update(input.prompt).update("\0").update(input.inputSha256 ?? "").update("\0").update(input.deadlineClass).digest("hex").slice(0, 16);
|
|
1548
|
+
}
|
|
1549
|
+
function taskLedgerDir(agentDir, direction) {
|
|
1550
|
+
return join2(agentDir, "fabric", "tasks", direction);
|
|
1551
|
+
}
|
|
1552
|
+
function isRecord(value) {
|
|
1553
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
1554
|
+
}
|
|
1555
|
+
function validate(record) {
|
|
1556
|
+
if (!isRecord(record)) throw new TaskLedgerError("E_INVALID_PARAMS", "task must be an object");
|
|
1557
|
+
const taskId = typeof record.taskId === "string" ? record.taskId : "";
|
|
1558
|
+
if (!/^[0-9a-f]{16}$/.test(taskId)) {
|
|
1559
|
+
throw new TaskLedgerError("E_INVALID_PARAMS", "taskId must be 16 hex characters");
|
|
1560
|
+
}
|
|
1561
|
+
const state = record.state;
|
|
1562
|
+
if (typeof state !== "string" || ![
|
|
1563
|
+
"submitted",
|
|
1564
|
+
"accepted",
|
|
1565
|
+
"running",
|
|
1566
|
+
"done",
|
|
1567
|
+
"failed",
|
|
1568
|
+
"lost",
|
|
1569
|
+
"cancelled"
|
|
1570
|
+
].includes(state)) {
|
|
1571
|
+
throw new TaskLedgerError("E_INVALID_PARAMS", "unknown task state");
|
|
1572
|
+
}
|
|
1573
|
+
const deadlineClass = record.deadlineClass;
|
|
1574
|
+
if (typeof deadlineClass !== "string" || !["quick", "build", "long"].includes(deadlineClass)) {
|
|
1575
|
+
throw new TaskLedgerError("E_INVALID_PARAMS", "unknown deadline class");
|
|
1576
|
+
}
|
|
1577
|
+
return {
|
|
1578
|
+
taskId,
|
|
1579
|
+
direction: record.direction === "inbound" ? "inbound" : "outbound",
|
|
1580
|
+
peerId: typeof record.peerId === "string" ? record.peerId : "",
|
|
1581
|
+
state,
|
|
1582
|
+
deadlineClass,
|
|
1583
|
+
deadlineAt: typeof record.deadlineAt === "number" ? record.deadlineAt : 0,
|
|
1584
|
+
createdAt: typeof record.createdAt === "number" ? record.createdAt : 0,
|
|
1585
|
+
updatedAt: typeof record.updatedAt === "number" ? record.updatedAt : 0,
|
|
1586
|
+
startedAt: typeof record.startedAt === "number" ? record.startedAt : null,
|
|
1587
|
+
finishedAt: typeof record.finishedAt === "number" ? record.finishedAt : null,
|
|
1588
|
+
inputRef: isArtifactRef(record.inputRef) ? record.inputRef : null,
|
|
1589
|
+
resultRef: isArtifactRef(record.resultRef) ? record.resultRef : null,
|
|
1590
|
+
diffRef: isArtifactRef(record.diffRef) ? record.diffRef : null,
|
|
1591
|
+
workspaceHint: typeof record.workspaceHint === "string" ? record.workspaceHint : "",
|
|
1592
|
+
summary: typeof record.summary === "string" ? record.summary.slice(0, 2e3) : "",
|
|
1593
|
+
progress: typeof record.progress === "string" ? record.progress.slice(0, 200) : "",
|
|
1594
|
+
progressCode: typeof record.progressCode === "string" ? record.progressCode.slice(0, 40) : "",
|
|
1595
|
+
progressParams: record.progressParams && typeof record.progressParams === "object" ? record.progressParams : null,
|
|
1596
|
+
progressAt: typeof record.progressAt === "number" ? record.progressAt : null,
|
|
1597
|
+
files: Array.isArray(record.files) ? record.files.filter((item) => typeof item === "string").slice(0, 200) : [],
|
|
1598
|
+
exitCode: typeof record.exitCode === "number" ? record.exitCode : null,
|
|
1599
|
+
error: typeof record.error === "string" ? record.error : null,
|
|
1600
|
+
pid: typeof record.pid === "number" ? record.pid : null
|
|
1601
|
+
};
|
|
1602
|
+
}
|
|
1603
|
+
var TaskLedger = class {
|
|
1604
|
+
constructor(agentDir, direction, overrideDir) {
|
|
1605
|
+
this.direction = direction;
|
|
1606
|
+
this.dir = overrideDir ?? taskLedgerDir(agentDir, direction);
|
|
1607
|
+
}
|
|
1608
|
+
fileFor(taskId) {
|
|
1609
|
+
return join2(this.dir, `${taskId}.json`);
|
|
1610
|
+
}
|
|
1611
|
+
create(input) {
|
|
1612
|
+
const now = input.now ?? Date.now();
|
|
1613
|
+
const existing = this.get(input.taskId);
|
|
1614
|
+
if (existing) return existing;
|
|
1615
|
+
const record = {
|
|
1616
|
+
taskId: input.taskId,
|
|
1617
|
+
direction: this.direction,
|
|
1618
|
+
peerId: input.peerId,
|
|
1619
|
+
state: "submitted",
|
|
1620
|
+
deadlineClass: input.deadlineClass,
|
|
1621
|
+
deadlineAt: now + FABRIC_DEADLINE_MS[input.deadlineClass],
|
|
1622
|
+
createdAt: now,
|
|
1623
|
+
updatedAt: now,
|
|
1624
|
+
startedAt: null,
|
|
1625
|
+
finishedAt: null,
|
|
1626
|
+
inputRef: input.inputRef ?? null,
|
|
1627
|
+
resultRef: null,
|
|
1628
|
+
diffRef: null,
|
|
1629
|
+
workspaceHint: input.workspaceHint ?? "",
|
|
1630
|
+
summary: "",
|
|
1631
|
+
progress: "",
|
|
1632
|
+
progressCode: "",
|
|
1633
|
+
progressParams: null,
|
|
1634
|
+
progressAt: null,
|
|
1635
|
+
files: [],
|
|
1636
|
+
exitCode: null,
|
|
1637
|
+
error: null,
|
|
1638
|
+
pid: null
|
|
1639
|
+
};
|
|
1640
|
+
this.write(record);
|
|
1641
|
+
return record;
|
|
1642
|
+
}
|
|
1643
|
+
get(taskId) {
|
|
1644
|
+
const file = this.fileFor(taskId);
|
|
1645
|
+
if (!existsSync2(file)) return null;
|
|
1646
|
+
try {
|
|
1647
|
+
return validate(JSON.parse(readFileSync2(file, "utf8")));
|
|
1648
|
+
} catch {
|
|
1649
|
+
return null;
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
list() {
|
|
1653
|
+
if (!existsSync2(this.dir)) return [];
|
|
1654
|
+
const records = [];
|
|
1655
|
+
for (const name of readdirSync2(this.dir)) {
|
|
1656
|
+
if (!/^[0-9a-f]{16}\.json$/.test(name)) continue;
|
|
1657
|
+
const record = this.get(name.slice(0, 16));
|
|
1658
|
+
if (record) records.push(record);
|
|
1659
|
+
}
|
|
1660
|
+
return records.sort((a, b) => b.updatedAt - a.updatedAt);
|
|
1661
|
+
}
|
|
1662
|
+
update(taskId, patch, now = Date.now()) {
|
|
1663
|
+
const current = this.get(taskId);
|
|
1664
|
+
if (!current) throw new TaskLedgerError("E_TASK_UNKNOWN", `unknown task ${taskId}`);
|
|
1665
|
+
const state = patch.state ?? current.state;
|
|
1666
|
+
if (isTerminalState(current.state) && current.state !== state) {
|
|
1667
|
+
throw new TaskLedgerError("E_TASK_TERMINAL", `task ${taskId} already ${current.state}`);
|
|
1668
|
+
}
|
|
1669
|
+
const next = {
|
|
1670
|
+
...current,
|
|
1671
|
+
...patch,
|
|
1672
|
+
taskId: current.taskId,
|
|
1673
|
+
direction: current.direction,
|
|
1674
|
+
state,
|
|
1675
|
+
updatedAt: now,
|
|
1676
|
+
startedAt: patch.startedAt ?? (state === "running" && current.startedAt === null ? now : current.startedAt),
|
|
1677
|
+
finishedAt: isTerminalState(state) ? patch.finishedAt ?? now : current.finishedAt
|
|
1678
|
+
};
|
|
1679
|
+
this.write(next);
|
|
1680
|
+
return next;
|
|
1681
|
+
}
|
|
1682
|
+
/** 断线对账:超过 deadline 还没进终态就是 lost。只判「超时」,不判「网络抖动」。 */
|
|
1683
|
+
reconcile(now = Date.now()) {
|
|
1684
|
+
const lost = [];
|
|
1685
|
+
for (const record of this.list()) {
|
|
1686
|
+
if (isTerminalState(record.state)) continue;
|
|
1687
|
+
if (now <= record.deadlineAt) continue;
|
|
1688
|
+
this.update(
|
|
1689
|
+
record.taskId,
|
|
1690
|
+
{ state: "lost", error: `deadline exceeded (${record.deadlineClass})` },
|
|
1691
|
+
now
|
|
1692
|
+
);
|
|
1693
|
+
lost.push(record.taskId);
|
|
1694
|
+
}
|
|
1695
|
+
return { lost };
|
|
1696
|
+
}
|
|
1697
|
+
/** 所有被任务引用的对象 sha256:artifact 的 TTL 清理靠它区分「有主」和「无主」。 */
|
|
1698
|
+
references() {
|
|
1699
|
+
const refs = /* @__PURE__ */ new Set();
|
|
1700
|
+
for (const record of this.list()) {
|
|
1701
|
+
for (const ref of [record.inputRef, record.resultRef, record.diffRef]) {
|
|
1702
|
+
if (ref) refs.add(ref.sha256);
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1705
|
+
return [...refs];
|
|
1706
|
+
}
|
|
1707
|
+
/** 只清终态任务记录,避免把正在跑的对账信息删掉。 */
|
|
1708
|
+
prune(olderThanMs, now = Date.now()) {
|
|
1709
|
+
let removed = 0;
|
|
1710
|
+
for (const record of this.list()) {
|
|
1711
|
+
if (!isTerminalState(record.state)) continue;
|
|
1712
|
+
if (now - record.updatedAt <= olderThanMs) continue;
|
|
1713
|
+
rmSync3(this.fileFor(record.taskId), { force: true });
|
|
1714
|
+
removed += 1;
|
|
1715
|
+
}
|
|
1716
|
+
return removed;
|
|
1717
|
+
}
|
|
1718
|
+
write(record) {
|
|
1719
|
+
mkdirSync3(dirname2(this.fileFor(record.taskId)), { recursive: true });
|
|
1720
|
+
const file = this.fileFor(record.taskId);
|
|
1721
|
+
const temp = `${file}.tmp`;
|
|
1722
|
+
writeFileSync2(temp, `${JSON.stringify(record, null, 2)}
|
|
1723
|
+
`, "utf8");
|
|
1724
|
+
renameSync2(temp, file);
|
|
1725
|
+
}
|
|
1726
|
+
};
|
|
1727
|
+
|
|
1728
|
+
// src/dispatcher.ts
|
|
1729
|
+
init_transport();
|
|
1730
|
+
|
|
1731
|
+
// src/peer-store.ts
|
|
1732
|
+
init_fabric();
|
|
1733
|
+
import { chmodSync as chmodSync2, existsSync as existsSync4, mkdirSync as mkdirSync5, readFileSync as readFileSync4, renameSync as renameSync4, writeFileSync as writeFileSync4 } from "node:fs";
|
|
1734
|
+
import { dirname as dirname4, join as join4 } from "node:path";
|
|
1735
|
+
var MAX_PEERS = 12;
|
|
1736
|
+
var MAX_PEER_NAME_CHARS = 60;
|
|
1737
|
+
var MAX_ADDRESS_CHARS = 255;
|
|
1738
|
+
var PEERS_SCHEMA = 1;
|
|
1739
|
+
var PeerStoreError = class extends Error {
|
|
1740
|
+
constructor(message, code = "E_INVALID_PARAMS") {
|
|
1741
|
+
super(message);
|
|
1742
|
+
this.name = "PeerStoreError";
|
|
1743
|
+
this.code = code;
|
|
1744
|
+
}
|
|
1745
|
+
};
|
|
1746
|
+
function peersStorePath(agentDir) {
|
|
1747
|
+
return join4(agentDir, "fabric", "peers.json");
|
|
1748
|
+
}
|
|
1749
|
+
var overridePath2 = null;
|
|
1750
|
+
function resolvePath2(agentDir) {
|
|
1751
|
+
return overridePath2 ?? peersStorePath(agentDir);
|
|
1752
|
+
}
|
|
1753
|
+
function isRecord3(value) {
|
|
1754
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
1755
|
+
}
|
|
1756
|
+
function sanitizePeerName(raw) {
|
|
1757
|
+
const name = typeof raw === "string" ? raw.replace(/\s+/g, " ").trim() : "";
|
|
1758
|
+
if (!name) throw new PeerStoreError("peer name is required");
|
|
1759
|
+
if (name.length > MAX_PEER_NAME_CHARS) {
|
|
1760
|
+
throw new PeerStoreError(`peer name must be at most ${MAX_PEER_NAME_CHARS} characters`);
|
|
1761
|
+
}
|
|
1762
|
+
return name;
|
|
1763
|
+
}
|
|
1764
|
+
function sanitizeAddress(raw) {
|
|
1765
|
+
const address = typeof raw === "string" ? raw.trim() : "";
|
|
1766
|
+
if (!address) throw new PeerStoreError("peer address is required");
|
|
1767
|
+
if (address.length > MAX_ADDRESS_CHARS) {
|
|
1768
|
+
throw new PeerStoreError(`peer address must be at most ${MAX_ADDRESS_CHARS} characters`);
|
|
1769
|
+
}
|
|
1770
|
+
if (!/^[A-Za-z0-9._:-]+$/.test(address)) {
|
|
1771
|
+
throw new PeerStoreError("peer address contains unsupported characters");
|
|
1772
|
+
}
|
|
1773
|
+
return address;
|
|
1774
|
+
}
|
|
1775
|
+
function sanitizePort(raw) {
|
|
1776
|
+
const port = typeof raw === "number" ? raw : Number.parseInt(String(raw ?? ""), 10);
|
|
1777
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535) {
|
|
1778
|
+
throw new PeerStoreError("peer port must be an integer in 1..65535");
|
|
1779
|
+
}
|
|
1780
|
+
return port;
|
|
1781
|
+
}
|
|
1782
|
+
function sanitizeGrants(raw) {
|
|
1783
|
+
return typeof raw === "string" && FABRIC_GRANTS.includes(raw) ? raw : "read-only";
|
|
1784
|
+
}
|
|
1785
|
+
function sanitizeFeatures(raw) {
|
|
1786
|
+
if (!Array.isArray(raw)) return [];
|
|
1787
|
+
const wanted = new Set(raw.filter((item) => typeof item === "string"));
|
|
1788
|
+
return FABRIC_FEATURES.filter((feature) => wanted.has(feature));
|
|
1789
|
+
}
|
|
1790
|
+
function sanitizeNodeId(raw) {
|
|
1791
|
+
const nodeId = typeof raw === "string" ? raw.trim().toLowerCase() : "";
|
|
1792
|
+
if (!/^[0-9a-f]{16}$/.test(nodeId)) {
|
|
1793
|
+
throw new PeerStoreError("nodeId must be 16 lowercase hex characters");
|
|
1794
|
+
}
|
|
1795
|
+
return nodeId;
|
|
1796
|
+
}
|
|
1797
|
+
function validatePeer(raw) {
|
|
1798
|
+
if (!isRecord3(raw)) throw new PeerStoreError("peer must be an object");
|
|
1799
|
+
const now = Date.now();
|
|
1800
|
+
const createdAt = typeof raw.createdAt === "number" ? raw.createdAt : now;
|
|
1801
|
+
return {
|
|
1802
|
+
nodeId: sanitizeNodeId(raw.nodeId),
|
|
1803
|
+
name: sanitizePeerName(raw.name),
|
|
1804
|
+
address: sanitizeAddress(raw.address),
|
|
1805
|
+
port: sanitizePort(raw.port),
|
|
1806
|
+
grants: sanitizeGrants(raw.grants),
|
|
1807
|
+
features: sanitizeFeatures(raw.features),
|
|
1808
|
+
appVersion: typeof raw.appVersion === "string" ? raw.appVersion.slice(0, 32) : "",
|
|
1809
|
+
pairedAt: typeof raw.pairedAt === "number" ? raw.pairedAt : createdAt,
|
|
1810
|
+
createdAt,
|
|
1811
|
+
updatedAt: typeof raw.updatedAt === "number" ? raw.updatedAt : createdAt,
|
|
1812
|
+
lastSeenAt: typeof raw.lastSeenAt === "number" ? raw.lastSeenAt : null
|
|
1813
|
+
};
|
|
1814
|
+
}
|
|
1815
|
+
function readFile(file) {
|
|
1816
|
+
const empty = { extras: {}, raw: /* @__PURE__ */ new Map(), peers: [] };
|
|
1817
|
+
if (!existsSync4(file)) return empty;
|
|
1818
|
+
try {
|
|
1819
|
+
const parsed = JSON.parse(readFileSync4(file, "utf8"));
|
|
1820
|
+
const container = isRecord3(parsed) ? parsed : {};
|
|
1821
|
+
const peersRaw = Array.isArray(parsed) ? parsed : Array.isArray(container.peers) ? container.peers : [];
|
|
1822
|
+
const extras = {};
|
|
1823
|
+
for (const [key, value] of Object.entries(container)) {
|
|
1824
|
+
if (key === "peers" || key === "schemaVersion") continue;
|
|
1825
|
+
extras[key] = value;
|
|
1826
|
+
}
|
|
1827
|
+
const raw = /* @__PURE__ */ new Map();
|
|
1828
|
+
const peers = [];
|
|
1829
|
+
for (const item of peersRaw) {
|
|
1830
|
+
try {
|
|
1831
|
+
const peer = validatePeer(item);
|
|
1832
|
+
peers.push(peer);
|
|
1833
|
+
if (isRecord3(item)) raw.set(peer.nodeId, item);
|
|
1834
|
+
} catch {
|
|
1835
|
+
}
|
|
1836
|
+
}
|
|
1837
|
+
return { extras, raw, peers };
|
|
1838
|
+
} catch {
|
|
1839
|
+
return empty;
|
|
1840
|
+
}
|
|
1841
|
+
}
|
|
1842
|
+
function writeFile(file, data) {
|
|
1843
|
+
mkdirSync5(dirname4(file), { recursive: true });
|
|
1844
|
+
const peers = data.peers.map((peer) => ({
|
|
1845
|
+
...data.raw.get(peer.nodeId) ?? {},
|
|
1846
|
+
...peer
|
|
1847
|
+
}));
|
|
1848
|
+
const payload = { ...data.extras, schemaVersion: PEERS_SCHEMA, peers };
|
|
1849
|
+
const temp = `${file}.tmp`;
|
|
1850
|
+
writeFileSync4(temp, `${JSON.stringify(payload, null, 2)}
|
|
1851
|
+
`, "utf8");
|
|
1852
|
+
renameSync4(temp, file);
|
|
1853
|
+
if (process.platform !== "win32") {
|
|
1854
|
+
try {
|
|
1855
|
+
chmodSync2(file, 384);
|
|
1856
|
+
} catch {
|
|
1857
|
+
}
|
|
1858
|
+
}
|
|
1859
|
+
}
|
|
1860
|
+
function listPeers(agentDir) {
|
|
1861
|
+
return readFile(resolvePath2(agentDir)).peers.slice().sort((a, b) => b.pairedAt - a.pairedAt);
|
|
1862
|
+
}
|
|
1863
|
+
function getPeer(agentDir, nodeId) {
|
|
1864
|
+
const wanted = sanitizeNodeId(nodeId);
|
|
1865
|
+
return readFile(resolvePath2(agentDir)).peers.find((peer) => peer.nodeId === wanted) ?? null;
|
|
1866
|
+
}
|
|
1867
|
+
function savePeer(agentDir, input) {
|
|
1868
|
+
const file = resolvePath2(agentDir);
|
|
1869
|
+
const data = readFile(file);
|
|
1870
|
+
const now = Date.now();
|
|
1871
|
+
const existing = data.peers.find((peer) => peer.nodeId === input.nodeId);
|
|
1872
|
+
const merged = validatePeer({
|
|
1873
|
+
...existing,
|
|
1874
|
+
...input,
|
|
1875
|
+
createdAt: existing?.createdAt ?? input.createdAt ?? now,
|
|
1876
|
+
pairedAt: input.pairedAt ?? existing?.pairedAt ?? now,
|
|
1877
|
+
updatedAt: now,
|
|
1878
|
+
lastSeenAt: input.lastSeenAt ?? existing?.lastSeenAt ?? null
|
|
1879
|
+
});
|
|
1880
|
+
if (existing) {
|
|
1881
|
+
data.peers = data.peers.map((peer) => peer.nodeId === merged.nodeId ? merged : peer);
|
|
1882
|
+
} else {
|
|
1883
|
+
if (data.peers.length >= MAX_PEERS) {
|
|
1884
|
+
throw new PeerStoreError(
|
|
1885
|
+
`too many peers (max ${MAX_PEERS}); unpair one first`,
|
|
1886
|
+
"E_PEER_LIMIT"
|
|
1887
|
+
);
|
|
1888
|
+
}
|
|
1889
|
+
data.peers.push(merged);
|
|
1890
|
+
}
|
|
1891
|
+
writeFile(file, data);
|
|
1892
|
+
return merged;
|
|
1893
|
+
}
|
|
1894
|
+
function touchPeer(agentDir, nodeId, at = Date.now()) {
|
|
1895
|
+
const peer = getPeer(agentDir, nodeId);
|
|
1896
|
+
if (!peer) return null;
|
|
1897
|
+
return savePeer(agentDir, { ...peer, lastSeenAt: at, grants: peer.grants });
|
|
1898
|
+
}
|
|
1899
|
+
function deletePeer(agentDir, nodeId) {
|
|
1900
|
+
const file = resolvePath2(agentDir);
|
|
1901
|
+
const wanted = sanitizeNodeId(nodeId);
|
|
1902
|
+
const data = readFile(file);
|
|
1903
|
+
const next = data.peers.filter((peer) => peer.nodeId !== wanted);
|
|
1904
|
+
if (next.length === data.peers.length) return false;
|
|
1905
|
+
data.peers = next;
|
|
1906
|
+
data.raw.delete(wanted);
|
|
1907
|
+
writeFile(file, data);
|
|
1908
|
+
return true;
|
|
1909
|
+
}
|
|
1910
|
+
|
|
1911
|
+
// src/history.ts
|
|
1912
|
+
import { existsSync as existsSync5, mkdirSync as mkdirSync6, readFileSync as readFileSync5, renameSync as renameSync5, writeFileSync as writeFileSync5 } from "node:fs";
|
|
1913
|
+
import { dirname as dirname5, join as join5 } from "node:path";
|
|
1914
|
+
var HISTORY_SAMPLES = 20;
|
|
1915
|
+
var HISTORY_MAX_KEYS = 32;
|
|
1916
|
+
function historyKey(labels) {
|
|
1917
|
+
const clean = [...new Set(labels.map((label) => label.trim().toLowerCase()).filter(Boolean))].sort();
|
|
1918
|
+
return clean.length === 0 ? "*" : clean.join(",");
|
|
1919
|
+
}
|
|
1920
|
+
function historyPath(agentDir) {
|
|
1921
|
+
return join5(agentDir, "fabric", "history.json");
|
|
1922
|
+
}
|
|
1923
|
+
function median(values) {
|
|
1924
|
+
if (values.length === 0) return null;
|
|
1925
|
+
const sorted = [...values].sort((a, b) => a - b);
|
|
1926
|
+
const middle = Math.floor(sorted.length / 2);
|
|
1927
|
+
return sorted.length % 2 === 1 ? sorted[middle] ?? 0 : Math.round(((sorted[middle - 1] ?? 0) + (sorted[middle] ?? 0)) / 2);
|
|
1928
|
+
}
|
|
1929
|
+
var FabricHistory = class {
|
|
1930
|
+
constructor(agentDir, overridePath3) {
|
|
1931
|
+
this.book = null;
|
|
1932
|
+
this.agentDir = agentDir;
|
|
1933
|
+
this.overridePath = overridePath3 ?? null;
|
|
1934
|
+
}
|
|
1935
|
+
file() {
|
|
1936
|
+
return this.overridePath ?? historyPath(this.agentDir);
|
|
1937
|
+
}
|
|
1938
|
+
read() {
|
|
1939
|
+
if (this.book) return this.book;
|
|
1940
|
+
try {
|
|
1941
|
+
const file = this.file();
|
|
1942
|
+
if (!existsSync5(file)) {
|
|
1943
|
+
this.book = {};
|
|
1944
|
+
return this.book;
|
|
1945
|
+
}
|
|
1946
|
+
const raw = JSON.parse(readFileSync5(file, "utf8"));
|
|
1947
|
+
const book = {};
|
|
1948
|
+
if (raw && typeof raw === "object") {
|
|
1949
|
+
for (const [key, value] of Object.entries(raw)) {
|
|
1950
|
+
if (!value || typeof value !== "object") continue;
|
|
1951
|
+
const entry = value;
|
|
1952
|
+
const samples = Array.isArray(entry.samples) ? entry.samples.filter((item) => typeof item === "number" && item >= 0) : [];
|
|
1953
|
+
book[key] = {
|
|
1954
|
+
samples: samples.slice(-HISTORY_SAMPLES),
|
|
1955
|
+
lastOk: entry.lastOk === true,
|
|
1956
|
+
updatedAt: typeof entry.updatedAt === "number" ? entry.updatedAt : 0
|
|
1957
|
+
};
|
|
1958
|
+
}
|
|
1959
|
+
}
|
|
1960
|
+
this.book = book;
|
|
1961
|
+
} catch {
|
|
1962
|
+
this.book = {};
|
|
1963
|
+
}
|
|
1964
|
+
return this.book;
|
|
1965
|
+
}
|
|
1966
|
+
write() {
|
|
1967
|
+
const book = this.read();
|
|
1968
|
+
const keys = Object.keys(book);
|
|
1969
|
+
if (keys.length > HISTORY_MAX_KEYS) {
|
|
1970
|
+
const keep = keys.sort((a, b) => (book[b]?.updatedAt ?? 0) - (book[a]?.updatedAt ?? 0)).slice(0, HISTORY_MAX_KEYS);
|
|
1971
|
+
for (const key of keys) if (!keep.includes(key)) delete book[key];
|
|
1972
|
+
}
|
|
1973
|
+
try {
|
|
1974
|
+
const file = this.file();
|
|
1975
|
+
mkdirSync6(dirname5(file), { recursive: true });
|
|
1976
|
+
const temp = `${file}.${process.pid}.tmp`;
|
|
1977
|
+
writeFileSync5(temp, `${JSON.stringify(book, null, 2)}
|
|
1978
|
+
`, "utf8");
|
|
1979
|
+
renameSync5(temp, file);
|
|
1980
|
+
} catch {
|
|
1981
|
+
}
|
|
1982
|
+
}
|
|
1983
|
+
record(labels, durationMs, ok, now = Date.now()) {
|
|
1984
|
+
const key = typeof labels === "string" ? labels : historyKey(labels);
|
|
1985
|
+
const book = this.read();
|
|
1986
|
+
const current = book[key] ?? { samples: [], lastOk: false, updatedAt: now };
|
|
1987
|
+
const samples = [...current.samples, Math.max(0, Math.round(durationMs))].slice(-HISTORY_SAMPLES);
|
|
1988
|
+
book[key] = { samples, lastOk: ok, updatedAt: now };
|
|
1989
|
+
this.write();
|
|
1990
|
+
}
|
|
1991
|
+
/** 中位耗时;没有样本返回 null(调用方据此区分「没跑过」与「跑了 0 秒」)。 */
|
|
1992
|
+
p50(labels) {
|
|
1993
|
+
const key = typeof labels === "string" ? labels : historyKey(labels);
|
|
1994
|
+
return median(this.read()[key]?.samples ?? []);
|
|
1995
|
+
}
|
|
1996
|
+
snapshot() {
|
|
1997
|
+
return { ...this.read() };
|
|
1998
|
+
}
|
|
1999
|
+
};
|
|
2000
|
+
|
|
2001
|
+
// src/host-load.ts
|
|
2002
|
+
import { cpus, freemem, loadavg } from "node:os";
|
|
2003
|
+
function cpuLoad() {
|
|
2004
|
+
const cores = cpus().length || 1;
|
|
2005
|
+
const average = loadavg()[0] ?? 0;
|
|
2006
|
+
if (!(average > 0)) return null;
|
|
2007
|
+
return Math.min(1, average / cores);
|
|
2008
|
+
}
|
|
2009
|
+
function memAvailableMb() {
|
|
2010
|
+
return Math.round(freemem() / (1024 * 1024));
|
|
2011
|
+
}
|
|
2012
|
+
|
|
2013
|
+
// src/dispatcher.ts
|
|
2014
|
+
var LABEL_MAX = 8;
|
|
2015
|
+
var LABEL_CHARS = 24;
|
|
2016
|
+
function sanitizeLabels(raw) {
|
|
2017
|
+
if (!Array.isArray(raw)) return [];
|
|
2018
|
+
const labels = raw.filter((item) => typeof item === "string").map((item) => item.trim().toLowerCase()).filter((item) => item && item.length <= LABEL_CHARS);
|
|
2019
|
+
return [...new Set(labels)].slice(0, LABEL_MAX);
|
|
2020
|
+
}
|
|
2021
|
+
var FabricDispatcher = class {
|
|
2022
|
+
constructor(options) {
|
|
2023
|
+
this.links = /* @__PURE__ */ new Map();
|
|
2024
|
+
this.loads = /* @__PURE__ */ new Map();
|
|
2025
|
+
/** 常驻连接:配对即连,不手动取消就一直连着(指数退避,永不放弃)。 */
|
|
2026
|
+
this.connections = /* @__PURE__ */ new Map();
|
|
2027
|
+
this.inflight = /* @__PURE__ */ new Map();
|
|
2028
|
+
this.historyStore = null;
|
|
2029
|
+
/** taskId -> 历史标签键:任务落终态时才知道耗时,靠这张表把两边对上。 */
|
|
2030
|
+
this.historyKeyByTask = /* @__PURE__ */ new Map();
|
|
2031
|
+
/** B 侧上报的能力标签(例如 gpu / build / long-running)。 */
|
|
2032
|
+
this.labels = null;
|
|
2033
|
+
this.options = options;
|
|
2034
|
+
this.artifacts = options.artifacts ?? new ArtifactStore(options.agentDir);
|
|
2035
|
+
this.outbound = options.outbound ?? new TaskLedger(options.agentDir, "outbound");
|
|
2036
|
+
this.inbound = options.inbound ?? new TaskLedger(options.agentDir, "inbound");
|
|
2037
|
+
}
|
|
2038
|
+
history() {
|
|
2039
|
+
this.historyStore ??= new FabricHistory(this.options.agentDir);
|
|
2040
|
+
return this.historyStore;
|
|
2041
|
+
}
|
|
2042
|
+
/** 任务终态时写一条历史;没有标签键就不记(测试注入的假任务没有标签)。 */
|
|
2043
|
+
recordOutcome(taskId, ok) {
|
|
2044
|
+
const key = this.historyKeyByTask.get(taskId);
|
|
2045
|
+
this.historyKeyByTask.delete(taskId);
|
|
2046
|
+
if (!key) return;
|
|
2047
|
+
const startedAt = this.outbound.get(taskId)?.startedAt ?? null;
|
|
2048
|
+
const duration = startedAt === null ? 0 : Math.max(0, this.now() - startedAt);
|
|
2049
|
+
this.history().record(key, duration, ok, this.now());
|
|
2050
|
+
}
|
|
2051
|
+
now() {
|
|
2052
|
+
return this.options.now?.() ?? Date.now();
|
|
2053
|
+
}
|
|
2054
|
+
/** 已配对的机器从这里进;连接失败只记日志,不抛(断线是常态,不是异常)。 */
|
|
2055
|
+
async linkFor(peer) {
|
|
2056
|
+
const persistent = this.connections.get(peer.nodeId)?.current();
|
|
2057
|
+
if (persistent?.connected) {
|
|
2058
|
+
this.links.set(peer.nodeId, persistent);
|
|
2059
|
+
return persistent;
|
|
2060
|
+
}
|
|
2061
|
+
const existing = this.links.get(peer.nodeId);
|
|
2062
|
+
if (existing?.connected) return existing;
|
|
2063
|
+
try {
|
|
2064
|
+
const connect = this.options.connect ?? (async (target) => {
|
|
2065
|
+
const { dialFabricLink: dialFabricLink2 } = await Promise.resolve().then(() => (init_transport(), transport_exports));
|
|
2066
|
+
return dialFabricLink2({
|
|
2067
|
+
identity: this.options.identity,
|
|
2068
|
+
peer: { nodeId: target.nodeId, address: target.address, port: target.port },
|
|
2069
|
+
appVersion: this.options.appVersion ?? "",
|
|
2070
|
+
log: this.options.log
|
|
2071
|
+
});
|
|
2072
|
+
});
|
|
2073
|
+
const link = await connect(peer);
|
|
2074
|
+
this.links.set(peer.nodeId, link);
|
|
2075
|
+
return link;
|
|
2076
|
+
} catch (error) {
|
|
2077
|
+
this.options.log?.(
|
|
2078
|
+
`fabric connect failed (${peer.nodeId}): ${error instanceof Error ? error.message : String(error)}`
|
|
2079
|
+
);
|
|
2080
|
+
this.links.delete(peer.nodeId);
|
|
2081
|
+
return null;
|
|
2082
|
+
}
|
|
2083
|
+
}
|
|
2084
|
+
/** 刷新每台机器「在不在 / 忙不忙 / 会什么」——这些信息只在宿主内存里。 */
|
|
2085
|
+
async refreshLoads(peers = listPeers(this.options.agentDir)) {
|
|
2086
|
+
const result = [];
|
|
2087
|
+
for (const peer of peers) {
|
|
2088
|
+
const link = await this.linkFor(peer);
|
|
2089
|
+
if (!link) {
|
|
2090
|
+
result.push({ nodeId: peer.nodeId, online: false, queueDepth: 9, hbAgeMs: null, labels: [] });
|
|
2091
|
+
continue;
|
|
2092
|
+
}
|
|
2093
|
+
try {
|
|
2094
|
+
const raw = await link.call("peer.status", {});
|
|
2095
|
+
const load = {
|
|
2096
|
+
nodeId: peer.nodeId,
|
|
2097
|
+
online: raw.online !== false,
|
|
2098
|
+
queueDepth: typeof raw.queueDepth === "number" ? raw.queueDepth : 0,
|
|
2099
|
+
hbAgeMs: typeof raw.hbAgeMs === "number" ? raw.hbAgeMs : 0,
|
|
2100
|
+
labels: sanitizeLabels(raw.labels),
|
|
2101
|
+
cpuLoad: typeof raw.cpuLoad === "number" ? raw.cpuLoad : null,
|
|
2102
|
+
memAvailableMb: typeof raw.memAvailableMb === "number" ? raw.memAvailableMb : null
|
|
2103
|
+
};
|
|
2104
|
+
this.loads.set(peer.nodeId, load);
|
|
2105
|
+
result.push(load);
|
|
2106
|
+
touchPeer(this.options.agentDir, peer.nodeId, this.now());
|
|
2107
|
+
} catch {
|
|
2108
|
+
result.push({ nodeId: peer.nodeId, online: false, queueDepth: 9, hbAgeMs: null, labels: [] });
|
|
2109
|
+
}
|
|
2110
|
+
}
|
|
2111
|
+
return result;
|
|
2112
|
+
}
|
|
2113
|
+
candidates(loads, peers = listPeers(this.options.agentDir)) {
|
|
2114
|
+
return loads.map((load) => {
|
|
2115
|
+
const peer = peers.find((item) => item.nodeId === load.nodeId);
|
|
2116
|
+
return {
|
|
2117
|
+
nodeId: load.nodeId,
|
|
2118
|
+
name: peer?.name ?? load.nodeId,
|
|
2119
|
+
online: load.online,
|
|
2120
|
+
hbAgeMs: load.hbAgeMs,
|
|
2121
|
+
queueDepth: load.queueDepth,
|
|
2122
|
+
labels: load.labels,
|
|
2123
|
+
grants: peer?.grants ?? "read-only",
|
|
2124
|
+
cpuLoad: load.cpuLoad ?? null,
|
|
2125
|
+
historyP50Ms: this.history().p50(load.labels)
|
|
2126
|
+
};
|
|
2127
|
+
});
|
|
2128
|
+
}
|
|
2129
|
+
/** 派活:选机器 -> 存输入 -> 记账 -> 发给对端。 */
|
|
2130
|
+
async submit(input) {
|
|
2131
|
+
if (!(input.estimatedMs >= REMOTE_MIN_ESTIMATE_MS)) {
|
|
2132
|
+
return {
|
|
2133
|
+
ok: false,
|
|
2134
|
+
code: "E_LOCAL_FASTER",
|
|
2135
|
+
reason: `\u9884\u8BA1 ${input.estimatedMs}ms < ${REMOTE_MIN_ESTIMATE_MS}ms\uFF0C\u672C\u5730\u8DD1\u66F4\u5FEB`
|
|
2136
|
+
};
|
|
2137
|
+
}
|
|
2138
|
+
const peers = listPeers(this.options.agentDir);
|
|
2139
|
+
const loads = await this.refreshLoads(peers);
|
|
2140
|
+
const needLabels = sanitizeLabels(input.labels ?? []);
|
|
2141
|
+
const decision = choosePeer(this.candidates(loads, peers), {
|
|
2142
|
+
labels: needLabels,
|
|
2143
|
+
estimatedMs: input.estimatedMs,
|
|
2144
|
+
grant: input.grant,
|
|
2145
|
+
pin: input.pin ?? null
|
|
2146
|
+
});
|
|
2147
|
+
if (decision.ok === false) {
|
|
2148
|
+
return { ok: false, code: decision.code, reason: decision.reason };
|
|
2149
|
+
}
|
|
2150
|
+
const peer = peers.find((item) => item.nodeId === decision.peerId);
|
|
2151
|
+
if (!peer) return { ok: false, code: "E_PEER_UNKNOWN", reason: "peer record disappeared" };
|
|
2152
|
+
const inputRef = input.input ? this.artifacts.put(input.input, "input") : null;
|
|
2153
|
+
const taskId = taskIdFor({
|
|
2154
|
+
prompt: input.prompt,
|
|
2155
|
+
deadlineClass: input.deadlineClass,
|
|
2156
|
+
inputSha256: inputRef?.sha256 ?? null
|
|
2157
|
+
});
|
|
2158
|
+
this.historyKeyByTask.set(taskId, historyKey(needLabels));
|
|
2159
|
+
const record = this.outbound.create({
|
|
2160
|
+
taskId,
|
|
2161
|
+
peerId: peer.nodeId,
|
|
2162
|
+
deadlineClass: input.deadlineClass,
|
|
2163
|
+
workspaceHint: input.workspaceHint ?? "",
|
|
2164
|
+
inputRef,
|
|
2165
|
+
now: this.now()
|
|
2166
|
+
});
|
|
2167
|
+
if (record.state === "done" || record.state === "running") {
|
|
2168
|
+
return { ok: true, taskId, peerId: peer.nodeId, reason: "already dispatched (idempotent)" };
|
|
2169
|
+
}
|
|
2170
|
+
const link = await this.linkFor(peer);
|
|
2171
|
+
if (!link) return { ok: false, code: "E_PEER_OFFLINE", reason: `${peer.name} \u8FDE\u4E0D\u4E0A` };
|
|
2172
|
+
try {
|
|
2173
|
+
if (inputRef && input.input) {
|
|
2174
|
+
await link.call("artifact.put", {
|
|
2175
|
+
sha256: inputRef.sha256,
|
|
2176
|
+
len: inputRef.len,
|
|
2177
|
+
kind: inputRef.kind,
|
|
2178
|
+
data: input.input.toString("base64")
|
|
2179
|
+
});
|
|
2180
|
+
}
|
|
2181
|
+
await link.call("task.submit", {
|
|
2182
|
+
taskId,
|
|
2183
|
+
prompt: input.prompt,
|
|
2184
|
+
deadlineClass: input.deadlineClass,
|
|
2185
|
+
grant: peer.grants,
|
|
2186
|
+
workspaceHint: input.workspaceHint ?? "",
|
|
2187
|
+
inputRef
|
|
2188
|
+
});
|
|
2189
|
+
this.advance(taskId, { state: "accepted" });
|
|
2190
|
+
return { ok: true, taskId, peerId: peer.nodeId, reason: decision.reason };
|
|
2191
|
+
} catch (error) {
|
|
2192
|
+
this.advance(taskId, {
|
|
2193
|
+
state: "failed",
|
|
2194
|
+
error: error instanceof Error ? error.message : String(error)
|
|
2195
|
+
});
|
|
2196
|
+
return { ok: false, code: "E_DISPATCH_FAILED", reason: "\u6295\u9012\u5931\u8D25\uFF08\u4EFB\u52A1\u5DF2\u8BB0\u8D26\uFF0C\u53EF\u91CD\u8BD5\u540C\u4E00 taskId\uFF09" };
|
|
2197
|
+
}
|
|
2198
|
+
}
|
|
2199
|
+
/**
|
|
2200
|
+
* 对账:先把超时的判 lost,再向对端要状态。
|
|
2201
|
+
* 断线期间对端可能已经干完了——所以「问」永远优先于「重派」。
|
|
2202
|
+
*/
|
|
2203
|
+
async reconcile() {
|
|
2204
|
+
const { lost } = this.outbound.reconcile(this.now());
|
|
2205
|
+
const done = [];
|
|
2206
|
+
const peers = listPeers(this.options.agentDir);
|
|
2207
|
+
for (const record of this.outbound.list()) {
|
|
2208
|
+
if (record.state === "done" || record.state === "failed" || record.state === "lost") continue;
|
|
2209
|
+
const peer = peers.find((item) => item.nodeId === record.peerId);
|
|
2210
|
+
if (!peer) continue;
|
|
2211
|
+
const link = await this.linkFor(peer);
|
|
2212
|
+
if (!link) continue;
|
|
2213
|
+
try {
|
|
2214
|
+
const status = await link.call("task.status", { taskId: record.taskId });
|
|
2215
|
+
const state = typeof status.state === "string" ? status.state : "";
|
|
2216
|
+
if (state === "done") {
|
|
2217
|
+
const resultRef = await this.pullResult(link, record, status);
|
|
2218
|
+
const diffRef = await this.pullArtifact(link, status.diffRef);
|
|
2219
|
+
this.outbound.update(
|
|
2220
|
+
record.taskId,
|
|
2221
|
+
{
|
|
2222
|
+
state: "done",
|
|
2223
|
+
resultRef,
|
|
2224
|
+
...diffRef ? { diffRef } : {},
|
|
2225
|
+
summary: typeof status.summary === "string" ? status.summary : "",
|
|
2226
|
+
files: Array.isArray(status.files) ? status.files.filter((item) => typeof item === "string") : [],
|
|
2227
|
+
exitCode: typeof status.exitCode === "number" ? status.exitCode : null
|
|
2228
|
+
},
|
|
2229
|
+
this.now()
|
|
2230
|
+
);
|
|
2231
|
+
this.recordOutcome(record.taskId, true);
|
|
2232
|
+
done.push(record.taskId);
|
|
2233
|
+
} else if (state === "failed") {
|
|
2234
|
+
this.outbound.update(
|
|
2235
|
+
record.taskId,
|
|
2236
|
+
{ state: "failed", error: typeof status.error === "string" ? status.error : "remote failure" },
|
|
2237
|
+
this.now()
|
|
2238
|
+
);
|
|
2239
|
+
this.recordOutcome(record.taskId, false);
|
|
2240
|
+
} else if (state === "running" && record.state !== "running") {
|
|
2241
|
+
this.outbound.update(record.taskId, { state: "running" }, this.now());
|
|
2242
|
+
}
|
|
2243
|
+
} catch {
|
|
2244
|
+
}
|
|
2245
|
+
}
|
|
2246
|
+
return { lost, done };
|
|
2247
|
+
}
|
|
2248
|
+
/** 只允许把任务往前推:终态不可回退,也不会被迟到的 accepted/failed 覆盖。 */
|
|
2249
|
+
advance(taskId, patch) {
|
|
2250
|
+
const current = this.outbound.get(taskId);
|
|
2251
|
+
if (!current || isTerminalState(current.state)) return;
|
|
2252
|
+
this.outbound.update(taskId, patch, this.now());
|
|
2253
|
+
}
|
|
2254
|
+
pullResult(link, record, status) {
|
|
2255
|
+
void record;
|
|
2256
|
+
return this.pullArtifact(link, status.resultRef);
|
|
2257
|
+
}
|
|
2258
|
+
/** 按引用把产物拉到本机;拉不到就保留引用(下次对账/按需再取,不把已完成的任务判死)。 */
|
|
2259
|
+
async pullArtifact(link, raw) {
|
|
2260
|
+
const ref = raw;
|
|
2261
|
+
if (!ref || typeof ref !== "object") return null;
|
|
2262
|
+
const candidate = ref;
|
|
2263
|
+
if (typeof candidate.sha256 !== "string") return null;
|
|
2264
|
+
if (this.artifacts.has(candidate.sha256)) return candidate;
|
|
2265
|
+
try {
|
|
2266
|
+
const pulled = await link.call("artifact.get", {
|
|
2267
|
+
sha256: candidate.sha256,
|
|
2268
|
+
len: candidate.len,
|
|
2269
|
+
kind: candidate.kind
|
|
2270
|
+
});
|
|
2271
|
+
if (typeof pulled.data !== "string") return candidate;
|
|
2272
|
+
const stored = this.artifacts.put(Buffer.from(pulled.data, "base64"), candidate.kind ?? "result");
|
|
2273
|
+
return stored.sha256 === candidate.sha256 ? stored : candidate;
|
|
2274
|
+
} catch {
|
|
2275
|
+
return candidate;
|
|
2276
|
+
}
|
|
2277
|
+
}
|
|
2278
|
+
/** A 侧收到的事件:对端说它干完了 / 干挂了,直接落台账。 */
|
|
2279
|
+
async applyEvent(frame) {
|
|
2280
|
+
const taskId = typeof frame.taskId === "string" ? frame.taskId : "";
|
|
2281
|
+
const record = this.outbound.get(taskId);
|
|
2282
|
+
if (!record) return;
|
|
2283
|
+
if (frame.type === "task_done") {
|
|
2284
|
+
const link = this.links.get(record.peerId);
|
|
2285
|
+
const diffRef = link ? await this.pullArtifact(link, frame.diffRef) : isArtifactRef(frame.diffRef) ? frame.diffRef : null;
|
|
2286
|
+
this.outbound.update(
|
|
2287
|
+
taskId,
|
|
2288
|
+
{
|
|
2289
|
+
state: "done",
|
|
2290
|
+
diffRef,
|
|
2291
|
+
summary: typeof frame.summary === "string" ? frame.summary : "",
|
|
2292
|
+
exitCode: typeof frame.exitCode === "number" ? frame.exitCode : null,
|
|
2293
|
+
files: Array.isArray(frame.files) ? frame.files.filter((item) => typeof item === "string") : []
|
|
2294
|
+
},
|
|
2295
|
+
this.now()
|
|
2296
|
+
);
|
|
2297
|
+
this.recordOutcome(taskId, true);
|
|
2298
|
+
return;
|
|
2299
|
+
}
|
|
2300
|
+
if (frame.type === "task_progress") {
|
|
2301
|
+
this.advance(taskId, {
|
|
2302
|
+
progress: typeof frame.text === "string" ? frame.text.slice(0, 200) : "",
|
|
2303
|
+
progressCode: typeof frame.code === "string" ? frame.code.slice(0, 40) : "",
|
|
2304
|
+
progressParams: frame.params && typeof frame.params === "object" ? frame.params : null,
|
|
2305
|
+
progressAt: this.now()
|
|
2306
|
+
});
|
|
2307
|
+
return;
|
|
2308
|
+
}
|
|
2309
|
+
if (frame.type === "task_failed") {
|
|
2310
|
+
this.outbound.update(
|
|
2311
|
+
taskId,
|
|
2312
|
+
{ state: "failed", error: typeof frame.error === "string" ? frame.error : "remote failure" },
|
|
2313
|
+
this.now()
|
|
2314
|
+
);
|
|
2315
|
+
this.recordOutcome(taskId, false);
|
|
2316
|
+
}
|
|
2317
|
+
}
|
|
2318
|
+
/**
|
|
2319
|
+
* B 侧入口:所有入站方法都在这里。
|
|
2320
|
+
* 未配对的调用根本到不了这一层(握手阶段已拒绝),这里只做档位与参数校验。
|
|
2321
|
+
*/
|
|
2322
|
+
async handleInbound(method, params, caller = { nodeId: "", grants: "read-only" }) {
|
|
2323
|
+
switch (method) {
|
|
2324
|
+
case "peer.status":
|
|
2325
|
+
return {
|
|
2326
|
+
online: true,
|
|
2327
|
+
queueDepth: this.inflight.size,
|
|
2328
|
+
hbAgeMs: 0,
|
|
2329
|
+
labels: this.labels?.() ?? [],
|
|
2330
|
+
// 真实负载:选机打分用。报不出来就是 null,调用方会按中性值处理。
|
|
2331
|
+
cpuLoad: cpuLoad(),
|
|
2332
|
+
memAvailableMb: memAvailableMb(),
|
|
2333
|
+
features: this.options.identity.nodeId ? ["fabric.task.v1"] : []
|
|
2334
|
+
};
|
|
2335
|
+
case "artifact.put": {
|
|
2336
|
+
const data = typeof params.data === "string" ? Buffer.from(params.data, "base64") : null;
|
|
2337
|
+
if (!data) throw new FabricDispatchError("E_INVALID_PARAMS", "artifact data is required");
|
|
2338
|
+
const stored = this.artifacts.put(data, params.kind ?? "input");
|
|
2339
|
+
if (typeof params.sha256 === "string" && params.sha256 !== stored.sha256) {
|
|
2340
|
+
throw new FabricDispatchError("E_ARTIFACT_CORRUPT", "pushed artifact does not match its sha256");
|
|
2341
|
+
}
|
|
2342
|
+
return { stored: true, sha256: stored.sha256, len: stored.len };
|
|
2343
|
+
}
|
|
2344
|
+
case "artifact.get": {
|
|
2345
|
+
const sha256 = typeof params.sha256 === "string" ? params.sha256 : "";
|
|
2346
|
+
if (!/^[0-9a-f]{64}$/.test(sha256)) {
|
|
2347
|
+
throw new FabricDispatchError("E_INVALID_PARAMS", "bad sha256");
|
|
2348
|
+
}
|
|
2349
|
+
const data = this.artifacts.read({
|
|
2350
|
+
sha256,
|
|
2351
|
+
len: typeof params.len === "number" ? params.len : 0,
|
|
2352
|
+
kind: params.kind ?? "result"
|
|
2353
|
+
});
|
|
2354
|
+
return { sha256, len: data.length, data: data.toString("base64") };
|
|
2355
|
+
}
|
|
2356
|
+
case "task.submit":
|
|
2357
|
+
return this.acceptTask(params, caller);
|
|
2358
|
+
case "task.status": {
|
|
2359
|
+
const taskId = typeof params.taskId === "string" ? params.taskId : "";
|
|
2360
|
+
const record = this.inbound.get(taskId);
|
|
2361
|
+
if (!record) return { state: "unknown" };
|
|
2362
|
+
return {
|
|
2363
|
+
state: record.state,
|
|
2364
|
+
summary: record.summary,
|
|
2365
|
+
files: record.files,
|
|
2366
|
+
exitCode: record.exitCode,
|
|
2367
|
+
error: record.error,
|
|
2368
|
+
resultRef: record.resultRef,
|
|
2369
|
+
diffRef: record.diffRef
|
|
2370
|
+
};
|
|
2371
|
+
}
|
|
2372
|
+
case "task.cancel": {
|
|
2373
|
+
const taskId = typeof params.taskId === "string" ? params.taskId : "";
|
|
2374
|
+
const controller = this.inflight.get(taskId);
|
|
2375
|
+
if (controller) {
|
|
2376
|
+
controller.abort();
|
|
2377
|
+
this.inflight.delete(taskId);
|
|
2378
|
+
}
|
|
2379
|
+
const record = this.inbound.get(taskId);
|
|
2380
|
+
if (record && record.state !== "done") {
|
|
2381
|
+
this.inbound.update(taskId, { state: "cancelled" }, this.now());
|
|
2382
|
+
}
|
|
2383
|
+
return { cancelled: Boolean(controller) };
|
|
2384
|
+
}
|
|
2385
|
+
default:
|
|
2386
|
+
throw new FabricDispatchError("E_PROTOCOL", `unknown fabric method: ${method}`);
|
|
2387
|
+
}
|
|
2388
|
+
}
|
|
2389
|
+
async acceptTask(params, caller) {
|
|
2390
|
+
const taskId = typeof params.taskId === "string" ? params.taskId : "";
|
|
2391
|
+
if (!/^[0-9a-f]{16}$/.test(taskId)) {
|
|
2392
|
+
throw new FabricDispatchError("E_INVALID_PARAMS", "bad taskId");
|
|
2393
|
+
}
|
|
2394
|
+
const prompt = typeof params.prompt === "string" ? params.prompt : "";
|
|
2395
|
+
if (!prompt.trim()) throw new FabricDispatchError("E_INVALID_PARAMS", "prompt is required");
|
|
2396
|
+
const deadlineClass = params.deadlineClass;
|
|
2397
|
+
if (typeof deadlineClass !== "string" || !(deadlineClass in FABRIC_DEADLINE_MS)) {
|
|
2398
|
+
throw new FabricDispatchError("E_INVALID_PARAMS", "unknown deadlineClass");
|
|
2399
|
+
}
|
|
2400
|
+
const existing = this.inbound.get(taskId);
|
|
2401
|
+
if (existing && existing.state !== "lost" && existing.state !== "failed") {
|
|
2402
|
+
return { accepted: true, state: existing.state, idempotent: true };
|
|
2403
|
+
}
|
|
2404
|
+
const grant = caller.grants;
|
|
2405
|
+
const tools = FABRIC_TOOLS_BY_GRANT[grant];
|
|
2406
|
+
const inputRef = params.inputRef && typeof params.inputRef === "object" ? params.inputRef : null;
|
|
2407
|
+
const record = this.inbound.create({
|
|
2408
|
+
taskId,
|
|
2409
|
+
peerId: caller.nodeId,
|
|
2410
|
+
deadlineClass,
|
|
2411
|
+
workspaceHint: typeof params.workspaceHint === "string" ? params.workspaceHint : "",
|
|
2412
|
+
inputRef,
|
|
2413
|
+
now: this.now()
|
|
2414
|
+
});
|
|
2415
|
+
const runner = this.options.runner;
|
|
2416
|
+
if (!runner) {
|
|
2417
|
+
this.inbound.update(taskId, { state: "failed", error: "E_UNSUPPORTED: no remote runner" }, this.now());
|
|
2418
|
+
throw new FabricDispatchError("E_UNSUPPORTED", "E_UNSUPPORTED: this host has no remote runner");
|
|
2419
|
+
}
|
|
2420
|
+
const controller = new AbortController();
|
|
2421
|
+
this.inflight.set(taskId, controller);
|
|
2422
|
+
this.inbound.update(taskId, { state: "running", pid: process.pid }, this.now());
|
|
2423
|
+
void (async () => {
|
|
2424
|
+
try {
|
|
2425
|
+
const input = inputRef ? this.artifacts.read(inputRef) : null;
|
|
2426
|
+
let lastProgressAt = 0;
|
|
2427
|
+
let lastProgressText = "";
|
|
2428
|
+
const onProgress = (note) => {
|
|
2429
|
+
const value = note.text.trim().slice(0, 200);
|
|
2430
|
+
if (!value || value === lastProgressText) return;
|
|
2431
|
+
const now = this.now();
|
|
2432
|
+
if (lastProgressAt !== 0 && now - lastProgressAt < FABRIC_PROGRESS_THROTTLE_MS) return;
|
|
2433
|
+
lastProgressAt = now;
|
|
2434
|
+
lastProgressText = value;
|
|
2435
|
+
this.inbound.update(
|
|
2436
|
+
taskId,
|
|
2437
|
+
{
|
|
2438
|
+
progress: value,
|
|
2439
|
+
progressCode: note.code,
|
|
2440
|
+
progressParams: note.params ?? null,
|
|
2441
|
+
progressAt: now
|
|
2442
|
+
},
|
|
2443
|
+
now
|
|
2444
|
+
);
|
|
2445
|
+
this.options.notify?.(record.peerId, {
|
|
2446
|
+
type: "task_progress",
|
|
2447
|
+
taskId,
|
|
2448
|
+
text: value,
|
|
2449
|
+
code: note.code,
|
|
2450
|
+
...note.params ? { params: note.params } : {}
|
|
2451
|
+
});
|
|
2452
|
+
};
|
|
2453
|
+
const result = await runner.run({
|
|
2454
|
+
taskId,
|
|
2455
|
+
prompt,
|
|
2456
|
+
workspaceHint: record.workspaceHint,
|
|
2457
|
+
grant,
|
|
2458
|
+
tools,
|
|
2459
|
+
input,
|
|
2460
|
+
signal: controller.signal,
|
|
2461
|
+
onProgress
|
|
2462
|
+
});
|
|
2463
|
+
const resultRef = result.result ? this.artifacts.put(result.result, "result") : null;
|
|
2464
|
+
const diffRef = result.diff ? this.artifacts.put(result.diff, "diff") : null;
|
|
2465
|
+
this.inbound.update(
|
|
2466
|
+
taskId,
|
|
2467
|
+
{
|
|
2468
|
+
state: "done",
|
|
2469
|
+
summary: result.summary,
|
|
2470
|
+
files: result.files ?? [],
|
|
2471
|
+
exitCode: result.exitCode ?? 0,
|
|
2472
|
+
resultRef,
|
|
2473
|
+
diffRef
|
|
2474
|
+
},
|
|
2475
|
+
this.now()
|
|
2476
|
+
);
|
|
2477
|
+
this.options.notify?.(record.peerId, {
|
|
2478
|
+
type: "task_done",
|
|
2479
|
+
taskId,
|
|
2480
|
+
summary: result.summary,
|
|
2481
|
+
files: result.files ?? [],
|
|
2482
|
+
exitCode: result.exitCode ?? 0,
|
|
2483
|
+
resultRef,
|
|
2484
|
+
diffRef
|
|
2485
|
+
});
|
|
2486
|
+
} catch (error) {
|
|
2487
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
2488
|
+
this.inbound.update(
|
|
2489
|
+
taskId,
|
|
2490
|
+
{
|
|
2491
|
+
state: controller.signal.aborted ? "cancelled" : "failed",
|
|
2492
|
+
error: message
|
|
2493
|
+
},
|
|
2494
|
+
this.now()
|
|
2495
|
+
);
|
|
2496
|
+
this.options.notify?.(record.peerId, { type: "task_failed", taskId, error: message });
|
|
2497
|
+
} finally {
|
|
2498
|
+
this.inflight.delete(taskId);
|
|
2499
|
+
}
|
|
2500
|
+
})();
|
|
2501
|
+
return { accepted: true, state: "running", grant, tools };
|
|
2502
|
+
}
|
|
2503
|
+
/**
|
|
2504
|
+
* 为每台已配对机器维持一条常驻连接:配对即连、断线自动重连、取消配对才断。
|
|
2505
|
+
* 这是「不手动取消就一直连着」的落点;返回本次新增/移除的 nodeId 便于记日志。
|
|
2506
|
+
*/
|
|
2507
|
+
keepAlive(peers = listPeers(this.options.agentDir)) {
|
|
2508
|
+
const wanted = new Set(peers.map((peer) => peer.nodeId));
|
|
2509
|
+
const stopped = [];
|
|
2510
|
+
for (const [nodeId, connection] of this.connections) {
|
|
2511
|
+
if (wanted.has(nodeId)) continue;
|
|
2512
|
+
connection.stop();
|
|
2513
|
+
this.connections.delete(nodeId);
|
|
2514
|
+
this.links.delete(nodeId);
|
|
2515
|
+
stopped.push(nodeId);
|
|
2516
|
+
}
|
|
2517
|
+
const started = [];
|
|
2518
|
+
for (const peer of peers) {
|
|
2519
|
+
if (this.connections.has(peer.nodeId)) continue;
|
|
2520
|
+
const connection = new FabricPeerConnection({
|
|
2521
|
+
identity: this.options.identity,
|
|
2522
|
+
peer: { nodeId: peer.nodeId, address: peer.address, port: peer.port },
|
|
2523
|
+
appVersion: this.options.appVersion,
|
|
2524
|
+
log: this.options.log
|
|
2525
|
+
});
|
|
2526
|
+
connection.onEvent((frame) => {
|
|
2527
|
+
void this.applyEvent(frame);
|
|
2528
|
+
});
|
|
2529
|
+
connection.start();
|
|
2530
|
+
this.connections.set(peer.nodeId, connection);
|
|
2531
|
+
started.push(peer.nodeId);
|
|
2532
|
+
}
|
|
2533
|
+
return { started, stopped };
|
|
2534
|
+
}
|
|
2535
|
+
/**
|
|
2536
|
+
* 强制重建某台机器的连接。
|
|
2537
|
+
*
|
|
2538
|
+
* 配对状态变化时必须重建:配对前建立的连接是「受限会话」(只放行 pair.request),
|
|
2539
|
+
* 它会一直连着,不重建就永远派不出活——这个 bug 只有真的跑一遍才看得出来。
|
|
2540
|
+
*/
|
|
2541
|
+
/**
|
|
2542
|
+
* 按引用去对端拉一个产物。
|
|
2543
|
+
*
|
|
2544
|
+
* 为什么需要它:帧里只带 {sha256,len,kind} 引用(大帧会把心跳挤掉、逼对端误判离线),
|
|
2545
|
+
* 而 ArtifactStore 是本机的——所以「对端任务回传的 patch」必须显式拉一次才落地。
|
|
2546
|
+
* 少了这一步,发起方那边永远 diffFor()===null,看起来像对端没产出改动。
|
|
2547
|
+
*/
|
|
2548
|
+
async fetchArtifact(nodeId, ref) {
|
|
2549
|
+
const peer = listPeers(this.options.agentDir).find((item) => item.nodeId === nodeId);
|
|
2550
|
+
if (!peer) return null;
|
|
2551
|
+
const link = await this.linkFor(peer);
|
|
2552
|
+
if (!link) return null;
|
|
2553
|
+
try {
|
|
2554
|
+
const reply = await link.call("artifact.get", {
|
|
2555
|
+
sha256: ref.sha256,
|
|
2556
|
+
len: ref.len,
|
|
2557
|
+
kind: ref.kind
|
|
2558
|
+
});
|
|
2559
|
+
if (typeof reply?.data !== "string") return null;
|
|
2560
|
+
const data = Buffer.from(reply.data, "base64");
|
|
2561
|
+
if (data.length === 0) return null;
|
|
2562
|
+
const digest = createHash4("sha256").update(data).digest("hex");
|
|
2563
|
+
if (digest !== ref.sha256) {
|
|
2564
|
+
this.options.log?.(`fabric artifact rejected: sha256 mismatch (${ref.sha256.slice(0, 12)})`);
|
|
2565
|
+
return null;
|
|
2566
|
+
}
|
|
2567
|
+
this.artifacts.put(data, ref.kind);
|
|
2568
|
+
return data;
|
|
2569
|
+
} catch (error) {
|
|
2570
|
+
this.options.log?.(
|
|
2571
|
+
`fabric artifact.get failed (${nodeId}): ${error instanceof Error ? error.message : String(error)}`
|
|
2572
|
+
);
|
|
2573
|
+
return null;
|
|
2574
|
+
}
|
|
2575
|
+
}
|
|
2576
|
+
resetConnection(nodeId) {
|
|
2577
|
+
const connection = this.connections.get(nodeId);
|
|
2578
|
+
if (connection) {
|
|
2579
|
+
connection.stop();
|
|
2580
|
+
this.connections.delete(nodeId);
|
|
2581
|
+
this.links.delete(nodeId);
|
|
2582
|
+
}
|
|
2583
|
+
this.keepAlive();
|
|
2584
|
+
}
|
|
2585
|
+
/** 每台机器的连接状态,给面板与排障用。 */
|
|
2586
|
+
connectionStates() {
|
|
2587
|
+
const states = {};
|
|
2588
|
+
for (const [nodeId, connection] of this.connections) states[nodeId] = connection.state;
|
|
2589
|
+
return states;
|
|
2590
|
+
}
|
|
2591
|
+
/** 关掉所有链路(Host 退出时)。 */
|
|
2592
|
+
close() {
|
|
2593
|
+
for (const connection of this.connections.values()) connection.stop();
|
|
2594
|
+
this.connections.clear();
|
|
2595
|
+
for (const link of this.links.values()) link.close();
|
|
2596
|
+
this.links.clear();
|
|
2597
|
+
for (const controller of this.inflight.values()) controller.abort();
|
|
2598
|
+
this.inflight.clear();
|
|
2599
|
+
}
|
|
2600
|
+
/** 供 UI 展示:已配对机器 + 当前推断的负载。 */
|
|
2601
|
+
snapshot() {
|
|
2602
|
+
return {
|
|
2603
|
+
peers: listPeers(this.options.agentDir),
|
|
2604
|
+
loads: [...this.loads.values()],
|
|
2605
|
+
tasks: this.outbound.list()
|
|
2606
|
+
};
|
|
2607
|
+
}
|
|
2608
|
+
};
|
|
2609
|
+
var FABRIC_PROGRESS_THROTTLE_MS = 2e3;
|
|
2610
|
+
var FabricDispatchError = class extends Error {
|
|
2611
|
+
constructor(code, message) {
|
|
2612
|
+
super(message);
|
|
2613
|
+
this.name = "FabricDispatchError";
|
|
2614
|
+
this.code = code;
|
|
2615
|
+
}
|
|
2616
|
+
};
|
|
2617
|
+
|
|
2618
|
+
// src/fabric-service.ts
|
|
2619
|
+
init_transport();
|
|
2620
|
+
|
|
2621
|
+
// src/fabric-apply.ts
|
|
2622
|
+
import { execFile as execFile2 } from "node:child_process";
|
|
2623
|
+
import { mkdtempSync, rmSync as rmSync5, writeFileSync as writeFileSync6 } from "node:fs";
|
|
2624
|
+
import { tmpdir } from "node:os";
|
|
2625
|
+
import { join as join7 } from "node:path";
|
|
2626
|
+
import { promisify as promisify2 } from "node:util";
|
|
2627
|
+
|
|
2628
|
+
// src/fabric-worktree.ts
|
|
2629
|
+
import { execFile } from "node:child_process";
|
|
2630
|
+
import { createHash as createHash5 } from "node:crypto";
|
|
2631
|
+
import { existsSync as existsSync6, mkdirSync as mkdirSync7, realpathSync, rmSync as rmSync4 } from "node:fs";
|
|
2632
|
+
import { dirname as dirname6, join as join6, resolve } from "node:path";
|
|
2633
|
+
import { promisify } from "node:util";
|
|
2634
|
+
var execFileAsync = promisify(execFile);
|
|
2635
|
+
var GIT_ENV_KEYS = [
|
|
2636
|
+
"GIT_DIR",
|
|
2637
|
+
"GIT_INDEX_FILE",
|
|
2638
|
+
"GIT_WORK_TREE",
|
|
2639
|
+
"GIT_OBJECT_DIRECTORY",
|
|
2640
|
+
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
|
|
2641
|
+
"GIT_COMMON_DIR",
|
|
2642
|
+
"GIT_NAMESPACE",
|
|
2643
|
+
"GIT_PREFIX"
|
|
2644
|
+
];
|
|
2645
|
+
function cleanGitEnv() {
|
|
2646
|
+
const env = { ...process.env };
|
|
2647
|
+
for (const key of GIT_ENV_KEYS) delete env[key];
|
|
2648
|
+
return env;
|
|
2649
|
+
}
|
|
2650
|
+
async function git2(gitBin, args, timeoutMs) {
|
|
2651
|
+
const { stdout } = await execFileAsync(gitBin, args, {
|
|
2652
|
+
timeout: timeoutMs,
|
|
2653
|
+
maxBuffer: 32 * 1024 * 1024,
|
|
2654
|
+
windowsHide: true,
|
|
2655
|
+
env: cleanGitEnv()
|
|
2656
|
+
});
|
|
2657
|
+
return String(stdout);
|
|
2658
|
+
}
|
|
2659
|
+
async function resolveRepoRoot(hint, options = {}) {
|
|
2660
|
+
const gitBin = options.git ?? "git";
|
|
2661
|
+
const timeoutMs = options.timeoutMs ?? 1e4;
|
|
2662
|
+
if (!hint) return null;
|
|
2663
|
+
try {
|
|
2664
|
+
const root = (await git2(gitBin, ["-C", hint, "rev-parse", "--show-toplevel"], timeoutMs)).trim();
|
|
2665
|
+
return root || null;
|
|
2666
|
+
} catch {
|
|
2667
|
+
return null;
|
|
2668
|
+
}
|
|
2669
|
+
}
|
|
2670
|
+
|
|
2671
|
+
// src/fabric-apply.ts
|
|
2672
|
+
var execFileAsync2 = promisify2(execFile2);
|
|
2673
|
+
function filesInPatch(patch) {
|
|
2674
|
+
const paths = /* @__PURE__ */ new Set();
|
|
2675
|
+
for (const line of patch.toString("utf8").split("\n")) {
|
|
2676
|
+
if (!line.startsWith("+++ b/")) continue;
|
|
2677
|
+
const path3 = line.slice(6).trim();
|
|
2678
|
+
if (path3 && path3 !== "/dev/null") paths.add(path3);
|
|
2679
|
+
}
|
|
2680
|
+
return [...paths].slice(0, 200);
|
|
2681
|
+
}
|
|
2682
|
+
async function changedFiles(gitBin, repo, timeoutMs) {
|
|
2683
|
+
try {
|
|
2684
|
+
const { stdout } = await execFileAsync2(gitBin, ["-C", repo, "status", "--porcelain"], {
|
|
2685
|
+
timeout: timeoutMs,
|
|
2686
|
+
maxBuffer: 8 * 1024 * 1024,
|
|
2687
|
+
windowsHide: true,
|
|
2688
|
+
env: cleanGitEnv()
|
|
2689
|
+
});
|
|
2690
|
+
return String(stdout).split("\n").map((line) => line.slice(3).trim()).filter((path3) => path3.length > 0).slice(0, 200);
|
|
2691
|
+
} catch {
|
|
2692
|
+
return [];
|
|
2693
|
+
}
|
|
2694
|
+
}
|
|
2695
|
+
async function gitApply(gitBin, repo, args, timeoutMs) {
|
|
2696
|
+
try {
|
|
2697
|
+
await execFileAsync2(gitBin, ["-C", repo, "apply", ...args], {
|
|
2698
|
+
timeout: timeoutMs,
|
|
2699
|
+
maxBuffer: 8 * 1024 * 1024,
|
|
2700
|
+
windowsHide: true,
|
|
2701
|
+
env: cleanGitEnv()
|
|
2702
|
+
});
|
|
2703
|
+
return { ok: true };
|
|
2704
|
+
} catch (error) {
|
|
2705
|
+
const stderr = typeof error === "object" && error && "stderr" in error ? String(error.stderr ?? "") : "";
|
|
2706
|
+
return { ok: false, message: (stderr || (error instanceof Error ? error.message : String(error))).trim() };
|
|
2707
|
+
}
|
|
2708
|
+
}
|
|
2709
|
+
async function applyPatchToRepo(options) {
|
|
2710
|
+
const gitBin = options.git ?? "git";
|
|
2711
|
+
const timeoutMs = options.timeoutMs ?? 6e4;
|
|
2712
|
+
const dryRun = options.dryRun ?? true;
|
|
2713
|
+
if (options.patch.length === 0) {
|
|
2714
|
+
return { ok: false, code: "E_PATCH_EMPTY", message: "\u8FD9\u4E2A\u4EFB\u52A1\u6CA1\u6709\u6539\u52A8\u53EF\u5E94\u7528" };
|
|
2715
|
+
}
|
|
2716
|
+
const repo = await resolveRepoRoot(options.repo, { git: gitBin });
|
|
2717
|
+
if (!repo) {
|
|
2718
|
+
return { ok: false, code: "E_NOT_A_REPO", message: `${options.repo} \u4E0D\u662F git \u4ED3\u5E93` };
|
|
2719
|
+
}
|
|
2720
|
+
const work = mkdtempSync(join7(tmpdir(), "pi-fabric-apply-"));
|
|
2721
|
+
const patchFile = join7(work, "change.patch");
|
|
2722
|
+
try {
|
|
2723
|
+
writeFileSync6(patchFile, options.patch);
|
|
2724
|
+
const args = ["--3way", "--whitespace=nowarn", patchFile];
|
|
2725
|
+
const check = await gitApply(gitBin, repo, ["--check", ...args], timeoutMs);
|
|
2726
|
+
if (check.ok === false) {
|
|
2727
|
+
options.log?.(`fabric apply check failed for ${repo}`);
|
|
2728
|
+
return {
|
|
2729
|
+
ok: false,
|
|
2730
|
+
code: "E_APPLY_CONFLICT",
|
|
2731
|
+
message: `\u8865\u4E01\u65E0\u6CD5\u5E72\u51C0\u5E94\u7528\uFF08\u672C\u5730\u53EF\u80FD\u5DF2\u6539\u8FC7\u540C\u4E00\u6279\u6587\u4EF6\uFF09\uFF1A${check.message.slice(0, 500)}`,
|
|
2732
|
+
files: filesInPatch(options.patch)
|
|
2733
|
+
};
|
|
2734
|
+
}
|
|
2735
|
+
const touched = filesInPatch(options.patch);
|
|
2736
|
+
if (dryRun) {
|
|
2737
|
+
return { ok: true, dryRun: true, repo, message: "\u53EF\u4EE5\u5E72\u51C0\u5E94\u7528", files: touched };
|
|
2738
|
+
}
|
|
2739
|
+
const applied = await gitApply(gitBin, repo, args, timeoutMs);
|
|
2740
|
+
if (applied.ok === false) {
|
|
2741
|
+
return {
|
|
2742
|
+
ok: false,
|
|
2743
|
+
code: "E_APPLY_FAILED",
|
|
2744
|
+
message: `\u5E94\u7528\u8865\u4E01\u5931\u8D25\uFF1A${applied.message.slice(0, 500)}`
|
|
2745
|
+
};
|
|
2746
|
+
}
|
|
2747
|
+
const statusFiles = await changedFiles(gitBin, repo, timeoutMs);
|
|
2748
|
+
return {
|
|
2749
|
+
ok: true,
|
|
2750
|
+
dryRun: false,
|
|
2751
|
+
repo,
|
|
2752
|
+
message: "\u5DF2\u5E94\u7528\u5230\u672C\u5730\u4ED3\u5E93\uFF0C\u6539\u52A8\u672A\u63D0\u4EA4",
|
|
2753
|
+
files: statusFiles.length > 0 ? statusFiles : touched
|
|
2754
|
+
};
|
|
2755
|
+
} finally {
|
|
2756
|
+
rmSync5(work, { recursive: true, force: true });
|
|
2757
|
+
}
|
|
2758
|
+
}
|
|
2759
|
+
|
|
2760
|
+
// src/fabric-server.ts
|
|
2761
|
+
init_fabric();
|
|
2762
|
+
init_transport();
|
|
2763
|
+
import { createServer } from "node:net";
|
|
2764
|
+
async function startFabricListener(options) {
|
|
2765
|
+
const host = options.host ?? "0.0.0.0";
|
|
2766
|
+
const port = options.port ?? FABRIC_DEFAULT_PORT;
|
|
2767
|
+
const links = /* @__PURE__ */ new Map();
|
|
2768
|
+
const server = createServer((socket) => {
|
|
2769
|
+
socket.setNoDelay(true);
|
|
2770
|
+
void acceptFabricLink({
|
|
2771
|
+
socket,
|
|
2772
|
+
identity: options.identity,
|
|
2773
|
+
isPaired: options.isPaired,
|
|
2774
|
+
onPairRequest: options.onPairRequest,
|
|
2775
|
+
onRestrictedCall: options.onRestrictedCall,
|
|
2776
|
+
onCall: options.onCall,
|
|
2777
|
+
appVersion: options.appVersion,
|
|
2778
|
+
log: options.log
|
|
2779
|
+
}).then((link) => {
|
|
2780
|
+
links.set(link.nodeId, link);
|
|
2781
|
+
options.onLink?.(link);
|
|
2782
|
+
options.log?.(`fabric inbound link up: ${link.nodeId} (${link.features.join(",")})`);
|
|
2783
|
+
}).catch((error) => {
|
|
2784
|
+
options.log?.(
|
|
2785
|
+
`fabric inbound handshake rejected: ${error instanceof Error ? error.message : String(error)}`
|
|
2786
|
+
);
|
|
2787
|
+
});
|
|
2788
|
+
});
|
|
2789
|
+
await new Promise((resolve2, reject) => {
|
|
2790
|
+
server.once("error", reject);
|
|
2791
|
+
server.listen(port, host, () => {
|
|
2792
|
+
server.removeListener("error", reject);
|
|
2793
|
+
resolve2();
|
|
2794
|
+
});
|
|
2795
|
+
});
|
|
2796
|
+
const address = server.address();
|
|
2797
|
+
const actualPort = typeof address === "object" && address ? address.port : port;
|
|
2798
|
+
return {
|
|
2799
|
+
port: actualPort,
|
|
2800
|
+
host,
|
|
2801
|
+
peers: () => [...links.keys()],
|
|
2802
|
+
publish(nodeId, frame) {
|
|
2803
|
+
const link = links.get(nodeId);
|
|
2804
|
+
if (!link || !link.connected) return false;
|
|
2805
|
+
link.send({ type: "event", event: frame });
|
|
2806
|
+
return true;
|
|
2807
|
+
},
|
|
2808
|
+
close: () => new Promise((resolve2) => {
|
|
2809
|
+
for (const link of links.values()) link.close();
|
|
2810
|
+
links.clear();
|
|
2811
|
+
server.close(() => resolve2());
|
|
2812
|
+
})
|
|
2813
|
+
};
|
|
2814
|
+
}
|
|
2815
|
+
|
|
2816
|
+
// src/fabric-service.ts
|
|
2817
|
+
init_pairing();
|
|
2818
|
+
var FABRIC_TASK_RETENTION_MS = 24 * 60 * 60 * 1e3;
|
|
2819
|
+
var FABRIC_DIFF_PREVIEW_BYTES = 256 * 1024;
|
|
2820
|
+
var FABRIC_PAIR_REQUEST_TTL_MS = 10 * 60 * 1e3;
|
|
2821
|
+
var FABRIC_SCAN_CACHE_MS = 5e3;
|
|
2822
|
+
var FabricService = class {
|
|
2823
|
+
constructor(options) {
|
|
2824
|
+
this.guard = new PairingGuard();
|
|
2825
|
+
this.listener = null;
|
|
2826
|
+
this.responder = null;
|
|
2827
|
+
this.pendingPair = null;
|
|
2828
|
+
/** 入站配对请求:等本机用户点「允许」。 */
|
|
2829
|
+
this.inboundRequests = /* @__PURE__ */ new Map();
|
|
2830
|
+
/** 出站配对请求:等对端用户点「允许」,之后本机自动补上 peer 记录。 */
|
|
2831
|
+
this.outboundRequests = /* @__PURE__ */ new Map();
|
|
2832
|
+
/** 被明确拒绝过的对端(带时间):发起方下一次探测就能立刻知道,不用等 TTL。 */
|
|
2833
|
+
this.deniedRequests = /* @__PURE__ */ new Map();
|
|
2834
|
+
this.started = false;
|
|
2835
|
+
this.announcer = null;
|
|
2836
|
+
/** 默认开:自家两台机器要能被零输入发现;公司/公共网可以在面板里关掉。 */
|
|
2837
|
+
this.discoverable = true;
|
|
2838
|
+
this.lastScan = null;
|
|
2839
|
+
this.options = options;
|
|
2840
|
+
this.identity = loadOrCreateIdentity(options.agentDir, this.now());
|
|
2841
|
+
this.artifacts = new ArtifactStore(options.agentDir);
|
|
2842
|
+
this.outbound = new TaskLedger(options.agentDir, "outbound");
|
|
2843
|
+
this.inbound = new TaskLedger(options.agentDir, "inbound");
|
|
2844
|
+
this.dispatcher = new FabricDispatcher({
|
|
2845
|
+
agentDir: options.agentDir,
|
|
2846
|
+
identity: this.identity,
|
|
2847
|
+
runner: options.runner,
|
|
2848
|
+
artifacts: this.artifacts,
|
|
2849
|
+
outbound: this.outbound,
|
|
2850
|
+
inbound: this.inbound,
|
|
2851
|
+
appVersion: options.appVersion,
|
|
2852
|
+
log: options.log,
|
|
2853
|
+
now: options.now,
|
|
2854
|
+
// 任务结束时主动推给发起方;没连上就返回 false(对方下次对账再收尾)。
|
|
2855
|
+
notify: (nodeId, frame) => this.listener?.publish(nodeId, frame) ?? false
|
|
2856
|
+
});
|
|
2857
|
+
if (options.labels) this.dispatcher.labels = options.labels;
|
|
2858
|
+
}
|
|
2859
|
+
now() {
|
|
2860
|
+
return this.options.now?.() ?? Date.now();
|
|
2861
|
+
}
|
|
2862
|
+
get nodeId() {
|
|
2863
|
+
return this.identity.nodeId;
|
|
2864
|
+
}
|
|
2865
|
+
get port() {
|
|
2866
|
+
return this.listener?.port ?? 0;
|
|
2867
|
+
}
|
|
2868
|
+
/**
|
|
2869
|
+
* 启动:监听 + 应答发现。任何一个失败都不阻断另一个(跨网用不到广播,
|
|
2870
|
+
* 端口占用也不该死掉整个 Host)——只记日志。
|
|
2871
|
+
*/
|
|
2872
|
+
async start() {
|
|
2873
|
+
if (this.started) return { port: this.port, discPort: this.responder?.port ?? null };
|
|
2874
|
+
this.started = true;
|
|
2875
|
+
const listen = (port) => startFabricListener({
|
|
2876
|
+
identity: this.identity,
|
|
2877
|
+
host: this.options.host ?? "0.0.0.0",
|
|
2878
|
+
port,
|
|
2879
|
+
appVersion: this.options.appVersion,
|
|
2880
|
+
log: this.options.log,
|
|
2881
|
+
isPaired: (nodeId) => Boolean(getPeer(this.options.agentDir, nodeId)),
|
|
2882
|
+
onPairRequest: (info) => this.acceptPairRequest(info),
|
|
2883
|
+
onRestrictedCall: async (method, _params, caller) => {
|
|
2884
|
+
if (method !== "peer.status") {
|
|
2885
|
+
throw new Error("E_UNAUTHORIZED");
|
|
2886
|
+
}
|
|
2887
|
+
return {
|
|
2888
|
+
restricted: true,
|
|
2889
|
+
pending: this.inboundRequests.has(caller.nodeId),
|
|
2890
|
+
denied: this.deniedRequests.has(caller.nodeId),
|
|
2891
|
+
online: false,
|
|
2892
|
+
queueDepth: 0,
|
|
2893
|
+
hbAgeMs: null,
|
|
2894
|
+
labels: []
|
|
2895
|
+
};
|
|
2896
|
+
},
|
|
2897
|
+
onCall: (method, params, caller) => {
|
|
2898
|
+
const peer = getPeer(this.options.agentDir, caller.nodeId);
|
|
2899
|
+
if (!peer) throw new Error("E_PEER_UNKNOWN");
|
|
2900
|
+
return this.dispatcher.handleInbound(method, params, {
|
|
2901
|
+
nodeId: caller.nodeId,
|
|
2902
|
+
grants: peer.grants
|
|
2903
|
+
});
|
|
2904
|
+
}
|
|
2905
|
+
});
|
|
2906
|
+
try {
|
|
2907
|
+
this.listener = await listen(this.options.port);
|
|
2908
|
+
} catch (error) {
|
|
2909
|
+
this.options.log?.(
|
|
2910
|
+
`fabric listen on ${this.options.port ?? "default"} failed, falling back to ephemeral: ${error instanceof Error ? error.message : String(error)}`
|
|
2911
|
+
);
|
|
2912
|
+
this.listener = await listen(0);
|
|
2913
|
+
}
|
|
2914
|
+
try {
|
|
2915
|
+
this.responder = await startResponder({
|
|
2916
|
+
nodeName: this.displayName(),
|
|
2917
|
+
tcpPort: this.listener.port,
|
|
2918
|
+
ctx: this.options.ctx ?? "piforge",
|
|
2919
|
+
log: this.options.log
|
|
2920
|
+
});
|
|
2921
|
+
} catch (error) {
|
|
2922
|
+
this.options.log?.(
|
|
2923
|
+
`fabric discovery disabled: ${error instanceof Error ? error.message : String(error)}`
|
|
2924
|
+
);
|
|
2925
|
+
}
|
|
2926
|
+
try {
|
|
2927
|
+
this.announcer = await startAnnouncer({
|
|
2928
|
+
nodeId: this.identity.nodeId,
|
|
2929
|
+
tcpPort: this.listener.port,
|
|
2930
|
+
...this.options.appVersion ? { appVersion: this.options.appVersion } : {},
|
|
2931
|
+
enabled: () => this.discoverable,
|
|
2932
|
+
log: this.options.log
|
|
2933
|
+
});
|
|
2934
|
+
} catch (error) {
|
|
2935
|
+
this.options.log?.(
|
|
2936
|
+
`fabric announce disabled: ${error instanceof Error ? error.message : String(error)}`
|
|
2937
|
+
);
|
|
2938
|
+
}
|
|
2939
|
+
const keep = this.dispatcher.keepAlive();
|
|
2940
|
+
if (keep.started.length > 0) {
|
|
2941
|
+
this.options.log?.(`fabric keep-alive started for ${keep.started.length} peer(s)`);
|
|
2942
|
+
}
|
|
2943
|
+
return { port: this.listener.port, discPort: this.responder?.port ?? null };
|
|
2944
|
+
}
|
|
2945
|
+
async stop() {
|
|
2946
|
+
this.started = false;
|
|
2947
|
+
this.dispatcher.close();
|
|
2948
|
+
await this.announcer?.close();
|
|
2949
|
+
this.announcer = null;
|
|
2950
|
+
await this.responder?.close();
|
|
2951
|
+
this.responder = null;
|
|
2952
|
+
await this.listener?.close();
|
|
2953
|
+
this.listener = null;
|
|
2954
|
+
}
|
|
2955
|
+
/** 本机在发现包里的名字:主机名 + nodeId 前缀,两台机器重名也能区分。 */
|
|
2956
|
+
displayName() {
|
|
2957
|
+
return `${process.env.COMPUTERNAME ?? process.env.HOSTNAME ?? "piforge"}-${this.identity.nodeId.slice(0, 6)}`;
|
|
2958
|
+
}
|
|
2959
|
+
/**
|
|
2960
|
+
* 配对:算 SAS + ECDH,并(可选)核对用户看到的 6 位码;确认后才写 peer 记录。
|
|
2961
|
+
* 失败不写任何持久化状态——「点了拒绝」等价于什么都没发生。
|
|
2962
|
+
*/
|
|
2963
|
+
pair(input) {
|
|
2964
|
+
const locked = this.guard.lockedUntil(input.nodeId);
|
|
2965
|
+
if (locked > this.now()) {
|
|
2966
|
+
return { ok: false, code: "E_PAIR_LOCKED", reason: `\u914D\u5BF9\u88AB\u9501\u5B9A\u76F4\u5230 ${new Date(locked).toISOString()}` };
|
|
2967
|
+
}
|
|
2968
|
+
let session;
|
|
2969
|
+
try {
|
|
2970
|
+
session = new PairingSession(this.identity, input.nodeId, input.publicKey, this.now(), {
|
|
2971
|
+
windowMs: PAIRING_WINDOW_MS
|
|
2972
|
+
});
|
|
2973
|
+
} catch (error) {
|
|
2974
|
+
return { ok: false, code: "E_INVALID_PARAMS", reason: error instanceof Error ? error.message : "bad key" };
|
|
2975
|
+
}
|
|
2976
|
+
this.pendingPair = session;
|
|
2977
|
+
const confirmed = session.confirm({ sas: input.sas }, this.now());
|
|
2978
|
+
if (confirmed.ok === false) {
|
|
2979
|
+
if (confirmed.code === "E_PAIR_LOCKED") this.guard.recordFailure(input.nodeId, this.now());
|
|
2980
|
+
else if (confirmed.code === "E_PAIR_SAS_MISMATCH") this.guard.recordFailure(input.nodeId, this.now());
|
|
2981
|
+
this.pendingPair = null;
|
|
2982
|
+
return { ok: false, code: confirmed.code, reason: "\u914D\u5BF9\u672A\u901A\u8FC7" };
|
|
2983
|
+
}
|
|
2984
|
+
this.guard.reset(input.nodeId);
|
|
2985
|
+
const peer = savePeer(this.options.agentDir, {
|
|
2986
|
+
nodeId: input.nodeId,
|
|
2987
|
+
name: input.name,
|
|
2988
|
+
address: input.address,
|
|
2989
|
+
port: input.port,
|
|
2990
|
+
grants: input.grants,
|
|
2991
|
+
features: [...FABRIC_FEATURES],
|
|
2992
|
+
appVersion: this.options.appVersion ?? "",
|
|
2993
|
+
lastSeenAt: this.now()
|
|
2994
|
+
});
|
|
2995
|
+
this.pendingPair = null;
|
|
2996
|
+
this.dispatcher.resetConnection(peer.nodeId);
|
|
2997
|
+
return { ok: true, peer, sas: session.sas };
|
|
2998
|
+
}
|
|
2999
|
+
/** 当前待确认的配对:UI 拿 sas 显示给用户比对。 */
|
|
3000
|
+
pendingSas() {
|
|
3001
|
+
return this.pendingPair?.sas ?? null;
|
|
3002
|
+
}
|
|
3003
|
+
/**
|
|
3004
|
+
* 未配对对端敲门的处理:算出 SAS、排队等用户点允许,并回「收到了」。
|
|
3005
|
+
* 注意这里不写任何 peer 记录——只有用户的点击会写。
|
|
3006
|
+
*/
|
|
3007
|
+
async acceptPairRequest(info) {
|
|
3008
|
+
this.prunePairRequests();
|
|
3009
|
+
const session = new PairingSession(this.identity, info.nodeId, info.publicKey, this.now(), {
|
|
3010
|
+
windowMs: FABRIC_PAIR_REQUEST_TTL_MS
|
|
3011
|
+
});
|
|
3012
|
+
this.inboundRequests.set(info.nodeId, {
|
|
3013
|
+
nodeId: info.nodeId,
|
|
3014
|
+
publicKey: info.publicKey,
|
|
3015
|
+
name: info.name || info.nodeId.slice(0, 6),
|
|
3016
|
+
address: info.address,
|
|
3017
|
+
port: info.claimedPort || info.port,
|
|
3018
|
+
sas: session.sas,
|
|
3019
|
+
at: this.now()
|
|
3020
|
+
});
|
|
3021
|
+
this.options.log?.(`fabric pair request from ${info.nodeId} at ${info.address} (sas=${session.sas})`);
|
|
3022
|
+
const stored = this.inboundRequests.get(info.nodeId);
|
|
3023
|
+
if (stored) this.options.onPairRequestNotice?.(stored);
|
|
3024
|
+
return { pending: true, sas: session.sas, publicKey: this.identity.publicKey };
|
|
3025
|
+
}
|
|
3026
|
+
/** 面板轮询用:两边待确认的请求,都带 6 位对照码。 */
|
|
3027
|
+
pendingRequests() {
|
|
3028
|
+
this.prunePairRequests();
|
|
3029
|
+
return {
|
|
3030
|
+
inbound: [...this.inboundRequests.values()],
|
|
3031
|
+
outbound: [...this.outboundRequests.values()],
|
|
3032
|
+
denied: [...this.deniedRequests.keys()]
|
|
3033
|
+
};
|
|
3034
|
+
}
|
|
3035
|
+
prunePairRequests(now = this.now()) {
|
|
3036
|
+
for (const [nodeId, request] of this.inboundRequests) {
|
|
3037
|
+
if (now - request.at > FABRIC_PAIR_REQUEST_TTL_MS) this.inboundRequests.delete(nodeId);
|
|
3038
|
+
}
|
|
3039
|
+
for (const [nodeId, request] of this.outboundRequests) {
|
|
3040
|
+
if (now - request.at > FABRIC_PAIR_REQUEST_TTL_MS) this.outboundRequests.delete(nodeId);
|
|
3041
|
+
}
|
|
3042
|
+
for (const [nodeId, at] of this.deniedRequests) {
|
|
3043
|
+
if (now - at > FABRIC_PAIR_REQUEST_TTL_MS) this.deniedRequests.delete(nodeId);
|
|
3044
|
+
}
|
|
3045
|
+
}
|
|
3046
|
+
/**
|
|
3047
|
+
* 本机发起配对(「让对方点一下确认」的一半):
|
|
3048
|
+
* 连过去只调 pair.request,然后等对方在它自己的面板上点允许。
|
|
3049
|
+
*/
|
|
3050
|
+
async requestPairing(input) {
|
|
3051
|
+
try {
|
|
3052
|
+
const reply = await requestPairing({
|
|
3053
|
+
identity: this.identity,
|
|
3054
|
+
address: input.address,
|
|
3055
|
+
port: input.port,
|
|
3056
|
+
name: input.name ?? this.displayName(),
|
|
3057
|
+
listenPort: this.port,
|
|
3058
|
+
log: this.options.log
|
|
3059
|
+
});
|
|
3060
|
+
const session = new PairingSession(this.identity, reply.nodeId, reply.publicKey, this.now(), {
|
|
3061
|
+
windowMs: FABRIC_PAIR_REQUEST_TTL_MS
|
|
3062
|
+
});
|
|
3063
|
+
this.outboundRequests.set(reply.nodeId, {
|
|
3064
|
+
nodeId: reply.nodeId,
|
|
3065
|
+
publicKey: reply.publicKey,
|
|
3066
|
+
name: input.name ?? input.address,
|
|
3067
|
+
address: input.address,
|
|
3068
|
+
port: input.port,
|
|
3069
|
+
sas: session.sas,
|
|
3070
|
+
at: this.now()
|
|
3071
|
+
});
|
|
3072
|
+
this.options.log?.(`fabric pair request sent to ${reply.nodeId} (sas=${session.sas})`);
|
|
3073
|
+
return { ok: true, nodeId: reply.nodeId, sas: session.sas };
|
|
3074
|
+
} catch (error) {
|
|
3075
|
+
return {
|
|
3076
|
+
ok: false,
|
|
3077
|
+
code: error instanceof Error && "code" in error ? String(error.code) : "E_PEER_OFFLINE",
|
|
3078
|
+
reason: error instanceof Error ? error.message : String(error)
|
|
3079
|
+
};
|
|
3080
|
+
}
|
|
3081
|
+
}
|
|
3082
|
+
/**
|
|
3083
|
+
* 本机用户点「允许 / 拒绝」(另一半)。
|
|
3084
|
+
* 允许才会写 peer 记录——档位就是这一刻定的,之后不再悄悄提升。
|
|
3085
|
+
*/
|
|
3086
|
+
confirmPairRequest(nodeId, accept, grants = "read-only", name) {
|
|
3087
|
+
const request = this.inboundRequests.get(nodeId);
|
|
3088
|
+
if (!request) return { ok: false, code: "E_PAIR_UNKNOWN" };
|
|
3089
|
+
if (nodeIdOf(request.publicKey) !== request.nodeId) {
|
|
3090
|
+
this.inboundRequests.delete(nodeId);
|
|
3091
|
+
this.guard.recordFailure(nodeId, this.now());
|
|
3092
|
+
this.options.log?.(`fabric pair rejected: nodeId does not match public key (${nodeId})`);
|
|
3093
|
+
return { ok: false, code: "E_PAIR_SAS_MISMATCH" };
|
|
3094
|
+
}
|
|
3095
|
+
this.inboundRequests.delete(nodeId);
|
|
3096
|
+
if (!accept) {
|
|
3097
|
+
this.deniedRequests.set(nodeId, this.now());
|
|
3098
|
+
this.options.log?.(`fabric pair request from ${nodeId} rejected`);
|
|
3099
|
+
return { ok: true };
|
|
3100
|
+
}
|
|
3101
|
+
const peer = savePeer(this.options.agentDir, {
|
|
3102
|
+
nodeId: request.nodeId,
|
|
3103
|
+
name: name?.trim() || request.name,
|
|
3104
|
+
address: request.address,
|
|
3105
|
+
// 记的是对端握手时的源端口:同机双实例、临时端口场景下猜 7788 会连错。
|
|
3106
|
+
port: request.port || FABRIC_DEFAULT_PORT,
|
|
3107
|
+
grants,
|
|
3108
|
+
features: [...FABRIC_FEATURES],
|
|
3109
|
+
appVersion: this.options.appVersion ?? "",
|
|
3110
|
+
lastSeenAt: this.now()
|
|
3111
|
+
});
|
|
3112
|
+
this.dispatcher.resetConnection(peer.nodeId);
|
|
3113
|
+
return { ok: true, peer };
|
|
3114
|
+
}
|
|
3115
|
+
/**
|
|
3116
|
+
* 出站请求的收尾:对端点允许后会开始接受正常握手,这里探一次成功就落盘。
|
|
3117
|
+
* 用「探一次」而不是等推送,是因为未配对连接上没有可信的事件通道。
|
|
3118
|
+
*/
|
|
3119
|
+
async resolveOutboundPairings() {
|
|
3120
|
+
this.prunePairRequests();
|
|
3121
|
+
const resolved = [];
|
|
3122
|
+
const denied = [];
|
|
3123
|
+
for (const [nodeId, request] of this.outboundRequests) {
|
|
3124
|
+
const link = await dialFabricLink({
|
|
3125
|
+
identity: this.identity,
|
|
3126
|
+
peer: { nodeId, address: request.address, port: request.port },
|
|
3127
|
+
timeoutMs: 1500,
|
|
3128
|
+
log: this.options.log
|
|
3129
|
+
}).catch(() => null);
|
|
3130
|
+
if (!link) continue;
|
|
3131
|
+
let status;
|
|
3132
|
+
try {
|
|
3133
|
+
status = await link.call("peer.status", {});
|
|
3134
|
+
} catch {
|
|
3135
|
+
link.close();
|
|
3136
|
+
continue;
|
|
3137
|
+
}
|
|
3138
|
+
link.close();
|
|
3139
|
+
if (status.restricted === true) {
|
|
3140
|
+
if (status.denied === true) {
|
|
3141
|
+
this.outboundRequests.delete(nodeId);
|
|
3142
|
+
this.deniedRequests.set(nodeId, this.now());
|
|
3143
|
+
denied.push(nodeId);
|
|
3144
|
+
}
|
|
3145
|
+
continue;
|
|
3146
|
+
}
|
|
3147
|
+
savePeer(this.options.agentDir, {
|
|
3148
|
+
nodeId,
|
|
3149
|
+
name: request.name,
|
|
3150
|
+
address: request.address,
|
|
3151
|
+
port: request.port,
|
|
3152
|
+
grants: "read-only",
|
|
3153
|
+
features: [...FABRIC_FEATURES],
|
|
3154
|
+
appVersion: this.options.appVersion ?? "",
|
|
3155
|
+
lastSeenAt: this.now()
|
|
3156
|
+
});
|
|
3157
|
+
this.outboundRequests.delete(nodeId);
|
|
3158
|
+
resolved.push(nodeId);
|
|
3159
|
+
this.dispatcher.keepAlive();
|
|
3160
|
+
}
|
|
3161
|
+
return { resolved, denied };
|
|
3162
|
+
}
|
|
3163
|
+
unpair(nodeId) {
|
|
3164
|
+
const removed = deletePeer(this.options.agentDir, nodeId);
|
|
3165
|
+
if (removed) this.dispatcher.keepAlive();
|
|
3166
|
+
return removed;
|
|
3167
|
+
}
|
|
3168
|
+
/** 一键检索匹配:局域网广播找对端,返回 host:port。 */
|
|
3169
|
+
async discover(wantNode, timeoutMs) {
|
|
3170
|
+
return discoverPeer({
|
|
3171
|
+
wantNode,
|
|
3172
|
+
ctx: this.options.ctx ?? "piforge",
|
|
3173
|
+
timeoutMs,
|
|
3174
|
+
log: this.options.log
|
|
3175
|
+
});
|
|
3176
|
+
}
|
|
3177
|
+
/**
|
|
3178
|
+
* 取对端任务的 patch:本机没有就去对端拉一次再落库。
|
|
3179
|
+
*
|
|
3180
|
+
* diffFor() 只读本机 ArtifactStore,而 patch 是在**对端**生成的产物,
|
|
3181
|
+
* 帧里只有引用。少了这一步拉取,「对端明明改了」在本机看起来就是空 diff。
|
|
3182
|
+
*/
|
|
3183
|
+
async fetchDiff(taskId) {
|
|
3184
|
+
const local = this.diffFor(taskId);
|
|
3185
|
+
if (local) return local;
|
|
3186
|
+
const record = this.outbound.get(taskId);
|
|
3187
|
+
if (!record?.diffRef) return null;
|
|
3188
|
+
await this.dispatcher.fetchArtifact(record.peerId, record.diffRef);
|
|
3189
|
+
return this.diffFor(taskId);
|
|
3190
|
+
}
|
|
3191
|
+
/**
|
|
3192
|
+
* 急停:不再应答发现、断开全部连接、把每台已配对机器的档位降回 read-only。
|
|
3193
|
+
*
|
|
3194
|
+
* 这是「远程机器能在本机跑 bash」这条授权的唯一逃生门,必须一条命令生效:
|
|
3195
|
+
* 只关 discoverable 不够(已配对连接还在),只断连接也不够(下次派活会自己重连)。
|
|
3196
|
+
*/
|
|
3197
|
+
panic() {
|
|
3198
|
+
this.discoverable = false;
|
|
3199
|
+
const peers = listPeers(this.options.agentDir);
|
|
3200
|
+
for (const peer of peers) {
|
|
3201
|
+
savePeer(this.options.agentDir, { ...peer, grants: "read-only" });
|
|
3202
|
+
}
|
|
3203
|
+
this.dispatcher.close();
|
|
3204
|
+
this.inboundRequests.clear();
|
|
3205
|
+
this.options.log?.(
|
|
3206
|
+
`fabric panic: \u5DF2\u65AD\u5F00\u5168\u90E8\u8FDE\u63A5\uFF0C${peers.length} \u53F0\u673A\u5668\u7684\u6863\u4F4D\u964D\u56DE read-only`
|
|
3207
|
+
);
|
|
3208
|
+
return { peers: peers.length, revoked: peers.length };
|
|
3209
|
+
}
|
|
3210
|
+
/**
|
|
3211
|
+
* 「允许局域网发现」开关:关掉只是不应答匿名扫描(SBF3),
|
|
3212
|
+
* 已配对的点名探测(SBF1)照常工作——否则关开关会把已经连着的机器一起弄丢。
|
|
3213
|
+
*/
|
|
3214
|
+
setDiscoverable(enabled) {
|
|
3215
|
+
this.discoverable = enabled;
|
|
3216
|
+
this.options.log?.(`fabric announce ${enabled ? "enabled" : "disabled"}`);
|
|
3217
|
+
return this.discoverable;
|
|
3218
|
+
}
|
|
3219
|
+
isDiscoverable() {
|
|
3220
|
+
return this.discoverable;
|
|
3221
|
+
}
|
|
3222
|
+
/** 扫一圈局域网;结果缓存几秒,配对时复用同一份(地址只能来自本机广播)。 */
|
|
3223
|
+
async nearby(force = false) {
|
|
3224
|
+
if (!force && this.lastScan && this.now() - this.lastScan.at < FABRIC_SCAN_CACHE_MS) {
|
|
3225
|
+
return this.lastScan.devices;
|
|
3226
|
+
}
|
|
3227
|
+
const devices = await scanLan({ log: this.options.log });
|
|
3228
|
+
const others = devices.filter((device) => device.nodeId !== this.identity.nodeId);
|
|
3229
|
+
this.lastScan = { at: this.now(), devices: others };
|
|
3230
|
+
return others;
|
|
3231
|
+
}
|
|
3232
|
+
/**
|
|
3233
|
+
* 从扫描列表里挑一台配对:地址/端口取自本机扫描结果,不接受 UI 传进来的地址
|
|
3234
|
+
* (UI 传来的地址等于让前端决定连到哪台机器)。
|
|
3235
|
+
*/
|
|
3236
|
+
async requestPairNearby(nodeId, name) {
|
|
3237
|
+
const devices = await this.nearby();
|
|
3238
|
+
const device = devices.find((item) => item.nodeId === nodeId);
|
|
3239
|
+
if (!device) {
|
|
3240
|
+
return { ok: false, code: "E_PEER_OFFLINE", reason: "\u626B\u63CF\u5217\u8868\u91CC\u6CA1\u6709\u8FD9\u53F0\u673A\u5668\uFF0C\u53EF\u80FD\u521A\u65AD\u7EBF" };
|
|
3241
|
+
}
|
|
3242
|
+
return this.requestPairing({
|
|
3243
|
+
address: device.address,
|
|
3244
|
+
port: device.tcpPort,
|
|
3245
|
+
...name ? { name } : {}
|
|
3246
|
+
});
|
|
3247
|
+
}
|
|
3248
|
+
snapshot() {
|
|
3249
|
+
const snap = this.dispatcher.snapshot();
|
|
3250
|
+
return {
|
|
3251
|
+
nodeId: this.identity.nodeId,
|
|
3252
|
+
publicKey: this.identity.publicKey,
|
|
3253
|
+
displayName: this.displayName(),
|
|
3254
|
+
port: this.port,
|
|
3255
|
+
discoverable: this.discoverable,
|
|
3256
|
+
...snap
|
|
3257
|
+
};
|
|
3258
|
+
}
|
|
3259
|
+
async dispatch(input) {
|
|
3260
|
+
return this.dispatcher.submit(input);
|
|
3261
|
+
}
|
|
3262
|
+
/** 断线对账:重连后第一件事,先问对端干完没有,再谈重派。 */
|
|
3263
|
+
async reconcile() {
|
|
3264
|
+
return this.dispatcher.reconcile();
|
|
3265
|
+
}
|
|
3266
|
+
/** 磁盘清理:无主产物 24h、有主 7 天、终态任务记录 24h。 */
|
|
3267
|
+
sweep(now = this.now()) {
|
|
3268
|
+
const referenced = /* @__PURE__ */ new Set();
|
|
3269
|
+
for (const ledger of [this.outbound, this.inbound]) {
|
|
3270
|
+
for (const sha of ledger.references()) referenced.add(sha);
|
|
3271
|
+
}
|
|
3272
|
+
const artifacts = this.artifacts.sweep(referenced, now).removed;
|
|
3273
|
+
const tasks = this.outbound.prune(FABRIC_TASK_RETENTION_MS, now) + this.inbound.prune(FABRIC_TASK_RETENTION_MS, now);
|
|
3274
|
+
void ARTIFACT_REFERENCED_TTL_MS;
|
|
3275
|
+
return { artifacts, tasks };
|
|
3276
|
+
}
|
|
3277
|
+
/** 供 UI 的「已配对机器」列表:负载是上一轮探测的快照,未探测则为空。 */
|
|
3278
|
+
/** 每台机器的连接状态(online / reconnecting / manual-off),面板直接显示。 */
|
|
3279
|
+
connectionStates() {
|
|
3280
|
+
return this.dispatcher.connectionStates();
|
|
3281
|
+
}
|
|
3282
|
+
peerRows() {
|
|
3283
|
+
const loads = new Map(this.dispatcher.snapshot().loads.map((load) => [load.nodeId, load]));
|
|
3284
|
+
return listPeers(this.options.agentDir).map((peer) => {
|
|
3285
|
+
const load = loads.get(peer.nodeId);
|
|
3286
|
+
return {
|
|
3287
|
+
peer,
|
|
3288
|
+
online: load?.online ?? false,
|
|
3289
|
+
queueDepth: load?.queueDepth ?? null,
|
|
3290
|
+
labels: sanitizeLabels(load?.labels ?? [])
|
|
3291
|
+
};
|
|
3292
|
+
});
|
|
3293
|
+
}
|
|
3294
|
+
/**
|
|
3295
|
+
* 取回某个任务的 diff 文本(面板展示 / 导出用)。
|
|
3296
|
+
* 有上限:diff 再大也不该把 WebView 撑死,超了就截断并标记。
|
|
3297
|
+
*/
|
|
3298
|
+
diffFor(taskId, limit = FABRIC_DIFF_PREVIEW_BYTES) {
|
|
3299
|
+
const record = this.outbound.get(taskId);
|
|
3300
|
+
if (!record?.diffRef) return null;
|
|
3301
|
+
try {
|
|
3302
|
+
const data = this.artifacts.read(record.diffRef);
|
|
3303
|
+
const truncated = data.length > limit;
|
|
3304
|
+
return {
|
|
3305
|
+
taskId,
|
|
3306
|
+
text: data.subarray(0, limit).toString("utf8"),
|
|
3307
|
+
bytes: data.length,
|
|
3308
|
+
truncated,
|
|
3309
|
+
files: [...record.files]
|
|
3310
|
+
};
|
|
3311
|
+
} catch {
|
|
3312
|
+
return null;
|
|
3313
|
+
}
|
|
3314
|
+
}
|
|
3315
|
+
/**
|
|
3316
|
+
* 把某个任务的远端改动应用到本机仓库。默认只做 dry-run —— 写别人仓库这件事,
|
|
3317
|
+
* 必须由用户点第二次确认,不能因为「反正能干净应用」就自动落。
|
|
3318
|
+
*/
|
|
3319
|
+
async applyDiff(input) {
|
|
3320
|
+
const record = this.outbound.get(input.taskId);
|
|
3321
|
+
if (!record) {
|
|
3322
|
+
return { ok: false, code: "E_TASK_UNKNOWN", message: "\u6CA1\u6709\u8FD9\u4E2A\u4EFB\u52A1" };
|
|
3323
|
+
}
|
|
3324
|
+
if (!record.diffRef) {
|
|
3325
|
+
return { ok: false, code: "E_PATCH_EMPTY", message: "\u8FD9\u4E2A\u4EFB\u52A1\u6CA1\u6709\u6539\u52A8\u53EF\u5E94\u7528" };
|
|
3326
|
+
}
|
|
3327
|
+
const repo = input.repo?.trim() || record.workspaceHint;
|
|
3328
|
+
if (!repo) {
|
|
3329
|
+
return { ok: false, code: "E_NOT_A_REPO", message: "\u4E0D\u77E5\u9053\u8BE5\u5E94\u7528\u5230\u54EA\u4E2A\u4ED3\u5E93\uFF08\u4EFB\u52A1\u6CA1\u6709\u8BB0\u5F55\u5DE5\u4F5C\u533A\uFF09" };
|
|
3330
|
+
}
|
|
3331
|
+
let patch;
|
|
3332
|
+
try {
|
|
3333
|
+
patch = this.artifacts.read(record.diffRef);
|
|
3334
|
+
} catch {
|
|
3335
|
+
return { ok: false, code: "E_PATCH_EMPTY", message: "diff \u4EA7\u7269\u5DF2\u88AB\u6E05\u7406\uFF0C\u65E0\u6CD5\u5E94\u7528" };
|
|
3336
|
+
}
|
|
3337
|
+
const result = await applyPatchToRepo({
|
|
3338
|
+
repo,
|
|
3339
|
+
patch,
|
|
3340
|
+
dryRun: input.dryRun !== false,
|
|
3341
|
+
log: this.options.log
|
|
3342
|
+
});
|
|
3343
|
+
this.options.log?.(
|
|
3344
|
+
`fabric apply ${input.taskId} -> ${repo}: ${result.ok ? "ok" : result.code}`
|
|
3345
|
+
);
|
|
3346
|
+
return result;
|
|
3347
|
+
}
|
|
3348
|
+
isTerminal(taskId) {
|
|
3349
|
+
const record = this.outbound.get(taskId);
|
|
3350
|
+
return record ? isTerminalState(record.state) : false;
|
|
3351
|
+
}
|
|
3352
|
+
};
|
|
3353
|
+
|
|
3354
|
+
// src/daemon.ts
|
|
3355
|
+
init_fabric();
|
|
3356
|
+
var DEFAULT_AGENT_DIR = path2.join(homedir(), ".piforge");
|
|
3357
|
+
function controlSocketPath(agentDir) {
|
|
3358
|
+
if (process2.platform === "win32") {
|
|
3359
|
+
const hash = createHash6("sha256").update(path2.resolve(agentDir)).digest("hex").slice(0, 16);
|
|
3360
|
+
return `\\\\.\\pipe\\piforge-fabric-${hash}`;
|
|
3361
|
+
}
|
|
3362
|
+
return path2.join(path2.resolve(agentDir), "fabric", "daemon.sock");
|
|
3363
|
+
}
|
|
3364
|
+
function parseArgs(argv) {
|
|
3365
|
+
const [command = "help", ...rest] = argv;
|
|
3366
|
+
const flags = {};
|
|
3367
|
+
const positional = [];
|
|
3368
|
+
for (let index = 0; index < rest.length; index += 1) {
|
|
3369
|
+
const token = rest[index];
|
|
3370
|
+
if (!token.startsWith("--")) {
|
|
3371
|
+
positional.push(token);
|
|
3372
|
+
continue;
|
|
3373
|
+
}
|
|
3374
|
+
const body = token.slice(2);
|
|
3375
|
+
const eq = body.indexOf("=");
|
|
3376
|
+
if (eq >= 0) {
|
|
3377
|
+
flags[body.slice(0, eq)] = body.slice(eq + 1);
|
|
3378
|
+
continue;
|
|
3379
|
+
}
|
|
3380
|
+
const next = rest[index + 1];
|
|
3381
|
+
if (next !== void 0 && !next.startsWith("--")) {
|
|
3382
|
+
flags[body] = next;
|
|
3383
|
+
index += 1;
|
|
3384
|
+
} else {
|
|
3385
|
+
flags[body] = true;
|
|
3386
|
+
}
|
|
3387
|
+
}
|
|
3388
|
+
return { command, flags, positional };
|
|
3389
|
+
}
|
|
3390
|
+
function str(flags, key) {
|
|
3391
|
+
const value = flags[key];
|
|
3392
|
+
return typeof value === "string" ? value : void 0;
|
|
3393
|
+
}
|
|
3394
|
+
function num(flags, key, fallback) {
|
|
3395
|
+
const value = str(flags, key);
|
|
3396
|
+
if (value === void 0) return fallback;
|
|
3397
|
+
const parsed = Number(value);
|
|
3398
|
+
return Number.isFinite(parsed) ? parsed : fallback;
|
|
3399
|
+
}
|
|
3400
|
+
async function settlePairing(service) {
|
|
3401
|
+
const pending = service.pendingRequests();
|
|
3402
|
+
if (pending.outbound.length > 0) {
|
|
3403
|
+
await service.resolveOutboundPairings().catch(() => void 0);
|
|
3404
|
+
}
|
|
3405
|
+
}
|
|
3406
|
+
async function tcpProbe(address, port, timeoutMs = 1200) {
|
|
3407
|
+
return new Promise((resolve2) => {
|
|
3408
|
+
const socket = netConnect2({ host: address, port });
|
|
3409
|
+
const finish = (ok) => {
|
|
3410
|
+
socket.destroy();
|
|
3411
|
+
resolve2(ok);
|
|
3412
|
+
};
|
|
3413
|
+
socket.setTimeout(timeoutMs);
|
|
3414
|
+
socket.once("connect", () => finish(true));
|
|
3415
|
+
socket.once("timeout", () => finish(false));
|
|
3416
|
+
socket.once("error", () => finish(false));
|
|
3417
|
+
});
|
|
3418
|
+
}
|
|
3419
|
+
async function diagnose(service) {
|
|
3420
|
+
const snapshot = service.snapshot();
|
|
3421
|
+
const startedAt = Date.now();
|
|
3422
|
+
const devices = await scanLan({ timeoutMs: 1200 }).catch(() => []);
|
|
3423
|
+
const peers = await Promise.all(
|
|
3424
|
+
(snapshot.peers ?? []).map(async (peer) => ({
|
|
3425
|
+
nodeId: peer.nodeId,
|
|
3426
|
+
name: peer.name,
|
|
3427
|
+
address: peer.address,
|
|
3428
|
+
port: peer.port ?? FABRIC_DEFAULT_PORT,
|
|
3429
|
+
reachable: await tcpProbe(peer.address, peer.port ?? FABRIC_DEFAULT_PORT)
|
|
3430
|
+
}))
|
|
3431
|
+
);
|
|
3432
|
+
const hints = [];
|
|
3433
|
+
if (!snapshot.discoverable) {
|
|
3434
|
+
hints.push("\u672C\u673A\u6CA1\u5F00\u5C40\u57DF\u7F51\u53D1\u73B0\uFF1A\u5BF9\u7AEF\u626B\u4E0D\u5230\u672C\u673A\uFF08\u5DF2\u914D\u5BF9\u7684\u70B9\u540D\u63A2\u6D4B\u4E0D\u53D7\u5F71\u54CD\uFF0C\u52A0 --discoverable \u6216 on \u6253\u5F00\uFF09\u3002");
|
|
3435
|
+
}
|
|
3436
|
+
if (devices.length === 0) {
|
|
3437
|
+
hints.push(
|
|
3438
|
+
`\u5C40\u57DF\u7F51\u626B\u63CF\uFF08UDP ${DISC_ANNOUNCE_PORT}\uFF09\u6CA1\u6709\u56DE\u5305\uFF1A\u786E\u8BA4\u5BF9\u7AEF\u5F00\u4E86\u53D1\u73B0\u3001\u540C\u4E00\u7F51\u6BB5\u3001\u9632\u706B\u5899\u653E\u884C UDP ${DISC_ANNOUNCE_PORT}\u3002`
|
|
3439
|
+
);
|
|
3440
|
+
}
|
|
3441
|
+
for (const peer of peers) {
|
|
3442
|
+
if (!peer.reachable) {
|
|
3443
|
+
hints.push(`\u5DF2\u914D\u5BF9\u673A\u5668 ${peer.name}\uFF08${peer.address}:${peer.port}\uFF09TCP \u4E0D\u53EF\u8FBE\uFF1A\u5BF9\u7AEF daemon \u6CA1\u5728\u8DD1\uFF0C\u6216\u9632\u706B\u5899\u62E6\u4E86 TCP\u3002`);
|
|
3444
|
+
}
|
|
3445
|
+
}
|
|
3446
|
+
return {
|
|
3447
|
+
protocolVersion: FABRIC_PROTOCOL_VERSION,
|
|
3448
|
+
self: {
|
|
3449
|
+
nodeId: snapshot.nodeId,
|
|
3450
|
+
name: snapshot.displayName,
|
|
3451
|
+
port: snapshot.port,
|
|
3452
|
+
discoverable: snapshot.discoverable
|
|
3453
|
+
},
|
|
3454
|
+
broadcast: broadcastAddresses(),
|
|
3455
|
+
scan: devices,
|
|
3456
|
+
peers,
|
|
3457
|
+
hints,
|
|
3458
|
+
ms: Date.now() - startedAt
|
|
3459
|
+
};
|
|
3460
|
+
}
|
|
3461
|
+
function auditTail(agentDir, tail) {
|
|
3462
|
+
const file = path2.join(agentDir, "fabric", "audit", "tasks.jsonl");
|
|
3463
|
+
if (!existsSync7(file)) return { file, total: 0, entries: [] };
|
|
3464
|
+
const lines = readFileSync6(file, "utf8").split("\n").filter((line) => line.trim().length > 0);
|
|
3465
|
+
const entries = lines.slice(-Math.max(1, tail)).flatMap((line) => {
|
|
3466
|
+
try {
|
|
3467
|
+
return [JSON.parse(line)];
|
|
3468
|
+
} catch {
|
|
3469
|
+
return [];
|
|
3470
|
+
}
|
|
3471
|
+
});
|
|
3472
|
+
return { file, total: lines.length, entries };
|
|
3473
|
+
}
|
|
3474
|
+
function makeHandlers(service, state) {
|
|
3475
|
+
return {
|
|
3476
|
+
"fabric.snapshot": async () => {
|
|
3477
|
+
await settlePairing(service);
|
|
3478
|
+
return {
|
|
3479
|
+
...service.snapshot(),
|
|
3480
|
+
pending: service.pendingRequests(),
|
|
3481
|
+
connections: service.connectionStates(),
|
|
3482
|
+
uptimeMs: Date.now() - state.startedAt
|
|
3483
|
+
};
|
|
3484
|
+
},
|
|
3485
|
+
"fabric.scan": async (params) => ({
|
|
3486
|
+
devices: await service.nearby(params?.force !== false)
|
|
3487
|
+
}),
|
|
3488
|
+
"fabric.pair": async (params) => {
|
|
3489
|
+
const address = typeof params?.address === "string" ? params.address : "";
|
|
3490
|
+
const port = Number(params?.port ?? 7788);
|
|
3491
|
+
if (!address) throw Object.assign(new Error("address is required"), { code: "E_INVALID_PARAMS" });
|
|
3492
|
+
return service.requestPairing({
|
|
3493
|
+
address,
|
|
3494
|
+
port,
|
|
3495
|
+
...typeof params?.name === "string" ? { name: params.name } : {}
|
|
3496
|
+
});
|
|
3497
|
+
},
|
|
3498
|
+
"fabric.pairNearby": async (params) => {
|
|
3499
|
+
const nodeId = typeof params?.nodeId === "string" ? params.nodeId : "";
|
|
3500
|
+
if (!nodeId) throw Object.assign(new Error("nodeId is required"), { code: "E_INVALID_PARAMS" });
|
|
3501
|
+
return service.requestPairNearby(nodeId, typeof params?.name === "string" ? params.name : void 0);
|
|
3502
|
+
},
|
|
3503
|
+
"fabric.allow": async (params) => {
|
|
3504
|
+
const nodeId = typeof params?.nodeId === "string" ? params.nodeId : "";
|
|
3505
|
+
if (!nodeId) throw Object.assign(new Error("nodeId is required"), { code: "E_INVALID_PARAMS" });
|
|
3506
|
+
const grants = typeof params?.grants === "string" ? params.grants : "workspace-rw";
|
|
3507
|
+
return service.confirmPairRequest(nodeId, true, grants, typeof params?.name === "string" ? params.name : void 0);
|
|
3508
|
+
},
|
|
3509
|
+
"fabric.deny": async (params) => {
|
|
3510
|
+
const nodeId = typeof params?.nodeId === "string" ? params.nodeId : "";
|
|
3511
|
+
if (!nodeId) throw Object.assign(new Error("nodeId is required"), { code: "E_INVALID_PARAMS" });
|
|
3512
|
+
return service.confirmPairRequest(nodeId, false);
|
|
3513
|
+
},
|
|
3514
|
+
"fabric.unpair": async (params) => {
|
|
3515
|
+
const nodeId = typeof params?.nodeId === "string" ? params.nodeId : "";
|
|
3516
|
+
return { removed: service.unpair(nodeId) };
|
|
3517
|
+
},
|
|
3518
|
+
"fabric.dispatch": async (params) => {
|
|
3519
|
+
const prompt = typeof params?.prompt === "string" ? params.prompt.trim() : "";
|
|
3520
|
+
if (!prompt) throw Object.assign(new Error("prompt is required"), { code: "E_INVALID_PARAMS" });
|
|
3521
|
+
const deadlineClass = params?.deadlineClass === "quick" || params?.deadlineClass === "long" ? params.deadlineClass : "build";
|
|
3522
|
+
await settlePairing(service);
|
|
3523
|
+
return service.dispatch({
|
|
3524
|
+
prompt,
|
|
3525
|
+
estimatedMs: Number(params?.estimatedMs ?? 6e4),
|
|
3526
|
+
deadlineClass,
|
|
3527
|
+
...typeof params?.grant === "string" ? { grant: params.grant } : {},
|
|
3528
|
+
...typeof params?.workspaceHint === "string" ? { workspaceHint: params.workspaceHint } : {},
|
|
3529
|
+
...typeof params?.pin === "string" ? { pin: params.pin } : {},
|
|
3530
|
+
...typeof params?.to === "string" ? { pin: params.to } : {}
|
|
3531
|
+
});
|
|
3532
|
+
},
|
|
3533
|
+
"fabric.status": async (params) => {
|
|
3534
|
+
await settlePairing(service);
|
|
3535
|
+
await service.reconcile().catch(() => void 0);
|
|
3536
|
+
const snapshot = service.snapshot();
|
|
3537
|
+
const taskId = typeof params?.taskId === "string" ? params.taskId : "";
|
|
3538
|
+
return taskId ? { task: snapshot.tasks.find((task) => task.taskId === taskId) ?? null } : { tasks: snapshot.tasks };
|
|
3539
|
+
},
|
|
3540
|
+
"fabric.diff": async (params) => {
|
|
3541
|
+
const taskId = typeof params?.taskId === "string" ? params.taskId : "";
|
|
3542
|
+
if (!taskId) throw Object.assign(new Error("taskId is required"), { code: "E_INVALID_PARAMS" });
|
|
3543
|
+
await service.reconcile().catch(() => void 0);
|
|
3544
|
+
return service.fetchDiff(taskId);
|
|
3545
|
+
},
|
|
3546
|
+
"fabric.panic": async () => service.panic(),
|
|
3547
|
+
"fabric.audit": async (params) => auditTail(state.agentDir, Number(params?.tail ?? 20)),
|
|
3548
|
+
"fabric.diagnose": async () => diagnose(service),
|
|
3549
|
+
"fabric.setDiscoverable": async (params) => ({
|
|
3550
|
+
discoverable: service.setDiscoverable(params?.enabled === true)
|
|
3551
|
+
}),
|
|
3552
|
+
"fabric.reconcile": async () => service.reconcile(),
|
|
3553
|
+
"fabric.sweep": async () => service.sweep()
|
|
3554
|
+
};
|
|
3555
|
+
}
|
|
3556
|
+
async function handleLine(handlers, line) {
|
|
3557
|
+
let request;
|
|
3558
|
+
try {
|
|
3559
|
+
request = JSON.parse(line);
|
|
3560
|
+
} catch {
|
|
3561
|
+
return { ok: false, error: { code: "E_BAD_JSON", message: "expected one JSON object per line" } };
|
|
3562
|
+
}
|
|
3563
|
+
const handler = handlers[request.method];
|
|
3564
|
+
if (!handler) {
|
|
3565
|
+
return { id: request.id, ok: false, error: { code: "E_METHOD", message: `unknown method: ${request.method}` } };
|
|
3566
|
+
}
|
|
3567
|
+
try {
|
|
3568
|
+
return { id: request.id, ok: true, result: await handler(request.params) };
|
|
3569
|
+
} catch (error) {
|
|
3570
|
+
const code = error instanceof Error && "code" in error ? String(error.code) : "E_FABRIC";
|
|
3571
|
+
return { id: request.id, ok: false, error: { code, message: error instanceof Error ? error.message : String(error) } };
|
|
3572
|
+
}
|
|
3573
|
+
}
|
|
3574
|
+
function serveControl(handlers, socketPath) {
|
|
3575
|
+
return new Promise((resolve2, reject) => {
|
|
3576
|
+
if (process2.platform !== "win32" && existsSync7(socketPath)) rmSync6(socketPath, { force: true });
|
|
3577
|
+
const server = createServer2((socket) => {
|
|
3578
|
+
socket.setEncoding("utf8");
|
|
3579
|
+
let buffer = "";
|
|
3580
|
+
socket.on("data", (chunk) => {
|
|
3581
|
+
buffer += chunk;
|
|
3582
|
+
let index = buffer.indexOf("\n");
|
|
3583
|
+
while (index >= 0) {
|
|
3584
|
+
const line = buffer.slice(0, index).trim();
|
|
3585
|
+
buffer = buffer.slice(index + 1);
|
|
3586
|
+
if (line) {
|
|
3587
|
+
void handleLine(handlers, line).then((reply) => {
|
|
3588
|
+
if (!socket.destroyed) socket.write(`${JSON.stringify(reply)}
|
|
3589
|
+
`);
|
|
3590
|
+
});
|
|
3591
|
+
}
|
|
3592
|
+
index = buffer.indexOf("\n");
|
|
3593
|
+
}
|
|
3594
|
+
});
|
|
3595
|
+
socket.on("error", () => void 0);
|
|
3596
|
+
});
|
|
3597
|
+
server.once("error", reject);
|
|
3598
|
+
server.listen(socketPath, () => resolve2(server));
|
|
3599
|
+
});
|
|
3600
|
+
}
|
|
3601
|
+
function callDaemon(agentDir, method, params = {}) {
|
|
3602
|
+
const socketPath = controlSocketPath(agentDir);
|
|
3603
|
+
return new Promise((resolve2, reject) => {
|
|
3604
|
+
const socket = netConnect2(socketPath);
|
|
3605
|
+
socket.setEncoding("utf8");
|
|
3606
|
+
let buffer = "";
|
|
3607
|
+
socket.once("error", (error) => reject(error));
|
|
3608
|
+
socket.on("connect", () => {
|
|
3609
|
+
socket.write(`${JSON.stringify({ id: 1, method, params })}
|
|
3610
|
+
`);
|
|
3611
|
+
});
|
|
3612
|
+
socket.on("data", (chunk) => {
|
|
3613
|
+
buffer += chunk;
|
|
3614
|
+
const index = buffer.indexOf("\n");
|
|
3615
|
+
if (index < 0) return;
|
|
3616
|
+
socket.end();
|
|
3617
|
+
try {
|
|
3618
|
+
resolve2(JSON.parse(buffer.slice(0, index)));
|
|
3619
|
+
} catch (error) {
|
|
3620
|
+
reject(error);
|
|
3621
|
+
}
|
|
3622
|
+
});
|
|
3623
|
+
});
|
|
3624
|
+
}
|
|
3625
|
+
async function runUp(flags) {
|
|
3626
|
+
const agentDir = path2.resolve(str(flags, "agent-dir") ?? DEFAULT_AGENT_DIR);
|
|
3627
|
+
const name = str(flags, "name") ?? path2.basename(homedir());
|
|
3628
|
+
const repo = str(flags, "repo") ? path2.resolve(str(flags, "repo")) : null;
|
|
3629
|
+
const exec = str(flags, "exec");
|
|
3630
|
+
if (!exec) {
|
|
3631
|
+
console.error('\u9700\u8981 --exec\uFF0C\u4F8B\u5982\uFF1A--exec "pi -p {prompt}"\uFF08\u8FD9\u662F\u88AB\u6D3E\u65B9\u6267\u884C\u4EFB\u52A1\u7528\u7684\u547D\u4EE4\u884C\uFF09');
|
|
3632
|
+
process2.exit(2);
|
|
3633
|
+
}
|
|
3634
|
+
const log = (message) => console.log(`[${(/* @__PURE__ */ new Date()).toISOString()}] ${message}`);
|
|
3635
|
+
const service = new FabricService({
|
|
3636
|
+
agentDir,
|
|
3637
|
+
port: num(flags, "port", 7788),
|
|
3638
|
+
appVersion: str(flags, "app-version") ?? "0.0.0-fabric-only",
|
|
3639
|
+
labels: str(flags, "labels") ? () => str(flags, "labels").split(",").map((item) => item.trim()) : void 0,
|
|
3640
|
+
runner: createShellRunner({
|
|
3641
|
+
exec,
|
|
3642
|
+
repo,
|
|
3643
|
+
agentDir,
|
|
3644
|
+
timeoutMs: num(flags, "timeout", DEFAULT_TASK_TIMEOUT_MS),
|
|
3645
|
+
auditPath: path2.join(agentDir, "fabric", "audit", "tasks.jsonl"),
|
|
3646
|
+
log
|
|
3647
|
+
}),
|
|
3648
|
+
log
|
|
3649
|
+
});
|
|
3650
|
+
const started = await service.start();
|
|
3651
|
+
service.setDiscoverable(flags.discoverable === true);
|
|
3652
|
+
const handlers = makeHandlers(service, { startedAt: Date.now(), agentDir });
|
|
3653
|
+
const socketPath = controlSocketPath(agentDir);
|
|
3654
|
+
const server = await serveControl(handlers, socketPath);
|
|
3655
|
+
console.log(
|
|
3656
|
+
JSON.stringify({
|
|
3657
|
+
ok: true,
|
|
3658
|
+
nodeId: service.nodeId,
|
|
3659
|
+
name: service.displayName(),
|
|
3660
|
+
port: started.port,
|
|
3661
|
+
discPort: started.discPort,
|
|
3662
|
+
discoverable: service.isDiscoverable(),
|
|
3663
|
+
repo,
|
|
3664
|
+
control: socketPath,
|
|
3665
|
+
agentDir
|
|
3666
|
+
})
|
|
3667
|
+
);
|
|
3668
|
+
const shutdown = async (signal) => {
|
|
3669
|
+
log(`\u6536\u5230 ${signal}\uFF0C\u6B63\u5728\u505C\u6B62`);
|
|
3670
|
+
server.close();
|
|
3671
|
+
await service.stop().catch(() => void 0);
|
|
3672
|
+
if (process2.platform !== "win32") rmSync6(socketPath, { force: true });
|
|
3673
|
+
process2.exit(0);
|
|
3674
|
+
};
|
|
3675
|
+
process2.on("SIGINT", () => void shutdown("SIGINT"));
|
|
3676
|
+
process2.on("SIGTERM", () => void shutdown("SIGTERM"));
|
|
3677
|
+
}
|
|
3678
|
+
var HELP = `piforge-fabric \u2014 \u8DE8\u673A\u6D3E\u6D3B\uFF08\u9636\u6BB5 c\uFF0C\u65E0\u5BBF\u4E3B\u4F9D\u8D56\uFF09
|
|
3679
|
+
|
|
3680
|
+
up \u8D77 daemon\uFF1A--name <\u540D> --repo <\u4ED3\u5E93> --exec "pi -p {prompt}"
|
|
3681
|
+
[--port 7788] [--discoverable] [--labels gpu,build] [--agent-dir <\u76EE\u5F55>] [--timeout <ms>]
|
|
3682
|
+
peers \u672C\u673A + \u5DF2\u914D\u5BF9\u673A\u5668\u7684\u5728\u7EBF\u72B6\u6001
|
|
3683
|
+
scan \u626B\u4E00\u5708\u5C40\u57DF\u7F51\uFF08\u9700\u8981\u5BF9\u65B9\u5F00\u4E86 --discoverable\uFF09
|
|
3684
|
+
pair --address <ip> [--port 7788] [--name <\u540D>] \u5411\u5BF9\u7AEF\u53D1\u8D77\u914D\u5BF9\uFF0C\u6253\u5370 SAS
|
|
3685
|
+
requests \u770B\u6709\u65E0\u5F85\u786E\u8BA4\u7684\u914D\u5BF9\u8BF7\u6C42
|
|
3686
|
+
allow <nodeId> [--grants workspace-rw+bash] \u5141\u8BB8\u5165\u7AD9\u914D\u5BF9
|
|
3687
|
+
deny <nodeId> \u62D2\u7EDD\u5165\u7AD9\u914D\u5BF9
|
|
3688
|
+
dispatch --to <nodeId|auto> --prompt <\u6587\u672C> [--deadline quick|build|long] [--est <ms>]
|
|
3689
|
+
status [taskId] \u4EFB\u52A1\u5217\u8868\u6216\u5355\u6761\u8BE6\u60C5
|
|
3690
|
+
diff <taskId> \u770B\u5BF9\u7AEF\u56DE\u4F20\u7684 patch
|
|
3691
|
+
on | off \u5F00\u5173\u300C\u5141\u8BB8\u5C40\u57DF\u7F51\u53D1\u73B0\u300D\uFF08\u5E94\u7B54 SBF3\uFF09
|
|
3692
|
+
diagnose \u4E3A\u4EC0\u4E48\u626B\u4E0D\u5230 / \u6D3E\u4E0D\u51FA\u6D3B\uFF1A\u7F51\u5361\u5E7F\u64AD\u3001SBF3 \u56DE\u5305\u3001peer TCP \u53EF\u8FBE\u6027
|
|
3693
|
+
audit [--tail 20] \u8FDC\u7A0B\u4EFB\u52A1\u7684\u6267\u884C\u5BA1\u8BA1\uFF08\u6BCF\u6761\u4EFB\u52A1\u4E00\u884C jsonl\uFF09
|
|
3694
|
+
panic \u6025\u505C\uFF1A\u505C\u53D1\u73B0\u3001\u65AD\u5168\u90E8\u8FDE\u63A5\u3001\u628A\u6BCF\u53F0\u673A\u5668\u6863\u4F4D\u964D\u56DE read-only
|
|
3695
|
+
`;
|
|
3696
|
+
async function main(argv) {
|
|
3697
|
+
const { command, flags, positional } = parseArgs(argv);
|
|
3698
|
+
const agentDir = path2.resolve(str(flags, "agent-dir") ?? DEFAULT_AGENT_DIR);
|
|
3699
|
+
const call = async (method, params = {}) => {
|
|
3700
|
+
const reply = await callDaemon(agentDir, method, params);
|
|
3701
|
+
return reply;
|
|
3702
|
+
};
|
|
3703
|
+
const print = (reply) => {
|
|
3704
|
+
if (!reply.ok) {
|
|
3705
|
+
console.error(JSON.stringify(reply.error ?? { code: "E_UNKNOWN" }));
|
|
3706
|
+
process2.exitCode = 1;
|
|
3707
|
+
return;
|
|
3708
|
+
}
|
|
3709
|
+
console.log(JSON.stringify(reply.result, null, 2));
|
|
3710
|
+
};
|
|
3711
|
+
switch (command) {
|
|
3712
|
+
case "help":
|
|
3713
|
+
case "--help":
|
|
3714
|
+
case "-h":
|
|
3715
|
+
console.log(HELP);
|
|
3716
|
+
return;
|
|
3717
|
+
case "up":
|
|
3718
|
+
await runUp(flags);
|
|
3719
|
+
return;
|
|
3720
|
+
case "peers":
|
|
3721
|
+
print(await call("fabric.snapshot"));
|
|
3722
|
+
return;
|
|
3723
|
+
case "scan":
|
|
3724
|
+
print(await call("fabric.scan", { force: true }));
|
|
3725
|
+
return;
|
|
3726
|
+
case "pair":
|
|
3727
|
+
print(
|
|
3728
|
+
await call("fabric.pair", {
|
|
3729
|
+
address: str(flags, "address") ?? "",
|
|
3730
|
+
port: num(flags, "port", 7788),
|
|
3731
|
+
...str(flags, "name") ? { name: str(flags, "name") } : {}
|
|
3732
|
+
})
|
|
3733
|
+
);
|
|
3734
|
+
return;
|
|
3735
|
+
case "requests":
|
|
3736
|
+
print(await call("fabric.snapshot"));
|
|
3737
|
+
return;
|
|
3738
|
+
case "allow":
|
|
3739
|
+
print(
|
|
3740
|
+
await call("fabric.allow", {
|
|
3741
|
+
nodeId: positional[0] ?? "",
|
|
3742
|
+
...str(flags, "grants") ? { grants: str(flags, "grants") } : {}
|
|
3743
|
+
})
|
|
3744
|
+
);
|
|
3745
|
+
return;
|
|
3746
|
+
case "deny":
|
|
3747
|
+
print(await call("fabric.deny", { nodeId: positional[0] ?? "" }));
|
|
3748
|
+
return;
|
|
3749
|
+
case "dispatch":
|
|
3750
|
+
print(
|
|
3751
|
+
await call("fabric.dispatch", {
|
|
3752
|
+
to: str(flags, "to") ?? "auto",
|
|
3753
|
+
prompt: str(flags, "prompt") ?? "",
|
|
3754
|
+
...str(flags, "deadline") ? { deadlineClass: str(flags, "deadline") } : {},
|
|
3755
|
+
...num(flags, "est") !== void 0 ? { estimatedMs: num(flags, "est") } : {}
|
|
3756
|
+
})
|
|
3757
|
+
);
|
|
3758
|
+
return;
|
|
3759
|
+
case "status":
|
|
3760
|
+
print(await call("fabric.status", positional[0] ? { taskId: positional[0] } : {}));
|
|
3761
|
+
return;
|
|
3762
|
+
case "diff":
|
|
3763
|
+
print(await call("fabric.diff", { taskId: positional[0] ?? "" }));
|
|
3764
|
+
return;
|
|
3765
|
+
case "diagnose":
|
|
3766
|
+
print(await call("fabric.diagnose"));
|
|
3767
|
+
return;
|
|
3768
|
+
case "audit":
|
|
3769
|
+
print(await call("fabric.audit", { tail: num(flags, "tail", 20) }));
|
|
3770
|
+
return;
|
|
3771
|
+
case "panic":
|
|
3772
|
+
print(await call("fabric.panic"));
|
|
3773
|
+
return;
|
|
3774
|
+
case "on":
|
|
3775
|
+
print(await call("fabric.setDiscoverable", { enabled: true }));
|
|
3776
|
+
return;
|
|
3777
|
+
case "off":
|
|
3778
|
+
print(await call("fabric.setDiscoverable", { enabled: false }));
|
|
3779
|
+
return;
|
|
3780
|
+
default:
|
|
3781
|
+
console.error(`\u672A\u77E5\u547D\u4EE4: ${command}
|
|
3782
|
+
|
|
3783
|
+
${HELP}`);
|
|
3784
|
+
process2.exit(2);
|
|
3785
|
+
}
|
|
3786
|
+
}
|
|
3787
|
+
if (import.meta.url === `file://${process2.argv[1]?.replace(/\\/g, "/")}` || process2.argv[1]?.endsWith("daemon.ts")) {
|
|
3788
|
+
void main(process2.argv.slice(2));
|
|
3789
|
+
}
|
|
3790
|
+
export {
|
|
3791
|
+
DEFAULT_AGENT_DIR,
|
|
3792
|
+
callDaemon,
|
|
3793
|
+
controlSocketPath,
|
|
3794
|
+
main,
|
|
3795
|
+
parseArgs,
|
|
3796
|
+
serveControl
|
|
3797
|
+
};
|