promptopskit 0.3.3 → 0.3.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 +3 -3
- package/SKILL.md +8 -8
- package/dist/cli/index.js +36 -16
- package/dist/cli/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -187,7 +187,7 @@ Direct adapter rendering also accepts `environment` and `tier` selectors. This i
|
|
|
187
187
|
```typescript
|
|
188
188
|
import type { ResolvedPromptAsset } from 'promptopskit';
|
|
189
189
|
import { openaiAdapter } from 'promptopskit/openai';
|
|
190
|
-
import compiledPrompt from '
|
|
190
|
+
import compiledPrompt from './.generated-prompts/esm/summarizePullRequest.mjs';
|
|
191
191
|
|
|
192
192
|
const prompt = compiledPrompt as ResolvedPromptAsset;
|
|
193
193
|
|
|
@@ -217,7 +217,7 @@ const request = await openaiAdapter.renderPrompt(
|
|
|
217
217
|
{
|
|
218
218
|
path: 'summarizePullRequest',
|
|
219
219
|
sourceDir: path.join(process.cwd(), 'prompts'),
|
|
220
|
-
compiledDir: path.join(process.cwd(), '
|
|
220
|
+
compiledDir: path.join(process.cwd(), '.generated-prompts', 'json'),
|
|
221
221
|
},
|
|
222
222
|
{
|
|
223
223
|
environment: 'dev',
|
|
@@ -386,7 +386,7 @@ promptopskit skill
|
|
|
386
386
|
promptopskit validate <dir> [--strict]
|
|
387
387
|
|
|
388
388
|
# Compile .md → JSON/ESM artifacts
|
|
389
|
-
promptopskit compile
|
|
389
|
+
promptopskit compile [src] [out] [--dry-run] [--format json|esm] [--no-clean]
|
|
390
390
|
|
|
391
391
|
# Render a prompt preview (auto-loads .test.yaml sidecar)
|
|
392
392
|
promptopskit render <file> [--env <name>] [--tier <name>] [--vars <file>] [--json]
|
package/SKILL.md
CHANGED
|
@@ -258,7 +258,7 @@ import { createPromptOpsKit } from 'promptopskit';
|
|
|
258
258
|
|
|
259
259
|
const kit = createPromptOpsKit({
|
|
260
260
|
sourceDir: './prompts',
|
|
261
|
-
compiledDir: '
|
|
261
|
+
compiledDir: './.generated-prompts/json',
|
|
262
262
|
warnings: {
|
|
263
263
|
contextSize: process.env.NODE_ENV === 'production' ? 'off' : 'console-and-result',
|
|
264
264
|
},
|
|
@@ -289,7 +289,7 @@ const request = await openaiAdapter.renderPrompt(
|
|
|
289
289
|
{
|
|
290
290
|
path: 'support/reply',
|
|
291
291
|
sourceDir: path.join(process.cwd(), 'prompts'),
|
|
292
|
-
compiledDir: path.join(process.cwd(), '
|
|
292
|
+
compiledDir: path.join(process.cwd(), '.generated-prompts', 'json'),
|
|
293
293
|
},
|
|
294
294
|
{
|
|
295
295
|
environment: 'production',
|
|
@@ -311,7 +311,7 @@ const request = await openaiAdapter.renderPrompt(
|
|
|
311
311
|
```typescript
|
|
312
312
|
import type { ResolvedPromptAsset } from 'promptopskit';
|
|
313
313
|
import { openaiAdapter } from 'promptopskit/openai';
|
|
314
|
-
import compiledPrompt from '
|
|
314
|
+
import compiledPrompt from './.generated-prompts/esm/support/reply.mjs';
|
|
315
315
|
|
|
316
316
|
const prompt = compiledPrompt as ResolvedPromptAsset;
|
|
317
317
|
|
|
@@ -344,13 +344,13 @@ Prompts should usually be validated and compiled as part of the normal build pip
|
|
|
344
344
|
{
|
|
345
345
|
"scripts": {
|
|
346
346
|
"validate:prompts": "promptopskit validate ./prompts --strict",
|
|
347
|
-
"build:prompts": "promptopskit compile
|
|
347
|
+
"build:prompts": "promptopskit compile",
|
|
348
348
|
"build": "npm run validate:prompts && npm run build:prompts && tsup"
|
|
349
349
|
}
|
|
350
350
|
}
|
|
351
351
|
```
|
|
352
352
|
|
|
353
|
-
|
|
353
|
+
`promptopskit compile` defaults to JSON output in `./.generated-prompts/json`, which matches runtime `compiledDir` loading. Use `promptopskit compile --format esm` when prompts need to be imported into a bundle; those artifacts default to `./.generated-prompts/esm`.
|
|
354
354
|
|
|
355
355
|
### Build strategy by environment
|
|
356
356
|
|
|
@@ -362,7 +362,7 @@ Use `--format json` for server-side Node usage where prompts are loaded from dis
|
|
|
362
362
|
|
|
363
363
|
- Add `validate:prompts` before `build:prompts` so schema or variable mistakes fail fast
|
|
364
364
|
- Treat compiled artifacts as build outputs, not the source of truth
|
|
365
|
-
- Keep prompt source in `./prompts`
|
|
365
|
+
- Keep prompt source in `./prompts`; use `./.generated-prompts/json` as the default server output and `./.generated-prompts/esm` for imported client artifacts unless a project-specific build layout needs something else
|
|
366
366
|
- If using `createPromptOpsKit` in `auto` mode, point both `sourceDir` and `compiledDir` at those directories so local development can fall back to source when artifacts are stale or missing
|
|
367
367
|
|
|
368
368
|
### Typical server-side setup
|
|
@@ -372,7 +372,7 @@ import { createPromptOpsKit } from 'promptopskit';
|
|
|
372
372
|
|
|
373
373
|
export const prompts = createPromptOpsKit({
|
|
374
374
|
sourceDir: './prompts',
|
|
375
|
-
compiledDir: '
|
|
375
|
+
compiledDir: './.generated-prompts/json',
|
|
376
376
|
mode: 'auto',
|
|
377
377
|
});
|
|
378
378
|
```
|
|
@@ -432,7 +432,7 @@ Hello {{ name }}
|
|
|
432
432
|
|---------|-------------|
|
|
433
433
|
| `promptopskit init [dir]` | Scaffold a prompts directory with starter files (including `defaults.md`) |
|
|
434
434
|
| `promptopskit validate <dir>` | Validate all prompt files in a directory |
|
|
435
|
-
| `promptopskit compile
|
|
435
|
+
| `promptopskit compile [src] [out]` | Compile `.md` prompts to JSON or ESM artifacts |
|
|
436
436
|
| `promptopskit render <file>` | Render a prompt preview |
|
|
437
437
|
| `promptopskit inspect <file>` | Print the normalized prompt asset |
|
|
438
438
|
|
package/dist/cli/index.js
CHANGED
|
@@ -569,11 +569,13 @@ async function collectPromptFiles(dir) {
|
|
|
569
569
|
import { readdir as readdir2, writeFile, mkdir, rm } from "fs/promises";
|
|
570
570
|
import { join as join3, extname as extname2, relative, dirname as dirname3 } from "path";
|
|
571
571
|
var HELP2 = `
|
|
572
|
-
promptopskit compile
|
|
572
|
+
promptopskit compile [sourceDir] [outputDir] [options]
|
|
573
573
|
|
|
574
|
-
Compile .md prompt files to JSON artifacts.
|
|
574
|
+
Compile .md prompt files to JSON or ESM artifacts.
|
|
575
575
|
|
|
576
576
|
Options:
|
|
577
|
+
--source, -s Source directory (default: ./prompts)
|
|
578
|
+
--output, -o Output directory (default: ./.generated-prompts/<format>)
|
|
577
579
|
--no-clean Don't clear the output directory before compiling
|
|
578
580
|
--dry-run Show what would be compiled without writing files
|
|
579
581
|
--format Output format: json (default) or esm
|
|
@@ -584,14 +586,7 @@ async function compile(args) {
|
|
|
584
586
|
console.log(HELP2);
|
|
585
587
|
return;
|
|
586
588
|
}
|
|
587
|
-
const positional = args
|
|
588
|
-
const sourceDir = positional[0];
|
|
589
|
-
const outputDir = positional[1];
|
|
590
|
-
if (!sourceDir || !outputDir) {
|
|
591
|
-
console.error("Error: Please provide source and output directories.");
|
|
592
|
-
console.error("Usage: promptopskit compile <sourceDir> <outputDir>");
|
|
593
|
-
process.exit(1);
|
|
594
|
-
}
|
|
589
|
+
const positional = getPositionalArgs(args, /* @__PURE__ */ new Set(["--format", "--source", "--output", "-s", "-o"]));
|
|
595
590
|
const dryRun = args.includes("--dry-run");
|
|
596
591
|
const noClean = args.includes("--no-clean");
|
|
597
592
|
const format = getFlag(args, "--format") ?? "json";
|
|
@@ -599,6 +594,8 @@ async function compile(args) {
|
|
|
599
594
|
console.error(`Error: Unknown format "${format}". Use "json" or "esm".`);
|
|
600
595
|
process.exit(1);
|
|
601
596
|
}
|
|
597
|
+
const sourceDir = getFlag(args, "--source", "-s") ?? positional[0] ?? "./prompts";
|
|
598
|
+
const outputDir = getFlag(args, "--output", "-o") ?? positional[1] ?? defaultOutputDirForFormat(format);
|
|
602
599
|
const files = await collectPromptFiles2(sourceDir);
|
|
603
600
|
if (files.length === 0) {
|
|
604
601
|
console.log(`No .md prompt files found in ${sourceDir}`);
|
|
@@ -647,10 +644,30 @@ async function compile(args) {
|
|
|
647
644
|
process.exit(1);
|
|
648
645
|
}
|
|
649
646
|
}
|
|
650
|
-
function
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
647
|
+
function defaultOutputDirForFormat(format) {
|
|
648
|
+
return format === "esm" ? "./.generated-prompts/esm" : "./.generated-prompts/json";
|
|
649
|
+
}
|
|
650
|
+
function getPositionalArgs(args, flagsWithValues) {
|
|
651
|
+
const positional = [];
|
|
652
|
+
for (let index = 0; index < args.length; index++) {
|
|
653
|
+
const arg = args[index];
|
|
654
|
+
if (flagsWithValues.has(arg)) {
|
|
655
|
+
index++;
|
|
656
|
+
continue;
|
|
657
|
+
}
|
|
658
|
+
if (arg.startsWith("-")) {
|
|
659
|
+
continue;
|
|
660
|
+
}
|
|
661
|
+
positional.push(arg);
|
|
662
|
+
}
|
|
663
|
+
return positional;
|
|
664
|
+
}
|
|
665
|
+
function getFlag(args, ...flags) {
|
|
666
|
+
for (const flag of flags) {
|
|
667
|
+
const idx = args.indexOf(flag);
|
|
668
|
+
if (idx >= 0 && idx + 1 < args.length) {
|
|
669
|
+
return args[idx + 1];
|
|
670
|
+
}
|
|
654
671
|
}
|
|
655
672
|
return void 0;
|
|
656
673
|
}
|
|
@@ -848,6 +865,9 @@ promptopskit init [dir]
|
|
|
848
865
|
|
|
849
866
|
Scaffold a prompts directory with starter files.
|
|
850
867
|
|
|
868
|
+
Arguments:
|
|
869
|
+
dir Target directory (default: ./prompts)
|
|
870
|
+
|
|
851
871
|
Options:
|
|
852
872
|
--help, -h Show this help
|
|
853
873
|
`.trim();
|
|
@@ -1008,7 +1028,7 @@ async function init(args) {
|
|
|
1008
1028
|
if (!pkg.scripts?.["build:prompts"]) {
|
|
1009
1029
|
console.log();
|
|
1010
1030
|
console.log(`Tip: Add to your package.json scripts:`);
|
|
1011
|
-
console.log(` "build:prompts": "promptopskit compile ${dir}
|
|
1031
|
+
console.log(` "build:prompts": "promptopskit compile ${dir}"`);
|
|
1012
1032
|
}
|
|
1013
1033
|
} catch {
|
|
1014
1034
|
}
|
|
@@ -1169,7 +1189,7 @@ Usage:
|
|
|
1169
1189
|
Commands:
|
|
1170
1190
|
init [dir] Scaffold a prompts directory with starter files
|
|
1171
1191
|
validate <dir> Validate prompt files
|
|
1172
|
-
compile
|
|
1192
|
+
compile [src] [out] [options] Compile .md prompts to JSON/ESM artifacts
|
|
1173
1193
|
render <file> [options] Render a prompt preview
|
|
1174
1194
|
inspect <file> Print normalized prompt asset
|
|
1175
1195
|
skill [options] Deploy AI agent instructions into your project
|
package/dist/cli/index.js.map
CHANGED
|
@@ -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/context.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/defaults-root.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 ContextInputDefinitionObjectSchema = z.object({\n name: z.string(),\n max_size: z.number().int().positive().optional(),\n});\n\nexport const ContextInputDefinitionSchema = z.union([\n z.string(),\n ContextInputDefinitionObjectSchema,\n]);\n\nexport type ContextInputDefinition = z.infer<typeof ContextInputDefinitionSchema>;\n\nexport const ContextSchema = z.object({\n inputs: z.array(ContextInputDefinitionSchema).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","import type { PromptAsset, ResolvedPromptAsset, ContextInputDefinition } from './schema/index.js';\n\nexport interface NormalizedContextInput {\n name: string;\n max_size?: number;\n}\n\nexport interface ContextSizeWarning {\n variable: string;\n maxSize: number;\n actualSize: number;\n}\n\nconst textEncoder = new TextEncoder();\n\nexport function getContextInputs(\n asset: Pick<PromptAsset | ResolvedPromptAsset, 'context'>,\n): NormalizedContextInput[] {\n return (asset.context?.inputs ?? []).map(normalizeContextInput);\n}\n\nexport function getContextInputNames(\n asset: Pick<PromptAsset | ResolvedPromptAsset, 'context'>,\n): string[] {\n return getContextInputs(asset).map((input) => input.name);\n}\n\nexport function normalizeContextInput(input: ContextInputDefinition): NormalizedContextInput {\n if (typeof input === 'string') {\n return { name: input };\n }\n\n return {\n name: input.name,\n max_size: input.max_size,\n };\n}\n\nexport function measureContextValueSize(value: string): number {\n return textEncoder.encode(value).length;\n}\n\nexport function collectContextSizeWarnings(\n asset: Pick<PromptAsset | ResolvedPromptAsset, 'context'>,\n variables: Record<string, string> = {},\n): ContextSizeWarning[] {\n const warnings: ContextSizeWarning[] = [];\n\n for (const input of getContextInputs(asset)) {\n if (input.max_size === undefined) {\n continue;\n }\n\n const value = variables[input.name];\n if (value === undefined) {\n continue;\n }\n\n const actualSize = measureContextValueSize(value);\n if (actualSize > input.max_size) {\n warnings.push({\n variable: input.name,\n maxSize: input.max_size,\n actualSize,\n });\n }\n }\n\n return warnings;\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 { getContextInputNames } from '../context.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(getContextInputNames(asset));\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.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';\nimport { findDefaultsRoot } from './defaults-root.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 defaultsRoot = findDefaultsRoot(file);\n const { asset: parsed } = await loadPromptFile(file, { defaultsRoot });\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 { existsSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\n\nexport function findDefaultsRoot(filePath: string): string {\n let current = resolve(dirname(filePath));\n let root = current;\n let foundDefaults = false;\n\n while (true) {\n if (existsSync(join(current, 'defaults.md'))) {\n root = current;\n foundDefaults = true;\n } else if (foundDefaults) {\n return root;\n }\n\n const parent = dirname(current);\n if (parent === current) {\n return root;\n }\n\n current = parent;\n }\n}","import { loadPromptFile } from '../../parser/index.js';\nimport { resolveIncludes } from '../../composition/index.js';\nimport { findDefaultsRoot } from './defaults-root.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 defaultsRoot = findDefaultsRoot(file);\n const { asset: parsed } = await loadPromptFile(file, { defaultsRoot });\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 /*\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.\n Current app context: Welcome screen.\n\n Always 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\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,M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;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","existsSync","dirname","join","resolve","HELP","getFlag","readFile","existsSync","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/context.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/defaults-root.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 ContextInputDefinitionObjectSchema = z.object({\n name: z.string(),\n max_size: z.number().int().positive().optional(),\n});\n\nexport const ContextInputDefinitionSchema = z.union([\n z.string(),\n ContextInputDefinitionObjectSchema,\n]);\n\nexport type ContextInputDefinition = z.infer<typeof ContextInputDefinitionSchema>;\n\nexport const ContextSchema = z.object({\n inputs: z.array(ContextInputDefinitionSchema).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","import type { PromptAsset, ResolvedPromptAsset, ContextInputDefinition } from './schema/index.js';\n\nexport interface NormalizedContextInput {\n name: string;\n max_size?: number;\n}\n\nexport interface ContextSizeWarning {\n variable: string;\n maxSize: number;\n actualSize: number;\n}\n\nconst textEncoder = new TextEncoder();\n\nexport function getContextInputs(\n asset: Pick<PromptAsset | ResolvedPromptAsset, 'context'>,\n): NormalizedContextInput[] {\n return (asset.context?.inputs ?? []).map(normalizeContextInput);\n}\n\nexport function getContextInputNames(\n asset: Pick<PromptAsset | ResolvedPromptAsset, 'context'>,\n): string[] {\n return getContextInputs(asset).map((input) => input.name);\n}\n\nexport function normalizeContextInput(input: ContextInputDefinition): NormalizedContextInput {\n if (typeof input === 'string') {\n return { name: input };\n }\n\n return {\n name: input.name,\n max_size: input.max_size,\n };\n}\n\nexport function measureContextValueSize(value: string): number {\n return textEncoder.encode(value).length;\n}\n\nexport function collectContextSizeWarnings(\n asset: Pick<PromptAsset | ResolvedPromptAsset, 'context'>,\n variables: Record<string, string> = {},\n): ContextSizeWarning[] {\n const warnings: ContextSizeWarning[] = [];\n\n for (const input of getContextInputs(asset)) {\n if (input.max_size === undefined) {\n continue;\n }\n\n const value = variables[input.name];\n if (value === undefined) {\n continue;\n }\n\n const actualSize = measureContextValueSize(value);\n if (actualSize > input.max_size) {\n warnings.push({\n variable: input.name,\n maxSize: input.max_size,\n actualSize,\n });\n }\n }\n\n return warnings;\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 { getContextInputNames } from '../context.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(getContextInputNames(asset));\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.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 or ESM artifacts.\n\nOptions:\n --source, -s Source directory (default: ./prompts)\n --output, -o Output directory (default: ./.generated-prompts/<format>)\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 = getPositionalArgs(args, new Set(['--format', '--source', '--output', '-s', '-o']));\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 const sourceDir = getFlag(args, '--source', '-s') ?? positional[0] ?? './prompts';\n const outputDir = getFlag(args, '--output', '-o') ?? positional[1] ?? defaultOutputDirForFormat(format);\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 defaultOutputDirForFormat(format: 'json' | 'esm'): string {\n return format === 'esm' ? './.generated-prompts/esm' : './.generated-prompts/json';\n}\n\nfunction getPositionalArgs(args: string[], flagsWithValues: Set<string>): string[] {\n const positional: string[] = [];\n\n for (let index = 0; index < args.length; index++) {\n const arg = args[index];\n if (flagsWithValues.has(arg)) {\n index++;\n continue;\n }\n\n if (arg.startsWith('-')) {\n continue;\n }\n\n positional.push(arg);\n }\n\n return positional;\n}\n\nfunction getFlag(args: string[], ...flags: string[]): string | undefined {\n for (const flag of flags) {\n const idx = args.indexOf(flag);\n if (idx >= 0 && idx + 1 < args.length) {\n return args[idx + 1];\n }\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';\nimport { findDefaultsRoot } from './defaults-root.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 defaultsRoot = findDefaultsRoot(file);\n const { asset: parsed } = await loadPromptFile(file, { defaultsRoot });\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 { existsSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\n\nexport function findDefaultsRoot(filePath: string): string {\n let current = resolve(dirname(filePath));\n let root = current;\n let foundDefaults = false;\n\n while (true) {\n if (existsSync(join(current, 'defaults.md'))) {\n root = current;\n foundDefaults = true;\n } else if (foundDefaults) {\n return root;\n }\n\n const parent = dirname(current);\n if (parent === current) {\n return root;\n }\n\n current = parent;\n }\n}","import { loadPromptFile } from '../../parser/index.js';\nimport { resolveIncludes } from '../../composition/index.js';\nimport { findDefaultsRoot } from './defaults-root.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 defaultsRoot = findDefaultsRoot(file);\n const { asset: parsed } = await loadPromptFile(file, { defaultsRoot });\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\nArguments:\n dir Target directory (default: ./prompts)\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 /*\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.\n Current app context: Welcome screen.\n\n Always 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\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}\"`);\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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E,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","existsSync","dirname","join","resolve","HELP","getFlag","readFile","existsSync","parsed","HELP","writeFile","mkdir","join","dirname","existsSync","HELP","writeFile","readFile","mkdir","dirname","existsSync","HELP","HELP"]}
|