@warlock.js/ai 4.6.0 → 4.7.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 (44) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/cjs/index.cjs +3 -1
  3. package/cjs/{src-Bmajk4Qg.cjs → src-DBn2_pbG.cjs} +1 -1
  4. package/cjs/{src-OZyDYHxm.cjs → src-DTlN47aO.cjs} +552 -17
  5. package/cjs/src-DTlN47aO.cjs.map +1 -0
  6. package/esm/agent/agent-input-builder.mjs +1 -0
  7. package/esm/agent/agent-input-builder.mjs.map +1 -1
  8. package/esm/contracts/index.d.mts +1 -1
  9. package/esm/contracts/system-prompt.contract.d.mts +148 -1
  10. package/esm/contracts/system-prompt.contract.d.mts.map +1 -1
  11. package/esm/errors/error-code.type.d.mts +1 -1
  12. package/esm/errors/index.d.mts +1 -0
  13. package/esm/errors/index.mjs +1 -0
  14. package/esm/errors/prompt-refinement-error.d.mts +36 -0
  15. package/esm/errors/prompt-refinement-error.d.mts.map +1 -0
  16. package/esm/errors/prompt-refinement-error.mjs +27 -0
  17. package/esm/errors/prompt-refinement-error.mjs.map +1 -0
  18. package/esm/index.d.mts +4 -2
  19. package/esm/index.mjs +3 -1
  20. package/esm/prompts/prompts-manager.d.mts.map +1 -1
  21. package/esm/prompts/prompts-manager.mjs +1 -1
  22. package/esm/prompts/prompts-manager.mjs.map +1 -1
  23. package/esm/prompts/prompts-manager.type.d.mts +15 -0
  24. package/esm/prompts/prompts-manager.type.d.mts.map +1 -1
  25. package/esm/prompts/prompts-validate.mjs +0 -0
  26. package/esm/prompts/prompts-validate.mjs.map +1 -1
  27. package/esm/system-prompt/index.d.mts +1 -0
  28. package/esm/system-prompt/index.mjs +1 -0
  29. package/esm/system-prompt/refined-system-prompt.d.mts +184 -0
  30. package/esm/system-prompt/refined-system-prompt.d.mts.map +1 -0
  31. package/esm/system-prompt/refined-system-prompt.mjs +461 -0
  32. package/esm/system-prompt/refined-system-prompt.mjs.map +1 -0
  33. package/esm/system-prompt/system-prompt.d.mts +14 -1
  34. package/esm/system-prompt/system-prompt.d.mts.map +1 -1
  35. package/esm/system-prompt/system-prompt.mjs +19 -0
  36. package/esm/system-prompt/system-prompt.mjs.map +1 -1
  37. package/llms-full.txt +104 -1
  38. package/llms.txt +2 -1
  39. package/package.json +3 -3
  40. package/skills/README.md +4 -0
  41. package/skills/manage-prompts/SKILL.md +8 -1
  42. package/skills/refine-prompts/SKILL.md +91 -0
  43. package/skills/write-system-prompt/SKILL.md +1 -0
  44. package/cjs/src-OZyDYHxm.cjs.map +0 -1
@@ -40,6 +40,7 @@ async function buildAgentInputMessages(params) {
40
40
  let promptVersion;
41
41
  if (typeof systemPrompt === "string") systemContent = systemPrompt;
42
42
  else if (systemPrompt) {
43
+ if (typeof systemPrompt.materialize === "function") await systemPrompt.materialize();
43
44
  systemContent = systemPrompt.resolve(placeholders);
44
45
  const meta = systemPrompt.meta();
45
46
  if (meta?.name) {
@@ -1 +1 @@
1
- {"version":3,"file":"agent-input-builder.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/agent/agent-input-builder.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { AgentExecuteOptions } from \"../contracts/agent/agent-options.type\";\nimport type { AttachmentPolicy } from \"../contracts/attachment-policy.type\";\nimport type { Attachment } from \"../contracts/attachment.type\";\nimport type { ContentPart } from \"../contracts/content-part.type\";\nimport type { Message } from \"../contracts/conversation-message.type\";\nimport type { Placeholders } from \"../contracts/placeholders.type\";\nimport { InvalidRequestError } from \"../errors\";\nimport { extractJsonSchema, prepareAttachmentPart } from \"../utils\";\nimport type { AgentConfig } from \"./agent-config.type\";\n\n/**\n * Outcome of `buildAgentInputMessages` — the seeded message list and\n * the JSON Schema cached for every trip's\n * `ModelCallOptions.responseSchema`. `responseSchema` is `undefined`\n * when the caller didn't ask for structured output.\n */\nexport type AgentInputBuildResult = {\n messages: Message[];\n responseSchema?: Record<string, unknown>;\n /**\n * The resolved system-prompt text actually sent as the `role: \"system\"`\n * message (persona + instructions + any auto-appended structured-output\n * instruction). Captured for observability; absent when the agent ran\n * without a system prompt.\n */\n systemPrompt?: string;\n /**\n * Registry name of the `SystemPromptContract` the agent resolved, read from\n * its `meta().name`. Present only when the agent ran against a *named*\n * prompt (one registered in `ai.prompts`); absent for a raw-string prompt,\n * an anonymous contract, or no prompt at all. Lets observers attribute a run\n * to a specific prompt in the registry.\n */\n promptName?: string;\n /**\n * Registry version label of the named prompt the agent resolved, read from\n * its `meta().version` (defaulting to `\"1\"` when the prompt carries a name\n * but no explicit version, mirroring the registry's default). Present only\n * alongside {@link AgentInputBuildResult.promptName}.\n */\n promptVersion?: string;\n};\n\n/**\n * Assemble the seed conversation for an agent execution. Runs exactly\n * once per run — subsequent trips append to the same message list.\n *\n * Responsibilities (previously three methods on `Execution`):\n * 1. Merge factory + per-call placeholders.\n * 2. Resolve the system prompt (string, contract, or absent).\n * 3. When an output schema is supplied:\n * - cache its JSON Schema form for `ModelCallOptions.responseSchema`\n * so native-structured-output providers enforce it at the token\n * level;\n * - fall back to a soft system-prompt instruction for providers\n * that don't advertise `structuredOutput` capability.\n * 4. Append caller-supplied `history` (e.g. session-level prior turns).\n * 5. Shape the user message — plain string in the common case,\n * multipart `ContentPart[]` when `attachments` are present. Image\n * attachments require model vision capability; mismatch throws\n * `InvalidRequestError` here rather than failing opaquely at the\n * provider.\n *\n * Extracted from the `Execution` class to isolate the declarative\n * input-shaping phase from the stateful trip loop.\n */\nexport async function buildAgentInputMessages<TOutput>(params: {\n config: AgentConfig<TOutput>;\n input: string;\n options?: AgentExecuteOptions<TOutput>;\n}): Promise<AgentInputBuildResult> {\n const { config, input, options } = params;\n\n const placeholders: Placeholders = {\n ...config.placeholders,\n ...options?.placeholders,\n };\n\n const systemPrompt = options?.systemPrompt ?? config.systemPrompt;\n let systemContent = \"\";\n let promptName: string | undefined;\n let promptVersion: string | undefined;\n\n if (typeof systemPrompt === \"string\") {\n systemContent = systemPrompt;\n } else if (systemPrompt) {\n systemContent = systemPrompt.resolve(placeholders);\n\n // Capture prompt-version linkage from the contract's metadata: a *named*\n // prompt (one addressable in `ai.prompts`) stamps `promptName@version`\n // onto the run's report so observers can group runs by the exact prompt\n // version that produced them. Anonymous prompts carry no name and are\n // left unlinked.\n const meta = systemPrompt.meta();\n\n if (meta?.name) {\n promptName = meta.name;\n promptVersion = meta.version ?? \"1\";\n }\n }\n\n const { responseSchema, instruction } = resolveStructuredOutput({\n outputSchema: options?.output ?? config.output,\n overrideResponseSchema: options?.responseSchema,\n modelSupportsStructuredOutput: Boolean(config.model.capabilities?.structuredOutput),\n });\n\n if (instruction) {\n systemContent = systemContent ? `${systemContent}\\n\\n${instruction}` : instruction;\n }\n\n const messages: Message[] = [];\n\n if (systemContent) {\n messages.push({ role: \"system\", content: systemContent });\n }\n\n if (options?.history) {\n messages.push(...options.history);\n }\n\n const userContent = await buildUserMessageContent({\n input,\n attachments: options?.attachments,\n attachmentPolicy: options?.attachmentPolicy ?? config.attachmentPolicy,\n modelName: config.model.name,\n modelSupportsVision: Boolean(config.model.capabilities?.vision),\n modelSupportsPdf: Boolean(config.model.capabilities?.pdf),\n modelSupportsAudio: Boolean(config.model.capabilities?.audio),\n });\n\n messages.push({ role: \"user\", content: userContent });\n\n return {\n messages,\n responseSchema,\n systemPrompt: systemContent || undefined,\n promptName,\n promptVersion,\n };\n}\n\n/**\n * Build the user message `content` field. Plain string when no\n * attachments (the hot path) — keeps wire payloads small. Multipart\n * `ContentPart[]` when attachments exist: input text first, resolved\n * parts in declaration order.\n */\nasync function buildUserMessageContent(params: {\n input: string;\n attachments?: Attachment[];\n attachmentPolicy?: AttachmentPolicy;\n modelName: string;\n modelSupportsVision: boolean;\n modelSupportsPdf: boolean;\n modelSupportsAudio: boolean;\n}): Promise<string | ContentPart[]> {\n const {\n input,\n attachments,\n attachmentPolicy,\n modelName,\n modelSupportsVision,\n modelSupportsPdf,\n modelSupportsAudio,\n } = params;\n\n if (!attachments || attachments.length === 0) {\n return input;\n }\n\n const parts: ContentPart[] = await Promise.all(\n attachments.map((attachment) => prepareAttachmentPart(attachment, attachmentPolicy)),\n );\n\n // Capability gate per modality (A2) — reject an attachment the model\n // can't consume here, with a clear message, rather than failing opaquely\n // at the provider.\n assertModality(parts, \"image\", modelSupportsVision, \"vision\", modelName);\n assertModality(parts, \"pdf\", modelSupportsPdf, \"pdf\", modelName);\n assertModality(parts, \"audio\", modelSupportsAudio, \"audio\", modelName);\n\n return [{ type: \"text\", text: input }, ...parts];\n}\n\n/** Throw when a modality is present but the model doesn't declare it. */\nfunction assertModality(\n parts: ContentPart[],\n partType: ContentPart[\"type\"],\n supported: boolean,\n capability: string,\n modelName: string,\n): void {\n if (!supported && parts.some((part) => part.type === partType)) {\n throw new InvalidRequestError(\n `Model \"${modelName}\" does not declare ${capability} capability — ${partType} attachments are not supported`,\n { context: { modelName } },\n );\n }\n}\n\n/**\n * When the caller supplied an `output` schema, resolve two artifacts:\n *\n * - `responseSchema` — extracted JSON Schema to attach on every trip.\n * Adapters that natively support structured output (OpenAI's\n * `response_format: json_schema`) consume it; others ignore it.\n * - `instruction` — a soft fallback appended to the system prompt\n * **only** for models without native structured-output capability.\n * Capable adapters skip it to save tokens and avoid redundancy.\n */\nfunction resolveStructuredOutput(params: {\n outputSchema?: StandardSchemaV1<unknown>;\n overrideResponseSchema?: Record<string, unknown>;\n modelSupportsStructuredOutput: boolean;\n}): {\n responseSchema?: Record<string, unknown>;\n instruction?: string;\n} {\n const { outputSchema, overrideResponseSchema, modelSupportsStructuredOutput } = params;\n\n if (!outputSchema) {\n return {};\n }\n\n const responseSchema = overrideResponseSchema ?? extractJsonSchema(outputSchema);\n\n if (modelSupportsStructuredOutput) {\n return { responseSchema };\n }\n\n const schemaHint = responseSchema\n ? `\\n\\nThe response MUST match this JSON Schema:\\n${JSON.stringify(responseSchema, null, 2)}`\n : \"\";\n\n const instruction = [\n \"You MUST respond with a single valid JSON value only.\",\n \"Do not wrap it in markdown code fences. Do not include prose, commentary, or explanation — JSON only.\",\n schemaHint,\n ]\n .join(\"\")\n .trim();\n\n return { responseSchema, instruction };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmEA,eAAsB,wBAAiC,QAIpB;CACjC,MAAM,EAAE,QAAQ,OAAO,YAAY;CAEnC,MAAM,eAA6B;EACjC,GAAG,OAAO;EACV,GAAG,SAAS;CACd;CAEA,MAAM,eAAe,SAAS,gBAAgB,OAAO;CACrD,IAAI,gBAAgB;CACpB,IAAI;CACJ,IAAI;CAEJ,IAAI,OAAO,iBAAiB,UAC1B,gBAAgB;MACX,IAAI,cAAc;EACvB,gBAAgB,aAAa,QAAQ,YAAY;EAOjD,MAAM,OAAO,aAAa,KAAK;EAE/B,IAAI,MAAM,MAAM;GACd,aAAa,KAAK;GAClB,gBAAgB,KAAK,WAAW;EAClC;CACF;CAEA,MAAM,EAAE,gBAAgB,gBAAgB,wBAAwB;EAC9D,cAAc,SAAS,UAAU,OAAO;EACxC,wBAAwB,SAAS;EACjC,+BAA+B,QAAQ,OAAO,MAAM,cAAc,gBAAgB;CACpF,CAAC;CAED,IAAI,aACF,gBAAgB,gBAAgB,GAAG,cAAc,MAAM,gBAAgB;CAGzE,MAAM,WAAsB,CAAC;CAE7B,IAAI,eACF,SAAS,KAAK;EAAE,MAAM;EAAU,SAAS;CAAc,CAAC;CAG1D,IAAI,SAAS,SACX,SAAS,KAAK,GAAG,QAAQ,OAAO;CAGlC,MAAM,cAAc,MAAM,wBAAwB;EAChD;EACA,aAAa,SAAS;EACtB,kBAAkB,SAAS,oBAAoB,OAAO;EACtD,WAAW,OAAO,MAAM;EACxB,qBAAqB,QAAQ,OAAO,MAAM,cAAc,MAAM;EAC9D,kBAAkB,QAAQ,OAAO,MAAM,cAAc,GAAG;EACxD,oBAAoB,QAAQ,OAAO,MAAM,cAAc,KAAK;CAC9D,CAAC;CAED,SAAS,KAAK;EAAE,MAAM;EAAQ,SAAS;CAAY,CAAC;CAEpD,OAAO;EACL;EACA;EACA,cAAc,iBAAiB;EAC/B;EACA;CACF;AACF;;;;;;;AAQA,eAAe,wBAAwB,QAQH;CAClC,MAAM,EACJ,OACA,aACA,kBACA,WACA,qBACA,kBACA,uBACE;CAEJ,IAAI,CAAC,eAAe,YAAY,WAAW,GACzC,OAAO;CAGT,MAAM,QAAuB,MAAM,QAAQ,IACzC,YAAY,KAAK,eAAe,sBAAsB,YAAY,gBAAgB,CAAC,CACrF;CAKA,eAAe,OAAO,SAAS,qBAAqB,UAAU,SAAS;CACvE,eAAe,OAAO,OAAO,kBAAkB,OAAO,SAAS;CAC/D,eAAe,OAAO,SAAS,oBAAoB,SAAS,SAAS;CAErE,OAAO,CAAC;EAAE,MAAM;EAAQ,MAAM;CAAM,GAAG,GAAG,KAAK;AACjD;;AAGA,SAAS,eACP,OACA,UACA,WACA,YACA,WACM;CACN,IAAI,CAAC,aAAa,MAAM,MAAM,SAAS,KAAK,SAAS,QAAQ,GAC3D,MAAM,IAAI,oBACR,UAAU,UAAU,qBAAqB,WAAW,gBAAgB,SAAS,iCAC7E,EAAE,SAAS,EAAE,UAAU,EAAE,CAC3B;AAEJ;;;;;;;;;;;AAYA,SAAS,wBAAwB,QAO/B;CACA,MAAM,EAAE,cAAc,wBAAwB,kCAAkC;CAEhF,IAAI,CAAC,cACH,OAAO,CAAC;CAGV,MAAM,iBAAiB,0BAA0B,kBAAkB,YAAY;CAE/E,IAAI,+BACF,OAAO,EAAE,eAAe;CAe1B,OAAO;EAAE;EAAgB,aARL;GAClB;GACA;GANiB,iBACf,kDAAkD,KAAK,UAAU,gBAAgB,MAAM,CAAC,MACxF;EAMJ,CAAC,CACE,KAAK,EAAE,CAAC,CACR,KAEgC;CAAE;AACvC"}
1
+ {"version":3,"file":"agent-input-builder.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/agent/agent-input-builder.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport type { AgentExecuteOptions } from \"../contracts/agent/agent-options.type\";\nimport type { AttachmentPolicy } from \"../contracts/attachment-policy.type\";\nimport type { Attachment } from \"../contracts/attachment.type\";\nimport type { ContentPart } from \"../contracts/content-part.type\";\nimport type { Message } from \"../contracts/conversation-message.type\";\nimport type { Placeholders } from \"../contracts/placeholders.type\";\nimport { InvalidRequestError } from \"../errors\";\nimport { extractJsonSchema, prepareAttachmentPart } from \"../utils\";\nimport type { AgentConfig } from \"./agent-config.type\";\n\n/**\n * Outcome of `buildAgentInputMessages` — the seeded message list and\n * the JSON Schema cached for every trip's\n * `ModelCallOptions.responseSchema`. `responseSchema` is `undefined`\n * when the caller didn't ask for structured output.\n */\nexport type AgentInputBuildResult = {\n messages: Message[];\n responseSchema?: Record<string, unknown>;\n /**\n * The resolved system-prompt text actually sent as the `role: \"system\"`\n * message (persona + instructions + any auto-appended structured-output\n * instruction). Captured for observability; absent when the agent ran\n * without a system prompt.\n */\n systemPrompt?: string;\n /**\n * Registry name of the `SystemPromptContract` the agent resolved, read from\n * its `meta().name`. Present only when the agent ran against a *named*\n * prompt (one registered in `ai.prompts`); absent for a raw-string prompt,\n * an anonymous contract, or no prompt at all. Lets observers attribute a run\n * to a specific prompt in the registry.\n */\n promptName?: string;\n /**\n * Registry version label of the named prompt the agent resolved, read from\n * its `meta().version` (defaulting to `\"1\"` when the prompt carries a name\n * but no explicit version, mirroring the registry's default). Present only\n * alongside {@link AgentInputBuildResult.promptName}.\n */\n promptVersion?: string;\n};\n\n/**\n * Assemble the seed conversation for an agent execution. Runs exactly\n * once per run — subsequent trips append to the same message list.\n *\n * Responsibilities (previously three methods on `Execution`):\n * 1. Merge factory + per-call placeholders.\n * 2. Resolve the system prompt (string, contract, or absent).\n * 3. When an output schema is supplied:\n * - cache its JSON Schema form for `ModelCallOptions.responseSchema`\n * so native-structured-output providers enforce it at the token\n * level;\n * - fall back to a soft system-prompt instruction for providers\n * that don't advertise `structuredOutput` capability.\n * 4. Append caller-supplied `history` (e.g. session-level prior turns).\n * 5. Shape the user message — plain string in the common case,\n * multipart `ContentPart[]` when `attachments` are present. Image\n * attachments require model vision capability; mismatch throws\n * `InvalidRequestError` here rather than failing opaquely at the\n * provider.\n *\n * Extracted from the `Execution` class to isolate the declarative\n * input-shaping phase from the stateful trip loop.\n */\nexport async function buildAgentInputMessages<TOutput>(params: {\n config: AgentConfig<TOutput>;\n input: string;\n options?: AgentExecuteOptions<TOutput>;\n}): Promise<AgentInputBuildResult> {\n const { config, input, options } = params;\n\n const placeholders: Placeholders = {\n ...config.placeholders,\n ...options?.placeholders,\n };\n\n const systemPrompt = options?.systemPrompt ?? config.systemPrompt;\n let systemContent = \"\";\n let promptName: string | undefined;\n let promptVersion: string | undefined;\n\n if (typeof systemPrompt === \"string\") {\n systemContent = systemPrompt;\n } else if (systemPrompt) {\n // A lazily-compiled prompt (`systemPrompt.refined(...)`) finishes its\n // async work here, before the synchronous `resolve()` below — a no-op for\n // plain builders, and never throws (a failed refinement falls back to the\n // original text).\n if (typeof systemPrompt.materialize === \"function\") {\n await systemPrompt.materialize();\n }\n\n systemContent = systemPrompt.resolve(placeholders);\n\n // Capture prompt-version linkage from the contract's metadata: a *named*\n // prompt (one addressable in `ai.prompts`) stamps `promptName@version`\n // onto the run's report so observers can group runs by the exact prompt\n // version that produced them. Anonymous prompts carry no name and are\n // left unlinked.\n const meta = systemPrompt.meta();\n\n if (meta?.name) {\n promptName = meta.name;\n promptVersion = meta.version ?? \"1\";\n }\n }\n\n const { responseSchema, instruction } = resolveStructuredOutput({\n outputSchema: options?.output ?? config.output,\n overrideResponseSchema: options?.responseSchema,\n modelSupportsStructuredOutput: Boolean(config.model.capabilities?.structuredOutput),\n });\n\n if (instruction) {\n systemContent = systemContent ? `${systemContent}\\n\\n${instruction}` : instruction;\n }\n\n const messages: Message[] = [];\n\n if (systemContent) {\n messages.push({ role: \"system\", content: systemContent });\n }\n\n if (options?.history) {\n messages.push(...options.history);\n }\n\n const userContent = await buildUserMessageContent({\n input,\n attachments: options?.attachments,\n attachmentPolicy: options?.attachmentPolicy ?? config.attachmentPolicy,\n modelName: config.model.name,\n modelSupportsVision: Boolean(config.model.capabilities?.vision),\n modelSupportsPdf: Boolean(config.model.capabilities?.pdf),\n modelSupportsAudio: Boolean(config.model.capabilities?.audio),\n });\n\n messages.push({ role: \"user\", content: userContent });\n\n return {\n messages,\n responseSchema,\n systemPrompt: systemContent || undefined,\n promptName,\n promptVersion,\n };\n}\n\n/**\n * Build the user message `content` field. Plain string when no\n * attachments (the hot path) — keeps wire payloads small. Multipart\n * `ContentPart[]` when attachments exist: input text first, resolved\n * parts in declaration order.\n */\nasync function buildUserMessageContent(params: {\n input: string;\n attachments?: Attachment[];\n attachmentPolicy?: AttachmentPolicy;\n modelName: string;\n modelSupportsVision: boolean;\n modelSupportsPdf: boolean;\n modelSupportsAudio: boolean;\n}): Promise<string | ContentPart[]> {\n const {\n input,\n attachments,\n attachmentPolicy,\n modelName,\n modelSupportsVision,\n modelSupportsPdf,\n modelSupportsAudio,\n } = params;\n\n if (!attachments || attachments.length === 0) {\n return input;\n }\n\n const parts: ContentPart[] = await Promise.all(\n attachments.map((attachment) => prepareAttachmentPart(attachment, attachmentPolicy)),\n );\n\n // Capability gate per modality (A2) — reject an attachment the model\n // can't consume here, with a clear message, rather than failing opaquely\n // at the provider.\n assertModality(parts, \"image\", modelSupportsVision, \"vision\", modelName);\n assertModality(parts, \"pdf\", modelSupportsPdf, \"pdf\", modelName);\n assertModality(parts, \"audio\", modelSupportsAudio, \"audio\", modelName);\n\n return [{ type: \"text\", text: input }, ...parts];\n}\n\n/** Throw when a modality is present but the model doesn't declare it. */\nfunction assertModality(\n parts: ContentPart[],\n partType: ContentPart[\"type\"],\n supported: boolean,\n capability: string,\n modelName: string,\n): void {\n if (!supported && parts.some((part) => part.type === partType)) {\n throw new InvalidRequestError(\n `Model \"${modelName}\" does not declare ${capability} capability — ${partType} attachments are not supported`,\n { context: { modelName } },\n );\n }\n}\n\n/**\n * When the caller supplied an `output` schema, resolve two artifacts:\n *\n * - `responseSchema` — extracted JSON Schema to attach on every trip.\n * Adapters that natively support structured output (OpenAI's\n * `response_format: json_schema`) consume it; others ignore it.\n * - `instruction` — a soft fallback appended to the system prompt\n * **only** for models without native structured-output capability.\n * Capable adapters skip it to save tokens and avoid redundancy.\n */\nfunction resolveStructuredOutput(params: {\n outputSchema?: StandardSchemaV1<unknown>;\n overrideResponseSchema?: Record<string, unknown>;\n modelSupportsStructuredOutput: boolean;\n}): {\n responseSchema?: Record<string, unknown>;\n instruction?: string;\n} {\n const { outputSchema, overrideResponseSchema, modelSupportsStructuredOutput } = params;\n\n if (!outputSchema) {\n return {};\n }\n\n const responseSchema = overrideResponseSchema ?? extractJsonSchema(outputSchema);\n\n if (modelSupportsStructuredOutput) {\n return { responseSchema };\n }\n\n const schemaHint = responseSchema\n ? `\\n\\nThe response MUST match this JSON Schema:\\n${JSON.stringify(responseSchema, null, 2)}`\n : \"\";\n\n const instruction = [\n \"You MUST respond with a single valid JSON value only.\",\n \"Do not wrap it in markdown code fences. Do not include prose, commentary, or explanation — JSON only.\",\n schemaHint,\n ]\n .join(\"\")\n .trim();\n\n return { responseSchema, instruction };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmEA,eAAsB,wBAAiC,QAIpB;CACjC,MAAM,EAAE,QAAQ,OAAO,YAAY;CAEnC,MAAM,eAA6B;EACjC,GAAG,OAAO;EACV,GAAG,SAAS;CACd;CAEA,MAAM,eAAe,SAAS,gBAAgB,OAAO;CACrD,IAAI,gBAAgB;CACpB,IAAI;CACJ,IAAI;CAEJ,IAAI,OAAO,iBAAiB,UAC1B,gBAAgB;MACX,IAAI,cAAc;EAKvB,IAAI,OAAO,aAAa,gBAAgB,YACtC,MAAM,aAAa,YAAY;EAGjC,gBAAgB,aAAa,QAAQ,YAAY;EAOjD,MAAM,OAAO,aAAa,KAAK;EAE/B,IAAI,MAAM,MAAM;GACd,aAAa,KAAK;GAClB,gBAAgB,KAAK,WAAW;EAClC;CACF;CAEA,MAAM,EAAE,gBAAgB,gBAAgB,wBAAwB;EAC9D,cAAc,SAAS,UAAU,OAAO;EACxC,wBAAwB,SAAS;EACjC,+BAA+B,QAAQ,OAAO,MAAM,cAAc,gBAAgB;CACpF,CAAC;CAED,IAAI,aACF,gBAAgB,gBAAgB,GAAG,cAAc,MAAM,gBAAgB;CAGzE,MAAM,WAAsB,CAAC;CAE7B,IAAI,eACF,SAAS,KAAK;EAAE,MAAM;EAAU,SAAS;CAAc,CAAC;CAG1D,IAAI,SAAS,SACX,SAAS,KAAK,GAAG,QAAQ,OAAO;CAGlC,MAAM,cAAc,MAAM,wBAAwB;EAChD;EACA,aAAa,SAAS;EACtB,kBAAkB,SAAS,oBAAoB,OAAO;EACtD,WAAW,OAAO,MAAM;EACxB,qBAAqB,QAAQ,OAAO,MAAM,cAAc,MAAM;EAC9D,kBAAkB,QAAQ,OAAO,MAAM,cAAc,GAAG;EACxD,oBAAoB,QAAQ,OAAO,MAAM,cAAc,KAAK;CAC9D,CAAC;CAED,SAAS,KAAK;EAAE,MAAM;EAAQ,SAAS;CAAY,CAAC;CAEpD,OAAO;EACL;EACA;EACA,cAAc,iBAAiB;EAC/B;EACA;CACF;AACF;;;;;;;AAQA,eAAe,wBAAwB,QAQH;CAClC,MAAM,EACJ,OACA,aACA,kBACA,WACA,qBACA,kBACA,uBACE;CAEJ,IAAI,CAAC,eAAe,YAAY,WAAW,GACzC,OAAO;CAGT,MAAM,QAAuB,MAAM,QAAQ,IACzC,YAAY,KAAK,eAAe,sBAAsB,YAAY,gBAAgB,CAAC,CACrF;CAKA,eAAe,OAAO,SAAS,qBAAqB,UAAU,SAAS;CACvE,eAAe,OAAO,OAAO,kBAAkB,OAAO,SAAS;CAC/D,eAAe,OAAO,SAAS,oBAAoB,SAAS,SAAS;CAErE,OAAO,CAAC;EAAE,MAAM;EAAQ,MAAM;CAAM,GAAG,GAAG,KAAK;AACjD;;AAGA,SAAS,eACP,OACA,UACA,WACA,YACA,WACM;CACN,IAAI,CAAC,aAAa,MAAM,MAAM,SAAS,KAAK,SAAS,QAAQ,GAC3D,MAAM,IAAI,oBACR,UAAU,UAAU,qBAAqB,WAAW,gBAAgB,SAAS,iCAC7E,EAAE,SAAS,EAAE,UAAU,EAAE,CAC3B;AAEJ;;;;;;;;;;;AAYA,SAAS,wBAAwB,QAO/B;CACA,MAAM,EAAE,cAAc,wBAAwB,kCAAkC;CAEhF,IAAI,CAAC,cACH,OAAO,CAAC;CAGV,MAAM,iBAAiB,0BAA0B,kBAAkB,YAAY;CAE/E,IAAI,+BACF,OAAO,EAAE,eAAe;CAe1B,OAAO;EAAE;EAAgB,aARL;GAClB;GACA;GANiB,iBACf,kDAAkD,KAAK,UAAU,gBAAgB,MAAM,CAAC,MACxF;EAMJ,CAAC,CACE,KAAK,EAAE,CAAC,CACR,KAEgC;CAAE;AACvC"}
@@ -41,7 +41,7 @@ import { MiddlewareState } from "./middleware/middleware-state.type.mjs";
41
41
  import { MiddlewareAgentRef, MiddlewareExecuteContext, MiddlewareModelRef, MiddlewareSupervisorContext, MiddlewareSupervisorRef, MiddlewareToolContext, MiddlewareTripContext } from "./middleware/middleware-context.type.mjs";
42
42
  import { AgentMiddleware, AgentMiddlewareExecuteHooks, AgentMiddlewareSupervisorHooks, AgentMiddlewareToolHooks, AgentMiddlewareTripHooks } from "./middleware/middleware.contract.mjs";
43
43
  import { Placeholders } from "./placeholders.type.mjs";
44
- import { InstructionContract, PersonaContract, SystemPromptBlockContract, SystemPromptContract, SystemPromptMergeOptions, SystemPromptMergeSource, SystemPromptMeta } from "./system-prompt.contract.mjs";
44
+ import { InstructionContract, PersonaContract, PromptRefineOptions, RefinedPromptStoreLike, RefinedSystemPromptContract, RefinedSystemPromptOptions, SystemPromptBlockContract, SystemPromptContract, SystemPromptMergeOptions, SystemPromptMergeSource, SystemPromptMeta } from "./system-prompt.contract.mjs";
45
45
  import { RouteContext } from "./supervisor/route-context.type.mjs";
46
46
  import { AckCallback, AckConfig, AckEntry, AckRunEntry } from "./supervisor/ack-entry.type.mjs";
47
47
  import { DispatchRawResult, IntentCallback, IntentEntry, IntentRunEntry, SupervisorIntentValue } from "./supervisor/intent-entry.type.mjs";
@@ -1,3 +1,4 @@
1
+ import { ModelContract } from "./model.contract.mjs";
1
2
  import { Placeholders } from "./placeholders.type.mjs";
2
3
  import { PromptValidationResult, PromptsValidateOptions } from "../prompts/prompts-manager.type.mjs";
3
4
 
@@ -83,6 +84,14 @@ interface SystemPromptMeta {
83
84
  readonly composedFrom?: readonly string[];
84
85
  /** Placeholder keys callers must supply when resolving this prompt. */
85
86
  readonly required?: readonly string[];
87
+ /**
88
+ * Provenance label of the prompt this one was refined from (e.g.
89
+ * `"support@1"`, or `"anonymous"` for an unnamed source). Stamped by
90
+ * `refined(...).refinePrompt()` — never set by hand.
91
+ */
92
+ readonly refinedFrom?: string;
93
+ /** `provider:name` of the model that produced a refined prompt's text. */
94
+ readonly refinerModel?: string;
86
95
  }
87
96
  /**
88
97
  * Options for the registry-aware overload of {@link SystemPromptContract.merge}
@@ -101,6 +110,54 @@ interface SystemPromptMergeOptions {
101
110
  * instructions append), or a registered prompt name resolved from `ai.prompts`.
102
111
  */
103
112
  type SystemPromptMergeSource = SystemPromptBlockContract | SystemPromptContract | string;
113
+ /**
114
+ * Structural store a refined prompt pins its compiled text into — the same
115
+ * `get` / `set` subset of `@warlock.js/cache`'s `CacheDriver` that
116
+ * `PromptJudgeCacheLike` uses, so any cache driver satisfies it while
117
+ * `@warlock.js/cache` stays an optional peer.
118
+ *
119
+ * Semantically a **store, not a cache**: a pinned refinement is re-generated
120
+ * only when an input changes (source text, refiner model, criteria, recipe
121
+ * version) — never evicted-and-silently-recomputed over time. Prefer a
122
+ * persistent/shared backend (redis, pg) so one process pays the refinement
123
+ * and the fleet reads the pin.
124
+ */
125
+ interface RefinedPromptStoreLike {
126
+ /** Read a pinned value, or `null` on a miss. */
127
+ get<T = unknown>(key: string): Promise<T | null>;
128
+ /** Pin a value (TTL / options ignored by this path — pins don't expire). */
129
+ set(key: string, value: unknown, ttlOrOptions?: unknown): Promise<unknown>;
130
+ }
131
+ /**
132
+ * Configuration for {@link SystemPromptContract.refined} — the prompt
133
+ * compiler. `model` writes the refined text; `criteria` steers the rewrite;
134
+ * `store` pins the result across processes.
135
+ */
136
+ interface RefinedSystemPromptOptions {
137
+ /** The refiner model that rewrites the prompt (one call per unique input). */
138
+ readonly model: ModelContract;
139
+ /**
140
+ * Rules the rewritten prompt must satisfy, on top of the built-in
141
+ * refinement recipe — same shape and meaning as `validate({ criteria })`
142
+ * (validate *grades* against criteria; refined *rewrites* against them).
143
+ * A single string is used verbatim; a list becomes a numbered rule set.
144
+ */
145
+ readonly criteria?: string | readonly string[];
146
+ /**
147
+ * Where the compiled text is pinned. Omitted ⇒ the pin lives on the
148
+ * refined prompt instance for the process lifetime (compile once per
149
+ * instance); pass a shared store for cross-process / persistent pinning.
150
+ */
151
+ readonly store?: RefinedPromptStoreLike;
152
+ }
153
+ /** Per-call options for `refine()` / `refinePrompt()`. */
154
+ interface PromptRefineOptions {
155
+ /**
156
+ * Skip the pinned value and compile a fresh take (the new result replaces
157
+ * the pin). Use when you want another attempt at the same source.
158
+ */
159
+ readonly fresh?: boolean;
160
+ }
104
161
  /**
105
162
  * Immutable builder for composing a layered system prompt out of persona and
106
163
  * instruction blocks. Every mutating method returns a fresh builder — the
@@ -214,7 +271,97 @@ interface SystemPromptContract {
214
271
  * reflects the deterministic verdict alone; a flaky judge never flips it.
215
272
  */
216
273
  validate(options?: PromptsValidateOptions): Promise<PromptValidationResult>;
274
+ /**
275
+ * Derive the **compiled** form of this prompt: a lazy wrapper that rewrites
276
+ * the human-authored text into a model-optimized version via
277
+ * `options.model` the first time it is used by an agent, pins the result
278
+ * (in `options.store` when given, else on the instance), and serves the
279
+ * pinned text from then on. The source prompt stays the editing surface;
280
+ * the refined text is a derived artifact — re-compiled only when the
281
+ * source text, refiner model, `criteria`, or built-in recipe change.
282
+ *
283
+ * The wrapper is a full `SystemPromptContract`, so it drops in anywhere a
284
+ * prompt does. Refinement is advisory on the agent path: if the refiner
285
+ * fails, the ORIGINAL prompt is served (warned once, never thrown).
286
+ * Placeholders are contract, not prose — the compiled text keeps the exact
287
+ * `{{placeholder}}` set or the refinement is rejected.
288
+ *
289
+ * @example
290
+ * const support = ai.systemPrompt(
291
+ * [ai.persona("You are a friendly assistant."), ai.instruction("Help {{name}} with orders.")],
292
+ * { name: "support" },
293
+ * ).refined({ model: anthropic.model({ name: "claude-sonnet-4-5" }) });
294
+ *
295
+ * const agent = ai.agent({ model, systemPrompt: support }); // compiles lazily on first run
296
+ */
297
+ refined(options: RefinedSystemPromptOptions): RefinedSystemPromptContract;
298
+ /**
299
+ * Optional async pre-resolution hook. When present, consumers that are
300
+ * about to call the synchronous `resolve()` on an async boundary (the
301
+ * agent input builder) await it first, letting a lazily-compiled prompt
302
+ * finish its work. Plain builders don't implement it; implementations
303
+ * must never throw (degrade to the original text instead).
304
+ */
305
+ materialize?(): Promise<void>;
306
+ }
307
+ /**
308
+ * The compiled form of a system prompt, returned by
309
+ * {@link SystemPromptContract.refined}. A full drop-in prompt contract plus
310
+ * the explicit compilation surface: `refine()` hands back the compiled
311
+ * template text (for admin routes, previews, boot warmup, CI), and
312
+ * `refinePrompt()` hands back a composable `SystemPromptContract` built from
313
+ * it. All three consumption paths — lazy agent use, `refine()`, and
314
+ * `refinePrompt()` — share one compilation pipeline and one pin.
315
+ */
316
+ interface RefinedSystemPromptContract extends SystemPromptContract {
317
+ /** The human-authored prompt this wrapper compiles — always the source of truth. */
318
+ readonly source: SystemPromptContract;
319
+ /**
320
+ * Chaining stays compiled: every derivation edits the SOURCE and re-wraps
321
+ * it with the same refinement options, so the return type stays refined —
322
+ * and the pin invalidates naturally (new source ⇒ new key).
323
+ */
324
+ persona(persona: PersonaContract | string): RefinedSystemPromptContract;
325
+ /** See {@link RefinedSystemPromptContract.persona} — chaining stays compiled. */
326
+ instruction(instruction: InstructionContract | string): RefinedSystemPromptContract;
327
+ /** See {@link RefinedSystemPromptContract.persona} — chaining stays compiled. */
328
+ merge(...blocks: readonly SystemPromptBlockContract[]): RefinedSystemPromptContract;
329
+ merge(source: SystemPromptContract): RefinedSystemPromptContract;
330
+ merge(name: string, options?: SystemPromptMergeOptions): RefinedSystemPromptContract;
331
+ /** Read the SOURCE prompt's metadata — a compiled prompt keeps its source identity. */
332
+ meta(): SystemPromptMeta | undefined;
333
+ /** Rename the SOURCE and re-wrap — refinement survives the rename. */
334
+ meta(meta: SystemPromptMeta): RefinedSystemPromptContract;
335
+ /**
336
+ * Compile now (or read the pin) and return the refined template **string**.
337
+ * Still a template: the exact `{{placeholder}}` set of the source survives
338
+ * verbatim, so the text stays parametric. Store-first — an unchanged input
339
+ * returns the pinned text without a model call; `{ fresh: true }` forces a
340
+ * new take (which replaces the pin).
341
+ *
342
+ * Unlike the lazy agent path, this explicit call **throws**
343
+ * `PromptRefinementError` when the refiner fails or breaks placeholder
344
+ * parity — a route/CI caller needs the failure, not a silent fallback.
345
+ */
346
+ refine(options?: PromptRefineOptions): Promise<string>;
347
+ /**
348
+ * Same compilation, returned as a new `SystemPromptContract` (one
349
+ * instruction block holding the refined template) for composition:
350
+ * hand it to an agent, `.resolve(placeholders)`, `.merge(...)`,
351
+ * `validate({ criteria })`, or `.meta({ name })` it to register the
352
+ * compiled text as a next version (unlocking `ai.prompts.diff` as the
353
+ * original-vs-refined review flow). Carries `meta.refinedFrom` /
354
+ * `meta.refinerModel` provenance and the source's `required` keys; never
355
+ * auto-registers — registry versions stay human-intentional.
356
+ */
357
+ refinePrompt(options?: PromptRefineOptions): Promise<SystemPromptContract>;
358
+ /**
359
+ * The advisory compilation hook the agent path awaits: compiles + pins on
360
+ * first call, no-op once pinned, and NEVER throws — on any refiner failure
361
+ * it warns once and leaves `resolve()` serving the original text.
362
+ */
363
+ materialize(): Promise<void>;
217
364
  }
218
365
  //#endregion
219
- export { InstructionContract, PersonaContract, SystemPromptBlockContract, SystemPromptContract, SystemPromptMergeOptions, SystemPromptMergeSource, SystemPromptMeta };
366
+ export { InstructionContract, PersonaContract, PromptRefineOptions, RefinedPromptStoreLike, RefinedSystemPromptContract, RefinedSystemPromptOptions, SystemPromptBlockContract, SystemPromptContract, SystemPromptMergeOptions, SystemPromptMergeSource, SystemPromptMeta };
220
367
  //# sourceMappingURL=system-prompt.contract.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"system-prompt.contract.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/contracts/system-prompt.contract.ts"],"mappings":";;;;;;AAqBA;;;;;;;;;;AAQqC;AAarC;;UArBiB,yBAAA;EAqBwB;EAAA,SAnB9B,IAAA;EAoCM;EAAA,SAjCN,IAAA;;EAGT,OAAA,CAAQ,YAAA,GAAe,YAAY;AAAA;AAoDrC;;;;;;;;;;AAAA,UAvCiB,eAAA,SAAwB,yBAAyB;EAAA,SACvD,IAAI;AAAA;;;AAgEO;AAQtB;;;;AAEwB;AAuCxB;;;;;UAjGiB,mBAAA,SAA4B,yBAAyB;EAAA,SAC3D,IAAI;AAAA;;;;;;;;;;;;;;;;;;;UAqBE,gBAAA;EAuGf;EAAA,SArGS,IAAA;EAqGJ;EAAA,SAlGI,OAAA;EAyGT;EAAA,SAtGS,WAAA;EAsGD;EAAA,SAnGC,YAAA;EAyGT;EAAA,SAtGS,QAAA;AAAA;;;;;UAOM,wBAAA;EAkHf;;;;EAAA,SA7GS,WAAW;AAAA;;;;;;KAQV,uBAAA,GACR,yBAAA,GACA,oBAAoB;;;;;;;AAgIoD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAzF3D,oBAAA;;WAEN,MAAA,WAAiB,yBAAA;;;;;;;;;;;;;;;EAiB1B,IAAA,IAAQ,gBAAA;;;;;;;;EASR,IAAA,CAAK,IAAA,EAAM,gBAAA,GAAmB,oBAAA;;;;;;EAO9B,OAAA,CAAQ,OAAA,EAAS,eAAA,YAA2B,oBAAA;;;;;EAM5C,WAAA,CAAY,WAAA,EAAa,mBAAA,YAA+B,oBAAA;;;;;;;;;EAUxD,KAAA,IAAS,MAAA,WAAiB,yBAAA,KAA8B,oBAAA;;;;;;;;EASxD,KAAA,CAAM,MAAA,EAAQ,oBAAA,GAAuB,oBAAA;;;;;;;EAQrC,KAAA,CACE,IAAA,UACA,OAAA,GAAU,wBAAA,GACT,oBAAA;;;;;;;;;EAUH,OAAA,CAAQ,YAAA,GAAe,YAAA;;;;;;;EAQvB,QAAA,CAAS,OAAA,GAAU,sBAAA,GAAyB,OAAA,CAAQ,sBAAA;AAAA"}
1
+ {"version":3,"file":"system-prompt.contract.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/contracts/system-prompt.contract.ts"],"mappings":";;;;;;;AAsBA;;;;;;;;;;AAQqC;AAarC;;UArBiB,yBAAA;EAqBwB;EAAA,SAnB9B,IAAA;EAoCM;EAAA,SAjCN,IAAA;;EAGT,OAAA,CAAQ,YAAA,GAAe,YAAY;AAAA;AAoDrC;;;;;;;;;;AAAA,UAvCiB,eAAA,SAAwB,yBAAyB;EAAA,SACvD,IAAI;AAAA;AAqEf;;;;AAKsB;AAQtB;;;;AAEwB;AAexB;;;AA9BA,UArDiB,mBAAA,SAA4B,yBAAyB;EAAA,SAC3D,IAAI;AAAA;;;;;;;;;;;;;;AAuFoD;AAQnE;;;;UA1EiB,gBAAA;EA4EC;EAAA,SA1EP,IAAA;EAyFA;EAAA,SAtFA,OAAA;EAsF8B;EAAA,SAnF9B,WAAA;EAuFM;EAAA,SApFN,YAAA;;WAGA,QAAA;EAsFK;AAuChB;;;;EAvCgB,SA/EL,WAAA;EAkJE;EAAA,SA/IF,YAAA;AAAA;;;;;UAOM,wBAAA;EAwKD;;;;EAAA,SAnKL,WAAW;AAAA;;;;;;KAQV,uBAAA,GACR,yBAAA,GACA,oBAAoB;;;;;;;;;;;;;UAeP,sBAAA;EAuHf;EArHA,GAAA,cAAiB,GAAA,WAAc,OAAA,CAAQ,CAAA;EAqH3B;EAlHZ,GAAA,CAAI,GAAA,UAAa,KAAA,WAAgB,YAAA,aAAyB,OAAA;AAAA;;;;;;UAQ3C,0BAAA;EA6HsB;EAAA,SA3H5B,KAAA,EAAO,aAAA;EAoId;;;;;;EAAA,SA5HO,QAAA;EAgJT;;;;;EAAA,SAzIS,KAAA,GAAQ,sBAAsB;AAAA;;UAIxB,mBAAA;EAuKf;;;AAAuB;EAAvB,SAlKS,KAAK;AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UAuCC,oBAAA;EAyJO;EAAA,SAvJb,MAAA,WAAiB,yBAAA;EAyJ1B;;;;;;;;;;EAOQ;;;;EA/IR,IAAA,IAAQ,gBAAA;EA+JR;;;;;;;EAtJA,IAAA,CAAK,IAAA,EAAM,gBAAA,GAAmB,oBAAA;EAkKuB;;;;AAO/B;EAlKtB,OAAA,CAAQ,OAAA,EAAS,eAAA,YAA2B,oBAAA;;;;;EAM5C,WAAA,CAAY,WAAA,EAAa,mBAAA,YAA+B,oBAAA;;;;;;;;;EAUxD,KAAA,IAAS,MAAA,WAAiB,yBAAA,KAA8B,oBAAA;;;;;;;;EASxD,KAAA,CAAM,MAAA,EAAQ,oBAAA,GAAuB,oBAAA;;;;;;;EAQrC,KAAA,CACE,IAAA,UACA,OAAA,GAAU,wBAAA,GACT,oBAAA;;;;;;;;;EAUH,OAAA,CAAQ,YAAA,GAAe,YAAA;;;;;;;EAQvB,QAAA,CAAS,OAAA,GAAU,sBAAA,GAAyB,OAAA,CAAQ,sBAAA;;;;;;;;;;;;;;;;;;;;;;;;EAyBpD,OAAA,CAAQ,OAAA,EAAS,0BAAA,GAA6B,2BAAA;;;;;;;;EAS9C,WAAA,KAAgB,OAAA;AAAA;;;;;;;;;;UAYD,2BAAA,SAAoC,oBAAA;;WAE1C,MAAA,EAAQ,oBAAA;;;;;;EAOjB,OAAA,CAAQ,OAAA,EAAS,eAAA,YAA2B,2BAAA;;EAG5C,WAAA,CACE,WAAA,EAAa,mBAAA,YACZ,2BAAA;;EAGH,KAAA,IACK,MAAA,WAAiB,yBAAA,KACnB,2BAAA;EACH,KAAA,CAAM,MAAA,EAAQ,oBAAA,GAAuB,2BAAA;EACrC,KAAA,CACE,IAAA,UACA,OAAA,GAAU,wBAAA,GACT,2BAAA;;EAGH,IAAA,IAAQ,gBAAA;;EAGR,IAAA,CAAK,IAAA,EAAM,gBAAA,GAAmB,2BAAA;;;;;;;;;;;;EAa9B,MAAA,CAAO,OAAA,GAAU,mBAAA,GAAsB,OAAA;;;;;;;;;;;EAYvC,YAAA,CAAa,OAAA,GAAU,mBAAA,GAAsB,OAAA,CAAQ,oBAAA;;;;;;EAOrD,WAAA,IAAe,OAAA;AAAA"}
@@ -13,7 +13,7 @@
13
13
  * return agent.execute(input);
14
14
  * }
15
15
  */
16
- type AIErrorCode = "AGENT_EXEC_FAILED" | "AGENT_CANCELLED" | "AGENT_MAX_TRIPS" | "AGENT_DRIFT" | "SCHEMA_VALIDATION_FAILED" | "TOOL_EXEC_FAILED" | "PROVIDER_ERROR" | "PROVIDER_RATE_LIMIT" | "PROVIDER_QUOTA_EXCEEDED" | "PROVIDER_TIMEOUT" | "CONTEXT_LENGTH_EXCEEDED" | "CONTENT_FILTER" | "PROVIDER_INVALID_REQUEST" | "PROVIDER_AUTH" | "BUDGET_EXCEEDED" | "GUARDRAIL_VIOLATION" | "WORKFLOW_ERROR" | "STEP_FAILED" | "WORKFLOW_DRIFT" | "WORKFLOW_CANCELLED" | "WORKFLOW_MAX_STEPS" | "WORKFLOW_INVALID_GOTO" | "SUPERVISOR_FAILED" | "SUPERVISOR_MAX_ITERATIONS" | "SUPERVISOR_INVALID_ROUTE" | "SUPERVISOR_CANCELLED" | "SUPERVISOR_DRIFT" | "SUPERVISOR_INTENT_DESCRIPTION_REQUIRED" | "SUPERVISOR_INTENT_MIXED_DISPATCH" | "SUPERVISOR_INTENT_STREAM_AND_OUTPUT" | "SUPERVISOR_INTENT_STREAM_TO_REQUIRED" | "SUPERVISOR_INTENT_STREAM_ON_WORKFLOW" | "SUPERVISOR_DISPATCH_CYCLE" | "ORCHESTRATOR_FAILED" | "ORCHESTRATOR_DRIFT" | "ORCHESTRATOR_CONFIG" | "ORCHESTRATOR_CANCELLED" | "PLANNER_FAILED" | "PLANNER_PLAN_INVALID" | "PLANNER_CANCELLED" | "PLANNER_DRIFT" | "VCR_CASSETTE_MISS" | "OUTBOUND_POLICY_BLOCKED";
16
+ type AIErrorCode = "AGENT_EXEC_FAILED" | "AGENT_CANCELLED" | "AGENT_MAX_TRIPS" | "AGENT_DRIFT" | "SCHEMA_VALIDATION_FAILED" | "TOOL_EXEC_FAILED" | "PROVIDER_ERROR" | "PROVIDER_RATE_LIMIT" | "PROVIDER_QUOTA_EXCEEDED" | "PROVIDER_TIMEOUT" | "CONTEXT_LENGTH_EXCEEDED" | "CONTENT_FILTER" | "PROVIDER_INVALID_REQUEST" | "PROVIDER_AUTH" | "BUDGET_EXCEEDED" | "GUARDRAIL_VIOLATION" | "WORKFLOW_ERROR" | "STEP_FAILED" | "WORKFLOW_DRIFT" | "WORKFLOW_CANCELLED" | "WORKFLOW_MAX_STEPS" | "WORKFLOW_INVALID_GOTO" | "SUPERVISOR_FAILED" | "SUPERVISOR_MAX_ITERATIONS" | "SUPERVISOR_INVALID_ROUTE" | "SUPERVISOR_CANCELLED" | "SUPERVISOR_DRIFT" | "SUPERVISOR_INTENT_DESCRIPTION_REQUIRED" | "SUPERVISOR_INTENT_MIXED_DISPATCH" | "SUPERVISOR_INTENT_STREAM_AND_OUTPUT" | "SUPERVISOR_INTENT_STREAM_TO_REQUIRED" | "SUPERVISOR_INTENT_STREAM_ON_WORKFLOW" | "SUPERVISOR_DISPATCH_CYCLE" | "ORCHESTRATOR_FAILED" | "ORCHESTRATOR_DRIFT" | "ORCHESTRATOR_CONFIG" | "ORCHESTRATOR_CANCELLED" | "PLANNER_FAILED" | "PLANNER_PLAN_INVALID" | "PLANNER_CANCELLED" | "PLANNER_DRIFT" | "VCR_CASSETTE_MISS" | "OUTBOUND_POLICY_BLOCKED" | "PROMPT_REFINEMENT_FAILED";
17
17
  //#endregion
18
18
  export { AIErrorCode };
19
19
  //# sourceMappingURL=error-code.type.d.mts.map
@@ -24,6 +24,7 @@ import { PlannerFailedError } from "./planner-failed-error.mjs";
24
24
  import { PlannerCancelledError, PlannerCancelledErrorOptions } from "./planner-cancelled-error.mjs";
25
25
  import { PlannerDriftError, PlannerDriftErrorOptions } from "./planner-drift-error.mjs";
26
26
  import { PlannerPlanInvalidError } from "./planner-plan-invalid-error.mjs";
27
+ import { PromptRefinementError, PromptRefinementErrorOptions, PromptRefinementFailureReason } from "./prompt-refinement-error.mjs";
27
28
  import { ProviderAuthError } from "./provider-auth-error.mjs";
28
29
  import { ProviderRateLimitError, ProviderRateLimitErrorOptions } from "./provider-rate-limit-error.mjs";
29
30
  import { ProviderTimeoutError } from "./provider-timeout-error.mjs";
@@ -22,6 +22,7 @@ import { PlannerFailedError } from "./planner-failed-error.mjs";
22
22
  import { PlannerCancelledError } from "./planner-cancelled-error.mjs";
23
23
  import { PlannerDriftError } from "./planner-drift-error.mjs";
24
24
  import { PlannerPlanInvalidError } from "./planner-plan-invalid-error.mjs";
25
+ import { PromptRefinementError } from "./prompt-refinement-error.mjs";
25
26
  import { ProviderAuthError } from "./provider-auth-error.mjs";
26
27
  import { ProviderRateLimitError } from "./provider-rate-limit-error.mjs";
27
28
  import { ProviderTimeoutError } from "./provider-timeout-error.mjs";
@@ -0,0 +1,36 @@
1
+ import { ErrorCategory } from "./error-category.type.mjs";
2
+ import { AIError, AIErrorOptions } from "./ai-error.mjs";
3
+
4
+ //#region ../@warlock.js/ai/src/errors/prompt-refinement-error.d.ts
5
+ /**
6
+ * Why a prompt refinement was rejected:
7
+ *
8
+ * - `"model"` — the refiner model call itself failed (provider error, no
9
+ * key, timeout); the underlying `AIError` rides on `cause`.
10
+ * - `"parity"` — the rewrite broke placeholder parity (added, removed, or
11
+ * renamed a `{{placeholder}}` / changed its `|default`) and one repair
12
+ * attempt didn't fix it; the offending tokens are listed in `context.issues`.
13
+ * - `"empty"` — the refiner returned no usable text.
14
+ */
15
+ type PromptRefinementFailureReason = "model" | "parity" | "empty";
16
+ type PromptRefinementErrorOptions = AIErrorOptions & {
17
+ reason: PromptRefinementFailureReason;
18
+ };
19
+ /**
20
+ * An explicit `refine()` / `refinePrompt()` call could not produce an
21
+ * acceptable compiled prompt. Thrown (not degraded) because the explicit
22
+ * compilation surface is used by routes, warmup, and CI — callers there need
23
+ * the failure, not a silently-served original.
24
+ *
25
+ * The LAZY agent path never sees this error: `materialize()` catches it,
26
+ * warns once, and serves the original prompt text — refinement is advisory
27
+ * there, mirroring the Nova-safe judge policy in `ai.prompts.validate`.
28
+ */
29
+ declare class PromptRefinementError extends AIError {
30
+ static readonly defaultCategory: ErrorCategory;
31
+ readonly reason: PromptRefinementFailureReason;
32
+ constructor(message: string, options: PromptRefinementErrorOptions);
33
+ }
34
+ //#endregion
35
+ export { PromptRefinementError, PromptRefinementErrorOptions, PromptRefinementFailureReason };
36
+ //# sourceMappingURL=prompt-refinement-error.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prompt-refinement-error.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/errors/prompt-refinement-error.ts"],"mappings":";;;;;AAcA;;;;AAAyC;AAEzC;;;;KAFY,6BAAA;AAAA,KAEA,4BAAA,GAA+B,cAAA;EACzC,MAAA,EAAQ,6BAA6B;AAAA;AAAA;AAavC;;;;;;;;;AAbuC,cAa1B,qBAAA,SAA8B,OAAA;EAAA,gBAClB,eAAA,EAAiB,aAAA;EAAA,SAExB,MAAA,EAAQ,6BAAA;cAEL,OAAA,UAAiB,OAAA,EAAS,4BAAA;AAAA"}
@@ -0,0 +1,27 @@
1
+ import { AIError } from "./ai-error.mjs";
2
+
3
+ //#region ../@warlock.js/ai/src/errors/prompt-refinement-error.ts
4
+ /**
5
+ * An explicit `refine()` / `refinePrompt()` call could not produce an
6
+ * acceptable compiled prompt. Thrown (not degraded) because the explicit
7
+ * compilation surface is used by routes, warmup, and CI — callers there need
8
+ * the failure, not a silently-served original.
9
+ *
10
+ * The LAZY agent path never sees this error: `materialize()` catches it,
11
+ * warns once, and serves the original prompt text — refinement is advisory
12
+ * there, mirroring the Nova-safe judge policy in `ai.prompts.validate`.
13
+ */
14
+ var PromptRefinementError = class extends AIError {
15
+ static {
16
+ this.defaultCategory = "validation";
17
+ }
18
+ constructor(message, options) {
19
+ super("PROMPT_REFINEMENT_FAILED", message, options);
20
+ this.name = "PromptRefinementError";
21
+ this.reason = options.reason;
22
+ }
23
+ };
24
+
25
+ //#endregion
26
+ export { PromptRefinementError };
27
+ //# sourceMappingURL=prompt-refinement-error.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prompt-refinement-error.mjs","names":[],"sources":["../../../../../../../@warlock.js/ai/src/errors/prompt-refinement-error.ts"],"sourcesContent":["import type { AIErrorOptions } from \"./ai-error\";\nimport { AIError } from \"./ai-error\";\nimport type { ErrorCategory } from \"./error-category.type\";\n\n/**\n * Why a prompt refinement was rejected:\n *\n * - `\"model\"` — the refiner model call itself failed (provider error, no\n * key, timeout); the underlying `AIError` rides on `cause`.\n * - `\"parity\"` — the rewrite broke placeholder parity (added, removed, or\n * renamed a `{{placeholder}}` / changed its `|default`) and one repair\n * attempt didn't fix it; the offending tokens are listed in `context.issues`.\n * - `\"empty\"` — the refiner returned no usable text.\n */\nexport type PromptRefinementFailureReason = \"model\" | \"parity\" | \"empty\";\n\nexport type PromptRefinementErrorOptions = AIErrorOptions & {\n reason: PromptRefinementFailureReason;\n};\n\n/**\n * An explicit `refine()` / `refinePrompt()` call could not produce an\n * acceptable compiled prompt. Thrown (not degraded) because the explicit\n * compilation surface is used by routes, warmup, and CI — callers there need\n * the failure, not a silently-served original.\n *\n * The LAZY agent path never sees this error: `materialize()` catches it,\n * warns once, and serves the original prompt text — refinement is advisory\n * there, mirroring the Nova-safe judge policy in `ai.prompts.validate`.\n */\nexport class PromptRefinementError extends AIError {\n public static readonly defaultCategory: ErrorCategory = \"validation\";\n\n public readonly reason: PromptRefinementFailureReason;\n\n public constructor(message: string, options: PromptRefinementErrorOptions) {\n super(\"PROMPT_REFINEMENT_FAILED\", message, options);\n this.name = \"PromptRefinementError\";\n this.reason = options.reason;\n }\n}\n"],"mappings":";;;;;;;;;;;;;AA8BA,IAAa,wBAAb,cAA2C,QAAQ;;yBACO;;CAIxD,AAAO,YAAY,SAAiB,SAAuC;EACzE,MAAM,4BAA4B,SAAS,OAAO;EAClD,KAAK,OAAO;EACZ,KAAK,SAAS,QAAQ;CACxB;AACF"}
package/esm/index.d.mts CHANGED
@@ -54,6 +54,7 @@ import { PlannerFailedError } from "./errors/planner-failed-error.mjs";
54
54
  import { PlannerCancelledError, PlannerCancelledErrorOptions } from "./errors/planner-cancelled-error.mjs";
55
55
  import { PlannerDriftError, PlannerDriftErrorOptions } from "./errors/planner-drift-error.mjs";
56
56
  import { PlannerPlanInvalidError } from "./errors/planner-plan-invalid-error.mjs";
57
+ import { PromptRefinementError, PromptRefinementErrorOptions, PromptRefinementFailureReason } from "./errors/prompt-refinement-error.mjs";
57
58
  import { ProviderAuthError } from "./errors/provider-auth-error.mjs";
58
59
  import { ProviderRateLimitError, ProviderRateLimitErrorOptions } from "./errors/provider-rate-limit-error.mjs";
59
60
  import { ProviderTimeoutError } from "./errors/provider-timeout-error.mjs";
@@ -87,7 +88,7 @@ import { MiddlewareAgentRef, MiddlewareExecuteContext, MiddlewareModelRef, Middl
87
88
  import { AgentMiddleware, AgentMiddlewareExecuteHooks, AgentMiddlewareSupervisorHooks, AgentMiddlewareToolHooks, AgentMiddlewareTripHooks } from "./contracts/middleware/middleware.contract.mjs";
88
89
  import { Placeholders } from "./contracts/placeholders.type.mjs";
89
90
  import { ExportedPrompt, ExportedPromptVersion, ExportedRegistry, PromptDiff, PromptDiffBlock, PromptJudgeCacheLike, PromptTemplateVersion, PromptValidateTarget, PromptValidationResult, PromptsManagerOptions, PromptsValidateOptions } from "./prompts/prompts-manager.type.mjs";
90
- import { InstructionContract, PersonaContract, SystemPromptBlockContract, SystemPromptContract, SystemPromptMergeOptions, SystemPromptMergeSource, SystemPromptMeta } from "./contracts/system-prompt.contract.mjs";
91
+ import { InstructionContract, PersonaContract, PromptRefineOptions, RefinedPromptStoreLike, RefinedSystemPromptContract, RefinedSystemPromptOptions, SystemPromptBlockContract, SystemPromptContract, SystemPromptMergeOptions, SystemPromptMergeSource, SystemPromptMeta } from "./contracts/system-prompt.contract.mjs";
91
92
  import { RouteContext } from "./contracts/supervisor/route-context.type.mjs";
92
93
  import { AckCallback, AckConfig, AckEntry, AckRunEntry } from "./contracts/supervisor/ack-entry.type.mjs";
93
94
  import { DispatchRawResult, IntentCallback, IntentEntry, IntentRunEntry, SupervisorIntentValue } from "./contracts/supervisor/intent-entry.type.mjs";
@@ -293,6 +294,7 @@ import { getObservers, isObserveAll, registerObserver, setObserveAll } from "./o
293
294
  import { assertUrlAllowed, fetchTextWithPolicy, guardedFetch, readTextCapped, resolveOutboundPolicy } from "./security/outbound-policy.mjs";
294
295
  import { isPrivateOrReservedIp } from "./security/private-ip.mjs";
295
296
  import { DEFAULT_SENSITIVE_KEYS, RedactOptions, RedactedError, SENSITIVE_HEADERS, redact, redactError, redactHeaders, scrubSecrets } from "./security/redact.mjs";
297
+ import { RefinedSystemPrompt } from "./system-prompt/refined-system-prompt.mjs";
296
298
  import { renderPlaceholders } from "./system-prompt/render-placeholders.mjs";
297
299
  import { accumulateCost, computeCost, mergeUsage } from "./utils/compute-cost.mjs";
298
300
  import { extractJsonLenient } from "./utils/extract-json-lenient.mjs";
@@ -309,7 +311,7 @@ import { computeSignature as computeSignature$1 } from "./workflow/signature.mjs
309
311
  import { MatcherVerdict, matchConverge, matchOutputShape, matchPassStep, matchRouteTo } from "./testing/matcher-logic.mjs";
310
312
  import { AiMatchers } from "./testing/matchers.mjs";
311
313
  import { registerAiMatchers } from "./testing/register-lazy.mjs";
312
- export { AIConfig, AIError, type AIErrorCode, type AIErrorOptions, type AckCallback, type AckConfig, type AckEntry, type AckRunEntry, type AckSnapshot, type AgentBranchSnapshot, AgentCancelledError, type AgentCancelledErrorOptions, type AgentCompletedPayload, type AgentConfig, type AgentContract, AgentDriftError, type AgentDriftErrorOptions, type AgentErrorPayload, type AgentEventHandler, type AgentEventMap, type AgentExecuteOptions, AgentExecutionError, AgentMaxTripsError, type AgentMaxTripsErrorOptions, type AgentMiddleware, type AgentMiddlewareExecuteHooks, type AgentMiddlewareSupervisorHooks, type AgentMiddlewareToolHooks, type AgentMiddlewareTripHooks, type AgentReport, type AgentResult, type AgentResumeOptions, type AgentSnapshot, type AgentSnapshotStatus, type AgentStartingPayload, type AgentStreamingPayload, type AgentToolCalledPayload, type AgentToolCallingFailedPayload, type AgentToolCallingPayload, type AgentToolEntry, type AgentTripCompletedPayload, type AgentTripStartedPayload, type Ai, type AiMatchers, type ApprovalDecision, type ApprovalDecisionType, type ApprovalHandler, ApprovalRejectedError, type ApprovalRejectedErrorOptions, type ApprovalRequest, type ApprovalRequestContext, Attachment, AttachmentPolicy, AttachmentSource, type AttemptEntry, AudioInput, type BaseReport, type BaseResult, type BatchItemHandler, type BatchItemResult, type BatchItemStatus, type BatchOptions, type BatchReport, type BatchResult, BinarySource, type BudgetContract, type BudgetContractDimension, type BudgetContractFallback, type BudgetContractViolation, type BudgetContractViolationMode, BudgetExceededError, type BudgetExceededErrorOptions, type BudgetFallbackSignal, type BudgetOptions, type BudgetPricing, type BudgetUnit, type CapturedMessage, type Cassette, type CassetteEntry, type CheckpointRecord, type CheckpointStore, type Chunk, type ChunkOptions, type ChunkType, type Citation, type ClassifierAgentEntry, type ClassifierCallback, type ClassifierConfig, type ClassifierContext, type ClassifierOutput, type ClassifierRefineContext, type ClassifierRefineResult, type ClassifierRunEntry, type ClassifierSnapshot, type CompactionResult, type CompleteEvent, ContentFilterError, type ContentFilterErrorOptions, ContentPart, ContextLengthExceededError, type ContextLengthExceededErrorOptions, DEFAULT_HASH_OPTIONS, DEFAULT_SENSITIVE_KEYS, type DatasetContract, type DatasetEntry, type DatasetOptions, type DecisionSource, type DispatchContext, type DispatchRawResult, END, EmbedderConfig, EmbedderContract, EmbeddingBatchResult, EmbeddingResult, EmbeddingUsage, EndSentinel, type EpisodicMemoryConfig, type ErrorCategory, type EvalCase, type EvalCaseResult, type EvalJudge, type EvalOptions, type EvalPredicate, type EvalReport, type EvalScore, type EvalScorer, type EvalScorerContext, type EvaluateBranchResult, type EvaluateContext, type EvaluateResult, type EventIdentity, ExecutableContract, type ExecutableTool, type ExecuteResult, type ExecutionReport, type ExecutionStatus, type ExportedPrompt, type ExportedPromptVersion, type ExportedRegistry, type ExtractJsonSchemaOptions, type FallbackAttempt, type FallbackModelContract, type FallbackModelOptions, type FallbackRetryPredicate, type FanOutOptions, type FanOutUnit, FinishReason, type FlagRecord, type FlowObserveOption, GeneratedAudio, GeneratedImage, type GuardOptions, type GuardrailAction, type GuardrailBlockEvent, type GuardrailCheck, type GuardrailCheckResult, type GuardrailDetector, type GuardrailDetectorContext, type GuardrailEscalation, type GuardrailFactory, type GuardrailMatch, type GuardrailOptions, type GuardrailPhase, type GuardrailVerdict, GuardrailViolationError, type GuardrailViolationErrorOptions, type HumanApprovalOptions, type HumanErrorCode, type ImageData, ImageGenerationOptions, ImageGenerationResponse, ImageModelConfig, ImageModelContract, ImageModelPricing, type ImageParams, type ImageReport, type ImageResult, ImageSource, type InjectionDetectorOptions, Instruction, InstructionContract, type IntentCallback, type IntentEntry, type IntentRunEntry, type IntentRunner, type IntentRunnerMap, type InterruptPolicy, type InterruptStore, InterruptSuspendedError, type InterruptSuspendedErrorOptions, InvalidRequestError, type IterationDecision, type IterationSnapshot, JUDGE_DEFAULT_REPAIR_ATTEMPTS, type JsonSchemaTarget, type JudgeAgentConfig, type JudgeConfig, type KeywordRerankerOptions, type LLMTrip, type LexicalDoc, type LineageStamp, type LlmRerankerOptions, type LoadHtmlOptions, type LoadPdfOptions, type LoadSkillInput, type LoadSkillResult, type LoadSkillToolDeps, type LoadTextOptions, type LoadWebOptions, type MatcherVerdict, MaxIterationsError, type MaxIterationsErrorOptions, MaxStepsExceededError, type MaxStepsExceededErrorOptions, type MemoryConfig, type MemoryContract, type MemoryItem, type MemoryTier, Message, type MiddlewareAgentRef, type MiddlewareContextByLevel, type MiddlewareExecuteContext, type MiddlewareLevel, type MiddlewareModelRef, type MiddlewareState, type MiddlewareSupervisorContext, type MiddlewareSupervisorRef, type MiddlewareToolContext, type MiddlewareTripContext, type MockImageCall, MockImageModel, type MockImageResponse, MockModel, type MockModelResponse, type MockRouterDecision, type MockRouterExhaustion, type MockRouterOptions, MockSDK, type MockSDKConfig, MockSkillsStore, type MockSpeechCall, MockSpeechModel, type MockSpeechResponse, type MockTranscriptionCall, MockTranscriptionModel, type MockTranscriptionResponse, ModelCallOptions, ModelCapabilities, ModelConfig, ModelContract, type ModelPricing, ModelResponse, ModelStreamChunk, ModelToolCallRequest, type MultiQueryOptions, type NamespacedStateAccessor, type Next, type NextStepResult, OPENAI_INSTALL_INSTRUCTIONS, type ObjectStreamEvent, type Observer, type OpenAiClientLike, type OpenAiModerationCreateBody, type OpenAiModerationOptions, type OpenAiModerationResponse, type OpenAiModerationResult, type OrchestratorAsToolOptions, type OrchestratorAwaitingStatus, OrchestratorCancelledError, type OrchestratorCancelledErrorOptions, type OrchestratorCommandHandlers, type OrchestratorCommands, type OrchestratorConfig, OrchestratorConfigError, type OrchestratorContract, OrchestratorDriftError, type OrchestratorDriftErrorOptions, OrchestratorEmitter, type OrchestratorEvent, type OrchestratorEventHandler, type OrchestratorEventHandlers, type OrchestratorEventMap, type OrchestratorEventName, type OrchestratorExecuteOptions, OrchestratorExecution, type OrchestratorExecutionParams, OrchestratorFailedError, type OrchestratorMemoryConfig, type OrchestratorReport, type OrchestratorReportStatus, type OrchestratorReportType, type OrchestratorResult, type OrchestratorResumeOptions, type OrchestratorSessionScope, type OrchestratorStreamController, type OutboundPolicy, OutboundPolicyError, PDF_PARSE_INSTALL_INSTRUCTIONS, type ParsedFrontmatter, type PendingInterrupt, type PendingInterruptStatus, Persona, PersonaContract, type PgCheckpointOptions, type PgClientLike, type PgInterruptOptions, type PgSnapshotStoreOptions, type PgVectorStoreInstance, type PgVectorStoreOptions, type PiiCategory, type PiiDetectorOptions, Placeholders, PlannerCancelledError, type PlannerCancelledErrorOptions, type PlannerCapability, type PlannerConfig, type PlannerContract, PlannerDriftError, type PlannerDriftErrorOptions, type PlannerExecuteOptions, PlannerFailedError, type PlannerPlan, PlannerPlanInvalidError, type PlannerReport, type PlannerReportType, type PlannerResult, type PlannerResumeOptions, type PlannerRunArgs, type PlannerSnapshot, type PlannerSnapshotStatus, type PlannerStep, type PlannerStepDirective, type PlannerStepSnapshot, type PolicyContext, type PolicyVerdict, type ProceduralMemoryConfig, type PromptDiff, type PromptDiffBlock, type PromptEntry, type PromptJudgeCacheLike, type PromptLangfuseSyncOptions, PromptNotFoundError, type PromptRegistryContract, type PromptRegistryOptions, type PromptResolveOptions, type PromptTemplateVersion, type PromptValidateOptions, type PromptValidateTarget, PromptValidationError, type PromptValidationNote, type PromptValidationReport, type PromptValidationResult, type PromptValidationSeverity, type PromptVersion, type PromptsManagerContract, type PromptsManagerEntry, type PromptsManagerOptions, type PromptsManagerRegisterOptions, type PromptsValidateOptions, ProviderAuthError, ProviderError, ProviderRateLimitError, type ProviderRateLimitErrorOptions, ProviderTimeoutError, QuotaExceededError, REPORT_SCHEMA_VERSION, type Rag, type RagAsToolOptions, type RagConfig, type RagDocument, type RagLoaderMetadata, type RagLoaderOptions, type RagLoaderResult, type RagLoaderType, type RagReranker, type RankedItem, ReasoningEffort, type RecallOptions, type RecalledMemory, type RedactOptions, type RedactedError, type RedisCheckpointOptions, type RedisClientLike, type RedisInterruptOptions, type RedisSnapshotStoreOptions, type ReportStatus, type ReportType, ResolvedAttachment, type ResolvedIntentEntry, type ResolvedOrchestratorMemory, type ResolvedOutboundPolicy, type ResolvedPrompt, type ResumeOptions, type ResumeResult, type RetrieveOptions, type RetrieveResult, type RetrievedChunk, type RetryBackoff, type RetryConfig, type ReviewOutcome, type RouteContext, type RouterConfig, type RouterEntry, type RouterIntents, type RouterOutput, RoutingError, type RoutingErrorOptions, type RunFrame, SDKAdapterContract, SENSITIVE_HEADERS, SSE_DONE, type SaveSkillInput, type SaveSkillResult, type SaveSkillToolDeps, SchemaValidationError, type SchemaValidationErrorOptions, type SemanticCacheOptions, type SemanticMemoryConfig, type ServableExecutable, type ServeOptions, type SessionContextOverrides, type SessionContract, type SessionLock, type SessionSendResult, type SkillAnalyticsEvent, type SkillCatalogEntry, type SkillInjectMode, type SkillRecord, type SkillReviewGate, type SkillSource, type SkillsConfig, type SkillsContract, type SkillsStoreContract, type SnapshotStore, type SpawnSubAgentSpec, type SpeechData, SpeechGenerationResponse, SpeechModelConfig, SpeechModelContract, SpeechModelPricing, SpeechOptions, type SpeechParams, type SpeechReport, type SpeechResult, type StepAgentInput, type StepDefinition, StepFailedError, type StepFailedErrorOptions, type StepLocalEvents, type StepOutputSpec, type StepSnapshot, StorageFileShape, type StreamContract, type StreamController, type StreamEvent, type StreamEventBody, type StreamLike, type StreamObjectParams, StreamingToolGuardConfig, type SummarizeCallback, type SummarizeConfig, type SupervisorAgentCompletedPayload, type SupervisorAgentFailedPayload, type SupervisorAgentStartingPayload, type SupervisorAgentStreamingPayload, type SupervisorAsToolOptions, SupervisorCancelledError, type SupervisorCancelledErrorOptions, type SupervisorCancelledPayload, type SupervisorCompletedPayload, type SupervisorConfig, type SupervisorContract, SupervisorDriftError, type SupervisorDriftErrorOptions, SupervisorEmitter, type SupervisorErrorPayload, type SupervisorEvaluateVerdictPayload, type SupervisorEventHandler, type SupervisorEventHandlers, type SupervisorEventMap, type SupervisorExecuteOptions, SupervisorExecution, SupervisorFailedError, type SupervisorInput, type SupervisorIntentValue, type SupervisorIterationCompletedPayload, type SupervisorIterationStartingPayload, type SupervisorReport, type SupervisorResult, type SupervisorResumeOptions, type SupervisorRouterDecidedPayload, type SupervisorRouterDecidingPayload, SupervisorRoutingError, type SupervisorRoutingErrorOptions, type SupervisorSnapshot, type SupervisorSnapshotStatus, type SupervisorStartingPayload, type SupervisorStreamController, type SupervisorStreamEvent, type SupervisorTerminatedBy, type SyncGuardrailDetector, SystemPrompt, SystemPromptBlockContract, SystemPromptContract, SystemPromptMergeOptions, SystemPromptMergeSource, SystemPromptMeta, type TeamConfig, type TeamGate, type TeamGateFn, type TeamMemberValue, type TextInput, type ToolCall, ToolConfig, ToolContext, type ToolContract, type ToolEventMeta, ToolExecutionError, type ToolExecutionErrorOptions, type ToolInvokeResult, ToolMeta, ToolMode, type TopicFilterOptions, TranscribeOptions, type TranscribeParams, type TranscriptionData, TranscriptionModelConfig, TranscriptionModelContract, TranscriptionModelPricing, type TranscriptionReport, TranscriptionResponse, type TranscriptionResult, TranscriptionSegment, type TurnSnapshot, type Usage, type UsageEvent, VcrCassetteMissError, type VcrCassetteMissErrorOptions, type VcrMode, type VcrModel, type VcrOptions, type VectorStore, type WithoutIdentity, WorkflowCancelledError, type WorkflowCancelledErrorOptions, type WorkflowCancelledPayload, type WorkflowCompletedPayload, type WorkflowContext, type WorkflowDefinition, WorkflowDriftError, type WorkflowDriftErrorOptions, WorkflowError, type WorkflowErrorPayload, type WorkflowEventHandler, type WorkflowEventHandlers, type WorkflowEventMap, type WorkflowExecuteOptions, type WorkflowInstance, type WorkflowLoopWarningPayload, type WorkflowReport, type WorkflowResult, type WorkflowResumeOptions, type WorkflowRunOptions, type WorkflowSnapshot, type WorkflowStartingPayload, type WorkflowStepCompletedPayload, type WorkflowStepFailedPayload, type WorkflowStepRetryingPayload, type WorkflowStepSkippedPayload, type WorkflowStepStartingPayload, type WorkflowStepStreamingPayload, accumulateCost, agent, ai, approximateTokenCount, assertUrlAllowed, audioFromBuffer, audioFromFile, audioMediaTypeForFilename, batch, bm25Rank, budget, buildCatalog, buildPlanSystemPrompt, buildRouterContextMessage, cacheVectorStore, captureChildReport, memory as checkpointMemory, pg as checkpointPg, redis as checkpointRedis, chunk, collectStreamObject, composeMiddleware, computeCost, computeImageCost, computeOrchestratorSignature, computeSignature as computePlannerSignature, computeSignature$1 as computeSignature, computeSignature$2 as computeSupervisorSignature, contains, createAgentStream, createCommandDispatcher as createOrchestratorCommandDispatcher, createOrchestratorStream, createCancelledError as createSupervisorCancelledError, createSupervisorStream, currentRunFrame, dataset, defaultPromptsManager, diff, directorySource, encodeSSE, evalScorers, evaluatePolicy, exact, executableToTool, extractJsonLenient, extractJsonPayload, extractJsonSchema, extractUserText, fallbackModel, fanOut, fetchTextWithPolicy, forTool, fromJSON, generateRunId, getAIConfig, getObservers, guard, guardedFetch, guardrail, hashRequest, humanApproval, hybridRank, image, inProcessSessionLock, injectMemories as injectOrchestratorMemories, injection, instruction, memory$1 as interruptMemory, pg$1 as interruptPg, redis$1 as interruptRedis, isExecutableTool, isObserveAll, isPrivateOrReservedIp, judge, keywordReranker, llmReranker, loadHtml, loadPdf, loadRecord, loadSkillTool, loadSnapshotForResume as loadSupervisorSnapshotForResume, loadText, loadWeb, matchConverge, matchOutputShape, matchPassStep, matchRouteTo, memory$2 as memory, mergeUsage, mockAgent, mockRouter, moderation, multiQuery, namespacedState, noopSessionLock, normalizeAgentTools, onConfigApplied, orchestrator, asTool as orchestratorAsTool, memoryQueryFromInput as orchestratorMemoryQueryFromInput, outcomeTextFromTurn as orchestratorOutcomeTextFromTurn, parseFrontmatter, parsePartialJson, parseTags, persistSupervisorSnapshot, persona, pgVectorStore, pii, planSchema, planner, predicate, prepareAttachmentPart, proceduralSkillStore, prompt, promptKey, prompts, rag, readBudgetFallbackSignal, readTextCapped, recallForTurn as recallOrchestratorMemory, reciprocalRankFusion, redact, redactError, redactHeaders, registerAiMatchers, registerObserver, rememberTurnOutcome as rememberOrchestratorTurnOutcome, renderCatalogPrompt, renderPlaceholders, resolveAttachment, resolveDefaultCheckpointStore, resolveDefaultSnapshotStore, resolveDefaultStore, resolveIntentEntries, resolveObservers, resolveOrchestratorMemory, resolveOutboundPolicy, resolveSource, resume, router, runEval, runResume as runOrchestratorResume, runTurn as runOrchestratorTurn, runPipeline, runReviewGate, safeJsonParse, saveSkillTool, scrubSecrets, semanticCache, semanticPreselect, serve, setAIConfig, setObserveAll, skills, memory$3 as snapshotMemory, pg$2 as snapshotPg, redis$2 as snapshotRedis, spawnSubAgent, speech, stampReportLineage, step, storeSource, streamObject, streamTurn as streamOrchestratorTurn, streamToSSE, supervisor, asTool$1 as supervisorAsTool, systemPrompt, team, toJSON, toJUnit, tool, topic, transcribe, urlSource, vcr, vectorLiteral, withRunFrame, withoutRunFrame, workflow };
314
+ export { AIConfig, AIError, type AIErrorCode, type AIErrorOptions, type AckCallback, type AckConfig, type AckEntry, type AckRunEntry, type AckSnapshot, type AgentBranchSnapshot, AgentCancelledError, type AgentCancelledErrorOptions, type AgentCompletedPayload, type AgentConfig, type AgentContract, AgentDriftError, type AgentDriftErrorOptions, type AgentErrorPayload, type AgentEventHandler, type AgentEventMap, type AgentExecuteOptions, AgentExecutionError, AgentMaxTripsError, type AgentMaxTripsErrorOptions, type AgentMiddleware, type AgentMiddlewareExecuteHooks, type AgentMiddlewareSupervisorHooks, type AgentMiddlewareToolHooks, type AgentMiddlewareTripHooks, type AgentReport, type AgentResult, type AgentResumeOptions, type AgentSnapshot, type AgentSnapshotStatus, type AgentStartingPayload, type AgentStreamingPayload, type AgentToolCalledPayload, type AgentToolCallingFailedPayload, type AgentToolCallingPayload, type AgentToolEntry, type AgentTripCompletedPayload, type AgentTripStartedPayload, type Ai, type AiMatchers, type ApprovalDecision, type ApprovalDecisionType, type ApprovalHandler, ApprovalRejectedError, type ApprovalRejectedErrorOptions, type ApprovalRequest, type ApprovalRequestContext, Attachment, AttachmentPolicy, AttachmentSource, type AttemptEntry, AudioInput, type BaseReport, type BaseResult, type BatchItemHandler, type BatchItemResult, type BatchItemStatus, type BatchOptions, type BatchReport, type BatchResult, BinarySource, type BudgetContract, type BudgetContractDimension, type BudgetContractFallback, type BudgetContractViolation, type BudgetContractViolationMode, BudgetExceededError, type BudgetExceededErrorOptions, type BudgetFallbackSignal, type BudgetOptions, type BudgetPricing, type BudgetUnit, type CapturedMessage, type Cassette, type CassetteEntry, type CheckpointRecord, type CheckpointStore, type Chunk, type ChunkOptions, type ChunkType, type Citation, type ClassifierAgentEntry, type ClassifierCallback, type ClassifierConfig, type ClassifierContext, type ClassifierOutput, type ClassifierRefineContext, type ClassifierRefineResult, type ClassifierRunEntry, type ClassifierSnapshot, type CompactionResult, type CompleteEvent, ContentFilterError, type ContentFilterErrorOptions, ContentPart, ContextLengthExceededError, type ContextLengthExceededErrorOptions, DEFAULT_HASH_OPTIONS, DEFAULT_SENSITIVE_KEYS, type DatasetContract, type DatasetEntry, type DatasetOptions, type DecisionSource, type DispatchContext, type DispatchRawResult, END, EmbedderConfig, EmbedderContract, EmbeddingBatchResult, EmbeddingResult, EmbeddingUsage, EndSentinel, type EpisodicMemoryConfig, type ErrorCategory, type EvalCase, type EvalCaseResult, type EvalJudge, type EvalOptions, type EvalPredicate, type EvalReport, type EvalScore, type EvalScorer, type EvalScorerContext, type EvaluateBranchResult, type EvaluateContext, type EvaluateResult, type EventIdentity, ExecutableContract, type ExecutableTool, type ExecuteResult, type ExecutionReport, type ExecutionStatus, type ExportedPrompt, type ExportedPromptVersion, type ExportedRegistry, type ExtractJsonSchemaOptions, type FallbackAttempt, type FallbackModelContract, type FallbackModelOptions, type FallbackRetryPredicate, type FanOutOptions, type FanOutUnit, FinishReason, type FlagRecord, type FlowObserveOption, GeneratedAudio, GeneratedImage, type GuardOptions, type GuardrailAction, type GuardrailBlockEvent, type GuardrailCheck, type GuardrailCheckResult, type GuardrailDetector, type GuardrailDetectorContext, type GuardrailEscalation, type GuardrailFactory, type GuardrailMatch, type GuardrailOptions, type GuardrailPhase, type GuardrailVerdict, GuardrailViolationError, type GuardrailViolationErrorOptions, type HumanApprovalOptions, type HumanErrorCode, type ImageData, ImageGenerationOptions, ImageGenerationResponse, ImageModelConfig, ImageModelContract, ImageModelPricing, type ImageParams, type ImageReport, type ImageResult, ImageSource, type InjectionDetectorOptions, Instruction, InstructionContract, type IntentCallback, type IntentEntry, type IntentRunEntry, type IntentRunner, type IntentRunnerMap, type InterruptPolicy, type InterruptStore, InterruptSuspendedError, type InterruptSuspendedErrorOptions, InvalidRequestError, type IterationDecision, type IterationSnapshot, JUDGE_DEFAULT_REPAIR_ATTEMPTS, type JsonSchemaTarget, type JudgeAgentConfig, type JudgeConfig, type KeywordRerankerOptions, type LLMTrip, type LexicalDoc, type LineageStamp, type LlmRerankerOptions, type LoadHtmlOptions, type LoadPdfOptions, type LoadSkillInput, type LoadSkillResult, type LoadSkillToolDeps, type LoadTextOptions, type LoadWebOptions, type MatcherVerdict, MaxIterationsError, type MaxIterationsErrorOptions, MaxStepsExceededError, type MaxStepsExceededErrorOptions, type MemoryConfig, type MemoryContract, type MemoryItem, type MemoryTier, Message, type MiddlewareAgentRef, type MiddlewareContextByLevel, type MiddlewareExecuteContext, type MiddlewareLevel, type MiddlewareModelRef, type MiddlewareState, type MiddlewareSupervisorContext, type MiddlewareSupervisorRef, type MiddlewareToolContext, type MiddlewareTripContext, type MockImageCall, MockImageModel, type MockImageResponse, MockModel, type MockModelResponse, type MockRouterDecision, type MockRouterExhaustion, type MockRouterOptions, MockSDK, type MockSDKConfig, MockSkillsStore, type MockSpeechCall, MockSpeechModel, type MockSpeechResponse, type MockTranscriptionCall, MockTranscriptionModel, type MockTranscriptionResponse, ModelCallOptions, ModelCapabilities, ModelConfig, ModelContract, type ModelPricing, ModelResponse, ModelStreamChunk, ModelToolCallRequest, type MultiQueryOptions, type NamespacedStateAccessor, type Next, type NextStepResult, OPENAI_INSTALL_INSTRUCTIONS, type ObjectStreamEvent, type Observer, type OpenAiClientLike, type OpenAiModerationCreateBody, type OpenAiModerationOptions, type OpenAiModerationResponse, type OpenAiModerationResult, type OrchestratorAsToolOptions, type OrchestratorAwaitingStatus, OrchestratorCancelledError, type OrchestratorCancelledErrorOptions, type OrchestratorCommandHandlers, type OrchestratorCommands, type OrchestratorConfig, OrchestratorConfigError, type OrchestratorContract, OrchestratorDriftError, type OrchestratorDriftErrorOptions, OrchestratorEmitter, type OrchestratorEvent, type OrchestratorEventHandler, type OrchestratorEventHandlers, type OrchestratorEventMap, type OrchestratorEventName, type OrchestratorExecuteOptions, OrchestratorExecution, type OrchestratorExecutionParams, OrchestratorFailedError, type OrchestratorMemoryConfig, type OrchestratorReport, type OrchestratorReportStatus, type OrchestratorReportType, type OrchestratorResult, type OrchestratorResumeOptions, type OrchestratorSessionScope, type OrchestratorStreamController, type OutboundPolicy, OutboundPolicyError, PDF_PARSE_INSTALL_INSTRUCTIONS, type ParsedFrontmatter, type PendingInterrupt, type PendingInterruptStatus, Persona, PersonaContract, type PgCheckpointOptions, type PgClientLike, type PgInterruptOptions, type PgSnapshotStoreOptions, type PgVectorStoreInstance, type PgVectorStoreOptions, type PiiCategory, type PiiDetectorOptions, Placeholders, PlannerCancelledError, type PlannerCancelledErrorOptions, type PlannerCapability, type PlannerConfig, type PlannerContract, PlannerDriftError, type PlannerDriftErrorOptions, type PlannerExecuteOptions, PlannerFailedError, type PlannerPlan, PlannerPlanInvalidError, type PlannerReport, type PlannerReportType, type PlannerResult, type PlannerResumeOptions, type PlannerRunArgs, type PlannerSnapshot, type PlannerSnapshotStatus, type PlannerStep, type PlannerStepDirective, type PlannerStepSnapshot, type PolicyContext, type PolicyVerdict, type ProceduralMemoryConfig, type PromptDiff, type PromptDiffBlock, type PromptEntry, type PromptJudgeCacheLike, type PromptLangfuseSyncOptions, PromptNotFoundError, PromptRefineOptions, PromptRefinementError, type PromptRefinementErrorOptions, type PromptRefinementFailureReason, type PromptRegistryContract, type PromptRegistryOptions, type PromptResolveOptions, type PromptTemplateVersion, type PromptValidateOptions, type PromptValidateTarget, PromptValidationError, type PromptValidationNote, type PromptValidationReport, type PromptValidationResult, type PromptValidationSeverity, type PromptVersion, type PromptsManagerContract, type PromptsManagerEntry, type PromptsManagerOptions, type PromptsManagerRegisterOptions, type PromptsValidateOptions, ProviderAuthError, ProviderError, ProviderRateLimitError, type ProviderRateLimitErrorOptions, ProviderTimeoutError, QuotaExceededError, REPORT_SCHEMA_VERSION, type Rag, type RagAsToolOptions, type RagConfig, type RagDocument, type RagLoaderMetadata, type RagLoaderOptions, type RagLoaderResult, type RagLoaderType, type RagReranker, type RankedItem, ReasoningEffort, type RecallOptions, type RecalledMemory, type RedactOptions, type RedactedError, type RedisCheckpointOptions, type RedisClientLike, type RedisInterruptOptions, type RedisSnapshotStoreOptions, RefinedPromptStoreLike, RefinedSystemPrompt, RefinedSystemPromptContract, RefinedSystemPromptOptions, type ReportStatus, type ReportType, ResolvedAttachment, type ResolvedIntentEntry, type ResolvedOrchestratorMemory, type ResolvedOutboundPolicy, type ResolvedPrompt, type ResumeOptions, type ResumeResult, type RetrieveOptions, type RetrieveResult, type RetrievedChunk, type RetryBackoff, type RetryConfig, type ReviewOutcome, type RouteContext, type RouterConfig, type RouterEntry, type RouterIntents, type RouterOutput, RoutingError, type RoutingErrorOptions, type RunFrame, SDKAdapterContract, SENSITIVE_HEADERS, SSE_DONE, type SaveSkillInput, type SaveSkillResult, type SaveSkillToolDeps, SchemaValidationError, type SchemaValidationErrorOptions, type SemanticCacheOptions, type SemanticMemoryConfig, type ServableExecutable, type ServeOptions, type SessionContextOverrides, type SessionContract, type SessionLock, type SessionSendResult, type SkillAnalyticsEvent, type SkillCatalogEntry, type SkillInjectMode, type SkillRecord, type SkillReviewGate, type SkillSource, type SkillsConfig, type SkillsContract, type SkillsStoreContract, type SnapshotStore, type SpawnSubAgentSpec, type SpeechData, SpeechGenerationResponse, SpeechModelConfig, SpeechModelContract, SpeechModelPricing, SpeechOptions, type SpeechParams, type SpeechReport, type SpeechResult, type StepAgentInput, type StepDefinition, StepFailedError, type StepFailedErrorOptions, type StepLocalEvents, type StepOutputSpec, type StepSnapshot, StorageFileShape, type StreamContract, type StreamController, type StreamEvent, type StreamEventBody, type StreamLike, type StreamObjectParams, StreamingToolGuardConfig, type SummarizeCallback, type SummarizeConfig, type SupervisorAgentCompletedPayload, type SupervisorAgentFailedPayload, type SupervisorAgentStartingPayload, type SupervisorAgentStreamingPayload, type SupervisorAsToolOptions, SupervisorCancelledError, type SupervisorCancelledErrorOptions, type SupervisorCancelledPayload, type SupervisorCompletedPayload, type SupervisorConfig, type SupervisorContract, SupervisorDriftError, type SupervisorDriftErrorOptions, SupervisorEmitter, type SupervisorErrorPayload, type SupervisorEvaluateVerdictPayload, type SupervisorEventHandler, type SupervisorEventHandlers, type SupervisorEventMap, type SupervisorExecuteOptions, SupervisorExecution, SupervisorFailedError, type SupervisorInput, type SupervisorIntentValue, type SupervisorIterationCompletedPayload, type SupervisorIterationStartingPayload, type SupervisorReport, type SupervisorResult, type SupervisorResumeOptions, type SupervisorRouterDecidedPayload, type SupervisorRouterDecidingPayload, SupervisorRoutingError, type SupervisorRoutingErrorOptions, type SupervisorSnapshot, type SupervisorSnapshotStatus, type SupervisorStartingPayload, type SupervisorStreamController, type SupervisorStreamEvent, type SupervisorTerminatedBy, type SyncGuardrailDetector, SystemPrompt, SystemPromptBlockContract, SystemPromptContract, SystemPromptMergeOptions, SystemPromptMergeSource, SystemPromptMeta, type TeamConfig, type TeamGate, type TeamGateFn, type TeamMemberValue, type TextInput, type ToolCall, ToolConfig, ToolContext, type ToolContract, type ToolEventMeta, ToolExecutionError, type ToolExecutionErrorOptions, type ToolInvokeResult, ToolMeta, ToolMode, type TopicFilterOptions, TranscribeOptions, type TranscribeParams, type TranscriptionData, TranscriptionModelConfig, TranscriptionModelContract, TranscriptionModelPricing, type TranscriptionReport, TranscriptionResponse, type TranscriptionResult, TranscriptionSegment, type TurnSnapshot, type Usage, type UsageEvent, VcrCassetteMissError, type VcrCassetteMissErrorOptions, type VcrMode, type VcrModel, type VcrOptions, type VectorStore, type WithoutIdentity, WorkflowCancelledError, type WorkflowCancelledErrorOptions, type WorkflowCancelledPayload, type WorkflowCompletedPayload, type WorkflowContext, type WorkflowDefinition, WorkflowDriftError, type WorkflowDriftErrorOptions, WorkflowError, type WorkflowErrorPayload, type WorkflowEventHandler, type WorkflowEventHandlers, type WorkflowEventMap, type WorkflowExecuteOptions, type WorkflowInstance, type WorkflowLoopWarningPayload, type WorkflowReport, type WorkflowResult, type WorkflowResumeOptions, type WorkflowRunOptions, type WorkflowSnapshot, type WorkflowStartingPayload, type WorkflowStepCompletedPayload, type WorkflowStepFailedPayload, type WorkflowStepRetryingPayload, type WorkflowStepSkippedPayload, type WorkflowStepStartingPayload, type WorkflowStepStreamingPayload, accumulateCost, agent, ai, approximateTokenCount, assertUrlAllowed, audioFromBuffer, audioFromFile, audioMediaTypeForFilename, batch, bm25Rank, budget, buildCatalog, buildPlanSystemPrompt, buildRouterContextMessage, cacheVectorStore, captureChildReport, memory as checkpointMemory, pg as checkpointPg, redis as checkpointRedis, chunk, collectStreamObject, composeMiddleware, computeCost, computeImageCost, computeOrchestratorSignature, computeSignature as computePlannerSignature, computeSignature$1 as computeSignature, computeSignature$2 as computeSupervisorSignature, contains, createAgentStream, createCommandDispatcher as createOrchestratorCommandDispatcher, createOrchestratorStream, createCancelledError as createSupervisorCancelledError, createSupervisorStream, currentRunFrame, dataset, defaultPromptsManager, diff, directorySource, encodeSSE, evalScorers, evaluatePolicy, exact, executableToTool, extractJsonLenient, extractJsonPayload, extractJsonSchema, extractUserText, fallbackModel, fanOut, fetchTextWithPolicy, forTool, fromJSON, generateRunId, getAIConfig, getObservers, guard, guardedFetch, guardrail, hashRequest, humanApproval, hybridRank, image, inProcessSessionLock, injectMemories as injectOrchestratorMemories, injection, instruction, memory$1 as interruptMemory, pg$1 as interruptPg, redis$1 as interruptRedis, isExecutableTool, isObserveAll, isPrivateOrReservedIp, judge, keywordReranker, llmReranker, loadHtml, loadPdf, loadRecord, loadSkillTool, loadSnapshotForResume as loadSupervisorSnapshotForResume, loadText, loadWeb, matchConverge, matchOutputShape, matchPassStep, matchRouteTo, memory$2 as memory, mergeUsage, mockAgent, mockRouter, moderation, multiQuery, namespacedState, noopSessionLock, normalizeAgentTools, onConfigApplied, orchestrator, asTool as orchestratorAsTool, memoryQueryFromInput as orchestratorMemoryQueryFromInput, outcomeTextFromTurn as orchestratorOutcomeTextFromTurn, parseFrontmatter, parsePartialJson, parseTags, persistSupervisorSnapshot, persona, pgVectorStore, pii, planSchema, planner, predicate, prepareAttachmentPart, proceduralSkillStore, prompt, promptKey, prompts, rag, readBudgetFallbackSignal, readTextCapped, recallForTurn as recallOrchestratorMemory, reciprocalRankFusion, redact, redactError, redactHeaders, registerAiMatchers, registerObserver, rememberTurnOutcome as rememberOrchestratorTurnOutcome, renderCatalogPrompt, renderPlaceholders, resolveAttachment, resolveDefaultCheckpointStore, resolveDefaultSnapshotStore, resolveDefaultStore, resolveIntentEntries, resolveObservers, resolveOrchestratorMemory, resolveOutboundPolicy, resolveSource, resume, router, runEval, runResume as runOrchestratorResume, runTurn as runOrchestratorTurn, runPipeline, runReviewGate, safeJsonParse, saveSkillTool, scrubSecrets, semanticCache, semanticPreselect, serve, setAIConfig, setObserveAll, skills, memory$3 as snapshotMemory, pg$2 as snapshotPg, redis$2 as snapshotRedis, spawnSubAgent, speech, stampReportLineage, step, storeSource, streamObject, streamTurn as streamOrchestratorTurn, streamToSSE, supervisor, asTool$1 as supervisorAsTool, systemPrompt, team, toJSON, toJUnit, tool, topic, transcribe, urlSource, vcr, vectorLiteral, withRunFrame, withoutRunFrame, workflow };
313
315
  import "./ai.mjs";
314
316
  import "./config.mjs";
315
317
  import "./testing/matchers.mjs";
package/esm/index.mjs CHANGED
@@ -22,6 +22,7 @@ import { PlannerFailedError } from "./errors/planner-failed-error.mjs";
22
22
  import { PlannerCancelledError } from "./errors/planner-cancelled-error.mjs";
23
23
  import { PlannerDriftError } from "./errors/planner-drift-error.mjs";
24
24
  import { PlannerPlanInvalidError } from "./errors/planner-plan-invalid-error.mjs";
25
+ import { PromptRefinementError } from "./errors/prompt-refinement-error.mjs";
25
26
  import { ProviderAuthError } from "./errors/provider-auth-error.mjs";
26
27
  import { ProviderRateLimitError } from "./errors/provider-rate-limit-error.mjs";
27
28
  import { ProviderTimeoutError } from "./errors/provider-timeout-error.mjs";
@@ -165,6 +166,7 @@ import "./planner/index.mjs";
165
166
  import { renderPlaceholders } from "./system-prompt/render-placeholders.mjs";
166
167
  import { Instruction, instruction } from "./system-prompt/instruction.mjs";
167
168
  import { Persona, persona } from "./system-prompt/persona.mjs";
169
+ import { RefinedSystemPrompt } from "./system-prompt/refined-system-prompt.mjs";
168
170
  import { SystemPrompt, systemPrompt } from "./system-prompt/system-prompt.mjs";
169
171
  import { defaultPromptsManager, promptKey, prompts } from "./prompts/prompts-manager.mjs";
170
172
  import { chunk } from "./rag/chunk/chunk.mjs";
@@ -212,4 +214,4 @@ import "./workflow/index.mjs";
212
214
  import { matchConverge, matchOutputShape, matchPassStep, matchRouteTo } from "./testing/matcher-logic.mjs";
213
215
  import { registerAiMatchers } from "./testing/register-lazy.mjs";
214
216
 
215
- export { AIError, AgentCancelledError, AgentDriftError, AgentExecutionError, AgentMaxTripsError, ApprovalRejectedError, BudgetExceededError, ContentFilterError, ContextLengthExceededError, DEFAULT_HASH_OPTIONS, DEFAULT_SENSITIVE_KEYS, END, GuardrailViolationError, Instruction, InterruptSuspendedError, InvalidRequestError, JUDGE_DEFAULT_REPAIR_ATTEMPTS, MaxIterationsError, MaxStepsExceededError, MockImageModel, MockModel, MockSDK, MockSkillsStore, MockSpeechModel, MockTranscriptionModel, OPENAI_INSTALL_INSTRUCTIONS, OrchestratorCancelledError, OrchestratorConfigError, OrchestratorDriftError, OrchestratorEmitter, OrchestratorExecution, OrchestratorFailedError, OutboundPolicyError, PDF_PARSE_INSTALL_INSTRUCTIONS, Persona, PlannerCancelledError, PlannerDriftError, PlannerFailedError, PlannerPlanInvalidError, PromptNotFoundError, PromptValidationError, ProviderAuthError, ProviderError, ProviderRateLimitError, ProviderTimeoutError, QuotaExceededError, REPORT_SCHEMA_VERSION, RoutingError, SENSITIVE_HEADERS, SSE_DONE, SchemaValidationError, StepFailedError, SupervisorCancelledError, SupervisorDriftError, SupervisorEmitter, SupervisorExecution, SupervisorFailedError, SupervisorRoutingError, SystemPrompt, ToolExecutionError, VcrCassetteMissError, WorkflowCancelledError, WorkflowDriftError, WorkflowError, accumulateCost, agent, ai, approximateTokenCount, assertUrlAllowed, audioFromBuffer, audioFromFile, audioMediaTypeForFilename, batch, bm25Rank, budget, buildCatalog, buildPlanSystemPrompt, buildRouterContextMessage, cacheVectorStore, captureChildReport, memory as checkpointMemory, pg as checkpointPg, redis as checkpointRedis, chunk, collectStreamObject, composeMiddleware, computeCost, computeImageCost, computeOrchestratorSignature, computeSignature as computePlannerSignature, computeSignature$1 as computeSignature, computeSignature$2 as computeSupervisorSignature, contains, createAgentStream, createCommandDispatcher as createOrchestratorCommandDispatcher, createOrchestratorStream, createCancelledError as createSupervisorCancelledError, createSupervisorStream, currentRunFrame, dataset, defaultPromptsManager, diff, directorySource, encodeSSE, evalScorers, evaluatePolicy, exact, executableToTool, extractJsonLenient, extractJsonPayload, extractJsonSchema, extractUserText, fallbackModel, fanOut, fetchTextWithPolicy, forTool, fromJSON, generateRunId, getAIConfig, getObservers, guard, guardedFetch, guardrail, hashRequest, humanApproval, hybridRank, image, inProcessSessionLock, injectMemories as injectOrchestratorMemories, injection, instruction, memory$1 as interruptMemory, pg$1 as interruptPg, redis$1 as interruptRedis, isExecutableTool, isObserveAll, isPrivateOrReservedIp, judge, keywordReranker, llmReranker, loadHtml, loadPdf, loadRecord, loadSkillTool, loadSnapshotForResume as loadSupervisorSnapshotForResume, loadText, loadWeb, matchConverge, matchOutputShape, matchPassStep, matchRouteTo, memory$2 as memory, mergeUsage, mockAgent, mockRouter, moderation, multiQuery, namespacedState, noopSessionLock, normalizeAgentTools, onConfigApplied, orchestrator, asTool as orchestratorAsTool, memoryQueryFromInput as orchestratorMemoryQueryFromInput, outcomeTextFromTurn as orchestratorOutcomeTextFromTurn, parseFrontmatter, parsePartialJson, parseTags, persistSupervisorSnapshot, persona, pgVectorStore, pii, planSchema, planner, predicate, prepareAttachmentPart, proceduralSkillStore, prompt, promptKey, prompts, rag, readBudgetFallbackSignal, readTextCapped, recallForTurn as recallOrchestratorMemory, reciprocalRankFusion, redact, redactError, redactHeaders, registerAiMatchers, registerObserver, rememberTurnOutcome as rememberOrchestratorTurnOutcome, renderCatalogPrompt, renderPlaceholders, resolveAttachment, resolveDefaultCheckpointStore, resolveDefaultSnapshotStore, resolveDefaultStore, resolveIntentEntries, resolveObservers, resolveOrchestratorMemory, resolveOutboundPolicy, resolveSource, resume, router, runEval, runResume as runOrchestratorResume, runTurn as runOrchestratorTurn, runPipeline, runReviewGate, safeJsonParse, saveSkillTool, scrubSecrets, semanticCache, semanticPreselect, serve, setAIConfig, setObserveAll, skills, memory$3 as snapshotMemory, pg$2 as snapshotPg, redis$2 as snapshotRedis, spawnSubAgent, speech, stampReportLineage, step, storeSource, streamObject, streamTurn as streamOrchestratorTurn, streamToSSE, supervisor, asTool$1 as supervisorAsTool, systemPrompt, team, toJSON, toJUnit, tool, topic, transcribe, urlSource, vcr, vectorLiteral, withRunFrame, withoutRunFrame, workflow };
217
+ export { AIError, AgentCancelledError, AgentDriftError, AgentExecutionError, AgentMaxTripsError, ApprovalRejectedError, BudgetExceededError, ContentFilterError, ContextLengthExceededError, DEFAULT_HASH_OPTIONS, DEFAULT_SENSITIVE_KEYS, END, GuardrailViolationError, Instruction, InterruptSuspendedError, InvalidRequestError, JUDGE_DEFAULT_REPAIR_ATTEMPTS, MaxIterationsError, MaxStepsExceededError, MockImageModel, MockModel, MockSDK, MockSkillsStore, MockSpeechModel, MockTranscriptionModel, OPENAI_INSTALL_INSTRUCTIONS, OrchestratorCancelledError, OrchestratorConfigError, OrchestratorDriftError, OrchestratorEmitter, OrchestratorExecution, OrchestratorFailedError, OutboundPolicyError, PDF_PARSE_INSTALL_INSTRUCTIONS, Persona, PlannerCancelledError, PlannerDriftError, PlannerFailedError, PlannerPlanInvalidError, PromptNotFoundError, PromptRefinementError, PromptValidationError, ProviderAuthError, ProviderError, ProviderRateLimitError, ProviderTimeoutError, QuotaExceededError, REPORT_SCHEMA_VERSION, RefinedSystemPrompt, RoutingError, SENSITIVE_HEADERS, SSE_DONE, SchemaValidationError, StepFailedError, SupervisorCancelledError, SupervisorDriftError, SupervisorEmitter, SupervisorExecution, SupervisorFailedError, SupervisorRoutingError, SystemPrompt, ToolExecutionError, VcrCassetteMissError, WorkflowCancelledError, WorkflowDriftError, WorkflowError, accumulateCost, agent, ai, approximateTokenCount, assertUrlAllowed, audioFromBuffer, audioFromFile, audioMediaTypeForFilename, batch, bm25Rank, budget, buildCatalog, buildPlanSystemPrompt, buildRouterContextMessage, cacheVectorStore, captureChildReport, memory as checkpointMemory, pg as checkpointPg, redis as checkpointRedis, chunk, collectStreamObject, composeMiddleware, computeCost, computeImageCost, computeOrchestratorSignature, computeSignature as computePlannerSignature, computeSignature$1 as computeSignature, computeSignature$2 as computeSupervisorSignature, contains, createAgentStream, createCommandDispatcher as createOrchestratorCommandDispatcher, createOrchestratorStream, createCancelledError as createSupervisorCancelledError, createSupervisorStream, currentRunFrame, dataset, defaultPromptsManager, diff, directorySource, encodeSSE, evalScorers, evaluatePolicy, exact, executableToTool, extractJsonLenient, extractJsonPayload, extractJsonSchema, extractUserText, fallbackModel, fanOut, fetchTextWithPolicy, forTool, fromJSON, generateRunId, getAIConfig, getObservers, guard, guardedFetch, guardrail, hashRequest, humanApproval, hybridRank, image, inProcessSessionLock, injectMemories as injectOrchestratorMemories, injection, instruction, memory$1 as interruptMemory, pg$1 as interruptPg, redis$1 as interruptRedis, isExecutableTool, isObserveAll, isPrivateOrReservedIp, judge, keywordReranker, llmReranker, loadHtml, loadPdf, loadRecord, loadSkillTool, loadSnapshotForResume as loadSupervisorSnapshotForResume, loadText, loadWeb, matchConverge, matchOutputShape, matchPassStep, matchRouteTo, memory$2 as memory, mergeUsage, mockAgent, mockRouter, moderation, multiQuery, namespacedState, noopSessionLock, normalizeAgentTools, onConfigApplied, orchestrator, asTool as orchestratorAsTool, memoryQueryFromInput as orchestratorMemoryQueryFromInput, outcomeTextFromTurn as orchestratorOutcomeTextFromTurn, parseFrontmatter, parsePartialJson, parseTags, persistSupervisorSnapshot, persona, pgVectorStore, pii, planSchema, planner, predicate, prepareAttachmentPart, proceduralSkillStore, prompt, promptKey, prompts, rag, readBudgetFallbackSignal, readTextCapped, recallForTurn as recallOrchestratorMemory, reciprocalRankFusion, redact, redactError, redactHeaders, registerAiMatchers, registerObserver, rememberTurnOutcome as rememberOrchestratorTurnOutcome, renderCatalogPrompt, renderPlaceholders, resolveAttachment, resolveDefaultCheckpointStore, resolveDefaultSnapshotStore, resolveDefaultStore, resolveIntentEntries, resolveObservers, resolveOrchestratorMemory, resolveOutboundPolicy, resolveSource, resume, router, runEval, runResume as runOrchestratorResume, runTurn as runOrchestratorTurn, runPipeline, runReviewGate, safeJsonParse, saveSkillTool, scrubSecrets, semanticCache, semanticPreselect, serve, setAIConfig, setObserveAll, skills, memory$3 as snapshotMemory, pg$2 as snapshotPg, redis$2 as snapshotRedis, spawnSubAgent, speech, stampReportLineage, step, storeSource, streamObject, streamTurn as streamOrchestratorTurn, streamToSSE, supervisor, asTool$1 as supervisorAsTool, systemPrompt, team, toJSON, toJUnit, tool, topic, transcribe, urlSource, vcr, vectorLiteral, withRunFrame, withoutRunFrame, workflow };
@@ -1 +1 @@
1
- {"version":3,"file":"prompts-manager.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/prompts/prompts-manager.ts"],"mappings":";;;;;;AAsCA;;iBAAgB,SAAA,CAAU,IAAA,UAAc,OAAe;;AAAA;AAqnBvD;;;;;;;;AAAgF;AAehF;;;;AAA+D;;;;;;;;iBAf/C,OAAA,CAAQ,OAAA,GAAU,qBAAA,GAAwB,sBAAsB;;iBAehE,qBAAA,IAAyB,sBAAsB"}
1
+ {"version":3,"file":"prompts-manager.d.mts","names":[],"sources":["../../../../../../../@warlock.js/ai/src/prompts/prompts-manager.ts"],"mappings":";;;;;;AAsCA;;iBAAgB,SAAA,CAAU,IAAA,UAAc,OAAe;;AAAA;AA2nBvD;;;;;;;;AAAgF;AAehF;;;;AAA+D;;;;;;;;iBAf/C,OAAA,CAAQ,OAAA,GAAU,qBAAA,GAAwB,sBAAsB;;iBAehE,qBAAA,IAAyB,sBAAsB"}
@@ -151,7 +151,7 @@ var PromptsManager = class {
151
151
  };
152
152
  }
153
153
  const cache = options.judgeCache ?? this.judgeCache;
154
- const judgeOutcome = await judgePromptBodyCached(text, options.judge, cache);
154
+ const judgeOutcome = await judgePromptBodyCached(text, options.judge, cache, options.criteria);
155
155
  const issues = [...unreferenced.map((key) => `Required key "${key}" is never referenced in the prompt.`), ...judgeOutcome.issues];
156
156
  return {
157
157
  ok,