@leavewhite9088/harness-bus 0.2.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/ARCHITECTURE.md +81 -81
  2. package/LICENSE +21 -21
  3. package/README.md +86 -86
  4. package/SETUP_FOR_AI.md +79 -79
  5. package/package.json +4 -2
  6. package/packages/agentd/agentd.config.json +3 -1
  7. package/packages/agentd/cli/commands.mjs +854 -810
  8. package/packages/agentd/cli/format.mjs +294 -238
  9. package/packages/agentd/cli/hbus.mjs +14 -14
  10. package/packages/agentd/cli/index.mjs +4 -4
  11. package/packages/agentd/cli/skill/SKILL.md +66 -61
  12. package/packages/agentd/cli/skill/references/custom.md +12 -0
  13. package/packages/agentd/cli/skill/references/playbooks.md +89 -86
  14. package/packages/agentd/cli/skill/references/routing.md +43 -35
  15. package/packages/agentd/cli/skill-install.mjs +157 -140
  16. package/packages/agentd/cli/update.mjs +221 -221
  17. package/packages/agentd/client/index.mjs +3 -3
  18. package/packages/agentd/contexts/executor.md +13 -12
  19. package/packages/agentd/contexts/templates/architect.md +12 -12
  20. package/packages/agentd/contexts/templates/coder.md +12 -12
  21. package/packages/agentd/contexts/templates/debugger.md +12 -12
  22. package/packages/agentd/contexts/templates/researcher.md +12 -12
  23. package/packages/agentd/contexts/templates/reviewer.md +12 -12
  24. package/packages/agentd/contexts/templates/tester.md +12 -12
  25. package/packages/agentd/core/base/data-dir.mjs +39 -39
  26. package/packages/agentd/core/base/index.mjs +5 -5
  27. package/packages/agentd/core/base/protocol.mjs +13 -13
  28. package/packages/agentd/core/env/config.mjs +52 -1
  29. package/packages/agentd/core/env/index.mjs +6 -1
  30. package/packages/agentd/core/env/install.mjs +82 -4
  31. package/packages/agentd/core/pi/index.mjs +1 -1
  32. package/packages/agentd/core/pi/rpc.mjs +206 -206
  33. package/packages/agentd/core/pool/acp/client.mjs +7 -9
  34. package/packages/agentd/core/pool/acp/process.mjs +27 -18
  35. package/packages/agentd/core/pool/acp/run-tracker.mjs +293 -293
  36. package/packages/agentd/core/pool/acp/sessions.mjs +465 -465
  37. package/packages/agentd/core/pool/acp/turn-runner.mjs +5 -3
  38. package/packages/agentd/core/pool/index.mjs +2 -2
  39. package/packages/agentd/core/pool/instances.mjs +3 -5
  40. package/packages/agentd/core/pool/probe.mjs +91 -85
  41. package/packages/agentd/core/pool/registry.mjs +45 -1
  42. package/packages/agentd/core/pool/support/compaction.mjs +2 -43
  43. package/packages/agentd/core/pool/support/index.mjs +1 -1
  44. package/packages/agentd/core/prompts/index.mjs +12 -12
  45. package/packages/agentd/core/prompts/rules.mjs +22 -22
  46. package/packages/agentd/core/prompts/templates.mjs +172 -172
  47. package/packages/agentd/core/providers/index.mjs +14 -14
  48. package/packages/agentd/core/providers/store.mjs +206 -206
  49. package/packages/agentd/core/records/cleanup.mjs +51 -51
  50. package/packages/agentd/core/records/index.mjs +8 -8
  51. package/packages/agentd/core/records/metrics.mjs +73 -73
  52. package/packages/agentd/core/records/recovery.mjs +39 -39
  53. package/packages/agentd/core/records/transcripts.mjs +122 -122
  54. package/packages/agentd/core/threads/index.mjs +18 -17
  55. package/packages/agentd/core/threads/manager.mjs +498 -476
  56. package/packages/agentd/core/threads/paths.mjs +78 -78
  57. package/packages/agentd/core/threads/store.mjs +146 -125
  58. package/packages/agentd/daemon/agentd.mjs +58 -58
  59. package/packages/agentd/daemon/events.mjs +126 -126
  60. package/packages/agentd/daemon/guard.mjs +127 -127
  61. package/packages/agentd/daemon/lifecycle.mjs +61 -61
  62. package/packages/agentd/daemon/ops/index.mjs +15 -15
  63. package/packages/agentd/daemon/ops/providers.mjs +46 -46
  64. package/packages/agentd/daemon/ops/run.mjs +413 -400
  65. package/packages/agentd/daemon/ops/system.mjs +76 -69
  66. package/packages/agentd/daemon/ops/threads.mjs +156 -153
  67. package/packages/agentd/daemon/server.mjs +130 -130
  68. package/packages/agentd/package.json +1 -1
  69. package/packages/agentd/pi-adapter/acp-adapter.mjs +501 -501
  70. package/packages/agentd/scripts/restart-daemon.mjs +74 -74
  71. package/packages/agentd/scripts/run-isolated.mjs +42 -42
  72. package/packages/agentd/scripts/run-unit.mjs +28 -28
  73. package/packages/backend/src/daemon.mjs +69 -69
  74. package/packages/backend/src/server.mjs +270 -270
  75. package/packages/drivers/{agy.mjs → agy/index.mjs} +2 -1
  76. package/packages/drivers/{claude.mjs → claude/index.mjs} +23 -1
  77. package/packages/drivers/{codex.mjs → codex/index.mjs} +2 -1
  78. package/packages/drivers/{dsh.mjs → dsh/index.mjs} +3 -2
  79. package/packages/drivers/grok/index.mjs +96 -0
  80. package/packages/drivers/index.mjs +25 -12
  81. package/packages/drivers/{kimi.mjs → kimi/index.mjs} +2 -1
  82. package/packages/drivers/{mcode.mjs → mcode/index.mjs} +2 -1
  83. package/packages/drivers/{opencode.mjs → opencode/index.mjs} +2 -1
  84. package/packages/drivers/{pi.mjs → pi/index.mjs} +3 -2
  85. package/packages/drivers/probes/acp.mjs +109 -109
  86. package/packages/drivers/probes/index.mjs +131 -129
  87. package/packages/drivers/probes/provider.mjs +222 -222
  88. package/packages/drivers/qoder/index.mjs +32 -0
  89. package/packages/drivers/{bin.mjs → shared/bin.mjs} +2 -0
  90. package/packages/drivers/shared/index.mjs +2 -0
  91. package/packages/preflight/bin/preflight.mjs +116 -116
  92. package/packages/preflight/src/index.mjs +5 -5
  93. package/packages/preflight/src/report.mjs +18 -1
  94. package/packages/web/dist/apple-touch-icon.png +0 -0
  95. package/packages/web/dist/assets/index-CT8dIwav.css +2 -0
  96. package/packages/web/dist/assets/index-CypTUMFB.js +79 -0
  97. package/packages/web/dist/favicon-32.png +0 -0
  98. package/packages/web/dist/favicon.svg +19 -15
  99. package/packages/web/dist/index.html +5 -5
  100. package/packages/web/dist/assets/index-B2kdkHNw.js +0 -79
  101. package/packages/web/dist/assets/index-DQTyjC4x.css +0 -2
  102. /package/packages/drivers/{dsh-sessions.mjs → dsh/sessions.mjs} +0 -0
  103. /package/packages/drivers/{pi-catalog.mjs → pi/catalog.mjs} +0 -0
  104. /package/packages/drivers/{lib.mjs → shared/lib.mjs} +0 -0
@@ -1,270 +1,270 @@
1
- import http from 'node:http';
2
- import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
3
- import { extname, isAbsolute, join, relative, resolve } from 'node:path';
4
- import { fileURLToPath } from 'node:url';
5
- import { call, onLive } from './daemon.mjs';
6
-
7
- const PORT = Number(process.env.BACKEND_PORT) || 8787;
8
- const HOST = process.env.BACKEND_HOST || '127.0.0.1';
9
- const GIT_SHA = process.env.APP_GIT_SHA || 'dev';
10
- const ALLOWED_ORIGIN = process.env.ALLOWED_ORIGIN || '';
11
- const WEB_DIST = process.env.SERVE_WEB_DIST === '1' ? resolve(fileURLToPath(new URL('../../web/dist', import.meta.url))) : null;
12
- const MAX_BODY = 1_000_000;
13
-
14
- const LOCAL_HOST = /^(localhost|127\.0\.0\.1|\[::1\]|gateway)(:\d+)?$/;
15
-
16
- class HttpError extends Error {
17
- constructor(status, message) {
18
- super(message);
19
- this.status = status;
20
- }
21
- }
22
-
23
- const json = (res, status, body) => {
24
- res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
25
- res.end(JSON.stringify(body));
26
- };
27
-
28
- async function readBody(req) {
29
- let size = 0;
30
- const chunks = [];
31
- for await (const c of req) {
32
- size += c.length;
33
- if (size > MAX_BODY) throw new HttpError(413, 'request body too large');
34
- chunks.push(c);
35
- }
36
- if (!chunks.length) return {};
37
- let text;
38
- try {
39
- text = new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks));
40
- } catch {
41
- throw new HttpError(400, 'body must be UTF-8 text');
42
- }
43
- try {
44
- return JSON.parse(text);
45
- } catch {
46
- throw new HttpError(400, 'body must be JSON');
47
- }
48
- }
49
-
50
- function guard(req, res) {
51
- if (!LOCAL_HOST.test(req.headers.host ?? '')) throw new HttpError(403, 'host not allowed');
52
- const origin = req.headers.origin;
53
- if (origin && ALLOWED_ORIGIN && origin === ALLOWED_ORIGIN) {
54
- res.setHeader('access-control-allow-origin', ALLOWED_ORIGIN);
55
- res.setHeader('access-control-allow-methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
56
- res.setHeader('access-control-allow-headers', 'content-type');
57
- res.setHeader('vary', 'Origin');
58
- return;
59
- }
60
- if (origin && req.method !== 'GET' && req.method !== 'HEAD') {
61
- let o;
62
- try {
63
- o = new URL(origin);
64
- } catch {
65
- throw new HttpError(403, 'bad origin');
66
- }
67
- if (!LOCAL_HOST.test(o.host)) throw new HttpError(403, 'origin not allowed');
68
- }
69
- }
70
-
71
- const num = (v) => (v == null || v === '' ? undefined : Number(v));
72
-
73
- const routes = [
74
- ['GET', '/api/health', async () => ({ ...(await call('health')), ok: true, gitSha: GIT_SHA })],
75
- ['GET', '/api/metrics', ({ query }) => call('metrics', { windowSec: num(query.windowSec) })],
76
- ['GET', '/api/receipts', ({ query }) => call('receipts', { limit: num(query.limit), workspace: query.workspace || undefined })],
77
- ['GET', '/api/audits', ({ query }) => call('audits', { limit: num(query.limit), workspace: query.workspace || undefined })],
78
- ['GET', '/api/models', ({ query }) => call('cli.models', { type: query.type, refresh: query.refresh === '1' })],
79
- [
80
- 'GET',
81
- '/api/effort',
82
- ({ query }) =>
83
- call('cli.effort', {
84
- type: query.type,
85
- model: query.model || undefined,
86
- refresh: query.refresh === '1',
87
- provider: query.provider ? { id: query.provider, model: query.providerModel || '' } : undefined,
88
- }),
89
- ],
90
-
91
- ['GET', '/api/threads', ({ query }) => call('thread.list', { cwd: query.cwd || undefined, onlyBusy: query.onlyBusy === '1' })],
92
- ['POST', '/api/threads', ({ body }) => call('thread.resolve', body)],
93
- ['GET', '/api/threads/:key', ({ params }) => call('thread.get', { thread: params.key })],
94
- [
95
- 'PATCH',
96
- '/api/threads/:key',
97
- ({ params, body }) =>
98
- call('thread.update', {
99
- thread: params.key,
100
- type: body.type,
101
- role: body.role,
102
- model: body.model,
103
- effort: body.effort,
104
- provider: body.provider,
105
- }),
106
- ],
107
- ['DELETE', '/api/threads/:key', ({ params }) => call('thread.remove', { thread: params.key })],
108
- ['POST', '/api/threads/:key/run', ({ params, body }) => startRun(params.key, body)],
109
- ['GET', '/api/threads/:key/tail', ({ params, query }) => call('tail', { thread: params.key, mode: query.mode || 'full' })],
110
- ['POST', '/api/threads/:key/start', ({ params }) => call('thread.start', { thread: params.key })],
111
- ['POST', '/api/threads/:key/probe', ({ params, body }) => call('thread.probe', { thread: params.key, timeoutMs: num(body?.timeoutMs) })],
112
- ['POST', '/api/threads/:key/recover', ({ params }) => call('thread.recover', { thread: params.key })],
113
- ['POST', '/api/threads/:key/cancel', ({ params, body }) => call('thread.cancel', { thread: params.key, jobId: body?.jobId })],
114
- ['POST', '/api/threads/:key/promote', ({ params, body }) => call('thread.promote', { thread: params.key, jobId: body.jobId })],
115
- ['POST', '/api/threads/:key/queue/clear', ({ params }) => call('thread.queue.clear', { thread: params.key })],
116
- ['GET', '/api/threads/:key/sessions', ({ params }) => call('thread.sessions', { thread: params.key })],
117
- ['POST', '/api/threads/:key/sessions', ({ params, body }) => call('thread.new', { thread: params.key, cwd: body?.cwd, label: body?.label })],
118
- ['POST', '/api/threads/:key/use', ({ params, body }) => call('thread.use', { thread: params.key, sessionId: body.sessionId })],
119
- ['POST', '/api/threads/:key/rename', ({ params, body }) => call('thread.renameSession', { thread: params.key, sessionId: body.sessionId, label: body.label })],
120
- ['DELETE', '/api/threads/:key/sessions/:sid', ({ params }) => call('thread.deleteSession', { thread: params.key, sessionId: params.sid })],
121
- [
122
- 'GET',
123
- '/api/threads/:key/sessions/:sid/transcript',
124
- ({ params, query }) =>
125
- call('thread.transcript', {
126
- thread: params.key,
127
- sessionId: params.sid,
128
- afterSeq: num(query.afterSeq),
129
- limit: num(query.limit),
130
- tail: query.tail === '1',
131
- }),
132
- ],
133
-
134
- ['GET', '/api/providers', () => call('provider.list')],
135
- ['POST', '/api/providers', ({ body }) => call('provider.save', body)],
136
- ['POST', '/api/providers/discover', ({ body }) => call('provider.discover', body)],
137
- ['DELETE', '/api/providers/:id', ({ params }) => call('provider.remove', { id: params.id })],
138
- ['POST', '/api/providers/:id/test', ({ params, body }) => call('provider.test', { id: params.id, model: body?.model, types: body?.types })],
139
-
140
- ['GET', '/api/roles', ({ query }) => call('role.list', { cwd: query.cwd || undefined })],
141
- ['PUT', '/api/roles/:id', ({ params, body }) => call('role.save', { ...body, id: params.id })],
142
- ['DELETE', '/api/roles/:id', ({ params }) => call('role.remove', { id: params.id })],
143
- ];
144
-
145
- async function startRun(thread, body) {
146
- if (typeof body.prompt !== 'string' || !body.prompt.trim()) throw new HttpError(400, 'prompt is required');
147
- return call('run', { thread, prompt: body.prompt, sessionId: body.sessionId, async: true, subscribe: true });
148
- }
149
-
150
- const compiled = routes.map(([method, pattern, handler]) => {
151
- const names = [];
152
- const re = new RegExp(
153
- '^' +
154
- pattern.replace(/:([a-z]+)/g, (_, n) => {
155
- names.push(n);
156
- return '([^/]+)';
157
- }) +
158
- '$',
159
- );
160
- return { method, re, names, handler };
161
- });
162
-
163
- function match(method, path) {
164
- for (const r of compiled) {
165
- if (r.method !== method) continue;
166
- const m = r.re.exec(path);
167
- if (m) return { r, params: Object.fromEntries(r.names.map((n, i) => [n, decodeURIComponent(m[i + 1])])) };
168
- }
169
- return null;
170
- }
171
-
172
- const sseClients = new Set();
173
-
174
- function writeSse(res, frame) {
175
- if (res.destroyed || res.writableEnded) {
176
- sseClients.delete(res);
177
- return;
178
- }
179
- try {
180
- res.write(frame);
181
- } catch {
182
- sseClients.delete(res);
183
- }
184
- }
185
-
186
- onLive((name, payload) => {
187
- if (!sseClients.size) return;
188
- const frame = `event: ${name}\ndata: ${JSON.stringify(payload)}\n\n`;
189
- for (const res of [...sseClients]) writeSse(res, frame);
190
- });
191
-
192
- async function events(req, res) {
193
- await call('hello');
194
- res.writeHead(200, {
195
- 'content-type': 'text/event-stream',
196
- 'cache-control': 'no-store',
197
- connection: 'keep-alive',
198
- });
199
- res.write('retry: 2000\n\n');
200
- sseClients.add(res);
201
- const ping = setInterval(() => writeSse(res, ': ping\n\n'), 20_000);
202
- req.on('close', () => {
203
- clearInterval(ping);
204
- sseClients.delete(res);
205
- });
206
- }
207
-
208
- const MIME = {
209
- '.html': 'text/html; charset=utf-8',
210
- '.js': 'application/javascript; charset=utf-8',
211
- '.css': 'text/css; charset=utf-8',
212
- '.json': 'application/json; charset=utf-8',
213
- '.svg': 'image/svg+xml',
214
- '.png': 'image/png',
215
- '.ico': 'image/x-icon',
216
- };
217
-
218
- function isInsideDist(target) {
219
- const rel = relative(WEB_DIST, target);
220
- if (rel.startsWith('..') || isAbsolute(rel)) return false;
221
- if (!existsSync(target)) return true;
222
- const realRel = relative(realpathSync(WEB_DIST), realpathSync(target));
223
- return !realRel.startsWith('..') && !isAbsolute(realRel);
224
- }
225
-
226
- function tryServeStatic(pathname, res) {
227
- if (!WEB_DIST || pathname.startsWith('/api/') || pathname === '/api') return false;
228
- const rel = pathname === '/' ? 'index.html' : pathname.replace(/^\/+/, '');
229
- let target = resolve(WEB_DIST, rel);
230
- if (!isInsideDist(target)) return false;
231
- if (!existsSync(target) || statSync(target).isDirectory()) target = join(WEB_DIST, 'index.html');
232
- if (!existsSync(target) || !isInsideDist(target)) return false;
233
- res.writeHead(200, { 'content-type': MIME[extname(target)] || 'application/octet-stream' });
234
- res.end(readFileSync(target));
235
- return true;
236
- }
237
-
238
- const server = http.createServer(async (req, res) => {
239
- try {
240
- guard(req, res);
241
- if (req.method === 'OPTIONS') {
242
- res.writeHead(204);
243
- return res.end();
244
- }
245
- const url = new URL(req.url, 'http://local');
246
- if (req.method === 'GET' && url.pathname === '/api/events') return await events(req, res);
247
- if (req.method === 'GET' && tryServeStatic(url.pathname, res)) return;
248
-
249
- const hit = match(req.method, url.pathname);
250
- if (!hit) throw new HttpError(404, `no route for ${req.method} ${url.pathname}`);
251
- const body = req.method === 'POST' || req.method === 'PUT' || req.method === 'PATCH' ? await readBody(req) : {};
252
- const result = await hit.r.handler({ params: hit.params, query: Object.fromEntries(url.searchParams), body });
253
- if (url.pathname === '/api/metrics' && url.searchParams.get('format') === 'prom' && typeof result?.prometheus === 'string') {
254
- res.writeHead(200, { 'content-type': 'text/plain; version=0.0.4; charset=utf-8', 'cache-control': 'no-store' });
255
- return res.end(result.prometheus);
256
- }
257
- json(res, 200, result ?? {});
258
- } catch (err) {
259
- if (res.headersSent) return res.end();
260
- const isDaemonConnErr =
261
- err.code === 'ECONNREFUSED' ||
262
- /agentd (?:closed|disconnected|did not start|not running)|could not connect to agentd|timed out waiting for agentd/i.test(err.message ?? '');
263
- const status = err.status ?? (isDaemonConnErr ? 502 : 400);
264
- json(res, status, { error: err.message });
265
- }
266
- });
267
-
268
- server.listen(PORT, HOST, () => {
269
- process.stderr.write(`[backend] http://${HOST}:${PORT} (agentd is started on first request)\n`);
270
- });
1
+ import http from 'node:http';
2
+ import { existsSync, readFileSync, realpathSync, statSync } from 'node:fs';
3
+ import { extname, isAbsolute, join, relative, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { call, onLive } from './daemon.mjs';
6
+
7
+ const PORT = Number(process.env.BACKEND_PORT) || 8787;
8
+ const HOST = process.env.BACKEND_HOST || '127.0.0.1';
9
+ const GIT_SHA = process.env.APP_GIT_SHA || 'dev';
10
+ const ALLOWED_ORIGIN = process.env.ALLOWED_ORIGIN || '';
11
+ const WEB_DIST = process.env.SERVE_WEB_DIST === '1' ? resolve(fileURLToPath(new URL('../../web/dist', import.meta.url))) : null;
12
+ const MAX_BODY = 1_000_000;
13
+
14
+ const LOCAL_HOST = /^(localhost|127\.0\.0\.1|\[::1\]|gateway)(:\d+)?$/;
15
+
16
+ class HttpError extends Error {
17
+ constructor(status, message) {
18
+ super(message);
19
+ this.status = status;
20
+ }
21
+ }
22
+
23
+ const json = (res, status, body) => {
24
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' });
25
+ res.end(JSON.stringify(body));
26
+ };
27
+
28
+ async function readBody(req) {
29
+ let size = 0;
30
+ const chunks = [];
31
+ for await (const c of req) {
32
+ size += c.length;
33
+ if (size > MAX_BODY) throw new HttpError(413, 'request body too large');
34
+ chunks.push(c);
35
+ }
36
+ if (!chunks.length) return {};
37
+ let text;
38
+ try {
39
+ text = new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks));
40
+ } catch {
41
+ throw new HttpError(400, 'body must be UTF-8 text');
42
+ }
43
+ try {
44
+ return JSON.parse(text);
45
+ } catch {
46
+ throw new HttpError(400, 'body must be JSON');
47
+ }
48
+ }
49
+
50
+ function guard(req, res) {
51
+ if (!LOCAL_HOST.test(req.headers.host ?? '')) throw new HttpError(403, 'host not allowed');
52
+ const origin = req.headers.origin;
53
+ if (origin && ALLOWED_ORIGIN && origin === ALLOWED_ORIGIN) {
54
+ res.setHeader('access-control-allow-origin', ALLOWED_ORIGIN);
55
+ res.setHeader('access-control-allow-methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
56
+ res.setHeader('access-control-allow-headers', 'content-type');
57
+ res.setHeader('vary', 'Origin');
58
+ return;
59
+ }
60
+ if (origin && req.method !== 'GET' && req.method !== 'HEAD') {
61
+ let o;
62
+ try {
63
+ o = new URL(origin);
64
+ } catch {
65
+ throw new HttpError(403, 'bad origin');
66
+ }
67
+ if (!LOCAL_HOST.test(o.host)) throw new HttpError(403, 'origin not allowed');
68
+ }
69
+ }
70
+
71
+ const num = (v) => (v == null || v === '' ? undefined : Number(v));
72
+
73
+ const routes = [
74
+ ['GET', '/api/health', async () => ({ ...(await call('health')), ok: true, gitSha: GIT_SHA })],
75
+ ['GET', '/api/metrics', ({ query }) => call('metrics', { windowSec: num(query.windowSec) })],
76
+ ['GET', '/api/receipts', ({ query }) => call('receipts', { limit: num(query.limit), workspace: query.workspace || undefined })],
77
+ ['GET', '/api/audits', ({ query }) => call('audits', { limit: num(query.limit), workspace: query.workspace || undefined })],
78
+ ['GET', '/api/models', ({ query }) => call('cli.models', { type: query.type, refresh: query.refresh === '1' })],
79
+ [
80
+ 'GET',
81
+ '/api/effort',
82
+ ({ query }) =>
83
+ call('cli.effort', {
84
+ type: query.type,
85
+ model: query.model || undefined,
86
+ refresh: query.refresh === '1',
87
+ provider: query.provider ? { id: query.provider, model: query.providerModel || '' } : undefined,
88
+ }),
89
+ ],
90
+
91
+ ['GET', '/api/threads', ({ query }) => call('thread.list', { cwd: query.cwd || undefined, onlyBusy: query.onlyBusy === '1' })],
92
+ ['POST', '/api/threads', ({ body }) => call('thread.resolve', body)],
93
+ ['GET', '/api/threads/:key', ({ params }) => call('thread.get', { thread: params.key })],
94
+ [
95
+ 'PATCH',
96
+ '/api/threads/:key',
97
+ ({ params, body }) =>
98
+ call('thread.update', {
99
+ thread: params.key,
100
+ type: body.type,
101
+ role: body.role,
102
+ model: body.model,
103
+ effort: body.effort,
104
+ provider: body.provider,
105
+ }),
106
+ ],
107
+ ['DELETE', '/api/threads/:key', ({ params }) => call('thread.remove', { thread: params.key })],
108
+ ['POST', '/api/threads/:key/run', ({ params, body }) => startRun(params.key, body)],
109
+ ['GET', '/api/threads/:key/tail', ({ params, query }) => call('tail', { thread: params.key, mode: query.mode || 'full' })],
110
+ ['POST', '/api/threads/:key/start', ({ params }) => call('thread.start', { thread: params.key })],
111
+ ['POST', '/api/threads/:key/probe', ({ params, body }) => call('thread.probe', { thread: params.key, timeoutMs: num(body?.timeoutMs) })],
112
+ ['POST', '/api/threads/:key/recover', ({ params }) => call('thread.recover', { thread: params.key })],
113
+ ['POST', '/api/threads/:key/cancel', ({ params, body }) => call('thread.cancel', { thread: params.key, jobId: body?.jobId })],
114
+ ['POST', '/api/threads/:key/promote', ({ params, body }) => call('thread.promote', { thread: params.key, jobId: body.jobId })],
115
+ ['POST', '/api/threads/:key/queue/clear', ({ params }) => call('thread.queue.clear', { thread: params.key })],
116
+ ['GET', '/api/threads/:key/sessions', ({ params }) => call('thread.sessions', { thread: params.key })],
117
+ ['POST', '/api/threads/:key/sessions', ({ params, body }) => call('thread.new', { thread: params.key, cwd: body?.cwd, label: body?.label })],
118
+ ['POST', '/api/threads/:key/use', ({ params, body }) => call('thread.use', { thread: params.key, sessionId: body.sessionId })],
119
+ ['POST', '/api/threads/:key/rename', ({ params, body }) => call('thread.renameSession', { thread: params.key, sessionId: body.sessionId, label: body.label })],
120
+ ['DELETE', '/api/threads/:key/sessions/:sid', ({ params }) => call('thread.deleteSession', { thread: params.key, sessionId: params.sid })],
121
+ [
122
+ 'GET',
123
+ '/api/threads/:key/sessions/:sid/transcript',
124
+ ({ params, query }) =>
125
+ call('thread.transcript', {
126
+ thread: params.key,
127
+ sessionId: params.sid,
128
+ afterSeq: num(query.afterSeq),
129
+ limit: num(query.limit),
130
+ tail: query.tail === '1',
131
+ }),
132
+ ],
133
+
134
+ ['GET', '/api/providers', () => call('provider.list')],
135
+ ['POST', '/api/providers', ({ body }) => call('provider.save', body)],
136
+ ['POST', '/api/providers/discover', ({ body }) => call('provider.discover', body)],
137
+ ['DELETE', '/api/providers/:id', ({ params }) => call('provider.remove', { id: params.id })],
138
+ ['POST', '/api/providers/:id/test', ({ params, body }) => call('provider.test', { id: params.id, model: body?.model, types: body?.types })],
139
+
140
+ ['GET', '/api/roles', ({ query }) => call('role.list', { cwd: query.cwd || undefined })],
141
+ ['PUT', '/api/roles/:id', ({ params, body }) => call('role.save', { ...body, id: params.id })],
142
+ ['DELETE', '/api/roles/:id', ({ params }) => call('role.remove', { id: params.id })],
143
+ ];
144
+
145
+ async function startRun(thread, body) {
146
+ if (typeof body.prompt !== 'string' || !body.prompt.trim()) throw new HttpError(400, 'prompt is required');
147
+ return call('run', { thread, prompt: body.prompt, sessionId: body.sessionId, async: true, subscribe: true });
148
+ }
149
+
150
+ const compiled = routes.map(([method, pattern, handler]) => {
151
+ const names = [];
152
+ const re = new RegExp(
153
+ '^' +
154
+ pattern.replace(/:([a-z]+)/g, (_, n) => {
155
+ names.push(n);
156
+ return '([^/]+)';
157
+ }) +
158
+ '$',
159
+ );
160
+ return { method, re, names, handler };
161
+ });
162
+
163
+ function match(method, path) {
164
+ for (const r of compiled) {
165
+ if (r.method !== method) continue;
166
+ const m = r.re.exec(path);
167
+ if (m) return { r, params: Object.fromEntries(r.names.map((n, i) => [n, decodeURIComponent(m[i + 1])])) };
168
+ }
169
+ return null;
170
+ }
171
+
172
+ const sseClients = new Set();
173
+
174
+ function writeSse(res, frame) {
175
+ if (res.destroyed || res.writableEnded) {
176
+ sseClients.delete(res);
177
+ return;
178
+ }
179
+ try {
180
+ res.write(frame);
181
+ } catch {
182
+ sseClients.delete(res);
183
+ }
184
+ }
185
+
186
+ onLive((name, payload) => {
187
+ if (!sseClients.size) return;
188
+ const frame = `event: ${name}\ndata: ${JSON.stringify(payload)}\n\n`;
189
+ for (const res of [...sseClients]) writeSse(res, frame);
190
+ });
191
+
192
+ async function events(req, res) {
193
+ await call('hello');
194
+ res.writeHead(200, {
195
+ 'content-type': 'text/event-stream',
196
+ 'cache-control': 'no-store',
197
+ connection: 'keep-alive',
198
+ });
199
+ res.write('retry: 2000\n\n');
200
+ sseClients.add(res);
201
+ const ping = setInterval(() => writeSse(res, ': ping\n\n'), 20_000);
202
+ req.on('close', () => {
203
+ clearInterval(ping);
204
+ sseClients.delete(res);
205
+ });
206
+ }
207
+
208
+ const MIME = {
209
+ '.html': 'text/html; charset=utf-8',
210
+ '.js': 'application/javascript; charset=utf-8',
211
+ '.css': 'text/css; charset=utf-8',
212
+ '.json': 'application/json; charset=utf-8',
213
+ '.svg': 'image/svg+xml',
214
+ '.png': 'image/png',
215
+ '.ico': 'image/x-icon',
216
+ };
217
+
218
+ function isInsideDist(target) {
219
+ const rel = relative(WEB_DIST, target);
220
+ if (rel.startsWith('..') || isAbsolute(rel)) return false;
221
+ if (!existsSync(target)) return true;
222
+ const realRel = relative(realpathSync(WEB_DIST), realpathSync(target));
223
+ return !realRel.startsWith('..') && !isAbsolute(realRel);
224
+ }
225
+
226
+ function tryServeStatic(pathname, res) {
227
+ if (!WEB_DIST || pathname.startsWith('/api/') || pathname === '/api') return false;
228
+ const rel = pathname === '/' ? 'index.html' : pathname.replace(/^\/+/, '');
229
+ let target = resolve(WEB_DIST, rel);
230
+ if (!isInsideDist(target)) return false;
231
+ if (!existsSync(target) || statSync(target).isDirectory()) target = join(WEB_DIST, 'index.html');
232
+ if (!existsSync(target) || !isInsideDist(target)) return false;
233
+ res.writeHead(200, { 'content-type': MIME[extname(target)] || 'application/octet-stream' });
234
+ res.end(readFileSync(target));
235
+ return true;
236
+ }
237
+
238
+ const server = http.createServer(async (req, res) => {
239
+ try {
240
+ guard(req, res);
241
+ if (req.method === 'OPTIONS') {
242
+ res.writeHead(204);
243
+ return res.end();
244
+ }
245
+ const url = new URL(req.url, 'http://local');
246
+ if (req.method === 'GET' && url.pathname === '/api/events') return await events(req, res);
247
+ if (req.method === 'GET' && tryServeStatic(url.pathname, res)) return;
248
+
249
+ const hit = match(req.method, url.pathname);
250
+ if (!hit) throw new HttpError(404, `no route for ${req.method} ${url.pathname}`);
251
+ const body = req.method === 'POST' || req.method === 'PUT' || req.method === 'PATCH' ? await readBody(req) : {};
252
+ const result = await hit.r.handler({ params: hit.params, query: Object.fromEntries(url.searchParams), body });
253
+ if (url.pathname === '/api/metrics' && url.searchParams.get('format') === 'prom' && typeof result?.prometheus === 'string') {
254
+ res.writeHead(200, { 'content-type': 'text/plain; version=0.0.4; charset=utf-8', 'cache-control': 'no-store' });
255
+ return res.end(result.prometheus);
256
+ }
257
+ json(res, 200, result ?? {});
258
+ } catch (err) {
259
+ if (res.headersSent) return res.end();
260
+ const isDaemonConnErr =
261
+ err.code === 'ECONNREFUSED' ||
262
+ /agentd (?:closed|disconnected|did not start|not running)|could not connect to agentd|timed out waiting for agentd/i.test(err.message ?? '');
263
+ const status = err.status ?? (isDaemonConnErr ? 502 : 400);
264
+ json(res, status, { error: err.message });
265
+ }
266
+ });
267
+
268
+ server.listen(PORT, HOST, () => {
269
+ process.stderr.write(`[backend] http://${HOST}:${PORT} (agentd is started on first request)\n`);
270
+ });
@@ -1,4 +1,4 @@
1
- import { binaryPath, NO_RULES } from './lib.mjs';
1
+ import { binaryPath, NO_RULES } from '../shared/index.mjs';
2
2
 
3
3
  const BIN = 'agy';
4
4
 
@@ -6,6 +6,7 @@ export default {
6
6
  type: 'agy',
7
7
  label: 'Antigravity',
8
8
  description: 'Google Antigravity CLI; native ACP, uses its own Google login.',
9
+ authHint: '运行 "agy" 或在 Antigravity 客户端中完成官方登录(暂不支持第三方中转渠道)',
9
10
 
10
11
  packages: [],
11
12
  binaries: [{ name: BIN, version: '1.5.9' }],
@@ -1,7 +1,7 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  import { homedir } from 'node:os';
3
3
  import { join } from 'node:path';
4
- import { exe, NO_RULES, packageDir } from './lib.mjs';
4
+ import { exe, NO_RULES, packageDir } from '../shared/index.mjs';
5
5
 
6
6
  const ADAPTER = '@agentclientprotocol/claude-agent-acp';
7
7
  const CLI = '@anthropic-ai/claude-code';
@@ -16,10 +16,30 @@ function settingsEnv() {
16
16
  }
17
17
  }
18
18
 
19
+ function readEndpointInfo() {
20
+ const env = settingsEnv();
21
+ const baseUrl = String(env.ANTHROPIC_BASE_URL ?? '').trim() || null;
22
+ const models = {};
23
+ const map = [
24
+ ['default', env.ANTHROPIC_MODEL],
25
+ ['opus', env.ANTHROPIC_DEFAULT_OPUS_MODEL],
26
+ ['sonnet', env.ANTHROPIC_DEFAULT_SONNET_MODEL],
27
+ ['haiku', env.ANTHROPIC_DEFAULT_HAIKU_MODEL],
28
+ ];
29
+ for (const [alias, target] of map) {
30
+ const clean = String(target ?? '').trim();
31
+ if (clean) models[alias] = clean;
32
+ }
33
+ const hasModels = Object.keys(models).length > 0;
34
+ if (!baseUrl && !hasModels) return { mode: 'official' };
35
+ return { mode: 'custom', ...(baseUrl ? { baseUrl } : {}), ...(hasModels ? { models } : {}) };
36
+ }
37
+
19
38
  export default {
20
39
  type: 'claude',
21
40
  label: 'Claude Code',
22
41
  description: 'Claude Code through the ACP adapter. Uses the endpoint and login configured in ~/.claude/settings.json.',
42
+ authHint: '运行 "claude" 完成官方登录,或运行 "hbus ui" 配置第三方兼容渠道',
23
43
 
24
44
  packages: [
25
45
  { name: ADAPTER, version: '0.108.0' },
@@ -42,6 +62,8 @@ export default {
42
62
 
43
63
  envFn: settingsEnv,
44
64
 
65
+ endpointInfo: readEndpointInfo,
66
+
45
67
  provider: {
46
68
  protocol: 'anthropic',
47
69
  scope: 'process',
@@ -1,7 +1,7 @@
1
1
  import { existsSync } from 'node:fs';
2
2
  import { homedir } from 'node:os';
3
3
  import { join } from 'node:path';
4
- import { NO_RULES, packageDir } from './lib.mjs';
4
+ import { NO_RULES, packageDir } from '../shared/index.mjs';
5
5
 
6
6
  const PKG = '@agentclientprotocol/codex-acp';
7
7
  const FULL_ACCESS_MODE = 'agent-full-access';
@@ -48,6 +48,7 @@ export default {
48
48
  type: 'codex',
49
49
  label: 'Codex',
50
50
  description: 'OpenAI Codex through the ACP adapter. Uses the ChatGPT login of the Codex app.',
51
+ authHint: '运行 "codex login" 完成登录,或运行 "hbus ui" 配置第三方兼容渠道',
51
52
 
52
53
  packages: [{ name: PKG, version: '2.12.1' }],
53
54
  verified: { on: '2026-12-01', note: 'rules, MCP servers, /compact, CODEX_CONFIG and full-access headless mode checked on 2.12.1 (codex 0.172.0)' },
@@ -1,5 +1,5 @@
1
- import { dshFolderName, dshSessions } from './dsh-sessions.mjs';
2
- import { RULES_IN_PROMPT, packageDir } from './lib.mjs';
1
+ import { dshFolderName, dshSessions } from './sessions.mjs';
2
+ import { RULES_IN_PROMPT, packageDir } from '../shared/index.mjs';
3
3
 
4
4
  const PKG = '@deepseek-ai/dsh';
5
5
 
@@ -9,6 +9,7 @@ export default {
9
9
  type: 'dsh',
10
10
  label: 'DeepSeek Harness',
11
11
  description: 'DeepSeek Harness agent. Fast startup and short answers.',
12
+ authHint: '运行 "dsh" 完成登录授权,或运行 "hbus ui" 配置第三方兼容渠道',
12
13
 
13
14
  packages: [{ name: PKG, version: '0.2.2-rc.1' }],
14
15
  verified: { on: '2026-11-18', note: 'rules, MCP servers and session.v4.jsonl.zstd on-disk format checked on 0.2.2-rc.1 (earlier 0.1.5-rc.2)' },