@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 +1 @@
1
- {"version":3,"file":"session-role.js","sourceRoot":"","sources":["../../src/core/session-role.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,uBAAuB,CAAC;AACrD,OAAO,EAAE,uBAAuB,EAAE,MAAM,4BAA4B,CAAC;AAKrE,MAAM,CAAC,MAAM,mBAAmB,GAAG,iBAAiB,CAAC;AAErD,MAAM,UAAU,qBAAqB,CAAC,KAAa;IAClD,OAAO,KAAK,KAAK,MAAM,IAAI,KAAK,KAAK,QAAQ,CAAC;AAC/C,CAAC;AAED,kGAAkG;AAClG,MAAM,UAAU,sBAAsB,CAAC,IAAyB,EAAE,GAAG,GAAsB,OAAO,CAAC,GAAG;IACrG,IAAI,IAAI,KAAK,QAAQ,EAAE,CAAC;QACvB,GAAG,CAAC,mBAAmB,CAAC,GAAG,QAAQ,CAAC;IACrC,CAAC;SAAM,IAAI,GAAG,CAAC,mBAAmB,CAAC,KAAK,QAAQ,EAAE,CAAC;QAClD,GAAG,CAAC,mBAAmB,CAAC,GAAG,MAAM,CAAC;IACnC,CAAC;AACF,CAAC;AAED,0FAA0F;AAC1F,MAAM,UAAU,cAAc,CAAC,GAAG,GAAsB,OAAO,CAAC,GAAG;IAClE,IAAI,GAAG,CAAC,mBAAmB,CAAC,KAAK,QAAQ;QAAE,OAAO,QAAQ,CAAC;IAC3D,IAAI,YAAY,CAAC,GAAG,CAAC,KAAK,SAAS;QAAE,OAAO,QAAQ,CAAC;IACrD,IAAI,uBAAuB,CAAC,GAAG,CAAC,KAAK,SAAS;QAAE,OAAO,QAAQ,CAAC;IAChE,OAAO,MAAM,CAAC;AACf,CAAC;AAED,qFAAqF;AACrF,MAAM,UAAU,eAAe,CAAC,GAAG,GAAsB,OAAO,CAAC,GAAG;IACnE,OAAO,cAAc,CAAC,GAAG,CAAC,KAAK,QAAQ,CAAC;AACzC,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,sBAAsB,GAAwB,IAAI,GAAG,CAAC;IAClE,MAAM;IACN,cAAc;IACd,cAAc;IACd,UAAU;IACV,iBAAiB;IACjB,gBAAgB;IAChB,kBAAkB;IAClB,cAAc;IACd,UAAU;IACV,oBAAoB;IACpB,eAAe;IACf,oBAAoB;IACpB,eAAe;IACf,QAAQ;CACR,CAAC,CAAC","sourcesContent":["/**\n * Session-role identity: distinguishes a MAIN session (an interactive/direct `pi` session) from a\n * WORKER session (lane-bound or explicitly dispatched) — the seam every worker-scoped UAC ceiling\n * and zero-footprint store gates on (see runtime-builder.ts's `isAllowedTool`, the worktree_sync\n * tool's worker scoping, and the read-only store options threaded through the persistence layer).\n *\n * A session is a worker iff EITHER:\n * - `PI_SESSION_ROLE=worker` is set (an explicit launcher declaration),\n * - a valid `PI_PARENT_PID` declares this process as a managed child, or\n * - it is bound to a worktree-sync lane (`PI_WORKTREE_LANE`; see worktree-sync/runtime.ts) — a\n * lane-bound session is a worker by construction, regardless of how it was launched.\n *\n * `PI_SESSION_ROLE=main` is deliberately NOT an escalation: it can never override a bound lane.\n * There is no environment value a lane-bound process can set to shed the worker ceiling — the env\n * var is additive evidence for \"worker\", never a downgrade signal.\n */\n\nimport { getParentPid } from \"./process-identity.ts\";\nimport { getBoundWorktreeLaneKey } from \"./worktree-sync/runtime.ts\";\n\nexport type SessionRole = \"main\" | \"worker\";\nexport type TerminalSessionMode = \"user\" | \"worker\";\n\nexport const PI_SESSION_ROLE_ENV = \"PI_SESSION_ROLE\";\n\nexport function isTerminalSessionMode(value: string): value is TerminalSessionMode {\n\treturn value === \"user\" || value === \"worker\";\n}\n\n/** Apply the terminal audience declaration without bypassing worker inference or UAC ceilings. */\nexport function setTerminalSessionMode(mode: TerminalSessionMode, env: NodeJS.ProcessEnv = process.env): void {\n\tif (mode === \"worker\") {\n\t\tenv[PI_SESSION_ROLE_ENV] = \"worker\";\n\t} else if (env[PI_SESSION_ROLE_ENV] !== \"worker\") {\n\t\tenv[PI_SESSION_ROLE_ENV] = \"main\";\n\t}\n}\n\n/** Derive this process's session role from the environment (env-injectable for tests). */\nexport function getSessionRole(env: NodeJS.ProcessEnv = process.env): SessionRole {\n\tif (env[PI_SESSION_ROLE_ENV] === \"worker\") return \"worker\";\n\tif (getParentPid(env) !== undefined) return \"worker\";\n\tif (getBoundWorktreeLaneKey(env) !== undefined) return \"worker\";\n\treturn \"main\";\n}\n\n/** True iff this process is a worker session (lane-bound or explicitly declared). */\nexport function isWorkerSession(env: NodeJS.ProcessEnv = process.env): boolean {\n\treturn getSessionRole(env) === \"worker\";\n}\n\n/**\n * Tools a worker session may never activate: the orchestration/self-adaptation surface that would\n * let a worker spawn its own sub-orchestration, bypass its parent to request owner input, mutate\n * settings-driven learning/model state, or shell out to the unbounded `python` execution contract.\n * `python` is load-bearing for the zero-footprint guarantee (it can write anywhere the interpreter\n * can reach); `context_scout` is\n * sub-orchestration (spawns its own isolated agent loop). `bash` is deliberately NOT included: it\n * stays available as the documented cooperative boundary (see docs/worktree-sync.md) — the same\n * trust model the lane gate already applies to foreign CLIs it cannot structurally contain.\n */\nexport const WORKER_FORBIDDEN_TOOLS: ReadonlySet<string> = new Set([\n\t\"goal\",\n\t\"ask_question\",\n\t\"secret_store\",\n\t\"delegate\",\n\t\"delegate_status\",\n\t\"profile_writer\",\n\t\"improvement_loop\",\n\t\"extensionify\",\n\t\"skillify\",\n\t\"run_toolkit_script\",\n\t\"model_fitness\",\n\t\"tmux_agent_manager\",\n\t\"context_scout\",\n\t\"python\",\n]);\n"]}
1
+ {"version":3,"file":"session-role.js","sourceRoot":"","sources":["../../src/core/session-role.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;A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B,cAAc;IACd,UAAU;IACV,oBAAoB;IACpB,eAAe;IACf,oBAAoB;IACpB,eAAe;IACf,QAAQ;CACR,CAAC,CAAC","sourcesContent":["/**\n * Session-role identity: distinguishes a MAIN session (an interactive/direct `pi` session) from a\n * WORKER session (lane-bound or explicitly dispatched) — the seam every worker-scoped UAC ceiling\n * and zero-footprint store gates on (see runtime-builder.ts's `isAllowedTool`, the worktree_sync\n * tool's worker scoping, and the read-only store options threaded through the persistence layer).\n *\n * A session is a worker iff EITHER:\n * - `PI_SESSION_ROLE=worker` is set (an explicit launcher declaration),\n * - a valid `PI_PARENT_PID` declares this process as a managed child, or\n * - it is bound to a worktree-sync lane (`PI_WORKTREE_LANE`; see worktree-sync/runtime.ts) — a\n * lane-bound session is a worker by construction, regardless of how it was launched.\n *\n * `PI_SESSION_ROLE=main` is deliberately NOT an escalation: it can never override a bound lane.\n * There is no environment value a lane-bound process can set to shed the worker ceiling — the env\n * var is additive evidence for \"worker\", never a downgrade signal.\n */\n\nimport { getParentPid } from \"./process-identity.ts\";\nimport { getBoundWorktreeLaneKey } from \"./worktree-sync/runtime.ts\";\n\nexport type SessionRole = \"main\" | \"worker\";\nexport type TerminalSessionMode = \"user\" | \"worker\";\n\nexport const PI_SESSION_ROLE_ENV = \"PI_SESSION_ROLE\";\n\nexport function isTerminalSessionMode(value: string): value is TerminalSessionMode {\n\treturn value === \"user\" || value === \"worker\";\n}\n\n/** Apply the terminal audience declaration without bypassing worker inference or UAC ceilings. */\nexport function setTerminalSessionMode(mode: TerminalSessionMode, env: NodeJS.ProcessEnv = process.env): void {\n\tif (mode === \"worker\") {\n\t\tenv[PI_SESSION_ROLE_ENV] = \"worker\";\n\t} else if (env[PI_SESSION_ROLE_ENV] !== \"worker\") {\n\t\tenv[PI_SESSION_ROLE_ENV] = \"main\";\n\t}\n}\n\n/** Derive this process's session role from the environment (env-injectable for tests). */\nexport function getSessionRole(env: NodeJS.ProcessEnv = process.env): SessionRole {\n\tif (env[PI_SESSION_ROLE_ENV] === \"worker\") return \"worker\";\n\tif (getParentPid(env) !== undefined) return \"worker\";\n\tif (getBoundWorktreeLaneKey(env) !== undefined) return \"worker\";\n\treturn \"main\";\n}\n\n/** True iff this process is a worker session (lane-bound or explicitly declared). */\nexport function isWorkerSession(env: NodeJS.ProcessEnv = process.env): boolean {\n\treturn getSessionRole(env) === \"worker\";\n}\n\n/**\n * Tools a worker session may never activate: the orchestration/self-adaptation surface that would\n * let a worker spawn its own sub-orchestration, bypass its parent to request owner input, mutate\n * settings-driven learning/model state, or shell out to the unbounded `python` execution contract.\n * `python` is load-bearing for the zero-footprint guarantee (it can write anywhere the interpreter\n * can reach); `context_scout` is\n * sub-orchestration (spawns its own isolated agent loop). `bash` is deliberately NOT included: it\n * stays available as the documented cooperative boundary (see docs/worktree-sync.md) — the same\n * trust model the lane gate already applies to foreign CLIs it cannot structurally contain.\n */\nexport const WORKER_FORBIDDEN_TOOLS: ReadonlySet<string> = new Set([\n\t\"goal\",\n\t\"ask_question\",\n\t\"secret_store\",\n\t\"skill\",\n\t\"delegate\",\n\t\"improvement_loop\",\n\t\"extensionify\",\n\t\"skillify\",\n\t\"run_toolkit_script\",\n\t\"model_fitness\",\n\t\"tmux_agent_manager\",\n\t\"context_scout\",\n\t\"python\",\n]);\n"]}
@@ -0,0 +1,98 @@
1
+ import type { AgentMessage } from "@caupulican/pi-agent-core";
2
+ import { type Skill } from "./skills.ts";
3
+ export declare const ACTIVE_SKILL_CONTEXT_CUSTOM_TYPE = "active_skill_context";
4
+ export declare const DEFAULT_SKILL_IDLE_TIMEOUT_MS: number;
5
+ export declare const MAX_ACTIVE_SKILL_BODY_BYTES: number;
6
+ export declare const MIN_ACTIVE_SKILL_BODY_BYTES: number;
7
+ type SkillVaultRequester = "model" | "user";
8
+ type SkillVaultUnloadReason = "explicit" | "idle_expired" | "resource_unavailable" | "budget_exceeded";
9
+ interface LoadedSkill {
10
+ skill: Skill;
11
+ bodyBytes: number;
12
+ contextMessage: AgentMessage;
13
+ requester: SkillVaultRequester;
14
+ loadedAtMs: number;
15
+ fileDevice: number;
16
+ fileInode: number;
17
+ fileSize: number;
18
+ fileModifiedAtMs: number;
19
+ fileChangedAtMs: number;
20
+ }
21
+ type SkillVaultState = {
22
+ state: "unloaded";
23
+ reason?: SkillVaultUnloadReason;
24
+ } | ({
25
+ state: "loaded_pending";
26
+ } & LoadedSkill) | ({
27
+ state: "active";
28
+ lastUsedAtMs: number;
29
+ useCount: number;
30
+ } & LoadedSkill);
31
+ export interface SkillVaultStatus {
32
+ state: SkillVaultState["state"];
33
+ idleTimeoutMs: number;
34
+ name?: string;
35
+ loadedAtMs?: number;
36
+ lastUsedAtMs?: number;
37
+ idleForMs?: number;
38
+ expiresInMs?: number;
39
+ useCount?: number;
40
+ reason?: SkillVaultUnloadReason;
41
+ }
42
+ export interface SkillSearchResult {
43
+ candidates: Array<{
44
+ name: string;
45
+ description: string;
46
+ }>;
47
+ }
48
+ export type SkillLoadResult = {
49
+ ok: true;
50
+ state: "loaded_pending";
51
+ name: string;
52
+ replaced?: string;
53
+ } | {
54
+ ok: false;
55
+ reason: "not_found" | "body_too_large" | "invalid_body" | "read_failed";
56
+ message: string;
57
+ };
58
+ export interface SkillVaultControllerOptions {
59
+ getSkills(): readonly Skill[];
60
+ now?: () => number;
61
+ idleTimeoutMs?: number;
62
+ getMaxBodyBytes?: () => number;
63
+ onSkillUsed?: (skill: Skill, usedAtMs: number) => void;
64
+ }
65
+ /** Reserve at most roughly one context token's worth of bytes per advertised context token. */
66
+ export declare function resolveActiveSkillBodyByteLimit(contextWindow: number | undefined): number;
67
+ /** One host-owned, event-driven lifecycle for lazy skill discovery and transient context projection. */
68
+ export declare class SkillVaultController {
69
+ private readonly getSkills;
70
+ private readonly now;
71
+ private readonly idleTimeoutMs;
72
+ private readonly getMaxBodyBytes;
73
+ private readonly onSkillUsed;
74
+ private current;
75
+ private contextRevision;
76
+ constructor(options: SkillVaultControllerOptions);
77
+ search(rawQuery: string): SkillSearchResult;
78
+ load(name: string, requester: SkillVaultRequester): SkillLoadResult;
79
+ unload(): {
80
+ ok: true;
81
+ unloaded?: string;
82
+ };
83
+ status(): SkillVaultStatus;
84
+ projectContext(messages: AgentMessage[]): AgentMessage[];
85
+ /** Model the next request's transient skill cost without treating a diagnostic read as use. */
86
+ previewContext(messages: AgentMessage[]): AgentMessage[];
87
+ /** Monotonic identity for provider-visible skill projection changes. */
88
+ getContextRevision(): number;
89
+ private appendContext;
90
+ /** Record host-observed work derived from an active skill, independent of agent cooperation. */
91
+ noteActivity(): void;
92
+ private reconcile;
93
+ private reconcileResource;
94
+ private replaceState;
95
+ private resolveMaxBodyBytes;
96
+ }
97
+ export {};
98
+ //# sourceMappingURL=skill-vault.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"skill-vault.d.ts","sourceRoot":"","sources":["../../src/core/skill-vault.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAI9D,OAAO,EAA+B,KAAK,KAAK,EAAyB,MAAM,aAAa,CAAC;AAG7F,eAAO,MAAM,gCAAgC,yBAAyB,CAAC;AACvE,eAAO,MAAM,6BAA6B,QAAiB,CAAC;AAC5D,eAAO,MAAM,2BAA2B,QAAY,CAAC;AACrD,eAAO,MAAM,2BAA2B,QAAW,CAAC;AAIpD,KAAK,mBAAmB,GAAG,OAAO,GAAG,MAAM,CAAC;AAC5C,KAAK,sBAAsB,GAAG,UAAU,GAAG,cAAc,GAAG,sBAAsB,GAAG,iBAAiB,CAAC;AAEvG,UAAU,WAAW;IACpB,KAAK,EAAE,KAAK,CAAC;IACb,SAAS,EAAE,MAAM,CAAC;IAClB,cAAc,EAAE,YAAY,CAAC;IAC7B,SAAS,EAAE,mBAAmB,CAAC;IAC/B,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IAC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KnB;IAED,OAAO,CAAC,SAAS;IAUjB,OAAO,CAAC,iBAAiB;IAoCzB,OAAO,CAAC,YAAY;IAKpB,OAAO,CAAC,mBAAmB;CAK3B"}
@@ -0,0 +1,270 @@
1
+ import { statSync } from "node:fs";
2
+ import { performance } from "node:perf_hooks";
3
+ import { createCustomMessage } from "@caupulican/pi-agent-core/messages";
4
+ import { parseFrontmatter } from "../utils/frontmatter.js";
5
+ import { stripResourceProfileBlocks } from "./resource-profile-blocks.js";
6
+ import { MAX_SKILL_FRONTMATTER_BYTES } from "./skills.js";
7
+ import { readBoundedTextFileSync, sameFileVersion } from "./util/bounded-file.js";
8
+ export const ACTIVE_SKILL_CONTEXT_CUSTOM_TYPE = "active_skill_context";
9
+ export const DEFAULT_SKILL_IDLE_TIMEOUT_MS = 10 * 60 * 1000;
10
+ export const MAX_ACTIVE_SKILL_BODY_BYTES = 64 * 1024;
11
+ export const MIN_ACTIVE_SKILL_BODY_BYTES = 4 * 1024;
12
+ const MAX_SEARCH_RESULTS = 5;
13
+ const MAX_SEARCH_DESCRIPTION_CHARS = 240;
14
+ function compactDescription(description) {
15
+ const normalized = description.replace(/\s+/g, " ").trim();
16
+ if (normalized.length <= MAX_SEARCH_DESCRIPTION_CHARS)
17
+ return normalized;
18
+ return `${normalized.slice(0, MAX_SEARCH_DESCRIPTION_CHARS - 1)}…`;
19
+ }
20
+ function queryTokens(value) {
21
+ return [...new Set(value.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? [])];
22
+ }
23
+ function searchScore(skill, query, tokens) {
24
+ const name = skill.name.toLowerCase();
25
+ const description = skill.description.toLowerCase();
26
+ let score = name === query ? 100 : name.includes(query) ? 40 : description.includes(query) ? 20 : 0;
27
+ for (const token of tokens) {
28
+ if (name === token)
29
+ score += 16;
30
+ else if (name.includes(token))
31
+ score += 8;
32
+ if (description.includes(token))
33
+ score += 3;
34
+ }
35
+ return score;
36
+ }
37
+ function activeSkillContext(skill, body) {
38
+ return [`ACTIVE SKILL ${skill.name}`, `BASE ${skill.baseDir}`, "NON-NEGOTIABLE WHILE ACTIVE:", body].join("\n");
39
+ }
40
+ /** Reserve at most roughly one context token's worth of bytes per advertised context token. */
41
+ export function resolveActiveSkillBodyByteLimit(contextWindow) {
42
+ if (contextWindow === undefined || !Number.isFinite(contextWindow) || contextWindow <= 0) {
43
+ return MAX_ACTIVE_SKILL_BODY_BYTES;
44
+ }
45
+ return Math.min(MAX_ACTIVE_SKILL_BODY_BYTES, Math.max(MIN_ACTIVE_SKILL_BODY_BYTES, Math.floor(contextWindow)));
46
+ }
47
+ /** One host-owned, event-driven lifecycle for lazy skill discovery and transient context projection. */
48
+ export class SkillVaultController {
49
+ constructor(options) {
50
+ this.current = { state: "unloaded" };
51
+ this.contextRevision = 0;
52
+ if (!Number.isFinite(options.idleTimeoutMs ?? DEFAULT_SKILL_IDLE_TIMEOUT_MS)) {
53
+ throw new TypeError("Skill idle timeout must be finite.");
54
+ }
55
+ this.getSkills = options.getSkills;
56
+ this.now = options.now ?? (() => performance.now());
57
+ this.idleTimeoutMs = Math.max(1, options.idleTimeoutMs ?? DEFAULT_SKILL_IDLE_TIMEOUT_MS);
58
+ this.getMaxBodyBytes = options.getMaxBodyBytes ?? (() => MAX_ACTIVE_SKILL_BODY_BYTES);
59
+ this.onSkillUsed = options.onSkillUsed;
60
+ }
61
+ search(rawQuery) {
62
+ const query = rawQuery.trim().toLowerCase();
63
+ const tokens = queryTokens(query);
64
+ if (!query || tokens.length === 0)
65
+ return { candidates: [] };
66
+ const candidates = this.getSkills()
67
+ .filter((skill) => !skill.disableModelInvocation)
68
+ .map((skill) => ({ skill, score: searchScore(skill, query, tokens) }))
69
+ .filter((entry) => entry.score > 0)
70
+ .sort((left, right) => right.score - left.score || left.skill.name.localeCompare(right.skill.name))
71
+ .slice(0, MAX_SEARCH_RESULTS)
72
+ .map(({ skill }) => ({ name: skill.name, description: compactDescription(skill.description) }));
73
+ return { candidates };
74
+ }
75
+ load(name, requester) {
76
+ const skill = this.getSkills().find((candidate) => candidate.name === name && (requester === "user" || !candidate.disableModelInvocation));
77
+ if (!skill) {
78
+ return { ok: false, reason: "not_found", message: `No eligible skill named ${JSON.stringify(name)}.` };
79
+ }
80
+ const maxBodyBytes = this.resolveMaxBodyBytes();
81
+ let before;
82
+ try {
83
+ before = statSync(skill.filePath);
84
+ }
85
+ catch (error) {
86
+ return { ok: false, reason: "read_failed", message: error instanceof Error ? error.message : String(error) };
87
+ }
88
+ let raw;
89
+ try {
90
+ raw = readBoundedTextFileSync(skill.filePath, maxBodyBytes + MAX_SKILL_FRONTMATTER_BYTES, `Skill ${JSON.stringify(skill.name)}`);
91
+ }
92
+ catch (error) {
93
+ const message = error instanceof Error ? error.message : String(error);
94
+ return message.includes("exceeds its byte limit")
95
+ ? {
96
+ ok: false,
97
+ reason: "body_too_large",
98
+ message: `Skill body exceeds ${maxBodyBytes} bytes; not truncated.`,
99
+ }
100
+ : { ok: false, reason: "read_failed", message };
101
+ }
102
+ const parsed = parseFrontmatter(raw);
103
+ const currentName = parsed.frontmatter.name ?? skill.name;
104
+ const body = stripResourceProfileBlocks(parsed.body).trim();
105
+ if (currentName !== skill.name || !parsed.frontmatter.description || !body) {
106
+ return { ok: false, reason: "invalid_body", message: "Skill metadata changed or its body is empty." };
107
+ }
108
+ const bodyBytes = Buffer.byteLength(body, "utf8");
109
+ if (bodyBytes > maxBodyBytes) {
110
+ return {
111
+ ok: false,
112
+ reason: "body_too_large",
113
+ message: `Skill body exceeds ${maxBodyBytes} bytes; not truncated.`,
114
+ };
115
+ }
116
+ let file;
117
+ try {
118
+ file = statSync(skill.filePath);
119
+ }
120
+ catch (error) {
121
+ return { ok: false, reason: "read_failed", message: error instanceof Error ? error.message : String(error) };
122
+ }
123
+ if (!sameFileVersion(before, file)) {
124
+ return { ok: false, reason: "read_failed", message: "Skill changed while it was being loaded." };
125
+ }
126
+ const replaced = this.current.state === "unloaded" ? undefined : this.current.skill.name;
127
+ this.replaceState({
128
+ state: "loaded_pending",
129
+ skill,
130
+ bodyBytes,
131
+ contextMessage: createCustomMessage(ACTIVE_SKILL_CONTEXT_CUSTOM_TYPE, activeSkillContext(skill, body), false, { name: skill.name, requestLocal: true }, new Date().toISOString()),
132
+ requester,
133
+ loadedAtMs: this.now(),
134
+ fileDevice: file.dev,
135
+ fileInode: file.ino,
136
+ fileSize: file.size,
137
+ fileModifiedAtMs: file.mtimeMs,
138
+ fileChangedAtMs: file.ctimeMs,
139
+ });
140
+ return { ok: true, state: "loaded_pending", name: skill.name, ...(replaced ? { replaced } : {}) };
141
+ }
142
+ unload() {
143
+ const unloaded = this.current.state === "unloaded" ? undefined : this.current.skill.name;
144
+ this.replaceState({ state: "unloaded", reason: "explicit" });
145
+ return { ok: true, ...(unloaded ? { unloaded } : {}) };
146
+ }
147
+ status() {
148
+ const now = this.now();
149
+ this.reconcile(now);
150
+ if (this.current.state === "unloaded") {
151
+ return {
152
+ state: "unloaded",
153
+ idleTimeoutMs: this.idleTimeoutMs,
154
+ ...(this.current.reason ? { reason: this.current.reason } : {}),
155
+ };
156
+ }
157
+ if (this.current.state === "loaded_pending") {
158
+ return {
159
+ state: "loaded_pending",
160
+ idleTimeoutMs: this.idleTimeoutMs,
161
+ name: this.current.skill.name,
162
+ loadedAtMs: this.current.loadedAtMs,
163
+ };
164
+ }
165
+ const idleForMs = Math.max(0, now - this.current.lastUsedAtMs);
166
+ return {
167
+ state: "active",
168
+ idleTimeoutMs: this.idleTimeoutMs,
169
+ name: this.current.skill.name,
170
+ loadedAtMs: this.current.loadedAtMs,
171
+ lastUsedAtMs: this.current.lastUsedAtMs,
172
+ idleForMs,
173
+ expiresInMs: Math.max(0, this.idleTimeoutMs - idleForMs),
174
+ useCount: this.current.useCount,
175
+ };
176
+ }
177
+ projectContext(messages) {
178
+ const now = this.now();
179
+ this.reconcile(now);
180
+ if (this.current.state === "unloaded")
181
+ return messages;
182
+ const loaded = this.current;
183
+ const firstUse = loaded.state === "loaded_pending";
184
+ const useCount = firstUse ? 1 : loaded.useCount + 1;
185
+ this.current = { ...loaded, state: "active", lastUsedAtMs: now, useCount };
186
+ if (firstUse) {
187
+ try {
188
+ this.onSkillUsed?.(loaded.skill, now);
189
+ }
190
+ catch {
191
+ // Usage telemetry must never block skill application.
192
+ }
193
+ }
194
+ return this.appendContext(messages, loaded);
195
+ }
196
+ /** Model the next request's transient skill cost without treating a diagnostic read as use. */
197
+ previewContext(messages) {
198
+ this.reconcile(this.now());
199
+ return this.current.state === "unloaded" ? messages : this.appendContext(messages, this.current);
200
+ }
201
+ /** Monotonic identity for provider-visible skill projection changes. */
202
+ getContextRevision() {
203
+ this.reconcile(this.now());
204
+ return this.contextRevision;
205
+ }
206
+ appendContext(messages, loaded) {
207
+ return [...messages, loaded.contextMessage];
208
+ }
209
+ /** Record host-observed work derived from an active skill, independent of agent cooperation. */
210
+ noteActivity() {
211
+ const now = this.now();
212
+ if (this.current.state === "active") {
213
+ this.current = { ...this.current, lastUsedAtMs: now };
214
+ }
215
+ }
216
+ reconcile(now) {
217
+ if (!this.reconcileResource())
218
+ return;
219
+ const current = this.current;
220
+ if (current.state === "unloaded")
221
+ return;
222
+ const lastUsedAtMs = current.state === "loaded_pending" ? current.loadedAtMs : current.lastUsedAtMs;
223
+ if (now - lastUsedAtMs >= this.idleTimeoutMs) {
224
+ this.replaceState({ state: "unloaded", reason: "idle_expired" });
225
+ }
226
+ }
227
+ reconcileResource() {
228
+ if (this.current.state === "unloaded")
229
+ return false;
230
+ const loaded = this.current;
231
+ if (loaded.bodyBytes > this.resolveMaxBodyBytes()) {
232
+ this.replaceState({ state: "unloaded", reason: "budget_exceeded" });
233
+ return false;
234
+ }
235
+ const currentSkill = this.getSkills().find((skill) => skill.name === loaded.skill.name &&
236
+ skill.filePath === loaded.skill.filePath &&
237
+ (loaded.requester === "user" || !skill.disableModelInvocation));
238
+ if (!currentSkill) {
239
+ this.replaceState({ state: "unloaded", reason: "resource_unavailable" });
240
+ return false;
241
+ }
242
+ try {
243
+ const file = statSync(loaded.skill.filePath);
244
+ if (file.dev !== loaded.fileDevice ||
245
+ file.ino !== loaded.fileInode ||
246
+ file.size !== loaded.fileSize ||
247
+ file.mtimeMs !== loaded.fileModifiedAtMs ||
248
+ file.ctimeMs !== loaded.fileChangedAtMs) {
249
+ this.replaceState({ state: "unloaded", reason: "resource_unavailable" });
250
+ return false;
251
+ }
252
+ }
253
+ catch {
254
+ this.replaceState({ state: "unloaded", reason: "resource_unavailable" });
255
+ return false;
256
+ }
257
+ return true;
258
+ }
259
+ replaceState(state) {
260
+ this.current = state;
261
+ this.contextRevision++;
262
+ }
263
+ resolveMaxBodyBytes() {
264
+ const configured = this.getMaxBodyBytes();
265
+ if (!Number.isFinite(configured))
266
+ return 1;
267
+ return Math.min(MAX_ACTIVE_SKILL_BODY_BYTES, Math.max(1, Math.floor(configured)));
268
+ }
269
+ }
270
+ //# sourceMappingURL=skill-vault.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"skill-vault.js","sourceRoot":"","sources":["../../src/core/skill-vault.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnC,OAAO,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAE9C,OAAO,EAAE,mBAAmB,EAAE,MAAM,oCAAoC,CAAC;AACzE,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EAAE,2BAA2B,EAAqC,MAAM,aAAa,CAAC;AAC7F,OAAO,EAAE,uBAAuB,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAElF,MAAM,CAAC,MAAM,gCAAgC,GAAG,sBAAsB,CAAC;AACvE,MAAM,CAAC,MAAM,6BAA6B,GAAG,EAAE,GAAG,EAAE,GAAG,IAAI,CAAC;AAC5D,MAAM,CAAC,MAAM,2BAA2B,GAAG,EAAE,GAAG,IAAI,CAAC;AAC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K,MAAM,CAAC,gBAAgB;gBACxC,IAAI,CAAC,OAAO,KAAK,MAAM,CAAC,eAAe,EACtC,CAAC;gBACF,IAAI,CAAC,YAAY,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,sBAAsB,EAAE,CAAC,CAAC;gBACzE,OAAO,KAAK,CAAC;YACd,CAAC;QACF,CAAC;QAAC,MAAM,CAAC;YACR,IAAI,CAAC,YAAY,CAAC,EAAE,KAAK,EAAE,UAAU,EAAE,MAAM,EAAE,sBAAsB,EAAE,CAAC,CAAC;YACzE,OAAO,KAAK,CAAC;QACd,CAAC;QACD,OAAO,IAAI,CAAC;IACb,CAAC;IAEO,YAAY,CAAC,KAAsB;QAC1C,IAAI,CAAC,OAAO,GAAG,KAAK,CAAC;QACrB,IAAI,CAAC,eAAe,EAAE,CAAC;IACxB,CAAC;IAEO,mBAAmB;QAC1B,MAAM,UAAU,GAAG,IAAI,CAAC,eAAe,EAAE,CAAC;QAC1C,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAC;YAAE,OAAO,CAAC,CAAC;QAC3C,OAAO,IAAI,CAAC,GAAG,CAAC,2BAA2B,EAAE,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,CAAC,CAAC,CAAC;IACnF,CAAC;CACD","sourcesContent":["import { statSync } from \"node:fs\";\nimport { performance } from \"node:perf_hooks\";\nimport type { AgentMessage } from \"@caupulican/pi-agent-core\";\nimport { createCustomMessage } from \"@caupulican/pi-agent-core/messages\";\nimport { parseFrontmatter } from \"../utils/frontmatter.ts\";\nimport { stripResourceProfileBlocks } from \"./resource-profile-blocks.ts\";\nimport { MAX_SKILL_FRONTMATTER_BYTES, type Skill, type SkillFrontmatter } from \"./skills.ts\";\nimport { readBoundedTextFileSync, sameFileVersion } from \"./util/bounded-file.ts\";\n\nexport const ACTIVE_SKILL_CONTEXT_CUSTOM_TYPE = \"active_skill_context\";\nexport const DEFAULT_SKILL_IDLE_TIMEOUT_MS = 10 * 60 * 1000;\nexport const MAX_ACTIVE_SKILL_BODY_BYTES = 64 * 1024;\nexport const MIN_ACTIVE_SKILL_BODY_BYTES = 4 * 1024;\nconst MAX_SEARCH_RESULTS = 5;\nconst MAX_SEARCH_DESCRIPTION_CHARS = 240;\n\ntype SkillVaultRequester = \"model\" | \"user\";\ntype SkillVaultUnloadReason = \"explicit\" | \"idle_expired\" | \"resource_unavailable\" | \"budget_exceeded\";\n\ninterface LoadedSkill {\n\tskill: Skill;\n\tbodyBytes: number;\n\tcontextMessage: AgentMessage;\n\trequester: SkillVaultRequester;\n\tloadedAtMs: number;\n\tfileDevice: number;\n\tfileInode: number;\n\tfileSize: number;\n\tfileModifiedAtMs: number;\n\tfileChangedAtMs: number;\n}\n\ntype SkillVaultState =\n\t| { state: \"unloaded\"; reason?: SkillVaultUnloadReason }\n\t| ({ state: \"loaded_pending\" } & LoadedSkill)\n\t| ({ state: \"active\"; lastUsedAtMs: number; useCount: number } & LoadedSkill);\n\nexport interface SkillVaultStatus {\n\tstate: SkillVaultState[\"state\"];\n\tidleTimeoutMs: number;\n\tname?: string;\n\tloadedAtMs?: number;\n\tlastUsedAtMs?: number;\n\tidleForMs?: number;\n\texpiresInMs?: number;\n\tuseCount?: number;\n\treason?: SkillVaultUnloadReason;\n}\n\nexport interface SkillSearchResult {\n\tcandidates: Array<{ name: string; description: string }>;\n}\n\nexport type SkillLoadResult =\n\t| { ok: true; state: \"loaded_pending\"; name: string; replaced?: string }\n\t| { ok: false; reason: \"not_found\" | \"body_too_large\" | \"invalid_body\" | \"read_failed\"; message: string };\n\nexport interface SkillVaultControllerOptions {\n\tgetSkills(): readonly Skill[];\n\tnow?: () => number;\n\tidleTimeoutMs?: number;\n\tgetMaxBodyBytes?: () => number;\n\tonSkillUsed?: (skill: Skill, usedAtMs: number) => void;\n}\n\nfunction compactDescription(description: string): string {\n\tconst normalized = description.replace(/\\s+/g, \" \").trim();\n\tif (normalized.length <= MAX_SEARCH_DESCRIPTION_CHARS) return normalized;\n\treturn `${normalized.slice(0, MAX_SEARCH_DESCRIPTION_CHARS - 1)}…`;\n}\n\nfunction queryTokens(value: string): string[] {\n\treturn [...new Set(value.toLowerCase().match(/[\\p{L}\\p{N}]+/gu) ?? [])];\n}\n\nfunction searchScore(skill: Skill, query: string, tokens: readonly string[]): number {\n\tconst name = skill.name.toLowerCase();\n\tconst description = skill.description.toLowerCase();\n\tlet score = name === query ? 100 : name.includes(query) ? 40 : description.includes(query) ? 20 : 0;\n\tfor (const token of tokens) {\n\t\tif (name === token) score += 16;\n\t\telse if (name.includes(token)) score += 8;\n\t\tif (description.includes(token)) score += 3;\n\t}\n\treturn score;\n}\n\nfunction activeSkillContext(skill: Skill, body: string): string {\n\treturn [`ACTIVE SKILL ${skill.name}`, `BASE ${skill.baseDir}`, \"NON-NEGOTIABLE WHILE ACTIVE:\", body].join(\"\\n\");\n}\n\n/** Reserve at most roughly one context token's worth of bytes per advertised context token. */\nexport function resolveActiveSkillBodyByteLimit(contextWindow: number | undefined): number {\n\tif (contextWindow === undefined || !Number.isFinite(contextWindow) || contextWindow <= 0) {\n\t\treturn MAX_ACTIVE_SKILL_BODY_BYTES;\n\t}\n\treturn Math.min(MAX_ACTIVE_SKILL_BODY_BYTES, Math.max(MIN_ACTIVE_SKILL_BODY_BYTES, Math.floor(contextWindow)));\n}\n\n/** One host-owned, event-driven lifecycle for lazy skill discovery and transient context projection. */\nexport class SkillVaultController {\n\tprivate readonly getSkills: () => readonly Skill[];\n\tprivate readonly now: () => number;\n\tprivate readonly idleTimeoutMs: number;\n\tprivate readonly getMaxBodyBytes: () => number;\n\tprivate readonly onSkillUsed: ((skill: Skill, usedAtMs: number) => void) | undefined;\n\tprivate current: SkillVaultState = { state: \"unloaded\" };\n\tprivate contextRevision = 0;\n\n\tconstructor(options: SkillVaultControllerOptions) {\n\t\tif (!Number.isFinite(options.idleTimeoutMs ?? DEFAULT_SKILL_IDLE_TIMEOUT_MS)) {\n\t\t\tthrow new TypeError(\"Skill idle timeout must be finite.\");\n\t\t}\n\t\tthis.getSkills = options.getSkills;\n\t\tthis.now = options.now ?? (() => performance.now());\n\t\tthis.idleTimeoutMs = Math.max(1, options.idleTimeoutMs ?? DEFAULT_SKILL_IDLE_TIMEOUT_MS);\n\t\tthis.getMaxBodyBytes = options.getMaxBodyBytes ?? (() => MAX_ACTIVE_SKILL_BODY_BYTES);\n\t\tthis.onSkillUsed = options.onSkillUsed;\n\t}\n\n\tsearch(rawQuery: string): SkillSearchResult {\n\t\tconst query = rawQuery.trim().toLowerCase();\n\t\tconst tokens = queryTokens(query);\n\t\tif (!query || tokens.length === 0) return { candidates: [] };\n\t\tconst candidates = this.getSkills()\n\t\t\t.filter((skill) => !skill.disableModelInvocation)\n\t\t\t.map((skill) => ({ skill, score: searchScore(skill, query, tokens) }))\n\t\t\t.filter((entry) => entry.score > 0)\n\t\t\t.sort((left, right) => right.score - left.score || left.skill.name.localeCompare(right.skill.name))\n\t\t\t.slice(0, MAX_SEARCH_RESULTS)\n\t\t\t.map(({ skill }) => ({ name: skill.name, description: compactDescription(skill.description) }));\n\t\treturn { candidates };\n\t}\n\n\tload(name: string, requester: SkillVaultRequester): SkillLoadResult {\n\t\tconst skill = this.getSkills().find(\n\t\t\t(candidate) => candidate.name === name && (requester === \"user\" || !candidate.disableModelInvocation),\n\t\t);\n\t\tif (!skill) {\n\t\t\treturn { ok: false, reason: \"not_found\", message: `No eligible skill named ${JSON.stringify(name)}.` };\n\t\t}\n\t\tconst maxBodyBytes = this.resolveMaxBodyBytes();\n\t\tlet before: ReturnType<typeof statSync>;\n\t\ttry {\n\t\t\tbefore = statSync(skill.filePath);\n\t\t} catch (error) {\n\t\t\treturn { ok: false, reason: \"read_failed\", message: error instanceof Error ? error.message : String(error) };\n\t\t}\n\t\tlet raw: string;\n\t\ttry {\n\t\t\traw = readBoundedTextFileSync(\n\t\t\t\tskill.filePath,\n\t\t\t\tmaxBodyBytes + MAX_SKILL_FRONTMATTER_BYTES,\n\t\t\t\t`Skill ${JSON.stringify(skill.name)}`,\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\treturn message.includes(\"exceeds its byte limit\")\n\t\t\t\t? {\n\t\t\t\t\t\tok: false,\n\t\t\t\t\t\treason: \"body_too_large\",\n\t\t\t\t\t\tmessage: `Skill body exceeds ${maxBodyBytes} bytes; not truncated.`,\n\t\t\t\t\t}\n\t\t\t\t: { ok: false, reason: \"read_failed\", message };\n\t\t}\n\t\tconst parsed = parseFrontmatter<SkillFrontmatter>(raw);\n\t\tconst currentName = parsed.frontmatter.name ?? skill.name;\n\t\tconst body = stripResourceProfileBlocks(parsed.body).trim();\n\t\tif (currentName !== skill.name || !parsed.frontmatter.description || !body) {\n\t\t\treturn { ok: false, reason: \"invalid_body\", message: \"Skill metadata changed or its body is empty.\" };\n\t\t}\n\t\tconst bodyBytes = Buffer.byteLength(body, \"utf8\");\n\t\tif (bodyBytes > maxBodyBytes) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\treason: \"body_too_large\",\n\t\t\t\tmessage: `Skill body exceeds ${maxBodyBytes} bytes; not truncated.`,\n\t\t\t};\n\t\t}\n\t\tlet file: ReturnType<typeof statSync>;\n\t\ttry {\n\t\t\tfile = statSync(skill.filePath);\n\t\t} catch (error) {\n\t\t\treturn { ok: false, reason: \"read_failed\", message: error instanceof Error ? error.message : String(error) };\n\t\t}\n\t\tif (!sameFileVersion(before, file)) {\n\t\t\treturn { ok: false, reason: \"read_failed\", message: \"Skill changed while it was being loaded.\" };\n\t\t}\n\t\tconst replaced = this.current.state === \"unloaded\" ? undefined : this.current.skill.name;\n\t\tthis.replaceState({\n\t\t\tstate: \"loaded_pending\",\n\t\t\tskill,\n\t\t\tbodyBytes,\n\t\t\tcontextMessage: createCustomMessage(\n\t\t\t\tACTIVE_SKILL_CONTEXT_CUSTOM_TYPE,\n\t\t\t\tactiveSkillContext(skill, body),\n\t\t\t\tfalse,\n\t\t\t\t{ name: skill.name, requestLocal: true },\n\t\t\t\tnew Date().toISOString(),\n\t\t\t),\n\t\t\trequester,\n\t\t\tloadedAtMs: this.now(),\n\t\t\tfileDevice: file.dev,\n\t\t\tfileInode: file.ino,\n\t\t\tfileSize: file.size,\n\t\t\tfileModifiedAtMs: file.mtimeMs,\n\t\t\tfileChangedAtMs: file.ctimeMs,\n\t\t});\n\t\treturn { ok: true, state: \"loaded_pending\", name: skill.name, ...(replaced ? { replaced } : {}) };\n\t}\n\n\tunload(): { ok: true; unloaded?: string } {\n\t\tconst unloaded = this.current.state === \"unloaded\" ? undefined : this.current.skill.name;\n\t\tthis.replaceState({ state: \"unloaded\", reason: \"explicit\" });\n\t\treturn { ok: true, ...(unloaded ? { unloaded } : {}) };\n\t}\n\n\tstatus(): SkillVaultStatus {\n\t\tconst now = this.now();\n\t\tthis.reconcile(now);\n\t\tif (this.current.state === \"unloaded\") {\n\t\t\treturn {\n\t\t\t\tstate: \"unloaded\",\n\t\t\t\tidleTimeoutMs: this.idleTimeoutMs,\n\t\t\t\t...(this.current.reason ? { reason: this.current.reason } : {}),\n\t\t\t};\n\t\t}\n\t\tif (this.current.state === \"loaded_pending\") {\n\t\t\treturn {\n\t\t\t\tstate: \"loaded_pending\",\n\t\t\t\tidleTimeoutMs: this.idleTimeoutMs,\n\t\t\t\tname: this.current.skill.name,\n\t\t\t\tloadedAtMs: this.current.loadedAtMs,\n\t\t\t};\n\t\t}\n\t\tconst idleForMs = Math.max(0, now - this.current.lastUsedAtMs);\n\t\treturn {\n\t\t\tstate: \"active\",\n\t\t\tidleTimeoutMs: this.idleTimeoutMs,\n\t\t\tname: this.current.skill.name,\n\t\t\tloadedAtMs: this.current.loadedAtMs,\n\t\t\tlastUsedAtMs: this.current.lastUsedAtMs,\n\t\t\tidleForMs,\n\t\t\texpiresInMs: Math.max(0, this.idleTimeoutMs - idleForMs),\n\t\t\tuseCount: this.current.useCount,\n\t\t};\n\t}\n\n\tprojectContext(messages: AgentMessage[]): AgentMessage[] {\n\t\tconst now = this.now();\n\t\tthis.reconcile(now);\n\t\tif (this.current.state === \"unloaded\") return messages;\n\t\tconst loaded = this.current;\n\t\tconst firstUse = loaded.state === \"loaded_pending\";\n\t\tconst useCount = firstUse ? 1 : loaded.useCount + 1;\n\t\tthis.current = { ...loaded, state: \"active\", lastUsedAtMs: now, useCount };\n\t\tif (firstUse) {\n\t\t\ttry {\n\t\t\t\tthis.onSkillUsed?.(loaded.skill, now);\n\t\t\t} catch {\n\t\t\t\t// Usage telemetry must never block skill application.\n\t\t\t}\n\t\t}\n\t\treturn this.appendContext(messages, loaded);\n\t}\n\n\t/** Model the next request's transient skill cost without treating a diagnostic read as use. */\n\tpreviewContext(messages: AgentMessage[]): AgentMessage[] {\n\t\tthis.reconcile(this.now());\n\t\treturn this.current.state === \"unloaded\" ? messages : this.appendContext(messages, this.current);\n\t}\n\n\t/** Monotonic identity for provider-visible skill projection changes. */\n\tgetContextRevision(): number {\n\t\tthis.reconcile(this.now());\n\t\treturn this.contextRevision;\n\t}\n\n\tprivate appendContext(messages: AgentMessage[], loaded: LoadedSkill): AgentMessage[] {\n\t\treturn [...messages, loaded.contextMessage];\n\t}\n\n\t/** Record host-observed work derived from an active skill, independent of agent cooperation. */\n\tnoteActivity(): void {\n\t\tconst now = this.now();\n\t\tif (this.current.state === \"active\") {\n\t\t\tthis.current = { ...this.current, lastUsedAtMs: now };\n\t\t}\n\t}\n\n\tprivate reconcile(now: number): void {\n\t\tif (!this.reconcileResource()) return;\n\t\tconst current = this.current;\n\t\tif (current.state === \"unloaded\") return;\n\t\tconst lastUsedAtMs = current.state === \"loaded_pending\" ? current.loadedAtMs : current.lastUsedAtMs;\n\t\tif (now - lastUsedAtMs >= this.idleTimeoutMs) {\n\t\t\tthis.replaceState({ state: \"unloaded\", reason: \"idle_expired\" });\n\t\t}\n\t}\n\n\tprivate reconcileResource(): boolean {\n\t\tif (this.current.state === \"unloaded\") return false;\n\t\tconst loaded = this.current;\n\t\tif (loaded.bodyBytes > this.resolveMaxBodyBytes()) {\n\t\t\tthis.replaceState({ state: \"unloaded\", reason: \"budget_exceeded\" });\n\t\t\treturn false;\n\t\t}\n\t\tconst currentSkill = this.getSkills().find(\n\t\t\t(skill) =>\n\t\t\t\tskill.name === loaded.skill.name &&\n\t\t\t\tskill.filePath === loaded.skill.filePath &&\n\t\t\t\t(loaded.requester === \"user\" || !skill.disableModelInvocation),\n\t\t);\n\t\tif (!currentSkill) {\n\t\t\tthis.replaceState({ state: \"unloaded\", reason: \"resource_unavailable\" });\n\t\t\treturn false;\n\t\t}\n\t\ttry {\n\t\t\tconst file = statSync(loaded.skill.filePath);\n\t\t\tif (\n\t\t\t\tfile.dev !== loaded.fileDevice ||\n\t\t\t\tfile.ino !== loaded.fileInode ||\n\t\t\t\tfile.size !== loaded.fileSize ||\n\t\t\t\tfile.mtimeMs !== loaded.fileModifiedAtMs ||\n\t\t\t\tfile.ctimeMs !== loaded.fileChangedAtMs\n\t\t\t) {\n\t\t\t\tthis.replaceState({ state: \"unloaded\", reason: \"resource_unavailable\" });\n\t\t\t\treturn false;\n\t\t\t}\n\t\t} catch {\n\t\t\tthis.replaceState({ state: \"unloaded\", reason: \"resource_unavailable\" });\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\tprivate replaceState(state: SkillVaultState): void {\n\t\tthis.current = state;\n\t\tthis.contextRevision++;\n\t}\n\n\tprivate resolveMaxBodyBytes(): number {\n\t\tconst configured = this.getMaxBodyBytes();\n\t\tif (!Number.isFinite(configured)) return 1;\n\t\treturn Math.min(MAX_ACTIVE_SKILL_BODY_BYTES, Math.max(1, Math.floor(configured)));\n\t}\n}\n"]}
@@ -1,12 +1,16 @@
1
1
  import type { ThinkingLevel } from "@caupulican/pi-agent-core";
2
2
  import type { ResourceDiagnostic } from "./diagnostics.ts";
3
3
  import { type SourceInfo } from "./source-info.ts";
4
+ /** Discovery retains only this bounded metadata prefix, never the whole skill body. */
5
+ export declare const MAX_SKILL_FRONTMATTER_BYTES: number;
4
6
  export interface SkillFrontmatter {
5
7
  name?: string;
6
8
  description?: string;
7
9
  "disable-model-invocation"?: boolean;
8
10
  /** Optional thinking-level hint (R1 follow-up); see Skill.thinking. */
9
11
  thinking?: string;
12
+ /** Reflection-generated skill marker used by the curator. */
13
+ promoted?: boolean;
10
14
  [key: string]: unknown;
11
15
  }
12
16
  export interface Skill {
@@ -16,6 +20,7 @@ export interface Skill {
16
20
  baseDir: string;
17
21
  sourceInfo: SourceInfo;
18
22
  disableModelInvocation: boolean;
23
+ promoted?: boolean;
19
24
  /**
20
25
  * Optional thinking-level hint parsed from frontmatter (R1 follow-up: skill-surfaced thinking
21
26
  * governance, alongside resource-profile thinking). Core only parses and surfaces this value —
@@ -45,6 +50,11 @@ export interface LoadSkillsFromDirOptions {
45
50
  /** Profile UAC gate: when provided, files it denies are never read from disk. */
46
51
  isPathAllowed?: (path: string) => boolean;
47
52
  }
53
+ /**
54
+ * Read one stable, bounded frontmatter prefix. The closing delimiter ends the read, so discovery
55
+ * cost depends on metadata size, never body size. Unterminated metadata fails at the explicit cap.
56
+ */
57
+ export declare function readSkillFrontmatterFile(filePath: string): string;
48
58
  /**
49
59
  * Load skills from a directory.
50
60
  *
@@ -54,15 +64,6 @@ export interface LoadSkillsFromDirOptions {
54
64
  * - recurse into subdirectories to find SKILL.md
55
65
  */
56
66
  export declare function loadSkillsFromDir(options: LoadSkillsFromDirOptions): LoadSkillsResult;
57
- /**
58
- * Format skills for inclusion in a system prompt.
59
- * Uses XML format per Agent Skills standard.
60
- * See: https://agentskills.io/integrate-skills
61
- *
62
- * Skills with disableModelInvocation=true are excluded from the prompt
63
- * (they can only be invoked explicitly via /skill:name commands).
64
- */
65
- export declare function formatSkillsForPrompt(skills: Skill[]): string;
66
67
  export interface LoadSkillsOptions {
67
68
  /** Working directory for project-local skills. */
68
69
  cwd: string;
@@ -1 +1 @@
1
- {"version":3,"file":"skills.d.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AAC;IACvB,sBAAsB,EAAE,OAAO,CAAC;IAChC,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB;;;;;;;;;OASG;IACH,QAAQ,CAAC,EAAE,aAAa,CAAC;CACzB;AAED,MAAM,WAAW,gBAAgB;IAChC,MAAM,EAAE,KAAK,EAAE,CAAC;IAChB,WAAW,EAAE,kBAAkB,EAAE,CAAC;CAClC;AAED;;;GAGG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,EAAE,CAoBxD;AAiBD,MAAM,WAAW,wBAAwB;IACxC,mCAAmC;IACnC,GAAG,EAAE,MAAM,CAAC;IACZ,yCAAyC;IACzC,MAAM,EAAE,MAAM,CAAC;IACf,iFAAiF;IACjF,aAAa,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC;CAC1C;AA0BD;;;GAGG;AACH,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CA6BjE;AAED;;;;;;;GAOG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,wBAAwB,GAAG,gBAAgB,CAGrF;AAuED,MAAM,WAAW,iBAAiB;IACjC,kDAAkD;IAClD,GAAG,EAAE,MAAM,CAAC;IACZ,gDAAgD;IAChD,QAAQ,EAAE,MAAM,CAAC;IACjB,kDAAkD;IAClD,UAAU,EAAE,MAAM,EAAE,CAAC;IACrB,0CAA0C;IAC1C,eAAe,EAAE,OAAO,CAAC;IACzB,iFAAiF;IACjF,aAAa,CAAC,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC;CAC1C;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,OAAO,EAAE,iBAAiB,GAAG,gBAAgB,CAiGvE"}
@@ -1,14 +1,15 @@
1
- import { existsSync, readFileSync, statSync } from "fs";
1
+ import { closeSync, existsSync, fstatSync, openSync, readSync, statSync } from "fs";
2
2
  import { basename, dirname, join, resolve } from "path";
3
3
  import { CONFIG_DIR_NAME, getAgentDir } from "../config.js";
4
4
  import { parseFrontmatter } from "../utils/frontmatter.js";
5
5
  import { canonicalizePath, resolvePath } from "../utils/paths.js";
6
- import { escapePromptXml } from "./prompt-markup.js";
7
6
  import { isResourcePathWithin } from "./resource-traversal.js";
8
7
  import { discoverSkillFiles } from "./skill-discovery.js";
9
8
  import { createSyntheticSourceInfo } from "./source-info.js";
10
- /** Max name length per spec */
11
- const MAX_SKILL_FILE_BYTES = 8 * 1024 * 1024;
9
+ import { sameFileVersion } from "./util/bounded-file.js";
10
+ /** Discovery retains only this bounded metadata prefix, never the whole skill body. */
11
+ export const MAX_SKILL_FRONTMATTER_BYTES = 16 * 1024;
12
+ const SKILL_FRONTMATTER_READ_CHUNK_BYTES = 1024;
12
13
  const MAX_NAME_LENGTH = 64;
13
14
  /** Max description length per spec */
14
15
  const MAX_DESCRIPTION_LENGTH = 1024;
@@ -75,6 +76,41 @@ function createSkillSourceInfo(filePath, baseDir, source) {
75
76
  return createSyntheticSourceInfo(filePath, { source, baseDir });
76
77
  }
77
78
  }
79
+ /**
80
+ * Read one stable, bounded frontmatter prefix. The closing delimiter ends the read, so discovery
81
+ * cost depends on metadata size, never body size. Unterminated metadata fails at the explicit cap.
82
+ */
83
+ export function readSkillFrontmatterFile(filePath) {
84
+ const fileDescriptor = openSync(filePath, "r");
85
+ try {
86
+ const before = fstatSync(fileDescriptor);
87
+ if (!before.isFile())
88
+ throw new Error("Skill is not a regular file.");
89
+ const chunks = [];
90
+ let totalBytes = 0;
91
+ while (totalBytes < MAX_SKILL_FRONTMATTER_BYTES) {
92
+ const chunk = Buffer.allocUnsafe(Math.min(SKILL_FRONTMATTER_READ_CHUNK_BYTES, MAX_SKILL_FRONTMATTER_BYTES - totalBytes));
93
+ const bytesRead = readSync(fileDescriptor, chunk, 0, chunk.length, totalBytes);
94
+ if (bytesRead > 0) {
95
+ chunks.push(chunk.subarray(0, bytesRead));
96
+ totalBytes += bytesRead;
97
+ }
98
+ const prefix = Buffer.concat(chunks, totalBytes).toString("utf8").replace(/\r\n/g, "\n").replace(/\r/g, "\n");
99
+ const hasOpeningDelimiter = prefix.length >= 3 && prefix.startsWith("---");
100
+ const closingDelimiter = hasOpeningDelimiter ? prefix.indexOf("\n---", 3) : -1;
101
+ if (!hasOpeningDelimiter || closingDelimiter !== -1 || bytesRead === 0) {
102
+ const after = fstatSync(fileDescriptor);
103
+ if (!sameFileVersion(before, after))
104
+ throw new Error("Skill changed while metadata was being read.");
105
+ return closingDelimiter === -1 ? prefix : prefix.slice(0, closingDelimiter + 4);
106
+ }
107
+ }
108
+ throw new Error(`Skill frontmatter exceeds ${MAX_SKILL_FRONTMATTER_BYTES} bytes or is unterminated.`);
109
+ }
110
+ finally {
111
+ closeSync(fileDescriptor);
112
+ }
113
+ }
78
114
  /**
79
115
  * Load skills from a directory.
80
116
  *
@@ -104,19 +140,7 @@ function loadSkillsFromDirInternal(dir, source, isPathAllowed) {
104
140
  function loadSkillFromFile(filePath, source) {
105
141
  const diagnostics = [];
106
142
  try {
107
- // A skill file is prompt material; anything beyond this is a mistake (or
108
- // hostile) and would otherwise be loaded whole into the heap at startup.
109
- const { size } = statSync(filePath);
110
- if (size > MAX_SKILL_FILE_BYTES) {
111
- diagnostics.push({
112
- type: "warning",
113
- path: filePath,
114
- message: `Skill file is ${Math.round(size / (1024 * 1024))}MB (limit ${Math.round(MAX_SKILL_FILE_BYTES / (1024 * 1024))}MB); skipped.`,
115
- });
116
- return { skill: null, diagnostics };
117
- }
118
- const rawContent = readFileSync(filePath, "utf-8");
119
- const { frontmatter } = parseFrontmatter(rawContent);
143
+ const { frontmatter } = parseFrontmatter(readSkillFrontmatterFile(filePath));
120
144
  const skillDir = dirname(filePath);
121
145
  const parentDirName = basename(skillDir);
122
146
  // Validate description
@@ -143,6 +167,7 @@ function loadSkillFromFile(filePath, source) {
143
167
  baseDir: skillDir,
144
168
  sourceInfo: createSkillSourceInfo(filePath, skillDir, source),
145
169
  disableModelInvocation: frontmatter["disable-model-invocation"] === true,
170
+ promoted: frontmatter.promoted === true,
146
171
  thinking: isSkillThinkingLevel(frontmatter.thinking) ? frontmatter.thinking : undefined,
147
172
  },
148
173
  diagnostics,
@@ -154,39 +179,6 @@ function loadSkillFromFile(filePath, source) {
154
179
  return { skill: null, diagnostics };
155
180
  }
156
181
  }
157
- /**
158
- * Format skills for inclusion in a system prompt.
159
- * Uses XML format per Agent Skills standard.
160
- * See: https://agentskills.io/integrate-skills
161
- *
162
- * Skills with disableModelInvocation=true are excluded from the prompt
163
- * (they can only be invoked explicitly via /skill:name commands).
164
- */
165
- export function formatSkillsForPrompt(skills) {
166
- const visibleSkills = skills.filter((s) => !s.disableModelInvocation);
167
- if (visibleSkills.length === 0) {
168
- return "";
169
- }
170
- const lines = [
171
- "\n\nThe following skills provide specialized instructions for specific tasks.",
172
- "Use the read tool to load a skill's file when the task matches its description.",
173
- "When multiple skills seem relevant, prefer the narrowest task-specific skill; combine skills only when their descriptions clearly cover distinct parts of the request.",
174
- "Do not use a skill merely because it is loaded; if the fit is unclear, inspect the skill or ask before applying broad behavior.",
175
- "Resource-profile blocks inside skill files are configuration data, not task instructions, and are stripped from /skill expansion.",
176
- "When a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.",
177
- "",
178
- "<available_skills>",
179
- ];
180
- for (const skill of visibleSkills) {
181
- lines.push(" <skill>");
182
- lines.push(` <name>${escapePromptXml(skill.name)}</name>`);
183
- lines.push(` <description>${escapePromptXml(skill.description)}</description>`);
184
- lines.push(` <location>${escapePromptXml(skill.filePath)}</location>`);
185
- lines.push(" </skill>");
186
- }
187
- lines.push("</available_skills>");
188
- return lines.join("\n");
189
- }
190
182
  /**
191
183
  * Load skills from all configured locations.
192
184
  * Returns skills and any validation diagnostics.