@glrs-dev/cli 2.4.0 → 2.6.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.
Files changed (49) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/dist/{chunk-HQUCVJ4G.js → chunk-FBXSGZAA.js} +4 -0
  3. package/dist/chunk-J3FXSHMA.js +263 -0
  4. package/dist/{chunk-5ZVUFNCP.js → chunk-S6N5E2GG.js} +8 -1
  5. package/dist/{chunk-2VMFXAJH.js → chunk-UO7WHIKY.js} +18 -5
  6. package/dist/cli.js +10 -3
  7. package/dist/commands/autopilot-tui.d.ts +11 -1
  8. package/dist/commands/autopilot-tui.js +2 -1
  9. package/dist/commands/autopilot.d.ts +2 -0
  10. package/dist/commands/autopilot.js +62 -21
  11. package/dist/commands/debrief.d.ts +2 -0
  12. package/dist/commands/debrief.js +1 -1
  13. package/dist/commands/loop.d.ts +2 -0
  14. package/dist/commands/loop.js +33 -12
  15. package/dist/index.d.ts +1 -1
  16. package/dist/index.js +1 -1
  17. package/dist/node_modules/@glrs-dev/adapter-opencode/dist/index.d.ts +270 -0
  18. package/dist/node_modules/@glrs-dev/adapter-opencode/dist/index.js +506 -0
  19. package/dist/node_modules/@glrs-dev/adapter-opencode/package.json +8 -0
  20. package/dist/node_modules/@glrs-dev/autopilot/dist/auto-ship-EVLBKHUZ.js +7 -0
  21. package/dist/node_modules/@glrs-dev/autopilot/dist/changeset-generator-HAHYSSUR.js +15 -0
  22. package/dist/node_modules/@glrs-dev/autopilot/dist/chunk-2X3CWH47.js +3288 -0
  23. package/dist/node_modules/@glrs-dev/autopilot/dist/chunk-2ZQ6SBV3.js +70 -0
  24. package/dist/node_modules/@glrs-dev/autopilot/dist/chunk-6JZQLIRP.js +781 -0
  25. package/dist/node_modules/@glrs-dev/autopilot/dist/chunk-AWRK6S6G.js +91 -0
  26. package/dist/node_modules/@glrs-dev/autopilot/dist/chunk-BLEIZHET.js +101 -0
  27. package/dist/node_modules/@glrs-dev/autopilot/dist/chunk-GXXCEGDD.js +251 -0
  28. package/dist/node_modules/@glrs-dev/autopilot/dist/chunk-S34HOCZ4.js +44 -0
  29. package/dist/node_modules/@glrs-dev/autopilot/dist/index.d.ts +1915 -0
  30. package/dist/node_modules/@glrs-dev/autopilot/dist/index.js +768 -0
  31. package/dist/node_modules/@glrs-dev/autopilot/dist/logger-3XLFMXLN.js +8 -0
  32. package/dist/node_modules/@glrs-dev/autopilot/dist/loop-session-YLCVJGPV.js +9 -0
  33. package/dist/node_modules/@glrs-dev/autopilot/dist/plan-enrichment-4SQYV5FC.js +17 -0
  34. package/dist/node_modules/@glrs-dev/autopilot/package.json +8 -0
  35. package/dist/vendor/harness-opencode/dist/agents/prompts/agents-md-writer.md +1 -1
  36. package/dist/vendor/harness-opencode/dist/agents/prompts/architecture-advisor.md +1 -1
  37. package/dist/vendor/harness-opencode/dist/agents/prompts/code-searcher.md +1 -1
  38. package/dist/vendor/harness-opencode/dist/agents/prompts/docs-maintainer.md +0 -8
  39. package/dist/vendor/harness-opencode/dist/agents/prompts/gap-analyzer.md +1 -3
  40. package/dist/vendor/harness-opencode/dist/agents/prompts/lib-reader.md +1 -1
  41. package/dist/vendor/harness-opencode/dist/agents/prompts/plan-reviewer.md +0 -2
  42. package/dist/vendor/harness-opencode/dist/agents/prompts/plan.md +1 -1
  43. package/dist/vendor/harness-opencode/dist/agents/prompts/prime.md +78 -262
  44. package/dist/vendor/harness-opencode/dist/agents/prompts/research.md +5 -14
  45. package/dist/vendor/harness-opencode/dist/agents/prompts/scoper.md +7 -2
  46. package/dist/vendor/harness-opencode/dist/autopilot/strategies/default.md +29 -0
  47. package/dist/vendor/harness-opencode/dist/index.js +112 -82
  48. package/dist/vendor/harness-opencode/package.json +1 -1
  49. package/package.json +9 -7
@@ -0,0 +1,768 @@
1
+ import {
2
+ enrichPlanForFastModel,
3
+ isFreeformFile
4
+ } from "./chunk-6JZQLIRP.js";
5
+ import {
6
+ generateChangeset
7
+ } from "./chunk-AWRK6S6G.js";
8
+ import {
9
+ autoShip
10
+ } from "./chunk-BLEIZHET.js";
11
+ import {
12
+ MAX_ITERATIONS,
13
+ MAX_ITERATIONS_PER_PHASE_BY_TIER,
14
+ STALL_MS,
15
+ STALL_MS_BY_TIER,
16
+ STATUS_INTERVAL_MS,
17
+ STRUGGLE_THRESHOLD,
18
+ StruggleDetector,
19
+ TIMEOUT_MS,
20
+ buildConflictGraph,
21
+ checkKillSwitch,
22
+ createStatusHeartbeat,
23
+ createWorktree,
24
+ deleteCheckpoint,
25
+ detectSentinel,
26
+ formatCost,
27
+ formatElapsed,
28
+ getChangedFiles,
29
+ hasParallelism,
30
+ markPhaseCompleted,
31
+ mergeWorktree,
32
+ parseItems,
33
+ parsePlanState,
34
+ readCheckpoint,
35
+ recordHead,
36
+ resetSoft,
37
+ runLanes,
38
+ runLoopSession,
39
+ runRalphLoop,
40
+ runVerifyCommands,
41
+ validatePlan,
42
+ validateScope,
43
+ writeCheckpoint
44
+ } from "./chunk-2X3CWH47.js";
45
+ import {
46
+ resolveModel
47
+ } from "./chunk-S34HOCZ4.js";
48
+ import {
49
+ childLogger,
50
+ createAutopilotLogger
51
+ } from "./chunk-2ZQ6SBV3.js";
52
+ import {
53
+ detectSpecPhases,
54
+ filterUncheckedSpecPhases,
55
+ hasSpec,
56
+ parseSpecItems,
57
+ readSpecConstraints,
58
+ readSpecGoal,
59
+ validateMainSpec,
60
+ validatePhaseSpec
61
+ } from "./chunk-GXXCEGDD.js";
62
+
63
+ // src/event-stream.ts
64
+ import * as fs from "fs";
65
+ import * as path from "path";
66
+ var EventStreamWriter = class {
67
+ fd;
68
+ constructor(filePath) {
69
+ const dir = path.dirname(filePath);
70
+ fs.mkdirSync(dir, { recursive: true });
71
+ this.fd = fs.openSync(filePath, "a");
72
+ }
73
+ /**
74
+ * Serialize `event` as a JSON line and write it synchronously.
75
+ * Sync write ensures the line is on disk even if the process crashes
76
+ * immediately after.
77
+ */
78
+ emit(event) {
79
+ const line = JSON.stringify(event) + "\n";
80
+ const buf = Buffer.from(line, "utf8");
81
+ fs.writeSync(this.fd, buf);
82
+ }
83
+ /**
84
+ * Close the underlying file descriptor. Safe to call multiple times
85
+ * (subsequent calls are no-ops).
86
+ */
87
+ close() {
88
+ try {
89
+ fs.closeSync(this.fd);
90
+ } catch {
91
+ }
92
+ }
93
+ };
94
+ var EventStreamReader = class {
95
+ constructor(filePath) {
96
+ this.filePath = filePath;
97
+ }
98
+ filePath;
99
+ /**
100
+ * Read all events from the file. Returns an empty array if the file
101
+ * does not exist or is empty.
102
+ */
103
+ readAll() {
104
+ let raw;
105
+ try {
106
+ raw = fs.readFileSync(this.filePath, "utf8");
107
+ } catch {
108
+ return [];
109
+ }
110
+ return parseLines(raw);
111
+ }
112
+ /**
113
+ * Read events starting at `byteOffset`. Returns the parsed events and
114
+ * the new byte offset (= file size after reading). Useful for polling
115
+ * (tail mode): pass the returned `newOffset` on the next call to read
116
+ * only new events.
117
+ *
118
+ * Truncated or malformed last lines are skipped.
119
+ */
120
+ readFrom(byteOffset) {
121
+ let stat;
122
+ try {
123
+ stat = fs.statSync(this.filePath);
124
+ } catch {
125
+ return { events: [], newOffset: byteOffset };
126
+ }
127
+ const fileSize = stat.size;
128
+ if (fileSize <= byteOffset) {
129
+ return { events: [], newOffset: byteOffset };
130
+ }
131
+ const length = fileSize - byteOffset;
132
+ const buf = Buffer.alloc(length);
133
+ const fd = fs.openSync(this.filePath, "r");
134
+ try {
135
+ fs.readSync(fd, buf, 0, length, byteOffset);
136
+ } finally {
137
+ fs.closeSync(fd);
138
+ }
139
+ const raw = buf.toString("utf8");
140
+ const events = parseLines(raw);
141
+ return { events, newOffset: fileSize };
142
+ }
143
+ };
144
+ function parseLines(raw) {
145
+ const events = [];
146
+ const lines = raw.split("\n");
147
+ for (const line of lines) {
148
+ const trimmed = line.trim();
149
+ if (!trimmed) continue;
150
+ try {
151
+ const parsed = JSON.parse(trimmed);
152
+ events.push(parsed);
153
+ } catch {
154
+ }
155
+ }
156
+ return events;
157
+ }
158
+
159
+ // src/session-runner.ts
160
+ import { EventEmitter } from "events";
161
+ import * as fs2 from "fs";
162
+ import * as path2 from "path";
163
+ var SessionEventEmitter = class extends EventEmitter {
164
+ emitEvent(event) {
165
+ const eventName = event.type === "error" ? "session:error" : event.type;
166
+ this.emit(eventName, event);
167
+ this.emit("event", event);
168
+ }
169
+ };
170
+ var STATUS_WRITE_INTERVAL_MS = 5e3;
171
+ var LegacyStatusBridge = class {
172
+ statusFilePath;
173
+ lastWriteMs = 0;
174
+ startedAt = Date.now();
175
+ iterationsCompleted = 0;
176
+ cumulativeCostUsd = 0;
177
+ phasesCompleted = 0;
178
+ phaseCount = 0;
179
+ lastIterationProgress = false;
180
+ lastIterationErrored = false;
181
+ constructor(cwd) {
182
+ this.statusFilePath = path2.join(cwd, ".agent", "autopilot-status.json");
183
+ }
184
+ /** Update internal state from an event and conditionally write the file. */
185
+ onEvent(event) {
186
+ switch (event.type) {
187
+ case "session:start":
188
+ this.startedAt = Date.now();
189
+ this._writeNow();
190
+ return;
191
+ case "iteration:done":
192
+ this.iterationsCompleted = event.iteration;
193
+ this.lastIterationProgress = event.madeProgress ?? false;
194
+ this.lastIterationErrored = false;
195
+ break;
196
+ case "cost:update":
197
+ this.cumulativeCostUsd = event.cumulativeCostUsd;
198
+ break;
199
+ case "phase:start":
200
+ this.phaseCount = event.total;
201
+ break;
202
+ case "phase:done":
203
+ this.phasesCompleted += 1;
204
+ break;
205
+ case "error":
206
+ this.lastIterationErrored = true;
207
+ break;
208
+ case "session:done":
209
+ if (event.cumulativeCostUsd !== void 0) {
210
+ this.cumulativeCostUsd = event.cumulativeCostUsd;
211
+ }
212
+ this._writeNow();
213
+ return;
214
+ default:
215
+ break;
216
+ }
217
+ const now = Date.now();
218
+ if (now - this.lastWriteMs >= STATUS_WRITE_INTERVAL_MS) {
219
+ this._writeNow();
220
+ }
221
+ }
222
+ _writeNow() {
223
+ const now = Date.now();
224
+ this.lastWriteMs = now;
225
+ const state = {
226
+ startedAt: this.startedAt,
227
+ iterationsCompleted: this.iterationsCompleted,
228
+ cumulativeCostUsd: this.cumulativeCostUsd,
229
+ lastIterationProgress: this.lastIterationProgress,
230
+ lastIterationErrored: this.lastIterationErrored,
231
+ phaseCount: this.phaseCount > 0 ? this.phaseCount : void 0,
232
+ phasesCompleted: this.phasesCompleted > 0 ? this.phasesCompleted : void 0
233
+ };
234
+ const snapshot = {
235
+ ...state,
236
+ elapsedMs: now - this.startedAt,
237
+ writtenAt: new Date(now).toISOString()
238
+ };
239
+ try {
240
+ const dir = path2.dirname(this.statusFilePath);
241
+ if (!fs2.existsSync(dir)) {
242
+ fs2.mkdirSync(dir, { recursive: true });
243
+ }
244
+ const tmp = `${this.statusFilePath}.tmp.${process.pid}.${Math.random().toString(36).slice(2, 10)}`;
245
+ fs2.writeFileSync(tmp, JSON.stringify(snapshot, null, 2) + "\n", "utf8");
246
+ fs2.renameSync(tmp, this.statusFilePath);
247
+ } catch {
248
+ }
249
+ }
250
+ };
251
+ var SessionRunner = class {
252
+ /** Channel 1: in-process event emitter. Subscribe to event types or "event" for all. */
253
+ events;
254
+ opts;
255
+ _abortController = null;
256
+ _abortCount = 0;
257
+ constructor(opts) {
258
+ this.opts = opts;
259
+ this.events = new SessionEventEmitter();
260
+ }
261
+ /**
262
+ * Request graceful shutdown. First call signals the running loop session
263
+ * to stop at the next phase boundary (checkpoint is written). Second call
264
+ * force-exits via process.exit(1).
265
+ */
266
+ abort() {
267
+ this._abortCount++;
268
+ if (this._abortCount === 1) {
269
+ if (this._abortController) {
270
+ this._abortController.abort();
271
+ }
272
+ } else {
273
+ process.exit(1);
274
+ }
275
+ }
276
+ /**
277
+ * Run the autopilot session:
278
+ * 1. Emit session:start
279
+ * 2. If --fast, run enrichment (emitting enrich:* events)
280
+ * 3. Run the loop session (emitting phase:* events via loop-session.ts)
281
+ * 4. Emit session:done
282
+ *
283
+ * Returns a SessionResult with the final LoopResult.
284
+ */
285
+ async run() {
286
+ this._abortController = new AbortController();
287
+ this._abortCount = 0;
288
+ const { planPath, cwd, fast, resume, parallel, ship, maxIterationsPerPhase } = this.opts;
289
+ const eventStreamPath = this.opts.eventStreamPath ?? path2.join(cwd, ".agent", "autopilot-events.jsonl");
290
+ const _createWriter = this.opts._deps?.createWriter ?? ((fp) => new EventStreamWriter(fp));
291
+ const _createLogger = this.opts._deps?.createLogger;
292
+ const _enrichPlan = this.opts._deps?.enrichPlan;
293
+ const _runLoopSession = this.opts._deps?.runLoopSession;
294
+ const writer = _createWriter(eventStreamPath);
295
+ const statusBridge = new LegacyStatusBridge(cwd);
296
+ const emitEvent = (event) => {
297
+ this.events.emitEvent(event);
298
+ writer.emit(event);
299
+ statusBridge.onEvent(event);
300
+ };
301
+ let logger;
302
+ if (_createLogger) {
303
+ logger = _createLogger({ cwd });
304
+ } else {
305
+ const { createAutopilotLogger: createAutopilotLogger2 } = await import("./logger-3XLFMXLN.js");
306
+ const logLevel = this.opts.config?.log_level;
307
+ logger = createAutopilotLogger2({ cwd, level: logLevel });
308
+ }
309
+ const adapterName = this.opts.adapter?.name ?? "unknown";
310
+ let enrichModel = "unknown";
311
+ let executeModel = "unknown";
312
+ const cfgObj = this.opts.config;
313
+ const cfgModels = cfgObj?.models;
314
+ if (adapterName === "claude-code-cli") {
315
+ enrichModel = cfgModels?.enrichment ?? "claude-opus-4-7";
316
+ executeModel = cfgModels?.execution ?? "claude-haiku-4-5-20251001";
317
+ } else {
318
+ try {
319
+ const { join: join3 } = await import("path");
320
+ const { readFileSync: readFileSync3 } = await import("fs");
321
+ const configHome = process.env["XDG_CONFIG_HOME"] ?? join3(process.env["HOME"] ?? "", ".config");
322
+ const configPath = join3(configHome, "opencode", "opencode.json");
323
+ const raw = readFileSync3(configPath, "utf8");
324
+ const config = JSON.parse(raw);
325
+ const plugins = Array.isArray(config.plugin) ? config.plugin : [];
326
+ for (const entry of plugins) {
327
+ if (Array.isArray(entry) && entry.length >= 2) {
328
+ const opts2 = entry[1];
329
+ const models = opts2?.models;
330
+ if (models) {
331
+ const deepArr = models["deep"] ?? models["prime"];
332
+ if (Array.isArray(deepArr) && deepArr[0]) enrichModel = deepArr[0];
333
+ const execArr = models["autopilot-execute"] ?? models["mid-execute"] ?? models["mid"];
334
+ if (Array.isArray(execArr) && execArr[0]) executeModel = execArr[0];
335
+ }
336
+ }
337
+ }
338
+ if (typeof config.model === "string" && enrichModel === "unknown") {
339
+ enrichModel = config.model;
340
+ }
341
+ } catch {
342
+ }
343
+ }
344
+ let branch = "unknown";
345
+ try {
346
+ const { execFileSync } = await import("child_process");
347
+ branch = execFileSync("git", ["branch", "--show-current"], { cwd, encoding: "utf8" }).trim() || "detached";
348
+ } catch {
349
+ }
350
+ emitEvent({
351
+ type: "session:start",
352
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
353
+ planPath,
354
+ cwd,
355
+ fast: fast ?? false,
356
+ resume: resume ?? false,
357
+ enrichModel,
358
+ executeModel,
359
+ adapter: adapterName,
360
+ branch
361
+ });
362
+ let loopResult;
363
+ let effectivePlanPath = planPath;
364
+ try {
365
+ if (fast && planPath) {
366
+ emitEvent({
367
+ type: "enrich:start",
368
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
369
+ planPath,
370
+ fileCount: 0
371
+ // file count is determined inside enrichPlanForFastModel
372
+ });
373
+ try {
374
+ if (_enrichPlan) {
375
+ effectivePlanPath = await _enrichPlan(cwd, planPath, logger);
376
+ emitEvent({
377
+ type: "enrich:done",
378
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
379
+ filesProcessed: 0
380
+ });
381
+ } else {
382
+ const { enrichPlanForFastModel: enrichPlanForFastModel2 } = await import("./plan-enrichment-4SQYV5FC.js");
383
+ effectivePlanPath = await enrichPlanForFastModel2(cwd, planPath, logger, this.events, this.opts.adapter, this.opts.enrichmentConfig, this.opts.config);
384
+ }
385
+ } catch (err) {
386
+ const message = err instanceof Error ? err.message : String(err);
387
+ emitEvent({
388
+ type: "error",
389
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
390
+ message: `Enrichment failed: ${message}`
391
+ });
392
+ }
393
+ }
394
+ const loopOpts = {
395
+ planPath: effectivePlanPath,
396
+ cwd,
397
+ fast,
398
+ resume,
399
+ parallel,
400
+ ship,
401
+ maxIterationsPerPhase,
402
+ logger,
403
+ emitter: this.events,
404
+ adapter: this.opts.adapter,
405
+ config: this.opts.config,
406
+ signal: this._abortController?.signal
407
+ };
408
+ if (_runLoopSession) {
409
+ loopResult = await _runLoopSession(loopOpts);
410
+ } else {
411
+ const { runLoopSession: runLoopSession2 } = await import("./loop-session-YLCVJGPV.js");
412
+ loopResult = await runLoopSession2(loopOpts);
413
+ }
414
+ } catch (err) {
415
+ const message = err instanceof Error ? err.message : String(err);
416
+ emitEvent({
417
+ type: "error",
418
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
419
+ message
420
+ });
421
+ loopResult = {
422
+ exitReason: "error",
423
+ iterations: 0,
424
+ message
425
+ };
426
+ } finally {
427
+ if (logger) {
428
+ await logger.flush().catch(() => {
429
+ });
430
+ }
431
+ }
432
+ emitEvent({
433
+ type: "session:done",
434
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
435
+ exitReason: loopResult.exitReason,
436
+ iterations: loopResult.iterations,
437
+ cumulativeCostUsd: loopResult.cumulativeCostUsd,
438
+ message: loopResult.message
439
+ });
440
+ writer.close();
441
+ return { planPath, loopResult };
442
+ }
443
+ };
444
+
445
+ // src/config-reader.ts
446
+ function deepClone(obj) {
447
+ if (obj === null || typeof obj !== "object") {
448
+ return obj;
449
+ }
450
+ if (Array.isArray(obj)) {
451
+ return obj.map((item) => deepClone(item));
452
+ }
453
+ if (obj instanceof Date) {
454
+ return new Date(obj.getTime());
455
+ }
456
+ const cloned = {};
457
+ for (const key in obj) {
458
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
459
+ cloned[key] = deepClone(obj[key]);
460
+ }
461
+ }
462
+ return cloned;
463
+ }
464
+ function applyCLIOverrides(config, flags) {
465
+ const result = deepClone(config);
466
+ if (!result.models || typeof result.models !== "object") {
467
+ result.models = {};
468
+ }
469
+ const models = result.models;
470
+ if (flags.adapter !== void 0) {
471
+ result.adapter = flags.adapter;
472
+ }
473
+ if (flags.fast) {
474
+ const activeAdapter = flags.adapter ?? result.adapter;
475
+ models.execution = activeAdapter === "claude-code-cli" ? "claude-haiku-4-5-20251001" : "autopilot-execute";
476
+ }
477
+ if (flags.parallel !== void 0) {
478
+ result.execution_order = "parallel";
479
+ result.parallel_lanes = flags.parallel;
480
+ }
481
+ if (flags.ship) {
482
+ result.auto_ship = true;
483
+ }
484
+ if (flags.resume) {
485
+ result.checkpoint = true;
486
+ }
487
+ if (flags.maxIterationsPerPhase !== void 0) {
488
+ result.max_iterations_per_phase = flags.maxIterationsPerPhase;
489
+ }
490
+ if (flags.stallTimeout !== void 0) {
491
+ result.stall_timeout = flags.stallTimeout;
492
+ }
493
+ if (flags.notify !== void 0) {
494
+ result.notify_url = flags.notify;
495
+ }
496
+ return result;
497
+ }
498
+
499
+ // src/session-state.ts
500
+ function deriveId(planPath, startedAt) {
501
+ const raw = `${planPath}|${startedAt}`;
502
+ return Buffer.from(raw).toString("base64url").slice(0, 24);
503
+ }
504
+ function deriveState(events) {
505
+ const startEvent = events.find((e) => e.type === "session:start");
506
+ if (!startEvent || startEvent.type !== "session:start") {
507
+ return null;
508
+ }
509
+ const id = deriveId(startEvent.planPath, startEvent.timestamp);
510
+ let status = "running";
511
+ let currentPhase = void 0;
512
+ let currentIteration = void 0;
513
+ let totalIterations = 0;
514
+ let cost = 0;
515
+ let lastEventAt = startEvent.timestamp;
516
+ let error = void 0;
517
+ let exitReason = void 0;
518
+ let enrichProgress = void 0;
519
+ let verifyProgress = void 0;
520
+ for (const event of events) {
521
+ lastEventAt = event.timestamp;
522
+ switch (event.type) {
523
+ case "session:start":
524
+ status = "running";
525
+ break;
526
+ case "session:done":
527
+ status = "complete";
528
+ exitReason = event.exitReason;
529
+ totalIterations = event.iterations;
530
+ if (event.cumulativeCostUsd !== void 0) {
531
+ cost = event.cumulativeCostUsd;
532
+ }
533
+ break;
534
+ case "enrich:start":
535
+ status = "enriching";
536
+ enrichProgress = { done: 0, total: event.fileCount };
537
+ break;
538
+ case "enrich:file:done":
539
+ case "enrich:file:skip":
540
+ case "enrich:file:error":
541
+ if (enrichProgress) {
542
+ enrichProgress = { done: enrichProgress.done + 1, total: enrichProgress.total };
543
+ }
544
+ break;
545
+ case "enrich:file:start":
546
+ break;
547
+ case "enrich:done":
548
+ status = "running";
549
+ enrichProgress = enrichProgress ? { done: enrichProgress.total, total: enrichProgress.total } : void 0;
550
+ break;
551
+ case "phase:start":
552
+ status = "running";
553
+ currentPhase = {
554
+ phase: event.phase,
555
+ current: event.current,
556
+ total: event.total
557
+ };
558
+ break;
559
+ case "phase:done":
560
+ currentPhase = void 0;
561
+ currentIteration = void 0;
562
+ break;
563
+ case "iteration:start":
564
+ status = "running";
565
+ currentIteration = {
566
+ iteration: event.iteration,
567
+ max: event.maxIterations
568
+ };
569
+ break;
570
+ case "iteration:done":
571
+ totalIterations = event.iteration;
572
+ currentIteration = void 0;
573
+ if (event.costUsd !== void 0) {
574
+ cost = event.costUsd;
575
+ }
576
+ break;
577
+ case "cost:update":
578
+ cost = event.cumulativeCostUsd;
579
+ break;
580
+ case "error":
581
+ status = "error";
582
+ error = event.message;
583
+ break;
584
+ case "credential:expired":
585
+ status = "error";
586
+ error = `Credential expired: ${event.provider} \u2014 ${event.message}`;
587
+ break;
588
+ case "verify:start":
589
+ status = "verifying";
590
+ verifyProgress = { passed: 0, total: event.itemCount };
591
+ break;
592
+ case "verify:result":
593
+ if (verifyProgress) {
594
+ verifyProgress = {
595
+ passed: verifyProgress.passed + (event.passed ? 1 : 0),
596
+ total: verifyProgress.total
597
+ };
598
+ }
599
+ break;
600
+ case "verify:done":
601
+ status = "running";
602
+ verifyProgress = verifyProgress ? { passed: verifyProgress.passed, total: event.passed + event.failed } : void 0;
603
+ break;
604
+ case "tool:call":
605
+ case "thinking":
606
+ break;
607
+ }
608
+ }
609
+ return {
610
+ id,
611
+ planPath: startEvent.planPath,
612
+ cwd: startEvent.cwd,
613
+ fast: startEvent.fast,
614
+ resume: startEvent.resume,
615
+ status,
616
+ currentPhase,
617
+ currentIteration,
618
+ totalIterations,
619
+ cost,
620
+ startedAt: startEvent.timestamp,
621
+ lastEventAt,
622
+ error,
623
+ exitReason,
624
+ enrichProgress,
625
+ verifyProgress
626
+ };
627
+ }
628
+
629
+ // src/plan-session.ts
630
+ import * as fs3 from "fs";
631
+ import * as path3 from "path";
632
+ var DEFAULT_PLAN_TIMEOUT_MS = 10 * 60 * 1e3;
633
+ async function runPlanSession(opts) {
634
+ const timeoutMs = opts.timeoutMs ?? DEFAULT_PLAN_TIMEOUT_MS;
635
+ const adapter = opts.adapter;
636
+ const _existsSync = opts._deps?.existsSync ?? fs3.existsSync;
637
+ const handle = await adapter.start({ cwd: opts.planDir });
638
+ try {
639
+ const sessionId = await adapter.createSession(handle, {
640
+ agentName: "plan"
641
+ });
642
+ const multiFileDir = path3.join(opts.planDir, opts.slug);
643
+ const multiFileMain = path3.join(multiFileDir, "main.md");
644
+ const singleFilePlan = path3.join(opts.planDir, `${opts.slug}.md`);
645
+ const prompt = `Read the scope at ${opts.scopePath} and produce a plan. Use slug ${opts.slug} for the plan file(s). If the scope warrants multiple phases, produce a multi-file plan at ${multiFileDir}/main.md + phase_N.md files. Otherwise produce a single-file plan at ${singleFilePlan}.`;
646
+ const result = await adapter.sendAndWait(handle, {
647
+ sessionId,
648
+ message: prompt,
649
+ stallMs: timeoutMs
650
+ });
651
+ if (result.kind === "abort") {
652
+ throw new Error(
653
+ `Plan session aborted (timeout after ${timeoutMs}ms).`
654
+ );
655
+ }
656
+ if (result.kind === "stall") {
657
+ throw new Error(
658
+ `Plan session stalled for ${result.stallMs}ms with no idle signal.`
659
+ );
660
+ }
661
+ if (result.kind === "error") {
662
+ throw new Error(`Plan session error: ${result.message}`);
663
+ }
664
+ if (result.kind === "question_rejected") {
665
+ }
666
+ if (_existsSync(multiFileMain)) {
667
+ return { planPath: multiFileDir };
668
+ }
669
+ if (_existsSync(singleFilePlan)) {
670
+ return { planPath: singleFilePlan };
671
+ }
672
+ const retryPrompt = `You did not write a plan file. Write the plan NOW. Read the scope at ${opts.scopePath}. Write the plan to ${singleFilePlan} (single-file) or ${multiFileDir}/main.md (multi-file). Do NOT ask questions. Just write the plan.`;
673
+ const retryResult = await adapter.sendAndWait(handle, {
674
+ sessionId,
675
+ message: retryPrompt,
676
+ stallMs: timeoutMs
677
+ });
678
+ if (retryResult.kind !== "idle" && retryResult.kind !== "question_rejected") {
679
+ throw new Error(`@plan retry failed: ${retryResult.kind}`);
680
+ }
681
+ if (_existsSync(multiFileMain)) {
682
+ return { planPath: multiFileDir };
683
+ }
684
+ if (_existsSync(singleFilePlan)) {
685
+ return { planPath: singleFilePlan };
686
+ }
687
+ const scopeContent = fs3.existsSync(opts.scopePath) ? fs3.readFileSync(opts.scopePath, "utf-8") : `# Plan
688
+
689
+ Scope file not found at ${opts.scopePath}.`;
690
+ const minimalPlan = [
691
+ `# Plan (auto-generated from scope)`,
692
+ "",
693
+ "This plan was auto-generated because @plan did not produce a plan file.",
694
+ "Review and refine before executing.",
695
+ "",
696
+ scopeContent,
697
+ "",
698
+ "## Acceptance criteria",
699
+ "",
700
+ "- [ ] Review and refine this auto-generated plan",
701
+ "",
702
+ "## File-level changes",
703
+ "",
704
+ "- To be determined after plan review."
705
+ ].join("\n");
706
+ fs3.mkdirSync(path3.dirname(singleFilePlan), { recursive: true });
707
+ fs3.writeFileSync(singleFilePlan, minimalPlan);
708
+ return { planPath: singleFilePlan };
709
+ } finally {
710
+ await adapter.shutdown(handle);
711
+ }
712
+ }
713
+ export {
714
+ EventStreamReader,
715
+ EventStreamWriter,
716
+ MAX_ITERATIONS,
717
+ MAX_ITERATIONS_PER_PHASE_BY_TIER,
718
+ STALL_MS,
719
+ STALL_MS_BY_TIER,
720
+ STATUS_INTERVAL_MS,
721
+ STRUGGLE_THRESHOLD,
722
+ SessionEventEmitter,
723
+ SessionRunner,
724
+ StruggleDetector,
725
+ TIMEOUT_MS,
726
+ applyCLIOverrides,
727
+ autoShip,
728
+ buildConflictGraph,
729
+ checkKillSwitch,
730
+ childLogger,
731
+ createAutopilotLogger,
732
+ createStatusHeartbeat,
733
+ createWorktree,
734
+ deleteCheckpoint,
735
+ deriveState,
736
+ detectSentinel,
737
+ detectSpecPhases,
738
+ enrichPlanForFastModel,
739
+ filterUncheckedSpecPhases,
740
+ formatCost,
741
+ formatElapsed,
742
+ generateChangeset,
743
+ getChangedFiles,
744
+ hasParallelism,
745
+ hasSpec,
746
+ isFreeformFile,
747
+ markPhaseCompleted,
748
+ mergeWorktree,
749
+ parseItems,
750
+ parsePlanState,
751
+ parseSpecItems,
752
+ readCheckpoint,
753
+ readSpecConstraints,
754
+ readSpecGoal,
755
+ recordHead,
756
+ resetSoft,
757
+ resolveModel,
758
+ runLanes,
759
+ runLoopSession,
760
+ runPlanSession,
761
+ runRalphLoop,
762
+ runVerifyCommands,
763
+ validateMainSpec,
764
+ validatePhaseSpec,
765
+ validatePlan,
766
+ validateScope,
767
+ writeCheckpoint
768
+ };