@caupulican/pi-adaptative 0.86.17 → 0.90.2

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 (297) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +1 -1
  3. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts.map +1 -1
  4. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js +14 -15
  5. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js.map +1 -1
  6. package/dist/bundled-resources/extensions/tmux-agent-manager/index.ts +14 -16
  7. package/dist/bundled-resources/skills/worker-profile-writer/SKILL.md +4 -4
  8. package/dist/core/agent-session.d.ts +23 -33
  9. package/dist/core/agent-session.d.ts.map +1 -1
  10. package/dist/core/agent-session.js +81 -110
  11. package/dist/core/agent-session.js.map +1 -1
  12. package/dist/core/autonomy/contracts.d.ts +1 -1
  13. package/dist/core/autonomy/contracts.js.map +1 -1
  14. package/dist/core/autonomy/gates.d.ts.map +1 -1
  15. package/dist/core/autonomy/gates.js +16 -0
  16. package/dist/core/autonomy/gates.js.map +1 -1
  17. package/dist/core/autonomy/subagent-prompt.d.ts +2 -1
  18. package/dist/core/autonomy/subagent-prompt.d.ts.map +1 -1
  19. package/dist/core/autonomy/subagent-prompt.js +2 -18
  20. package/dist/core/autonomy/subagent-prompt.js.map +1 -1
  21. package/dist/core/background-tool-task-controller.js +5 -5
  22. package/dist/core/background-tool-task-controller.js.map +1 -1
  23. package/dist/core/compaction-controller.d.ts +22 -2
  24. package/dist/core/compaction-controller.d.ts.map +1 -1
  25. package/dist/core/compaction-controller.js +75 -39
  26. package/dist/core/compaction-controller.js.map +1 -1
  27. package/dist/core/context/brain-curator.d.ts +2 -3
  28. package/dist/core/context/brain-curator.d.ts.map +1 -1
  29. package/dist/core/context/brain-curator.js +3 -20
  30. package/dist/core/context/brain-curator.js.map +1 -1
  31. package/dist/core/context/context-composition.d.ts +2 -1
  32. package/dist/core/context/context-composition.d.ts.map +1 -1
  33. package/dist/core/context/context-composition.js +6 -1
  34. package/dist/core/context/context-composition.js.map +1 -1
  35. package/dist/core/context/memory-prompt-block.js +1 -1
  36. package/dist/core/context/memory-prompt-block.js.map +1 -1
  37. package/dist/core/context/tool-output-packer.js +1 -1
  38. package/dist/core/context/tool-output-packer.js.map +1 -1
  39. package/dist/core/context-gc.js +10 -10
  40. package/dist/core/context-gc.js.map +1 -1
  41. package/dist/core/context-pipeline.d.ts +4 -4
  42. package/dist/core/context-pipeline.js +4 -4
  43. package/dist/core/context-pipeline.js.map +1 -1
  44. package/dist/core/default-tool-surface.d.ts.map +1 -1
  45. package/dist/core/default-tool-surface.js +1 -2
  46. package/dist/core/default-tool-surface.js.map +1 -1
  47. package/dist/core/delegation/session-worker-claim.d.ts +2 -2
  48. package/dist/core/delegation/session-worker-claim.js +2 -2
  49. package/dist/core/delegation/session-worker-claim.js.map +1 -1
  50. package/dist/core/delegation/worker-agent-control-coordinator.js +1 -1
  51. package/dist/core/delegation/worker-agent-control-coordinator.js.map +1 -1
  52. package/dist/core/delegation/worker-resource-materializer.js +3 -3
  53. package/dist/core/delegation/worker-resource-materializer.js.map +1 -1
  54. package/dist/core/delegation/worker-runner.d.ts +2 -13
  55. package/dist/core/delegation/worker-runner.d.ts.map +1 -1
  56. package/dist/core/delegation/worker-runner.js +5 -67
  57. package/dist/core/delegation/worker-runner.js.map +1 -1
  58. package/dist/core/extensions/builtin.js +4 -4
  59. package/dist/core/extensions/builtin.js.map +1 -1
  60. package/dist/core/extensions/runner.d.ts +6 -2
  61. package/dist/core/extensions/runner.d.ts.map +1 -1
  62. package/dist/core/extensions/runner.js +21 -9
  63. package/dist/core/extensions/runner.js.map +1 -1
  64. package/dist/core/extensions/types.d.ts +9 -2
  65. package/dist/core/extensions/types.d.ts.map +1 -1
  66. package/dist/core/extensions/types.js.map +1 -1
  67. package/dist/core/foreground-terminal-handoff-controller.js +2 -2
  68. package/dist/core/foreground-terminal-handoff-controller.js.map +1 -1
  69. package/dist/core/goals/compact-goal-context.d.ts.map +1 -1
  70. package/dist/core/goals/compact-goal-context.js +13 -9
  71. package/dist/core/goals/compact-goal-context.js.map +1 -1
  72. package/dist/core/goals/goal-continuation-prompt.js +1 -1
  73. package/dist/core/goals/goal-continuation-prompt.js.map +1 -1
  74. package/dist/core/goals/goal-session-controller.d.ts +6 -0
  75. package/dist/core/goals/goal-session-controller.d.ts.map +1 -1
  76. package/dist/core/goals/goal-session-controller.js +16 -13
  77. package/dist/core/goals/goal-session-controller.js.map +1 -1
  78. package/dist/core/human-input-controller.js +1 -1
  79. package/dist/core/human-input-controller.js.map +1 -1
  80. package/dist/core/improvement-loop.js +13 -13
  81. package/dist/core/improvement-loop.js.map +1 -1
  82. package/dist/core/learning/reflection-engine.d.ts +2 -1
  83. package/dist/core/learning/reflection-engine.d.ts.map +1 -1
  84. package/dist/core/learning/reflection-engine.js +4 -24
  85. package/dist/core/learning/reflection-engine.js.map +1 -1
  86. package/dist/core/model-capability.d.ts.map +1 -1
  87. package/dist/core/model-capability.js +1 -1
  88. package/dist/core/model-capability.js.map +1 -1
  89. package/dist/core/model-router/route-judge.d.ts +2 -1
  90. package/dist/core/model-router/route-judge.d.ts.map +1 -1
  91. package/dist/core/model-router/route-judge.js +4 -12
  92. package/dist/core/model-router/route-judge.js.map +1 -1
  93. package/dist/core/models/perf-profile.d.ts +1 -1
  94. package/dist/core/models/perf-profile.d.ts.map +1 -1
  95. package/dist/core/models/perf-profile.js +2 -8
  96. package/dist/core/models/perf-profile.js.map +1 -1
  97. package/dist/core/orchestration/lane-tool-manifests.d.ts +1 -1
  98. package/dist/core/orchestration/lane-tool-manifests.d.ts.map +1 -1
  99. package/dist/core/orchestration/lane-tool-manifests.js +1 -6
  100. package/dist/core/orchestration/lane-tool-manifests.js.map +1 -1
  101. package/dist/core/process-matrix/resume-launcher.js +3 -3
  102. package/dist/core/process-matrix/resume-launcher.js.map +1 -1
  103. package/dist/core/process-matrix/runtime.d.ts +2 -0
  104. package/dist/core/process-matrix/runtime.d.ts.map +1 -1
  105. package/dist/core/process-matrix/runtime.js +23 -19
  106. package/dist/core/process-matrix/runtime.js.map +1 -1
  107. package/dist/core/provider-prompt-contracts.d.ts +34 -0
  108. package/dist/core/provider-prompt-contracts.d.ts.map +1 -0
  109. package/dist/core/provider-prompt-contracts.js +133 -0
  110. package/dist/core/provider-prompt-contracts.js.map +1 -0
  111. package/dist/core/provider-request-context-controller.d.ts +40 -0
  112. package/dist/core/provider-request-context-controller.d.ts.map +1 -0
  113. package/dist/core/provider-request-context-controller.js +68 -0
  114. package/dist/core/provider-request-context-controller.js.map +1 -0
  115. package/dist/core/provider-request-runtime-controller.d.ts +22 -0
  116. package/dist/core/provider-request-runtime-controller.d.ts.map +1 -0
  117. package/dist/core/provider-request-runtime-controller.js +87 -0
  118. package/dist/core/provider-request-runtime-controller.js.map +1 -0
  119. package/dist/core/provider-tool-text.d.ts +7 -0
  120. package/dist/core/provider-tool-text.d.ts.map +1 -0
  121. package/dist/core/provider-tool-text.js +42 -0
  122. package/dist/core/provider-tool-text.js.map +1 -0
  123. package/dist/core/research/model-fitness.d.ts +2 -5
  124. package/dist/core/research/model-fitness.d.ts.map +1 -1
  125. package/dist/core/research/model-fitness.js +2 -20
  126. package/dist/core/research/model-fitness.js.map +1 -1
  127. package/dist/core/research/research-runner.d.ts +2 -1
  128. package/dist/core/research/research-runner.d.ts.map +1 -1
  129. package/dist/core/research/research-runner.js +6 -21
  130. package/dist/core/research/research-runner.js.map +1 -1
  131. package/dist/core/risk-classifier.d.ts.map +1 -1
  132. package/dist/core/risk-classifier.js +9 -1
  133. package/dist/core/risk-classifier.js.map +1 -1
  134. package/dist/core/runtime-builder.d.ts +3 -0
  135. package/dist/core/runtime-builder.d.ts.map +1 -1
  136. package/dist/core/runtime-builder.js +20 -25
  137. package/dist/core/runtime-builder.js.map +1 -1
  138. package/dist/core/scout-controller.d.ts +2 -1
  139. package/dist/core/scout-controller.d.ts.map +1 -1
  140. package/dist/core/scout-controller.js +2 -16
  141. package/dist/core/scout-controller.js.map +1 -1
  142. package/dist/core/sdk.d.ts +1 -1
  143. package/dist/core/sdk.js.map +1 -1
  144. package/dist/core/secrets/credential-exposure-guard.js +6 -6
  145. package/dist/core/secrets/credential-exposure-guard.js.map +1 -1
  146. package/dist/core/secrets/credential-manager.d.ts +11 -1
  147. package/dist/core/secrets/credential-manager.d.ts.map +1 -1
  148. package/dist/core/secrets/credential-manager.js +28 -7
  149. package/dist/core/secrets/credential-manager.js.map +1 -1
  150. package/dist/core/secrets/credential-migration-source.d.ts +20 -0
  151. package/dist/core/secrets/credential-migration-source.d.ts.map +1 -0
  152. package/dist/core/secrets/credential-migration-source.js +113 -0
  153. package/dist/core/secrets/credential-migration-source.js.map +1 -0
  154. package/dist/core/secrets/credential-session-connection.d.ts +9 -0
  155. package/dist/core/secrets/credential-session-connection.d.ts.map +1 -0
  156. package/dist/core/secrets/credential-session-connection.js +39 -0
  157. package/dist/core/secrets/credential-session-connection.js.map +1 -0
  158. package/dist/core/security/untrusted-boundary.d.ts +2 -2
  159. package/dist/core/security/untrusted-boundary.d.ts.map +1 -1
  160. package/dist/core/security/untrusted-boundary.js +3 -10
  161. package/dist/core/security/untrusted-boundary.js.map +1 -1
  162. package/dist/core/session-role.d.ts.map +1 -1
  163. package/dist/core/session-role.js +1 -2
  164. package/dist/core/session-role.js.map +1 -1
  165. package/dist/core/skill-vault.d.ts +98 -0
  166. package/dist/core/skill-vault.d.ts.map +1 -0
  167. package/dist/core/skill-vault.js +270 -0
  168. package/dist/core/skill-vault.js.map +1 -0
  169. package/dist/core/skills.d.ts +10 -9
  170. package/dist/core/skills.d.ts.map +1 -1
  171. package/dist/core/skills.js +42 -50
  172. package/dist/core/skills.js.map +1 -1
  173. package/dist/core/system-prompt-builder.d.ts +1 -1
  174. package/dist/core/system-prompt-builder.d.ts.map +1 -1
  175. package/dist/core/system-prompt-builder.js +20 -60
  176. package/dist/core/system-prompt-builder.js.map +1 -1
  177. package/dist/core/system-prompt.d.ts +4 -4
  178. package/dist/core/system-prompt.d.ts.map +1 -1
  179. package/dist/core/system-prompt.js +87 -121
  180. package/dist/core/system-prompt.js.map +1 -1
  181. package/dist/core/tasks/task-state.d.ts.map +1 -1
  182. package/dist/core/tasks/task-state.js +6 -7
  183. package/dist/core/tasks/task-state.js.map +1 -1
  184. package/dist/core/tool-capability-policy.d.ts.map +1 -1
  185. package/dist/core/tool-capability-policy.js +2 -1
  186. package/dist/core/tool-capability-policy.js.map +1 -1
  187. package/dist/core/tool-protocol-controller.d.ts.map +1 -1
  188. package/dist/core/tool-protocol-controller.js +4 -7
  189. package/dist/core/tool-protocol-controller.js.map +1 -1
  190. package/dist/core/tool-selection/promotion.d.ts.map +1 -1
  191. package/dist/core/tool-selection/promotion.js +2 -6
  192. package/dist/core/tool-selection/promotion.js.map +1 -1
  193. package/dist/core/toolkit/reflex-interpreter.d.ts +2 -1
  194. package/dist/core/toolkit/reflex-interpreter.d.ts.map +1 -1
  195. package/dist/core/toolkit/reflex-interpreter.js +2 -14
  196. package/dist/core/toolkit/reflex-interpreter.js.map +1 -1
  197. package/dist/core/tools/ask-question.js +6 -6
  198. package/dist/core/tools/ask-question.js.map +1 -1
  199. package/dist/core/tools/bash.d.ts.map +1 -1
  200. package/dist/core/tools/bash.js +8 -7
  201. package/dist/core/tools/bash.js.map +1 -1
  202. package/dist/core/tools/delegate-status.d.ts +17 -13
  203. package/dist/core/tools/delegate-status.d.ts.map +1 -1
  204. package/dist/core/tools/delegate-status.js +111 -226
  205. package/dist/core/tools/delegate-status.js.map +1 -1
  206. package/dist/core/tools/delegate.d.ts +29 -2
  207. package/dist/core/tools/delegate.d.ts.map +1 -1
  208. package/dist/core/tools/delegate.js +149 -48
  209. package/dist/core/tools/delegate.js.map +1 -1
  210. package/dist/core/tools/edit.js +3 -3
  211. package/dist/core/tools/edit.js.map +1 -1
  212. package/dist/core/tools/extensionify-runtime.js +4 -4
  213. package/dist/core/tools/extensionify-runtime.js.map +1 -1
  214. package/dist/core/tools/find.d.ts.map +1 -1
  215. package/dist/core/tools/find.js +2 -4
  216. package/dist/core/tools/find.js.map +1 -1
  217. package/dist/core/tools/goal.js +3 -3
  218. package/dist/core/tools/goal.js.map +1 -1
  219. package/dist/core/tools/grep.js +2 -2
  220. package/dist/core/tools/grep.js.map +1 -1
  221. package/dist/core/tools/index.d.ts +1 -1
  222. package/dist/core/tools/index.d.ts.map +1 -1
  223. package/dist/core/tools/index.js +1 -1
  224. package/dist/core/tools/index.js.map +1 -1
  225. package/dist/core/tools/model-fitness.js +4 -4
  226. package/dist/core/tools/model-fitness.js.map +1 -1
  227. package/dist/core/tools/profile-writer.d.ts +30 -16
  228. package/dist/core/tools/profile-writer.d.ts.map +1 -1
  229. package/dist/core/tools/profile-writer.js +98 -59
  230. package/dist/core/tools/profile-writer.js.map +1 -1
  231. package/dist/core/tools/python.js +6 -6
  232. package/dist/core/tools/python.js.map +1 -1
  233. package/dist/core/tools/run-process.js +4 -4
  234. package/dist/core/tools/run-process.js.map +1 -1
  235. package/dist/core/tools/run-toolkit-script.js +4 -4
  236. package/dist/core/tools/run-toolkit-script.js.map +1 -1
  237. package/dist/core/tools/secret-store.d.ts +32 -3
  238. package/dist/core/tools/secret-store.d.ts.map +1 -1
  239. package/dist/core/tools/secret-store.js +141 -34
  240. package/dist/core/tools/secret-store.js.map +1 -1
  241. package/dist/core/tools/skill.d.ts +29 -0
  242. package/dist/core/tools/skill.d.ts.map +1 -0
  243. package/dist/core/tools/skill.js +79 -0
  244. package/dist/core/tools/skill.js.map +1 -0
  245. package/dist/core/tools/task-steps.js +4 -4
  246. package/dist/core/tools/task-steps.js.map +1 -1
  247. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
  248. package/dist/core/tools/tool-definition-wrapper.js +2 -0
  249. package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
  250. package/dist/core/tools/tool-task.d.ts.map +1 -1
  251. package/dist/core/tools/tool-task.js +4 -0
  252. package/dist/core/tools/tool-task.js.map +1 -1
  253. package/dist/core/tools/worktree-sync.js +6 -6
  254. package/dist/core/tools/worktree-sync.js.map +1 -1
  255. package/dist/core/tools/write.js +3 -3
  256. package/dist/core/tools/write.js.map +1 -1
  257. package/dist/index.d.ts +5 -2
  258. package/dist/index.d.ts.map +1 -1
  259. package/dist/index.js +4 -1
  260. package/dist/index.js.map +1 -1
  261. package/dist/modes/interactive/interactive-event-controller.js +1 -1
  262. package/dist/modes/interactive/interactive-event-controller.js.map +1 -1
  263. package/dist/modes/interactive/interactive-mode.js +1 -1
  264. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  265. package/dist/modes/interactive/report-commands.js +1 -1
  266. package/dist/modes/interactive/report-commands.js.map +1 -1
  267. package/dist/modes/interactive/secret-menu-controller.d.ts.map +1 -1
  268. package/dist/modes/interactive/secret-menu-controller.js +2 -18
  269. package/dist/modes/interactive/secret-menu-controller.js.map +1 -1
  270. package/dist/modes/interactive/session-flow-commands.js +1 -1
  271. package/dist/modes/interactive/session-flow-commands.js.map +1 -1
  272. package/docs/compaction.md +45 -25
  273. package/docs/extensions.md +23 -7
  274. package/docs/settings.md +3 -3
  275. package/docs/skills.md +14 -10
  276. package/docs/task-steps.md +2 -2
  277. package/docs/tmux-agent-manager.md +1 -1
  278. package/docs/tool-repair.md +18 -1
  279. package/docs/usage.md +4 -2
  280. package/docs/worker-profiles.md +3 -3
  281. package/docs/worktree-sync.md +2 -2
  282. package/examples/extensions/custom-compaction.ts +5 -17
  283. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  284. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  285. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  286. package/examples/extensions/sandbox/package-lock.json +2 -2
  287. package/examples/extensions/sandbox/package.json +1 -1
  288. package/examples/extensions/summarize.ts +3 -5
  289. package/examples/extensions/with-deps/package-lock.json +2 -2
  290. package/examples/extensions/with-deps/package.json +1 -1
  291. package/examples/sdk/04-skills.ts +1 -1
  292. package/npm-shrinkwrap.json +12 -12
  293. package/package.json +4 -4
  294. package/dist/core/util/json-size.d.ts +0 -3
  295. package/dist/core/util/json-size.d.ts.map +0 -1
  296. package/dist/core/util/json-size.js +0 -95
  297. package/dist/core/util/json-size.js.map +0 -1
@@ -132,7 +132,7 @@ export interface WorkerClaim {
132
132
  * distinct from `false`, which means the gate explicitly cleared it. */
133
133
  parentReviewRequired?: boolean;
134
134
  /** ISO 8601 timestamp set once the parent explicitly acknowledges an unreviewed mutation via
135
- * delegate_status's "review" action. Presence means reviewed; absence keeps the notice sticky.
135
+ * delegate's "review" action. Presence means reviewed; absence keeps the notice sticky.
136
136
  * The ack is durable — re-derived from the latest persisted snapshot, not session-local state. */
137
137
  parentReviewedAt?: string;
138
138
  /** Typed semantic verdict emitted only by a verifier-profile worker. */
@@ -1 +1 @@
1
- {"version":3,"file":"contracts.js","sourceRoot":"","sources":["../../../src/core/autonomy/contracts.ts"],"names":[],"mappings":"","sourcesContent":["import type { HarnessCapability } from \"../capability-contract.ts\";\n\nexport type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };\nexport interface JsonObject {\n\t[key: string]: JsonValue;\n}\n\nexport type ModelTier = \"cheap\" | \"medium\" | \"expensive\" | \"learning\";\n\nexport type RouteRisk = \"read-only\" | \"scoped-write\" | \"high-impact\" | \"approval-required\";\n\nexport type OperationRisk = \"read-only\" | \"scoped-write\" | \"high-impact\" | \"approval-required\";\n\nexport interface RiskAssessmentInput {\n\toperation: string;\n\ttoolName?: string;\n\tcommand?: string;\n\tpaths?: readonly string[];\n\tcapabilities?: readonly HarnessCapability[];\n}\n\nexport interface RiskAssessment {\n\trisk: OperationRisk;\n\treasonCode: string;\n\treasons: readonly string[];\n\trequiresApproval: boolean;\n}\n\nexport type PathScopeDecisionKind = \"inside\" | \"outside\" | \"denied\" | \"missing\";\n\nexport interface PathScope {\n\troot: string;\n\tallowedPaths?: readonly string[];\n\tdeniedPaths?: readonly string[];\n\tfollowSymlinks?: boolean;\n}\n\nexport interface PathScopeDecision {\n\tkind: PathScopeDecisionKind;\n\tpath: string;\n\tresolvedPath?: string;\n\tmatchedRule?: string;\n\treasonCode: string;\n}\n\nexport interface RouteDecision {\n\ttier: ModelTier;\n\tmodel?: string;\n\trisk: RouteRisk;\n\tconfidence: number;\n\treasonCode: string;\n\treasons: readonly string[];\n\tfallbackFrom?: ModelTier;\n\tcreatedAt?: string;\n}\n\nexport interface CapabilityEnvelope {\n\tid: string;\n\tprofileId?: string;\n\tcapabilities: readonly HarnessCapability[];\n\tallowedTools?: readonly string[];\n\tdeniedTools?: readonly string[];\n\tallowedPaths?: readonly string[];\n\tdeniedPaths?: readonly string[];\n\tmaxEstimatedUsd?: number;\n\tcreatedAt?: string;\n}\n\nexport type GateOutcomeKind = \"allow\" | \"downgrade\" | \"escalate\" | \"ask-user\" | \"block\";\n\nexport interface GateOutcome {\n\toutcome: GateOutcomeKind;\n\tgate: string;\n\treasonCode: string;\n\tmessage?: string;\n\treversible?: boolean;\n\tdetails?: JsonObject;\n}\n\nexport interface ApprovalRequest {\n\tid: string;\n\toperation: string;\n\ttarget: string;\n\treversible: boolean;\n\tcapabilities: readonly HarnessCapability[];\n\treasonCode: string;\n\tcreatedAt?: string;\n}\n\nexport type EvidenceSourceKind = \"workspace\" | \"transcript\" | \"automata\" | \"web\" | \"user\" | \"tool\";\n\nexport interface EvidenceRef {\n\tid: string;\n\tkind: EvidenceSourceKind;\n\ttitle?: string;\n\turi?: string;\n\ttrusted: boolean;\n\texcerpt?: string;\n\tmetadata?: JsonObject;\n}\n\nexport interface Finding {\n\tid: string;\n\tsummary: string;\n\tevidenceIds: readonly string[];\n\tconfidence?: number;\n}\n\nexport interface EvidenceBundle {\n\tquery: string;\n\tsources: readonly EvidenceRef[];\n\tfindings: readonly Finding[];\n\tcreatedAt?: string;\n}\n\nexport interface WorkerRequest {\n\tid: string;\n\tinstructions: string;\n\troute: RouteDecision;\n\tenvelope: CapabilityEnvelope;\n\tevidence?: EvidenceBundle;\n\tmaxEstimatedUsd?: number;\n\tcreatedAt?: string;\n}\n\nexport type WorkerClaimStatus = \"completed\" | \"blocked\" | \"failed\" | \"cancelled\";\n\nexport type WorkerClaimOutputFormat = \"structured\" | \"plain_text\";\n\nexport interface WorkerClaimVerificationDecision {\n\tsubjectTaskId: string;\n\tverdict: \"accepted\" | \"rejected\";\n\treasonCodes: readonly string[];\n}\n\n/** Untrusted worker-authored report. Only host adjudication can turn this into a durable result. */\nexport interface WorkerClaim {\n\trequestId: string;\n\t/** Host-stamped durable attempt identity for replay-safe claim persistence. */\n\tterminalAttemptId?: string;\n\tstatus: WorkerClaimStatus;\n\tsummary: string;\n\toutputFormat?: WorkerClaimOutputFormat;\n\tevidence?: EvidenceBundle;\n\tchangedFiles: readonly string[];\n\tblockers?: readonly string[];\n\tusageReportId?: string;\n\tcreatedAt?: string;\n\t/** Stamped at persistence time when validateWorkerClaim's gate flagged this claim\n\t * \"ask-user\"/\"parent_review_required\" (mutated files or blockers on an otherwise-completed run).\n\t * Undefined when not computable because an externally managed lane had no WorkerRequest —\n\t * distinct from `false`, which means the gate explicitly cleared it. */\n\tparentReviewRequired?: boolean;\n\t/** ISO 8601 timestamp set once the parent explicitly acknowledges an unreviewed mutation via\n\t * delegate_status's \"review\" action. Presence means reviewed; absence keeps the notice sticky.\n\t * The ack is durable — re-derived from the latest persisted snapshot, not session-local state. */\n\tparentReviewedAt?: string;\n\t/** Typed semantic verdict emitted only by a verifier-profile worker. */\n\tverification?: WorkerClaimVerificationDecision;\n}\n\nexport type LearningDecisionKind = \"no-op\" | \"proposal\" | \"apply\";\n\nexport interface LearningDecision {\n\tkind: LearningDecisionKind;\n\treasonCode: string;\n\tconfidence: number;\n\tsummary: string;\n\trequiresApproval: boolean;\n\tcreatedAt?: string;\n}\n"]}
1
+ {"version":3,"file":"contracts.js","sourceRoot":"","sources":["../../../src/core/autonomy/contracts.ts"],"names":[],"mappings":"","sourcesContent":["import type { HarnessCapability } from \"../capability-contract.ts\";\n\nexport type JsonPrimitive = string | number | boolean | null;\nexport type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };\nexport interface JsonObject {\n\t[key: string]: JsonValue;\n}\n\nexport type ModelTier = \"cheap\" | \"medium\" | \"expensive\" | \"learning\";\n\nexport type RouteRisk = \"read-only\" | \"scoped-write\" | \"high-impact\" | \"approval-required\";\n\nexport type OperationRisk = \"read-only\" | \"scoped-write\" | \"high-impact\" | \"approval-required\";\n\nexport interface RiskAssessmentInput {\n\toperation: string;\n\ttoolName?: string;\n\tcommand?: string;\n\tpaths?: readonly string[];\n\tcapabilities?: readonly HarnessCapability[];\n}\n\nexport interface RiskAssessment {\n\trisk: OperationRisk;\n\treasonCode: string;\n\treasons: readonly string[];\n\trequiresApproval: boolean;\n}\n\nexport type PathScopeDecisionKind = \"inside\" | \"outside\" | \"denied\" | \"missing\";\n\nexport interface PathScope {\n\troot: string;\n\tallowedPaths?: readonly string[];\n\tdeniedPaths?: readonly string[];\n\tfollowSymlinks?: boolean;\n}\n\nexport interface PathScopeDecision {\n\tkind: PathScopeDecisionKind;\n\tpath: string;\n\tresolvedPath?: string;\n\tmatchedRule?: string;\n\treasonCode: string;\n}\n\nexport interface RouteDecision {\n\ttier: ModelTier;\n\tmodel?: string;\n\trisk: RouteRisk;\n\tconfidence: number;\n\treasonCode: string;\n\treasons: readonly string[];\n\tfallbackFrom?: ModelTier;\n\tcreatedAt?: string;\n}\n\nexport interface CapabilityEnvelope {\n\tid: string;\n\tprofileId?: string;\n\tcapabilities: readonly HarnessCapability[];\n\tallowedTools?: readonly string[];\n\tdeniedTools?: readonly string[];\n\tallowedPaths?: readonly string[];\n\tdeniedPaths?: readonly string[];\n\tmaxEstimatedUsd?: number;\n\tcreatedAt?: string;\n}\n\nexport type GateOutcomeKind = \"allow\" | \"downgrade\" | \"escalate\" | \"ask-user\" | \"block\";\n\nexport interface GateOutcome {\n\toutcome: GateOutcomeKind;\n\tgate: string;\n\treasonCode: string;\n\tmessage?: string;\n\treversible?: boolean;\n\tdetails?: JsonObject;\n}\n\nexport interface ApprovalRequest {\n\tid: string;\n\toperation: string;\n\ttarget: string;\n\treversible: boolean;\n\tcapabilities: readonly HarnessCapability[];\n\treasonCode: string;\n\tcreatedAt?: string;\n}\n\nexport type EvidenceSourceKind = \"workspace\" | \"transcript\" | \"automata\" | \"web\" | \"user\" | \"tool\";\n\nexport interface EvidenceRef {\n\tid: string;\n\tkind: EvidenceSourceKind;\n\ttitle?: string;\n\turi?: string;\n\ttrusted: boolean;\n\texcerpt?: string;\n\tmetadata?: JsonObject;\n}\n\nexport interface Finding {\n\tid: string;\n\tsummary: string;\n\tevidenceIds: readonly string[];\n\tconfidence?: number;\n}\n\nexport interface EvidenceBundle {\n\tquery: string;\n\tsources: readonly EvidenceRef[];\n\tfindings: readonly Finding[];\n\tcreatedAt?: string;\n}\n\nexport interface WorkerRequest {\n\tid: string;\n\tinstructions: string;\n\troute: RouteDecision;\n\tenvelope: CapabilityEnvelope;\n\tevidence?: EvidenceBundle;\n\tmaxEstimatedUsd?: number;\n\tcreatedAt?: string;\n}\n\nexport type WorkerClaimStatus = \"completed\" | \"blocked\" | \"failed\" | \"cancelled\";\n\nexport type WorkerClaimOutputFormat = \"structured\" | \"plain_text\";\n\nexport interface WorkerClaimVerificationDecision {\n\tsubjectTaskId: string;\n\tverdict: \"accepted\" | \"rejected\";\n\treasonCodes: readonly string[];\n}\n\n/** Untrusted worker-authored report. Only host adjudication can turn this into a durable result. */\nexport interface WorkerClaim {\n\trequestId: string;\n\t/** Host-stamped durable attempt identity for replay-safe claim persistence. */\n\tterminalAttemptId?: string;\n\tstatus: WorkerClaimStatus;\n\tsummary: string;\n\toutputFormat?: WorkerClaimOutputFormat;\n\tevidence?: EvidenceBundle;\n\tchangedFiles: readonly string[];\n\tblockers?: readonly string[];\n\tusageReportId?: string;\n\tcreatedAt?: string;\n\t/** Stamped at persistence time when validateWorkerClaim's gate flagged this claim\n\t * \"ask-user\"/\"parent_review_required\" (mutated files or blockers on an otherwise-completed run).\n\t * Undefined when not computable because an externally managed lane had no WorkerRequest —\n\t * distinct from `false`, which means the gate explicitly cleared it. */\n\tparentReviewRequired?: boolean;\n\t/** ISO 8601 timestamp set once the parent explicitly acknowledges an unreviewed mutation via\n\t * delegate's \"review\" action. Presence means reviewed; absence keeps the notice sticky.\n\t * The ack is durable — re-derived from the latest persisted snapshot, not session-local state. */\n\tparentReviewedAt?: string;\n\t/** Typed semantic verdict emitted only by a verifier-profile worker. */\n\tverification?: WorkerClaimVerificationDecision;\n}\n\nexport type LearningDecisionKind = \"no-op\" | \"proposal\" | \"apply\";\n\nexport interface LearningDecision {\n\tkind: LearningDecisionKind;\n\treasonCode: string;\n\tconfidence: number;\n\tsummary: string;\n\trequiresApproval: boolean;\n\tcreatedAt?: string;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"gates.d.ts","sourceRoot":"","sources":["../../../src/core/autonomy/gates.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,kBAAkB,EAAE,WAAW,EAAmB,MAAM,gBAAgB,CAAC;AAmBvF,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,SAAS,WAAW,EAAE,GAAG,WAAW,CA+BjF;AAED,wBAAgB,mBAAmB,CAAC,IAAI,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,OAAO,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,GAAG,WAAW,CAWhH;AAED,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,MAAM,EAAE,CAmB/E;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE;IACvC,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,CAAC,EAAE,kBAAkB,CAAC;CAC9B,GAAG,WAAW,CAqJd"}
1
+ {"version":3,"file":"gates.d.ts","sourceRoot":"","sources":["../../../src/core/autonomy/gates.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,kBAAkB,EAAE,WAAW,EAAmB,MAAM,gBAAgB,CAAC;AAmBvF,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,SAAS,WAAW,EAAE,GAAG,WAAW,CA+BjF;AAED,wBAAgB,mBAAmB,CAAC,IAAI,EAAE;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,OAAO,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,GAAG,WAAW,CAWhH;AAED,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,MAAM,EAAE,CA+B/E;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE;IACvC,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,CAAC,EAAE,OAAO,CAAC;IACf,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,CAAC,EAAE,kBAAkB,CAAC;CAC9B,GAAG,WAAW,CAwJd"}
@@ -72,6 +72,17 @@ export function extractCandidatePaths(toolName, args) {
72
72
  paths.push(obj.path.trim());
73
73
  }
74
74
  }
75
+ else if (toolName === "secret_store" && obj.action === "migrate" && Array.isArray(obj.sources)) {
76
+ for (const source of obj.sources) {
77
+ if (source &&
78
+ typeof source === "object" &&
79
+ "path" in source &&
80
+ typeof source.path === "string" &&
81
+ source.path.trim()) {
82
+ paths.push(source.path.trim());
83
+ }
84
+ }
85
+ }
75
86
  return paths;
76
87
  }
77
88
  export function evaluateToolGate(input) {
@@ -177,6 +188,11 @@ export function evaluateToolGate(input) {
177
188
  command = `python ${argsObj.scriptPath}`;
178
189
  }
179
190
  }
191
+ else if (input.toolName === "secret_store") {
192
+ const argsObj = input.args;
193
+ if (argsObj && typeof argsObj.action === "string")
194
+ command = argsObj.action;
195
+ }
180
196
  const riskResult = assessOperationRisk({
181
197
  operation: `Tool ${input.toolName}`,
182
198
  toolName: input.toolName,
@@ -1 +1 @@
1
- {"version":3,"file":"gates.js","sourceRoot":"","sources":["../../../src/core/autonomy/gates.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EACN,0BAA0B,EAC1B,4BAA4B,EAC5B,2BAA2B,GAC3B,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAE3D,SAAS,iBAAiB,CAAC,KAAc;IACxC,OAAO,CACN,KAAK,KAAK,OAAO,IAAI,KAAK,KAAK,WAAW,IAAI,KAAK,KAAK,UAAU,IAAI,KAAK,KAAK,UAAU,IAAI,KAAK,KAAK,OAAO,CAC/G,CAAC;AACH,CAAC;AAED,SAAS,aAAa,CAAC,IAAa;IACnC,IAAI,IAAI,KAAK,OAAO;QAAE,OAAO,CAAC,CAAC;IAC/B,IAAI,IAAI,KAAK,WAAW;QAAE,OAAO,CAAC,CAAC;IACnC,IAAI,IAAI,KAAK,UAAU;QAAE,OAAO,CAAC,CAAC;IAClC,IAAI,IAAI,KAAK,UAAU;QAAE,OAAO,CAAC,CAAC;IAClC,IAAI,IAAI,KAAK,OAAO;QAAE,OAAO,CAAC,CAAC;IAC/B,OAAO,CAAC,CAAC,CAAC,sEAAsE;AACjF,CAAC;AAED,MAAM,UAAU,mBAAmB,CAAC,QAAgC;IACnE,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC3B,OAAO;YACN,OAAO,EAAE,UAAU;YACnB,IAAI,EAAE,eAAe;YACrB,UAAU,EAAE,kBAAkB;YAC9B,OAAO,EAAE,6BAA6B;SACtC,CAAC;IACH,CAAC;IAED,IAAI,MAAM,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC;IACzB,IAAI,aAAa,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EAAE,qBAAqB;QACjC,OAAO,EAAE,mDAAmD;KAC5D,CAAC;AACH,CAAC","sourcesContent":["import path from \"node:path\";\nimport {\n\thasCapabilityPolicyForTool,\n\thasRequiredCapabilityForTool,\n\trequiredCapabilitiesForTool,\n} from \"./approval-gate.ts\";\nimport type { CapabilityEnvelope, GateOutcome, GateOutcomeKind } from \"./contracts.ts\";\nimport { checkPathScope } from \"./path-scope.ts\";\nimport { assessOperationRisk } from \"./risk-assessment.ts\";\n\nfunction isGateOutcomeKind(value: unknown): value is GateOutcomeKind {\n\treturn (\n\t\tvalue === \"allow\" || value === \"downgrade\" || value === \"escalate\" || value === \"ask-user\" || value === \"block\"\n\t);\n}\n\nfunction getPrecedence(kind: unknown): number {\n\tif (kind === \"allow\") return 0;\n\tif (kind === \"downgrade\") return 1;\n\tif (kind === \"escalate\") return 2;\n\tif (kind === \"ask-user\") return 3;\n\tif (kind === \"block\") return 4;\n\treturn 4; // Malformed/unknown outcome kind defaults to most restrictive (block)\n}\n\nexport function combineGateOutcomes(outcomes: readonly GateOutcome[]): GateOutcome {\n\tif (outcomes.length === 0) {\n\t\treturn {\n\t\t\toutcome: \"ask-user\",\n\t\t\tgate: \"gate-combiner\",\n\t\t\treasonCode: \"no_gate_outcomes\",\n\t\t\tmessage: \"No gate outcomes to combine\",\n\t\t};\n\t}\n\n\tlet winner = outcomes[0];\n\tlet maxPrecedence = getPrecedence(winner.outcome);\n\n\tfor (let i = 1; i < outcomes.length; i++) {\n\t\tconst current = outcomes[i];\n\t\tconst currentPrecedence = getPrecedence(current.outcome);\n\t\tif (currentPrecedence > maxPrecedence) {\n\t\t\twinner = current;\n\t\t\tmaxPrecedence = currentPrecedence;\n\t\t}\n\t}\n\n\tif (!isGateOutcomeKind(winner.outcome)) {\n\t\treturn {\n\t\t\t...winner,\n\t\t\toutcome: \"block\",\n\t\t\tmessage: winner.message || \"Malformed outcome kind coerced to block\",\n\t\t};\n\t}\n\n\treturn winner;\n}\n\nexport function fallbackGateOutcome(args: { gate: string; reversible: boolean; reasonCode: string }): GateOutcome {\n\tconst gate = (args.gate || \"\").trim() || \"unknown_gate\";\n\tconst reasonCode = (args.reasonCode || \"\").trim() || \"unknown_reason\";\n\tconst outcome: GateOutcomeKind = args.reversible ? \"ask-user\" : \"block\";\n\n\treturn {\n\t\toutcome,\n\t\tgate,\n\t\treasonCode,\n\t\tmessage: `Fallback gate outcome: ${outcome} for gate ${gate} (${reasonCode})`,\n\t};\n}\n\nexport function extractCandidatePaths(toolName: string, args: unknown): string[] {\n\tif (!args || typeof args !== \"object\") return [];\n\tconst obj = args as Record<string, unknown>;\n\tconst paths: string[] = [];\n\n\tif (\n\t\ttoolName === \"read\" ||\n\t\ttoolName === \"write\" ||\n\t\ttoolName === \"edit\" ||\n\t\ttoolName === \"ls\" ||\n\t\ttoolName === \"grep\" ||\n\t\ttoolName === \"find\"\n\t) {\n\t\tif (typeof obj.path === \"string\" && obj.path.trim()) {\n\t\t\tpaths.push(obj.path.trim());\n\t\t}\n\t}\n\n\treturn paths;\n}\n\nexport function evaluateToolGate(input: {\n\ttoolName: string;\n\targs?: unknown;\n\tcwd: string;\n\tenvelope?: CapabilityEnvelope;\n}): GateOutcome {\n\tif (!input.envelope) {\n\t\treturn {\n\t\t\toutcome: \"allow\",\n\t\t\tgate: \"tool_gate\",\n\t\t\treasonCode: \"no_envelope\",\n\t\t\tmessage: \"No envelope active, preserving existing session behavior.\",\n\t\t};\n\t}\n\n\tconst envelope = input.envelope;\n\n\t// 1. Tool allow/deny list overrides\n\tif (envelope.deniedTools?.includes(input.toolName)) {\n\t\treturn {\n\t\t\toutcome: \"block\",\n\t\t\tgate: \"tool_gate\",\n\t\t\treasonCode: \"tool_denied\",\n\t\t\tmessage: `Tool '${input.toolName}' is explicitly denied.`,\n\t\t};\n\t}\n\n\tif (envelope.allowedTools && !envelope.allowedTools.includes(input.toolName)) {\n\t\treturn {\n\t\t\toutcome: \"block\",\n\t\t\tgate: \"tool_gate\",\n\t\t\treasonCode: \"tool_not_allowed\",\n\t\t\tmessage: `Tool '${input.toolName}' is not in the allowed tools list.`,\n\t\t};\n\t}\n\n\t// 2. Path scope containment for file tools\n\tconst paths = extractCandidatePaths(input.toolName, input.args);\n\tif (paths.length > 0 && envelope.allowedPaths) {\n\t\t// If envelope has allowedPaths, we must check them\n\t\tfor (const targetPath of paths) {\n\t\t\tconst scopedTargetPath = path.isAbsolute(targetPath) ? targetPath : path.resolve(input.cwd, targetPath);\n\t\t\tlet isInsideAny = false;\n\t\t\tlet isDenied = false;\n\t\t\tlet denyRule = \"\";\n\n\t\t\tfor (const allowedRoot of envelope.allowedPaths) {\n\t\t\t\tconst decision = checkPathScope(\n\t\t\t\t\t{\n\t\t\t\t\t\troot: allowedRoot,\n\t\t\t\t\t\tallowedPaths: envelope.allowedPaths,\n\t\t\t\t\t\tdeniedPaths: envelope.deniedPaths,\n\t\t\t\t\t},\n\t\t\t\t\tscopedTargetPath,\n\t\t\t\t);\n\n\t\t\t\tif (decision.kind === \"denied\") {\n\t\t\t\t\tisDenied = true;\n\t\t\t\t\tdenyRule = decision.matchedRule || \"\";\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (decision.kind === \"inside\") {\n\t\t\t\t\tisInsideAny = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (isDenied) {\n\t\t\t\treturn {\n\t\t\t\t\toutcome: \"block\",\n\t\t\t\t\tgate: \"path_scope\",\n\t\t\t\t\treasonCode: \"path_denied\",\n\t\t\t\t\tmessage: `Path '${targetPath}' is explicitly denied by rule '${denyRule}'.`,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (!isInsideAny) {\n\t\t\t\t// Block only if the tool is mutating. Wait, read path outside allowed root -> block.\n\t\t\t\t// \"read path inside allowed root -> allow. write/edit path outside allowed root -> block. denied path inside allowed root -> block.\"\n\t\t\t\treturn {\n\t\t\t\t\toutcome: \"block\",\n\t\t\t\t\tgate: \"path_scope\",\n\t\t\t\t\treasonCode: \"path_outside_allowed_roots\",\n\t\t\t\t\tmessage: `Path '${targetPath}' is outside all allowed roots.`,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\t// 2.5. Capability checks\n\tif (!hasCapabilityPolicyForTool(input.toolName)) {\n\t\treturn {\n\t\t\toutcome: \"block\",\n\t\t\tgate: \"tool_gate\",\n\t\t\treasonCode: \"unknown_tool_capability\",\n\t\t\tmessage: `Tool '${input.toolName}' has no capability policy in the active envelope.`,\n\t\t};\n\t}\n\n\tconst requiredCaps = requiredCapabilitiesForTool(input.toolName, input.args);\n\tif (!hasRequiredCapabilityForTool(envelope.capabilities, input.toolName, input.args)) {\n\t\treturn {\n\t\t\toutcome: \"block\",\n\t\t\tgate: \"tool_gate\",\n\t\t\treasonCode: \"missing_capability\",\n\t\t\tmessage: `Tool '${input.toolName}' requires capability '${requiredCaps.join(\" or \")}', which is missing from the active envelope.`,\n\t\t};\n\t}\n\tlet command = \"\";\n\tif (\n\t\tinput.toolName === \"bash\" ||\n\t\tinput.toolName === \"powershell\" ||\n\t\tinput.toolName === \"shell\" ||\n\t\tinput.toolName === \"python\"\n\t) {\n\t\tconst argsObj = input.args as Record<string, unknown>;\n\t\tif (argsObj && typeof argsObj.command === \"string\") command = argsObj.command;\n\t\telse if (input.toolName === \"python\" && argsObj && typeof argsObj.code === \"string\") command = argsObj.code;\n\t\telse if (input.toolName === \"python\" && argsObj && typeof argsObj.scriptPath === \"string\") {\n\t\t\tcommand = `python ${argsObj.scriptPath}`;\n\t\t}\n\t}\n\n\tconst riskResult = assessOperationRisk({\n\t\toperation: `Tool ${input.toolName}`,\n\t\ttoolName: input.toolName,\n\t\tcommand,\n\t\tpaths,\n\t\tcapabilities: envelope.capabilities,\n\t});\n\n\tif (riskResult.requiresApproval) {\n\t\treturn {\n\t\t\toutcome: \"ask-user\", // or block, prompt says: ask-user/block\n\t\t\tgate: \"risk_assessment\",\n\t\t\treasonCode: riskResult.reasonCode,\n\t\t\tmessage: `Operation requires approval: ${riskResult.reasons.join(\", \")}`,\n\t\t};\n\t}\n\n\tif (riskResult.risk === \"high-impact\") {\n\t\treturn {\n\t\t\toutcome: \"ask-user\",\n\t\t\tgate: \"risk_assessment\",\n\t\t\treasonCode: riskResult.reasonCode,\n\t\t\tmessage: `High-impact operation requires review: ${riskResult.reasons.join(\", \")}`,\n\t\t};\n\t}\n\n\treturn {\n\t\toutcome: \"allow\",\n\t\tgate: \"tool_gate\",\n\t\treasonCode: \"allowed_by_envelope\",\n\t\tmessage: \"Operation allowed by current capability envelope.\",\n\t};\n}\n"]}
1
+ {"version":3,"file":"gates.js","sourceRoot":"","sources":["../../../src/core/autonomy/gates.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EACN,0BAA0B,EAC1B,4BAA4B,EAC5B,2BAA2B,GAC3B,MAAM,oBAAoB,CAAC;AAE5B,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAE,mBAAmB,EAAE,MAAM,sBAAsB,CAAC;AAE3D,SAAS,iBAAiB,CAAC,KAAc;IACxC,OAAO,CACN,KAAK,KAAK,OAAO,IAAI,KAAK,KAAK,WAAW,IAAI,KAAK,KAAK,UAAU,IAAI,KAAK,KAAK,UAAU,IAAI,KAAK,KAAK,OAAO,CAC/G,CAAC;AACH,CAAC;AAED,SAAS,aAAa,CAAC,IAAa;IACnC,IAAI,IAAI,KAAK,OAAO;QAAE,OAAO,CAAC,CAAC;IAC/B,IAAI,IAAI,KAAK,WAAW;QAAE,OAAO,CAAC,CAAC;IACnC,IAAI,IAAI,KAAK,UAAU;QAAE,OAAO,CAAC,CAAC;IAClC,IAAI,IAAI,KAAK,UAAU;QAAE,OAAO,CAAC,CAAC;IAClC,IAAI,IAAI,KAAK,OAAO;QAAE,OAAO,CAAC,CAAC;IAC/B,OAAO,CAAC,CAAC,CAAC,sEAAsE;AACjF,CAAC;AAED,MAAM,UAAU,mBAAmB,CAAC,Q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,cAAc,EAAE,CAAC;QAC9C,MAAM,OAAO,GAAG,KAAK,CAAC,IAA+B,CAAC;QACtD,IAAI,OAAO,IAAI,OAAO,OAAO,CAAC,MAAM,KAAK,QAAQ;YAAE,OAAO,GAAG,OAAO,CAAC,MAAM,CAAC;IAC7E,CAAC;IAED,MAAM,UAAU,GAAG,mBAAmB,CAAC;QACtC,SAAS,EAAE,QAAQ,KAAK,CAAC,QAAQ,EAAE;QACnC,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,OAAO;QACP,KAAK;QACL,YAAY,EAAE,QAAQ,CAAC,YAAY;KACnC,CAAC,CAAC;IAEH,IAAI,UAAU,CAAC,gBAAgB,EAAE,CAAC;QACjC,OAAO;YACN,OAAO,EAAE,UAAU,EAAE,wCAAwC;YAC7D,IAAI,EAAE,iBAAiB;YACvB,UAAU,EAAE,UAAU,CAAC,UAAU;YACjC,OAAO,EAAE,gCAAgC,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;SACxE,CAAC;IACH,CAAC;IAED,IAAI,UAAU,CAAC,IAAI,KAAK,aAAa,EAAE,CAAC;QACvC,OAAO;YACN,OAAO,EAAE,UAAU;YACnB,IAAI,EAAE,iBAAiB;YACvB,UAAU,EAAE,UAAU,CAAC,UAAU;YACjC,OAAO,EAAE,0CAA0C,UAAU,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE;SAClF,CAAC;IACH,CAAC;IAED,OAAO;QACN,OAAO,EAAE,OAAO;QAChB,IAAI,EAAE,WAAW;QACjB,UAAU,EAAE,qBAAqB;QACjC,OAAO,EAAE,mDAAmD;KAC5D,CAAC;AACH,CAAC","sourcesContent":["import path from \"node:path\";\nimport {\n\thasCapabilityPolicyForTool,\n\thasRequiredCapabilityForTool,\n\trequiredCapabilitiesForTool,\n} from \"./approval-gate.ts\";\nimport type { CapabilityEnvelope, GateOutcome, GateOutcomeKind } from \"./contracts.ts\";\nimport { checkPathScope } from \"./path-scope.ts\";\nimport { assessOperationRisk } from \"./risk-assessment.ts\";\n\nfunction isGateOutcomeKind(value: unknown): value is GateOutcomeKind {\n\treturn (\n\t\tvalue === \"allow\" || value === \"downgrade\" || value === \"escalate\" || value === \"ask-user\" || value === \"block\"\n\t);\n}\n\nfunction getPrecedence(kind: unknown): number {\n\tif (kind === \"allow\") return 0;\n\tif (kind === \"downgrade\") return 1;\n\tif (kind === \"escalate\") return 2;\n\tif (kind === \"ask-user\") return 3;\n\tif (kind === \"block\") return 4;\n\treturn 4; // Malformed/unknown outcome kind defaults to most restrictive (block)\n}\n\nexport function combineGateOutcomes(outcomes: readonly GateOutcome[]): GateOutcome {\n\tif (outcomes.length === 0) {\n\t\treturn {\n\t\t\toutcome: \"ask-user\",\n\t\t\tgate: \"gate-combiner\",\n\t\t\treasonCode: \"no_gate_outcomes\",\n\t\t\tmessage: \"No gate outcomes to combine\",\n\t\t};\n\t}\n\n\tlet winner = outcomes[0];\n\tlet maxPrecedence = getPrecedence(winner.outcome);\n\n\tfor (let i = 1; i < outcomes.length; i++) {\n\t\tconst current = outcomes[i];\n\t\tconst currentPrecedence = getPrecedence(current.outcome);\n\t\tif (currentPrecedence > maxPrecedence) {\n\t\t\twinner = current;\n\t\t\tmaxPrecedence = currentPrecedence;\n\t\t}\n\t}\n\n\tif (!isGateOutcomeKind(winner.outcome)) {\n\t\treturn {\n\t\t\t...winner,\n\t\t\toutcome: \"block\",\n\t\t\tmessage: winner.message || \"Malformed outcome kind coerced to block\",\n\t\t};\n\t}\n\n\treturn winner;\n}\n\nexport function fallbackGateOutcome(args: { gate: string; reversible: boolean; reasonCode: string }): GateOutcome {\n\tconst gate = (args.gate || \"\").trim() || \"unknown_gate\";\n\tconst reasonCode = (args.reasonCode || \"\").trim() || \"unknown_reason\";\n\tconst outcome: GateOutcomeKind = args.reversible ? \"ask-user\" : \"block\";\n\n\treturn {\n\t\toutcome,\n\t\tgate,\n\t\treasonCode,\n\t\tmessage: `Fallback gate outcome: ${outcome} for gate ${gate} (${reasonCode})`,\n\t};\n}\n\nexport function extractCandidatePaths(toolName: string, args: unknown): string[] {\n\tif (!args || typeof args !== \"object\") return [];\n\tconst obj = args as Record<string, unknown>;\n\tconst paths: string[] = [];\n\n\tif (\n\t\ttoolName === \"read\" ||\n\t\ttoolName === \"write\" ||\n\t\ttoolName === \"edit\" ||\n\t\ttoolName === \"ls\" ||\n\t\ttoolName === \"grep\" ||\n\t\ttoolName === \"find\"\n\t) {\n\t\tif (typeof obj.path === \"string\" && obj.path.trim()) {\n\t\t\tpaths.push(obj.path.trim());\n\t\t}\n\t} else if (toolName === \"secret_store\" && obj.action === \"migrate\" && Array.isArray(obj.sources)) {\n\t\tfor (const source of obj.sources) {\n\t\t\tif (\n\t\t\t\tsource &&\n\t\t\t\ttypeof source === \"object\" &&\n\t\t\t\t\"path\" in source &&\n\t\t\t\ttypeof source.path === \"string\" &&\n\t\t\t\tsource.path.trim()\n\t\t\t) {\n\t\t\t\tpaths.push(source.path.trim());\n\t\t\t}\n\t\t}\n\t}\n\n\treturn paths;\n}\n\nexport function evaluateToolGate(input: {\n\ttoolName: string;\n\targs?: unknown;\n\tcwd: string;\n\tenvelope?: CapabilityEnvelope;\n}): GateOutcome {\n\tif (!input.envelope) {\n\t\treturn {\n\t\t\toutcome: \"allow\",\n\t\t\tgate: \"tool_gate\",\n\t\t\treasonCode: \"no_envelope\",\n\t\t\tmessage: \"No envelope active, preserving existing session behavior.\",\n\t\t};\n\t}\n\n\tconst envelope = input.envelope;\n\n\t// 1. Tool allow/deny list overrides\n\tif (envelope.deniedTools?.includes(input.toolName)) {\n\t\treturn {\n\t\t\toutcome: \"block\",\n\t\t\tgate: \"tool_gate\",\n\t\t\treasonCode: \"tool_denied\",\n\t\t\tmessage: `Tool '${input.toolName}' is explicitly denied.`,\n\t\t};\n\t}\n\n\tif (envelope.allowedTools && !envelope.allowedTools.includes(input.toolName)) {\n\t\treturn {\n\t\t\toutcome: \"block\",\n\t\t\tgate: \"tool_gate\",\n\t\t\treasonCode: \"tool_not_allowed\",\n\t\t\tmessage: `Tool '${input.toolName}' is not in the allowed tools list.`,\n\t\t};\n\t}\n\n\t// 2. Path scope containment for file tools\n\tconst paths = extractCandidatePaths(input.toolName, input.args);\n\tif (paths.length > 0 && envelope.allowedPaths) {\n\t\t// If envelope has allowedPaths, we must check them\n\t\tfor (const targetPath of paths) {\n\t\t\tconst scopedTargetPath = path.isAbsolute(targetPath) ? targetPath : path.resolve(input.cwd, targetPath);\n\t\t\tlet isInsideAny = false;\n\t\t\tlet isDenied = false;\n\t\t\tlet denyRule = \"\";\n\n\t\t\tfor (const allowedRoot of envelope.allowedPaths) {\n\t\t\t\tconst decision = checkPathScope(\n\t\t\t\t\t{\n\t\t\t\t\t\troot: allowedRoot,\n\t\t\t\t\t\tallowedPaths: envelope.allowedPaths,\n\t\t\t\t\t\tdeniedPaths: envelope.deniedPaths,\n\t\t\t\t\t},\n\t\t\t\t\tscopedTargetPath,\n\t\t\t\t);\n\n\t\t\t\tif (decision.kind === \"denied\") {\n\t\t\t\t\tisDenied = true;\n\t\t\t\t\tdenyRule = decision.matchedRule || \"\";\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (decision.kind === \"inside\") {\n\t\t\t\t\tisInsideAny = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (isDenied) {\n\t\t\t\treturn {\n\t\t\t\t\toutcome: \"block\",\n\t\t\t\t\tgate: \"path_scope\",\n\t\t\t\t\treasonCode: \"path_denied\",\n\t\t\t\t\tmessage: `Path '${targetPath}' is explicitly denied by rule '${denyRule}'.`,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\tif (!isInsideAny) {\n\t\t\t\t// Block only if the tool is mutating. Wait, read path outside allowed root -> block.\n\t\t\t\t// \"read path inside allowed root -> allow. write/edit path outside allowed root -> block. denied path inside allowed root -> block.\"\n\t\t\t\treturn {\n\t\t\t\t\toutcome: \"block\",\n\t\t\t\t\tgate: \"path_scope\",\n\t\t\t\t\treasonCode: \"path_outside_allowed_roots\",\n\t\t\t\t\tmessage: `Path '${targetPath}' is outside all allowed roots.`,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\t// 2.5. Capability checks\n\tif (!hasCapabilityPolicyForTool(input.toolName)) {\n\t\treturn {\n\t\t\toutcome: \"block\",\n\t\t\tgate: \"tool_gate\",\n\t\t\treasonCode: \"unknown_tool_capability\",\n\t\t\tmessage: `Tool '${input.toolName}' has no capability policy in the active envelope.`,\n\t\t};\n\t}\n\n\tconst requiredCaps = requiredCapabilitiesForTool(input.toolName, input.args);\n\tif (!hasRequiredCapabilityForTool(envelope.capabilities, input.toolName, input.args)) {\n\t\treturn {\n\t\t\toutcome: \"block\",\n\t\t\tgate: \"tool_gate\",\n\t\t\treasonCode: \"missing_capability\",\n\t\t\tmessage: `Tool '${input.toolName}' requires capability '${requiredCaps.join(\" or \")}', which is missing from the active envelope.`,\n\t\t};\n\t}\n\tlet command = \"\";\n\tif (\n\t\tinput.toolName === \"bash\" ||\n\t\tinput.toolName === \"powershell\" ||\n\t\tinput.toolName === \"shell\" ||\n\t\tinput.toolName === \"python\"\n\t) {\n\t\tconst argsObj = input.args as Record<string, unknown>;\n\t\tif (argsObj && typeof argsObj.command === \"string\") command = argsObj.command;\n\t\telse if (input.toolName === \"python\" && argsObj && typeof argsObj.code === \"string\") command = argsObj.code;\n\t\telse if (input.toolName === \"python\" && argsObj && typeof argsObj.scriptPath === \"string\") {\n\t\t\tcommand = `python ${argsObj.scriptPath}`;\n\t\t}\n\t} else if (input.toolName === \"secret_store\") {\n\t\tconst argsObj = input.args as Record<string, unknown>;\n\t\tif (argsObj && typeof argsObj.action === \"string\") command = argsObj.action;\n\t}\n\n\tconst riskResult = assessOperationRisk({\n\t\toperation: `Tool ${input.toolName}`,\n\t\ttoolName: input.toolName,\n\t\tcommand,\n\t\tpaths,\n\t\tcapabilities: envelope.capabilities,\n\t});\n\n\tif (riskResult.requiresApproval) {\n\t\treturn {\n\t\t\toutcome: \"ask-user\", // or block, prompt says: ask-user/block\n\t\t\tgate: \"risk_assessment\",\n\t\t\treasonCode: riskResult.reasonCode,\n\t\t\tmessage: `Operation requires approval: ${riskResult.reasons.join(\", \")}`,\n\t\t};\n\t}\n\n\tif (riskResult.risk === \"high-impact\") {\n\t\treturn {\n\t\t\toutcome: \"ask-user\",\n\t\t\tgate: \"risk_assessment\",\n\t\t\treasonCode: riskResult.reasonCode,\n\t\t\tmessage: `High-impact operation requires review: ${riskResult.reasons.join(\", \")}`,\n\t\t};\n\t}\n\n\treturn {\n\t\toutcome: \"allow\",\n\t\tgate: \"tool_gate\",\n\t\treasonCode: \"allowed_by_envelope\",\n\t\tmessage: \"Operation allowed by current capability envelope.\",\n\t};\n}\n"]}
@@ -1,3 +1,5 @@
1
+ import { SUBAGENT_CORE_SYSTEM_PROMPT } from "../provider-prompt-contracts.ts";
2
+ export { SUBAGENT_CORE_SYSTEM_PROMPT };
1
3
  /**
2
4
  * Agent system-prompt composition with an irreducible execution-contract core.
3
5
  *
@@ -8,7 +10,6 @@
8
10
  * caller can hand a tiny model a purpose-built minimal prompt) while the kernel remains the sole
9
11
  * authority and budget owner. Keep the core UNDER 300 tokens; it is deliberately terse.
10
12
  */
11
- export declare const SUBAGENT_CORE_SYSTEM_PROMPT: string;
12
13
  export interface SubagentPromptParts {
13
14
  /** Situational identity from the shipped profile (replaceable layer). */
14
15
  soul?: string;
@@ -1 +1 @@
1
- {"version":3,"file":"subagent-prompt.d.ts","sourceRoot":"","sources":["../../../src/core/autonomy/subagent-prompt.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,eAAO,MAAM,2BAA2B,QAO5B,CAAC;AAEb,MAAM,WAAW,mBAAmB;IACnC,yEAAyE;IACzE,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,0DAA0D;IAC1D,UAAU,EAAE,MAAM,CAAC;IACnB,yEAAyE;IACzE,QAAQ,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,wBAAgB,2BAA2B,CAAC,KAAK,EAAE,mBAAmB,GAAG,MAAM,CAS9E"}
1
+ {"version":3,"file":"subagent-prompt.d.ts","sourceRoot":"","sources":["../../../src/core/autonomy/subagent-prompt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,2BAA2B,EAAE,MAAM,iCAAiC,CAAC;AAE9E,OAAO,EAAE,2BAA2B,EAAE,CAAC;AAEvC;;;;;;;;;GASG;AACH,MAAM,WAAW,mBAAmB;IACnC,yEAAyE;IACzE,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,0DAA0D;IAC1D,UAAU,EAAE,MAAM,CAAC;IACnB,yEAAyE;IACzE,QAAQ,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,wBAAgB,2BAA2B,CAAC,KAAK,EAAE,mBAAmB,GAAG,MAAM,CAS9E"}
@@ -1,21 +1,5 @@
1
- /**
2
- * Agent system-prompt composition with an irreducible execution-contract core.
3
- *
4
- * The core is the "ultimate level-0 default": ~80 tokens of non-negotiable rules that survive ANY
5
- * customization. Everything above it — the lane's role prompt and a shipped profile's soul — is a
6
- * replaceable layer: settings, a lane profile, or the calling model (delegate tool) can erase and
7
- * replace it entirely. This keeps shipped subagents maximally efficient on small open models (a
8
- * caller can hand a tiny model a purpose-built minimal prompt) while the kernel remains the sole
9
- * authority and budget owner. Keep the core UNDER 300 tokens; it is deliberately terse.
10
- */
11
- export const SUBAGENT_CORE_SYSTEM_PROMPT = [
12
- "You are an autonomous agent in a coding-agent orchestration tree. Execution contract:",
13
- "1. Use the maximum useful capability exposed by your tool surface; the kernel enforces the exact inherited authority.",
14
- "2. You may delegate recursively within host-enforced fleet bounds, inspect only your own control subtree transcripts, and exchange threaded peer messages when those tools are present.",
15
- "3. Concurrency, cumulative budgets, leases, cycle detection, cancellation, and irreversible user-authority boundaries are kernel-owned.",
16
- "4. Never invent facts, file paths, APIs, or command results; state uncertainty directly.",
17
- "5. Follow the requested output contract exactly; your result remains evidence that other agents may independently verify.",
18
- ].join("\n");
1
+ import { SUBAGENT_CORE_SYSTEM_PROMPT } from "../provider-prompt-contracts.js";
2
+ export { SUBAGENT_CORE_SYSTEM_PROMPT };
19
3
  export function composeSubagentSystemPrompt(parts) {
20
4
  const override = parts.override?.trim();
21
5
  const above = override && override.length > 0
@@ -1 +1 @@
1
- {"version":3,"file":"subagent-prompt.js","sourceRoot":"","sources":["../../../src/core/autonomy/subagent-prompt.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAG;IAC1C,uFAAuF;IACvF,uHAAuH;IACvH,yLAAyL;IACzL,yIAAyI;IACzI,0FAA0F;IAC1F,2HAA2H;CAC3H,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAWb,MAAM,UAAU,2BAA2B,CAAC,KAA0B;IACrE,MAAM,QAAQ,GAAG,KAAK,CAAC,QAAQ,EAAE,IAAI,EAAE,CAAC;IACxC,MAAM,KAAK,GACV,QAAQ,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC;QAC9B,CAAC,CAAC,QAAQ;QACV,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,KAAK,CAAC,UAAU,CAAC;aACrC,MAAM,CAAC,CAAC,IAAI,EAAkB,EAAE,CAAC,OAAO,CAAC,IAAI,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;aAClE,IAAI,CAAC,MAAM,CAAC,CAAC;IAClB,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,2BAA2B,OAAO,KAAK,EAAE,CAAC,CAAC,CAAC,2BAA2B,CAAC;AACtG,CAAC","sourcesContent":["/**\n * Agent system-prompt composition with an irreducible execution-contract core.\n *\n * The core is the \"ultimate level-0 default\": ~80 tokens of non-negotiable rules that survive ANY\n * customization. Everything above it — the lane's role prompt and a shipped profile's soul — is a\n * replaceable layer: settings, a lane profile, or the calling model (delegate tool) can erase and\n * replace it entirely. This keeps shipped subagents maximally efficient on small open models (a\n * caller can hand a tiny model a purpose-built minimal prompt) while the kernel remains the sole\n * authority and budget owner. Keep the core UNDER 300 tokens; it is deliberately terse.\n */\nexport const SUBAGENT_CORE_SYSTEM_PROMPT = [\n\t\"You are an autonomous agent in a coding-agent orchestration tree. Execution contract:\",\n\t\"1. Use the maximum useful capability exposed by your tool surface; the kernel enforces the exact inherited authority.\",\n\t\"2. You may delegate recursively within host-enforced fleet bounds, inspect only your own control subtree transcripts, and exchange threaded peer messages when those tools are present.\",\n\t\"3. Concurrency, cumulative budgets, leases, cycle detection, cancellation, and irreversible user-authority boundaries are kernel-owned.\",\n\t\"4. Never invent facts, file paths, APIs, or command results; state uncertainty directly.\",\n\t\"5. Follow the requested output contract exactly; your result remains evidence that other agents may independently verify.\",\n].join(\"\\n\");\n\nexport interface SubagentPromptParts {\n\t/** Situational identity from the shipped profile (replaceable layer). */\n\tsoul?: string;\n\t/** The lane's default role prompt (replaceable layer). */\n\trolePrompt: string;\n\t/** User- or model-provided replacement for every layer above level 0. */\n\toverride?: string;\n}\n\nexport function composeSubagentSystemPrompt(parts: SubagentPromptParts): string {\n\tconst override = parts.override?.trim();\n\tconst above =\n\t\toverride && override.length > 0\n\t\t\t? override\n\t\t\t: [parts.soul?.trim(), parts.rolePrompt]\n\t\t\t\t\t.filter((part): part is string => Boolean(part && part.length > 0))\n\t\t\t\t\t.join(\"\\n\\n\");\n\treturn above.length > 0 ? `${SUBAGENT_CORE_SYSTEM_PROMPT}\\n\\n${above}` : SUBAGENT_CORE_SYSTEM_PROMPT;\n}\n"]}
1
+ {"version":3,"file":"subagent-prompt.js","sourceRoot":"","sources":["../../../src/core/autonomy/subagent-prompt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,2BAA2B,EAAE,MAAM,iCAAiC,CAAC;AAE9E,OAAO,EAAE,2BAA2B,EAAE,CAAC;AAqBvC,MAAM,UAAU,2BAA2B,CAAC,KAA0B;IACrE,MAAM,QAAQ,GAAG,KAAK,CAAC,QAAQ,EAAE,IAAI,EAAE,CAAC;IACxC,MAAM,KAAK,GACV,QAAQ,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC;QAC9B,CAAC,CAAC,QAAQ;QACV,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,EAAE,IAAI,EAAE,EAAE,KAAK,CAAC,UAAU,CAAC;aACrC,MAAM,CAAC,CAAC,IAAI,EAAkB,EAAE,CAAC,OAAO,CAAC,IAAI,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC;aAClE,IAAI,CAAC,MAAM,CAAC,CAAC;IAClB,OAAO,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,2BAA2B,OAAO,KAAK,EAAE,CAAC,CAAC,CAAC,2BAA2B,CAAC;AACtG,CAAC","sourcesContent":["import { SUBAGENT_CORE_SYSTEM_PROMPT } from \"../provider-prompt-contracts.ts\";\n\nexport { SUBAGENT_CORE_SYSTEM_PROMPT };\n\n/**\n * Agent system-prompt composition with an irreducible execution-contract core.\n *\n * The core is the \"ultimate level-0 default\": ~80 tokens of non-negotiable rules that survive ANY\n * customization. Everything above it — the lane's role prompt and a shipped profile's soul — is a\n * replaceable layer: settings, a lane profile, or the calling model (delegate tool) can erase and\n * replace it entirely. This keeps shipped subagents maximally efficient on small open models (a\n * caller can hand a tiny model a purpose-built minimal prompt) while the kernel remains the sole\n * authority and budget owner. Keep the core UNDER 300 tokens; it is deliberately terse.\n */\nexport interface SubagentPromptParts {\n\t/** Situational identity from the shipped profile (replaceable layer). */\n\tsoul?: string;\n\t/** The lane's default role prompt (replaceable layer). */\n\trolePrompt: string;\n\t/** User- or model-provided replacement for every layer above level 0. */\n\toverride?: string;\n}\n\nexport function composeSubagentSystemPrompt(parts: SubagentPromptParts): string {\n\tconst override = parts.override?.trim();\n\tconst above =\n\t\toverride && override.length > 0\n\t\t\t? override\n\t\t\t: [parts.soul?.trim(), parts.rolePrompt]\n\t\t\t\t\t.filter((part): part is string => Boolean(part && part.length > 0))\n\t\t\t\t\t.join(\"\\n\\n\");\n\treturn above.length > 0 ? `${SUBAGENT_CORE_SYSTEM_PROMPT}\\n\\n${above}` : SUBAGENT_CORE_SYSTEM_PROMPT;\n}\n"]}
@@ -46,9 +46,9 @@ export function createBackgroundToolTerminalMessage(records) {
46
46
  customType: "background-tool-completion",
47
47
  content: [
48
48
  "Background tool terminal handoff:",
49
- ...included.map((record) => `- ${record.taskId}: ${record.status} (tool=${record.toolName})`),
50
- ...(omitted > 0 ? [`- ${omitted} additional terminal tool task(s) omitted from this bounded handoff.`] : []),
51
- "This terminal event woke the owning session. Retrieve the result once with tool_task action=wait if it is needed; never poll.",
49
+ ...included.map((record) => `- ${record.taskId}: ${record.status} tool=${record.toolName}`),
50
+ ...(omitted > 0 ? [`- ${omitted} additional terminal tool task(s) omitted.`] : []),
51
+ "Parent woke. Need result: tool_task action=wait once; never poll.",
52
52
  ].join("\n"),
53
53
  display: true,
54
54
  details: {
@@ -206,8 +206,8 @@ export class BackgroundToolTaskController {
206
206
  {
207
207
  type: "text",
208
208
  text: [
209
- `Tool ${context.toolCall.name} exceeded ${Math.max(1, Math.round(context.elapsedMs / 1000))}s and continues as session task ${taskId}.`,
210
- "Continue independent work. If its result is a dependency, call tool_task once with action=wait and this taskId; the wait is event-driven. Never poll.",
209
+ `Tool ${context.toolCall.name} exceeded ${Math.max(1, Math.round(context.elapsedMs / 1000))}s; running as session task ${taskId}.`,
210
+ "Continue independent work. Dependency: tool_task action=wait once with taskId; event-driven, never poll.",
211
211
  ].join("\n"),
212
212
  },
213
213
  ],
@@ -1 +1 @@
1
- {"version":3,"file":"background-tool-task-controller.js","sourceRoot":"","sources":["../../src/core/background-tool-task-controller.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AACvF,OAAO,EAAE,WAAW,EAAE,aAAa,EAAE,MAAM,wBAAwB,CAAC;AA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AAC,MAAM,CAAC,UAAU,EAAE,KAAK,CAAC,gBAAgB,CAAC,CAAC;YACxE,KAAK,EAAE,OAAO,EAAE,CAAC;QAClB,CAAC;IACF,CAAC;IAEO,GAAG;QACV,OAAO,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,EAAE,IAAI,IAAI,IAAI,EAAE,CAAC;IACxC,CAAC;CACD","sourcesContent":["import type {\n\tBackgroundToolCallCompletion,\n\tBackgroundToolCallContext,\n\tBackgroundToolCallHandoff,\n} from \"@caupulican/pi-agent-core\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport type { Usage } from \"@caupulican/pi-ai\";\nimport type { ArtifactStore } from \"./context/context-artifacts.ts\";\nimport { formatArtifactNotice, packToolOutput } from \"./context/tool-output-packer.ts\";\nimport { hasOnlyKeys, isPlainRecord } from \"./util/value-guards.ts\";\n\nexport const DEFAULT_BACKGROUND_TOOL_CALL_AFTER_MS = 15_000;\nexport const BACKGROUND_TOOL_TASK_CUSTOM_TYPE = \"background_tool_task\";\n\nconst MAX_RETAINED_TERMINAL_TASKS = 64;\nconst MAX_INLINE_OUTPUT_BYTES = 32 * 1024;\nconst MAX_INLINE_OUTPUT_LINES = 400;\nconst MAX_SUMMARY_CHARS = 200;\nconst MAX_TERMINAL_HANDOFF_RECORDS = 8;\nconst TASK_ID_PATTERN = /^tool-task-([1-9]\\d*)$/;\nconst RECORD_KEYS = [\n\t\"sessionId\",\n\t\"taskId\",\n\t\"toolCallId\",\n\t\"toolName\",\n\t\"status\",\n\t\"startedAt\",\n\t\"completedAt\",\n\t\"elapsedBeforeHandoffMs\",\n\t\"summary\",\n\t\"output\",\n\t\"artifactId\",\n\t\"usage\",\n\t\"cancellationRequested\",\n] as const;\n\nexport type BackgroundToolTaskStatus = \"running\" | \"completed\" | \"failed\" | \"canceled\";\n\nexport interface BackgroundToolTaskRecord {\n\tsessionId: string;\n\ttaskId: string;\n\ttoolCallId: string;\n\ttoolName: string;\n\tstatus: BackgroundToolTaskStatus;\n\tstartedAt: string;\n\tcompletedAt?: string;\n\telapsedBeforeHandoffMs: number;\n\tsummary: string;\n\toutput: string;\n\tartifactId?: string;\n\tusage?: Usage;\n\tcancellationRequested?: boolean;\n}\n\nexport interface BackgroundToolTaskLiveView {\n\ttaskId: string;\n\ttoolCallId: string;\n\ttoolName: string;\n\tdescription: string;\n}\n\nexport interface BackgroundToolTerminalMessage {\n\tcustomType: \"background-tool-completion\";\n\tcontent: string;\n\tdisplay: true;\n\tdetails: {\n\t\trecords: Array<{\n\t\t\ttaskId: string;\n\t\t\tstatus: BackgroundToolTaskStatus;\n\t\t\ttoolName: string;\n\t\t\tartifactId?: string;\n\t\t}>;\n\t};\n}\n\nexport interface BackgroundToolTaskControllerDeps {\n\tgetSessionId(): string;\n\tgetArtifactStore(): ArtifactStore | undefined;\n\t/** Durable task records on the active branch, newest first, without rebuilding full model context. */\n\tloadPersistedRecordsNewestFirst?(): readonly unknown[];\n\tpersist(record: BackgroundToolTaskRecord): void;\n\tnotifyTerminal(records: readonly BackgroundToolTaskRecord[], options: { wakeParent: boolean }): Promise<void> | void;\n\tonLiveTasksChanged?(tasks: readonly BackgroundToolTaskLiveView[]): void;\n\trecordUsage?(taskId: string, usage: Usage): void;\n\tonError?(message: string, error: unknown): void;\n\tnow?(): Date;\n}\n\ninterface BackgroundToolTaskState {\n\trecord: BackgroundToolTaskRecord;\n\tcancel: () => void;\n\tcancellationRequested: boolean;\n\twaitingConsumers: number;\n\tterminal: Promise<BackgroundToolTaskRecord>;\n\tresolveTerminal: (record: BackgroundToolTaskRecord) => void;\n\tartifactHolderId: string;\n}\n\n/** Read only task records on the active branch without allocating or hydrating the full branch context. */\nexport function loadBackgroundToolTaskRecordsNewestFirst(\n\tsessionManager: Pick<SessionManager, \"getLatestCustomEntryOnBranch\">,\n): unknown[] {\n\tconst records: unknown[] = [];\n\tlet fromId: string | undefined;\n\tfor (;;) {\n\t\tconst entry = sessionManager.getLatestCustomEntryOnBranch(BACKGROUND_TOOL_TASK_CUSTOM_TYPE, fromId);\n\t\tif (!entry) return records;\n\t\trecords.push(entry.data);\n\t\tif (entry.parentId === null) return records;\n\t\tfromId = entry.parentId;\n\t}\n}\n\nexport function createBackgroundToolTerminalMessage(\n\trecords: readonly BackgroundToolTaskRecord[],\n): BackgroundToolTerminalMessage {\n\tif (records.length === 0) throw new TypeError(\"Background tool terminal handoff requires at least one record\");\n\tconst included = records.slice(0, MAX_TERMINAL_HANDOFF_RECORDS);\n\tconst omitted = records.length - included.length;\n\treturn {\n\t\tcustomType: \"background-tool-completion\",\n\t\tcontent: [\n\t\t\t\"Background tool terminal handoff:\",\n\t\t\t...included.map((record) => `- ${record.taskId}: ${record.status} (tool=${record.toolName})`),\n\t\t\t...(omitted > 0 ? [`- ${omitted} additional terminal tool task(s) omitted from this bounded handoff.`] : []),\n\t\t\t\"This terminal event woke the owning session. Retrieve the result once with tool_task action=wait if it is needed; never poll.\",\n\t\t].join(\"\\n\"),\n\t\tdisplay: true,\n\t\tdetails: {\n\t\t\trecords: included.map((record) => ({\n\t\t\t\ttaskId: record.taskId,\n\t\t\t\tstatus: record.status,\n\t\t\t\ttoolName: record.toolName,\n\t\t\t\t...(record.artifactId ? { artifactId: record.artifactId } : {}),\n\t\t\t})),\n\t\t},\n\t};\n}\n\nfunction renderCompletionOutput(completion: BackgroundToolCallCompletion): string {\n\tconst blocks = completion.result.content.map((block) =>\n\t\tblock.type === \"text\" ? block.text : \"[Image output retained outside the foreground transcript]\",\n\t);\n\treturn blocks.join(\"\\n\") || \"Tool completed without text output.\";\n}\n\nfunction oneLine(value: string): string {\n\treturn value\n\t\t.replace(/[\\r\\n]+/g, \" \")\n\t\t.replace(/\\s+/g, \" \")\n\t\t.trim();\n}\n\nfunction summaryFor(status: BackgroundToolTaskStatus, toolName: string, output: string): string {\n\tconst prefix = `${toolName} ${status}`;\n\tconst firstLine = oneLine(output);\n\tif (!firstLine) return prefix;\n\tconst remaining = Math.max(0, MAX_SUMMARY_CHARS - prefix.length - 2);\n\treturn `${prefix}: ${firstLine.slice(0, remaining)}`;\n}\n\nfunction taskNumber(taskId: string): number | undefined {\n\tconst match = TASK_ID_PATTERN.exec(taskId);\n\tif (!match) return undefined;\n\tconst value = Number(match[1]);\n\treturn Number.isSafeInteger(value) && value > 0 ? value : undefined;\n}\n\nfunction cloneUsage(value: unknown): Usage | undefined {\n\tif (!isPlainRecord(value)) return undefined;\n\tconst cost = value.cost;\n\tif (!isPlainRecord(cost)) return undefined;\n\tconst fields = [\"input\", \"output\", \"cacheRead\", \"cacheWrite\", \"totalTokens\"] as const;\n\tconst costFields = [\"input\", \"output\", \"cacheRead\", \"cacheWrite\", \"total\"] as const;\n\tif (\n\t\tfields.some((field) => typeof value[field] !== \"number\" || !Number.isFinite(value[field])) ||\n\t\tcostFields.some((field) => typeof cost[field] !== \"number\" || !Number.isFinite(cost[field]))\n\t) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\tinput: value.input as number,\n\t\toutput: value.output as number,\n\t\tcacheRead: value.cacheRead as number,\n\t\tcacheWrite: value.cacheWrite as number,\n\t\ttotalTokens: value.totalTokens as number,\n\t\tcost: {\n\t\t\tinput: cost.input as number,\n\t\t\toutput: cost.output as number,\n\t\t\tcacheRead: cost.cacheRead as number,\n\t\t\tcacheWrite: cost.cacheWrite as number,\n\t\t\ttotal: cost.total as number,\n\t\t},\n\t};\n}\n\nfunction decodeRecord(value: unknown, sessionId: string): BackgroundToolTaskRecord | undefined {\n\tif (!isPlainRecord(value) || !hasOnlyKeys(value, RECORD_KEYS)) return undefined;\n\tif (\n\t\tvalue.sessionId !== sessionId ||\n\t\ttypeof value.taskId !== \"string\" ||\n\t\ttaskNumber(value.taskId) === undefined ||\n\t\ttypeof value.toolCallId !== \"string\" ||\n\t\tvalue.toolCallId.length === 0 ||\n\t\ttypeof value.toolName !== \"string\" ||\n\t\tvalue.toolName.length === 0 ||\n\t\t(value.status !== \"running\" &&\n\t\t\tvalue.status !== \"completed\" &&\n\t\t\tvalue.status !== \"failed\" &&\n\t\t\tvalue.status !== \"canceled\") ||\n\t\ttypeof value.startedAt !== \"string\" ||\n\t\t!Number.isFinite(Date.parse(value.startedAt)) ||\n\t\t(value.completedAt !== undefined &&\n\t\t\t(typeof value.completedAt !== \"string\" || !Number.isFinite(Date.parse(value.completedAt)))) ||\n\t\t(value.status !== \"running\" && value.completedAt === undefined) ||\n\t\ttypeof value.elapsedBeforeHandoffMs !== \"number\" ||\n\t\t!Number.isFinite(value.elapsedBeforeHandoffMs) ||\n\t\tvalue.elapsedBeforeHandoffMs < 0 ||\n\t\ttypeof value.summary !== \"string\" ||\n\t\ttypeof value.output !== \"string\" ||\n\t\t(value.artifactId !== undefined &&\n\t\t\t(typeof value.artifactId !== \"string\" || !/^[0-9a-f]{1,64}$/.test(value.artifactId))) ||\n\t\t(value.cancellationRequested !== undefined && typeof value.cancellationRequested !== \"boolean\")\n\t) {\n\t\treturn undefined;\n\t}\n\tconst usage = value.usage === undefined ? undefined : cloneUsage(value.usage);\n\tif (value.usage !== undefined && !usage) return undefined;\n\treturn {\n\t\tsessionId,\n\t\ttaskId: value.taskId,\n\t\ttoolCallId: value.toolCallId,\n\t\ttoolName: value.toolName,\n\t\tstatus: value.status,\n\t\tstartedAt: value.startedAt,\n\t\t...(value.completedAt ? { completedAt: value.completedAt } : {}),\n\t\telapsedBeforeHandoffMs: value.elapsedBeforeHandoffMs,\n\t\tsummary: value.summary,\n\t\toutput: value.output,\n\t\t...(value.artifactId ? { artifactId: value.artifactId } : {}),\n\t\t...(usage ? { usage } : {}),\n\t\t...(value.cancellationRequested !== undefined ? { cancellationRequested: value.cancellationRequested } : {}),\n\t};\n}\n\n/**\n * Session-owned registry for foreground tool calls transferred into background execution.\n * It emits edge records for durability and a replace-style live-task signal for UI consumers.\n */\nexport class BackgroundToolTaskController {\n\tprivate readonly deps: BackgroundToolTaskControllerDeps;\n\tprivate readonly tasks = new Map<string, BackgroundToolTaskState>();\n\tprivate readonly handoffRequests = new Map<string, Set<() => void>>();\n\tprivate readonly queuedNotifications: Array<{ record: BackgroundToolTaskRecord; wakeParent: boolean }> = [];\n\tprivate notificationDrain: Promise<void> | undefined;\n\tprivate nextTaskId = 1;\n\tprivate disposed = false;\n\n\tconstructor(deps: BackgroundToolTaskControllerDeps) {\n\t\tthis.deps = deps;\n\t\tthis.restorePersistedTasks();\n\t}\n\n\thandoff(context: BackgroundToolCallContext): BackgroundToolCallHandoff | undefined {\n\t\tif (this.disposed || context.toolCall.name === \"tool_task\") return undefined;\n\t\tconst sessionId = this.deps.getSessionId();\n\t\tconst taskId = `tool-task-${this.nextTaskId++}`;\n\t\tconst startedAt = this.now().toISOString();\n\t\tconst record: BackgroundToolTaskRecord = {\n\t\t\tsessionId,\n\t\t\ttaskId,\n\t\t\ttoolCallId: context.toolCall.id,\n\t\t\ttoolName: context.toolCall.name,\n\t\t\tstatus: \"running\",\n\t\t\tstartedAt,\n\t\t\telapsedBeforeHandoffMs: context.elapsedMs,\n\t\t\tsummary: `${context.toolCall.name} running in the background`,\n\t\t\toutput: \"\",\n\t\t};\n\t\tconst state = this.createState(record, context.cancel);\n\t\tthis.tasks.set(taskId, state);\n\t\tif (!this.persist(record)) {\n\t\t\tthis.tasks.delete(taskId);\n\t\t\treturn undefined;\n\t\t}\n\t\tthis.emitLiveTasks();\n\t\tcontext.completion.then(\n\t\t\t(completion) => this.settle(state, completion),\n\t\t\t(error) => this.settleRejected(state, error),\n\t\t);\n\n\t\treturn {\n\t\t\tresult: {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: [\n\t\t\t\t\t\t\t`Tool ${context.toolCall.name} exceeded ${Math.max(1, Math.round(context.elapsedMs / 1000))}s and continues as session task ${taskId}.`,\n\t\t\t\t\t\t\t\"Continue independent work. If its result is a dependency, call tool_task once with action=wait and this taskId; the wait is event-driven. Never poll.\",\n\t\t\t\t\t\t].join(\"\\n\"),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tdetails: { sessionId, taskId, status: \"running\" as const },\n\t\t\t},\n\t\t};\n\t}\n\n\tlist(): BackgroundToolTaskRecord[] {\n\t\treturn [...this.tasks.values()].map((state) => ({ ...state.record }));\n\t}\n\n\twait(taskId: string, signal?: AbortSignal): Promise<BackgroundToolTaskRecord> {\n\t\tconst state = this.tasks.get(taskId);\n\t\tif (!state) return Promise.reject(new Error(`Unknown background tool task: ${taskId}`));\n\t\tif (state.record.status !== \"running\") return Promise.resolve({ ...state.record });\n\t\tstate.waitingConsumers++;\n\t\tlet waiting = true;\n\t\tconst releaseWaiter = (): void => {\n\t\t\tif (!waiting) return;\n\t\t\twaiting = false;\n\t\t\tstate.waitingConsumers--;\n\t\t};\n\t\tif (!signal) {\n\t\t\treturn state.terminal.then((record) => {\n\t\t\t\treleaseWaiter();\n\t\t\t\treturn { ...record };\n\t\t\t});\n\t\t}\n\t\tif (signal.aborted) {\n\t\t\treleaseWaiter();\n\t\t\treturn Promise.reject(signal.reason ?? new Error(\"Operation aborted\"));\n\t\t}\n\t\treturn new Promise<BackgroundToolTaskRecord>((resolve, reject) => {\n\t\t\tconst onAbort = (): void => {\n\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\treleaseWaiter();\n\t\t\t\treject(signal.reason ?? new Error(\"Operation aborted\"));\n\t\t\t};\n\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tstate.terminal.then((record) => {\n\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\treleaseWaiter();\n\t\t\t\tresolve({ ...record });\n\t\t\t});\n\t\t});\n\t}\n\n\tcancel(taskId: string): boolean {\n\t\tconst state = this.tasks.get(taskId);\n\t\tif (!state || state.record.status !== \"running\") return false;\n\t\tstate.cancellationRequested = true;\n\t\tstate.record = { ...state.record, cancellationRequested: true };\n\t\ttry {\n\t\t\tstate.cancel();\n\t\t} catch (error) {\n\t\t\tthis.deps.onError?.(`Failed to cancel background tool task ${taskId}`, error);\n\t\t}\n\t\treturn true;\n\t}\n\n\tsubscribeHandoffRequest(toolCallId: string, request: () => void): () => void {\n\t\tif (this.disposed) return () => {};\n\t\tconst requests = this.handoffRequests.get(toolCallId) ?? new Set<() => void>();\n\t\trequests.add(request);\n\t\tthis.handoffRequests.set(toolCallId, requests);\n\t\treturn () => {\n\t\t\trequests.delete(request);\n\t\t\tif (requests.size === 0) this.handoffRequests.delete(toolCallId);\n\t\t};\n\t}\n\n\trequestHandoff(toolCallId?: string): number {\n\t\tif (this.disposed) return 0;\n\t\tconst requested = toolCallId\n\t\t\t? [...(this.handoffRequests.get(toolCallId) ?? [])]\n\t\t\t: [...this.handoffRequests.values()].flatMap((requests) => [...requests]);\n\t\tfor (const request of requested) request();\n\t\treturn requested.length;\n\t}\n\n\tasync waitForNotifications(): Promise<void> {\n\t\t// A just-resolved tool completion settles through its promise continuation before it can enqueue\n\t\t// the notification drain. Yield once so this event-driven barrier observes that enqueue.\n\t\tawait Promise.resolve();\n\t\tfor (;;) {\n\t\t\tconst drain = this.notificationDrain;\n\t\t\tif (!drain) return;\n\t\t\tawait drain;\n\t\t\tif (!this.notificationDrain && this.queuedNotifications.length === 0) return;\n\t\t}\n\t}\n\n\tasync shutdown(): Promise<void> {\n\t\tif (!this.disposed) {\n\t\t\tthis.disposed = true;\n\t\t\tthis.handoffRequests.clear();\n\t\t\tfor (const state of this.tasks.values()) {\n\t\t\t\tif (state.record.status !== \"running\") continue;\n\t\t\t\tstate.cancellationRequested = true;\n\t\t\t\ttry {\n\t\t\t\t\tstate.cancel();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.deps.onError?.(`Failed to cancel background tool task ${state.record.taskId}`, error);\n\t\t\t\t}\n\t\t\t\tthis.finishState(\n\t\t\t\t\tstate,\n\t\t\t\t\t\"canceled\",\n\t\t\t\t\t\"Session ended before the background tool completed.\",\n\t\t\t\t\tundefined,\n\t\t\t\t\tfalse,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tawait this.waitForNotifications();\n\t}\n\n\tprivate settle(state: BackgroundToolTaskState, completion: BackgroundToolCallCompletion): void {\n\t\tif (state.record.status !== \"running\") return;\n\t\tconst status = state.cancellationRequested ? \"canceled\" : completion.isError ? \"failed\" : \"completed\";\n\t\tconst output = renderCompletionOutput(completion);\n\t\tthis.finishState(state, status, output, completion.result.usage, true);\n\t}\n\n\tprivate settleRejected(state: BackgroundToolTaskState, error: unknown): void {\n\t\tif (state.record.status !== \"running\") return;\n\t\tconst status = state.cancellationRequested ? \"canceled\" : \"failed\";\n\t\tconst output = error instanceof Error ? error.message : String(error);\n\t\tthis.finishState(state, status, output, undefined, true);\n\t}\n\n\tprivate restorePersistedTasks(): void {\n\t\tconst load = this.deps.loadPersistedRecordsNewestFirst;\n\t\tif (!load) return;\n\t\tlet values: readonly unknown[];\n\t\ttry {\n\t\t\tvalues = load();\n\t\t} catch (error) {\n\t\t\tthis.deps.onError?.(\"Failed to load persisted background tool tasks\", error);\n\t\t\treturn;\n\t\t}\n\t\tconst sessionId = this.deps.getSessionId();\n\t\tconst seenTaskIds = new Set<string>();\n\t\tconst latestRecords: BackgroundToolTaskRecord[] = [];\n\t\tlet highestTaskNumber = 0;\n\t\tfor (const value of values) {\n\t\t\tif (!isPlainRecord(value) || value.sessionId !== sessionId || typeof value.taskId !== \"string\") continue;\n\t\t\tconst numericTaskId = taskNumber(value.taskId);\n\t\t\tif (numericTaskId === undefined) continue;\n\t\t\thighestTaskNumber = Math.max(highestTaskNumber, numericTaskId);\n\t\t\tif (seenTaskIds.has(value.taskId)) continue;\n\t\t\tseenTaskIds.add(value.taskId);\n\t\t\tconst record = decodeRecord(value, sessionId);\n\t\t\tif (record) latestRecords.push(record);\n\t\t}\n\t\tthis.nextTaskId = highestTaskNumber + 1;\n\t\tlatestRecords.sort((left, right) => taskNumber(left.taskId)! - taskNumber(right.taskId)!);\n\t\tfor (const record of latestRecords) {\n\t\t\tconst state = this.createState(record, () => {});\n\t\t\tthis.tasks.set(record.taskId, state);\n\t\t\tif (record.status !== \"running\") {\n\t\t\t\tstate.resolveTerminal(record);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis.finishState(\n\t\t\t\tstate,\n\t\t\t\t\"failed\",\n\t\t\t\t\"The session resumed after the owning process ended; the original tool completion is unavailable.\",\n\t\t\t\tundefined,\n\t\t\t\tfalse,\n\t\t\t);\n\t\t}\n\t\tthis.pruneTerminalTasks();\n\t\tthis.emitLiveTasks();\n\t}\n\n\tprivate createState(record: BackgroundToolTaskRecord, cancel: () => void): BackgroundToolTaskState {\n\t\tlet resolveTerminal: ((terminalRecord: BackgroundToolTaskRecord) => void) | undefined;\n\t\tconst terminal = new Promise<BackgroundToolTaskRecord>((resolve) => {\n\t\t\tresolveTerminal = resolve;\n\t\t});\n\t\treturn {\n\t\t\trecord: { ...record },\n\t\t\tcancel,\n\t\t\tcancellationRequested: record.cancellationRequested ?? false,\n\t\t\twaitingConsumers: 0,\n\t\t\tterminal,\n\t\t\tresolveTerminal: resolveTerminal!,\n\t\t\tartifactHolderId: `background-tool-task:${record.sessionId}:${record.taskId}`,\n\t\t};\n\t}\n\n\tprivate finishState(\n\t\tstate: BackgroundToolTaskState,\n\t\tstatus: Exclude<BackgroundToolTaskStatus, \"running\">,\n\t\trawOutput: string,\n\t\tusage: Usage | undefined,\n\t\tnotify: boolean,\n\t): void {\n\t\tconst packed = packToolOutput(\n\t\t\t{\n\t\t\t\ttoolName: state.record.toolName,\n\t\t\t\trawContent: rawOutput,\n\t\t\t\tsessionEntryId: state.record.taskId,\n\t\t\t\tcreatedAtTurn: 0,\n\t\t\t\treproducible: false,\n\t\t\t\ttruncation: { maxBytes: MAX_INLINE_OUTPUT_BYTES, maxLines: MAX_INLINE_OUTPUT_LINES },\n\t\t\t},\n\t\t\tthis.deps.getArtifactStore(),\n\t\t\tstate.artifactHolderId,\n\t\t);\n\t\tconst output = packed.artifactId\n\t\t\t? `${packed.content}\\n\\n[${formatArtifactNotice(packed.artifactId)}]`\n\t\t\t: packed.content;\n\t\tconst record: BackgroundToolTaskRecord = {\n\t\t\t...state.record,\n\t\t\tstatus,\n\t\t\tcompletedAt: this.now().toISOString(),\n\t\t\tsummary: summaryFor(status, state.record.toolName, output),\n\t\t\toutput,\n\t\t\t...(packed.artifactId ? { artifactId: packed.artifactId } : {}),\n\t\t\t...(usage ? { usage } : {}),\n\t\t\t...(state.cancellationRequested ? { cancellationRequested: true } : {}),\n\t\t};\n\t\tstate.record = record;\n\t\tthis.persist(record);\n\t\tif (usage) this.deps.recordUsage?.(record.taskId, usage);\n\t\tstate.resolveTerminal(record);\n\t\tthis.emitLiveTasks();\n\t\tthis.pruneTerminalTasks();\n\t\tif (notify) this.notify(record, state.waitingConsumers === 0);\n\t}\n\n\tprivate persist(record: BackgroundToolTaskRecord): boolean {\n\t\ttry {\n\t\t\tthis.deps.persist({ ...record });\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tthis.deps.onError?.(`Failed to persist background tool task ${record.taskId}`, error);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprivate notify(record: BackgroundToolTaskRecord, wakeParent: boolean): void {\n\t\tthis.queuedNotifications.push({ record: { ...record }, wakeParent });\n\t\tthis.scheduleNotificationDrain();\n\t}\n\n\tprivate scheduleNotificationDrain(): void {\n\t\tif (this.notificationDrain) return;\n\t\tthis.notificationDrain = this.drainNotifications().finally(() => {\n\t\t\tthis.notificationDrain = undefined;\n\t\t\tif (this.queuedNotifications.length > 0) this.scheduleNotificationDrain();\n\t\t});\n\t}\n\n\tprivate async drainNotifications(): Promise<void> {\n\t\t// Allow completions released by the same event to reach this queue before forming the batch.\n\t\tawait Promise.resolve();\n\t\twhile (this.queuedNotifications.length > 0) {\n\t\t\tawait Promise.resolve();\n\t\t\tconst batch = this.queuedNotifications.splice(0);\n\t\t\tconst records = batch.map((notification) => notification.record);\n\t\t\ttry {\n\t\t\t\tawait this.deps.notifyTerminal(records, {\n\t\t\t\t\twakeParent: batch.some((notification) => notification.wakeParent),\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tconst includedIds = records.slice(0, MAX_TERMINAL_HANDOFF_RECORDS).map((record) => record.taskId);\n\t\t\t\tconst omitted = records.length - includedIds.length;\n\t\t\t\tconst suffix = omitted > 0 ? ` (+${omitted} more)` : \"\";\n\t\t\t\tthis.deps.onError?.(\n\t\t\t\t\t`Failed to notify terminal background tool task batch ${includedIds.join(\", \")}${suffix}`,\n\t\t\t\t\terror,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate emitLiveTasks(): void {\n\t\tconst tasks = [...this.tasks.values()]\n\t\t\t.filter((state) => state.record.status === \"running\")\n\t\t\t.map((state) => ({\n\t\t\t\ttaskId: state.record.taskId,\n\t\t\t\ttoolCallId: state.record.toolCallId,\n\t\t\t\ttoolName: state.record.toolName,\n\t\t\t\tdescription: state.record.summary,\n\t\t\t}));\n\t\ttry {\n\t\t\tthis.deps.onLiveTasksChanged?.(tasks);\n\t\t} catch (error) {\n\t\t\tthis.deps.onError?.(\"Failed to emit background tool task level signal\", error);\n\t\t}\n\t}\n\n\tprivate pruneTerminalTasks(): void {\n\t\tconst terminal = [...this.tasks.values()].filter((state) => state.record.status !== \"running\");\n\t\tfor (const state of terminal.slice(0, Math.max(0, terminal.length - MAX_RETAINED_TERMINAL_TASKS))) {\n\t\t\tthis.tasks.delete(state.record.taskId);\n\t\t\tif (!state.record.artifactId) continue;\n\t\t\tconst store = this.deps.getArtifactStore();\n\t\t\tstore?.removeReference(state.record.artifactId, state.artifactHolderId);\n\t\t\tstore?.cleanup();\n\t\t}\n\t}\n\n\tprivate now(): Date {\n\t\treturn this.deps.now?.() ?? new Date();\n\t}\n}\n"]}
1
+ {"version":3,"file":"background-tool-task-controller.js","sourceRoot":"","sources":["../../src/core/background-tool-task-controller.ts"],"names":[],"mappings":"AAQA,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AACvF,OA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B,EAAE,CAAC;YAC3C,KAAK,EAAE,eAAe,CAAC,KAAK,CAAC,MAAM,CAAC,UAAU,EAAE,KAAK,CAAC,gBAAgB,CAAC,CAAC;YACxE,KAAK,EAAE,OAAO,EAAE,CAAC;QAClB,CAAC;IACF,CAAC;IAEO,GAAG;QACV,OAAO,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,EAAE,IAAI,IAAI,IAAI,EAAE,CAAC;IACxC,CAAC;CACD","sourcesContent":["import type {\n\tBackgroundToolCallCompletion,\n\tBackgroundToolCallContext,\n\tBackgroundToolCallHandoff,\n} from \"@caupulican/pi-agent-core\";\nimport type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport type { Usage } from \"@caupulican/pi-ai\";\nimport type { ArtifactStore } from \"./context/context-artifacts.ts\";\nimport { formatArtifactNotice, packToolOutput } from \"./context/tool-output-packer.ts\";\nimport { hasOnlyKeys, isPlainRecord } from \"./util/value-guards.ts\";\n\nexport const DEFAULT_BACKGROUND_TOOL_CALL_AFTER_MS = 15_000;\nexport const BACKGROUND_TOOL_TASK_CUSTOM_TYPE = \"background_tool_task\";\n\nconst MAX_RETAINED_TERMINAL_TASKS = 64;\nconst MAX_INLINE_OUTPUT_BYTES = 32 * 1024;\nconst MAX_INLINE_OUTPUT_LINES = 400;\nconst MAX_SUMMARY_CHARS = 200;\nconst MAX_TERMINAL_HANDOFF_RECORDS = 8;\nconst TASK_ID_PATTERN = /^tool-task-([1-9]\\d*)$/;\nconst RECORD_KEYS = [\n\t\"sessionId\",\n\t\"taskId\",\n\t\"toolCallId\",\n\t\"toolName\",\n\t\"status\",\n\t\"startedAt\",\n\t\"completedAt\",\n\t\"elapsedBeforeHandoffMs\",\n\t\"summary\",\n\t\"output\",\n\t\"artifactId\",\n\t\"usage\",\n\t\"cancellationRequested\",\n] as const;\n\nexport type BackgroundToolTaskStatus = \"running\" | \"completed\" | \"failed\" | \"canceled\";\n\nexport interface BackgroundToolTaskRecord {\n\tsessionId: string;\n\ttaskId: string;\n\ttoolCallId: string;\n\ttoolName: string;\n\tstatus: BackgroundToolTaskStatus;\n\tstartedAt: string;\n\tcompletedAt?: string;\n\telapsedBeforeHandoffMs: number;\n\tsummary: string;\n\toutput: string;\n\tartifactId?: string;\n\tusage?: Usage;\n\tcancellationRequested?: boolean;\n}\n\nexport interface BackgroundToolTaskLiveView {\n\ttaskId: string;\n\ttoolCallId: string;\n\ttoolName: string;\n\tdescription: string;\n}\n\nexport interface BackgroundToolTerminalMessage {\n\tcustomType: \"background-tool-completion\";\n\tcontent: string;\n\tdisplay: true;\n\tdetails: {\n\t\trecords: Array<{\n\t\t\ttaskId: string;\n\t\t\tstatus: BackgroundToolTaskStatus;\n\t\t\ttoolName: string;\n\t\t\tartifactId?: string;\n\t\t}>;\n\t};\n}\n\nexport interface BackgroundToolTaskControllerDeps {\n\tgetSessionId(): string;\n\tgetArtifactStore(): ArtifactStore | undefined;\n\t/** Durable task records on the active branch, newest first, without rebuilding full model context. */\n\tloadPersistedRecordsNewestFirst?(): readonly unknown[];\n\tpersist(record: BackgroundToolTaskRecord): void;\n\tnotifyTerminal(records: readonly BackgroundToolTaskRecord[], options: { wakeParent: boolean }): Promise<void> | void;\n\tonLiveTasksChanged?(tasks: readonly BackgroundToolTaskLiveView[]): void;\n\trecordUsage?(taskId: string, usage: Usage): void;\n\tonError?(message: string, error: unknown): void;\n\tnow?(): Date;\n}\n\ninterface BackgroundToolTaskState {\n\trecord: BackgroundToolTaskRecord;\n\tcancel: () => void;\n\tcancellationRequested: boolean;\n\twaitingConsumers: number;\n\tterminal: Promise<BackgroundToolTaskRecord>;\n\tresolveTerminal: (record: BackgroundToolTaskRecord) => void;\n\tartifactHolderId: string;\n}\n\n/** Read only task records on the active branch without allocating or hydrating the full branch context. */\nexport function loadBackgroundToolTaskRecordsNewestFirst(\n\tsessionManager: Pick<SessionManager, \"getLatestCustomEntryOnBranch\">,\n): unknown[] {\n\tconst records: unknown[] = [];\n\tlet fromId: string | undefined;\n\tfor (;;) {\n\t\tconst entry = sessionManager.getLatestCustomEntryOnBranch(BACKGROUND_TOOL_TASK_CUSTOM_TYPE, fromId);\n\t\tif (!entry) return records;\n\t\trecords.push(entry.data);\n\t\tif (entry.parentId === null) return records;\n\t\tfromId = entry.parentId;\n\t}\n}\n\nexport function createBackgroundToolTerminalMessage(\n\trecords: readonly BackgroundToolTaskRecord[],\n): BackgroundToolTerminalMessage {\n\tif (records.length === 0) throw new TypeError(\"Background tool terminal handoff requires at least one record\");\n\tconst included = records.slice(0, MAX_TERMINAL_HANDOFF_RECORDS);\n\tconst omitted = records.length - included.length;\n\treturn {\n\t\tcustomType: \"background-tool-completion\",\n\t\tcontent: [\n\t\t\t\"Background tool terminal handoff:\",\n\t\t\t...included.map((record) => `- ${record.taskId}: ${record.status} tool=${record.toolName}`),\n\t\t\t...(omitted > 0 ? [`- ${omitted} additional terminal tool task(s) omitted.`] : []),\n\t\t\t\"Parent woke. Need result: tool_task action=wait once; never poll.\",\n\t\t].join(\"\\n\"),\n\t\tdisplay: true,\n\t\tdetails: {\n\t\t\trecords: included.map((record) => ({\n\t\t\t\ttaskId: record.taskId,\n\t\t\t\tstatus: record.status,\n\t\t\t\ttoolName: record.toolName,\n\t\t\t\t...(record.artifactId ? { artifactId: record.artifactId } : {}),\n\t\t\t})),\n\t\t},\n\t};\n}\n\nfunction renderCompletionOutput(completion: BackgroundToolCallCompletion): string {\n\tconst blocks = completion.result.content.map((block) =>\n\t\tblock.type === \"text\" ? block.text : \"[Image output retained outside the foreground transcript]\",\n\t);\n\treturn blocks.join(\"\\n\") || \"Tool completed without text output.\";\n}\n\nfunction oneLine(value: string): string {\n\treturn value\n\t\t.replace(/[\\r\\n]+/g, \" \")\n\t\t.replace(/\\s+/g, \" \")\n\t\t.trim();\n}\n\nfunction summaryFor(status: BackgroundToolTaskStatus, toolName: string, output: string): string {\n\tconst prefix = `${toolName} ${status}`;\n\tconst firstLine = oneLine(output);\n\tif (!firstLine) return prefix;\n\tconst remaining = Math.max(0, MAX_SUMMARY_CHARS - prefix.length - 2);\n\treturn `${prefix}: ${firstLine.slice(0, remaining)}`;\n}\n\nfunction taskNumber(taskId: string): number | undefined {\n\tconst match = TASK_ID_PATTERN.exec(taskId);\n\tif (!match) return undefined;\n\tconst value = Number(match[1]);\n\treturn Number.isSafeInteger(value) && value > 0 ? value : undefined;\n}\n\nfunction cloneUsage(value: unknown): Usage | undefined {\n\tif (!isPlainRecord(value)) return undefined;\n\tconst cost = value.cost;\n\tif (!isPlainRecord(cost)) return undefined;\n\tconst fields = [\"input\", \"output\", \"cacheRead\", \"cacheWrite\", \"totalTokens\"] as const;\n\tconst costFields = [\"input\", \"output\", \"cacheRead\", \"cacheWrite\", \"total\"] as const;\n\tif (\n\t\tfields.some((field) => typeof value[field] !== \"number\" || !Number.isFinite(value[field])) ||\n\t\tcostFields.some((field) => typeof cost[field] !== \"number\" || !Number.isFinite(cost[field]))\n\t) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\tinput: value.input as number,\n\t\toutput: value.output as number,\n\t\tcacheRead: value.cacheRead as number,\n\t\tcacheWrite: value.cacheWrite as number,\n\t\ttotalTokens: value.totalTokens as number,\n\t\tcost: {\n\t\t\tinput: cost.input as number,\n\t\t\toutput: cost.output as number,\n\t\t\tcacheRead: cost.cacheRead as number,\n\t\t\tcacheWrite: cost.cacheWrite as number,\n\t\t\ttotal: cost.total as number,\n\t\t},\n\t};\n}\n\nfunction decodeRecord(value: unknown, sessionId: string): BackgroundToolTaskRecord | undefined {\n\tif (!isPlainRecord(value) || !hasOnlyKeys(value, RECORD_KEYS)) return undefined;\n\tif (\n\t\tvalue.sessionId !== sessionId ||\n\t\ttypeof value.taskId !== \"string\" ||\n\t\ttaskNumber(value.taskId) === undefined ||\n\t\ttypeof value.toolCallId !== \"string\" ||\n\t\tvalue.toolCallId.length === 0 ||\n\t\ttypeof value.toolName !== \"string\" ||\n\t\tvalue.toolName.length === 0 ||\n\t\t(value.status !== \"running\" &&\n\t\t\tvalue.status !== \"completed\" &&\n\t\t\tvalue.status !== \"failed\" &&\n\t\t\tvalue.status !== \"canceled\") ||\n\t\ttypeof value.startedAt !== \"string\" ||\n\t\t!Number.isFinite(Date.parse(value.startedAt)) ||\n\t\t(value.completedAt !== undefined &&\n\t\t\t(typeof value.completedAt !== \"string\" || !Number.isFinite(Date.parse(value.completedAt)))) ||\n\t\t(value.status !== \"running\" && value.completedAt === undefined) ||\n\t\ttypeof value.elapsedBeforeHandoffMs !== \"number\" ||\n\t\t!Number.isFinite(value.elapsedBeforeHandoffMs) ||\n\t\tvalue.elapsedBeforeHandoffMs < 0 ||\n\t\ttypeof value.summary !== \"string\" ||\n\t\ttypeof value.output !== \"string\" ||\n\t\t(value.artifactId !== undefined &&\n\t\t\t(typeof value.artifactId !== \"string\" || !/^[0-9a-f]{1,64}$/.test(value.artifactId))) ||\n\t\t(value.cancellationRequested !== undefined && typeof value.cancellationRequested !== \"boolean\")\n\t) {\n\t\treturn undefined;\n\t}\n\tconst usage = value.usage === undefined ? undefined : cloneUsage(value.usage);\n\tif (value.usage !== undefined && !usage) return undefined;\n\treturn {\n\t\tsessionId,\n\t\ttaskId: value.taskId,\n\t\ttoolCallId: value.toolCallId,\n\t\ttoolName: value.toolName,\n\t\tstatus: value.status,\n\t\tstartedAt: value.startedAt,\n\t\t...(value.completedAt ? { completedAt: value.completedAt } : {}),\n\t\telapsedBeforeHandoffMs: value.elapsedBeforeHandoffMs,\n\t\tsummary: value.summary,\n\t\toutput: value.output,\n\t\t...(value.artifactId ? { artifactId: value.artifactId } : {}),\n\t\t...(usage ? { usage } : {}),\n\t\t...(value.cancellationRequested !== undefined ? { cancellationRequested: value.cancellationRequested } : {}),\n\t};\n}\n\n/**\n * Session-owned registry for foreground tool calls transferred into background execution.\n * It emits edge records for durability and a replace-style live-task signal for UI consumers.\n */\nexport class BackgroundToolTaskController {\n\tprivate readonly deps: BackgroundToolTaskControllerDeps;\n\tprivate readonly tasks = new Map<string, BackgroundToolTaskState>();\n\tprivate readonly handoffRequests = new Map<string, Set<() => void>>();\n\tprivate readonly queuedNotifications: Array<{ record: BackgroundToolTaskRecord; wakeParent: boolean }> = [];\n\tprivate notificationDrain: Promise<void> | undefined;\n\tprivate nextTaskId = 1;\n\tprivate disposed = false;\n\n\tconstructor(deps: BackgroundToolTaskControllerDeps) {\n\t\tthis.deps = deps;\n\t\tthis.restorePersistedTasks();\n\t}\n\n\thandoff(context: BackgroundToolCallContext): BackgroundToolCallHandoff | undefined {\n\t\tif (this.disposed || context.toolCall.name === \"tool_task\") return undefined;\n\t\tconst sessionId = this.deps.getSessionId();\n\t\tconst taskId = `tool-task-${this.nextTaskId++}`;\n\t\tconst startedAt = this.now().toISOString();\n\t\tconst record: BackgroundToolTaskRecord = {\n\t\t\tsessionId,\n\t\t\ttaskId,\n\t\t\ttoolCallId: context.toolCall.id,\n\t\t\ttoolName: context.toolCall.name,\n\t\t\tstatus: \"running\",\n\t\t\tstartedAt,\n\t\t\telapsedBeforeHandoffMs: context.elapsedMs,\n\t\t\tsummary: `${context.toolCall.name} running in the background`,\n\t\t\toutput: \"\",\n\t\t};\n\t\tconst state = this.createState(record, context.cancel);\n\t\tthis.tasks.set(taskId, state);\n\t\tif (!this.persist(record)) {\n\t\t\tthis.tasks.delete(taskId);\n\t\t\treturn undefined;\n\t\t}\n\t\tthis.emitLiveTasks();\n\t\tcontext.completion.then(\n\t\t\t(completion) => this.settle(state, completion),\n\t\t\t(error) => this.settleRejected(state, error),\n\t\t);\n\n\t\treturn {\n\t\t\tresult: {\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: [\n\t\t\t\t\t\t\t`Tool ${context.toolCall.name} exceeded ${Math.max(1, Math.round(context.elapsedMs / 1000))}s; running as session task ${taskId}.`,\n\t\t\t\t\t\t\t\"Continue independent work. Dependency: tool_task action=wait once with taskId; event-driven, never poll.\",\n\t\t\t\t\t\t].join(\"\\n\"),\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tdetails: { sessionId, taskId, status: \"running\" as const },\n\t\t\t},\n\t\t};\n\t}\n\n\tlist(): BackgroundToolTaskRecord[] {\n\t\treturn [...this.tasks.values()].map((state) => ({ ...state.record }));\n\t}\n\n\twait(taskId: string, signal?: AbortSignal): Promise<BackgroundToolTaskRecord> {\n\t\tconst state = this.tasks.get(taskId);\n\t\tif (!state) return Promise.reject(new Error(`Unknown background tool task: ${taskId}`));\n\t\tif (state.record.status !== \"running\") return Promise.resolve({ ...state.record });\n\t\tstate.waitingConsumers++;\n\t\tlet waiting = true;\n\t\tconst releaseWaiter = (): void => {\n\t\t\tif (!waiting) return;\n\t\t\twaiting = false;\n\t\t\tstate.waitingConsumers--;\n\t\t};\n\t\tif (!signal) {\n\t\t\treturn state.terminal.then((record) => {\n\t\t\t\treleaseWaiter();\n\t\t\t\treturn { ...record };\n\t\t\t});\n\t\t}\n\t\tif (signal.aborted) {\n\t\t\treleaseWaiter();\n\t\t\treturn Promise.reject(signal.reason ?? new Error(\"Operation aborted\"));\n\t\t}\n\t\treturn new Promise<BackgroundToolTaskRecord>((resolve, reject) => {\n\t\t\tconst onAbort = (): void => {\n\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\treleaseWaiter();\n\t\t\t\treject(signal.reason ?? new Error(\"Operation aborted\"));\n\t\t\t};\n\t\t\tsignal.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tstate.terminal.then((record) => {\n\t\t\t\tsignal.removeEventListener(\"abort\", onAbort);\n\t\t\t\treleaseWaiter();\n\t\t\t\tresolve({ ...record });\n\t\t\t});\n\t\t});\n\t}\n\n\tcancel(taskId: string): boolean {\n\t\tconst state = this.tasks.get(taskId);\n\t\tif (!state || state.record.status !== \"running\") return false;\n\t\tstate.cancellationRequested = true;\n\t\tstate.record = { ...state.record, cancellationRequested: true };\n\t\ttry {\n\t\t\tstate.cancel();\n\t\t} catch (error) {\n\t\t\tthis.deps.onError?.(`Failed to cancel background tool task ${taskId}`, error);\n\t\t}\n\t\treturn true;\n\t}\n\n\tsubscribeHandoffRequest(toolCallId: string, request: () => void): () => void {\n\t\tif (this.disposed) return () => {};\n\t\tconst requests = this.handoffRequests.get(toolCallId) ?? new Set<() => void>();\n\t\trequests.add(request);\n\t\tthis.handoffRequests.set(toolCallId, requests);\n\t\treturn () => {\n\t\t\trequests.delete(request);\n\t\t\tif (requests.size === 0) this.handoffRequests.delete(toolCallId);\n\t\t};\n\t}\n\n\trequestHandoff(toolCallId?: string): number {\n\t\tif (this.disposed) return 0;\n\t\tconst requested = toolCallId\n\t\t\t? [...(this.handoffRequests.get(toolCallId) ?? [])]\n\t\t\t: [...this.handoffRequests.values()].flatMap((requests) => [...requests]);\n\t\tfor (const request of requested) request();\n\t\treturn requested.length;\n\t}\n\n\tasync waitForNotifications(): Promise<void> {\n\t\t// A just-resolved tool completion settles through its promise continuation before it can enqueue\n\t\t// the notification drain. Yield once so this event-driven barrier observes that enqueue.\n\t\tawait Promise.resolve();\n\t\tfor (;;) {\n\t\t\tconst drain = this.notificationDrain;\n\t\t\tif (!drain) return;\n\t\t\tawait drain;\n\t\t\tif (!this.notificationDrain && this.queuedNotifications.length === 0) return;\n\t\t}\n\t}\n\n\tasync shutdown(): Promise<void> {\n\t\tif (!this.disposed) {\n\t\t\tthis.disposed = true;\n\t\t\tthis.handoffRequests.clear();\n\t\t\tfor (const state of this.tasks.values()) {\n\t\t\t\tif (state.record.status !== \"running\") continue;\n\t\t\t\tstate.cancellationRequested = true;\n\t\t\t\ttry {\n\t\t\t\t\tstate.cancel();\n\t\t\t\t} catch (error) {\n\t\t\t\t\tthis.deps.onError?.(`Failed to cancel background tool task ${state.record.taskId}`, error);\n\t\t\t\t}\n\t\t\t\tthis.finishState(\n\t\t\t\t\tstate,\n\t\t\t\t\t\"canceled\",\n\t\t\t\t\t\"Session ended before the background tool completed.\",\n\t\t\t\t\tundefined,\n\t\t\t\t\tfalse,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tawait this.waitForNotifications();\n\t}\n\n\tprivate settle(state: BackgroundToolTaskState, completion: BackgroundToolCallCompletion): void {\n\t\tif (state.record.status !== \"running\") return;\n\t\tconst status = state.cancellationRequested ? \"canceled\" : completion.isError ? \"failed\" : \"completed\";\n\t\tconst output = renderCompletionOutput(completion);\n\t\tthis.finishState(state, status, output, completion.result.usage, true);\n\t}\n\n\tprivate settleRejected(state: BackgroundToolTaskState, error: unknown): void {\n\t\tif (state.record.status !== \"running\") return;\n\t\tconst status = state.cancellationRequested ? \"canceled\" : \"failed\";\n\t\tconst output = error instanceof Error ? error.message : String(error);\n\t\tthis.finishState(state, status, output, undefined, true);\n\t}\n\n\tprivate restorePersistedTasks(): void {\n\t\tconst load = this.deps.loadPersistedRecordsNewestFirst;\n\t\tif (!load) return;\n\t\tlet values: readonly unknown[];\n\t\ttry {\n\t\t\tvalues = load();\n\t\t} catch (error) {\n\t\t\tthis.deps.onError?.(\"Failed to load persisted background tool tasks\", error);\n\t\t\treturn;\n\t\t}\n\t\tconst sessionId = this.deps.getSessionId();\n\t\tconst seenTaskIds = new Set<string>();\n\t\tconst latestRecords: BackgroundToolTaskRecord[] = [];\n\t\tlet highestTaskNumber = 0;\n\t\tfor (const value of values) {\n\t\t\tif (!isPlainRecord(value) || value.sessionId !== sessionId || typeof value.taskId !== \"string\") continue;\n\t\t\tconst numericTaskId = taskNumber(value.taskId);\n\t\t\tif (numericTaskId === undefined) continue;\n\t\t\thighestTaskNumber = Math.max(highestTaskNumber, numericTaskId);\n\t\t\tif (seenTaskIds.has(value.taskId)) continue;\n\t\t\tseenTaskIds.add(value.taskId);\n\t\t\tconst record = decodeRecord(value, sessionId);\n\t\t\tif (record) latestRecords.push(record);\n\t\t}\n\t\tthis.nextTaskId = highestTaskNumber + 1;\n\t\tlatestRecords.sort((left, right) => taskNumber(left.taskId)! - taskNumber(right.taskId)!);\n\t\tfor (const record of latestRecords) {\n\t\t\tconst state = this.createState(record, () => {});\n\t\t\tthis.tasks.set(record.taskId, state);\n\t\t\tif (record.status !== \"running\") {\n\t\t\t\tstate.resolveTerminal(record);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tthis.finishState(\n\t\t\t\tstate,\n\t\t\t\t\"failed\",\n\t\t\t\t\"The session resumed after the owning process ended; the original tool completion is unavailable.\",\n\t\t\t\tundefined,\n\t\t\t\tfalse,\n\t\t\t);\n\t\t}\n\t\tthis.pruneTerminalTasks();\n\t\tthis.emitLiveTasks();\n\t}\n\n\tprivate createState(record: BackgroundToolTaskRecord, cancel: () => void): BackgroundToolTaskState {\n\t\tlet resolveTerminal: ((terminalRecord: BackgroundToolTaskRecord) => void) | undefined;\n\t\tconst terminal = new Promise<BackgroundToolTaskRecord>((resolve) => {\n\t\t\tresolveTerminal = resolve;\n\t\t});\n\t\treturn {\n\t\t\trecord: { ...record },\n\t\t\tcancel,\n\t\t\tcancellationRequested: record.cancellationRequested ?? false,\n\t\t\twaitingConsumers: 0,\n\t\t\tterminal,\n\t\t\tresolveTerminal: resolveTerminal!,\n\t\t\tartifactHolderId: `background-tool-task:${record.sessionId}:${record.taskId}`,\n\t\t};\n\t}\n\n\tprivate finishState(\n\t\tstate: BackgroundToolTaskState,\n\t\tstatus: Exclude<BackgroundToolTaskStatus, \"running\">,\n\t\trawOutput: string,\n\t\tusage: Usage | undefined,\n\t\tnotify: boolean,\n\t): void {\n\t\tconst packed = packToolOutput(\n\t\t\t{\n\t\t\t\ttoolName: state.record.toolName,\n\t\t\t\trawContent: rawOutput,\n\t\t\t\tsessionEntryId: state.record.taskId,\n\t\t\t\tcreatedAtTurn: 0,\n\t\t\t\treproducible: false,\n\t\t\t\ttruncation: { maxBytes: MAX_INLINE_OUTPUT_BYTES, maxLines: MAX_INLINE_OUTPUT_LINES },\n\t\t\t},\n\t\t\tthis.deps.getArtifactStore(),\n\t\t\tstate.artifactHolderId,\n\t\t);\n\t\tconst output = packed.artifactId\n\t\t\t? `${packed.content}\\n\\n[${formatArtifactNotice(packed.artifactId)}]`\n\t\t\t: packed.content;\n\t\tconst record: BackgroundToolTaskRecord = {\n\t\t\t...state.record,\n\t\t\tstatus,\n\t\t\tcompletedAt: this.now().toISOString(),\n\t\t\tsummary: summaryFor(status, state.record.toolName, output),\n\t\t\toutput,\n\t\t\t...(packed.artifactId ? { artifactId: packed.artifactId } : {}),\n\t\t\t...(usage ? { usage } : {}),\n\t\t\t...(state.cancellationRequested ? { cancellationRequested: true } : {}),\n\t\t};\n\t\tstate.record = record;\n\t\tthis.persist(record);\n\t\tif (usage) this.deps.recordUsage?.(record.taskId, usage);\n\t\tstate.resolveTerminal(record);\n\t\tthis.emitLiveTasks();\n\t\tthis.pruneTerminalTasks();\n\t\tif (notify) this.notify(record, state.waitingConsumers === 0);\n\t}\n\n\tprivate persist(record: BackgroundToolTaskRecord): boolean {\n\t\ttry {\n\t\t\tthis.deps.persist({ ...record });\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tthis.deps.onError?.(`Failed to persist background tool task ${record.taskId}`, error);\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprivate notify(record: BackgroundToolTaskRecord, wakeParent: boolean): void {\n\t\tthis.queuedNotifications.push({ record: { ...record }, wakeParent });\n\t\tthis.scheduleNotificationDrain();\n\t}\n\n\tprivate scheduleNotificationDrain(): void {\n\t\tif (this.notificationDrain) return;\n\t\tthis.notificationDrain = this.drainNotifications().finally(() => {\n\t\t\tthis.notificationDrain = undefined;\n\t\t\tif (this.queuedNotifications.length > 0) this.scheduleNotificationDrain();\n\t\t});\n\t}\n\n\tprivate async drainNotifications(): Promise<void> {\n\t\t// Allow completions released by the same event to reach this queue before forming the batch.\n\t\tawait Promise.resolve();\n\t\twhile (this.queuedNotifications.length > 0) {\n\t\t\tawait Promise.resolve();\n\t\t\tconst batch = this.queuedNotifications.splice(0);\n\t\t\tconst records = batch.map((notification) => notification.record);\n\t\t\ttry {\n\t\t\t\tawait this.deps.notifyTerminal(records, {\n\t\t\t\t\twakeParent: batch.some((notification) => notification.wakeParent),\n\t\t\t\t});\n\t\t\t} catch (error) {\n\t\t\t\tconst includedIds = records.slice(0, MAX_TERMINAL_HANDOFF_RECORDS).map((record) => record.taskId);\n\t\t\t\tconst omitted = records.length - includedIds.length;\n\t\t\t\tconst suffix = omitted > 0 ? ` (+${omitted} more)` : \"\";\n\t\t\t\tthis.deps.onError?.(\n\t\t\t\t\t`Failed to notify terminal background tool task batch ${includedIds.join(\", \")}${suffix}`,\n\t\t\t\t\terror,\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate emitLiveTasks(): void {\n\t\tconst tasks = [...this.tasks.values()]\n\t\t\t.filter((state) => state.record.status === \"running\")\n\t\t\t.map((state) => ({\n\t\t\t\ttaskId: state.record.taskId,\n\t\t\t\ttoolCallId: state.record.toolCallId,\n\t\t\t\ttoolName: state.record.toolName,\n\t\t\t\tdescription: state.record.summary,\n\t\t\t}));\n\t\ttry {\n\t\t\tthis.deps.onLiveTasksChanged?.(tasks);\n\t\t} catch (error) {\n\t\t\tthis.deps.onError?.(\"Failed to emit background tool task level signal\", error);\n\t\t}\n\t}\n\n\tprivate pruneTerminalTasks(): void {\n\t\tconst terminal = [...this.tasks.values()].filter((state) => state.record.status !== \"running\");\n\t\tfor (const state of terminal.slice(0, Math.max(0, terminal.length - MAX_RETAINED_TERMINAL_TASKS))) {\n\t\t\tthis.tasks.delete(state.record.taskId);\n\t\t\tif (!state.record.artifactId) continue;\n\t\t\tconst store = this.deps.getArtifactStore();\n\t\t\tstore?.removeReference(state.record.artifactId, state.artifactHolderId);\n\t\t\tstore?.cleanup();\n\t\t}\n\t}\n\n\tprivate now(): Date {\n\t\treturn this.deps.now?.() ?? new Date();\n\t}\n}\n"]}
@@ -7,6 +7,26 @@ import type { ExtensionRunner } from "./extensions/index.ts";
7
7
  import type { FailureCorpusRecorder } from "./failure-corpus.ts";
8
8
  import type { SettingsManager } from "./settings-manager.ts";
9
9
  export type AutoCompactionReason = "overflow" | "threshold";
10
+ export interface ProviderRequestCompactionInput {
11
+ requestTokens: number;
12
+ nonCompactableTokens: number;
13
+ attempt: number;
14
+ }
15
+ export type ProviderRequestCompactionDecision = {
16
+ action: "send";
17
+ } | {
18
+ action: "replan";
19
+ };
20
+ interface AutoCompactionRunOptions {
21
+ initialTokens?: number;
22
+ singlePass?: boolean;
23
+ allowTrailingCompactionAsPrevious?: boolean;
24
+ forceDeterministic?: boolean;
25
+ recordThresholdFrontier?: boolean;
26
+ }
27
+ export declare class ProviderRequestEnvelopeOverflowError extends Error {
28
+ constructor(message: string);
29
+ }
10
30
  type CompactionControllerEvent = {
11
31
  type: "compaction_start";
12
32
  reason: "manual" | AutoCompactionReason;
@@ -80,13 +100,13 @@ export declare class CompactionController {
80
100
  private buildCompactionInstructions;
81
101
  isRunning(): boolean;
82
102
  resetOverflowRecovery(): void;
103
+ admitProviderRequest(input: ProviderRequestCompactionInput): Promise<ProviderRequestCompactionDecision>;
83
104
  abort(): void;
84
105
  checkContextWindowUsageWarning(): void;
85
- maybeCompactBeforeContextTransform(messages: AgentMessage[], projectContextGc: (messages: AgentMessage[]) => AgentMessage[]): Promise<boolean>;
86
106
  compact(customInstructions?: string): Promise<CompactionResult>;
87
107
  check(assistantMessage: AssistantMessage, skipAbortedCheck?: boolean): Promise<boolean>;
88
108
  measureLiveContextTokens(): number;
89
- runAuto(reason: AutoCompactionReason, willRetry: boolean): Promise<boolean>;
109
+ runAuto(reason: AutoCompactionReason, willRetry: boolean, options?: AutoCompactionRunOptions): Promise<boolean>;
90
110
  private runAutoOnce;
91
111
  private shouldDeferThresholdRetry;
92
112
  private recordThresholdFrontier;
@@ -1 +1 @@
1
- {"version":3,"file":"compaction-controller.d.ts","sourceRoot":"","sources":["../../src/core/compaction-controller.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,iCAAiC,CAAC;AAC7D,OAAO,EAEN,KAAK,gBAAgB,EACrB,KAAK,kBAAkB,EAOvB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