@ordewell/core 0.10.9 → 0.10.11

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 (40) hide show
  1. package/dist/{IFileSystem-C9W5mRYA.d.mts → IFileSystem-1PqRCjhu.d.mts} +21 -3
  2. package/dist/{IFileSystem-B8qRNC_6.d.ts → IFileSystem-lTRL_G9Z.d.ts} +21 -3
  3. package/dist/{ModeResolver-C1PN5FYG.d.mts → ModeResolver-6TQXVsde.d.mts} +1 -1
  4. package/dist/{ModeResolver-CaPnoU8N.d.ts → ModeResolver-CoJAJD-f.d.ts} +1 -1
  5. package/dist/{Task-hFfRS9rN.d.mts → Task-CfBM0wkV.d.mts} +94 -21
  6. package/dist/{Task-hFfRS9rN.d.ts → Task-CfBM0wkV.d.ts} +94 -21
  7. package/dist/{chunk-H7QX32BH.mjs → chunk-24EL4Z2W.mjs} +2 -2
  8. package/dist/{chunk-O6LQU3W6.mjs → chunk-ESKK5I4F.mjs} +138 -21
  9. package/dist/chunk-ESKK5I4F.mjs.map +1 -0
  10. package/dist/{chunk-LTHKFBKM.mjs → chunk-KWS3VEER.mjs} +3 -3
  11. package/dist/{chunk-EEE2GBLG.mjs → chunk-PFH7WFIB.mjs} +1 -1
  12. package/dist/chunk-PFH7WFIB.mjs.map +1 -0
  13. package/dist/index.d.mts +129 -20
  14. package/dist/index.d.ts +129 -20
  15. package/dist/index.js +556 -92
  16. package/dist/index.js.map +1 -1
  17. package/dist/index.mjs +432 -76
  18. package/dist/index.mjs.map +1 -1
  19. package/dist/parsing.d.mts +2 -2
  20. package/dist/parsing.d.ts +2 -2
  21. package/dist/parsing.js.map +1 -1
  22. package/dist/parsing.mjs +3 -3
  23. package/dist/plan-utils.d.mts +4 -4
  24. package/dist/plan-utils.d.ts +4 -4
  25. package/dist/plan-utils.js +144 -18
  26. package/dist/plan-utils.js.map +1 -1
  27. package/dist/plan-utils.mjs +22 -4
  28. package/dist/{runSettingsText-CGKX3aeV.d.ts → runSettingsText-C5uv2axI.d.ts} +29 -18
  29. package/dist/{runSettingsText-rLoYQlUH.d.mts → runSettingsText-Jb_efnI4.d.mts} +29 -18
  30. package/dist/testing.d.mts +12 -3
  31. package/dist/testing.d.ts +12 -3
  32. package/dist/testing.js +16 -1
  33. package/dist/testing.js.map +1 -1
  34. package/dist/testing.mjs +17 -2
  35. package/dist/testing.mjs.map +1 -1
  36. package/package.json +1 -1
  37. package/dist/chunk-EEE2GBLG.mjs.map +0 -1
  38. package/dist/chunk-O6LQU3W6.mjs.map +0 -1
  39. /package/dist/{chunk-H7QX32BH.mjs.map → chunk-24EL4Z2W.mjs.map} +0 -0
  40. /package/dist/{chunk-LTHKFBKM.mjs.map → chunk-KWS3VEER.mjs.map} +0 -0
@@ -7,10 +7,10 @@ import {
7
7
  plannedTask,
8
8
  stripTrailingCommas,
9
9
  taskWhere
10
- } from "./chunk-H7QX32BH.mjs";
10
+ } from "./chunk-24EL4Z2W.mjs";
11
11
  import {
12
12
  flattenTasksWithParents
13
- } from "./chunk-EEE2GBLG.mjs";
13
+ } from "./chunk-PFH7WFIB.mjs";
14
14
 
15
15
  // src/services/PlanValidator.ts
16
16
  function parsePlanJson(raw, runners, runnerModes, autonomousDefault = true) {
@@ -94,4 +94,4 @@ export {
94
94
  validatePlanTasks,
95
95
  looksLikePlanAttempt
96
96
  };
97
- //# sourceMappingURL=chunk-LTHKFBKM.mjs.map
97
+ //# sourceMappingURL=chunk-KWS3VEER.mjs.map
@@ -476,4 +476,4 @@ export {
476
476
  stampOrigin,
477
477
  keepExecutionState
478
478
  };
479
- //# sourceMappingURL=chunk-EEE2GBLG.mjs.map
479
+ //# sourceMappingURL=chunk-PFH7WFIB.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/conversation/skillTokens.ts","../src/services/PlanTree.ts","../src/services/TaskRefs.ts","../src/models/Task.ts"],"sourcesContent":["/** A name a skill can have, lower-cased: the one pattern for a `/name` token and for a skill folder. */\nexport const SKILL_NAME_PATTERN = '[a-z0-9][a-z0-9_-]*';\n\n/**\n * A `/skill-name` token anywhere in a message: whitespace (or string start)\n * before it, a skill name in any case, optional trailing punctuation that\n * isn't part of the name, then whitespace (or string end). The punctuation\n * group is what lets \"/grilling,\" name \"grilling\".\n */\nconst SKILL_TOKEN = new RegExp(`(^|\\\\s)\\\\/(${SKILL_NAME_PATTERN})([,.!?;:]*)(?=\\\\s|$)`, 'gi');\n\n/** Where a skill name is invoked: `start` is its `/`, `end` is just past the name, before any punctuation. */\nexport interface SkillToken {\n name: string;\n start: number;\n end: number;\n}\n\n/**\n * The first `/name` token for each name in `text`, names lower-cased. Only\n * the first counts because a skill loads once per message however often it is\n * named, so a later repeat is plain text.\n */\nexport function skillTokens(text: string): SkillToken[] {\n const tokens: SkillToken[] = [];\n const seen = new Set<string>();\n for (const match of text.matchAll(SKILL_TOKEN)) {\n const name = match[2].toLowerCase();\n if (seen.has(name)) continue;\n seen.add(name);\n const start = match.index + match[1].length;\n tokens.push({ name, start, end: start + 1 + match[2].length });\n }\n return tokens;\n}\n\n/** The tokens in a sent message that loaded one of `loaded` — what a surface highlights in the user's bubble. */\nexport function loadedSkillTokens(text: string, loaded: readonly string[]): SkillToken[] {\n return skillTokens(text).filter((t) => loaded.includes(t.name));\n}\n","/** Plan placement and dependency rules, shared with browser-bundled surfaces. */\nexport interface TreeTask<T> {\n id: string;\n order: number;\n title: string;\n subtasks?: readonly T[];\n}\n\nexport interface DependencyTask<T> extends TreeTask<T> {\n dependencies: readonly string[];\n}\n\nexport interface TaskPlacement<T> {\n task: T;\n parent?: T;\n ancestors: readonly T[];\n siblings: readonly T[];\n label: string;\n}\n\nexport function* walkPlan<T extends TreeTask<T>>(tasks: readonly T[]): Generator<TaskPlacement<T>> {\n function* walk(level: readonly T[], ancestors: readonly T[], parentLabel?: string): Generator<TaskPlacement<T>> {\n for (const task of level) {\n const label = parentLabel ? `${parentLabel}.${task.order}` : String(task.order);\n yield { task, parent: ancestors.at(-1), ancestors, siblings: level, label };\n yield* walk(task.subtasks ?? [], [...ancestors, task], label);\n }\n }\n yield* walk(tasks, []);\n}\n\nexport function taskPlacement<T extends TreeTask<T>>(tasks: readonly T[], id: string): TaskPlacement<T> | undefined {\n for (const row of walkPlan(tasks)) if (row.task.id === id) return row;\n return undefined;\n}\n\n/** Includes the root: deletion has to detach every edge into the removed tree. */\nexport function subtreeIds<T extends TreeTask<T>>(tasks: readonly T[], id: string): Set<string> {\n const found = taskPlacement(tasks, id);\n return new Set(found ? [...walkPlan([found.task])].map(({ task }) => task.id) : []);\n}\n\n/** Pickers offer earlier siblings; API validity is independent of display order. */\nexport function dependencyCandidates<T extends TreeTask<T>>(tasks: readonly T[], taskId?: string): T[] {\n if (!taskId) return [...tasks];\n const found = taskPlacement(tasks, taskId);\n return found ? found.siblings.filter((t) => t.order < found.task.order) : [];\n}\n\n/** The surviving tasks whose dependency lists a subtree removal will change. */\nexport function dependentsOf<T extends DependencyTask<T>>(tasks: readonly T[], taskId: string): T[] {\n const removed = subtreeIds(tasks, taskId);\n return [...walkPlan(tasks)].map(({ task }) => task)\n .filter((t) => !removed.has(t.id) && t.dependencies.some((id) => removed.has(id)));\n}\n\nexport interface DependencyCheck { ok: boolean; error?: string }\n\n/** Target restrictions, separate from cycles so a planner batch can check its final graph. */\nexport function dependencyTargetErrors<T extends TreeTask<T>>(\n tasks: readonly T[], taskId: string, dependencies: readonly string[],\n): string[] {\n const found = taskPlacement(tasks, taskId);\n if (!found) return ['Task not found'];\n const descendants = subtreeIds(tasks, taskId);\n const errors: string[] = [];\n for (const dep of dependencies) {\n if (dep === taskId) { errors.push(`\"${found.task.title}\" cannot depend on itself`); continue; }\n const target = taskPlacement(tasks, dep)?.task;\n if (!target) { errors.push(`Unknown dependency \"${dep}\"`); continue; }\n if (found.ancestors.some((t) => t.id === dep) || descendants.has(dep)) {\n errors.push(`\"${found.task.title}\" cannot depend on \"${target.title}\", its ancestor or descendant`);\n }\n }\n return errors;\n}\n\n/** The tasks on one dependency cycle, in dependency order, or null. */\nexport function findDependencyCycle<T extends DependencyTask<T>>(tasks: readonly T[]): T[] | null {\n const byId = new Map([...walkPlan(tasks)].map(({ task }) => [task.id, task]));\n const path: string[] = [];\n const done = new Set<string>();\n const visit = (id: string): string[] | null => {\n if (done.has(id)) return null;\n const at = path.indexOf(id);\n if (at >= 0) return path.slice(at);\n path.push(id);\n for (const dep of byId.get(id)?.dependencies ?? []) {\n const hit = visit(dep);\n if (hit) return hit;\n }\n path.pop();\n done.add(id);\n return null;\n };\n for (const id of byId.keys()) {\n const hit = visit(id);\n if (hit) return hit.map((key) => byId.get(key)!);\n }\n return null;\n}\n\nexport function canSetDependencies<T extends DependencyTask<T>>(\n tasks: readonly T[], taskId: string, dependencies: readonly string[],\n): DependencyCheck {\n const [error] = dependencyTargetErrors(tasks, taskId, dependencies);\n if (error) return { ok: false, error };\n const replace = (level: readonly T[]): T[] => level.map((t) => ({\n ...t,\n dependencies: t.id === taskId ? dependencies : t.dependencies,\n subtasks: replace(t.subtasks ?? []),\n }));\n const cycle = findDependencyCycle(replace(tasks));\n return cycle\n ? { ok: false, error: `Dependency cycle detected: ${[...cycle, cycle[0]].map((t) => `\"${t.title}\"`).join(' → ')}` }\n : { ok: true };\n}\n","import { taskPlacement, walkPlan, type TreeTask } from './PlanTree';\n\n/**\n * Task references: the one grammar for naming a task in a plan, both ways.\n * A label is rendered from a task's order under its parent (\"2\", \"2.1\"), and\n * a reference written by anyone — the planner, a tool call, a command — is\n * resolved back against the plan tree. Pure so a\n * browser-bundled surface can use it through `@ordewell/core/plan-utils`.\n */\n\n/** The shape a reference resolves over: the plan's task tree, or a surface's projection of it. */\nexport type RefTask<T> = TreeTask<T>;\n\n/**\n * The parent a label extends. A label is the full path (\"3.2.1\"), so a parent\n * below the top level carries the label it was itself reached by; without one\n * the parent's order stands for it, which is right for a top-level parent.\n */\nexport interface RefParent {\n order: number;\n label?: string;\n}\n\n/** Dotted path label for a task, e.g. \"2.1\" for the first subtask of task 2, \"2.1.3\" one level down. */\nexport function taskOrderLabel(task: { order: number }, parent?: RefParent): string {\n return parent ? `${parent.label ?? parent.order}.${task.order}` : String(task.order);\n}\n\n/** How a surface refers to a task in prose: \"#2\", or \"#2.1\" for a subtask. */\nexport function taskRef(task: { order: number }, parent?: RefParent): string {\n return `#${taskOrderLabel(task, parent)}`;\n}\n\n/** A task named in full, as a confirmation or a picker title does: \"#2 Deploy\". */\nexport function titledTaskRef(task: { order: number; title: string }, parent?: RefParent): string {\n return `${taskRef(task, parent)} ${task.title}`;\n}\n\n/** A task found in a plan tree, with its parent and the full path label its reference extends. */\nexport interface RefTaskMatch<T> {\n task: T;\n parent?: T;\n label: string;\n}\n\n/** The task a plan tree holds, by id, with its parent; undefined when the tree holds none. */\nexport function findTaskRef<T extends RefTask<T>>(tasks: readonly T[], id: string): RefTaskMatch<T> | undefined {\n return taskPlacement(tasks, id);\n}\n\n/**\n * The reference {@link taskRef} renders for the task a plan tree holds, by id\n * — its full path, dotted, for a subtask. Undefined when the tree holds no such task.\n */\nexport function taskRefOf<T extends RefTask<T>>(tasks: readonly T[], id: string): string | undefined {\n const found = findTaskRef(tasks, id);\n return found && `#${found.label}`;\n}\n\n/**\n * The reference and title {@link titledTaskRef} renders for the task a plan\n * tree holds, by id — its full path, dotted, for a subtask. Undefined when the\n * tree holds no such task.\n */\nexport function titledTaskRefOf<T extends RefTask<T>>(tasks: readonly T[], id: string): string | undefined {\n const found = findTaskRef(tasks, id);\n return found && `#${found.label} ${found.task.title}`;\n}\n\n/**\n * Resolve a written reference to a task at any depth: an id, then an order\n * label with or without \"#\" (\"#2\", \"2\", \"#2.1\"), then an exact title.\n *\n * An order label is read against the tree, never a flattened list: subtask\n * orders restart at 1 under each parent, so \"#2\" always means top-level task 2\n * and a subtask is reachable only by its dotted path (\"#2.1\", \"#2.1.3\").\n */\nexport function resolveTaskRef<T extends RefTask<T>>(tasks: readonly T[], ref: string | number): T | undefined {\n const s = String(ref).trim();\n if (!s) return undefined;\n for (const { task } of walkPlan(tasks)) if (task.id === s) return task;\n const label = s.startsWith('#') ? s.slice(1) : s;\n if (/^\\d+(\\.\\d+)*$/.test(label)) {\n let level: readonly T[] | undefined = tasks;\n let found: T | undefined;\n for (const order of label.split('.').map(Number)) {\n found = level?.find((t) => t.order === order);\n level = found?.subtasks;\n }\n return found;\n }\n for (const { task } of walkPlan(tasks)) if (task.title === s) return task;\n return undefined;\n}\n\n/**\n * A reference as the user types one: {@link resolveTaskRef}, then a unique\n * prefix of a task's id at any depth. Only the user's: a model's reference\n * that names no task is refused, never matched to the one task a fragment of\n * it happens to fit.\n */\nexport function resolveUserTaskRef<T extends RefTask<T>>(tasks: readonly T[], ref: string | number): T | undefined {\n const found = resolveTaskRef(tasks, ref);\n if (found) return found;\n const prefix = String(ref).trim();\n const matches = prefix ? [...walkPlan(tasks)].filter(({ task }) => task.id.startsWith(prefix)) : [];\n return matches.length === 1 ? matches[0].task : undefined;\n}\n","import { v4 as uuidv4 } from 'uuid';\nimport type { PlanIsolation } from '../interfaces/IWorktreeIsolation';\nimport type { AttemptUsage, PlannerUsage, ReportedWindow, UsageRecord, UsageTotals } from './Usage';\nimport type { ExecutionRecord, SupervisorLevel } from './Execution';\nimport type { SkillSource } from '../services/SkillsService';\nimport type { SupervisionMemorySnapshot } from '../services/LoopGuards';\nimport type { SupervisorSnapshot } from '../services/Supervisor';\nimport { SKILL_NAME_PATTERN } from '../conversation/skillTokens';\nimport { subtreeIds, walkPlan } from '../services/PlanTree';\n\nexport interface UserStep {\n order: number;\n instruction: string;\n completed: boolean;\n}\n\n/** One deterministic signal gathered while verifying a completed task. `completion_marker` is only in verdicts saved before completion was reported through `task_complete` alone. */\nexport interface VerificationCheck {\n name: 'exit_code' | 'completion_marker' | 'task_complete' | 'manual';\n passed: boolean;\n /** A check that did not apply. Skipped checks don't affect the verdict. */\n skipped: boolean;\n detail: string;\n}\n\n/** Evidence-based verdict for a completed task. Single end-to-end outcome produced by verification. */\nexport interface Verdict {\n outcome: 'pass' | 'fail';\n reason: string;\n checks: VerificationCheck[];\n decidedAt: string;\n}\n\nexport interface TaskOutputSummary {\n reviewReason: string;\n /** The `task_complete` summary, the task's report; absent when the attempt ended without one, and from sessions saved before it was kept. */\n report?: string;\n /** Empty when there is a report: the turn's final text is the report itself. */\n logTail: string;\n capturedAt: string;\n}\n\nexport type TaskType = 'ai' | 'user';\n/**\n * `skipped` is terminal and verdict-less: the task will not be waited for, and\n * nothing it did lands. Its dependents go ahead without it once the work it\n * waited on is done. There is no stored `blocked`: a task is blocked when a\n * failed dependency says so (ADR-0034), and a file that kept the old status\n * loads as pending.\n */\nexport type TaskStatus = 'pending' | 'approved' | 'in_progress' | 'completed' | 'failed' | 'awaiting_user' | 'skipped';\nexport type TaskMode = string;\n\n/**\n * Why an `awaiting_user` task waits (ADR-0018, W1): a structured turn that\n * ended without a `task_complete` call, a checkpoint question, work that did not\n * land, an ops task that changed tracked files (ADR-0020), or its runner's\n * usage limit. Saved, so no surface has to guess it from whether an attempt\n * is live.\n */\nexport type AwaitingReason = 'input' | 'checkpoint' | 'conflict' | 'files-changed' | 'usage-limit';\n\nexport function isAwaitingReason(value: unknown): value is AwaitingReason {\n return value === 'input' || value === 'checkpoint' || value === 'conflict' || value === 'files-changed' || value === 'usage-limit';\n}\n\nexport interface TaskModelAssignment {\n modelId: string;\n modelLabel: string;\n thinkingEffort?: string;\n /**\n * All variant ids the model offered when this assignment was made. Carried\n * on the assignment because runners need it at spawn time (opencode's TUI\n * only honors an assigned variant when the others are config-disabled) and\n * the discovery catalog isn't available there.\n */\n availableVariants?: string[];\n}\n\nexport type RunnerId = string;\n\n/**\n * Bring loaded tasks to the structured-only shape, in place. A task saved\n * while the terminal transport existed may say it ran there, and why; neither\n * means anything now, and such a task left no session to continue. Its\n * completion marker id went with the text markers: completion is reported\n * only through `task_complete`.\n */\nexport function migrateLoadedTasks(tasks: readonly Task[]): void {\n for (const task of tasks) {\n if (typeof task.runnerSessionId !== 'string') delete task.runnerSessionId;\n if (typeof task.carriedFrom !== 'string') delete task.carriedFrom;\n if (typeof task.runnerSessionOwner !== 'string') delete task.runnerSessionOwner;\n const legacy = task as Task & { transport?: { kind?: unknown; nativeSessionId?: unknown } };\n if (!task.runnerSessionId && legacy.transport?.kind === 'structured' && typeof legacy.transport.nativeSessionId === 'string') {\n task.runnerSessionId = legacy.transport.nativeSessionId;\n }\n delete legacy.transport;\n delete (task as { completionMarker?: unknown }).completionMarker;\n // The effort once had a second home on the task; the spawn reads only the model's.\n const effort = (task as { thinkingEffort?: unknown }).thinkingEffort;\n if (typeof effort === 'string' && task.assignedModel && !task.assignedModel.thinkingEffort) task.assignedModel.thinkingEffort = effort;\n delete (task as { thinkingEffort?: unknown }).thinkingEffort;\n migrateLoadedTasks(task.subtasks ?? []);\n }\n}\n\n/**\n * A task skill as one attempt received it: read from the task's own worktree\n * (or global) at spawn, kept so the user can see what the runner was told\n * even after the skill's file changes.\n */\nexport interface TaskSkillSnapshot {\n name: string;\n source: SkillSource;\n path: string;\n content: string;\n}\n\n/** A task skill as a surface is told of it: the body stays in the task's log file and the session. */\nexport type TaskSkillNotice = Omit<TaskSkillSnapshot, 'content'>;\n\nexport interface Task {\n id: string;\n order: number;\n title: string;\n description: string;\n type: TaskType;\n status: TaskStatus;\n dependencies: string[];\n prompt?: string;\n userSteps?: UserStep[];\n subtasks: Task[];\n verdict?: Verdict;\n outputSummary?: TaskOutputSummary;\n assignedModel?: TaskModelAssignment;\n assignedRunner: RunnerId;\n taskMode?: TaskMode;\n autonomy?: 'AFK' | 'HITL';\n sliceType?: 'HITL' | 'AFK';\n userStoriesCovered?: string[];\n /** The runner's saved session for a later continue; cleared when a fresh attempt starts. */\n runnerSessionId?: string;\n /**\n * The runner that session belongs to: a session cannot cross runners, so\n * Continue is offered only while the task is still assigned to it. Absent\n * on a plan saved before it was recorded; the last attempt's runner stands\n * in (see `sessionOwner`).\n */\n runnerSessionOwner?: RunnerId;\n /** Set only while `status` is `awaiting_user`, and not always then — a pause saved by an older build has none. */\n awaitingReason?: AwaitingReason;\n /**\n * When a task paused on its runner's usage limit is resumed on its own (ISO\n * time): the reset the runner announced, plus a short margin. Absent when no\n * reset time could be read or the user cancelled the resume — the task then\n * waits for a manual retry. Set only with `awaitingReason` `usage-limit`.\n */\n resumeAt?: string;\n /**\n * The runner a task paused on its usage limit was moved off (ADR-0018, U1):\n * its next attempt is a carry-over, a fresh session that starts from that\n * attempt's files. Cleared once that attempt runs, and by a retry.\n */\n carriedFrom?: RunnerId;\n /** Why the task was skipped, as whoever skipped it put it; set only while `status` is `skipped`, and not always then. */\n skipReason?: string;\n /**\n * An ops task (ADR-0020): it changes no repository files, runs at the\n * workspace root rather than in a worktree, and waits for the change tasks\n * it depends on to be merged into the user's branch. Top-level AI tasks\n * only; absent means a change task.\n */\n ops?: boolean;\n /**\n * The dependencies, by title, whose work was not merged into the user's\n * branch when the user force-started this task past its merge gate\n * (ADR-0020). Cleared when the task is retried.\n */\n forcedPastGate?: string[];\n /**\n * Task skills (`applies-to: task`) attached by name. Their bodies are put in\n * the runner's prompt at spawn, resolved where the task runs — a subtask's\n * are its own, never its parent's. Absent means none.\n */\n skills?: string[];\n /** The skills the latest attempt was given, as read when it spawned. */\n attemptSkills?: TaskSkillSnapshot[];\n /**\n * Who put the task in the plan, when it was not the user's own planning:\n * `supervisor` for a task an Act supervisor added during a run, which\n * counts as approved to run (ADR-0029). Set by the session, never by an op.\n */\n addedBy?: 'supervisor';\n attemptUsage?: AttemptUsage[];\n}\n\nexport interface DiscoveredMode {\n id: string;\n label: string;\n description: string;\n}\n\nexport type ResearchToolType =\n | 'read_file' | 'read_files' | 'glob' | 'grep' | 'find_symbol' | 'list_dir'\n | 'bash' | 'fetch' | 'web_search' | 'spawn_research_agent'\n | 'task_query' | 'task_output' | 'task_diff'\n /**\n * A tool belonging to a harness planner's own toolbox (ADR-0009) that has no\n * Ordewell equivalent — Edit, WebFetch, TodoWrite, whatever a coding agent\n * ships next. The real name travels in `toolLabel` rather than being\n * relabelled as a tool it is not; the union stays closed so the\n * exhaustiveness checks in every surface's icon/label switch survive.\n */\n | 'agent_tool';\n\n/**\n * What happened when a research tool call ran, for honest per-surface\n * rendering. The broadcast seam carries this on every `research_step_done` so\n * surfaces do not have to pattern-match refusal text to tell a refused `rm`\n * from a successful `rm` — the old render path flipped a `✓` for both.\n */\nexport type ResearchStepOutcome = 'success' | 'failure' | 'refused' | 'denied' | 'not_executed';\n\nexport interface ResearchStep {\n id: string;\n tool: ResearchToolType;\n /** The tool's own name when it came from a harness planner — always set for `agent_tool`. */\n toolLabel?: string;\n args: string;\n result: string;\n success: boolean;\n outcome: ResearchStepOutcome;\n /** The model's tool_call id, so a surface can match `tool_result` to the\n * pending `tool_call` it announced — robust under parallel same-tool rounds. */\n toolCallId?: string;\n /** The research subagent that ran the call, so a reload regroups it under that subagent. */\n subagentId?: string;\n timestamp: string;\n thinkingText?: string;\n}\n\nexport interface UserPromptEntry {\n id: string;\n type: 'user_prompt' | 'system';\n content: string;\n timestamp: string;\n}\n\nexport type SubagentOutcome = 'done' | 'failed' | 'stopped';\n\n/**\n * One subagent's whole run, logged when it finishes: what it was asked, how it\n * ended and what it reported. Its steps stay separate entries carrying the same\n * `subagentId`, so an older reader that knows only steps still shows them.\n */\nexport interface SubagentLogEntry {\n id: string;\n type: 'subagent';\n subagentId: string;\n brief: string;\n model?: string;\n outcome: SubagentOutcome;\n digest: string;\n usage?: UsageTotals;\n timestamp: string;\n}\n\nexport type ResearchLogEntry = ResearchStep | UserPromptEntry | SubagentLogEntry;\n\nexport interface ResearchProgress {\n // 'liveness' carries no content: a raw-line signal from the harness process\n // (ADR-0009) that reaches a surface even when a turn is producing nothing\n // visible — a subagent's filtered chatter, most often — so an idle watchdog\n // downstream doesn't mistake \"nothing to show\" for \"nothing happening\".\n //\n // The turn-scoped kinds below carry one planner turn's stream (#47); see the\n // matching SessionMessage variants for the invariants each one keeps.\n // 'text_delta' is reply text as the model streams it (`text`, `segmentId`),\n // an envelope included: the turn's owner routes each segment to prose or to\n // the plan display, so no backend has to tell them apart. 'text_retracted'\n // takes back an attempt's text: `segmentId`'s, or when absent everything the\n // backend call that sends it has streamed.\n // 'usage' reports one model call (`record`). 'subagent_started' carries\n // `brief` and `model`; 'subagent_finished' carries `outcome`, `digest` and\n // `usage`.\n type:\n | 'thinking' | 'tool_call' | 'tool_result' | 'plan_token' | 'interrupted' | 'liveness'\n | 'text_delta' | 'text_retracted' | 'usage' | 'subagent_started' | 'subagent_finished';\n /** Minted by whoever runs the turn and passed through untouched; absent outside a turn. */\n turnId?: string;\n /** One continuous run of model text — text before a tool call is its own segment. */\n segmentId?: string;\n text?: string;\n tool?: string;\n /** Harness planners (ADR-0009): the agent's own name for a tool Ordewell has no member for. */\n toolLabel?: string;\n toolArgs?: string;\n toolResult?: string;\n planToken?: string;\n step?: ResearchStep;\n /** The model's tool_call id, threaded on tool_call and tool_result so a\n * surface can match the result to its pending call — robust under parallel\n * same-tool rounds where LIFO-by-name matching mislabels summaries. */\n toolCallId?: string;\n /** Present when this event originates from (or reports on) one spawned research subagent (issue #34). */\n subagentId?: string;\n record?: UsageRecord;\n brief?: string;\n model?: string;\n outcome?: SubagentOutcome;\n digest?: string;\n usage?: UsageTotals;\n}\n\nexport interface ThinkingBlock {\n id: string;\n text: string;\n}\n\nexport interface StreamThinkingEvent {\n type: 'thinking';\n block: ThinkingBlock;\n}\n\nexport interface StreamStepEvent {\n type: 'step';\n step: ResearchStep;\n}\n\nexport type StreamEvent = StreamThinkingEvent | StreamStepEvent;\n\nexport interface DiscoveredModel {\n modelId: string;\n modelLabel: string;\n runnerProvider?: string;\n /**\n * Human-facing provider name as the runner itself reports it (e.g.\n * \"OpenCode Zen\" for `runnerProvider: 'opencode'`). Populated from the\n * runner's own provider catalog when available; when absent the UI derives a\n * label from `runnerProvider` by title-casing.\n */\n runnerProviderLabel?: string;\n /**\n * The runner whose catalog listed this model. Stamped once, at the single\n * `ModelDiscovery.discover` choke point, so a flat cross-runner list can\n * still say where each entry came from — `runnerProvider` alone cannot:\n * OpenCode reports most of its catalog as `openrouter`, which names the\n * serving backend, not the agent Ordewell would spawn.\n */\n runnerId?: string;\n /** The runner's display name (`OpenCode`), from its manifest. */\n runnerLabel?: string;\n variants: { id: string; label: string }[];\n /**\n * The model's context window when the runner or catalog reports it (#49).\n * Read by the planner-model lookup so context fill can be shown; absent when\n * unknown rather than defaulted to zero.\n */\n contextWindow?: number;\n}\n\nexport type PlanStatus = 'draft' | 'approved' | 'rejected' | 'running' | 'completed';\n\n/**\n * One entry of the planner's persisted dialogue (ADR-0002). The single source\n * of truth for both UI redisplay and conversational context. Tool-call results\n * are NOT stored here — they live in the AI service's tool-use history;\n * `researchLog` remains the persisted tool trace for the UI.\n */\nexport interface ConversationMessage {\n role: 'user' | 'assistant';\n content: string;\n timestamp: string;\n /**\n * Timeline marker: 'plan_generated' records the point in the dialogue where\n * the plan was committed (the UI anchors the plan card there on restore);\n * 'system' is a host-injected notice; 'compaction' is the summary a\n * user-triggered compaction left in place of the earlier messages — always\n * the transcript's first entry. 'skill_load' is a skill loaded into the\n * conversation, its snapshot in `skill`; one the user invoked follows the\n * message that named it. 'execution' is a call at the command seam\n * (ADR-0029), its record in `execution`. 'wake_up' is the digest a wake-up\n * gave the supervisor (role 'user': the model was told it), and\n * 'supervisor' what the supervisor said in a wake-up turn (ADR-0029).\n * 'error' is a planner turn that ended on the planner's usage limit, drawn\n * as a failure and never replayed to the planner: it is not the planner's\n * answer, and its inputs are sent again (see {@link PlannerResendState}).\n * Absent for ordinary chat turns, so sessions saved before markers existed\n * degrade gracefully.\n */\n kind?: 'plan_generated' | 'system' | 'compaction' | 'skill_load' | 'execution' | 'wake_up' | 'supervisor' | 'error';\n actor?: 'Ordewell setting';\n /** Present exactly when `kind` is 'skill_load'. */\n skill?: SkillLoad;\n /** Present exactly when `kind` is 'execution'. */\n execution?: ExecutionRecord;\n /** A user's message that was force sent, stopping the turn before it (ADR-0023). */\n forced?: true;\n /**\n * What a reply showed, run by run, where each began (ADR-0017 A1). Beside\n * `content`, which stays the reply as the planner is told it. Absent on\n * entries saved before runs were kept, which reload as one message.\n */\n runs?: ReplyRun[];\n}\n\n/**\n * One run of a planner reply's text: the segment it streamed under, its\n * settled text, and when it began. A run that never streamed (a message the\n * conversation wrote in the planner's place) has a segment no stream used.\n */\nexport interface ReplyRun {\n segmentId: string;\n text: string;\n /** ISO timestamp. */\n startedAt: string;\n}\n\n/**\n * A skill's SKILL.md as it was when loaded into a planner conversation. A\n * snapshot rather than a reference: a resumed, forked or rewound conversation\n * replays the body the planner originally saw, even after the file changed or\n * was deleted.\n */\nexport interface SkillLoad {\n invokedBy: 'user' | 'planner';\n name: string;\n source: SkillSource;\n /** The SKILL.md that won, home-abbreviated (`~/...`): which copy loaded is what a reader needs from it. */\n path: string;\n content: string;\n /**\n * Set when the user named a task skill: it is not loaded into the planner's\n * context, which is only told to attach it to the tasks it fits. `content`\n * is empty; the description is what the planner's directive quotes.\n */\n attaches?: { description: string };\n}\n\n/** A skill load as a surface announces it — the body stays with the transcript. */\nexport type SkillLoadNotice = Omit<SkillLoad, 'content'>;\n\n/** A message the user sent, as opposed to a skill load their message caused or a wake-up digest. */\nexport function isUserMessage(entry: Pick<ConversationMessage, 'role' | 'kind'>): boolean {\n return entry.role === 'user' && entry.kind !== 'skill_load' && entry.kind !== 'wake_up';\n}\n\n/** A follow-up an older build queued behind a run's batch boundary; read only to carry it over as a {@link PendingPlanTurn}. */\nexport interface QueuedMessage {\n id: string;\n text: string;\n timestamp: string;\n skills?: SkillLoad[];\n}\n\n/** Who a planner turn answers (ADR-0029): the user's message, or a wake-up batch the supervisor is given. */\nexport type PlanTurnSource = 'user' | 'supervisor';\n\n/**\n * A planner turn's input not yet answered by a turn that ended. It leaves the\n * plan with the change its turn made, in the same save, so a reload replays\n * exactly the inputs no turn answered — once. A supervisor's input is a\n * wake-up batch not yet delivered (ADR-0029): it stays until a turn lands\n * with it, whatever turns fail meanwhile.\n */\nexport interface PendingPlanTurn {\n id: string;\n source: PlanTurnSource;\n /** The user's message, or a wake-up batch's digest. */\n text: string;\n timestamp: string;\n /** What its `/name` tokens loaded when it was sent, so a replay sends the same skills. */\n skills?: SkillLoad[];\n /** Force sent: it waits ahead of every input not forced, and its turn is its own (ADR-0023, F2). */\n forced?: true;\n}\n\n/**\n * The run's own copy of the user's run settings (ADR-0030): taken when the\n * user starts it, changed at once by a change made in this session, and\n * lowered by a tripped guard or a failed supervisor.\n */\nexport interface RunSettings {\n mergeAtGatesAutomatically: boolean;\n /** Absent on a run started before supervisor levels existed: Off. */\n supervisorLevel?: SupervisorLevel;\n /** Absent on a run started before ADR-0030: the user's setting. */\n supervisorRetryLimit?: number;\n /** Absent on a run started before ADR-0030: the user's setting. */\n wakeUpReadBudget?: number;\n /** Why the supervisor stopped for the rest of this run, which carries on as Off; absent while it watches. */\n unsupervised?: string;\n}\n\n/**\n * What supervision remembers across a daemon restart (ADR-0029): the loop\n * guards' memory and the wake-up state not yet delivered with a turn.\n */\nexport interface SupervisionSnapshot {\n /** Retries, failed-attempt shapes, the supervisor's edits and what the user was told. */\n guards?: SupervisionMemorySnapshot;\n /** The events inside their debounce window and the wake-up rate's timestamps. */\n wake?: SupervisorSnapshot;\n}\n\n/**\n * What waits on the planner's usage limit. With `at`, the inputs no turn\n * answered are sent again then, on their own; without it — the reset could\n * not be read, the resend hit the limit again, or it was cancelled — they go\n * with the next input: the user's message, or a wake-up.\n */\nexport interface PlannerResendState {\n /** The runner whose account hit the limit; a planner on another one is not held by it. */\n runner?: RunnerId;\n at?: string;\n}\n\nexport interface LegacyPlanState {\n runSettings?: RunSettings;\n /** What supervision remembers across a daemon restart (ADR-0029); absent on plans saved before it existed. */\n supervision?: SupervisionSnapshot;\n tasks: Task[];\n generatedAt: string;\n status: PlanStatus;\n runners: RunnerId[];\n lastUpdated: string;\n researchLog?: ResearchLogEntry[];\n /** The planner dialogue — user messages and assistant messages, in order (ADR-0002). */\n conversationHistory?: ConversationMessage[];\n /** Full markdown PRD once written by the planner (PRD mode), also saved to .scratch/<slug>/PRD.md. */\n prdMarkdown?: string;\n /** Planner turn inputs no turn has answered yet (ADR-0029); a reload replays them. */\n pendingTurns?: PendingPlanTurn[];\n /** Written by builds that queued mid-run edits; a load moves it into {@link pendingTurns}. */\n queuedMessages?: QueuedMessage[];\n /**\n * The plan's isolation run (ADR-0013), written from the orchestrator at\n * persist time and read back only when a saved plan is adopted. It names\n * branches and worktrees that belong to this plan alone: a fork of the plan\n * must leave it behind rather than share it.\n */\n isolation?: PlanIsolation;\n /** Kept so a reopened session shows the same token line (#49). */\n plannerUsage?: PlannerUsage;\n /** The windows reported over the session, so a reopened one knows each model's from its first call. */\n contextWindows?: ReportedWindow[];\n /** The planner hit its usage limit and the inputs its turn took wait to be sent again; absent otherwise. */\n plannerResend?: PlannerResendState;\n /**\n * The tasks the user approved to run: every task when they executed the\n * plan, and each one they started or retried themselves since. A command\n * from anyone else starts only these (ADR-0029); a task the planner added\n * after the approval waits for the user's. Only tasks still in the plan: a\n * task that leaves takes its approval with it.\n */\n approvedTasks?: string[];\n /**\n * The user approved the plan to run: Execute plan, signing off a review, or\n * autorun's start (ADR-0029, ADR-0030). Kept apart from {@link status},\n * which surfaces rewrite for display; a user's start of one task approves\n * that task, not the plan.\n */\n approved?: boolean;\n}\n\nexport interface Message {\n id: string;\n role: 'user' | 'planner' | 'system';\n content: string;\n timestamp: number;\n}\n\nexport interface TaskSnapshot extends Task {\n completedAt: number;\n verdict?: Verdict;\n retryCount: number;\n finalized: boolean;\n}\n\n/** The plan a surface reads whole carries the approval record, so it can tell which tasks wait for the user (ADR-0035). */\nexport type PlanState = (\n | {\n phase: 'planning';\n history: Message[];\n message: string;\n pendingTasks: Task[];\n }\n | {\n phase: 'executing';\n history: Message[];\n message: string;\n executionLog: TaskSnapshot[];\n pendingTasks: Task[];\n goal: string;\n runners: string[];\n status: PlanStatus;\n }\n) & ApprovalRecord;\n\nfunction hasPhase(raw: unknown): raw is PlanState {\n return typeof raw === 'object' && raw !== null && 'phase' in raw;\n}\n\nfunction hasTasks(raw: unknown): raw is LegacyPlanState {\n return typeof raw === 'object' && raw !== null && 'tasks' in raw && Array.isArray((raw as Record<string, unknown>).tasks);\n}\n\nfunction logEntryToMessage(entry: ResearchLogEntry): Message {\n const timestamp = new Date(entry.timestamp).getTime();\n if (!('type' in entry)) {\n return { id: entry.id, role: 'system', content: JSON.stringify({ tool: entry.tool, args: entry.args, result: entry.result }), timestamp };\n }\n if (entry.type === 'subagent') {\n const { subagentId, brief, outcome, digest } = entry;\n return { id: entry.id, role: 'system', content: JSON.stringify({ subagentId, brief, outcome, digest }), timestamp };\n }\n return { id: entry.id, role: entry.type === 'user_prompt' ? 'user' : 'system', content: entry.content, timestamp };\n}\n\nfunction migrateHistory(raw: LegacyPlanState): Message[] {\n const messages: Message[] = [];\n\n if (raw.researchLog) {\n messages.push(...raw.researchLog.map(logEntryToMessage));\n }\n\n if (raw.queuedMessages) {\n for (const qm of raw.queuedMessages) {\n messages.push({\n id: qm.id,\n role: 'system',\n content: qm.text,\n timestamp: new Date(qm.timestamp).getTime(),\n });\n }\n }\n\n return messages;\n}\n\nexport function migratePlanState(raw: unknown): PlanState {\n if (hasPhase(raw)) return raw;\n\n if (!hasTasks(raw)) {\n return {\n phase: 'planning',\n history: [],\n message: '',\n pendingTasks: [],\n };\n }\n\n const hasExecution = raw.tasks.some(\n (t) => t.status === 'completed' || t.status === 'failed',\n );\n\n const messages = migrateHistory(raw);\n const record = approvalRecordOf(raw);\n\n if (hasExecution) {\n const executionLog: TaskSnapshot[] = raw.tasks\n .filter((t) => t.status === 'completed' || t.status === 'failed')\n .map((t) => ({\n ...t,\n completedAt: new Date(raw.lastUpdated).getTime(),\n verdict: t.verdict,\n retryCount: 0,\n finalized: true,\n }));\n\n const pendingTasks = raw.tasks.filter(\n (t) => t.status !== 'completed' && t.status !== 'failed',\n );\n\n return {\n phase: 'executing',\n history: messages,\n message: '',\n executionLog,\n pendingTasks,\n goal: '',\n runners: raw.runners,\n status: raw.status,\n ...record,\n };\n }\n\n return {\n phase: 'planning',\n history: messages,\n message: '',\n pendingTasks: raw.tasks,\n ...record,\n };\n}\n\nexport { taskOrderLabel, taskRef, taskRefOf, titledTaskRef, titledTaskRefOf, resolveTaskRef, resolveUserTaskRef } from '../services/TaskRefs';\n\nexport function createTask(overrides: Partial<Task> = {}): Task {\n const skills = skillNames(overrides.skills);\n return {\n id: overrides.id ?? uuidv4(),\n order: overrides.order ?? 0,\n title: overrides.title ?? '',\n description: overrides.description ?? '',\n type: overrides.type ?? 'ai',\n status: overrides.status ?? 'pending',\n dependencies: overrides.dependencies ?? [],\n prompt: overrides.prompt,\n userSteps: overrides.userSteps,\n subtasks: overrides.subtasks ?? [],\n verdict: overrides.verdict,\n outputSummary: overrides.outputSummary,\n ...(overrides.attemptUsage ? { attemptUsage: structuredClone(overrides.attemptUsage) } : {}),\n assignedModel: overrides.assignedModel,\n assignedRunner: overrides.assignedRunner ?? DEFAULT_RUNNERS[0],\n taskMode: overrides.taskMode ?? 'build',\n autonomy: overrides.autonomy,\n sliceType: overrides.sliceType,\n userStoriesCovered: overrides.userStoriesCovered,\n ...(opsFlag(overrides.ops, overrides.type) ? { ops: true } : {}),\n ...(skills ? { skills } : {}),\n ...(overrides.addedBy === 'supervisor' ? { addedBy: 'supervisor' as const } : {}),\n };\n}\n\n/**\n * A name a skill can have, lower-cased as `/name` is. Anything else — a path\n * separator, `..` — is joined into a path and could only reach outside the\n * skill dirs.\n */\nconst SKILL_NAME = new RegExp(`^${SKILL_NAME_PATTERN}$`);\n\nexport function isSkillName(name: string): boolean {\n return SKILL_NAME.test(name);\n}\n\n/**\n * The `skills` field as a task stores it, however it arrived: the planner's\n * JSON is untyped. Names are trimmed, lower-cased and deduplicated, and one\n * no skill could have is dropped; none at all is stored absent, so a plan\n * without skills reads exactly as it did before them.\n */\nexport function skillNames(value: unknown): string[] | undefined {\n if (!Array.isArray(value)) return undefined;\n const names = [...new Set(value.filter((v): v is string => typeof v === 'string').map((v) => v.trim().toLowerCase()).filter(isSkillName))];\n return names.length > 0 ? names : undefined;\n}\n\n/**\n * The skills of a task a merge or a split makes from others: what the edit\n * chose when it named any, none when it chose an explicit `[]`, else what the\n * tasks it came from had — a malformed value is not a request to drop them.\n */\nexport function inheritedSkills(chosen: unknown, inherited: readonly string[] | undefined): string[] | undefined {\n if (Array.isArray(chosen) && chosen.length === 0) return undefined;\n return skillNames(chosen) ?? skillNames(inherited);\n}\n\n/**\n * The `ops` flag as a task stores it (ADR-0020), however it arrived. Only a\n * literal `true` on an AI task marks an ops task: the planner's JSON is\n * untyped, and a quoted \"true\" read as ops would move a task out of its\n * worktree. Anything else is a change task, stored absent so saved plans need\n * no migration. Whether the task may be ops at all — a subtask may not — is\n * for whoever knows where it sits: the planner intake refuses it (`checkPlanInvariants`).\n */\nexport function opsFlag(value: unknown, type: Task['type'] = 'ai'): true | undefined {\n return value === true && type === 'ai' ? true : undefined;\n}\n\n/**\n * The flag of a task a merge or a split makes from others: what the edit\n * chose, else ops only when every task it came from was. A merge that takes\n * in a change edits files, so it is a change; a split part runs where its\n * task did.\n */\nexport function inheritedOps(from: readonly Pick<Task, 'ops'>[], chosen?: boolean): boolean {\n return chosen ?? from.every((t) => opsFlag(t.ops) === true);\n}\n\n/**\n * The runner set a plan has until one is chosen. The one runner named outside\n * its declaration on purpose: a default is a product choice that no manifest\n * or connector implies.\n */\nexport const DEFAULT_RUNNERS: readonly RunnerId[] = ['claude-code'];\n\nexport function createEmptyPlan(): LegacyPlanState {\n return {\n tasks: [],\n generatedAt: new Date().toISOString(),\n status: 'draft',\n runners: [...DEFAULT_RUNNERS],\n lastUpdated: new Date().toISOString(),\n };\n}\n\nexport function flattenTasks(tasks: readonly Task[]): Task[] {\n return [...walkPlan(tasks)].map(({ task }) => task);\n}\n\n/**\n * A phase-tagged plan rejoined into its tree. The execution log is flat — a\n * finished subtask is logged on its own as well as inside its parent — and in\n * the order tasks finished, so read as a list it puts subtasks at the top level\n * under orders that clash with real top-level tasks. A task's own entry is the\n * latest word on it: its parent's copy was taken when the parent last changed.\n */\nexport function rejoinPlanTree<T extends { id: string; order: number; subtasks?: T[] }>(pending: readonly T[], log: readonly T[]): T[] {\n const latest = new Map<string, T>();\n for (const task of [...pending, ...log]) latest.set(task.id, task);\n const nested = new Set<string>();\n const markNested = (task: T): void => {\n for (const sub of task.subtasks ?? []) {\n nested.add(sub.id);\n markNested(sub);\n }\n };\n for (const task of latest.values()) markNested(task);\n const rebuild = (task: T): T => {\n const own = latest.get(task.id) ?? task;\n return own.subtasks?.length ? { ...own, subtasks: own.subtasks.map(rebuild) } : own;\n };\n return [...latest.values()].filter((task) => !nested.has(task.id)).map(rebuild).sort((a, b) => a.order - b.order);\n}\n\n/**\n * A flattened task with the parent it hangs under, null for a top-level task,\n * and the path label and reference (`#2.1.3`) `TaskRefs` renders for it.\n */\nexport interface TaskWithParent {\n task: Task;\n parent: Task | null;\n label: string;\n ref: string;\n}\n\nexport function flattenTasksWithParents(tasks: readonly Task[]): TaskWithParent[] {\n return [...walkPlan(tasks)].map(({ task, parent, label }) => ({ task, parent: parent ?? null, label, ref: `#${label}` }));\n}\n\nexport function addTaskToPlan(tasks: readonly Task[], partial: Partial<Task>): Task[] {\n const maxOrder = tasks.reduce((max, t) => Math.max(max, t.order), 0);\n const newTask = createTask({\n ...partial,\n order: partial.order ?? maxOrder + 1,\n status: 'pending',\n });\n return renumberTasks([...tasks, newTask]);\n}\n\nexport function removeTaskFromPlan(tasks: readonly Task[], taskId: string): Task[] {\n const removed = subtreeIds(tasks, taskId);\n const prune = (level: readonly Task[]): Task[] => level\n .filter((t) => !removed.has(t.id))\n .map((t) => ({\n ...t,\n dependencies: t.dependencies.filter((depId) => !removed.has(depId)),\n subtasks: prune(t.subtasks),\n }));\n return renumberTasks(prune(tasks));\n}\n\nexport function updateTaskInPlan(tasks: readonly Task[], taskId: string, changes: Partial<Task>): Task[] {\n return renumberTasks(\n tasks.map((t) => {\n if (t.id === taskId) return { ...t, ...changes, id: t.id };\n return { ...t, subtasks: updateTaskInPlan(t.subtasks, taskId, changes) };\n })\n );\n}\n\nexport function renumberTasks(tasks: readonly Task[]): Task[] {\n return tasks.map((t, i) => ({\n ...t,\n order: i + 1,\n subtasks: renumberTasks(t.subtasks),\n }));\n}\n\n/** A task paused on its runner's usage limit, whether it resumes on its own or waits for the user (#84). */\nexport function pausedOnLimit(task: Readonly<Task>): boolean {\n return task.status === 'awaiting_user' && task.awaitingReason === 'usage-limit';\n}\n\n/** A task paused on a usage limit that resumes on its own when the limit resets (#84). */\nexport function waitsForReset(task: Readonly<Task>): boolean {\n return pausedOnLimit(task) && !!task.resumeAt;\n}\n\n/** The user's approval record, as a plan carries it (ADR-0029). */\nexport type ApprovalRecord = Pick<LegacyPlanState, 'approved' | 'approvedTasks'>;\n\n/** A copy of the plan's approval record, for a plan read whole; a field the plan lacks stays absent. */\nexport function approvalRecordOf(plan: ApprovalRecord): ApprovalRecord {\n return {\n ...(plan.approved !== undefined ? { approved: plan.approved } : {}),\n ...(plan.approvedTasks ? { approvedTasks: [...plan.approvedTasks] } : {}),\n };\n}\n\n/**\n * A task the scheduler leaves for the user (ADR-0035): an AI task not started\n * yet, in a plan they approved, outside their approval record — the planner\n * added it since. It starts once they start it or execute the plan. In a plan\n * they never approved nothing is theirs yet, so nothing is singled out.\n */\nexport function waitsForApproval(task: Pick<Task, 'id' | 'type' | 'status'>, record: ApprovalRecord): boolean {\n return record.approved === true\n && task.type === 'ai'\n && (task.status === 'pending' || task.status === 'approved')\n && !(record.approvedTasks ?? []).includes(task.id);\n}\n\n/**\n * Who put each task of an adopted list in the plan. A task the plan already\n * had keeps its origin, whatever the planner wrote; a new one is the\n * supervisor's when `bySupervisor`, and nobody's in particular otherwise, so\n * no planner can mark its own task as the supervisor's. `added` lists the new\n * tasks, subtasks included.\n */\nexport function stampOrigin(before: readonly Task[], after: readonly Task[], bySupervisor: boolean): { tasks: Task[]; added: string[] } {\n const prior = new Map(flattenTasks([...before]).map((t) => [t.id, t]));\n const added: string[] = [];\n const stamp = (tasks: readonly Task[]): Task[] => tasks.map((t) => {\n const was = prior.get(t.id);\n const origin = was ? was.addedBy : bySupervisor ? 'supervisor' : undefined;\n if (!was) added.push(t.id);\n const stamped: Task = { ...t, subtasks: stamp(t.subtasks ?? []) };\n if (origin) stamped.addedBy = origin;\n else delete stamped.addedBy;\n return stamped;\n });\n return { tasks: stamp(after), added };\n}\n\n/** Done, running, or held for the user: execution state only a runner or the user can change. */\nconst SETTLED_STATUSES: ReadonlySet<TaskStatus> = new Set<TaskStatus>(['completed', 'in_progress', 'awaiting_user']);\n\nfunction holdsSettledWork(task: Task): boolean {\n return SETTLED_STATUSES.has(task.status) || (task.subtasks ?? []).some(holdsSettledWork);\n}\n\n/**\n * Lay a planner-written task list over the plan it rewrites without letting it\n * change execution state. A planner restates tasks; it never witnessed one run,\n * so the status it writes is not evidence. A settled task is kept exactly as\n * it stands wherever the rewrite names it, and put back beside its old\n * neighbour where the rewrite leaves it out. Every other task keeps the status\n * it had; a task the rewrite adds starts pending.\n */\nexport function keepExecutionState(current: readonly Task[], rewrite: Task[]): Task[] {\n const existing = new Map(flattenTasks(current).map((t) => [t.id, t]));\n const named = new Set(flattenTasks(rewrite).map((t) => t.id));\n\n const overlay = (tasks: Task[], was: readonly Task[]): Task[] => {\n const result = tasks.map((t): Task => {\n const prior = existing.get(t.id);\n if (prior && SETTLED_STATUSES.has(prior.status)) return { ...prior };\n return {\n ...t,\n status: prior?.status ?? 'pending',\n skipReason: prior?.skipReason,\n verdict: prior?.verdict,\n outputSummary: prior?.outputSummary,\n runnerSessionId: prior?.runnerSessionId,\n runnerSessionOwner: prior?.runnerSessionOwner,\n carriedFrom: prior?.carriedFrom,\n attemptSkills: prior?.attemptSkills,\n attemptUsage: prior?.attemptUsage,\n // Where a task that has run ran is fixed, like its runner session (ADR-0020).\n ...(prior?.status === 'failed' ? { ops: prior.ops } : {}),\n forcedPastGate: prior?.forcedPastGate,\n subtasks: overlay(t.subtasks ?? [], prior?.subtasks ?? []),\n };\n });\n was.forEach((left, i) => {\n if (named.has(left.id) || !holdsSettledWork(left)) return;\n const neighbour = was.slice(0, i).reverse().find((t) => result.some((r) => r.id === t.id));\n const at = neighbour ? result.findIndex((r) => r.id === neighbour.id) + 1 : 0;\n result.splice(at, 0, { ...left });\n });\n return result;\n };\n\n return renumberTasks(overlay(rewrite, current));\n}\n"],"mappings":";AACO,IAAM,qBAAqB;AAQlC,IAAM,cAAc,IAAI,OAAO,cAAc,kBAAkB,yBAAyB,IAAI;AAcrF,SAAS,YAAY,MAA4B;AACtD,QAAM,SAAuB,CAAC;AAC9B,QAAM,OAAO,oBAAI,IAAY;AAC7B,aAAW,SAAS,KAAK,SAAS,WAAW,GAAG;AAC9C,UAAM,OAAO,MAAM,CAAC,EAAE,YAAY;AAClC,QAAI,KAAK,IAAI,IAAI,EAAG;AACpB,SAAK,IAAI,IAAI;AACb,UAAM,QAAQ,MAAM,QAAQ,MAAM,CAAC,EAAE;AACrC,WAAO,KAAK,EAAE,MAAM,OAAO,KAAK,QAAQ,IAAI,MAAM,CAAC,EAAE,OAAO,CAAC;AAAA,EAC/D;AACA,SAAO;AACT;AAGO,SAAS,kBAAkB,MAAc,QAAyC;AACvF,SAAO,YAAY,IAAI,EAAE,OAAO,CAAC,MAAM,OAAO,SAAS,EAAE,IAAI,CAAC;AAChE;;;ACnBO,UAAU,SAAgC,OAAkD;AACjG,YAAU,KAAK,OAAqB,WAAyB,aAAmD;AAC9G,eAAW,QAAQ,OAAO;AACxB,YAAM,QAAQ,cAAc,GAAG,WAAW,IAAI,KAAK,KAAK,KAAK,OAAO,KAAK,KAAK;AAC9E,YAAM,EAAE,MAAM,QAAQ,UAAU,GAAG,EAAE,GAAG,WAAW,UAAU,OAAO,MAAM;AAC1E,aAAO,KAAK,KAAK,YAAY,CAAC,GAAG,CAAC,GAAG,WAAW,IAAI,GAAG,KAAK;A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oBAAoB,OAAO;AAAA,QAC3B,aAAa,OAAO;AAAA,QACpB,eAAe,OAAO;AAAA,QACtB,cAAc,OAAO;AAAA;AAAA,QAErB,GAAI,OAAO,WAAW,WAAW,EAAE,KAAK,MAAM,IAAI,IAAI,CAAC;AAAA,QACvD,gBAAgB,OAAO;AAAA,QACvB,UAAU,QAAQ,EAAE,YAAY,CAAC,GAAG,OAAO,YAAY,CAAC,CAAC;AAAA,MAC3D;AAAA,IACF,CAAC;AACD,QAAI,QAAQ,CAAC,MAAM,MAAM;AACvB,UAAI,MAAM,IAAI,KAAK,EAAE,KAAK,CAAC,iBAAiB,IAAI,EAAG;AACnD,YAAM,YAAY,IAAI,MAAM,GAAG,CAAC,EAAE,QAAQ,EAAE,KAAK,CAAC,MAAM,OAAO,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,EAAE,CAAC;AACzF,YAAM,KAAK,YAAY,OAAO,UAAU,CAAC,MAAM,EAAE,OAAO,UAAU,EAAE,IAAI,IAAI;AAC5E,aAAO,OAAO,IAAI,GAAG,EAAE,GAAG,KAAK,CAAC;AAAA,IAClC,CAAC;AACD,WAAO;AAAA,EACT;AAEA,SAAO,cAAc,QAAQ,SAAS,OAAO,CAAC;AAChD;","names":[]}
package/dist/index.d.mts CHANGED
@@ -1,11 +1,11 @@
1
- import { r as IsolationMergeResult, ai as Task, E as ExecutionActor, f as ExecutionRecord, g as GuardTrip, ah as SupervisorLevel, e as ExecutionCommandName, G as GuardTarget, n as IsolationLandedTask, I as IWorktreeIsolation, F as IsolationTaskStatus, J as PlanIsolation, a4 as RunnerId, $ as ResearchProgress, av as UsageRecord, _ as ResearchLogEntry, d as DiscoveredModel, L as LegacyPlanState, a5 as RunnerSessionCost, a2 as ResearchToolType, R as PlannerUsage, ap as TaskSkillSnapshot, af as SkillsService, aq as TaskSnapshot, K as PlanState, H as IsolationView, ax as Verdict } from './Task-hFfRS9rN.mjs';
2
- export { A as ApprovalRecord, a as AttemptUsage, b as AwaitingReason, B as BUILTIN_SKILL_NAMES, C as ConversationMessage, D as DEFAULT_RUNNERS, c as DEFAULT_SUPERVISOR_RETRY_LIMIT, h as IntegrationDisposal, i as InvalidSkill, j as IsolationAvailability, k as IsolationHandoff, l as IsolationHandoffRepo, m as IsolationInactiveReason, o as IsolationLanding, p as IsolationMergeBlock, q as IsolationMergeBlockReason, s as IsolationOutcome, t as IsolationPruneResult, u as IsolationRemoval, v as IsolationRepo, w as IsolationRun, x as IsolationTaskRecord, y as IsolationTaskRef, z as IsolationTaskRepo, M as ModelUsage, N as PlanStatus, O as PlanUsage, Q as PlannerResendState, S as PrepareIntent, T as PreparedTask, U as PreservedWork, V as PreviousWork, W as RefusedRemoval, X as RepairEvidence, Y as ReplyRun, Z as RepoGroupLayout, a0 as ResearchStep, a1 as ResearchStepOutcome, a3 as RunSettings, a6 as SetupFailure, a7 as ShadowedSkill, a8 as SkillAppliesTo, a9 as SkillCatalog, aa as SkillInfo, ab as SkillLoad, ac as SkillLoadNotice, ad as SkillMetadata, ae as SkillSource, al as TaskIsolation, am as TaskIsolationState, an as TaskModelAssignment, ar as TaskStatus, as as TaskUsageSummary, at as TreeSnapshot, au as UsageLine, aw as UsageTotals, ay as VerificationCheck, az as addAttemptUsage, aA as addModelUsage, aB as addPlannerUsage, aC as addUsage, aD as addUsageTotals, aE as countedSessionCost, aF as createEmptyPlan, aG as createSkillsService, aH as createTask, aI as endAttemptUsage, aJ as flattenTasks, aK as flattenTasksWithParents, aL as isAwaitingReason, aM as isMeasured, aN as isSupervisorLevel, aO as isUserMessage, aP as migratePlanState, aQ as partedPromptUsage, aR as pausedOnLimit, aS as planUsage, aT as plannerContextFill, aU as rejoinPlanTree, aV as resumedSessionWindow, aW as startAttemptUsage, aX as taskUsageSummary, aY as usageLine, aZ as waitsForApproval } from './Task-hFfRS9rN.mjs';
3
- import { bv as StartAdmission, bw as StartWait, aY as ResolveAll, a8 as IWebFetcher, cp as WebReadPolicy, cn as WebRead, co as WebReadDecision, aw as PendingApprovals, K as ConversationTurn, aL as PlannerModes, a6 as IAiService, I as ConversationRequest, n as AssignmentWriter, m as AssignmentScope, c1 as TaskQueryCatalog, k as AssignmentCatalog, b7 as RunnerCatalog, bl as SessionMessage, bh as SessionBroadcaster, bn as SessionNotice, aC as PlanStore, bX as TaskOrchestrator, ab as IsolationRunController, at as OrchestratorObserver, bQ as TaskLogEvent, a7 as INotification, a2 as GlobalRunSettings, aF as PlannerConversationHost, aE as PlannerConversation, av as PendingApproval, E as ConversationCompaction, a_ as RewindTarget, b6 as RunView, b1 as RunMergeView, b_ as TaskOutputSource, cl as UserSettings, ae as LiveTailOptions, ad as LiveTail, bm as SessionMeta, aK as PlannerModelStore, aJ as PlannerModelRecall, aG as PlannerModelCandidate } from './runSettingsText-rLoYQlUH.mjs';
4
- export { A as ACT_RISK, a as AUTORUN_RISK, b as AdoptSessionResponse, c as ApplyTaskOpsResult, d as ApprovalAnswerResponse, e as ApprovalBlock, f as ApprovalRequestMessage, g as ApprovalStatus, h as ApprovalsResponse, i as ApproveReviewResponse, j as AskOptions, l as AssignmentIssue, o as AutoMergeTrigger, B as BlockingSubject, C as CHAT_COMMANDS, p as CHECKPOINT_TRUNCATE_LENGTH, q as CancelPlanningResponse, r as CancelResumeResponse, s as CliAgentAiService, t as CliAgentAiServiceDeps, u as CommandBlock, v as CommandDescriptor, w as CommandStatus, x as CommandsResponse, y as CompactionBlock, z as ConversationBusyError, D as ConversationCompactResponse, F as ConversationEditError, G as ConversationForkResponse, H as ConversationInput, J as ConversationRewindResponse, L as ConversationView, M as DEFAULT_WEB_READ_BUDGET, N as DaemonErrorCode, O as DecideOptions, P as DiffRow, Q as DiffRowKind, R as DiffStat, S as DisplayBlock, T as EMPTY_CONVERSATION, U as EMPTY_HOLD, V as EMPTY_RUN, W as EMPTY_TASK_LOG, X as EMPTY_TASK_LOG_FOLLOW, Y as ErrorBody, Z as ExecuteResponse, _ as ExecutionSummary, $ as ForceSendResponse, a0 as GatedConversation, a1 as GeneratePlanResponse, a3 as HEADLESS_CLI_COMMANDS, a4 as HeldEdit, a5 as HeldEditMark, a9 as IsolationDiffResponse, aa as IsolationMergeResponse, ac as LiveOutputLookup, af as LocalEntry, ag as MarkdownToken, ah as MergeGateEntry, ai as MergeGateResponse, aj as MessageBlock, ak as MessageRole, al as ModelsResponse, am as NOT_STARTED, an as NO_TURN, ao as NewTaskFields, ap as NotificationAction, aq as OUTPUT_LINES_DEFAULT, ar as OUTPUT_LINES_MAX, as as OkResponse, au as OutputPreview, ax as PendingApprovalsOptions, ay as PlanBlock, az as PlanMarkerStatus, aA as PlanResponse, aB as PlanSnapshot, aD as PlannerCommandSyntax, aH as PlannerModelChoice, aI as PlannerModelMemory, aM as PlannerNotReady, aN as PlannerNotReadyError, aO as PlannerReadinessConfig, aP as PlannerSubmission, aQ as PlannerTurnDiscardedError, aR as PlannerTurnStoppedError, aS as PlannerUsageLimitError, aT as PrdResponse, aU as PromptHold, aV as RUN_SETTINGS_DEFAULTS, aX as RemoveMessageResponse, aZ as ResolveConflictResponse, a$ as RewindTargetsResponse, b0 as RunInput, b2 as RunSettingsError, b3 as RunSnapshotFrame, b4 as RunTask, b5 as RunTaskStatus, b8 as RunnerLoadedBlock, b9 as RunnersResponse, ba as STOPPED_BEFORE_START, bb as SUPERVISOR_LEVEL_LABEL, bc as SerializedConversationMessage, bd as SerializedPendingTurn, be as SerializedPlan, bf as SerializedTask, bg as SerializedTaskStatus, bi as SessionData, bj as SessionFrame, bk as SessionListResponse, bo as SessionResponse, bp as SettingsResponse, bq as SettingsService, br as SettingsUpdateResponse, bs as SkillInvocation, bt as SkillLoadBlock, bu as SkillToken, bx as StopResponse, by as StreamStamp, bz as SubagentBlock, bA as SubagentChild, bB as SubagentStatus, bC as SurfacePlan, bD as SurfacePlanState, bE as SurfaceTask, bF as TASK_QUERY_ANSWER_MAX_CHARS, bG as TASK_QUERY_ANSWER_OR_OPS, bH as TASK_QUERY_FIELDS, bI as TASK_QUERY_PROTOCOL, bJ as TASK_QUERY_REMINDER, bK as TERMINAL_UI_COMMANDS, bL as TakenPrompt, bM as TaskAttemptSnapshot, bN as TaskControlError, bO as TaskLogAttemptsResponse, bP as TaskLogBatch, bR as TaskLogFollow, bS as TaskLogFollowInput, bT as TaskLogResponse, bU as TaskLogView, bV as TaskMessageResponse, bW as TaskOp, bY as TaskOrchestratorDeps, bZ as TaskOrchestratorOptions, b$ as TaskPlacement, c0 as TaskQuery, c2 as TaskQueryField, c3 as TaskRef, c4 as TaskRowAction, c5 as TaskRowContext, c6 as TaskRowIsolation, c7 as TaskRowKind, c8 as TaskRowPlacement, c9 as TaskRowSubject, ca as TaskRowUsage, cb as TaskRowView, cc as TaskStartResponse, cd as TaskStatusKind, ce as ThinkingDisplayBlock, cf as ToolBlock, cg as ToolHeadline, ch as ToolStatus, ci as TreeTask, cj as TurnGate, ck as UsageBlock, cm as WAITS_FOR_APPROVAL_LABEL, cq as Worded, cr as WorkspacesResponse, cs as abbreviateHome, ct as aheadOfDraft, cu as applyTaskOps, cv as approvalLabel, cw as assignmentIssue, cx as assignmentIssueText, cy as automergeSummary, cz as autorunSummary, cA as awaitingLabel, cB as blockedByLabel, cC as blockingFailures, cD as canMergeTasks, cE as canSetDependencies, cF as canSplitTask, cG as capConflictFiles, cH as classifyOutcome, cI as coalesceTaskLog, cJ as createAiService, cK as dependencyCandidates, cL as dependentsNotice, cM as dependentsOf, cN as describePlannerNotReady, cO as diffRows, cP as diffStat, cQ as diffSummary, cR as digestTaskLog, cS as drainNext, cT as executionSummary, cU as followTaskLog, cV as followTurn, cW as fromTranscript, cX as getSettingsPath, cY as hasHiddenDetail, cZ as holdPrompt, c_ as isTaskRunning, c$ as loadedSkillTokens, d0 as markAction, d1 as markRequestFor, d2 as markdownHtml, d3 as markdownTokens, d4 as namedRepos, d5 as newTaskFields, d6 as opsEditable, d7 as outputLines, d8 as outputPreview, d9 as parseCount, da as parseSwitch, db as parseTaskOpsJson, dc as parseTaskQueryJson, dd as pastGateConfirmation, de as plannerMessage, df as plannerNotReady, dg as plannerNotReadyFor, dh as plannerTranscript, di as reconcileApprovals, dj as reduceConversation, dk as reduceRun, dl as reduceTaskLog, dm as renderTaskQueryAnswer, dn as replayTaskLog, dp as resolveSkillInvocation, dq as resolveTaskRef, dr as resolveUserTaskRef, ds as resumeLabel, dt as resumeTime, du as runSettingsOf, dv as runnerToolSubject, dw as serializePlan, dx as serializeTask, dy as serializeTaskStatus, dz as skillTokens, dA as skippedLabel, dB as stopTurn, dC as subtreeIds, dD as summarizeToolCall, dE as supervisorSummary, dF as surfacePlan, dG as surfacePlanState, dH as takeAt, dI as taskLogForSurface, dJ as taskOrderLabel, dK as taskPlacement, dL as taskQuerySignature, dM as taskRef, dN as taskRefOf, dO as taskRowActions, dP as taskRowView, dQ as taskStartedNotice, dR as taskStatusKind, dS as textHasTaskOps, dT as textHasTaskQuery, dU as titledRefs, dV as titledTaskRef, dW as titledTaskRefOf, dX as toTaskLogEvent, dY as toolHeadline, dZ as trimToolOutput, d_ as truncateCheckpointSummary, d$ as unsendAll, e0 as unsendLatest, e1 as walkPlan } from './runSettingsText-rLoYQlUH.mjs';
5
- import { j as ApprovalDecision, J as IApproval, L as IFileSystem, ak as ResearchShell, aj as ReadFileOpts, aU as ToolOutcome, H as GrepOptions, B as GlobOptions, y as FindSymbolOptions, M as IRunner, K as IConfig, a9 as PlannerBackendId, af as ProviderModelLists, f as AiProvider, m as ApprovalModeSetting, ac as PlannerToolHandler, ay as RunnerRegistry, a3 as OrchestratorOption, d as AgentProcessDeps, aM as TaskModeAgentAdapter, a as AgentAdapter, e as AgentStartOptions, c as AgentEvent, ap as RunnerCommand, ad as ProjectMcpServer, N as IRunnerSession, n as ApprovalPolicy, i as ApprovalAnswer, a4 as OrdewellMcpServer, aJ as TaskCompleteArgs, r as CheckpointAnswer, aE as StructuredTurnEnd, aD as StructuredEvent, aL as TaskMessageFrom, ah as QueuedTaskMessage, aR as TaskStartOptions, aS as TaskTokenScope, at as RunnerManifest, aQ as TaskRunnerFlags } from './IFileSystem-C9W5mRYA.mjs';
6
- export { A as AUTO_COMMANDS, b as AgentAdapterFactory, g as AllProviderModels, h as AnswerApprovalArgs, k as ApprovalKind, l as ApprovalMode, o as ApprovalPolicyOptions, p as ApprovalRequest, q as ApprovalSource, C as CatalogModel, s as CheckpointArgs, t as CommandClassification, u as CommandTier, v as CommandWords, D as DEFAULT_PLANNER_ALLOWLIST, w as DENY_ALL, x as DiscoveryCommand, E as EditPlanArgs, F as FetchAllProviderModelsOptions, G as GIT_READONLY_SUBCOMMANDS, z as GREP_DEFAULT_HEAD_LIMIT, I as GrepOutputMode, O as InvokedCommand, P as LineBuffer, Q as ListModelsArgs, R as ListRunnersArgs, S as LoadSkillArgs, T as McpClientConfig, U as McpCredential, V as McpTool, W as McpToolContext, X as McpToolReply, Y as MessageTaskArgs, Z as ModelCatalog, _ as ModelShortcut, $ as ORCHESTRATOR_SHORTCUTS, a0 as ORDEWELL_MCP_PATH, a1 as ORDEWELL_MCP_SERVER_NAME, a2 as OneTaskArgs, a5 as OwnerOnlyFile, a6 as PLANNER_EXECUTION_TOOLS, a7 as PLANNER_TOOLS, a8 as PlannerAllowlist, aa as PlannerStartOptions, ab as PlannerTokenScope, ae as ProviderCredentialSource, ag as ProviderModelsResult, ai as REFUSED_COMMANDS, al as ResearchShellDeps, am as RetryTaskArgs, an as RunCommandArgs, ao as RunPlanArgs, aq as RunnerCommandKind, ar as RunnerEntry, as as RunnerFeatures, au as RunnerMcpServer, av as RunnerMode, aw as RunnerModelDiscovery, ax as RunnerModelRef, az as SEARCH_EXCLUSIONS, aA as ShellDialect, aB as SpawnFn, aC as StandingDecision, aF as SubmitPlanArgs, aG as TASK_COMPLETE_TOOL, aH as TASK_COMPLETION_CONTRACT, aI as TASK_TOOLS, aK as TaskDiffArgs, aN as TaskModeUnsupportedError, aO as TaskOutputArgs, aP as TaskQueryArgs, aT as TaskToolHandler, aW as approvalScopes, aX as classifyCommand, aY as clearResearchShellCache, aZ as collectProviderCredentials, a_ as commandAllowedBy, a$ as effectiveApprovalMode, b0 as enabledRunners, b1 as fetchAllProviderModels, b2 as findRunnerCommand, b3 as isGranted, b4 as isRunnerApproval, b5 as knownModelId, b6 as mcpClientConfig, b7 as ownerOnlyConfigFile, b8 as parseAllowlist, b9 as parseApprovalModeSetting, ba as researchShellWarning, bb as researchToolsPath, bc as resolveModelShortcut, bd as resolveProvider, be as resolveResearchShell, bf as scopeAllowed, bg as sharedMcpServer, bh as toApprovalDecision, bi as toOrchestratorOptions, bj as toolAllowed } from './IFileSystem-C9W5mRYA.mjs';
7
- import { R as RunnerModeInfo } from './ModeResolver-C1PN5FYG.mjs';
8
- export { a as autonomyLevelLabel, p as parseAutonomyLevel, r as runnerModesFrom } from './ModeResolver-C1PN5FYG.mjs';
1
+ import { t as IsolationMergeResult, am as Task, E as ExecutionActor, h as ExecutionRecord, i as GuardTrip, al as SupervisorLevel, g as ExecutionCommandName, G as GuardTarget, p as IsolationLandedTask, I as IWorktreeIsolation, J as IsolationTaskStatus, N as PlanIsolation, a7 as RunnerId, a2 as ResearchProgress, az as UsageRecord, a1 as ResearchLogEntry, f as DiscoveredModel, L as LegacyPlanState, a8 as RunnerSessionCost, a5 as ResearchToolType, a0 as ReportedWindow, T as PlannerUsage, at as TaskSkillSnapshot, aj as SkillsService, au as TaskSnapshot, O as PlanState, K as IsolationView, aB as Verdict } from './Task-CfBM0wkV.mjs';
2
+ export { A as ApprovalRecord, a as AttemptUsage, b as AwaitingReason, B as BUILTIN_SKILL_NAMES, C as ContextFill, c as ConversationMessage, d as CostProvenance, D as DEFAULT_RUNNERS, e as DEFAULT_SUPERVISOR_RETRY_LIMIT, j as IntegrationDisposal, k as InvalidSkill, l as IsolationAvailability, m as IsolationHandoff, n as IsolationHandoffRepo, o as IsolationInactiveReason, q as IsolationLanding, r as IsolationMergeBlock, s as IsolationMergeBlockReason, u as IsolationOutcome, v as IsolationPruneResult, w as IsolationRemoval, x as IsolationRepo, y as IsolationRun, z as IsolationTaskRecord, F as IsolationTaskRef, H as IsolationTaskRepo, M as ModelUsage, Q as PlanStatus, R as PlanUsage, S as PlannerResendState, U as PrepareIntent, V as PreparedTask, W as PreservedWork, X as PreviousWork, Y as RefusedRemoval, Z as RepairEvidence, _ as ReplyRun, $ as RepoGroupLayout, a3 as ResearchStep, a4 as ResearchStepOutcome, a6 as RunSettings, a9 as SessionBilling, aa as SetupFailure, ab as ShadowedSkill, ac as SkillAppliesTo, ad as SkillCatalog, ae as SkillInfo, af as SkillLoad, ag as SkillLoadNotice, ah as SkillMetadata, ai as SkillSource, ap as TaskIsolation, aq as TaskIsolationState, ar as TaskModelAssignment, av as TaskStatus, aw as TaskUsageSummary, ax as TreeSnapshot, ay as UsageLine, aA as UsageTotals, aC as VerificationCheck, aD as addAttemptUsage, aE as addModelUsage, aF as addPlannerUsage, aG as addUsage, aH as addUsageTotals, aI as contextMeterText, aJ as contextMeterTitle, aK as costText, aL as countedSessionCost, aM as createEmptyPlan, aN as createSkillsService, aO as createTask, aP as endAttemptUsage, aQ as flattenTasks, aR as flattenTasksWithParents, aS as formatCost, aT as formatTokenCount, aU as isAwaitingReason, aV as isMeasured, aW as isSupervisorLevel, aX as isUserMessage, aY as migratePlanState, aZ as modelCostTitle, a_ as partedPromptUsage, a$ as pausedOnLimit, b0 as planUsage, b1 as plannerContextFill, b2 as rejoinPlanTree, b3 as resumedSessionWindow, b4 as startAttemptUsage, b5 as subagentCostTitle, b6 as taskUsageSummary, b7 as tasksTotalText, b8 as usageLine, b9 as usageText, ba as waitsForApproval } from './Task-CfBM0wkV.mjs';
3
+ import { bv as StartAdmission, bw as StartWait, aY as ResolveAll, a8 as IWebFetcher, cp as WebReadPolicy, cn as WebRead, co as WebReadDecision, aw as PendingApprovals, K as ConversationTurn, aL as PlannerModes, a6 as IAiService, I as ConversationRequest, n as AssignmentWriter, m as AssignmentScope, c1 as TaskQueryCatalog, k as AssignmentCatalog, b7 as RunnerCatalog, bl as SessionMessage, bh as SessionBroadcaster, bn as SessionNotice, aC as PlanStore, bX as TaskOrchestrator, ab as IsolationRunController, at as OrchestratorObserver, bQ as TaskLogEvent, a7 as INotification, a2 as GlobalRunSettings, aF as PlannerConversationHost, aE as PlannerConversation, av as PendingApproval, E as ConversationCompaction, a_ as RewindTarget, b6 as RunView, b1 as RunMergeView, b_ as TaskOutputSource, cl as UserSettings, ae as LiveTailOptions, ad as LiveTail, bm as SessionMeta, aK as PlannerModelStore, aJ as PlannerModelRecall, aG as PlannerModelCandidate } from './runSettingsText-Jb_efnI4.mjs';
4
+ export { A as ACT_RISK, a as AUTORUN_RISK, b as AdoptSessionResponse, c as ApplyTaskOpsResult, d as ApprovalAnswerResponse, e as ApprovalBlock, f as ApprovalRequestMessage, g as ApprovalStatus, h as ApprovalsResponse, i as ApproveReviewResponse, j as AskOptions, l as AssignmentIssue, o as AutoMergeTrigger, B as BlockingSubject, C as CHAT_COMMANDS, p as CHECKPOINT_TRUNCATE_LENGTH, q as CancelPlanningResponse, r as CancelResumeResponse, s as CliAgentAiService, t as CliAgentAiServiceDeps, u as CommandBlock, v as CommandDescriptor, w as CommandStatus, x as CommandsResponse, y as CompactionBlock, z as ConversationBusyError, D as ConversationCompactResponse, F as ConversationEditError, G as ConversationForkResponse, H as ConversationInput, J as ConversationRewindResponse, L as ConversationView, M as DEFAULT_WEB_READ_BUDGET, N as DaemonErrorCode, O as DecideOptions, P as DiffRow, Q as DiffRowKind, R as DiffStat, S as DisplayBlock, T as EMPTY_CONVERSATION, U as EMPTY_HOLD, V as EMPTY_RUN, W as EMPTY_TASK_LOG, X as EMPTY_TASK_LOG_FOLLOW, Y as ErrorBody, Z as ExecuteResponse, _ as ExecutionSummary, $ as ForceSendResponse, a0 as GatedConversation, a1 as GeneratePlanResponse, a3 as HEADLESS_CLI_COMMANDS, a4 as HeldEdit, a5 as HeldEditMark, a9 as IsolationDiffResponse, aa as IsolationMergeResponse, ac as LiveOutputLookup, af as LocalEntry, ag as MarkdownToken, ah as MergeGateEntry, ai as MergeGateResponse, aj as MessageBlock, ak as MessageRole, al as ModelsResponse, am as NOT_STARTED, an as NO_TURN, ao as NewTaskFields, ap as NotificationAction, aq as OUTPUT_LINES_DEFAULT, ar as OUTPUT_LINES_MAX, as as OkResponse, au as OutputPreview, ax as PendingApprovalsOptions, ay as PlanBlock, az as PlanMarkerStatus, aA as PlanResponse, aB as PlanSnapshot, aD as PlannerCommandSyntax, aH as PlannerModelChoice, aI as PlannerModelMemory, aM as PlannerNotReady, aN as PlannerNotReadyError, aO as PlannerReadinessConfig, aP as PlannerSubmission, aQ as PlannerTurnDiscardedError, aR as PlannerTurnStoppedError, aS as PlannerUsageLimitError, aT as PrdResponse, aU as PromptHold, aV as RUN_SETTINGS_DEFAULTS, aX as RemoveMessageResponse, aZ as ResolveConflictResponse, a$ as RewindTargetsResponse, b0 as RunInput, b2 as RunSettingsError, b3 as RunSnapshotFrame, b4 as RunTask, b5 as RunTaskStatus, b8 as RunnerLoadedBlock, b9 as RunnersResponse, ba as STOPPED_BEFORE_START, bb as SUPERVISOR_LEVEL_LABEL, bc as SerializedConversationMessage, bd as SerializedPendingTurn, be as SerializedPlan, bf as SerializedTask, bg as SerializedTaskStatus, bi as SessionData, bj as SessionFrame, bk as SessionListResponse, bo as SessionResponse, bp as SettingsResponse, bq as SettingsService, br as SettingsUpdateResponse, bs as SkillInvocation, bt as SkillLoadBlock, bu as SkillToken, bx as StopResponse, by as StreamStamp, bz as SubagentBlock, bA as SubagentChild, bB as SubagentStatus, bC as SurfacePlan, bD as SurfacePlanState, bE as SurfaceTask, bF as TASK_QUERY_ANSWER_MAX_CHARS, bG as TASK_QUERY_ANSWER_OR_OPS, bH as TASK_QUERY_FIELDS, bI as TASK_QUERY_PROTOCOL, bJ as TASK_QUERY_REMINDER, bK as TERMINAL_UI_COMMANDS, bL as TakenPrompt, bM as TaskAttemptSnapshot, bN as TaskControlError, bO as TaskLogAttemptsResponse, bP as TaskLogBatch, bR as TaskLogFollow, bS as TaskLogFollowInput, bT as TaskLogResponse, bU as TaskLogView, bV as TaskMessageResponse, bW as TaskOp, bY as TaskOrchestratorDeps, bZ as TaskOrchestratorOptions, b$ as TaskPlacement, c0 as TaskQuery, c2 as TaskQueryField, c3 as TaskRef, c4 as TaskRowAction, c5 as TaskRowContext, c6 as TaskRowIsolation, c7 as TaskRowKind, c8 as TaskRowPlacement, c9 as TaskRowSubject, ca as TaskRowUsage, cb as TaskRowView, cc as TaskStartResponse, cd as TaskStatusKind, ce as ThinkingDisplayBlock, cf as ToolBlock, cg as ToolHeadline, ch as ToolStatus, ci as TreeTask, cj as TurnGate, ck as UsageBlock, cm as WAITS_FOR_APPROVAL_LABEL, cq as Worded, cr as WorkspacesResponse, cs as abbreviateHome, ct as aheadOfDraft, cu as applyTaskOps, cv as approvalLabel, cw as assignmentIssue, cx as assignmentIssueText, cy as automergeSummary, cz as autorunSummary, cA as awaitingLabel, cB as blockedByLabel, cC as blockingFailures, cD as canMergeTasks, cE as canSetDependencies, cF as canSplitTask, cG as capConflictFiles, cH as classifyOutcome, cI as coalesceTaskLog, cJ as createAiService, cK as dependencyCandidates, cL as dependentsNotice, cM as dependentsOf, cN as describePlannerNotReady, cO as diffRows, cP as diffStat, cQ as diffSummary, cR as digestTaskLog, cS as drainNext, cT as executionSummary, cU as followTaskLog, cV as followTurn, cW as fromTranscript, cX as getSettingsPath, cY as hasHiddenDetail, cZ as holdPrompt, c_ as isTaskRunning, c$ as loadedSkillTokens, d0 as markAction, d1 as markRequestFor, d2 as markdownHtml, d3 as markdownTokens, d4 as namedRepos, d5 as newTaskFields, d6 as opsEditable, d7 as outputLines, d8 as outputPreview, d9 as parseCount, da as parseSwitch, db as parseTaskOpsJson, dc as parseTaskQueryJson, dd as pastGateConfirmation, de as plannerMessage, df as plannerNotReady, dg as plannerNotReadyFor, dh as plannerTranscript, di as reconcileApprovals, dj as reduceConversation, dk as reduceRun, dl as reduceTaskLog, dm as renderTaskQueryAnswer, dn as replayTaskLog, dp as resolveSkillInvocation, dq as resolveTaskRef, dr as resolveUserTaskRef, ds as resumeLabel, dt as resumeTime, du as runSettingsOf, dv as runnerToolSubject, dw as serializePlan, dx as serializeTask, dy as serializeTaskStatus, dz as skillTokens, dA as skippedLabel, dB as stopTurn, dC as subtreeIds, dD as summarizeToolCall, dE as supervisorSummary, dF as surfacePlan, dG as surfacePlanState, dH as takeAt, dI as taskLogForSurface, dJ as taskOrderLabel, dK as taskPlacement, dL as taskQuerySignature, dM as taskRef, dN as taskRefOf, dO as taskRowActions, dP as taskRowView, dQ as taskStartedNotice, dR as taskStatusKind, dS as textHasTaskOps, dT as textHasTaskQuery, dU as titledRefs, dV as titledTaskRef, dW as titledTaskRefOf, dX as toTaskLogEvent, dY as toolHeadline, dZ as trimToolOutput, d_ as truncateCheckpointSummary, d$ as unsendAll, e0 as unsendLatest, e1 as walkPlan } from './runSettingsText-Jb_efnI4.mjs';
5
+ import { j as ApprovalDecision, J as IApproval, L as IFileSystem, ak as ResearchShell, aj as ReadFileOpts, aU as ToolOutcome, H as GrepOptions, B as GlobOptions, y as FindSymbolOptions, M as IRunner, K as IConfig, a9 as PlannerBackendId, af as ProviderModelLists, f as AiProvider, m as ApprovalModeSetting, ac as PlannerToolHandler, ay as RunnerRegistry, a3 as OrchestratorOption, d as AgentProcessDeps, aM as TaskModeAgentAdapter, a as AgentAdapter, e as AgentStartOptions, c as AgentEvent, ap as RunnerCommand, ad as ProjectMcpServer, N as IRunnerSession, n as ApprovalPolicy, i as ApprovalAnswer, a4 as OrdewellMcpServer, aJ as TaskCompleteArgs, r as CheckpointAnswer, aE as StructuredTurnEnd, aD as StructuredEvent, aL as TaskMessageFrom, ah as QueuedTaskMessage, aR as TaskStartOptions, aS as TaskTokenScope, at as RunnerManifest, aQ as TaskRunnerFlags } from './IFileSystem-1PqRCjhu.mjs';
6
+ export { A as AUTO_COMMANDS, b as AgentAdapterFactory, g as AllProviderModels, h as AnswerApprovalArgs, k as ApprovalKind, l as ApprovalMode, o as ApprovalPolicyOptions, p as ApprovalRequest, q as ApprovalSource, C as CatalogModel, s as CheckpointArgs, t as CommandClassification, u as CommandTier, v as CommandWords, D as DEFAULT_PLANNER_ALLOWLIST, w as DENY_ALL, x as DiscoveryCommand, E as EditPlanArgs, F as FetchAllProviderModelsOptions, G as GIT_READONLY_SUBCOMMANDS, z as GREP_DEFAULT_HEAD_LIMIT, I as GrepOutputMode, O as InvokedCommand, P as LineBuffer, Q as ListModelsArgs, R as ListRunnersArgs, S as LoadSkillArgs, T as McpClientConfig, U as McpCredential, V as McpTool, W as McpToolContext, X as McpToolReply, Y as MessageTaskArgs, Z as ModelCatalog, _ as ModelShortcut, $ as ORCHESTRATOR_SHORTCUTS, a0 as ORDEWELL_MCP_PATH, a1 as ORDEWELL_MCP_SERVER_NAME, a2 as OneTaskArgs, a5 as OwnerOnlyFile, a6 as PLANNER_EXECUTION_TOOLS, a7 as PLANNER_TOOLS, a8 as PlannerAllowlist, aa as PlannerStartOptions, ab as PlannerTokenScope, ae as ProviderCredentialSource, ag as ProviderModelsResult, ai as REFUSED_COMMANDS, al as ResearchShellDeps, am as RetryTaskArgs, an as RunCommandArgs, ao as RunPlanArgs, aq as RunnerCommandKind, ar as RunnerEntry, as as RunnerFeatures, au as RunnerMcpServer, av as RunnerMode, aw as RunnerModelDiscovery, ax as RunnerModelRef, az as SEARCH_EXCLUSIONS, aA as ShellDialect, aB as SpawnFn, aC as StandingDecision, aF as SubmitPlanArgs, aG as TASK_COMPLETE_TOOL, aH as TASK_COMPLETION_CONTRACT, aI as TASK_TOOLS, aK as TaskDiffArgs, aN as TaskModeUnsupportedError, aO as TaskOutputArgs, aP as TaskQueryArgs, aT as TaskToolHandler, aW as approvalScopes, aX as classifyCommand, aY as clearResearchShellCache, aZ as collectProviderCredentials, a_ as commandAllowedBy, a$ as effectiveApprovalMode, b0 as enabledRunners, b1 as fetchAllProviderModels, b2 as findRunnerCommand, b3 as isGranted, b4 as isRunnerApproval, b5 as knownModelId, b6 as mcpClientConfig, b7 as ownerOnlyConfigFile, b8 as parseAllowlist, b9 as parseApprovalModeSetting, ba as researchShellWarning, bb as researchToolsPath, bc as resolveModelShortcut, bd as resolveProvider, be as resolveResearchShell, bf as scopeAllowed, bg as sharedMcpServer, bh as toApprovalDecision, bi as toOrchestratorOptions, bj as toolAllowed } from './IFileSystem-1PqRCjhu.mjs';
7
+ import { R as RunnerModeInfo } from './ModeResolver-6TQXVsde.mjs';
8
+ export { a as autonomyLevelLabel, p as parseAutonomyLevel, r as runnerModesFrom } from './ModeResolver-6TQXVsde.mjs';
9
9
  import { ChildProcess } from 'child_process';
10
10
  import { EventEmitter } from 'events';
11
11
  import 'zod/v4';
@@ -914,8 +914,8 @@ interface ResolvedPlanner extends ResolvedChoice {
914
914
  interface ConfiguredPlanner extends PlannerChoice {
915
915
  setting?: string;
916
916
  /**
917
- * The planner a `/model` or `/planner` pick in this session made the model
918
- * for. A pick belongs to that planner alone: once routing moves (its key
917
+ * The planner a `/planner` pick in this session made the model for. A pick
918
+ * belongs to that planner alone: once routing moves (its key
919
919
  * removed), the model is configuration left for when it comes back, not a
920
920
  * choice the planner now in effect made.
921
921
  */
@@ -1837,16 +1837,27 @@ declare class ClaudeCodeAdapter extends StdioAgentAdapter implements TaskModeAge
1837
1837
  private replyRuns;
1838
1838
  /** The model answering the planner's current message, and the message's id, as its `message_start` named them. */
1839
1839
  private plannerModel;
1840
+ /**
1841
+ * The id the turn runs as, as `init` names it. A `[1m]` variant is the
1842
+ * selected id, while a message names the API's canonical id without it.
1843
+ */
1844
+ private sessionModel;
1845
+ private billing;
1840
1846
  private streamingMessage;
1841
1847
  /** The message the last `assistant` line was part of, and how many of its blocks the lines have carried. */
1842
1848
  private lineMessage;
1843
1849
  /**
1844
- * The session's `total_cost_usd` as last counted. A resume starts from what
1845
- * was counted of that session before, and is undefined without it: the CLI
1846
- * restores the session's running total, which holds turns counted earlier.
1850
+ * What has been counted of the session's running cost: a resume starts from
1851
+ * it, and it is undefined without a kept count — the next result then only
1852
+ * sets the baseline, since the CLI restores spend from turns before it. It
1853
+ * grows by what each result is counted for, never by a total that includes
1854
+ * cost the runner marked unknown, so that spend can be counted when its basis
1855
+ * is reported; and it never lowers, since counted dollars are not un-spent.
1847
1856
  */
1848
1857
  private reportedCostUsd;
1849
1858
  private reportedModelCostUsd;
1859
+ /** What this turn's streamed calls already reported, so its result only adds what did not stream. */
1860
+ private turnCallUsage;
1850
1861
  /**
1851
1862
  * Subagents started and not yet finished, keyed by the `Agent` call's id.
1852
1863
  * Kept across turns: a backgrounded one reports after its turn has ended.
@@ -1899,6 +1910,11 @@ declare class ClaudeCodeAdapter extends StdioAgentAdapter implements TaskModeAge
1899
1910
  private modelCommands;
1900
1911
  protected spawnSpec(opts: AgentStartOptions, workspace: Record<string, string>): SpawnSpec;
1901
1912
  sessionCost(): RunnerSessionCost | null;
1913
+ /**
1914
+ * A cleared conversation's totals start again from zero, so what follows is
1915
+ * all new spend, even for a resume that had no count kept.
1916
+ */
1917
+ private restartCount;
1902
1918
  /** A count kept for another session says nothing of this one's. */
1903
1919
  private countFrom;
1904
1920
  savedOutput(abs: string): boolean;
@@ -1943,6 +1959,13 @@ declare class ClaudeCodeAdapter extends StdioAgentAdapter implements TaskModeAge
1943
1959
  * as an interrupted `turn_end`.
1944
1960
  */
1945
1961
  interrupt(timeoutMs: number): Promise<boolean>;
1962
+ /**
1963
+ * On stdin's end the CLI exits by itself once its turn has closed, and only
1964
+ * an exit of its own saves the session's running totals for a `--resume` to
1965
+ * restore (checked on 2.1.303: about a second later, code 0, or 1 after an
1966
+ * interrupted turn).
1967
+ */
1968
+ endInput(): void;
1946
1969
  /**
1947
1970
  * A `user` line written mid-turn is Claude Code's own queue (ADR-0023): the
1948
1971
  * CLI attaches it to the next tool result, or runs it as a turn of its own
@@ -2051,6 +2074,22 @@ declare class ClaudeCodeAdapter extends StdioAgentAdapter implements TaskModeAge
2051
2074
  * {@link AgentEvent}), so nothing here has to reconcile with it.
2052
2075
  */
2053
2076
  private handleStreamEvent;
2077
+ /**
2078
+ * The id a reported model runs as. `init` names the selected value — a
2079
+ * `[1m]` variant included — while a message names the API's canonical id
2080
+ * without it. Keeping the variant is what lets the meter find the window
2081
+ * `modelUsage` keys it by, and keeps that window off the base model.
2082
+ */
2083
+ private modelId;
2084
+ private reportBilling;
2085
+ /**
2086
+ * A turn's `result` states its own token sum. Every call that streamed its
2087
+ * `message_delta` usage has already reported, so only the remainder is added:
2088
+ * all of it when nothing streamed (a recording without partial messages), or
2089
+ * a lost call's share. It is a sum across calls, marked `aggregate` so it
2090
+ * never moves the meter — only a call says what the context was left at.
2091
+ */
2092
+ private reportUnstreamedUsage;
2054
2093
  /**
2055
2094
  * What only the result line knows: the cost, which covers every call the
2056
2095
  * session made — subagents included, since none of their lines carries one —
@@ -2059,6 +2098,19 @@ declare class ClaudeCodeAdapter extends StdioAgentAdapter implements TaskModeAge
2059
2098
  * the session before; with no count kept, the first turn only sets the
2060
2099
  * baseline: its total includes turns counted before, and a turn's own share
2061
2100
  * cannot be told apart from them.
2101
+ *
2102
+ * The running total never lowers: money already reported and counted is not
2103
+ * un-spent because a later or resumed process remembers less of it, and
2104
+ * counting its return would count the same dollars twice. A zero is not a
2105
+ * measurement at all — a crash can end with one — and only `/clear` restarts
2106
+ * the count, through {@link restartCount}. Per-model baselines never lower
2107
+ * either, for the same reason.
2108
+ *
2109
+ * A report without a model breakdown is counted as a session total; one with
2110
+ * a breakdown is counted per model. A breakdown that would count more than
2111
+ * the session total's own growth (the count before it had no model split, or
2112
+ * a lossy report) is counted as that growth alone, so the two shapes
2113
+ * together still add each dollar once.
2062
2114
  */
2063
2115
  private reportSessionCost;
2064
2116
  }
@@ -2222,6 +2274,13 @@ declare class CodexAdapter extends StdioAgentAdapter implements TaskModeAgentAda
2222
2274
  * `last.outputTokens` already includes `reasoningOutputTokens` — the thread
2223
2275
  * total is `inputTokens + outputTokens`, not a sum of three — so reasoning is
2224
2276
  * not added a second time. Codex reports no price.
2277
+ *
2278
+ * The main thread's context is what Codex itself shows as in its window:
2279
+ * `TokenUsage::tokens_in_context_window`, which is `total_tokens` over
2280
+ * `last` as codex-rs defines it. `total_tokens` is input plus output, and
2281
+ * reasoning is part of output, so this is not `input + output − reasoning`
2282
+ * (checked against codex-rs and codex-cli 0.163.0's token_count events,
2283
+ * where `total_tokens` is `input_tokens + output_tokens`).
2225
2284
  */
2226
2285
  private emitUsage;
2227
2286
  /**
@@ -2700,6 +2759,27 @@ declare class SessionCatalog {
2700
2759
  * Ordewell. `source` is the record's reporter: a runner id or a vendor id.
2701
2760
  */
2702
2761
  type CatalogWindow = (source: string, model: string) => number | undefined;
2762
+ /**
2763
+ * The windows runners and providers reported over one Ordewell session, by
2764
+ * reporter and exact model id, shared by every stream of it: the planner's,
2765
+ * each task attempt's and each continue's. Claude Code states a window only on
2766
+ * a turn's last line, and a task is often one long turn, so without the
2767
+ * planner's or an earlier attempt's report on the same model the task would
2768
+ * have none for its whole run. Saved with the plan, so a reload knows them too.
2769
+ *
2770
+ * Holds only what a reporter stated — never a catalog's window, which the
2771
+ * catalog serves again, and never a table kept in Ordewell (ADR-0017 U1).
2772
+ */
2773
+ declare class SessionWindows {
2774
+ readonly catalog: CatalogWindow;
2775
+ private readonly reported;
2776
+ constructor(catalog?: CatalogWindow);
2777
+ report(source: string, model: string, contextWindow: number): void;
2778
+ get(source: string, model: string): number | undefined;
2779
+ snapshot(): ReportedWindow[];
2780
+ restore(saved: readonly ReportedWindow[] | undefined): void;
2781
+ clear(): void;
2782
+ }
2703
2783
 
2704
2784
  /** The `planner_usage` member of the session broadcast union. */
2705
2785
  type PlannerUsageMessage = Extract<SessionMessage, {
@@ -2715,18 +2795,18 @@ type PlannerUsageMessage = Extract<SessionMessage, {
2715
2795
  * defined — this module just holds the state and the broadcast shape.
2716
2796
  */
2717
2797
  declare class PlannerUsageLedger {
2718
- private readonly catalogWindow;
2798
+ private readonly sessionWindows;
2719
2799
  private usage;
2720
2800
  private windows;
2721
- /** `catalogWindow` serves the window of a planner model whose backend reports none. */
2722
- constructor(catalogWindow?: CatalogWindow);
2801
+ /** `sessionWindows` serves the window of a planner model whose backend reports none. */
2802
+ constructor(sessionWindows?: SessionWindows);
2723
2803
  /** Fold one model call's record into the totals; returns the running ledger. */
2724
2804
  record(record: UsageRecord): PlannerUsage;
2725
2805
  /** Adopt a persisted ledger (a reopened session) or start from zero. */
2726
2806
  restore(usage: PlannerUsage | undefined): void;
2727
2807
  /** Start a fresh session's ledger from zero. */
2728
2808
  clear(): void;
2729
- /** Whether anything has been recorded — a plan with no usage says nothing. */
2809
+ /** Whether the ledger has measures or session billing facts to broadcast. */
2730
2810
  get hasUsage(): boolean;
2731
2811
  /** The value persisted onto the plan state. */
2732
2812
  snapshot(): PlannerUsage;
@@ -2989,6 +3069,8 @@ interface SessionParts {
2989
3069
  runs: IsolationRunController;
2990
3070
  events: SessionEventRelay;
2991
3071
  usage: PlannerUsageLedger;
3072
+ /** The windows every stream of the session reports, saved with the plan. */
3073
+ windows: SessionWindows;
2992
3074
  approvals: PendingApprovals;
2993
3075
  approvalPolicy: ApprovalPolicy;
2994
3076
  /** Where the Session writes what it made of a task's event into that attempt's log. */
@@ -3014,6 +3096,7 @@ interface SessionParts {
3014
3096
  declare class Session {
3015
3097
  private readonly backend;
3016
3098
  private readonly usage;
3099
+ private readonly windows;
3017
3100
  private readonly events;
3018
3101
  private readonly planner;
3019
3102
  private readonly orchestrator;
@@ -3785,6 +3868,7 @@ declare abstract class AbstractRunnerSession implements IRunnerSession {
3785
3868
  onOutput(callback: (text: string) => void): void;
3786
3869
  onExit(callback: (code: number) => void): void;
3787
3870
  abstract kill(): void;
3871
+ abstract stop(): Promise<void>;
3788
3872
  abstract getOutput(): string;
3789
3873
  abstract write(text: string): void;
3790
3874
  abstract turnState(): 'working' | 'idle';
@@ -3806,7 +3890,8 @@ declare abstract class AbstractRunnerSession implements IRunnerSession {
3806
3890
  declare abstract class AbstractRunner<S extends IRunnerSession> implements IRunner {
3807
3891
  protected sessions: Map<string, S>;
3808
3892
  get activeCount(): number;
3809
- stop(sessionId: string): void;
3893
+ /** A session winding down stays registered until it exits, so a second stop gets the same wind-down. */
3894
+ stop(sessionId: string): Promise<void>;
3810
3895
  stopAll(): void;
3811
3896
  protected registerSession(id: string, session: S): void;
3812
3897
  abstract spawn(opts: RunnerSpawnOptions): Promise<IRunnerSession>;
@@ -3856,12 +3941,17 @@ declare class StructuredSession extends AbstractRunnerSession {
3856
3941
  private readonly text;
3857
3942
  private state;
3858
3943
  private turn;
3944
+ /** A `task_complete` report waiting for its turn to close; the verdict is published then. */
3945
+ private completionReport;
3946
+ private completionTimer;
3859
3947
  /** A terminal event ends the turn before the adapter releases its send. */
3860
3948
  private sending;
3861
3949
  private turnCount;
3862
3950
  private queue;
3863
3951
  private messageCount;
3864
3952
  private interrupting;
3953
+ /** The wind-down once {@link stop} was asked for: the same for every caller, and nothing new is sent meanwhile. */
3954
+ private stopping;
3865
3955
  private lastSessionId;
3866
3956
  private lastSessionCost;
3867
3957
  private readonly structuredEmitter;
@@ -3904,6 +3994,21 @@ declare class StructuredSession extends AbstractRunnerSession {
3904
3994
  */
3905
3995
  write(text: string): void;
3906
3996
  kill(): void;
3997
+ stop(): Promise<void>;
3998
+ /**
3999
+ * The attempt is over (ADR-0018, L1), so what is still owed goes undelivered
4000
+ * and every tool request unanswered at once. A turn still open is
4001
+ * interrupted, and its close — where Claude Code reports the turn's cost and
4002
+ * its model's window — is waited for; then the runner is told nothing more
4003
+ * is coming and left to exit by itself. All of it within the interrupt
4004
+ * grace: a runner still there once it runs out is killed.
4005
+ */
4006
+ private windDown;
4007
+ /** Whether `turn` closed within the deadline once interrupted. */
4008
+ private turnClosed;
4009
+ /** Whether `done` settled before the deadline, or the session ended meanwhile. */
4010
+ private within;
4011
+ private gone;
3907
4012
  turnState(): 'working' | 'idle';
3908
4013
  onTurnEnd(listener: (reason: StructuredTurnEnd) => void): void;
3909
4014
  onEvent(listener: (event: StructuredEvent) => void): void;
@@ -3975,6 +4080,10 @@ declare class StructuredSession extends AbstractRunnerSession {
3975
4080
  private openPermission;
3976
4081
  private cancelPermission;
3977
4082
  private handleEvent;
4083
+ /** Publish a `task_complete` report whose turn has closed, or that waited out the grace. */
4084
+ private flushCompletion;
4085
+ /** A message the runner reads, or a turn it opens, voids a report made before it (ADR-0023, D6). */
4086
+ private discardCompletion;
3978
4087
  /**
3979
4088
  * A queued message goes out as the turn closes, and the state never passes
3980
4089
  * through `idle` on the way, so a listener told the turn ended can already
@@ -4438,7 +4547,7 @@ type PlannerModelLookup = Pick<PlannerModelStore, 'getPlannerModel'>;
4438
4547
  */
4439
4548
  declare function selectPlanner(current: PlannerSelectionCurrent, change: PlannerSelectionChange, memory: PlannerModelLookup, catalog: PlannerModelCandidate[]): PlannerSelectionResult;
4440
4549
 
4441
- /** How many AI tasks may run at once: `ORDEWELL_MAX_PARALLEL`, `/parallel`, `ordewell.maxParallelSessions`. */
4550
+ /** How many AI tasks may run at once: `ORDEWELL_MAX_PARALLEL`, `/settings`, `ordewell.maxParallelSessions`. */
4442
4551
  declare const DEFAULT_MAX_PARALLEL = 5;
4443
4552
  /**
4444
4553
  * A usable limit from what a user typed or a setting holds: any whole number
@@ -4448,4 +4557,4 @@ declare const DEFAULT_MAX_PARALLEL = 5;
4448
4557
  */
4449
4558
  declare function parseMaxParallel(value: unknown): number | null;
4450
4559
 
4451
- export { ALL_PROVIDERS, AbstractRunner, AbstractRunnerSession, type Adr0013IsolationRun, type Adr0013PlanIsolation, type Adr0013TaskRecord, AgentAdapter, AgentEvent, AgentProcessDeps, AgentStartOptions, AiProvider, AlreadyExecutingError, ApprovalAnswer, ApprovalDecision, ApprovalModeSetting, ApprovalPolicy, AssignmentScope, BaseAiService, BaseConfig, BaseFileSystem, BufferedTaskOutputSource, type ByPlannerBackend, CLAUDE_CODE_MANIFEST, CLI_PROVIDERS, CMD_EXE_MAX_COMMAND_LINE, CODEX_SANDBOX_DOCS, CODEX_SANDBOX_OFF_LINE, type CachedPage, type CappedRows, CheckpointAnswer, type CheckpointListener, ClaudeCodeAdapter, CodexAdapter, CodexSandboxAvailability, CommandLineTooLongError, type CommandOutcome, type CommandPayload, type ConfiguredPlanner, type Consent, ConsoleLogger, ContextCollector, type Continuability, ConversationCompaction, type ConversationFork, ConversationRequest, type ConversationRewind, ConversationTurn, DAEMON_SUBPROTOCOL, DAEMON_TOKEN_SUBPROTOCOL_PREFIX, DEFAULT_MAX_PARALLEL, type DirEntry, DiscoveredModel, DuckDuckGoSearchProvider, EmbeddedNewlineError, type EnvAdmission, EnvConfig, type ExecImpl, ExecutableNotFoundError, ExecutionActor, type ExecutionCommand, ExecutionCommandName, ExecutionCommands, type ExecutionHost, ExecutionRecord, FindSymbolOptions, GREP_PCRE_PROBE_ARGS, GeminiService, type GitExecFn, GlobOptions, GlobalRunSettings, type GrepInvocation, GrepOptions, type GrepRegex, GuardTarget, GuardTrip, HARNESS_PLANNER_REASON, type HasBinFn, HttpWebFetcher, type HttpWebFetcherOptions, IAiService, IApproval, IConfig, IFileSystem, type ILogger, INotification, IRunner, IRunnerSession, type ISearchProvider, IWorktreeIsolation, IsolationLandedTask, IsolationMergeResult, IsolationTaskStatus, IsolationView, type KillTreeDeps, type LaunchDeps, type LaunchPlan, LegacyPlanState, LiveTail, LiveTailOptions, type LoopGuard, type MappedTool, type MergeWordingHandoff, ModelResolver, type ModelResolverDeps, NoPlanError, OPENCODE_MANIFEST, ORDEWELL_SETTABLE_ENV, OpenAiService, OpenCodeAdapter, OrchestratorObserver, OrchestratorOption, OrdewellMcpServer, PROVIDER_CREDENTIAL_ENV, PROVIDER_DETECT_PRIORITY, PROVIDER_LABEL, PROVIDER_PRIORITY, PROVIDER_SHORT_LABEL, PendingApproval, PendingApprovals, PlanEditError, PlanIsolation, type PlanRequest, PlanState, PlanStore, Planner, type PlannerBackendEntry, PlannerBackendId, type PlannerChoice, PlannerModelCandidate, type PlannerModelLookup, PlannerModelRecall, type PlannerModelSource, PlannerModelStore, type PlannerSelectionChange, type PlannerSelectionCurrent, type PlannerSelectionResult, type PlannerSelectionState, PlannerToolHandler, type PlannerUsability, PlannerUsage, type PrdBlock, ProviderModelLists, type ProviderRegistration, QueuedTaskMessage, ReadFileOpts, type ResearchChat, ResearchLogEntry, ResearchShell, type ResearchTurn, type ResolvedChoice, type ResolvedPlanner, RewindTarget, RunMergeView, RunView, RunnerApprovals, RunnerCommand, RunnerId, RunnerInstallation, RunnerManifest, RunnerModeInfo, RunnerRegistry, RunnerSessionCost, type RunnerSpawnOptions, SETTINGS_ENV_ALLOWLIST, SETTINGS_ENV_REFUSED, STATE_DIR, STATE_DIR_IGNORE, STOPPED_TOOL_RESULT, SUPERVISOR_LEVELS, SYMBOL_LANGUAGES, type SaveSession, type SavedState, type SearchHit, type SearchOutcome, type SearchPage, type SearchTransport, Session, SessionBroadcaster, type SessionDeps, SessionMessage, SessionMeta, SessionNotFoundError, SessionNotice, type SessionPlanner, type SessionRuntimeSettings, SkillsService, type SpawnSpec, StartAdmission, StdioAgentAdapter, StructuredEvent, StructuredRunner, type StructuredRunnerDeps, StructuredSession, StructuredTurnEnd, SupervisorLevel, type SupervisorPolicy, Task, TaskCompleteArgs, TaskLogEvent, type TaskLogFile, type TaskLogLocation, TaskLogRecorder, type TaskLogRecorderDeps, TaskMessageFrom, TaskModeAgentAdapter, TaskOrchestrator, TaskOutputSource, TaskQueryCatalog, TaskRunnerFlags, TaskStartOptions, TaskTokenScope, type TokenCarriers, type ToolCall, ToolOutcome, type ToolResult, UsageRecord, UserSettings, VerdictEngine, type VerdictListener, WINDOWS_MAX_COMMAND_LINE, WebRead, WebReadDecision, type WebResponse, WebResponseCache, type WebResponseCacheOptions, type WebTransport, type WorkspaceCheckDeps, WorkspaceNotAProjectError, WorkspaceNotFoundError, type WorkspaceProjectCheckDeps, type WorktreeIsolationDeps, admitSettingsEnv, applyHeadLimit, assertWorkspaceExists, assertWorkspaceIsProject, augmentedPath, bearerHeaderValue, buildFallbackGrepArgs, buildGlobArgs, buildGrepArgs, canContinue, checkoutRule, clearAugmentedPathCache, clearDaemonToken, clearState, clipboardCopyCommand, codexSandboxNotice, configuredProviders, continuability, createSession, createTaskAdapter, createWorktreeIsolation, daemonTokenPath, defaultEnabledRunners, defaultLogger, definitionPattern, deleteSession, describeMergeResult, detectInstalledPlanner, discoverGeminiModels, ensureDir, ensurePrivateDir, ensureStateDirIgnored, extractPrdBlock, extractPresentedToken, filterFallbackByAnchoredInclude, findInstalledPlanner, formatSearchOutput, getLatestSession, getProviderMeta, getStateDir, globalDataDir, grantScopeFor, grepRegexFromProbe, idSegment, includeGlobFor, installedPlannerAnswered, installedPlannerDetected, isApiProvider, isCliProvider, isExecutableResolved, isOpenAiProvider, isPlannerBackend, isRepoGroup, isVendorModelFor, killTree, languageForId, listSessions, listTaskLogAttempts, listTree, loadSession, loadSessionPlanState, loadState, looksLikeChallenge, mapAgentTool, mergeTarget, migrateOldConfigDir, migratePlanIsolation, mintDaemonToken, mintSessionId, normalizeAgentArgs, normalizeGeminiModel, openTaskLog, parseMaxParallel, parseSearchHits, planDirectLaunch, plannerBackendEntries, prefixModelId, providerForRunner, readDaemonToken, readTaskLog, recordInstalledPlanner, recordedInstalledPlanner, referencePattern, removedPluginNotice, reposWithWork, resetInstalledPlanner, resolveProviderFromPrefix, resolveTaskRunnerFlags, resolveWithin, runnerForProvider, sanitizeSlug, savePrdMarkdown, saveSession, saveState, selectPlanner, sessionDataDir, sessionRuntimeSettings, sharedSearchProvider, sharedWebResponseCache, stateExists, stripAnsi, stripModelPrefix, supportsTaskMode, tokenSubprotocols, tokensMatch, wellKnownBinDirs, windowsCommandLine, withPath, writePrivateFile };
4560
+ export { ALL_PROVIDERS, AbstractRunner, AbstractRunnerSession, type Adr0013IsolationRun, type Adr0013PlanIsolation, type Adr0013TaskRecord, AgentAdapter, AgentEvent, AgentProcessDeps, AgentStartOptions, AiProvider, AlreadyExecutingError, ApprovalAnswer, ApprovalDecision, ApprovalModeSetting, ApprovalPolicy, AssignmentScope, BaseAiService, BaseConfig, BaseFileSystem, BufferedTaskOutputSource, type ByPlannerBackend, CLAUDE_CODE_MANIFEST, CLI_PROVIDERS, CMD_EXE_MAX_COMMAND_LINE, CODEX_SANDBOX_DOCS, CODEX_SANDBOX_OFF_LINE, type CachedPage, type CappedRows, CheckpointAnswer, type CheckpointListener, ClaudeCodeAdapter, CodexAdapter, CodexSandboxAvailability, CommandLineTooLongError, type CommandOutcome, type CommandPayload, type ConfiguredPlanner, type Consent, ConsoleLogger, ContextCollector, type Continuability, ConversationCompaction, type ConversationFork, ConversationRequest, type ConversationRewind, ConversationTurn, DAEMON_SUBPROTOCOL, DAEMON_TOKEN_SUBPROTOCOL_PREFIX, DEFAULT_MAX_PARALLEL, type DirEntry, DiscoveredModel, DuckDuckGoSearchProvider, EmbeddedNewlineError, type EnvAdmission, EnvConfig, type ExecImpl, ExecutableNotFoundError, ExecutionActor, type ExecutionCommand, ExecutionCommandName, ExecutionCommands, type ExecutionHost, ExecutionRecord, FindSymbolOptions, GREP_PCRE_PROBE_ARGS, GeminiService, type GitExecFn, GlobOptions, GlobalRunSettings, type GrepInvocation, GrepOptions, type GrepRegex, GuardTarget, GuardTrip, HARNESS_PLANNER_REASON, type HasBinFn, HttpWebFetcher, type HttpWebFetcherOptions, IAiService, IApproval, IConfig, IFileSystem, type ILogger, INotification, IRunner, IRunnerSession, type ISearchProvider, IWorktreeIsolation, IsolationLandedTask, IsolationMergeResult, IsolationTaskStatus, IsolationView, type KillTreeDeps, type LaunchDeps, type LaunchPlan, LegacyPlanState, LiveTail, LiveTailOptions, type LoopGuard, type MappedTool, type MergeWordingHandoff, ModelResolver, type ModelResolverDeps, NoPlanError, OPENCODE_MANIFEST, ORDEWELL_SETTABLE_ENV, OpenAiService, OpenCodeAdapter, OrchestratorObserver, OrchestratorOption, OrdewellMcpServer, PROVIDER_CREDENTIAL_ENV, PROVIDER_DETECT_PRIORITY, PROVIDER_LABEL, PROVIDER_PRIORITY, PROVIDER_SHORT_LABEL, PendingApproval, PendingApprovals, PlanEditError, PlanIsolation, type PlanRequest, PlanState, PlanStore, Planner, type PlannerBackendEntry, PlannerBackendId, type PlannerChoice, PlannerModelCandidate, type PlannerModelLookup, PlannerModelRecall, type PlannerModelSource, PlannerModelStore, type PlannerSelectionChange, type PlannerSelectionCurrent, type PlannerSelectionResult, type PlannerSelectionState, PlannerToolHandler, type PlannerUsability, PlannerUsage, type PrdBlock, ProviderModelLists, type ProviderRegistration, QueuedTaskMessage, ReadFileOpts, ReportedWindow, type ResearchChat, ResearchLogEntry, ResearchShell, type ResearchTurn, type ResolvedChoice, type ResolvedPlanner, RewindTarget, RunMergeView, RunView, RunnerApprovals, RunnerCommand, RunnerId, RunnerInstallation, RunnerManifest, RunnerModeInfo, RunnerRegistry, RunnerSessionCost, type RunnerSpawnOptions, SETTINGS_ENV_ALLOWLIST, SETTINGS_ENV_REFUSED, STATE_DIR, STATE_DIR_IGNORE, STOPPED_TOOL_RESULT, SUPERVISOR_LEVELS, SYMBOL_LANGUAGES, type SaveSession, type SavedState, type SearchHit, type SearchOutcome, type SearchPage, type SearchTransport, Session, SessionBroadcaster, type SessionDeps, SessionMessage, SessionMeta, SessionNotFoundError, SessionNotice, type SessionPlanner, type SessionRuntimeSettings, SkillsService, type SpawnSpec, StartAdmission, StdioAgentAdapter, StructuredEvent, StructuredRunner, type StructuredRunnerDeps, StructuredSession, StructuredTurnEnd, SupervisorLevel, type SupervisorPolicy, Task, TaskCompleteArgs, TaskLogEvent, type TaskLogFile, type TaskLogLocation, TaskLogRecorder, type TaskLogRecorderDeps, TaskMessageFrom, TaskModeAgentAdapter, TaskOrchestrator, TaskOutputSource, TaskQueryCatalog, TaskRunnerFlags, TaskStartOptions, TaskTokenScope, type TokenCarriers, type ToolCall, ToolOutcome, type ToolResult, UsageRecord, UserSettings, VerdictEngine, type VerdictListener, WINDOWS_MAX_COMMAND_LINE, WebRead, WebReadDecision, type WebResponse, WebResponseCache, type WebResponseCacheOptions, type WebTransport, type WorkspaceCheckDeps, WorkspaceNotAProjectError, WorkspaceNotFoundError, type WorkspaceProjectCheckDeps, type WorktreeIsolationDeps, admitSettingsEnv, applyHeadLimit, assertWorkspaceExists, assertWorkspaceIsProject, augmentedPath, bearerHeaderValue, buildFallbackGrepArgs, buildGlobArgs, buildGrepArgs, canContinue, checkoutRule, clearAugmentedPathCache, clearDaemonToken, clearState, clipboardCopyCommand, codexSandboxNotice, configuredProviders, continuability, createSession, createTaskAdapter, createWorktreeIsolation, daemonTokenPath, defaultEnabledRunners, defaultLogger, definitionPattern, deleteSession, describeMergeResult, detectInstalledPlanner, discoverGeminiModels, ensureDir, ensurePrivateDir, ensureStateDirIgnored, extractPrdBlock, extractPresentedToken, filterFallbackByAnchoredInclude, findInstalledPlanner, formatSearchOutput, getLatestSession, getProviderMeta, getStateDir, globalDataDir, grantScopeFor, grepRegexFromProbe, idSegment, includeGlobFor, installedPlannerAnswered, installedPlannerDetected, isApiProvider, isCliProvider, isExecutableResolved, isOpenAiProvider, isPlannerBackend, isRepoGroup, isVendorModelFor, killTree, languageForId, listSessions, listTaskLogAttempts, listTree, loadSession, loadSessionPlanState, loadState, looksLikeChallenge, mapAgentTool, mergeTarget, migrateOldConfigDir, migratePlanIsolation, mintDaemonToken, mintSessionId, normalizeAgentArgs, normalizeGeminiModel, openTaskLog, parseMaxParallel, parseSearchHits, planDirectLaunch, plannerBackendEntries, prefixModelId, providerForRunner, readDaemonToken, readTaskLog, recordInstalledPlanner, recordedInstalledPlanner, referencePattern, removedPluginNotice, reposWithWork, resetInstalledPlanner, resolveProviderFromPrefix, resolveTaskRunnerFlags, resolveWithin, runnerForProvider, sanitizeSlug, savePrdMarkdown, saveSession, saveState, selectPlanner, sessionDataDir, sessionRuntimeSettings, sharedSearchProvider, sharedWebResponseCache, stateExists, stripAnsi, stripModelPrefix, supportsTaskMode, tokenSubprotocols, tokensMatch, wellKnownBinDirs, windowsCommandLine, withPath, writePrivateFile };