@ngockhoale/ckit 0.2.7 → 0.2.8

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.
Files changed (60) hide show
  1. package/dist/src/adapters/launch/executor.d.ts +2 -0
  2. package/dist/src/adapters/launch/executor.js +12 -1
  3. package/dist/src/gui/server.js +1 -1
  4. package/dist/src/team/engine.d.ts +10 -0
  5. package/dist/src/team/engine.js +118 -10
  6. package/dist/src/team/journal.d.ts +2 -0
  7. package/dist/src/team/journal.js +28 -3
  8. package/dist/src/team/runners.d.ts +4 -0
  9. package/dist/src/team/runners.js +16 -2
  10. package/dist/src/team/types.d.ts +4 -0
  11. package/dist/src/tui/team/model.js +2 -0
  12. package/gui/app.css +1 -19
  13. package/gui/app.js +43 -53
  14. package/gui/comic/assets/backgrounds/command-center.svg +1 -0
  15. package/gui/comic/assets/backgrounds/developer-workshop.svg +1 -0
  16. package/gui/comic/assets/backgrounds/handoff-corridor.svg +1 -0
  17. package/gui/comic/assets/backgrounds/incident-room.svg +1 -0
  18. package/gui/comic/assets/backgrounds/mission-overview.svg +1 -0
  19. package/gui/comic/assets/backgrounds/quality-lab.svg +1 -0
  20. package/gui/comic/assets/backgrounds/reporting-hall.svg +1 -0
  21. package/gui/comic/assets/backgrounds/research-library.svg +1 -0
  22. package/gui/comic/assets/backgrounds/review-chamber.svg +1 -0
  23. package/gui/comic/assets/backgrounds/strategy-room.svg +1 -0
  24. package/gui/comic/assets/effects/check-burst.svg +1 -0
  25. package/gui/comic/assets/effects/focus-lines.svg +1 -0
  26. package/gui/comic/assets/effects/glow.svg +1 -0
  27. package/gui/comic/assets/effects/particles.svg +1 -0
  28. package/gui/comic/assets/effects/speed-lines.svg +1 -0
  29. package/gui/comic/assets/effects/warning-flash.svg +1 -0
  30. package/gui/comic/assets/frame/episode-banner.svg +1 -0
  31. package/gui/comic/assets/frame/panel-corner.svg +1 -0
  32. package/gui/comic/assets/props/approval-seal.svg +1 -0
  33. package/gui/comic/assets/props/bug-warning.svg +1 -0
  34. package/gui/comic/assets/props/capsule.svg +1 -0
  35. package/gui/comic/assets/props/checklist.svg +1 -0
  36. package/gui/comic/assets/props/code-display.svg +1 -0
  37. package/gui/comic/assets/props/document.svg +1 -0
  38. package/gui/comic/assets/props/files.svg +1 -0
  39. package/gui/comic/assets/props/folder.svg +1 -0
  40. package/gui/comic/assets/props/magnifier.svg +1 -0
  41. package/gui/comic/assets/props/package.svg +1 -0
  42. package/gui/comic/assets/props/rejection-mark.svg +1 -0
  43. package/gui/comic/assets/props/report.svg +1 -0
  44. package/gui/comic/assets/props/scroll.svg +1 -0
  45. package/gui/comic/assets/props/shield.svg +1 -0
  46. package/gui/comic/assets/props/tablet.svg +1 -0
  47. package/gui/comic/assets/props/workstation.svg +1 -0
  48. package/gui/comic/comic.css +130 -0
  49. package/gui/comic/contact-sheet.html +15 -0
  50. package/gui/comic/contact-sheet.js +41 -0
  51. package/gui/comic/engine.js +366 -0
  52. package/gui/comic/manifests/backgrounds.json +216 -0
  53. package/gui/comic/manifests/characters.json +96 -0
  54. package/gui/comic/manifests/effects.json +96 -0
  55. package/gui/comic/manifests/props.json +246 -0
  56. package/gui/comic/manifests/scenes.json +205 -0
  57. package/gui/comic/render.js +594 -0
  58. package/gui/index.html +2 -2
  59. package/gui/network.js +195 -284
  60. package/package.json +1 -1
@@ -91,6 +91,8 @@ export interface RunExecutorOptions {
91
91
  readonly killGraceMs?: number;
92
92
  /** Receives each parsed NDJSON stdout object as soon as its line is complete (line-buffered across chunks). */
93
93
  readonly onEvent?: (frame: unknown) => void;
94
+ /** Receives every raw stdout line (complete lines) and stderr chunk, unparsed. */
95
+ readonly onRaw?: (stream: 'stdout' | 'stderr', line: string) => void;
94
96
  /** Exact secret values redacted from stderrTail (in addition to pattern redaction). */
95
97
  readonly secrets?: readonly string[];
96
98
  }
@@ -226,6 +226,12 @@ export function runExecutor(spec, path, instruction, options) {
226
226
  let stdout = '', stderr = '', pending = '', done = false, stop = null, killTimer;
227
227
  const tail = () => { const t = redactSecretText(stderr, options.secrets ?? []).slice(-STDERR_TAIL); return t.trim() ? { stderrTail: t } : {}; };
228
228
  const emit = (line) => {
229
+ if (options.onRaw && line.trim()) {
230
+ try {
231
+ options.onRaw('stdout', line);
232
+ }
233
+ catch { /* observer */ }
234
+ }
229
235
  const t = line.trim();
230
236
  if (!options.onEvent || !t.startsWith('{'))
231
237
  return;
@@ -284,7 +290,12 @@ export function runExecutor(spec, path, instruction, options) {
284
290
  for (const line of lines)
285
291
  emit(line);
286
292
  });
287
- child.stderr?.on('data', (chunk) => { stderr += chunk.toString('utf8'); if (stderr.length > STDERR_TAIL * 2)
293
+ child.stderr?.on('data', (chunk) => { if (options.onRaw) {
294
+ try {
295
+ options.onRaw('stderr', chunk.toString('utf8'));
296
+ }
297
+ catch { /* observer */ }
298
+ } stderr += chunk.toString('utf8'); if (stderr.length > STDERR_TAIL * 2)
288
299
  stderr = stderr.slice(-STDERR_TAIL * 2); });
289
300
  child.on('error', error => finish({ status: 'unknown', reason: 'spawn-error', note: error.message }));
290
301
  child.on('spawn', () => options.onSpawn?.());
@@ -34,7 +34,7 @@ export function packageVersion(file = fileURLToPath(new URL('../../../package.js
34
34
  }
35
35
  }
36
36
  const START_VERSION = packageVersion();
37
- const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.json': 'application/json; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.ico': 'image/x-icon' };
37
+ const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.json': 'application/json; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.webp': 'image/webp', '.ico': 'image/x-icon' };
38
38
  const ARTIFACT_RE = /^(report\.md|transcript\.md|handoff-ba\.md|qc-report-\d{1,3}\.md)$/;
39
39
  const RUN_ID_RE = /^team-\d{8}-\d{6}-[0-9a-f]{4}$/;
40
40
  /** Attachments: any file type. Limits only keep a runaway upload from filling the disk. */
@@ -39,6 +39,16 @@ export declare const HANDOFF_SECTIONS: readonly HandoffSection[];
39
39
  export declare function parseHandoff(text: string): Record<HandoffSection, string> | null;
40
40
  /** Last `REVIEW: PASS|FAIL` wins; null when no verdict line exists. */
41
41
  export declare function parseReview(text: string): 'PASS' | 'FAIL' | null;
42
+ /** Parses a Director checkpoint reply. decision null = unreadable (callers accept). Consults: first 2 `CONSULT <agent id>: <question>` lines. */
43
+ export declare function parseCheckpoint(text: string): {
44
+ decision: 'accept' | 'return' | null;
45
+ dispatch: string;
46
+ reason: string;
47
+ consults: {
48
+ agentId: string;
49
+ question: string;
50
+ }[];
51
+ };
42
52
  export declare function startTeamRun(opts: StartTeamRunOptions): TeamRunHandle;
43
53
  /** Re-emits a journal with original relative timing / speed (gaps capped at 1.5s/speed). */
44
54
  export declare function replayTeamRun(runDir: string, opts?: {
@@ -2,7 +2,7 @@
2
2
  import { basename, join } from 'node:path';
3
3
  import { attachmentLines, attachmentPromptBlock, storeAttachments } from './attachments.js';
4
4
  import { readSecret } from './secrets.js';
5
- import { createTeamJournal } from './journal.js';
5
+ import { createCappedSink, createTeamJournal } from './journal.js';
6
6
  import { readTeamJournal } from './journal.js';
7
7
  import { advisorKeyOf, createSimulatedRunner, dispatchRunner, simHeader } from './runners.js';
8
8
  import { DEFAULT_MISSIONS, allAgentsOf, effectiveOrder } from './types.js';
@@ -90,6 +90,16 @@ export function parseReview(text) {
90
90
  const all = [...text.matchAll(/REVIEW\s*[:\-]?\s*\**\s*(PASS|FAIL)/gi)], last = all[all.length - 1]?.[1];
91
91
  return last ? last.toUpperCase() : null;
92
92
  }
93
+ /** Parses a Director checkpoint reply. decision null = unreadable (callers accept). Consults: first 2 `CONSULT <agent id>: <question>` lines. */
94
+ export function parseCheckpoint(text) {
95
+ const consults = [...text.matchAll(/^[ \t>*_#-]*CONSULT[ \t]+([A-Za-z0-9_-]+)\**[ \t]*:\**[ \t]*(.+)$/gim)].slice(0, 2).map(m => ({ agentId: m[1].toLowerCase(), question: m[2].trim() }));
96
+ const all = [...text.matchAll(/CHECKPOINT\s*[:\-]?\s*\**\s*(ACCEPT|RETURN)/gi)], last = all[all.length - 1]?.[1];
97
+ const decision = last ? last.toLowerCase() : null;
98
+ const reason = /^[ \t>*_#-]*RETURN REASON\**[ \t]*:\**[ \t]*([\s\S]*?)(?=^[ \t>*_#-]*(?:CHECKPOINT|DISPATCH|CONSULT)\b|$(?![\s\S]))/im.exec(text)?.[1]?.trim() ?? '';
99
+ const d = /^[ \t>*_#-]*DISPATCH\**[ \t]*:\**[ \t]*([\s\S]*)$/im.exec(text)?.[1] ?? '';
100
+ const dispatch = d.split('\n').filter(l => !/^[ \t>*_#-]*(CONSULT[ \t]+\S+|CHECKPOINT)\b/i.test(l)).join('\n').trim();
101
+ return { decision, dispatch, reason, consults };
102
+ }
93
103
  function makeHandle(runId, runDir, history, listeners, done, sendToDirector, stop, proceedWithAssumptions) {
94
104
  return {
95
105
  runId, runDir, done, sendToDirector, stop, ...(proceedWithAssumptions ? { proceedWithAssumptions } : {}),
@@ -201,7 +211,8 @@ export function startTeamRun(opts) {
201
211
  return `FLOW: You are team ${k + 1} of ${order.length}; before you: ${before}; after you: ${after}. Work goes Director -> ${order.map(teamName).join(' -> ')}.\nIf something from ${before} is unclear, end your message with a line "ASK PREVIOUS: <your question>" and ${before} will answer. If the work you received is not good enough to continue, end your message with a line "RETURN TO PREVIOUS: <reason>" and ${before} will redo it. Use these only when really needed.\n`;
202
212
  };
203
213
  const sysBlock = () => config.systemPrompt ? `PROJECT INSTRUCTIONS FROM THE OWNER (they apply to everything you do here, but they do not override the flow markers, the handoff format or your read/write access):\n${config.systemPrompt}\n\n` : '';
204
- const role = (agent, what, readOnly = false) => `${sysBlock()}You are ${agent.name}, member of the ${teamLabel(agent)} team in a software "agent company" (Director -> ${order.map(teamName).join(' -> ') || 'teams'}). ${agent.persona ?? ''}\n${what}\n${teamBlock(agent)}${flowBlock(agent)}${accessLine(agent, readOnly)}\nAnswer concisely.`;
214
+ const WORKER_NOTE = 'You run inside CKit as a worker process: ignore any message from host hooks, completion gates or status checks of the CLI tool itself (they are not your task and not from the owner); never answer about them - just do what this prompt asks.';
215
+ const role = (agent, what, readOnly = false) => `${sysBlock()}You are ${agent.name}, member of the ${teamLabel(agent)} team in a software "agent company" (Director -> ${order.map(teamName).join(' -> ') || 'teams'}). ${agent.persona ?? ''}\n${what}\n${teamBlock(agent)}${flowBlock(agent)}${accessLine(agent, readOnly)}\nAnswer concisely.\n${WORKER_NOTE}`;
205
216
  /** Pulls the flow markers out of an agent message (first of each, anywhere in the text, optional bullet/bold). Never throws. */
206
217
  const markers = (text) => {
207
218
  let ask = null, ret = null;
@@ -228,35 +239,66 @@ export function startTeamRun(opts) {
228
239
  const simAgent = (a) => simulated || a.cli === 'simulated';
229
240
  /** Failure text for an agent with extra CLI arguments: name them, so a typo is easy to find. */
230
241
  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
+ const rawSinks = new Map();
243
+ const RAW_CAP = 5 * 1024 * 1024;
244
+ /** Appends to agents/<id>.log; a logging failure never breaks a run. */
245
+ const agentLog = (agent, text) => { try {
246
+ journal.appendArtifact(`agents/${agent.id}.log`, text);
247
+ }
248
+ catch { /* debug log only */ } };
249
+ const rawSink = (agent) => {
250
+ let sink = rawSinks.get(agent.id);
251
+ if (!sink) {
252
+ sink = createCappedSink(t => { try {
253
+ journal.appendArtifact(`agents/${agent.id}.raw.log`, t);
254
+ }
255
+ catch { /* debug log only */ } }, RAW_CAP);
256
+ rawSinks.set(agent.id, sink);
257
+ }
258
+ return sink;
259
+ };
260
+ const logPath = (agent) => `.ckit/team/runs/${journal.runId}/agents/${agent.id}.log`;
231
261
  /** Runs one agent turn through the runner, wiring activity/step/subagent events. Never throws. */
232
262
  async function callRunner(agent, prompt, first, last) {
263
+ const t0 = Date.now(), stamp = () => new Date().toISOString();
264
+ 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
+ const done = (res) => {
266
+ agentLog(agent, res.ok ? `----- RESULT (ok, ${Date.now() - t0} ms) -----\n${res.text}\n\n` : `----- FAILED (${Date.now() - t0} ms) -----\n${res.reason}\n\n`);
267
+ return res.ok || res.reason === 'cancelled' ? res : { ok: false, reason: `${res.reason} (full log: ${logPath(agent)})` };
268
+ };
233
269
  let n = 0, lastLabel = '';
234
270
  const step = (label, k, total) => {
235
271
  if (label === lastLabel)
236
272
  return;
237
273
  lastLabel = label;
238
274
  n = k ?? n + 1;
275
+ agentLog(agent, `[${stamp()}] step ${n}${total ? `/${total}` : ''}: ${label}\n`);
239
276
  emit({ type: 'agent.step', agentId: agent.id, step: n, total: total ?? null, label });
240
277
  };
241
278
  const own = simAgent(agent);
242
279
  if (!own)
243
280
  step(first);
244
281
  try {
282
+ const raw = rawSink(agent);
245
283
  const res = await runner(agent, prompt, {
246
284
  cwd: opts.projectRoot, timeoutMs: config.limits.agentTimeoutMs, signal: abort.signal, ...(atts.length ? { images: images() } : {}),
247
- onActivity: text => { emit({ type: 'agent.activity', agentId: agent.id, text: oneLine(text, 160) }); const l = own ? null : stepOf(text); if (l)
285
+ onRaw: (stream, line) => raw(`[${stamp()}] ${stream}: ${line.endsWith('\n') ? line : `${line}\n`}`),
286
+ 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)
248
287
  step(l); },
249
288
  onStep: (label, k, total) => step(oneLine(label, 80), k, total),
250
- onSubagent: e => emit(e.type === 'started' ? { type: 'subagent.started', agentId: agent.id, childId: e.childId, kind: e.kind, task: oneLine(e.task, 160) }
251
- : e.type === 'activity' ? { type: 'subagent.activity', agentId: agent.id, childId: e.childId, text: oneLine(e.text, 160) }
252
- : { type: 'subagent.finished', agentId: agent.id, childId: e.childId, ok: e.ok, summary: oneLine(e.summary, 200) }),
289
+ onSubagent: e => {
290
+ agentLog(agent, `[${stamp()}] subagent ${e.type} ${e.childId}: ${e.type === 'started' ? e.task : e.type === 'activity' ? e.text : e.summary}\n`);
291
+ emit(e.type === 'started' ? { type: 'subagent.started', agentId: agent.id, childId: e.childId, kind: e.kind, task: oneLine(e.task, 160) }
292
+ : e.type === 'activity' ? { type: 'subagent.activity', agentId: agent.id, childId: e.childId, text: oneLine(e.text, 160) }
293
+ : { type: 'subagent.finished', agentId: agent.id, childId: e.childId, ok: e.ok, summary: oneLine(e.summary, 200) });
294
+ },
253
295
  });
254
296
  if (res.ok && !own)
255
297
  step(last);
256
- return res.ok ? res : { ok: false, reason: withArgsNote(agent, res.reason) };
298
+ return done(res.ok ? res : { ok: false, reason: withArgsNote(agent, res.reason) });
257
299
  }
258
300
  catch (e) {
259
- return { ok: false, reason: withArgsNote(agent, e instanceof Error ? e.message : 'runner threw') };
301
+ return done({ ok: false, reason: withArgsNote(agent, e instanceof Error ? e.message : 'runner threw') });
260
302
  }
261
303
  }
262
304
  async function turn(agent, task, to, prompt, round) {
@@ -463,6 +505,8 @@ export function startTeamRun(opts) {
463
505
  };
464
506
  const hdr = (agent, stage, loop, turn, turns, phase, round) => simAgent(agent) ? `${simHeader({ stage, loop, turn, turns, final: phase === 'handoff' || phase === 'single', phase, round })}\n` : '';
465
507
  const hdrS = (agent, stage, loop) => simAgent(agent) ? `${simHeader({ stage, loop, turn: 1, turns: 1, final: true })}\n` : '';
508
+ const dispatches = new Map(); // Director's dispatch text per team (model Director only)
509
+ const dirBacks = new Map(); // Director send-backs per team at a checkpoint
466
510
  const inputBlock = (k, id) => {
467
511
  const p = prevId(k), parts = [];
468
512
  if (p !== 'director')
@@ -470,6 +514,9 @@ export function startTeamRun(opts) {
470
514
  const trail = trailBlock(k - 1);
471
515
  if (trail)
472
516
  parts.push(trail.trimEnd());
517
+ const dp = dispatches.get(id);
518
+ if (dp)
519
+ parts.push(`DIRECTOR'S DISPATCH FOR YOUR TEAM:\n${clip(dp, 3000)}`);
473
520
  const sb = sentBack.get(id);
474
521
  if (sb)
475
522
  parts.push(`YOUR PREVIOUS HANDOFF:\n${clip(outs.get(id) ?? '', 4000)}\n\nSENT BACK TO YOU by the ${teamName(sb.from)} team (redo your work and fix this):\n${clip(sb.reason, 4000)}`);
@@ -641,8 +688,8 @@ export function startTeamRun(opts) {
641
688
  const art = journal.writeArtifact(`handoff-${id}.md`, text);
642
689
  if (id === 'ba')
643
690
  journal.writeArtifact('handoff-ba.md', text);
644
- emit({ type: 'handoff.created', from: id, to, title: `${name} -> ${toName}`, artifact: art, text: clip(text, 8000) });
645
- return { out: text, back };
691
+ emit({ type: 'handoff.created', from: id, to: 'director', title: `${name} -> Director`, artifact: art, text: clip(text, 8000) }); // every team reports to the Director; the Director dispatches the next team
692
+ return { out: text, back, art };
646
693
  }
647
694
  /** Director rewrites the brief for team 1 after it sent the work back. */
648
695
  async function directorRewrite(id, reason) {
@@ -655,6 +702,37 @@ export function startTeamRun(opts) {
655
702
  const said = directorSay(id, text);
656
703
  briefs.set(id, parseBriefs(said).get(id) ?? clip(said, 2500));
657
704
  }
705
+ /** Director checkpoint after a team report: accept (dispatch the next team) or return the work to the same team. May consult read-only agents for context (max 2, once). Never fails the run. */
706
+ async function checkpoint(id, nextId, report) {
707
+ const dflt = { decision: 'accept', dispatch: '', said: '', reason: '' };
708
+ if (!modelDirector())
709
+ return dflt;
710
+ 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
+ let t = await ask('', false);
712
+ if (t === null)
713
+ return dflt;
714
+ let cp = parseCheckpoint(t);
715
+ if (cp.consults.length) {
716
+ const known = allAgentsOf(config).filter(a => a.team !== 'director'), answers = [];
717
+ for (const c of cp.consults) {
718
+ const a = known.find(x => x.id === c.agentId);
719
+ if (!a) {
720
+ answers.push(`CONSULT ${c.agentId}: unknown agent id`);
721
+ continue;
722
+ }
723
+ emit({ type: 'director.consult', agentId: a.id, question: oneLine(c.question, 300) });
724
+ const ro = { ...a, access: 'read' }; // consulting never grants write
725
+ const r = await turn(ro, `consulted by the Director`, 'director', `${role(ro, 'The Director consults you for context. Answer the question briefly; do not change any file.', true)}\n${common()}\nQUESTION: ${c.question}`);
726
+ answers.push(`CONSULT ${a.id} (${a.name}): ${r === null ? 'consult failed: the agent could not answer' : clip(r, 2000)}`);
727
+ }
728
+ const t2 = await ask(`\n\nANSWERS TO YOUR CONSULTS:\n${answers.join('\n\n')}\nNow decide; do not consult again.`, true);
729
+ if (t2 !== null) {
730
+ t = t2;
731
+ cp = parseCheckpoint(t2);
732
+ }
733
+ }
734
+ return { decision: cp.decision === 'return' ? 'return' : 'accept', dispatch: cp.dispatch, said: cp.dispatch || t.trim(), reason: cp.reason };
735
+ }
658
736
  /** Runs the teams strictly in order from team index `from`. A return from team k re-runs team k-1 with the reason, then moves forward again; bounded per boundary by limits.qcLoops. */
659
737
  async function flow(from = 0) {
660
738
  let k = from;
@@ -663,6 +741,7 @@ export function startTeamRun(opts) {
663
741
  passes.set(id, pass);
664
742
  retReason = null;
665
743
  const res = await teamPass(k, id, pass);
744
+ let note = '';
666
745
  sentBack.delete(id);
667
746
  outs.set(id, res.out);
668
747
  if (res.back) {
@@ -682,6 +761,33 @@ export function startTeamRun(opts) {
682
761
  if (id === 'qc')
683
762
  qcPassed = false;
684
763
  }
764
+ else if (k < order.length - 1) {
765
+ const nextId = order[k + 1], cp = await checkpoint(id, nextId, res.out);
766
+ if (cp.decision === 'return') {
767
+ const used = dirBacks.get(id) ?? 0;
768
+ if (used < limit) {
769
+ dirBacks.set(id, used + 1);
770
+ const reason = cp.reason || 'the Director asked for a rework';
771
+ emit({ type: 'flow.back', kind: 'return', from: 'director', to: id, reason: oneLine(reason, 300) });
772
+ sentBack.set(id, { from: 'director', reason });
773
+ continue;
774
+ }
775
+ note = `\n\n(Note: the Director wanted this team to rework (${oneLine(cp.reason, 200)}) but the send-back limit of ${limit} was reached.)`;
776
+ }
777
+ if (modelDirector()) {
778
+ if (cp.dispatch || note)
779
+ dispatches.set(nextId, `${cp.dispatch || 'Proceed with your brief.'}${note}`);
780
+ directorSay(nextId, `${cp.said || 'Proceed with your brief.'}${note}`);
781
+ }
782
+ }
783
+ if (k < order.length - 1 && !res.back) {
784
+ const nextId = order[k + 1];
785
+ emit({ type: 'handoff.created', from: 'director', to: nextId, title: `Director -> ${teamName(nextId)}`, artifact: res.art ?? `handoff-${id}.md`, text: clip(`### HANDOFF Director -> ${teamName(nextId)}\n${dispatches.get(nextId) ?? `Proceed with your brief. The ${teamName(id)} team's report is attached in full.`}`, 8000) });
786
+ }
787
+ else if (k < order.length - 1) {
788
+ const nextId = order[k + 1];
789
+ emit({ type: 'handoff.created', from: 'director', to: nextId, title: `Director -> ${teamName(nextId)}`, artifact: res.art ?? `handoff-${id}.md`, text: `### HANDOFF Director -> ${teamName(nextId)}\nProceed with your brief; the ${teamName(id)} team's report is attached (send-back limit reached, open problems remain).` });
790
+ }
685
791
  k++;
686
792
  }
687
793
  const lastId = order.at(-1);
@@ -764,6 +870,8 @@ export function startTeamRun(opts) {
764
870
  deliverable = '';
765
871
  qcPassed = !order.includes('qc');
766
872
  outs.clear();
873
+ dispatches.clear();
874
+ dirBacks.clear();
767
875
  passes.clear();
768
876
  sentBack.clear();
769
877
  asks.clear();
@@ -28,3 +28,5 @@ export interface TeamRunInfo {
28
28
  }
29
29
  /** Newest first (runId embeds the timestamp). */
30
30
  export declare function listTeamRuns(root: string): TeamRunInfo[];
31
+ /** Byte-bounded sink: passes text through until `cap` bytes, then writes one truncation line and drops the rest. */
32
+ export declare function createCappedSink(write: (text: string) => void, cap: number): (text: string) => void;
@@ -1,6 +1,6 @@
1
1
  // Append-only team journal (JSONL) + artifacts under <root>/.ckit/team/runs/<runId>/. Every string is secret-redacted first.
2
2
  import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
3
- import { join } from 'node:path';
3
+ import { dirname, join } from 'node:path';
4
4
  import { randomBytes } from 'node:crypto';
5
5
  import { redactSecretText } from '../security/redact.js';
6
6
  const pad = (n) => String(n).padStart(2, '0');
@@ -24,6 +24,15 @@ export function createTeamJournal(opts) {
24
24
  mkdirSync(runDir, { recursive: true });
25
25
  const file = join(runDir, 'events.jsonl');
26
26
  let seq = 0;
27
+ /** Artifact names: one file, or one subdirectory + file; never traversal. The subdirectory is created on demand. */
28
+ const artifactPath = (name) => {
29
+ if (!/^[A-Za-z0-9._-]+(\/[A-Za-z0-9._-]+)?$/.test(name) || name.split('/').some(p => p === '.' || p === '..'))
30
+ throw new Error(`invalid artifact name: ${name}`);
31
+ const path = join(runDir, name);
32
+ if (name.includes('/'))
33
+ mkdirSync(dirname(path), { recursive: true });
34
+ return path;
35
+ };
27
36
  return {
28
37
  runId, runDir,
29
38
  append(event) {
@@ -31,8 +40,8 @@ export function createTeamJournal(opts) {
31
40
  appendFileSync(file, JSON.stringify(full) + '\n');
32
41
  return full;
33
42
  },
34
- writeArtifact(name, text) { writeFileSync(join(runDir, name), redactSecretText(text, secrets)); return name; },
35
- appendArtifact(name, text) { appendFileSync(join(runDir, name), redactSecretText(text, secrets)); },
43
+ writeArtifact(name, text) { writeFileSync(artifactPath(name), redactSecretText(text, secrets)); return name; },
44
+ appendArtifact(name, text) { appendFileSync(artifactPath(name), redactSecretText(text, secrets)); },
36
45
  redact: text => redactSecretText(text, secrets),
37
46
  };
38
47
  }
@@ -67,4 +76,20 @@ export function listTeamRuns(root) {
67
76
  return [];
68
77
  return readdirSync(dir).filter(n => /^team-\d{8}-\d{6}-[0-9a-f]{4}$/.test(n)).sort().reverse().map(runId => ({ runId, runDir: join(dir, runId) }));
69
78
  }
79
+ /** Byte-bounded sink: passes text through until `cap` bytes, then writes one truncation line and drops the rest. */
80
+ export function createCappedSink(write, cap) {
81
+ let bytes = 0, stopped = false;
82
+ return text => {
83
+ if (stopped)
84
+ return;
85
+ const n = Buffer.byteLength(text);
86
+ if (bytes + n > cap) {
87
+ stopped = true;
88
+ write('[truncated: raw log cap reached]\n');
89
+ return;
90
+ }
91
+ bytes += n;
92
+ write(text);
93
+ };
94
+ }
70
95
  //# sourceMappingURL=journal.js.map
@@ -13,6 +13,8 @@ export interface AgentRunOptions {
13
13
  readonly env?: Readonly<Record<string, string>>;
14
14
  /** Absolute paths of owner-attached images. codex receives them as image inputs (-i); the other CLIs open them by path from the prompt. */
15
15
  readonly images?: readonly string[];
16
+ /** Raw child output for debug logs: each stdout line / stderr chunk, cut to 4000 chars. */
17
+ readonly onRaw?: (stream: 'stdout' | 'stderr', line: string) => void;
16
18
  }
17
19
  export type SubagentSignal = {
18
20
  readonly type: 'started';
@@ -63,6 +65,8 @@ export declare function claudeFrameActivity(frame: unknown): string[];
63
65
  export declare const withCliArgs: <T extends {
64
66
  readonly args: readonly string[];
65
67
  }>(spec: T, agent: AgentConfig) => T;
68
+ /** Claude team workers run with host hooks disabled (workspace Stop gates / prompt routers must not hijack the answer); the owner's cliArgs come after. */
69
+ export declare const claudeTeamArgs: (args: readonly string[], agent: AgentConfig) => string[];
66
70
  export declare function runExecutorAgent(agent: AgentConfig, prompt: string, opts: AgentRunOptions): Promise<AgentRunResult>;
67
71
  export { parseExecutorOutput };
68
72
  export declare function runApiAgent(agent: AgentConfig, prompt: string, opts: AgentRunOptions & {
@@ -8,6 +8,11 @@ import { OpenAiCompatibleAdvisor } from '../adapters/openai/openai-advisor.js';
8
8
  import { readSecret } from './secrets.js';
9
9
  import { loadCkitConfig, resolveProjectRoot } from '../settings/env-config.js';
10
10
  import { cliArgTokens } from './cli-args.js';
11
+ const RAW_MAX = 4000;
12
+ const rawOf = (opts) => opts.onRaw ? (stream, line) => { try {
13
+ opts.onRaw?.(stream, line.slice(0, RAW_MAX));
14
+ }
15
+ catch { /* observer must not break the run */ } } : undefined;
11
16
  const oneLine = (s, max = 120) => { const t = s.replace(/\s+/g, ' ').trim(); return t.length > max ? `${t.slice(0, max - 1)}…` : t; };
12
17
  /** 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. */
13
18
  export const advisorKeyOf = (cwd) => {
@@ -149,7 +154,10 @@ export function runCodex(agent, prompt, opts) {
149
154
  onAbort();
150
155
  else
151
156
  opts.signal?.addEventListener('abort', onAbort, { once: true });
157
+ const raw = rawOf(opts);
152
158
  const handle = (line) => {
159
+ if (raw && line.trim())
160
+ raw('stdout', line);
153
161
  const t = line.trim();
154
162
  if (!t.startsWith('{'))
155
163
  return;
@@ -178,7 +186,7 @@ export function runCodex(agent, prompt, opts) {
178
186
  }
179
187
  };
180
188
  child.stdout?.on('data', (c) => { pending += c.toString('utf8'); const lines = pending.split('\n'); pending = lines.pop() ?? ''; lines.forEach(handle); });
181
- child.stderr?.on('data', (c) => { stderr = (stderr + c.toString('utf8')).slice(-2000); });
189
+ child.stderr?.on('data', (c) => { raw?.('stderr', c.toString('utf8')); stderr = (stderr + c.toString('utf8')).slice(-2000); });
182
190
  child.on('error', e => finish({ ok: false, reason: e.message }));
183
191
  child.on('close', code => {
184
192
  if (pending)
@@ -221,11 +229,16 @@ export function claudeFrameActivity(frame) {
221
229
  }
222
230
  /** The executor spec with the agent's extra CLI arguments appended after CKit's own flags (runExecutor appends the prompt last). */
223
231
  export const withCliArgs = (spec, agent) => { const extra = cliArgTokens(agent.cliArgs); return extra.length ? { ...spec, args: [...spec.args, ...extra] } : spec; };
232
+ /** Claude team workers run with host hooks disabled (workspace Stop gates / prompt routers must not hijack the answer); the owner's cliArgs come after. */
233
+ export const claudeTeamArgs = (args, agent) => {
234
+ const hooksOff = ['--settings', '{"disableAllHooks":true}'];
235
+ return [...args, ...hooksOff, ...cliArgTokens(agent.cliArgs)];
236
+ };
224
237
  export async function runExecutorAgent(agent, prompt, opts) {
225
238
  const kind = agent.cli === 'omp' ? 'omp' : 'claude-code';
226
239
  const base = selectExecutor({ executor: kind, executorModel: agent.model, executorPermissionMode: kind === 'claude-code' && agent.access === 'write' ? 'acceptEdits' : null });
227
240
  const env = opts.env ?? executorEnvironment(process.env, advisorKeyOf(opts.cwd), kind);
228
- const spec = withCliArgs(base, agent);
241
+ const spec = kind === 'claude-code' ? { ...base, args: claudeTeamArgs(base.args, agent) } : withCliArgs(base, agent);
229
242
  let path;
230
243
  try {
231
244
  path = resolveExecutable(spec, { executorPath: null }, env);
@@ -269,6 +282,7 @@ export async function runExecutorAgent(agent, prompt, opts) {
269
282
  };
270
283
  const r = await runExecutor(spec, path, prompt, {
271
284
  cwd: opts.cwd, timeoutMs: opts.timeoutMs, env, ...(opts.signal ? { signal: opts.signal } : {}), onEvent: onFrame,
285
+ ...(opts.onRaw ? { onRaw: rawOf(opts) } : {}),
272
286
  });
273
287
  for (const [childId] of open)
274
288
  opts.onSubagent?.({ type: 'finished', childId, ok: r.status === 'completed', summary: r.status === 'completed' ? 'finished with the turn' : 'turn ended early' });
@@ -207,6 +207,10 @@ export type TeamEvent = {
207
207
  readonly type: 'user.message';
208
208
  readonly text: string;
209
209
  readonly attachments?: readonly AttachmentInfo[];
210
+ } | {
211
+ readonly type: 'director.consult';
212
+ readonly agentId: string;
213
+ readonly question: string;
210
214
  } | {
211
215
  readonly type: 'director.decision';
212
216
  readonly decision: 'continue' | 'redirect' | 'stop';
@@ -105,6 +105,8 @@ export function reduceTeam(state, event) {
105
105
  return push(s0, { kind: 'director', from: 'director', fromTeam: 'director', to: 'all', text: `Waiting for the owner: ${oneLine(event.questions)}`, at });
106
106
  case 'user.message':
107
107
  return push({ ...s0, messageCount: s0.messageCount + 1 }, { kind: 'user', from: 'user', fromTeam: null, to: 'director', text: sanitize(event.text).trim(), at });
108
+ case 'director.consult':
109
+ return push(s0, { kind: 'system', from: 'director', fromTeam: 'director', to: 'all', text: `◆ Director consults ${s0.agents.find(a => a.id === event.agentId)?.name ?? event.agentId}: ${sanitize(event.question).trim()}`, at });
108
110
  case 'director.decision':
109
111
  return push(s0, { kind: 'director', from: 'director', fromTeam: 'director', to: 'all', text: `Decision: ${event.decision}${event.note ? ` — ${sanitize(event.note).trim()}` : ''}`, at });
110
112
  case 'run.completed': {
package/gui/app.css CHANGED
@@ -95,23 +95,7 @@ svg.spark{width:100%;height:16px;display:block;margin-top:4px}
95
95
  textarea.json{font:12px/1.5 var(--mono);height:100%;min-height:360px;resize:none}
96
96
  table.runs{width:100%;border-collapse:collapse}table.runs td,table.runs th{padding:9px 10px;border-bottom:1px solid var(--b1);text-align:left}table.runs th{font:600 10px var(--mono);letter-spacing:.1em;color:var(--mu);text-transform:uppercase}
97
97
  /* comic */
98
- #comic{position:absolute;left:8px;right:8px;top:8px;bottom:calc(var(--dock) + 16px);background:#04060b;border:1px solid var(--b2);border-radius:4px;overflow:auto;z-index:5;padding:14px;background-image:radial-gradient(rgba(120,150,190,.12) 1px,transparent 1px);background-size:9px 9px}
99
- #comic[hidden]{display:none}#comicpanels{display:flex;flex-wrap:wrap;gap:14px;align-items:flex-start}
100
- .panel{width:min(440px,100%);flex:0 0 auto;border:3px solid var(--pc);border-radius:4px;background:linear-gradient(#0b1220,#070b14);box-shadow:0 0 18px var(--pg),6px 6px 0 rgba(0,0,0,.6);padding:10px;position:relative;overflow:hidden;animation:pop .35s}
101
- .panel:before{content:"";position:absolute;inset:0;background-image:radial-gradient(rgba(255,255,255,.05) 1px,transparent 1.2px);background-size:6px 6px;pointer-events:none}
102
- .panel.wide{width:min(904px,100%)}
103
- .cap{display:inline-block;background:#fff2a8;color:#171200;border:2px solid #171200;font:800 13px var(--mono);padding:4px 10px;margin-bottom:8px;letter-spacing:.04em;position:relative;box-shadow:3px 3px 0 rgba(0,0,0,.6)}
104
- .cscene{display:flex;gap:12px;align-items:flex-end;min-height:110px;position:relative}.cscene.r{flex-direction:row-reverse}
105
- .cav{width:64px;height:64px;border-radius:50%;border:3px solid var(--pc);display:grid;place-items:center;font:800 22px var(--sans);background:radial-gradient(circle at 30% 30%,var(--pg),#0a101c);flex:none;box-shadow:0 0 14px var(--pg)}
106
- .cav small{position:absolute}.cwho{font:700 11px var(--mono);color:var(--pc);text-align:center;margin-top:4px;letter-spacing:.06em}
107
- .cbub{position:relative;flex:1;background:#f4f7ff;color:#0a1020;border:3px solid #0a1020;outline:2px solid var(--pc);border-radius:16px;padding:10px 14px;font:600 15px/1.45 var(--mono);cursor:pointer;margin-bottom:18px}
108
- .cbub:after{content:"";position:absolute;bottom:14px;left:-14px;border:9px solid transparent;border-right-color:#0a1020;border-left:0}.cscene.r .cbub:after{left:auto;right:-14px;border-left:9px solid #0a1020;border-right:0}
109
- .cbub .to{display:block;font:700 10px var(--mono);color:#556;margin-bottom:3px}
110
- .onom{font:900 44px/1 var(--mono);letter-spacing:.04em;color:var(--pc);text-shadow:3px 3px 0 #000,0 0 22px var(--pc);transform:rotate(-5deg);text-align:center;padding:16px 4px}
111
- .stamp{display:inline-block;border:5px solid;padding:4px 18px;font:900 40px var(--mono);transform:rotate(-8deg);letter-spacing:.1em}
112
- .dron{display:flex;gap:6px;flex-wrap:wrap;margin-top:6px}.dron span{font:600 11px var(--mono);border:1px dashed var(--pc);border-radius:10px;padding:2px 8px;color:#c3d0e2;background:#0a101c}
113
- .panel .sm{font:12px var(--mono);color:#9fb0c6;margin-top:6px}
114
- body.comicmode #comicpanels .cbub{font-size:17px}
98
+ #comic[hidden]{display:none}
115
99
  ::-webkit-scrollbar{width:8px;height:8px}::-webkit-scrollbar-thumb{background:#243349;border-radius:4px}
116
100
  .firstrun{background:rgba(255,255,255,.04);border:1px solid var(--am);border-radius:4px;padding:10px 12px;margin-bottom:10px;font-size:13px;line-height:1.5}
117
101
  /* --- live view v2: bigger agents, glass chat, workspace, compact drawers --- */
@@ -213,7 +197,6 @@ table.runs td.warn{color:var(--am)}
213
197
  .enhorig{white-space:pre-wrap;word-break:break-word;font-size:13px;line-height:1.55;color:var(--mu);max-height:52vh;overflow:auto;padding:10px 12px;border:1px dashed var(--b2);border-radius:4px}
214
198
  .enhta{width:100%;height:52vh;resize:vertical;font-size:13.5px;line-height:1.55;border-color:#4a3a86}.enhnote{margin:10px 0 0;font-size:12px;color:var(--mu)}
215
199
  @media (max-width:820px){.enhcols{grid-template-columns:1fr}.enhta{height:34vh}.enhorig{max-height:18vh}}
216
- #comicpanels:empty::before{content:'Comic view retells a run as comic panels: who said what, each handoff, each verdict.\A Nothing to show yet: start a mission in the box below, or open Runs and replay an old one.';white-space:pre-line;display:block;margin:12vh auto 0;max-width:560px;text-align:center;font:13px/1.7 var(--mono);color:var(--mu)}
217
200
  /* "@" file mentions */
218
201
  .ment{position:fixed;z-index:90;display:flex;flex-direction:column;overflow:auto;background:var(--p1);border:1px solid var(--b2);border-top:2px solid var(--cy);border-radius:6px;box-shadow:0 18px 60px rgba(0,0,0,.65),0 0 40px rgba(33,214,232,.12);padding:4px}
219
202
  .menth{display:flex;justify-content:space-between;gap:12px;padding:6px 8px 7px;font:600 10px var(--mono);letter-spacing:.08em;color:var(--mu);position:sticky;top:-4px;background:var(--p1);white-space:nowrap}.menth span:first-child{overflow:hidden;text-overflow:ellipsis}.menth span:last-child{letter-spacing:0;font-weight:400}
@@ -427,7 +410,6 @@ body.noroster #live{grid-template-columns:0 minmax(0,1fr) var(--iw)}body.noroste
427
410
  .avpick{display:flex;flex-direction:column;align-items:center;gap:3px;padding:4px;background:none;border-color:transparent;margin-bottom:12px}.avpick:hover{border-color:var(--b2);box-shadow:none}
428
411
  @media (max-width:820px){.avbody{grid-template-columns:1fr}}
429
412
  /* resize handles: offsets unchanged (grid lives inside #live) */
430
- #comic{bottom:calc(var(--dock) + 16px)}
431
413
  /* compact screens */
432
414
  @media (max-height:720px),(max-width:1180px){#rail{--rail:44px}.rb{width:34px;height:34px}#roster.pop{display:flex}.metric{padding-left:8px}.wsbox{max-width:140px}}
433
415
  @media (max-width:1180px){#strip{padding-left:14px}.st{min-width:0;padding:0 14px 0 18px}#top .metric:nth-of-type(n+3){display:none}}