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
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// Who claims an open task: the agents in that room bid by skill, level and load (CITY-PROTOCOL.md section 7).
|
|
2
|
+
// Pure: the City engine calls it with the state and what it knows about busy agents and machine load.
|
|
3
|
+
|
|
4
|
+
/** score = 0.6 skill + 0.25 min(level, 10) / 10 + 0.15 (1 - load) */
|
|
5
|
+
export function bidScore({ skill, level, load }) {
|
|
6
|
+
return Math.round((0.6 * skill + 0.25 * (Math.min(Math.max(level || 1, 1), 10) / 10) + 0.15 * (1 - Math.min(Math.max(load || 0, 0), 1))) * 1000) / 1000;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export function skillFor(agent, roomId) {
|
|
10
|
+
const spec = agent.specialization || [];
|
|
11
|
+
if (spec[0] === roomId) return 1;
|
|
12
|
+
if (spec.includes(roomId)) return 0.6;
|
|
13
|
+
return 0;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* @param {any} city CityState
|
|
18
|
+
* @param {any} task CityTask (open)
|
|
19
|
+
* @param {{ busy: (agentId: string) => boolean, load: (machineId: string) => number, canThink: (agent: any) => boolean }} ctx
|
|
20
|
+
* @returns {{ agent: any, bid: { score, skill, load, level, rivals } } | null}
|
|
21
|
+
*/
|
|
22
|
+
export function pickAgent(city, task, ctx) {
|
|
23
|
+
const roomId = task.pipeline?.[task.stage];
|
|
24
|
+
const room = city.rooms[roomId];
|
|
25
|
+
if (!room) return null;
|
|
26
|
+
const candidates = [];
|
|
27
|
+
for (const a of Object.values(city.agents)) {
|
|
28
|
+
if (a.retired || a.status === 'sleeping' || a.status === 'offline') continue;
|
|
29
|
+
if (task.wantAgent && a.id !== task.wantAgent) continue;
|
|
30
|
+
if (ctx.busy(a.id)) continue;
|
|
31
|
+
const m = city.machines[a.home];
|
|
32
|
+
if (!m || !m.online) continue;
|
|
33
|
+
if (!ctx.canThink(a)) continue;
|
|
34
|
+
if (room.kind === 'board') {
|
|
35
|
+
if (a.workerId !== 'mel') continue;
|
|
36
|
+
} else {
|
|
37
|
+
if (a.workerId === 'mel') continue;
|
|
38
|
+
if (!task.wantAgent && skillFor(a, roomId) === 0) continue;
|
|
39
|
+
}
|
|
40
|
+
if (room.kind === 'review' && task.author && a.id === task.author && !task.wantAgent) continue;
|
|
41
|
+
let skill = room.kind === 'board' ? 1 : (skillFor(a, roomId) || 0.6);
|
|
42
|
+
if (room.kind === 'test' && !task.wantAgent) {
|
|
43
|
+
const reviewer = [...(task.verdicts || [])].reverse().find((v) => city.rooms[v.room]?.kind === 'review')?.agentId;
|
|
44
|
+
if (a.id === task.author || a.id === reviewer) skill *= 0.5;
|
|
45
|
+
}
|
|
46
|
+
const load = ctx.load(a.home);
|
|
47
|
+
candidates.push({ agent: a, skill, level: a.level || 1, load, score: bidScore({ skill, level: a.level, load }) });
|
|
48
|
+
}
|
|
49
|
+
if (!candidates.length) return null;
|
|
50
|
+
candidates.sort((x, y) => y.score - x.score || String(x.agent.id).localeCompare(String(y.agent.id)));
|
|
51
|
+
const best = candidates[0];
|
|
52
|
+
return { agent: best.agent, bid: { score: best.score, skill: best.skill, load: best.load, level: best.level, rivals: candidates.length - 1 } };
|
|
53
|
+
}
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
// Hive City state: a pure reducer over the event log. No Node imports: the UI loads this file
|
|
2
|
+
// from /lib/city.js. Shapes are documented in CITY-PROTOCOL.md section 3.
|
|
3
|
+
|
|
4
|
+
export const CITY = 1;
|
|
5
|
+
export const HOP_LIMIT = 200;
|
|
6
|
+
export const VERDICT_LIMIT = 20;
|
|
7
|
+
export const MAX_LOOPS = 3;
|
|
8
|
+
|
|
9
|
+
/** The builtin rooms and their rules. Extensions add more through city.room.add. */
|
|
10
|
+
export const ROOMS = Object.freeze([
|
|
11
|
+
{ id: 'lobby', name: 'Lobby', kind: 'board', tools: [], accepts: ['plan'], requireApproval: false, hostOnly: false, order: 0, color: '#FFB531' },
|
|
12
|
+
{ id: 'design', name: 'Design', kind: 'work', tools: ['list_files', 'read_file', 'write_file', 'edit_file', 'check', 'preview'], accepts: ['design'], requireApproval: false, hostOnly: false, order: 1, color: '#FF7AB6' },
|
|
13
|
+
{ id: 'code', name: 'Code', kind: 'work', tools: ['list_files', 'read_file', 'write_file', 'edit_file', 'delete_file', 'run', 'check', 'preview'], accepts: ['code', 'fix'], requireApproval: false, hostOnly: false, order: 2, color: '#6CC4FF' },
|
|
14
|
+
{ id: 'review', name: 'Review', kind: 'review', tools: ['list_files', 'read_file', 'check'], accepts: ['review'], requireApproval: false, hostOnly: false, mode: 'auto', order: 3, color: '#C9A7FF' },
|
|
15
|
+
{ id: 'test', name: 'Test', kind: 'test', tools: ['list_files', 'read_file', 'run', 'check', 'preview'], accepts: ['test'], requireApproval: false, hostOnly: false, order: 4, color: '#7BE0A0' },
|
|
16
|
+
{ id: 'ops', name: 'Ops', kind: 'ops', tools: ['list_files', 'read_file', 'run'], accepts: ['ops'], requireApproval: true, hostOnly: true, order: 5, color: '#E8C27A' },
|
|
17
|
+
{ id: 'library', name: 'Library', kind: 'library', tools: ['list_files', 'read_file', 'write_file', 'edit_file', 'check', 'preview'], accepts: ['docs'], requireApproval: false, hostOnly: false, order: 6, color: '#9FD3C7' }
|
|
18
|
+
].map((r) => Object.freeze({ ...r, builtin: true })));
|
|
19
|
+
|
|
20
|
+
export const ROOM_IDS = ROOMS.map((r) => r.id);
|
|
21
|
+
/** Room kinds where an agent does the work itself (a crew job with one task). */
|
|
22
|
+
export const WORK_KINDS = new Set(['work', 'library', 'ops']);
|
|
23
|
+
|
|
24
|
+
/** Where the builtin crew works. The first room is the home room. */
|
|
25
|
+
export const SPECIALIZATION = Object.freeze({
|
|
26
|
+
mel: ['lobby', 'library'],
|
|
27
|
+
dev: ['code', 'review', 'ops'],
|
|
28
|
+
designer: ['design', 'review'],
|
|
29
|
+
qa: ['test', 'review'],
|
|
30
|
+
writer: ['library', 'design']
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
/** A home room for a hired worker, from its role. */
|
|
34
|
+
export function roomForRole(role = '') {
|
|
35
|
+
const r = String(role).toLowerCase();
|
|
36
|
+
if (/review/.test(r)) return 'review';
|
|
37
|
+
if (/\b(qa|test|check)/.test(r)) return 'test';
|
|
38
|
+
if (/design|\bui\b|css|style/.test(r)) return 'design';
|
|
39
|
+
if (/doc|writ|copy|readme/.test(r)) return 'library';
|
|
40
|
+
if (/ops|deploy|git|release/.test(r)) return 'ops';
|
|
41
|
+
return 'code';
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export const AGENT_STATUSES = Object.freeze(['idle', 'thinking', 'waiting_model', 'working', 'reviewing', 'testing', 'waiting', 'sleeping', 'offline']);
|
|
45
|
+
export const TASK_STATUSES = Object.freeze(['open', 'claimed', 'in_progress', 'in_review', 'in_test', 'done', 'blocked', 'cancelled']);
|
|
46
|
+
|
|
47
|
+
/** level = floor((1 + sqrt(1 + 8 xp / 25)) / 2): 0 xp level 1, 25 level 2, 75 level 3, 150 level 4. */
|
|
48
|
+
export function levelFor(xp) {
|
|
49
|
+
const x = Math.max(0, Number(xp) || 0);
|
|
50
|
+
return Math.max(1, Math.floor((1 + Math.sqrt(1 + (8 * x) / 25)) / 2));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** The task status while it is in a room of this kind. */
|
|
54
|
+
export function statusForKind(kind) {
|
|
55
|
+
if (kind === 'review') return 'in_review';
|
|
56
|
+
if (kind === 'test') return 'in_test';
|
|
57
|
+
return 'in_progress';
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The public view of a private memory list: the count and up to 4 highlights (pinned first, then the newest). */
|
|
61
|
+
export function publicMemory(entries = []) {
|
|
62
|
+
const list = Array.isArray(entries) ? entries : [];
|
|
63
|
+
const pinned = list.filter((e) => e.pinned);
|
|
64
|
+
const rest = list.filter((e) => !e.pinned).slice().reverse();
|
|
65
|
+
return { count: list.length, highlights: [...pinned, ...rest].slice(0, 4).map((e) => ({ id: e.id, kind: e.kind, text: e.text })) };
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Events the city reducer reads: every city.* event plus these crew events. */
|
|
69
|
+
export const CREW_EVENTS = new Set(['worker.status', 'turn.started']);
|
|
70
|
+
export const isCityEvent = (e) => !!e && typeof e.type === 'string' && (e.type.startsWith('city.') || CREW_EVENTS.has(e.type));
|
|
71
|
+
|
|
72
|
+
export function initialCity() {
|
|
73
|
+
return { v: CITY, host: null, lastSeq: 0, machines: {}, rooms: {}, agents: {}, tasks: {}, borrows: {}, hops: [] };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const WORKER_STATUS = { queued: 'waiting_model', thinking: 'thinking', tool: 'working', waiting_approval: 'waiting', error: 'idle' };
|
|
77
|
+
|
|
78
|
+
function agentByWorker(city, workerId) {
|
|
79
|
+
for (const a of Object.values(city.agents)) if (a.workerId === workerId && !a.retired) return a;
|
|
80
|
+
return null;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const BUSY = new Set(['working', 'reviewing', 'testing']);
|
|
84
|
+
|
|
85
|
+
function unhold(a) {
|
|
86
|
+
a.taskId = null;
|
|
87
|
+
if (BUSY.has(a.status)) a.status = 'idle';
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function release(city, task) {
|
|
91
|
+
for (const a of Object.values(city.agents)) if (a.taskId === task.id && a.id !== task.agentId) unhold(a);
|
|
92
|
+
if (task.agentId && city.agents[task.agentId]) city.agents[task.agentId].taskId = task.id;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function freeAll(city, task) {
|
|
96
|
+
for (const a of Object.values(city.agents)) if (a.taskId === task.id) unhold(a);
|
|
97
|
+
task.agentId = null;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function merge(target, patch) {
|
|
101
|
+
for (const [k, v] of Object.entries(patch || {})) if (k !== 'id') target[k] = v;
|
|
102
|
+
return target;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Applies one event to the city, mutating it. Returns the same object.
|
|
107
|
+
* Unknown types are ignored, so new types never break an older UI.
|
|
108
|
+
*/
|
|
109
|
+
export function reduceCity(city, event) {
|
|
110
|
+
if (!city || !event || typeof event.seq !== 'number') return city;
|
|
111
|
+
if (event.seq > city.lastSeq) city.lastSeq = event.seq;
|
|
112
|
+
if (!isCityEvent(event)) return city;
|
|
113
|
+
const d = event.data || {};
|
|
114
|
+
const ts = event.ts;
|
|
115
|
+
switch (event.type) {
|
|
116
|
+
case 'city.started':
|
|
117
|
+
city.host = d.host || city.host;
|
|
118
|
+
break;
|
|
119
|
+
case 'city.machine.joined': {
|
|
120
|
+
const m = d.machine;
|
|
121
|
+
if (!m?.id) break;
|
|
122
|
+
const before = city.machines[m.id] || {};
|
|
123
|
+
city.machines[m.id] = { lending: { turns: 0, active: 0 }, agents: [], ...before, ...m, online: m.online !== false, joinedAt: m.joinedAt || ts };
|
|
124
|
+
for (const a of Object.values(city.agents)) if (a.home === m.id && !city.machines[m.id].agents.includes(a.id) && !a.retired) city.machines[m.id].agents.push(a.id);
|
|
125
|
+
break;
|
|
126
|
+
}
|
|
127
|
+
case 'city.machine.updated':
|
|
128
|
+
if (d.machine?.id && city.machines[d.machine.id]) merge(city.machines[d.machine.id], d.machine);
|
|
129
|
+
break;
|
|
130
|
+
case 'city.machine.left': {
|
|
131
|
+
const m = city.machines[d.machineId];
|
|
132
|
+
if (!m) break;
|
|
133
|
+
m.online = false;
|
|
134
|
+
m.leftAt = ts;
|
|
135
|
+
m.brainId = null;
|
|
136
|
+
for (const a of Object.values(city.agents)) if (a.home === m.id) a.status = 'offline';
|
|
137
|
+
break;
|
|
138
|
+
}
|
|
139
|
+
case 'city.room.added':
|
|
140
|
+
if (d.room?.id) city.rooms[d.room.id] = { ...d.room };
|
|
141
|
+
break;
|
|
142
|
+
case 'city.room.updated':
|
|
143
|
+
if (d.room?.id && city.rooms[d.room.id]) merge(city.rooms[d.room.id], d.room);
|
|
144
|
+
break;
|
|
145
|
+
case 'city.room.removed':
|
|
146
|
+
delete city.rooms[d.roomId];
|
|
147
|
+
break;
|
|
148
|
+
case 'city.agent.joined': {
|
|
149
|
+
const a = d.agent;
|
|
150
|
+
if (!a?.id) break;
|
|
151
|
+
city.agents[a.id] = { ...(city.agents[a.id] || {}), ...a };
|
|
152
|
+
const m = city.machines[a.home];
|
|
153
|
+
if (m && !m.agents.includes(a.id)) m.agents.push(a.id);
|
|
154
|
+
break;
|
|
155
|
+
}
|
|
156
|
+
case 'city.agent.updated':
|
|
157
|
+
if (d.agent?.id && city.agents[d.agent.id]) merge(city.agents[d.agent.id], d.agent);
|
|
158
|
+
break;
|
|
159
|
+
case 'city.agent.moved':
|
|
160
|
+
if (city.agents[d.agentId]) city.agents[d.agentId].room = d.to;
|
|
161
|
+
break;
|
|
162
|
+
case 'city.agent.status':
|
|
163
|
+
if (city.agents[d.agentId]) city.agents[d.agentId].status = d.status;
|
|
164
|
+
break;
|
|
165
|
+
case 'city.agent.leveled':
|
|
166
|
+
if (city.agents[d.agentId]) Object.assign(city.agents[d.agentId], { level: d.level, xp: d.xp });
|
|
167
|
+
break;
|
|
168
|
+
case 'city.agent.memory':
|
|
169
|
+
if (city.agents[d.agentId]) city.agents[d.agentId].memory = { count: d.count || 0, highlights: Array.isArray(d.highlights) ? d.highlights : [] };
|
|
170
|
+
break;
|
|
171
|
+
case 'city.agent.retired': {
|
|
172
|
+
const a = city.agents[d.agentId];
|
|
173
|
+
if (!a) break;
|
|
174
|
+
a.retired = true;
|
|
175
|
+
a.status = 'sleeping';
|
|
176
|
+
a.taskId = null;
|
|
177
|
+
const m = city.machines[a.home];
|
|
178
|
+
if (m) m.agents = m.agents.filter((id) => id !== a.id);
|
|
179
|
+
break;
|
|
180
|
+
}
|
|
181
|
+
case 'city.task.created':
|
|
182
|
+
if (d.task?.id) city.tasks[d.task.id] = { issues: [], files: [], verdicts: [], loops: 0, maxLoops: MAX_LOOPS, ...d.task };
|
|
183
|
+
break;
|
|
184
|
+
case 'city.task.claimed': {
|
|
185
|
+
const t = city.tasks[d.taskId];
|
|
186
|
+
if (!t) break;
|
|
187
|
+
t.agentId = d.agentId;
|
|
188
|
+
t.status = 'claimed';
|
|
189
|
+
if (d.room) t.room = d.room;
|
|
190
|
+
t.updatedAt = ts;
|
|
191
|
+
release(city, t);
|
|
192
|
+
break;
|
|
193
|
+
}
|
|
194
|
+
case 'city.task.hop': {
|
|
195
|
+
const hop = d.hop;
|
|
196
|
+
if (hop) {
|
|
197
|
+
city.hops.push(hop);
|
|
198
|
+
if (city.hops.length > HOP_LIMIT) city.hops.splice(0, city.hops.length - HOP_LIMIT);
|
|
199
|
+
}
|
|
200
|
+
const t = d.task?.id ? city.tasks[d.task.id] : null;
|
|
201
|
+
if (!t) break;
|
|
202
|
+
merge(t, d.task);
|
|
203
|
+
t.updatedAt = ts;
|
|
204
|
+
release(city, t);
|
|
205
|
+
break;
|
|
206
|
+
}
|
|
207
|
+
case 'city.task.updated': {
|
|
208
|
+
const t = d.task?.id ? city.tasks[d.task.id] : null;
|
|
209
|
+
if (!t) break;
|
|
210
|
+
merge(t, d.task);
|
|
211
|
+
t.updatedAt = ts;
|
|
212
|
+
if ('agentId' in d.task) release(city, t);
|
|
213
|
+
break;
|
|
214
|
+
}
|
|
215
|
+
case 'city.task.verdict': {
|
|
216
|
+
const t = city.tasks[d.taskId];
|
|
217
|
+
if (!t) break;
|
|
218
|
+
t.verdicts = [...(t.verdicts || []), { room: d.room, agentId: d.agentId, passed: !!d.passed, issues: d.issues || [], by: d.by }].slice(-VERDICT_LIMIT);
|
|
219
|
+
t.issues = d.passed ? [] : (d.issues || []);
|
|
220
|
+
break;
|
|
221
|
+
}
|
|
222
|
+
case 'city.task.awaiting':
|
|
223
|
+
if (city.tasks[d.taskId]) city.tasks[d.taskId].awaiting = d.room;
|
|
224
|
+
break;
|
|
225
|
+
case 'city.task.done': {
|
|
226
|
+
const t = city.tasks[d.taskId];
|
|
227
|
+
if (!t) break;
|
|
228
|
+
t.status = 'done';
|
|
229
|
+
t.stage = (t.pipeline || []).length;
|
|
230
|
+
t.awaiting = null;
|
|
231
|
+
t.updatedAt = ts;
|
|
232
|
+
freeAll(city, t);
|
|
233
|
+
break;
|
|
234
|
+
}
|
|
235
|
+
case 'city.task.blocked':
|
|
236
|
+
case 'city.task.cancelled': {
|
|
237
|
+
const t = city.tasks[d.taskId];
|
|
238
|
+
if (!t) break;
|
|
239
|
+
t.status = event.type === 'city.task.blocked' ? 'blocked' : 'cancelled';
|
|
240
|
+
if (d.reason) t.reason = d.reason;
|
|
241
|
+
t.awaiting = null;
|
|
242
|
+
t.updatedAt = ts;
|
|
243
|
+
freeAll(city, t);
|
|
244
|
+
break;
|
|
245
|
+
}
|
|
246
|
+
case 'city.borrow.requested':
|
|
247
|
+
if (d.borrow?.id) city.borrows[d.borrow.id] = { used: { turns: 0, completionTokens: 0, ms: 0 }, ...d.borrow };
|
|
248
|
+
break;
|
|
249
|
+
case 'city.borrow.answered': {
|
|
250
|
+
const b = city.borrows[d.borrowId];
|
|
251
|
+
if (!b) break;
|
|
252
|
+
if (d.accepted) {
|
|
253
|
+
b.status = 'active';
|
|
254
|
+
b.startedAt = ts;
|
|
255
|
+
if (d.limit) b.limit = { ...b.limit, ...d.limit };
|
|
256
|
+
const m = city.machines[b.to];
|
|
257
|
+
if (m) m.lending = { ...(m.lending || { turns: 0, active: 0 }), active: (m.lending?.active || 0) + 1 };
|
|
258
|
+
}
|
|
259
|
+
break;
|
|
260
|
+
}
|
|
261
|
+
case 'city.borrow.turn': {
|
|
262
|
+
const b = city.borrows[d.borrowId];
|
|
263
|
+
if (!b) break;
|
|
264
|
+
b.used = { turns: (b.used?.turns || 0) + 1, completionTokens: (b.used?.completionTokens || 0) + (d.completionTokens || 0), ms: (b.used?.ms || 0) + (d.ms || 0) };
|
|
265
|
+
const m = city.machines[b.to];
|
|
266
|
+
if (m) m.lending = { ...(m.lending || { turns: 0, active: 0 }), turns: (m.lending?.turns || 0) + 1 };
|
|
267
|
+
break;
|
|
268
|
+
}
|
|
269
|
+
case 'city.borrow.ended': {
|
|
270
|
+
const b = city.borrows[d.borrowId];
|
|
271
|
+
if (!b) break;
|
|
272
|
+
const wasActive = b.status === 'active';
|
|
273
|
+
b.status = 'ended';
|
|
274
|
+
b.reason = d.reason;
|
|
275
|
+
b.endedAt = ts;
|
|
276
|
+
if (d.used) b.used = d.used;
|
|
277
|
+
const m = city.machines[b.to];
|
|
278
|
+
if (m && wasActive) m.lending = { ...(m.lending || { turns: 0, active: 0 }), active: Math.max(0, (m.lending?.active || 1) - 1) };
|
|
279
|
+
break;
|
|
280
|
+
}
|
|
281
|
+
case 'worker.status': {
|
|
282
|
+
const a = agentByWorker(city, d.workerId);
|
|
283
|
+
if (!a || a.status === 'sleeping' || a.status === 'offline') break;
|
|
284
|
+
if (d.status === 'idle') {
|
|
285
|
+
const t = a.taskId ? city.tasks[a.taskId] : null;
|
|
286
|
+
a.status = t ? (t.status === 'in_review' ? 'reviewing' : t.status === 'in_test' ? 'testing' : 'working') : 'idle';
|
|
287
|
+
} else if (WORKER_STATUS[d.status]) {
|
|
288
|
+
a.status = WORKER_STATUS[d.status];
|
|
289
|
+
}
|
|
290
|
+
break;
|
|
291
|
+
}
|
|
292
|
+
case 'turn.started': {
|
|
293
|
+
const a = agentByWorker(city, d.workerId);
|
|
294
|
+
if (!a) break;
|
|
295
|
+
const m = Object.values(city.machines).find((x) => x.brainId && x.brainId === d.brainId);
|
|
296
|
+
if (m) a.brain = { kind: m.id === a.home ? (m.host ? 'local' : 'remote') : 'lent', machineId: m.id, label: m.model || m.name };
|
|
297
|
+
else a.brain = { kind: 'cloud', label: d.brainId };
|
|
298
|
+
break;
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
return city;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** Rebuilds the city from a list of events, optionally on top of a snapshot. */
|
|
305
|
+
export function replayCity(events, upto = Infinity, base = null) {
|
|
306
|
+
const city = base ? JSON.parse(JSON.stringify(base)) : initialCity();
|
|
307
|
+
for (const e of events) {
|
|
308
|
+
if (e.seq > upto) break;
|
|
309
|
+
if (base && e.seq <= base.lastSeq) continue;
|
|
310
|
+
reduceCity(city, e);
|
|
311
|
+
}
|
|
312
|
+
return city;
|
|
313
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
// Hive City on disk.
|
|
2
|
+
// <home>/city/machine.json this machine's stable id and name
|
|
3
|
+
// <home>/city/agents/<id>.json one persistent agent per file, with its full private memory
|
|
4
|
+
// <dir>/.hivedesk/city/snapshot.json the last city snapshot of this project and its seq (a cache for city.sync)
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import crypto from 'node:crypto';
|
|
8
|
+
|
|
9
|
+
function readJson(file, fallback) {
|
|
10
|
+
try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return fallback; }
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function writeJson(file, data) {
|
|
14
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
15
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
16
|
+
fs.writeFileSync(tmp, JSON.stringify(data, null, 2));
|
|
17
|
+
fs.renameSync(tmp, file);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Agent ids become file names: keep them to a safe set of characters. */
|
|
21
|
+
export function agentFileName(id) {
|
|
22
|
+
return `${String(id).replace(/[^A-Za-z0-9_.-]/g, '_').slice(0, 80)}.json`;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export class CityStore {
|
|
26
|
+
/** @param {{ home?: string | null, projectDir?: string | null }} opts home: the shared cache (~/.hivedesk); projectDir: <dir>/.hivedesk/city */
|
|
27
|
+
constructor(opts = {}) {
|
|
28
|
+
this.root = opts.home ? path.join(opts.home, 'city') : null;
|
|
29
|
+
this.projectDir = opts.projectDir || null;
|
|
30
|
+
this._machine = null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** This machine's card, created once: { id: "m_" + 8 hex, name }. */
|
|
34
|
+
machine() {
|
|
35
|
+
if (this._machine) return this._machine;
|
|
36
|
+
const file = this.root ? path.join(this.root, 'machine.json') : null;
|
|
37
|
+
let m = file ? readJson(file, null) : null;
|
|
38
|
+
if (!m || typeof m.id !== 'string' || !/^m_[0-9a-f]{8}$/.test(m.id)) {
|
|
39
|
+
m = { id: `m_${crypto.randomBytes(4).toString('hex')}`, name: 'My PC', createdAt: new Date().toISOString() };
|
|
40
|
+
if (file) { try { writeJson(file, m); } catch { /* read only home: the id lives for this run */ } }
|
|
41
|
+
}
|
|
42
|
+
this._machine = m;
|
|
43
|
+
return m;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
setMachineName(name) {
|
|
47
|
+
const m = { ...this.machine(), name: String(name).slice(0, 40) };
|
|
48
|
+
this._machine = m;
|
|
49
|
+
if (this.root) { try { writeJson(path.join(this.root, 'machine.json'), m); } catch { /* ignore */ } }
|
|
50
|
+
return m;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
agentsDir() {
|
|
54
|
+
return this.root ? path.join(this.root, 'agents') : null;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Every agent saved on this machine. */
|
|
58
|
+
loadAgents() {
|
|
59
|
+
const dir = this.agentsDir();
|
|
60
|
+
if (!dir || !fs.existsSync(dir)) return [];
|
|
61
|
+
const out = [];
|
|
62
|
+
for (const f of fs.readdirSync(dir)) {
|
|
63
|
+
if (!f.endsWith('.json')) continue;
|
|
64
|
+
const a = readJson(path.join(dir, f), null);
|
|
65
|
+
if (a && typeof a.id === 'string') out.push(a);
|
|
66
|
+
}
|
|
67
|
+
return out;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
loadAgent(id) {
|
|
71
|
+
const dir = this.agentsDir();
|
|
72
|
+
return dir ? readJson(path.join(dir, agentFileName(id)), null) : null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
saveAgent(agent) {
|
|
76
|
+
const dir = this.agentsDir();
|
|
77
|
+
if (!dir || !agent?.id) return false;
|
|
78
|
+
try { writeJson(path.join(dir, agentFileName(agent.id)), { ...agent, savedAt: new Date().toISOString() }); return true; } catch { return false; }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
loadSnapshot() {
|
|
82
|
+
if (!this.projectDir) return null;
|
|
83
|
+
const s = readJson(path.join(this.projectDir, 'snapshot.json'), null);
|
|
84
|
+
return s && typeof s.seq === 'number' && s.city ? s : null;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
saveSnapshot(seq, city) {
|
|
88
|
+
if (!this.projectDir) return false;
|
|
89
|
+
try { writeJson(path.join(this.projectDir, 'snapshot.json'), { seq, city }); return true; } catch { return false; }
|
|
90
|
+
}
|
|
91
|
+
}
|
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
|
|
|
@@ -21,9 +22,12 @@ Usage: npx hivedesk [options]
|
|
|
21
22
|
--brain <name> ollama, lmstudio or openai (with --url, --model and HIVEDESK_API_KEY)
|
|
22
23
|
--url <url> base URL for --brain
|
|
23
24
|
--no-download never download a model; the UI offers the download instead
|
|
25
|
+
--no-city run without Hive City (agents, rooms and the task bus); the 0.1 desktop works the same
|
|
24
26
|
--cpu do not use the GPU
|
|
25
27
|
--ctx <n> context size for the local model (default: up to 8192)
|
|
26
|
-
--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)
|
|
27
31
|
--lend lend this machine's model to a paired friend (opens the Lend screen)
|
|
28
32
|
--join <link|words> open the desktop with "Use a friend's PC" filled in with these six words
|
|
29
33
|
--yes skip the setup questions (the saved setup, or the recommended defaults)
|
|
@@ -33,9 +37,11 @@ Usage: npx hivedesk [options]
|
|
|
33
37
|
|
|
34
38
|
First run: see FIRST-RUN.md. Cache folder: ~/.hivedesk (or HIVEDESK_HOME).`;
|
|
35
39
|
|
|
40
|
+
export { hasRealLog };
|
|
41
|
+
|
|
36
42
|
export function parseArgs(argv) {
|
|
37
43
|
const o = { open: true, download: true };
|
|
38
|
-
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']);
|
|
39
45
|
for (let i = 0; i < argv.length; i++) {
|
|
40
46
|
const a = argv[i];
|
|
41
47
|
if (!a.startsWith('--')) throw new Error(`unexpected argument: ${a}`);
|
|
@@ -48,6 +54,7 @@ export function parseArgs(argv) {
|
|
|
48
54
|
o[key] = val;
|
|
49
55
|
} else if (key === 'no-open') o.open = false;
|
|
50
56
|
else if (key === 'no-download') o.download = false;
|
|
57
|
+
else if (key === 'no-city') o.city = false;
|
|
51
58
|
else if (['demo', 'lend', 'doctor', 'help', 'version', 'cpu', 'yes', 'browser', 'new-token'].includes(key)) o[key] = true;
|
|
52
59
|
else throw new Error(`unknown option: --${key}`);
|
|
53
60
|
}
|
|
@@ -65,6 +72,27 @@ export function parseArgs(argv) {
|
|
|
65
72
|
return o;
|
|
66
73
|
}
|
|
67
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
|
+
|
|
68
96
|
/** Six words from a share link (#w=...) or from words separated by spaces or dashes. */
|
|
69
97
|
export function joinWords(input) {
|
|
70
98
|
const s = String(input || '');
|
|
@@ -226,17 +254,28 @@ async function main() {
|
|
|
226
254
|
if (setup.open === false) args.open = false;
|
|
227
255
|
}
|
|
228
256
|
}
|
|
229
|
-
if (args
|
|
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
|
+
}
|
|
230
267
|
const progress = makeProgress();
|
|
231
268
|
const log = (line) => { progress(null); console.log(` ${line}`); };
|
|
232
|
-
console.log(`hivedesk ${VERSION}${args.demo ? ' (
|
|
269
|
+
console.log(`hivedesk ${VERSION}${args.demo ? ' (DEMO: no model, scripted crew, a separate demo folder)' : ''}${args.lend ? ' (lend mode)' : ''}`);
|
|
233
270
|
const port = args.port !== undefined ? args.port : await stablePort(4174);
|
|
234
271
|
const app = await startHive({
|
|
235
272
|
dir,
|
|
236
273
|
port,
|
|
237
274
|
token: args.demo ? undefined : loadToken(cacheHome(), !!args['new-token']),
|
|
238
275
|
demo: !!args.demo,
|
|
276
|
+
...(demoHome ? { home: demoHome } : {}),
|
|
239
277
|
lend: !!args.lend,
|
|
278
|
+
city: args.city !== false,
|
|
240
279
|
log,
|
|
241
280
|
progress,
|
|
242
281
|
flags: {
|
|
@@ -246,7 +285,7 @@ async function main() {
|
|
|
246
285
|
}
|
|
247
286
|
});
|
|
248
287
|
if (setup) app.hive.setSettings({ approvalMode: setup.approvalMode, crew: setup.crew });
|
|
249
|
-
console.log(` folder: ${path.join(dir, '.hivedesk')}`);
|
|
288
|
+
console.log(` ${args.demo ? 'demo folder' : 'folder'}: ${path.join(dir, '.hivedesk')}`);
|
|
250
289
|
console.log(` open: ${app.url}`);
|
|
251
290
|
const openUrl = startUrl(app.server.port, app.server.token, args);
|
|
252
291
|
if (openUrl !== app.url) console.log(` ${openUrl}`);
|
package/src/collab/index.js
CHANGED
|
@@ -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
|
|
5
|
-
//
|
|
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 =
|
|
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
|
+
}
|