@ngockhoale/ckit 0.2.9 → 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.
@@ -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
- let current = null;
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
- let unsub = null;
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
- const cur = { handle, goal, simulated, startedAt: new Date().toISOString(), outcome: null, ...(replay ? { replay } : {}) };
110
- current = cur;
111
- for (const r of sse)
112
- r.write('event: reset\ndata: {}\n\n');
113
- unsub = handle.subscribe(e => { for (const r of sse) {
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
- sendEvent(r, e);
133
+ r.write(`event: runstarted\ndata: ${JSON.stringify({ runId: handle.runId })}\n\n`);
116
134
  }
117
135
  catch { /* dead socket */ }
118
- } });
119
- for (const r of sse)
120
- r.write('event: ready\ndata: {}\n\n');
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 isRunning = () => current !== null && current.outcome === null;
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 current?.handle.runDir ?? null;
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 (current) { // replay history only to this client
176
- const h = current.handle;
177
- let un = null;
178
- un = h.subscribe(e => { try {
179
- sendEvent(res, e);
180
- }
181
- catch { /* closed */ } });
182
- un(); // subscribe replays synchronously; live events arrive through the shared fan-out
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: current ? { runId: current.handle.runId, goal: current.goal, simulated: current.simulated, startedAt: current.startedAt, running: current.outcome === null, outcome: current.outcome, ...(current.replay ? { replay: current.replay } : {}) } : null });
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: isRunning() && current ? { runId: current.handle.runId, replay: !!current.replay, speed: current.replay?.speed ?? null } : null });
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 (isRunning())
283
- return json(res, 409, { error: 'a run is already active' });
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 (isRunning())
312
- current?.handle.stop();
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
- if (m === 'POST' && p === '/api/runs/current/message') {
387
- if (!isRunning() || !current)
388
- return json(res, 409, { error: 'no active run' });
389
- const b = obj(await readBody(req)), t = typeof b['text'] === 'string' ? b['text'] : '', files = claim(b['attachments']);
390
- if (files === null)
391
- return json(res, 400, { error: 'unknown attachment; attach the file again' });
392
- if (!t.trim() && files.length === 0)
393
- return json(res, 400, { error: 'text required' });
394
- current.handle.sendToDirector(t.slice(0, 4000), files);
395
- release(b['attachments']);
396
- return json(res, 200, { ok: true });
397
- }
398
- if (m === 'POST' && p === '/api/runs/current/proceed') {
399
- if (!isRunning() || !current)
400
- return json(res, 409, { error: 'no active run' });
401
- if (!current.handle.proceedWithAssumptions)
402
- return json(res, 409, { error: 'this run cannot proceed with assumptions' });
403
- current.handle.proceedWithAssumptions();
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
- try {
546
- current?.handle.stop();
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()]);
@@ -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): {
@@ -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 res = await runner(agent, prompt, {
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) });
@@ -368,10 +472,17 @@ export function startTeamRun(opts) {
368
472
  if (modelDirector()) {
369
473
  const answered = qaRounds.length ? `\nYOUR EARLIER QUESTIONS AND THE OWNER'S ANSWERS:\n${qaRounds.map((q, i) => `Round ${i + 1} questions:\n${q.questions}\nOwner's answer:\n${q.answer}`).join('\n\n')}\n` : '';
370
474
  const limitNote = forced ? '\nThe owner chose to proceed with your stated assumptions: answer "DECISION: PROCEED" now.' : needRounds >= 3 ? '\nYou already asked 3 times: you must not use NEED INFO again. Choose PROCEED with stated assumptions, or CANNOT DO.' : '';
371
- const t = await directorAsk('intake brief', `${role(config.director, `You are the Director. First triage the owner request, then (only on PROCEED) split it between your teams.\nYour reply must contain exactly one decision line on its own line: "DECISION: PROCEED", "DECISION: NEED INFO" or "DECISION: CANNOT DO".\n- PROCEED: write a short overall summary (scope), an "ASSUMPTIONS:" list when you assumed anything, then one section per listed team, each starting with a line exactly "### TEAM <team id>" followed by: what this team must do for this goal, the expected deliverable, and what is out of scope for it. Assign every part of the goal to exactly one listed team and assign nothing to a team that is not listed.\n- NEED INFO: no team starts. Write a numbered list of at most 5 specific questions, each with why you need it; when sensible add a line "ASSUMPTIONS IF NO ANSWER:" followed by what you would assume.\n- CANNOT DO: write "REASON:" and then "WHAT WOULD WORK:" with 1 to 3 alternatives.\nRules: prefer PROCEED with stated assumptions when the gap is small and a wrong guess is cheap. Use NEED INFO only when a wrong guess wastes work or risks damage. Use CANNOT DO only when no reasonable reading of the request can be achieved with the configured teams, their access and this workspace. Never invent requirements. Never start teams on a request you do not understand. Answer in the owner's language. You may read project files (read only) to decide. Check the work is assignable: changing files needs a team with a write agent.${limitNote}`, true)}\n${accessFacts()}\n${lanes.length ? `LANES (choose exactly one; you may not invent lanes or teams):\n${laneRosterText()}\n${ownerLane ? `The owner FIXED the lane: "${ownerLane.id}". Brief only its teams. You may still answer NEED INFO or CANNOT DO.` : 'On PROCEED you MUST include a line "LANE: <lane id>" and a line "LANE REASON: <one sentence>", and write sections only for the teams of that lane. If no lane fits, answer DECISION: CANNOT DO with the reason "no lane fits" and say which lane would be needed; if the request is unclear between lanes, use NEED INFO.'}` : `TEAM ROSTER (pipeline order):\n${rosterText()}`}\n${common()}${answered}`);
372
- if (t?.trim())
373
- return t;
374
- return `DECISION: PROCEED\n${ruleBrief()}`; // the Director could not answer: carry on with the rule-based brief
475
+ const ask = () => directorAsk('intake brief', `${role(config.director, `You are the Director. First triage the owner request, then (only on PROCEED) split it between your teams.\nYour reply must contain exactly one decision line on its own line: "DECISION: PROCEED", "DECISION: NEED INFO" or "DECISION: CANNOT DO".\n- PROCEED: write a short overall summary (scope), an "ASSUMPTIONS:" list when you assumed anything, then one section per listed team, each starting with a line exactly "### TEAM <team id>" followed by: what this team must do for this goal, the expected deliverable, and what is out of scope for it. Assign every part of the goal to exactly one listed team and assign nothing to a team that is not listed.\n- NEED INFO: no team starts. Write a numbered list of at most 5 specific questions, each with why you need it; when sensible add a line "ASSUMPTIONS IF NO ANSWER:" followed by what you would assume.\n- CANNOT DO: write "REASON:" and then "WHAT WOULD WORK:" with 1 to 3 alternatives.\nRules: prefer PROCEED with stated assumptions when the gap is small and a wrong guess is cheap. Use NEED INFO only when a wrong guess wastes work or risks damage. Use CANNOT DO only when no reasonable reading of the request can be achieved with the configured teams, their access and this workspace. Never invent requirements. Never start teams on a request you do not understand. Answer in the owner's language. You may read project files (read only) to decide. Check the work is assignable: changing files needs a team with a write agent.${limitNote}`, true)}\n${accessFacts()}\n${lanes.length ? `LANES (choose exactly one; you may not invent lanes or teams):\n${laneRosterText()}\n${ownerLane ? `The owner FIXED the lane: "${ownerLane.id}". Brief only its teams. You may still answer NEED INFO or CANNOT DO.` : 'On PROCEED you MUST include a line "LANE: <lane id>" and a line "LANE REASON: <one sentence>", and write sections only for the teams of that lane. If no lane fits, answer DECISION: CANNOT DO with the reason "no lane fits" and say which lane would be needed; if the request is unclear between lanes, use NEED INFO.'}` : `TEAM ROSTER (pipeline order):\n${rosterText()}`}\n${common()}${answered}`);
476
+ for (let attempt = 0; attempt < 2; attempt++) {
477
+ const t = await ask();
478
+ if (t?.trim())
479
+ return t;
480
+ }
481
+ // the Director gave no decision twice: no team may start on a request nobody triaged
482
+ const why = 'The Director could not triage this request (no answer after 2 attempts), so no team was started. Check the Director CLI login and model in Config, then start the run again.';
483
+ directorSay('all', why);
484
+ finish('failed', why);
485
+ throw new Halt();
375
486
  }
376
487
  emit({ type: 'agent.started', agentId: config.director.id, task: 'intake brief' });
377
488
  if (/\[sim-cannot\]/i.test(goal))
@@ -622,7 +733,7 @@ export function startTeamRun(opts) {
622
733
  return { out: [...lastMsg.values()].at(-1) ?? '', back: backOf() };
623
734
  };
624
735
  if (!multi) {
625
- raw = await run(lead, 'single', 1, `${workWhat(id)}\n${handoffInstr(id, k)}`, name, to, false);
736
+ raw = await run(lead, 'single', 1, `${workWhat(id)}\n${handoffInstr(id, k)}`, name, 'director', false); // the team's result goes to the Director, never straight to the next team
626
737
  const r = returnedEarly();
627
738
  if (r)
628
739
  return r;
@@ -647,7 +758,7 @@ export function startTeamRun(opts) {
647
758
  break;
648
759
  }
649
760
  if (qcReturn === null && writer) {
650
- const t = await run(writer, 'work', 1, `The discussion is over. You are the ONLY member of the ${name} team who changes files in this pass: do the work following the team discussion. ${workWhat(id)}${writer === lead ? `\n${handoffInstr(id, k)}` : ''}`, `${name} work`, to, false);
761
+ const t = await run(writer, 'work', 1, `The discussion is over. You are the ONLY member of the ${name} team who changes files in this pass: do the work following the team discussion. ${workWhat(id)}${writer === lead ? `\n${handoffInstr(id, k)}` : ''}`, `${name} work`, writer === lead ? 'director' : lead.id, false); // a non-lead writer reports inside the team; the lead's handoff is what reaches the Director
651
762
  const rr = returnedEarly();
652
763
  if (rr)
653
764
  return rr;
@@ -657,7 +768,7 @@ export function startTeamRun(opts) {
657
768
  log.push(`[work] ${writer.name}: ${clip(t ?? '', 2500)}`);
658
769
  }
659
770
  if (qcReturn === null && raw === null) {
660
- raw = await run(lead, 'handoff', 1, `The discussion is over. You are the team lead: write the team's single result. ${isQc ? 'State the merged result: "VERDICT: FAIL" when any reviewer failed it, else "VERDICT: PASS". ' : ''}${handoffInstr(id, k)}`, `${name} handoff`, to, true);
771
+ raw = await run(lead, 'handoff', 1, `The discussion is over. You are the team lead: write the team's single result. ${isQc ? 'State the merged result: "VERDICT: FAIL" when any reviewer failed it, else "VERDICT: PASS". ' : ''}${handoffInstr(id, k)}`, `${name} handoff`, 'director', true);
661
772
  const rr = returnedEarly();
662
773
  if (rr)
663
774
  return rr;
@@ -707,6 +818,12 @@ export function startTeamRun(opts) {
707
818
  const dflt = { decision: 'accept', dispatch: '', said: '', reason: '' };
708
819
  if (!modelDirector())
709
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
710
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}`);
711
828
  let t = await ask('', false);
712
829
  if (t === null)
@@ -918,6 +1035,12 @@ export function startTeamRun(opts) {
918
1035
  w.wake({ how: 'answer', text: added.length ? `${text} [owner attached: ${added.map(a => a.path).join(', ')}]` : text });
919
1036
  return;
920
1037
  }
1038
+ for (const sess of running.values()) {
1039
+ try {
1040
+ sess.steer(text);
1041
+ }
1042
+ catch { /* steering is best effort */ }
1043
+ }
921
1044
  inbox.push(added.length ? `${text} [owner attached: ${added.map(a => a.path).join(', ')}]` : text);
922
1045
  }, () => doStop('Stopped from the console.'), () => { const w = waiting; if (w && w.assumptions)
923
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[];
@@ -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
+ }