@ngockhoale/ckit 0.2.10 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/gui/server.js +122 -68
- package/dist/src/team/config.js +2 -0
- package/dist/src/team/engine.d.ts +6 -0
- package/dist/src/team/engine.js +118 -2
- package/dist/src/team/runners.d.ts +4 -1
- package/dist/src/team/runners.js +2 -2
- package/dist/src/team/sessions/claude.d.ts +19 -0
- package/dist/src/team/sessions/claude.js +84 -0
- package/dist/src/team/sessions/codex.d.ts +23 -0
- package/dist/src/team/sessions/codex.js +130 -0
- package/dist/src/team/sessions/fallback.d.ts +4 -0
- package/dist/src/team/sessions/fallback.js +33 -0
- package/dist/src/team/sessions/index.d.ts +6 -0
- package/dist/src/team/sessions/index.js +38 -0
- package/dist/src/team/sessions/omp.d.ts +20 -0
- package/dist/src/team/sessions/omp.js +75 -0
- package/dist/src/team/sessions/proc.d.ts +62 -0
- package/dist/src/team/sessions/proc.js +188 -0
- package/dist/src/team/sessions/types.d.ts +43 -0
- package/dist/src/team/sessions/types.js +2 -0
- package/dist/src/team/types.d.ts +6 -0
- package/dist/src/team/workspace-lease.d.ts +21 -0
- package/dist/src/team/workspace-lease.js +72 -0
- package/dist/src/tui/team/model.js +1 -0
- package/gui/app.css +12 -0
- package/gui/app.js +76 -13
- package/gui/index.html +2 -1
- package/gui/network.js +5 -1
- package/package.json +1 -1
package/dist/src/gui/server.js
CHANGED
|
@@ -100,27 +100,55 @@ export async function startGuiServer(opts) {
|
|
|
100
100
|
const root = opts.projectRoot;
|
|
101
101
|
const token = opts.token !== undefined && /^[A-Za-z0-9_-]{16,128}$/.test(opts.token) ? opts.token : randomBytes(24).toString('hex');
|
|
102
102
|
let port = 0;
|
|
103
|
-
|
|
103
|
+
// Real runs by runId (several can be live at once); at most one playback; `focus` = most recently started or replayed.
|
|
104
|
+
const runs = new Map();
|
|
105
|
+
let playback = null, focus = null;
|
|
104
106
|
const sse = new Set();
|
|
105
|
-
|
|
107
|
+
const MAX_LIVE_RUNS = 8, MAX_TRACKED_RUNS = 24;
|
|
106
108
|
const sendEvent = (res, e) => { res.write(`data: ${JSON.stringify(e)}\n\n`); };
|
|
109
|
+
const toAll = (t, write) => { for (const r of [...sse, ...t.listeners]) {
|
|
110
|
+
try {
|
|
111
|
+
write(r);
|
|
112
|
+
}
|
|
113
|
+
catch { /* dead socket */ }
|
|
114
|
+
} };
|
|
107
115
|
const attach = (handle, goal, simulated, replay) => {
|
|
108
|
-
unsub
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
116
|
+
const cur = { handle, goal, simulated, startedAt: new Date().toISOString(), outcome: null, ...(replay ? { replay } : {}), unsub: () => undefined, listeners: new Set() };
|
|
117
|
+
if (replay) {
|
|
118
|
+
playback?.unsub();
|
|
119
|
+
playback = cur;
|
|
120
|
+
}
|
|
121
|
+
else {
|
|
122
|
+
runs.set(handle.runId, cur);
|
|
123
|
+
for (const [id, t] of runs) {
|
|
124
|
+
if (runs.size <= MAX_TRACKED_RUNS)
|
|
125
|
+
break;
|
|
126
|
+
if (t.outcome !== null && t !== focus)
|
|
127
|
+
runs.delete(id);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
focus = cur;
|
|
131
|
+
for (const r of sse) {
|
|
114
132
|
try {
|
|
115
|
-
|
|
133
|
+
r.write(`event: runstarted\ndata: ${JSON.stringify({ runId: handle.runId })}\n\n`);
|
|
116
134
|
}
|
|
117
135
|
catch { /* dead socket */ }
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
|
|
136
|
+
}
|
|
137
|
+
cur.unsub = handle.subscribe(e => toAll(cur, r => sendEvent(r, e)));
|
|
138
|
+
toAll(cur, r => r.write('event: ready\ndata: {}\n\n'));
|
|
121
139
|
void handle.done.then(o => { cur.outcome = o; });
|
|
140
|
+
return cur;
|
|
122
141
|
};
|
|
123
|
-
const
|
|
142
|
+
const isLive = (t) => !!t && t.outcome === null;
|
|
143
|
+
const liveReal = () => [...runs.values()].filter(t => t.outcome === null);
|
|
144
|
+
/** 'current' = focus run; otherwise a tracked real run or the playback with that id. */
|
|
145
|
+
const trackedOf = (id) => id === 'current' ? focus : runs.get(id) ?? (playback?.handle.runId === id ? playback : null);
|
|
146
|
+
const view = (t) => ({ runId: t.handle.runId, goal: t.goal, simulated: t.simulated, startedAt: t.startedAt, running: t.outcome === null, outcome: t.outcome, ...(t.replay ? { replay: t.replay } : {}) });
|
|
147
|
+
/** Replays history to one client only; live events arrive through the shared fan-out. */
|
|
148
|
+
const replayTo = (t, res) => { t.handle.subscribe(e => { try {
|
|
149
|
+
sendEvent(res, e);
|
|
150
|
+
}
|
|
151
|
+
catch { /* closed */ } })(); };
|
|
124
152
|
const loadConfig = () => { const r = loadTeamConfig(root); return r.ok ? r.config : defaultTeamConfig(); };
|
|
125
153
|
const publicConfig = (c) => {
|
|
126
154
|
const dec = (a) => ({ ...a, hasKey: a.apiKeyRef ? hasSecret(a.apiKeyRef) : false });
|
|
@@ -128,7 +156,7 @@ export async function startGuiServer(opts) {
|
|
|
128
156
|
};
|
|
129
157
|
const runDirOf = (id) => {
|
|
130
158
|
if (id === 'current')
|
|
131
|
-
return
|
|
159
|
+
return focus?.handle.runDir ?? null;
|
|
132
160
|
if (!RUN_ID_RE.test(id))
|
|
133
161
|
return null;
|
|
134
162
|
return listTeamRuns(root).find(r => r.runId === id)?.runDir ?? null;
|
|
@@ -172,15 +200,28 @@ export async function startGuiServer(opts) {
|
|
|
172
200
|
}
|
|
173
201
|
catch { /* closed */ } }, 15_000);
|
|
174
202
|
req.on('close', () => { clearInterval(hb); sse.delete(res); });
|
|
175
|
-
if (
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
203
|
+
if (focus)
|
|
204
|
+
replayTo(focus, res);
|
|
205
|
+
res.write('event: ready\ndata: {}\n\n');
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
const evs = /^\/api\/runs\/([^/]+)\/events$/.exec(p);
|
|
209
|
+
if (m === 'GET' && evs) {
|
|
210
|
+
const id = decodeURIComponent(evs[1]);
|
|
211
|
+
if (id !== 'current' && !RUN_ID_RE.test(id))
|
|
212
|
+
return json(res, 404, { error: 'unknown run' });
|
|
213
|
+
const t = trackedOf(id);
|
|
214
|
+
if (!t)
|
|
215
|
+
return json(res, 404, { error: 'unknown run' });
|
|
216
|
+
res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' });
|
|
217
|
+
res.write('retry: 2000\n\n');
|
|
218
|
+
t.listeners.add(res);
|
|
219
|
+
const hb = setInterval(() => { try {
|
|
220
|
+
res.write(': hb\n\n');
|
|
183
221
|
}
|
|
222
|
+
catch { /* closed */ } }, 15_000);
|
|
223
|
+
req.on('close', () => { clearInterval(hb); t.listeners.delete(res); });
|
|
224
|
+
replayTo(t, res);
|
|
184
225
|
res.write('event: ready\ndata: {}\n\n');
|
|
185
226
|
return;
|
|
186
227
|
}
|
|
@@ -190,7 +231,7 @@ export async function startGuiServer(opts) {
|
|
|
190
231
|
const c = loadConfig();
|
|
191
232
|
const configured = allAgents(c).some(a => a.cli !== 'auto' && a.cli !== 'simulated');
|
|
192
233
|
return json(res, 200, { config: publicConfig(c), configExists: existsSync(teamConfigPath(root)), projectRoot: root, version: START_VERSION, diskVersion: packageVersion(), simulatedDefault: !configured,
|
|
193
|
-
run:
|
|
234
|
+
run: focus ? view(focus) : null, runs: [...runs.values(), ...(playback ? [playback] : [])].map(view) });
|
|
194
235
|
}
|
|
195
236
|
if (m === 'PUT' && p === '/api/config') {
|
|
196
237
|
const body = await readBody(req);
|
|
@@ -248,7 +289,7 @@ export async function startGuiServer(opts) {
|
|
|
248
289
|
return { runId: r.runId, goal, outcome, lane: lane && lane.type === 'lane.chosen' ? lane.name : null, waiting: last?.type === 'run.waiting', startedAt: first?.at ?? null, durationMs, simulated: first?.type === 'run.started' ? first.simulated : false };
|
|
249
290
|
});
|
|
250
291
|
// The run on screen right now (a real run or a playback), so the list can mark its row and offer Stop.
|
|
251
|
-
return json(res, 200, { runs, active:
|
|
292
|
+
return json(res, 200, { runs, active: isLive(focus) ? { runId: focus.handle.runId, replay: !!focus.replay, speed: focus.replay?.speed ?? null } : null, live: [...liveReal(), ...(isLive(playback) ? [playback] : [])].map(t => t.handle.runId) });
|
|
252
293
|
}
|
|
253
294
|
if (m === 'POST' && p === '/api/uploads') {
|
|
254
295
|
// Raw file body (any type), name in ?name=. Streamed to disk, never parsed or executed here.
|
|
@@ -279,8 +320,8 @@ export async function startGuiServer(opts) {
|
|
|
279
320
|
return json(res, 200, { ok: true });
|
|
280
321
|
}
|
|
281
322
|
if (m === 'POST' && p === '/api/runs') {
|
|
282
|
-
if (
|
|
283
|
-
return json(res,
|
|
323
|
+
if (liveReal().length >= MAX_LIVE_RUNS)
|
|
324
|
+
return json(res, 429, { error: `too many runs are active (${MAX_LIVE_RUNS}); stop or wait for one to finish` });
|
|
284
325
|
const b = obj(await readBody(req));
|
|
285
326
|
const files = claim(b['attachments']);
|
|
286
327
|
if (files === null)
|
|
@@ -302,14 +343,12 @@ export async function startGuiServer(opts) {
|
|
|
302
343
|
const id = decodeURIComponent(rp[1]);
|
|
303
344
|
if (m === 'POST' && rp[2] === 'replay') {
|
|
304
345
|
// A playback may be replaced by another playback (other run or other speed); a real run is never interrupted this way.
|
|
305
|
-
if (isRunning() && !current?.replay)
|
|
306
|
-
return json(res, 409, { error: 'a run is already active' });
|
|
307
346
|
const dir = runDirOf(id);
|
|
308
347
|
if (!dir || id === 'current')
|
|
309
348
|
return json(res, 404, { error: 'unknown run' });
|
|
310
349
|
const asked = Number(obj(await readBody(req))['speed']), speed = [1, 2, 4].includes(asked) ? asked : 1;
|
|
311
|
-
if (
|
|
312
|
-
|
|
350
|
+
if (isLive(playback))
|
|
351
|
+
playback.handle.stop();
|
|
313
352
|
const handle = replayTeamRun(dir, { speed });
|
|
314
353
|
attach(handle, '(replay)', false, { speed });
|
|
315
354
|
return json(res, 200, { runId: handle.runId, replay: true });
|
|
@@ -383,24 +422,53 @@ export async function startGuiServer(opts) {
|
|
|
383
422
|
}
|
|
384
423
|
if (m === 'GET' && p === '/api/clis')
|
|
385
424
|
return json(res, 200, { clis: detectClis(), configFile: teamConfigPath(root) });
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
return
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
return
|
|
403
|
-
|
|
425
|
+
const act = /^\/api\/runs\/([^/]+)\/(message|proceed|stop)$/.exec(p);
|
|
426
|
+
const actOn = () => {
|
|
427
|
+
if (!act || m !== 'POST')
|
|
428
|
+
return null;
|
|
429
|
+
const id = decodeURIComponent(act[1]);
|
|
430
|
+
if (id !== 'current' && !RUN_ID_RE.test(id)) {
|
|
431
|
+
json(res, 404, { error: 'unknown run' });
|
|
432
|
+
return null;
|
|
433
|
+
}
|
|
434
|
+
const t = trackedOf(id);
|
|
435
|
+
if (!t) {
|
|
436
|
+
json(res, id === 'current' ? 409 : 404, { error: id === 'current' ? 'no active run' : 'unknown run' });
|
|
437
|
+
return null;
|
|
438
|
+
}
|
|
439
|
+
if (!isLive(t)) {
|
|
440
|
+
json(res, 409, { error: 'no active run' });
|
|
441
|
+
return null;
|
|
442
|
+
}
|
|
443
|
+
return { t, kind: act[2] };
|
|
444
|
+
};
|
|
445
|
+
if (act && m === 'POST') {
|
|
446
|
+
const a = actOn();
|
|
447
|
+
if (!a)
|
|
448
|
+
return;
|
|
449
|
+
const { t } = a;
|
|
450
|
+
if (a.kind === 'message') {
|
|
451
|
+
const b = obj(await readBody(req)), text = typeof b['text'] === 'string' ? b['text'] : '', files = claim(b['attachments']);
|
|
452
|
+
if (files === null)
|
|
453
|
+
return json(res, 400, { error: 'unknown attachment; attach the file again' });
|
|
454
|
+
if (!text.trim() && files.length === 0)
|
|
455
|
+
return json(res, 400, { error: 'text required' });
|
|
456
|
+
t.handle.sendToDirector(text.slice(0, 4000), files);
|
|
457
|
+
release(b['attachments']);
|
|
458
|
+
return json(res, 200, { ok: true });
|
|
459
|
+
}
|
|
460
|
+
if (a.kind === 'proceed') {
|
|
461
|
+
if (!t.handle.proceedWithAssumptions)
|
|
462
|
+
return json(res, 409, { error: 'this run cannot proceed with assumptions' });
|
|
463
|
+
t.handle.proceedWithAssumptions();
|
|
464
|
+
return json(res, 200, { ok: true });
|
|
465
|
+
}
|
|
466
|
+
t.handle.stop();
|
|
467
|
+
// A playback has no run.completed of its own when it is cut short, so every open page is told directly.
|
|
468
|
+
if (t.replay) {
|
|
469
|
+
t.outcome = 'stopped';
|
|
470
|
+
toAll(t, r => r.write('event: replaystop\ndata: {}\n\n'));
|
|
471
|
+
}
|
|
404
472
|
return json(res, 200, { ok: true });
|
|
405
473
|
}
|
|
406
474
|
if (m === 'POST' && p === '/api/enhance-prompt') {
|
|
@@ -452,22 +520,6 @@ export async function startGuiServer(opts) {
|
|
|
452
520
|
enhancing = false;
|
|
453
521
|
}
|
|
454
522
|
}
|
|
455
|
-
if (m === 'POST' && p === '/api/runs/current/stop') {
|
|
456
|
-
if (!isRunning() || !current)
|
|
457
|
-
return json(res, 409, { error: 'no active run' });
|
|
458
|
-
current.handle.stop();
|
|
459
|
-
// A playback has no run.completed of its own when it is cut short, so every open page is told directly.
|
|
460
|
-
if (current.replay) {
|
|
461
|
-
current.outcome = 'stopped';
|
|
462
|
-
for (const r of sse) {
|
|
463
|
-
try {
|
|
464
|
-
r.write('event: replaystop\ndata: {}\n\n');
|
|
465
|
-
}
|
|
466
|
-
catch { /* dead socket */ }
|
|
467
|
-
}
|
|
468
|
-
}
|
|
469
|
-
return json(res, 200, { ok: true });
|
|
470
|
-
}
|
|
471
523
|
json(res, 404, { error: 'not found' });
|
|
472
524
|
}
|
|
473
525
|
function serveStatic(res, pathname) {
|
|
@@ -542,11 +594,13 @@ export async function startGuiServer(opts) {
|
|
|
542
594
|
return {
|
|
543
595
|
url,
|
|
544
596
|
close: () => new Promise(done => {
|
|
545
|
-
|
|
546
|
-
|
|
597
|
+
for (const t of [...runs.values(), ...(playback ? [playback] : [])]) {
|
|
598
|
+
try {
|
|
599
|
+
t.handle.stop();
|
|
600
|
+
}
|
|
601
|
+
catch { /* ignore */ }
|
|
602
|
+
t.unsub();
|
|
547
603
|
}
|
|
548
|
-
catch { /* ignore */ }
|
|
549
|
-
unsub?.();
|
|
550
604
|
for (const r of sse)
|
|
551
605
|
r.end();
|
|
552
606
|
release([...uploads.keys()]);
|
package/dist/src/team/config.js
CHANGED
|
@@ -12,6 +12,8 @@ export function defaultTeamConfig() {
|
|
|
12
12
|
implement: [agent('dev-claude', 'Dev · Claude', 'implement', 'claude-code', 'write')],
|
|
13
13
|
qc: [agent('qc-codex-1', 'QC · Codex 1', 'qc', 'codex', 'read'), agent('qc-codex-2', 'QC · Codex 2', 'qc', 'codex', 'read')],
|
|
14
14
|
},
|
|
15
|
+
extraTeams: [{ id: 'test', name: 'Tester', mission: "Run the project's real checks (build, unit/integration tests, and a quick manual check of the changed behaviour); write missing tests for the acceptance criteria when needed; report PASS/FAIL with the exact commands and output summary.", agents: [agent('tester-codex', 'Tester · Codex', 'test', 'codex', 'write')] }],
|
|
16
|
+
order: ['ba', 'implement', 'test', 'qc'],
|
|
15
17
|
limits: { baRounds: 2, qcLoops: 2, agentTimeoutMs: 900000 },
|
|
16
18
|
};
|
|
17
19
|
}
|
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import { type AttachmentInput } from './attachments.js';
|
|
2
|
+
import { type OpenSession } from './sessions/index.js';
|
|
3
|
+
import { type WorkspaceLease } from './workspace-lease.js';
|
|
2
4
|
import { type AgentRunner } from './runners.js';
|
|
3
5
|
import { type TeamConfig, type TeamRunHandle } from './types.js';
|
|
4
6
|
export interface StartTeamRunOptions {
|
|
7
|
+
/** Persistent-session factory (default: native drivers for codex/claude-code/omp). Tests inject fakes. Ignored when `runner` is set or the run is simulated. */
|
|
8
|
+
readonly openSession?: OpenSession;
|
|
5
9
|
readonly projectRoot: string;
|
|
6
10
|
readonly goal: string;
|
|
7
11
|
readonly config: TeamConfig;
|
|
@@ -15,6 +19,8 @@ export interface StartTeamRunOptions {
|
|
|
15
19
|
readonly attachments?: readonly AttachmentInput[];
|
|
16
20
|
/** Lane id fixed by the owner (only when the config has lanes); absent = the Director decides. */
|
|
17
21
|
readonly lane?: string;
|
|
22
|
+
/** Workspace write lease (default: the shared per-project lease). Tests inject their own. */
|
|
23
|
+
readonly lease?: WorkspaceLease;
|
|
18
24
|
}
|
|
19
25
|
/** Pure rule-based owner-chat decision (director cli 'auto', and the fallback for model directors). */
|
|
20
26
|
export declare function ruleDecision(text: string): {
|
package/dist/src/team/engine.js
CHANGED
|
@@ -4,6 +4,8 @@ import { attachmentLines, attachmentPromptBlock, storeAttachments } from './atta
|
|
|
4
4
|
import { readSecret } from './secrets.js';
|
|
5
5
|
import { createCappedSink, createTeamJournal } from './journal.js';
|
|
6
6
|
import { readTeamJournal } from './journal.js';
|
|
7
|
+
import { openSession as defaultOpenSession, sessionsEnabled } from './sessions/index.js';
|
|
8
|
+
import { otherRunsNote, workspaceLeaseFor } from './workspace-lease.js';
|
|
7
9
|
import { advisorKeyOf, createSimulatedRunner, dispatchRunner, simHeader } from './runners.js';
|
|
8
10
|
import { DEFAULT_MISSIONS, allAgentsOf, effectiveOrder } from './types.js';
|
|
9
11
|
/** Every secret value the agents may touch (stored apiKeyRefs + CKit advisor key): always redacted from journal/artifacts. */
|
|
@@ -182,6 +184,7 @@ export function startTeamRun(opts) {
|
|
|
182
184
|
return;
|
|
183
185
|
emit({ type: 'run.completed', outcome, report }); // emitted while !finished (guard allows run.completed anyway)
|
|
184
186
|
finished = true;
|
|
187
|
+
closeSessions();
|
|
185
188
|
journal.writeArtifact('report.md', report);
|
|
186
189
|
resolveDone(outcome);
|
|
187
190
|
};
|
|
@@ -240,6 +243,65 @@ export function startTeamRun(opts) {
|
|
|
240
243
|
/** Failure text for an agent with extra CLI arguments: name them, so a typo is easy to find. */
|
|
241
244
|
const withArgsNote = (agent, reason) => agent.cliArgs && reason !== 'cancelled' && agent.cli !== 'api' && agent.cli !== 'auto' && agent.cli !== 'simulated' ? `${reason}\nExtra CLI arguments are set for this agent: ${agent.cliArgs}. If the CLI rejected an option, fix or clear them in Config (Extra CLI arguments).` : reason;
|
|
242
245
|
const rawSinks = new Map();
|
|
246
|
+
// ---- persistent sessions: one per agent per run, created lazily, closed when the run ends ----
|
|
247
|
+
const useSessions = !simulated && (opts.openSession !== undefined || (!opts.runner && sessionsEnabled()));
|
|
248
|
+
const sessions = new Map(), running = new Map();
|
|
249
|
+
const sessionFor = (agent) => {
|
|
250
|
+
if (!useSessions || simAgent(agent) || agent.cli === 'api' || agent.cli === 'auto')
|
|
251
|
+
return null;
|
|
252
|
+
let s = sessions.get(agent.id);
|
|
253
|
+
if (!s) {
|
|
254
|
+
try {
|
|
255
|
+
s = (opts.openSession ?? defaultOpenSession)(agent, { cwd: opts.projectRoot });
|
|
256
|
+
}
|
|
257
|
+
catch {
|
|
258
|
+
return null;
|
|
259
|
+
}
|
|
260
|
+
sessions.set(agent.id, s);
|
|
261
|
+
}
|
|
262
|
+
return s;
|
|
263
|
+
};
|
|
264
|
+
const dropSession = (agent) => { const s = sessions.get(agent.id); sessions.delete(agent.id); running.delete(agent.id); try {
|
|
265
|
+
s?.close();
|
|
266
|
+
}
|
|
267
|
+
catch { /* already gone */ } };
|
|
268
|
+
const closeSessions = () => { for (const s of sessions.values()) {
|
|
269
|
+
try {
|
|
270
|
+
s.close();
|
|
271
|
+
}
|
|
272
|
+
catch { /* already gone */ }
|
|
273
|
+
} sessions.clear(); running.clear(); };
|
|
274
|
+
/** Live-only partial text (never written to events.jsonl: too chatty). Coalesced to ~250 ms per agent. */
|
|
275
|
+
const deltaBuf = new Map();
|
|
276
|
+
const flushDelta = (agentId) => {
|
|
277
|
+
const b = deltaBuf.get(agentId);
|
|
278
|
+
if (!b)
|
|
279
|
+
return;
|
|
280
|
+
if (b.timer)
|
|
281
|
+
clearTimeout(b.timer);
|
|
282
|
+
deltaBuf.delete(agentId);
|
|
283
|
+
if (!b.text || finished)
|
|
284
|
+
return;
|
|
285
|
+
const e = { seq: history.length ? history[history.length - 1].seq : 0, at: new Date().toISOString(), runId: journal.runId, type: 'agent.delta', agentId, text: journal.redact(b.text) };
|
|
286
|
+
for (const l of [...listeners]) {
|
|
287
|
+
try {
|
|
288
|
+
l(e);
|
|
289
|
+
}
|
|
290
|
+
catch { /* ignore */ }
|
|
291
|
+
}
|
|
292
|
+
};
|
|
293
|
+
const pushDelta = (agentId, text) => {
|
|
294
|
+
let b = deltaBuf.get(agentId);
|
|
295
|
+
if (!b) {
|
|
296
|
+
b = { text: '', timer: null };
|
|
297
|
+
deltaBuf.set(agentId, b);
|
|
298
|
+
}
|
|
299
|
+
b.text += text;
|
|
300
|
+
if (!b.timer) {
|
|
301
|
+
b.timer = setTimeout(() => flushDelta(agentId), 250);
|
|
302
|
+
b.timer.unref?.();
|
|
303
|
+
}
|
|
304
|
+
};
|
|
243
305
|
const RAW_CAP = 5 * 1024 * 1024;
|
|
244
306
|
/** Appends to agents/<id>.log; a logging failure never breaks a run. */
|
|
245
307
|
const agentLog = (agent, text) => { try {
|
|
@@ -259,7 +321,30 @@ export function startTeamRun(opts) {
|
|
|
259
321
|
};
|
|
260
322
|
const logPath = (agent) => `.ckit/team/runs/${journal.runId}/agents/${agent.id}.log`;
|
|
261
323
|
/** Runs one agent turn through the runner, wiring activity/step/subagent events. Never throws. */
|
|
324
|
+
const lease = opts.lease ?? workspaceLeaseFor(opts.projectRoot), startedMs = Date.now();
|
|
325
|
+
/** Write turns hold the workspace lease (FIFO across runs); every turn is told when other runs changed files meanwhile. */
|
|
262
326
|
async function callRunner(agent, prompt, first, last) {
|
|
327
|
+
let release = null, waitedNoted = false;
|
|
328
|
+
if (agent.access === 'write') {
|
|
329
|
+
try {
|
|
330
|
+
release = await lease.acquire(journal.runId, agent.id, abort.signal, h => { if (!waitedNoted) {
|
|
331
|
+
waitedNoted = true;
|
|
332
|
+
emit({ type: 'agent.activity', agentId: agent.id, text: oneLine(`Waiting for the workspace: run ${h.runId} (${h.agentId}) is changing files`, 160) });
|
|
333
|
+
} });
|
|
334
|
+
}
|
|
335
|
+
catch {
|
|
336
|
+
return { ok: false, reason: 'cancelled' };
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
try {
|
|
340
|
+
const others = lease.othersSince(journal.runId, startedMs);
|
|
341
|
+
return await callRunnerLeased(agent, others.length ? `${otherRunsNote(others)}\n\n${prompt}` : prompt, first, last);
|
|
342
|
+
}
|
|
343
|
+
finally {
|
|
344
|
+
release?.();
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
async function callRunnerLeased(agent, prompt, first, last) {
|
|
263
348
|
const t0 = Date.now(), stamp = () => new Date().toISOString();
|
|
264
349
|
agentLog(agent, `===== ${stamp()} agent ${agent.id} (${agent.name}) =====\ncli: ${agent.cli}\nmodel: ${agent.model ?? '(default)'}\naccess: ${agent.access}\ntask: ${first}\n----- PROMPT -----\n${prompt}\n----- EVENTS -----\n`);
|
|
265
350
|
const done = (res) => {
|
|
@@ -280,7 +365,7 @@ export function startTeamRun(opts) {
|
|
|
280
365
|
step(first);
|
|
281
366
|
try {
|
|
282
367
|
const raw = rawSink(agent);
|
|
283
|
-
const
|
|
368
|
+
const runOpts = {
|
|
284
369
|
cwd: opts.projectRoot, timeoutMs: config.limits.agentTimeoutMs, signal: abort.signal, ...(atts.length ? { images: images() } : {}),
|
|
285
370
|
onRaw: (stream, line) => raw(`[${stamp()}] ${stream}: ${line.endsWith('\n') ? line : `${line}\n`}`),
|
|
286
371
|
onActivity: text => { agentLog(agent, `[${stamp()}] activity: ${oneLine(text, 400)}\n`); emit({ type: 'agent.activity', agentId: agent.id, text: oneLine(text, 160) }); const l = own ? null : stepOf(text); if (l)
|
|
@@ -292,7 +377,26 @@ export function startTeamRun(opts) {
|
|
|
292
377
|
: e.type === 'activity' ? { type: 'subagent.activity', agentId: agent.id, childId: e.childId, text: oneLine(e.text, 160) }
|
|
293
378
|
: { type: 'subagent.finished', agentId: agent.id, childId: e.childId, ok: e.ok, summary: oneLine(e.summary, 200) });
|
|
294
379
|
},
|
|
295
|
-
}
|
|
380
|
+
};
|
|
381
|
+
const sess = sessionFor(agent);
|
|
382
|
+
let res;
|
|
383
|
+
if (!sess)
|
|
384
|
+
res = await runner(agent, prompt, runOpts);
|
|
385
|
+
else {
|
|
386
|
+
running.set(agent.id, sess);
|
|
387
|
+
try {
|
|
388
|
+
res = await sess.send(prompt, { ...runOpts, onDelta: t => pushDelta(agent.id, t) });
|
|
389
|
+
}
|
|
390
|
+
finally {
|
|
391
|
+
flushDelta(agent.id);
|
|
392
|
+
running.delete(agent.id);
|
|
393
|
+
}
|
|
394
|
+
if (!res.ok && res.transport && !abort.signal.aborted) {
|
|
395
|
+
dropSession(agent);
|
|
396
|
+
runOpts.onActivity?.(`Persistent session failed (${oneLine(res.reason, 100)}); retrying this turn with a fresh one-shot process`);
|
|
397
|
+
res = await runner(agent, prompt, runOpts);
|
|
398
|
+
}
|
|
399
|
+
}
|
|
296
400
|
if (res.ok && !own)
|
|
297
401
|
step(last);
|
|
298
402
|
return done(res.ok ? res : { ok: false, reason: withArgsNote(agent, res.reason) });
|
|
@@ -714,6 +818,12 @@ export function startTeamRun(opts) {
|
|
|
714
818
|
const dflt = { decision: 'accept', dispatch: '', said: '', reason: '' };
|
|
715
819
|
if (!modelDirector())
|
|
716
820
|
return dflt;
|
|
821
|
+
const ho = handoffs.get(id), ids = new Set(agentsOf(id).map(x => x.id));
|
|
822
|
+
const clean = !!ho && /^\(?(nothing|none|n\/a|no open (questions|items|issues))\.?\)?$/i.test(ho.open.trim()) && !inbox.length && !history.some(e => e.type === 'agent.failed' && ids.has(e.agentId));
|
|
823
|
+
if (clean) {
|
|
824
|
+
emit({ type: 'director.decision', decision: 'continue', note: 'auto: clean handoff' });
|
|
825
|
+
return dflt;
|
|
826
|
+
} // nothing open: skip the Director model call
|
|
717
827
|
const ask = (extra, again) => directorAsk(`checkpoint ${teamName(id)}`, `${role(config.director, `You are the Director. The ${teamName(id)} team reported to you. Check the report against the owner goal and your brief, then decide. Reply with a line exactly "CHECKPOINT: ACCEPT" followed by a section "DISPATCH:" with the instructions for the ${teamName(nextId)} team, or a line exactly "CHECKPOINT: RETURN" and a line "RETURN REASON: <what the ${teamName(id)} team must fix>".${again ? '' : ' You may first gather context from a teammate agent (read-only) with up to 2 lines "CONSULT <agent id>: <question>"; then you are asked again.'} Do not change any file.`, true)}\nTEAM ROSTER (flow order):\n${rosterText()}\nORIGINAL GOAL: ${oneLine(goal, 2000)}\n${common()}\nYOUR BRIEF FOR ${teamName(id).toUpperCase()}:\n${briefOf(id)}\n\nREPORT OF THE ${teamName(id).toUpperCase()} TEAM:\n${clip(report, 6000)}\n\nYOUR BRIEF FOR ${teamName(nextId).toUpperCase()} (next team):\n${briefOf(nextId)}${extra}`);
|
|
718
828
|
let t = await ask('', false);
|
|
719
829
|
if (t === null)
|
|
@@ -925,6 +1035,12 @@ export function startTeamRun(opts) {
|
|
|
925
1035
|
w.wake({ how: 'answer', text: added.length ? `${text} [owner attached: ${added.map(a => a.path).join(', ')}]` : text });
|
|
926
1036
|
return;
|
|
927
1037
|
}
|
|
1038
|
+
for (const sess of running.values()) {
|
|
1039
|
+
try {
|
|
1040
|
+
sess.steer(text);
|
|
1041
|
+
}
|
|
1042
|
+
catch { /* steering is best effort */ }
|
|
1043
|
+
}
|
|
928
1044
|
inbox.push(added.length ? `${text} [owner attached: ${added.map(a => a.path).join(', ')}]` : text);
|
|
929
1045
|
}, () => doStop('Stopped from the console.'), () => { const w = waiting; if (w && w.assumptions)
|
|
930
1046
|
w.wake({ how: 'proceed', text: '' }); });
|
|
@@ -37,7 +37,8 @@ export type AgentRunResult = {
|
|
|
37
37
|
readonly tokens: number | null;
|
|
38
38
|
} | {
|
|
39
39
|
readonly ok: false;
|
|
40
|
-
readonly reason: string;
|
|
40
|
+
readonly reason: string; /** session driver only: process/protocol failure (not a model, timeout or cancel outcome); the engine may retry the turn via the per-turn runner */
|
|
41
|
+
readonly transport?: boolean;
|
|
41
42
|
};
|
|
42
43
|
export type AgentRunner = (agent: AgentConfig, prompt: string, opts: AgentRunOptions) => Promise<AgentRunResult>;
|
|
43
44
|
/** CKit advisor key to keep away from workers. The workspace may be a sub-folder of the repository that holds the CKit config, so the enclosing project is checked too. */
|
|
@@ -50,6 +51,7 @@ export interface CodexFrameInfo {
|
|
|
50
51
|
}
|
|
51
52
|
/** Pure: one parsed `codex exec --json` frame -> activity line / final-message candidate / token usage. `error` items are warnings, not fatal. */
|
|
52
53
|
export declare function parseCodexFrame(frame: unknown): CodexFrameInfo;
|
|
54
|
+
export declare function findOnPath(name: string, env: Readonly<Record<string, string | undefined>>): string | null;
|
|
53
55
|
export declare function codexArgs(agent: AgentConfig, cwd: string, prompt: string, images?: readonly string[]): string[];
|
|
54
56
|
/**
|
|
55
57
|
* Codex worker env. Same boundary as the other workers, with one documented exemption (mirrors the claude-code allowlist): a variable that
|
|
@@ -58,6 +60,7 @@ export declare function codexArgs(agent: AgentConfig, cwd: string, prompt: strin
|
|
|
58
60
|
* same gateway, not that CKit copied the advisor key. Values that merely contain the key, and every other name, stay withheld.
|
|
59
61
|
*/
|
|
60
62
|
export declare function codexWorkerEnv(processEnv: Readonly<Record<string, string | undefined>>, advisorKey: string, configToml: string): WorkerEnvPolicy;
|
|
63
|
+
export declare const codexConfigText: (env: Readonly<Record<string, string | undefined>>) => string;
|
|
61
64
|
export declare function runCodex(agent: AgentConfig, prompt: string, opts: AgentRunOptions): Promise<AgentRunResult>;
|
|
62
65
|
/** Pure: claude stream-json frame -> short activity lines. */
|
|
63
66
|
export declare function claudeFrameActivity(frame: unknown): string[];
|
package/dist/src/team/runners.js
CHANGED
|
@@ -60,7 +60,7 @@ export function parseCodexFrame(frame) {
|
|
|
60
60
|
return { activity: oneLine(`warning: ${str(it['message'])}`), error: str(it['message']) };
|
|
61
61
|
return {};
|
|
62
62
|
}
|
|
63
|
-
function findOnPath(name, env) {
|
|
63
|
+
export function findOnPath(name, env) {
|
|
64
64
|
for (const dir of (env['PATH'] ?? '').split(delimiter).filter(Boolean)) {
|
|
65
65
|
if (!isAbsolute(dir))
|
|
66
66
|
continue;
|
|
@@ -98,7 +98,7 @@ export function codexWorkerEnv(processEnv, advisorKey, configToml) {
|
|
|
98
98
|
});
|
|
99
99
|
return { env, withheld, workerAuth: policy.workerAuth };
|
|
100
100
|
}
|
|
101
|
-
const codexConfigText = (env) => {
|
|
101
|
+
export const codexConfigText = (env) => {
|
|
102
102
|
try {
|
|
103
103
|
return readFileSync(join(env['CODEX_HOME'] || join(homedir(), '.codex'), 'config.toml'), 'utf8');
|
|
104
104
|
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { AgentConfig } from '../types.js';
|
|
2
|
+
import { NativeSession } from './proc.js';
|
|
3
|
+
import type { SessionCommand } from './types.js';
|
|
4
|
+
export declare function claudeSessionArgs(agent: AgentConfig, sessionId: string): string[];
|
|
5
|
+
export declare class ClaudeSession extends NativeSession {
|
|
6
|
+
private readonly agent;
|
|
7
|
+
private readonly cmd;
|
|
8
|
+
protected readonly label = "claude";
|
|
9
|
+
private held;
|
|
10
|
+
private open;
|
|
11
|
+
private seen;
|
|
12
|
+
constructor(agent: AgentConfig, cwd: string, env: Readonly<Record<string, string>>, cmd: (sessionId: string) => SessionCommand, grace: number);
|
|
13
|
+
protected start(): Promise<void>;
|
|
14
|
+
protected begin(prompt: string): void;
|
|
15
|
+
/** claude has no native mid-turn injection: hold the text and prepend it to the next send. */
|
|
16
|
+
steer(text: string): boolean;
|
|
17
|
+
protected interruptTurn(): void;
|
|
18
|
+
protected onLine(line: string): void;
|
|
19
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
// claude driver: ONE long-lived `claude -p --input-format stream-json --output-format stream-json` process per agent.
|
|
2
|
+
// Turns are `user` frames on stdin; a `result` frame closes each turn; text deltas come from `stream_event` frames.
|
|
3
|
+
import { randomUUID } from 'node:crypto';
|
|
4
|
+
import { claudeSubagentObservations } from '../../adapters/launch/executor.js';
|
|
5
|
+
import { claudeFrameActivity, claudeTeamArgs } from '../runners.js';
|
|
6
|
+
import { NativeSession, oneLine } from './proc.js';
|
|
7
|
+
export function claudeSessionArgs(agent, sessionId) {
|
|
8
|
+
const base = ['-p', '--input-format', 'stream-json', '--output-format', 'stream-json', '--verbose', '--include-partial-messages', '--session-id', sessionId,
|
|
9
|
+
...(agent.model ? ['--model', agent.model] : []), ...(agent.access === 'write' ? ['--permission-mode', 'acceptEdits'] : [])];
|
|
10
|
+
return claudeTeamArgs(base, agent);
|
|
11
|
+
}
|
|
12
|
+
export class ClaudeSession extends NativeSession {
|
|
13
|
+
agent;
|
|
14
|
+
cmd;
|
|
15
|
+
label = 'claude';
|
|
16
|
+
held = [];
|
|
17
|
+
open = new Map();
|
|
18
|
+
seen = new Set();
|
|
19
|
+
constructor(agent, cwd, env, cmd, grace) {
|
|
20
|
+
super(cwd, env, grace);
|
|
21
|
+
this.agent = agent;
|
|
22
|
+
this.cmd = cmd;
|
|
23
|
+
this.sessionId = randomUUID();
|
|
24
|
+
}
|
|
25
|
+
async start() { this.spawnLink(this.cmd(this.sessionId)); }
|
|
26
|
+
begin(prompt) {
|
|
27
|
+
const text = this.held.length ? `${this.held.splice(0).map(h => `[Owner guidance sent while you were working] ${h}`).join('\n')}\n\n${prompt}` : prompt;
|
|
28
|
+
if (!this.link?.write({ type: 'user', message: { role: 'user', content: text } }))
|
|
29
|
+
throw new Error('could not write to claude stdin');
|
|
30
|
+
}
|
|
31
|
+
/** claude has no native mid-turn injection: hold the text and prepend it to the next send. */
|
|
32
|
+
steer(text) { if (text.trim())
|
|
33
|
+
this.held.push(text.trim()); return false; }
|
|
34
|
+
interruptTurn() { this.link?.write({ type: 'control_request', request_id: randomUUID(), request: { subtype: 'interrupt' } }); }
|
|
35
|
+
onLine(line) {
|
|
36
|
+
const t = this.turn;
|
|
37
|
+
if (!t || !line.startsWith('{'))
|
|
38
|
+
return;
|
|
39
|
+
let f;
|
|
40
|
+
try {
|
|
41
|
+
f = JSON.parse(line);
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
const opts = t.opts;
|
|
47
|
+
if (f['type'] === 'stream_event') {
|
|
48
|
+
const d = f['event']?.delta;
|
|
49
|
+
if (d?.type === 'text_delta' && typeof d.text === 'string' && !f['parent_tool_use_id'])
|
|
50
|
+
opts.onDelta?.(d.text);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
if (f['type'] === 'assistant' || f['type'] === 'user') {
|
|
54
|
+
for (const o of claudeSubagentObservations(f))
|
|
55
|
+
if (!this.seen.has(o.childId)) {
|
|
56
|
+
this.seen.add(o.childId);
|
|
57
|
+
this.open.set(o.childId, o.description ?? o.subagentType ?? 'subagent');
|
|
58
|
+
opts.onSubagent?.({ type: 'started', childId: o.childId, kind: o.subagentType, task: oneLine(this.open.get(o.childId)) });
|
|
59
|
+
}
|
|
60
|
+
const parent = typeof f['parent_tool_use_id'] === 'string' ? f['parent_tool_use_id'] : '';
|
|
61
|
+
if (parent && this.open.has(parent)) {
|
|
62
|
+
for (const a of claudeFrameActivity(f))
|
|
63
|
+
opts.onSubagent?.({ type: 'activity', childId: parent, text: a });
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
for (const a of claudeFrameActivity(f))
|
|
67
|
+
opts.onActivity?.(a);
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
if (f['type'] === 'result') {
|
|
71
|
+
for (const [childId] of this.open)
|
|
72
|
+
opts.onSubagent?.({ type: 'finished', childId, ok: f['is_error'] !== true, summary: 'finished with the turn' });
|
|
73
|
+
this.open.clear();
|
|
74
|
+
const text = typeof f['result'] === 'string' ? f['result'] : '';
|
|
75
|
+
const u = f['usage'];
|
|
76
|
+
const tokens = u && typeof u.input_tokens === 'number' && typeof u.output_tokens === 'number' ? u.input_tokens + u.output_tokens : null;
|
|
77
|
+
if (f['is_error'] === true)
|
|
78
|
+
this.finishTurn({ ok: false, reason: oneLine(text || String(f['subtype'] ?? 'error'), 200) });
|
|
79
|
+
else
|
|
80
|
+
this.finishTurn(text.trim() ? { ok: true, text, tokens } : { ok: false, reason: 'agent returned no text' });
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
//# sourceMappingURL=claude.js.map
|