@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/package.json
CHANGED
|
@@ -1,6 +1,32 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@yourstandby/fabric",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "LAN agent fabric: pair two machines, dispatch a task, get a patch back.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=20"
|
|
9
|
+
},
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./src/index.ts",
|
|
13
|
+
"default": "./dist/index.js"
|
|
14
|
+
},
|
|
15
|
+
"./daemon": {
|
|
16
|
+
"types": "./src/daemon.ts",
|
|
17
|
+
"default": "./dist/daemon.js"
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"dist",
|
|
22
|
+
"src",
|
|
23
|
+
"README.md"
|
|
24
|
+
],
|
|
25
|
+
"scripts": {
|
|
26
|
+
"build": "node ../../scripts/build-fabric-packages.mjs",
|
|
27
|
+
"prepack": "node ../../scripts/build-fabric-packages.mjs"
|
|
28
|
+
},
|
|
29
|
+
"publishConfig": {
|
|
30
|
+
"access": "public"
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import test from "node:test";
|
|
2
|
+
import assert from "node:assert/strict";
|
|
3
|
+
import { mkdtempSync, rmSync, statSync } from "node:fs";
|
|
4
|
+
import { tmpdir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import {
|
|
7
|
+
ARTIFACT_MAX_OBJECT_BYTES,
|
|
8
|
+
ArtifactError,
|
|
9
|
+
ArtifactStore,
|
|
10
|
+
artifactsRoot,
|
|
11
|
+
isArtifactRef,
|
|
12
|
+
} from "./artifacts.ts";
|
|
13
|
+
|
|
14
|
+
function setup(options: { maxBytes?: number; maxObjects?: number } = {}) {
|
|
15
|
+
const dir = mkdtempSync(join(tmpdir(), "pi-fabric-artifacts-"));
|
|
16
|
+
const store = new ArtifactStore(dir, options);
|
|
17
|
+
return {
|
|
18
|
+
dir,
|
|
19
|
+
store,
|
|
20
|
+
cleanup: () => rmSync(dir, { recursive: true, force: true }),
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
test("put 幂等:同样内容只有一个对象,引用带 sha256 与长度", () => {
|
|
25
|
+
const env = setup();
|
|
26
|
+
try {
|
|
27
|
+
const a = env.store.put(Buffer.from("hello fabric"), "input");
|
|
28
|
+
const b = env.store.put(Buffer.from("hello fabric"), "input");
|
|
29
|
+
assert.equal(a.sha256, b.sha256);
|
|
30
|
+
assert.equal(a.len, 12);
|
|
31
|
+
assert.equal(a.kind, "input");
|
|
32
|
+
assert.equal(env.store.stats().objects, 1);
|
|
33
|
+
assert.equal(isArtifactRef(a), true);
|
|
34
|
+
} finally {
|
|
35
|
+
env.cleanup();
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
test("读回校验:内容对得上才返回,被改过或截断报 CORRUPT", () => {
|
|
40
|
+
const env = setup();
|
|
41
|
+
try {
|
|
42
|
+
const ref = env.store.put(Buffer.from("payload"), "result");
|
|
43
|
+
assert.equal(env.store.read(ref).toString(), "payload");
|
|
44
|
+
const bad = { ...ref, len: ref.len + 1 };
|
|
45
|
+
assert.throws(
|
|
46
|
+
() => env.store.read(bad),
|
|
47
|
+
(error: unknown) => error instanceof ArtifactError && error.code === "E_ARTIFACT_CORRUPT",
|
|
48
|
+
);
|
|
49
|
+
const missing = { ...ref, sha256: "0".repeat(64) };
|
|
50
|
+
assert.throws(
|
|
51
|
+
() => env.store.read(missing),
|
|
52
|
+
(error: unknown) => error instanceof ArtifactError && error.code === "E_ARTIFACT_MISSING",
|
|
53
|
+
);
|
|
54
|
+
} finally {
|
|
55
|
+
env.cleanup();
|
|
56
|
+
}
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test("坏引用直接拒绝,不会去拼一个越权路径", () => {
|
|
60
|
+
const env = setup();
|
|
61
|
+
try {
|
|
62
|
+
assert.throws(
|
|
63
|
+
() => env.store.read({ sha256: "../../etc/passwd", len: 1, kind: "log" } as never),
|
|
64
|
+
(error: unknown) => error instanceof ArtifactError && error.code === "E_INVALID_PARAMS",
|
|
65
|
+
);
|
|
66
|
+
assert.throws(
|
|
67
|
+
() => env.store.read({ sha256: "a".repeat(64), len: ARTIFACT_MAX_OBJECT_BYTES + 1, kind: "log" }),
|
|
68
|
+
(error: unknown) => error instanceof ArtifactError && error.code === "E_ARTIFACT_TOO_LARGE",
|
|
69
|
+
);
|
|
70
|
+
} finally {
|
|
71
|
+
env.cleanup();
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
test("LRU 淘汰按容量执行:先删最久没被读过的", () => {
|
|
76
|
+
const env = setup({ maxBytes: 24, maxObjects: 10 });
|
|
77
|
+
try {
|
|
78
|
+
const first = env.store.put(Buffer.alloc(10, 1));
|
|
79
|
+
const second = env.store.put(Buffer.alloc(10, 2));
|
|
80
|
+
const third = env.store.put(Buffer.alloc(10, 3));
|
|
81
|
+
assert.equal(env.store.stats().objects, 2);
|
|
82
|
+
assert.equal(env.store.has(second.sha256), true);
|
|
83
|
+
assert.equal(env.store.has(third.sha256), true);
|
|
84
|
+
assert.equal(env.store.has(first.sha256), false);
|
|
85
|
+
} finally {
|
|
86
|
+
env.cleanup();
|
|
87
|
+
}
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
test("连续写入的 mtime 严格递增:Windows 的墙钟粒度再粗也不会打平", () => {
|
|
91
|
+
// Windows 上连续写文件经常落在同一个时钟拍里(实测 20 次写入必出现相同的
|
|
92
|
+
// mtimeMs),mtime 一打平,enforceQuota 的排序就退化成 readdir 顺序,删错对象。
|
|
93
|
+
const realNow = Date.now;
|
|
94
|
+
const stampsOf = (env: ReturnType<typeof setup>, refs: { sha256: string }[]) =>
|
|
95
|
+
refs.map((ref) =>
|
|
96
|
+
statSync(join(artifactsRoot(env.dir), ref.sha256.slice(0, 2), ref.sha256)).mtimeMs,
|
|
97
|
+
);
|
|
98
|
+
const assertIncreasing = (stamps: number[]) => {
|
|
99
|
+
for (let i = 1; i < stamps.length; i += 1) {
|
|
100
|
+
assert.equal(stamps[i]! > stamps[i - 1]!, true, `mtime 第 ${i} 次没有递增`);
|
|
101
|
+
}
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
const env = setup({ maxBytes: 1_000_000, maxObjects: 100 });
|
|
105
|
+
try {
|
|
106
|
+
const refs = Array.from({ length: 20 }, (_, n) => env.store.put(Buffer.alloc(8, n + 1)));
|
|
107
|
+
assertIncreasing(stampsOf(env, refs));
|
|
108
|
+
|
|
109
|
+
// 墙钟卡死(时钟不前进)时也要单调:只能靠逻辑时钟推进。
|
|
110
|
+
Date.now = () => 1_700_000_000_000;
|
|
111
|
+
const frozen = Array.from({ length: 5 }, (_, n) => env.store.put(Buffer.alloc(8, 100 + n)));
|
|
112
|
+
assertIncreasing(stampsOf(env, frozen));
|
|
113
|
+
} finally {
|
|
114
|
+
Date.now = realNow;
|
|
115
|
+
env.cleanup();
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
test("条数上限同样生效", () => {
|
|
120
|
+
const env = setup({ maxBytes: 1_000_000, maxObjects: 2 });
|
|
121
|
+
try {
|
|
122
|
+
env.store.put(Buffer.from("a"));
|
|
123
|
+
env.store.put(Buffer.from("b"));
|
|
124
|
+
env.store.put(Buffer.from("c"));
|
|
125
|
+
assert.equal(env.store.stats().objects, 2);
|
|
126
|
+
} finally {
|
|
127
|
+
env.cleanup();
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
|
|
131
|
+
test("TTL:被引用的留一周,无主的留一天", () => {
|
|
132
|
+
const env = setup();
|
|
133
|
+
try {
|
|
134
|
+
const owned = env.store.put(Buffer.from("owned"), "result");
|
|
135
|
+
const orphan = env.store.put(Buffer.from("orphan"), "log");
|
|
136
|
+
const day = 24 * 60 * 60 * 1000;
|
|
137
|
+
const twoDaysLater = Date.now() + 2 * day;
|
|
138
|
+
const result = env.store.sweep([owned.sha256], twoDaysLater);
|
|
139
|
+
assert.equal(result.removed, 1);
|
|
140
|
+
assert.equal(env.store.has(orphan.sha256), false);
|
|
141
|
+
assert.equal(env.store.has(owned.sha256), true);
|
|
142
|
+
const afterWeek = Date.now() + 8 * day;
|
|
143
|
+
env.store.sweep([owned.sha256], afterWeek);
|
|
144
|
+
assert.equal(env.store.has(owned.sha256), false);
|
|
145
|
+
} finally {
|
|
146
|
+
env.cleanup();
|
|
147
|
+
}
|
|
148
|
+
});
|
package/src/artifacts.ts
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 内容寻址产物库(Fabric artifact)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么不让 payload 走协议帧:协议是单连接 NDJSON 多路复用,一个大帧会把后面的
|
|
5
|
+
* 心跳 pong 一起排队,对端就会误判离线、触发重连、任务重跑。所以帧里只出现
|
|
6
|
+
* {sha256, len, kind} 这个引用,真正的字节落在这里,按引用单次拉取。
|
|
7
|
+
*
|
|
8
|
+
* 存储:<agentDir>/fabric/artifacts/<前两位>/<sha256>
|
|
9
|
+
* 清理:容量/条数上限按 LRU 淘汰(mtime 即访问时间),TTL 由调用方带引用集合来扫。
|
|
10
|
+
*/
|
|
11
|
+
import { createHash } from "node:crypto";
|
|
12
|
+
import {
|
|
13
|
+
createReadStream,
|
|
14
|
+
existsSync,
|
|
15
|
+
mkdirSync,
|
|
16
|
+
readdirSync,
|
|
17
|
+
readFileSync,
|
|
18
|
+
renameSync,
|
|
19
|
+
rmSync,
|
|
20
|
+
statSync,
|
|
21
|
+
utimesSync,
|
|
22
|
+
writeFileSync,
|
|
23
|
+
} from "node:fs";
|
|
24
|
+
import { dirname, join } from "node:path";
|
|
25
|
+
|
|
26
|
+
export const ARTIFACT_MAX_BYTES = 512 * 1024 * 1024;
|
|
27
|
+
export const ARTIFACT_MAX_OBJECTS = 1_000;
|
|
28
|
+
/** 没被任何任务引用的对象:一天后就没用了。 */
|
|
29
|
+
export const ARTIFACT_UNREFERENCED_TTL_MS = 24 * 60 * 60 * 1000;
|
|
30
|
+
/** 被任务引用的对象:留一周,够事后追查。 */
|
|
31
|
+
export const ARTIFACT_REFERENCED_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
|
32
|
+
/** 单次读上限:引用里带 len,超过这个值的读取要显式允许。 */
|
|
33
|
+
export const ARTIFACT_MAX_OBJECT_BYTES = 256 * 1024 * 1024;
|
|
34
|
+
|
|
35
|
+
export type ArtifactKind = "input" | "result" | "diff" | "log" | "bundle";
|
|
36
|
+
|
|
37
|
+
export interface ArtifactRef {
|
|
38
|
+
sha256: string;
|
|
39
|
+
len: number;
|
|
40
|
+
kind: ArtifactKind;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export class ArtifactError extends Error {
|
|
44
|
+
code: string;
|
|
45
|
+
constructor(code: string, message: string) {
|
|
46
|
+
super(message);
|
|
47
|
+
this.name = "ArtifactError";
|
|
48
|
+
this.code = code;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const SHA256_RE = /^[0-9a-f]{64}$/;
|
|
53
|
+
|
|
54
|
+
export function artifactsRoot(agentDir: string): string {
|
|
55
|
+
return join(agentDir, "fabric", "artifacts");
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function isArtifactRef(value: unknown): value is ArtifactRef {
|
|
59
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
60
|
+
const ref = value as Record<string, unknown>;
|
|
61
|
+
return (
|
|
62
|
+
typeof ref.sha256 === "string" &&
|
|
63
|
+
SHA256_RE.test(ref.sha256) &&
|
|
64
|
+
typeof ref.len === "number" &&
|
|
65
|
+
Number.isInteger(ref.len) &&
|
|
66
|
+
ref.len >= 0 &&
|
|
67
|
+
typeof ref.kind === "string"
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function sanitizeRef(value: unknown): ArtifactRef {
|
|
72
|
+
if (!isArtifactRef(value)) throw new ArtifactError("E_INVALID_PARAMS", "invalid artifact ref");
|
|
73
|
+
if (value.len > ARTIFACT_MAX_OBJECT_BYTES) {
|
|
74
|
+
throw new ArtifactError("E_ARTIFACT_TOO_LARGE", "artifact exceeds the single-object limit");
|
|
75
|
+
}
|
|
76
|
+
return { sha256: value.sha256, len: value.len, kind: value.kind as ArtifactKind };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface ArtifactStoreOptions {
|
|
80
|
+
root?: string;
|
|
81
|
+
maxBytes?: number;
|
|
82
|
+
maxObjects?: number;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export class ArtifactStore {
|
|
86
|
+
private readonly root: string;
|
|
87
|
+
private readonly maxBytes: number;
|
|
88
|
+
private readonly maxObjects: number;
|
|
89
|
+
/** LRU 逻辑时钟(毫秒),保证连续触碰拿到严格递增的 mtime。 */
|
|
90
|
+
private clock = 0;
|
|
91
|
+
|
|
92
|
+
constructor(agentDir: string, options: ArtifactStoreOptions = {}) {
|
|
93
|
+
this.root = options.root ?? artifactsRoot(agentDir);
|
|
94
|
+
this.maxBytes = options.maxBytes ?? ARTIFACT_MAX_BYTES;
|
|
95
|
+
this.maxObjects = options.maxObjects ?? ARTIFACT_MAX_OBJECTS;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** 幂等:同样的内容写两次只有一个对象(sha256 就是幂等键)。 */
|
|
99
|
+
put(data: Buffer, kind: ArtifactKind = "input"): ArtifactRef {
|
|
100
|
+
if (data.length > ARTIFACT_MAX_OBJECT_BYTES) {
|
|
101
|
+
throw new ArtifactError("E_ARTIFACT_TOO_LARGE", "artifact exceeds the single-object limit");
|
|
102
|
+
}
|
|
103
|
+
const sha256 = createHash("sha256").update(data).digest("hex");
|
|
104
|
+
const file = this.pathFor(sha256);
|
|
105
|
+
if (!existsSync(file)) {
|
|
106
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
107
|
+
const temp = file + ".tmp";
|
|
108
|
+
writeFileSync(temp, data);
|
|
109
|
+
renameSync(temp, file);
|
|
110
|
+
}
|
|
111
|
+
// 新对象同样算“刚用过”,统一盖单调时间戳:Windows 的系统时钟粒度约 15.6ms,
|
|
112
|
+
// 同一拍里连续写入的三个对象 mtime 会完全相等,LRU 淘汰就会删到别人。
|
|
113
|
+
this.touch(sha256);
|
|
114
|
+
this.enforceQuota();
|
|
115
|
+
return { sha256, len: data.length, kind };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** 读取并校验:内容被改过或截断一律报 E_ARTIFACT_CORRUPT,不把坏数据交给任务。 */
|
|
119
|
+
read(ref: ArtifactRef): Buffer {
|
|
120
|
+
const safe = sanitizeRef(ref);
|
|
121
|
+
const file = this.pathFor(safe.sha256);
|
|
122
|
+
if (!existsSync(file)) throw new ArtifactError("E_ARTIFACT_MISSING", "artifact not found");
|
|
123
|
+
const data = readFileSync(file);
|
|
124
|
+
const digest = createHash("sha256").update(data).digest("hex");
|
|
125
|
+
if (digest !== safe.sha256) {
|
|
126
|
+
throw new ArtifactError("E_ARTIFACT_CORRUPT", "artifact content does not match its sha256");
|
|
127
|
+
}
|
|
128
|
+
if (safe.len !== data.length) {
|
|
129
|
+
throw new ArtifactError("E_ARTIFACT_CORRUPT", "artifact length does not match its ref");
|
|
130
|
+
}
|
|
131
|
+
this.touch(safe.sha256);
|
|
132
|
+
return data;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
stream(ref: ArtifactRef) {
|
|
136
|
+
const safe = sanitizeRef(ref);
|
|
137
|
+
const file = this.pathFor(safe.sha256);
|
|
138
|
+
if (!existsSync(file)) throw new ArtifactError("E_ARTIFACT_MISSING", "artifact not found");
|
|
139
|
+
this.touch(safe.sha256);
|
|
140
|
+
return createReadStream(file);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
has(sha256: string): boolean {
|
|
144
|
+
return SHA256_RE.test(sha256) && existsSync(this.pathFor(sha256));
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
stats(): { bytes: number; objects: number } {
|
|
148
|
+
let bytes = 0;
|
|
149
|
+
let objects = 0;
|
|
150
|
+
for (const entry of this.entries()) {
|
|
151
|
+
bytes += entry.size;
|
|
152
|
+
objects += 1;
|
|
153
|
+
}
|
|
154
|
+
return { bytes, objects };
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** 按 LRU(mtime)淘汰到配额以内。写得进来但永远删不掉,最终会把磁盘吃满。 */
|
|
158
|
+
enforceQuota(now = Date.now()): { removed: number; bytesFreed: number } {
|
|
159
|
+
const entries = this.entries();
|
|
160
|
+
let bytes = entries.reduce((sum, entry) => sum + entry.size, 0);
|
|
161
|
+
let objects = entries.length;
|
|
162
|
+
let removed = 0;
|
|
163
|
+
let bytesFreed = 0;
|
|
164
|
+
for (const entry of entries) {
|
|
165
|
+
if (bytes <= this.maxBytes && objects <= this.maxObjects) break;
|
|
166
|
+
rmSync(entry.file, { force: true });
|
|
167
|
+
bytes -= entry.size;
|
|
168
|
+
objects -= 1;
|
|
169
|
+
bytesFreed += entry.size;
|
|
170
|
+
removed += 1;
|
|
171
|
+
}
|
|
172
|
+
void now;
|
|
173
|
+
return { removed, bytesFreed };
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** TTL 清理:被引用的留一周,没被引用的留一天。 */
|
|
177
|
+
sweep(
|
|
178
|
+
referenced: Iterable<string> = [],
|
|
179
|
+
now = Date.now(),
|
|
180
|
+
): { removed: number; bytesFreed: number } {
|
|
181
|
+
const keep = new Set(referenced);
|
|
182
|
+
const referencedTtl = ARTIFACT_REFERENCED_TTL_MS;
|
|
183
|
+
const unreferencedTtl = ARTIFACT_UNREFERENCED_TTL_MS;
|
|
184
|
+
let removed = 0;
|
|
185
|
+
let bytesFreed = 0;
|
|
186
|
+
for (const entry of this.entries()) {
|
|
187
|
+
const ttl = keep.has(entry.sha256) ? referencedTtl : unreferencedTtl;
|
|
188
|
+
if (now - entry.mtime <= ttl) continue;
|
|
189
|
+
rmSync(entry.file, { force: true });
|
|
190
|
+
removed += 1;
|
|
191
|
+
bytesFreed += entry.size;
|
|
192
|
+
}
|
|
193
|
+
return { removed, bytesFreed };
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
private pathFor(sha256: string): string {
|
|
197
|
+
if (!SHA256_RE.test(sha256)) throw new ArtifactError("E_INVALID_PARAMS", "bad sha256");
|
|
198
|
+
return join(this.root, sha256.slice(0, 2), sha256);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* 单调递增的毫秒时间戳:同一毫秒(Windows 上甚至是同一 15.6ms 时钟拍)里的连续
|
|
203
|
+
* 操作也必须分得出先后,否则 mtime 打平后 LRU 淘汰顺序退化成 readdir 顺序。
|
|
204
|
+
* 只能按整毫秒推进——stat().mtimeMs 是 double,毫秒以下在今天的时间戳量级上根本存不下。
|
|
205
|
+
*/
|
|
206
|
+
private nextStamp(): number {
|
|
207
|
+
const now = Date.now();
|
|
208
|
+
this.clock = now > this.clock ? now : this.clock + 1;
|
|
209
|
+
return this.clock;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
private touch(sha256: string): void {
|
|
213
|
+
const at = new Date(this.nextStamp());
|
|
214
|
+
try {
|
|
215
|
+
utimesSync(this.pathFor(sha256), at, at);
|
|
216
|
+
} catch {
|
|
217
|
+
// 触碰失败只影响 LRU 精度,不影响正确性。
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
private entries(): { sha256: string; file: string; size: number; mtime: number }[] {
|
|
222
|
+
if (!existsSync(this.root)) return [];
|
|
223
|
+
const collected: { sha256: string; file: string; size: number; mtime: number }[] = [];
|
|
224
|
+
for (const bucket of readdirSync(this.root)) {
|
|
225
|
+
if (!/^[0-9a-f]{2}$/.test(bucket)) continue;
|
|
226
|
+
const bucketDir = join(this.root, bucket);
|
|
227
|
+
let names: string[];
|
|
228
|
+
try {
|
|
229
|
+
names = readdirSync(bucketDir);
|
|
230
|
+
} catch {
|
|
231
|
+
continue;
|
|
232
|
+
}
|
|
233
|
+
for (const name of names) {
|
|
234
|
+
if (!SHA256_RE.test(name)) continue;
|
|
235
|
+
const file = join(bucketDir, name);
|
|
236
|
+
try {
|
|
237
|
+
const stat = statSync(file);
|
|
238
|
+
if (!stat.isFile()) continue;
|
|
239
|
+
collected.push({ sha256: name, file, size: stat.size, mtime: stat.mtimeMs });
|
|
240
|
+
} catch {
|
|
241
|
+
// 并发删除,跳过。
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
return collected.sort((a, b) => a.mtime - b.mtime);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 阶段 c 的远程执行器:把 Fabric 远程任务接到「用户配置的一条 shell 命令行」上。
|
|
3
|
+
*
|
|
4
|
+
* 为什么不复用 fabric-runner.ts 的 spawnSubagent:
|
|
5
|
+
* 那条路要求整个 Pi SDK / 会话 / 模型配置在场。--fabric-only daemon 是从 Electron 里
|
|
6
|
+
* 剥出来的裸进程,它只需要「给一段 prompt,跑一个 agent CLI,收 diff」。
|
|
7
|
+
* 执行器由用户填(--exec "pi -p {prompt}" / "claude -p {prompt}"),本文件不认识任何具体 agent。
|
|
8
|
+
*
|
|
9
|
+
* 两条硬约束与 spawnSubagent 一致:
|
|
10
|
+
* 1. 工作目录必须来自 prepareWorkspace(独立 git worktree),绝不直接用本机用户工作区;
|
|
11
|
+
* 2. 有 repo 才回传 patch;没有 repo 的任务只回文字结论。
|
|
12
|
+
*/
|
|
13
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
14
|
+
import { appendFileSync, mkdirSync, rmSync } from "node:fs";
|
|
15
|
+
import path from "node:path";
|
|
16
|
+
import { progressNote } from "../../../contract/domains/fabric.ts";
|
|
17
|
+
import type { FabricRemoteRunner } from "./dispatcher.ts";
|
|
18
|
+
|
|
19
|
+
export interface ShellRunnerOptions {
|
|
20
|
+
/** 例如 `pi -p {prompt}`;没有 {prompt} 占位符时把它拼在末尾。 */
|
|
21
|
+
exec: string;
|
|
22
|
+
/** 被派方默认仓库:远程任务在它的 worktree 副本里跑,改动用 patch 回传。 */
|
|
23
|
+
repo?: string | null;
|
|
24
|
+
agentDir: string;
|
|
25
|
+
timeoutMs?: number;
|
|
26
|
+
maxOutputBytes?: number;
|
|
27
|
+
/** 每条远程任务落一行审计(jsonl);不给就不记。 */
|
|
28
|
+
auditPath?: string | null;
|
|
29
|
+
log?: (message: string) => void;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export const DEFAULT_TASK_TIMEOUT_MS = 30 * 60 * 1000;
|
|
33
|
+
export const DEFAULT_MAX_OUTPUT_BYTES = 4 * 1024 * 1024;
|
|
34
|
+
|
|
35
|
+
/** 把 prompt 变成「能安全塞进一条命令行」的一个参数。 */
|
|
36
|
+
export function quotePrompt(text: string, platform: NodeJS.Platform = process.platform): string {
|
|
37
|
+
if (platform === "win32") return `"${text.replace(/"/g, '\\"')}"`;
|
|
38
|
+
return `'${text.replace(/'/g, "'\\''")}'`;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function buildCommand(
|
|
42
|
+
template: string,
|
|
43
|
+
prompt: string,
|
|
44
|
+
platform: NodeJS.Platform = process.platform,
|
|
45
|
+
): string {
|
|
46
|
+
const quoted = quotePrompt(prompt, platform);
|
|
47
|
+
return template.includes("{prompt}") ? template.split("{prompt}").join(quoted) : `${template} ${quoted}`;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
interface ShellResult {
|
|
51
|
+
code: number | null;
|
|
52
|
+
stdout: string;
|
|
53
|
+
stderr: string;
|
|
54
|
+
timedOut: boolean;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function runShell(command: string, cwd: string, timeoutMs: number, maxBytes: number): Promise<ShellResult> {
|
|
58
|
+
return new Promise((resolve) => {
|
|
59
|
+
const child = spawn(command, {
|
|
60
|
+
cwd,
|
|
61
|
+
shell: true,
|
|
62
|
+
windowsHide: true,
|
|
63
|
+
env: { ...process.env, FABRIC_WORKDIR: cwd },
|
|
64
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
65
|
+
});
|
|
66
|
+
let stdout = "";
|
|
67
|
+
let stderr = "";
|
|
68
|
+
let timedOut = false;
|
|
69
|
+
const cap = (current: string, chunk: Buffer) =>
|
|
70
|
+
current.length >= maxBytes ? current : current + chunk.toString("utf8").slice(0, maxBytes - current.length);
|
|
71
|
+
child.stdout.on("data", (chunk: Buffer) => {
|
|
72
|
+
stdout = cap(stdout, chunk);
|
|
73
|
+
});
|
|
74
|
+
child.stderr.on("data", (chunk: Buffer) => {
|
|
75
|
+
stderr = cap(stderr, chunk);
|
|
76
|
+
});
|
|
77
|
+
const timer = setTimeout(() => {
|
|
78
|
+
timedOut = true;
|
|
79
|
+
// 必须杀进程树:agent CLI 常有自己的子进程,只杀父进程会留下孤儿继续写文件。
|
|
80
|
+
if (process.platform === "win32" && child.pid) {
|
|
81
|
+
spawnSync("taskkill", ["/T", "/F", "/PID", String(child.pid)], { windowsHide: true });
|
|
82
|
+
} else {
|
|
83
|
+
child.kill("SIGKILL");
|
|
84
|
+
}
|
|
85
|
+
}, Math.max(1_000, timeoutMs));
|
|
86
|
+
child.on("error", (error) => {
|
|
87
|
+
clearTimeout(timer);
|
|
88
|
+
resolve({ code: 1, stdout, stderr: `${stderr}\n${error.message}`, timedOut });
|
|
89
|
+
});
|
|
90
|
+
child.on("close", (code) => {
|
|
91
|
+
clearTimeout(timer);
|
|
92
|
+
resolve({ code, stdout, stderr, timedOut });
|
|
93
|
+
});
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function git(args: string[], cwd: string): { ok: boolean; stdout: string; stderr: string } {
|
|
98
|
+
const result = spawnSync("git", args, { cwd, encoding: "utf8", windowsHide: true });
|
|
99
|
+
return {
|
|
100
|
+
ok: result.status === 0,
|
|
101
|
+
stdout: result.stdout ?? "",
|
|
102
|
+
stderr: result.stderr ?? result.error?.message ?? "",
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export interface PreparedWorkspace {
|
|
107
|
+
cwd: string;
|
|
108
|
+
diff?: () => Promise<Buffer | null>;
|
|
109
|
+
cleanup?: () => Promise<void>;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** 有 repo 就开一间 worktree(detached HEAD),没有就退到 agentDir 下的 scratch 目录。 */
|
|
113
|
+
export function prepareWorkspace(options: ShellRunnerOptions, taskId: string): PreparedWorkspace {
|
|
114
|
+
const repo = options.repo?.trim();
|
|
115
|
+
if (!repo) {
|
|
116
|
+
const cwd = path.join(options.agentDir, "fabric", "scratch", taskId);
|
|
117
|
+
mkdirSync(cwd, { recursive: true });
|
|
118
|
+
return {
|
|
119
|
+
cwd,
|
|
120
|
+
cleanup: async () => {
|
|
121
|
+
rmSync(cwd, { recursive: true, force: true });
|
|
122
|
+
},
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
const cwd = path.join(options.agentDir, "fabric", "worktrees", taskId);
|
|
126
|
+
mkdirSync(path.dirname(cwd), { recursive: true });
|
|
127
|
+
const added = git(["worktree", "add", "--detach", cwd, "HEAD"], repo);
|
|
128
|
+
if (!added.ok) {
|
|
129
|
+
throw new Error(`E_WORKSPACE: git worktree add failed: ${added.stderr.trim() || added.stdout.trim()}`);
|
|
130
|
+
}
|
|
131
|
+
return {
|
|
132
|
+
cwd,
|
|
133
|
+
diff: async () => {
|
|
134
|
+
// 先 add -A 让新建文件进 patch;--binary 保证二进制也能原样回传。
|
|
135
|
+
git(["add", "-A"], cwd);
|
|
136
|
+
const result = git(["diff", "--cached", "--binary", "--no-color"], cwd);
|
|
137
|
+
if (!result.ok) {
|
|
138
|
+
options.log?.(`fabric diff failed: ${result.stderr.trim()}`);
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
return result.stdout.trim() ? Buffer.from(result.stdout, "utf8") : null;
|
|
142
|
+
},
|
|
143
|
+
cleanup: async () => {
|
|
144
|
+
git(["worktree", "remove", "--force", cwd], repo);
|
|
145
|
+
rmSync(cwd, { recursive: true, force: true });
|
|
146
|
+
},
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function audit(options: ShellRunnerOptions, record: Record<string, unknown>): void {
|
|
151
|
+
if (!options.auditPath) return;
|
|
152
|
+
try {
|
|
153
|
+
mkdirSync(path.dirname(options.auditPath), { recursive: true });
|
|
154
|
+
appendFileSync(options.auditPath, `${JSON.stringify(record)}\n`, "utf8");
|
|
155
|
+
} catch (error) {
|
|
156
|
+
options.log?.(`fabric audit append failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export function createShellRunner(options: ShellRunnerOptions): FabricRemoteRunner {
|
|
161
|
+
const timeoutMs = options.timeoutMs ?? DEFAULT_TASK_TIMEOUT_MS;
|
|
162
|
+
const maxBytes = options.maxOutputBytes ?? DEFAULT_MAX_OUTPUT_BYTES;
|
|
163
|
+
return {
|
|
164
|
+
async run(input) {
|
|
165
|
+
const startedAt = Date.now();
|
|
166
|
+
const workspace = prepareWorkspace(options, input.taskId);
|
|
167
|
+
input.onProgress(progressNote("workspace_ready", undefined, `已在 ${workspace.cwd} 就绪`));
|
|
168
|
+
const prompt = [
|
|
169
|
+
input.prompt,
|
|
170
|
+
"",
|
|
171
|
+
"---",
|
|
172
|
+
"远程派活说明:上面的任务来自另一台已配对机器,请在当前工作目录内完成;",
|
|
173
|
+
"结束时用不超过 8 行说明:做了什么、改了哪些文件、有没有风险。",
|
|
174
|
+
].join("\n");
|
|
175
|
+
const command = buildCommand(options.exec, prompt);
|
|
176
|
+
options.log?.(`fabric task ${input.taskId} start in ${workspace.cwd}`);
|
|
177
|
+
let result: ShellResult;
|
|
178
|
+
try {
|
|
179
|
+
result = await runShell(command, workspace.cwd, timeoutMs, maxBytes);
|
|
180
|
+
const diff = workspace.diff ? await workspace.diff().catch(() => null) : null;
|
|
181
|
+
audit(options, {
|
|
182
|
+
at: new Date(startedAt).toISOString(),
|
|
183
|
+
taskId: input.taskId,
|
|
184
|
+
grant: input.grant,
|
|
185
|
+
command: options.exec,
|
|
186
|
+
cwd: workspace.cwd,
|
|
187
|
+
exitCode: result.code,
|
|
188
|
+
timedOut: result.timedOut,
|
|
189
|
+
ms: Date.now() - startedAt,
|
|
190
|
+
diffBytes: diff?.length ?? 0,
|
|
191
|
+
stdout: result.stdout.slice(-4_000),
|
|
192
|
+
stderr: result.stderr.slice(-2_000),
|
|
193
|
+
});
|
|
194
|
+
if (result.timedOut) throw new Error(`E_TIMEOUT: 超过 ${timeoutMs} ms 未结束,已杀掉进程树`);
|
|
195
|
+
return {
|
|
196
|
+
summary: (result.stdout || result.stderr || "(无输出)").replace(/\r\n/g, "\n").trim().slice(0, 1_200),
|
|
197
|
+
files: [],
|
|
198
|
+
exitCode: result.code ?? 0,
|
|
199
|
+
result: Buffer.from(`${result.stdout}\n${result.stderr}`.trim(), "utf8"),
|
|
200
|
+
diff,
|
|
201
|
+
};
|
|
202
|
+
} catch (error) {
|
|
203
|
+
audit(options, {
|
|
204
|
+
at: new Date(startedAt).toISOString(),
|
|
205
|
+
taskId: input.taskId,
|
|
206
|
+
grant: input.grant,
|
|
207
|
+
command: options.exec,
|
|
208
|
+
cwd: workspace.cwd,
|
|
209
|
+
error: error instanceof Error ? error.message : String(error),
|
|
210
|
+
ms: Date.now() - startedAt,
|
|
211
|
+
});
|
|
212
|
+
throw error;
|
|
213
|
+
} finally {
|
|
214
|
+
await workspace.cleanup?.().catch(() => undefined);
|
|
215
|
+
}
|
|
216
|
+
},
|
|
217
|
+
};
|
|
218
|
+
}
|