hivedesk 0.1.1 → 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 (66) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/FIRST-RUN.md +14 -0
  3. package/PROTOCOL.md +23 -6
  4. package/README.md +51 -6
  5. package/assets/illustrations/hive-city.svg +113 -0
  6. package/assets/video-poster.webp +0 -0
  7. package/i18n/README.pt-BR.md +50 -6
  8. package/i18n/de.json +178 -0
  9. package/i18n/en.json +178 -0
  10. package/i18n/es.json +178 -0
  11. package/i18n/fr.json +178 -0
  12. package/i18n/it.json +178 -0
  13. package/i18n/ja.json +178 -0
  14. package/i18n/ko.json +178 -0
  15. package/i18n/pt-BR.json +178 -0
  16. package/i18n/ru.json +178 -0
  17. package/i18n/zh-CN.json +178 -0
  18. package/package.json +1 -1
  19. package/src/bus.js +22 -2
  20. package/src/city/demo.js +76 -0
  21. package/src/city/hops.js +95 -0
  22. package/src/city/index.js +1546 -0
  23. package/src/city/router.js +53 -0
  24. package/src/city/state.js +313 -0
  25. package/src/city/store.js +91 -0
  26. package/src/cli.js +44 -5
  27. package/src/collab/index.js +10 -6
  28. package/src/collab/policy.js +48 -0
  29. package/src/crew/engine.js +40 -3
  30. package/src/crew/scheduler.js +4 -0
  31. package/src/crew/worker.js +5 -1
  32. package/src/demo.js +30 -2
  33. package/src/extensions/sandbox.js +81 -56
  34. package/src/index.js +26 -3
  35. package/src/lend/guard.js +115 -7
  36. package/src/lend/index.js +38 -8
  37. package/src/replay/reduce.js +2 -1
  38. package/src/server.js +22 -4
  39. package/src/tools/approvals.js +12 -3
  40. package/src/tools/index.js +46 -2
  41. package/ui/city/city.css +204 -0
  42. package/ui/city/city.js +933 -0
  43. package/ui/city/collab.js +67 -0
  44. package/ui/city/layout.js +142 -0
  45. package/ui/city/mock.js +358 -0
  46. package/ui/city/model.js +195 -0
  47. package/ui/city/scene.js +2033 -0
  48. package/ui/css/hive.css +2 -0
  49. package/ui/js/main.js +3 -1
  50. package/ui/js/widgets/approvals.js +3 -0
  51. package/ui/lend/collab/client.js +1 -1
  52. package/ui/lend/collab/roles.js +21 -12
  53. package/ui/lend/core/bridge.js +18 -5
  54. package/ui/lend/core/frames.js +20 -0
  55. package/ui/office/office.js +51 -21
  56. package/ui/office/scene.js +3 -0
  57. package/ui/screenshots/city-agent-card-1440.png +0 -0
  58. package/ui/screenshots/city-agent-card-1920.png +0 -0
  59. package/ui/screenshots/city-bridge-gpu-borrow-1440.png +0 -0
  60. package/ui/screenshots/city-bridge-gpu-borrow-1920.png +0 -0
  61. package/ui/screenshots/city-friend-rising-1440.png +0 -0
  62. package/ui/screenshots/city-friend-rising-1920.png +0 -0
  63. package/ui/screenshots/city-overview-1440.png +0 -0
  64. package/ui/screenshots/city-overview-1920.png +0 -0
  65. package/ui/screenshots/city-review-room-1440.png +0 -0
  66. package/ui/screenshots/city-review-room-1920.png +0 -0
@@ -48,6 +48,9 @@ export class Hive {
48
48
  this.memory = new Memory();
49
49
  /** @type {Map<string, { ctrl: AbortController, notes: Map<string, string[]>, promise: Promise<any> }>} */
50
50
  this.active = new Map();
51
+ /** Hive City hooks (src/city/), optional: the worker a task runs with (room tools) and extra memories for its prompt. */
52
+ this.adaptWorker = null;
53
+ this.extraMemories = null;
51
54
  }
52
55
 
53
56
  get state() {
@@ -165,11 +168,14 @@ export class Hive {
165
168
  refine: spec.refine === undefined ? this.state.settings.refine !== false : !!spec.refine,
166
169
  createdAt: new Date().toISOString(), taskIds: []
167
170
  };
171
+ // A city hop (src/city/): one given task, no brief, no planner, no report.
172
+ const plan = Array.isArray(spec.plan) && spec.plan.length ? spec.plan : null;
173
+ if (plan) { job.refine = false; job.cityTaskId = String(spec.cityTaskId || '').slice(0, 40) || undefined; }
168
174
  const ctrl = new AbortController();
169
175
  const run = { ctrl, notes: new Map(), promise: null };
170
176
  this.active.set(jobId, run);
171
177
  this.bus.emit('job.created', { job }, { jobId });
172
- run.promise = this._runJob(job, run, spec.playbookId).catch((err) => {
178
+ run.promise = (plan ? this._runPlanned(job, run, plan) : this._runJob(job, run, spec.playbookId)).catch((err) => {
173
179
  if (ctrl.signal.aborted) return;
174
180
  this.bus.emit('job.failed', { error: String(err?.message || err) }, { jobId });
175
181
  }).finally(() => {
@@ -265,6 +271,34 @@ export class Hive {
265
271
  });
266
272
  }
267
273
 
274
+ /** A job with a given plan (a Hive City hop): the tasks run as they are, without the planner, QA rounds or the report. */
275
+ async _runPlanned(job, run, plan) {
276
+ const jobNum = job.id.slice(2);
277
+ const graph = new TaskGraph();
278
+ const known = this.crewById();
279
+ const tasks = plan.slice(0, 8).map((t, i) => graph.add({
280
+ id: `t_${jobNum}_${i + 1}`, jobId: job.id, title: String(t.title || 'Task').slice(0, 200), detail: String(t.detail || '').slice(0, 8000),
281
+ assignee: known.has(t.assignee) ? t.assignee : 'dev', dependsOn: (t.dependsOn || []).map((d) => `t_${jobNum}_${d + 1}`), status: 'pending', attempts: 0,
282
+ kind: ['build', 'fix', 'docs'].includes(t.kind) ? t.kind : 'build'
283
+ }));
284
+ run.memories = [];
285
+ this.bus.emit('job.planned', { tasks: tasks.map((t) => ({ ...t })) }, { jobId: job.id });
286
+ await this._drive(job, run, {
287
+ graph, tasks: null, preexisting: new Set(this.toolbox.ws.list().map((f) => f.path)), fixRounds: MAX_FIX_ROUNDS, nextIdx: tasks.length + 1,
288
+ qaPassed: true, openIssues: [], playbook: null, score: 0, quiet: true
289
+ });
290
+ }
291
+
292
+ /** Adds a note for one worker of a running job, as if the user had written it (Hive City review notes). */
293
+ addNote(jobId, workerId, text) {
294
+ const run = this.active.get(jobId);
295
+ if (!run) return false;
296
+ const list = run.notes.get(workerId) || [];
297
+ list.push(String(text).slice(0, 2000));
298
+ run.notes.set(workerId, list.slice(-5));
299
+ return true;
300
+ }
301
+
268
302
  /** Runs the task graph of a job to the end: workers take turns, QA adds fix rounds, then done. */
269
303
  async _drive(job, run, st) {
270
304
  const jobId = job.id;
@@ -285,7 +319,8 @@ export class Hive {
285
319
 
286
320
  const startTask = (task) => {
287
321
  const crewById = this.crewById();
288
- const worker = crewById.get(task.assignee) || crewById.get('dev');
322
+ const base = crewById.get(task.assignee) || crewById.get('dev');
323
+ const worker = (this.adaptWorker && this.adaptWorker(base, task, job)) || base;
289
324
  graph.setStatus(task.id, 'running');
290
325
  this.bus.emit('task.status', { taskId: task.id, status: 'running' }, ev);
291
326
  const userNotes = () => [...(run.notes.get('*') || []), ...(run.notes.get(worker.id) || [])];
@@ -314,7 +349,7 @@ export class Hive {
314
349
  job, task, worker, graph, crewById, scheduler: this.scheduler, toolbox: this.toolbox, memory: this.memory, bus: this.bus,
315
350
  signal: anySignal([signal, control.ctrl.signal]), maxTurns: this.maxTurns, extra, userNotes, preexisting: st.preexisting, budget: run.budget,
316
351
  family: modelFamily(this.state.brain), contextTokens: this.state.brain?.ctx || undefined,
317
- recent: () => this._recentFiles(jobId), memories: run.memories || [],
352
+ recent: () => this._recentFiles(jobId), memories: [...(run.memories || []), ...((this.extraMemories && this.extraMemories(worker.id, task)) || [])],
318
353
  verify: task.kind === 'qa' ? undefined : (wrote) => {
319
354
  // Fix tasks must clear every static issue; build tasks only the ones in their own files
320
355
  // (a link to a file another worker has not written yet is not their problem).
@@ -398,6 +433,7 @@ export class Hive {
398
433
  const buildTasks = all.filter((t) => t.kind !== 'qa' && t.status !== 'skipped');
399
434
  if (buildTasks.length && buildTasks.every((t) => t.status === 'failed' || t.status === 'blocked')) {
400
435
  this.bus.emit('job.failed', { error: `${failed.length} tasks failed` }, ev);
436
+ if (st.quiet) return;
401
437
  this.chat('mel', 'This job did not work out. You can retry a task from its menu, try a smaller request, or use a bigger model.', undefined, 'general', jobId);
402
438
  await this._report(job, run);
403
439
  return;
@@ -406,6 +442,7 @@ export class Hive {
406
442
  ? `Finished with ${failed.length} failed tasks.`
407
443
  : st.qaPassed ? `Finished, and QA passed.${skipped ? ` ${skipped} tasks were cancelled.` : ''}` : `Finished, but QA still reports ${st.openIssues.length} issues.`;
408
444
  this.bus.emit('job.done', { summary, files: outFiles }, ev);
445
+ if (st.quiet) return;
409
446
  const url = this.previewUrl();
410
447
  this.chat('mel', `${summary} Files: ${outFiles.join(', ') || 'none'}.${url ? ' Open the Live preview to see it.' : ''}`, undefined, 'general', jobId);
411
448
  if (st.tasks && !failed.length && !skipped && st.qaPassed && !(st.playbook && st.score >= 0.6)) {
@@ -132,6 +132,8 @@ export class Scheduler {
132
132
  /** Can this brain take this turn? A brain with `only` serves just those workers; a preference wins. */
133
133
  _eligible(item, brainId, brain) {
134
134
  if (brain?.only && !brain.only.has(item.workerId)) return false;
135
+ // A turn may limit the brains it runs on (a lent turn: this machine's own local models only).
136
+ if (typeof item.accept === 'function' && !item.accept(brain, brainId)) return false;
135
137
  const pref = this.prefs.get(item.workerId);
136
138
  if (pref && pref !== brainId && this.brains.has(pref)) return false;
137
139
  return true;
@@ -171,6 +173,8 @@ export class Scheduler {
171
173
  this.bus.live('brain.stats', { brainId, tps, queue: this.waiting.length, loaded: true });
172
174
  const rec = this.prompts.get(item.turnId);
173
175
  if (rec) rec.response = String(result.text || '').slice(0, 20000);
176
+ // A turn a friend's machine answered is marked, so its tool calls wait for the host.
177
+ if (slot.brain.kind === 'remote' && result && typeof result === 'object') result.remote = { brainId, label: String(slot.brain.label || 'friend').slice(0, 80) };
174
178
  item.resolve(result);
175
179
  } catch (err) {
176
180
  const cancelled = item.signal?.aborted;
@@ -161,6 +161,9 @@ export async function runTask(ctx) {
161
161
 
162
162
  /** Files this worker read or created in this task: changing any other existing file needs a read first. */
163
163
  const known = new Set();
164
+ // Untrusted origin: a worker brought by a guest, or any turn of this task that a friend's machine
165
+ // answered. Its writes and runs then always wait for the host (src/tools/index.js, STRICT_TOOLS).
166
+ let origin = worker.origin && typeof worker.origin === 'object' ? worker.origin : null;
164
167
  let hint = '';
165
168
  let nothingAsked = false;
166
169
  for (let n = 1; n <= maxTurns; n++) {
@@ -211,6 +214,7 @@ export async function runTask(ctx) {
211
214
  continue;
212
215
  }
213
216
  invalid = 0;
217
+ if (result?.remote && (!origin || origin.kind !== 'remote')) origin = { kind: 'remote', brainId: result.remote.brainId, label: result.remote.label };
214
218
  const action = result.json;
215
219
  const key = JSON.stringify(compactAction(action));
216
220
  repeats = key === lastKey ? repeats + 1 : 0;
@@ -271,7 +275,7 @@ export async function runTask(ctx) {
271
275
  bus.emit('worker.status', { workerId: worker.id, status: 'tool', detail: `${action.tool}${action.args?.path ? ' ' + action.args.path : ''}`, taskId: task.id }, jobOpt);
272
276
  const out = await toolbox.execute(action.tool, action.args, {
273
277
  jobId: job.id, taskId: task.id, workerId: worker.id, allowed: worker.tools,
274
- preexisting: ctx.preexisting, approval: job.approval, signal
278
+ preexisting: ctx.preexisting, approval: job.approval, signal, ...(origin ? { origin } : {})
275
279
  });
276
280
  if (out.ok && (action.tool === 'write_file' || action.tool === 'edit_file')) wrote.add(String(action.args.path).replace(/^\.\//, ''));
277
281
  if (out.ok && target && ['read_file', 'write_file', 'edit_file'].includes(action.tool)) known.add(target);
package/src/demo.js CHANGED
@@ -146,7 +146,33 @@ const PLAN = {
146
146
  ]
147
147
  };
148
148
 
149
+ /** The Hive City demo task (src/city/demo.js): Design, Code, Review, Test, done. */
150
+ export const DEMO_CITY_TASK = {
151
+ title: 'Add a weekly specials section',
152
+ detail: 'Show the three specials of this week on the bakery page, between the breads and the opening hours.'
153
+ };
154
+
155
+ const SPECIALS = ` <section class="specials">
156
+ <h2>This week</h2>
157
+ <ul>
158
+ <li>Pumpkin loaf, on Tuesday</li>
159
+ <li>Fig and walnut rye, on Thursday</li>
160
+ <li>Cardamom buns, on Saturday</li>
161
+ </ul>
162
+ </section>
163
+ <section class="hours">`;
164
+
165
+ const DESIGN = {
166
+ spec: 'In index.html, add a section with class "specials" right before the opening hours: an h2 "This week" and a list of three specials, each with its day. Reuse the existing card look; no new files.',
167
+ criteria: ['index.html has a "This week" section before the opening hours', 'The section lists three specials, each with a day', 'The page still passes the static checks']
168
+ };
169
+
149
170
  const SCRIPTS = {
171
+ [DEMO_CITY_TASK.title]: [
172
+ { tool: 'read_file', args: { path: 'index.html' } },
173
+ { tool: 'edit_file', args: { path: 'index.html', search: ' <section class="hours">', replace: SPECIALS } },
174
+ { tool: 'done', args: { summary: 'Added the weekly specials section before the opening hours.' } }
175
+ ],
150
176
  'Set the look': [
151
177
  { tool: 'say', args: { text: 'Going for warm crust colors and a lot of air around the text.' } },
152
178
  { tool: 'write_file', args: { path: 'style.css', content: STYLE } },
@@ -201,6 +227,8 @@ const REPORT = {
201
227
 
202
228
  /** The demo responder: the brief and the plan for Mel, a fixed list of actions per task, then the report. */
203
229
  export function demoRespond(messages, options) {
230
+ if (options.schema?.properties?.spec) return DESIGN;
231
+ if (options.schema?.properties?.approved) return { approved: true, issues: [] };
204
232
  if (options.schema?.properties?.goal) return BRIEF;
205
233
  if (options.schema?.properties?.improvedPrompt) return REPORT;
206
234
  if (options.schema?.properties?.tasks) return PLAN;
@@ -214,8 +242,8 @@ export function demoRespond(messages, options) {
214
242
 
215
243
  export function createDemoBrain(opts = {}) {
216
244
  return createFakeBrain({
217
- id: 'demo',
218
- label: 'Demo script (no model)',
245
+ id: opts.id || 'demo',
246
+ label: opts.label || 'Demo script (no model)',
219
247
  model: 'demo script',
220
248
  respond: demoRespond,
221
249
  delayMs: opts.delayMs ?? 400,
@@ -1,5 +1,8 @@
1
- // Parent side of the extension sandbox: one shared child process for every extension, started
2
- // on the first tool call and stopped after a quiet minute, so idle extensions cost no memory.
1
+ // Parent side of the extension sandbox: one child process per extension, started on its first
2
+ // tool call and stopped after a quiet minute, so idle extensions cost no memory.
3
+ // Each child runs only its own extension's code, and the parent binds every message from a child
4
+ // to the extension it started that child for: an id sent by the child is never trusted, so one
5
+ // extension cannot use another one's granted capabilities.
3
6
  import { spawn } from 'node:child_process';
4
7
  import path from 'node:path';
5
8
  import { fileURLToPath } from 'node:url';
@@ -20,122 +23,144 @@ export class Sandbox {
20
23
  this.timeoutMs = opts.timeoutMs ?? CALL_TIMEOUT;
21
24
  /** @type {Map<string, { files: Record<string,string>, entry: string }>} code to load into a fresh child */
22
25
  this.sources = new Map();
23
- this.child = null;
24
- this.loaded = new Map();
25
- this.pending = new Map();
26
+ /** @type {Map<string, { child: any, ready: Promise<void>, tools: string[] | null, pending: Map<string, any>, idle: any, isolated: boolean }>} */
27
+ this.children = new Map();
26
28
  this.seq = 0;
27
- this.idle = null;
28
- this.isolated = false;
29
29
  }
30
30
 
31
- /** Remembers an extension's code; it is evaluated in the child on its first call. */
31
+ /** True when a running child runs under Node's permission model. */
32
+ get isolated() {
33
+ for (const c of this.children.values()) if (c.isolated) return true;
34
+ return false;
35
+ }
36
+
37
+ /** Remembers an extension's code; it is evaluated in its own child on its first call (a reload reuses that child). */
32
38
  set(extId, files, entry) {
33
39
  this.sources.set(extId, { files, entry });
34
- this.loaded.delete(extId);
35
- if (this.child) this._send({ t: 'unload', extId }).catch(() => {});
40
+ const c = this.children.get(extId);
41
+ if (c) {
42
+ c.tools = null;
43
+ this._send(extId, c, { t: 'unload', extId }).catch(() => {});
44
+ }
36
45
  }
37
46
 
47
+ /** Forgets an extension's code and stops its child, or unloads it there while a call is under way (a reload). */
38
48
  remove(extId) {
39
49
  this.sources.delete(extId);
40
- this.loaded.delete(extId);
41
- if (this.child) this._send({ t: 'unload', extId }).catch(() => {});
50
+ const c = this.children.get(extId);
51
+ if (!c) return;
52
+ if (c.starting || c.pending.size) {
53
+ c.tools = null;
54
+ this._send(extId, c, { t: 'unload', extId }).catch(() => {});
55
+ return;
56
+ }
57
+ this._stopOne(extId);
42
58
  }
43
59
 
44
60
  /** Loads the code now and returns the exported tool names (used to check a manifest). */
45
61
  async exports(extId) {
46
- await this._start();
47
- return this._ensure(extId);
62
+ const c = await this._start(extId);
63
+ return this._ensure(extId, c);
48
64
  }
49
65
 
50
66
  async call(extId, tool, args) {
51
- await this._start();
52
- await this._ensure(extId);
53
- return this._send({ t: 'call', extId, tool, args });
67
+ const c = await this._start(extId);
68
+ await this._ensure(extId, c);
69
+ return this._send(extId, c, { t: 'call', extId, tool, args });
54
70
  }
55
71
 
56
- async _ensure(extId) {
57
- if (this.loaded.has(extId)) return this.loaded.get(extId);
72
+ async _ensure(extId, c) {
73
+ if (c.tools) return c.tools;
58
74
  const src = this.sources.get(extId);
59
75
  if (!src) throw new Error(`extension ${extId} has no code`);
60
- const r = await this._send({ t: 'load', extId, files: src.files, entry: src.entry });
61
- this.loaded.set(extId, r.tools);
76
+ const r = await this._send(extId, c, { t: 'load', extId, files: src.files, entry: src.entry });
77
+ c.tools = r.tools;
62
78
  return r.tools;
63
79
  }
64
80
 
65
- _start() {
66
- if (this.child) { this._touch(); return this.ready; }
81
+ async _start(extId) {
82
+ if (!this.sources.has(extId)) throw new Error(`extension ${extId} has no code`);
83
+ const have = this.children.get(extId);
84
+ if (have) { this._touch(extId, have); await have.ready; return have; }
67
85
  const flag = permissionFlag();
68
86
  const args = [];
69
87
  if (flag) args.push(flag, `--allow-fs-read=${CHILD}`);
70
88
  args.push('--experimental-vm-modules', '--no-warnings', '--max-old-space-size=64', '--disallow-code-generation-from-strings', CHILD);
71
89
  const child = spawn(process.execPath, args, { stdio: ['ignore', 'ignore', 'pipe', 'ipc'], windowsHide: true, env: { NODE_OPTIONS: '' } });
72
- this.child = child;
73
- this.loaded = new Map();
90
+ const c = { child, ready: null, tools: null, pending: new Map(), idle: null, isolated: false, starting: true };
91
+ this.children.set(extId, c);
74
92
  let stderr = '';
75
93
  child.stderr.on('data', (d) => { stderr = (stderr + d).slice(-2000); });
76
- this.ready = new Promise((resolve, reject) => {
94
+ c.ready = new Promise((resolve, reject) => {
77
95
  const t = setTimeout(() => reject(new Error('the extension sandbox did not start')), 10_000);
78
- child.once('message', (m) => { clearTimeout(t); this.isolated = !!m?.permission; resolve(); });
96
+ child.once('message', (m) => { clearTimeout(t); c.isolated = !!m?.permission; resolve(); });
79
97
  child.once('exit', (code) => { clearTimeout(t); reject(new Error(`the extension sandbox stopped (${code}): ${stderr.trim().slice(0, 300)}`)); });
80
98
  });
81
- child.on('message', (m) => this._onMessage(m));
99
+ c.ready.then(() => { c.starting = false; }, () => { c.starting = false; });
100
+ // Every message of this child is bound to extId, whatever id the child puts in it.
101
+ child.on('message', (m) => this._onMessage(extId, c, m));
82
102
  child.on('error', () => { /* a send after the child stopped; the pending calls fail below */ });
83
103
  child.on('exit', () => {
84
- if (this.child === child) this.child = null;
85
- for (const p of this.pending.values()) { clearTimeout(p.timer); p.reject(new Error('the extension sandbox stopped')); }
86
- this.pending.clear();
104
+ if (this.children.get(extId) === c) this.children.delete(extId);
105
+ clearTimeout(c.idle);
106
+ for (const p of c.pending.values()) { clearTimeout(p.timer); p.reject(new Error('the extension sandbox stopped')); }
107
+ c.pending.clear();
87
108
  });
88
109
  child.unref();
89
110
  child.channel?.unref?.();
90
- this._touch();
91
- return this.ready;
111
+ this._touch(extId, c);
112
+ await c.ready;
113
+ return c;
92
114
  }
93
115
 
94
- _touch() {
95
- clearTimeout(this.idle);
96
- this.idle = setTimeout(() => this.stop(), this.idleMs);
97
- this.idle.unref?.();
116
+ _touch(extId, c) {
117
+ clearTimeout(c.idle);
118
+ c.idle = setTimeout(() => this._stopOne(extId), this.idleMs);
119
+ c.idle.unref?.();
98
120
  }
99
121
 
100
- _send(msg) {
122
+ _send(extId, c, msg) {
101
123
  const id = `m${++this.seq}`;
102
- const child = this.child;
103
- if (!child) return Promise.reject(new Error('the extension sandbox is not running'));
104
- this._touch();
124
+ if (this.children.get(extId) !== c) return Promise.reject(new Error('the extension sandbox is not running'));
125
+ this._touch(extId, c);
105
126
  return new Promise((resolve, reject) => {
106
127
  const timer = setTimeout(() => {
107
- this.pending.delete(id);
128
+ c.pending.delete(id);
108
129
  reject(new Error(`the extension took longer than ${Math.round(this.timeoutMs / 1000)} s and was stopped`));
109
- this.stop();
130
+ this._stopOne(extId);
110
131
  }, this.timeoutMs);
111
- this.pending.set(id, { resolve, reject, timer });
112
- child.send({ ...msg, id });
132
+ c.pending.set(id, { resolve, reject, timer });
133
+ try { c.child.send({ ...msg, id }); } catch (err) { clearTimeout(timer); c.pending.delete(id); reject(err); }
113
134
  });
114
135
  }
115
136
 
116
- async _onMessage(m) {
137
+ async _onMessage(extId, c, m) {
117
138
  if (!m || typeof m !== 'object') return;
118
139
  if (m.t === 'reply') {
119
- const p = this.pending.get(m.id);
140
+ const p = c.pending.get(m.id);
120
141
  if (!p) return;
121
- this.pending.delete(m.id);
142
+ c.pending.delete(m.id);
122
143
  clearTimeout(p.timer);
123
144
  if (m.ok) p.resolve(m.result); else p.reject(new Error(m.error));
124
145
  return;
125
146
  }
126
- if (m.t === 'log') { this.onLog(m.extId, m.level, m.text); return; }
147
+ if (m.t === 'log') { this.onLog(extId, m.level, m.text); return; }
127
148
  if (m.t === 'cap') {
128
149
  let reply;
129
- try { reply = { t: 'capResult', id: m.id, ok: true, result: await this.onCapability(m.extId, m.cap, m.args) }; } catch (err) { reply = { t: 'capResult', id: m.id, ok: false, error: String(err?.message || err) }; }
130
- try { this.child?.send(reply); } catch { /* stopped meanwhile */ }
150
+ try { reply = { t: 'capResult', id: m.id, ok: true, result: await this.onCapability(extId, m.cap, m.args) }; } catch (err) { reply = { t: 'capResult', id: m.id, ok: false, error: String(err?.message || err) }; }
151
+ try { c.child?.send(reply); } catch { /* stopped meanwhile */ }
131
152
  }
132
153
  }
133
154
 
155
+ _stopOne(extId) {
156
+ const c = this.children.get(extId);
157
+ if (!c) return;
158
+ this.children.delete(extId);
159
+ clearTimeout(c.idle);
160
+ try { c.child.kill(); } catch { /* gone */ }
161
+ }
162
+
134
163
  stop() {
135
- clearTimeout(this.idle);
136
- const c = this.child;
137
- this.child = null;
138
- this.loaded = new Map();
139
- if (c) { try { c.kill(); } catch { /* gone */ } }
164
+ for (const id of [...this.children.keys()]) this._stopOne(id);
140
165
  }
141
166
  }
package/src/index.js CHANGED
@@ -3,7 +3,7 @@ import fs from 'node:fs';
3
3
  import os from 'node:os';
4
4
  import path from 'node:path';
5
5
  import { pathToFileURL } from 'node:url';
6
- import { EventBus, initHome } from './bus.js';
6
+ import { EventBus, initHome, hasRealLog } from './bus.js';
7
7
  import { Scheduler } from './crew/scheduler.js';
8
8
  import { Hive } from './crew/engine.js';
9
9
  import { ToolBox, Workspace } from './tools/index.js';
@@ -15,6 +15,8 @@ import { createDemoBrain, DEMO_NOTICE, DEMO_REQUEST } from './demo.js';
15
15
  import { runDoctor } from './doctor.js';
16
16
  import { PROTOCOL } from './replay/reduce.js';
17
17
  import { MemoryStore, attachMemory } from './memory/index.js';
18
+ import { City } from './city/index.js';
19
+ import { runCityDemo } from './city/demo.js';
18
20
 
19
21
  export const VERSION = JSON.parse(fs.readFileSync(path.join(PACKAGE_ROOT, 'package.json'), 'utf8')).version;
20
22
 
@@ -34,6 +36,8 @@ export function cacheHome() {
34
36
  */
35
37
  export async function startHive(opts) {
36
38
  const dir = path.resolve(opts.dir);
39
+ // A demo never writes into the log of a real project (CHANGELOG 0.2.1).
40
+ if (opts.demo && hasRealLog(dir)) throw Object.assign(new Error(`the demo will not run in ${dir}: it holds a real hivedesk project`), { code: 'demo_dir' });
37
41
  const paths = initHome(dir);
38
42
  const home = opts.home || cacheHome();
39
43
  const log = opts.log || (() => {});
@@ -56,9 +60,21 @@ export async function startHive(opts) {
56
60
  server = createServer({
57
61
  bus, hive, scheduler, approvals, playbooks, toolbox, brains, memory,
58
62
  doctor: () => runDoctor({ home, model: opts.flags?.model }),
59
- token: opts.token, port: opts.port, uiDir: opts.uiDir, demo: !!opts.demo, lend: !!opts.lend, version: VERSION, dir
63
+ token: opts.token, port: opts.port, uiDir: opts.uiDir, demo: !!opts.demo, lend: !!opts.lend, version: VERSION, dir, city: opts.city !== false
60
64
  });
61
65
 
66
+ // Hive City (src/city/, CITY-PROTOCOL.md): agents, rooms, the task bus and machines on the same log.
67
+ let city = null;
68
+ if (opts.city !== false) {
69
+ try {
70
+ city = new City({ bus, hive, scheduler, toolbox, home, projectDir: paths.city, version: VERSION });
71
+ city.start();
72
+ city.register(server);
73
+ } catch (err) {
74
+ log(`city failed to start: ${err.message}`);
75
+ }
76
+ }
77
+
62
78
  // Optional lend plug-in (PROTOCOL.md section 6). The engine works without it.
63
79
  const lendEntry = path.join(PACKAGE_ROOT, 'src', 'lend', 'index.js');
64
80
  if (fs.existsSync(lendEntry)) {
@@ -81,6 +97,7 @@ export async function startHive(opts) {
81
97
 
82
98
  let demoTimer = null;
83
99
  let demoFallback = null;
100
+ const demoCtrl = new AbortController();
84
101
  if (opts.demo) {
85
102
  scheduler.addBrain(createDemoBrain({ delayMs: opts.demoDelayMs, tokenDelayMs: opts.demoDelayMs === 0 ? 0 : undefined }));
86
103
  bus.emit('brain.status', { state: 'ready', backend: 'fake', model: 'demo script', detail: 'demo: no model is running' });
@@ -94,6 +111,10 @@ export async function startHive(opts) {
94
111
  clearInterval(demoTimer);
95
112
  clearTimeout(demoFallback);
96
113
  hive.createJob({ request: DEMO_REQUEST });
114
+ if (city) {
115
+ const stepMs = opts.demoDelayMs === 0 ? 0 : (opts.demoCityStepMs ?? 1800);
116
+ setTimeout(() => { runCityDemo({ city, scheduler, bus, stepMs, signal: demoCtrl.signal }).catch((err) => log(`city demo stopped: ${err.message}`)); }, stepMs ? 1500 : 0).unref?.();
117
+ }
97
118
  };
98
119
  demoTimer = setInterval(() => { if (server.clients.size) { clearInterval(demoTimer); setTimeout(go, 1500).unref?.(); } }, 300);
99
120
  demoFallback = setTimeout(go, 8000);
@@ -108,11 +129,13 @@ export async function startHive(opts) {
108
129
  }
109
130
 
110
131
  return {
111
- bus, hive, scheduler, approvals, playbooks, toolbox, server, brains, paths, home, memory,
132
+ bus, hive, scheduler, approvals, playbooks, toolbox, server, brains, paths, home, memory, city,
112
133
  url: server.url,
113
134
  async close() {
114
135
  if (demoTimer) clearInterval(demoTimer);
115
136
  if (demoFallback) clearTimeout(demoFallback);
137
+ demoCtrl.abort();
138
+ await city?.close();
116
139
  extensions?.close();
117
140
  await hive.close();
118
141
  await brains?.close();