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/lend/index.js CHANGED
@@ -1,6 +1,9 @@
1
1
  // Lend your PC, server side (PROTOCOL.md section 6, "Server side plug-in").
2
2
  // The engine calls register() at start. On a hivedesk started with --lend it adds:
3
3
  // lend.chat the guarded way for the friend's browser to run one turn on the local brain
4
+ // lend.cancel aborts the running lent turn (the host cancelled it)
5
+ // lend.grant what one pairing lends: { minutes, turns, models, cloud } (guard.js)
6
+ // brain.chat the engine's older entry, routed through the same guard
4
7
  // lend.log the friend's browser records what it did with a request (counts only)
5
8
  // lend.stop stop lending: every later lend.chat is refused
6
9
  // lend.resume lend again after a stop (a new pairing in the same run)
@@ -12,33 +15,47 @@
12
15
  // On the host nothing is needed here: the remote brain rides the engine's brain.attach,
13
16
  // brain.request and brain.respond frames.
14
17
 
15
- import { createLendGuard } from './guard.js';
18
+ import { createLendGuard, lendable } from './guard.js';
16
19
  import registerCollab from '../collab/index.js';
17
20
 
18
21
  const LOG_STATUSES = new Set(['running', 'done', 'refused', 'failed', 'cancelled', 'stopped']);
19
22
  const num = (v) => (Number.isFinite(v) && v >= 0 ? Math.round(v) : undefined);
20
23
 
21
- /** Picks the local brain's chat function from whatever the engine hands the plug-in. */
24
+ /**
25
+ * Picks the local brain's chat function from whatever the engine hands the plug-in.
26
+ * The chat takes (messages, options, { signal, accept }): signal aborts the turn, accept(brain)
27
+ * says which brains may run it (guard.js: local models of this PC, the allowlist, cloud only when granted).
28
+ */
22
29
  export function findLocalChat(ctx) {
23
30
  const candidates = [ctx.chatLocal, ctx.brain, ctx.localBrain, ctx.scheduler?.localBrain, ctx.scheduler?.local];
24
31
  for (const c of candidates) {
25
32
  if (typeof c === 'function') return c;
26
- if (c && typeof c.chat === 'function') return (messages, options) => c.chat(messages, options);
33
+ if (c && typeof c.chat === 'function') {
34
+ const chat = (messages, options, run = {}) => c.chat(messages, run.signal ? { ...options, signal: run.signal } : options);
35
+ chat.brains = () => [c];
36
+ return chat;
37
+ }
27
38
  }
28
- // The engine's own scheduler: a lent turn waits in the same fair queue as the friend's crew.
39
+ // The engine's own scheduler: a lent turn waits in the same fair queue as the friend's crew,
40
+ // and runs only on a brain the grant accepts.
29
41
  if (typeof ctx.scheduler?.turn === 'function') {
30
- return (messages, options) => ctx.scheduler.turn({ workerId: 'lend:friend', messages, options });
42
+ const chat = (messages, options, run = {}) => ctx.scheduler.turn({ workerId: 'lend:friend', messages, options, signal: run.signal, accept: run.accept });
43
+ if (ctx.scheduler.brains instanceof Map) chat.brains = () => [...ctx.scheduler.brains.values()].map((slot) => slot.brain);
44
+ return chat;
31
45
  }
32
46
  if (typeof ctx.scheduler?.getLocalBrain === 'function') {
33
- return async (messages, options) => {
47
+ return async (messages, options, run = {}) => {
34
48
  const brain = await ctx.scheduler.getLocalBrain();
35
49
  if (!brain) throw Object.assign(new Error('No local model is ready'), { code: 'busy' });
36
- return brain.chat(messages, options);
50
+ if (run.accept && !run.accept(brain)) throw Object.assign(new Error('No local model on this PC is allowed for lending'), { code: 'no_model' });
51
+ return brain.chat(messages, run.signal ? { ...options, signal: run.signal } : options);
37
52
  };
38
53
  }
39
54
  return null;
40
55
  }
41
56
 
57
+ export { lendable };
58
+
42
59
  /** Keeps only counts and short codes from a browser log entry. Prompt text never reaches the log. */
43
60
  export function cleanLogEntry(e) {
44
61
  if (!e || typeof e !== 'object' || !LOG_STATUSES.has(e.status)) return null;
@@ -56,7 +73,7 @@ export default function register(ctx) {
56
73
  const { bus, server, config = {} } = ctx;
57
74
  const emit = (type, data) => bus?.emit?.(type, data);
58
75
  const chat = findLocalChat(ctx);
59
- const guard = createLendGuard({ chat, emit });
76
+ const guard = createLendGuard({ chat, emit, grant: config.lendGrant });
60
77
  // guarded: lend.chat can reach the local brain. When false the browser uses the engine's brain.chat.
61
78
  let lending = !!config.lend;
62
79
  const status = () => ({ lend: lending, guarded: !!chat, ...guard.status() });
@@ -75,6 +92,19 @@ export default function register(ctx) {
75
92
  onlyLend();
76
93
  return guard.handle(data);
77
94
  });
95
+ // The older entry the Lend screen used when it was not guarded: the same checks now.
96
+ server?.command?.('brain.chat', (data) => {
97
+ onlyLend();
98
+ return guard.handle(data);
99
+ });
100
+ server?.command?.('lend.cancel', (data) => {
101
+ onlyLend();
102
+ return { cancelled: guard.cancel(typeof data?.requestId === 'string' ? data.requestId.slice(0, 64) : null) };
103
+ });
104
+ server?.command?.('lend.grant', (data) => {
105
+ onlyLend();
106
+ return { grant: guard.setGrant(data) };
107
+ });
78
108
  server?.command?.('lend.log', (data) => {
79
109
  onlyLend();
80
110
  const entry = cleanLogEntry(data);
@@ -55,7 +55,8 @@ export function reduce(state, event) {
55
55
  switch (event.type) {
56
56
  case 'session.started':
57
57
  state.version = d.version || state.version;
58
- state.demo = state.demo || !!d.demo;
58
+ // Each run says whether it is a demo; an older demo run in the same log does not stick.
59
+ state.demo = !!d.demo;
59
60
  state.lend = !!d.lend;
60
61
  break;
61
62
  case 'settings.changed': {
package/src/server.js CHANGED
@@ -8,6 +8,7 @@ import { acceptUpgrade, rejectUpgrade } from './ws.js';
8
8
  import { createRelayBrain } from './brain/relay.js';
9
9
  import { PROTOCOL } from './replay/reduce.js';
10
10
  import { marks } from './replay/index.js';
11
+ import { guestOf, checkGuest } from './collab/policy.js';
11
12
 
12
13
  const HERE = path.dirname(fileURLToPath(import.meta.url));
13
14
  export const PACKAGE_ROOT = path.resolve(HERE, '..');
@@ -152,7 +153,11 @@ export function createServer(opts) {
152
153
  async function runCommand(type, data, client) {
153
154
  const handler = commands.get(type);
154
155
  if (!handler) throw new CommandError('bad_request', `unknown command: ${type}`);
155
- return handler(data && typeof data === 'object' ? data : {}, client);
156
+ const d = data && typeof data === 'object' ? data : {};
157
+ // A guest command (forwarded by the host's browser with `as`) is checked against its role here,
158
+ // whatever the browser decided (src/collab/policy.js).
159
+ checkGuest(guestOf(d), type, (code, message) => new CommandError(code, message));
160
+ return handler(d, client);
156
161
  }
157
162
 
158
163
  const need = (cond, msg) => { if (!cond) throw new CommandError('bad_request', msg); };
@@ -160,14 +165,21 @@ export function createServer(opts) {
160
165
  command('ping', () => ({ pong: true, ts: new Date().toISOString() }));
161
166
  command('job.create', (d) => {
162
167
  need(typeof d.request === 'string' && d.request.trim(), 'request is required');
163
- const { jobId } = hive.createJob({ request: d.request, approval: typeof d.approval === 'boolean' ? d.approval : undefined, refine: typeof d.refine === 'boolean' ? d.refine : undefined, playbookId: d.playbookId });
168
+ const guest = guestOf(d);
169
+ // A guest's job runs with approval on, and every write or run in it waits for the host.
170
+ const approval = guest ? true : typeof d.approval === 'boolean' ? d.approval : undefined;
171
+ const { jobId } = hive.createJob({ request: d.request, approval, refine: typeof d.refine === 'boolean' ? d.refine : undefined, playbookId: d.playbookId });
172
+ if (guest) toolbox.markOrigin?.(jobId, { kind: 'guest', id: guest.id, label: guest.name });
164
173
  return { jobId };
165
174
  });
166
175
  command('job.cancel', (d) => { hive.cancelJob(d.jobId); return {}; });
167
176
  command('chat.send', (d) => ({ id: hive.userChat(d.channel, d.text) }));
168
177
  command('approval.resolve', (d) => {
169
178
  need(typeof d.approvalId === 'string', 'approvalId is required');
170
- if (!approvals.resolve(d.approvalId, !!d.approved, d.note, 'user')) throw new CommandError('not_found', 'no pending approval with that id');
179
+ const guest = guestOf(d);
180
+ // Actions that come from a guest or a friend's model are answered by the host only.
181
+ if (guest && approvals.get?.(d.approvalId)?.strict) throw new CommandError('forbidden', 'only the host can answer this approval');
182
+ if (!approvals.resolve(d.approvalId, !!d.approved, d.note, guest ? 'guest' : 'user')) throw new CommandError('not_found', 'no pending approval with that id');
171
183
  return {};
172
184
  });
173
185
  command('crew.hire', (d) => ({ worker: hive.hire(d) }));
@@ -239,6 +251,9 @@ export function createServer(opts) {
239
251
  model: typeof d.model === 'string' ? d.model.slice(0, 120) : undefined,
240
252
  send: (frame) => { if (!client.conn.sendJson(frame)) throw new Error('the remote brain disconnected'); }
241
253
  });
254
+ // Who lends it: a Code together guest (its building may use it), or a friend outside the city.
255
+ const lender = typeof d.guest === 'string' ? d.guest.trim().slice(0, 24) : '';
256
+ brain.owner = lender ? `peer:${lender}` : null;
242
257
  client.brains.set(id, brain);
243
258
  scheduler.addBrain(brain);
244
259
  return { brainId: id };
@@ -13,7 +13,7 @@ export class Approvals {
13
13
  }
14
14
 
15
15
  /**
16
- * @param {{ jobId?: string, taskId?: string, workerId?: string, tool: string, args: any, summary: string, diff?: string }} req
16
+ * @param {{ jobId?: string, taskId?: string, workerId?: string, tool: string, args: any, summary: string, diff?: string, origin?: any, strict?: boolean }} req
17
17
  * @param {AbortSignal} [signal]
18
18
  * @returns {Promise<{ approved: boolean, note?: string, by: string }>}
19
19
  */
@@ -25,6 +25,7 @@ export class Approvals {
25
25
  this.pending.set(id, { resolve, approval });
26
26
  this.bus.emit('approval.requested', { approval }, { jobId: req.jobId });
27
27
  if (req.workerId) this.bus.emit('worker.status', { workerId: req.workerId, status: 'waiting_approval', detail: approval.summary, taskId: req.taskId }, { jobId: req.jobId });
28
+ // Demo mode answers by itself; a strict approval outside the demo never does.
28
29
  if (this.autoApproveMs) {
29
30
  const t = setTimeout(() => this.resolve(id, true, 'approved automatically in the demo', 'auto'), this.autoApproveMs);
30
31
  t.unref?.();
@@ -43,6 +44,11 @@ export class Approvals {
43
44
  });
44
45
  }
45
46
 
47
+ /** The pending approval with this id, or null. */
48
+ get(approvalId) {
49
+ return this.pending.get(approvalId)?.approval || null;
50
+ }
51
+
46
52
  /** @returns {boolean} false when the id is unknown */
47
53
  resolve(approvalId, approved, note, by = 'user') {
48
54
  const p = this.pending.get(approvalId);
@@ -55,8 +61,11 @@ export class Approvals {
55
61
  return true;
56
62
  }
57
63
 
58
- /** Approves everything that is pending (used when approval mode is switched off). */
64
+ /**
65
+ * Approves everything that is pending (used when approval mode is switched off), except strict
66
+ * approvals: actions from a guest or a friend's model always wait for the host's own answer.
67
+ */
59
68
  approveAll(by = 'auto') {
60
- for (const id of [...this.pending.keys()]) this.resolve(id, true, 'approval mode turned off', by);
69
+ for (const [id, p] of [...this.pending]) if (!p.approval.strict) this.resolve(id, true, 'approval mode turned off', by);
61
70
  }
62
71
  }
@@ -1,7 +1,7 @@
1
1
  // Tool definitions (each with a JSON schema) and the executor with approval mode and events.
2
2
  import { Workspace } from './workspace.js';
3
3
  import { unifiedDiff, diffStats } from './diff.js';
4
- import { runCommand } from './run.js';
4
+ import { runCommand, splitArgs } from './run.js';
5
5
  import { checkWorkspace } from './check.js';
6
6
 
7
7
  const S = (properties) => ({ type: 'object', properties, required: Object.keys(properties), additionalProperties: false });
@@ -23,6 +23,8 @@ export const TOOLS = {
23
23
  };
24
24
 
25
25
  export const ALL_TOOLS = Object.keys(TOOLS);
26
+ /** Tools that change the workspace or run code: from a guest or a friend's model they always wait for the host. */
27
+ export const STRICT_TOOLS = new Set(['write_file', 'edit_file', 'delete_file', 'run']);
26
28
 
27
29
  export function toolList(names = ALL_TOOLS) {
28
30
  return names.filter((n) => TOOLS[n]).map((name) => ({ name, description: TOOLS[name].description, parameters: TOOLS[name].parameters }));
@@ -56,10 +58,29 @@ export class ToolBox {
56
58
  this.approvals = opts.approvals;
57
59
  this.previewUrl = opts.previewUrl || (() => null);
58
60
  this.isApprovalMode = opts.isApprovalMode || (() => this.bus.state.settings.approvalMode !== false);
61
+ /** jobId -> origin of jobs that did not start at this PC (a guest's request) */
62
+ this.origins = new Map();
63
+ }
64
+
65
+ /** Marks a job as started by someone else (a Code together guest): its writes and runs wait for the host. */
66
+ markOrigin(jobId, origin) {
67
+ const o = cleanOrigin(origin);
68
+ if (jobId && o) this.origins.set(jobId, o);
69
+ }
70
+
71
+ /** Where a call comes from when it is not this PC's own crew: a guest or a friend's model. */
72
+ originOf(ctx = {}) {
73
+ return cleanOrigin(ctx.origin) || (ctx.jobId && this.origins.get(ctx.jobId)) || null;
74
+ }
75
+
76
+ /** True when this call must wait for the host whatever the approval mode. */
77
+ isStrict(tool, ctx = {}) {
78
+ return STRICT_TOOLS.has(tool) && !!this.originOf(ctx);
59
79
  }
60
80
 
61
81
  /** Whether this call needs the user's approval in approval mode. */
62
82
  needsApproval(tool, args, ctx = {}) {
83
+ if (this.isStrict(tool, ctx)) return true;
63
84
  const mode = ctx.approval === undefined ? this.isApprovalMode() : ctx.approval && this.isApprovalMode();
64
85
  if (!mode) return false;
65
86
  if (TOOLS[tool]?.destructive) return true;
@@ -87,9 +108,12 @@ export class ToolBox {
87
108
  if (!TOOLS[tool]) throw new Error(`unknown tool: ${tool}`);
88
109
  if (ctx.allowed && !ctx.allowed.includes(tool)) throw new Error(`${ctx.workerId || 'this worker'} is not allowed to use ${tool}`);
89
110
  if (this.needsApproval(tool, args, ctx)) {
111
+ const origin = this.originOf(ctx);
112
+ const script = tool === 'run' ? this.scriptOf(args.command) : null;
90
113
  const decision = await this.approvals.request({
91
114
  jobId: ctx.jobId, taskId: ctx.taskId, workerId: ctx.workerId, tool, args: redactArgs(tool, args),
92
- summary: describe(tool, args), diff: this.previewDiff(tool, args)
115
+ summary: describe(tool, args), diff: this.previewDiff(tool, args),
116
+ ...(origin ? { origin, strict: STRICT_TOOLS.has(tool) } : {}), ...(script ? { script } : {})
93
117
  }, ctx.signal);
94
118
  if (!decision.approved) throw new Error(`the user rejected this action${decision.note ? ': ' + decision.note : ''}`);
95
119
  }
@@ -102,6 +126,18 @@ export class ToolBox {
102
126
  return out;
103
127
  }
104
128
 
129
+ /** For "npm test" and "npm run x": the script from package.json that would really run. */
130
+ scriptOf(command) {
131
+ let argv;
132
+ try { argv = splitArgs(String(command || '')); } catch { return null; }
133
+ if (String(argv[0] || '').toLowerCase().replace(/\.(exe|cmd)$/, '') !== 'npm') return null;
134
+ const name = ['test', 't'].includes(argv[1]) ? 'test' : ['run', 'run-script'].includes(argv[1]) ? argv[2] : null;
135
+ if (!name) return null;
136
+ let body = null;
137
+ try { body = JSON.parse(this.ws.read('package.json'))?.scripts?.[name] ?? null; } catch { body = null; }
138
+ return { name: String(name).slice(0, 80), body: typeof body === 'string' ? body.slice(0, 2000) : null };
139
+ }
140
+
105
141
  previewDiff(tool, args) {
106
142
  try {
107
143
  if (tool === 'write_file') {
@@ -176,6 +212,14 @@ export class ToolBox {
176
212
  }
177
213
  }
178
214
 
215
+ function cleanOrigin(o) {
216
+ if (!o || typeof o !== 'object' || !['guest', 'remote'].includes(o.kind)) return null;
217
+ const out = { kind: o.kind, label: String(o.label || (o.kind === 'guest' ? 'a guest' : "a friend's model")).slice(0, 80) };
218
+ if (o.id) out.id = String(o.id).slice(0, 40);
219
+ if (o.brainId) out.brainId = String(o.brainId).slice(0, 40);
220
+ return out;
221
+ }
222
+
179
223
  function normalize(p) {
180
224
  return String(p || '').trim().replace(/\\/g, '/').replace(/^\.\//, '');
181
225
  }
package/ui/city/collab.js CHANGED
@@ -48,11 +48,14 @@ export function wireCollab(getCity) {
48
48
  if (!collab || collab._cityWired) return false;
49
49
  collab._cityWired = true;
50
50
  let was = collab.mode;
51
+ // Only a collaborator brings a building (the host engine refuses a viewer); a promotion joins then.
52
+ const join = () => joinAsGuest().catch((err) => { if (err.code !== 'forbidden') console.warn('[hivedesk] could not join the city', err.message); });
51
53
  collab.on('change', (mode) => {
52
- if (mode === 'guest' && was !== 'guest') joinAsGuest().catch((err) => console.warn('[hivedesk] could not join the city', err.message));
54
+ if (mode === 'guest' && was !== 'guest' && collab.guest?.role !== 'viewer') join();
53
55
  if (mode !== 'guest') mine = null;
54
56
  was = mode;
55
57
  });
58
+ collab.on('role', () => { if (collab.mode === 'guest' && !mine && collab.guest?.role === 'collaborator') join(); });
56
59
  // host: a guest left, its building goes dark
57
60
  collab.on('left', (g) => {
58
61
  const city = getCity();
package/ui/css/hive.css CHANGED
@@ -724,6 +724,8 @@ dialog.dlg::backdrop { background: rgb(8 7 6 / .6); backdrop-filter: blur(4px);
724
724
  .appr-t { font-size: 13px; font-weight: 600; }
725
725
  .appr .udiff { max-height: 220px; overflow: auto; background: var(--bg-2); border-top: 1px solid var(--line); border-bottom: 1px solid var(--line); }
726
726
  .appr-a { display: flex; gap: 8px; padding: 10px 12px; justify-content: flex-end; }
727
+ .appr-origin { margin: 0 12px 10px; padding: 7px 10px; border-radius: 8px; border: 1px solid rgb(226 109 90 / .45); background: rgb(226 109 90 / .1); }
728
+ .appr-script { margin: 0 12px 10px; padding: 7px 10px; border-radius: 8px; background: var(--bg-2); white-space: pre-wrap; word-break: break-word; max-height: 140px; overflow: auto; }
727
729
 
728
730
  /* ---------- ntoasts ---------- */
729
731
  .ntoasts { position: fixed; right: 16px; bottom: calc(var(--dock-h) + 10px); z-index: 9700; display: flex; flex-direction: column; gap: 8px; width: min(360px, calc(100vw - 32px)); pointer-events: none; }
@@ -26,6 +26,9 @@ export function approvalCard(a, { compact = false } = {}) {
26
26
  h('div', { class: 'grow' }, h('div', { class: 'appr-t', text: approvalTitle(a) }),
27
27
  h('div', { class: 'small muted ellipsis', text: a.summary || target }))),
28
28
  target ? h('div', { class: 'row', style: 'padding:0 12px 10px' }, h('span', { class: 'hchip hchip-mono', text: a.tool }), h('span', { class: 'mono small ellipsis', text: target }), h('span', { class: 'grow' }), h('span', { class: 'tiny faint', text: ago(a.createdAt) })) : null,
29
+ // Where it comes from when it is not this PC's own crew: a guest or a friend's model (always waits for you).
30
+ a.origin ? h('div', { class: 'small appr-origin', role: 'note', text: t(a.origin.kind === 'remote' ? 'approvals.origin.remote' : 'approvals.origin.guest', { name: a.origin.label || '' }) }) : null,
31
+ a.script ? h('div', { class: 'mono small appr-script', text: a.script.body != null ? t('approvals.script', { name: a.script.name, body: a.script.body }) : t('approvals.scriptMissing', { name: a.script.name }) }) : null,
29
32
  a.diff && !compact ? diffView(a.diff) : null,
30
33
  h('div', { class: 'appr-a' },
31
34
  ui.replay ? h('span', { class: 'small muted', text: t('approvals.replayOff') }) : null,
@@ -272,7 +272,7 @@ class Collab extends Emitter {
272
272
  };
273
273
  peer.receive(raw);
274
274
  if (peer.remoteHello?.role !== 'lender') return;
275
- const bridge = new HostBridge({ hive, peer, label: this.profile.name || 'host' });
275
+ const bridge = new HostBridge({ hive, peer, label: this.profile.name || 'host', guestId: g.id });
276
276
  l = { peer, bridge };
277
277
  this.lends.set(g.id, l);
278
278
  bridge.on('attached', () => this.emit('people'));
@@ -1,8 +1,10 @@
1
1
  // Who may do what in Code together. The host's browser checks every guest command here before
2
- // it reaches the host's engine, and the engine then applies its own approval rules as usual.
2
+ // it reaches the host's engine. Every forwarded command carries `as: { id, name, role }`, and the
3
+ // engine checks the role again on its side (src/collab/policy.js) before its own approval rules.
3
4
  //
4
5
  // viewer sees everything, can chat
5
- // collaborator can also send requests to the crew, approve steps and edit files
6
+ // collaborator can also send requests to the crew, approve steps, edit files (the host
7
+ // approves every write) and bring a building and its agents into the city
6
8
  // host everything (the person whose hivedesk and disk it is)
7
9
  //
8
10
  // There is no command that runs a shell. Commands that change the model, settings, crew, lent
@@ -12,10 +14,10 @@ export const ROLES = Object.freeze(['viewer', 'collaborator', 'host']);
12
14
  export const GUEST_ROLES = Object.freeze(['viewer', 'collaborator']);
13
15
 
14
16
  const READ = ['ping', 'events.since', 'replay.at', 'replay.marks', 'files.list', 'files.read', 'playbook.list'];
15
- // Hive City (CITY-PROTOCOL.md): everyone can see the city, bring a building and its agents, and lend or
16
- // borrow a GPU; collaborators can also put tasks on the board. The host engine checks ownership again.
17
- const CITY_VIEWER = ['city.state', 'city.sync', 'city.presence', 'city.machine.join', 'city.machine.update', 'city.machine.leave', 'city.agent.update', 'city.borrow.request', 'city.borrow.answer', 'city.borrow.stop'];
18
- const CITY_COLLABORATOR = ['city.task.create', 'city.task.assign', 'city.task.move', 'city.task.approve', 'city.task.reject', 'city.task.retry', 'city.task.cancel', 'city.agent.move', 'city.agent.retire', 'city.agent.wake'];
17
+ // Hive City (CITY-PROTOCOL.md): everyone can see the city; collaborators can also bring a building and
18
+ // its agents, lend or borrow a GPU and put tasks on the board. The host engine checks roles and ownership again.
19
+ const CITY_VIEWER = ['city.state', 'city.sync', 'city.presence'];
20
+ const CITY_COLLABORATOR = ['city.machine.join', 'city.machine.update', 'city.machine.leave', 'city.agent.update', 'city.borrow.request', 'city.borrow.answer', 'city.borrow.stop', 'city.task.create', 'city.task.assign', 'city.task.move', 'city.task.approve', 'city.task.reject', 'city.task.retry', 'city.task.cancel', 'city.agent.move', 'city.agent.retire', 'city.agent.wake'];
19
21
  const VIEWER = new Set([...READ, 'chat.send', ...CITY_VIEWER]);
20
22
  const COLLABORATOR = new Set([...VIEWER, 'job.create', 'job.cancel', 'approval.resolve', 'task.retry', 'task.reassign', 'task.cancel', 'files.write', ...CITY_COLLABORATOR]);
21
23
 
@@ -44,28 +46,29 @@ const short = (v, n) => String(v ?? '').slice(0, n);
44
46
 
45
47
  /**
46
48
  * Checks one guest command and returns what the host forwards to its engine, or throws a
47
- * PermissionError. guest is { id, name, role }.
49
+ * PermissionError. guest is { id, name, role }. Every command carries `as`, which replaces any
50
+ * `as` the guest sent, so the engine knows who sent it and with which role.
48
51
  * chat.send the text is signed with the guest's name
49
- * files.write carries `as` so the engine asks the host for approval like any crew write
50
- * job.create the request is signed with the guest's name in the job log
52
+ * files.write the engine asks the host for approval, new files included
53
+ * job.create the job runs with approval mode on and its writes wait for the host
51
54
  */
52
55
  export function checkCommand(guest, type, data = {}) {
53
56
  if (typeof type !== 'string' || !canCommand(guest.role, type)) {
54
57
  throw new PermissionError(guest.role === 'viewer' ? `A viewer cannot use ${type}. Ask the host to make you a collaborator.` : `Guests cannot use ${type}.`);
55
58
  }
56
59
  const d = data && typeof data === 'object' && !Array.isArray(data) ? { ...data } : {};
60
+ const as = { id: guest.id, name: guest.name, role: guest.role };
57
61
  switch (type) {
58
62
  case 'chat.send':
59
- return { type, data: { channel: short(d.channel, 60) || 'general', text: `${guest.name}: ${short(d.text, 4000)}` } };
63
+ return { type, data: { channel: short(d.channel, 60) || 'general', text: `${guest.name}: ${short(d.text, 4000)}`, as } };
60
64
  case 'files.write':
61
- return { type, data: { path: short(d.path, 300), content: String(d.content ?? ''), as: { id: guest.id, name: guest.name } } };
65
+ return { type, data: { path: short(d.path, 300), content: String(d.content ?? ''), as } };
62
66
  case 'job.create':
63
- return { type, data: { request: short(d.request, 4000), ...(d.playbookId ? { playbookId: short(d.playbookId, 80) } : {}) } };
67
+ return { type, data: { request: short(d.request, 4000), ...(d.playbookId ? { playbookId: short(d.playbookId, 80) } : {}), as } };
64
68
  case 'approval.resolve':
65
- return { type, data: { approvalId: short(d.approvalId, 80), approved: !!d.approved, note: `${guest.name}${d.note ? `: ${short(d.note, 300)}` : ''}` } };
69
+ return { type, data: { approvalId: short(d.approvalId, 80), approved: !!d.approved, note: `${guest.name}${d.note ? `: ${short(d.note, 300)}` : ''}`, as } };
66
70
  default:
67
- // City commands carry who sent them, so the host engine can apply "the owner wins". Any as sent by the guest is replaced.
68
- if (type.startsWith('city.')) return { type, data: { ...d, as: { id: guest.id, name: guest.name } } };
69
- return { type, data: d };
71
+ // Commands carry who sent them, so the host engine can apply roles and "the owner wins".
72
+ return { type, data: { ...d, as } };
70
73
  }
71
74
  }
@@ -15,11 +15,13 @@ import { FrameError, LEND_PROTOCOL, LIMITS, promptChars, readResult } from './fr
15
15
  import { RateLimiter, DEFAULT_RATE } from './ratelimit.js';
16
16
 
17
17
  export class HostBridge extends Emitter {
18
- constructor({ hive, peer, label = 'host' }) {
18
+ /** guestId: the Code together guest who lends (its building in the city may then use this brain). */
19
+ constructor({ hive, peer, label = 'host', guestId = null }) {
19
20
  super();
20
21
  this.hive = hive;
21
22
  this.peer = peer;
22
23
  this.label = label;
24
+ this.guestId = guestId;
23
25
  this.brainId = null;
24
26
  this.pending = new Map(); // requestId -> { at, chars }
25
27
  this.offs = [];
@@ -41,7 +43,7 @@ export class HostBridge extends Emitter {
41
43
  this.attaching = true;
42
44
  const hello = this.peer.remoteHello || {};
43
45
  try {
44
- const res = await this.hive.command('brain.attach', { label: `${hello.label || 'friend'} (lent PC)`, model: hello.model, ctx: hello.ctx });
46
+ const res = await this.hive.command('brain.attach', { label: `${hello.label || 'friend'} (lent PC)`, model: hello.model, ctx: hello.ctx, ...(this.guestId ? { guest: this.guestId } : {}) });
45
47
  this.brainId = res.brainId;
46
48
  this.offs.push(this.hive.on('brain.request', (m) => m.brainId === this.brainId && this._request(m)));
47
49
  this.offs.push(this.hive.on('brain.cancel', (m) => m.brainId === this.brainId && this._cancel(m.requestId)));
@@ -153,7 +155,10 @@ export class LenderBridge extends Emitter {
153
155
 
154
156
  async _frame(f) {
155
157
  if (f.t === 'cancel') {
156
- if (this.busy?.id === f.id) this.busy.cancelled = true;
158
+ if (this.busy?.id === f.id) {
159
+ this.busy.cancelled = true;
160
+ this._abort(f.id);
161
+ }
157
162
  return;
158
163
  }
159
164
  if (f.t !== 'req') return;
@@ -169,7 +174,7 @@ export class LenderBridge extends Emitter {
169
174
  const entry = this._entry({ id: f.id, status: 'running', ...base, preview: f.messages[f.messages.length - 1].content.slice(0, 160) });
170
175
  const started = this.now();
171
176
  try {
172
- const raw = await this.hive.command(this.chatCommand, { messages: f.messages, options: f.options });
177
+ const raw = await this.hive.command(this.chatCommand, { messages: f.messages, options: f.options, requestId: f.id });
173
178
  const result = readResult(raw, this.limits);
174
179
  if (job.cancelled || !this.lending) {
175
180
  this._entry({ id: f.id, status: 'cancelled', ...base });
@@ -192,10 +197,18 @@ export class LenderBridge extends Emitter {
192
197
  }
193
198
  }
194
199
 
200
+ /** Stops the model on this PC for a cancelled request (the engine aborts the running turn). */
201
+ _abort(id) {
202
+ this.hive.command('lend.cancel', { requestId: id }).catch(() => {});
203
+ }
204
+
195
205
  /** The friend stops lending: refuses anything new, tells the host and closes the link. */
196
206
  stop(reason = 'The friend stopped lending') {
197
207
  if (!this.lending) return;
198
- if (this.busy) this.busy.cancelled = true;
208
+ if (this.busy) {
209
+ this.busy.cancelled = true;
210
+ this._abort(this.busy.id);
211
+ }
199
212
  this.peer.stop(reason);
200
213
  this._stopped(reason);
201
214
  }
@@ -20,6 +20,8 @@ export const LIMITS = Object.freeze({
20
20
  messages: 64, // messages in one request
21
21
  promptChars: 120000, // all message contents of one request together
22
22
  schemaChars: 16000, // the JSON schema of one request
23
+ schemaDepth: 16, // how deep the schema nests (it becomes a grammar on the lender)
24
+ schemaNodes: 1000, // objects and arrays in the schema
23
25
  maxTokens: 4096, // the most completion tokens a request may ask for
24
26
  completionChars: 120000, // the completion text (and its parsed JSON) of one answer
25
27
  tokenChars: 8000, // one streamed token frame
@@ -79,6 +81,22 @@ export function readMessages(messages, limits = LIMITS) {
79
81
  return out;
80
82
  }
81
83
 
84
+ /** How deep a JSON value nests and how many objects and arrays it has. */
85
+ export function schemaShape(value) {
86
+ let nodes = 0;
87
+ let depth = 0;
88
+ const stack = [[value, 1]];
89
+ while (stack.length) {
90
+ const [v, d] = stack.pop();
91
+ if (!v || typeof v !== 'object') continue;
92
+ nodes++;
93
+ if (d > depth) depth = d;
94
+ if (nodes > 100000) break;
95
+ for (const x of Array.isArray(v) ? v : Object.values(v)) if (x && typeof x === 'object') stack.push([x, d + 1]);
96
+ }
97
+ return { depth, nodes };
98
+ }
99
+
82
100
  /** Only schema, maxTokens and temperature travel. Signals, callbacks and tools stay home. */
83
101
  export function readOptions(options, limits = LIMITS) {
84
102
  const out = {};
@@ -88,6 +106,8 @@ export function readOptions(options, limits = LIMITS) {
88
106
  const text = JSON.stringify(options.schema);
89
107
  if (text.length > limits.schemaChars) fail('schema_too_big', `The schema has ${text.length} characters, the limit is ${limits.schemaChars}`);
90
108
  out.schema = JSON.parse(text);
109
+ const shape = schemaShape(out.schema);
110
+ if (shape.depth > (limits.schemaDepth ?? LIMITS.schemaDepth) || shape.nodes > (limits.schemaNodes ?? LIMITS.schemaNodes)) fail('schema_too_big', 'The schema nests too deep or has too many parts');
91
111
  }
92
112
  if (Number.isFinite(options.maxTokens)) out.maxTokens = clamp(Math.round(options.maxTokens), 1, limits.maxTokens);
93
113
  if (Number.isFinite(options.temperature)) out.temperature = clamp(options.temperature, 0, 2);