promptopskit 0.2.3 → 0.2.4

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/README.md CHANGED
@@ -34,6 +34,7 @@ npm install promptopskit
34
34
 
35
35
  ```bash
36
36
  npx promptopskit init ./prompts
37
+ npx promptopskit skill
37
38
  ```
38
39
 
39
40
  This creates:
@@ -246,8 +247,9 @@ prompts/
246
247
  ## CLI
247
248
 
248
249
  ```bash
249
- # Scaffold starter prompts
250
+ # Scaffold starter prompts and deploy AI agent instructions
250
251
  promptopskit init [dir]
252
+ promptopskit skill
251
253
 
252
254
  # Validate all .md files in a directory
253
255
  promptopskit validate <dir> [--strict]
@@ -267,7 +269,7 @@ promptopskit skill [--target agents|claude|copilot|cursor] [--force]
267
269
 
268
270
  ## AI Agent Instructions
269
271
 
270
- The `skill` command deploys instruction files so AI coding assistants automatically understand how to create and manage prompts with promptopskit. By default it generates files for **all** major vendors:
272
+ The `skill` command deploys instruction files so AI coding assistants automatically understand how to create and manage prompts with promptopskit. Each file references the full guide at `node_modules/promptopskit/SKILL.md`, so instructions stay in sync with the installed version. By default it generates files for **all** major vendors:
271
273
 
272
274
  ```bash
273
275
  # Deploy for all AI coding assistants (default)
@@ -280,11 +282,13 @@ promptopskit skill
280
282
  # Deploy only a specific target
281
283
  promptopskit skill --target copilot
282
284
 
283
- # Overwrite existing instructions files
285
+ # Overwrite entire file instead of merging
284
286
  promptopskit skill --force
285
287
  ```
286
288
 
287
- The `CLAUDE.md` file uses Claude Code's `@AGENTS.md` import syntax to avoid duplicating content. The deployed files cover the prompt format, front matter schema, variable interpolation, includes, overrides, the TypeScript API, provider adapters, and project conventions — everything an AI agent needs to write correct prompts on the first try.
289
+ If a target file already exists, the promptopskit section is merged in-place (or appended) rather than skipping or overwriting. Use `--force` to replace the entire file.
290
+
291
+ The `CLAUDE.md` file uses Claude Code's `@AGENTS.md` import syntax to avoid duplicating content.
288
292
 
289
293
  ## Inline Source
290
294
 
package/SKILL.md ADDED
@@ -0,0 +1,327 @@
1
+ # promptopskit — Prompt Engineering Skill
2
+
3
+ This project uses **promptopskit** to manage LLM prompts as code.
4
+ Prompts live in markdown files with YAML front matter, are validated against
5
+ a schema, and render into provider-specific request bodies (OpenAI, Anthropic,
6
+ Gemini, OpenRouter). Follow these instructions when creating or editing prompts.
7
+
8
+ ---
9
+
10
+ ## Prompt file format
11
+
12
+ Every prompt is a `.md` file with two parts:
13
+
14
+ 1. **YAML front matter** — model settings, provider config, variables, overrides
15
+ 2. **Markdown body** — sections separated by H1 headings
16
+
17
+ ### Minimal example
18
+
19
+ ```markdown
20
+ ---
21
+ id: greeting
22
+ schema_version: 1
23
+ provider: openai
24
+ model: gpt-5.4
25
+ context:
26
+ inputs:
27
+ - name
28
+ ---
29
+
30
+ # System instructions
31
+
32
+ You are a helpful assistant.
33
+
34
+ # Prompt template
35
+
36
+ Hello {{ name }}, how can I help you?
37
+ ```
38
+
39
+ ---
40
+
41
+ ## Front matter reference
42
+
43
+ | Field | Type | Required | Description |
44
+ |-------|------|----------|-------------|
45
+ | `id` | string | **yes** | Unique identifier for the prompt |
46
+ | `schema_version` | number | yes | Always `1` |
47
+ | `description` | string | no | Human-readable description |
48
+ | `provider` | enum | no | `openai`, `anthropic`, `google`, `gemini`, `openrouter`, or `any` |
49
+ | `model` | string | no | Model identifier (e.g. `gpt-5.4`, `claude-sonnet-4-20250514`) |
50
+ | `fallback_models` | string[] | no | Ordered fallback model list |
51
+ | `reasoning` | object | no | `{ effort: low|medium|high, budget_tokens: number }` |
52
+ | `sampling` | object | no | `{ temperature, top_p, frequency_penalty, presence_penalty, stop, max_output_tokens }` |
53
+ | `response` | object | no | `{ format: text|json|markdown, stream: boolean }` |
54
+ | `tools` | array | no | Tool names (strings) or inline definitions with `{ name, description, input_schema }` |
55
+ | `mcp` | object | no | `{ servers: [string | { name, config }] }` |
56
+ | `context.inputs` | string[] | no | Declared variable names used in templates |
57
+ | `context.history` | object | no | `{ max_items: number }` |
58
+ | `includes` | string[] | no | Relative paths to other prompt files to include |
59
+ | `environments` | object | no | Per-environment overrides (see Overrides) |
60
+ | `tiers` | object | no | Per-tier overrides (see Overrides) |
61
+ | `metadata` | object | no | `{ owner, tags, review_required, stable }` |
62
+
63
+ ---
64
+
65
+ ## Sections (markdown body)
66
+
67
+ Use H1 headings to define sections. The parser recognizes these headings
68
+ (case-insensitive):
69
+
70
+ | Heading | Maps to | Purpose |
71
+ |---------|---------|---------|
72
+ | `# System instructions` | `system_instructions` | System/developer message |
73
+ | `# Prompt template` | `prompt_template` | User message template |
74
+ | `# Notes` | `notes` | Documentation only — not sent to the model |
75
+
76
+ If the body has **no H1 headings**, the entire body becomes the `prompt_template`.
77
+
78
+ ---
79
+
80
+ ## Variable interpolation
81
+
82
+ Use `{{ variable_name }}` syntax in system instructions and prompt template
83
+ sections. Variables are replaced at render time.
84
+
85
+ Rules:
86
+ - Declare all variables in `context.inputs` — validation warns on undeclared usage
87
+ - Escape literal braces with `\{{` and `\}}`
88
+ - In strict mode, missing variables throw an error
89
+ - In permissive mode, unresolved placeholders are left intact
90
+
91
+ ---
92
+
93
+ ## Includes (composition)
94
+
95
+ Compose prompts from shared fragments:
96
+
97
+ ```yaml
98
+ includes:
99
+ - ./shared/tone.md
100
+ - ./shared/safety.md
101
+ ```
102
+
103
+ Included files are parsed and their `system_instructions` are **prepended**
104
+ before the including file's own system instructions. Includes resolve
105
+ recursively. Circular includes are detected and rejected.
106
+
107
+ > **Note:** Included files do not inherit folder defaults. Only the top-level
108
+ > prompt that is loaded via `loadPromptFile` receives defaults.
109
+
110
+ ---
111
+
112
+ ## Folder defaults (`defaults.md`)
113
+
114
+ Define shared defaults for a prompt tree by adding a `defaults.md` file in any
115
+ folder:
116
+
117
+ ```text
118
+ prompts/
119
+ ├── defaults.md # global provider, model, metadata + system instructions
120
+ └── support/
121
+ ├── defaults.md # overrides for support/*
122
+ └── reply.md # inherits from support/defaults.md
123
+ ```
124
+
125
+ Supported default fields:
126
+ - `provider` (front matter) — default provider for the folder
127
+ - `model` (front matter) — default model for the folder
128
+ - `metadata` (front matter) — merged with prompt-local metadata
129
+ - `# System instructions` (body section) — used when the prompt has none
130
+
131
+ This lets you configure app-wide settings like `provider` and `model`
132
+ in a single root `defaults.md`, so individual prompts only declare what's unique to them.
133
+
134
+ Rules:
135
+ - Nearest subfolder `defaults.md` overrides parent defaults
136
+ - Prompt-local values always take precedence over defaults
137
+ - `defaults.md` files are skipped during compilation and validation
138
+ - `loadPromptFile` defaults the search boundary to the file's own directory;
139
+ pass `defaultsRoot` to enable ancestor traversal
140
+
141
+ ---
142
+
143
+ ## Environment & tier overrides
144
+
145
+ Override model settings per environment or tier:
146
+
147
+ ```yaml
148
+ environments:
149
+ development:
150
+ model: gpt-4.1-mini
151
+ reasoning:
152
+ effort: low
153
+ sampling:
154
+ temperature: 0.9
155
+ production:
156
+ model: gpt-5.4
157
+ reasoning:
158
+ effort: high
159
+ sampling:
160
+ temperature: 0.3
161
+
162
+ tiers:
163
+ free:
164
+ model: gpt-4.1-mini
165
+ sampling:
166
+ max_output_tokens: 500
167
+ premium:
168
+ model: gpt-5.4
169
+ ```
170
+
171
+ Overridable fields: `model`, `fallback_models`, `reasoning`, `sampling`,
172
+ `response`, `tools`.
173
+
174
+ Override application order: **base → environment → tier → runtime**.
175
+
176
+ ---
177
+
178
+ ## Test sidecars
179
+
180
+ Create a `.test.yaml` file alongside a prompt to define test cases:
181
+
182
+ ```yaml
183
+ # greeting.test.yaml
184
+ cases:
185
+ - name: basic
186
+ variables:
187
+ name: "World"
188
+ - name: formal
189
+ variables:
190
+ name: "Dr. Smith"
191
+ ```
192
+
193
+ ---
194
+
195
+ ## Using the library (TypeScript / JavaScript)
196
+
197
+ ### Quick start
198
+
199
+ ```typescript
200
+ import { createPromptOpsKit } from 'promptopskit';
201
+
202
+ const kit = createPromptOpsKit({ sourceDir: './prompts' });
203
+
204
+ // Load → resolve includes → apply overrides → render
205
+ const request = await kit.renderPrompt('greeting', {
206
+ variables: { name: 'Alice' },
207
+ environment: 'production',
208
+ });
209
+
210
+ // request.body is ready for the provider's API
211
+ const response = await fetch('https://api.openai.com/v1/chat/completions', {
212
+ method: 'POST',
213
+ headers: {
214
+ 'Content-Type': 'application/json',
215
+ Authorization: `Bearer ${apiKey}`,
216
+ },
217
+ body: JSON.stringify(request.body),
218
+ });
219
+ ```
220
+
221
+ ### Step-by-step API
222
+
223
+ ```typescript
224
+ import {
225
+ parsePrompt,
226
+ resolveIncludes,
227
+ applyOverrides,
228
+ getAdapter,
229
+ } from 'promptopskit';
230
+ import { readFileSync } from 'fs';
231
+
232
+ // 1. Parse a prompt file
233
+ const source = readFileSync('./prompts/greeting.md', 'utf-8');
234
+ const asset = parsePrompt(source, 'greeting.md');
235
+
236
+ // 2. Resolve includes
237
+ const resolved = await resolveIncludes(asset, './prompts');
238
+
239
+ // 3. Apply overrides
240
+ const configured = applyOverrides(resolved, {
241
+ environment: 'production',
242
+ tier: 'premium',
243
+ });
244
+
245
+ // 4. Get provider adapter and render
246
+ const adapter = getAdapter(configured.provider ?? 'openai');
247
+ const request = adapter.render(configured, {
248
+ variables: { name: 'Alice' },
249
+ history: [
250
+ { role: 'user', content: 'Previous message' },
251
+ { role: 'assistant', content: 'Previous response' },
252
+ ],
253
+ });
254
+ ```
255
+
256
+ ### Available provider adapters
257
+
258
+ | Provider | Import path | Provider request format |
259
+ |----------|------------|----------------------|
260
+ | OpenAI | `promptopskit` or `promptopskit/openai` | Chat Completions API |
261
+ | Anthropic | `promptopskit/anthropic` | Messages API |
262
+ | Gemini | `promptopskit/gemini` | GenerateContent API |
263
+ | OpenRouter | `promptopskit/openrouter` | OpenAI-compatible + extras |
264
+
265
+ ### Validation
266
+
267
+ ```typescript
268
+ import { validateAsset, parsePrompt } from 'promptopskit';
269
+
270
+ const asset = parsePrompt(source);
271
+ const result = validateAsset(asset);
272
+
273
+ if (!result.valid) {
274
+ console.error(result.errors); // Error codes: POK001-POK021
275
+ }
276
+ ```
277
+
278
+ ### Testing helpers
279
+
280
+ ```typescript
281
+ import { createMockAsset, parseTestPrompt } from 'promptopskit/testing';
282
+
283
+ // Create a mock asset for unit tests
284
+ const mock = createMockAsset({ model: 'gpt-4.1-mini' });
285
+
286
+ // Parse an inline prompt string for tests
287
+ const asset = parseTestPrompt(`
288
+ ---
289
+ id: test
290
+ schema_version: 1
291
+ provider: openai
292
+ model: gpt-5.4
293
+ ---
294
+
295
+ # Prompt template
296
+
297
+ Hello {{ name }}
298
+ `);
299
+ ```
300
+
301
+ ---
302
+
303
+ ## CLI commands
304
+
305
+ | Command | Description |
306
+ |---------|-------------|
307
+ | `promptopskit init [dir]` | Scaffold a prompts directory with starter files (including `defaults.md`) |
308
+ | `promptopskit validate <dir>` | Validate all prompt files in a directory |
309
+ | `promptopskit compile <src> <out>` | Compile .md prompts to JSON artifacts |
310
+ | `promptopskit render <file> [--set key=value]` | Render a prompt preview |
311
+ | `promptopskit inspect <file>` | Print the normalized prompt asset |
312
+
313
+ ---
314
+
315
+ ## Conventions to follow
316
+
317
+ 1. **One prompt per file** — each `.md` file is a single prompt asset
318
+ 2. **Always set `id` and `schema_version: 1`** in front matter (or inherit `schema_version` from `defaults.md`)
319
+ 3. **Declare all variables** in `context.inputs` that appear in templates
320
+ 4. **Use includes** for shared system instructions (tone, safety, formatting)
321
+ 5. **Keep prompt templates focused** — compose behavior via includes, not duplication
322
+ 6. **Use environment overrides** for dev/staging/prod model differences
323
+ 7. **Add test sidecars** (`.test.yaml`) for critical prompts
324
+ 8. **Run `promptopskit validate`** before committing changes
325
+ 9. **Use `defaults.md`** to share provider, model, metadata, and system instructions across a folder
326
+ 10. **Variable names** should be `snake_case`
327
+ 11. **Prompt file names** should be `kebab-case.md`
package/dist/cli/index.js CHANGED
@@ -990,6 +990,12 @@ Options:
990
990
  --force, -f Overwrite entire file instead of merging
991
991
  --help, -h Show this help
992
992
  `.trim();
993
+ var STUB_CONTENT = `# promptopskit
994
+
995
+ This project uses **promptopskit** to manage LLM prompts as code.
996
+ Read the full guide at \`node_modules/promptopskit/SKILL.md\` before
997
+ creating or editing prompt files.`;
998
+ var CLAUDE_LINE = "@AGENTS.md";
993
999
  var TARGETS = {
994
1000
  agents: {
995
1001
  path: "AGENTS.md",
@@ -997,7 +1003,7 @@ var TARGETS = {
997
1003
  },
998
1004
  claude: {
999
1005
  path: "CLAUDE.md",
1000
- wrap: () => "@AGENTS.md\n"
1006
+ wrap: () => CLAUDE_LINE + "\n"
1001
1007
  },
1002
1008
  copilot: {
1003
1009
  path: ".github/instructions/promptopskit.instructions.md",
@@ -1041,7 +1047,11 @@ async function skill(args) {
1041
1047
  for (const target of targets) {
1042
1048
  const config = TARGETS[target];
1043
1049
  const filePath = config.path;
1044
- const markedContent = config.wrap(wrapMarkers(SKILL_CONTENT));
1050
+ if (target === "claude") {
1051
+ written += await deployClaude(filePath, force);
1052
+ continue;
1053
+ }
1054
+ const markedContent = config.wrap(wrapMarkers(STUB_CONTENT));
1045
1055
  if (existsSync3(filePath) && !force) {
1046
1056
  const existing = await readFile4(filePath, "utf-8");
1047
1057
  const merged = mergeContent(existing, markedContent);
@@ -1064,6 +1074,24 @@ async function skill(args) {
1064
1074
  console.log(`AI agents will now understand how to create and manage prompts with promptopskit.`);
1065
1075
  }
1066
1076
  }
1077
+ async function deployClaude(filePath, force) {
1078
+ const content = CLAUDE_LINE + "\n";
1079
+ if (!existsSync3(filePath) || force) {
1080
+ await mkdir3(dirname5(filePath), { recursive: true });
1081
+ await writeFile3(filePath, content, "utf-8");
1082
+ console.log(` \u2713 ${filePath}`);
1083
+ return 1;
1084
+ }
1085
+ const existing = await readFile4(filePath, "utf-8");
1086
+ if (existing.split("\n").some((line) => line.trim() === CLAUDE_LINE)) {
1087
+ console.log(` skip ${filePath} (already up to date)`);
1088
+ return 0;
1089
+ }
1090
+ const separator = existing.endsWith("\n") ? "\n" : "\n\n";
1091
+ await writeFile3(filePath, existing + separator + content, "utf-8");
1092
+ console.log(` \u2713 ${filePath} (merged)`);
1093
+ return 1;
1094
+ }
1067
1095
  function wrapMarkers(content) {
1068
1096
  return `${MARKER_START}
1069
1097
  ${content}
@@ -1078,334 +1106,6 @@ function mergeContent(existing, markedContent) {
1078
1106
  const separator = existing.endsWith("\n") ? "\n" : "\n\n";
1079
1107
  return existing + separator + markedContent + "\n";
1080
1108
  }
1081
- var SKILL_CONTENT = `# promptopskit \u2014 Prompt Engineering Skill
1082
-
1083
- This project uses **promptopskit** to manage LLM prompts as code.
1084
- Prompts live in markdown files with YAML front matter, are validated against
1085
- a schema, and render into provider-specific request bodies (OpenAI, Anthropic,
1086
- Gemini, OpenRouter). Follow these instructions when creating or editing prompts.
1087
-
1088
- ---
1089
-
1090
- ## Prompt file format
1091
-
1092
- Every prompt is a \`.md\` file with two parts:
1093
-
1094
- 1. **YAML front matter** \u2014 model settings, provider config, variables, overrides
1095
- 2. **Markdown body** \u2014 sections separated by H1 headings
1096
-
1097
- ### Minimal example
1098
-
1099
- \`\`\`markdown
1100
- ---
1101
- id: greeting
1102
- schema_version: 1
1103
- provider: openai
1104
- model: gpt-5.4
1105
- context:
1106
- inputs:
1107
- - name
1108
- ---
1109
-
1110
- # System instructions
1111
-
1112
- You are a helpful assistant.
1113
-
1114
- # Prompt template
1115
-
1116
- Hello {{ name }}, how can I help you?
1117
- \`\`\`
1118
-
1119
- ---
1120
-
1121
- ## Front matter reference
1122
-
1123
- | Field | Type | Required | Description |
1124
- |-------|------|----------|-------------|
1125
- | \`id\` | string | **yes** | Unique identifier for the prompt |
1126
- | \`schema_version\` | number | yes | Always \`1\` |
1127
- | \`description\` | string | no | Human-readable description |
1128
- | \`provider\` | enum | no | \`openai\`, \`anthropic\`, \`google\`, \`gemini\`, \`openrouter\`, or \`any\` |
1129
- | \`model\` | string | no | Model identifier (e.g. \`gpt-5.4\`, \`claude-sonnet-4-20250514\`) |
1130
- | \`fallback_models\` | string[] | no | Ordered fallback model list |
1131
- | \`reasoning\` | object | no | \`{ effort: low|medium|high, budget_tokens: number }\` |
1132
- | \`sampling\` | object | no | \`{ temperature, top_p, frequency_penalty, presence_penalty, stop, max_output_tokens }\` |
1133
- | \`response\` | object | no | \`{ format: text|json|markdown, stream: boolean }\` |
1134
- | \`tools\` | array | no | Tool names (strings) or inline definitions with \`{ name, description, input_schema }\` |
1135
- | \`mcp\` | object | no | \`{ servers: [string | { name, config }] }\` |
1136
- | \`context.inputs\` | string[] | no | Declared variable names used in templates |
1137
- | \`context.history\` | object | no | \`{ max_items: number }\` |
1138
- | \`includes\` | string[] | no | Relative paths to other prompt files to include |
1139
- | \`environments\` | object | no | Per-environment overrides (see Overrides) |
1140
- | \`tiers\` | object | no | Per-tier overrides (see Overrides) |
1141
- | \`metadata\` | object | no | \`{ owner, tags, review_required, stable }\` |
1142
-
1143
- ---
1144
-
1145
- ## Sections (markdown body)
1146
-
1147
- Use H1 headings to define sections. The parser recognizes these headings
1148
- (case-insensitive):
1149
-
1150
- | Heading | Maps to | Purpose |
1151
- |---------|---------|---------|
1152
- | \`# System instructions\` | \`system_instructions\` | System/developer message |
1153
- | \`# Prompt template\` | \`prompt_template\` | User message template |
1154
- | \`# Notes\` | \`notes\` | Documentation only \u2014 not sent to the model |
1155
-
1156
- If the body has **no H1 headings**, the entire body becomes the \`prompt_template\`.
1157
-
1158
- ---
1159
-
1160
- ## Variable interpolation
1161
-
1162
- Use \`{{ variable_name }}\` syntax in system instructions and prompt template
1163
- sections. Variables are replaced at render time.
1164
-
1165
- Rules:
1166
- - Declare all variables in \`context.inputs\` \u2014 validation warns on undeclared usage
1167
- - Escape literal braces with \`\\\\{{\` and \`\\\\}}\`
1168
- - In strict mode, missing variables throw an error
1169
- - In permissive mode, unresolved placeholders are left intact
1170
-
1171
- ---
1172
-
1173
- ## Includes (composition)
1174
-
1175
- Compose prompts from shared fragments:
1176
-
1177
- \`\`\`yaml
1178
- includes:
1179
- - ./shared/tone.md
1180
- - ./shared/safety.md
1181
- \`\`\`
1182
-
1183
- Included files are parsed and their \`system_instructions\` are **prepended**
1184
- before the including file's own system instructions. Includes resolve
1185
- recursively. Circular includes are detected and rejected.
1186
-
1187
- > **Note:** Included files do not inherit folder defaults. Only the top-level
1188
- > prompt that is loaded via \`loadPromptFile\` receives defaults.
1189
-
1190
- ---
1191
-
1192
- ## Folder defaults (\`defaults.md\`)
1193
-
1194
- Define shared defaults for a prompt tree by adding a \`defaults.md\` file in any
1195
- folder:
1196
-
1197
- \`\`\`text
1198
- prompts/
1199
- \u251C\u2500\u2500 defaults.md # global provider, model, metadata + system instructions
1200
- \u2514\u2500\u2500 support/
1201
- \u251C\u2500\u2500 defaults.md # overrides for support/*
1202
- \u2514\u2500\u2500 reply.md # inherits from support/defaults.md
1203
- \`\`\`
1204
-
1205
- Supported default fields:
1206
- - \`provider\` (front matter) \u2014 default provider for the folder
1207
- - \`model\` (front matter) \u2014 default model for the folder
1208
- - \`metadata\` (front matter) \u2014 merged with prompt-local metadata
1209
- - \`# System instructions\` (body section) \u2014 used when the prompt has none
1210
-
1211
- This lets you configure app-wide settings like \`provider\` and \`model\`
1212
- in a single root \`defaults.md\`, so individual prompts only declare what\u2019s unique to them.
1213
-
1214
- Rules:
1215
- - Nearest subfolder \`defaults.md\` overrides parent defaults
1216
- - Prompt-local values always take precedence over defaults
1217
- - \`defaults.md\` files are skipped during compilation and validation
1218
- - \`loadPromptFile\` defaults the search boundary to the file's own directory;
1219
- pass \`defaultsRoot\` to enable ancestor traversal
1220
-
1221
- ---
1222
-
1223
- ## Environment & tier overrides
1224
-
1225
- Override model settings per environment or tier:
1226
-
1227
- \`\`\`yaml
1228
- environments:
1229
- development:
1230
- model: gpt-4.1-mini
1231
- reasoning:
1232
- effort: low
1233
- sampling:
1234
- temperature: 0.9
1235
- production:
1236
- model: gpt-5.4
1237
- reasoning:
1238
- effort: high
1239
- sampling:
1240
- temperature: 0.3
1241
-
1242
- tiers:
1243
- free:
1244
- model: gpt-4.1-mini
1245
- sampling:
1246
- max_output_tokens: 500
1247
- premium:
1248
- model: gpt-5.4
1249
- \`\`\`
1250
-
1251
- Overridable fields: \`model\`, \`fallback_models\`, \`reasoning\`, \`sampling\`,
1252
- \`response\`, \`tools\`.
1253
-
1254
- Override application order: **base \u2192 environment \u2192 tier \u2192 runtime**.
1255
-
1256
- ---
1257
-
1258
- ## Test sidecars
1259
-
1260
- Create a \`.test.yaml\` file alongside a prompt to define test cases:
1261
-
1262
- \`\`\`yaml
1263
- # greeting.test.yaml
1264
- cases:
1265
- - name: basic
1266
- variables:
1267
- name: "World"
1268
- - name: formal
1269
- variables:
1270
- name: "Dr. Smith"
1271
- \`\`\`
1272
-
1273
- ---
1274
-
1275
- ## Using the library (TypeScript / JavaScript)
1276
-
1277
- ### Quick start
1278
-
1279
- \`\`\`typescript
1280
- import { createPromptOpsKit } from 'promptopskit';
1281
-
1282
- const kit = createPromptOpsKit({ sourceDir: './prompts' });
1283
-
1284
- // Load \u2192 resolve includes \u2192 apply overrides \u2192 render
1285
- const request = await kit.renderPrompt('greeting', {
1286
- variables: { name: 'Alice' },
1287
- environment: 'production',
1288
- });
1289
-
1290
- // request.body is ready for the provider's API
1291
- const response = await fetch('https://api.openai.com/v1/chat/completions', {
1292
- method: 'POST',
1293
- headers: {
1294
- 'Content-Type': 'application/json',
1295
- Authorization: \`Bearer \${apiKey}\`,
1296
- },
1297
- body: JSON.stringify(request.body),
1298
- });
1299
- \`\`\`
1300
-
1301
- ### Step-by-step API
1302
-
1303
- \`\`\`typescript
1304
- import {
1305
- parsePrompt,
1306
- resolveIncludes,
1307
- applyOverrides,
1308
- getAdapter,
1309
- } from 'promptopskit';
1310
- import { readFileSync } from 'fs';
1311
-
1312
- // 1. Parse a prompt file
1313
- const source = readFileSync('./prompts/greeting.md', 'utf-8');
1314
- const asset = parsePrompt(source, 'greeting.md');
1315
-
1316
- // 2. Resolve includes
1317
- const resolved = await resolveIncludes(asset, './prompts');
1318
-
1319
- // 3. Apply overrides
1320
- const configured = applyOverrides(resolved, {
1321
- environment: 'production',
1322
- tier: 'premium',
1323
- });
1324
-
1325
- // 4. Get provider adapter and render
1326
- const adapter = getAdapter(configured.provider ?? 'openai');
1327
- const request = adapter.render(configured, {
1328
- variables: { name: 'Alice' },
1329
- history: [
1330
- { role: 'user', content: 'Previous message' },
1331
- { role: 'assistant', content: 'Previous response' },
1332
- ],
1333
- });
1334
- \`\`\`
1335
-
1336
- ### Available provider adapters
1337
-
1338
- | Provider | Import path | Provider request format |
1339
- |----------|------------|----------------------|
1340
- | OpenAI | \`promptopskit\` or \`promptopskit/openai\` | Chat Completions API |
1341
- | Anthropic | \`promptopskit/anthropic\` | Messages API |
1342
- | Gemini | \`promptopskit/gemini\` | GenerateContent API |
1343
- | OpenRouter | \`promptopskit/openrouter\` | OpenAI-compatible + extras |
1344
-
1345
- ### Validation
1346
-
1347
- \`\`\`typescript
1348
- import { validateAsset, parsePrompt } from 'promptopskit';
1349
-
1350
- const asset = parsePrompt(source);
1351
- const result = validateAsset(asset);
1352
-
1353
- if (!result.valid) {
1354
- console.error(result.errors); // Error codes: POK001-POK021
1355
- }
1356
- \`\`\`
1357
-
1358
- ### Testing helpers
1359
-
1360
- \`\`\`typescript
1361
- import { createMockAsset, parseTestPrompt } from 'promptopskit/testing';
1362
-
1363
- // Create a mock asset for unit tests
1364
- const mock = createMockAsset({ model: 'gpt-4.1-mini' });
1365
-
1366
- // Parse an inline prompt string for tests
1367
- const asset = parseTestPrompt(\`
1368
- ---
1369
- id: test
1370
- schema_version: 1
1371
- provider: openai
1372
- model: gpt-5.4
1373
- ---
1374
-
1375
- # Prompt template
1376
-
1377
- Hello {{ name }}
1378
- \`);
1379
- \`\`\`
1380
-
1381
- ---
1382
-
1383
- ## CLI commands
1384
-
1385
- | Command | Description |
1386
- |---------|-------------|
1387
- | \`promptopskit init [dir]\` | Scaffold a prompts directory with starter files (including \`defaults.md\`) |
1388
- | \`promptopskit validate <dir>\` | Validate all prompt files in a directory |
1389
- | \`promptopskit compile <src> <out>\` | Compile .md prompts to JSON artifacts |
1390
- | \`promptopskit render <file> [--set key=value]\` | Render a prompt preview |
1391
- | \`promptopskit inspect <file>\` | Print the normalized prompt asset |
1392
-
1393
- ---
1394
-
1395
- ## Conventions to follow
1396
-
1397
- 1. **One prompt per file** \u2014 each \`.md\` file is a single prompt asset
1398
- 2. **Always set \`id\` and \`schema_version: 1\`** in front matter (or inherit \`schema_version\` from \`defaults.md\`)
1399
- 3. **Declare all variables** in \`context.inputs\` that appear in templates
1400
- 4. **Use includes** for shared system instructions (tone, safety, formatting)
1401
- 5. **Keep prompt templates focused** \u2014 compose behavior via includes, not duplication
1402
- 6. **Use environment overrides** for dev/staging/prod model differences
1403
- 7. **Add test sidecars** (\`.test.yaml\`) for critical prompts
1404
- 8. **Run \`promptopskit validate\`** before committing changes
1405
- 9. **Use \`defaults.md\`** to share provider, model, metadata, and system instructions across a folder
1406
- 10. **Variable names** should be \`snake_case\`
1407
- 11. **Prompt file names** should be \`kebab-case.md\`
1408
- `.trimEnd();
1409
1109
 
1410
1110
  // src/cli/index.ts
1411
1111
  var HELP7 = `
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/cli/commands/validate.ts","../../src/parser/parser.ts","../../src/schema/schema.ts","../../src/parser/sections.ts","../../src/parser/loader.ts","../../src/renderer/interpolate.ts","../../src/composition/resolve-includes.ts","../../src/validation/levenshtein.ts","../../src/validation/validate.ts","../../src/cli/commands/compile.ts","../../src/cli/commands/render.ts","../../src/overrides/apply-overrides.ts","../../src/cli/commands/inspect.ts","../../src/cli/commands/init.ts","../../src/cli/commands/skill.ts","../../src/cli/index.ts"],"sourcesContent":["import { readdir } from 'node:fs/promises';\nimport { join, extname } from 'node:path';\nimport { loadPromptFile } from '../../parser/index.js';\nimport { validateAssetWithIncludes } from '../../validation/index.js';\n\nconst HELP = `\npromptopskit validate <dir>\n\nValidate all prompt .md files in a directory.\n\nOptions:\n --strict Treat warnings as errors\n --help, -h Show this help\n`.trim();\n\nexport async function validate(args: string[]): Promise<void> {\n if (args.includes('--help') || args.includes('-h')) {\n console.log(HELP);\n return;\n }\n\n const dir = args.find((a) => !a.startsWith('--'));\n if (!dir) {\n console.error('Error: Please provide a directory to validate.');\n process.exit(1);\n }\n\n const strict = args.includes('--strict');\n const files = await collectPromptFiles(dir);\n\n if (files.length === 0) {\n console.log(`No .md prompt files found in ${dir}`);\n return;\n }\n\n let errorCount = 0;\n let warnCount = 0;\n\n for (const file of files) {\n try {\n const { asset, raw } = await loadPromptFile(file, { defaultsRoot: dir });\n const result = await validateAssetWithIncludes(asset, file, Object.keys(raw.frontMatter));\n\n if (result.errors.length > 0) {\n errorCount += result.errors.length;\n console.error(` ✗ ${file}`);\n for (const err of result.errors) {\n console.error(` ${err.code}: ${err.message}`);\n }\n } else {\n console.log(` ✓ ${file}`);\n }\n\n if (result.warnings.length > 0) {\n warnCount += result.warnings.length;\n for (const warn of result.warnings) {\n const suggestion = warn.suggestion ? ` (${warn.suggestion})` : '';\n console.warn(` ⚠ ${warn.code}: ${warn.message}${suggestion}`);\n }\n }\n } catch (err) {\n errorCount++;\n const message = err instanceof Error ? err.message : String(err);\n console.error(` ✗ ${file}`);\n console.error(` ${message}`);\n }\n }\n\n console.log();\n console.log(`Validated ${files.length} file(s): ${errorCount} error(s), ${warnCount} warning(s)`);\n\n if (errorCount > 0 || (strict && warnCount > 0)) {\n process.exit(1);\n }\n}\n\nasync function collectPromptFiles(dir: string): Promise<string[]> {\n const results: string[] = [];\n const entries = await readdir(dir, { withFileTypes: true, recursive: true });\n for (const entry of entries) {\n if (\n entry.isFile()\n && extname(entry.name) === '.md'\n && !entry.name.endsWith('.test.md')\n && entry.name !== 'defaults.md'\n ) {\n results.push(join(entry.parentPath ?? dir, entry.name));\n }\n }\n return results.sort();\n}\n","import matter from 'gray-matter';\nimport { PromptAssetSchema } from '../schema/index.js';\nimport type { PromptAsset } from '../schema/index.js';\nimport { extractSections } from './sections.js';\n\nexport interface ParseResult {\n asset: PromptAsset;\n raw: {\n frontMatter: Record<string, unknown>;\n body: string;\n };\n}\n\n/**\n * Parse a prompt markdown string (YAML front matter + markdown body)\n * into a validated PromptAsset.\n */\nexport function parsePrompt(content: string, filePath?: string): ParseResult {\n const { data: frontMatter, content: body } = matter(content);\n\n const sections = extractSections(body);\n\n const raw = {\n ...frontMatter,\n sections,\n source: filePath ? { file_path: filePath } : undefined,\n };\n\n const asset = PromptAssetSchema.parse(raw);\n\n return {\n asset,\n raw: {\n frontMatter: frontMatter as Record<string, unknown>,\n body,\n },\n };\n}\n","import { z } from 'zod';\n\n// --- Tool definitions ---\n\nexport const InlineToolDefSchema = z.object({\n name: z.string(),\n description: z.string().optional(),\n input_schema: z.record(z.unknown()).optional(),\n});\n\nexport type InlineToolDef = z.infer<typeof InlineToolDefSchema>;\n\nexport const ToolRefSchema = z.union([z.string(), InlineToolDefSchema]);\n\n// --- MCP ---\n\nexport const MCPServerRefSchema = z.union([\n z.string(),\n z.object({\n name: z.string(),\n config: z.record(z.unknown()).optional(),\n }),\n]);\n\nexport type MCPServerRef = z.infer<typeof MCPServerRefSchema>;\n\n// --- Reasoning ---\n\nexport const ReasoningSchema = z.object({\n effort: z.enum(['low', 'medium', 'high']).optional(),\n budget_tokens: z.number().int().positive().optional(),\n});\n\n// --- Sampling ---\n\nexport const SamplingSchema = z.object({\n temperature: z.number().min(0).max(2).optional(),\n top_p: z.number().min(0).max(1).optional(),\n frequency_penalty: z.number().optional(),\n presence_penalty: z.number().optional(),\n stop: z.array(z.string()).optional(),\n max_output_tokens: z.number().int().positive().optional(),\n});\n\n// --- Response ---\n\nexport const ResponseSchema = z.object({\n format: z.enum(['text', 'json', 'markdown']).optional(),\n stream: z.boolean().optional(),\n});\n\n// --- Context ---\n\nexport const HistorySchema = z.object({\n max_items: z.number().int().positive().optional(),\n});\n\nexport const ContextSchema = z.object({\n inputs: z.array(z.string()).optional(),\n history: HistorySchema.optional(),\n});\n\n// --- Metadata ---\n\nexport const MetadataSchema = z.object({\n owner: z.string().optional(),\n tags: z.array(z.string()).optional(),\n review_required: z.boolean().optional(),\n stable: z.boolean().optional(),\n});\n\n// --- MCP block ---\n\nexport const MCPSchema = z.object({\n servers: z.array(MCPServerRefSchema).optional(),\n});\n\n// --- Overrides (subset allowed in environments/tiers) ---\n\nexport const PromptAssetOverridesSchema = z.object({\n model: z.string().optional(),\n fallback_models: z.array(z.string()).optional(),\n reasoning: ReasoningSchema.optional(),\n sampling: SamplingSchema.optional(),\n response: ResponseSchema.optional(),\n tools: z.array(ToolRefSchema).optional(),\n});\n\nexport type PromptAssetOverrides = z.infer<typeof PromptAssetOverridesSchema>;\n\n// --- Source tracking ---\n\nexport const SourceSchema = z.object({\n file_path: z.string().optional(),\n checksum: z.string().optional(),\n});\n\n// --- Sections (populated by parser) ---\n\nexport const SectionsSchema = z.object({\n system_instructions: z.string().optional(),\n prompt_template: z.string().optional(),\n notes: z.string().optional(),\n});\n\n// --- Defaults files (folder-level inheritance) ---\n\nexport const PromptDefaultsSchema = z.object({\n provider: z.enum(['openai', 'anthropic', 'google', 'gemini', 'openrouter', 'any']).optional(),\n model: z.string().optional(),\n metadata: MetadataSchema.optional(),\n sections: z.object({\n system_instructions: z.string().optional(),\n }).optional(),\n});\n\nexport type PromptDefaults = z.infer<typeof PromptDefaultsSchema>;\n\n// --- Top-level PromptAsset ---\n\nexport const PromptAssetSchema = z.object({\n id: z.string(),\n schema_version: z.number().int().positive().default(1),\n description: z.string().optional(),\n\n provider: z.enum(['openai', 'anthropic', 'google', 'gemini', 'openrouter', 'any']).optional(),\n model: z.string().optional(),\n fallback_models: z.array(z.string()).optional(),\n\n reasoning: ReasoningSchema.optional(),\n sampling: SamplingSchema.optional(),\n response: ResponseSchema.optional(),\n\n tools: z.array(ToolRefSchema).optional(),\n mcp: MCPSchema.optional(),\n\n context: ContextSchema.optional(),\n\n includes: z.array(z.string()).optional(),\n\n environments: z.record(PromptAssetOverridesSchema).optional(),\n tiers: z.record(PromptAssetOverridesSchema).optional(),\n\n metadata: MetadataSchema.optional(),\n\n // Populated by parser, not authored in YAML\n sections: SectionsSchema.optional(),\n source: SourceSchema.optional(),\n});\n\nexport type PromptAsset = z.infer<typeof PromptAssetSchema>;\n\n// --- Resolved asset (after includes, overrides applied) ---\n\nexport interface ResolvedPromptAsset extends PromptAsset {\n sections: {\n system_instructions?: string;\n prompt_template?: string;\n notes?: string;\n };\n source: {\n file_path?: string;\n checksum?: string;\n };\n}\n","export interface Sections {\n system_instructions?: string;\n prompt_template?: string;\n notes?: string;\n}\n\nconst SECTION_MAP: Record<string, keyof Sections> = {\n 'system instructions': 'system_instructions',\n 'prompt template': 'prompt_template',\n 'notes': 'notes',\n};\n\n/**\n * Extract named sections from the markdown body using H1 headings.\n * Case-insensitive. H2+ within a section is treated as content.\n * If no H1 headings are found, the entire body is treated as prompt_template.\n */\nexport function extractSections(body: string): Sections {\n const lines = body.split(/\\r?\\n/);\n const sections: Sections = {};\n\n let currentKey: keyof Sections | null = null;\n let currentLines: string[] = [];\n let foundAnyH1 = false;\n\n for (const line of lines) {\n const h1Match = line.match(/^#\\s+(.+)$/);\n if (h1Match) {\n // Flush previous section\n if (currentKey) {\n sections[currentKey] = currentLines.join('\\n').trim();\n }\n\n foundAnyH1 = true;\n const heading = h1Match[1].trim().toLowerCase();\n currentKey = SECTION_MAP[heading] ?? null;\n currentLines = [];\n } else {\n currentLines.push(line);\n }\n }\n\n // Flush last section\n if (currentKey) {\n sections[currentKey] = currentLines.join('\\n').trim();\n }\n\n // If no H1 headings found, treat entire body as prompt_template\n if (!foundAnyH1) {\n const trimmed = body.trim();\n if (trimmed) {\n sections.prompt_template = trimmed;\n }\n }\n\n return sections;\n}\n","import { readFile } from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\nimport matter from 'gray-matter';\nimport { parsePrompt } from './parser.js';\nimport type { ParseResult } from './parser.js';\nimport { extractSections } from './sections.js';\nimport { PromptDefaultsSchema } from '../schema/index.js';\nimport type { PromptDefaults } from '../schema/index.js';\n\nconst DEFAULTS_FILE_NAME = 'defaults.md';\n\nexport interface LoadPromptOptions {\n /**\n * Optional boundary directory for defaults discovery.\n * If provided, defaults are loaded from this directory down to the prompt directory.\n */\n defaultsRoot?: string;\n}\n\n/**\n * Load and parse a prompt file from disk.\n */\nexport async function loadPromptFile(filePath: string, options: LoadPromptOptions = {}): Promise<ParseResult> {\n const content = await readFile(filePath, 'utf-8');\n const parsed = parsePrompt(content, filePath);\n // Default the boundary to the file's own directory so traversal never\n // walks above the prompt tree when no explicit root is provided.\n const root = options.defaultsRoot ?? dirname(filePath);\n const defaults = await loadDefaultsForPath(filePath, root);\n const asset = applyDefaults(parsed.asset, defaults);\n\n return {\n ...parsed,\n asset,\n };\n}\n\nasync function loadDefaultsForPath(filePath: string, defaultsRoot?: string): Promise<PromptDefaults> {\n const directories = getDirectoriesToCheck(filePath, defaultsRoot);\n let merged: PromptDefaults = {};\n\n for (const dir of directories) {\n const defaultsPath = join(dir, DEFAULTS_FILE_NAME);\n try {\n const defaultsContent = await readFile(defaultsPath, 'utf-8');\n const defaults = parseDefaults(defaultsContent);\n merged = mergeDefaults(merged, defaults);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n }\n\n return merged;\n}\n\nfunction getDirectoriesToCheck(filePath: string, defaultsRoot?: string): string[] {\n const dirs: string[] = [];\n let current = resolve(dirname(filePath));\n const boundary = defaultsRoot ? resolve(defaultsRoot) : undefined;\n\n while (true) {\n dirs.unshift(current);\n if ((boundary && current === boundary) || current === dirname(current)) {\n break;\n }\n current = dirname(current);\n }\n\n return dirs;\n}\n\nfunction parseDefaults(content: string): PromptDefaults {\n const { data: frontMatter, content: body } = matter(content);\n const sections = extractSections(body);\n\n return PromptDefaultsSchema.parse({\n ...frontMatter,\n sections: {\n system_instructions: sections.system_instructions,\n },\n });\n}\n\nfunction mergeDefaults(base: PromptDefaults, local: PromptDefaults): PromptDefaults {\n return {\n provider: local.provider ?? base.provider,\n model: local.model ?? base.model,\n metadata: {\n ...(base.metadata ?? {}),\n ...(local.metadata ?? {}),\n },\n sections: {\n ...(base.sections ?? {}),\n ...(local.sections ?? {}),\n },\n };\n}\n\nfunction applyDefaults(asset: ParseResult['asset'], defaults: PromptDefaults): ParseResult['asset'] {\n const hasDefaultMetadata = defaults.metadata && Object.keys(defaults.metadata).length > 0;\n const hasDefaultSystem = !!defaults.sections?.system_instructions;\n const hasDefaultScalars = defaults.provider !== undefined\n || defaults.model !== undefined;\n\n // Short-circuit: nothing to merge\n if (!hasDefaultMetadata && !hasDefaultSystem && !hasDefaultScalars) {\n return asset;\n }\n\n const mergedMetadata = {\n ...(defaults.metadata ?? {}),\n ...(asset.metadata ?? {}),\n };\n const metadata = Object.keys(mergedMetadata).length > 0 ? mergedMetadata : undefined;\n\n const systemInstructions = asset.sections?.system_instructions ?? defaults.sections?.system_instructions;\n\n const sections = asset.sections\n ? { ...asset.sections, system_instructions: systemInstructions }\n : systemInstructions\n ? { system_instructions: systemInstructions }\n : undefined;\n\n return {\n ...asset,\n provider: asset.provider ?? defaults.provider,\n model: asset.model ?? defaults.model,\n metadata,\n sections,\n };\n}\n","export interface InterpolateOptions {\n strict?: boolean;\n}\n\nconst VARIABLE_RE = /\\{\\{\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\}\\}/g;\nconst ESCAPED_OPEN = /\\\\\\{\\\\\\{/g;\nconst ESCAPE_PLACEHOLDER = '\\x00ESCAPED_OPEN\\x00';\n\n/**\n * Interpolate variables into a template string.\n *\n * Syntax: {{ variable_name }}\n * Escape: \\{\\{ produces literal {{\n *\n * In strict mode, throws on missing variables.\n * In permissive mode, leaves {{ placeholder }} intact.\n */\nexport function interpolate(\n template: string,\n variables: Record<string, string>,\n options: InterpolateOptions = {},\n): string {\n const { strict = false } = options;\n\n // Replace escaped sequences with placeholder\n let result = template.replace(ESCAPED_OPEN, ESCAPE_PLACEHOLDER);\n\n result = result.replace(VARIABLE_RE, (match, name: string) => {\n if (name in variables) {\n return variables[name];\n }\n if (strict) {\n throw new Error(`Missing required variable: \"${name}\"`);\n }\n return match; // leave placeholder intact in permissive mode\n });\n\n // Restore escaped sequences\n result = result.replaceAll(ESCAPE_PLACEHOLDER, '{{');\n\n return result;\n}\n\n/**\n * Extract all variable names referenced in a template.\n */\nexport function extractVariables(template: string): string[] {\n const vars = new Set<string>();\n let match: RegExpExecArray | null;\n const re = new RegExp(VARIABLE_RE.source, 'g');\n while ((match = re.exec(template)) !== null) {\n vars.add(match[1]);\n }\n return [...vars];\n}\n","import { readFile } from 'node:fs/promises';\nimport { resolve, dirname } from 'node:path';\nimport { parsePrompt } from '../parser/index.js';\nimport type { PromptAsset } from '../schema/index.js';\n\n/**\n * Resolve includes for a prompt asset, inlining content from referenced files.\n * Detects and rejects circular includes.\n */\nexport async function resolveIncludes(\n asset: PromptAsset,\n basePath: string,\n visited: Set<string> = new Set(),\n): Promise<PromptAsset> {\n if (!asset.includes || asset.includes.length === 0) {\n return asset;\n }\n\n const baseDir = dirname(basePath);\n const resolvedPath = resolve(basePath);\n\n if (visited.has(resolvedPath)) {\n throw new Error(`Circular include detected: ${resolvedPath}`);\n }\n visited.add(resolvedPath);\n\n let mergedSystemInstructions = '';\n\n for (const includePath of asset.includes) {\n const fullPath = resolve(baseDir, includePath);\n\n if (visited.has(fullPath)) {\n throw new Error(`Circular include detected: ${fullPath} (included from ${basePath})`);\n }\n\n const content = await readFile(fullPath, 'utf-8');\n const { asset: includedAsset } = parsePrompt(content, fullPath);\n\n // Recursively resolve nested includes\n const resolved = await resolveIncludes(includedAsset, fullPath, new Set(visited));\n\n // Append included system instructions before local ones\n if (resolved.sections?.system_instructions) {\n mergedSystemInstructions += resolved.sections.system_instructions + '\\n\\n';\n }\n }\n\n // Prepend included system instructions before the local ones\n const localSystem = asset.sections?.system_instructions ?? '';\n const combinedSystem = (mergedSystemInstructions + localSystem).trim() || undefined;\n\n return {\n ...asset,\n sections: {\n ...asset.sections,\n system_instructions: combinedSystem,\n },\n // Drop includes from the resolved asset — they've been inlined\n includes: undefined,\n };\n}\n","/**\n * Compute the Levenshtein distance between two strings.\n * Used for \"did you mean?\" suggestions on unknown fields.\n */\nexport function levenshtein(a: string, b: string): number {\n const m = a.length;\n const n = b.length;\n\n if (m === 0) return n;\n if (n === 0) return m;\n\n const dp: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0) as number[]);\n\n for (let i = 0; i <= m; i++) dp[i][0] = i;\n for (let j = 0; j <= n; j++) dp[0][j] = j;\n\n for (let i = 1; i <= m; i++) {\n for (let j = 1; j <= n; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n dp[i][j] = Math.min(\n dp[i - 1][j] + 1,\n dp[i][j - 1] + 1,\n dp[i - 1][j - 1] + cost,\n );\n }\n }\n\n return dp[m][n];\n}\n","import { PromptAssetSchema } from '../schema/index.js';\nimport type { PromptAsset } from '../schema/index.js';\nimport { extractVariables } from '../renderer/index.js';\nimport { resolveIncludes } from '../composition/index.js';\nimport { levenshtein } from './levenshtein.js';\n\nexport interface ValidationError {\n code: string;\n message: string;\n filePath?: string;\n suggestion?: string;\n}\n\nexport interface PromptValidationResult {\n valid: boolean;\n errors: ValidationError[];\n warnings: ValidationError[];\n}\n\nconst KNOWN_FRONT_MATTER_KEYS = new Set([\n 'id', 'schema_version', 'description', 'provider', 'model', 'fallback_models',\n 'reasoning', 'sampling', 'response', 'tools', 'mcp', 'context', 'includes',\n 'environments', 'tiers', 'metadata',\n]);\n\n/**\n * Validate a parsed prompt asset, returning all errors and warnings.\n */\nexport function validateAsset(\n asset: PromptAsset,\n frontMatterKeys?: string[],\n filePath?: string,\n): PromptValidationResult {\n const errors: ValidationError[] = [];\n const warnings: ValidationError[] = [];\n\n // Schema validation\n const result = PromptAssetSchema.safeParse(asset);\n if (!result.success) {\n for (const issue of result.error.issues) {\n errors.push({\n code: 'POK001',\n message: `Schema error at ${issue.path.join('.')}: ${issue.message}`,\n filePath,\n });\n }\n }\n\n // Missing id\n if (!asset.id) {\n errors.push({\n code: 'POK002',\n message: 'Missing required field: \"id\"',\n filePath,\n });\n }\n\n // Missing body sections\n if (!asset.sections?.system_instructions && !asset.sections?.prompt_template) {\n errors.push({\n code: 'POK003',\n message: 'Prompt must have at least one body section (System instructions or Prompt template)',\n filePath,\n });\n }\n\n // Unknown front matter keys with \"did you mean?\"\n if (frontMatterKeys) {\n for (const key of frontMatterKeys) {\n if (!KNOWN_FRONT_MATTER_KEYS.has(key)) {\n const suggestion = findClosestMatch(key, KNOWN_FRONT_MATTER_KEYS);\n warnings.push({\n code: 'POK010',\n message: `Unknown front matter field: \"${key}\"`,\n filePath,\n suggestion: suggestion ? `Did you mean \"${suggestion}\"?` : undefined,\n });\n }\n }\n }\n\n // Variable validation: used but not declared\n const declaredInputs = new Set(asset.context?.inputs ?? []);\n const usedVars = new Set<string>();\n\n if (asset.sections?.system_instructions) {\n for (const v of extractVariables(asset.sections.system_instructions)) {\n usedVars.add(v);\n }\n }\n if (asset.sections?.prompt_template) {\n for (const v of extractVariables(asset.sections.prompt_template)) {\n usedVars.add(v);\n }\n }\n\n for (const v of usedVars) {\n if (declaredInputs.size > 0 && !declaredInputs.has(v)) {\n warnings.push({\n code: 'POK011',\n message: `Variable \"{{ ${v} }}\" is used but not declared in context.inputs`,\n filePath,\n });\n }\n }\n\n // Declared but unused\n for (const v of declaredInputs) {\n if (!usedVars.has(v)) {\n warnings.push({\n code: 'POK012',\n message: `Variable \"${v}\" is declared in context.inputs but never used`,\n filePath,\n });\n }\n }\n\n return {\n valid: errors.length === 0,\n errors,\n warnings,\n };\n}\n\n/**\n * Validate a prompt asset including its include graph.\n * Catches missing include files, circular includes, and parse errors in included files.\n */\nexport async function validateAssetWithIncludes(\n asset: PromptAsset,\n filePath: string,\n frontMatterKeys?: string[],\n): Promise<PromptValidationResult> {\n // Run standard validation first\n const result = validateAsset(asset, frontMatterKeys, filePath);\n\n // Validate includes\n if (asset.includes && asset.includes.length > 0) {\n try {\n await resolveIncludes(asset, filePath);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n const isCircular = message.includes('Circular include');\n result.errors.push({\n code: isCircular ? 'POK021' : 'POK020',\n message: isCircular\n ? `Circular include detected: ${message}`\n : `Include resolution failed: ${message}`,\n filePath,\n });\n result.valid = false;\n }\n }\n\n return result;\n}\n\nfunction findClosestMatch(input: string, candidates: Set<string>): string | undefined {\n let best: string | undefined;\n let bestDist = Infinity;\n\n for (const candidate of candidates) {\n const dist = levenshtein(input.toLowerCase(), candidate.toLowerCase());\n if (dist < bestDist && dist <= 3) {\n bestDist = dist;\n best = candidate;\n }\n }\n\n return best;\n}\n","import { readdir, writeFile, mkdir, rm } from 'node:fs/promises';\nimport { join, extname, relative, dirname } from 'node:path';\nimport { loadPromptFile } from '../../parser/index.js';\nimport { resolveIncludes } from '../../composition/index.js';\n\nconst HELP = `\npromptopskit compile <sourceDir> <outputDir> [options]\n\nCompile .md prompt files to JSON artifacts.\n\nOptions:\n --no-clean Don't clear the output directory before compiling\n --dry-run Show what would be compiled without writing files\n --format Output format: json (default) or esm\n --help, -h Show this help\n`.trim();\n\nexport async function compile(args: string[]): Promise<void> {\n if (args.includes('--help') || args.includes('-h')) {\n console.log(HELP);\n return;\n }\n\n const positional = args.filter((a) => !a.startsWith('--'));\n const sourceDir = positional[0];\n const outputDir = positional[1];\n\n if (!sourceDir || !outputDir) {\n console.error('Error: Please provide source and output directories.');\n console.error('Usage: promptopskit compile <sourceDir> <outputDir>');\n process.exit(1);\n }\n\n const dryRun = args.includes('--dry-run');\n const noClean = args.includes('--no-clean');\n const format = getFlag(args, '--format') ?? 'json';\n\n if (format !== 'json' && format !== 'esm') {\n console.error(`Error: Unknown format \"${format}\". Use \"json\" or \"esm\".`);\n process.exit(1);\n }\n\n // Collect prompt files\n const files = await collectPromptFiles(sourceDir);\n\n if (files.length === 0) {\n console.log(`No .md prompt files found in ${sourceDir}`);\n return;\n }\n\n // Clean output dir\n if (!noClean && !dryRun) {\n await rm(outputDir, { recursive: true, force: true });\n }\n\n let compiled = 0;\n let errors = 0;\n\n for (const file of files) {\n const rel = relative(sourceDir, file).replace(/\\.md$/, '');\n const outExt = format === 'esm' ? '.mjs' : '.json';\n const outPath = join(outputDir, rel + outExt);\n\n try {\n const { asset: parsed } = await loadPromptFile(file, { defaultsRoot: sourceDir });\n\n // Resolve includes so compiled artifacts are self-sufficient\n const asset = (parsed.includes && parsed.includes.length > 0)\n ? await resolveIncludes(parsed, file)\n : parsed;\n\n if (dryRun) {\n console.log(` Would create: ${outPath}`);\n } else {\n await mkdir(dirname(outPath), { recursive: true });\n\n if (format === 'esm') {\n const esmContent = `export default ${JSON.stringify(asset, null, 2)};\\n`;\n await writeFile(outPath, esmContent, 'utf-8');\n } else {\n await writeFile(outPath, JSON.stringify(asset, null, 2) + '\\n', 'utf-8');\n }\n console.log(` ✓ ${outPath}`);\n }\n compiled++;\n } catch (err) {\n errors++;\n const message = err instanceof Error ? err.message : String(err);\n console.error(` ✗ ${file}`);\n console.error(` ${message}`);\n }\n }\n\n console.log();\n if (dryRun) {\n console.log(`Dry run: ${compiled} file(s) would be compiled, ${errors} error(s)`);\n } else {\n console.log(`Compiled ${compiled} file(s), ${errors} error(s)`);\n }\n\n if (errors > 0) {\n process.exit(1);\n }\n}\n\nfunction getFlag(args: string[], flag: string): string | undefined {\n const idx = args.indexOf(flag);\n if (idx >= 0 && idx + 1 < args.length) {\n return args[idx + 1];\n }\n return undefined;\n}\n\nasync function collectPromptFiles(dir: string): Promise<string[]> {\n const results: string[] = [];\n const entries = await readdir(dir, { withFileTypes: true, recursive: true });\n for (const entry of entries) {\n if (\n entry.isFile()\n && extname(entry.name) === '.md'\n && !entry.name.endsWith('.test.md')\n && entry.name !== 'defaults.md'\n ) {\n results.push(join(entry.parentPath ?? dir, entry.name));\n }\n }\n return results.sort();\n}\n","import { readFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { loadPromptFile } from '../../parser/index.js';\nimport { resolveIncludes } from '../../composition/index.js';\nimport { applyOverrides } from '../../overrides/index.js';\nimport { interpolate } from '../../renderer/interpolate.js';\n\nconst HELP = `\npromptopskit render <file> [options]\n\nRender a prompt preview with variables.\n\nOptions:\n --env <name> Environment override\n --tier <name> Tier override\n --vars <file> JSON file with variables\n --json Output raw JSON instead of readable format\n --help, -h Show this help\n`.trim();\n\nexport async function render(args: string[]): Promise<void> {\n if (args.includes('--help') || args.includes('-h')) {\n console.log(HELP);\n return;\n }\n\n const file = args.find((a) => !a.startsWith('--'));\n if (!file) {\n console.error('Error: Please provide a prompt file to render.');\n process.exit(1);\n }\n\n const env = getFlag(args, '--env');\n const tier = getFlag(args, '--tier');\n const varsFile = getFlag(args, '--vars');\n const jsonOutput = args.includes('--json');\n\n // Load variables from file or sidecar\n let variables: Record<string, string> = {};\n\n if (varsFile) {\n const varsContent = await readFile(varsFile, 'utf-8');\n variables = JSON.parse(varsContent);\n } else {\n // Try auto-loading sidecar .test.yaml\n const sidecarPath = file.replace(/\\.md$/, '.test.yaml');\n if (existsSync(sidecarPath)) {\n const { default: yaml } = await import('gray-matter');\n const sidecarContent = await readFile(sidecarPath, 'utf-8');\n // Wrap in --- delimiters so gray-matter parses the entire file as front matter\n const parsed = yaml(`---\\n${sidecarContent}---\\n`);\n const data = parsed.data as { cases?: Array<{ variables?: Record<string, string> }> };\n if (data.cases?.[0]?.variables) {\n variables = data.cases[0].variables;\n }\n }\n }\n\n const { asset: parsed } = await loadPromptFile(file);\n\n // Resolve includes (matching the library pipeline)\n const resolved = (parsed.includes && parsed.includes.length > 0)\n ? await resolveIncludes(parsed, file)\n : parsed;\n\n // Apply overrides using the standard applyOverrides function\n const overridden = applyOverrides(resolved, {\n environment: env,\n tier: tier,\n });\n\n // Render sections with variables\n const renderedSystem = overridden.sections?.system_instructions\n ? interpolate(overridden.sections.system_instructions, variables)\n : undefined;\n const renderedPrompt = overridden.sections?.prompt_template\n ? interpolate(overridden.sections.prompt_template, variables)\n : undefined;\n\n if (jsonOutput) {\n console.log(JSON.stringify({\n id: overridden.id,\n provider: overridden.provider,\n model: overridden.model,\n system_instructions: renderedSystem,\n prompt_template: renderedPrompt,\n tools: overridden.tools,\n }, null, 2));\n return;\n }\n\n // Readable output\n const label = [\n overridden.provider,\n overridden.model,\n [env, tier].filter(Boolean).join('/'),\n ].filter(Boolean).join(', ');\n\n console.log(`── ${overridden.id} (${label}) ${'─'.repeat(Math.max(0, 50 - overridden.id.length - label.length))}`);\n\n if (renderedSystem) {\n console.log(`System: ${renderedSystem.split('\\n')[0]}${renderedSystem.includes('\\n') ? '...' : ''}`);\n }\n if (renderedPrompt) {\n console.log(`User: ${renderedPrompt.split('\\n')[0]}${renderedPrompt.includes('\\n') ? '...' : ''}`);\n }\n if (overridden.tools?.length) {\n const toolNames = overridden.tools.map((t) => typeof t === 'string' ? t : t.name);\n console.log(`Tools: ${toolNames.join(', ')}`);\n }\n console.log(`Model: ${overridden.model ?? 'not set'}`);\n console.log('─'.repeat(60));\n}\n\nfunction getFlag(args: string[], flag: string): string | undefined {\n const idx = args.indexOf(flag);\n if (idx >= 0 && idx + 1 < args.length) {\n return args[idx + 1];\n }\n return undefined;\n}\n","import type { PromptAsset, PromptAssetOverrides } from '../schema/index.js';\n\nexport interface OverrideOptions {\n environment?: string;\n tier?: string;\n runtime?: Partial<PromptAssetOverrides>;\n}\n\n/**\n * Apply environment, tier, and runtime overrides to a prompt asset.\n *\n * Precedence: base → environment → tier → runtime\n * Scalars are replaced. Arrays are replaced (not concatenated).\n */\nexport function applyOverrides(\n asset: PromptAsset,\n options: OverrideOptions = {},\n): PromptAsset {\n let result = { ...asset };\n\n // Apply environment override\n if (options.environment && result.environments?.[options.environment]) {\n result = mergeOverride(result, result.environments[options.environment]);\n }\n\n // Apply tier override\n if (options.tier && result.tiers?.[options.tier]) {\n result = mergeOverride(result, result.tiers[options.tier]);\n }\n\n // Apply runtime overrides\n if (options.runtime) {\n result = mergeOverride(result, options.runtime);\n }\n\n return result;\n}\n\nfunction mergeOverride(\n base: PromptAsset,\n override: Partial<PromptAssetOverrides>,\n): PromptAsset {\n const result = { ...base };\n\n if (override.model !== undefined) result.model = override.model;\n if (override.fallback_models !== undefined) result.fallback_models = override.fallback_models;\n if (override.tools !== undefined) result.tools = override.tools;\n\n if (override.reasoning !== undefined) {\n result.reasoning = { ...result.reasoning, ...override.reasoning };\n }\n if (override.sampling !== undefined) {\n result.sampling = { ...result.sampling, ...override.sampling };\n }\n if (override.response !== undefined) {\n result.response = { ...result.response, ...override.response };\n }\n\n return result;\n}\n","import { loadPromptFile } from '../../parser/index.js';\nimport { resolveIncludes } from '../../composition/index.js';\n\nconst HELP = `\npromptopskit inspect <file>\n\nPrint the normalized prompt asset as JSON.\n\nOptions:\n --help, -h Show this help\n`.trim();\n\nexport async function inspect(args: string[]): Promise<void> {\n if (args.includes('--help') || args.includes('-h')) {\n console.log(HELP);\n return;\n }\n\n const file = args.find((a) => !a.startsWith('--'));\n if (!file) {\n console.error('Error: Please provide a prompt file to inspect.');\n process.exit(1);\n }\n\n const { asset: parsed } = await loadPromptFile(file);\n\n // Resolve includes so the output shows the fully resolved asset\n const asset = (parsed.includes && parsed.includes.length > 0)\n ? await resolveIncludes(parsed, file)\n : parsed;\n\n console.log(JSON.stringify(asset, null, 2));\n}\n","import { writeFile, mkdir } from 'node:fs/promises';\nimport { join, dirname } from 'node:path';\nimport { existsSync, readFileSync } from 'node:fs';\n\nconst HELP = `\npromptopskit init [dir]\n\nScaffold a prompts directory with starter files.\n\nOptions:\n --help, -h Show this help\n`.trim();\n\nconst HELLO_PROMPT = `---\nid: hello\ncontext:\n inputs:\n - name\n - app_context\nincludes:\n - ./shared/tone.md\nreasoning:\n effort: high\nenvironments:\n dev:\n model: gpt-5.4-mini\n reasoning:\n effort: low\n sampling:\n temperature: 0.2\n---\n\n# System instructions\n\nYou are a friendly assistant. Be helpful and concise.\nCurrent app context: {{ app_context }}.\n\n# Prompt template\n\nSay hello to {{ name }} and ask how you can help them today.\n`.trimStart();\n\nconst TONE_INCLUDE = `---\nid: shared/tone\nschema_version: 1\n---\n\n# System instructions\n\nAlways be polite, professional, and concise. Avoid jargon unless the user uses it first.\n`.trimStart();\n\nconst DEFAULTS = `---\nprovider: openai\nmodel: gpt-5.4\nmetadata:\n owner: my-team\n review_required: true\n---\n\n# System instructions\n\nYou are a helpful AI assistant. Follow company guidelines at all times.\n`.trimStart();\n\nconst TEST_SIDECAR = `cases:\n - name: basic-greeting\n variables:\n name: \"World\"\n app_context: \"Welcome screen\"\n - name: named-greeting\n variables:\n name: \"Alice\"\n app_context: \"Settings page\"\n`;\n\nconst EXAMPLE_USAGE = `// Example: render the hello prompt and send it to OpenAI\n// Full docs: https://promptopskit.com/docs/index.html#/\n\nimport { createPromptOpsKit } from 'promptopskit';\n\nasync function main() {\n const kit = createPromptOpsKit({ sourceDir: './prompts' });\n\n // Determine environment from ENV var (defaults to 'dev')\n // - dev: uses gpt-5.4-mini, low reasoning effort, temperature 0.2\n // - production: uses base model gpt-5.4 with high reasoning effort\n const environment = process.env.NODE_ENV === 'production' ? 'prod' : 'dev';\n\n const { request } = await kit.renderPrompt({\n path: 'hello',\n provider: 'openai',\n environment,\n variables: {\n name: 'World',\n app_context: 'Welcome screen',\n },\n });\n\n // request.body is the fully transformed OpenAI Chat Completions payload.\n // For the hello.md prompt in the dev environment it looks like:\n //\n // {\n // \"model\": \"gpt-5.4-mini\",\n // \"reasoning_effort\": \"low\",\n // \"temperature\": 0.2,\n // \"messages\": [\n // {\n // \"role\": \"system\",\n // \"content\": \"You are a friendly assistant. Be helpful and concise.\\nCurrent app context: Welcome screen.\\n\\nAlways be polite, professional, and concise. Avoid jargon unless the user uses it first.\"\n // },\n // {\n // \"role\": \"user\",\n // \"content\": \"Say hello to World and ask how you can help them today.\"\n // }\n // ]\n // }\n\n console.log('Model:', request.body.model);\n\n const res = await fetch('https://api.openai.com/v1/chat/completions', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: \\`Bearer \\${process.env.OPENAI_API_KEY}\\`,\n },\n body: JSON.stringify(request.body),\n });\n\n const data = await res.json();\n console.log(data.choices[0].message.content);\n}\n\nmain();\n`;\n\nexport async function init(args: string[]): Promise<void> {\n if (args.includes('--help') || args.includes('-h')) {\n console.log(HELP);\n return;\n }\n\n const dir = args.find((a) => !a.startsWith('--')) ?? './prompts';\n\n const files: Array<{ path: string; content: string }> = [\n { path: join(dir, 'defaults.md'), content: DEFAULTS },\n { path: join(dir, 'hello.md'), content: HELLO_PROMPT },\n { path: join(dir, 'hello.test.yaml'), content: TEST_SIDECAR },\n { path: join(dir, 'shared', 'tone.md'), content: TONE_INCLUDE },\n { path: join(dir, 'example-usage.ts'), content: EXAMPLE_USAGE },\n ];\n\n let created = 0;\n let skipped = 0;\n\n for (const file of files) {\n if (existsSync(file.path)) {\n console.log(` skip ${file.path} (already exists)`);\n skipped++;\n continue;\n }\n await mkdir(dirname(file.path), { recursive: true });\n await writeFile(file.path, file.content, 'utf-8');\n console.log(` ✓ ${file.path}`);\n created++;\n }\n\n console.log();\n console.log(`Created ${created} file(s), skipped ${skipped} existing.`);\n\n // Suggest build script if package.json exists\n if (existsSync('package.json')) {\n try {\n const pkg = JSON.parse(readFileSync('package.json', 'utf-8'));\n if (!pkg.scripts?.['build:prompts']) {\n console.log();\n console.log(`Tip: Add to your package.json scripts:`);\n console.log(` \"build:prompts\": \"promptopskit compile ${dir} ./dist/prompts\"`);\n }\n } catch {\n // Ignore parse errors\n }\n }\n}\n","import { writeFile, readFile, mkdir } from 'node:fs/promises';\nimport { join, dirname } from 'node:path';\nimport { existsSync } from 'node:fs';\n\nconst MARKER_START = '<!-- promptopskit:start -->';\nconst MARKER_END = '<!-- promptopskit:end -->';\n\nconst HELP = `\npromptopskit skill [--target <target>] [--force]\n\nDeploy AI agent instructions so coding assistants know how to\ncreate and manage prompts using promptopskit.\n\nBy default, generates files for all major AI coding assistants:\n\n AGENTS.md Codex, OpenCode, Cursor, Copilot\n CLAUDE.md Claude Code (imports AGENTS.md)\n .github/instructions/promptopskit.instructions.md GitHub Copilot (path-specific)\n .cursor/rules/promptopskit.mdc Cursor (project rule)\n\nIf a file already exists, the promptopskit section is merged (replaced\nin-place or appended). Use --force to overwrite the entire file.\n\nOptions:\n --target, -t Deploy only a specific target (agents, claude, copilot, cursor)\n --force, -f Overwrite entire file instead of merging\n --help, -h Show this help\n`.trim();\n\ninterface TargetConfig {\n path: string;\n wrap: (content: string) => string;\n}\n\nconst TARGETS: Record<string, TargetConfig> = {\n agents: {\n path: 'AGENTS.md',\n wrap: (content) => content,\n },\n claude: {\n path: 'CLAUDE.md',\n wrap: () => '@AGENTS.md\\n',\n },\n copilot: {\n path: '.github/instructions/promptopskit.instructions.md',\n wrap: (content) =>\n `---\\napplyTo: \"**\"\\n---\\n\\n${content}`,\n },\n cursor: {\n path: '.cursor/rules/promptopskit.mdc',\n wrap: (content) =>\n `---\\ndescription: How to create and manage prompts using promptopskit\\nglobs: \"**\"\\nalwaysApply: true\\n---\\n\\n${content}`,\n },\n};\n\nconst ALL_TARGETS = ['agents', 'claude', 'copilot', 'cursor'];\n\nexport async function skill(args: string[]): Promise<void> {\n if (args.includes('--help') || args.includes('-h')) {\n console.log(HELP);\n return;\n }\n\n const force = args.includes('--force') || args.includes('-f');\n\n let targets = ALL_TARGETS;\n const targetIdx = args.findIndex((a) => a === '--target' || a === '-t');\n if (targetIdx !== -1 && args[targetIdx + 1]) {\n const target = args[targetIdx + 1];\n const config = TARGETS[target];\n if (!config) {\n console.error(`Unknown target: ${target}`);\n console.error(`Valid targets: ${Object.keys(TARGETS).join(', ')}`);\n process.exit(1);\n }\n targets = [target];\n }\n\n let written = 0;\n for (const target of targets) {\n const config = TARGETS[target];\n const filePath = config.path;\n const markedContent = config.wrap(wrapMarkers(SKILL_CONTENT));\n\n if (existsSync(filePath) && !force) {\n const existing = await readFile(filePath, 'utf-8');\n const merged = mergeContent(existing, markedContent);\n if (merged === existing) {\n console.log(` skip ${filePath} (already up to date)`);\n continue;\n }\n await writeFile(filePath, merged, 'utf-8');\n console.log(` ✓ ${filePath} (merged)`);\n written++;\n continue;\n }\n\n await mkdir(dirname(filePath), { recursive: true });\n await writeFile(filePath, markedContent, 'utf-8');\n console.log(` ✓ ${filePath}`);\n written++;\n }\n\n if (written > 0) {\n console.log();\n console.log(`AI agents will now understand how to create and manage prompts with promptopskit.`);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Marker helpers\n// ---------------------------------------------------------------------------\n\nfunction wrapMarkers(content: string): string {\n return `${MARKER_START}\\n${content}\\n${MARKER_END}`;\n}\n\nfunction mergeContent(existing: string, markedContent: string): string {\n const startIdx = existing.indexOf(MARKER_START);\n const endIdx = existing.indexOf(MARKER_END);\n\n // Replace existing block in-place\n if (startIdx !== -1 && endIdx !== -1 && endIdx > startIdx) {\n return (\n existing.slice(0, startIdx) +\n markedContent +\n existing.slice(endIdx + MARKER_END.length)\n );\n }\n\n // Append to end\n const separator = existing.endsWith('\\n') ? '\\n' : '\\n\\n';\n return existing + separator + markedContent + '\\n';\n}\n\n// ---------------------------------------------------------------------------\n// Skill content — comprehensive instructions for AI coding agents\n// ---------------------------------------------------------------------------\n\nconst SKILL_CONTENT = `# promptopskit — Prompt Engineering Skill\n\nThis project uses **promptopskit** to manage LLM prompts as code.\nPrompts live in markdown files with YAML front matter, are validated against\na schema, and render into provider-specific request bodies (OpenAI, Anthropic,\nGemini, OpenRouter). Follow these instructions when creating or editing prompts.\n\n---\n\n## Prompt file format\n\nEvery prompt is a \\`.md\\` file with two parts:\n\n1. **YAML front matter** — model settings, provider config, variables, overrides\n2. **Markdown body** — sections separated by H1 headings\n\n### Minimal example\n\n\\`\\`\\`markdown\n---\nid: greeting\nschema_version: 1\nprovider: openai\nmodel: gpt-5.4\ncontext:\n inputs:\n - name\n---\n\n# System instructions\n\nYou are a helpful assistant.\n\n# Prompt template\n\nHello {{ name }}, how can I help you?\n\\`\\`\\`\n\n---\n\n## Front matter reference\n\n| Field | Type | Required | Description |\n|-------|------|----------|-------------|\n| \\`id\\` | string | **yes** | Unique identifier for the prompt |\n| \\`schema_version\\` | number | yes | Always \\`1\\` |\n| \\`description\\` | string | no | Human-readable description |\n| \\`provider\\` | enum | no | \\`openai\\`, \\`anthropic\\`, \\`google\\`, \\`gemini\\`, \\`openrouter\\`, or \\`any\\` |\n| \\`model\\` | string | no | Model identifier (e.g. \\`gpt-5.4\\`, \\`claude-sonnet-4-20250514\\`) |\n| \\`fallback_models\\` | string[] | no | Ordered fallback model list |\n| \\`reasoning\\` | object | no | \\`{ effort: low|medium|high, budget_tokens: number }\\` |\n| \\`sampling\\` | object | no | \\`{ temperature, top_p, frequency_penalty, presence_penalty, stop, max_output_tokens }\\` |\n| \\`response\\` | object | no | \\`{ format: text|json|markdown, stream: boolean }\\` |\n| \\`tools\\` | array | no | Tool names (strings) or inline definitions with \\`{ name, description, input_schema }\\` |\n| \\`mcp\\` | object | no | \\`{ servers: [string | { name, config }] }\\` |\n| \\`context.inputs\\` | string[] | no | Declared variable names used in templates |\n| \\`context.history\\` | object | no | \\`{ max_items: number }\\` |\n| \\`includes\\` | string[] | no | Relative paths to other prompt files to include |\n| \\`environments\\` | object | no | Per-environment overrides (see Overrides) |\n| \\`tiers\\` | object | no | Per-tier overrides (see Overrides) |\n| \\`metadata\\` | object | no | \\`{ owner, tags, review_required, stable }\\` |\n\n---\n\n## Sections (markdown body)\n\nUse H1 headings to define sections. The parser recognizes these headings\n(case-insensitive):\n\n| Heading | Maps to | Purpose |\n|---------|---------|---------|\n| \\`# System instructions\\` | \\`system_instructions\\` | System/developer message |\n| \\`# Prompt template\\` | \\`prompt_template\\` | User message template |\n| \\`# Notes\\` | \\`notes\\` | Documentation only — not sent to the model |\n\nIf the body has **no H1 headings**, the entire body becomes the \\`prompt_template\\`.\n\n---\n\n## Variable interpolation\n\nUse \\`{{ variable_name }}\\` syntax in system instructions and prompt template\nsections. Variables are replaced at render time.\n\nRules:\n- Declare all variables in \\`context.inputs\\` — validation warns on undeclared usage\n- Escape literal braces with \\`\\\\\\\\{{\\` and \\`\\\\\\\\}}\\`\n- In strict mode, missing variables throw an error\n- In permissive mode, unresolved placeholders are left intact\n\n---\n\n## Includes (composition)\n\nCompose prompts from shared fragments:\n\n\\`\\`\\`yaml\nincludes:\n - ./shared/tone.md\n - ./shared/safety.md\n\\`\\`\\`\n\nIncluded files are parsed and their \\`system_instructions\\` are **prepended**\nbefore the including file's own system instructions. Includes resolve\nrecursively. Circular includes are detected and rejected.\n\n> **Note:** Included files do not inherit folder defaults. Only the top-level\n> prompt that is loaded via \\`loadPromptFile\\` receives defaults.\n\n---\n\n## Folder defaults (\\`defaults.md\\`)\n\nDefine shared defaults for a prompt tree by adding a \\`defaults.md\\` file in any\nfolder:\n\n\\`\\`\\`text\nprompts/\n├── defaults.md # global provider, model, metadata + system instructions\n└── support/\n ├── defaults.md # overrides for support/*\n └── reply.md # inherits from support/defaults.md\n\\`\\`\\`\n\nSupported default fields:\n- \\`provider\\` (front matter) — default provider for the folder\n- \\`model\\` (front matter) — default model for the folder\n- \\`metadata\\` (front matter) — merged with prompt-local metadata\n- \\`# System instructions\\` (body section) — used when the prompt has none\n\nThis lets you configure app-wide settings like \\`provider\\` and \\`model\\`\nin a single root \\`defaults.md\\`, so individual prompts only declare what\\u2019s unique to them.\n\nRules:\n- Nearest subfolder \\`defaults.md\\` overrides parent defaults\n- Prompt-local values always take precedence over defaults\n- \\`defaults.md\\` files are skipped during compilation and validation\n- \\`loadPromptFile\\` defaults the search boundary to the file's own directory;\n pass \\`defaultsRoot\\` to enable ancestor traversal\n\n---\n\n## Environment & tier overrides\n\nOverride model settings per environment or tier:\n\n\\`\\`\\`yaml\nenvironments:\n development:\n model: gpt-4.1-mini\n reasoning:\n effort: low\n sampling:\n temperature: 0.9\n production:\n model: gpt-5.4\n reasoning:\n effort: high\n sampling:\n temperature: 0.3\n\ntiers:\n free:\n model: gpt-4.1-mini\n sampling:\n max_output_tokens: 500\n premium:\n model: gpt-5.4\n\\`\\`\\`\n\nOverridable fields: \\`model\\`, \\`fallback_models\\`, \\`reasoning\\`, \\`sampling\\`,\n\\`response\\`, \\`tools\\`.\n\nOverride application order: **base → environment → tier → runtime**.\n\n---\n\n## Test sidecars\n\nCreate a \\`.test.yaml\\` file alongside a prompt to define test cases:\n\n\\`\\`\\`yaml\n# greeting.test.yaml\ncases:\n - name: basic\n variables:\n name: \"World\"\n - name: formal\n variables:\n name: \"Dr. Smith\"\n\\`\\`\\`\n\n---\n\n## Using the library (TypeScript / JavaScript)\n\n### Quick start\n\n\\`\\`\\`typescript\nimport { createPromptOpsKit } from 'promptopskit';\n\nconst kit = createPromptOpsKit({ sourceDir: './prompts' });\n\n// Load → resolve includes → apply overrides → render\nconst request = await kit.renderPrompt('greeting', {\n variables: { name: 'Alice' },\n environment: 'production',\n});\n\n// request.body is ready for the provider's API\nconst response = await fetch('https://api.openai.com/v1/chat/completions', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: \\`Bearer $\\{apiKey}\\`,\n },\n body: JSON.stringify(request.body),\n});\n\\`\\`\\`\n\n### Step-by-step API\n\n\\`\\`\\`typescript\nimport {\n parsePrompt,\n resolveIncludes,\n applyOverrides,\n getAdapter,\n} from 'promptopskit';\nimport { readFileSync } from 'fs';\n\n// 1. Parse a prompt file\nconst source = readFileSync('./prompts/greeting.md', 'utf-8');\nconst asset = parsePrompt(source, 'greeting.md');\n\n// 2. Resolve includes\nconst resolved = await resolveIncludes(asset, './prompts');\n\n// 3. Apply overrides\nconst configured = applyOverrides(resolved, {\n environment: 'production',\n tier: 'premium',\n});\n\n// 4. Get provider adapter and render\nconst adapter = getAdapter(configured.provider ?? 'openai');\nconst request = adapter.render(configured, {\n variables: { name: 'Alice' },\n history: [\n { role: 'user', content: 'Previous message' },\n { role: 'assistant', content: 'Previous response' },\n ],\n});\n\\`\\`\\`\n\n### Available provider adapters\n\n| Provider | Import path | Provider request format |\n|----------|------------|----------------------|\n| OpenAI | \\`promptopskit\\` or \\`promptopskit/openai\\` | Chat Completions API |\n| Anthropic | \\`promptopskit/anthropic\\` | Messages API |\n| Gemini | \\`promptopskit/gemini\\` | GenerateContent API |\n| OpenRouter | \\`promptopskit/openrouter\\` | OpenAI-compatible + extras |\n\n### Validation\n\n\\`\\`\\`typescript\nimport { validateAsset, parsePrompt } from 'promptopskit';\n\nconst asset = parsePrompt(source);\nconst result = validateAsset(asset);\n\nif (!result.valid) {\n console.error(result.errors); // Error codes: POK001-POK021\n}\n\\`\\`\\`\n\n### Testing helpers\n\n\\`\\`\\`typescript\nimport { createMockAsset, parseTestPrompt } from 'promptopskit/testing';\n\n// Create a mock asset for unit tests\nconst mock = createMockAsset({ model: 'gpt-4.1-mini' });\n\n// Parse an inline prompt string for tests\nconst asset = parseTestPrompt(\\`\n---\nid: test\nschema_version: 1\nprovider: openai\nmodel: gpt-5.4\n---\n\n# Prompt template\n\nHello {{ name }}\n\\`);\n\\`\\`\\`\n\n---\n\n## CLI commands\n\n| Command | Description |\n|---------|-------------|\n| \\`promptopskit init [dir]\\` | Scaffold a prompts directory with starter files (including \\`defaults.md\\`) |\n| \\`promptopskit validate <dir>\\` | Validate all prompt files in a directory |\n| \\`promptopskit compile <src> <out>\\` | Compile .md prompts to JSON artifacts |\n| \\`promptopskit render <file> [--set key=value]\\` | Render a prompt preview |\n| \\`promptopskit inspect <file>\\` | Print the normalized prompt asset |\n\n---\n\n## Conventions to follow\n\n1. **One prompt per file** — each \\`.md\\` file is a single prompt asset\n2. **Always set \\`id\\` and \\`schema_version: 1\\`** in front matter (or inherit \\`schema_version\\` from \\`defaults.md\\`)\n3. **Declare all variables** in \\`context.inputs\\` that appear in templates\n4. **Use includes** for shared system instructions (tone, safety, formatting)\n5. **Keep prompt templates focused** — compose behavior via includes, not duplication\n6. **Use environment overrides** for dev/staging/prod model differences\n7. **Add test sidecars** (\\`.test.yaml\\`) for critical prompts\n8. **Run \\`promptopskit validate\\`** before committing changes\n9. **Use \\`defaults.md\\`** to share provider, model, metadata, and system instructions across a folder\n10. **Variable names** should be \\`snake_case\\`\n11. **Prompt file names** should be \\`kebab-case.md\\`\n`.trimEnd();\n","import { validate } from './commands/validate.js';\nimport { compile } from './commands/compile.js';\nimport { render } from './commands/render.js';\nimport { inspect } from './commands/inspect.js';\nimport { init } from './commands/init.js';\nimport { skill } from './commands/skill.js';\n\nconst HELP = `\npromptopskit — Manage prompts, system instructions, tools, and model settings as code\n\nUsage:\n promptopskit <command> [options]\n\nCommands:\n init [dir] Scaffold a prompts directory with starter files\n validate <dir> Validate prompt files\n compile <src> <out> [options] Compile .md prompts to JSON/ESM artifacts\n render <file> [options] Render a prompt preview\n inspect <file> Print normalized prompt asset\n skill [options] Deploy AI agent instructions into your project\n\nOptions:\n --help, -h Show this help message\n --version, -v Show version\n\nRun promptopskit <command> --help for command-specific help.\n`.trim();\n\nasync function main() {\n const args = process.argv.slice(2);\n const command = args[0];\n\n if (!command || command === '--help' || command === '-h') {\n console.log(HELP);\n process.exit(0);\n }\n\n if (command === '--version' || command === '-v') {\n // Dynamic import to read version from package.json\n console.log('0.0.1');\n process.exit(0);\n }\n\n const commandArgs = args.slice(1);\n\n switch (command) {\n case 'init':\n await init(commandArgs);\n break;\n case 'validate':\n await validate(commandArgs);\n break;\n case 'compile':\n await compile(commandArgs);\n break;\n case 'render':\n await render(commandArgs);\n break;\n case 'inspect':\n await inspect(commandArgs);\n break;\n case 'skill':\n await skill(commandArgs);\n break;\n default:\n console.error(`Unknown command: ${command}`);\n console.log(HELP);\n process.exit(1);\n }\n}\n\nmain().catch((err) => {\n console.error(err.message);\n process.exit(1);\n});\n"],"mappings":";;;AAAA,SAAS,eAAe;AACxB,SAAS,QAAAA,OAAM,eAAe;;;ACD9B,OAAO,YAAY;;;ACAnB,SAAS,SAAS;AAIX,IAAM,sBAAsB,EAAE,OAAO;AAAA,EAC1C,MAAM,EAAE,OAAO;AAAA,EACf,aAAa,EAAE,OAAO,EAAE,SAAS;AAAA,EACjC,cAAc,EAAE,OAAO,EAAE,QAAQ,CAAC,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AA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAuUpB,QAAQ;;;AC3cV,IAAMM,QAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAmBX,KAAK;AAEP,eAAe,OAAO;AACpB,QAAM,OAAO,QAAQ,KAAK,MAAM,CAAC;AACjC,QAAM,UAAU,KAAK,CAAC;AAEtB,MAAI,CAAC,WAAW,YAAY,YAAY,YAAY,MAAM;AACxD,YAAQ,IAAIA,KAAI;AAChB,YAAQ,KAAK,CAAC;AAAA,EAChB;AAEA,MAAI,YAAY,eAAe,YAAY,MAAM;AAE/C,YAAQ,IAAI,OAAO;AACnB,YAAQ,KAAK,CAAC;AAAA,EAChB;AAEA,QAAM,cAAc,KAAK,MAAM,CAAC;AAEhC,UAAQ,SAAS;AAAA,IACf,KAAK;AACH,YAAM,KAAK,WAAW;AACtB;AAAA,IACF,KAAK;AACH,YAAM,SAAS,WAAW;AAC1B;AAAA,IACF,KAAK;AACH,YAAM,QAAQ,WAAW;AACzB;AAAA,IACF,KAAK;AACH,YAAM,OAAO,WAAW;AACxB;AAAA,IACF,KAAK;AACH,YAAM,QAAQ,WAAW;AACzB;AAAA,IACF,KAAK;AACH,YAAM,MAAM,WAAW;AACvB;AAAA,IACF;AACE,cAAQ,MAAM,oBAAoB,OAAO,EAAE;AAC3C,cAAQ,IAAIA,KAAI;AAChB,cAAQ,KAAK,CAAC;AAAA,EAClB;AACF;AAEA,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,UAAQ,MAAM,IAAI,OAAO;AACzB,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["join","matter","matter","readFile","resolve","dirname","dirname","resolve","readFile","join","readdir","join","extname","dirname","HELP","collectPromptFiles","join","dirname","readdir","extname","readFile","HELP","getFlag","readFile","parsed","HELP","writeFile","mkdir","join","dirname","existsSync","HELP","writeFile","readFile","mkdir","dirname","existsSync","HELP","HELP"]}
1
+ {"version":3,"sources":["../../src/cli/commands/validate.ts","../../src/parser/parser.ts","../../src/schema/schema.ts","../../src/parser/sections.ts","../../src/parser/loader.ts","../../src/renderer/interpolate.ts","../../src/composition/resolve-includes.ts","../../src/validation/levenshtein.ts","../../src/validation/validate.ts","../../src/cli/commands/compile.ts","../../src/cli/commands/render.ts","../../src/overrides/apply-overrides.ts","../../src/cli/commands/inspect.ts","../../src/cli/commands/init.ts","../../src/cli/commands/skill.ts","../../src/cli/index.ts"],"sourcesContent":["import { readdir } from 'node:fs/promises';\nimport { join, extname } from 'node:path';\nimport { loadPromptFile } from '../../parser/index.js';\nimport { validateAssetWithIncludes } from '../../validation/index.js';\n\nconst HELP = `\npromptopskit validate <dir>\n\nValidate all prompt .md files in a directory.\n\nOptions:\n --strict Treat warnings as errors\n --help, -h Show this help\n`.trim();\n\nexport async function validate(args: string[]): Promise<void> {\n if (args.includes('--help') || args.includes('-h')) {\n console.log(HELP);\n return;\n }\n\n const dir = args.find((a) => !a.startsWith('--'));\n if (!dir) {\n console.error('Error: Please provide a directory to validate.');\n process.exit(1);\n }\n\n const strict = args.includes('--strict');\n const files = await collectPromptFiles(dir);\n\n if (files.length === 0) {\n console.log(`No .md prompt files found in ${dir}`);\n return;\n }\n\n let errorCount = 0;\n let warnCount = 0;\n\n for (const file of files) {\n try {\n const { asset, raw } = await loadPromptFile(file, { defaultsRoot: dir });\n const result = await validateAssetWithIncludes(asset, file, Object.keys(raw.frontMatter));\n\n if (result.errors.length > 0) {\n errorCount += result.errors.length;\n console.error(` ✗ ${file}`);\n for (const err of result.errors) {\n console.error(` ${err.code}: ${err.message}`);\n }\n } else {\n console.log(` ✓ ${file}`);\n }\n\n if (result.warnings.length > 0) {\n warnCount += result.warnings.length;\n for (const warn of result.warnings) {\n const suggestion = warn.suggestion ? ` (${warn.suggestion})` : '';\n console.warn(` ⚠ ${warn.code}: ${warn.message}${suggestion}`);\n }\n }\n } catch (err) {\n errorCount++;\n const message = err instanceof Error ? err.message : String(err);\n console.error(` ✗ ${file}`);\n console.error(` ${message}`);\n }\n }\n\n console.log();\n console.log(`Validated ${files.length} file(s): ${errorCount} error(s), ${warnCount} warning(s)`);\n\n if (errorCount > 0 || (strict && warnCount > 0)) {\n process.exit(1);\n }\n}\n\nasync function collectPromptFiles(dir: string): Promise<string[]> {\n const results: string[] = [];\n const entries = await readdir(dir, { withFileTypes: true, recursive: true });\n for (const entry of entries) {\n if (\n entry.isFile()\n && extname(entry.name) === '.md'\n && !entry.name.endsWith('.test.md')\n && entry.name !== 'defaults.md'\n ) {\n results.push(join(entry.parentPath ?? dir, entry.name));\n }\n }\n return results.sort();\n}\n","import matter from 'gray-matter';\nimport { PromptAssetSchema } from '../schema/index.js';\nimport type { PromptAsset } from '../schema/index.js';\nimport { extractSections } from './sections.js';\n\nexport interface ParseResult {\n asset: PromptAsset;\n raw: {\n frontMatter: Record<string, unknown>;\n body: string;\n };\n}\n\n/**\n * Parse a prompt markdown string (YAML front matter + markdown body)\n * into a validated PromptAsset.\n */\nexport function parsePrompt(content: string, filePath?: string): ParseResult {\n const { data: frontMatter, content: body } = matter(content);\n\n const sections = extractSections(body);\n\n const raw = {\n ...frontMatter,\n sections,\n source: filePath ? { file_path: filePath } : undefined,\n };\n\n const asset = PromptAssetSchema.parse(raw);\n\n return {\n asset,\n raw: {\n frontMatter: frontMatter as Record<string, unknown>,\n body,\n },\n };\n}\n","import { z } from 'zod';\n\n// --- Tool definitions ---\n\nexport const InlineToolDefSchema = z.object({\n name: z.string(),\n description: z.string().optional(),\n input_schema: z.record(z.unknown()).optional(),\n});\n\nexport type InlineToolDef = z.infer<typeof InlineToolDefSchema>;\n\nexport const ToolRefSchema = z.union([z.string(), InlineToolDefSchema]);\n\n// --- MCP ---\n\nexport const MCPServerRefSchema = z.union([\n z.string(),\n z.object({\n name: z.string(),\n config: z.record(z.unknown()).optional(),\n }),\n]);\n\nexport type MCPServerRef = z.infer<typeof MCPServerRefSchema>;\n\n// --- Reasoning ---\n\nexport const ReasoningSchema = z.object({\n effort: z.enum(['low', 'medium', 'high']).optional(),\n budget_tokens: z.number().int().positive().optional(),\n});\n\n// --- Sampling ---\n\nexport const SamplingSchema = z.object({\n temperature: z.number().min(0).max(2).optional(),\n top_p: z.number().min(0).max(1).optional(),\n frequency_penalty: z.number().optional(),\n presence_penalty: z.number().optional(),\n stop: z.array(z.string()).optional(),\n max_output_tokens: z.number().int().positive().optional(),\n});\n\n// --- Response ---\n\nexport const ResponseSchema = z.object({\n format: z.enum(['text', 'json', 'markdown']).optional(),\n stream: z.boolean().optional(),\n});\n\n// --- Context ---\n\nexport const HistorySchema = z.object({\n max_items: z.number().int().positive().optional(),\n});\n\nexport const ContextSchema = z.object({\n inputs: z.array(z.string()).optional(),\n history: HistorySchema.optional(),\n});\n\n// --- Metadata ---\n\nexport const MetadataSchema = z.object({\n owner: z.string().optional(),\n tags: z.array(z.string()).optional(),\n review_required: z.boolean().optional(),\n stable: z.boolean().optional(),\n});\n\n// --- MCP block ---\n\nexport const MCPSchema = z.object({\n servers: z.array(MCPServerRefSchema).optional(),\n});\n\n// --- Overrides (subset allowed in environments/tiers) ---\n\nexport const PromptAssetOverridesSchema = z.object({\n model: z.string().optional(),\n fallback_models: z.array(z.string()).optional(),\n reasoning: ReasoningSchema.optional(),\n sampling: SamplingSchema.optional(),\n response: ResponseSchema.optional(),\n tools: z.array(ToolRefSchema).optional(),\n});\n\nexport type PromptAssetOverrides = z.infer<typeof PromptAssetOverridesSchema>;\n\n// --- Source tracking ---\n\nexport const SourceSchema = z.object({\n file_path: z.string().optional(),\n checksum: z.string().optional(),\n});\n\n// --- Sections (populated by parser) ---\n\nexport const SectionsSchema = z.object({\n system_instructions: z.string().optional(),\n prompt_template: z.string().optional(),\n notes: z.string().optional(),\n});\n\n// --- Defaults files (folder-level inheritance) ---\n\nexport const PromptDefaultsSchema = z.object({\n provider: z.enum(['openai', 'anthropic', 'google', 'gemini', 'openrouter', 'any']).optional(),\n model: z.string().optional(),\n metadata: MetadataSchema.optional(),\n sections: z.object({\n system_instructions: z.string().optional(),\n }).optional(),\n});\n\nexport type PromptDefaults = z.infer<typeof PromptDefaultsSchema>;\n\n// --- Top-level PromptAsset ---\n\nexport const PromptAssetSchema = z.object({\n id: z.string(),\n schema_version: z.number().int().positive().default(1),\n description: z.string().optional(),\n\n provider: z.enum(['openai', 'anthropic', 'google', 'gemini', 'openrouter', 'any']).optional(),\n model: z.string().optional(),\n fallback_models: z.array(z.string()).optional(),\n\n reasoning: ReasoningSchema.optional(),\n sampling: SamplingSchema.optional(),\n response: ResponseSchema.optional(),\n\n tools: z.array(ToolRefSchema).optional(),\n mcp: MCPSchema.optional(),\n\n context: ContextSchema.optional(),\n\n includes: z.array(z.string()).optional(),\n\n environments: z.record(PromptAssetOverridesSchema).optional(),\n tiers: z.record(PromptAssetOverridesSchema).optional(),\n\n metadata: MetadataSchema.optional(),\n\n // Populated by parser, not authored in YAML\n sections: SectionsSchema.optional(),\n source: SourceSchema.optional(),\n});\n\nexport type PromptAsset = z.infer<typeof PromptAssetSchema>;\n\n// --- Resolved asset (after includes, overrides applied) ---\n\nexport interface ResolvedPromptAsset extends PromptAsset {\n sections: {\n system_instructions?: string;\n prompt_template?: string;\n notes?: string;\n };\n source: {\n file_path?: string;\n checksum?: string;\n };\n}\n","export interface Sections {\n system_instructions?: string;\n prompt_template?: string;\n notes?: string;\n}\n\nconst SECTION_MAP: Record<string, keyof Sections> = {\n 'system instructions': 'system_instructions',\n 'prompt template': 'prompt_template',\n 'notes': 'notes',\n};\n\n/**\n * Extract named sections from the markdown body using H1 headings.\n * Case-insensitive. H2+ within a section is treated as content.\n * If no H1 headings are found, the entire body is treated as prompt_template.\n */\nexport function extractSections(body: string): Sections {\n const lines = body.split(/\\r?\\n/);\n const sections: Sections = {};\n\n let currentKey: keyof Sections | null = null;\n let currentLines: string[] = [];\n let foundAnyH1 = false;\n\n for (const line of lines) {\n const h1Match = line.match(/^#\\s+(.+)$/);\n if (h1Match) {\n // Flush previous section\n if (currentKey) {\n sections[currentKey] = currentLines.join('\\n').trim();\n }\n\n foundAnyH1 = true;\n const heading = h1Match[1].trim().toLowerCase();\n currentKey = SECTION_MAP[heading] ?? null;\n currentLines = [];\n } else {\n currentLines.push(line);\n }\n }\n\n // Flush last section\n if (currentKey) {\n sections[currentKey] = currentLines.join('\\n').trim();\n }\n\n // If no H1 headings found, treat entire body as prompt_template\n if (!foundAnyH1) {\n const trimmed = body.trim();\n if (trimmed) {\n sections.prompt_template = trimmed;\n }\n }\n\n return sections;\n}\n","import { readFile } from 'node:fs/promises';\nimport { dirname, join, resolve } from 'node:path';\nimport matter from 'gray-matter';\nimport { parsePrompt } from './parser.js';\nimport type { ParseResult } from './parser.js';\nimport { extractSections } from './sections.js';\nimport { PromptDefaultsSchema } from '../schema/index.js';\nimport type { PromptDefaults } from '../schema/index.js';\n\nconst DEFAULTS_FILE_NAME = 'defaults.md';\n\nexport interface LoadPromptOptions {\n /**\n * Optional boundary directory for defaults discovery.\n * If provided, defaults are loaded from this directory down to the prompt directory.\n */\n defaultsRoot?: string;\n}\n\n/**\n * Load and parse a prompt file from disk.\n */\nexport async function loadPromptFile(filePath: string, options: LoadPromptOptions = {}): Promise<ParseResult> {\n const content = await readFile(filePath, 'utf-8');\n const parsed = parsePrompt(content, filePath);\n // Default the boundary to the file's own directory so traversal never\n // walks above the prompt tree when no explicit root is provided.\n const root = options.defaultsRoot ?? dirname(filePath);\n const defaults = await loadDefaultsForPath(filePath, root);\n const asset = applyDefaults(parsed.asset, defaults);\n\n return {\n ...parsed,\n asset,\n };\n}\n\nasync function loadDefaultsForPath(filePath: string, defaultsRoot?: string): Promise<PromptDefaults> {\n const directories = getDirectoriesToCheck(filePath, defaultsRoot);\n let merged: PromptDefaults = {};\n\n for (const dir of directories) {\n const defaultsPath = join(dir, DEFAULTS_FILE_NAME);\n try {\n const defaultsContent = await readFile(defaultsPath, 'utf-8');\n const defaults = parseDefaults(defaultsContent);\n merged = mergeDefaults(merged, defaults);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {\n throw error;\n }\n }\n }\n\n return merged;\n}\n\nfunction getDirectoriesToCheck(filePath: string, defaultsRoot?: string): string[] {\n const dirs: string[] = [];\n let current = resolve(dirname(filePath));\n const boundary = defaultsRoot ? resolve(defaultsRoot) : undefined;\n\n while (true) {\n dirs.unshift(current);\n if ((boundary && current === boundary) || current === dirname(current)) {\n break;\n }\n current = dirname(current);\n }\n\n return dirs;\n}\n\nfunction parseDefaults(content: string): PromptDefaults {\n const { data: frontMatter, content: body } = matter(content);\n const sections = extractSections(body);\n\n return PromptDefaultsSchema.parse({\n ...frontMatter,\n sections: {\n system_instructions: sections.system_instructions,\n },\n });\n}\n\nfunction mergeDefaults(base: PromptDefaults, local: PromptDefaults): PromptDefaults {\n return {\n provider: local.provider ?? base.provider,\n model: local.model ?? base.model,\n metadata: {\n ...(base.metadata ?? {}),\n ...(local.metadata ?? {}),\n },\n sections: {\n ...(base.sections ?? {}),\n ...(local.sections ?? {}),\n },\n };\n}\n\nfunction applyDefaults(asset: ParseResult['asset'], defaults: PromptDefaults): ParseResult['asset'] {\n const hasDefaultMetadata = defaults.metadata && Object.keys(defaults.metadata).length > 0;\n const hasDefaultSystem = !!defaults.sections?.system_instructions;\n const hasDefaultScalars = defaults.provider !== undefined\n || defaults.model !== undefined;\n\n // Short-circuit: nothing to merge\n if (!hasDefaultMetadata && !hasDefaultSystem && !hasDefaultScalars) {\n return asset;\n }\n\n const mergedMetadata = {\n ...(defaults.metadata ?? {}),\n ...(asset.metadata ?? {}),\n };\n const metadata = Object.keys(mergedMetadata).length > 0 ? mergedMetadata : undefined;\n\n const systemInstructions = asset.sections?.system_instructions ?? defaults.sections?.system_instructions;\n\n const sections = asset.sections\n ? { ...asset.sections, system_instructions: systemInstructions }\n : systemInstructions\n ? { system_instructions: systemInstructions }\n : undefined;\n\n return {\n ...asset,\n provider: asset.provider ?? defaults.provider,\n model: asset.model ?? defaults.model,\n metadata,\n sections,\n };\n}\n","export interface InterpolateOptions {\n strict?: boolean;\n}\n\nconst VARIABLE_RE = /\\{\\{\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*\\}\\}/g;\nconst ESCAPED_OPEN = /\\\\\\{\\\\\\{/g;\nconst ESCAPE_PLACEHOLDER = '\\x00ESCAPED_OPEN\\x00';\n\n/**\n * Interpolate variables into a template string.\n *\n * Syntax: {{ variable_name }}\n * Escape: \\{\\{ produces literal {{\n *\n * In strict mode, throws on missing variables.\n * In permissive mode, leaves {{ placeholder }} intact.\n */\nexport function interpolate(\n template: string,\n variables: Record<string, string>,\n options: InterpolateOptions = {},\n): string {\n const { strict = false } = options;\n\n // Replace escaped sequences with placeholder\n let result = template.replace(ESCAPED_OPEN, ESCAPE_PLACEHOLDER);\n\n result = result.replace(VARIABLE_RE, (match, name: string) => {\n if (name in variables) {\n return variables[name];\n }\n if (strict) {\n throw new Error(`Missing required variable: \"${name}\"`);\n }\n return match; // leave placeholder intact in permissive mode\n });\n\n // Restore escaped sequences\n result = result.replaceAll(ESCAPE_PLACEHOLDER, '{{');\n\n return result;\n}\n\n/**\n * Extract all variable names referenced in a template.\n */\nexport function extractVariables(template: string): string[] {\n const vars = new Set<string>();\n let match: RegExpExecArray | null;\n const re = new RegExp(VARIABLE_RE.source, 'g');\n while ((match = re.exec(template)) !== null) {\n vars.add(match[1]);\n }\n return [...vars];\n}\n","import { readFile } from 'node:fs/promises';\nimport { resolve, dirname } from 'node:path';\nimport { parsePrompt } from '../parser/index.js';\nimport type { PromptAsset } from '../schema/index.js';\n\n/**\n * Resolve includes for a prompt asset, inlining content from referenced files.\n * Detects and rejects circular includes.\n */\nexport async function resolveIncludes(\n asset: PromptAsset,\n basePath: string,\n visited: Set<string> = new Set(),\n): Promise<PromptAsset> {\n if (!asset.includes || asset.includes.length === 0) {\n return asset;\n }\n\n const baseDir = dirname(basePath);\n const resolvedPath = resolve(basePath);\n\n if (visited.has(resolvedPath)) {\n throw new Error(`Circular include detected: ${resolvedPath}`);\n }\n visited.add(resolvedPath);\n\n let mergedSystemInstructions = '';\n\n for (const includePath of asset.includes) {\n const fullPath = resolve(baseDir, includePath);\n\n if (visited.has(fullPath)) {\n throw new Error(`Circular include detected: ${fullPath} (included from ${basePath})`);\n }\n\n const content = await readFile(fullPath, 'utf-8');\n const { asset: includedAsset } = parsePrompt(content, fullPath);\n\n // Recursively resolve nested includes\n const resolved = await resolveIncludes(includedAsset, fullPath, new Set(visited));\n\n // Append included system instructions before local ones\n if (resolved.sections?.system_instructions) {\n mergedSystemInstructions += resolved.sections.system_instructions + '\\n\\n';\n }\n }\n\n // Prepend included system instructions before the local ones\n const localSystem = asset.sections?.system_instructions ?? '';\n const combinedSystem = (mergedSystemInstructions + localSystem).trim() || undefined;\n\n return {\n ...asset,\n sections: {\n ...asset.sections,\n system_instructions: combinedSystem,\n },\n // Drop includes from the resolved asset — they've been inlined\n includes: undefined,\n };\n}\n","/**\n * Compute the Levenshtein distance between two strings.\n * Used for \"did you mean?\" suggestions on unknown fields.\n */\nexport function levenshtein(a: string, b: string): number {\n const m = a.length;\n const n = b.length;\n\n if (m === 0) return n;\n if (n === 0) return m;\n\n const dp: number[][] = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0) as number[]);\n\n for (let i = 0; i <= m; i++) dp[i][0] = i;\n for (let j = 0; j <= n; j++) dp[0][j] = j;\n\n for (let i = 1; i <= m; i++) {\n for (let j = 1; j <= n; j++) {\n const cost = a[i - 1] === b[j - 1] ? 0 : 1;\n dp[i][j] = Math.min(\n dp[i - 1][j] + 1,\n dp[i][j - 1] + 1,\n dp[i - 1][j - 1] + cost,\n );\n }\n }\n\n return dp[m][n];\n}\n","import { PromptAssetSchema } from '../schema/index.js';\nimport type { PromptAsset } from '../schema/index.js';\nimport { extractVariables } from '../renderer/index.js';\nimport { resolveIncludes } from '../composition/index.js';\nimport { levenshtein } from './levenshtein.js';\n\nexport interface ValidationError {\n code: string;\n message: string;\n filePath?: string;\n suggestion?: string;\n}\n\nexport interface PromptValidationResult {\n valid: boolean;\n errors: ValidationError[];\n warnings: ValidationError[];\n}\n\nconst KNOWN_FRONT_MATTER_KEYS = new Set([\n 'id', 'schema_version', 'description', 'provider', 'model', 'fallback_models',\n 'reasoning', 'sampling', 'response', 'tools', 'mcp', 'context', 'includes',\n 'environments', 'tiers', 'metadata',\n]);\n\n/**\n * Validate a parsed prompt asset, returning all errors and warnings.\n */\nexport function validateAsset(\n asset: PromptAsset,\n frontMatterKeys?: string[],\n filePath?: string,\n): PromptValidationResult {\n const errors: ValidationError[] = [];\n const warnings: ValidationError[] = [];\n\n // Schema validation\n const result = PromptAssetSchema.safeParse(asset);\n if (!result.success) {\n for (const issue of result.error.issues) {\n errors.push({\n code: 'POK001',\n message: `Schema error at ${issue.path.join('.')}: ${issue.message}`,\n filePath,\n });\n }\n }\n\n // Missing id\n if (!asset.id) {\n errors.push({\n code: 'POK002',\n message: 'Missing required field: \"id\"',\n filePath,\n });\n }\n\n // Missing body sections\n if (!asset.sections?.system_instructions && !asset.sections?.prompt_template) {\n errors.push({\n code: 'POK003',\n message: 'Prompt must have at least one body section (System instructions or Prompt template)',\n filePath,\n });\n }\n\n // Unknown front matter keys with \"did you mean?\"\n if (frontMatterKeys) {\n for (const key of frontMatterKeys) {\n if (!KNOWN_FRONT_MATTER_KEYS.has(key)) {\n const suggestion = findClosestMatch(key, KNOWN_FRONT_MATTER_KEYS);\n warnings.push({\n code: 'POK010',\n message: `Unknown front matter field: \"${key}\"`,\n filePath,\n suggestion: suggestion ? `Did you mean \"${suggestion}\"?` : undefined,\n });\n }\n }\n }\n\n // Variable validation: used but not declared\n const declaredInputs = new Set(asset.context?.inputs ?? []);\n const usedVars = new Set<string>();\n\n if (asset.sections?.system_instructions) {\n for (const v of extractVariables(asset.sections.system_instructions)) {\n usedVars.add(v);\n }\n }\n if (asset.sections?.prompt_template) {\n for (const v of extractVariables(asset.sections.prompt_template)) {\n usedVars.add(v);\n }\n }\n\n for (const v of usedVars) {\n if (declaredInputs.size > 0 && !declaredInputs.has(v)) {\n warnings.push({\n code: 'POK011',\n message: `Variable \"{{ ${v} }}\" is used but not declared in context.inputs`,\n filePath,\n });\n }\n }\n\n // Declared but unused\n for (const v of declaredInputs) {\n if (!usedVars.has(v)) {\n warnings.push({\n code: 'POK012',\n message: `Variable \"${v}\" is declared in context.inputs but never used`,\n filePath,\n });\n }\n }\n\n return {\n valid: errors.length === 0,\n errors,\n warnings,\n };\n}\n\n/**\n * Validate a prompt asset including its include graph.\n * Catches missing include files, circular includes, and parse errors in included files.\n */\nexport async function validateAssetWithIncludes(\n asset: PromptAsset,\n filePath: string,\n frontMatterKeys?: string[],\n): Promise<PromptValidationResult> {\n // Run standard validation first\n const result = validateAsset(asset, frontMatterKeys, filePath);\n\n // Validate includes\n if (asset.includes && asset.includes.length > 0) {\n try {\n await resolveIncludes(asset, filePath);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n const isCircular = message.includes('Circular include');\n result.errors.push({\n code: isCircular ? 'POK021' : 'POK020',\n message: isCircular\n ? `Circular include detected: ${message}`\n : `Include resolution failed: ${message}`,\n filePath,\n });\n result.valid = false;\n }\n }\n\n return result;\n}\n\nfunction findClosestMatch(input: string, candidates: Set<string>): string | undefined {\n let best: string | undefined;\n let bestDist = Infinity;\n\n for (const candidate of candidates) {\n const dist = levenshtein(input.toLowerCase(), candidate.toLowerCase());\n if (dist < bestDist && dist <= 3) {\n bestDist = dist;\n best = candidate;\n }\n }\n\n return best;\n}\n","import { readdir, writeFile, mkdir, rm } from 'node:fs/promises';\nimport { join, extname, relative, dirname } from 'node:path';\nimport { loadPromptFile } from '../../parser/index.js';\nimport { resolveIncludes } from '../../composition/index.js';\n\nconst HELP = `\npromptopskit compile <sourceDir> <outputDir> [options]\n\nCompile .md prompt files to JSON artifacts.\n\nOptions:\n --no-clean Don't clear the output directory before compiling\n --dry-run Show what would be compiled without writing files\n --format Output format: json (default) or esm\n --help, -h Show this help\n`.trim();\n\nexport async function compile(args: string[]): Promise<void> {\n if (args.includes('--help') || args.includes('-h')) {\n console.log(HELP);\n return;\n }\n\n const positional = args.filter((a) => !a.startsWith('--'));\n const sourceDir = positional[0];\n const outputDir = positional[1];\n\n if (!sourceDir || !outputDir) {\n console.error('Error: Please provide source and output directories.');\n console.error('Usage: promptopskit compile <sourceDir> <outputDir>');\n process.exit(1);\n }\n\n const dryRun = args.includes('--dry-run');\n const noClean = args.includes('--no-clean');\n const format = getFlag(args, '--format') ?? 'json';\n\n if (format !== 'json' && format !== 'esm') {\n console.error(`Error: Unknown format \"${format}\". Use \"json\" or \"esm\".`);\n process.exit(1);\n }\n\n // Collect prompt files\n const files = await collectPromptFiles(sourceDir);\n\n if (files.length === 0) {\n console.log(`No .md prompt files found in ${sourceDir}`);\n return;\n }\n\n // Clean output dir\n if (!noClean && !dryRun) {\n await rm(outputDir, { recursive: true, force: true });\n }\n\n let compiled = 0;\n let errors = 0;\n\n for (const file of files) {\n const rel = relative(sourceDir, file).replace(/\\.md$/, '');\n const outExt = format === 'esm' ? '.mjs' : '.json';\n const outPath = join(outputDir, rel + outExt);\n\n try {\n const { asset: parsed } = await loadPromptFile(file, { defaultsRoot: sourceDir });\n\n // Resolve includes so compiled artifacts are self-sufficient\n const asset = (parsed.includes && parsed.includes.length > 0)\n ? await resolveIncludes(parsed, file)\n : parsed;\n\n if (dryRun) {\n console.log(` Would create: ${outPath}`);\n } else {\n await mkdir(dirname(outPath), { recursive: true });\n\n if (format === 'esm') {\n const esmContent = `export default ${JSON.stringify(asset, null, 2)};\\n`;\n await writeFile(outPath, esmContent, 'utf-8');\n } else {\n await writeFile(outPath, JSON.stringify(asset, null, 2) + '\\n', 'utf-8');\n }\n console.log(` ✓ ${outPath}`);\n }\n compiled++;\n } catch (err) {\n errors++;\n const message = err instanceof Error ? err.message : String(err);\n console.error(` ✗ ${file}`);\n console.error(` ${message}`);\n }\n }\n\n console.log();\n if (dryRun) {\n console.log(`Dry run: ${compiled} file(s) would be compiled, ${errors} error(s)`);\n } else {\n console.log(`Compiled ${compiled} file(s), ${errors} error(s)`);\n }\n\n if (errors > 0) {\n process.exit(1);\n }\n}\n\nfunction getFlag(args: string[], flag: string): string | undefined {\n const idx = args.indexOf(flag);\n if (idx >= 0 && idx + 1 < args.length) {\n return args[idx + 1];\n }\n return undefined;\n}\n\nasync function collectPromptFiles(dir: string): Promise<string[]> {\n const results: string[] = [];\n const entries = await readdir(dir, { withFileTypes: true, recursive: true });\n for (const entry of entries) {\n if (\n entry.isFile()\n && extname(entry.name) === '.md'\n && !entry.name.endsWith('.test.md')\n && entry.name !== 'defaults.md'\n ) {\n results.push(join(entry.parentPath ?? dir, entry.name));\n }\n }\n return results.sort();\n}\n","import { readFile } from 'node:fs/promises';\nimport { existsSync } from 'node:fs';\nimport { loadPromptFile } from '../../parser/index.js';\nimport { resolveIncludes } from '../../composition/index.js';\nimport { applyOverrides } from '../../overrides/index.js';\nimport { interpolate } from '../../renderer/interpolate.js';\n\nconst HELP = `\npromptopskit render <file> [options]\n\nRender a prompt preview with variables.\n\nOptions:\n --env <name> Environment override\n --tier <name> Tier override\n --vars <file> JSON file with variables\n --json Output raw JSON instead of readable format\n --help, -h Show this help\n`.trim();\n\nexport async function render(args: string[]): Promise<void> {\n if (args.includes('--help') || args.includes('-h')) {\n console.log(HELP);\n return;\n }\n\n const file = args.find((a) => !a.startsWith('--'));\n if (!file) {\n console.error('Error: Please provide a prompt file to render.');\n process.exit(1);\n }\n\n const env = getFlag(args, '--env');\n const tier = getFlag(args, '--tier');\n const varsFile = getFlag(args, '--vars');\n const jsonOutput = args.includes('--json');\n\n // Load variables from file or sidecar\n let variables: Record<string, string> = {};\n\n if (varsFile) {\n const varsContent = await readFile(varsFile, 'utf-8');\n variables = JSON.parse(varsContent);\n } else {\n // Try auto-loading sidecar .test.yaml\n const sidecarPath = file.replace(/\\.md$/, '.test.yaml');\n if (existsSync(sidecarPath)) {\n const { default: yaml } = await import('gray-matter');\n const sidecarContent = await readFile(sidecarPath, 'utf-8');\n // Wrap in --- delimiters so gray-matter parses the entire file as front matter\n const parsed = yaml(`---\\n${sidecarContent}---\\n`);\n const data = parsed.data as { cases?: Array<{ variables?: Record<string, string> }> };\n if (data.cases?.[0]?.variables) {\n variables = data.cases[0].variables;\n }\n }\n }\n\n const { asset: parsed } = await loadPromptFile(file);\n\n // Resolve includes (matching the library pipeline)\n const resolved = (parsed.includes && parsed.includes.length > 0)\n ? await resolveIncludes(parsed, file)\n : parsed;\n\n // Apply overrides using the standard applyOverrides function\n const overridden = applyOverrides(resolved, {\n environment: env,\n tier: tier,\n });\n\n // Render sections with variables\n const renderedSystem = overridden.sections?.system_instructions\n ? interpolate(overridden.sections.system_instructions, variables)\n : undefined;\n const renderedPrompt = overridden.sections?.prompt_template\n ? interpolate(overridden.sections.prompt_template, variables)\n : undefined;\n\n if (jsonOutput) {\n console.log(JSON.stringify({\n id: overridden.id,\n provider: overridden.provider,\n model: overridden.model,\n system_instructions: renderedSystem,\n prompt_template: renderedPrompt,\n tools: overridden.tools,\n }, null, 2));\n return;\n }\n\n // Readable output\n const label = [\n overridden.provider,\n overridden.model,\n [env, tier].filter(Boolean).join('/'),\n ].filter(Boolean).join(', ');\n\n console.log(`── ${overridden.id} (${label}) ${'─'.repeat(Math.max(0, 50 - overridden.id.length - label.length))}`);\n\n if (renderedSystem) {\n console.log(`System: ${renderedSystem.split('\\n')[0]}${renderedSystem.includes('\\n') ? '...' : ''}`);\n }\n if (renderedPrompt) {\n console.log(`User: ${renderedPrompt.split('\\n')[0]}${renderedPrompt.includes('\\n') ? '...' : ''}`);\n }\n if (overridden.tools?.length) {\n const toolNames = overridden.tools.map((t) => typeof t === 'string' ? t : t.name);\n console.log(`Tools: ${toolNames.join(', ')}`);\n }\n console.log(`Model: ${overridden.model ?? 'not set'}`);\n console.log('─'.repeat(60));\n}\n\nfunction getFlag(args: string[], flag: string): string | undefined {\n const idx = args.indexOf(flag);\n if (idx >= 0 && idx + 1 < args.length) {\n return args[idx + 1];\n }\n return undefined;\n}\n","import type { PromptAsset, PromptAssetOverrides } from '../schema/index.js';\n\nexport interface OverrideOptions {\n environment?: string;\n tier?: string;\n runtime?: Partial<PromptAssetOverrides>;\n}\n\n/**\n * Apply environment, tier, and runtime overrides to a prompt asset.\n *\n * Precedence: base → environment → tier → runtime\n * Scalars are replaced. Arrays are replaced (not concatenated).\n */\nexport function applyOverrides(\n asset: PromptAsset,\n options: OverrideOptions = {},\n): PromptAsset {\n let result = { ...asset };\n\n // Apply environment override\n if (options.environment && result.environments?.[options.environment]) {\n result = mergeOverride(result, result.environments[options.environment]);\n }\n\n // Apply tier override\n if (options.tier && result.tiers?.[options.tier]) {\n result = mergeOverride(result, result.tiers[options.tier]);\n }\n\n // Apply runtime overrides\n if (options.runtime) {\n result = mergeOverride(result, options.runtime);\n }\n\n return result;\n}\n\nfunction mergeOverride(\n base: PromptAsset,\n override: Partial<PromptAssetOverrides>,\n): PromptAsset {\n const result = { ...base };\n\n if (override.model !== undefined) result.model = override.model;\n if (override.fallback_models !== undefined) result.fallback_models = override.fallback_models;\n if (override.tools !== undefined) result.tools = override.tools;\n\n if (override.reasoning !== undefined) {\n result.reasoning = { ...result.reasoning, ...override.reasoning };\n }\n if (override.sampling !== undefined) {\n result.sampling = { ...result.sampling, ...override.sampling };\n }\n if (override.response !== undefined) {\n result.response = { ...result.response, ...override.response };\n }\n\n return result;\n}\n","import { loadPromptFile } from '../../parser/index.js';\nimport { resolveIncludes } from '../../composition/index.js';\n\nconst HELP = `\npromptopskit inspect <file>\n\nPrint the normalized prompt asset as JSON.\n\nOptions:\n --help, -h Show this help\n`.trim();\n\nexport async function inspect(args: string[]): Promise<void> {\n if (args.includes('--help') || args.includes('-h')) {\n console.log(HELP);\n return;\n }\n\n const file = args.find((a) => !a.startsWith('--'));\n if (!file) {\n console.error('Error: Please provide a prompt file to inspect.');\n process.exit(1);\n }\n\n const { asset: parsed } = await loadPromptFile(file);\n\n // Resolve includes so the output shows the fully resolved asset\n const asset = (parsed.includes && parsed.includes.length > 0)\n ? await resolveIncludes(parsed, file)\n : parsed;\n\n console.log(JSON.stringify(asset, null, 2));\n}\n","import { writeFile, mkdir } from 'node:fs/promises';\nimport { join, dirname } from 'node:path';\nimport { existsSync, readFileSync } from 'node:fs';\n\nconst HELP = `\npromptopskit init [dir]\n\nScaffold a prompts directory with starter files.\n\nOptions:\n --help, -h Show this help\n`.trim();\n\nconst HELLO_PROMPT = `---\nid: hello\ncontext:\n inputs:\n - name\n - app_context\nincludes:\n - ./shared/tone.md\nreasoning:\n effort: high\nenvironments:\n dev:\n model: gpt-5.4-mini\n reasoning:\n effort: low\n sampling:\n temperature: 0.2\n---\n\n# System instructions\n\nYou are a friendly assistant. Be helpful and concise.\nCurrent app context: {{ app_context }}.\n\n# Prompt template\n\nSay hello to {{ name }} and ask how you can help them today.\n`.trimStart();\n\nconst TONE_INCLUDE = `---\nid: shared/tone\nschema_version: 1\n---\n\n# System instructions\n\nAlways be polite, professional, and concise. Avoid jargon unless the user uses it first.\n`.trimStart();\n\nconst DEFAULTS = `---\nprovider: openai\nmodel: gpt-5.4\nmetadata:\n owner: my-team\n review_required: true\n---\n\n# System instructions\n\nYou are a helpful AI assistant. Follow company guidelines at all times.\n`.trimStart();\n\nconst TEST_SIDECAR = `cases:\n - name: basic-greeting\n variables:\n name: \"World\"\n app_context: \"Welcome screen\"\n - name: named-greeting\n variables:\n name: \"Alice\"\n app_context: \"Settings page\"\n`;\n\nconst EXAMPLE_USAGE = `// Example: render the hello prompt and send it to OpenAI\n// Full docs: https://promptopskit.com/docs/index.html#/\n\nimport { createPromptOpsKit } from 'promptopskit';\n\nasync function main() {\n const kit = createPromptOpsKit({ sourceDir: './prompts' });\n\n // Determine environment from ENV var (defaults to 'dev')\n // - dev: uses gpt-5.4-mini, low reasoning effort, temperature 0.2\n // - production: uses base model gpt-5.4 with high reasoning effort\n const environment = process.env.NODE_ENV === 'production' ? 'prod' : 'dev';\n\n const { request } = await kit.renderPrompt({\n path: 'hello',\n provider: 'openai',\n environment,\n variables: {\n name: 'World',\n app_context: 'Welcome screen',\n },\n });\n\n // request.body is the fully transformed OpenAI Chat Completions payload.\n // For the hello.md prompt in the dev environment it looks like:\n //\n // {\n // \"model\": \"gpt-5.4-mini\",\n // \"reasoning_effort\": \"low\",\n // \"temperature\": 0.2,\n // \"messages\": [\n // {\n // \"role\": \"system\",\n // \"content\": \"You are a friendly assistant. Be helpful and concise.\\nCurrent app context: Welcome screen.\\n\\nAlways be polite, professional, and concise. Avoid jargon unless the user uses it first.\"\n // },\n // {\n // \"role\": \"user\",\n // \"content\": \"Say hello to World and ask how you can help them today.\"\n // }\n // ]\n // }\n\n console.log('Model:', request.body.model);\n\n const res = await fetch('https://api.openai.com/v1/chat/completions', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: \\`Bearer \\${process.env.OPENAI_API_KEY}\\`,\n },\n body: JSON.stringify(request.body),\n });\n\n const data = await res.json();\n console.log(data.choices[0].message.content);\n}\n\nmain();\n`;\n\nexport async function init(args: string[]): Promise<void> {\n if (args.includes('--help') || args.includes('-h')) {\n console.log(HELP);\n return;\n }\n\n const dir = args.find((a) => !a.startsWith('--')) ?? './prompts';\n\n const files: Array<{ path: string; content: string }> = [\n { path: join(dir, 'defaults.md'), content: DEFAULTS },\n { path: join(dir, 'hello.md'), content: HELLO_PROMPT },\n { path: join(dir, 'hello.test.yaml'), content: TEST_SIDECAR },\n { path: join(dir, 'shared', 'tone.md'), content: TONE_INCLUDE },\n { path: join(dir, 'example-usage.ts'), content: EXAMPLE_USAGE },\n ];\n\n let created = 0;\n let skipped = 0;\n\n for (const file of files) {\n if (existsSync(file.path)) {\n console.log(` skip ${file.path} (already exists)`);\n skipped++;\n continue;\n }\n await mkdir(dirname(file.path), { recursive: true });\n await writeFile(file.path, file.content, 'utf-8');\n console.log(` ✓ ${file.path}`);\n created++;\n }\n\n console.log();\n console.log(`Created ${created} file(s), skipped ${skipped} existing.`);\n\n // Suggest build script if package.json exists\n if (existsSync('package.json')) {\n try {\n const pkg = JSON.parse(readFileSync('package.json', 'utf-8'));\n if (!pkg.scripts?.['build:prompts']) {\n console.log();\n console.log(`Tip: Add to your package.json scripts:`);\n console.log(` \"build:prompts\": \"promptopskit compile ${dir} ./dist/prompts\"`);\n }\n } catch {\n // Ignore parse errors\n }\n }\n}\n","import { writeFile, readFile, mkdir } from 'node:fs/promises';\nimport { dirname } from 'node:path';\nimport { existsSync } from 'node:fs';\n\nconst MARKER_START = '<!-- promptopskit:start -->';\nconst MARKER_END = '<!-- promptopskit:end -->';\n\nconst HELP = `\npromptopskit skill [--target <target>] [--force]\n\nDeploy AI agent instructions so coding assistants know how to\ncreate and manage prompts using promptopskit.\n\nBy default, generates files for all major AI coding assistants:\n\n AGENTS.md Codex, OpenCode, Cursor, Copilot\n CLAUDE.md Claude Code (imports AGENTS.md)\n .github/instructions/promptopskit.instructions.md GitHub Copilot (path-specific)\n .cursor/rules/promptopskit.mdc Cursor (project rule)\n\nIf a file already exists, the promptopskit section is merged (replaced\nin-place or appended). Use --force to overwrite the entire file.\n\nOptions:\n --target, -t Deploy only a specific target (agents, claude, copilot, cursor)\n --force, -f Overwrite entire file instead of merging\n --help, -h Show this help\n`.trim();\n\nconst STUB_CONTENT = `# promptopskit\n\nThis project uses **promptopskit** to manage LLM prompts as code.\nRead the full guide at \\`node_modules/promptopskit/SKILL.md\\` before\ncreating or editing prompt files.`;\n\nconst CLAUDE_LINE = '@AGENTS.md';\n\ninterface TargetConfig {\n path: string;\n wrap: (content: string) => string;\n}\n\nconst TARGETS: Record<string, TargetConfig> = {\n agents: {\n path: 'AGENTS.md',\n wrap: (content) => content,\n },\n claude: {\n path: 'CLAUDE.md',\n wrap: () => CLAUDE_LINE + '\\n',\n },\n copilot: {\n path: '.github/instructions/promptopskit.instructions.md',\n wrap: (content) =>\n `---\\napplyTo: \"**\"\\n---\\n\\n${content}`,\n },\n cursor: {\n path: '.cursor/rules/promptopskit.mdc',\n wrap: (content) =>\n `---\\ndescription: How to create and manage prompts using promptopskit\\nglobs: \"**\"\\nalwaysApply: true\\n---\\n\\n${content}`,\n },\n};\n\nconst ALL_TARGETS = ['agents', 'claude', 'copilot', 'cursor'];\n\nexport async function skill(args: string[]): Promise<void> {\n if (args.includes('--help') || args.includes('-h')) {\n console.log(HELP);\n return;\n }\n\n const force = args.includes('--force') || args.includes('-f');\n\n let targets = ALL_TARGETS;\n const targetIdx = args.findIndex((a) => a === '--target' || a === '-t');\n if (targetIdx !== -1 && args[targetIdx + 1]) {\n const target = args[targetIdx + 1];\n const config = TARGETS[target];\n if (!config) {\n console.error(`Unknown target: ${target}`);\n console.error(`Valid targets: ${Object.keys(TARGETS).join(', ')}`);\n process.exit(1);\n }\n targets = [target];\n }\n\n let written = 0;\n for (const target of targets) {\n const config = TARGETS[target];\n const filePath = config.path;\n\n // CLAUDE.md uses a simple import line — handle dedup separately\n if (target === 'claude') {\n written += await deployClaude(filePath, force);\n continue;\n }\n\n const markedContent = config.wrap(wrapMarkers(STUB_CONTENT));\n\n if (existsSync(filePath) && !force) {\n const existing = await readFile(filePath, 'utf-8');\n const merged = mergeContent(existing, markedContent);\n if (merged === existing) {\n console.log(` skip ${filePath} (already up to date)`);\n continue;\n }\n await writeFile(filePath, merged, 'utf-8');\n console.log(` ✓ ${filePath} (merged)`);\n written++;\n continue;\n }\n\n await mkdir(dirname(filePath), { recursive: true });\n await writeFile(filePath, markedContent, 'utf-8');\n console.log(` ✓ ${filePath}`);\n written++;\n }\n\n if (written > 0) {\n console.log();\n console.log(`AI agents will now understand how to create and manage prompts with promptopskit.`);\n }\n}\n\n// ---------------------------------------------------------------------------\n// CLAUDE.md — append @AGENTS.md if not already present\n// ---------------------------------------------------------------------------\n\nasync function deployClaude(filePath: string, force: boolean): Promise<number> {\n const content = CLAUDE_LINE + '\\n';\n\n if (!existsSync(filePath) || force) {\n await mkdir(dirname(filePath), { recursive: true });\n await writeFile(filePath, content, 'utf-8');\n console.log(` ✓ ${filePath}`);\n return 1;\n }\n\n const existing = await readFile(filePath, 'utf-8');\n if (existing.split('\\n').some((line) => line.trim() === CLAUDE_LINE)) {\n console.log(` skip ${filePath} (already up to date)`);\n return 0;\n }\n\n const separator = existing.endsWith('\\n') ? '\\n' : '\\n\\n';\n await writeFile(filePath, existing + separator + content, 'utf-8');\n console.log(` ✓ ${filePath} (merged)`);\n return 1;\n}\n\n// ---------------------------------------------------------------------------\n// Marker helpers\n// ---------------------------------------------------------------------------\n\nfunction wrapMarkers(content: string): string {\n return `${MARKER_START}\\n${content}\\n${MARKER_END}`;\n}\n\nfunction mergeContent(existing: string, markedContent: string): string {\n const startIdx = existing.indexOf(MARKER_START);\n const endIdx = existing.indexOf(MARKER_END);\n\n // Replace existing block in-place\n if (startIdx !== -1 && endIdx !== -1 && endIdx > startIdx) {\n return (\n existing.slice(0, startIdx) +\n markedContent +\n existing.slice(endIdx + MARKER_END.length)\n );\n }\n\n // Append to end\n const separator = existing.endsWith('\\n') ? '\\n' : '\\n\\n';\n return existing + separator + markedContent + '\\n';\n}\n","import { validate } from './commands/validate.js';\nimport { compile } from './commands/compile.js';\nimport { render } from './commands/render.js';\nimport { inspect } from './commands/inspect.js';\nimport { init } from './commands/init.js';\nimport { skill } from './commands/skill.js';\n\nconst HELP = `\npromptopskit — Manage prompts, system instructions, tools, and model settings as code\n\nUsage:\n promptopskit <command> [options]\n\nCommands:\n init [dir] Scaffold a prompts directory with starter files\n validate <dir> Validate prompt files\n compile <src> <out> [options] Compile .md prompts to JSON/ESM artifacts\n render <file> [options] Render a prompt preview\n inspect <file> Print normalized prompt asset\n skill [options] Deploy AI agent instructions into your project\n\nOptions:\n --help, -h Show this help message\n --version, -v Show version\n\nRun promptopskit <command> --help for command-specific help.\n`.trim();\n\nasync function main() {\n const args = process.argv.slice(2);\n const command = args[0];\n\n if (!command || command === '--help' || command === '-h') {\n console.log(HELP);\n process.exit(0);\n }\n\n if (command === '--version' || command === '-v') {\n // Dynamic import to read version from package.json\n console.log('0.0.1');\n process.exit(0);\n }\n\n const commandArgs = args.slice(1);\n\n switch (command) {\n case 'init':\n await init(commandArgs);\n break;\n case 'validate':\n await validate(commandArgs);\n break;\n case 'compile':\n await compile(commandArgs);\n break;\n case 'render':\n await render(commandArgs);\n break;\n case 'inspect':\n await inspect(commandArgs);\n break;\n case 'skill':\n await skill(commandArgs);\n break;\n default:\n console.error(`Unknown command: ${command}`);\n console.log(HELP);\n process.exit(1);\n }\n}\n\nmain().catch((err) => {\n console.error(err.message);\n process.exit(1);\n});\n"],"mappings":";;;AAAA,SAAS,eAAe;AACxB,SAAS,QAAAA,OAAM,eAAe;;;ACD9B,OAAO,YAAY;;;ACAnB,SAAS,SAAS;AAIX,IAAM,sBAAsB,EAAE,OAAO;AAAA,EAC1C,MAAM,EAAE,OAAO;AAAA,EACf,aAAa,EAAE,OAAO,EAAE,SAAS;AAAA,EACjC,cAAc,EAAE,OAAO,EAAE,QAAQ,CAAC,EAAE,SAAS;AAC/C,CAAC;AAIM,IAAM,gBAAgB,EAAE,MAAM,CAAC,EAAE,OAAO,GAAG,mBAAmB,CAAC;AAI/D,IAAM,qBAAqB,EAAE,MAAM;AAAA,EACxC,EAAE,OAAO;AAAA,EACT,EAAE,OAAO;AAAA,IACP,MAAM,EAAE,OAAO;AAAA,IACf,QAAQ,EAAE,OAAO,EAAE,QAAQ,CAAC,EAAE,SAAS;AAAA,EACzC,CAAC;AACH,CAAC;AAMM,IAAM,kBAAkB,EAAE,OAAO;AAAA,EACtC,QAAQ,EAAE,KAAK,CAAC,OAAO,UAAU,MAAM,CAAC,EAAE,SAAS;AAAA,EACnD,eAAe,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,SAAS;AACtD,CAAC;AAIM,IAAM,iBAAiB,EAAE,OAAO;AAAA,EACrC,aAAa,EAAE,OAA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Q,KAAK,CAAC;AAAA,EAChB;AAEA,QAAM,cAAc,KAAK,MAAM,CAAC;AAEhC,UAAQ,SAAS;AAAA,IACf,KAAK;AACH,YAAM,KAAK,WAAW;AACtB;AAAA,IACF,KAAK;AACH,YAAM,SAAS,WAAW;AAC1B;AAAA,IACF,KAAK;AACH,YAAM,QAAQ,WAAW;AACzB;AAAA,IACF,KAAK;AACH,YAAM,OAAO,WAAW;AACxB;AAAA,IACF,KAAK;AACH,YAAM,QAAQ,WAAW;AACzB;AAAA,IACF,KAAK;AACH,YAAM,MAAM,WAAW;AACvB;AAAA,IACF;AACE,cAAQ,MAAM,oBAAoB,OAAO,EAAE;AAC3C,cAAQ,IAAIA,KAAI;AAChB,cAAQ,KAAK,CAAC;AAAA,EAClB;AACF;AAEA,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,UAAQ,MAAM,IAAI,OAAO;AACzB,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["join","matter","matter","readFile","resolve","dirname","dirname","resolve","readFile","join","readdir","join","extname","dirname","HELP","collectPromptFiles","join","dirname","readdir","extname","readFile","HELP","getFlag","readFile","parsed","HELP","writeFile","mkdir","join","dirname","existsSync","HELP","writeFile","readFile","mkdir","dirname","existsSync","HELP","HELP"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "promptopskit",
3
- "version": "0.2.3",
3
+ "version": "0.2.4",
4
4
  "description": "Manage prompts, system instructions, tools, and model settings as code",
5
5
  "type": "module",
6
6
  "bin": {
@@ -72,7 +72,8 @@
72
72
  }
73
73
  },
74
74
  "files": [
75
- "dist"
75
+ "dist",
76
+ "SKILL.md"
76
77
  ],
77
78
  "scripts": {
78
79
  "build": "tsup",