@dadado/agent-kit-cli 6.7.2 → 6.9.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.
@@ -0,0 +1,600 @@
1
+ import {
2
+ readRunQueueState,
3
+ runPlanLoop,
4
+ shouldUseLiveTui,
5
+ withLiveTui
6
+ } from "./chunk-3Z4PGEEJ.js";
7
+ import {
8
+ DRIVER_EVENTS_FORMATS,
9
+ DRIVER_PROTOCOL_VERSION,
10
+ DriverAgentSink,
11
+ createDriverAnswerReader,
12
+ createDriverEmitter,
13
+ driverReplies,
14
+ driverStop
15
+ } from "./chunk-CXDAT76O.js";
16
+ import {
17
+ REVIEW_PACK_SLASH,
18
+ runReviewJob
19
+ } from "./chunk-S7XAV6JK.js";
20
+ import {
21
+ detectAgentBackend,
22
+ listDetectBackendIds
23
+ } from "./chunk-BB22FGQ4.js";
24
+ import "./chunk-BSYQJ5WF.js";
25
+ import {
26
+ LAND_ON_GATE_DESCRIPTION,
27
+ classifyGateExit,
28
+ landGateExit
29
+ } from "./chunk-26KXYR5T.js";
30
+ import "./chunk-3LLXDHIU.js";
31
+ import {
32
+ negatedFlag
33
+ } from "./chunk-XDCCYBCJ.js";
34
+ import "./chunk-L5V3W3DY.js";
35
+ import "./chunk-MUTTNRX4.js";
36
+ import {
37
+ buildDispatchPrompt,
38
+ classifySlash,
39
+ ensureDispatchLogPath,
40
+ normalizeSlashName,
41
+ promoteBlockedMessage,
42
+ readCommandFile,
43
+ runHeadlessDispatch,
44
+ unknownSlashMessage
45
+ } from "./chunk-BZI5G3OZ.js";
46
+ import {
47
+ getBackend
48
+ } from "./chunk-6UKI4CAN.js";
49
+ import {
50
+ HITL_UNANSWERED_EXIT_CODE,
51
+ formatHitlSummary,
52
+ hitlExitCode
53
+ } from "./chunk-MTLQN57O.js";
54
+ import "./chunk-WGLPZXNU.js";
55
+ import "./chunk-6RRG3WOE.js";
56
+ import "./chunk-QTON2GQX.js";
57
+ import {
58
+ logger
59
+ } from "./chunk-ZB43YMHW.js";
60
+ import {
61
+ HANDOFF_REL
62
+ } from "./chunk-C4Q77GGJ.js";
63
+ import "./chunk-5B4DVO6C.js";
64
+
65
+ // src/commands/run.ts
66
+ import { homedir } from "os";
67
+ import path2 from "path";
68
+ import { defineCommand } from "citty";
69
+
70
+ // src/plan-loop/dispatch-driver.ts
71
+ import { readFile } from "fs/promises";
72
+ import path from "path";
73
+ var DISPATCH_DRIVER_TICK = 1;
74
+ var QUEUE_STATE_POLL_MS = 1e3;
75
+ function projectQueueState(handoff) {
76
+ const { queue, cursor, current, status } = readRunQueueState(handoff);
77
+ if (queue.length === 0) return { cursor: null, total: 0, current: null, status: null };
78
+ return { cursor, total: queue.length, current, status };
79
+ }
80
+ async function readHandoffText(root) {
81
+ try {
82
+ return await readFile(path.join(root, HANDOFF_REL), "utf8");
83
+ } catch {
84
+ return null;
85
+ }
86
+ }
87
+ async function readQueueState(root) {
88
+ return projectQueueState(await readHandoffText(root) ?? "");
89
+ }
90
+ function createQueueStateWatcher(opts) {
91
+ const read = opts.read ?? (() => readHandoffText(opts.root));
92
+ let last = JSON.stringify(opts.initial);
93
+ let pending = null;
94
+ let busy = null;
95
+ let stopped = false;
96
+ const emit = (next, key) => {
97
+ last = key;
98
+ pending = null;
99
+ opts.emitter.emit({ type: "queue_state", ...next });
100
+ };
101
+ const sample = async () => {
102
+ const text = await read();
103
+ if (text !== null && text.trim() === "") return null;
104
+ const next = projectQueueState(text ?? "");
105
+ return { next, key: JSON.stringify(next) };
106
+ };
107
+ const check = async () => {
108
+ const got = await sample();
109
+ if (!got || stopped) return;
110
+ if (got.key === last) {
111
+ pending = null;
112
+ return;
113
+ }
114
+ if (got.key !== pending) {
115
+ pending = got.key;
116
+ return;
117
+ }
118
+ emit(got.next, got.key);
119
+ };
120
+ const tick = () => {
121
+ if (busy) return busy;
122
+ busy = check().finally(() => {
123
+ busy = null;
124
+ });
125
+ return busy;
126
+ };
127
+ opts.emitter.emit({ type: "queue_state", ...opts.initial });
128
+ const timer = setInterval(() => {
129
+ void tick();
130
+ }, opts.pollMs ?? QUEUE_STATE_POLL_MS);
131
+ timer.unref?.();
132
+ return {
133
+ flush: async () => {
134
+ if (busy) await busy;
135
+ const got = await sample();
136
+ if (!got || stopped || got.key === last) return;
137
+ emit(got.next, got.key);
138
+ },
139
+ stop: () => {
140
+ stopped = true;
141
+ clearInterval(timer);
142
+ }
143
+ };
144
+ }
145
+ async function landDispatchOutcome(opts) {
146
+ const { result } = opts;
147
+ const stop = result.hitl?.stop;
148
+ const trigger = classifyGateExit({ stop, failed: opts.exitCode !== 0 });
149
+ if (!trigger) return;
150
+ const summary = result.lastResult?.resultText.trim() || result.lastResult?.assistantTexts.at(-1)?.trim() || void 0;
151
+ try {
152
+ await landGateExit({
153
+ root: opts.root,
154
+ outcome: {
155
+ trigger,
156
+ exitCode: opts.exitCode,
157
+ reason: stop?.message ?? `${opts.backendId} exited with code ${opts.exitCode}`,
158
+ command: `run ${opts.slash}`,
159
+ backend: opts.backendId,
160
+ logPath: opts.logPath,
161
+ ...stop ? { askId: stop.askId } : {},
162
+ ...summary ? { summary } : {},
163
+ ...result.lastResult ? {
164
+ gateText: [result.lastResult.resultText, ...result.lastResult.assistantTexts].join(
165
+ "\n"
166
+ )
167
+ } : {}
168
+ },
169
+ log: opts.log
170
+ });
171
+ } catch (err) {
172
+ opts.log(`gate-exit: landing failed: ${String(err)}`);
173
+ }
174
+ }
175
+ async function runDispatchDriver(opts) {
176
+ const root = path.resolve(opts.root);
177
+ const emitter = createDriverEmitter(opts.events.write, opts.events.now);
178
+ const reader = createDriverAnswerReader({
179
+ input: opts.events.input,
180
+ emitter,
181
+ tick: () => DISPATCH_DRIVER_TICK
182
+ });
183
+ const writeErr = opts.events.writeErr ?? ((text) => {
184
+ process.stderr.write(text);
185
+ });
186
+ const say = (message, level = "info") => emitter.emit({ type: "log", level, message });
187
+ let ticks = 0;
188
+ let queue = null;
189
+ const finish = async (exitCode, reason, result) => {
190
+ if (queue) {
191
+ await queue.flush();
192
+ queue.stop();
193
+ }
194
+ emitter.emit({
195
+ type: "run_end",
196
+ exitCode,
197
+ ticks,
198
+ pending: null,
199
+ reason,
200
+ planExhausted: false,
201
+ replies: driverReplies(result?.hitl?.replies),
202
+ stop: driverStop(result?.hitl?.stop)
203
+ });
204
+ reader.close();
205
+ return exitCode;
206
+ };
207
+ const detected = await detectAgentBackend(opts.backend, opts.whichFn);
208
+ if (!detected.ok) {
209
+ say(detected.message, "error");
210
+ return finish(1, detected.message);
211
+ }
212
+ const file = await readCommandFile(root, opts.slash);
213
+ if (!file.ok) {
214
+ say(file.message, "error");
215
+ return finish(1, file.message);
216
+ }
217
+ const prompt = buildDispatchPrompt(file.body);
218
+ const initialQueue = await readQueueState(root);
219
+ emitter.emit({
220
+ type: "run_start",
221
+ protocol: DRIVER_PROTOCOL_VERSION,
222
+ command: opts.slash,
223
+ backend: detected.id,
224
+ plan: null,
225
+ pending: null,
226
+ maxTicks: null,
227
+ hitl: opts.noHitl ? "off" : "driver",
228
+ queue: initialQueue
229
+ });
230
+ queue = createQueueStateWatcher({
231
+ root,
232
+ emitter,
233
+ initial: initialQueue,
234
+ pollMs: opts.queuePollMs
235
+ });
236
+ say(`Dispatch: ${opts.slash} via ${detected.id}`);
237
+ say(`Command file: ${path.relative(root, file.path)}`);
238
+ if (opts.dryRun) {
239
+ say("--dry-run: no agent will be started. Prompt:");
240
+ say(prompt);
241
+ return finish(0, "dry-run");
242
+ }
243
+ const logPath = await ensureDispatchLogPath(root);
244
+ say(`Log: ${path.relative(root, logPath)}`);
245
+ const onSigInt = () => {
246
+ queue?.stop();
247
+ emitter.emit({
248
+ type: "run_end",
249
+ exitCode: 130,
250
+ ticks,
251
+ pending: null,
252
+ reason: "interrupted (SIGINT)",
253
+ planExhausted: false
254
+ });
255
+ process.exit(130);
256
+ };
257
+ process.on("SIGINT", onSigInt);
258
+ try {
259
+ ticks = DISPATCH_DRIVER_TICK;
260
+ let result;
261
+ try {
262
+ result = await runHeadlessDispatch({
263
+ backendId: detected.id,
264
+ bin: detected.bin,
265
+ workspace: root,
266
+ prompt,
267
+ model: opts.model,
268
+ logPath,
269
+ spawnFn: opts.spawnFn,
270
+ versionFn: opts.versionFn,
271
+ log: (line) => say(line),
272
+ render: new DriverAgentSink(emitter, DISPATCH_DRIVER_TICK),
273
+ hitl: {
274
+ policy: opts.noHitl ? "off" : "driver",
275
+ readAnswer: reader.read,
276
+ write: writeErr
277
+ }
278
+ });
279
+ } catch (err) {
280
+ say(String(err), "error");
281
+ return finish(1, `${opts.slash} failed to start: ${String(err)}`);
282
+ }
283
+ for (const line of formatHitlSummary(result.hitl)) say(line);
284
+ const exitCode = hitlExitCode(result.exitCode, result.hitl);
285
+ if (opts.landOnGate) {
286
+ await landDispatchOutcome({
287
+ root,
288
+ slash: opts.slash,
289
+ backendId: detected.id,
290
+ logPath,
291
+ exitCode,
292
+ result,
293
+ log: (line) => say(line, "warn")
294
+ });
295
+ }
296
+ const stop = result.hitl?.stop;
297
+ const reason = stop ? stop.message : exitCode === 0 ? "session ended" : `${detected.id} exited with code ${exitCode}`;
298
+ return finish(exitCode, reason, result);
299
+ } finally {
300
+ process.off("SIGINT", onSigInt);
301
+ }
302
+ }
303
+
304
+ // src/commands/run.ts
305
+ var DRIVER_DISPATCH_SLASH = "run-plan-all";
306
+ function displayPath(target, home = homedir()) {
307
+ const resolvedHome = path2.resolve(home);
308
+ if (target === resolvedHome) return "~";
309
+ const prefix = resolvedHome.endsWith(path2.sep) ? resolvedHome : `${resolvedHome}${path2.sep}`;
310
+ return target.startsWith(prefix) ? `~${path2.sep}${target.slice(prefix.length)}` : target;
311
+ }
312
+ async function executeRun(input) {
313
+ const root = path2.resolve(input.cwd);
314
+ const slash = normalizeSlashName(input.slash);
315
+ if (!slash) {
316
+ return { exitCode: 1, error: "Provide a slash: agent-kit run <slash>" };
317
+ }
318
+ const kind = classifySlash(slash);
319
+ if (kind === "promote-blocked") {
320
+ return { exitCode: 1, error: promoteBlockedMessage(slash) };
321
+ }
322
+ if (kind === "unknown") {
323
+ return { exitCode: 1, error: unknownSlashMessage(slash) };
324
+ }
325
+ if (input.maxPackBytes?.trim() && slash !== REVIEW_PACK_SLASH) {
326
+ return { exitCode: 1, error: `--max-pack-bytes only applies to ${REVIEW_PACK_SLASH}` };
327
+ }
328
+ if (input.includeReviewed && slash !== REVIEW_PACK_SLASH) {
329
+ return { exitCode: 1, error: `--include-reviewed only applies to ${REVIEW_PACK_SLASH}` };
330
+ }
331
+ if (input.events) {
332
+ if (slash !== DRIVER_DISPATCH_SLASH) {
333
+ return {
334
+ exitCode: 1,
335
+ error: `--events only applies to ${DRIVER_DISPATCH_SLASH} (and agent-kit run-plan)`
336
+ };
337
+ }
338
+ const exitCode = await runDispatchDriver({
339
+ root,
340
+ slash: DRIVER_DISPATCH_SLASH,
341
+ backend: input.backend,
342
+ model: input.model,
343
+ dryRun: input.dryRun,
344
+ noHitl: input.noHitl === true,
345
+ landOnGate: input.landOnGate === true,
346
+ events: input.events,
347
+ whichFn: input.whichFn
348
+ });
349
+ return { exitCode };
350
+ }
351
+ const detected = await detectAgentBackend(input.backend, input.whichFn);
352
+ if (!detected.ok) {
353
+ return { exitCode: 1, error: detected.message };
354
+ }
355
+ if (kind === "run-plan") {
356
+ let backend;
357
+ try {
358
+ backend = getBackend(detected.id);
359
+ } catch (err) {
360
+ return { exitCode: 1, error: String(err) };
361
+ }
362
+ if (input.dryRun) {
363
+ const preview = [
364
+ `--dry-run: alias agent-kit run-plan (backend ${detected.id} at ${displayPath(detected.bin)})`,
365
+ "No agent will be started. Tick prompt is the existing run-plan loop prompt."
366
+ ].join("\n");
367
+ return { exitCode: 0, stdout: preview };
368
+ }
369
+ const code = await runPlanLoop({
370
+ root,
371
+ maxTicks: input.maxTicks,
372
+ sleepSeconds: input.sleepSeconds,
373
+ model: input.model,
374
+ dryRun: false,
375
+ backend,
376
+ noHitl: input.noHitl === true,
377
+ plain: input.plain === true,
378
+ landOnGate: input.landOnGate === true
379
+ });
380
+ return { exitCode: code };
381
+ }
382
+ if (slash === REVIEW_PACK_SLASH) {
383
+ try {
384
+ return await runReviewJob({
385
+ root,
386
+ backendId: detected.id,
387
+ bin: detected.bin,
388
+ model: input.model,
389
+ maxPackBytes: input.maxPackBytes,
390
+ includeReviewed: input.includeReviewed === true,
391
+ noHitl: input.noHitl === true,
392
+ dryRun: input.dryRun
393
+ });
394
+ } catch (err) {
395
+ return { exitCode: 1, error: String(err) };
396
+ }
397
+ }
398
+ const file = await readCommandFile(root, slash);
399
+ if (!file.ok) {
400
+ return { exitCode: 1, error: file.message };
401
+ }
402
+ const prompt = buildDispatchPrompt(file.body);
403
+ if (input.dryRun) {
404
+ const stdout = [
405
+ "--dry-run: no agent will be started.",
406
+ `Slash: ${slash}`,
407
+ `Command file: ${path2.relative(root, file.path)}`,
408
+ `Backend: ${detected.id} (${displayPath(detected.bin)})`,
409
+ "Prompt:",
410
+ prompt
411
+ ].join("\n");
412
+ return { exitCode: 0, stdout };
413
+ }
414
+ const logPath = await ensureDispatchLogPath(root);
415
+ console.log(`Dispatch: ${slash} via ${detected.id}`);
416
+ console.log(`Command file: ${path2.relative(root, file.path)}`);
417
+ console.log(`Log: ${path2.relative(root, logPath)}`);
418
+ try {
419
+ const dispatch = {
420
+ backendId: detected.id,
421
+ bin: detected.bin,
422
+ workspace: root,
423
+ prompt,
424
+ model: input.model,
425
+ logPath
426
+ };
427
+ const result = shouldUseLiveTui({ plain: input.plain }) ? await withLiveTui(
428
+ { root, backend: detected.id, logPath, noHitl: input.noHitl === true },
429
+ (seams) => runHeadlessDispatch({
430
+ ...dispatch,
431
+ hitl: seams.hitl,
432
+ render: seams.render,
433
+ onSpawn: seams.onSpawn,
434
+ log: seams.log
435
+ })
436
+ ) : await runHeadlessDispatch({
437
+ ...dispatch,
438
+ hitl: { policy: input.noHitl ? "off" : "prompt" }
439
+ });
440
+ for (const line of formatHitlSummary(result.hitl)) console.log(line);
441
+ const exitCode = hitlExitCode(result.exitCode, result.hitl);
442
+ if (input.landOnGate) {
443
+ await landDispatchOutcome({
444
+ root,
445
+ slash,
446
+ backendId: detected.id,
447
+ logPath,
448
+ exitCode,
449
+ result,
450
+ log: (line) => console.log(line)
451
+ });
452
+ }
453
+ return { exitCode };
454
+ } catch (err) {
455
+ return { exitCode: 1, error: String(err) };
456
+ }
457
+ }
458
+ var runDispatchArgs = {
459
+ cwd: {
460
+ type: "string",
461
+ description: "Project root (default: current directory)",
462
+ default: process.cwd()
463
+ },
464
+ backend: {
465
+ type: "string",
466
+ description: `Agent CLI (${listDetectBackendIds().join(" | ")}; default: auto)`,
467
+ default: "auto"
468
+ },
469
+ model: {
470
+ type: "string",
471
+ description: "Optional model id passed to the agent CLI",
472
+ default: ""
473
+ },
474
+ "dry-run": {
475
+ type: "boolean",
476
+ description: "Print the resolved backend and prompt, then exit without starting an agent",
477
+ default: false
478
+ },
479
+ "max-ticks": {
480
+ type: "string",
481
+ description: "For run-plan alias only: maximum ticks (default: 10)",
482
+ default: "10"
483
+ },
484
+ sleep: {
485
+ type: "string",
486
+ description: "For run-plan alias only: seconds between ticks (default: 5)",
487
+ default: "5"
488
+ },
489
+ "no-hitl": {
490
+ type: "boolean",
491
+ description: `CI: never prompt; a HITL gate stops the run with exit ${HITL_UNANSWERED_EXIT_CODE} (no default answer)`,
492
+ default: false
493
+ },
494
+ plain: {
495
+ type: "boolean",
496
+ description: "Status lines instead of the Mission Control live view (the default on a TTY; non-TTY, NO_COLOR and CI are always plain)",
497
+ default: false
498
+ },
499
+ "land-on-gate": {
500
+ type: "boolean",
501
+ description: LAND_ON_GATE_DESCRIPTION,
502
+ default: false
503
+ }
504
+ };
505
+ var maxPackBytesArg = {
506
+ type: "string",
507
+ description: "For review-pack only: diff pack ceiling in bytes (default: 98304; a branch whose section does not fit is listed as not reviewed, never cut)",
508
+ default: ""
509
+ };
510
+ var includeReviewedArg = {
511
+ type: "boolean",
512
+ description: "For review-pack only: also review branches whose tip is unchanged since the last completed review (.cursor/context/review-ledger.json)",
513
+ default: false
514
+ };
515
+ async function runSlashCli(slash, args) {
516
+ const maxTicks = Number.parseInt(String(args["max-ticks"]), 10);
517
+ const sleepSeconds = Number.parseFloat(String(args.sleep));
518
+ if (!Number.isFinite(maxTicks) || maxTicks < 1) {
519
+ logger.error("--max-ticks must be a positive integer");
520
+ process.exitCode = 1;
521
+ return;
522
+ }
523
+ if (!Number.isFinite(sleepSeconds) || sleepSeconds < 0) {
524
+ logger.error("--sleep must be a non-negative number");
525
+ process.exitCode = 1;
526
+ return;
527
+ }
528
+ const events = String(args.events ?? "");
529
+ if (events && !DRIVER_EVENTS_FORMATS.includes(events)) {
530
+ logger.error(`--events must be one of: ${DRIVER_EVENTS_FORMATS.join(", ")}`);
531
+ process.exitCode = 1;
532
+ return;
533
+ }
534
+ const result = await executeRun({
535
+ slash,
536
+ cwd: String(args.cwd),
537
+ backend: String(args.backend),
538
+ model: args.model ? String(args.model) : void 0,
539
+ dryRun: Boolean(args["dry-run"]),
540
+ maxTicks,
541
+ sleepSeconds,
542
+ noHitl: negatedFlag(args, "hitl"),
543
+ plain: Boolean(args.plain),
544
+ landOnGate: Boolean(args["land-on-gate"]),
545
+ ...args["max-pack-bytes"] ? { maxPackBytes: String(args["max-pack-bytes"]) } : {},
546
+ ...args["include-reviewed"] ? { includeReviewed: true } : {},
547
+ ...events ? { events: {} } : {}
548
+ });
549
+ if (result.stdout) {
550
+ console.log(result.stdout);
551
+ }
552
+ if (result.error) {
553
+ logger.error(result.error);
554
+ }
555
+ process.exitCode = result.exitCode;
556
+ }
557
+ var runCommand = defineCommand({
558
+ meta: {
559
+ name: "run",
560
+ description: "Start one headless session from an L0 slash file. Numbered-list HITL answered from the terminal (claude backend). Never git-prod."
561
+ },
562
+ args: {
563
+ slash: {
564
+ type: "positional",
565
+ description: "Slash name (e.g. run-plan-all, backlog-add, continue-plan)",
566
+ required: true
567
+ },
568
+ ...runDispatchArgs,
569
+ "max-pack-bytes": maxPackBytesArg,
570
+ "include-reviewed": includeReviewedArg
571
+ },
572
+ async run({ args }) {
573
+ await runSlashCli(String(args.slash ?? ""), args);
574
+ }
575
+ });
576
+ var runPlanAllCommand = defineCommand({
577
+ meta: {
578
+ name: "run-plan-all",
579
+ description: "Headless /run-plan-all queue from the L0 file. Numbered-list HITL answered from the terminal (claude backend). Never git-prod."
580
+ },
581
+ args: {
582
+ ...runDispatchArgs,
583
+ events: {
584
+ type: "string",
585
+ description: "Driver mode for apps: `ndjson` writes only NDJSON events to stdout and reads HITL answers as JSON lines on stdin (no TTY needed; driver protocol 1.2.0, see docs/driver-events-protocol.md)",
586
+ default: ""
587
+ }
588
+ },
589
+ async run({ args }) {
590
+ await runSlashCli("run-plan-all", args);
591
+ }
592
+ });
593
+ export {
594
+ DRIVER_DISPATCH_SLASH,
595
+ displayPath,
596
+ executeRun,
597
+ runCommand,
598
+ runPlanAllCommand,
599
+ runSlashCli
600
+ };
@@ -1,9 +1,9 @@
1
1
  import {
2
2
  runPlanLoop
3
- } from "./chunk-5WDFOFL4.js";
3
+ } from "./chunk-3Z4PGEEJ.js";
4
4
  import {
5
5
  DRIVER_EVENTS_FORMATS
6
- } from "./chunk-R6WH5P7R.js";
6
+ } from "./chunk-CXDAT76O.js";
7
7
  import {
8
8
  detectAgentBackend,
9
9
  listDetectBackendIds
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dadado/agent-kit-cli",
3
- "version": "6.7.2",
3
+ "version": "6.9.0",
4
4
  "description": "Agent Kit CLI: HITL framework install and tooling for AI-assisted IDEs (rules, skills, plan/handoff, context).",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",