@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,69 +1,76 @@
1
- import { AGENTS } from '../../core/env/index.mjs';
2
- import { getAgent, pool, probeEffort, probeModels } from '../../core/pool/index.mjs';
3
- import { getRole, listRoles, removeRole, saveRole } from '../../core/prompts/index.mjs';
4
- import { computeMetrics, readAudits, readDaemonLog, readReceipts } from '../../core/records/index.mjs';
5
- import { EPOCH, RING_MAX, eventsSince, subscribe, unsubscribe } from '../events.mjs';
6
-
7
- export function systemOps(ctx) {
8
- return {
9
- hello: () => ({
10
- protocol: ctx.protocol,
11
- epoch: EPOCH,
12
- pid: process.pid,
13
- startedAt: ctx.startedAt,
14
- threads: [...pool.keys()],
15
- types: Object.keys(AGENTS),
16
- }),
17
-
18
- 'events.since': ({ afterId, limit } = {}) => eventsSince(afterId, Math.min(Number(limit) || 500, RING_MAX)),
19
-
20
- receipts: ({ limit, workspace } = {}) => ({ receipts: readReceipts(Math.min(Number(limit) || 50, 500), workspace ?? null) }),
21
-
22
- audits: ({ limit, workspace } = {}) => ({ audits: readAudits(Math.min(Number(limit) || 50, 500), workspace ?? null) }),
23
-
24
- metrics: ({ windowSec } = {}) =>
25
- computeMetrics({
26
- windowSec,
27
- queues: [...pool.values()].map((a) => ({ agent: a.name, inflight: a.inflight ?? 0, waiting: a.waitingJobs?.().length ?? 0 })),
28
- }),
29
-
30
- health: () => ({
31
- threads: [...pool.keys()].map((name) => getAgent(name).status()),
32
- }),
33
-
34
- logs: ({ lines = 80 } = {}) => readDaemonLog(lines),
35
-
36
- 'cli.models': ({ type, refresh = false }) => probeModels(type, { refresh }),
37
-
38
- 'cli.effort': ({ type, model, refresh = false, provider } = {}) => probeEffort(type, model, { refresh, provider }),
39
-
40
- 'role.list': ({ cwd = null } = {}) => ({ roles: listRoles({ cwd }) }),
41
-
42
- 'role.get': ({ id, cwd = null }) => {
43
- const role = getRole(id, { cwd });
44
- if (!role) throw new Error(`unknown role "${id}"`);
45
- return role;
46
- },
47
-
48
- 'role.save': (spec) => saveRole(spec),
49
-
50
- 'role.remove': ({ id }) => removeRole(id),
51
-
52
- subscribe: ({ jobId }, sock) => {
53
- if (jobId) subscribe(sock, jobId);
54
- return { subscribed: jobId ?? null };
55
- },
56
-
57
- unsubscribe: ({ jobId }, sock) => {
58
- if (jobId) unsubscribe(sock, jobId);
59
- return { subscribed: null };
60
- },
61
-
62
- 'daemon.shutdown': () => {
63
- const busy = [...pool.values()].filter((a) => a.busy || a.inflight > 0).map((a) => a.name);
64
- if (busy.length) throw new Error(`not stopping: still working on ${busy.join(', ')}`);
65
- setTimeout(() => void ctx.shutdown(0), 200);
66
- return { stopping: true, pid: process.pid };
67
- },
68
- };
69
- }
1
+ import { AGENTS, cliAvailability, enrichAuthError } from '../../core/env/index.mjs';
2
+ import { getAgent, pool, probeEffort, probeModels } from '../../core/pool/index.mjs';
3
+ import { getRole, listRoles, removeRole, saveRole } from '../../core/prompts/index.mjs';
4
+ import { computeMetrics, readAudits, readDaemonLog, readReceipts } from '../../core/records/index.mjs';
5
+ import { EPOCH, RING_MAX, eventsSince, subscribe, unsubscribe } from '../events.mjs';
6
+
7
+ export function systemOps(ctx) {
8
+ return {
9
+ hello: () => ({
10
+ protocol: ctx.protocol,
11
+ epoch: EPOCH,
12
+ pid: process.pid,
13
+ startedAt: ctx.startedAt,
14
+ threads: [...pool.keys()],
15
+ types: Object.keys(AGENTS),
16
+ clis: cliAvailability(),
17
+ }),
18
+
19
+ 'events.since': ({ afterId, limit } = {}) => eventsSince(afterId, Math.min(Number(limit) || 500, RING_MAX)),
20
+
21
+ receipts: ({ limit, workspace } = {}) => ({ receipts: readReceipts(Math.min(Number(limit) || 50, 500), workspace ?? null) }),
22
+
23
+ audits: ({ limit, workspace } = {}) => ({ audits: readAudits(Math.min(Number(limit) || 50, 500), workspace ?? null) }),
24
+
25
+ metrics: ({ windowSec } = {}) =>
26
+ computeMetrics({
27
+ windowSec,
28
+ queues: [...pool.values()].map((a) => ({ agent: a.name, inflight: a.inflight ?? 0, waiting: a.waitingJobs?.().length ?? 0 })),
29
+ }),
30
+
31
+ health: () => ({
32
+ threads: [...pool.keys()].map((name) => getAgent(name).status()),
33
+ }),
34
+
35
+ logs: ({ lines = 80 } = {}) => readDaemonLog(lines),
36
+
37
+ 'cli.models': ({ type, refresh = false }) =>
38
+ probeModels(type, { refresh }).catch((err) => {
39
+ throw enrichAuthError(type, err);
40
+ }),
41
+
42
+ 'cli.effort': ({ type, model, refresh = false, provider } = {}) =>
43
+ probeEffort(type, model, { refresh, provider }).catch((err) => {
44
+ throw enrichAuthError(type, err);
45
+ }),
46
+
47
+ 'role.list': ({ cwd = null } = {}) => ({ roles: listRoles({ cwd }) }),
48
+
49
+ 'role.get': ({ id, cwd = null }) => {
50
+ const role = getRole(id, { cwd });
51
+ if (!role) throw new Error(`unknown role "${id}"`);
52
+ return role;
53
+ },
54
+
55
+ 'role.save': (spec) => saveRole(spec),
56
+
57
+ 'role.remove': ({ id }) => removeRole(id),
58
+
59
+ subscribe: ({ jobId }, sock) => {
60
+ if (jobId) subscribe(sock, jobId);
61
+ return { subscribed: jobId ?? null };
62
+ },
63
+
64
+ unsubscribe: ({ jobId }, sock) => {
65
+ if (jobId) unsubscribe(sock, jobId);
66
+ return { subscribed: null };
67
+ },
68
+
69
+ 'daemon.shutdown': () => {
70
+ const busy = [...pool.values()].filter((a) => a.busy || a.inflight > 0).map((a) => a.name);
71
+ if (busy.length) throw new Error(`not stopping: still working on ${busy.join(', ')}`);
72
+ setTimeout(() => void ctx.shutdown(0), 200);
73
+ return { stopping: true, pid: process.pid };
74
+ },
75
+ };
76
+ }
@@ -1,153 +1,156 @@
1
- import { AGENTS } from '../../core/env/index.mjs';
2
- import { aliveCount, getAgent, maxProcesses, pool } from '../../core/pool/index.mjs';
3
- import { readTranscript } from '../../core/records/index.mjs';
4
- import * as threads from '../../core/threads/index.mjs';
5
- import { allocEvent, publish } from '../events.mjs';
6
-
7
- const keyArg = (args) => args?.thread ?? args?.agent;
8
-
9
- function resolveKey(args) {
10
- const direct = keyArg(args);
11
- if (direct) return direct;
12
- if (args?.cwd && args?.topic) {
13
- const found = threads.findThread({ cwd: args.cwd, topic: args.topic });
14
- if (found) return found.key;
15
- }
16
- throw new Error('thread key (or cwd + topic) is required');
17
- }
18
-
19
- export function threadOps(ctx) {
20
- return {
21
- 'thread.list': ({ cwd, onlyBusy } = {}) => {
22
- const workspaces = threads.listWorkspaces({ cwd });
23
- const flat = workspaces.flatMap((w) => w.threads);
24
- const filtered = onlyBusy ? flat.filter((t) => t.busy || t.waiting > 0) : flat;
25
- return {
26
- workspaces: onlyBusy ? workspaces.map((w) => ({ ...w, threads: w.threads.filter((t) => t.busy || t.waiting > 0) })).filter((w) => w.threads.length > 0) : workspaces,
27
- threads: filtered,
28
- types: Object.keys(AGENTS),
29
- limits: {
30
- alive: aliveCount(),
31
- maxProcesses: maxProcesses(),
32
- idleMinutes: Math.round((ctx?.idleInstanceMs ?? 900_000) / 60_000),
33
- },
34
- };
35
- },
36
-
37
- 'thread.get': (args) => threads.getThreadView(resolveKey(args)),
38
-
39
- 'thread.resolve': async (args) => {
40
- const isManaged = Boolean(args?.callerAgent) || args?.caller === 'managed';
41
- const res = await threads.resolveThread({ ...args, allowMutateExisting: !isManaged });
42
- publish(allocEvent('threads.changed', { workspaceId: res.thread.workspaceId, thread: res.key }));
43
- return res;
44
- },
45
-
46
- 'thread.update': async (args) => {
47
- const key = resolveKey(args);
48
- const updated = await threads.updateThread(key, args);
49
- publish(allocEvent('threads.changed', { workspaceId: updated.workspaceId, thread: key }));
50
- return updated;
51
- },
52
-
53
- 'thread.remove': async (args) => {
54
- const key = resolveKey(args);
55
- const res = await threads.removeThread(key);
56
- publish(allocEvent('threads.changed', { thread: key, removed: true }));
57
- return res;
58
- },
59
-
60
- 'thread.start': async (args) => {
61
- const a = getAgent(resolveKey(args));
62
- await a.serialized(() => a.ensureReady());
63
- return a.status();
64
- },
65
-
66
- 'thread.probe': (args) => getAgent(resolveKey(args)).probe({ timeoutMs: args?.timeoutMs ?? 45_000 }),
67
-
68
- 'thread.recover': (args) => {
69
- const a = getAgent(resolveKey(args));
70
- a.recover();
71
- publish(allocEvent('agent.recovered', { agent: a.name, thread: a.name }));
72
- return a.status();
73
- },
74
-
75
- 'thread.renameSession': (args) => getAgent(resolveKey(args)).renameSession(args.sessionId, args.label),
76
-
77
- 'thread.sessions': async (args) => getAgent(resolveKey(args)).listSessions(),
78
-
79
- 'thread.use': async (args) => {
80
- const a = getAgent(resolveKey(args));
81
- if (!a.inUse) return a.useSession(args.sessionId, args.cwd);
82
- a.useSession(args.sessionId, args.cwd).catch((err) => process.stderr.write(`[${a.name}] queued switch to ${args.sessionId} failed: ${err.message}\n`));
83
- return { thread: a.name, sessionId: args.sessionId, queued: true };
84
- },
85
-
86
- 'thread.new': async (args) => {
87
- const a = getAgent(resolveKey(args));
88
- const make = async () => {
89
- const sessionId = await a.newSession(args.cwd);
90
- if (args.label) a.renameSession(sessionId, args.label);
91
- return sessionId;
92
- };
93
- if (!a.inUse) return { thread: a.name, sessionId: await make(), cwd: a.cwd, label: args.label ?? null };
94
- make().catch((err) => process.stderr.write(`[${a.name}] queued new session failed: ${err.message}\n`));
95
- return { thread: a.name, queued: true, label: args.label ?? null };
96
- },
97
-
98
- 'thread.deleteSession': (args) => getAgent(resolveKey(args)).deleteSession(args.sessionId),
99
-
100
- 'thread.models': async (args) => getAgent(resolveKey(args)).describeModels(args.sessionId),
101
-
102
- 'thread.setModel': async (args) => {
103
- const a = getAgent(resolveKey(args));
104
- return a.setConfigOption(args.configId || 'model', args.value, args.sessionId);
105
- },
106
-
107
- 'thread.transcript': (args) => {
108
- const a = getAgent(resolveKey(args));
109
- const sid = args.sessionId || a.sessionId || a.preferSession;
110
- if (!sid) throw new Error(`${a.name} has no active session; pass sessionId`);
111
- return readTranscript(a.name, sid, { afterSeq: args.afterSeq, limit: args.limit, tail: args.tail });
112
- },
113
-
114
- 'thread.cancel': (args) => {
115
- if (!keyArg(args) && args?.jobId) {
116
- const jid = String(args.jobId);
117
- const owner = [...pool.values()].find(
118
- (a) => a.run?.jobId === jid || a.waitingJobs().some((w) => w.jobId === jid) || a.jobs.has(jid),
119
- );
120
- if (!owner) throw new Error(`unknown job "${jid}"`);
121
- if (args?.callerAgent) {
122
- const callerWs = threads.findThreadByKey(args.callerAgent)?.ws;
123
- const ownerWs = threads.findThreadByKey(owner.name)?.ws;
124
- if (!callerWs || !ownerWs || callerWs.id !== ownerWs.id) {
125
- throw new Error(`managed child agent "agent:${args.callerAgent}" cannot cancel job outside its workspace`);
126
- }
127
- }
128
- return owner.cancel(jid);
129
- }
130
- const key = resolveKey(args);
131
- return getAgent(key).cancel(args.jobId);
132
- },
133
-
134
- 'thread.queue': (args) => {
135
- const a = getAgent(resolveKey(args));
136
- return { thread: a.name, running: a.run?.jobId ?? null, waiting: a.waitingJobs() };
137
- },
138
-
139
- 'thread.queue.clear': (args) => {
140
- const a = getAgent(resolveKey(args));
141
- const removed = a.clearQueue();
142
- if (removed?.cleared > 0) publish(allocEvent('queue.changed', { thread: a.name, agent: a.name, waiting: a.waitingJobs() }));
143
- return { thread: a.name, removed };
144
- },
145
-
146
- 'thread.promote': (args) => {
147
- const a = getAgent(resolveKey(args));
148
- const ok = a.promote(args.jobId);
149
- if (ok?.promoted) publish(allocEvent('queue.changed', { thread: a.name, agent: a.name, waiting: a.waitingJobs() }));
150
- return { thread: a.name, jobId: args.jobId, moved: Boolean(ok?.promoted), detail: ok, waiting: a.waitingJobs() };
151
- },
152
- };
153
- }
1
+ import { AGENTS, cliAvailability } from '../../core/env/index.mjs';
2
+ import { aliveCount, getAgent, maxProcesses, pool } from '../../core/pool/index.mjs';
3
+ import { readTranscript } from '../../core/records/index.mjs';
4
+ import * as threads from '../../core/threads/index.mjs';
5
+ import { allocEvent, publish } from '../events.mjs';
6
+
7
+ const keyArg = (args) => args?.thread ?? args?.agent;
8
+
9
+ function resolveKey(args) {
10
+ const direct = keyArg(args);
11
+ if (direct) return direct;
12
+ if (args?.cwd && args?.topic) {
13
+ const found = threads.findThread({ cwd: args.cwd, topic: args.topic });
14
+ if (found) return found.key;
15
+ }
16
+ throw new Error('thread key (or cwd + topic) is required');
17
+ }
18
+
19
+ export function threadOps(ctx) {
20
+ return {
21
+ 'thread.list': ({ cwd, onlyBusy } = {}) => {
22
+ const workspaces = threads.listWorkspaces({ cwd });
23
+ const flat = workspaces.flatMap((w) => w.threads);
24
+ const filtered = onlyBusy ? flat.filter((t) => t.busy || t.waiting > 0) : flat;
25
+ return {
26
+ workspaces: onlyBusy ? workspaces.map((w) => ({ ...w, threads: w.threads.filter((t) => t.busy || t.waiting > 0) })).filter((w) => w.threads.length > 0) : workspaces,
27
+ threads: filtered,
28
+ types: Object.keys(AGENTS),
29
+ clis: cliAvailability(),
30
+ limits: {
31
+ alive: aliveCount(),
32
+ maxProcesses: maxProcesses(),
33
+ idleMinutes: Math.round((ctx?.idleInstanceMs ?? 900_000) / 60_000),
34
+ },
35
+ };
36
+ },
37
+
38
+ 'thread.get': (args) => threads.getThreadView(resolveKey(args)),
39
+
40
+ 'thread.resolve': async (args) => {
41
+ const isManaged = Boolean(args?.callerAgent) || args?.caller === 'managed';
42
+ const res = await threads.resolveThread({ ...args, allowMutateExisting: !isManaged });
43
+ publish(allocEvent('threads.changed', { workspaceId: res.thread.workspaceId, thread: res.key }));
44
+ return res;
45
+ },
46
+
47
+ 'thread.update': async (args) => {
48
+ const key = resolveKey(args);
49
+ const updated = await threads.updateThread(key, args);
50
+ publish(allocEvent('threads.changed', { workspaceId: updated.workspaceId, thread: key }));
51
+ return updated;
52
+ },
53
+
54
+ 'thread.remove': async (args) => {
55
+ const key = resolveKey(args);
56
+ const res = await threads.removeThread(key);
57
+ publish(allocEvent('threads.changed', { thread: key, removed: true }));
58
+ return res;
59
+ },
60
+
61
+ 'thread.start': async (args) => {
62
+ const a = getAgent(resolveKey(args));
63
+ await a.serialized(() => a.ensureReady());
64
+ return a.status();
65
+ },
66
+
67
+ 'thread.probe': (args) => getAgent(resolveKey(args)).probe({ timeoutMs: args?.timeoutMs ?? 45_000 }),
68
+
69
+ 'thread.recover': (args) => {
70
+ const a = getAgent(resolveKey(args));
71
+ a.recover();
72
+ publish(allocEvent('agent.recovered', { agent: a.name, thread: a.name }));
73
+ return a.status();
74
+ },
75
+
76
+ 'thread.renameSession': (args) => getAgent(resolveKey(args)).renameSession(args.sessionId, args.label),
77
+
78
+ 'thread.sessions': async (args) => getAgent(resolveKey(args)).listSessions(),
79
+
80
+ 'thread.use': async (args) => {
81
+ const a = getAgent(resolveKey(args));
82
+ if (!a.inUse) return a.useSession(args.sessionId, args.cwd);
83
+ a.useSession(args.sessionId, args.cwd).catch((err) => process.stderr.write(`[${a.name}] queued switch to ${args.sessionId} failed: ${err.message}\n`));
84
+ return { thread: a.name, sessionId: args.sessionId, queued: true };
85
+ },
86
+
87
+ 'thread.new': async (args) => {
88
+ const a = getAgent(resolveKey(args));
89
+ const make = async () => {
90
+ const sessionId = await a.newSession(args.cwd);
91
+ if (args.label) a.renameSession(sessionId, args.label);
92
+ const found = threads.findThreadByKey(a.name);
93
+ publish(allocEvent('threads.changed', { workspaceId: found?.ws?.id ?? a.project, thread: a.name, sessionId }));
94
+ return sessionId;
95
+ };
96
+ if (!a.inUse) return { thread: a.name, sessionId: await make(), cwd: a.cwd, label: args.label ?? null };
97
+ make().catch((err) => process.stderr.write(`[${a.name}] queued new session failed: ${err.message}\n`));
98
+ return { thread: a.name, queued: true, label: args.label ?? null };
99
+ },
100
+
101
+ 'thread.deleteSession': (args) => getAgent(resolveKey(args)).deleteSession(args.sessionId),
102
+
103
+ 'thread.models': async (args) => getAgent(resolveKey(args)).describeModels(args.sessionId),
104
+
105
+ 'thread.setModel': async (args) => {
106
+ const a = getAgent(resolveKey(args));
107
+ return a.setConfigOption(args.configId || 'model', args.value, args.sessionId);
108
+ },
109
+
110
+ 'thread.transcript': (args) => {
111
+ const a = getAgent(resolveKey(args));
112
+ const sid = args.sessionId || a.sessionId || a.preferSession;
113
+ if (!sid) throw new Error(`${a.name} has no active session; pass sessionId`);
114
+ return readTranscript(a.name, sid, { afterSeq: args.afterSeq, limit: args.limit, tail: args.tail });
115
+ },
116
+
117
+ 'thread.cancel': (args) => {
118
+ if (!keyArg(args) && args?.jobId) {
119
+ const jid = String(args.jobId);
120
+ const owner = [...pool.values()].find(
121
+ (a) => a.run?.jobId === jid || a.waitingJobs().some((w) => w.jobId === jid) || a.jobs.has(jid),
122
+ );
123
+ if (!owner) throw new Error(`unknown job "${jid}"`);
124
+ if (args?.callerAgent) {
125
+ const callerWs = threads.findThreadByKey(args.callerAgent)?.ws;
126
+ const ownerWs = threads.findThreadByKey(owner.name)?.ws;
127
+ if (!callerWs || !ownerWs || callerWs.id !== ownerWs.id) {
128
+ throw new Error(`managed child agent "agent:${args.callerAgent}" cannot cancel job outside its workspace`);
129
+ }
130
+ }
131
+ return owner.cancel(jid);
132
+ }
133
+ const key = resolveKey(args);
134
+ return getAgent(key).cancel(args.jobId);
135
+ },
136
+
137
+ 'thread.queue': (args) => {
138
+ const a = getAgent(resolveKey(args));
139
+ return { thread: a.name, running: a.run?.jobId ?? null, waiting: a.waitingJobs() };
140
+ },
141
+
142
+ 'thread.queue.clear': (args) => {
143
+ const a = getAgent(resolveKey(args));
144
+ const removed = a.clearQueue();
145
+ if (removed?.cleared > 0) publish(allocEvent('queue.changed', { thread: a.name, agent: a.name, waiting: a.waitingJobs() }));
146
+ return { thread: a.name, removed };
147
+ },
148
+
149
+ 'thread.promote': (args) => {
150
+ const a = getAgent(resolveKey(args));
151
+ const ok = a.promote(args.jobId);
152
+ if (ok?.promoted) publish(allocEvent('queue.changed', { thread: a.name, agent: a.name, waiting: a.waitingJobs() }));
153
+ return { thread: a.name, jobId: args.jobId, moved: Boolean(ok?.promoted), detail: ok, waiting: a.waitingJobs() };
154
+ },
155
+ };
156
+ }