@ngockhoale/ckit 0.4.5 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -29,6 +29,8 @@ A Director plus the default teams BA → Implement → Tester → Security → Q
29
29
  - **Security team (default, read-only).** One agent (`security-claude`, claude, default model) reviews the change for secrets, auth, injection, unsafe spawn/exec, path traversal, dependency risk and data exposure, with severity and evidence per finding. It runs right before QC whenever the goal changes code and is skipped (journaled) for read-only goals. A critical finding wakes the Director at once and blocks Delivery: the work goes back to Implement (bounded), then the owner must reply `ACCEPT: <reason>` to deliver anyway. Like every team except the Director it can be edited or removed in Config; an existing `.ckit/team.json` is never changed.
30
30
  - **Agent tools.** Agents can message each other and the Director through CKit's MCP tools, which use a local socket and never a network port.
31
31
  - **Owner control.** Owner messages that arrive close together are coalesced into one Director decision; urgent wording or STOP is handled at once. Pause / Resume / Interrupt buttons stop new turns or abort running turns. An interrupted turn is redone after resume with your newest guidance.
32
+ - **Continuous session (GUI default).** One run is one conversation, not one prompt: after an objective is delivered the run goes **idle** (sessions, tools and journal stay open) and your next message starts the next objective in the same run with the same team, which sees the earlier objectives. Every message gets a durable ack (`inputId`, `inputSeq`, status `received → queued / applied / answered → resolved`, or `cancelled` / `rejected`), a retried send with the same `clientRequestId` is never duplicated, and more than 100 waiting messages are refused with a reason (HTTP 429) instead of being dropped. Short status questions ("status?", "tiến độ thế nào?") are answered from the run state with no model call. Owner requirements and corrections are listed per objective in `requirements.md` (with their input ids); each objective keeps its own `report-objective-N.md`. Long messages are never cut (the whole text is saved for the team). A message that arrives while the delivery report is written starts the next objective. STOP ends the session; **Close session** (`POST /api/runs/<id>/close`) ends it with the last outcome; "New run" still starts a separate run. `ckit team` and API callers that do not send `persistent: true` keep the one-prompt behaviour.
33
+ - **Lean company.** Default profile has 6 roles (Director, BA, Dev, Tester, Security, QC; BA, Tester and QC have two seats each for independent views; see `docs/architecture/LEAN_COMPANY.md` for 4- and 8-person references). The Director picks the smallest mode that fits (`DIRECT` answers with no team, `DELEGATE` one agent), discussion rounds are 0 by default, clean handoffs are accepted without a Director checkpoint, and agents talk to each other directly through the CKit tools.
32
34
  - **Long prompts** are compacted. The full text is kept as a run artifact. 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. When a team asks the Director something only you can decide, the Director passes it on (at most 3 times per run): the run pauses, the question appears in the conversation and the request box turns into an amber ANSWER box (text, attached files and `@` mentions all work; "Proceed with assumptions" uses the Director's stated assumption).
33
35
 
34
36
  ```bash
@@ -36,7 +36,7 @@ export function packageVersion(file = fileURLToPath(new URL('../../../package.js
36
36
  }
37
37
  const START_VERSION = packageVersion();
38
38
  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' };
39
- const ARTIFACT_RE = /^(report\.md|transcript\.md|handoff-ba\.md|qc-report-\d{1,3}\.md)$/;
39
+ const ARTIFACT_RE = /^(report\.md|report-objective-\d{1,4}\.md|owner-input-\d{1,6}\.md|requirements\.md|transcript\.md|handoff-ba\.md|qc-report-\d{1,3}\.md)$/;
40
40
  const RUN_ID_RE = /^team-\d{8}-\d{6}-[0-9a-f]{4}$/;
41
41
  /** Attachments: any file type. Limits only keep a runaway upload from filling the disk. */
42
42
  const MAX_UPLOAD_BYTES = 2 * 1024 ** 3, MAX_PENDING_UPLOADS = 100, MAX_ATTACHMENTS_PER_SEND = 50;
@@ -114,7 +114,7 @@ export async function startGuiServer(opts) {
114
114
  catch { /* dead socket */ }
115
115
  } };
116
116
  const attach = (handle, goal, simulated, replay) => {
117
- const cur = { handle, goal, simulated, startedAt: new Date().toISOString(), outcome: null, ...(replay ? { replay } : {}), unsub: () => undefined, listeners: new Set(), events: [], tele: null };
117
+ const cur = { handle, goal, simulated, startedAt: new Date().toISOString(), outcome: null, ...(replay ? { replay } : {}), unsub: () => undefined, listeners: new Set(), events: [], tele: null, idle: false };
118
118
  if (replay) {
119
119
  playback?.unsub();
120
120
  playback = cur;
@@ -135,7 +135,10 @@ export async function startGuiServer(opts) {
135
135
  }
136
136
  catch { /* dead socket */ }
137
137
  }
138
- cur.unsub = handle.subscribe(e => { if (e.type !== 'agent.delta' && e.type !== 'agent.tool') {
138
+ cur.unsub = handle.subscribe(e => { if (e.type === 'run.idle')
139
+ cur.idle = true;
140
+ else if (e.type === 'objective.started')
141
+ cur.idle = false; if (e.type !== 'agent.delta' && e.type !== 'agent.tool') {
139
142
  cur.events.push(e);
140
143
  cur.tele = null;
141
144
  } toAll(cur, r => sendEvent(r, e)); });
@@ -153,7 +156,7 @@ export async function startGuiServer(opts) {
153
156
  t.tele = { at: now, value: runTelemetry(t.events, now) };
154
157
  return t.tele.value;
155
158
  };
156
- const view = (t) => ({ telemetry: telemetryOf(t), paused: t.outcome === null && telemetryOf(t).paused, runId: t.handle.runId, goal: t.goal, simulated: t.simulated, startedAt: t.startedAt, running: t.outcome === null, outcome: t.outcome, ...(t.replay ? { replay: t.replay } : {}) });
159
+ const view = (t) => ({ telemetry: telemetryOf(t), paused: t.outcome === null && telemetryOf(t).paused, runId: t.handle.runId, goal: t.events[0]?.type === 'run.started' ? t.events[0].goal : t.goal, simulated: t.simulated, startedAt: t.startedAt, running: t.outcome === null, idle: t.outcome === null && t.idle, outcome: t.outcome, ...(t.replay ? { replay: t.replay } : {}) });
157
160
  /** Replays history to one client only; live events arrive through the shared fan-out. */
158
161
  const replayTo = (t, res) => { t.handle.subscribe(e => { try {
159
162
  sendEvent(res, e);
@@ -343,7 +346,7 @@ export async function startGuiServer(opts) {
343
346
  const cfgNow = loadConfig(), laneId = typeof b['lane'] === 'string' ? b['lane'] : '';
344
347
  if (laneId && !(cfgNow.lanes ?? []).some(l => l.id === laneId))
345
348
  return json(res, 400, { error: `unknown lane "${laneId.slice(0, 40)}"` });
346
- const handle = (opts.startRun ?? startTeamRun)({ projectRoot: root, goal, config: cfgNow, simulated, attachments: files, ...(laneId ? { lane: laneId } : {}) });
349
+ const handle = (opts.startRun ?? startTeamRun)({ projectRoot: root, goal, config: cfgNow, simulated, attachments: files, ...(laneId ? { lane: laneId } : {}), ...(b['persistent'] === true ? { persistent: true } : {}) });
347
350
  release(b['attachments']);
348
351
  attach(handle, goal, simulated);
349
352
  return json(res, 200, { runId: handle.runId });
@@ -432,7 +435,7 @@ export async function startGuiServer(opts) {
432
435
  }
433
436
  if (m === 'GET' && p === '/api/clis')
434
437
  return json(res, 200, { clis: detectClis(), configFile: teamConfigPath(root) });
435
- const act = /^\/api\/runs\/([^/]+)\/(message|proceed|stop|pause|resume|interrupt)$/.exec(p);
438
+ const act = /^\/api\/runs\/([^/]+)\/(message|proceed|stop|pause|resume|interrupt|close)$/.exec(p);
436
439
  const actOn = () => {
437
440
  if (!act || m !== 'POST')
438
441
  return null;
@@ -458,14 +461,21 @@ export async function startGuiServer(opts) {
458
461
  return;
459
462
  const { t } = a;
460
463
  if (a.kind === 'message') {
461
- const b = obj(await readBody(req)), text = typeof b['text'] === 'string' ? b['text'] : '', files = claim(b['attachments']);
464
+ const b = obj(await readBody(req)), text = typeof b['text'] === 'string' ? b['text'] : '';
465
+ const cid = typeof b['clientRequestId'] === 'string' && /^[A-Za-z0-9_.:-]{1,100}$/.test(b['clientRequestId']) ? b['clientRequestId'] : undefined;
466
+ const prior = cid ? t.handle.inputByClient?.(cid) : undefined;
467
+ if (prior)
468
+ return json(res, 200, { ok: true, ...prior }); // a retry of a send that already landed: same input (its uploads were already claimed), never a second copy
469
+ const files = claim(b['attachments']);
462
470
  if (files === null)
463
471
  return json(res, 400, { error: 'unknown attachment; attach the file again' });
464
472
  if (!text.trim() && files.length === 0)
465
473
  return json(res, 400, { error: 'text required' });
466
- t.handle.sendToDirector(text.slice(0, 4000), files);
474
+ const ack = t.handle.sendToDirector(text, files, cid ? { clientRequestId: cid } : undefined); // full text: a long message is saved by the engine, never cut here
475
+ if (ack && ack.status === 'rejected')
476
+ return json(res, ack.inputId ? 200 : 429, { ok: false, ...ack, error: ack.reason ?? 'message not accepted' }); // uploads stay claimable for the retry
467
477
  release(b['attachments']);
468
- return json(res, 200, { ok: true });
478
+ return json(res, 200, { ok: true, ...(ack ?? {}) });
469
479
  }
470
480
  if (a.kind === 'proceed') {
471
481
  if (!t.handle.proceedWithAssumptions)
@@ -480,6 +490,13 @@ export async function startGuiServer(opts) {
480
490
  fn.call(t.handle);
481
491
  return json(res, 200, { ok: true });
482
492
  }
493
+ if (a.kind === 'close') {
494
+ if (t.handle.close)
495
+ t.handle.close();
496
+ else
497
+ t.handle.stop();
498
+ return json(res, 200, { ok: true });
499
+ }
483
500
  t.handle.stop();
484
501
  // A playback has no run.completed of its own when it is cut short, so every open page is told directly.
485
502
  if (t.replay) {
@@ -11,6 +11,8 @@ export interface StartTeamRunOptions {
11
11
  readonly projectRoot: string;
12
12
  readonly goal: string;
13
13
  readonly config: TeamConfig;
14
+ /** Continuous Director session: after delivery the run goes idle (run.idle) instead of completing; the next owner input starts a new objective in the same run. */
15
+ readonly persistent?: boolean;
14
16
  readonly runner?: AgentRunner;
15
17
  readonly simulated?: boolean;
16
18
  readonly now?: () => Date;
@@ -36,7 +36,14 @@ class NodeCancelled extends Error {
36
36
  } // a PARALLEL_EXECUTE node stopped because a sibling node redirected or halted the flow // run already finished (stop) or failed; unwinds the pipeline
37
37
  const oneLine = (s, max = 200) => { const t = s.replace(/\s+/g, ' ').trim(); return t.length > max ? `${t.slice(0, max - 1)}…` : t; };
38
38
  const clip = (s, max) => s.length > max ? `${s.slice(0, max)}\n[...truncated]` : s;
39
- const STOP_RE = /^\s*(stop|dừng)(?![\p{L}\p{N}_])/iu, REDIRECT_RE = /^\s*(redirect|đổi hướng)[:\s]\s*/i;
39
+ /** A session STOP is the whole message ("stop", "stop now", "stop the run", "dừng lại ngay") or an all-caps STOP; "Stop the spinner after loading" is product work, never a session stop. */
40
+ const STOP_WORDS_RE = /^\s*(?:stop|dừng)(?:[\s,]+(?:now|please|pls|it|all|everything|right now|immediately|at once|(?:this|the|current|whole|entire)(?: (?:whole|entire|current))? (?:run|team|session|work|task|job|mission|agents?)|ngay|lại|hết|đi|nhé|nha|lập tức|tất cả|toàn bộ|mọi thứ|mọi việc|(?:phiên|run|công việc|team|nhóm|nhiệm vụ)(?: (?:này|hiện tại))?))*\s*[.!]*\s*$/iu, STOP_CAPS_RE = /^\s*(?:STOP|DỪNG)(?![\p{L}\p{N}_])/u;
41
+ const STOP_RE = { test: (t) => (t.length <= 120 && STOP_WORDS_RE.test(t)) || STOP_CAPS_RE.test(t) }; // every list item is unambiguous (no item splits into other items) and the input is bounded: linear, never a ReDoS
42
+ const REDIRECT_RE = /^\s*(redirect|đổi hướng)[:\s]\s*/i;
43
+ /** "status?", "tiến độ thế nào", "xong chưa": a short status question is answered from the run state, with no model call. */
44
+ /** Status-only messages: the WHOLE message is a status question (no work words), so "status bar is broken, fix it" is work, not a status query. */
45
+ const STATUS_RE = /^\s*(?:(?:any )?(?:status|progress|update)(?: update| report)?(?: please| pls)?|what(?:'s| is) the (?:status|progress)(?: now)?|how(?:'s| is) it going|how far along(?: are you)?|what are you (?:doing|working on)(?: now)?|(?:cho (?:tôi|mình|em|anh) )?(?:xem )?(?:tiến độ|trạng thái)(?: (?:thế nào|ra sao|sao rồi|đến đâu rồi|tới đâu rồi))?(?: (?:vậy|rồi|nhé|nha))?|đang làm gì(?: (?:vậy|thế|đó))?|làm (?:tới|đến) đâu rồi|xong chưa|sao rồi)\s*[?.!]*\s*$/iu;
46
+ const CANCEL_RE = /^\s*(?:cancel|drop|skip|forget|bỏ|hủy|huỷ|không cần)(?![\p{L}])/iu;
40
47
  /** Pure rule-based owner-chat decision (director cli 'auto', and the fallback for model directors). */
41
48
  export function ruleDecision(text) {
42
49
  if (STOP_RE.test(text))
@@ -215,6 +222,8 @@ const HOW_TO_RE = new RegExp(String.raw `${HOW_TO_HEAD}[^\n]*?(?=$|\n|[,;!?]|\.(
215
222
  const HOW_TO_SENT_RE = new RegExp(String.raw `${HOW_TO_HEAD}[^\n]*?(?=$|\n|[;!?]|\.(?=\s|$))`, 'gimu'); // before an explicit no-write order: the explained clause runs to its sentence end
216
223
  /** The owner forbade writing in so many words (not only a "read-only" label): "do not change any files", "no code changes", "không sửa". */
217
224
  const NO_WRITE_RE = /(?<![\p{L}])(?:(?:do not|don't|dont|never|without) (?:change|changing|modify|modifying|edit|editing|touch|touching|write|writing) (?:(?:any(?: of the)?|the|a single) )?(?:files?|code|anything|the repo|the project|the codebase)(?![\p{L}])(?!,? (?:except|outside|other than|besides|beyond|apart from|in production|else)(?![\p{L}]))|no (?:code |file )?changes(?![\p{L}])(?!,? (?:except|outside|other than|besides|beyond|apart from|in production|else)(?![\p{L}]))|không (?:được )?(?:sửa|thay đổi|chỉnh sửa)(?: (?:file|code|gì))?(?![\p{L}])(?!,? (?:file |code )?(?:ngoài|trừ)(?![\p{L}])))/iu; // a whole no-write order; one whose object is directly limited ("files outside docs/", "file ngoài docs/") is a scope, not read-only
225
+ /** The owner takes back what came before: "Correction:", "actually", "instead", "đính chính", "à không". */
226
+ const CORRECTION_RE = /(?<![\p{L}])(?:correction|actually|instead|on second thought|scratch that|forget that|change of plan|đính chính|à không|thay vào đó|thôi)(?![\p{L}])[^.;!?\n]{0,20}$/iu;
218
227
  /** "In your reply, add a summary": shapes the answer, never the workspace. */
219
228
  const REPLY_RE = /(?<![\p{L}])(?:in|to|into) (?:your|the) (?:reply|answer|response|report|summary|explanation|câu trả lời)(?![\p{L}])[^.;!?\n]*|(?<![\p{L}])(?:trong|vào) (?:câu trả lời|báo cáo|phần trả lời)[^.;!?\n]*/giu;
220
229
  /** PF-MODES: the owner asked for a read-only result (question, analysis, review) - no team may change files.
@@ -223,8 +232,10 @@ export const isReadOnlyGoal = (goal) => {
223
232
  const g = goal.replace(/\[[^\]]*\]/g, ' ').replace(/[^\S\n]+/g, ' ').trim(), first = [...g.matchAll(READ_ONLY_RE)][0], nw = NO_WRITE_RE.exec(g);
224
233
  const asks = (t, how = HOW_TO_RE) => CHANGE_RE.test(t.replace(READ_ONLY_RE, ' ').replace(REPLY_RE, ' ').replace(how, ' '));
225
234
  // an explicit whole no-write order (anywhere) wins when nothing before it asks for a change: the rest is to be explained, never done
226
- if (nw && !asks(g.slice(0, nw.index), HOW_TO_SENT_RE))
227
- return true;
235
+ if (nw && /^(?:please )?(?:review|explain|analy[sz]e|inspect|audit|assess|evaluate|summari[sz]e|describe|investigate|look (?:at|into)|read|what|why|how|which|xem|giải thích|phân tích|đánh giá|tại sao|vì sao)(?![\p{L}])/iu.test(g))
236
+ return true; // a read-only verb opens the goal + an explicit no-write order: a change verb inside what is reviewed ("Review the plan to add OAuth. Do not change any files.") never grants write
237
+ if (nw && (!asks(g.slice(0, nw.index), HOW_TO_SENT_RE) || CORRECTION_RE.test(g.slice(Math.max(0, nw.index - 40), nw.index))))
238
+ return true; // a correction ("Correction: do not change any files") overrides the earlier write request
228
239
  if (!first || (first.index ?? 0) > 25)
229
240
  return false;
230
241
  return !asks(g);
@@ -259,6 +270,10 @@ export function buildGraph(order, deps) {
259
270
  const said = deps?.get(id), valid = said ? [...new Set(said.filter(d => order.indexOf(d) >= 0 && order.indexOf(d) < k))] : [];
260
271
  g.set(id, said && (valid.length || !said.length) ? valid : k > 0 ? [order[k - 1]] : []); // "x <- none" = no dependency; only unknown/later ids = keep the owner order
261
272
  });
273
+ const reaches = (from, to, seen = new Set()) => (g.get(from) ?? []).some(d => d === to || (!seen.has(d) && (seen.add(d), reaches(d, to, seen))));
274
+ const sk = order.indexOf('security'), ik = order.indexOf('implement');
275
+ if (sk > ik && ik >= 0 && !reaches('security', 'implement'))
276
+ g.set('security', [...(g.get('security') ?? []), 'implement'].sort((a, b) => order.indexOf(a) - order.indexOf(b))); // Security reviews the change: it never runs before the implementation exists
262
277
  const qk = order.indexOf('qc');
263
278
  if (qk > 0) {
264
279
  const before = order.slice(0, qk), used = new Set(before.flatMap(id => g.get(id) ?? []));
@@ -291,15 +306,17 @@ function makeHandle(runId, runDir, history, listeners, done, sendToDirector, sto
291
306
  };
292
307
  }
293
308
  export function startTeamRun(opts) {
294
- const { config, goal } = opts, simulated = opts.simulated === true;
309
+ const { config } = opts, simulated = opts.simulated === true, persistent = opts.persistent === true;
310
+ let goal = opts.goal; // the CURRENT objective's request; a continuous session replaces it per objective
295
311
  const known = [...(opts.secrets ?? []), ...knownSecretValues(config, opts.projectRoot)];
296
312
  const journal = createTeamJournal({ projectRoot: opts.projectRoot, ...(opts.now ? { now: opts.now } : {}), secrets: known });
297
313
  const runner = opts.runner ?? (simulated ? createSimulatedRunner(opts.simSpeed !== undefined ? { speed: opts.simSpeed } : {}) : dispatchRunner);
298
314
  const history = [], listeners = new Set();
299
- const abort = new AbortController();
315
+ let abort = new AbortController(); // per objective in a continuous session (a new objective gets a fresh one); STOP aborts the current one
300
316
  const inbox = [], notes = [], convo = [];
301
317
  const lanes = config.lanes ?? [], ownerLane = lanes.find(l => l.id === opts.lane) ?? null;
302
- let order = ownerLane ? [...ownerLane.order] : lanes.length ? [...lanes[0].order] : effectiveOrder(config); // with lanes: the chosen lane's teams (set at intake)
318
+ const initialOrder = () => ownerLane ? [...ownerLane.order] : lanes.length ? [...lanes[0].order] : effectiveOrder(config);
319
+ let order = initialOrder(); // with lanes: the chosen lane's teams (set at intake)
303
320
  let earlyTest = null; // PF-TEST / PF-PROG: the Tester team's early test plan, written while Implement works
304
321
  const outs = new Map(); // flow order; each team's latest output
305
322
  const passes = new Map(), sentBack = new Map(), asks = new Map(), backs = new Map();
@@ -358,6 +375,15 @@ export function startTeamRun(opts) {
358
375
  const finish = (outcome, report) => {
359
376
  if (finished)
360
377
  return;
378
+ if (persistent && outcome !== 'stopped' && !closing) {
379
+ endObjective(outcome, report);
380
+ return;
381
+ } // continuous session: the objective ends, the run stays open
382
+ for (const i of inputs.values())
383
+ if (i.status === 'received' || i.status === 'queued')
384
+ setInput(i, 'cancelled', 'the run ended before this input was handled');
385
+ else if (i.status === 'applied')
386
+ setInput(i, outcome === 'delivered' ? 'resolved' : outcome === 'stopped' ? 'cancelled' : 'answered', outcome === 'stopped' ? 'the run was stopped before this input was delivered' : `run ${outcome}`);
361
387
  emit({ type: 'run.completed', outcome, report }); // emitted while !finished (guard allows run.completed anyway)
362
388
  finished = true;
363
389
  closeSessions();
@@ -369,11 +395,116 @@ export function startTeamRun(opts) {
369
395
  paused = false;
370
396
  wakeAll();
371
397
  wakeNow?.();
398
+ idleWake?.();
372
399
  journal.writeArtifact('report.md', report);
373
400
  resolveDone(outcome);
374
401
  };
375
- const halted = () => { if (finished)
402
+ const halted = () => { if (finished || ended)
376
403
  throw new Halt(); };
404
+ // ---- Continuous Director session: objectives, durable owner inputs, requirement ledger ----
405
+ /** One run = many objectives. `ended` = the current objective is over and the run is idle (persistent mode only). */
406
+ let objective = 1, ended = false, closing = false, lastOutcome = 'delivered', lastReport = '', idleWake = null, reqSeq = 0, inputSeq = 0;
407
+ const pastObjectives = [];
408
+ const inputs = new Map(), byClient = new Map();
409
+ const MAX_PENDING_INPUTS = 100; // backpressure: unhandled inputs beyond this are rejected (the GUI shows 429), never silently dropped
410
+ const setInput = (i, status, note, intent) => {
411
+ if (i.status === status && (!intent || intent === i.intent))
412
+ return;
413
+ i.status = status;
414
+ if (intent)
415
+ i.intent = intent;
416
+ emit({ type: 'owner.input', inputId: i.inputId, inputSeq: i.inputSeq, status, intent: i.intent, objective: i.objective, ...(i.clientRequestId ? { clientRequestId: i.clientRequestId } : {}), ...(note ? { note: oneLine(note, 200) } : {}) });
417
+ };
418
+ const setInputs = (ids, status, note, intent) => { for (const id of ids) {
419
+ const i = inputs.get(id);
420
+ if (i)
421
+ setInput(i, status, note, intent);
422
+ } };
423
+ /** Requirement ledger: one line per owner requirement / correction / cancel, as an event and in requirements.md (no transcript copy). */
424
+ const recordReq = (inputIds, kind, text) => {
425
+ const reqId = `R-${++reqSeq}`, t = oneLine(journal.redact(text), 600);
426
+ emit({ type: 'requirement.recorded', reqId, inputId: inputIds[0] ?? '', objective, kind, text: t });
427
+ journal.appendArtifact('requirements.md', `${reqSeq === 1 ? '# Owner requirements (this run)\n\n' : ''}- ${reqId} [objective ${objective}, ${kind}${inputIds.length ? `, ${inputIds.join(' ')}` : ''}] ${t}\n`);
428
+ };
429
+ const kindOf = (text) => CANCEL_RE.test(text) ? 'cancel' : CORRECTION_RE.test(text) || REDIRECT_RE.test(text) ? 'correction' : 'requirement';
430
+ /** Status answered from the run state: no model call, no fake progress. */
431
+ const statusText = () => {
432
+ const busy = [...waits].filter(([, w]) => w !== 'idle').map(([a, w]) => `${nameOf(a)} (${w})`);
433
+ const tasks = new Map();
434
+ let from = 0;
435
+ for (let k = history.length - 1; k >= 0; k--)
436
+ if (history[k]?.type === 'objective.started') {
437
+ from = k;
438
+ break;
439
+ }
440
+ for (const e of history.slice(from))
441
+ if (e.type === 'task.updated')
442
+ tasks.set(e.taskId, e.status);
443
+ const count = (st) => [...tasks.values()].filter(v => v === st).length;
444
+ const stage = [...history].reverse().find(e => e.type === 'stage.changed');
445
+ const pend = [...inputs.values()].filter(i => i.status === 'queued' || i.status === 'received').length;
446
+ return ended
447
+ ? `Status (from the run state, no agent was asked): objective ${objective} is ${lastOutcome}; the team is idle and ready for your next request.${pend ? ` ${pend} message(s) queued.` : ''}`
448
+ : `Status (from the run state, no agent was asked): objective ${objective}, stage ${stage && stage.type === 'stage.changed' ? stage.team ?? stage.stage : 'starting'}. Working now: ${busy.join(', ') || 'nobody (between steps)'}. Tasks: ${count('done')} done, ${count('running')} running, ${count('failed')} failed.${pend ? ` ${pend} message(s) waiting.` : ''}`;
449
+ };
450
+ /** The objective is over; the persistent run stays open (sessions, tool hub, journal) and waits for the next owner input. */
451
+ function endObjective(outcome, report) {
452
+ if (ended)
453
+ return;
454
+ ended = true;
455
+ lastOutcome = outcome;
456
+ lastReport = report;
457
+ abort.abort();
458
+ earlyTest?.ctl.abort(); // nothing of this objective keeps running
459
+ pastObjectives.push({ n: objective, text: oneLine(goal, 300), outcome });
460
+ // completion race: whatever is still in the inbox was not reviewed by the Director (even if steered into a turn): it starts the next objective, never lost
461
+ for (const it of inbox)
462
+ setInputs(it.ids, 'queued', 'arrived while the objective was finishing: it starts the next objective');
463
+ for (const i of inputs.values())
464
+ if (i.objective === objective && (i.status === 'applied' || i.status === 'received'))
465
+ setInput(i, outcome === 'delivered' ? 'resolved' : 'answered', `objective ${objective} ${outcome}`); // completion race: never lost, never applied to finished work
466
+ journal.writeArtifact('report.md', report);
467
+ journal.writeArtifact(`report-objective-${objective}.md`, report); // report.md = latest; every objective keeps its own report
468
+ emit({ type: 'run.idle', objective, outcome, report });
469
+ idleWake?.();
470
+ }
471
+ /** Next objective from the queued inputs: per-objective state is reset, sessions / hub / ledgers / journal are kept. */
472
+ function startObjective(items) {
473
+ const ids = items.flatMap(i => i.ids);
474
+ objective++;
475
+ ended = false;
476
+ abort = new AbortController();
477
+ goal = items.map(i => i.text).join('\n\n');
478
+ goalPath = '';
479
+ goalRevision++; // contributions of the previous objective are stale
480
+ order = initialOrder();
481
+ graph = null;
482
+ collabMode = 'PARALLEL_MERGE';
483
+ delegateTo = null;
484
+ briefs.clear();
485
+ intakeBrief = '';
486
+ intakeIntro = '';
487
+ assumptions = '';
488
+ laneNote = '';
489
+ notes.length = 0;
490
+ convo.length = 0;
491
+ qaRounds.length = 0;
492
+ needRounds = 0;
493
+ forced = false;
494
+ ownerAsks = 0;
495
+ criticalSince = false;
496
+ emit({ type: 'objective.started', objective, text: oneLine(journal.redact(goal), 2000), inputIds: ids });
497
+ for (const id of ids) {
498
+ const i = inputs.get(id);
499
+ if (i) {
500
+ i.objective = objective;
501
+ setInput(i, 'applied', `objective ${objective}`);
502
+ }
503
+ }
504
+ for (const it of items)
505
+ recordReq(it.ids, kindOf(it.text), it.text); // one ledger line per input (a merged batch still reaches the Director as one goal)
506
+ }
507
+ const sessionBlock = () => pastObjectives.length ? `\nEARLIER IN THIS SESSION (same run, same team; the owner may refer to it):\n${pastObjectives.slice(-5).map(o => `- objective ${o.n} (${o.outcome}): ${o.text}`).join('\n')}${lastReport ? `\nLAST REPORT TO THE OWNER (shortened):\n${clip(lastReport, 1500)}` : ''}\n` : '';
377
508
  /** Live-only event (never journaled): deltas, native tool calls. */
378
509
  const liveEmit = (ev) => {
379
510
  if (finished)
@@ -528,7 +659,7 @@ export function startTeamRun(opts) {
528
659
  const goalFile = () => { if (!goalPath) {
529
660
  goalPath = join(journal.runDir, journal.writeArtifact('owner-request.md', goal));
530
661
  } return goalPath; };
531
- const common = () => `GOAL: ${oneLine(goal, 2000)}\n${assumptionsBlock()}${notes.length ? `\nOWNER NOTES (follow them):\n${notes.map(n => `- ${n}`).join('\n')}\n` : ''}${intakeIntro ? `\nDIRECTOR BRIEF:\n${intakeIntro}\n` : ''}${attachmentPromptBlock(atts, excerpts)}`;
662
+ const common = () => `GOAL: ${oneLine(goal, 2000)}\n${sessionBlock()}${assumptionsBlock()}${notes.length ? `\nOWNER NOTES (follow them):\n${notes.map(n => `- ${n}`).join('\n')}\n` : ''}${intakeIntro ? `\nDIRECTOR BRIEF:\n${intakeIntro}\n` : ''}${attachmentPromptBlock(atts, excerpts)}`;
532
663
  // ---- one agent turn ----
533
664
  /** Heuristic step label for real runners' activity lines (null = not a step boundary). */
534
665
  const stepOf = (text) => /^\$ /.test(text) ? 'Running commands' : /^edited |^tool: (Edit|Write|MultiEdit|NotebookEdit)/.test(text) ? 'Editing files' : /^tool: (Read|Grep|Glob|LS)/.test(text) ? 'Reading code' : /^thinking/.test(text) ? 'Thinking' : /^tool: /.test(text) ? 'Using tools' : null;
@@ -725,8 +856,10 @@ export function startTeamRun(opts) {
725
856
  const own = simAgent(agent);
726
857
  if (!own)
727
858
  step(first);
728
- const ctl = new AbortController(), onAbort = () => ctl.abort();
729
- abort.signal.addEventListener('abort', onAbort, { once: true });
859
+ const ctl = new AbortController(), onAbort = () => ctl.abort(), objAbort = abort; // this objective's controller (a later objective gets a new one)
860
+ objAbort.signal.addEventListener('abort', onAbort, { once: true });
861
+ if (objAbort.signal.aborted)
862
+ ctl.abort();
730
863
  signal?.addEventListener('abort', onAbort, { once: true }); // the pass this turn belongs to was cancelled (a sibling redirected/halted)
731
864
  if (signal?.aborted)
732
865
  ctl.abort();
@@ -786,7 +919,7 @@ export function startTeamRun(opts) {
786
919
  ent.busy = false;
787
920
  inSession = false;
788
921
  }
789
- if (!res.ok && (res.transport || stalled) && !abort.signal.aborted && !ctl.signal.aborted) {
922
+ if (!res.ok && (res.transport || stalled) && !objAbort.signal.aborted && !ctl.signal.aborted) {
790
923
  dropSession(agent);
791
924
  const why = stalled ? `no model output for ${Math.round(stallMs / 1000)} s (stalled stream)` : oneLine(res.reason, 100);
792
925
  runOpts().onActivity?.(`Persistent session failed (${why}); retrying this turn with a fresh one-shot process`);
@@ -794,12 +927,12 @@ export function startTeamRun(opts) {
794
927
  res = await runner(agent, prompt, runOpts());
795
928
  }
796
929
  }
797
- if (!res.ok && stalled && !sess && !abort.signal.aborted && !ctl.signal.aborted) {
930
+ if (!res.ok && stalled && !sess && !objAbort.signal.aborted && !ctl.signal.aborted) {
798
931
  runOpts().onActivity?.(`No model output for ${Math.round(stallMs / 1000)} s (stalled stream); retrying this turn with a fresh process`);
799
932
  fresh();
800
933
  res = await runner(agent, prompt, runOpts());
801
934
  }
802
- if (!res.ok && stalled && !abort.signal.aborted && !ctl.signal.aborted)
935
+ if (!res.ok && stalled && !objAbort.signal.aborted && !ctl.signal.aborted)
803
936
  res = { ok: false, reason: `no model output for ${Math.round(stallMs / 1000)} s, twice (the provider stream stalled); check the CLI/provider connection` };
804
937
  if (res.ok && !own)
805
938
  step(last);
@@ -811,7 +944,7 @@ export function startTeamRun(opts) {
811
944
  finally {
812
945
  if (watch)
813
946
  clearInterval(watch);
814
- abort.signal.removeEventListener('abort', onAbort);
947
+ objAbort.signal.removeEventListener('abort', onAbort);
815
948
  signal?.removeEventListener('abort', onAbort);
816
949
  if (turnCtl.get(agent.id) === ctl)
817
950
  turnCtl.delete(agent.id);
@@ -840,7 +973,7 @@ export function startTeamRun(opts) {
840
973
  if (!res.ok && interrupted.delete(agent.id)) {
841
974
  emit({ type: 'agent.interrupted', agentId: agent.id });
842
975
  await gate(agent.id);
843
- const guidance = [...inbox, ...notes.slice(-3)];
976
+ const guidance = [...inbox.map(i => i.text), ...notes.slice(-3)];
844
977
  p = `${prompt}\n\nYOUR PREVIOUS ATTEMPT AT THIS TURN WAS INTERRUPTED BY THE OWNER. Start this turn again${guidance.length ? ` and follow the owner's newest guidance:\n${guidance.map(g => `- ${clip(g, 1500)}`).join('\n')}` : '.'}`;
845
978
  continue;
846
979
  }
@@ -1125,23 +1258,31 @@ export function startTeamRun(opts) {
1125
1258
  let redirect = false;
1126
1259
  if (inbox.length && modelDirector()) { // PF-WAKE coalescing: messages that arrive within the window share one Director turn (STOP never waits: it is handled on arrival)
1127
1260
  const win = Number(process.env['CKIT_WAKE_WINDOW_MS'] ?? 1500), left = lastInboxAt + (Number.isFinite(win) ? Math.max(0, win) : 1500) - Date.now();
1128
- const bypass = criticalSince || inbox.some(t => URGENT_RE.test(t)); // urgent steer / critical finding: wake now (STOP is handled on arrival)
1261
+ const bypass = criticalSince || inbox.some(t => URGENT_RE.test(t.text)); // urgent steer / critical finding: wake now (STOP is handled on arrival)
1129
1262
  if (left > 0 && !bypass)
1130
1263
  await wakeSleep(left);
1131
1264
  halted();
1132
1265
  criticalSince = false;
1133
1266
  if (inbox.length > 1)
1134
- inbox.splice(0, inbox.length, inbox.join('\n\n'));
1267
+ inbox.splice(0, inbox.length, { text: inbox.map(i => i.text).join('\n\n'), ids: inbox.flatMap(i => i.ids) });
1135
1268
  }
1136
1269
  while (inbox.length) {
1137
- const text = inbox.shift();
1270
+ const it = inbox.shift(), text = it.text;
1138
1271
  const d = await decide(text);
1272
+ if (finished || ended) {
1273
+ inbox.unshift(it);
1274
+ if (!finished)
1275
+ setInputs(it.ids, 'queued', 'the objective ended first: it starts the next objective');
1276
+ } // never lost to a completion race
1139
1277
  halted();
1140
1278
  emit({ type: 'director.decision', decision: d.decision, note: d.note });
1141
1279
  if (d.decision === 'stop') {
1280
+ setInputs(it.ids, 'resolved', 'the Director stopped the run', 'STOP');
1142
1281
  doStop('Owner asked the Director to stop.');
1143
1282
  throw new Halt();
1144
1283
  }
1284
+ recordReq(it.ids, kindOf(text), text);
1285
+ setInputs(it.ids, 'applied', d.decision === 'redirect' ? 'the Director redirected the work to it' : 'the Director took it into the current work');
1145
1286
  notes.push(d.note);
1146
1287
  goalRevision++;
1147
1288
  record('d-owner', { title: 'Owner instruction', selected: d.decision, status: 'committed', authority: 'owner', rationale: d.note });
@@ -1931,26 +2072,43 @@ export function startTeamRun(opts) {
1931
2072
  else
1932
2073
  emit({ type: 'agent.started', agentId: config.director.id, task: 'delivery report' });
1933
2074
  directorSay('all', report);
1934
- await drain();
2075
+ if (!persistent)
2076
+ await drain(); // continuous session: input that arrives during the report starts the next objective (never a note on finished work)
1935
2077
  finish('delivered', journal.redact(report));
1936
2078
  }
2079
+ /** One run, many objectives: in a continuous session the run goes idle after each objective and the next owner input starts the next one. */
1937
2080
  async function pipeline() {
1938
- try {
1939
- if (toolsOn) {
1940
- try {
1941
- hub = await startToolHub(bus, { runId: journal.runId });
1942
- if (finished) {
1943
- hub.close();
1944
- hub = null;
1945
- }
1946
- }
1947
- catch (e) {
1948
- emit({ type: 'agent.activity', agentId: config.director.id, text: oneLine(`CKit tools unavailable (${e instanceof Error ? e.message : String(e)}); agents run without them`, 160) });
2081
+ if (toolsOn) {
2082
+ try {
2083
+ hub = await startToolHub(bus, { runId: journal.runId });
2084
+ if (finished) {
2085
+ hub.close();
2086
+ hub = null;
1949
2087
  }
1950
2088
  }
1951
- await intake();
2089
+ catch (e) {
2090
+ emit({ type: 'agent.activity', agentId: config.director.id, text: oneLine(`CKit tools unavailable (${e instanceof Error ? e.message : String(e)}); agents run without them`, 160) });
2091
+ }
2092
+ }
2093
+ for (;;) {
2094
+ await runObjective();
2095
+ if (!persistent || finished)
2096
+ return;
2097
+ if (!ended)
2098
+ endObjective('failed', 'The objective ended without a result.');
2099
+ while (!inbox.length && !finished)
2100
+ await new Promise(r => { idleWake = r; });
2101
+ idleWake = null;
1952
2102
  if (finished)
1953
2103
  return;
2104
+ startObjective(inbox.splice(0));
2105
+ }
2106
+ }
2107
+ async function runObjective() {
2108
+ try {
2109
+ await intake();
2110
+ if (finished || ended)
2111
+ return;
1954
2112
  for (;;) {
1955
2113
  try {
1956
2114
  handoff = '';
@@ -1999,35 +2157,72 @@ export function startTeamRun(opts) {
1999
2157
  }
2000
2158
  const initial = opts.attachments?.length ? addAttachments(opts.attachments) : [];
2001
2159
  emit({ type: 'run.started', goal, config, simulated, ...(initial.length ? { attachments: initial } : {}) });
2160
+ if (persistent)
2161
+ recordReq([], 'requirement', goal);
2002
2162
  void Promise.resolve().then(pipeline);
2003
- return makeHandle(journal.runId, journal.runDir, history, listeners, done, (raw, files) => {
2163
+ return makeHandle(journal.runId, journal.runDir, history, listeners, done, (raw, files, o) => {
2164
+ const no = (reason) => ({ inputId: '', inputSeq: 0, status: 'rejected', duplicate: false, reason });
2004
2165
  if (finished)
2005
- return;
2166
+ return no('the run has finished; start a new run');
2167
+ const cid = typeof o?.clientRequestId === 'string' && o.clientRequestId.trim() ? o.clientRequestId.trim().slice(0, 100) : undefined;
2168
+ const dup = cid ? byClient.get(cid) : undefined;
2169
+ if (dup)
2170
+ return { inputId: dup.inputId, inputSeq: dup.inputSeq, status: dup.status, duplicate: true }; // a retried send: same input, never a second copy
2171
+ if ([...inputs.values()].filter(i => i.status === 'received' || i.status === 'queued').length >= MAX_PENDING_INPUTS)
2172
+ return no('too many messages are waiting; let the team catch up and send again');
2173
+ if (!raw.trim() && !files?.length)
2174
+ return no('empty message');
2006
2175
  const added = files?.length ? addAttachments(files) : [];
2007
2176
  if (!raw.trim() && added.length === 0)
2008
- return;
2177
+ return no('empty message');
2009
2178
  const text = raw.trim() ? raw : 'Please take the attached file(s) into account.';
2010
- emit({ type: 'user.message', text, ...(added.length ? { attachments: added } : {}) });
2179
+ const LONG_INPUT = 4000; // a long message is kept whole in the journal + a file; a running turn gets a pointer to it, never a silent cut
2180
+ const steerText = text.length <= LONG_INPUT ? text : `${clip(text, LONG_INPUT)}\n[the owner message is ${text.length} chars; the whole message is saved at ${join(journal.runDir, journal.writeArtifact(`owner-input-${inputSeq + 1}.md`, text))} - read it completely]`;
2181
+ const full = added.length ? `${steerText} [owner attached: ${added.map(a => a.path).join(', ')}]` : steerText;
2182
+ const rec = { inputId: `in-${++inputSeq}`, inputSeq, status: 'received', intent: 'PENDING', objective, ...(cid ? { clientRequestId: cid } : {}) };
2183
+ inputs.set(rec.inputId, rec);
2184
+ if (cid)
2185
+ byClient.set(cid, rec);
2186
+ emit({ type: 'user.message', text, inputId: rec.inputId, ...(added.length ? { attachments: added } : {}) });
2187
+ emit({ type: 'owner.input', inputId: rec.inputId, inputSeq: rec.inputSeq, status: 'received', intent: 'PENDING', objective, ...(cid ? { clientRequestId: cid } : {}) }); // journaled (sync append) before the ack returns
2188
+ const ack = () => ({ inputId: rec.inputId, inputSeq: rec.inputSeq, status: rec.status, duplicate: false });
2011
2189
  if (STOP_RE.test(text)) {
2190
+ setInput(rec, 'resolved', 'stop', 'STOP');
2012
2191
  emit({ type: 'director.decision', decision: 'stop', note: 'Owner asked to stop' });
2013
2192
  doStop('Owner asked the Director to stop.');
2014
- return;
2193
+ return ack();
2015
2194
  }
2016
2195
  if (waiting) {
2017
2196
  const w = waiting;
2018
- w.wake({ how: 'answer', text: added.length ? `${text} [owner attached: ${added.map(a => a.path).join(', ')}]` : text });
2019
- return;
2197
+ setInput(rec, 'applied', 'answers the Director question', 'ANSWER_PENDING_QUESTION');
2198
+ w.wake({ how: 'answer', text: full });
2199
+ return ack();
2020
2200
  }
2201
+ if (!added.length && text.length <= 60 && STATUS_RE.test(text)) {
2202
+ directorSay('all', statusText());
2203
+ setInput(rec, 'answered', 'answered from the run state (no model call)', 'STATUS_QUERY');
2204
+ return ack();
2205
+ }
2206
+ const k = kindOf(text), intent = k === 'cancel' ? 'CANCEL_SCOPE' : k === 'correction' ? 'CORRECTION' : ended ? 'NEW_WORK_ITEM' : 'ADD_REQUIREMENT';
2207
+ lastInboxAt = Date.now();
2208
+ inbox.push({ text: full, ids: [rec.inputId] });
2209
+ if (ended) {
2210
+ setInput(rec, 'queued', 'starts the next objective', intent);
2211
+ idleWake?.();
2212
+ return ack();
2213
+ }
2214
+ let steered = false;
2021
2215
  for (const sess of running.values()) {
2022
2216
  try {
2023
- sess.steer(text);
2217
+ if (sess.steer(steerText))
2218
+ steered = true;
2024
2219
  }
2025
2220
  catch { /* steering is best effort */ }
2026
2221
  }
2027
- lastInboxAt = Date.now();
2028
- inbox.push(added.length ? `${text} [owner attached: ${added.map(a => a.path).join(', ')}]` : text);
2222
+ setInput(rec, steered ? 'applied' : 'queued', steered ? 'steered into the running turn; the Director also reviews it at the next step' : 'the Director takes it at the next step', intent);
2029
2223
  if (URGENT_RE.test(text))
2030
2224
  wakeNow?.(); // an urgent steer is not held by the coalescing window
2225
+ return ack();
2031
2226
  }, () => doStop('Stopped from the console.'), {
2032
2227
  proceedWithAssumptions: () => { const w = waiting; if (w && w.assumptions)
2033
2228
  w.wake({ how: 'proceed', text: '' }); },
@@ -2052,7 +2247,13 @@ export function startTeamRun(opts) {
2052
2247
  ctl.abort();
2053
2248
  }
2054
2249
  },
2055
- whenClosed: () => done.then(() => Promise.all(exits)).then(() => undefined), // resolves only after every owned child process has exited
2250
+ whenClosed: () => done.then(() => Promise.all(exits)).then(() => undefined),
2251
+ inputByClient: cid => { const r = byClient.get(cid.trim().slice(0, 100)); return r ? { inputId: r.inputId, inputSeq: r.inputSeq, status: r.status, duplicate: true } : undefined; },
2252
+ close: () => { if (finished)
2253
+ return; closing = true; if (ended)
2254
+ finish(lastOutcome, lastReport || 'Session closed by the owner.');
2255
+ else
2256
+ doStop('Session closed by the owner.'); }, // resolves only after every owned child process has exited
2056
2257
  });
2057
2258
  }
2058
2259
  /** Re-emits a journal with original relative timing / speed (gaps capped at 1.5s/speed). */
@@ -281,7 +281,8 @@ export type TeamEvent = {
281
281
  readonly team?: string;
282
282
  } | {
283
283
  readonly type: 'user.message';
284
- readonly text: string;
284
+ readonly text: string; /** continuous session: the durable input id of this message */
285
+ readonly inputId?: string;
285
286
  readonly attachments?: readonly AttachmentInfo[];
286
287
  } | {
287
288
  readonly type: 'director.consult';
@@ -390,7 +391,53 @@ export type TeamEvent = {
390
391
  readonly type: 'run.completed';
391
392
  readonly outcome: 'delivered' | 'failed' | 'stopped' | 'declined';
392
393
  readonly report: string;
394
+ }
395
+ /** Continuous session: one owner input admitted (durable before the ack) or moved to a new lifecycle state. inputSeq is per run, 1-based. */
396
+ | {
397
+ readonly type: 'owner.input';
398
+ readonly inputId: string;
399
+ readonly inputSeq: number;
400
+ readonly status: OwnerInputStatus;
401
+ readonly intent: OwnerIntent;
402
+ readonly clientRequestId?: string;
403
+ readonly objective: number;
404
+ readonly note?: string;
405
+ }
406
+ /** Continuous session: an objective (one piece of owner work) starts inside the same run; its sessions, ledgers and history are reused. */
407
+ | {
408
+ readonly type: 'objective.started';
409
+ readonly objective: number;
410
+ readonly text: string;
411
+ readonly inputIds: readonly string[];
412
+ }
413
+ /** Continuous session: the objective ended (delivered / failed / declined); the run stays open and idle, waiting for the next owner input. */
414
+ | {
415
+ readonly type: 'run.idle';
416
+ readonly objective: number;
417
+ readonly outcome: 'delivered' | 'failed' | 'declined';
418
+ readonly report: string;
419
+ }
420
+ /** Requirement ledger: an owner requirement / correction / cancelled scope, recorded once per input. */
421
+ | {
422
+ readonly type: 'requirement.recorded';
423
+ readonly reqId: string;
424
+ readonly inputId: string;
425
+ readonly objective: number;
426
+ readonly kind: 'requirement' | 'correction' | 'cancel';
427
+ readonly text: string;
393
428
  });
429
+ /** received = durably admitted; queued = waits for the next objective; applied = steered into the running objective; answered = replied without changing the work;
430
+ * resolved = the objective it belongs to was delivered; cancelled = the run stopped before it was handled; rejected = not admitted (queue full / run closed). */
431
+ export type OwnerInputStatus = 'received' | 'queued' | 'applied' | 'answered' | 'resolved' | 'cancelled' | 'rejected';
432
+ export type OwnerIntent = 'STATUS_QUERY' | 'QUESTION' | 'ADD_REQUIREMENT' | 'CORRECTION' | 'NEW_WORK_ITEM' | 'CANCEL_SCOPE' | 'ANSWER_PENDING_QUESTION' | 'STOP' | 'CONTINUE_OBJECTIVE' | 'PENDING';
433
+ /** What sendToDirector returns: the input is durable in the run journal before this ack. */
434
+ export interface OwnerInputAck {
435
+ readonly inputId: string;
436
+ readonly inputSeq: number;
437
+ readonly status: OwnerInputStatus;
438
+ readonly duplicate: boolean;
439
+ readonly reason?: string;
440
+ }
394
441
  export type TeamEventType = TeamEvent['type'];
395
442
  /** Distributive Omit so each union member keeps its own fields. */
396
443
  export type TeamEventInput = TeamEvent extends infer E ? E extends TeamEvent ? Omit<E, 'seq' | 'at' | 'runId'> : never : never;
@@ -405,7 +452,9 @@ export interface TeamRunHandle {
405
452
  sendToDirector(text: string, files?: readonly {
406
453
  readonly name: string;
407
454
  readonly file: string;
408
- }[]): void;
455
+ }[], opts?: {
456
+ readonly clientRequestId?: string;
457
+ }): OwnerInputAck | void;
409
458
  /** Stops all agents (kills their process groups) and completes the run as 'stopped'. */
410
459
  stop(): void;
411
460
  /** While the Director waits for the owner's answer: carry on with the Director's stated assumptions. No-op otherwise. */
@@ -415,6 +464,10 @@ export interface TeamRunHandle {
415
464
  resume?(): void;
416
465
  /** Cancel the running agent turns now and pause; each interrupted turn is redone after resume (with the owner's newest messages). */
417
466
  interrupt?(): void;
467
+ /** Continuous session: ends an idle persistent run (outcome = the last objective's outcome); while work runs it is the same as stop. */
468
+ close?(): void;
469
+ /** The ack of an earlier input sent with this clientRequestId (a retried send), if any. */
470
+ inputByClient?(clientRequestId: string): OwnerInputAck | undefined;
418
471
  /** Resolves once every agent process this run started has exited (after stop/finish). */
419
472
  whenClosed?(): Promise<void>;
420
473
  /** Resolves when the run completes. */
package/gui/app.css CHANGED
@@ -468,3 +468,4 @@ body.noroster #live{grid-template-columns:0 minmax(0,1fr) var(--iw)}body.noroste
468
468
  .xdh{display:flex;gap:6px;align-items:center;justify-content:space-between}.xsel{font-size:11.5px;margin-top:4px}.xrat{font-size:11px;color:var(--mu);margin-top:3px}.xwait{font-size:11px;color:var(--am);margin-top:3px}
469
469
  .xtask.done{opacity:.7}
470
470
  .xla{font-size:10.5px;color:var(--cy);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.tst.skipped{color:var(--mu);border-color:#3b4a63}.xtask.skipped{opacity:.7}
471
+ .inchip{opacity:.75;font-size:.9em}.inchip.applied,.inchip.resolved,.inchip.answered{color:var(--gr,#5fd38d)}.inchip.rejected,.inchip.cancelled{color:#ff6b6b}
package/gui/app.js CHANGED
@@ -306,7 +306,7 @@
306
306
  feedBanner(e.verdict === 'PASS' ? 'pass' : 'fail', (e.verdict === 'PASS' ? '✔ QC PASS' : '✕ QC FAIL') + ' · loop ' + e.loop + ' — ' + e.summary);
307
307
  setNarr(e.verdict === 'FAIL' ? 'QC phát hiện lỗi → trả về Implement để sửa.' : 'QC PASS — sản phẩm đạt yêu cầu!');
308
308
  break;
309
- case 'user.message': feedBanner('you', '▸ OWNER: ' + e.text); feedAtts(e.attachments); break;
309
+ case 'user.message': feedBanner('you', '▸ OWNER: ' + e.text); if (e.inputId) { var yb = $('feed').lastElementChild; if (yb) yb.setAttribute('data-input', e.inputId); } feedAtts(e.attachments); break;
310
310
  case 'director.consult': feedBanner('dir', '◆ Director consults ' + nm(e.agentId) + ': ' + e.question); if (!S.history) net.pulse(S.config.director.id, e.agentId, undefined, e.question.slice(0, 24)); break;
311
311
  case 'director.decision': feedBanner('dir', '◆ DIRECTOR ' + e.decision.toUpperCase() + ' — ' + e.note); break;
312
312
  case 'lane.chosen': {
@@ -324,7 +324,19 @@
324
324
  break;
325
325
  case 'subagent.activity': if (a && a.subs[e.childId]) { a.subs[e.childId].text = e.text; net.subActivity(e.childId, e.text); } break;
326
326
  case 'subagent.finished': if (a && a.subs[e.childId]) { a.subs[e.childId].state = e.ok ? 'done' : 'failed'; net.finishSub(e.childId, e.ok); feedSub(e.agentId, (e.ok ? '✓ ' : '✕ ') + a.subs[e.childId].kind + ': ' + e.summary); } break;
327
+ case 'owner.input': ownerChip(e); break;
328
+ case 'objective.started':
329
+ S.idle = false; S.objective = e.objective; S.stageIdx = -1; S.stageKey = ''; S.loop = 1;
330
+ feedBanner('you', '◆ Objective ' + e.objective + ' started (same run, same team)'); setNarr('Director is on objective ' + e.objective + '…');
331
+ break;
332
+ case 'run.idle':
333
+ S.idle = true; S.reportText = e.report; S.objective = e.objective;
334
+ S.order.forEach(function (id) { if (A(id).state === 'thinking') { A(id).state = 'idle'; net.setState(id, 'idle'); } });
335
+ feedBanner(e.outcome === 'delivered' ? 'pass' : 'fail', '◆ Objective ' + e.objective + ' ' + e.outcome + ' — the team is ready for your next request (click for the report)', function () { showArtifact('Objective ' + e.objective + ' report', 'report-objective-' + e.objective + '.md'); });
336
+ setNarr('Objective ' + e.objective + ' ' + e.outcome + ' · type your next request, the same team continues');
337
+ break;
327
338
  case 'run.completed':
339
+ S.idle = false;
328
340
  S.ended = Date.parse(e.at); S.outcome = e.outcome; S.reportText = e.report; if (S.run) S.run.running = false; if (S.view === 'runs') renderRuns();
329
341
  if (S.stageKey) S.stageTimes[S.stageKey] = Date.parse(e.at) - S.lastStageAt;
330
342
  if (e.outcome === 'delivered') { var sl2 = stageList(S.config); S.stageIdx = sl2.length; S.stageKey = 'done'; net.setStage(sl2.length, S.loop, sl2.length); }
@@ -381,6 +393,16 @@
381
393
  $('bTerm').onclick = function () { dockView(UI.dockView === 'term' ? 'chat' : 'term'); };
382
394
  function teamLbl(id) { if (id === 'director') return 'Director'; var t = extrasOf(S.config).filter(function (x) { return x.id === id; })[0]; return t ? t.name : ({ba: 'BA', implement: 'Implement', qc: 'QC'})[id] || id; }
383
395
  function feedPhase(t, team) { $('feed').appendChild(h('div', {class: 'fphase', style: 'color:' + TC[team], text: '▍' + t})); feedScroll(); }
396
+ /* Per-message status chip: received → queued / applied / answered → resolved (text only, never HTML). */
397
+ var IN_LABEL = {received: 'received', queued: 'queued for the next step', applied: 'taken into the work', answered: 'answered', resolved: 'done', cancelled: 'cancelled', rejected: 'not accepted'};
398
+ function ownerChip(e) {
399
+ var feed = $('feed'), chip = feed.querySelector('[data-in="' + e.inputId + '"]');
400
+ if (!chip) {
401
+ var last = feed.querySelector('.fban.you[data-input="' + e.inputId + '"]'); if (!last || last.querySelector('.inchip')) return; // bound by inputId, never to whichever owner row is last
402
+ chip = h('span', {class: 'inchip'}); chip.setAttribute('data-in', e.inputId); last.appendChild(chip);
403
+ }
404
+ chip.textContent = ' · ' + (IN_LABEL[e.status] || e.status); chip.className = 'inchip ' + e.status; if (e.note) chip.title = e.note;
405
+ }
384
406
  function feedBanner(kind, t, onclick) { $('feed').appendChild(h('div', {class: 'fban ' + kind + (onclick ? ' click' : '') + (curTab ? ' fhide' : ''), text: t, onclick: onclick})); feedScroll(); count(); }
385
407
  function fmtSize(n) { return n >= 1048576 ? (n / 1048576).toFixed(1) + ' MB' : n >= 1024 ? Math.round(n / 1024) + ' KB' : n + ' B'; }
386
408
  function attUrl(a) { return '/api/runs/' + encodeURIComponent((S.run && S.run.runId) || 'current') + '/attachment/' + encodeURIComponent(a.name) + '?t=' + encodeURIComponent(TOKEN); }
@@ -674,6 +696,9 @@
674
696
  $('cnote').textContent = wt ? (S.waiting.team ? 'The run is paused: the Director is waiting for your decision.' : 'The Director is waiting for you: no team has started and nothing is running.') : live ? '' : sim ? 'Demo mode: no real agent is configured, so this starts a simulated run.' : 'Starts real agents in ' + shortPath(S.projectRoot); $('cnote').title = S.projectRoot || '';
675
697
  waitButtons(wt); if (wt) setTimeout(function () { $('msg').focus(); }, 30);
676
698
  }
699
+ var cs = $('closeSess'), showCs = !!(live && S.idle && S.run && S.run.running && !S.outcome && !S.replay); // only between objectives: closing mid-work is Stop
700
+ if (!cs && showCs) { cs = h('button', {class: 'chip', id: 'closeSess', text: 'Close session', title: 'End this continuous session (the team stops waiting for more requests)', onclick: function () { api('POST', runBase() + '/close').then(function (r) { if (r.status !== 200) toast(r.body.error || 'No active run'); }); }}); $('chips').parentNode.insertBefore(cs, $('wbtns')); }
701
+ if (cs) cs.hidden = !showCs;
677
702
  var lanes = (S.config && S.config.lanes) || [], sig = live ? '' : lanes.map(function (l) { return l.id + ':' + l.name; }).join('|');
678
703
  if (S.laneSig !== sig) { S.laneSig = sig; var old = $('lane').value, ns = laneSelect(); $('lane').innerHTML = ns ? ns.innerHTML : ''; if (old && ns && Array.prototype.some.call($('lane').options, function (o) { return o.value === old; })) $('lane').value = old; }
679
704
  $('lanewrap').hidden = !sig; syncEnh();
@@ -1001,7 +1026,7 @@
1001
1026
  var ids = pendingIds(); if (!ids) return Promise.resolve(false);
1002
1027
  if (!goal.trim() && !ids.length) return Promise.resolve(false);
1003
1028
  S.starting = true;
1004
- return api('POST', '/api/runs', Object.assign({goal: goal, simulated: sim, attachments: ids}, lane ? {lane: lane} : {})).then(function (r) { S.starting = false; if (r.status !== 200) { toast(r.body.error || 'could not start the run'); return false; } clearPending(); closeModal(); S.replay = false; setView('live'); return true; });
1029
+ return api('POST', '/api/runs', Object.assign({goal: goal, simulated: sim, attachments: ids, persistent: true}, lane ? {lane: lane} : {})).then(function (r) { S.starting = false; if (r.status !== 200) { toast(r.body.error || 'could not start the run'); return false; } clearPending(); closeModal(); S.replay = false; setView('live'); return true; });
1005
1030
  }
1006
1031
  /* Start another run even while one is live (plain Send still messages the run on screen). */
1007
1032
  $('sendNew').onclick = function () {
@@ -1012,8 +1037,22 @@
1012
1037
  var chip = !!text; text = (text || $('msg').value).trim(); if (!text && !PEND.length) return;
1013
1038
  if (!(S.run && S.run.running && !S.outcome)) { startRun(text, simDefault(), $('lanewrap').hidden ? '' : $('lane').value).then(function (ok) { if (ok) { $('msg').value = ''; REQ.applied = null; syncEnh(); } }); return; }
1014
1039
  var ids = chip ? [] : pendingIds(); if (!ids) return;
1015
- api('POST', runBase() + '/message', {text: text, attachments: ids}).then(function (r) { if (r.status !== 200) toast(r.body.error || 'No active run'); else { if (!chip) { $('msg').value = ''; clearPending(); } } });
1040
+ /* one clientRequestId per draft: a resend of the same unsent text + files after a network failure reuses it, so the server dedupes */
1041
+ var key = text + '\u0000' + ids.join(',');
1042
+ if (!SENDQ || SENDQ.key !== key) SENDQ = {key: key, cid: 'c' + Date.now().toString(36) + Math.random().toString(36).slice(2, 8)};
1043
+ var mine = SENDQ, base = runBase(), body = {text: text, attachments: ids, clientRequestId: mine.cid}, sentPend = chip ? [] : PEND.slice();
1044
+ var post = function (n) { // a network error is retried with the SAME clientRequestId and the SAME run: a retry never sends the message twice or to another run
1045
+ return api('POST', base + '/message', body).then(function (r) {
1046
+ if (SENDQ === mine) SENDQ = null;
1047
+ if (r.status !== 200 || r.body.ok === false) { toast(r.body.error || 'No active run'); return; }
1048
+ if (chip) return;
1049
+ if ($('msg').value.trim() === text) $('msg').value = ''; // never clear a newer draft typed while this send was in flight
1050
+ if (sentPend.length && sentPend.every(function (p) { return PEND.indexOf(p) >= 0; })) { PEND = PEND.filter(function (p) { if (sentPend.indexOf(p) >= 0) { if (p.thumb) URL.revokeObjectURL(p.thumb); return false; } return true; }); renderPending(); }
1051
+ }, function () { if (n > 0) return new Promise(function (ok) { setTimeout(ok, 800); }).then(function () { return post(n - 1); }); toast('Delivery unknown: the network failed. Your message is still in this box; send again (it will not be duplicated).'); });
1052
+ };
1053
+ post(2);
1016
1054
  }
1055
+ var SENDQ = null;
1017
1056
  /* "@" mentions: typing @ in a request box lists files and folders of the workspace; the chosen path goes into the text as @path */
1018
1057
  var MENT = null;
1019
1058
  function mentionClose() { if (MENT) { MENT.box.remove(); MENT = null; } }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ngockhoale/ckit",
3
- "version": "0.4.5",
3
+ "version": "0.5.0",
4
4
  "description": "CKit — local Agent Company: a Director plus BA / Implement / QC teams running your own codex, claude and omp CLIs, with a web Mission Control (ckit gui).",
5
5
  "type": "module",
6
6
  "bin": {