promptopskit 0.7.1 → 0.8.1

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 (71) hide show
  1. package/README.md +39 -4
  2. package/SKILL.md +152 -2
  3. package/dist/{chunk-OWMP5NMV.js → chunk-5XH2GROP.js} +2 -2
  4. package/dist/{chunk-FICB2ZSK.js → chunk-DI7Q4T7A.js} +3 -3
  5. package/dist/{chunk-ULVY473P.js → chunk-E4GEKWVP.js} +31 -3
  6. package/dist/chunk-E4GEKWVP.js.map +1 -0
  7. package/dist/{chunk-3G3EAV7H.js → chunk-PDVUVZAU.js} +2 -2
  8. package/dist/chunk-RVAFVWR2.js +1760 -0
  9. package/dist/chunk-RVAFVWR2.js.map +1 -0
  10. package/dist/{chunk-35NN5F6O.js → chunk-UQLAWU67.js} +2 -2
  11. package/dist/{chunk-6NOUETAC.js → chunk-Z3DPPJNU.js} +2 -2
  12. package/dist/{chunk-R65RAHAG.js → chunk-ZVCKP4EM.js} +3 -3
  13. package/dist/cli/index.js +86 -5
  14. package/dist/cli/index.js.map +1 -1
  15. package/dist/index.cjs +964 -44
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.d.cts +45 -5
  18. package/dist/index.d.ts +45 -5
  19. package/dist/index.js +18 -10
  20. package/dist/index.js.map +1 -1
  21. package/dist/providers/anthropic.cjs +954 -42
  22. package/dist/providers/anthropic.cjs.map +1 -1
  23. package/dist/providers/anthropic.d.cts +2 -2
  24. package/dist/providers/anthropic.d.ts +2 -2
  25. package/dist/providers/anthropic.js +3 -3
  26. package/dist/providers/gemini.cjs +954 -42
  27. package/dist/providers/gemini.cjs.map +1 -1
  28. package/dist/providers/gemini.d.cts +2 -2
  29. package/dist/providers/gemini.d.ts +2 -2
  30. package/dist/providers/gemini.js +3 -3
  31. package/dist/providers/llmasaservice.cjs +954 -42
  32. package/dist/providers/llmasaservice.cjs.map +1 -1
  33. package/dist/providers/llmasaservice.d.cts +2 -2
  34. package/dist/providers/llmasaservice.d.ts +2 -2
  35. package/dist/providers/llmasaservice.js +4 -4
  36. package/dist/providers/openai-responses.cjs +954 -42
  37. package/dist/providers/openai-responses.cjs.map +1 -1
  38. package/dist/providers/openai-responses.d.cts +2 -2
  39. package/dist/providers/openai-responses.d.ts +2 -2
  40. package/dist/providers/openai-responses.js +3 -3
  41. package/dist/providers/openai.cjs +954 -42
  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 +954 -42
  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-DBcSns_b.d.cts → schema-BgVLZ2u5.d.cts} +641 -0
  52. package/dist/{schema-DBcSns_b.d.ts → schema-BgVLZ2u5.d.ts} +641 -0
  53. package/dist/testing.cjs +27 -1
  54. package/dist/testing.cjs.map +1 -1
  55. package/dist/testing.d.cts +1 -1
  56. package/dist/testing.d.ts +1 -1
  57. package/dist/testing.js +1 -1
  58. package/dist/{types-BlLXT5Qb.d.ts → types-2hnZmCkH.d.cts} +16 -3
  59. package/dist/{types-8T2D5KB5.d.cts → types-DgAT4jSR.d.ts} +16 -3
  60. package/dist/usagetap/index.d.cts +2 -2
  61. package/dist/usagetap/index.d.ts +2 -2
  62. package/package.json +1 -1
  63. package/dist/chunk-F552OBUV.js +0 -875
  64. package/dist/chunk-F552OBUV.js.map +0 -1
  65. package/dist/chunk-ULVY473P.js.map +0 -1
  66. /package/dist/{chunk-OWMP5NMV.js.map → chunk-5XH2GROP.js.map} +0 -0
  67. /package/dist/{chunk-FICB2ZSK.js.map → chunk-DI7Q4T7A.js.map} +0 -0
  68. /package/dist/{chunk-3G3EAV7H.js.map → chunk-PDVUVZAU.js.map} +0 -0
  69. /package/dist/{chunk-35NN5F6O.js.map → chunk-UQLAWU67.js.map} +0 -0
  70. /package/dist/{chunk-6NOUETAC.js.map → chunk-Z3DPPJNU.js.map} +0 -0
  71. /package/dist/{chunk-R65RAHAG.js.map → chunk-ZVCKP4EM.js.map} +0 -0
@@ -1,875 +0,0 @@
1
- import {
2
- loadPromptFile,
3
- parsePrompt
4
- } from "./chunk-ULVY473P.js";
5
-
6
- // src/renderer/interpolate.ts
7
- var VARIABLE_RE = /\{\{\s*([a-zA-Z_][a-zA-Z0-9_]*)\s*\}\}/g;
8
- var ESCAPED_OPEN = /\\\{\\\{/g;
9
- var ESCAPE_PLACEHOLDER = "\0ESCAPED_OPEN\0";
10
- function interpolate(template, variables, options = {}) {
11
- const { strict = false } = options;
12
- const optionalVariables = new Set(options.optionalVariables ?? []);
13
- let result = template.replace(ESCAPED_OPEN, ESCAPE_PLACEHOLDER);
14
- result = result.replace(VARIABLE_RE, (match, name) => {
15
- if (name in variables) {
16
- return variables[name];
17
- }
18
- if (strict && !optionalVariables.has(name)) {
19
- throw new Error(`Missing required variable: "${name}"`);
20
- }
21
- return match;
22
- });
23
- result = result.replaceAll(ESCAPE_PLACEHOLDER, "{{");
24
- return result;
25
- }
26
- function extractVariables(template) {
27
- const vars = /* @__PURE__ */ new Set();
28
- let match;
29
- const re = new RegExp(VARIABLE_RE.source, "g");
30
- while ((match = re.exec(template)) !== null) {
31
- vars.add(match[1]);
32
- }
33
- return [...vars];
34
- }
35
-
36
- // src/context.ts
37
- var textEncoder = new TextEncoder();
38
- var REJECT_SECRETS_PATTERN = "(secret|api[_-]?key|password)";
39
- var REJECT_SECRETS_FLAGS = "i";
40
- function getContextInputs(asset) {
41
- return (asset.context?.inputs ?? []).map(normalizeContextInput);
42
- }
43
- function normalizeContextInput(input) {
44
- if (typeof input === "string") {
45
- return { name: input };
46
- }
47
- return {
48
- name: input.name,
49
- optional: input.optional,
50
- warnings: input.warnings,
51
- max_size: input.max_size,
52
- trim: input.trim,
53
- allow_regex: normalizeContextRegex(input.allow_regex),
54
- deny_regex: normalizeContextRegex(input.deny_regex),
55
- non_empty: normalizeBuiltInValidator(input.non_empty),
56
- reject_secrets: normalizeBuiltInValidator(input.reject_secrets)
57
- };
58
- }
59
- function areContextInputWarningsEnabled(input) {
60
- return input.warnings !== false;
61
- }
62
- function normalizeContextRegex(value) {
63
- if (value === void 0) {
64
- return void 0;
65
- }
66
- if (typeof value === "string") {
67
- const literal = parseRegexLiteral(value);
68
- if (value.startsWith("/") && !literal) {
69
- return {
70
- pattern: value,
71
- flags: "",
72
- raw: value,
73
- invalidLiteral: true
74
- };
75
- }
76
- return {
77
- pattern: literal?.pattern ?? value,
78
- flags: literal?.flags ?? "",
79
- raw: value
80
- };
81
- }
82
- return {
83
- pattern: value.pattern,
84
- flags: value.flags ?? "",
85
- raw: JSON.stringify(value),
86
- returnMessage: value.return_message
87
- };
88
- }
89
- function normalizeBuiltInValidator(value) {
90
- if (value === void 0 || value === false) {
91
- return void 0;
92
- }
93
- if (value === true) {
94
- return {};
95
- }
96
- return {
97
- returnMessage: value.return_message
98
- };
99
- }
100
- function parseRegexLiteral(value) {
101
- if (!value.startsWith("/")) {
102
- return void 0;
103
- }
104
- for (let index = value.length - 1; index > 0; index -= 1) {
105
- if (value[index] !== "/") {
106
- continue;
107
- }
108
- let backslashCount = 0;
109
- for (let cursor = index - 1; cursor >= 0 && value[cursor] === "\\"; cursor -= 1) {
110
- backslashCount += 1;
111
- }
112
- if (backslashCount % 2 === 1) {
113
- continue;
114
- }
115
- return {
116
- pattern: value.slice(1, index),
117
- flags: value.slice(index + 1)
118
- };
119
- }
120
- return void 0;
121
- }
122
- function formatInvalidContextRegexMessage(details) {
123
- return [
124
- `Invalid context regex for prompt "${details.promptId}"`,
125
- `variable "${details.variable}"`,
126
- `field "${details.field}"`,
127
- `value ${JSON.stringify(details.raw)}: ${details.reason}`
128
- ].join(", ");
129
- }
130
- function compileContextRegex(regex, details) {
131
- if (regex.invalidLiteral) {
132
- throw new Error(
133
- `POK013: ${formatInvalidContextRegexMessage({
134
- ...details,
135
- raw: regex.raw,
136
- reason: "Malformed regex literal. Use /pattern/flags or { pattern, flags }."
137
- })}`
138
- );
139
- }
140
- try {
141
- return new RegExp(regex.pattern, regex.flags);
142
- } catch (error) {
143
- const reason = error instanceof Error ? error.message : String(error);
144
- throw new Error(`POK013: ${formatInvalidContextRegexMessage({ ...details, raw: regex.raw, reason })}`);
145
- }
146
- }
147
- function getRejectSecretsRegex() {
148
- return {
149
- pattern: REJECT_SECRETS_PATTERN,
150
- flags: REJECT_SECRETS_FLAGS,
151
- raw: JSON.stringify({ pattern: REJECT_SECRETS_PATTERN, flags: REJECT_SECRETS_FLAGS })
152
- };
153
- }
154
- function isTrimEnabled(mode) {
155
- return mode === true || mode === "start" || mode === "end" || mode === "both";
156
- }
157
- function normalizeTrimMode(mode) {
158
- if (mode === "start") {
159
- return "start";
160
- }
161
- return "end";
162
- }
163
- function trimToMaxSize(value, maxSize, mode) {
164
- const measured = measureContextValueSize(value);
165
- if (measured <= maxSize) {
166
- return value;
167
- }
168
- const characters = Array.from(value);
169
- const normalizedMode = normalizeTrimMode(mode);
170
- if (normalizedMode === "start") {
171
- let collected2 = "";
172
- let size2 = 0;
173
- for (let i = characters.length - 1; i >= 0; i -= 1) {
174
- const next = characters[i];
175
- const charSize = measureContextValueSize(next);
176
- if (size2 + charSize > maxSize) {
177
- break;
178
- }
179
- collected2 = next + collected2;
180
- size2 += charSize;
181
- }
182
- return collected2;
183
- }
184
- let collected = "";
185
- let size = 0;
186
- for (const char of characters) {
187
- const charSize = measureContextValueSize(char);
188
- if (size + charSize > maxSize) {
189
- break;
190
- }
191
- collected += char;
192
- size += charSize;
193
- }
194
- return collected;
195
- }
196
- function sanitizeContextVariables(asset, variables = {}, options = {}) {
197
- const { onContextOverflow } = options;
198
- const sanitized = { ...variables };
199
- for (const input of getContextInputs(asset)) {
200
- const value = sanitized[input.name];
201
- if (value === void 0) {
202
- continue;
203
- }
204
- let candidate = value;
205
- if (input.max_size !== void 0) {
206
- const actualSize = measureContextValueSize(candidate);
207
- if (actualSize > input.max_size && onContextOverflow) {
208
- candidate = onContextOverflow({
209
- promptId: asset.id,
210
- variable: input.name,
211
- value: candidate,
212
- maxSize: input.max_size,
213
- actualSize
214
- });
215
- }
216
- }
217
- if (isTrimEnabled(input.trim) && input.max_size !== void 0) {
218
- candidate = trimToMaxSize(candidate, input.max_size, input.trim);
219
- }
220
- sanitized[input.name] = candidate;
221
- if (input.allow_regex) {
222
- const candidate2 = sanitized[input.name];
223
- const matcher = compileContextRegex(input.allow_regex, {
224
- promptId: asset.id,
225
- variable: input.name,
226
- field: "allow_regex"
227
- });
228
- if (!matcher.test(candidate2)) {
229
- if (input.allow_regex.returnMessage) {
230
- return {
231
- variables: sanitized,
232
- shortCircuit: {
233
- returnMessage: input.allow_regex.returnMessage,
234
- code: "POK031",
235
- variable: input.name,
236
- field: "allow_regex"
237
- }
238
- };
239
- }
240
- throw new Error(
241
- `POK031: Context variable "${input.name}" failed allow_regex validation for prompt "${asset.id}".`
242
- );
243
- }
244
- }
245
- if (input.deny_regex) {
246
- const candidate2 = sanitized[input.name];
247
- const matcher = compileContextRegex(input.deny_regex, {
248
- promptId: asset.id,
249
- variable: input.name,
250
- field: "deny_regex"
251
- });
252
- if (matcher.test(candidate2)) {
253
- if (input.deny_regex.returnMessage) {
254
- return {
255
- variables: sanitized,
256
- shortCircuit: {
257
- returnMessage: input.deny_regex.returnMessage,
258
- code: "POK032",
259
- variable: input.name,
260
- field: "deny_regex"
261
- }
262
- };
263
- }
264
- throw new Error(
265
- `POK032: Context variable "${input.name}" matched deny_regex for prompt "${asset.id}".`
266
- );
267
- }
268
- }
269
- if (input.non_empty && candidate.trim().length === 0) {
270
- if (input.non_empty.returnMessage) {
271
- return {
272
- variables: sanitized,
273
- shortCircuit: {
274
- returnMessage: input.non_empty.returnMessage,
275
- code: "POK033",
276
- variable: input.name,
277
- field: "non_empty"
278
- }
279
- };
280
- }
281
- throw new Error(
282
- `POK033: Context variable "${input.name}" failed non_empty validation for prompt "${asset.id}".`
283
- );
284
- }
285
- if (input.reject_secrets) {
286
- const matcher = compileContextRegex(getRejectSecretsRegex(), {
287
- promptId: asset.id,
288
- variable: input.name,
289
- field: "reject_secrets"
290
- });
291
- if (matcher.test(candidate)) {
292
- if (input.reject_secrets.returnMessage) {
293
- return {
294
- variables: sanitized,
295
- shortCircuit: {
296
- returnMessage: input.reject_secrets.returnMessage,
297
- code: "POK034",
298
- variable: input.name,
299
- field: "reject_secrets"
300
- }
301
- };
302
- }
303
- throw new Error(
304
- `POK034: Context variable "${input.name}" matched reject_secrets validation for prompt "${asset.id}".`
305
- );
306
- }
307
- }
308
- }
309
- return { variables: sanitized };
310
- }
311
- function measureContextValueSize(value) {
312
- return textEncoder.encode(value).length;
313
- }
314
- function collectContextSizeWarnings(asset, variables = {}) {
315
- const warnings = [];
316
- for (const input of getContextInputs(asset)) {
317
- if (!areContextInputWarningsEnabled(input)) {
318
- continue;
319
- }
320
- if (input.max_size === void 0) {
321
- continue;
322
- }
323
- const value = variables[input.name];
324
- if (value === void 0) {
325
- continue;
326
- }
327
- const actualSize = measureContextValueSize(value);
328
- if (actualSize > input.max_size) {
329
- warnings.push({
330
- variable: input.name,
331
- maxSize: input.max_size,
332
- actualSize
333
- });
334
- }
335
- }
336
- return warnings;
337
- }
338
-
339
- // src/renderer/renderer.ts
340
- function renderSections(asset, options = {}) {
341
- const { variables = {}, strict = false } = options;
342
- const optionalVariables = getContextInputs(asset).filter((input) => input.optional === true).map((input) => input.name);
343
- const result = {};
344
- if (asset.sections.system_instructions) {
345
- result.system_instructions = interpolate(
346
- asset.sections.system_instructions,
347
- variables,
348
- { strict, optionalVariables }
349
- );
350
- }
351
- if (asset.sections.prompt_template) {
352
- result.prompt_template = interpolate(
353
- asset.sections.prompt_template,
354
- variables,
355
- { strict, optionalVariables }
356
- );
357
- }
358
- return result;
359
- }
360
-
361
- // src/overrides/apply-overrides.ts
362
- function applyOverrides(asset, options = {}) {
363
- let result = { ...asset };
364
- if (options.environment && result.environments?.[options.environment]) {
365
- result = mergeOverride(result, result.environments[options.environment]);
366
- }
367
- if (options.tier && result.tiers?.[options.tier]) {
368
- result = mergeOverride(result, result.tiers[options.tier]);
369
- }
370
- if (options.runtime) {
371
- result = mergeOverride(result, options.runtime);
372
- }
373
- return result;
374
- }
375
- function mergeOverride(base, override) {
376
- const result = { ...base };
377
- if (override.model !== void 0) result.model = override.model;
378
- if (override.fallback_models !== void 0) result.fallback_models = override.fallback_models;
379
- if (override.tools !== void 0) result.tools = override.tools;
380
- if (override.reasoning !== void 0) {
381
- result.reasoning = { ...result.reasoning, ...override.reasoning };
382
- }
383
- if (override.sampling !== void 0) {
384
- result.sampling = { ...result.sampling, ...override.sampling };
385
- }
386
- if (override.response !== void 0) {
387
- result.response = { ...result.response, ...override.response };
388
- }
389
- if (override.compression !== void 0) {
390
- result.compression = {
391
- ...result.compression,
392
- ...override.compression,
393
- thetokencompany: mergeRecordBlock(
394
- result.compression?.thetokencompany,
395
- override.compression.thetokencompany
396
- )
397
- };
398
- }
399
- if (override.cache !== void 0) {
400
- result.cache = {
401
- ...result.cache,
402
- ...override.cache,
403
- openai: mergeRecordBlock(result.cache?.openai, override.cache.openai),
404
- anthropic: mergeRecordBlock(result.cache?.anthropic, override.cache.anthropic),
405
- gemini: mergeRecordBlock(result.cache?.gemini, override.cache.gemini),
406
- google: mergeRecordBlock(result.cache?.google, override.cache.google)
407
- };
408
- }
409
- if (override.raw !== void 0) {
410
- result.raw = {
411
- ...result.raw,
412
- ...override.raw,
413
- openai: mergeRecordBlock(result.raw?.openai, override.raw.openai),
414
- "openai-responses": mergeRecordBlock(result.raw?.["openai-responses"], override.raw["openai-responses"]),
415
- openai_responses: mergeRecordBlock(result.raw?.openai_responses, override.raw.openai_responses),
416
- anthropic: mergeRecordBlock(result.raw?.anthropic, override.raw.anthropic),
417
- gemini: mergeRecordBlock(result.raw?.gemini, override.raw.gemini),
418
- google: mergeRecordBlock(result.raw?.google, override.raw.google),
419
- openrouter: mergeRecordBlock(result.raw?.openrouter, override.raw.openrouter),
420
- llmasaservice: mergeRecordBlock(result.raw?.llmasaservice, override.raw.llmasaservice)
421
- };
422
- }
423
- if (override.provider_options !== void 0) {
424
- result.provider_options = {
425
- ...result.provider_options,
426
- ...override.provider_options,
427
- anthropic: {
428
- ...result.provider_options?.anthropic,
429
- ...override.provider_options.anthropic
430
- },
431
- gemini: {
432
- ...result.provider_options?.gemini,
433
- ...override.provider_options.gemini
434
- },
435
- openrouter: {
436
- ...result.provider_options?.openrouter,
437
- ...override.provider_options.openrouter
438
- },
439
- llmasaservice: {
440
- ...result.provider_options?.llmasaservice,
441
- ...override.provider_options.llmasaservice
442
- }
443
- };
444
- }
445
- return result;
446
- }
447
- function mergeRecordBlock(base, override) {
448
- if (override === void 0) return base;
449
- return { ...base, ...override };
450
- }
451
-
452
- // src/providers/resolve-asset.ts
453
- function resolveAssetForProvider(asset, runtime = {}) {
454
- if (!runtime.environment && !runtime.tier && !runtime.runtime) {
455
- return asset;
456
- }
457
- return applyOverrides(asset, {
458
- environment: runtime.environment,
459
- tier: runtime.tier,
460
- runtime: runtime.runtime
461
- });
462
- }
463
-
464
- // src/cache.ts
465
- import { statSync } from "fs";
466
- var PromptCache = class {
467
- cache = /* @__PURE__ */ new Map();
468
- maxSize;
469
- constructor(maxSize = 100) {
470
- this.maxSize = maxSize;
471
- }
472
- get(filePath) {
473
- const entry = this.cache.get(filePath);
474
- if (!entry) return void 0;
475
- try {
476
- const stat = statSync(filePath);
477
- if (stat.mtimeMs !== entry.mtime) {
478
- this.cache.delete(filePath);
479
- return void 0;
480
- }
481
- } catch {
482
- this.cache.delete(filePath);
483
- return void 0;
484
- }
485
- this.cache.delete(filePath);
486
- this.cache.set(filePath, entry);
487
- return entry.value;
488
- }
489
- set(filePath, value) {
490
- try {
491
- const stat = statSync(filePath);
492
- if (this.cache.has(filePath)) {
493
- this.cache.delete(filePath);
494
- } else if (this.cache.size >= this.maxSize) {
495
- const oldest = this.cache.keys().next().value;
496
- if (oldest) this.cache.delete(oldest);
497
- }
498
- this.cache.set(filePath, { value, mtime: stat.mtimeMs });
499
- } catch {
500
- }
501
- }
502
- clear() {
503
- this.cache.clear();
504
- }
505
- get size() {
506
- return this.cache.size;
507
- }
508
- };
509
-
510
- // src/composition/resolve-includes.ts
511
- import { readFile } from "fs/promises";
512
- import { resolve, dirname } from "path";
513
- async function resolveIncludes(asset, basePath, visited = /* @__PURE__ */ new Set()) {
514
- if (!asset.includes || asset.includes.length === 0) {
515
- return asset;
516
- }
517
- const baseDir = dirname(basePath);
518
- const resolvedPath = resolve(basePath);
519
- if (visited.has(resolvedPath)) {
520
- throw new Error(`Circular include detected: ${resolvedPath}`);
521
- }
522
- visited.add(resolvedPath);
523
- let mergedSystemInstructions = "";
524
- for (const includePath of asset.includes) {
525
- const fullPath = resolve(baseDir, includePath);
526
- if (visited.has(fullPath)) {
527
- throw new Error(`Circular include detected: ${fullPath} (included from ${basePath})`);
528
- }
529
- const content = await readFile(fullPath, "utf-8");
530
- const { asset: includedAsset } = parsePrompt(content, fullPath);
531
- const resolved = await resolveIncludes(includedAsset, fullPath, new Set(visited));
532
- if (resolved.sections?.system_instructions) {
533
- mergedSystemInstructions += resolved.sections.system_instructions + "\n\n";
534
- }
535
- }
536
- const localSystem = asset.sections?.system_instructions ?? "";
537
- const combinedSystem = (mergedSystemInstructions + localSystem).trim() || void 0;
538
- return {
539
- ...asset,
540
- sections: {
541
- ...asset.sections,
542
- system_instructions: combinedSystem
543
- },
544
- // Drop includes from the resolved asset — they've been inlined
545
- includes: void 0
546
- };
547
- }
548
-
549
- // src/prompt-resolution.ts
550
- import { readFile as readFile2 } from "fs/promises";
551
- import { existsSync, statSync as statSync2 } from "fs";
552
- import { resolve as resolve2 } from "path";
553
- var DEFAULT_PROMPTS_DIR = "./prompts";
554
- var DEFAULT_COMPILED_JSON_DIR = "./.generated-prompts/json";
555
- function withPromptResolutionDefaults(config) {
556
- return {
557
- ...config,
558
- sourceDir: config.sourceDir ?? DEFAULT_PROMPTS_DIR,
559
- compiledDir: config.compiledDir ?? DEFAULT_COMPILED_JSON_DIR
560
- };
561
- }
562
- var sharedPromptCache = new PromptCache();
563
- async function loadPromptAsset(promptPath, config, promptCache = sharedPromptCache) {
564
- const resolvedConfig = withPromptResolutionDefaults(config);
565
- const mode = resolvedConfig.mode ?? "auto";
566
- if (mode !== "source-only" && resolvedConfig.compiledDir) {
567
- const compiledFile = resolve2(resolvedConfig.compiledDir, promptPath + ".json");
568
- if (existsSync(compiledFile)) {
569
- if (mode === "auto") {
570
- const sourceFile = resolve2(resolvedConfig.sourceDir, promptPath + ".md");
571
- if (existsSync(sourceFile)) {
572
- const compiledMtime = statSync2(compiledFile).mtimeMs;
573
- const sourceMtime = statSync2(sourceFile).mtimeMs;
574
- if (sourceMtime > compiledMtime) {
575
- console.warn(
576
- `[promptopskit] Warning: compiled artifact for "${promptPath}" is older than source .md file.
577
- Run "promptopskit compile" or switch to source-only mode.`
578
- );
579
- }
580
- }
581
- }
582
- const content = await readFile2(compiledFile, "utf-8");
583
- return JSON.parse(content);
584
- }
585
- if (mode === "compiled-only") {
586
- throw new Error(
587
- `Compiled artifact not found: ${compiledFile}
588
- Run "promptopskit compile" to generate it.`
589
- );
590
- }
591
- }
592
- if (mode !== "compiled-only") {
593
- const sourceFile = resolve2(resolvedConfig.sourceDir, promptPath + ".md");
594
- if (resolvedConfig.cache !== false) {
595
- const cached = promptCache.get(sourceFile);
596
- if (cached) {
597
- return cached;
598
- }
599
- }
600
- if (!existsSync(sourceFile)) {
601
- const paths = [sourceFile];
602
- if (resolvedConfig.compiledDir) {
603
- paths.unshift(resolve2(resolvedConfig.compiledDir, promptPath + ".json"));
604
- }
605
- throw new Error(
606
- `Prompt not found: "${promptPath}"
607
- Searched:
608
- ${paths.map((candidate) => ` - ${candidate}`).join("\n")}`
609
- );
610
- }
611
- const { asset } = await loadPromptFile(sourceFile, { defaultsRoot: resolvedConfig.sourceDir });
612
- if (resolvedConfig.cache !== false) {
613
- promptCache.set(sourceFile, asset);
614
- }
615
- return asset;
616
- }
617
- throw new Error(`Prompt not found: "${promptPath}"`);
618
- }
619
- async function resolvePromptAsset(promptPath, config, options = {}, promptCache = sharedPromptCache) {
620
- const resolvedConfig = withPromptResolutionDefaults(config);
621
- let asset = await loadPromptAsset(promptPath, resolvedConfig, promptCache);
622
- const sourceFile = resolve2(resolvedConfig.sourceDir, promptPath + ".md");
623
- if (asset.includes && asset.includes.length > 0 && existsSync(sourceFile)) {
624
- asset = await resolveIncludes(asset, sourceFile);
625
- }
626
- asset = applyOverrides(asset, {
627
- environment: options.environment,
628
- tier: options.tier,
629
- runtime: options.runtime
630
- });
631
- return asset;
632
- }
633
- function resolveInlinePromptSource(source, options = {}) {
634
- const { asset } = parsePrompt(source);
635
- return applyOverrides(asset, {
636
- environment: options.environment,
637
- tier: options.tier,
638
- runtime: options.runtime
639
- });
640
- }
641
-
642
- // src/history.ts
643
- function defaultCompactHistory(info) {
644
- const content = info.overflow.map((message) => `${message.role}: ${message.content}`).join("\n\n");
645
- return {
646
- role: "user",
647
- content: `Earlier conversation compacted to preserve history:
648
-
649
- ${content}`
650
- };
651
- }
652
- function normalizeCompactionResult(result) {
653
- if (typeof result === "string") {
654
- return {
655
- role: "user",
656
- content: result
657
- };
658
- }
659
- return result;
660
- }
661
- function compactHistoryForPrompt(asset, runtime) {
662
- const history = runtime.history;
663
- const maxItems = asset.context?.history?.max_items;
664
- if (!history || maxItems === void 0 || history.length <= maxItems) {
665
- return history;
666
- }
667
- if (maxItems === 1) {
668
- const info2 = {
669
- promptId: asset.id,
670
- maxItems,
671
- overflow: history,
672
- preserved: [],
673
- history
674
- };
675
- const compacted2 = runtime.onHistoryCompaction ? normalizeCompactionResult(runtime.onHistoryCompaction(info2)) : defaultCompactHistory(info2);
676
- return [compacted2];
677
- }
678
- const preservedCount = maxItems - 1;
679
- const overflow = history.slice(0, history.length - preservedCount);
680
- const preserved = history.slice(-preservedCount);
681
- const info = {
682
- promptId: asset.id,
683
- maxItems,
684
- overflow,
685
- preserved,
686
- history
687
- };
688
- const compacted = runtime.onHistoryCompaction ? normalizeCompactionResult(runtime.onHistoryCompaction(info)) : defaultCompactHistory(info);
689
- return [compacted, ...preserved];
690
- }
691
-
692
- // src/compression.ts
693
- var THETOKENCOMPANY_DEFAULT_MODEL = "bear-2";
694
- var THETOKENCOMPANY_DEFAULT_BASE_URL = "https://api.thetokencompany.com";
695
- async function applyPromptCompressionForRender(asset, runtime) {
696
- const config = asset.compression?.thetokencompany;
697
- if (config?.enabled !== true || !asset.sections.prompt_template) {
698
- return { asset, runtime, compression: [] };
699
- }
700
- const sections = renderSections(asset, {
701
- variables: runtime.variables,
702
- strict: runtime.strict
703
- });
704
- if (!sections.prompt_template) {
705
- return { asset, runtime, compression: [] };
706
- }
707
- const model = config.model ?? THETOKENCOMPANY_DEFAULT_MODEL;
708
- const result = await compressWithTheTokenCompany(sections.prompt_template, {
709
- apiKey: runtime.theTokenCompany?.apiKey,
710
- baseURL: runtime.theTokenCompany?.baseURL,
711
- fetch: runtime.theTokenCompany?.fetch,
712
- model,
713
- aggressiveness: config.aggressiveness
714
- });
715
- return {
716
- asset: {
717
- ...asset,
718
- sections: {
719
- ...asset.sections,
720
- ...sections,
721
- prompt_template: result.output
722
- }
723
- },
724
- runtime: {
725
- ...runtime,
726
- variables: {},
727
- strict: false
728
- },
729
- compression: [{
730
- provider: "thetokencompany",
731
- model,
732
- inputTokens: result.input_tokens,
733
- outputTokens: result.output_tokens,
734
- tokensSaved: result.tokens_saved,
735
- compressionRatio: result.compression_ratio
736
- }]
737
- };
738
- }
739
- async function compressWithTheTokenCompany(input, options) {
740
- const apiKey = options.apiKey ?? getEnv("THETOKENCOMPANY_API_KEY") ?? getEnv("TTC_API_KEY");
741
- if (!apiKey) {
742
- throw new Error(
743
- "TheTokenCompany compression is enabled, but no API key was provided. Pass theTokenCompany.apiKey to renderPrompt() or set THETOKENCOMPANY_API_KEY."
744
- );
745
- }
746
- const fetchImpl = options.fetch ?? globalThis.fetch;
747
- if (!fetchImpl) {
748
- throw new Error("TheTokenCompany compression requires a runtime with fetch support.");
749
- }
750
- const baseURL = (options.baseURL ?? THETOKENCOMPANY_DEFAULT_BASE_URL).replace(/\/+$/, "");
751
- const compressionSettings = options.aggressiveness === void 0 ? void 0 : { aggressiveness: options.aggressiveness };
752
- const response = await fetchImpl(`${baseURL}/v1/compress`, {
753
- method: "POST",
754
- headers: {
755
- Authorization: `Bearer ${apiKey}`,
756
- "Content-Type": "application/json"
757
- },
758
- body: JSON.stringify({
759
- model: options.model,
760
- input,
761
- ...compressionSettings ? { compression_settings: compressionSettings } : {}
762
- })
763
- });
764
- if (!response.ok) {
765
- const body = await response.text().catch(() => "");
766
- throw new Error(
767
- `TheTokenCompany compression failed with HTTP ${response.status}` + (body ? `: ${body}` : ".")
768
- );
769
- }
770
- const data = await response.json();
771
- if (typeof data.output !== "string" || typeof data.output_tokens !== "number" || typeof data.input_tokens !== "number" || typeof data.tokens_saved !== "number" || typeof data.compression_ratio !== "number") {
772
- throw new Error("TheTokenCompany compression returned an invalid response payload.");
773
- }
774
- return data;
775
- }
776
- function getEnv(name) {
777
- if (typeof process === "undefined") {
778
- return void 0;
779
- }
780
- return process.env[name];
781
- }
782
-
783
- // src/providers/prompt-input.ts
784
- function isPromptLookup(input) {
785
- return "path" in input && typeof input.path === "string";
786
- }
787
- function isInlinePromptSource(input) {
788
- return "source" in input && typeof input.source === "string";
789
- }
790
- async function resolveProviderPromptInput(input, runtime) {
791
- if (isPromptLookup(input)) {
792
- return resolvePromptAsset(input.path, input, runtime);
793
- }
794
- if (isInlinePromptSource(input)) {
795
- return resolveInlinePromptSource(input.source, runtime);
796
- }
797
- return input;
798
- }
799
- function withPromptInputSupport(adapter) {
800
- const validatePrompt = async (input, runtime) => {
801
- const resolved = await resolveProviderPromptInput(input, runtime);
802
- return adapter.validate(resolved, runtime);
803
- };
804
- const renderPrompt = async (input, runtime) => {
805
- const resolved = await resolveProviderPromptInput(input, runtime);
806
- const resolvedForRender = resolveAssetForProvider(resolved, runtime);
807
- const sanitization = sanitizeContextVariables(resolvedForRender, runtime.variables, {
808
- onContextOverflow: runtime.onContextOverflow
809
- });
810
- if (sanitization.shortCircuit) {
811
- return {
812
- provider: adapter.name,
813
- model: resolvedForRender.model ?? "",
814
- returnMessage: sanitization.shortCircuit.returnMessage
815
- };
816
- }
817
- const prepared = await applyPromptCompressionForRender(resolvedForRender, {
818
- ...runtime,
819
- environment: void 0,
820
- tier: void 0,
821
- runtime: void 0,
822
- variables: sanitization.variables,
823
- history: compactHistoryForPrompt(resolvedForRender, runtime)
824
- });
825
- const request = adapter.render(prepared.asset, prepared.runtime);
826
- return prepared.compression.length > 0 ? { ...request, compression: prepared.compression } : request;
827
- };
828
- return {
829
- ...adapter,
830
- validatePrompt,
831
- renderPrompt
832
- };
833
- }
834
-
835
- // src/providers/raw.ts
836
- function applyRawProviderBody(body, asset, provider) {
837
- const raw = getRawProviderBody(asset, provider);
838
- return raw ? { ...body, ...raw } : body;
839
- }
840
- function getRawProviderBody(asset, provider) {
841
- if (provider === "openai-responses") {
842
- return asset.raw?.["openai-responses"] ?? asset.raw?.openai_responses;
843
- }
844
- if (provider === "gemini") {
845
- return asset.raw?.gemini ?? asset.raw?.google;
846
- }
847
- return asset.raw?.[provider];
848
- }
849
-
850
- export {
851
- interpolate,
852
- extractVariables,
853
- getContextInputs,
854
- areContextInputWarningsEnabled,
855
- compileContextRegex,
856
- sanitizeContextVariables,
857
- collectContextSizeWarnings,
858
- renderSections,
859
- applyOverrides,
860
- resolveAssetForProvider,
861
- PromptCache,
862
- resolveIncludes,
863
- DEFAULT_PROMPTS_DIR,
864
- withPromptResolutionDefaults,
865
- loadPromptAsset,
866
- resolvePromptAsset,
867
- resolveInlinePromptSource,
868
- compactHistoryForPrompt,
869
- THETOKENCOMPANY_DEFAULT_MODEL,
870
- THETOKENCOMPANY_DEFAULT_BASE_URL,
871
- applyPromptCompressionForRender,
872
- withPromptInputSupport,
873
- applyRawProviderBody
874
- };
875
- //# sourceMappingURL=chunk-F552OBUV.js.map