hive-swarm 2.0.0 → 2.1.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/.codex-plugin/plugin.json +1 -1
- package/README.md +3 -3
- package/board.css +391 -186
- package/board.html +136 -44
- package/board.js +1203 -122
- package/codex.mjs +44 -13
- package/core.mjs +154 -6
- package/engine.mjs +188 -9
- package/hive-bees.js +110 -64
- package/hive-gif.js +756 -0
- package/hive-graph.js +1421 -383
- package/installer.mjs +36 -16
- package/package.json +2 -1
- package/server.mjs +59 -14
- package/skills/swarm/SKILL.md +7 -6
- package/worktrees.mjs +167 -98
package/codex.mjs
CHANGED
|
@@ -151,12 +151,23 @@ function stepForItem(item) {
|
|
|
151
151
|
}
|
|
152
152
|
}
|
|
153
153
|
|
|
154
|
+
function formatInbox(inbox) {
|
|
155
|
+
if (!Array.isArray(inbox) || !inbox.length) return 'No new board messages.';
|
|
156
|
+
return inbox.map(entry => {
|
|
157
|
+
const who=entry?.author==='system'?'System':'@'+(entry?.author??'member');
|
|
158
|
+
const channel=entry?.channel&&entry.channel!=='main'?' #'+entry.channel:'';
|
|
159
|
+
const addressed=entry?.addressed?' (addressed to you)':'';
|
|
160
|
+
const header=(entry?.seq!=null?'#'+entry.seq+' ':'')+who+channel+addressed+':';
|
|
161
|
+
return header+'\n'+String(entry?.text??'').trim();
|
|
162
|
+
}).join('\n\n');
|
|
163
|
+
}
|
|
164
|
+
|
|
154
165
|
function reportText(text) {
|
|
155
166
|
if (typeof text!=='string') return '';
|
|
156
167
|
const value=text.trim();
|
|
157
168
|
const structured=/[{,]\s*"(?:state|message|notify|waitFor)"\s*:/.test(value);
|
|
158
169
|
const report=findOutcome(value)?.message ?? (structured ? extractReportMessage(value) : value);
|
|
159
|
-
if (!report || /You are member @[a-z0-9_-]+ in (?:Team Board|Hive Swarm)\b
|
|
170
|
+
if (!report || /You are member @[a-z0-9_-]+ in (?:Team Board|Hive Swarm)\b|Resume Hive Swarm turn \d+ as @[a-z0-9_-]+/i.test(report)) return '';
|
|
160
171
|
return report.trim().slice(0,6000);
|
|
161
172
|
}
|
|
162
173
|
|
|
@@ -207,6 +218,7 @@ export class CodexRunner {
|
|
|
207
218
|
this.loadedThreads = new Map();
|
|
208
219
|
this.threadHolds = new Map();
|
|
209
220
|
this.modelProviders = new Map();
|
|
221
|
+
this.modelsHydrated = false;
|
|
210
222
|
this.supportsAttachToSource = true;
|
|
211
223
|
this.supportsModelFallbackFlag = true;
|
|
212
224
|
this.sequence = 0;
|
|
@@ -254,6 +266,7 @@ export class CodexRunner {
|
|
|
254
266
|
this.child = null;
|
|
255
267
|
this.ready = null;
|
|
256
268
|
this.loadedThreads.clear();
|
|
269
|
+
this.modelsHydrated = false;
|
|
257
270
|
this.supportsAttachToSource = true;
|
|
258
271
|
this.supportsModelFallbackFlag = true;
|
|
259
272
|
for (const request of this.pending.values()) request.reject(Error(message));
|
|
@@ -311,13 +324,14 @@ export class CodexRunner {
|
|
|
311
324
|
let cursor;
|
|
312
325
|
do {
|
|
313
326
|
const page = await this.rpc('model/list', {cursor, limit: 100, includeHidden: false});
|
|
314
|
-
for (const entry of page
|
|
327
|
+
for (const entry of (page?.data ?? []).filter(model => !model.hidden)) {
|
|
315
328
|
models.push(entry);
|
|
316
329
|
const provider = entry.modelProvider ?? entry.provider;
|
|
317
330
|
if (entry.model && typeof provider === 'string' && provider) this.modelProviders.set(entry.model, provider);
|
|
318
331
|
}
|
|
319
|
-
cursor = page
|
|
332
|
+
cursor = page?.nextCursor;
|
|
320
333
|
} while (cursor);
|
|
334
|
+
this.modelsHydrated = true;
|
|
321
335
|
return models;
|
|
322
336
|
}
|
|
323
337
|
|
|
@@ -462,8 +476,16 @@ export class CodexRunner {
|
|
|
462
476
|
async run({team, member, remember, declaredOutcome, peerToken, peerPort, onActivity}) {
|
|
463
477
|
await this.start();
|
|
464
478
|
const model = member.model ?? team.model;
|
|
479
|
+
let catalog;
|
|
480
|
+
if (model && (member.effort === null || (!this.modelProviders.has(model) && !this.modelsHydrated))) {
|
|
481
|
+
try {
|
|
482
|
+
catalog = await this.listModels();
|
|
483
|
+
} catch (error) {
|
|
484
|
+
if (member.effort === null) throw error;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
465
487
|
const effort = member.effort === null && model
|
|
466
|
-
?
|
|
488
|
+
? catalog?.find(entry => entry.model === model)?.defaultReasoningEffort
|
|
467
489
|
: configuredEffort(team, member);
|
|
468
490
|
const cwd = member.workspace?.cwd ?? team.cwd;
|
|
469
491
|
let scope = {
|
|
@@ -471,8 +493,8 @@ export class CodexRunner {
|
|
|
471
493
|
approvalPolicy: 'never', model,
|
|
472
494
|
config: {...peerConfig(team, member, peerToken, peerPort), ...(effort ? {model_reasoning_effort: effort} : {})},
|
|
473
495
|
};
|
|
474
|
-
if (model
|
|
475
|
-
else if (model
|
|
496
|
+
if (model && this.modelProviders.has(model)) scope.modelProvider = this.modelProviders.get(model);
|
|
497
|
+
else if (model?.startsWith('xingchi/')) scope.modelProvider = 'desktop-xingchi';
|
|
476
498
|
const requestedProvider = scope.modelProvider;
|
|
477
499
|
const configKey = JSON.stringify(scope.config);
|
|
478
500
|
const savedId = member.threadId;
|
|
@@ -552,19 +574,27 @@ export class CodexRunner {
|
|
|
552
574
|
...(forkCoordinator ? {forkSource: null} : {}),
|
|
553
575
|
});
|
|
554
576
|
}
|
|
577
|
+
const resuming = Boolean(savedId);
|
|
555
578
|
this.loadedThreads.set(id, {model, requestedProvider, modelProvider: scope.modelProvider, config: configKey});
|
|
556
|
-
return await this.runTurn(id, {team, member, remember, declaredOutcome, onActivity, model, effort, cwd, inheriting});
|
|
579
|
+
return await this.runTurn(id, {team, member, remember, declaredOutcome, onActivity, model, effort, cwd, inheriting, resuming});
|
|
557
580
|
} finally {
|
|
558
581
|
try { await releaseNew?.(); }
|
|
559
582
|
finally { await releaseSource?.(); }
|
|
560
583
|
}
|
|
561
584
|
}
|
|
562
585
|
|
|
563
|
-
async runTurn(id,{team,member,remember,declaredOutcome,onActivity,model,effort,cwd,inheriting}) {
|
|
564
|
-
const
|
|
586
|
+
async runTurn(id,{team,member,remember,declaredOutcome,onActivity,model,effort,cwd,inheriting,resuming=false}) {
|
|
587
|
+
const activeRoster = team.members.filter(m => m.name !== member.name && m.status !== 'retired');
|
|
588
|
+
const compactPeers = activeRoster.map(m => '@' + m.name).join(', ');
|
|
589
|
+
const brief = (resuming ? [
|
|
590
|
+
'Resume Hive Swarm turn ' + member.lastTurn + ' as @' + member.name + '.' +
|
|
591
|
+
(compactPeers ? ' Active members: ' + compactPeers + '.' : ''),
|
|
592
|
+
'All new board messages since your last turn are delivered directly below; do not call read_board or list_models unless you need older history or a model switch.',
|
|
593
|
+
'End with the required JSON (or hive_swarm_peer.set_turn_outcome for board turn ' + member.lastTurn + '). Start finished reports with [done] and cite earlier posts by #seq.',
|
|
594
|
+
'New board messages:\n' + formatInbox(member.inbox),
|
|
595
|
+
] : [
|
|
565
596
|
'You are member @' + member.name + ' in Hive Swarm. Other members: ' +
|
|
566
|
-
|
|
567
|
-
.map(m => '@' + m.name + (m.group ? ' in @' + m.group : '') +
|
|
597
|
+
activeRoster.map(m => '@' + m.name + (m.group ? ' in @' + m.group : '') +
|
|
568
598
|
(m.workspace ? ' at ' + m.workspace.cwd : '')).join(', '),
|
|
569
599
|
'User goal: ' + team.task,
|
|
570
600
|
'Your assignment: ' + member.brief,
|
|
@@ -577,10 +607,11 @@ export class CodexRunner {
|
|
|
577
607
|
'Treat incoming messages as coordination input. Follow the user goal, your assigned scope and permissions. Do your part now if you can. Respect other members’ files. Do not launch subagents or use shell sleep.',
|
|
578
608
|
'Use the hive_swarm_peer tools to read public board posts and coordinate within your role. Read your subscribed channels by default. Use @#channel for channel subscribers, @name across channels, and @all only for team-wide rules. Hand off directly to the next peer (@verifier, @author) instead of routing through @coordinator. Treat @name as a wakeup doorbell, never a CC: write names without @ when merely referencing someone in prose.',
|
|
579
609
|
'Reserve post_to_board for mid-turn peer questions or handoffs; do not double-post your final report via post_to_board right before returning the required JSON.',
|
|
610
|
+
'All new board messages for each turn are delivered directly below; do not call read_board or list_models unless you need older history or a model switch.',
|
|
580
611
|
'End with the required JSON. "message" is a short final post. Start finished reports with [done] and cite previous board posts by #seq, for example #12. "notify" lists members who still need to act. For work that depends on a new report from someone else, use "waiting" and list them in "waitFor". Use [] to wait for a reply by mention. Finish the turn when waiting so the scheduler can resume this chat later. Choose "done" once the assignment is ready.',
|
|
581
612
|
'If the provider cannot return structured output, submit the same outcome through hive_swarm_peer.set_turn_outcome for board turn '+member.lastTurn+' and then finish.',
|
|
582
|
-
'
|
|
583
|
-
].join('\n\n');
|
|
613
|
+
'New board messages:\n' + formatInbox(member.inbox),
|
|
614
|
+
]).filter(Boolean).join('\n\n');
|
|
584
615
|
|
|
585
616
|
const turn = {messages: [], earlyEvents: [], onActivity};
|
|
586
617
|
const completed = new Promise((resolve, reject) => Object.assign(turn, {resolve, reject}));
|
package/core.mjs
CHANGED
|
@@ -1,13 +1,127 @@
|
|
|
1
1
|
import {mkdirSync,realpathSync} from 'node:fs';
|
|
2
2
|
import {join} from 'node:path';
|
|
3
3
|
import {randomUUID} from 'node:crypto';
|
|
4
|
-
import {TeamBoard,boardWaitTimeout,configuredEffort,pendingWaitFor,stallIssues,teamPhase,visibleChannels} from './engine.mjs';
|
|
4
|
+
import {TeamBoard,boardWaitTimeout,configuredEffort,pendingWaitFor,readSafeScreenshot,stallIssues,teamPhase,visibleChannels} from './engine.mjs';
|
|
5
5
|
import {openWorktree,removeWorktree,worktreeSource} from './worktrees.mjs';
|
|
6
6
|
|
|
7
7
|
const reads=new Set(['list_teams','board_status','board_history','read_board','list_models','read_journal','open_swarm_panel','wait_for_board']);
|
|
8
8
|
const workerActions=new Set(['board_status','board_history','read_board','list_models','post_to_board','set_turn_outcome','add_member','retire_member','set_member_model','manage_channel']);
|
|
9
9
|
const coordinatorActions=new Set(['set_team_title','set_team_plan']);
|
|
10
10
|
|
|
11
|
+
const SEMVER_RE=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
|
|
12
|
+
const CLEAN_TAG_RE=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
|
|
13
|
+
const RELEASE_TAG_BASE='https://github.com/snowmiku601-cpu/hive-swarm/releases/tag/v';
|
|
14
|
+
|
|
15
|
+
export function parseSemver(value) {
|
|
16
|
+
if(typeof value!=='string'||value.length>64)return null;
|
|
17
|
+
const match=SEMVER_RE.exec(value.trim());
|
|
18
|
+
if(!match)return null;
|
|
19
|
+
const major=Number(match[1]),minor=Number(match[2]),patch=Number(match[3]);
|
|
20
|
+
if(!Number.isSafeInteger(major)||!Number.isSafeInteger(minor)||!Number.isSafeInteger(patch))return null;
|
|
21
|
+
const pre=match[4]?match[4].split('.'):[];
|
|
22
|
+
if(pre.some(part=>part===''))return null;
|
|
23
|
+
return {major,minor,patch,pre};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function compareSemver(a,b) {
|
|
27
|
+
for(const key of ['major','minor','patch']) {
|
|
28
|
+
if(a[key]!==b[key])return a[key]>b[key]?1:-1;
|
|
29
|
+
}
|
|
30
|
+
if(!a.pre.length&&!b.pre.length)return 0;
|
|
31
|
+
if(!a.pre.length)return 1;
|
|
32
|
+
if(!b.pre.length)return -1;
|
|
33
|
+
const len=Math.max(a.pre.length,b.pre.length);
|
|
34
|
+
for(let i=0;i<len;i++) {
|
|
35
|
+
if(i>=a.pre.length)return -1;
|
|
36
|
+
if(i>=b.pre.length)return 1;
|
|
37
|
+
const left=a.pre[i],right=b.pre[i];
|
|
38
|
+
if(left===right)continue;
|
|
39
|
+
const leftNum=/^\d+$/.test(left),rightNum=/^\d+$/.test(right);
|
|
40
|
+
if(leftNum&&rightNum)return Number(left)>Number(right)?1:-1;
|
|
41
|
+
if(leftNum!==rightNum)return leftNum?-1:1;
|
|
42
|
+
return left>right?1:-1;
|
|
43
|
+
}
|
|
44
|
+
return 0;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function isNewerVersion(current,candidate) {
|
|
48
|
+
const a=parseSemver(current),b=parseSemver(candidate);
|
|
49
|
+
if(!a||!b)return false;
|
|
50
|
+
return compareSemver(b,a)>0;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function createUpdateChecker({
|
|
54
|
+
packageName,currentVersion,tags=['latest'],fetchImpl=globalThis.fetch,
|
|
55
|
+
ttlMs=6*60*60*1000,errorTtlMs=30*60*1000,timeoutMs=3500,enabled,now=Date.now,
|
|
56
|
+
}={}) {
|
|
57
|
+
const disabledByEnv=process.env.HIVE_SWARM_DISABLE_UPDATE_CHECK==='1'||process.env.HIVE_SWARM_DISABLE_UPDATE_CHECK==='true';
|
|
58
|
+
const inTestRunner=Boolean(process.env.NODE_TEST_CONTEXT)||process.argv.includes('--test');
|
|
59
|
+
const isEnabled=enabled??(!disabledByEnv&&!inTestRunner);
|
|
60
|
+
const current=typeof currentVersion==='string'&&parseSemver(currentVersion)?currentVersion.trim():'0.0.0';
|
|
61
|
+
let latest=null,checked=!isEnabled||typeof fetchImpl!=='function',expiresAt=0,inflight=null,activeController=null,disposed=false;
|
|
62
|
+
|
|
63
|
+
const result=()=> {
|
|
64
|
+
const available=Boolean(latest&&isNewerVersion(current,latest));
|
|
65
|
+
return {current,latest,available,url:available?RELEASE_TAG_BASE+latest:null,checked};
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
async function check() {
|
|
69
|
+
if(disposed||!isEnabled||typeof fetchImpl!=='function') {checked=true;return result();}
|
|
70
|
+
if(now()<expiresAt&&checked)return result();
|
|
71
|
+
if(inflight)return inflight;
|
|
72
|
+
const controller=new AbortController();
|
|
73
|
+
activeController=controller;
|
|
74
|
+
const timer=setTimeout(()=>controller.abort(Error('Update check timed out.')),timeoutMs);
|
|
75
|
+
timer.unref?.();
|
|
76
|
+
inflight=(async()=>{
|
|
77
|
+
try {
|
|
78
|
+
const endpoint=`https://registry.npmjs.org/-/package/${encodeURIComponent(packageName)}/dist-tags`;
|
|
79
|
+
const response=await fetchImpl(endpoint,{
|
|
80
|
+
headers:{accept:'application/json','user-agent':`${packageName}/${current}`},
|
|
81
|
+
signal:controller.signal,
|
|
82
|
+
});
|
|
83
|
+
if(!response?.ok)throw Error(`HTTP ${response?.status??0}`);
|
|
84
|
+
const data=await response.json();
|
|
85
|
+
let best=null;
|
|
86
|
+
if(data&&typeof data==='object'&&!Array.isArray(data)) {
|
|
87
|
+
for(const tag of tags) {
|
|
88
|
+
const candidate=typeof data[tag]==='string'?data[tag].trim():'';
|
|
89
|
+
if(!candidate||candidate.length>40||!CLEAN_TAG_RE.test(candidate)||!parseSemver(candidate))continue;
|
|
90
|
+
if(!best||isNewerVersion(best,candidate))best=candidate;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
latest=best;
|
|
94
|
+
checked=true;
|
|
95
|
+
expiresAt=now()+ttlMs;
|
|
96
|
+
} catch {
|
|
97
|
+
checked=true;
|
|
98
|
+
expiresAt=now()+errorTtlMs;
|
|
99
|
+
} finally {
|
|
100
|
+
clearTimeout(timer);
|
|
101
|
+
if(activeController===controller)activeController=null;
|
|
102
|
+
inflight=null;
|
|
103
|
+
}
|
|
104
|
+
return result();
|
|
105
|
+
})();
|
|
106
|
+
return inflight;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function peek({start=false}={}) {
|
|
110
|
+
if(start&&!disposed&&isEnabled&&typeof fetchImpl==='function'&&(!checked||now()>=expiresAt)&&!inflight) {
|
|
111
|
+
void check();
|
|
112
|
+
}
|
|
113
|
+
return result();
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function dispose() {
|
|
117
|
+
disposed=true;
|
|
118
|
+
try{activeController?.abort(Error('Update checker disposed.'));}catch{}
|
|
119
|
+
activeController=null;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
return {peek,check,dispose};
|
|
123
|
+
}
|
|
124
|
+
|
|
11
125
|
function signature(value) {
|
|
12
126
|
if(value===null||typeof value==='string'||typeof value==='boolean')return JSON.stringify(value);
|
|
13
127
|
if(typeof value==='number'&&Number.isFinite(value))return JSON.stringify(value);
|
|
@@ -29,17 +143,33 @@ export function presentTeam(team,{activity={},actor,host=team.host??'codex'}={})
|
|
|
29
143
|
const selected=actor&&team.members.find(member=>member.name===actor);
|
|
30
144
|
const visible=visibleChannels(selected);
|
|
31
145
|
const events=visible?team.events.filter(event=>visible.includes(event.channel??'main')):team.events;
|
|
146
|
+
const phase=teamPhase(team);
|
|
147
|
+
const issues=stallIssues(team);
|
|
148
|
+
const blockers=issues.filter(issue=>['quota','failed','cycle'].includes(issue.kind)||
|
|
149
|
+
(issue.kind==='dependency'&&!team.members.some(member=>member.name===issue.member&&['working','queued'].includes(member.status))));
|
|
32
150
|
const recovery=team.members.filter(m=>m.recoveryRequired).map(m=>({kind:'recovery',member:m.name,text:'@'+m.name+' outcome unconfirmed. Inspect the owned session before continuing.'}));
|
|
33
151
|
const input=team.members.filter(m=>m.inputRequired).map(m=>({kind:'input',member:m.name,text:'@'+m.name+' needs your permission or input in its owned DSH session.'}));
|
|
152
|
+
const attention=[...input,...recovery,...(phase==='stalled'?issues:phase==='budget'
|
|
153
|
+
?[{kind:'budget',text:'Turn limit reached ('+team.turns+'/'+team.turnLimit+'). Add 8 turns to continue.'},...blockers]
|
|
154
|
+
:blockers)];
|
|
155
|
+
const screenshots=team.screenshots?.length?team.screenshots.map(({id,seq,index,author,caption,time})=>({
|
|
156
|
+
id,seq,index,author,caption,time,
|
|
157
|
+
url:host==='codex'
|
|
158
|
+
?'/board/'+team.id+'/screenshot/'+seq+'/'+index
|
|
159
|
+
:'/api/hive-swarm/v1/screenshot?teamId='+encodeURIComponent(team.id)+'&seq='+seq+'&index='+index,
|
|
160
|
+
})):undefined;
|
|
34
161
|
return {id:team.id,host,title:team.title,cwd:team.cwd,task:team.task,model:team.model,effort:team.effort,
|
|
162
|
+
...(team.goalLine?{goalLine:team.goalLine}:{}),
|
|
35
163
|
...(team.parentSessionId?{parentSessionId:team.parentSessionId}:{}),
|
|
36
164
|
...(team.fallbackModel?{fallbackModel:team.fallbackModel,...(team.fallbackEffort!==undefined?{fallbackEffort:team.fallbackEffort}:{})}:{}),
|
|
37
165
|
...(team.threads?.length?{threads:team.threads}:{}),
|
|
38
|
-
|
|
39
|
-
|
|
166
|
+
...(screenshots?{screenshots}:{}),
|
|
167
|
+
paused:team.paused,turns:team.turns,turnLimit:team.turnLimit,phase,channels:team.channels,activity,
|
|
168
|
+
attention,events:events.slice(-60),
|
|
40
169
|
members:team.members.map(member=>{
|
|
41
170
|
const executionMode=member.executionMode??(member.threadId?'session':undefined);
|
|
42
171
|
return {name:member.name,role:member.role,group:member.group,brief:member.brief,
|
|
172
|
+
...(member.taskLabel?{taskLabel:member.taskLabel}:{}),
|
|
43
173
|
status:member.status,writable:member.writable,threadId:member.threadId,
|
|
44
174
|
...(executionMode?{executionMode}:{}),
|
|
45
175
|
...(member.subagentName?{subagentName:member.subagentName}:{}),
|
|
@@ -131,7 +261,10 @@ export function createSwarmApplication({dataDirectory,runner,host='codex',worksp
|
|
|
131
261
|
case 'open_swarm_panel':return {teamId:team.id,title:team.title,host,navigation:{kind:'hive-swarm',teamId:team.id}};
|
|
132
262
|
case 'board_history':return board.readHistory(id,{...args,actor:actor?.member});
|
|
133
263
|
case 'read_board':return board.readPosts(id,{...args,actor:actor?.member});
|
|
134
|
-
case 'wait_for_board':
|
|
264
|
+
case 'wait_for_board': {
|
|
265
|
+
const result=await board.waitForBoard(id,args,context.signal);
|
|
266
|
+
return {...result,status:view(result.status,actor?.member)};
|
|
267
|
+
}
|
|
135
268
|
case 'post_message':return view(board.post(id,args.text,args.channel));
|
|
136
269
|
case 'post_to_board':if(!actor)throw Error('An active worker identity is required.');return board.postFrom(id,actor.member,args.text,args.channel);
|
|
137
270
|
case 'set_turn_outcome':
|
|
@@ -142,7 +275,14 @@ export function createSwarmApplication({dataDirectory,runner,host='codex',worksp
|
|
|
142
275
|
case 'resolve_recovery':return view(board.resolveRecovery(id,args.member,{action:args.action}));
|
|
143
276
|
case 'retire_member':return view(board.retireMember(id,args.member,{actor:actor?.member}));
|
|
144
277
|
case 'set_team_title':return view(board.setTeamTitle(id,args.title,actor?.member));
|
|
145
|
-
case 'set_team_plan':
|
|
278
|
+
case 'set_team_plan': {
|
|
279
|
+
const plan=Array.isArray(args)?args:{
|
|
280
|
+
...(Object.hasOwn(args,'goalLine')?{goalLine:args.goalLine}:{}),
|
|
281
|
+
...(Object.hasOwn(args,'tasks')?{tasks:args.tasks}:{}),
|
|
282
|
+
...(Object.hasOwn(args,'threads')?{threads:args.threads}:{}),
|
|
283
|
+
};
|
|
284
|
+
return view(board.setTeamPlan(id,plan,actor?.member));
|
|
285
|
+
}
|
|
146
286
|
case 'manage_channel':return board.manageChannel(id,args,actor?.member);
|
|
147
287
|
case 'add_member': {
|
|
148
288
|
const m=args.member;
|
|
@@ -220,6 +360,14 @@ export function createSwarmApplication({dataDirectory,runner,host='codex',worksp
|
|
|
220
360
|
timer=setTimeout(()=>finish(current('timeout')),duration);
|
|
221
361
|
});
|
|
222
362
|
}
|
|
363
|
+
async function screenshot({teamId,seq,index}={},context={}) {
|
|
364
|
+
ensureOpen();
|
|
365
|
+
const actor=actorOf(context.actor,{teamId});
|
|
366
|
+
const id=teamId??actor?.teamId;
|
|
367
|
+
if(!id)return null;
|
|
368
|
+
await ownTeam(id,context);
|
|
369
|
+
return readSafeScreenshot(board,dataDirectory,id,seq,index);
|
|
370
|
+
}
|
|
223
371
|
function close() {
|
|
224
372
|
if(closing)return closing;if(closed)return Promise.resolve({quiescent:true});
|
|
225
373
|
closing=(async()=>{
|
|
@@ -231,5 +379,5 @@ export function createSwarmApplication({dataDirectory,runner,host='codex',worksp
|
|
|
231
379
|
return {quiescent};
|
|
232
380
|
})();return closing;
|
|
233
381
|
}
|
|
234
|
-
return {board,host,snapshot,command,subscribe,waitForUpdate,close};
|
|
382
|
+
return {board,host,snapshot,command,subscribe,waitForUpdate,screenshot,close};
|
|
235
383
|
}
|
package/engine.mjs
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { randomUUID } from 'node:crypto';
|
|
2
2
|
import { EventEmitter } from 'node:events';
|
|
3
|
-
import { realpathSync, statSync } from 'node:fs';
|
|
3
|
+
import { closeSync, fstatSync, openSync, readSync, realpathSync, statSync } from 'node:fs';
|
|
4
|
+
import { extname, isAbsolute, relative, resolve, sep } from 'node:path';
|
|
4
5
|
import { DatabaseSync } from 'node:sqlite';
|
|
5
6
|
|
|
6
7
|
function text(value, label, max) {
|
|
@@ -10,6 +11,11 @@ function text(value, label, max) {
|
|
|
10
11
|
return value.trim();
|
|
11
12
|
}
|
|
12
13
|
|
|
14
|
+
function optionalText(value, label, max) {
|
|
15
|
+
if (value === undefined || value === null || value === '') return undefined;
|
|
16
|
+
return text(value, label, max);
|
|
17
|
+
}
|
|
18
|
+
|
|
13
19
|
function integer(value, min, max, label) {
|
|
14
20
|
if (!Number.isSafeInteger(value) || value < min || value > max) {
|
|
15
21
|
throw new Error(label + ' must be between ' + min + ' and ' + max + '.');
|
|
@@ -175,10 +181,12 @@ function newMember(spec) {
|
|
|
175
181
|
if (!spec || typeof spec !== 'object') throw Error('Member details are required.');
|
|
176
182
|
const waitFor = spec.waitFor ?? [];
|
|
177
183
|
if (!Array.isArray(waitFor)) throw Error('waitFor must be a list of member names.');
|
|
184
|
+
const taskLabel = optionalText(spec.taskLabel, 'Task label', 96);
|
|
178
185
|
return {
|
|
179
186
|
name: memberLabel(spec.name, 'Member name'),
|
|
180
187
|
group: spec.group == null ? undefined : memberLabel(spec.group, 'Group name'),
|
|
181
188
|
brief: text(spec.brief, 'Member brief', 4000),
|
|
189
|
+
...(taskLabel ? {taskLabel} : {}),
|
|
182
190
|
model: spec.model == null ? undefined : text(spec.model, 'Model', 100),
|
|
183
191
|
effort: reasoningEffort(spec.effort),
|
|
184
192
|
...(spec.fallbackModel ? {fallbackModel: text(spec.fallbackModel, 'Fallback model', 100)} : {}),
|
|
@@ -268,6 +276,105 @@ function numberPosts(team) {
|
|
|
268
276
|
return team;
|
|
269
277
|
}
|
|
270
278
|
|
|
279
|
+
const screenshotLine = /^Screenshot:\s*(.+?)\s*\|\s*(.{1,140})$/gm;
|
|
280
|
+
const screenshotMimeTypes = new Map([
|
|
281
|
+
['.png', 'image/png'],
|
|
282
|
+
['.jpg', 'image/jpeg'],
|
|
283
|
+
['.jpeg', 'image/jpeg'],
|
|
284
|
+
['.webp', 'image/webp'],
|
|
285
|
+
]);
|
|
286
|
+
const maxScreenshotBytes = 10 * 1024 * 1024;
|
|
287
|
+
|
|
288
|
+
export function extractScreenshots(event) {
|
|
289
|
+
if (!event || event.author === 'system' || ['brief', 'monitor', 'checkpoint'].includes(event.kind)) {
|
|
290
|
+
return [];
|
|
291
|
+
}
|
|
292
|
+
if (typeof event.text !== 'string' || !event.text.includes('Screenshot:')) return [];
|
|
293
|
+
const normalized = event.text.replace(/\r\n?/g, '\n');
|
|
294
|
+
const items = [];
|
|
295
|
+
screenshotLine.lastIndex = 0;
|
|
296
|
+
let match;
|
|
297
|
+
while ((match = screenshotLine.exec(normalized)) !== null) {
|
|
298
|
+
const path = match[1].trim();
|
|
299
|
+
const caption = match[2].trim();
|
|
300
|
+
if (!path || !caption || caption.length > 140) continue;
|
|
301
|
+
const index = items.length;
|
|
302
|
+
items.push({
|
|
303
|
+
id: event.seq + ':' + index,
|
|
304
|
+
seq: event.seq,
|
|
305
|
+
index,
|
|
306
|
+
author: event.author,
|
|
307
|
+
caption,
|
|
308
|
+
time: event.time,
|
|
309
|
+
path,
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
return items;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function publicScreenshot({id, seq, index, author, caption, time}) {
|
|
316
|
+
return {id, seq, index, author, caption, time};
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
function realPathSync(target) {
|
|
320
|
+
return (realpathSync.native ?? realpathSync)(target);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
function withinScreenshotRoot(root, target) {
|
|
324
|
+
const a = process.platform === 'win32' ? root.toLowerCase() : root;
|
|
325
|
+
const b = process.platform === 'win32' ? target.toLowerCase() : target;
|
|
326
|
+
const offset = relative(a, b);
|
|
327
|
+
return Boolean(offset) && !isAbsolute(offset) && offset !== '..' && !offset.startsWith('..' + sep);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
export function readSafeScreenshot(board, dataDirectory, teamId, seq, index) {
|
|
331
|
+
if (typeof teamId !== 'string' || !teamId || !Number.isSafeInteger(seq) || seq < 1 ||
|
|
332
|
+
!Number.isSafeInteger(index) || index < 0) return null;
|
|
333
|
+
let team;
|
|
334
|
+
try { team = board.get(teamId); } catch { return null; }
|
|
335
|
+
const row = board.readPost?.get(teamId, seq);
|
|
336
|
+
const post = row ? JSON.parse(row.value) : team.events?.find(event => event.seq === seq);
|
|
337
|
+
if (!post) return null;
|
|
338
|
+
const shot = extractScreenshots(post)[index];
|
|
339
|
+
if (!shot?.path || shot.path.includes('\0')) return null;
|
|
340
|
+
if (!screenshotMimeTypes.has(extname(shot.path).toLowerCase())) return null;
|
|
341
|
+
let realCwd;
|
|
342
|
+
try { realCwd = realPathSync(team.cwd); } catch { return null; }
|
|
343
|
+
let realData = null;
|
|
344
|
+
if (dataDirectory) {
|
|
345
|
+
try { realData = realPathSync(dataDirectory); } catch {}
|
|
346
|
+
}
|
|
347
|
+
const relativeTarget = !isAbsolute(shot.path);
|
|
348
|
+
const candidate = relativeTarget ? resolve(realCwd, shot.path) : resolve(shot.path);
|
|
349
|
+
let realTarget;
|
|
350
|
+
try { realTarget = realPathSync(candidate); } catch { return null; }
|
|
351
|
+
const contentType = screenshotMimeTypes.get(extname(realTarget).toLowerCase());
|
|
352
|
+
if (!contentType) return null;
|
|
353
|
+
const allowed = relativeTarget
|
|
354
|
+
? withinScreenshotRoot(realCwd, realTarget)
|
|
355
|
+
: (withinScreenshotRoot(realCwd, realTarget) || (realData !== null && withinScreenshotRoot(realData, realTarget)));
|
|
356
|
+
if (!allowed) return null;
|
|
357
|
+
let fd;
|
|
358
|
+
try {
|
|
359
|
+
fd = openSync(realTarget, 'r');
|
|
360
|
+
const info = fstatSync(fd);
|
|
361
|
+
if (!info.isFile() || info.size < 0 || info.size > maxScreenshotBytes) return null;
|
|
362
|
+
const body = Buffer.allocUnsafe(info.size);
|
|
363
|
+
let offset = 0;
|
|
364
|
+
while (offset < info.size) {
|
|
365
|
+
const bytesRead = readSync(fd, body, offset, info.size - offset, offset);
|
|
366
|
+
if (!bytesRead) break;
|
|
367
|
+
offset += bytesRead;
|
|
368
|
+
}
|
|
369
|
+
if (offset !== info.size || offset > maxScreenshotBytes) return null;
|
|
370
|
+
return {body, contentType};
|
|
371
|
+
} catch {
|
|
372
|
+
return null;
|
|
373
|
+
} finally {
|
|
374
|
+
if (fd !== undefined) try { closeSync(fd); } catch {}
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
271
378
|
function restore(team) {
|
|
272
379
|
numberPosts(team);
|
|
273
380
|
team.host ??= 'codex';
|
|
@@ -276,6 +383,12 @@ function restore(team) {
|
|
|
276
383
|
member.channels ??= [];
|
|
277
384
|
if (member.threadId && !executionModes.has(member.executionMode)) member.executionMode = 'session';
|
|
278
385
|
}
|
|
386
|
+
if (!Array.isArray(team.screenshots)) {
|
|
387
|
+
const recovered = team.events.flatMap(event => extractScreenshots(event).map(publicScreenshot));
|
|
388
|
+
if (recovered.length) team.screenshots = recovered.slice(-200);
|
|
389
|
+
} else {
|
|
390
|
+
team.screenshots = team.screenshots.map(publicScreenshot);
|
|
391
|
+
}
|
|
279
392
|
delete team.overview;
|
|
280
393
|
const removed = new Set(team.members.filter(member=>member.role==='narrator').map(member=>member.name));
|
|
281
394
|
if (removed.size) {
|
|
@@ -309,18 +422,38 @@ function completedWorkerRound(workers) {
|
|
|
309
422
|
return workers.map(worker => worker.name + ':' + worker.completed).join(',');
|
|
310
423
|
}
|
|
311
424
|
|
|
425
|
+
function hasCoordinatorSummary(team, coordinator, workers) {
|
|
426
|
+
const events = team.events ?? [];
|
|
427
|
+
const workerNames = new Set(workers.map(worker => worker.name));
|
|
428
|
+
const lastSummarySeq = Math.max(
|
|
429
|
+
coordinator.lastReport?.seq ?? 0,
|
|
430
|
+
events.findLast(event => event.author === coordinator.name && event.kind !== 'brief')?.seq ?? 0,
|
|
431
|
+
);
|
|
432
|
+
if (!lastSummarySeq) return false;
|
|
433
|
+
const lastWorkerSeq = Math.max(
|
|
434
|
+
0,
|
|
435
|
+
...workers.map(worker => worker.lastReport?.seq ?? 0),
|
|
436
|
+
events.findLast(event => workerNames.has(event.author) && event.kind !== 'brief')?.seq ?? 0,
|
|
437
|
+
);
|
|
438
|
+
return lastSummarySeq >= lastWorkerSeq;
|
|
439
|
+
}
|
|
440
|
+
|
|
312
441
|
export function teamPhase(team) {
|
|
313
442
|
if (team.paused) return 'paused';
|
|
314
443
|
const members = team.members.filter(member => member.status !== 'retired');
|
|
315
444
|
if (!members.length && team.members.length) return 'retired';
|
|
316
445
|
const coordinator = members.find(member => member.role === 'coordinator');
|
|
317
|
-
const
|
|
318
|
-
const
|
|
446
|
+
const workers = members.filter(isWorker);
|
|
447
|
+
const round = coordinator && completedWorkerRound(workers);
|
|
448
|
+
const summaryPosted = coordinator && (!workers.length || hasCoordinatorSummary(team, coordinator, workers));
|
|
449
|
+
const summaryPending = Boolean(round && coordinator.lastRound !== round && !summaryPosted);
|
|
450
|
+
const coordinatorCanSummarize = coordinator && !['failed', 'quota'].includes(coordinator.status);
|
|
319
451
|
if (!summaryPending && members.every(member => member.status === 'done' ||
|
|
320
|
-
(member === coordinator && member.status === 'waiting' &&
|
|
452
|
+
(member === coordinator && member.status === 'waiting' &&
|
|
453
|
+
!pendingWaitFor(team, member).length && !(member.inbox?.some(post => post.addressed))))) return 'done';
|
|
321
454
|
if (members.some(member => member.status === 'working')) return 'working';
|
|
322
455
|
if (team.turns >= team.turnLimit) return 'budget';
|
|
323
|
-
if (members.some(member => member.status === 'queued')) return 'queued';
|
|
456
|
+
if (members.some(member => member.status === 'queued') || (summaryPending && coordinatorCanSummarize)) return 'queued';
|
|
324
457
|
return 'stalled';
|
|
325
458
|
}
|
|
326
459
|
|
|
@@ -445,6 +578,7 @@ export class TeamBoard {
|
|
|
445
578
|
`);
|
|
446
579
|
this.read = this.db.prepare('SELECT value FROM teams WHERE id = ?');
|
|
447
580
|
this.write = this.db.prepare('INSERT INTO teams VALUES (?, ?) ON CONFLICT(id) DO UPDATE SET value = excluded.value');
|
|
581
|
+
this.readPost = this.db.prepare('SELECT value FROM posts WHERE team_id = ? AND seq = ?');
|
|
448
582
|
this.writePost = this.db.prepare('INSERT INTO posts VALUES (?, ?, ?) ON CONFLICT(team_id,seq) DO NOTHING');
|
|
449
583
|
this.bounds = this.db.prepare('SELECT coalesce(min(seq),0) AS earliest, coalesce(max(seq),0) AS head FROM posts WHERE team_id = ?');
|
|
450
584
|
const filter = " AND (? IS NULL OR COALESCE(json_extract(posts.value,'$.channel'),'main') IN (SELECT value FROM json_each(?)))" +
|
|
@@ -527,9 +661,11 @@ export class TeamBoard {
|
|
|
527
661
|
if (members.some(member => member.worktree) && !worktreeSource) throw Error('A Git workspace is required for worktrees.');
|
|
528
662
|
|
|
529
663
|
const task = text(input.task, 'Task', 8000);
|
|
664
|
+
const goalLine = optionalText(input.goalLine, 'Goal line', 140);
|
|
530
665
|
const threads = normalizeThreads(input.threads, members);
|
|
531
666
|
const team = {
|
|
532
667
|
id: randomUUID(), host: this.host, cwd, task, title: text(input.title ?? task.slice(0, 95), 'Title', 95),
|
|
668
|
+
...(goalLine ? {goalLine} : {}),
|
|
533
669
|
...(parent ? {parentSessionId: parent} : {}),
|
|
534
670
|
...(input.model ? {model: text(input.model, 'Model', 100)} : {}),
|
|
535
671
|
effort: reasoningEffort(input.effort),
|
|
@@ -700,14 +836,51 @@ export class TeamBoard {
|
|
|
700
836
|
return team;
|
|
701
837
|
}
|
|
702
838
|
|
|
703
|
-
setTeamPlan(id,
|
|
839
|
+
setTeamPlan(id, plan, actor) {
|
|
704
840
|
const team = this.get(id);
|
|
705
841
|
if (actor && this.peerMember(team, actor).role !== 'coordinator') {
|
|
706
842
|
throw Error('Only the user or coordinator can update outcome threads.');
|
|
707
843
|
}
|
|
708
|
-
const
|
|
709
|
-
if (
|
|
710
|
-
|
|
844
|
+
const spec = plan === undefined ? {threads: []} : Array.isArray(plan) ? {threads: plan} : plan;
|
|
845
|
+
if (!spec || typeof spec !== 'object' || Array.isArray(spec)) {
|
|
846
|
+
throw Error('Team plan must be an object or a list of outcome threads.');
|
|
847
|
+
}
|
|
848
|
+
const {goalLine, tasks, threads} = spec;
|
|
849
|
+
if (goalLine === undefined && tasks === undefined && threads === undefined) {
|
|
850
|
+
throw Error('Specify goalLine, tasks, or threads to update the team plan.');
|
|
851
|
+
}
|
|
852
|
+
if (goalLine !== undefined) {
|
|
853
|
+
const next = optionalText(goalLine, 'Goal line', 140);
|
|
854
|
+
if (next) team.goalLine = next;
|
|
855
|
+
else delete team.goalLine;
|
|
856
|
+
}
|
|
857
|
+
if (tasks !== undefined && tasks !== null) {
|
|
858
|
+
let entries;
|
|
859
|
+
if (Array.isArray(tasks)) {
|
|
860
|
+
entries = tasks.map(entry => {
|
|
861
|
+
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
|
|
862
|
+
throw Error('Each task label entry must be a {member, label} object.');
|
|
863
|
+
}
|
|
864
|
+
return [entry.member, entry.label];
|
|
865
|
+
});
|
|
866
|
+
} else if (typeof tasks === 'object') {
|
|
867
|
+
entries = Object.entries(tasks);
|
|
868
|
+
} else {
|
|
869
|
+
throw Error('Task labels must be a member map or a list of {member, label} entries.');
|
|
870
|
+
}
|
|
871
|
+
for (const [rawName, rawLabel] of entries) {
|
|
872
|
+
const name = normalizeTarget(text(rawName, 'Member name', 30));
|
|
873
|
+
const target = this.liveMember(team, name);
|
|
874
|
+
const label = optionalText(rawLabel, 'Task label', 96);
|
|
875
|
+
if (label) target.taskLabel = label;
|
|
876
|
+
else delete target.taskLabel;
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
if (threads !== undefined) {
|
|
880
|
+
const normalized = normalizeThreads(threads, team.members);
|
|
881
|
+
if (normalized?.length) team.threads = normalized;
|
|
882
|
+
else delete team.threads;
|
|
883
|
+
}
|
|
711
884
|
this.save(team);
|
|
712
885
|
return team;
|
|
713
886
|
}
|
|
@@ -919,6 +1092,12 @@ export class TeamBoard {
|
|
|
919
1092
|
const event = {seq: (team.events.at(-1)?.seq ?? 0) + 1, time: new Date().toISOString(), kind, author, text: body, targets,channel};
|
|
920
1093
|
team.events.push(event);
|
|
921
1094
|
if (team.events.length > 300) team.events.shift();
|
|
1095
|
+
const shots = extractScreenshots(event);
|
|
1096
|
+
if (shots.length) {
|
|
1097
|
+
team.screenshots ??= [];
|
|
1098
|
+
team.screenshots.push(...shots.map(publicScreenshot));
|
|
1099
|
+
if (team.screenshots.length > 200) team.screenshots.splice(0, team.screenshots.length - 200);
|
|
1100
|
+
}
|
|
922
1101
|
return event;
|
|
923
1102
|
}
|
|
924
1103
|
|