create-principles-disciple 1.150.2 → 1.150.4

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 (267) hide show
  1. package/_release/product-identity.json +1 -1
  2. package/codex-adapter/dist/ingestion/admission.js +2 -0
  3. package/codex-adapter/dist/pd-hook.d.ts +7 -5
  4. package/codex-adapter/dist/pd-hook.js +18 -7
  5. package/codex-adapter/dist/tool-semantics.js +5 -1
  6. package/codex-adapter/dist/worker/workspace-worker.js +4 -2
  7. package/codex-adapter/package.json +1 -1
  8. package/console/dist/lib/utils.js +16 -1
  9. package/console/dist/web/assets/app.css +147 -46
  10. package/console/dist/web/assets/app.js +35 -32
  11. package/console/package.json +2 -0
  12. package/core/dist/runtime/activation/adaptive-selection-output.d.ts +35 -0
  13. package/core/dist/runtime/activation/adaptive-selection-output.d.ts.map +1 -0
  14. package/core/dist/runtime/activation/adaptive-selection-output.js +38 -0
  15. package/core/dist/runtime/activation/adaptive-selection-output.js.map +1 -0
  16. package/core/dist/runtime/activation-compatibility-read-model.d.ts.map +1 -1
  17. package/core/dist/runtime/activation-compatibility-read-model.js +2 -1
  18. package/core/dist/runtime/activation-compatibility-read-model.js.map +1 -1
  19. package/core/dist/runtime/adapter/artificer-l2-adapter.d.ts.map +1 -1
  20. package/core/dist/runtime/adapter/artificer-l2-adapter.js +89 -27
  21. package/core/dist/runtime/adapter/artificer-l2-adapter.js.map +1 -1
  22. package/core/dist/runtime/adapter/context-budget.d.ts +49 -0
  23. package/core/dist/runtime/adapter/context-budget.d.ts.map +1 -0
  24. package/core/dist/runtime/adapter/context-budget.js +127 -0
  25. package/core/dist/runtime/adapter/context-budget.js.map +1 -0
  26. package/core/dist/runtime/adapter/output-schema-registry.d.ts.map +1 -1
  27. package/core/dist/runtime/adapter/output-schema-registry.js +7 -0
  28. package/core/dist/runtime/adapter/output-schema-registry.js.map +1 -1
  29. package/core/dist/runtime/adapter/pi-ai-runtime-adapter.d.ts +30 -7
  30. package/core/dist/runtime/adapter/pi-ai-runtime-adapter.d.ts.map +1 -1
  31. package/core/dist/runtime/adapter/pi-ai-runtime-adapter.js +559 -211
  32. package/core/dist/runtime/adapter/pi-ai-runtime-adapter.js.map +1 -1
  33. package/core/dist/runtime/candidate-audit.d.ts.map +1 -1
  34. package/core/dist/runtime/candidate-audit.js +2 -1
  35. package/core/dist/runtime/candidate-audit.js.map +1 -1
  36. package/core/dist/runtime/config/pd-config-effective.d.ts.map +1 -1
  37. package/core/dist/runtime/config/pd-config-effective.js +2 -0
  38. package/core/dist/runtime/config/pd-config-effective.js.map +1 -1
  39. package/core/dist/runtime/config/pd-config-types.d.ts +52 -0
  40. package/core/dist/runtime/config/pd-config-types.d.ts.map +1 -1
  41. package/core/dist/runtime/config/pd-config-types.js.map +1 -1
  42. package/core/dist/runtime/config/pd-config-validate.d.ts.map +1 -1
  43. package/core/dist/runtime/config/pd-config-validate.js +134 -0
  44. package/core/dist/runtime/config/pd-config-validate.js.map +1 -1
  45. package/core/dist/runtime/feature-flags/feature-flag-contract.d.ts.map +1 -1
  46. package/core/dist/runtime/feature-flags/feature-flag-contract.js +8 -0
  47. package/core/dist/runtime/feature-flags/feature-flag-contract.js.map +1 -1
  48. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.d.ts.map +1 -1
  49. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js +24 -0
  50. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js.map +1 -1
  51. package/core/dist/runtime/index.d.ts +2 -0
  52. package/core/dist/runtime/index.d.ts.map +1 -1
  53. package/core/dist/runtime/index.js +2 -0
  54. package/core/dist/runtime/index.js.map +1 -1
  55. package/core/dist/runtime/internalization/rule-host-input-builder.d.ts +16 -0
  56. package/core/dist/runtime/internalization/rule-host-input-builder.d.ts.map +1 -1
  57. package/core/dist/runtime/internalization/rule-host-input-builder.js +18 -0
  58. package/core/dist/runtime/internalization/rule-host-input-builder.js.map +1 -1
  59. package/core/dist/runtime/internalization/split-diagnostician-runner.d.ts +8 -0
  60. package/core/dist/runtime/internalization/split-diagnostician-runner.d.ts.map +1 -1
  61. package/core/dist/runtime/internalization/split-diagnostician-runner.js +24 -2
  62. package/core/dist/runtime/internalization/split-diagnostician-runner.js.map +1 -1
  63. package/core/dist/runtime/internalization/tool-semantic-registry.d.ts +26 -0
  64. package/core/dist/runtime/internalization/tool-semantic-registry.d.ts.map +1 -1
  65. package/core/dist/runtime/internalization/tool-semantic-registry.js +55 -5
  66. package/core/dist/runtime/internalization/tool-semantic-registry.js.map +1 -1
  67. package/core/dist/runtime/internalization-chain-integrity-read-model.d.ts.map +1 -1
  68. package/core/dist/runtime/internalization-chain-integrity-read-model.js +2 -2
  69. package/core/dist/runtime/internalization-chain-integrity-read-model.js.map +1 -1
  70. package/core/dist/runtime/internalization-integrity-remediation.d.ts.map +1 -1
  71. package/core/dist/runtime/internalization-integrity-remediation.js +2 -2
  72. package/core/dist/runtime/internalization-integrity-remediation.js.map +1 -1
  73. package/core/dist/runtime/operator-health-read-model.d.ts.map +1 -1
  74. package/core/dist/runtime/operator-health-read-model.js +2 -2
  75. package/core/dist/runtime/operator-health-read-model.js.map +1 -1
  76. package/core/dist/runtime/pain-recall-read-model.d.ts.map +1 -1
  77. package/core/dist/runtime/pain-recall-read-model.js +4 -3
  78. package/core/dist/runtime/pain-recall-read-model.js.map +1 -1
  79. package/core/dist/runtime/pruning-read-model.d.ts.map +1 -1
  80. package/core/dist/runtime/pruning-read-model.js +3 -2
  81. package/core/dist/runtime/pruning-read-model.js.map +1 -1
  82. package/core/dist/runtime/risk/risk-calculator-policy.d.ts +12 -2
  83. package/core/dist/runtime/risk/risk-calculator-policy.d.ts.map +1 -1
  84. package/core/dist/runtime/risk/risk-calculator-policy.js +33 -22
  85. package/core/dist/runtime/risk/risk-calculator-policy.js.map +1 -1
  86. package/core/dist/runtime/schema-conformance-read-model.js +2 -2
  87. package/core/dist/runtime/schema-conformance-read-model.js.map +1 -1
  88. package/core/dist/runtime/store/sqlite-connection.d.ts +0 -5
  89. package/core/dist/runtime/store/sqlite-connection.d.ts.map +1 -1
  90. package/core/dist/runtime/store/sqlite-connection.js +4 -12
  91. package/core/dist/runtime/store/sqlite-connection.js.map +1 -1
  92. package/core/dist/runtime/store/storage-paths.d.ts +17 -0
  93. package/core/dist/runtime/store/storage-paths.d.ts.map +1 -0
  94. package/core/dist/runtime/store/storage-paths.js +52 -0
  95. package/core/dist/runtime/store/storage-paths.js.map +1 -0
  96. package/core/dist/runtime/trajectory-retention.d.ts +257 -0
  97. package/core/dist/runtime/trajectory-retention.d.ts.map +1 -0
  98. package/core/dist/runtime/trajectory-retention.js +598 -0
  99. package/core/dist/runtime/trajectory-retention.js.map +1 -0
  100. package/core/dist/telemetry-event.d.ts +2 -2
  101. package/core/dist/telemetry-event.d.ts.map +1 -1
  102. package/core/dist/telemetry-event.js +5 -0
  103. package/core/dist/telemetry-event.js.map +1 -1
  104. package/core/dist/trajectory-store.d.ts +9 -9
  105. package/core/dist/trajectory-store.d.ts.map +1 -1
  106. package/core/dist/trajectory-store.js +9 -12
  107. package/core/dist/trajectory-store.js.map +1 -1
  108. package/core/package.json +1 -1
  109. package/dist/installers/codex-host-installer.d.ts.map +1 -1
  110. package/dist/installers/codex-host-installer.js +92 -5
  111. package/dist/installers/codex-host-installer.js.map +1 -1
  112. package/dist/installers/mcp-binding-shape-mirror.d.ts +27 -0
  113. package/dist/installers/mcp-binding-shape-mirror.d.ts.map +1 -0
  114. package/dist/installers/mcp-binding-shape-mirror.js +105 -0
  115. package/dist/installers/mcp-binding-shape-mirror.js.map +1 -0
  116. package/dist/skill-catalog.d.ts +35 -0
  117. package/dist/skill-catalog.d.ts.map +1 -0
  118. package/dist/skill-catalog.js +85 -0
  119. package/dist/skill-catalog.js.map +1 -0
  120. package/dist/skill-delivery-parity.d.ts +22 -0
  121. package/dist/skill-delivery-parity.d.ts.map +1 -0
  122. package/dist/skill-delivery-parity.js +31 -0
  123. package/dist/skill-delivery-parity.js.map +1 -0
  124. package/host-runtime/dist/active-principle-prompt.d.ts +8 -0
  125. package/host-runtime/dist/active-principle-prompt.js +15 -5
  126. package/host-runtime/dist/adaptive-decision-protocol.d.ts +142 -0
  127. package/host-runtime/dist/adaptive-decision-protocol.js +190 -0
  128. package/host-runtime/dist/adaptive-priority-provider.d.ts +37 -13
  129. package/host-runtime/dist/adaptive-priority-provider.js +65 -62
  130. package/host-runtime/dist/adaptive-selection.d.ts +67 -62
  131. package/host-runtime/dist/adaptive-selection.js +218 -301
  132. package/host-runtime/dist/adaptive-skip-decision.d.ts +26 -14
  133. package/host-runtime/dist/adaptive-skip-decision.js +33 -29
  134. package/host-runtime/dist/codex-rule-context-provider.js +4 -1
  135. package/host-runtime/dist/governance-observation-store.d.ts +40 -1
  136. package/host-runtime/dist/governance-observation-store.js +188 -9
  137. package/host-runtime/dist/governance-signal-admission.d.ts +19 -3
  138. package/host-runtime/dist/governance-signal-admission.js +12 -4
  139. package/host-runtime/dist/host-tool-declaration.d.ts +18 -2
  140. package/host-runtime/dist/host-tool-declaration.js +67 -11
  141. package/host-runtime/dist/host-tool-semantic-resolver.d.ts +7 -0
  142. package/host-runtime/dist/host-tool-semantic-resolver.js +22 -2
  143. package/host-runtime/dist/index.d.ts +3 -0
  144. package/host-runtime/dist/index.js +14 -0
  145. package/host-runtime/dist/production-rulehost-gate.js +36 -4
  146. package/host-runtime/dist/trajectory-retention.d.ts +147 -0
  147. package/host-runtime/dist/trajectory-retention.js +907 -0
  148. package/host-runtime/package.json +1 -1
  149. package/install-layout/dist/index.d.ts +9 -2
  150. package/install-layout/dist/index.js +26 -9
  151. package/install-layout/dist/mcp-binding-contract.d.ts +91 -0
  152. package/install-layout/dist/mcp-binding-contract.js +230 -0
  153. package/install-layout/package.json +1 -1
  154. package/package.json +4 -4
  155. package/pd-cli/dist/commands/build-trajectory-evidence.d.ts.map +1 -1
  156. package/pd-cli/dist/commands/build-trajectory-evidence.js +17 -11
  157. package/pd-cli/dist/commands/build-trajectory-evidence.js.map +1 -1
  158. package/pd-cli/dist/commands/codex-reconcile.d.ts +7 -0
  159. package/pd-cli/dist/commands/codex-reconcile.d.ts.map +1 -1
  160. package/pd-cli/dist/commands/codex-reconcile.js +11 -2
  161. package/pd-cli/dist/commands/codex-reconcile.js.map +1 -1
  162. package/pd-cli/dist/commands/codex-worker.d.ts.map +1 -1
  163. package/pd-cli/dist/commands/codex-worker.js +35 -0
  164. package/pd-cli/dist/commands/codex-worker.js.map +1 -1
  165. package/pd-cli/dist/commands/command-helpers.d.ts +1 -1
  166. package/pd-cli/dist/commands/command-helpers.js +1 -1
  167. package/pd-cli/dist/commands/errors-list.d.ts +1 -1
  168. package/pd-cli/dist/commands/errors-list.js +1 -1
  169. package/pd-cli/dist/commands/health-mcp.d.ts +23 -1
  170. package/pd-cli/dist/commands/health-mcp.d.ts.map +1 -1
  171. package/pd-cli/dist/commands/health-mcp.js +81 -22
  172. package/pd-cli/dist/commands/health-mcp.js.map +1 -1
  173. package/pd-cli/dist/commands/health.d.ts +1 -1
  174. package/pd-cli/dist/commands/health.d.ts.map +1 -1
  175. package/pd-cli/dist/commands/health.js +12 -5
  176. package/pd-cli/dist/commands/health.js.map +1 -1
  177. package/pd-cli/dist/commands/principles-stats.d.ts +1 -1
  178. package/pd-cli/dist/commands/principles-stats.js +1 -1
  179. package/pd-cli/dist/commands/trajectory-retention.d.ts +23 -0
  180. package/pd-cli/dist/commands/trajectory-retention.d.ts.map +1 -0
  181. package/pd-cli/dist/commands/trajectory-retention.js +159 -0
  182. package/pd-cli/dist/commands/trajectory-retention.js.map +1 -0
  183. package/pd-cli/dist/commands/workbuddy-setup.d.ts +69 -0
  184. package/pd-cli/dist/commands/workbuddy-setup.d.ts.map +1 -0
  185. package/pd-cli/dist/commands/workbuddy-setup.js +379 -0
  186. package/pd-cli/dist/commands/workbuddy-setup.js.map +1 -0
  187. package/pd-cli/dist/commands/workbuddy-worker.d.ts.map +1 -1
  188. package/pd-cli/dist/commands/workbuddy-worker.js +42 -6
  189. package/pd-cli/dist/commands/workbuddy-worker.js.map +1 -1
  190. package/pd-cli/dist/index.d.ts +1 -7
  191. package/pd-cli/dist/index.d.ts.map +1 -1
  192. package/pd-cli/dist/index.js +15 -1201
  193. package/pd-cli/dist/index.js.map +1 -1
  194. package/pd-cli/dist/program.d.ts +17 -0
  195. package/pd-cli/dist/program.d.ts.map +1 -0
  196. package/pd-cli/dist/program.js +1263 -0
  197. package/pd-cli/dist/program.js.map +1 -0
  198. package/pd-cli/dist/services/delivery-surfaces.d.ts.map +1 -1
  199. package/pd-cli/dist/services/delivery-surfaces.js +7 -5
  200. package/pd-cli/dist/services/delivery-surfaces.js.map +1 -1
  201. package/pd-cli/dist/services/version-report.d.ts.map +1 -1
  202. package/pd-cli/dist/services/version-report.js +30 -4
  203. package/pd-cli/dist/services/version-report.js.map +1 -1
  204. package/pd-cli/package.json +1 -1
  205. package/pd-mcp-server/dist/version.d.ts +1 -1
  206. package/pd-mcp-server/dist/version.js +1 -1
  207. package/pd-mcp-server/package.json +3 -1
  208. package/plugin/dist/bundle.js +477 -471
  209. package/plugin/dist/constants/tools.d.ts +8 -1
  210. package/plugin/dist/core/trajectory-retention-trigger.d.ts +13 -0
  211. package/plugin/dist/core/trajectory.d.ts +14 -0
  212. package/plugin/dist/hooks/gate-block-helper.d.ts +17 -0
  213. package/plugin/dist/hooks/gate.d.ts +7 -2
  214. package/plugin/dist/host-runtime/openclaw-host-runtime.d.ts +1 -0
  215. package/plugin/dist/index.d.ts +5 -0
  216. package/plugin/dist/openclaw.plugin.json +1 -1
  217. package/plugin/dist/rulehost-evidence.js +29 -23
  218. package/plugin/dist/templates/langs/en/skills/pd-cli-operator/SKILL.md +16 -5
  219. package/plugin/dist/templates/langs/en/skills/pd-control/SKILL.md +7 -6
  220. package/plugin/dist/templates/langs/en/skills/pd-pain-signal/SKILL.md +141 -28
  221. package/plugin/dist/templates/langs/en/skills/pd-review/SKILL.md +15 -1
  222. package/plugin/dist/templates/langs/zh/skills/pd-cli-operator/SKILL.md +16 -5
  223. package/plugin/dist/templates/langs/zh/skills/pd-control/SKILL.md +7 -6
  224. package/plugin/dist/templates/langs/zh/skills/pd-pain-signal/SKILL.md +142 -29
  225. package/plugin/dist/templates/langs/zh/skills/pd-review/SKILL.md +15 -1
  226. package/plugin/openclaw.plugin.json +1 -1
  227. package/plugin/package.json +1 -1
  228. package/plugin/templates/langs/en/skills/pd-cli-operator/SKILL.md +16 -5
  229. package/plugin/templates/langs/en/skills/pd-control/SKILL.md +7 -6
  230. package/plugin/templates/langs/en/skills/pd-pain-signal/SKILL.md +141 -28
  231. package/plugin/templates/langs/en/skills/pd-review/SKILL.md +15 -1
  232. package/plugin/templates/langs/zh/skills/pd-cli-operator/SKILL.md +16 -5
  233. package/plugin/templates/langs/zh/skills/pd-control/SKILL.md +7 -6
  234. package/plugin/templates/langs/zh/skills/pd-pain-signal/SKILL.md +142 -29
  235. package/plugin/templates/langs/zh/skills/pd-review/SKILL.md +15 -1
  236. package/release-manager/dist/installers/codex-host-installer.js +92 -5
  237. package/release-manager/dist/installers/mcp-binding-shape-mirror.js +105 -0
  238. package/release-manager/package.json +1 -1
  239. package/workbuddy-adapter/dist/codec/input-decoder.d.ts +10 -0
  240. package/workbuddy-adapter/dist/codec/input-decoder.js +62 -5
  241. package/workbuddy-adapter/dist/host-adapter.js +1 -0
  242. package/workbuddy-adapter/dist/index.d.ts +1 -0
  243. package/workbuddy-adapter/dist/index.js +1 -0
  244. package/workbuddy-adapter/dist/ingestion/catch-up.d.ts +25 -0
  245. package/workbuddy-adapter/dist/ingestion/catch-up.js +161 -0
  246. package/workbuddy-adapter/dist/ingestion/encode-cwd.d.ts +6 -0
  247. package/workbuddy-adapter/dist/ingestion/encode-cwd.js +39 -0
  248. package/workbuddy-adapter/dist/ingestion/index.d.ts +13 -0
  249. package/workbuddy-adapter/dist/ingestion/index.js +13 -0
  250. package/workbuddy-adapter/dist/ingestion/ingestion.d.ts +46 -0
  251. package/workbuddy-adapter/dist/ingestion/ingestion.js +135 -0
  252. package/workbuddy-adapter/dist/ingestion/transcript-decoder.d.ts +70 -0
  253. package/workbuddy-adapter/dist/ingestion/transcript-decoder.js +554 -0
  254. package/workbuddy-adapter/dist/ingestion/transcript-path.d.ts +39 -0
  255. package/workbuddy-adapter/dist/ingestion/transcript-path.js +117 -0
  256. package/workbuddy-adapter/dist/ingestion/transcript-source.d.ts +15 -0
  257. package/workbuddy-adapter/dist/ingestion/transcript-source.js +152 -0
  258. package/workbuddy-adapter/dist/pd-hook.d.ts +8 -0
  259. package/workbuddy-adapter/dist/pd-hook.js +59 -2
  260. package/workbuddy-adapter/dist/worker/workspace-worker.d.ts +9 -0
  261. package/workbuddy-adapter/dist/worker/workspace-worker.js +46 -17
  262. package/workbuddy-adapter/package.json +1 -1
  263. package/workbuddy-adapter/plugin/hooks/hooks.json +11 -0
  264. package/workbuddy-adapter/plugin/skills/pd-cli-operator/SKILL.md +57 -19
  265. package/workbuddy-adapter/plugin/skills/pd-control/SKILL.md +21 -9
  266. package/workbuddy-adapter/plugin/skills/pd-pain-signal/SKILL.md +72 -61
  267. package/workbuddy-adapter/plugin/skills/pd-review/SKILL.md +27 -12
@@ -4,46 +4,42 @@
4
4
  * ONE implementation of the bounded "current turn → pick at most one candidate"
5
5
  * protocol, shared by the selector lab and the production host runtimes.
6
6
  *
7
- * Contract highlights (PRI-1122 measurement findings):
8
- * - Candidates are sent with a LOCALLY PRECOMPUTED digest. The model can only
9
- * copy it; it is never asked to compute a hash. A payload without digests
10
- * makes every `selected` answer invalid by construction.
7
+ * PRI-1182 replaced the free-form chat-completions selector with the verified
8
+ * Decisions scoring protocol (`scripts/dev/adaptive-selector-lab/diagnostic.mjs`):
9
+ * one POST carries every candidate's applicability condition plus one
10
+ * "insufficient context" condition; the model returns an INDEPENDENT score per
11
+ * question; PD validates and adjudicates locally
12
+ * (`adaptive-decision-protocol.ts`). The model is never asked to emit a
13
+ * decision, a ref, or a digest.
14
+ *
15
+ * Contract highlights, unchanged from PRI-1122:
11
16
  * - The incremental deadline is a FIRST-BYTE deadline, not a whole-generation
12
17
  * wall clock. Once the endpoint has started answering, generation is bounded
13
18
  * by its own window; late completions are still discarded.
14
19
  * - One real send per turn, zero retries, zero repair, zero provider fallback.
20
+ * - The host deadline can only shorten the request's own short limit.
15
21
  * - Diagnostics never carry the raw prompt, the raw response, or credentials.
16
22
  */
17
23
  import crypto from 'node:crypto';
18
- import { PiAiRuntimeAdapter, StoreEventEmitter, } from '@principles/core/runtime';
19
- import { readPromptActivationCandidates } from './active-principle-prompt.js';
20
24
  import { revalidateAdaptivePrinciple } from './adaptive-principle-revalidation.js';
25
+ import { adjudicateDecision, buildDecisionRequest, validateDecisionResponse, } from './adaptive-decision-protocol.js';
21
26
  export const ADAPTIVE_SELECTION_LIMITS = {
22
27
  maxCandidates: 12,
23
28
  maxCandidateChars: 600,
24
29
  maxPriorMessages: 4,
25
30
  maxPriorMessageChars: 1200,
26
31
  maxInputChars: 6000,
27
- /** Admission (time-to-first-byte) deadline for the incremental step. */
28
- firstByteTimeoutMs: 10_000,
29
- /** Bounded completion window once the endpoint has started answering. */
30
- generationTimeoutMs: 10_000,
31
- maxOutputTokens: 512,
32
+ /** Total time from sending a decision request to validating the full response. */
33
+ requestTimeoutMs: 2000,
34
+ /** Bounded outbound payload (current instruction + candidate snapshot + conditions). */
35
+ maxPayloadChars: 20_000,
36
+ /** Bounded response body; a Decisions answer table is a few KB at most. */
37
+ maxResponseBytes: 65_536,
38
+ /** Bounded provider usage projection is unnecessary: only token counts are kept. */
32
39
  };
33
40
  export function hash(value) {
34
41
  return crypto.createHash('sha256').update(value, 'utf8').digest('hex');
35
42
  }
36
- export const ADAPTIVE_SELECTOR_SYSTEM = [
37
- '你是 Principles Disciple 的原则选择器。只判断:当前用户输入是否需要追加一条已批准原则。',
38
- '候选只在「当前输入明确要求交付、实现、修复、审查或验证,且这条原则会改变你这一步的做法」时才算适用。',
39
- '通用礼貌、闲聊、元问题、与当前任务无关的原则一律不选。',
40
- '只能返回下面三种 JSON 之一,不要 Markdown、不要解释:',
41
- '{"status":"selected","id":"候选引用(例如 c1)","digest":"该候选随附的 digest 原样复制;不要计算或改写","reason":"一句话理由"}',
42
- '{"status":"none_applicable","id":null,"digest":null,"reason":"一句话理由"}',
43
- '{"status":"uncertain","id":null,"digest":null,"reason":"一句话理由"}',
44
- 'digest 由本地预计算并随候选下发;必须逐字符原样返回所选候选的 digest。',
45
- '最多只能选一条。',
46
- ].join('\n');
47
43
  function boundText(value, max) {
48
44
  const text = value.replace(/\s+/gu, ' ').trim();
49
45
  if (text.length <= max)
@@ -74,8 +70,9 @@ export function buildBoundedSelectionInput(input) {
74
70
  entries.push({
75
71
  ref: `c${entries.length + 1}`,
76
72
  text: candidateText,
77
- // Digest the body exactly as it goes on the wire, so the model can copy it
78
- // and anyone can recompute it from the request it actually received.
73
+ // The digest stays part of the frozen candidate snapshot even though the
74
+ // Decisions protocol scores question ids instead of asking for a ref: it
75
+ // lets a later reader recompute exactly what was sent.
79
76
  digest: hash(candidateText),
80
77
  principle,
81
78
  });
@@ -90,7 +87,6 @@ export function buildBoundedSelectionInput(input) {
90
87
  payload: {
91
88
  currentInstruction,
92
89
  priorMessages: boundedPrior,
93
- // The digest is part of the outbound contract: the model copies it.
94
90
  candidates: entries.map((entry) => ({ ref: entry.ref, text: entry.text, digest: entry.digest })),
95
91
  },
96
92
  entries,
@@ -102,152 +98,92 @@ export function buildBoundedSelectionInput(input) {
102
98
  function isRecord(value) {
103
99
  return value !== null && typeof value === 'object' && !Array.isArray(value);
104
100
  }
105
- export function parseSelectionShape(value) {
106
- if (!isRecord(value)) {
107
- return { ok: false, reason: 'SELECTION_OUTPUT_INVALID' };
108
- }
109
- const { status } = value;
110
- const { id } = value;
111
- const { digest } = value;
112
- if (status === 'selected') {
113
- if (typeof id !== 'string' || !id)
114
- return { ok: false, reason: 'SELECTION_OUTPUT_INVALID' };
115
- if (typeof digest !== 'string' || !digest)
116
- return { ok: false, reason: 'SELECTION_DIGEST_INVALID' };
117
- return { ok: true, selection: { status: 'selected', id, digest } };
118
- }
119
- if (status === 'none_applicable' || status === 'uncertain') {
120
- if (id !== null && id !== undefined)
121
- return { ok: false, reason: 'SELECTION_OUTPUT_INVALID' };
122
- if (digest !== null && digest !== undefined)
123
- return { ok: false, reason: 'SELECTION_OUTPUT_INVALID' };
124
- return { ok: true, selection: { status, id: null, digest: null } };
125
- }
126
- return { ok: false, reason: 'SELECTION_OUTPUT_INVALID' };
127
- }
128
- export function validateSelectionResult(value, entries) {
129
- const parsed = parseSelectionShape(value);
130
- if (!parsed.ok) {
131
- return {
132
- ok: false,
133
- reason: parsed.reason,
134
- refValid: null,
135
- digestValid: null,
136
- };
137
- }
138
- const { selection } = parsed;
139
- if (selection.status !== 'selected') {
140
- return {
141
- ok: true,
142
- selected: null,
143
- outcome: selection.status === 'uncertain' ? 'uncertain' : 'no_increment',
144
- };
145
- }
146
- const entry = entries.find((candidate) => candidate.ref === selection.id);
147
- if (!entry) {
148
- return { ok: false, reason: 'SELECTION_REFERENCE_INVALID', refValid: false, digestValid: null };
149
- }
150
- // Two independent computations of the wire-body digest must agree: the value
151
- // frozen into the candidate table and a fresh hash of the frozen body.
152
- if (selection.digest !== entry.digest || selection.digest !== hash(entry.text)) {
153
- return { ok: false, reason: 'SELECTION_DIGEST_INVALID', refValid: true, digestValid: false };
154
- }
155
- if (entries.some((candidate) => candidate !== entry && candidate.principle.principleId === entry.principle.principleId)) {
156
- return { ok: false, reason: 'SELECTION_AMBIGUOUS', refValid: true, digestValid: true };
157
- }
158
- return { ok: true, selected: entry, outcome: 'selected' };
159
- }
160
- export function localFailureCode(reason) {
161
- if (reason === 'SELECTION_OUTPUT_INVALID')
162
- return 'SELECTION_OUTPUT_INVALID';
163
- if (reason === 'SELECTION_DIGEST_INVALID')
164
- return 'SELECTION_DIGEST_INVALID';
165
- if (reason === 'SELECTION_REFERENCE_INVALID')
166
- return 'SELECTION_REFERENCE_INVALID';
167
- if (reason === 'SELECTION_AMBIGUOUS')
168
- return 'SELECTION_AMBIGUOUS';
169
- if (reason === 'SELECTION_EXPIRED')
170
- return 'SELECTION_EXPIRED';
171
- return 'SELECTION_OUTPUT_INVALID';
172
- }
173
101
  function outerDeadlineReached(now, outerDeadlineAt, signal) {
174
102
  // Without an outer deadline this is an ordinary caller signal; keep the
175
103
  // previous SELECTION_EXPIRED / TRANSPORT_FAILED classification for it.
176
104
  return outerDeadlineAt !== undefined && (signal?.aborted === true || now() >= outerDeadlineAt);
177
105
  }
178
- function emptyDiagnostics(admissionDeadlineAt) {
106
+ /**
107
+ * The provider caps every model window at the host deadline, so the host
108
+ * deadline can ALSO be the admission/generation deadline. Two timers then end
109
+ * at the same instant: either may run first, and `Date.now()` can still read
110
+ * one millisecond short of the deadline, which made "which controller
111
+ * aborted" decide the diagnostic. The expired window's own deadline is the
112
+ * authority (P4): when it is the host window, the host window is the cause.
113
+ */
114
+ function deadlineIsHostWindow(outerDeadlineAt, expiredAt) {
115
+ return outerDeadlineAt !== undefined && expiredAt !== null && expiredAt >= outerDeadlineAt;
116
+ }
117
+ function emptyDiagnostics() {
179
118
  return {
180
119
  stage: 'idle',
181
- admissionDeadlineAt,
120
+ requestDeadlineAt: null,
121
+ requestSentAt: null,
182
122
  completionDeadlineAt: null,
183
123
  firstByteAt: null,
184
124
  generationEndedAt: null,
125
+ validatedAt: null,
185
126
  cancelledAt: null,
186
127
  httpStatus: null,
187
128
  finishReason: 'unknown',
129
+ modelObserved: null,
130
+ providerObserved: null,
188
131
  usage: null,
132
+ decision: null,
189
133
  failures: [],
190
134
  };
191
135
  }
192
- function parseFinishMetadata(raw) {
193
- const result = { finishReason: 'unknown', usage: null };
194
- const absorb = (parsed) => {
195
- if (!isRecord(parsed))
196
- return;
197
- const { choices } = parsed;
198
- if (Array.isArray(choices) && choices.length > 0) {
199
- const [first] = choices;
200
- if (isRecord(first)) {
201
- const finish = first.finish_reason;
202
- if (typeof finish === 'string' && finish)
203
- result.finishReason = finish;
204
- }
205
- }
206
- const { usage } = parsed;
207
- if (isRecord(usage)) {
208
- const input = usage.prompt_tokens ?? usage.input_tokens;
209
- const output = usage.completion_tokens ?? usage.output_tokens;
210
- result.usage = {
211
- inputTokens: typeof input === 'number' ? input : null,
212
- outputTokens: typeof output === 'number' ? output : null,
213
- };
214
- }
136
+ function projectUsage(value) {
137
+ if (!isRecord(value))
138
+ return null;
139
+ const input = value.input_tokens ?? value.prompt_tokens;
140
+ const output = value.output_tokens ?? value.completion_tokens;
141
+ return {
142
+ inputTokens: typeof input === 'number' && Number.isFinite(input) ? input : null,
143
+ outputTokens: typeof output === 'number' && Number.isFinite(output) ? output : null,
215
144
  };
216
- const trimmed = raw.trim();
217
- if (!trimmed)
218
- return result;
219
- if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
220
- try {
221
- absorb(JSON.parse(trimmed));
222
- return result;
223
- }
224
- catch {
225
- return result;
145
+ }
146
+ async function readBoundedBody(response, maxBytes, controller) {
147
+ if (!response.body) {
148
+ const text = await response.text();
149
+ if (Buffer.byteLength(text, 'utf8') > maxBytes) {
150
+ controller.abort(new Error('RESPONSE_TOO_LARGE'));
151
+ throw new Error('SELECTION_OUTPUT_INVALID');
226
152
  }
153
+ return text;
227
154
  }
228
- for (const line of trimmed.split(/\r?\n/u)) {
229
- const payload = line.startsWith('data:') ? line.slice(5).trim() : '';
230
- if (!payload || payload === '[DONE]')
231
- continue;
232
- try {
233
- absorb(JSON.parse(payload));
234
- }
235
- catch {
236
- // Ignore non-JSON keep-alives; diagnostics stay 'unknown' rather than guessing.
155
+ const reader = response.body.getReader();
156
+ const chunks = [];
157
+ let bytes = 0;
158
+ try {
159
+ for (;;) {
160
+ const part = await reader.read();
161
+ if (part.done)
162
+ break;
163
+ bytes += part.value.byteLength;
164
+ if (bytes > maxBytes) {
165
+ controller.abort(new Error('RESPONSE_TOO_LARGE'));
166
+ throw new Error('SELECTION_OUTPUT_INVALID');
167
+ }
168
+ chunks.push(Buffer.from(part.value));
237
169
  }
170
+ return Buffer.concat(chunks).toString('utf8');
171
+ }
172
+ finally {
173
+ reader.releaseLock();
238
174
  }
239
- return result;
240
175
  }
241
- export function createSingleModelSelector(options) {
176
+ /**
177
+ * One Decisions POST per turn. Every failure is classified at the transport
178
+ * edge; the caller never sees provider text, headers or credentials.
179
+ */
180
+ export function createDecisionSelector(options) {
242
181
  const now = options.now ?? Date.now;
243
- const Adapter = options.PiAiRuntimeAdapterImpl ?? PiAiRuntimeAdapter;
244
- const generationTimeoutMs = options.generationTimeoutMs ?? ADAPTIVE_SELECTION_LIMITS.generationTimeoutMs;
245
- const maxTokens = options.maxTokens ?? ADAPTIVE_SELECTION_LIMITS.maxOutputTokens;
246
- const diagnostics = emptyDiagnostics(options.admissionDeadlineAt);
182
+ const requestTimeoutMs = options.requestTimeoutMs ?? ADAPTIVE_SELECTION_LIMITS.requestTimeoutMs;
183
+ const diagnostics = emptyDiagnostics();
247
184
  let sends = 0;
248
185
  let status = 'not_sent';
249
186
  let failure = null;
250
- let finishMetadata = Promise.resolve({ finishReason: 'unknown', usage: null });
251
187
  const fail = (code) => {
252
188
  failure = code;
253
189
  status = 'failed';
@@ -261,150 +197,123 @@ export function createSingleModelSelector(options) {
261
197
  diagnostics.cancelledAt = now();
262
198
  fail('TURN_DEADLINE_EXCEEDED');
263
199
  }
264
- if (now() >= options.admissionDeadlineAt) {
265
- diagnostics.cancelledAt = now();
266
- fail('SELECTION_EXPIRED');
200
+ const apiKey = process.env[options.model.apiKeyEnv];
201
+ if (!apiKey)
202
+ fail('DECISION_CREDENTIAL_MISSING');
203
+ const body = JSON.stringify(input.body);
204
+ const sentAt = now();
205
+ if (outerDeadlineReached(() => sentAt, options.outerDeadlineAt, options.signal)) {
206
+ diagnostics.cancelledAt = sentAt;
207
+ fail('TURN_DEADLINE_EXCEEDED');
267
208
  }
268
- const remainingAdmission = Math.max(1, options.admissionDeadlineAt - now());
269
- const ttfbController = new AbortController();
270
- const ttfbTimer = setTimeout(() => ttfbController.abort(new Error('ADMISSION_DEADLINE')), remainingAdmission);
271
- ttfbTimer.unref?.();
272
- let firstByteAt = null;
273
- let completionDeadlineAt = null;
274
- const guardedFetch = async (resource, init) => {
275
- const url = resource instanceof Request ? resource.url : String(resource);
276
- const requestInit = init ?? {};
277
- if (options.model.url) {
278
- if (url !== options.model.url)
279
- fail('TRANSPORT_NOT_SENT');
280
- }
281
- else if (options.model.baseUrl) {
282
- if (!url.startsWith(options.model.baseUrl))
283
- fail('TRANSPORT_NOT_SENT');
284
- }
285
- else if (!url.startsWith('https://')) {
286
- fail('TRANSPORT_NOT_SENT');
287
- }
288
- let body;
289
- try {
290
- const parsed = typeof requestInit.body === 'string' ? JSON.parse(requestInit.body) : null;
291
- body = isRecord(parsed) ? parsed : null;
292
- }
293
- catch {
294
- body = null;
295
- }
296
- if (!body || body.model !== options.model.model)
297
- fail('TRANSPORT_NOT_SENT');
298
- if (body.max_tokens !== maxTokens)
299
- fail('TRANSPORT_NOT_SENT');
300
- const apiKey = process.env[options.model.apiKeyEnv];
301
- if (!apiKey)
302
- fail('TRANSPORT_NOT_SENT');
303
- sends += 1;
304
- status = 'sent';
305
- diagnostics.stage = 'admission';
306
- const combined = AbortSignal.any([
307
- ...(requestInit.signal ? [requestInit.signal] : []),
308
- ttfbController.signal,
309
- ...(options.signal ? [options.signal] : []),
310
- ]);
209
+ const deadlineAt = Math.min(sentAt + requestTimeoutMs, options.outerDeadlineAt ?? Infinity);
210
+ const controller = new AbortController();
211
+ const deadlineError = new Error('DECISION_DEADLINE');
212
+ const timer = setTimeout(() => controller.abort(deadlineError), Math.max(1, deadlineAt - sentAt));
213
+ timer.unref?.();
214
+ const signal = options.signal
215
+ ? AbortSignal.any([options.signal, controller.signal])
216
+ : controller.signal;
217
+ const expire = () => {
218
+ controller.abort(deadlineError);
219
+ diagnostics.cancelledAt = now();
220
+ return fail(outerDeadlineReached(now, options.outerDeadlineAt, options.signal)
221
+ || deadlineIsHostWindow(options.outerDeadlineAt, deadlineAt)
222
+ ? 'TURN_DEADLINE_EXCEEDED'
223
+ : 'SELECTION_EXPIRED');
224
+ };
225
+ const checkDeadline = () => {
226
+ if (outerDeadlineReached(now, options.outerDeadlineAt, options.signal)
227
+ || controller.signal.reason === deadlineError || now() >= deadlineAt)
228
+ expire();
229
+ };
230
+ sends += 1;
231
+ status = 'sent';
232
+ diagnostics.stage = 'admission';
233
+ diagnostics.requestSentAt = sentAt;
234
+ diagnostics.requestDeadlineAt = deadlineAt;
235
+ try {
311
236
  let response;
312
237
  try {
313
- response = await (options.fetchImpl ?? fetch)(url, { ...requestInit, signal: combined, redirect: 'error' });
238
+ response = await (options.fetchImpl ?? fetch)(options.model.endpoint, {
239
+ method: 'POST',
240
+ headers: {
241
+ 'Content-Type': 'application/json',
242
+ Authorization: `Bearer ${apiKey}`,
243
+ },
244
+ body,
245
+ signal,
246
+ redirect: 'error',
247
+ });
314
248
  }
315
- catch (error) {
316
- diagnostics.cancelledAt = now();
317
- diagnostics.stage = 'admission';
318
- fail(outerDeadlineReached(now, options.outerDeadlineAt, options.signal)
319
- ? 'TURN_DEADLINE_EXCEEDED'
320
- : ttfbController.signal.aborted ? 'SELECTION_EXPIRED' : 'TRANSPORT_FAILED');
321
- throw error;
249
+ catch {
250
+ checkDeadline();
251
+ return fail('TRANSPORT_FAILED');
322
252
  }
323
- // First byte is here: stop the admission clock, start the completion window.
324
- firstByteAt = now();
325
- diagnostics.firstByteAt = firstByteAt;
253
+ diagnostics.firstByteAt = now();
326
254
  diagnostics.httpStatus = response.status;
327
- clearTimeout(ttfbTimer);
328
- if (outerDeadlineReached(now, options.outerDeadlineAt, options.signal)) {
329
- diagnostics.cancelledAt = firstByteAt;
330
- fail('TURN_DEADLINE_EXCEEDED');
255
+ checkDeadline();
256
+ if (!response.ok) {
257
+ controller.abort();
258
+ return fail('TRANSPORT_HTTP_ERROR');
331
259
  }
332
- if (firstByteAt >= options.admissionDeadlineAt) {
333
- diagnostics.cancelledAt = firstByteAt;
334
- fail('SELECTION_EXPIRED');
335
- }
336
- // Headers arriving is not completion: the generation window may never
337
- // extend past the host deadline.
338
- completionDeadlineAt = options.outerDeadlineAt === undefined
339
- ? firstByteAt + generationTimeoutMs
340
- : Math.min(firstByteAt + generationTimeoutMs, options.outerDeadlineAt);
341
- diagnostics.completionDeadlineAt = completionDeadlineAt;
342
260
  diagnostics.stage = 'generation';
261
+ diagnostics.completionDeadlineAt = deadlineAt;
262
+ let raw;
343
263
  try {
344
- const clone = response.clone();
345
- finishMetadata = clone
346
- .text()
347
- .then((raw) => parseFinishMetadata(raw))
348
- .catch(() => ({ finishReason: 'unknown', usage: null }));
264
+ raw = await readBoundedBody(response, ADAPTIVE_SELECTION_LIMITS.maxResponseBytes, controller);
349
265
  }
350
266
  catch {
351
- finishMetadata = Promise.resolve({ finishReason: 'unknown', usage: null });
267
+ checkDeadline();
268
+ return fail('SELECTION_OUTPUT_INVALID');
269
+ }
270
+ checkDeadline();
271
+ let parsed;
272
+ try {
273
+ parsed = JSON.parse(raw);
274
+ }
275
+ catch {
276
+ return fail('SELECTION_OUTPUT_INVALID');
352
277
  }
353
- return response;
354
- };
355
- try {
356
- const adapter = new Adapter({
357
- provider: options.model.provider,
358
- model: options.model.model,
359
- ...(options.model.baseUrl ? { baseUrl: options.model.baseUrl } : {}),
360
- apiKeyEnv: options.model.apiKeyEnv,
361
- maxRetries: 0,
362
- maxRepairAttempts: 0,
363
- outputPathStrategy: 'free_form_only',
364
- reasoning: 'low',
365
- timeoutMs: remainingAdmission + generationTimeoutMs,
366
- maxTokens,
367
- fetch: guardedFetch,
368
- eventEmitter: new StoreEventEmitter(),
369
- });
370
- const run = await adapter.startRun({
371
- agentSpec: { agentId: 'adaptive-principle-selector', schemaVersion: 'current' },
372
- inputPayload: input.payload,
373
- contextItems: [],
374
- timeoutMs: remainingAdmission + generationTimeoutMs,
375
- maxTokens,
376
- systemPrompt: ADAPTIVE_SELECTOR_SYSTEM,
377
- });
378
- const output = await adapter.fetchOutput(run.runId);
379
278
  const endedAt = now();
380
279
  diagnostics.generationEndedAt = endedAt;
381
- if (outerDeadlineReached(now, options.outerDeadlineAt, options.signal)) {
382
- diagnostics.cancelledAt = endedAt;
383
- fail('TURN_DEADLINE_EXCEEDED');
280
+ checkDeadline();
281
+ diagnostics.usage = projectUsage(isRecord(parsed) ? parsed.usage : undefined);
282
+ // Record what the endpoint actually claimed BEFORE validating it, so the
283
+ // acceptance report can state observed model/provider instead of
284
+ // inferring a route from the request.
285
+ if (isRecord(parsed)) {
286
+ diagnostics.modelObserved = typeof parsed.model === 'string' ? parsed.model : null;
287
+ diagnostics.providerObserved = typeof parsed.provider === 'string' ? parsed.provider : null;
384
288
  }
385
- if (!output)
386
- fail('SELECTION_OUTPUT_INVALID');
387
- if (completionDeadlineAt !== null && endedAt > completionDeadlineAt) {
388
- diagnostics.cancelledAt = endedAt;
389
- fail('SELECTION_EXPIRED');
390
- }
391
- const metadata = await finishMetadata;
392
- diagnostics.finishReason = metadata.finishReason;
393
- diagnostics.usage = metadata.usage;
394
289
  diagnostics.stage = 'validate';
395
- return output.payload;
396
- }
397
- catch (error) {
398
- // An abort can surface while the adapter reads the body (the fetch call
399
- // itself already resolved), so classify it here, at the transport edge.
400
- if (outerDeadlineReached(now, options.outerDeadlineAt, options.signal)) {
401
- diagnostics.cancelledAt = now();
402
- fail('TURN_DEADLINE_EXCEEDED');
403
- }
404
- throw error;
290
+ const validated = validateDecisionResponse(parsed, {
291
+ model: options.model.model,
292
+ questionIds: input.questionIds,
293
+ ...(options.model.provider !== undefined ? { provider: options.model.provider } : {}),
294
+ ...(options.model.allowedResponseModels !== undefined
295
+ ? { allowedResponseModels: options.model.allowedResponseModels }
296
+ : {}),
297
+ });
298
+ if (!validated.ok)
299
+ return fail(validated.reason);
300
+ // The envelope is measured to a VALIDATED table, not to the last byte:
301
+ // a table that only parses after the completion deadline is expired even
302
+ // though the body arrived, so the caller never applies a late decision.
303
+ diagnostics.validatedAt = now();
304
+ checkDeadline();
305
+ diagnostics.finishReason = 'decisions';
306
+ const outcome = adjudicateDecision(validated.scores, input.candidates);
307
+ diagnostics.decision = {
308
+ status: outcome.status,
309
+ ref: outcome.ref,
310
+ reason: outcome.reason,
311
+ scores: validated.scores,
312
+ };
313
+ return outcome;
405
314
  }
406
315
  finally {
407
- clearTimeout(ttfbTimer);
316
+ clearTimeout(timer);
408
317
  }
409
318
  };
410
319
  return {
@@ -413,45 +322,47 @@ export function createSingleModelSelector(options) {
413
322
  };
414
323
  }
415
324
  /**
416
- * Minimal host-facing selection step: read the current frozen candidates,
417
- * make at most one bounded model call, verify ref+digest, then independently
418
- * revalidate the chosen principle's content/revision/authorization.
325
+ * Minimal host-facing selection step: use the current frozen Native gap,
326
+ * make at most one bounded Decisions request, adjudicate locally, then
327
+ * independently revalidate the chosen principle's content/revision/authorization.
419
328
  */
420
329
  export async function runAdaptiveSelection(options) {
421
- const earlyDiagnostics = emptyDiagnostics(options.admissionDeadlineAt);
330
+ const earlyDiagnostics = emptyDiagnostics();
422
331
  const unavailable = (reason, stage) => {
423
332
  earlyDiagnostics.stage = stage;
424
333
  return { status: 'unavailable', target: null, reason, sends: 0, diagnostics: earlyDiagnostics };
425
334
  };
426
- const read = await readPromptActivationCandidates({
427
- workspaceDir: options.workspaceDir,
428
- includeAuthority: true,
429
- });
430
- if (read.aborted || read.warnings.length > 0) {
431
- return unavailable(`candidates_unavailable:${read.warnings[0] ?? 'aborted'}`, 'idle');
432
- }
433
335
  const built = buildBoundedSelectionInput({
434
336
  currentInput: options.currentPrompt,
435
- candidates: read.principles,
337
+ candidates: options.candidates,
436
338
  });
437
339
  if (!built.ok)
438
340
  return unavailable(built.reason, 'idle');
439
- const selector = createSingleModelSelector({
440
- admissionDeadlineAt: options.admissionDeadlineAt,
341
+ const request = buildDecisionRequest({
342
+ model: options.model.model,
343
+ ...(options.model.provider !== undefined ? { provider: options.model.provider } : {}),
344
+ currentInstruction: built.input.payload.currentInstruction,
345
+ priorMessages: built.input.payload.priorMessages,
346
+ candidates: built.input.payload.candidates,
347
+ maxPayloadChars: ADAPTIVE_SELECTION_LIMITS.maxPayloadChars,
348
+ });
349
+ if (!request.ok)
350
+ return unavailable(request.reason, 'idle');
351
+ const selector = createDecisionSelector({
441
352
  model: options.model,
442
- ...(options.generationTimeoutMs !== undefined ? { generationTimeoutMs: options.generationTimeoutMs } : {}),
443
- ...(options.maxTokens !== undefined ? { maxTokens: options.maxTokens } : {}),
353
+ ...(options.requestTimeoutMs !== undefined ? { requestTimeoutMs: options.requestTimeoutMs } : {}),
444
354
  ...(options.signal ? { signal: options.signal } : {}),
445
355
  ...(options.outerDeadlineAt !== undefined ? { outerDeadlineAt: options.outerDeadlineAt } : {}),
446
356
  ...(options.now ? { now: options.now } : {}),
447
357
  ...(options.fetchImpl ? { fetchImpl: options.fetchImpl } : {}),
448
- ...(options.PiAiRuntimeAdapterImpl
449
- ? { PiAiRuntimeAdapterImpl: options.PiAiRuntimeAdapterImpl }
450
- : {}),
451
358
  });
452
- let payload;
359
+ let decision;
453
360
  try {
454
- payload = await selector.select(built.input);
361
+ decision = await selector.select({
362
+ body: request.body,
363
+ questionIds: request.questionIds,
364
+ candidates: built.input.entries,
365
+ });
455
366
  }
456
367
  catch {
457
368
  const report = selector.report();
@@ -467,20 +378,26 @@ export async function runAdaptiveSelection(options) {
467
378
  const report = selector.report();
468
379
  const { diagnostics } = report;
469
380
  const { sends } = report;
470
- const validated = validateSelectionResult(payload, built.input.entries);
471
- if (!validated.ok) {
472
- diagnostics.stage = 'validate';
473
- diagnostics.failures.push(localFailureCode(validated.reason));
474
- return { status: 'none', target: null, reason: validated.reason, sends, diagnostics };
475
- }
476
- if (!validated.selected) {
381
+ if (decision.status !== 'selected') {
477
382
  diagnostics.stage = 'done';
478
- return { status: 'none', target: null, reason: validated.outcome, sends, diagnostics };
383
+ return {
384
+ status: 'none',
385
+ target: null,
386
+ reason: decision.status === 'uncertain' ? 'uncertain' : 'no_increment',
387
+ sends,
388
+ diagnostics,
389
+ };
390
+ }
391
+ const selected = built.input.entries.find((entry) => entry.ref === decision.ref);
392
+ if (!selected) {
393
+ diagnostics.stage = 'validate';
394
+ diagnostics.failures.push('SELECTION_OUTPUT_INVALID');
395
+ return { status: 'none', target: null, reason: 'SELECTION_OUTPUT_INVALID', sends, diagnostics };
479
396
  }
480
- const target = validated.selected.principle;
397
+ const target = selected.principle;
481
398
  diagnostics.stage = 'revalidate';
482
399
  const now = options.now ?? Date.now;
483
- const revalidationBudgetMs = options.generationTimeoutMs ?? ADAPTIVE_SELECTION_LIMITS.generationTimeoutMs;
400
+ const revalidationBudgetMs = options.requestTimeoutMs ?? ADAPTIVE_SELECTION_LIMITS.requestTimeoutMs;
484
401
  const signal = options.signal ?? AbortSignal.timeout(options.outerDeadlineAt === undefined
485
402
  ? revalidationBudgetMs
486
403
  : Math.max(1, Math.min(revalidationBudgetMs, options.outerDeadlineAt - now())));