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