promptopskit 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +88 -15
  2. package/dist/{chunk-X64JII57.js → chunk-HMYPMHTG.js} +91 -4
  3. package/dist/chunk-HMYPMHTG.js.map +1 -0
  4. package/dist/cli/index.js +593 -35
  5. package/dist/cli/index.js.map +1 -1
  6. package/dist/index.cjs +1049 -0
  7. package/dist/index.cjs.map +1 -0
  8. package/dist/index.d.cts +191 -0
  9. package/dist/index.d.ts +18 -6
  10. package/dist/index.js +28 -4
  11. package/dist/index.js.map +1 -1
  12. package/dist/providers/anthropic.cjs +151 -0
  13. package/dist/providers/anthropic.cjs.map +1 -0
  14. package/dist/providers/anthropic.d.cts +11 -0
  15. package/dist/providers/anthropic.d.ts +2 -2
  16. package/dist/providers/gemini.cjs +155 -0
  17. package/dist/providers/gemini.cjs.map +1 -0
  18. package/dist/providers/gemini.d.cts +11 -0
  19. package/dist/providers/gemini.d.ts +2 -2
  20. package/dist/providers/openai.cjs +146 -0
  21. package/dist/providers/openai.cjs.map +1 -0
  22. package/dist/providers/openai.d.cts +11 -0
  23. package/dist/providers/openai.d.ts +2 -2
  24. package/dist/providers/openrouter.cjs +161 -0
  25. package/dist/providers/openrouter.cjs.map +1 -0
  26. package/dist/providers/openrouter.d.cts +13 -0
  27. package/dist/providers/openrouter.d.ts +2 -2
  28. package/dist/{schema-DHRI5Mzl.d.ts → schema-C6smABrt.d.cts} +3 -3
  29. package/dist/schema-C6smABrt.d.ts +695 -0
  30. package/dist/testing.cjs +236 -0
  31. package/dist/testing.cjs.map +1 -0
  32. package/dist/testing.d.cts +17 -0
  33. package/dist/testing.d.ts +1 -1
  34. package/dist/testing.js +1 -1
  35. package/dist/{types-D9hquVja.d.ts → types-D7lW5IYT.d.ts} +1 -1
  36. package/dist/types-S_c-ZEfK.d.cts +40 -0
  37. package/package.json +54 -16
  38. package/dist/chunk-X64JII57.js.map +0 -1
package/dist/index.cjs ADDED
@@ -0,0 +1,1049 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var src_exports = {};
32
+ __export(src_exports, {
33
+ PromptAssetOverridesSchema: () => PromptAssetOverridesSchema,
34
+ PromptAssetSchema: () => PromptAssetSchema,
35
+ PromptOpsKit: () => PromptOpsKit,
36
+ anthropicAdapter: () => anthropicAdapter,
37
+ applyOverrides: () => applyOverrides,
38
+ createPromptOpsKit: () => createPromptOpsKit,
39
+ extractSections: () => extractSections,
40
+ extractVariables: () => extractVariables,
41
+ geminiAdapter: () => geminiAdapter,
42
+ getAdapter: () => getAdapter,
43
+ interpolate: () => interpolate,
44
+ loadPromptFile: () => loadPromptFile,
45
+ openaiAdapter: () => openaiAdapter,
46
+ openrouterAdapter: () => openrouterAdapter,
47
+ parsePrompt: () => parsePrompt,
48
+ renderPrompt: () => renderPrompt,
49
+ resolveIncludes: () => resolveIncludes,
50
+ validateAsset: () => validateAsset,
51
+ validateAssetWithIncludes: () => validateAssetWithIncludes
52
+ });
53
+ module.exports = __toCommonJS(src_exports);
54
+ var import_promises3 = require("fs/promises");
55
+ var import_node_fs2 = require("fs");
56
+ var import_node_path3 = require("path");
57
+
58
+ // src/parser/parser.ts
59
+ var import_gray_matter = __toESM(require("gray-matter"), 1);
60
+
61
+ // src/schema/schema.ts
62
+ var import_zod = require("zod");
63
+ var InlineToolDefSchema = import_zod.z.object({
64
+ name: import_zod.z.string(),
65
+ description: import_zod.z.string().optional(),
66
+ input_schema: import_zod.z.record(import_zod.z.unknown()).optional()
67
+ });
68
+ var ToolRefSchema = import_zod.z.union([import_zod.z.string(), InlineToolDefSchema]);
69
+ var MCPServerRefSchema = import_zod.z.union([
70
+ import_zod.z.string(),
71
+ import_zod.z.object({
72
+ name: import_zod.z.string(),
73
+ config: import_zod.z.record(import_zod.z.unknown()).optional()
74
+ })
75
+ ]);
76
+ var ReasoningSchema = import_zod.z.object({
77
+ effort: import_zod.z.enum(["low", "medium", "high"]).optional(),
78
+ budget_tokens: import_zod.z.number().int().positive().optional()
79
+ });
80
+ var SamplingSchema = import_zod.z.object({
81
+ temperature: import_zod.z.number().min(0).max(2).optional(),
82
+ top_p: import_zod.z.number().min(0).max(1).optional(),
83
+ frequency_penalty: import_zod.z.number().optional(),
84
+ presence_penalty: import_zod.z.number().optional(),
85
+ stop: import_zod.z.array(import_zod.z.string()).optional(),
86
+ max_output_tokens: import_zod.z.number().int().positive().optional()
87
+ });
88
+ var ResponseSchema = import_zod.z.object({
89
+ format: import_zod.z.enum(["text", "json", "markdown"]).optional(),
90
+ stream: import_zod.z.boolean().optional()
91
+ });
92
+ var HistorySchema = import_zod.z.object({
93
+ max_items: import_zod.z.number().int().positive().optional()
94
+ });
95
+ var ContextSchema = import_zod.z.object({
96
+ inputs: import_zod.z.array(import_zod.z.string()).optional(),
97
+ history: HistorySchema.optional()
98
+ });
99
+ var MetadataSchema = import_zod.z.object({
100
+ owner: import_zod.z.string().optional(),
101
+ tags: import_zod.z.array(import_zod.z.string()).optional(),
102
+ review_required: import_zod.z.boolean().optional(),
103
+ stable: import_zod.z.boolean().optional()
104
+ });
105
+ var MCPSchema = import_zod.z.object({
106
+ servers: import_zod.z.array(MCPServerRefSchema).optional()
107
+ });
108
+ var PromptAssetOverridesSchema = import_zod.z.object({
109
+ model: import_zod.z.string().optional(),
110
+ fallback_models: import_zod.z.array(import_zod.z.string()).optional(),
111
+ reasoning: ReasoningSchema.optional(),
112
+ sampling: SamplingSchema.optional(),
113
+ response: ResponseSchema.optional(),
114
+ tools: import_zod.z.array(ToolRefSchema).optional()
115
+ });
116
+ var SourceSchema = import_zod.z.object({
117
+ file_path: import_zod.z.string().optional(),
118
+ checksum: import_zod.z.string().optional()
119
+ });
120
+ var SectionsSchema = import_zod.z.object({
121
+ system_instructions: import_zod.z.string().optional(),
122
+ prompt_template: import_zod.z.string().optional(),
123
+ notes: import_zod.z.string().optional()
124
+ });
125
+ var PromptDefaultsSchema = import_zod.z.object({
126
+ metadata: MetadataSchema.optional(),
127
+ sections: import_zod.z.object({
128
+ system_instructions: import_zod.z.string().optional()
129
+ }).optional()
130
+ });
131
+ var PromptAssetSchema = import_zod.z.object({
132
+ id: import_zod.z.string(),
133
+ schema_version: import_zod.z.number().int().positive().default(1),
134
+ description: import_zod.z.string().optional(),
135
+ provider: import_zod.z.enum(["openai", "anthropic", "google", "gemini", "openrouter", "any"]).optional(),
136
+ model: import_zod.z.string().optional(),
137
+ fallback_models: import_zod.z.array(import_zod.z.string()).optional(),
138
+ reasoning: ReasoningSchema.optional(),
139
+ sampling: SamplingSchema.optional(),
140
+ response: ResponseSchema.optional(),
141
+ tools: import_zod.z.array(ToolRefSchema).optional(),
142
+ mcp: MCPSchema.optional(),
143
+ context: ContextSchema.optional(),
144
+ includes: import_zod.z.array(import_zod.z.string()).optional(),
145
+ environments: import_zod.z.record(PromptAssetOverridesSchema).optional(),
146
+ tiers: import_zod.z.record(PromptAssetOverridesSchema).optional(),
147
+ metadata: MetadataSchema.optional(),
148
+ // Populated by parser, not authored in YAML
149
+ sections: SectionsSchema.optional(),
150
+ source: SourceSchema.optional()
151
+ });
152
+
153
+ // src/parser/sections.ts
154
+ var SECTION_MAP = {
155
+ "system instructions": "system_instructions",
156
+ "prompt template": "prompt_template",
157
+ "notes": "notes"
158
+ };
159
+ function extractSections(body) {
160
+ const lines = body.split("\n");
161
+ const sections = {};
162
+ let currentKey = null;
163
+ let currentLines = [];
164
+ let foundAnyH1 = false;
165
+ for (const line of lines) {
166
+ const h1Match = line.match(/^#\s+(.+)$/);
167
+ if (h1Match) {
168
+ if (currentKey) {
169
+ sections[currentKey] = currentLines.join("\n").trim();
170
+ }
171
+ foundAnyH1 = true;
172
+ const heading = h1Match[1].trim().toLowerCase();
173
+ currentKey = SECTION_MAP[heading] ?? null;
174
+ currentLines = [];
175
+ } else {
176
+ currentLines.push(line);
177
+ }
178
+ }
179
+ if (currentKey) {
180
+ sections[currentKey] = currentLines.join("\n").trim();
181
+ }
182
+ if (!foundAnyH1) {
183
+ const trimmed = body.trim();
184
+ if (trimmed) {
185
+ sections.prompt_template = trimmed;
186
+ }
187
+ }
188
+ return sections;
189
+ }
190
+
191
+ // src/parser/parser.ts
192
+ function parsePrompt(content, filePath) {
193
+ const { data: frontMatter, content: body } = (0, import_gray_matter.default)(content);
194
+ const sections = extractSections(body);
195
+ const raw = {
196
+ ...frontMatter,
197
+ sections,
198
+ source: filePath ? { file_path: filePath } : void 0
199
+ };
200
+ const asset = PromptAssetSchema.parse(raw);
201
+ return {
202
+ asset,
203
+ raw: {
204
+ frontMatter,
205
+ body
206
+ }
207
+ };
208
+ }
209
+
210
+ // src/parser/loader.ts
211
+ var import_promises = require("fs/promises");
212
+ var import_node_path = require("path");
213
+ var import_gray_matter2 = __toESM(require("gray-matter"), 1);
214
+ var DEFAULTS_FILE_NAME = "defaults.md";
215
+ async function loadPromptFile(filePath, options = {}) {
216
+ const content = await (0, import_promises.readFile)(filePath, "utf-8");
217
+ const parsed = parsePrompt(content, filePath);
218
+ const root = options.defaultsRoot ?? (0, import_node_path.dirname)(filePath);
219
+ const defaults = await loadDefaultsForPath(filePath, root);
220
+ const asset = applyDefaults(parsed.asset, defaults);
221
+ return {
222
+ ...parsed,
223
+ asset
224
+ };
225
+ }
226
+ async function loadDefaultsForPath(filePath, defaultsRoot) {
227
+ const directories = getDirectoriesToCheck(filePath, defaultsRoot);
228
+ let merged = {};
229
+ for (const dir of directories) {
230
+ const defaultsPath = (0, import_node_path.join)(dir, DEFAULTS_FILE_NAME);
231
+ try {
232
+ const defaultsContent = await (0, import_promises.readFile)(defaultsPath, "utf-8");
233
+ const defaults = parseDefaults(defaultsContent);
234
+ merged = mergeDefaults(merged, defaults);
235
+ } catch (error) {
236
+ if (error.code !== "ENOENT") {
237
+ throw error;
238
+ }
239
+ }
240
+ }
241
+ return merged;
242
+ }
243
+ function getDirectoriesToCheck(filePath, defaultsRoot) {
244
+ const dirs = [];
245
+ let current = (0, import_node_path.resolve)((0, import_node_path.dirname)(filePath));
246
+ const boundary = defaultsRoot ? (0, import_node_path.resolve)(defaultsRoot) : void 0;
247
+ while (true) {
248
+ dirs.unshift(current);
249
+ if (boundary && current === boundary || current === (0, import_node_path.dirname)(current)) {
250
+ break;
251
+ }
252
+ current = (0, import_node_path.dirname)(current);
253
+ }
254
+ return dirs;
255
+ }
256
+ function parseDefaults(content) {
257
+ const { data: frontMatter, content: body } = (0, import_gray_matter2.default)(content);
258
+ const sections = extractSections(body);
259
+ return PromptDefaultsSchema.parse({
260
+ ...frontMatter,
261
+ sections: {
262
+ system_instructions: sections.system_instructions
263
+ }
264
+ });
265
+ }
266
+ function mergeDefaults(base, local) {
267
+ return {
268
+ metadata: {
269
+ ...base.metadata ?? {},
270
+ ...local.metadata ?? {}
271
+ },
272
+ sections: {
273
+ ...base.sections ?? {},
274
+ ...local.sections ?? {}
275
+ }
276
+ };
277
+ }
278
+ function applyDefaults(asset, defaults) {
279
+ const hasDefaultMetadata = defaults.metadata && Object.keys(defaults.metadata).length > 0;
280
+ const hasDefaultSystem = !!defaults.sections?.system_instructions;
281
+ if (!hasDefaultMetadata && !hasDefaultSystem) {
282
+ return asset;
283
+ }
284
+ const mergedMetadata = {
285
+ ...defaults.metadata ?? {},
286
+ ...asset.metadata ?? {}
287
+ };
288
+ const metadata = Object.keys(mergedMetadata).length > 0 ? mergedMetadata : void 0;
289
+ const systemInstructions = asset.sections?.system_instructions ?? defaults.sections?.system_instructions;
290
+ const sections = asset.sections ? { ...asset.sections, system_instructions: systemInstructions } : systemInstructions ? { system_instructions: systemInstructions } : void 0;
291
+ return {
292
+ ...asset,
293
+ metadata,
294
+ sections
295
+ };
296
+ }
297
+
298
+ // src/composition/resolve-includes.ts
299
+ var import_promises2 = require("fs/promises");
300
+ var import_node_path2 = require("path");
301
+ async function resolveIncludes(asset, basePath, visited = /* @__PURE__ */ new Set()) {
302
+ if (!asset.includes || asset.includes.length === 0) {
303
+ return asset;
304
+ }
305
+ const baseDir = (0, import_node_path2.dirname)(basePath);
306
+ const resolvedPath = (0, import_node_path2.resolve)(basePath);
307
+ if (visited.has(resolvedPath)) {
308
+ throw new Error(`Circular include detected: ${resolvedPath}`);
309
+ }
310
+ visited.add(resolvedPath);
311
+ let mergedSystemInstructions = "";
312
+ for (const includePath of asset.includes) {
313
+ const fullPath = (0, import_node_path2.resolve)(baseDir, includePath);
314
+ if (visited.has(fullPath)) {
315
+ throw new Error(`Circular include detected: ${fullPath} (included from ${basePath})`);
316
+ }
317
+ const content = await (0, import_promises2.readFile)(fullPath, "utf-8");
318
+ const { asset: includedAsset } = parsePrompt(content, fullPath);
319
+ const resolved = await resolveIncludes(includedAsset, fullPath, new Set(visited));
320
+ if (resolved.sections?.system_instructions) {
321
+ mergedSystemInstructions += resolved.sections.system_instructions + "\n\n";
322
+ }
323
+ }
324
+ const localSystem = asset.sections?.system_instructions ?? "";
325
+ const combinedSystem = (mergedSystemInstructions + localSystem).trim() || void 0;
326
+ return {
327
+ ...asset,
328
+ sections: {
329
+ ...asset.sections,
330
+ system_instructions: combinedSystem
331
+ },
332
+ // Drop includes from the resolved asset — they've been inlined
333
+ includes: void 0
334
+ };
335
+ }
336
+
337
+ // src/overrides/apply-overrides.ts
338
+ function applyOverrides(asset, options = {}) {
339
+ let result = { ...asset };
340
+ if (options.environment && result.environments?.[options.environment]) {
341
+ result = mergeOverride(result, result.environments[options.environment]);
342
+ }
343
+ if (options.tier && result.tiers?.[options.tier]) {
344
+ result = mergeOverride(result, result.tiers[options.tier]);
345
+ }
346
+ if (options.runtime) {
347
+ result = mergeOverride(result, options.runtime);
348
+ }
349
+ return result;
350
+ }
351
+ function mergeOverride(base, override) {
352
+ const result = { ...base };
353
+ if (override.model !== void 0) result.model = override.model;
354
+ if (override.fallback_models !== void 0) result.fallback_models = override.fallback_models;
355
+ if (override.tools !== void 0) result.tools = override.tools;
356
+ if (override.reasoning !== void 0) {
357
+ result.reasoning = { ...result.reasoning, ...override.reasoning };
358
+ }
359
+ if (override.sampling !== void 0) {
360
+ result.sampling = { ...result.sampling, ...override.sampling };
361
+ }
362
+ if (override.response !== void 0) {
363
+ result.response = { ...result.response, ...override.response };
364
+ }
365
+ return result;
366
+ }
367
+
368
+ // src/renderer/interpolate.ts
369
+ var VARIABLE_RE = /\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}/g;
370
+ var ESCAPED_OPEN = /\\\{\\\{/g;
371
+ var ESCAPE_PLACEHOLDER = "\0ESCAPED_OPEN\0";
372
+ function interpolate(template, variables, options = {}) {
373
+ const { strict = false } = options;
374
+ let result = template.replace(ESCAPED_OPEN, ESCAPE_PLACEHOLDER);
375
+ result = result.replace(VARIABLE_RE, (match, name) => {
376
+ if (name in variables) {
377
+ return variables[name];
378
+ }
379
+ if (strict) {
380
+ throw new Error(`Missing required variable: "${name}"`);
381
+ }
382
+ return match;
383
+ });
384
+ result = result.replaceAll(ESCAPE_PLACEHOLDER, "{{");
385
+ return result;
386
+ }
387
+ function extractVariables(template) {
388
+ const vars = /* @__PURE__ */ new Set();
389
+ let match;
390
+ const re = new RegExp(VARIABLE_RE.source, "g");
391
+ while ((match = re.exec(template)) !== null) {
392
+ vars.add(match[1]);
393
+ }
394
+ return [...vars];
395
+ }
396
+
397
+ // src/renderer/renderer.ts
398
+ function renderSections(asset, options = {}) {
399
+ const { variables = {}, strict = false } = options;
400
+ const result = {};
401
+ if (asset.sections.system_instructions) {
402
+ result.system_instructions = interpolate(
403
+ asset.sections.system_instructions,
404
+ variables,
405
+ { strict }
406
+ );
407
+ }
408
+ if (asset.sections.prompt_template) {
409
+ result.prompt_template = interpolate(
410
+ asset.sections.prompt_template,
411
+ variables,
412
+ { strict }
413
+ );
414
+ }
415
+ return result;
416
+ }
417
+
418
+ // src/providers/openai.ts
419
+ var openaiAdapter = {
420
+ name: "openai",
421
+ validate(asset) {
422
+ const errors = [];
423
+ const warnings = [];
424
+ if (!asset.model) {
425
+ errors.push("OpenAI adapter requires a model to be specified.");
426
+ }
427
+ if (asset.reasoning?.budget_tokens !== void 0) {
428
+ warnings.push("OpenAI uses reasoning_effort, not budget_tokens. budget_tokens will be ignored.");
429
+ }
430
+ return { valid: errors.length === 0, errors, warnings };
431
+ },
432
+ render(asset, runtime) {
433
+ const sections = renderSections(asset, {
434
+ variables: runtime.variables,
435
+ strict: runtime.strict
436
+ });
437
+ const messages = [];
438
+ if (sections.system_instructions) {
439
+ messages.push({ role: "system", content: sections.system_instructions });
440
+ }
441
+ if (runtime.history) {
442
+ for (const msg of runtime.history) {
443
+ messages.push({ role: msg.role, content: msg.content });
444
+ }
445
+ }
446
+ if (sections.prompt_template) {
447
+ messages.push({ role: "user", content: sections.prompt_template });
448
+ }
449
+ const body = {
450
+ model: asset.model,
451
+ messages
452
+ };
453
+ if (asset.sampling?.temperature !== void 0) body.temperature = asset.sampling.temperature;
454
+ if (asset.sampling?.top_p !== void 0) body.top_p = asset.sampling.top_p;
455
+ if (asset.sampling?.frequency_penalty !== void 0) body.frequency_penalty = asset.sampling.frequency_penalty;
456
+ if (asset.sampling?.presence_penalty !== void 0) body.presence_penalty = asset.sampling.presence_penalty;
457
+ if (asset.sampling?.stop !== void 0) body.stop = asset.sampling.stop;
458
+ if (asset.sampling?.max_output_tokens !== void 0) body.max_tokens = asset.sampling.max_output_tokens;
459
+ if (asset.reasoning?.effort) {
460
+ body.reasoning_effort = asset.reasoning.effort;
461
+ }
462
+ if (asset.response?.format === "json") {
463
+ body.response_format = { type: "json_object" };
464
+ }
465
+ if (asset.response?.stream !== void 0) {
466
+ body.stream = asset.response.stream;
467
+ }
468
+ if (asset.tools && asset.tools.length > 0) {
469
+ body.tools = asset.tools.map((tool) => {
470
+ if (typeof tool === "string") {
471
+ const def = runtime.toolRegistry?.[tool];
472
+ if (def) return def;
473
+ return { type: "function", function: { name: tool } };
474
+ }
475
+ return {
476
+ type: "function",
477
+ function: {
478
+ name: tool.name,
479
+ description: tool.description,
480
+ parameters: tool.input_schema
481
+ }
482
+ };
483
+ });
484
+ }
485
+ return {
486
+ body,
487
+ provider: "openai",
488
+ model: asset.model ?? "unknown"
489
+ };
490
+ }
491
+ };
492
+
493
+ // src/providers/anthropic.ts
494
+ var anthropicAdapter = {
495
+ name: "anthropic",
496
+ validate(asset) {
497
+ const errors = [];
498
+ const warnings = [];
499
+ if (!asset.model) {
500
+ errors.push("Anthropic adapter requires a model to be specified.");
501
+ }
502
+ if (asset.sampling?.frequency_penalty !== void 0) {
503
+ warnings.push("Anthropic does not support frequency_penalty. It will be ignored.");
504
+ }
505
+ if (asset.sampling?.presence_penalty !== void 0) {
506
+ warnings.push("Anthropic does not support presence_penalty. It will be ignored.");
507
+ }
508
+ if (asset.reasoning?.effort !== void 0) {
509
+ warnings.push("Anthropic uses budget_tokens for thinking, not effort. effort will be mapped approximately.");
510
+ }
511
+ return { valid: errors.length === 0, errors, warnings };
512
+ },
513
+ render(asset, runtime) {
514
+ const sections = renderSections(asset, {
515
+ variables: runtime.variables,
516
+ strict: runtime.strict
517
+ });
518
+ const messages = [];
519
+ if (runtime.history) {
520
+ for (const msg of runtime.history) {
521
+ messages.push({ role: msg.role, content: msg.content });
522
+ }
523
+ }
524
+ if (sections.prompt_template) {
525
+ messages.push({ role: "user", content: sections.prompt_template });
526
+ }
527
+ const body = {
528
+ model: asset.model,
529
+ messages
530
+ };
531
+ if (sections.system_instructions) {
532
+ body.system = sections.system_instructions;
533
+ }
534
+ if (asset.sampling?.temperature !== void 0) body.temperature = asset.sampling.temperature;
535
+ if (asset.sampling?.top_p !== void 0) body.top_p = asset.sampling.top_p;
536
+ if (asset.sampling?.stop !== void 0) body.stop_sequences = asset.sampling.stop;
537
+ if (asset.sampling?.max_output_tokens !== void 0) {
538
+ body.max_tokens = asset.sampling.max_output_tokens;
539
+ } else {
540
+ body.max_tokens = 4096;
541
+ }
542
+ if (asset.reasoning?.budget_tokens) {
543
+ body.thinking = {
544
+ type: "enabled",
545
+ budget_tokens: asset.reasoning.budget_tokens
546
+ };
547
+ }
548
+ if (asset.response?.stream !== void 0) {
549
+ body.stream = asset.response.stream;
550
+ }
551
+ if (asset.tools && asset.tools.length > 0) {
552
+ body.tools = asset.tools.map((tool) => {
553
+ if (typeof tool === "string") {
554
+ const def = runtime.toolRegistry?.[tool];
555
+ if (def) return def;
556
+ return { name: tool };
557
+ }
558
+ return {
559
+ name: tool.name,
560
+ description: tool.description,
561
+ input_schema: tool.input_schema ?? { type: "object", properties: {} }
562
+ };
563
+ });
564
+ }
565
+ return {
566
+ body,
567
+ provider: "anthropic",
568
+ model: asset.model ?? "unknown"
569
+ };
570
+ }
571
+ };
572
+
573
+ // src/providers/gemini.ts
574
+ var geminiAdapter = {
575
+ name: "gemini",
576
+ validate(asset) {
577
+ const errors = [];
578
+ const warnings = [];
579
+ if (!asset.model) {
580
+ errors.push("Gemini adapter requires a model to be specified.");
581
+ }
582
+ if (asset.sampling?.frequency_penalty !== void 0) {
583
+ warnings.push("Gemini does not support frequency_penalty. It will be ignored.");
584
+ }
585
+ if (asset.sampling?.presence_penalty !== void 0) {
586
+ warnings.push("Gemini does not support presence_penalty. It will be ignored.");
587
+ }
588
+ return { valid: errors.length === 0, errors, warnings };
589
+ },
590
+ render(asset, runtime) {
591
+ const sections = renderSections(asset, {
592
+ variables: runtime.variables,
593
+ strict: runtime.strict
594
+ });
595
+ const contents = [];
596
+ if (runtime.history) {
597
+ for (const msg of runtime.history) {
598
+ contents.push({
599
+ role: msg.role === "assistant" ? "model" : "user",
600
+ parts: [{ text: msg.content }]
601
+ });
602
+ }
603
+ }
604
+ if (sections.prompt_template) {
605
+ contents.push({
606
+ role: "user",
607
+ parts: [{ text: sections.prompt_template }]
608
+ });
609
+ }
610
+ const body = {
611
+ contents
612
+ };
613
+ if (sections.system_instructions) {
614
+ body.systemInstruction = {
615
+ parts: [{ text: sections.system_instructions }]
616
+ };
617
+ }
618
+ const generationConfig = {};
619
+ if (asset.sampling?.temperature !== void 0) generationConfig.temperature = asset.sampling.temperature;
620
+ if (asset.sampling?.top_p !== void 0) generationConfig.topP = asset.sampling.top_p;
621
+ if (asset.sampling?.max_output_tokens !== void 0) generationConfig.maxOutputTokens = asset.sampling.max_output_tokens;
622
+ if (asset.sampling?.stop !== void 0) generationConfig.stopSequences = asset.sampling.stop;
623
+ if (asset.response?.format === "json") {
624
+ generationConfig.responseMimeType = "application/json";
625
+ }
626
+ if (asset.reasoning?.effort) {
627
+ body.thinkingConfig = {
628
+ thinkingBudget: asset.reasoning.effort === "high" ? 8192 : asset.reasoning.effort === "medium" ? 4096 : 1024
629
+ };
630
+ }
631
+ if (Object.keys(generationConfig).length > 0) {
632
+ body.generationConfig = generationConfig;
633
+ }
634
+ if (asset.tools && asset.tools.length > 0) {
635
+ const functionDeclarations = asset.tools.map((tool) => {
636
+ if (typeof tool === "string") {
637
+ const def = runtime.toolRegistry?.[tool];
638
+ if (def) return def;
639
+ return { name: tool };
640
+ }
641
+ return {
642
+ name: tool.name,
643
+ description: tool.description,
644
+ parameters: tool.input_schema
645
+ };
646
+ });
647
+ body.tools = [{ functionDeclarations }];
648
+ }
649
+ return {
650
+ body,
651
+ provider: "gemini",
652
+ model: asset.model ?? "unknown"
653
+ };
654
+ }
655
+ };
656
+
657
+ // src/providers/openrouter.ts
658
+ var openrouterAdapter = {
659
+ name: "openrouter",
660
+ validate(asset) {
661
+ return openaiAdapter.validate(asset);
662
+ },
663
+ render(asset, runtime) {
664
+ const result = openaiAdapter.render(asset, runtime);
665
+ return {
666
+ ...result,
667
+ provider: "openrouter"
668
+ };
669
+ }
670
+ };
671
+
672
+ // src/providers/index.ts
673
+ var adapters = {
674
+ openai: openaiAdapter,
675
+ anthropic: anthropicAdapter,
676
+ google: geminiAdapter,
677
+ gemini: geminiAdapter,
678
+ openrouter: openrouterAdapter
679
+ };
680
+ function getAdapter(provider) {
681
+ const adapter = adapters[provider];
682
+ if (!adapter) {
683
+ throw new Error(
684
+ `Unknown provider: "${provider}". Supported: ${Object.keys(adapters).join(", ")}`
685
+ );
686
+ }
687
+ return adapter;
688
+ }
689
+
690
+ // src/validation/levenshtein.ts
691
+ function levenshtein(a, b) {
692
+ const m = a.length;
693
+ const n = b.length;
694
+ if (m === 0) return n;
695
+ if (n === 0) return m;
696
+ const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(0));
697
+ for (let i = 0; i <= m; i++) dp[i][0] = i;
698
+ for (let j = 0; j <= n; j++) dp[0][j] = j;
699
+ for (let i = 1; i <= m; i++) {
700
+ for (let j = 1; j <= n; j++) {
701
+ const cost = a[i - 1] === b[j - 1] ? 0 : 1;
702
+ dp[i][j] = Math.min(
703
+ dp[i - 1][j] + 1,
704
+ dp[i][j - 1] + 1,
705
+ dp[i - 1][j - 1] + cost
706
+ );
707
+ }
708
+ }
709
+ return dp[m][n];
710
+ }
711
+
712
+ // src/validation/validate.ts
713
+ var KNOWN_FRONT_MATTER_KEYS = /* @__PURE__ */ new Set([
714
+ "id",
715
+ "schema_version",
716
+ "description",
717
+ "provider",
718
+ "model",
719
+ "fallback_models",
720
+ "reasoning",
721
+ "sampling",
722
+ "response",
723
+ "tools",
724
+ "mcp",
725
+ "context",
726
+ "includes",
727
+ "environments",
728
+ "tiers",
729
+ "metadata"
730
+ ]);
731
+ function validateAsset(asset, frontMatterKeys, filePath) {
732
+ const errors = [];
733
+ const warnings = [];
734
+ const result = PromptAssetSchema.safeParse(asset);
735
+ if (!result.success) {
736
+ for (const issue of result.error.issues) {
737
+ errors.push({
738
+ code: "POK001",
739
+ message: `Schema error at ${issue.path.join(".")}: ${issue.message}`,
740
+ filePath
741
+ });
742
+ }
743
+ }
744
+ if (!asset.id) {
745
+ errors.push({
746
+ code: "POK002",
747
+ message: 'Missing required field: "id"',
748
+ filePath
749
+ });
750
+ }
751
+ if (!asset.sections?.system_instructions && !asset.sections?.prompt_template) {
752
+ errors.push({
753
+ code: "POK003",
754
+ message: "Prompt must have at least one body section (System instructions or Prompt template)",
755
+ filePath
756
+ });
757
+ }
758
+ if (frontMatterKeys) {
759
+ for (const key of frontMatterKeys) {
760
+ if (!KNOWN_FRONT_MATTER_KEYS.has(key)) {
761
+ const suggestion = findClosestMatch(key, KNOWN_FRONT_MATTER_KEYS);
762
+ warnings.push({
763
+ code: "POK010",
764
+ message: `Unknown front matter field: "${key}"`,
765
+ filePath,
766
+ suggestion: suggestion ? `Did you mean "${suggestion}"?` : void 0
767
+ });
768
+ }
769
+ }
770
+ }
771
+ const declaredInputs = new Set(asset.context?.inputs ?? []);
772
+ const usedVars = /* @__PURE__ */ new Set();
773
+ if (asset.sections?.system_instructions) {
774
+ for (const v of extractVariables(asset.sections.system_instructions)) {
775
+ usedVars.add(v);
776
+ }
777
+ }
778
+ if (asset.sections?.prompt_template) {
779
+ for (const v of extractVariables(asset.sections.prompt_template)) {
780
+ usedVars.add(v);
781
+ }
782
+ }
783
+ for (const v of usedVars) {
784
+ if (declaredInputs.size > 0 && !declaredInputs.has(v)) {
785
+ warnings.push({
786
+ code: "POK011",
787
+ message: `Variable "{{ ${v} }}" is used but not declared in context.inputs`,
788
+ filePath
789
+ });
790
+ }
791
+ }
792
+ for (const v of declaredInputs) {
793
+ if (!usedVars.has(v)) {
794
+ warnings.push({
795
+ code: "POK012",
796
+ message: `Variable "${v}" is declared in context.inputs but never used`,
797
+ filePath
798
+ });
799
+ }
800
+ }
801
+ return {
802
+ valid: errors.length === 0,
803
+ errors,
804
+ warnings
805
+ };
806
+ }
807
+ async function validateAssetWithIncludes(asset, filePath, frontMatterKeys) {
808
+ const result = validateAsset(asset, frontMatterKeys, filePath);
809
+ if (asset.includes && asset.includes.length > 0) {
810
+ try {
811
+ await resolveIncludes(asset, filePath);
812
+ } catch (err) {
813
+ const message = err instanceof Error ? err.message : String(err);
814
+ const isCircular = message.includes("Circular include");
815
+ result.errors.push({
816
+ code: isCircular ? "POK021" : "POK020",
817
+ message: isCircular ? `Circular include detected: ${message}` : `Include resolution failed: ${message}`,
818
+ filePath
819
+ });
820
+ result.valid = false;
821
+ }
822
+ }
823
+ return result;
824
+ }
825
+ function findClosestMatch(input, candidates) {
826
+ let best;
827
+ let bestDist = Infinity;
828
+ for (const candidate of candidates) {
829
+ const dist = levenshtein(input.toLowerCase(), candidate.toLowerCase());
830
+ if (dist < bestDist && dist <= 3) {
831
+ bestDist = dist;
832
+ best = candidate;
833
+ }
834
+ }
835
+ return best;
836
+ }
837
+
838
+ // src/cache.ts
839
+ var import_node_fs = require("fs");
840
+ var PromptCache = class {
841
+ cache = /* @__PURE__ */ new Map();
842
+ maxSize;
843
+ constructor(maxSize = 100) {
844
+ this.maxSize = maxSize;
845
+ }
846
+ get(filePath) {
847
+ const entry = this.cache.get(filePath);
848
+ if (!entry) return void 0;
849
+ try {
850
+ const stat = (0, import_node_fs.statSync)(filePath);
851
+ if (stat.mtimeMs !== entry.mtime) {
852
+ this.cache.delete(filePath);
853
+ return void 0;
854
+ }
855
+ } catch {
856
+ this.cache.delete(filePath);
857
+ return void 0;
858
+ }
859
+ return entry.value;
860
+ }
861
+ set(filePath, value) {
862
+ if (this.cache.size >= this.maxSize) {
863
+ const oldest = this.cache.keys().next().value;
864
+ if (oldest) this.cache.delete(oldest);
865
+ }
866
+ try {
867
+ const stat = (0, import_node_fs.statSync)(filePath);
868
+ this.cache.set(filePath, { value, mtime: stat.mtimeMs });
869
+ } catch {
870
+ }
871
+ }
872
+ clear() {
873
+ this.cache.clear();
874
+ }
875
+ get size() {
876
+ return this.cache.size;
877
+ }
878
+ };
879
+
880
+ // src/index.ts
881
+ var PromptOpsKit = class {
882
+ config;
883
+ promptCache;
884
+ constructor(config) {
885
+ this.config = {
886
+ ...config,
887
+ mode: config.mode ?? "auto",
888
+ cache: config.cache ?? true
889
+ };
890
+ this.promptCache = new PromptCache();
891
+ }
892
+ /**
893
+ * Load a prompt asset from compiled or source, based on mode.
894
+ */
895
+ async loadPrompt(promptPath) {
896
+ const mode = this.config.mode;
897
+ if (mode !== "source-only" && this.config.compiledDir) {
898
+ const compiledFile = (0, import_node_path3.resolve)(this.config.compiledDir, promptPath + ".json");
899
+ if ((0, import_node_fs2.existsSync)(compiledFile)) {
900
+ if (mode === "auto") {
901
+ const sourceFile = (0, import_node_path3.resolve)(this.config.sourceDir, promptPath + ".md");
902
+ if ((0, import_node_fs2.existsSync)(sourceFile)) {
903
+ const compiledMtime = (0, import_node_fs2.statSync)(compiledFile).mtimeMs;
904
+ const sourceMtime = (0, import_node_fs2.statSync)(sourceFile).mtimeMs;
905
+ if (sourceMtime > compiledMtime) {
906
+ console.warn(
907
+ `[promptopskit] Warning: compiled artifact for "${promptPath}" is older than source .md file.
908
+ Run "promptopskit compile" or switch to source-only mode.`
909
+ );
910
+ }
911
+ }
912
+ }
913
+ const content = await (0, import_promises3.readFile)(compiledFile, "utf-8");
914
+ return JSON.parse(content);
915
+ }
916
+ if (mode === "compiled-only") {
917
+ throw new Error(
918
+ `Compiled artifact not found: ${compiledFile}
919
+ Run "promptopskit compile" to generate it.`
920
+ );
921
+ }
922
+ }
923
+ if (mode !== "compiled-only") {
924
+ const sourceFile = (0, import_node_path3.resolve)(this.config.sourceDir, promptPath + ".md");
925
+ if (this.config.cache) {
926
+ const cached = this.promptCache.get(sourceFile);
927
+ if (cached) return cached;
928
+ }
929
+ if (!(0, import_node_fs2.existsSync)(sourceFile)) {
930
+ const paths = [sourceFile];
931
+ if (this.config.compiledDir) {
932
+ paths.unshift((0, import_node_path3.resolve)(this.config.compiledDir, promptPath + ".json"));
933
+ }
934
+ throw new Error(
935
+ `Prompt not found: "${promptPath}"
936
+ Searched:
937
+ ${paths.map((p) => ` - ${p}`).join("\n")}`
938
+ );
939
+ }
940
+ const { asset } = await loadPromptFile(sourceFile, { defaultsRoot: this.config.sourceDir });
941
+ if (this.config.cache) {
942
+ this.promptCache.set(sourceFile, asset);
943
+ }
944
+ return asset;
945
+ }
946
+ throw new Error(`Prompt not found: "${promptPath}"`);
947
+ }
948
+ /**
949
+ * Resolve a prompt: load, resolve includes, apply overrides.
950
+ */
951
+ async resolvePrompt(promptPath, options = {}) {
952
+ let asset = await this.loadPrompt(promptPath);
953
+ const sourceFile = (0, import_node_path3.resolve)(this.config.sourceDir, promptPath + ".md");
954
+ if (asset.includes && asset.includes.length > 0 && (0, import_node_fs2.existsSync)(sourceFile)) {
955
+ asset = await resolveIncludes(asset, sourceFile);
956
+ }
957
+ asset = applyOverrides(asset, {
958
+ environment: options.environment,
959
+ tier: options.tier
960
+ });
961
+ return asset;
962
+ }
963
+ /**
964
+ * Render a prompt for a specific provider.
965
+ */
966
+ async renderPrompt(options) {
967
+ let resolved;
968
+ if (options.source) {
969
+ const { asset } = parsePrompt(options.source);
970
+ const overridden = applyOverrides(asset, {
971
+ environment: options.environment,
972
+ tier: options.tier
973
+ });
974
+ resolved = overridden;
975
+ } else if (options.path) {
976
+ resolved = await this.resolvePrompt(options.path, {
977
+ environment: options.environment,
978
+ tier: options.tier
979
+ });
980
+ } else {
981
+ throw new Error('Either "path" or "source" must be provided to renderPrompt()');
982
+ }
983
+ const adapter = getAdapter(options.provider);
984
+ const validation = adapter.validate(resolved);
985
+ if (!validation.valid) {
986
+ throw new Error(
987
+ `Provider validation failed for "${options.provider}":
988
+ ` + validation.errors.map((e) => ` - ${e}`).join("\n")
989
+ );
990
+ }
991
+ const request = adapter.render(resolved, {
992
+ variables: options.variables,
993
+ history: options.history,
994
+ toolRegistry: options.toolRegistry,
995
+ strict: options.strict
996
+ });
997
+ return {
998
+ resolved,
999
+ request,
1000
+ warnings: validation.warnings
1001
+ };
1002
+ }
1003
+ /**
1004
+ * Validate a prompt file.
1005
+ */
1006
+ async validatePrompt(promptPath) {
1007
+ const asset = await this.loadPrompt(promptPath);
1008
+ return validateAsset(asset, void 0, promptPath);
1009
+ }
1010
+ /**
1011
+ * Clear the internal cache.
1012
+ */
1013
+ clearCache() {
1014
+ this.promptCache.clear();
1015
+ }
1016
+ };
1017
+ function createPromptOpsKit(config) {
1018
+ return new PromptOpsKit(config);
1019
+ }
1020
+ async function renderPrompt(options) {
1021
+ const kit = createPromptOpsKit({
1022
+ sourceDir: options.sourceDir ?? ".",
1023
+ cache: false
1024
+ });
1025
+ return kit.renderPrompt(options);
1026
+ }
1027
+ // Annotate the CommonJS export names for ESM import in node:
1028
+ 0 && (module.exports = {
1029
+ PromptAssetOverridesSchema,
1030
+ PromptAssetSchema,
1031
+ PromptOpsKit,
1032
+ anthropicAdapter,
1033
+ applyOverrides,
1034
+ createPromptOpsKit,
1035
+ extractSections,
1036
+ extractVariables,
1037
+ geminiAdapter,
1038
+ getAdapter,
1039
+ interpolate,
1040
+ loadPromptFile,
1041
+ openaiAdapter,
1042
+ openrouterAdapter,
1043
+ parsePrompt,
1044
+ renderPrompt,
1045
+ resolveIncludes,
1046
+ validateAsset,
1047
+ validateAssetWithIncludes
1048
+ });
1049
+ //# sourceMappingURL=index.cjs.map