@caupulican/pi-adaptative 0.81.38 → 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 (433) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/dist/bundled-resources/extensions/tmux-agent-manager/README.md +18 -1
  3. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts +131 -0
  4. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.d.ts.map +1 -0
  5. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js +196 -0
  6. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.js.map +1 -0
  7. package/dist/bundled-resources/extensions/tmux-agent-manager/dispatch-grant.ts +308 -0
  8. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts +22 -2
  9. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts.map +1 -1
  10. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js +585 -24
  11. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js.map +1 -1
  12. package/dist/bundled-resources/extensions/tmux-agent-manager/index.ts +749 -27
  13. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/__init__.py +43 -0
  14. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/fs.py +270 -0
  15. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/search.py +252 -0
  16. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/strings.py +399 -0
  17. package/dist/bundled-resources/runtimes/pi-shell-engine/commands/text.py +575 -0
  18. package/dist/bundled-resources/runtimes/pi-shell-engine/context.py +52 -0
  19. package/dist/bundled-resources/runtimes/pi-shell-engine/errors.py +49 -0
  20. package/dist/bundled-resources/runtimes/pi-shell-engine/exec.py +734 -0
  21. package/dist/bundled-resources/runtimes/pi-shell-engine/expand.py +238 -0
  22. package/dist/bundled-resources/runtimes/pi-shell-engine/main.py +132 -0
  23. package/dist/bundled-resources/runtimes/pi-shell-engine/nodes.py +116 -0
  24. package/dist/bundled-resources/runtimes/pi-shell-engine/parser.py +287 -0
  25. package/dist/bundled-resources/runtimes/pi-shell-engine/proc.py +137 -0
  26. package/dist/bundled-resources/runtimes/pi-shell-engine/state.py +100 -0
  27. package/dist/bundled-resources/runtimes/pi-shell-engine/tokens.py +579 -0
  28. package/dist/bundled-resources/skills/tool-call-repair/SKILL.md +19 -9
  29. package/dist/bundled-resources/skills/tool-call-repair/references/failure-grammar.md +22 -5
  30. package/dist/bundled-resources/skills/tool-call-repair/references/repair-catalogue.md +5 -5
  31. package/dist/bundled-resources/skills/tool-call-repair/references/text-protocol-grammar.md +28 -7
  32. package/dist/cli/args.d.ts +3 -0
  33. package/dist/cli/args.d.ts.map +1 -1
  34. package/dist/cli/args.js +15 -0
  35. package/dist/cli/args.js.map +1 -1
  36. package/dist/core/agent-paths.d.ts +49 -0
  37. package/dist/core/agent-paths.d.ts.map +1 -0
  38. package/dist/core/agent-paths.js +107 -0
  39. package/dist/core/agent-paths.js.map +1 -0
  40. package/dist/core/agent-session-services.d.ts.map +1 -1
  41. package/dist/core/agent-session-services.js +3 -3
  42. package/dist/core/agent-session-services.js.map +1 -1
  43. package/dist/core/agent-session.d.ts +234 -17
  44. package/dist/core/agent-session.d.ts.map +1 -1
  45. package/dist/core/agent-session.js +484 -62
  46. package/dist/core/agent-session.js.map +1 -1
  47. package/dist/core/autonomy/contracts.d.ts +9 -0
  48. package/dist/core/autonomy/contracts.d.ts.map +1 -1
  49. package/dist/core/autonomy/contracts.js.map +1 -1
  50. package/dist/core/autonomy/lane-tracker.d.ts +10 -1
  51. package/dist/core/autonomy/lane-tracker.d.ts.map +1 -1
  52. package/dist/core/autonomy/lane-tracker.js +5 -1
  53. package/dist/core/autonomy/lane-tracker.js.map +1 -1
  54. package/dist/core/background-lane-controller.d.ts +122 -6
  55. package/dist/core/background-lane-controller.d.ts.map +1 -1
  56. package/dist/core/background-lane-controller.js +446 -89
  57. package/dist/core/background-lane-controller.js.map +1 -1
  58. package/dist/core/bash-execution-controller.d.ts +4 -0
  59. package/dist/core/bash-execution-controller.d.ts.map +1 -1
  60. package/dist/core/bash-execution-controller.js +7 -1
  61. package/dist/core/bash-execution-controller.js.map +1 -1
  62. package/dist/core/compaction-support.d.ts +13 -3
  63. package/dist/core/compaction-support.d.ts.map +1 -1
  64. package/dist/core/compaction-support.js +43 -7
  65. package/dist/core/compaction-support.js.map +1 -1
  66. package/dist/core/context/context-audit.d.ts +33 -1
  67. package/dist/core/context/context-audit.d.ts.map +1 -1
  68. package/dist/core/context/context-audit.js +31 -5
  69. package/dist/core/context/context-audit.js.map +1 -1
  70. package/dist/core/context-gc.d.ts.map +1 -1
  71. package/dist/core/context-gc.js +16 -1
  72. package/dist/core/context-gc.js.map +1 -1
  73. package/dist/core/context-pipeline.d.ts +26 -4
  74. package/dist/core/context-pipeline.d.ts.map +1 -1
  75. package/dist/core/context-pipeline.js +137 -14
  76. package/dist/core/context-pipeline.js.map +1 -1
  77. package/dist/core/cost-guard.d.ts +19 -3
  78. package/dist/core/cost-guard.d.ts.map +1 -1
  79. package/dist/core/cost-guard.js +18 -3
  80. package/dist/core/cost-guard.js.map +1 -1
  81. package/dist/core/delegation/session-worker-result.d.ts +34 -4
  82. package/dist/core/delegation/session-worker-result.d.ts.map +1 -1
  83. package/dist/core/delegation/session-worker-result.js +64 -4
  84. package/dist/core/delegation/session-worker-result.js.map +1 -1
  85. package/dist/core/delegation/worker-result.d.ts +42 -1
  86. package/dist/core/delegation/worker-result.d.ts.map +1 -1
  87. package/dist/core/delegation/worker-result.js +68 -0
  88. package/dist/core/delegation/worker-result.js.map +1 -1
  89. package/dist/core/extensions/loader.d.ts.map +1 -1
  90. package/dist/core/extensions/loader.js +20 -0
  91. package/dist/core/extensions/loader.js.map +1 -1
  92. package/dist/core/extensions/runner.d.ts.map +1 -1
  93. package/dist/core/extensions/runner.js +1 -0
  94. package/dist/core/extensions/runner.js.map +1 -1
  95. package/dist/core/extensions/types.d.ts +51 -0
  96. package/dist/core/extensions/types.d.ts.map +1 -1
  97. package/dist/core/extensions/types.js.map +1 -1
  98. package/dist/core/goal-loop-controller.d.ts +17 -1
  99. package/dist/core/goal-loop-controller.d.ts.map +1 -1
  100. package/dist/core/goal-loop-controller.js +79 -11
  101. package/dist/core/goal-loop-controller.js.map +1 -1
  102. package/dist/core/goals/goal-continuation-controller.d.ts +48 -2
  103. package/dist/core/goals/goal-continuation-controller.d.ts.map +1 -1
  104. package/dist/core/goals/goal-continuation-controller.js +77 -0
  105. package/dist/core/goals/goal-continuation-controller.js.map +1 -1
  106. package/dist/core/goals/goal-continuation-defaults.d.ts +39 -0
  107. package/dist/core/goals/goal-continuation-defaults.d.ts.map +1 -1
  108. package/dist/core/goals/goal-continuation-defaults.js +42 -0
  109. package/dist/core/goals/goal-continuation-defaults.js.map +1 -1
  110. package/dist/core/goals/goal-continuation-prompt.d.ts +4 -0
  111. package/dist/core/goals/goal-continuation-prompt.d.ts.map +1 -1
  112. package/dist/core/goals/goal-continuation-prompt.js +51 -10
  113. package/dist/core/goals/goal-continuation-prompt.js.map +1 -1
  114. package/dist/core/goals/goal-runtime-snapshot.d.ts +101 -2
  115. package/dist/core/goals/goal-runtime-snapshot.d.ts.map +1 -1
  116. package/dist/core/goals/goal-runtime-snapshot.js +87 -4
  117. package/dist/core/goals/goal-runtime-snapshot.js.map +1 -1
  118. package/dist/core/goals/goal-state.d.ts +89 -1
  119. package/dist/core/goals/goal-state.d.ts.map +1 -1
  120. package/dist/core/goals/goal-state.js +71 -5
  121. package/dist/core/goals/goal-state.js.map +1 -1
  122. package/dist/core/goals/goal-tool-core.d.ts +56 -2
  123. package/dist/core/goals/goal-tool-core.d.ts.map +1 -1
  124. package/dist/core/goals/goal-tool-core.js +111 -5
  125. package/dist/core/goals/goal-tool-core.js.map +1 -1
  126. package/dist/core/goals/session-goal-state.d.ts +11 -2
  127. package/dist/core/goals/session-goal-state.d.ts.map +1 -1
  128. package/dist/core/goals/session-goal-state.js +32 -17
  129. package/dist/core/goals/session-goal-state.js.map +1 -1
  130. package/dist/core/keybindings.d.ts +10 -0
  131. package/dist/core/keybindings.d.ts.map +1 -1
  132. package/dist/core/keybindings.js +10 -2
  133. package/dist/core/keybindings.js.map +1 -1
  134. package/dist/core/learning/observation-store.d.ts +12 -3
  135. package/dist/core/learning/observation-store.d.ts.map +1 -1
  136. package/dist/core/learning/observation-store.js +30 -15
  137. package/dist/core/learning/observation-store.js.map +1 -1
  138. package/dist/core/learning/skill-curator.d.ts +5 -1
  139. package/dist/core/learning/skill-curator.d.ts.map +1 -1
  140. package/dist/core/learning/skill-curator.js +21 -19
  141. package/dist/core/learning/skill-curator.js.map +1 -1
  142. package/dist/core/local-runtime-controller.d.ts +65 -3
  143. package/dist/core/local-runtime-controller.d.ts.map +1 -1
  144. package/dist/core/local-runtime-controller.js +186 -26
  145. package/dist/core/local-runtime-controller.js.map +1 -1
  146. package/dist/core/memory/providers/file-store.d.ts +1 -1
  147. package/dist/core/memory/providers/file-store.d.ts.map +1 -1
  148. package/dist/core/memory/providers/file-store.js +6 -6
  149. package/dist/core/memory/providers/file-store.js.map +1 -1
  150. package/dist/core/model-capability.d.ts +34 -0
  151. package/dist/core/model-capability.d.ts.map +1 -1
  152. package/dist/core/model-capability.js +42 -1
  153. package/dist/core/model-capability.js.map +1 -1
  154. package/dist/core/model-router/tool-escalation.d.ts +15 -0
  155. package/dist/core/model-router/tool-escalation.d.ts.map +1 -1
  156. package/dist/core/model-router/tool-escalation.js +23 -1
  157. package/dist/core/model-router/tool-escalation.js.map +1 -1
  158. package/dist/core/model-router-controller.d.ts +34 -7
  159. package/dist/core/model-router-controller.d.ts.map +1 -1
  160. package/dist/core/model-router-controller.js +95 -16
  161. package/dist/core/model-router-controller.js.map +1 -1
  162. package/dist/core/models/adaptation-store.d.ts +7 -0
  163. package/dist/core/models/adaptation-store.d.ts.map +1 -1
  164. package/dist/core/models/adaptation-store.js +47 -11
  165. package/dist/core/models/adaptation-store.js.map +1 -1
  166. package/dist/core/models/default-model-suggestions.d.ts.map +1 -1
  167. package/dist/core/models/default-model-suggestions.js +17 -0
  168. package/dist/core/models/default-model-suggestions.js.map +1 -1
  169. package/dist/core/models/fitness-store.d.ts +3 -0
  170. package/dist/core/models/fitness-store.d.ts.map +1 -1
  171. package/dist/core/models/fitness-store.js +11 -2
  172. package/dist/core/models/fitness-store.js.map +1 -1
  173. package/dist/core/models/llamacpp-runtime.d.ts +180 -0
  174. package/dist/core/models/llamacpp-runtime.d.ts.map +1 -0
  175. package/dist/core/models/llamacpp-runtime.js +475 -0
  176. package/dist/core/models/llamacpp-runtime.js.map +1 -0
  177. package/dist/core/models/local-registration.d.ts +40 -0
  178. package/dist/core/models/local-registration.d.ts.map +1 -1
  179. package/dist/core/models/local-registration.js +94 -5
  180. package/dist/core/models/local-registration.js.map +1 -1
  181. package/dist/core/models/local-runtime.d.ts.map +1 -1
  182. package/dist/core/models/local-runtime.js +6 -5
  183. package/dist/core/models/local-runtime.js.map +1 -1
  184. package/dist/core/models/model-ref.d.ts +7 -0
  185. package/dist/core/models/model-ref.d.ts.map +1 -1
  186. package/dist/core/models/model-ref.js +26 -0
  187. package/dist/core/models/model-ref.js.map +1 -1
  188. package/dist/core/models/needle-runtime.d.ts +257 -0
  189. package/dist/core/models/needle-runtime.d.ts.map +1 -0
  190. package/dist/core/models/needle-runtime.js +519 -0
  191. package/dist/core/models/needle-runtime.js.map +1 -0
  192. package/dist/core/models/prism-llamacpp-lifecycle.d.ts +89 -0
  193. package/dist/core/models/prism-llamacpp-lifecycle.d.ts.map +1 -0
  194. package/dist/core/models/prism-llamacpp-lifecycle.js +121 -0
  195. package/dist/core/models/prism-llamacpp-lifecycle.js.map +1 -0
  196. package/dist/core/package-manager.d.ts.map +1 -1
  197. package/dist/core/package-manager.js +11 -10
  198. package/dist/core/package-manager.js.map +1 -1
  199. package/dist/core/process-matrix/codes.d.ts +72 -0
  200. package/dist/core/process-matrix/codes.d.ts.map +1 -0
  201. package/dist/core/process-matrix/codes.js +15 -0
  202. package/dist/core/process-matrix/codes.js.map +1 -0
  203. package/dist/core/process-matrix/runtime.d.ts +63 -0
  204. package/dist/core/process-matrix/runtime.d.ts.map +1 -0
  205. package/dist/core/process-matrix/runtime.js +310 -0
  206. package/dist/core/process-matrix/runtime.js.map +1 -0
  207. package/dist/core/process-matrix/store.d.ts +22 -0
  208. package/dist/core/process-matrix/store.d.ts.map +1 -0
  209. package/dist/core/process-matrix/store.js +80 -0
  210. package/dist/core/process-matrix/store.js.map +1 -0
  211. package/dist/core/process-matrix/supervisor.d.ts +72 -0
  212. package/dist/core/process-matrix/supervisor.d.ts.map +1 -0
  213. package/dist/core/process-matrix/supervisor.js +130 -0
  214. package/dist/core/process-matrix/supervisor.js.map +1 -0
  215. package/dist/core/profile-registry.d.ts +7 -0
  216. package/dist/core/profile-registry.d.ts.map +1 -1
  217. package/dist/core/profile-registry.js +20 -0
  218. package/dist/core/profile-registry.js.map +1 -1
  219. package/dist/core/python-runtime.d.ts.map +1 -1
  220. package/dist/core/python-runtime.js +3 -3
  221. package/dist/core/python-runtime.js.map +1 -1
  222. package/dist/core/reflection-controller.d.ts +29 -5
  223. package/dist/core/reflection-controller.d.ts.map +1 -1
  224. package/dist/core/reflection-controller.js +215 -126
  225. package/dist/core/reflection-controller.js.map +1 -1
  226. package/dist/core/reload-blockers.d.ts +36 -0
  227. package/dist/core/reload-blockers.d.ts.map +1 -1
  228. package/dist/core/reload-blockers.js +44 -0
  229. package/dist/core/reload-blockers.js.map +1 -1
  230. package/dist/core/resource-loader.d.ts.map +1 -1
  231. package/dist/core/resource-loader.js +8 -7
  232. package/dist/core/resource-loader.js.map +1 -1
  233. package/dist/core/runtime-builder.d.ts +58 -5
  234. package/dist/core/runtime-builder.d.ts.map +1 -1
  235. package/dist/core/runtime-builder.js +209 -25
  236. package/dist/core/runtime-builder.js.map +1 -1
  237. package/dist/core/scout-controller.d.ts +6 -0
  238. package/dist/core/scout-controller.d.ts.map +1 -1
  239. package/dist/core/scout-controller.js +66 -52
  240. package/dist/core/scout-controller.js.map +1 -1
  241. package/dist/core/sdk.d.ts.map +1 -1
  242. package/dist/core/sdk.js +3 -3
  243. package/dist/core/sdk.js.map +1 -1
  244. package/dist/core/session-role.d.ts +31 -0
  245. package/dist/core/session-role.d.ts.map +1 -0
  246. package/dist/core/session-role.js +52 -0
  247. package/dist/core/session-role.js.map +1 -0
  248. package/dist/core/settings-manager.d.ts +42 -3
  249. package/dist/core/settings-manager.d.ts.map +1 -1
  250. package/dist/core/settings-manager.js +94 -60
  251. package/dist/core/settings-manager.js.map +1 -1
  252. package/dist/core/system-prompt-builder.d.ts +12 -0
  253. package/dist/core/system-prompt-builder.d.ts.map +1 -1
  254. package/dist/core/system-prompt-builder.js +6 -0
  255. package/dist/core/system-prompt-builder.js.map +1 -1
  256. package/dist/core/system-prompt.d.ts +14 -1
  257. package/dist/core/system-prompt.d.ts.map +1 -1
  258. package/dist/core/system-prompt.js +20 -3
  259. package/dist/core/system-prompt.js.map +1 -1
  260. package/dist/core/tasks/session-task-state.d.ts +11 -2
  261. package/dist/core/tasks/session-task-state.d.ts.map +1 -1
  262. package/dist/core/tasks/session-task-state.js +27 -11
  263. package/dist/core/tasks/session-task-state.js.map +1 -1
  264. package/dist/core/tasks/task-contract-monitor.d.ts +45 -0
  265. package/dist/core/tasks/task-contract-monitor.d.ts.map +1 -0
  266. package/dist/core/tasks/task-contract-monitor.js +56 -0
  267. package/dist/core/tasks/task-contract-monitor.js.map +1 -0
  268. package/dist/core/tasks/task-state.d.ts +8 -0
  269. package/dist/core/tasks/task-state.d.ts.map +1 -1
  270. package/dist/core/tasks/task-state.js +28 -1
  271. package/dist/core/tasks/task-state.js.map +1 -1
  272. package/dist/core/tool-gate-controller.d.ts.map +1 -1
  273. package/dist/core/tool-gate-controller.js +5 -0
  274. package/dist/core/tool-gate-controller.js.map +1 -1
  275. package/dist/core/tool-recovery-log-records.d.ts +7 -0
  276. package/dist/core/tool-recovery-log-records.d.ts.map +1 -1
  277. package/dist/core/tool-recovery-log-records.js +14 -6
  278. package/dist/core/tool-recovery-log-records.js.map +1 -1
  279. package/dist/core/tool-selection/promotion.d.ts +54 -0
  280. package/dist/core/tool-selection/promotion.d.ts.map +1 -0
  281. package/dist/core/tool-selection/promotion.js +81 -0
  282. package/dist/core/tool-selection/promotion.js.map +1 -0
  283. package/dist/core/tool-selection/tool-performance-store.d.ts +37 -0
  284. package/dist/core/tool-selection/tool-performance-store.d.ts.map +1 -1
  285. package/dist/core/tool-selection/tool-performance-store.js +87 -3
  286. package/dist/core/tool-selection/tool-performance-store.js.map +1 -1
  287. package/dist/core/tool-selection/tool-selection-controller.d.ts +45 -0
  288. package/dist/core/tool-selection/tool-selection-controller.d.ts.map +1 -1
  289. package/dist/core/tool-selection/tool-selection-controller.js +96 -0
  290. package/dist/core/tool-selection/tool-selection-controller.js.map +1 -1
  291. package/dist/core/tools/bash.d.ts +18 -0
  292. package/dist/core/tools/bash.d.ts.map +1 -1
  293. package/dist/core/tools/bash.js +95 -16
  294. package/dist/core/tools/bash.js.map +1 -1
  295. package/dist/core/tools/delegate-status.d.ts +14 -0
  296. package/dist/core/tools/delegate-status.d.ts.map +1 -1
  297. package/dist/core/tools/delegate-status.js +82 -7
  298. package/dist/core/tools/delegate-status.js.map +1 -1
  299. package/dist/core/tools/delegate.d.ts.map +1 -1
  300. package/dist/core/tools/delegate.js +25 -8
  301. package/dist/core/tools/delegate.js.map +1 -1
  302. package/dist/core/tools/goal.d.ts +94 -3
  303. package/dist/core/tools/goal.d.ts.map +1 -1
  304. package/dist/core/tools/goal.js +165 -15
  305. package/dist/core/tools/goal.js.map +1 -1
  306. package/dist/core/tools/model-fitness.d.ts +7 -0
  307. package/dist/core/tools/model-fitness.d.ts.map +1 -1
  308. package/dist/core/tools/model-fitness.js +2 -2
  309. package/dist/core/tools/model-fitness.js.map +1 -1
  310. package/dist/core/tools/shell-contract-router.d.ts +6 -1
  311. package/dist/core/tools/shell-contract-router.d.ts.map +1 -1
  312. package/dist/core/tools/shell-contract-router.js +23 -2
  313. package/dist/core/tools/shell-contract-router.js.map +1 -1
  314. package/dist/core/tools/shell-session.d.ts +89 -0
  315. package/dist/core/tools/shell-session.d.ts.map +1 -0
  316. package/dist/core/tools/shell-session.js +432 -0
  317. package/dist/core/tools/shell-session.js.map +1 -0
  318. package/dist/core/tools/task-steps.d.ts +4 -0
  319. package/dist/core/tools/task-steps.d.ts.map +1 -1
  320. package/dist/core/tools/task-steps.js +63 -8
  321. package/dist/core/tools/task-steps.js.map +1 -1
  322. package/dist/core/tools/tmux-dispatch.d.ts +86 -0
  323. package/dist/core/tools/tmux-dispatch.d.ts.map +1 -0
  324. package/dist/core/tools/tmux-dispatch.js +91 -0
  325. package/dist/core/tools/tmux-dispatch.js.map +1 -0
  326. package/dist/core/tools/windows-shell-engine.d.ts +42 -0
  327. package/dist/core/tools/windows-shell-engine.d.ts.map +1 -0
  328. package/dist/core/tools/windows-shell-engine.js +153 -0
  329. package/dist/core/tools/windows-shell-engine.js.map +1 -0
  330. package/dist/core/tools/windows-shell-state.d.ts +40 -0
  331. package/dist/core/tools/windows-shell-state.d.ts.map +1 -0
  332. package/dist/core/tools/windows-shell-state.js +59 -0
  333. package/dist/core/tools/windows-shell-state.js.map +1 -0
  334. package/dist/core/tools/worktree-sync.d.ts +24 -0
  335. package/dist/core/tools/worktree-sync.d.ts.map +1 -0
  336. package/dist/core/tools/worktree-sync.js +338 -0
  337. package/dist/core/tools/worktree-sync.js.map +1 -0
  338. package/dist/core/trust-manager.d.ts +4 -1
  339. package/dist/core/trust-manager.d.ts.map +1 -1
  340. package/dist/core/trust-manager.js +20 -2
  341. package/dist/core/trust-manager.js.map +1 -1
  342. package/dist/core/util/atomic-file.d.ts +55 -0
  343. package/dist/core/util/atomic-file.d.ts.map +1 -0
  344. package/dist/core/util/atomic-file.js +255 -0
  345. package/dist/core/util/atomic-file.js.map +1 -0
  346. package/dist/core/util/minimatch-cache.d.ts +33 -0
  347. package/dist/core/util/minimatch-cache.d.ts.map +1 -0
  348. package/dist/core/util/minimatch-cache.js +0 -0
  349. package/dist/core/util/minimatch-cache.js.map +1 -0
  350. package/dist/core/worktree-sync/codes.d.ts +227 -0
  351. package/dist/core/worktree-sync/codes.d.ts.map +1 -0
  352. package/dist/core/worktree-sync/codes.js +14 -0
  353. package/dist/core/worktree-sync/codes.js.map +1 -0
  354. package/dist/core/worktree-sync/git-engine.d.ts +156 -0
  355. package/dist/core/worktree-sync/git-engine.d.ts.map +1 -0
  356. package/dist/core/worktree-sync/git-engine.js +1191 -0
  357. package/dist/core/worktree-sync/git-engine.js.map +1 -0
  358. package/dist/core/worktree-sync/lane-gate.d.ts +75 -0
  359. package/dist/core/worktree-sync/lane-gate.d.ts.map +1 -0
  360. package/dist/core/worktree-sync/lane-gate.js +360 -0
  361. package/dist/core/worktree-sync/lane-gate.js.map +1 -0
  362. package/dist/core/worktree-sync/runtime.d.ts +47 -0
  363. package/dist/core/worktree-sync/runtime.d.ts.map +1 -0
  364. package/dist/core/worktree-sync/runtime.js +96 -0
  365. package/dist/core/worktree-sync/runtime.js.map +1 -0
  366. package/dist/core/worktree-sync/store.d.ts +69 -0
  367. package/dist/core/worktree-sync/store.d.ts.map +1 -0
  368. package/dist/core/worktree-sync/store.js +247 -0
  369. package/dist/core/worktree-sync/store.js.map +1 -0
  370. package/dist/core/worktree-sync/watcher.d.ts +29 -0
  371. package/dist/core/worktree-sync/watcher.d.ts.map +1 -0
  372. package/dist/core/worktree-sync/watcher.js +93 -0
  373. package/dist/core/worktree-sync/watcher.js.map +1 -0
  374. package/dist/main.d.ts.map +1 -1
  375. package/dist/main.js +94 -0
  376. package/dist/main.js.map +1 -1
  377. package/dist/migrations.d.ts +9 -0
  378. package/dist/migrations.d.ts.map +1 -1
  379. package/dist/migrations.js +38 -0
  380. package/dist/migrations.js.map +1 -1
  381. package/dist/modes/interactive/auto-learn-controller.d.ts +16 -1
  382. package/dist/modes/interactive/auto-learn-controller.d.ts.map +1 -1
  383. package/dist/modes/interactive/auto-learn-controller.js +50 -8
  384. package/dist/modes/interactive/auto-learn-controller.js.map +1 -1
  385. package/dist/modes/interactive/components/profile-resource-editor.d.ts.map +1 -1
  386. package/dist/modes/interactive/components/profile-resource-editor.js +23 -1
  387. package/dist/modes/interactive/components/profile-resource-editor.js.map +1 -1
  388. package/dist/modes/interactive/interactive-mode.d.ts +1 -0
  389. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  390. package/dist/modes/interactive/interactive-mode.js +4 -0
  391. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  392. package/dist/modes/interactive/local-model-commands.d.ts +43 -0
  393. package/dist/modes/interactive/local-model-commands.d.ts.map +1 -1
  394. package/dist/modes/interactive/local-model-commands.js +290 -3
  395. package/dist/modes/interactive/local-model-commands.js.map +1 -1
  396. package/dist/modes/interactive/session-flow-commands.d.ts.map +1 -1
  397. package/dist/modes/interactive/session-flow-commands.js +24 -4
  398. package/dist/modes/interactive/session-flow-commands.js.map +1 -1
  399. package/dist/utils/fs-watch.d.ts +11 -0
  400. package/dist/utils/fs-watch.d.ts.map +1 -1
  401. package/dist/utils/fs-watch.js +20 -2
  402. package/dist/utils/fs-watch.js.map +1 -1
  403. package/dist/utils/highlight-js-languages.d.ts +4 -0
  404. package/dist/utils/highlight-js-languages.d.ts.map +1 -0
  405. package/dist/utils/highlight-js-languages.js +573 -0
  406. package/dist/utils/highlight-js-languages.js.map +1 -0
  407. package/dist/utils/shell.d.ts +7 -1
  408. package/dist/utils/shell.d.ts.map +1 -1
  409. package/dist/utils/shell.js +21 -6
  410. package/dist/utils/shell.js.map +1 -1
  411. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  412. package/dist/utils/syntax-highlight.js +53 -5
  413. package/dist/utils/syntax-highlight.js.map +1 -1
  414. package/dist/utils/tools-manager.d.ts.map +1 -1
  415. package/dist/utils/tools-manager.js +112 -1
  416. package/dist/utils/tools-manager.js.map +1 -1
  417. package/docs/process-matrix.md +120 -0
  418. package/docs/settings.md +3 -0
  419. package/docs/tmux-agent-manager.md +85 -2
  420. package/docs/windows.md +52 -3
  421. package/docs/work-directory.md +29 -0
  422. package/docs/worktree-sync.md +250 -0
  423. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  424. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  425. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  426. package/examples/extensions/sandbox/package-lock.json +2 -2
  427. package/examples/extensions/sandbox/package.json +1 -1
  428. package/examples/extensions/with-deps/package-lock.json +2 -2
  429. package/examples/extensions/with-deps/package.json +1 -1
  430. package/npm-shrinkwrap.json +12 -12
  431. package/package.json +10 -4
  432. package/docs/integration-sweep-builder-blueprint-2026-07-09.md +0 -365
  433. package/docs/integration-sweep-resume-2026-07-09.md +0 -407
@@ -18,6 +18,7 @@ import type { ModelAdaptationRule } from "./models/adaptation-store.ts";
18
18
  import type { ResourceLoader } from "./resource-loader.ts";
19
19
  import type { SettingsManager } from "./settings-manager.ts";
20
20
  import { type BuildSystemPromptOptions } from "./system-prompt.ts";
21
+ import { type ToolSelectionHint } from "./tool-selection/promotion.ts";
21
22
  export interface SystemPromptBuilderDeps {
22
23
  /** The session's working directory (read fresh; base for self-modification source resolution). */
23
24
  getCwd(): string;
@@ -35,6 +36,15 @@ export interface SystemPromptBuilderDeps {
35
36
  getToolPromptGuidelines(name: string): string[] | undefined;
36
37
  /** The standing tool-shape rules learned for the session's current model. */
37
38
  getModelAdaptationRules(): readonly ModelAdaptationRule[];
39
+ /**
40
+ * The evidence-gated tool-selection hints active for the session's current model (see
41
+ * `tool-selection/promotion.ts` and `ToolSelectionController.getActiveHints`). Optional: a
42
+ * session that has not wired a `ToolSelectionController` into this builder simply renders no
43
+ * hint block, same as an empty list. Changes RARELY (only when the underlying evidence flips
44
+ * which tool is promoted for an intent) — never per turn — so it does not threaten the
45
+ * single-cached-system-prompt-block invariant (see system-prompt.ts).
46
+ */
47
+ getToolSelectionHints?(): readonly ToolSelectionHint[];
38
48
  /** The session's currently active extensions. */
39
49
  getActiveExtensions(): ReadonlyArray<Extension>;
40
50
  /** Active model context window, used to compact-cap static memory prompt blocks. */
@@ -58,6 +68,8 @@ export declare class SystemPromptBuilder {
58
68
  private _buildSelfModificationPrompt;
59
69
  private _buildStaticMemoryPrompt;
60
70
  private _buildModelAdaptationPrompt;
71
+ /** The evidence-gated tool-selection hint block (see `getToolSelectionHints` on the deps). */
72
+ private _buildToolSelectionHintPrompt;
61
73
  private _buildAutonomyPrompt;
62
74
  private _buildUltraDelegationPrompt;
63
75
  private _buildSystemPromptOptionsForToolNames;
@@ -1 +1 @@
1
- {"version":3,"file":"system-prompt-builder.d.ts","sourceRoot":"","sources":["../../src/core/system-prompt-builder.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAGH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAG/D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAE3D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,KAAK,wBAAwB,EAAqB,MAAM,oBAAoB,CAAC;AAEtF,MAAM,WAAW,uBAAuB;IACvC,kGAAkG;IAClG,MAAM,IAAI,MAAM,CAAC;IACjB,qGAAmG;IACnG,kBAAkB,IAAI,eAAe,CAAC;IACtC,mGAAiG;IACjG,iBAAiB,IAAI,cAAc,CAAC;IACpC,kGAAgG;IAChG,gBAAgB,IAAI,aAAa,CAAC;IAClC,kEAAkE;IAClE,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC;IAC/B,iEAAiE;IACjE,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,SAAS,CAAC;IACvD,iEAAiE;IACjE,uBAAuB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,GAAG,SAAS,CAAC;IAC5D,6EAA6E;IAC7E,uBAAuB,IAAI,SAAS,mBAAmB,EAAE,CAAC;IAC1D,iDAAiD;IACjD,mBAAmB,IAAI,aAAa,CAAC,SAAS,CAAC,CAAC;IAChD,oFAAoF;IACpF,gBAAgB,IAAI,MAAM,GAAG,SAAS,CAAC;IACvC,gGAAgG;IAChG,gBAAgB,IAAI,aAAa,CAAC;CAClC;AAED,qBAAa,mBAAmB;IAC/B,OAAO,CAAC,QAAQ,CAAC,IAAI,CAA0B;IAC/C,OAAO,CAAC,wBAAwB,CAA4B;IAE5D,YAAY,IAAI,EAAE,uBAAuB,EAExC;IAED,uGAAqG;IACrG,0BAA0B,IAAI,wBAAwB,CAErD;IAED,sBAAsB,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAOnE;IAED,yBAAyB,CAAC,UAAU,EAAE,MAAM,EAAE,GAAG,SAAS,GAAG,MAAM,EAAE,CAapE;IAED;;;OAGG;IACH,OAAO,CAAC,yBAAyB;IAMjC,OAAO,CAAC,4BAA4B;IAgDpC,OAAO,CAAC,wBAAwB;IAShC,OAAO,CAAC,2BAA2B;IAOnC,OAAO,CAAC,oBAAoB;IAyB5B,OAAO,CAAC,2BAA2B;IAgBnC,OAAO,CAAC,qCAAqC;IAmD7C,mBAAmB,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,MAAM,CAG/C;IAED;;;;;;OAMG;IACH,6BAA6B,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,MAAM,CAEzD;CACD","sourcesContent":["/**\n * Session system-prompt construction.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the assembly of the\n * session's base system prompt from live session state — the active profile's situational soul, the\n * self-modification and autonomy guardrail blocks, the memory block, the loader's custom/append\n * prompts, and the per-tool snippet/guideline surface — into the {@link BuildSystemPromptOptions}\n * that the pure {@link buildSystemPrompt} renderer (core/system-prompt.ts, a different job: the\n * stateless string builder) consumes. Holds the last-built `_baseSystemPromptOptions` so a\n * before_agent_start extension hook can read it. Takes narrow accessor deps (each read fresh, since\n * several collaborators — tool registries, memory manager, extension runner — are reassigned across\n * the session lifecycle) rather than the whole AgentSession.\n */\n\nimport { existsSync } from \"node:fs\";\nimport type { ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { resolveMemoryPromptBudget } from \"./context/memory-prompt-budget.ts\";\nimport type { Extension } from \"./extensions/types.ts\";\nimport type { MemoryManager } from \"./memory/memory-manager.ts\";\nimport type { ModelAdaptationRule } from \"./models/adaptation-store.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { UNTRUSTED_BOUNDARY_SYSTEM_RULE } from \"./security/untrusted-boundary.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport { type BuildSystemPromptOptions, buildSystemPrompt } from \"./system-prompt.ts\";\n\nexport interface SystemPromptBuilderDeps {\n\t/** The session's working directory (read fresh; base for self-modification source resolution). */\n\tgetCwd(): string;\n\t/** The session's settings manager — soul, self-modification, autonomy, and auto-learn settings. */\n\tgetSettingsManager(): SettingsManager;\n\t/** The session's resource loader — custom/append system prompts, active skills, agents files. */\n\tgetResourceLoader(): ResourceLoader;\n\t/** The session's memory manager — the static, frozen-per-session memory system-prompt block. */\n\tgetMemoryManager(): MemoryManager;\n\t/** Whether a tool name is currently registered on the session. */\n\thasTool(name: string): boolean;\n\t/** The one-line prompt snippet registered for a tool, if any. */\n\tgetToolPromptSnippet(name: string): string | undefined;\n\t/** The extra guideline bullets registered for a tool, if any. */\n\tgetToolPromptGuidelines(name: string): string[] | undefined;\n\t/** The standing tool-shape rules learned for the session's current model. */\n\tgetModelAdaptationRules(): readonly ModelAdaptationRule[];\n\t/** The session's currently active extensions. */\n\tgetActiveExtensions(): ReadonlyArray<Extension>;\n\t/** Active model context window, used to compact-cap static memory prompt blocks. */\n\tgetContextWindow(): number | undefined;\n\t/** Live reasoning/orchestration selection; Ultra adds a bounded proactive-delegation policy. */\n\tgetThinkingLevel(): ThinkingLevel;\n}\n\nexport class SystemPromptBuilder {\n\tprivate readonly deps: SystemPromptBuilderDeps;\n\tprivate _baseSystemPromptOptions!: BuildSystemPromptOptions;\n\n\tconstructor(deps: SystemPromptBuilderDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\t/** The options used to render the last base prompt — read by a before_agent_start extension hook. */\n\tgetBaseSystemPromptOptions(): BuildSystemPromptOptions {\n\t\treturn this._baseSystemPromptOptions;\n\t}\n\n\tnormalizePromptSnippet(text: string | undefined): string | undefined {\n\t\tif (!text) return undefined;\n\t\tconst oneLine = text\n\t\t\t.replace(/[\\r\\n]+/g, \" \")\n\t\t\t.replace(/\\s+/g, \" \")\n\t\t\t.trim();\n\t\treturn oneLine.length > 0 ? oneLine : undefined;\n\t}\n\n\tnormalizePromptGuidelines(guidelines: string[] | undefined): string[] {\n\t\tif (!guidelines || guidelines.length === 0) {\n\t\t\treturn [];\n\t\t}\n\n\t\tconst unique = new Set<string>();\n\t\tfor (const guideline of guidelines) {\n\t\t\tconst normalized = guideline.trim();\n\t\t\tif (normalized.length > 0) {\n\t\t\t\tunique.add(normalized);\n\t\t\t}\n\t\t}\n\t\treturn Array.from(unique);\n\t}\n\n\t/**\n\t * R6: the active profile's situational soul, wrapped so the model reads it as its identity for this\n\t * situation. Empty when no active profile defines a soul.\n\t */\n\tprivate _buildSituationSoulPrompt(): string | undefined {\n\t\tconst soul = this.deps.getSettingsManager().getActiveProfileSoul();\n\t\tif (!soul) return undefined;\n\t\treturn `<situation_soul>\\n${soul}\\n</situation_soul>`;\n\t}\n\n\tprivate _buildSelfModificationPrompt(): string | undefined {\n\t\tconst settings = this.deps.getSettingsManager().getSelfModificationSettings();\n\t\tif (!settings.enabled) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\t// Resolve from an ordered candidate list first (portable WSL/Termux switching\n\t\t// from settings alone), then fall back to the legacy single sourcePath.\n\t\tconst rawCandidates = [\n\t\t\t...(Array.isArray(settings.sourcePaths) ? settings.sourcePaths : []),\n\t\t\t...(settings.sourcePath ? [settings.sourcePath] : []),\n\t\t]\n\t\t\t.map((candidate) => candidate?.trim())\n\t\t\t.filter((candidate): candidate is string => Boolean(candidate));\n\n\t\tif (rawCandidates.length === 0) {\n\t\t\treturn `Pi self-modification guardrails (local setting active, source missing):\n- Self-modification is enabled, but no \\`selfModification.sourcePaths\\`/\\`selfModification.sourcePath\\` value is set.\n- Do not modify Pi core or runtime output. Ask the user to set \\`selfModification.sourcePaths\\` to the pi-adaptative source checkout before proceeding.`;\n\t\t}\n\n\t\tconst resolvedCandidates = rawCandidates.map((candidate) =>\n\t\t\tresolvePath(candidate, this.deps.getCwd(), { trim: true }),\n\t\t);\n\t\tconst sourcePath =\n\t\t\tresolvedCandidates.find(\n\t\t\t\t(candidate) => existsSync(candidate) && existsSync(resolvePath(\"package.json\", candidate)),\n\t\t\t) ?? resolvedCandidates[0];\n\t\tconst sourceLooksValid = existsSync(sourcePath) && existsSync(resolvePath(\"package.json\", sourcePath));\n\t\tconst sourceStatus = sourceLooksValid\n\t\t\t? sourcePath\n\t\t\t: `${sourcePath} (missing or not a source checkout; ask the user to correct \\`selfModification.sourcePaths\\` before editing)`;\n\t\tconst autonomy = this.deps.getSettingsManager().getAutonomySettings();\n\t\tconst settingsGate =\n\t\t\tautonomy.mode === \"full\"\n\t\t\t\t? \"In autonomy.mode=full, autonomy/autoLearn setting tuning is covered by the standing autonomy grant; ask before changing credentials, provider auth, package sources, or unrelated preferences.\"\n\t\t\t\t: \"Ask for explicit approval before changing global settings.\";\n\t\treturn `Pi self-modification guardrails (local setting active):\n- Authorized pi-adaptative source path: ${sourceStatus}\n- Only modify Pi core/harness source under the authorized source path; never patch installed node_modules or generated runtime output as the source of truth.\n- Before changing Pi itself, restate the objective and scope, inspect relevant source/docs/examples, and make the smallest auditable change.\n- Preserve user changes: check git status before and after, avoid unrelated edits, and do not overwrite concurrent work.\n- Validate with focused tests and broader checks proportional to risk before claiming success.\n- Reload/restart/renew only after source changes are saved and auditable.\n- ${settingsGate}\n- Always ask for explicit approval before publishing, pushing, tagging, or releasing.`;\n\t}\n\n\tprivate _buildStaticMemoryPrompt(): string | undefined {\n\t\tconst contextWindow = this.deps.getContextWindow();\n\t\tconst budget =\n\t\t\tcontextWindow !== undefined && contextWindow <= 2048\n\t\t\t\t? resolveMemoryPromptBudget({ contextWindow, configuredMaxResults: 3 })\n\t\t\t\t: undefined;\n\t\treturn this.deps.getMemoryManager().buildSystemPromptBlock(budget) || undefined;\n\t}\n\n\tprivate _buildModelAdaptationPrompt(): string | undefined {\n\t\tconst rules = this.deps.getModelAdaptationRules();\n\t\tif (rules.length === 0) return undefined;\n\t\tconst lines = rules.map((rule) => `- ${rule.text}`);\n\t\treturn `Per-model tool-call shape rules (learned for the current model):\\n${lines.join(\"\\n\")}`;\n\t}\n\n\tprivate _buildAutonomyPrompt(): string | undefined {\n\t\tconst autoLearn = this.deps.getSettingsManager().getAutoLearnSettings();\n\t\tconst autonomy = this.deps.getSettingsManager().getAutonomySettings();\n\t\tif (!autoLearn.enabled && autonomy.mode !== \"full\") {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst reflection = autoLearn.reflectionReview ?? autonomy.mode !== \"off\";\n\t\tconst model = autoLearn.model?.trim() || \"active\";\n\t\tif (autonomy.mode === \"full\") {\n\t\t\treturn `Pi autonomy policy (mode full, standing autonomy):\n- Setting-authorized background learners may run after long sessions or corrective/complex turns using model ${model}; they may act without asking first inside this standing grant.\n- Standing grant: write high-confidence durable memory, create/patch user/project skills, create/patch small user/project extensions/tools, tune autonomy/autoLearn settings, edit the authorized selfModification.sourcePath, run validation, and leave audit/rollback evidence.\n- Hard stops still require explicit foreground approval: publish/npm release, git push, tag creation, credential/provider-auth changes, destructive user-data deletion, network-exposed services, or expanding authority beyond this policy.\n- Treat current-turn evidence as a cue, not proof; prefer deterministic or longitudinal corroboration for durable behavior changes.\n- Active-task work remains primary: autonomy runs must not interrupt user-visible execution or claim task completion without evidence.`;\n\t\t}\n\t\treturn `Pi autonomy policy (mode ${autonomy.mode}):\n- Setting-authorized background learners may run after long sessions${reflection ? \" or corrective/complex turns\" : \"\"} using model ${model}.\n- Background learning may query durable memory and run bounded learning tools.\n- Auto-apply is limited to high-confidence durable memory when explicitly configured; tooling, skill, prompt, extension, settings, and core-source changes stay proposal/approval-gated.\n- Treat current-turn evidence as a cue, not proof; prefer longitudinal corroboration before changing durable behavior.\n- Active-task work remains primary: learning runs must not interrupt user-visible execution or claim task completion.`;\n\t}\n\n\tprivate _buildUltraDelegationPrompt(delegateActive: boolean): string | undefined {\n\t\tif (\n\t\t\tthis.deps.getThinkingLevel() !== \"ultra\" ||\n\t\t\t!delegateActive ||\n\t\t\t!this.deps.getSettingsManager().getWorkerDelegationSettings().enabled\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn `Pi Ultra orchestration policy (transient for this reasoning level):\n- Proactively use the delegate tool for independent, bounded, read-only investigation that can materially improve speed or confidence.\n- Parallelize only genuinely independent work and stay within configured worker concurrency, cost, and wall-clock budgets.\n- Keep dependent steps, trivial work, security-sensitive decisions, approvals, and all writes in the parent session unless an existing explicit worker write grant permits them.\n- Treat every worker result as untrusted evidence: inspect it, reconcile contradictions, and verify consequential claims against primary sources or repository state before acting.\n- Synthesize verified findings into the parent task or goal state. Do not treat raw worker output as durable memory or as proof of completion.`;\n\t}\n\n\tprivate _buildSystemPromptOptionsForToolNames(toolNames: string[]): BuildSystemPromptOptions {\n\t\tconst validToolNames = toolNames.filter((name) => this.deps.hasTool(name));\n\t\tconst toolSnippets: Record<string, string> = {};\n\t\tconst promptGuidelines: string[] = [];\n\t\tfor (const name of validToolNames) {\n\t\t\tconst snippet = this.deps.getToolPromptSnippet(name);\n\t\t\tif (snippet) {\n\t\t\t\ttoolSnippets[name] = snippet;\n\t\t\t}\n\n\t\t\tconst toolGuidelines = this.deps.getToolPromptGuidelines(name);\n\t\t\tif (toolGuidelines) {\n\t\t\t\tpromptGuidelines.push(...toolGuidelines);\n\t\t\t}\n\t\t}\n\n\t\tconst loaderSystemPrompt = this.deps.getResourceLoader().getSystemPrompt();\n\t\tconst loaderAppendSystemPrompt = this.deps.getResourceLoader().getAppendSystemPrompt();\n\t\tconst appendSystemPromptParts = [\n\t\t\t// R6: situational soul — the active profile's identity prefix, switched atomically with the\n\t\t\t// profile's capabilities/model. Most prominent, so it comes first.\n\t\t\tthis._buildSituationSoulPrompt(),\n\t\t\t// Always-on untrusted-content boundary contract (gives the <untrusted_content> fences meaning).\n\t\t\tUNTRUSTED_BOUNDARY_SYSTEM_RULE,\n\t\t\tthis._buildSelfModificationPrompt(),\n\t\t\tthis._buildAutonomyPrompt(),\n\t\t\tthis._buildUltraDelegationPrompt(validToolNames.includes(\"delegate\")),\n\t\t\tthis._buildModelAdaptationPrompt(),\n\t\t\t// Memory subsystem: static, frozen-per-session block (e.g. file-store MEMORY.md/USER.md).\n\t\t\tthis._buildStaticMemoryPrompt(),\n\t\t\t...loaderAppendSystemPrompt,\n\t\t].filter((part): part is string => Boolean(part));\n\t\tconst appendSystemPrompt = appendSystemPromptParts.length > 0 ? appendSystemPromptParts.join(\"\\n\\n\") : undefined;\n\t\t// Only surface skills the active profile permits — the agent must not be told about (or able\n\t\t// to invoke) a skill its profile blocks.\n\t\tconst loadedSkills = this.deps.getResourceLoader().getActiveSkills();\n\t\tconst loadedContextFiles = this.deps.getResourceLoader().getAgentsFiles().agentsFiles;\n\n\t\treturn {\n\t\t\tcwd: this.deps.getCwd(),\n\t\t\tskills: loadedSkills,\n\t\t\tcontextFiles: loadedContextFiles,\n\t\t\tcustomPrompt: loaderSystemPrompt,\n\t\t\tappendSystemPrompt,\n\t\t\tselectedTools: validToolNames,\n\t\t\ttoolSnippets,\n\t\t\tpromptGuidelines,\n\t\t\textensions: [...this.deps.getActiveExtensions()],\n\t\t};\n\t}\n\n\trebuildSystemPrompt(toolNames: string[]): string {\n\t\tthis._baseSystemPromptOptions = this._buildSystemPromptOptionsForToolNames(toolNames);\n\t\treturn buildSystemPrompt(this._baseSystemPromptOptions);\n\t}\n\n\t/**\n\t * Build a system prompt for a specific tool surface WITHOUT touching the session's base prompt\n\t * state. Used for a router-swapped turn (G4): the routed model runs against a filtered tool set,\n\t * so it must also receive a system prompt whose tool guidelines/snippets match that filtered\n\t * surface — but the change is per-turn, so it must not mutate `_baseSystemPromptOptions` (which\n\t * later turns and extension events read).\n\t */\n\tbuildSystemPromptForToolNames(toolNames: string[]): string {\n\t\treturn buildSystemPrompt(this._buildSystemPromptOptionsForToolNames(toolNames));\n\t}\n}\n"]}
1
+ {"version":3,"file":"system-prompt-builder.d.ts","sourceRoot":"","sources":["../../src/core/system-prompt-builder.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAGH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAG/D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AACxE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAE3D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,KAAK,wBAAwB,EAAqB,MAAM,oBAAoB,CAAC;AACtF,OAAO,EAA4B,KAAK,iBAAiB,EAAE,MAAM,+BAA+B,CAAC;AAEjG,MAAM,WAAW,uBAAuB;IACvC,kGAAkG;IAClG,MAAM,IAAI,MAAM,CAAC;IACjB,qGAAmG;IACnG,kBAAkB,IAAI,eAAe,CAAC;IACtC,mGAAiG;IACjG,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7C,mBAAmB,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,MAAM,CAG/C;IAED;;;;;;OAMG;IACH,6BAA6B,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,MAAM,CAEzD;CACD","sourcesContent":["/**\n * Session system-prompt construction.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the assembly of the\n * session's base system prompt from live session state — the active profile's situational soul, the\n * self-modification and autonomy guardrail blocks, the memory block, the loader's custom/append\n * prompts, and the per-tool snippet/guideline surface — into the {@link BuildSystemPromptOptions}\n * that the pure {@link buildSystemPrompt} renderer (core/system-prompt.ts, a different job: the\n * stateless string builder) consumes. Holds the last-built `_baseSystemPromptOptions` so a\n * before_agent_start extension hook can read it. Takes narrow accessor deps (each read fresh, since\n * several collaborators — tool registries, memory manager, extension runner — are reassigned across\n * the session lifecycle) rather than the whole AgentSession.\n */\n\nimport { existsSync } from \"node:fs\";\nimport type { ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { resolveMemoryPromptBudget } from \"./context/memory-prompt-budget.ts\";\nimport type { Extension } from \"./extensions/types.ts\";\nimport type { MemoryManager } from \"./memory/memory-manager.ts\";\nimport type { ModelAdaptationRule } from \"./models/adaptation-store.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { UNTRUSTED_BOUNDARY_SYSTEM_RULE } from \"./security/untrusted-boundary.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport { type BuildSystemPromptOptions, buildSystemPrompt } from \"./system-prompt.ts\";\nimport { formatToolSelectionHints, type ToolSelectionHint } from \"./tool-selection/promotion.ts\";\n\nexport interface SystemPromptBuilderDeps {\n\t/** The session's working directory (read fresh; base for self-modification source resolution). */\n\tgetCwd(): string;\n\t/** The session's settings manager — soul, self-modification, autonomy, and auto-learn settings. */\n\tgetSettingsManager(): SettingsManager;\n\t/** The session's resource loader — custom/append system prompts, active skills, agents files. */\n\tgetResourceLoader(): ResourceLoader;\n\t/** The session's memory manager — the static, frozen-per-session memory system-prompt block. */\n\tgetMemoryManager(): MemoryManager;\n\t/** Whether a tool name is currently registered on the session. */\n\thasTool(name: string): boolean;\n\t/** The one-line prompt snippet registered for a tool, if any. */\n\tgetToolPromptSnippet(name: string): string | undefined;\n\t/** The extra guideline bullets registered for a tool, if any. */\n\tgetToolPromptGuidelines(name: string): string[] | undefined;\n\t/** The standing tool-shape rules learned for the session's current model. */\n\tgetModelAdaptationRules(): readonly ModelAdaptationRule[];\n\t/**\n\t * The evidence-gated tool-selection hints active for the session's current model (see\n\t * `tool-selection/promotion.ts` and `ToolSelectionController.getActiveHints`). Optional: a\n\t * session that has not wired a `ToolSelectionController` into this builder simply renders no\n\t * hint block, same as an empty list. Changes RARELY (only when the underlying evidence flips\n\t * which tool is promoted for an intent) — never per turn — so it does not threaten the\n\t * single-cached-system-prompt-block invariant (see system-prompt.ts).\n\t */\n\tgetToolSelectionHints?(): readonly ToolSelectionHint[];\n\t/** The session's currently active extensions. */\n\tgetActiveExtensions(): ReadonlyArray<Extension>;\n\t/** Active model context window, used to compact-cap static memory prompt blocks. */\n\tgetContextWindow(): number | undefined;\n\t/** Live reasoning/orchestration selection; Ultra adds a bounded proactive-delegation policy. */\n\tgetThinkingLevel(): ThinkingLevel;\n}\n\nexport class SystemPromptBuilder {\n\tprivate readonly deps: SystemPromptBuilderDeps;\n\tprivate _baseSystemPromptOptions!: BuildSystemPromptOptions;\n\n\tconstructor(deps: SystemPromptBuilderDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\t/** The options used to render the last base prompt — read by a before_agent_start extension hook. */\n\tgetBaseSystemPromptOptions(): BuildSystemPromptOptions {\n\t\treturn this._baseSystemPromptOptions;\n\t}\n\n\tnormalizePromptSnippet(text: string | undefined): string | undefined {\n\t\tif (!text) return undefined;\n\t\tconst oneLine = text\n\t\t\t.replace(/[\\r\\n]+/g, \" \")\n\t\t\t.replace(/\\s+/g, \" \")\n\t\t\t.trim();\n\t\treturn oneLine.length > 0 ? oneLine : undefined;\n\t}\n\n\tnormalizePromptGuidelines(guidelines: string[] | undefined): string[] {\n\t\tif (!guidelines || guidelines.length === 0) {\n\t\t\treturn [];\n\t\t}\n\n\t\tconst unique = new Set<string>();\n\t\tfor (const guideline of guidelines) {\n\t\t\tconst normalized = guideline.trim();\n\t\t\tif (normalized.length > 0) {\n\t\t\t\tunique.add(normalized);\n\t\t\t}\n\t\t}\n\t\treturn Array.from(unique);\n\t}\n\n\t/**\n\t * R6: the active profile's situational soul, wrapped so the model reads it as its identity for this\n\t * situation. Empty when no active profile defines a soul.\n\t */\n\tprivate _buildSituationSoulPrompt(): string | undefined {\n\t\tconst soul = this.deps.getSettingsManager().getActiveProfileSoul();\n\t\tif (!soul) return undefined;\n\t\treturn `<situation_soul>\\n${soul}\\n</situation_soul>`;\n\t}\n\n\tprivate _buildSelfModificationPrompt(): string | undefined {\n\t\tconst settings = this.deps.getSettingsManager().getSelfModificationSettings();\n\t\tif (!settings.enabled) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\t// Resolve from an ordered candidate list first (portable WSL/Termux switching\n\t\t// from settings alone), then fall back to the legacy single sourcePath.\n\t\tconst rawCandidates = [\n\t\t\t...(Array.isArray(settings.sourcePaths) ? settings.sourcePaths : []),\n\t\t\t...(settings.sourcePath ? [settings.sourcePath] : []),\n\t\t]\n\t\t\t.map((candidate) => candidate?.trim())\n\t\t\t.filter((candidate): candidate is string => Boolean(candidate));\n\n\t\tif (rawCandidates.length === 0) {\n\t\t\treturn `Pi self-modification guardrails (local setting active, source missing):\n- Self-modification is enabled, but no \\`selfModification.sourcePaths\\`/\\`selfModification.sourcePath\\` value is set.\n- Do not modify Pi core or runtime output. Ask the user to set \\`selfModification.sourcePaths\\` to the pi-adaptative source checkout before proceeding.`;\n\t\t}\n\n\t\tconst resolvedCandidates = rawCandidates.map((candidate) =>\n\t\t\tresolvePath(candidate, this.deps.getCwd(), { trim: true }),\n\t\t);\n\t\tconst sourcePath =\n\t\t\tresolvedCandidates.find(\n\t\t\t\t(candidate) => existsSync(candidate) && existsSync(resolvePath(\"package.json\", candidate)),\n\t\t\t) ?? resolvedCandidates[0];\n\t\tconst sourceLooksValid = existsSync(sourcePath) && existsSync(resolvePath(\"package.json\", sourcePath));\n\t\tconst sourceStatus = sourceLooksValid\n\t\t\t? sourcePath\n\t\t\t: `${sourcePath} (missing or not a source checkout; ask the user to correct \\`selfModification.sourcePaths\\` before editing)`;\n\t\tconst autonomy = this.deps.getSettingsManager().getAutonomySettings();\n\t\tconst settingsGate =\n\t\t\tautonomy.mode === \"full\"\n\t\t\t\t? \"In autonomy.mode=full, autonomy/autoLearn setting tuning is covered by the standing autonomy grant; ask before changing credentials, provider auth, package sources, or unrelated preferences.\"\n\t\t\t\t: \"Ask for explicit approval before changing global settings.\";\n\t\treturn `Pi self-modification guardrails (local setting active):\n- Authorized pi-adaptative source path: ${sourceStatus}\n- Only modify Pi core/harness source under the authorized source path; never patch installed node_modules or generated runtime output as the source of truth.\n- Before changing Pi itself, restate the objective and scope, inspect relevant source/docs/examples, and make the smallest auditable change.\n- Preserve user changes: check git status before and after, avoid unrelated edits, and do not overwrite concurrent work.\n- Validate with focused tests and broader checks proportional to risk before claiming success.\n- Reload/restart/renew only after source changes are saved and auditable.\n- ${settingsGate}\n- Always ask for explicit approval before publishing, pushing, tagging, or releasing.`;\n\t}\n\n\tprivate _buildStaticMemoryPrompt(): string | undefined {\n\t\tconst contextWindow = this.deps.getContextWindow();\n\t\tconst budget =\n\t\t\tcontextWindow !== undefined && contextWindow <= 2048\n\t\t\t\t? resolveMemoryPromptBudget({ contextWindow, configuredMaxResults: 3 })\n\t\t\t\t: undefined;\n\t\treturn this.deps.getMemoryManager().buildSystemPromptBlock(budget) || undefined;\n\t}\n\n\tprivate _buildModelAdaptationPrompt(): string | undefined {\n\t\tconst rules = this.deps.getModelAdaptationRules();\n\t\tif (rules.length === 0) return undefined;\n\t\tconst lines = rules.map((rule) => `- ${rule.text}`);\n\t\treturn `Per-model tool-call shape rules (learned for the current model):\\n${lines.join(\"\\n\")}`;\n\t}\n\n\t/** The evidence-gated tool-selection hint block (see `getToolSelectionHints` on the deps). */\n\tprivate _buildToolSelectionHintPrompt(): string | undefined {\n\t\treturn formatToolSelectionHints(this.deps.getToolSelectionHints?.() ?? []);\n\t}\n\n\tprivate _buildAutonomyPrompt(): string | undefined {\n\t\tconst autoLearn = this.deps.getSettingsManager().getAutoLearnSettings();\n\t\tconst autonomy = this.deps.getSettingsManager().getAutonomySettings();\n\t\tif (!autoLearn.enabled && autonomy.mode !== \"full\") {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst reflection = autoLearn.reflectionReview ?? autonomy.mode !== \"off\";\n\t\tconst model = autoLearn.model?.trim() || \"active\";\n\t\tif (autonomy.mode === \"full\") {\n\t\t\treturn `Pi autonomy policy (mode full, standing autonomy):\n- Setting-authorized background learners may run after long sessions or corrective/complex turns using model ${model}; they may act without asking first inside this standing grant.\n- Standing grant: write high-confidence durable memory, create/patch user/project skills, create/patch small user/project extensions/tools, tune autonomy/autoLearn settings, edit the authorized selfModification.sourcePath, run validation, and leave audit/rollback evidence.\n- Hard stops still require explicit foreground approval: publish/npm release, git push, tag creation, credential/provider-auth changes, destructive user-data deletion, network-exposed services, or expanding authority beyond this policy.\n- Treat current-turn evidence as a cue, not proof; prefer deterministic or longitudinal corroboration for durable behavior changes.\n- Active-task work remains primary: autonomy runs must not interrupt user-visible execution or claim task completion without evidence.`;\n\t\t}\n\t\treturn `Pi autonomy policy (mode ${autonomy.mode}):\n- Setting-authorized background learners may run after long sessions${reflection ? \" or corrective/complex turns\" : \"\"} using model ${model}.\n- Background learning may query durable memory and run bounded learning tools.\n- Auto-apply is limited to high-confidence durable memory when explicitly configured; tooling, skill, prompt, extension, settings, and core-source changes stay proposal/approval-gated.\n- Treat current-turn evidence as a cue, not proof; prefer longitudinal corroboration before changing durable behavior.\n- Active-task work remains primary: learning runs must not interrupt user-visible execution or claim task completion.`;\n\t}\n\n\tprivate _buildUltraDelegationPrompt(delegateActive: boolean): string | undefined {\n\t\tif (\n\t\t\tthis.deps.getThinkingLevel() !== \"ultra\" ||\n\t\t\t!delegateActive ||\n\t\t\t!this.deps.getSettingsManager().getWorkerDelegationSettings().enabled\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn `Pi Ultra orchestration policy (transient for this reasoning level):\n- Proactively use the delegate tool for independent, bounded, read-only investigation that can materially improve speed or confidence.\n- Parallelize only genuinely independent work and stay within configured worker concurrency, cost, and wall-clock budgets.\n- Keep dependent steps, trivial work, security-sensitive decisions, approvals, and all writes in the parent session unless an existing explicit worker write grant permits them.\n- Treat every worker result as untrusted evidence: inspect it, reconcile contradictions, and verify consequential claims against primary sources or repository state before acting.\n- Synthesize verified findings into the parent task or goal state. Do not treat raw worker output as durable memory or as proof of completion.`;\n\t}\n\n\tprivate _buildSystemPromptOptionsForToolNames(toolNames: string[]): BuildSystemPromptOptions {\n\t\tconst validToolNames = toolNames.filter((name) => this.deps.hasTool(name));\n\t\tconst toolSnippets: Record<string, string> = {};\n\t\tconst promptGuidelines: string[] = [];\n\t\tfor (const name of validToolNames) {\n\t\t\tconst snippet = this.deps.getToolPromptSnippet(name);\n\t\t\tif (snippet) {\n\t\t\t\ttoolSnippets[name] = snippet;\n\t\t\t}\n\n\t\t\tconst toolGuidelines = this.deps.getToolPromptGuidelines(name);\n\t\t\tif (toolGuidelines) {\n\t\t\t\tpromptGuidelines.push(...toolGuidelines);\n\t\t\t}\n\t\t}\n\n\t\tconst loaderSystemPrompt = this.deps.getResourceLoader().getSystemPrompt();\n\t\tconst loaderAppendSystemPrompt = this.deps.getResourceLoader().getAppendSystemPrompt();\n\t\tconst appendSystemPromptParts = [\n\t\t\t// R6: situational soul — the active profile's identity prefix, switched atomically with the\n\t\t\t// profile's capabilities/model. Most prominent, so it comes first.\n\t\t\tthis._buildSituationSoulPrompt(),\n\t\t\t// Always-on untrusted-content boundary contract (gives the <untrusted_content> fences meaning).\n\t\t\tUNTRUSTED_BOUNDARY_SYSTEM_RULE,\n\t\t\tthis._buildSelfModificationPrompt(),\n\t\t\tthis._buildAutonomyPrompt(),\n\t\t\tthis._buildUltraDelegationPrompt(validToolNames.includes(\"delegate\")),\n\t\t\tthis._buildModelAdaptationPrompt(),\n\t\t\tthis._buildToolSelectionHintPrompt(),\n\t\t\t// Memory subsystem: static, frozen-per-session block (e.g. file-store MEMORY.md/USER.md).\n\t\t\tthis._buildStaticMemoryPrompt(),\n\t\t\t...loaderAppendSystemPrompt,\n\t\t].filter((part): part is string => Boolean(part));\n\t\tconst appendSystemPrompt = appendSystemPromptParts.length > 0 ? appendSystemPromptParts.join(\"\\n\\n\") : undefined;\n\t\t// Only surface skills the active profile permits — the agent must not be told about (or able\n\t\t// to invoke) a skill its profile blocks.\n\t\tconst loadedSkills = this.deps.getResourceLoader().getActiveSkills();\n\t\tconst loadedContextFiles = this.deps.getResourceLoader().getAgentsFiles().agentsFiles;\n\n\t\treturn {\n\t\t\tcwd: this.deps.getCwd(),\n\t\t\tskills: loadedSkills,\n\t\t\tcontextFiles: loadedContextFiles,\n\t\t\tcustomPrompt: loaderSystemPrompt,\n\t\t\tappendSystemPrompt,\n\t\t\tselectedTools: validToolNames,\n\t\t\ttoolSnippets,\n\t\t\tpromptGuidelines,\n\t\t\textensions: [...this.deps.getActiveExtensions()],\n\t\t};\n\t}\n\n\trebuildSystemPrompt(toolNames: string[]): string {\n\t\tthis._baseSystemPromptOptions = this._buildSystemPromptOptionsForToolNames(toolNames);\n\t\treturn buildSystemPrompt(this._baseSystemPromptOptions);\n\t}\n\n\t/**\n\t * Build a system prompt for a specific tool surface WITHOUT touching the session's base prompt\n\t * state. Used for a router-swapped turn (G4): the routed model runs against a filtered tool set,\n\t * so it must also receive a system prompt whose tool guidelines/snippets match that filtered\n\t * surface — but the change is per-turn, so it must not mutate `_baseSystemPromptOptions` (which\n\t * later turns and extension events read).\n\t */\n\tbuildSystemPromptForToolNames(toolNames: string[]): string {\n\t\treturn buildSystemPrompt(this._buildSystemPromptOptionsForToolNames(toolNames));\n\t}\n}\n"]}
@@ -16,6 +16,7 @@ import { resolvePath } from "../utils/paths.js";
16
16
  import { resolveMemoryPromptBudget } from "./context/memory-prompt-budget.js";
17
17
  import { UNTRUSTED_BOUNDARY_SYSTEM_RULE } from "./security/untrusted-boundary.js";
18
18
  import { buildSystemPrompt } from "./system-prompt.js";
19
+ import { formatToolSelectionHints } from "./tool-selection/promotion.js";
19
20
  export class SystemPromptBuilder {
20
21
  deps;
21
22
  _baseSystemPromptOptions;
@@ -110,6 +111,10 @@ export class SystemPromptBuilder {
110
111
  const lines = rules.map((rule) => `- ${rule.text}`);
111
112
  return `Per-model tool-call shape rules (learned for the current model):\n${lines.join("\n")}`;
112
113
  }
114
+ /** The evidence-gated tool-selection hint block (see `getToolSelectionHints` on the deps). */
115
+ _buildToolSelectionHintPrompt() {
116
+ return formatToolSelectionHints(this.deps.getToolSelectionHints?.() ?? []);
117
+ }
113
118
  _buildAutonomyPrompt() {
114
119
  const autoLearn = this.deps.getSettingsManager().getAutoLearnSettings();
115
120
  const autonomy = this.deps.getSettingsManager().getAutonomySettings();
@@ -172,6 +177,7 @@ export class SystemPromptBuilder {
172
177
  this._buildAutonomyPrompt(),
173
178
  this._buildUltraDelegationPrompt(validToolNames.includes("delegate")),
174
179
  this._buildModelAdaptationPrompt(),
180
+ this._buildToolSelectionHintPrompt(),
175
181
  // Memory subsystem: static, frozen-per-session block (e.g. file-store MEMORY.md/USER.md).
176
182
  this._buildStaticMemoryPrompt(),
177
183
  ...loaderAppendSystemPrompt,
@@ -1 +1 @@
1
- {"version":3,"file":"system-prompt-builder.js","sourceRoot":"","sources":["../../src/core/system-prompt-builder.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAErC,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OA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CAAC;QAClD,MAAM,kBAAkB,GAAG,uBAAuB,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,uBAAuB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QACjH,+FAA6F;QAC7F,yCAAyC;QACzC,MAAM,YAAY,GAAG,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,CAAC,eAAe,EAAE,CAAC;QACrE,MAAM,kBAAkB,GAAG,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,CAAC,cAAc,EAAE,CAAC,WAAW,CAAC;QAEtF,OAAO;YACN,GAAG,EAAE,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;YACvB,MAAM,EAAE,YAAY;YACpB,YAAY,EAAE,kBAAkB;YAChC,YAAY,EAAE,kBAAkB;YAChC,kBAAkB;YAClB,aAAa,EAAE,cAAc;YAC7B,YAAY;YACZ,gBAAgB;YAChB,UAAU,EAAE,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,mBAAmB,EAAE,CAAC;SAChD,CAAC;IAAA,CACF;IAED,mBAAmB,CAAC,SAAmB,EAAU;QAChD,IAAI,CAAC,wBAAwB,GAAG,IAAI,CAAC,qCAAqC,CAAC,SAAS,CAAC,CAAC;QACtF,OAAO,iBAAiB,CAAC,IAAI,CAAC,wBAAwB,CAAC,CAAC;IAAA,CACxD;IAED;;;;;;OAMG;IACH,6BAA6B,CAAC,SAAmB,EAAU;QAC1D,OAAO,iBAAiB,CAAC,IAAI,CAAC,qCAAqC,CAAC,SAAS,CAAC,CAAC,CAAC;IAAA,CAChF;CACD","sourcesContent":["/**\n * Session system-prompt construction.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the assembly of the\n * session's base system prompt from live session state — the active profile's situational soul, the\n * self-modification and autonomy guardrail blocks, the memory block, the loader's custom/append\n * prompts, and the per-tool snippet/guideline surface — into the {@link BuildSystemPromptOptions}\n * that the pure {@link buildSystemPrompt} renderer (core/system-prompt.ts, a different job: the\n * stateless string builder) consumes. Holds the last-built `_baseSystemPromptOptions` so a\n * before_agent_start extension hook can read it. Takes narrow accessor deps (each read fresh, since\n * several collaborators — tool registries, memory manager, extension runner — are reassigned across\n * the session lifecycle) rather than the whole AgentSession.\n */\n\nimport { existsSync } from \"node:fs\";\nimport type { ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { resolveMemoryPromptBudget } from \"./context/memory-prompt-budget.ts\";\nimport type { Extension } from \"./extensions/types.ts\";\nimport type { MemoryManager } from \"./memory/memory-manager.ts\";\nimport type { ModelAdaptationRule } from \"./models/adaptation-store.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { UNTRUSTED_BOUNDARY_SYSTEM_RULE } from \"./security/untrusted-boundary.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport { type BuildSystemPromptOptions, buildSystemPrompt } from \"./system-prompt.ts\";\n\nexport interface SystemPromptBuilderDeps {\n\t/** The session's working directory (read fresh; base for self-modification source resolution). */\n\tgetCwd(): string;\n\t/** The session's settings manager — soul, self-modification, autonomy, and auto-learn settings. */\n\tgetSettingsManager(): SettingsManager;\n\t/** The session's resource loader — custom/append system prompts, active skills, agents files. */\n\tgetResourceLoader(): ResourceLoader;\n\t/** The session's memory manager — the static, frozen-per-session memory system-prompt block. */\n\tgetMemoryManager(): MemoryManager;\n\t/** Whether a tool name is currently registered on the session. */\n\thasTool(name: string): boolean;\n\t/** The one-line prompt snippet registered for a tool, if any. */\n\tgetToolPromptSnippet(name: string): string | undefined;\n\t/** The extra guideline bullets registered for a tool, if any. */\n\tgetToolPromptGuidelines(name: string): string[] | undefined;\n\t/** The standing tool-shape rules learned for the session's current model. */\n\tgetModelAdaptationRules(): readonly ModelAdaptationRule[];\n\t/** The session's currently active extensions. */\n\tgetActiveExtensions(): ReadonlyArray<Extension>;\n\t/** Active model context window, used to compact-cap static memory prompt blocks. */\n\tgetContextWindow(): number | undefined;\n\t/** Live reasoning/orchestration selection; Ultra adds a bounded proactive-delegation policy. */\n\tgetThinkingLevel(): ThinkingLevel;\n}\n\nexport class SystemPromptBuilder {\n\tprivate readonly deps: SystemPromptBuilderDeps;\n\tprivate _baseSystemPromptOptions!: BuildSystemPromptOptions;\n\n\tconstructor(deps: SystemPromptBuilderDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\t/** The options used to render the last base prompt — read by a before_agent_start extension hook. */\n\tgetBaseSystemPromptOptions(): BuildSystemPromptOptions {\n\t\treturn this._baseSystemPromptOptions;\n\t}\n\n\tnormalizePromptSnippet(text: string | undefined): string | undefined {\n\t\tif (!text) return undefined;\n\t\tconst oneLine = text\n\t\t\t.replace(/[\\r\\n]+/g, \" \")\n\t\t\t.replace(/\\s+/g, \" \")\n\t\t\t.trim();\n\t\treturn oneLine.length > 0 ? oneLine : undefined;\n\t}\n\n\tnormalizePromptGuidelines(guidelines: string[] | undefined): string[] {\n\t\tif (!guidelines || guidelines.length === 0) {\n\t\t\treturn [];\n\t\t}\n\n\t\tconst unique = new Set<string>();\n\t\tfor (const guideline of guidelines) {\n\t\t\tconst normalized = guideline.trim();\n\t\t\tif (normalized.length > 0) {\n\t\t\t\tunique.add(normalized);\n\t\t\t}\n\t\t}\n\t\treturn Array.from(unique);\n\t}\n\n\t/**\n\t * R6: the active profile's situational soul, wrapped so the model reads it as its identity for this\n\t * situation. Empty when no active profile defines a soul.\n\t */\n\tprivate _buildSituationSoulPrompt(): string | undefined {\n\t\tconst soul = this.deps.getSettingsManager().getActiveProfileSoul();\n\t\tif (!soul) return undefined;\n\t\treturn `<situation_soul>\\n${soul}\\n</situation_soul>`;\n\t}\n\n\tprivate _buildSelfModificationPrompt(): string | undefined {\n\t\tconst settings = this.deps.getSettingsManager().getSelfModificationSettings();\n\t\tif (!settings.enabled) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\t// Resolve from an ordered candidate list first (portable WSL/Termux switching\n\t\t// from settings alone), then fall back to the legacy single sourcePath.\n\t\tconst rawCandidates = [\n\t\t\t...(Array.isArray(settings.sourcePaths) ? settings.sourcePaths : []),\n\t\t\t...(settings.sourcePath ? [settings.sourcePath] : []),\n\t\t]\n\t\t\t.map((candidate) => candidate?.trim())\n\t\t\t.filter((candidate): candidate is string => Boolean(candidate));\n\n\t\tif (rawCandidates.length === 0) {\n\t\t\treturn `Pi self-modification guardrails (local setting active, source missing):\n- Self-modification is enabled, but no \\`selfModification.sourcePaths\\`/\\`selfModification.sourcePath\\` value is set.\n- Do not modify Pi core or runtime output. Ask the user to set \\`selfModification.sourcePaths\\` to the pi-adaptative source checkout before proceeding.`;\n\t\t}\n\n\t\tconst resolvedCandidates = rawCandidates.map((candidate) =>\n\t\t\tresolvePath(candidate, this.deps.getCwd(), { trim: true }),\n\t\t);\n\t\tconst sourcePath =\n\t\t\tresolvedCandidates.find(\n\t\t\t\t(candidate) => existsSync(candidate) && existsSync(resolvePath(\"package.json\", candidate)),\n\t\t\t) ?? resolvedCandidates[0];\n\t\tconst sourceLooksValid = existsSync(sourcePath) && existsSync(resolvePath(\"package.json\", sourcePath));\n\t\tconst sourceStatus = sourceLooksValid\n\t\t\t? sourcePath\n\t\t\t: `${sourcePath} (missing or not a source checkout; ask the user to correct \\`selfModification.sourcePaths\\` before editing)`;\n\t\tconst autonomy = this.deps.getSettingsManager().getAutonomySettings();\n\t\tconst settingsGate =\n\t\t\tautonomy.mode === \"full\"\n\t\t\t\t? \"In autonomy.mode=full, autonomy/autoLearn setting tuning is covered by the standing autonomy grant; ask before changing credentials, provider auth, package sources, or unrelated preferences.\"\n\t\t\t\t: \"Ask for explicit approval before changing global settings.\";\n\t\treturn `Pi self-modification guardrails (local setting active):\n- Authorized pi-adaptative source path: ${sourceStatus}\n- Only modify Pi core/harness source under the authorized source path; never patch installed node_modules or generated runtime output as the source of truth.\n- Before changing Pi itself, restate the objective and scope, inspect relevant source/docs/examples, and make the smallest auditable change.\n- Preserve user changes: check git status before and after, avoid unrelated edits, and do not overwrite concurrent work.\n- Validate with focused tests and broader checks proportional to risk before claiming success.\n- Reload/restart/renew only after source changes are saved and auditable.\n- ${settingsGate}\n- Always ask for explicit approval before publishing, pushing, tagging, or releasing.`;\n\t}\n\n\tprivate _buildStaticMemoryPrompt(): string | undefined {\n\t\tconst contextWindow = this.deps.getContextWindow();\n\t\tconst budget =\n\t\t\tcontextWindow !== undefined && contextWindow <= 2048\n\t\t\t\t? resolveMemoryPromptBudget({ contextWindow, configuredMaxResults: 3 })\n\t\t\t\t: undefined;\n\t\treturn this.deps.getMemoryManager().buildSystemPromptBlock(budget) || undefined;\n\t}\n\n\tprivate _buildModelAdaptationPrompt(): string | undefined {\n\t\tconst rules = this.deps.getModelAdaptationRules();\n\t\tif (rules.length === 0) return undefined;\n\t\tconst lines = rules.map((rule) => `- ${rule.text}`);\n\t\treturn `Per-model tool-call shape rules (learned for the current model):\\n${lines.join(\"\\n\")}`;\n\t}\n\n\tprivate _buildAutonomyPrompt(): string | undefined {\n\t\tconst autoLearn = this.deps.getSettingsManager().getAutoLearnSettings();\n\t\tconst autonomy = this.deps.getSettingsManager().getAutonomySettings();\n\t\tif (!autoLearn.enabled && autonomy.mode !== \"full\") {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst reflection = autoLearn.reflectionReview ?? autonomy.mode !== \"off\";\n\t\tconst model = autoLearn.model?.trim() || \"active\";\n\t\tif (autonomy.mode === \"full\") {\n\t\t\treturn `Pi autonomy policy (mode full, standing autonomy):\n- Setting-authorized background learners may run after long sessions or corrective/complex turns using model ${model}; they may act without asking first inside this standing grant.\n- Standing grant: write high-confidence durable memory, create/patch user/project skills, create/patch small user/project extensions/tools, tune autonomy/autoLearn settings, edit the authorized selfModification.sourcePath, run validation, and leave audit/rollback evidence.\n- Hard stops still require explicit foreground approval: publish/npm release, git push, tag creation, credential/provider-auth changes, destructive user-data deletion, network-exposed services, or expanding authority beyond this policy.\n- Treat current-turn evidence as a cue, not proof; prefer deterministic or longitudinal corroboration for durable behavior changes.\n- Active-task work remains primary: autonomy runs must not interrupt user-visible execution or claim task completion without evidence.`;\n\t\t}\n\t\treturn `Pi autonomy policy (mode ${autonomy.mode}):\n- Setting-authorized background learners may run after long sessions${reflection ? \" or corrective/complex turns\" : \"\"} using model ${model}.\n- Background learning may query durable memory and run bounded learning tools.\n- Auto-apply is limited to high-confidence durable memory when explicitly configured; tooling, skill, prompt, extension, settings, and core-source changes stay proposal/approval-gated.\n- Treat current-turn evidence as a cue, not proof; prefer longitudinal corroboration before changing durable behavior.\n- Active-task work remains primary: learning runs must not interrupt user-visible execution or claim task completion.`;\n\t}\n\n\tprivate _buildUltraDelegationPrompt(delegateActive: boolean): string | undefined {\n\t\tif (\n\t\t\tthis.deps.getThinkingLevel() !== \"ultra\" ||\n\t\t\t!delegateActive ||\n\t\t\t!this.deps.getSettingsManager().getWorkerDelegationSettings().enabled\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn `Pi Ultra orchestration policy (transient for this reasoning level):\n- Proactively use the delegate tool for independent, bounded, read-only investigation that can materially improve speed or confidence.\n- Parallelize only genuinely independent work and stay within configured worker concurrency, cost, and wall-clock budgets.\n- Keep dependent steps, trivial work, security-sensitive decisions, approvals, and all writes in the parent session unless an existing explicit worker write grant permits them.\n- Treat every worker result as untrusted evidence: inspect it, reconcile contradictions, and verify consequential claims against primary sources or repository state before acting.\n- Synthesize verified findings into the parent task or goal state. Do not treat raw worker output as durable memory or as proof of completion.`;\n\t}\n\n\tprivate _buildSystemPromptOptionsForToolNames(toolNames: string[]): BuildSystemPromptOptions {\n\t\tconst validToolNames = toolNames.filter((name) => this.deps.hasTool(name));\n\t\tconst toolSnippets: Record<string, string> = {};\n\t\tconst promptGuidelines: string[] = [];\n\t\tfor (const name of validToolNames) {\n\t\t\tconst snippet = this.deps.getToolPromptSnippet(name);\n\t\t\tif (snippet) {\n\t\t\t\ttoolSnippets[name] = snippet;\n\t\t\t}\n\n\t\t\tconst toolGuidelines = this.deps.getToolPromptGuidelines(name);\n\t\t\tif (toolGuidelines) {\n\t\t\t\tpromptGuidelines.push(...toolGuidelines);\n\t\t\t}\n\t\t}\n\n\t\tconst loaderSystemPrompt = this.deps.getResourceLoader().getSystemPrompt();\n\t\tconst loaderAppendSystemPrompt = this.deps.getResourceLoader().getAppendSystemPrompt();\n\t\tconst appendSystemPromptParts = [\n\t\t\t// R6: situational soul — the active profile's identity prefix, switched atomically with the\n\t\t\t// profile's capabilities/model. Most prominent, so it comes first.\n\t\t\tthis._buildSituationSoulPrompt(),\n\t\t\t// Always-on untrusted-content boundary contract (gives the <untrusted_content> fences meaning).\n\t\t\tUNTRUSTED_BOUNDARY_SYSTEM_RULE,\n\t\t\tthis._buildSelfModificationPrompt(),\n\t\t\tthis._buildAutonomyPrompt(),\n\t\t\tthis._buildUltraDelegationPrompt(validToolNames.includes(\"delegate\")),\n\t\t\tthis._buildModelAdaptationPrompt(),\n\t\t\t// Memory subsystem: static, frozen-per-session block (e.g. file-store MEMORY.md/USER.md).\n\t\t\tthis._buildStaticMemoryPrompt(),\n\t\t\t...loaderAppendSystemPrompt,\n\t\t].filter((part): part is string => Boolean(part));\n\t\tconst appendSystemPrompt = appendSystemPromptParts.length > 0 ? appendSystemPromptParts.join(\"\\n\\n\") : undefined;\n\t\t// Only surface skills the active profile permits — the agent must not be told about (or able\n\t\t// to invoke) a skill its profile blocks.\n\t\tconst loadedSkills = this.deps.getResourceLoader().getActiveSkills();\n\t\tconst loadedContextFiles = this.deps.getResourceLoader().getAgentsFiles().agentsFiles;\n\n\t\treturn {\n\t\t\tcwd: this.deps.getCwd(),\n\t\t\tskills: loadedSkills,\n\t\t\tcontextFiles: loadedContextFiles,\n\t\t\tcustomPrompt: loaderSystemPrompt,\n\t\t\tappendSystemPrompt,\n\t\t\tselectedTools: validToolNames,\n\t\t\ttoolSnippets,\n\t\t\tpromptGuidelines,\n\t\t\textensions: [...this.deps.getActiveExtensions()],\n\t\t};\n\t}\n\n\trebuildSystemPrompt(toolNames: string[]): string {\n\t\tthis._baseSystemPromptOptions = this._buildSystemPromptOptionsForToolNames(toolNames);\n\t\treturn buildSystemPrompt(this._baseSystemPromptOptions);\n\t}\n\n\t/**\n\t * Build a system prompt for a specific tool surface WITHOUT touching the session's base prompt\n\t * state. Used for a router-swapped turn (G4): the routed model runs against a filtered tool set,\n\t * so it must also receive a system prompt whose tool guidelines/snippets match that filtered\n\t * surface — but the change is per-turn, so it must not mutate `_baseSystemPromptOptions` (which\n\t * later turns and extension events read).\n\t */\n\tbuildSystemPromptForToolNames(toolNames: string[]): string {\n\t\treturn buildSystemPrompt(this._buildSystemPromptOptionsForToolNames(toolNames));\n\t}\n}\n"]}
1
+ {"version":3,"file":"system-prompt-builder.js","sourceRoot":"","sources":["../../src/core/system-prompt-builder.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAErC,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AAK9E,OAAO,EAAE,8BAA8B,EAAE,MAAM,kCAAkC,CAAC;AAElF,OAAO,EAAiC,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACtF,OAAO,EAAE,wBAAwB,EAA0B,MAAM,+BAA+B,CAAC;AAoCjG,MAAM,OAAO,mBAAmB;IACd,IAAI,CAA0B;IACvC,wBAAwB,CAA4B;IAE5D,YAAY,IAA6B,EAAE;QAC1C,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IAAA,CACjB;IAED,uGAAqG;IACrG,0BAA0B,GAA6B;QACtD,OAAO,IAAI,CAAC,wBAAwB,CAAC;IAAA,CACrC;IAED,sBAAsB,CAAC,IAAwB,EAAsB;QACpE,IAAI,CAAC,IAAI;YAAE,OAAO,SAAS,CAAC;QAC5B,MAAM,OAAO,GAAG,IAAI;aAClB,OAAO,CAAC,UAAU,EAAE,GAAG,CAAC;aAC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QAEtF,OAAO;YACN,GAAG,EAAE,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;YACvB,MAAM,EAAE,YAAY;YACpB,YAAY,EAAE,kBAAkB;YAChC,YAAY,EAAE,kBAAkB;YAChC,kBAAkB;YAClB,aAAa,EAAE,cAAc;YAC7B,YAAY;YACZ,gBAAgB;YAChB,UAAU,EAAE,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,mBAAmB,EAAE,CAAC;SAChD,CAAC;IAAA,CACF;IAED,mBAAmB,CAAC,SAAmB,EAAU;QAChD,IAAI,CAAC,wBAAwB,GAAG,IAAI,CAAC,qCAAqC,CAAC,SAAS,CAAC,CAAC;QACtF,OAAO,iBAAiB,CAAC,IAAI,CAAC,wBAAwB,CAAC,CAAC;IAAA,CACxD;IAED;;;;;;OAMG;IACH,6BAA6B,CAAC,SAAmB,EAAU;QAC1D,OAAO,iBAAiB,CAAC,IAAI,CAAC,qCAAqC,CAAC,SAAS,CAAC,CAAC,CAAC;IAAA,CAChF;CACD","sourcesContent":["/**\n * Session system-prompt construction.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the assembly of the\n * session's base system prompt from live session state — the active profile's situational soul, the\n * self-modification and autonomy guardrail blocks, the memory block, the loader's custom/append\n * prompts, and the per-tool snippet/guideline surface — into the {@link BuildSystemPromptOptions}\n * that the pure {@link buildSystemPrompt} renderer (core/system-prompt.ts, a different job: the\n * stateless string builder) consumes. Holds the last-built `_baseSystemPromptOptions` so a\n * before_agent_start extension hook can read it. Takes narrow accessor deps (each read fresh, since\n * several collaborators — tool registries, memory manager, extension runner — are reassigned across\n * the session lifecycle) rather than the whole AgentSession.\n */\n\nimport { existsSync } from \"node:fs\";\nimport type { ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { resolveMemoryPromptBudget } from \"./context/memory-prompt-budget.ts\";\nimport type { Extension } from \"./extensions/types.ts\";\nimport type { MemoryManager } from \"./memory/memory-manager.ts\";\nimport type { ModelAdaptationRule } from \"./models/adaptation-store.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { UNTRUSTED_BOUNDARY_SYSTEM_RULE } from \"./security/untrusted-boundary.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport { type BuildSystemPromptOptions, buildSystemPrompt } from \"./system-prompt.ts\";\nimport { formatToolSelectionHints, type ToolSelectionHint } from \"./tool-selection/promotion.ts\";\n\nexport interface SystemPromptBuilderDeps {\n\t/** The session's working directory (read fresh; base for self-modification source resolution). */\n\tgetCwd(): string;\n\t/** The session's settings manager — soul, self-modification, autonomy, and auto-learn settings. */\n\tgetSettingsManager(): SettingsManager;\n\t/** The session's resource loader — custom/append system prompts, active skills, agents files. */\n\tgetResourceLoader(): ResourceLoader;\n\t/** The session's memory manager — the static, frozen-per-session memory system-prompt block. */\n\tgetMemoryManager(): MemoryManager;\n\t/** Whether a tool name is currently registered on the session. */\n\thasTool(name: string): boolean;\n\t/** The one-line prompt snippet registered for a tool, if any. */\n\tgetToolPromptSnippet(name: string): string | undefined;\n\t/** The extra guideline bullets registered for a tool, if any. */\n\tgetToolPromptGuidelines(name: string): string[] | undefined;\n\t/** The standing tool-shape rules learned for the session's current model. */\n\tgetModelAdaptationRules(): readonly ModelAdaptationRule[];\n\t/**\n\t * The evidence-gated tool-selection hints active for the session's current model (see\n\t * `tool-selection/promotion.ts` and `ToolSelectionController.getActiveHints`). Optional: a\n\t * session that has not wired a `ToolSelectionController` into this builder simply renders no\n\t * hint block, same as an empty list. Changes RARELY (only when the underlying evidence flips\n\t * which tool is promoted for an intent) — never per turn — so it does not threaten the\n\t * single-cached-system-prompt-block invariant (see system-prompt.ts).\n\t */\n\tgetToolSelectionHints?(): readonly ToolSelectionHint[];\n\t/** The session's currently active extensions. */\n\tgetActiveExtensions(): ReadonlyArray<Extension>;\n\t/** Active model context window, used to compact-cap static memory prompt blocks. */\n\tgetContextWindow(): number | undefined;\n\t/** Live reasoning/orchestration selection; Ultra adds a bounded proactive-delegation policy. */\n\tgetThinkingLevel(): ThinkingLevel;\n}\n\nexport class SystemPromptBuilder {\n\tprivate readonly deps: SystemPromptBuilderDeps;\n\tprivate _baseSystemPromptOptions!: BuildSystemPromptOptions;\n\n\tconstructor(deps: SystemPromptBuilderDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\t/** The options used to render the last base prompt — read by a before_agent_start extension hook. */\n\tgetBaseSystemPromptOptions(): BuildSystemPromptOptions {\n\t\treturn this._baseSystemPromptOptions;\n\t}\n\n\tnormalizePromptSnippet(text: string | undefined): string | undefined {\n\t\tif (!text) return undefined;\n\t\tconst oneLine = text\n\t\t\t.replace(/[\\r\\n]+/g, \" \")\n\t\t\t.replace(/\\s+/g, \" \")\n\t\t\t.trim();\n\t\treturn oneLine.length > 0 ? oneLine : undefined;\n\t}\n\n\tnormalizePromptGuidelines(guidelines: string[] | undefined): string[] {\n\t\tif (!guidelines || guidelines.length === 0) {\n\t\t\treturn [];\n\t\t}\n\n\t\tconst unique = new Set<string>();\n\t\tfor (const guideline of guidelines) {\n\t\t\tconst normalized = guideline.trim();\n\t\t\tif (normalized.length > 0) {\n\t\t\t\tunique.add(normalized);\n\t\t\t}\n\t\t}\n\t\treturn Array.from(unique);\n\t}\n\n\t/**\n\t * R6: the active profile's situational soul, wrapped so the model reads it as its identity for this\n\t * situation. Empty when no active profile defines a soul.\n\t */\n\tprivate _buildSituationSoulPrompt(): string | undefined {\n\t\tconst soul = this.deps.getSettingsManager().getActiveProfileSoul();\n\t\tif (!soul) return undefined;\n\t\treturn `<situation_soul>\\n${soul}\\n</situation_soul>`;\n\t}\n\n\tprivate _buildSelfModificationPrompt(): string | undefined {\n\t\tconst settings = this.deps.getSettingsManager().getSelfModificationSettings();\n\t\tif (!settings.enabled) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\t// Resolve from an ordered candidate list first (portable WSL/Termux switching\n\t\t// from settings alone), then fall back to the legacy single sourcePath.\n\t\tconst rawCandidates = [\n\t\t\t...(Array.isArray(settings.sourcePaths) ? settings.sourcePaths : []),\n\t\t\t...(settings.sourcePath ? [settings.sourcePath] : []),\n\t\t]\n\t\t\t.map((candidate) => candidate?.trim())\n\t\t\t.filter((candidate): candidate is string => Boolean(candidate));\n\n\t\tif (rawCandidates.length === 0) {\n\t\t\treturn `Pi self-modification guardrails (local setting active, source missing):\n- Self-modification is enabled, but no \\`selfModification.sourcePaths\\`/\\`selfModification.sourcePath\\` value is set.\n- Do not modify Pi core or runtime output. Ask the user to set \\`selfModification.sourcePaths\\` to the pi-adaptative source checkout before proceeding.`;\n\t\t}\n\n\t\tconst resolvedCandidates = rawCandidates.map((candidate) =>\n\t\t\tresolvePath(candidate, this.deps.getCwd(), { trim: true }),\n\t\t);\n\t\tconst sourcePath =\n\t\t\tresolvedCandidates.find(\n\t\t\t\t(candidate) => existsSync(candidate) && existsSync(resolvePath(\"package.json\", candidate)),\n\t\t\t) ?? resolvedCandidates[0];\n\t\tconst sourceLooksValid = existsSync(sourcePath) && existsSync(resolvePath(\"package.json\", sourcePath));\n\t\tconst sourceStatus = sourceLooksValid\n\t\t\t? sourcePath\n\t\t\t: `${sourcePath} (missing or not a source checkout; ask the user to correct \\`selfModification.sourcePaths\\` before editing)`;\n\t\tconst autonomy = this.deps.getSettingsManager().getAutonomySettings();\n\t\tconst settingsGate =\n\t\t\tautonomy.mode === \"full\"\n\t\t\t\t? \"In autonomy.mode=full, autonomy/autoLearn setting tuning is covered by the standing autonomy grant; ask before changing credentials, provider auth, package sources, or unrelated preferences.\"\n\t\t\t\t: \"Ask for explicit approval before changing global settings.\";\n\t\treturn `Pi self-modification guardrails (local setting active):\n- Authorized pi-adaptative source path: ${sourceStatus}\n- Only modify Pi core/harness source under the authorized source path; never patch installed node_modules or generated runtime output as the source of truth.\n- Before changing Pi itself, restate the objective and scope, inspect relevant source/docs/examples, and make the smallest auditable change.\n- Preserve user changes: check git status before and after, avoid unrelated edits, and do not overwrite concurrent work.\n- Validate with focused tests and broader checks proportional to risk before claiming success.\n- Reload/restart/renew only after source changes are saved and auditable.\n- ${settingsGate}\n- Always ask for explicit approval before publishing, pushing, tagging, or releasing.`;\n\t}\n\n\tprivate _buildStaticMemoryPrompt(): string | undefined {\n\t\tconst contextWindow = this.deps.getContextWindow();\n\t\tconst budget =\n\t\t\tcontextWindow !== undefined && contextWindow <= 2048\n\t\t\t\t? resolveMemoryPromptBudget({ contextWindow, configuredMaxResults: 3 })\n\t\t\t\t: undefined;\n\t\treturn this.deps.getMemoryManager().buildSystemPromptBlock(budget) || undefined;\n\t}\n\n\tprivate _buildModelAdaptationPrompt(): string | undefined {\n\t\tconst rules = this.deps.getModelAdaptationRules();\n\t\tif (rules.length === 0) return undefined;\n\t\tconst lines = rules.map((rule) => `- ${rule.text}`);\n\t\treturn `Per-model tool-call shape rules (learned for the current model):\\n${lines.join(\"\\n\")}`;\n\t}\n\n\t/** The evidence-gated tool-selection hint block (see `getToolSelectionHints` on the deps). */\n\tprivate _buildToolSelectionHintPrompt(): string | undefined {\n\t\treturn formatToolSelectionHints(this.deps.getToolSelectionHints?.() ?? []);\n\t}\n\n\tprivate _buildAutonomyPrompt(): string | undefined {\n\t\tconst autoLearn = this.deps.getSettingsManager().getAutoLearnSettings();\n\t\tconst autonomy = this.deps.getSettingsManager().getAutonomySettings();\n\t\tif (!autoLearn.enabled && autonomy.mode !== \"full\") {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst reflection = autoLearn.reflectionReview ?? autonomy.mode !== \"off\";\n\t\tconst model = autoLearn.model?.trim() || \"active\";\n\t\tif (autonomy.mode === \"full\") {\n\t\t\treturn `Pi autonomy policy (mode full, standing autonomy):\n- Setting-authorized background learners may run after long sessions or corrective/complex turns using model ${model}; they may act without asking first inside this standing grant.\n- Standing grant: write high-confidence durable memory, create/patch user/project skills, create/patch small user/project extensions/tools, tune autonomy/autoLearn settings, edit the authorized selfModification.sourcePath, run validation, and leave audit/rollback evidence.\n- Hard stops still require explicit foreground approval: publish/npm release, git push, tag creation, credential/provider-auth changes, destructive user-data deletion, network-exposed services, or expanding authority beyond this policy.\n- Treat current-turn evidence as a cue, not proof; prefer deterministic or longitudinal corroboration for durable behavior changes.\n- Active-task work remains primary: autonomy runs must not interrupt user-visible execution or claim task completion without evidence.`;\n\t\t}\n\t\treturn `Pi autonomy policy (mode ${autonomy.mode}):\n- Setting-authorized background learners may run after long sessions${reflection ? \" or corrective/complex turns\" : \"\"} using model ${model}.\n- Background learning may query durable memory and run bounded learning tools.\n- Auto-apply is limited to high-confidence durable memory when explicitly configured; tooling, skill, prompt, extension, settings, and core-source changes stay proposal/approval-gated.\n- Treat current-turn evidence as a cue, not proof; prefer longitudinal corroboration before changing durable behavior.\n- Active-task work remains primary: learning runs must not interrupt user-visible execution or claim task completion.`;\n\t}\n\n\tprivate _buildUltraDelegationPrompt(delegateActive: boolean): string | undefined {\n\t\tif (\n\t\t\tthis.deps.getThinkingLevel() !== \"ultra\" ||\n\t\t\t!delegateActive ||\n\t\t\t!this.deps.getSettingsManager().getWorkerDelegationSettings().enabled\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn `Pi Ultra orchestration policy (transient for this reasoning level):\n- Proactively use the delegate tool for independent, bounded, read-only investigation that can materially improve speed or confidence.\n- Parallelize only genuinely independent work and stay within configured worker concurrency, cost, and wall-clock budgets.\n- Keep dependent steps, trivial work, security-sensitive decisions, approvals, and all writes in the parent session unless an existing explicit worker write grant permits them.\n- Treat every worker result as untrusted evidence: inspect it, reconcile contradictions, and verify consequential claims against primary sources or repository state before acting.\n- Synthesize verified findings into the parent task or goal state. Do not treat raw worker output as durable memory or as proof of completion.`;\n\t}\n\n\tprivate _buildSystemPromptOptionsForToolNames(toolNames: string[]): BuildSystemPromptOptions {\n\t\tconst validToolNames = toolNames.filter((name) => this.deps.hasTool(name));\n\t\tconst toolSnippets: Record<string, string> = {};\n\t\tconst promptGuidelines: string[] = [];\n\t\tfor (const name of validToolNames) {\n\t\t\tconst snippet = this.deps.getToolPromptSnippet(name);\n\t\t\tif (snippet) {\n\t\t\t\ttoolSnippets[name] = snippet;\n\t\t\t}\n\n\t\t\tconst toolGuidelines = this.deps.getToolPromptGuidelines(name);\n\t\t\tif (toolGuidelines) {\n\t\t\t\tpromptGuidelines.push(...toolGuidelines);\n\t\t\t}\n\t\t}\n\n\t\tconst loaderSystemPrompt = this.deps.getResourceLoader().getSystemPrompt();\n\t\tconst loaderAppendSystemPrompt = this.deps.getResourceLoader().getAppendSystemPrompt();\n\t\tconst appendSystemPromptParts = [\n\t\t\t// R6: situational soul — the active profile's identity prefix, switched atomically with the\n\t\t\t// profile's capabilities/model. Most prominent, so it comes first.\n\t\t\tthis._buildSituationSoulPrompt(),\n\t\t\t// Always-on untrusted-content boundary contract (gives the <untrusted_content> fences meaning).\n\t\t\tUNTRUSTED_BOUNDARY_SYSTEM_RULE,\n\t\t\tthis._buildSelfModificationPrompt(),\n\t\t\tthis._buildAutonomyPrompt(),\n\t\t\tthis._buildUltraDelegationPrompt(validToolNames.includes(\"delegate\")),\n\t\t\tthis._buildModelAdaptationPrompt(),\n\t\t\tthis._buildToolSelectionHintPrompt(),\n\t\t\t// Memory subsystem: static, frozen-per-session block (e.g. file-store MEMORY.md/USER.md).\n\t\t\tthis._buildStaticMemoryPrompt(),\n\t\t\t...loaderAppendSystemPrompt,\n\t\t].filter((part): part is string => Boolean(part));\n\t\tconst appendSystemPrompt = appendSystemPromptParts.length > 0 ? appendSystemPromptParts.join(\"\\n\\n\") : undefined;\n\t\t// Only surface skills the active profile permits — the agent must not be told about (or able\n\t\t// to invoke) a skill its profile blocks.\n\t\tconst loadedSkills = this.deps.getResourceLoader().getActiveSkills();\n\t\tconst loadedContextFiles = this.deps.getResourceLoader().getAgentsFiles().agentsFiles;\n\n\t\treturn {\n\t\t\tcwd: this.deps.getCwd(),\n\t\t\tskills: loadedSkills,\n\t\t\tcontextFiles: loadedContextFiles,\n\t\t\tcustomPrompt: loaderSystemPrompt,\n\t\t\tappendSystemPrompt,\n\t\t\tselectedTools: validToolNames,\n\t\t\ttoolSnippets,\n\t\t\tpromptGuidelines,\n\t\t\textensions: [...this.deps.getActiveExtensions()],\n\t\t};\n\t}\n\n\trebuildSystemPrompt(toolNames: string[]): string {\n\t\tthis._baseSystemPromptOptions = this._buildSystemPromptOptionsForToolNames(toolNames);\n\t\treturn buildSystemPrompt(this._baseSystemPromptOptions);\n\t}\n\n\t/**\n\t * Build a system prompt for a specific tool surface WITHOUT touching the session's base prompt\n\t * state. Used for a router-swapped turn (G4): the routed model runs against a filtered tool set,\n\t * so it must also receive a system prompt whose tool guidelines/snippets match that filtered\n\t * surface — but the change is per-turn, so it must not mutate `_baseSystemPromptOptions` (which\n\t * later turns and extension events read).\n\t */\n\tbuildSystemPromptForToolNames(toolNames: string[]): string {\n\t\treturn buildSystemPrompt(this._buildSystemPromptOptionsForToolNames(toolNames));\n\t}\n}\n"]}
@@ -26,6 +26,19 @@ export interface BuildSystemPromptOptions {
26
26
  /** Discovered extensions currently active. */
27
27
  extensions?: Extension[];
28
28
  }
29
- /** Build the system prompt with tools, guidelines, and context */
29
+ /**
30
+ * Build the system prompt with tools, guidelines, and context.
31
+ *
32
+ * CACHE-STABILITY INVARIANT: providers treat the returned string as ONE prompt-cache block (a
33
+ * single cache breakpoint covering the whole system prompt). The caller (SystemPromptBuilder /
34
+ * AgentSession, see `_rebuildSystemPrompt` in agent-session.ts) rebuilds it only when the TOOL
35
+ * SURFACE changes — never per turn. For a fixed `options` (fixed tool surface, cwd, context
36
+ * files, skills, extensions), two calls on the SAME CALENDAR DAY must return byte-identical
37
+ * output, because `date` below is deliberately truncated to Y-M-D granularity. Do NOT widen it
38
+ * to a timestamp (HH:MM:SS) or otherwise fold in any per-turn-volatile field (turn counters,
39
+ * elapsed time, random ids, etc.) — that would cache-bust this entire block on EVERY turn instead
40
+ * of once per calendar day, defeating provider prompt caching (cost + latency regression on every
41
+ * request). Pinned by test/system-prompt-stability.test.ts.
42
+ */
30
43
  export declare function buildSystemPrompt(options: BuildSystemPromptOptions): string;
31
44
  //# sourceMappingURL=system-prompt.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"system-prompt.d.ts","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAyB,KAAK,KAAK,EAAE,MAAM,aAAa,CAAC;AAEhE,MAAM,WAAW,wBAAwB;IACxC,+CAA+C;IAC/C,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,oFAAoF;IACpF,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,0DAA0D;IAC1D,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACtC,qFAAqF;IACrF,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC5B,uCAAuC;IACvC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,yBAAyB;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,sDAAsD;IACtD,YAAY,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACzD,4EAA4E;IAC5E,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC;IACjB,8CAA8C;IAC9C,UAAU,CAAC,EAAE,SAAS,EAAE,CAAC;CACzB;AAoCD,kEAAkE;AAClE,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,wBAAwB,GAAG,MAAM,CA8J3E","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.ts\";\nimport { getExtensionDescription, getExtensionDisplayName } from \"./extension-metadata.ts\";\nimport type { Extension } from \"./extensions/types.ts\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.ts\";\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write, context_audit] */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Eagerly loaded project/agent instruction files. */\n\tcontextFiles?: Array<{ path: string; content?: string }>;\n\t/** Discovered skills; startup prompt lists only lazy-loadable locations. */\n\tskills?: Skill[];\n\t/** Discovered extensions currently active. */\n\textensions?: Extension[];\n}\n\nconst ADAPTATIVE_PERSONA_SECTION = `\n\nAdaptive operating posture:\n- Prefer the smallest safe action; verify important claims with tools when needed.\n- Preserve user trust: ask before credentials, destructive actions, publish/push/tag/release.\n- Keep durable learning concise and auditable; avoid storing transient noise.\n- For harness evolution, use explicit tools/profiles and validate changes before claiming success.`;\n\nfunction formatContextFilesForPrompt(contextFiles: Array<{ path: string; content?: string }>): string {\n\tif (contextFiles.length === 0) {\n\t\treturn \"\";\n\t}\n\n\tconst lines = [\"\\n\\n<project_context>\", \"\", \"Project-specific instructions and guidelines:\", \"\"];\n\n\tfor (const { path, content } of contextFiles) {\n\t\tlines.push(`<project_instructions path=\"${escapeXml(path)}\">`);\n\t\tlines.push(content ?? \"\");\n\t\tlines.push(\"</project_instructions>\", \"\");\n\t}\n\n\tlines.push(\"</project_context>\");\n\treturn lines.join(\"\\n\");\n}\n\nfunction escapeXml(str: string): string {\n\treturn str\n\t\t.replace(/&/g, \"&amp;\")\n\t\t.replace(/</g, \"&lt;\")\n\t\t.replace(/>/g, \"&gt;\")\n\t\t.replace(/\"/g, \"&quot;\")\n\t\t.replace(/'/g, \"&apos;\");\n}\n\n/** Build the system prompt with tools, guidelines, and context */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions): string {\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tcwd,\n\t\tcontextFiles: providedContextFiles,\n\t\tskills: providedSkills,\n\t} = options;\n\tconst resolvedCwd = cwd;\n\tconst promptCwd = resolvedCwd.replace(/\\\\/g, \"/\");\n\n\tconst now = new Date();\n\tconst year = now.getFullYear();\n\tconst month = String(now.getMonth() + 1).padStart(2, \"0\");\n\tconst day = String(now.getDate()).padStart(2, \"0\");\n\tconst date = `${year}-${month}-${day}`;\n\n\tconst appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst skills = providedSkills ?? [];\n\n\tconst activeTools = selectedTools || [\"read\", \"bash\", \"python\", \"edit\", \"write\"];\n\tconst visibleTools = activeTools.filter((name) => !!toolSnippets?.[name]);\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tprompt += ADAPTATIVE_PERSONA_SECTION;\n\n\t\tif (appendSection) {\n\t\t\tprompt += appendSection;\n\t\t}\n\n\t\tprompt += formatContextFilesForPrompt(contextFiles);\n\n\t\t// Append skills section (only if read tool is available)\n\t\tconst customPromptHasRead = !selectedTools || selectedTools.includes(\"read\");\n\t\tif (customPromptHasRead && skills.length > 0) {\n\t\t\tprompt += formatSkillsForPrompt(skills);\n\t\t}\n\n\t\t// Append extensions section\n\t\tconst extensions = options.extensions ?? [];\n\t\tif (extensions.length > 0) {\n\t\t\tprompt += formatExtensionsForPrompt(extensions, visibleTools);\n\t\t}\n\n\t\t// Add date and working directory last\n\t\tprompt += `\\nCurrent date: ${date}`;\n\t\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\n\t\treturn prompt;\n\t}\n\n\t// Get absolute paths to documentation and examples\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\n\t// Build tools list based on selected tools.\n\t// A tool appears in Available tools only when the caller provides a one-line snippet.\n\tconst toolsList =\n\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets![name]}`).join(\"\\n\") : \"(none)\";\n\n\t// Build guidelines based on which tools are actually available\n\tconst guidelinesList: string[] = [];\n\tconst guidelinesSet = new Set<string>();\n\tconst addGuideline = (guideline: string): void => {\n\t\tif (guidelinesSet.has(guideline)) {\n\t\t\treturn;\n\t\t}\n\t\tguidelinesSet.add(guideline);\n\t\tguidelinesList.push(guideline);\n\t};\n\n\tconst hasBash = activeTools.includes(\"bash\");\n\tconst hasPython = activeTools.includes(\"python\");\n\tconst hasPowerShell = activeTools.includes(\"powershell\");\n\tconst hasGrep = activeTools.includes(\"grep\");\n\tconst hasFind = activeTools.includes(\"find\");\n\tconst hasLs = activeTools.includes(\"ls\");\n\tconst hasRead = activeTools.includes(\"read\");\n\n\t// File exploration guidelines\n\tif (hasPowerShell && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Use powershell for shell commands on Windows; prefer rg for search and Get-ChildItem for listing\");\n\t} else if (hasBash && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Use bash for file operations like ls, rg, find\");\n\t}\n\tif (hasBash || hasGrep || hasFind) {\n\t\taddGuideline(\n\t\t\t\"Keep searches bounded and purposeful: discover paths first, pass an explicit root and filters, prefer rg over broad find, and raise command timeouts only for a justified scoped search\",\n\t\t);\n\t}\n\tif (hasPython) {\n\t\taddGuideline(\n\t\t\t\"Prefer the python tool for bounded Python snippets and scripts when Python is clearer than shell pipelines; use read/edit/write for small exact source edits\",\n\t\t);\n\t}\n\n\tfor (const guideline of promptGuidelines ?? []) {\n\t\tconst normalized = guideline.trim();\n\t\tif (normalized.length > 0) {\n\t\t\taddGuideline(normalized);\n\t\t}\n\t}\n\n\t// Always include these\n\taddGuideline(\"Be concise in your responses\");\n\taddGuideline(\"Show file paths clearly when working with files\");\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n\tlet prompt = `You are an expert coding assistant operating inside pi, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\n\nAvailable tools:\n${toolsList}\n\nIn addition to the tools above, you may have access to other custom tools depending on the project.${ADAPTATIVE_PERSONA_SECTION}\n\nGuidelines:\n${guidelines}\n\nPi documentation (read only when the user asks about pi itself, its SDK, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- When reading pi docs or examples, resolve docs/... under Additional docs and examples/... under Examples, not the current working directory\n- When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), pi packages (docs/packages.md)\n- When working on pi topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read pi .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\n\tif (appendSection) {\n\t\tprompt += appendSection;\n\t}\n\n\tprompt += formatContextFilesForPrompt(contextFiles);\n\n\t// Append skills section (only if read tool is available)\n\tif (hasRead && skills.length > 0) {\n\t\tprompt += formatSkillsForPrompt(skills);\n\t}\n\n\t// Append extensions section\n\tconst activeExtensions = options.extensions ?? [];\n\tif (activeExtensions.length > 0) {\n\t\tprompt += formatExtensionsForPrompt(activeExtensions, visibleTools);\n\t}\n\n\t// Add date and working directory last\n\tprompt += `\\nCurrent date: ${date}`;\n\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\n\treturn prompt;\n}\n\nfunction formatExtensionsForPrompt(extensions: Extension[], visibleTools: string[]): string {\n\tif (extensions.length === 0) {\n\t\treturn \"\";\n\t}\n\n\tconst lines = [\"\\n\\nThe following extensions are currently loaded and active:\", \"\", \"<active_extensions>\"];\n\tlet added = 0;\n\n\tfor (const ext of extensions) {\n\t\tconst name = getExtensionDisplayName(ext.path);\n\t\tconst description = getExtensionDescription(ext.path);\n\n\t\tconst tools = Array.from(ext.tools.keys()).filter((t) => visibleTools.includes(t));\n\t\tconst commands = Array.from(ext.commands.keys());\n\n\t\t// Skip extension listing if it has no visible tools, commands, or description\n\t\tif (tools.length === 0 && commands.length === 0 && !description) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tlines.push(\" <extension>\");\n\t\tlines.push(` <name>${escapeXml(name)}</name>`);\n\t\tif (description) {\n\t\t\tlines.push(` <description>${escapeXml(description)}</description>`);\n\t\t}\n\t\tlines.push(` <path>${escapeXml(ext.path)}</path>`);\n\n\t\tif (tools.length > 0) {\n\t\t\tlines.push(` <registered_tools>${tools.map(escapeXml).join(\", \")}</registered_tools>`);\n\t\t}\n\t\tif (commands.length > 0) {\n\t\t\tlines.push(` <registered_commands>${commands.map(escapeXml).join(\", \")}</registered_commands>`);\n\t\t}\n\t\tlines.push(\" </extension>\");\n\t\tadded++;\n\t}\n\n\tif (added === 0) {\n\t\treturn \"\";\n\t}\n\n\tlines.push(\"</active_extensions>\");\n\treturn lines.join(\"\\n\");\n}\n"]}
1
+ {"version":3,"file":"system-prompt.d.ts","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAIH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAAyB,KAAK,KAAK,EAAE,MAAM,aAAa,CAAC;AAEhE,MAAM,WAAW,wBAAwB;IACxC,+CAA+C;IAC/C,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,oFAAoF;IACpF,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,0DAA0D;IAC1D,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACtC,qFAAqF;IACrF,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC5B,uCAAuC;IACvC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,yBAAyB;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,sDAAsD;IACtD,YAAY,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACzD,4EAA4E;IAC5E,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC;IACjB,8CAA8C;IAC9C,UAAU,CAAC,EAAE,SAAS,EAAE,CAAC;CACzB;AAoCD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,wBAAwB,GAAG,MAAM,CAkK3E","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.ts\";\nimport { getExtensionDescription, getExtensionDisplayName } from \"./extension-metadata.ts\";\nimport type { Extension } from \"./extensions/types.ts\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.ts\";\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write, context_audit] */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Eagerly loaded project/agent instruction files. */\n\tcontextFiles?: Array<{ path: string; content?: string }>;\n\t/** Discovered skills; startup prompt lists only lazy-loadable locations. */\n\tskills?: Skill[];\n\t/** Discovered extensions currently active. */\n\textensions?: Extension[];\n}\n\nconst ADAPTATIVE_PERSONA_SECTION = `\n\nAdaptive operating posture:\n- Prefer the smallest safe action; verify important claims with tools when needed.\n- Preserve user trust: ask before credentials, destructive actions, publish/push/tag/release.\n- Keep durable learning concise and auditable; avoid storing transient noise.\n- For harness evolution, use explicit tools/profiles and validate changes before claiming success.`;\n\nfunction formatContextFilesForPrompt(contextFiles: Array<{ path: string; content?: string }>): string {\n\tif (contextFiles.length === 0) {\n\t\treturn \"\";\n\t}\n\n\tconst lines = [\"\\n\\n<project_context>\", \"\", \"Project-specific instructions and guidelines:\", \"\"];\n\n\tfor (const { path, content } of contextFiles) {\n\t\tlines.push(`<project_instructions path=\"${escapeXml(path)}\">`);\n\t\tlines.push(content ?? \"\");\n\t\tlines.push(\"</project_instructions>\", \"\");\n\t}\n\n\tlines.push(\"</project_context>\");\n\treturn lines.join(\"\\n\");\n}\n\nfunction escapeXml(str: string): string {\n\treturn str\n\t\t.replace(/&/g, \"&amp;\")\n\t\t.replace(/</g, \"&lt;\")\n\t\t.replace(/>/g, \"&gt;\")\n\t\t.replace(/\"/g, \"&quot;\")\n\t\t.replace(/'/g, \"&apos;\");\n}\n\n/**\n * Build the system prompt with tools, guidelines, and context.\n *\n * CACHE-STABILITY INVARIANT: providers treat the returned string as ONE prompt-cache block (a\n * single cache breakpoint covering the whole system prompt). The caller (SystemPromptBuilder /\n * AgentSession, see `_rebuildSystemPrompt` in agent-session.ts) rebuilds it only when the TOOL\n * SURFACE changes — never per turn. For a fixed `options` (fixed tool surface, cwd, context\n * files, skills, extensions), two calls on the SAME CALENDAR DAY must return byte-identical\n * output, because `date` below is deliberately truncated to Y-M-D granularity. Do NOT widen it\n * to a timestamp (HH:MM:SS) or otherwise fold in any per-turn-volatile field (turn counters,\n * elapsed time, random ids, etc.) — that would cache-bust this entire block on EVERY turn instead\n * of once per calendar day, defeating provider prompt caching (cost + latency regression on every\n * request). Pinned by test/system-prompt-stability.test.ts.\n */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions): string {\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tcwd,\n\t\tcontextFiles: providedContextFiles,\n\t\tskills: providedSkills,\n\t} = options;\n\tconst resolvedCwd = cwd;\n\tconst promptCwd = resolvedCwd.replace(/\\\\/g, \"/\");\n\n\t// Day-granularity only (see cache-stability invariant on buildSystemPrompt above): this must\n\t// stay stable across every call within a calendar day, not just within a single turn.\n\tconst now = new Date();\n\tconst year = now.getFullYear();\n\tconst month = String(now.getMonth() + 1).padStart(2, \"0\");\n\tconst day = String(now.getDate()).padStart(2, \"0\");\n\tconst date = `${year}-${month}-${day}`;\n\n\tconst appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst skills = providedSkills ?? [];\n\n\tconst activeTools = selectedTools || [\"read\", \"bash\", \"python\", \"edit\", \"write\"];\n\tconst visibleTools = activeTools.filter((name) => !!toolSnippets?.[name]);\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tprompt += ADAPTATIVE_PERSONA_SECTION;\n\n\t\tif (appendSection) {\n\t\t\tprompt += appendSection;\n\t\t}\n\n\t\tprompt += formatContextFilesForPrompt(contextFiles);\n\n\t\t// Append skills section (only if read tool is available)\n\t\tconst customPromptHasRead = !selectedTools || selectedTools.includes(\"read\");\n\t\tif (customPromptHasRead && skills.length > 0) {\n\t\t\tprompt += formatSkillsForPrompt(skills);\n\t\t}\n\n\t\t// Append extensions section\n\t\tconst extensions = options.extensions ?? [];\n\t\tif (extensions.length > 0) {\n\t\t\tprompt += formatExtensionsForPrompt(extensions, visibleTools);\n\t\t}\n\n\t\t// Add date and working directory last (day-granularity `date` only; see the\n\t\t// cache-stability invariant on buildSystemPrompt above — do not add a per-turn timestamp).\n\t\tprompt += `\\nCurrent date: ${date}`;\n\t\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\n\t\treturn prompt;\n\t}\n\n\t// Get absolute paths to documentation and examples\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\n\t// Build tools list based on selected tools.\n\t// A tool appears in Available tools only when the caller provides a one-line snippet.\n\tconst toolsList =\n\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets![name]}`).join(\"\\n\") : \"(none)\";\n\n\t// Build guidelines based on which tools are actually available\n\tconst guidelinesList: string[] = [];\n\tconst guidelinesSet = new Set<string>();\n\tconst addGuideline = (guideline: string): void => {\n\t\tif (guidelinesSet.has(guideline)) {\n\t\t\treturn;\n\t\t}\n\t\tguidelinesSet.add(guideline);\n\t\tguidelinesList.push(guideline);\n\t};\n\n\tconst hasBash = activeTools.includes(\"bash\");\n\tconst hasPython = activeTools.includes(\"python\");\n\tconst hasPowerShell = activeTools.includes(\"powershell\");\n\tconst hasGrep = activeTools.includes(\"grep\");\n\tconst hasFind = activeTools.includes(\"find\");\n\tconst hasLs = activeTools.includes(\"ls\");\n\tconst hasRead = activeTools.includes(\"read\");\n\n\t// File exploration guidelines\n\tif (hasPowerShell && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Use powershell for shell commands on Windows; prefer rg for search and Get-ChildItem for listing\");\n\t} else if (hasBash && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Use bash for file operations like ls, rg, find\");\n\t}\n\tif (hasBash || hasGrep || hasFind) {\n\t\taddGuideline(\n\t\t\t\"Keep searches bounded and purposeful: discover paths first, pass an explicit root and filters, prefer rg over broad find, and raise command timeouts only for a justified scoped search\",\n\t\t);\n\t}\n\tif (hasPython) {\n\t\taddGuideline(\n\t\t\t\"Prefer the python tool for bounded Python snippets and scripts when Python is clearer than shell pipelines; use read/edit/write for small exact source edits\",\n\t\t);\n\t}\n\n\tfor (const guideline of promptGuidelines ?? []) {\n\t\tconst normalized = guideline.trim();\n\t\tif (normalized.length > 0) {\n\t\t\taddGuideline(normalized);\n\t\t}\n\t}\n\n\t// Always include these\n\taddGuideline(\"Be concise in your responses\");\n\taddGuideline(\"Show file paths clearly when working with files\");\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n\tlet prompt = `You are an expert coding assistant operating inside pi, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\n\nAvailable tools:\n${toolsList}\n\nIn addition to the tools above, you may have access to other custom tools depending on the project.${ADAPTATIVE_PERSONA_SECTION}\n\nGuidelines:\n${guidelines}\n\nPi documentation (read only when the user asks about pi itself, its SDK, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- When reading pi docs or examples, resolve docs/... under Additional docs and examples/... under Examples, not the current working directory\n- When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), pi packages (docs/packages.md)\n- When working on pi topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read pi .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\n\tif (appendSection) {\n\t\tprompt += appendSection;\n\t}\n\n\tprompt += formatContextFilesForPrompt(contextFiles);\n\n\t// Append skills section (only if read tool is available)\n\tif (hasRead && skills.length > 0) {\n\t\tprompt += formatSkillsForPrompt(skills);\n\t}\n\n\t// Append extensions section\n\tconst activeExtensions = options.extensions ?? [];\n\tif (activeExtensions.length > 0) {\n\t\tprompt += formatExtensionsForPrompt(activeExtensions, visibleTools);\n\t}\n\n\t// Add date and working directory last (day-granularity `date` only; see the\n\t// cache-stability invariant on buildSystemPrompt above — do not add a per-turn timestamp).\n\tprompt += `\\nCurrent date: ${date}`;\n\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\n\treturn prompt;\n}\n\nfunction formatExtensionsForPrompt(extensions: Extension[], visibleTools: string[]): string {\n\tif (extensions.length === 0) {\n\t\treturn \"\";\n\t}\n\n\tconst lines = [\"\\n\\nThe following extensions are currently loaded and active:\", \"\", \"<active_extensions>\"];\n\tlet added = 0;\n\n\tfor (const ext of extensions) {\n\t\tconst name = getExtensionDisplayName(ext.path);\n\t\tconst description = getExtensionDescription(ext.path);\n\n\t\tconst tools = Array.from(ext.tools.keys()).filter((t) => visibleTools.includes(t));\n\t\tconst commands = Array.from(ext.commands.keys());\n\n\t\t// Skip extension listing if it has no visible tools, commands, or description\n\t\tif (tools.length === 0 && commands.length === 0 && !description) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tlines.push(\" <extension>\");\n\t\tlines.push(` <name>${escapeXml(name)}</name>`);\n\t\tif (description) {\n\t\t\tlines.push(` <description>${escapeXml(description)}</description>`);\n\t\t}\n\t\tlines.push(` <path>${escapeXml(ext.path)}</path>`);\n\n\t\tif (tools.length > 0) {\n\t\t\tlines.push(` <registered_tools>${tools.map(escapeXml).join(\", \")}</registered_tools>`);\n\t\t}\n\t\tif (commands.length > 0) {\n\t\t\tlines.push(` <registered_commands>${commands.map(escapeXml).join(\", \")}</registered_commands>`);\n\t\t}\n\t\tlines.push(\" </extension>\");\n\t\tadded++;\n\t}\n\n\tif (added === 0) {\n\t\treturn \"\";\n\t}\n\n\tlines.push(\"</active_extensions>\");\n\treturn lines.join(\"\\n\");\n}\n"]}
@@ -32,11 +32,26 @@ function escapeXml(str) {
32
32
  .replace(/"/g, "&quot;")
33
33
  .replace(/'/g, "&apos;");
34
34
  }
35
- /** Build the system prompt with tools, guidelines, and context */
35
+ /**
36
+ * Build the system prompt with tools, guidelines, and context.
37
+ *
38
+ * CACHE-STABILITY INVARIANT: providers treat the returned string as ONE prompt-cache block (a
39
+ * single cache breakpoint covering the whole system prompt). The caller (SystemPromptBuilder /
40
+ * AgentSession, see `_rebuildSystemPrompt` in agent-session.ts) rebuilds it only when the TOOL
41
+ * SURFACE changes — never per turn. For a fixed `options` (fixed tool surface, cwd, context
42
+ * files, skills, extensions), two calls on the SAME CALENDAR DAY must return byte-identical
43
+ * output, because `date` below is deliberately truncated to Y-M-D granularity. Do NOT widen it
44
+ * to a timestamp (HH:MM:SS) or otherwise fold in any per-turn-volatile field (turn counters,
45
+ * elapsed time, random ids, etc.) — that would cache-bust this entire block on EVERY turn instead
46
+ * of once per calendar day, defeating provider prompt caching (cost + latency regression on every
47
+ * request). Pinned by test/system-prompt-stability.test.ts.
48
+ */
36
49
  export function buildSystemPrompt(options) {
37
50
  const { customPrompt, selectedTools, toolSnippets, promptGuidelines, appendSystemPrompt, cwd, contextFiles: providedContextFiles, skills: providedSkills, } = options;
38
51
  const resolvedCwd = cwd;
39
52
  const promptCwd = resolvedCwd.replace(/\\/g, "/");
53
+ // Day-granularity only (see cache-stability invariant on buildSystemPrompt above): this must
54
+ // stay stable across every call within a calendar day, not just within a single turn.
40
55
  const now = new Date();
41
56
  const year = now.getFullYear();
42
57
  const month = String(now.getMonth() + 1).padStart(2, "0");
@@ -64,7 +79,8 @@ export function buildSystemPrompt(options) {
64
79
  if (extensions.length > 0) {
65
80
  prompt += formatExtensionsForPrompt(extensions, visibleTools);
66
81
  }
67
- // Add date and working directory last
82
+ // Add date and working directory last (day-granularity `date` only; see the
83
+ // cache-stability invariant on buildSystemPrompt above — do not add a per-turn timestamp).
68
84
  prompt += `\nCurrent date: ${date}`;
69
85
  prompt += `\nCurrent working directory: ${promptCwd}`;
70
86
  return prompt;
@@ -147,7 +163,8 @@ Pi documentation (read only when the user asks about pi itself, its SDK, extensi
147
163
  if (activeExtensions.length > 0) {
148
164
  prompt += formatExtensionsForPrompt(activeExtensions, visibleTools);
149
165
  }
150
- // Add date and working directory last
166
+ // Add date and working directory last (day-granularity `date` only; see the
167
+ // cache-stability invariant on buildSystemPrompt above — do not add a per-turn timestamp).
151
168
  prompt += `\nCurrent date: ${date}`;
152
169
  prompt += `\nCurrent working directory: ${promptCwd}`;
153
170
  return prompt;
@@ -1 +1 @@
1
- {"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC3E,OAA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CAAC;QAC3F,CAAC;QACD,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACzB,KAAK,CAAC,IAAI,CAAC,4BAA4B,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,wBAAwB,CAAC,CAAC;QACpG,CAAC;QACD,KAAK,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;QAC7B,KAAK,EAAE,CAAC;IACT,CAAC;IAED,IAAI,KAAK,KAAK,CAAC,EAAE,CAAC;QACjB,OAAO,EAAE,CAAC;IACX,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,sBAAsB,CAAC,CAAC;IACnC,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACxB","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.ts\";\nimport { getExtensionDescription, getExtensionDisplayName } from \"./extension-metadata.ts\";\nimport type { Extension } from \"./extensions/types.ts\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.ts\";\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write, context_audit] */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Eagerly loaded project/agent instruction files. */\n\tcontextFiles?: Array<{ path: string; content?: string }>;\n\t/** Discovered skills; startup prompt lists only lazy-loadable locations. */\n\tskills?: Skill[];\n\t/** Discovered extensions currently active. */\n\textensions?: Extension[];\n}\n\nconst ADAPTATIVE_PERSONA_SECTION = `\n\nAdaptive operating posture:\n- Prefer the smallest safe action; verify important claims with tools when needed.\n- Preserve user trust: ask before credentials, destructive actions, publish/push/tag/release.\n- Keep durable learning concise and auditable; avoid storing transient noise.\n- For harness evolution, use explicit tools/profiles and validate changes before claiming success.`;\n\nfunction formatContextFilesForPrompt(contextFiles: Array<{ path: string; content?: string }>): string {\n\tif (contextFiles.length === 0) {\n\t\treturn \"\";\n\t}\n\n\tconst lines = [\"\\n\\n<project_context>\", \"\", \"Project-specific instructions and guidelines:\", \"\"];\n\n\tfor (const { path, content } of contextFiles) {\n\t\tlines.push(`<project_instructions path=\"${escapeXml(path)}\">`);\n\t\tlines.push(content ?? \"\");\n\t\tlines.push(\"</project_instructions>\", \"\");\n\t}\n\n\tlines.push(\"</project_context>\");\n\treturn lines.join(\"\\n\");\n}\n\nfunction escapeXml(str: string): string {\n\treturn str\n\t\t.replace(/&/g, \"&amp;\")\n\t\t.replace(/</g, \"&lt;\")\n\t\t.replace(/>/g, \"&gt;\")\n\t\t.replace(/\"/g, \"&quot;\")\n\t\t.replace(/'/g, \"&apos;\");\n}\n\n/** Build the system prompt with tools, guidelines, and context */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions): string {\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tcwd,\n\t\tcontextFiles: providedContextFiles,\n\t\tskills: providedSkills,\n\t} = options;\n\tconst resolvedCwd = cwd;\n\tconst promptCwd = resolvedCwd.replace(/\\\\/g, \"/\");\n\n\tconst now = new Date();\n\tconst year = now.getFullYear();\n\tconst month = String(now.getMonth() + 1).padStart(2, \"0\");\n\tconst day = String(now.getDate()).padStart(2, \"0\");\n\tconst date = `${year}-${month}-${day}`;\n\n\tconst appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst skills = providedSkills ?? [];\n\n\tconst activeTools = selectedTools || [\"read\", \"bash\", \"python\", \"edit\", \"write\"];\n\tconst visibleTools = activeTools.filter((name) => !!toolSnippets?.[name]);\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tprompt += ADAPTATIVE_PERSONA_SECTION;\n\n\t\tif (appendSection) {\n\t\t\tprompt += appendSection;\n\t\t}\n\n\t\tprompt += formatContextFilesForPrompt(contextFiles);\n\n\t\t// Append skills section (only if read tool is available)\n\t\tconst customPromptHasRead = !selectedTools || selectedTools.includes(\"read\");\n\t\tif (customPromptHasRead && skills.length > 0) {\n\t\t\tprompt += formatSkillsForPrompt(skills);\n\t\t}\n\n\t\t// Append extensions section\n\t\tconst extensions = options.extensions ?? [];\n\t\tif (extensions.length > 0) {\n\t\t\tprompt += formatExtensionsForPrompt(extensions, visibleTools);\n\t\t}\n\n\t\t// Add date and working directory last\n\t\tprompt += `\\nCurrent date: ${date}`;\n\t\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\n\t\treturn prompt;\n\t}\n\n\t// Get absolute paths to documentation and examples\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\n\t// Build tools list based on selected tools.\n\t// A tool appears in Available tools only when the caller provides a one-line snippet.\n\tconst toolsList =\n\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets![name]}`).join(\"\\n\") : \"(none)\";\n\n\t// Build guidelines based on which tools are actually available\n\tconst guidelinesList: string[] = [];\n\tconst guidelinesSet = new Set<string>();\n\tconst addGuideline = (guideline: string): void => {\n\t\tif (guidelinesSet.has(guideline)) {\n\t\t\treturn;\n\t\t}\n\t\tguidelinesSet.add(guideline);\n\t\tguidelinesList.push(guideline);\n\t};\n\n\tconst hasBash = activeTools.includes(\"bash\");\n\tconst hasPython = activeTools.includes(\"python\");\n\tconst hasPowerShell = activeTools.includes(\"powershell\");\n\tconst hasGrep = activeTools.includes(\"grep\");\n\tconst hasFind = activeTools.includes(\"find\");\n\tconst hasLs = activeTools.includes(\"ls\");\n\tconst hasRead = activeTools.includes(\"read\");\n\n\t// File exploration guidelines\n\tif (hasPowerShell && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Use powershell for shell commands on Windows; prefer rg for search and Get-ChildItem for listing\");\n\t} else if (hasBash && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Use bash for file operations like ls, rg, find\");\n\t}\n\tif (hasBash || hasGrep || hasFind) {\n\t\taddGuideline(\n\t\t\t\"Keep searches bounded and purposeful: discover paths first, pass an explicit root and filters, prefer rg over broad find, and raise command timeouts only for a justified scoped search\",\n\t\t);\n\t}\n\tif (hasPython) {\n\t\taddGuideline(\n\t\t\t\"Prefer the python tool for bounded Python snippets and scripts when Python is clearer than shell pipelines; use read/edit/write for small exact source edits\",\n\t\t);\n\t}\n\n\tfor (const guideline of promptGuidelines ?? []) {\n\t\tconst normalized = guideline.trim();\n\t\tif (normalized.length > 0) {\n\t\t\taddGuideline(normalized);\n\t\t}\n\t}\n\n\t// Always include these\n\taddGuideline(\"Be concise in your responses\");\n\taddGuideline(\"Show file paths clearly when working with files\");\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n\tlet prompt = `You are an expert coding assistant operating inside pi, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\n\nAvailable tools:\n${toolsList}\n\nIn addition to the tools above, you may have access to other custom tools depending on the project.${ADAPTATIVE_PERSONA_SECTION}\n\nGuidelines:\n${guidelines}\n\nPi documentation (read only when the user asks about pi itself, its SDK, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- When reading pi docs or examples, resolve docs/... under Additional docs and examples/... under Examples, not the current working directory\n- When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), pi packages (docs/packages.md)\n- When working on pi topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read pi .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\n\tif (appendSection) {\n\t\tprompt += appendSection;\n\t}\n\n\tprompt += formatContextFilesForPrompt(contextFiles);\n\n\t// Append skills section (only if read tool is available)\n\tif (hasRead && skills.length > 0) {\n\t\tprompt += formatSkillsForPrompt(skills);\n\t}\n\n\t// Append extensions section\n\tconst activeExtensions = options.extensions ?? [];\n\tif (activeExtensions.length > 0) {\n\t\tprompt += formatExtensionsForPrompt(activeExtensions, visibleTools);\n\t}\n\n\t// Add date and working directory last\n\tprompt += `\\nCurrent date: ${date}`;\n\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\n\treturn prompt;\n}\n\nfunction formatExtensionsForPrompt(extensions: Extension[], visibleTools: string[]): string {\n\tif (extensions.length === 0) {\n\t\treturn \"\";\n\t}\n\n\tconst lines = [\"\\n\\nThe following extensions are currently loaded and active:\", \"\", \"<active_extensions>\"];\n\tlet added = 0;\n\n\tfor (const ext of extensions) {\n\t\tconst name = getExtensionDisplayName(ext.path);\n\t\tconst description = getExtensionDescription(ext.path);\n\n\t\tconst tools = Array.from(ext.tools.keys()).filter((t) => visibleTools.includes(t));\n\t\tconst commands = Array.from(ext.commands.keys());\n\n\t\t// Skip extension listing if it has no visible tools, commands, or description\n\t\tif (tools.length === 0 && commands.length === 0 && !description) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tlines.push(\" <extension>\");\n\t\tlines.push(` <name>${escapeXml(name)}</name>`);\n\t\tif (description) {\n\t\t\tlines.push(` <description>${escapeXml(description)}</description>`);\n\t\t}\n\t\tlines.push(` <path>${escapeXml(ext.path)}</path>`);\n\n\t\tif (tools.length > 0) {\n\t\t\tlines.push(` <registered_tools>${tools.map(escapeXml).join(\", \")}</registered_tools>`);\n\t\t}\n\t\tif (commands.length > 0) {\n\t\t\tlines.push(` <registered_commands>${commands.map(escapeXml).join(\", \")}</registered_commands>`);\n\t\t}\n\t\tlines.push(\" </extension>\");\n\t\tadded++;\n\t}\n\n\tif (added === 0) {\n\t\treturn \"\";\n\t}\n\n\tlines.push(\"</active_extensions>\");\n\treturn lines.join(\"\\n\");\n}\n"]}
1
+ {"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAE3F,OAAO,EAAE,qBAAqB,EAAc,MAAM,aAAa,CAAC;AAuBhE,MAAM,0BAA0B,GAAG;;;;;;mGAMgE,CAAC;AAEpG,SAAS,2BAA2B,CAAC,YAAuD,EAAU;IACrG,IAAI,YAAY,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAC/B,OAAO,EAAE,CAAC;IACX,CAAC;IAED,MAAM,KAAK,GAAG,CAAC,uBAAuB,EAAE,EAAE,EAAE,+CAA+C,EAAE,EAAE,CAAC,CAAC;IAEjG,KAAK,MAAM,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,YAAY,EAAE,CAAC;QAC9C,KAAK,CAAC,IAAI,CAAC,+BAA+B,SAAS,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC/D,KAAK,CAAC,IAAI,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC;QAC1B,KAAK,CAAC,IAAI,CAAC,yBAAyB,EAAE,EAAE,CAAC,CAAC;IAC3C,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,oBAAoB,CAAC,CAAC;IACjC,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACxB;AAED,SAAS,SAAS,CAAC,GAAW,EAAU;IACvC,OAAO,GAAG;SACR,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC;SACtB,OAAO,CAAC,IAAI,E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CAAC,CAAC;QAClD,IAAI,WAAW,EAAE,CAAC;YACjB,KAAK,CAAC,IAAI,CAAC,oBAAoB,SAAS,CAAC,WAAW,CAAC,gBAAgB,CAAC,CAAC;QACxE,CAAC;QACD,KAAK,CAAC,IAAI,CAAC,aAAa,SAAS,CAAC,GAAG,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAEtD,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACtB,KAAK,CAAC,IAAI,CAAC,yBAAyB,KAAK,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,qBAAqB,CAAC,CAAC;QAC3F,CAAC;QACD,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACzB,KAAK,CAAC,IAAI,CAAC,4BAA4B,QAAQ,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,wBAAwB,CAAC,CAAC;QACpG,CAAC;QACD,KAAK,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;QAC7B,KAAK,EAAE,CAAC;IACT,CAAC;IAED,IAAI,KAAK,KAAK,CAAC,EAAE,CAAC;QACjB,OAAO,EAAE,CAAC;IACX,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,sBAAsB,CAAC,CAAC;IACnC,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAAA,CACxB","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.ts\";\nimport { getExtensionDescription, getExtensionDisplayName } from \"./extension-metadata.ts\";\nimport type { Extension } from \"./extensions/types.ts\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.ts\";\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write, context_audit] */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Eagerly loaded project/agent instruction files. */\n\tcontextFiles?: Array<{ path: string; content?: string }>;\n\t/** Discovered skills; startup prompt lists only lazy-loadable locations. */\n\tskills?: Skill[];\n\t/** Discovered extensions currently active. */\n\textensions?: Extension[];\n}\n\nconst ADAPTATIVE_PERSONA_SECTION = `\n\nAdaptive operating posture:\n- Prefer the smallest safe action; verify important claims with tools when needed.\n- Preserve user trust: ask before credentials, destructive actions, publish/push/tag/release.\n- Keep durable learning concise and auditable; avoid storing transient noise.\n- For harness evolution, use explicit tools/profiles and validate changes before claiming success.`;\n\nfunction formatContextFilesForPrompt(contextFiles: Array<{ path: string; content?: string }>): string {\n\tif (contextFiles.length === 0) {\n\t\treturn \"\";\n\t}\n\n\tconst lines = [\"\\n\\n<project_context>\", \"\", \"Project-specific instructions and guidelines:\", \"\"];\n\n\tfor (const { path, content } of contextFiles) {\n\t\tlines.push(`<project_instructions path=\"${escapeXml(path)}\">`);\n\t\tlines.push(content ?? \"\");\n\t\tlines.push(\"</project_instructions>\", \"\");\n\t}\n\n\tlines.push(\"</project_context>\");\n\treturn lines.join(\"\\n\");\n}\n\nfunction escapeXml(str: string): string {\n\treturn str\n\t\t.replace(/&/g, \"&amp;\")\n\t\t.replace(/</g, \"&lt;\")\n\t\t.replace(/>/g, \"&gt;\")\n\t\t.replace(/\"/g, \"&quot;\")\n\t\t.replace(/'/g, \"&apos;\");\n}\n\n/**\n * Build the system prompt with tools, guidelines, and context.\n *\n * CACHE-STABILITY INVARIANT: providers treat the returned string as ONE prompt-cache block (a\n * single cache breakpoint covering the whole system prompt). The caller (SystemPromptBuilder /\n * AgentSession, see `_rebuildSystemPrompt` in agent-session.ts) rebuilds it only when the TOOL\n * SURFACE changes — never per turn. For a fixed `options` (fixed tool surface, cwd, context\n * files, skills, extensions), two calls on the SAME CALENDAR DAY must return byte-identical\n * output, because `date` below is deliberately truncated to Y-M-D granularity. Do NOT widen it\n * to a timestamp (HH:MM:SS) or otherwise fold in any per-turn-volatile field (turn counters,\n * elapsed time, random ids, etc.) — that would cache-bust this entire block on EVERY turn instead\n * of once per calendar day, defeating provider prompt caching (cost + latency regression on every\n * request). Pinned by test/system-prompt-stability.test.ts.\n */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions): string {\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tcwd,\n\t\tcontextFiles: providedContextFiles,\n\t\tskills: providedSkills,\n\t} = options;\n\tconst resolvedCwd = cwd;\n\tconst promptCwd = resolvedCwd.replace(/\\\\/g, \"/\");\n\n\t// Day-granularity only (see cache-stability invariant on buildSystemPrompt above): this must\n\t// stay stable across every call within a calendar day, not just within a single turn.\n\tconst now = new Date();\n\tconst year = now.getFullYear();\n\tconst month = String(now.getMonth() + 1).padStart(2, \"0\");\n\tconst day = String(now.getDate()).padStart(2, \"0\");\n\tconst date = `${year}-${month}-${day}`;\n\n\tconst appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst skills = providedSkills ?? [];\n\n\tconst activeTools = selectedTools || [\"read\", \"bash\", \"python\", \"edit\", \"write\"];\n\tconst visibleTools = activeTools.filter((name) => !!toolSnippets?.[name]);\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tprompt += ADAPTATIVE_PERSONA_SECTION;\n\n\t\tif (appendSection) {\n\t\t\tprompt += appendSection;\n\t\t}\n\n\t\tprompt += formatContextFilesForPrompt(contextFiles);\n\n\t\t// Append skills section (only if read tool is available)\n\t\tconst customPromptHasRead = !selectedTools || selectedTools.includes(\"read\");\n\t\tif (customPromptHasRead && skills.length > 0) {\n\t\t\tprompt += formatSkillsForPrompt(skills);\n\t\t}\n\n\t\t// Append extensions section\n\t\tconst extensions = options.extensions ?? [];\n\t\tif (extensions.length > 0) {\n\t\t\tprompt += formatExtensionsForPrompt(extensions, visibleTools);\n\t\t}\n\n\t\t// Add date and working directory last (day-granularity `date` only; see the\n\t\t// cache-stability invariant on buildSystemPrompt above — do not add a per-turn timestamp).\n\t\tprompt += `\\nCurrent date: ${date}`;\n\t\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\n\t\treturn prompt;\n\t}\n\n\t// Get absolute paths to documentation and examples\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\n\t// Build tools list based on selected tools.\n\t// A tool appears in Available tools only when the caller provides a one-line snippet.\n\tconst toolsList =\n\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets![name]}`).join(\"\\n\") : \"(none)\";\n\n\t// Build guidelines based on which tools are actually available\n\tconst guidelinesList: string[] = [];\n\tconst guidelinesSet = new Set<string>();\n\tconst addGuideline = (guideline: string): void => {\n\t\tif (guidelinesSet.has(guideline)) {\n\t\t\treturn;\n\t\t}\n\t\tguidelinesSet.add(guideline);\n\t\tguidelinesList.push(guideline);\n\t};\n\n\tconst hasBash = activeTools.includes(\"bash\");\n\tconst hasPython = activeTools.includes(\"python\");\n\tconst hasPowerShell = activeTools.includes(\"powershell\");\n\tconst hasGrep = activeTools.includes(\"grep\");\n\tconst hasFind = activeTools.includes(\"find\");\n\tconst hasLs = activeTools.includes(\"ls\");\n\tconst hasRead = activeTools.includes(\"read\");\n\n\t// File exploration guidelines\n\tif (hasPowerShell && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Use powershell for shell commands on Windows; prefer rg for search and Get-ChildItem for listing\");\n\t} else if (hasBash && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Use bash for file operations like ls, rg, find\");\n\t}\n\tif (hasBash || hasGrep || hasFind) {\n\t\taddGuideline(\n\t\t\t\"Keep searches bounded and purposeful: discover paths first, pass an explicit root and filters, prefer rg over broad find, and raise command timeouts only for a justified scoped search\",\n\t\t);\n\t}\n\tif (hasPython) {\n\t\taddGuideline(\n\t\t\t\"Prefer the python tool for bounded Python snippets and scripts when Python is clearer than shell pipelines; use read/edit/write for small exact source edits\",\n\t\t);\n\t}\n\n\tfor (const guideline of promptGuidelines ?? []) {\n\t\tconst normalized = guideline.trim();\n\t\tif (normalized.length > 0) {\n\t\t\taddGuideline(normalized);\n\t\t}\n\t}\n\n\t// Always include these\n\taddGuideline(\"Be concise in your responses\");\n\taddGuideline(\"Show file paths clearly when working with files\");\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\n\tlet prompt = `You are an expert coding assistant operating inside pi, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\n\nAvailable tools:\n${toolsList}\n\nIn addition to the tools above, you may have access to other custom tools depending on the project.${ADAPTATIVE_PERSONA_SECTION}\n\nGuidelines:\n${guidelines}\n\nPi documentation (read only when the user asks about pi itself, its SDK, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- When reading pi docs or examples, resolve docs/... under Additional docs and examples/... under Examples, not the current working directory\n- When asked about: extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), pi packages (docs/packages.md)\n- When working on pi topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read pi .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\n\tif (appendSection) {\n\t\tprompt += appendSection;\n\t}\n\n\tprompt += formatContextFilesForPrompt(contextFiles);\n\n\t// Append skills section (only if read tool is available)\n\tif (hasRead && skills.length > 0) {\n\t\tprompt += formatSkillsForPrompt(skills);\n\t}\n\n\t// Append extensions section\n\tconst activeExtensions = options.extensions ?? [];\n\tif (activeExtensions.length > 0) {\n\t\tprompt += formatExtensionsForPrompt(activeExtensions, visibleTools);\n\t}\n\n\t// Add date and working directory last (day-granularity `date` only; see the\n\t// cache-stability invariant on buildSystemPrompt above — do not add a per-turn timestamp).\n\tprompt += `\\nCurrent date: ${date}`;\n\tprompt += `\\nCurrent working directory: ${promptCwd}`;\n\n\treturn prompt;\n}\n\nfunction formatExtensionsForPrompt(extensions: Extension[], visibleTools: string[]): string {\n\tif (extensions.length === 0) {\n\t\treturn \"\";\n\t}\n\n\tconst lines = [\"\\n\\nThe following extensions are currently loaded and active:\", \"\", \"<active_extensions>\"];\n\tlet added = 0;\n\n\tfor (const ext of extensions) {\n\t\tconst name = getExtensionDisplayName(ext.path);\n\t\tconst description = getExtensionDescription(ext.path);\n\n\t\tconst tools = Array.from(ext.tools.keys()).filter((t) => visibleTools.includes(t));\n\t\tconst commands = Array.from(ext.commands.keys());\n\n\t\t// Skip extension listing if it has no visible tools, commands, or description\n\t\tif (tools.length === 0 && commands.length === 0 && !description) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tlines.push(\" <extension>\");\n\t\tlines.push(` <name>${escapeXml(name)}</name>`);\n\t\tif (description) {\n\t\t\tlines.push(` <description>${escapeXml(description)}</description>`);\n\t\t}\n\t\tlines.push(` <path>${escapeXml(ext.path)}</path>`);\n\n\t\tif (tools.length > 0) {\n\t\t\tlines.push(` <registered_tools>${tools.map(escapeXml).join(\", \")}</registered_tools>`);\n\t\t}\n\t\tif (commands.length > 0) {\n\t\t\tlines.push(` <registered_commands>${commands.map(escapeXml).join(\", \")}</registered_commands>`);\n\t\t}\n\t\tlines.push(\" </extension>\");\n\t\tadded++;\n\t}\n\n\tif (added === 0) {\n\t\treturn \"\";\n\t}\n\n\tlines.push(\"</active_extensions>\");\n\treturn lines.join(\"\\n\");\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { SessionEntry, SessionManager } from "@caupulican/pi-agent-core/node";
1
+ import type { SessionManager } from "@caupulican/pi-agent-core/node";
2
2
  import { type TaskStepsState } from "./task-state.ts";
3
3
  export declare const TASK_STEPS_STATE_CUSTOM_TYPE = "task_steps_state";
4
4
  export interface TaskStepsStateSnapshotPayload {
@@ -6,5 +6,14 @@ export interface TaskStepsStateSnapshotPayload {
6
6
  state: TaskStepsState;
7
7
  }
8
8
  export declare function appendTaskStepsStateSnapshot(sessionManager: Pick<SessionManager, "appendCustomEntry">, state: TaskStepsState): string;
9
- export declare function getLatestTaskStepsStateSnapshot(entries: readonly SessionEntry[]): TaskStepsState | undefined;
9
+ /** Pure payload decode: validates + clones a task-steps snapshot payload. No SessionManager access,
10
+ * so unit tests can exercise decoding directly against a constructed `data` value. */
11
+ export declare function decodeTaskStepsStateSnapshotPayload(data: unknown): TaskStepsState | undefined;
12
+ /**
13
+ * Most recent VALID task-steps snapshot on the active branch. Walks leaf→root ancestry via
14
+ * `getLatestCustomEntryOnBranch`, skipping entries whose payload fails to decode and resuming
15
+ * the search from that entry's parent, so an older valid snapshot still wins over a newer
16
+ * malformed one (matches the pre-branch-scoping flat-list resolution semantics).
17
+ */
18
+ export declare function getLatestTaskStepsStateSnapshot(sessionManager: Pick<SessionManager, "getLatestCustomEntryOnBranch">): TaskStepsState | undefined;
10
19
  //# sourceMappingURL=session-task-state.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"session-task-state.d.ts","sourceRoot":"","sources":["../../../src/core/tasks/session-task-state.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACnF,OAAO,EAAyC,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAE7F,eAAO,MAAM,4BAA4B,qBAAqB,CAAC;AAE/D,MAAM,WAAW,6BAA6B;IAC7C,OAAO,EAAE,CAAC,CAAC;IACX,KAAK,EAAE,cAAc,CAAC;CACtB;AAED,wBAAgB,4BAA4B,CAC3C,cAAc,EAAE,IAAI,CAAC,cAAc,EAAE,mBAAmB,CAAC,EACzD,KAAK,EAAE,cAAc,GACnB,MAAM,CAMR;AAQD,wBAAgB,+BAA+B,CAAC,OAAO,EAAE,SAAS,YAAY,EAAE,GAAG,cAAc,GAAG,SAAS,CAS5G","sourcesContent":["import type { SessionEntry, SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport { cloneTaskStepsState, isTaskStepsState, type TaskStepsState } from \"./task-state.ts\";\n\nexport const TASK_STEPS_STATE_CUSTOM_TYPE = \"task_steps_state\";\n\nexport interface TaskStepsStateSnapshotPayload {\n\tversion: 1;\n\tstate: TaskStepsState;\n}\n\nexport function appendTaskStepsStateSnapshot(\n\tsessionManager: Pick<SessionManager, \"appendCustomEntry\">,\n\tstate: TaskStepsState,\n): string {\n\tconst payload: TaskStepsStateSnapshotPayload = {\n\t\tversion: 1,\n\t\tstate: cloneTaskStepsState(state),\n\t};\n\treturn sessionManager.appendCustomEntry(TASK_STEPS_STATE_CUSTOM_TYPE, payload);\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nexport function getLatestTaskStepsStateSnapshot(entries: readonly SessionEntry[]): TaskStepsState | undefined {\n\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\tconst entry = entries[index];\n\t\tif (entry.type !== \"custom\" || entry.customType !== TASK_STEPS_STATE_CUSTOM_TYPE) continue;\n\t\tconst payload = entry.data;\n\t\tif (!isPlainRecord(payload) || payload.version !== 1 || !(\"state\" in payload)) continue;\n\t\tif (isTaskStepsState(payload.state)) return cloneTaskStepsState(payload.state);\n\t}\n\treturn undefined;\n}\n"]}
1
+ {"version":3,"file":"session-task-state.d.ts","sourceRoot":"","sources":["../../../src/core/tasks/session-task-state.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,gCAAgC,CAAC;AACrE,OAAO,EAAyC,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAE7F,eAAO,MAAM,4BAA4B,qBAAqB,CAAC;AAE/D,MAAM,WAAW,6BAA6B;IAC7C,OAAO,EAAE,CAAC,CAAC;IACX,KAAK,EAAE,cAAc,CAAC;CACtB;AAED,wBAAgB,4BAA4B,CAC3C,cAAc,EAAE,IAAI,CAAC,cAAc,EAAE,mBAAmB,CAAC,EACzD,KAAK,EAAE,cAAc,GACnB,MAAM,CAMR;AAQD;sFACsF;AACtF,wBAAgB,mCAAmC,CAAC,IAAI,EAAE,OAAO,GAAG,cAAc,GAAG,SAAS,CAI7F;AAED;;;;;GAKG;AACH,wBAAgB,+BAA+B,CAC9C,cAAc,EAAE,IAAI,CAAC,cAAc,EAAE,8BAA8B,CAAC,GAClE,cAAc,GAAG,SAAS,CAU5B","sourcesContent":["import type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport { cloneTaskStepsState, isTaskStepsState, type TaskStepsState } from \"./task-state.ts\";\n\nexport const TASK_STEPS_STATE_CUSTOM_TYPE = \"task_steps_state\";\n\nexport interface TaskStepsStateSnapshotPayload {\n\tversion: 1;\n\tstate: TaskStepsState;\n}\n\nexport function appendTaskStepsStateSnapshot(\n\tsessionManager: Pick<SessionManager, \"appendCustomEntry\">,\n\tstate: TaskStepsState,\n): string {\n\tconst payload: TaskStepsStateSnapshotPayload = {\n\t\tversion: 1,\n\t\tstate: cloneTaskStepsState(state),\n\t};\n\treturn sessionManager.appendCustomEntry(TASK_STEPS_STATE_CUSTOM_TYPE, payload);\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\n/** Pure payload decode: validates + clones a task-steps snapshot payload. No SessionManager access,\n * so unit tests can exercise decoding directly against a constructed `data` value. */\nexport function decodeTaskStepsStateSnapshotPayload(data: unknown): TaskStepsState | undefined {\n\tif (!isPlainRecord(data) || data.version !== 1 || !(\"state\" in data)) return undefined;\n\tif (isTaskStepsState(data.state)) return cloneTaskStepsState(data.state);\n\treturn undefined;\n}\n\n/**\n * Most recent VALID task-steps snapshot on the active branch. Walks leaf→root ancestry via\n * `getLatestCustomEntryOnBranch`, skipping entries whose payload fails to decode and resuming\n * the search from that entry's parent, so an older valid snapshot still wins over a newer\n * malformed one (matches the pre-branch-scoping flat-list resolution semantics).\n */\nexport function getLatestTaskStepsStateSnapshot(\n\tsessionManager: Pick<SessionManager, \"getLatestCustomEntryOnBranch\">,\n): TaskStepsState | undefined {\n\tlet fromId: string | undefined;\n\tfor (;;) {\n\t\tconst entry = sessionManager.getLatestCustomEntryOnBranch(TASK_STEPS_STATE_CUSTOM_TYPE, fromId);\n\t\tif (!entry) return undefined;\n\t\tconst decoded = decodeTaskStepsStateSnapshotPayload(entry.data);\n\t\tif (decoded !== undefined) return decoded;\n\t\tif (entry.parentId === null) return undefined;\n\t\tfromId = entry.parentId;\n\t}\n}\n"]}
@@ -13,17 +13,33 @@ function isPlainRecord(value) {
13
13
  const prototype = Object.getPrototypeOf(value);
14
14
  return prototype === Object.prototype || prototype === null;
15
15
  }
16
- export function getLatestTaskStepsStateSnapshot(entries) {
17
- for (let index = entries.length - 1; index >= 0; index--) {
18
- const entry = entries[index];
19
- if (entry.type !== "custom" || entry.customType !== TASK_STEPS_STATE_CUSTOM_TYPE)
20
- continue;
21
- const payload = entry.data;
22
- if (!isPlainRecord(payload) || payload.version !== 1 || !("state" in payload))
23
- continue;
24
- if (isTaskStepsState(payload.state))
25
- return cloneTaskStepsState(payload.state);
26
- }
16
+ /** Pure payload decode: validates + clones a task-steps snapshot payload. No SessionManager access,
17
+ * so unit tests can exercise decoding directly against a constructed `data` value. */
18
+ export function decodeTaskStepsStateSnapshotPayload(data) {
19
+ if (!isPlainRecord(data) || data.version !== 1 || !("state" in data))
20
+ return undefined;
21
+ if (isTaskStepsState(data.state))
22
+ return cloneTaskStepsState(data.state);
27
23
  return undefined;
28
24
  }
25
+ /**
26
+ * Most recent VALID task-steps snapshot on the active branch. Walks leaf→root ancestry via
27
+ * `getLatestCustomEntryOnBranch`, skipping entries whose payload fails to decode and resuming
28
+ * the search from that entry's parent, so an older valid snapshot still wins over a newer
29
+ * malformed one (matches the pre-branch-scoping flat-list resolution semantics).
30
+ */
31
+ export function getLatestTaskStepsStateSnapshot(sessionManager) {
32
+ let fromId;
33
+ for (;;) {
34
+ const entry = sessionManager.getLatestCustomEntryOnBranch(TASK_STEPS_STATE_CUSTOM_TYPE, fromId);
35
+ if (!entry)
36
+ return undefined;
37
+ const decoded = decodeTaskStepsStateSnapshotPayload(entry.data);
38
+ if (decoded !== undefined)
39
+ return decoded;
40
+ if (entry.parentId === null)
41
+ return undefined;
42
+ fromId = entry.parentId;
43
+ }
44
+ }
29
45
  //# sourceMappingURL=session-task-state.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"session-task-state.js","sourceRoot":"","sources":["../../../src/core/tasks/session-task-state.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,gBAAgB,EAAuB,MAAM,iBAAiB,CAAC;AAE7F,MAAM,CAAC,MAAM,4BAA4B,GAAG,kBAAkB,CAAC;AAO/D,MAAM,UAAU,4BAA4B,CAC3C,cAAyD,EACzD,KAAqB,EACZ;IACT,MAAM,OAAO,GAAkC;QAC9C,OAAO,EAAE,CAAC;QACV,KAAK,EAAE,mBAAmB,CAAC,KAAK,CAAC;KACjC,CAAC;IACF,OAAO,cAAc,CAAC,iBAAiB,CAAC,4BAA4B,EAAE,OAAO,CAAC,CAAC;AAAA,CAC/E;AAED,SAAS,aAAa,CAAC,KAAc,EAAoC;IACxE,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAC9E,MAAM,SAAS,GAAG,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;IAC/C,OAAO,SAAS,KAAK,MAAM,CAAC,SAAS,IAAI,SAAS,KAAK,IAAI,CAAC;AAAA,CAC5D;AAED,MAAM,UAAU,+BAA+B,CAAC,OAAgC,EAA8B;IAC7G,KAAK,IAAI,KAAK,GAAG,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,KAAK,IAAI,CAAC,EAAE,KAAK,EAAE,EAAE,CAAC;QAC1D,MAAM,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC;QAC7B,IAAI,KAAK,CAAC,IAAI,KAAK,QAAQ,IAAI,KAAK,CAAC,UAAU,KAAK,4BAA4B;YAAE,SAAS;QAC3F,MAAM,OAAO,GAAG,KAAK,CAAC,IAAI,CAAC;QAC3B,IAAI,CAAC,aAAa,CAAC,OAAO,CAAC,IAAI,OAAO,CAAC,OAAO,KAAK,CAAC,IAAI,CAAC,CAAC,OAAO,IAAI,OAAO,CAAC;YAAE,SAAS;QACxF,IAAI,gBAAgB,CAAC,OAAO,CAAC,KAAK,CAAC;YAAE,OAAO,mBAAmB,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IAChF,CAAC;IACD,OAAO,SAAS,CAAC;AAAA,CACjB","sourcesContent":["import type { SessionEntry, SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport { cloneTaskStepsState, isTaskStepsState, type TaskStepsState } from \"./task-state.ts\";\n\nexport const TASK_STEPS_STATE_CUSTOM_TYPE = \"task_steps_state\";\n\nexport interface TaskStepsStateSnapshotPayload {\n\tversion: 1;\n\tstate: TaskStepsState;\n}\n\nexport function appendTaskStepsStateSnapshot(\n\tsessionManager: Pick<SessionManager, \"appendCustomEntry\">,\n\tstate: TaskStepsState,\n): string {\n\tconst payload: TaskStepsStateSnapshotPayload = {\n\t\tversion: 1,\n\t\tstate: cloneTaskStepsState(state),\n\t};\n\treturn sessionManager.appendCustomEntry(TASK_STEPS_STATE_CUSTOM_TYPE, payload);\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\nexport function getLatestTaskStepsStateSnapshot(entries: readonly SessionEntry[]): TaskStepsState | undefined {\n\tfor (let index = entries.length - 1; index >= 0; index--) {\n\t\tconst entry = entries[index];\n\t\tif (entry.type !== \"custom\" || entry.customType !== TASK_STEPS_STATE_CUSTOM_TYPE) continue;\n\t\tconst payload = entry.data;\n\t\tif (!isPlainRecord(payload) || payload.version !== 1 || !(\"state\" in payload)) continue;\n\t\tif (isTaskStepsState(payload.state)) return cloneTaskStepsState(payload.state);\n\t}\n\treturn undefined;\n}\n"]}
1
+ {"version":3,"file":"session-task-state.js","sourceRoot":"","sources":["../../../src/core/tasks/session-task-state.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,mBAAmB,EAAE,gBAAgB,EAAuB,MAAM,iBAAiB,CAAC;AAE7F,MAAM,CAAC,MAAM,4BAA4B,GAAG,kBAAkB,CAAC;AAO/D,MAAM,UAAU,4BAA4B,CAC3C,cAAyD,EACzD,KAAqB,EACZ;IACT,MAAM,OAAO,GAAkC;QAC9C,OAAO,EAAE,CAAC;QACV,KAAK,EAAE,mBAAmB,CAAC,KAAK,CAAC;KACjC,CAAC;IACF,OAAO,cAAc,CAAC,iBAAiB,CAAC,4BAA4B,EAAE,OAAO,CAAC,CAAC;AAAA,CAC/E;AAED,SAAS,aAAa,CAAC,KAAc,EAAoC;IACxE,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC;QAAE,OAAO,KAAK,CAAC;IAC9E,MAAM,SAAS,GAAG,MAAM,CAAC,cAAc,CAAC,KAAK,CAAC,CAAC;IAC/C,OAAO,SAAS,KAAK,MAAM,CAAC,SAAS,IAAI,SAAS,KAAK,IAAI,CAAC;AAAA,CAC5D;AAED;sFACsF;AACtF,MAAM,UAAU,mCAAmC,CAAC,IAAa,EAA8B;IAC9F,IAAI,CAAC,aAAa,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,OAAO,KAAK,CAAC,IAAI,CAAC,CAAC,OAAO,IAAI,IAAI,CAAC;QAAE,OAAO,SAAS,CAAC;IACvF,IAAI,gBAAgB,CAAC,IAAI,CAAC,KAAK,CAAC;QAAE,OAAO,mBAAmB,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACzE,OAAO,SAAS,CAAC;AAAA,CACjB;AAED;;;;;GAKG;AACH,MAAM,UAAU,+BAA+B,CAC9C,cAAoE,EACvC;IAC7B,IAAI,MAA0B,CAAC;IAC/B,SAAS,CAAC;QACT,MAAM,KAAK,GAAG,cAAc,CAAC,4BAA4B,CAAC,4BAA4B,EAAE,MAAM,CAAC,CAAC;QAChG,IAAI,CAAC,KAAK;YAAE,OAAO,SAAS,CAAC;QAC7B,MAAM,OAAO,GAAG,mCAAmC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAChE,IAAI,OAAO,KAAK,SAAS;YAAE,OAAO,OAAO,CAAC;QAC1C,IAAI,KAAK,CAAC,QAAQ,KAAK,IAAI;YAAE,OAAO,SAAS,CAAC;QAC9C,MAAM,GAAG,KAAK,CAAC,QAAQ,CAAC;IACzB,CAAC;AAAA,CACD","sourcesContent":["import type { SessionManager } from \"@caupulican/pi-agent-core/node\";\nimport { cloneTaskStepsState, isTaskStepsState, type TaskStepsState } from \"./task-state.ts\";\n\nexport const TASK_STEPS_STATE_CUSTOM_TYPE = \"task_steps_state\";\n\nexport interface TaskStepsStateSnapshotPayload {\n\tversion: 1;\n\tstate: TaskStepsState;\n}\n\nexport function appendTaskStepsStateSnapshot(\n\tsessionManager: Pick<SessionManager, \"appendCustomEntry\">,\n\tstate: TaskStepsState,\n): string {\n\tconst payload: TaskStepsStateSnapshotPayload = {\n\t\tversion: 1,\n\t\tstate: cloneTaskStepsState(state),\n\t};\n\treturn sessionManager.appendCustomEntry(TASK_STEPS_STATE_CUSTOM_TYPE, payload);\n}\n\nfunction isPlainRecord(value: unknown): value is Record<string, unknown> {\n\tif (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\n/** Pure payload decode: validates + clones a task-steps snapshot payload. No SessionManager access,\n * so unit tests can exercise decoding directly against a constructed `data` value. */\nexport function decodeTaskStepsStateSnapshotPayload(data: unknown): TaskStepsState | undefined {\n\tif (!isPlainRecord(data) || data.version !== 1 || !(\"state\" in data)) return undefined;\n\tif (isTaskStepsState(data.state)) return cloneTaskStepsState(data.state);\n\treturn undefined;\n}\n\n/**\n * Most recent VALID task-steps snapshot on the active branch. Walks leaf→root ancestry via\n * `getLatestCustomEntryOnBranch`, skipping entries whose payload fails to decode and resuming\n * the search from that entry's parent, so an older valid snapshot still wins over a newer\n * malformed one (matches the pre-branch-scoping flat-list resolution semantics).\n */\nexport function getLatestTaskStepsStateSnapshot(\n\tsessionManager: Pick<SessionManager, \"getLatestCustomEntryOnBranch\">,\n): TaskStepsState | undefined {\n\tlet fromId: string | undefined;\n\tfor (;;) {\n\t\tconst entry = sessionManager.getLatestCustomEntryOnBranch(TASK_STEPS_STATE_CUSTOM_TYPE, fromId);\n\t\tif (!entry) return undefined;\n\t\tconst decoded = decodeTaskStepsStateSnapshotPayload(entry.data);\n\t\tif (decoded !== undefined) return decoded;\n\t\tif (entry.parentId === null) return undefined;\n\t\tfromId = entry.parentId;\n\t}\n}\n"]}