hivedesk 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.
package/src/cli.js CHANGED
@@ -7,6 +7,7 @@ import { spawn } from 'node:child_process';
7
7
  import { fileURLToPath } from 'node:url';
8
8
  import net from 'node:net';
9
9
  import crypto from 'node:crypto';
10
+ import { hasRealLog } from './bus.js';
10
11
 
11
12
  const HELP = `hivedesk: a crew of AI workers that build real files on your machine with a local model.
12
13
 
@@ -24,7 +25,9 @@ Usage: npx hivedesk [options]
24
25
  --no-city run without Hive City (agents, rooms and the task bus); the 0.1 desktop works the same
25
26
  --cpu do not use the GPU
26
27
  --ctx <n> context size for the local model (default: up to 8192)
27
- --demo scripted demo, no model; every event is labeled as a demo
28
+ --demo scripted demo, no model; every event is labeled as a demo. It runs in a
29
+ temporary folder with its own home and never writes into a project
30
+ --demo-dir <folder> run the demo in this folder instead (never one with a real project log)
28
31
  --lend lend this machine's model to a paired friend (opens the Lend screen)
29
32
  --join <link|words> open the desktop with "Use a friend's PC" filled in with these six words
30
33
  --yes skip the setup questions (the saved setup, or the recommended defaults)
@@ -34,9 +37,11 @@ Usage: npx hivedesk [options]
34
37
 
35
38
  First run: see FIRST-RUN.md. Cache folder: ~/.hivedesk (or HIVEDESK_HOME).`;
36
39
 
40
+ export { hasRealLog };
41
+
37
42
  export function parseArgs(argv) {
38
43
  const o = { open: true, download: true };
39
- const takes = new Set(['dir', 'port', 'model', 'brain', 'url', 'ctx', 'join']);
44
+ const takes = new Set(['dir', 'port', 'model', 'brain', 'url', 'ctx', 'join', 'demo-dir']);
40
45
  for (let i = 0; i < argv.length; i++) {
41
46
  const a = argv[i];
42
47
  if (!a.startsWith('--')) throw new Error(`unexpected argument: ${a}`);
@@ -67,6 +72,27 @@ export function parseArgs(argv) {
67
72
  return o;
68
73
  }
69
74
 
75
+ /**
76
+ * Where --demo runs: a new temporary folder; --demo-dir <folder> when given. A --dir that is a real
77
+ * project (a folder with files in it) is refused, so the demo never writes into a project's log.
78
+ */
79
+ export function demoFolder(args, { tmp = os.tmpdir(), cwd = process.cwd() } = {}) {
80
+ if (args['demo-dir']) {
81
+ const dir = path.resolve(cwd, args['demo-dir']);
82
+ if (hasRealLog(dir)) throw new Error(`${dir} holds a real hivedesk project; the demo needs a folder of its own`);
83
+ return dir;
84
+ }
85
+ if (args.dir) {
86
+ const dir = path.resolve(cwd, args.dir);
87
+ let entries = [];
88
+ try { entries = fs.readdirSync(dir); } catch { entries = []; }
89
+ const demoOnly = entries.length === 1 && entries[0] === '.hivedesk' && fs.existsSync(path.join(dir, '.hivedesk', 'events.jsonl')) && !hasRealLog(dir);
90
+ if (entries.length && !demoOnly) throw new Error(`--demo will not run in ${dir}: the folder is not empty. Leave out --dir for a temporary demo folder, or pass --demo-dir <folder>`);
91
+ return dir;
92
+ }
93
+ return fs.mkdtempSync(path.join(tmp, 'hivedesk-demo-'));
94
+ }
95
+
70
96
  /** Six words from a share link (#w=...) or from words separated by spaces or dashes. */
71
97
  export function joinWords(input) {
72
98
  const s = String(input || '');
@@ -228,16 +254,26 @@ async function main() {
228
254
  if (setup.open === false) args.open = false;
229
255
  }
230
256
  }
231
- if (args.demo && !args.dir) dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hivedesk-demo-'));
257
+ if (args['demo-dir'] && !args.demo) {
258
+ console.error('hivedesk: --demo-dir goes with --demo');
259
+ process.exit(2);
260
+ }
261
+ // The demo never touches a real project or the real ~/.hivedesk: its own folder and its own home.
262
+ let demoHome;
263
+ if (args.demo) {
264
+ try { dir = demoFolder(args); } catch (err) { console.error(`hivedesk: ${err.message}`); process.exit(2); }
265
+ demoHome = fs.mkdtempSync(path.join(os.tmpdir(), 'hivedesk-demo-home-'));
266
+ }
232
267
  const progress = makeProgress();
233
268
  const log = (line) => { progress(null); console.log(` ${line}`); };
234
- console.log(`hivedesk ${VERSION}${args.demo ? ' (demo: no model, scripted crew)' : ''}${args.lend ? ' (lend mode)' : ''}`);
269
+ console.log(`hivedesk ${VERSION}${args.demo ? ' (DEMO: no model, scripted crew, a separate demo folder)' : ''}${args.lend ? ' (lend mode)' : ''}`);
235
270
  const port = args.port !== undefined ? args.port : await stablePort(4174);
236
271
  const app = await startHive({
237
272
  dir,
238
273
  port,
239
274
  token: args.demo ? undefined : loadToken(cacheHome(), !!args['new-token']),
240
275
  demo: !!args.demo,
276
+ ...(demoHome ? { home: demoHome } : {}),
241
277
  lend: !!args.lend,
242
278
  city: args.city !== false,
243
279
  log,
@@ -249,7 +285,7 @@ async function main() {
249
285
  }
250
286
  });
251
287
  if (setup) app.hive.setSettings({ approvalMode: setup.approvalMode, crew: setup.crew });
252
- console.log(` folder: ${path.join(dir, '.hivedesk')}`);
288
+ console.log(` ${args.demo ? 'demo folder' : 'folder'}: ${path.join(dir, '.hivedesk')}`);
253
289
  console.log(` open: ${app.url}`);
254
290
  const openUrl = startUrl(app.server.port, app.server.token, args);
255
291
  if (openUrl !== app.url) console.log(` ${openUrl}`);
@@ -1,11 +1,14 @@
1
1
  // Code together and the Code editor, server side. Loaded by the lend plug-in (src/lend/index.js).
2
2
  // files.write { path, content, as? } save a file from the editor through the engine's tools.
3
3
  // Without `as` it is the person at this PC saving their own file: it runs at once.
4
- // With `as: { id, name }` it is a guest's save, forwarded by the host's browser: it goes
5
- // through approval mode like a crew write of an existing file, so the host sees the diff
6
- // and approves or rejects it.
4
+ // With `as: { id, name, role }` it is a guest's save, forwarded by the host's browser: it always
5
+ // waits for the host's approval (new files too, whatever the approval mode), so the host sees
6
+ // the diff and approves or rejects it.
7
7
  // Guests never reach this server directly: their commands arrive through the host's browser,
8
- // which checks their role first (ui/lend/collab/roles.js).
8
+ // which checks their role first (ui/lend/collab/roles.js); the engine checks it again
9
+ // (src/collab/policy.js), so a viewer cannot save.
10
+
11
+ import { guestOf } from './policy.js';
9
12
 
10
13
  export class CommandError extends Error {
11
14
  constructor(code, message) {
@@ -28,9 +31,10 @@ export async function writeFile(toolbox, data) {
28
31
  const path = cleanPath(data?.path);
29
32
  if (typeof data?.content !== 'string') throw new CommandError('bad_request', 'content must be text');
30
33
  if (Buffer.byteLength(data.content) > MAX) throw new CommandError('bad_request', 'file too large (max 512 KB)');
31
- const guest = data.as && typeof data.as === 'object' ? { id: String(data.as.id || 'guest').slice(0, 24), name: String(data.as.name || 'Guest').slice(0, 40) } : null;
34
+ const guest = guestOf(data);
35
+ if (guest && guest.role !== 'collaborator') throw new CommandError('forbidden', 'a viewer cannot save files');
32
36
  const ctx = guest
33
- ? { workerId: `guest:${guest.name}`, approval: true, preexisting: new Set(toolbox.ws.list().map((f) => f.path)) }
37
+ ? { workerId: `guest:${guest.name}`, approval: true, preexisting: new Set(toolbox.ws.list().map((f) => f.path)), origin: { kind: 'guest', id: guest.id, label: guest.name } }
34
38
  : { workerId: 'user', approval: false };
35
39
  const r = await toolbox.execute('write_file', { path, content: data.content }, ctx);
36
40
  if (!r.ok) throw new CommandError(/rejected/.test(r.error) ? 'rejected' : 'bad_request', r.error);
@@ -0,0 +1,48 @@
1
+ // Engine side guest policy (0.2.1). A guest command reaches this engine through the host's
2
+ // browser with `as: { id, name, role }`. The browser checks the role first (ui/lend/collab/roles.js),
3
+ // and the engine checks it again here, so a bug in the browser cannot widen what a guest may do.
4
+ // A missing or unknown role counts as a viewer.
5
+ //
6
+ // viewer reads and chats
7
+ // collaborator also creates tasks and jobs, edits files (through the host's approval) and
8
+ // brings its own building and agents into the city
9
+ // host everything; never a guest
10
+ //
11
+ // Hiring agents, changing an agent's tools, rooms, settings, models, providers and brains stay
12
+ // with the host.
13
+
14
+ export const GUEST_ROLES = Object.freeze(['viewer', 'collaborator']);
15
+
16
+ const READ = ['ping', 'events.since', 'replay.at', 'replay.marks', 'files.list', 'files.read', 'playbook.list', 'city.state', 'city.sync', 'city.presence'];
17
+ const VIEWER = new Set([...READ, 'chat.send']);
18
+ const COLLABORATOR = new Set([
19
+ ...VIEWER,
20
+ 'job.create', 'job.cancel', 'approval.resolve', 'task.retry', 'task.reassign', 'task.cancel', 'files.write',
21
+ 'city.task.create', 'city.task.assign', 'city.task.move', 'city.task.approve', 'city.task.reject', 'city.task.retry', 'city.task.cancel',
22
+ 'city.machine.join', 'city.machine.update', 'city.machine.leave', 'city.agent.update', 'city.agent.move', 'city.agent.retire', 'city.agent.wake',
23
+ 'city.borrow.request', 'city.borrow.answer', 'city.borrow.stop'
24
+ ]);
25
+
26
+ const clip = (v, n) => String(v ?? '').trim().slice(0, n);
27
+
28
+ /** The guest behind a command, or null when the person at this PC sent it. */
29
+ export function guestOf(data) {
30
+ const as = data && typeof data === 'object' ? data.as : null;
31
+ if (!as || typeof as !== 'object') return null;
32
+ const id = clip(as.id, 24) || 'guest';
33
+ const role = GUEST_ROLES.includes(as.role) ? as.role : 'viewer';
34
+ return { id, name: clip(as.name, 40) || 'Guest', role, owner: `peer:${id}` };
35
+ }
36
+
37
+ /** True when a guest with this role may send this command type. */
38
+ export function guestMay(role, type) {
39
+ if (role === 'collaborator') return COLLABORATOR.has(type);
40
+ return VIEWER.has(type);
41
+ }
42
+
43
+ /** Throws a forbidden error when this guest may not send this command. */
44
+ export function checkGuest(guest, type, makeError) {
45
+ if (!guest || guestMay(guest.role, type)) return;
46
+ const message = guest.role === 'viewer' ? `a viewer cannot use ${type}; the host can make you a collaborator` : `guests cannot use ${type}`;
47
+ throw makeError ? makeError('forbidden', message) : Object.assign(new Error(message), { code: 'forbidden' });
48
+ }
@@ -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);
@@ -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';
@@ -36,6 +36,8 @@ export function cacheHome() {
36
36
  */
37
37
  export async function startHive(opts) {
38
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' });
39
41
  const paths = initHome(dir);
40
42
  const home = opts.home || cacheHome();
41
43
  const log = opts.log || (() => {});
package/src/lend/guard.js CHANGED
@@ -2,6 +2,11 @@
2
2
  // --lend). The friend's browser already checks every request, but the server checks again
3
3
  // before the local brain runs: same frame limits, same rate limit, one turn at a time, and
4
4
  // nothing runs after lending was stopped. Only the counts are logged, never the prompt text.
5
+ //
6
+ // A grant (0.2.1) is what the friend agreed to lend in one pairing: a lease of at most `minutes`
7
+ // and `turns`, the models allowed (empty: any local model) and whether a cloud provider key of the
8
+ // friend may be used (off unless the friend turns it on for this grant). A lent turn never runs
9
+ // on a brain that is itself borrowed. Cancel and stop abort the running turn.
5
10
 
6
11
  import { LIMITS, readMessages, readOptions, readResult, promptChars } from '../../ui/lend/core/frames.js';
7
12
  import { RateLimiter, DEFAULT_RATE } from '../../ui/lend/core/ratelimit.js';
@@ -14,16 +19,53 @@ export class GuardError extends Error {
14
19
  }
15
20
  }
16
21
 
22
+ export const DEFAULT_GRANT = Object.freeze({ minutes: 60, turns: 200, models: Object.freeze([]), cloud: false });
23
+ const MAX_GRANT = { minutes: 24 * 60, turns: 5000 };
24
+
25
+ const clampInt = (v, min, max, dflt) => {
26
+ const n = Math.round(Number(v));
27
+ return Number.isFinite(n) ? Math.min(Math.max(n, min), max) : dflt;
28
+ };
29
+
30
+ /** A clean grant from what the friend asked for, over the defaults. */
31
+ export function cleanGrant(g = {}, base = DEFAULT_GRANT) {
32
+ const src = g && typeof g === 'object' ? g : {};
33
+ const models = Array.isArray(src.models) ? src.models : base.models;
34
+ return {
35
+ minutes: clampInt(src.minutes, 1, MAX_GRANT.minutes, base.minutes),
36
+ turns: clampInt(src.turns, 1, MAX_GRANT.turns, base.turns),
37
+ models: [...new Set(models.map((m) => String(m ?? '').trim().slice(0, 120)).filter(Boolean))].slice(0, 16),
38
+ cloud: typeof src.cloud === 'boolean' ? src.cloud : !!base.cloud
39
+ };
40
+ }
41
+
42
+ /** The model name of a brain, for the allowlist. */
43
+ export function brainModel(brain) {
44
+ try { return String(brain?.info?.()?.model || brain?.model || '').trim(); } catch { return ''; }
45
+ }
46
+
47
+ /** Can this brain take a lent turn under this grant? */
48
+ export function lendable(brain, grant) {
49
+ if (!brain || brain.kind === 'remote') return false;
50
+ if (brain.kind === 'cloud' && !grant.cloud) return false;
51
+ if (grant.models.length && !grant.models.includes(brainModel(brain))) return false;
52
+ return true;
53
+ }
54
+
17
55
  /**
18
- * chat: (messages, options) => Promise<ChatResult>, the friend's local brain.
56
+ * chat: (messages, options, { signal, accept }) => Promise<ChatResult>, the friend's local brain.
57
+ * chat.brains, when present, lists the brains it may pick from (to refuse early when none fits).
19
58
  * emit: (type, data) => void, appends a lend.* event.
20
59
  */
21
- export function createLendGuard({ chat, emit = () => {}, limits = LIMITS, rate = DEFAULT_RATE, now = () => Date.now() }) {
60
+ export function createLendGuard({ chat, emit = () => {}, limits = LIMITS, rate = DEFAULT_RATE, now = () => Date.now(), grant = DEFAULT_GRANT, setTimer = setTimeout, clearTimer = clearTimeout }) {
22
61
  const limiter = new RateLimiter({ ...rate, now });
23
62
  let lending = true;
24
- let busy = false;
63
+ let busy = null; // { requestId, ctrl }
25
64
  let served = 0;
26
65
  let refused = 0;
66
+ let current = cleanGrant(grant);
67
+ let lease = null; // { startedAt, expiresAt, turns, ended: null | 'time' | 'turns' }
68
+ let leaseTimer = null;
27
69
 
28
70
  const refuse = (code, message, extra) => {
29
71
  refused++;
@@ -31,6 +73,31 @@ export function createLendGuard({ chat, emit = () => {}, limits = LIMITS, rate =
31
73
  throw new GuardError(code, message);
32
74
  };
33
75
 
76
+ const endLease = (reason) => {
77
+ if (!lease || lease.ended) return;
78
+ lease.ended = reason;
79
+ clearTimer(leaseTimer);
80
+ leaseTimer = null;
81
+ busy?.ctrl.abort();
82
+ emit('lend.expired', { reason, turns: lease.turns });
83
+ };
84
+
85
+ const startLease = () => {
86
+ clearTimer(leaseTimer);
87
+ const t = now();
88
+ lease = { startedAt: t, expiresAt: t + current.minutes * 60_000, turns: 0, ended: null };
89
+ leaseTimer = setTimer(() => endLease('time'), current.minutes * 60_000);
90
+ leaseTimer?.unref?.();
91
+ };
92
+
93
+ const dropLease = () => {
94
+ clearTimer(leaseTimer);
95
+ leaseTimer = null;
96
+ lease = null;
97
+ };
98
+
99
+ const accept = (brain) => lendable(brain, current);
100
+
34
101
  async function handle(data) {
35
102
  if (typeof chat !== 'function') throw new GuardError('not_lending', 'No local brain to lend');
36
103
  let messages;
@@ -44,33 +111,74 @@ export function createLendGuard({ chat, emit = () => {}, limits = LIMITS, rate =
44
111
  const chars = promptChars(messages);
45
112
  const extra = { messages: messages.length, chars };
46
113
  if (!lending) return refuse('stopped', 'Lending is stopped', extra);
114
+ if (!lease) startLease();
115
+ if (!lease.ended && now() >= lease.expiresAt) endLease('time');
116
+ if (!lease.ended && lease.turns >= current.turns) endLease('turns');
117
+ if (lease.ended) return refuse('expired', `This lend ended (${lease.ended === 'time' ? `${current.minutes} minutes` : `${current.turns} turns`}); pair again to lend more`, extra);
47
118
  if (busy) return refuse('busy', 'One request at a time', extra);
119
+ if (typeof chat.brains === 'function' && !chat.brains().some(accept)) {
120
+ return refuse('no_model', current.cloud ? 'No model on this PC is allowed for lending' : 'No local model on this PC is allowed for lending (cloud keys are not lent)', extra);
121
+ }
48
122
  const gate = limiter.take(chars);
49
123
  if (!gate.ok) return refuse('rate_limited', `Rate limit reached (${gate.reason}), retry in ${Math.ceil(gate.retryInMs / 1000)} s`, extra);
50
- busy = true;
124
+ const job = { requestId: typeof data?.requestId === 'string' ? data.requestId.slice(0, 64) : null, ctrl: new AbortController() };
125
+ busy = job;
126
+ lease.turns++;
51
127
  const started = now();
52
128
  try {
53
- const result = readResult(await chat(messages, options), limits);
129
+ const raw = await chat(messages, options, { signal: job.ctrl.signal, accept });
130
+ if (job.ctrl.signal.aborted) throw new GuardError('cancelled', 'The request was cancelled');
131
+ const result = readResult(raw, limits);
54
132
  served++;
55
133
  emit('lend.served', { ...extra, completionTokens: result.completionTokens, ms: result.ms || now() - started });
56
134
  return result;
135
+ } catch (err) {
136
+ if (job.ctrl.signal.aborted) {
137
+ emit('lend.cancelled', extra);
138
+ throw err instanceof GuardError ? err : new GuardError('cancelled', 'The request was cancelled');
139
+ }
140
+ throw err;
57
141
  } finally {
58
- busy = false;
142
+ if (busy === job) busy = null;
59
143
  }
60
144
  }
61
145
 
62
146
  return {
63
147
  handle,
148
+ /** Aborts the running turn (when requestId is missing or matches it). */
149
+ cancel(requestId) {
150
+ if (!busy) return false;
151
+ if (requestId && busy.requestId && busy.requestId !== requestId) return false;
152
+ busy.ctrl.abort();
153
+ return true;
154
+ },
64
155
  stop(reason = 'stopped') {
156
+ busy?.ctrl.abort();
65
157
  if (!lending) return;
66
158
  lending = false;
159
+ dropLease();
67
160
  emit('lend.stopped', { reason });
68
161
  },
69
162
  resume() {
70
163
  if (lending) return;
71
164
  lending = true;
165
+ dropLease();
72
166
  emit('lend.resumed', {});
73
167
  },
74
- status: () => ({ lending, busy, served, refused, usage: limiter.usage(), perMinute: limiter.perMinute, limits: { promptChars: limits.promptChars, maxTokens: limits.maxTokens } }),
168
+ /** Sets what the next lease lends (minutes, turns, models, cloud); a running lease starts over. */
169
+ setGrant(g) {
170
+ current = cleanGrant(g, current);
171
+ dropLease();
172
+ emit('lend.grant', { minutes: current.minutes, turns: current.turns, models: current.models.length, cloud: current.cloud });
173
+ return { ...current, models: [...current.models] };
174
+ },
175
+ grant: () => ({ ...current, models: [...current.models] }),
176
+ close() { busy?.ctrl.abort(); dropLease(); },
177
+ status: () => ({
178
+ lending, busy: !!busy, served, refused, usage: limiter.usage(), perMinute: limiter.perMinute,
179
+ limits: { promptChars: limits.promptChars, maxTokens: limits.maxTokens },
180
+ grant: { ...current, models: [...current.models] },
181
+ lease: lease ? { turns: lease.turns, expiresAt: new Date(lease.expiresAt).toISOString(), ended: lease.ended } : null
182
+ }),
75
183
  };
76
184
  }