@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,476 +1,498 @@
1
- import { randomBytes } from 'node:crypto';
2
- import { resolve } from 'node:path';
3
- import { AGENTS } from '../env/index.mjs';
4
- import { buildInstance, forgetProject as forgetPoolWorkspace, listInstances, pool } from '../pool/index.mjs';
5
- import { executorRulesFor, getRole } from '../prompts/index.mjs';
6
- import { cleanInstanceProvider, listProviders } from '../providers/index.mjs';
7
- import { forgetProject as forgetRecordsWorkspace, withInterrupted } from '../records/index.mjs';
8
- import { canonicalDir, relativeInside, resolveInside, threadIdForTopic, workspaceIdOf } from './paths.mjs';
9
- import {
10
- EPHEMERAL_KEEP_MS,
11
- SEP,
12
- allWorkspaces,
13
- checkId,
14
- clearMemoryStore,
15
- deleteWorkspace,
16
- findWorkspaceByRoot,
17
- getWorkspace,
18
- keyOf,
19
- loadWorkspacesFromDisk,
20
- saveWorkspace,
21
- upsertWorkspace,
22
- } from './store.mjs';
23
-
24
- const DEFAULT_CLI_ORDER = ['claude', 'codex', 'dsh', 'kimi', 'opencode', 'mcode', 'pi', 'agy'];
25
-
26
- let threadHooks = null;
27
- export function setThreadHooks(hooks) {
28
- threadHooks = hooks ?? null;
29
- for (const agent of pool.values()) applyHooks(agent);
30
- }
31
-
32
- function applyHooks(agent) {
33
- if (!threadHooks || !agent) return;
34
- if (typeof threadHooks.onProgress === 'function') agent.setProgressSink?.((jobId, payload) => threadHooks.onProgress(agent, jobId, payload));
35
- if (typeof threadHooks.onRunStart === 'function') agent.onRunStart = (info) => threadHooks.onRunStart(agent, info);
36
- if (typeof threadHooks.onExit === 'function') agent.onExit = (info) => threadHooks.onExit(agent, info);
37
- if (typeof threadHooks.onForcedStop === 'function') agent.onForcedStop = (info) => threadHooks.onForcedStop(agent, info);
38
- if (typeof threadHooks.onCompact === 'function') agent.onCompact = (info) => threadHooks.onCompact(agent, info);
39
- }
40
-
41
- function persistWorkspace(ws) {
42
- const busyIds = new Set();
43
- for (const t of ws.threads) {
44
- const a = pool.get(keyOf(ws.id, t.id));
45
- if (a && (a.busy || a.inUse)) busyIds.add(t.id);
46
- }
47
- const { dropped } = saveWorkspace(ws, { busyIds });
48
- for (const t of dropped) {
49
- const k = keyOf(ws.id, t.id);
50
- const a = pool.get(k);
51
- if (a) {
52
- pool.delete(k);
53
- a.shutdown({ clearQueue: false }).catch(() => {});
54
- }
55
- }
56
- }
57
-
58
- let resolveChain = Promise.resolve();
59
- function withResolveLock(fn) {
60
- const next = resolveChain.then(fn, fn);
61
- resolveChain = next.catch(() => {});
62
- return next;
63
- }
64
-
65
- function cleanEffort(v) {
66
- const s = String(v ?? '').trim();
67
- return s && s !== 'default' ? s.slice(0, 40) : null;
68
- }
69
-
70
- function inferProviderForModel(cli, model) {
71
- if (!model) return null;
72
- for (const p of listProviders()) {
73
- if (!Array.isArray(p.types) || !p.types.includes(cli)) continue;
74
- const models = Array.isArray(p.models) ? p.models : [];
75
- if (models.includes(model)) return { id: p.id, model };
76
- }
77
- return null;
78
- }
79
-
80
- function normalizeProvider(provider, cli, model) {
81
- if (provider === null || provider === '') return null;
82
- if (typeof provider === 'string') {
83
- return cleanInstanceProvider({ id: provider, ...(model ? { model } : {}) }, cli);
84
- }
85
- if (provider && typeof provider === 'object') {
86
- return cleanInstanceProvider(provider, cli);
87
- }
88
- return inferProviderForModel(cli, model);
89
- }
90
-
91
- function pickDefaultCli() {
92
- const avail = Object.keys(AGENTS);
93
- for (const t of DEFAULT_CLI_ORDER) {
94
- if (avail.includes(t)) return t;
95
- }
96
- if (avail.length) return avail[0];
97
- throw new Error('no native CLI driver available');
98
- }
99
-
100
- function registerThread(ws, th) {
101
- const key = keyOf(ws.id, th.id);
102
- if (pool.has(key)) return pool.get(key);
103
- const cwd = resolve(ws.root, th.dir || '.');
104
- const agent = buildInstance({
105
- id: key,
106
- type: th.type,
107
- cwd,
108
- project: ws.id,
109
- shortId: th.id,
110
- role: th.role ?? null,
111
- model: th.model ?? null,
112
- effort: th.effort ?? null,
113
- sessionId: th.sessionId ?? null,
114
- provider: () => th.provider ?? null,
115
- systemPrompt: () => executorRulesFor(th.role, { cwd }) || null,
116
- ephemeral: Boolean(th.ephemeral),
117
- onSession: (sid) => {
118
- th.sessionId = sid;
119
- th.lastActiveAt = new Date().toISOString();
120
- ws.updatedAt = th.lastActiveAt;
121
- persistWorkspace(ws);
122
- },
123
- });
124
- applyHooks(agent);
125
- pool.set(key, agent);
126
- return agent;
127
- }
128
-
129
- export function initThreads() {
130
- const loaded = loadWorkspacesFromDisk();
131
- for (const ws of loaded) {
132
- for (const th of ws.threads) {
133
- if (!AGENTS[th.type]) continue;
134
- registerThread(ws, th);
135
- }
136
- }
137
- return loaded;
138
- }
139
-
140
- export function resetThreadsForTest() {
141
- pool.clear();
142
- clearMemoryStore();
143
- }
144
-
145
- export function findThreadByKey(key) {
146
- const s = String(key ?? '');
147
- const idx = s.indexOf(SEP);
148
- if (idx < 0) return null;
149
- const wsId = s.slice(0, idx);
150
- const thId = s.slice(idx + SEP.length);
151
- const ws = getWorkspace(wsId);
152
- if (!ws) return null;
153
- const th = ws.threads.find((t) => t.id === thId);
154
- if (!th) return null;
155
- return { ws, th, key: keyOf(ws.id, th.id), agent: pool.get(keyOf(ws.id, th.id)) ?? null };
156
- }
157
-
158
- export function findThread({ key, cwd, topic }) {
159
- if (key) return findThreadByKey(key);
160
- if (!cwd) return null;
161
- const root = canonicalDir(cwd);
162
- const ws = findWorkspaceByRoot(root) ?? getWorkspace(workspaceIdOf(root));
163
- if (!ws || !topic) return null;
164
- const trimmed = String(topic).trim();
165
- const th = ws.threads.find((t) => t.topic === trimmed || t.id === trimmed);
166
- if (!th) return null;
167
- const k = keyOf(ws.id, th.id);
168
- return { ws, th, key: k, agent: pool.get(k) ?? null };
169
- }
170
-
171
- function viewThread(ws, th, liveByKey) {
172
- const key = keyOf(ws.id, th.id);
173
- const live = liveByKey.get(key) ?? null;
174
- return {
175
- key,
176
- id: th.id,
177
- workspaceId: ws.id,
178
- workspaceRoot: ws.root,
179
- workspaceLabel: ws.label,
180
- topic: th.topic ?? null,
181
- ephemeral: Boolean(th.ephemeral),
182
- type: th.type,
183
- dir: th.dir || '.',
184
- cwd: resolve(ws.root, th.dir || '.'),
185
- role: th.role ?? null,
186
- model: live?.model ?? th.model ?? null,
187
- preferModel: th.model ?? null,
188
- effort: th.effort ?? null,
189
- provider: th.provider ?? null,
190
- sessionId: live?.sessionId ?? th.sessionId ?? null,
191
- createdAt: th.createdAt,
192
- lastActiveAt: th.lastActiveAt,
193
- alive: live?.alive ?? false,
194
- busy: live?.busy ?? false,
195
- activity: live?.activity ?? null,
196
- waiting: live?.waiting ?? 0,
197
- waitingJobs: live?.waitingJobs ?? [],
198
- unstable: live?.unstable ?? false,
199
- lastError: live?.lastError ?? null,
200
- interrupted: live?.interrupted ?? null,
201
- context: live?.context ?? null,
202
- };
203
- }
204
-
205
- export function listWorkspaces({ cwd = null } = {}) {
206
- const liveRows = withInterrupted(listInstances());
207
- const liveByKey = new Map(liveRows.map((r) => [r.id, r]));
208
- let targetRoot = null;
209
- if (cwd) {
210
- try {
211
- targetRoot = canonicalDir(cwd);
212
- } catch {
213
- targetRoot = resolve(cwd);
214
- }
215
- }
216
- const norm = (p) => (process.platform === 'win32' ? p.toLowerCase() : p);
217
- return allWorkspaces()
218
- .filter((ws) => (!targetRoot ? true : norm(ws.root) === norm(targetRoot)))
219
- .map((ws) => ({
220
- id: ws.id,
221
- root: ws.root,
222
- label: ws.label,
223
- updatedAt: ws.updatedAt,
224
- threads: ws.threads
225
- .map((th) => viewThread(ws, th, liveByKey))
226
- .sort((a, b) => Number(b.busy) - Number(a.busy) || String(b.lastActiveAt ?? '').localeCompare(String(a.lastActiveAt ?? ''))),
227
- }))
228
- .sort((a, b) => String(b.updatedAt ?? '').localeCompare(String(a.updatedAt ?? '')));
229
- }
230
-
231
- export function listThreads({ cwd = null, onlyBusy = false } = {}) {
232
- const all = listWorkspaces({ cwd }).flatMap((w) => w.threads);
233
- return onlyBusy ? all.filter((t) => t.busy || t.waiting > 0) : all;
234
- }
235
-
236
- export function getThreadView(key) {
237
- const found = findThreadByKey(key);
238
- if (!found) throw new Error(`unknown thread "${key}"`);
239
- const liveRows = withInterrupted(listInstances());
240
- const liveByKey = new Map(liveRows.map((r) => [r.id, r]));
241
- return viewThread(found.ws, found.th, liveByKey);
242
- }
243
-
244
- export function resolveThread({ cwd, topic = null, cli = null, role = null, model = null, effort = null, provider = undefined, dir = '.', allowMutateExisting = true } = {}) {
245
- return withResolveLock(async () => {
246
- const root = canonicalDir(cwd);
247
- const relDir = relativeInside(root, dir);
248
- const targetCwd = resolveInside(root, relDir);
249
- const wsId = workspaceIdOf(root);
250
- const ws = findWorkspaceByRoot(root) ?? upsertWorkspace({ id: wsId, root });
251
-
252
- const roleDef = role ? getRole(role, { cwd: targetCwd }) : null;
253
- if (role && !roleDef) throw new Error(`unknown role "${role}"`);
254
-
255
- const cleanTopic = topic !== null && topic !== undefined ? String(topic).trim() : '';
256
- const now = new Date().toISOString();
257
-
258
- if (cleanTopic) {
259
- const existing = ws.threads.find((t) => t.topic === cleanTopic || t.id === cleanTopic);
260
- if (existing) {
261
- const key = keyOf(ws.id, existing.id);
262
- const requestedCli = cli || null;
263
- const wantsMutation =
264
- (requestedCli && requestedCli !== existing.type) ||
265
- (role !== null && role !== undefined && role !== existing.role) ||
266
- (model !== null && model !== undefined && model !== existing.model) ||
267
- (effort !== null && effort !== undefined && cleanEffort(effort) !== existing.effort) ||
268
- provider !== undefined;
269
- if (wantsMutation && !allowMutateExisting) {
270
- throw new Error(`managed child agent is not allowed to mutate existing thread "${cleanTopic}"`);
271
- }
272
- if (requestedCli && requestedCli !== existing.type) {
273
- await updateThread(key, {
274
- type: requestedCli,
275
- ...(role !== null && role !== undefined ? { role } : {}),
276
- ...(model !== null && model !== undefined ? { model } : {}),
277
- ...(effort !== null && effort !== undefined ? { effort } : {}),
278
- ...(provider !== undefined ? { provider } : {}),
279
- });
280
- } else if (role !== null || model !== null || effort !== null || provider !== undefined) {
281
- await updateThread(key, {
282
- ...(role !== null && role !== undefined ? { role } : {}),
283
- ...(model !== null && model !== undefined ? { model } : {}),
284
- ...(effort !== null && effort !== undefined ? { effort } : {}),
285
- ...(provider !== undefined ? { provider } : {}),
286
- });
287
- }
288
- existing.lastActiveAt = now;
289
- ws.updatedAt = now;
290
- persistWorkspace(ws);
291
- return { key, created: false, thread: getThreadView(key) };
292
- }
293
-
294
- const chosenCli = cli || (roleDef?.type && AGENTS[roleDef.type] ? roleDef.type : null) || pickDefaultCli();
295
- if (!AGENTS[chosenCli]) throw new Error(`unknown CLI "${chosenCli}"; available: ${Object.keys(AGENTS).join(', ')}`);
296
- const chosenModel = model || roleDef?.model || null;
297
- const chosenProvider = normalizeProvider(provider, chosenCli, chosenModel);
298
- const baseId = threadIdForTopic(cleanTopic);
299
- let id = baseId;
300
- let n = 2;
301
- while (ws.threads.some((t) => t.id === id)) {
302
- id = `${baseId}-${n}`;
303
- n += 1;
304
- }
305
- checkId('thread', id);
306
- const th = {
307
- id,
308
- topic: cleanTopic,
309
- ephemeral: false,
310
- type: chosenCli,
311
- dir: relDir,
312
- role: roleDef?.id ?? null,
313
- model: chosenModel,
314
- effort: cleanEffort(effort),
315
- provider: chosenProvider,
316
- sessionId: null,
317
- createdAt: now,
318
- lastActiveAt: now,
319
- };
320
- ws.threads.push(th);
321
- ws.updatedAt = now;
322
- registerThread(ws, th);
323
- persistWorkspace(ws);
324
- const key = keyOf(ws.id, th.id);
325
- return { key, created: true, thread: getThreadView(key) };
326
- }
327
-
328
- const chosenCli = cli || (roleDef?.type && AGENTS[roleDef.type] ? roleDef.type : null) || pickDefaultCli();
329
- if (!AGENTS[chosenCli]) throw new Error(`unknown CLI "${chosenCli}"; available: ${Object.keys(AGENTS).join(', ')}`);
330
- const chosenModel = model || roleDef?.model || null;
331
- const chosenProvider = normalizeProvider(provider, chosenCli, chosenModel);
332
- const id = `run-${chosenCli}-${randomBytes(3).toString('hex')}`;
333
- const th = {
334
- id,
335
- topic: null,
336
- ephemeral: true,
337
- type: chosenCli,
338
- dir: relDir,
339
- role: roleDef?.id ?? null,
340
- model: chosenModel,
341
- effort: cleanEffort(effort),
342
- provider: chosenProvider,
343
- sessionId: null,
344
- createdAt: now,
345
- lastActiveAt: now,
346
- };
347
- ws.threads.push(th);
348
- ws.updatedAt = now;
349
- registerThread(ws, th);
350
- persistWorkspace(ws);
351
- const key = keyOf(ws.id, th.id);
352
- return { key, created: true, thread: getThreadView(key) };
353
- });
354
- }
355
-
356
- export async function updateThread(key, { type, role, model, effort, provider } = {}) {
357
- const found = findThreadByKey(key);
358
- if (!found) throw new Error(`unknown thread "${key}"`);
359
- const { ws, th } = found;
360
- let agent = found.agent ?? registerThread(ws, th);
361
- const retype = type !== undefined && type !== th.type;
362
-
363
- if (retype) {
364
- if (!AGENTS[type]) throw new Error(`unknown CLI "${type}"; available: ${Object.keys(AGENTS).join(', ')}`);
365
- if (agent.inUse) throw new Error(`thread "${key}" is currently running; cancel it first or use a new topic`);
366
- // Only pre-validate an explicitly supplied provider; an inherited provider is gracefully cleared below if incompatible.
367
- if (provider !== undefined && provider) normalizeProvider(provider, type, model ?? null);
368
- await agent.shutdown({ clearQueue: true });
369
- pool.delete(key);
370
- th.type = type;
371
- th.sessionId = null;
372
- if (model === undefined) th.model = null;
373
- if (effort === undefined) th.effort = null;
374
- if (provider === undefined && th.provider) {
375
- try {
376
- th.provider = normalizeProvider(th.provider, type, th.model);
377
- } catch {
378
- th.provider = null;
379
- }
380
- }
381
- agent = registerThread(ws, th);
382
- }
383
-
384
- if (role !== undefined) {
385
- if (role && !getRole(role, { cwd: resolve(ws.root, th.dir || '.') })) {
386
- throw new Error(`unknown role "${role}"`);
387
- }
388
- th.role = role || null;
389
- agent.role = th.role;
390
- }
391
-
392
- if (model !== undefined) {
393
- th.model = model ? String(model).slice(0, 200) : null;
394
- agent.preferModel = th.model;
395
- }
396
-
397
- if (effort !== undefined) {
398
- th.effort = cleanEffort(effort);
399
- agent.preferEffort = th.effort;
400
- }
401
-
402
- if (provider !== undefined) {
403
- const nextProv = normalizeProvider(provider, th.type, th.model);
404
- const changed = JSON.stringify(th.provider ?? null) !== JSON.stringify(nextProv ?? null);
405
- th.provider = nextProv;
406
- if (changed && agent.child && !agent.inUse) {
407
- await agent.shutdown({ clearQueue: false });
408
- }
409
- }
410
-
411
- th.lastActiveAt = new Date().toISOString();
412
- ws.updatedAt = th.lastActiveAt;
413
- persistWorkspace(ws);
414
- return getThreadView(key);
415
- }
416
-
417
- export async function removeThread(key) {
418
- const found = findThreadByKey(key);
419
- if (!found) throw new Error(`unknown thread "${key}"`);
420
- const { ws, th, agent } = found;
421
- if (agent) {
422
- await agent.shutdown({ clearQueue: true }).catch(() => {});
423
- pool.delete(key);
424
- }
425
- ws.threads = ws.threads.filter((t) => t.id !== th.id);
426
- if (ws.threads.length === 0) {
427
- deleteWorkspace(ws.id);
428
- forgetPoolWorkspace(ws.id);
429
- forgetRecordsWorkspace(ws.id);
430
- } else {
431
- ws.updatedAt = new Date().toISOString();
432
- persistWorkspace(ws);
433
- }
434
- return { removed: key };
435
- }
436
-
437
- export async function sweepIdle(idleMs, { ephemeralKeepMs = EPHEMERAL_KEEP_MS } = {}) {
438
- const now = Date.now();
439
- const stopped = [];
440
- for (const ws of allWorkspaces()) {
441
- const keep = [];
442
- let dropped = false;
443
- for (const th of ws.threads) {
444
- const key = keyOf(ws.id, th.id);
445
- const a = pool.get(key);
446
- if (a && a.child && !a.busy && now - a.lastActive > idleMs) {
447
- await a.shutdown().catch(() => {});
448
- stopped.push(key);
449
- }
450
- const last = a?.lastActive ?? Date.parse(th.lastActiveAt || th.createdAt || 0);
451
- if (th.ephemeral && (!a || (!a.busy && !a.child)) && now - last > ephemeralKeepMs) {
452
- if (a) pool.delete(key);
453
- dropped = true;
454
- continue;
455
- }
456
- keep.push(th);
457
- }
458
- ws.threads = keep;
459
- if (dropped) {
460
- if (ws.threads.length === 0) {
461
- deleteWorkspace(ws.id);
462
- forgetPoolWorkspace(ws.id);
463
- forgetRecordsWorkspace(ws.id);
464
- } else {
465
- persistWorkspace(ws);
466
- }
467
- }
468
- }
469
- return stopped;
470
- }
471
-
472
- export function workspaceRootOf(workspaceId) {
473
- const ws = getWorkspace(workspaceId);
474
- if (!ws) throw new Error(`unknown workspace "${workspaceId}"`);
475
- return ws.root;
476
- }
1
+ import { randomBytes } from 'node:crypto';
2
+ import { resolve } from 'node:path';
3
+ import { AGENTS, cliAvailability } from '../env/index.mjs';
4
+ import { buildInstance, forgetProject as forgetPoolWorkspace, listInstances, pool } from '../pool/index.mjs';
5
+ import { executorRulesFor, getRole } from '../prompts/index.mjs';
6
+ import { cleanInstanceProvider, listProviders } from '../providers/index.mjs';
7
+ import { forgetProject as forgetRecordsWorkspace, withInterrupted } from '../records/index.mjs';
8
+ import { canonicalDir, relativeInside, resolveInside, threadIdForTopic, workspaceIdOf } from './paths.mjs';
9
+ import {
10
+ EPHEMERAL_KEEP_MS,
11
+ SEP,
12
+ allWorkspaces,
13
+ checkId,
14
+ clearMemoryStore,
15
+ deleteWorkspace,
16
+ findWorkspaceByRoot,
17
+ getWorkspace,
18
+ keyOf,
19
+ loadWorkspacesFromDisk,
20
+ saveWorkspace,
21
+ upsertWorkspace,
22
+ } from './store.mjs';
23
+
24
+ const DEFAULT_CLI_ORDER = ['claude', 'codex', 'dsh', 'kimi', 'opencode', 'mcode', 'pi', 'agy', 'qoder', 'grok'];
25
+
26
+ let threadHooks = null;
27
+ export function setThreadHooks(hooks) {
28
+ threadHooks = hooks ?? null;
29
+ for (const agent of pool.values()) applyHooks(agent);
30
+ }
31
+
32
+ function applyHooks(agent) {
33
+ if (!threadHooks || !agent) return;
34
+ if (typeof threadHooks.onProgress === 'function') agent.setProgressSink?.((jobId, payload) => threadHooks.onProgress(agent, jobId, payload));
35
+ if (typeof threadHooks.onRunStart === 'function') agent.onRunStart = (info) => threadHooks.onRunStart(agent, info);
36
+ if (typeof threadHooks.onExit === 'function') agent.onExit = (info) => threadHooks.onExit(agent, info);
37
+ if (typeof threadHooks.onForcedStop === 'function') agent.onForcedStop = (info) => threadHooks.onForcedStop(agent, info);
38
+ if (typeof threadHooks.onCompact === 'function') agent.onCompact = (info) => threadHooks.onCompact(agent, info);
39
+ }
40
+
41
+ function touchThread(ws, th, now = new Date().toISOString()) {
42
+ th.lastActiveAt = now;
43
+ ws.updatedAt = now;
44
+ const idx = ws.threads.indexOf(th);
45
+ if (idx > 0) {
46
+ ws.threads.splice(idx, 1);
47
+ ws.threads.unshift(th);
48
+ }
49
+ }
50
+
51
+ function persistWorkspace(ws) {
52
+ const busyIds = new Set();
53
+ for (const t of ws.threads) {
54
+ const a = pool.get(keyOf(ws.id, t.id));
55
+ if (a && (a.busy || a.inUse || a.inflight > 0)) busyIds.add(t.id);
56
+ }
57
+ const { dropped } = saveWorkspace(ws, { busyIds });
58
+ for (const t of dropped) {
59
+ const k = keyOf(ws.id, t.id);
60
+ const a = pool.get(k);
61
+ if (a) {
62
+ pool.delete(k);
63
+ a.shutdown({ clearQueue: false }).catch(() => {});
64
+ }
65
+ }
66
+ }
67
+
68
+ let resolveChain = Promise.resolve();
69
+ function withResolveLock(fn) {
70
+ const next = resolveChain.then(fn, fn);
71
+ resolveChain = next.catch(() => {});
72
+ return next;
73
+ }
74
+
75
+ function cleanEffort(v) {
76
+ const s = String(v ?? '').trim();
77
+ return s && s !== 'default' ? s.slice(0, 40) : null;
78
+ }
79
+
80
+ function inferProviderForModel(cli, model) {
81
+ if (!model) return null;
82
+ for (const p of listProviders()) {
83
+ if (!Array.isArray(p.types) || !p.types.includes(cli)) continue;
84
+ const models = Array.isArray(p.models) ? p.models : [];
85
+ if (models.includes(model)) return { id: p.id, model };
86
+ }
87
+ return null;
88
+ }
89
+
90
+ function normalizeProvider(provider, cli, model) {
91
+ if (provider === null || provider === '') return null;
92
+ if (typeof provider === 'string') {
93
+ return cleanInstanceProvider({ id: provider, ...(model ? { model } : {}) }, cli);
94
+ }
95
+ if (provider && typeof provider === 'object') {
96
+ return cleanInstanceProvider(provider, cli);
97
+ }
98
+ return inferProviderForModel(cli, model);
99
+ }
100
+
101
+ function pickDefaultCli() {
102
+ const installed = new Set(cliAvailability().filter((c) => c.installed).map((c) => c.type));
103
+ for (const t of DEFAULT_CLI_ORDER) {
104
+ if (installed.has(t)) return t;
105
+ }
106
+ const avail = Object.keys(AGENTS);
107
+ for (const t of DEFAULT_CLI_ORDER) {
108
+ if (avail.includes(t)) return t;
109
+ }
110
+ if (avail.length) return avail[0];
111
+ throw new Error('no native CLI driver available');
112
+ }
113
+
114
+ function registerThread(ws, th) {
115
+ const key = keyOf(ws.id, th.id);
116
+ if (pool.has(key)) return pool.get(key);
117
+ const cwd = resolve(ws.root, th.dir || '.');
118
+ const agent = buildInstance({
119
+ id: key,
120
+ type: th.type,
121
+ cwd,
122
+ project: ws.id,
123
+ shortId: th.id,
124
+ role: th.role ?? null,
125
+ model: th.model ?? null,
126
+ effort: th.effort ?? null,
127
+ sessionId: th.sessionId ?? null,
128
+ provider: () => th.provider ?? null,
129
+ systemPrompt: () => executorRulesFor(th.role, { cwd }) || null,
130
+ ephemeral: Boolean(th.ephemeral),
131
+ onSession: (sid) => {
132
+ th.sessionId = sid;
133
+ touchThread(ws, th);
134
+ persistWorkspace(ws);
135
+ },
136
+ });
137
+ applyHooks(agent);
138
+ pool.set(key, agent);
139
+ return agent;
140
+ }
141
+
142
+ export function initThreads() {
143
+ const loaded = loadWorkspacesFromDisk();
144
+ for (const ws of loaded) {
145
+ for (const th of ws.threads) {
146
+ if (!AGENTS[th.type]) continue;
147
+ registerThread(ws, th);
148
+ }
149
+ }
150
+ return loaded;
151
+ }
152
+
153
+ export function resetThreadsForTest() {
154
+ pool.clear();
155
+ clearMemoryStore();
156
+ }
157
+
158
+ export function findThreadByKey(key) {
159
+ const s = String(key ?? '');
160
+ const idx = s.indexOf(SEP);
161
+ if (idx < 0) return null;
162
+ const wsId = s.slice(0, idx);
163
+ const thId = s.slice(idx + SEP.length);
164
+ const ws = getWorkspace(wsId);
165
+ if (!ws) return null;
166
+ const th = ws.threads.find((t) => t.id === thId);
167
+ if (!th) return null;
168
+ return { ws, th, key: keyOf(ws.id, th.id), agent: pool.get(keyOf(ws.id, th.id)) ?? null };
169
+ }
170
+
171
+ export function findThread({ key, cwd, topic }) {
172
+ if (key) return findThreadByKey(key);
173
+ if (!cwd) return null;
174
+ const root = canonicalDir(cwd);
175
+ const ws = findWorkspaceByRoot(root) ?? getWorkspace(workspaceIdOf(root));
176
+ if (!ws || !topic) return null;
177
+ const trimmed = String(topic).trim();
178
+ const th = ws.threads.find((t) => t.topic === trimmed || t.id === trimmed);
179
+ if (!th) return null;
180
+ const k = keyOf(ws.id, th.id);
181
+ return { ws, th, key: k, agent: pool.get(k) ?? null };
182
+ }
183
+
184
+ function viewThread(ws, th, liveByKey) {
185
+ const key = keyOf(ws.id, th.id);
186
+ const live = liveByKey.get(key) ?? null;
187
+ return {
188
+ key,
189
+ id: th.id,
190
+ workspaceId: ws.id,
191
+ workspaceRoot: ws.root,
192
+ workspaceLabel: ws.label,
193
+ topic: th.topic ?? null,
194
+ ephemeral: Boolean(th.ephemeral),
195
+ type: th.type,
196
+ dir: th.dir || '.',
197
+ cwd: resolve(ws.root, th.dir || '.'),
198
+ role: th.role ?? null,
199
+ model: live?.model ?? th.model ?? null,
200
+ preferModel: th.model ?? null,
201
+ effort: th.effort ?? null,
202
+ provider: th.provider ?? null,
203
+ sessionId: live?.sessionId ?? th.sessionId ?? null,
204
+ createdAt: th.createdAt,
205
+ lastActiveAt: th.lastActiveAt,
206
+ alive: live?.alive ?? false,
207
+ busy: live?.busy ?? false,
208
+ activity: live?.activity ?? null,
209
+ waiting: live?.waiting ?? 0,
210
+ waitingJobs: live?.waitingJobs ?? [],
211
+ unstable: live?.unstable ?? false,
212
+ lastError: live?.lastError ?? null,
213
+ interrupted: live?.interrupted ?? null,
214
+ context: live?.context ?? null,
215
+ };
216
+ }
217
+
218
+ export function listWorkspaces({ cwd = null } = {}) {
219
+ const liveRows = withInterrupted(listInstances());
220
+ const liveByKey = new Map(liveRows.map((r) => [r.id, r]));
221
+ let targetRoot = null;
222
+ if (cwd) {
223
+ try {
224
+ targetRoot = canonicalDir(cwd);
225
+ } catch {
226
+ targetRoot = resolve(cwd);
227
+ }
228
+ }
229
+ const norm = (p) => (process.platform === 'win32' ? p.toLowerCase() : p);
230
+ return allWorkspaces()
231
+ .filter((ws) => (!targetRoot ? true : norm(ws.root) === norm(targetRoot)))
232
+ .map((ws) => ({
233
+ id: ws.id,
234
+ root: ws.root,
235
+ label: ws.label,
236
+ updatedAt: ws.updatedAt,
237
+ threads: ws.threads
238
+ .map((th) => viewThread(ws, th, liveByKey))
239
+ .sort((a, b) => Number(b.busy) - Number(a.busy) || String(b.lastActiveAt ?? '').localeCompare(String(a.lastActiveAt ?? ''))),
240
+ }))
241
+ .sort((a, b) => String(b.updatedAt ?? '').localeCompare(String(a.updatedAt ?? '')));
242
+ }
243
+
244
+ export function listThreads({ cwd = null, onlyBusy = false } = {}) {
245
+ const all = listWorkspaces({ cwd }).flatMap((w) => w.threads);
246
+ return onlyBusy ? all.filter((t) => t.busy || t.waiting > 0) : all;
247
+ }
248
+
249
+ export function getThreadView(key) {
250
+ const found = findThreadByKey(key);
251
+ if (!found) throw new Error(`unknown thread "${key}"`);
252
+ const liveRows = withInterrupted(listInstances());
253
+ const liveByKey = new Map(liveRows.map((r) => [r.id, r]));
254
+ return viewThread(found.ws, found.th, liveByKey);
255
+ }
256
+
257
+ export function resolveThread({ cwd, topic = null, cli = null, role = null, model = null, effort = null, provider = undefined, dir = '.', allowMutateExisting = true } = {}) {
258
+ return withResolveLock(async () => {
259
+ const root = canonicalDir(cwd);
260
+ const relDir = relativeInside(root, dir);
261
+ const targetCwd = resolveInside(root, relDir);
262
+ const wsId = workspaceIdOf(root);
263
+ const ws = findWorkspaceByRoot(root) ?? upsertWorkspace({ id: wsId, root });
264
+
265
+ const roleDef = role ? getRole(role, { cwd: targetCwd }) : null;
266
+ if (role && !roleDef) throw new Error(`unknown role "${role}"`);
267
+
268
+ const cleanTopic = topic !== null && topic !== undefined ? String(topic).trim() : '';
269
+ const now = new Date().toISOString();
270
+
271
+ if (cleanTopic) {
272
+ const existing = ws.threads.find((t) => t.topic === cleanTopic || t.id === cleanTopic);
273
+ if (existing) {
274
+ const key = keyOf(ws.id, existing.id);
275
+ const requestedCli = cli || null;
276
+ const targetCli = requestedCli || existing.type;
277
+ const nextEffort = effort !== null && effort !== undefined ? cleanEffort(effort) : undefined;
278
+ let providerChanged = false;
279
+ if (provider !== undefined) {
280
+ const previewProv = normalizeProvider(provider, targetCli, model ?? existing.model);
281
+ providerChanged = JSON.stringify(existing.provider ?? null) !== JSON.stringify(previewProv ?? null);
282
+ }
283
+ const wantsMutation =
284
+ Boolean(requestedCli && requestedCli !== existing.type) ||
285
+ (role !== null && role !== undefined && (role || null) !== existing.role) ||
286
+ (model !== null && model !== undefined && (model || null) !== existing.model) ||
287
+ (nextEffort !== undefined && nextEffort !== existing.effort) ||
288
+ providerChanged;
289
+ if (wantsMutation && !allowMutateExisting) {
290
+ throw new Error(`managed child agent is not allowed to mutate existing thread "${cleanTopic}"`);
291
+ }
292
+ if (wantsMutation) {
293
+ await updateThread(key, {
294
+ ...(requestedCli && requestedCli !== existing.type ? { type: requestedCli } : {}),
295
+ ...(role !== null && role !== undefined ? { role } : {}),
296
+ ...(model !== null && model !== undefined ? { model } : {}),
297
+ ...(effort !== null && effort !== undefined ? { effort } : {}),
298
+ ...(provider !== undefined ? { provider } : {}),
299
+ });
300
+ }
301
+ touchThread(ws, existing, now);
302
+ persistWorkspace(ws);
303
+ return { key, created: false, thread: getThreadView(key) };
304
+ }
305
+
306
+ const chosenCli = cli || (roleDef?.type && AGENTS[roleDef.type] ? roleDef.type : null) || pickDefaultCli();
307
+ if (!AGENTS[chosenCli]) throw new Error(`unknown CLI "${chosenCli}"; available: ${Object.keys(AGENTS).join(', ')}`);
308
+ const chosenModel = model || roleDef?.model || null;
309
+ const chosenProvider = normalizeProvider(provider, chosenCli, chosenModel);
310
+ const baseId = threadIdForTopic(cleanTopic);
311
+ let id = baseId;
312
+ let n = 2;
313
+ while (ws.threads.some((t) => t.id === id)) {
314
+ id = `${baseId}-${n}`;
315
+ n += 1;
316
+ }
317
+ checkId('thread', id);
318
+ const th = {
319
+ id,
320
+ topic: cleanTopic,
321
+ ephemeral: false,
322
+ type: chosenCli,
323
+ dir: relDir,
324
+ role: roleDef?.id ?? null,
325
+ model: chosenModel,
326
+ effort: cleanEffort(effort),
327
+ provider: chosenProvider,
328
+ sessionId: null,
329
+ createdAt: now,
330
+ lastActiveAt: now,
331
+ };
332
+ ws.threads.unshift(th);
333
+ ws.updatedAt = now;
334
+ registerThread(ws, th);
335
+ persistWorkspace(ws);
336
+ const key = keyOf(ws.id, th.id);
337
+ return { key, created: true, thread: getThreadView(key) };
338
+ }
339
+
340
+ const chosenCli = cli || (roleDef?.type && AGENTS[roleDef.type] ? roleDef.type : null) || pickDefaultCli();
341
+ if (!AGENTS[chosenCli]) throw new Error(`unknown CLI "${chosenCli}"; available: ${Object.keys(AGENTS).join(', ')}`);
342
+ const chosenModel = model || roleDef?.model || null;
343
+ const chosenProvider = normalizeProvider(provider, chosenCli, chosenModel);
344
+ const id = `run-${chosenCli}-${randomBytes(3).toString('hex')}`;
345
+ const th = {
346
+ id,
347
+ topic: null,
348
+ ephemeral: true,
349
+ type: chosenCli,
350
+ dir: relDir,
351
+ role: roleDef?.id ?? null,
352
+ model: chosenModel,
353
+ effort: cleanEffort(effort),
354
+ provider: chosenProvider,
355
+ sessionId: null,
356
+ createdAt: now,
357
+ lastActiveAt: now,
358
+ };
359
+ ws.threads.unshift(th);
360
+ ws.updatedAt = now;
361
+ registerThread(ws, th);
362
+ persistWorkspace(ws);
363
+ const key = keyOf(ws.id, th.id);
364
+ return { key, created: true, thread: getThreadView(key) };
365
+ });
366
+ }
367
+
368
+ export async function updateThread(key, { type, role, model, effort, provider } = {}) {
369
+ const found = findThreadByKey(key);
370
+ if (!found) throw new Error(`unknown thread "${key}"`);
371
+ const { ws, th } = found;
372
+ let agent = found.agent ?? registerThread(ws, th);
373
+ const retype = type !== undefined && type !== th.type;
374
+
375
+ if (retype) {
376
+ if (!AGENTS[type]) throw new Error(`unknown CLI "${type}"; available: ${Object.keys(AGENTS).join(', ')}`);
377
+ if (agent.inUse) throw new Error(`thread "${key}" is currently running; cancel it first or use a new topic`);
378
+ // Only pre-validate an explicitly supplied provider; an inherited provider is gracefully cleared below if incompatible.
379
+ if (provider !== undefined && provider) normalizeProvider(provider, type, model ?? null);
380
+ await agent.shutdown({ clearQueue: true });
381
+ pool.delete(key);
382
+ th.type = type;
383
+ th.sessionId = null;
384
+ if (model === undefined) th.model = null;
385
+ if (effort === undefined) th.effort = null;
386
+ if (provider === undefined && th.provider) {
387
+ try {
388
+ th.provider = normalizeProvider(th.provider, type, th.model);
389
+ } catch {
390
+ th.provider = null;
391
+ }
392
+ }
393
+ agent = registerThread(ws, th);
394
+ }
395
+
396
+ if (role !== undefined) {
397
+ if (role && !getRole(role, { cwd: resolve(ws.root, th.dir || '.') })) {
398
+ throw new Error(`unknown role "${role}"`);
399
+ }
400
+ th.role = role || null;
401
+ agent.role = th.role;
402
+ }
403
+
404
+ if (model !== undefined) {
405
+ th.model = model ? String(model).slice(0, 200) : null;
406
+ agent.preferModel = th.model;
407
+ }
408
+
409
+ if (effort !== undefined) {
410
+ const nextEffort = cleanEffort(effort);
411
+ if (nextEffort !== th.effort) {
412
+ th.effort = nextEffort;
413
+ await agent.chooseEffort(th.effort);
414
+ }
415
+ }
416
+
417
+ if (provider !== undefined) {
418
+ const nextProv = normalizeProvider(provider, th.type, th.model);
419
+ const changed = JSON.stringify(th.provider ?? null) !== JSON.stringify(nextProv ?? null);
420
+ th.provider = nextProv;
421
+ if (changed && agent.child && !agent.inUse) {
422
+ await agent.shutdown({ clearQueue: false });
423
+ }
424
+ }
425
+
426
+ touchThread(ws, th);
427
+ persistWorkspace(ws);
428
+ return getThreadView(key);
429
+ }
430
+
431
+ export function touchThreadByKey(key) {
432
+ const found = findThreadByKey(key);
433
+ if (!found) return null;
434
+ touchThread(found.ws, found.th);
435
+ persistWorkspace(found.ws);
436
+ return found.th;
437
+ }
438
+
439
+ export async function removeThread(key) {
440
+ const found = findThreadByKey(key);
441
+ if (!found) throw new Error(`unknown thread "${key}"`);
442
+ const { ws, th, agent } = found;
443
+ if (agent) {
444
+ await agent.shutdown({ clearQueue: true }).catch(() => {});
445
+ pool.delete(key);
446
+ }
447
+ ws.threads = ws.threads.filter((t) => t.id !== th.id);
448
+ if (ws.threads.length === 0) {
449
+ deleteWorkspace(ws.id);
450
+ forgetPoolWorkspace(ws.id);
451
+ forgetRecordsWorkspace(ws.id);
452
+ } else {
453
+ ws.updatedAt = new Date().toISOString();
454
+ persistWorkspace(ws);
455
+ }
456
+ return { removed: key };
457
+ }
458
+
459
+ export async function sweepIdle(idleMs, { ephemeralKeepMs = EPHEMERAL_KEEP_MS } = {}) {
460
+ const now = Date.now();
461
+ const stopped = [];
462
+ for (const ws of allWorkspaces()) {
463
+ const keep = [];
464
+ let dropped = false;
465
+ for (const th of ws.threads) {
466
+ const key = keyOf(ws.id, th.id);
467
+ const a = pool.get(key);
468
+ if (a && a.child && !a.busy && now - a.lastActive > idleMs) {
469
+ await a.shutdown().catch(() => {});
470
+ stopped.push(key);
471
+ }
472
+ const last = a?.lastActive ?? Date.parse(th.lastActiveAt || th.createdAt || 0);
473
+ if (th.ephemeral && (!a || (!a.busy && !a.child)) && now - last > ephemeralKeepMs) {
474
+ if (a) pool.delete(key);
475
+ dropped = true;
476
+ continue;
477
+ }
478
+ keep.push(th);
479
+ }
480
+ ws.threads = keep;
481
+ if (dropped) {
482
+ if (ws.threads.length === 0) {
483
+ deleteWorkspace(ws.id);
484
+ forgetPoolWorkspace(ws.id);
485
+ forgetRecordsWorkspace(ws.id);
486
+ } else {
487
+ persistWorkspace(ws);
488
+ }
489
+ }
490
+ }
491
+ return stopped;
492
+ }
493
+
494
+ export function workspaceRootOf(workspaceId) {
495
+ const ws = getWorkspace(workspaceId);
496
+ if (!ws) throw new Error(`unknown workspace "${workspaceId}"`);
497
+ return ws.root;
498
+ }