@caupulican/pi-adaptative 0.95.0 → 0.96.0
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 +19 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.d.ts.map +1 -1
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.js +28 -0
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.js.map +1 -1
- package/dist/bundled-resources/extensions/tmux-agent-manager/index.ts +25 -0
- package/dist/bundled-resources/extensions/tps/index.d.ts +3 -0
- package/dist/bundled-resources/extensions/tps/index.d.ts.map +1 -0
- package/dist/bundled-resources/extensions/tps/index.js +44 -0
- package/dist/bundled-resources/extensions/tps/index.js.map +1 -0
- package/dist/bundled-resources/extensions/tps/index.ts +48 -0
- package/dist/core/agent-session-services.d.ts.map +1 -1
- package/dist/core/agent-session-services.js +12 -3
- package/dist/core/agent-session-services.js.map +1 -1
- package/dist/core/compaction-controller.d.ts +3 -0
- package/dist/core/compaction-controller.d.ts.map +1 -1
- package/dist/core/compaction-controller.js +12 -1
- package/dist/core/compaction-controller.js.map +1 -1
- package/dist/core/extension-import-authority.d.ts +3 -1
- package/dist/core/extension-import-authority.d.ts.map +1 -1
- package/dist/core/extension-import-authority.js +15 -0
- package/dist/core/extension-import-authority.js.map +1 -1
- package/dist/core/keybindings.d.ts +2 -2
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +2 -2
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/profile-filter-controller.d.ts.map +1 -1
- package/dist/core/profile-filter-controller.js +5 -2
- package/dist/core/profile-filter-controller.js.map +1 -1
- package/dist/core/provider-prompt-contracts.d.ts +5 -1
- package/dist/core/provider-prompt-contracts.d.ts.map +1 -1
- package/dist/core/provider-prompt-contracts.js +5 -1
- package/dist/core/provider-prompt-contracts.js.map +1 -1
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +6 -2
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/risk-classifier.d.ts.map +1 -1
- package/dist/core/risk-classifier.js +22 -2
- package/dist/core/risk-classifier.js.map +1 -1
- package/dist/core/settings-manager.d.ts +7 -0
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +22 -0
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/system-prompt-builder.d.ts +1 -0
- package/dist/core/system-prompt-builder.d.ts.map +1 -1
- package/dist/core/system-prompt-builder.js +21 -1
- package/dist/core/system-prompt-builder.js.map +1 -1
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +5 -1
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tools/goal.d.ts.map +1 -1
- package/dist/core/tools/goal.js +6 -16
- package/dist/core/tools/goal.js.map +1 -1
- package/dist/core/tools/orchestration-panel.d.ts +7 -0
- package/dist/core/tools/orchestration-panel.d.ts.map +1 -1
- package/dist/core/tools/orchestration-panel.js +58 -9
- package/dist/core/tools/orchestration-panel.js.map +1 -1
- package/dist/core/tools/task-steps.d.ts.map +1 -1
- package/dist/core/tools/task-steps.js +1 -0
- package/dist/core/tools/task-steps.js.map +1 -1
- package/dist/modes/interactive/components/agents-overlay.d.ts +16 -4
- package/dist/modes/interactive/components/agents-overlay.d.ts.map +1 -1
- package/dist/modes/interactive/components/agents-overlay.js +108 -29
- package/dist/modes/interactive/components/agents-overlay.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +5 -4
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/docs/extensions.md +2 -0
- package/docs/index.md +1 -0
- package/docs/keybindings.md +2 -0
- package/docs/task-steps.md +2 -0
- package/docs/tmux-agent-manager.md +1 -1
- package/docs/work-lifecycle.md +137 -0
- 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/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/npm-shrinkwrap.json +12 -12
- package/package.json +4 -4
|
@@ -78,6 +78,7 @@ export declare class SystemPromptBuilder {
|
|
|
78
78
|
private _buildToolSelectionHintPrompt;
|
|
79
79
|
private _buildToolApplicabilityPrompt;
|
|
80
80
|
private _buildAutonomyPrompt;
|
|
81
|
+
private _buildWorkLifecyclePrompt;
|
|
81
82
|
private _buildDelegationPrompt;
|
|
82
83
|
private _buildSystemPromptOptionsForToolNames;
|
|
83
84
|
rebuildSystemPrompt(toolNames: string[]): string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"system-prompt-builder.d.ts","sourceRoot":"","sources":["../../src/core/system-prompt-builder.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAKH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAEvD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,EAGN,KAAK,sBAAsB,EAC3B,MAAM,uBAAuB,CAAC;AAC/B,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;AAKH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AAEvD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAChE,OAAO,EAGN,KAAK,sBAAsB,EAC3B,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AAOxE,OAAO,KAAK,EAAE,cAA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AAI,EAAE,uBAAuB,EAExC;IAED,qGAAqG;IACrG,0BAA0B,IAAI,wBAAwB,CAErD;IAED,kGAAkG;IAClG,yBAAyB,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM,CAEtD;IAED,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,6BAA6B;IAwBrC,OAAO,CAAC,oBAAoB;IAqB5B,OAAO,CAAC,yBAAyB;IAoBjC,OAAO,CAAC,sBAAsB;IAY9B,OAAO,CAAC,qCAAqC;IA2D7C,mBAAmB,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,MAAM,CAG/C;IAED;;;;;;OAMG;IACH,6BAA6B,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,MAAM,CAEzD;CACD"}
|
|
@@ -16,7 +16,7 @@ import { resolvePath } from "../utils/paths.js";
|
|
|
16
16
|
import { resolveMemoryPromptBudget } from "./context/memory-prompt-budget.js";
|
|
17
17
|
import { isCurrentSessionReflectionEnabled, resolveAutoLearnSettings } from "./learning/auto-learn-settings.js";
|
|
18
18
|
import { enforceModelCapabilitySystemPromptBudget, MODEL_CAPABILITY_TOOL_GUIDELINES_MAX_CHARS, } from "./model-capability.js";
|
|
19
|
-
import { DELEGATION_DECISION_RULE } from "./provider-prompt-contracts.js";
|
|
19
|
+
import { CHAT_WORK_LIFECYCLE_SYSTEM_RULE, DELEGATION_DECISION_RULE, WORK_LIFECYCLE_SYSTEM_RULE, } from "./provider-prompt-contracts.js";
|
|
20
20
|
import { normalizeProviderPromptGuidelines, normalizeProviderPromptSnippet } from "./provider-tool-text.js";
|
|
21
21
|
import { UNTRUSTED_BOUNDARY_SYSTEM_RULE } from "./security/untrusted-boundary.js";
|
|
22
22
|
import { buildSystemPrompt } from "./system-prompt.js";
|
|
@@ -182,6 +182,25 @@ export class SystemPromptBuilder {
|
|
|
182
182
|
}
|
|
183
183
|
return `PI AUTONOMY ${autonomy.mode}: ${reflectionContract} Query memory and use bounded tools already available in this session. Auto-apply configured high-confidence memory and clean additive skill promotions; code/prompt/extension/settings changes need approval. Evidence is cue, never proof; active task primary.`;
|
|
184
184
|
}
|
|
185
|
+
_buildWorkLifecyclePrompt(toolNames) {
|
|
186
|
+
if (this.deps.isChildSession())
|
|
187
|
+
return undefined;
|
|
188
|
+
const capabilityClass = this.deps.getModelCapabilityProfile().class;
|
|
189
|
+
if (capabilityClass === "chat")
|
|
190
|
+
return CHAT_WORK_LIFECYCLE_SYSTEM_RULE;
|
|
191
|
+
if (capabilityClass === "minimal")
|
|
192
|
+
return `PI WORK LIFECYCLE\n- ${CHAT_WORK_LIFECYCLE_SYSTEM_RULE}`;
|
|
193
|
+
const hasWorkPlanningTool = toolNames.some((name) => name === "goal" ||
|
|
194
|
+
name === "create_goal" ||
|
|
195
|
+
name === "get_goal" ||
|
|
196
|
+
name === "update_goal" ||
|
|
197
|
+
name === "task_steps");
|
|
198
|
+
const ownerRule = hasWorkPlanningTool
|
|
199
|
+
? "\n- One owner per invariant: goal owns outcome/contract, task_steps owns plan, delegate owns workers, evidence owns acceptance. Never create parallel workflow state."
|
|
200
|
+
: "";
|
|
201
|
+
return `PI WORK LIFECYCLE
|
|
202
|
+
- ${WORK_LIFECYCLE_SYSTEM_RULE}${ownerRule}`;
|
|
203
|
+
}
|
|
185
204
|
_buildDelegationPrompt(delegateActive) {
|
|
186
205
|
if (!delegateActive || !this.deps.getSettingsManager().getWorkerDelegationSettings().enabled) {
|
|
187
206
|
return undefined;
|
|
@@ -220,6 +239,7 @@ export class SystemPromptBuilder {
|
|
|
220
239
|
UNTRUSTED_BOUNDARY_SYSTEM_RULE,
|
|
221
240
|
this._buildSelfModificationPrompt(modelCapability),
|
|
222
241
|
this._buildAutonomyPrompt(modelCapability),
|
|
242
|
+
this._buildWorkLifecyclePrompt(validToolNames),
|
|
223
243
|
this._buildDelegationPrompt(validToolNames.includes("delegate")),
|
|
224
244
|
this._buildModelAdaptationPrompt(),
|
|
225
245
|
this._buildToolSelectionHintPrompt(),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"system-prompt-builder.js","sourceRoot":"","sources":["../../src/core/system-prompt-builder.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAC;AACrC,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AAE9E,OAAO,EAAE,iCAAiC,EAAE,wBAAwB,EAAE,MAAM,mCAAmC,CAAC;AAEhH,OAAO,EACN,wCAAwC,EACxC,0CAA0C,GAE1C,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EAAE,wBAAwB,EAAE,MAAM,gCAAgC,CAAC;AAC1E,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,CAAC,QAGvD;IACA,MAAM,UAAU,GAAa,EAAE,CAAC;IAChC,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAC,EAAE,CAAC;QACzC,KAAK,MAAM,SAAS,IAAI,QAAQ,CAAC,WAAW,EAAE,CAAC;YAC9C,MAAM,UAAU,GA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G;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 { resolvePath } from \"../utils/paths.ts\";\nimport { resolveMemoryPromptBudget } from \"./context/memory-prompt-budget.ts\";\nimport type { Extension } from \"./extensions/types.ts\";\nimport { isCurrentSessionReflectionEnabled, resolveAutoLearnSettings } from \"./learning/auto-learn-settings.ts\";\nimport type { MemoryManager } from \"./memory/memory-manager.ts\";\nimport {\n\tenforceModelCapabilitySystemPromptBudget,\n\tMODEL_CAPABILITY_TOOL_GUIDELINES_MAX_CHARS,\n\ttype ModelCapabilityProfile,\n} from \"./model-capability.ts\";\nimport type { ModelAdaptationRule } from \"./models/adaptation-store.ts\";\nimport { DELEGATION_DECISION_RULE } from \"./provider-prompt-contracts.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/** Child/worker sessions never receive root autonomy or reflection instructions. */\n\tisChildSession(): boolean;\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\n/**\n * Constrained profiles admit tool guidance in priority rounds: every tool's first rule is\n * considered before any tool's second. Tool definitions already list mandatory guidance first;\n * this prevents an early verbose tool from starving a later security or authorization rule.\n */\nfunction collectPromptGuidelines(\n\tgroups: readonly (readonly string[])[],\n\tmaxRenderedChars: number | undefined,\n): string[] {\n\tif (maxRenderedChars === undefined) return groups.flat();\n\n\tconst accepted: string[] = [];\n\tconst seen = new Set<string>();\n\tlet renderedChars = 0;\n\tfor (let priority = 0; ; priority++) {\n\t\tlet foundCandidate = false;\n\t\tfor (const group of groups) {\n\t\t\tconst guideline = group[priority]?.trim();\n\t\t\tif (!guideline) continue;\n\t\t\tfoundCandidate = true;\n\t\t\tif (seen.has(guideline)) continue;\n\t\t\tseen.add(guideline);\n\n\t\t\t// \"- \" plus the separating newline. Charging three for the first bullet too is a\n\t\t\t// conservative upper bound and keeps the policy independent of renderer position.\n\t\t\tconst candidateChars = guideline.length + 3;\n\t\t\tif (renderedChars + candidateChars > maxRenderedChars) continue;\n\t\t\taccepted.push(guideline);\n\t\t\trenderedChars += candidateChars;\n\t\t}\n\t\tif (!foundCandidate) break;\n\t}\n\treturn accepted;\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 _buildToolApplicabilityPrompt(\n\t\tvalidToolNames: readonly string[],\n\t\tactiveExtensions: ReadonlyArray<Extension>,\n\t\tprofile: ModelCapabilityProfile,\n\t): string | undefined {\n\t\tconst activeNames = new Set(validToolNames);\n\t\tif (!activeNames.has(\"secret_store\")) {\n\t\t\tlet hasActiveExtensionTool = false;\n\t\t\tfor (const extension of activeExtensions) {\n\t\t\t\tfor (const name of extension.tools.keys()) {\n\t\t\t\t\tif (!activeNames.has(name)) continue;\n\t\t\t\t\thasActiveExtensionTool = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (hasActiveExtensionTool) break;\n\t\t\t}\n\t\t\tif (!hasActiveExtensionTool) return undefined;\n\t\t}\n\t\tif (profile.class !== \"full\") {\n\t\t\treturn \"PI TOOL APPLICABILITY: availability is not a mandate. Use extension/project/account tools only when this request needs their data or action. Context or guidance alone is not a trigger. Missing optional credentials never block unrelated work or require secret_store.\";\n\t\t}\n\t\treturn \"PI TOOL APPLICABILITY: active means available, not required. Use extension/project/account tools only when the current request explicitly asks for them or genuinely depends on their data/action; cwd, repository, prior session, wildcard profile, or tool guidance alone are not triggers. Missing optional credentials never block unrelated work or justify speculative secret_store use.\";\n\t}\n\n\tprivate _buildAutonomyPrompt(profile: ModelCapabilityProfile): string | undefined {\n\t\tif (this.deps.isChildSession()) return undefined;\n\t\tconst settingsManager = this.deps.getSettingsManager();\n\t\tconst autonomy = settingsManager.getAutonomySettings();\n\t\tconst autoLearn = resolveAutoLearnSettings(autonomy.mode, settingsManager.getAutoLearnSettings());\n\t\tif (!autoLearn.enabled && autonomy.mode !== \"full\") {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst reflectionContract = isCurrentSessionReflectionEnabled(autoLearn)\n\t\t\t? \"ROOT REFLECTION: decide and apply warranted durable learning in the current root provider turn only; never add a provider request or delegate reflection.\"\n\t\t\t: \"Root reflection is disabled.\";\n\t\tif (profile.class !== \"full\") {\n\t\t\treturn `PI AUTONOMY ${autonomy.mode}: ${reflectionContract} 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): ${reflectionContract} 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}: ${reflectionContract} Query memory and use bounded tools already available in this session. Auto-apply configured high-confidence memory and clean additive skill promotions; code/prompt/extension/settings changes need approval. Evidence is cue, never proof; active task primary.`;\n\t}\n\n\tprivate _buildDelegationPrompt(delegateActive: boolean): string | undefined {\n\t\tif (!delegateActive || !this.deps.getSettingsManager().getWorkerDelegationSettings().enabled) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn `PI DELEGATION\n- ${DELEGATION_DECISION_RULE}\n- Continue parent work while workers run; wait only at a true dependency, then inspect status and handoffs event-driven.\n- Parent owns integration, verification, security and approval decisions, and writes unless authority explicitly grants worker writes.\n- Treat worker output as evidence, reconcile conflicts, and finish only after success criteria.\n- Per-worker token, cost, wall-clock, and tool ceilings come only from host settings or an owner-authored profileId.`;\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 promptGuidelineGroups: 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 && toolGuidelines.length > 0) {\n\t\t\t\tpromptGuidelineGroups.push(toolGuidelines);\n\t\t\t}\n\t\t}\n\t\tconst promptGuidelines = collectPromptGuidelines(\n\t\t\tpromptGuidelineGroups,\n\t\t\tMODEL_CAPABILITY_TOOL_GUIDELINES_MAX_CHARS[modelCapability.class],\n\t\t);\n\n\t\tconst loaderSystemPrompt = this.deps.getResourceLoader().getSystemPrompt();\n\t\tconst loaderAppendSystemPrompt = this.deps.getResourceLoader().getAppendSystemPrompt();\n\t\tconst activeExtensions = this.deps.getActiveExtensions();\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._buildDelegationPrompt(validToolNames.includes(\"delegate\")),\n\t\t\tthis._buildModelAdaptationPrompt(),\n\t\t\tthis._buildToolSelectionHintPrompt(),\n\t\t\tthis._buildToolApplicabilityPrompt(validToolNames, activeExtensions, modelCapability),\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: [...activeExtensions],\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;AACrC,OAAO,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAChD,OAAO,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAAC;AAE9E,OAAO,EAAE,iCAAiC,EAAE,wBAAwB,EAAE,MAAM,mCAAmC,CAAC;AAEhH,OAAO,EACN,wCAAwC,EACxC,0CAA0C,GAE1C,MAAM,uBAAuB,CAAC;AAE/B,OAAO,EACN,+BAA+B,EAC/B,wBAAwB,EACxB,0BAA0B,GAC1B,MAAM,gCAAgC,CAAC;AACxC,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;AAoC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AC,eAAe,CAAC;YAC9C,GAAG,wBAAwB;SAC3B,CAAC,MAAM,CAAC,CAAC,IAAI,EAAkB,EAAE,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC;QAClD,MAAM,kBAAkB,GAAG,uBAAuB,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,uBAAuB,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;QACjH,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,gBAAgB,CAAC;SACjC,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 { resolvePath } from \"../utils/paths.ts\";\nimport { resolveMemoryPromptBudget } from \"./context/memory-prompt-budget.ts\";\nimport type { Extension } from \"./extensions/types.ts\";\nimport { isCurrentSessionReflectionEnabled, resolveAutoLearnSettings } from \"./learning/auto-learn-settings.ts\";\nimport type { MemoryManager } from \"./memory/memory-manager.ts\";\nimport {\n\tenforceModelCapabilitySystemPromptBudget,\n\tMODEL_CAPABILITY_TOOL_GUIDELINES_MAX_CHARS,\n\ttype ModelCapabilityProfile,\n} from \"./model-capability.ts\";\nimport type { ModelAdaptationRule } from \"./models/adaptation-store.ts\";\nimport {\n\tCHAT_WORK_LIFECYCLE_SYSTEM_RULE,\n\tDELEGATION_DECISION_RULE,\n\tWORK_LIFECYCLE_SYSTEM_RULE,\n} from \"./provider-prompt-contracts.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/** Child/worker sessions never receive root autonomy or reflection instructions. */\n\tisChildSession(): boolean;\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\n/**\n * Constrained profiles admit tool guidance in priority rounds: every tool's first rule is\n * considered before any tool's second. Tool definitions already list mandatory guidance first;\n * this prevents an early verbose tool from starving a later security or authorization rule.\n */\nfunction collectPromptGuidelines(\n\tgroups: readonly (readonly string[])[],\n\tmaxRenderedChars: number | undefined,\n): string[] {\n\tif (maxRenderedChars === undefined) return groups.flat();\n\n\tconst accepted: string[] = [];\n\tconst seen = new Set<string>();\n\tlet renderedChars = 0;\n\tfor (let priority = 0; ; priority++) {\n\t\tlet foundCandidate = false;\n\t\tfor (const group of groups) {\n\t\t\tconst guideline = group[priority]?.trim();\n\t\t\tif (!guideline) continue;\n\t\t\tfoundCandidate = true;\n\t\t\tif (seen.has(guideline)) continue;\n\t\t\tseen.add(guideline);\n\n\t\t\t// \"- \" plus the separating newline. Charging three for the first bullet too is a\n\t\t\t// conservative upper bound and keeps the policy independent of renderer position.\n\t\t\tconst candidateChars = guideline.length + 3;\n\t\t\tif (renderedChars + candidateChars > maxRenderedChars) continue;\n\t\t\taccepted.push(guideline);\n\t\t\trenderedChars += candidateChars;\n\t\t}\n\t\tif (!foundCandidate) break;\n\t}\n\treturn accepted;\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 _buildToolApplicabilityPrompt(\n\t\tvalidToolNames: readonly string[],\n\t\tactiveExtensions: ReadonlyArray<Extension>,\n\t\tprofile: ModelCapabilityProfile,\n\t): string | undefined {\n\t\tconst activeNames = new Set(validToolNames);\n\t\tif (!activeNames.has(\"secret_store\")) {\n\t\t\tlet hasActiveExtensionTool = false;\n\t\t\tfor (const extension of activeExtensions) {\n\t\t\t\tfor (const name of extension.tools.keys()) {\n\t\t\t\t\tif (!activeNames.has(name)) continue;\n\t\t\t\t\thasActiveExtensionTool = true;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tif (hasActiveExtensionTool) break;\n\t\t\t}\n\t\t\tif (!hasActiveExtensionTool) return undefined;\n\t\t}\n\t\tif (profile.class !== \"full\") {\n\t\t\treturn \"PI TOOL APPLICABILITY: availability is not a mandate. Use extension/project/account tools only when this request needs their data or action. Context or guidance alone is not a trigger. Missing optional credentials never block unrelated work or require secret_store.\";\n\t\t}\n\t\treturn \"PI TOOL APPLICABILITY: active means available, not required. Use extension/project/account tools only when the current request explicitly asks for them or genuinely depends on their data/action; cwd, repository, prior session, wildcard profile, or tool guidance alone are not triggers. Missing optional credentials never block unrelated work or justify speculative secret_store use.\";\n\t}\n\n\tprivate _buildAutonomyPrompt(profile: ModelCapabilityProfile): string | undefined {\n\t\tif (this.deps.isChildSession()) return undefined;\n\t\tconst settingsManager = this.deps.getSettingsManager();\n\t\tconst autonomy = settingsManager.getAutonomySettings();\n\t\tconst autoLearn = resolveAutoLearnSettings(autonomy.mode, settingsManager.getAutoLearnSettings());\n\t\tif (!autoLearn.enabled && autonomy.mode !== \"full\") {\n\t\t\treturn undefined;\n\t\t}\n\n\t\tconst reflectionContract = isCurrentSessionReflectionEnabled(autoLearn)\n\t\t\t? \"ROOT REFLECTION: decide and apply warranted durable learning in the current root provider turn only; never add a provider request or delegate reflection.\"\n\t\t\t: \"Root reflection is disabled.\";\n\t\tif (profile.class !== \"full\") {\n\t\t\treturn `PI AUTONOMY ${autonomy.mode}: ${reflectionContract} 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): ${reflectionContract} 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}: ${reflectionContract} Query memory and use bounded tools already available in this session. Auto-apply configured high-confidence memory and clean additive skill promotions; code/prompt/extension/settings changes need approval. Evidence is cue, never proof; active task primary.`;\n\t}\n\n\tprivate _buildWorkLifecyclePrompt(toolNames: readonly string[]): string | undefined {\n\t\tif (this.deps.isChildSession()) return undefined;\n\t\tconst capabilityClass = this.deps.getModelCapabilityProfile().class;\n\t\tif (capabilityClass === \"chat\") return CHAT_WORK_LIFECYCLE_SYSTEM_RULE;\n\t\tif (capabilityClass === \"minimal\") return `PI WORK LIFECYCLE\\n- ${CHAT_WORK_LIFECYCLE_SYSTEM_RULE}`;\n\t\tconst hasWorkPlanningTool = toolNames.some(\n\t\t\t(name) =>\n\t\t\t\tname === \"goal\" ||\n\t\t\t\tname === \"create_goal\" ||\n\t\t\t\tname === \"get_goal\" ||\n\t\t\t\tname === \"update_goal\" ||\n\t\t\t\tname === \"task_steps\",\n\t\t);\n\t\tconst ownerRule = hasWorkPlanningTool\n\t\t\t? \"\\n- One owner per invariant: goal owns outcome/contract, task_steps owns plan, delegate owns workers, evidence owns acceptance. Never create parallel workflow state.\"\n\t\t\t: \"\";\n\t\treturn `PI WORK LIFECYCLE\n- ${WORK_LIFECYCLE_SYSTEM_RULE}${ownerRule}`;\n\t}\n\n\tprivate _buildDelegationPrompt(delegateActive: boolean): string | undefined {\n\t\tif (!delegateActive || !this.deps.getSettingsManager().getWorkerDelegationSettings().enabled) {\n\t\t\treturn undefined;\n\t\t}\n\t\treturn `PI DELEGATION\n- ${DELEGATION_DECISION_RULE}\n- Continue parent work while workers run; wait only at a true dependency, then inspect status and handoffs event-driven.\n- Parent owns integration, verification, security and approval decisions, and writes unless authority explicitly grants worker writes.\n- Treat worker output as evidence, reconcile conflicts, and finish only after success criteria.\n- Per-worker token, cost, wall-clock, and tool ceilings come only from host settings or an owner-authored profileId.`;\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 promptGuidelineGroups: 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 && toolGuidelines.length > 0) {\n\t\t\t\tpromptGuidelineGroups.push(toolGuidelines);\n\t\t\t}\n\t\t}\n\t\tconst promptGuidelines = collectPromptGuidelines(\n\t\t\tpromptGuidelineGroups,\n\t\t\tMODEL_CAPABILITY_TOOL_GUIDELINES_MAX_CHARS[modelCapability.class],\n\t\t);\n\n\t\tconst loaderSystemPrompt = this.deps.getResourceLoader().getSystemPrompt();\n\t\tconst loaderAppendSystemPrompt = this.deps.getResourceLoader().getAppendSystemPrompt();\n\t\tconst activeExtensions = this.deps.getActiveExtensions();\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._buildWorkLifecyclePrompt(validToolNames),\n\t\t\tthis._buildDelegationPrompt(validToolNames.includes(\"delegate\")),\n\t\t\tthis._buildModelAdaptationPrompt(),\n\t\t\tthis._buildToolSelectionHintPrompt(),\n\t\t\tthis._buildToolApplicabilityPrompt(validToolNames, activeExtensions, modelCapability),\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: [...activeExtensions],\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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"system-prompt.d.ts","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAMH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,uBAAuB,CAAC;AACvD,OAAO,EAA4C,KAAK,sBAAsB,EAAE,MAAM,uBA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C,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,wFAAwF;IACxF,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;AAsKD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,iBAAiB,CAAC,OAAO,EAAE,wBAAwB,GAAG,MAAM,CAqJ3E"}
|
|
@@ -132,7 +132,11 @@ function appendPromptResources(prompt, options) {
|
|
|
132
132
|
}
|
|
133
133
|
// Day-granularity only; keep this tail stable across every call on the same calendar day.
|
|
134
134
|
result += `\nCurrent date: ${options.date}`;
|
|
135
|
-
|
|
135
|
+
// Chat-class models have no filesystem tools, so cwd is unusable context and makes the hard
|
|
136
|
+
// prompt budget depend on host checkout-path length. Tool-capable profiles retain it.
|
|
137
|
+
if (options.modelCapability?.class !== "chat") {
|
|
138
|
+
result += `\nCurrent working directory: ${options.promptCwd}`;
|
|
139
|
+
}
|
|
136
140
|
// Prompt resources can come from CRLF checkouts or user files. Canonicalize once at the final
|
|
137
141
|
// assembly boundary so capability budgets and provider cache keys are host-independent.
|
|
138
142
|
const normalizedResult = result.replace(/\r\n?/g, "\n");
|
|
@@ -1 +1 @@
|
|
|
1
|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AC,CAAC,EAAE,WAAW,EAAE,iBAAiB,CAAC,WAAW,EAAE,kCAAkC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC3G,CAAC,CACF,CAAC;QACF,KAAK,EAAE,CAAC;IACT,CAAC;IAED,IAAI,KAAK,KAAK,CAAC,EAAE,CAAC;QACjB,OAAO,EAAE,CAAC;IACX,CAAC;IAED,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACzB,CAAC","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { dirname } from \"node:path\";\nimport { TOOL_FAILURE_RETRY_MODEL_RULE } from \"@caupulican/pi-agent-core\";\nimport { getReadmePath } from \"../config.ts\";\nimport { getExtensionDescription, getExtensionDisplayName } from \"./extension-metadata.ts\";\nimport type { Extension } from \"./extensions/types.ts\";\nimport { enforceModelCapabilitySystemPromptBudget, type ModelCapabilityProfile } from \"./model-capability.ts\";\nimport { SKILL_VAULT_SYSTEM_RULE } from \"./provider-prompt-contracts.ts\";\nimport type { Skill } from \"./skills.ts\";\n\nexport interface BuildSystemPromptOptions {\n\t/** Capability profile that selects the stable prompt shape. Missing means full/legacy behavior. */\n\tmodelCapability?: Pick<ModelCapabilityProfile, \"class\" | \"contextWindow\" | \"reasonCode\" | \"systemPromptMaxChars\">;\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/** Tools to include in the prompt. Defaults come from the shared active-tool surface. */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Global instruction files (with content) plus on-demand project paths (path only). */\n\tcontextFiles?: Array<{ path: string; content?: string }>;\n\t/** Discovered skills remain host-side; retained for extension/API construction compatibility. */\n\tskills?: Skill[];\n\t/** Discovered extensions currently active. */\n\textensions?: Extension[];\n}\n\nconst MODEL_BLIND_CREDENTIAL_AUTHORITY =\n\t\"Active secret_store: host gate authorizes model-blind activation/migration from named accessible sources; no duplicate confirmation.\";\n\nconst ULTRA_TERSE_OUTPUT_POLICY = `\n\nULTRA-TERSE OUTPUT\n\n- Drop articles/filler/pleasantries/hedging; fragments valid. Strip conjunctions only when clear; each fact once.\n- Never drop not/never/no/only/except; never invent abbreviations or use causal arrows. Preserve numbers, units, code symbols, function/API names, commands, errors.\n- No self-reference/tool narration/tables/emoji/log dumps. Keep user language. Full grammar: security, irreversible actions, ambiguous order. Replies terse; artifacts normal prose.\n- Answer shape: status/ops turns terse; analysis/review/evaluation asks get complete structured answers; never restate harness protocol text or failure-record JSON to the user as an answer.`;\n\nconst PI_ADAPTATIVE_CORE_SECTION = `\n\nOPERATING CONTRACT\n\n- Clear conversational outcome is goal; persist progress/evidence through compaction; finish or report blocker.\n- Hold scope; verify unknowns from primary sources; simplest proven design, one owner/path per invariant.\n- User outcome governs, method does not. Outcome risk: show evidence, test when practical, offer safest effective path, execute.\n- Work over 15 seconds: managed background run, event terminal, bounded handoff, owner notice; never poll.\n- Facts: memory; specialization: skills; behavior: source. Discard noise.\n- Implementation/verification work loads skill evidence-gated-tdd; architecture/performance design loads skill n-plus-2-architecture; their gates bind only while that work is active.\n- Explicit user instruction in current message overrides standing style (length/format/tone); security, untrusted-content, and authorization rules are never overridable.\n- Ask before broader scope, credential or authentication change/disclosure, destructive action, publication. Bound, source-label output; show paths.\n- ${MODEL_BLIND_CREDENTIAL_AUTHORITY}`;\n\nconst PI_ADAPTATIVE_LEAN_CORE_SECTION = `\n\nOPERATING CONTRACT\n\n- Complete current goal within scope, granted authority; keep progress, evidence concise.\n- Inspect relevant files and instructions before editing; make minimal coherent change, run focused checks.\n- Use active tools/schemas. On failure, follow error guidance. ${TOOL_FAILURE_RETRY_MODEL_RULE}\n- Batch independent reads, order mutations; report real output, unresolved failures.\n- Ask before destructive actions, credential disclosure or provider authentication changes, publication, push/tag/release, scope expansion.\n- ${MODEL_BLIND_CREDENTIAL_AUTHORITY}`;\n\nconst PI_ADAPTATIVE_MINIMAL_CORE_SECTION = `\n\nEXECUTION RULES\n\n- Work one scoped task. Inspect before editing, make small coherent change, run narrowest useful check.\n- Use listed tools/schemas. On failure, follow error guidance. ${TOOL_FAILURE_RETRY_MODEL_RULE}\n- Batch independent reads, order mutations. Report actual results; never claim incomplete action.\n- Ask before destructive actions, credential disclosure or provider authentication changes, publication, push/tag/release, material scope change.\n- ${MODEL_BLIND_CREDENTIAL_AUTHORITY}`;\n\nconst PI_ADAPTATIVE_CHAT_CORE_SECTION = `\n\nCHAT RULES\n\n- Answer concisely from conversation; state uncertainty.\n- No execution tools are active. Do not claim to read files, run commands, or make changes.\n- Say when the request requires a tool-capable model or additional user-provided context.`;\n\nconst DEFERRED_CONTEXT_PATH_BUDGET_CHARS = 512;\nconst EXTENSION_DESCRIPTION_BUDGET_CHARS = 180;\n\nfunction compactPromptText(value: string, maxChars: number): string {\n\tconst normalized = value.replace(/\\s+/g, \" \").trim();\n\tif (normalized.length <= maxChars) return normalized;\n\tlet end = maxChars - 1;\n\tconst code = normalized.charCodeAt(end - 1);\n\tif (code >= 0xd800 && code <= 0xdbff) end--;\n\treturn `${normalized.slice(0, end)}…`;\n}\n\nfunction formatContextFilesForPrompt(\n\tcontextFiles: Array<{ path: string; content?: string }>,\n\toptions: { deferContents: boolean; canRead: boolean },\n): string {\n\tif (contextFiles.length === 0) {\n\t\treturn \"\";\n\t}\n\tconst injected = options.deferContents ? [] : contextFiles.filter((file) => file.content !== undefined);\n\tconst deferred = options.deferContents ? contextFiles : contextFiles.filter((file) => file.content === undefined);\n\tconst parts: string[] = [];\n\n\tif (injected.length > 0) {\n\t\tconst lines = [\"\\n\\nPROJECT-SPECIFIC INSTRUCTIONS (apply in listed order)\"];\n\t\tconst seen = new Set<string>();\n\t\tfor (const { path, content } of injected) {\n\t\t\tconst identity = `${path}\\0${content ?? \"\"}`;\n\t\t\tif (seen.has(identity)) continue;\n\t\t\tseen.add(identity);\n\t\t\tlines.push(`FILE ${JSON.stringify(path)} (${(content ?? \"\").length} chars)`);\n\t\t\tlines.push(content ?? \"\");\n\t\t\tlines.push(\"END FILE\");\n\t\t}\n\t\tparts.push(lines.join(\"\\n\"));\n\t}\n\n\tif (deferred.length > 0) {\n\t\tconst lines = [\n\t\t\t\"\\n\\nPROJECT RULE PATHS — contents not preloaded.\",\n\t\t\toptions.deferContents\n\t\t\t\t? options.canRead\n\t\t\t\t\t? \"Before editing, writing, or running a mutating command, read each relevant listed file completely before any mutation. Follow its instructions; if a file cannot fit, ask for a scoped instruction digest.\"\n\t\t\t\t\t: \"No read tool is active. Ask the user for the relevant project instructions before giving project-specific guidance.\"\n\t\t\t\t: options.canRead\n\t\t\t\t\t? \"Read a listed file completely before following it. Do not assume its contents.\"\n\t\t\t\t\t: \"No read tool is active. Ask the user for the relevant project instructions before giving project-specific guidance.\",\n\t\t];\n\t\tlet pathChars = 0;\n\t\tlet included = 0;\n\t\tfor (const { path } of deferred) {\n\t\t\tconst line = `- ${JSON.stringify(path)}`;\n\t\t\tif (pathChars + line.length > DEFERRED_CONTEXT_PATH_BUDGET_CHARS) break;\n\t\t\tlines.push(line);\n\t\t\tpathChars += line.length + 1;\n\t\t\tincluded++;\n\t\t}\n\t\tconst omitted = deferred.length - included;\n\t\tif (omitted > 0) {\n\t\t\tlines.push(`- omitted=${omitted}`);\n\t\t\tlines.push(\n\t\t\t\t\"Do not mutate until the omitted instruction paths are supplied or a more capable profile is used.\",\n\t\t\t);\n\t\t}\n\t\tparts.push(lines.join(\"\\n\"));\n\t}\n\n\treturn parts.join(\"\");\n}\n\nfunction appendPromptResources(\n\tprompt: string,\n\toptions: {\n\t\tappendSection: string;\n\t\tcontextFiles: Array<{ path: string; content?: string }>;\n\t\textensions: Extension[];\n\t\tvisibleTools: string[];\n\t\tfullPrompt: boolean;\n\t\thasRead: boolean;\n\t\tdate: string;\n\t\tpromptCwd: string;\n\t\tmodelCapability: BuildSystemPromptOptions[\"modelCapability\"];\n\t},\n): string {\n\tlet result = prompt;\n\tif (options.appendSection) result += options.appendSection;\n\tresult += formatContextFilesForPrompt(options.contextFiles, {\n\t\tdeferContents: !options.fullPrompt,\n\t\tcanRead: options.hasRead,\n\t});\n\t// Extension metadata is redundant with the active tool snippets on constrained profiles.\n\tif (options.fullPrompt && options.extensions.length > 0) {\n\t\tresult += formatExtensionsForPrompt(options.extensions, options.visibleTools);\n\t}\n\t// Day-granularity only; keep this tail stable across every call on the same calendar day.\n\tresult += `\\nCurrent date: ${options.date}`;\n\tresult += `\\nCurrent working directory: ${options.promptCwd}`;\n\t// Prompt resources can come from CRLF checkouts or user files. Canonicalize once at the final\n\t// assembly boundary so capability budgets and provider cache keys are host-independent.\n\tconst normalizedResult = result.replace(/\\r\\n?/g, \"\\n\");\n\treturn options.modelCapability\n\t\t? enforceModelCapabilitySystemPromptBudget(normalizedResult, options.modelCapability)\n\t\t: normalizedResult;\n}\n\n/**\n * Build the system prompt with tools, guidelines, and context.\n *\n * CACHE-STABILITY INVARIANT: providers treat the returned string as ONE prompt-cache block (a\n * single cache breakpoint covering the whole system prompt). The caller (SystemPromptBuilder /\n * AgentSession, see `_rebuildSystemPrompt` in agent-session.ts) rebuilds it only when the TOOL\n * SURFACE changes — never per turn. For a fixed `options` (fixed tool surface, cwd, context\n * files, extensions), two calls on the SAME CALENDAR DAY must return byte-identical\n * output, because `date` below is deliberately truncated to Y-M-D granularity. Do NOT widen it\n * to a timestamp (HH:MM:SS) or otherwise fold in any per-turn-volatile field (turn counters,\n * elapsed time, random ids, etc.) — that would cache-bust this entire block on EVERY turn instead\n * of once per calendar day, defeating provider prompt caching (cost + latency regression on every\n * request). Pinned by test/system-prompt-stability.test.ts.\n */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions): string {\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tcwd,\n\t\tcontextFiles: providedContextFiles,\n\t} = options;\n\tconst resolvedCwd = cwd;\n\tconst promptCwd = resolvedCwd.replace(/\\\\/g, \"/\");\n\n\t// Day-granularity only (see cache-stability invariant on buildSystemPrompt above): this must\n\t// stay stable across every call within a calendar day, not just within a single turn.\n\tconst now = new Date();\n\tconst year = now.getFullYear();\n\tconst month = String(now.getMonth() + 1).padStart(2, \"0\");\n\tconst day = String(now.getDate()).padStart(2, \"0\");\n\tconst date = `${year}-${month}-${day}`;\n\n\tconst appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst capabilityClass = options.modelCapability?.class ?? \"full\";\n\tconst fullPrompt = capabilityClass === \"full\";\n\tconst leanPrompt = capabilityClass === \"lean\";\n\n\tconst activeTools = selectedTools || [\"read\", \"bash\", \"python\", \"edit\", \"write\"];\n\tconst visibleTools = activeTools.filter((name) => !!toolSnippets?.[name]);\n\tconst hasRead = activeTools.includes(\"read\");\n\tconst coreSection = fullPrompt\n\t\t? PI_ADAPTATIVE_CORE_SECTION\n\t\t: leanPrompt\n\t\t\t? PI_ADAPTATIVE_LEAN_CORE_SECTION\n\t\t\t: capabilityClass === \"minimal\"\n\t\t\t\t? PI_ADAPTATIVE_MINIMAL_CORE_SECTION\n\t\t\t\t: PI_ADAPTATIVE_CHAT_CORE_SECTION;\n\tconst skillVaultContract = activeTools.includes(\"skill\") ? `\\n\\n${SKILL_VAULT_SYSTEM_RULE}` : \"\";\n\tconst operatingContract = `${coreSection}${skillVaultContract}${ULTRA_TERSE_OUTPUT_POLICY}`;\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tprompt += operatingContract;\n\t\treturn appendPromptResources(prompt, {\n\t\t\tappendSection,\n\t\t\tcontextFiles,\n\t\t\textensions: options.extensions ?? [],\n\t\t\tvisibleTools,\n\t\t\tfullPrompt,\n\t\t\thasRead,\n\t\t\tdate,\n\t\t\tpromptCwd,\n\t\t\tmodelCapability: options.modelCapability,\n\t\t});\n\t}\n\n\tconst packageRoot = dirname(getReadmePath());\n\n\t// Build tools list based on selected tools.\n\t// A tool appears in Available tools only when the caller provides a one-line snippet.\n\tconst toolsList =\n\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets![name]}`).join(\"\\n\") : \"(none)\";\n\n\t// Build guidelines based on which tools are actually available\n\tconst guidelinesList: string[] = [];\n\tconst guidelinesSet = new Set<string>();\n\tconst addGuideline = (guideline: string): void => {\n\t\tif (guidelinesSet.has(guideline)) {\n\t\t\treturn;\n\t\t}\n\t\tguidelinesSet.add(guideline);\n\t\tguidelinesList.push(guideline);\n\t};\n\n\tconst hasBash = activeTools.includes(\"bash\");\n\tconst hasPython = activeTools.includes(\"python\");\n\tconst hasGrep = activeTools.includes(\"grep\");\n\tconst hasFind = activeTools.includes(\"find\");\n\tconst hasLs = activeTools.includes(\"ls\");\n\tconst hasReadOnlyTools = hasRead || hasGrep || hasFind || hasLs;\n\n\t// File exploration guidelines\n\tif (!fullPrompt && !leanPrompt) {\n\t\tif (hasBash) addGuideline(\"Use bash for bounded shell commands\");\n\t\tif (hasReadOnlyTools) addGuideline(\"Batch independent reads; keep mutations and dependent calls ordered\");\n\t} else if (hasBash && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Bash: ls, rg, find\");\n\t}\n\tif (fullPrompt || leanPrompt) {\n\t\tif (hasBash || hasGrep || hasFind) {\n\t\t\taddGuideline(\"rg/jq: scoped roots/filters, exhaustive output to file\");\n\t\t}\n\t\tif (hasPython) {\n\t\t\taddGuideline(\"Python: bounded scripts/data, source edits via read/edit/write\");\n\t\t}\n\t\tif (hasReadOnlyTools) {\n\t\t\taddGuideline(\"Batch independent reads; order dependent/mutating/stateful calls\");\n\t\t}\n\t}\n\n\tif (fullPrompt || leanPrompt) {\n\t\tfor (const guideline of promptGuidelines ?? []) {\n\t\t\tconst normalized = guideline.trim();\n\t\t\tif (normalized.length > 0) {\n\t\t\t\taddGuideline(normalized);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\tconst toolGuidelinesSection = guidelines.length > 0 ? `\\n\\nTOOL GUIDELINES\\n\\n${guidelines}` : \"\";\n\n\tconst introduction = fullPrompt\n\t\t? \"Pi-Adaptative: self-evolving assistant. Deliver goals within authority; preserve continuity, own integration.\"\n\t\t: leanPrompt\n\t\t\t? \"Pi-Adaptative bounded coding agent. Complete current goal with active surface; preserve handoff evidence.\"\n\t\t\t: capabilityClass === \"minimal\"\n\t\t\t\t? \"Pi-Adaptative focused coding executor. Complete one scoped task with active tools; report verified results.\"\n\t\t\t\t: \"Pi-Adaptative concise chat assistant. No execution tools active.\";\n\tconst toolSurfaceRule =\n\t\tfullPrompt || leanPrompt\n\t\t\t? \"Use active tool surface only; unlisted capabilities may exist.\"\n\t\t\t: \"Use only the active tool surface.\";\n\tlet prompt = `${introduction}\n\nAvailable tools:\n${toolsList}\n\n${toolSurfaceRule}${operatingContract}${toolGuidelinesSection}`;\n\n\tif (fullPrompt) {\n\t\tprompt += `\n\nPI DOCS: root=${packageRoot}. Relevant work only; read needed README.md, \\`docs/...\\`, \\`examples/...\\` fully, follow links.`;\n\t}\n\n\treturn appendPromptResources(prompt, {\n\t\tappendSection,\n\t\tcontextFiles,\n\t\textensions: options.extensions ?? [],\n\t\tvisibleTools,\n\t\tfullPrompt,\n\t\thasRead,\n\t\tdate,\n\t\tpromptCwd,\n\t\tmodelCapability: options.modelCapability,\n\t});\n}\n\nfunction formatExtensionsForPrompt(extensions: Extension[], visibleTools: string[]): string {\n\tif (extensions.length === 0) {\n\t\treturn \"\";\n\t}\n\n\tconst lines = [\"\\n\\nEXTENSIONS: name, path, tools, commands, description\"];\n\tlet added = 0;\n\n\tfor (const ext of extensions) {\n\t\tconst name = getExtensionDisplayName(ext.path);\n\t\tconst description = getExtensionDescription(ext.path);\n\n\t\tconst tools = Array.from(ext.tools.keys()).filter((t) => visibleTools.includes(t));\n\t\tconst commands = Array.from(ext.commands.keys());\n\n\t\t// Skip extension listing if it has no visible tools, commands, or description\n\t\tif (tools.length === 0 && commands.length === 0 && !description) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tlines.push(\n\t\t\tJSON.stringify({\n\t\t\t\tname,\n\t\t\t\tpath: ext.path,\n\t\t\t\t...(tools.length > 0 ? { tools } : {}),\n\t\t\t\t...(commands.length > 0 ? { commands } : {}),\n\t\t\t\t...(description ? { description: compactPromptText(description, EXTENSION_DESCRIPTION_BUDGET_CHARS) } : {}),\n\t\t\t}),\n\t\t);\n\t\tadded++;\n\t}\n\n\tif (added === 0) {\n\t\treturn \"\";\n\t}\n\n\treturn lines.join(\"\\n\");\n}\n"]}
|
|
1
|
+
{"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpC,OAAO,EAAE,6BAA6B,EAAE,MAAM,2BAA2B,CAAC;AAC1E,OAAO,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC7C,OAAO,EAAE,uBAAuB,EAAE,uBAAuB,EAAE,MAAM,yBAAyB,CAAC;AAE3F,OAAO,EAAE,wCAAwC,EAA+B,MAAM,uBAAuB,CAAC;AAC9G,OAAO,EAAE,uBAAuB,EAAE,MAAM,gCAAgC,CAAC;AA0BzE,MAAM,gCAAgC,GACrC,sIAAsI,CAAC;AAExI,MAAM,yBAAyB,GAAG;;;;;;;8LAO4J,CAAC;AAE/L,MAAM,0BAA0B,GAAG;;;;;;;;;;;;IAY/B,gCAAgC,EAAE,CAAC;AAEvC,MAAM,+BAA+B,GAAG;;;;;;iEAMyB,6BAA6B;;;IAG1F,gCAAgC,EAAE,CAAC;AAEvC,MAAM,kCAAkC,GAAG;;;;;iEAKsB,6BAA6B;;;I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AC,CAAC,CAAC,CAAC;QACnF,MAAM,QAAQ,GAAG,KAAK,CAAC,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,CAAC;QAEjD,8EAA8E;QAC9E,IAAI,KAAK,CAAC,MAAM,KAAK,CAAC,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC;YACjE,SAAS;QACV,CAAC;QAED,KAAK,CAAC,IAAI,CACT,IAAI,CAAC,SAAS,CAAC;YACd,IAAI;YACJ,IAAI,EAAE,GAAG,CAAC,IAAI;YACd,GAAG,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACtC,GAAG,CAAC,QAAQ,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YAC5C,GAAG,CAAC,WAAW,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,iBAAiB,CAAC,WAAW,EAAE,kCAAkC,CAAC,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAC3G,CAAC,CACF,CAAC;QACF,KAAK,EAAE,CAAC;IACT,CAAC;IAED,IAAI,KAAK,KAAK,CAAC,EAAE,CAAC;QACjB,OAAO,EAAE,CAAC;IACX,CAAC;IAED,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AACzB,CAAC","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { dirname } from \"node:path\";\nimport { TOOL_FAILURE_RETRY_MODEL_RULE } from \"@caupulican/pi-agent-core\";\nimport { getReadmePath } from \"../config.ts\";\nimport { getExtensionDescription, getExtensionDisplayName } from \"./extension-metadata.ts\";\nimport type { Extension } from \"./extensions/types.ts\";\nimport { enforceModelCapabilitySystemPromptBudget, type ModelCapabilityProfile } from \"./model-capability.ts\";\nimport { SKILL_VAULT_SYSTEM_RULE } from \"./provider-prompt-contracts.ts\";\nimport type { Skill } from \"./skills.ts\";\n\nexport interface BuildSystemPromptOptions {\n\t/** Capability profile that selects the stable prompt shape. Missing means full/legacy behavior. */\n\tmodelCapability?: Pick<ModelCapabilityProfile, \"class\" | \"contextWindow\" | \"reasonCode\" | \"systemPromptMaxChars\">;\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/** Tools to include in the prompt. Defaults come from the shared active-tool surface. */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Global instruction files (with content) plus on-demand project paths (path only). */\n\tcontextFiles?: Array<{ path: string; content?: string }>;\n\t/** Discovered skills remain host-side; retained for extension/API construction compatibility. */\n\tskills?: Skill[];\n\t/** Discovered extensions currently active. */\n\textensions?: Extension[];\n}\n\nconst MODEL_BLIND_CREDENTIAL_AUTHORITY =\n\t\"Active secret_store: host gate authorizes model-blind activation/migration from named accessible sources; no duplicate confirmation.\";\n\nconst ULTRA_TERSE_OUTPUT_POLICY = `\n\nULTRA-TERSE OUTPUT\n\n- Drop articles/filler/pleasantries/hedging; fragments valid. Strip conjunctions only when clear; each fact once.\n- Never drop not/never/no/only/except; never invent abbreviations or use causal arrows. Preserve numbers, units, code symbols, function/API names, commands, errors.\n- No self-reference/tool narration/tables/emoji/log dumps. Keep user language. Full grammar: security, irreversible actions, ambiguous order. Replies terse; artifacts normal prose.\n- Answer shape: status/ops turns terse; analysis/review/evaluation asks get complete structured answers; never restate harness protocol text or failure-record JSON to the user as an answer.`;\n\nconst PI_ADAPTATIVE_CORE_SECTION = `\n\nOPERATING CONTRACT\n\n- Clear conversational outcome is goal; persist progress/evidence through compaction; finish or report blocker.\n- Hold scope; verify unknowns from primary sources; simplest proven design, one owner/path per invariant.\n- User outcome governs, method does not. Outcome risk: show evidence, test when practical, offer safest effective path, execute.\n- Work over 15 seconds: managed background run, event terminal, bounded handoff, owner notice; never poll.\n- Facts: memory; specialization: skills; behavior: source. Discard noise.\n- Implementation/verification work loads skill evidence-gated-tdd; architecture/performance design loads skill n-plus-2-architecture; their gates bind only while that work is active.\n- Explicit user instruction in current message overrides standing style (length/format/tone); security, untrusted-content, and authorization rules are never overridable.\n- Ask before broader scope, credential or authentication change/disclosure, destructive action, publication. Bound, source-label output; show paths.\n- ${MODEL_BLIND_CREDENTIAL_AUTHORITY}`;\n\nconst PI_ADAPTATIVE_LEAN_CORE_SECTION = `\n\nOPERATING CONTRACT\n\n- Complete current goal within scope, granted authority; keep progress, evidence concise.\n- Inspect relevant files and instructions before editing; make minimal coherent change, run focused checks.\n- Use active tools/schemas. On failure, follow error guidance. ${TOOL_FAILURE_RETRY_MODEL_RULE}\n- Batch independent reads, order mutations; report real output, unresolved failures.\n- Ask before destructive actions, credential disclosure or provider authentication changes, publication, push/tag/release, scope expansion.\n- ${MODEL_BLIND_CREDENTIAL_AUTHORITY}`;\n\nconst PI_ADAPTATIVE_MINIMAL_CORE_SECTION = `\n\nEXECUTION RULES\n\n- Work one scoped task. Inspect before editing, make small coherent change, run narrowest useful check.\n- Use listed tools/schemas. On failure, follow error guidance. ${TOOL_FAILURE_RETRY_MODEL_RULE}\n- Batch independent reads, order mutations. Report actual results; never claim incomplete action.\n- Ask before destructive actions, credential disclosure or provider authentication changes, publication, push/tag/release, material scope change.\n- ${MODEL_BLIND_CREDENTIAL_AUTHORITY}`;\n\nconst PI_ADAPTATIVE_CHAT_CORE_SECTION = `\n\nCHAT RULES\n\n- Answer concisely from conversation; state uncertainty.\n- No execution tools are active. Do not claim to read files, run commands, or make changes.\n- Say when the request requires a tool-capable model or additional user-provided context.`;\n\nconst DEFERRED_CONTEXT_PATH_BUDGET_CHARS = 512;\nconst EXTENSION_DESCRIPTION_BUDGET_CHARS = 180;\n\nfunction compactPromptText(value: string, maxChars: number): string {\n\tconst normalized = value.replace(/\\s+/g, \" \").trim();\n\tif (normalized.length <= maxChars) return normalized;\n\tlet end = maxChars - 1;\n\tconst code = normalized.charCodeAt(end - 1);\n\tif (code >= 0xd800 && code <= 0xdbff) end--;\n\treturn `${normalized.slice(0, end)}…`;\n}\n\nfunction formatContextFilesForPrompt(\n\tcontextFiles: Array<{ path: string; content?: string }>,\n\toptions: { deferContents: boolean; canRead: boolean },\n): string {\n\tif (contextFiles.length === 0) {\n\t\treturn \"\";\n\t}\n\tconst injected = options.deferContents ? [] : contextFiles.filter((file) => file.content !== undefined);\n\tconst deferred = options.deferContents ? contextFiles : contextFiles.filter((file) => file.content === undefined);\n\tconst parts: string[] = [];\n\n\tif (injected.length > 0) {\n\t\tconst lines = [\"\\n\\nPROJECT-SPECIFIC INSTRUCTIONS (apply in listed order)\"];\n\t\tconst seen = new Set<string>();\n\t\tfor (const { path, content } of injected) {\n\t\t\tconst identity = `${path}\\0${content ?? \"\"}`;\n\t\t\tif (seen.has(identity)) continue;\n\t\t\tseen.add(identity);\n\t\t\tlines.push(`FILE ${JSON.stringify(path)} (${(content ?? \"\").length} chars)`);\n\t\t\tlines.push(content ?? \"\");\n\t\t\tlines.push(\"END FILE\");\n\t\t}\n\t\tparts.push(lines.join(\"\\n\"));\n\t}\n\n\tif (deferred.length > 0) {\n\t\tconst lines = [\n\t\t\t\"\\n\\nPROJECT RULE PATHS — contents not preloaded.\",\n\t\t\toptions.deferContents\n\t\t\t\t? options.canRead\n\t\t\t\t\t? \"Before editing, writing, or running a mutating command, read each relevant listed file completely before any mutation. Follow its instructions; if a file cannot fit, ask for a scoped instruction digest.\"\n\t\t\t\t\t: \"No read tool is active. Ask the user for the relevant project instructions before giving project-specific guidance.\"\n\t\t\t\t: options.canRead\n\t\t\t\t\t? \"Read a listed file completely before following it. Do not assume its contents.\"\n\t\t\t\t\t: \"No read tool is active. Ask the user for the relevant project instructions before giving project-specific guidance.\",\n\t\t];\n\t\tlet pathChars = 0;\n\t\tlet included = 0;\n\t\tfor (const { path } of deferred) {\n\t\t\tconst line = `- ${JSON.stringify(path)}`;\n\t\t\tif (pathChars + line.length > DEFERRED_CONTEXT_PATH_BUDGET_CHARS) break;\n\t\t\tlines.push(line);\n\t\t\tpathChars += line.length + 1;\n\t\t\tincluded++;\n\t\t}\n\t\tconst omitted = deferred.length - included;\n\t\tif (omitted > 0) {\n\t\t\tlines.push(`- omitted=${omitted}`);\n\t\t\tlines.push(\n\t\t\t\t\"Do not mutate until the omitted instruction paths are supplied or a more capable profile is used.\",\n\t\t\t);\n\t\t}\n\t\tparts.push(lines.join(\"\\n\"));\n\t}\n\n\treturn parts.join(\"\");\n}\n\nfunction appendPromptResources(\n\tprompt: string,\n\toptions: {\n\t\tappendSection: string;\n\t\tcontextFiles: Array<{ path: string; content?: string }>;\n\t\textensions: Extension[];\n\t\tvisibleTools: string[];\n\t\tfullPrompt: boolean;\n\t\thasRead: boolean;\n\t\tdate: string;\n\t\tpromptCwd: string;\n\t\tmodelCapability: BuildSystemPromptOptions[\"modelCapability\"];\n\t},\n): string {\n\tlet result = prompt;\n\tif (options.appendSection) result += options.appendSection;\n\tresult += formatContextFilesForPrompt(options.contextFiles, {\n\t\tdeferContents: !options.fullPrompt,\n\t\tcanRead: options.hasRead,\n\t});\n\t// Extension metadata is redundant with the active tool snippets on constrained profiles.\n\tif (options.fullPrompt && options.extensions.length > 0) {\n\t\tresult += formatExtensionsForPrompt(options.extensions, options.visibleTools);\n\t}\n\t// Day-granularity only; keep this tail stable across every call on the same calendar day.\n\tresult += `\\nCurrent date: ${options.date}`;\n\t// Chat-class models have no filesystem tools, so cwd is unusable context and makes the hard\n\t// prompt budget depend on host checkout-path length. Tool-capable profiles retain it.\n\tif (options.modelCapability?.class !== \"chat\") {\n\t\tresult += `\\nCurrent working directory: ${options.promptCwd}`;\n\t}\n\t// Prompt resources can come from CRLF checkouts or user files. Canonicalize once at the final\n\t// assembly boundary so capability budgets and provider cache keys are host-independent.\n\tconst normalizedResult = result.replace(/\\r\\n?/g, \"\\n\");\n\treturn options.modelCapability\n\t\t? enforceModelCapabilitySystemPromptBudget(normalizedResult, options.modelCapability)\n\t\t: normalizedResult;\n}\n\n/**\n * Build the system prompt with tools, guidelines, and context.\n *\n * CACHE-STABILITY INVARIANT: providers treat the returned string as ONE prompt-cache block (a\n * single cache breakpoint covering the whole system prompt). The caller (SystemPromptBuilder /\n * AgentSession, see `_rebuildSystemPrompt` in agent-session.ts) rebuilds it only when the TOOL\n * SURFACE changes — never per turn. For a fixed `options` (fixed tool surface, cwd, context\n * files, extensions), two calls on the SAME CALENDAR DAY must return byte-identical\n * output, because `date` below is deliberately truncated to Y-M-D granularity. Do NOT widen it\n * to a timestamp (HH:MM:SS) or otherwise fold in any per-turn-volatile field (turn counters,\n * elapsed time, random ids, etc.) — that would cache-bust this entire block on EVERY turn instead\n * of once per calendar day, defeating provider prompt caching (cost + latency regression on every\n * request). Pinned by test/system-prompt-stability.test.ts.\n */\nexport function buildSystemPrompt(options: BuildSystemPromptOptions): string {\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tcwd,\n\t\tcontextFiles: providedContextFiles,\n\t} = options;\n\tconst resolvedCwd = cwd;\n\tconst promptCwd = resolvedCwd.replace(/\\\\/g, \"/\");\n\n\t// Day-granularity only (see cache-stability invariant on buildSystemPrompt above): this must\n\t// stay stable across every call within a calendar day, not just within a single turn.\n\tconst now = new Date();\n\tconst year = now.getFullYear();\n\tconst month = String(now.getMonth() + 1).padStart(2, \"0\");\n\tconst day = String(now.getDate()).padStart(2, \"0\");\n\tconst date = `${year}-${month}-${day}`;\n\n\tconst appendSection = appendSystemPrompt ? `\\n\\n${appendSystemPrompt}` : \"\";\n\n\tconst contextFiles = providedContextFiles ?? [];\n\tconst capabilityClass = options.modelCapability?.class ?? \"full\";\n\tconst fullPrompt = capabilityClass === \"full\";\n\tconst leanPrompt = capabilityClass === \"lean\";\n\n\tconst activeTools = selectedTools || [\"read\", \"bash\", \"python\", \"edit\", \"write\"];\n\tconst visibleTools = activeTools.filter((name) => !!toolSnippets?.[name]);\n\tconst hasRead = activeTools.includes(\"read\");\n\tconst coreSection = fullPrompt\n\t\t? PI_ADAPTATIVE_CORE_SECTION\n\t\t: leanPrompt\n\t\t\t? PI_ADAPTATIVE_LEAN_CORE_SECTION\n\t\t\t: capabilityClass === \"minimal\"\n\t\t\t\t? PI_ADAPTATIVE_MINIMAL_CORE_SECTION\n\t\t\t\t: PI_ADAPTATIVE_CHAT_CORE_SECTION;\n\tconst skillVaultContract = activeTools.includes(\"skill\") ? `\\n\\n${SKILL_VAULT_SYSTEM_RULE}` : \"\";\n\tconst operatingContract = `${coreSection}${skillVaultContract}${ULTRA_TERSE_OUTPUT_POLICY}`;\n\n\tif (customPrompt) {\n\t\tlet prompt = customPrompt;\n\n\t\tprompt += operatingContract;\n\t\treturn appendPromptResources(prompt, {\n\t\t\tappendSection,\n\t\t\tcontextFiles,\n\t\t\textensions: options.extensions ?? [],\n\t\t\tvisibleTools,\n\t\t\tfullPrompt,\n\t\t\thasRead,\n\t\t\tdate,\n\t\t\tpromptCwd,\n\t\t\tmodelCapability: options.modelCapability,\n\t\t});\n\t}\n\n\tconst packageRoot = dirname(getReadmePath());\n\n\t// Build tools list based on selected tools.\n\t// A tool appears in Available tools only when the caller provides a one-line snippet.\n\tconst toolsList =\n\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets![name]}`).join(\"\\n\") : \"(none)\";\n\n\t// Build guidelines based on which tools are actually available\n\tconst guidelinesList: string[] = [];\n\tconst guidelinesSet = new Set<string>();\n\tconst addGuideline = (guideline: string): void => {\n\t\tif (guidelinesSet.has(guideline)) {\n\t\t\treturn;\n\t\t}\n\t\tguidelinesSet.add(guideline);\n\t\tguidelinesList.push(guideline);\n\t};\n\n\tconst hasBash = activeTools.includes(\"bash\");\n\tconst hasPython = activeTools.includes(\"python\");\n\tconst hasGrep = activeTools.includes(\"grep\");\n\tconst hasFind = activeTools.includes(\"find\");\n\tconst hasLs = activeTools.includes(\"ls\");\n\tconst hasReadOnlyTools = hasRead || hasGrep || hasFind || hasLs;\n\n\t// File exploration guidelines\n\tif (!fullPrompt && !leanPrompt) {\n\t\tif (hasBash) addGuideline(\"Use bash for bounded shell commands\");\n\t\tif (hasReadOnlyTools) addGuideline(\"Batch independent reads; keep mutations and dependent calls ordered\");\n\t} else if (hasBash && !hasGrep && !hasFind && !hasLs) {\n\t\taddGuideline(\"Bash: ls, rg, find\");\n\t}\n\tif (fullPrompt || leanPrompt) {\n\t\tif (hasBash || hasGrep || hasFind) {\n\t\t\taddGuideline(\"rg/jq: scoped roots/filters, exhaustive output to file\");\n\t\t}\n\t\tif (hasPython) {\n\t\t\taddGuideline(\"Python: bounded scripts/data, source edits via read/edit/write\");\n\t\t}\n\t\tif (hasReadOnlyTools) {\n\t\t\taddGuideline(\"Batch independent reads; order dependent/mutating/stateful calls\");\n\t\t}\n\t}\n\n\tif (fullPrompt || leanPrompt) {\n\t\tfor (const guideline of promptGuidelines ?? []) {\n\t\t\tconst normalized = guideline.trim();\n\t\t\tif (normalized.length > 0) {\n\t\t\t\taddGuideline(normalized);\n\t\t\t}\n\t\t}\n\t}\n\n\tconst guidelines = guidelinesList.map((g) => `- ${g}`).join(\"\\n\");\n\tconst toolGuidelinesSection = guidelines.length > 0 ? `\\n\\nTOOL GUIDELINES\\n\\n${guidelines}` : \"\";\n\n\tconst introduction = fullPrompt\n\t\t? \"Pi-Adaptative: self-evolving assistant. Deliver goals within authority; preserve continuity, own integration.\"\n\t\t: leanPrompt\n\t\t\t? \"Pi-Adaptative bounded coding agent. Complete current goal with active surface; preserve handoff evidence.\"\n\t\t\t: capabilityClass === \"minimal\"\n\t\t\t\t? \"Pi-Adaptative focused coding executor. Complete one scoped task with active tools; report verified results.\"\n\t\t\t\t: \"Pi-Adaptative concise chat assistant. No execution tools active.\";\n\tconst toolSurfaceRule =\n\t\tfullPrompt || leanPrompt\n\t\t\t? \"Use active tool surface only; unlisted capabilities may exist.\"\n\t\t\t: \"Use only the active tool surface.\";\n\tlet prompt = `${introduction}\n\nAvailable tools:\n${toolsList}\n\n${toolSurfaceRule}${operatingContract}${toolGuidelinesSection}`;\n\n\tif (fullPrompt) {\n\t\tprompt += `\n\nPI DOCS: root=${packageRoot}. Relevant work only; read needed README.md, \\`docs/...\\`, \\`examples/...\\` fully, follow links.`;\n\t}\n\n\treturn appendPromptResources(prompt, {\n\t\tappendSection,\n\t\tcontextFiles,\n\t\textensions: options.extensions ?? [],\n\t\tvisibleTools,\n\t\tfullPrompt,\n\t\thasRead,\n\t\tdate,\n\t\tpromptCwd,\n\t\tmodelCapability: options.modelCapability,\n\t});\n}\n\nfunction formatExtensionsForPrompt(extensions: Extension[], visibleTools: string[]): string {\n\tif (extensions.length === 0) {\n\t\treturn \"\";\n\t}\n\n\tconst lines = [\"\\n\\nEXTENSIONS: name, path, tools, commands, description\"];\n\tlet added = 0;\n\n\tfor (const ext of extensions) {\n\t\tconst name = getExtensionDisplayName(ext.path);\n\t\tconst description = getExtensionDescription(ext.path);\n\n\t\tconst tools = Array.from(ext.tools.keys()).filter((t) => visibleTools.includes(t));\n\t\tconst commands = Array.from(ext.commands.keys());\n\n\t\t// Skip extension listing if it has no visible tools, commands, or description\n\t\tif (tools.length === 0 && commands.length === 0 && !description) {\n\t\t\tcontinue;\n\t\t}\n\n\t\tlines.push(\n\t\t\tJSON.stringify({\n\t\t\t\tname,\n\t\t\t\tpath: ext.path,\n\t\t\t\t...(tools.length > 0 ? { tools } : {}),\n\t\t\t\t...(commands.length > 0 ? { commands } : {}),\n\t\t\t\t...(description ? { description: compactPromptText(description, EXTENSION_DESCRIPTION_BUDGET_CHARS) } : {}),\n\t\t\t}),\n\t\t);\n\t\tadded++;\n\t}\n\n\tif (added === 0) {\n\t\treturn \"\";\n\t}\n\n\treturn lines.join(\"\\n\");\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"goal.d.ts","sourceRoot":"","sources":["../../../src/core/tools/goal.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AACnF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,EAAE,KAAK,iBAAiB,EAAwB,MAAM,4BAA4B,CAAC;AAC1F,OAAO,EAAyB,KAAK,SAAS,EAA0C,MAAM,wBAAwB,CAAC;AACvH,OAAO,EAGN,KAAK,cAAc,EACnB,KAAK,eAAe,EAEpB,MAAM,4BAA4B,CAAC;
|
|
1
|
+
{"version":3,"file":"goal.d.ts","sourceRoot":"","sources":["../../../src/core/tools/goal.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAC5D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AAC9D,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,uCAAuC,CAAC;AACnF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,EAAE,KAAK,iBAAiB,EAAwB,MAAM,4BAA4B,CAAC;AAC1F,OAAO,EAAyB,KAAK,SAAS,EAA0C,MAAM,wBAAwB,CAAC;AACvH,OAAO,EAGN,KAAK,cAAc,EACnB,KAAK,eAAe,EAEpB,MAAM,4BAA4B,CAAC;AAWpC,QAAA,MA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;QAC3B,aAAa,EAAE,MAAM,CAAC;QACtB,YAAY,EAAE,MAAM,CAAC;KACrB,KAAK,OAAO,CAAC;QAAE,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IACxD,mGAAmG;IACnG,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;IACnB;;;OAGG;IACH,oCAAoC,CAAC,EAAE,MAAM,OAAO,CAAC;IACrD;;;;;OAKG;IACH,gBAAgB,CAAC,EAAE,MAAM,SAAS,eAAe,EAAE,CAAC;IACpD,6FAA6F;IAC7F,sBAAsB,CAAC,EAAE,MAAM,SAAS,qBAAqB,EAAE,CAAC;IAChE,+DAA+D;IAC/D,iBAAiB,CAAC,EAAE,MAAM;QAAE,KAAK,EAAE,MAAM,CAAC;QAAC,YAAY,EAAE,MAAM,CAAC;QAAC,MAAM,CAAC,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,GAAG,SAAS,CAAC;IAC/G,+GAA+G;IAC/G,cAAc,CAAC,EAAE,CAAC,KAAK,EAAE,IAAI,CAAC,aAAa,EAAE,UAAU,GAAG,aAAa,CAAC,KAAK,MAAM,GAAG,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IAChH;;;OAGG;IACH,mBAAmB,CAAC,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,OAAO,CAAC;CAC/C;AAuLD,wBAAgB,wBAAwB,CAAC,IAAI,EAAE,oBAAoB,GAAG,kBAAkB,CA+OvF;AAED;;;;GAIG;AACH,wBAAgB,kCAAkC,CAAC,QAAQ,EAAE,kBAAkB,iJAuD9E"}
|
package/dist/core/tools/goal.js
CHANGED
|
@@ -5,7 +5,7 @@ import { getGoalStateRevision } from "../goals/goal-lifecycle.js";
|
|
|
5
5
|
import { isGoalExecutionActive } from "../goals/goal-state.js";
|
|
6
6
|
import { applyGoalAction, summarizeGoalState, } from "../goals/goal-tool-core.js";
|
|
7
7
|
import { GOAL_LIFECYCLE_TOOL_NAMES, LEGACY_GOAL_TOOL_NAME } from "../goals/goal-tool-names.js";
|
|
8
|
-
import { emptyOrchestrationCall, renderOrchestrationToolResult, } from "./orchestration-panel.js";
|
|
8
|
+
import { emptyOrchestrationCall, goalEvidencePanelRow, goalRequirementPanelRow, renderOrchestrationToolResult, } from "./orchestration-panel.js";
|
|
9
9
|
import { resolveToCwd } from "./path-utils.js";
|
|
10
10
|
const goalSchema = Type.Object({
|
|
11
11
|
action: Type.Union([
|
|
@@ -218,20 +218,9 @@ function goalPanelModel(details) {
|
|
|
218
218
|
`${state.evidence.length} evidence`,
|
|
219
219
|
...(state.tokenBudget !== undefined ? [`${state.tokensUsed ?? 0}/${state.tokenBudget} tokens`] : []),
|
|
220
220
|
],
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
: requirement.status === "open"
|
|
225
|
-
? "pending"
|
|
226
|
-
: "blocked",
|
|
227
|
-
label: requirement.text,
|
|
228
|
-
meta: [
|
|
229
|
-
requirement.id,
|
|
230
|
-
requirement.evidenceIds.length > 0 ? `${requirement.evidenceIds.length} evidence` : undefined,
|
|
231
|
-
requirement.boundLaneId ? `worker ${requirement.boundLaneId}` : undefined,
|
|
232
|
-
].filter((value) => value !== undefined),
|
|
233
|
-
details: requirement.blockedReason ? [`blocked: ${requirement.blockedReason}`] : undefined,
|
|
234
|
-
})),
|
|
221
|
+
description: state.userGoal,
|
|
222
|
+
wrapRows: true,
|
|
223
|
+
rows: [...state.requirements.map(goalRequirementPanelRow), ...state.evidence.map(goalEvidencePanelRow)],
|
|
235
224
|
notices: [
|
|
236
225
|
...(details.dispatchSkipReason
|
|
237
226
|
? [{ status: "warning", text: `Worker dispatch skipped: ${details.dispatchSkipReason}` }]
|
|
@@ -257,6 +246,7 @@ export function createGoalToolDefinition(deps) {
|
|
|
257
246
|
promptSnippet: "Read or update the durable goal.",
|
|
258
247
|
promptGuidelines: [
|
|
259
248
|
"Start when persistent continuation materially benefits current work or the user/system requests it. Skip routine one-turn tasks; get if uncertain; never replace unfinished goal; tokenBudget only if requested.",
|
|
249
|
+
"After bounded read-only survey, make the project-relative delivery contract explicit in the goal requirements: POC/MVP proves the requested capability; complete means full integration across affected project surfaces.",
|
|
260
250
|
"Plans: task_steps. Workers: delegate. Background tools: tool_task wait once; cite taskId as kind=tool evidence.",
|
|
261
251
|
"increment satisfies the current open requirement from unused evidence, or completes when none remain.",
|
|
262
252
|
"complete needs current authoritative evidence, no remaining work, no active goal-owned lanes, no open task_steps, no goal-owned running or cited non-completed tool_task, and no active pipeline. block_goal needs same real impasse for 3 goal turns.",
|
|
@@ -271,7 +261,7 @@ export function createGoalToolDefinition(deps) {
|
|
|
271
261
|
return renderOrchestrationToolResult(theme, goalPanelModel(details), {
|
|
272
262
|
isPartial,
|
|
273
263
|
collapse: !expanded && details?.applied === true,
|
|
274
|
-
expanded
|
|
264
|
+
expanded,
|
|
275
265
|
});
|
|
276
266
|
},
|
|
277
267
|
async execute(_toolCallId, input) {
|