@ngockhoale/ckit 0.1.1 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -17,7 +17,7 @@ No env file and no API key are needed: every agent uses the login of its own CLI
17
17
 
18
18
  ## Agent Company (team mode)
19
19
 
20
- A Director plus Team BA (2 agents discuss, then write one handoff) → Team Implement → Team QC (2 reviewers; FAIL returns to Implement, up to `limits.qcLoops`) → BA review → Director delivery report. You always talk to the Director; it can continue, redirect or stop the run.
20
+ A Director plus Team BA (2 agents discuss, then write one handoff) → Team Implement → Team QC (2 reviewers; FAIL returns to Implement, up to `limits.qcLoops`) → (optional) Director review against your original request → Director delivery report. Inside a team the agents discuss in bounded rounds (`limits.baRounds`, early stop on AGREED), the lead writes one `### HANDOFF` (DONE / DECISIONS / OPEN / FOR YOU) and the next team gets it in full. Before any team starts the Director triages the request (PROCEED / NEED INFO, up to 3 rounds, no turns are spent while it waits for you / CANNOT DO, shown as `declined`); runs live only in the CKit process that started them, so a run waiting for your answer is not resumed after a restart and shows in Runs as interrupted. You always talk to the Director; it can continue, redirect or stop the run.
21
21
 
22
22
  ```bash
23
23
  ckit # no command, in a terminal: opens the GUI. First time in a project it lands on Config so setup is done there
@@ -28,6 +28,7 @@ ckit team --demo # same pipeline in the terminal, fully SIMULATED (no mo
28
28
  ckit team "<goal>" # real run with the agents in <project>/.ckit/team.json (codex / claude-code / omp / api)
29
29
  ckit team --init # write the default .ckit/team.json (--force overwrites)
30
30
  ```
31
+ - Teams are configurable in Config: only the Director is mandatory; BA, Implement and QC can each be removed or re-added, and `+ Add team` creates your own team (`extraTeams` in `.ckit/team.json`: name, mission, agents). All teams follow one numbered flow, `order` (e.g. `["ba","implement","test","qc"]`, reorder with the arrows in Config; absent = ba, implement, qc with custom teams placed by the old `runAfter`): work goes Director -> team 1 -> team 2 ..., each team gets the Director's brief and the previous team's output. A team can end its message with `ASK PREVIOUS: <question>` (the team before it, or the Director, answers) or `RETURN TO PREVIOUS: <reason>` (QC's FAIL means the same); both are limited to `limits.qcLoops` per team boundary ("Max send-backs per team"). Each agent (Director too) also has an optional `cliArgs` text box ("Extra CLI arguments"), e.g. `--settings ./other-settings.json`: it is split like a shell would (quotes group, no `~` or `$VAR` expansion), appended to that agent's start command after CKit's own flags and before the prompt, and empty means not used.
31
32
 
32
33
  Every run is journaled to `.ckit/team/runs/<runId>/` (`events.jsonl`, `handoff-ba.md`, `qc-report-N.md`, `transcript.md`, `report.md`). Real agents use their own CLI login; codex runs `read-only` unless the agent has `access: "write"` (then `workspace-write`), claude uses `acceptEdits` only for write access, never bypass.
33
34
 
@@ -69,3 +70,6 @@ the exact shape the UI will consume. ADR-016 records the hand-written state mach
69
70
  - Published as `@ngockhoale/ckit`; publish only on the owner's request, after `npm test` passes.
70
71
  - Simulated adapter output must stay labeled `simulated`; live evidence requires a `live` provenance ref.
71
72
  - Unknown external outcomes stop the flow (`needsReconciliation`); the core never blind-resends.
73
+
74
+
75
+ Optional project-wide `systemPrompt` (Config, "System prompt (optional)") is sent to every agent; empty means prompts are unchanged. Each prompt box has an Enhance button that shows a proposal next to your text and applies it only when you press "Use this". Optional `lanes` (`[{id, name, when, order}]`) let the Director pick which teams a request needs (it answers `LANE: <id>`; the owner can fix a lane in the composer); without lanes the single `order` flow runs as before.
@@ -15,7 +15,9 @@ import { deleteSecret, hasSecret, readSecret, setSecret, SECRET_NAME_RE } from '
15
15
  import { replayTeamRun, startTeamRun } from '../team/engine.js';
16
16
  import { detectClis } from '../team/cli-models.js';
17
17
  import { dispatchRunner } from '../team/runners.js';
18
+ import { splitCliArgs } from '../team/cli-args.js';
18
19
  import { listTeamRuns, readTeamJournal } from '../team/journal.js';
20
+ import { DEFAULT_MISSIONS, allAgentsOf, effectiveOrder } from '../team/types.js';
19
21
  import { mkdirSync, writeFileSync } from 'node:fs';
20
22
  import { dirname } from 'node:path';
21
23
  const GUI_DIR = resolve(fileURLToPath(new URL('../../../gui/', import.meta.url)));
@@ -27,7 +29,7 @@ const MAX_UPLOAD_BYTES = 2 * 1024 ** 3, MAX_PENDING_UPLOADS = 100, MAX_ATTACHMEN
27
29
  const UPLOAD_ID_RE = /^[0-9a-f]{24}$/, ATTACHMENT_NAME_RE = /^[^\\/\0]{1,160}$/;
28
30
  /** Shown inline (thumbnails / new tab); every other attachment is sent as a download so the browser never runs it. */
29
31
  const INLINE_IMAGE = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp' };
30
- const allAgents = (c) => [c.director, ...c.teams.ba, ...c.teams.implement, ...c.teams.qc];
32
+ const allAgents = allAgentsOf;
31
33
  function json(res, status, body) {
32
34
  const s = JSON.stringify(body);
33
35
  res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store', 'content-length': Buffer.byteLength(s) });
@@ -83,7 +85,7 @@ export async function startGuiServer(opts) {
83
85
  const loadConfig = () => { const r = loadTeamConfig(root); return r.ok ? r.config : defaultTeamConfig(); };
84
86
  const publicConfig = (c) => {
85
87
  const dec = (a) => ({ ...a, hasKey: a.apiKeyRef ? hasSecret(a.apiKeyRef) : false });
86
- return { version: 1, director: dec(c.director), teams: { ba: c.teams.ba.map(dec), implement: c.teams.implement.map(dec), qc: c.teams.qc.map(dec) }, limits: c.limits };
88
+ return { version: 1, director: dec(c.director), teams: { ba: c.teams.ba.map(dec), implement: c.teams.implement.map(dec), qc: c.teams.qc.map(dec) }, ...(c.extraTeams?.length ? { extraTeams: c.extraTeams.map(t => ({ ...t, agents: t.agents.map(dec) })) } : {}), ...(c.order ? { order: c.order } : {}), ...(c.lanes?.length ? { lanes: c.lanes } : {}), ...(c.directorReview === false ? { directorReview: false } : {}), ...(c.systemPrompt ? { systemPrompt: c.systemPrompt } : {}), ...(c.missions ? { missions: c.missions } : {}), limits: c.limits };
87
89
  };
88
90
  const runDirOf = (id) => {
89
91
  if (id === 'current')
@@ -118,7 +120,7 @@ export async function startGuiServer(opts) {
118
120
  uploads.delete(i);
119
121
  }
120
122
  } };
121
- let checks = 0;
123
+ let checks = 0, enhancing = false;
122
124
  async function api(req, res, url) {
123
125
  const m = req.method ?? 'GET', p = url.pathname;
124
126
  if (m === 'GET' && p === '/api/events') {
@@ -200,7 +202,8 @@ export async function startGuiServer(opts) {
200
202
  const goal = first?.type === 'run.started' ? first.goal : '';
201
203
  const outcome = last?.type === 'run.completed' ? last.outcome : 'incomplete';
202
204
  const durationMs = first && last ? Math.max(0, Date.parse(last.at) - Date.parse(first.at)) : 0;
203
- return { runId: r.runId, goal, outcome, startedAt: first?.at ?? null, durationMs, simulated: first?.type === 'run.started' ? first.simulated : false };
205
+ const lane = ev.find(e => e.type === 'lane.chosen');
206
+ 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 };
204
207
  });
205
208
  return json(res, 200, { runs });
206
209
  }
@@ -243,7 +246,10 @@ export async function startGuiServer(opts) {
243
246
  if (!goal)
244
247
  return json(res, 400, { error: 'goal required' });
245
248
  const simulated = b['simulated'] === true;
246
- const handle = startTeamRun({ projectRoot: root, goal, config: loadConfig(), simulated, attachments: files });
249
+ const cfgNow = loadConfig(), laneId = typeof b['lane'] === 'string' ? b['lane'] : '';
250
+ if (laneId && !(cfgNow.lanes ?? []).some(l => l.id === laneId))
251
+ return json(res, 400, { error: `unknown lane "${laneId.slice(0, 40)}"` });
252
+ const handle = startTeamRun({ projectRoot: root, goal, config: cfgNow, simulated, attachments: files, ...(laneId ? { lane: laneId } : {}) });
247
253
  release(b['attachments']);
248
254
  attach(handle, goal, simulated);
249
255
  return json(res, 200, { runId: handle.runId });
@@ -301,11 +307,22 @@ export async function startGuiServer(opts) {
301
307
  return json(res, 400, { error: 'cli must be claude-code, codex or omp' });
302
308
  if (model !== null && (typeof model !== 'string' || !/^[A-Za-z0-9._:\/@\[\]-]{1,120}$/.test(model)))
303
309
  return json(res, 400, { error: 'invalid model name' });
310
+ const rawArgs = b['cliArgs'];
311
+ let cliArgs;
312
+ if (rawArgs !== undefined && rawArgs !== null && rawArgs !== '') {
313
+ if (typeof rawArgs !== 'string' || rawArgs.length > 500 || /[\n\r\0]/.test(rawArgs))
314
+ return json(res, 400, { error: 'extra CLI arguments must be one line of at most 500 characters' });
315
+ const sp = splitCliArgs(rawArgs);
316
+ if (!sp.ok)
317
+ return json(res, 400, { error: `extra CLI arguments ${sp.error}; close the quote or remove it` });
318
+ if (rawArgs.trim())
319
+ cliArgs = rawArgs.trim();
320
+ }
304
321
  if (checks >= 3)
305
322
  return json(res, 429, { error: 'too many checks running; wait for one to finish' });
306
323
  checks++;
307
324
  try {
308
- const r = await dispatchRunner({ id: 'check', name: 'check', team: 'qc', cli, model, access: 'read' }, 'Reply with the single word OK. Do not use any tools.', { cwd: root, timeoutMs: 90_000 });
325
+ const r = await dispatchRunner({ id: 'check', name: 'check', team: 'qc', cli, model, access: 'read', ...(cliArgs ? { cliArgs } : {}) }, 'Reply with the single word OK. Do not use any tools.', { cwd: root, timeoutMs: 90_000 });
309
326
  return json(res, 200, r.ok ? { ok: true } : { ok: false, reason: r.reason });
310
327
  }
311
328
  finally {
@@ -326,6 +343,55 @@ export async function startGuiServer(opts) {
326
343
  release(b['attachments']);
327
344
  return json(res, 200, { ok: true });
328
345
  }
346
+ if (m === 'POST' && p === '/api/runs/current/proceed') {
347
+ if (!isRunning() || !current)
348
+ return json(res, 409, { error: 'no active run' });
349
+ if (!current.handle.proceedWithAssumptions)
350
+ return json(res, 409, { error: 'this run cannot proceed with assumptions' });
351
+ current.handle.proceedWithAssumptions();
352
+ return json(res, 200, { ok: true });
353
+ }
354
+ if (m === 'POST' && p === '/api/enhance-prompt') {
355
+ // One read-only turn of the Director's CLI that rewrites a draft. Own process, so it also works while a run is active. Never applied automatically.
356
+ const b = obj(await readBody(req)), kind = b['kind'], text = typeof b['text'] === 'string' ? b['text'] : '';
357
+ if (kind !== 'system' && kind !== 'mission' && kind !== 'persona' && kind !== 'lane')
358
+ return json(res, 400, { error: 'kind must be system, mission, persona or lane' });
359
+ if (!text.trim())
360
+ return json(res, 400, { error: 'text required' });
361
+ if (text.length > (kind === 'system' ? 8000 : 4000))
362
+ return json(res, 400, { error: 'text is too long' });
363
+ if (text.includes('\0'))
364
+ return json(res, 400, { error: 'text must not contain NUL characters' });
365
+ if (enhancing)
366
+ return json(res, 429, { error: 'another enhance is running; wait for it to finish' });
367
+ const cfg = loadConfig(), ids = obj(b['ids']), teamName = (id) => { const x = typeof id === 'string' ? id : ''; return x === 'ba' ? 'BA' : x === 'implement' ? 'Implement' : x === 'qc' ? 'QC' : (cfg.extraTeams ?? []).find(t => t.id === x)?.name ?? x; };
368
+ const missionOf = (id) => (cfg.extraTeams ?? []).find(t => t.id === id)?.mission ?? cfg.missions?.[id] ?? DEFAULT_MISSIONS[id] ?? '';
369
+ const allIds = ['ba', 'implement', 'qc', ...(cfg.extraTeams ?? []).map(t => t.id)];
370
+ const teamId = typeof ids['team'] === 'string' ? ids['team'] : '';
371
+ const others = allIds.filter(i => i !== teamId).map(i => `- ${teamName(i)}: ${missionOf(i)}`).join('\n');
372
+ const ctx = kind === 'mission' ? `This is the mission of team "${teamName(teamId)}" (position ${Math.max(0, effectiveOrder(cfg).indexOf(teamId)) + 1} of ${effectiveOrder(cfg).length}). Other teams:\n${others}`
373
+ : kind === 'persona' ? `This is the persona of the agent "${typeof ids['agent'] === 'string' ? ids['agent'].slice(0, 60) : 'agent'}" in team "${teamName(teamId)}". The team mission: ${missionOf(teamId)}`
374
+ : kind === 'lane' ? `This is the "when to use" text of a lane (it tells the Director which requests belong in the lane). Other lanes:\n${(cfg.lanes ?? []).filter(l => l.id !== ids['lane']).map(l => `- ${l.name}: ${l.when}`).join('\n') || '(none)'}`
375
+ : `These are project-wide instructions sent to every agent. The teams:\n${allIds.map(i => `- ${teamName(i)}`).join('\n')}`;
376
+ const words = kind === 'system' ? 400 : 200;
377
+ const d = cfg.director;
378
+ if (d.cli === 'auto' || d.cli === 'simulated') { // offline / demo: deterministic rewrite
379
+ const t = text.trim().replace(/\s+/g, ' ');
380
+ return json(res, 200, { ok: true, proposal: (`${t.charAt(0).toUpperCase()}${t.slice(1)}`.replace(/[.!?]*$/, '') + '. Be specific, keep to this scope and report anything unclear.').slice(0, 8000) });
381
+ }
382
+ const prompt = `Rewrite the DRAFT below into clear, specific, non-contradictory instructions. Rules: write in the same language as the draft; keep every intent of the draft; add nothing new; at most about ${words} words; output ONLY the rewritten text, with no preface, no quotes and no commentary. Do not use any tools.\nCONTEXT: ${ctx}\nDRAFT:\n${text}`;
383
+ enhancing = true;
384
+ try {
385
+ const r = await dispatchRunner({ ...d, access: 'read' }, prompt, { cwd: root, timeoutMs: Math.min(cfg.limits.agentTimeoutMs, 120_000) });
386
+ if (!r.ok)
387
+ return json(res, 200, { ok: false, reason: r.reason });
388
+ const out = r.text.trim().slice(0, kind === 'system' ? 8000 : 4000);
389
+ return json(res, 200, out ? { ok: true, proposal: out } : { ok: false, reason: 'the agent returned no text' });
390
+ }
391
+ finally {
392
+ enhancing = false;
393
+ }
394
+ }
329
395
  if (m === 'POST' && p === '/api/runs/current/stop') {
330
396
  if (!isRunning() || !current)
331
397
  return json(res, 409, { error: 'no active run' });
@@ -0,0 +1,12 @@
1
+ /** Splits `text` on whitespace; single and double quotes group; a backslash escapes the next character outside quotes and inside double quotes. No ~ or $VAR expansion. */
2
+ export declare function splitCliArgs(text: string): {
3
+ ok: true;
4
+ args: string[];
5
+ } | {
6
+ ok: false;
7
+ error: string;
8
+ };
9
+ /** Home-folder shorthand as a shell would resolve it: a leading `~` / `~/` (also right after `--flag=`), and `$HOME` / `${HOME}`. No other variable is expanded. */
10
+ export declare function expandHome(token: string, home: string): string;
11
+ /** Tokens for an agent, home shorthand expanded; a value that does not split (cannot happen after parseTeamConfig) yields none. */
12
+ export declare const cliArgTokens: (cliArgs: string | undefined, home?: string) => string[];
@@ -0,0 +1,69 @@
1
+ import { homedir } from 'node:os';
2
+ // Per-agent "extra CLI arguments": a shell-like splitter (no shell is ever involved; tokens go straight into the spawn argv array).
3
+ /** Splits `text` on whitespace; single and double quotes group; a backslash escapes the next character outside quotes and inside double quotes. No ~ or $VAR expansion. */
4
+ export function splitCliArgs(text) {
5
+ const args = [];
6
+ let cur = '', has = false, quote = null;
7
+ for (let i = 0; i < text.length; i++) {
8
+ const c = text[i];
9
+ if (quote === "'") {
10
+ if (c === "'")
11
+ quote = null;
12
+ else
13
+ cur += c;
14
+ continue;
15
+ }
16
+ if (c === '\\') {
17
+ if (i + 1 >= text.length)
18
+ return { ok: false, error: 'ends with a lone backslash' };
19
+ cur += text[++i];
20
+ has = true;
21
+ continue;
22
+ }
23
+ if (quote === '"') {
24
+ if (c === '"')
25
+ quote = null;
26
+ else
27
+ cur += c;
28
+ continue;
29
+ }
30
+ if (c === '"' || c === "'") {
31
+ quote = c;
32
+ has = true;
33
+ continue;
34
+ }
35
+ if (/\s/.test(c)) {
36
+ if (has) {
37
+ args.push(cur);
38
+ cur = '';
39
+ has = false;
40
+ }
41
+ continue;
42
+ }
43
+ cur += c;
44
+ has = true;
45
+ }
46
+ if (quote)
47
+ return { ok: false, error: `has an unterminated ${quote === '"' ? 'double' : 'single'} quote` };
48
+ if (has)
49
+ args.push(cur);
50
+ return { ok: true, args };
51
+ }
52
+ /** Home-folder shorthand as a shell would resolve it: a leading `~` / `~/` (also right after `--flag=`), and `$HOME` / `${HOME}`. No other variable is expanded. */
53
+ export function expandHome(token, home) {
54
+ const t = token.replace(/\$\{HOME\}|\$HOME(?![A-Za-z0-9_])/g, () => home);
55
+ if (t === '~')
56
+ return home;
57
+ if (t.startsWith('~/'))
58
+ return home + t.slice(1);
59
+ const m = /^(--?[A-Za-z0-9][A-Za-z0-9_-]*=)~(\/.*)?$/.exec(t);
60
+ return m ? `${m[1]}${home}${m[2] ?? ''}` : t;
61
+ }
62
+ /** Tokens for an agent, home shorthand expanded; a value that does not split (cannot happen after parseTeamConfig) yields none. */
63
+ export const cliArgTokens = (cliArgs, home = homedir()) => {
64
+ if (!cliArgs || !cliArgs.trim())
65
+ return [];
66
+ const r = splitCliArgs(cliArgs);
67
+ return r.ok ? r.args.map(a => expandHome(a, home)) : [];
68
+ };
69
+ //# sourceMappingURL=cli-args.js.map
@@ -1,6 +1,7 @@
1
1
  // Team config: defaults, strict validation, load/write of <root>/.ckit/team.json.
2
2
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
3
  import { dirname, join } from 'node:path';
4
+ import { splitCliArgs } from './cli-args.js';
4
5
  const agent = (id, name, team, cli, access) => ({ id, name, team, cli, model: null, access });
5
6
  export function defaultTeamConfig() {
6
7
  return {
@@ -29,11 +30,12 @@ export function parseTeamConfig(json) {
29
30
  return null;
30
31
  }
31
32
  const n = errors.length;
33
+ const cliArgsRaw = raw['cliArgs'];
32
34
  const id = raw['id'], name = raw['name'], cli = raw['cli'], model = raw['model'] ?? null, access = raw['access'] ?? 'read', persona = raw['persona'], short = raw['short'];
33
35
  if (typeof id !== 'string' || !ID_RE.test(id))
34
36
  errors.push(`${path}.id must match ${ID_RE}`);
35
37
  else if (seen.has(id))
36
- errors.push(`${path}.id "${id}" is not unique`);
38
+ errors.push(`${path}.id "${id}" is already used by another agent; every agent id must be unique across all teams (change this id, e.g. "${id}-2")`);
37
39
  else
38
40
  seen.add(id);
39
41
  if (typeof name !== 'string' || !name.trim())
@@ -43,7 +45,7 @@ export function parseTeamConfig(json) {
43
45
  else if (cli === 'auto' && team !== 'director')
44
46
  errors.push(`${path}.cli "auto" is only valid for the director`);
45
47
  if (raw['team'] !== undefined && raw['team'] !== team)
46
- errors.push(`${path}.team must be "${team}"`);
48
+ errors.push(`${path}.team is "${String(raw['team'])}" but this agent sits in team "${team}"; set team to "${team}" or leave it out`);
47
49
  if (model !== null && (typeof model !== 'string' || !model.trim()))
48
50
  errors.push(`${path}.model must be a string or null`);
49
51
  if (access !== 'read' && access !== 'write')
@@ -52,6 +54,22 @@ export function parseTeamConfig(json) {
52
54
  errors.push(`${path}.persona must be a string`);
53
55
  if (short !== undefined && (typeof short !== 'string' || !/^[\p{L}\p{N}]{1,4}$/u.test(short)))
54
56
  errors.push(`${path}.short must be 1-4 letters or digits`);
57
+ let cliArgs;
58
+ if (cliArgsRaw !== undefined && cliArgsRaw !== null) {
59
+ if (typeof cliArgsRaw !== 'string')
60
+ errors.push(`${path}.cliArgs must be a string`);
61
+ else if (cliArgsRaw.length > 500)
62
+ errors.push(`${path}.cliArgs is ${cliArgsRaw.length} characters; the limit is 500`);
63
+ else if (/[\n\r\0]/.test(cliArgsRaw))
64
+ errors.push(`${path}.cliArgs must be a single line (no line breaks or NUL characters)`);
65
+ else if (cliArgsRaw.trim()) {
66
+ const sp = splitCliArgs(cliArgsRaw);
67
+ if (!sp.ok)
68
+ errors.push(`${path}.cliArgs ${sp.error}; close the quote or remove it`);
69
+ else
70
+ cliArgs = cliArgsRaw.trim();
71
+ }
72
+ }
55
73
  const baseUrl = raw['baseUrl'], apiKeyRef = raw['apiKeyRef'];
56
74
  if (baseUrl !== undefined && (typeof baseUrl !== 'string' || !/^https?:\/\/[^\s/]+/i.test(baseUrl)))
57
75
  errors.push(`${path}.baseUrl must be an http(s) URL`);
@@ -59,19 +77,180 @@ export function parseTeamConfig(json) {
59
77
  errors.push(`${path}.apiKeyRef must match /^[A-Za-z0-9_-]{1,64}$/`);
60
78
  if (errors.length > n)
61
79
  return null;
62
- return { id: id, name: name, team, cli: cli, model: model, access: access, ...(typeof persona === 'string' ? { persona } : {}), ...(typeof short === 'string' ? { short: short.toUpperCase() } : {}), ...(typeof baseUrl === 'string' ? { baseUrl: baseUrl.replace(/\/+$/, '') } : {}), ...(typeof apiKeyRef === 'string' ? { apiKeyRef } : {}) };
80
+ return { id: id, name: name, team, cli: cli, model: model, access: access, ...(typeof persona === 'string' ? { persona } : {}), ...(typeof short === 'string' ? { short: short.toUpperCase() } : {}), ...(cliArgs ? { cliArgs } : {}), ...(typeof baseUrl === 'string' ? { baseUrl: baseUrl.replace(/\/+$/, '') } : {}), ...(typeof apiKeyRef === 'string' ? { apiKeyRef } : {}) };
63
81
  };
64
82
  const director = parseAgent(json['director'], 'director', 'director');
65
- const teams = isObj(json['teams']) ? json['teams'] : (errors.push('teams must be an object'), {});
83
+ const teams = json['teams'] === undefined ? {} : isObj(json['teams']) ? json['teams'] : (errors.push('teams must be an object'), {});
84
+ for (const k of Object.keys(teams))
85
+ if (k !== 'ba' && k !== 'implement' && k !== 'qc')
86
+ errors.push(`teams.${k} is not a built-in team: "teams" only holds ba, implement and qc. To add your own team use the "+ Add team" button in Config, or put it under "extraTeams" ({"id": "${k}", "name": "...", "mission": "...", "runAfter": "implement", "agents": [...]}) and give its agents new unique ids`);
66
87
  const list = (team) => {
67
- const raw = teams[team];
68
- if (!Array.isArray(raw) || raw.length < 1) {
69
- errors.push(`teams.${team} needs at least one agent`);
88
+ const raw = teams[team] ?? [];
89
+ if (!Array.isArray(raw)) {
90
+ errors.push(`teams.${team} must be an array of agents (empty or absent = no ${team} team)`);
70
91
  return [];
71
92
  }
72
93
  return raw.map((r, i) => parseAgent(r, team, `teams.${team}[${i}]`)).filter((a) => a !== null);
73
94
  };
74
95
  const ba = list('ba'), implement = list('implement'), qc = list('qc');
96
+ const missions = {};
97
+ if (json['missions'] !== undefined) {
98
+ if (!isObj(json['missions']))
99
+ errors.push('missions must be an object like {"qc": "..."}');
100
+ else
101
+ for (const k of Object.keys(json['missions'])) {
102
+ const v = json['missions'][k];
103
+ if (k !== 'ba' && k !== 'implement' && k !== 'qc')
104
+ errors.push(`missions.${k} is not a built-in team (use ba, implement or qc; extra teams carry their own mission)`);
105
+ else if (typeof v !== 'string' || !v.trim())
106
+ errors.push(`missions.${k} must be a non-empty string`);
107
+ else
108
+ missions[k] = v.trim();
109
+ }
110
+ }
111
+ const extraTeams = [];
112
+ const rawExtra = json['extraTeams'];
113
+ if (rawExtra !== undefined) {
114
+ if (!Array.isArray(rawExtra))
115
+ errors.push('extraTeams must be an array');
116
+ else {
117
+ const teamIds = new Set(['director', 'ba', 'implement', 'qc']);
118
+ rawExtra.forEach((t, i) => {
119
+ const path = `extraTeams[${i}]`;
120
+ if (!isObj(t)) {
121
+ errors.push(`${path} must be an object`);
122
+ return;
123
+ }
124
+ const id = t['id'], name = t['name'], mission = t['mission'], runAfter = t['runAfter'];
125
+ let idOk = false;
126
+ if (typeof id !== 'string' || !ID_RE.test(id))
127
+ errors.push(`${path}.id must match ${ID_RE}`);
128
+ else if (teamIds.has(id))
129
+ errors.push(`${path}.id "${id}" is already a team id (director, ba, implement, qc and other extra teams are taken)`);
130
+ else {
131
+ teamIds.add(id);
132
+ idOk = true;
133
+ }
134
+ if (typeof name !== 'string' || !name.trim())
135
+ errors.push(`${path}.name must be a non-empty string`);
136
+ if (typeof mission !== 'string' || !mission.trim())
137
+ errors.push(`${path}.mission must say what this team does`);
138
+ const raOk = runAfter === undefined || runAfter === 'ba' || runAfter === 'implement' || runAfter === 'qc';
139
+ if (!raOk)
140
+ errors.push(`${path}.runAfter must be ba|implement|qc (old files only; use the top-level "order" list instead)`);
141
+ const rawAgents = t['agents'];
142
+ if (!Array.isArray(rawAgents) || rawAgents.length < 1) {
143
+ errors.push(`${path}.agents needs at least one agent`);
144
+ return;
145
+ }
146
+ const agents = rawAgents.map((r, k) => parseAgent(r, idOk ? id : 'extra', `${path}.agents[${k}]`)).filter((a) => a !== null);
147
+ if (idOk && typeof name === 'string' && name.trim() && typeof mission === 'string' && mission.trim() && raOk && agents.length === rawAgents.length)
148
+ extraTeams.push({ id: id, name: name.trim(), mission: mission.trim(), ...(runAfter ? { runAfter: runAfter } : {}), agents });
149
+ });
150
+ }
151
+ }
152
+ let order;
153
+ if (json['order'] !== undefined) {
154
+ const raw = json['order'];
155
+ if (!Array.isArray(raw))
156
+ errors.push('order must be a list of team ids, e.g. ["ba", "implement", "test", "qc"]');
157
+ else {
158
+ const withAgents = new Set([...(ba.length ? ['ba'] : []), ...(implement.length ? ['implement'] : []), ...(qc.length ? ['qc'] : []), ...extraTeams.map(t => t.id)]);
159
+ const known = new Set([...withAgents, 'ba', 'implement', 'qc', ...extraTeams.map(t => t.id)]);
160
+ const got = new Set(), list = [];
161
+ raw.forEach((v, i) => {
162
+ if (typeof v !== 'string') {
163
+ errors.push(`order[${i}] must be a team id (string)`);
164
+ return;
165
+ }
166
+ if (v === 'director')
167
+ errors.push(`order[${i}] is "director": the Director always comes first and is not part of the list`);
168
+ else if (!known.has(v))
169
+ errors.push(`order[${i}] "${v}" is not a team of this company (known teams: ${[...withAgents].join(', ') || 'none'})`);
170
+ else if (!withAgents.has(v))
171
+ errors.push(`order[${i}] "${v}" has no agents; leave empty teams out of the order`);
172
+ else if (got.has(v))
173
+ errors.push(`order[${i}] "${v}" appears twice; each team must be listed exactly once`);
174
+ else {
175
+ got.add(v);
176
+ list.push(v);
177
+ }
178
+ });
179
+ const missing = [...withAgents].filter(id => !got.has(id));
180
+ if (missing.length)
181
+ errors.push(`order is missing team(s) that have agents: ${missing.join(', ')}; every team with agents must be in the order`);
182
+ order = list;
183
+ }
184
+ }
185
+ let lanes;
186
+ if (json['lanes'] !== undefined && json['lanes'] !== null) {
187
+ const raw = json['lanes'];
188
+ if (!Array.isArray(raw))
189
+ errors.push('lanes must be a list of {id, name, when, order}');
190
+ else if (raw.length) {
191
+ const withAgents = new Set([...(ba.length ? ['ba'] : []), ...(implement.length ? ['implement'] : []), ...(qc.length ? ['qc'] : []), ...extraTeams.map(t => t.id)]);
192
+ const seen = new Set(), list = [];
193
+ raw.forEach((l, i) => {
194
+ const p = `lanes[${i}]`;
195
+ if (!isObj(l)) {
196
+ errors.push(`${p} must be an object`);
197
+ return;
198
+ }
199
+ const id = l['id'], name = l['name'], when = l['when'], ord = l['order'];
200
+ let ok = true;
201
+ if (typeof id !== 'string' || !ID_RE.test(id) || id === 'director') {
202
+ errors.push(`${p}.id must be lowercase letters, digits or dashes`);
203
+ ok = false;
204
+ }
205
+ else if (seen.has(id)) {
206
+ errors.push(`${p}.id "${id}" is used by another lane; lane ids must be unique`);
207
+ ok = false;
208
+ }
209
+ else
210
+ seen.add(id);
211
+ if (typeof name !== 'string' || !name.trim()) {
212
+ errors.push(`${p}.name must not be empty`);
213
+ ok = false;
214
+ }
215
+ if (typeof when !== 'string' || !when.trim()) {
216
+ errors.push(`${p}.when must say what kind of request belongs in this lane`);
217
+ ok = false;
218
+ }
219
+ const got = new Set(), seq = [];
220
+ if (!Array.isArray(ord) || ord.length === 0) {
221
+ errors.push(`${p}${typeof name === 'string' && name.trim() ? ` ("${name.trim()}")` : ''} has no teams; add at least one team or remove the lane`);
222
+ ok = false;
223
+ }
224
+ else
225
+ ord.forEach((v, k) => {
226
+ if (typeof v !== 'string') {
227
+ errors.push(`${p}.order[${k}] must be a team id (string)`);
228
+ ok = false;
229
+ }
230
+ else if (v === 'director') {
231
+ errors.push(`${p}.order[${k}] is "director": the Director is not part of a lane`);
232
+ ok = false;
233
+ }
234
+ else if (!withAgents.has(v)) {
235
+ errors.push(`${p}.order[${k}] "${v}" is not a team with agents (teams: ${[...withAgents].join(', ') || 'none'})`);
236
+ ok = false;
237
+ }
238
+ else if (got.has(v)) {
239
+ errors.push(`${p}.order[${k}] "${v}" appears twice in this lane`);
240
+ ok = false;
241
+ }
242
+ else {
243
+ got.add(v);
244
+ seq.push(v);
245
+ }
246
+ });
247
+ if (ok)
248
+ list.push({ id: id, name: name.trim(), when: when.trim(), order: seq });
249
+ });
250
+ if (list.length === raw.length)
251
+ lanes = list;
252
+ }
253
+ }
75
254
  const lim = isObj(json['limits']) ? json['limits'] : (errors.push('limits must be an object'), {});
76
255
  const int = (key, lo, hi) => {
77
256
  const v = lim[key];
@@ -81,10 +260,28 @@ export function parseTeamConfig(json) {
81
260
  }
82
261
  return v;
83
262
  };
263
+ let directorReview, systemPrompt;
264
+ if (json['directorReview'] !== undefined && json['directorReview'] !== null) {
265
+ if (typeof json['directorReview'] !== 'boolean')
266
+ errors.push('directorReview must be true or false');
267
+ else if (!json['directorReview'])
268
+ directorReview = false; // true is the default: keep the file small
269
+ }
270
+ const sp = json['systemPrompt'];
271
+ if (sp !== undefined && sp !== null) {
272
+ if (typeof sp !== 'string')
273
+ errors.push('systemPrompt must be a string');
274
+ else if (sp.length > 8000)
275
+ errors.push(`systemPrompt is ${sp.length} characters; the limit is 8000`);
276
+ else if (sp.includes('\0'))
277
+ errors.push('systemPrompt must not contain NUL characters');
278
+ else if (sp.trim())
279
+ systemPrompt = sp.trim();
280
+ }
84
281
  const limits = { baRounds: int('baRounds', 1, 10), qcLoops: int('qcLoops', 0, 10), agentTimeoutMs: int('agentTimeoutMs', 1000, 7200000) };
85
282
  if (errors.length || !director)
86
283
  return { ok: false, errors };
87
- return { ok: true, config: { version: 1, director, teams: { ba, implement, qc }, limits } };
284
+ return { ok: true, config: { version: 1, director, teams: { ba, implement, qc }, ...(Object.keys(missions).length ? { missions } : {}), ...(extraTeams.length ? { extraTeams } : {}), ...(order ? { order } : {}), ...(lanes ? { lanes } : {}), ...(directorReview === false ? { directorReview } : {}), ...(systemPrompt ? { systemPrompt } : {}), limits } };
88
285
  }
89
286
  export const teamConfigPath = (root) => join(root, '.ckit', 'team.json');
90
287
  /** Missing file -> default. Present but invalid/unreadable -> ok:false with errors (never silently default). */
@@ -1,6 +1,6 @@
1
1
  import { type AttachmentInput } from './attachments.js';
2
2
  import { type AgentRunner } from './runners.js';
3
- import type { TeamConfig, TeamRunHandle } from './types.js';
3
+ import { type TeamConfig, type TeamRunHandle } from './types.js';
4
4
  export interface StartTeamRunOptions {
5
5
  readonly projectRoot: string;
6
6
  readonly goal: string;
@@ -13,6 +13,8 @@ export interface StartTeamRunOptions {
13
13
  readonly simSpeed?: number;
14
14
  /** Files the owner attached to the request (any type). Copied into the run folder; every agent turn is told where they are. */
15
15
  readonly attachments?: readonly AttachmentInput[];
16
+ /** Lane id fixed by the owner (only when the config has lanes); absent = the Director decides. */
17
+ readonly lane?: string;
16
18
  }
17
19
  /** Pure rule-based owner-chat decision (director cli 'auto', and the fallback for model directors). */
18
20
  export declare function ruleDecision(text: string): {
@@ -21,6 +23,22 @@ export declare function ruleDecision(text: string): {
21
23
  };
22
24
  /** Last `VERDICT: PASS|FAIL` wins; no verdict at all counts as FAIL (conservative). */
23
25
  export declare function parseVerdict(text: string): 'PASS' | 'FAIL';
26
+ export interface DirectorDecision {
27
+ readonly kind: 'proceed' | 'need' | 'cannot';
28
+ readonly body: string;
29
+ readonly questions: string;
30
+ readonly assumptions: string;
31
+ readonly reason: string;
32
+ readonly alternatives: string;
33
+ }
34
+ /** The Director's first-turn decision line (lenient: case, bullets, bold, dashes). No decision line = PROCEED. Never throws. */
35
+ export declare function parseDirectorDecision(text: string): DirectorDecision;
36
+ export type HandoffSection = 'DONE' | 'DECISIONS' | 'OPEN' | 'FOR YOU';
37
+ export declare const HANDOFF_SECTIONS: readonly HandoffSection[];
38
+ /** Reads the four handoff sections out of a team lead's message. null when any is missing (callers fall back to the raw message). Never throws. */
39
+ export declare function parseHandoff(text: string): Record<HandoffSection, string> | null;
40
+ /** Last `REVIEW: PASS|FAIL` wins; null when no verdict line exists. */
41
+ export declare function parseReview(text: string): 'PASS' | 'FAIL' | null;
24
42
  export declare function startTeamRun(opts: StartTeamRunOptions): TeamRunHandle;
25
43
  /** Re-emits a journal with original relative timing / speed (gaps capped at 1.5s/speed). */
26
44
  export declare function replayTeamRun(runDir: string, opts?: {