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.
- package/CHANGELOG.md +30 -0
- package/FIRST-RUN.md +14 -0
- package/PROTOCOL.md +23 -6
- package/README.md +51 -6
- package/assets/illustrations/hive-city.svg +113 -0
- package/assets/video-poster.webp +0 -0
- package/i18n/README.pt-BR.md +50 -6
- package/i18n/de.json +178 -0
- package/i18n/en.json +178 -0
- package/i18n/es.json +178 -0
- package/i18n/fr.json +178 -0
- package/i18n/it.json +178 -0
- package/i18n/ja.json +178 -0
- package/i18n/ko.json +178 -0
- package/i18n/pt-BR.json +178 -0
- package/i18n/ru.json +178 -0
- package/i18n/zh-CN.json +178 -0
- package/package.json +1 -1
- package/src/bus.js +22 -2
- package/src/city/demo.js +76 -0
- package/src/city/hops.js +95 -0
- package/src/city/index.js +1546 -0
- package/src/city/router.js +53 -0
- package/src/city/state.js +313 -0
- package/src/city/store.js +91 -0
- package/src/cli.js +44 -5
- package/src/collab/index.js +10 -6
- package/src/collab/policy.js +48 -0
- package/src/crew/engine.js +40 -3
- package/src/crew/scheduler.js +4 -0
- package/src/crew/worker.js +5 -1
- package/src/demo.js +30 -2
- package/src/extensions/sandbox.js +81 -56
- package/src/index.js +26 -3
- package/src/lend/guard.js +115 -7
- package/src/lend/index.js +38 -8
- package/src/replay/reduce.js +2 -1
- package/src/server.js +22 -4
- package/src/tools/approvals.js +12 -3
- package/src/tools/index.js +46 -2
- package/ui/city/city.css +204 -0
- package/ui/city/city.js +933 -0
- package/ui/city/collab.js +67 -0
- package/ui/city/layout.js +142 -0
- package/ui/city/mock.js +358 -0
- package/ui/city/model.js +195 -0
- package/ui/city/scene.js +2033 -0
- package/ui/css/hive.css +2 -0
- package/ui/js/main.js +3 -1
- package/ui/js/widgets/approvals.js +3 -0
- package/ui/lend/collab/client.js +1 -1
- package/ui/lend/collab/roles.js +21 -12
- package/ui/lend/core/bridge.js +18 -5
- package/ui/lend/core/frames.js +20 -0
- package/ui/office/office.js +51 -21
- package/ui/office/scene.js +3 -0
- package/ui/screenshots/city-agent-card-1440.png +0 -0
- package/ui/screenshots/city-agent-card-1920.png +0 -0
- package/ui/screenshots/city-bridge-gpu-borrow-1440.png +0 -0
- package/ui/screenshots/city-bridge-gpu-borrow-1920.png +0 -0
- package/ui/screenshots/city-friend-rising-1440.png +0 -0
- package/ui/screenshots/city-friend-rising-1920.png +0 -0
- package/ui/screenshots/city-overview-1440.png +0 -0
- package/ui/screenshots/city-overview-1920.png +0 -0
- package/ui/screenshots/city-review-room-1440.png +0 -0
- package/ui/screenshots/city-review-room-1920.png +0 -0
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 =
|
|
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
|
-
|
|
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
|
|
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 =
|
|
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
|
-
|
|
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
|
}
|
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
|
-
/**
|
|
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')
|
|
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
|
-
|
|
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
|
-
|
|
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);
|
package/src/replay/reduce.js
CHANGED
|
@@ -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
|
-
|
|
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, '..');
|
|
@@ -76,7 +77,7 @@ export function createServer(opts) {
|
|
|
76
77
|
let port = 0;
|
|
77
78
|
let clientSeq = 0;
|
|
78
79
|
|
|
79
|
-
const meta = () => ({ protocol: PROTOCOL, version, demo: !!opts.demo, lend: !!opts.lend });
|
|
80
|
+
const meta = () => ({ protocol: PROTOCOL, version, demo: !!opts.demo, lend: !!opts.lend, ...(opts.city ? { city: 1 } : {}) });
|
|
80
81
|
|
|
81
82
|
function allowedHost(req) {
|
|
82
83
|
const h = String(req.headers.host || '');
|
|
@@ -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
|
-
|
|
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
|
|
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
|
-
|
|
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 };
|
|
@@ -367,6 +382,8 @@ export function createServer(opts) {
|
|
|
367
382
|
}
|
|
368
383
|
if (req.method !== 'GET' && req.method !== 'HEAD') return sendError(res, 405, 'bad_request', 'method not allowed');
|
|
369
384
|
if (url.pathname === '/lib/reduce.js') return serveFile(res, path.join(HERE, 'replay', 'reduce.js'), cookie) || sendError(res, 404, 'not_found', 'missing');
|
|
385
|
+
// The Hive City reducer (CITY-PROTOCOL.md section 1), pure and import free like reduce.js.
|
|
386
|
+
if (url.pathname === '/lib/city.js') return serveFile(res, path.join(HERE, 'city', 'state.js'), cookie) || sendError(res, 404, 'not_found', 'missing');
|
|
370
387
|
if (url.pathname.startsWith('/i18n/')) {
|
|
371
388
|
// Shared UI strings and the message formatter (i18n/<locale>.json, i18n/index.js).
|
|
372
389
|
const rel = url.pathname.slice('/i18n/'.length);
|
|
@@ -483,6 +500,7 @@ function statusFor(err) {
|
|
|
483
500
|
case 'not_lending': return 409;
|
|
484
501
|
case 'busy': return 429;
|
|
485
502
|
case 'unauthorized': return 401;
|
|
503
|
+
case 'forbidden': return 403;
|
|
486
504
|
case 'internal': return 500;
|
|
487
505
|
case 'rate_limited': return 429;
|
|
488
506
|
default: return 400;
|
package/src/tools/approvals.js
CHANGED
|
@@ -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
|
-
/**
|
|
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
|
|
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
|
}
|
package/src/tools/index.js
CHANGED
|
@@ -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
|
}
|