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,1546 @@
|
|
|
1
|
+
// Hive City, engine side (CITY-PROTOCOL.md). The city is the state of the system:
|
|
2
|
+
// machines are buildings, crew workers are persistent agents with levels and memory, rooms have
|
|
3
|
+
// rules (tools, what they accept, approval), tasks travel a pipeline of rooms on a bus, every hop
|
|
4
|
+
// is an event, and an agent can borrow another machine's GPU.
|
|
5
|
+
// It runs inside the host engine on the same event log, so the existing Code together relay
|
|
6
|
+
// (engine frames to every guest) replicates it, and a restart replays it.
|
|
7
|
+
import os from 'node:os';
|
|
8
|
+
import { ALL_TOOLS } from '../tools/index.js';
|
|
9
|
+
import { guestOf, checkGuest } from '../collab/policy.js';
|
|
10
|
+
import { acceptanceFrom } from '../crew/brief.js';
|
|
11
|
+
import {
|
|
12
|
+
CITY, ROOMS, ROOM_IDS, WORK_KINDS, SPECIALIZATION, MAX_LOOPS, roomForRole, levelFor, publicMemory, statusForKind, isCityEvent
|
|
13
|
+
} from './state.js';
|
|
14
|
+
import { CityStore } from './store.js';
|
|
15
|
+
import { pickAgent } from './router.js';
|
|
16
|
+
import { DESIGN_SCHEMA, REVIEW_SCHEMA, designMessages, reviewMessages, checkFiles, readReview, readDesign } from './hops.js';
|
|
17
|
+
|
|
18
|
+
export { CityStore } from './store.js';
|
|
19
|
+
export * from './state.js';
|
|
20
|
+
|
|
21
|
+
export class CityError extends Error {
|
|
22
|
+
constructor(code, message) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.code = code;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const fail = (code, message) => { throw new CityError(code, message); };
|
|
29
|
+
const str = (v, max) => (typeof v === 'string' ? v.trim().slice(0, max) : '');
|
|
30
|
+
const COLOR = /^#[0-9a-fA-F]{6}$/;
|
|
31
|
+
const TERMINAL = new Set(['done', 'blocked', 'cancelled']);
|
|
32
|
+
/** Tools a guest's task never gets: no shell, no deletes. */
|
|
33
|
+
export const GUEST_DENY = new Set(['run', 'delete_file']);
|
|
34
|
+
/** The tools a guest's agent comes with: it reads and checks; only the host can grant more. */
|
|
35
|
+
export const GUEST_TOOLS = Object.freeze(['list_files', 'read_file', 'check', 'preview']);
|
|
36
|
+
export const LIMITS = Object.freeze({
|
|
37
|
+
title: 200, detail: 4000, criteria: 6, criterion: 200, memoryText: 300, memoryEntries: 40, name: 40,
|
|
38
|
+
guestCommands: 40, guestWindowMs: 10_000, presencePerSecond: 15, agentsPerMachine: 4, pipeline: 8,
|
|
39
|
+
borrowTurns: 50, borrowMinutes: 60, borrowPendingMs: 60_000, tail: 5000, snapshotEvery: 200
|
|
40
|
+
});
|
|
41
|
+
const XP = { work: 10, review: 4, test: 3, clean: 5 };
|
|
42
|
+
const MEMORY_KINDS = new Set(['fact', 'preference', 'decision', 'task']);
|
|
43
|
+
const PROMPT_KINDS = new Set(['fact', 'preference', 'decision']);
|
|
44
|
+
|
|
45
|
+
export class City {
|
|
46
|
+
/**
|
|
47
|
+
* @param {{
|
|
48
|
+
* bus: import('../bus.js').EventBus, hive: import('../crew/engine.js').Hive, scheduler: import('../crew/scheduler.js').Scheduler,
|
|
49
|
+
* toolbox: import('../tools/index.js').ToolBox, home?: string | null, projectDir?: string | null, version?: string,
|
|
50
|
+
* store?: CityStore, now?: () => number
|
|
51
|
+
* }} opts
|
|
52
|
+
*/
|
|
53
|
+
constructor(opts) {
|
|
54
|
+
this.bus = opts.bus;
|
|
55
|
+
this.hive = opts.hive;
|
|
56
|
+
this.scheduler = opts.scheduler;
|
|
57
|
+
this.toolbox = opts.toolbox;
|
|
58
|
+
this.version = opts.version || '0.0.0';
|
|
59
|
+
this.now = opts.now || Date.now;
|
|
60
|
+
this.store = opts.store || new CityStore({ home: opts.home ?? null, projectDir: opts.projectDir ?? null });
|
|
61
|
+
this.machineId = this.store.machine().id;
|
|
62
|
+
/** taskId -> { ctrl, agentId, room, jobId? } the hops the city runs itself */
|
|
63
|
+
this.exec = new Map();
|
|
64
|
+
/** agentId -> private memory entries (agents homed on this machine) */
|
|
65
|
+
this.memories = new Map();
|
|
66
|
+
/** jobId -> { taskId, mode: "hop" | "plan" } jobs the city started */
|
|
67
|
+
this.jobOwners = new Map();
|
|
68
|
+
/** crew taskId -> city taskId (planner tasks) */
|
|
69
|
+
this.linkIndex = new Map();
|
|
70
|
+
/** crew fix taskId -> city task ids that loop through it */
|
|
71
|
+
this.fixFor = new Map();
|
|
72
|
+
/** city task ids waiting in Test for the crew QA report */
|
|
73
|
+
this.waitingQa = new Set();
|
|
74
|
+
/** crew taskId -> Map(path -> diff) */
|
|
75
|
+
this.crewFiles = new Map();
|
|
76
|
+
/** borrowId -> { timer, prevPref, addedOnly, workerId, brainId } */
|
|
77
|
+
this.borrowRt = new Map();
|
|
78
|
+
this.guestRate = new Map();
|
|
79
|
+
this.presenceRate = new Map();
|
|
80
|
+
this.loads = new Map();
|
|
81
|
+
this.queue = [];
|
|
82
|
+
this.draining = false;
|
|
83
|
+
this.routeQueued = false;
|
|
84
|
+
this.saveTimers = new Map();
|
|
85
|
+
this.closed = false;
|
|
86
|
+
this.started = false;
|
|
87
|
+
this.cityEvents = 0;
|
|
88
|
+
this.snapshot = null;
|
|
89
|
+
this.onTaskDone = null;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
get state() {
|
|
93
|
+
return this.bus.state.city;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
emit(type, data) {
|
|
97
|
+
if (this.closed) return null;
|
|
98
|
+
return this.bus.emit(type, data);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// ---------------------------------------------------------------- start
|
|
102
|
+
start() {
|
|
103
|
+
if (this.started) return this;
|
|
104
|
+
this.started = true;
|
|
105
|
+
const s = this.state;
|
|
106
|
+
for (const t of Object.values(s.tasks)) {
|
|
107
|
+
const m = /^ct_(\d+)$/.exec(t.id);
|
|
108
|
+
if (m) this.taskSeq = Math.max(this.taskSeq || 0, Number(m[1]));
|
|
109
|
+
}
|
|
110
|
+
this.taskSeq = this.taskSeq || 0;
|
|
111
|
+
this.emit('city.started', { city: CITY, host: this.machineId, version: this.version });
|
|
112
|
+
this._hostMachine();
|
|
113
|
+
for (const m of Object.values(s.machines)) {
|
|
114
|
+
if (m.id !== this.machineId && m.online) this.emit('city.machine.left', { machineId: m.id, reason: 'restart' });
|
|
115
|
+
}
|
|
116
|
+
for (const r of ROOMS) if (!s.rooms[r.id]) this.emit('city.room.added', { room: { ...r } });
|
|
117
|
+
// Agents: the crew of this project, with the levels and memories saved on this machine.
|
|
118
|
+
for (const w of this.bus.state.crew) this._ensureAgent(w);
|
|
119
|
+
for (const a of Object.values(s.agents)) {
|
|
120
|
+
if (a.home === this.machineId && !a.retired && a.status !== 'sleeping' && a.status !== 'idle') this.emit('city.agent.status', { agentId: a.id, status: 'idle' });
|
|
121
|
+
}
|
|
122
|
+
for (const b of Object.values(s.borrows)) if (b.status !== 'ended') this.emit('city.borrow.ended', { borrowId: b.id, reason: 'stopped', used: b.used });
|
|
123
|
+
// Unfinished work opens again in the same room and is claimed again.
|
|
124
|
+
for (const t of Object.values(s.tasks)) {
|
|
125
|
+
if (!['claimed', 'in_progress', 'in_review', 'in_test'].includes(t.status) && !(t.status === 'open' && t.link)) continue;
|
|
126
|
+
const patch = { status: 'open', agentId: null, awaiting: t.awaiting || null };
|
|
127
|
+
if (t.link) Object.assign(patch, { link: null, was: t.link });
|
|
128
|
+
this._hop(t, t.room, patch, 'system', 'hivedesk restarted: the task opens again here');
|
|
129
|
+
}
|
|
130
|
+
this.snapshot = { seq: this.bus.seq, city: clone(this.state) };
|
|
131
|
+
this.store.saveSnapshot(this.snapshot.seq, this.snapshot.city);
|
|
132
|
+
this.off = this.bus.on((e) => this._enqueue(e));
|
|
133
|
+
if (this.hive) {
|
|
134
|
+
this.hive.adaptWorker = (worker, task, job) => this._adaptWorker(worker, task, job);
|
|
135
|
+
this.hive.extraMemories = (workerId) => this._promptMemories(workerId);
|
|
136
|
+
}
|
|
137
|
+
this._kick();
|
|
138
|
+
return this;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
_hostMachine() {
|
|
142
|
+
const s = this.state;
|
|
143
|
+
const card = this.store.machine();
|
|
144
|
+
const hw = this.bus.state.hardware;
|
|
145
|
+
const brain = this.bus.state.brain;
|
|
146
|
+
const local = this._localBrainId();
|
|
147
|
+
const machine = {
|
|
148
|
+
id: this.machineId, name: card.name || 'My PC', host: true, owner: 'host', online: true,
|
|
149
|
+
gpu: hw?.gpu || null, ramBytes: hw?.ramBytes, cpus: hw?.cpus || os.cpus()?.length,
|
|
150
|
+
model: brain?.model || undefined, brainId: local || null, via: 'local'
|
|
151
|
+
};
|
|
152
|
+
if (!s.machines[this.machineId]) this.emit('city.machine.joined', { machine: { ...machine, lending: { turns: 0, active: 0 }, agents: [] } });
|
|
153
|
+
else this.emit('city.machine.updated', { machine });
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** The id of a brain on this machine (local or cloud), if one is attached. */
|
|
157
|
+
_localBrainId() {
|
|
158
|
+
const linked = new Set(Object.values(this.state.machines).filter((m) => !m.host && m.brainId).map((m) => m.brainId));
|
|
159
|
+
for (const [id, slot] of this.scheduler.brains) if (slot.brain.kind !== 'remote' && !linked.has(id)) return id;
|
|
160
|
+
return null;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
_agentByWorker(workerId) {
|
|
164
|
+
for (const a of Object.values(this.state.agents)) if (a.workerId === workerId && !a.retired) return a;
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
_ensureAgent(w, extra = {}) {
|
|
169
|
+
const existing = this._agentByWorker(w.id);
|
|
170
|
+
if (existing) {
|
|
171
|
+
if (!this.memories.has(existing.id) && existing.home === this.machineId) {
|
|
172
|
+
const saved = this.store.loadAgent(existing.id);
|
|
173
|
+
this.memories.set(existing.id, Array.isArray(saved?.memoryEntries) ? saved.memoryEntries : []);
|
|
174
|
+
// A higher level saved on this machine (another project) wins: the agent is the same.
|
|
175
|
+
if (saved && (saved.xp || 0) > (existing.xp || 0)) this.emit('city.agent.leveled', { agentId: existing.id, level: levelFor(saved.xp), xp: saved.xp });
|
|
176
|
+
if (!saved) this._save(existing.id);
|
|
177
|
+
}
|
|
178
|
+
return existing;
|
|
179
|
+
}
|
|
180
|
+
const saved = this.store.loadAgent(w.id);
|
|
181
|
+
const entries = Array.isArray(saved?.memoryEntries) ? saved.memoryEntries.slice(-LIMITS.memoryEntries) : [];
|
|
182
|
+
this.memories.set(w.id, entries);
|
|
183
|
+
const spec = cleanSpec(extra.specialization) || cleanSpec(saved?.specialization) || SPECIALIZATION[w.id] || [roomForRole(w.role)];
|
|
184
|
+
const xp = Math.max(0, Number(saved?.xp) || 0);
|
|
185
|
+
const agent = {
|
|
186
|
+
id: w.id, workerId: w.id, name: w.name, role: w.role, avatar: w.avatar, color: w.color,
|
|
187
|
+
specialization: spec, level: levelFor(xp), xp,
|
|
188
|
+
tools: [...(w.tools || [])], permissions: perms(w.tools || []),
|
|
189
|
+
memory: publicMemory(entries), room: spec[0], taskId: null, status: w.paused ? 'sleeping' : 'idle',
|
|
190
|
+
brain: { kind: 'local', machineId: this.machineId }, home: this.machineId, builtin: !!w.builtin, retired: false,
|
|
191
|
+
stats: { done: 0, reviews: 0, tests: 0, loops: 0, ...(saved?.stats || {}) }
|
|
192
|
+
};
|
|
193
|
+
this.emit('city.agent.joined', { agent });
|
|
194
|
+
this._save(agent.id);
|
|
195
|
+
return agent;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// ---------------------------------------------------------------- persistence
|
|
199
|
+
_save(agentId) {
|
|
200
|
+
const a = this.state.agents[agentId];
|
|
201
|
+
if (!a || a.home !== this.machineId) return;
|
|
202
|
+
clearTimeout(this.saveTimers.get(agentId));
|
|
203
|
+
const t = setTimeout(() => { this.saveTimers.delete(agentId); this._saveNow(agentId); }, 300);
|
|
204
|
+
t.unref?.();
|
|
205
|
+
this.saveTimers.set(agentId, t);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
_saveNow(agentId) {
|
|
209
|
+
const a = this.state.agents[agentId];
|
|
210
|
+
if (!a || a.home !== this.machineId) return;
|
|
211
|
+
const { taskId, status, room, ...keep } = a;
|
|
212
|
+
this.store.saveAgent({ ...keep, memoryEntries: this.memories.get(agentId) || [] });
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
_snapshotMaybe(force = false) {
|
|
216
|
+
if (!force && this.cityEvents < LIMITS.snapshotEvery) return;
|
|
217
|
+
this.cityEvents = 0;
|
|
218
|
+
this.snapshot = { seq: this.bus.seq, city: clone(this.state) };
|
|
219
|
+
this.store.saveSnapshot(this.snapshot.seq, this.snapshot.city);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// ---------------------------------------------------------------- reactions to events
|
|
223
|
+
_enqueue(e) {
|
|
224
|
+
if (this.closed) return;
|
|
225
|
+
this.queue.push(e);
|
|
226
|
+
if (this.draining) return;
|
|
227
|
+
this.draining = true;
|
|
228
|
+
queueMicrotask(() => this._drain());
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
_drain() {
|
|
232
|
+
while (this.queue.length && !this.closed) {
|
|
233
|
+
const e = this.queue.shift();
|
|
234
|
+
try { this._react(e); } catch { /* a reaction must never break the log */ }
|
|
235
|
+
}
|
|
236
|
+
this.draining = false;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
_react(e) {
|
|
240
|
+
const d = e.data || {};
|
|
241
|
+
if (isCityEvent(e) && e.type.startsWith('city.')) {
|
|
242
|
+
this.cityEvents++;
|
|
243
|
+
const id = d.agent?.id || d.agentId;
|
|
244
|
+
if (id && ['city.agent.joined', 'city.agent.updated', 'city.agent.leveled', 'city.agent.memory', 'city.agent.retired'].includes(e.type)) this._save(id);
|
|
245
|
+
if (['city.task.done', 'city.task.blocked', 'city.task.cancelled'].includes(e.type)) this._childFinished(d.taskId);
|
|
246
|
+
if (e.type === 'city.task.done') this.onTaskDone?.(d.taskId);
|
|
247
|
+
this._snapshotMaybe();
|
|
248
|
+
this._kick();
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
switch (e.type) {
|
|
252
|
+
case 'crew.hired': if (!this._agentByWorker(d.worker?.id)) this._ensureAgent(d.worker); break;
|
|
253
|
+
case 'crew.updated': this._crewUpdated(d.worker); break;
|
|
254
|
+
case 'crew.fired': {
|
|
255
|
+
const a = this._agentByWorker(d.workerId);
|
|
256
|
+
if (a) this.emit('city.agent.retired', { agentId: a.id });
|
|
257
|
+
break;
|
|
258
|
+
}
|
|
259
|
+
case 'hardware.detected':
|
|
260
|
+
this.emit('city.machine.updated', { machine: { id: this.machineId, gpu: d.gpu || null, ramBytes: d.ramBytes, cpus: d.cpus } });
|
|
261
|
+
break;
|
|
262
|
+
case 'brain.status':
|
|
263
|
+
if (d.state === 'ready' && d.model && this.state.machines[this.machineId]?.model !== d.model) this.emit('city.machine.updated', { machine: { id: this.machineId, model: d.model } });
|
|
264
|
+
break;
|
|
265
|
+
case 'brain.attached': {
|
|
266
|
+
if (d.kind === 'remote') break;
|
|
267
|
+
if (Object.values(this.state.machines).some((m) => m.brainId === d.brainId)) break;
|
|
268
|
+
const host = this.state.machines[this.machineId];
|
|
269
|
+
if (host && (!host.brainId || !this.scheduler.brains.has(host.brainId))) this.emit('city.machine.updated', { machine: { id: this.machineId, brainId: d.brainId } });
|
|
270
|
+
break;
|
|
271
|
+
}
|
|
272
|
+
case 'brain.detached': this._brainGone(d.brainId); break;
|
|
273
|
+
case 'job.planned': this._jobPlanned(e); break;
|
|
274
|
+
case 'task.added': this._taskAdded(e); break;
|
|
275
|
+
case 'task.status': this._crewStatus(e); break;
|
|
276
|
+
case 'qa.report': this._qaReport(e); break;
|
|
277
|
+
case 'file.changed': {
|
|
278
|
+
if (!d.taskId) break;
|
|
279
|
+
const map = this.crewFiles.get(d.taskId) || new Map();
|
|
280
|
+
map.set(d.path, d.diff || '');
|
|
281
|
+
this.crewFiles.set(d.taskId, map);
|
|
282
|
+
break;
|
|
283
|
+
}
|
|
284
|
+
case 'job.done':
|
|
285
|
+
case 'job.failed':
|
|
286
|
+
case 'job.cancelled': this._jobEnded(e); break;
|
|
287
|
+
case 'turn.ended': this._borrowTurn(d); break;
|
|
288
|
+
case 'queue.updated': this._loads(d); break;
|
|
289
|
+
case 'worker.status': if (d.status === 'idle') this._kick(); break;
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
_crewUpdated(w) {
|
|
294
|
+
if (!w) return;
|
|
295
|
+
const a = this._agentByWorker(w.id);
|
|
296
|
+
if (!a) return;
|
|
297
|
+
const patch = { id: a.id };
|
|
298
|
+
for (const k of ['name', 'role', 'avatar', 'color']) if (w[k] && w[k] !== a[k]) patch[k] = w[k];
|
|
299
|
+
if (Array.isArray(w.tools) && w.tools.join() !== (a.tools || []).join()) Object.assign(patch, { tools: [...w.tools], permissions: perms(w.tools) });
|
|
300
|
+
if (Object.keys(patch).length > 1) this.emit('city.agent.updated', { agent: patch });
|
|
301
|
+
if (typeof w.paused === 'boolean') {
|
|
302
|
+
const want = w.paused ? 'sleeping' : 'idle';
|
|
303
|
+
if ((w.paused && a.status !== 'sleeping') || (!w.paused && a.status === 'sleeping')) this.emit('city.agent.status', { agentId: a.id, status: want });
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// ---------------------------------------------------------------- hive hooks
|
|
308
|
+
_cityTaskFor(job, task) {
|
|
309
|
+
if (job?.cityTaskId) return this.state.tasks[job.cityTaskId] || null;
|
|
310
|
+
const id = this.linkIndex.get(task?.id) || this.fixFor.get(task?.id)?.[0];
|
|
311
|
+
return id ? this.state.tasks[id] || null : null;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** A task runs with the tools of its room, and a guest's task never gets a shell. */
|
|
315
|
+
_adaptWorker(worker, task, job) {
|
|
316
|
+
const ct = this._cityTaskFor(job, task);
|
|
317
|
+
if (!ct) return worker;
|
|
318
|
+
const room = this.state.rooms[this.fixFor.has(task?.id) ? 'code' : ct.room];
|
|
319
|
+
let tools = room && room.tools?.length ? worker.tools.filter((t) => room.tools.includes(t)) : [...worker.tools];
|
|
320
|
+
if (ct.guest) tools = tools.filter((t) => !GUEST_DENY.has(t));
|
|
321
|
+
const origin = this._originFor(worker, ct);
|
|
322
|
+
if (tools.length === worker.tools.length && !origin) return worker;
|
|
323
|
+
return { ...worker, tools, ...(origin ? { origin } : {}) };
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/** A guest's task, or an agent a guest brought: its writes always wait for the host. */
|
|
327
|
+
_originFor(worker, ct) {
|
|
328
|
+
const a = this._agentByWorker(worker?.id);
|
|
329
|
+
const m = a && a.home !== this.machineId ? this.state.machines[a.home] : null;
|
|
330
|
+
if (m) return { kind: 'guest', id: String(m.owner || '').replace(/^peer:/, ''), label: m.name || 'a guest' };
|
|
331
|
+
if (ct?.guest) return { kind: 'guest', id: ct.createdBy?.id, label: ct.createdBy?.name || 'a guest' };
|
|
332
|
+
return null;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/** What an agent remembers goes into its prompts: pinned entries and facts, preferences, decisions. */
|
|
336
|
+
_promptMemories(workerId) {
|
|
337
|
+
const a = this._agentByWorker(workerId);
|
|
338
|
+
if (!a) return [];
|
|
339
|
+
const list = (this.memories.get(a.id) || []).filter((m) => m.pinned || PROMPT_KINDS.has(m.kind));
|
|
340
|
+
return list.slice(-4).map((m) => `${a.name} remembers: ${m.text}`);
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// ---------------------------------------------------------------- tasks: creation and hops
|
|
344
|
+
_newTaskId() {
|
|
345
|
+
this.taskSeq = (this.taskSeq || 0) + 1;
|
|
346
|
+
while (this.state.tasks[`ct_${this.taskSeq}`]) this.taskSeq++;
|
|
347
|
+
return `ct_${this.taskSeq}`;
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
_createTask(fields) {
|
|
351
|
+
const now = new Date(this.now()).toISOString();
|
|
352
|
+
const task = {
|
|
353
|
+
id: this._newTaskId(), title: fields.title, detail: fields.detail || '', criteria: fields.criteria || [],
|
|
354
|
+
pipeline: fields.pipeline, stage: 0, room: fields.pipeline[0], status: fields.status || 'open',
|
|
355
|
+
agentId: null, loops: 0, maxLoops: MAX_LOOPS, awaiting: null, issues: [], files: fields.files || [], verdicts: [],
|
|
356
|
+
createdBy: fields.createdBy, guest: !!fields.guest, createdAt: now, updatedAt: now
|
|
357
|
+
};
|
|
358
|
+
if (fields.wantAgent) task.wantAgent = fields.wantAgent;
|
|
359
|
+
if (fields.link) task.link = fields.link;
|
|
360
|
+
if (fields.parent) task.parent = fields.parent;
|
|
361
|
+
this.emit('city.task.created', { task });
|
|
362
|
+
return this.state.tasks[task.id];
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
_hop(t, to, patch, by, reason) {
|
|
366
|
+
const hop = { id: `h_${this.bus.seq + 1}`, taskId: t.id, from: t.room || null, to, agentId: patch.agentId ?? null, by, reason: String(reason || '').slice(0, 300), loop: patch.loops ?? t.loops ?? 0, ts: new Date(this.now()).toISOString() };
|
|
367
|
+
this.emit('city.task.hop', { hop, task: { id: t.id, room: to, ...patch } });
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
_claim(t, agent, bid, by = 'agent') {
|
|
371
|
+
const roomId = t.pipeline[t.stage];
|
|
372
|
+
this.emit('city.task.claimed', bid ? { taskId: t.id, agentId: agent.id, room: roomId, bid } : { taskId: t.id, agentId: agent.id, room: roomId });
|
|
373
|
+
if (agent.room !== roomId) this.emit('city.agent.moved', { agentId: agent.id, from: agent.room, to: roomId, taskId: t.id });
|
|
374
|
+
if (by !== 'crew') this._startHop(t.id);
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
_busy(agentId) {
|
|
378
|
+
const a = this.state.agents[agentId];
|
|
379
|
+
if (!a) return true;
|
|
380
|
+
if (a.taskId && !TERMINAL.has(this.state.tasks[a.taskId]?.status)) return true;
|
|
381
|
+
for (const x of this.exec.values()) if (x.agentId === agentId) return true;
|
|
382
|
+
return false;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/** An agent can think when its home machine has a brain (a friend's agent needs its machine's brain). */
|
|
386
|
+
_canThink(a) {
|
|
387
|
+
const m = this.state.machines[a.home];
|
|
388
|
+
if (!m || !m.online) return false;
|
|
389
|
+
if (m.id === this.machineId) return true;
|
|
390
|
+
return !!(m.brainId && this.scheduler.brains.has(m.brainId));
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
_kick() {
|
|
394
|
+
if (this.routeQueued || this.closed) return;
|
|
395
|
+
this.routeQueued = true;
|
|
396
|
+
queueMicrotask(() => {
|
|
397
|
+
this.routeQueued = false;
|
|
398
|
+
if (!this.closed) this._route();
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
_route() {
|
|
403
|
+
const open = Object.values(this.state.tasks).filter((t) => t.status === 'open' && !t.link && !t.awaiting && t.stage < t.pipeline.length)
|
|
404
|
+
.sort((a, b) => taskNum(a.id) - taskNum(b.id));
|
|
405
|
+
for (const t of open) {
|
|
406
|
+
const room = this.state.rooms[t.pipeline[t.stage]];
|
|
407
|
+
if (!room) continue;
|
|
408
|
+
const pick = pickAgent(this.state, t, { busy: (id) => this._busy(id), load: (m) => this.loads.get(m) || 0, canThink: (a) => this._canThink(a) });
|
|
409
|
+
if (pick) this._claim(this.state.tasks[t.id], pick.agent, pick.bid);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
_startHop(taskId) {
|
|
414
|
+
const t = this.state.tasks[taskId];
|
|
415
|
+
if (!t || this.closed) return;
|
|
416
|
+
const roomId = t.pipeline[t.stage];
|
|
417
|
+
const room = this.state.rooms[roomId];
|
|
418
|
+
const agent = this.state.agents[t.agentId];
|
|
419
|
+
if (!room || !agent) return;
|
|
420
|
+
this.emit('city.task.updated', { task: { id: t.id, status: statusForKind(room.kind) } });
|
|
421
|
+
const status = room.kind === 'review' ? 'reviewing' : room.kind === 'test' ? 'testing' : room.kind === 'board' ? 'thinking' : 'working';
|
|
422
|
+
this.emit('city.agent.status', { agentId: agent.id, status });
|
|
423
|
+
const ctrl = new AbortController();
|
|
424
|
+
const x = { ctrl, agentId: agent.id, room: roomId };
|
|
425
|
+
this.exec.set(t.id, x);
|
|
426
|
+
let run;
|
|
427
|
+
if (room.kind === 'board') run = this._plan(t, agent, ctrl, x);
|
|
428
|
+
else if (room.kind === 'review') run = this._review(t, agent, room, ctrl);
|
|
429
|
+
else if (room.kind === 'test') run = this._test(t);
|
|
430
|
+
else if (roomId === 'design' || room.executor === 'design') run = this._design(t, agent, ctrl);
|
|
431
|
+
else run = this._work(t, agent, room, ctrl, x);
|
|
432
|
+
Promise.resolve(run).then((res) => this._afterHop(t.id, roomId, agent.id, res, ctrl), (err) => this._afterHop(t.id, roomId, agent.id, { passed: false, issues: [String(err?.message || err).slice(0, 300)], by: 'agent' }, ctrl));
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
_afterHop(taskId, roomId, agentId, res, ctrl) {
|
|
436
|
+
if (this.exec.get(taskId)?.ctrl === ctrl) this.exec.delete(taskId);
|
|
437
|
+
if (this.closed || ctrl.signal.aborted) return;
|
|
438
|
+
const t = this.state.tasks[taskId];
|
|
439
|
+
if (!t || TERMINAL.has(t.status) || t.pipeline[t.stage] !== roomId) return;
|
|
440
|
+
const room = this.state.rooms[roomId] || { kind: 'work' };
|
|
441
|
+
const agent = this.state.agents[agentId];
|
|
442
|
+
if (res.waitChildren) {
|
|
443
|
+
this.emit('city.task.updated', { task: { id: t.id, status: 'in_progress', agentId: null } });
|
|
444
|
+
this._agentHome(agent);
|
|
445
|
+
return this._childFinished(null, t.id);
|
|
446
|
+
}
|
|
447
|
+
if (room.kind === 'review' || room.kind === 'test') {
|
|
448
|
+
this.emit('city.task.verdict', { taskId, room: roomId, agentId, passed: !!res.passed, issues: res.issues || [], by: res.by || 'agent' });
|
|
449
|
+
this._xp(agentId, room.kind === 'review' ? XP.review : XP.test, room.kind === 'review' ? 'reviews' : 'tests');
|
|
450
|
+
} else if (res.passed && room.kind !== 'board') {
|
|
451
|
+
const patch = { id: taskId, author: agentId };
|
|
452
|
+
if (res.files) patch.files = [...new Set([...(t.files || []), ...res.files])];
|
|
453
|
+
if (res.spec) patch.spec = res.spec;
|
|
454
|
+
if (res.criteria) patch.criteria = res.criteria;
|
|
455
|
+
this.emit('city.task.updated', { task: patch });
|
|
456
|
+
this._xp(agentId, XP.work, null);
|
|
457
|
+
}
|
|
458
|
+
this._agentHome(agent);
|
|
459
|
+
if (room.requireApproval) {
|
|
460
|
+
this.emit('city.task.updated', { task: { id: taskId, agentId: null, issues: res.passed ? [] : (res.issues || []) } });
|
|
461
|
+
this.emit('city.task.awaiting', { taskId, room: roomId });
|
|
462
|
+
return;
|
|
463
|
+
}
|
|
464
|
+
if (res.passed) this._advance(this.state.tasks[taskId], 'agent', `${agent?.name || 'The agent'} finished in ${room.name || roomId}`);
|
|
465
|
+
else this._loop(this.state.tasks[taskId], res.issues || [], 'agent');
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
_agentHome(agent) {
|
|
469
|
+
if (!agent || this.state.agents[agent.id]?.retired) return;
|
|
470
|
+
const a = this.state.agents[agent.id];
|
|
471
|
+
if (a.status !== 'sleeping' && a.status !== 'offline') this.emit('city.agent.status', { agentId: a.id, status: 'idle' });
|
|
472
|
+
const home = a.specialization?.[0];
|
|
473
|
+
if (home && a.room !== home && !this._busy(a.id)) this.emit('city.agent.moved', { agentId: a.id, from: a.room, to: home });
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
_advance(t, by, reason) {
|
|
477
|
+
if (!t || TERMINAL.has(t.status)) return;
|
|
478
|
+
const next = t.stage + 1;
|
|
479
|
+
if (next >= t.pipeline.length) return this._done(t, by);
|
|
480
|
+
this._hop(t, t.pipeline[next], { stage: next, status: 'open', agentId: null, wantAgent: null, awaiting: null }, by, reason);
|
|
481
|
+
this._kick();
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
_done(t, by) {
|
|
485
|
+
if (t.author && t.loops === 0) this._xp(t.author, XP.clean, null);
|
|
486
|
+
if (t.author) {
|
|
487
|
+
this._statInc(t.author, 'done');
|
|
488
|
+
this._remember(t.author, 'task', `Finished "${t.title}"${t.files?.length ? ` (${t.files.slice(0, 4).join(', ')})` : ''}${t.loops ? ` after ${t.loops} loop${t.loops > 1 ? 's' : ''}` : ''}.`);
|
|
489
|
+
}
|
|
490
|
+
this.emit('city.task.done', { taskId: t.id, by });
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
_blocked(t, reason) {
|
|
494
|
+
if (!t || TERMINAL.has(t.status)) return;
|
|
495
|
+
this.emit('city.task.blocked', { taskId: t.id, reason: String(reason).slice(0, 300) });
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
_loop(t, issues, by) {
|
|
499
|
+
if (!t || TERMINAL.has(t.status)) return;
|
|
500
|
+
const loops = (t.loops || 0) + 1;
|
|
501
|
+
if (t.author) this._statInc(t.author, 'loops');
|
|
502
|
+
if (loops > (t.maxLoops ?? MAX_LOOPS)) return this._blocked(t, `still failing after ${t.maxLoops ?? MAX_LOOPS} loops: ${issues[0] || 'no detail'}`);
|
|
503
|
+
let idx = t.stage;
|
|
504
|
+
for (let i = t.stage; i >= 0; i--) {
|
|
505
|
+
const r = this.state.rooms[t.pipeline[i]];
|
|
506
|
+
if (r && (WORK_KINDS.has(r.kind) || r.id === 'design')) { idx = i; break; }
|
|
507
|
+
}
|
|
508
|
+
const author = t.author && this.state.agents[t.author] && !this.state.agents[t.author].retired ? t.author : null;
|
|
509
|
+
this._hop(t, t.pipeline[idx], { stage: idx, status: 'open', agentId: null, wantAgent: author, loops, issues: issues.slice(0, 12), awaiting: null }, by, `changes requested: ${issues[0] || 'see the issues'}`);
|
|
510
|
+
this._kick();
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
_xp(agentId, amount, stat) {
|
|
514
|
+
const a = this.state.agents[agentId];
|
|
515
|
+
if (!a || !amount) return;
|
|
516
|
+
const xp = (a.xp || 0) + amount;
|
|
517
|
+
this.emit('city.agent.leveled', { agentId, level: levelFor(xp), xp });
|
|
518
|
+
if (stat) this._statInc(agentId, stat);
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
_statInc(agentId, stat) {
|
|
522
|
+
const a = this.state.agents[agentId];
|
|
523
|
+
if (!a) return;
|
|
524
|
+
const stats = { done: 0, reviews: 0, tests: 0, loops: 0, ...(a.stats || {}) };
|
|
525
|
+
stats[stat] = (stats[stat] || 0) + 1;
|
|
526
|
+
this.emit('city.agent.updated', { agent: { id: agentId, stats } });
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
// ---------------------------------------------------------------- what happens in each room
|
|
530
|
+
/** Lobby: Mel plans the task into crew tasks (they become this task's children). */
|
|
531
|
+
async _plan(t, agent, ctrl, x) {
|
|
532
|
+
const request = [t.title, t.detail].filter(Boolean).join('\n\n');
|
|
533
|
+
const { jobId, done } = this.hive.createJob({ request, ...(t.guest ? { approval: true } : {}) });
|
|
534
|
+
if (t.guest) this.toolbox.markOrigin?.(jobId, this._originFor(null, t));
|
|
535
|
+
x.jobId = jobId;
|
|
536
|
+
this.jobOwners.set(jobId, { taskId: t.id, mode: 'plan' });
|
|
537
|
+
this.emit('city.task.updated', { task: { id: t.id, jobId } });
|
|
538
|
+
ctrl.signal.addEventListener('abort', () => { try { this.hive.cancelJob(jobId); } catch { /* already over */ } }, { once: true });
|
|
539
|
+
await done;
|
|
540
|
+
const job = this.bus.state.jobs.find((j) => j.id === jobId);
|
|
541
|
+
if (job?.status === 'done') return { passed: true, by: 'agent', waitChildren: true };
|
|
542
|
+
return { passed: false, issues: [job?.error || `the job ended ${job?.status || 'without a result'}`], by: 'agent' };
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/** Design: the agent writes a short spec and criteria for the builder (one model turn). */
|
|
546
|
+
async _design(t, agent, ctrl) {
|
|
547
|
+
const files = this.toolbox.ws.list().map((f) => f.path).slice(0, 60);
|
|
548
|
+
const r = await this.scheduler.turn({ workerId: agent.workerId, taskId: t.id, messages: designMessages(agent, t, files), options: { schema: DESIGN_SCHEMA, maxTokens: 700, temperature: 0.3 }, signal: ctrl.signal });
|
|
549
|
+
const d = readDesign(r.json ?? safeJson(r.text), t);
|
|
550
|
+
return { passed: true, spec: d.spec, criteria: d.criteria, by: 'agent' };
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/** Code, Library, Ops and extension work rooms: a crew job with one task for this agent. */
|
|
554
|
+
async _work(t, agent, room, ctrl, x) {
|
|
555
|
+
const kind = room.id === 'library' ? 'docs' : t.loops ? 'fix' : 'build';
|
|
556
|
+
const detail = [
|
|
557
|
+
t.detail,
|
|
558
|
+
t.spec ? `Spec from Design:\n${t.spec}` : '',
|
|
559
|
+
t.criteria?.length ? `Acceptance criteria:\n- ${t.criteria.join('\n- ')}` : '',
|
|
560
|
+
t.issues?.length ? `Review or Test found these problems. Fix each one:\n- ${t.issues.join('\n- ')}` : ''
|
|
561
|
+
].filter(Boolean).join('\n\n');
|
|
562
|
+
const approval = t.guest || room.requireApproval ? { approval: true } : {};
|
|
563
|
+
const { jobId, done } = this.hive.createJob({ request: t.title, plan: [{ title: t.title, detail, assignee: agent.workerId, kind }], cityTaskId: t.id, ...approval });
|
|
564
|
+
if (t.guest) this.toolbox.markOrigin?.(jobId, this._originFor(null, t));
|
|
565
|
+
x.jobId = jobId;
|
|
566
|
+
this.jobOwners.set(jobId, { taskId: t.id, mode: 'hop' });
|
|
567
|
+
this.emit('city.task.updated', { task: { id: t.id, jobId } });
|
|
568
|
+
ctrl.signal.addEventListener('abort', () => { try { this.hive.cancelJob(jobId); } catch { /* already over */ } }, { once: true });
|
|
569
|
+
await done;
|
|
570
|
+
const job = this.bus.state.jobs.find((j) => j.id === jobId);
|
|
571
|
+
const crewTask = job ? this.bus.state.tasks[job.taskIds?.[0]] : null;
|
|
572
|
+
const files = this._jobFiles(job);
|
|
573
|
+
if (crewTask?.status === 'done') return { passed: true, files, by: 'agent' };
|
|
574
|
+
return { passed: false, issues: [crewTask?.note || job?.error || 'the work did not finish'], files, by: 'agent' };
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
async _review(t, agent, room, ctrl) {
|
|
578
|
+
const checks = checkFiles(this.toolbox.ws, t.files || [], { links: false });
|
|
579
|
+
const mode = room.mode || 'auto';
|
|
580
|
+
if (mode === 'checks' || (mode === 'auto' && t.link)) return { passed: checks.passed, issues: checks.issues, by: 'checks' };
|
|
581
|
+
// A work hop before this review that changed nothing is not done (the user can still approve it).
|
|
582
|
+
const worked = t.pipeline.slice(0, t.stage).some((r) => WORK_KINDS.has(this.state.rooms[r]?.kind) && r !== 'design');
|
|
583
|
+
if (worked && !(t.files || []).length) return { passed: false, issues: ['Nothing changed: no file was written for this task.'], by: 'checks' };
|
|
584
|
+
try {
|
|
585
|
+
const r = await this.scheduler.turn({ workerId: agent.workerId, taskId: t.id, messages: reviewMessages(agent, t, this._diffs(t), checks), options: { schema: REVIEW_SCHEMA, maxTokens: 500, temperature: 0.2 }, signal: ctrl.signal });
|
|
586
|
+
return { ...readReview(r.json ?? safeJson(r.text), checks), by: 'agent' };
|
|
587
|
+
} catch (err) {
|
|
588
|
+
if (ctrl.signal.aborted) throw err;
|
|
589
|
+
return { passed: checks.passed, issues: checks.issues, by: 'checks' };
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
|
|
593
|
+
async _test(t) {
|
|
594
|
+
const checks = checkFiles(this.toolbox.ws, t.files || [], { links: true });
|
|
595
|
+
return { passed: checks.passed, issues: checks.issues, by: 'checks' };
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
_jobFiles(job) {
|
|
599
|
+
const out = new Set();
|
|
600
|
+
for (const id of job?.taskIds || []) for (const p of this.crewFiles.get(id)?.keys() || []) out.add(p);
|
|
601
|
+
return [...out];
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/** The diffs of a task's work, or the files as they are now when the diffs are gone (after a restart). */
|
|
605
|
+
_diffs(t) {
|
|
606
|
+
const out = new Map();
|
|
607
|
+
const jobs = this.bus.state.jobs.filter((j) => j.cityTaskId === t.id || (t.link && j.id === t.link.jobId));
|
|
608
|
+
for (const j of jobs) for (const id of j.taskIds || []) for (const [p, diff] of this.crewFiles.get(id) || []) out.set(p, diff);
|
|
609
|
+
if (!out.size) {
|
|
610
|
+
for (const p of t.files || []) {
|
|
611
|
+
try { out.set(p, `(the file now)\n${this.toolbox.ws.read(p).slice(0, 3000)}`); } catch { /* deleted */ }
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
return [...out].map(([path, diff]) => ({ path, diff }));
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
// ---------------------------------------------------------------- planner tasks (the crew runs the work hop)
|
|
618
|
+
_jobPlanned(e) {
|
|
619
|
+
const owner = this.jobOwners.get(e.jobId);
|
|
620
|
+
if (owner?.mode === 'hop') return;
|
|
621
|
+
const job = this.bus.state.jobs.find((j) => j.id === e.jobId);
|
|
622
|
+
const criteria = acceptanceFrom(job?.brief?.text || '').slice(0, LIMITS.criteria);
|
|
623
|
+
const parent = owner?.mode === 'plan' ? this.state.tasks[owner.taskId] : null;
|
|
624
|
+
const kids = [];
|
|
625
|
+
for (const ct of e.data.tasks || []) {
|
|
626
|
+
const t = this._mirror(ct, e.jobId, criteria, parent);
|
|
627
|
+
if (t) kids.push(t.id);
|
|
628
|
+
}
|
|
629
|
+
if (parent && kids.length) this.emit('city.task.updated', { task: { id: parent.id, children: [...(parent.children || []), ...kids] } });
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
_mirror(ct, jobId, criteria, parent) {
|
|
633
|
+
if (!ct || ct.kind === 'qa' || ct.kind === 'fix' || this.linkIndex.has(ct.id)) return null;
|
|
634
|
+
const work = ct.kind === 'docs' ? 'library' : ct.assignee === 'designer' ? 'design' : 'code';
|
|
635
|
+
const pipeline = work === 'library' ? ['library', 'review', 'test'] : [work, 'review', 'test'];
|
|
636
|
+
const t = this._createTask({
|
|
637
|
+
title: String(ct.title || 'Task').slice(0, LIMITS.title), detail: String(ct.detail || '').slice(0, LIMITS.detail), criteria,
|
|
638
|
+
pipeline, link: { jobId, taskId: ct.id }, createdBy: { kind: 'planner', id: 'mel', name: 'Mel' },
|
|
639
|
+
guest: !!parent?.guest, parent: parent?.id
|
|
640
|
+
});
|
|
641
|
+
this.linkIndex.set(ct.id, t.id);
|
|
642
|
+
return t;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
_taskAdded(e) {
|
|
646
|
+
const ct = e.data.task;
|
|
647
|
+
if (!ct || this.jobOwners.get(e.jobId)?.mode === 'hop') return;
|
|
648
|
+
if (ct.kind === 'fix') {
|
|
649
|
+
// QA found issues: the waiting tasks whose files it names loop back to Code through this fix task.
|
|
650
|
+
const waiting = [...this.waitingQa].map((id) => this.state.tasks[id]).filter((t) => t && t.link?.jobId === e.jobId && t.issues?.length);
|
|
651
|
+
const text = ct.detail || '';
|
|
652
|
+
let hit = waiting.filter((t) => (t.files || []).some((f) => text.includes(f)));
|
|
653
|
+
if (!hit.length) hit = waiting;
|
|
654
|
+
const agent = this._agentByWorker(ct.assignee);
|
|
655
|
+
const ids = [];
|
|
656
|
+
for (const t of hit) {
|
|
657
|
+
this.waitingQa.delete(t.id);
|
|
658
|
+
const loops = (t.loops || 0) + 1;
|
|
659
|
+
if (loops > (t.maxLoops ?? MAX_LOOPS)) { this._blocked(t, `still failing after ${t.maxLoops ?? MAX_LOOPS} loops: ${t.issues[0]}`); continue; }
|
|
660
|
+
if (t.author) this._statInc(t.author, 'loops');
|
|
661
|
+
const idx = Math.max(0, t.pipeline.findIndex((r) => r === 'code' || r === 'design' || r === 'library'));
|
|
662
|
+
this._hop(t, 'code', { stage: idx, status: 'in_progress', agentId: agent?.id || null, loops }, 'agent', `QA asked for a fix: ${t.issues[0]}`);
|
|
663
|
+
if (t.pipeline[idx] !== 'code') this.emit('city.task.updated', { task: { id: t.id, pipeline: ['code', ...t.pipeline.slice(idx + 1)], stage: 0 } });
|
|
664
|
+
if (agent && agent.room !== 'code') this.emit('city.agent.moved', { agentId: agent.id, from: agent.room, to: 'code', taskId: t.id });
|
|
665
|
+
ids.push(t.id);
|
|
666
|
+
}
|
|
667
|
+
if (ids.length) this.fixFor.set(ct.id, ids);
|
|
668
|
+
return;
|
|
669
|
+
}
|
|
670
|
+
if (ct.kind !== 'qa') {
|
|
671
|
+
const job = this.bus.state.jobs.find((j) => j.id === e.jobId);
|
|
672
|
+
const owner = this.jobOwners.get(e.jobId);
|
|
673
|
+
this._mirror(ct, e.jobId, acceptanceFrom(job?.brief?.text || ''), owner?.mode === 'plan' ? this.state.tasks[owner.taskId] : null);
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
_crewStatus(e) {
|
|
678
|
+
const { taskId, status, note } = e.data;
|
|
679
|
+
const owner = this.jobOwners.get(e.jobId);
|
|
680
|
+
if (owner?.mode === 'hop') return;
|
|
681
|
+
const crewTask = this.bus.state.tasks[taskId];
|
|
682
|
+
const agent = crewTask ? this._agentByWorker(crewTask.assignee) : null;
|
|
683
|
+
const fixes = this.fixFor.get(taskId);
|
|
684
|
+
if (fixes) {
|
|
685
|
+
for (const id of fixes) {
|
|
686
|
+
const t = this.state.tasks[id];
|
|
687
|
+
if (!t || TERMINAL.has(t.status)) continue;
|
|
688
|
+
if (status === 'running' && agent && t.agentId !== agent.id) this.emit('city.task.claimed', { taskId: t.id, agentId: agent.id, room: 'code' });
|
|
689
|
+
if (status === 'running') this.emit('city.task.updated', { task: { id: t.id, status: 'in_progress' } });
|
|
690
|
+
if (status === 'done') this._linkedWorkDone(t, agent, taskId);
|
|
691
|
+
if (status === 'failed') this._blocked(t, `the fix failed: ${note || 'no detail'}`);
|
|
692
|
+
}
|
|
693
|
+
if (status === 'done' || status === 'failed') this.fixFor.delete(taskId);
|
|
694
|
+
return;
|
|
695
|
+
}
|
|
696
|
+
const id = this.linkIndex.get(taskId);
|
|
697
|
+
const t = id ? this.state.tasks[id] : null;
|
|
698
|
+
if (!t || !t.link || t.status === 'done' || t.status === 'cancelled') return;
|
|
699
|
+
switch (status) {
|
|
700
|
+
case 'running': {
|
|
701
|
+
if (!agent) break;
|
|
702
|
+
const room = t.pipeline[t.stage];
|
|
703
|
+
if (t.agentId !== agent.id) this._claim(t, agent, null, 'crew');
|
|
704
|
+
this.emit('city.task.updated', { task: { id: t.id, status: 'in_progress', room } });
|
|
705
|
+
break;
|
|
706
|
+
}
|
|
707
|
+
case 'done': if (t.status !== 'in_review' && t.status !== 'in_test') this._linkedWorkDone(t, agent, taskId); break;
|
|
708
|
+
case 'failed': this._blocked(t, note || 'the crew task failed'); break;
|
|
709
|
+
case 'skipped': this.emit('city.task.cancelled', { taskId: t.id, by: note === 'cancelled by the user' ? 'user' : 'system' }); break;
|
|
710
|
+
case 'blocked': this._blocked(t, note || 'a task it depends on failed'); break;
|
|
711
|
+
case 'ready':
|
|
712
|
+
case 'pending':
|
|
713
|
+
// task.retry from the old UI: a blocked city task opens again at its work room.
|
|
714
|
+
if (t.status === 'blocked' && note) {
|
|
715
|
+
this.emit('city.task.updated', { task: { id: t.id, status: 'open', reason: null } });
|
|
716
|
+
this._hop(t, t.pipeline[0], { stage: 0, status: 'open', agentId: null }, 'user', 'the crew task was retried');
|
|
717
|
+
}
|
|
718
|
+
break;
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/** The crew finished the work of a planner task: a reviewer checks the changed files, then it waits in Test. */
|
|
723
|
+
_linkedWorkDone(t, agent, crewTaskId) {
|
|
724
|
+
const files = [...new Set([...(t.files || []), ...(this.crewFiles.get(crewTaskId)?.keys() || [])])];
|
|
725
|
+
if (agent) this._xp(agent.id, XP.work, null);
|
|
726
|
+
this.emit('city.task.updated', { task: { id: t.id, files, ...(agent ? { author: agent.id } : {}) } });
|
|
727
|
+
const reviewIdx = t.pipeline.indexOf('review');
|
|
728
|
+
const testIdx = t.pipeline.indexOf('test');
|
|
729
|
+
const job = this.bus.state.jobs.find((j) => j.id === t.link.jobId);
|
|
730
|
+
if (reviewIdx !== -1) {
|
|
731
|
+
const cur = this.state.tasks[t.id];
|
|
732
|
+
const reviewTask = { ...cur, stage: reviewIdx };
|
|
733
|
+
const pick = pickAgent(this.state, reviewTask, { busy: () => false, load: (m) => this.loads.get(m) || 0, canThink: (a) => this._canThink(a) });
|
|
734
|
+
const reviewer = pick?.agent || null;
|
|
735
|
+
this._hop(cur, 'review', { stage: reviewIdx, status: 'in_review', agentId: reviewer?.id || null }, 'agent', `${agent?.name || 'The crew'} finished the work`);
|
|
736
|
+
const checks = checkFiles(this.toolbox.ws, files, { links: false });
|
|
737
|
+
this.emit('city.task.verdict', { taskId: t.id, room: 'review', agentId: reviewer?.id || null, passed: checks.passed, issues: checks.issues, by: 'checks' });
|
|
738
|
+
if (reviewer) this._xp(reviewer.id, XP.review, 'reviews');
|
|
739
|
+
// A failed review goes to the crew QA as a note, so the QA report covers it.
|
|
740
|
+
if (!checks.passed && job) this.hive.addNote(job.id, 'qa', `Review of "${t.title}" found:\n- ${checks.issues.join('\n- ')}`);
|
|
741
|
+
}
|
|
742
|
+
if (testIdx === -1) return this._done(this.state.tasks[t.id], 'agent');
|
|
743
|
+
const cur = this.state.tasks[t.id];
|
|
744
|
+
this._hop(cur, 'test', { stage: testIdx, status: 'in_test', agentId: null }, 'agent', 'the review is done');
|
|
745
|
+
const qaPending = job && (job.taskIds || []).some((id) => {
|
|
746
|
+
const x = this.bus.state.tasks[id];
|
|
747
|
+
return x && x.kind === 'qa' && !['done', 'skipped', 'failed', 'blocked'].includes(x.status);
|
|
748
|
+
});
|
|
749
|
+
if (qaPending) { this.waitingQa.add(t.id); return; }
|
|
750
|
+
this._linkedChecksTest(t.id);
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
_linkedChecksTest(id) {
|
|
754
|
+
const t = this.state.tasks[id];
|
|
755
|
+
if (!t || TERMINAL.has(t.status)) return;
|
|
756
|
+
const checks = checkFiles(this.toolbox.ws, t.files || [], { links: true });
|
|
757
|
+
const tester = this._agentByWorker('qa');
|
|
758
|
+
this.emit('city.task.verdict', { taskId: t.id, room: 'test', agentId: tester?.id || null, passed: checks.passed, issues: checks.issues, by: 'checks' });
|
|
759
|
+
if (checks.passed) this._done(this.state.tasks[t.id], 'agent');
|
|
760
|
+
else this._blocked(t, `the checks still fail: ${checks.issues[0]}`);
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
_qaReport(e) {
|
|
764
|
+
const qa = this.bus.state.tasks[e.data.taskId];
|
|
765
|
+
const tester = qa ? this._agentByWorker(qa.assignee) : null;
|
|
766
|
+
for (const id of [...this.waitingQa]) {
|
|
767
|
+
const t = this.state.tasks[id];
|
|
768
|
+
if (!t || t.link?.jobId !== e.jobId) continue;
|
|
769
|
+
if (tester) this._xp(tester.id, XP.test, 'tests');
|
|
770
|
+
this.emit('city.task.verdict', { taskId: id, room: 'test', agentId: tester?.id || null, passed: !!e.data.passed, issues: e.data.issues || [], by: 'qa' });
|
|
771
|
+
if (e.data.passed) {
|
|
772
|
+
this.waitingQa.delete(id);
|
|
773
|
+
this._done(this.state.tasks[id], 'agent');
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
_jobEnded(e) {
|
|
779
|
+
const owner = this.jobOwners.get(e.jobId);
|
|
780
|
+
if (owner) this.jobOwners.delete(e.jobId);
|
|
781
|
+
if (owner?.mode === 'hop') return; // the hop's own promise handles it
|
|
782
|
+
for (const id of [...this.waitingQa]) {
|
|
783
|
+
const t = this.state.tasks[id];
|
|
784
|
+
if (!t || t.link?.jobId !== e.jobId) continue;
|
|
785
|
+
this.waitingQa.delete(id);
|
|
786
|
+
const last = [...(t.verdicts || [])].reverse().find((v) => v.room === 'test');
|
|
787
|
+
if (last && !last.passed) this._blocked(t, `QA still reports issues: ${last.issues[0] || 'see the report'}`);
|
|
788
|
+
else this._linkedChecksTest(id);
|
|
789
|
+
}
|
|
790
|
+
for (const t of Object.values(this.state.tasks)) {
|
|
791
|
+
if (t.link?.jobId !== e.jobId || TERMINAL.has(t.status) || this.waitingQa.has(t.id)) continue;
|
|
792
|
+
if (e.type === 'job.cancelled') this.emit('city.task.cancelled', { taskId: t.id, by: 'user' });
|
|
793
|
+
else this._blocked(t, 'the job ended before this task finished');
|
|
794
|
+
}
|
|
795
|
+
}
|
|
796
|
+
|
|
797
|
+
/** A Lobby task is done when every task Mel planned for it is finished. */
|
|
798
|
+
_childFinished(childId, parentId) {
|
|
799
|
+
const pid = parentId || (childId && this.state.tasks[childId]?.parent);
|
|
800
|
+
const p = pid ? this.state.tasks[pid] : null;
|
|
801
|
+
if (!p || TERMINAL.has(p.status) || this.exec.has(p.id)) return;
|
|
802
|
+
if (p.pipeline[p.stage] !== 'lobby' || p.status !== 'in_progress') return;
|
|
803
|
+
const kids = (p.children || []).map((id) => this.state.tasks[id]).filter(Boolean);
|
|
804
|
+
if (kids.some((k) => !TERMINAL.has(k.status))) return;
|
|
805
|
+
const bad = kids.filter((k) => k.status === 'blocked');
|
|
806
|
+
if (bad.length) return this._blocked(p, `${bad.length} of its tasks are blocked`);
|
|
807
|
+
this._advance(p, 'agent', 'every planned task is done');
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
_brainGone(brainId) {
|
|
811
|
+
for (const m of Object.values(this.state.machines)) {
|
|
812
|
+
if (m.brainId !== brainId) continue;
|
|
813
|
+
const next = m.host ? this._localBrainId() : null;
|
|
814
|
+
this.emit('city.machine.updated', { machine: { id: m.id, brainId: next } });
|
|
815
|
+
}
|
|
816
|
+
for (const b of Object.values(this.state.borrows)) if (b.status !== 'ended' && this.borrowRt.get(b.id)?.brainId === brainId) this._endBorrow(b.id, 'brain_gone');
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
_loads(q) {
|
|
820
|
+
const busy = new Set((q.running || []).map((r) => r.brainId));
|
|
821
|
+
for (const m of Object.values(this.state.machines)) {
|
|
822
|
+
if (!m.online) continue;
|
|
823
|
+
let load;
|
|
824
|
+
if (m.host) {
|
|
825
|
+
const own = [...this.scheduler.brains.entries()].filter(([id, slot]) => slot.brain.kind !== 'remote' && !Object.values(this.state.machines).some((x) => !x.host && x.brainId === id));
|
|
826
|
+
load = own.length ? own.filter(([id]) => busy.has(id)).length / own.length : 0;
|
|
827
|
+
} else {
|
|
828
|
+
load = m.brainId && busy.has(m.brainId) ? 1 : 0;
|
|
829
|
+
}
|
|
830
|
+
if (this.loads.get(m.id) === load) continue;
|
|
831
|
+
this.loads.set(m.id, load);
|
|
832
|
+
this.bus.live('city.machine.load', { machineId: m.id, load, queue: (q.waiting || []).length, tps: 0 });
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
|
|
836
|
+
// ---------------------------------------------------------------- machines and friends' agents
|
|
837
|
+
/** A friend's building joins the city. owner: "peer:<guestId>" (or "host" for a machine of the host's own). */
|
|
838
|
+
joinMachine(data, owner) {
|
|
839
|
+
const m = data?.machine || {};
|
|
840
|
+
const id = str(m.id, 30);
|
|
841
|
+
if (!/^m_[0-9a-z_]{1,26}$/.test(id)) fail('bad_request', 'machine.id must look like m_1a2b3c4d');
|
|
842
|
+
if (id === this.machineId) fail('forbidden', 'that is the host machine');
|
|
843
|
+
const old = this.state.machines[id];
|
|
844
|
+
if (old && old.online && old.owner !== owner) fail('forbidden', 'another person is in the city with that machine');
|
|
845
|
+
const brainId = typeof data.brainId === 'string' && this._lentBy(data.brainId, owner) ? data.brainId : null;
|
|
846
|
+
const machine = {
|
|
847
|
+
id, name: str(m.name, LIMITS.name) || 'Friend', host: false, owner, online: true,
|
|
848
|
+
gpu: m.gpu && typeof m.gpu === 'object' ? { name: str(m.gpu.name, 80) || undefined, vramBytes: num(m.gpu.vramBytes), backend: str(m.gpu.backend, 20) || undefined } : null,
|
|
849
|
+
ramBytes: num(m.ramBytes), cpus: num(m.cpus), model: str(m.model, 120) || undefined,
|
|
850
|
+
color: COLOR.test(m.color || '') ? m.color : undefined, brainId,
|
|
851
|
+
via: ['words', 'qr', 'link', 'demo'].includes(data.via) ? data.via : 'words', leftAt: null
|
|
852
|
+
};
|
|
853
|
+
this.emit('city.machine.joined', { machine: { lending: old?.lending || { turns: 0, active: 0 }, agents: old?.agents || [], ...machine } });
|
|
854
|
+
if (brainId) this._restrictBrain(brainId, id);
|
|
855
|
+
const ids = [];
|
|
856
|
+
for (const a of (Array.isArray(data.agents) ? data.agents : []).slice(0, LIMITS.agentsPerMachine)) {
|
|
857
|
+
const agent = this._contribute(id, a);
|
|
858
|
+
if (agent) ids.push(agent.id);
|
|
859
|
+
}
|
|
860
|
+
// Friends' agents that came before and did not come back this time stay offline.
|
|
861
|
+
this._kick();
|
|
862
|
+
return { machineId: id, agents: ids };
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
/**
|
|
866
|
+
* True when brainId is a friend's brain that this owner lent itself (brain.attach with its guest id).
|
|
867
|
+
* The host's own models, cloud brains and other guests' brains never qualify.
|
|
868
|
+
*/
|
|
869
|
+
_lentBy(brainId, owner) {
|
|
870
|
+
const slot = this.scheduler.brains.get(brainId);
|
|
871
|
+
return !!slot && slot.brain.kind === 'remote' && !!owner && owner !== 'host' && slot.brain.owner === owner;
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
/** A friend's brain inside the city serves only that friend's agents and the borrows its owner accepts. */
|
|
875
|
+
_restrictBrain(brainId, machineId) {
|
|
876
|
+
const slot = this.scheduler.brains.get(brainId);
|
|
877
|
+
if (!slot) return;
|
|
878
|
+
const only = new Set();
|
|
879
|
+
for (const a of Object.values(this.state.agents)) if (a.home === machineId && !a.retired) only.add(a.workerId);
|
|
880
|
+
for (const [bid, rt] of this.borrowRt) if (rt.brainId === brainId && this.state.borrows[bid]?.status === 'active') only.add(rt.workerId);
|
|
881
|
+
slot.brain.only = only;
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
_contribute(machineId, a) {
|
|
885
|
+
if (!a || typeof a !== 'object') return null;
|
|
886
|
+
const local = str(a.id, 40).replace(/[^A-Za-z0-9_-]/g, '_');
|
|
887
|
+
const name = str(a.name, LIMITS.name);
|
|
888
|
+
if (!local || !name) return null;
|
|
889
|
+
const id = `${machineId}:${local}`;
|
|
890
|
+
const role = str(a.role, 64) || 'Friend';
|
|
891
|
+
// A guest's agent reads and checks only; the host grants more with city.agent.update.
|
|
892
|
+
const existing = this.state.agents[id];
|
|
893
|
+
const granted = existing?.tools && existing.grantedBy === 'host' ? existing.tools : null;
|
|
894
|
+
const asked = (Array.isArray(a.tools) ? a.tools : GUEST_TOOLS).filter((t) => GUEST_TOOLS.includes(t));
|
|
895
|
+
const tools = granted || (asked.length ? asked : [...GUEST_TOOLS]);
|
|
896
|
+
let worker = existing ? this.bus.state.crew.find((w) => w.id === existing.workerId) : null;
|
|
897
|
+
if (!worker) worker = this.hive.hire({ name, role, prompt: str(a.prompt, 2000) || undefined, tools, color: a.color, avatar: a.avatar });
|
|
898
|
+
else {
|
|
899
|
+
// A worker hired by an older version may still hold write tools: it comes back with the safe set.
|
|
900
|
+
if (!granted && (worker.tools || []).some((t) => !tools.includes(t))) worker = this.hive.updateWorker(worker.id, { tools }) || worker;
|
|
901
|
+
this.scheduler.setPaused(worker.id, false);
|
|
902
|
+
}
|
|
903
|
+
const xp = Math.min(Math.max(0, Number(a.xp) || 0), 1e6);
|
|
904
|
+
const spec = cleanSpec(a.specialization, Object.keys(this.state.rooms)) || [roomForRole(role)];
|
|
905
|
+
const m = this.state.machines[machineId];
|
|
906
|
+
const agent = {
|
|
907
|
+
id, workerId: worker.id, name, role, avatar: worker.avatar, color: worker.color, specialization: spec,
|
|
908
|
+
level: levelFor(xp), xp, tools, permissions: perms(tools), ...(granted ? { grantedBy: 'host' } : {}),
|
|
909
|
+
memory: a.memory && Array.isArray(a.memory.highlights) ? { count: num(a.memory.count) || 0, highlights: a.memory.highlights.slice(0, 4).map((h) => ({ id: str(h.id, 40), kind: str(h.kind, 20), text: str(h.text, LIMITS.memoryText) })) } : { count: 0, highlights: [] },
|
|
910
|
+
room: spec[0], taskId: null, status: 'idle', brain: { kind: 'remote', machineId, label: m?.model || m?.name },
|
|
911
|
+
home: machineId, builtin: false, retired: false, stats: { done: 0, reviews: 0, tests: 0, loops: 0, ...(existing?.stats || {}) }
|
|
912
|
+
};
|
|
913
|
+
this.emit('city.agent.joined', { agent });
|
|
914
|
+
if (m?.brainId) {
|
|
915
|
+
this.scheduler.setPreference(worker.id, m.brainId);
|
|
916
|
+
this._restrictBrain(m.brainId, machineId);
|
|
917
|
+
}
|
|
918
|
+
return this.state.agents[id];
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
leaveMachine(machineId, reason = 'left') {
|
|
922
|
+
const m = this.state.machines[machineId];
|
|
923
|
+
if (!m || m.host) return;
|
|
924
|
+
for (const b of Object.values(this.state.borrows)) if (b.status !== 'ended' && (b.to === machineId || b.from === machineId)) this._endBorrow(b.id, 'left');
|
|
925
|
+
for (const a of Object.values(this.state.agents)) {
|
|
926
|
+
if (a.home !== machineId) continue;
|
|
927
|
+
this.scheduler.setPaused(a.workerId, true);
|
|
928
|
+
this.scheduler.setPreference(a.workerId, null);
|
|
929
|
+
const t = a.taskId ? this.state.tasks[a.taskId] : null;
|
|
930
|
+
if (t && !TERMINAL.has(t.status)) this._reopen(t, 'system', `${a.name} went offline`);
|
|
931
|
+
}
|
|
932
|
+
this.emit('city.machine.left', { machineId, reason: str(reason, 60) || 'left' });
|
|
933
|
+
this._kick();
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
/** Stops the current hop of a task and opens it again in the same room. */
|
|
937
|
+
_reopen(t, by, reason, patch = {}) {
|
|
938
|
+
const x = this.exec.get(t.id);
|
|
939
|
+
if (x) { this.exec.delete(t.id); x.ctrl.abort(); }
|
|
940
|
+
const p = { status: 'open', agentId: null, awaiting: null, ...patch };
|
|
941
|
+
if (t.link) Object.assign(p, { link: null, was: t.link });
|
|
942
|
+
this._hop(t, (p.pipeline || t.pipeline)[p.stage ?? t.stage] || t.room, p, by, reason);
|
|
943
|
+
this._kick();
|
|
944
|
+
}
|
|
945
|
+
|
|
946
|
+
// ---------------------------------------------------------------- GPU borrowing
|
|
947
|
+
requestBorrow(data, who) {
|
|
948
|
+
const agent = this.state.agents[str(data.agentId, 80)];
|
|
949
|
+
if (!agent || agent.retired) fail('not_found', 'no such agent');
|
|
950
|
+
if (!this._ownsAgent(who, agent)) fail('forbidden', 'only the owner of an agent can ask for a GPU for it');
|
|
951
|
+
const to = this.state.machines[str(data.machineId, 30)];
|
|
952
|
+
if (!to || !to.online) fail('not_found', 'that machine is not in the city');
|
|
953
|
+
const brainId = to.host ? (to.brainId && this.scheduler.brains.has(to.brainId) ? to.brainId : this._localBrainId()) : to.brainId;
|
|
954
|
+
if (!brainId || !this.scheduler.brains.has(brainId)) fail('conflict', `${to.name} has no model ready to lend`);
|
|
955
|
+
if (agent.home === to.id) fail('bad_request', 'the agent already lives on that machine');
|
|
956
|
+
if (Object.values(this.state.borrows).some((b) => b.agentId === agent.id && b.status !== 'ended')) fail('conflict', `${agent.name} already has a borrow`);
|
|
957
|
+
const borrow = {
|
|
958
|
+
id: `bw_${Object.keys(this.state.borrows).length + 1}`, agentId: agent.id, from: agent.home, to: to.id, status: 'pending',
|
|
959
|
+
limit: { turns: clampInt(data.turns, 1, LIMITS.borrowTurns, 6), minutes: clampInt(data.minutes, 1, LIMITS.borrowMinutes, 10) },
|
|
960
|
+
used: { turns: 0, completionTokens: 0, ms: 0 }, requestedBy: who.owner, createdAt: new Date(this.now()).toISOString()
|
|
961
|
+
};
|
|
962
|
+
this.emit('city.borrow.requested', { borrow });
|
|
963
|
+
const timer = setTimeout(() => { if (this.state.borrows[borrow.id]?.status === 'pending') this._endBorrow(borrow.id, 'expired'); }, LIMITS.borrowPendingMs);
|
|
964
|
+
timer.unref?.();
|
|
965
|
+
this.borrowRt.set(borrow.id, { timer, brainId, workerId: agent.workerId });
|
|
966
|
+
return this.state.borrows[borrow.id];
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
answerBorrow(data, who) {
|
|
970
|
+
const b = this.state.borrows[str(data.borrowId, 40)];
|
|
971
|
+
if (!b) fail('not_found', 'no such borrow');
|
|
972
|
+
if (b.status !== 'pending') fail('conflict', `the borrow is ${b.status}`);
|
|
973
|
+
const lender = this.state.machines[b.to];
|
|
974
|
+
if (!lender || lender.owner !== who.owner) fail('forbidden', 'only the lender can answer');
|
|
975
|
+
if (!data.accept) {
|
|
976
|
+
this.emit('city.borrow.answered', { borrowId: b.id, accepted: false, by: who.owner });
|
|
977
|
+
this._endBorrow(b.id, 'refused');
|
|
978
|
+
return this.state.borrows[b.id];
|
|
979
|
+
}
|
|
980
|
+
const rt = this.borrowRt.get(b.id);
|
|
981
|
+
const slot = rt && this.scheduler.brains.get(rt.brainId);
|
|
982
|
+
if (!slot) { this._endBorrow(b.id, 'brain_gone'); fail('conflict', 'the lent model is gone'); }
|
|
983
|
+
const limit = { turns: Math.min(b.limit.turns, clampInt(data.turns, 1, LIMITS.borrowTurns, b.limit.turns)), minutes: Math.min(b.limit.minutes, clampInt(data.minutes, 1, LIMITS.borrowMinutes, b.limit.minutes)) };
|
|
984
|
+
clearTimeout(rt.timer);
|
|
985
|
+
rt.prevPref = this.scheduler.prefs.get(rt.workerId) || null;
|
|
986
|
+
if (slot.brain.only && !slot.brain.only.has(rt.workerId)) { slot.brain.only.add(rt.workerId); rt.addedOnly = true; }
|
|
987
|
+
this.emit('city.borrow.answered', { borrowId: b.id, accepted: true, limit, by: who.owner });
|
|
988
|
+
this.scheduler.setPreference(rt.workerId, rt.brainId);
|
|
989
|
+
rt.timer = setTimeout(() => this._endBorrow(b.id, 'time'), limit.minutes * 60_000);
|
|
990
|
+
rt.timer.unref?.();
|
|
991
|
+
return this.state.borrows[b.id];
|
|
992
|
+
}
|
|
993
|
+
|
|
994
|
+
stopBorrow(data, who) {
|
|
995
|
+
const b = this.state.borrows[str(data.borrowId, 40)];
|
|
996
|
+
if (!b) fail('not_found', 'no such borrow');
|
|
997
|
+
const lender = this.state.machines[b.to];
|
|
998
|
+
const borrower = this.state.machines[b.from];
|
|
999
|
+
if (who.owner !== lender?.owner && who.owner !== borrower?.owner && who.owner !== 'host') fail('forbidden', 'only the lender or the borrower can stop it');
|
|
1000
|
+
if (b.status !== 'ended') this._endBorrow(b.id, 'stopped');
|
|
1001
|
+
return this.state.borrows[b.id];
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
_endBorrow(id, reason) {
|
|
1005
|
+
const b = this.state.borrows[id];
|
|
1006
|
+
if (!b || b.status === 'ended') return;
|
|
1007
|
+
const rt = this.borrowRt.get(id);
|
|
1008
|
+
if (rt) {
|
|
1009
|
+
clearTimeout(rt.timer);
|
|
1010
|
+
this.borrowRt.delete(id);
|
|
1011
|
+
if (b.status === 'active') {
|
|
1012
|
+
const slot = this.scheduler.brains.get(rt.brainId);
|
|
1013
|
+
if (rt.addedOnly && slot?.brain.only) slot.brain.only.delete(rt.workerId);
|
|
1014
|
+
this.scheduler.setPreference(rt.workerId, rt.prevPref && this.scheduler.brains.has(rt.prevPref) ? rt.prevPref : null);
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
this.emit('city.borrow.ended', { borrowId: id, reason, used: b.used });
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
_borrowTurn(d) {
|
|
1021
|
+
if (d.error) return;
|
|
1022
|
+
for (const [id, rt] of this.borrowRt) {
|
|
1023
|
+
const b = this.state.borrows[id];
|
|
1024
|
+
if (!b || b.status !== 'active' || rt.workerId !== d.workerId || rt.brainId !== d.brainId) continue;
|
|
1025
|
+
this.emit('city.borrow.turn', { borrowId: id, turnId: d.turnId, completionTokens: d.completionTokens || 0, ms: d.ms || 0 });
|
|
1026
|
+
if (this.state.borrows[id].used.turns >= b.limit.turns) this._endBorrow(id, 'limit');
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
// ---------------------------------------------------------------- memory
|
|
1031
|
+
_remember(agentId, kind, text, pinned = false) {
|
|
1032
|
+
const a = this.state.agents[agentId];
|
|
1033
|
+
if (!a || a.home !== this.machineId) return null;
|
|
1034
|
+
const list = this.memories.get(agentId) || [];
|
|
1035
|
+
const entry = { id: `am_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`, kind: MEMORY_KINDS.has(kind) ? kind : 'fact', text: String(text).trim().slice(0, LIMITS.memoryText), pinned: !!pinned, ts: new Date(this.now()).toISOString() };
|
|
1036
|
+
list.push(entry);
|
|
1037
|
+
while (list.length > LIMITS.memoryEntries) {
|
|
1038
|
+
const i = list.findIndex((e) => !e.pinned);
|
|
1039
|
+
if (i === -1) break;
|
|
1040
|
+
list.splice(i, 1);
|
|
1041
|
+
}
|
|
1042
|
+
this.memories.set(agentId, list);
|
|
1043
|
+
this.emit('city.agent.memory', { agentId, ...publicMemory(list) });
|
|
1044
|
+
return entry;
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
// ---------------------------------------------------------------- who is asking
|
|
1048
|
+
_who(d) {
|
|
1049
|
+
const g = guestOf(d);
|
|
1050
|
+
if (g) return { guest: true, id: g.id, name: str(g.name, LIMITS.name) || 'Guest', role: g.role, owner: g.owner };
|
|
1051
|
+
return { guest: false, id: 'h', name: 'You', role: 'host', owner: 'host' };
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
_ownsAgent(who, a) {
|
|
1055
|
+
const m = this.state.machines[a.home];
|
|
1056
|
+
return m ? m.owner === who.owner : !who.guest;
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
_ownsTask(who, t) {
|
|
1060
|
+
return !who.guest || (t.createdBy?.kind === 'guest' && t.createdBy.id === who.id);
|
|
1061
|
+
}
|
|
1062
|
+
|
|
1063
|
+
_hostOnly(who) {
|
|
1064
|
+
if (who.guest) fail('forbidden', 'only the host can do this');
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
_rate(who) {
|
|
1068
|
+
if (!who.guest) return;
|
|
1069
|
+
const now = this.now();
|
|
1070
|
+
const list = (this.guestRate.get(who.id) || []).filter((t) => now - t < LIMITS.guestWindowMs);
|
|
1071
|
+
if (list.length >= LIMITS.guestCommands) fail('rate_limited', 'too many city commands, wait a few seconds');
|
|
1072
|
+
list.push(now);
|
|
1073
|
+
this.guestRate.set(who.id, list);
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
_task(d, who) {
|
|
1077
|
+
const t = this.state.tasks[str(d.taskId, 40)];
|
|
1078
|
+
if (!t) fail('not_found', 'no such task');
|
|
1079
|
+
if (!this._ownsTask(who, t)) fail('forbidden', 'a guest can change only the tasks it created');
|
|
1080
|
+
return t;
|
|
1081
|
+
}
|
|
1082
|
+
|
|
1083
|
+
_agent(d) {
|
|
1084
|
+
const a = this.state.agents[str(d.agentId, 80)];
|
|
1085
|
+
if (!a) fail('not_found', 'no such agent');
|
|
1086
|
+
return a;
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
// ---------------------------------------------------------------- commands
|
|
1090
|
+
createTask(d, who) {
|
|
1091
|
+
const title = str(d.title, LIMITS.title);
|
|
1092
|
+
if (!title) fail('bad_request', 'title is required');
|
|
1093
|
+
const want = d.agentId ? this.state.agents[str(d.agentId, 80)] : null;
|
|
1094
|
+
if (d.agentId && (!want || want.retired)) fail('not_found', 'no such agent');
|
|
1095
|
+
let room = str(d.room, 40) || (want ? want.specialization?.[0] : 'lobby');
|
|
1096
|
+
if (!this.state.rooms[room]) fail('bad_request', `no room ${room}`);
|
|
1097
|
+
if (who.guest && this.state.rooms[room].hostOnly) fail('forbidden', `guests cannot send tasks to ${this.state.rooms[room].name}`);
|
|
1098
|
+
let pipeline = Array.isArray(d.pipeline) && d.pipeline.length ? d.pipeline.map((r) => str(r, 40)).slice(0, LIMITS.pipeline) : null;
|
|
1099
|
+
if (pipeline) {
|
|
1100
|
+
for (const r of pipeline) if (!this.state.rooms[r]) fail('bad_request', `no room ${r}`);
|
|
1101
|
+
if (who.guest && pipeline.some((r) => this.state.rooms[r].hostOnly)) fail('forbidden', 'guests cannot send tasks to the Ops room');
|
|
1102
|
+
room = pipeline[0];
|
|
1103
|
+
} else {
|
|
1104
|
+
const kind = this.state.rooms[room].kind;
|
|
1105
|
+
if (room === 'lobby' && want) room = want.specialization?.[0] || 'code';
|
|
1106
|
+
if (kind === 'board' && room === 'lobby') pipeline = ['lobby'];
|
|
1107
|
+
else if (room === 'design') pipeline = ['design', 'code', 'review', 'test'];
|
|
1108
|
+
else if (kind === 'review') pipeline = ['review', 'test'];
|
|
1109
|
+
else if (kind === 'test') pipeline = ['test'];
|
|
1110
|
+
else pipeline = [room, 'review', 'test'];
|
|
1111
|
+
}
|
|
1112
|
+
const criteria = (Array.isArray(d.criteria) ? d.criteria : []).map((c) => str(c, LIMITS.criterion)).filter(Boolean).slice(0, LIMITS.criteria);
|
|
1113
|
+
const reviewOnly = this.state.rooms[pipeline[0]].kind === 'review' || this.state.rooms[pipeline[0]].kind === 'test';
|
|
1114
|
+
const t = this._createTask({
|
|
1115
|
+
title, detail: str(d.detail, LIMITS.detail), criteria, pipeline,
|
|
1116
|
+
files: reviewOnly ? this.toolbox.ws.list().map((f) => f.path).slice(0, 60) : [],
|
|
1117
|
+
wantAgent: want?.id, createdBy: who.guest ? { kind: 'guest', id: who.id, name: who.name } : { kind: 'user', id: 'user' }, guest: who.guest
|
|
1118
|
+
});
|
|
1119
|
+
this._kick();
|
|
1120
|
+
return clone(t);
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
assignTask(d, who) {
|
|
1124
|
+
const t = this._task(d, who);
|
|
1125
|
+
const a = this._agent(d);
|
|
1126
|
+
if (a.retired) fail('conflict', `${a.name} is retired`);
|
|
1127
|
+
if (TERMINAL.has(t.status)) fail('conflict', `the task is ${t.status}`);
|
|
1128
|
+
if (t.link) {
|
|
1129
|
+
const crew = this.bus.state.tasks[t.link.taskId];
|
|
1130
|
+
if (crew && crew.status !== 'done') {
|
|
1131
|
+
this.hive.reassignTask(t.link.taskId, a.workerId);
|
|
1132
|
+
return this.state.tasks[t.id];
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
if (this.exec.has(t.id) || ['claimed', 'in_progress', 'in_review', 'in_test'].includes(t.status)) this._reopen(t, who.guest ? 'guest' : 'user', `handed to ${a.name}`, { wantAgent: a.id });
|
|
1136
|
+
else this.emit('city.task.updated', { task: { id: t.id, wantAgent: a.id } });
|
|
1137
|
+
this._kick();
|
|
1138
|
+
return this.state.tasks[t.id];
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
moveTask(d, who) {
|
|
1142
|
+
const t = this._task(d, who);
|
|
1143
|
+
const room = this.state.rooms[str(d.room, 40)];
|
|
1144
|
+
if (!room) fail('bad_request', 'no such room');
|
|
1145
|
+
if (who.guest && room.hostOnly) fail('forbidden', `guests cannot send tasks to ${room.name}`);
|
|
1146
|
+
if (t.status === 'done' || t.status === 'cancelled') fail('conflict', `the task is ${t.status}`);
|
|
1147
|
+
if (t.link && ['running', 'review'].includes(this.bus.state.tasks[t.link.taskId]?.status)) fail('conflict', 'the crew is working on it; hand it to another agent instead');
|
|
1148
|
+
let pipeline = t.pipeline;
|
|
1149
|
+
let stage = pipeline.indexOf(room.id);
|
|
1150
|
+
if (stage === -1) {
|
|
1151
|
+
const rest = pipeline.slice(t.stage).filter((r) => ['review', 'test'].includes(this.state.rooms[r]?.kind));
|
|
1152
|
+
pipeline = [...pipeline.slice(0, t.stage), room.id, ...rest];
|
|
1153
|
+
stage = t.stage;
|
|
1154
|
+
}
|
|
1155
|
+
this._reopen(t, who.guest ? 'guest' : 'user', `moved to ${room.name}`, { stage, pipeline, wantAgent: null, status: 'open' });
|
|
1156
|
+
if (t.status === 'blocked') this.emit('city.task.updated', { task: { id: t.id, reason: null } });
|
|
1157
|
+
return this.state.tasks[t.id];
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
approveTask(d, who) {
|
|
1161
|
+
const t = this._task(d, who);
|
|
1162
|
+
if (TERMINAL.has(t.status)) fail('conflict', `the task is ${t.status}`);
|
|
1163
|
+
const roomId = t.pipeline[t.stage];
|
|
1164
|
+
const room = this.state.rooms[roomId];
|
|
1165
|
+
if (t.link && t.stage === 0) {
|
|
1166
|
+
// The crew still runs the work hop: only the hops after it can be approved.
|
|
1167
|
+
const crew = this.bus.state.tasks[t.link.taskId];
|
|
1168
|
+
if (crew && !['done', 'failed', 'skipped', 'blocked'].includes(crew.status)) fail('conflict', 'the crew is still working on it');
|
|
1169
|
+
}
|
|
1170
|
+
const x = this.exec.get(t.id);
|
|
1171
|
+
if (x) { this.exec.delete(t.id); x.ctrl.abort(); }
|
|
1172
|
+
this.waitingQa.delete(t.id);
|
|
1173
|
+
if (room && (room.kind === 'review' || room.kind === 'test') && !t.awaiting) {
|
|
1174
|
+
this.emit('city.task.verdict', { taskId: t.id, room: roomId, agentId: null, passed: true, issues: [], by: 'user' });
|
|
1175
|
+
}
|
|
1176
|
+
if (t.awaiting) this.emit('city.task.awaiting', { taskId: t.id, room: null });
|
|
1177
|
+
if (t.link) this.emit('city.task.updated', { task: { id: t.id, link: null, was: t.link } });
|
|
1178
|
+
if (str(d.note, 300)) this.emit('city.task.updated', { task: { id: t.id, note: str(d.note, 300) } });
|
|
1179
|
+
this._advance(this.state.tasks[t.id], who.guest ? 'guest' : 'user', `approved by ${who.name}`);
|
|
1180
|
+
return this.state.tasks[t.id];
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
rejectTask(d, who) {
|
|
1184
|
+
const t = this._task(d, who);
|
|
1185
|
+
if (TERMINAL.has(t.status)) fail('conflict', `the task is ${t.status}`);
|
|
1186
|
+
const note = str(d.note, 300) || 'changes requested';
|
|
1187
|
+
const x = this.exec.get(t.id);
|
|
1188
|
+
if (x) { this.exec.delete(t.id); x.ctrl.abort(); }
|
|
1189
|
+
this.waitingQa.delete(t.id);
|
|
1190
|
+
const roomId = t.pipeline[t.stage];
|
|
1191
|
+
this.emit('city.task.verdict', { taskId: t.id, room: roomId, agentId: null, passed: false, issues: [note], by: 'user' });
|
|
1192
|
+
if (t.awaiting) this.emit('city.task.awaiting', { taskId: t.id, room: null });
|
|
1193
|
+
if (t.link) this.emit('city.task.updated', { task: { id: t.id, link: null, was: t.link } });
|
|
1194
|
+
this._loop(this.state.tasks[t.id], [note], who.guest ? 'guest' : 'user');
|
|
1195
|
+
return this.state.tasks[t.id];
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
retryTask(d, who) {
|
|
1199
|
+
const t = this._task(d, who);
|
|
1200
|
+
if (t.status !== 'blocked' && t.status !== 'cancelled') fail('conflict', 'only a blocked or cancelled task can be retried');
|
|
1201
|
+
this._reopen(t, who.guest ? 'guest' : 'user', 'retried', { loops: 0, reason: null });
|
|
1202
|
+
return this.state.tasks[t.id];
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
cancelTask(d, who) {
|
|
1206
|
+
const t = this._task(d, who);
|
|
1207
|
+
if (TERMINAL.has(t.status)) fail('conflict', `the task is ${t.status}`);
|
|
1208
|
+
const x = this.exec.get(t.id);
|
|
1209
|
+
if (x) { this.exec.delete(t.id); x.ctrl.abort(); }
|
|
1210
|
+
this.waitingQa.delete(t.id);
|
|
1211
|
+
if (t.link) {
|
|
1212
|
+
const crew = this.bus.state.tasks[t.link.taskId];
|
|
1213
|
+
if (crew && !['done', 'skipped'].includes(crew.status)) { try { this.hive.cancelTask(t.link.taskId); } catch { /* already over */ } }
|
|
1214
|
+
}
|
|
1215
|
+
if (!TERMINAL.has(this.state.tasks[t.id].status)) this.emit('city.task.cancelled', { taskId: t.id, by: who.guest ? 'guest' : 'user' });
|
|
1216
|
+
return this.state.tasks[t.id];
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
hireAgent(d, who) {
|
|
1220
|
+
this._hostOnly(who);
|
|
1221
|
+
const spec = cleanSpec(d.specialization, Object.keys(this.state.rooms));
|
|
1222
|
+
const worker = this.hive.hire({ name: d.name, role: d.role, prompt: d.prompt, tools: d.tools, color: d.color, avatar: d.avatar });
|
|
1223
|
+
return this._ensureAgent(worker, { specialization: spec });
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
updateAgent(d, who) {
|
|
1227
|
+
const a = this._agent(d);
|
|
1228
|
+
const owns = this._ownsAgent(who, a);
|
|
1229
|
+
// The host may grant tools to a guest's agent; nothing else of it changes then.
|
|
1230
|
+
if (!owns && (who.guest || !Array.isArray(d.tools))) fail('forbidden', 'only the owner of an agent can change it');
|
|
1231
|
+
const patch = { id: a.id };
|
|
1232
|
+
const crewPatch = {};
|
|
1233
|
+
if (owns) {
|
|
1234
|
+
for (const k of ['name', 'role', 'avatar']) if (str(d[k], k === 'role' ? 64 : LIMITS.name)) { patch[k] = str(d[k], k === 'role' ? 64 : LIMITS.name); crewPatch[k] = patch[k]; }
|
|
1235
|
+
if (COLOR.test(d.color || '')) { patch.color = d.color; crewPatch.color = d.color; }
|
|
1236
|
+
const spec = cleanSpec(d.specialization, Object.keys(this.state.rooms));
|
|
1237
|
+
if (spec) patch.specialization = spec;
|
|
1238
|
+
}
|
|
1239
|
+
if (Array.isArray(d.tools)) {
|
|
1240
|
+
// Tools are what an agent may do on the host's disk: only the host grants them.
|
|
1241
|
+
if (who.guest) fail('forbidden', 'only the host can change the tools of an agent');
|
|
1242
|
+
let tools = d.tools.filter((t) => ALL_TOOLS.includes(t));
|
|
1243
|
+
if (a.home !== this.machineId) tools = tools.filter((t) => !GUEST_DENY.has(t));
|
|
1244
|
+
if (tools.length) { patch.tools = tools; patch.permissions = perms(tools); crewPatch.tools = tools; if (a.home !== this.machineId) patch.grantedBy = 'host'; }
|
|
1245
|
+
}
|
|
1246
|
+
const w = this.bus.state.crew.find((x) => x.id === a.workerId);
|
|
1247
|
+
if (w && Object.keys(crewPatch).length) {
|
|
1248
|
+
if (w.builtin) delete crewPatch.tools;
|
|
1249
|
+
if (Object.keys(crewPatch).length) this.hive.updateWorker(w.id, crewPatch);
|
|
1250
|
+
if (w.builtin && patch.tools) fail('bad_request', 'the tools of the default crew cannot be changed; hire an agent instead');
|
|
1251
|
+
}
|
|
1252
|
+
if (Object.keys(patch).length > 1) this.emit('city.agent.updated', { agent: patch });
|
|
1253
|
+
return this.state.agents[a.id];
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
moveAgent(d, who) {
|
|
1257
|
+
const a = this._agent(d);
|
|
1258
|
+
if (who.guest && !this._ownsAgent(who, a)) fail('forbidden', 'only the owner of an agent can move it');
|
|
1259
|
+
const room = this.state.rooms[str(d.room, 40)];
|
|
1260
|
+
if (!room) fail('bad_request', 'no such room');
|
|
1261
|
+
if (this._busy(a.id)) fail('conflict', `${a.name} is busy with a task`);
|
|
1262
|
+
if (a.room !== room.id) this.emit('city.agent.moved', { agentId: a.id, from: a.room, to: room.id });
|
|
1263
|
+
return this.state.agents[a.id];
|
|
1264
|
+
}
|
|
1265
|
+
|
|
1266
|
+
retireAgent(d, who) {
|
|
1267
|
+
const a = this._agent(d);
|
|
1268
|
+
if (!this._ownsAgent(who, a)) fail('forbidden', 'only the owner of an agent can retire it');
|
|
1269
|
+
if (this._busy(a.id)) fail('conflict', `${a.name} is busy with a task`);
|
|
1270
|
+
if (a.builtin) { this.emit('city.agent.status', { agentId: a.id, status: 'sleeping' }); return {}; }
|
|
1271
|
+
this.hive.fire(a.workerId);
|
|
1272
|
+
if (!this.state.agents[a.id].retired) this.emit('city.agent.retired', { agentId: a.id });
|
|
1273
|
+
return {};
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
wakeAgent(d, who) {
|
|
1277
|
+
const a = this._agent(d);
|
|
1278
|
+
if (!this._ownsAgent(who, a)) fail('forbidden', 'only the owner of an agent can wake it');
|
|
1279
|
+
if (a.retired) fail('conflict', `${a.name} is retired`);
|
|
1280
|
+
if (a.status === 'sleeping') this.emit('city.agent.status', { agentId: a.id, status: 'idle' });
|
|
1281
|
+
this._kick();
|
|
1282
|
+
return this.state.agents[a.id];
|
|
1283
|
+
}
|
|
1284
|
+
|
|
1285
|
+
_memoryAgent(d, who) {
|
|
1286
|
+
const a = this._agent(d);
|
|
1287
|
+
if (!this._ownsAgent(who, a)) fail('forbidden', 'only the owner of an agent can read or change its memory');
|
|
1288
|
+
if (a.home !== this.machineId) fail('forbidden', "a friend's agent keeps its memory on its own machine");
|
|
1289
|
+
return a;
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1292
|
+
memoryCommand(op, d, who) {
|
|
1293
|
+
const a = this._memoryAgent(d, who);
|
|
1294
|
+
const list = this.memories.get(a.id) || [];
|
|
1295
|
+
if (op === 'list') return { entries: list.map((e) => ({ ...e })) };
|
|
1296
|
+
if (op === 'add') {
|
|
1297
|
+
const text = str(d.text, LIMITS.memoryText);
|
|
1298
|
+
if (!text) fail('bad_request', 'text is required');
|
|
1299
|
+
return { entry: this._remember(a.id, d.kind, text, !!d.pinned) };
|
|
1300
|
+
}
|
|
1301
|
+
const e = list.find((x) => x.id === str(d.id, 40));
|
|
1302
|
+
if (!e) fail('not_found', 'no such memory');
|
|
1303
|
+
if (op === 'delete') list.splice(list.indexOf(e), 1);
|
|
1304
|
+
else {
|
|
1305
|
+
if (str(d.text, LIMITS.memoryText)) e.text = str(d.text, LIMITS.memoryText);
|
|
1306
|
+
if (MEMORY_KINDS.has(d.kind)) e.kind = d.kind;
|
|
1307
|
+
if (typeof d.pinned === 'boolean') e.pinned = d.pinned;
|
|
1308
|
+
e.updatedAt = new Date(this.now()).toISOString();
|
|
1309
|
+
}
|
|
1310
|
+
this.memories.set(a.id, list);
|
|
1311
|
+
this.emit('city.agent.memory', { agentId: a.id, ...publicMemory(list) });
|
|
1312
|
+
return op === 'delete' ? {} : { entry: { ...e } };
|
|
1313
|
+
}
|
|
1314
|
+
|
|
1315
|
+
/** This machine's card and its own agents, for a guest's browser to send in city.machine.join. */
|
|
1316
|
+
localAgents() {
|
|
1317
|
+
const m = this.state.machines[this.machineId] || {};
|
|
1318
|
+
const agents = Object.values(this.state.agents).filter((a) => a.home === this.machineId && !a.retired && a.workerId !== 'mel')
|
|
1319
|
+
.map(({ taskId, status, room, ...a }) => a);
|
|
1320
|
+
return { machine: { id: this.machineId, name: m.name || 'My PC', gpu: m.gpu || null, ramBytes: m.ramBytes, cpus: m.cpus, model: m.model, color: m.color }, agents };
|
|
1321
|
+
}
|
|
1322
|
+
|
|
1323
|
+
/** A guest's browser writes back the levels its agents earned in a friend's city. */
|
|
1324
|
+
saveLocalAgents(d, who) {
|
|
1325
|
+
this._hostOnly(who);
|
|
1326
|
+
const out = [];
|
|
1327
|
+
for (const x of (Array.isArray(d.agents) ? d.agents : []).slice(0, 16)) {
|
|
1328
|
+
const a = this.state.agents[str(x?.id, 80)];
|
|
1329
|
+
if (!a || a.home !== this.machineId) continue;
|
|
1330
|
+
const xp = Math.min(Number(x.xp) || 0, 1e6);
|
|
1331
|
+
if (xp > (a.xp || 0)) { this.emit('city.agent.leveled', { agentId: a.id, level: levelFor(xp), xp }); out.push(a.id); }
|
|
1332
|
+
}
|
|
1333
|
+
return { saved: out };
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
addRoom(d, who) {
|
|
1337
|
+
this._hostOnly(who);
|
|
1338
|
+
const id = str(d.id, 24).toLowerCase();
|
|
1339
|
+
if (!/^[a-z][a-z0-9-]{1,23}$/.test(id)) fail('bad_request', 'room id: 2 to 24 lowercase letters, digits or dashes');
|
|
1340
|
+
if (this.state.rooms[id]) fail('conflict', 'that room exists');
|
|
1341
|
+
const kind = ['work', 'review', 'test', 'library', 'ops'].includes(d.kind) ? d.kind : 'work';
|
|
1342
|
+
const room = {
|
|
1343
|
+
id, name: str(d.name, LIMITS.name) || id, kind, tools: (Array.isArray(d.tools) ? d.tools : ['list_files', 'read_file']).filter((t) => ALL_TOOLS.includes(t)),
|
|
1344
|
+
accepts: (Array.isArray(d.accepts) ? d.accepts : [kind === 'work' ? 'code' : kind]).map((x) => str(x, 20)).filter(Boolean).slice(0, 8),
|
|
1345
|
+
requireApproval: !!d.requireApproval, hostOnly: !!d.hostOnly, builtin: false, ext: str(d.ext, 60) || undefined,
|
|
1346
|
+
order: Object.keys(this.state.rooms).length, color: COLOR.test(d.color || '') ? d.color : undefined
|
|
1347
|
+
};
|
|
1348
|
+
if (kind === 'review') room.mode = ['auto', 'model', 'checks'].includes(d.mode) ? d.mode : 'auto';
|
|
1349
|
+
this.emit('city.room.added', { room });
|
|
1350
|
+
return this.state.rooms[id];
|
|
1351
|
+
}
|
|
1352
|
+
|
|
1353
|
+
updateRoom(d, who) {
|
|
1354
|
+
this._hostOnly(who);
|
|
1355
|
+
const r = this.state.rooms[str(d.roomId, 24)];
|
|
1356
|
+
if (!r) fail('not_found', 'no such room');
|
|
1357
|
+
const patch = { id: r.id };
|
|
1358
|
+
if (str(d.name, LIMITS.name)) patch.name = str(d.name, LIMITS.name);
|
|
1359
|
+
if (Array.isArray(d.tools)) patch.tools = d.tools.filter((t) => ALL_TOOLS.includes(t));
|
|
1360
|
+
if (typeof d.requireApproval === 'boolean') patch.requireApproval = d.requireApproval;
|
|
1361
|
+
if (r.kind === 'review' && ['auto', 'model', 'checks'].includes(d.mode)) patch.mode = d.mode;
|
|
1362
|
+
if (COLOR.test(d.color || '')) patch.color = d.color;
|
|
1363
|
+
if (Object.keys(patch).length > 1) this.emit('city.room.updated', { room: patch });
|
|
1364
|
+
return this.state.rooms[r.id];
|
|
1365
|
+
}
|
|
1366
|
+
|
|
1367
|
+
removeRoom(d, who) {
|
|
1368
|
+
this._hostOnly(who);
|
|
1369
|
+
const r = this.state.rooms[str(d.roomId, 24)];
|
|
1370
|
+
if (!r) fail('not_found', 'no such room');
|
|
1371
|
+
if (r.builtin) fail('bad_request', 'builtin rooms cannot be removed');
|
|
1372
|
+
if (Object.values(this.state.tasks).some((t) => !TERMINAL.has(t.status) && t.pipeline.includes(r.id))) fail('conflict', 'open tasks still go through that room');
|
|
1373
|
+
this.emit('city.room.removed', { roomId: r.id });
|
|
1374
|
+
return {};
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
presence(d, who) {
|
|
1378
|
+
const now = this.now();
|
|
1379
|
+
const r = this.presenceRate.get(who.id) || { sec: 0, n: 0 };
|
|
1380
|
+
const sec = Math.floor(now / 1000);
|
|
1381
|
+
if (r.sec !== sec) { r.sec = sec; r.n = 0; }
|
|
1382
|
+
if (++r.n > LIMITS.presencePerSecond) { this.presenceRate.set(who.id, r); return {}; }
|
|
1383
|
+
this.presenceRate.set(who.id, r);
|
|
1384
|
+
const x = Number(d.x);
|
|
1385
|
+
const y = Number(d.y);
|
|
1386
|
+
if (d.left === true) { this.bus.live('city.presence.left', { id: who.id }); return {}; }
|
|
1387
|
+
if (!Number.isFinite(x) || !Number.isFinite(y)) return {};
|
|
1388
|
+
this.bus.live('city.presence', {
|
|
1389
|
+
id: who.id, name: str(d.name, LIMITS.name) || who.name, color: COLOR.test(d.color || '') ? d.color : undefined,
|
|
1390
|
+
x: Math.round(x * 100) / 100, y: Math.round(y * 100) / 100, room: str(d.room, 24) || undefined, building: str(d.building, 30) || undefined, ts: now
|
|
1391
|
+
});
|
|
1392
|
+
return {};
|
|
1393
|
+
}
|
|
1394
|
+
|
|
1395
|
+
/** The snapshot and the tail for a late joiner (CITY-PROTOCOL.md, city.sync). */
|
|
1396
|
+
sync(d) {
|
|
1397
|
+
if (!this.snapshot) this._snapshotMaybe(true);
|
|
1398
|
+
const since = Number(d?.since);
|
|
1399
|
+
const tailFrom = (seq) => {
|
|
1400
|
+
const out = [];
|
|
1401
|
+
for (const e of this.bus.events) if (e.seq > seq && isCityEvent(e)) out.push(e);
|
|
1402
|
+
return out;
|
|
1403
|
+
};
|
|
1404
|
+
if (Number.isFinite(since) && since >= this.snapshot.seq) {
|
|
1405
|
+
const tail = tailFrom(since);
|
|
1406
|
+
if (tail.length <= LIMITS.tail) return { tail, lastSeq: this.bus.seq };
|
|
1407
|
+
}
|
|
1408
|
+
let tail = tailFrom(this.snapshot.seq);
|
|
1409
|
+
if (tail.length > LIMITS.tail) { this._snapshotMaybe(true); tail = tailFrom(this.snapshot.seq); }
|
|
1410
|
+
return { snapshot: this.snapshot.city, snapshotSeq: this.snapshot.seq, tail, lastSeq: this.bus.seq };
|
|
1411
|
+
}
|
|
1412
|
+
|
|
1413
|
+
/** Registers the city.* commands on the engine server. */
|
|
1414
|
+
register(server) {
|
|
1415
|
+
const cmd = (type, fn, { guest = true } = {}) => server.command(type, (data, client) => {
|
|
1416
|
+
const d = data && typeof data === 'object' ? data : {};
|
|
1417
|
+
const who = this._who(d);
|
|
1418
|
+
if (who.guest && !guest) fail('forbidden', 'only the host can do this');
|
|
1419
|
+
// The role of a guest is checked here too, not only in the host's browser (src/collab/policy.js).
|
|
1420
|
+
if (who.guest) checkGuest(who, type, (code, message) => new CityError(code, message));
|
|
1421
|
+
if (type !== 'city.presence') this._rate(who);
|
|
1422
|
+
return fn(d, who, client);
|
|
1423
|
+
});
|
|
1424
|
+
cmd('city.state', () => ({ city: this.state, lastSeq: this.bus.seq }));
|
|
1425
|
+
cmd('city.sync', (d) => this.sync(d));
|
|
1426
|
+
cmd('city.task.create', (d, w) => ({ task: this.createTask(d, w) }));
|
|
1427
|
+
cmd('city.task.assign', (d, w) => ({ task: this.assignTask(d, w) }));
|
|
1428
|
+
cmd('city.task.move', (d, w) => ({ task: this.moveTask(d, w) }));
|
|
1429
|
+
cmd('city.task.approve', (d, w) => ({ task: this.approveTask(d, w) }));
|
|
1430
|
+
cmd('city.task.reject', (d, w) => ({ task: this.rejectTask(d, w) }));
|
|
1431
|
+
cmd('city.task.retry', (d, w) => ({ task: this.retryTask(d, w) }));
|
|
1432
|
+
cmd('city.task.cancel', (d, w) => ({ task: this.cancelTask(d, w) }));
|
|
1433
|
+
cmd('city.agent.hire', (d, w) => ({ agent: this.hireAgent(d, w) }), { guest: false });
|
|
1434
|
+
cmd('city.agent.update', (d, w) => ({ agent: this.updateAgent(d, w) }));
|
|
1435
|
+
cmd('city.agent.move', (d, w) => ({ agent: this.moveAgent(d, w) }));
|
|
1436
|
+
cmd('city.agent.retire', (d, w) => this.retireAgent(d, w));
|
|
1437
|
+
cmd('city.agent.wake', (d, w) => ({ agent: this.wakeAgent(d, w) }));
|
|
1438
|
+
for (const op of ['list', 'add', 'update', 'delete']) cmd(`city.agent.memory.${op}`, (d, w) => this.memoryCommand(op, d, w));
|
|
1439
|
+
cmd('city.agents.local', () => this.localAgents(), { guest: false });
|
|
1440
|
+
cmd('city.agents.save', (d, w) => this.saveLocalAgents(d, w), { guest: false });
|
|
1441
|
+
cmd('city.machine.join', (d, w) => {
|
|
1442
|
+
if (!w.guest) fail('bad_request', 'city.machine.join comes from a guest: the host browser forwards it with as');
|
|
1443
|
+
return this.joinMachine(d, w.owner);
|
|
1444
|
+
});
|
|
1445
|
+
cmd('city.machine.update', (d, w) => {
|
|
1446
|
+
const m = this.state.machines[str(d.machineId, 30)];
|
|
1447
|
+
if (!m) fail('not_found', 'no such machine');
|
|
1448
|
+
if (m.owner !== w.owner) fail('forbidden', 'only the owner of a machine can change it');
|
|
1449
|
+
const patch = { id: m.id };
|
|
1450
|
+
if (str(d.name, LIMITS.name)) patch.name = str(d.name, LIMITS.name);
|
|
1451
|
+
if (str(d.model, 120)) patch.model = str(d.model, 120);
|
|
1452
|
+
if (COLOR.test(d.color || '')) patch.color = d.color;
|
|
1453
|
+
if (typeof d.brainId === 'string' && !m.host) {
|
|
1454
|
+
if (!this.scheduler.brains.has(d.brainId)) fail('not_found', 'no such brain');
|
|
1455
|
+
// Only the machine's owner binds a model to it, and only a model that owner lent itself.
|
|
1456
|
+
if (!this._lentBy(d.brainId, m.owner)) fail('forbidden', 'a building can use only the model its owner lends');
|
|
1457
|
+
patch.brainId = d.brainId;
|
|
1458
|
+
}
|
|
1459
|
+
if (m.host && patch.name) this.store.setMachineName(patch.name);
|
|
1460
|
+
this.emit('city.machine.updated', { machine: patch });
|
|
1461
|
+
if (patch.brainId) {
|
|
1462
|
+
this._restrictBrain(patch.brainId, m.id);
|
|
1463
|
+
for (const a of Object.values(this.state.agents)) if (a.home === m.id && !a.retired) this.scheduler.setPreference(a.workerId, patch.brainId);
|
|
1464
|
+
}
|
|
1465
|
+
this._kick();
|
|
1466
|
+
return { machine: this.state.machines[m.id] };
|
|
1467
|
+
});
|
|
1468
|
+
cmd('city.machine.leave', (d, w) => {
|
|
1469
|
+
const m = this.state.machines[str(d.machineId, 30)];
|
|
1470
|
+
if (!m) fail('not_found', 'no such machine');
|
|
1471
|
+
if (m.owner !== w.owner && w.guest) fail('forbidden', 'only the owner of a machine (or the host) can take it out');
|
|
1472
|
+
if (m.host) fail('bad_request', 'the host machine cannot leave its own city');
|
|
1473
|
+
this.leaveMachine(m.id, d.reason);
|
|
1474
|
+
return {};
|
|
1475
|
+
});
|
|
1476
|
+
cmd('city.borrow.request', (d, w) => ({ borrow: this.requestBorrow(d, w) }));
|
|
1477
|
+
cmd('city.borrow.answer', (d, w) => ({ borrow: this.answerBorrow(d, w) }));
|
|
1478
|
+
cmd('city.borrow.stop', (d, w) => ({ borrow: this.stopBorrow(d, w) }));
|
|
1479
|
+
cmd('city.presence', (d, w) => this.presence(d, w));
|
|
1480
|
+
cmd('city.room.add', (d, w) => ({ room: this.addRoom(d, w) }), { guest: false });
|
|
1481
|
+
cmd('city.room.update', (d, w) => ({ room: this.updateRoom(d, w) }), { guest: false });
|
|
1482
|
+
cmd('city.room.remove', (d, w) => this.removeRoom(d, w), { guest: false });
|
|
1483
|
+
}
|
|
1484
|
+
|
|
1485
|
+
async close() {
|
|
1486
|
+
if (this.closed) return;
|
|
1487
|
+
for (const x of this.exec.values()) x.ctrl.abort();
|
|
1488
|
+
this.exec.clear();
|
|
1489
|
+
for (const id of [...this.borrowRt.keys()]) {
|
|
1490
|
+
const b = this.state.borrows[id];
|
|
1491
|
+
if (b && b.status !== 'ended') this._endBorrow(id, 'stopped');
|
|
1492
|
+
}
|
|
1493
|
+
for (const t of this.saveTimers.values()) clearTimeout(t);
|
|
1494
|
+
for (const id of this.saveTimers.keys()) this._saveNow(id);
|
|
1495
|
+
this.saveTimers.clear();
|
|
1496
|
+
for (const a of Object.values(this.state.agents)) if (a.home === this.machineId) this._saveNow(a.id);
|
|
1497
|
+
this._snapshotMaybe(true);
|
|
1498
|
+
this.closed = true;
|
|
1499
|
+
this.off?.();
|
|
1500
|
+
if (this.hive) { this.hive.adaptWorker = null; this.hive.extraMemories = null; }
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
|
|
1504
|
+
function clone(x) {
|
|
1505
|
+
return JSON.parse(JSON.stringify(x));
|
|
1506
|
+
}
|
|
1507
|
+
|
|
1508
|
+
function taskNum(id) {
|
|
1509
|
+
const m = /^ct_(\d+)$/.exec(id);
|
|
1510
|
+
return m ? Number(m[1]) : 0;
|
|
1511
|
+
}
|
|
1512
|
+
|
|
1513
|
+
function perms(tools) {
|
|
1514
|
+
return { shell: tools.includes('run'), write: tools.includes('write_file') || tools.includes('edit_file') || tools.includes('delete_file') };
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
function num(v) {
|
|
1518
|
+
return Number.isFinite(v) && v >= 0 ? v : undefined;
|
|
1519
|
+
}
|
|
1520
|
+
|
|
1521
|
+
function clampInt(v, min, max, dflt) {
|
|
1522
|
+
const n = Math.round(Number(v));
|
|
1523
|
+
return Number.isFinite(n) ? Math.min(Math.max(n, min), max) : dflt;
|
|
1524
|
+
}
|
|
1525
|
+
|
|
1526
|
+
function safeJson(text) {
|
|
1527
|
+
try { return JSON.parse(String(text || '').replace(/^```(?:json)?\s*|\s*```$/g, '')); } catch { return null; }
|
|
1528
|
+
}
|
|
1529
|
+
|
|
1530
|
+
/** A clean list of room ids (the first one is the home room), or null. */
|
|
1531
|
+
function cleanSpec(list, known = ROOM_IDS) {
|
|
1532
|
+
if (!Array.isArray(list)) return null;
|
|
1533
|
+
const out = [...new Set(list.map((x) => String(x).trim().toLowerCase()).filter((x) => known.includes(x)))].slice(0, 6);
|
|
1534
|
+
return out.length ? out : null;
|
|
1535
|
+
}
|
|
1536
|
+
|
|
1537
|
+
/**
|
|
1538
|
+
* Starts the city on a running engine and registers its commands.
|
|
1539
|
+
* @returns {City}
|
|
1540
|
+
*/
|
|
1541
|
+
export function startCity({ bus, hive, scheduler, toolbox, server, home, projectDir, version }) {
|
|
1542
|
+
const city = new City({ bus, hive, scheduler, toolbox, home, projectDir, version });
|
|
1543
|
+
city.start();
|
|
1544
|
+
if (server) city.register(server);
|
|
1545
|
+
return city;
|
|
1546
|
+
}
|