@bastani/atomic 0.9.14-alpha.4 → 0.9.14-alpha.5

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 (141) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/dist/builtin/intercom/package.json +1 -1
  3. package/dist/builtin/mcp/package.json +1 -1
  4. package/dist/builtin/subagents/CHANGELOG.md +6 -0
  5. package/dist/builtin/subagents/package.json +1 -1
  6. package/dist/builtin/subagents/src/extension/schemas.ts +5 -0
  7. package/dist/builtin/subagents/src/runs/shared/long-running-guard.ts +3 -1
  8. package/dist/builtin/subagents/src/runs/shared/progress-trend.ts +69 -0
  9. package/dist/builtin/subagents/src/runs/shared/subagent-control.ts +12 -1
  10. package/dist/builtin/subagents/src/shared/types-results.ts +2 -0
  11. package/dist/builtin/web-access/package.json +1 -1
  12. package/dist/builtin/workflows/CHANGELOG.md +41 -1
  13. package/dist/builtin/workflows/README.md +6 -5
  14. package/dist/builtin/workflows/builtin/adversarial-verification-prompts.ts +13 -5
  15. package/dist/builtin/workflows/builtin/adversarial-verification-runner.ts +376 -89
  16. package/dist/builtin/workflows/builtin/adversarial-verification.d.ts +30 -6
  17. package/dist/builtin/workflows/builtin/adversarial-verification.ts +14 -9
  18. package/dist/builtin/workflows/builtin/generate-and-filter-prompts.ts +26 -3
  19. package/dist/builtin/workflows/builtin/generate-and-filter-runner.ts +18 -14
  20. package/dist/builtin/workflows/builtin/goal-artifacts.ts +9 -8
  21. package/dist/builtin/workflows/builtin/goal-convergence.ts +87 -0
  22. package/dist/builtin/workflows/builtin/goal-ledger.ts +4 -0
  23. package/dist/builtin/workflows/builtin/goal-prompts.ts +2 -0
  24. package/dist/builtin/workflows/builtin/goal-reducer.ts +6 -1
  25. package/dist/builtin/workflows/builtin/goal-reverify.ts +305 -0
  26. package/dist/builtin/workflows/builtin/goal-runner.ts +75 -10
  27. package/dist/builtin/workflows/builtin/goal-schemas.ts +7 -0
  28. package/dist/builtin/workflows/builtin/goal-types.ts +6 -0
  29. package/dist/builtin/workflows/builtin/loop-until-done-runner.ts +94 -6
  30. package/dist/builtin/workflows/builtin/loop-until-done.d.ts +8 -0
  31. package/dist/builtin/workflows/builtin/loop-until-done.ts +15 -0
  32. package/dist/builtin/workflows/builtin/progress-scoring.ts +230 -0
  33. package/dist/builtin/workflows/builtin/ralph-core.ts +11 -0
  34. package/dist/builtin/workflows/builtin/ralph-review-gate.ts +1 -0
  35. package/dist/builtin/workflows/builtin/ralph-reviewer-prompt.ts +2 -0
  36. package/dist/builtin/workflows/builtin/ralph-runner.ts +60 -10
  37. package/dist/builtin/workflows/builtin/selection-math.ts +156 -0
  38. package/dist/builtin/workflows/builtin/shared-prompts.ts +5 -0
  39. package/dist/builtin/workflows/builtin/tournament-prompts.ts +57 -75
  40. package/dist/builtin/workflows/builtin/tournament-runner.ts +384 -178
  41. package/dist/builtin/workflows/builtin/tournament.d.ts +46 -17
  42. package/dist/builtin/workflows/builtin/tournament.ts +66 -32
  43. package/dist/builtin/workflows/builtin/verification-criteria.ts +330 -0
  44. package/dist/builtin/workflows/builtin/verification-prompts.ts +206 -0
  45. package/dist/builtin/workflows/builtin/verification-usage.ts +44 -0
  46. package/dist/builtin/workflows/package.json +1 -1
  47. package/dist/builtin/workflows/skills/create-spec/SKILL.md +90 -30
  48. package/dist/builtin/workflows/skills/show-me/LICENSE.txt +21 -0
  49. package/dist/builtin/workflows/skills/show-me/SKILL.md +143 -0
  50. package/dist/builtin/workflows/src/authoring/workflow.ts +8 -0
  51. package/dist/builtin/workflows/src/authoring.d.ts +1 -1
  52. package/dist/builtin/workflows/src/durable/completed-catalog.ts +5 -2
  53. package/dist/builtin/workflows/src/durable/dbos-envelope.ts +1 -1
  54. package/dist/builtin/workflows/src/durable/resume-eligibility.ts +5 -3
  55. package/dist/builtin/workflows/src/durable/run-timing.ts +41 -10
  56. package/dist/builtin/workflows/src/durable/tool-primitive.ts +24 -2
  57. package/dist/builtin/workflows/src/engine/options.ts +1 -0
  58. package/dist/builtin/workflows/src/engine/primitives/workflow.ts +12 -3
  59. package/dist/builtin/workflows/src/engine/run-budget.ts +308 -0
  60. package/dist/builtin/workflows/src/engine/run-returned-status.ts +8 -0
  61. package/dist/builtin/workflows/src/engine/run-tool-node-lifecycle.ts +6 -0
  62. package/dist/builtin/workflows/src/engine/run.ts +124 -2
  63. package/dist/builtin/workflows/src/engine/runtime.ts +9 -0
  64. package/dist/builtin/workflows/src/extension/config-file-loader.ts +6 -0
  65. package/dist/builtin/workflows/src/extension/config-loader.ts +24 -1
  66. package/dist/builtin/workflows/src/extension/dispatcher.ts +6 -5
  67. package/dist/builtin/workflows/src/extension/extension-runtime-state.ts +2 -0
  68. package/dist/builtin/workflows/src/extension/index.bundle.mjs +2975 -843
  69. package/dist/builtin/workflows/src/extension/lifecycle-notifications.ts +51 -4
  70. package/dist/builtin/workflows/src/extension/public-types.ts +3 -1
  71. package/dist/builtin/workflows/src/extension/runtime-durable-resume.ts +7 -1
  72. package/dist/builtin/workflows/src/extension/runtime.ts +22 -10
  73. package/dist/builtin/workflows/src/extension/workflow-module-loader.ts +5 -0
  74. package/dist/builtin/workflows/src/extension/workflow-prompts.ts +1 -0
  75. package/dist/builtin/workflows/src/extension/workflow-schema.ts +16 -0
  76. package/dist/builtin/workflows/src/extension/workflow-status-summary.ts +44 -1
  77. package/dist/builtin/workflows/src/extension/workflow-tool-content.ts +10 -1
  78. package/dist/builtin/workflows/src/extension/workflow-tool-control.ts +21 -9
  79. package/dist/builtin/workflows/src/runs/foreground/executor-continuation.ts +14 -0
  80. package/dist/builtin/workflows/src/runs/foreground/executor-lifecycle.ts +15 -4
  81. package/dist/builtin/workflows/src/runs/foreground/executor-stage-call.ts +62 -5
  82. package/dist/builtin/workflows/src/runs/foreground/executor-stage-factory.ts +4 -0
  83. package/dist/builtin/workflows/src/runs/foreground/executor-stage-types.ts +2 -0
  84. package/dist/builtin/workflows/src/runs/foreground/executor-types.ts +3 -1
  85. package/dist/builtin/workflows/src/runs/foreground/stage-runner-controller.ts +10 -1
  86. package/dist/builtin/workflows/src/shared/authoring-contract-stage.d.ts +1 -0
  87. package/dist/builtin/workflows/src/shared/authoring-contract-stage.ts +1 -0
  88. package/dist/builtin/workflows/src/shared/authoring-contract-ui.d.ts +7 -0
  89. package/dist/builtin/workflows/src/shared/authoring-contract-ui.ts +7 -0
  90. package/dist/builtin/workflows/src/shared/authoring-contract.d.ts +1 -0
  91. package/dist/builtin/workflows/src/shared/budget-meter.ts +34 -0
  92. package/dist/builtin/workflows/src/shared/budget.d.ts +67 -0
  93. package/dist/builtin/workflows/src/shared/budget.ts +127 -0
  94. package/dist/builtin/workflows/src/shared/persistence-restore-helpers.ts +92 -8
  95. package/dist/builtin/workflows/src/shared/persistence-restore.ts +11 -1
  96. package/dist/builtin/workflows/src/shared/persistence-session-entries.ts +15 -3
  97. package/dist/builtin/workflows/src/shared/returned-run-status.ts +35 -2
  98. package/dist/builtin/workflows/src/shared/store-public-types.ts +4 -1
  99. package/dist/builtin/workflows/src/shared/store-run-methods.ts +8 -1
  100. package/dist/builtin/workflows/src/shared/store-stage-methods.ts +1 -0
  101. package/dist/builtin/workflows/src/shared/store-types.ts +24 -0
  102. package/dist/builtin/workflows/src/shared/types.ts +3 -0
  103. package/dist/builtin/workflows/src/shared/workflow-artifacts.ts +1 -0
  104. package/dist/builtin/workflows/src/shared/workflow-authoring-types.d.ts +3 -0
  105. package/dist/builtin/workflows/src/shared/workflow-authoring-types.ts +3 -0
  106. package/dist/core/atomic-guide-command.d.ts.map +1 -1
  107. package/dist/core/atomic-guide-command.js +1 -0
  108. package/dist/core/atomic-guide-command.js.map +1 -1
  109. package/dist/core/extensions/ui-types.d.ts +13 -3
  110. package/dist/core/extensions/ui-types.d.ts.map +1 -1
  111. package/dist/core/extensions/ui-types.js +15 -3
  112. package/dist/core/extensions/ui-types.js.map +1 -1
  113. package/dist/core/slash-commands.d.ts.map +1 -1
  114. package/dist/core/slash-commands.js +33 -3
  115. package/dist/core/slash-commands.js.map +1 -1
  116. package/dist/main-deferred-startup.d.ts.map +1 -1
  117. package/dist/main-deferred-startup.js +6 -2
  118. package/dist/main-deferred-startup.js.map +1 -1
  119. package/dist/modes/interactive/interactive-startup.js +4 -0
  120. package/dist/modes/interactive/interactive-startup.js.map +1 -1
  121. package/dist/modes/interactive/interactive-tui.d.ts.map +1 -1
  122. package/dist/modes/interactive/interactive-tui.js +19 -1
  123. package/dist/modes/interactive/interactive-tui.js.map +1 -1
  124. package/dist/modes/interactive-engine/isolated-runtime.d.ts +7 -0
  125. package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
  126. package/dist/modes/interactive-engine/isolated-runtime.js +94 -37
  127. package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
  128. package/dist/modes/rpc/rpc-client.d.ts +1 -0
  129. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  130. package/dist/modes/rpc/rpc-client.js +15 -2
  131. package/dist/modes/rpc/rpc-client.js.map +1 -1
  132. package/dist/modes/rpc/rpc-input-scheduler.d.ts +3 -2
  133. package/dist/modes/rpc/rpc-input-scheduler.d.ts.map +1 -1
  134. package/dist/modes/rpc/rpc-input-scheduler.js +5 -2
  135. package/dist/modes/rpc/rpc-input-scheduler.js.map +1 -1
  136. package/docs/extensions.md +1 -1
  137. package/docs/quickstart.md +1 -0
  138. package/docs/skills.md +4 -0
  139. package/docs/workflows.md +74 -10
  140. package/npm-shrinkwrap.json +29 -29
  141. package/package.json +2 -2
@@ -1 +1 @@
1
- {"version":3,"file":"rpc-client.js","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-client.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,8BAA8B,EAAE,MAAM,6BAA6B,CAAC;AAE7E,OAAO,EAAE,KAAK,EAAE,MAAM,sBAAsB,CAAC;AAO7C,OAAO,EAAE,wBAAwB,EAAE,MAAM,yCAAyC,CAAC;AACnF,OAAO,EAIN,+BAA+B,GAC/B,MAAM,mCA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AAC,SAAS,EAC/B,SAAS,EACT,EAAE,KAAK,EAAE,IAAI,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CACpC,CAAC;QACH,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IACjC,CAAC;IACS,IAAI,CAAI,QAAqB;QACtC,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;QAC7B,MAAM,eAAe,GAAG,QAAkE,CAAC;QAC3F,OAAO,eAAe,CAAC,IAAS,CAAC;IAClC,CAAC;CACD","sourcesContent":["import type { ChildProcess } from \"node:child_process\";\nimport type { ImageContent } from \"@earendil-works/pi-ai/compat\";\nimport type { BashResult } from \"../../core/bash-executor.ts\";\nimport { CredentialSynchronizationError } from \"../../core/model-runtime.js\";\nimport type { BashOutputChannel } from \"../../core/tools/bash.ts\";\nimport { sleep } from \"../../utils/sleep.ts\";\nimport type { ActivityWatchdogDiagnostic } from \"../interactive-engine/activity-watchdog.ts\";\nimport type {\n\tInteractiveEngineGenerationEnded,\n\tInteractiveEngineGenerationEndedListener,\n\tInteractiveEngineGenerationEndKind,\n} from \"../interactive-engine/engine-generation.ts\";\nimport { InteractiveEngineMonitor } from \"../interactive-engine/engine-monitor.ts\";\nimport {\n\ttype EngineKeybindingState,\n\ttype InteractiveEngineCommand,\n\ttype InteractiveEngineMessage,\n\tserializeInteractiveEngineFrame,\n} from \"../interactive-engine/protocol.ts\";\nimport { attachJsonlLineReader, serializeJsonLine } from \"./jsonl.ts\";\nimport { QueuedWriter } from \"./queued-writer.ts\";\nimport { RpcClientApi, type RpcCommandBody } from \"./rpc-client-api.ts\";\nimport {\n\tappendBoundedStderr,\n\tcreateInteractiveJsonlOptions,\n\trestartCliArgs,\n\tspawnRpcClientProcess,\n\tterminateRpcClientProcess,\n} from \"./rpc-client-process.ts\";\nimport { collectRpcEvents, runUserBashWithUpdates, waitForRpcIdle } from \"./rpc-client-waits.ts\";\nimport { DEFAULT_REQUEST_TIMEOUT_MS, LONG_LIVED_COMMANDS, RESTART_CANCELLED_MESSAGE } from \"./rpc-command-timeouts.ts\";\nimport { RpcEventBuffer } from \"./rpc-event-buffer.ts\";\nimport { GenerationBuffer } from \"./rpc-generation-buffer.ts\";\nimport { RpcPendingRequests } from \"./rpc-pending-requests.ts\";\nimport { RpcTerminalDrain } from \"./rpc-terminal-drain.ts\";\nimport { markRpcTransportFailure, rpcTransportError } from \"./rpc-transport-error.ts\";\nimport type { RpcCommand, RpcEvent, RpcExtensionUIRequest, RpcExtensionUIResponse, RpcResponse } from \"./rpc-types.ts\";\n\nexport type { ModelInfo, RpcCommandBody } from \"./rpc-client-api.ts\";\nexport type { RpcEvent } from \"./rpc-types.ts\";\n\nexport interface RpcClientOptions {\n\tcliPath?: string;\n\tcwd?: string;\n\tenv?: Record<string, string>;\n\tprovider?: string;\n\tmodel?: string;\n\targs?: string[];\n\truntimeExecutable?: string;\n\truntimeArgs?: string[];\n\t/**\n\t * Bounded deadline (ms) applied to short metadata/control requests. Long-lived\n\t * commands (see LONG_LIVED_COMMANDS) never use this timer. Defaults to 30s.\n\t */\n\trequestTimeoutMs?: number;\n\tinteractiveEngine?: {\n\t\tonDiagnostic: (diagnostic: ActivityWatchdogDiagnostic) => void;\n\t\tonActivityChange?: (active: boolean) => void;\n\t\t/**\n\t\t * Heartbeat observer. Deliberately NOT a generic engine-message listener:\n\t\t * subscribing there drains the buffered startup custom-UI messages into the\n\t\t * first subscriber and stops buffering for the real controllers.\n\t\t */\n\t\tonHeartbeat?: () => void;\n\t\t/**\n\t\t * Credential for the engine child. Delivered through the protected\n\t\t * bootstrap file, never through the child's environment or argv.\n\t\t */\n\t\tapiKey?: string;\n\t};\n}\n\nexport type RpcEventListener = (event: RpcEvent) => void;\n\nexport class RpcClient extends RpcClientApi {\n\tprivate process: ChildProcess | null = null;\n\tprivate stopReadingStdout: (() => void) | null = null;\n\tprivate eventListeners: RpcEventListener[] = [];\n\tprivate extensionUIListeners: Array<(request: RpcExtensionUIRequest) => void> = [];\n\tprivate readonly pendingExtensionUIRequests = new GenerationBuffer<RpcExtensionUIRequest>();\n\tprivate engineMessageListeners: Array<(message: InteractiveEngineMessage) => void> = [];\n\tprivate latestEngineKeybindingState: EngineKeybindingState | undefined;\n\tprivate readonly pendingEngineMessages = new GenerationBuffer<InteractiveEngineMessage>();\n\tprivate readonly pendingRequests = new RpcPendingRequests();\n\t/** Bumped by every explicit stop; a restart holds a permit across its own stop. */\n\tprivate restartRevision = 0;\n\tprivate readonly terminalDrain = new RpcTerminalDrain();\n\tprivate stdoutDrained: Promise<void> = Promise.resolve();\n\tprivate requestId = 0;\n\tprivate stderr = \"\";\n\tprivate exitError: Error | null = null;\n\tprivate engineMonitor: InteractiveEngineMonitor | undefined;\n\tprivate eventBuffer: RpcEventBuffer | undefined;\n\tprivate stdinWriter: QueuedWriter | undefined;\n\tprivate generation = 0;\n\tprivate lastEndedGeneration = 0;\n\tprivate generationEndedListeners: InteractiveEngineGenerationEndedListener[] = [];\n\t/**\n\t * The latest generation-end event, retained so a subscriber that attaches\n\t * after the child died still observes it. A child can exit between\n\t * `start()` returning and the runtime constructing its listeners.\n\t */\n\tprivate retainedGenerationEnd: InteractiveEngineGenerationEnded | undefined;\n\tprivate readonly activeActivityIds = new Set<string>();\n\tprivate enginePid: number | undefined;\n\n\tprivate declare options: RpcClientOptions;\n\n\tconstructor(options: RpcClientOptions = {}) {\n\t\tsuper();\n\t\tthis.options = options;\n\t}\n\n\tasync start(): Promise<void> {\n\t\tif (this.process) {\n\t\t\tthrow new Error(\"Client already started\");\n\t\t}\n\n\t\tconst cliPath = this.options.cliPath ?? \"dist/cli.js\";\n\t\tconst args = [\"--mode\", \"rpc\"];\n\n\t\tif (this.options.provider) {\n\t\t\targs.push(\"--provider\", this.options.provider);\n\t\t}\n\t\tif (this.options.model) {\n\t\t\targs.push(\"--model\", this.options.model);\n\t\t}\n\t\tif (this.options.args) {\n\t\t\targs.push(...this.options.args);\n\t\t}\n\n\t\tconst generation = ++this.generation;\n\t\tthis.exitError = null;\n\t\tthis.stderr = \"\";\n\t\tthis.activeActivityIds.clear();\n\t\tthis.enginePid = undefined;\n\t\tthis.engineMonitor = this.options.interactiveEngine\n\t\t\t? new InteractiveEngineMonitor(this.options.interactiveEngine.onDiagnostic, (message) =>\n\t\t\t\t\tthis.observeInteractiveEngineMessage(message, generation),\n\t\t\t\t)\n\t\t\t: undefined;\n\t\tthis.eventBuffer = this.engineMonitor ? new RpcEventBuffer((event) => this.emitEvent(event)) : undefined;\n\t\tconst childProcess = spawnRpcClientProcess({\n\t\t\tcliPath,\n\t\t\tcliArgs: args,\n\t\t\tcwd: this.options.cwd,\n\t\t\tenv: this.options.env,\n\t\t\truntimeExecutable: this.options.runtimeExecutable,\n\t\t\truntimeArgs: this.options.runtimeArgs,\n\t\t\tinteractiveEngine: this.engineMonitor !== undefined,\n\t\t\t...(this.options.interactiveEngine?.apiKey\n\t\t\t\t? { interactiveEngineApiKey: this.options.interactiveEngine.apiKey }\n\t\t\t\t: {}),\n\t\t});\n\t\tthis.process = childProcess;\n\t\tthis.stdinWriter = new QueuedWriter(childProcess.stdin!);\n\n\t\tchildProcess.once(\"exit\", (code, signal) =>\n\t\t\tthis.failGeneration(this.createProcessExitError(code, signal), generation, \"exit\"),\n\t\t);\n\t\tchildProcess.once(\"error\", (rawError) => this.failGeneration(rawError, generation, \"process-error\"));\n\t\tchildProcess.stdin?.on(\"error\", (rawError) => this.failGeneration(rawError, generation, \"stdin-error\"));\n\t\tchildProcess.stderr?.on(\"data\", (data) => {\n\t\t\tif (generation !== this.generation) return;\n\t\t\tthis.stderr = appendBoundedStderr(this.stderr, data.toString());\n\t\t\tprocess.stderr.write(data);\n\t\t});\n\t\tconst readerOptions = createInteractiveJsonlOptions(this.engineMonitor !== undefined);\n\t\tlet markStdoutDrained!: () => void;\n\t\tthis.stdoutDrained = new Promise<void>((resolve) => {\n\t\t\tmarkStdoutDrained = resolve;\n\t\t});\n\t\tthis.stopReadingStdout = attachJsonlLineReader(\n\t\t\tchildProcess.stdout!,\n\t\t\t(line) => {\n\t\t\t\tif (generation === this.generation) this.handleLine(line, generation);\n\t\t\t},\n\t\t\t{ ...readerOptions, onDrained: () => markStdoutDrained() },\n\t\t);\n\t\tif (this.engineMonitor) await this.engineMonitor.waitUntilReady();\n\t\telse await sleep(100);\n\n\t\tif (generation !== this.generation || this.process?.exitCode !== null) {\n\t\t\tthrow rpcTransportError(`Agent process exited immediately. Stderr: ${this.stderr}`);\n\t\t}\n\t}\n\n\t/**\n\t * Explicit stop. Voids any in-flight restart permit, so a replacement caught\n\t * between its own stop and start can never spawn after this returns.\n\t */\n\tasync stop(): Promise<void> {\n\t\tthis.restartRevision += 1;\n\t\tawait this.stopCurrentGeneration();\n\t}\n\n\t/**\n\t * Tear down the current child without touching the restart permit. The reader\n\t * stays attached and the generation stays current until the dead child's\n\t * stdout settles, so an ownership frame it already sent still reaches its\n\t * request; only then is the generation retired (see RpcTerminalDrain).\n\t */\n\tprivate async stopCurrentGeneration(): Promise<void> {\n\t\tconst child = this.process;\n\t\tif (!child) return;\n\t\tconst endedGeneration = this.generation;\n\t\tconst stopError = rpcTransportError(\"Agent process stopped\");\n\t\tthis.invalidateEngineShortcuts();\n\t\tconst terminateTree = this.engineMonitor !== undefined;\n\t\tthis.engineMonitor?.stop();\n\t\tthis.stdinWriter?.close(stopError);\n\t\t// Unblock an in-flight start()/waitUntilBound() for the generation being\n\t\t// replaced. Readiness has no deadline by design, so without this an\n\t\t// explicit stop of a hung replacement child could never be observed.\n\t\tthis.engineMonitor?.fail(stopError);\n\t\tthis.engineMonitor = undefined;\n\t\tthis.stdinWriter = undefined;\n\t\tthis.process = null;\n\t\t// Publish before terminating so host controllers tear down this generation's\n\t\t// UI while the writer is detached: disposal cannot write into a replacement.\n\t\tthis.publishGenerationEnded(endedGeneration, stopError, \"explicit-stop\", true);\n\t\t// Claim before terminating so the exit this provokes does not relabel a\n\t\t// deliberate stop; an exit that already claimed keeps its own error.\n\t\tthis.terminalDrain.claim(endedGeneration, stopError);\n\t\tawait terminateRpcClientProcess(child, terminateTree);\n\t\tawait this.beginTerminalDrain(endedGeneration, stopError);\n\t\tthis.stopReadingStdout?.();\n\t\tthis.stopReadingStdout = null;\n\t\tthis.generation += 1;\n\t\tthis.pendingRequests.rejectAll(stopError);\n\t\tthis.eventBuffer?.dispose();\n\t\tthis.eventBuffer = undefined;\n\t\tthis.activeActivityIds.clear();\n\t\tthis.options.interactiveEngine?.onActivityChange?.(false);\n\t}\n\n\t/** Subscribe to agent events. */\n\tonEvent(listener: RpcEventListener): () => void {\n\t\tthis.eventListeners.push(listener);\n\t\treturn () => {\n\t\t\tconst index = this.eventListeners.indexOf(listener);\n\t\t\tif (index !== -1) {\n\t\t\t\tthis.eventListeners.splice(index, 1);\n\t\t\t}\n\t\t};\n\t}\n\n\tonExtensionUIRequest(listener: (request: RpcExtensionUIRequest) => void): () => void {\n\t\tthis.extensionUIListeners.push(listener);\n\t\tfor (const request of this.pendingExtensionUIRequests.drain(this.generation)) listener(request);\n\t\treturn () => {\n\t\t\tconst index = this.extensionUIListeners.indexOf(listener);\n\t\t\tif (index !== -1) this.extensionUIListeners.splice(index, 1);\n\t\t};\n\t}\n\n\tasync respondExtensionUI(response: RpcExtensionUIResponse): Promise<void> {\n\t\tawait this.requireWriter().write(serializeJsonLine(response));\n\t}\n\n\tonInteractiveEngineMessage(listener: (message: InteractiveEngineMessage) => void): () => void {\n\t\tthis.engineMessageListeners.push(listener);\n\t\tfor (const message of this.pendingEngineMessages.drain(this.generation)) listener(message);\n\t\treturn () => {\n\t\t\tconst index = this.engineMessageListeners.indexOf(listener);\n\t\t\tif (index !== -1) this.engineMessageListeners.splice(index, 1);\n\t\t};\n\t}\n\n\tonInteractiveEngineKeybindingState(listener: (state: EngineKeybindingState) => void): () => void {\n\t\tconst messageListener = (message: InteractiveEngineMessage): void => {\n\t\t\tif (message.type === \"engine_keybindings_reloaded\") listener(message.state);\n\t\t};\n\t\tthis.engineMessageListeners.push(messageListener);\n\t\tif (this.latestEngineKeybindingState) listener(this.latestEngineKeybindingState);\n\t\treturn () => {\n\t\t\tconst index = this.engineMessageListeners.indexOf(messageListener);\n\t\t\tif (index !== -1) this.engineMessageListeners.splice(index, 1);\n\t\t};\n\t}\n\n\t/**\n\t * Subscribe to host-local generation death. Fires at most once per\n\t * generation, synchronously, before any restart work. A death that has\n\t * already happened for the current generation replays immediately, so a\n\t * listener attached after an exit still sees it.\n\t */\n\tonGenerationEnded(listener: InteractiveEngineGenerationEndedListener): () => void {\n\t\tthis.generationEndedListeners.push(listener);\n\t\tconst retained = this.retainedGenerationEnd;\n\t\t// Only while it still describes the live generation: once stop()/start()\n\t\t// has moved on, that death belongs to a replaced child.\n\t\tif (retained && retained.generation === this.generation) listener(retained);\n\t\treturn () => {\n\t\t\tconst index = this.generationEndedListeners.indexOf(listener);\n\t\t\tif (index !== -1) this.generationEndedListeners.splice(index, 1);\n\t\t};\n\t}\n\n\tsendInteractiveEngineCommand(command: InteractiveEngineCommand): void {\n\t\tconst writer = this.stdinWriter;\n\t\tif (!writer) return;\n\t\tconst frame = serializeInteractiveEngineFrame(command);\n\t\tif (\n\t\t\tcommand.type === \"engine_custom_render\" ||\n\t\t\tcommand.type === \"engine_tool_render\" ||\n\t\t\tcommand.type === \"engine_message_render\"\n\t\t) {\n\t\t\twriter.offerLatest(`render:${command.componentId}`, frame);\n\t\t\treturn;\n\t\t}\n\t\tthis.bestEffort(writer.write(frame), `engine command ${command.type}`);\n\t}\n\twaitForInteractiveEngineBound(): Promise<void> {\n\t\treturn this.engineMonitor?.waitUntilBound() ?? Promise.resolve();\n\t}\n\tgetEnginePid(): number | undefined {\n\t\treturn this.enginePid;\n\t}\n\tgetGeneration(): number {\n\t\treturn this.generation;\n\t}\n\n\t/**\n\t * Replace the engine child, unless an explicit stop supersedes this attempt.\n\t * The permit is checked immediately before spawning, so a `stop()` in that\n\t * window is always observed; cancellation throws rather than returning\n\t * quietly, because callers go on to initialize against the new child.\n\t */\n\tasync restart(sessionFile: string | undefined): Promise<void> {\n\t\tconst permit = this.restartRevision;\n\t\tawait this.stopCurrentGeneration();\n\t\tif (permit !== this.restartRevision) throw rpcTransportError(RESTART_CANCELLED_MESSAGE);\n\t\tthis.options = { ...this.options, args: restartCliArgs(this.options.args, sessionFile) };\n\t\tawait this.start();\n\t\tawait this.waitForInteractiveEngineBound();\n\t}\n\n\tasync requestInternal<T>(command: RpcCommandBody): Promise<T> {\n\t\treturn this.data<T>(await this.request(command));\n\t}\n\tuserBashWithUpdates(\n\t\tcommand: string,\n\t\tonUpdate: (delta: string, channel: BashOutputChannel) => void,\n\t\toptions?: { excludeFromContext?: boolean; onRequestId?: (id: string) => void },\n\t): Promise<BashResult> {\n\t\treturn runUserBashWithUpdates(this, command, onUpdate, options, (body, onId) => this.request(body, onId));\n\t}\n\tgetStderr(): string {\n\t\treturn this.stderr;\n\t}\n\n\twaitForIdle(timeout = 60000): Promise<void> {\n\t\treturn waitForRpcIdle(this, timeout);\n\t}\n\tcollectEvents(timeout = 60000): Promise<RpcEvent[]> {\n\t\treturn collectRpcEvents(this, timeout);\n\t}\n\tasync promptAndWait(message: string, images?: ImageContent[], timeout = 60000): Promise<RpcEvent[]> {\n\t\tconst eventsPromise = this.collectEvents(timeout);\n\t\tawait this.prompt(message, images);\n\t\treturn eventsPromise;\n\t}\n\tprivate handleLine(line: string, generation: number): void {\n\t\tif (this.terminalDrain.observe(generation, line, (id) => this.pendingRequests.markAccepted(id))) return;\n\t\tif (this.engineMonitor?.handleLine(line)) return;\n\t\ttry {\n\t\t\tconst data = JSON.parse(line) as { type?: string; id?: string };\n\t\t\tif (data.type === \"extension_ui_request\") {\n\t\t\t\tconst request = data as RpcExtensionUIRequest;\n\t\t\t\tif (this.extensionUIListeners.length === 0) this.pendingExtensionUIRequests.push(generation, request);\n\t\t\t\tfor (const listener of this.extensionUIListeners) listener(request);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (data.type === \"response\" && data.id && this.pendingRequests.resolve(data.id, data as RpcResponse)) return;\n\t\t\tconst event = data as RpcEvent;\n\t\t\tif (this.eventBuffer) this.eventBuffer.enqueue(event);\n\t\t\telse this.emitEvent(event);\n\t\t} catch {\n\t\t\tif (this.engineMonitor) this.failTransport(rpcTransportError(\"Interactive engine emitted malformed JSONL\"));\n\t\t}\n\t}\n\tprivate emitEvent(event: RpcEvent): void {\n\t\tfor (const listener of this.eventListeners) listener(event);\n\t}\n\tprivate emitInteractiveEngineMessage(message: InteractiveEngineMessage, generation: number): void {\n\t\tif (this.engineMessageListeners.length === 0 && message.type.startsWith(\"engine_custom_\")) {\n\t\t\tthis.pendingEngineMessages.push(generation, message);\n\t\t}\n\t\tfor (const listener of this.engineMessageListeners) listener(message);\n\t}\n\tprivate createProcessExitError(code: number | null, signal: NodeJS.Signals | null): Error {\n\t\treturn rpcTransportError(`Agent process exited (code=${code} signal=${signal}). Stderr: ${this.stderr}`);\n\t}\n\tprivate invalidateEngineShortcuts(): void {\n\t\tif (!this.latestEngineKeybindingState || this.latestEngineKeybindingState.shortcuts.length === 0) return;\n\t\tconst state: EngineKeybindingState = { ...this.latestEngineKeybindingState, shortcuts: [] };\n\t\tthis.latestEngineKeybindingState = state;\n\t\tthis.emitInteractiveEngineMessage({ type: \"engine_keybindings_reloaded\", state }, this.generation);\n\t}\n\tprivate observeInteractiveEngineMessage(message: InteractiveEngineMessage, generation: number): void {\n\t\t// Ownership is the one thing a dead generation may still report: request\n\t\t// ids never repeat, and the alternative is classifying work it already\n\t\t// started as never sent. Nothing else from it may touch host state — a\n\t\t// stale frame would revive a PID, an activity, or a mount that is gone.\n\t\tif (message.type === \"engine_request_accepted\") {\n\t\t\tif (generation === this.generation) this.pendingRequests.markAccepted(message.requestId);\n\t\t\treturn;\n\t\t}\n\t\tif (generation !== this.generation || generation <= this.lastEndedGeneration) return;\n\t\tif (message.type === \"engine_heartbeat\") this.options.interactiveEngine?.onHeartbeat?.();\n\t\tif (message.type === \"engine_ready\") this.enginePid = message.pid;\n\t\tif (message.type === \"engine_keybindings_reloaded\") this.latestEngineKeybindingState = message.state;\n\t\tif (message.type === \"engine_activity_started\") this.activeActivityIds.add(message.activity.id);\n\t\telse if (message.type === \"engine_activity_finished\") this.activeActivityIds.delete(message.activityId);\n\t\tthis.options.interactiveEngine?.onActivityChange?.(this.activeActivityIds.size > 0);\n\t\tthis.emitInteractiveEngineMessage(message, generation);\n\t}\n\t/**\n\t * Shared teardown for every unexpected end of `generation`. Death publishes\n\t * at once for the host UI; its requests wait for stdout (RpcTerminalDrain).\n\t */\n\tprivate failGeneration(rawError: Error, generation: number, kind: InteractiveEngineGenerationEndKind): void {\n\t\tif (generation !== this.generation) return;\n\t\tconst error = markRpcTransportFailure(rawError);\n\t\tthis.exitError = error;\n\t\tthis.stdinWriter?.close(error);\n\t\tthis.engineMonitor?.fail(error);\n\t\tif (kind === \"exit\") {\n\t\t\tthis.activeActivityIds.clear();\n\t\t\tthis.options.interactiveEngine?.onActivityChange?.(false);\n\t\t}\n\t\tthis.beginTerminalDrain(generation, error);\n\t\tthis.publishGenerationEnded(generation, error, kind, false);\n\t}\n\t/** Hold this generation's requests until its stdout drains (RpcTerminalDrain). */\n\tprivate beginTerminalDrain(generation: number, error: Error): Promise<void> {\n\t\treturn this.terminalDrain.begin(generation, this.stdoutDrained, error, (settled) => {\n\t\t\tif (generation === this.generation) this.pendingRequests.rejectAll(settled);\n\t\t});\n\t}\n\tprivate publishGenerationEnded(\n\t\tgeneration: number,\n\t\terror: Error,\n\t\tkind: InteractiveEngineGenerationEndKind,\n\t\texpected: boolean,\n\t): void {\n\t\tif (generation <= this.lastEndedGeneration) return;\n\t\tthis.lastEndedGeneration = generation;\n\t\tconst event: InteractiveEngineGenerationEnded = { generation, error, kind, expected };\n\t\tthis.retainedGenerationEnd = event;\n\t\t// Death is a strict boundary: drop this generation's buffered frames\n\t\t// BEFORE teardown runs, so no listener can drain a stale mount frame\n\t\t// while it is closing that very generation's components.\n\t\tthis.pendingEngineMessages.dropGeneration(generation);\n\t\tthis.pendingExtensionUIRequests.dropGeneration(generation);\n\t\tfor (const listener of [...this.generationEndedListeners]) listener(event);\n\t}\n\tprivate failTransport(rawError: Error): void {\n\t\tthis.options.interactiveEngine?.onDiagnostic({\n\t\t\tactivity: undefined,\n\t\t\telapsedMs: 0,\n\t\t\tlevel: \"unresponsive\",\n\t\t\tmessage: rawError.message,\n\t\t});\n\t\tthis.failGeneration(rawError, this.generation, \"transport-error\");\n\t}\n\tprivate requireWriter(): QueuedWriter {\n\t\tif (!this.stdinWriter) throw rpcTransportError(\"Agent process stdin is not writable\");\n\t\treturn this.stdinWriter;\n\t}\n\tprivate bestEffort(operation: Promise<void>, label: string): void {\n\t\tvoid operation.catch((error: Error) => {\n\t\t\tif (!this.process || this.exitError) return;\n\t\t\tthis.options.interactiveEngine?.onDiagnostic({\n\t\t\t\tactivity: undefined,\n\t\t\t\telapsedMs: 0,\n\t\t\t\tlevel: \"unresponsive\",\n\t\t\t\tmessage: `Interactive engine ${label} failed: ${error.message}`,\n\t\t\t});\n\t\t});\n\t}\n\tprotected async request(command: RpcCommandBody, onRequestId?: (id: string) => void): Promise<RpcResponse> {\n\t\tconst childProcess = this.process;\n\t\tif (!childProcess) throw rpcTransportError(\"Client not started\");\n\t\tif (this.exitError) throw this.exitError;\n\t\tif (childProcess.exitCode !== null) {\n\t\t\tconst error = this.createProcessExitError(childProcess.exitCode, childProcess.signalCode);\n\t\t\tthis.exitError = error;\n\t\t\tthrow error;\n\t\t}\n\t\tconst id = `req_${++this.requestId}`;\n\t\tonRequestId?.(id);\n\t\tconst fullCommand = { ...command, id } as RpcCommand;\n\t\tlet timeout: ReturnType<typeof setTimeout> | undefined;\n\t\tlet rejectResponse!: (error: Error) => void;\n\t\tconst response = new Promise<RpcResponse>((resolve, reject) => {\n\t\t\trejectResponse = reject;\n\t\t\tthis.pendingRequests.add(id, {\n\t\t\t\tresolve: (value) => {\n\t\t\t\t\tif (timeout) clearTimeout(timeout);\n\t\t\t\t\tresolve(value);\n\t\t\t\t},\n\t\t\t\treject: (error) => {\n\t\t\t\t\tif (timeout) clearTimeout(timeout);\n\t\t\t\t\treject(error);\n\t\t\t\t},\n\t\t\t});\n\t\t});\n\t\ttry {\n\t\t\tawait this.requireWriter().write(serializeJsonLine(fullCommand));\n\t\t} catch (error) {\n\t\t\tthis.pendingRequests.delete(id);\n\t\t\t// Idempotent: the writer already classified this, but a caller-supplied\n\t\t\t// stream can reject with anything, and a send that never left the host\n\t\t\t// is a transport failure whatever it threw.\n\t\t\trejectResponse(markRpcTransportFailure(error));\n\t\t\treturn response;\n\t\t}\n\t\tif (this.pendingRequests.has(id) && !LONG_LIVED_COMMANDS.has(command.type)) {\n\t\t\ttimeout = setTimeout(() => {\n\t\t\t\tthis.pendingRequests.delete(id);\n\t\t\t\trejectResponse(new Error(`Timeout waiting for response to ${command.type}. Stderr: ${this.stderr}`));\n\t\t\t}, this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS);\n\t\t}\n\t\treturn response;\n\t}\n\tprivate assertSuccess(response: RpcResponse): void {\n\t\tif (response.success) return;\n\t\tif (response.errorCode === \"credential_synchronization\" && response.errorDetails) {\n\t\t\tthrow new CredentialSynchronizationError(\n\t\t\t\tresponse.errorDetails.providerId,\n\t\t\t\tresponse.errorDetails.operation,\n\t\t\t\tundefined,\n\t\t\t\t{ cause: new Error(response.error) },\n\t\t\t);\n\t\t}\n\t\tthrow new Error(response.error);\n\t}\n\tprotected data<T>(response: RpcResponse): T {\n\t\tthis.assertSuccess(response);\n\t\tconst successResponse = response as Extract<RpcResponse, { success: true; data: unknown }>;\n\t\treturn successResponse.data as T;\n\t}\n}\n"]}
1
+ {"version":3,"file":"rpc-client.js","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-client.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,8BAA8B,EAAE,MAAM,6BAA6B,CAAC;AAE7E,OAAO,EAAE,KAAK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AAG,UAAU,CAAC,GAAG,EAAE;gBACzB,IAAI,CAAC,eAAe,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;gBAChC,cAAc,CAAC,IAAI,KAAK,CAAC,mCAAmC,OAAO,CAAC,IAAI,aAAa,IAAI,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC;YACtG,CAAC,EAAE,IAAI,CAAC,OAAO,CAAC,gBAAgB,IAAI,0BAA0B,CAAC,CAAC;QACjE,CAAC;QACD,OAAO,QAAQ,CAAC;IACjB,CAAC;IACO,aAAa,CAAC,QAAqB;QAC1C,IAAI,QAAQ,CAAC,OAAO;YAAE,OAAO;QAC7B,IAAI,QAAQ,CAAC,SAAS,KAAK,4BAA4B,IAAI,QAAQ,CAAC,YAAY,EAAE,CAAC;YAClF,MAAM,IAAI,8BAA8B,CACvC,QAAQ,CAAC,YAAY,CAAC,UAAU,EAChC,QAAQ,CAAC,YAAY,CAAC,SAAS,EAC/B,SAAS,EACT,EAAE,KAAK,EAAE,IAAI,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CACpC,CAAC;QACH,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IACjC,CAAC;IACS,IAAI,CAAI,QAAqB;QACtC,IAAI,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAC;QAC7B,MAAM,eAAe,GAAG,QAAkE,CAAC;QAC3F,OAAO,eAAe,CAAC,IAAS,CAAC;IAClC,CAAC;CACD","sourcesContent":["import type { ChildProcess } from \"node:child_process\";\nimport type { ImageContent } from \"@earendil-works/pi-ai/compat\";\nimport type { BashResult } from \"../../core/bash-executor.ts\";\nimport { CredentialSynchronizationError } from \"../../core/model-runtime.js\";\nimport type { BashOutputChannel } from \"../../core/tools/bash.ts\";\nimport { sleep } from \"../../utils/sleep.ts\";\nimport type { ActivityWatchdogDiagnostic } from \"../interactive-engine/activity-watchdog.ts\";\nimport type {\n\tInteractiveEngineGenerationEnded,\n\tInteractiveEngineGenerationEndedListener,\n\tInteractiveEngineGenerationEndKind,\n} from \"../interactive-engine/engine-generation.ts\";\nimport { InteractiveEngineMonitor } from \"../interactive-engine/engine-monitor.ts\";\nimport {\n\ttype EngineKeybindingState,\n\ttype InteractiveEngineCommand,\n\ttype InteractiveEngineMessage,\n\tserializeInteractiveEngineFrame,\n} from \"../interactive-engine/protocol.ts\";\nimport { attachJsonlLineReader, serializeJsonLine } from \"./jsonl.ts\";\nimport { QueuedWriter } from \"./queued-writer.ts\";\nimport { RpcClientApi, type RpcCommandBody } from \"./rpc-client-api.ts\";\nimport {\n\tappendBoundedStderr,\n\tcreateInteractiveJsonlOptions,\n\trestartCliArgs,\n\tspawnRpcClientProcess,\n\tterminateRpcClientProcess,\n} from \"./rpc-client-process.ts\";\nimport { collectRpcEvents, runUserBashWithUpdates, waitForRpcIdle } from \"./rpc-client-waits.ts\";\nimport { DEFAULT_REQUEST_TIMEOUT_MS, LONG_LIVED_COMMANDS, RESTART_CANCELLED_MESSAGE } from \"./rpc-command-timeouts.ts\";\nimport { RpcEventBuffer } from \"./rpc-event-buffer.ts\";\nimport { GenerationBuffer } from \"./rpc-generation-buffer.ts\";\nimport { RpcPendingRequests } from \"./rpc-pending-requests.ts\";\nimport { RpcTerminalDrain } from \"./rpc-terminal-drain.ts\";\nimport { markRpcTransportFailure, rpcTransportError } from \"./rpc-transport-error.ts\";\nimport type { RpcCommand, RpcEvent, RpcExtensionUIRequest, RpcExtensionUIResponse, RpcResponse } from \"./rpc-types.ts\";\n\nexport type { ModelInfo, RpcCommandBody } from \"./rpc-client-api.ts\";\nexport type { RpcEvent } from \"./rpc-types.ts\";\n\nexport interface RpcClientOptions {\n\tcliPath?: string;\n\tcwd?: string;\n\tenv?: Record<string, string>;\n\tprovider?: string;\n\tmodel?: string;\n\targs?: string[];\n\truntimeExecutable?: string;\n\truntimeArgs?: string[];\n\t/**\n\t * Bounded deadline (ms) applied to short metadata/control requests. Long-lived\n\t * commands (see LONG_LIVED_COMMANDS) never use this timer. Defaults to 30s.\n\t */\n\trequestTimeoutMs?: number;\n\tinteractiveEngine?: {\n\t\tonDiagnostic: (diagnostic: ActivityWatchdogDiagnostic) => void;\n\t\tonActivityChange?: (active: boolean) => void;\n\t\t/**\n\t\t * Heartbeat observer. Deliberately NOT a generic engine-message listener:\n\t\t * subscribing there drains the buffered startup custom-UI messages into the\n\t\t * first subscriber and stops buffering for the real controllers.\n\t\t */\n\t\tonHeartbeat?: () => void;\n\t\t/**\n\t\t * Credential for the engine child. Delivered through the protected\n\t\t * bootstrap file, never through the child's environment or argv.\n\t\t */\n\t\tapiKey?: string;\n\t};\n}\n\nexport type RpcEventListener = (event: RpcEvent) => void;\n\nexport class RpcClient extends RpcClientApi {\n\tprivate process: ChildProcess | null = null;\n\tprivate stopReadingStdout: (() => void) | null = null;\n\tprivate eventListeners: RpcEventListener[] = [];\n\tprivate extensionUIListeners: Array<(request: RpcExtensionUIRequest) => void> = [];\n\tprivate readonly pendingExtensionUIRequests = new GenerationBuffer<RpcExtensionUIRequest>();\n\tprivate engineMessageListeners: Array<(message: InteractiveEngineMessage) => void> = [];\n\tprivate latestEngineKeybindingState: EngineKeybindingState | undefined;\n\tprivate readonly pendingEngineMessages = new GenerationBuffer<InteractiveEngineMessage>();\n\tprivate readonly pendingRequests = new RpcPendingRequests();\n\t/** Bumped by every explicit stop; a restart holds a permit across its own stop. */\n\tprivate restartRevision = 0;\n\tprivate stopPromise: Promise<void> | undefined;\n\tprivate readonly terminalDrain = new RpcTerminalDrain();\n\tprivate stdoutDrained: Promise<void> = Promise.resolve();\n\tprivate requestId = 0;\n\tprivate stderr = \"\";\n\tprivate exitError: Error | null = null;\n\tprivate engineMonitor: InteractiveEngineMonitor | undefined;\n\tprivate eventBuffer: RpcEventBuffer | undefined;\n\tprivate stdinWriter: QueuedWriter | undefined;\n\tprivate generation = 0;\n\tprivate lastEndedGeneration = 0;\n\tprivate generationEndedListeners: InteractiveEngineGenerationEndedListener[] = [];\n\t/**\n\t * The latest generation-end event, retained so a subscriber that attaches\n\t * after the child died still observes it. A child can exit between\n\t * `start()` returning and the runtime constructing its listeners.\n\t */\n\tprivate retainedGenerationEnd: InteractiveEngineGenerationEnded | undefined;\n\tprivate readonly activeActivityIds = new Set<string>();\n\tprivate enginePid: number | undefined;\n\n\tprivate declare options: RpcClientOptions;\n\n\tconstructor(options: RpcClientOptions = {}) {\n\t\tsuper();\n\t\tthis.options = options;\n\t}\n\n\tasync start(): Promise<void> {\n\t\tif (this.process) {\n\t\t\tthrow new Error(\"Client already started\");\n\t\t}\n\n\t\tconst cliPath = this.options.cliPath ?? \"dist/cli.js\";\n\t\tconst args = [\"--mode\", \"rpc\"];\n\n\t\tif (this.options.provider) {\n\t\t\targs.push(\"--provider\", this.options.provider);\n\t\t}\n\t\tif (this.options.model) {\n\t\t\targs.push(\"--model\", this.options.model);\n\t\t}\n\t\tif (this.options.args) {\n\t\t\targs.push(...this.options.args);\n\t\t}\n\n\t\tconst generation = ++this.generation;\n\t\tthis.exitError = null;\n\t\tthis.stderr = \"\";\n\t\tthis.activeActivityIds.clear();\n\t\tthis.enginePid = undefined;\n\t\tthis.engineMonitor = this.options.interactiveEngine\n\t\t\t? new InteractiveEngineMonitor(this.options.interactiveEngine.onDiagnostic, (message) =>\n\t\t\t\t\tthis.observeInteractiveEngineMessage(message, generation),\n\t\t\t\t)\n\t\t\t: undefined;\n\t\tthis.eventBuffer = this.engineMonitor ? new RpcEventBuffer((event) => this.emitEvent(event)) : undefined;\n\t\tconst childProcess = spawnRpcClientProcess({\n\t\t\tcliPath,\n\t\t\tcliArgs: args,\n\t\t\tcwd: this.options.cwd,\n\t\t\tenv: this.options.env,\n\t\t\truntimeExecutable: this.options.runtimeExecutable,\n\t\t\truntimeArgs: this.options.runtimeArgs,\n\t\t\tinteractiveEngine: this.engineMonitor !== undefined,\n\t\t\t...(this.options.interactiveEngine?.apiKey\n\t\t\t\t? { interactiveEngineApiKey: this.options.interactiveEngine.apiKey }\n\t\t\t\t: {}),\n\t\t});\n\t\tthis.process = childProcess;\n\t\tthis.stdinWriter = new QueuedWriter(childProcess.stdin!);\n\n\t\tchildProcess.once(\"exit\", (code, signal) =>\n\t\t\tthis.failGeneration(this.createProcessExitError(code, signal), generation, \"exit\"),\n\t\t);\n\t\tchildProcess.once(\"error\", (rawError) => this.failGeneration(rawError, generation, \"process-error\"));\n\t\tchildProcess.stdin?.on(\"error\", (rawError) => this.failGeneration(rawError, generation, \"stdin-error\"));\n\t\tchildProcess.stderr?.on(\"data\", (data) => {\n\t\t\tif (generation !== this.generation) return;\n\t\t\tthis.stderr = appendBoundedStderr(this.stderr, data.toString());\n\t\t\tprocess.stderr.write(data);\n\t\t});\n\t\tconst readerOptions = createInteractiveJsonlOptions(this.engineMonitor !== undefined);\n\t\tlet markStdoutDrained!: () => void;\n\t\tthis.stdoutDrained = new Promise<void>((resolve) => {\n\t\t\tmarkStdoutDrained = resolve;\n\t\t});\n\t\tthis.stopReadingStdout = attachJsonlLineReader(\n\t\t\tchildProcess.stdout!,\n\t\t\t(line) => {\n\t\t\t\tif (generation === this.generation) this.handleLine(line, generation);\n\t\t\t},\n\t\t\t{ ...readerOptions, onDrained: () => markStdoutDrained() },\n\t\t);\n\t\tif (this.engineMonitor) await this.engineMonitor.waitUntilReady();\n\t\telse await sleep(100);\n\n\t\tif (generation !== this.generation || this.process?.exitCode !== null) {\n\t\t\tthrow rpcTransportError(`Agent process exited immediately. Stderr: ${this.stderr}`);\n\t\t}\n\t}\n\n\t/**\n\t * Explicit stop. Voids any in-flight restart permit, so a replacement caught\n\t * between its own stop and start can never spawn after this returns.\n\t */\n\tstop(): Promise<void> {\n\t\tthis.restartRevision += 1;\n\t\tif (this.stopPromise) return this.stopPromise;\n\t\tif (!this.process) return Promise.resolve();\n\t\tconst stopPromise = this.stopCurrentGeneration().finally(() => {\n\t\t\tif (this.stopPromise === stopPromise) this.stopPromise = undefined;\n\t\t});\n\t\tthis.stopPromise = stopPromise;\n\t\treturn stopPromise;\n\t}\n\n\t/**\n\t * Tear down the current child without touching the restart permit. The reader\n\t * stays attached and the generation stays current until the dead child's\n\t * stdout settles, so an ownership frame it already sent still reaches its\n\t * request; only then is the generation retired (see RpcTerminalDrain).\n\t */\n\tprivate async stopCurrentGeneration(): Promise<void> {\n\t\tconst child = this.process;\n\t\tif (!child) return;\n\t\tconst endedGeneration = this.generation;\n\t\tconst stopError = rpcTransportError(\"Agent process stopped\");\n\t\tthis.invalidateEngineShortcuts();\n\t\tconst terminateTree = this.engineMonitor !== undefined;\n\t\tthis.engineMonitor?.stop();\n\t\tthis.stdinWriter?.close(stopError);\n\t\t// Unblock an in-flight start()/waitUntilBound() for the generation being\n\t\t// replaced. Readiness has no deadline by design, so without this an\n\t\t// explicit stop of a hung replacement child could never be observed.\n\t\tthis.engineMonitor?.fail(stopError);\n\t\tthis.engineMonitor = undefined;\n\t\tthis.stdinWriter = undefined;\n\t\tthis.process = null;\n\t\t// Publish before terminating so host controllers tear down this generation's\n\t\t// UI while the writer is detached: disposal cannot write into a replacement.\n\t\tthis.publishGenerationEnded(endedGeneration, stopError, \"explicit-stop\", true);\n\t\t// Claim before terminating so the exit this provokes does not relabel a\n\t\t// deliberate stop; an exit that already claimed keeps its own error.\n\t\tthis.terminalDrain.claim(endedGeneration, stopError);\n\t\tawait terminateRpcClientProcess(child, terminateTree);\n\t\tawait this.beginTerminalDrain(endedGeneration, stopError);\n\t\tthis.stopReadingStdout?.();\n\t\tthis.stopReadingStdout = null;\n\t\tthis.generation += 1;\n\t\tthis.pendingRequests.rejectAll(stopError);\n\t\tthis.eventBuffer?.dispose();\n\t\tthis.eventBuffer = undefined;\n\t\tthis.activeActivityIds.clear();\n\t\tthis.options.interactiveEngine?.onActivityChange?.(false);\n\t}\n\n\t/** Subscribe to agent events. */\n\tonEvent(listener: RpcEventListener): () => void {\n\t\tthis.eventListeners.push(listener);\n\t\treturn () => {\n\t\t\tconst index = this.eventListeners.indexOf(listener);\n\t\t\tif (index !== -1) {\n\t\t\t\tthis.eventListeners.splice(index, 1);\n\t\t\t}\n\t\t};\n\t}\n\n\tonExtensionUIRequest(listener: (request: RpcExtensionUIRequest) => void): () => void {\n\t\tthis.extensionUIListeners.push(listener);\n\t\tfor (const request of this.pendingExtensionUIRequests.drain(this.generation)) listener(request);\n\t\treturn () => {\n\t\t\tconst index = this.extensionUIListeners.indexOf(listener);\n\t\t\tif (index !== -1) this.extensionUIListeners.splice(index, 1);\n\t\t};\n\t}\n\n\tasync respondExtensionUI(response: RpcExtensionUIResponse): Promise<void> {\n\t\tawait this.requireWriter().write(serializeJsonLine(response));\n\t}\n\n\tonInteractiveEngineMessage(listener: (message: InteractiveEngineMessage) => void): () => void {\n\t\tthis.engineMessageListeners.push(listener);\n\t\tfor (const message of this.pendingEngineMessages.drain(this.generation)) listener(message);\n\t\treturn () => {\n\t\t\tconst index = this.engineMessageListeners.indexOf(listener);\n\t\t\tif (index !== -1) this.engineMessageListeners.splice(index, 1);\n\t\t};\n\t}\n\n\tonInteractiveEngineKeybindingState(listener: (state: EngineKeybindingState) => void): () => void {\n\t\tconst messageListener = (message: InteractiveEngineMessage): void => {\n\t\t\tif (message.type === \"engine_keybindings_reloaded\") listener(message.state);\n\t\t};\n\t\tthis.engineMessageListeners.push(messageListener);\n\t\tif (this.latestEngineKeybindingState) listener(this.latestEngineKeybindingState);\n\t\treturn () => {\n\t\t\tconst index = this.engineMessageListeners.indexOf(messageListener);\n\t\t\tif (index !== -1) this.engineMessageListeners.splice(index, 1);\n\t\t};\n\t}\n\n\t/**\n\t * Subscribe to host-local generation death. Fires at most once per\n\t * generation, synchronously, before any restart work. A death that has\n\t * already happened for the current generation replays immediately, so a\n\t * listener attached after an exit still sees it.\n\t */\n\tonGenerationEnded(listener: InteractiveEngineGenerationEndedListener): () => void {\n\t\tthis.generationEndedListeners.push(listener);\n\t\tconst retained = this.retainedGenerationEnd;\n\t\t// Only while it still describes the live generation: once stop()/start()\n\t\t// has moved on, that death belongs to a replaced child.\n\t\tif (retained && retained.generation === this.generation) listener(retained);\n\t\treturn () => {\n\t\t\tconst index = this.generationEndedListeners.indexOf(listener);\n\t\t\tif (index !== -1) this.generationEndedListeners.splice(index, 1);\n\t\t};\n\t}\n\n\tsendInteractiveEngineCommand(command: InteractiveEngineCommand): void {\n\t\tconst writer = this.stdinWriter;\n\t\tif (!writer) return;\n\t\tconst frame = serializeInteractiveEngineFrame(command);\n\t\tif (\n\t\t\tcommand.type === \"engine_custom_render\" ||\n\t\t\tcommand.type === \"engine_tool_render\" ||\n\t\t\tcommand.type === \"engine_message_render\"\n\t\t) {\n\t\t\twriter.offerLatest(`render:${command.componentId}`, frame);\n\t\t\treturn;\n\t\t}\n\t\tthis.bestEffort(writer.write(frame), `engine command ${command.type}`);\n\t}\n\twaitForInteractiveEngineBound(): Promise<void> {\n\t\treturn this.engineMonitor?.waitUntilBound() ?? Promise.resolve();\n\t}\n\tgetEnginePid(): number | undefined {\n\t\treturn this.enginePid;\n\t}\n\tgetGeneration(): number {\n\t\treturn this.generation;\n\t}\n\n\t/**\n\t * Replace the engine child, unless an explicit stop supersedes this attempt.\n\t * The permit is checked immediately before spawning, so a `stop()` in that\n\t * window is always observed; cancellation throws rather than returning\n\t * quietly, because callers go on to initialize against the new child.\n\t */\n\tasync restart(sessionFile: string | undefined): Promise<void> {\n\t\tconst permit = this.restartRevision;\n\t\tawait this.stopCurrentGeneration();\n\t\t// Join an in-flight stop before the permit check: waiting after it would\n\t\t// reopen the window this fence exists to close.\n\t\tif (this.stopPromise) await this.stopPromise;\n\t\tif (permit !== this.restartRevision) throw rpcTransportError(RESTART_CANCELLED_MESSAGE);\n\t\tthis.options = { ...this.options, args: restartCliArgs(this.options.args, sessionFile) };\n\t\tawait this.start();\n\t\tawait this.waitForInteractiveEngineBound();\n\t}\n\n\tasync requestInternal<T>(command: RpcCommandBody): Promise<T> {\n\t\treturn this.data<T>(await this.request(command));\n\t}\n\tuserBashWithUpdates(\n\t\tcommand: string,\n\t\tonUpdate: (delta: string, channel: BashOutputChannel) => void,\n\t\toptions?: { excludeFromContext?: boolean; onRequestId?: (id: string) => void },\n\t): Promise<BashResult> {\n\t\treturn runUserBashWithUpdates(this, command, onUpdate, options, (body, onId) => this.request(body, onId));\n\t}\n\tgetStderr(): string {\n\t\treturn this.stderr;\n\t}\n\n\twaitForIdle(timeout = 60000): Promise<void> {\n\t\treturn waitForRpcIdle(this, timeout);\n\t}\n\tcollectEvents(timeout = 60000): Promise<RpcEvent[]> {\n\t\treturn collectRpcEvents(this, timeout);\n\t}\n\tasync promptAndWait(message: string, images?: ImageContent[], timeout = 60000): Promise<RpcEvent[]> {\n\t\tconst eventsPromise = this.collectEvents(timeout);\n\t\tawait this.prompt(message, images);\n\t\treturn eventsPromise;\n\t}\n\tprivate handleLine(line: string, generation: number): void {\n\t\tif (this.terminalDrain.observe(generation, line, (id) => this.pendingRequests.markAccepted(id))) return;\n\t\tif (this.engineMonitor?.handleLine(line)) return;\n\t\ttry {\n\t\t\tconst data = JSON.parse(line) as { type?: string; id?: string };\n\t\t\tif (data.type === \"extension_ui_request\") {\n\t\t\t\tconst request = data as RpcExtensionUIRequest;\n\t\t\t\tif (this.extensionUIListeners.length === 0) this.pendingExtensionUIRequests.push(generation, request);\n\t\t\t\tfor (const listener of this.extensionUIListeners) listener(request);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (data.type === \"response\" && data.id && this.pendingRequests.resolve(data.id, data as RpcResponse)) return;\n\t\t\tconst event = data as RpcEvent;\n\t\t\tif (this.eventBuffer) this.eventBuffer.enqueue(event);\n\t\t\telse this.emitEvent(event);\n\t\t} catch {\n\t\t\tif (this.engineMonitor) this.failTransport(rpcTransportError(\"Interactive engine emitted malformed JSONL\"));\n\t\t}\n\t}\n\tprivate emitEvent(event: RpcEvent): void {\n\t\tfor (const listener of this.eventListeners) listener(event);\n\t}\n\tprivate emitInteractiveEngineMessage(message: InteractiveEngineMessage, generation: number): void {\n\t\tif (this.engineMessageListeners.length === 0 && message.type.startsWith(\"engine_custom_\")) {\n\t\t\tthis.pendingEngineMessages.push(generation, message);\n\t\t}\n\t\tfor (const listener of this.engineMessageListeners) listener(message);\n\t}\n\tprivate createProcessExitError(code: number | null, signal: NodeJS.Signals | null): Error {\n\t\treturn rpcTransportError(`Agent process exited (code=${code} signal=${signal}). Stderr: ${this.stderr}`);\n\t}\n\tprivate invalidateEngineShortcuts(): void {\n\t\tif (!this.latestEngineKeybindingState || this.latestEngineKeybindingState.shortcuts.length === 0) return;\n\t\tconst state: EngineKeybindingState = { ...this.latestEngineKeybindingState, shortcuts: [] };\n\t\tthis.latestEngineKeybindingState = state;\n\t\tthis.emitInteractiveEngineMessage({ type: \"engine_keybindings_reloaded\", state }, this.generation);\n\t}\n\tprivate observeInteractiveEngineMessage(message: InteractiveEngineMessage, generation: number): void {\n\t\t// Ownership is the one thing a dead generation may still report: request\n\t\t// ids never repeat, and the alternative is classifying work it already\n\t\t// started as never sent. Nothing else from it may touch host state — a\n\t\t// stale frame would revive a PID, an activity, or a mount that is gone.\n\t\tif (message.type === \"engine_request_accepted\") {\n\t\t\tif (generation === this.generation) this.pendingRequests.markAccepted(message.requestId);\n\t\t\treturn;\n\t\t}\n\t\tif (generation !== this.generation || generation <= this.lastEndedGeneration) return;\n\t\tif (message.type === \"engine_heartbeat\") this.options.interactiveEngine?.onHeartbeat?.();\n\t\tif (message.type === \"engine_ready\") this.enginePid = message.pid;\n\t\tif (message.type === \"engine_keybindings_reloaded\") this.latestEngineKeybindingState = message.state;\n\t\tif (message.type === \"engine_activity_started\") this.activeActivityIds.add(message.activity.id);\n\t\telse if (message.type === \"engine_activity_finished\") this.activeActivityIds.delete(message.activityId);\n\t\tthis.options.interactiveEngine?.onActivityChange?.(this.activeActivityIds.size > 0);\n\t\tthis.emitInteractiveEngineMessage(message, generation);\n\t}\n\t/**\n\t * Shared teardown for every unexpected end of `generation`. Death publishes\n\t * at once for the host UI; its requests wait for stdout (RpcTerminalDrain).\n\t */\n\tprivate failGeneration(rawError: Error, generation: number, kind: InteractiveEngineGenerationEndKind): void {\n\t\tif (generation !== this.generation) return;\n\t\tconst error = markRpcTransportFailure(rawError);\n\t\tthis.exitError = error;\n\t\tthis.stdinWriter?.close(error);\n\t\tthis.engineMonitor?.fail(error);\n\t\tif (kind === \"exit\") {\n\t\t\tthis.activeActivityIds.clear();\n\t\t\tthis.options.interactiveEngine?.onActivityChange?.(false);\n\t\t}\n\t\tthis.beginTerminalDrain(generation, error);\n\t\tthis.publishGenerationEnded(generation, error, kind, false);\n\t}\n\t/** Hold this generation's requests until its stdout drains (RpcTerminalDrain). */\n\tprivate beginTerminalDrain(generation: number, error: Error): Promise<void> {\n\t\treturn this.terminalDrain.begin(generation, this.stdoutDrained, error, (settled) => {\n\t\t\tif (generation === this.generation) this.pendingRequests.rejectAll(settled);\n\t\t});\n\t}\n\tprivate publishGenerationEnded(\n\t\tgeneration: number,\n\t\terror: Error,\n\t\tkind: InteractiveEngineGenerationEndKind,\n\t\texpected: boolean,\n\t): void {\n\t\tif (generation <= this.lastEndedGeneration) return;\n\t\tthis.lastEndedGeneration = generation;\n\t\tconst event: InteractiveEngineGenerationEnded = { generation, error, kind, expected };\n\t\tthis.retainedGenerationEnd = event;\n\t\t// Death is a strict boundary: drop this generation's buffered frames\n\t\t// BEFORE teardown runs, so no listener can drain a stale mount frame\n\t\t// while it is closing that very generation's components.\n\t\tthis.pendingEngineMessages.dropGeneration(generation);\n\t\tthis.pendingExtensionUIRequests.dropGeneration(generation);\n\t\tfor (const listener of [...this.generationEndedListeners]) listener(event);\n\t}\n\tprivate failTransport(rawError: Error): void {\n\t\tthis.options.interactiveEngine?.onDiagnostic({\n\t\t\tactivity: undefined,\n\t\t\telapsedMs: 0,\n\t\t\tlevel: \"unresponsive\",\n\t\t\tmessage: rawError.message,\n\t\t});\n\t\tthis.failGeneration(rawError, this.generation, \"transport-error\");\n\t}\n\tprivate requireWriter(): QueuedWriter {\n\t\tif (!this.stdinWriter) throw rpcTransportError(\"Agent process stdin is not writable\");\n\t\treturn this.stdinWriter;\n\t}\n\tprivate bestEffort(operation: Promise<void>, label: string): void {\n\t\tvoid operation.catch((error: Error) => {\n\t\t\tif (!this.process || this.exitError) return;\n\t\t\tthis.options.interactiveEngine?.onDiagnostic({\n\t\t\t\tactivity: undefined,\n\t\t\t\telapsedMs: 0,\n\t\t\t\tlevel: \"unresponsive\",\n\t\t\t\tmessage: `Interactive engine ${label} failed: ${error.message}`,\n\t\t\t});\n\t\t});\n\t}\n\tprotected async request(command: RpcCommandBody, onRequestId?: (id: string) => void): Promise<RpcResponse> {\n\t\tconst childProcess = this.process;\n\t\tif (!childProcess) throw rpcTransportError(\"Client not started\");\n\t\tif (this.exitError) throw this.exitError;\n\t\tif (childProcess.exitCode !== null) {\n\t\t\tconst error = this.createProcessExitError(childProcess.exitCode, childProcess.signalCode);\n\t\t\tthis.exitError = error;\n\t\t\tthrow error;\n\t\t}\n\t\tconst id = `req_${++this.requestId}`;\n\t\tonRequestId?.(id);\n\t\tconst fullCommand = { ...command, id } as RpcCommand;\n\t\tlet timeout: ReturnType<typeof setTimeout> | undefined;\n\t\tlet rejectResponse!: (error: Error) => void;\n\t\tconst response = new Promise<RpcResponse>((resolve, reject) => {\n\t\t\trejectResponse = reject;\n\t\t\tthis.pendingRequests.add(id, {\n\t\t\t\tresolve: (value) => {\n\t\t\t\t\tif (timeout) clearTimeout(timeout);\n\t\t\t\t\tresolve(value);\n\t\t\t\t},\n\t\t\t\treject: (error) => {\n\t\t\t\t\tif (timeout) clearTimeout(timeout);\n\t\t\t\t\treject(error);\n\t\t\t\t},\n\t\t\t});\n\t\t});\n\t\ttry {\n\t\t\tawait this.requireWriter().write(serializeJsonLine(fullCommand));\n\t\t} catch (error) {\n\t\t\tthis.pendingRequests.delete(id);\n\t\t\t// Idempotent: the writer already classified this, but a caller-supplied\n\t\t\t// stream can reject with anything, and a send that never left the host\n\t\t\t// is a transport failure whatever it threw.\n\t\t\trejectResponse(markRpcTransportFailure(error));\n\t\t\treturn response;\n\t\t}\n\t\tif (this.pendingRequests.has(id) && !LONG_LIVED_COMMANDS.has(command.type)) {\n\t\t\ttimeout = setTimeout(() => {\n\t\t\t\tthis.pendingRequests.delete(id);\n\t\t\t\trejectResponse(new Error(`Timeout waiting for response to ${command.type}. Stderr: ${this.stderr}`));\n\t\t\t}, this.options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS);\n\t\t}\n\t\treturn response;\n\t}\n\tprivate assertSuccess(response: RpcResponse): void {\n\t\tif (response.success) return;\n\t\tif (response.errorCode === \"credential_synchronization\" && response.errorDetails) {\n\t\t\tthrow new CredentialSynchronizationError(\n\t\t\t\tresponse.errorDetails.providerId,\n\t\t\t\tresponse.errorDetails.operation,\n\t\t\t\tundefined,\n\t\t\t\t{ cause: new Error(response.error) },\n\t\t\t);\n\t\t}\n\t\tthrow new Error(response.error);\n\t}\n\tprotected data<T>(response: RpcResponse): T {\n\t\tthis.assertSuccess(response);\n\t\tconst successResponse = response as Extract<RpcResponse, { success: true; data: unknown }>;\n\t\treturn successResponse.data as T;\n\t}\n}\n"]}
@@ -2,8 +2,9 @@ import type { RpcExtensionUIResponse } from "./rpc-types.ts";
2
2
  export declare function isRpcExtensionUIResponse(value: unknown): value is RpcExtensionUIResponse;
3
3
  /**
4
4
  * Control frames must remain reachable while an ordinary RPC command is
5
- * pending. Interrupts cancel that command, while host responses can unblock UI
6
- * work awaited by it. Everything else stays on the ordered command lane.
5
+ * pending. Interrupts cancel or adjust queued work for that command, while
6
+ * host responses can unblock UI work awaited by it. Everything else stays on
7
+ * the ordered command lane.
7
8
  */
8
9
  export declare function isConcurrentRpcControlLine(line: string): boolean;
9
10
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"rpc-input-scheduler.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-input-scheduler.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AAY7D,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,sBAAsB,CASxF;AAED;;;;GAIG;AACH,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAgBhE;AAED;;;;;GAKG;AACH,wBAAgB,uBAAuB,CAAC,UAAU,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAgC3G"}
1
+ {"version":3,"file":"rpc-input-scheduler.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-input-scheduler.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,gBAAgB,CAAC;AAc7D,wBAAgB,wBAAwB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,sBAAsB,CASxF;AAED;;;;;GAKG;AACH,wBAAgB,0BAA0B,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAgBhE;AAED;;;;;GAKG;AACH,wBAAgB,uBAAuB,CAAC,UAAU,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,CAgC3G"}
@@ -6,6 +6,8 @@ const INTERRUPT_COMMANDS = new Set([
6
6
  "abort_retry",
7
7
  "abort_bash",
8
8
  "pause_queued_messages",
9
+ "resume_queued_messages",
10
+ "clear_queue",
9
11
  ]);
10
12
  const CONCURRENT_COMMANDS = new Set(["bash", "user_bash", "refresh_models"]);
11
13
  export function isRpcExtensionUIResponse(value) {
@@ -18,8 +20,9 @@ export function isRpcExtensionUIResponse(value) {
18
20
  }
19
21
  /**
20
22
  * Control frames must remain reachable while an ordinary RPC command is
21
- * pending. Interrupts cancel that command, while host responses can unblock UI
22
- * work awaited by it. Everything else stays on the ordered command lane.
23
+ * pending. Interrupts cancel or adjust queued work for that command, while
24
+ * host responses can unblock UI work awaited by it. Everything else stays on
25
+ * the ordered command lane.
23
26
  */
24
27
  export function isConcurrentRpcControlLine(line) {
25
28
  if (parseInteractiveEngineCommand(line))
@@ -1 +1 @@
1
- {"version":3,"file":"rpc-input-scheduler.js","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-input-scheduler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,6BAA6B,EAAE,MAAM,mCAAmC,CAAC;AAGlF,MAAM,kBAAkB,GAAwB,IAAI,GAAG,CAAC;IACvD,OAAO;IACP,uBAAuB;IACvB,kBAAkB;IAClB,aAAa;IACb,YAAY;IACZ,uBAAuB;CACvB,CAAC,CAAC;AACH,MAAM,mBAAmB,GAAwB,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,WAAW,EAAE,gBAAgB,CAAC,CAAC,CAAC;AAElG,MAAM,UAAU,wBAAwB,CAAC,KAAc;IACtD,OAAO,CACN,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,MAAM,IAAI,KAAK;QACf,KAAK,CAAC,IAAI,KAAK,uBAAuB;QACtC,IAAI,IAAI,KAAK;QACb,OAAO,KAAK,CAAC,EAAE,KAAK,QAAQ,CAC5B,CAAC;AACH,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,0BAA0B,CAAC,IAAY;IACtD,IAAI,6BAA6B,CAAC,IAAI,CAAC;QAAE,OAAO,IAAI,CAAC;IACrD,IAAI,KAAoB,CAAC;IACzB,IAAI,CAAC;QACJ,MAAM,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAA8C,CAAC;QAC7E,KAAK,GAAG,OAAO,MAAM,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC;IAC9E,CAAC;IAAC,MAAM,CAAC;QACR,OAAO,KAAK,CAAC;IACd,CAAC;IACD,IAAI,wBAAwB,CAAC,KAAK,CAAC;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,CAAC,CAAC;QACzB,IAAI,CAAC,cAAc;YAAE,iBAAiB,EAAE,CAAC;IAC1C,CAAC,CAAC;AACH,CAAC","sourcesContent":["import { parseInteractiveEngineCommand } from \"../interactive-engine/protocol.ts\";\nimport type { RpcExtensionUIResponse } from \"./rpc-types.ts\";\n\nconst INTERRUPT_COMMANDS: ReadonlySet<string> = new Set([\n\t\"abort\",\n\t\"cancel_login_provider\",\n\t\"abort_compaction\",\n\t\"abort_retry\",\n\t\"abort_bash\",\n\t\"pause_queued_messages\",\n]);\nconst CONCURRENT_COMMANDS: ReadonlySet<string> = new Set([\"bash\", \"user_bash\", \"refresh_models\"]);\n\nexport function isRpcExtensionUIResponse(value: unknown): value is RpcExtensionUIResponse {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue !== null &&\n\t\t\"type\" in value &&\n\t\tvalue.type === \"extension_ui_response\" &&\n\t\t\"id\" in value &&\n\t\ttypeof value.id === \"string\"\n\t);\n}\n\n/**\n * Control frames must remain reachable while an ordinary RPC command is\n * pending. Interrupts cancel that command, while host responses can unblock UI\n * work awaited by it. Everything else stays on the ordered command lane.\n */\nexport function isConcurrentRpcControlLine(line: string): boolean {\n\tif (parseInteractiveEngineCommand(line)) return true;\n\tlet value: object | null;\n\ttry {\n\t\tconst parsed = JSON.parse(line) as object | boolean | null | number | string;\n\t\tvalue = typeof parsed === \"object\" && !Array.isArray(parsed) ? parsed : null;\n\t} catch {\n\t\treturn false;\n\t}\n\tif (isRpcExtensionUIResponse(value)) return true;\n\treturn (\n\t\tvalue !== null &&\n\t\t\"type\" in value &&\n\t\ttypeof value.type === \"string\" &&\n\t\t(INTERRUPT_COMMANDS.has(value.type) || CONCURRENT_COMMANDS.has(value.type))\n\t);\n}\n\n/**\n * Runs ordinary RPC input one frame at a time while giving validated control\n * frames and independently correlated bash executions a concurrent lane. The\n * first ordinary frame starts synchronously, so a following interrupt cannot\n * overtake initialization of the operation it is intended to cancel.\n */\nexport function createRpcInputScheduler(handleLine: (line: string) => Promise<void>): (line: string) => void {\n\tconst ordinaryQueue: string[] = [];\n\tlet ordinaryActive = false;\n\n\tconst invoke = (line: string): Promise<void> => {\n\t\ttry {\n\t\t\treturn handleLine(line);\n\t\t} catch (error) {\n\t\t\treturn Promise.reject(error);\n\t\t}\n\t};\n\n\tconst startNextOrdinary = (): void => {\n\t\tconst line = ordinaryQueue.shift();\n\t\tif (line === undefined) {\n\t\t\tordinaryActive = false;\n\t\t\treturn;\n\t\t}\n\t\tordinaryActive = true;\n\t\tvoid invoke(line)\n\t\t\t.finally(startNextOrdinary)\n\t\t\t.catch(() => {});\n\t};\n\n\treturn (line: string): void => {\n\t\tif (isConcurrentRpcControlLine(line)) {\n\t\t\tvoid invoke(line).catch(() => {});\n\t\t\treturn;\n\t\t}\n\t\tordinaryQueue.push(line);\n\t\tif (!ordinaryActive) startNextOrdinary();\n\t};\n}\n"]}
1
+ {"version":3,"file":"rpc-input-scheduler.js","sourceRoot":"","sources":["../../../src/modes/rpc/rpc-input-scheduler.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,6BAA6B,EAAE,MAAM,mCAAmC,CAAC;AAGlF,MAAM,kBAAkB,GAAwB,IAAI,GAAG,CAAC;IACvD,OAAO;IACP,uBAAuB;IACvB,kBAAkB;IAClB,aAAa;IACb,YAAY;IACZ,uBAAuB;IACvB,wBAAwB;IACxB,aAAa;CACb,CAAC,CAAC;AACH,MAAM,mBAAmB,GAAwB,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,WAAW,EAAE,gBAAgB,CAAC,CAAC,CAAC;AAElG,MAAM,UAAU,wBAAwB,CAAC,KAAc;IACtD,OAAO,CACN,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,MAAM,IAAI,KAAK;QACf,KAAK,CAAC,IAAI,KAAK,uBAAuB;QACtC,IAAI,IAAI,KAAK;QACb,OAAO,KAAK,CAAC,EAAE,KAAK,QAAQ,CAC5B,CAAC;AACH,CAAC;AAED;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EAAE,CAAC;YACxB,cAAc,GAAG,KAAK,CAAC;YACvB,OAAO;QACR,CAAC;QACD,cAAc,GAAG,IAAI,CAAC;QACtB,KAAK,MAAM,CAAC,IAAI,CAAC;aACf,OAAO,CAAC,iBAAiB,CAAC;aAC1B,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;IACnB,CAAC,CAAC;IAEF,OAAO,CAAC,IAAY,EAAQ,EAAE;QAC7B,IAAI,0BAA0B,CAAC,IAAI,CAAC,EAAE,CAAC;YACtC,KAAK,MAAM,CAAC,IAAI,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;YAClC,OAAO;QACR,CAAC;QACD,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACzB,IAAI,CAAC,cAAc;YAAE,iBAAiB,EAAE,CAAC;IAC1C,CAAC,CAAC;AACH,CAAC","sourcesContent":["import { parseInteractiveEngineCommand } from \"../interactive-engine/protocol.ts\";\nimport type { RpcExtensionUIResponse } from \"./rpc-types.ts\";\n\nconst INTERRUPT_COMMANDS: ReadonlySet<string> = new Set([\n\t\"abort\",\n\t\"cancel_login_provider\",\n\t\"abort_compaction\",\n\t\"abort_retry\",\n\t\"abort_bash\",\n\t\"pause_queued_messages\",\n\t\"resume_queued_messages\",\n\t\"clear_queue\",\n]);\nconst CONCURRENT_COMMANDS: ReadonlySet<string> = new Set([\"bash\", \"user_bash\", \"refresh_models\"]);\n\nexport function isRpcExtensionUIResponse(value: unknown): value is RpcExtensionUIResponse {\n\treturn (\n\t\ttypeof value === \"object\" &&\n\t\tvalue !== null &&\n\t\t\"type\" in value &&\n\t\tvalue.type === \"extension_ui_response\" &&\n\t\t\"id\" in value &&\n\t\ttypeof value.id === \"string\"\n\t);\n}\n\n/**\n * Control frames must remain reachable while an ordinary RPC command is\n * pending. Interrupts cancel or adjust queued work for that command, while\n * host responses can unblock UI work awaited by it. Everything else stays on\n * the ordered command lane.\n */\nexport function isConcurrentRpcControlLine(line: string): boolean {\n\tif (parseInteractiveEngineCommand(line)) return true;\n\tlet value: object | null;\n\ttry {\n\t\tconst parsed = JSON.parse(line) as object | boolean | null | number | string;\n\t\tvalue = typeof parsed === \"object\" && !Array.isArray(parsed) ? parsed : null;\n\t} catch {\n\t\treturn false;\n\t}\n\tif (isRpcExtensionUIResponse(value)) return true;\n\treturn (\n\t\tvalue !== null &&\n\t\t\"type\" in value &&\n\t\ttypeof value.type === \"string\" &&\n\t\t(INTERRUPT_COMMANDS.has(value.type) || CONCURRENT_COMMANDS.has(value.type))\n\t);\n}\n\n/**\n * Runs ordinary RPC input one frame at a time while giving validated control\n * frames and independently correlated bash executions a concurrent lane. The\n * first ordinary frame starts synchronously, so a following interrupt cannot\n * overtake initialization of the operation it is intended to cancel.\n */\nexport function createRpcInputScheduler(handleLine: (line: string) => Promise<void>): (line: string) => void {\n\tconst ordinaryQueue: string[] = [];\n\tlet ordinaryActive = false;\n\n\tconst invoke = (line: string): Promise<void> => {\n\t\ttry {\n\t\t\treturn handleLine(line);\n\t\t} catch (error) {\n\t\t\treturn Promise.reject(error);\n\t\t}\n\t};\n\n\tconst startNextOrdinary = (): void => {\n\t\tconst line = ordinaryQueue.shift();\n\t\tif (line === undefined) {\n\t\t\tordinaryActive = false;\n\t\t\treturn;\n\t\t}\n\t\tordinaryActive = true;\n\t\tvoid invoke(line)\n\t\t\t.finally(startNextOrdinary)\n\t\t\t.catch(() => {});\n\t};\n\n\treturn (line: string): void => {\n\t\tif (isConcurrentRpcControlLine(line)) {\n\t\t\tvoid invoke(line).catch(() => {});\n\t\t\treturn;\n\t\t}\n\t\tordinaryQueue.push(line);\n\t\tif (!ordinaryActive) startNextOrdinary();\n\t};\n}\n"]}
@@ -2829,7 +2829,7 @@ const result = await ctx.ui.custom<string | null>(
2829
2829
 
2830
2830
  A component mounted with `reserveTranscriptRows` always releases configured fullscreen transcript actions and vertical wheel input to the host viewport, including while a nested input has focus. The component keeps all other keyboard and mouse input, including text editing, arrows, confirmation, cancellation, and clicks. This rule applies only to reserving overlays; other focused overlays still receive page and wheel input first and can keep it by returning `true`.
2831
2831
 
2832
- Bounding a tall dialog means dropping rows, and the host would otherwise have to guess which. Embed `OVERLAY_ACTIVE_ROW_MARKER` in the line your component most needs kept — the selected row of a list — and the host places what it keeps around that row instead of taking a fixed head, even when the effective `maxHeight` is only one row. The mark is a zero-width APC sequence that `visibleWidth` measures as zero, and the host strips it before the line is painted, so it never reaches the terminal. Embed it once per frame; the host uses the first line that carries it. The `ask_user_question` dialog marks every active selectable row, including single- and multi-select options, Next, Submit, Cancel, and inline sentinel rows. Focused pi-tui inputs also anchor the bound through their cursor marker, so arrow keys and text input stay visible on a 16-row terminal.
2832
+ Bounding a tall dialog means dropping rows, and the host would otherwise have to guess which. Embed `OVERLAY_ACTIVE_ROW_MARKER` in the line your component most needs kept — the selected row of a list — and the host places what it keeps around that row instead of taking a fixed head, even when the effective `maxHeight` is only one row. The mark is a zero-width APC sequence that `visibleWidth` measures as zero, terminated with ST as ECMA-48 requires. The renderer strips it centrally, in the last transform over the composited screen before it is written out, so it never reaches the terminal — from a reserving overlay, an ordinary overlay, an inline mount, a widget, or a workflow stage chat alike. Embed it once per frame; the host uses the first line that carries it. Put it anywhere on that line: a mark buried mid-line is removed just as a trailing one is. The `ask_user_question` dialog marks every active selectable row, including single- and multi-select options, Next, Submit, Cancel, and inline sentinel rows. Focused pi-tui inputs also anchor the bound through their cursor marker, so arrow keys and text input stay visible on a 16-row terminal.
2833
2833
 
2834
2834
  ```typescript
2835
2835
  import { OVERLAY_ACTIVE_ROW_MARKER } from "@bastani/atomic";
@@ -171,6 +171,7 @@ Skills are reusable expert instructions. Trigger one with `/skill:<name>` follow
171
171
  | `impeccable` | Critique or refine web/native frontend and product UI; includes detector hooks, framework-aware live review, and mount-failure recovery. | `/skill:impeccable` |
172
172
  | `playwright-cli` | Drive a real browser for end-to-end UI checks, screenshots, and reviewable proof videos. | `/skill:playwright-cli` |
173
173
  | `liteparse` | Pull text, tables, or values out of PDF, DOCX, PPTX, XLSX, and image files locally. | `/skill:liteparse` |
174
+ | `show-me` | Explain a topic visually with concise diagrams, code-shape sketches, or focused HTML artifacts. HumanLayer, MIT licensed. | `/skill:show-me` |
174
175
 
175
176
  Impeccable 4.1.1 resolves Live sessions to the selected app root, supports SvelteKit, Nuxt, TanStack Start, Astro, Next.js, Vite, and static HTML injection, and rejects absolute, traversing, or symlinked configured write targets. Its concept roll may contact `impeccable.style`; set `IMPECCABLE_NO_TELEMETRY=1` or `DO_NOT_TRACK=1` to disable the anonymous choice ping. The image fallback runs only with `OPENAI_API_KEY`, sends prompts and optional reference images to OpenAI, and spends that account's API credit. Generated image prompts are embedded in the image or a sidecar, so do not include secrets.
176
177
 
package/docs/skills.md CHANGED
@@ -76,6 +76,10 @@ The bundled `/skill:prompt-engineer` creates, optimizes, evaluates, and troubles
76
76
 
77
77
  The skill no longer recommends response prefilling, which returns an error on Claude 4.6 and later, or visible chain-of-thought as a primary technique. Use explicit output instructions, schemas, tools, or post-processing instead of prefilling. Request conclusions, citations, commands, and observed results rather than reconstructed private reasoning; such requests can trigger Claude Fable 5's `reasoning_extraction` safeguard and force a model fallback.
78
78
 
79
+ ### Built-in visual explanation guidance
80
+
81
+ The bundled `/skill:show-me` from [HumanLayer](https://github.com/humanlayer/skills) helps explain the current topic visually with concise diagrams, code-shape sketches, and focused HTML artifacts. It is distributed under the MIT License.
82
+
79
83
  ## Skill Commands
80
84
 
81
85
  Skills register as `/skill:name` commands:
package/docs/workflows.md CHANGED
@@ -731,9 +731,9 @@ Atomic bundles nine workflows: six reusable control-flow patterns, two autonomou
731
731
  |---|---|---|
732
732
  | `classify-and-act` | Structured classifier → deterministic category action; low confidence can fall back to human selection. | Route mixed requests to isolated category-specific work. |
733
733
  | `fan-out-and-synthesize` | Structured partition → bounded parallel artifact branches → synthesis barrier. | Split independent slices, including repository research, and merge evidence. |
734
- | `adversarial-verification` | Worker → fresh rubric verifiersreducer → bounded repair loop. | Independently prove or reject a candidate. |
734
+ | `adversarial-verification` | Worker → per-criterion fresh verifier fan-outdeterministic mean+veto gate findings consolidation / bounded repair; consolidator cannot approve. | Independently prove or reject a candidate with auditable graded scores. |
735
735
  | `generate-and-filter` | Candidate fan-out → rubric dedupe/filter → optional judge → shortlist. | Explore more options than needed and keep the strongest distinct few. |
736
- | `tournament` | Whole-task attempts → balanced pairwise judgesbracket reducer. | Compare subjective or approach-sensitive solutions. |
736
+ | `tournament` | Whole-task attempts → seeded ring and pivot-round soft scoring full ranking reducer. | Compare subjective or approach-sensitive solutions. |
737
737
  | `loop-until-done` | Durable ledger → iteration/evaluator loop → success or inspectable bound exhaustion. | Continue until explicit evidence proves completion. |
738
738
  | `goal` | Durable goal ledger → bounded sub-agent orchestration → parallel review → deterministic reducer. | Autonomous implementation that needs receipts and reviewer-gated completion. |
739
739
  | `ralph` | Prompt refinement → codebase research → delegated implementation → multi-model review loop. | Research-first autonomous implementation with bounded review and repair. |
@@ -749,10 +749,10 @@ The six common patterns are full definitions exported from `@bastani/workflows/b
749
749
  |---|---|---|---|
750
750
  | `classify-and-act` | `prompt` | `categories` (1–8), `confidence_threshold` (0.5–0.99) | `result`, category, confidence, classification/action paths |
751
751
  | `fan-out-and-synthesize` | `prompt` | `max_branches` (1–12), `max_concurrency` (1–12) | `result`, partitions, branch paths, synthesis/manifest paths |
752
- | `adversarial-verification` | `task` | `verifier_count` (1–5), `max_repairs` (0–5) | `result`, approval, repairs, candidate/review/verifier paths |
752
+ | `adversarial-verification` | `task` | `criteria` (record or criteria.md markdown; defaults to task_fit/evidence/completeness), `verifier_count=3` (1–5), `max_repairs=2` (0–5), `accept_mean=14`, `reask_limit=1`; normal calls per round: criteria.length × verifier_count | `approved`, `mean_score`, `score_table_path`, `repairs_completed`, `candidate_path`, `review_report_path`, `remaining_work` |
753
753
  | `generate-and-filter` | `prompt` | `num_candidates` (2–20), `shortlist_size` (1–10), `use_judge`, `max_concurrency` | `result`, shortlist, candidate/filter/judge/final/manifest paths |
754
- | `tournament` | `prompt` | `num_attempts` (2–8), `max_concurrency` (1–8) | `result`, winner, attempt/judge/bracket paths |
755
- | `loop-until-done` | `prompt` | `max_iterations` (1–20) | `result`, `status`, ledger, iteration/evaluation paths, remaining work |
754
+ | `tournament` | `prompt` | `num_attempts` (2–8), `max_concurrency` (1–8), `n_evaluations=2`, `pivots=1`, `seed=0`, optional `criteria`/`models` | `result`, `winner`, `attempt_artifact_paths`, `judge_artifact_paths`, `comparisons_path`, `ranking`, `seed` |
755
+ | `loop-until-done` | `prompt` | `max_iterations` (1–20), `progress_scoring`, `progress_repeats` (≥1) | `result`, `status`, ledger, iteration/evaluation paths, remaining work, `progress_curve`, `final_trend`, `progress_disclaimer` |
756
756
 
757
757
  ```ts
758
758
  import {
@@ -782,6 +782,7 @@ All six can run by name or as nested definitions. Prefer composition over copyin
782
782
  Goal persists the literal objective and immutable acceptance criteria in a run ledger, delegates implementation through bounded orchestrator turns, records receipts, and asks independent reviewers to inspect the current delta. A TypeScript reducer returns `complete`, `blocked`, or `needs_human` rather than trusting free-form completion claims.
783
783
 
784
784
  Goal reviewers derive checks from the literal objective before consulting implementation receipts, inspect the actual checkout delta, and report commands, observed output, and file:line evidence rather than internal reasoning. Shared contracts cover acceptance-matrix traceability, contract-fidelity risks, end-to-end and QA-video evidence, and independent verification. `stop_review_loop` is the authoritative convergence signal: it remains `false` for P0–P2 findings, any `required_by_objective` finding, or unproven implementation/validation requirements; it becomes `true` only when independent evidence proves the objective and only non-blocking or authorized post-approval work remains. The deterministic reducer consumes that signal without reinterpreting free-form prose.
785
+ Goal and Ralph share the same low-confidence finding re-verification and per-round convergence evidence, documented under [`ralph`](#ralph).
785
786
 
786
787
  | Input | Type | Required | Default | Description |
787
788
  |---|---|---|---|---|
@@ -805,6 +806,12 @@ Ralph starts from the raw task, refines it into a research question, runs codeba
805
806
 
806
807
  Ralph uses the same canonical reviewer evidence and convergence contracts as Goal. Its reviewer prompt receives artifacts first and the review objective last, requires independently derived probes before implementation-authored evidence, and preserves unresolved findings when the bounded loop ends. Forked continuation prompts send only changed state and artifact paths instead of repeating the full established contract.
807
808
 
809
+ Goal and Ralph re-verify only an eligible consolidated finding: it must still be blocking, have exactly one reviewer, carry a finite `confidence_score` strictly below `DEFAULT_REVERIFY_THRESHOLD=0.7`, and not be aligned `beyond_objective` or `contradicts_objective`; missing confidence is not eligible. Eligible findings are rescored in fresh contexts with the primitive's default `DEFAULT_REPEATS=3`, and an invalid repeat is re-asked once before its audit entry records a null score.
810
+
811
+ Re-verification has two demotion bars. For an ordinary in-scope finding, demotion requires at least `ceil(repeatCount / 2)` valid scores and a mean below `STANDARD_CONFIRM_THRESHOLD=10`; for `required_by_objective`, every repeat must be valid and the mean must be below `REQUIRED_CONFIRM_THRESHOLD=6`. The original finding remains in the review record while the durable `reverification` audit records the verdict, mean, per-repeat scores, and evidence.
812
+
813
+ Each parsed Goal review round and Ralph review round appends convergence evidence with `unresolvedBlockingCount`, `meanFindingConfidence`, `fractionProven`, `demotions`, and folded `usage`. Goal persists it in the goal ledger's `convergence` array beside `reverification`; Ralph exposes the same per-round series in `review-round-latest.json`. The convergence classifier reports blocker and proven trends, and its escalation text is evidence only: `stop_review_loop` remains the authoritative closure signal, while review scores and convergence evidence are audit/advisory data that never approve or terminate a loop.
814
+
808
815
  | Input | Type | Required | Default | Description |
809
816
  |---|---|---|---|---|
810
817
  | `prompt` | text | yes | — | Task, issue, or spec to research, implement, and review. Keep PR/MR creation out of this text. |
@@ -1072,7 +1079,7 @@ Workflow outputs are runtime contracts for completed workflow runs and for paren
1072
1079
 
1073
1080
  **Return convention:** outputs are return-object keys. Atomic never infers child workflow outputs from stage names, stage order, or the final assistant message. If a parent should read `child.outputs.foo`, the child workflow's `run` must both declare `outputs: { foo: schema }` and return `{ foo: value }`. `result` is not special, and Atomic never adds it: to expose `result`, declare it in `outputs` and return `{ result }` exactly like any other output. Returning a key that is not declared in `outputs` fails the run with `atomic-workflows: workflow "<name>" returned undeclared output "<key>"; declare it in outputs or remove it from the run return`.
1074
1081
 
1075
- **Reserved `status` output convention and structured failures:** if a workflow declares and returns a top-level `status` output with the string value `"failed"`, Atomic treats the run as failed instead of recording a successful completion. Returned `"blocked"`, `"needs_human"`, `"incomplete"`, `"active"`, and `"auth_blocked"` statuses are treated as blocked/incomplete terminal states rather than successful completions.
1082
+ **Reserved `status` output convention and structured failures:** if a workflow declares and returns a top-level `status` output with the string value `"failed"`, Atomic treats the run as failed instead of recording a successful completion. Returned `"blocked"`, `"needs_human"`, `"incomplete"`, `"active"`, and `"auth_blocked"` statuses are treated as blocked/incomplete terminal states rather than successful completions. The engine's own system-owned `budget_exceeded` stop is likewise blocked; a workflow-returned `budget_exceeded` value cannot forge that stop and is treated as a normal completion.
1076
1083
 
1077
1084
  Independently of that convention, Atomic uses structured failure metadata captured from the run's blocking stage (`failedStageId`) or run-level failure metadata to keep recoverable auth, rate-limit, and provider fallback exhaustion blocked/resumable even when the workflow did not declare a `status` output. Atomic does not infer failure state by scanning arbitrary output text or by scanning every failed stage in an otherwise completed non-fail-fast branch.
1078
1085
 
@@ -3242,7 +3249,7 @@ Deliberate control actions on a top-level run report themselves too. `/workflow
3242
3249
 
3243
3250
  **One notice per request.** A whole-run pause or resume reports at run scope. A stage-scoped `/workflow pause <run> <stage>` that leaves other stages running reports at stage scope, and one that stops the last active stage reports the run instead — never a stage card and a run card for the same request. A quit reports only the quit, never the pause it publishes on the way. Because control actions are reversible, these notices are deduplicated by run id *and* the occurrence timestamp, so pause → resume → pause → resume emits four notices while repeated snapshot invalidations at one unchanged state emit one. Resuming reports a resume and never a start, whoever asked for it — a resumed run re-enters the dispatch path, so keying that on the resume rather than on the requester is what stops an agent-requested resume of a user-started run from being announced as a fresh launch. Resuming a failed or blocked run launches a continuation under a fresh run id, and its notice names both ("run 4d7e, continuing run 8c31"); resuming a quit run reuses the original workflow id so durable checkpoints replay, so that notice names the one id. A run that is already started, paused, or quit when notifications install — restore, replay, `/reload`, or a session-preserving reinstall — is seeded as delivered and stays silent, and nested `ctx.workflow(...)` child runs never notify at top level.
3244
3251
 
3245
- Configure lifecycle behavior with `workflowNotifications.enabled` (default `true`) and `workflowNotifications.notifyOn` (default `["started", "completed", "failed", "blocked", "awaiting_input", "paused", "quit", "resumed"]`). A config that pins `notifyOn` explicitly keeps exactly the kinds it lists, so `notifyOn: ["failed"]` suppresses every control notice.
3252
+ Configure lifecycle behavior with `workflowNotifications.enabled` (default `true`) and `workflowNotifications.notifyOn` (default `["started", "completed", "failed", "blocked", "budget_warning", "awaiting_input", "paused", "quit", "resumed"]`). A config that pins `notifyOn` explicitly keeps exactly the kinds it lists, so `notifyOn: ["failed"]` suppresses every control notice. `budget_warning` is delivered once per run and dimension through the same lifecycle-notice renderer.
3246
3253
 
3247
3254
  **Heartbeats are separate from lifecycle notices.** A lifecycle notice reports a transition; a heartbeat reports that nothing has transitioned yet. While a top-level run is active, Atomic raises one `workflows:workflow-heartbeat` card per `startedAt + n × heartbeatIntervalMinutes` boundary, on the same queued-steer delivery (`triggerTurn`, `deliverAs: "steer"`, `persistWhenStreaming`) and the same notice-card renderer, under its own custom type. The cadence is per workflow definition — `15` minutes by default, `0` to disable — and is documented under [`heartbeatIntervalMinutes`](#heartbeatintervalminutes). `workflowNotifications.notifyOn` selects lifecycle kinds only; it does not list or filter heartbeats. Heartbeats stop when the run reaches a terminal state: one idempotent cleanup pass drops its timer, its schedule, and any heartbeat still queued inside the scheduler, a later process discards those records rather than replaying them, and a card the parent's queue had already accepted is excluded from the model's context when it is read ([#1975](https://github.com/bastani-inc/atomic/issues/1975)).
3248
3255
 
@@ -3512,6 +3519,27 @@ The `/workflow` argument-completion popup reads that same live registry. Project
3512
3519
 
3513
3520
  A successful rescan may still contain per-resource diagnostics. Both reload surfaces show `CONFIG_INVALID`, `IMPORT_FAILED`, `INVALID_DEFINITION`, `PATH_NOT_FOUND`, and duplicate-name diagnostics instead of reporting bare success while silently skipping a resource. Valid sibling workflows remain available. Fix the reported source/path and reload again; no process restart is required.
3514
3521
 
3522
+ ## Run budgets
3523
+
3524
+ Set an optional `budget` on workflow extension config, an authored `workflow({...})` definition, a `workflow({ action: "run" })` tool call, or a `workflow({ action: "resume" })` continuation to raise or narrow the ceiling. Each field resolves independently: run override, then definition, then config default. An omitted field falls through; a present `0` disables that dimension.
3525
+
3526
+ ```ts
3527
+ export default workflow({
3528
+ name: "bounded-review",
3529
+ description: "Review a change within an operator-selected budget.",
3530
+ budget: { maxDurationMs: 900_000, maxTokens: 50_000, maxCost: 5, warnAtPercent: 80 },
3531
+ outputs: {},
3532
+ run: async (ctx) => {
3533
+ // ...
3534
+ return {};
3535
+ },
3536
+ });
3537
+ ```
3538
+
3539
+ `maxDurationMs` and `maxTokens` must be non-negative finite integers. `maxCost` and `warnAtPercent` must be non-negative finite numbers. Invalid config produces `CONFIG_INVALID`; invalid authored or direct-run declarations throw a `TypeError` before the workflow body runs. Nested `ctx.workflow(child)` calls use the child's own declared budget and remain subject to the root run's duration scope; a root exhaustion wins simultaneous child exhaustion, while a child-only exhaustion soft-lands that child run and returns to the parent.
3540
+
3541
+ `maxDurationMs` is enforced at stage and durable-tool boundaries using elapsed run time (paused time is excluded and resumed runs carry prior elapsed time). `maxTokens` counts uncached input plus output tokens across the complete run tree, including nested children and stage retries; cache reads and writes remain reported counters and `maxCost` charges the summed `usage.cost`. A `budget_warning` lifecycle notice is emitted once per run and dimension at `warnAtPercent` (default `80`); exhaustion gives an already-live frontier stage one current-turn wrap-up, then records a resumable `budget_exceeded` blocked result with its reading, ceiling, frontier, wrap-up summary, and the wrap-up turn's own `wrapUpUsage` when model usage is available. No new stage is created just to host a wrap-up; when no stage turn is live at the exhausting boundary, the run stops with no wrap-up summary and leaves the once-per-run delivery allowance unused. A resumed run carries prior duration, token, and cost spend without double-charging replayed completions; pass a raised resume budget to continue with the prior spend. Nested child budgets meter only their subtree while the root meter still includes child spend, and a child-only exhaustion returns to the parent as a blocked child result while the parent continues.
3542
+
3515
3543
  ## Workflow Configuration
3516
3544
 
3517
3545
  Configured workflow paths live in workflow extension config. Project config paths are relative to the project root. Global config paths are relative to `~/.atomic/agent`.
@@ -3538,12 +3566,13 @@ Example config:
3538
3566
  },
3539
3567
  "defaultConcurrency": 4,
3540
3568
  "maxDepth": 4,
3569
+ "budget": { "maxDurationMs": 0, "maxTokens": 0, "maxCost": 0, "warnAtPercent": 80 },
3541
3570
  "persistRuns": true,
3542
3571
  "statusFile": false,
3543
3572
  "resumeInFlight": "ask",
3544
3573
  "workflowNotifications": {
3545
3574
  "enabled": true,
3546
- "notifyOn": ["started", "completed", "failed", "blocked", "awaiting_input", "paused", "quit", "resumed"]
3575
+ "notifyOn": ["started", "completed", "failed", "blocked", "budget_warning", "awaiting_input", "paused", "quit", "resumed"]
3547
3576
  },
3548
3577
  "worktree": {
3549
3578
  "symlinkDirectories": ["node_modules"]
@@ -3557,11 +3586,12 @@ Runtime config defaults:
3557
3586
  |-----|---------|---------|
3558
3587
  | `defaultConcurrency` | `4` | Default concurrency for authored `ctx.parallel(...)` execution |
3559
3588
  | `maxDepth` | `4` | Maximum workflow nesting depth |
3589
+ | `budget` | `{ maxDurationMs: 0, maxTokens: 0, maxCost: 0, warnAtPercent: 80 }` | Default per-run budget declaration; `0` disables a dimension; warnings default to `80` percent |
3560
3590
  | `persistRuns` | `true` | Persist run metadata for status/resume/history |
3561
3591
  | `statusFile` | `false` | Write a derived status file; defaults under `.atomic/workflows/status.json` when enabled |
3562
3592
  | `resumeInFlight` | `"ask"` | Behavior when discovering resumable in-flight work |
3563
3593
  | `workflowNotifications.enabled` | `true` | Emit workflow lifecycle notices into the active main chat |
3564
- | `workflowNotifications.notifyOn` | `["started", "completed", "failed", "blocked", "awaiting_input", "paused", "quit", "resumed"]` | Lifecycle states to track; terminal `completed`/`failed`/`blocked` outcomes, active recoverable blocks, and the user-initiated `started`/`paused`/`quit`/`resumed` control actions on a top-level run create main-chat notices, while `awaiting_input` is tracked for dedupe/restore without waking the main agent |
3594
+ | `workflowNotifications.notifyOn` | `["started", "completed", "failed", "blocked", "budget_warning", "awaiting_input", "paused", "quit", "resumed"]` | Lifecycle states to track; terminal `completed`/`failed`/`blocked` outcomes, active recoverable blocks, duration budget warnings, and the user-initiated `started`/`paused`/`quit`/`resumed` control actions on a top-level run create main-chat notices, while `awaiting_input` is tracked for dedupe/restore without waking the main agent |
3565
3595
  | `worktree.symlinkDirectories` | `["node_modules"]` | Main-root directories symlinked into each runner-managed temporary worktree during post-creation setup |
3566
3596
 
3567
3597
  Invalid JSON or invalid shapes produce `CONFIG_INVALID` diagnostics. Missing config files are ignored.
@@ -4547,7 +4577,7 @@ These patterns organize work **inside one root lifecycle**. They do not replace
4547
4577
  | **Fan-out-and-synthesize** | The task can be split into many independent slices that benefit from clean context windows. | `ctx.parallel([...])` with separate artifacts → synthesis barrier that reads the artifacts and merges the answer. |
4548
4578
  | **Adversarial verification** | Outputs need independent checking against a rubric, security rule, factual source, or acceptance contract. | Worker stage(s) → fresh-context verifier stage(s) → reducer that accepts, rejects, or asks for repair. |
4549
4579
  | **Generate-and-filter** | You need many candidate ideas, plans, names, fixes, or hypotheses before selecting the best few. | Generator fan-out → dedupe/filter stage → optional verifier/judge → final shortlist. |
4550
- | **Tournament** | The whole task is subjective or approach-sensitive, and comparative judgment is more reliable than absolute scoring. | Several agents attempt the same task → pairwise judges compare resultsbracket reducer returns winners. |
4580
+ | **Tournament** | The whole task is subjective or approach-sensitive, and comparative judgment is more reliable than absolute scoring. | Several agents attempt the same task → seeded ring and pivot rounds score each candidate pair by criterion → reducer reports the winner and full ranking. |
4551
4581
  | **Loop until done** | The amount of work is unknown up front, such as finding all failures, mining repeated issues, or iterating until checks pass. | Bounded loop with an explicit stop condition, progress ledger, per-iteration artifacts, and a max-iteration escape hatch. |
4552
4582
  | **Constructive quorum** | Several fresh-context verifiers judge the same artifact and a tallied vote could mask a defect one verifier found or block on one verifier's misreading. | Parallel verifiers form independent preliminary verdicts → exactly one bounded Intercom evidence-exchange round (share and challenge evidence) → each emits its own final structured verdict → deterministic reducer counts votes. |
4553
4583
  | **Scope guard** | A worker or repair stage may turn valid adjacent findings into unplanned work. | Immutable contract artifact → fresh boundary or live scope checker → bounded decision artifact → forked worker continuation; correctness review stays separate. |
@@ -4636,6 +4666,17 @@ Best practices:
4636
4666
  - Separate adversarial probe design from authoritative execution. Require a structured verifier plan with each exact probe, inputs, command/assertion, expected success condition, and covered requirement/risk; then run selected compile, test, schema generation/validation, runtime, or artifact checks through durable workflow-owned `ctx.tool(...)` calls. Actual tool results—not model self-report—feed judgment and consolidated repair.
4637
4667
  - Known contracts may use direct task-specific `ctx.tool(...)` gates designed before launch; uncertain risks may use model-selected probes executed by those deterministic tools. Rerun the tools after repair until the declared pass condition or iteration limit.
4638
4668
  - Ask verifiers to find blockers and not rewrite the candidate unless you explicitly assign them to repair it. Keep pure transformations as ordinary TypeScript rather than wrapping every model-stage action in `ctx.tool`.
4669
+ - Decompose the rubric into named criteria and score each in its own call. Compound rubrics can latch onto one salient factor; the reference scan reports 76.4% for the best single criterion versus 78.3% for a three-criterion ensemble (§4.3).
4670
+ - Aggregate by mean plus an explicit veto for genuinely disqualifying findings, never a unanimity AND across verifiers: unanimity makes false-reject grow as 1−(1−p)^K while the false-accept it buys only decays as (1−p)^K. See [Verification scaling](#verification-scaling).
4671
+ - The shipped `adversarial-verification` builtin accepts `criteria` as a record of criterion names to descriptions or as a `criteria.md` Markdown string; the shared `verification-criteria` module also canonicalizes string lists and `CriterionInput` lists. Its public doors are `parse_rubric`, `normalize_criteria`, `select_criteria`, and `decide_verification`, using the `Criterion`, `CriterionInput`, `CriterionScore`, and `Finding` shapes; `NoCriteria` and `EmptyCriterion` are explicit rubric errors.
4672
+ - A `criteria.md` rubric may have a `#` title, an optional `##` section whose heading contains `ground truth` (normally `## Ground Truth Note`; the first such section wins), and must include a `##` section whose heading contains `criteri` (normally `## Criteria`) whose `### Name {#id}` headings own non-empty criterion bodies. HTML comments are ignored; an omitted `{#id}` is slugged to lowercase alphanumeric/underscore text (up to 40 characters), with a fallback `criterion` id and encounter-order `_2`/`_3` deduplication. `parse_rubric` rejects a rubric with no criterion headings or an empty criterion body.
4673
+ - `VERIFICATION_SCALE` anchors integer scores from 1 (certainly fails) through 20 (verified correct). `select_criteria` preserves the requested id order and rejects unknown ids; `decide_verification` accepts only with quorum, a mean at or above the policy threshold, and no `veto` finding, while an invalid report remains metadata rather than a score.
4674
+ - Keep a scoring family in the `SHARED HEAD ‖ VARYING TAIL` layout from `verification-prompts`: the byte-identical head contains the task, ground-truth note, candidate bodies (or caller-provided read paths), and scale anchors in that order; the tail contains only the criterion name and description plus the output-format instruction. Candidate-specific bodies stay in the shared head, not the varying tail, so sibling criteria can reuse the cached prefix.
4675
+ - Inline the whole candidate family only while every body is at most `32 * 1024` UTF-8 bytes (`MAX_INLINE_CANDIDATE_BYTES`). If any body is larger, switch the whole family to caller-bound paths, preserving path order and duplicates; an oversized pathless family is rejected rather than guessed.
4676
+ - `warm_first_fan_out` schedules the first-seen step for each prefix before releasing the remaining steps, establishing the provider's warm prefix before sibling criteria or pair slots vary. Warm failures are observed without fail-fast, the remaining phase is still attempted before the error is rethrown, and successful results return in input order.
4677
+ - The builtin input defaults are `verifier_count=3`, `max_repairs=2`, `accept_mean=14` on the 1–20 scale, and `reask_limit=1`; omitted `criteria` uses the `task_fit`, `evidence`, and `completeness` record. A round expects one schema-valid score for every criterion/verifier cell, and the normal call shape is criteria length multiplied by verifier count.
4678
+ - Invalid criterion reports are written as invalid artifacts and re-asked in bounded waves up to `reask_limit`; an invalid or missing report is counted in `invalidCount` only and is never converted into a fail vote or included in the mean. If the required quorum is still missing after the re-asks, the round is `indeterminate` rather than silently narrowing the decision.
4679
+ - `score_table_path` names the durable `verification-summary-<round>.json` for the final round. Its object contains `scores` (`criterion_id`, integer `score`, `evidence`, and `findings` with `finding` plus `severity`), `mean`, `invalidCount`, the `decision` (`accept`, `repair`, or `indeterminate` with its corresponding mean/findings or missing count), and folded `usage`; `review_report_path` carries repair guidance or quorum evidence.
4639
4680
 
4640
4681
  ##### 4. Generate-and-filter
4641
4682
 
@@ -4662,6 +4703,8 @@ Best practices:
4662
4703
  - Generate more candidates than you need, then filter hard by an explicit rubric.
4663
4704
  - Dedupe before judging so near-identical candidates do not dominate the shortlist.
4664
4705
  - Use this for exploration, naming, design options, hypotheses, and lightweight eval ideas.
4706
+ - When the filter ranks candidates rather than applying a threshold, use the same judge guidance as Tournament: graded per-criterion integer scores rather than binary keep/drop, a Bradley–Terry preference from the score gap so near-ties stay near-ties, and K repeats with candidates swapped between the A and B slots. See [Verification scaling](#verification-scaling).
4707
+ - For a custom ranking filter, reuse the shared `verification-criteria` module and its `criteria.md` parser rather than inventing a binary keep/drop rubric; stable criterion ids let the judge select the same criteria in each comparison. See [Adversarial verification](#3-adversarial-verification) for the accepted shapes and score decision.
4665
4708
 
4666
4709
  ##### 5. Tournament
4667
4710
 
@@ -4690,6 +4733,11 @@ Best practices:
4690
4733
  - Use pairwise comparison when absolute scores are noisy or subjective.
4691
4734
  - Randomize or balance presentation order where possible to reduce order bias.
4692
4735
  - Keep the judge rubric short and require rationale tied to observable criteria.
4736
+ - Have judges emit graded per-criterion integer scores rather than a binary winner, then derive a Bradley–Terry preference from the score gap so near-ties stay near-ties.
4737
+ - Repeat each pair K times with the candidates swapped between the A and B slots; the swap cancels positional bias within the pair and variance falls as O(1/K). In the reference scan's discrete-judge study, 26.7% of pairs tied at K=1; with slot swaps, the reported K=1→16 result moved from 74.7% to 77.5%.
4738
+ - See [Verification scaling](#verification-scaling) for score granularity and call-budget trade-offs.
4739
+ - The shipped tournament inputs use `num_attempts=4` and `max_concurrency=4`; `n_evaluations=2` repeats each criterion/directed pair, `pivots=1` selects the second comparison phase's pivot candidates, and `seed=0` drives the deterministic schedule. `criteria` is optional and accepts a markdown rubric, a string-to-description record, a string list, or a `CriterionInput` list; omission uses the shipped three-criterion Correctness, Completeness, and Evidence and task fit rubric. Optional ordered `models` ids are assigned round-robin to attempt slots.
4740
+ - `comparisons_path` points to `comparisons.json`, whose ledger records the task and seed, `params` (`n`, `pivots`, `n_evaluations`, and normalized `criteria`), per-job `comparisons` rows (`a`, `b`, phase, criterion id, repeat, slot-swap flag, scores or an `invalid` marker, preference, and judge artifact path), aggregate `pairs`, weights/counts, the complete `ranking`, and optional model assignment. Its `budget` records planned versus executed judge stages, including re-asks; invalid reports remain auditable rows and an all-invalid pair remains marked invalid rather than becoming a score.
4693
4741
 
4694
4742
  ##### 6. Loop until done
4695
4743
 
@@ -4715,6 +4763,11 @@ Best practices:
4715
4763
  - Keep a durable ledger of attempted work, findings, failures, and validation evidence.
4716
4764
  - Bound loops by iterations, budget, or convergence criteria so exhausting a bound produces an inspectable failure instead of letting the loop continue indefinitely.
4717
4765
  - Materialize every iteration as distinct tracked work with stable iteration identity and call order. Never represent repetition by a self-edge, a back-edge to an ancestor, or reopening an ancestor below its downstream work.
4766
+ - Record a progress magnitude in the ledger beside the boolean stop bit; a flat or decreasing series is the stall signal that the loop is burning iterations without moving.
4767
+ - Treat the trend as a monitoring and escalate-to-human signal, never a kill switch: the explicit stop condition remains authoritative. See [Verification scaling](#verification-scaling).
4768
+ - The builtin defaults `max_iterations=5`, `progress_scoring=true`, and `progress_repeats=1`; set `progress_scoring` false to omit advisory scoring, while `progress_repeats` is the repeat count passed to the scoring primitive. Each scored iteration adds a `progress` entry to `progress-ledger.json` with `score`, `perRepeat` (null for an invalid repeat), `trend`, and the classifier `window`; the ledger also emits `progress_curve`, `final_trend`, and `progress_disclaimer`.
4769
+ - Progress scores use the anchored 1–20 scale and average valid repeat scores per checkpoint. `classify_trend` uses `window=3`, `riseDelta=1.5`, and `fallDelta=-1.5`; it compares equal leading/trailing halves of the trailing two windows, drops an odd middle sample, and classifies inclusive threshold crossings as `rising`, `flat`, or `regressing`. A short series is `flat` evidence.
4770
+ - The trend is monitoring and escalation evidence only: it never kills, terminates, or approves a loop, and the explicit evaluator stop condition remains authoritative. `progress_curve`, `final_trend`, and `progress_disclaimer` are advisory outputs, not alternate closure signals.
4718
4771
 
4719
4772
  ##### 7. Constructive quorum
4720
4773
 
@@ -4891,6 +4944,17 @@ The `prepareSliceWorktree` tools run before their child boundaries and use `git
4891
4944
 
4892
4945
  Use `ralph` or a task-specific child in the same positions when its input contract fits better. For a longer stack, keep the same explicit downstream shape: create each next named branch from the previous verified branch, pass that previous branch as the next child's `base_branch`, and use a distinct worktree. Do not replace the chain with a loop that points back to an ancestor. A final handoff can report `slice → branch → worktree → verified/failed` from the explicit inputs and preparation records without reopening completed child work.
4893
4946
 
4947
+ #### Verification scaling
4948
+
4949
+ This is authoring guidance for custom workflows, not a description of shipped builtin inputs:
4950
+
4951
+ - Use an anchored 1–20 integer scale as the default score granularity.
4952
+ - Providers expose no token logprobs, so a K-sample average is the substitute; K=16 parity costs roughly 16× the call cost, making K a budget decision.
4953
+ - Treat pool diversity as a bet on the selector's oracle ceiling. In the reference scan's pivot tournament, best-of-3 selection reached 86.5% ±1.1 against 79.4% pass@1 with a 92.1% oracle ceiling, while best-of-5 reached 88.0% ±0.6 against 78.7% pass@1 with a 96.6% oracle ceiling. A chance-level selector can make a more diverse pool worse, so widen the pool only once the judge beats chance.
4954
+ - Self-verification—having the same model judge its own rollouts—still gained +7.1 over pass@1 in the best-of-3 comparison (86.5% versus 79.4%) and +9.3 in the best-of-5 comparison (88.0% versus 78.7%).
4955
+ - For a cheap operating point, an author can use one pivot and K=2 repeats for a best-of-3-shaped comparison budget; this is an authoring recipe, not a shipped default.
4956
+ - For the shipped primitive references, see [Adversarial verification](#3-adversarial-verification) for criteria parsing, warm-first scoring, re-asks, and score summaries; [Tournament](#5-tournament) for inputs and `comparisons.json`; [Loop until done](#6-loop-until-done) for progress ledger/trend outputs; and [Goal](#goal)/[Ralph](#ralph) for re-verification and convergence evidence.
4957
+
4894
4958
  #### Choosing a common workflow pattern
4895
4959
 
4896
4960
  - Pick **classify-and-act** when routing correctness matters more than breadth.