@caupulican/pi-adaptative 0.86.17 → 0.90.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (297) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +1 -1
  3. package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts.map +1 -1
  4. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js +14 -15
  5. package/dist/bundled-resources/extensions/tmux-agent-manager/index.js.map +1 -1
  6. package/dist/bundled-resources/extensions/tmux-agent-manager/index.ts +14 -16
  7. package/dist/bundled-resources/skills/worker-profile-writer/SKILL.md +4 -4
  8. package/dist/core/agent-session.d.ts +23 -33
  9. package/dist/core/agent-session.d.ts.map +1 -1
  10. package/dist/core/agent-session.js +81 -110
  11. package/dist/core/agent-session.js.map +1 -1
  12. package/dist/core/autonomy/contracts.d.ts +1 -1
  13. package/dist/core/autonomy/contracts.js.map +1 -1
  14. package/dist/core/autonomy/gates.d.ts.map +1 -1
  15. package/dist/core/autonomy/gates.js +16 -0
  16. package/dist/core/autonomy/gates.js.map +1 -1
  17. package/dist/core/autonomy/subagent-prompt.d.ts +2 -1
  18. package/dist/core/autonomy/subagent-prompt.d.ts.map +1 -1
  19. package/dist/core/autonomy/subagent-prompt.js +2 -18
  20. package/dist/core/autonomy/subagent-prompt.js.map +1 -1
  21. package/dist/core/background-tool-task-controller.js +5 -5
  22. package/dist/core/background-tool-task-controller.js.map +1 -1
  23. package/dist/core/compaction-controller.d.ts +22 -2
  24. package/dist/core/compaction-controller.d.ts.map +1 -1
  25. package/dist/core/compaction-controller.js +75 -39
  26. package/dist/core/compaction-controller.js.map +1 -1
  27. package/dist/core/context/brain-curator.d.ts +2 -3
  28. package/dist/core/context/brain-curator.d.ts.map +1 -1
  29. package/dist/core/context/brain-curator.js +3 -20
  30. package/dist/core/context/brain-curator.js.map +1 -1
  31. package/dist/core/context/context-composition.d.ts +2 -1
  32. package/dist/core/context/context-composition.d.ts.map +1 -1
  33. package/dist/core/context/context-composition.js +6 -1
  34. package/dist/core/context/context-composition.js.map +1 -1
  35. package/dist/core/context/memory-prompt-block.js +1 -1
  36. package/dist/core/context/memory-prompt-block.js.map +1 -1
  37. package/dist/core/context/tool-output-packer.js +1 -1
  38. package/dist/core/context/tool-output-packer.js.map +1 -1
  39. package/dist/core/context-gc.js +10 -10
  40. package/dist/core/context-gc.js.map +1 -1
  41. package/dist/core/context-pipeline.d.ts +4 -4
  42. package/dist/core/context-pipeline.js +4 -4
  43. package/dist/core/context-pipeline.js.map +1 -1
  44. package/dist/core/default-tool-surface.d.ts.map +1 -1
  45. package/dist/core/default-tool-surface.js +1 -2
  46. package/dist/core/default-tool-surface.js.map +1 -1
  47. package/dist/core/delegation/session-worker-claim.d.ts +2 -2
  48. package/dist/core/delegation/session-worker-claim.js +2 -2
  49. package/dist/core/delegation/session-worker-claim.js.map +1 -1
  50. package/dist/core/delegation/worker-agent-control-coordinator.js +1 -1
  51. package/dist/core/delegation/worker-agent-control-coordinator.js.map +1 -1
  52. package/dist/core/delegation/worker-resource-materializer.js +3 -3
  53. package/dist/core/delegation/worker-resource-materializer.js.map +1 -1
  54. package/dist/core/delegation/worker-runner.d.ts +2 -13
  55. package/dist/core/delegation/worker-runner.d.ts.map +1 -1
  56. package/dist/core/delegation/worker-runner.js +5 -67
  57. package/dist/core/delegation/worker-runner.js.map +1 -1
  58. package/dist/core/extensions/builtin.js +4 -4
  59. package/dist/core/extensions/builtin.js.map +1 -1
  60. package/dist/core/extensions/runner.d.ts +6 -2
  61. package/dist/core/extensions/runner.d.ts.map +1 -1
  62. package/dist/core/extensions/runner.js +21 -9
  63. package/dist/core/extensions/runner.js.map +1 -1
  64. package/dist/core/extensions/types.d.ts +9 -2
  65. package/dist/core/extensions/types.d.ts.map +1 -1
  66. package/dist/core/extensions/types.js.map +1 -1
  67. package/dist/core/foreground-terminal-handoff-controller.js +2 -2
  68. package/dist/core/foreground-terminal-handoff-controller.js.map +1 -1
  69. package/dist/core/goals/compact-goal-context.d.ts.map +1 -1
  70. package/dist/core/goals/compact-goal-context.js +13 -9
  71. package/dist/core/goals/compact-goal-context.js.map +1 -1
  72. package/dist/core/goals/goal-continuation-prompt.js +1 -1
  73. package/dist/core/goals/goal-continuation-prompt.js.map +1 -1
  74. package/dist/core/goals/goal-session-controller.d.ts +6 -0
  75. package/dist/core/goals/goal-session-controller.d.ts.map +1 -1
  76. package/dist/core/goals/goal-session-controller.js +16 -13
  77. package/dist/core/goals/goal-session-controller.js.map +1 -1
  78. package/dist/core/human-input-controller.js +1 -1
  79. package/dist/core/human-input-controller.js.map +1 -1
  80. package/dist/core/improvement-loop.js +13 -13
  81. package/dist/core/improvement-loop.js.map +1 -1
  82. package/dist/core/learning/reflection-engine.d.ts +2 -1
  83. package/dist/core/learning/reflection-engine.d.ts.map +1 -1
  84. package/dist/core/learning/reflection-engine.js +4 -24
  85. package/dist/core/learning/reflection-engine.js.map +1 -1
  86. package/dist/core/model-capability.d.ts.map +1 -1
  87. package/dist/core/model-capability.js +1 -1
  88. package/dist/core/model-capability.js.map +1 -1
  89. package/dist/core/model-router/route-judge.d.ts +2 -1
  90. package/dist/core/model-router/route-judge.d.ts.map +1 -1
  91. package/dist/core/model-router/route-judge.js +4 -12
  92. package/dist/core/model-router/route-judge.js.map +1 -1
  93. package/dist/core/models/perf-profile.d.ts +1 -1
  94. package/dist/core/models/perf-profile.d.ts.map +1 -1
  95. package/dist/core/models/perf-profile.js +2 -8
  96. package/dist/core/models/perf-profile.js.map +1 -1
  97. package/dist/core/orchestration/lane-tool-manifests.d.ts +1 -1
  98. package/dist/core/orchestration/lane-tool-manifests.d.ts.map +1 -1
  99. package/dist/core/orchestration/lane-tool-manifests.js +1 -6
  100. package/dist/core/orchestration/lane-tool-manifests.js.map +1 -1
  101. package/dist/core/process-matrix/resume-launcher.js +3 -3
  102. package/dist/core/process-matrix/resume-launcher.js.map +1 -1
  103. package/dist/core/process-matrix/runtime.d.ts +2 -0
  104. package/dist/core/process-matrix/runtime.d.ts.map +1 -1
  105. package/dist/core/process-matrix/runtime.js +23 -19
  106. package/dist/core/process-matrix/runtime.js.map +1 -1
  107. package/dist/core/provider-prompt-contracts.d.ts +34 -0
  108. package/dist/core/provider-prompt-contracts.d.ts.map +1 -0
  109. package/dist/core/provider-prompt-contracts.js +133 -0
  110. package/dist/core/provider-prompt-contracts.js.map +1 -0
  111. package/dist/core/provider-request-context-controller.d.ts +40 -0
  112. package/dist/core/provider-request-context-controller.d.ts.map +1 -0
  113. package/dist/core/provider-request-context-controller.js +68 -0
  114. package/dist/core/provider-request-context-controller.js.map +1 -0
  115. package/dist/core/provider-request-runtime-controller.d.ts +22 -0
  116. package/dist/core/provider-request-runtime-controller.d.ts.map +1 -0
  117. package/dist/core/provider-request-runtime-controller.js +87 -0
  118. package/dist/core/provider-request-runtime-controller.js.map +1 -0
  119. package/dist/core/provider-tool-text.d.ts +7 -0
  120. package/dist/core/provider-tool-text.d.ts.map +1 -0
  121. package/dist/core/provider-tool-text.js +42 -0
  122. package/dist/core/provider-tool-text.js.map +1 -0
  123. package/dist/core/research/model-fitness.d.ts +2 -5
  124. package/dist/core/research/model-fitness.d.ts.map +1 -1
  125. package/dist/core/research/model-fitness.js +2 -20
  126. package/dist/core/research/model-fitness.js.map +1 -1
  127. package/dist/core/research/research-runner.d.ts +2 -1
  128. package/dist/core/research/research-runner.d.ts.map +1 -1
  129. package/dist/core/research/research-runner.js +6 -21
  130. package/dist/core/research/research-runner.js.map +1 -1
  131. package/dist/core/risk-classifier.d.ts.map +1 -1
  132. package/dist/core/risk-classifier.js +9 -1
  133. package/dist/core/risk-classifier.js.map +1 -1
  134. package/dist/core/runtime-builder.d.ts +3 -0
  135. package/dist/core/runtime-builder.d.ts.map +1 -1
  136. package/dist/core/runtime-builder.js +20 -25
  137. package/dist/core/runtime-builder.js.map +1 -1
  138. package/dist/core/scout-controller.d.ts +2 -1
  139. package/dist/core/scout-controller.d.ts.map +1 -1
  140. package/dist/core/scout-controller.js +2 -16
  141. package/dist/core/scout-controller.js.map +1 -1
  142. package/dist/core/sdk.d.ts +1 -1
  143. package/dist/core/sdk.js.map +1 -1
  144. package/dist/core/secrets/credential-exposure-guard.js +6 -6
  145. package/dist/core/secrets/credential-exposure-guard.js.map +1 -1
  146. package/dist/core/secrets/credential-manager.d.ts +11 -1
  147. package/dist/core/secrets/credential-manager.d.ts.map +1 -1
  148. package/dist/core/secrets/credential-manager.js +28 -7
  149. package/dist/core/secrets/credential-manager.js.map +1 -1
  150. package/dist/core/secrets/credential-migration-source.d.ts +20 -0
  151. package/dist/core/secrets/credential-migration-source.d.ts.map +1 -0
  152. package/dist/core/secrets/credential-migration-source.js +113 -0
  153. package/dist/core/secrets/credential-migration-source.js.map +1 -0
  154. package/dist/core/secrets/credential-session-connection.d.ts +9 -0
  155. package/dist/core/secrets/credential-session-connection.d.ts.map +1 -0
  156. package/dist/core/secrets/credential-session-connection.js +39 -0
  157. package/dist/core/secrets/credential-session-connection.js.map +1 -0
  158. package/dist/core/security/untrusted-boundary.d.ts +2 -2
  159. package/dist/core/security/untrusted-boundary.d.ts.map +1 -1
  160. package/dist/core/security/untrusted-boundary.js +3 -10
  161. package/dist/core/security/untrusted-boundary.js.map +1 -1
  162. package/dist/core/session-role.d.ts.map +1 -1
  163. package/dist/core/session-role.js +1 -2
  164. package/dist/core/session-role.js.map +1 -1
  165. package/dist/core/skill-vault.d.ts +98 -0
  166. package/dist/core/skill-vault.d.ts.map +1 -0
  167. package/dist/core/skill-vault.js +270 -0
  168. package/dist/core/skill-vault.js.map +1 -0
  169. package/dist/core/skills.d.ts +10 -9
  170. package/dist/core/skills.d.ts.map +1 -1
  171. package/dist/core/skills.js +42 -50
  172. package/dist/core/skills.js.map +1 -1
  173. package/dist/core/system-prompt-builder.d.ts +1 -1
  174. package/dist/core/system-prompt-builder.d.ts.map +1 -1
  175. package/dist/core/system-prompt-builder.js +20 -60
  176. package/dist/core/system-prompt-builder.js.map +1 -1
  177. package/dist/core/system-prompt.d.ts +4 -4
  178. package/dist/core/system-prompt.d.ts.map +1 -1
  179. package/dist/core/system-prompt.js +87 -121
  180. package/dist/core/system-prompt.js.map +1 -1
  181. package/dist/core/tasks/task-state.d.ts.map +1 -1
  182. package/dist/core/tasks/task-state.js +6 -7
  183. package/dist/core/tasks/task-state.js.map +1 -1
  184. package/dist/core/tool-capability-policy.d.ts.map +1 -1
  185. package/dist/core/tool-capability-policy.js +2 -1
  186. package/dist/core/tool-capability-policy.js.map +1 -1
  187. package/dist/core/tool-protocol-controller.d.ts.map +1 -1
  188. package/dist/core/tool-protocol-controller.js +4 -7
  189. package/dist/core/tool-protocol-controller.js.map +1 -1
  190. package/dist/core/tool-selection/promotion.d.ts.map +1 -1
  191. package/dist/core/tool-selection/promotion.js +2 -6
  192. package/dist/core/tool-selection/promotion.js.map +1 -1
  193. package/dist/core/toolkit/reflex-interpreter.d.ts +2 -1
  194. package/dist/core/toolkit/reflex-interpreter.d.ts.map +1 -1
  195. package/dist/core/toolkit/reflex-interpreter.js +2 -14
  196. package/dist/core/toolkit/reflex-interpreter.js.map +1 -1
  197. package/dist/core/tools/ask-question.js +6 -6
  198. package/dist/core/tools/ask-question.js.map +1 -1
  199. package/dist/core/tools/bash.d.ts.map +1 -1
  200. package/dist/core/tools/bash.js +8 -7
  201. package/dist/core/tools/bash.js.map +1 -1
  202. package/dist/core/tools/delegate-status.d.ts +17 -13
  203. package/dist/core/tools/delegate-status.d.ts.map +1 -1
  204. package/dist/core/tools/delegate-status.js +111 -226
  205. package/dist/core/tools/delegate-status.js.map +1 -1
  206. package/dist/core/tools/delegate.d.ts +29 -2
  207. package/dist/core/tools/delegate.d.ts.map +1 -1
  208. package/dist/core/tools/delegate.js +149 -48
  209. package/dist/core/tools/delegate.js.map +1 -1
  210. package/dist/core/tools/edit.js +3 -3
  211. package/dist/core/tools/edit.js.map +1 -1
  212. package/dist/core/tools/extensionify-runtime.js +4 -4
  213. package/dist/core/tools/extensionify-runtime.js.map +1 -1
  214. package/dist/core/tools/find.d.ts.map +1 -1
  215. package/dist/core/tools/find.js +2 -4
  216. package/dist/core/tools/find.js.map +1 -1
  217. package/dist/core/tools/goal.js +3 -3
  218. package/dist/core/tools/goal.js.map +1 -1
  219. package/dist/core/tools/grep.js +2 -2
  220. package/dist/core/tools/grep.js.map +1 -1
  221. package/dist/core/tools/index.d.ts +1 -1
  222. package/dist/core/tools/index.d.ts.map +1 -1
  223. package/dist/core/tools/index.js +1 -1
  224. package/dist/core/tools/index.js.map +1 -1
  225. package/dist/core/tools/model-fitness.js +4 -4
  226. package/dist/core/tools/model-fitness.js.map +1 -1
  227. package/dist/core/tools/profile-writer.d.ts +30 -16
  228. package/dist/core/tools/profile-writer.d.ts.map +1 -1
  229. package/dist/core/tools/profile-writer.js +98 -59
  230. package/dist/core/tools/profile-writer.js.map +1 -1
  231. package/dist/core/tools/python.js +6 -6
  232. package/dist/core/tools/python.js.map +1 -1
  233. package/dist/core/tools/run-process.js +4 -4
  234. package/dist/core/tools/run-process.js.map +1 -1
  235. package/dist/core/tools/run-toolkit-script.js +4 -4
  236. package/dist/core/tools/run-toolkit-script.js.map +1 -1
  237. package/dist/core/tools/secret-store.d.ts +32 -3
  238. package/dist/core/tools/secret-store.d.ts.map +1 -1
  239. package/dist/core/tools/secret-store.js +141 -34
  240. package/dist/core/tools/secret-store.js.map +1 -1
  241. package/dist/core/tools/skill.d.ts +29 -0
  242. package/dist/core/tools/skill.d.ts.map +1 -0
  243. package/dist/core/tools/skill.js +79 -0
  244. package/dist/core/tools/skill.js.map +1 -0
  245. package/dist/core/tools/task-steps.js +4 -4
  246. package/dist/core/tools/task-steps.js.map +1 -1
  247. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
  248. package/dist/core/tools/tool-definition-wrapper.js +2 -0
  249. package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
  250. package/dist/core/tools/tool-task.d.ts.map +1 -1
  251. package/dist/core/tools/tool-task.js +4 -0
  252. package/dist/core/tools/tool-task.js.map +1 -1
  253. package/dist/core/tools/worktree-sync.js +6 -6
  254. package/dist/core/tools/worktree-sync.js.map +1 -1
  255. package/dist/core/tools/write.js +3 -3
  256. package/dist/core/tools/write.js.map +1 -1
  257. package/dist/index.d.ts +5 -2
  258. package/dist/index.d.ts.map +1 -1
  259. package/dist/index.js +4 -1
  260. package/dist/index.js.map +1 -1
  261. package/dist/modes/interactive/interactive-event-controller.js +1 -1
  262. package/dist/modes/interactive/interactive-event-controller.js.map +1 -1
  263. package/dist/modes/interactive/interactive-mode.js +1 -1
  264. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  265. package/dist/modes/interactive/report-commands.js +1 -1
  266. package/dist/modes/interactive/report-commands.js.map +1 -1
  267. package/dist/modes/interactive/secret-menu-controller.d.ts.map +1 -1
  268. package/dist/modes/interactive/secret-menu-controller.js +2 -18
  269. package/dist/modes/interactive/secret-menu-controller.js.map +1 -1
  270. package/dist/modes/interactive/session-flow-commands.js +1 -1
  271. package/dist/modes/interactive/session-flow-commands.js.map +1 -1
  272. package/docs/compaction.md +45 -25
  273. package/docs/extensions.md +23 -7
  274. package/docs/settings.md +3 -3
  275. package/docs/skills.md +14 -10
  276. package/docs/task-steps.md +2 -2
  277. package/docs/tmux-agent-manager.md +1 -1
  278. package/docs/tool-repair.md +18 -1
  279. package/docs/usage.md +4 -2
  280. package/docs/worker-profiles.md +3 -3
  281. package/docs/worktree-sync.md +2 -2
  282. package/examples/extensions/custom-compaction.ts +5 -17
  283. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  284. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  285. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  286. package/examples/extensions/sandbox/package-lock.json +2 -2
  287. package/examples/extensions/sandbox/package.json +1 -1
  288. package/examples/extensions/summarize.ts +3 -5
  289. package/examples/extensions/with-deps/package-lock.json +2 -2
  290. package/examples/extensions/with-deps/package.json +1 -1
  291. package/examples/sdk/04-skills.ts +1 -1
  292. package/npm-shrinkwrap.json +12 -12
  293. package/package.json +4 -4
  294. package/dist/core/util/json-size.d.ts +0 -3
  295. package/dist/core/util/json-size.d.ts.map +0 -1
  296. package/dist/core/util/json-size.js +0 -95
  297. package/dist/core/util/json-size.js.map +0 -1
@@ -1,87 +1,97 @@
1
1
  /**
2
2
  * System prompt construction and project context loading
3
3
  */
4
- import { getDocsPath, getExamplesPath, getReadmePath } from "../config.js";
4
+ import { dirname } from "node:path";
5
+ import { getReadmePath } from "../config.js";
5
6
  import { getExtensionDescription, getExtensionDisplayName } from "./extension-metadata.js";
6
7
  import { enforceModelCapabilitySystemPromptBudget } from "./model-capability.js";
7
- import { escapePromptXml } from "./prompt-markup.js";
8
- import { formatSkillsForPrompt } from "./skills.js";
9
- const PI_ADAPTATIVE_CORE_SECTION = `
10
-
11
- OPERATING POSTURE
12
-
13
- - Treat a clear outcome expressed in normal conversation as a goal; no slash command is required. Persist evidence and progress, survive compaction, and continue until delivered or stopped.
14
- - Hold scope. Verify uncertainty from authoritative sources; use the simplest proven design that satisfies ownership, lifecycle, performance, and failure needs.
15
- - Store durable facts in memory, reusable specialization in skills, and behavior in source. Shard and index oversized memory; discard noise.
16
- - Choose autonomously; create recursive agents for coherent parallel work while the root owns integration and the scheduler owns global budgets and concurrency.
17
- - The user’s desired outcome is authoritative; a proposed method is not. If a method may undermine the outcome, pause: give causal evidence, test the disputed premise when practical, and offer the strongest outcome-preserving alternative. Once chosen, execute faithfully within authority.
18
- - Move work expected to exceed 15 seconds into managed background execution. Require event-driven completion, a bounded handoff, and owner notification; never poll.
19
- - Ask before scope expansion, credentials, destructive actions, or publication. Keep external and tool output bounded, source-labeled, and evidence-focused; show file paths clearly.
20
-
21
- N+2 ARCHITECTURE
8
+ import { SKILL_VAULT_SYSTEM_RULE } from "./provider-prompt-contracts.js";
9
+ const MODEL_BLIND_CREDENTIAL_AUTHORITY = "Active secret_store: host gate authorizes model-blind activation/migration from named accessible sources; no duplicate confirmation.";
10
+ const ULTRA_TERSE_OUTPUT_POLICY = `
22
11
 
23
- Apply these language-agnostic principles with direct runtime facilities:
12
+ ULTRA-TERSE OUTPUT
24
13
 
25
- 1. Group Lifetimes: Put overlapping lifetimes in bounded arenas, pools, rings, chunks, or flat owners; recycle in batches and avoid per-item churn.
14
+ - Drop articles/filler/pleasantries/hedging; fragments valid. Strip conjunctions only when clear; each fact once.
15
+ - Never drop not/never/no/only/except; never invent abbreviations or use causal arrows. Preserve numbers, units, code symbols, function/API names, commands, errors.
16
+ - No self-reference/tool narration/tables/emoji/log dumps. Keep user language. Full grammar: security, irreversible actions, ambiguous order. Replies terse; artifacts normal prose.`;
17
+ const PI_ADAPTATIVE_CORE_SECTION = `
26
18
 
27
- 2. Valid Defaults: Make zero/default data, handles, states, and resources safe without hidden allocation; one system owns activation.
19
+ OPERATING CONTRACT
28
20
 
29
- 3. Stubs and Boundaries: Validate trust and external boundaries once. Internal misses return benign stubs, sentinels, or defaults; external failures stay explicit.
21
+ - Clear conversational outcome is goal; persist progress/evidence through compaction; finish or report blocker.
22
+ - Hold scope; verify unknowns from primary sources; simplest proven design, one owner/path per invariant.
23
+ - User outcome governs, method does not. Outcome risk: show evidence, test when practical, offer safest effective path, execute.
24
+ - Work over 15 seconds: managed background run, event terminal, bounded handoff, owner notice; never poll.
25
+ - Delegate independent work within host bounds; root integrates/verifies. Facts: memory, specialization: skills, behavior: source; discard noise.
26
+ - Ask before broader scope, credential or authentication change/disclosure, destructive action, publication. Bound, source-label output; show paths.
27
+ - ${MODEL_BLIND_CREDENTIAL_AUTHORITY}
30
28
 
31
- 4. Flat Ownership: Prefer flat/chunked data, stable IDs, compact indexes, buffers, and batches over pointer graphs, needless dispatch, fallbacks, or wrappers.
29
+ N+2 ARCHITECTURE
32
30
 
33
- 5. Linear Bounds: Never concatenate growing prefixes, prepend repeatedly, rescan consumed input, serialize unchanged history, or rebuild full incremental state. Materialize only the needed window once.
31
+ Language-agnostic principles:
32
+ 1. Bounded flat arenas/pools/rings/chunks, batch recycle.
33
+ 2. Safe zero/default data/state, no hidden allocation, one activation owner.
34
+ 3. Validate trust boundary once; internal miss gets safe stub/default, external failure explicit.
35
+ 4. Stable IDs/indexes/buffers/batches; avoid pointer graphs/dispatch/fallback.
36
+ 5. Never concatenate growing prefixes, prepend, rescan consumed input, serialize unchanged history, rebuild incremental state; materialize once.
34
37
 
35
- ENGINEERING WORKFLOW
38
+ EVIDENCE GATE
36
39
 
37
- - Map flow, lifetimes, boundaries, hot paths, and one authoritative path per invariant.
38
- - Detect Verify Score Gate: baseline; reproduce with a negative control; fix the lowest owner; run focused, then proportionate gates.
39
- - Scanner, fuzzer, log, static, and model findings are candidates until reproduced. Never weaken tests or claim success from incomplete probes.`;
40
+ - Map flow/lifetimes/boundaries/hot paths. Detect, verify, score, gate: baseline; deterministic positive/negative controls; lowest-owner fix; focused/proportionate checks.
41
+ - Scanner/fuzzer/log/static/model finding stays candidate pending reproduction. Never weaken tests, claim success from skipped/incomplete probes.`;
40
42
  const PI_ADAPTATIVE_LEAN_CORE_SECTION = `
41
43
 
42
44
  OPERATING CONTRACT
43
45
 
44
- - Complete the current goal within scope and granted authority. Keep progress and evidence concise.
45
- - Inspect relevant files and project instructions before mutation. Make the smallest coherent change and verify it with focused checks.
46
- - Use only active tools and follow their schemas exactly. When a call fails, use the returned error and expected shape to correct it; never repeat an unchanged failed call.
47
- - Keep independent reads together and mutations ordered. Report real output and unresolved failures.
48
- - Ask before destructive actions, credentials, publication, push/tag/release, or material scope expansion.`;
46
+ - Complete current goal within scope, granted authority; keep progress, evidence concise.
47
+ - Inspect relevant files, project instructions before mutation; make smallest coherent change, run focused checks.
48
+ - Use active tools, exact schemas. On failure, read error, expected shape, correct call; never repeat unchanged failure.
49
+ - Batch independent reads, order mutations; report real output, unresolved failures.
50
+ - Ask before destructive actions, credential disclosure or provider authentication changes, publication, push/tag/release, material scope expansion.
51
+ - ${MODEL_BLIND_CREDENTIAL_AUTHORITY}`;
49
52
  const PI_ADAPTATIVE_MINIMAL_CORE_SECTION = `
50
53
 
51
54
  EXECUTION RULES
52
55
 
53
- - Work on one scoped task at a time. Inspect before editing, make a small coherent change, then run the narrowest useful verification.
54
- - Use only listed tools and exact schemas. If a tool call fails, read the returned error and expected shape, correct the call, and do not repeat it unchanged.
55
- - Keep independent reads together and mutations ordered. Report actual results; never claim an action you did not complete.
56
- - Ask before destructive actions, credentials, publication, push/tag/release, or a material scope change.`;
56
+ - Work one scoped task. Inspect before editing, make small coherent change, run narrowest useful check.
57
+ - Use listed tools, exact schemas. On failure, read error, expected shape, correct call; never repeat unchanged failure.
58
+ - Batch independent reads, order mutations. Report actual results; never claim incomplete action.
59
+ - Ask before destructive actions, credential disclosure or provider authentication changes, publication, push/tag/release, material scope change.
60
+ - ${MODEL_BLIND_CREDENTIAL_AUTHORITY}`;
57
61
  const PI_ADAPTATIVE_CHAT_CORE_SECTION = `
58
62
 
59
63
  CHAT RULES
60
64
 
61
- - Answer concisely from the conversation and state uncertainty.
65
+ - Answer concisely from conversation; state uncertainty.
62
66
  - No execution tools are active. Do not claim to read files, run commands, or make changes.
63
67
  - Say when the request requires a tool-capable model or additional user-provided context.`;
64
68
  const DEFERRED_CONTEXT_PATH_BUDGET_CHARS = 512;
65
- const LEAN_SKILL_CATALOG_BUDGET_CHARS = 500;
69
+ const EXTENSION_DESCRIPTION_BUDGET_CHARS = 180;
70
+ function compactPromptText(value, maxChars) {
71
+ const normalized = value.replace(/\s+/g, " ").trim();
72
+ if (normalized.length <= maxChars)
73
+ return normalized;
74
+ let end = maxChars - 1;
75
+ const code = normalized.charCodeAt(end - 1);
76
+ if (code >= 0xd800 && code <= 0xdbff)
77
+ end--;
78
+ return `${normalized.slice(0, end)}…`;
79
+ }
66
80
  function formatContextFilesForPrompt(contextFiles, options) {
67
81
  if (contextFiles.length === 0) {
68
82
  return "";
69
83
  }
70
84
  if (options.deferContents) {
71
85
  const lines = [
72
- "\n\n<project_context>",
73
- "",
74
- "Project instruction contents are deferred for this capability profile to preserve working context.",
86
+ "\n\nPROJECT RULE PATHS — contents deferred for this capability profile.",
75
87
  options.canRead
76
88
  ? "Before editing, writing, or running a mutating command, read each relevant listed file completely before any mutation. Follow its instructions; if a file cannot fit, ask for a scoped instruction digest."
77
89
  : "No read tool is active. Ask the user for the relevant project instructions before giving project-specific guidance.",
78
- "",
79
- "<deferred_project_instructions>",
80
90
  ];
81
91
  let pathChars = 0;
82
92
  let included = 0;
83
93
  for (const { path } of contextFiles) {
84
- const line = ` <file path="${escapePromptXml(path)}" />`;
94
+ const line = `- ${JSON.stringify(path)}`;
85
95
  if (pathChars + line.length > DEFERRED_CONTEXT_PATH_BUDGET_CHARS)
86
96
  break;
87
97
  lines.push(line);
@@ -90,42 +100,24 @@ function formatContextFilesForPrompt(contextFiles, options) {
90
100
  }
91
101
  const omitted = contextFiles.length - included;
92
102
  if (omitted > 0) {
93
- lines.push(` <omitted count="${omitted}" />`);
103
+ lines.push(`- omitted=${omitted}`);
94
104
  }
95
- lines.push("</deferred_project_instructions>", "", "</project_context>");
96
105
  if (omitted > 0) {
97
106
  lines.push("Do not mutate until the omitted instruction paths are supplied or a more capable profile is used.");
98
107
  }
99
108
  return lines.join("\n");
100
109
  }
101
- const lines = ["\n\n<project_context>", "", "Project-specific instructions and guidelines:", ""];
110
+ const lines = ["\n\nPROJECT-SPECIFIC INSTRUCTIONS (apply in listed order)"];
111
+ const seen = new Set();
102
112
  for (const { path, content } of contextFiles) {
103
- lines.push(`<project_instructions path="${escapePromptXml(path)}">`);
113
+ const identity = `${path}\0${content ?? ""}`;
114
+ if (seen.has(identity))
115
+ continue;
116
+ seen.add(identity);
117
+ lines.push(`FILE ${JSON.stringify(path)} (${(content ?? "").length} chars)`);
104
118
  lines.push(content ?? "");
105
- lines.push("</project_instructions>", "");
119
+ lines.push("END FILE");
106
120
  }
107
- lines.push("</project_context>");
108
- return lines.join("\n");
109
- }
110
- function formatLeanSkillsForPrompt(skills) {
111
- const eligibleSkills = skills.filter((skill) => !skill.disableModelInvocation);
112
- if (eligibleSkills.length === 0)
113
- return "";
114
- const lines = ["\n\nSpecialized skills (load only when clearly relevant):", "<available_skills>"];
115
- let catalogChars = 0;
116
- let included = 0;
117
- for (const skill of eligibleSkills) {
118
- const line = ` <skill name="${escapePromptXml(skill.name)}" location="${escapePromptXml(skill.filePath)}">${escapePromptXml(skill.description.slice(0, 120))}</skill>`;
119
- if (catalogChars + line.length > LEAN_SKILL_CATALOG_BUDGET_CHARS)
120
- break;
121
- lines.push(line);
122
- catalogChars += line.length + 1;
123
- included++;
124
- }
125
- lines.push("</available_skills>");
126
- const omitted = eligibleSkills.length - included;
127
- if (omitted > 0)
128
- lines.push(`${omitted} additional skill(s) are not preloaded on this profile.`);
129
121
  return lines.join("\n");
130
122
  }
131
123
  function appendPromptResources(prompt, options) {
@@ -136,12 +128,6 @@ function appendPromptResources(prompt, options) {
136
128
  deferContents: !options.fullPrompt,
137
129
  canRead: options.hasRead,
138
130
  });
139
- if (options.hasRead && options.skills.length > 0) {
140
- if (options.fullPrompt)
141
- result += formatSkillsForPrompt(options.skills);
142
- else if (options.leanPrompt)
143
- result += formatLeanSkillsForPrompt(options.skills);
144
- }
145
131
  // Extension metadata is redundant with the active tool snippets on constrained profiles.
146
132
  if (options.fullPrompt && options.extensions.length > 0) {
147
133
  result += formatExtensionsForPrompt(options.extensions, options.visibleTools);
@@ -158,7 +144,7 @@ function appendPromptResources(prompt, options) {
158
144
  * single cache breakpoint covering the whole system prompt). The caller (SystemPromptBuilder /
159
145
  * AgentSession, see `_rebuildSystemPrompt` in agent-session.ts) rebuilds it only when the TOOL
160
146
  * SURFACE changes — never per turn. For a fixed `options` (fixed tool surface, cwd, context
161
- * files, skills, extensions), two calls on the SAME CALENDAR DAY must return byte-identical
147
+ * files, extensions), two calls on the SAME CALENDAR DAY must return byte-identical
162
148
  * output, because `date` below is deliberately truncated to Y-M-D granularity. Do NOT widen it
163
149
  * to a timestamp (HH:MM:SS) or otherwise fold in any per-turn-volatile field (turn counters,
164
150
  * elapsed time, random ids, etc.) — that would cache-bust this entire block on EVERY turn instead
@@ -166,7 +152,7 @@ function appendPromptResources(prompt, options) {
166
152
  * request). Pinned by test/system-prompt-stability.test.ts.
167
153
  */
168
154
  export function buildSystemPrompt(options) {
169
- const { customPrompt, selectedTools, toolSnippets, promptGuidelines, appendSystemPrompt, cwd, contextFiles: providedContextFiles, skills: providedSkills, } = options;
155
+ const { customPrompt, selectedTools, toolSnippets, promptGuidelines, appendSystemPrompt, cwd, contextFiles: providedContextFiles, } = options;
170
156
  const resolvedCwd = cwd;
171
157
  const promptCwd = resolvedCwd.replace(/\\/g, "/");
172
158
  // Day-granularity only (see cache-stability invariant on buildSystemPrompt above): this must
@@ -178,7 +164,6 @@ export function buildSystemPrompt(options) {
178
164
  const date = `${year}-${month}-${day}`;
179
165
  const appendSection = appendSystemPrompt ? `\n\n${appendSystemPrompt}` : "";
180
166
  const contextFiles = providedContextFiles ?? [];
181
- const skills = providedSkills ?? [];
182
167
  const capabilityClass = options.modelCapability?.class ?? "full";
183
168
  const fullPrompt = capabilityClass === "full";
184
169
  const leanPrompt = capabilityClass === "lean";
@@ -192,27 +177,24 @@ export function buildSystemPrompt(options) {
192
177
  : capabilityClass === "minimal"
193
178
  ? PI_ADAPTATIVE_MINIMAL_CORE_SECTION
194
179
  : PI_ADAPTATIVE_CHAT_CORE_SECTION;
180
+ const skillVaultContract = activeTools.includes("skill") ? `\n\n${SKILL_VAULT_SYSTEM_RULE}` : "";
181
+ const operatingContract = `${coreSection}${skillVaultContract}${ULTRA_TERSE_OUTPUT_POLICY}`;
195
182
  if (customPrompt) {
196
183
  let prompt = customPrompt;
197
- prompt += coreSection;
184
+ prompt += operatingContract;
198
185
  return appendPromptResources(prompt, {
199
186
  appendSection,
200
187
  contextFiles,
201
- skills,
202
188
  extensions: options.extensions ?? [],
203
189
  visibleTools,
204
190
  fullPrompt,
205
- leanPrompt,
206
191
  hasRead,
207
192
  date,
208
193
  promptCwd,
209
194
  modelCapability: options.modelCapability,
210
195
  });
211
196
  }
212
- // Get absolute paths to documentation and examples
213
- const readmePath = getReadmePath();
214
- const docsPath = getDocsPath();
215
- const examplesPath = getExamplesPath();
197
+ const packageRoot = dirname(getReadmePath());
216
198
  // Build tools list based on selected tools.
217
199
  // A tool appears in Available tools only when the caller provides a one-line snippet.
218
200
  const toolsList = visibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets[name]}`).join("\n") : "(none)";
@@ -240,17 +222,17 @@ export function buildSystemPrompt(options) {
240
222
  addGuideline("Batch independent reads; keep mutations and dependent calls ordered");
241
223
  }
242
224
  else if (hasBash && !hasGrep && !hasFind && !hasLs) {
243
- addGuideline("Use bash for file operations like ls, rg, find");
225
+ addGuideline("Bash: ls, rg, find");
244
226
  }
245
227
  if (fullPrompt || leanPrompt) {
246
228
  if (hasBash || hasGrep || hasFind) {
247
- addGuideline("Use scoped rg to filter text and jq to project JSON: pass explicit roots and filters, inspect only selected records natively, and route unavoidable exhaustive output to a file");
229
+ addGuideline("rg/jq: scoped roots/filters, exhaustive output to file");
248
230
  }
249
231
  if (hasPython) {
250
- addGuideline("Use python for bounded scripts and data shaping when clearer than shell; use read/edit/write for exact source edits");
232
+ addGuideline("Python: bounded scripts/data, source edits via read/edit/write");
251
233
  }
252
234
  if (hasReadOnlyTools) {
253
- addGuideline("Issue independent read-only tool calls together in one assistant turn. Keep dependent calls, mutations, and stateful commands ordered");
235
+ addGuideline("Batch independent reads; order dependent/mutating/stateful calls");
254
236
  }
255
237
  }
256
238
  if (fullPrompt || leanPrompt) {
@@ -264,41 +246,32 @@ export function buildSystemPrompt(options) {
264
246
  const guidelines = guidelinesList.map((g) => `- ${g}`).join("\n");
265
247
  const toolGuidelinesSection = guidelines.length > 0 ? `\n\nTOOL GUIDELINES\n\n${guidelines}` : "";
266
248
  const introduction = fullPrompt
267
- ? "You are Pi-Adaptative, a self-evolving assistant. Complete and deliver the user’s goals within granted authority; preserve continuity through compaction and own the integrated result."
249
+ ? "Pi-Adaptative: self-evolving assistant. Deliver goals within authority; preserve continuity, own integration."
268
250
  : leanPrompt
269
- ? "You are Pi-Adaptative's bounded coding agent. Complete the current goal with the active surface and preserve enough evidence for handoff."
251
+ ? "Pi-Adaptative bounded coding agent. Complete current goal with active surface; preserve handoff evidence."
270
252
  : capabilityClass === "minimal"
271
- ? "You are Pi-Adaptative's focused coding executor. Complete one scoped task with active tools and report verified results."
272
- : "You are Pi-Adaptative's concise chat assistant. No execution tools are active.";
253
+ ? "Pi-Adaptative focused coding executor. Complete one scoped task with active tools; report verified results."
254
+ : "Pi-Adaptative concise chat assistant. No execution tools active.";
273
255
  const toolSurfaceRule = fullPrompt || leanPrompt
274
- ? "Use only capabilities present in the active tool surface; others may exist in the environment."
256
+ ? "Use active tool surface only; unlisted capabilities may exist."
275
257
  : "Use only the active tool surface.";
276
258
  let prompt = `${introduction}
277
259
 
278
260
  Available tools:
279
261
  ${toolsList}
280
262
 
281
- ${toolSurfaceRule}${coreSection}${toolGuidelinesSection}`;
263
+ ${toolSurfaceRule}${operatingContract}${toolGuidelinesSection}`;
282
264
  if (fullPrompt) {
283
265
  prompt += `
284
266
 
285
- PI-ADAPTATIVE DOCUMENTATION
286
-
287
- Only when asked about Pi-Adaptative, read the relevant files completely from:
288
- - Main documentation: ${readmePath}
289
- - Additional documentation: ${docsPath}
290
- - Examples: ${examplesPath}
291
-
292
- Resolve \`docs/...\` and \`examples/...\` from those roots and follow relevant Markdown cross-references before implementing.`;
267
+ PI DOCS: root=${packageRoot}. Relevant work only; read needed README.md, \`docs/...\`, \`examples/...\` fully, follow links.`;
293
268
  }
294
269
  return appendPromptResources(prompt, {
295
270
  appendSection,
296
271
  contextFiles,
297
- skills,
298
272
  extensions: options.extensions ?? [],
299
273
  visibleTools,
300
274
  fullPrompt,
301
- leanPrompt,
302
275
  hasRead,
303
276
  date,
304
277
  promptCwd,
@@ -309,7 +282,7 @@ function formatExtensionsForPrompt(extensions, visibleTools) {
309
282
  if (extensions.length === 0) {
310
283
  return "";
311
284
  }
312
- const lines = ["\n\nThe following extensions are currently loaded and active:", "", "<active_extensions>"];
285
+ const lines = ["\n\nEXTENSIONS: name, path, tools, commands, description"];
313
286
  let added = 0;
314
287
  for (const ext of extensions) {
315
288
  const name = getExtensionDisplayName(ext.path);
@@ -320,25 +293,18 @@ function formatExtensionsForPrompt(extensions, visibleTools) {
320
293
  if (tools.length === 0 && commands.length === 0 && !description) {
321
294
  continue;
322
295
  }
323
- lines.push(" <extension>");
324
- lines.push(` <name>${escapePromptXml(name)}</name>`);
325
- if (description) {
326
- lines.push(` <description>${escapePromptXml(description)}</description>`);
327
- }
328
- lines.push(` <path>${escapePromptXml(ext.path)}</path>`);
329
- if (tools.length > 0) {
330
- lines.push(` <registered_tools>${tools.map(escapePromptXml).join(", ")}</registered_tools>`);
331
- }
332
- if (commands.length > 0) {
333
- lines.push(` <registered_commands>${commands.map(escapePromptXml).join(", ")}</registered_commands>`);
334
- }
335
- lines.push(" </extension>");
296
+ lines.push(JSON.stringify({
297
+ name,
298
+ path: ext.path,
299
+ ...(tools.length > 0 ? { tools } : {}),
300
+ ...(commands.length > 0 ? { commands } : {}),
301
+ ...(description ? { description: compactPromptText(description, EXTENSION_DESCRIPTION_BUDGET_CHARS) } : {}),
302
+ }));
336
303
  added++;
337
304
  }
338
305
  if (added === 0) {
339
306
  return "";
340
307
  }
341
- lines.push("</active_extensions>");
342
308
  return lines.join("\n");
343
309
  }
344
310
  //# sourceMappingURL=system-prompt.js.map
@@ -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,OAAO,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAE3F,OAAO,EAAE,wCAAwC,EAA+B,MAAM,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AC,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;AACzB,CAAC","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 { enforceModelCapabilitySystemPromptBudget, type ModelCapabilityProfile } from \"./model-capability.ts\";\nimport { escapePromptXml } from \"./prompt-markup.ts\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.ts\";\n\nexport interface BuildSystemPromptOptions {\n\t/** Capability profile that selects the stable prompt shape. Missing means full/legacy behavior. */\n\tmodelCapability?: Pick<ModelCapabilityProfile, \"class\" | \"contextWindow\" | \"reasonCode\" | \"systemPromptMaxChars\">;\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 PI_ADAPTATIVE_CORE_SECTION = `\n\nOPERATING POSTURE\n\n- Treat a clear outcome expressed in normal conversation as a goal; no slash command is required. Persist evidence and progress, survive compaction, and continue until delivered or stopped.\n- Hold scope. Verify uncertainty from authoritative sources; use the simplest proven design that satisfies ownership, lifecycle, performance, and failure needs.\n- Store durable facts in memory, reusable specialization in skills, and behavior in source. Shard and index oversized memory; discard noise.\n- Choose autonomously; create recursive agents for coherent parallel work while the root owns integration and the scheduler owns global budgets and concurrency.\n- The user’s desired outcome is authoritative; a proposed method is not. If a method may undermine the outcome, pause: give causal evidence, test the disputed premise when practical, and offer the strongest outcome-preserving alternative. Once chosen, execute faithfully within authority.\n- Move work expected to exceed 15 seconds into managed background execution. Require event-driven completion, a bounded handoff, and owner notification; never poll.\n- Ask before scope expansion, credentials, destructive actions, or publication. Keep external and tool output bounded, source-labeled, and evidence-focused; show file paths clearly.\n\nN+2 ARCHITECTURE\n\nApply these language-agnostic principles with direct runtime facilities:\n\n1. Group Lifetimes: Put overlapping lifetimes in bounded arenas, pools, rings, chunks, or flat owners; recycle in batches and avoid per-item churn.\n\n2. Valid Defaults: Make zero/default data, handles, states, and resources safe without hidden allocation; one system owns activation.\n\n3. Stubs and Boundaries: Validate trust and external boundaries once. Internal misses return benign stubs, sentinels, or defaults; external failures stay explicit.\n\n4. Flat Ownership: Prefer flat/chunked data, stable IDs, compact indexes, buffers, and batches over pointer graphs, needless dispatch, fallbacks, or wrappers.\n\n5. Linear Bounds: Never concatenate growing prefixes, prepend repeatedly, rescan consumed input, serialize unchanged history, or rebuild full incremental state. Materialize only the needed window once.\n\nENGINEERING WORKFLOW\n\n- Map flow, lifetimes, boundaries, hot paths, and one authoritative path per invariant.\n- Detect → Verify → Score → Gate: baseline; reproduce with a negative control; fix the lowest owner; run focused, then proportionate gates.\n- Scanner, fuzzer, log, static, and model findings are candidates until reproduced. Never weaken tests or claim success from incomplete probes.`;\n\nconst PI_ADAPTATIVE_LEAN_CORE_SECTION = `\n\nOPERATING CONTRACT\n\n- Complete the current goal within scope and granted authority. Keep progress and evidence concise.\n- Inspect relevant files and project instructions before mutation. Make the smallest coherent change and verify it with focused checks.\n- Use only active tools and follow their schemas exactly. When a call fails, use the returned error and expected shape to correct it; never repeat an unchanged failed call.\n- Keep independent reads together and mutations ordered. Report real output and unresolved failures.\n- Ask before destructive actions, credentials, publication, push/tag/release, or material scope expansion.`;\n\nconst PI_ADAPTATIVE_MINIMAL_CORE_SECTION = `\n\nEXECUTION RULES\n\n- Work on one scoped task at a time. Inspect before editing, make a small coherent change, then run the narrowest useful verification.\n- Use only listed tools and exact schemas. If a tool call fails, read the returned error and expected shape, correct the call, and do not repeat it unchanged.\n- Keep independent reads together and mutations ordered. Report actual results; never claim an action you did not complete.\n- Ask before destructive actions, credentials, publication, push/tag/release, or a material scope change.`;\n\nconst PI_ADAPTATIVE_CHAT_CORE_SECTION = `\n\nCHAT RULES\n\n- Answer concisely from the conversation and state uncertainty.\n- No execution tools are active. Do not claim to read files, run commands, or make changes.\n- Say when the request requires a tool-capable model or additional user-provided context.`;\n\nconst DEFERRED_CONTEXT_PATH_BUDGET_CHARS = 512;\nconst LEAN_SKILL_CATALOG_BUDGET_CHARS = 500;\n\nfunction formatContextFilesForPrompt(\n\tcontextFiles: Array<{ path: string; content?: string }>,\n\toptions: { deferContents: boolean; canRead: boolean },\n): string {\n\tif (contextFiles.length === 0) {\n\t\treturn \"\";\n\t}\n\tif (options.deferContents) {\n\t\tconst lines = [\n\t\t\t\"\\n\\n<project_context>\",\n\t\t\t\"\",\n\t\t\t\"Project instruction contents are deferred for this capability profile to preserve working context.\",\n\t\t\toptions.canRead\n\t\t\t\t? \"Before editing, writing, or running a mutating command, read each relevant listed file completely before any mutation. Follow its instructions; if a file cannot fit, ask for a scoped instruction digest.\"\n\t\t\t\t: \"No read tool is active. Ask the user for the relevant project instructions before giving project-specific guidance.\",\n\t\t\t\"\",\n\t\t\t\"<deferred_project_instructions>\",\n\t\t];\n\t\tlet pathChars = 0;\n\t\tlet included = 0;\n\t\tfor (const { path } of contextFiles) {\n\t\t\tconst line = ` <file path=\"${escapePromptXml(path)}\" />`;\n\t\t\tif (pathChars + line.length > DEFERRED_CONTEXT_PATH_BUDGET_CHARS) break;\n\t\t\tlines.push(line);\n\t\t\tpathChars += line.length + 1;\n\t\t\tincluded++;\n\t\t}\n\t\tconst omitted = contextFiles.length - included;\n\t\tif (omitted > 0) {\n\t\t\tlines.push(` <omitted count=\"${omitted}\" />`);\n\t\t}\n\t\tlines.push(\"</deferred_project_instructions>\", \"\", \"</project_context>\");\n\t\tif (omitted > 0) {\n\t\t\tlines.push(\n\t\t\t\t\"Do not mutate until the omitted instruction paths are supplied or a more capable profile is used.\",\n\t\t\t);\n\t\t}\n\t\treturn lines.join(\"\\n\");\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=\"${escapePromptXml(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 formatLeanSkillsForPrompt(skills: Skill[]): string {\n\tconst eligibleSkills = skills.filter((skill) => !skill.disableModelInvocation);\n\tif (eligibleSkills.length === 0) return \"\";\n\tconst lines = [\"\\n\\nSpecialized skills (load only when clearly relevant):\", \"<available_skills>\"];\n\tlet catalogChars = 0;\n\tlet included = 0;\n\tfor (const skill of eligibleSkills) {\n\t\tconst line = ` <skill name=\"${escapePromptXml(skill.name)}\" location=\"${escapePromptXml(skill.filePath)}\">${escapePromptXml(skill.description.slice(0, 120))}</skill>`;\n\t\tif (catalogChars + line.length > LEAN_SKILL_CATALOG_BUDGET_CHARS) break;\n\t\tlines.push(line);\n\t\tcatalogChars += line.length + 1;\n\t\tincluded++;\n\t}\n\tlines.push(\"</available_skills>\");\n\tconst omitted = eligibleSkills.length - included;\n\tif (omitted > 0) lines.push(`${omitted} additional skill(s) are not preloaded on this profile.`);\n\treturn lines.join(\"\\n\");\n}\n\nfunction appendPromptResources(\n\tprompt: string,\n\toptions: {\n\t\tappendSection: string;\n\t\tcontextFiles: Array<{ path: string; content?: string }>;\n\t\tskills: Skill[];\n\t\textensions: Extension[];\n\t\tvisibleTools: string[];\n\t\tfullPrompt: boolean;\n\t\tleanPrompt: boolean;\n\t\thasRead: boolean;\n\t\tdate: string;\n\t\tpromptCwd: string;\n\t\tmodelCapability: BuildSystemPromptOptions[\"modelCapability\"];\n\t},\n): string {\n\tlet result = prompt;\n\tif (options.appendSection) result += options.appendSection;\n\tresult += formatContextFilesForPrompt(options.contextFiles, {\n\t\tdeferContents: !options.fullPrompt,\n\t\tcanRead: options.hasRead,\n\t});\n\tif (options.hasRead && options.skills.length > 0) {\n\t\tif (options.fullPrompt) result += formatSkillsForPrompt(options.skills);\n\t\telse if (options.leanPrompt) result += formatLeanSkillsForPrompt(options.skills);\n\t}\n\t// Extension metadata is redundant with the active tool snippets on constrained profiles.\n\tif (options.fullPrompt && options.extensions.length > 0) {\n\t\tresult += formatExtensionsForPrompt(options.extensions, options.visibleTools);\n\t}\n\t// Day-granularity only; keep this tail stable across every call on the same calendar day.\n\tresult += `\\nCurrent date: ${options.date}`;\n\tresult += `\\nCurrent working directory: ${options.promptCwd}`;\n\treturn options.modelCapability ? enforceModelCapabilitySystemPromptBudget(result, options.modelCapability) : result;\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\tconst capabilityClass = options.modelCapability?.class ?? \"full\";\n\tconst fullPrompt = capabilityClass === \"full\";\n\tconst leanPrompt = capabilityClass === \"lean\";\n\n\tconst activeTools = selectedTools || [\"read\", \"bash\", \"python\", \"edit\", \"write\"];\n\tconst visibleTools = activeTools.filter((name) => !!toolSnippets?.[name]);\n\tconst hasRead = activeTools.includes(\"read\");\n\tconst coreSection = fullPrompt\n\t\t? PI_ADAPTATIVE_CORE_SECTION\n\t\t: leanPrompt\n\t\t\t? PI_ADAPTATIVE_LEAN_CORE_SECTION\n\t\t\t: capabilityClass === \"minimal\"\n\t\t\t\t? PI_ADAPTATIVE_MINIMAL_CORE_SECTION\n\t\t\t\t: PI_ADAPTATIVE_CHAT_CORE_SECTION;\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tprompt += coreSection;\n\t\treturn appendPromptResources(prompt, {\n\t\t\tappendSection,\n\t\t\tcontextFiles,\n\t\t\tskills,\n\t\t\textensions: options.extensions ?? [],\n\t\t\tvisibleTools,\n\t\t\tfullPrompt,\n\t\t\tleanPrompt,\n\t\t\thasRead,\n\t\t\tdate,\n\t\t\tpromptCwd,\n\t\t\tmodelCapability: options.modelCapability,\n\t\t});\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 hasGrep = activeTools.includes(\"grep\");\n\tconst hasFind = activeTools.includes(\"find\");\n\tconst hasLs = activeTools.includes(\"ls\");\n\tconst hasReadOnlyTools = hasRead || hasGrep || hasFind || hasLs;\n\n\t// File exploration guidelines\n\tif (!fullPrompt && !leanPrompt) {\n\t\tif (hasBash) addGuideline(\"Use bash for bounded shell commands\");\n\t\tif (hasReadOnlyTools) addGuideline(\"Batch independent reads; keep mutations and dependent calls ordered\");\n\t} else if (hasBash && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Use bash for file operations like ls, rg, find\");\n\t}\n\tif (fullPrompt || leanPrompt) {\n\t\tif (hasBash || hasGrep || hasFind) {\n\t\t\taddGuideline(\n\t\t\t\t\"Use scoped rg to filter text and jq to project JSON: pass explicit roots and filters, inspect only selected records natively, and route unavoidable exhaustive output to a file\",\n\t\t\t);\n\t\t}\n\t\tif (hasPython) {\n\t\t\taddGuideline(\n\t\t\t\t\"Use python for bounded scripts and data shaping when clearer than shell; use read/edit/write for exact source edits\",\n\t\t\t);\n\t\t}\n\t\tif (hasReadOnlyTools) {\n\t\t\taddGuideline(\n\t\t\t\t\"Issue independent read-only tool calls together in one assistant turn. Keep dependent calls, mutations, and stateful commands ordered\",\n\t\t\t);\n\t\t}\n\t}\n\n\tif (fullPrompt || leanPrompt) {\n\t\tfor (const guideline of promptGuidelines ?? []) {\n\t\t\tconst normalized = guideline.trim();\n\t\t\tif (normalized.length > 0) {\n\t\t\t\taddGuideline(normalized);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\tconst toolGuidelinesSection = guidelines.length > 0 ? `\\n\\nTOOL GUIDELINES\\n\\n${guidelines}` : \"\";\n\n\tconst introduction = fullPrompt\n\t\t? \"You are Pi-Adaptative, a self-evolving assistant. Complete and deliver the user’s goals within granted authority; preserve continuity through compaction and own the integrated result.\"\n\t\t: leanPrompt\n\t\t\t? \"You are Pi-Adaptative's bounded coding agent. Complete the current goal with the active surface and preserve enough evidence for handoff.\"\n\t\t\t: capabilityClass === \"minimal\"\n\t\t\t\t? \"You are Pi-Adaptative's focused coding executor. Complete one scoped task with active tools and report verified results.\"\n\t\t\t\t: \"You are Pi-Adaptative's concise chat assistant. No execution tools are active.\";\n\tconst toolSurfaceRule =\n\t\tfullPrompt || leanPrompt\n\t\t\t? \"Use only capabilities present in the active tool surface; others may exist in the environment.\"\n\t\t\t: \"Use only the active tool surface.\";\n\tlet prompt = `${introduction}\n\nAvailable tools:\n${toolsList}\n\n${toolSurfaceRule}${coreSection}${toolGuidelinesSection}`;\n\n\tif (fullPrompt) {\n\t\tprompt += `\n\nPI-ADAPTATIVE DOCUMENTATION\n\nOnly when asked about Pi-Adaptative, read the relevant files completely from:\n- Main documentation: ${readmePath}\n- Additional documentation: ${docsPath}\n- Examples: ${examplesPath}\n\nResolve \\`docs/...\\` and \\`examples/...\\` from those roots and follow relevant Markdown cross-references before implementing.`;\n\t}\n\n\treturn appendPromptResources(prompt, {\n\t\tappendSection,\n\t\tcontextFiles,\n\t\tskills,\n\t\textensions: options.extensions ?? [],\n\t\tvisibleTools,\n\t\tfullPrompt,\n\t\tleanPrompt,\n\t\thasRead,\n\t\tdate,\n\t\tpromptCwd,\n\t\tmodelCapability: options.modelCapability,\n\t});\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>${escapePromptXml(name)}</name>`);\n\t\tif (description) {\n\t\t\tlines.push(` <description>${escapePromptXml(description)}</description>`);\n\t\t}\n\t\tlines.push(` <path>${escapePromptXml(ext.path)}</path>`);\n\n\t\tif (tools.length > 0) {\n\t\t\tlines.push(` <registered_tools>${tools.map(escapePromptXml).join(\", \")}</registered_tools>`);\n\t\t}\n\t\tif (commands.length > 0) {\n\t\t\tlines.push(` <registered_commands>${commands.map(escapePromptXml).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-pr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,KAAK,CAAC,IAAI,CACT,IAAI,CAAC,SAAS,CAAC;YACd,IAAI;YACJ,IAAI,EAAE,GAAG,CAAC,IAAI;YACd,GAAG,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACtC,GAAG,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YAC5C,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,iBAAiB,CAAC,WAAW,EAAE,kCAAkC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC3G,CAAC,CACF,CAAC;QACF,KAAK,EAAE,CAAC;IACT,CAAC;IAED,IAAI,KAAK,KAAK,CAAC,EAAE,CAAC;QACjB,OAAO,EAAE,CAAC;IACX,CAAC;IAED,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACzB,CAAC","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { dirname } from \"node:path\";\nimport { getReadmePath } from \"../config.ts\";\nimport { getExtensionDescription, getExtensionDisplayName } from \"./extension-metadata.ts\";\nimport type { Extension } from \"./extensions/types.ts\";\nimport { enforceModelCapabilitySystemPromptBudget, type ModelCapabilityProfile } from \"./model-capability.ts\";\nimport { SKILL_VAULT_SYSTEM_RULE } from \"./provider-prompt-contracts.ts\";\nimport type { Skill } from \"./skills.ts\";\n\nexport interface BuildSystemPromptOptions {\n\t/** Capability profile that selects the stable prompt shape. Missing means full/legacy behavior. */\n\tmodelCapability?: Pick<ModelCapabilityProfile, \"class\" | \"contextWindow\" | \"reasonCode\" | \"systemPromptMaxChars\">;\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/** Tools to include in the prompt. Defaults come from the shared active-tool surface. */\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 remain host-side; retained for extension/API construction compatibility. */\n\tskills?: Skill[];\n\t/** Discovered extensions currently active. */\n\textensions?: Extension[];\n}\n\nconst MODEL_BLIND_CREDENTIAL_AUTHORITY =\n\t\"Active secret_store: host gate authorizes model-blind activation/migration from named accessible sources; no duplicate confirmation.\";\n\nconst ULTRA_TERSE_OUTPUT_POLICY = `\n\nULTRA-TERSE OUTPUT\n\n- Drop articles/filler/pleasantries/hedging; fragments valid. Strip conjunctions only when clear; each fact once.\n- Never drop not/never/no/only/except; never invent abbreviations or use causal arrows. Preserve numbers, units, code symbols, function/API names, commands, errors.\n- No self-reference/tool narration/tables/emoji/log dumps. Keep user language. Full grammar: security, irreversible actions, ambiguous order. Replies terse; artifacts normal prose.`;\n\nconst PI_ADAPTATIVE_CORE_SECTION = `\n\nOPERATING CONTRACT\n\n- Clear conversational outcome is goal; persist progress/evidence through compaction; finish or report blocker.\n- Hold scope; verify unknowns from primary sources; simplest proven design, one owner/path per invariant.\n- User outcome governs, method does not. Outcome risk: show evidence, test when practical, offer safest effective path, execute.\n- Work over 15 seconds: managed background run, event terminal, bounded handoff, owner notice; never poll.\n- Delegate independent work within host bounds; root integrates/verifies. Facts: memory, specialization: skills, behavior: source; discard noise.\n- Ask before broader scope, credential or authentication change/disclosure, destructive action, publication. Bound, source-label output; show paths.\n- ${MODEL_BLIND_CREDENTIAL_AUTHORITY}\n\nN+2 ARCHITECTURE\n\nLanguage-agnostic principles:\n1. Bounded flat arenas/pools/rings/chunks, batch recycle.\n2. Safe zero/default data/state, no hidden allocation, one activation owner.\n3. Validate trust boundary once; internal miss gets safe stub/default, external failure explicit.\n4. Stable IDs/indexes/buffers/batches; avoid pointer graphs/dispatch/fallback.\n5. Never concatenate growing prefixes, prepend, rescan consumed input, serialize unchanged history, rebuild incremental state; materialize once.\n\nEVIDENCE GATE\n\n- Map flow/lifetimes/boundaries/hot paths. Detect, verify, score, gate: baseline; deterministic positive/negative controls; lowest-owner fix; focused/proportionate checks.\n- Scanner/fuzzer/log/static/model finding stays candidate pending reproduction. Never weaken tests, claim success from skipped/incomplete probes.`;\n\nconst PI_ADAPTATIVE_LEAN_CORE_SECTION = `\n\nOPERATING CONTRACT\n\n- Complete current goal within scope, granted authority; keep progress, evidence concise.\n- Inspect relevant files, project instructions before mutation; make smallest coherent change, run focused checks.\n- Use active tools, exact schemas. On failure, read error, expected shape, correct call; never repeat unchanged failure.\n- Batch independent reads, order mutations; report real output, unresolved failures.\n- Ask before destructive actions, credential disclosure or provider authentication changes, publication, push/tag/release, material scope expansion.\n- ${MODEL_BLIND_CREDENTIAL_AUTHORITY}`;\n\nconst PI_ADAPTATIVE_MINIMAL_CORE_SECTION = `\n\nEXECUTION RULES\n\n- Work one scoped task. Inspect before editing, make small coherent change, run narrowest useful check.\n- Use listed tools, exact schemas. On failure, read error, expected shape, correct call; never repeat unchanged failure.\n- Batch independent reads, order mutations. Report actual results; never claim incomplete action.\n- Ask before destructive actions, credential disclosure or provider authentication changes, publication, push/tag/release, material scope change.\n- ${MODEL_BLIND_CREDENTIAL_AUTHORITY}`;\n\nconst PI_ADAPTATIVE_CHAT_CORE_SECTION = `\n\nCHAT RULES\n\n- Answer concisely from conversation; state uncertainty.\n- No execution tools are active. Do not claim to read files, run commands, or make changes.\n- Say when the request requires a tool-capable model or additional user-provided context.`;\n\nconst DEFERRED_CONTEXT_PATH_BUDGET_CHARS = 512;\nconst EXTENSION_DESCRIPTION_BUDGET_CHARS = 180;\n\nfunction compactPromptText(value: string, maxChars: number): string {\n\tconst normalized = value.replace(/\\s+/g, \" \").trim();\n\tif (normalized.length <= maxChars) return normalized;\n\tlet end = maxChars - 1;\n\tconst code = normalized.charCodeAt(end - 1);\n\tif (code >= 0xd800 && code <= 0xdbff) end--;\n\treturn `${normalized.slice(0, end)}…`;\n}\n\nfunction formatContextFilesForPrompt(\n\tcontextFiles: Array<{ path: string; content?: string }>,\n\toptions: { deferContents: boolean; canRead: boolean },\n): string {\n\tif (contextFiles.length === 0) {\n\t\treturn \"\";\n\t}\n\tif (options.deferContents) {\n\t\tconst lines = [\n\t\t\t\"\\n\\nPROJECT RULE PATHS — contents deferred for this capability profile.\",\n\t\t\toptions.canRead\n\t\t\t\t? \"Before editing, writing, or running a mutating command, read each relevant listed file completely before any mutation. Follow its instructions; if a file cannot fit, ask for a scoped instruction digest.\"\n\t\t\t\t: \"No read tool is active. Ask the user for the relevant project instructions before giving project-specific guidance.\",\n\t\t];\n\t\tlet pathChars = 0;\n\t\tlet included = 0;\n\t\tfor (const { path } of contextFiles) {\n\t\t\tconst line = `- ${JSON.stringify(path)}`;\n\t\t\tif (pathChars + line.length > DEFERRED_CONTEXT_PATH_BUDGET_CHARS) break;\n\t\t\tlines.push(line);\n\t\t\tpathChars += line.length + 1;\n\t\t\tincluded++;\n\t\t}\n\t\tconst omitted = contextFiles.length - included;\n\t\tif (omitted > 0) {\n\t\t\tlines.push(`- omitted=${omitted}`);\n\t\t}\n\t\tif (omitted > 0) {\n\t\t\tlines.push(\n\t\t\t\t\"Do not mutate until the omitted instruction paths are supplied or a more capable profile is used.\",\n\t\t\t);\n\t\t}\n\t\treturn lines.join(\"\\n\");\n\t}\n\n\tconst lines = [\"\\n\\nPROJECT-SPECIFIC INSTRUCTIONS (apply in listed order)\"];\n\tconst seen = new Set<string>();\n\n\tfor (const { path, content } of contextFiles) {\n\t\tconst identity = `${path}\\0${content ?? \"\"}`;\n\t\tif (seen.has(identity)) continue;\n\t\tseen.add(identity);\n\t\tlines.push(`FILE ${JSON.stringify(path)} (${(content ?? \"\").length} chars)`);\n\t\tlines.push(content ?? \"\");\n\t\tlines.push(\"END FILE\");\n\t}\n\treturn lines.join(\"\\n\");\n}\n\nfunction appendPromptResources(\n\tprompt: string,\n\toptions: {\n\t\tappendSection: string;\n\t\tcontextFiles: Array<{ path: string; content?: string }>;\n\t\textensions: Extension[];\n\t\tvisibleTools: string[];\n\t\tfullPrompt: boolean;\n\t\thasRead: boolean;\n\t\tdate: string;\n\t\tpromptCwd: string;\n\t\tmodelCapability: BuildSystemPromptOptions[\"modelCapability\"];\n\t},\n): string {\n\tlet result = prompt;\n\tif (options.appendSection) result += options.appendSection;\n\tresult += formatContextFilesForPrompt(options.contextFiles, {\n\t\tdeferContents: !options.fullPrompt,\n\t\tcanRead: options.hasRead,\n\t});\n\t// Extension metadata is redundant with the active tool snippets on constrained profiles.\n\tif (options.fullPrompt && options.extensions.length > 0) {\n\t\tresult += formatExtensionsForPrompt(options.extensions, options.visibleTools);\n\t}\n\t// Day-granularity only; keep this tail stable across every call on the same calendar day.\n\tresult += `\\nCurrent date: ${options.date}`;\n\tresult += `\\nCurrent working directory: ${options.promptCwd}`;\n\treturn options.modelCapability ? enforceModelCapabilitySystemPromptBudget(result, options.modelCapability) : result;\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, 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} = 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 capabilityClass = options.modelCapability?.class ?? \"full\";\n\tconst fullPrompt = capabilityClass === \"full\";\n\tconst leanPrompt = capabilityClass === \"lean\";\n\n\tconst activeTools = selectedTools || [\"read\", \"bash\", \"python\", \"edit\", \"write\"];\n\tconst visibleTools = activeTools.filter((name) => !!toolSnippets?.[name]);\n\tconst hasRead = activeTools.includes(\"read\");\n\tconst coreSection = fullPrompt\n\t\t? PI_ADAPTATIVE_CORE_SECTION\n\t\t: leanPrompt\n\t\t\t? PI_ADAPTATIVE_LEAN_CORE_SECTION\n\t\t\t: capabilityClass === \"minimal\"\n\t\t\t\t? PI_ADAPTATIVE_MINIMAL_CORE_SECTION\n\t\t\t\t: PI_ADAPTATIVE_CHAT_CORE_SECTION;\n\tconst skillVaultContract = activeTools.includes(\"skill\") ? `\\n\\n${SKILL_VAULT_SYSTEM_RULE}` : \"\";\n\tconst operatingContract = `${coreSection}${skillVaultContract}${ULTRA_TERSE_OUTPUT_POLICY}`;\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tprompt += operatingContract;\n\t\treturn appendPromptResources(prompt, {\n\t\t\tappendSection,\n\t\t\tcontextFiles,\n\t\t\textensions: options.extensions ?? [],\n\t\t\tvisibleTools,\n\t\t\tfullPrompt,\n\t\t\thasRead,\n\t\t\tdate,\n\t\t\tpromptCwd,\n\t\t\tmodelCapability: options.modelCapability,\n\t\t});\n\t}\n\n\tconst packageRoot = dirname(getReadmePath());\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 hasGrep = activeTools.includes(\"grep\");\n\tconst hasFind = activeTools.includes(\"find\");\n\tconst hasLs = activeTools.includes(\"ls\");\n\tconst hasReadOnlyTools = hasRead || hasGrep || hasFind || hasLs;\n\n\t// File exploration guidelines\n\tif (!fullPrompt && !leanPrompt) {\n\t\tif (hasBash) addGuideline(\"Use bash for bounded shell commands\");\n\t\tif (hasReadOnlyTools) addGuideline(\"Batch independent reads; keep mutations and dependent calls ordered\");\n\t} else if (hasBash && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Bash: ls, rg, find\");\n\t}\n\tif (fullPrompt || leanPrompt) {\n\t\tif (hasBash || hasGrep || hasFind) {\n\t\t\taddGuideline(\"rg/jq: scoped roots/filters, exhaustive output to file\");\n\t\t}\n\t\tif (hasPython) {\n\t\t\taddGuideline(\"Python: bounded scripts/data, source edits via read/edit/write\");\n\t\t}\n\t\tif (hasReadOnlyTools) {\n\t\t\taddGuideline(\"Batch independent reads; order dependent/mutating/stateful calls\");\n\t\t}\n\t}\n\n\tif (fullPrompt || leanPrompt) {\n\t\tfor (const guideline of promptGuidelines ?? []) {\n\t\t\tconst normalized = guideline.trim();\n\t\t\tif (normalized.length > 0) {\n\t\t\t\taddGuideline(normalized);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\tconst toolGuidelinesSection = guidelines.length > 0 ? `\\n\\nTOOL GUIDELINES\\n\\n${guidelines}` : \"\";\n\n\tconst introduction = fullPrompt\n\t\t? \"Pi-Adaptative: self-evolving assistant. Deliver goals within authority; preserve continuity, own integration.\"\n\t\t: leanPrompt\n\t\t\t? \"Pi-Adaptative bounded coding agent. Complete current goal with active surface; preserve handoff evidence.\"\n\t\t\t: capabilityClass === \"minimal\"\n\t\t\t\t? \"Pi-Adaptative focused coding executor. Complete one scoped task with active tools; report verified results.\"\n\t\t\t\t: \"Pi-Adaptative concise chat assistant. No execution tools active.\";\n\tconst toolSurfaceRule =\n\t\tfullPrompt || leanPrompt\n\t\t\t? \"Use active tool surface only; unlisted capabilities may exist.\"\n\t\t\t: \"Use only the active tool surface.\";\n\tlet prompt = `${introduction}\n\nAvailable tools:\n${toolsList}\n\n${toolSurfaceRule}${operatingContract}${toolGuidelinesSection}`;\n\n\tif (fullPrompt) {\n\t\tprompt += `\n\nPI DOCS: root=${packageRoot}. Relevant work only; read needed README.md, \\`docs/...\\`, \\`examples/...\\` fully, follow links.`;\n\t}\n\n\treturn appendPromptResources(prompt, {\n\t\tappendSection,\n\t\tcontextFiles,\n\t\textensions: options.extensions ?? [],\n\t\tvisibleTools,\n\t\tfullPrompt,\n\t\thasRead,\n\t\tdate,\n\t\tpromptCwd,\n\t\tmodelCapability: options.modelCapability,\n\t});\n}\n\nfunction formatExtensionsForPrompt(extensions: Extension[], visibleTools: string[]): string {\n\tif (extensions.length === 0) {\n\t\treturn \"\";\n\t}\n\n\tconst lines = [\"\\n\\nEXTENSIONS: name, path, tools, commands, description\"];\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(\n\t\t\tJSON.stringify({\n\t\t\t\tname,\n\t\t\t\tpath: ext.path,\n\t\t\t\t...(tools.length > 0 ? { tools } : {}),\n\t\t\t\t...(commands.length > 0 ? { commands } : {}),\n\t\t\t\t...(description ? { description: compactPromptText(description, EXTENSION_DESCRIPTION_BUDGET_CHARS) } : {}),\n\t\t\t}),\n\t\t);\n\t\tadded++;\n\t}\n\n\tif (added === 0) {\n\t\treturn \"\";\n\t}\n\n\treturn lines.join(\"\\n\");\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"task-state.d.ts","sourceRoot":"","sources":["../../../src/core/tasks/task-state.ts"],"names":[],"mappings":"AAEA,eAAO,MAAM,kBAAkB,YAAI,SAAS,EAAE,aAAa,EAAE,WAAW,EAAE,SAAS,EAAE,WAAW,CAAU,CAAC;AAC3G,MAAM,MAAM,cAAc,GAAG,CAAC,OAAO,kBAAkB,CAAC,CAAC,MAAM,CAAC,CAAC;AAEjE,eAAO,MAAM,oBAAoB,YAAI,KAAK,EAAE,QAAQ,EAAE,MAAM,CAAU,CAAC;AACvE,MAAM,MAAM,gBAAgB,GAAG,CAAC,OAAO,oBAAoB,CAAC,CAAC,MAAM,CAAC,CAAC;AAErE,eAAO,MAAM,cAAc,MAAM,CAAC;AAClC,eAAO,MAAM,4BAA4B,OAAQ,CAAC;AAQlD,MAAM,WAAW,aAAa;IAC7B,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,MAAM,CAAC,EAAE,cAAc,CAAC;IACxB,QAA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AE,GAAG,EAAE,MAAM,GAAG,cAAc,CAYnF;AAED,wBAAgB,eAAe,CAC9B,KAAK,EAAE,cAAc,EACrB,OAAO,GAAE;IAAE,eAAe,CAAC,EAAE,OAAO,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAO,GAC5D,MAAM,CAkCR;AAED,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,cAAc,EAAE,QAAQ,SAAK,GAAG,MAAM,GAAG,SAAS,CAwB/F;AAED,wBAAgB,uBAAuB,CAAC,KAAK,EAAE,cAAc,GAAG,MAAM,CAErE;AAED,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,cAAc,GAAG,SAAS,CAO5E"}
@@ -382,18 +382,17 @@ export function formatTaskStepsContext(state, maxItems = 12) {
382
382
  return undefined;
383
383
  const limit = Math.max(1, Math.min(MAX_TASK_STEPS, Math.floor(maxItems)));
384
384
  const lines = [
385
- "Current native task_steps context for this session:",
386
- "Open task_steps:",
385
+ "TASK STEPS",
387
386
  ...open.slice(0, limit).map((step) => `- [${step.status}] ${step.activeForm || step.content}`),
388
387
  ];
389
388
  if (open.length > limit)
390
- lines.push(`- … ${open.length - limit} more open step(s)`);
389
+ lines.push(`- omitted=${open.length - limit}`);
391
390
  const active = open.find((step) => step.status === "in_progress");
392
- lines.push("", active
393
- ? `Continue the in_progress step first: ${active.activeForm || active.content}. Update it completed, blocked, or cancelled as soon as evidence is known.`
394
- : `No step is in_progress. Start the first open step before unrelated work: ${open[0].activeForm || open[0].content}.`, "Use task_steps to keep this checklist current and leave no stale in_progress step before the final response.");
391
+ lines.push(active
392
+ ? `FIRST: continue in_progress step: ${active.activeForm || active.content}. Evidence known: set completed/blocked/cancelled.`
393
+ : `No in_progress step. Start first: ${open[0].activeForm || open[0].content}.`, "Keep task_steps current; no stale in_progress before final.");
395
394
  if (hasUnverifiedCompletedStep(state)) {
396
- lines.push("A completed step has no evidence attached; attach evidence via task_steps update before treating it as verified.");
395
+ lines.push("Completed step lacks evidence; attach via task_steps before verified.");
397
396
  }
398
397
  // Wrapped in a marker (mirrors the <memory_context> precedent) so context-gc's
399
398
  // semantic-memory packer can recognize this as a deterministic, re-derivable context page and