promptopskit 0.3.8 → 0.4.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 (73) hide show
  1. package/README.md +97 -10
  2. package/SKILL.md +69 -6
  3. package/dist/chunk-F6UJ73Y6.js +113 -0
  4. package/dist/chunk-F6UJ73Y6.js.map +1 -0
  5. package/dist/chunk-HLNVKKMS.js +145 -0
  6. package/dist/chunk-HLNVKKMS.js.map +1 -0
  7. package/dist/{chunk-5OYWNRNC.js → chunk-JBLUPKY4.js} +191 -5
  8. package/dist/chunk-JBLUPKY4.js.map +1 -0
  9. package/dist/{chunk-UJU5XERR.js → chunk-L2V7LDKD.js} +25 -4
  10. package/dist/chunk-L2V7LDKD.js.map +1 -0
  11. package/dist/{chunk-E6NPZOJL.js → chunk-RY5DVTLV.js} +29 -4
  12. package/dist/chunk-RY5DVTLV.js.map +1 -0
  13. package/dist/chunk-UPTCSWK3.js +60 -0
  14. package/dist/chunk-UPTCSWK3.js.map +1 -0
  15. package/dist/{chunk-X73VG645.js → chunk-XNNDGDPI.js} +64 -3
  16. package/dist/chunk-XNNDGDPI.js.map +1 -0
  17. package/dist/cli/index.js +423 -7
  18. package/dist/cli/index.js.map +1 -1
  19. package/dist/index.cjs +655 -22
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.cts +7 -4
  22. package/dist/index.d.ts +7 -4
  23. package/dist/index.js +172 -11
  24. package/dist/index.js.map +1 -1
  25. package/dist/providers/anthropic.cjs +306 -10
  26. package/dist/providers/anthropic.cjs.map +1 -1
  27. package/dist/providers/anthropic.d.cts +2 -2
  28. package/dist/providers/anthropic.d.ts +2 -2
  29. package/dist/providers/anthropic.js +3 -3
  30. package/dist/providers/gemini.cjs +274 -6
  31. package/dist/providers/gemini.cjs.map +1 -1
  32. package/dist/providers/gemini.d.cts +2 -2
  33. package/dist/providers/gemini.d.ts +2 -2
  34. package/dist/providers/gemini.js +3 -3
  35. package/dist/providers/openai-responses.cjs +1245 -0
  36. package/dist/providers/openai-responses.cjs.map +1 -0
  37. package/dist/providers/openai-responses.d.cts +11 -0
  38. package/dist/providers/openai-responses.d.ts +11 -0
  39. package/dist/providers/openai-responses.js +9 -0
  40. package/dist/providers/openai-responses.js.map +1 -0
  41. package/dist/providers/openai.cjs +270 -6
  42. package/dist/providers/openai.cjs.map +1 -1
  43. package/dist/providers/openai.d.cts +2 -2
  44. package/dist/providers/openai.d.ts +2 -2
  45. package/dist/providers/openai.js +3 -3
  46. package/dist/providers/openrouter.cjs +305 -9
  47. package/dist/providers/openrouter.cjs.map +1 -1
  48. package/dist/providers/openrouter.d.cts +2 -2
  49. package/dist/providers/openrouter.d.ts +2 -2
  50. package/dist/providers/openrouter.js +4 -4
  51. package/dist/schema-B9A1zLRk.d.cts +2403 -0
  52. package/dist/schema-B9A1zLRk.d.ts +2403 -0
  53. package/dist/testing.cjs +264 -6
  54. package/dist/testing.cjs.map +1 -1
  55. package/dist/testing.d.cts +59 -2
  56. package/dist/testing.d.ts +59 -2
  57. package/dist/testing.js +70 -2
  58. package/dist/testing.js.map +1 -1
  59. package/dist/{types-fBvo_d4k.d.ts → types-DjGAwJxC.d.ts} +13 -1
  60. package/dist/{types-C6RG0Si0.d.cts → types-DpbzzZO2.d.cts} +13 -1
  61. package/dist/usagetap/index.d.cts +2 -2
  62. package/dist/usagetap/index.d.ts +2 -2
  63. package/package.json +12 -2
  64. package/dist/chunk-5OYWNRNC.js.map +0 -1
  65. package/dist/chunk-BBVVA27J.js +0 -92
  66. package/dist/chunk-BBVVA27J.js.map +0 -1
  67. package/dist/chunk-E2NXJLS6.js +0 -26
  68. package/dist/chunk-E2NXJLS6.js.map +0 -1
  69. package/dist/chunk-E6NPZOJL.js.map +0 -1
  70. package/dist/chunk-UJU5XERR.js.map +0 -1
  71. package/dist/chunk-X73VG645.js.map +0 -1
  72. package/dist/schema-DwzYbZba.d.cts +0 -859
  73. package/dist/schema-DwzYbZba.d.ts +0 -859
@@ -0,0 +1,1245 @@
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/providers/openai-responses.ts
31
+ var openai_responses_exports = {};
32
+ __export(openai_responses_exports, {
33
+ openaiResponsesAdapter: () => openaiResponsesAdapter
34
+ });
35
+ module.exports = __toCommonJS(openai_responses_exports);
36
+
37
+ // src/renderer/interpolate.ts
38
+ var VARIABLE_RE = /\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}/g;
39
+ var ESCAPED_OPEN = /\\\{\\\{/g;
40
+ var ESCAPE_PLACEHOLDER = "\0ESCAPED_OPEN\0";
41
+ function interpolate(template, variables, options = {}) {
42
+ const { strict = false } = options;
43
+ let result = template.replace(ESCAPED_OPEN, ESCAPE_PLACEHOLDER);
44
+ result = result.replace(VARIABLE_RE, (match, name) => {
45
+ if (name in variables) {
46
+ return variables[name];
47
+ }
48
+ if (strict) {
49
+ throw new Error(`Missing required variable: "${name}"`);
50
+ }
51
+ return match;
52
+ });
53
+ result = result.replaceAll(ESCAPE_PLACEHOLDER, "{{");
54
+ return result;
55
+ }
56
+
57
+ // src/renderer/renderer.ts
58
+ function renderSections(asset, options = {}) {
59
+ const { variables = {}, strict = false } = options;
60
+ const result = {};
61
+ if (asset.sections.system_instructions) {
62
+ result.system_instructions = interpolate(
63
+ asset.sections.system_instructions,
64
+ variables,
65
+ { strict }
66
+ );
67
+ }
68
+ if (asset.sections.prompt_template) {
69
+ result.prompt_template = interpolate(
70
+ asset.sections.prompt_template,
71
+ variables,
72
+ { strict }
73
+ );
74
+ }
75
+ return result;
76
+ }
77
+
78
+ // src/overrides/apply-overrides.ts
79
+ function applyOverrides(asset, options = {}) {
80
+ let result = { ...asset };
81
+ if (options.environment && result.environments?.[options.environment]) {
82
+ result = mergeOverride(result, result.environments[options.environment]);
83
+ }
84
+ if (options.tier && result.tiers?.[options.tier]) {
85
+ result = mergeOverride(result, result.tiers[options.tier]);
86
+ }
87
+ if (options.runtime) {
88
+ result = mergeOverride(result, options.runtime);
89
+ }
90
+ return result;
91
+ }
92
+ function mergeOverride(base, override) {
93
+ const result = { ...base };
94
+ if (override.model !== void 0) result.model = override.model;
95
+ if (override.fallback_models !== void 0) result.fallback_models = override.fallback_models;
96
+ if (override.tools !== void 0) result.tools = override.tools;
97
+ if (override.reasoning !== void 0) {
98
+ result.reasoning = { ...result.reasoning, ...override.reasoning };
99
+ }
100
+ if (override.sampling !== void 0) {
101
+ result.sampling = { ...result.sampling, ...override.sampling };
102
+ }
103
+ if (override.response !== void 0) {
104
+ result.response = { ...result.response, ...override.response };
105
+ }
106
+ if (override.cache !== void 0) {
107
+ result.cache = {
108
+ ...result.cache,
109
+ ...override.cache,
110
+ openai: mergeRecordBlock(result.cache?.openai, override.cache.openai),
111
+ anthropic: mergeRecordBlock(result.cache?.anthropic, override.cache.anthropic),
112
+ gemini: mergeRecordBlock(result.cache?.gemini, override.cache.gemini),
113
+ google: mergeRecordBlock(result.cache?.google, override.cache.google)
114
+ };
115
+ }
116
+ if (override.raw !== void 0) {
117
+ result.raw = {
118
+ ...result.raw,
119
+ ...override.raw,
120
+ openai: mergeRecordBlock(result.raw?.openai, override.raw.openai),
121
+ "openai-responses": mergeRecordBlock(result.raw?.["openai-responses"], override.raw["openai-responses"]),
122
+ openai_responses: mergeRecordBlock(result.raw?.openai_responses, override.raw.openai_responses),
123
+ anthropic: mergeRecordBlock(result.raw?.anthropic, override.raw.anthropic),
124
+ gemini: mergeRecordBlock(result.raw?.gemini, override.raw.gemini),
125
+ google: mergeRecordBlock(result.raw?.google, override.raw.google),
126
+ openrouter: mergeRecordBlock(result.raw?.openrouter, override.raw.openrouter)
127
+ };
128
+ }
129
+ if (override.provider_options !== void 0) {
130
+ result.provider_options = {
131
+ ...result.provider_options,
132
+ ...override.provider_options,
133
+ anthropic: {
134
+ ...result.provider_options?.anthropic,
135
+ ...override.provider_options.anthropic
136
+ },
137
+ gemini: {
138
+ ...result.provider_options?.gemini,
139
+ ...override.provider_options.gemini
140
+ },
141
+ openrouter: {
142
+ ...result.provider_options?.openrouter,
143
+ ...override.provider_options.openrouter
144
+ }
145
+ };
146
+ }
147
+ return result;
148
+ }
149
+ function mergeRecordBlock(base, override) {
150
+ if (override === void 0) return base;
151
+ return { ...base, ...override };
152
+ }
153
+
154
+ // src/providers/resolve-asset.ts
155
+ function resolveAssetForProvider(asset, runtime = {}) {
156
+ if (!runtime.environment && !runtime.tier && !runtime.runtime) {
157
+ return asset;
158
+ }
159
+ return applyOverrides(asset, {
160
+ environment: runtime.environment,
161
+ tier: runtime.tier,
162
+ runtime: runtime.runtime
163
+ });
164
+ }
165
+
166
+ // src/prompt-resolution.ts
167
+ var import_promises3 = require("fs/promises");
168
+ var import_node_fs2 = require("fs");
169
+ var import_node_path3 = require("path");
170
+
171
+ // src/cache.ts
172
+ var import_node_fs = require("fs");
173
+ var PromptCache = class {
174
+ cache = /* @__PURE__ */ new Map();
175
+ maxSize;
176
+ constructor(maxSize = 100) {
177
+ this.maxSize = maxSize;
178
+ }
179
+ get(filePath) {
180
+ const entry = this.cache.get(filePath);
181
+ if (!entry) return void 0;
182
+ try {
183
+ const stat = (0, import_node_fs.statSync)(filePath);
184
+ if (stat.mtimeMs !== entry.mtime) {
185
+ this.cache.delete(filePath);
186
+ return void 0;
187
+ }
188
+ } catch {
189
+ this.cache.delete(filePath);
190
+ return void 0;
191
+ }
192
+ this.cache.delete(filePath);
193
+ this.cache.set(filePath, entry);
194
+ return entry.value;
195
+ }
196
+ set(filePath, value) {
197
+ try {
198
+ const stat = (0, import_node_fs.statSync)(filePath);
199
+ if (this.cache.has(filePath)) {
200
+ this.cache.delete(filePath);
201
+ } else if (this.cache.size >= this.maxSize) {
202
+ const oldest = this.cache.keys().next().value;
203
+ if (oldest) this.cache.delete(oldest);
204
+ }
205
+ this.cache.set(filePath, { value, mtime: stat.mtimeMs });
206
+ } catch {
207
+ }
208
+ }
209
+ clear() {
210
+ this.cache.clear();
211
+ }
212
+ get size() {
213
+ return this.cache.size;
214
+ }
215
+ };
216
+
217
+ // src/composition/resolve-includes.ts
218
+ var import_promises2 = require("fs/promises");
219
+ var import_node_path2 = require("path");
220
+
221
+ // src/parser/parser.ts
222
+ var import_gray_matter = __toESM(require("gray-matter"), 1);
223
+
224
+ // src/schema/schema.ts
225
+ var import_zod = require("zod");
226
+ var InlineToolDefSchema = import_zod.z.object({
227
+ name: import_zod.z.string(),
228
+ description: import_zod.z.string().optional(),
229
+ input_schema: import_zod.z.record(import_zod.z.unknown()).optional()
230
+ });
231
+ var ToolRefSchema = import_zod.z.union([import_zod.z.string(), InlineToolDefSchema]);
232
+ var MCPServerRefSchema = import_zod.z.union([
233
+ import_zod.z.string(),
234
+ import_zod.z.object({
235
+ name: import_zod.z.string(),
236
+ config: import_zod.z.record(import_zod.z.unknown()).optional()
237
+ })
238
+ ]);
239
+ var ReasoningSchema = import_zod.z.object({
240
+ effort: import_zod.z.enum(["low", "medium", "high"]).optional(),
241
+ budget_tokens: import_zod.z.number().int().positive().optional()
242
+ });
243
+ var SamplingSchema = import_zod.z.object({
244
+ temperature: import_zod.z.number().min(0).max(2).optional(),
245
+ top_p: import_zod.z.number().min(0).max(1).optional(),
246
+ frequency_penalty: import_zod.z.number().optional(),
247
+ presence_penalty: import_zod.z.number().optional(),
248
+ stop: import_zod.z.array(import_zod.z.string()).optional(),
249
+ max_output_tokens: import_zod.z.number().int().positive().optional()
250
+ });
251
+ var ResponseSchema = import_zod.z.object({
252
+ format: import_zod.z.enum(["text", "json", "markdown"]).optional(),
253
+ stream: import_zod.z.boolean().optional(),
254
+ schema: import_zod.z.record(import_zod.z.unknown()).optional(),
255
+ schema_name: import_zod.z.string().optional(),
256
+ schema_description: import_zod.z.string().optional(),
257
+ schema_strict: import_zod.z.boolean().optional()
258
+ });
259
+ var AnthropicProviderOptionsSchema = import_zod.z.object({
260
+ top_k: import_zod.z.number().int().min(0).optional(),
261
+ tool_choice: import_zod.z.record(import_zod.z.unknown()).optional(),
262
+ output_config: import_zod.z.record(import_zod.z.unknown()).optional()
263
+ });
264
+ var GeminiProviderOptionsSchema = import_zod.z.object({
265
+ candidate_count: import_zod.z.number().int().positive().optional(),
266
+ top_k: import_zod.z.number().int().min(0).optional(),
267
+ seed: import_zod.z.number().int().optional(),
268
+ response_schema: import_zod.z.record(import_zod.z.unknown()).optional(),
269
+ response_json_schema: import_zod.z.record(import_zod.z.unknown()).optional(),
270
+ response_modalities: import_zod.z.array(import_zod.z.string()).optional(),
271
+ thinking_budget_tokens: import_zod.z.number().int().positive().optional()
272
+ });
273
+ var OpenRouterProviderOptionsSchema = import_zod.z.object({
274
+ provider: import_zod.z.record(import_zod.z.unknown()).optional(),
275
+ transforms: import_zod.z.array(import_zod.z.string()).optional(),
276
+ plugins: import_zod.z.array(import_zod.z.record(import_zod.z.unknown())).optional(),
277
+ models: import_zod.z.array(import_zod.z.string()).optional()
278
+ });
279
+ var ProviderOptionsSchema = import_zod.z.object({
280
+ anthropic: AnthropicProviderOptionsSchema.optional(),
281
+ gemini: GeminiProviderOptionsSchema.optional(),
282
+ openrouter: OpenRouterProviderOptionsSchema.optional()
283
+ });
284
+ var RawProviderBodySchema = import_zod.z.object({
285
+ openai: import_zod.z.record(import_zod.z.unknown()).optional(),
286
+ "openai-responses": import_zod.z.record(import_zod.z.unknown()).optional(),
287
+ openai_responses: import_zod.z.record(import_zod.z.unknown()).optional(),
288
+ anthropic: import_zod.z.record(import_zod.z.unknown()).optional(),
289
+ gemini: import_zod.z.record(import_zod.z.unknown()).optional(),
290
+ google: import_zod.z.record(import_zod.z.unknown()).optional(),
291
+ openrouter: import_zod.z.record(import_zod.z.unknown()).optional()
292
+ });
293
+ var OpenAICacheSchema = import_zod.z.object({
294
+ prompt_cache_key: import_zod.z.string().min(1).optional(),
295
+ retention: import_zod.z.enum(["in_memory", "24h"]).optional()
296
+ });
297
+ var AnthropicCacheSchema = import_zod.z.object({
298
+ mode: import_zod.z.enum(["automatic", "explicit"]).optional(),
299
+ type: import_zod.z.literal("ephemeral").optional(),
300
+ ttl: import_zod.z.enum(["5m", "1h"]).optional(),
301
+ cache_system_instructions: import_zod.z.boolean().optional(),
302
+ cache_tools: import_zod.z.boolean().optional(),
303
+ cache_prompt_template: import_zod.z.boolean().optional()
304
+ });
305
+ var GeminiCacheSchema = import_zod.z.object({
306
+ cached_content: import_zod.z.string().min(1).optional()
307
+ });
308
+ var CacheSchema = import_zod.z.object({
309
+ openai: OpenAICacheSchema.optional(),
310
+ anthropic: AnthropicCacheSchema.optional(),
311
+ gemini: GeminiCacheSchema.optional(),
312
+ google: GeminiCacheSchema.optional()
313
+ });
314
+ var HistorySchema = import_zod.z.object({
315
+ max_items: import_zod.z.number().int().positive().optional()
316
+ });
317
+ var ContextRegexSchema = import_zod.z.union([
318
+ import_zod.z.string(),
319
+ import_zod.z.object({
320
+ pattern: import_zod.z.string(),
321
+ flags: import_zod.z.string().optional(),
322
+ return_message: import_zod.z.string().optional()
323
+ })
324
+ ]);
325
+ var ContextBuiltInValidatorSchema = import_zod.z.union([
326
+ import_zod.z.boolean(),
327
+ import_zod.z.object({
328
+ return_message: import_zod.z.string().optional()
329
+ })
330
+ ]);
331
+ var ContextInputDefinitionObjectSchema = import_zod.z.object({
332
+ name: import_zod.z.string(),
333
+ max_size: import_zod.z.number().int().positive().optional(),
334
+ trim: import_zod.z.union([import_zod.z.boolean(), import_zod.z.enum(["start", "end", "both"])]).optional(),
335
+ allow_regex: ContextRegexSchema.optional(),
336
+ deny_regex: ContextRegexSchema.optional(),
337
+ non_empty: ContextBuiltInValidatorSchema.optional(),
338
+ reject_secrets: ContextBuiltInValidatorSchema.optional()
339
+ });
340
+ var ContextInputDefinitionSchema = import_zod.z.union([
341
+ import_zod.z.string(),
342
+ ContextInputDefinitionObjectSchema
343
+ ]);
344
+ var ContextSchema = import_zod.z.object({
345
+ inputs: import_zod.z.array(ContextInputDefinitionSchema).optional(),
346
+ history: HistorySchema.optional()
347
+ });
348
+ var MetadataSchema = import_zod.z.object({
349
+ owner: import_zod.z.string().optional(),
350
+ tags: import_zod.z.array(import_zod.z.string()).optional(),
351
+ review_required: import_zod.z.boolean().optional(),
352
+ stable: import_zod.z.boolean().optional()
353
+ });
354
+ var MCPSchema = import_zod.z.object({
355
+ servers: import_zod.z.array(MCPServerRefSchema).optional()
356
+ });
357
+ var PromptAssetOverridesSchema = import_zod.z.object({
358
+ model: import_zod.z.string().optional(),
359
+ fallback_models: import_zod.z.array(import_zod.z.string()).optional(),
360
+ reasoning: ReasoningSchema.optional(),
361
+ sampling: SamplingSchema.optional(),
362
+ response: ResponseSchema.optional(),
363
+ cache: CacheSchema.optional(),
364
+ raw: RawProviderBodySchema.optional(),
365
+ tools: import_zod.z.array(ToolRefSchema).optional(),
366
+ provider_options: ProviderOptionsSchema.optional()
367
+ });
368
+ var SourceSchema = import_zod.z.object({
369
+ file_path: import_zod.z.string().optional(),
370
+ checksum: import_zod.z.string().optional()
371
+ });
372
+ var SectionsSchema = import_zod.z.object({
373
+ system_instructions: import_zod.z.string().optional(),
374
+ prompt_template: import_zod.z.string().optional(),
375
+ notes: import_zod.z.string().optional()
376
+ });
377
+ var PromptDefaultsSchema = import_zod.z.object({
378
+ provider: import_zod.z.enum(["openai", "openai-responses", "anthropic", "google", "gemini", "openrouter", "any"]).optional(),
379
+ model: import_zod.z.string().optional(),
380
+ cache: CacheSchema.optional(),
381
+ metadata: MetadataSchema.optional(),
382
+ sections: import_zod.z.object({
383
+ system_instructions: import_zod.z.string().optional()
384
+ }).optional()
385
+ });
386
+ var PromptAssetSchema = import_zod.z.object({
387
+ id: import_zod.z.string(),
388
+ schema_version: import_zod.z.number().int().positive().default(1),
389
+ description: import_zod.z.string().optional(),
390
+ provider: import_zod.z.enum(["openai", "openai-responses", "anthropic", "google", "gemini", "openrouter", "any"]).optional(),
391
+ model: import_zod.z.string().optional(),
392
+ fallback_models: import_zod.z.array(import_zod.z.string()).optional(),
393
+ reasoning: ReasoningSchema.optional(),
394
+ sampling: SamplingSchema.optional(),
395
+ response: ResponseSchema.optional(),
396
+ cache: CacheSchema.optional(),
397
+ raw: RawProviderBodySchema.optional(),
398
+ tools: import_zod.z.array(ToolRefSchema).optional(),
399
+ provider_options: ProviderOptionsSchema.optional(),
400
+ mcp: MCPSchema.optional(),
401
+ context: ContextSchema.optional(),
402
+ includes: import_zod.z.array(import_zod.z.string()).optional(),
403
+ environments: import_zod.z.record(PromptAssetOverridesSchema).optional(),
404
+ tiers: import_zod.z.record(PromptAssetOverridesSchema).optional(),
405
+ metadata: MetadataSchema.optional(),
406
+ // Populated by parser, not authored in YAML
407
+ sections: SectionsSchema.optional(),
408
+ source: SourceSchema.optional()
409
+ });
410
+
411
+ // src/parser/frontmatter-guard.ts
412
+ var FRONT_MATTER_DELIMITER = /^---[ \t]*$/;
413
+ var REGEX_FIELD = /^(?<indent>\s*)(?<field>allow_regex|deny_regex)\s*:\s*(?<value>.*)$/;
414
+ var PATTERN_FIELD = /^(?<indent>\s*)pattern\s*:\s*(?<value>.*)$/;
415
+ var INLINE_PATTERN_FIELD = /(?:^|[{,]\s*)pattern\s*:\s*(?<value>"(?:\\.|[^"\\])*")/;
416
+ function assertRegexFrontMatterQuoting(content, filePath) {
417
+ const frontMatter = extractFrontMatter(content);
418
+ if (!frontMatter) {
419
+ return;
420
+ }
421
+ let pendingRegex;
422
+ for (const [index, line] of frontMatter.lines.entries()) {
423
+ const lineNumber = frontMatter.startLine + index;
424
+ const regexMatch = line.match(REGEX_FIELD);
425
+ if (regexMatch?.groups) {
426
+ const field = regexMatch.groups.field;
427
+ const indent2 = regexMatch.groups.indent.length;
428
+ const value = regexMatch.groups.value.trim();
429
+ pendingRegex = value === "" ? { field, indent: indent2 } : void 0;
430
+ assertNoUnescapedBackslashInDoubleQuotedRegex(value, field, filePath, lineNumber);
431
+ assertNoUnescapedBackslashInInlinePattern(value, field, filePath, lineNumber);
432
+ continue;
433
+ }
434
+ if (!pendingRegex) {
435
+ continue;
436
+ }
437
+ if (line.trim() === "" || line.trimStart().startsWith("#")) {
438
+ continue;
439
+ }
440
+ const indent = line.match(/^\s*/)?.[0].length ?? 0;
441
+ if (indent <= pendingRegex.indent) {
442
+ pendingRegex = void 0;
443
+ continue;
444
+ }
445
+ const patternMatch = line.match(PATTERN_FIELD);
446
+ if (!patternMatch?.groups) {
447
+ continue;
448
+ }
449
+ assertNoUnescapedBackslashInDoubleQuotedRegex(
450
+ patternMatch.groups.value.trim(),
451
+ `${pendingRegex.field}.pattern`,
452
+ filePath,
453
+ lineNumber
454
+ );
455
+ }
456
+ }
457
+ function assertNoUnescapedBackslashInInlinePattern(value, field, filePath, lineNumber) {
458
+ const match = value.match(INLINE_PATTERN_FIELD);
459
+ const pattern = match?.groups?.value;
460
+ if (!pattern) {
461
+ return;
462
+ }
463
+ assertNoUnescapedBackslashInDoubleQuotedRegex(pattern, `${field}.pattern`, filePath, lineNumber);
464
+ }
465
+ function extractFrontMatter(content) {
466
+ const lines = content.split(/\r?\n/);
467
+ if (!FRONT_MATTER_DELIMITER.test(lines[0] ?? "")) {
468
+ return void 0;
469
+ }
470
+ for (let index = 1; index < lines.length; index += 1) {
471
+ if (FRONT_MATTER_DELIMITER.test(lines[index] ?? "")) {
472
+ return {
473
+ lines: lines.slice(1, index),
474
+ startLine: 2
475
+ };
476
+ }
477
+ }
478
+ return void 0;
479
+ }
480
+ function assertNoUnescapedBackslashInDoubleQuotedRegex(value, field, filePath, lineNumber) {
481
+ if (!value.startsWith('"')) {
482
+ return;
483
+ }
484
+ const quoted = readDoubleQuotedScalar(value);
485
+ if (!quoted) {
486
+ return;
487
+ }
488
+ if (!hasUnescapedBackslash(quoted)) {
489
+ return;
490
+ }
491
+ const location = filePath ? `${filePath}:${lineNumber}` : `line ${lineNumber}`;
492
+ throw new Error(
493
+ `POK013: Invalid context regex YAML at ${location}, field "${field}": double-quoted regex strings treat backslashes as YAML escapes. Use unquoted /pattern/i literal form, single quotes, or double each backslash.`
494
+ );
495
+ }
496
+ function readDoubleQuotedScalar(value) {
497
+ let result = "";
498
+ for (let index = 1; index < value.length; index += 1) {
499
+ const char = value[index];
500
+ if (char === '"') {
501
+ return result;
502
+ }
503
+ result += char;
504
+ if (char === "\\" && index + 1 < value.length) {
505
+ index += 1;
506
+ result += value[index];
507
+ }
508
+ }
509
+ return void 0;
510
+ }
511
+ function hasUnescapedBackslash(value) {
512
+ for (let index = 0; index < value.length; index += 1) {
513
+ if (value[index] !== "\\") {
514
+ continue;
515
+ }
516
+ let count = 1;
517
+ while (value[index + count] === "\\") {
518
+ count += 1;
519
+ }
520
+ if (count % 2 === 1) {
521
+ return true;
522
+ }
523
+ index += count - 1;
524
+ }
525
+ return false;
526
+ }
527
+
528
+ // src/parser/sections.ts
529
+ var SECTION_MAP = {
530
+ "system instructions": "system_instructions",
531
+ "prompt template": "prompt_template",
532
+ "notes": "notes"
533
+ };
534
+ function extractSections(body) {
535
+ const lines = body.split(/\r?\n/);
536
+ const sections = {};
537
+ let currentKey = null;
538
+ let currentLines = [];
539
+ let foundAnyH1 = false;
540
+ for (const line of lines) {
541
+ const h1Match = line.match(/^#\s+(.+)$/);
542
+ if (h1Match) {
543
+ if (currentKey) {
544
+ sections[currentKey] = currentLines.join("\n").trim();
545
+ }
546
+ foundAnyH1 = true;
547
+ const heading = h1Match[1].trim().toLowerCase();
548
+ currentKey = SECTION_MAP[heading] ?? null;
549
+ currentLines = [];
550
+ } else {
551
+ currentLines.push(line);
552
+ }
553
+ }
554
+ if (currentKey) {
555
+ sections[currentKey] = currentLines.join("\n").trim();
556
+ }
557
+ if (!foundAnyH1) {
558
+ const trimmed = body.trim();
559
+ if (trimmed) {
560
+ sections.prompt_template = trimmed;
561
+ }
562
+ }
563
+ return sections;
564
+ }
565
+
566
+ // src/parser/parser.ts
567
+ function parsePrompt(content, filePath) {
568
+ assertRegexFrontMatterQuoting(content, filePath);
569
+ const { data: frontMatter, content: body } = (0, import_gray_matter.default)(content);
570
+ const sections = extractSections(body);
571
+ const raw = {
572
+ ...frontMatter,
573
+ sections,
574
+ source: filePath ? { file_path: filePath } : void 0
575
+ };
576
+ const asset = PromptAssetSchema.parse(raw);
577
+ return {
578
+ asset,
579
+ raw: {
580
+ frontMatter,
581
+ body
582
+ }
583
+ };
584
+ }
585
+
586
+ // src/parser/loader.ts
587
+ var import_promises = require("fs/promises");
588
+ var import_node_path = require("path");
589
+ var import_gray_matter2 = __toESM(require("gray-matter"), 1);
590
+ var DEFAULTS_FILE_NAME = "defaults.md";
591
+ async function loadPromptFile(filePath, options = {}) {
592
+ const content = await (0, import_promises.readFile)(filePath, "utf-8");
593
+ const parsed = parsePrompt(content, filePath);
594
+ const root = options.defaultsRoot ?? (0, import_node_path.dirname)(filePath);
595
+ const defaults = await loadDefaultsForPath(filePath, root);
596
+ const asset = applyDefaults(parsed.asset, defaults);
597
+ return {
598
+ ...parsed,
599
+ asset
600
+ };
601
+ }
602
+ async function loadDefaultsForPath(filePath, defaultsRoot) {
603
+ const directories = getDirectoriesToCheck(filePath, defaultsRoot);
604
+ let merged = {};
605
+ for (const dir of directories) {
606
+ const defaultsPath = (0, import_node_path.join)(dir, DEFAULTS_FILE_NAME);
607
+ try {
608
+ const defaultsContent = await (0, import_promises.readFile)(defaultsPath, "utf-8");
609
+ const defaults = parseDefaults(defaultsContent);
610
+ merged = mergeDefaults(merged, defaults);
611
+ } catch (error) {
612
+ if (error.code !== "ENOENT") {
613
+ throw error;
614
+ }
615
+ }
616
+ }
617
+ return merged;
618
+ }
619
+ function getDirectoriesToCheck(filePath, defaultsRoot) {
620
+ const dirs = [];
621
+ let current = (0, import_node_path.resolve)((0, import_node_path.dirname)(filePath));
622
+ const boundary = defaultsRoot ? (0, import_node_path.resolve)(defaultsRoot) : void 0;
623
+ while (true) {
624
+ dirs.unshift(current);
625
+ if (boundary && current === boundary || current === (0, import_node_path.dirname)(current)) {
626
+ break;
627
+ }
628
+ current = (0, import_node_path.dirname)(current);
629
+ }
630
+ return dirs;
631
+ }
632
+ function parseDefaults(content) {
633
+ const { data: frontMatter, content: body } = (0, import_gray_matter2.default)(content);
634
+ const sections = extractSections(body);
635
+ return PromptDefaultsSchema.parse({
636
+ ...frontMatter,
637
+ sections: {
638
+ system_instructions: sections.system_instructions
639
+ }
640
+ });
641
+ }
642
+ function mergeDefaults(base, local) {
643
+ return {
644
+ provider: local.provider ?? base.provider,
645
+ model: local.model ?? base.model,
646
+ metadata: {
647
+ ...base.metadata ?? {},
648
+ ...local.metadata ?? {}
649
+ },
650
+ sections: {
651
+ ...base.sections ?? {},
652
+ ...local.sections ?? {}
653
+ }
654
+ };
655
+ }
656
+ function applyDefaults(asset, defaults) {
657
+ const hasDefaultMetadata = defaults.metadata && Object.keys(defaults.metadata).length > 0;
658
+ const hasDefaultSystem = !!defaults.sections?.system_instructions;
659
+ const hasDefaultScalars = defaults.provider !== void 0 || defaults.model !== void 0;
660
+ if (!hasDefaultMetadata && !hasDefaultSystem && !hasDefaultScalars) {
661
+ return asset;
662
+ }
663
+ const mergedMetadata = {
664
+ ...defaults.metadata ?? {},
665
+ ...asset.metadata ?? {}
666
+ };
667
+ const metadata = Object.keys(mergedMetadata).length > 0 ? mergedMetadata : void 0;
668
+ const systemInstructions = asset.sections?.system_instructions ?? defaults.sections?.system_instructions;
669
+ const sections = asset.sections ? { ...asset.sections, system_instructions: systemInstructions } : systemInstructions ? { system_instructions: systemInstructions } : void 0;
670
+ return {
671
+ ...asset,
672
+ provider: asset.provider ?? defaults.provider,
673
+ model: asset.model ?? defaults.model,
674
+ metadata,
675
+ sections
676
+ };
677
+ }
678
+
679
+ // src/composition/resolve-includes.ts
680
+ async function resolveIncludes(asset, basePath, visited = /* @__PURE__ */ new Set()) {
681
+ if (!asset.includes || asset.includes.length === 0) {
682
+ return asset;
683
+ }
684
+ const baseDir = (0, import_node_path2.dirname)(basePath);
685
+ const resolvedPath = (0, import_node_path2.resolve)(basePath);
686
+ if (visited.has(resolvedPath)) {
687
+ throw new Error(`Circular include detected: ${resolvedPath}`);
688
+ }
689
+ visited.add(resolvedPath);
690
+ let mergedSystemInstructions = "";
691
+ for (const includePath of asset.includes) {
692
+ const fullPath = (0, import_node_path2.resolve)(baseDir, includePath);
693
+ if (visited.has(fullPath)) {
694
+ throw new Error(`Circular include detected: ${fullPath} (included from ${basePath})`);
695
+ }
696
+ const content = await (0, import_promises2.readFile)(fullPath, "utf-8");
697
+ const { asset: includedAsset } = parsePrompt(content, fullPath);
698
+ const resolved = await resolveIncludes(includedAsset, fullPath, new Set(visited));
699
+ if (resolved.sections?.system_instructions) {
700
+ mergedSystemInstructions += resolved.sections.system_instructions + "\n\n";
701
+ }
702
+ }
703
+ const localSystem = asset.sections?.system_instructions ?? "";
704
+ const combinedSystem = (mergedSystemInstructions + localSystem).trim() || void 0;
705
+ return {
706
+ ...asset,
707
+ sections: {
708
+ ...asset.sections,
709
+ system_instructions: combinedSystem
710
+ },
711
+ // Drop includes from the resolved asset — they've been inlined
712
+ includes: void 0
713
+ };
714
+ }
715
+
716
+ // src/prompt-resolution.ts
717
+ var DEFAULT_PROMPTS_DIR = "./prompts";
718
+ var DEFAULT_COMPILED_JSON_DIR = "./.generated-prompts/json";
719
+ function withPromptResolutionDefaults(config) {
720
+ return {
721
+ ...config,
722
+ sourceDir: config.sourceDir ?? DEFAULT_PROMPTS_DIR,
723
+ compiledDir: config.compiledDir ?? DEFAULT_COMPILED_JSON_DIR
724
+ };
725
+ }
726
+ var sharedPromptCache = new PromptCache();
727
+ async function loadPromptAsset(promptPath, config, promptCache = sharedPromptCache) {
728
+ const resolvedConfig = withPromptResolutionDefaults(config);
729
+ const mode = resolvedConfig.mode ?? "auto";
730
+ if (mode !== "source-only" && resolvedConfig.compiledDir) {
731
+ const compiledFile = (0, import_node_path3.resolve)(resolvedConfig.compiledDir, promptPath + ".json");
732
+ if ((0, import_node_fs2.existsSync)(compiledFile)) {
733
+ if (mode === "auto") {
734
+ const sourceFile = (0, import_node_path3.resolve)(resolvedConfig.sourceDir, promptPath + ".md");
735
+ if ((0, import_node_fs2.existsSync)(sourceFile)) {
736
+ const compiledMtime = (0, import_node_fs2.statSync)(compiledFile).mtimeMs;
737
+ const sourceMtime = (0, import_node_fs2.statSync)(sourceFile).mtimeMs;
738
+ if (sourceMtime > compiledMtime) {
739
+ console.warn(
740
+ `[promptopskit] Warning: compiled artifact for "${promptPath}" is older than source .md file.
741
+ Run "promptopskit compile" or switch to source-only mode.`
742
+ );
743
+ }
744
+ }
745
+ }
746
+ const content = await (0, import_promises3.readFile)(compiledFile, "utf-8");
747
+ return JSON.parse(content);
748
+ }
749
+ if (mode === "compiled-only") {
750
+ throw new Error(
751
+ `Compiled artifact not found: ${compiledFile}
752
+ Run "promptopskit compile" to generate it.`
753
+ );
754
+ }
755
+ }
756
+ if (mode !== "compiled-only") {
757
+ const sourceFile = (0, import_node_path3.resolve)(resolvedConfig.sourceDir, promptPath + ".md");
758
+ if (resolvedConfig.cache !== false) {
759
+ const cached = promptCache.get(sourceFile);
760
+ if (cached) {
761
+ return cached;
762
+ }
763
+ }
764
+ if (!(0, import_node_fs2.existsSync)(sourceFile)) {
765
+ const paths = [sourceFile];
766
+ if (resolvedConfig.compiledDir) {
767
+ paths.unshift((0, import_node_path3.resolve)(resolvedConfig.compiledDir, promptPath + ".json"));
768
+ }
769
+ throw new Error(
770
+ `Prompt not found: "${promptPath}"
771
+ Searched:
772
+ ${paths.map((candidate) => ` - ${candidate}`).join("\n")}`
773
+ );
774
+ }
775
+ const { asset } = await loadPromptFile(sourceFile, { defaultsRoot: resolvedConfig.sourceDir });
776
+ if (resolvedConfig.cache !== false) {
777
+ promptCache.set(sourceFile, asset);
778
+ }
779
+ return asset;
780
+ }
781
+ throw new Error(`Prompt not found: "${promptPath}"`);
782
+ }
783
+ async function resolvePromptAsset(promptPath, config, options = {}, promptCache = sharedPromptCache) {
784
+ const resolvedConfig = withPromptResolutionDefaults(config);
785
+ let asset = await loadPromptAsset(promptPath, resolvedConfig, promptCache);
786
+ const sourceFile = (0, import_node_path3.resolve)(resolvedConfig.sourceDir, promptPath + ".md");
787
+ if (asset.includes && asset.includes.length > 0 && (0, import_node_fs2.existsSync)(sourceFile)) {
788
+ asset = await resolveIncludes(asset, sourceFile);
789
+ }
790
+ asset = applyOverrides(asset, {
791
+ environment: options.environment,
792
+ tier: options.tier,
793
+ runtime: options.runtime
794
+ });
795
+ return asset;
796
+ }
797
+ function resolveInlinePromptSource(source, options = {}) {
798
+ const { asset } = parsePrompt(source);
799
+ return applyOverrides(asset, {
800
+ environment: options.environment,
801
+ tier: options.tier,
802
+ runtime: options.runtime
803
+ });
804
+ }
805
+
806
+ // src/context.ts
807
+ var textEncoder = new TextEncoder();
808
+ var REJECT_SECRETS_PATTERN = "(secret|api[_-]?key|password)";
809
+ var REJECT_SECRETS_FLAGS = "i";
810
+ function getContextInputs(asset) {
811
+ return (asset.context?.inputs ?? []).map(normalizeContextInput);
812
+ }
813
+ function normalizeContextInput(input) {
814
+ if (typeof input === "string") {
815
+ return { name: input };
816
+ }
817
+ return {
818
+ name: input.name,
819
+ max_size: input.max_size,
820
+ trim: input.trim,
821
+ allow_regex: normalizeContextRegex(input.allow_regex),
822
+ deny_regex: normalizeContextRegex(input.deny_regex),
823
+ non_empty: normalizeBuiltInValidator(input.non_empty),
824
+ reject_secrets: normalizeBuiltInValidator(input.reject_secrets)
825
+ };
826
+ }
827
+ function normalizeContextRegex(value) {
828
+ if (value === void 0) {
829
+ return void 0;
830
+ }
831
+ if (typeof value === "string") {
832
+ const literal = parseRegexLiteral(value);
833
+ if (value.startsWith("/") && !literal) {
834
+ return {
835
+ pattern: value,
836
+ flags: "",
837
+ raw: value,
838
+ invalidLiteral: true
839
+ };
840
+ }
841
+ return {
842
+ pattern: literal?.pattern ?? value,
843
+ flags: literal?.flags ?? "",
844
+ raw: value
845
+ };
846
+ }
847
+ return {
848
+ pattern: value.pattern,
849
+ flags: value.flags ?? "",
850
+ raw: JSON.stringify(value),
851
+ returnMessage: value.return_message
852
+ };
853
+ }
854
+ function normalizeBuiltInValidator(value) {
855
+ if (value === void 0 || value === false) {
856
+ return void 0;
857
+ }
858
+ if (value === true) {
859
+ return {};
860
+ }
861
+ return {
862
+ returnMessage: value.return_message
863
+ };
864
+ }
865
+ function parseRegexLiteral(value) {
866
+ if (!value.startsWith("/")) {
867
+ return void 0;
868
+ }
869
+ for (let index = value.length - 1; index > 0; index -= 1) {
870
+ if (value[index] !== "/") {
871
+ continue;
872
+ }
873
+ let backslashCount = 0;
874
+ for (let cursor = index - 1; cursor >= 0 && value[cursor] === "\\"; cursor -= 1) {
875
+ backslashCount += 1;
876
+ }
877
+ if (backslashCount % 2 === 1) {
878
+ continue;
879
+ }
880
+ return {
881
+ pattern: value.slice(1, index),
882
+ flags: value.slice(index + 1)
883
+ };
884
+ }
885
+ return void 0;
886
+ }
887
+ function formatInvalidContextRegexMessage(details) {
888
+ return [
889
+ `Invalid context regex for prompt "${details.promptId}"`,
890
+ `variable "${details.variable}"`,
891
+ `field "${details.field}"`,
892
+ `value ${JSON.stringify(details.raw)}: ${details.reason}`
893
+ ].join(", ");
894
+ }
895
+ function compileContextRegex(regex, details) {
896
+ if (regex.invalidLiteral) {
897
+ throw new Error(
898
+ `POK013: ${formatInvalidContextRegexMessage({
899
+ ...details,
900
+ raw: regex.raw,
901
+ reason: "Malformed regex literal. Use /pattern/flags or { pattern, flags }."
902
+ })}`
903
+ );
904
+ }
905
+ try {
906
+ return new RegExp(regex.pattern, regex.flags);
907
+ } catch (error) {
908
+ const reason = error instanceof Error ? error.message : String(error);
909
+ throw new Error(`POK013: ${formatInvalidContextRegexMessage({ ...details, raw: regex.raw, reason })}`);
910
+ }
911
+ }
912
+ function getRejectSecretsRegex() {
913
+ return {
914
+ pattern: REJECT_SECRETS_PATTERN,
915
+ flags: REJECT_SECRETS_FLAGS,
916
+ raw: JSON.stringify({ pattern: REJECT_SECRETS_PATTERN, flags: REJECT_SECRETS_FLAGS })
917
+ };
918
+ }
919
+ function isTrimEnabled(mode) {
920
+ return mode === true || mode === "start" || mode === "end" || mode === "both";
921
+ }
922
+ function normalizeTrimMode(mode) {
923
+ if (mode === "start") {
924
+ return "start";
925
+ }
926
+ return "end";
927
+ }
928
+ function trimToMaxSize(value, maxSize, mode) {
929
+ const measured = measureContextValueSize(value);
930
+ if (measured <= maxSize) {
931
+ return value;
932
+ }
933
+ const characters = Array.from(value);
934
+ const normalizedMode = normalizeTrimMode(mode);
935
+ if (normalizedMode === "start") {
936
+ let collected2 = "";
937
+ let size2 = 0;
938
+ for (let i = characters.length - 1; i >= 0; i -= 1) {
939
+ const next = characters[i];
940
+ const charSize = measureContextValueSize(next);
941
+ if (size2 + charSize > maxSize) {
942
+ break;
943
+ }
944
+ collected2 = next + collected2;
945
+ size2 += charSize;
946
+ }
947
+ return collected2;
948
+ }
949
+ let collected = "";
950
+ let size = 0;
951
+ for (const char of characters) {
952
+ const charSize = measureContextValueSize(char);
953
+ if (size + charSize > maxSize) {
954
+ break;
955
+ }
956
+ collected += char;
957
+ size += charSize;
958
+ }
959
+ return collected;
960
+ }
961
+ function sanitizeContextVariables(asset, variables = {}, options = {}) {
962
+ const { onContextOverflow } = options;
963
+ const sanitized = { ...variables };
964
+ for (const input of getContextInputs(asset)) {
965
+ const value = sanitized[input.name];
966
+ if (value === void 0) {
967
+ continue;
968
+ }
969
+ let candidate = value;
970
+ if (input.max_size !== void 0) {
971
+ const actualSize = measureContextValueSize(candidate);
972
+ if (actualSize > input.max_size && onContextOverflow) {
973
+ candidate = onContextOverflow({
974
+ promptId: asset.id,
975
+ variable: input.name,
976
+ value: candidate,
977
+ maxSize: input.max_size,
978
+ actualSize
979
+ });
980
+ }
981
+ }
982
+ if (isTrimEnabled(input.trim) && input.max_size !== void 0) {
983
+ candidate = trimToMaxSize(candidate, input.max_size, input.trim);
984
+ }
985
+ sanitized[input.name] = candidate;
986
+ if (input.allow_regex) {
987
+ const candidate2 = sanitized[input.name];
988
+ const matcher = compileContextRegex(input.allow_regex, {
989
+ promptId: asset.id,
990
+ variable: input.name,
991
+ field: "allow_regex"
992
+ });
993
+ if (!matcher.test(candidate2)) {
994
+ if (input.allow_regex.returnMessage) {
995
+ return {
996
+ variables: sanitized,
997
+ shortCircuit: {
998
+ returnMessage: input.allow_regex.returnMessage,
999
+ code: "POK031",
1000
+ variable: input.name,
1001
+ field: "allow_regex"
1002
+ }
1003
+ };
1004
+ }
1005
+ throw new Error(
1006
+ `POK031: Context variable "${input.name}" failed allow_regex validation for prompt "${asset.id}".`
1007
+ );
1008
+ }
1009
+ }
1010
+ if (input.deny_regex) {
1011
+ const candidate2 = sanitized[input.name];
1012
+ const matcher = compileContextRegex(input.deny_regex, {
1013
+ promptId: asset.id,
1014
+ variable: input.name,
1015
+ field: "deny_regex"
1016
+ });
1017
+ if (matcher.test(candidate2)) {
1018
+ if (input.deny_regex.returnMessage) {
1019
+ return {
1020
+ variables: sanitized,
1021
+ shortCircuit: {
1022
+ returnMessage: input.deny_regex.returnMessage,
1023
+ code: "POK032",
1024
+ variable: input.name,
1025
+ field: "deny_regex"
1026
+ }
1027
+ };
1028
+ }
1029
+ throw new Error(
1030
+ `POK032: Context variable "${input.name}" matched deny_regex for prompt "${asset.id}".`
1031
+ );
1032
+ }
1033
+ }
1034
+ if (input.non_empty && candidate.trim().length === 0) {
1035
+ if (input.non_empty.returnMessage) {
1036
+ return {
1037
+ variables: sanitized,
1038
+ shortCircuit: {
1039
+ returnMessage: input.non_empty.returnMessage,
1040
+ code: "POK033",
1041
+ variable: input.name,
1042
+ field: "non_empty"
1043
+ }
1044
+ };
1045
+ }
1046
+ throw new Error(
1047
+ `POK033: Context variable "${input.name}" failed non_empty validation for prompt "${asset.id}".`
1048
+ );
1049
+ }
1050
+ if (input.reject_secrets) {
1051
+ const matcher = compileContextRegex(getRejectSecretsRegex(), {
1052
+ promptId: asset.id,
1053
+ variable: input.name,
1054
+ field: "reject_secrets"
1055
+ });
1056
+ if (matcher.test(candidate)) {
1057
+ if (input.reject_secrets.returnMessage) {
1058
+ return {
1059
+ variables: sanitized,
1060
+ shortCircuit: {
1061
+ returnMessage: input.reject_secrets.returnMessage,
1062
+ code: "POK034",
1063
+ variable: input.name,
1064
+ field: "reject_secrets"
1065
+ }
1066
+ };
1067
+ }
1068
+ throw new Error(
1069
+ `POK034: Context variable "${input.name}" matched reject_secrets validation for prompt "${asset.id}".`
1070
+ );
1071
+ }
1072
+ }
1073
+ }
1074
+ return { variables: sanitized };
1075
+ }
1076
+ function measureContextValueSize(value) {
1077
+ return textEncoder.encode(value).length;
1078
+ }
1079
+
1080
+ // src/providers/prompt-input.ts
1081
+ function isPromptLookup(input) {
1082
+ return "path" in input && typeof input.path === "string";
1083
+ }
1084
+ function isInlinePromptSource(input) {
1085
+ return "source" in input && typeof input.source === "string";
1086
+ }
1087
+ async function resolveProviderPromptInput(input, runtime) {
1088
+ if (isPromptLookup(input)) {
1089
+ return resolvePromptAsset(input.path, input, runtime);
1090
+ }
1091
+ if (isInlinePromptSource(input)) {
1092
+ return resolveInlinePromptSource(input.source, runtime);
1093
+ }
1094
+ return input;
1095
+ }
1096
+ function withPromptInputSupport(adapter) {
1097
+ const validatePrompt = async (input, runtime) => {
1098
+ const resolved = await resolveProviderPromptInput(input, runtime);
1099
+ return adapter.validate(resolved, runtime);
1100
+ };
1101
+ const renderPrompt = async (input, runtime) => {
1102
+ const resolved = await resolveProviderPromptInput(input, runtime);
1103
+ const sanitization = sanitizeContextVariables(resolved, runtime.variables, {
1104
+ onContextOverflow: runtime.onContextOverflow
1105
+ });
1106
+ if (sanitization.shortCircuit) {
1107
+ return {
1108
+ provider: adapter.name,
1109
+ model: resolved.model ?? "",
1110
+ returnMessage: sanitization.shortCircuit.returnMessage
1111
+ };
1112
+ }
1113
+ return adapter.render(resolved, {
1114
+ ...runtime,
1115
+ variables: sanitization.variables
1116
+ });
1117
+ };
1118
+ return {
1119
+ ...adapter,
1120
+ validatePrompt,
1121
+ renderPrompt
1122
+ };
1123
+ }
1124
+
1125
+ // src/providers/raw.ts
1126
+ function applyRawProviderBody(body, asset, provider) {
1127
+ const raw = getRawProviderBody(asset, provider);
1128
+ return raw ? { ...body, ...raw } : body;
1129
+ }
1130
+ function getRawProviderBody(asset, provider) {
1131
+ if (provider === "openai-responses") {
1132
+ return asset.raw?.["openai-responses"] ?? asset.raw?.openai_responses;
1133
+ }
1134
+ if (provider === "gemini") {
1135
+ return asset.raw?.gemini ?? asset.raw?.google;
1136
+ }
1137
+ return asset.raw?.[provider];
1138
+ }
1139
+
1140
+ // src/providers/openai-responses.ts
1141
+ var openaiResponsesAdapter = withPromptInputSupport({
1142
+ name: "openai-responses",
1143
+ validate(asset, runtime) {
1144
+ const resolvedAsset = resolveAssetForProvider(asset, runtime);
1145
+ const errors = [];
1146
+ const warnings = [];
1147
+ if (!resolvedAsset.model) {
1148
+ errors.push("OpenAI Responses adapter requires a model to be specified.");
1149
+ }
1150
+ if (resolvedAsset.reasoning?.budget_tokens !== void 0) {
1151
+ warnings.push("OpenAI Responses uses reasoning.effort, not budget_tokens. budget_tokens will be ignored.");
1152
+ }
1153
+ if (resolvedAsset.response?.schema !== void 0 && resolvedAsset.response?.format !== "json") {
1154
+ warnings.push("OpenAI Responses response.schema requires response.format: json. schema will still be applied as JSON schema output.");
1155
+ }
1156
+ if (runtime?.openaiResponses?.conversation !== void 0 && runtime?.openaiResponses?.previous_response_id !== void 0) {
1157
+ errors.push('OpenAI Responses options "conversation" and "previous_response_id" cannot both be set.');
1158
+ }
1159
+ return { valid: errors.length === 0, errors, warnings };
1160
+ },
1161
+ render(asset, runtime) {
1162
+ const resolvedAsset = resolveAssetForProvider(asset, runtime);
1163
+ const sections = renderSections(resolvedAsset, {
1164
+ variables: runtime.variables,
1165
+ strict: runtime.strict
1166
+ });
1167
+ const responseOptions = runtime.openaiResponses;
1168
+ const input = [];
1169
+ if (runtime.history) {
1170
+ for (const msg of runtime.history) {
1171
+ input.push({ role: msg.role, content: msg.content });
1172
+ }
1173
+ }
1174
+ if (sections.prompt_template) {
1175
+ input.push({ role: "user", content: sections.prompt_template });
1176
+ }
1177
+ const body = {
1178
+ model: resolvedAsset.model,
1179
+ input
1180
+ };
1181
+ if (responseOptions?.instructions !== void 0) {
1182
+ body.instructions = responseOptions.instructions;
1183
+ } else if (sections.system_instructions) {
1184
+ body.instructions = sections.system_instructions;
1185
+ }
1186
+ if (resolvedAsset.sampling?.temperature !== void 0) body.temperature = resolvedAsset.sampling.temperature;
1187
+ if (resolvedAsset.sampling?.top_p !== void 0) body.top_p = resolvedAsset.sampling.top_p;
1188
+ if (resolvedAsset.sampling?.frequency_penalty !== void 0) body.frequency_penalty = resolvedAsset.sampling.frequency_penalty;
1189
+ if (resolvedAsset.sampling?.presence_penalty !== void 0) body.presence_penalty = resolvedAsset.sampling.presence_penalty;
1190
+ if (resolvedAsset.sampling?.stop !== void 0) body.stop = resolvedAsset.sampling.stop;
1191
+ if (resolvedAsset.sampling?.max_output_tokens !== void 0) body.max_output_tokens = resolvedAsset.sampling.max_output_tokens;
1192
+ if (resolvedAsset.reasoning?.effort) {
1193
+ body.reasoning = { effort: resolvedAsset.reasoning.effort };
1194
+ }
1195
+ if (resolvedAsset.response?.schema) {
1196
+ body.text = {
1197
+ format: {
1198
+ type: "json_schema",
1199
+ name: resolvedAsset.response.schema_name ?? `${resolvedAsset.id}_response`,
1200
+ ...resolvedAsset.response.schema_description ? { description: resolvedAsset.response.schema_description } : {},
1201
+ schema: resolvedAsset.response.schema,
1202
+ strict: resolvedAsset.response.schema_strict ?? true
1203
+ }
1204
+ };
1205
+ } else if (resolvedAsset.response?.format === "json") {
1206
+ body.text = { format: { type: "json_object" } };
1207
+ }
1208
+ if (resolvedAsset.response?.stream !== void 0) {
1209
+ body.stream = resolvedAsset.response.stream;
1210
+ }
1211
+ if (resolvedAsset.tools && resolvedAsset.tools.length > 0) {
1212
+ body.tools = resolvedAsset.tools.map((tool) => {
1213
+ if (typeof tool === "string") {
1214
+ const def = runtime.toolRegistry?.[tool];
1215
+ if (def) return def;
1216
+ return { type: "function", name: tool };
1217
+ }
1218
+ return {
1219
+ type: "function",
1220
+ name: tool.name,
1221
+ description: tool.description,
1222
+ parameters: tool.input_schema
1223
+ };
1224
+ });
1225
+ }
1226
+ if (responseOptions?.previous_response_id !== void 0) body.previous_response_id = responseOptions.previous_response_id;
1227
+ if (responseOptions?.conversation !== void 0) body.conversation = responseOptions.conversation;
1228
+ if (responseOptions?.parallel_tool_calls !== void 0) body.parallel_tool_calls = responseOptions.parallel_tool_calls;
1229
+ if (responseOptions?.max_tool_calls !== void 0) body.max_tool_calls = responseOptions.max_tool_calls;
1230
+ if (responseOptions?.store !== void 0) body.store = responseOptions.store;
1231
+ if (responseOptions?.metadata !== void 0) body.metadata = responseOptions.metadata;
1232
+ if (responseOptions?.include !== void 0) body.include = responseOptions.include;
1233
+ if (responseOptions?.background !== void 0) body.background = responseOptions.background;
1234
+ return {
1235
+ body: applyRawProviderBody(body, resolvedAsset, "openai-responses"),
1236
+ provider: "openai-responses",
1237
+ model: resolvedAsset.model ?? "unknown"
1238
+ };
1239
+ }
1240
+ });
1241
+ // Annotate the CommonJS export names for ESM import in node:
1242
+ 0 && (module.exports = {
1243
+ openaiResponsesAdapter
1244
+ });
1245
+ //# sourceMappingURL=openai-responses.cjs.map