@ordewell/core 0.5.5 → 0.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 (54) hide show
  1. package/dist/IFileSystem-CFYf4yR2.d.mts +76 -0
  2. package/dist/IFileSystem-D4dAl2r8.d.ts +76 -0
  3. package/dist/{ModeResolver-D-SUFRNF.d.mts → ModeResolver-DVYVRbJp.d.ts} +6 -2
  4. package/dist/{ModeResolver-D3XO0fT9.d.ts → ModeResolver-a4xJFlEp.d.mts} +6 -2
  5. package/dist/Task-CZJr6rmz.d.mts +2121 -0
  6. package/dist/Task-CZJr6rmz.d.ts +2121 -0
  7. package/dist/{chunk-KLN7ELXO.mjs → chunk-2SOVKO7P.mjs} +1561 -1269
  8. package/dist/chunk-2SOVKO7P.mjs.map +1 -0
  9. package/dist/{chunk-T2S5O36I.mjs → chunk-C44UWIAD.mjs} +6 -6
  10. package/dist/chunk-C44UWIAD.mjs.map +1 -0
  11. package/dist/{chunk-HD2FWPRV.mjs → chunk-EDGUFCIR.mjs} +6 -1
  12. package/dist/chunk-EDGUFCIR.mjs.map +1 -0
  13. package/dist/{chunk-UUBGVCGJ.mjs → chunk-OM4D274O.mjs} +20 -2
  14. package/dist/chunk-OM4D274O.mjs.map +1 -0
  15. package/dist/index.d.mts +1594 -803
  16. package/dist/index.d.ts +1594 -803
  17. package/dist/index.js +9540 -6040
  18. package/dist/index.js.map +1 -1
  19. package/dist/index.mjs +8167 -4996
  20. package/dist/index.mjs.map +1 -1
  21. package/dist/order-labels.d.mts +3 -1
  22. package/dist/order-labels.d.ts +3 -1
  23. package/dist/{parsing-BTP4bwkk.d.ts → parsing-Bd6-b644.d.ts} +2 -2
  24. package/dist/{parsing-CDtRSxBY.d.mts → parsing-DIaGZmiQ.d.mts} +2 -2
  25. package/dist/parsing.d.mts +5 -3
  26. package/dist/parsing.d.ts +5 -3
  27. package/dist/parsing.js.map +1 -1
  28. package/dist/parsing.mjs +2 -2
  29. package/dist/{plan-utils-pE4TBwxl.d.mts → plan-utils-Ba-l8EZS.d.mts} +212 -43
  30. package/dist/{plan-utils-BFaPo-IT.d.ts → plan-utils-_T5S7Mnk.d.ts} +212 -43
  31. package/dist/plan-utils.d.mts +5 -4
  32. package/dist/plan-utils.d.ts +5 -4
  33. package/dist/plan-utils.js +352 -64
  34. package/dist/plan-utils.js.map +1 -1
  35. package/dist/plan-utils.mjs +11 -5
  36. package/dist/testing.d.mts +54 -4
  37. package/dist/testing.d.ts +54 -4
  38. package/dist/testing.js +93 -2
  39. package/dist/testing.js.map +1 -1
  40. package/dist/testing.mjs +91 -2
  41. package/dist/testing.mjs.map +1 -1
  42. package/package.json +2 -1
  43. package/skills/grilling/SKILL.md +6 -16
  44. package/skills/improve-codebase-architecture/SKILL.md +1 -1
  45. package/dist/ApprovalPolicy-BVhGdECT.d.mts +0 -79
  46. package/dist/ApprovalPolicy-BVhGdECT.d.ts +0 -79
  47. package/dist/ITerminalRunner-BV9Rd2o9.d.ts +0 -563
  48. package/dist/ITerminalRunner-C77ZNZS9.d.mts +0 -563
  49. package/dist/Task-Vl5Zq_D-.d.mts +0 -825
  50. package/dist/Task-Vl5Zq_D-.d.ts +0 -825
  51. package/dist/chunk-HD2FWPRV.mjs.map +0 -1
  52. package/dist/chunk-KLN7ELXO.mjs.map +0 -1
  53. package/dist/chunk-T2S5O36I.mjs.map +0 -1
  54. package/dist/chunk-UUBGVCGJ.mjs.map +0 -1
@@ -0,0 +1,2121 @@
1
+ import { ChildProcess } from 'child_process';
2
+ import { EventEmitter } from 'events';
3
+
4
+ /**
5
+ * Why isolated execution is unavailable for a workspace. The orchestrator needs
6
+ * the reason, not just a boolean: `dirty` is offered a stash or an explicit
7
+ * "run without isolation", while the others fall back to the shared
8
+ * workspace root with a one-line notice.
9
+ */
10
+ type IsolationInactiveReason = 'disabled' | 'git-missing' | 'not-git' | 'no-commits' | 'dirty';
11
+ /**
12
+ * `repos` names, relative to the workspace, the repositories behind the answer:
13
+ * when active, the ones that will isolate, with `shared` the paths every task
14
+ * will share live — loose entries of the workspace root, or, for a lone
15
+ * repository, the repositories nested inside it; otherwise the dirty ones of a
16
+ * `dirty` group, or the commitless ones of a `no-commits` group. A group of one
17
+ * names none.
18
+ */
19
+ type IsolationAvailability = {
20
+ active: true;
21
+ repos?: string[];
22
+ shared?: string[];
23
+ } | {
24
+ active: false;
25
+ reason: IsolationInactiveReason;
26
+ repos?: string[];
27
+ };
28
+ /**
29
+ * Where a run's tasks work, as the planner is told it: the repos of the group
30
+ * and the paths shared live between tasks. A lone repository is `['.']` with
31
+ * nothing shared, unless it holds nested repositories, which are shared live
32
+ * and named in `shared`.
33
+ */
34
+ interface RepoGroupLayout {
35
+ repos: string[];
36
+ shared: string[];
37
+ }
38
+ type IsolationOutcome = 'merged' | 'conflict' | 'failed';
39
+ /**
40
+ * `active` — worktree exists, a runner may be writing to it.
41
+ * `kept` — released with its worktree and branch preserved for inspection.
42
+ * `conflict` — integration stopped on a merge conflict; worktree and refs kept.
43
+ * `repairing` — a conflict repair (ADR-0015) is working in the kept worktree;
44
+ * one that ends without landing leaves the task `conflict` again.
45
+ * `failed` — integration hit a git error other than a conflict; refs kept.
46
+ * `merged` — landed on the integration branch; worktree and task branch removed.
47
+ */
48
+ type IsolationTaskStatus = 'active' | 'kept' | 'conflict' | 'repairing' | 'failed' | 'merged';
49
+ /** One repo's share of a task: its worktree inside the task workspace. */
50
+ interface IsolationTaskRepo {
51
+ /** Absolute path of this repo's worktree: the task workspace joined with the repo's path. */
52
+ worktree: string;
53
+ /**
54
+ * Paths linked from the real workspace and kept out of the task's commit:
55
+ * the artifacts bootstrapped from the real repo, and a lone repository's
56
+ * nested repositories (`run.shared`). Recorded because a symlink is not
57
+ * matched by an ignore rule such as `node_modules/` and would otherwise be
58
+ * committed.
59
+ */
60
+ linked: string[];
61
+ /** Whether the task brought commits to this repo; unknown until it first integrates. */
62
+ changed?: boolean;
63
+ }
64
+ interface IsolationTaskRecord {
65
+ taskId: string;
66
+ order: number;
67
+ title: string;
68
+ /** One branch name, the same in every repo, so a task is one name to look up across the group. */
69
+ branch: string;
70
+ /**
71
+ * Absolute path of the task workspace, holding one worktree per repo at the
72
+ * repo's path. The Runner's cwd is inside it when the workspace is a repo
73
+ * subdirectory; for a group of one it is the worktree.
74
+ */
75
+ workspace: string;
76
+ /** For the task as a whole: landing is atomic across the repos it changed. */
77
+ status: IsolationTaskStatus;
78
+ /** Keyed by repo path. */
79
+ repos: Record<string, IsolationTaskRepo>;
80
+ /** The repo whose merge stopped the task from landing, while `status` is `conflict` or `failed`. */
81
+ conflictRepo?: string;
82
+ /**
83
+ * What a `failed` landing stopped on, in words a surface can repeat — a
84
+ * missing worktree is the common one. Cleared by the next landing attempt,
85
+ * so a stale reason cannot outlive the failure it explains.
86
+ */
87
+ landingError?: string;
88
+ /** Repo-relative paths, in `conflictRepo`, that conflicted; set only while `status` is `conflict` or `repairing`. */
89
+ conflictFiles?: string[];
90
+ /**
91
+ * Conflict repairs started for this task (ADR-0015). Counted when one starts,
92
+ * so a crash cannot hand the spent attempt back; absent reads as none.
93
+ */
94
+ repairs?: number;
95
+ /**
96
+ * Keyed by repo path: each changed repo's integration tip when the repair in
97
+ * flight started — what the task branch must contain before it may land.
98
+ * Set only while `status` is `repairing`.
99
+ */
100
+ repairBase?: Record<string, string>;
101
+ /**
102
+ * Every file a repair was started for, across all of them: as `conflictFiles`
103
+ * names it in a group of one, prefixed with its repo's path in a group.
104
+ */
105
+ repairedFiles?: string[];
106
+ }
107
+ /**
108
+ * A task's landing in flight: each changed repo's integration tip from before
109
+ * the task's merge. On the run rather than the task record because it must
110
+ * outlive that record — a retry drops and recreates it — until every repo is
111
+ * back at its tip or the task has landed.
112
+ */
113
+ interface IsolationLanding {
114
+ taskId: string;
115
+ /** Keyed by repo path. */
116
+ tips: Record<string, string>;
117
+ }
118
+ /**
119
+ * One repository of the group (ADR-0014). Every git operation on it runs in
120
+ * `root`, never in the workspace root.
121
+ */
122
+ interface IsolationRepo {
123
+ /** Relative to the workspace root; `.` when the workspace is itself the repository. */
124
+ path: string;
125
+ /**
126
+ * Absolute: the workspace root joined with `path`. For a group of one that is
127
+ * the workspace root, which may be a subdirectory of the repository.
128
+ */
129
+ root: string;
130
+ /** The commit checked out at run start. Switching branches mid-run does not retarget it. */
131
+ baseRef: string;
132
+ /** Branch name checked out at run start; absent on a detached HEAD. */
133
+ baseBranch?: string;
134
+ integrationBranch: string;
135
+ }
136
+ /**
137
+ * One Execute-Plan click or one manual task run over the workspace's repo
138
+ * group. Plain JSON on purpose: the orchestrator persists it with the plan
139
+ * state so a resumed session can find its integration branches again. The
140
+ * module mutates `tasks` in place.
141
+ */
142
+ interface IsolationRun {
143
+ id: string;
144
+ workspaceRoot: string;
145
+ repos: IsolationRepo[];
146
+ /**
147
+ * Workspace paths outside every isolated repo, linked live into each task
148
+ * workspace: loose entries of the workspace root, the entries beside a deeper
149
+ * repo, and `sharedRepos`. For a lone repository, the repositories nested
150
+ * inside it, which cannot be isolated with it and so are linked live instead.
151
+ * Empty when a group of one holds no nested repositories.
152
+ */
153
+ shared: string[];
154
+ /** Repos of the group that could not be isolated — no commits, or git refused a worktree — and are among `shared`. */
155
+ sharedRepos: string[];
156
+ /** Keyed by task id — ids are unique within one plan and a run belongs to one plan. */
157
+ tasks: Record<string, IsolationTaskRecord>;
158
+ /**
159
+ * Set before a task's first merge and cleared once it has landed or been
160
+ * rolled back. One found set — after a crash, or a rollback git refused —
161
+ * names exactly what to return each repo's integration branch to.
162
+ */
163
+ landing?: IsolationLanding;
164
+ }
165
+ /**
166
+ * What a plan persists of isolated execution (`LegacyPlanState.isolation`): its
167
+ * run, and which added tasks resolve which conflicts. Belongs to that plan and
168
+ * its branches alone, so a copy of the plan (a fork) must not carry it.
169
+ */
170
+ interface PlanIsolation {
171
+ run: IsolationRun;
172
+ /** Resolver task id → the conflicted task whose branch it merges. */
173
+ resolvers: Record<string, string>;
174
+ }
175
+ /**
176
+ * A task's isolation as a surface shows it. `kept` covers every record whose
177
+ * worktree stays for inspection — a failed verdict, an interrupted attempt, an
178
+ * integration git refused — because to the user they are one thing: work that
179
+ * did not land and can be looked at. `none` is a task with no worktree in a plan
180
+ * that has an isolation run.
181
+ */
182
+ type TaskIsolationState = 'none' | 'active' | 'integrated' | 'conflict' | 'repairing' | 'kept';
183
+ type TaskIsolation = {
184
+ state: 'none';
185
+ } | {
186
+ state: Exclude<TaskIsolationState, 'none'>;
187
+ branch: string;
188
+ /** The task workspace; for a group of one, the task's worktree. */
189
+ worktree: string;
190
+ /** Paths of the repos the task changed. */
191
+ repos: string[];
192
+ conflictRepo?: string;
193
+ /** Repo-relative paths, in `conflictRepo`, that conflicted. */
194
+ conflictFiles?: string[];
195
+ /** The conflict repair running or last run, of the most a task may have; absent before its first. */
196
+ repair?: {
197
+ attempt: number;
198
+ limit: number;
199
+ };
200
+ /** What {@link IsolationTaskRecord.repairedFiles} says. */
201
+ repairedFiles?: string[];
202
+ };
203
+ interface IsolationLandedTask {
204
+ taskId: string;
205
+ order: number;
206
+ title: string;
207
+ /** Set when the task landed only after a conflict repair (ADR-0015): the files it was started for. */
208
+ repairedFiles?: string[];
209
+ }
210
+ interface IsolationHandoffRepo {
211
+ path: string;
212
+ integrationBranch: string;
213
+ baseRef: string;
214
+ /** Tasks whose work landed in this repo, in plan order. */
215
+ landed: IsolationLandedTask[];
216
+ }
217
+ interface IsolationHandoff {
218
+ repos: IsolationHandoffRepo[];
219
+ /** Tasks that landed on the integration branches, in plan order. */
220
+ landed: IsolationLandedTask[];
221
+ }
222
+ /** A plan's isolation as a surface shows it: a mark for each task the run touched, and its handoff. */
223
+ interface IsolationView {
224
+ tasks: Record<string, TaskIsolation>;
225
+ handoff: IsolationHandoff;
226
+ }
227
+ /**
228
+ * Why "Merge all" would not touch a repo. `partial-landing`: a task's landing
229
+ * was interrupted and could not be rolled back there, so its integration
230
+ * branch holds part of a task.
231
+ */
232
+ type IsolationMergeBlockReason = 'merge-in-progress' | 'conflict' | 'uncommitted-changes' | 'partial-landing' | 'git-error';
233
+ interface IsolationMergeBlock {
234
+ repo: string;
235
+ reason: IsolationMergeBlockReason;
236
+ /** The files that would conflict, or the user's uncommitted ones the merge also changes; empty for the other reasons. */
237
+ files: string[];
238
+ }
239
+ /**
240
+ * How "Merge all" went.
241
+ * - `merged`: every repo with work on its integration branch took it.
242
+ * - `blocked`: the preflight found repos that could not, so nothing was
243
+ * touched anywhere; `blocked` says which and why.
244
+ * - `conflict` / `failed`: a merge stopped in `repo` — on git older than 2.38,
245
+ * which cannot preflight, or for a reason no preflight could foresee. That
246
+ * merge was aborted, leaving `repo` as it was; `landed` names the repos
247
+ * merged before it, which stay merged, and is absent when there are none.
248
+ *
249
+ * A group of one is blocked only by a partial landing; otherwise its one merge
250
+ * lands or is aborted whole, so it reports as it always has.
251
+ */
252
+ type IsolationMergeResult = {
253
+ outcome: 'merged';
254
+ } | {
255
+ outcome: 'blocked';
256
+ blocked: IsolationMergeBlock[];
257
+ } | {
258
+ outcome: 'conflict' | 'failed';
259
+ repo: string;
260
+ files?: string[];
261
+ landed?: string[];
262
+ };
263
+ /**
264
+ * What `discard` does with each repo's integration branch: `keep` it for review
265
+ * or merge, `delete` it, or delete it only in the repos whose checked-out HEAD
266
+ * already contains it (`delete-merged`) — the one way that can never give up
267
+ * landed work the user has not merged.
268
+ */
269
+ type IntegrationDisposal = 'keep' | 'delete' | 'delete-merged';
270
+ /**
271
+ * Whether a conflict repair's work may land. `not-merged`: the task branch in
272
+ * `repo` does not contain the tip the repair started from. `conflict-markers`:
273
+ * it adds leftover conflict markers to `files`. `failed`: git could not tell.
274
+ */
275
+ type RepairEvidence = {
276
+ ok: true;
277
+ } | {
278
+ ok: false;
279
+ reason: 'not-merged' | 'conflict-markers' | 'failed';
280
+ repo: string;
281
+ files?: string[];
282
+ };
283
+ interface PreparedTask {
284
+ cwd: string;
285
+ branch: string;
286
+ /**
287
+ * Paths, relative to the task workspace, that are copies rather than links
288
+ * because a hard link was impossible (Windows, another volume). Edits to them
289
+ * stay in the task, so the user is told.
290
+ */
291
+ copied: string[];
292
+ }
293
+ /**
294
+ * What a crash-recovery prune found and left alone: task records that were
295
+ * `active` yet still held unlanded work, so the prune kept them as `kept`
296
+ * rather than deleting work no one else has.
297
+ */
298
+ interface IsolationPruneResult {
299
+ kept: Array<{
300
+ taskId: string;
301
+ order: number;
302
+ title: string;
303
+ }>;
304
+ }
305
+ interface IWorktreeIsolation {
306
+ /**
307
+ * A repo group with at least one repo to isolate, a clean tracked tree in
308
+ * each, and the config enabled; otherwise the reason it is not.
309
+ */
310
+ isActive(workspaceRoot: string): Promise<IsolationAvailability>;
311
+ /**
312
+ * Put the tracked changes of every dirty repo of the group on its git stash,
313
+ * the user's way out of a `dirty` refusal. Untracked files stay: they never
314
+ * block isolation.
315
+ */
316
+ stash(workspaceRoot: string): Promise<void>;
317
+ /**
318
+ * Mint a run: resolve each repo's base ref to a commit now, and share the
319
+ * repos that cannot be isolated. Only meaningful after `isActive` said yes;
320
+ * throws when no repo of the group can be isolated after all.
321
+ */
322
+ startRun(workspaceRoot: string): Promise<IsolationRun>;
323
+ /**
324
+ * Create the task workspace — one worktree per isolated repo from its
325
+ * integration tip, the shared paths linked in — and return the cwd to spawn
326
+ * the Runner into. A second `prepare` for the same task is a retry: the old
327
+ * attempt is discarded and the workspace recreated from the tips, so the
328
+ * task sees everything its predecessors have integrated.
329
+ */
330
+ prepare(task: Task, run: IsolationRun): Promise<PreparedTask>;
331
+ /**
332
+ * Hand a conflicted task's kept workspace to a conflict repair (ADR-0015)
333
+ * as it is — nothing is re-cut — and return the same cwd. Records each
334
+ * changed repo's integration tip as `repairBase`, counts the repair, and
335
+ * moves the task to `repairing`. Throws for a task that is not `conflict`.
336
+ */
337
+ reopen(task: Task, run: IsolationRun): Promise<PreparedTask>;
338
+ /**
339
+ * The evidence a repair must show before it lands: its work committed, and
340
+ * in each repo of `repairBase` the task branch containing that tip
341
+ * (`git merge-base --is-ancestor`) and adding no leftover conflict markers
342
+ * (`git diff --check`; whitespace warnings do not count). Changes nothing
343
+ * else: a task that fails stays `repairing` until released.
344
+ */
345
+ verifyRepair(task: Task, run: IsolationRun): Promise<RepairEvidence>;
346
+ /**
347
+ * Land the task atomically across the repos it changed: commit each
348
+ * worktree, then `git merge --no-ff` the task branch into each changed
349
+ * repo's integration branch. If any merge conflicts or fails, it is aborted
350
+ * and the merges already made for the task are reset away, so `merged`
351
+ * always means the whole task landed. Serialized inside the module; among
352
+ * tasks waiting at once the lowest plan order goes first. On anything but
353
+ * `merged` the worktrees and refs stay, and nothing is resolved here: a
354
+ * conflict is repaired, if at all, by a new attempt of the task in its own
355
+ * worktree (ADR-0015), never inside this queue.
356
+ *
357
+ * `persist` is called once `run.landing` is set and before the first
358
+ * merge; the caller saves the run there, synchronously, which is what
359
+ * lets `pruneOrphans` finish a landing a crash interrupted.
360
+ */
361
+ integrate(task: Task, run: IsolationRun, persist?: () => void): Promise<IsolationOutcome>;
362
+ /**
363
+ * `keep: false` removes the task's worktree, branch and record (retry, task
364
+ * removal). `keep: true` leaves the worktree and branch exactly as they are
365
+ * for inspection — a failed verdict, a stop, a cancel — and only moves the task off `active`,
366
+ * so a crash-recovery prune does not sweep it away; a repair it ends leaves
367
+ * the task `conflict`, as it was before the repair. Takes the run rather than
368
+ * a bare task id: ids are only unique within one plan, and one daemon serves
369
+ * many (ADR-0007).
370
+ */
371
+ release(run: IsolationRun, taskId: string, opts: {
372
+ keep: boolean;
373
+ }): Promise<void>;
374
+ /** End of run: park the integration branch for review and report what landed. */
375
+ handoff(run: IsolationRun): Promise<IsolationHandoff>;
376
+ /**
377
+ * Drop what a crash left behind: a landing it interrupted is rolled back in
378
+ * every repo, a repair it interrupted leaves its task `conflict`, then stale
379
+ * active worktrees and directories no record owns go. An `active` record
380
+ * that still holds unlanded work — commits its branch alone carries, or
381
+ * edits in its worktree — is not a crash orphan: it may belong to a runner
382
+ * another host is still driving, so it is kept as `kept` and named in the
383
+ * result.
384
+ */
385
+ pruneOrphans(run: IsolationRun): Promise<IsolationPruneResult>;
386
+ /** Unified diff of each repo's integration branch against its base ref. */
387
+ reviewDiff(run: IsolationRun): Promise<string>;
388
+ /**
389
+ * "Merge all": merge each repo's integration branch into whatever the user
390
+ * has checked out there. The one irreversible step, so it only ever happens
391
+ * when a caller asks for it. Every repo with work is preflighted first — no
392
+ * merge of the user's in progress, no conflict against their HEAD, no
393
+ * uncommitted edit to a file the merge changes — and unless all pass,
394
+ * nothing is merged anywhere. Only a merge Ordewell itself just started is
395
+ * ever aborted; nothing of the user's is reset.
396
+ */
397
+ mergeIntoCheckedOut(run: IsolationRun): Promise<IsolationMergeResult>;
398
+ /**
399
+ * Remove every worktree and task branch of the run, and settle each repo's
400
+ * integration branch as `integration` says. Anything but `keep` also clears
401
+ * the run's task records.
402
+ */
403
+ discard(run: IsolationRun, opts: {
404
+ integration: IntegrationDisposal;
405
+ }): Promise<void>;
406
+ /**
407
+ * Clear what other runs left in each repo of `run`'s group: every
408
+ * `ordewell/<run-id>/…` branch the repo's checked-out HEAD already contains.
409
+ * Never a branch of `run` itself, one a worktree has checked out, or any
410
+ * branch of a run that still has a worktree — that run may be live in
411
+ * another plan. Tries every repo, then throws naming those where git failed.
412
+ */
413
+ sweep(run: IsolationRun): Promise<void>;
414
+ }
415
+
416
+ /** One source for the spawn options, so a runner built on this base cannot drift from the interface. */
417
+ type RunnerSpawnOptions = Parameters<ITerminalRunner['spawn']>[0];
418
+ declare abstract class AbstractTerminalSession implements ITerminalSession {
419
+ id: string;
420
+ taskId: string;
421
+ protected exited: boolean;
422
+ protected outputEmitter: EventEmitter<any>;
423
+ protected exitEmitter: EventEmitter<any>;
424
+ constructor(id: string, taskId: string);
425
+ protected baseHandleExit(code: number): void;
426
+ onOutput(callback: (text: string) => void): void;
427
+ onExit(callback: (code: number) => void): void;
428
+ abstract kill(): void;
429
+ abstract getOutput(): string;
430
+ abstract write(text: string): void;
431
+ }
432
+ declare abstract class AbstractRunner<S extends ITerminalSession> implements ITerminalRunner {
433
+ protected sessions: Map<string, S>;
434
+ get activeCount(): number;
435
+ stop(sessionId: string): void;
436
+ stopAll(): void;
437
+ protected registerSession(id: string, session: S): void;
438
+ abstract spawn(opts: RunnerSpawnOptions): Promise<ITerminalSession>;
439
+ }
440
+
441
+ declare function stripAnsi(text: string): string;
442
+ declare function posixShellQuote(s: string): string;
443
+ /**
444
+ * Wrap a command for execution inside a POSIX login shell, which is what
445
+ * resolves runner binaries managed by nvm/volta/asdf.
446
+ *
447
+ * Deliberately POSIX-only. This used to take a `platform` and emit
448
+ * `powershell.exe -Command "'claude' '-p' '…'"` for Windows, which PowerShell
449
+ * cannot run at all: a quoted string in leading position is parsed in
450
+ * expression mode, so the invocation died with a parse error before the runner
451
+ * started — a task that failed instantly, every time, on that platform. Windows
452
+ * has no login-shell equivalent to emulate (its PATH comes from the registry
453
+ * and is already inherited), so {@link planShellLaunch} starts the runner
454
+ * directly there instead of routing it through a shell. Platform choice belongs
455
+ * to that function; this one only knows how to phrase the POSIX half.
456
+ */
457
+ declare function buildShellInvocation(command: string, args: string[]): {
458
+ shellPath: string;
459
+ shellArgs: string[];
460
+ };
461
+ /** A terminal size in cells. */
462
+ interface PtySize {
463
+ cols: number;
464
+ rows: number;
465
+ }
466
+ /**
467
+ * Options for {@link wrapWithPty}. `size` sets the PTY's window size before the
468
+ * wrapped command starts. `controlChannel` makes the wrapper listen on its fd 3
469
+ * for `"<cols> <rows>"` lines and resize the PTY live — the caller spawns the
470
+ * child with an extra pipe there and writes resize requests into it.
471
+ */
472
+ interface PtyWrapOptions {
473
+ size?: PtySize;
474
+ controlChannel?: boolean;
475
+ }
476
+ /**
477
+ * Wrap a command in `script` to allocate the PTY some runners require when
478
+ * headless; `-e` propagates the child's exit code so verification still works.
479
+ *
480
+ * POSIX-only by nature — there is no `script` on Windows, which
481
+ * `HeadlessRunner`'s `hasScriptCmd` probe already discovers, so this is never
482
+ * reached there.
483
+ *
484
+ * `script` sizes its PTY off the terminal it is attached to; spawned off a pipe
485
+ * (every transport here) it allocates 0x0, which a runner TUI renders as
486
+ * garbage. `stty` fixes the size on the PTY slave before the command starts, so
487
+ * the TUI reads its true dimensions via ioctl.
488
+ *
489
+ * The control channel can only live on a *separate* fd from the agent's stdin,
490
+ * so the wrapper saves the PTY on fd 4 first: POSIX sends an asynchronous
491
+ * command's stdin to `/dev/null`, so the watcher's own stdin cannot be the PTY.
492
+ * A background job also inherits an fd 0 that is not the terminal; `stty` names
493
+ * fd 4 explicitly for that reason.
494
+ */
495
+ declare function wrapWithPty(command: string, args: string[], opts?: PtyWrapOptions): {
496
+ command: string;
497
+ args: string[];
498
+ };
499
+
500
+ /**
501
+ * cmd.exe's command-line buffer. A longer line is truncated rather than
502
+ * rejected, which would corrupt a planner's system prompt or a task's prompt
503
+ * mid-sentence and produce a confident answer to half a question — so the
504
+ * batch route refuses instead. See {@link CommandLineTooLongError}.
505
+ */
506
+ declare const CMD_EXE_MAX_COMMAND_LINE = 8191;
507
+ /**
508
+ * CreateProcess's own ceiling, which the native and PowerShell routes are
509
+ * bounded by instead. Windows truncates here too, so the same refusal applies —
510
+ * it is simply four times further away.
511
+ */
512
+ declare const WINDOWS_MAX_COMMAND_LINE = 32767;
513
+ interface LaunchPlan {
514
+ /** The executable handed to `spawn()` or `vscode.window.createTerminal`. */
515
+ file: string;
516
+ /** Arguments for `file`. Pass verbatim when {@link verbatim} is set. */
517
+ args: string[];
518
+ /**
519
+ * Windows batch route only: `args` is already a quoted command line and must
520
+ * not be re-quoted. Maps to `windowsVerbatimArguments` for `spawn`, and to
521
+ * the string form of `shellArgs` for a VS Code terminal.
522
+ */
523
+ verbatim?: boolean;
524
+ }
525
+ /** Test seam: every OS touchpoint is injectable, and production uses the defaults. */
526
+ interface LaunchDeps {
527
+ platform?: NodeJS.Platform;
528
+ /** The PATH executables are looked up on. Defaults to the augmented PATH. */
529
+ resolvePath?: () => Promise<string>;
530
+ /** True when `candidate` names an existing file. */
531
+ exists?: (candidate: string) => boolean;
532
+ /** Absolute path to the Windows command interpreter. */
533
+ comSpec?: () => string;
534
+ /** Absolute path to Windows PowerShell. */
535
+ powerShell?: () => string;
536
+ /** PATHEXT, as the environment reports it. */
537
+ pathExt?: () => string;
538
+ }
539
+ /**
540
+ * Thrown when a command's arguments do not fit the buffer of the only
541
+ * interpreter that can start it. Windows truncates rather than rejecting, and a
542
+ * system prompt cut off mid-sentence makes the planner answer half a question
543
+ * confidently — the silent success this repo refuses — so this is raised
544
+ * instead. `TaskOrchestrator.startTask` catches it and holds the task, so the
545
+ * message is what the user reads: it names the fix, because they cannot infer
546
+ * it from a truncated prompt.
547
+ */
548
+ declare class CommandLineTooLongError extends Error {
549
+ readonly command: string;
550
+ readonly length: number;
551
+ readonly limit: number;
552
+ constructor(command: string, length: number, limit?: number);
553
+ }
554
+ /**
555
+ * Thrown when only a batch shim resolved for a multi-line argument. cmd.exe
556
+ * reads up to the first CR/LF and discards the rest with no error and exit code
557
+ * 0 — quoting does not help — so the agent would get the first paragraph of its
558
+ * prompt without the completion marker instruction, then exit looking successful.
559
+ */
560
+ declare class EmbeddedNewlineError extends Error {
561
+ readonly command: string;
562
+ constructor(command: string);
563
+ }
564
+ /**
565
+ * Thrown when `command` cannot be resolved to a real file. Kept distinguishable
566
+ * from `WorkspaceNotFoundError` (utils/workspace) even though both a missing
567
+ * cwd and a missing binary surface as the same `spawn` ENOENT to Node — the two
568
+ * are checked, and named, separately so the failure names the actual cause.
569
+ */
570
+ declare class ExecutableNotFoundError extends Error {
571
+ readonly command: string;
572
+ readonly searchedPath: string;
573
+ constructor(command: string, searchedPath: string);
574
+ }
575
+ /**
576
+ * Whether `command` actually resolves to a file, given the plan
577
+ * {@link planDirectLaunch} produced for it and the PATH it was resolved
578
+ * against.
579
+ *
580
+ * POSIX is deliberately identity in `planDirectLaunch` (execvp does its own
581
+ * PATH search), so the search is repeated here instead. Windows already did
582
+ * the search inside `planDirectLaunch` — signalled by the returned file
583
+ * differing from the bare command name it was given; an unresolved command
584
+ * comes back unchanged.
585
+ */
586
+ declare function isExecutableResolved(command: string, plan: LaunchPlan, PATH: string, deps?: LaunchDeps): boolean;
587
+ /** The verbatim command line cmd.exe receives after `/d /s /c`, before wrapping. */
588
+ declare function windowsCommandLine(file: string, args: string[]): string;
589
+ /**
590
+ * How to start `command` with `args` through `spawn()`, with no shell.
591
+ *
592
+ * POSIX returns its input unchanged — execvp already searches PATH, and adding
593
+ * a resolution step there would be a new way for a working setup to break.
594
+ *
595
+ * Windows resolves the command against PATH × PATHEXT, preferring a native
596
+ * executable (spawned directly) over a batch shim (through cmd.exe) over a
597
+ * PowerShell script shim (through `powershell.exe -File`). A command that
598
+ * resolves to nothing is returned unchanged, so the caller's existing ENOENT —
599
+ * which names what the user typed — is what surfaces rather than a second,
600
+ * vaguer error from here.
601
+ *
602
+ * The tiers are tried in preference order and the first that *fits* wins, with
603
+ * one deliberate exception: an overflowing batch shim does not fall through to
604
+ * PowerShell. Overflow means a very large prompt, which is precisely where
605
+ * `-File` argument fidelity is least worth betting on, and where a clear held
606
+ * task beats a plausibly-mangled one. So capacity does not reorder the tiers —
607
+ * a `.ps1` beside a too-long `.cmd` still raises.
608
+ *
609
+ * A line break does reorder them: cmd.exe cannot carry one at any length, so a
610
+ * `.ps1` beside a `.cmd` wins, and a lone `.cmd` raises.
611
+ *
612
+ * @throws {CommandLineTooLongError} when the selected route's buffer cannot
613
+ * carry the arguments.
614
+ * @throws {EmbeddedNewlineError} when the arguments span lines and only the
615
+ * batch route resolved.
616
+ */
617
+ declare function planDirectLaunch(command: string, args: string[], deps?: LaunchDeps): Promise<LaunchPlan>;
618
+ /**
619
+ * How to start `command` for a surface that hands an executable and arguments
620
+ * to a terminal — the VS Code runner today, a Windows TUI later.
621
+ *
622
+ * On POSIX this is the login shell, unchanged: `bash -lc` runs the user's
623
+ * profile, which is how nvm/volta/asdf-managed runner binaries resolve at all.
624
+ * Windows has no login-shell equivalent (its PATH comes from the registry and
625
+ * is already inherited), so it takes the direct route instead. That is not just
626
+ * a simplification: it means the runner's own exit code is the terminal's exit
627
+ * code, rather than a `$LASTEXITCODE` that PowerShell propagates unreliably —
628
+ * and the exit code is half of what {@link VerdictEngine} judges a task on.
629
+ */
630
+ declare function planShellLaunch(command: string, args: string[], deps?: LaunchDeps): Promise<LaunchPlan>;
631
+
632
+ type SpawnFn = (command: string, args: string[], options: {
633
+ env: NodeJS.ProcessEnv;
634
+ stdio: Array<'pipe' | 'ignore'>;
635
+ cwd: string;
636
+ /** Set by the Windows batch route, where `args` is already a quoted command line. */
637
+ windowsVerbatimArguments?: boolean;
638
+ }) => ChildProcess;
639
+ /** Test seam: every OS touchpoint is injectable; production uses the defaults. */
640
+ interface HeadlessRunnerDeps {
641
+ spawnImpl?: SpawnFn;
642
+ hasScriptCmd?: () => boolean;
643
+ resolvePath?: () => Promise<string>;
644
+ /**
645
+ * Overrides for executable resolution ({@link planDirectLaunch}). Only the
646
+ * Windows branch consults them, so a POSIX test never needs to pass anything.
647
+ */
648
+ launchDeps?: LaunchDeps;
649
+ }
650
+ declare class HeadlessSession extends AbstractTerminalSession {
651
+ private spawnImpl;
652
+ readonly interactive: boolean;
653
+ private process;
654
+ private outputBuffer;
655
+ private controlStream;
656
+ constructor(id: string, taskId: string, spawnImpl: SpawnFn, interactive?: boolean);
657
+ get isStarted(): boolean;
658
+ start(launch: LaunchPlan, cwd: string, resolvedPath: string, env?: Record<string, string>, options?: {
659
+ controlChannel?: boolean;
660
+ }): void;
661
+ kill(): void;
662
+ getOutput(): string;
663
+ write(text: string): void;
664
+ /** PTY resize requests from a surface that owns the terminal rendering the wrapper. */
665
+ writeControl(text: string): void;
666
+ }
667
+
668
+ /** Everything needed to start one runner process, resolved before any child exists. */
669
+ interface PreparedLaunch {
670
+ launch: LaunchPlan;
671
+ resolvedPath: string;
672
+ env: Record<string, string>;
673
+ /** True when the invocation was wrapped in `script` to allocate a PTY. */
674
+ pty: boolean;
675
+ /** True when the started process needs an explicit Enter sent to submit its pre-filled prompt. */
676
+ submitPromptKey: boolean;
677
+ }
678
+ declare class HeadlessRunner extends AbstractRunner<HeadlessSession> {
679
+ private spawnImpl;
680
+ private hasScriptCmd;
681
+ private resolvePath;
682
+ private launchDeps;
683
+ private spawnCount;
684
+ /**
685
+ * Session shape: a piped subprocess is not a terminal, so runners get their
686
+ * non-interactive subcommand. The VS Code runner owns a pseudoterminal and
687
+ * overrides this to true. Autonomy is a separate axis (see `ResolveContext`)
688
+ * and stays on either way — no surface has a human answering permission
689
+ * prompts on the orchestrator's behalf.
690
+ */
691
+ protected readonly defaultInteractive: boolean;
692
+ constructor(deps?: HeadlessRunnerDeps);
693
+ /**
694
+ * Unique per spawn, not per task: a retry reuses its task id and ids often
695
+ * share a prefix, and a shared registry key let the old attempt's exit
696
+ * unregister the new one. Unlike TmuxRunner, nothing outside this process
697
+ * keys on the id, so a counter is enough to scope it to the attempt.
698
+ */
699
+ protected nextSessionId(taskId: string): string;
700
+ protected createSession(id: string, taskId: string): HeadlessSession;
701
+ /** Everything up to, but not including, spawning — so a surface that owns its own child reaches the same decisions. */
702
+ protected prepareLaunch(opts: RunnerSpawnOptions, ptyOptions?: PtyWrapOptions): Promise<PreparedLaunch>;
703
+ spawn(opts: RunnerSpawnOptions): Promise<ITerminalSession>;
704
+ }
705
+
706
+ /**
707
+ * What one model call consumed, as its provider or runner reported it. Shared
708
+ * by the planner's usage line (#49) and per-attempt task usage (#26): a record
709
+ * says nothing about who asked for the call, so either can hold a list of them.
710
+ *
711
+ * Every measure is optional because backends report different subsets. An
712
+ * absent field means "not reported" — never zero — so a total can tell the two
713
+ * apart.
714
+ */
715
+ interface UsageRecord {
716
+ /** The provider or runner id that reported the call — `openai`, `claude-code`, … */
717
+ source: string;
718
+ model?: string;
719
+ inputTokens?: number;
720
+ outputTokens?: number;
721
+ /** The share of `inputTokens` served from the provider's prompt cache. */
722
+ cachedInputTokens?: number;
723
+ /**
724
+ * Filled only from a provider's or runner's own report, never from a price
725
+ * table or an estimate: prices go stale, and a subscription runner has no
726
+ * per-token price at all. No report means no cost, not a guessed one.
727
+ */
728
+ reportedCost?: {
729
+ amount: number;
730
+ currency: string;
731
+ };
732
+ /** The model's context window, when the runner itself reports it. */
733
+ contextWindow?: number;
734
+ /** Set when a subagent made the call; its usage still counts toward the total. */
735
+ subagentId?: string;
736
+ }
737
+ /**
738
+ * A running sum of {@link UsageRecord}s. A measure stays absent until some
739
+ * record reports it. Cost is kept per currency: two runners may bill in
740
+ * different ones, and there is no honest exchange rate to fold them together.
741
+ */
742
+ interface UsageTotals {
743
+ inputTokens?: number;
744
+ outputTokens?: number;
745
+ cachedInputTokens?: number;
746
+ reportedCost?: Record<string, number>;
747
+ }
748
+ /**
749
+ * The input side of a call whose provider reports its prompt in parts — the
750
+ * uncached tail, with cache reads and cache writes beside it rather than inside
751
+ * it (Anthropic, and OpenCode after it). The prompt the model saw is all three;
752
+ * only the reads were served from cache, since a write is billed as fresh
753
+ * input. A part left unreported adds nothing, and with no part reported there
754
+ * is no measure at all.
755
+ */
756
+ declare function partedPromptUsage(parts: {
757
+ uncached?: number;
758
+ cacheRead?: number;
759
+ cacheWrite?: number;
760
+ }): Pick<UsageRecord, 'inputTokens' | 'cachedInputTokens'>;
761
+ declare function addUsage(totals: UsageTotals, record: UsageRecord): UsageTotals;
762
+ /**
763
+ * What the planner has consumed over a session (#49). `totals` includes every
764
+ * `bySubagent` entry. `lastPromptTokens` and `contextWindow` track the
765
+ * planner's own calls only — a subagent runs its own model, whose window says
766
+ * nothing about the planner's.
767
+ */
768
+ interface PlannerUsage {
769
+ totals: UsageTotals;
770
+ bySubagent?: Record<string, UsageTotals>;
771
+ lastPromptTokens?: number;
772
+ contextWindow?: number;
773
+ }
774
+ declare function addPlannerUsage(usage: PlannerUsage, record: UsageRecord): PlannerUsage;
775
+ /** Whether any measure was reported: a token line of nothing but blanks says nothing. */
776
+ declare function isMeasured(totals: UsageTotals): boolean;
777
+ /** What the token line shows of a ledger — live from its broadcast, or reloaded from the saved one. */
778
+ interface UsageLine {
779
+ totals: UsageTotals;
780
+ bySubagent?: Record<string, UsageTotals>;
781
+ contextFill?: {
782
+ usedTokens: number;
783
+ windowTokens: number;
784
+ };
785
+ }
786
+ declare function usageLine(usage: PlannerUsage): UsageLine;
787
+ /**
788
+ * The last planner prompt against its window, or undefined while either is
789
+ * unknown. `usedTokens` is the prompt total as reported, cached tokens
790
+ * included: a cached token still occupies the window, so subtracting the
791
+ * cached share would understate how full the context is. A window of 0 is
792
+ * treated as unknown — never guessed.
793
+ */
794
+ declare function plannerContextFill(usage: PlannerUsage): {
795
+ usedTokens: number;
796
+ windowTokens: number;
797
+ } | undefined;
798
+
799
+ /**
800
+ * The planner's single approval seam. Every capability that reaches beyond the
801
+ * default read-only, in-workspace envelope — a path outside the workspace root,
802
+ * a shell command outside the auto-allowed set, a URL fetch — routes through
803
+ * one `request()` so the policy has exactly one owner (the same "one repair
804
+ * owner" shape as PlanRepair).
805
+ *
806
+ * Surfaces supply the human channel. VS Code answers with a modal; the web
807
+ * server currently has no prompt UI, so it denies unless the scope was
808
+ * pre-approved through config. Denial is always a visible, actionable tool
809
+ * result — never a silent success.
810
+ */
811
+ /**
812
+ * `runner_tool` is a task runner's own tool request (ADR-0018, A1): it waits
813
+ * for an answer as long as it takes, and never passes through the planner's
814
+ * policy — the runner's mode already decided it needed asking.
815
+ */
816
+ type ApprovalKind = 'external_path' | 'shell_command' | 'url_fetch' | 'runner_tool';
817
+ interface ApprovalRequest {
818
+ kind: ApprovalKind;
819
+ /** The concrete thing being asked about: an absolute path, a command line, a URL. */
820
+ subject: string;
821
+ /**
822
+ * What a grant covers. Approving remembers this, not `subject`, so reading a
823
+ * second file from an already-approved directory does not prompt again.
824
+ */
825
+ scope: string;
826
+ /**
827
+ * Every scope one answer settles, when a command needs more than one — its
828
+ * own and each outside directory it touches — so it prompts once rather than
829
+ * once per scope. `scope` is the first. Absent means `scope` alone.
830
+ */
831
+ scopes?: string[];
832
+ /** One-line context for the prompt. */
833
+ detail?: string;
834
+ /** The task whose runner asked; absent for the planner's own requests. */
835
+ taskId?: string;
836
+ /** "Allow for this task" can be offered: the runner proposed its own session-scoped grant. */
837
+ allowForTask?: boolean;
838
+ }
839
+ /**
840
+ * An answer, from whoever gives it — a person on any surface, or later the
841
+ * supervisor (#28). `allowForTask` is Allow plus the runner's own grant for
842
+ * the rest of the task; `note` goes back to the agent with a denial.
843
+ */
844
+ type ApprovalDecision = {
845
+ decision: 'allow';
846
+ } | {
847
+ decision: 'allowForTask';
848
+ } | {
849
+ decision: 'deny';
850
+ note?: string;
851
+ };
852
+ /** What an answer may be given as: a planner prompt's yes/no still is one. */
853
+ type ApprovalAnswer = boolean | ApprovalDecision;
854
+ declare function toApprovalDecision(answer: ApprovalAnswer): ApprovalDecision;
855
+ declare function isGranted(decision: ApprovalDecision): boolean;
856
+ declare function approvalScopes(request: ApprovalRequest): string[];
857
+ declare function isRunnerApproval(request: ApprovalRequest): boolean;
858
+ interface IApproval {
859
+ request(req: ApprovalRequest): Promise<boolean>;
860
+ }
861
+ /** Denies everything. The safe default when a surface wires no approval channel. */
862
+ declare const DENY_ALL: IApproval;
863
+
864
+ /**
865
+ * The harness-planner transport contract (ADR-0009).
866
+ *
867
+ * One adapter per coding agent, each speaking that agent's own programmatic
868
+ * protocol and normalizing it to the event union below. Everything above this
869
+ * line — reply classification, the repair loop, plan validation, the four
870
+ * surfaces — is already provider-agnostic, so an adapter is the entire cost of
871
+ * teaching Ordewell to plan with another agent.
872
+ */
873
+ /**
874
+ * One normalized event from a running agent turn. Deliberately smaller than
875
+ * any single agent's native protocol: this is the intersection Ordewell can act
876
+ * on, not a lossless re-encoding. Event fidelity differs by agent — `thinking`
877
+ * is rich on Claude Code and absent elsewhere — so consumers must tolerate a
878
+ * turn that emits nothing but `assistant_text` and `turn_end`.
879
+ */
880
+ type AgentEvent =
881
+ /**
882
+ * A complete run of the assistant's reply. Concatenated in order to form the
883
+ * turn's text. When the same run already streamed as `assistant_text_delta`,
884
+ * this is the authoritative copy of it — it replaces the deltas, it is not
885
+ * appended after them.
886
+ */
887
+ {
888
+ type: 'assistant_text';
889
+ text: string;
890
+ }
891
+ /**
892
+ * An incremental piece of the assistant's reply, for agents that stream
893
+ * partial messages. The planner's own text only: a subagent's words never
894
+ * arrive here, so they can never become the reply.
895
+ */
896
+ | {
897
+ type: 'assistant_text_delta';
898
+ text: string;
899
+ }
900
+ /**
901
+ * Reasoning the agent chose to expose. Never contributes to the reply text.
902
+ * Like `assistant_text`, it supersedes deltas already streamed for it.
903
+ */
904
+ | {
905
+ type: 'thinking';
906
+ text: string;
907
+ subagentId?: string;
908
+ } | {
909
+ type: 'thinking_delta';
910
+ text: string;
911
+ subagentId?: string;
912
+ }
913
+ /** `subagentId` marks a call made inside a subagent rather than by the planner itself. */
914
+ | {
915
+ type: 'tool_call';
916
+ id: string;
917
+ name: string;
918
+ args: Record<string, unknown>;
919
+ subagentId?: string;
920
+ } | {
921
+ type: 'tool_result';
922
+ id: string;
923
+ name: string;
924
+ output: string;
925
+ success: boolean;
926
+ subagentId?: string;
927
+ }
928
+ /** One model call's usage, as the agent reported it — never estimated. */
929
+ | {
930
+ type: 'usage';
931
+ record: UsageRecord;
932
+ }
933
+ /** The agent delegated `brief` to a subagent, whose events carry `subagentId` until it finishes. */
934
+ | {
935
+ type: 'subagent_started';
936
+ subagentId: string;
937
+ brief: string;
938
+ model?: string;
939
+ } | {
940
+ type: 'subagent_finished';
941
+ subagentId: string;
942
+ outcome: SubagentOutcome;
943
+ digest: string;
944
+ }
945
+ /**
946
+ * The agent asked to do something its mode does not cover. A planner always
947
+ * auto-denies it (T1) — a planner that can mutate is not a planner — and the
948
+ * adapter answers so the turn does not hang. A task's request stays open
949
+ * until {@link TaskModeAgentAdapter.answerPermission} (ADR-0018, A1).
950
+ *
951
+ * `input` and `suggestions` are the raw request; `suggestions` are the
952
+ * agent's own session-scoped grants, what "Allow for this task" answers with.
953
+ * `decided` marks a request the task's mode already answered — the adapter
954
+ * replied as the manifest says that mode does — so it is shown, never asked.
955
+ */
956
+ | {
957
+ type: 'permission_request';
958
+ id: string;
959
+ name: string;
960
+ detail: string;
961
+ input?: Record<string, unknown>;
962
+ suggestions?: unknown[];
963
+ toolUseId?: string;
964
+ decided?: ApprovalDecision;
965
+ }
966
+ /** The agent withdrew an open request — an interrupt cancels the call it was for. It takes no answer now. */
967
+ | {
968
+ type: 'permission_cancelled';
969
+ id: string;
970
+ }
971
+ /**
972
+ * The agent delegated work to a subagent it left running in the background,
973
+ * and may end its turn before that work reports. Ordewell's conversation is
974
+ * request/response: a turn that ends hands control back to the user, and
975
+ * anything the agent says afterwards arrives with no turn open and is lost.
976
+ * Naming the launch is what lets the service ask for the results in time.
977
+ */
978
+ | {
979
+ type: 'background_agent';
980
+ id: string;
981
+ }
982
+ /**
983
+ * The agent finished its turn and is waiting for the next user message.
984
+ * `interrupted` marks a turn cut short by {@link TaskModeAgentAdapter.interrupt}
985
+ * rather than one the agent chose to end.
986
+ */
987
+ | {
988
+ type: 'turn_end';
989
+ interrupted?: boolean;
990
+ }
991
+ /** The turn failed. Carries the agent's own words — never a Ordewell paraphrase. */
992
+ | {
993
+ type: 'error';
994
+ message: string;
995
+ };
996
+ interface AgentStartCommon {
997
+ /** Workspace root. The agent works from here and, in read-only mode, cannot leave it. */
998
+ cwd: string;
999
+ /** Model id from the runner's own discovery catalog. Omitted means the agent's default. */
1000
+ model?: string;
1001
+ /**
1002
+ * The agent's own session id from a previous run. For the planner a hint
1003
+ * only: Ordewell's transcript is the source of truth (T4), so a failed resume
1004
+ * degrades to a fresh session seeded from the stored history, not an error.
1005
+ */
1006
+ resumeSessionId?: string;
1007
+ }
1008
+ /** The read-only planner (ADR-0008/0009). The only start `CliAgentAiService` can express. */
1009
+ interface PlannerStartOptions extends AgentStartCommon {
1010
+ kind: 'planner';
1011
+ /** The planner system prompt, in its harness variant. */
1012
+ systemPrompt: string;
1013
+ /** Variant / reasoning effort id from that model's `variants` list. */
1014
+ effort?: string;
1015
+ }
1016
+ /**
1017
+ * What a runner manifest says the task's mode and effort mean (ADR-0001),
1018
+ * resolved by the same code terminal tasks use — see `resolveTaskRunnerFlags`.
1019
+ * The adapter adds only its protocol flags around these.
1020
+ */
1021
+ interface TaskRunnerFlags {
1022
+ /** The runner's own permission-mode value for the task's mode. */
1023
+ permissionMode: string;
1024
+ /** The task's raw effort id, present only alongside a model. Each adapter maps it to its own protocol. */
1025
+ effort?: string;
1026
+ /** The manifest's further settings for the task's mode, by setting name — see `PluginFeatures.modeSettings`. */
1027
+ modeSettings: Record<string, string>;
1028
+ }
1029
+ /** A plan task driven over the runner's programmatic protocol (ADR-0018, C1). */
1030
+ interface TaskStartOptions extends AgentStartCommon {
1031
+ kind: 'task';
1032
+ /** The task's runner mode id, as the plan names it. */
1033
+ mode: string;
1034
+ flags: TaskRunnerFlags;
1035
+ }
1036
+ /**
1037
+ * The explicit start switch. Discriminated so that a read-only planner and a
1038
+ * mutating task can never be confused by a missing field: every caller names
1039
+ * which one it is starting.
1040
+ */
1041
+ type AgentStartOptions = PlannerStartOptions | TaskStartOptions;
1042
+ /** A runner asked to start in task mode that has no task-mode connector yet. */
1043
+ declare class TaskModeUnsupportedError extends Error {
1044
+ readonly runner: string;
1045
+ constructor(runner: string);
1046
+ }
1047
+ interface AgentAdapter {
1048
+ /** The runner id this adapter drives — `claude-code`, `codex`, `opencode`. */
1049
+ readonly agentId: string;
1050
+ /** Spawn the agent — read-only for a planner, in the task's mode for a task — ready to receive messages. */
1051
+ start(opts: AgentStartOptions): Promise<void>;
1052
+ /**
1053
+ * Send one user message and stream the turn's events until it ends. Resolves
1054
+ * when the agent yields the floor; rejects only when the transport itself
1055
+ * failed in a way no `error` event could describe.
1056
+ *
1057
+ * `onActivity`, when given, fires on raw transport traffic — every stdio
1058
+ * line or stream chunk the process produces — independent of whether that
1059
+ * traffic becomes an `AgentEvent`. An adapter may legitimately emit nothing
1060
+ * for long stretches (a subagent's filtered output, most often); a caller
1061
+ * using presence-of-events as a liveness signal would read that silence as
1062
+ * a hang. `onActivity` is the seam that keeps liveness detection from being
1063
+ * coupled to what each adapter chooses to surface.
1064
+ */
1065
+ send(message: string, onEvent: (event: AgentEvent) => void, signal?: AbortSignal, onActivity?: () => void): Promise<void>;
1066
+ /** The agent's native session id once it has announced one. Resumption hint only. */
1067
+ nativeSessionId(): string | null;
1068
+ /** Kill the process and release its resources. Idempotent. */
1069
+ dispose(): void;
1070
+ }
1071
+ /** What an adapter adds to run a task rather than a planner (ADR-0018). */
1072
+ interface TaskModeAgentAdapter extends AgentAdapter {
1073
+ /**
1074
+ * Ask the running turn to stop, keeping the process and its session. Resolves
1075
+ * true once the agent acknowledged it; the turn then ends with
1076
+ * `turn_end { interrupted: true }`. False means the agent did not answer
1077
+ * within `timeoutMs`, and the caller must fall back to killing it.
1078
+ */
1079
+ interrupt(timeoutMs: number): Promise<boolean>;
1080
+ /**
1081
+ * Registers the listener for what the agent does after a turn has ended and
1082
+ * before the next message — a turn it opens itself when background work
1083
+ * finishes, most often. Without one that output is dropped, which is right
1084
+ * for a planner and wrong for a task, whose marker may be said there.
1085
+ */
1086
+ onOutOfTurn?(listener: (event: AgentEvent) => void): void;
1087
+ /** Registers a listener for the process ending, for any reason. Fires at most once. */
1088
+ onProcessExit(listener: (code: number) => void): void;
1089
+ /**
1090
+ * Answer an open `permission_request`. False when the id is not open — it
1091
+ * was answered, cancelled, or never asked.
1092
+ */
1093
+ answerPermission(id: string, decision: ApprovalDecision): boolean;
1094
+ }
1095
+ /**
1096
+ * The single injected boundary between Ordewell and the operating system —
1097
+ * the same pattern `HeadlessRunnerDeps` uses for task execution. Tests feed
1098
+ * recorded agent output through `spawn` (and, for HTTP-transport agents,
1099
+ * `fetch`) so one test exercises adapter parsing, event mapping, reply
1100
+ * classification and the repair loop as a single observable behavior.
1101
+ */
1102
+ interface AgentProcessDeps {
1103
+ spawn: SpawnFn;
1104
+ fetch: typeof globalThis.fetch;
1105
+ /** Resolves the PATH agents are spawned under. Defaults to the augmented PATH. */
1106
+ resolvePath?: () => Promise<string>;
1107
+ /** Host platform. Defaults to the real one; injected so OS-specific behavior is testable anywhere. */
1108
+ platform?: NodeJS.Platform;
1109
+ /** True when `workspace` names an existing directory. Defaults to a real filesystem check. */
1110
+ isDirectory?: (workspace: string) => boolean;
1111
+ /** True when `candidate` names an existing, spawnable file. Defaults to a real filesystem check. */
1112
+ exists?: (candidate: string) => boolean;
1113
+ /** The workspace's own variables for a cwd (ADR-0016). Defaults to {@link resolveWorkspaceEnv}. */
1114
+ workspaceEnv?: (cwd: string) => Promise<Record<string, string>>;
1115
+ }
1116
+ /** Builds the adapter for one runner id, or null when that runner cannot plan. */
1117
+ type AgentAdapterFactory = (runner: string, deps: AgentProcessDeps) => AgentAdapter | null;
1118
+ /**
1119
+ * Split a stream of chunks into complete lines. Every agent transport here is
1120
+ * newline-delimited JSON of some shape, and a chunk boundary lands mid-object
1121
+ * often enough that parsing per-chunk silently drops events.
1122
+ */
1123
+ declare class LineBuffer {
1124
+ private buffer;
1125
+ push(chunk: string, onLine: (line: string) => void): void;
1126
+ /** Anything left unterminated when the stream closed. */
1127
+ flush(): string;
1128
+ }
1129
+
1130
+ interface RunnerPluginManifest {
1131
+ name: string;
1132
+ displayName: string;
1133
+ description: string;
1134
+ version: string;
1135
+ author?: string;
1136
+ homepage?: string;
1137
+ runner: PluginRunnerDef;
1138
+ features: PluginFeatures;
1139
+ modelDiscovery: PluginModelDiscovery;
1140
+ contextFile?: string;
1141
+ contextFileAltPath?: string;
1142
+ modes?: PluginMode[];
1143
+ }
1144
+ interface PluginRunnerDef {
1145
+ command: string;
1146
+ argsTemplate: string[];
1147
+ promptInArgs: boolean;
1148
+ env?: Record<string, string>;
1149
+ /** When true, the runner requires a PTY. HeadlessRunner wraps with `script` to allocate one. */
1150
+ requiresTty?: boolean;
1151
+ /**
1152
+ * True when this runner's interactive prompt flag (e.g. opencode's
1153
+ * `--prompt`) only pre-fills its TUI's composer instead of running it, so a
1154
+ * surface driving that TUI unattended must send an explicit Enter after
1155
+ * launch. Only takes effect while the resolved invocation is interactive —
1156
+ * see `RunnerInvocation.submitPromptKey`.
1157
+ */
1158
+ submitPromptKey?: boolean;
1159
+ /**
1160
+ * Screens the agent can stop on before starting the task, waiting for a
1161
+ * human — a folder-trust or permission-mode confirmation. Ordewell never
1162
+ * answers one; seeing it, the task's user is told where to.
1163
+ */
1164
+ blockingPrompts?: BlockingPrompt[];
1165
+ }
1166
+ interface BlockingPrompt {
1167
+ /** Text the prompt shows; matched ignoring case and whitespace. */
1168
+ phrase: string;
1169
+ /** Completes "<runner> is asking …", e.g. "whether to trust this folder". */
1170
+ asks: string;
1171
+ }
1172
+ interface PluginFeatures {
1173
+ modelSelection: boolean;
1174
+ thinkingEffort: boolean;
1175
+ planMode: boolean;
1176
+ planModeFlag: string;
1177
+ buildModeFlag?: string;
1178
+ /** Flag appended when headless mode is on, so the agent never prompts for permission (e.g. Claude's --dangerously-skip-permissions). */
1179
+ headlessFlag?: string;
1180
+ thinkingFlag?: string;
1181
+ thinkingValueEnabled?: string;
1182
+ thinkingValueDisabled?: string;
1183
+ thinkingValueAdaptive?: string;
1184
+ /** Maps mode IDs to the CLI --permission-mode value. Used by {{feature:permissionModeVal}}. */
1185
+ permissionModeValues?: Record<string, string>;
1186
+ /**
1187
+ * Further per-mode settings for runners whose permission story has more than
1188
+ * one axis (Codex: sandbox, approval policy, approvals reviewer). Keyed by
1189
+ * setting name, then by mode id; a mode a map does not name leaves that
1190
+ * setting to the runner's own default. Codex declares `approvalPolicy`
1191
+ * (`-a` / `approval_policy`) and `approvalsReviewer` (`approvals_reviewer`);
1192
+ * the terminal template reads them too, through `{{feature:approvalPolicyVal}}`
1193
+ * and the `*Config` tokens.
1194
+ */
1195
+ modeSettings?: Record<string, Record<string, string>>;
1196
+ }
1197
+ type PluginParser = 'claude-help' | 'opencode-models' | 'opencode-models-verbose' | 'anthropic-models' | 'line-by-line' | 'json' | 'json-table';
1198
+ interface DiscoveryCommand {
1199
+ command: string;
1200
+ args: string[];
1201
+ parser?: PluginParser;
1202
+ }
1203
+ type ApiAuthMethod = {
1204
+ type: 'env';
1205
+ varName: string;
1206
+ header: string;
1207
+ prefix?: string;
1208
+ } | {
1209
+ type: 'file';
1210
+ path: string;
1211
+ jsonPath: string;
1212
+ header: string;
1213
+ prefix?: string;
1214
+ };
1215
+ interface ApiDiscoveryConfig {
1216
+ url: string;
1217
+ headers?: Record<string, string>;
1218
+ auth: ApiAuthMethod[];
1219
+ parser: PluginParser;
1220
+ }
1221
+ interface PluginModelDiscovery {
1222
+ method: 'command' | 'hardcoded';
1223
+ command?: string;
1224
+ args?: string[];
1225
+ parser?: PluginParser;
1226
+ jsonPath?: string;
1227
+ /**
1228
+ * Stdio JSON-RPC discovery (Codex `app-server`): spawn the command, send
1229
+ * `initialize` then `model/list`, and read the catalog from the response.
1230
+ * Tried BEFORE apiDiscovery and command discovery. When the call fails,
1231
+ * `cacheFile` (the runner's own on-disk catalog cache, `~` expanded) is
1232
+ * read before falling through to the remaining discovery methods.
1233
+ */
1234
+ appServer?: {
1235
+ command: string;
1236
+ args: string[];
1237
+ cacheFile?: string;
1238
+ };
1239
+ /**
1240
+ * Optional last-resort list for user plugins whose CLI cannot enumerate
1241
+ * models. Used only when command discovery fails entirely or the CLI is
1242
+ * unavailable. Built-in manifests must NOT use this: anything listed here is
1243
+ * shown to the user as available even when it isn't.
1244
+ */
1245
+ fallbackModels?: {
1246
+ modelId: string;
1247
+ modelLabel: string;
1248
+ }[];
1249
+ /**
1250
+ * Stable `--model` aliases that the runner's CLI always accepts but its help
1251
+ * text may omit (e.g. Claude's 'haiku'). Merged into successful discovery
1252
+ * results to fill gaps — discovered models take precedence, missing aliases
1253
+ * are appended — and used as the last resort when discovery fails entirely.
1254
+ * Unlike `fallbackModels`, entries must be stable CLI-accepted aliases
1255
+ * (contracts that always resolve), not arbitrary model IDs.
1256
+ */
1257
+ canonicalAliases?: {
1258
+ modelId: string;
1259
+ modelLabel: string;
1260
+ }[];
1261
+ /**
1262
+ * HTTP API discovery — tried BEFORE command discovery. When the runner's CLI
1263
+ * has no model-listing subcommand (Claude Code), an API endpoint can serve as
1264
+ * the authoritative source. Auth methods are tried in order; the first that
1265
+ * yields a token is used. If no auth method yields a token or the request
1266
+ * fails, discovery falls through to `discoveryCommands` + `canonicalAliases`.
1267
+ */
1268
+ apiDiscovery?: ApiDiscoveryConfig;
1269
+ preferredPatterns?: {
1270
+ id: string;
1271
+ label: string;
1272
+ }[];
1273
+ variants?: {
1274
+ id: string;
1275
+ label: string;
1276
+ }[];
1277
+ discoveryCommands?: DiscoveryCommand[];
1278
+ }
1279
+ interface PluginMode {
1280
+ id: string;
1281
+ label: string;
1282
+ description: string;
1283
+ /** CLI value passed to the runner's permission/mode flag. Defaults to id if omitted. */
1284
+ cliValue?: string;
1285
+ /** Marks this mode as the runner's most permissive mode — the resolved default when autonomous mode is ON. */
1286
+ autonomous?: boolean;
1287
+ /** Marks this mode as the runner's conservative build mode — the resolved default when autonomous mode is OFF. */
1288
+ safe?: boolean;
1289
+ }
1290
+ interface PluginEntry {
1291
+ manifest: RunnerPluginManifest;
1292
+ source: 'builtin' | 'user';
1293
+ installPath?: string;
1294
+ }
1295
+ interface ResolveContext {
1296
+ prompt: string;
1297
+ model?: string;
1298
+ thinkingEffort?: string;
1299
+ /** All variant ids the assigned model offers — lets {{opencodeVariantConfig}} disable the non-chosen ones. */
1300
+ modelVariants?: string[];
1301
+ mode: string;
1302
+ /**
1303
+ * Autonomy axis: when true, resolve {{if headless}} blocks and the
1304
+ * {{feature:headless}} token so the agent never stops to ask for permission.
1305
+ * True for every orchestrated task run — nobody is watching the terminal on
1306
+ * Ordewell's behalf — independently of the session *shape* below.
1307
+ */
1308
+ headless?: boolean;
1309
+ /**
1310
+ * Session-shape axis: true when the runner is launched onto a real TTY the
1311
+ * user can attach to (a tmux window, a VS Code pseudoterminal), so the
1312
+ * runner's own TUI should come up rather than its non-interactive
1313
+ * subcommand. Defaults to `!headless` for callers that predate the split.
1314
+ */
1315
+ interactive?: boolean;
1316
+ /** The task's working directory — needed by runners whose autonomy flags name a path. */
1317
+ cwd?: string;
1318
+ }
1319
+ interface RunnerInvocation {
1320
+ command: string;
1321
+ args: string[];
1322
+ env: Record<string, string>;
1323
+ promptInArgs: boolean;
1324
+ /** True when a surface running this invocation on a real TTY must send an explicit Enter once the process starts. */
1325
+ submitPromptKey: boolean;
1326
+ }
1327
+ /**
1328
+ * Persistent storage seam for plugin manifests. The RunnerRegistry delegates
1329
+ * all filesystem operations to this interface so the plugin lifecycle is
1330
+ * testable without real I/O.
1331
+ */
1332
+ interface IPluginStore {
1333
+ /** Path to the user plugins directory (~/.ordewell/plugins/). */
1334
+ getUserPluginsDir(): string;
1335
+ /** List subdirectory names inside the user plugins directory. */
1336
+ listUserPluginDirs(): string[];
1337
+ /** List entry names directly inside a directory. Returns [] when unreadable. */
1338
+ listDir(dir: string): string[];
1339
+ /** Read and parse a manifest.json from pluginDir. Returns null on failure. */
1340
+ loadManifest(pluginDir: string): RunnerPluginManifest | null;
1341
+ /** Recursively copy sourceDir to destDir. */
1342
+ copyDir(sourceDir: string, destDir: string): void;
1343
+ /** Recursively remove a directory. */
1344
+ removeDir(dir: string): void;
1345
+ /** Ensure a directory exists (mkdir -p). */
1346
+ ensureDir(dir: string): void;
1347
+ /** Write a text file. */
1348
+ writeFile(filePath: string, content: string): void;
1349
+ /** Read a UTF-8 text file. Returns null on ENOENT or read error. */
1350
+ readFile(filePath: string): string | null;
1351
+ /** True if path exists and is a directory. */
1352
+ dirExists(path: string): boolean;
1353
+ /** True if path exists. */
1354
+ exists(path: string): boolean;
1355
+ }
1356
+
1357
+ /**
1358
+ * Decides whether one out-of-envelope capability may run, and remembers the
1359
+ * answer for the rest of the session.
1360
+ *
1361
+ * Grants are keyed on {@link ApprovalRequest.scope}, never on the concrete
1362
+ * subject: approving a read of `/tmp/foo/a.log` grants `/tmp/foo/*`, and
1363
+ * approving `az group list` grants `az group`. Without that, a planner doing
1364
+ * real research would prompt on every single call and the feature would be
1365
+ * unusable.
1366
+ *
1367
+ * `mode` is the policy floor:
1368
+ * ask consult the human channel; no channel means deny (headless, web)
1369
+ * allow grant everything the tier system did not already refuse
1370
+ * deny grant nothing beyond `preApproved`
1371
+ *
1372
+ * Note the ordering: `preApproved` is honored under every mode including
1373
+ * `deny`, because it is an explicit operator decision rather than a default.
1374
+ */
1375
+ type ApprovalMode = 'ask' | 'allow' | 'deny';
1376
+ interface ApprovalPolicyOptions {
1377
+ mode?: ApprovalMode;
1378
+ /** Scopes granted up front from config. A trailing `*` matches by prefix. */
1379
+ preApproved?: string[];
1380
+ /** The human channel. Absent means there is nobody to ask. */
1381
+ ask?: (req: ApprovalRequest) => Promise<boolean>;
1382
+ /** Called whenever a decision is reached, for surfacing in a UI or a log. */
1383
+ onDecision?: (req: ApprovalRequest, granted: boolean, source: ApprovalSource) => void;
1384
+ }
1385
+ type ApprovalSource = 'pre-approved' | 'remembered' | 'mode' | 'asked' | 'no-channel';
1386
+ declare class ApprovalPolicy implements IApproval {
1387
+ private readonly mode;
1388
+ private readonly preApproved;
1389
+ private readonly asker?;
1390
+ private readonly onDecision?;
1391
+ private readonly granted;
1392
+ private readonly refused;
1393
+ /** One in-flight ask per scope: a parallel tool round must not prompt twice for the same thing. */
1394
+ private readonly inFlight;
1395
+ private generation;
1396
+ constructor(opts?: ApprovalPolicyOptions);
1397
+ request(req: ApprovalRequest): Promise<boolean>;
1398
+ /** Scopes the user has granted this session — for display and for persistence. */
1399
+ grantedScopes(): string[];
1400
+ /** Drop every session-scoped decision. Called on session reset. */
1401
+ reset(): void;
1402
+ }
1403
+
1404
+ interface CatalogModel {
1405
+ id: string;
1406
+ name: string;
1407
+ description: string;
1408
+ pricing: {
1409
+ prompt: string;
1410
+ completion: string;
1411
+ };
1412
+ contextLength: number;
1413
+ }
1414
+ declare class ModelCatalog {
1415
+ static fetchModels(apiKey: string, baseUrl?: string, fetchImpl?: typeof fetch): Promise<CatalogModel[]>;
1416
+ /**
1417
+ * Delete the on-disk catalog cache for a base URL so the next fetch re-runs.
1418
+ * Used by the resolver's `invalidate()` in production (no injected fetch);
1419
+ * best-effort — a missing file or unreadable dir is a no-op.
1420
+ */
1421
+ static clearCache(baseUrl?: string): void;
1422
+ private static readCache;
1423
+ private static writeCache;
1424
+ }
1425
+
1426
+ interface ModelShortcut {
1427
+ label: string;
1428
+ id: string;
1429
+ provider: string;
1430
+ description: string;
1431
+ pricing?: string;
1432
+ }
1433
+ declare const ORCHESTRATOR_SHORTCUTS: ModelShortcut[];
1434
+ declare function resolveModelShortcut(input: string, shortcuts: ModelShortcut[]): string | null;
1435
+ /**
1436
+ * Resolves a value to a model id ONLY when it is in the supplied catalog
1437
+ * option list — either directly or via a shortcut label. Free-typed, unknown,
1438
+ * or not-currently-available values return null, so callers never store an id
1439
+ * the user couldn't have selected from the list. Keeps model-setting list-only.
1440
+ */
1441
+ declare function knownModelId(value: string, optionIds: string[], shortcuts: ModelShortcut[]): string | null;
1442
+
1443
+ type ProviderModelLists = Record<string, string[]>;
1444
+ interface OrchestratorOption {
1445
+ id: string;
1446
+ label: string;
1447
+ provider: string;
1448
+ apiProvider: AiProvider;
1449
+ description?: string;
1450
+ pricing?: string;
1451
+ /** The model's context window when the catalog reports one (#49). */
1452
+ contextWindow?: number;
1453
+ }
1454
+
1455
+ interface FetchAllProviderModelsOptions {
1456
+ apiKeys: Record<string, string>;
1457
+ baseUrls: Record<string, string>;
1458
+ fetchImpl?: typeof fetch;
1459
+ }
1460
+ type AllProviderModels = Record<string, CatalogModel[]>;
1461
+ /**
1462
+ * Result of a picker-catalog fetch fan-out: the per-provider model lists plus
1463
+ * the per-provider failures. `errors` is keyed by provider id and holds the
1464
+ * failure message for any provider whose catalog fetch rejected — the seam the
1465
+ * surfaces (CLI, VS Code) use to flag "this configured provider didn't work"
1466
+ * rather than silently showing a short list.
1467
+ */
1468
+ interface ProviderModelsResult {
1469
+ models: AllProviderModels;
1470
+ errors: Record<string, string>;
1471
+ }
1472
+ /** The provider config fields the discovery fan-out needs. */
1473
+ interface ProviderCredentialSource {
1474
+ getProviderApiKey(provider: AiProvider): string;
1475
+ getProviderBaseUrl(provider: AiProvider): string;
1476
+ openaiCompatibleBaseUrl: string;
1477
+ }
1478
+ /**
1479
+ * Collect the API keys and base URLs the picker fan-out should probe, applying
1480
+ * the single "configured" policy shared by every surface (CLI + VS Code):
1481
+ * - a preset is discovered only when it has an API key (OpenRouter included —
1482
+ * its public catalog is not probed keyless, matching the product rule that
1483
+ * only key-configured providers appear);
1484
+ * - `openai_compatible` is discovered only when an explicit endpoint is set
1485
+ * (keyless local servers like ollama / LM Studio).
1486
+ * Base URLs are handed through only for providers that pass the gate, so the
1487
+ * fan-out never touches an unconfigured third-party endpoint.
1488
+ */
1489
+ declare function collectProviderCredentials(config: ProviderCredentialSource): {
1490
+ apiKeys: Record<string, string>;
1491
+ baseUrls: Record<string, string>;
1492
+ };
1493
+ declare function fetchAllProviderModels(opts: FetchAllProviderModelsOptions): Promise<ProviderModelsResult>;
1494
+ declare function resolveProvider(modelId: string, providerModelLists: Record<string, string[]>): AiProvider | null;
1495
+ declare function toOrchestratorOptions(providerModels: AllProviderModels, shortcuts: ModelShortcut[]): OrchestratorOption[];
1496
+
1497
+ /**
1498
+ * Who plans. Mostly LLM vendors reached over HTTP; the last three are *harness
1499
+ * planners* (ADR-0009) — a coding agent CLI already installed on the machine,
1500
+ * driven as the planner over its own programmatic transport and authenticated
1501
+ * by the subscription the user already holds. They are runners in the provider
1502
+ * axis, deliberately: "what plans for me?" is one question, and it belongs in
1503
+ * one setting. `isCliProvider` is the single guard that tells the two kinds
1504
+ * apart.
1505
+ */
1506
+ type AiProvider = 'google' | 'openrouter' | 'openai_compatible' | 'openai' | 'xai' | 'groq' | 'deepseek' | 'together' | 'mistral' | 'anthropic' | 'fireworks' | 'perplexity' | 'zhipu' | 'kimi' | 'cerebras' | 'deepinfra' | 'doubao' | 'qwen' | 'hunyuan' | 'baichuan' | 'minimax' | 'yi' | 'stepfun' | 'siliconflow' | 'cohere' | 'novita' | 'claude-code' | 'codex' | 'opencode';
1507
+ interface IConfig {
1508
+ aiProvider: AiProvider;
1509
+ apiKey: string;
1510
+ planningModel: string;
1511
+ enabledRunners: string[];
1512
+ maxParallelSessions: number;
1513
+ researchEnabled: boolean;
1514
+ researchMaxSteps: number;
1515
+ researchMaxFileSize: number;
1516
+ openAiBaseUrl: string;
1517
+ openAiApiKey: string;
1518
+ /** Provider keys + base URL the ModelResolver uses to fetch the picker catalogs. */
1519
+ openrouterKey: string;
1520
+ geminiKey: string;
1521
+ geminiBaseUrl?: string;
1522
+ /** Base URL + API key for a user-provided OpenAI-compatible endpoint (ollama, vLLM, LM Studio, etc.). */
1523
+ openaiCompatibleBaseUrl: string;
1524
+ openaiCompatibleApiKey: string;
1525
+ orchestratorModel: string;
1526
+ geminiModel: string;
1527
+ /** Model for research subagents (issue #34); defaults to the (cheap) planner model. */
1528
+ researchSubagentModel: string;
1529
+ /**
1530
+ * Thinking effort / model variant for a harness planner (ADR-0009), chosen
1531
+ * from the agent's own discovered variants. Separate from the per-task
1532
+ * efforts the plan carries — this one is the planner's own dial.
1533
+ */
1534
+ plannerThinkingEffort?: string;
1535
+ planMapEnabled: boolean;
1536
+ autonomousMode: boolean;
1537
+ /**
1538
+ * Run each AI task in its own git worktree and integrate the results on a
1539
+ * per-run branch (ADR-0013). Non-git workspaces fall back to the shared
1540
+ * workspace root regardless of this flag.
1541
+ */
1542
+ worktreeIsolation: boolean;
1543
+ /**
1544
+ * Shell command run in a fresh task worktree instead of symlinking ignored
1545
+ * artifacts from the main worktree — for repos where sharing `node_modules`
1546
+ * or a virtualenv is wrong.
1547
+ */
1548
+ worktreeSetupCommand?: string;
1549
+ /**
1550
+ * Repositories of the repo group listed by hand, relative to the workspace
1551
+ * (ADR-0014). When non-empty the group is exactly these, replacing the
1552
+ * repositories auto-detected directly inside the folder; needed for ones
1553
+ * deeper than that, which are never auto-detected.
1554
+ */
1555
+ workspaceRepos: string[];
1556
+ /**
1557
+ * Extra paths or globs, relative to each repo root, linked from the real repo
1558
+ * into its task worktree where they exist — gitignored local state such as
1559
+ * `*.tfstate` that a task must use, not a copy of.
1560
+ */
1561
+ worktreeLinks: string[];
1562
+ /**
1563
+ * How many conflict repairs one task may go through before its conflict is
1564
+ * left for a person (ADR-0015); 0 turns repair off.
1565
+ */
1566
+ conflictRepairAttempts: number;
1567
+ /**
1568
+ * What to do when planner research reaches outside its default envelope — an
1569
+ * out-of-workspace path, or a shell command beyond the auto-allowed read-only
1570
+ * set. `ask` prompts the user (and denies where no surface can prompt, such as
1571
+ * headless runs); `allow` and `deny` skip the prompt entirely.
1572
+ */
1573
+ approvalMode: ApprovalMode;
1574
+ /** Scopes granted up front, so CI and power users never see a prompt. Trailing `*` matches by prefix. */
1575
+ approvalPreApproved: string[];
1576
+ /** Get the base URL for an OpenAI-compatible provider. */
1577
+ getProviderBaseUrl(provider: AiProvider): string;
1578
+ /** Get the API key for a provider. */
1579
+ getProviderApiKey(provider: AiProvider): string;
1580
+ /**
1581
+ * Push the canonical provider routing lists in (sole producer: ModelResolver).
1582
+ * Config consumes them when resolving a chosen model id to its serving API.
1583
+ */
1584
+ setProviderModelLists(lists: ProviderModelLists): void;
1585
+ }
1586
+ declare function enabledRunners(cfg: IConfig): RunnerId[];
1587
+
1588
+ /** True when a name belongs to a built-in runner and is therefore not installable. */
1589
+ declare function isReservedRunnerName(name: string): boolean;
1590
+ /** Clone seam: takes a validated URL and a destination, or throws. */
1591
+ type PluginCloneFn = (url: string, destDir: string) => void;
1592
+ declare class RunnerRegistry {
1593
+ private plugins;
1594
+ private store;
1595
+ private clone;
1596
+ constructor(store?: IPluginStore, clone?: PluginCloneFn);
1597
+ private loadBuiltins;
1598
+ loadUserPlugins(): void;
1599
+ get(id: string): PluginEntry | undefined;
1600
+ getManifest(id: string): RunnerPluginManifest | undefined;
1601
+ list(): PluginEntry[];
1602
+ listEnabled(config: IConfig): PluginEntry[];
1603
+ listEnabledIds(config: IConfig): string[];
1604
+ isBuiltIn(id: string): boolean;
1605
+ installFromPath(sourcePath: string): RunnerPluginManifest;
1606
+ installFromGit(url: string): RunnerPluginManifest;
1607
+ /**
1608
+ * The single destination-building step both install routes share: the name is
1609
+ * constrained to a plain segment and the resolved destination is asserted to
1610
+ * be inside the plugins directory before anything is copied.
1611
+ */
1612
+ private registerInstalled;
1613
+ remove(name: string): void;
1614
+ createSkeleton(name: string, outputDir: string): string;
1615
+ }
1616
+
1617
+ interface ITerminalSession {
1618
+ id: string;
1619
+ taskId: string;
1620
+ onOutput(callback: (text: string) => void): void;
1621
+ onExit(callback: (code: number) => void): void;
1622
+ kill(): void;
1623
+ getOutput(): string;
1624
+ write(text: string): void;
1625
+ /**
1626
+ * True when the session runs the agent as a raw-mode TUI (a real PTY for the
1627
+ * VS Code terminal, a tmux window). Such a surface submits an input line on
1628
+ * the Enter keystroke (`\r`), so a synchronized resume token terminated with
1629
+ * `\n` only types the line and never sends it. A line-oriented piped session
1630
+ * (`defaultInteractive = false`) leaves this false and accepts `\n`.
1631
+ */
1632
+ readonly interactive?: boolean;
1633
+ /**
1634
+ * Optional transport-level control channel: PTY resize requests for a session
1635
+ * whose runner renders a TUI. Absent on transports without a resizable PTY
1636
+ * (a plain piped subprocess); surfaces must feature-detect before calling.
1637
+ */
1638
+ writeControl?(text: string): void;
1639
+ }
1640
+ /**
1641
+ * How Ordewell drives a task's runner (ADR-0018): through its screen and
1642
+ * keyboard, or through its programmatic protocol.
1643
+ */
1644
+ type RunnerTransport = 'terminal' | 'structured';
1645
+ declare function isRunnerTransport(value: unknown): value is RunnerTransport;
1646
+ /** How a structured turn ended. `failed` carries the agent's own words in the preceding `error` event. */
1647
+ type StructuredTurnEnd = 'completed' | 'interrupted' | 'failed';
1648
+ /**
1649
+ * One normalized event from a structured task (ADR-0018, O1b): the adapter's
1650
+ * events, with the turn made explicit at both ends and the message queue (M1)
1651
+ * alongside. Subagent work carries its `subagentId`. The source for the
1652
+ * full-fidelity task log, never for verdicts.
1653
+ */
1654
+ type StructuredEvent = Exclude<AgentEvent, {
1655
+ type: 'turn_end';
1656
+ } | {
1657
+ type: 'permission_cancelled';
1658
+ }>
1659
+ /** `text` is the user message the turn answers; `messageId` is set when it had waited in the queue. */
1660
+ | {
1661
+ type: 'turn_start';
1662
+ text: string;
1663
+ messageId?: string;
1664
+ } | {
1665
+ type: 'turn_end';
1666
+ reason: StructuredTurnEnd;
1667
+ } | {
1668
+ type: 'message_queued';
1669
+ messageId: string;
1670
+ text: string;
1671
+ } | {
1672
+ type: 'message_removed';
1673
+ messageId: string;
1674
+ }
1675
+ /** An open `permission_request` was answered, by whoever answered it (ADR-0018, A1). */
1676
+ | {
1677
+ type: 'permission_decided';
1678
+ id: string;
1679
+ decision: ApprovalDecision;
1680
+ }
1681
+ /** An open `permission_request` can no longer be answered: the runner withdrew it, or its process is gone. */
1682
+ | {
1683
+ type: 'permission_withdrawn';
1684
+ id: string;
1685
+ };
1686
+ interface QueuedTaskMessage {
1687
+ id: string;
1688
+ text: string;
1689
+ }
1690
+ /**
1691
+ * What a session driven over its runner's protocol can do that a terminal
1692
+ * cannot (ADR-0018, S2). Optional: callers feature-detect it with
1693
+ * {@link isStructuredSession}, and code that does not look behaves as it did.
1694
+ */
1695
+ interface StructuredSessionCapability {
1696
+ readonly transport: 'structured';
1697
+ /** `working` while a turn runs; `idle` between turns, waiting for a message. */
1698
+ turnState(): 'working' | 'idle';
1699
+ onTurnEnd(listener: (reason: StructuredTurnEnd) => void): void;
1700
+ onEvent(listener: (event: StructuredEvent) => void): void;
1701
+ /**
1702
+ * Queue a user message, delivered when the current turn ends — or at once
1703
+ * when idle. Returns its id, for {@link removeQueued}.
1704
+ */
1705
+ sendMessage(text: string): string;
1706
+ /** Take a message back before it is delivered. False when it already was. */
1707
+ removeQueued(id: string): boolean;
1708
+ /** Messages waiting for the current turn to end, oldest first. */
1709
+ queued(): QueuedTaskMessage[];
1710
+ /**
1711
+ * Stop the running turn, keeping the session: a soft interrupt first, then —
1712
+ * if the runner does not answer in time — kill and resume. Either way the
1713
+ * turn ends `interrupted`. Resolves once it has.
1714
+ */
1715
+ interrupt(): Promise<void>;
1716
+ /** The runner's own session id once announced — what a continue resumes (ADR-0018, K1). */
1717
+ nativeSessionId(): string | null;
1718
+ /**
1719
+ * Answer a `permission_request` this session emitted, by its event id. False
1720
+ * when it is no longer open — answered, withdrawn, or never asked.
1721
+ */
1722
+ answerPermission(id: string, decision: ApprovalDecision): boolean;
1723
+ }
1724
+ declare function isStructuredSession(session: ITerminalSession): session is ITerminalSession & StructuredSessionCapability;
1725
+
1726
+ interface ITerminalRunner {
1727
+ spawn(opts: {
1728
+ taskId: string;
1729
+ runner: string;
1730
+ prompt: string;
1731
+ modelId?: string;
1732
+ thinkingEffort?: string;
1733
+ modelVariants?: string[];
1734
+ mode?: string;
1735
+ headless?: boolean;
1736
+ cwd: string;
1737
+ registry?: RunnerRegistry;
1738
+ /** Task order and title — surfaces use these to label task_started/output events. */
1739
+ order?: number;
1740
+ title?: string;
1741
+ /**
1742
+ * The owning plan session. Task ids are only unique within one plan, so
1743
+ * transports that key OS resources by task (tmux windows, log files) need
1744
+ * this to keep two plans' identically named tasks apart.
1745
+ */
1746
+ planSessionId?: string;
1747
+ /**
1748
+ * The workspace's own variables (ADR-0016), under the runner's: a
1749
+ * manifest's env still wins over them.
1750
+ */
1751
+ env?: Record<string, string>;
1752
+ /**
1753
+ * The transport the plan asks for (ADR-0018, S1). A router decides per
1754
+ * task whether the runner can honour it; any other runner ignores it.
1755
+ */
1756
+ transport?: RunnerTransport;
1757
+ /**
1758
+ * The runner's own session to continue in (ADR-0018, K1). Only the
1759
+ * structured transport can honour it; a terminal session comes back fresh,
1760
+ * which is why a continue refuses one.
1761
+ */
1762
+ resumeSessionId?: string;
1763
+ }): Promise<ITerminalSession>;
1764
+ stop(sessionId: string): void;
1765
+ stopAll(): void;
1766
+ activeCount: number;
1767
+ }
1768
+
1769
+ interface UserStep {
1770
+ order: number;
1771
+ instruction: string;
1772
+ completed: boolean;
1773
+ }
1774
+ /** One deterministic signal gathered while verifying a completed task. */
1775
+ interface VerificationCheck {
1776
+ name: 'exit_code' | 'completion_marker' | 'manual';
1777
+ passed: boolean;
1778
+ /** A check that did not apply. Skipped checks don't affect the verdict. */
1779
+ skipped: boolean;
1780
+ detail: string;
1781
+ }
1782
+ /** Evidence-based verdict for a completed task. Single end-to-end outcome produced by verification. */
1783
+ interface Verdict {
1784
+ outcome: 'pass' | 'fail';
1785
+ reason: string;
1786
+ checks: VerificationCheck[];
1787
+ decidedAt: string;
1788
+ }
1789
+ interface TaskOutputSummary {
1790
+ reviewReason: string;
1791
+ logTail: string;
1792
+ capturedAt: string;
1793
+ }
1794
+ type TaskType = 'ai' | 'user';
1795
+ type TaskStatus = 'pending' | 'approved' | 'in_progress' | 'completed' | 'failed' | 'blocked' | 'awaiting_user';
1796
+ type TaskMode = string;
1797
+ /**
1798
+ * Why an `awaiting_user` task waits (ADR-0018, W1): a structured turn that
1799
+ * ended without the done marker, a checkpoint question, or work that did not
1800
+ * land. Saved, so no surface has to guess it from whether an attempt is live.
1801
+ */
1802
+ type AwaitingReason = 'input' | 'checkpoint' | 'conflict';
1803
+ declare function isAwaitingReason(value: unknown): value is AwaitingReason;
1804
+ interface TaskModelAssignment {
1805
+ modelId: string;
1806
+ modelLabel: string;
1807
+ thinkingEffort?: string;
1808
+ /**
1809
+ * All variant ids the model offered when this assignment was made. Carried
1810
+ * on the assignment because runners need it at spawn time (opencode's TUI
1811
+ * only honors an assigned variant when the others are config-disabled) and
1812
+ * the discovery catalog isn't available there.
1813
+ */
1814
+ availableVariants?: string[];
1815
+ }
1816
+ type RunnerId = string;
1817
+ /**
1818
+ * How a task's latest attempt was driven (ADR-0018). Recorded only when its
1819
+ * plan asked for the structured transport, so a terminal plan's tasks carry
1820
+ * nothing new.
1821
+ */
1822
+ interface TaskTransport {
1823
+ kind: RunnerTransport;
1824
+ /** Why a plan that asked for structured ran this task on the terminal — never a silent downgrade (S3). */
1825
+ fallback?: string;
1826
+ /** The runner's own session id of a structured attempt, once it ends: what a continue resumes (K1). */
1827
+ nativeSessionId?: string;
1828
+ }
1829
+ interface Task {
1830
+ id: string;
1831
+ order: number;
1832
+ title: string;
1833
+ description: string;
1834
+ type: TaskType;
1835
+ status: TaskStatus;
1836
+ dependencies: string[];
1837
+ prompt?: string;
1838
+ userSteps?: UserStep[];
1839
+ subtasks: Task[];
1840
+ verdict?: Verdict;
1841
+ outputSummary?: TaskOutputSummary;
1842
+ assignedModel?: TaskModelAssignment;
1843
+ assignedRunner: RunnerId;
1844
+ thinkingEffort?: string;
1845
+ taskMode?: TaskMode;
1846
+ completionMarker: string;
1847
+ autonomy?: 'AFK' | 'HITL';
1848
+ sliceType?: 'HITL' | 'AFK';
1849
+ userStoriesCovered?: string[];
1850
+ transport?: TaskTransport;
1851
+ /** Set only while `status` is `awaiting_user`, and not always then — a usage-limit pause has none. */
1852
+ awaitingReason?: AwaitingReason;
1853
+ }
1854
+ interface DiscoveredMode {
1855
+ id: string;
1856
+ label: string;
1857
+ description: string;
1858
+ }
1859
+ type ResearchToolType = 'read_file' | 'read_files' | 'glob' | 'grep' | 'find_symbol' | 'list_dir' | 'bash' | 'fetch' | 'web_search' | 'spawn_research_agent'
1860
+ /**
1861
+ * A tool belonging to a harness planner's own toolbox (ADR-0009) that has no
1862
+ * Ordewell equivalent — Edit, WebFetch, TodoWrite, whatever a coding agent
1863
+ * ships next. The real name travels in `toolLabel` rather than being
1864
+ * relabelled as a tool it is not; the union stays closed so the
1865
+ * exhaustiveness checks in every surface's icon/label switch survive.
1866
+ */
1867
+ | 'agent_tool';
1868
+ /**
1869
+ * What happened when a research tool call ran, for honest per-surface
1870
+ * rendering. The broadcast seam carries this on every `research_step_done` so
1871
+ * surfaces do not have to pattern-match refusal text to tell a refused `rm`
1872
+ * from a successful `rm` — the old render path flipped a `✓` for both.
1873
+ */
1874
+ type ResearchStepOutcome = 'success' | 'failure' | 'refused' | 'denied' | 'not_executed';
1875
+ interface ResearchStep {
1876
+ id: string;
1877
+ tool: ResearchToolType;
1878
+ /** The tool's own name when it came from a harness planner — always set for `agent_tool`. */
1879
+ toolLabel?: string;
1880
+ args: string;
1881
+ result: string;
1882
+ success: boolean;
1883
+ outcome: ResearchStepOutcome;
1884
+ /** The model's tool_call id, so a surface can match `tool_result` to the
1885
+ * pending `tool_call` it announced — robust under parallel same-tool rounds. */
1886
+ toolCallId?: string;
1887
+ /** The research subagent that ran the call, so a reload regroups it under that subagent. */
1888
+ subagentId?: string;
1889
+ timestamp: string;
1890
+ thinkingText?: string;
1891
+ }
1892
+ interface UserPromptEntry {
1893
+ id: string;
1894
+ type: 'user_prompt' | 'system';
1895
+ content: string;
1896
+ timestamp: string;
1897
+ }
1898
+ type SubagentOutcome = 'done' | 'failed' | 'stopped';
1899
+ /**
1900
+ * One subagent's whole run, logged when it finishes: what it was asked, how it
1901
+ * ended and what it reported. Its steps stay separate entries carrying the same
1902
+ * `subagentId`, so an older reader that knows only steps still shows them.
1903
+ */
1904
+ interface SubagentLogEntry {
1905
+ id: string;
1906
+ type: 'subagent';
1907
+ subagentId: string;
1908
+ brief: string;
1909
+ model?: string;
1910
+ outcome: SubagentOutcome;
1911
+ digest: string;
1912
+ usage?: UsageTotals;
1913
+ timestamp: string;
1914
+ }
1915
+ type ResearchLogEntry = ResearchStep | UserPromptEntry | SubagentLogEntry;
1916
+ interface ResearchProgress {
1917
+ type: 'thinking' | 'tool_call' | 'tool_result' | 'plan_token' | 'interrupted' | 'liveness' | 'text_delta' | 'text_retracted' | 'usage' | 'subagent_started' | 'subagent_finished';
1918
+ /** Minted by whoever runs the turn and passed through untouched; absent outside a turn. */
1919
+ turnId?: string;
1920
+ /** One continuous run of model text — text before a tool call is its own segment. */
1921
+ segmentId?: string;
1922
+ text?: string;
1923
+ tool?: string;
1924
+ /** Harness planners (ADR-0009): the agent's own name for a tool Ordewell has no member for. */
1925
+ toolLabel?: string;
1926
+ toolArgs?: string;
1927
+ toolResult?: string;
1928
+ planToken?: string;
1929
+ step?: ResearchStep;
1930
+ /** The model's tool_call id, threaded on tool_call and tool_result so a
1931
+ * surface can match the result to its pending call — robust under parallel
1932
+ * same-tool rounds where LIFO-by-name matching mislabels summaries. */
1933
+ toolCallId?: string;
1934
+ /** Present when this event originates from (or reports on) one spawned research subagent (issue #34). */
1935
+ subagentId?: string;
1936
+ record?: UsageRecord;
1937
+ brief?: string;
1938
+ model?: string;
1939
+ outcome?: SubagentOutcome;
1940
+ digest?: string;
1941
+ usage?: UsageTotals;
1942
+ }
1943
+ interface ThinkingBlock {
1944
+ id: string;
1945
+ text: string;
1946
+ }
1947
+ interface StreamThinkingEvent {
1948
+ type: 'thinking';
1949
+ block: ThinkingBlock;
1950
+ }
1951
+ interface StreamStepEvent {
1952
+ type: 'step';
1953
+ step: ResearchStep;
1954
+ }
1955
+ type StreamEvent = StreamThinkingEvent | StreamStepEvent;
1956
+ interface DiscoveredModel {
1957
+ modelId: string;
1958
+ modelLabel: string;
1959
+ runnerProvider?: string;
1960
+ /**
1961
+ * Human-facing provider name as the runner itself reports it (e.g.
1962
+ * "OpenCode Zen" for `runnerProvider: 'opencode'`). Populated from the
1963
+ * runner's own provider catalog when available; when absent the UI derives a
1964
+ * label from `runnerProvider` by title-casing.
1965
+ */
1966
+ runnerProviderLabel?: string;
1967
+ /**
1968
+ * The runner whose catalog listed this model. Stamped once, at the single
1969
+ * `ModelDiscovery.discover` choke point, so a flat cross-runner list can
1970
+ * still say where each entry came from — `runnerProvider` alone cannot:
1971
+ * OpenCode reports most of its catalog as `openrouter`, which names the
1972
+ * serving backend, not the agent Ordewell would spawn.
1973
+ */
1974
+ runnerId?: string;
1975
+ /** The runner's display name (`OpenCode`), from its manifest. */
1976
+ runnerLabel?: string;
1977
+ variants: {
1978
+ id: string;
1979
+ label: string;
1980
+ }[];
1981
+ /**
1982
+ * The model's context window when the runner or catalog reports it (#49).
1983
+ * Read by the planner-model lookup so context fill can be shown; absent when
1984
+ * unknown rather than defaulted to zero.
1985
+ */
1986
+ contextWindow?: number;
1987
+ }
1988
+ type PlanStatus = 'draft' | 'approved' | 'rejected' | 'running' | 'completed';
1989
+ /**
1990
+ * One entry of the planner's persisted dialogue (ADR-0002). The single source
1991
+ * of truth for both UI redisplay and conversational context. Tool-call results
1992
+ * are NOT stored here — they live in the AI service's tool-use history;
1993
+ * `researchLog` remains the persisted tool trace for the UI.
1994
+ */
1995
+ interface ConversationMessage {
1996
+ role: 'user' | 'assistant';
1997
+ content: string;
1998
+ timestamp: string;
1999
+ /**
2000
+ * Timeline marker: 'plan_generated' records the point in the dialogue where
2001
+ * the plan was committed (the UI anchors the plan card there on restore);
2002
+ * 'system' is a host-injected notice; 'compaction' is the summary a
2003
+ * user-triggered compaction left in place of the earlier messages — always
2004
+ * the transcript's first entry. Absent for ordinary chat turns, so
2005
+ * sessions saved before markers existed degrade gracefully.
2006
+ */
2007
+ kind?: 'plan_generated' | 'system' | 'compaction';
2008
+ }
2009
+ interface QueuedMessage {
2010
+ id: string;
2011
+ text: string;
2012
+ timestamp: string;
2013
+ }
2014
+ interface PlanModificationWarnings {
2015
+ deletedCompleted: string[];
2016
+ changedCompleted: string[];
2017
+ deletedInProgress: string[];
2018
+ modifiedInProgress: string[];
2019
+ brokenDependencies: string[];
2020
+ }
2021
+ declare function emptyWarnings(): PlanModificationWarnings;
2022
+ interface LegacyPlanState {
2023
+ tasks: Task[];
2024
+ generatedAt: string;
2025
+ status: PlanStatus;
2026
+ runners: RunnerId[];
2027
+ lastUpdated: string;
2028
+ researchLog?: ResearchLogEntry[];
2029
+ /** The planner dialogue — user messages and assistant messages, in order (ADR-0002). */
2030
+ conversationHistory?: ConversationMessage[];
2031
+ /** Full markdown PRD once written by the planner (PRD mode), also saved to .scratch/<slug>/PRD.md. */
2032
+ prdMarkdown?: string;
2033
+ /** Follow-ups queued while tasks execute — applied as plan modifications between batches. */
2034
+ queuedMessages?: QueuedMessage[];
2035
+ /**
2036
+ * The plan's isolation run (ADR-0013), written from the orchestrator at
2037
+ * persist time and read back only when a saved plan is adopted. It names
2038
+ * branches and worktrees that belong to this plan alone: a fork of the plan
2039
+ * must leave it behind rather than share it.
2040
+ */
2041
+ isolation?: PlanIsolation;
2042
+ /**
2043
+ * The `runnerTransport` setting as the plan's latest run copied it when it
2044
+ * started (ADR-0018, S1): the plan, not the live setting, says what runs.
2045
+ */
2046
+ runnerTransport?: RunnerTransport;
2047
+ /** Kept so a reopened session shows the same token line (#49). */
2048
+ plannerUsage?: PlannerUsage;
2049
+ }
2050
+ interface Message {
2051
+ id: string;
2052
+ role: 'user' | 'planner' | 'system';
2053
+ content: string;
2054
+ timestamp: number;
2055
+ }
2056
+ interface TaskSnapshot extends Task {
2057
+ completedAt: number;
2058
+ verdict?: Verdict;
2059
+ retryCount: number;
2060
+ finalized: boolean;
2061
+ }
2062
+ type PlanState = {
2063
+ phase: 'planning';
2064
+ history: Message[];
2065
+ message: string;
2066
+ pendingTasks: Task[];
2067
+ } | {
2068
+ phase: 'executing';
2069
+ history: Message[];
2070
+ message: string;
2071
+ executionLog: TaskSnapshot[];
2072
+ pendingTasks: Task[];
2073
+ goal: string;
2074
+ runners: string[];
2075
+ status: PlanStatus;
2076
+ };
2077
+ declare function migratePlanState(raw: unknown): PlanState;
2078
+ declare function migrateLegacyPlan(legacy: LegacyPlanState): PlanState;
2079
+
2080
+ declare function createTask(overrides?: Partial<Task>): Task;
2081
+ declare function createEmptyPlan(): LegacyPlanState;
2082
+ declare function flattenTasks(tasks: readonly Task[]): Task[];
2083
+ /** A flattened task with the parent it hangs under, null for a top-level task. */
2084
+ interface TaskWithParent {
2085
+ task: Task;
2086
+ parent: Task | null;
2087
+ }
2088
+ declare function flattenTasksWithParents(tasks: readonly Task[]): TaskWithParent[];
2089
+ declare function migrateTask(task: Record<string, unknown>): Task;
2090
+ declare function addTaskToPlan(tasks: readonly Task[], partial: Partial<Task>): Task[];
2091
+ declare function removeTaskFromPlan(tasks: readonly Task[], taskId: string): Task[];
2092
+ declare function updateTaskInPlan(tasks: readonly Task[], taskId: string, changes: Partial<Task>): Task[];
2093
+ declare function renumberTasks(tasks: readonly Task[]): Task[];
2094
+ /**
2095
+ * Lay a planner-written task list over the plan it rewrites without letting it
2096
+ * change execution state. A planner restates tasks; it never witnessed one run,
2097
+ * so the status it writes is not evidence. A settled task is kept exactly as
2098
+ * it stands wherever the rewrite names it, and put back beside its old
2099
+ * neighbour where the rewrite leaves it out. Every other task keeps the status
2100
+ * it had; a task the rewrite adds starts pending.
2101
+ */
2102
+ declare function keepExecutionState(current: readonly Task[], rewrite: Task[]): Task[];
2103
+ declare function validateModifiedPlan(original: Task[], modified: Task[]): PlanModificationWarnings;
2104
+ interface ActiveTaskSession {
2105
+ id: string;
2106
+ taskId: string;
2107
+ }
2108
+ interface ValidationResult {
2109
+ valid: boolean;
2110
+ errors: string[];
2111
+ }
2112
+ interface ValidationContext {
2113
+ executionLog: TaskSnapshot[];
2114
+ oldPending: Task[];
2115
+ newPending: Task[];
2116
+ activeSessions: Map<string, ActiveTaskSession>;
2117
+ }
2118
+ type ValidationCheck = (ctx: ValidationContext) => ValidationResult;
2119
+ declare function warningsText(w: PlanModificationWarnings): string | null;
2120
+
2121
+ export { type IsolationRun as $, AbstractRunner as A, type BlockingPrompt as B, CMD_EXE_MAX_COMMAND_LINE as C, DENY_ALL as D, EmbeddedNewlineError as E, type FetchAllProviderModelsOptions as F, HeadlessSession as G, HeadlessRunner as H, type IApproval as I, type IConfig as J, type IPluginStore as K, type ITerminalRunner as L, type ITerminalSession as M, type IWorktreeIsolation as N, type IntegrationDisposal as O, type IsolationAvailability as P, type IsolationHandoff as Q, type IsolationHandoffRepo as R, type IsolationInactiveReason as S, type IsolationLandedTask as T, type IsolationLanding as U, type IsolationMergeBlock as V, type IsolationMergeBlockReason as W, type IsolationMergeResult as X, type IsolationOutcome as Y, type IsolationPruneResult as Z, type IsolationRepo as _, AbstractTerminalSession as a, type TaskOutputSummary as a$, type IsolationTaskRecord as a0, type IsolationTaskRepo as a1, type IsolationTaskStatus as a2, type IsolationView as a3, type LaunchDeps as a4, type LaunchPlan as a5, type LegacyPlanState as a6, LineBuffer as a7, type Message as a8, ModelCatalog as a9, type ResearchLogEntry as aA, type ResearchProgress as aB, type ResearchStep as aC, type ResearchStepOutcome as aD, type ResearchToolType as aE, type ResolveContext as aF, type RunnerId as aG, type RunnerInvocation as aH, type RunnerPluginManifest as aI, RunnerRegistry as aJ, type RunnerSpawnOptions as aK, type RunnerTransport as aL, type StreamEvent as aM, type StreamStepEvent as aN, type StreamThinkingEvent as aO, type StructuredEvent as aP, type StructuredSessionCapability as aQ, type StructuredTurnEnd as aR, type SubagentLogEntry as aS, type SubagentOutcome as aT, type Task as aU, type TaskIsolation as aV, type TaskIsolationState as aW, type TaskMode as aX, type TaskModeAgentAdapter as aY, TaskModeUnsupportedError as aZ, type TaskModelAssignment as a_, type ModelShortcut as aa, ORCHESTRATOR_SHORTCUTS as ab, type OrchestratorOption as ac, type PlanIsolation as ad, type PlanModificationWarnings as ae, type PlanState as af, type PlanStatus as ag, type PlannerStartOptions as ah, type PlannerUsage as ai, type PluginCloneFn as aj, type PluginEntry as ak, type PluginFeatures as al, type PluginMode as am, type PluginModelDiscovery as an, type PluginRunnerDef as ao, type PreparedLaunch as ap, type PreparedTask as aq, type ProviderCredentialSource as ar, type ProviderModelLists as as, type ProviderModelsResult as at, type PtySize as au, type PtyWrapOptions as av, type QueuedMessage as aw, type QueuedTaskMessage as ax, type RepairEvidence as ay, type RepoGroupLayout as az, type ActiveTaskSession as b, type TaskRunnerFlags as b0, type TaskSnapshot as b1, type TaskStartOptions as b2, type TaskStatus as b3, type TaskTransport as b4, type TaskType as b5, type TaskWithParent as b6, type ThinkingBlock as b7, type UsageLine as b8, type UsageRecord as b9, isReservedRunnerName as bA, isRunnerApproval as bB, isRunnerTransport as bC, isStructuredSession as bD, keepExecutionState as bE, knownModelId as bF, migrateLegacyPlan as bG, migratePlanState as bH, migrateTask as bI, partedPromptUsage as bJ, planDirectLaunch as bK, planShellLaunch as bL, plannerContextFill as bM, posixShellQuote as bN, removeTaskFromPlan as bO, renumberTasks as bP, resolveModelShortcut as bQ, resolveProvider as bR, stripAnsi as bS, toApprovalDecision as bT, toOrchestratorOptions as bU, updateTaskInPlan as bV, usageLine as bW, validateModifiedPlan as bX, warningsText as bY, windowsCommandLine as bZ, wrapWithPty as b_, type UsageTotals as ba, type UserPromptEntry as bb, type UserStep as bc, type ValidationCheck as bd, type ValidationContext as be, type ValidationResult as bf, type Verdict as bg, type VerificationCheck as bh, WINDOWS_MAX_COMMAND_LINE as bi, addPlannerUsage as bj, addTaskToPlan as bk, addUsage as bl, approvalScopes as bm, buildShellInvocation as bn, collectProviderCredentials as bo, createEmptyPlan as bp, createTask as bq, emptyWarnings as br, enabledRunners as bs, fetchAllProviderModels as bt, flattenTasks as bu, flattenTasksWithParents as bv, isAwaitingReason as bw, isExecutableResolved as bx, isGranted as by, isMeasured as bz, type AgentAdapter as c, type AgentAdapterFactory as d, type AgentEvent as e, type AgentProcessDeps as f, type AgentStartOptions as g, type AiProvider as h, type AllProviderModels as i, type ApprovalAnswer as j, type ApprovalDecision as k, type ApprovalKind as l, type ApprovalMode as m, ApprovalPolicy as n, type ApprovalPolicyOptions as o, type ApprovalRequest as p, type ApprovalSource as q, type AwaitingReason as r, type CatalogModel as s, CommandLineTooLongError as t, type ConversationMessage as u, type DiscoveredMode as v, type DiscoveredModel as w, type DiscoveryCommand as x, ExecutableNotFoundError as y, type HeadlessRunnerDeps as z };