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.
Files changed (131) hide show
  1. package/README.md +33 -2
  2. package/apps/README.md +7 -0
  3. package/apps/web/README.md +21 -0
  4. package/apps/web/pocket-adapter.mjs +323 -0
  5. package/apps/web/public/LICENSE.pocket +21 -0
  6. package/apps/web/public/activity-fold.js +28 -0
  7. package/apps/web/public/agent-now.js +37 -0
  8. package/apps/web/public/agent-tile.js +79 -0
  9. package/apps/web/public/app.js +975 -0
  10. package/apps/web/public/apple-touch-icon.png +0 -0
  11. package/apps/web/public/artifact-bridge.js +687 -0
  12. package/apps/web/public/avatar.js +87 -0
  13. package/apps/web/public/back.js +554 -0
  14. package/apps/web/public/box-keys.js +216 -0
  15. package/apps/web/public/browser-panel.js +1097 -0
  16. package/apps/web/public/browser.js +68 -0
  17. package/apps/web/public/calls.js +139 -0
  18. package/apps/web/public/chat.js +919 -0
  19. package/apps/web/public/clock.js +34 -0
  20. package/apps/web/public/commands.js +578 -0
  21. package/apps/web/public/composer.js +2068 -0
  22. package/apps/web/public/diff-parse.js +672 -0
  23. package/apps/web/public/diff.js +1646 -0
  24. package/apps/web/public/dock.js +299 -0
  25. package/apps/web/public/extension-ui.js +2734 -0
  26. package/apps/web/public/files-panel.js +775 -0
  27. package/apps/web/public/files.js +368 -0
  28. package/apps/web/public/fonts/FiraCode-VF.woff2 +0 -0
  29. package/apps/web/public/fonts/Geist.woff2 +0 -0
  30. package/apps/web/public/fonts/IBMPlexMono-Variable-Italic.woff2 +0 -0
  31. package/apps/web/public/fonts/IBMPlexMono-Variable.woff2 +0 -0
  32. package/apps/web/public/fonts/InterVariable-Italic.woff2 +0 -0
  33. package/apps/web/public/fonts/InterVariable.woff2 +0 -0
  34. package/apps/web/public/fonts/Iosevka-Bold.woff2 +0 -0
  35. package/apps/web/public/fonts/Iosevka-BoldItalic.woff2 +0 -0
  36. package/apps/web/public/fonts/Iosevka-Italic.woff2 +0 -0
  37. package/apps/web/public/fonts/Iosevka-Regular.woff2 +0 -0
  38. package/apps/web/public/fonts/Iosevka-SemiBold.woff2 +0 -0
  39. package/apps/web/public/fonts/Iosevka-SemiBoldItalic.woff2 +0 -0
  40. package/apps/web/public/fonts/JetBrainsMono-Italic.woff2 +0 -0
  41. package/apps/web/public/fonts/JetBrainsMono.woff2 +0 -0
  42. package/apps/web/public/fonts/NerdFontsSymbolsMono.woff2 +0 -0
  43. package/apps/web/public/fonts/SOURCES.md +69 -0
  44. package/apps/web/public/gestures.js +610 -0
  45. package/apps/web/public/highlight.js +480 -0
  46. package/apps/web/public/history.js +70 -0
  47. package/apps/web/public/home.js +169 -0
  48. package/apps/web/public/icon-192.png +0 -0
  49. package/apps/web/public/icon-512.png +0 -0
  50. package/apps/web/public/icon-maskable-512.png +0 -0
  51. package/apps/web/public/icon.svg +16 -0
  52. package/apps/web/public/index.html +71 -0
  53. package/apps/web/public/launcher.js +1293 -0
  54. package/apps/web/public/linked-sessions.js +55 -0
  55. package/apps/web/public/live.js +39 -0
  56. package/apps/web/public/manifest.webmanifest +32 -0
  57. package/apps/web/public/model-refresh.js +73 -0
  58. package/apps/web/public/notify.js +251 -0
  59. package/apps/web/public/peeks.js +920 -0
  60. package/apps/web/public/pip-attachments.js +182 -0
  61. package/apps/web/public/pip-window.js +141 -0
  62. package/apps/web/public/pip.js +1217 -0
  63. package/apps/web/public/quote-reply.js +109 -0
  64. package/apps/web/public/quote-text.js +31 -0
  65. package/apps/web/public/rich.js +403 -0
  66. package/apps/web/public/run-frame.js +106 -0
  67. package/apps/web/public/safe-mode.js +71 -0
  68. package/apps/web/public/seen.js +169 -0
  69. package/apps/web/public/session-tree.js +117 -0
  70. package/apps/web/public/sessions.js +2695 -0
  71. package/apps/web/public/share.js +126 -0
  72. package/apps/web/public/sheets/appearance.js +820 -0
  73. package/apps/web/public/sheets/branch.js +353 -0
  74. package/apps/web/public/sheets/extensions.js +818 -0
  75. package/apps/web/public/sheets/file.js +318 -0
  76. package/apps/web/public/sheets/find.js +250 -0
  77. package/apps/web/public/sheets/folder.js +680 -0
  78. package/apps/web/public/sheets/gallery.js +2340 -0
  79. package/apps/web/public/sheets/hooks.js +350 -0
  80. package/apps/web/public/sheets/memory.js +531 -0
  81. package/apps/web/public/sheets/menu.js +580 -0
  82. package/apps/web/public/sheets/message.js +220 -0
  83. package/apps/web/public/sheets/model.js +412 -0
  84. package/apps/web/public/sheets/people.js +414 -0
  85. package/apps/web/public/sheets/pi-sessions.js +264 -0
  86. package/apps/web/public/sheets/providers.js +525 -0
  87. package/apps/web/public/sheets/running.js +130 -0
  88. package/apps/web/public/sheets/schedules.js +71 -0
  89. package/apps/web/public/sheets/session.js +249 -0
  90. package/apps/web/public/sheets/shortcuts.js +101 -0
  91. package/apps/web/public/sheets/spend.js +150 -0
  92. package/apps/web/public/sheets/text.js +53 -0
  93. package/apps/web/public/sheets/viewers.js +363 -0
  94. package/apps/web/public/sheets/worktree.js +50 -0
  95. package/apps/web/public/sheets.js +410 -0
  96. package/apps/web/public/signin.js +57 -0
  97. package/apps/web/public/slots.js +208 -0
  98. package/apps/web/public/store.js +1760 -0
  99. package/apps/web/public/style.css +18625 -0
  100. package/apps/web/public/subagents-board.js +879 -0
  101. package/apps/web/public/subagents.js +273 -0
  102. package/apps/web/public/sw.js +169 -0
  103. package/apps/web/public/taps.js +26 -0
  104. package/apps/web/public/theme-surface.d.ts +4 -0
  105. package/apps/web/public/theme-surface.js +266 -0
  106. package/apps/web/public/theme.js +845 -0
  107. package/apps/web/public/themes/lantern/colors.toml +25 -0
  108. package/apps/web/public/themes/lantern/direction.css +60 -0
  109. package/apps/web/public/themes/lantern/frame.css +254 -0
  110. package/apps/web/public/themes/lantern/theme.css +10 -0
  111. package/apps/web/public/themes/lantern/theme.json +7 -0
  112. package/apps/web/public/themes/pocket/theme.css +189 -0
  113. package/apps/web/public/themes/pocket/theme.json +6 -0
  114. package/apps/web/public/themes.js +556 -0
  115. package/apps/web/public/transcript.js +3348 -0
  116. package/apps/web/public/trust.js +295 -0
  117. package/apps/web/public/turns.js +507 -0
  118. package/apps/web/public/ui.js +1910 -0
  119. package/apps/web/public/voice.js +345 -0
  120. package/apps/web/server.mjs +774 -0
  121. package/package.json +43 -4
  122. package/packages/cli/src/bom-pi.mjs +452 -0
  123. package/packages/cli/templates/blank.factory.json +7 -0
  124. package/packages/cli/templates/dev.factory.json +11 -0
  125. package/packages/cli/templates/docs.factory.json +12 -0
  126. package/packages/cli/templates/ops.factory.json +14 -0
  127. package/packages/cli/templates/triage.factory.json +10 -0
  128. package/packages/core/src/daemon.mjs +2047 -0
  129. package/packages/core/src/limit-gate.mjs +192 -0
  130. package/packages/core/src/rpc-client.mjs +66 -0
  131. package/systemd/README.md +11 -0
@@ -0,0 +1,192 @@
1
+ // limit-gate.mjs — LimitGate TỐI GIẢN cho bom-core (khuôn pi-pocket limit-gate.ts, DECISIONS)
2
+ //
3
+ //Một request model fail TRƯỚC khi có nội dung, do limit tự-clear theo thời gian
4
+ // (429/408/5xx/rate-limit/usage-limit/overload) KHÔNG fail nữa: nó mở gate cho key,
5
+ // đợi theo thang backoff rồi GỬI LẠI trong chính stream đó — Harness chỉ thấy một
6
+ // request chậm. Gate theo `provider` khi lỗi nhắm cả account (usage limit), còn lại
7
+ // theo `provider/modelId`. KHÔNG tự đổi model, KHÔNG trả tiền thêm (request bị từ
8
+ // chối không tốn gì). Hết thang ⇒ fail như thường (không đợi vô hạn).
9
+ // Gate ghi `provider-limits.json` (chỉ là hint — mất file = không biết limit).
10
+ //
11
+ // KHÔNG có (so bản pi-pocket): canary 1-request-đợi-ngoài (ở đây mỗi stream tự retry
12
+ // trong nó), parse header reset-time, noWait marking, epoch sign-in. Đủ cho 1 user.
13
+
14
+ import { createAssistantMessageEventStream } from '@earendil-works/pi-ai/utils/event-stream';
15
+ import { readFile, writeFile, rename } from 'node:fs/promises';
16
+
17
+ // Thang backoff khi không biết reset-time (ms) — cuối lặp lại đến khi hết cap
18
+ const LADDER = [15_000, 30_000, 60_000, 120_000, 300_000, 600_000];
19
+ const MAX_TRIES = 8; // mỗi stream
20
+ const MAX_TOTAL_WAIT_MS = 30 * 60_000;
21
+
22
+ const CLEARABLE = /(^|[^0-9])(429|408|502|503|520)([^0-9]|$)|rate.?limit|usage.?limit|overload|temporar|try again|too many requests/i;
23
+ const ACCOUNT_WIDE = /usage.?limit/i;
24
+ const NON_CLEARABLE = /(^|[^0-9])(401|402|403)([^0-9]|$)|insufficient|billing|payment|credit|quota exceeded|unauthor/i;
25
+
26
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
27
+
28
+ export function classifyLimit(errorMessage) {
29
+ const text = String(errorMessage ?? '');
30
+ if (NON_CLEARABLE.test(text)) return { clearable: false }; // 402 hết tiền… — đợi cũng vô ích
31
+ if (CLEARABLE.test(text)) return { clearable: true, accountWide: ACCOUNT_WIDE.test(text) };
32
+ return { clearable: false };
33
+ }
34
+
35
+ export function createLimitGate({ statePath, log = () => {} }) {
36
+ const gates = new Map(); // key -> {until, tries, since}
37
+ let loaded = false;
38
+
39
+ async function load() {
40
+ if (loaded) return;
41
+ loaded = true;
42
+ try {
43
+ const raw = JSON.parse(await readFile(statePath, 'utf8'));
44
+ for (const [k, v] of Object.entries(raw)) {
45
+ if (v && typeof v.until === 'number') gates.set(k, { until: v.until, tries: v.tries ?? 0, since: v.since ?? Date.now() });
46
+ }
47
+ } catch {}
48
+ }
49
+ async function save() {
50
+ const obj = {};
51
+ for (const [k, v] of gates) obj[k] = v;
52
+ try {
53
+ await writeFile(statePath + '.tmp', JSON.stringify(obj, null, 2));
54
+ await rename(statePath + '.tmp', statePath);
55
+ } catch (e) {
56
+ log('limit-gate: không lưu được state:', e?.message ?? e);
57
+ }
58
+ }
59
+
60
+ function keysFor(model) {
61
+ const provider = String(model?.provider ?? '?');
62
+ const full = `${provider}/${String(model?.id ?? '?')}`;
63
+ return { provider, full };
64
+ }
65
+ function effectiveWait(model) {
66
+ const { provider, full } = keysFor(model);
67
+ const now = Date.now();
68
+ const w1 = gates.get(full)?.until ?? 0;
69
+ const w2 = gates.get(provider)?.until ?? 0;
70
+ return Math.max(w1, w2) - now;
71
+ }
72
+ function openGate(model, accountWide, waitMs) {
73
+ const { provider, full } = keysFor(model);
74
+ const key = accountWide ? provider : full;
75
+ const prev = gates.get(key);
76
+ const tries = (prev?.tries ?? 0) + 1;
77
+ const g = { until: Date.now() + waitMs, tries, since: prev?.since ?? Date.now() };
78
+ gates.set(key, g);
79
+ void save();
80
+ log(`limit-gate: MỞ ${key} ${Math.round(waitMs / 1000)}s (lần ${tries})`);
81
+ return g;
82
+ }
83
+ function clearGates(model) {
84
+ // canary LẤY ĐƯỢC content ⇒ gate mở hẳn (khuôn pi-pocket "the gate opens")
85
+ const { provider, full } = keysFor(model);
86
+ if (gates.delete(full) | gates.delete(provider)) {
87
+ void save();
88
+ log('limit-gate: MỞ KHÓA (request thành công)', full);
89
+ }
90
+ }
91
+
92
+ function list() {
93
+ const now = Date.now();
94
+ return [...gates.entries()].map(([key, g]) => ({ key, openMs: Math.max(0, g.until - now), tries: g.tries, since: g.since }));
95
+ }
96
+ function retry(key) {
97
+ const g = gates.get(key);
98
+ if (!g) return false;
99
+ g.until = Date.now();
100
+ void save();
101
+ log('limit-gate: retry', key);
102
+ return true;
103
+ }
104
+
105
+ // Wrap models: mọi method delegate về raw (bind raw), riêng streamSimple đi qua gate
106
+ function wrapModels(rawModels) {
107
+ const gatedStreamSimple = (model, context, options) => {
108
+ const out = createAssistantMessageEventStream();
109
+ void (async () => {
110
+ await load();
111
+ let waited = 0;
112
+ for (let attempt = 0; attempt <= MAX_TRIES; attempt++) {
113
+ const w = effectiveWait(model);
114
+ if (w > 0) {
115
+ log(`limit-gate: chờ ${Math.round(w / 1000)}s (${keysFor(model).full}, thử ${attempt + 1})`);
116
+ await sleep(w + 500 + Math.floor(Math.random() * 2500));
117
+ waited += w;
118
+ }
119
+ let sawContent = false;
120
+ let terminalMsg = null; // message cuối (done.message hoặc error.error) — không dựa stream.result()
121
+ const CONTENT = new Set(['text_delta', 'text_end', 'thinking_delta', 'thinking_end', 'toolcall_delta', 'toolcall_end']);
122
+ const stream = rawModels.streamSimple(model, context, options);
123
+ try {
124
+ // Nuốt event pre-content trong buffer: lần thử hỏng (429 trước nội dung) KHÔNG push
125
+ // gì ra ngoài — consumer thấy một request chậm rồi stream thật. EventStream kết thúc
126
+ // iteration ở terminal ĐẦU TIÊN nên tuyệt đối không push error event của lần thử hỏng.
127
+ const buf = [];
128
+ let flushed = false;
129
+ let cleared = false;
130
+ for await (const ev of stream) {
131
+ const t = ev?.type;
132
+ if (CONTENT.has(t)) sawContent = true;
133
+ if (t === 'done') terminalMsg = ev.message;
134
+ if (t === 'error') terminalMsg = ev.error;
135
+ if (sawContent && !cleared) { cleared = true; clearGates(model); }
136
+ if (!flushed) {
137
+ buf.push(ev);
138
+ if (sawContent) {
139
+ flushed = true;
140
+ for (const b of buf) out.push(b);
141
+ buf.length = 0;
142
+ }
143
+ } else {
144
+ out.push(ev);
145
+ }
146
+ }
147
+ if (!sawContent && terminalMsg?.errorMessage) {
148
+ const cls = classifyLimit(terminalMsg.errorMessage);
149
+ if (cls.clearable && attempt < MAX_TRIES && waited < MAX_TOTAL_WAIT_MS) {
150
+ const idx = Math.min(attempt, LADDER.length - 1);
151
+ openGate(model, cls.accountWide, LADDER[idx]);
152
+ continue; // gửi lại — buffer lần hỏng bị bỏ
153
+ }
154
+ }
155
+ for (const b of buf) out.push(b); // stream kết thúc không content (done trống / lỗi không-clearable)
156
+ out.end(terminalMsg ?? undefined);
157
+ return;
158
+ } catch (e) {
159
+ // lỗi ngoài event-stream: forward thành error event rồi kết thúc
160
+ out.push({
161
+ type: 'error',
162
+ reason: 'error',
163
+ error: {
164
+ role: 'assistant',
165
+ content: [],
166
+ api: model?.api ?? 'unknown',
167
+ provider: model?.provider ?? '?',
168
+ model: model?.id ?? '?',
169
+ stopReason: 'error',
170
+ errorMessage: String(e?.message ?? e),
171
+ timestamp: Date.now(),
172
+ },
173
+ });
174
+ out.end();
175
+ return;
176
+ }
177
+ }
178
+ })();
179
+ return out;
180
+ };
181
+
182
+ return new Proxy(rawModels, {
183
+ get(target, prop) {
184
+ if (prop === 'streamSimple') return gatedStreamSimple;
185
+ const v = Reflect.get(target, prop, target);
186
+ return typeof v === 'function' ? v.bind(target) : v;
187
+ },
188
+ });
189
+ }
190
+
191
+ return { wrapModels, list, retry, load };
192
+ }
@@ -0,0 +1,66 @@
1
+ // rpc-client.mjs — client NDJSON dùng chung cho cli/plugin/pane (một connection dài,
2
+ // nhiều request + nhận notification đẩy về).
3
+ import { resolve } from 'node:path';
4
+ import { userInfo } from 'node:os';
5
+ import { connect } from 'node:net';
6
+
7
+ export function bomSocketPath(env = process.env) {
8
+ if (env.BOM_PI_SOCKET) return env.BOM_PI_SOCKET;
9
+ const runtimeDir = env.XDG_RUNTIME_DIR || `/tmp/run-${userInfo().uid}`;
10
+ return resolve(runtimeDir, 'bom-pi.sock');
11
+ }
12
+
13
+ /**
14
+ * Mở 1 connection dài tới bom-core.
15
+ * callbacks: { onEvent(method, params), onClose(err), onError(err) }
16
+ * Trả: { rpc(method, params, timeoutMs), notify(method, params), close(), conn }
17
+ */
18
+ export function bomConnect(socketPath = bomSocketPath(), callbacks = {}) {
19
+ const conn = connect(socketPath);
20
+ let buf = '';
21
+ let nextId = 1;
22
+ const pending = new Map(); // id -> {resolve, reject, timer}
23
+
24
+ conn.on('data', (chunk) => {
25
+ buf += chunk.toString('utf8');
26
+ let nl;
27
+ while ((nl = buf.indexOf('\n')) >= 0) {
28
+ const line = buf.slice(0, nl).trim();
29
+ buf = buf.slice(nl + 1);
30
+ if (!line) continue;
31
+ let msg;
32
+ try { msg = JSON.parse(line); } catch { continue; }
33
+ if (msg.method) {
34
+ callbacks.onEvent?.(msg.method, msg.params ?? {});
35
+ } else if (pending.has(msg.id)) {
36
+ const p = pending.get(msg.id);
37
+ pending.delete(msg.id);
38
+ clearTimeout(p.timer);
39
+ if (msg.error) p.reject(new Error(`${msg.error.code}: ${msg.error.message}`));
40
+ else p.resolve(msg.result);
41
+ }
42
+ }
43
+ });
44
+ conn.on('error', (e) => callbacks.onError?.(e));
45
+ conn.on('close', () => {
46
+ for (const [, p] of pending) { clearTimeout(p.timer); p.reject(new Error('bom-core closed the connection')); }
47
+ pending.clear();
48
+ callbacks.onClose?.();
49
+ });
50
+
51
+ function rpc(method, params, timeoutMs = 8000) {
52
+ return new Promise((res, rej) => {
53
+ const id = nextId++;
54
+ const timer = setTimeout(() => {
55
+ pending.delete(id);
56
+ rej(new Error(`timeout after ${timeoutMs}ms: ${method}`));
57
+ }, timeoutMs);
58
+ pending.set(id, { resolve: res, reject: rej, timer });
59
+ conn.write(JSON.stringify({ jsonrpc: '2.0', id, method, params: params ?? {} }) + '\n');
60
+ });
61
+ }
62
+ const notify = (method, params) => conn.write(JSON.stringify({ jsonrpc: '2.0', method, params: params ?? {} }) + '\n');
63
+ const ready = () => new Promise((res, rej) => { conn.on('connect', res); conn.on('error', rej); });
64
+
65
+ return { conn, rpc, notify, ready, close: () => conn.end() };
66
+ }
@@ -0,0 +1,11 @@
1
+ # systemd user units (mẫu)
2
+
3
+ Đừng copy tay — chạy `bom-pi setup`: nó tự tìm đường dẫn cài (npm global hoặc working
4
+ tree), sinh 2 unit dưới `~/.config/systemd/user/`, daemon-reload và enable:
5
+
6
+ - `bom-core.service` — daemon (unix socket `$XDG_RUNTIME_DIR/bom-pi.sock`, data
7
+ `~/.local/state/bom-pi`)
8
+ - `bom-web.service` — web UI pocket (port 8791; set `BOM_PI_PUBLIC_URL` khi có tunnel)
9
+
10
+ Muốn expose ra internet: khuôn cloudflared (một tunnel một app, KHÔNG mở port router)
11
+ — xem docs/DECISIONS.md vòng "cloud trung gian".