bom-pi 0.0.0-stage → 0.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +33 -2
- package/apps/README.md +7 -0
- package/apps/web/README.md +21 -0
- package/apps/web/pocket-adapter.mjs +323 -0
- package/apps/web/public/LICENSE.pocket +21 -0
- package/apps/web/public/activity-fold.js +28 -0
- package/apps/web/public/agent-now.js +37 -0
- package/apps/web/public/agent-tile.js +79 -0
- package/apps/web/public/app.js +975 -0
- package/apps/web/public/apple-touch-icon.png +0 -0
- package/apps/web/public/artifact-bridge.js +687 -0
- package/apps/web/public/avatar.js +87 -0
- package/apps/web/public/back.js +554 -0
- package/apps/web/public/box-keys.js +216 -0
- package/apps/web/public/browser-panel.js +1097 -0
- package/apps/web/public/browser.js +68 -0
- package/apps/web/public/calls.js +139 -0
- package/apps/web/public/chat.js +919 -0
- package/apps/web/public/clock.js +34 -0
- package/apps/web/public/commands.js +578 -0
- package/apps/web/public/composer.js +2068 -0
- package/apps/web/public/diff-parse.js +672 -0
- package/apps/web/public/diff.js +1646 -0
- package/apps/web/public/dock.js +299 -0
- package/apps/web/public/extension-ui.js +2734 -0
- package/apps/web/public/files-panel.js +775 -0
- package/apps/web/public/files.js +368 -0
- package/apps/web/public/fonts/FiraCode-VF.woff2 +0 -0
- package/apps/web/public/fonts/Geist.woff2 +0 -0
- package/apps/web/public/fonts/IBMPlexMono-Variable-Italic.woff2 +0 -0
- package/apps/web/public/fonts/IBMPlexMono-Variable.woff2 +0 -0
- package/apps/web/public/fonts/InterVariable-Italic.woff2 +0 -0
- package/apps/web/public/fonts/InterVariable.woff2 +0 -0
- package/apps/web/public/fonts/Iosevka-Bold.woff2 +0 -0
- package/apps/web/public/fonts/Iosevka-BoldItalic.woff2 +0 -0
- package/apps/web/public/fonts/Iosevka-Italic.woff2 +0 -0
- package/apps/web/public/fonts/Iosevka-Regular.woff2 +0 -0
- package/apps/web/public/fonts/Iosevka-SemiBold.woff2 +0 -0
- package/apps/web/public/fonts/Iosevka-SemiBoldItalic.woff2 +0 -0
- package/apps/web/public/fonts/JetBrainsMono-Italic.woff2 +0 -0
- package/apps/web/public/fonts/JetBrainsMono.woff2 +0 -0
- package/apps/web/public/fonts/NerdFontsSymbolsMono.woff2 +0 -0
- package/apps/web/public/fonts/SOURCES.md +69 -0
- package/apps/web/public/gestures.js +610 -0
- package/apps/web/public/highlight.js +480 -0
- package/apps/web/public/history.js +70 -0
- package/apps/web/public/home.js +169 -0
- package/apps/web/public/icon-192.png +0 -0
- package/apps/web/public/icon-512.png +0 -0
- package/apps/web/public/icon-maskable-512.png +0 -0
- package/apps/web/public/icon.svg +16 -0
- package/apps/web/public/index.html +71 -0
- package/apps/web/public/launcher.js +1293 -0
- package/apps/web/public/linked-sessions.js +55 -0
- package/apps/web/public/live.js +39 -0
- package/apps/web/public/manifest.webmanifest +32 -0
- package/apps/web/public/model-refresh.js +73 -0
- package/apps/web/public/notify.js +251 -0
- package/apps/web/public/peeks.js +920 -0
- package/apps/web/public/pip-attachments.js +182 -0
- package/apps/web/public/pip-window.js +141 -0
- package/apps/web/public/pip.js +1217 -0
- package/apps/web/public/quote-reply.js +109 -0
- package/apps/web/public/quote-text.js +31 -0
- package/apps/web/public/rich.js +403 -0
- package/apps/web/public/run-frame.js +106 -0
- package/apps/web/public/safe-mode.js +71 -0
- package/apps/web/public/seen.js +169 -0
- package/apps/web/public/session-tree.js +117 -0
- package/apps/web/public/sessions.js +2695 -0
- package/apps/web/public/share.js +126 -0
- package/apps/web/public/sheets/appearance.js +820 -0
- package/apps/web/public/sheets/branch.js +353 -0
- package/apps/web/public/sheets/extensions.js +818 -0
- package/apps/web/public/sheets/file.js +318 -0
- package/apps/web/public/sheets/find.js +250 -0
- package/apps/web/public/sheets/folder.js +680 -0
- package/apps/web/public/sheets/gallery.js +2340 -0
- package/apps/web/public/sheets/hooks.js +350 -0
- package/apps/web/public/sheets/memory.js +531 -0
- package/apps/web/public/sheets/menu.js +580 -0
- package/apps/web/public/sheets/message.js +220 -0
- package/apps/web/public/sheets/model.js +412 -0
- package/apps/web/public/sheets/people.js +414 -0
- package/apps/web/public/sheets/pi-sessions.js +264 -0
- package/apps/web/public/sheets/providers.js +525 -0
- package/apps/web/public/sheets/running.js +130 -0
- package/apps/web/public/sheets/schedules.js +71 -0
- package/apps/web/public/sheets/session.js +249 -0
- package/apps/web/public/sheets/shortcuts.js +101 -0
- package/apps/web/public/sheets/spend.js +150 -0
- package/apps/web/public/sheets/text.js +53 -0
- package/apps/web/public/sheets/viewers.js +363 -0
- package/apps/web/public/sheets/worktree.js +50 -0
- package/apps/web/public/sheets.js +410 -0
- package/apps/web/public/signin.js +57 -0
- package/apps/web/public/slots.js +208 -0
- package/apps/web/public/store.js +1760 -0
- package/apps/web/public/style.css +18625 -0
- package/apps/web/public/subagents-board.js +879 -0
- package/apps/web/public/subagents.js +273 -0
- package/apps/web/public/sw.js +169 -0
- package/apps/web/public/taps.js +26 -0
- package/apps/web/public/theme-surface.d.ts +4 -0
- package/apps/web/public/theme-surface.js +266 -0
- package/apps/web/public/theme.js +845 -0
- package/apps/web/public/themes/lantern/colors.toml +25 -0
- package/apps/web/public/themes/lantern/direction.css +60 -0
- package/apps/web/public/themes/lantern/frame.css +254 -0
- package/apps/web/public/themes/lantern/theme.css +10 -0
- package/apps/web/public/themes/lantern/theme.json +7 -0
- package/apps/web/public/themes/pocket/theme.css +189 -0
- package/apps/web/public/themes/pocket/theme.json +6 -0
- package/apps/web/public/themes.js +556 -0
- package/apps/web/public/transcript.js +3348 -0
- package/apps/web/public/trust.js +295 -0
- package/apps/web/public/turns.js +507 -0
- package/apps/web/public/ui.js +1910 -0
- package/apps/web/public/voice.js +345 -0
- package/apps/web/server.mjs +774 -0
- package/package.json +43 -4
- package/packages/cli/src/bom-pi.mjs +452 -0
- package/packages/cli/templates/blank.factory.json +7 -0
- package/packages/cli/templates/dev.factory.json +11 -0
- package/packages/cli/templates/docs.factory.json +12 -0
- package/packages/cli/templates/ops.factory.json +14 -0
- package/packages/cli/templates/triage.factory.json +10 -0
- package/packages/core/src/daemon.mjs +2047 -0
- package/packages/core/src/limit-gate.mjs +192 -0
- package/packages/core/src/rpc-client.mjs +66 -0
- package/systemd/README.md +11 -0
|
@@ -0,0 +1,2047 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// bom-core daemon v0.4 — M1+M2+M3+M4a (blueprint docs/BLUEPRINT.md §4)
|
|
3
|
+
//
|
|
4
|
+
// Lý niệm herdr: "core draws nothing" — daemon headless sở hữu pi-durable Harness,
|
|
5
|
+
// clients (herdr plugin / cli / web) là process riêng nói chuyện qua unix socket.
|
|
6
|
+
//
|
|
7
|
+
// Giao thức v0.4: NDJSON JSON-RPC 2.0, nhiều request / 1 connection, notification 2 chiều:
|
|
8
|
+
// hello -> { name, version, protocol, node, piDurable, db, pid }
|
|
9
|
+
// status -> inspect() + usage() (scheduling / tasks / submissions)
|
|
10
|
+
// models.list -> model khả dụng từ ModelRuntime (credentials ~/.pi/agent/auth.json)
|
|
11
|
+
// session.list -> mọi conversation (scan) + active + model/cwd mỗi conversation
|
|
12
|
+
// session.new { model?, cwd?, instructions? } -> conversation mới, thành active
|
|
13
|
+
// session.switch { id } -> đổi conversation active của daemon
|
|
14
|
+
// session.configure { model?, cwd?, instructions? } (conversation active hoặc conversationId)
|
|
15
|
+
// session.submit { text, requestId?, model?, conversationId? }
|
|
16
|
+
// session.reset { handoff?, conversationId? } -> bối cảnh mới cùng conversation
|
|
17
|
+
// transcript.get { limit?, conversationId? } -> entries nhẹ
|
|
18
|
+
// events.subscribe { conversationId? } -> reply snapshot + seq; push events.update/heartbeat
|
|
19
|
+
// shutdown -> đóng storage đúng cách rồi exit 0
|
|
20
|
+
// Handler nhận (params, ctx) với ctx.push(method, params) = notification không-id.
|
|
21
|
+
//
|
|
22
|
+
// Vận hành: single-owner lock (dataDir/bom-core.lock); probe socket cũ; chmod 0600;
|
|
23
|
+
// onReport log mọi lỗi async; harness.closed → exit(1); resume() ngay sau open;
|
|
24
|
+
// kill giữa turn sẽ chạy lại (restartLimit 5). Tools: CodingTools (read/write/edit/bash).
|
|
25
|
+
|
|
26
|
+
import { connect, createServer } from 'node:net';
|
|
27
|
+
import { mkdir, readFile, readdir, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
28
|
+
import { chmodSync } from 'node:fs';
|
|
29
|
+
import { dirname, join, relative, resolve, sep } from 'node:path';
|
|
30
|
+
import { homedir, userInfo } from 'node:os';
|
|
31
|
+
import process from 'node:process';
|
|
32
|
+
import { execFile as execFileCb } from 'node:child_process';
|
|
33
|
+
import { promisify } from 'node:util';
|
|
34
|
+
import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes } from 'node:crypto';
|
|
35
|
+
import { createLimitGate } from './limit-gate.mjs';
|
|
36
|
+
|
|
37
|
+
const VERSION = '0.0.4';
|
|
38
|
+
const PROTOCOL = 1; // bump khi break client — additive-only giữa các bump
|
|
39
|
+
|
|
40
|
+
function arg(name, fallback) {
|
|
41
|
+
const i = process.argv.indexOf(`--${name}`);
|
|
42
|
+
return i >= 0 && process.argv[i + 1] ? process.argv[i + 1] : fallback;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const runtimeDir = process.env.XDG_RUNTIME_DIR || `/tmp/run-${userInfo().uid}`;
|
|
46
|
+
const socketPath = arg('socket', resolve(runtimeDir, 'bom-pi.sock'));
|
|
47
|
+
const dataDir = arg('data', resolve(homedir(), '.local/state/bom-pi'));
|
|
48
|
+
const defaultCwd = arg('cwd', homedir()); // thư mục làm việc mặc định của agent (đổi qua --cwd)
|
|
49
|
+
const dbPath = resolve(dataDir, 'pi.sqlite');
|
|
50
|
+
const lockPath = join(dataDir, 'bom-core.lock');
|
|
51
|
+
|
|
52
|
+
const log = (...a) => process.stderr.write(`[bom-core] ${new Date().toISOString()} ${a.join(' ')}\n`);
|
|
53
|
+
const execFileAsync = promisify(execFileCb); // M6a: daemon-side git cho change-set (propose/merge)
|
|
54
|
+
|
|
55
|
+
// ---- Trạng thái boot + shutdown (handler signal gắn TRƯỚC khi mở storage) ----
|
|
56
|
+
let models = null; // ModelRuntime (pi-coding-agent) — credentials pi thật
|
|
57
|
+
let harness = null;
|
|
58
|
+
let storage = null;
|
|
59
|
+
let server = null;
|
|
60
|
+
let listening = false;
|
|
61
|
+
let closing = false;
|
|
62
|
+
let signalWhileOpening = false;
|
|
63
|
+
let rootConv = null; // conversation root
|
|
64
|
+
let activeConvId = null; // conversation active (submit/transcript mặc định)
|
|
65
|
+
let eventsSeq = 0;
|
|
66
|
+
let heartbeatTimer = null;
|
|
67
|
+
const watches = new Map(); // ConversationId -> {handle, conns:Set<conn>}
|
|
68
|
+
const connConvs = new Map(); // conn -> Set<ConversationId>
|
|
69
|
+
|
|
70
|
+
async function shutdown(reason) {
|
|
71
|
+
if (closing) return;
|
|
72
|
+
closing = true;
|
|
73
|
+
log('đóng:', reason);
|
|
74
|
+
let failed = false;
|
|
75
|
+
if (heartbeatTimer) clearInterval(heartbeatTimer);
|
|
76
|
+
if (scheduleTimer) clearInterval(scheduleTimer);
|
|
77
|
+
for (const [, w] of watches) {
|
|
78
|
+
try { await w.handle.stop(); } catch {}
|
|
79
|
+
}
|
|
80
|
+
watches.clear();
|
|
81
|
+
connConvs.clear();
|
|
82
|
+
if (harness) {
|
|
83
|
+
try {
|
|
84
|
+
// Session.close(context): "Seal admission, settle admitted commits, then close storage"
|
|
85
|
+
// — tự đóng storage luôn, KHÔNG gọi storage.close() lần hai
|
|
86
|
+
await harness.close(BACKGROUND_CONTEXT);
|
|
87
|
+
} catch (e) {
|
|
88
|
+
failed = true;
|
|
89
|
+
log('lỗi khi đóng:', e?.message ?? e);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (listening) await rm(socketPath, { force: true });
|
|
93
|
+
await rm(lockPath, { force: true });
|
|
94
|
+
process.exit(failed ? 1 : 0);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
process.on('SIGTERM', () => (harness ? shutdown('SIGTERM') : ((signalWhileOpening = true), log('SIGTERM khi đang mở — sẽ đóng ngay khi mở xong'))));
|
|
98
|
+
process.on('SIGINT', () => (harness ? shutdown('SIGINT') : ((signalWhileOpening = true), log('SIGINT khi đang mở — sẽ đóng ngay khi mở xong'))));
|
|
99
|
+
process.on('unhandledRejection', (e) => log('unhandledRejection:', e?.message ?? e));
|
|
100
|
+
process.on('uncaughtException', (e) => {
|
|
101
|
+
log('uncaughtException:', e?.stack ?? e);
|
|
102
|
+
shutdown('uncaughtException').finally(() => process.exit(1));
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
// ---- Single-owner lock: một-process-một-storage (WAL không tự ép — khuôn pi-pocket harness.lock) ----
|
|
106
|
+
function pidAlive(pid) {
|
|
107
|
+
try {
|
|
108
|
+
process.kill(pid, 0); // ESRCH nếu chết; EPERM = tồn tại (khác user) → coi như sống
|
|
109
|
+
return true;
|
|
110
|
+
} catch {
|
|
111
|
+
return false;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async function acquireLock() {
|
|
116
|
+
const write = () => writeFile(lockPath, JSON.stringify({ pid: process.pid, startedAt: Date.now() }) + '\n');
|
|
117
|
+
try {
|
|
118
|
+
await write(); // tạo mới
|
|
119
|
+
return true;
|
|
120
|
+
} catch (e) {
|
|
121
|
+
if (e?.code !== 'EEXIST') throw e;
|
|
122
|
+
let owner = null;
|
|
123
|
+
try {
|
|
124
|
+
owner = JSON.parse(await readFile(lockPath, 'utf8'));
|
|
125
|
+
} catch {}
|
|
126
|
+
if (owner?.pid && pidAlive(owner.pid)) {
|
|
127
|
+
log(`từ chối khởi động: bom-core khác đang sống (pid ${owner.pid}) giữ ${lockPath}`);
|
|
128
|
+
return false;
|
|
129
|
+
}
|
|
130
|
+
log(`dọn lock rỗng/chết (pid ${owner?.pid ?? '?'}):`, lockPath);
|
|
131
|
+
await rm(lockPath, { force: true });
|
|
132
|
+
await write();
|
|
133
|
+
return true;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// Probe socket cũ trước khi cướp đường dẫn: có daemon sống trả lời thì dừng.
|
|
138
|
+
function probeSocket(path) {
|
|
139
|
+
return new Promise((done) => {
|
|
140
|
+
const c = connect(path);
|
|
141
|
+
const finish = (alive, hello) => { try { c.destroy(); } catch {} done({ alive, hello }); };
|
|
142
|
+
const timer = setTimeout(() => finish(false), 1000);
|
|
143
|
+
c.on('connect', () => c.write(JSON.stringify({ jsonrpc: '2.0', id: 0, method: 'hello' }) + '\n'));
|
|
144
|
+
c.on('data', (chunk) => {
|
|
145
|
+
clearTimeout(timer);
|
|
146
|
+
try { finish(true, JSON.parse(chunk.toString('utf8').split('\n')[0])); } catch { finish(true); }
|
|
147
|
+
});
|
|
148
|
+
c.on('error', () => { clearTimeout(timer); finish(false); });
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// ---- Approvals (tự chế — pi-durable 1.4.0 không có builtin; khuôn pi-pocket host.ts Approvals) ----
|
|
153
|
+
// Wrap tool 'bash': trước khi chạy, tạo request chờ operator (cli/web/plugin) trả lời.
|
|
154
|
+
// Pending nằm trong RAM: daemon restart giữa lúc chờ ⇒ promise chết, durable task
|
|
155
|
+
// tự xử theo replay-policy của bash — ghi DECISIONS D-approval.
|
|
156
|
+
const APPROVALS_ON = process.env.BOM_APPROVALS !== 'off';
|
|
157
|
+
const pendingApprovals = new Map(); // id -> {request, resolve}
|
|
158
|
+
const approvalConns = new Set(); // conn đã approvals.subscribe
|
|
159
|
+
|
|
160
|
+
function approvalList() {
|
|
161
|
+
return [...pendingApprovals.values()].map((p) => p.request);
|
|
162
|
+
}
|
|
163
|
+
function pushApprovals() {
|
|
164
|
+
if (!approvalConns.size) return;
|
|
165
|
+
const payload = JSON.stringify({ jsonrpc: '2.0', method: 'approvals.update', params: { pending: approvalList() } }) + '\n';
|
|
166
|
+
for (const c of approvalConns) c.write(payload);
|
|
167
|
+
}
|
|
168
|
+
function requestApproval({ id, conversationId, taskId, tool, command, extra }) {
|
|
169
|
+
const old = pendingApprovals.get(id);
|
|
170
|
+
if (old) old.resolve({ allow: false, reason: 'superseded' }); // id trùng ⇒ bản cũ tự hủy
|
|
171
|
+
const request = { id, conversationId, taskId, tool, type: extra?.type ?? 'tool', command: String(command).slice(0, 300), ...(extra ?? {}), at: Date.now() };
|
|
172
|
+
const answered = new Promise((resolve) => pendingApprovals.set(id, { request, resolve }));
|
|
173
|
+
log('approval chờ:', id, '—', String(command).slice(0, 80));
|
|
174
|
+
pushApprovals();
|
|
175
|
+
return answered.finally(() => {
|
|
176
|
+
if (pendingApprovals.get(id)?.request === request) {
|
|
177
|
+
pendingApprovals.delete(id);
|
|
178
|
+
pushApprovals();
|
|
179
|
+
}
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// Trust ladder (D-trust-ladder): L0 = phê MỌI tool ghi/chạy (bash+write+edit) — mặc định;
|
|
184
|
+
// L1/L2 = chỉ bash (ghi file tự do — merge/propose vẫn là cổng riêng ở M6a). Orphan ⇒ L0.
|
|
185
|
+
// Autonomy đọc từ factory.json của conversation đang gọi (một kênh dữ liệu như configure).
|
|
186
|
+
async function autonomyOfConversation(cid) {
|
|
187
|
+
const f = deriveFactory(cid);
|
|
188
|
+
if (!f) return 'L0';
|
|
189
|
+
try { return (await readFactoryConfig(f.dir)).autonomy; } catch { return 'L0'; }
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function buildApprovalsExtension(wrappedTools) {
|
|
193
|
+
// wrapTool nhận ĐỐI TƯỢNG tool (lấy .name từ nó) — truyền chuỗi thì wrap nhắm
|
|
194
|
+
// tên undefined và KHÔNG bao giờ khớp (đã probe: resolved execute vẫn bản gốc).
|
|
195
|
+
// M6a: wrap MỌI tool ghi/chạy (bash+write+edit) — mức phê theo autonomy (trust ladder).
|
|
196
|
+
return defineExtension({
|
|
197
|
+
name: 'bom.approvals',
|
|
198
|
+
wraps: wrappedTools.map((original) => wrapTool(original, (tool) => ({
|
|
199
|
+
...tool,
|
|
200
|
+
description: `${tool.description}\nEvery call needs operator approval before it runs.`,
|
|
201
|
+
async execute(args, api, context) {
|
|
202
|
+
const id = `${api.taskId}:${api.callId}`;
|
|
203
|
+
// L1+: write/edit chạy thẳng (chỉ bash cần phê); L0 phê tất cả
|
|
204
|
+
if (tool.name !== 'bash' && await autonomyOfConversation(api.conversationId) !== 'L0') {
|
|
205
|
+
return tool.execute(args, api, context);
|
|
206
|
+
}
|
|
207
|
+
const preview = tool.name === 'bash'
|
|
208
|
+
? args?.command
|
|
209
|
+
: `${tool.name} ${args?.path ?? args?.file_path ?? ''} ${String(args?.content ?? '').slice(0, 120)}`;
|
|
210
|
+
const answer = await requestApproval({
|
|
211
|
+
id,
|
|
212
|
+
conversationId: api.conversationId,
|
|
213
|
+
taskId: api.taskId,
|
|
214
|
+
tool: tool.name,
|
|
215
|
+
command: preview,
|
|
216
|
+
});
|
|
217
|
+
if (!answer?.allow) {
|
|
218
|
+
return {
|
|
219
|
+
// content array — chuỗi thuần bị pi-durable bỏ (model sẽ thấy "unavailable")
|
|
220
|
+
output: [{ type: 'text', text: `DENIED by operator${answer?.reason ? ` (${answer.reason})` : ''}: ${String(preview).slice(0, 200)}` }],
|
|
221
|
+
isError: true,
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
return tool.execute(args, api, context);
|
|
225
|
+
},
|
|
226
|
+
}))),
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// ---- Schedules (cron nộp việc — file dataDir/schedules.json + timer 30s, catch-up sau restart) ----
|
|
231
|
+
// KHÔNG dùng durable sleepUntil-task (việc của M4 sau nếu cần) — chọn pragmatic: lịch nằm file,
|
|
232
|
+
// daemon tick 30s, due ⇒ submit prompt vào conversation; boot lại tính lại dueMs từ lastRun.
|
|
233
|
+
const schedulesPath = join(dataDir, 'schedules.json');
|
|
234
|
+
let schedules = [];
|
|
235
|
+
let scheduleTimer = null;
|
|
236
|
+
|
|
237
|
+
async function loadSchedules() {
|
|
238
|
+
try { schedules = JSON.parse(await readFile(schedulesPath, 'utf8')); } catch { schedules = []; }
|
|
239
|
+
}
|
|
240
|
+
async function saveSchedules() {
|
|
241
|
+
await writeFile(schedulesPath, JSON.stringify(schedules, null, 2) + '\n');
|
|
242
|
+
}
|
|
243
|
+
async function tickSchedules() {
|
|
244
|
+
const now = Date.now();
|
|
245
|
+
let dirty = false;
|
|
246
|
+
for (const s of schedules) {
|
|
247
|
+
if (s.disabled) continue;
|
|
248
|
+
if (s.dueMs <= now) {
|
|
249
|
+
try {
|
|
250
|
+
// conversationId ghi chết trong schedule; null ⇒ conversation active LÚC CHẠY
|
|
251
|
+
const target = s.conversationId ?? activeConvId;
|
|
252
|
+
const conv = target === rootConv?.id ? rootConv : await harness.conversation(target, BACKGROUND_CONTEXT);
|
|
253
|
+
if (conv) {
|
|
254
|
+
await conv.submit({ type: 'input', content: `[schedule ${s.id}] ${s.prompt}`, requestId: `sched-${s.id}-${s.dueMs}` }, BACKGROUND_CONTEXT);
|
|
255
|
+
log('schedule chạy:', s.id, '— vào conv', conv.id);
|
|
256
|
+
}
|
|
257
|
+
} catch (e) {
|
|
258
|
+
log('schedule lỗi:', s.id, e?.message ?? e);
|
|
259
|
+
}
|
|
260
|
+
s.lastRunMs = now;
|
|
261
|
+
s.dueMs = now + s.everySec * 1000;
|
|
262
|
+
dirty = true;
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
if (dirty) await saveSchedules();
|
|
266
|
+
}
|
|
267
|
+
function startSchedules() {
|
|
268
|
+
if (scheduleTimer) return;
|
|
269
|
+
scheduleTimer = setInterval(() => { tickSchedules().catch((e) => log('tick lỗi:', e?.message ?? e)); }, 30_000);
|
|
270
|
+
scheduleTimer.unref?.();
|
|
271
|
+
tickSchedules().catch(() => {});
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// ---- Factories (M5a — spec TSF docs/superpowers/specs/2026-11-02 §2) — đặt TRƯỚC boot (quy tắc TDZ) ----
|
|
275
|
+
// Registry nằm dataDir/factories.json (MỘT nơi state với schedules/lock — khác chữ spec §2.1
|
|
276
|
+
// "~/.local/state" nhưng cùng ý, tránh 2 thư mục state; ghi tmp+rename vì K6: file hỏng mất
|
|
277
|
+
// TOÀN BỘ registry, mount lại từng dir để hồi).
|
|
278
|
+
const factoriesPath = join(dataDir, 'factories.json');
|
|
279
|
+
let factories = [];
|
|
280
|
+
let factoryCounter = 0;
|
|
281
|
+
|
|
282
|
+
async function loadFactories() {
|
|
283
|
+
try {
|
|
284
|
+
factories = JSON.parse(await readFile(factoriesPath, 'utf8'));
|
|
285
|
+
if (!Array.isArray(factories)) throw new Error('không phải mảng');
|
|
286
|
+
} catch (e) {
|
|
287
|
+
factories = [];
|
|
288
|
+
if (e?.code !== 'ENOENT') log('factories.json hỏng — bỏ qua TOÀN BỘ registry (K6), mount lại từng dir:', e?.message ?? e);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
async function saveFactories() {
|
|
292
|
+
const tmp = factoriesPath + '.tmp';
|
|
293
|
+
await writeFile(tmp, JSON.stringify(factories, null, 2) + '\n');
|
|
294
|
+
await rename(tmp, factoriesPath);
|
|
295
|
+
}
|
|
296
|
+
const factoryByDir = (dir) => factories.find((f) => f.dir === dir) ?? null;
|
|
297
|
+
const factoryById = (id) => factories.find((f) => f.id === id) ?? null;
|
|
298
|
+
|
|
299
|
+
function parseModelRef(m) {
|
|
300
|
+
const { provider, modelId } = m ?? {};
|
|
301
|
+
if (!provider || !modelId) throw new Error('model cần {provider, modelId} — xem models.list');
|
|
302
|
+
if (!models.getModel?.(provider, modelId)) throw new Error(`không biết model ${provider}/${modelId} — xem models.list`);
|
|
303
|
+
return { provider, modelId };
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
// Tạo conversation KHÔNG đụng activeConvId — đường internal chung cho session.new (RPC) và
|
|
307
|
+
// factory.mount (spec §4: parity gọi đúng hàm internal; active là glue tầng RPC-face).
|
|
308
|
+
async function createConversationInternal(agent) {
|
|
309
|
+
return harness.createConversation(
|
|
310
|
+
{ ownership: { kind: 'ownerless' }, ...(Object.keys(agent).length ? { agent } : {}) },
|
|
311
|
+
BACKGROUND_CONTEXT,
|
|
312
|
+
);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// Đọc + validate factory.json (spec §2.2): name bắt buộc; schedules[] name-unique + everySec≥10,
|
|
316
|
+
// cap 10 (spec §4); watch chỉ validate hình dạng ở M5a (kích hoạt là M5d), cap 10.
|
|
317
|
+
async function readFactoryConfig(dir) {
|
|
318
|
+
let cfg;
|
|
319
|
+
try {
|
|
320
|
+
cfg = JSON.parse(await readFile(join(dir, 'factory.json'), 'utf8'));
|
|
321
|
+
} catch (e) {
|
|
322
|
+
throw new Error(`không đọc được ${join(dir, 'factory.json')}: ${e?.message ?? e} — xem bom-pi factory init`);
|
|
323
|
+
}
|
|
324
|
+
const name = typeof cfg?.name === 'string' && cfg.name.trim() ? cfg.name.trim() : null;
|
|
325
|
+
if (!name) throw new Error('factory.json thiếu "name"');
|
|
326
|
+
// pagesDir: relative, KHÔNG thoát dir factory (chặn pagesDir '../../' ⇒ traversal)
|
|
327
|
+
let pagesDir = 'pages';
|
|
328
|
+
if (typeof cfg?.pagesDir === 'string' && cfg.pagesDir.trim()) {
|
|
329
|
+
const pd = cfg.pagesDir.trim();
|
|
330
|
+
if (pd.startsWith('..') || pd.startsWith('/')) throw new Error(`factory ${name}: pagesDir phải relative trong dir ("${pd}")`);
|
|
331
|
+
pagesDir = pd;
|
|
332
|
+
}
|
|
333
|
+
let model = null;
|
|
334
|
+
if (cfg.model != null) model = parseModelRef(cfg.model);
|
|
335
|
+
const cwd = typeof cfg.cwd === 'string' && cfg.cwd.trim() ? resolve(dir, cfg.cwd.trim()) : dir;
|
|
336
|
+
const schedulesIn = Array.isArray(cfg.schedules) ? cfg.schedules : [];
|
|
337
|
+
if (schedulesIn.length > 10) throw new Error(`factory ${name}: ${schedulesIn.length} schedules > cap 10`);
|
|
338
|
+
const names = new Set();
|
|
339
|
+
for (const s of schedulesIn) {
|
|
340
|
+
if (!s || typeof s.name !== 'string' || !s.name.trim()) throw new Error(`factory ${name}: schedule thiếu name`);
|
|
341
|
+
if (names.has(s.name)) throw new Error(`factory ${name}: schedule name trùng "${s.name}" — name unique trong factory`);
|
|
342
|
+
names.add(s.name);
|
|
343
|
+
if (!Number.isFinite(Number(s.everySec)) || Number(s.everySec) < 10) throw new Error(`factory ${name}: schedule "${s.name}" everySec ≥ 10`);
|
|
344
|
+
if (typeof s.prompt !== 'string' || !s.prompt.trim()) throw new Error(`factory ${name}: schedule "${s.name}" thiếu prompt`);
|
|
345
|
+
}
|
|
346
|
+
const watchIn = Array.isArray(cfg.watch) ? cfg.watch : [];
|
|
347
|
+
if (watchIn.length > 10) throw new Error(`factory ${name}: ${watchIn.length} watch > cap 10`);
|
|
348
|
+
for (const w of watchIn) {
|
|
349
|
+
if (!w || typeof w.name !== 'string' || !w.name.trim() || typeof w.glob !== 'string' || !w.glob.trim() || typeof w.prompt !== 'string' || !w.prompt.trim()) {
|
|
350
|
+
throw new Error(`factory ${name}: watch cần {name, glob, prompt}`);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
// Trust ladder (M6a): L0 phê mọi tool ghi/chạy (mặc định) · L1/L2 chỉ phê bash — thăng cấp
|
|
354
|
+
// do người bấm khi số đo đủ, KHÔNG phải cấu hình agent tự ghi được là lên.
|
|
355
|
+
const AUTONOMY_LEVELS = ['L0', 'L1', 'L2'];
|
|
356
|
+
if (cfg.autonomy != null && !AUTONOMY_LEVELS.includes(cfg.autonomy)) {
|
|
357
|
+
throw new Error(`factory ${name}: autonomy phải một trong ${AUTONOMY_LEVELS.join('|')} (mặc định L0)`);
|
|
358
|
+
}
|
|
359
|
+
// M6b: chặng REVIEW — vắng field = TẮT reviewer (propose thẳng cổng người); có `review`
|
|
360
|
+
// (kể cả object rỗng) = BẬT; model reviewer = review.model ?? model factory.
|
|
361
|
+
let review = null;
|
|
362
|
+
if (cfg.review != null) {
|
|
363
|
+
if (typeof cfg.review !== 'object' || Array.isArray(cfg.review)) {
|
|
364
|
+
throw new Error(`factory ${name}: review phải là object {model?} — bỏ field để tắt reviewer`);
|
|
365
|
+
}
|
|
366
|
+
review = { ...(cfg.review.model ? { model: parseModelRef(cfg.review.model) } : {}) };
|
|
367
|
+
}
|
|
368
|
+
return {
|
|
369
|
+
name,
|
|
370
|
+
instructions: typeof cfg.instructions === 'string' && cfg.instructions.trim() ? cfg.instructions : null,
|
|
371
|
+
model,
|
|
372
|
+
cwd,
|
|
373
|
+
pagesDir,
|
|
374
|
+
autonomy: cfg.autonomy ?? 'L0',
|
|
375
|
+
review,
|
|
376
|
+
schedules: schedulesIn,
|
|
377
|
+
watch: watchIn,
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
const schedulesOfFactory = (convId) => schedules.filter((s) => s.conversationId === convId);
|
|
382
|
+
|
|
383
|
+
// Sync semantics (spec §2.5 chốt): upsert config-origin theo name; item config biến mất ⇒
|
|
384
|
+
// disabled; origin=agent KHÔNG bị đụng; đổi everySec ⇒ nhịp mới, giữ ⇒ giữ dueMs nhịp cũ.
|
|
385
|
+
async function syncFactorySchedules(f, cfgSchedules) {
|
|
386
|
+
const mine = schedulesOfFactory(f.conversationId);
|
|
387
|
+
const byName = new Map(mine.map((s) => [s.name ?? null, s]));
|
|
388
|
+
const cfgNames = new Set();
|
|
389
|
+
for (const c of cfgSchedules) {
|
|
390
|
+
cfgNames.add(c.name);
|
|
391
|
+
const everySec = Math.floor(Number(c.everySec));
|
|
392
|
+
const existing = byName.get(c.name);
|
|
393
|
+
if (existing) {
|
|
394
|
+
existing.prompt = c.prompt;
|
|
395
|
+
if (existing.everySec !== everySec) {
|
|
396
|
+
existing.everySec = everySec;
|
|
397
|
+
existing.dueMs = Date.now() + everySec * 1000;
|
|
398
|
+
}
|
|
399
|
+
} else {
|
|
400
|
+
schedules.push({
|
|
401
|
+
id: `sch-${Date.now().toString(36)}${(factoryCounter++).toString(36)}`,
|
|
402
|
+
name: c.name,
|
|
403
|
+
origin: 'config',
|
|
404
|
+
everySec,
|
|
405
|
+
prompt: c.prompt,
|
|
406
|
+
conversationId: f.conversationId,
|
|
407
|
+
disabled: f.status === 'stopped',
|
|
408
|
+
dueMs: Date.now() + everySec * 1000,
|
|
409
|
+
lastRunMs: null,
|
|
410
|
+
createdAtMs: Date.now(),
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
for (const s of mine) {
|
|
415
|
+
if (s.origin !== 'agent' && !cfgNames.has(s.name ?? null)) s.disabled = true;
|
|
416
|
+
}
|
|
417
|
+
await saveSchedules();
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
async function factorySnapshot(f, cfg) {
|
|
421
|
+
// pages: chỉ đếm .md trong pagesDir của config (nội dung pages là M5c1)
|
|
422
|
+
const pages = (await listPagesInternal(f.dir, cfg?.pagesDir ?? 'pages')).length;
|
|
423
|
+
const mine = schedulesOfFactory(f.conversationId);
|
|
424
|
+
return {
|
|
425
|
+
id: f.id,
|
|
426
|
+
name: cfg?.name ?? null,
|
|
427
|
+
dir: f.dir,
|
|
428
|
+
status: f.status,
|
|
429
|
+
conversationId: f.conversationId,
|
|
430
|
+
childConversations: f.childConversationIds.length,
|
|
431
|
+
autonomy: cfg?.autonomy ?? 'L0',
|
|
432
|
+
review: cfg?.review ? true : false,
|
|
433
|
+
schedules: { total: mine.length, enabled: mine.filter((s) => !s.disabled).length },
|
|
434
|
+
watches: watchesOf(f.conversationId).length,
|
|
435
|
+
pages,
|
|
436
|
+
createdAtMs: f.createdAtMs,
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
// mount == sync, idempotent theo dir (spec §2.5). Sync áp trường CÓ MẶT trong config — trường
|
|
441
|
+
// vắng giữ nguyên (factory_configure M5b sẽ ghi cả config nên luôn nhất quán).
|
|
442
|
+
async function mountFactory(params) {
|
|
443
|
+
const dirRaw = typeof params?.dir === 'string' ? params.dir.trim() : '';
|
|
444
|
+
if (!dirRaw) throw new Error('factory.mount cần {dir}');
|
|
445
|
+
const dir = resolve(dirRaw);
|
|
446
|
+
const cfg = await readFactoryConfig(dir);
|
|
447
|
+
let f = factoryByDir(dir);
|
|
448
|
+
if (!f) {
|
|
449
|
+
const conv = await createConversationInternal({
|
|
450
|
+
...(cfg.instructions ? { instructions: cfg.instructions } : {}),
|
|
451
|
+
...(cfg.model ? { model: cfg.model } : {}),
|
|
452
|
+
cwd: cfg.cwd,
|
|
453
|
+
});
|
|
454
|
+
f = {
|
|
455
|
+
id: `fac-${Date.now().toString(36)}${(factoryCounter++).toString(36)}`,
|
|
456
|
+
dir,
|
|
457
|
+
conversationId: conv.id,
|
|
458
|
+
childConversationIds: [],
|
|
459
|
+
status: 'mounted',
|
|
460
|
+
createdAtMs: Date.now(),
|
|
461
|
+
};
|
|
462
|
+
factories.push(f);
|
|
463
|
+
await saveFactories();
|
|
464
|
+
log('factory mount:', cfg.name, f.id, '— conv', conv.id);
|
|
465
|
+
} else if (f.status === 'mounted') {
|
|
466
|
+
const conv = await harness.conversation(f.conversationId, BACKGROUND_CONTEXT);
|
|
467
|
+
if (!conv) throw new Error(`conversation ${f.conversationId} của factory ${f.id} không còn — factory rm rồi mount lại`);
|
|
468
|
+
const change = {};
|
|
469
|
+
if (cfg.instructions) change.instructions = cfg.instructions;
|
|
470
|
+
if (cfg.model) change.model = cfg.model;
|
|
471
|
+
change.cwd = cfg.cwd;
|
|
472
|
+
await conv.configure(change, BACKGROUND_CONTEXT);
|
|
473
|
+
log('factory sync:', cfg.name, f.id);
|
|
474
|
+
}
|
|
475
|
+
if (f.status === 'mounted') await syncFactorySchedules(f, cfg.schedules);
|
|
476
|
+
else await saveFactories(); // stopped: sync chỉ đọc/ghi registry, KHÔNG enable lại (spec §2.5)
|
|
477
|
+
if (f.status === 'mounted') syncFactoryWatches(f, cfg.watch);
|
|
478
|
+
return { factory: await factorySnapshot(f, cfg) };
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// ---- Watch registry (M5b đăng ký; scan-timer là M5d — spec §5.1 chốt) — RAM ----
|
|
482
|
+
// id watch = <factoryId>/<name> hoặc conv-<cid>/<name> (orphan K7); boot + mount đăng lại
|
|
483
|
+
// watch config-origin; watch agent-added KHÔNG bền qua restart (K12).
|
|
484
|
+
const watchRegistry = new Map(); // key → {key, ownerKey, name, glob, debounceSec, prompt, conversationId, origin}
|
|
485
|
+
const watchesOf = (convId) => [...watchRegistry.values()].filter((w) => w.conversationId === convId);
|
|
486
|
+
function registerWatch({ ownerKey, name, glob, debounceSec, prompt, conversationId, origin }) {
|
|
487
|
+
const key = `${ownerKey}/${name}`;
|
|
488
|
+
watchRegistry.set(key, {
|
|
489
|
+
key, ownerKey, name,
|
|
490
|
+
glob: String(glob),
|
|
491
|
+
debounceSec: Number.isFinite(Number(debounceSec)) && Number(debounceSec) >= 1 ? Math.floor(Number(debounceSec)) : 30,
|
|
492
|
+
prompt: String(prompt),
|
|
493
|
+
conversationId,
|
|
494
|
+
origin,
|
|
495
|
+
createdAtMs: Date.now(),
|
|
496
|
+
});
|
|
497
|
+
return watchRegistry.get(key);
|
|
498
|
+
}
|
|
499
|
+
// sync watch của factory: xoá watch config-origin cũ, đăng lại từ config — agent-watch giữ (K12)
|
|
500
|
+
function syncFactoryWatches(f, cfgWatch) {
|
|
501
|
+
for (const [k, w] of watchRegistry) {
|
|
502
|
+
if (w.ownerKey === f.id && w.origin === 'config') watchRegistry.delete(k);
|
|
503
|
+
}
|
|
504
|
+
for (const w of cfgWatch ?? []) {
|
|
505
|
+
if (f.status === 'mounted') registerWatch({ ownerKey: f.id, name: w.name, glob: w.glob, debounceSec: w.debounceSec, prompt: w.prompt, conversationId: f.conversationId, origin: 'config' });
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
// boot + sau-mount: đăng lại watch config mọi factory mounted (spec §5.1 — filesystem là state)
|
|
509
|
+
async function loadConfigWatches() {
|
|
510
|
+
for (const f of factories) {
|
|
511
|
+
if (f.status !== 'mounted') continue;
|
|
512
|
+
try { syncFactoryWatches(f, (await readFactoryConfig(f.dir)).watch); } catch (e) { log('watch load lỗi:', f.id, e?.message ?? e); }
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
// ---- Triggers M5d (spec §5): polling scan 10s + glob matcher mini + debounce ----
|
|
517
|
+
// KHÔNG fs.watch (K2: trễ ≤40s, bỏ lỡ khi daemon chết — filesystem chính là state).
|
|
518
|
+
// glob: '**' đệ quy bất kỳ, '*' một tầng, phần còn lại literal (~15 dòng, không dependency).
|
|
519
|
+
function globToRegExp(glob) {
|
|
520
|
+
let re = '';
|
|
521
|
+
let i = 0;
|
|
522
|
+
const g = String(glob);
|
|
523
|
+
while (i < g.length) {
|
|
524
|
+
const c = g[i];
|
|
525
|
+
if (c === '*') {
|
|
526
|
+
if (g[i + 1] === '*') {
|
|
527
|
+
// '**/' ⇒ đệ quy (0+ tầng); '**' cuối ⇒ mọi thứ còn lại
|
|
528
|
+
if (g[i + 2] === '/') { re += '(?:[^/]+/)*'; i += 3; }
|
|
529
|
+
else { re += '.*'; i += 2; }
|
|
530
|
+
} else { re += '[^/]*'; i += 1; }
|
|
531
|
+
} else if ('\\^$.|?+()[]{}'.includes(c)) { re += '\\' + c; i += 1; }
|
|
532
|
+
else { re += c; i += 1; }
|
|
533
|
+
}
|
|
534
|
+
return new RegExp(`^${re}$`);
|
|
535
|
+
}
|
|
536
|
+
// walk dir bỏ .git/node_modules (K11: glob hẹp là trách nhiệm config)
|
|
537
|
+
async function walkFiles(root, rel = '', out = []) {
|
|
538
|
+
let entries;
|
|
539
|
+
try { entries = await readdir(join(root, rel || '.'), { withFileTypes: true }); } catch { return out; }
|
|
540
|
+
for (const e of entries) {
|
|
541
|
+
if (e.name === '.git' || e.name === 'node_modules') continue;
|
|
542
|
+
const r = rel ? `${rel}/${e.name}` : e.name;
|
|
543
|
+
if (e.isDirectory()) await walkFiles(root, r, out);
|
|
544
|
+
else if (e.isFile()) out.push(r);
|
|
545
|
+
}
|
|
546
|
+
return out;
|
|
547
|
+
}
|
|
548
|
+
const watchSnapshots = new Map(); // w.key → Map(rel → {size, mtimeMs})
|
|
549
|
+
const watchPending = new Map(); // w.key → {changes: [], dueMs, snapshot}
|
|
550
|
+
let watchTimer = null;
|
|
551
|
+
async function scanWatch(w) {
|
|
552
|
+
const f = factoryById(w.ownerKey); // watch của factory; orphan ownerKey conv-* ⇒ không scan
|
|
553
|
+
if (!f || f.status !== 'mounted') return;
|
|
554
|
+
const re = globToRegExp(w.glob);
|
|
555
|
+
const files = await walkFiles(f.dir);
|
|
556
|
+
const next = new Map();
|
|
557
|
+
for (const rel of files) {
|
|
558
|
+
if (!re.test(rel)) continue;
|
|
559
|
+
let st;
|
|
560
|
+
try { st = await stat(join(f.dir, rel)); } catch { continue; }
|
|
561
|
+
next.set(rel, { size: st.size, mtimeMs: st.mtimeMs });
|
|
562
|
+
}
|
|
563
|
+
const prev = watchSnapshots.get(w.key); // chưa có ⇒ scan nền, KHÔNG kích (tránh bùng lúc boot)
|
|
564
|
+
watchSnapshots.set(w.key, next);
|
|
565
|
+
if (!prev) return;
|
|
566
|
+
const changes = [];
|
|
567
|
+
for (const [rel, meta] of next) {
|
|
568
|
+
const old = prev.get(rel);
|
|
569
|
+
if (!old) changes.push(`+ ${rel}`);
|
|
570
|
+
else if (old.size !== meta.size || old.mtimeMs !== meta.mtimeMs) changes.push(`~ ${rel}`);
|
|
571
|
+
}
|
|
572
|
+
for (const rel of prev.keys()) if (!next.has(rel)) changes.push(`- ${rel}`);
|
|
573
|
+
if (!changes.length) return;
|
|
574
|
+
const p = watchPending.get(w.key);
|
|
575
|
+
if (p) p.changes.push(...changes.filter((c) => !p.changes.includes(c)));
|
|
576
|
+
else watchPending.set(w.key, { changes, dueMs: Date.now() + w.debounceSec * 1000 });
|
|
577
|
+
}
|
|
578
|
+
async function flushWatches() {
|
|
579
|
+
const now = Date.now();
|
|
580
|
+
for (const [key, p] of watchPending) {
|
|
581
|
+
if (p.dueMs > now) continue;
|
|
582
|
+
watchPending.delete(key);
|
|
583
|
+
const w = [...watchRegistry.values()].find((x) => x.key === key);
|
|
584
|
+
if (!w) continue;
|
|
585
|
+
const f = factoryById(w.ownerKey);
|
|
586
|
+
if (!f || f.status !== 'mounted') continue;
|
|
587
|
+
const roundMs = now;
|
|
588
|
+
try {
|
|
589
|
+
const conv = await harness.conversation(w.conversationId, BACKGROUND_CONTEXT);
|
|
590
|
+
await conv.submit({
|
|
591
|
+
type: 'input',
|
|
592
|
+
content: `[watch ${key}] ${w.prompt}\nChanges:\n${p.changes.slice(0, 30).join('\n')}`,
|
|
593
|
+
requestId: `watch-${key}-${roundMs}`,
|
|
594
|
+
}, BACKGROUND_CONTEXT);
|
|
595
|
+
log('watch kích:', key, `(${p.changes.length} thay đổi)`);
|
|
596
|
+
} catch (e) {
|
|
597
|
+
log('watch submit lỗi:', key, e?.message ?? e);
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
function startWatchScanner() {
|
|
602
|
+
if (watchTimer) return;
|
|
603
|
+
watchTimer = setInterval(() => {
|
|
604
|
+
(async () => {
|
|
605
|
+
for (const w of watchRegistry.values()) await scanWatch(w);
|
|
606
|
+
await flushWatches();
|
|
607
|
+
})().catch((e) => log('watch scan lỗi:', e?.message ?? e));
|
|
608
|
+
}, 10_000);
|
|
609
|
+
watchTimer.unref?.();
|
|
610
|
+
}
|
|
611
|
+
function clearWatchState(ownerKey) {
|
|
612
|
+
// stop/rm factory: huỷ snapshot + debounce đang chờ (spec §2.5 — watch ngừng kích)
|
|
613
|
+
for (const k of watchSnapshots.keys()) if (k.startsWith(`${ownerKey}/`)) watchSnapshots.delete(k);
|
|
614
|
+
for (const k of watchPending.keys()) if (k.startsWith(`${ownerKey}/`)) watchPending.delete(k);
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
// ---- Helpers dùng chung RPC ↔ parity (spec §4: parity gọi ĐÚNG hàm internal, không song song) ----
|
|
618
|
+
async function agentStateOf(id) {
|
|
619
|
+
try { return await harness.snapshot(AgentDoc, id, BACKGROUND_CONTEXT); } catch { return undefined; }
|
|
620
|
+
}
|
|
621
|
+
// factory của conversation gọi (gốc hoặc con); null = orphan (K7 — vẫn chạy, không thuộc xưởng)
|
|
622
|
+
function deriveFactory(cid) {
|
|
623
|
+
return factories.find((f) => f.conversationId === cid || f.childConversationIds.includes(cid)) ?? null;
|
|
624
|
+
}
|
|
625
|
+
// Internal thêm schedule — đường chung của RPC schedules.add (origin agent) và parity M5b
|
|
626
|
+
async function addScheduleInternal({ name, everySec, prompt, conversationId, origin }) {
|
|
627
|
+
const sec = Number(everySec);
|
|
628
|
+
if (!Number.isFinite(sec) || sec < 10) throw new Error('everySec ≥ 10 (giây)');
|
|
629
|
+
if (typeof prompt !== 'string' || !prompt.trim()) throw new Error('thiếu prompt');
|
|
630
|
+
const nm = typeof name === 'string' && name.trim() ? name.trim() : null;
|
|
631
|
+
const cid = Number.isInteger(conversationId) ? conversationId : null;
|
|
632
|
+
if (nm && schedules.some((s) => s.name === nm && s.conversationId === cid)) {
|
|
633
|
+
throw new Error(`schedule name "${nm}" đã có trong conversation — name unique (spec §2.4)`);
|
|
634
|
+
}
|
|
635
|
+
const s = {
|
|
636
|
+
id: `sch-${Date.now().toString(36)}${(factoryCounter++).toString(36)}`,
|
|
637
|
+
...(nm ? { name: nm } : {}),
|
|
638
|
+
origin,
|
|
639
|
+
everySec: Math.floor(sec),
|
|
640
|
+
prompt: prompt.trim(),
|
|
641
|
+
conversationId: cid,
|
|
642
|
+
disabled: false,
|
|
643
|
+
dueMs: Date.now() + sec * 1000,
|
|
644
|
+
lastRunMs: null,
|
|
645
|
+
createdAtMs: Date.now(),
|
|
646
|
+
};
|
|
647
|
+
schedules.push(s);
|
|
648
|
+
await saveSchedules();
|
|
649
|
+
return s;
|
|
650
|
+
}
|
|
651
|
+
// Internal xoá theo name trong conversation — parity factory_schedule_remove đi đường này
|
|
652
|
+
async function removeScheduleByName(cid, name) {
|
|
653
|
+
const s = schedules.find((x) => x.name === name && x.conversationId === cid);
|
|
654
|
+
if (!s) throw new Error(`không có schedule name "${name}" trong conversation ${cid}`);
|
|
655
|
+
schedules = schedules.filter((x) => x.id !== s.id);
|
|
656
|
+
await saveSchedules();
|
|
657
|
+
return s;
|
|
658
|
+
}
|
|
659
|
+
// Pages: liệt kê .md trong pagesDir + title = heading đầu (spec §3) — RPC pages.list và parity
|
|
660
|
+
// pages_list đi đường này. factory có pagesDir riêng (config), orphan mặc định 'pages'.
|
|
661
|
+
async function listPagesInternal(baseDir, pagesDir = 'pages') {
|
|
662
|
+
try {
|
|
663
|
+
const root = join(baseDir, pagesDir);
|
|
664
|
+
const entries = await readdir(root, { withFileTypes: true });
|
|
665
|
+
const out = [];
|
|
666
|
+
for (const e of entries) {
|
|
667
|
+
if (!e.isFile() || !e.name.endsWith('.md')) continue;
|
|
668
|
+
const p = join(root, e.name);
|
|
669
|
+
const st = await stat(p);
|
|
670
|
+
let title = null;
|
|
671
|
+
try {
|
|
672
|
+
const md = await readFile(p, 'utf8');
|
|
673
|
+
title = (md.match(/^#\s+(.+)$/m) ?? [null, null])[1];
|
|
674
|
+
} catch { /* đọc lỗi title — vẫn liệt kê */ }
|
|
675
|
+
out.push({ name: e.name, title, bytes: st.size, mtimeMs: st.mtimeMs });
|
|
676
|
+
}
|
|
677
|
+
return out.sort((a, b) => a.name.localeCompare(b.name));
|
|
678
|
+
} catch { return []; } // pagesDir chưa có — rỗng
|
|
679
|
+
}
|
|
680
|
+
// pagesDir chuẩn hoá của factory (từ config) — các đường RPC/parity cùng dùng
|
|
681
|
+
async function pagesDirOf(f) {
|
|
682
|
+
try { return (await readFactoryConfig(f.dir)).pagesDir; } catch { return 'pages'; }
|
|
683
|
+
}
|
|
684
|
+
// pages.get: validate name + realpath nằm TRONG pagesDir (spec §3 vá — chặn ../ và symlink)
|
|
685
|
+
async function getPageInternal(f, name) {
|
|
686
|
+
if (typeof name !== 'string' || !/^[A-Za-z0-9._-]+\.md$/.test(name)) {
|
|
687
|
+
throw new Error(`page name không hợp lệ (chữ/số/._- và hậu tố .md): ${String(name).slice(0, 60)}`);
|
|
688
|
+
}
|
|
689
|
+
const pagesDir = await pagesDirOf(f);
|
|
690
|
+
const root = join(f.dir, pagesDir);
|
|
691
|
+
const target = join(root, name);
|
|
692
|
+
let realRoot;
|
|
693
|
+
let realTarget;
|
|
694
|
+
try {
|
|
695
|
+
realRoot = await realpath(root);
|
|
696
|
+
realTarget = await realpath(target); // throw khi không tồn tại
|
|
697
|
+
} catch {
|
|
698
|
+
throw new Error(`không có page "${name}"`);
|
|
699
|
+
}
|
|
700
|
+
if (realTarget !== realRoot && !realTarget.startsWith(realRoot + '/')) {
|
|
701
|
+
throw new Error(`không có page "${name}"`); // symlink/../ thoát dir — trả not-found, không lộ đường dẫn
|
|
702
|
+
}
|
|
703
|
+
const content = await readFile(target, 'utf8');
|
|
704
|
+
return { name, content };
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
// ---- M6a: change-set merge gate (G2 — chặng REVIEW/SHIP) ----
|
|
708
|
+
// Agent branch+commit bằng bash (đã qua approval), rồi propose: đăng approval type 'merge'
|
|
709
|
+
// chờ người duyệt. Approve ⇒ daemon `git merge --no-ff` branch vào base (branch đang checkout);
|
|
710
|
+
// deny ⇒ không đụng repo. Merge là cổng người duyệt ở MỌI cấp autonomy (kể cả L2).
|
|
711
|
+
async function gitIn(dir, ...args) {
|
|
712
|
+
try {
|
|
713
|
+
const { stdout } = await execFileAsync('git', ['-C', dir, ...args], { timeout: 30_000, maxBuffer: 4 * 1024 * 1024 });
|
|
714
|
+
return stdout.toString().trim();
|
|
715
|
+
} catch (e) {
|
|
716
|
+
throw new Error(`git ${args[0]} trong ${dir}: ${e?.stderr?.toString().trim() || e?.message || e}`);
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
async function proposeInternal({ conversationId, branch, title, summary }) {
|
|
720
|
+
const f = deriveFactory(conversationId);
|
|
721
|
+
if (!f) throw new Error('propose chỉ chạy trong factory — orphan không có repo (K7)');
|
|
722
|
+
const cfg = await readFactoryConfig(f.dir);
|
|
723
|
+
const repo = cfg.cwd; // repo là nơi agent làm việc (cwd config, mặc định dir factory)
|
|
724
|
+
const branchS = String(branch ?? '').trim();
|
|
725
|
+
const titleS = String(title ?? '').trim();
|
|
726
|
+
if (!branchS || !titleS) throw new Error('propose cần {branch, title}');
|
|
727
|
+
// branch dạng an toàn, không cho '-' đứng đầu (chặn bị git parse là flag)
|
|
728
|
+
if (!/^(?!-)[A-Za-z0-9._/-]+$/.test(branchS)) throw new Error(`branch không hợp lệ: ${branchS.slice(0, 60)}`);
|
|
729
|
+
try {
|
|
730
|
+
await gitIn(repo, 'rev-parse', '--verify', branchS);
|
|
731
|
+
} catch {
|
|
732
|
+
throw new Error(`branch "${branchS}" không tồn tại trong repo ${repo} — tạo branch và commit trước khi propose`);
|
|
733
|
+
}
|
|
734
|
+
const base = await gitIn(repo, 'rev-parse', '--abbrev-ref', 'HEAD'); // đang checkout = nơi merge vào
|
|
735
|
+
if (base === branchS) throw new Error(`branch "${branchS}" đang là HEAD — propose branch khác để merge vào ${base}`);
|
|
736
|
+
const commits = (await gitIn(repo, 'log', '--oneline', `${base}..${branchS}`)).split('\n').filter(Boolean);
|
|
737
|
+
if (!commits.length) throw new Error(`branch "${branchS}" không có commit nào hơn ${base} — commit trước khi propose`);
|
|
738
|
+
// M6b: chặng REVIEW chạy TRƯỚC cổng người (reviewer chỉ góp ý — người vẫn quyết)
|
|
739
|
+
let review = null;
|
|
740
|
+
if (cfg.review) {
|
|
741
|
+
let diff = await gitIn(repo, 'diff', `${base}..${branchS}`);
|
|
742
|
+
if (diff.length > 20000) diff = `${diff.slice(0, 20000)}\n… (diff cắt từ ${diff.length} ký tự)`;
|
|
743
|
+
review = await runReviewerInternal(f, cfg, { branch: branchS, base, title: titleS, summary, commits, diff });
|
|
744
|
+
}
|
|
745
|
+
const answer = await requestApproval({
|
|
746
|
+
id: `merge:${f.id}:${branchS}`,
|
|
747
|
+
conversationId: f.conversationId,
|
|
748
|
+
taskId: null,
|
|
749
|
+
tool: 'merge',
|
|
750
|
+
command: `merge ${branchS} → ${base}: ${titleS}`,
|
|
751
|
+
extra: {
|
|
752
|
+
type: 'merge',
|
|
753
|
+
dir: repo,
|
|
754
|
+
branch: branchS,
|
|
755
|
+
base,
|
|
756
|
+
title: titleS,
|
|
757
|
+
...(summary ? { summary: String(summary).slice(0, 500) } : {}),
|
|
758
|
+
commits,
|
|
759
|
+
...(review ? { review: { verdict: review.verdict ?? review.status, page: review.page ?? null } } : {}),
|
|
760
|
+
},
|
|
761
|
+
});
|
|
762
|
+
if (!answer?.allow) {
|
|
763
|
+
await recordMetric({ kind: 'merge', factoryId: f.id, branch: branchS, merged: false, verdict: review?.verdict ?? null });
|
|
764
|
+
if (answer?.reason !== 'superseded') await maybeDemote(f); // deny merge = can thiệp; supersede không
|
|
765
|
+
return { merged: false, branch: branchS, base, reason: answer?.reason === 'superseded' ? 'superseded' : 'denied', ...(review ? { review } : {}) };
|
|
766
|
+
}
|
|
767
|
+
const before = await gitIn(repo, 'rev-parse', 'HEAD');
|
|
768
|
+
await gitIn(repo, 'merge', '--no-ff', '-m', `bom merge: ${titleS}`, branchS); // conflict ⇒ throw, model thấy lỗi
|
|
769
|
+
const after = await gitIn(repo, 'rev-parse', 'HEAD');
|
|
770
|
+
await recordMetric({ kind: 'merge', factoryId: f.id, branch: branchS, merged: true, verdict: review?.verdict ?? null });
|
|
771
|
+
log('merge gate:', branchS, '→', base, `(${commits.length} commits)`);
|
|
772
|
+
return { merged: true, branch: branchS, base, title: titleS, commits, before, after, ...(review ? { review } : {}) };
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
// ---- M6b: reviewer agent phê diff vào page (chặng REVIEW của line INPUT→…→REVIEW→SHIP) ----
|
|
776
|
+
// Reviewer = conversation con của factory (agents.list thấy trong cây), KHÔNG dùng tool
|
|
777
|
+
// (instructions cấm — gọi tool sẽ rơi vào approval L0 chờ người ⇒ hết timeout, hướng xuống
|
|
778
|
+
// an toàn). Daemon đợi turn reviewer (poll transcript), parse verdict, GHI PAGE
|
|
779
|
+
// review-<branch>.md bằng writeFile daemon-side (artifact như schedules.json — không qua
|
|
780
|
+
// tool approval). Verdict KHÔNG chặn merge: người đọc page rồi quyết.
|
|
781
|
+
const REVIEW_TIMEOUT_MS = Number(process.env.BOM_REVIEW_TIMEOUT_MS) > 0 ? Number(process.env.BOM_REVIEW_TIMEOUT_MS) : 150_000;
|
|
782
|
+
const sanitizePageToken = (s) => String(s).replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 60) || 'branch';
|
|
783
|
+
|
|
784
|
+
async function waitAssistantText(cid, timeoutMs) {
|
|
785
|
+
const t0 = Date.now();
|
|
786
|
+
while (Date.now() - t0 < timeoutMs) {
|
|
787
|
+
await new Promise((r) => setTimeout(r, 2000));
|
|
788
|
+
try {
|
|
789
|
+
const conv = await harness.conversation(cid, BACKGROUND_CONTEXT);
|
|
790
|
+
const view = await conv.context(BACKGROUND_CONTEXT);
|
|
791
|
+
const asst = lightEntries(view.entries).filter((e) => e.kind === 'pi.assistant' && (e.text ?? '').trim());
|
|
792
|
+
if (asst.length) return asst[asst.length - 1].text;
|
|
793
|
+
} catch { /* conversation chưa sẵn sàng — thử lại */ }
|
|
794
|
+
}
|
|
795
|
+
return null;
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
async function runReviewerInternal(f, cfg, cs) {
|
|
799
|
+
const model = cfg.review?.model ?? cfg.model ?? null;
|
|
800
|
+
if (!model) return { status: 'no-model', verdict: null, page: null };
|
|
801
|
+
const reviewer = await createConversationInternal({
|
|
802
|
+
instructions: 'You are a code reviewer inside a software factory. You review change-sets (branch diffs before merge). Be concise and concrete: what changed, risks, missing tests. You must NOT use any tools — reply with your review as text only. Always end your reply with a final line exactly "VERDICT: approve" or "VERDICT: request_changes".',
|
|
803
|
+
model,
|
|
804
|
+
});
|
|
805
|
+
f.childConversationIds.push(reviewer.id);
|
|
806
|
+
if (f.childConversationIds.length > 20) f.childConversationIds.shift();
|
|
807
|
+
await saveFactories();
|
|
808
|
+
const prompt = [
|
|
809
|
+
'Review this change-set proposed for merge.',
|
|
810
|
+
`Title: ${cs.title}`,
|
|
811
|
+
...(cs.summary ? [`Summary: ${cs.summary}`] : []),
|
|
812
|
+
`Branch ${cs.branch} → base ${cs.base}`,
|
|
813
|
+
'Commits:',
|
|
814
|
+
...cs.commits.map((c) => `- ${c}`),
|
|
815
|
+
'',
|
|
816
|
+
'Diff:',
|
|
817
|
+
'```diff',
|
|
818
|
+
cs.diff,
|
|
819
|
+
'```',
|
|
820
|
+
'',
|
|
821
|
+
'Write your review now (text only, no tools). Last line: VERDICT: approve | VERDICT: request_changes.',
|
|
822
|
+
].join('\n');
|
|
823
|
+
await reviewer.submit({ type: 'input', content: prompt, requestId: `review-${f.id}-${sanitizePageToken(cs.branch)}-${Date.now()}` }, BACKGROUND_CONTEXT);
|
|
824
|
+
const text = await waitAssistantText(reviewer.id, REVIEW_TIMEOUT_MS);
|
|
825
|
+
const verdict = text ? (/VERDICT:\s*(approve|request_changes)/i.exec(text)?.[1]?.toLowerCase() ?? null) : null;
|
|
826
|
+
const verdictLabel = verdict ?? (text ? 'unclear' : 'timeout');
|
|
827
|
+
const page = `review-${sanitizePageToken(cs.branch)}.md`;
|
|
828
|
+
const pagesDirAbs = join(f.dir, cfg.pagesDir);
|
|
829
|
+
await mkdir(pagesDirAbs, { recursive: true });
|
|
830
|
+
const body = [
|
|
831
|
+
`# Review: ${cs.title}`,
|
|
832
|
+
'',
|
|
833
|
+
`- branch: \`${cs.branch}\` → \`${cs.base}\``,
|
|
834
|
+
`- commits: ${cs.commits.length}`,
|
|
835
|
+
`- verdict: **${verdictLabel}**`,
|
|
836
|
+
`- reviewer: ${model.provider}/${model.modelId} · conv ${reviewer.id} · ${new Date().toISOString()}`,
|
|
837
|
+
...(cs.summary ? [`- summary: ${cs.summary}`] : []),
|
|
838
|
+
'',
|
|
839
|
+
'## Commits',
|
|
840
|
+
...cs.commits.map((c) => `- ${c}`),
|
|
841
|
+
'',
|
|
842
|
+
'## Diff',
|
|
843
|
+
'```diff',
|
|
844
|
+
cs.diff,
|
|
845
|
+
'```',
|
|
846
|
+
'',
|
|
847
|
+
'## Reviewer notes',
|
|
848
|
+
'',
|
|
849
|
+
(text ?? '(reviewer không trả lời trong thời gian chờ — xem transcript conv ' + reviewer.id + ')'),
|
|
850
|
+
'',
|
|
851
|
+
].join('\n');
|
|
852
|
+
await writeFile(join(pagesDirAbs, page), body);
|
|
853
|
+
log('review gate:', cs.branch, '— verdict', verdictLabel);
|
|
854
|
+
return { status: 'done', verdict, verdictLabel, page, conversationId: reviewer.id };
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
// ---- M6c: metrics ledger — số đo cho trust ladder (D-trust-ladder: thăng do người bấm khi
|
|
858
|
+
// số đo đủ, hạ TỰ ĐỘNG khi can thiệp tăng). Kinds: approval {tool, allow} · merge {branch,
|
|
859
|
+
// merged, verdict} · abort · stop · demote {from, to}. File dataDir/metrics.json tmp+rename
|
|
860
|
+
// (K6 khuôn factories.json), cap 2000 dòng trượt. Can thiệp = tool-deny + merge-deny +
|
|
861
|
+
// abort + stop — mọi lần người phải TAY.
|
|
862
|
+
const metricsPath = join(dataDir, 'metrics.json');
|
|
863
|
+
let metricsEvents = [];
|
|
864
|
+
const METRICS_CAP = 2000;
|
|
865
|
+
const DEMOTE_THRESHOLD = 3; // can thiệp/24h để hạ 1 cấp
|
|
866
|
+
const DEMOTE_COOLDOWN_MS = 12 * 3600_000;
|
|
867
|
+
|
|
868
|
+
async function loadMetrics() {
|
|
869
|
+
try { metricsEvents = JSON.parse(await readFile(metricsPath, 'utf8')); } catch { metricsEvents = []; }
|
|
870
|
+
}
|
|
871
|
+
async function recordMetric(ev) {
|
|
872
|
+
metricsEvents.push({ at: Date.now(), ...ev });
|
|
873
|
+
if (metricsEvents.length > METRICS_CAP) metricsEvents = metricsEvents.slice(-METRICS_CAP);
|
|
874
|
+
const tmp = metricsPath + '.tmp';
|
|
875
|
+
await writeFile(tmp, JSON.stringify(metricsEvents) + '\n');
|
|
876
|
+
await rename(tmp, metricsPath);
|
|
877
|
+
}
|
|
878
|
+
const interventionsSince = (factoryId, since) => metricsEvents.filter((e) =>
|
|
879
|
+
e.factoryId === factoryId && e.at >= since
|
|
880
|
+
&& ((e.kind === 'approval' && e.allow === false) || (e.kind === 'merge' && e.merged === false) || e.kind === 'abort' || e.kind === 'stop')).length;
|
|
881
|
+
|
|
882
|
+
// Hạ cấp tự động: ≥DEMOTE_THRESHOLD can thiệp trong 24h ⇒ hạ 1 cấp (floor L0), cooldown
|
|
883
|
+
// 12h giữa 2 lần (không cắm thang xuống L0 vì 1 vụ ồn). Ghi factory.json (một kênh dữ liệu)
|
|
884
|
+
// — người xem config thấy ngay autonomy đã đổi.
|
|
885
|
+
async function maybeDemote(f) {
|
|
886
|
+
let lvl;
|
|
887
|
+
try { lvl = (await readFactoryConfig(f.dir)).autonomy; } catch { return null; }
|
|
888
|
+
if (lvl === 'L0') return null;
|
|
889
|
+
const dayAgo = Date.now() - 24 * 3600_000;
|
|
890
|
+
const hits = interventionsSince(f.id, dayAgo);
|
|
891
|
+
const lastDemote = metricsEvents.filter((e) => e.kind === 'demote' && e.factoryId === f.id).at(-1)?.at ?? 0;
|
|
892
|
+
if (hits < DEMOTE_THRESHOLD || Date.now() - lastDemote < DEMOTE_COOLDOWN_MS) return null;
|
|
893
|
+
const next = lvl === 'L2' ? 'L1' : 'L0';
|
|
894
|
+
try {
|
|
895
|
+
const cfgPath = join(f.dir, 'factory.json');
|
|
896
|
+
const raw = JSON.parse(await readFile(cfgPath, 'utf8'));
|
|
897
|
+
raw.autonomy = next;
|
|
898
|
+
await writeFile(cfgPath, JSON.stringify(raw, null, 2) + '\n');
|
|
899
|
+
} catch (e) {
|
|
900
|
+
log('demote: không ghi được factory.json', f.id, e?.message ?? e);
|
|
901
|
+
return null;
|
|
902
|
+
}
|
|
903
|
+
await recordMetric({ kind: 'demote', factoryId: f.id, from: lvl, to: next, interventions: hits });
|
|
904
|
+
log(`trust ladder TỰ HẠ ${f.id}: ${lvl} → ${next} (${hits} can thiệp/24h)`);
|
|
905
|
+
return { from: lvl, to: next };
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
// Tóm tắt số đo cho dashboard (RPC metrics.summary) — window 24h + 7d, per-factory 7d,
|
|
909
|
+
// usage() daemon-wide (chi phí). G2 mục tiêu đo được: "≥3 merge/tuần duyệt từ phone".
|
|
910
|
+
async function metricsSummaryInternal() {
|
|
911
|
+
const now = Date.now();
|
|
912
|
+
const summarize = (since) => {
|
|
913
|
+
const evs = metricsEvents.filter((e) => e.at >= since);
|
|
914
|
+
const ap = evs.filter((e) => e.kind === 'approval');
|
|
915
|
+
const mg = evs.filter((e) => e.kind === 'merge');
|
|
916
|
+
const denied = ap.filter((a) => a.allow === false).length;
|
|
917
|
+
return {
|
|
918
|
+
approvals: { total: ap.length, allowed: ap.length - denied, denied, denyRate: ap.length ? Math.round((denied / ap.length) * 100) / 100 : 0 },
|
|
919
|
+
merges: {
|
|
920
|
+
proposed: mg.length,
|
|
921
|
+
merged: mg.filter((m) => m.merged).length,
|
|
922
|
+
denied: mg.filter((m) => !m.merged).length,
|
|
923
|
+
reviewApprove: mg.filter((m) => m.verdict === 'approve').length,
|
|
924
|
+
reviewRequestChanges: mg.filter((m) => m.verdict === 'request_changes').length,
|
|
925
|
+
mergesPerWeekTarget: 3, // G2 định nghĩa đo được (BLUEPRINT)
|
|
926
|
+
},
|
|
927
|
+
interventions: {
|
|
928
|
+
total: evs.filter((e) => (e.kind === 'approval' && e.allow === false) || (e.kind === 'merge' && e.merged === false) || e.kind === 'abort' || e.kind === 'stop').length,
|
|
929
|
+
aborts: evs.filter((e) => e.kind === 'abort').length,
|
|
930
|
+
stops: evs.filter((e) => e.kind === 'stop').length,
|
|
931
|
+
demotions: evs.filter((e) => e.kind === 'demote').length,
|
|
932
|
+
},
|
|
933
|
+
};
|
|
934
|
+
};
|
|
935
|
+
const factories7d = [];
|
|
936
|
+
for (const f of factories) {
|
|
937
|
+
let name = null;
|
|
938
|
+
let autonomy = 'L0';
|
|
939
|
+
try { const cfg = await readFactoryConfig(f.dir); name = cfg.name; autonomy = cfg.autonomy; } catch { /* config hỏng */ }
|
|
940
|
+
const dayAgo = now - 24 * 3600_000;
|
|
941
|
+
factories7d.push({
|
|
942
|
+
id: f.id, name, autonomy,
|
|
943
|
+
interventions24h: interventionsSince(f.id, dayAgo),
|
|
944
|
+
interventions7d: interventionsSince(f.id, now - 7 * 24 * 3600_000),
|
|
945
|
+
merges7d: metricsEvents.filter((e) => e.kind === 'merge' && e.factoryId === f.id && e.merged && e.at >= now - 7 * 24 * 3600_000).length,
|
|
946
|
+
});
|
|
947
|
+
}
|
|
948
|
+
const usage = await harness.usage(BACKGROUND_CONTEXT);
|
|
949
|
+
return { generatedAtMs: now, window24h: summarize(now - 24 * 3600_000), window7d: summarize(now - 7 * 24 * 3600_000), factories: factories7d, usage };
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
// ---- Pairing (M8): ghép thiết bị (phone/laptop) bằng CODE NGẮN thay copy token ----
|
|
953
|
+
// Khuôn durable-pi spec 03-pairing, cắt theo quy mô bom-pi (1 máy, LAN, không hub public):
|
|
954
|
+
// giữ — code 8 ký tự base32 TTL 5' single-use RAM-không-log · device token bom_<43>
|
|
955
|
+
// hash-at-rest (sha256), plaintext trả MỘT lần · revoke giữ tombstone hash · rate-limit
|
|
956
|
+
// fail cửa sổ trượt. Bỏ — keypair Ed25519 + tunnel WSS (dành cho device-sau-NAT ↔ hub
|
|
957
|
+
// public; nâng khi có relay). Nguồn tham chiếu: ~/source/my-durable/specs/
|
|
958
|
+
// 20261019-durable-agent-network/03-pairing.md.
|
|
959
|
+
// Vòng security sau (user chốt): 2 CHIỀU — device nhập code (chiều 1) chỉ tạo
|
|
960
|
+
// enrollment PENDING; token chỉ cấp khi OPERATOR duyệt tại máy (chiều 2, RPC qua unix
|
|
961
|
+
// socket 0600 — đúng §4.2 awaiting_approval). Device đối chiếu mã ghép displayId
|
|
962
|
+
// (ABCD-1234) hiện trên MÀN HÌNH nó với dòng `bom-pi pair pending` — thay fingerprint
|
|
963
|
+
// keypair đã cắt. Retry trong grace trả CÙNG token (receipt, §4.3).
|
|
964
|
+
const devicesPath = join(dataDir, 'web-devices.json');
|
|
965
|
+
let webDevices = []; // [{id, name, tokenHash, createdAtMs, lastSeenMs, revokedAtMs?}]
|
|
966
|
+
let pairCodes = new Map(); // code -> {expiresAt, used} — RAM, mất khi restart (đúng spec)
|
|
967
|
+
let pairEnrolls = new Map(); // enrollId -> enrollment 2-CHIỀU (xem pairStart) — RAM
|
|
968
|
+
let pairFails = []; // timestamps fail gần nhất (rate-limit cửa sổ trượt 15')
|
|
969
|
+
|
|
970
|
+
const PAIR_TTL_MS = 5 * 60_000;
|
|
971
|
+
const PAIR_GRACE_MS = 120_000; // sau approve: device có 2' pick-up token (receipt §4.3)
|
|
972
|
+
const PAIR_FAIL_WINDOW_MS = 15 * 60_000;
|
|
973
|
+
const PAIR_FAIL_MAX = 20;
|
|
974
|
+
|
|
975
|
+
async function loadDevices() {
|
|
976
|
+
try { webDevices = JSON.parse(await readFile(devicesPath, 'utf8')); } catch { webDevices = []; }
|
|
977
|
+
}
|
|
978
|
+
async function saveDevices() {
|
|
979
|
+
const tmp = devicesPath + '.tmp';
|
|
980
|
+
await writeFile(tmp, JSON.stringify(webDevices, null, 2) + '\n');
|
|
981
|
+
await rename(tmp, devicesPath);
|
|
982
|
+
}
|
|
983
|
+
const sha256hex = (s) => createHash('sha256').update(s).digest('hex');
|
|
984
|
+
// Daemon keypair Ed25519 — sinh tại lần boot đầu (khuôn ssh host key / spin daemon):
|
|
985
|
+
// MÁY NÀO cài bom-pi cũng tự có cặp key riêng. fp = 8 hex đầu sha256(publicKey DER) —
|
|
986
|
+
// fingerprint THẬT của pubkey, offer pair mang kèm pubkey base64 (daemonPublicKeyB64,
|
|
987
|
+
// khuôn paseo). Chữ ký offer/handshake sẽ bật ở chặng relay (DECISIONS) — identity
|
|
988
|
+
// ổn định từ bây giờ nên devices đã pair không phải pair lại khi nâng cấp.
|
|
989
|
+
let daemonFp = '';
|
|
990
|
+
let daemonPubB64 = '';
|
|
991
|
+
async function loadDaemonKeys() {
|
|
992
|
+
const p = join(dataDir, 'daemon-key');
|
|
993
|
+
let privB64 = '';
|
|
994
|
+
try { privB64 = (await readFile(p, 'utf8')).trim(); } catch { /* lần đầu — sinh mới */ }
|
|
995
|
+
let priv;
|
|
996
|
+
if (/^[A-Za-z0-9+/=]+$/.test(privB64) && privB64.length >= 60) { // PKCS8 ed25519 ⇒ base64 64 ký tự
|
|
997
|
+
priv = createPrivateKey({ key: Buffer.from(privB64, 'base64'), format: 'der', type: 'pkcs8' });
|
|
998
|
+
} else {
|
|
999
|
+
const kp = generateKeyPairSync('ed25519');
|
|
1000
|
+
priv = kp.privateKey;
|
|
1001
|
+
await writeFile(p, priv.export({ type: 'pkcs8', format: 'der' }).toString('base64') + '\n', { mode: 0o600 });
|
|
1002
|
+
}
|
|
1003
|
+
daemonPubB64 = createPublicKey(priv).export({ type: 'spki', format: 'der' }).toString('base64');
|
|
1004
|
+
daemonFp = sha256hex(Buffer.from(daemonPubB64, 'base64')).slice(0, 8).toUpperCase(); // hash bytes DER (khuôn ssh: hash blob key thật)
|
|
1005
|
+
}
|
|
1006
|
+
const newPairCode = () => {
|
|
1007
|
+
// 40 bit (5 byte) → 8 ký tự base32 RFC 4648 (A-Z2-7) — không 0/1 để khỏi lẫn O/I
|
|
1008
|
+
const alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
|
1009
|
+
const bytes = randomBytes(5);
|
|
1010
|
+
let val = 0n;
|
|
1011
|
+
for (const b of bytes) val = (val << 8n) | BigInt(b);
|
|
1012
|
+
let out = '';
|
|
1013
|
+
for (let i = 0; i < 8; i++) out = alpha[Number((val >> BigInt(35 - i * 5)) & 31n)] + out;
|
|
1014
|
+
return out;
|
|
1015
|
+
};
|
|
1016
|
+
function deviceTokenOk(token) {
|
|
1017
|
+
if (typeof token !== 'string' || !/^bom_[A-Za-z0-9_-]{43}$/.test(token)) return null;
|
|
1018
|
+
const d = webDevices.find((x) => !x.revokedAtMs && x.tokenHash === sha256hex(token));
|
|
1019
|
+
if (!d) return null;
|
|
1020
|
+
d.lastSeenMs = Date.now();
|
|
1021
|
+
return d;
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
// ---- LimitGate (tối giản khuôn pi-pocket — xem limit-gate.mjs) — tạo TRƯỚC boot (quy tắc TDZ) ----
|
|
1025
|
+
const limitGate = createLimitGate({ statePath: join(dataDir, 'provider-limits.json'), log });
|
|
1026
|
+
|
|
1027
|
+
// ---- Durable task debug (cầu real-test task-graph roles) — đặt TRƯỚC boot (quy tắc TDZ) ----
|
|
1028
|
+
// Sleeper: commit sleep 2 phút ⇒ node sống trong taskGraph để agents.list chiếu roles.
|
|
1029
|
+
// Task definition PHẢI đến qua extension.tasks (registry đọc extension.tasks, không nhận definition rời).
|
|
1030
|
+
const SLEEPER_DEF = {
|
|
1031
|
+
name: 'bom.debug.sleeper',
|
|
1032
|
+
version: 1,
|
|
1033
|
+
initial: () => ({ phase: 'sleep' }),
|
|
1034
|
+
phases: {
|
|
1035
|
+
sleep: async (task, runtime, context) => {
|
|
1036
|
+
await runtime.sleepUntil(runtime.now() + 120_000, { phase: 'sleep' }, context);
|
|
1037
|
+
},
|
|
1038
|
+
},
|
|
1039
|
+
abort: async (task, runtime, context) => {
|
|
1040
|
+
await runtime.commit({ status: 'completed', value: 'aborted' }, context);
|
|
1041
|
+
},
|
|
1042
|
+
};
|
|
1043
|
+
let taskRegistry = null; // gán trong boot sau createRegistry (registry là local của boot-try)
|
|
1044
|
+
|
|
1045
|
+
// ---- Mở Harness (pin exact @earendil-works 1.4.0 — xem DECISIONS.md) ----
|
|
1046
|
+
const { Harness } = await import('@earendil-works/pi-durable');
|
|
1047
|
+
const { openNodeSqliteStorage } = await import('@earendil-works/pi-durable/storage/sqlite/node');
|
|
1048
|
+
const { createRegistry, AgentDoc, defineExtension, wrapTool } = await import('@earendil-works/pi-durable');
|
|
1049
|
+
const { CodingTools } = await import('@earendil-works/pi-durable/tools');
|
|
1050
|
+
const { NodeExecutionEnv } = await import('@earendil-works/pi-durable/env/node');
|
|
1051
|
+
const { ModelRuntime } = await import('@earendil-works/pi-coding-agent');
|
|
1052
|
+
const { BACKGROUND_CONTEXT } = await import('@earendil-works/chord/context');
|
|
1053
|
+
const { defineTool } = await import('@earendil-works/pi-durable');
|
|
1054
|
+
const { Type } = await import('typebox');
|
|
1055
|
+
|
|
1056
|
+
// ---- Parity toolset `bom.factory` (M5b — spec §4): agent gọi ngược daemon ----
|
|
1057
|
+
// Nguyên tắc ĐỘC NHẤT: mỗi tool gọi ĐÚNG hàm internal mà RPC tương ứng đang gọi.
|
|
1058
|
+
// Scope: api.conversationId thật (probe P2) ⇒ tự suy ra factory — KHÔNG cần factoryId?.
|
|
1059
|
+
// Orphan (conversation không thuộc factory nào — K7): vẫn chạy conversation-scoped, không cap.
|
|
1060
|
+
// K4: BOM_PARITY_CONFIGURE=off ⇒ bỏ tool factory_configure khỏi toolset.
|
|
1061
|
+
function buildFactoryTools() {
|
|
1062
|
+
const tools = [];
|
|
1063
|
+
const ok = (obj) => ({ output: [{ type: 'text', text: JSON.stringify(obj) }] });
|
|
1064
|
+
// BẪY: output phải là content ARRAY [{type:'text'}] — trả chuỗi ⇒ pi-durable bỏ channel
|
|
1065
|
+
// output, replay cho model thấy "Tool result unavailable..." (lỗi này ẩn từ M4b DENY)
|
|
1066
|
+
const err = (msg) => ({ output: [{ type: 'text', text: String(msg) }], isError: true });
|
|
1067
|
+
const parseModelStr = (m) => {
|
|
1068
|
+
const [provider, modelId] = String(m ?? '').split('/');
|
|
1069
|
+
if (!provider || !modelId) throw new Error('model cần dạng "provider/modelId"');
|
|
1070
|
+
return parseModelRef({ provider, modelId });
|
|
1071
|
+
};
|
|
1072
|
+
|
|
1073
|
+
tools.push(defineTool({
|
|
1074
|
+
name: 'factory_spawn',
|
|
1075
|
+
description: 'Open a child conversation to handle one job, then submit its first prompt. The child inherits your cwd (your factory dir) and, unless given, your model. Max 20 tracked children per factory (oldest falls off the list — sliding).',
|
|
1076
|
+
parameters: Type.Object({
|
|
1077
|
+
instructions: Type.String({ description: 'System prompt for the child conversation' }),
|
|
1078
|
+
firstPrompt: Type.String({ description: 'First prompt the child starts working on' }),
|
|
1079
|
+
model: Type.Optional(Type.String({ description: 'provider/modelId — default: inherit yours' })),
|
|
1080
|
+
}),
|
|
1081
|
+
async execute(args, api) {
|
|
1082
|
+
try {
|
|
1083
|
+
const f = deriveFactory(api.conversationId);
|
|
1084
|
+
const callerState = await agentStateOf(api.conversationId);
|
|
1085
|
+
const model = args.model ? parseModelStr(args.model) : callerState?.model ?? null;
|
|
1086
|
+
const cwd = f ? (await agentStateOf(f.conversationId))?.cwd : callerState?.cwd ?? undefined; // con kế thừa cwd factory
|
|
1087
|
+
const child = await createConversationInternal({
|
|
1088
|
+
instructions: String(args.instructions ?? ''),
|
|
1089
|
+
...(model ? { model } : {}),
|
|
1090
|
+
...(cwd ? { cwd } : {}),
|
|
1091
|
+
});
|
|
1092
|
+
if (f) {
|
|
1093
|
+
f.childConversationIds.push(child.id);
|
|
1094
|
+
if (f.childConversationIds.length > 20) f.childConversationIds.shift(); // danh sách trượt — không brick (spec §4)
|
|
1095
|
+
await saveFactories();
|
|
1096
|
+
}
|
|
1097
|
+
if (args.firstPrompt) {
|
|
1098
|
+
await child.submit({ type: 'input', content: String(args.firstPrompt), requestId: `spawn-${child.id}` }, BACKGROUND_CONTEXT);
|
|
1099
|
+
}
|
|
1100
|
+
log('factory_spawn: conv', child.id, 'từ conv', api.conversationId, f ? `factory ${f.id}` : '(orphan K7)');
|
|
1101
|
+
return ok({ conversationId: child.id, factory: f?.id ?? null, cwd: cwd ?? null, model, note: f ? undefined : 'orphan spawn (không thuộc factory nào — K7)' });
|
|
1102
|
+
} catch (e) { return err(e?.message ?? e); }
|
|
1103
|
+
},
|
|
1104
|
+
}));
|
|
1105
|
+
|
|
1106
|
+
tools.push(defineTool({
|
|
1107
|
+
name: 'factory_schedule_add',
|
|
1108
|
+
description: 'Schedule your own future work: add a recurring prompt into YOUR conversation (cron-style, min 10s). Max 10 schedules per factory.',
|
|
1109
|
+
parameters: Type.Object({
|
|
1110
|
+
name: Type.String({ description: 'Unique schedule name within your factory' }),
|
|
1111
|
+
everySec: Type.Number({ description: 'Interval in seconds, >= 10' }),
|
|
1112
|
+
prompt: Type.String({ description: 'Prompt submitted to you on each tick' }),
|
|
1113
|
+
}),
|
|
1114
|
+
async execute(args, api) {
|
|
1115
|
+
try {
|
|
1116
|
+
const f = deriveFactory(api.conversationId);
|
|
1117
|
+
if (f && schedulesOfFactory(f.conversationId).length >= 10) return err(`cap: factory đã đủ 10 schedules (spec §4)`);
|
|
1118
|
+
const s = await addScheduleInternal({ name: args.name, everySec: args.everySec, prompt: args.prompt, conversationId: api.conversationId, origin: 'agent' });
|
|
1119
|
+
log('factory_schedule_add:', s.name, '— conv', api.conversationId);
|
|
1120
|
+
return ok({ schedule: { id: s.id, name: s.name, everySec: s.everySec, nextRunMs: s.dueMs } });
|
|
1121
|
+
} catch (e) { return err(e?.message ?? e); }
|
|
1122
|
+
},
|
|
1123
|
+
}));
|
|
1124
|
+
|
|
1125
|
+
tools.push(defineTool({
|
|
1126
|
+
name: 'factory_schedule_remove',
|
|
1127
|
+
description: 'Remove one of your schedules by name. Note: a schedule that still exists in factory.json comes back at the next sync — edit factory.json for permanent changes.',
|
|
1128
|
+
parameters: Type.Object({ name: Type.String({ description: 'Schedule name to remove' }) }),
|
|
1129
|
+
async execute(args, api) {
|
|
1130
|
+
try {
|
|
1131
|
+
const s = await removeScheduleByName(api.conversationId, String(args.name));
|
|
1132
|
+
log('factory_schedule_remove:', s.name, '— conv', api.conversationId);
|
|
1133
|
+
return ok({ removed: s.name, ...(s.origin === 'config' ? { warning: 'origin=config — sync kế tiếp sẽ THÊM LẠI từ factory.json; sửa factory.json để xoá hẳn' } : {}) });
|
|
1134
|
+
} catch (e) { return err(e?.message ?? e); }
|
|
1135
|
+
},
|
|
1136
|
+
}));
|
|
1137
|
+
|
|
1138
|
+
tools.push(defineTool({
|
|
1139
|
+
name: 'factory_watch',
|
|
1140
|
+
description: 'Register a file trigger: when files matching the glob change (poll ~10s + debounce), a prompt is submitted to your factory conversation. NOT durable across daemon restarts (K12). Max 10 watches per factory.',
|
|
1141
|
+
parameters: Type.Object({
|
|
1142
|
+
name: Type.String({ description: 'Unique watch name within your factory' }),
|
|
1143
|
+
glob: Type.String({ description: 'Glob like src/**/*.ts — keep it narrow; avoid watching your own pages/' }),
|
|
1144
|
+
prompt: Type.String({ description: 'Prompt submitted when changes are detected' }),
|
|
1145
|
+
debounceSec: Type.Optional(Type.Number({ description: 'Group changes within N seconds — default 30' })),
|
|
1146
|
+
}),
|
|
1147
|
+
async execute(args, api) {
|
|
1148
|
+
try {
|
|
1149
|
+
const f = deriveFactory(api.conversationId);
|
|
1150
|
+
if (f && watchesOf(f.conversationId).length >= 10) return err('cap: factory đã đủ 10 watches (spec §4)');
|
|
1151
|
+
const w = registerWatch({
|
|
1152
|
+
ownerKey: f?.id ?? `conv-${api.conversationId}`,
|
|
1153
|
+
name: String(args.name),
|
|
1154
|
+
glob: String(args.glob),
|
|
1155
|
+
debounceSec: args.debounceSec,
|
|
1156
|
+
prompt: String(args.prompt),
|
|
1157
|
+
conversationId: f?.conversationId ?? api.conversationId,
|
|
1158
|
+
origin: 'agent',
|
|
1159
|
+
});
|
|
1160
|
+
log('factory_watch:', w.key);
|
|
1161
|
+
return ok({ watch: w, note: 'kích hoạt scan từ M5d — hiện đã đăng ký; KHÔNG bền qua restart (K12)' });
|
|
1162
|
+
} catch (e) { return err(e?.message ?? e); }
|
|
1163
|
+
},
|
|
1164
|
+
}));
|
|
1165
|
+
|
|
1166
|
+
tools.push(defineTool({
|
|
1167
|
+
name: 'factory_configure',
|
|
1168
|
+
description: 'Modify YOUR OWN agent config (model / instructions). Writes both the live agent doc AND your factory.json so a later sync keeps your changes (one data channel).',
|
|
1169
|
+
parameters: Type.Object({
|
|
1170
|
+
model: Type.Optional(Type.String({ description: 'provider/modelId' })),
|
|
1171
|
+
instructions: Type.Optional(Type.String({ description: 'New system prompt' })),
|
|
1172
|
+
}),
|
|
1173
|
+
async execute(args, api) {
|
|
1174
|
+
try {
|
|
1175
|
+
const change = {};
|
|
1176
|
+
if (args.model !== undefined) change.model = parseModelStr(args.model);
|
|
1177
|
+
if (args.instructions !== undefined) change.instructions = String(args.instructions);
|
|
1178
|
+
if (!Object.keys(change).length) return err('cần model? hoặc instructions?');
|
|
1179
|
+
const conv = await harness.conversation(api.conversationId, BACKGROUND_CONTEXT);
|
|
1180
|
+
await conv.configure(change, BACKGROUND_CONTEXT);
|
|
1181
|
+
// Một kênh dữ liệu (spec §2.5 vá): ghi lại vào factory.json để sync không đè self-modify
|
|
1182
|
+
const f = deriveFactory(api.conversationId);
|
|
1183
|
+
let configUpdated = false;
|
|
1184
|
+
if (f) {
|
|
1185
|
+
const cfgPath = join(f.dir, 'factory.json');
|
|
1186
|
+
try {
|
|
1187
|
+
const raw = JSON.parse(await readFile(cfgPath, 'utf8'));
|
|
1188
|
+
if (change.model) raw.model = change.model;
|
|
1189
|
+
if (change.instructions) raw.instructions = change.instructions;
|
|
1190
|
+
await writeFile(cfgPath, JSON.stringify(raw, null, 2) + '\n');
|
|
1191
|
+
configUpdated = true;
|
|
1192
|
+
} catch (e) { log('factory_configure: không ghi được factory.json:', e?.message ?? e); }
|
|
1193
|
+
}
|
|
1194
|
+
log('factory_configure: conv', api.conversationId, Object.keys(change).join(','));
|
|
1195
|
+
return ok({ applied: Object.keys(change), configUpdated, ...(f ? {} : { note: 'orphan — chỉ áp agent doc, không có factory.json (K7)' }) });
|
|
1196
|
+
} catch (e) { return err(e?.message ?? e); }
|
|
1197
|
+
},
|
|
1198
|
+
}));
|
|
1199
|
+
|
|
1200
|
+
tools.push(defineTool({
|
|
1201
|
+
name: 'factory_status',
|
|
1202
|
+
description: 'See your factory: status, schedules, watches, tracked child conversations, pages. Works for orphan conversations too (factory: null).',
|
|
1203
|
+
parameters: Type.Object({}),
|
|
1204
|
+
async execute(args, api) {
|
|
1205
|
+
try {
|
|
1206
|
+
const f = deriveFactory(api.conversationId);
|
|
1207
|
+
if (!f) {
|
|
1208
|
+
const mine = schedules.filter((s) => s.conversationId === api.conversationId).map((s) => ({ id: s.id, name: s.name ?? null, everySec: s.everySec, disabled: s.disabled, origin: s.origin }));
|
|
1209
|
+
return ok({ factory: null, conversationId: api.conversationId, schedules: mine, note: 'orphan — không thuộc factory nào (K7)' });
|
|
1210
|
+
}
|
|
1211
|
+
let cfg = null;
|
|
1212
|
+
try { cfg = await readFactoryConfig(f.dir); } catch { /* config hỏng — vẫn trả phần registry */ }
|
|
1213
|
+
return ok(await factorySnapshot(f, cfg));
|
|
1214
|
+
} catch (e) { return err(e?.message ?? e); }
|
|
1215
|
+
},
|
|
1216
|
+
}));
|
|
1217
|
+
|
|
1218
|
+
tools.push(defineTool({
|
|
1219
|
+
name: 'pages_list',
|
|
1220
|
+
description: 'List your markdown pages (files in pages/ of your factory dir) — what you have already written. Write pages with the write tool.',
|
|
1221
|
+
parameters: Type.Object({}),
|
|
1222
|
+
async execute(args, api) {
|
|
1223
|
+
try {
|
|
1224
|
+
const f = deriveFactory(api.conversationId);
|
|
1225
|
+
const baseDir = f ? f.dir : (await agentStateOf(api.conversationId))?.cwd;
|
|
1226
|
+
if (!baseDir) return err('không xác định được dir (orphan không có cwd)');
|
|
1227
|
+
return ok({ pages: await listPagesInternal(baseDir, f ? await pagesDirOf(f) : 'pages') });
|
|
1228
|
+
} catch (e) { return err(e?.message ?? e); }
|
|
1229
|
+
},
|
|
1230
|
+
}));
|
|
1231
|
+
|
|
1232
|
+
tools.push(defineTool({
|
|
1233
|
+
name: 'factory_propose',
|
|
1234
|
+
description: 'Propose your branch for merge: creates a MERGE approval for the operator. Work on a branch (git checkout -b … , commit), then call this with the branch name and a title. Approve ⇒ daemon merges --no-ff into the current base branch; deny ⇒ repo untouched. Merge always needs the operator — every autonomy level.',
|
|
1235
|
+
parameters: Type.Object({
|
|
1236
|
+
branch: Type.String({ description: 'Branch you worked on — must exist and have commits ahead of base' }),
|
|
1237
|
+
title: Type.String({ description: 'One-line merge title shown to the operator' }),
|
|
1238
|
+
summary: Type.Optional(Type.String({ description: 'What changed and why (shown to the operator)' })),
|
|
1239
|
+
}),
|
|
1240
|
+
async execute(args, api) {
|
|
1241
|
+
try {
|
|
1242
|
+
return ok(await proposeInternal({ conversationId: api.conversationId, branch: args.branch, title: args.title, summary: args.summary }));
|
|
1243
|
+
} catch (e) { return err(e?.message ?? e); }
|
|
1244
|
+
},
|
|
1245
|
+
}));
|
|
1246
|
+
|
|
1247
|
+
const toolset = { name: 'bom.factory', tools };
|
|
1248
|
+
if (/^(off|0|false)$/i.test(process.env.BOM_PARITY_CONFIGURE ?? '')) {
|
|
1249
|
+
// K4: tắt self-modify model/instructions (agent không tự chọn model đắt)
|
|
1250
|
+
toolset.tools = tools.filter((t) => t.name !== 'factory_configure');
|
|
1251
|
+
}
|
|
1252
|
+
return defineExtension(toolset);
|
|
1253
|
+
}
|
|
1254
|
+
|
|
1255
|
+
try {
|
|
1256
|
+
await mkdir(dataDir, { recursive: true });
|
|
1257
|
+
if (!(await acquireLock())) process.exit(1);
|
|
1258
|
+
const probe = await probeSocket(socketPath);
|
|
1259
|
+
if (probe.alive) {
|
|
1260
|
+
log(`từ chối khởi động: bom-core khác đang nghe tại ${socketPath} (pid ${probe.hello?.result?.pid ?? '?'})`);
|
|
1261
|
+
await rm(lockPath, { force: true });
|
|
1262
|
+
process.exit(1);
|
|
1263
|
+
}
|
|
1264
|
+
|
|
1265
|
+
log('mở storage:', dbPath);
|
|
1266
|
+
storage = await openNodeSqliteStorage(dbPath);
|
|
1267
|
+
// ModelRuntime của pi-coding-agent: đọc credentials thật ~/.pi/agent/auth.json +
|
|
1268
|
+
// models catalog — daemon dùng CHÍNH account pi của user (DECISIONS D-models).
|
|
1269
|
+
models = await ModelRuntime.create();
|
|
1270
|
+
models = limitGate.wrapModels(models); // 429/usage-limit ⇒ đợi + retry trong stream, KHÔNG fail
|
|
1271
|
+
// CodingTools (read/write/edit/bash) — agent LÀM VIỆC được, không chỉ chat.
|
|
1272
|
+
// Chạy unattended trên máy user: giờ chưa có approval-gate (ghi DECISIONS).
|
|
1273
|
+
const registry = createRegistry();
|
|
1274
|
+
taskRegistry = registry;
|
|
1275
|
+
registry.install(CodingTools);
|
|
1276
|
+
registry.install(buildFactoryTools()); // parity M5b — agent gọi ngược daemon (spec §4)
|
|
1277
|
+
registry.install({ name: 'bom.debug.tasks', tasks: [{ definition: SLEEPER_DEF }] }); // task def qua extension.tasks — phải có trước open
|
|
1278
|
+
if (APPROVALS_ON) {
|
|
1279
|
+
// M6a trust ladder: wrap MỌI tool ghi/chạy — L0 phê tất cả, L1+ chỉ bash (autonomyOfConversation)
|
|
1280
|
+
const names = ['bash', 'write', 'edit'];
|
|
1281
|
+
const found = names.map((n) => registry.snapshot().tools().find((t) => t.tool.name === n)?.tool);
|
|
1282
|
+
const missing = names.filter((n, i) => !found[i]);
|
|
1283
|
+
if (missing.length) throw new Error(`không tìm thấy tool ${missing.join(', ')} trong CodingTools để wrap approval`);
|
|
1284
|
+
registry.install(buildApprovalsExtension(found)); // select mặc định = mọi extension đã install
|
|
1285
|
+
}
|
|
1286
|
+
const envs = new Map(); // cwd → NodeExecutionEnv (cache như pi-pocket)
|
|
1287
|
+
// onReport = kênh DUY NHẤT nhận lỗi async (task_faulted, session_failed…) — phải log.
|
|
1288
|
+
harness = await Harness.open(storage, {
|
|
1289
|
+
registry,
|
|
1290
|
+
models,
|
|
1291
|
+
env: ({ cwd }) => {
|
|
1292
|
+
const dir = cwd ?? defaultCwd;
|
|
1293
|
+
let env = envs.get(dir);
|
|
1294
|
+
if (!env) {
|
|
1295
|
+
env = new NodeExecutionEnv({ cwd: dir });
|
|
1296
|
+
envs.set(dir, env);
|
|
1297
|
+
}
|
|
1298
|
+
return env;
|
|
1299
|
+
},
|
|
1300
|
+
onReport: (error, info) => log('report:', info?.type ?? '?', String(error?.message ?? error)),
|
|
1301
|
+
}, BACKGROUND_CONTEXT);
|
|
1302
|
+
// Session fail tự close chính nó — daemon chết theo (exit 1) để systemd restart.
|
|
1303
|
+
harness.closed.then((end) => {
|
|
1304
|
+
if (!closing && end?.reason === 'failed') {
|
|
1305
|
+
log('session failed:', String(end.error?.message ?? end.error));
|
|
1306
|
+
process.exit(1);
|
|
1307
|
+
}
|
|
1308
|
+
});
|
|
1309
|
+
// Daemon TỒN TẠI ĐỂ CHẠY VIỆC: bật scheduling ngay (idempotent).
|
|
1310
|
+
harness.resume();
|
|
1311
|
+
rootConv = await harness.root(BACKGROUND_CONTEXT); // tạo root lần đầu nếu chưa có
|
|
1312
|
+
activeConvId = rootConv.id;
|
|
1313
|
+
await loadSchedules();
|
|
1314
|
+
startSchedules();
|
|
1315
|
+
await loadFactories();
|
|
1316
|
+
await loadMetrics(); // M6c: ledger số đo trust ladder
|
|
1317
|
+
await loadDevices(); // M8: thiết bị đã pair (web-devices.json)
|
|
1318
|
+
await loadDaemonKeys(); // offer pair: keypair danh tính — fp + pubkey cho device đối chiếu
|
|
1319
|
+
if (factories.length) log('factories nạp lại:', factories.length, '—', factories.map((f) => f.id).join(', '));
|
|
1320
|
+
await loadConfigWatches(); // M5b: đăng lại watch config (scan-timer là M5d)
|
|
1321
|
+
startWatchScanner(); // M5d: polling 10s + debounce + submit [watch …]
|
|
1322
|
+
log('harness mở — scheduling =', (await harness.inspect(BACKGROUND_CONTEXT)).scheduling, '— root', rootConv.id, '— active', activeConvId);
|
|
1323
|
+
if (signalWhileOpening) await shutdown('signal khi mở');
|
|
1324
|
+
} catch (e) {
|
|
1325
|
+
log('lỗi khởi động:', e?.stack ?? e);
|
|
1326
|
+
await rm(lockPath, { force: true });
|
|
1327
|
+
process.exit(1);
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
const piDurableVersion = (await import('@earendil-works/pi-durable/package.json', { with: { type: 'json' } })).default.version;
|
|
1331
|
+
|
|
1332
|
+
// ---- Entries nhẹ cho transcript / events ----
|
|
1333
|
+
function textOf(message) {
|
|
1334
|
+
const c = message?.content;
|
|
1335
|
+
if (typeof c === 'string') return c;
|
|
1336
|
+
if (Array.isArray(c)) {
|
|
1337
|
+
return c
|
|
1338
|
+
.map((b) => {
|
|
1339
|
+
if (typeof b === 'string') return b;
|
|
1340
|
+
if (b?.type === 'toolCall') return `[tool ${b.name}]`; // làm tool call nhìn thấy được
|
|
1341
|
+
return b?.text ?? '';
|
|
1342
|
+
})
|
|
1343
|
+
.join('');
|
|
1344
|
+
}
|
|
1345
|
+
return '';
|
|
1346
|
+
}
|
|
1347
|
+
const lightEntries = (entries) => (entries ?? []).map((e) => {
|
|
1348
|
+
const m = e.model?.[0];
|
|
1349
|
+
const out = {
|
|
1350
|
+
id: e.id,
|
|
1351
|
+
kind: e.kind,
|
|
1352
|
+
role: m?.role ?? null,
|
|
1353
|
+
text: textOf(m),
|
|
1354
|
+
};
|
|
1355
|
+
// Lộ lỗi provider (vd 402 hết tiền) — không để assistant rỗng vô hình
|
|
1356
|
+
if (m?.stopReason === 'error' || m?.errorMessage) {
|
|
1357
|
+
out.error = String(m.errorMessage ?? m.stopReason).slice(0, 200);
|
|
1358
|
+
}
|
|
1359
|
+
return out;
|
|
1360
|
+
});
|
|
1361
|
+
|
|
1362
|
+
// ---- Conversation helpers ----
|
|
1363
|
+
async function convFor(params) {
|
|
1364
|
+
const id = params?.conversationId ?? activeConvId;
|
|
1365
|
+
const conv = id === rootConv?.id ? rootConv : await harness.conversation(id, BACKGROUND_CONTEXT);
|
|
1366
|
+
if (!conv) throw new Error(`conversation không tồn tại: ${id} — xem session.list`);
|
|
1367
|
+
return conv;
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
// ---- Events: MỘT watch handle mỗi conversation, fan-out N connection ----
|
|
1371
|
+
async function ensureWatch(convId, conv) {
|
|
1372
|
+
let w = watches.get(convId);
|
|
1373
|
+
if (w) return w;
|
|
1374
|
+
const handle = await conv.watch(BACKGROUND_CONTEXT);
|
|
1375
|
+
w = { handle, conns: new Set() };
|
|
1376
|
+
watches.set(convId, w);
|
|
1377
|
+
handle.start(async (value) => {
|
|
1378
|
+
eventsSeq += 1;
|
|
1379
|
+
const payload = JSON.stringify({
|
|
1380
|
+
jsonrpc: '2.0',
|
|
1381
|
+
method: 'events.update',
|
|
1382
|
+
params: { conversationId: convId, seq: eventsSeq, entries: lightEntries(value.entries) },
|
|
1383
|
+
}) + '\n';
|
|
1384
|
+
for (const c of w.conns) c.write(payload);
|
|
1385
|
+
});
|
|
1386
|
+
handle.closed.then((end) => {
|
|
1387
|
+
if (watches.get(convId) === w && end?.reason !== 'stopped') {
|
|
1388
|
+
log('watch', convId, 'kết thúc:', end?.reason ?? '?', '— dựng lại ở subscribe sau');
|
|
1389
|
+
watches.delete(convId);
|
|
1390
|
+
}
|
|
1391
|
+
}).catch(() => {});
|
|
1392
|
+
return w;
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
function startHeartbeat() {
|
|
1396
|
+
if (heartbeatTimer) return;
|
|
1397
|
+
heartbeatTimer = setInterval(() => {
|
|
1398
|
+
if (!watches.size) return;
|
|
1399
|
+
const at = Date.now();
|
|
1400
|
+
for (const [convId, w] of watches) {
|
|
1401
|
+
if (!w.conns.size) continue;
|
|
1402
|
+
const payload = JSON.stringify({ jsonrpc: '2.0', method: 'events.heartbeat', params: { conversationId: convId, seq: eventsSeq, at } }) + '\n';
|
|
1403
|
+
for (const conn of w.conns) conn.write(payload);
|
|
1404
|
+
}
|
|
1405
|
+
}, 30_000);
|
|
1406
|
+
heartbeatTimer.unref?.();
|
|
1407
|
+
}
|
|
1408
|
+
|
|
1409
|
+
// ---- JSON-RPC NDJSON ----
|
|
1410
|
+
const methods = {
|
|
1411
|
+
async hello() {
|
|
1412
|
+
return {
|
|
1413
|
+
name: 'bom-core',
|
|
1414
|
+
version: VERSION,
|
|
1415
|
+
protocol: PROTOCOL,
|
|
1416
|
+
node: process.version,
|
|
1417
|
+
pid: process.pid,
|
|
1418
|
+
piDurable: piDurableVersion,
|
|
1419
|
+
fp: daemonFp, pub: daemonPubB64, // danh tính daemon — device đối chiếu với offer pair
|
|
1420
|
+
db: dbPath,
|
|
1421
|
+
activeConversationId: activeConvId,
|
|
1422
|
+
};
|
|
1423
|
+
},
|
|
1424
|
+
async status() {
|
|
1425
|
+
const [inspection, usage] = await Promise.all([
|
|
1426
|
+
harness.inspect(BACKGROUND_CONTEXT),
|
|
1427
|
+
harness.usage(BACKGROUND_CONTEXT),
|
|
1428
|
+
]);
|
|
1429
|
+
return {
|
|
1430
|
+
scheduling: inspection.scheduling,
|
|
1431
|
+
// TaskInspection = {record: TaskRecord, state: {kind: running|ready|waiting|sleeping|completing|blocked}}
|
|
1432
|
+
tasks: (inspection.tasks ?? []).map((t) => ({ id: t.record?.id, kind: t.state?.kind })),
|
|
1433
|
+
// SubmissionRecord = {id, conversationId, requestId?, type, status: queued|placed|…}
|
|
1434
|
+
submissions: (inspection.submissions ?? []).map((s) => ({ id: s.id, status: s.status, requestId: s.requestId ?? null })),
|
|
1435
|
+
usage,
|
|
1436
|
+
};
|
|
1437
|
+
},
|
|
1438
|
+
async modelsList() {
|
|
1439
|
+
const available = models.getAvailableSnapshot?.() ?? [];
|
|
1440
|
+
const list = (available.length ? available : models.getModels?.() ?? []).map((m) => ({
|
|
1441
|
+
provider: m.provider,
|
|
1442
|
+
id: m.id,
|
|
1443
|
+
name: m.name ?? null,
|
|
1444
|
+
contextWindow: m.contextWindow ?? null,
|
|
1445
|
+
}));
|
|
1446
|
+
return { count: list.length, availableOnly: available.length > 0, models: list };
|
|
1447
|
+
},
|
|
1448
|
+
async sessionList() {
|
|
1449
|
+
// scanConversations qua commit (khuôn pi-pocket #recover) + AgentDoc mỗi conversation
|
|
1450
|
+
const ids = [];
|
|
1451
|
+
let cursor;
|
|
1452
|
+
for (;;) {
|
|
1453
|
+
const page = await harness.commit((tx) => tx.scanConversations({}, 256, cursor), BACKGROUND_CONTEXT);
|
|
1454
|
+
ids.push(...page.items.map((c) => c.id));
|
|
1455
|
+
cursor = page.cursor;
|
|
1456
|
+
if (!page.items.length || cursor === undefined || page.items.length < 256) break;
|
|
1457
|
+
}
|
|
1458
|
+
const out = [];
|
|
1459
|
+
for (const id of ids) {
|
|
1460
|
+
const agentState = await agentStateOf(id);
|
|
1461
|
+
out.push({
|
|
1462
|
+
id,
|
|
1463
|
+
active: id === activeConvId,
|
|
1464
|
+
root: rootConv && id === rootConv.id,
|
|
1465
|
+
model: agentState?.model ?? null,
|
|
1466
|
+
cwd: agentState?.cwd ?? null,
|
|
1467
|
+
instructions: agentState?.instructions ?? null, // M5a: smoke kiểm instructions của factory conv
|
|
1468
|
+
});
|
|
1469
|
+
}
|
|
1470
|
+
return { active: activeConvId, count: out.length, conversations: out };
|
|
1471
|
+
},
|
|
1472
|
+
async agentsList() {
|
|
1473
|
+
// Chiếu task-graph roles vào view (bản thực dụng của "tokens/agent.view.set"):
|
|
1474
|
+
// harness.taskGraph() là TaskGraph thật (node.owner = parent, node.conversations =
|
|
1475
|
+
// conversations task fork sở hữu) nhưng CHỈ chứa live tasks — conversation roots
|
|
1476
|
+
// không có trong graph (verify §8) ⇒ re-scan conversations để có cây đầy đủ.
|
|
1477
|
+
const [graph, convs, inspection] = await Promise.all([
|
|
1478
|
+
harness.taskGraph(BACKGROUND_CONTEXT),
|
|
1479
|
+
methods.sessionList(), // handleOne gọi fn tách khỏi methods ⇒ KHÔNG dùng this
|
|
1480
|
+
harness.inspect(BACKGROUND_CONTEXT),
|
|
1481
|
+
]);
|
|
1482
|
+
const nodes = Object.values((graph && graph.tasks) || graph?.value?.tasks || {});
|
|
1483
|
+
const byConv = new Map(convs.conversations.map((c) => [c.id, { ...c, tasks: [] }]));
|
|
1484
|
+
const orphanTasks = [];
|
|
1485
|
+
for (const n of nodes) {
|
|
1486
|
+
const node = {
|
|
1487
|
+
taskId: n.id,
|
|
1488
|
+
kind: n.kind ?? null,
|
|
1489
|
+
role: n.owner ? 'worker' : 'root', // có owner = worker; conv-owned = root
|
|
1490
|
+
fork: (n.conversations ?? []).length > 0,
|
|
1491
|
+
owns: n.conversations ?? [],
|
|
1492
|
+
owner: n.owner ?? null,
|
|
1493
|
+
background: n.background ?? false,
|
|
1494
|
+
status: n.state?.status ?? null,
|
|
1495
|
+
phase: n.state?.phase ?? null,
|
|
1496
|
+
blocked: n.blocked ?? null,
|
|
1497
|
+
};
|
|
1498
|
+
const bucket = byConv.get(n.conversationId);
|
|
1499
|
+
(bucket ? bucket.tasks : orphanTasks).push(node);
|
|
1500
|
+
}
|
|
1501
|
+
return {
|
|
1502
|
+
conversations: [...byConv.values()],
|
|
1503
|
+
orphanTasks,
|
|
1504
|
+
submissions: (inspection.submissions ?? []).map((s) => ({
|
|
1505
|
+
id: s.id,
|
|
1506
|
+
conversationId: s.conversationId ?? null,
|
|
1507
|
+
status: s.status,
|
|
1508
|
+
requestId: s.requestId ?? null,
|
|
1509
|
+
})),
|
|
1510
|
+
};
|
|
1511
|
+
},
|
|
1512
|
+
async tasksDebug(params) {
|
|
1513
|
+
// Tạo durable sleeper task (2 phút) — cầu real-test agents.list: {childOf} ⇒ worker,
|
|
1514
|
+
// mặc định ⇒ root. SLEEPER_DEF install lúc boot qua extension 'bom.debug.tasks'.
|
|
1515
|
+
if (!taskRegistry) throw new Error('harness chưa mở');
|
|
1516
|
+
const conv = await convFor(params);
|
|
1517
|
+
const owner = params.childOf ?? null;
|
|
1518
|
+
const taskId = await harness.commit(
|
|
1519
|
+
(tx) => tx.createTask(
|
|
1520
|
+
{ definition: SLEEPER_DEF },
|
|
1521
|
+
{},
|
|
1522
|
+
{ conversationId: conv.id, ownership: owner ? { kind: 'task', taskId: owner } : { kind: 'conversation' } },
|
|
1523
|
+
BACKGROUND_CONTEXT,
|
|
1524
|
+
),
|
|
1525
|
+
BACKGROUND_CONTEXT,
|
|
1526
|
+
);
|
|
1527
|
+
log('debug sleeper task', taskId, '—', owner ? `child của ${owner}` : 'conv-owned');
|
|
1528
|
+
return { taskId, conversationId: conv.id, role: owner ? 'worker' : 'root', sleepsMs: 120_000 };
|
|
1529
|
+
},
|
|
1530
|
+
async sessionNew(params) {
|
|
1531
|
+
const agent = {};
|
|
1532
|
+
if (params.model !== undefined) agent.model = parseModelRef(params.model);
|
|
1533
|
+
if (typeof params.cwd === 'string' && params.cwd.trim()) agent.cwd = resolve(params.cwd.trim());
|
|
1534
|
+
if (typeof params.instructions === 'string' && params.instructions.trim()) agent.instructions = params.instructions.trim();
|
|
1535
|
+
const conv = await createConversationInternal(agent);
|
|
1536
|
+
activeConvId = conv.id; // active là glue tầng RPC-face — internal không đụng (spec §4)
|
|
1537
|
+
log('conversation mới', conv.id, '— active');
|
|
1538
|
+
return { conversationId: conv.id };
|
|
1539
|
+
},
|
|
1540
|
+
async sessionSwitch(params) {
|
|
1541
|
+
const id = params.id ?? params.conversationId;
|
|
1542
|
+
const conv = await harness.conversation(id, BACKGROUND_CONTEXT);
|
|
1543
|
+
if (!conv) throw new Error(`conversation không tồn tại: ${id} — xem session.list`);
|
|
1544
|
+
activeConvId = conv.id;
|
|
1545
|
+
return { ok: true, conversationId: conv.id };
|
|
1546
|
+
},
|
|
1547
|
+
async sessionConfigure(params) {
|
|
1548
|
+
const conv = await convFor(params);
|
|
1549
|
+
const change = {};
|
|
1550
|
+
if (params.model !== undefined) {
|
|
1551
|
+
const { provider, modelId } = params.model ?? {};
|
|
1552
|
+
if (!provider || !modelId) throw new Error('model cần {provider, modelId} — xem models.list');
|
|
1553
|
+
if (!models.getModel?.(provider, modelId)) throw new Error(`không biết model ${provider}/${modelId} — xem models.list`);
|
|
1554
|
+
change.model = { provider, modelId };
|
|
1555
|
+
}
|
|
1556
|
+
if (typeof params.instructions === 'string') change.instructions = params.instructions;
|
|
1557
|
+
if (typeof params.cwd === 'string' && params.cwd.trim()) change.cwd = resolve(params.cwd.trim());
|
|
1558
|
+
if (Object.keys(change).length === 0) throw new Error('không có gì để cấu hình: model? / instructions? / cwd?');
|
|
1559
|
+
await conv.configure(change, BACKGROUND_CONTEXT);
|
|
1560
|
+
return { ok: true, conversationId: conv.id };
|
|
1561
|
+
},
|
|
1562
|
+
async sessionSubmit(params) {
|
|
1563
|
+
const conv = await convFor(params);
|
|
1564
|
+
const text = typeof params.text === 'string' ? params.text.trim() : '';
|
|
1565
|
+
if (!text) throw new Error('thiếu text');
|
|
1566
|
+
if (params.model) await methods.sessionConfigure({ ...params.model ? { model: params.model } : {}, conversationId: conv.id });
|
|
1567
|
+
const agent = await conv.agent(BACKGROUND_CONTEXT);
|
|
1568
|
+
if (!agent?.model) {
|
|
1569
|
+
throw new Error('chưa cấu hình model — session.configure {model:{provider,modelId}} rồi submit lại (xem models.list)');
|
|
1570
|
+
}
|
|
1571
|
+
const sub = await conv.submit(
|
|
1572
|
+
{
|
|
1573
|
+
type: 'input',
|
|
1574
|
+
content: text,
|
|
1575
|
+
...(params.requestId ? { requestId: String(params.requestId) } : {}),
|
|
1576
|
+
},
|
|
1577
|
+
BACKGROUND_CONTEXT,
|
|
1578
|
+
);
|
|
1579
|
+
return { conversationId: conv.id, submissionId: sub.id };
|
|
1580
|
+
},
|
|
1581
|
+
async sessionReset(params) {
|
|
1582
|
+
// Bối cảnh mới trong CÙNG conversation — đỡ phải mang toàn bộ lịch sử
|
|
1583
|
+
// vào context mỗi turn (pi.reset entry; handoff thành user-message đầu mới).
|
|
1584
|
+
const conv = await convFor(params);
|
|
1585
|
+
const handoff = typeof params.handoff === 'string' && params.handoff.trim() ? params.handoff.trim() : undefined;
|
|
1586
|
+
await conv.reset(handoff, BACKGROUND_CONTEXT);
|
|
1587
|
+
return { ok: true, conversationId: conv.id };
|
|
1588
|
+
},
|
|
1589
|
+
async sessionAbort(params) {
|
|
1590
|
+
// Đánh dấu mọi task sống + rút input đang chờ, chờ scope idle — cứu turn kẹt
|
|
1591
|
+
// (vd limit-gate đang đợi thang dài mà operator muốn bỏ).
|
|
1592
|
+
const conv = await convFor(params);
|
|
1593
|
+
await conv.abort(BACKGROUND_CONTEXT);
|
|
1594
|
+
const f = deriveFactory(conv.id); // M6c: abort = can thiệp — ledger + cân hạ cấp
|
|
1595
|
+
if (f) {
|
|
1596
|
+
await recordMetric({ kind: 'abort', factoryId: f.id, conversationId: conv.id });
|
|
1597
|
+
await maybeDemote(f);
|
|
1598
|
+
}
|
|
1599
|
+
return { ok: true, conversationId: conv.id };
|
|
1600
|
+
},
|
|
1601
|
+
async transcriptGet(params) {
|
|
1602
|
+
const limit = Number.isInteger(params.limit) && params.limit > 0 ? params.limit : 50;
|
|
1603
|
+
const conv = await convFor(params);
|
|
1604
|
+
const view = await conv.context(BACKGROUND_CONTEXT);
|
|
1605
|
+
const entries = lightEntries(view.entries);
|
|
1606
|
+
return { conversationId: conv.id, count: entries.length, entries: entries.slice(-limit) };
|
|
1607
|
+
},
|
|
1608
|
+
async transcriptRaw(params) {
|
|
1609
|
+
// Cho pocket-adapter (web): entries THÔ của pi-durable {id, kind, model:[…]} —
|
|
1610
|
+
// web tự projectEntry sang shape client pi-pocket (projection.ts port). Không qua
|
|
1611
|
+
// lightEntries vì bỏ mất blocks/thinking/toolCall/at.
|
|
1612
|
+
const conv = await convFor(params);
|
|
1613
|
+
const view = await conv.context(BACKGROUND_CONTEXT);
|
|
1614
|
+
const entries = (view.entries ?? []).map((e) => ({ id: e.id, kind: e.kind, model: e.model ?? null }));
|
|
1615
|
+
return { conversationId: conv.id, count: entries.length, entries };
|
|
1616
|
+
},
|
|
1617
|
+
// ---- Files & Changes (pocket Files tile / Changes review) ----
|
|
1618
|
+
// cwd của conversation từ agent config; path client bị nhốt trong cwd (traversal chặn).
|
|
1619
|
+
async convCwd(params) {
|
|
1620
|
+
const conv = await convFor(params);
|
|
1621
|
+
const agent = await conv.agent(BACKGROUND_CONTEXT);
|
|
1622
|
+
return { conversationId: conv.id, cwd: agent?.cwd ?? process.env.HOME ?? process.cwd() };
|
|
1623
|
+
},
|
|
1624
|
+
async fsList(params) {
|
|
1625
|
+
const { cwd } = await methods.convCwd(params);
|
|
1626
|
+
const files = [];
|
|
1627
|
+
let truncated = false;
|
|
1628
|
+
const SKIP = new Set(['node_modules', '.git', 'dist', 'build', '.cache']);
|
|
1629
|
+
const walk = async (rel) => {
|
|
1630
|
+
if (files.length >= 2000) { truncated = true; return; }
|
|
1631
|
+
let entries;
|
|
1632
|
+
try { entries = await readdir(join(cwd, rel), { withFileTypes: true }); } catch { return; }
|
|
1633
|
+
entries.sort((a, b) => a.name.localeCompare(b.name));
|
|
1634
|
+
for (const e of entries) {
|
|
1635
|
+
if (e.name.startsWith('.') || SKIP.has(e.name)) continue;
|
|
1636
|
+
const p = rel ? `${rel}/${e.name}` : e.name;
|
|
1637
|
+
if (e.isDirectory()) await walk(p);
|
|
1638
|
+
else { files.push(p); if (files.length >= 2000) { truncated = true; break; } }
|
|
1639
|
+
}
|
|
1640
|
+
};
|
|
1641
|
+
await walk('');
|
|
1642
|
+
return { files, truncated };
|
|
1643
|
+
},
|
|
1644
|
+
async fsView(params) {
|
|
1645
|
+
const { cwd } = await methods.convCwd(params);
|
|
1646
|
+
const p = resolve(cwd, String(params?.path ?? ''));
|
|
1647
|
+
if (p !== cwd && !p.startsWith(cwd + sep)) throw new Error('path ngoài thư mục làm việc');
|
|
1648
|
+
const st = await stat(p);
|
|
1649
|
+
if (st.size > 1_000_000) throw new Error('file quá lớn (>1MB)');
|
|
1650
|
+
return { path: String(params.path), text: await readFile(p, 'utf8') };
|
|
1651
|
+
},
|
|
1652
|
+
async changesGet(params) {
|
|
1653
|
+
const { cwd } = await methods.convCwd(params);
|
|
1654
|
+
let root = '';
|
|
1655
|
+
try { root = (await execFileAsync('git', ['-C', cwd, 'rev-parse', '--show-toplevel'], { timeout: 10_000 })).stdout.trim(); } catch { return { repo: null, files: [], more: 0, piOnly: [] }; }
|
|
1656
|
+
const branch = (await execFileAsync('git', ['-C', cwd, 'rev-parse', '--abbrev-ref', 'HEAD'], { timeout: 10_000 })).stdout.trim();
|
|
1657
|
+
const head = (await execFileAsync('git', ['-C', cwd, 'rev-parse', 'HEAD'], { timeout: 10_000 })).stdout.trim();
|
|
1658
|
+
const st = (await execFileAsync('git', ['-C', cwd, 'status', '--porcelain=v1', '-uall'], { timeout: 10_000 })).stdout;
|
|
1659
|
+
let numstat = '';
|
|
1660
|
+
try { numstat = (await execFileAsync('git', ['-C', cwd, 'diff', 'HEAD', '--numstat'], { timeout: 10_000 })).stdout; } catch { numstat = ''; }
|
|
1661
|
+
const statMap = new Map();
|
|
1662
|
+
for (const line of numstat.split('\n').filter(Boolean)) {
|
|
1663
|
+
const [a, r, p] = line.split('\t');
|
|
1664
|
+
statMap.set(p, { added: a === '-' ? 0 : Number(a), removed: r === '-' ? 0 : Number(r) });
|
|
1665
|
+
}
|
|
1666
|
+
const KIND = { M: 'modified', A: 'new', '?': 'new', D: 'deleted', R: 'renamed' };
|
|
1667
|
+
const files = [];
|
|
1668
|
+
for (const line of st.split('\n').filter(Boolean)) {
|
|
1669
|
+
const x = line[0] === ' ' ? '?' : line[0]; // staged letter; '?' = untracked
|
|
1670
|
+
const path = line.slice(3).trim();
|
|
1671
|
+
let s = statMap.get(path) ?? { added: 0, removed: 0 };
|
|
1672
|
+
if (s.added === 0 && s.removed === 0 && (KIND[x] === 'new')) {
|
|
1673
|
+
// untracked: numstat không có — đếm dòng file (diff full là +all)
|
|
1674
|
+
try { s = { added: (await readFile(join(cwd, path), 'utf8')).split('\n').filter(Boolean).length, removed: 0 }; } catch { /* binary/đã đổi */ }
|
|
1675
|
+
}
|
|
1676
|
+
files.push({ path, kind: KIND[x] ?? 'modified', added: s.added, removed: s.removed, byPi: false, version: `1:${Date.now()}` });
|
|
1677
|
+
}
|
|
1678
|
+
return { repo: { root, branch, head }, files, more: 0, piOnly: [] };
|
|
1679
|
+
},
|
|
1680
|
+
async changesDiff(params) {
|
|
1681
|
+
const { cwd } = await methods.convCwd(params);
|
|
1682
|
+
const p = resolve(cwd, String(params?.path ?? ''));
|
|
1683
|
+
if (p !== cwd && !p.startsWith(cwd + sep)) throw new Error('path ngoài thư mục làm việc');
|
|
1684
|
+
const rel = relative(cwd, p);
|
|
1685
|
+
try {
|
|
1686
|
+
const tracked = (await execFileAsync('git', ['-C', cwd, 'ls-files', '--error-unmatch', rel], { timeout: 10_000 })).stdout.trim();
|
|
1687
|
+
if (tracked) {
|
|
1688
|
+
const { stdout } = await execFileAsync('git', ['-C', cwd, 'diff', 'HEAD', '--', rel], { timeout: 20_000, maxBuffer: 4 * 1024 * 1024 });
|
|
1689
|
+
return { diff: stdout };
|
|
1690
|
+
}
|
|
1691
|
+
} catch { /* untracked hoặc lỗi — rơi về --no-index */ }
|
|
1692
|
+
try {
|
|
1693
|
+
// -C + path relative để header diff đúng b/<rel> (absolute path làm header a/<cwd>/...)
|
|
1694
|
+
const { stdout } = await execFileAsync('git', ['-C', cwd, 'diff', '--no-index', '--', '/dev/null', rel], { timeout: 20_000, maxBuffer: 4 * 1024 * 1024 });
|
|
1695
|
+
return { diff: stdout };
|
|
1696
|
+
} catch (e) {
|
|
1697
|
+
// git diff --no-index exit 1 khi CÓ khác biệt — stdout vẫn chứa diff
|
|
1698
|
+
if (e?.stdout) return { diff: String(e.stdout) };
|
|
1699
|
+
throw e;
|
|
1700
|
+
}
|
|
1701
|
+
},
|
|
1702
|
+
async eventsSubscribe(params, ctx) {
|
|
1703
|
+
const conv = await convFor(params);
|
|
1704
|
+
const w = await ensureWatch(conv.id, conv);
|
|
1705
|
+
w.conns.add(ctx.conn);
|
|
1706
|
+
let set = connConvs.get(ctx.conn);
|
|
1707
|
+
if (!set) { set = new Set(); connConvs.set(ctx.conn, set); }
|
|
1708
|
+
set.add(conv.id);
|
|
1709
|
+
startHeartbeat();
|
|
1710
|
+
const view = w.handle.value; // snapshot hiện tại (immutable)
|
|
1711
|
+
return {
|
|
1712
|
+
conversationId: conv.id,
|
|
1713
|
+
seq: eventsSeq,
|
|
1714
|
+
snapshot: lightEntries(view?.entries),
|
|
1715
|
+
heartbeatMs: 30_000,
|
|
1716
|
+
};
|
|
1717
|
+
},
|
|
1718
|
+
async approvalsList() {
|
|
1719
|
+
return { pending: approvalList() };
|
|
1720
|
+
},
|
|
1721
|
+
async approvalsAnswer(params) {
|
|
1722
|
+
const id = String(params?.id ?? '');
|
|
1723
|
+
const allow = params?.allow === true;
|
|
1724
|
+
const entry = pendingApprovals.get(id);
|
|
1725
|
+
if (!entry) throw new Error(`không có approval đang chờ id ${id} — xem approvals.list`);
|
|
1726
|
+
pendingApprovals.delete(id);
|
|
1727
|
+
entry.resolve({ allow, by: params?.by ?? 'operator' });
|
|
1728
|
+
pushApprovals();
|
|
1729
|
+
log('approval', allow ? 'CHO' : 'TỪ CHỐI', id);
|
|
1730
|
+
// M6c: ledger answer tool (merge do proposeInternal ghi sau merge thật) + cân hạ cấp
|
|
1731
|
+
const req = entry.request ?? {};
|
|
1732
|
+
const f = req.type === 'merge' ? null : deriveFactory(req.conversationId);
|
|
1733
|
+
if (f) {
|
|
1734
|
+
await recordMetric({ kind: 'approval', factoryId: f.id, tool: req.tool, allow });
|
|
1735
|
+
if (!allow) await maybeDemote(f);
|
|
1736
|
+
}
|
|
1737
|
+
return { ok: true, id, allow };
|
|
1738
|
+
},
|
|
1739
|
+
async approvalsSubscribe(params, ctx) {
|
|
1740
|
+
approvalConns.add(ctx.conn);
|
|
1741
|
+
return { ok: true, pending: approvalList() };
|
|
1742
|
+
},
|
|
1743
|
+
async schedulesList() {
|
|
1744
|
+
return { schedules: schedules.map(({ prompt, ...rest }) => ({ ...rest, prompt: prompt.slice(0, 80) })) };
|
|
1745
|
+
},
|
|
1746
|
+
async schedulesAdd(params) {
|
|
1747
|
+
// Đường RPC = kênh agent (spec §2.4) — DÙNG CHUNG addScheduleInternal với parity M5b
|
|
1748
|
+
const s = await addScheduleInternal({
|
|
1749
|
+
name: params?.name,
|
|
1750
|
+
everySec: params?.everySec,
|
|
1751
|
+
prompt: params?.prompt,
|
|
1752
|
+
conversationId: Number.isInteger(params?.conversationId) ? params.conversationId : null, // null = conversation active lúc chạy
|
|
1753
|
+
origin: 'agent',
|
|
1754
|
+
});
|
|
1755
|
+
return { ok: true, schedule: s };
|
|
1756
|
+
},
|
|
1757
|
+
async schedulesRemove(params) {
|
|
1758
|
+
const n = schedules.length;
|
|
1759
|
+
schedules = schedules.filter((s) => s.id !== params?.id);
|
|
1760
|
+
if (schedules.length === n) throw new Error(`không có schedule ${params?.id}`);
|
|
1761
|
+
await saveSchedules();
|
|
1762
|
+
return { ok: true, removed: n - schedules.length };
|
|
1763
|
+
},
|
|
1764
|
+
// ---- Factory RPC (M5a — spec §3; mount == sync idempotent theo dir) ----
|
|
1765
|
+
async pagesList(params) {
|
|
1766
|
+
// M5c1: [{name, title, bytes, mtimeMs}] — title = heading đầu (spec §3)
|
|
1767
|
+
const f = factoryById(String(params?.factoryId ?? params?.id ?? ''));
|
|
1768
|
+
if (!f) throw new Error(`không có factory ${params?.factoryId} — xem factory.list`);
|
|
1769
|
+
return { pages: await listPagesInternal(f.dir, await pagesDirOf(f)) };
|
|
1770
|
+
},
|
|
1771
|
+
async pagesGet(params) {
|
|
1772
|
+
// M5c1: validate name + realpath trong pagesDir (chặn ../ và symlink — spec §3 vá)
|
|
1773
|
+
const f = factoryById(String(params?.factoryId ?? params?.id ?? ''));
|
|
1774
|
+
if (!f) throw new Error(`không có factory ${params?.factoryId} — xem factory.list`);
|
|
1775
|
+
return getPageInternal(f, params?.name);
|
|
1776
|
+
},
|
|
1777
|
+
async factoryHook(params) {
|
|
1778
|
+
// M5d (spec §5.3): webhook nộp '[hook] <body>' vào conversation gốc của factory;
|
|
1779
|
+
// requestId hook-<factoryId>-<id gọi truyền | Date.now()> — ?id= riêng để idempotent
|
|
1780
|
+
const f = factoryById(String(params?.factoryId ?? ''));
|
|
1781
|
+
if (!f) throw new Error(`không có factory ${params?.factoryId} — xem factory.list`);
|
|
1782
|
+
if (f.status !== 'mounted') throw new Error(`factory ${f.id} đang stopped — hook bị từ chối`);
|
|
1783
|
+
const body = typeof params?.body === 'string' && params.body.trim() ? params.body.trim().slice(0, 4000) : '(empty)';
|
|
1784
|
+
const conv = await harness.conversation(f.conversationId, BACKGROUND_CONTEXT);
|
|
1785
|
+
const requestId = `hook-${f.id}-${typeof params?.id === 'string' && params.id ? params.id : Date.now()}`;
|
|
1786
|
+
await conv.submit({ type: 'input', content: `[hook] ${body}`, requestId }, BACKGROUND_CONTEXT);
|
|
1787
|
+
log('hook:', f.id, '—', body.slice(0, 60));
|
|
1788
|
+
return { ok: true, factoryId: f.id, conversationId: f.conversationId, requestId };
|
|
1789
|
+
},
|
|
1790
|
+
async factoryMount(params) {
|
|
1791
|
+
return mountFactory(params);
|
|
1792
|
+
},
|
|
1793
|
+
async factoryList() {
|
|
1794
|
+
const out = [];
|
|
1795
|
+
for (const f of factories) {
|
|
1796
|
+
let cfg = null;
|
|
1797
|
+
try { cfg = await readFactoryConfig(f.dir); } catch { /* config hỏng/bị xoá — snapshot vẫn hiện, name null */ }
|
|
1798
|
+
out.push(await factorySnapshot(f, cfg));
|
|
1799
|
+
}
|
|
1800
|
+
return { count: out.length, factories: out };
|
|
1801
|
+
},
|
|
1802
|
+
async factoryStop(params) {
|
|
1803
|
+
const f = factoryById(String(params?.id ?? ''));
|
|
1804
|
+
if (!f) throw new Error(`không có factory ${params?.id} — xem factory.list`);
|
|
1805
|
+
f.status = 'stopped';
|
|
1806
|
+
for (const s of schedulesOfFactory(f.conversationId)) s.disabled = true;
|
|
1807
|
+
clearWatchState(f.id); // M5d: huỷ debounce đang chờ
|
|
1808
|
+
await saveFactories();
|
|
1809
|
+
await saveSchedules();
|
|
1810
|
+
await recordMetric({ kind: 'stop', factoryId: f.id }); // M6c: stop = can thiệp
|
|
1811
|
+
await maybeDemote(f);
|
|
1812
|
+
log('factory stop:', f.id);
|
|
1813
|
+
return { ok: true, id: f.id, status: f.status };
|
|
1814
|
+
},
|
|
1815
|
+
async factoryStart(params) {
|
|
1816
|
+
const f = factoryById(String(params?.id ?? ''));
|
|
1817
|
+
if (!f) throw new Error(`không có factory ${params?.id} — xem factory.list`);
|
|
1818
|
+
f.status = 'mounted';
|
|
1819
|
+
const now = Date.now();
|
|
1820
|
+
for (const s of schedulesOfFactory(f.conversationId)) {
|
|
1821
|
+
s.disabled = false;
|
|
1822
|
+
if (s.dueMs <= now) s.dueMs = now + s.everySec * 1000; // không chạy bù dồn sau thời gian dừng
|
|
1823
|
+
}
|
|
1824
|
+
await saveFactories();
|
|
1825
|
+
await saveSchedules();
|
|
1826
|
+
log('factory start:', f.id);
|
|
1827
|
+
return { ok: true, id: f.id, status: f.status };
|
|
1828
|
+
},
|
|
1829
|
+
async factoryRemove(params) {
|
|
1830
|
+
const f = factoryById(String(params?.id ?? ''));
|
|
1831
|
+
if (!f) throw new Error(`không có factory ${params?.id} — xem factory.list`);
|
|
1832
|
+
factories = factories.filter((x) => x.id !== f.id);
|
|
1833
|
+
for (const s of schedulesOfFactory(f.conversationId)) s.disabled = true;
|
|
1834
|
+
clearWatchState(f.id); // M5d: huỷ watch state của factory đã gỡ
|
|
1835
|
+
await saveFactories();
|
|
1836
|
+
await saveSchedules();
|
|
1837
|
+
log('factory remove:', f.id, '— conversation', f.conversationId, 'giữ nguyên (data của daemon)');
|
|
1838
|
+
return { ok: true, removed: f.id, keptConversationId: f.conversationId };
|
|
1839
|
+
},
|
|
1840
|
+
// M6a (G2): cổng merge — RPC factory.propose {id, branch, title, summary?}; parity tool
|
|
1841
|
+
// factory_propose gọi ĐÚNG proposeInternal này (nguyên tắc §4 — không đường song song).
|
|
1842
|
+
async factoryPropose(params) {
|
|
1843
|
+
const f = factoryById(String(params?.id ?? params?.factoryId ?? ''));
|
|
1844
|
+
if (!f) throw new Error(`không có factory ${params?.id} — xem factory.list`);
|
|
1845
|
+
return proposeInternal({ conversationId: f.conversationId, branch: params?.branch, title: params?.title, summary: params?.summary });
|
|
1846
|
+
},
|
|
1847
|
+
async limitsList() {
|
|
1848
|
+
return { limits: limitGate.list() };
|
|
1849
|
+
},
|
|
1850
|
+
// M6c: dashboard số đo trust ladder — windows 24h/7d + per-factory + usage daemon-wide
|
|
1851
|
+
async metricsSummary() {
|
|
1852
|
+
return metricsSummaryInternal();
|
|
1853
|
+
},
|
|
1854
|
+
// ---- Pairing M8 (khuôn durable-pi 03-pairing, mức 1 máy LAN) ----
|
|
1855
|
+
async pairCode() {
|
|
1856
|
+
// operator-side (CLI trên máy): sinh code — RAM, TTL 5', single-use, không log
|
|
1857
|
+
// publicUrl: đặt khi daemon ngồi sau reverse-proxy/tunnel (vd cloudflared) — offer
|
|
1858
|
+
// pair sẽ mang URL công cộng để QR dùng được cả ngoài LAN (env của systemd unit)
|
|
1859
|
+
const now = Date.now();
|
|
1860
|
+
const code = newPairCode();
|
|
1861
|
+
pairCodes.set(code, { codeId: `pc-${now.toString(36)}${(factoryCounter++).toString(36)}`, expiresAt: now + PAIR_TTL_MS });
|
|
1862
|
+
return { code, expiresAtMs: now + PAIR_TTL_MS, ttlSec: PAIR_TTL_MS / 1000, fp: daemonFp, pub: daemonPubB64, publicUrl: process.env.BOM_PI_PUBLIC_URL || null };
|
|
1863
|
+
},
|
|
1864
|
+
async pairStart(params) {
|
|
1865
|
+
// device-side (public trong LAN): code đúng ⇒ tạo enrollment PENDING chờ operator
|
|
1866
|
+
// duyệt ở máy (2 chiều). KHÔNG cấp token ở bước này (vá: ai nhìn trộm code cũng
|
|
1867
|
+
// không tự pair được — operator phải bấm duyệt tại máy).
|
|
1868
|
+
const now = Date.now();
|
|
1869
|
+
pairFails = pairFails.filter((t) => t > now - PAIR_FAIL_WINDOW_MS);
|
|
1870
|
+
if (pairFails.length >= PAIR_FAIL_MAX) throw new Error('rate_limited — thử lại sau 15 phút');
|
|
1871
|
+
const code = String(params?.code ?? '').trim().toUpperCase();
|
|
1872
|
+
const entry = pairCodes.get(code);
|
|
1873
|
+
if (!entry || entry.expiresAt < now) {
|
|
1874
|
+
pairFails.push(now);
|
|
1875
|
+
throw new Error('code_invalid hoặc hết hạn — chạy `bom-pi pair` lấy code mới');
|
|
1876
|
+
}
|
|
1877
|
+
if (entry.used) {
|
|
1878
|
+
pairFails.push(now);
|
|
1879
|
+
throw new Error('code_used — code chỉ dùng MỘT lần, chạy `bom-pi pair` lấy code mới'); // spec §4.3
|
|
1880
|
+
}
|
|
1881
|
+
entry.used = true; // single-use: giữ tombstone đến TTL để phân biệt code_used/invalid
|
|
1882
|
+
const name = String(params?.name ?? '').trim().slice(0, 64) || 'device';
|
|
1883
|
+
const enrollId = randomBytes(16).toString('hex');
|
|
1884
|
+
const displayId = `${randomBytes(2).toString('hex').toUpperCase()}-${randomBytes(2).toString('hex').toUpperCase()}`; // mã ghép đối chiếu màn hình
|
|
1885
|
+
pairEnrolls.set(enrollId, { displayId, name, code, expiresAt: entry.expiresAt, approved: false, rejected: false, token: null, deviceId: null });
|
|
1886
|
+
log('pairing: THIẾT BỊ XIN PAIR', displayId, `"${name}" — chờ duyệt: bom-pi pair pending`);
|
|
1887
|
+
return { pending: true, enrollId, displayId, pollAfterMs: 1000, note: 'chờ operator duyệt tại máy (bom-pi pair pending)' };
|
|
1888
|
+
},
|
|
1889
|
+
async pairPending() {
|
|
1890
|
+
// operator-side: danh sách enrollment chờ quyết (duyệt/từ chối)
|
|
1891
|
+
const now = Date.now();
|
|
1892
|
+
for (const [id, e] of pairEnrolls) if (e.expiresAt + PAIR_GRACE_MS < now) pairEnrolls.delete(id); // dọn hết hạn
|
|
1893
|
+
const out = [...pairEnrolls.entries()].filter(([, e]) => !e.approved && !e.rejected)
|
|
1894
|
+
.map(([id, e]) => ({ enrollId: id, displayId: e.displayId, name: e.name, expiresAtMs: e.expiresAt }));
|
|
1895
|
+
return { pending: out };
|
|
1896
|
+
},
|
|
1897
|
+
async pairApprove(params) {
|
|
1898
|
+
// operator-side (unix socket 0600): duyệt enrollment ⇒ cấp device token, giữ trong
|
|
1899
|
+
// enrollment cho device pick-up trong grace (retry trả CÙNG token — receipt §4.3)
|
|
1900
|
+
const key = String(params?.enrollId ?? params?.id ?? '');
|
|
1901
|
+
const e = pairEnrolls.get(key) ?? [...pairEnrolls.entries()].find(([, x]) => x.displayId === String(params?.displayId ?? params?.id ?? ''))?.[1];
|
|
1902
|
+
if (!e || e.approved || e.rejected) throw new Error(`không có enrollment đang chờ "${key || params?.displayId}" — xem pair.pending`);
|
|
1903
|
+
const now = Date.now();
|
|
1904
|
+
if (e.expiresAt < now) throw new Error('enrollment hết hạn — thiết bị xin lại code mới');
|
|
1905
|
+
const token = `bom_${randomBytes(32).toString('base64url')}`;
|
|
1906
|
+
const dev = { id: `dev-${randomBytes(4).toString('hex')}`, name: e.name, tokenHash: sha256hex(token), createdAtMs: now, lastSeenMs: now };
|
|
1907
|
+
webDevices.push(dev);
|
|
1908
|
+
await saveDevices();
|
|
1909
|
+
e.approved = true;
|
|
1910
|
+
e.token = token; // receipt trong grace — pick-up nhiều lần trả cùng token (RAM, không log)
|
|
1911
|
+
e.deviceId = dev.id;
|
|
1912
|
+
log('pairing: DUYỆT', e.displayId, `"${e.name}" → device ${dev.id}`);
|
|
1913
|
+
return { approved: true, displayId: e.displayId, name: e.name, deviceId: dev.id };
|
|
1914
|
+
},
|
|
1915
|
+
async pairReject(params) {
|
|
1916
|
+
const key = String(params?.enrollId ?? params?.id ?? '');
|
|
1917
|
+
const e = pairEnrolls.get(key) ?? [...pairEnrolls.entries()].find(([, x]) => x.displayId === String(params?.displayId ?? params?.id ?? ''))?.[1];
|
|
1918
|
+
if (!e || e.approved || e.rejected) throw new Error(`không có enrollment đang chờ "${key || params?.displayId}" — xem pair.pending`);
|
|
1919
|
+
e.rejected = true;
|
|
1920
|
+
log('pairing: TỪ CHỐI', e.displayId, `"${e.name}"`);
|
|
1921
|
+
return { rejected: true, displayId: e.displayId };
|
|
1922
|
+
},
|
|
1923
|
+
async pairPoll(params) {
|
|
1924
|
+
// device-side (public): enrollmentId => pending | approved(+token 1 lần/receipt) | rejected | expired
|
|
1925
|
+
const now = Date.now();
|
|
1926
|
+
pairFails = pairFails.filter((t) => t > now - PAIR_FAIL_WINDOW_MS);
|
|
1927
|
+
if (pairFails.length >= PAIR_FAIL_MAX) throw new Error('rate_limited — thử lại sau 15 phút');
|
|
1928
|
+
const e = pairEnrolls.get(String(params?.enrollId ?? ''));
|
|
1929
|
+
if (!e) { pairFails.push(now); throw new Error('enrollment không tồn tại (hoặc đã hết hạn + dọn)'); }
|
|
1930
|
+
if (e.rejected) return { status: 'rejected' };
|
|
1931
|
+
if (e.expiresAt + PAIR_GRACE_MS < now) { pairEnrolls.delete(String(params?.enrollId)); throw new Error('enrollment hết hạn'); }
|
|
1932
|
+
if (e.approved) {
|
|
1933
|
+
const out = { status: 'approved', deviceId: e.deviceId, deviceToken: e.token, displayId: e.displayId };
|
|
1934
|
+
if (now > e.expiresAt) pairEnrolls.delete(String(params?.enrollId)); // hết grace ⇒ dọn, token chỉ còn ở device
|
|
1935
|
+
return out;
|
|
1936
|
+
}
|
|
1937
|
+
return { status: 'pending', pollAfterMs: 1000 };
|
|
1938
|
+
},
|
|
1939
|
+
async devicesList() {
|
|
1940
|
+
return { devices: webDevices.map(({ tokenHash, ...rest }) => ({ ...rest, tokenHash8: tokenHash.slice(0, 8) })) };
|
|
1941
|
+
},
|
|
1942
|
+
async devicesRemove(params) {
|
|
1943
|
+
const d = webDevices.find((x) => x.id === String(params?.id ?? '') && !x.revokedAtMs);
|
|
1944
|
+
if (!d) throw new Error(`không có device đang sống ${params?.id} — xem devices.list`);
|
|
1945
|
+
d.revokedAtMs = Date.now(); // tombstone: GIỮ tokenHash, token đã chết (spec §8.3)
|
|
1946
|
+
await saveDevices();
|
|
1947
|
+
log('pairing: thu hồi', d.id, `"${d.name}"`);
|
|
1948
|
+
return { ok: true, revoked: d.id };
|
|
1949
|
+
},
|
|
1950
|
+
async devicesVerify(params) {
|
|
1951
|
+
// web gọi (cache RAM riêng) — hash tra bảng active, sai trả {ok:false} không throw
|
|
1952
|
+
const d = deviceTokenOk(String(params?.token ?? ''));
|
|
1953
|
+
return d ? { ok: true, deviceId: d.id, name: d.name } : { ok: false };
|
|
1954
|
+
},
|
|
1955
|
+
async limitsRetry(params) {
|
|
1956
|
+
if (!limitGate.retry(String(params?.key ?? ''))) throw new Error(`không có gate ${params?.key} — xem limits.list`);
|
|
1957
|
+
return { ok: true };
|
|
1958
|
+
},
|
|
1959
|
+
async shutdown() {
|
|
1960
|
+
setImmediate(() => shutdown('rpc shutdown'));
|
|
1961
|
+
return { ok: true };
|
|
1962
|
+
},
|
|
1963
|
+
};
|
|
1964
|
+
|
|
1965
|
+
const writeMsg = (conn, obj) => conn.write(JSON.stringify(obj) + '\n');
|
|
1966
|
+
|
|
1967
|
+
async function handleOne(conn, msg) {
|
|
1968
|
+
// -32600 invalid request: null / không phải object / thiếu jsonrpc 2.0 / method không phải chuỗi
|
|
1969
|
+
if (!msg || typeof msg !== 'object' || Array.isArray(msg) || msg.jsonrpc !== '2.0' || typeof msg.method !== 'string') {
|
|
1970
|
+
writeMsg(conn, { jsonrpc: '2.0', id: msg?.id ?? null, error: { code: -32600, message: 'invalid request' } });
|
|
1971
|
+
return;
|
|
1972
|
+
}
|
|
1973
|
+
// method RPC dùng dấu chấm (models.list) — map sang key camelCase trong bảng
|
|
1974
|
+
const key = msg.method.replace(/\.[a-z]/g, (m) => m.slice(1).toUpperCase());
|
|
1975
|
+
const fn = Object.hasOwn(methods, key) ? methods[key] : null;
|
|
1976
|
+
if (!fn) {
|
|
1977
|
+
// Notification (không id) KHÔNG được trả lời theo spec — kể cả method lạ
|
|
1978
|
+
if (msg.id !== undefined) writeMsg(conn, { jsonrpc: '2.0', id: msg.id, error: { code: -32601, message: `method not found: ${msg.method}` } });
|
|
1979
|
+
return;
|
|
1980
|
+
}
|
|
1981
|
+
try {
|
|
1982
|
+
const ctx = {
|
|
1983
|
+
conn,
|
|
1984
|
+
// Notification server→client trên cùng connection — kênh events.update / events.heartbeat
|
|
1985
|
+
push: (method, params) => writeMsg(conn, { jsonrpc: '2.0', method, params: params ?? {} }),
|
|
1986
|
+
};
|
|
1987
|
+
const result = await fn(msg.params ?? {}, ctx);
|
|
1988
|
+
if (msg.id !== undefined) writeMsg(conn, { jsonrpc: '2.0', id: msg.id, result });
|
|
1989
|
+
} catch (e) {
|
|
1990
|
+
if (msg.id !== undefined) writeMsg(conn, { jsonrpc: '2.0', id: msg.id, error: { code: -32000, message: e?.message ?? String(e) } });
|
|
1991
|
+
}
|
|
1992
|
+
}
|
|
1993
|
+
|
|
1994
|
+
async function handle(conn, line) {
|
|
1995
|
+
let msg;
|
|
1996
|
+
try {
|
|
1997
|
+
msg = JSON.parse(line);
|
|
1998
|
+
} catch {
|
|
1999
|
+
writeMsg(conn, { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'parse error' } });
|
|
2000
|
+
return;
|
|
2001
|
+
}
|
|
2002
|
+
if (Array.isArray(msg)) {
|
|
2003
|
+
if (msg.length === 0) {
|
|
2004
|
+
writeMsg(conn, { jsonrpc: '2.0', id: null, error: { code: -32600, message: 'invalid request: empty batch' } });
|
|
2005
|
+
return;
|
|
2006
|
+
}
|
|
2007
|
+
for (const item of msg) await handleOne(conn, item); // batch: mỗi phần tử một dòng response
|
|
2008
|
+
return;
|
|
2009
|
+
}
|
|
2010
|
+
await handleOne(conn, msg);
|
|
2011
|
+
}
|
|
2012
|
+
|
|
2013
|
+
server = createServer((conn) => {
|
|
2014
|
+
let buf = '';
|
|
2015
|
+
conn.on('data', (chunk) => {
|
|
2016
|
+
buf += chunk.toString('utf8');
|
|
2017
|
+
let nl;
|
|
2018
|
+
while ((nl = buf.indexOf('\n')) >= 0) {
|
|
2019
|
+
const line = buf.slice(0, nl).trim();
|
|
2020
|
+
buf = buf.slice(nl + 1);
|
|
2021
|
+
if (!line) continue;
|
|
2022
|
+
handle(conn, line).catch((e) => log('lỗi xử lý request:', e?.message ?? e)); // không để reject giết daemon
|
|
2023
|
+
}
|
|
2024
|
+
});
|
|
2025
|
+
conn.on('close', () => {
|
|
2026
|
+
approvalConns.delete(conn);
|
|
2027
|
+
// bỏ mọi subscribe của connection này; conversation hết subscriber → stop watch
|
|
2028
|
+
for (const convId of connConvs.get(conn) ?? []) {
|
|
2029
|
+
const w = watches.get(convId);
|
|
2030
|
+
if (!w) continue;
|
|
2031
|
+
w.conns.delete(conn);
|
|
2032
|
+
if (!w.conns.size) {
|
|
2033
|
+
w.handle.stop().catch(() => {});
|
|
2034
|
+
watches.delete(convId);
|
|
2035
|
+
}
|
|
2036
|
+
}
|
|
2037
|
+
connConvs.delete(conn);
|
|
2038
|
+
});
|
|
2039
|
+
conn.on('error', (e) => log('conn lỗi:', e.message));
|
|
2040
|
+
});
|
|
2041
|
+
|
|
2042
|
+
await rm(socketPath, { force: true }); // an toàn: probe ở trên đã xác nhận không daemon sống
|
|
2043
|
+
await mkdir(dirname(socketPath), { recursive: true, mode: 0o700 });
|
|
2044
|
+
await new Promise((res) => server.listen(socketPath, res));
|
|
2045
|
+
chmodSync(socketPath, 0o600); // socket chỉ owner nối được
|
|
2046
|
+
listening = true;
|
|
2047
|
+
log('nghe tại', socketPath, '— protocol', PROTOCOL, '— pid', process.pid);
|