@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.
- package/CHANGELOG.md +43 -0
- package/README.md +1 -1
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts.map +1 -1
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.js +14 -15
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.js.map +1 -1
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.ts +14 -16
- package/dist/bundled-resources/skills/worker-profile-writer/SKILL.md +4 -4
- package/dist/core/agent-session.d.ts +23 -33
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +81 -110
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/autonomy/contracts.d.ts +1 -1
- package/dist/core/autonomy/contracts.js.map +1 -1
- package/dist/core/autonomy/gates.d.ts.map +1 -1
- package/dist/core/autonomy/gates.js +16 -0
- package/dist/core/autonomy/gates.js.map +1 -1
- package/dist/core/autonomy/subagent-prompt.d.ts +2 -1
- package/dist/core/autonomy/subagent-prompt.d.ts.map +1 -1
- package/dist/core/autonomy/subagent-prompt.js +2 -18
- package/dist/core/autonomy/subagent-prompt.js.map +1 -1
- package/dist/core/background-tool-task-controller.js +5 -5
- package/dist/core/background-tool-task-controller.js.map +1 -1
- package/dist/core/compaction-controller.d.ts +22 -2
- package/dist/core/compaction-controller.d.ts.map +1 -1
- package/dist/core/compaction-controller.js +75 -39
- package/dist/core/compaction-controller.js.map +1 -1
- package/dist/core/context/brain-curator.d.ts +2 -3
- package/dist/core/context/brain-curator.d.ts.map +1 -1
- package/dist/core/context/brain-curator.js +3 -20
- package/dist/core/context/brain-curator.js.map +1 -1
- package/dist/core/context/context-composition.d.ts +2 -1
- package/dist/core/context/context-composition.d.ts.map +1 -1
- package/dist/core/context/context-composition.js +6 -1
- package/dist/core/context/context-composition.js.map +1 -1
- package/dist/core/context/memory-prompt-block.js +1 -1
- package/dist/core/context/memory-prompt-block.js.map +1 -1
- package/dist/core/context/tool-output-packer.js +1 -1
- package/dist/core/context/tool-output-packer.js.map +1 -1
- package/dist/core/context-gc.js +10 -10
- package/dist/core/context-gc.js.map +1 -1
- package/dist/core/context-pipeline.d.ts +4 -4
- package/dist/core/context-pipeline.js +4 -4
- package/dist/core/context-pipeline.js.map +1 -1
- package/dist/core/default-tool-surface.d.ts.map +1 -1
- package/dist/core/default-tool-surface.js +1 -2
- package/dist/core/default-tool-surface.js.map +1 -1
- package/dist/core/delegation/session-worker-claim.d.ts +2 -2
- package/dist/core/delegation/session-worker-claim.js +2 -2
- package/dist/core/delegation/session-worker-claim.js.map +1 -1
- package/dist/core/delegation/worker-agent-control-coordinator.js +1 -1
- package/dist/core/delegation/worker-agent-control-coordinator.js.map +1 -1
- package/dist/core/delegation/worker-resource-materializer.js +3 -3
- package/dist/core/delegation/worker-resource-materializer.js.map +1 -1
- package/dist/core/delegation/worker-runner.d.ts +2 -13
- package/dist/core/delegation/worker-runner.d.ts.map +1 -1
- package/dist/core/delegation/worker-runner.js +5 -67
- package/dist/core/delegation/worker-runner.js.map +1 -1
- package/dist/core/extensions/builtin.js +4 -4
- package/dist/core/extensions/builtin.js.map +1 -1
- package/dist/core/extensions/runner.d.ts +6 -2
- package/dist/core/extensions/runner.d.ts.map +1 -1
- package/dist/core/extensions/runner.js +21 -9
- package/dist/core/extensions/runner.js.map +1 -1
- package/dist/core/extensions/types.d.ts +9 -2
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/foreground-terminal-handoff-controller.js +2 -2
- package/dist/core/foreground-terminal-handoff-controller.js.map +1 -1
- package/dist/core/goals/compact-goal-context.d.ts.map +1 -1
- package/dist/core/goals/compact-goal-context.js +13 -9
- package/dist/core/goals/compact-goal-context.js.map +1 -1
- package/dist/core/goals/goal-continuation-prompt.js +1 -1
- package/dist/core/goals/goal-continuation-prompt.js.map +1 -1
- package/dist/core/goals/goal-session-controller.d.ts +6 -0
- package/dist/core/goals/goal-session-controller.d.ts.map +1 -1
- package/dist/core/goals/goal-session-controller.js +16 -13
- package/dist/core/goals/goal-session-controller.js.map +1 -1
- package/dist/core/human-input-controller.js +1 -1
- package/dist/core/human-input-controller.js.map +1 -1
- package/dist/core/improvement-loop.js +13 -13
- package/dist/core/improvement-loop.js.map +1 -1
- package/dist/core/learning/reflection-engine.d.ts +2 -1
- package/dist/core/learning/reflection-engine.d.ts.map +1 -1
- package/dist/core/learning/reflection-engine.js +4 -24
- package/dist/core/learning/reflection-engine.js.map +1 -1
- package/dist/core/model-capability.d.ts.map +1 -1
- package/dist/core/model-capability.js +1 -1
- package/dist/core/model-capability.js.map +1 -1
- package/dist/core/model-router/route-judge.d.ts +2 -1
- package/dist/core/model-router/route-judge.d.ts.map +1 -1
- package/dist/core/model-router/route-judge.js +4 -12
- package/dist/core/model-router/route-judge.js.map +1 -1
- package/dist/core/models/perf-profile.d.ts +1 -1
- package/dist/core/models/perf-profile.d.ts.map +1 -1
- package/dist/core/models/perf-profile.js +2 -8
- package/dist/core/models/perf-profile.js.map +1 -1
- package/dist/core/orchestration/lane-tool-manifests.d.ts +1 -1
- package/dist/core/orchestration/lane-tool-manifests.d.ts.map +1 -1
- package/dist/core/orchestration/lane-tool-manifests.js +1 -6
- package/dist/core/orchestration/lane-tool-manifests.js.map +1 -1
- package/dist/core/process-matrix/resume-launcher.js +3 -3
- package/dist/core/process-matrix/resume-launcher.js.map +1 -1
- package/dist/core/process-matrix/runtime.d.ts +2 -0
- package/dist/core/process-matrix/runtime.d.ts.map +1 -1
- package/dist/core/process-matrix/runtime.js +23 -19
- package/dist/core/process-matrix/runtime.js.map +1 -1
- package/dist/core/provider-prompt-contracts.d.ts +34 -0
- package/dist/core/provider-prompt-contracts.d.ts.map +1 -0
- package/dist/core/provider-prompt-contracts.js +133 -0
- package/dist/core/provider-prompt-contracts.js.map +1 -0
- package/dist/core/provider-request-context-controller.d.ts +40 -0
- package/dist/core/provider-request-context-controller.d.ts.map +1 -0
- package/dist/core/provider-request-context-controller.js +68 -0
- package/dist/core/provider-request-context-controller.js.map +1 -0
- package/dist/core/provider-request-runtime-controller.d.ts +22 -0
- package/dist/core/provider-request-runtime-controller.d.ts.map +1 -0
- package/dist/core/provider-request-runtime-controller.js +87 -0
- package/dist/core/provider-request-runtime-controller.js.map +1 -0
- package/dist/core/provider-tool-text.d.ts +7 -0
- package/dist/core/provider-tool-text.d.ts.map +1 -0
- package/dist/core/provider-tool-text.js +42 -0
- package/dist/core/provider-tool-text.js.map +1 -0
- package/dist/core/research/model-fitness.d.ts +2 -5
- package/dist/core/research/model-fitness.d.ts.map +1 -1
- package/dist/core/research/model-fitness.js +2 -20
- package/dist/core/research/model-fitness.js.map +1 -1
- package/dist/core/research/research-runner.d.ts +2 -1
- package/dist/core/research/research-runner.d.ts.map +1 -1
- package/dist/core/research/research-runner.js +6 -21
- package/dist/core/research/research-runner.js.map +1 -1
- package/dist/core/risk-classifier.d.ts.map +1 -1
- package/dist/core/risk-classifier.js +9 -1
- package/dist/core/risk-classifier.js.map +1 -1
- package/dist/core/runtime-builder.d.ts +3 -0
- package/dist/core/runtime-builder.d.ts.map +1 -1
- package/dist/core/runtime-builder.js +20 -25
- package/dist/core/runtime-builder.js.map +1 -1
- package/dist/core/scout-controller.d.ts +2 -1
- package/dist/core/scout-controller.d.ts.map +1 -1
- package/dist/core/scout-controller.js +2 -16
- package/dist/core/scout-controller.js.map +1 -1
- package/dist/core/sdk.d.ts +1 -1
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/secrets/credential-exposure-guard.js +6 -6
- package/dist/core/secrets/credential-exposure-guard.js.map +1 -1
- package/dist/core/secrets/credential-manager.d.ts +11 -1
- package/dist/core/secrets/credential-manager.d.ts.map +1 -1
- package/dist/core/secrets/credential-manager.js +28 -7
- package/dist/core/secrets/credential-manager.js.map +1 -1
- package/dist/core/secrets/credential-migration-source.d.ts +20 -0
- package/dist/core/secrets/credential-migration-source.d.ts.map +1 -0
- package/dist/core/secrets/credential-migration-source.js +113 -0
- package/dist/core/secrets/credential-migration-source.js.map +1 -0
- package/dist/core/secrets/credential-session-connection.d.ts +9 -0
- package/dist/core/secrets/credential-session-connection.d.ts.map +1 -0
- package/dist/core/secrets/credential-session-connection.js +39 -0
- package/dist/core/secrets/credential-session-connection.js.map +1 -0
- package/dist/core/security/untrusted-boundary.d.ts +2 -2
- package/dist/core/security/untrusted-boundary.d.ts.map +1 -1
- package/dist/core/security/untrusted-boundary.js +3 -10
- package/dist/core/security/untrusted-boundary.js.map +1 -1
- package/dist/core/session-role.d.ts.map +1 -1
- package/dist/core/session-role.js +1 -2
- package/dist/core/session-role.js.map +1 -1
- package/dist/core/skill-vault.d.ts +98 -0
- package/dist/core/skill-vault.d.ts.map +1 -0
- package/dist/core/skill-vault.js +270 -0
- package/dist/core/skill-vault.js.map +1 -0
- package/dist/core/skills.d.ts +10 -9
- package/dist/core/skills.d.ts.map +1 -1
- package/dist/core/skills.js +42 -50
- package/dist/core/skills.js.map +1 -1
- package/dist/core/system-prompt-builder.d.ts +1 -1
- package/dist/core/system-prompt-builder.d.ts.map +1 -1
- package/dist/core/system-prompt-builder.js +20 -60
- package/dist/core/system-prompt-builder.js.map +1 -1
- package/dist/core/system-prompt.d.ts +4 -4
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +87 -121
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tasks/task-state.d.ts.map +1 -1
- package/dist/core/tasks/task-state.js +6 -7
- package/dist/core/tasks/task-state.js.map +1 -1
- package/dist/core/tool-capability-policy.d.ts.map +1 -1
- package/dist/core/tool-capability-policy.js +2 -1
- package/dist/core/tool-capability-policy.js.map +1 -1
- package/dist/core/tool-protocol-controller.d.ts.map +1 -1
- package/dist/core/tool-protocol-controller.js +4 -7
- package/dist/core/tool-protocol-controller.js.map +1 -1
- package/dist/core/tool-selection/promotion.d.ts.map +1 -1
- package/dist/core/tool-selection/promotion.js +2 -6
- package/dist/core/tool-selection/promotion.js.map +1 -1
- package/dist/core/toolkit/reflex-interpreter.d.ts +2 -1
- package/dist/core/toolkit/reflex-interpreter.d.ts.map +1 -1
- package/dist/core/toolkit/reflex-interpreter.js +2 -14
- package/dist/core/toolkit/reflex-interpreter.js.map +1 -1
- package/dist/core/tools/ask-question.js +6 -6
- package/dist/core/tools/ask-question.js.map +1 -1
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js +8 -7
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/delegate-status.d.ts +17 -13
- package/dist/core/tools/delegate-status.d.ts.map +1 -1
- package/dist/core/tools/delegate-status.js +111 -226
- package/dist/core/tools/delegate-status.js.map +1 -1
- package/dist/core/tools/delegate.d.ts +29 -2
- package/dist/core/tools/delegate.d.ts.map +1 -1
- package/dist/core/tools/delegate.js +149 -48
- package/dist/core/tools/delegate.js.map +1 -1
- package/dist/core/tools/edit.js +3 -3
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/extensionify-runtime.js +4 -4
- package/dist/core/tools/extensionify-runtime.js.map +1 -1
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js +2 -4
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/goal.js +3 -3
- package/dist/core/tools/goal.js.map +1 -1
- package/dist/core/tools/grep.js +2 -2
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/index.d.ts +1 -1
- package/dist/core/tools/index.d.ts.map +1 -1
- package/dist/core/tools/index.js +1 -1
- package/dist/core/tools/index.js.map +1 -1
- package/dist/core/tools/model-fitness.js +4 -4
- package/dist/core/tools/model-fitness.js.map +1 -1
- package/dist/core/tools/profile-writer.d.ts +30 -16
- package/dist/core/tools/profile-writer.d.ts.map +1 -1
- package/dist/core/tools/profile-writer.js +98 -59
- package/dist/core/tools/profile-writer.js.map +1 -1
- package/dist/core/tools/python.js +6 -6
- package/dist/core/tools/python.js.map +1 -1
- package/dist/core/tools/run-process.js +4 -4
- package/dist/core/tools/run-process.js.map +1 -1
- package/dist/core/tools/run-toolkit-script.js +4 -4
- package/dist/core/tools/run-toolkit-script.js.map +1 -1
- package/dist/core/tools/secret-store.d.ts +32 -3
- package/dist/core/tools/secret-store.d.ts.map +1 -1
- package/dist/core/tools/secret-store.js +141 -34
- package/dist/core/tools/secret-store.js.map +1 -1
- package/dist/core/tools/skill.d.ts +29 -0
- package/dist/core/tools/skill.d.ts.map +1 -0
- package/dist/core/tools/skill.js +79 -0
- package/dist/core/tools/skill.js.map +1 -0
- package/dist/core/tools/task-steps.js +4 -4
- package/dist/core/tools/task-steps.js.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.js +2 -0
- package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
- package/dist/core/tools/tool-task.d.ts.map +1 -1
- package/dist/core/tools/tool-task.js +4 -0
- package/dist/core/tools/tool-task.js.map +1 -1
- package/dist/core/tools/worktree-sync.js +6 -6
- package/dist/core/tools/worktree-sync.js.map +1 -1
- package/dist/core/tools/write.js +3 -3
- package/dist/core/tools/write.js.map +1 -1
- package/dist/index.d.ts +5 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -1
- package/dist/index.js.map +1 -1
- package/dist/modes/interactive/interactive-event-controller.js +1 -1
- package/dist/modes/interactive/interactive-event-controller.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +1 -1
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/report-commands.js +1 -1
- package/dist/modes/interactive/report-commands.js.map +1 -1
- package/dist/modes/interactive/secret-menu-controller.d.ts.map +1 -1
- package/dist/modes/interactive/secret-menu-controller.js +2 -18
- package/dist/modes/interactive/secret-menu-controller.js.map +1 -1
- package/dist/modes/interactive/session-flow-commands.js +1 -1
- package/dist/modes/interactive/session-flow-commands.js.map +1 -1
- package/docs/compaction.md +45 -25
- package/docs/extensions.md +23 -7
- package/docs/settings.md +3 -3
- package/docs/skills.md +14 -10
- package/docs/task-steps.md +2 -2
- package/docs/tmux-agent-manager.md +1 -1
- package/docs/tool-repair.md +18 -1
- package/docs/usage.md +4 -2
- package/docs/worker-profiles.md +3 -3
- package/docs/worktree-sync.md +2 -2
- package/examples/extensions/custom-compaction.ts +5 -17
- package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
- package/examples/extensions/custom-provider-anthropic/package.json +1 -1
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/sandbox/package-lock.json +2 -2
- package/examples/extensions/sandbox/package.json +1 -1
- package/examples/extensions/summarize.ts +3 -5
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/examples/sdk/04-skills.ts +1 -1
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 -4
- package/dist/core/util/json-size.d.ts +0 -3
- package/dist/core/util/json-size.d.ts.map +0 -1
- package/dist/core/util/json-size.js +0 -95
- package/dist/core/util/json-size.js.map +0 -1
package/dist/core/skills.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"skills.js","sourceRoot":"","sources":["../../src/core/skills.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AACxD,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAElE,OAAO,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACrD,OAAO,EAAE,oBAAoB,EAAE,MAAM,y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CAAC;gBACP,cAAc,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,mCAAmC,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC,CAAC;YAC5G,CAAC;QACF,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,2BAA2B,CAAC;YACrF,cAAc,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC,CAAC;QACvE,CAAC;IACF,CAAC;IAED,OAAO;QACN,MAAM,EAAE,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC;QACrC,WAAW,EAAE,CAAC,GAAG,cAAc,EAAE,GAAG,oBAAoB,CAAC;KACzD,CAAC;AACH,CAAC","sourcesContent":["import type { ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { existsSync, readFileSync, statSync } from \"fs\";\nimport { basename, dirname, join, resolve } from \"path\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"../config.ts\";\nimport { parseFrontmatter } from \"../utils/frontmatter.ts\";\nimport { canonicalizePath, resolvePath } from \"../utils/paths.ts\";\nimport type { ResourceDiagnostic } from \"./diagnostics.ts\";\nimport { escapePromptXml } from \"./prompt-markup.ts\";\nimport { isResourcePathWithin } from \"./resource-traversal.ts\";\nimport { discoverSkillFiles } from \"./skill-discovery.ts\";\nimport { createSyntheticSourceInfo, type SourceInfo } from \"./source-info.ts\";\n\n/** Max name length per spec */\nconst MAX_SKILL_FILE_BYTES = 8 * 1024 * 1024;\n\nconst MAX_NAME_LENGTH = 64;\n\n/** Max description length per spec */\nconst MAX_DESCRIPTION_LENGTH = 1024;\n\n// Kept local rather than imported from settings-manager.ts's ThinkingLevel validation: that module\n// already imports validateSkillName FROM this file, so importing back would cycle. The literal set\n// is small and stable (mirrors settings-manager.ts's own VALID_THINKING_LEVELS).\nconst VALID_SKILL_THINKING_LEVELS = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\", \"ultra\"] as const;\nfunction isSkillThinkingLevel(value: unknown): value is ThinkingLevel {\n\treturn typeof value === \"string\" && (VALID_SKILL_THINKING_LEVELS as readonly string[]).includes(value);\n}\n\nexport interface SkillFrontmatter {\n\tname?: string;\n\tdescription?: string;\n\t\"disable-model-invocation\"?: boolean;\n\t/** Optional thinking-level hint (R1 follow-up); see Skill.thinking. */\n\tthinking?: string;\n\t[key: string]: unknown;\n}\n\nexport interface Skill {\n\tname: string;\n\tdescription: string;\n\tfilePath: string;\n\tbaseDir: string;\n\tsourceInfo: SourceInfo;\n\tdisableModelInvocation: boolean;\n\t/**\n\t * Optional thinking-level hint parsed from frontmatter (R1 follow-up: skill-surfaced thinking\n\t * governance, alongside resource-profile thinking). Core only parses and surfaces this value —\n\t * nothing in pi-adaptative core applies it to a session's thinking level yet. Unlike an active\n\t * resource profile (a persistent \"situation\", see settings-manager.ts's activeResourceProfile)\n\t * or a routed turn (bracketed by a try/finally swap/restore, see agent-session.ts's\n\t * _runAgentPromptWithModelRouter), a skill has no session-lifecycle hook marking when it starts\n\t * or stops governing a turn, so applying this is left to the consumer (e.g. a skill-router\n\t * extension) via the existing ctx.setThinkingLevel() extension API.\n\t */\n\tthinking?: ThinkingLevel;\n}\n\nexport interface LoadSkillsResult {\n\tskills: Skill[];\n\tdiagnostics: ResourceDiagnostic[];\n}\n\n/**\n * Validate skill name per Agent Skills spec.\n * Returns array of validation error messages (empty if valid).\n */\nexport function validateSkillName(name: string): string[] {\n\tconst errors: string[] = [];\n\n\tif (name.length > MAX_NAME_LENGTH) {\n\t\terrors.push(`name exceeds ${MAX_NAME_LENGTH} characters (${name.length})`);\n\t}\n\n\tif (!/^[a-z0-9-]+$/.test(name)) {\n\t\terrors.push(`name contains invalid characters (must be lowercase a-z, 0-9, hyphens only)`);\n\t}\n\n\tif (name.startsWith(\"-\") || name.endsWith(\"-\")) {\n\t\terrors.push(`name must not start or end with a hyphen`);\n\t}\n\n\tif (name.includes(\"--\")) {\n\t\terrors.push(`name must not contain consecutive hyphens`);\n\t}\n\n\treturn errors;\n}\n\n/**\n * Validate description per Agent Skills spec.\n */\nfunction validateDescription(description: string | undefined): string[] {\n\tconst errors: string[] = [];\n\n\tif (!description || description.trim() === \"\") {\n\t\terrors.push(\"description is required\");\n\t} else if (description.length > MAX_DESCRIPTION_LENGTH) {\n\t\terrors.push(`description exceeds ${MAX_DESCRIPTION_LENGTH} characters (${description.length})`);\n\t}\n\n\treturn errors;\n}\n\nexport interface LoadSkillsFromDirOptions {\n\t/** Directory to scan for skills */\n\tdir: string;\n\t/** Source identifier for these skills */\n\tsource: string;\n\t/** Profile UAC gate: when provided, files it denies are never read from disk. */\n\tisPathAllowed?: (path: string) => boolean;\n}\n\nfunction createSkillSourceInfo(filePath: string, baseDir: string, source: string): SourceInfo {\n\tswitch (source) {\n\t\tcase \"user\":\n\t\t\treturn createSyntheticSourceInfo(filePath, {\n\t\t\t\tsource: \"local\",\n\t\t\t\tscope: \"user\",\n\t\t\t\tbaseDir,\n\t\t\t});\n\t\tcase \"project\":\n\t\t\treturn createSyntheticSourceInfo(filePath, {\n\t\t\t\tsource: \"local\",\n\t\t\t\tscope: \"project\",\n\t\t\t\tbaseDir,\n\t\t\t});\n\t\tcase \"path\":\n\t\t\treturn createSyntheticSourceInfo(filePath, {\n\t\t\t\tsource: \"local\",\n\t\t\t\tbaseDir,\n\t\t\t});\n\t\tdefault:\n\t\t\treturn createSyntheticSourceInfo(filePath, { source, baseDir });\n\t}\n}\n\n/**\n * Load skills from a directory.\n *\n * Discovery rules:\n * - if a directory contains SKILL.md, treat it as a skill root and do not recurse further\n * - otherwise, load direct .md children in the root\n * - recurse into subdirectories to find SKILL.md\n */\nexport function loadSkillsFromDir(options: LoadSkillsFromDirOptions): LoadSkillsResult {\n\tconst { dir, source } = options;\n\treturn loadSkillsFromDirInternal(dir, source, options.isPathAllowed);\n}\n\nfunction loadSkillsFromDirInternal(\n\tdir: string,\n\tsource: string,\n\tisPathAllowed?: (path: string) => boolean,\n): LoadSkillsResult {\n\tconst skills: Skill[] = [];\n\tconst diagnostics: ResourceDiagnostic[] = [];\n\tfor (const filePath of discoverSkillFiles(dir, \"pi\")) {\n\t\t// Profile UAC: denied skill contents are never read from disk.\n\t\tif (isPathAllowed && !isPathAllowed(filePath)) continue;\n\t\tconst result = loadSkillFromFile(filePath, source);\n\t\tif (result.skill) skills.push(result.skill);\n\t\tdiagnostics.push(...result.diagnostics);\n\t}\n\n\treturn { skills, diagnostics };\n}\n\nfunction loadSkillFromFile(\n\tfilePath: string,\n\tsource: string,\n): { skill: Skill | null; diagnostics: ResourceDiagnostic[] } {\n\tconst diagnostics: ResourceDiagnostic[] = [];\n\n\ttry {\n\t\t// A skill file is prompt material; anything beyond this is a mistake (or\n\t\t// hostile) and would otherwise be loaded whole into the heap at startup.\n\t\tconst { size } = statSync(filePath);\n\t\tif (size > MAX_SKILL_FILE_BYTES) {\n\t\t\tdiagnostics.push({\n\t\t\t\ttype: \"warning\",\n\t\t\t\tpath: filePath,\n\t\t\t\tmessage: `Skill file is ${Math.round(size / (1024 * 1024))}MB (limit ${Math.round(MAX_SKILL_FILE_BYTES / (1024 * 1024))}MB); skipped.`,\n\t\t\t});\n\t\t\treturn { skill: null, diagnostics };\n\t\t}\n\t\tconst rawContent = readFileSync(filePath, \"utf-8\");\n\t\tconst { frontmatter } = parseFrontmatter<SkillFrontmatter>(rawContent);\n\t\tconst skillDir = dirname(filePath);\n\t\tconst parentDirName = basename(skillDir);\n\n\t\t// Validate description\n\t\tconst descErrors = validateDescription(frontmatter.description);\n\t\tfor (const error of descErrors) {\n\t\t\tdiagnostics.push({ type: \"warning\", message: error, path: filePath });\n\t\t}\n\n\t\t// Use name from frontmatter, or fall back to parent directory name\n\t\tconst name = frontmatter.name || parentDirName;\n\n\t\t// Validate name\n\t\tconst nameErrors = validateSkillName(name);\n\t\tfor (const error of nameErrors) {\n\t\t\tdiagnostics.push({ type: \"warning\", message: error, path: filePath });\n\t\t}\n\n\t\t// Still load the skill even with warnings (unless description is completely missing)\n\t\tif (!frontmatter.description || frontmatter.description.trim() === \"\") {\n\t\t\treturn { skill: null, diagnostics };\n\t\t}\n\n\t\treturn {\n\t\t\tskill: {\n\t\t\t\tname,\n\t\t\t\tdescription: frontmatter.description,\n\t\t\t\tfilePath,\n\t\t\t\tbaseDir: skillDir,\n\t\t\t\tsourceInfo: createSkillSourceInfo(filePath, skillDir, source),\n\t\t\t\tdisableModelInvocation: frontmatter[\"disable-model-invocation\"] === true,\n\t\t\t\tthinking: isSkillThinkingLevel(frontmatter.thinking) ? frontmatter.thinking : undefined,\n\t\t\t},\n\t\t\tdiagnostics,\n\t\t};\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : \"failed to parse skill file\";\n\t\tdiagnostics.push({ type: \"warning\", message, path: filePath });\n\t\treturn { skill: null, diagnostics };\n\t}\n}\n\n/**\n * Format skills for inclusion in a system prompt.\n * Uses XML format per Agent Skills standard.\n * See: https://agentskills.io/integrate-skills\n *\n * Skills with disableModelInvocation=true are excluded from the prompt\n * (they can only be invoked explicitly via /skill:name commands).\n */\nexport function formatSkillsForPrompt(skills: Skill[]): string {\n\tconst visibleSkills = skills.filter((s) => !s.disableModelInvocation);\n\n\tif (visibleSkills.length === 0) {\n\t\treturn \"\";\n\t}\n\n\tconst lines = [\n\t\t\"\\n\\nThe following skills provide specialized instructions for specific tasks.\",\n\t\t\"Use the read tool to load a skill's file when the task matches its description.\",\n\t\t\"When multiple skills seem relevant, prefer the narrowest task-specific skill; combine skills only when their descriptions clearly cover distinct parts of the request.\",\n\t\t\"Do not use a skill merely because it is loaded; if the fit is unclear, inspect the skill or ask before applying broad behavior.\",\n\t\t\"Resource-profile blocks inside skill files are configuration data, not task instructions, and are stripped from /skill expansion.\",\n\t\t\"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.\",\n\t\t\"\",\n\t\t\"<available_skills>\",\n\t];\n\n\tfor (const skill of visibleSkills) {\n\t\tlines.push(\" <skill>\");\n\t\tlines.push(` <name>${escapePromptXml(skill.name)}</name>`);\n\t\tlines.push(` <description>${escapePromptXml(skill.description)}</description>`);\n\t\tlines.push(` <location>${escapePromptXml(skill.filePath)}</location>`);\n\t\tlines.push(\" </skill>\");\n\t}\n\n\tlines.push(\"</available_skills>\");\n\n\treturn lines.join(\"\\n\");\n}\n\nexport interface LoadSkillsOptions {\n\t/** Working directory for project-local skills. */\n\tcwd: string;\n\t/** Agent config directory for global skills. */\n\tagentDir: string;\n\t/** Explicit skill paths (files or directories) */\n\tskillPaths: string[];\n\t/** Include default skills directories. */\n\tincludeDefaults: boolean;\n\t/** Profile UAC gate: when provided, files it denies are never read from disk. */\n\tisPathAllowed?: (path: string) => boolean;\n}\n\n/**\n * Load skills from all configured locations.\n * Returns skills and any validation diagnostics.\n */\nexport function loadSkills(options: LoadSkillsOptions): LoadSkillsResult {\n\tconst { agentDir, skillPaths, includeDefaults } = options;\n\n\t// Resolve agentDir - if not provided, use default from config\n\tconst resolvedCwd = resolvePath(options.cwd);\n\tconst resolvedAgentDir = resolvePath(agentDir ?? getAgentDir());\n\n\tconst skillMap = new Map<string, Skill>();\n\tconst realPathSet = new Set<string>();\n\tconst allDiagnostics: ResourceDiagnostic[] = [];\n\tconst collisionDiagnostics: ResourceDiagnostic[] = [];\n\n\tfunction addSkills(result: LoadSkillsResult) {\n\t\tallDiagnostics.push(...result.diagnostics);\n\t\tfor (const skill of result.skills) {\n\t\t\t// Resolve symlinks to detect duplicate files\n\t\t\tconst realPath = canonicalizePath(skill.filePath);\n\n\t\t\t// Skip silently if we've already loaded this exact file (via symlink)\n\t\t\tif (realPathSet.has(realPath)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst existing = skillMap.get(skill.name);\n\t\t\tif (existing) {\n\t\t\t\tcollisionDiagnostics.push({\n\t\t\t\t\ttype: \"collision\",\n\t\t\t\t\tmessage: `name \"${skill.name}\" collision`,\n\t\t\t\t\tpath: skill.filePath,\n\t\t\t\t\tcollision: {\n\t\t\t\t\t\tresourceType: \"skill\",\n\t\t\t\t\t\tname: skill.name,\n\t\t\t\t\t\twinnerPath: existing.filePath,\n\t\t\t\t\t\tloserPath: skill.filePath,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tskillMap.set(skill.name, skill);\n\t\t\t\trealPathSet.add(realPath);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (includeDefaults) {\n\t\taddSkills(loadSkillsFromDirInternal(join(resolvedAgentDir, \"skills\"), \"user\", options.isPathAllowed));\n\t\taddSkills(\n\t\t\tloadSkillsFromDirInternal(resolve(resolvedCwd, CONFIG_DIR_NAME, \"skills\"), \"project\", options.isPathAllowed),\n\t\t);\n\t}\n\n\tconst userSkillsDir = join(resolvedAgentDir, \"skills\");\n\tconst projectSkillsDir = resolve(resolvedCwd, CONFIG_DIR_NAME, \"skills\");\n\n\tconst getSource = (resolvedPath: string): \"user\" | \"project\" | \"path\" => {\n\t\tif (!includeDefaults) {\n\t\t\tif (isResourcePathWithin(resolvedPath, userSkillsDir)) return \"user\";\n\t\t\tif (isResourcePathWithin(resolvedPath, projectSkillsDir)) return \"project\";\n\t\t}\n\t\treturn \"path\";\n\t};\n\n\tfor (const rawPath of skillPaths) {\n\t\tconst resolvedPath = resolvePath(rawPath, resolvedCwd, { trim: true });\n\t\tif (!existsSync(resolvedPath)) {\n\t\t\tallDiagnostics.push({ type: \"warning\", message: \"skill path does not exist\", path: resolvedPath });\n\t\t\tcontinue;\n\t\t}\n\n\t\ttry {\n\t\t\tconst stats = statSync(resolvedPath);\n\t\t\tconst source = getSource(resolvedPath);\n\t\t\tif (stats.isDirectory()) {\n\t\t\t\taddSkills(loadSkillsFromDirInternal(resolvedPath, source, options.isPathAllowed));\n\t\t\t} else if (stats.isFile() && resolvedPath.endsWith(\".md\")) {\n\t\t\t\t// Profile UAC: a denied skill file is never read from disk.\n\t\t\t\tif (options.isPathAllowed && !options.isPathAllowed(resolvedPath)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst result = loadSkillFromFile(resolvedPath, source);\n\t\t\t\tif (result.skill) {\n\t\t\t\t\taddSkills({ skills: [result.skill], diagnostics: result.diagnostics });\n\t\t\t\t} else {\n\t\t\t\t\tallDiagnostics.push(...result.diagnostics);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tallDiagnostics.push({ type: \"warning\", message: \"skill path is not a markdown file\", path: resolvedPath });\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"failed to read skill path\";\n\t\t\tallDiagnostics.push({ type: \"warning\", message, path: resolvedPath });\n\t\t}\n\t}\n\n\treturn {\n\t\tskills: Array.from(skillMap.values()),\n\t\tdiagnostics: [...allDiagnostics, ...collisionDiagnostics],\n\t};\n}\n"]}
|
|
1
|
+
{"version":3,"file":"skills.js","sourceRoot":"","sources":["../../src/core/skills.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,UAAU,EAAE,SAAS,EAAE,QAAQ,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,IAAI,CAAC;AACpF,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,MAAM,CAAC;AACxD,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAC5D,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAElE,OAAO,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAC/D,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAE,yBAAyB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;oBACnE,SAAS;gBACV,CAAC;gBACD,MAAM,MAAM,GAAG,iBAAiB,CAAC,YAAY,EAAE,MAAM,CAAC,CAAC;gBACvD,IAAI,MAAM,CAAC,KAAK,EAAE,CAAC;oBAClB,SAAS,CAAC,EAAE,MAAM,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,EAAE,WAAW,EAAE,MAAM,CAAC,WAAW,EAAE,CAAC,CAAC;gBACxE,CAAC;qBAAM,CAAC;oBACP,cAAc,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,WAAW,CAAC,CAAC;gBAC5C,CAAC;YACF,CAAC;iBAAM,CAAC;gBACP,cAAc,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,mCAAmC,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC,CAAC;YAC5G,CAAC;QACF,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,MAAM,OAAO,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,2BAA2B,CAAC;YACrF,cAAc,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,CAAC,CAAC;QACvE,CAAC;IACF,CAAC;IAED,OAAO;QACN,MAAM,EAAE,KAAK,CAAC,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC;QACrC,WAAW,EAAE,CAAC,GAAG,cAAc,EAAE,GAAG,oBAAoB,CAAC;KACzD,CAAC;AACH,CAAC","sourcesContent":["import type { ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { closeSync, existsSync, fstatSync, openSync, readSync, statSync } from \"fs\";\nimport { basename, dirname, join, resolve } from \"path\";\nimport { CONFIG_DIR_NAME, getAgentDir } from \"../config.ts\";\nimport { parseFrontmatter } from \"../utils/frontmatter.ts\";\nimport { canonicalizePath, resolvePath } from \"../utils/paths.ts\";\nimport type { ResourceDiagnostic } from \"./diagnostics.ts\";\nimport { isResourcePathWithin } from \"./resource-traversal.ts\";\nimport { discoverSkillFiles } from \"./skill-discovery.ts\";\nimport { createSyntheticSourceInfo, type SourceInfo } from \"./source-info.ts\";\nimport { sameFileVersion } from \"./util/bounded-file.ts\";\n\n/** Discovery retains only this bounded metadata prefix, never the whole skill body. */\nexport const MAX_SKILL_FRONTMATTER_BYTES = 16 * 1024;\nconst SKILL_FRONTMATTER_READ_CHUNK_BYTES = 1024;\n\nconst MAX_NAME_LENGTH = 64;\n\n/** Max description length per spec */\nconst MAX_DESCRIPTION_LENGTH = 1024;\n\n// Kept local rather than imported from settings-manager.ts's ThinkingLevel validation: that module\n// already imports validateSkillName FROM this file, so importing back would cycle. The literal set\n// is small and stable (mirrors settings-manager.ts's own VALID_THINKING_LEVELS).\nconst VALID_SKILL_THINKING_LEVELS = [\"off\", \"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\", \"ultra\"] as const;\nfunction isSkillThinkingLevel(value: unknown): value is ThinkingLevel {\n\treturn typeof value === \"string\" && (VALID_SKILL_THINKING_LEVELS as readonly string[]).includes(value);\n}\n\nexport interface SkillFrontmatter {\n\tname?: string;\n\tdescription?: string;\n\t\"disable-model-invocation\"?: boolean;\n\t/** Optional thinking-level hint (R1 follow-up); see Skill.thinking. */\n\tthinking?: string;\n\t/** Reflection-generated skill marker used by the curator. */\n\tpromoted?: boolean;\n\t[key: string]: unknown;\n}\n\nexport interface Skill {\n\tname: string;\n\tdescription: string;\n\tfilePath: string;\n\tbaseDir: string;\n\tsourceInfo: SourceInfo;\n\tdisableModelInvocation: boolean;\n\tpromoted?: boolean;\n\t/**\n\t * Optional thinking-level hint parsed from frontmatter (R1 follow-up: skill-surfaced thinking\n\t * governance, alongside resource-profile thinking). Core only parses and surfaces this value —\n\t * nothing in pi-adaptative core applies it to a session's thinking level yet. Unlike an active\n\t * resource profile (a persistent \"situation\", see settings-manager.ts's activeResourceProfile)\n\t * or a routed turn (bracketed by a try/finally swap/restore, see agent-session.ts's\n\t * _runAgentPromptWithModelRouter), a skill has no session-lifecycle hook marking when it starts\n\t * or stops governing a turn, so applying this is left to the consumer (e.g. a skill-router\n\t * extension) via the existing ctx.setThinkingLevel() extension API.\n\t */\n\tthinking?: ThinkingLevel;\n}\n\nexport interface LoadSkillsResult {\n\tskills: Skill[];\n\tdiagnostics: ResourceDiagnostic[];\n}\n\n/**\n * Validate skill name per Agent Skills spec.\n * Returns array of validation error messages (empty if valid).\n */\nexport function validateSkillName(name: string): string[] {\n\tconst errors: string[] = [];\n\n\tif (name.length > MAX_NAME_LENGTH) {\n\t\terrors.push(`name exceeds ${MAX_NAME_LENGTH} characters (${name.length})`);\n\t}\n\n\tif (!/^[a-z0-9-]+$/.test(name)) {\n\t\terrors.push(`name contains invalid characters (must be lowercase a-z, 0-9, hyphens only)`);\n\t}\n\n\tif (name.startsWith(\"-\") || name.endsWith(\"-\")) {\n\t\terrors.push(`name must not start or end with a hyphen`);\n\t}\n\n\tif (name.includes(\"--\")) {\n\t\terrors.push(`name must not contain consecutive hyphens`);\n\t}\n\n\treturn errors;\n}\n\n/**\n * Validate description per Agent Skills spec.\n */\nfunction validateDescription(description: string | undefined): string[] {\n\tconst errors: string[] = [];\n\n\tif (!description || description.trim() === \"\") {\n\t\terrors.push(\"description is required\");\n\t} else if (description.length > MAX_DESCRIPTION_LENGTH) {\n\t\terrors.push(`description exceeds ${MAX_DESCRIPTION_LENGTH} characters (${description.length})`);\n\t}\n\n\treturn errors;\n}\n\nexport interface LoadSkillsFromDirOptions {\n\t/** Directory to scan for skills */\n\tdir: string;\n\t/** Source identifier for these skills */\n\tsource: string;\n\t/** Profile UAC gate: when provided, files it denies are never read from disk. */\n\tisPathAllowed?: (path: string) => boolean;\n}\n\nfunction createSkillSourceInfo(filePath: string, baseDir: string, source: string): SourceInfo {\n\tswitch (source) {\n\t\tcase \"user\":\n\t\t\treturn createSyntheticSourceInfo(filePath, {\n\t\t\t\tsource: \"local\",\n\t\t\t\tscope: \"user\",\n\t\t\t\tbaseDir,\n\t\t\t});\n\t\tcase \"project\":\n\t\t\treturn createSyntheticSourceInfo(filePath, {\n\t\t\t\tsource: \"local\",\n\t\t\t\tscope: \"project\",\n\t\t\t\tbaseDir,\n\t\t\t});\n\t\tcase \"path\":\n\t\t\treturn createSyntheticSourceInfo(filePath, {\n\t\t\t\tsource: \"local\",\n\t\t\t\tbaseDir,\n\t\t\t});\n\t\tdefault:\n\t\t\treturn createSyntheticSourceInfo(filePath, { source, baseDir });\n\t}\n}\n\n/**\n * Read one stable, bounded frontmatter prefix. The closing delimiter ends the read, so discovery\n * cost depends on metadata size, never body size. Unterminated metadata fails at the explicit cap.\n */\nexport function readSkillFrontmatterFile(filePath: string): string {\n\tconst fileDescriptor = openSync(filePath, \"r\");\n\ttry {\n\t\tconst before = fstatSync(fileDescriptor);\n\t\tif (!before.isFile()) throw new Error(\"Skill is not a regular file.\");\n\t\tconst chunks: Buffer[] = [];\n\t\tlet totalBytes = 0;\n\t\twhile (totalBytes < MAX_SKILL_FRONTMATTER_BYTES) {\n\t\t\tconst chunk = Buffer.allocUnsafe(\n\t\t\t\tMath.min(SKILL_FRONTMATTER_READ_CHUNK_BYTES, MAX_SKILL_FRONTMATTER_BYTES - totalBytes),\n\t\t\t);\n\t\t\tconst bytesRead = readSync(fileDescriptor, chunk, 0, chunk.length, totalBytes);\n\t\t\tif (bytesRead > 0) {\n\t\t\t\tchunks.push(chunk.subarray(0, bytesRead));\n\t\t\t\ttotalBytes += bytesRead;\n\t\t\t}\n\t\t\tconst prefix = Buffer.concat(chunks, totalBytes).toString(\"utf8\").replace(/\\r\\n/g, \"\\n\").replace(/\\r/g, \"\\n\");\n\t\t\tconst hasOpeningDelimiter = prefix.length >= 3 && prefix.startsWith(\"---\");\n\t\t\tconst closingDelimiter = hasOpeningDelimiter ? prefix.indexOf(\"\\n---\", 3) : -1;\n\t\t\tif (!hasOpeningDelimiter || closingDelimiter !== -1 || bytesRead === 0) {\n\t\t\t\tconst after = fstatSync(fileDescriptor);\n\t\t\t\tif (!sameFileVersion(before, after)) throw new Error(\"Skill changed while metadata was being read.\");\n\t\t\t\treturn closingDelimiter === -1 ? prefix : prefix.slice(0, closingDelimiter + 4);\n\t\t\t}\n\t\t}\n\t\tthrow new Error(`Skill frontmatter exceeds ${MAX_SKILL_FRONTMATTER_BYTES} bytes or is unterminated.`);\n\t} finally {\n\t\tcloseSync(fileDescriptor);\n\t}\n}\n\n/**\n * Load skills from a directory.\n *\n * Discovery rules:\n * - if a directory contains SKILL.md, treat it as a skill root and do not recurse further\n * - otherwise, load direct .md children in the root\n * - recurse into subdirectories to find SKILL.md\n */\nexport function loadSkillsFromDir(options: LoadSkillsFromDirOptions): LoadSkillsResult {\n\tconst { dir, source } = options;\n\treturn loadSkillsFromDirInternal(dir, source, options.isPathAllowed);\n}\n\nfunction loadSkillsFromDirInternal(\n\tdir: string,\n\tsource: string,\n\tisPathAllowed?: (path: string) => boolean,\n): LoadSkillsResult {\n\tconst skills: Skill[] = [];\n\tconst diagnostics: ResourceDiagnostic[] = [];\n\tfor (const filePath of discoverSkillFiles(dir, \"pi\")) {\n\t\t// Profile UAC: denied skill contents are never read from disk.\n\t\tif (isPathAllowed && !isPathAllowed(filePath)) continue;\n\t\tconst result = loadSkillFromFile(filePath, source);\n\t\tif (result.skill) skills.push(result.skill);\n\t\tdiagnostics.push(...result.diagnostics);\n\t}\n\n\treturn { skills, diagnostics };\n}\n\nfunction loadSkillFromFile(\n\tfilePath: string,\n\tsource: string,\n): { skill: Skill | null; diagnostics: ResourceDiagnostic[] } {\n\tconst diagnostics: ResourceDiagnostic[] = [];\n\n\ttry {\n\t\tconst { frontmatter } = parseFrontmatter<SkillFrontmatter>(readSkillFrontmatterFile(filePath));\n\t\tconst skillDir = dirname(filePath);\n\t\tconst parentDirName = basename(skillDir);\n\n\t\t// Validate description\n\t\tconst descErrors = validateDescription(frontmatter.description);\n\t\tfor (const error of descErrors) {\n\t\t\tdiagnostics.push({ type: \"warning\", message: error, path: filePath });\n\t\t}\n\n\t\t// Use name from frontmatter, or fall back to parent directory name\n\t\tconst name = frontmatter.name || parentDirName;\n\n\t\t// Validate name\n\t\tconst nameErrors = validateSkillName(name);\n\t\tfor (const error of nameErrors) {\n\t\t\tdiagnostics.push({ type: \"warning\", message: error, path: filePath });\n\t\t}\n\n\t\t// Still load the skill even with warnings (unless description is completely missing)\n\t\tif (!frontmatter.description || frontmatter.description.trim() === \"\") {\n\t\t\treturn { skill: null, diagnostics };\n\t\t}\n\n\t\treturn {\n\t\t\tskill: {\n\t\t\t\tname,\n\t\t\t\tdescription: frontmatter.description,\n\t\t\t\tfilePath,\n\t\t\t\tbaseDir: skillDir,\n\t\t\t\tsourceInfo: createSkillSourceInfo(filePath, skillDir, source),\n\t\t\t\tdisableModelInvocation: frontmatter[\"disable-model-invocation\"] === true,\n\t\t\t\tpromoted: frontmatter.promoted === true,\n\t\t\t\tthinking: isSkillThinkingLevel(frontmatter.thinking) ? frontmatter.thinking : undefined,\n\t\t\t},\n\t\t\tdiagnostics,\n\t\t};\n\t} catch (error) {\n\t\tconst message = error instanceof Error ? error.message : \"failed to parse skill file\";\n\t\tdiagnostics.push({ type: \"warning\", message, path: filePath });\n\t\treturn { skill: null, diagnostics };\n\t}\n}\n\nexport interface LoadSkillsOptions {\n\t/** Working directory for project-local skills. */\n\tcwd: string;\n\t/** Agent config directory for global skills. */\n\tagentDir: string;\n\t/** Explicit skill paths (files or directories) */\n\tskillPaths: string[];\n\t/** Include default skills directories. */\n\tincludeDefaults: boolean;\n\t/** Profile UAC gate: when provided, files it denies are never read from disk. */\n\tisPathAllowed?: (path: string) => boolean;\n}\n\n/**\n * Load skills from all configured locations.\n * Returns skills and any validation diagnostics.\n */\nexport function loadSkills(options: LoadSkillsOptions): LoadSkillsResult {\n\tconst { agentDir, skillPaths, includeDefaults } = options;\n\n\t// Resolve agentDir - if not provided, use default from config\n\tconst resolvedCwd = resolvePath(options.cwd);\n\tconst resolvedAgentDir = resolvePath(agentDir ?? getAgentDir());\n\n\tconst skillMap = new Map<string, Skill>();\n\tconst realPathSet = new Set<string>();\n\tconst allDiagnostics: ResourceDiagnostic[] = [];\n\tconst collisionDiagnostics: ResourceDiagnostic[] = [];\n\n\tfunction addSkills(result: LoadSkillsResult) {\n\t\tallDiagnostics.push(...result.diagnostics);\n\t\tfor (const skill of result.skills) {\n\t\t\t// Resolve symlinks to detect duplicate files\n\t\t\tconst realPath = canonicalizePath(skill.filePath);\n\n\t\t\t// Skip silently if we've already loaded this exact file (via symlink)\n\t\t\tif (realPathSet.has(realPath)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tconst existing = skillMap.get(skill.name);\n\t\t\tif (existing) {\n\t\t\t\tcollisionDiagnostics.push({\n\t\t\t\t\ttype: \"collision\",\n\t\t\t\t\tmessage: `name \"${skill.name}\" collision`,\n\t\t\t\t\tpath: skill.filePath,\n\t\t\t\t\tcollision: {\n\t\t\t\t\t\tresourceType: \"skill\",\n\t\t\t\t\t\tname: skill.name,\n\t\t\t\t\t\twinnerPath: existing.filePath,\n\t\t\t\t\t\tloserPath: skill.filePath,\n\t\t\t\t\t},\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tskillMap.set(skill.name, skill);\n\t\t\t\trealPathSet.add(realPath);\n\t\t\t}\n\t\t}\n\t}\n\n\tif (includeDefaults) {\n\t\taddSkills(loadSkillsFromDirInternal(join(resolvedAgentDir, \"skills\"), \"user\", options.isPathAllowed));\n\t\taddSkills(\n\t\t\tloadSkillsFromDirInternal(resolve(resolvedCwd, CONFIG_DIR_NAME, \"skills\"), \"project\", options.isPathAllowed),\n\t\t);\n\t}\n\n\tconst userSkillsDir = join(resolvedAgentDir, \"skills\");\n\tconst projectSkillsDir = resolve(resolvedCwd, CONFIG_DIR_NAME, \"skills\");\n\n\tconst getSource = (resolvedPath: string): \"user\" | \"project\" | \"path\" => {\n\t\tif (!includeDefaults) {\n\t\t\tif (isResourcePathWithin(resolvedPath, userSkillsDir)) return \"user\";\n\t\t\tif (isResourcePathWithin(resolvedPath, projectSkillsDir)) return \"project\";\n\t\t}\n\t\treturn \"path\";\n\t};\n\n\tfor (const rawPath of skillPaths) {\n\t\tconst resolvedPath = resolvePath(rawPath, resolvedCwd, { trim: true });\n\t\tif (!existsSync(resolvedPath)) {\n\t\t\tallDiagnostics.push({ type: \"warning\", message: \"skill path does not exist\", path: resolvedPath });\n\t\t\tcontinue;\n\t\t}\n\n\t\ttry {\n\t\t\tconst stats = statSync(resolvedPath);\n\t\t\tconst source = getSource(resolvedPath);\n\t\t\tif (stats.isDirectory()) {\n\t\t\t\taddSkills(loadSkillsFromDirInternal(resolvedPath, source, options.isPathAllowed));\n\t\t\t} else if (stats.isFile() && resolvedPath.endsWith(\".md\")) {\n\t\t\t\t// Profile UAC: a denied skill file is never read from disk.\n\t\t\t\tif (options.isPathAllowed && !options.isPathAllowed(resolvedPath)) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst result = loadSkillFromFile(resolvedPath, source);\n\t\t\t\tif (result.skill) {\n\t\t\t\t\taddSkills({ skills: [result.skill], diagnostics: result.diagnostics });\n\t\t\t\t} else {\n\t\t\t\t\tallDiagnostics.push(...result.diagnostics);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tallDiagnostics.push({ type: \"warning\", message: \"skill path is not a markdown file\", path: resolvedPath });\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst message = error instanceof Error ? error.message : \"failed to read skill path\";\n\t\t\tallDiagnostics.push({ type: \"warning\", message, path: resolvedPath });\n\t\t}\n\t}\n\n\treturn {\n\t\tskills: Array.from(skillMap.values()),\n\t\tdiagnostics: [...allDiagnostics, ...collisionDiagnostics],\n\t};\n}\n"]}
|
|
@@ -25,7 +25,7 @@ export interface SystemPromptBuilderDeps {
|
|
|
25
25
|
getCwd(): string;
|
|
26
26
|
/** The session's settings manager — soul, self-modification, autonomy, and auto-learn settings. */
|
|
27
27
|
getSettingsManager(): SettingsManager;
|
|
28
|
-
/** The session's resource loader — custom/append system prompts
|
|
28
|
+
/** The session's resource loader — custom/append system prompts and agents files. */
|
|
29
29
|
getResourceLoader(): ResourceLoader;
|
|
30
30
|
/** The session's memory manager — the static, frozen-per-session memory system-prompt block. */
|
|
31
31
|
getMemoryManager(): MemoryManager;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"system-prompt-builder.d.ts","sourceRoot":"","sources":["../../src/core/system-prompt-builder.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAGH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAG/D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,EAA4C,KAAK,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAC9G,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;
|
|
1
|
+
{"version":3,"file":"system-prompt-builder.d.ts","sourceRoot":"","sources":["../../src/core/system-prompt-builder.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAGH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,2BAA2B,CAAC;AAG/D,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,EAA4C,KAAK,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAC9G,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AAExE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAE3D,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAC7D,OAAO,EAAE,KAAK,wBAAwB,EAAqB,MAAM,oBAAoB,CAAC;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sBAAsB,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,GAAG,SAAS,CAEnE;IAED,yBAAyB,CAAC,UAAU,EAAE,MAAM,EAAE,GAAG,SAAS,GAAG,MAAM,EAAE,CAEpE;IAED;;;OAGG;IACH,OAAO,CAAC,yBAAyB;IAMjC,OAAO,CAAC,4BAA4B;IAoCpC,OAAO,CAAC,wBAAwB;IAQhC,OAAO,CAAC,2BAA2B;IAOnC,8FAA8F;IAC9F,OAAO,CAAC,6BAA6B;IAIrC,OAAO,CAAC,oBAAoB;IAkB5B,OAAO,CAAC,2BAA2B;IAenC,OAAO,CAAC,qCAAqC;IAoD7C,mBAAmB,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,MAAM,CAG/C;IAED;;;;;;OAMG;IACH,6BAA6B,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,MAAM,CAEzD;CACD"}
|
|
@@ -15,6 +15,7 @@ import { existsSync } from "node:fs";
|
|
|
15
15
|
import { resolvePath } from "../utils/paths.js";
|
|
16
16
|
import { resolveMemoryPromptBudget } from "./context/memory-prompt-budget.js";
|
|
17
17
|
import { enforceModelCapabilitySystemPromptBudget } from "./model-capability.js";
|
|
18
|
+
import { normalizeProviderPromptGuidelines, normalizeProviderPromptSnippet } from "./provider-tool-text.js";
|
|
18
19
|
import { UNTRUSTED_BOUNDARY_SYSTEM_RULE } from "./security/untrusted-boundary.js";
|
|
19
20
|
import { buildSystemPrompt } from "./system-prompt.js";
|
|
20
21
|
import { formatToolSelectionHints } from "./tool-selection/promotion.js";
|
|
@@ -45,26 +46,10 @@ export class SystemPromptBuilder {
|
|
|
45
46
|
return enforceModelCapabilitySystemPromptBudget(systemPrompt, this.deps.getModelCapabilityProfile());
|
|
46
47
|
}
|
|
47
48
|
normalizePromptSnippet(text) {
|
|
48
|
-
|
|
49
|
-
return undefined;
|
|
50
|
-
const oneLine = text
|
|
51
|
-
.replace(/[\r\n]+/g, " ")
|
|
52
|
-
.replace(/\s+/g, " ")
|
|
53
|
-
.trim();
|
|
54
|
-
return oneLine.length > 0 ? oneLine : undefined;
|
|
49
|
+
return normalizeProviderPromptSnippet(text);
|
|
55
50
|
}
|
|
56
51
|
normalizePromptGuidelines(guidelines) {
|
|
57
|
-
|
|
58
|
-
return [];
|
|
59
|
-
}
|
|
60
|
-
const unique = new Set();
|
|
61
|
-
for (const guideline of guidelines) {
|
|
62
|
-
const normalized = guideline.trim();
|
|
63
|
-
if (normalized.length > 0) {
|
|
64
|
-
unique.add(normalized);
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
return Array.from(unique);
|
|
52
|
+
return normalizeProviderPromptGuidelines(guidelines);
|
|
68
53
|
}
|
|
69
54
|
/**
|
|
70
55
|
* R6: the active profile's situational soul, wrapped so the model reads it as its identity for this
|
|
@@ -74,7 +59,7 @@ export class SystemPromptBuilder {
|
|
|
74
59
|
const soul = this.deps.getSettingsManager().getActiveProfileSoul();
|
|
75
60
|
if (!soul)
|
|
76
61
|
return undefined;
|
|
77
|
-
return
|
|
62
|
+
return `SITUATION SOUL\n${soul}`;
|
|
78
63
|
}
|
|
79
64
|
_buildSelfModificationPrompt(profile) {
|
|
80
65
|
const settings = this.deps.getSettingsManager().getSelfModificationSettings();
|
|
@@ -85,32 +70,22 @@ export class SystemPromptBuilder {
|
|
|
85
70
|
// from settings alone), then fall back to the legacy single sourcePath.
|
|
86
71
|
const rawCandidates = collectSelfModificationSourceCandidates(settings);
|
|
87
72
|
if (rawCandidates.length === 0) {
|
|
88
|
-
return
|
|
89
|
-
- Self-modification is enabled, but no \`selfModification.sourcePaths\`/\`selfModification.sourcePath\` value is set.
|
|
90
|
-
- Do not modify Pi core or runtime output. Ask the user to set \`selfModification.sourcePaths\` to the pi-adaptative source checkout before proceeding.`;
|
|
73
|
+
return "PI SELF-MODIFICATION: enabled but sourcePaths/sourcePath is missing. Do not modify core/runtime output; ask for the pi-adaptative source checkout path.";
|
|
91
74
|
}
|
|
92
75
|
const resolvedCandidates = rawCandidates.map((candidate) => resolvePath(candidate, this.deps.getCwd(), { trim: true }));
|
|
93
76
|
const sourcePath = resolvedCandidates.find((candidate) => existsSync(candidate) && existsSync(resolvePath("package.json", candidate))) ?? resolvedCandidates[0];
|
|
94
77
|
const sourceLooksValid = existsSync(sourcePath) && existsSync(resolvePath("package.json", sourcePath));
|
|
95
78
|
const sourceStatus = sourceLooksValid
|
|
96
79
|
? sourcePath
|
|
97
|
-
: `${sourcePath} (
|
|
80
|
+
: `${sourcePath} (invalid source checkout; user must correct \`selfModification.sourcePaths\` before editing)`;
|
|
98
81
|
const autonomy = this.deps.getSettingsManager().getAutonomySettings();
|
|
99
82
|
const settingsGate = autonomy.mode === "full"
|
|
100
|
-
? "
|
|
83
|
+
? "autonomy.mode=full grants autonomy/autoLearn tuning. Ask before credential disclosure, provider authentication changes, credential operations outside active user-plane secret_store grant, package-source changes, unrelated preferences."
|
|
101
84
|
: "Ask for explicit approval before changing global settings.";
|
|
102
85
|
if (profile.class !== "full") {
|
|
103
|
-
return `
|
|
86
|
+
return `PI SELF-MODIFICATION: edit core only under ${sourceStatus}. Inspect first; preserve concurrent work; smallest auditable change; focused validation. ${settingsGate} Always ask before publish/push/tag/release.`;
|
|
104
87
|
}
|
|
105
|
-
return `
|
|
106
|
-
- Authorized pi-adaptative source path: ${sourceStatus}
|
|
107
|
-
- Only modify Pi core/harness source under the authorized source path; never patch installed node_modules or generated runtime output as the source of truth.
|
|
108
|
-
- Before changing Pi itself, restate the objective and scope, inspect relevant source/docs/examples, and make the smallest auditable change.
|
|
109
|
-
- Preserve user changes: check git status before and after, avoid unrelated edits, and do not overwrite concurrent work.
|
|
110
|
-
- Validate with focused tests and broader checks proportional to risk before claiming success.
|
|
111
|
-
- Reload/restart/renew only after source changes are saved and auditable.
|
|
112
|
-
- ${settingsGate}
|
|
113
|
-
- Always ask for explicit approval before publishing, pushing, tagging, or releasing.`;
|
|
88
|
+
return `PI SELF-MODIFICATION: source=${sourceStatus}. Edit core/harness only there; never patch installed/generated output as source of truth. Restate scope; inspect source/docs; preserve concurrent changes; make the smallest auditable edit; run focused then proportionate checks; reload only after saved evidence. ${settingsGate} Always ask before publish/push/tag/release.`;
|
|
114
89
|
}
|
|
115
90
|
_buildStaticMemoryPrompt(profile) {
|
|
116
91
|
const budget = profile.class !== "full" && profile.contextWindow !== undefined
|
|
@@ -123,7 +98,7 @@ export class SystemPromptBuilder {
|
|
|
123
98
|
if (rules.length === 0)
|
|
124
99
|
return undefined;
|
|
125
100
|
const lines = rules.map((rule) => `- ${rule.text}`);
|
|
126
|
-
return `
|
|
101
|
+
return `MODEL TOOL SHAPE RULES\n${lines.join("\n")}`;
|
|
127
102
|
}
|
|
128
103
|
/** The evidence-gated tool-selection hint block (see `getToolSelectionHints` on the deps). */
|
|
129
104
|
_buildToolSelectionHintPrompt() {
|
|
@@ -138,22 +113,12 @@ export class SystemPromptBuilder {
|
|
|
138
113
|
const reflection = autoLearn.reflectionReview ?? autonomy.mode !== "off";
|
|
139
114
|
const model = autoLearn.model?.trim() || "active";
|
|
140
115
|
if (profile.class !== "full") {
|
|
141
|
-
return `
|
|
116
|
+
return `PI AUTONOMY ${autonomy.mode}: background learning may use ${model}; active task primary. Observations are evidence; bound changes. Approval: publish/push/tag/release, credential/authentication changes outside active secret_store authority, destructive deletion, broader authority.`;
|
|
142
117
|
}
|
|
143
118
|
if (autonomy.mode === "full") {
|
|
144
|
-
return `
|
|
145
|
-
- Setting-authorized background learners may run after long sessions or corrective/complex turns using model ${model}; they may act without asking first inside this standing grant.
|
|
146
|
-
- Standing grant: write high-confidence durable memory, create/patch user/project skills, create/patch small user/project extensions/tools, tune autonomy/autoLearn settings, edit the authorized selfModification.sourcePath, run validation, and leave audit/rollback evidence.
|
|
147
|
-
- Hard stops still require explicit foreground approval: publish/npm release, git push, tag creation, credential/provider-auth changes, destructive user-data deletion, network-exposed services, or expanding authority beyond this policy.
|
|
148
|
-
- Treat current-turn evidence as a cue, not proof; prefer deterministic or longitudinal corroboration for durable behavior changes.
|
|
149
|
-
- Active-task work remains primary: autonomy runs must not interrupt user-visible execution or claim task completion without evidence.`;
|
|
119
|
+
return `PI AUTONOMY full (standing): learners may use ${model} after long/corrective/complex sessions. Grant: high-confidence memory; user/project skills and small extensions/tools; autonomy/autoLearn tuning; authorized selfModification source edits; validation plus rollback evidence. Hard stop for publish/release/push/tag, credential disclosure/provider authentication/out-of-grant secret operations, destructive user-data deletion, exposed services, or more authority. Current-turn evidence is a cue, not proof; active task stays primary.`;
|
|
150
120
|
}
|
|
151
|
-
return `
|
|
152
|
-
- Setting-authorized background learners may run after long sessions${reflection ? " or corrective/complex turns" : ""} using model ${model}.
|
|
153
|
-
- Background learning may query durable memory and run bounded learning tools.
|
|
154
|
-
- Auto-apply is limited to high-confidence durable memory when explicitly configured; tooling, skill, prompt, extension, settings, and core-source changes stay proposal/approval-gated.
|
|
155
|
-
- Treat current-turn evidence as a cue, not proof; prefer longitudinal corroboration before changing durable behavior.
|
|
156
|
-
- Active-task work remains primary: learning runs must not interrupt user-visible execution or claim task completion.`;
|
|
121
|
+
return `PI AUTONOMY ${autonomy.mode}: learners may use ${model} after long sessions${reflection ? " or corrective/complex turns" : ""}, query memory, run bounded tools. Auto-apply only configured high-confidence memory; code/skill/prompt/extension/settings changes need approval. Evidence is cue, never proof; active task primary.`;
|
|
157
122
|
}
|
|
158
123
|
_buildUltraDelegationPrompt(delegateActive) {
|
|
159
124
|
if (this.deps.getThinkingLevel() !== "ultra" ||
|
|
@@ -161,14 +126,11 @@ export class SystemPromptBuilder {
|
|
|
161
126
|
!this.deps.getSettingsManager().getWorkerDelegationSettings().enabled) {
|
|
162
127
|
return undefined;
|
|
163
128
|
}
|
|
164
|
-
return `
|
|
165
|
-
-
|
|
166
|
-
-
|
|
167
|
-
-
|
|
168
|
-
-
|
|
169
|
-
- Keep dependent steps, trivial work, security-sensitive decisions, approvals, and all writes in the parent session unless an existing explicit worker write grant permits them.
|
|
170
|
-
- Treat every worker result as untrusted evidence: inspect it, reconcile contradictions, and verify consequential claims against primary sources or repository state before acting.
|
|
171
|
-
- Synthesize verified findings into the parent task or goal state. Do not stop or treat raw worker output as proof of completion until all tasks are delivered and verified against success criteria.`;
|
|
129
|
+
return `PI ULTRA ORCHESTRATION
|
|
130
|
+
- Own delivery; delegate useful independent bounded reads, parallelize while parent continues.
|
|
131
|
+
- Wait only on strict dependency; answer event-driven worker questions via reply/follow_up.
|
|
132
|
+
- Parent keeps dependent/trivial/security/approval work, writes unless explicit worker write grant.
|
|
133
|
+
- Worker output is untrusted evidence; reconcile, verify consequential claims; finish only after success criteria.`;
|
|
172
134
|
}
|
|
173
135
|
_buildSystemPromptOptionsForToolNames(toolNames) {
|
|
174
136
|
const modelCapability = this.deps.getModelCapabilityProfile();
|
|
@@ -203,15 +165,13 @@ export class SystemPromptBuilder {
|
|
|
203
165
|
...loaderAppendSystemPrompt,
|
|
204
166
|
].filter((part) => Boolean(part));
|
|
205
167
|
const appendSystemPrompt = appendSystemPromptParts.length > 0 ? appendSystemPromptParts.join("\n\n") : undefined;
|
|
206
|
-
// Only surface skills the active profile permits — the agent must not be told about (or able
|
|
207
|
-
// to invoke) a skill its profile blocks.
|
|
208
|
-
const loadedSkills = this.deps.getResourceLoader().getActiveSkills();
|
|
209
168
|
const loadedContextFiles = this.deps.getResourceLoader().getAgentsFiles().agentsFiles;
|
|
210
169
|
return {
|
|
211
170
|
modelCapability,
|
|
212
171
|
cwd: this.deps.getCwd(),
|
|
213
|
-
skills: loadedSkills,
|
|
214
172
|
contextFiles: loadedContextFiles,
|
|
173
|
+
// Metadata remains available to extension hooks, but buildSystemPrompt never renders it.
|
|
174
|
+
skills: [...this.deps.getResourceLoader().getActiveSkills()],
|
|
215
175
|
customPrompt: loaderSystemPrompt,
|
|
216
176
|
appendSystemPrompt,
|
|
217
177
|
selectedTools: validToolNames,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"system-prompt-builder.js","sourceRoot":"","sources":["../../src/core/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GAAG,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,CAAC,eAAe,EAAE,CAAC;QACrE,MAAM,kBAAkB,GAAG,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,CAAC,cAAc,EAAE,CAAC,WAAW,CAAC;QAEtF,OAAO;YACN,eAAe;YACf,GAAG,EAAE,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;YACvB,MAAM,EAAE,YAAY;YACpB,YAAY,EAAE,kBAAkB;YAChC,YAAY,EAAE,kBAAkB;YAChC,kBAAkB;YAClB,aAAa,EAAE,cAAc;YAC7B,YAAY;YACZ,gBAAgB;YAChB,UAAU,EAAE,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,mBAAmB,EAAE,CAAC;SAChD,CAAC;IACH,CAAC;IAED,mBAAmB,CAAC,SAAmB;QACtC,IAAI,CAAC,wBAAwB,GAAG,IAAI,CAAC,qCAAqC,CAAC,SAAS,CAAC,CAAC;QACtF,OAAO,iBAAiB,CAAC,IAAI,CAAC,wBAAwB,CAAC,CAAC;IACzD,CAAC;IAED;;;;;;OAMG;IACH,6BAA6B,CAAC,SAAmB;QAChD,OAAO,iBAAiB,CAAC,IAAI,CAAC,qCAAqC,CAAC,SAAS,CAAC,CAAC,CAAC;IACjF,CAAC;CACD","sourcesContent":["/**\n * Session system-prompt construction.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the assembly of the\n * session's base system prompt from live session state — the active profile's situational soul, the\n * self-modification and autonomy guardrail blocks, the memory block, the loader's custom/append\n * prompts, and the per-tool snippet/guideline surface — into the {@link BuildSystemPromptOptions}\n * that the pure {@link buildSystemPrompt} renderer (core/system-prompt.ts, a different job: the\n * stateless string builder) consumes. Holds the last-built `_baseSystemPromptOptions` so a\n * before_agent_start extension hook can read it. Takes narrow accessor deps (each read fresh, since\n * several collaborators — tool registries, memory manager, extension runner — are reassigned across\n * the session lifecycle) rather than the whole AgentSession.\n */\n\nimport { existsSync } from \"node:fs\";\nimport type { ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { resolveMemoryPromptBudget } from \"./context/memory-prompt-budget.ts\";\nimport type { Extension } from \"./extensions/types.ts\";\nimport type { MemoryManager } from \"./memory/memory-manager.ts\";\nimport { enforceModelCapabilitySystemPromptBudget, type ModelCapabilityProfile } from \"./model-capability.ts\";\nimport type { ModelAdaptationRule } from \"./models/adaptation-store.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { UNTRUSTED_BOUNDARY_SYSTEM_RULE } from \"./security/untrusted-boundary.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport { type BuildSystemPromptOptions, buildSystemPrompt } from \"./system-prompt.ts\";\nimport { formatToolSelectionHints, type ToolSelectionHint } from \"./tool-selection/promotion.ts\";\n\nexport interface SystemPromptBuilderDeps {\n\t/** The session's working directory (read fresh; base for self-modification source resolution). */\n\tgetCwd(): string;\n\t/** The session's settings manager — soul, self-modification, autonomy, and auto-learn settings. */\n\tgetSettingsManager(): SettingsManager;\n\t/** The session's resource loader — custom/append system prompts, active skills, agents files. */\n\tgetResourceLoader(): ResourceLoader;\n\t/** The session's memory manager — the static, frozen-per-session memory system-prompt block. */\n\tgetMemoryManager(): MemoryManager;\n\t/** Whether a tool name is currently registered on the session. */\n\thasTool(name: string): boolean;\n\t/** The one-line prompt snippet registered for a tool, if any. */\n\tgetToolPromptSnippet(name: string): string | undefined;\n\t/** The extra guideline bullets registered for a tool, if any. */\n\tgetToolPromptGuidelines(name: string): string[] | undefined;\n\t/** The standing tool-shape rules learned for the session's current model. */\n\tgetModelAdaptationRules(): readonly ModelAdaptationRule[];\n\t/**\n\t * The evidence-gated tool-selection hints active for the session's current model (see\n\t * `tool-selection/promotion.ts` and `ToolSelectionController.getActiveHints`). Optional: a\n\t * session that has not wired a `ToolSelectionController` into this builder simply renders no\n\t * hint block, same as an empty list. Changes RARELY (only when the underlying evidence flips\n\t * which tool is promoted for an intent) — never per turn — so it does not threaten the\n\t * single-cached-system-prompt-block invariant (see system-prompt.ts).\n\t */\n\tgetToolSelectionHints?(): readonly ToolSelectionHint[];\n\t/** The session's currently active extensions. */\n\tgetActiveExtensions(): ReadonlyArray<Extension>;\n\t/** The authoritative profile used by tools, lanes, and stable prompt shaping. */\n\tgetModelCapabilityProfile(): ModelCapabilityProfile;\n\t/** Live reasoning/orchestration selection; Ultra adds a bounded proactive-delegation policy. */\n\tgetThinkingLevel(): ThinkingLevel;\n}\n\nexport function collectSelfModificationSourceCandidates(settings: {\n\tsourcePath?: string;\n\tsourcePaths?: string[];\n}): string[] {\n\tconst candidates: string[] = [];\n\tif (Array.isArray(settings.sourcePaths)) {\n\t\tfor (const candidate of settings.sourcePaths) {\n\t\t\tconst normalized = candidate?.trim();\n\t\t\tif (normalized) candidates.push(normalized);\n\t\t}\n\t}\n\tconst legacyCandidate = settings.sourcePath?.trim();\n\tif (legacyCandidate) candidates.push(legacyCandidate);\n\treturn candidates;\n}\n\nexport class SystemPromptBuilder {\n\tprivate readonly deps: SystemPromptBuilderDeps;\n\tprivate _baseSystemPromptOptions!: BuildSystemPromptOptions;\n\n\tconstructor(deps: SystemPromptBuilderDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\t/** The options used to render the last base prompt — read by a before_agent_start extension hook. */\n\tgetBaseSystemPromptOptions(): BuildSystemPromptOptions {\n\t\treturn this._baseSystemPromptOptions;\n\t}\n\n\t/** Recheck the final prompt after extension and routed-turn overrides, immediately before use. */\n\tenforceSystemPromptBudget(systemPrompt: string): string {\n\t\treturn enforceModelCapabilitySystemPromptBudget(systemPrompt, this.deps.getModelCapabilityProfile());\n\t}\n\n\tnormalizePromptSnippet(text: string | undefined): string | undefined {\n\t\tif (!text) return undefined;\n\t\tconst oneLine = text\n\t\t\t.replace(/[\\r\\n]+/g, \" \")\n\t\t\t.replace(/\\s+/g, \" \")\n\t\t\t.trim();\n\t\treturn oneLine.length > 0 ? oneLine : undefined;\n\t}\n\n\tnormalizePromptGuidelines(guidelines: string[] | undefined): string[] {\n\t\tif (!guidelines || guidelines.length === 0) {\n\t\t\treturn [];\n\t\t}\n\n\t\tconst unique = new Set<string>();\n\t\tfor (const guideline of guidelines) {\n\t\t\tconst normalized = guideline.trim();\n\t\t\tif (normalized.length > 0) {\n\t\t\t\tunique.add(normalized);\n\t\t\t}\n\t\t}\n\t\treturn Array.from(unique);\n\t}\n\n\t/**\n\t * R6: the active profile's situational soul, wrapped so the model reads it as its identity for this\n\t * situation. Empty when no active profile defines a soul.\n\t */\n\tprivate _buildSituationSoulPrompt(): string | undefined {\n\t\tconst soul = this.deps.getSettingsManager().getActiveProfileSoul();\n\t\tif (!soul) return undefined;\n\t\treturn `<situation_soul>\\n${soul}\\n</situation_soul>`;\n\t}\n\n\tprivate _buildSelfModificationPrompt(profile: ModelCapabilityProfile): string | undefined {\n\t\tconst settings = this.deps.getSettingsManager().getSelfModificationSettings();\n\t\tif (!settings.enabled) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\t// Resolve from an ordered candidate list first (portable WSL/Termux switching\n\t\t// from settings alone), then fall back to the legacy single sourcePath.\n\t\tconst rawCandidates = collectSelfModificationSourceCandidates(settings);\n\n\t\tif (rawCandidates.length === 0) {\n\t\t\treturn `Pi self-modification guardrails (local setting active, source missing):\n- Self-modification is enabled, but no \\`selfModification.sourcePaths\\`/\\`selfModification.sourcePath\\` value is set.\n- Do not modify Pi core or runtime output. Ask the user to set \\`selfModification.sourcePaths\\` to the pi-adaptative source checkout before proceeding.`;\n\t\t}\n\n\t\tconst resolvedCandidates = rawCandidates.map((candidate) =>\n\t\t\tresolvePath(candidate, this.deps.getCwd(), { trim: true }),\n\t\t);\n\t\tconst sourcePath =\n\t\t\tresolvedCandidates.find(\n\t\t\t\t(candidate) => existsSync(candidate) && existsSync(resolvePath(\"package.json\", candidate)),\n\t\t\t) ?? resolvedCandidates[0];\n\t\tconst sourceLooksValid = existsSync(sourcePath) && existsSync(resolvePath(\"package.json\", sourcePath));\n\t\tconst sourceStatus = sourceLooksValid\n\t\t\t? sourcePath\n\t\t\t: `${sourcePath} (missing or not a source checkout; ask the user to correct \\`selfModification.sourcePaths\\` before editing)`;\n\t\tconst autonomy = this.deps.getSettingsManager().getAutonomySettings();\n\t\tconst settingsGate =\n\t\t\tautonomy.mode === \"full\"\n\t\t\t\t? \"In autonomy.mode=full, autonomy/autoLearn setting tuning is covered by the standing autonomy grant; ask before changing credentials, provider auth, package sources, or unrelated preferences.\"\n\t\t\t\t: \"Ask for explicit approval before changing global settings.\";\n\t\tif (profile.class !== \"full\") {\n\t\t\treturn `Pi self-modification boundary: edit Pi core only under ${sourceStatus}. Inspect first, preserve concurrent work, make a small auditable change, and run focused validation. ${settingsGate} Always ask before publishing, pushing, tagging, or releasing.`;\n\t\t}\n\t\treturn `Pi self-modification guardrails (local setting active):\n- Authorized pi-adaptative source path: ${sourceStatus}\n- Only modify Pi core/harness source under the authorized source path; never patch installed node_modules or generated runtime output as the source of truth.\n- Before changing Pi itself, restate the objective and scope, inspect relevant source/docs/examples, and make the smallest auditable change.\n- Preserve user changes: check git status before and after, avoid unrelated edits, and do not overwrite concurrent work.\n- Validate with focused tests and broader checks proportional to risk before claiming success.\n- Reload/restart/renew only after source changes are saved and auditable.\n- ${settingsGate}\n- Always ask for explicit approval before publishing, pushing, tagging, or releasing.`;\n\t}\n\n\tprivate _buildStaticMemoryPrompt(profile: ModelCapabilityProfile): string | undefined {\n\t\tconst budget =\n\t\t\tprofile.class !== \"full\" && profile.contextWindow !== undefined\n\t\t\t\t? resolveMemoryPromptBudget({ contextWindow: profile.contextWindow, configuredMaxResults: 3 })\n\t\t\t\t: undefined;\n\t\treturn this.deps.getMemoryManager().buildSystemPromptBlock(budget) || undefined;\n\t}\n\n\tprivate _buildModelAdaptationPrompt(): string | undefined {\n\t\tconst rules = this.deps.getModelAdaptationRules();\n\t\tif (rules.length === 0) return undefined;\n\t\tconst lines = rules.map((rule) => `- ${rule.text}`);\n\t\treturn `Per-model tool-call shape rules (learned for the current model):\\n${lines.join(\"\\n\")}`;\n\t}\n\n\t/** The evidence-gated tool-selection hint block (see `getToolSelectionHints` on the deps). */\n\tprivate _buildToolSelectionHintPrompt(): string | undefined {\n\t\treturn formatToolSelectionHints(this.deps.getToolSelectionHints?.() ?? []);\n\t}\n\n\tprivate _buildAutonomyPrompt(profile: ModelCapabilityProfile): string | undefined {\n\t\tconst autoLearn = this.deps.getSettingsManager().getAutoLearnSettings();\n\t\tconst autonomy = this.deps.getSettingsManager().getAutonomySettings();\n\t\tif (!profile.backgroundLanesEnabled || (!autoLearn.enabled && autonomy.mode !== \"full\")) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst reflection = autoLearn.reflectionReview ?? autonomy.mode !== \"off\";\n\t\tconst model = autoLearn.model?.trim() || \"active\";\n\t\tif (profile.class !== \"full\") {\n\t\t\treturn `Pi autonomy policy (${autonomy.mode}): configured background learning may run using model ${model}, but the active task stays primary. Treat observations as evidence, keep changes bounded, and require explicit approval for publication, push/tag/release, credentials, destructive deletion, or broader authority.`;\n\t\t}\n\t\tif (autonomy.mode === \"full\") {\n\t\t\treturn `Pi autonomy policy (mode full, standing autonomy):\n- Setting-authorized background learners may run after long sessions or corrective/complex turns using model ${model}; they may act without asking first inside this standing grant.\n- Standing grant: write high-confidence durable memory, create/patch user/project skills, create/patch small user/project extensions/tools, tune autonomy/autoLearn settings, edit the authorized selfModification.sourcePath, run validation, and leave audit/rollback evidence.\n- Hard stops still require explicit foreground approval: publish/npm release, git push, tag creation, credential/provider-auth changes, destructive user-data deletion, network-exposed services, or expanding authority beyond this policy.\n- Treat current-turn evidence as a cue, not proof; prefer deterministic or longitudinal corroboration for durable behavior changes.\n- Active-task work remains primary: autonomy runs must not interrupt user-visible execution or claim task completion without evidence.`;\n\t\t}\n\t\treturn `Pi autonomy policy (mode ${autonomy.mode}):\n- Setting-authorized background learners may run after long sessions${reflection ? \" or corrective/complex turns\" : \"\"} using model ${model}.\n- Background learning may query durable memory and run bounded learning tools.\n- Auto-apply is limited to high-confidence durable memory when explicitly configured; tooling, skill, prompt, extension, settings, and core-source changes stay proposal/approval-gated.\n- Treat current-turn evidence as a cue, not proof; prefer longitudinal corroboration before changing durable behavior.\n- Active-task work remains primary: learning runs must not interrupt user-visible execution or claim task completion.`;\n\t}\n\n\tprivate _buildUltraDelegationPrompt(delegateActive: boolean): string | undefined {\n\t\tif (\n\t\t\tthis.deps.getThinkingLevel() !== \"ultra\" ||\n\t\t\t!delegateActive ||\n\t\t\t!this.deps.getSettingsManager().getWorkerDelegationSettings().enabled\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn `Pi Ultra orchestration policy (transient for this reasoning level):\n- Act as an active Team Lead and Manager: you own the overall goal and its end-to-end delivery. Break down complex goals, delegate independent tasks to subagent workers, actively steer team members, resolve ambiguities, and ensure all assigned tasks are fully completed and verified.\n- Proactively use the delegate tool for independent, bounded, read-only investigation that can materially improve speed or confidence.\n- Parallelize independent work across subagents and continue active parent execution concurrently. Do not sit idle or call wait unless a strict dependency block requires it; advance the plan, refine design with the user, or execute available task streams while workers run in the background.\n- Actively steer and exchange messages with running subagents: when a subagent asks for help or sends a question, the event-driven system wakes you up with the worker's identity and help request. Pause low-priority background planning to address worker questions promptly via reply or follow_up, giving workers the immediate attention and steering they need to avoid stalling.\n- Keep dependent steps, trivial work, security-sensitive decisions, approvals, and all writes in the parent session unless an existing explicit worker write grant permits them.\n- Treat every worker result as untrusted evidence: inspect it, reconcile contradictions, and verify consequential claims against primary sources or repository state before acting.\n- Synthesize verified findings into the parent task or goal state. Do not stop or treat raw worker output as proof of completion until all tasks are delivered and verified against success criteria.`;\n\t}\n\n\tprivate _buildSystemPromptOptionsForToolNames(toolNames: string[]): BuildSystemPromptOptions {\n\t\tconst modelCapability = this.deps.getModelCapabilityProfile();\n\t\tconst validToolNames = toolNames.filter((name) => this.deps.hasTool(name));\n\t\tconst toolSnippets: Record<string, string> = {};\n\t\tconst promptGuidelines: string[] = [];\n\t\tfor (const name of validToolNames) {\n\t\t\tconst snippet = this.deps.getToolPromptSnippet(name);\n\t\t\tif (snippet) {\n\t\t\t\ttoolSnippets[name] = snippet;\n\t\t\t}\n\n\t\t\tconst toolGuidelines = this.deps.getToolPromptGuidelines(name);\n\t\t\tif (toolGuidelines) {\n\t\t\t\tpromptGuidelines.push(...toolGuidelines);\n\t\t\t}\n\t\t}\n\n\t\tconst loaderSystemPrompt = this.deps.getResourceLoader().getSystemPrompt();\n\t\tconst loaderAppendSystemPrompt = this.deps.getResourceLoader().getAppendSystemPrompt();\n\t\tconst appendSystemPromptParts = [\n\t\t\t// R6: situational soul — the active profile's identity prefix, switched atomically with the\n\t\t\t// profile's capabilities/model. Most prominent, so it comes first.\n\t\t\tthis._buildSituationSoulPrompt(),\n\t\t\t// Always-on untrusted-content boundary contract (gives the <untrusted_content> fences meaning).\n\t\t\tUNTRUSTED_BOUNDARY_SYSTEM_RULE,\n\t\t\tthis._buildSelfModificationPrompt(modelCapability),\n\t\t\tthis._buildAutonomyPrompt(modelCapability),\n\t\t\tthis._buildUltraDelegationPrompt(validToolNames.includes(\"delegate\")),\n\t\t\tthis._buildModelAdaptationPrompt(),\n\t\t\tthis._buildToolSelectionHintPrompt(),\n\t\t\t// Memory subsystem: static, frozen-per-session block (e.g. file-store MEMORY.md/USER.md).\n\t\t\tthis._buildStaticMemoryPrompt(modelCapability),\n\t\t\t...loaderAppendSystemPrompt,\n\t\t].filter((part): part is string => Boolean(part));\n\t\tconst appendSystemPrompt = appendSystemPromptParts.length > 0 ? appendSystemPromptParts.join(\"\\n\\n\") : undefined;\n\t\t// Only surface skills the active profile permits — the agent must not be told about (or able\n\t\t// to invoke) a skill its profile blocks.\n\t\tconst loadedSkills = this.deps.getResourceLoader().getActiveSkills();\n\t\tconst loadedContextFiles = this.deps.getResourceLoader().getAgentsFiles().agentsFiles;\n\n\t\treturn {\n\t\t\tmodelCapability,\n\t\t\tcwd: this.deps.getCwd(),\n\t\t\tskills: loadedSkills,\n\t\t\tcontextFiles: loadedContextFiles,\n\t\t\tcustomPrompt: loaderSystemPrompt,\n\t\t\tappendSystemPrompt,\n\t\t\tselectedTools: validToolNames,\n\t\t\ttoolSnippets,\n\t\t\tpromptGuidelines,\n\t\t\textensions: [...this.deps.getActiveExtensions()],\n\t\t};\n\t}\n\n\trebuildSystemPrompt(toolNames: string[]): string {\n\t\tthis._baseSystemPromptOptions = this._buildSystemPromptOptionsForToolNames(toolNames);\n\t\treturn buildSystemPrompt(this._baseSystemPromptOptions);\n\t}\n\n\t/**\n\t * Build a system prompt for a specific tool surface WITHOUT touching the session's base prompt\n\t * state. Used for a router-swapped turn (G4): the routed model runs against a filtered tool set,\n\t * so it must also receive a system prompt whose tool guidelines/snippets match that filtered\n\t * surface — but the change is per-turn, so it must not mutate `_baseSystemPromptOptions` (which\n\t * later turns and extension events read).\n\t */\n\tbuildSystemPromptForToolNames(toolNames: string[]): string {\n\t\treturn buildSystemPrompt(this._buildSystemPromptOptionsForToolNames(toolNames));\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"system-prompt-builder.js","sourceRoot":"","sources":["../../src/core/system-prompt-builder.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AAErC,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AAG9E,OAAO,EAAE,wCAAwC,EAA+B,MAAM,uBAAuB,CAAC;AAE9G,OAAO,EAAE,iCAAiC,EAAE,8BAA8B,EAAE,MAAM,yBAAyB,CAAC;AAE5G,OAAO,EAAE,8BAA8B,EAAE,MAAM,kCAAkC,CAAC;AAElF,OAAO,EAAiC,iBAAiB,EAAE,MAAM,oBAAoB,CAAC;AACtF,OAAO,EAAE,wBAAwB,EAA0B,MAAM,+BAA+B,CAAC;AAoCjG,MAAM,UAAU,uCAAuC,CAA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AAC,CAAC,uBAAuB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QACjH,MAAM,kBAAkB,GAAG,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,CAAC,cAAc,EAAE,CAAC,WAAW,CAAC;QAEtF,OAAO;YACN,eAAe;YACf,GAAG,EAAE,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE;YACvB,YAAY,EAAE,kBAAkB;YAChC,yFAAyF;YACzF,MAAM,EAAE,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,CAAC,eAAe,EAAE,CAAC;YAC5D,YAAY,EAAE,kBAAkB;YAChC,kBAAkB;YAClB,aAAa,EAAE,cAAc;YAC7B,YAAY;YACZ,gBAAgB;YAChB,UAAU,EAAE,CAAC,GAAG,IAAI,CAAC,IAAI,CAAC,mBAAmB,EAAE,CAAC;SAChD,CAAC;IACH,CAAC;IAED,mBAAmB,CAAC,SAAmB;QACtC,IAAI,CAAC,wBAAwB,GAAG,IAAI,CAAC,qCAAqC,CAAC,SAAS,CAAC,CAAC;QACtF,OAAO,iBAAiB,CAAC,IAAI,CAAC,wBAAwB,CAAC,CAAC;IACzD,CAAC;IAED;;;;;;OAMG;IACH,6BAA6B,CAAC,SAAmB;QAChD,OAAO,iBAAiB,CAAC,IAAI,CAAC,qCAAqC,CAAC,SAAS,CAAC,CAAC,CAAC;IACjF,CAAC;CACD","sourcesContent":["/**\n * Session system-prompt construction.\n *\n * Extracted verbatim from agent-session.ts (god-file decomposition). Owns the assembly of the\n * session's base system prompt from live session state — the active profile's situational soul, the\n * self-modification and autonomy guardrail blocks, the memory block, the loader's custom/append\n * prompts, and the per-tool snippet/guideline surface — into the {@link BuildSystemPromptOptions}\n * that the pure {@link buildSystemPrompt} renderer (core/system-prompt.ts, a different job: the\n * stateless string builder) consumes. Holds the last-built `_baseSystemPromptOptions` so a\n * before_agent_start extension hook can read it. Takes narrow accessor deps (each read fresh, since\n * several collaborators — tool registries, memory manager, extension runner — are reassigned across\n * the session lifecycle) rather than the whole AgentSession.\n */\n\nimport { existsSync } from \"node:fs\";\nimport type { ThinkingLevel } from \"@caupulican/pi-agent-core\";\nimport { resolvePath } from \"../utils/paths.ts\";\nimport { resolveMemoryPromptBudget } from \"./context/memory-prompt-budget.ts\";\nimport type { Extension } from \"./extensions/types.ts\";\nimport type { MemoryManager } from \"./memory/memory-manager.ts\";\nimport { enforceModelCapabilitySystemPromptBudget, type ModelCapabilityProfile } from \"./model-capability.ts\";\nimport type { ModelAdaptationRule } from \"./models/adaptation-store.ts\";\nimport { normalizeProviderPromptGuidelines, normalizeProviderPromptSnippet } from \"./provider-tool-text.ts\";\nimport type { ResourceLoader } from \"./resource-loader.ts\";\nimport { UNTRUSTED_BOUNDARY_SYSTEM_RULE } from \"./security/untrusted-boundary.ts\";\nimport type { SettingsManager } from \"./settings-manager.ts\";\nimport { type BuildSystemPromptOptions, buildSystemPrompt } from \"./system-prompt.ts\";\nimport { formatToolSelectionHints, type ToolSelectionHint } from \"./tool-selection/promotion.ts\";\n\nexport interface SystemPromptBuilderDeps {\n\t/** The session's working directory (read fresh; base for self-modification source resolution). */\n\tgetCwd(): string;\n\t/** The session's settings manager — soul, self-modification, autonomy, and auto-learn settings. */\n\tgetSettingsManager(): SettingsManager;\n\t/** The session's resource loader — custom/append system prompts and agents files. */\n\tgetResourceLoader(): ResourceLoader;\n\t/** The session's memory manager — the static, frozen-per-session memory system-prompt block. */\n\tgetMemoryManager(): MemoryManager;\n\t/** Whether a tool name is currently registered on the session. */\n\thasTool(name: string): boolean;\n\t/** The one-line prompt snippet registered for a tool, if any. */\n\tgetToolPromptSnippet(name: string): string | undefined;\n\t/** The extra guideline bullets registered for a tool, if any. */\n\tgetToolPromptGuidelines(name: string): string[] | undefined;\n\t/** The standing tool-shape rules learned for the session's current model. */\n\tgetModelAdaptationRules(): readonly ModelAdaptationRule[];\n\t/**\n\t * The evidence-gated tool-selection hints active for the session's current model (see\n\t * `tool-selection/promotion.ts` and `ToolSelectionController.getActiveHints`). Optional: a\n\t * session that has not wired a `ToolSelectionController` into this builder simply renders no\n\t * hint block, same as an empty list. Changes RARELY (only when the underlying evidence flips\n\t * which tool is promoted for an intent) — never per turn — so it does not threaten the\n\t * single-cached-system-prompt-block invariant (see system-prompt.ts).\n\t */\n\tgetToolSelectionHints?(): readonly ToolSelectionHint[];\n\t/** The session's currently active extensions. */\n\tgetActiveExtensions(): ReadonlyArray<Extension>;\n\t/** The authoritative profile used by tools, lanes, and stable prompt shaping. */\n\tgetModelCapabilityProfile(): ModelCapabilityProfile;\n\t/** Live reasoning/orchestration selection; Ultra adds a bounded proactive-delegation policy. */\n\tgetThinkingLevel(): ThinkingLevel;\n}\n\nexport function collectSelfModificationSourceCandidates(settings: {\n\tsourcePath?: string;\n\tsourcePaths?: string[];\n}): string[] {\n\tconst candidates: string[] = [];\n\tif (Array.isArray(settings.sourcePaths)) {\n\t\tfor (const candidate of settings.sourcePaths) {\n\t\t\tconst normalized = candidate?.trim();\n\t\t\tif (normalized) candidates.push(normalized);\n\t\t}\n\t}\n\tconst legacyCandidate = settings.sourcePath?.trim();\n\tif (legacyCandidate) candidates.push(legacyCandidate);\n\treturn candidates;\n}\n\nexport class SystemPromptBuilder {\n\tprivate readonly deps: SystemPromptBuilderDeps;\n\tprivate _baseSystemPromptOptions!: BuildSystemPromptOptions;\n\n\tconstructor(deps: SystemPromptBuilderDeps) {\n\t\tthis.deps = deps;\n\t}\n\n\t/** The options used to render the last base prompt — read by a before_agent_start extension hook. */\n\tgetBaseSystemPromptOptions(): BuildSystemPromptOptions {\n\t\treturn this._baseSystemPromptOptions;\n\t}\n\n\t/** Recheck the final prompt after extension and routed-turn overrides, immediately before use. */\n\tenforceSystemPromptBudget(systemPrompt: string): string {\n\t\treturn enforceModelCapabilitySystemPromptBudget(systemPrompt, this.deps.getModelCapabilityProfile());\n\t}\n\n\tnormalizePromptSnippet(text: string | undefined): string | undefined {\n\t\treturn normalizeProviderPromptSnippet(text);\n\t}\n\n\tnormalizePromptGuidelines(guidelines: string[] | undefined): string[] {\n\t\treturn normalizeProviderPromptGuidelines(guidelines);\n\t}\n\n\t/**\n\t * R6: the active profile's situational soul, wrapped so the model reads it as its identity for this\n\t * situation. Empty when no active profile defines a soul.\n\t */\n\tprivate _buildSituationSoulPrompt(): string | undefined {\n\t\tconst soul = this.deps.getSettingsManager().getActiveProfileSoul();\n\t\tif (!soul) return undefined;\n\t\treturn `SITUATION SOUL\\n${soul}`;\n\t}\n\n\tprivate _buildSelfModificationPrompt(profile: ModelCapabilityProfile): string | undefined {\n\t\tconst settings = this.deps.getSettingsManager().getSelfModificationSettings();\n\t\tif (!settings.enabled) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\t// Resolve from an ordered candidate list first (portable WSL/Termux switching\n\t\t// from settings alone), then fall back to the legacy single sourcePath.\n\t\tconst rawCandidates = collectSelfModificationSourceCandidates(settings);\n\n\t\tif (rawCandidates.length === 0) {\n\t\t\treturn \"PI SELF-MODIFICATION: enabled but sourcePaths/sourcePath is missing. Do not modify core/runtime output; ask for the pi-adaptative source checkout path.\";\n\t\t}\n\n\t\tconst resolvedCandidates = rawCandidates.map((candidate) =>\n\t\t\tresolvePath(candidate, this.deps.getCwd(), { trim: true }),\n\t\t);\n\t\tconst sourcePath =\n\t\t\tresolvedCandidates.find(\n\t\t\t\t(candidate) => existsSync(candidate) && existsSync(resolvePath(\"package.json\", candidate)),\n\t\t\t) ?? resolvedCandidates[0];\n\t\tconst sourceLooksValid = existsSync(sourcePath) && existsSync(resolvePath(\"package.json\", sourcePath));\n\t\tconst sourceStatus = sourceLooksValid\n\t\t\t? sourcePath\n\t\t\t: `${sourcePath} (invalid source checkout; user must correct \\`selfModification.sourcePaths\\` before editing)`;\n\t\tconst autonomy = this.deps.getSettingsManager().getAutonomySettings();\n\t\tconst settingsGate =\n\t\t\tautonomy.mode === \"full\"\n\t\t\t\t? \"autonomy.mode=full grants autonomy/autoLearn tuning. Ask before credential disclosure, provider authentication changes, credential operations outside active user-plane secret_store grant, package-source changes, unrelated preferences.\"\n\t\t\t\t: \"Ask for explicit approval before changing global settings.\";\n\t\tif (profile.class !== \"full\") {\n\t\t\treturn `PI SELF-MODIFICATION: edit core only under ${sourceStatus}. Inspect first; preserve concurrent work; smallest auditable change; focused validation. ${settingsGate} Always ask before publish/push/tag/release.`;\n\t\t}\n\t\treturn `PI SELF-MODIFICATION: source=${sourceStatus}. Edit core/harness only there; never patch installed/generated output as source of truth. Restate scope; inspect source/docs; preserve concurrent changes; make the smallest auditable edit; run focused then proportionate checks; reload only after saved evidence. ${settingsGate} Always ask before publish/push/tag/release.`;\n\t}\n\n\tprivate _buildStaticMemoryPrompt(profile: ModelCapabilityProfile): string | undefined {\n\t\tconst budget =\n\t\t\tprofile.class !== \"full\" && profile.contextWindow !== undefined\n\t\t\t\t? resolveMemoryPromptBudget({ contextWindow: profile.contextWindow, configuredMaxResults: 3 })\n\t\t\t\t: undefined;\n\t\treturn this.deps.getMemoryManager().buildSystemPromptBlock(budget) || undefined;\n\t}\n\n\tprivate _buildModelAdaptationPrompt(): string | undefined {\n\t\tconst rules = this.deps.getModelAdaptationRules();\n\t\tif (rules.length === 0) return undefined;\n\t\tconst lines = rules.map((rule) => `- ${rule.text}`);\n\t\treturn `MODEL TOOL SHAPE RULES\\n${lines.join(\"\\n\")}`;\n\t}\n\n\t/** The evidence-gated tool-selection hint block (see `getToolSelectionHints` on the deps). */\n\tprivate _buildToolSelectionHintPrompt(): string | undefined {\n\t\treturn formatToolSelectionHints(this.deps.getToolSelectionHints?.() ?? []);\n\t}\n\n\tprivate _buildAutonomyPrompt(profile: ModelCapabilityProfile): string | undefined {\n\t\tconst autoLearn = this.deps.getSettingsManager().getAutoLearnSettings();\n\t\tconst autonomy = this.deps.getSettingsManager().getAutonomySettings();\n\t\tif (!profile.backgroundLanesEnabled || (!autoLearn.enabled && autonomy.mode !== \"full\")) {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst reflection = autoLearn.reflectionReview ?? autonomy.mode !== \"off\";\n\t\tconst model = autoLearn.model?.trim() || \"active\";\n\t\tif (profile.class !== \"full\") {\n\t\t\treturn `PI AUTONOMY ${autonomy.mode}: background learning may use ${model}; active task primary. Observations are evidence; bound changes. Approval: publish/push/tag/release, credential/authentication changes outside active secret_store authority, destructive deletion, broader authority.`;\n\t\t}\n\t\tif (autonomy.mode === \"full\") {\n\t\t\treturn `PI AUTONOMY full (standing): learners may use ${model} after long/corrective/complex sessions. Grant: high-confidence memory; user/project skills and small extensions/tools; autonomy/autoLearn tuning; authorized selfModification source edits; validation plus rollback evidence. Hard stop for publish/release/push/tag, credential disclosure/provider authentication/out-of-grant secret operations, destructive user-data deletion, exposed services, or more authority. Current-turn evidence is a cue, not proof; active task stays primary.`;\n\t\t}\n\t\treturn `PI AUTONOMY ${autonomy.mode}: learners may use ${model} after long sessions${reflection ? \" or corrective/complex turns\" : \"\"}, query memory, run bounded tools. Auto-apply only configured high-confidence memory; code/skill/prompt/extension/settings changes need approval. Evidence is cue, never proof; active task primary.`;\n\t}\n\n\tprivate _buildUltraDelegationPrompt(delegateActive: boolean): string | undefined {\n\t\tif (\n\t\t\tthis.deps.getThinkingLevel() !== \"ultra\" ||\n\t\t\t!delegateActive ||\n\t\t\t!this.deps.getSettingsManager().getWorkerDelegationSettings().enabled\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn `PI ULTRA ORCHESTRATION\n- Own delivery; delegate useful independent bounded reads, parallelize while parent continues.\n- Wait only on strict dependency; answer event-driven worker questions via reply/follow_up.\n- Parent keeps dependent/trivial/security/approval work, writes unless explicit worker write grant.\n- Worker output is untrusted evidence; reconcile, verify consequential claims; finish only after success criteria.`;\n\t}\n\n\tprivate _buildSystemPromptOptionsForToolNames(toolNames: string[]): BuildSystemPromptOptions {\n\t\tconst modelCapability = this.deps.getModelCapabilityProfile();\n\t\tconst validToolNames = toolNames.filter((name) => this.deps.hasTool(name));\n\t\tconst toolSnippets: Record<string, string> = {};\n\t\tconst promptGuidelines: string[] = [];\n\t\tfor (const name of validToolNames) {\n\t\t\tconst snippet = this.deps.getToolPromptSnippet(name);\n\t\t\tif (snippet) {\n\t\t\t\ttoolSnippets[name] = snippet;\n\t\t\t}\n\n\t\t\tconst toolGuidelines = this.deps.getToolPromptGuidelines(name);\n\t\t\tif (toolGuidelines) {\n\t\t\t\tpromptGuidelines.push(...toolGuidelines);\n\t\t\t}\n\t\t}\n\n\t\tconst loaderSystemPrompt = this.deps.getResourceLoader().getSystemPrompt();\n\t\tconst loaderAppendSystemPrompt = this.deps.getResourceLoader().getAppendSystemPrompt();\n\t\tconst appendSystemPromptParts = [\n\t\t\t// R6: situational soul — the active profile's identity prefix, switched atomically with the\n\t\t\t// profile's capabilities/model. Most prominent, so it comes first.\n\t\t\tthis._buildSituationSoulPrompt(),\n\t\t\t// Always-on untrusted-content boundary contract (gives the <untrusted_content> fences meaning).\n\t\t\tUNTRUSTED_BOUNDARY_SYSTEM_RULE,\n\t\t\tthis._buildSelfModificationPrompt(modelCapability),\n\t\t\tthis._buildAutonomyPrompt(modelCapability),\n\t\t\tthis._buildUltraDelegationPrompt(validToolNames.includes(\"delegate\")),\n\t\t\tthis._buildModelAdaptationPrompt(),\n\t\t\tthis._buildToolSelectionHintPrompt(),\n\t\t\t// Memory subsystem: static, frozen-per-session block (e.g. file-store MEMORY.md/USER.md).\n\t\t\tthis._buildStaticMemoryPrompt(modelCapability),\n\t\t\t...loaderAppendSystemPrompt,\n\t\t].filter((part): part is string => Boolean(part));\n\t\tconst appendSystemPrompt = appendSystemPromptParts.length > 0 ? appendSystemPromptParts.join(\"\\n\\n\") : undefined;\n\t\tconst loadedContextFiles = this.deps.getResourceLoader().getAgentsFiles().agentsFiles;\n\n\t\treturn {\n\t\t\tmodelCapability,\n\t\t\tcwd: this.deps.getCwd(),\n\t\t\tcontextFiles: loadedContextFiles,\n\t\t\t// Metadata remains available to extension hooks, but buildSystemPrompt never renders it.\n\t\t\tskills: [...this.deps.getResourceLoader().getActiveSkills()],\n\t\t\tcustomPrompt: loaderSystemPrompt,\n\t\t\tappendSystemPrompt,\n\t\t\tselectedTools: validToolNames,\n\t\t\ttoolSnippets,\n\t\t\tpromptGuidelines,\n\t\t\textensions: [...this.deps.getActiveExtensions()],\n\t\t};\n\t}\n\n\trebuildSystemPrompt(toolNames: string[]): string {\n\t\tthis._baseSystemPromptOptions = this._buildSystemPromptOptionsForToolNames(toolNames);\n\t\treturn buildSystemPrompt(this._baseSystemPromptOptions);\n\t}\n\n\t/**\n\t * Build a system prompt for a specific tool surface WITHOUT touching the session's base prompt\n\t * state. Used for a router-swapped turn (G4): the routed model runs against a filtered tool set,\n\t * so it must also receive a system prompt whose tool guidelines/snippets match that filtered\n\t * surface — but the change is per-turn, so it must not mutate `_baseSystemPromptOptions` (which\n\t * later turns and extension events read).\n\t */\n\tbuildSystemPromptForToolNames(toolNames: string[]): string {\n\t\treturn buildSystemPrompt(this._buildSystemPromptOptionsForToolNames(toolNames));\n\t}\n}\n"]}
|
|
@@ -3,13 +3,13 @@
|
|
|
3
3
|
*/
|
|
4
4
|
import type { Extension } from "./extensions/types.ts";
|
|
5
5
|
import { type ModelCapabilityProfile } from "./model-capability.ts";
|
|
6
|
-
import {
|
|
6
|
+
import type { Skill } from "./skills.ts";
|
|
7
7
|
export interface BuildSystemPromptOptions {
|
|
8
8
|
/** Capability profile that selects the stable prompt shape. Missing means full/legacy behavior. */
|
|
9
9
|
modelCapability?: Pick<ModelCapabilityProfile, "class" | "contextWindow" | "reasonCode" | "systemPromptMaxChars">;
|
|
10
10
|
/** Custom system prompt (replaces default). */
|
|
11
11
|
customPrompt?: string;
|
|
12
|
-
/** Tools to include in prompt.
|
|
12
|
+
/** Tools to include in the prompt. Defaults come from the shared active-tool surface. */
|
|
13
13
|
selectedTools?: string[];
|
|
14
14
|
/** Optional one-line tool snippets keyed by tool name. */
|
|
15
15
|
toolSnippets?: Record<string, string>;
|
|
@@ -24,7 +24,7 @@ export interface BuildSystemPromptOptions {
|
|
|
24
24
|
path: string;
|
|
25
25
|
content?: string;
|
|
26
26
|
}>;
|
|
27
|
-
/** Discovered skills;
|
|
27
|
+
/** Discovered skills remain host-side; retained for extension/API construction compatibility. */
|
|
28
28
|
skills?: Skill[];
|
|
29
29
|
/** Discovered extensions currently active. */
|
|
30
30
|
extensions?: Extension[];
|
|
@@ -36,7 +36,7 @@ export interface BuildSystemPromptOptions {
|
|
|
36
36
|
* single cache breakpoint covering the whole system prompt). The caller (SystemPromptBuilder /
|
|
37
37
|
* AgentSession, see `_rebuildSystemPrompt` in agent-session.ts) rebuilds it only when the TOOL
|
|
38
38
|
* SURFACE changes — never per turn. For a fixed `options` (fixed tool surface, cwd, context
|
|
39
|
-
* files,
|
|
39
|
+
* files, extensions), two calls on the SAME CALENDAR DAY must return byte-identical
|
|
40
40
|
* output, because `date` below is deliberately truncated to Y-M-D granularity. Do NOT widen it
|
|
41
41
|
* to a timestamp (HH:MM:SS) or otherwise fold in any per-turn-volatile field (turn counters,
|
|
42
42
|
* elapsed time, random ids, etc.) — that would cache-bust this entire block on EVERY turn instead
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"system-prompt.d.ts","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;
|
|
1
|
+
{"version":3,"file":"system-prompt.d.ts","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAKH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAA4C,KAAK,sBAAsB,EAAE,MAAM,uBAAuB,CAAC;AAE9G,OAAO,KAAK,EAAE,KAAK,EAAE,MAAM,aAAa,CAAC;AAEzC,MAAM,WAAW,wBAAwB;IACxC,mGAAmG;IACnG,eAAe,CAAC,EAAE,IAAI,CAAC,sBAAsB,EAAE,OAAO,GAAG,eAAe,GAAG,YAAY,GAAG,sBAAsB,CAAC,CAAC;IAClH,+CAA+C;IAC/C,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,yFAAyF;IACzF,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,0DAA0D;IAC1D,YAAY,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACtC,qFAAqF;IACrF,gBAAgB,CAAC,EAAE,MAAM,EAAE,CAAC;IAC5B,uCAAuC;IACvC,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,yBAAyB;IACzB,GAAG,EAAE,MAAM,CAAC;IACZ,sDAAsD;IACtD,YAAY,CAAC,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACzD,iGAAiG;IACjG,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC;IACjB,8CAA8C;IAC9C,UAAU,CAAC,EAAE,SAAS,EAAE,CAAC;CACzB;AA+JD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,wBAAwB,GAAG,MAAM,CAqJ3E"}
|