hivedesk 0.1.0 → 0.2.0
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 +24 -0
- package/FIRST-RUN.md +14 -0
- package/PROTOCOL.md +16 -3
- package/README.md +50 -6
- package/assets/illustrations/hive-city.svg +113 -0
- package/assets/video-poster.webp +0 -0
- package/i18n/README.pt-BR.md +44 -6
- package/i18n/de.json +174 -0
- package/i18n/en.json +174 -0
- package/i18n/es.json +174 -0
- package/i18n/fr.json +174 -0
- package/i18n/it.json +174 -0
- package/i18n/ja.json +174 -0
- package/i18n/ko.json +174 -0
- package/i18n/pt-BR.json +174 -0
- package/i18n/ru.json +174 -0
- package/i18n/zh-CN.json +174 -0
- package/package.json +1 -1
- package/src/bus.js +7 -1
- package/src/city/demo.js +75 -0
- package/src/city/hops.js +95 -0
- package/src/city/index.js +1507 -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 +3 -0
- package/src/crew/engine.js +40 -3
- package/src/demo.js +30 -2
- package/src/index.js +23 -2
- package/src/server.js +4 -1
- package/ui/city/city.css +204 -0
- package/ui/city/city.js +933 -0
- package/ui/city/collab.js +64 -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/js/main.js +3 -1
- package/ui/lend/collab/roles.js +8 -2
- 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
|
@@ -21,6 +21,7 @@ Usage: npx hivedesk [options]
|
|
|
21
21
|
--brain <name> ollama, lmstudio or openai (with --url, --model and HIVEDESK_API_KEY)
|
|
22
22
|
--url <url> base URL for --brain
|
|
23
23
|
--no-download never download a model; the UI offers the download instead
|
|
24
|
+
--no-city run without Hive City (agents, rooms and the task bus); the 0.1 desktop works the same
|
|
24
25
|
--cpu do not use the GPU
|
|
25
26
|
--ctx <n> context size for the local model (default: up to 8192)
|
|
26
27
|
--demo scripted demo, no model; every event is labeled as a demo
|
|
@@ -48,6 +49,7 @@ export function parseArgs(argv) {
|
|
|
48
49
|
o[key] = val;
|
|
49
50
|
} else if (key === 'no-open') o.open = false;
|
|
50
51
|
else if (key === 'no-download') o.download = false;
|
|
52
|
+
else if (key === 'no-city') o.city = false;
|
|
51
53
|
else if (['demo', 'lend', 'doctor', 'help', 'version', 'cpu', 'yes', 'browser', 'new-token'].includes(key)) o[key] = true;
|
|
52
54
|
else throw new Error(`unknown option: --${key}`);
|
|
53
55
|
}
|
|
@@ -237,6 +239,7 @@ async function main() {
|
|
|
237
239
|
token: args.demo ? undefined : loadToken(cacheHome(), !!args['new-token']),
|
|
238
240
|
demo: !!args.demo,
|
|
239
241
|
lend: !!args.lend,
|
|
242
|
+
city: args.city !== false,
|
|
240
243
|
log,
|
|
241
244
|
progress,
|
|
242
245
|
flags: {
|
package/src/crew/engine.js
CHANGED
|
@@ -48,6 +48,9 @@ export class Hive {
|
|
|
48
48
|
this.memory = new Memory();
|
|
49
49
|
/** @type {Map<string, { ctrl: AbortController, notes: Map<string, string[]>, promise: Promise<any> }>} */
|
|
50
50
|
this.active = new Map();
|
|
51
|
+
/** Hive City hooks (src/city/), optional: the worker a task runs with (room tools) and extra memories for its prompt. */
|
|
52
|
+
this.adaptWorker = null;
|
|
53
|
+
this.extraMemories = null;
|
|
51
54
|
}
|
|
52
55
|
|
|
53
56
|
get state() {
|
|
@@ -165,11 +168,14 @@ export class Hive {
|
|
|
165
168
|
refine: spec.refine === undefined ? this.state.settings.refine !== false : !!spec.refine,
|
|
166
169
|
createdAt: new Date().toISOString(), taskIds: []
|
|
167
170
|
};
|
|
171
|
+
// A city hop (src/city/): one given task, no brief, no planner, no report.
|
|
172
|
+
const plan = Array.isArray(spec.plan) && spec.plan.length ? spec.plan : null;
|
|
173
|
+
if (plan) { job.refine = false; job.cityTaskId = String(spec.cityTaskId || '').slice(0, 40) || undefined; }
|
|
168
174
|
const ctrl = new AbortController();
|
|
169
175
|
const run = { ctrl, notes: new Map(), promise: null };
|
|
170
176
|
this.active.set(jobId, run);
|
|
171
177
|
this.bus.emit('job.created', { job }, { jobId });
|
|
172
|
-
run.promise = this._runJob(job, run, spec.playbookId).catch((err) => {
|
|
178
|
+
run.promise = (plan ? this._runPlanned(job, run, plan) : this._runJob(job, run, spec.playbookId)).catch((err) => {
|
|
173
179
|
if (ctrl.signal.aborted) return;
|
|
174
180
|
this.bus.emit('job.failed', { error: String(err?.message || err) }, { jobId });
|
|
175
181
|
}).finally(() => {
|
|
@@ -265,6 +271,34 @@ export class Hive {
|
|
|
265
271
|
});
|
|
266
272
|
}
|
|
267
273
|
|
|
274
|
+
/** A job with a given plan (a Hive City hop): the tasks run as they are, without the planner, QA rounds or the report. */
|
|
275
|
+
async _runPlanned(job, run, plan) {
|
|
276
|
+
const jobNum = job.id.slice(2);
|
|
277
|
+
const graph = new TaskGraph();
|
|
278
|
+
const known = this.crewById();
|
|
279
|
+
const tasks = plan.slice(0, 8).map((t, i) => graph.add({
|
|
280
|
+
id: `t_${jobNum}_${i + 1}`, jobId: job.id, title: String(t.title || 'Task').slice(0, 200), detail: String(t.detail || '').slice(0, 8000),
|
|
281
|
+
assignee: known.has(t.assignee) ? t.assignee : 'dev', dependsOn: (t.dependsOn || []).map((d) => `t_${jobNum}_${d + 1}`), status: 'pending', attempts: 0,
|
|
282
|
+
kind: ['build', 'fix', 'docs'].includes(t.kind) ? t.kind : 'build'
|
|
283
|
+
}));
|
|
284
|
+
run.memories = [];
|
|
285
|
+
this.bus.emit('job.planned', { tasks: tasks.map((t) => ({ ...t })) }, { jobId: job.id });
|
|
286
|
+
await this._drive(job, run, {
|
|
287
|
+
graph, tasks: null, preexisting: new Set(this.toolbox.ws.list().map((f) => f.path)), fixRounds: MAX_FIX_ROUNDS, nextIdx: tasks.length + 1,
|
|
288
|
+
qaPassed: true, openIssues: [], playbook: null, score: 0, quiet: true
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** Adds a note for one worker of a running job, as if the user had written it (Hive City review notes). */
|
|
293
|
+
addNote(jobId, workerId, text) {
|
|
294
|
+
const run = this.active.get(jobId);
|
|
295
|
+
if (!run) return false;
|
|
296
|
+
const list = run.notes.get(workerId) || [];
|
|
297
|
+
list.push(String(text).slice(0, 2000));
|
|
298
|
+
run.notes.set(workerId, list.slice(-5));
|
|
299
|
+
return true;
|
|
300
|
+
}
|
|
301
|
+
|
|
268
302
|
/** Runs the task graph of a job to the end: workers take turns, QA adds fix rounds, then done. */
|
|
269
303
|
async _drive(job, run, st) {
|
|
270
304
|
const jobId = job.id;
|
|
@@ -285,7 +319,8 @@ export class Hive {
|
|
|
285
319
|
|
|
286
320
|
const startTask = (task) => {
|
|
287
321
|
const crewById = this.crewById();
|
|
288
|
-
const
|
|
322
|
+
const base = crewById.get(task.assignee) || crewById.get('dev');
|
|
323
|
+
const worker = (this.adaptWorker && this.adaptWorker(base, task, job)) || base;
|
|
289
324
|
graph.setStatus(task.id, 'running');
|
|
290
325
|
this.bus.emit('task.status', { taskId: task.id, status: 'running' }, ev);
|
|
291
326
|
const userNotes = () => [...(run.notes.get('*') || []), ...(run.notes.get(worker.id) || [])];
|
|
@@ -314,7 +349,7 @@ export class Hive {
|
|
|
314
349
|
job, task, worker, graph, crewById, scheduler: this.scheduler, toolbox: this.toolbox, memory: this.memory, bus: this.bus,
|
|
315
350
|
signal: anySignal([signal, control.ctrl.signal]), maxTurns: this.maxTurns, extra, userNotes, preexisting: st.preexisting, budget: run.budget,
|
|
316
351
|
family: modelFamily(this.state.brain), contextTokens: this.state.brain?.ctx || undefined,
|
|
317
|
-
recent: () => this._recentFiles(jobId), memories: run.memories || [],
|
|
352
|
+
recent: () => this._recentFiles(jobId), memories: [...(run.memories || []), ...((this.extraMemories && this.extraMemories(worker.id, task)) || [])],
|
|
318
353
|
verify: task.kind === 'qa' ? undefined : (wrote) => {
|
|
319
354
|
// Fix tasks must clear every static issue; build tasks only the ones in their own files
|
|
320
355
|
// (a link to a file another worker has not written yet is not their problem).
|
|
@@ -398,6 +433,7 @@ export class Hive {
|
|
|
398
433
|
const buildTasks = all.filter((t) => t.kind !== 'qa' && t.status !== 'skipped');
|
|
399
434
|
if (buildTasks.length && buildTasks.every((t) => t.status === 'failed' || t.status === 'blocked')) {
|
|
400
435
|
this.bus.emit('job.failed', { error: `${failed.length} tasks failed` }, ev);
|
|
436
|
+
if (st.quiet) return;
|
|
401
437
|
this.chat('mel', 'This job did not work out. You can retry a task from its menu, try a smaller request, or use a bigger model.', undefined, 'general', jobId);
|
|
402
438
|
await this._report(job, run);
|
|
403
439
|
return;
|
|
@@ -406,6 +442,7 @@ export class Hive {
|
|
|
406
442
|
? `Finished with ${failed.length} failed tasks.`
|
|
407
443
|
: st.qaPassed ? `Finished, and QA passed.${skipped ? ` ${skipped} tasks were cancelled.` : ''}` : `Finished, but QA still reports ${st.openIssues.length} issues.`;
|
|
408
444
|
this.bus.emit('job.done', { summary, files: outFiles }, ev);
|
|
445
|
+
if (st.quiet) return;
|
|
409
446
|
const url = this.previewUrl();
|
|
410
447
|
this.chat('mel', `${summary} Files: ${outFiles.join(', ') || 'none'}.${url ? ' Open the Live preview to see it.' : ''}`, undefined, 'general', jobId);
|
|
411
448
|
if (st.tasks && !failed.length && !skipped && st.qaPassed && !(st.playbook && st.score >= 0.6)) {
|
package/src/demo.js
CHANGED
|
@@ -146,7 +146,33 @@ const PLAN = {
|
|
|
146
146
|
]
|
|
147
147
|
};
|
|
148
148
|
|
|
149
|
+
/** The Hive City demo task (src/city/demo.js): Design, Code, Review, Test, done. */
|
|
150
|
+
export const DEMO_CITY_TASK = {
|
|
151
|
+
title: 'Add a weekly specials section',
|
|
152
|
+
detail: 'Show the three specials of this week on the bakery page, between the breads and the opening hours.'
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
const SPECIALS = ` <section class="specials">
|
|
156
|
+
<h2>This week</h2>
|
|
157
|
+
<ul>
|
|
158
|
+
<li>Pumpkin loaf, on Tuesday</li>
|
|
159
|
+
<li>Fig and walnut rye, on Thursday</li>
|
|
160
|
+
<li>Cardamom buns, on Saturday</li>
|
|
161
|
+
</ul>
|
|
162
|
+
</section>
|
|
163
|
+
<section class="hours">`;
|
|
164
|
+
|
|
165
|
+
const DESIGN = {
|
|
166
|
+
spec: 'In index.html, add a section with class "specials" right before the opening hours: an h2 "This week" and a list of three specials, each with its day. Reuse the existing card look; no new files.',
|
|
167
|
+
criteria: ['index.html has a "This week" section before the opening hours', 'The section lists three specials, each with a day', 'The page still passes the static checks']
|
|
168
|
+
};
|
|
169
|
+
|
|
149
170
|
const SCRIPTS = {
|
|
171
|
+
[DEMO_CITY_TASK.title]: [
|
|
172
|
+
{ tool: 'read_file', args: { path: 'index.html' } },
|
|
173
|
+
{ tool: 'edit_file', args: { path: 'index.html', search: ' <section class="hours">', replace: SPECIALS } },
|
|
174
|
+
{ tool: 'done', args: { summary: 'Added the weekly specials section before the opening hours.' } }
|
|
175
|
+
],
|
|
150
176
|
'Set the look': [
|
|
151
177
|
{ tool: 'say', args: { text: 'Going for warm crust colors and a lot of air around the text.' } },
|
|
152
178
|
{ tool: 'write_file', args: { path: 'style.css', content: STYLE } },
|
|
@@ -201,6 +227,8 @@ const REPORT = {
|
|
|
201
227
|
|
|
202
228
|
/** The demo responder: the brief and the plan for Mel, a fixed list of actions per task, then the report. */
|
|
203
229
|
export function demoRespond(messages, options) {
|
|
230
|
+
if (options.schema?.properties?.spec) return DESIGN;
|
|
231
|
+
if (options.schema?.properties?.approved) return { approved: true, issues: [] };
|
|
204
232
|
if (options.schema?.properties?.goal) return BRIEF;
|
|
205
233
|
if (options.schema?.properties?.improvedPrompt) return REPORT;
|
|
206
234
|
if (options.schema?.properties?.tasks) return PLAN;
|
|
@@ -214,8 +242,8 @@ export function demoRespond(messages, options) {
|
|
|
214
242
|
|
|
215
243
|
export function createDemoBrain(opts = {}) {
|
|
216
244
|
return createFakeBrain({
|
|
217
|
-
id: 'demo',
|
|
218
|
-
label: 'Demo script (no model)',
|
|
245
|
+
id: opts.id || 'demo',
|
|
246
|
+
label: opts.label || 'Demo script (no model)',
|
|
219
247
|
model: 'demo script',
|
|
220
248
|
respond: demoRespond,
|
|
221
249
|
delayMs: opts.delayMs ?? 400,
|