@caupulican/pi-adaptative 0.81.37 → 0.81.39

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 (451) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/README.md +1 -1
  3. package/dist/bundled-resources/extensions/tmux-agent-manager/README.md +18 -1
  4. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts +131 -0
  5. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts.map +1 -0
  6. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js +196 -0
  7. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js.map +1 -0
  8. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.ts +308 -0
  9. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts +22 -2
  10. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts.map +1 -1
  11. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js +585 -24
  12. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js.map +1 -1
  13. package/dist/bundled-resources/extensions/tmux-agent-manager/index.ts +749 -27
  14. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/__init__.py +43 -0
  15. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/fs.py +270 -0
  16. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/search.py +252 -0
  17. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/strings.py +399 -0
  18. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/text.py +575 -0
  19. package/dist/bundled-resources/runtimes/pi-shell-engine/context.py +52 -0
  20. package/dist/bundled-resources/runtimes/pi-shell-engine/errors.py +49 -0
  21. package/dist/bundled-resources/runtimes/pi-shell-engine/exec.py +734 -0
  22. package/dist/bundled-resources/runtimes/pi-shell-engine/expand.py +238 -0
  23. package/dist/bundled-resources/runtimes/pi-shell-engine/main.py +132 -0
  24. package/dist/bundled-resources/runtimes/pi-shell-engine/nodes.py +116 -0
  25. package/dist/bundled-resources/runtimes/pi-shell-engine/parser.py +287 -0
  26. package/dist/bundled-resources/runtimes/pi-shell-engine/proc.py +137 -0
  27. package/dist/bundled-resources/runtimes/pi-shell-engine/state.py +100 -0
  28. package/dist/bundled-resources/runtimes/pi-shell-engine/tokens.py +579 -0
  29. package/dist/bundled-resources/skills/tool-call-repair/SKILL.md +19 -9
  30. package/dist/bundled-resources/skills/tool-call-repair/references/failure-grammar.md +22 -5
  31. package/dist/bundled-resources/skills/tool-call-repair/references/repair-catalogue.md +5 -5
  32. package/dist/bundled-resources/skills/tool-call-repair/references/text-protocol-grammar.md +28 -7
  33. package/dist/cli/args.d.ts +3 -0
  34. package/dist/cli/args.d.ts.map +1 -1
  35. package/dist/cli/args.js +15 -0
  36. package/dist/cli/args.js.map +1 -1
  37. package/dist/core/agent-paths.d.ts +49 -0
  38. package/dist/core/agent-paths.d.ts.map +1 -0
  39. package/dist/core/agent-paths.js +107 -0
  40. package/dist/core/agent-paths.js.map +1 -0
  41. package/dist/core/agent-session-services.d.ts.map +1 -1
  42. package/dist/core/agent-session-services.js +3 -3
  43. package/dist/core/agent-session-services.js.map +1 -1
  44. package/dist/core/agent-session.d.ts +234 -17
  45. package/dist/core/agent-session.d.ts.map +1 -1
  46. package/dist/core/agent-session.js +484 -62
  47. package/dist/core/agent-session.js.map +1 -1
  48. package/dist/core/autonomy/contracts.d.ts +9 -0
  49. package/dist/core/autonomy/contracts.d.ts.map +1 -1
  50. package/dist/core/autonomy/contracts.js.map +1 -1
  51. package/dist/core/autonomy/lane-tracker.d.ts +10 -1
  52. package/dist/core/autonomy/lane-tracker.d.ts.map +1 -1
  53. package/dist/core/autonomy/lane-tracker.js +5 -1
  54. package/dist/core/autonomy/lane-tracker.js.map +1 -1
  55. package/dist/core/background-lane-controller.d.ts +122 -6
  56. package/dist/core/background-lane-controller.d.ts.map +1 -1
  57. package/dist/core/background-lane-controller.js +447 -90
  58. package/dist/core/background-lane-controller.js.map +1 -1
  59. package/dist/core/bash-execution-controller.d.ts +4 -0
  60. package/dist/core/bash-execution-controller.d.ts.map +1 -1
  61. package/dist/core/bash-execution-controller.js +7 -1
  62. package/dist/core/bash-execution-controller.js.map +1 -1
  63. package/dist/core/compaction-support.d.ts +13 -3
  64. package/dist/core/compaction-support.d.ts.map +1 -1
  65. package/dist/core/compaction-support.js +43 -7
  66. package/dist/core/compaction-support.js.map +1 -1
  67. package/dist/core/context/context-audit.d.ts +33 -1
  68. package/dist/core/context/context-audit.d.ts.map +1 -1
  69. package/dist/core/context/context-audit.js +31 -5
  70. package/dist/core/context/context-audit.js.map +1 -1
  71. package/dist/core/context/sqlite-runtime-index.d.ts.map +1 -1
  72. package/dist/core/context/sqlite-runtime-index.js +13 -7
  73. package/dist/core/context/sqlite-runtime-index.js.map +1 -1
  74. package/dist/core/context-gc.d.ts.map +1 -1
  75. package/dist/core/context-gc.js +16 -1
  76. package/dist/core/context-gc.js.map +1 -1
  77. package/dist/core/context-pipeline.d.ts +26 -4
  78. package/dist/core/context-pipeline.d.ts.map +1 -1
  79. package/dist/core/context-pipeline.js +137 -14
  80. package/dist/core/context-pipeline.js.map +1 -1
  81. package/dist/core/cost-guard.d.ts +19 -3
  82. package/dist/core/cost-guard.d.ts.map +1 -1
  83. package/dist/core/cost-guard.js +18 -3
  84. package/dist/core/cost-guard.js.map +1 -1
  85. package/dist/core/delegation/session-worker-result.d.ts +34 -4
  86. package/dist/core/delegation/session-worker-result.d.ts.map +1 -1
  87. package/dist/core/delegation/session-worker-result.js +64 -4
  88. package/dist/core/delegation/session-worker-result.js.map +1 -1
  89. package/dist/core/delegation/worker-actions.d.ts.map +1 -1
  90. package/dist/core/delegation/worker-actions.js +1 -1
  91. package/dist/core/delegation/worker-actions.js.map +1 -1
  92. package/dist/core/delegation/worker-result.d.ts +42 -1
  93. package/dist/core/delegation/worker-result.d.ts.map +1 -1
  94. package/dist/core/delegation/worker-result.js +68 -0
  95. package/dist/core/delegation/worker-result.js.map +1 -1
  96. package/dist/core/extensions/loader.d.ts.map +1 -1
  97. package/dist/core/extensions/loader.js +23 -7
  98. package/dist/core/extensions/loader.js.map +1 -1
  99. package/dist/core/extensions/runner.d.ts.map +1 -1
  100. package/dist/core/extensions/runner.js +1 -0
  101. package/dist/core/extensions/runner.js.map +1 -1
  102. package/dist/core/extensions/types.d.ts +51 -0
  103. package/dist/core/extensions/types.d.ts.map +1 -1
  104. package/dist/core/extensions/types.js.map +1 -1
  105. package/dist/core/goal-loop-controller.d.ts +17 -1
  106. package/dist/core/goal-loop-controller.d.ts.map +1 -1
  107. package/dist/core/goal-loop-controller.js +79 -11
  108. package/dist/core/goal-loop-controller.js.map +1 -1
  109. package/dist/core/goals/goal-continuation-controller.d.ts +48 -2
  110. package/dist/core/goals/goal-continuation-controller.d.ts.map +1 -1
  111. package/dist/core/goals/goal-continuation-controller.js +77 -0
  112. package/dist/core/goals/goal-continuation-controller.js.map +1 -1
  113. package/dist/core/goals/goal-continuation-defaults.d.ts +39 -0
  114. package/dist/core/goals/goal-continuation-defaults.d.ts.map +1 -1
  115. package/dist/core/goals/goal-continuation-defaults.js +42 -0
  116. package/dist/core/goals/goal-continuation-defaults.js.map +1 -1
  117. package/dist/core/goals/goal-continuation-prompt.d.ts +4 -0
  118. package/dist/core/goals/goal-continuation-prompt.d.ts.map +1 -1
  119. package/dist/core/goals/goal-continuation-prompt.js +51 -10
  120. package/dist/core/goals/goal-continuation-prompt.js.map +1 -1
  121. package/dist/core/goals/goal-runtime-snapshot.d.ts +101 -2
  122. package/dist/core/goals/goal-runtime-snapshot.d.ts.map +1 -1
  123. package/dist/core/goals/goal-runtime-snapshot.js +87 -4
  124. package/dist/core/goals/goal-runtime-snapshot.js.map +1 -1
  125. package/dist/core/goals/goal-state.d.ts +89 -1
  126. package/dist/core/goals/goal-state.d.ts.map +1 -1
  127. package/dist/core/goals/goal-state.js +71 -5
  128. package/dist/core/goals/goal-state.js.map +1 -1
  129. package/dist/core/goals/goal-tool-core.d.ts +56 -2
  130. package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
  131. package/dist/core/goals/goal-tool-core.js +111 -5
  132. package/dist/core/goals/goal-tool-core.js.map +1 -1
  133. package/dist/core/goals/session-goal-state.d.ts +11 -2
  134. package/dist/core/goals/session-goal-state.d.ts.map +1 -1
  135. package/dist/core/goals/session-goal-state.js +32 -17
  136. package/dist/core/goals/session-goal-state.js.map +1 -1
  137. package/dist/core/keybindings.d.ts +10 -0
  138. package/dist/core/keybindings.d.ts.map +1 -1
  139. package/dist/core/keybindings.js +10 -2
  140. package/dist/core/keybindings.js.map +1 -1
  141. package/dist/core/learning/observation-store.d.ts +12 -3
  142. package/dist/core/learning/observation-store.d.ts.map +1 -1
  143. package/dist/core/learning/observation-store.js +30 -15
  144. package/dist/core/learning/observation-store.js.map +1 -1
  145. package/dist/core/learning/skill-curator.d.ts +5 -1
  146. package/dist/core/learning/skill-curator.d.ts.map +1 -1
  147. package/dist/core/learning/skill-curator.js +21 -19
  148. package/dist/core/learning/skill-curator.js.map +1 -1
  149. package/dist/core/local-runtime-controller.d.ts +65 -3
  150. package/dist/core/local-runtime-controller.d.ts.map +1 -1
  151. package/dist/core/local-runtime-controller.js +186 -26
  152. package/dist/core/local-runtime-controller.js.map +1 -1
  153. package/dist/core/memory/providers/file-store.d.ts +1 -1
  154. package/dist/core/memory/providers/file-store.d.ts.map +1 -1
  155. package/dist/core/memory/providers/file-store.js +6 -6
  156. package/dist/core/memory/providers/file-store.js.map +1 -1
  157. package/dist/core/model-capability.d.ts +34 -0
  158. package/dist/core/model-capability.d.ts.map +1 -1
  159. package/dist/core/model-capability.js +42 -1
  160. package/dist/core/model-capability.js.map +1 -1
  161. package/dist/core/model-router/tool-escalation.d.ts +15 -0
  162. package/dist/core/model-router/tool-escalation.d.ts.map +1 -1
  163. package/dist/core/model-router/tool-escalation.js +23 -1
  164. package/dist/core/model-router/tool-escalation.js.map +1 -1
  165. package/dist/core/model-router-controller.d.ts +34 -7
  166. package/dist/core/model-router-controller.d.ts.map +1 -1
  167. package/dist/core/model-router-controller.js +95 -16
  168. package/dist/core/model-router-controller.js.map +1 -1
  169. package/dist/core/models/adaptation-store.d.ts +7 -0
  170. package/dist/core/models/adaptation-store.d.ts.map +1 -1
  171. package/dist/core/models/adaptation-store.js +47 -11
  172. package/dist/core/models/adaptation-store.js.map +1 -1
  173. package/dist/core/models/default-model-suggestions.d.ts.map +1 -1
  174. package/dist/core/models/default-model-suggestions.js +17 -0
  175. package/dist/core/models/default-model-suggestions.js.map +1 -1
  176. package/dist/core/models/fitness-store.d.ts +3 -0
  177. package/dist/core/models/fitness-store.d.ts.map +1 -1
  178. package/dist/core/models/fitness-store.js +11 -2
  179. package/dist/core/models/fitness-store.js.map +1 -1
  180. package/dist/core/models/llamacpp-runtime.d.ts +180 -0
  181. package/dist/core/models/llamacpp-runtime.d.ts.map +1 -0
  182. package/dist/core/models/llamacpp-runtime.js +475 -0
  183. package/dist/core/models/llamacpp-runtime.js.map +1 -0
  184. package/dist/core/models/local-registration.d.ts +40 -0
  185. package/dist/core/models/local-registration.d.ts.map +1 -1
  186. package/dist/core/models/local-registration.js +94 -5
  187. package/dist/core/models/local-registration.js.map +1 -1
  188. package/dist/core/models/local-runtime.d.ts.map +1 -1
  189. package/dist/core/models/local-runtime.js +9 -7
  190. package/dist/core/models/local-runtime.js.map +1 -1
  191. package/dist/core/models/model-ref.d.ts +7 -0
  192. package/dist/core/models/model-ref.d.ts.map +1 -1
  193. package/dist/core/models/model-ref.js +26 -0
  194. package/dist/core/models/model-ref.js.map +1 -1
  195. package/dist/core/models/needle-runtime.d.ts +257 -0
  196. package/dist/core/models/needle-runtime.d.ts.map +1 -0
  197. package/dist/core/models/needle-runtime.js +519 -0
  198. package/dist/core/models/needle-runtime.js.map +1 -0
  199. package/dist/core/models/prism-llamacpp-lifecycle.d.ts +89 -0
  200. package/dist/core/models/prism-llamacpp-lifecycle.d.ts.map +1 -0
  201. package/dist/core/models/prism-llamacpp-lifecycle.js +121 -0
  202. package/dist/core/models/prism-llamacpp-lifecycle.js.map +1 -0
  203. package/dist/core/package-manager.d.ts.map +1 -1
  204. package/dist/core/package-manager.js +11 -10
  205. package/dist/core/package-manager.js.map +1 -1
  206. package/dist/core/process-matrix/codes.d.ts +72 -0
  207. package/dist/core/process-matrix/codes.d.ts.map +1 -0
  208. package/dist/core/process-matrix/codes.js +15 -0
  209. package/dist/core/process-matrix/codes.js.map +1 -0
  210. package/dist/core/process-matrix/runtime.d.ts +63 -0
  211. package/dist/core/process-matrix/runtime.d.ts.map +1 -0
  212. package/dist/core/process-matrix/runtime.js +310 -0
  213. package/dist/core/process-matrix/runtime.js.map +1 -0
  214. package/dist/core/process-matrix/store.d.ts +22 -0
  215. package/dist/core/process-matrix/store.d.ts.map +1 -0
  216. package/dist/core/process-matrix/store.js +80 -0
  217. package/dist/core/process-matrix/store.js.map +1 -0
  218. package/dist/core/process-matrix/supervisor.d.ts +72 -0
  219. package/dist/core/process-matrix/supervisor.d.ts.map +1 -0
  220. package/dist/core/process-matrix/supervisor.js +130 -0
  221. package/dist/core/process-matrix/supervisor.js.map +1 -0
  222. package/dist/core/profile-registry.d.ts +7 -0
  223. package/dist/core/profile-registry.d.ts.map +1 -1
  224. package/dist/core/profile-registry.js +20 -0
  225. package/dist/core/profile-registry.js.map +1 -1
  226. package/dist/core/python-runtime.d.ts.map +1 -1
  227. package/dist/core/python-runtime.js +3 -3
  228. package/dist/core/python-runtime.js.map +1 -1
  229. package/dist/core/reflection-controller.d.ts +29 -5
  230. package/dist/core/reflection-controller.d.ts.map +1 -1
  231. package/dist/core/reflection-controller.js +215 -126
  232. package/dist/core/reflection-controller.js.map +1 -1
  233. package/dist/core/reload-blockers.d.ts +36 -0
  234. package/dist/core/reload-blockers.d.ts.map +1 -1
  235. package/dist/core/reload-blockers.js +44 -0
  236. package/dist/core/reload-blockers.js.map +1 -1
  237. package/dist/core/resource-loader.d.ts.map +1 -1
  238. package/dist/core/resource-loader.js +8 -7
  239. package/dist/core/resource-loader.js.map +1 -1
  240. package/dist/core/runtime-builder.d.ts +58 -5
  241. package/dist/core/runtime-builder.d.ts.map +1 -1
  242. package/dist/core/runtime-builder.js +209 -25
  243. package/dist/core/runtime-builder.js.map +1 -1
  244. package/dist/core/scout-controller.d.ts +6 -0
  245. package/dist/core/scout-controller.d.ts.map +1 -1
  246. package/dist/core/scout-controller.js +66 -52
  247. package/dist/core/scout-controller.js.map +1 -1
  248. package/dist/core/sdk.d.ts.map +1 -1
  249. package/dist/core/sdk.js +3 -3
  250. package/dist/core/sdk.js.map +1 -1
  251. package/dist/core/session-role.d.ts +31 -0
  252. package/dist/core/session-role.d.ts.map +1 -0
  253. package/dist/core/session-role.js +52 -0
  254. package/dist/core/session-role.js.map +1 -0
  255. package/dist/core/settings-manager.d.ts +42 -3
  256. package/dist/core/settings-manager.d.ts.map +1 -1
  257. package/dist/core/settings-manager.js +94 -60
  258. package/dist/core/settings-manager.js.map +1 -1
  259. package/dist/core/system-prompt-builder.d.ts +12 -0
  260. package/dist/core/system-prompt-builder.d.ts.map +1 -1
  261. package/dist/core/system-prompt-builder.js +6 -0
  262. package/dist/core/system-prompt-builder.js.map +1 -1
  263. package/dist/core/system-prompt.d.ts +14 -1
  264. package/dist/core/system-prompt.d.ts.map +1 -1
  265. package/dist/core/system-prompt.js +20 -3
  266. package/dist/core/system-prompt.js.map +1 -1
  267. package/dist/core/tasks/session-task-state.d.ts +11 -2
  268. package/dist/core/tasks/session-task-state.d.ts.map +1 -1
  269. package/dist/core/tasks/session-task-state.js +27 -11
  270. package/dist/core/tasks/session-task-state.js.map +1 -1
  271. package/dist/core/tasks/task-contract-monitor.d.ts +45 -0
  272. package/dist/core/tasks/task-contract-monitor.d.ts.map +1 -0
  273. package/dist/core/tasks/task-contract-monitor.js +56 -0
  274. package/dist/core/tasks/task-contract-monitor.js.map +1 -0
  275. package/dist/core/tasks/task-state.d.ts +8 -0
  276. package/dist/core/tasks/task-state.d.ts.map +1 -1
  277. package/dist/core/tasks/task-state.js +28 -1
  278. package/dist/core/tasks/task-state.js.map +1 -1
  279. package/dist/core/tool-gate-controller.d.ts.map +1 -1
  280. package/dist/core/tool-gate-controller.js +5 -0
  281. package/dist/core/tool-gate-controller.js.map +1 -1
  282. package/dist/core/tool-recovery-log-records.d.ts +7 -0
  283. package/dist/core/tool-recovery-log-records.d.ts.map +1 -1
  284. package/dist/core/tool-recovery-log-records.js +14 -6
  285. package/dist/core/tool-recovery-log-records.js.map +1 -1
  286. package/dist/core/tool-selection/promotion.d.ts +54 -0
  287. package/dist/core/tool-selection/promotion.d.ts.map +1 -0
  288. package/dist/core/tool-selection/promotion.js +81 -0
  289. package/dist/core/tool-selection/promotion.js.map +1 -0
  290. package/dist/core/tool-selection/tool-performance-store.d.ts +37 -0
  291. package/dist/core/tool-selection/tool-performance-store.d.ts.map +1 -1
  292. package/dist/core/tool-selection/tool-performance-store.js +87 -3
  293. package/dist/core/tool-selection/tool-performance-store.js.map +1 -1
  294. package/dist/core/tool-selection/tool-selection-controller.d.ts +45 -0
  295. package/dist/core/tool-selection/tool-selection-controller.d.ts.map +1 -1
  296. package/dist/core/tool-selection/tool-selection-controller.js +96 -0
  297. package/dist/core/tool-selection/tool-selection-controller.js.map +1 -1
  298. package/dist/core/tools/bash.d.ts +18 -0
  299. package/dist/core/tools/bash.d.ts.map +1 -1
  300. package/dist/core/tools/bash.js +97 -18
  301. package/dist/core/tools/bash.js.map +1 -1
  302. package/dist/core/tools/delegate-status.d.ts +14 -0
  303. package/dist/core/tools/delegate-status.d.ts.map +1 -1
  304. package/dist/core/tools/delegate-status.js +82 -7
  305. package/dist/core/tools/delegate-status.js.map +1 -1
  306. package/dist/core/tools/delegate.d.ts.map +1 -1
  307. package/dist/core/tools/delegate.js +25 -8
  308. package/dist/core/tools/delegate.js.map +1 -1
  309. package/dist/core/tools/find.d.ts.map +1 -1
  310. package/dist/core/tools/find.js +52 -44
  311. package/dist/core/tools/find.js.map +1 -1
  312. package/dist/core/tools/goal.d.ts +94 -3
  313. package/dist/core/tools/goal.d.ts.map +1 -1
  314. package/dist/core/tools/goal.js +165 -15
  315. package/dist/core/tools/goal.js.map +1 -1
  316. package/dist/core/tools/grep.d.ts.map +1 -1
  317. package/dist/core/tools/grep.js +5 -4
  318. package/dist/core/tools/grep.js.map +1 -1
  319. package/dist/core/tools/model-fitness.d.ts +7 -0
  320. package/dist/core/tools/model-fitness.d.ts.map +1 -1
  321. package/dist/core/tools/model-fitness.js +2 -2
  322. package/dist/core/tools/model-fitness.js.map +1 -1
  323. package/dist/core/tools/render-utils.d.ts.map +1 -1
  324. package/dist/core/tools/render-utils.js +1 -1
  325. package/dist/core/tools/render-utils.js.map +1 -1
  326. package/dist/core/tools/shell-contract-router.d.ts +6 -1
  327. package/dist/core/tools/shell-contract-router.d.ts.map +1 -1
  328. package/dist/core/tools/shell-contract-router.js +69 -13
  329. package/dist/core/tools/shell-contract-router.js.map +1 -1
  330. package/dist/core/tools/shell-session.d.ts +89 -0
  331. package/dist/core/tools/shell-session.d.ts.map +1 -0
  332. package/dist/core/tools/shell-session.js +432 -0
  333. package/dist/core/tools/shell-session.js.map +1 -0
  334. package/dist/core/tools/task-steps.d.ts +4 -0
  335. package/dist/core/tools/task-steps.d.ts.map +1 -1
  336. package/dist/core/tools/task-steps.js +63 -8
  337. package/dist/core/tools/task-steps.js.map +1 -1
  338. package/dist/core/tools/tmux-dispatch.d.ts +86 -0
  339. package/dist/core/tools/tmux-dispatch.d.ts.map +1 -0
  340. package/dist/core/tools/tmux-dispatch.js +91 -0
  341. package/dist/core/tools/tmux-dispatch.js.map +1 -0
  342. package/dist/core/tools/windows-shell-engine.d.ts +42 -0
  343. package/dist/core/tools/windows-shell-engine.d.ts.map +1 -0
  344. package/dist/core/tools/windows-shell-engine.js +153 -0
  345. package/dist/core/tools/windows-shell-engine.js.map +1 -0
  346. package/dist/core/tools/windows-shell-state.d.ts +40 -0
  347. package/dist/core/tools/windows-shell-state.d.ts.map +1 -0
  348. package/dist/core/tools/windows-shell-state.js +59 -0
  349. package/dist/core/tools/windows-shell-state.js.map +1 -0
  350. package/dist/core/tools/worktree-sync.d.ts +24 -0
  351. package/dist/core/tools/worktree-sync.d.ts.map +1 -0
  352. package/dist/core/tools/worktree-sync.js +338 -0
  353. package/dist/core/tools/worktree-sync.js.map +1 -0
  354. package/dist/core/trust-manager.d.ts +4 -1
  355. package/dist/core/trust-manager.d.ts.map +1 -1
  356. package/dist/core/trust-manager.js +20 -2
  357. package/dist/core/trust-manager.js.map +1 -1
  358. package/dist/core/util/atomic-file.d.ts +55 -0
  359. package/dist/core/util/atomic-file.d.ts.map +1 -0
  360. package/dist/core/util/atomic-file.js +255 -0
  361. package/dist/core/util/atomic-file.js.map +1 -0
  362. package/dist/core/util/minimatch-cache.d.ts +33 -0
  363. package/dist/core/util/minimatch-cache.d.ts.map +1 -0
  364. package/dist/core/util/minimatch-cache.js +0 -0
  365. package/dist/core/util/minimatch-cache.js.map +1 -0
  366. package/dist/core/worktree-sync/codes.d.ts +227 -0
  367. package/dist/core/worktree-sync/codes.d.ts.map +1 -0
  368. package/dist/core/worktree-sync/codes.js +14 -0
  369. package/dist/core/worktree-sync/codes.js.map +1 -0
  370. package/dist/core/worktree-sync/git-engine.d.ts +156 -0
  371. package/dist/core/worktree-sync/git-engine.d.ts.map +1 -0
  372. package/dist/core/worktree-sync/git-engine.js +1191 -0
  373. package/dist/core/worktree-sync/git-engine.js.map +1 -0
  374. package/dist/core/worktree-sync/lane-gate.d.ts +75 -0
  375. package/dist/core/worktree-sync/lane-gate.d.ts.map +1 -0
  376. package/dist/core/worktree-sync/lane-gate.js +360 -0
  377. package/dist/core/worktree-sync/lane-gate.js.map +1 -0
  378. package/dist/core/worktree-sync/runtime.d.ts +47 -0
  379. package/dist/core/worktree-sync/runtime.d.ts.map +1 -0
  380. package/dist/core/worktree-sync/runtime.js +96 -0
  381. package/dist/core/worktree-sync/runtime.js.map +1 -0
  382. package/dist/core/worktree-sync/store.d.ts +69 -0
  383. package/dist/core/worktree-sync/store.d.ts.map +1 -0
  384. package/dist/core/worktree-sync/store.js +247 -0
  385. package/dist/core/worktree-sync/store.js.map +1 -0
  386. package/dist/core/worktree-sync/watcher.d.ts +29 -0
  387. package/dist/core/worktree-sync/watcher.d.ts.map +1 -0
  388. package/dist/core/worktree-sync/watcher.js +93 -0
  389. package/dist/core/worktree-sync/watcher.js.map +1 -0
  390. package/dist/main.d.ts.map +1 -1
  391. package/dist/main.js +94 -0
  392. package/dist/main.js.map +1 -1
  393. package/dist/migrations.d.ts +9 -0
  394. package/dist/migrations.d.ts.map +1 -1
  395. package/dist/migrations.js +38 -0
  396. package/dist/migrations.js.map +1 -1
  397. package/dist/modes/interactive/auto-learn-controller.d.ts +16 -1
  398. package/dist/modes/interactive/auto-learn-controller.d.ts.map +1 -1
  399. package/dist/modes/interactive/auto-learn-controller.js +50 -8
  400. package/dist/modes/interactive/auto-learn-controller.js.map +1 -1
  401. package/dist/modes/interactive/components/profile-resource-editor.d.ts.map +1 -1
  402. package/dist/modes/interactive/components/profile-resource-editor.js +23 -1
  403. package/dist/modes/interactive/components/profile-resource-editor.js.map +1 -1
  404. package/dist/modes/interactive/interactive-mode.d.ts +1 -0
  405. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  406. package/dist/modes/interactive/interactive-mode.js +4 -0
  407. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  408. package/dist/modes/interactive/local-model-commands.d.ts +43 -0
  409. package/dist/modes/interactive/local-model-commands.d.ts.map +1 -1
  410. package/dist/modes/interactive/local-model-commands.js +290 -3
  411. package/dist/modes/interactive/local-model-commands.js.map +1 -1
  412. package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -1
  413. package/dist/modes/interactive/session-flow-commands.js +24 -4
  414. package/dist/modes/interactive/session-flow-commands.js.map +1 -1
  415. package/dist/utils/fs-watch.d.ts +11 -0
  416. package/dist/utils/fs-watch.d.ts.map +1 -1
  417. package/dist/utils/fs-watch.js +20 -2
  418. package/dist/utils/fs-watch.js.map +1 -1
  419. package/dist/utils/highlight-js-languages.d.ts +4 -0
  420. package/dist/utils/highlight-js-languages.d.ts.map +1 -0
  421. package/dist/utils/highlight-js-languages.js +573 -0
  422. package/dist/utils/highlight-js-languages.js.map +1 -0
  423. package/dist/utils/shell.d.ts +7 -1
  424. package/dist/utils/shell.d.ts.map +1 -1
  425. package/dist/utils/shell.js +39 -9
  426. package/dist/utils/shell.js.map +1 -1
  427. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  428. package/dist/utils/syntax-highlight.js +53 -5
  429. package/dist/utils/syntax-highlight.js.map +1 -1
  430. package/dist/utils/tools-manager.d.ts.map +1 -1
  431. package/dist/utils/tools-manager.js +112 -1
  432. package/dist/utils/tools-manager.js.map +1 -1
  433. package/docs/development.md +2 -0
  434. package/docs/packages.md +1 -1
  435. package/docs/process-matrix.md +120 -0
  436. package/docs/settings.md +5 -2
  437. package/docs/tmux-agent-manager.md +85 -2
  438. package/docs/windows.md +52 -3
  439. package/docs/work-directory.md +29 -0
  440. package/docs/worktree-sync.md +250 -0
  441. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  442. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  443. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  444. package/examples/extensions/sandbox/package-lock.json +2 -2
  445. package/examples/extensions/sandbox/package.json +1 -1
  446. package/examples/extensions/with-deps/package-lock.json +2 -2
  447. package/examples/extensions/with-deps/package.json +1 -1
  448. package/npm-shrinkwrap.json +12 -12
  449. package/package.json +10 -4
  450. package/docs/integration-sweep-builder-blueprint-2026-07-09.md +0 -365
  451. package/docs/integration-sweep-resume-2026-07-09.md +0 -407
@@ -1,4 +1,5 @@
1
1
  import { Agent } from "@caupulican/pi-agent-core";
2
+ import { registerInFlightWork } from "./reload-blockers.js";
2
3
  export const SCOUT_SYSTEM_PROMPT = `You are a repository scout. You explore a codebase with read-only tools and return compact evidence. You do NOT solve tasks, write code, or modify anything.
3
4
 
4
5
  TOOLS: read (file contents), grep (search file contents), find (locate files by glob/name).
@@ -40,65 +41,78 @@ export class ScoutController {
40
41
  if ("failure" in modelResolution) {
41
42
  return { ...unavailable, failure: modelResolution.failure };
42
43
  }
43
- let turnsUsed = 0;
44
- let truncated = false;
45
- let lastAssistantText = "";
46
- let outputTokens = 0;
47
- const agent = new Agent({
48
- initialState: {
49
- model: modelResolution.model,
50
- systemPrompt: SCOUT_SYSTEM_PROMPT.replace("{MAX_TURNS}", String(turnLimit)),
51
- tools: this.deps
52
- .buildReadOnlyTools(this.deps.getCwd())
53
- .filter((tool) => READ_ONLY_TOOL_NAMES.has(tool.name)),
54
- },
55
- streamFn: this.deps.streamFn,
56
- getApiKey: () => modelResolution.apiKey,
57
- maxStallTurns: turnLimit,
58
- });
59
- const unsubscribe = agent.subscribe((event) => {
60
- if (event.type !== "message_end" || event.message.role !== "assistant") {
61
- return;
62
- }
63
- turnsUsed += 1;
64
- lastAssistantText = assistantText(event.message);
65
- outputTokens += getScoutOutputTokenCount(event.message);
66
- this.deps.onEvent?.({ type: "scout_turn", detail: `turn ${turnsUsed}` });
67
- if (hasFinalAnswer(lastAssistantText)) {
68
- return;
69
- }
70
- if (turnsUsed >= turnLimit || outputTokens >= MAX_OUTPUT_TOKENS) {
44
+ // Registered while this scout's own Agent drives turns, so the reload gate waits it out.
45
+ // registerInFlightWork is a pure sync map op (cannot throw), so wrapping everything from here
46
+ // through the end in try/finally guarantees deregistration on every exit path. Optional dep —
47
+ // a caller that hasn't wired an agent dir through stays invisible to the gate, matching the
48
+ // behavior before this registration was added.
49
+ const deregisterInFlight = this.deps.getAgentDir
50
+ ? registerInFlightWork(this.deps.getAgentDir(), "scout", query.slice(0, 80))
51
+ : undefined;
52
+ try {
53
+ let turnsUsed = 0;
54
+ let truncated = false;
55
+ let lastAssistantText = "";
56
+ let outputTokens = 0;
57
+ const agent = new Agent({
58
+ initialState: {
59
+ model: modelResolution.model,
60
+ systemPrompt: SCOUT_SYSTEM_PROMPT.replace("{MAX_TURNS}", String(turnLimit)),
61
+ tools: this.deps
62
+ .buildReadOnlyTools(this.deps.getCwd())
63
+ .filter((tool) => READ_ONLY_TOOL_NAMES.has(tool.name)),
64
+ },
65
+ streamFn: this.deps.streamFn,
66
+ getApiKey: () => modelResolution.apiKey,
67
+ maxStallTurns: turnLimit,
68
+ });
69
+ const unsubscribe = agent.subscribe((event) => {
70
+ if (event.type !== "message_end" || event.message.role !== "assistant") {
71
+ return;
72
+ }
73
+ turnsUsed += 1;
74
+ lastAssistantText = assistantText(event.message);
75
+ outputTokens += getScoutOutputTokenCount(event.message);
76
+ this.deps.onEvent?.({ type: "scout_turn", detail: `turn ${turnsUsed}` });
77
+ if (hasFinalAnswer(lastAssistantText)) {
78
+ return;
79
+ }
80
+ if (turnsUsed >= turnLimit || outputTokens >= MAX_OUTPUT_TOKENS) {
81
+ truncated = true;
82
+ agent.abort();
83
+ }
84
+ });
85
+ const abortScout = () => {
71
86
  truncated = true;
72
87
  agent.abort();
88
+ };
89
+ this.deps.signal?.addEventListener("abort", abortScout, { once: true });
90
+ let runFailure;
91
+ try {
92
+ await agent.prompt(query);
73
93
  }
74
- });
75
- const abortScout = () => {
76
- truncated = true;
77
- agent.abort();
78
- };
79
- this.deps.signal?.addEventListener("abort", abortScout, { once: true });
80
- let runFailure;
81
- try {
82
- await agent.prompt(query);
83
- }
84
- catch (error) {
85
- if (!truncated && !this.deps.signal?.aborted) {
86
- runFailure = error instanceof Error ? error.message : String(error);
94
+ catch (error) {
95
+ if (!truncated && !this.deps.signal?.aborted) {
96
+ runFailure = error instanceof Error ? error.message : String(error);
97
+ }
98
+ }
99
+ finally {
100
+ unsubscribe();
101
+ this.deps.signal?.removeEventListener("abort", abortScout);
87
102
  }
103
+ const result = parseScoutAnswer(lastAssistantText, (path) => this.deps.fileExists(path), (path) => this.deps.countLines(path));
104
+ const finalResult = {
105
+ ...result,
106
+ truncated: truncated || !hasFinalAnswer(lastAssistantText),
107
+ turnsUsed,
108
+ failure: this.deps.signal?.aborted ? "aborted" : runFailure,
109
+ };
110
+ this.deps.onEvent?.({ type: "scout_end", detail: finalResult.failure ?? "ok" });
111
+ return finalResult;
88
112
  }
89
113
  finally {
90
- unsubscribe();
91
- this.deps.signal?.removeEventListener("abort", abortScout);
114
+ deregisterInFlight?.();
92
115
  }
93
- const result = parseScoutAnswer(lastAssistantText, (path) => this.deps.fileExists(path), (path) => this.deps.countLines(path));
94
- const finalResult = {
95
- ...result,
96
- truncated: truncated || !hasFinalAnswer(lastAssistantText),
97
- turnsUsed,
98
- failure: this.deps.signal?.aborted ? "aborted" : runFailure,
99
- };
100
- this.deps.onEvent?.({ type: "scout_end", detail: finalResult.failure ?? "ok" });
101
- return finalResult;
102
116
  }
103
117
  }
104
118
  export function getScoutOutputTokenCount(message) {
@@ -1 +1 @@
1
- {"version":3,"file":"scout-controller.js","sourceRoot":"","sources":["../../src/core/scout-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAiC,MAAM,2BAA2B,CAAC;AAGjF,MAAM,CAAC,MAAM,mBAAmB,GAAG;;;;;;;;;;;;;;;wEAeqC,CAAC;AAgCzE,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAC5B,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAC9B,MAAM,iBAAiB,GAAG,MAAM,CAAC;AACjC,MAAM,oBAAoB,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;AAE/D,MAAM,OAAO,eAAe;IACV,IAAI,CAAsB;IAE3C,YAAY,IAAyB,EAAE;QACtC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAAA,CACjB;IAED,KAAK,CAAC,GAAG,CAAC,KAAa,EAAE,QAAQ,GAAG,iBAAiB,EAA2B;QAC/E,MAAM,SAAS,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC;QACvC,MAAM,WAAW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C/C,OAAO,OAAO,CAAC,OAAO;SACpB,MAAM,CAAC,CAAC,OAAO,EAA6C,EAAE,CAC9D,OAAO,CACN,OAAO;QACN,OAAO,OAAO,KAAK,QAAQ;QAC1B,OAA8B,CAAC,IAAI,KAAK,MAAM;QAC/C,OAAQ,OAA8B,CAAC,IAAI,KAAK,QAAQ,CACzD,CACD;SACA,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC;SAC9B,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACb","sourcesContent":["import { Agent, type AgentTool, type StreamFn } from \"@caupulican/pi-agent-core\";\nimport type { Model } from \"@caupulican/pi-ai\";\n\nexport const SCOUT_SYSTEM_PROMPT = `You are a repository scout. You explore a codebase with read-only tools and return compact evidence. You do NOT solve tasks, write code, or modify anything.\n\nTOOLS: read (file contents), grep (search file contents), find (locate files by glob/name).\n- Issue INDEPENDENT tool calls in parallel in the same turn whenever possible.\n- Prefer grep/find to narrow, then read only the decisive regions.\n\nOUTPUT CONTRACT: when you have enough evidence (or hit your turn budget), reply with:\n<final_answer>\n<one-to-three-sentence summary of what you found>\npath/to/file.ts:START-END\npath/to/other.ts:START-END\n</final_answer>\n- Every path MUST be one you actually observed via a tool result this run.\n- Line ranges point at the decisive code, not whole files.\n- If you found nothing relevant, say so inside <final_answer> with zero citations.\nTurn budget: {MAX_TURNS} turns. Be fast; be precise; cite, don't paste.`;\n\nexport interface ScoutCitation {\n\tpath: string;\n\tstart: number;\n\tend: number;\n\tvalid: boolean;\n}\n\nexport interface ScoutRunResult {\n\tsummary: string;\n\tcitations: ScoutCitation[];\n\tdroppedCitations: number;\n\tunreliable: boolean;\n\ttruncated: boolean;\n\tturnsUsed: number;\n\tfailure?: string;\n}\n\nexport interface ScoutControllerDeps {\n\tresolveScoutModel(): Promise<\n\t\t{ model: Model<any>; apiKey?: string; headers?: Record<string, string> } | { failure: string }\n\t>;\n\tgetCwd(): string;\n\tbuildReadOnlyTools(cwd: string): AgentTool<any>[];\n\tstreamFn?: StreamFn;\n\tfileExists(path: string): boolean;\n\tcountLines(path: string): number | undefined;\n\tonEvent?(event: { type: \"scout_turn\" | \"scout_end\"; detail: string }): void;\n\tsignal?: AbortSignal;\n}\n\nconst MAX_TURNS_DEFAULT = 8;\nconst MAX_TURNS_HARD_CAP = 12;\nconst MAX_OUTPUT_TOKENS = 30_000;\nconst READ_ONLY_TOOL_NAMES = new Set([\"read\", \"grep\", \"find\"]);\n\nexport class ScoutController {\n\tprivate readonly deps: ScoutControllerDeps;\n\n\tconstructor(deps: ScoutControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tasync run(query: string, maxTurns = MAX_TURNS_DEFAULT): Promise<ScoutRunResult> {\n\t\tconst turnLimit = clampTurns(maxTurns);\n\t\tconst unavailable = emptyResult();\n\t\tif (this.deps.signal?.aborted) {\n\t\t\treturn { ...unavailable, failure: \"aborted\" };\n\t\t}\n\n\t\tlet modelResolution: Awaited<ReturnType<ScoutControllerDeps[\"resolveScoutModel\"]>>;\n\t\ttry {\n\t\t\tmodelResolution = await this.deps.resolveScoutModel();\n\t\t} catch (error) {\n\t\t\treturn { ...unavailable, failure: error instanceof Error ? error.message : String(error) };\n\t\t}\n\t\tif (\"failure\" in modelResolution) {\n\t\t\treturn { ...unavailable, failure: modelResolution.failure };\n\t\t}\n\n\t\tlet turnsUsed = 0;\n\t\tlet truncated = false;\n\t\tlet lastAssistantText = \"\";\n\t\tlet outputTokens = 0;\n\t\tconst agent = new Agent({\n\t\t\tinitialState: {\n\t\t\t\tmodel: modelResolution.model,\n\t\t\t\tsystemPrompt: SCOUT_SYSTEM_PROMPT.replace(\"{MAX_TURNS}\", String(turnLimit)),\n\t\t\t\ttools: this.deps\n\t\t\t\t\t.buildReadOnlyTools(this.deps.getCwd())\n\t\t\t\t\t.filter((tool) => READ_ONLY_TOOL_NAMES.has(tool.name)),\n\t\t\t},\n\t\t\tstreamFn: this.deps.streamFn,\n\t\t\tgetApiKey: () => modelResolution.apiKey,\n\t\t\tmaxStallTurns: turnLimit,\n\t\t});\n\n\t\tconst unsubscribe = agent.subscribe((event) => {\n\t\t\tif (event.type !== \"message_end\" || event.message.role !== \"assistant\") {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tturnsUsed += 1;\n\t\t\tlastAssistantText = assistantText(event.message);\n\t\t\toutputTokens += getScoutOutputTokenCount(event.message);\n\t\t\tthis.deps.onEvent?.({ type: \"scout_turn\", detail: `turn ${turnsUsed}` });\n\t\t\tif (hasFinalAnswer(lastAssistantText)) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (turnsUsed >= turnLimit || outputTokens >= MAX_OUTPUT_TOKENS) {\n\t\t\t\ttruncated = true;\n\t\t\t\tagent.abort();\n\t\t\t}\n\t\t});\n\n\t\tconst abortScout = (): void => {\n\t\t\ttruncated = true;\n\t\t\tagent.abort();\n\t\t};\n\t\tthis.deps.signal?.addEventListener(\"abort\", abortScout, { once: true });\n\t\tlet runFailure: string | undefined;\n\t\ttry {\n\t\t\tawait agent.prompt(query);\n\t\t} catch (error) {\n\t\t\tif (!truncated && !this.deps.signal?.aborted) {\n\t\t\t\trunFailure = error instanceof Error ? error.message : String(error);\n\t\t\t}\n\t\t} finally {\n\t\t\tunsubscribe();\n\t\t\tthis.deps.signal?.removeEventListener(\"abort\", abortScout);\n\t\t}\n\n\t\tconst result = parseScoutAnswer(\n\t\t\tlastAssistantText,\n\t\t\t(path) => this.deps.fileExists(path),\n\t\t\t(path) => this.deps.countLines(path),\n\t\t);\n\t\tconst finalResult = {\n\t\t\t...result,\n\t\t\ttruncated: truncated || !hasFinalAnswer(lastAssistantText),\n\t\t\tturnsUsed,\n\t\t\tfailure: this.deps.signal?.aborted ? \"aborted\" : runFailure,\n\t\t};\n\t\tthis.deps.onEvent?.({ type: \"scout_end\", detail: finalResult.failure ?? \"ok\" });\n\t\treturn finalResult;\n\t}\n}\n\nexport function getScoutOutputTokenCount(message: { usage?: { output?: number } }): number {\n\treturn message.usage?.output ?? 0;\n}\n\nexport function parseScoutAnswer(\n\ttext: string,\n\tfileExists: (path: string) => boolean,\n\tcountLines: (path: string) => number | undefined,\n): Omit<ScoutRunResult, \"truncated\" | \"turnsUsed\" | \"failure\"> {\n\tconst finalAnswer = /<final_answer>([\\s\\S]*?)<\\/final_answer>/i.exec(text)?.[1] ?? text;\n\tconst summaryLines: string[] = [];\n\tconst citations: ScoutCitation[] = [];\n\n\tfor (const rawLine of finalAnswer.split(/\\r?\\n/)) {\n\t\tconst line = rawLine.trim();\n\t\tif (!line) continue;\n\t\tconst citation = parseCitationLine(line, fileExists, countLines);\n\t\tif (citation) {\n\t\t\tcitations.push(citation);\n\t\t\tcontinue;\n\t\t}\n\t\tsummaryLines.push(line);\n\t}\n\n\tconst droppedCitations = citations.filter((citation) => !citation.valid).length;\n\treturn {\n\t\tsummary: summaryLines.join(\"\\n\"),\n\t\tcitations,\n\t\tdroppedCitations,\n\t\tunreliable: citations.length > 0 && droppedCitations / citations.length > 0.5,\n\t};\n}\n\nfunction parseCitationLine(\n\tline: string,\n\tfileExists: (path: string) => boolean,\n\tcountLines: (path: string) => number | undefined,\n): ScoutCitation | undefined {\n\tconst match = /^(.+?):(\\d+)(?:-(\\d+))?$/.exec(line);\n\tif (!match) return undefined;\n\tconst path = match[1].trim();\n\tconst start = Number.parseInt(match[2], 10);\n\tconst end = Number.parseInt(match[3] ?? match[2], 10);\n\tconst lineCount = countLines(path);\n\tconst valid =\n\t\tfileExists(path) &&\n\t\tNumber.isFinite(start) &&\n\t\tNumber.isFinite(end) &&\n\t\tstart >= 1 &&\n\t\tend >= start &&\n\t\t(lineCount === undefined || end <= lineCount);\n\treturn { path, start, end, valid };\n}\n\nfunction clampTurns(maxTurns: number): number {\n\tif (!Number.isFinite(maxTurns)) return MAX_TURNS_DEFAULT;\n\treturn Math.min(MAX_TURNS_HARD_CAP, Math.max(1, Math.trunc(maxTurns)));\n}\n\nfunction emptyResult(): ScoutRunResult {\n\treturn { summary: \"\", citations: [], droppedCitations: 0, unreliable: false, truncated: false, turnsUsed: 0 };\n}\n\nfunction hasFinalAnswer(text: string): boolean {\n\treturn /<final_answer>[\\s\\S]*?<\\/final_answer>/i.test(text);\n}\n\nfunction assistantText(message: { content: unknown }): string {\n\tif (!Array.isArray(message.content)) return \"\";\n\treturn message.content\n\t\t.filter((content): content is { type: \"text\"; text: string } =>\n\t\t\tBoolean(\n\t\t\t\tcontent &&\n\t\t\t\t\ttypeof content === \"object\" &&\n\t\t\t\t\t(content as { type?: unknown }).type === \"text\" &&\n\t\t\t\t\ttypeof (content as { text?: unknown }).text === \"string\",\n\t\t\t),\n\t\t)\n\t\t.map((content) => content.text)\n\t\t.join(\"\\n\");\n}\n"]}
1
+ {"version":3,"file":"scout-controller.js","sourceRoot":"","sources":["../../src/core/scout-controller.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAiC,MAAM,2BAA2B,CAAC;AAEjF,OAAO,EAAE,oBAAoB,EAAE,MAAM,sBAAsB,CAAC;AAE5D,MAAM,CAAC,MAAM,mBAAmB,GAAG;;;;;;;;;;;;;;;wEAeqC,CAAC;AAsCzE,MAAM,iBAAiB,GAAG,CAAC,CAAC;AAC5B,MAAM,kBAAkB,GAAG,EAAE,CAAC;AAC9B,MAAM,iBAAiB,GAAG,MAAM,CAAC;AACjC,MAAM,oBAAoB,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;AAE/D,MAAM,OAAO,eAAe;IACV,IAAI,CAAsB;IAE3C,YAAY,IAAyB,EAAE;QACtC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAAA,CACjB;IAED,KAAK,CAAC,GAAG,CAAC,KAAa,EAAE,QAAQ,GAAG,iBAAiB,EAA2B;QAC/E,MAAM,SAAS,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC;QACvC,MAAM,WAAW,GAAG,WAAW,EAAE,CAAC;QAClC,IAA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AE,EAAE,SAAS,EAAE,EAAE,EAAE,gBAAgB,EAAE,CAAC,EAAE,UAAU,EAAE,KAAK,EAAE,SAAS,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,EAAE,CAAC;AAAA,CAC9G;AAED,SAAS,cAAc,CAAC,IAAY,EAAW;IAC9C,OAAO,yCAAyC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CAC5D;AAED,SAAS,aAAa,CAAC,OAA6B,EAAU;IAC7D,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC;QAAE,OAAO,EAAE,CAAC;IAC/C,OAAO,OAAO,CAAC,OAAO;SACpB,MAAM,CAAC,CAAC,OAAO,EAA6C,EAAE,CAC9D,OAAO,CACN,OAAO;QACN,OAAO,OAAO,KAAK,QAAQ;QAC1B,OAA8B,CAAC,IAAI,KAAK,MAAM;QAC/C,OAAQ,OAA8B,CAAC,IAAI,KAAK,QAAQ,CACzD,CACD;SACA,GAAG,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC;SAC9B,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACb","sourcesContent":["import { Agent, type AgentTool, type StreamFn } from \"@caupulican/pi-agent-core\";\nimport type { Model } from \"@caupulican/pi-ai\";\nimport { registerInFlightWork } from \"./reload-blockers.ts\";\n\nexport const SCOUT_SYSTEM_PROMPT = `You are a repository scout. You explore a codebase with read-only tools and return compact evidence. You do NOT solve tasks, write code, or modify anything.\n\nTOOLS: read (file contents), grep (search file contents), find (locate files by glob/name).\n- Issue INDEPENDENT tool calls in parallel in the same turn whenever possible.\n- Prefer grep/find to narrow, then read only the decisive regions.\n\nOUTPUT CONTRACT: when you have enough evidence (or hit your turn budget), reply with:\n<final_answer>\n<one-to-three-sentence summary of what you found>\npath/to/file.ts:START-END\npath/to/other.ts:START-END\n</final_answer>\n- Every path MUST be one you actually observed via a tool result this run.\n- Line ranges point at the decisive code, not whole files.\n- If you found nothing relevant, say so inside <final_answer> with zero citations.\nTurn budget: {MAX_TURNS} turns. Be fast; be precise; cite, don't paste.`;\n\nexport interface ScoutCitation {\n\tpath: string;\n\tstart: number;\n\tend: number;\n\tvalid: boolean;\n}\n\nexport interface ScoutRunResult {\n\tsummary: string;\n\tcitations: ScoutCitation[];\n\tdroppedCitations: number;\n\tunreliable: boolean;\n\ttruncated: boolean;\n\tturnsUsed: number;\n\tfailure?: string;\n}\n\nexport interface ScoutControllerDeps {\n\tresolveScoutModel(): Promise<\n\t\t{ model: Model<any>; apiKey?: string; headers?: Record<string, string> } | { failure: string }\n\t>;\n\tgetCwd(): string;\n\tbuildReadOnlyTools(cwd: string): AgentTool<any>[];\n\tstreamFn?: StreamFn;\n\tfileExists(path: string): boolean;\n\tcountLines(path: string): number | undefined;\n\tonEvent?(event: { type: \"scout_turn\" | \"scout_end\"; detail: string }): void;\n\tsignal?: AbortSignal;\n\t/** Registers this scout's own Agent run in the reload-gate quiesce registry while it drives\n\t * turns, so `/reload`/profile-switch/live extension load-unload-reconcile wait it out. Optional —\n\t * a caller that hasn't wired an agent dir through (e.g. an existing test construction) sees no\n\t * behavior change; the scout simply stays invisible to the reload gate, matching its behavior\n\t * before this registration was added. */\n\tgetAgentDir?(): string;\n}\n\nconst MAX_TURNS_DEFAULT = 8;\nconst MAX_TURNS_HARD_CAP = 12;\nconst MAX_OUTPUT_TOKENS = 30_000;\nconst READ_ONLY_TOOL_NAMES = new Set([\"read\", \"grep\", \"find\"]);\n\nexport class ScoutController {\n\tprivate readonly deps: ScoutControllerDeps;\n\n\tconstructor(deps: ScoutControllerDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\tasync run(query: string, maxTurns = MAX_TURNS_DEFAULT): Promise<ScoutRunResult> {\n\t\tconst turnLimit = clampTurns(maxTurns);\n\t\tconst unavailable = emptyResult();\n\t\tif (this.deps.signal?.aborted) {\n\t\t\treturn { ...unavailable, failure: \"aborted\" };\n\t\t}\n\n\t\tlet modelResolution: Awaited<ReturnType<ScoutControllerDeps[\"resolveScoutModel\"]>>;\n\t\ttry {\n\t\t\tmodelResolution = await this.deps.resolveScoutModel();\n\t\t} catch (error) {\n\t\t\treturn { ...unavailable, failure: error instanceof Error ? error.message : String(error) };\n\t\t}\n\t\tif (\"failure\" in modelResolution) {\n\t\t\treturn { ...unavailable, failure: modelResolution.failure };\n\t\t}\n\n\t\t// Registered while this scout's own Agent drives turns, so the reload gate waits it out.\n\t\t// registerInFlightWork is a pure sync map op (cannot throw), so wrapping everything from here\n\t\t// through the end in try/finally guarantees deregistration on every exit path. Optional dep —\n\t\t// a caller that hasn't wired an agent dir through stays invisible to the gate, matching the\n\t\t// behavior before this registration was added.\n\t\tconst deregisterInFlight = this.deps.getAgentDir\n\t\t\t? registerInFlightWork(this.deps.getAgentDir(), \"scout\", query.slice(0, 80))\n\t\t\t: undefined;\n\t\ttry {\n\t\t\tlet turnsUsed = 0;\n\t\t\tlet truncated = false;\n\t\t\tlet lastAssistantText = \"\";\n\t\t\tlet outputTokens = 0;\n\t\t\tconst agent = new Agent({\n\t\t\t\tinitialState: {\n\t\t\t\t\tmodel: modelResolution.model,\n\t\t\t\t\tsystemPrompt: SCOUT_SYSTEM_PROMPT.replace(\"{MAX_TURNS}\", String(turnLimit)),\n\t\t\t\t\ttools: this.deps\n\t\t\t\t\t\t.buildReadOnlyTools(this.deps.getCwd())\n\t\t\t\t\t\t.filter((tool) => READ_ONLY_TOOL_NAMES.has(tool.name)),\n\t\t\t\t},\n\t\t\t\tstreamFn: this.deps.streamFn,\n\t\t\t\tgetApiKey: () => modelResolution.apiKey,\n\t\t\t\tmaxStallTurns: turnLimit,\n\t\t\t});\n\n\t\t\tconst unsubscribe = agent.subscribe((event) => {\n\t\t\t\tif (event.type !== \"message_end\" || event.message.role !== \"assistant\") {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tturnsUsed += 1;\n\t\t\t\tlastAssistantText = assistantText(event.message);\n\t\t\t\toutputTokens += getScoutOutputTokenCount(event.message);\n\t\t\t\tthis.deps.onEvent?.({ type: \"scout_turn\", detail: `turn ${turnsUsed}` });\n\t\t\t\tif (hasFinalAnswer(lastAssistantText)) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (turnsUsed >= turnLimit || outputTokens >= MAX_OUTPUT_TOKENS) {\n\t\t\t\t\ttruncated = true;\n\t\t\t\t\tagent.abort();\n\t\t\t\t}\n\t\t\t});\n\n\t\t\tconst abortScout = (): void => {\n\t\t\t\ttruncated = true;\n\t\t\t\tagent.abort();\n\t\t\t};\n\t\t\tthis.deps.signal?.addEventListener(\"abort\", abortScout, { once: true });\n\t\t\tlet runFailure: string | undefined;\n\t\t\ttry {\n\t\t\t\tawait agent.prompt(query);\n\t\t\t} catch (error) {\n\t\t\t\tif (!truncated && !this.deps.signal?.aborted) {\n\t\t\t\t\trunFailure = error instanceof Error ? error.message : String(error);\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tunsubscribe();\n\t\t\t\tthis.deps.signal?.removeEventListener(\"abort\", abortScout);\n\t\t\t}\n\n\t\t\tconst result = parseScoutAnswer(\n\t\t\t\tlastAssistantText,\n\t\t\t\t(path) => this.deps.fileExists(path),\n\t\t\t\t(path) => this.deps.countLines(path),\n\t\t\t);\n\t\t\tconst finalResult = {\n\t\t\t\t...result,\n\t\t\t\ttruncated: truncated || !hasFinalAnswer(lastAssistantText),\n\t\t\t\tturnsUsed,\n\t\t\t\tfailure: this.deps.signal?.aborted ? \"aborted\" : runFailure,\n\t\t\t};\n\t\t\tthis.deps.onEvent?.({ type: \"scout_end\", detail: finalResult.failure ?? \"ok\" });\n\t\t\treturn finalResult;\n\t\t} finally {\n\t\t\tderegisterInFlight?.();\n\t\t}\n\t}\n}\n\nexport function getScoutOutputTokenCount(message: { usage?: { output?: number } }): number {\n\treturn message.usage?.output ?? 0;\n}\n\nexport function parseScoutAnswer(\n\ttext: string,\n\tfileExists: (path: string) => boolean,\n\tcountLines: (path: string) => number | undefined,\n): Omit<ScoutRunResult, \"truncated\" | \"turnsUsed\" | \"failure\"> {\n\tconst finalAnswer = /<final_answer>([\\s\\S]*?)<\\/final_answer>/i.exec(text)?.[1] ?? text;\n\tconst summaryLines: string[] = [];\n\tconst citations: ScoutCitation[] = [];\n\n\tfor (const rawLine of finalAnswer.split(/\\r?\\n/)) {\n\t\tconst line = rawLine.trim();\n\t\tif (!line) continue;\n\t\tconst citation = parseCitationLine(line, fileExists, countLines);\n\t\tif (citation) {\n\t\t\tcitations.push(citation);\n\t\t\tcontinue;\n\t\t}\n\t\tsummaryLines.push(line);\n\t}\n\n\tconst droppedCitations = citations.filter((citation) => !citation.valid).length;\n\treturn {\n\t\tsummary: summaryLines.join(\"\\n\"),\n\t\tcitations,\n\t\tdroppedCitations,\n\t\tunreliable: citations.length > 0 && droppedCitations / citations.length > 0.5,\n\t};\n}\n\nfunction parseCitationLine(\n\tline: string,\n\tfileExists: (path: string) => boolean,\n\tcountLines: (path: string) => number | undefined,\n): ScoutCitation | undefined {\n\tconst match = /^(.+?):(\\d+)(?:-(\\d+))?$/.exec(line);\n\tif (!match) return undefined;\n\tconst path = match[1].trim();\n\tconst start = Number.parseInt(match[2], 10);\n\tconst end = Number.parseInt(match[3] ?? match[2], 10);\n\tconst lineCount = countLines(path);\n\tconst valid =\n\t\tfileExists(path) &&\n\t\tNumber.isFinite(start) &&\n\t\tNumber.isFinite(end) &&\n\t\tstart >= 1 &&\n\t\tend >= start &&\n\t\t(lineCount === undefined || end <= lineCount);\n\treturn { path, start, end, valid };\n}\n\nfunction clampTurns(maxTurns: number): number {\n\tif (!Number.isFinite(maxTurns)) return MAX_TURNS_DEFAULT;\n\treturn Math.min(MAX_TURNS_HARD_CAP, Math.max(1, Math.trunc(maxTurns)));\n}\n\nfunction emptyResult(): ScoutRunResult {\n\treturn { summary: \"\", citations: [], droppedCitations: 0, unreliable: false, truncated: false, turnsUsed: 0 };\n}\n\nfunction hasFinalAnswer(text: string): boolean {\n\treturn /<final_answer>[\\s\\S]*?<\\/final_answer>/i.test(text);\n}\n\nfunction assistantText(message: { content: unknown }): string {\n\tif (!Array.isArray(message.content)) return \"\";\n\treturn message.content\n\t\t.filter((content): content is { type: \"text\"; text: string } =>\n\t\t\tBoolean(\n\t\t\t\tcontent &&\n\t\t\t\t\ttypeof content === \"object\" &&\n\t\t\t\t\t(content as { type?: unknown }).type === \"text\" &&\n\t\t\t\t\ttypeof (content as { text?: unknown }).text === \"string\",\n\t\t\t),\n\t\t)\n\t\t.map((content) => content.text)\n\t\t.join(\"\\n\");\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AACA,OAAO,EAA0C,KAAK,aAAa,EAAE,MAAM,2BAA2B,CAAC;AACvG,OAAO,EAAwB,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACtF,OAAO,EAAoC,KAAK,KAAK,EAAgB,MAAM,mBAAmB,CAAC;AAG/F,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAGhD,OAAO,KAAK,EAAmB,oBAAoB,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACtH,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAG3D,OAAO,KAAK,EACX,sBAAsB,EACtB,6BAA6B,EAC7B,uBAAuB,EACvB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAGxD,OAAO,EACN,cAAc,EACd,iBAAiB,EACjB,cAAc,EACd,cAAc,EACd,cAAc,EACd,YAAY,EACZ,mBAAmB,EACnB,cAAc,EACd,eAAe,EACf,qBAAqB,EACrB,MAAM,kBAAkB,CAAC;AAE1B,MAAM,WAAW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,0GAA0G;IAC1G,cAAc,CAAC,EAAE,cAAc,CAAC;IAEhC,uEAAuE;IACvE,eAAe,CAAC,EAAE,eAAe,CAAC;IAClC,kEAAkE;IAClE,iBAAiB,CAAC,EAAE,iBAAiB,CAAC;CACtC;AAED,qCAAqC;AACrC,MAAM,WAAW,wBAAwB;IACxC,0BAA0B;IAC1B,OAAO,EAAE,YAAY,CAAC;IACtB,mEAAmE;IACnE,gBAAgB,EAAE,oBAAoB,CAAC;IACvC,wEAAwE;IACxE,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAID,cAAc,4BAA4B,CAAC;AAC3C,YAAY,EACX,YAAY,EACZ,uBAAuB,EACvB,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,kBAAkB,EAClB,cAAc,GACd,MAAM,uBAAuB,CAAC;AAC/B,YAAY,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC5D,YAAY,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACzC,YAAY,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAE7C,OAAO,EACN,qBAAqB,EAErB,iBAAiB,EACjB,mBAAmB,EACnB,cAAc,EACd,cAAc,EACd,cAAc,EACd,eAAe,EACf,cAAc,EACd,cAAc,EACd,YAAY,GACZ,CAAC;AA8CF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAsB,kBAAkB,CAAC,OAAO,GAAE,yBAA8B,GAAG,OAAO,CAAC,wBAAwB,CAAC,CA8SnH","sourcesContent":["import { join } from \"node:path\";\nimport { Agent, type AgentMessage, convertToLlm, type ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { getDefaultSessionDir, SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport { clampThinkingLevel, type Message, type Model, streamSimple } from \"@caupulican/pi-ai\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { AgentSession } from \"./agent-session.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { AuthStorage } from \"./auth-storage.ts\";\nimport { DEFAULT_ACTIVE_TOOL_NAMES } from \"./default-tool-surface.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel, resolveProfileModelSettings } from \"./model-resolver.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { DefaultResourceLoader } from \"./resource-loader.ts\";\nimport { parseResourceProfileInput } from \"./resource-profile-blocks.ts\";\nimport type {\n\tProfileDefinitionInput,\n\tResourceProfileFilterSettings,\n\tResourceProfileSettings,\n} from \"./settings-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { isInstallTelemetryEnabled } from \"./telemetry.ts\";\nimport { time } from \"./timings.ts\";\nimport {\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateWriteTool,\n\twithFileMutationQueue,\n} from \"./tools/index.ts\";\n\nexport interface CreateAgentSessionOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.pi/agent */\n\tagentDir?: string;\n\n\t/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<any>;\n\t/** Thinking level. Default: from settings, then the model's declared default, else 'medium'. */\n\tthinkingLevel?: ThinkingLevel;\n\t/**\n\t * Whether `model` came from an explicit CLI/SDK flag (vs. profile/settings resolution).\n\t * When false (default), the active profile's model is re-applied on reload so live profile\n\t * edits take effect; when true, the explicit launch-time model is preserved across reloads.\n\t */\n\tisExplicitModel?: boolean;\n\t/** Whether `thinkingLevel` came from an explicit flag (see isExplicitModel). */\n\tisExplicitThinking?: boolean;\n\t/** True when this session is a spawned subagent/child — gates durable memory writes. */\n\tisChildSession?: boolean;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (read, bash, edit, write, context_audit,\n\t * goal, delegate, and run_toolkit_script)\n\t * but keep extension/custom tools enabled\n\t */\n\tnoTools?: \"all\" | \"builtin\";\n\t/**\n\t * Optional allowlist of tool names.\n\t *\n\t * When omitted, pi enables the shared default built-in tool surface and leaves extension/custom\n\t * tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/** Optional denylist of tool names to disable. Applies after `tools` when both are provided. */\n\texcludeTools?: string[];\n\t/** Optional resource-profile allow/block filters for tool names. */\n\ttoolProfileFilter?: ResourceProfileFilterSettings;\n\t/** Optional one-shot resource filters or complete situation profiles. Never persisted to disk. */\n\tresourceProfileDefinitions?: Record<string, ResourceProfileSettings | ProfileDefinitionInput>;\n\t/** Optional one-shot profile definitions as JSON or <resource-profile> tag text. Never persisted to disk. */\n\tresourceProfileJson?: string | string[];\n\t/** Optional runtime profile selection. Never persisted to disk. */\n\tresourceProfiles?: string[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd, agentDir, getDefaultSessionDir(cwd, agentDir)) */\n\tsessionManager?: SessionManager;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning if session was restored with a different model than saved */\n\tmodelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport * from \"./agent-session-runtime.ts\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nexport type { PromptTemplate } from \"./prompt-templates.ts\";\nexport type { Skill } from \"./skills.ts\";\nexport type { Tool } from \"./tools/index.ts\";\n\nexport {\n\twithFileMutationQueue,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateWriteTool,\n\tcreateGrepTool,\n\tcreateFindTool,\n\tcreateLsTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\nfunction getAttributionHeaders(\n\tmodel: Model<any>,\n\tsettingsManager: SettingsManager,\n\tsessionId?: string,\n): Record<string, string> | undefined {\n\tif (\n\t\tsessionId &&\n\t\t(model.provider === \"opencode\" || model.provider === \"opencode-go\" || model.baseUrl.includes(\"opencode.ai\"))\n\t) {\n\t\treturn { \"x-opencode-session\": sessionId, \"x-opencode-client\": \"pi\" };\n\t}\n\n\tif (!isInstallTelemetryEnabled(settingsManager)) {\n\t\treturn undefined;\n\t}\n\n\tif (model.provider === \"openrouter\" || model.baseUrl.includes(\"openrouter.ai\")) {\n\t\treturn {\n\t\t\t\"HTTP-Referer\": \"https://pi.dev\",\n\t\t\t\"X-OpenRouter-Title\": \"pi\",\n\t\t\t\"X-OpenRouter-Categories\": \"cli-agent\",\n\t\t};\n\t}\n\n\tif (\n\t\tmodel.provider === \"cloudflare-workers-ai\" ||\n\t\tmodel.provider === \"cloudflare-ai-gateway\" ||\n\t\tmodel.baseUrl.includes(\"api.cloudflare.com\") ||\n\t\tmodel.baseUrl.includes(\"gateway.ai.cloudflare.com\")\n\t) {\n\t\treturn {\n\t\t\t\"User-Agent\": \"pi-coding-agent\",\n\t\t};\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@caupulican/pi-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\t// Use provided or create AuthStorage and ModelRegistry\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst authStorage = options.authStorage ?? AuthStorage.create(authPath);\n\tconst modelRegistry = options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst needsProfileReload =\n\t\toptions.resourceProfileDefinitions !== undefined ||\n\t\toptions.resourceProfileJson !== undefined ||\n\t\toptions.resourceProfiles !== undefined;\n\tif (options.resourceProfileDefinitions) {\n\t\tsettingsManager.addInlineResourceProfileDefinitions(options.resourceProfileDefinitions);\n\t}\n\tif (options.resourceProfileJson) {\n\t\tconst inputs = Array.isArray(options.resourceProfileJson)\n\t\t\t? options.resourceProfileJson\n\t\t\t: [options.resourceProfileJson];\n\t\tfor (const input of inputs) {\n\t\t\tsettingsManager.addInlineResourceProfileDefinitions(parseResourceProfileInput(input).profiles);\n\t\t}\n\t}\n\tif (options.resourceProfiles !== undefined) {\n\t\tsettingsManager.setRuntimeResourceProfiles(options.resourceProfiles);\n\t}\n\tconst sessionManager =\n\t\toptions.sessionManager ?? SessionManager.create(cwd, agentDir, getDefaultSessionDir(cwd, agentDir));\n\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t} else if (needsProfileReload) {\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\n\t// Check if session has existing data to restore\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst hasExistingSession = existingSession.messages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\tconst activeProfileNames = settingsManager.getActiveResourceProfileNames();\n\tif (activeProfileNames.length > 0) {\n\t\tconst profileSettings = resolveProfileModelSettings({\n\t\t\tactiveProfileNames,\n\t\t\tregistry: settingsManager.getProfileRegistry(),\n\t\t\tmodelRegistry,\n\t\t\tcwd,\n\t\t});\n\t\tif (profileSettings.error) {\n\t\t\tmodelFallbackMessage = `Profile model resolution error: ${profileSettings.error}`;\n\t\t}\n\t\tif (!model && profileSettings.model) {\n\t\t\tmodel = profileSettings.model;\n\t\t}\n\t\tif (thinkingLevel === undefined && profileSettings.thinkingLevel) {\n\t\t\tthinkingLevel = profileSettings.thinkingLevel;\n\t\t}\n\t}\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tconst restoredModel = modelRegistry.find(existingSession.model.provider, existingSession.model.modelId);\n\t\tif (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {\n\t\t\tmodel = restoredModel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n\t\t}\n\t}\n\n\t// If still no model, use findInitialModel (checks settings default, then provider defaults)\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelRegistry,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (thinkingLevel === undefined && !(hasExistingSession && hasThinkingEntry)) {\n\t\t\tthinkingLevel = result.thinkingLevel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = formatNoModelsAvailableMessage();\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n\t\t}\n\t}\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? model?.defaultThinkingLevel ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to the user's default, then the selected model's own default.\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel =\n\t\t\tsettingsManager.getDefaultThinkingLevel() ?? model?.defaultThinkingLevel ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model) {\n\t\tthinkingLevel = \"off\";\n\t} else {\n\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t}\n\n\tconst defaultActiveToolNames = [\n\t\t...DEFAULT_ACTIVE_TOOL_NAMES,\n\t\t...(settingsManager.getScoutSettings().enabled ? [\"context_scout\"] : []),\n\t];\n\tconst toolProfileFilter = options.toolProfileFilter ?? settingsManager.getResourceProfileFilter(\"tools\");\n\tconst allowedToolNames = options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\tconst excludedToolNames = options.excludeTools;\n\tconst excludedToolNameSet = excludedToolNames ? new Set(excludedToolNames) : undefined;\n\tconst initialActiveToolNames: string[] = (\n\t\toptions.tools ? [...options.tools] : options.noTools ? [] : defaultActiveToolNames\n\t).filter((name) => !excludedToolNameSet?.has(name));\n\n\tlet agent: Agent;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\treturn converted.map((msg) => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tstreamFn: async (model, context, options) => {\n\t\t\tconst auth = await modelRegistry.getApiKeyAndHeaders(model);\n\t\t\tif (!auth.ok) {\n\t\t\t\tthrow new Error(auth.error);\n\t\t\t}\n\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\tconst httpIdleTimeoutMs = settingsManager.getHttpIdleTimeoutMs();\n\t\t\t// SDKs treat timeout=0 as 0ms (immediate timeout), not \"no timeout\".\n\t\t\t// Use max int32 to effectively disable the timeout.\n\t\t\tconst effectiveTimeoutMs = httpIdleTimeoutMs === 0 ? 2147483647 : httpIdleTimeoutMs;\n\t\t\tconst timeoutMs = options?.timeoutMs ?? providerRetrySettings.timeoutMs ?? effectiveTimeoutMs;\n\t\t\tconst websocketConnectTimeoutMs =\n\t\t\t\toptions?.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();\n\t\t\tconst attributionHeaders = getAttributionHeaders(model, settingsManager, options?.sessionId);\n\t\t\treturn streamSimple(model, context, {\n\t\t\t\t...options,\n\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\tonAuthRejection:\n\t\t\t\t\tauth.apiKey && model.provider === \"openai-codex\"\n\t\t\t\t\t\t? async () => modelRegistry.recoverRejectedOAuthApiKey(model.provider, auth.apiKey as string)\n\t\t\t\t\t\t: options?.onAuthRejection,\n\t\t\t\ttimeoutMs,\n\t\t\t\twebsocketConnectTimeoutMs,\n\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t\theaders:\n\t\t\t\t\tattributionHeaders || auth.headers || options?.headers\n\t\t\t\t\t\t? { ...attributionHeaders, ...auth.headers, ...options?.headers }\n\t\t\t\t\t\t: undefined,\n\t\t\t});\n\t\t},\n\t\tonPayload: async (payload, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t},\n\t\tonResponse: async (response, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait runner.emit({\n\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers,\n\t\t\t});\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner) return messages;\n\t\t\treturn runner.emitContext(messages);\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t\tmaxStallTurns: settingsManager.getAutonomySettings().maxStallTurns,\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.state.messages = existingSession.messages;\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd,\n\t\tagentDir,\n\t\tscopedModels: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tmodelRegistry,\n\t\tinitialActiveToolNames,\n\t\tallowedToolNames,\n\t\texcludedToolNames,\n\t\textensionRunnerRef,\n\t\ttoolProfileFilter,\n\t\tisExplicitModel: options.isExplicitModel ?? options.model != null,\n\t\tisExplicitThinking: options.isExplicitThinking ?? options.thinkingLevel !== undefined,\n\t\tisChildSession: options.isChildSession ?? process.env.PI_CHILD_SESSION === \"1\",\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t});\n\ttry {\n\t\t// The initial runtime has now bound providers from profile-granted extensions. Re-resolve the\n\t\t// profile model against that authoritative registry generation, then resync model capability.\n\t\tawait session.reapplyActiveProfileModelSettings();\n\t\tif (modelFallbackMessage?.startsWith(\"Profile model resolution error:\")) {\n\t\t\tmodelFallbackMessage = undefined;\n\t\t}\n\t} catch (error) {\n\t\t// Preserve the established non-fatal fallback for a genuinely unresolved profile model.\n\t\tif (!modelFallbackMessage?.startsWith(\"Profile model resolution error:\")) {\n\t\t\tsession.dispose();\n\t\t\tthrow error;\n\t\t}\n\t}\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]}
1
+ {"version":3,"file":"sdk.d.ts","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAA0C,KAAK,aAAa,EAAE,MAAM,2BAA2B,CAAC;AACvG,OAAO,EAAwB,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACtF,OAAO,EAAoC,KAAK,KAAK,EAAgB,MAAM,mBAAmB,CAAC;AAI/F,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAElD,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAGhD,OAAO,KAAK,EAAmB,oBAAoB,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AACtH,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAEpD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAG3D,OAAO,KAAK,EACX,sBAAsB,EACtB,6BAA6B,EAC7B,uBAAuB,EACvB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAGxD,OAAO,EACN,cAAc,EACd,iBAAiB,EACjB,cAAc,EACd,cAAc,EACd,cAAc,EACd,YAAY,EACZ,mBAAmB,EACnB,cAAc,EACd,eAAe,EACf,qBAAqB,EACrB,MAAM,kBAAkB,CAAC;AAE1B,MAAM,WAAW,yBAAyB;IACzC,4EAA4E;IAC5E,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,oDAAoD;IACpD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAElB,oFAAoF;IACpF,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B,uFAAuF;IACvF,aAAa,CAAC,EAAE,aAAa,CAAC;IAE9B,iEAAiE;IACjE,KAAK,CAAC,EAAE,KAAK,CAAC,GAAG,CAAC,CAAC;IACnB,g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AC;IACvC,wEAAwE;IACxE,oBAAoB,CAAC,EAAE,MAAM,CAAC;CAC9B;AAID,cAAc,4BAA4B,CAAC;AAC3C,YAAY,EACX,YAAY,EACZ,uBAAuB,EACvB,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,kBAAkB,EAClB,cAAc,GACd,MAAM,uBAAuB,CAAC;AAC/B,YAAY,EAAE,cAAc,EAAE,MAAM,uBAAuB,CAAC;AAC5D,YAAY,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AACzC,YAAY,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAE7C,OAAO,EACN,qBAAqB,EAErB,iBAAiB,EACjB,mBAAmB,EACnB,cAAc,EACd,cAAc,EACd,cAAc,EACd,eAAe,EACf,cAAc,EACd,cAAc,EACd,YAAY,GACZ,CAAC;AA8CF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAkCG;AACH,wBAAsB,kBAAkB,CAAC,OAAO,GAAE,yBAA8B,GAAG,OAAO,CAAC,wBAAwB,CAAC,CA8SnH","sourcesContent":["import { Agent, type AgentMessage, convertToLlm, type ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { getDefaultSessionDir, SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport { clampThinkingLevel, type Message, type Model, streamSimple } from \"@caupulican/pi-ai\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { configFile } from \"./agent-paths.ts\";\nimport { AgentSession } from \"./agent-session.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { AuthStorage } from \"./auth-storage.ts\";\nimport { DEFAULT_ACTIVE_TOOL_NAMES } from \"./default-tool-surface.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel, resolveProfileModelSettings } from \"./model-resolver.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { DefaultResourceLoader } from \"./resource-loader.ts\";\nimport { parseResourceProfileInput } from \"./resource-profile-blocks.ts\";\nimport type {\n\tProfileDefinitionInput,\n\tResourceProfileFilterSettings,\n\tResourceProfileSettings,\n} from \"./settings-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { isInstallTelemetryEnabled } from \"./telemetry.ts\";\nimport { time } from \"./timings.ts\";\nimport {\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateWriteTool,\n\twithFileMutationQueue,\n} from \"./tools/index.ts\";\n\nexport interface CreateAgentSessionOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.pi/agent */\n\tagentDir?: string;\n\n\t/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<any>;\n\t/** Thinking level. Default: from settings, then the model's declared default, else 'medium'. */\n\tthinkingLevel?: ThinkingLevel;\n\t/**\n\t * Whether `model` came from an explicit CLI/SDK flag (vs. profile/settings resolution).\n\t * When false (default), the active profile's model is re-applied on reload so live profile\n\t * edits take effect; when true, the explicit launch-time model is preserved across reloads.\n\t */\n\tisExplicitModel?: boolean;\n\t/** Whether `thinkingLevel` came from an explicit flag (see isExplicitModel). */\n\tisExplicitThinking?: boolean;\n\t/** True when this session is a spawned subagent/child — gates durable memory writes. */\n\tisChildSession?: boolean;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (read, bash, edit, write, context_audit,\n\t * goal, delegate, and run_toolkit_script)\n\t * but keep extension/custom tools enabled\n\t */\n\tnoTools?: \"all\" | \"builtin\";\n\t/**\n\t * Optional allowlist of tool names.\n\t *\n\t * When omitted, pi enables the shared default built-in tool surface and leaves extension/custom\n\t * tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/** Optional denylist of tool names to disable. Applies after `tools` when both are provided. */\n\texcludeTools?: string[];\n\t/** Optional resource-profile allow/block filters for tool names. */\n\ttoolProfileFilter?: ResourceProfileFilterSettings;\n\t/** Optional one-shot resource filters or complete situation profiles. Never persisted to disk. */\n\tresourceProfileDefinitions?: Record<string, ResourceProfileSettings | ProfileDefinitionInput>;\n\t/** Optional one-shot profile definitions as JSON or <resource-profile> tag text. Never persisted to disk. */\n\tresourceProfileJson?: string | string[];\n\t/** Optional runtime profile selection. Never persisted to disk. */\n\tresourceProfiles?: string[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd, agentDir, getDefaultSessionDir(cwd, agentDir)) */\n\tsessionManager?: SessionManager;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning if session was restored with a different model than saved */\n\tmodelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport * from \"./agent-session-runtime.ts\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nexport type { PromptTemplate } from \"./prompt-templates.ts\";\nexport type { Skill } from \"./skills.ts\";\nexport type { Tool } from \"./tools/index.ts\";\n\nexport {\n\twithFileMutationQueue,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateWriteTool,\n\tcreateGrepTool,\n\tcreateFindTool,\n\tcreateLsTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\nfunction getAttributionHeaders(\n\tmodel: Model<any>,\n\tsettingsManager: SettingsManager,\n\tsessionId?: string,\n): Record<string, string> | undefined {\n\tif (\n\t\tsessionId &&\n\t\t(model.provider === \"opencode\" || model.provider === \"opencode-go\" || model.baseUrl.includes(\"opencode.ai\"))\n\t) {\n\t\treturn { \"x-opencode-session\": sessionId, \"x-opencode-client\": \"pi\" };\n\t}\n\n\tif (!isInstallTelemetryEnabled(settingsManager)) {\n\t\treturn undefined;\n\t}\n\n\tif (model.provider === \"openrouter\" || model.baseUrl.includes(\"openrouter.ai\")) {\n\t\treturn {\n\t\t\t\"HTTP-Referer\": \"https://pi.dev\",\n\t\t\t\"X-OpenRouter-Title\": \"pi\",\n\t\t\t\"X-OpenRouter-Categories\": \"cli-agent\",\n\t\t};\n\t}\n\n\tif (\n\t\tmodel.provider === \"cloudflare-workers-ai\" ||\n\t\tmodel.provider === \"cloudflare-ai-gateway\" ||\n\t\tmodel.baseUrl.includes(\"api.cloudflare.com\") ||\n\t\tmodel.baseUrl.includes(\"gateway.ai.cloudflare.com\")\n\t) {\n\t\treturn {\n\t\t\t\"User-Agent\": \"pi-coding-agent\",\n\t\t};\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@caupulican/pi-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\t// Use provided or create AuthStorage and ModelRegistry\n\tconst authPath = options.agentDir ? configFile(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? configFile(agentDir, \"models.json\") : undefined;\n\tconst authStorage = options.authStorage ?? AuthStorage.create(authPath);\n\tconst modelRegistry = options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst needsProfileReload =\n\t\toptions.resourceProfileDefinitions !== undefined ||\n\t\toptions.resourceProfileJson !== undefined ||\n\t\toptions.resourceProfiles !== undefined;\n\tif (options.resourceProfileDefinitions) {\n\t\tsettingsManager.addInlineResourceProfileDefinitions(options.resourceProfileDefinitions);\n\t}\n\tif (options.resourceProfileJson) {\n\t\tconst inputs = Array.isArray(options.resourceProfileJson)\n\t\t\t? options.resourceProfileJson\n\t\t\t: [options.resourceProfileJson];\n\t\tfor (const input of inputs) {\n\t\t\tsettingsManager.addInlineResourceProfileDefinitions(parseResourceProfileInput(input).profiles);\n\t\t}\n\t}\n\tif (options.resourceProfiles !== undefined) {\n\t\tsettingsManager.setRuntimeResourceProfiles(options.resourceProfiles);\n\t}\n\tconst sessionManager =\n\t\toptions.sessionManager ?? SessionManager.create(cwd, agentDir, getDefaultSessionDir(cwd, agentDir));\n\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t} else if (needsProfileReload) {\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\n\t// Check if session has existing data to restore\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst hasExistingSession = existingSession.messages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\tconst activeProfileNames = settingsManager.getActiveResourceProfileNames();\n\tif (activeProfileNames.length > 0) {\n\t\tconst profileSettings = resolveProfileModelSettings({\n\t\t\tactiveProfileNames,\n\t\t\tregistry: settingsManager.getProfileRegistry(),\n\t\t\tmodelRegistry,\n\t\t\tcwd,\n\t\t});\n\t\tif (profileSettings.error) {\n\t\t\tmodelFallbackMessage = `Profile model resolution error: ${profileSettings.error}`;\n\t\t}\n\t\tif (!model && profileSettings.model) {\n\t\t\tmodel = profileSettings.model;\n\t\t}\n\t\tif (thinkingLevel === undefined && profileSettings.thinkingLevel) {\n\t\t\tthinkingLevel = profileSettings.thinkingLevel;\n\t\t}\n\t}\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tconst restoredModel = modelRegistry.find(existingSession.model.provider, existingSession.model.modelId);\n\t\tif (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {\n\t\t\tmodel = restoredModel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n\t\t}\n\t}\n\n\t// If still no model, use findInitialModel (checks settings default, then provider defaults)\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelRegistry,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (thinkingLevel === undefined && !(hasExistingSession && hasThinkingEntry)) {\n\t\t\tthinkingLevel = result.thinkingLevel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = formatNoModelsAvailableMessage();\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n\t\t}\n\t}\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? model?.defaultThinkingLevel ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to the user's default, then the selected model's own default.\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel =\n\t\t\tsettingsManager.getDefaultThinkingLevel() ?? model?.defaultThinkingLevel ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model) {\n\t\tthinkingLevel = \"off\";\n\t} else {\n\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t}\n\n\tconst defaultActiveToolNames = [\n\t\t...DEFAULT_ACTIVE_TOOL_NAMES,\n\t\t...(settingsManager.getScoutSettings().enabled ? [\"context_scout\"] : []),\n\t];\n\tconst toolProfileFilter = options.toolProfileFilter ?? settingsManager.getResourceProfileFilter(\"tools\");\n\tconst allowedToolNames = options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\tconst excludedToolNames = options.excludeTools;\n\tconst excludedToolNameSet = excludedToolNames ? new Set(excludedToolNames) : undefined;\n\tconst initialActiveToolNames: string[] = (\n\t\toptions.tools ? [...options.tools] : options.noTools ? [] : defaultActiveToolNames\n\t).filter((name) => !excludedToolNameSet?.has(name));\n\n\tlet agent: Agent;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\treturn converted.map((msg) => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tstreamFn: async (model, context, options) => {\n\t\t\tconst auth = await modelRegistry.getApiKeyAndHeaders(model);\n\t\t\tif (!auth.ok) {\n\t\t\t\tthrow new Error(auth.error);\n\t\t\t}\n\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\tconst httpIdleTimeoutMs = settingsManager.getHttpIdleTimeoutMs();\n\t\t\t// SDKs treat timeout=0 as 0ms (immediate timeout), not \"no timeout\".\n\t\t\t// Use max int32 to effectively disable the timeout.\n\t\t\tconst effectiveTimeoutMs = httpIdleTimeoutMs === 0 ? 2147483647 : httpIdleTimeoutMs;\n\t\t\tconst timeoutMs = options?.timeoutMs ?? providerRetrySettings.timeoutMs ?? effectiveTimeoutMs;\n\t\t\tconst websocketConnectTimeoutMs =\n\t\t\t\toptions?.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();\n\t\t\tconst attributionHeaders = getAttributionHeaders(model, settingsManager, options?.sessionId);\n\t\t\treturn streamSimple(model, context, {\n\t\t\t\t...options,\n\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\tonAuthRejection:\n\t\t\t\t\tauth.apiKey && model.provider === \"openai-codex\"\n\t\t\t\t\t\t? async () => modelRegistry.recoverRejectedOAuthApiKey(model.provider, auth.apiKey as string)\n\t\t\t\t\t\t: options?.onAuthRejection,\n\t\t\t\ttimeoutMs,\n\t\t\t\twebsocketConnectTimeoutMs,\n\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t\theaders:\n\t\t\t\t\tattributionHeaders || auth.headers || options?.headers\n\t\t\t\t\t\t? { ...attributionHeaders, ...auth.headers, ...options?.headers }\n\t\t\t\t\t\t: undefined,\n\t\t\t});\n\t\t},\n\t\tonPayload: async (payload, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t},\n\t\tonResponse: async (response, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait runner.emit({\n\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers,\n\t\t\t});\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner) return messages;\n\t\t\treturn runner.emitContext(messages);\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t\tmaxStallTurns: settingsManager.getAutonomySettings().maxStallTurns,\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.state.messages = existingSession.messages;\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd,\n\t\tagentDir,\n\t\tscopedModels: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tmodelRegistry,\n\t\tinitialActiveToolNames,\n\t\tallowedToolNames,\n\t\texcludedToolNames,\n\t\textensionRunnerRef,\n\t\ttoolProfileFilter,\n\t\tisExplicitModel: options.isExplicitModel ?? options.model != null,\n\t\tisExplicitThinking: options.isExplicitThinking ?? options.thinkingLevel !== undefined,\n\t\tisChildSession: options.isChildSession ?? process.env.PI_CHILD_SESSION === \"1\",\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t});\n\ttry {\n\t\t// The initial runtime has now bound providers from profile-granted extensions. Re-resolve the\n\t\t// profile model against that authoritative registry generation, then resync model capability.\n\t\tawait session.reapplyActiveProfileModelSettings();\n\t\tif (modelFallbackMessage?.startsWith(\"Profile model resolution error:\")) {\n\t\t\tmodelFallbackMessage = undefined;\n\t\t}\n\t} catch (error) {\n\t\t// Preserve the established non-fatal fallback for a genuinely unresolved profile model.\n\t\tif (!modelFallbackMessage?.startsWith(\"Profile model resolution error:\")) {\n\t\t\tsession.dispose();\n\t\t\tthrow error;\n\t\t}\n\t}\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]}
package/dist/core/sdk.js CHANGED
@@ -1,9 +1,9 @@
1
- import { join } from "node:path";
2
1
  import { Agent, convertToLlm } from "@caupulican/pi-agent-core";
3
2
  import { getDefaultSessionDir, SessionManager } from "@caupulican/pi-agent-core/node";
4
3
  import { clampThinkingLevel, streamSimple } from "@caupulican/pi-ai";
5
4
  import { getAgentDir } from "../config.js";
6
5
  import { resolvePath } from "../utils/paths.js";
6
+ import { configFile } from "./agent-paths.js";
7
7
  import { AgentSession } from "./agent-session.js";
8
8
  import { formatNoModelsAvailableMessage } from "./auth-guidance.js";
9
9
  import { AuthStorage } from "./auth-storage.js";
@@ -91,8 +91,8 @@ export async function createAgentSession(options = {}) {
91
91
  const agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();
92
92
  let resourceLoader = options.resourceLoader;
93
93
  // Use provided or create AuthStorage and ModelRegistry
94
- const authPath = options.agentDir ? join(agentDir, "auth.json") : undefined;
95
- const modelsPath = options.agentDir ? join(agentDir, "models.json") : undefined;
94
+ const authPath = options.agentDir ? configFile(agentDir, "auth.json") : undefined;
95
+ const modelsPath = options.agentDir ? configFile(agentDir, "models.json") : undefined;
96
96
  const authStorage = options.authStorage ?? AuthStorage.create(authPath);
97
97
  const modelRegistry = options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);
98
98
  const settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);
@@ -1 +1 @@
1
- {"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAC;AACjC,OAAO,EAAE,KAAK,EAAqB,YAAY,EAAsB,MAAM,2BAA2B,CAAC;AACvG,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACtF,OAAO,EAAE,kBAAkB,EAA4B,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAC/F,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,8BAA8B,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAA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AAE,CAAC;QAChB,wFAAwF;QACxF,IAAI,CAAC,oBAAoB,EAAE,UAAU,CAAC,iCAAiC,CAAC,EAAE,CAAC;YAC1E,OAAO,CAAC,OAAO,EAAE,CAAC;YAClB,MAAM,KAAK,CAAC;QACb,CAAC;IACF,CAAC;IACD,MAAM,gBAAgB,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;IAExD,OAAO;QACN,OAAO;QACP,gBAAgB;QAChB,oBAAoB;KACpB,CAAC;AAAA,CACF","sourcesContent":["import { join } from \"node:path\";\nimport { Agent, type AgentMessage, convertToLlm, type ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { getDefaultSessionDir, SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport { clampThinkingLevel, type Message, type Model, streamSimple } from \"@caupulican/pi-ai\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { AgentSession } from \"./agent-session.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { AuthStorage } from \"./auth-storage.ts\";\nimport { DEFAULT_ACTIVE_TOOL_NAMES } from \"./default-tool-surface.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel, resolveProfileModelSettings } from \"./model-resolver.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { DefaultResourceLoader } from \"./resource-loader.ts\";\nimport { parseResourceProfileInput } from \"./resource-profile-blocks.ts\";\nimport type {\n\tProfileDefinitionInput,\n\tResourceProfileFilterSettings,\n\tResourceProfileSettings,\n} from \"./settings-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { isInstallTelemetryEnabled } from \"./telemetry.ts\";\nimport { time } from \"./timings.ts\";\nimport {\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateWriteTool,\n\twithFileMutationQueue,\n} from \"./tools/index.ts\";\n\nexport interface CreateAgentSessionOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.pi/agent */\n\tagentDir?: string;\n\n\t/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<any>;\n\t/** Thinking level. Default: from settings, then the model's declared default, else 'medium'. */\n\tthinkingLevel?: ThinkingLevel;\n\t/**\n\t * Whether `model` came from an explicit CLI/SDK flag (vs. profile/settings resolution).\n\t * When false (default), the active profile's model is re-applied on reload so live profile\n\t * edits take effect; when true, the explicit launch-time model is preserved across reloads.\n\t */\n\tisExplicitModel?: boolean;\n\t/** Whether `thinkingLevel` came from an explicit flag (see isExplicitModel). */\n\tisExplicitThinking?: boolean;\n\t/** True when this session is a spawned subagent/child — gates durable memory writes. */\n\tisChildSession?: boolean;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (read, bash, edit, write, context_audit,\n\t * goal, delegate, and run_toolkit_script)\n\t * but keep extension/custom tools enabled\n\t */\n\tnoTools?: \"all\" | \"builtin\";\n\t/**\n\t * Optional allowlist of tool names.\n\t *\n\t * When omitted, pi enables the shared default built-in tool surface and leaves extension/custom\n\t * tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/** Optional denylist of tool names to disable. Applies after `tools` when both are provided. */\n\texcludeTools?: string[];\n\t/** Optional resource-profile allow/block filters for tool names. */\n\ttoolProfileFilter?: ResourceProfileFilterSettings;\n\t/** Optional one-shot resource filters or complete situation profiles. Never persisted to disk. */\n\tresourceProfileDefinitions?: Record<string, ResourceProfileSettings | ProfileDefinitionInput>;\n\t/** Optional one-shot profile definitions as JSON or <resource-profile> tag text. Never persisted to disk. */\n\tresourceProfileJson?: string | string[];\n\t/** Optional runtime profile selection. Never persisted to disk. */\n\tresourceProfiles?: string[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd, agentDir, getDefaultSessionDir(cwd, agentDir)) */\n\tsessionManager?: SessionManager;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning if session was restored with a different model than saved */\n\tmodelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport * from \"./agent-session-runtime.ts\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nexport type { PromptTemplate } from \"./prompt-templates.ts\";\nexport type { Skill } from \"./skills.ts\";\nexport type { Tool } from \"./tools/index.ts\";\n\nexport {\n\twithFileMutationQueue,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateWriteTool,\n\tcreateGrepTool,\n\tcreateFindTool,\n\tcreateLsTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\nfunction getAttributionHeaders(\n\tmodel: Model<any>,\n\tsettingsManager: SettingsManager,\n\tsessionId?: string,\n): Record<string, string> | undefined {\n\tif (\n\t\tsessionId &&\n\t\t(model.provider === \"opencode\" || model.provider === \"opencode-go\" || model.baseUrl.includes(\"opencode.ai\"))\n\t) {\n\t\treturn { \"x-opencode-session\": sessionId, \"x-opencode-client\": \"pi\" };\n\t}\n\n\tif (!isInstallTelemetryEnabled(settingsManager)) {\n\t\treturn undefined;\n\t}\n\n\tif (model.provider === \"openrouter\" || model.baseUrl.includes(\"openrouter.ai\")) {\n\t\treturn {\n\t\t\t\"HTTP-Referer\": \"https://pi.dev\",\n\t\t\t\"X-OpenRouter-Title\": \"pi\",\n\t\t\t\"X-OpenRouter-Categories\": \"cli-agent\",\n\t\t};\n\t}\n\n\tif (\n\t\tmodel.provider === \"cloudflare-workers-ai\" ||\n\t\tmodel.provider === \"cloudflare-ai-gateway\" ||\n\t\tmodel.baseUrl.includes(\"api.cloudflare.com\") ||\n\t\tmodel.baseUrl.includes(\"gateway.ai.cloudflare.com\")\n\t) {\n\t\treturn {\n\t\t\t\"User-Agent\": \"pi-coding-agent\",\n\t\t};\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@caupulican/pi-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\t// Use provided or create AuthStorage and ModelRegistry\n\tconst authPath = options.agentDir ? join(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? join(agentDir, \"models.json\") : undefined;\n\tconst authStorage = options.authStorage ?? AuthStorage.create(authPath);\n\tconst modelRegistry = options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst needsProfileReload =\n\t\toptions.resourceProfileDefinitions !== undefined ||\n\t\toptions.resourceProfileJson !== undefined ||\n\t\toptions.resourceProfiles !== undefined;\n\tif (options.resourceProfileDefinitions) {\n\t\tsettingsManager.addInlineResourceProfileDefinitions(options.resourceProfileDefinitions);\n\t}\n\tif (options.resourceProfileJson) {\n\t\tconst inputs = Array.isArray(options.resourceProfileJson)\n\t\t\t? options.resourceProfileJson\n\t\t\t: [options.resourceProfileJson];\n\t\tfor (const input of inputs) {\n\t\t\tsettingsManager.addInlineResourceProfileDefinitions(parseResourceProfileInput(input).profiles);\n\t\t}\n\t}\n\tif (options.resourceProfiles !== undefined) {\n\t\tsettingsManager.setRuntimeResourceProfiles(options.resourceProfiles);\n\t}\n\tconst sessionManager =\n\t\toptions.sessionManager ?? SessionManager.create(cwd, agentDir, getDefaultSessionDir(cwd, agentDir));\n\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t} else if (needsProfileReload) {\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\n\t// Check if session has existing data to restore\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst hasExistingSession = existingSession.messages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\tconst activeProfileNames = settingsManager.getActiveResourceProfileNames();\n\tif (activeProfileNames.length > 0) {\n\t\tconst profileSettings = resolveProfileModelSettings({\n\t\t\tactiveProfileNames,\n\t\t\tregistry: settingsManager.getProfileRegistry(),\n\t\t\tmodelRegistry,\n\t\t\tcwd,\n\t\t});\n\t\tif (profileSettings.error) {\n\t\t\tmodelFallbackMessage = `Profile model resolution error: ${profileSettings.error}`;\n\t\t}\n\t\tif (!model && profileSettings.model) {\n\t\t\tmodel = profileSettings.model;\n\t\t}\n\t\tif (thinkingLevel === undefined && profileSettings.thinkingLevel) {\n\t\t\tthinkingLevel = profileSettings.thinkingLevel;\n\t\t}\n\t}\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tconst restoredModel = modelRegistry.find(existingSession.model.provider, existingSession.model.modelId);\n\t\tif (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {\n\t\t\tmodel = restoredModel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n\t\t}\n\t}\n\n\t// If still no model, use findInitialModel (checks settings default, then provider defaults)\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelRegistry,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (thinkingLevel === undefined && !(hasExistingSession && hasThinkingEntry)) {\n\t\t\tthinkingLevel = result.thinkingLevel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = formatNoModelsAvailableMessage();\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n\t\t}\n\t}\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? model?.defaultThinkingLevel ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to the user's default, then the selected model's own default.\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel =\n\t\t\tsettingsManager.getDefaultThinkingLevel() ?? model?.defaultThinkingLevel ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model) {\n\t\tthinkingLevel = \"off\";\n\t} else {\n\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t}\n\n\tconst defaultActiveToolNames = [\n\t\t...DEFAULT_ACTIVE_TOOL_NAMES,\n\t\t...(settingsManager.getScoutSettings().enabled ? [\"context_scout\"] : []),\n\t];\n\tconst toolProfileFilter = options.toolProfileFilter ?? settingsManager.getResourceProfileFilter(\"tools\");\n\tconst allowedToolNames = options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\tconst excludedToolNames = options.excludeTools;\n\tconst excludedToolNameSet = excludedToolNames ? new Set(excludedToolNames) : undefined;\n\tconst initialActiveToolNames: string[] = (\n\t\toptions.tools ? [...options.tools] : options.noTools ? [] : defaultActiveToolNames\n\t).filter((name) => !excludedToolNameSet?.has(name));\n\n\tlet agent: Agent;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\treturn converted.map((msg) => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tstreamFn: async (model, context, options) => {\n\t\t\tconst auth = await modelRegistry.getApiKeyAndHeaders(model);\n\t\t\tif (!auth.ok) {\n\t\t\t\tthrow new Error(auth.error);\n\t\t\t}\n\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\tconst httpIdleTimeoutMs = settingsManager.getHttpIdleTimeoutMs();\n\t\t\t// SDKs treat timeout=0 as 0ms (immediate timeout), not \"no timeout\".\n\t\t\t// Use max int32 to effectively disable the timeout.\n\t\t\tconst effectiveTimeoutMs = httpIdleTimeoutMs === 0 ? 2147483647 : httpIdleTimeoutMs;\n\t\t\tconst timeoutMs = options?.timeoutMs ?? providerRetrySettings.timeoutMs ?? effectiveTimeoutMs;\n\t\t\tconst websocketConnectTimeoutMs =\n\t\t\t\toptions?.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();\n\t\t\tconst attributionHeaders = getAttributionHeaders(model, settingsManager, options?.sessionId);\n\t\t\treturn streamSimple(model, context, {\n\t\t\t\t...options,\n\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\tonAuthRejection:\n\t\t\t\t\tauth.apiKey && model.provider === \"openai-codex\"\n\t\t\t\t\t\t? async () => modelRegistry.recoverRejectedOAuthApiKey(model.provider, auth.apiKey as string)\n\t\t\t\t\t\t: options?.onAuthRejection,\n\t\t\t\ttimeoutMs,\n\t\t\t\twebsocketConnectTimeoutMs,\n\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t\theaders:\n\t\t\t\t\tattributionHeaders || auth.headers || options?.headers\n\t\t\t\t\t\t? { ...attributionHeaders, ...auth.headers, ...options?.headers }\n\t\t\t\t\t\t: undefined,\n\t\t\t});\n\t\t},\n\t\tonPayload: async (payload, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t},\n\t\tonResponse: async (response, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait runner.emit({\n\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers,\n\t\t\t});\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner) return messages;\n\t\t\treturn runner.emitContext(messages);\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t\tmaxStallTurns: settingsManager.getAutonomySettings().maxStallTurns,\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.state.messages = existingSession.messages;\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd,\n\t\tagentDir,\n\t\tscopedModels: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tmodelRegistry,\n\t\tinitialActiveToolNames,\n\t\tallowedToolNames,\n\t\texcludedToolNames,\n\t\textensionRunnerRef,\n\t\ttoolProfileFilter,\n\t\tisExplicitModel: options.isExplicitModel ?? options.model != null,\n\t\tisExplicitThinking: options.isExplicitThinking ?? options.thinkingLevel !== undefined,\n\t\tisChildSession: options.isChildSession ?? process.env.PI_CHILD_SESSION === \"1\",\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t});\n\ttry {\n\t\t// The initial runtime has now bound providers from profile-granted extensions. Re-resolve the\n\t\t// profile model against that authoritative registry generation, then resync model capability.\n\t\tawait session.reapplyActiveProfileModelSettings();\n\t\tif (modelFallbackMessage?.startsWith(\"Profile model resolution error:\")) {\n\t\t\tmodelFallbackMessage = undefined;\n\t\t}\n\t} catch (error) {\n\t\t// Preserve the established non-fatal fallback for a genuinely unresolved profile model.\n\t\tif (!modelFallbackMessage?.startsWith(\"Profile model resolution error:\")) {\n\t\t\tsession.dispose();\n\t\t\tthrow error;\n\t\t}\n\t}\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]}
1
+ {"version":3,"file":"sdk.js","sourceRoot":"","sources":["../../src/core/sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAqB,YAAY,EAAsB,MAAM,2BAA2B,CAAC;AACvG,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACtF,OAAO,EAAE,kBAAkB,EAA4B,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAC/F,OAAO,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAC9C,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OAAO,EAAE,8BAA8B,EAAE,MAAM,oBAAoB,CAAC;AACpE,OAAO,EAAE,WAAW,EAAE,MAAM,mBA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AC;QAChB,wFAAwF;QACxF,IAAI,CAAC,oBAAoB,EAAE,UAAU,CAAC,iCAAiC,CAAC,EAAE,CAAC;YAC1E,OAAO,CAAC,OAAO,EAAE,CAAC;YAClB,MAAM,KAAK,CAAC;QACb,CAAC;IACF,CAAC;IACD,MAAM,gBAAgB,GAAG,cAAc,CAAC,aAAa,EAAE,CAAC;IAExD,OAAO;QACN,OAAO;QACP,gBAAgB;QAChB,oBAAoB;KACpB,CAAC;AAAA,CACF","sourcesContent":["import { Agent, type AgentMessage, convertToLlm, type ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { getDefaultSessionDir, SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport { clampThinkingLevel, type Message, type Model, streamSimple } from \"@caupulican/pi-ai\";\nimport { getAgentDir } from \"../config.ts\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { configFile } from \"./agent-paths.ts\";\nimport { AgentSession } from \"./agent-session.ts\";\nimport { formatNoModelsAvailableMessage } from \"./auth-guidance.ts\";\nimport { AuthStorage } from \"./auth-storage.ts\";\nimport { DEFAULT_ACTIVE_TOOL_NAMES } from \"./default-tool-surface.ts\";\nimport { DEFAULT_THINKING_LEVEL } from \"./defaults.ts\";\nimport type { ExtensionRunner, LoadExtensionsResult, SessionStartEvent, ToolDefinition } from \"./extensions/index.ts\";\nimport { ModelRegistry } from \"./model-registry.ts\";\nimport { findInitialModel, resolveProfileModelSettings } from \"./model-resolver.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { DefaultResourceLoader } from \"./resource-loader.ts\";\nimport { parseResourceProfileInput } from \"./resource-profile-blocks.ts\";\nimport type {\n\tProfileDefinitionInput,\n\tResourceProfileFilterSettings,\n\tResourceProfileSettings,\n} from \"./settings-manager.ts\";\nimport { SettingsManager } from \"./settings-manager.ts\";\nimport { isInstallTelemetryEnabled } from \"./telemetry.ts\";\nimport { time } from \"./timings.ts\";\nimport {\n\tcreateBashTool,\n\tcreateCodingTools,\n\tcreateEditTool,\n\tcreateFindTool,\n\tcreateGrepTool,\n\tcreateLsTool,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateWriteTool,\n\twithFileMutationQueue,\n} from \"./tools/index.ts\";\n\nexport interface CreateAgentSessionOptions {\n\t/** Working directory for project-local discovery. Default: process.cwd() */\n\tcwd?: string;\n\t/** Global config directory. Default: ~/.pi/agent */\n\tagentDir?: string;\n\n\t/** Auth storage for credentials. Default: AuthStorage.create(agentDir/auth.json) */\n\tauthStorage?: AuthStorage;\n\t/** Model registry. Default: ModelRegistry.create(authStorage, agentDir/models.json) */\n\tmodelRegistry?: ModelRegistry;\n\n\t/** Model to use. Default: from settings, else first available */\n\tmodel?: Model<any>;\n\t/** Thinking level. Default: from settings, then the model's declared default, else 'medium'. */\n\tthinkingLevel?: ThinkingLevel;\n\t/**\n\t * Whether `model` came from an explicit CLI/SDK flag (vs. profile/settings resolution).\n\t * When false (default), the active profile's model is re-applied on reload so live profile\n\t * edits take effect; when true, the explicit launch-time model is preserved across reloads.\n\t */\n\tisExplicitModel?: boolean;\n\t/** Whether `thinkingLevel` came from an explicit flag (see isExplicitModel). */\n\tisExplicitThinking?: boolean;\n\t/** True when this session is a spawned subagent/child — gates durable memory writes. */\n\tisChildSession?: boolean;\n\t/** Models available for cycling (Ctrl+P in interactive mode) */\n\tscopedModels?: Array<{ model: Model<any>; thinkingLevel?: ThinkingLevel }>;\n\n\t/**\n\t * Optional default tool suppression mode when no explicit allowlist is provided.\n\t *\n\t * - \"all\": start with no tools enabled\n\t * - \"builtin\": disable the default built-in tools (read, bash, edit, write, context_audit,\n\t * goal, delegate, and run_toolkit_script)\n\t * but keep extension/custom tools enabled\n\t */\n\tnoTools?: \"all\" | \"builtin\";\n\t/**\n\t * Optional allowlist of tool names.\n\t *\n\t * When omitted, pi enables the shared default built-in tool surface and leaves extension/custom\n\t * tools enabled unless `noTools` changes that default.\n\t * When provided, only the listed tool names are enabled.\n\t */\n\ttools?: string[];\n\t/** Optional denylist of tool names to disable. Applies after `tools` when both are provided. */\n\texcludeTools?: string[];\n\t/** Optional resource-profile allow/block filters for tool names. */\n\ttoolProfileFilter?: ResourceProfileFilterSettings;\n\t/** Optional one-shot resource filters or complete situation profiles. Never persisted to disk. */\n\tresourceProfileDefinitions?: Record<string, ResourceProfileSettings | ProfileDefinitionInput>;\n\t/** Optional one-shot profile definitions as JSON or <resource-profile> tag text. Never persisted to disk. */\n\tresourceProfileJson?: string | string[];\n\t/** Optional runtime profile selection. Never persisted to disk. */\n\tresourceProfiles?: string[];\n\t/** Custom tools to register (in addition to built-in tools). */\n\tcustomTools?: ToolDefinition[];\n\n\t/** Resource loader. When omitted, DefaultResourceLoader is used. */\n\tresourceLoader?: ResourceLoader;\n\n\t/** Session manager. Default: SessionManager.create(cwd, agentDir, getDefaultSessionDir(cwd, agentDir)) */\n\tsessionManager?: SessionManager;\n\n\t/** Settings manager. Default: SettingsManager.create(cwd, agentDir) */\n\tsettingsManager?: SettingsManager;\n\t/** Session start event metadata for extension runtime startup. */\n\tsessionStartEvent?: SessionStartEvent;\n}\n\n/** Result from createAgentSession */\nexport interface CreateAgentSessionResult {\n\t/** The created session */\n\tsession: AgentSession;\n\t/** Extensions result (for UI context setup in interactive mode) */\n\textensionsResult: LoadExtensionsResult;\n\t/** Warning if session was restored with a different model than saved */\n\tmodelFallbackMessage?: string;\n}\n\n// Re-exports\n\nexport * from \"./agent-session-runtime.ts\";\nexport type {\n\tExtensionAPI,\n\tExtensionCommandContext,\n\tExtensionContext,\n\tExtensionFactory,\n\tSlashCommandInfo,\n\tSlashCommandSource,\n\tToolDefinition,\n} from \"./extensions/index.ts\";\nexport type { PromptTemplate } from \"./prompt-templates.ts\";\nexport type { Skill } from \"./skills.ts\";\nexport type { Tool } from \"./tools/index.ts\";\n\nexport {\n\twithFileMutationQueue,\n\t// Tool factories (for custom cwd)\n\tcreateCodingTools,\n\tcreateReadOnlyTools,\n\tcreateReadTool,\n\tcreateBashTool,\n\tcreateEditTool,\n\tcreateWriteTool,\n\tcreateGrepTool,\n\tcreateFindTool,\n\tcreateLsTool,\n};\n\n// Helper Functions\n\nfunction getDefaultAgentDir(): string {\n\treturn getAgentDir();\n}\n\nfunction getAttributionHeaders(\n\tmodel: Model<any>,\n\tsettingsManager: SettingsManager,\n\tsessionId?: string,\n): Record<string, string> | undefined {\n\tif (\n\t\tsessionId &&\n\t\t(model.provider === \"opencode\" || model.provider === \"opencode-go\" || model.baseUrl.includes(\"opencode.ai\"))\n\t) {\n\t\treturn { \"x-opencode-session\": sessionId, \"x-opencode-client\": \"pi\" };\n\t}\n\n\tif (!isInstallTelemetryEnabled(settingsManager)) {\n\t\treturn undefined;\n\t}\n\n\tif (model.provider === \"openrouter\" || model.baseUrl.includes(\"openrouter.ai\")) {\n\t\treturn {\n\t\t\t\"HTTP-Referer\": \"https://pi.dev\",\n\t\t\t\"X-OpenRouter-Title\": \"pi\",\n\t\t\t\"X-OpenRouter-Categories\": \"cli-agent\",\n\t\t};\n\t}\n\n\tif (\n\t\tmodel.provider === \"cloudflare-workers-ai\" ||\n\t\tmodel.provider === \"cloudflare-ai-gateway\" ||\n\t\tmodel.baseUrl.includes(\"api.cloudflare.com\") ||\n\t\tmodel.baseUrl.includes(\"gateway.ai.cloudflare.com\")\n\t) {\n\t\treturn {\n\t\t\t\"User-Agent\": \"pi-coding-agent\",\n\t\t};\n\t}\n\n\treturn undefined;\n}\n\n/**\n * Create an AgentSession with the specified options.\n *\n * @example\n * ```typescript\n * // Minimal - uses defaults\n * const { session } = await createAgentSession();\n *\n * // With explicit model\n * import { getModel } from '@caupulican/pi-ai';\n * const { session } = await createAgentSession({\n * model: getModel('anthropic', 'claude-opus-4-5'),\n * thinkingLevel: 'high',\n * });\n *\n * // Continue previous session\n * const { session, modelFallbackMessage } = await createAgentSession({\n * continueSession: true,\n * });\n *\n * // Full control\n * const loader = new DefaultResourceLoader({\n * cwd: process.cwd(),\n * agentDir: getAgentDir(),\n * settingsManager: SettingsManager.create(),\n * });\n * await loader.reload();\n * const { session } = await createAgentSession({\n * model: myModel,\n * tools: [\"read\", \"bash\"],\n * resourceLoader: loader,\n * sessionManager: SessionManager.inMemory(),\n * });\n * ```\n */\nexport async function createAgentSession(options: CreateAgentSessionOptions = {}): Promise<CreateAgentSessionResult> {\n\tconst cwd = resolvePath(options.cwd ?? options.sessionManager?.getCwd() ?? process.cwd());\n\tconst agentDir = options.agentDir ? resolvePath(options.agentDir) : getDefaultAgentDir();\n\tlet resourceLoader = options.resourceLoader;\n\n\t// Use provided or create AuthStorage and ModelRegistry\n\tconst authPath = options.agentDir ? configFile(agentDir, \"auth.json\") : undefined;\n\tconst modelsPath = options.agentDir ? configFile(agentDir, \"models.json\") : undefined;\n\tconst authStorage = options.authStorage ?? AuthStorage.create(authPath);\n\tconst modelRegistry = options.modelRegistry ?? ModelRegistry.create(authStorage, modelsPath);\n\n\tconst settingsManager = options.settingsManager ?? SettingsManager.create(cwd, agentDir);\n\tconst needsProfileReload =\n\t\toptions.resourceProfileDefinitions !== undefined ||\n\t\toptions.resourceProfileJson !== undefined ||\n\t\toptions.resourceProfiles !== undefined;\n\tif (options.resourceProfileDefinitions) {\n\t\tsettingsManager.addInlineResourceProfileDefinitions(options.resourceProfileDefinitions);\n\t}\n\tif (options.resourceProfileJson) {\n\t\tconst inputs = Array.isArray(options.resourceProfileJson)\n\t\t\t? options.resourceProfileJson\n\t\t\t: [options.resourceProfileJson];\n\t\tfor (const input of inputs) {\n\t\t\tsettingsManager.addInlineResourceProfileDefinitions(parseResourceProfileInput(input).profiles);\n\t\t}\n\t}\n\tif (options.resourceProfiles !== undefined) {\n\t\tsettingsManager.setRuntimeResourceProfiles(options.resourceProfiles);\n\t}\n\tconst sessionManager =\n\t\toptions.sessionManager ?? SessionManager.create(cwd, agentDir, getDefaultSessionDir(cwd, agentDir));\n\n\tif (!resourceLoader) {\n\t\tresourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager });\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t} else if (needsProfileReload) {\n\t\tawait resourceLoader.reload();\n\t\ttime(\"resourceLoader.reload\");\n\t}\n\n\t// Check if session has existing data to restore\n\tconst existingSession = sessionManager.buildSessionContext();\n\tconst hasExistingSession = existingSession.messages.length > 0;\n\tconst hasThinkingEntry = sessionManager.getBranch().some((entry) => entry.type === \"thinking_level_change\");\n\n\tlet model = options.model;\n\tlet modelFallbackMessage: string | undefined;\n\n\tlet thinkingLevel = options.thinkingLevel;\n\n\tconst activeProfileNames = settingsManager.getActiveResourceProfileNames();\n\tif (activeProfileNames.length > 0) {\n\t\tconst profileSettings = resolveProfileModelSettings({\n\t\t\tactiveProfileNames,\n\t\t\tregistry: settingsManager.getProfileRegistry(),\n\t\t\tmodelRegistry,\n\t\t\tcwd,\n\t\t});\n\t\tif (profileSettings.error) {\n\t\t\tmodelFallbackMessage = `Profile model resolution error: ${profileSettings.error}`;\n\t\t}\n\t\tif (!model && profileSettings.model) {\n\t\t\tmodel = profileSettings.model;\n\t\t}\n\t\tif (thinkingLevel === undefined && profileSettings.thinkingLevel) {\n\t\t\tthinkingLevel = profileSettings.thinkingLevel;\n\t\t}\n\t}\n\n\t// If session has data, try to restore model from it\n\tif (!model && hasExistingSession && existingSession.model) {\n\t\tconst restoredModel = modelRegistry.find(existingSession.model.provider, existingSession.model.modelId);\n\t\tif (restoredModel && modelRegistry.hasConfiguredAuth(restoredModel)) {\n\t\t\tmodel = restoredModel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = `Could not restore model ${existingSession.model.provider}/${existingSession.model.modelId}`;\n\t\t}\n\t}\n\n\t// If still no model, use findInitialModel (checks settings default, then provider defaults)\n\tif (!model) {\n\t\tconst result = await findInitialModel({\n\t\t\tscopedModels: [],\n\t\t\tisContinuing: hasExistingSession,\n\t\t\tdefaultProvider: settingsManager.getDefaultProvider(),\n\t\t\tdefaultModelId: settingsManager.getDefaultModel(),\n\t\t\tdefaultThinkingLevel: settingsManager.getDefaultThinkingLevel(),\n\t\t\tmodelRegistry,\n\t\t});\n\t\tmodel = result.model;\n\t\tif (thinkingLevel === undefined && !(hasExistingSession && hasThinkingEntry)) {\n\t\t\tthinkingLevel = result.thinkingLevel;\n\t\t}\n\t\tif (!model) {\n\t\t\tmodelFallbackMessage = formatNoModelsAvailableMessage();\n\t\t} else if (modelFallbackMessage) {\n\t\t\tmodelFallbackMessage += `. Using ${model.provider}/${model.id}`;\n\t\t}\n\t}\n\n\t// If session has data, restore thinking level from it\n\tif (thinkingLevel === undefined && hasExistingSession) {\n\t\tthinkingLevel = hasThinkingEntry\n\t\t\t? (existingSession.thinkingLevel as ThinkingLevel)\n\t\t\t: (settingsManager.getDefaultThinkingLevel() ?? model?.defaultThinkingLevel ?? DEFAULT_THINKING_LEVEL);\n\t}\n\n\t// Fall back to the user's default, then the selected model's own default.\n\tif (thinkingLevel === undefined) {\n\t\tthinkingLevel =\n\t\t\tsettingsManager.getDefaultThinkingLevel() ?? model?.defaultThinkingLevel ?? DEFAULT_THINKING_LEVEL;\n\t}\n\n\t// Clamp to model capabilities\n\tif (!model) {\n\t\tthinkingLevel = \"off\";\n\t} else {\n\t\tthinkingLevel = clampThinkingLevel(model, thinkingLevel) as ThinkingLevel;\n\t}\n\n\tconst defaultActiveToolNames = [\n\t\t...DEFAULT_ACTIVE_TOOL_NAMES,\n\t\t...(settingsManager.getScoutSettings().enabled ? [\"context_scout\"] : []),\n\t];\n\tconst toolProfileFilter = options.toolProfileFilter ?? settingsManager.getResourceProfileFilter(\"tools\");\n\tconst allowedToolNames = options.tools ?? (options.noTools === \"all\" ? [] : undefined);\n\tconst excludedToolNames = options.excludeTools;\n\tconst excludedToolNameSet = excludedToolNames ? new Set(excludedToolNames) : undefined;\n\tconst initialActiveToolNames: string[] = (\n\t\toptions.tools ? [...options.tools] : options.noTools ? [] : defaultActiveToolNames\n\t).filter((name) => !excludedToolNameSet?.has(name));\n\n\tlet agent: Agent;\n\n\t// Create convertToLlm wrapper that filters images if blockImages is enabled (defense-in-depth)\n\tconst convertToLlmWithBlockImages = (messages: AgentMessage[]): Message[] => {\n\t\tconst converted = convertToLlm(messages);\n\t\t// Check setting dynamically so mid-session changes take effect\n\t\tif (!settingsManager.getBlockImages()) {\n\t\t\treturn converted;\n\t\t}\n\t\t// Filter out ImageContent from all messages, replacing with text placeholder\n\t\treturn converted.map((msg) => {\n\t\t\tif (msg.role === \"user\" || msg.role === \"toolResult\") {\n\t\t\t\tconst content = msg.content;\n\t\t\t\tif (Array.isArray(content)) {\n\t\t\t\t\tconst hasImages = content.some((c) => c.type === \"image\");\n\t\t\t\t\tif (hasImages) {\n\t\t\t\t\t\tconst filteredContent = content\n\t\t\t\t\t\t\t.map((c) =>\n\t\t\t\t\t\t\t\tc.type === \"image\" ? { type: \"text\" as const, text: \"Image reading is disabled.\" } : c,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\t.filter(\n\t\t\t\t\t\t\t\t(c, i, arr) =>\n\t\t\t\t\t\t\t\t\t// Dedupe consecutive \"Image reading is disabled.\" texts\n\t\t\t\t\t\t\t\t\t!(\n\t\t\t\t\t\t\t\t\t\tc.type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\tc.text === \"Image reading is disabled.\" &&\n\t\t\t\t\t\t\t\t\t\ti > 0 &&\n\t\t\t\t\t\t\t\t\t\tarr[i - 1].type === \"text\" &&\n\t\t\t\t\t\t\t\t\t\t(arr[i - 1] as { type: \"text\"; text: string }).text === \"Image reading is disabled.\"\n\t\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\treturn { ...msg, content: filteredContent };\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn msg;\n\t\t});\n\t};\n\n\tconst extensionRunnerRef: { current?: ExtensionRunner } = {};\n\n\tagent = new Agent({\n\t\tinitialState: {\n\t\t\tsystemPrompt: \"\",\n\t\t\tmodel,\n\t\t\tthinkingLevel,\n\t\t\ttools: [],\n\t\t},\n\t\tconvertToLlm: convertToLlmWithBlockImages,\n\t\tstreamFn: async (model, context, options) => {\n\t\t\tconst auth = await modelRegistry.getApiKeyAndHeaders(model);\n\t\t\tif (!auth.ok) {\n\t\t\t\tthrow new Error(auth.error);\n\t\t\t}\n\t\t\tconst providerRetrySettings = settingsManager.getProviderRetrySettings();\n\t\t\tconst httpIdleTimeoutMs = settingsManager.getHttpIdleTimeoutMs();\n\t\t\t// SDKs treat timeout=0 as 0ms (immediate timeout), not \"no timeout\".\n\t\t\t// Use max int32 to effectively disable the timeout.\n\t\t\tconst effectiveTimeoutMs = httpIdleTimeoutMs === 0 ? 2147483647 : httpIdleTimeoutMs;\n\t\t\tconst timeoutMs = options?.timeoutMs ?? providerRetrySettings.timeoutMs ?? effectiveTimeoutMs;\n\t\t\tconst websocketConnectTimeoutMs =\n\t\t\t\toptions?.websocketConnectTimeoutMs ?? settingsManager.getWebSocketConnectTimeoutMs();\n\t\t\tconst attributionHeaders = getAttributionHeaders(model, settingsManager, options?.sessionId);\n\t\t\treturn streamSimple(model, context, {\n\t\t\t\t...options,\n\t\t\t\tapiKey: auth.apiKey,\n\t\t\t\tonAuthRejection:\n\t\t\t\t\tauth.apiKey && model.provider === \"openai-codex\"\n\t\t\t\t\t\t? async () => modelRegistry.recoverRejectedOAuthApiKey(model.provider, auth.apiKey as string)\n\t\t\t\t\t\t: options?.onAuthRejection,\n\t\t\t\ttimeoutMs,\n\t\t\t\twebsocketConnectTimeoutMs,\n\t\t\t\tmaxRetries: options?.maxRetries ?? providerRetrySettings.maxRetries,\n\t\t\t\tmaxRetryDelayMs: options?.maxRetryDelayMs ?? providerRetrySettings.maxRetryDelayMs,\n\t\t\t\theaders:\n\t\t\t\t\tattributionHeaders || auth.headers || options?.headers\n\t\t\t\t\t\t? { ...attributionHeaders, ...auth.headers, ...options?.headers }\n\t\t\t\t\t\t: undefined,\n\t\t\t});\n\t\t},\n\t\tonPayload: async (payload, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"before_provider_request\")) {\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\treturn runner.emitBeforeProviderRequest(payload);\n\t\t},\n\t\tonResponse: async (response, _model) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner?.hasHandlers(\"after_provider_response\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tawait runner.emit({\n\t\t\t\ttype: \"after_provider_response\",\n\t\t\t\tstatus: response.status,\n\t\t\t\theaders: response.headers,\n\t\t\t});\n\t\t},\n\t\tsessionId: sessionManager.getSessionId(),\n\t\ttransformContext: async (messages) => {\n\t\t\tconst runner = extensionRunnerRef.current;\n\t\t\tif (!runner) return messages;\n\t\t\treturn runner.emitContext(messages);\n\t\t},\n\t\tsteeringMode: settingsManager.getSteeringMode(),\n\t\tfollowUpMode: settingsManager.getFollowUpMode(),\n\t\ttransport: settingsManager.getTransport(),\n\t\tthinkingBudgets: settingsManager.getThinkingBudgets(),\n\t\tmaxRetryDelayMs: settingsManager.getProviderRetrySettings().maxRetryDelayMs,\n\t\tmaxStallTurns: settingsManager.getAutonomySettings().maxStallTurns,\n\t});\n\n\t// Restore messages if session has existing data\n\tif (hasExistingSession) {\n\t\tagent.state.messages = existingSession.messages;\n\t\tif (!hasThinkingEntry) {\n\t\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t\t}\n\t} else {\n\t\t// Save initial model and thinking level for new sessions so they can be restored on resume\n\t\tif (model) {\n\t\t\tsessionManager.appendModelChange(model.provider, model.id);\n\t\t}\n\t\tsessionManager.appendThinkingLevelChange(thinkingLevel);\n\t}\n\n\tconst session = new AgentSession({\n\t\tagent,\n\t\tsessionManager,\n\t\tsettingsManager,\n\t\tcwd,\n\t\tagentDir,\n\t\tscopedModels: options.scopedModels,\n\t\tresourceLoader,\n\t\tcustomTools: options.customTools,\n\t\tmodelRegistry,\n\t\tinitialActiveToolNames,\n\t\tallowedToolNames,\n\t\texcludedToolNames,\n\t\textensionRunnerRef,\n\t\ttoolProfileFilter,\n\t\tisExplicitModel: options.isExplicitModel ?? options.model != null,\n\t\tisExplicitThinking: options.isExplicitThinking ?? options.thinkingLevel !== undefined,\n\t\tisChildSession: options.isChildSession ?? process.env.PI_CHILD_SESSION === \"1\",\n\t\tsessionStartEvent: options.sessionStartEvent,\n\t});\n\ttry {\n\t\t// The initial runtime has now bound providers from profile-granted extensions. Re-resolve the\n\t\t// profile model against that authoritative registry generation, then resync model capability.\n\t\tawait session.reapplyActiveProfileModelSettings();\n\t\tif (modelFallbackMessage?.startsWith(\"Profile model resolution error:\")) {\n\t\t\tmodelFallbackMessage = undefined;\n\t\t}\n\t} catch (error) {\n\t\t// Preserve the established non-fatal fallback for a genuinely unresolved profile model.\n\t\tif (!modelFallbackMessage?.startsWith(\"Profile model resolution error:\")) {\n\t\t\tsession.dispose();\n\t\t\tthrow error;\n\t\t}\n\t}\n\tconst extensionsResult = resourceLoader.getExtensions();\n\n\treturn {\n\t\tsession,\n\t\textensionsResult,\n\t\tmodelFallbackMessage,\n\t};\n}\n"]}
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Session-role identity: distinguishes a MAIN session (an interactive/direct `pi` session) from a
3
+ * WORKER session (lane-bound or explicitly dispatched) — the seam every worker-scoped UAC ceiling
4
+ * and zero-footprint store gates on (see runtime-builder.ts's `isAllowedTool`, the worktree_sync
5
+ * tool's worker scoping, and the read-only store options threaded through the persistence layer).
6
+ *
7
+ * A session is a worker iff EITHER:
8
+ * - `PI_SESSION_ROLE=worker` is set (an explicit launcher declaration), or
9
+ * - it is bound to a worktree-sync lane (`PI_WORKTREE_LANE`; see worktree-sync/runtime.ts) — a
10
+ * lane-bound session is a worker by construction, regardless of how it was launched.
11
+ *
12
+ * `PI_SESSION_ROLE=main` is deliberately NOT an escalation: it can never override a bound lane.
13
+ * There is no environment value a lane-bound process can set to shed the worker ceiling — the env
14
+ * var is additive evidence for "worker", never a downgrade signal.
15
+ */
16
+ export type SessionRole = "main" | "worker";
17
+ /** Derive this process's session role from the environment (env-injectable for tests). */
18
+ export declare function getSessionRole(env?: NodeJS.ProcessEnv): SessionRole;
19
+ /** True iff this process is a worker session (lane-bound or explicitly declared). */
20
+ export declare function isWorkerSession(env?: NodeJS.ProcessEnv): boolean;
21
+ /**
22
+ * Tools a worker session may never activate: the orchestration/self-adaptation surface that would
23
+ * let a worker spawn its own sub-orchestration, mutate settings-driven learning/model state, or
24
+ * shell out to the unbounded `python` execution contract. `python` is load-bearing for the
25
+ * zero-footprint guarantee (it can write anywhere the interpreter can reach); `context_scout` is
26
+ * sub-orchestration (spawns its own isolated agent loop). `bash` is deliberately NOT included: it
27
+ * stays available as the documented cooperative boundary (see docs/worktree-sync.md) — the same
28
+ * trust model the lane gate already applies to foreign CLIs it cannot structurally contain.
29
+ */
30
+ export declare const WORKER_FORBIDDEN_TOOLS: ReadonlySet<string>;
31
+ //# sourceMappingURL=session-role.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-role.d.ts","sourceRoot":"","sources":["../../src/core/session-role.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAIH,MAAM,MAAM,WAAW,GAAG,MAAM,GAAG,QAAQ,CAAC;AAI5C,0FAA0F;AAC1F,wBAAgB,cAAc,CAAC,GAAG,GAAE,MAAM,CAAC,UAAwB,GAAG,WAAW,CAIhF;AAED,qFAAqF;AACrF,wBAAgB,eAAe,CAAC,GAAG,GAAE,MAAM,CAAC,UAAwB,GAAG,OAAO,CAE7E;AAED;;;;;;;;GAQG;AACH,eAAO,MAAM,sBAAsB,EAAE,WAAW,CAAC,MAAM,CAYrD,CAAC","sourcesContent":["/**\n * Session-role identity: distinguishes a MAIN session (an interactive/direct `pi` session) from a\n * WORKER session (lane-bound or explicitly dispatched) — the seam every worker-scoped UAC ceiling\n * and zero-footprint store gates on (see runtime-builder.ts's `isAllowedTool`, the worktree_sync\n * tool's worker scoping, and the read-only store options threaded through the persistence layer).\n *\n * A session is a worker iff EITHER:\n * - `PI_SESSION_ROLE=worker` is set (an explicit launcher declaration), or\n * - it is bound to a worktree-sync lane (`PI_WORKTREE_LANE`; see worktree-sync/runtime.ts) — a\n * lane-bound session is a worker by construction, regardless of how it was launched.\n *\n * `PI_SESSION_ROLE=main` is deliberately NOT an escalation: it can never override a bound lane.\n * There is no environment value a lane-bound process can set to shed the worker ceiling — the env\n * var is additive evidence for \"worker\", never a downgrade signal.\n */\n\nimport { getBoundWorktreeLaneKey } from \"./worktree-sync/runtime.ts\";\n\nexport type SessionRole = \"main\" | \"worker\";\n\nconst PI_SESSION_ROLE_ENV = \"PI_SESSION_ROLE\";\n\n/** Derive this process's session role from the environment (env-injectable for tests). */\nexport function getSessionRole(env: NodeJS.ProcessEnv = process.env): SessionRole {\n\tif (env[PI_SESSION_ROLE_ENV] === \"worker\") return \"worker\";\n\tif (getBoundWorktreeLaneKey(env) !== undefined) return \"worker\";\n\treturn \"main\";\n}\n\n/** True iff this process is a worker session (lane-bound or explicitly declared). */\nexport function isWorkerSession(env: NodeJS.ProcessEnv = process.env): boolean {\n\treturn getSessionRole(env) === \"worker\";\n}\n\n/**\n * Tools a worker session may never activate: the orchestration/self-adaptation surface that would\n * let a worker spawn its own sub-orchestration, mutate settings-driven learning/model state, or\n * shell out to the unbounded `python` execution contract. `python` is load-bearing for the\n * zero-footprint guarantee (it can write anywhere the interpreter can reach); `context_scout` is\n * sub-orchestration (spawns its own isolated agent loop). `bash` is deliberately NOT included: it\n * stays available as the documented cooperative boundary (see docs/worktree-sync.md) — the same\n * trust model the lane gate already applies to foreign CLIs it cannot structurally contain.\n */\nexport const WORKER_FORBIDDEN_TOOLS: ReadonlySet<string> = new Set([\n\t\"goal\",\n\t\"delegate\",\n\t\"delegate_status\",\n\t\"improvement_loop\",\n\t\"extensionify\",\n\t\"skillify\",\n\t\"run_toolkit_script\",\n\t\"model_fitness\",\n\t\"tmux_agent_manager\",\n\t\"context_scout\",\n\t\"python\",\n]);\n"]}