@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.
@@ -59,6 +59,10 @@ export declare function codexWorkerEnv(processEnv: Readonly<Record<string, strin
59
59
  export declare function runCodex(agent: AgentConfig, prompt: string, opts: AgentRunOptions): Promise<AgentRunResult>;
60
60
  /** Pure: claude stream-json frame -> short activity lines. */
61
61
  export declare function claudeFrameActivity(frame: unknown): string[];
62
+ /** The executor spec with the agent's extra CLI arguments appended after CKit's own flags (runExecutor appends the prompt last). */
63
+ export declare const withCliArgs: <T extends {
64
+ readonly args: readonly string[];
65
+ }>(spec: T, agent: AgentConfig) => T;
62
66
  export declare function runExecutorAgent(agent: AgentConfig, prompt: string, opts: AgentRunOptions): Promise<AgentRunResult>;
63
67
  export { parseExecutorOutput };
64
68
  export declare function runApiAgent(agent: AgentConfig, prompt: string, opts: AgentRunOptions & {
@@ -73,6 +77,8 @@ export declare function simHeader(h: {
73
77
  turn: number;
74
78
  turns: number;
75
79
  final: boolean;
80
+ phase?: string;
81
+ round?: number;
76
82
  }): string;
77
83
  export declare function createSimulatedRunner(options?: {
78
84
  readonly speed?: number;
@@ -7,6 +7,7 @@ import { claudeSubagentObservations, envBoundaryNote, executorEnvironment, execu
7
7
  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
+ import { cliArgTokens } from './cli-args.js';
10
11
  const oneLine = (s, max = 120) => { const t = s.replace(/\s+/g, ' ').trim(); return t.length > max ? `${t.slice(0, max - 1)}…` : t; };
11
12
  /** 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. */
12
13
  export const advisorKeyOf = (cwd) => {
@@ -70,8 +71,9 @@ function findOnPath(name, env) {
70
71
  return null;
71
72
  }
72
73
  export function codexArgs(agent, cwd, prompt, images = []) {
74
+ // agent.cliArgs go after CKit's own flags and before the prompt positional.
73
75
  // `-i` takes several values, so it goes after the prompt: placed before, it would swallow the prompt as one more image path.
74
- return ['exec', '--json', '--skip-git-repo-check', '--ephemeral', '-s', agent.access === 'write' ? 'workspace-write' : 'read-only', '-C', cwd, ...(agent.model ? ['-m', agent.model] : []), prompt.startsWith('-') ? ` ${prompt}` : prompt, ...images.slice(0, 8).flatMap(f => ['-i', f])];
76
+ return ['exec', '--json', '--skip-git-repo-check', '--ephemeral', '-s', agent.access === 'write' ? 'workspace-write' : 'read-only', '-C', cwd, ...(agent.model ? ['-m', agent.model] : []), ...cliArgTokens(agent.cliArgs), prompt.startsWith('-') ? ` ${prompt}` : prompt, ...images.slice(0, 8).flatMap(f => ['-i', f])];
75
77
  }
76
78
  /**
77
79
  * Codex worker env. Same boundary as the other workers, with one documented exemption (mirrors the claude-code allowlist): a variable that
@@ -217,10 +219,13 @@ export function claudeFrameActivity(frame) {
217
219
  }
218
220
  return out;
219
221
  }
222
+ /** The executor spec with the agent's extra CLI arguments appended after CKit's own flags (runExecutor appends the prompt last). */
223
+ export const withCliArgs = (spec, agent) => { const extra = cliArgTokens(agent.cliArgs); return extra.length ? { ...spec, args: [...spec.args, ...extra] } : spec; };
220
224
  export async function runExecutorAgent(agent, prompt, opts) {
221
225
  const kind = agent.cli === 'omp' ? 'omp' : 'claude-code';
222
- const spec = selectExecutor({ executor: kind, executorModel: agent.model, executorPermissionMode: kind === 'claude-code' && agent.access === 'write' ? 'acceptEdits' : null });
226
+ const base = selectExecutor({ executor: kind, executorModel: agent.model, executorPermissionMode: kind === 'claude-code' && agent.access === 'write' ? 'acceptEdits' : null });
223
227
  const env = opts.env ?? executorEnvironment(process.env, advisorKeyOf(opts.cwd), kind);
228
+ const spec = withCliArgs(base, agent);
224
229
  let path;
225
230
  try {
226
231
  path = resolveExecutable(spec, { executorPath: null }, env);
@@ -315,7 +320,7 @@ export const dispatchRunner = (agent, prompt, opts) => {
315
320
  // ---- simulated (offline demo) ----
316
321
  /** Engine prompts begin with `[[ckit-team stage=<s> loop=<n> turn=<i>/<n> final=<0|1>]]` and carry a `GOAL: ...` line; the simulator keys off those. */
317
322
  export function simHeader(h) {
318
- return `[[ckit-team stage=${h.stage} loop=${h.loop} turn=${h.turn}/${h.turns} final=${h.final ? 1 : 0}]]`;
323
+ return `[[ckit-team stage=${h.stage} loop=${h.loop} turn=${h.turn}/${h.turns} final=${h.final ? 1 : 0}${h.phase ? ` phase=${h.phase} round=${h.round ?? 1}` : ''}]]`;
319
324
  }
320
325
  const sleep = (ms, signal) => new Promise(res => {
321
326
  if (signal?.aborted) {
@@ -332,10 +337,12 @@ export function createSimulatedRunner(options = {}) {
332
337
  const envSpeed = Number(process.env['CKIT_TEAM_SIM_SPEED']);
333
338
  const speed = options.speed ?? (envSpeed > 0 ? envSpeed : 1);
334
339
  return async (agent, prompt, opts) => {
335
- const hm = /\[\[ckit-team stage=(\S+) loop=(\d+) turn=(\d+)\/(\d+) final=([01])\]\]/.exec(prompt);
340
+ const hm = /\[\[ckit-team stage=(\S+) loop=(\d+) turn=(\d+)\/(\d+) final=([01])(?: phase=(\S+) round=(\d+))?\]\]/.exec(prompt);
336
341
  const stage = hm?.[1] ?? 'unknown', loop = Number(hm?.[2] ?? 1), turn = Number(hm?.[3] ?? 1), final = hm?.[5] === '1';
342
+ const phase = hm?.[6] ?? '', round = Number(hm?.[7] ?? 1);
337
343
  const goal = oneLine(/^GOAL: (.*)$/m.exec(prompt)?.[1] ?? 'the request', 100);
338
344
  const plan = simPlan(agent, stage, loop, turn);
345
+ const flags = { phase, round, handoff: /HANDOFF: end your message with ONE structured handoff/.test(prompt), hand: /"### HANDOFF (.+?) -> (.+?)"/.exec(prompt), laneFail: false, answered: /ANSWER FROM/.test(prompt), sentBack: /SENT BACK TO YOU/.test(prompt), goalFlags: /^GOAL: (.*)$/m.exec(prompt)?.[1] ?? '' };
339
346
  const totalMs = (2500 + hashOf(agent.id + goal) % 2500) / speed, cancelled = () => opts.signal?.aborted === true;
340
347
  const total = plan.steps.length, per = totalMs / (total + 1);
341
348
  for (let i = 0; i < total; i++) {
@@ -370,7 +377,7 @@ export function createSimulatedRunner(options = {}) {
370
377
  await sleep(per, opts.signal);
371
378
  if (cancelled())
372
379
  return { ok: false, reason: 'cancelled' };
373
- return { ok: true, text: simText(agent, stage, loop, turn, final, goal), tokens: 400 + hashOf(agent.id + prompt.length) % 900 };
380
+ return { ok: true, text: simWrap(agent, stage, loop, turn, final, goal, flags), tokens: 400 + hashOf(agent.id + prompt.length) % 900 };
374
381
  };
375
382
  }
376
383
  function simPlan(agent, stage, loop, turn) {
@@ -380,11 +387,12 @@ function simPlan(agent, stage, loop, turn) {
380
387
  { label: 'Drafting acceptance criteria', activity: ['thinking: who is the user and what is the smallest useful scope?', 'thinking: listing testable acceptance criteria'] },
381
388
  { label: 'Replying to partner', activity: ['comparing with the partner proposal'] }
382
389
  ] };
383
- if (stage === 'ba-review')
390
+ if (stage === 'ask-answer')
391
+ return { steps: [{ label: 'Reading the question', activity: ['re-reading my earlier output'] }, { label: 'Answering', activity: ['thinking: short answer, no rework'] }] };
392
+ if (stage === 'extra-team')
384
393
  return { steps: [
385
- { label: 'Reading the handoff', activity: ['reading handoff-ba.md'] },
386
- { label: 'Checking acceptance criteria', activity: ['$ git diff --stat', 'thinking: every criterion has evidence'] },
387
- { label: 'Writing the review', activity: ['drafting review notes'] }
394
+ { label: 'Reading the context', activity: ['reading handoff-ba.md', 'thinking: what does my team need to check?'] },
395
+ { label: 'Doing the team task', activity: ['$ npm test', 'thinking: summarising findings'] }
388
396
  ] };
389
397
  if (agent.team === 'implement')
390
398
  return { steps: [
@@ -408,9 +416,29 @@ function simPlan(agent, stage, loop, turn) {
408
416
  { label: 'Writing verdict', activity: ['drafting verdict'] }
409
417
  ] };
410
418
  }
411
- function simText(agent, stage, loop, turn, final, goal) {
419
+ /** Team protocol around the stage text: discussion rounds (AGREED from round 2), then a structured handoff when the prompt asks for one. */
420
+ function simWrap(agent, stage, loop, turn, final, goal, flags) {
421
+ if (stage === 'ask-answer' || flags.phase === '')
422
+ return simText(agent, stage, loop, turn, final, goal, flags);
423
+ const base = simText(agent, stage, loop, turn, final, goal, flags);
424
+ if (/^(ASK PREVIOUS|RETURN TO PREVIOUS)/m.test(base))
425
+ return base;
426
+ if (flags.phase === 'discuss') {
427
+ const own = flags.round === 1 ? `My take on "${goal}" (round 1): ${base.split('\n')[0]}` : `Round ${flags.round}: I read my teammates' points, merged them with mine and I accept the common plan.\nAGREED`;
428
+ return stage === 'qc' && /VERDICT/.test(base) ? `${own}\n${base.split('\n').filter(l => /VERDICT/.test(l)).join('\n')}` : own;
429
+ }
430
+ if (!flags.handoff)
431
+ return base;
432
+ const from = flags.hand?.[1] ?? agent.team, to = flags.hand?.[2] ?? 'Director', verdict = base.split('\n').filter(l => /VERDICT/.test(l)).join('\n');
433
+ const body = base.split('\n').filter(l => !/VERDICT/.test(l)).join('\n').trim();
434
+ return `${body}\n\n### HANDOFF ${from} -> ${to}\nDONE: ${oneLineSim(body)}\nDECISIONS: kept to the smallest slice; empty input fails loudly.\nOPEN: ${verdict.includes('FAIL') ? 'acceptance criterion not met yet' : 'nothing'}\nFOR YOU: build on this and report anything unclear.${verdict ? `\n${verdict}` : ''}`;
435
+ }
436
+ const oneLineSim = (s) => s.replace(/\s+/g, ' ').trim().slice(0, 240);
437
+ function simText(agent, stage, loop, turn, final, goal, flags = { answered: false, sentBack: false, goalFlags: '' }) {
438
+ if (stage === 'ask-answer')
439
+ return `Answer: yes, keep to the handoff; empty input must fail loudly and nothing else changes.`;
412
440
  if (stage === 'ba-discussion') {
413
- if (final)
441
+ if (final || flags.phase === 'single' || flags.phase === 'handoff')
414
442
  return `# HANDOFF\n\n## Goal\n${goal}\n\n## Scope\n- Implement the smallest end-to-end slice of the request.\n- Handle empty and invalid input explicitly.\n\n## Acceptance criteria\n- [ ] The requested behaviour works for the happy path\n- [ ] Empty/invalid input returns a clear error\n- [ ] Tests cover both cases and \`npm test\` passes\n\n## Out of scope\n- UI polish, performance tuning, new dependencies\n\n## Risks\n- Ambiguous wording in the request; assumptions are listed above.`;
415
443
  const lines = [
416
444
  `Okay, I read "${goal}" twice. My take: ship the smallest slice first. Quick question though: what should happen when the input is bad or empty?`,
@@ -420,6 +448,14 @@ function simText(agent, stage, loop, turn, final, goal) {
420
448
  ];
421
449
  return lines[Math.min(turn - 1, lines.length - 1)];
422
450
  }
451
+ if (stage === 'extra-team') {
452
+ // Deterministic flow demo: the first pass of a custom team asks the previous team once (unless the goal says [sim-quiet]) and, with [sim-return] in the goal, sends the work back once.
453
+ if (loop === 1 && turn === 1 && !flags.answered && !flags.goalFlags.includes('[sim-quiet]'))
454
+ return `Before I start, one thing is unclear in what I received.\nASK PREVIOUS: should empty input fail loudly or be ignored?`;
455
+ if (loop === 1 && turn === 1 && flags.goalFlags.includes('[sim-return]') && !flags.sentBack)
456
+ return `The work I received is missing a regression test.\nRETURN TO PREVIOUS: add a regression test for empty input`;
457
+ return `${agent.name} (${agent.team}) report${loop > 1 ? ` for pass ${loop}` : ''}: done my part for "${goal}" (turn ${turn}). No blocking issues.`;
458
+ }
423
459
  if (stage === 'implement')
424
460
  return `Implemented "${goal}".\n\nChanged: src/feature.ts (new behaviour), test/feature.test.ts (happy path${loop > 1 ? ', empty input regression' : ''}).${loop > 1 ? '\nAddressed the QC finding: empty input is now validated and rejected with a clear error.' : ''}\nVerify: npm test (all green locally).`;
425
461
  if (stage === 'qc') {
@@ -429,8 +465,6 @@ function simText(agent, stage, loop, turn, final, goal) {
429
465
  return turn === 1 ? `Re-ran the tests and re-read the diff: empty input now throws a clear error and has a regression test. All acceptance criteria are met.\nVERDICT: PASS`
430
466
  : `I agree: the earlier finding is fixed and covered by a test; no new issues found.\nVERDICT: PASS`;
431
467
  }
432
- if (stage === 'ba-review')
433
- return `Checked the deliverable against the handoff: happy path, input validation and tests are all present. Acceptance criteria met; out-of-scope items untouched. Approved for delivery.`;
434
468
  return `${agent.name}: done.`;
435
469
  }
436
470
  //# sourceMappingURL=runners.js.map
@@ -3,16 +3,21 @@ export type AgentCli = 'codex' | 'claude-code' | 'omp' | 'api' | 'auto' | 'simul
3
3
  /** Every agent can read the whole project. read = read only (must not change files); write = read AND change files inside the project (codex workspace-write, claude acceptEdits). Never bypass. */
4
4
  export type AgentAccess = 'read' | 'write';
5
5
  export type TeamId = 'director' | 'ba' | 'implement' | 'qc';
6
+ /** Built-in team ids a custom team can run after. */
7
+ export type BuiltinStageTeam = 'ba' | 'implement' | 'qc';
6
8
  export interface AgentConfig {
7
9
  readonly id: string;
8
10
  readonly name: string;
9
- readonly team: TeamId;
11
+ /** A built-in TeamId, or the id of an extra team (TeamConfig.extraTeams). */
12
+ readonly team: string;
10
13
  readonly cli: AgentCli;
11
14
  readonly model: string | null;
12
15
  readonly access: AgentAccess;
13
16
  /** Optional badge text shown inside the agent's circle in the GUI: 1-4 letters/digits, stored upper-case. Absent = two letters derived from the name. */
14
17
  readonly short?: string;
15
18
  readonly persona?: string;
19
+ /** Optional extra command-line arguments appended to this agent's start command (codex / claude-code / omp), split shell-like, never run through a shell. Absent = none. */
20
+ readonly cliArgs?: string;
16
21
  /** cli 'api' only: per-agent OpenAI-compatible endpoint (must include the version segment, e.g. https://host/v1). Absent = the CKit advisor endpoint. */
17
22
  readonly baseUrl?: string;
18
23
  /** cli 'api' only: name of the stored secret holding this agent's API key (see src/team/secrets.ts); never the key itself. Absent = the CKit advisor key. */
@@ -29,14 +34,49 @@ export interface AttachmentInfo {
29
34
  /** Plain-text version extracted by CKit (.docx/.xlsx/.pptx), when extraction worked. */
30
35
  readonly textPath?: string;
31
36
  }
37
+ /** An owner-defined team that runs as one extra stage after a built-in stage (ba = after the handoff, implement = after each implementation pass, qc = after QC passes). */
38
+ export interface ExtraTeamConfig {
39
+ readonly id: string;
40
+ readonly name: string;
41
+ readonly mission: string;
42
+ /** Legacy placement, still accepted from old files: where the team sat before `order` existed. Ignored once TeamConfig.order is set. Default 'implement'. */
43
+ readonly runAfter?: BuiltinStageTeam;
44
+ readonly agents: readonly AgentConfig[];
45
+ }
46
+ /** What each built-in team does by default; `TeamConfig.missions` overrides per team. The Director sees these in its team roster and every team agent in its prompt. */
47
+ export declare const DEFAULT_MISSIONS: Readonly<Record<BuiltinStageTeam, string>>;
48
+ /** A named route through a subset of the teams. The Director picks one lane per request (the owner may fix it). */
49
+ export interface LaneConfig {
50
+ readonly id: string;
51
+ readonly name: string; /** what kind of request belongs here; the Director reads it */
52
+ readonly when: string; /** 1+ team ids with agents, each once */
53
+ readonly order: readonly string[];
54
+ }
32
55
  export interface TeamConfig {
33
56
  readonly version: 1;
34
57
  readonly director: AgentConfig;
58
+ /** Built-in teams. An empty array = the team is not part of this company (its stage is skipped). Only the director is mandatory. */
35
59
  readonly teams: {
36
60
  readonly ba: readonly AgentConfig[];
37
61
  readonly implement: readonly AgentConfig[];
38
62
  readonly qc: readonly AgentConfig[];
39
63
  };
64
+ /** Optional per-team mission overrides for the built-in teams (default: DEFAULT_MISSIONS). */
65
+ readonly missions?: {
66
+ readonly ba?: string;
67
+ readonly implement?: string;
68
+ readonly qc?: string;
69
+ };
70
+ /** Flow order: every team that has agents (built-in ids ba/implement/qc and extra team ids), each once. Work goes Director -> order[0] -> order[1] ... Absent = derived by effectiveOrder (ba, implement, qc with extra teams placed by runAfter). */
71
+ readonly order?: readonly string[];
72
+ /** Optional lanes. Absent or empty = one flow for every request, using `order`. With lanes, `order` is not used for runs. */
73
+ readonly lanes?: readonly LaneConfig[];
74
+ /** The Director checks the finished work against the original request right before delivery (default on; absent = on; skipped when there are no teams). */
75
+ readonly directorReview?: boolean;
76
+ /** Project-wide owner instructions, put in every agent prompt (max 8000 chars). Absent = prompts are unchanged. */
77
+ readonly systemPrompt?: string;
78
+ /** Optional custom teams; absent = none. */
79
+ readonly extraTeams?: readonly ExtraTeamConfig[];
40
80
  readonly limits: {
41
81
  readonly baRounds: number;
42
82
  readonly qcLoops: number;
@@ -44,8 +84,13 @@ export interface TeamConfig {
44
84
  };
45
85
  }
46
86
  /** Company pipeline stages, in order. */
47
- export declare const STAGES: readonly ['director-intake', 'ba-discussion', 'implement', 'qc', 'ba-review', 'delivery'];
48
- export type Stage = typeof STAGES[number];
87
+ export declare const STAGES: readonly ['director-intake', 'ba-discussion', 'implement', 'qc', 'review', 'delivery'];
88
+ /** `extra-team` is emitted (with a `team` id on stage.changed) for the stage of an owner-defined extra team; it is not part of the fixed STAGES strip. */
89
+ export type Stage = typeof STAGES[number] | 'extra-team';
90
+ /** The flow: ids of the teams that have agents, in run order. `order` wins; without it: ba, implement, qc with extra teams after the stage named by runAfter (default implement). */
91
+ export declare function effectiveOrder(c: TeamConfig): string[];
92
+ /** Every agent of the company: director, built-in teams, then extra teams. */
93
+ export declare const allAgentsOf: (c: TeamConfig) => AgentConfig[];
49
94
  export type AgentState = 'idle' | 'thinking' | 'done' | 'failed' | 'waiting';
50
95
  /** One journal line (JSONL, append-only, `.ckit/team/runs/<runId>/events.jsonl`). All text is secret-redacted before it is written or emitted. */
51
96
  export type TeamEvent = {
@@ -61,7 +106,8 @@ export type TeamEvent = {
61
106
  } | {
62
107
  readonly type: 'stage.changed';
63
108
  readonly stage: Stage;
64
- readonly loop: number;
109
+ readonly loop: number; /** extra-team stage only: the extra team's id */
110
+ readonly team?: string;
65
111
  } | {
66
112
  readonly type: 'agent.started';
67
113
  readonly agentId: string;
@@ -79,7 +125,8 @@ export type TeamEvent = {
79
125
  readonly agentId: string;
80
126
  readonly to: string;
81
127
  readonly text: string;
82
- readonly tokens: number | null;
128
+ readonly tokens: number | null; /** in-team discussion round (1-based); absent for single turns, handoffs and Director turns */
129
+ readonly round?: number;
83
130
  } | {
84
131
  readonly type: 'agent.failed';
85
132
  readonly agentId: string;
@@ -113,15 +160,46 @@ export type TeamEvent = {
113
160
  readonly summary: string;
114
161
  } | {
115
162
  readonly type: 'handoff.created';
116
- readonly from: TeamId;
117
- readonly to: TeamId;
163
+ readonly from: string;
164
+ readonly to: string;
118
165
  readonly title: string;
119
- readonly artifact: string;
166
+ readonly artifact: string; /** the full handoff message (DONE / DECISIONS / OPEN / FOR YOU) */
167
+ readonly text?: string;
168
+ }
169
+ /** A team asked the team before it a question (kind 'ask'; to = 'director' for team 1) or sent the work back to it (kind 'return'). from/to are team ids; reason = the question or the reason. */
170
+ | {
171
+ readonly type: 'flow.back';
172
+ readonly kind: 'ask' | 'return';
173
+ readonly from: string;
174
+ readonly to: string;
175
+ readonly reason: string;
120
176
  } | {
121
177
  readonly type: 'qc.verdict';
122
178
  readonly verdict: 'PASS' | 'FAIL';
123
179
  readonly loop: number;
124
180
  readonly summary: string;
181
+ }
182
+ /** The Director's review of the finished work against the original request (stage 'review'). */
183
+ /** The lane this run takes (only when the config has lanes). */
184
+ | {
185
+ readonly type: 'lane.chosen';
186
+ readonly laneId: string;
187
+ readonly name: string;
188
+ readonly by: 'director' | 'owner' | 'fallback';
189
+ readonly reason: string;
190
+ } | {
191
+ readonly type: 'review.verdict';
192
+ readonly verdict: 'PASS' | 'FAIL';
193
+ readonly loop: number;
194
+ readonly summary: string;
195
+ readonly checklist?: string;
196
+ }
197
+ /** Director triage at intake asked the owner for more information; nothing runs until the owner answers (or presses proceed / stop). */
198
+ | {
199
+ readonly type: 'run.waiting';
200
+ readonly round: number;
201
+ readonly questions: string;
202
+ readonly assumptions: string | null;
125
203
  } | {
126
204
  readonly type: 'user.message';
127
205
  readonly text: string;
@@ -132,7 +210,7 @@ export type TeamEvent = {
132
210
  readonly note: string;
133
211
  } | {
134
212
  readonly type: 'run.completed';
135
- readonly outcome: 'delivered' | 'failed' | 'stopped';
213
+ readonly outcome: 'delivered' | 'failed' | 'stopped' | 'declined';
136
214
  readonly report: string;
137
215
  });
138
216
  export type TeamEventType = TeamEvent['type'];
@@ -152,6 +230,8 @@ export interface TeamRunHandle {
152
230
  }[]): void;
153
231
  /** Stops all agents (kills their process groups) and completes the run as 'stopped'. */
154
232
  stop(): void;
233
+ /** While the Director waits for the owner's answer: carry on with the Director's stated assumptions. No-op otherwise. */
234
+ proceedWithAssumptions?(): void;
155
235
  /** Resolves when the run completes. */
156
- readonly done: Promise<'delivered' | 'failed' | 'stopped'>;
236
+ readonly done: Promise<'delivered' | 'failed' | 'stopped' | 'declined'>;
157
237
  }
@@ -1,5 +1,21 @@
1
1
  // Agent Company ("team mode") shared contract: config shape, journal events and the engine <-> TUI interface.
2
2
  // Engine (src/team/engine.ts, runners.ts, journal.ts, config.ts) and TUI (src/tui/team/*) both import only from here.
3
+ /** What each built-in team does by default; `TeamConfig.missions` overrides per team. The Director sees these in its team roster and every team agent in its prompt. */
4
+ export const DEFAULT_MISSIONS = {
5
+ ba: 'Turn the goal into one clear handoff: scope, testable acceptance criteria, out of scope, risks. Afterwards check the finished work against it.',
6
+ implement: 'Build what the handoff asks for in the project: change the code, run the checks, report what changed and how to verify.',
7
+ qc: 'Independently review and test the deliverable against the acceptance criteria and give a PASS or FAIL verdict with reasons.',
8
+ };
3
9
  /** Company pipeline stages, in order. */
4
- export const STAGES = ['director-intake', 'ba-discussion', 'implement', 'qc', 'ba-review', 'delivery'];
10
+ export const STAGES = ['director-intake', 'ba-discussion', 'implement', 'qc', 'review', 'delivery'];
11
+ /** The flow: ids of the teams that have agents, in run order. `order` wins; without it: ba, implement, qc with extra teams after the stage named by runAfter (default implement). */
12
+ export function effectiveOrder(c) {
13
+ const has = (id) => id === 'ba' || id === 'implement' || id === 'qc' ? c.teams[id].length > 0 : (c.extraTeams ?? []).some(t => t.id === id && t.agents.length > 0);
14
+ if (c.order)
15
+ return c.order.filter(has);
16
+ const ex = (after) => (c.extraTeams ?? []).filter(t => (t.runAfter ?? 'implement') === after).map(t => t.id);
17
+ return ['ba', ...ex('ba'), 'implement', ...ex('implement'), 'qc', ...ex('qc')].filter(has);
18
+ }
19
+ /** Every agent of the company: director, built-in teams, then extra teams. */
20
+ export const allAgentsOf = (c) => [c.director, ...c.teams.ba, ...c.teams.implement, ...c.teams.qc, ...(c.extraTeams ?? []).flatMap(t => t.agents)];
5
21
  //# sourceMappingURL=types.js.map
@@ -3,8 +3,8 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
3
  // Presentation only: subscribes to a TeamRunHandle, no network, no file writes, no child processes.
4
4
  import React, { useEffect, useMemo, useReducer, useState } from 'react';
5
5
  import { Box, Text, useInput, useWindowSize } from 'ink';
6
- import { STAGES } from '../../team/types.js';
7
- import { STAGE_LABEL, TEAM_LABEL, activeAgentCount, activeTeam, formatClock, formatDuration, formatTokens, initialTeamView, reduceTeam, sanitize, stageDuration, stageIndex } from './model.js';
6
+ import {} from '../../team/types.js';
7
+ import { STAGE_LABEL, TEAM_LABEL, activeAgentCount, activeTeam, formatClock, formatDuration, formatTokens, initialTeamView, reduceTeam, sanitize, stageChips, stageDuration, stageIndex } from './model.js';
8
8
  /** Text that tolerates explicit undefined props (exactOptionalPropertyTypes). */
9
9
  function Tx({ color, bold, dimColor, inverse, wrap, children }) {
10
10
  return _jsx(Text, { ...(color ? { color } : {}), ...(wrap ? { wrap } : {}), bold: bold === true, dimColor: dimColor === true, inverse: inverse === true, children: children });
@@ -65,7 +65,7 @@ export function buildFeedLines(feed, names, width, showActivity) {
65
65
  }
66
66
  if (m.kind === 'handoff') {
67
67
  lines.push({ key: `${k}s`, parts: [{ text: ' ' }] });
68
- lines.push({ key: k, parts: [{ text: `📦 HANDOFF ${TEAM_LABEL[m.fromTeam ?? 'director'].toUpperCase()} → ${(m.to in TEAM_LABEL ? TEAM_LABEL[m.to] : m.to).toUpperCase()}: ${m.text}`, bold: true, color: m.to in TEAM_COLOR ? TEAM_COLOR[m.to] : 'white', inverse: true }] });
68
+ lines.push({ key: k, parts: [{ text: `📦 HANDOFF ${(TEAM_LABEL[m.fromTeam ?? 'director'] ?? m.fromTeam ?? '').toUpperCase()} → ${(TEAM_LABEL[m.to] ?? m.to).toUpperCase()}: ${m.text}`, bold: true, color: m.to in TEAM_COLOR ? TEAM_COLOR[m.to] : 'white', inverse: true }] });
69
69
  lines.push({ key: `${k}e`, parts: [{ text: ' ' }] });
70
70
  continue;
71
71
  }
@@ -102,27 +102,27 @@ function Header({ state, width, tick, nowMs }) {
102
102
  return (_jsxs(Box, { width: width, height: 1, paddingX: 1, children: [_jsx(Tx, { bold: true, color: "magenta", children: "\u25C6 CKIT \u00B7 AGENT COMPANY" }), _jsx(Tx, { dimColor: true, children: " \u2502 " }), _jsx(Box, { flexGrow: 1, flexShrink: 1, children: _jsx(Tx, { wrap: "truncate-end", bold: true, children: state.goal }) }), _jsxs(Tx, { dimColor: true, children: [state.runId ?? '', state.simulated ? ' · sim' : '', " "] }), _jsxs(Tx, { bold: true, color: "cyan", children: ["\u23F1 ", formatClock(elapsed), " "] }), _jsxs(Tx, { bold: true, color: badgeColor, children: [dot, " ", badge] })] }));
103
103
  }
104
104
  function Pipeline({ state, width, tick, nowMs }) {
105
- const cur = stageIndex(state.stage);
105
+ const chips = stageChips(state.config), cur = stageIndex(state);
106
106
  const max = state.config?.limits.qcLoops ?? 0;
107
107
  const looping = state.loop > 0 && (state.loop > 1 || state.verdicts.some(v => v.verdict === 'FAIL'));
108
108
  const pulse = tick % 8 < 4;
109
- return (_jsxs(Box, { width: width, borderStyle: "round", borderColor: state.outcome === null ? 'blue' : state.outcome === 'delivered' ? 'green' : 'red', paddingX: 1, height: 3, children: [STAGES.map((st, i) => {
109
+ return (_jsxs(Box, { width: width, borderStyle: "round", borderColor: state.outcome === null ? 'blue' : state.outcome === 'delivered' ? 'green' : 'red', paddingX: 1, height: 3, children: [chips.map((chip, i) => {
110
110
  const done = state.outcome === 'delivered' || i < cur;
111
- const dur = stageDuration(state, st);
111
+ const dur = stageDuration(state, chip.id);
112
112
  const sep = i > 0 ? _jsx(Tx, { dimColor: true, children: " \u25B8 " }) : null;
113
113
  let label;
114
114
  if (done)
115
- label = _jsxs(Tx, { color: "green", children: ["\u2714 ", STAGE_LABEL[st], dur !== null ? ` ${formatDuration(dur)}` : ''] });
115
+ label = _jsxs(Tx, { color: "green", children: ["\u2714 ", chip.label, dur !== null ? ` ${formatDuration(dur)}` : ''] });
116
116
  else if (i === cur && state.outcome === null) {
117
117
  const span = state.stageHistory.at(-1);
118
118
  const t = span ? ` ${formatDuration(nowMs - span.startedAt)}` : '';
119
- label = _jsxs(Tx, { bold: true, inverse: true, color: pulse ? 'cyan' : 'blue', children: [" ", SPINNER[tick % SPINNER.length], " ", STAGE_LABEL[st], t, " "] });
119
+ label = _jsxs(Tx, { bold: true, inverse: true, color: pulse ? 'cyan' : 'blue', children: [" ", SPINNER[tick % SPINNER.length], " ", chip.label, t, " "] });
120
120
  }
121
121
  else if (i === cur)
122
- label = _jsxs(Tx, { color: "red", children: ["\u2716 ", STAGE_LABEL[st]] });
122
+ label = _jsxs(Tx, { color: "red", children: ["\u2716 ", chip.label] });
123
123
  else
124
- label = _jsx(Tx, { dimColor: true, children: STAGE_LABEL[st] });
125
- return _jsxs(React.Fragment, { children: [sep, label] }, st);
124
+ label = _jsx(Tx, { dimColor: true, children: chip.label });
125
+ return _jsxs(React.Fragment, { children: [sep, label] }, chip.id);
126
126
  }), looping ? _jsxs(Tx, { bold: true, color: "yellow", children: [" \u21BB QC loop ", state.loop, "/", max > 0 ? Math.max(max, state.loop) : state.loop] }) : null] }));
127
127
  }
128
128
  const STATE_ICON = {
@@ -140,7 +140,7 @@ function AgentRow({ agent, width, compact, tick, nowMs }) {
140
140
  }
141
141
  function TeamCard({ team, agents, width, active, compact, tick, nowMs }) {
142
142
  const color = TEAM_COLOR[team];
143
- const title = team === 'director' ? 'DIRECTOR' : `TEAM ${TEAM_LABEL[team].toUpperCase()}`;
143
+ const title = team === 'director' ? 'DIRECTOR' : `TEAM ${(TEAM_LABEL[team] ?? team).toUpperCase()}`;
144
144
  const h = 3 + agents.length * (compact ? 1 : 2);
145
145
  return (_jsxs(Box, { flexDirection: "column", width: width, height: h, borderStyle: active ? 'bold' : 'round', borderColor: color, borderDimColor: !active, paddingX: 1, overflow: "hidden", children: [_jsxs(Tx, { bold: true, color: color, dimColor: !active, children: [active ? '▶ ' : ' ', title, active ? _jsxs(Tx, { color: color, children: [" ", tick % 8 < 4 ? '◀' : ' '] }) : null] }), agents.map(a => _jsx(AgentRow, { agent: a, width: width - 4, compact: compact, tick: tick, nowMs: nowMs }, a.id))] }));
146
146
  }
@@ -1,8 +1,8 @@
1
- import { type AgentCli, type AgentState, type Stage, type TeamConfig, type TeamEvent, type TeamId } from '../../team/types.js';
1
+ import { type AgentCli, type AgentState, type Stage, type TeamConfig, type TeamEvent } from '../../team/types.js';
2
2
  export interface AgentView {
3
3
  readonly id: string;
4
4
  readonly name: string;
5
- readonly team: TeamId;
5
+ readonly team: string;
6
6
  readonly cli: AgentCli;
7
7
  readonly model: string | null;
8
8
  readonly state: AgentState;
@@ -17,21 +17,22 @@ export interface FeedItem {
17
17
  readonly id: number;
18
18
  readonly kind: FeedKind;
19
19
  readonly from: string;
20
- readonly fromTeam: TeamId | null;
20
+ readonly fromTeam: string | null;
21
21
  readonly to: string;
22
22
  readonly text: string;
23
23
  readonly at: number;
24
24
  readonly tone?: 'pass' | 'fail' | 'bad';
25
25
  }
26
26
  export interface StageSpan {
27
- readonly stage: Stage;
27
+ readonly stage: Stage; /** extra-team stage only */
28
+ readonly team?: string;
28
29
  readonly loop: number;
29
30
  readonly startedAt: number;
30
31
  readonly endedAt: number | null;
31
32
  }
32
33
  export interface HandoffView {
33
- readonly from: TeamId;
34
- readonly to: TeamId;
34
+ readonly from: string;
35
+ readonly to: string;
35
36
  readonly title: string;
36
37
  readonly artifact: string;
37
38
  readonly at: number;
@@ -42,7 +43,7 @@ export interface VerdictView {
42
43
  readonly summary: string;
43
44
  readonly at: number;
44
45
  }
45
- export type Outcome = 'delivered' | 'failed' | 'stopped';
46
+ export type Outcome = 'delivered' | 'failed' | 'stopped' | 'declined';
46
47
  export interface TeamViewState {
47
48
  readonly runId: string | null;
48
49
  readonly goal: string;
@@ -64,17 +65,27 @@ export interface TeamViewState {
64
65
  readonly messageCount: number;
65
66
  }
66
67
  export declare const STAGE_LABEL: Readonly<Record<Stage, string>>;
67
- export declare const TEAM_LABEL: Readonly<Record<TeamId, string>>;
68
- export declare const stageTeam: (s: Stage) => TeamId;
69
- export declare const stageIndex: (s: Stage | null) => number;
68
+ export declare const TEAM_LABEL: Readonly<Record<string, string>>;
69
+ export declare const stageTeam: (s: Stage) => string;
70
+ /** Strip chips: Director, one chip per team in flow order, Delivery. The id of a span is its stage, or x:<id> for an extra team. */
71
+ export interface StageChip {
72
+ readonly id: string;
73
+ readonly label: string;
74
+ }
75
+ export declare function stageChips(config: TeamConfig | null): StageChip[];
76
+ export declare const spanKey: (h: {
77
+ readonly stage: Stage;
78
+ readonly team?: string;
79
+ }) => string;
80
+ export declare const stageIndex: (s: TeamViewState) => number;
70
81
  export declare const initialTeamView: () => TeamViewState;
71
82
  /** Agent output is untrusted: drop ANSI/OSC escapes and control characters, keep newlines, tabs become spaces. */
72
83
  export declare function sanitize(text: string): string;
73
- export declare function activeTeam(s: TeamViewState): TeamId | null;
84
+ export declare function activeTeam(s: TeamViewState): string | null;
74
85
  export declare function targetLabel(s: TeamViewState, to: string): string;
75
86
  export declare function reduceTeam(state: TeamViewState, event: TeamEvent): TeamViewState;
76
87
  /** Duration of the latest completed span of `stage`, or null. */
77
- export declare function stageDuration(s: TeamViewState, stage: Stage): number | null;
88
+ export declare function stageDuration(s: TeamViewState, key: string): number | null;
78
89
  export declare const activeAgentCount: (s: TeamViewState) => number;
79
90
  export declare function formatClock(msTotal: number): string;
80
91
  export declare function formatDuration(msTotal: number): string;
@@ -1,10 +1,16 @@
1
1
  // Pure view-model for the Agent Company TUI: folds TeamEvents into a renderable state. No React, no I/O.
2
- import { STAGES } from '../../team/types.js';
3
- export const STAGE_LABEL = { 'director-intake': 'Director', 'ba-discussion': 'BA', implement: 'Implement', qc: 'QC', 'ba-review': 'BA Review', delivery: 'Delivery' };
2
+ import { allAgentsOf, effectiveOrder } from '../../team/types.js';
3
+ export const STAGE_LABEL = { 'director-intake': 'Director', 'ba-discussion': 'BA', implement: 'Implement', qc: 'QC', review: 'Review', delivery: 'Delivery', 'extra-team': 'Extra team' };
4
4
  export const TEAM_LABEL = { director: 'Director', ba: 'BA', implement: 'Implement', qc: 'QC' };
5
- const STAGE_TEAM = { 'director-intake': 'director', 'ba-discussion': 'ba', implement: 'implement', qc: 'qc', 'ba-review': 'ba', delivery: 'director' };
5
+ const STAGE_TEAM = { 'extra-team': '', 'director-intake': 'director', 'ba-discussion': 'ba', implement: 'implement', qc: 'qc', review: 'director', delivery: 'director' };
6
6
  export const stageTeam = (s) => STAGE_TEAM[s];
7
- export const stageIndex = (s) => (s === null ? -1 : STAGES.indexOf(s));
7
+ export function stageChips(config) {
8
+ const ids = config ? effectiveOrder(config) : ['ba', 'implement', 'qc'];
9
+ const chip = (id) => id === 'ba' ? { id: 'ba-discussion', label: 'BA' } : id === 'implement' || id === 'qc' ? { id, label: STAGE_LABEL[id] } : { id: 'x:' + id, label: config?.extraTeams?.find(t => t.id === id)?.name ?? id };
10
+ return [{ id: 'director-intake', label: 'Director' }, ...ids.map(chip), { id: 'delivery', label: 'Delivery' }];
11
+ }
12
+ export const spanKey = (h) => (h.stage === 'extra-team' ? 'x:' + (h.team ?? '') : h.stage);
13
+ export const stageIndex = (s) => { const h = s.stageHistory.at(-1); return h ? stageChips(s.config).findIndex(z => z.id === spanKey(h)) : -1; };
8
14
  export const initialTeamView = () => ({ runId: null, goal: '', simulated: false, config: null, startedAt: null, endedAt: null, lastAt: null, agents: [], stage: null, loop: 0, stageHistory: [], feed: [], handoffs: [], verdicts: [], outcome: null, report: '', totalTokens: 0, messageCount: 0 });
9
15
  /** Agent output is untrusted: drop ANSI/OSC escapes and control characters, keep newlines, tabs become spaces. */
10
16
  export function sanitize(text) {
@@ -17,7 +23,7 @@ export function sanitize(text) {
17
23
  }
18
24
  const oneLine = (t) => sanitize(t).replace(/\s+/g, ' ').trim();
19
25
  const ms = (at, fallback) => { const v = Date.parse(at); return Number.isFinite(v) ? v : (fallback ?? 0); };
20
- export function activeTeam(s) { return s.outcome !== null || s.stage === null ? null : STAGE_TEAM[s.stage]; }
26
+ export function activeTeam(s) { return s.outcome !== null || s.stage === null || s.stage === 'extra-team' ? null : STAGE_TEAM[s.stage]; }
21
27
  /** waiting = members of the active stage's team that are not thinking (and have no result to show). Everyone else idle/done/failed stays. */
22
28
  function settle(s) {
23
29
  const team = activeTeam(s);
@@ -50,13 +56,15 @@ export function reduceTeam(state, event) {
50
56
  switch (event.type) {
51
57
  case 'run.started': {
52
58
  const cfg = event.config;
53
- const all = [cfg.director, ...cfg.teams.ba, ...cfg.teams.implement, ...cfg.teams.qc];
59
+ const all = allAgentsOf(cfg);
54
60
  const agents = all.map(a => ({ id: a.id, name: sanitize(a.name), team: a.team, cli: a.cli, model: a.model, state: 'idle', lastActivity: '', turns: 0, tokens: 0, turnStartedAt: null }));
55
61
  return push({ ...s0, goal: oneLine(event.goal), simulated: event.simulated, config: cfg, startedAt: at, agents }, { kind: 'system', from: 'system', fromTeam: null, to: 'all', text: `Run started: ${oneLine(event.goal)}`, at });
56
62
  }
57
63
  case 'stage.changed': {
64
+ if (!(event.stage in STAGE_LABEL))
65
+ return s0; // journals written before the BA-review stage was removed: ignored
58
66
  const hist = state.stageHistory.map((h, i) => (i === state.stageHistory.length - 1 && h.endedAt === null ? { ...h, endedAt: at } : h));
59
- const next = { ...s0, stage: event.stage, loop: event.loop, stageHistory: [...hist, { stage: event.stage, loop: event.loop, startedAt: at, endedAt: null }] };
67
+ const next = { ...s0, stage: event.stage, loop: event.loop, stageHistory: [...hist, { stage: event.stage, ...(event.team ? { team: event.team } : {}), loop: event.loop, startedAt: at, endedAt: null }] };
60
68
  return settle(push(next, { kind: 'system', from: 'system', fromTeam: null, to: 'all', text: `Stage → ${STAGE_LABEL[event.stage]}${event.loop > 0 ? ` (loop ${event.loop})` : ''}`, at }));
61
69
  }
62
70
  case 'agent.started': {
@@ -85,8 +93,16 @@ export function reduceTeam(state, event) {
85
93
  }
86
94
  case 'handoff.created':
87
95
  return push({ ...s0, handoffs: [...s0.handoffs, { from: event.from, to: event.to, title: oneLine(event.title), artifact: oneLine(event.artifact), at }] }, { kind: 'handoff', from: event.from, fromTeam: event.from, to: event.to, text: oneLine(event.title), at });
96
+ case 'flow.back':
97
+ return push(s0, { kind: 'system', from: 'system', fromTeam: null, to: 'all', text: `${event.kind === 'ask' ? '? ' + event.from + ' asked ' : '↩ ' + event.from + ' returned to '}${event.to}: ${oneLine(event.reason)}`, at });
88
98
  case 'qc.verdict':
89
99
  return push({ ...s0, verdicts: [...s0.verdicts, { verdict: event.verdict, loop: event.loop, summary: oneLine(event.summary), at }] }, { kind: 'verdict', from: 'qc', fromTeam: 'qc', to: 'all', text: oneLine(event.summary), at, tone: event.verdict === 'PASS' ? 'pass' : 'fail' });
100
+ case 'lane.chosen':
101
+ return push(s0, { kind: 'director', from: 'director', fromTeam: 'director', to: 'all', text: `Lane: ${event.name} (${event.by})`, at });
102
+ case 'review.verdict':
103
+ return push(s0, { kind: 'verdict', from: 'director', fromTeam: 'director', to: 'all', text: `Director review ${event.verdict}: ${oneLine(event.summary)}`, at, tone: event.verdict === 'PASS' ? 'pass' : 'fail' });
104
+ case 'run.waiting':
105
+ return push(s0, { kind: 'director', from: 'director', fromTeam: 'director', to: 'all', text: `Waiting for the owner: ${oneLine(event.questions)}`, at });
90
106
  case 'user.message':
91
107
  return push({ ...s0, messageCount: s0.messageCount + 1 }, { kind: 'user', from: 'user', fromTeam: null, to: 'director', text: sanitize(event.text).trim(), at });
92
108
  case 'director.decision':
@@ -111,10 +127,10 @@ export function reduceTeam(state, event) {
111
127
  }
112
128
  }
113
129
  /** Duration of the latest completed span of `stage`, or null. */
114
- export function stageDuration(s, stage) {
130
+ export function stageDuration(s, key) {
115
131
  for (let i = s.stageHistory.length - 1; i >= 0; i--) {
116
132
  const h = s.stageHistory[i];
117
- if (h && h.stage === stage && h.endedAt !== null)
133
+ if (h && spanKey(h) === key && h.endedAt !== null)
118
134
  return h.endedAt - h.startedAt;
119
135
  }
120
136
  return null;