@modainteract/moda-interact-shared 5.7.0 → 5.8.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.
@@ -1,9 +1,9 @@
1
- import { a as CommerceConversationGrant, b as CommerceManifest, S as SubsetSchema, e as CommercePurposeOutputSchema, d as CommerceFinalResponse, D as Digest, C as CommerceTurnIdentity } from '../response-DFDEw4K0.js';
2
- export { h as CommerceAlternativeSchema, i as CommerceAnswerPresentationSelection, j as CommerceAnswerPresentationSelectionSchema, k as CommerceAssertionSchema, l as CommerceBasketSchema, m as CommerceCategoryCandidate, n as CommerceCategoryCandidateSchema, o as CommerceCategoryResolution, p as CommerceCategoryResolutionSchema, q as CommerceConversationGrantSchema, r as CommerceDiscountCombinationFacts, s as CommerceDiscountCombinationFactsSchema, t as CommerceDiscountConditionFacts, u as CommerceDiscountConditionFactsSchema, v as CommerceDiscountDetails, w as CommerceDiscountDetailsSchema, x as CommerceErrorCodeSchema, y as CommerceEvidence, z as CommerceEvidenceSchema, A as CommerceExecuteAssertionSchema, B as CommerceFinalResponseSchema, E as CommerceManifestSchema, F as CommerceOfferSchema, G as CommerceOptionalLookupUnavailable, H as CommerceOptionalLookupUnavailableSchema, I as CommerceProduct, J as CommerceProductOptionsSchema, K as CommerceProductRecommendationSelection, L as CommerceProductRecommendationSelectionSchema, M as CommerceProductSaleEvidence, N as CommerceProductSaleEvidenceSchema, f as CommerceProductSchema, O as CommerceProductSelectedOptionsSchema, P as CommerceProposalSchema, Q as CommercePurposeOutputSchemaSchema, R as CommerceReleaseIdentitySchema, T as CommerceResolveAssertionSchema, U as CommerceResponseContract, V as CommerceResponseContractSchema, W as CommerceResponseDisposition, X as CommerceResponseDispositionSchema, Y as CommerceShippingInformation, Z as CommerceShippingInformationInput, _ as CommerceShippingInformationInputSchema, $ as CommerceShippingInformationSchema, g as CommerceToolInputs, a0 as CommerceToolOutputs, c as CommerceToolResult, a1 as CommerceToolResultSchema, a2 as CommerceTurnIdentitySchema, a3 as DetailsSchemaSchema, a4 as EMPTY_RESPONSE_CONTRACT, a5 as InputSchemaSchema, a6 as Json, a7 as MONEY_PATTERN, a8 as ReferralReasonSchema, a9 as canonicalJson, aa as commerceToolResultSchema, ab as compileCommercePurposeOutputSchema, ac as compileSubset, ad as finalResponseSchema, ae as finalResponseToolSchema, af as jsonBytes, ag as matchesSubset, ah as normalizeCommerceProductOptions, ai as normalizeCommerceProductSelectedOptions, aj as productBelongsToDomain, ak as responseContractCanonicalJson, al as safeName, am as safePath, an as validateCommercePurposeOutputSchema, ao as validateSubset, ap as verifyResponseContract } from '../response-DFDEw4K0.js';
1
+ import { a as CommerceConversationGrant, b as CommerceManifest, S as SubsetSchema, e as CommercePurposeOutputSchema, h as CommerceAnswerPresentationSelection, d as CommerceFinalResponse, D as Digest, C as CommerceTurnIdentity } from '../response-DD6HXT8s.js';
2
+ export { i as CommerceAlternativeSchema, j as CommerceAnswerPresentationSelectionSchema, k as CommerceAssertionSchema, l as CommerceBasketSchema, m as CommerceCategoryCandidate, n as CommerceCategoryCandidateSchema, o as CommerceCategoryResolution, p as CommerceCategoryResolutionSchema, q as CommerceConversationGrantSchema, r as CommerceDiscountCombinationFacts, s as CommerceDiscountCombinationFactsSchema, t as CommerceDiscountConditionFacts, u as CommerceDiscountConditionFactsSchema, v as CommerceDiscountDetails, w as CommerceDiscountDetailsSchema, x as CommerceErrorCodeSchema, y as CommerceEvidence, z as CommerceEvidenceSchema, A as CommerceExecuteAssertionSchema, B as CommerceFinalResponseSchema, E as CommerceManifestSchema, F as CommerceOfferSchema, G as CommerceOptionalLookupUnavailable, H as CommerceOptionalLookupUnavailableSchema, I as CommerceProduct, J as CommerceProductOptionsSchema, K as CommerceProductRecommendationSelection, L as CommerceProductRecommendationSelectionSchema, M as CommerceProductSaleEvidence, N as CommerceProductSaleEvidenceSchema, f as CommerceProductSchema, O as CommerceProductSelectedOptionsSchema, P as CommerceProposalSchema, Q as CommercePurposeOutputSchemaSchema, R as CommerceReleaseIdentitySchema, T as CommerceResolveAssertionSchema, U as CommerceResponseContract, V as CommerceResponseContractSchema, W as CommerceResponseDisposition, X as CommerceResponseDispositionSchema, Y as CommerceShippingInformation, Z as CommerceShippingInformationInput, _ as CommerceShippingInformationInputSchema, $ as CommerceShippingInformationSchema, g as CommerceToolInputs, a0 as CommerceToolOutputs, c as CommerceToolResult, a1 as CommerceToolResultSchema, a2 as CommerceTurnIdentitySchema, a3 as DetailsSchemaSchema, a4 as EMPTY_RESPONSE_CONTRACT, a5 as InputSchemaSchema, a6 as Json, a7 as MONEY_PATTERN, a8 as ReferralReasonSchema, a9 as canonicalJson, aa as commerceToolResultSchema, ab as compileCommercePurposeOutputSchema, ac as compileSubset, ad as finalResponseSchema, ae as finalResponseToolSchema, af as jsonBytes, ag as matchesSubset, ah as normalizeCommerceProductOptions, ai as normalizeCommerceProductSelectedOptions, aj as productBelongsToDomain, ak as responseContractCanonicalJson, al as safeName, am as safePath, an as validateCommercePurposeOutputSchema, ao as validateSubset, ap as verifyResponseContract } from '../response-DD6HXT8s.js';
3
3
  import * as zod from 'zod';
4
4
  import { z } from 'zod';
5
- import { b as CommerceBuiltInToolDescriptor, P as PublishedToolDescriptor, G as GrantedTool, c as CommerceToolDefinition, d as CommerceBuiltInToolGrant } from '../product-context-Bh74WGOo.js';
6
- export { e as CommerceBuiltInToolDescriptorSchema, f as CommerceBuiltInToolGrantSchema, g as CommerceBuiltInToolNameSchema, a as CommerceConversationProductContext, h as CommerceConversationProductContextSchema, i as CommerceDefinitionCompiler, C as CommerceExecutionPurpose, j as CommerceExecutionPurposeSchema, k as CommerceExecutionSchema, l as CommerceProductContextIdentity, m as CommerceProductObservation, n as CommercePurposeProfile, o as CommercePurposeProfileSchema, p as CommerceToolDefinitionSchema, q as CommerceToolDraftDefinition, r as CommerceToolDraftDefinitionSchema, s as CommerceToolIdentitySchema, t as CommerceToolRevisionIdentitySchema, E as ExternalHttpExecution, u as ExternalHttpExecutionSchema, v as GrantedToolSchema, w as GrantedToolsSchema, x as POLICY_OPERATIONS, y as POLICY_OPERATION_DESCRIPTORS, z as PublishedGrantedTool, A as PublishedGrantedToolSchema, B as PublishedToolDescriptorSchema, R as ResponseTemplateSchema, T as ToolDescriptor, D as ToolDescriptorSchema, F as ToolNameSchema, H as definitionToMcpDescriptor, I as isBuiltInTool, J as mapToolArguments, K as mergeConversationProductContext, L as requireCommercePurposeProfile, M as resolveConversationProductReference, N as toolHashInput, O as validateDefinitionForPublication, Q as validateDefinitionVersion } from '../product-context-Bh74WGOo.js';
5
+ import { b as CommerceBuiltInToolDescriptor, P as PublishedToolDescriptor, G as GrantedTool, c as CommerceToolDefinition, d as CommerceBuiltInToolGrant } from '../product-context-qfk6k9uk.js';
6
+ export { e as CommerceBuiltInToolDescriptorSchema, f as CommerceBuiltInToolGrantSchema, g as CommerceBuiltInToolNameSchema, a as CommerceConversationProductContext, h as CommerceConversationProductContextSchema, i as CommerceDefinitionCompiler, C as CommerceExecutionPurpose, j as CommerceExecutionPurposeSchema, k as CommerceExecutionSchema, l as CommerceProductContextIdentity, m as CommerceProductObservation, n as CommercePurposeProfile, o as CommercePurposeProfileSchema, p as CommerceToolDefinitionSchema, q as CommerceToolDraftDefinition, r as CommerceToolDraftDefinitionSchema, s as CommerceToolIdentitySchema, t as CommerceToolRevisionIdentitySchema, E as ExternalHttpExecution, u as ExternalHttpExecutionSchema, v as GrantedToolSchema, w as GrantedToolsSchema, x as POLICY_OPERATIONS, y as POLICY_OPERATION_DESCRIPTORS, z as PublishedGrantedTool, A as PublishedGrantedToolSchema, B as PublishedToolDescriptorSchema, R as ResponseTemplateSchema, T as ToolDescriptor, D as ToolDescriptorSchema, F as ToolNameSchema, H as definitionToMcpDescriptor, I as isBuiltInTool, J as mapToolArguments, K as mergeConversationProductContext, L as requireCommercePurposeProfile, M as resolveConversationProductReference, N as toolHashInput, O as validateDefinitionForPublication, Q as validateDefinitionVersion } from '../product-context-qfk6k9uk.js';
7
7
  import * as zod_v4_core from 'zod/v4/core';
8
8
 
9
9
  declare const ContractVersionSchema: z.ZodLiteral<"commerce.v1">;
@@ -302,6 +302,14 @@ declare function currentlyGrantedTools(grant: CommerceConversationGrant, eligibl
302
302
  toolName: "commerce_get_discount_options" | "commerce_get_discount_details";
303
303
  definitionVersion: "2.0.0";
304
304
  })[];
305
+ /** Validate model-selected identities; hosts must still authorize and freshly verify facts. */
306
+ declare function verifyCommerceAnswerPresentationSelection(raw: unknown): {
307
+ kind: "verified";
308
+ selection: CommerceAnswerPresentationSelection;
309
+ } | {
310
+ kind: "limitation";
311
+ reason: "INVALID_SELECTION";
312
+ };
305
313
 
306
314
  declare const ExternalQueryValueSchema: z.ZodUnion<readonly [z.ZodString, z.ZodNumber, z.ZodBoolean]>;
307
315
  declare const ExternalQueryMappingSchema: z.ZodUnion<readonly [z.ZodObject<{
@@ -681,4 +689,4 @@ declare const commerceDiscountBuiltInDescriptors: readonly CommerceBuiltInToolDe
681
689
  declare function isTrustedCommerceBuiltInDescriptor(value: CommerceBuiltInToolDescriptor): boolean;
682
690
  declare function isTrustedCommerceBuiltInGrant(value: CommerceBuiltInToolGrant): boolean;
683
691
 
684
- export { type CodeResponseProcessorInput, type CodeResponseProcessorResult, CommerceBuiltInToolDescriptor, CommerceBuiltInToolGrant, CommerceConversationGrant, CommerceFinalResponse, CommerceManifest, type CommerceOutreachToolContext, CommerceOutreachToolContextSchema, type CommerceProductAttributes, CommerceProductAttributesSchema, type CommerceProductDescription, CommerceProductDescriptionSchema, CommercePurposeOutputSchema, CommerceToolDefinition, CommerceTurnIdentity, type ConnectionCommand, ConnectionCommandSchema, ConnectionIssueSchema, type ConnectionResult, ConnectionResultSchema, type ConnectionRevisionView, ConnectionRevisionViewSchema, type ConnectionView, ConnectionViewSchema, ContractVersionSchema, type CredentialStatus, CredentialStatusSchema, CurrencySchema, DISCOUNT_POLICY_OPERATION_DESCRIPTORS, DateSchema, Digest, type DiscountPolicyOperationDescriptor, type ExternalHttpResultData, ExternalHttpResultDataSchema, ExternalPathSchema, ExternalQueryMappingSchema, ExternalQueryMappingsSchema, ExternalQueryValueSchema, type ExternalResponseFormat, ExternalResponseFormatSchema, type FeatureFacts, type FieldProjection, FieldProjectionSchema, GrantedTool, HashSchema, IdSchema, type InitialOutreachCheckoutOfferSet, InitialOutreachCheckoutOfferSetSchema, LanguageSchema, MAX_STORE_CATEGORY_PROMPT_CONDITIONS, MAX_STORE_CATEGORY_PROMPT_RENDERED_CHARS, MAX_STORE_CATEGORY_PROMPT_SOURCE_CHARS, MoneySchema, PublishedToolDescriptor, type ResponseFilter, ResponseFilterSchema, type ResponseProcessing, ResponseProcessingSchema, type RevisionInput, RevisionInputSchema, STORE_CATEGORY_PROMPT_RUNTIME_VERSION, SemverSchema, type StoreCategoryPromptConditionKey, StoreCategoryPromptConditionKeySchema, type StoreCategoryPromptContext, StoreCategoryPromptContextSchema, type StoreCategoryPromptRenderResult, type StoreCategoryPromptTemplateIssue, type StoreCategoryPromptTemplateValidation, SubsetSchema, type TransformResponse, TransformResponseSchema, type TransformSample, TransformSampleSchema, type VisualResponseProcessing, VisualResponseProcessingSchema, type VisualResponseProcessorInput, type VisualResponseProcessorResult, boundedJson, commerceDiscountBuiltInDescriptors, createStoreCategoryPromptConditionBlock, createStoreCategoryPromptContext, currentlyGrantedTools, deduplicateTools, distinct, exampleDefinition, exampleFinal, exampleGrant, exampleManifest, exampleTool, exampleTurn, isTrustedCommerceBuiltInDescriptor, isTrustedCommerceBuiltInGrant, manifestMatchesGrant, normalizeCommerceProductAttributes, normalizeCommerceProductDescription, normalizeCommerceProductDescriptionField, parseCommerceManifest, renderStoreCategoryPromptTemplate, selectCapabilities, validateStoreCategoryPromptTemplate };
692
+ export { type CodeResponseProcessorInput, type CodeResponseProcessorResult, CommerceAnswerPresentationSelection, CommerceBuiltInToolDescriptor, CommerceBuiltInToolGrant, CommerceConversationGrant, CommerceFinalResponse, CommerceManifest, type CommerceOutreachToolContext, CommerceOutreachToolContextSchema, type CommerceProductAttributes, CommerceProductAttributesSchema, type CommerceProductDescription, CommerceProductDescriptionSchema, CommercePurposeOutputSchema, CommerceToolDefinition, CommerceTurnIdentity, type ConnectionCommand, ConnectionCommandSchema, ConnectionIssueSchema, type ConnectionResult, ConnectionResultSchema, type ConnectionRevisionView, ConnectionRevisionViewSchema, type ConnectionView, ConnectionViewSchema, ContractVersionSchema, type CredentialStatus, CredentialStatusSchema, CurrencySchema, DISCOUNT_POLICY_OPERATION_DESCRIPTORS, DateSchema, Digest, type DiscountPolicyOperationDescriptor, type ExternalHttpResultData, ExternalHttpResultDataSchema, ExternalPathSchema, ExternalQueryMappingSchema, ExternalQueryMappingsSchema, ExternalQueryValueSchema, type ExternalResponseFormat, ExternalResponseFormatSchema, type FeatureFacts, type FieldProjection, FieldProjectionSchema, GrantedTool, HashSchema, IdSchema, type InitialOutreachCheckoutOfferSet, InitialOutreachCheckoutOfferSetSchema, LanguageSchema, MAX_STORE_CATEGORY_PROMPT_CONDITIONS, MAX_STORE_CATEGORY_PROMPT_RENDERED_CHARS, MAX_STORE_CATEGORY_PROMPT_SOURCE_CHARS, MoneySchema, PublishedToolDescriptor, type ResponseFilter, ResponseFilterSchema, type ResponseProcessing, ResponseProcessingSchema, type RevisionInput, RevisionInputSchema, STORE_CATEGORY_PROMPT_RUNTIME_VERSION, SemverSchema, type StoreCategoryPromptConditionKey, StoreCategoryPromptConditionKeySchema, type StoreCategoryPromptContext, StoreCategoryPromptContextSchema, type StoreCategoryPromptRenderResult, type StoreCategoryPromptTemplateIssue, type StoreCategoryPromptTemplateValidation, SubsetSchema, type TransformResponse, TransformResponseSchema, type TransformSample, TransformSampleSchema, type VisualResponseProcessing, VisualResponseProcessingSchema, type VisualResponseProcessorInput, type VisualResponseProcessorResult, boundedJson, commerceDiscountBuiltInDescriptors, createStoreCategoryPromptConditionBlock, createStoreCategoryPromptContext, currentlyGrantedTools, deduplicateTools, distinct, exampleDefinition, exampleFinal, exampleGrant, exampleManifest, exampleTool, exampleTurn, isTrustedCommerceBuiltInDescriptor, isTrustedCommerceBuiltInGrant, manifestMatchesGrant, normalizeCommerceProductAttributes, normalizeCommerceProductDescription, normalizeCommerceProductDescriptionField, parseCommerceManifest, renderStoreCategoryPromptTemplate, selectCapabilities, validateStoreCategoryPromptTemplate, verifyCommerceAnswerPresentationSelection };
@@ -9,8 +9,9 @@ import {
9
9
  mergeConversationProductContext,
10
10
  parseCommerceManifest,
11
11
  resolveConversationProductReference,
12
- selectCapabilities
13
- } from "../chunk-WK7QSBHJ.js";
12
+ selectCapabilities,
13
+ verifyCommerceAnswerPresentationSelection
14
+ } from "../chunk-2XZVIWQZ.js";
14
15
  import {
15
16
  CommerceAlternativeSchema,
16
17
  CommerceAnswerPresentationSelectionSchema,
@@ -119,7 +120,7 @@ import {
119
120
  validateDefinitionVersion,
120
121
  validateSubset,
121
122
  verifyResponseContract
122
- } from "../chunk-WF2BDUPZ.js";
123
+ } from "../chunk-SW2AFMT7.js";
123
124
  import {
124
125
  ContractVersionSchema,
125
126
  CurrencySchema,
@@ -788,6 +789,7 @@ export {
788
789
  validateDefinitionVersion,
789
790
  validateStoreCategoryPromptTemplate,
790
791
  validateSubset,
792
+ verifyCommerceAnswerPresentationSelection,
791
793
  verifyResponseContract
792
794
  };
793
795
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/commerce/discount-capability-contracts.ts","../../src/commerce/store-category-prompt.ts","../../src/commerce/outreach-context.ts","../../src/commerce/fixtures.ts"],"sourcesContent":["import { CommerceToolInputs, CommerceToolOutputs } from \"./schemas.js\";\n\n/**\n * Canonical Shared mapping for the two published discount capabilities.\n * Consumers reuse these validators instead of maintaining local copies.\n * `operationVersion` is independent of immutable published tool definition\n * versions selected by Commerce during publication.\n */\nexport const DISCOUNT_POLICY_OPERATION_DESCRIPTORS = Object.freeze([\n Object.freeze({\n toolName: \"commerce_get_discount_options\",\n displayName: \"Get Discount Options\",\n operation: \"discounts.getOptions\",\n operationVersion: \"1.0.0\",\n description: \"Read the configured discount mode and available offers.\",\n inputValidator: CommerceToolInputs.commerce_get_discount_options,\n outputValidator: CommerceToolOutputs.commerce_get_discount_options,\n }),\n Object.freeze({\n toolName: \"commerce_get_discount_details\",\n displayName: \"Get Discount Details\",\n operation: \"discounts.getDetails\",\n operationVersion: \"1.0.0\",\n description: \"Read details and condition facts for a permitted discount.\",\n inputValidator: CommerceToolInputs.commerce_get_discount_details,\n outputValidator: CommerceToolOutputs.commerce_get_discount_details,\n }),\n] as const);\n\nexport type DiscountPolicyOperationDescriptor =\n (typeof DISCOUNT_POLICY_OPERATION_DESCRIPTORS)[number];\n","import { z } from \"zod\";\n\nexport const STORE_CATEGORY_PROMPT_RUNTIME_VERSION = \"store-category-prompt.v1\" as const;\nexport const MAX_STORE_CATEGORY_PROMPT_SOURCE_CHARS = 100_000;\nexport const MAX_STORE_CATEGORY_PROMPT_RENDERED_CHARS = 100_000;\nexport const MAX_STORE_CATEGORY_PROMPT_CONDITIONS = 256;\nconst MAX_CONTROL_TAGS = 512;\nconst MAX_CONTROL_DEPTH = 8;\nconst MAX_EXPRESSION_CHARS = 1_024;\n\nconst forbiddenConditionKeys = new Set([\"__proto__\", \"prototype\", \"constructor\"]);\nconst conditionKeyPattern = /^[a-z][a-z0-9_]{0,127}$/;\n\nexport const StoreCategoryPromptConditionKeySchema = z\n .string()\n .regex(conditionKeyPattern)\n .refine((value) => !forbiddenConditionKeys.has(value));\n\nexport type StoreCategoryPromptConditionKey = z.infer<typeof StoreCategoryPromptConditionKeySchema>;\n\nexport const StoreCategoryPromptContextSchema = z.strictObject({\n mappings: z\n .record(StoreCategoryPromptConditionKeySchema, z.boolean())\n .refine((value) => Object.keys(value).length <= MAX_STORE_CATEGORY_PROMPT_CONDITIONS),\n});\n\nexport type StoreCategoryPromptContext = z.infer<typeof StoreCategoryPromptContextSchema>;\n\nexport type StoreCategoryPromptTemplateIssue = {\n path: \"/promptText\";\n code:\n | \"invalid_prompt_source\"\n | \"unsupported_template_construct\"\n | \"invalid_template_structure\"\n | \"invalid_template_expression\"\n | \"invalid_mapping_condition\"\n | \"unknown_mapping_condition\"\n | \"template_too_complex\"\n | \"rendered_prompt_too_large\";\n message: string;\n};\n\nexport type StoreCategoryPromptTemplateValidation = {\n valid: boolean;\n issues: StoreCategoryPromptTemplateIssue[];\n referencedConditionKeys: string[];\n};\n\nexport type StoreCategoryPromptRenderResult =\n | { ok: true; promptText: string; referencedConditionKeys: string[] }\n | { ok: false; issues: StoreCategoryPromptTemplateIssue[] };\n\ntype ExpressionNode =\n | { kind: \"condition\"; key: string }\n | { kind: \"not\"; operand: ExpressionNode }\n | { kind: \"and\"; left: ExpressionNode; right: ExpressionNode }\n | { kind: \"or\"; left: ExpressionNode; right: ExpressionNode };\n\ntype TemplateNode =\n | { kind: \"text\"; text: string }\n | {\n kind: \"if\";\n branches: Array<{ expression: ExpressionNode; body: TemplateNode[] }>;\n elseBody: TemplateNode[] | null;\n };\n\ntype TemplateToken =\n | { kind: \"text\"; text: string }\n | { kind: \"control\"; source: string }\n | { kind: \"unsupported\"; source: string; marker: \"interpolation\" | \"comment\" };\n\ntype CompileResult = {\n issues: StoreCategoryPromptTemplateIssue[];\n nodes: TemplateNode[];\n referencedConditionKeys: string[];\n};\n\nfunction issue(code: StoreCategoryPromptTemplateIssue[\"code\"], message: string): StoreCategoryPromptTemplateIssue {\n return { path: \"/promptText\", code, message };\n}\n\nfunction boundedIssues(issues: StoreCategoryPromptTemplateIssue[]): StoreCategoryPromptTemplateIssue[] {\n return issues.slice(0, 32).map((entry) => ({\n path: entry.path,\n code: entry.code,\n message: entry.message.slice(0, 512),\n }));\n}\n\nfunction sourceLength(value: string): number {\n return Array.from(value).length;\n}\n\nfunction findNextMarker(source: string, start: number): { index: number; marker: \"{%\" | \"{{\" | \"{#\" } | null {\n let best: { index: number; marker: \"{%\" | \"{{\" | \"{#\" } | null = null;\n for (const marker of [\"{%\", \"{{\", \"{#\"] as const) {\n const index = source.indexOf(marker, start);\n if (index >= 0 && (!best || index < best.index)) best = { index, marker };\n }\n return best;\n}\n\nfunction tokenizeTemplate(source: string, issues: StoreCategoryPromptTemplateIssue[]): TemplateToken[] {\n const tokens: TemplateToken[] = [];\n let cursor = 0;\n while (cursor < source.length) {\n const next = findNextMarker(source, cursor);\n if (!next) {\n tokens.push({ kind: \"text\", text: source.slice(cursor) });\n break;\n }\n if (next.index > cursor) tokens.push({ kind: \"text\", text: source.slice(cursor, next.index) });\n const closeMarker = next.marker === \"{%\" ? \"%}\" : next.marker === \"{{\" ? \"}}\" : \"#}\";\n const close = source.indexOf(closeMarker, next.index + 2);\n if (close < 0) {\n issues.push(issue(\"invalid_template_structure\", `Unclosed ${next.marker} template construct.`));\n tokens.push({ kind: \"text\", text: source.slice(next.index) });\n break;\n }\n const raw = source.slice(next.index + 2, close).trim();\n if (next.marker === \"{%\") tokens.push({ kind: \"control\", source: raw });\n else tokens.push({ kind: \"unsupported\", source: raw, marker: next.marker === \"{{\" ? \"interpolation\" : \"comment\" });\n cursor = close + 2;\n }\n if (source.length === 0) tokens.push({ kind: \"text\", text: \"\" });\n return tokens;\n}\n\ntype ExprToken = { kind: \"word\"; value: string } | { kind: \"dot\" } | { kind: \"lparen\" } | { kind: \"rparen\" };\n\nfunction lexExpression(source: string, issues: StoreCategoryPromptTemplateIssue[]): ExprToken[] | null {\n if (sourceLength(source) > MAX_EXPRESSION_CHARS) {\n issues.push(issue(\"template_too_complex\", `Conditional expressions must not exceed ${MAX_EXPRESSION_CHARS} characters.`));\n return null;\n }\n const tokens: ExprToken[] = [];\n let cursor = 0;\n while (cursor < source.length) {\n const char = source[cursor];\n if (/\\s/.test(char)) {\n cursor += 1;\n continue;\n }\n if (char === \".\") {\n tokens.push({ kind: \"dot\" });\n cursor += 1;\n continue;\n }\n if (char === \"(\") {\n tokens.push({ kind: \"lparen\" });\n cursor += 1;\n continue;\n }\n if (char === \")\") {\n tokens.push({ kind: \"rparen\" });\n cursor += 1;\n continue;\n }\n const match = /^[A-Za-z_][A-Za-z0-9_]*/.exec(source.slice(cursor));\n if (!match) {\n issues.push(issue(\"invalid_template_expression\", \"Conditional expressions may only use mappings.<conditionKey>, not, and, or, and parentheses.\"));\n return null;\n }\n tokens.push({ kind: \"word\", value: match[0] });\n cursor += match[0].length;\n }\n return tokens;\n}\n\nfunction parseExpression(source: string, issues: StoreCategoryPromptTemplateIssue[], referenced: string[]): ExpressionNode | null {\n const tokens = lexExpression(source, issues);\n if (!tokens || tokens.length === 0) {\n if (tokens?.length === 0) issues.push(issue(\"invalid_template_expression\", \"A conditional expression is required.\"));\n return null;\n }\n let index = 0;\n const peekWord = (word: string) => {\n const token = tokens[index];\n return token?.kind === \"word\" && token.value === word;\n };\n\n const parsePrimary = (): ExpressionNode | null => {\n const token = tokens[index];\n if (token?.kind === \"lparen\") {\n index += 1;\n const inner = parseOr();\n if (tokens[index]?.kind !== \"rparen\") {\n issues.push(issue(\"invalid_template_expression\", \"Conditional expression parentheses are unbalanced.\"));\n return null;\n }\n index += 1;\n return inner;\n }\n if (!peekWord(\"mappings\")) {\n issues.push(issue(\"invalid_template_expression\", \"Conditional expressions must reference mappings.<conditionKey>.\"));\n return null;\n }\n index += 1;\n if (tokens[index]?.kind !== \"dot\") {\n issues.push(issue(\"invalid_template_expression\", \"Mapping conditions must use mappings.<conditionKey>.\"));\n return null;\n }\n index += 1;\n const keyToken = tokens[index];\n if (keyToken?.kind !== \"word\") {\n issues.push(issue(\"invalid_mapping_condition\", \"A valid mapping condition key is required after mappings.\"));\n return null;\n }\n index += 1;\n if (!StoreCategoryPromptConditionKeySchema.safeParse(keyToken.value).success) {\n issues.push(issue(\"invalid_mapping_condition\", `Invalid mapping condition key: ${keyToken.value}.`));\n return null;\n }\n if (!referenced.includes(keyToken.value)) referenced.push(keyToken.value);\n return { kind: \"condition\", key: keyToken.value };\n };\n\n const parseNot = (): ExpressionNode | null => {\n if (peekWord(\"not\")) {\n index += 1;\n const operand = parseNot();\n return operand ? { kind: \"not\", operand } : null;\n }\n return parsePrimary();\n };\n\n const parseAnd = (): ExpressionNode | null => {\n let left = parseNot();\n while (left && peekWord(\"and\")) {\n index += 1;\n const right = parseNot();\n if (!right) return null;\n left = { kind: \"and\", left, right };\n }\n return left;\n };\n\n const parseOr = (): ExpressionNode | null => {\n let left = parseAnd();\n while (left && peekWord(\"or\")) {\n index += 1;\n const right = parseAnd();\n if (!right) return null;\n left = { kind: \"or\", left, right };\n }\n return left;\n };\n\n const expression = parseOr();\n if (expression && index !== tokens.length) {\n issues.push(issue(\"invalid_template_expression\", \"Conditional expression contains unsupported syntax.\"));\n return null;\n }\n return expression;\n}\n\nfunction compileStoreCategoryPromptTemplate(source: string): CompileResult {\n const issues: StoreCategoryPromptTemplateIssue[] = [];\n const referencedConditionKeys: string[] = [];\n const nodes: TemplateNode[] = [];\n\n if (source.trim().length === 0) issues.push(issue(\"invalid_prompt_source\", \"Prompt template must not be blank.\"));\n if (sourceLength(source) > MAX_STORE_CATEGORY_PROMPT_SOURCE_CHARS) {\n issues.push(issue(\"invalid_prompt_source\", `Prompt template must not exceed ${MAX_STORE_CATEGORY_PROMPT_SOURCE_CHARS.toLocaleString()} characters.`));\n }\n\n const tokens = tokenizeTemplate(source, issues);\n type Frame = {\n node: Extract<TemplateNode, { kind: \"if\" }>;\n parentBody: TemplateNode[];\n currentBody: TemplateNode[];\n sawElse: boolean;\n };\n const stack: Frame[] = [];\n let currentBody = nodes;\n let controlCount = 0;\n\n for (const token of tokens) {\n if (token.kind === \"text\") {\n if (token.text) currentBody.push({ kind: \"text\", text: token.text });\n continue;\n }\n if (token.kind === \"unsupported\") {\n issues.push(issue(\n \"unsupported_template_construct\",\n token.marker === \"interpolation\"\n ? \"Variable interpolation is not supported in Store Category prompt templates.\"\n : \"Template comments are not supported in Store Category prompt templates.\",\n ));\n continue;\n }\n\n controlCount += 1;\n if (controlCount > MAX_CONTROL_TAGS) {\n issues.push(issue(\"template_too_complex\", `Prompt template must not contain more than ${MAX_CONTROL_TAGS} control tags.`));\n break;\n }\n\n const ifMatch = /^if\\s+([\\s\\S]+)$/.exec(token.source);\n if (ifMatch) {\n if (stack.length >= MAX_CONTROL_DEPTH) {\n issues.push(issue(\"template_too_complex\", `Conditional nesting must not exceed ${MAX_CONTROL_DEPTH} levels.`));\n continue;\n }\n const expression = parseExpression(ifMatch[1].trim(), issues, referencedConditionKeys);\n if (!expression) continue;\n const branchBody: TemplateNode[] = [];\n const node: Extract<TemplateNode, { kind: \"if\" }> = {\n kind: \"if\",\n branches: [{ expression, body: branchBody }],\n elseBody: null,\n };\n currentBody.push(node);\n const frame: Frame = { node, parentBody: currentBody, currentBody: branchBody, sawElse: false };\n stack.push(frame);\n currentBody = branchBody;\n continue;\n }\n\n const elifMatch = /^elif\\s+([\\s\\S]+)$/.exec(token.source);\n if (elifMatch) {\n const frame = stack.at(-1);\n if (!frame || frame.sawElse) {\n issues.push(issue(\"invalid_template_structure\", \"elif must appear inside an if block and before else.\"));\n continue;\n }\n const expression = parseExpression(elifMatch[1].trim(), issues, referencedConditionKeys);\n if (!expression) continue;\n const branchBody: TemplateNode[] = [];\n frame.node.branches.push({ expression, body: branchBody });\n frame.currentBody = branchBody;\n currentBody = branchBody;\n continue;\n }\n\n if (token.source === \"else\") {\n const frame = stack.at(-1);\n if (!frame || frame.sawElse) {\n issues.push(issue(\"invalid_template_structure\", \"else must appear once inside an if block.\"));\n continue;\n }\n const elseBody: TemplateNode[] = [];\n frame.node.elseBody = elseBody;\n frame.currentBody = elseBody;\n frame.sawElse = true;\n currentBody = elseBody;\n continue;\n }\n\n if (token.source === \"endif\") {\n const frame = stack.pop();\n if (!frame) {\n issues.push(issue(\"invalid_template_structure\", \"endif does not have a matching if block.\"));\n continue;\n }\n currentBody = frame.parentBody;\n continue;\n }\n\n issues.push(issue(\n \"unsupported_template_construct\",\n \"Only if, elif, else, and endif control tags are supported in Store Category prompt templates.\",\n ));\n }\n\n if (stack.length) issues.push(issue(\"invalid_template_structure\", \"Every if block must end with endif.\"));\n return { issues: boundedIssues(issues), nodes, referencedConditionKeys };\n}\n\nfunction validateAvailableConditionKeys(values: readonly string[], issues: StoreCategoryPromptTemplateIssue[]): Set<string> {\n if (values.length > MAX_STORE_CATEGORY_PROMPT_CONDITIONS) {\n issues.push(issue(\"template_too_complex\", `At most ${MAX_STORE_CATEGORY_PROMPT_CONDITIONS} mapping conditions are supported.`));\n }\n const keys = new Set<string>();\n for (const value of values.slice(0, MAX_STORE_CATEGORY_PROMPT_CONDITIONS + 1)) {\n if (!StoreCategoryPromptConditionKeySchema.safeParse(value).success) {\n issues.push(issue(\"invalid_mapping_condition\", `Invalid mapping condition key: ${value}.`));\n continue;\n }\n if (keys.has(value)) {\n issues.push(issue(\"invalid_mapping_condition\", `Duplicate mapping condition key: ${value}.`));\n continue;\n }\n keys.add(value);\n }\n return keys;\n}\n\nexport function validateStoreCategoryPromptTemplate(input: {\n source: string;\n availableConditionKeys: readonly string[];\n}): StoreCategoryPromptTemplateValidation {\n const compiled = compileStoreCategoryPromptTemplate(input.source);\n const issues = [...compiled.issues];\n const available = validateAvailableConditionKeys(input.availableConditionKeys, issues);\n for (const key of compiled.referencedConditionKeys) {\n if (!available.has(key)) issues.push(issue(\"unknown_mapping_condition\", `Prompt template references unavailable mapping condition: mappings.${key}.`));\n }\n const bounded = boundedIssues(issues);\n return { valid: bounded.length === 0, issues: bounded, referencedConditionKeys: compiled.referencedConditionKeys };\n}\n\n\nexport function createStoreCategoryPromptConditionBlock(conditionKey: string): string {\n const parsed = StoreCategoryPromptConditionKeySchema.safeParse(conditionKey);\n if (!parsed.success) throw new TypeError(`Invalid mapping condition key: ${conditionKey}.`);\n return `{% if mappings.${conditionKey} %}\\n\\n{% endif %}`;\n}\n\nexport function createStoreCategoryPromptContext(input: {\n availableConditionKeys: readonly string[];\n selectedConditionKeys: readonly string[];\n}): StoreCategoryPromptContext {\n const issues: StoreCategoryPromptTemplateIssue[] = [];\n const available = validateAvailableConditionKeys(input.availableConditionKeys, issues);\n const selected = validateAvailableConditionKeys(input.selectedConditionKeys, issues);\n for (const key of selected) {\n if (!available.has(key)) issues.push(issue(\"unknown_mapping_condition\", `Selected mapping condition is unavailable: ${key}.`));\n }\n if (issues.length) throw new TypeError(issues[0].message);\n const mappings = Object.create(null) as Record<string, boolean>;\n for (const key of available) mappings[key] = selected.has(key);\n return { mappings };\n}\n\nfunction evaluateExpression(expression: ExpressionNode, mappings: Record<string, boolean>): boolean {\n switch (expression.kind) {\n case \"condition\":\n return mappings[expression.key] === true;\n case \"not\":\n return !evaluateExpression(expression.operand, mappings);\n case \"and\":\n return evaluateExpression(expression.left, mappings) && evaluateExpression(expression.right, mappings);\n case \"or\":\n return evaluateExpression(expression.left, mappings) || evaluateExpression(expression.right, mappings);\n }\n}\n\nfunction renderNodes(nodes: TemplateNode[], mappings: Record<string, boolean>, append: (text: string) => boolean): boolean {\n for (const node of nodes) {\n if (node.kind === \"text\") {\n if (!append(node.text)) return false;\n continue;\n }\n let renderedBranch = false;\n for (const branch of node.branches) {\n if (evaluateExpression(branch.expression, mappings)) {\n if (!renderNodes(branch.body, mappings, append)) return false;\n renderedBranch = true;\n break;\n }\n }\n if (!renderedBranch && node.elseBody && !renderNodes(node.elseBody, mappings, append)) return false;\n }\n return true;\n}\n\nexport function renderStoreCategoryPromptTemplate(input: {\n source: string;\n context: StoreCategoryPromptContext;\n}): StoreCategoryPromptRenderResult {\n const contextResult = StoreCategoryPromptContextSchema.safeParse(input.context);\n if (!contextResult.success) {\n return { ok: false, issues: [issue(\"invalid_mapping_condition\", \"Store Category prompt context contains invalid mapping conditions.\")] };\n }\n const availableConditionKeys = Object.keys(contextResult.data.mappings);\n const validation = validateStoreCategoryPromptTemplate({ source: input.source, availableConditionKeys });\n if (!validation.valid) return { ok: false, issues: validation.issues };\n\n const compiled = compileStoreCategoryPromptTemplate(input.source);\n let output = \"\";\n let outputChars = 0;\n const append = (text: string) => {\n outputChars += sourceLength(text);\n if (outputChars > MAX_STORE_CATEGORY_PROMPT_RENDERED_CHARS) return false;\n output += text;\n return true;\n };\n const rendered = renderNodes(compiled.nodes, contextResult.data.mappings, append);\n if (!rendered) {\n return {\n ok: false,\n issues: [issue(\"rendered_prompt_too_large\", `Rendered prompt must not exceed ${MAX_STORE_CATEGORY_PROMPT_RENDERED_CHARS.toLocaleString()} characters.`)],\n };\n }\n return { ok: true, promptText: output, referencedConditionKeys: validation.referencedConditionKeys };\n}\n","import { z } from \"zod\";\n\nexport const CommerceOutreachToolContextSchema = z.strictObject({\n purpose: z.literal(\"INITIAL_RECOVERY_OUTREACH\"),\n});\n\nexport type CommerceOutreachToolContext =\n z.infer<typeof CommerceOutreachToolContextSchema>;\n","/** Synthetic examples; no provider identity, schema artifact or publication claim. */\nimport type {\n CommerceManifest,\n CommerceConversationGrant,\n CommerceTurnIdentity,\n} from \"./schemas\";\nimport {\n EMPTY_RESPONSE_CONTRACT,\n type CommerceFinalResponse,\n} from \"./response\";\nimport type { Digest } from \"./canonical-json\";\nimport { responseContractCanonicalJson } from \"./canonical-json\";\nimport type { PublishedToolDescriptor, CommerceToolDefinition } from \"./definitions\";\nexport const exampleTool: PublishedToolDescriptor = {\n toolId: \"tool-fixture\",\n toolRevisionId: \"revision-fixture\",\n name: \"never_seeded_catalogue_facts\",\n definitionVersion: \"1.0.0\",\n description: \"Read synthetic catalogue facts.\",\n inputSchema: {\n type: \"object\",\n properties: { handle: { type: \"string\", minLength: 1, maxLength: 255 } },\n required: [\"handle\"],\n additionalProperties: false,\n },\n};\nexport const exampleDefinition: CommerceToolDefinition = {\n name: exampleTool.name,\n definitionVersion: \"1.0.0\",\n description: exampleTool.description,\n inputSchema: exampleTool.inputSchema,\n execution: {\n kind: \"SHOPIFY_STOREFRONT_QUERY\",\n executorVersion: \"1.0.0\",\n apiVersion: \"2026-07\",\n schemaHash: \"a\".repeat(64),\n document:\n \"query ProductDetails($handle: String!) { product(handle: $handle) { title description } }\",\n operationName: \"ProductDetails\",\n variables: { handle: { input: \"handle\" } },\n resultPath: \"product\",\n },\n responseTemplate: {\n kind: \"text\",\n text: \"{{result.values.title}}: {{result.values.description}}\",\n unavailable: \"Product details could not be verified.\",\n },\n};\nexport const exampleTurn: CommerceTurnIdentity = {\n contractVersion: \"commerce.v1\",\n shopId: \"shop-fixture\",\n checkoutRecoveryId: \"recovery-fixture\",\n conversationId: \"conversation-fixture\",\n inboundVersion: 1,\n};\nexport function exampleManifest(\n digest: Digest,\n withTool = false,\n): CommerceManifest {\n const capabilities = withTool\n ? [{\n capabilityId: \"capability-fixture\",\n key: \"feature_product_read\",\n featureId: \"feature-fixture\",\n position: 0,\n toolDescriptor: structuredClone(exampleTool),\n }]\n : [];\n return {\n contractVersion: \"commerce.v1\",\n releaseId: \"release-fixture\",\n runnerCompatibility: \"^1.0.0\",\n capabilities,\n featureBehaviours: withTool\n ? [{ featureId: \"feature-fixture\", behaviourPrompt: \"Synthetic Feature behavior.\" }]\n : [],\n selectedCapabilityKeys: capabilities.map((capability) => capability.key),\n builtInTools: [],\n grantedTools: withTool\n ? [\n {\n toolId: exampleTool.toolId,\n toolRevisionId: exampleTool.toolRevisionId,\n toolName: exampleTool.name,\n definitionVersion: \"1.0.0\",\n capabilityKeys: [\"feature_product_read\"],\n },\n ]\n : [],\n responseContract: structuredClone(EMPTY_RESPONSE_CONTRACT),\n responseContractHash: digest(\n responseContractCanonicalJson(EMPTY_RESPONSE_CONTRACT),\n ),\n };\n}\nexport function exampleGrant(\n manifest: CommerceManifest,\n): CommerceConversationGrant {\n return {\n id: \"grant-fixture\",\n shopId: exampleTurn.shopId,\n conversationId: exampleTurn.conversationId,\n initialInboundVersion: 1,\n releaseId: manifest.releaseId,\n selectedCapabilityKeys: [...manifest.selectedCapabilityKeys],\n grantedTools: structuredClone(manifest.grantedTools),\n runnerVersion: \"1.0.0\",\n createdAt: \"2026-09-20T00:00:00.000Z\",\n expiresAt: null,\n };\n}\nexport const exampleFinal: CommerceFinalResponse = {\n answerKind: \"REFER_TO_STORE\",\n replyText:\n \"I cannot verify that information. Please contact the store directly.\",\n referralReason: \"INSUFFICIENT_TOOLS\",\n detectedLanguageTag: null,\n detectedLanguageConfidence: null,\n evidenceIds: [],\n details: {},\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQO,IAAM,wCAAwC,OAAO,OAAO;AAAA,EACjE,OAAO,OAAO;AAAA,IACZ,UAAU;AAAA,IACV,aAAa;AAAA,IACb,WAAW;AAAA,IACX,kBAAkB;AAAA,IAClB,aAAa;AAAA,IACb,gBAAgB,mBAAmB;AAAA,IACnC,iBAAiB,oBAAoB;AAAA,EACvC,CAAC;AAAA,EACD,OAAO,OAAO;AAAA,IACZ,UAAU;AAAA,IACV,aAAa;AAAA,IACb,WAAW;AAAA,IACX,kBAAkB;AAAA,IAClB,aAAa;AAAA,IACb,gBAAgB,mBAAmB;AAAA,IACnC,iBAAiB,oBAAoB;AAAA,EACvC,CAAC;AACH,CAAU;;;AC3BV,SAAS,SAAS;AAEX,IAAM,wCAAwC;AAC9C,IAAM,yCAAyC;AAC/C,IAAM,2CAA2C;AACjD,IAAM,uCAAuC;AACpD,IAAM,mBAAmB;AACzB,IAAM,oBAAoB;AAC1B,IAAM,uBAAuB;AAE7B,IAAM,yBAAyB,oBAAI,IAAI,CAAC,aAAa,aAAa,aAAa,CAAC;AAChF,IAAM,sBAAsB;AAErB,IAAM,wCAAwC,EAClD,OAAO,EACP,MAAM,mBAAmB,EACzB,OAAO,CAAC,UAAU,CAAC,uBAAuB,IAAI,KAAK,CAAC;AAIhD,IAAM,mCAAmC,EAAE,aAAa;AAAA,EAC7D,UAAU,EACP,OAAO,uCAAuC,EAAE,QAAQ,CAAC,EACzD,OAAO,CAAC,UAAU,OAAO,KAAK,KAAK,EAAE,UAAU,oC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AAC,GAAG,SAAS,sBAAsB;AAAA,IAC3D,cAAc,gBAAgB,SAAS,YAAY;AAAA,IACnD,eAAe;AAAA,IACf,WAAW;AAAA,IACX,WAAW;AAAA,EACb;AACF;AACO,IAAM,eAAsC;AAAA,EACjD,YAAY;AAAA,EACZ,WACE;AAAA,EACF,gBAAgB;AAAA,EAChB,qBAAqB;AAAA,EACrB,4BAA4B;AAAA,EAC5B,aAAa,CAAC;AAAA,EACd,SAAS,CAAC;AACZ;","names":["z"]}
1
+ {"version":3,"sources":["../../src/commerce/discount-capability-contracts.ts","../../src/commerce/store-category-prompt.ts","../../src/commerce/outreach-context.ts","../../src/commerce/fixtures.ts"],"sourcesContent":["import { CommerceToolInputs, CommerceToolOutputs } from \"./schemas.js\";\n\n/**\n * Canonical Shared mapping for the two published discount capabilities.\n * Consumers reuse these validators instead of maintaining local copies.\n * `operationVersion` is independent of immutable published tool definition\n * versions selected by Commerce during publication.\n */\nexport const DISCOUNT_POLICY_OPERATION_DESCRIPTORS = Object.freeze([\n Object.freeze({\n toolName: \"commerce_get_discount_options\",\n displayName: \"Get Discount Options\",\n operation: \"discounts.getOptions\",\n operationVersion: \"1.0.0\",\n description: \"Read the configured discount mode and available offers.\",\n inputValidator: CommerceToolInputs.commerce_get_discount_options,\n outputValidator: CommerceToolOutputs.commerce_get_discount_options,\n }),\n Object.freeze({\n toolName: \"commerce_get_discount_details\",\n displayName: \"Get Discount Details\",\n operation: \"discounts.getDetails\",\n operationVersion: \"1.0.0\",\n description: \"Read details and condition facts for a permitted discount.\",\n inputValidator: CommerceToolInputs.commerce_get_discount_details,\n outputValidator: CommerceToolOutputs.commerce_get_discount_details,\n }),\n] as const);\n\nexport type DiscountPolicyOperationDescriptor =\n (typeof DISCOUNT_POLICY_OPERATION_DESCRIPTORS)[number];\n","import { z } from \"zod\";\n\nexport const STORE_CATEGORY_PROMPT_RUNTIME_VERSION = \"store-category-prompt.v1\" as const;\nexport const MAX_STORE_CATEGORY_PROMPT_SOURCE_CHARS = 100_000;\nexport const MAX_STORE_CATEGORY_PROMPT_RENDERED_CHARS = 100_000;\nexport const MAX_STORE_CATEGORY_PROMPT_CONDITIONS = 256;\nconst MAX_CONTROL_TAGS = 512;\nconst MAX_CONTROL_DEPTH = 8;\nconst MAX_EXPRESSION_CHARS = 1_024;\n\nconst forbiddenConditionKeys = new Set([\"__proto__\", \"prototype\", \"constructor\"]);\nconst conditionKeyPattern = /^[a-z][a-z0-9_]{0,127}$/;\n\nexport const StoreCategoryPromptConditionKeySchema = z\n .string()\n .regex(conditionKeyPattern)\n .refine((value) => !forbiddenConditionKeys.has(value));\n\nexport type StoreCategoryPromptConditionKey = z.infer<typeof StoreCategoryPromptConditionKeySchema>;\n\nexport const StoreCategoryPromptContextSchema = z.strictObject({\n mappings: z\n .record(StoreCategoryPromptConditionKeySchema, z.boolean())\n .refine((value) => Object.keys(value).length <= MAX_STORE_CATEGORY_PROMPT_CONDITIONS),\n});\n\nexport type StoreCategoryPromptContext = z.infer<typeof StoreCategoryPromptContextSchema>;\n\nexport type StoreCategoryPromptTemplateIssue = {\n path: \"/promptText\";\n code:\n | \"invalid_prompt_source\"\n | \"unsupported_template_construct\"\n | \"invalid_template_structure\"\n | \"invalid_template_expression\"\n | \"invalid_mapping_condition\"\n | \"unknown_mapping_condition\"\n | \"template_too_complex\"\n | \"rendered_prompt_too_large\";\n message: string;\n};\n\nexport type StoreCategoryPromptTemplateValidation = {\n valid: boolean;\n issues: StoreCategoryPromptTemplateIssue[];\n referencedConditionKeys: string[];\n};\n\nexport type StoreCategoryPromptRenderResult =\n | { ok: true; promptText: string; referencedConditionKeys: string[] }\n | { ok: false; issues: StoreCategoryPromptTemplateIssue[] };\n\ntype ExpressionNode =\n | { kind: \"condition\"; key: string }\n | { kind: \"not\"; operand: ExpressionNode }\n | { kind: \"and\"; left: ExpressionNode; right: ExpressionNode }\n | { kind: \"or\"; left: ExpressionNode; right: ExpressionNode };\n\ntype TemplateNode =\n | { kind: \"text\"; text: string }\n | {\n kind: \"if\";\n branches: Array<{ expression: ExpressionNode; body: TemplateNode[] }>;\n elseBody: TemplateNode[] | null;\n };\n\ntype TemplateToken =\n | { kind: \"text\"; text: string }\n | { kind: \"control\"; source: string }\n | { kind: \"unsupported\"; source: string; marker: \"interpolation\" | \"comment\" };\n\ntype CompileResult = {\n issues: StoreCategoryPromptTemplateIssue[];\n nodes: TemplateNode[];\n referencedConditionKeys: string[];\n};\n\nfunction issue(code: StoreCategoryPromptTemplateIssue[\"code\"], message: string): StoreCategoryPromptTemplateIssue {\n return { path: \"/promptText\", code, message };\n}\n\nfunction boundedIssues(issues: StoreCategoryPromptTemplateIssue[]): StoreCategoryPromptTemplateIssue[] {\n return issues.slice(0, 32).map((entry) => ({\n path: entry.path,\n code: entry.code,\n message: entry.message.slice(0, 512),\n }));\n}\n\nfunction sourceLength(value: string): number {\n return Array.from(value).length;\n}\n\nfunction findNextMarker(source: string, start: number): { index: number; marker: \"{%\" | \"{{\" | \"{#\" } | null {\n let best: { index: number; marker: \"{%\" | \"{{\" | \"{#\" } | null = null;\n for (const marker of [\"{%\", \"{{\", \"{#\"] as const) {\n const index = source.indexOf(marker, start);\n if (index >= 0 && (!best || index < best.index)) best = { index, marker };\n }\n return best;\n}\n\nfunction tokenizeTemplate(source: string, issues: StoreCategoryPromptTemplateIssue[]): TemplateToken[] {\n const tokens: TemplateToken[] = [];\n let cursor = 0;\n while (cursor < source.length) {\n const next = findNextMarker(source, cursor);\n if (!next) {\n tokens.push({ kind: \"text\", text: source.slice(cursor) });\n break;\n }\n if (next.index > cursor) tokens.push({ kind: \"text\", text: source.slice(cursor, next.index) });\n const closeMarker = next.marker === \"{%\" ? \"%}\" : next.marker === \"{{\" ? \"}}\" : \"#}\";\n const close = source.indexOf(closeMarker, next.index + 2);\n if (close < 0) {\n issues.push(issue(\"invalid_template_structure\", `Unclosed ${next.marker} template construct.`));\n tokens.push({ kind: \"text\", text: source.slice(next.index) });\n break;\n }\n const raw = source.slice(next.index + 2, close).trim();\n if (next.marker === \"{%\") tokens.push({ kind: \"control\", source: raw });\n else tokens.push({ kind: \"unsupported\", source: raw, marker: next.marker === \"{{\" ? \"interpolation\" : \"comment\" });\n cursor = close + 2;\n }\n if (source.length === 0) tokens.push({ kind: \"text\", text: \"\" });\n return tokens;\n}\n\ntype ExprToken = { kind: \"word\"; value: string } | { kind: \"dot\" } | { kind: \"lparen\" } | { kind: \"rparen\" };\n\nfunction lexExpression(source: string, issues: StoreCategoryPromptTemplateIssue[]): ExprToken[] | null {\n if (sourceLength(source) > MAX_EXPRESSION_CHARS) {\n issues.push(issue(\"template_too_complex\", `Conditional expressions must not exceed ${MAX_EXPRESSION_CHARS} characters.`));\n return null;\n }\n const tokens: ExprToken[] = [];\n let cursor = 0;\n while (cursor < source.length) {\n const char = source[cursor];\n if (/\\s/.test(char)) {\n cursor += 1;\n continue;\n }\n if (char === \".\") {\n tokens.push({ kind: \"dot\" });\n cursor += 1;\n continue;\n }\n if (char === \"(\") {\n tokens.push({ kind: \"lparen\" });\n cursor += 1;\n continue;\n }\n if (char === \")\") {\n tokens.push({ kind: \"rparen\" });\n cursor += 1;\n continue;\n }\n const match = /^[A-Za-z_][A-Za-z0-9_]*/.exec(source.slice(cursor));\n if (!match) {\n issues.push(issue(\"invalid_template_expression\", \"Conditional expressions may only use mappings.<conditionKey>, not, and, or, and parentheses.\"));\n return null;\n }\n tokens.push({ kind: \"word\", value: match[0] });\n cursor += match[0].length;\n }\n return tokens;\n}\n\nfunction parseExpression(source: string, issues: StoreCategoryPromptTemplateIssue[], referenced: string[]): ExpressionNode | null {\n const tokens = lexExpression(source, issues);\n if (!tokens || tokens.length === 0) {\n if (tokens?.length === 0) issues.push(issue(\"invalid_template_expression\", \"A conditional expression is required.\"));\n return null;\n }\n let index = 0;\n const peekWord = (word: string) => {\n const token = tokens[index];\n return token?.kind === \"word\" && token.value === word;\n };\n\n const parsePrimary = (): ExpressionNode | null => {\n const token = tokens[index];\n if (token?.kind === \"lparen\") {\n index += 1;\n const inner = parseOr();\n if (tokens[index]?.kind !== \"rparen\") {\n issues.push(issue(\"invalid_template_expression\", \"Conditional expression parentheses are unbalanced.\"));\n return null;\n }\n index += 1;\n return inner;\n }\n if (!peekWord(\"mappings\")) {\n issues.push(issue(\"invalid_template_expression\", \"Conditional expressions must reference mappings.<conditionKey>.\"));\n return null;\n }\n index += 1;\n if (tokens[index]?.kind !== \"dot\") {\n issues.push(issue(\"invalid_template_expression\", \"Mapping conditions must use mappings.<conditionKey>.\"));\n return null;\n }\n index += 1;\n const keyToken = tokens[index];\n if (keyToken?.kind !== \"word\") {\n issues.push(issue(\"invalid_mapping_condition\", \"A valid mapping condition key is required after mappings.\"));\n return null;\n }\n index += 1;\n if (!StoreCategoryPromptConditionKeySchema.safeParse(keyToken.value).success) {\n issues.push(issue(\"invalid_mapping_condition\", `Invalid mapping condition key: ${keyToken.value}.`));\n return null;\n }\n if (!referenced.includes(keyToken.value)) referenced.push(keyToken.value);\n return { kind: \"condition\", key: keyToken.value };\n };\n\n const parseNot = (): ExpressionNode | null => {\n if (peekWord(\"not\")) {\n index += 1;\n const operand = parseNot();\n return operand ? { kind: \"not\", operand } : null;\n }\n return parsePrimary();\n };\n\n const parseAnd = (): ExpressionNode | null => {\n let left = parseNot();\n while (left && peekWord(\"and\")) {\n index += 1;\n const right = parseNot();\n if (!right) return null;\n left = { kind: \"and\", left, right };\n }\n return left;\n };\n\n const parseOr = (): ExpressionNode | null => {\n let left = parseAnd();\n while (left && peekWord(\"or\")) {\n index += 1;\n const right = parseAnd();\n if (!right) return null;\n left = { kind: \"or\", left, right };\n }\n return left;\n };\n\n const expression = parseOr();\n if (expression && index !== tokens.length) {\n issues.push(issue(\"invalid_template_expression\", \"Conditional expression contains unsupported syntax.\"));\n return null;\n }\n return expression;\n}\n\nfunction compileStoreCategoryPromptTemplate(source: string): CompileResult {\n const issues: StoreCategoryPromptTemplateIssue[] = [];\n const referencedConditionKeys: string[] = [];\n const nodes: TemplateNode[] = [];\n\n if (source.trim().length === 0) issues.push(issue(\"invalid_prompt_source\", \"Prompt template must not be blank.\"));\n if (sourceLength(source) > MAX_STORE_CATEGORY_PROMPT_SOURCE_CHARS) {\n issues.push(issue(\"invalid_prompt_source\", `Prompt template must not exceed ${MAX_STORE_CATEGORY_PROMPT_SOURCE_CHARS.toLocaleString()} characters.`));\n }\n\n const tokens = tokenizeTemplate(source, issues);\n type Frame = {\n node: Extract<TemplateNode, { kind: \"if\" }>;\n parentBody: TemplateNode[];\n currentBody: TemplateNode[];\n sawElse: boolean;\n };\n const stack: Frame[] = [];\n let currentBody = nodes;\n let controlCount = 0;\n\n for (const token of tokens) {\n if (token.kind === \"text\") {\n if (token.text) currentBody.push({ kind: \"text\", text: token.text });\n continue;\n }\n if (token.kind === \"unsupported\") {\n issues.push(issue(\n \"unsupported_template_construct\",\n token.marker === \"interpolation\"\n ? \"Variable interpolation is not supported in Store Category prompt templates.\"\n : \"Template comments are not supported in Store Category prompt templates.\",\n ));\n continue;\n }\n\n controlCount += 1;\n if (controlCount > MAX_CONTROL_TAGS) {\n issues.push(issue(\"template_too_complex\", `Prompt template must not contain more than ${MAX_CONTROL_TAGS} control tags.`));\n break;\n }\n\n const ifMatch = /^if\\s+([\\s\\S]+)$/.exec(token.source);\n if (ifMatch) {\n if (stack.length >= MAX_CONTROL_DEPTH) {\n issues.push(issue(\"template_too_complex\", `Conditional nesting must not exceed ${MAX_CONTROL_DEPTH} levels.`));\n continue;\n }\n const expression = parseExpression(ifMatch[1].trim(), issues, referencedConditionKeys);\n if (!expression) continue;\n const branchBody: TemplateNode[] = [];\n const node: Extract<TemplateNode, { kind: \"if\" }> = {\n kind: \"if\",\n branches: [{ expression, body: branchBody }],\n elseBody: null,\n };\n currentBody.push(node);\n const frame: Frame = { node, parentBody: currentBody, currentBody: branchBody, sawElse: false };\n stack.push(frame);\n currentBody = branchBody;\n continue;\n }\n\n const elifMatch = /^elif\\s+([\\s\\S]+)$/.exec(token.source);\n if (elifMatch) {\n const frame = stack.at(-1);\n if (!frame || frame.sawElse) {\n issues.push(issue(\"invalid_template_structure\", \"elif must appear inside an if block and before else.\"));\n continue;\n }\n const expression = parseExpression(elifMatch[1].trim(), issues, referencedConditionKeys);\n if (!expression) continue;\n const branchBody: TemplateNode[] = [];\n frame.node.branches.push({ expression, body: branchBody });\n frame.currentBody = branchBody;\n currentBody = branchBody;\n continue;\n }\n\n if (token.source === \"else\") {\n const frame = stack.at(-1);\n if (!frame || frame.sawElse) {\n issues.push(issue(\"invalid_template_structure\", \"else must appear once inside an if block.\"));\n continue;\n }\n const elseBody: TemplateNode[] = [];\n frame.node.elseBody = elseBody;\n frame.currentBody = elseBody;\n frame.sawElse = true;\n currentBody = elseBody;\n continue;\n }\n\n if (token.source === \"endif\") {\n const frame = stack.pop();\n if (!frame) {\n issues.push(issue(\"invalid_template_structure\", \"endif does not have a matching if block.\"));\n continue;\n }\n currentBody = frame.parentBody;\n continue;\n }\n\n issues.push(issue(\n \"unsupported_template_construct\",\n \"Only if, elif, else, and endif control tags are supported in Store Category prompt templates.\",\n ));\n }\n\n if (stack.length) issues.push(issue(\"invalid_template_structure\", \"Every if block must end with endif.\"));\n return { issues: boundedIssues(issues), nodes, referencedConditionKeys };\n}\n\nfunction validateAvailableConditionKeys(values: readonly string[], issues: StoreCategoryPromptTemplateIssue[]): Set<string> {\n if (values.length > MAX_STORE_CATEGORY_PROMPT_CONDITIONS) {\n issues.push(issue(\"template_too_complex\", `At most ${MAX_STORE_CATEGORY_PROMPT_CONDITIONS} mapping conditions are supported.`));\n }\n const keys = new Set<string>();\n for (const value of values.slice(0, MAX_STORE_CATEGORY_PROMPT_CONDITIONS + 1)) {\n if (!StoreCategoryPromptConditionKeySchema.safeParse(value).success) {\n issues.push(issue(\"invalid_mapping_condition\", `Invalid mapping condition key: ${value}.`));\n continue;\n }\n if (keys.has(value)) {\n issues.push(issue(\"invalid_mapping_condition\", `Duplicate mapping condition key: ${value}.`));\n continue;\n }\n keys.add(value);\n }\n return keys;\n}\n\nexport function validateStoreCategoryPromptTemplate(input: {\n source: string;\n availableConditionKeys: readonly string[];\n}): StoreCategoryPromptTemplateValidation {\n const compiled = compileStoreCategoryPromptTemplate(input.source);\n const issues = [...compiled.issues];\n const available = validateAvailableConditionKeys(input.availableConditionKeys, issues);\n for (const key of compiled.referencedConditionKeys) {\n if (!available.has(key)) issues.push(issue(\"unknown_mapping_condition\", `Prompt template references unavailable mapping condition: mappings.${key}.`));\n }\n const bounded = boundedIssues(issues);\n return { valid: bounded.length === 0, issues: bounded, referencedConditionKeys: compiled.referencedConditionKeys };\n}\n\n\nexport function createStoreCategoryPromptConditionBlock(conditionKey: string): string {\n const parsed = StoreCategoryPromptConditionKeySchema.safeParse(conditionKey);\n if (!parsed.success) throw new TypeError(`Invalid mapping condition key: ${conditionKey}.`);\n return `{% if mappings.${conditionKey} %}\\n\\n{% endif %}`;\n}\n\nexport function createStoreCategoryPromptContext(input: {\n availableConditionKeys: readonly string[];\n selectedConditionKeys: readonly string[];\n}): StoreCategoryPromptContext {\n const issues: StoreCategoryPromptTemplateIssue[] = [];\n const available = validateAvailableConditionKeys(input.availableConditionKeys, issues);\n const selected = validateAvailableConditionKeys(input.selectedConditionKeys, issues);\n for (const key of selected) {\n if (!available.has(key)) issues.push(issue(\"unknown_mapping_condition\", `Selected mapping condition is unavailable: ${key}.`));\n }\n if (issues.length) throw new TypeError(issues[0].message);\n const mappings = Object.create(null) as Record<string, boolean>;\n for (const key of available) mappings[key] = selected.has(key);\n return { mappings };\n}\n\nfunction evaluateExpression(expression: ExpressionNode, mappings: Record<string, boolean>): boolean {\n switch (expression.kind) {\n case \"condition\":\n return mappings[expression.key] === true;\n case \"not\":\n return !evaluateExpression(expression.operand, mappings);\n case \"and\":\n return evaluateExpression(expression.left, mappings) && evaluateExpression(expression.right, mappings);\n case \"or\":\n return evaluateExpression(expression.left, mappings) || evaluateExpression(expression.right, mappings);\n }\n}\n\nfunction renderNodes(nodes: TemplateNode[], mappings: Record<string, boolean>, append: (text: string) => boolean): boolean {\n for (const node of nodes) {\n if (node.kind === \"text\") {\n if (!append(node.text)) return false;\n continue;\n }\n let renderedBranch = false;\n for (const branch of node.branches) {\n if (evaluateExpression(branch.expression, mappings)) {\n if (!renderNodes(branch.body, mappings, append)) return false;\n renderedBranch = true;\n break;\n }\n }\n if (!renderedBranch && node.elseBody && !renderNodes(node.elseBody, mappings, append)) return false;\n }\n return true;\n}\n\nexport function renderStoreCategoryPromptTemplate(input: {\n source: string;\n context: StoreCategoryPromptContext;\n}): StoreCategoryPromptRenderResult {\n const contextResult = StoreCategoryPromptContextSchema.safeParse(input.context);\n if (!contextResult.success) {\n return { ok: false, issues: [issue(\"invalid_mapping_condition\", \"Store Category prompt context contains invalid mapping conditions.\")] };\n }\n const availableConditionKeys = Object.keys(contextResult.data.mappings);\n const validation = validateStoreCategoryPromptTemplate({ source: input.source, availableConditionKeys });\n if (!validation.valid) return { ok: false, issues: validation.issues };\n\n const compiled = compileStoreCategoryPromptTemplate(input.source);\n let output = \"\";\n let outputChars = 0;\n const append = (text: string) => {\n outputChars += sourceLength(text);\n if (outputChars > MAX_STORE_CATEGORY_PROMPT_RENDERED_CHARS) return false;\n output += text;\n return true;\n };\n const rendered = renderNodes(compiled.nodes, contextResult.data.mappings, append);\n if (!rendered) {\n return {\n ok: false,\n issues: [issue(\"rendered_prompt_too_large\", `Rendered prompt must not exceed ${MAX_STORE_CATEGORY_PROMPT_RENDERED_CHARS.toLocaleString()} characters.`)],\n };\n }\n return { ok: true, promptText: output, referencedConditionKeys: validation.referencedConditionKeys };\n}\n","import { z } from \"zod\";\n\nexport const CommerceOutreachToolContextSchema = z.strictObject({\n purpose: z.literal(\"INITIAL_RECOVERY_OUTREACH\"),\n});\n\nexport type CommerceOutreachToolContext =\n z.infer<typeof CommerceOutreachToolContextSchema>;\n","/** Synthetic examples; no provider identity, schema artifact or publication claim. */\nimport type {\n CommerceManifest,\n CommerceConversationGrant,\n CommerceTurnIdentity,\n} from \"./schemas\";\nimport {\n EMPTY_RESPONSE_CONTRACT,\n type CommerceFinalResponse,\n} from \"./response\";\nimport type { Digest } from \"./canonical-json\";\nimport { responseContractCanonicalJson } from \"./canonical-json\";\nimport type { PublishedToolDescriptor, CommerceToolDefinition } from \"./definitions\";\nexport const exampleTool: PublishedToolDescriptor = {\n toolId: \"tool-fixture\",\n toolRevisionId: \"revision-fixture\",\n name: \"never_seeded_catalogue_facts\",\n definitionVersion: \"1.0.0\",\n description: \"Read synthetic catalogue facts.\",\n inputSchema: {\n type: \"object\",\n properties: { handle: { type: \"string\", minLength: 1, maxLength: 255 } },\n required: [\"handle\"],\n additionalProperties: false,\n },\n};\nexport const exampleDefinition: CommerceToolDefinition = {\n name: exampleTool.name,\n definitionVersion: \"1.0.0\",\n description: exampleTool.description,\n inputSchema: exampleTool.inputSchema,\n execution: {\n kind: \"SHOPIFY_STOREFRONT_QUERY\",\n executorVersion: \"1.0.0\",\n apiVersion: \"2026-07\",\n schemaHash: \"a\".repeat(64),\n document:\n \"query ProductDetails($handle: String!) { product(handle: $handle) { title description } }\",\n operationName: \"ProductDetails\",\n variables: { handle: { input: \"handle\" } },\n resultPath: \"product\",\n },\n responseTemplate: {\n kind: \"text\",\n text: \"{{result.values.title}}: {{result.values.description}}\",\n unavailable: \"Product details could not be verified.\",\n },\n};\nexport const exampleTurn: CommerceTurnIdentity = {\n contractVersion: \"commerce.v1\",\n shopId: \"shop-fixture\",\n checkoutRecoveryId: \"recovery-fixture\",\n conversationId: \"conversation-fixture\",\n inboundVersion: 1,\n};\nexport function exampleManifest(\n digest: Digest,\n withTool = false,\n): CommerceManifest {\n const capabilities = withTool\n ? [{\n capabilityId: \"capability-fixture\",\n key: \"feature_product_read\",\n featureId: \"feature-fixture\",\n position: 0,\n toolDescriptor: structuredClone(exampleTool),\n }]\n : [];\n return {\n contractVersion: \"commerce.v1\",\n releaseId: \"release-fixture\",\n runnerCompatibility: \"^1.0.0\",\n capabilities,\n featureBehaviours: withTool\n ? [{ featureId: \"feature-fixture\", behaviourPrompt: \"Synthetic Feature behavior.\" }]\n : [],\n selectedCapabilityKeys: capabilities.map((capability) => capability.key),\n builtInTools: [],\n grantedTools: withTool\n ? [\n {\n toolId: exampleTool.toolId,\n toolRevisionId: exampleTool.toolRevisionId,\n toolName: exampleTool.name,\n definitionVersion: \"1.0.0\",\n capabilityKeys: [\"feature_product_read\"],\n },\n ]\n : [],\n responseContract: structuredClone(EMPTY_RESPONSE_CONTRACT),\n responseContractHash: digest(\n responseContractCanonicalJson(EMPTY_RESPONSE_CONTRACT),\n ),\n };\n}\nexport function exampleGrant(\n manifest: CommerceManifest,\n): CommerceConversationGrant {\n return {\n id: \"grant-fixture\",\n shopId: exampleTurn.shopId,\n conversationId: exampleTurn.conversationId,\n initialInboundVersion: 1,\n releaseId: manifest.releaseId,\n selectedCapabilityKeys: [...manifest.selectedCapabilityKeys],\n grantedTools: structuredClone(manifest.grantedTools),\n runnerVersion: \"1.0.0\",\n createdAt: \"2026-09-20T00:00:00.000Z\",\n expiresAt: null,\n };\n}\nexport const exampleFinal: CommerceFinalResponse = {\n answerKind: \"REFER_TO_STORE\",\n replyText:\n \"I cannot verify that information. Please contact the store directly.\",\n referralReason: \"INSUFFICIENT_TOOLS\",\n detectedLanguageTag: null,\n detectedLanguageConfidence: null,\n evidenceIds: [],\n details: {},\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAQO,IAAM,wCAAwC,OAAO,OAAO;AAAA,EACjE,OAAO,OAAO;AAAA,IACZ,UAAU;AAAA,IACV,aAAa;AAAA,IACb,WAAW;AAAA,IACX,kBAAkB;AAAA,IAClB,aAAa;AAAA,IACb,gBAAgB,mBAAmB;AAAA,IACnC,iBAAiB,oBAAoB;AAAA,EAC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;AAAA,IACL,iBAAiB;AAAA,IACjB,WAAW;AAAA,IACX,qBAAqB;AAAA,IACrB;AAAA,IACA,mBAAmB,WACf,CAAC,EAAE,WAAW,mBAAmB,iBAAiB,8BAA8B,CAAC,IACjF,CAAC;AAAA,IACL,wBAAwB,aAAa,IAAI,CAAC,eAAe,WAAW,GAAG;AAAA,IACvE,cAAc,CAAC;AAAA,IACf,cAAc,WACV;AAAA,MACE;AAAA,QACE,QAAQ,YAAY;AAAA,QACpB,gBAAgB,YAAY;AAAA,QAC5B,UAAU,YAAY;AAAA,QACtB,mBAAmB;AAAA,QACnB,gBAAgB,CAAC,sBAAsB;AAAA,MACzC;AAAA,IACF,IACA,CAAC;AAAA,IACL,kBAAkB,gBAAgB,uBAAuB;AAAA,IACzD,sBAAsB;AAAA,MACpB,8BAA8B,uBAAuB;AAAA,IACvD;AAAA,EACF;AACF;AACO,SAAS,aACd,UAC2B;AAC3B,SAAO;AAAA,IACL,IAAI;AAAA,IACJ,QAAQ,YAAY;AAAA,IACpB,gBAAgB,YAAY;AAAA,IAC5B,uBAAuB;AAAA,IACvB,WAAW,SAAS;AAAA,IACpB,wBAAwB,CAAC,GAAG,SAAS,sBAAsB;AAAA,IAC3D,cAAc,gBAAgB,SAAS,YAAY;AAAA,IACnD,eAAe;AAAA,IACf,WAAW;AAAA,IACX,WAAW;AAAA,EACb;AACF;AACO,IAAM,eAAsC;AAAA,EACjD,YAAY;AAAA,EACZ,WACE;AAAA,EACF,gBAAgB;AAAA,EAChB,qBAAqB;AAAA,EACrB,4BAA4B;AAAA,EAC5B,aAAa,CAAC;AAAA,EACd,SAAS,CAAC;AACZ;","names":["z"]}
@@ -1,7 +1,7 @@
1
- import { R as RunnerTransportCode, C as CommerceModelInvoker, M as ModelStep } from '../../types-vIMrj5J4.js';
1
+ import { R as RunnerTransportCode, C as CommerceModelInvoker, M as ModelStep } from '../../types-BXeYmpeg.js';
2
2
  import { CommerceModelProvider, CommerceProviderModelId } from './index.js';
3
- import '../../product-context-Bh74WGOo.js';
4
- import '../../response-DFDEw4K0.js';
3
+ import '../../product-context-qfk6k9uk.js';
4
+ import '../../response-DD6HXT8s.js';
5
5
  import 'zod';
6
6
  import '../../types-B32wDMLO.js';
7
7
 
@@ -4,7 +4,7 @@ import {
4
4
  } from "../../chunk-WONND3OK.js";
5
5
  import {
6
6
  CommerceToolResultSchema
7
- } from "../../chunk-WF2BDUPZ.js";
7
+ } from "../../chunk-SW2AFMT7.js";
8
8
  import "../../chunk-GCCT2BDE.js";
9
9
  import "../../chunk-4KSODB2R.js";
10
10
  import {
@@ -1,8 +1,8 @@
1
1
  import { z } from 'zod';
2
- import { g as CommerceToolInputs } from '../../response-DFDEw4K0.js';
3
- import { C as CommerceModelInvoker } from '../../types-vIMrj5J4.js';
2
+ import { g as CommerceToolInputs } from '../../response-DD6HXT8s.js';
3
+ import { C as CommerceModelInvoker } from '../../types-BXeYmpeg.js';
4
4
  import { S as StructuredLogger } from '../../types-B32wDMLO.js';
5
- import '../../product-context-Bh74WGOo.js';
5
+ import '../../product-context-qfk6k9uk.js';
6
6
 
7
7
  declare const StageSchema: z.ZodEnum<{
8
8
  COMPLETE: "COMPLETE";
@@ -12,7 +12,7 @@ import {
12
12
  CommerceProductSchema,
13
13
  CommerceToolInputs,
14
14
  CommerceToolOutputs
15
- } from "../../chunk-WF2BDUPZ.js";
15
+ } from "../../chunk-SW2AFMT7.js";
16
16
  import {
17
17
  CurrencySchema,
18
18
  DateSchema,
@@ -1,7 +1,7 @@
1
1
  import * as zod from 'zod';
2
2
  import { z } from 'zod';
3
3
  import { ModaSupportedLanguageTag, IcuMessageCatalogue, InternationalizationRuntime } from '../../internationalization.js';
4
- import { Y as CommerceShippingInformation, d as CommerceFinalResponse } from '../../response-DFDEw4K0.js';
4
+ import { Y as CommerceShippingInformation, d as CommerceFinalResponse } from '../../response-DD6HXT8s.js';
5
5
  import 'intl-messageformat';
6
6
 
7
7
  declare const CommerceVerifiedPresentationSchema: z.ZodObject<{
@@ -5,7 +5,7 @@ import {
5
5
  CommerceProductOptionsSchema,
6
6
  CommerceProductSchema,
7
7
  CommerceProductSelectedOptionsSchema
8
- } from "../../chunk-WF2BDUPZ.js";
8
+ } from "../../chunk-SW2AFMT7.js";
9
9
  import "../../chunk-GCCT2BDE.js";
10
10
  import {
11
11
  MODA_SUPPORTED_LANGUAGE_TAGS,
@@ -1,7 +1,7 @@
1
- import { a as RunnerDiagnostic, b as RunCommerceTurnInput, c as RunCommerceTurnResult } from '../../types-vIMrj5J4.js';
2
- export { C as CommerceModelInvoker, d as ModelCall, e as ModelRequest, M as ModelStep, f as RunnerDiagnosticReason, g as RunnerDiagnosticStage, h as RunnerErrorCode, i as RunnerTool } from '../../types-vIMrj5J4.js';
3
- import '../../product-context-Bh74WGOo.js';
4
- import '../../response-DFDEw4K0.js';
1
+ import { a as RunnerDiagnostic, b as RunCommerceTurnInput, c as RunCommerceTurnResult } from '../../types-BXeYmpeg.js';
2
+ export { C as CommerceModelInvoker, d as ModelCall, e as ModelRequest, M as ModelStep, f as RunnerDiagnosticReason, g as RunnerDiagnosticStage, h as RunnerErrorCode, i as RunnerTool } from '../../types-BXeYmpeg.js';
3
+ import '../../product-context-qfk6k9uk.js';
4
+ import '../../response-DD6HXT8s.js';
5
5
  import 'zod';
6
6
  import '../../types-B32wDMLO.js';
7
7
 
@@ -6,7 +6,7 @@ import {
6
6
  import {
7
7
  manifestMatchesGrant,
8
8
  mergeConversationProductContext
9
- } from "../../chunk-WK7QSBHJ.js";
9
+ } from "../../chunk-2XZVIWQZ.js";
10
10
  import {
11
11
  CommerceModelInvocationFailure,
12
12
  RunnerFailure,
@@ -28,7 +28,7 @@ import {
28
28
  finalResponseToolSchema,
29
29
  isBuiltInTool,
30
30
  verifyResponseContract
31
- } from "../../chunk-WF2BDUPZ.js";
31
+ } from "../../chunk-SW2AFMT7.js";
32
32
  import {
33
33
  LanguageSchema
34
34
  } from "../../chunk-GCCT2BDE.js";
@@ -1,4 +1,4 @@
1
- import { S as SubsetSchema, e as CommercePurposeOutputSchema, f as CommerceProductSchema } from './response-DFDEw4K0.js';
1
+ import { S as SubsetSchema, e as CommercePurposeOutputSchema, f as CommerceProductSchema } from './response-DD6HXT8s.js';
2
2
  import { z } from 'zod';
3
3
 
4
4
  declare const ToolNameSchema: z.ZodString;
@@ -909,6 +909,7 @@ declare const CommerceResponseDispositionSchema: z.ZodEnum<{
909
909
  OUT_OF_SCOPE_REDIRECT: "OUT_OF_SCOPE_REDIRECT";
910
910
  SHIPPING_INFORMATION_UNVERIFIED: "SHIPPING_INFORMATION_UNVERIFIED";
911
911
  PRODUCT_OPTIONS: "PRODUCT_OPTIONS";
912
+ PRODUCT_DETAILS: "PRODUCT_DETAILS";
912
913
  }>;
913
914
  type CommerceResponseDisposition = z.infer<typeof CommerceResponseDispositionSchema>;
914
915
  declare const CommerceAnswerPresentationSelectionSchema: z.ZodObject<{
@@ -916,11 +917,16 @@ declare const CommerceAnswerPresentationSelectionSchema: z.ZodObject<{
916
917
  productId: z.ZodString;
917
918
  variantId: z.ZodNullable<z.ZodString>;
918
919
  }, z.core.$strict>>>;
920
+ productDetailSelections: z.ZodOptional<z.ZodArray<z.ZodObject<{
921
+ productId: z.ZodString;
922
+ variantId: z.ZodNullable<z.ZodString>;
923
+ }, z.core.$strict>>>;
919
924
  responseDisposition: z.ZodOptional<z.ZodEnum<{
920
925
  STANDARD: "STANDARD";
921
926
  OUT_OF_SCOPE_REDIRECT: "OUT_OF_SCOPE_REDIRECT";
922
927
  SHIPPING_INFORMATION_UNVERIFIED: "SHIPPING_INFORMATION_UNVERIFIED";
923
928
  PRODUCT_OPTIONS: "PRODUCT_OPTIONS";
929
+ PRODUCT_DETAILS: "PRODUCT_DETAILS";
924
930
  }>>;
925
931
  shippingInformationSelection: z.ZodOptional<z.ZodObject<{
926
932
  productId: z.ZodNullable<z.ZodString>;
@@ -1761,4 +1767,4 @@ declare function verifyResponseContract(definition: unknown, hash: string, diges
1761
1767
  /** JSON Schema branches retain the immutable envelope; only ANSWER details vary. */
1762
1768
  declare function finalResponseToolSchema(definition: CommerceResponseContract): Json;
1763
1769
 
1764
- export { CommerceShippingInformationSchema as $, CommerceExecuteAssertionSchema as A, CommerceFinalResponseSchema as B, type CommerceTurnIdentity as C, type Digest as D, CommerceManifestSchema as E, CommerceOfferSchema as F, type CommerceOptionalLookupUnavailable as G, CommerceOptionalLookupUnavailableSchema as H, type CommerceProduct as I, CommerceProductOptionsSchema as J, type CommerceProductRecommendationSelection as K, CommerceProductRecommendationSelectionSchema as L, type CommerceProductSaleEvidence as M, CommerceProductSaleEvidenceSchema as N, CommerceProductSelectedOptionsSchema as O, CommerceProposalSchema as P, CommercePurposeOutputSchemaSchema as Q, CommerceReleaseIdentitySchema as R, type SubsetSchema as S, CommerceResolveAssertionSchema as T, type CommerceResponseContract as U, CommerceResponseContractSchema as V, type CommerceResponseDisposition as W, CommerceResponseDispositionSchema as X, type CommerceShippingInformation as Y, type CommerceShippingInformationInput as Z, CommerceShippingInformationInputSchema as _, type CommerceConversationGrant as a, CommerceToolOutputs as a0, CommerceToolResultSchema as a1, CommerceTurnIdentitySchema as a2, DetailsSchemaSchema as a3, EMPTY_RESPONSE_CONTRACT as a4, InputSchemaSchema as a5, type Json as a6, MONEY_PATTERN as a7, ReferralReasonSchema as a8, canonicalJson as a9, commerceToolResultSchema as aa, compileCommercePurposeOutputSchema as ab, compileSubset as ac, finalResponseSchema as ad, finalResponseToolSchema as ae, jsonBytes as af, matchesSubset as ag, normalizeCommerceProductOptions as ah, normalizeCommerceProductSelectedOptions as ai, productBelongsToDomain as aj, responseContractCanonicalJson as ak, safeName as al, safePath as am, validateCommercePurposeOutputSchema as an, validateSubset as ao, verifyResponseContract as ap, type CommerceManifest as b, type CommerceToolResult as c, type CommerceFinalResponse as d, type CommercePurposeOutputSchema as e, CommerceProductSchema as f, CommerceToolInputs as g, CommerceAlternativeSchema as h, type CommerceAnswerPresentationSelection as i, CommerceAnswerPresentationSelectionSchema as j, CommerceAssertionSchema as k, CommerceBasketSchema as l, type CommerceCategoryCandidate as m, CommerceCategoryCandidateSchema as n, type CommerceCategoryResolution as o, CommerceCategoryResolutionSchema as p, CommerceConversationGrantSchema as q, type CommerceDiscountCombinationFacts as r, CommerceDiscountCombinationFactsSchema as s, type CommerceDiscountConditionFacts as t, CommerceDiscountConditionFactsSchema as u, type CommerceDiscountDetails as v, CommerceDiscountDetailsSchema as w, CommerceErrorCodeSchema as x, type CommerceEvidence as y, CommerceEvidenceSchema as z };
1770
+ export { CommerceShippingInformationSchema as $, CommerceExecuteAssertionSchema as A, CommerceFinalResponseSchema as B, type CommerceTurnIdentity as C, type Digest as D, CommerceManifestSchema as E, CommerceOfferSchema as F, type CommerceOptionalLookupUnavailable as G, CommerceOptionalLookupUnavailableSchema as H, type CommerceProduct as I, CommerceProductOptionsSchema as J, type CommerceProductRecommendationSelection as K, CommerceProductRecommendationSelectionSchema as L, type CommerceProductSaleEvidence as M, CommerceProductSaleEvidenceSchema as N, CommerceProductSelectedOptionsSchema as O, CommerceProposalSchema as P, CommercePurposeOutputSchemaSchema as Q, CommerceReleaseIdentitySchema as R, type SubsetSchema as S, CommerceResolveAssertionSchema as T, type CommerceResponseContract as U, CommerceResponseContractSchema as V, type CommerceResponseDisposition as W, CommerceResponseDispositionSchema as X, type CommerceShippingInformation as Y, type CommerceShippingInformationInput as Z, CommerceShippingInformationInputSchema as _, type CommerceConversationGrant as a, CommerceToolOutputs as a0, CommerceToolResultSchema as a1, CommerceTurnIdentitySchema as a2, DetailsSchemaSchema as a3, EMPTY_RESPONSE_CONTRACT as a4, InputSchemaSchema as a5, type Json as a6, MONEY_PATTERN as a7, ReferralReasonSchema as a8, canonicalJson as a9, commerceToolResultSchema as aa, compileCommercePurposeOutputSchema as ab, compileSubset as ac, finalResponseSchema as ad, finalResponseToolSchema as ae, jsonBytes as af, matchesSubset as ag, normalizeCommerceProductOptions as ah, normalizeCommerceProductSelectedOptions as ai, productBelongsToDomain as aj, responseContractCanonicalJson as ak, safeName as al, safePath as am, validateCommercePurposeOutputSchema as an, validateSubset as ao, verifyResponseContract as ap, type CommerceManifest as b, type CommerceToolResult as c, type CommerceFinalResponse as d, type CommercePurposeOutputSchema as e, CommerceProductSchema as f, CommerceToolInputs as g, type CommerceAnswerPresentationSelection as h, CommerceAlternativeSchema as i, CommerceAnswerPresentationSelectionSchema as j, CommerceAssertionSchema as k, CommerceBasketSchema as l, type CommerceCategoryCandidate as m, CommerceCategoryCandidateSchema as n, type CommerceCategoryResolution as o, CommerceCategoryResolutionSchema as p, CommerceConversationGrantSchema as q, type CommerceDiscountCombinationFacts as r, CommerceDiscountCombinationFactsSchema as s, type CommerceDiscountConditionFacts as t, CommerceDiscountConditionFactsSchema as u, type CommerceDiscountDetails as v, CommerceDiscountDetailsSchema as w, CommerceErrorCodeSchema as x, type CommerceEvidence as y, CommerceEvidenceSchema as z };
@@ -1,5 +1,5 @@
1
- import { C as CommerceExecutionPurpose, a as CommerceConversationProductContext, T as ToolDescriptor, G as GrantedTool } from './product-context-Bh74WGOo.js';
2
- import { C as CommerceTurnIdentity, a as CommerceConversationGrant, b as CommerceManifest, c as CommerceToolResult, D as Digest, d as CommerceFinalResponse } from './response-DFDEw4K0.js';
1
+ import { C as CommerceExecutionPurpose, a as CommerceConversationProductContext, T as ToolDescriptor, G as GrantedTool } from './product-context-qfk6k9uk.js';
2
+ import { C as CommerceTurnIdentity, a as CommerceConversationGrant, b as CommerceManifest, c as CommerceToolResult, D as Digest, d as CommerceFinalResponse } from './response-DD6HXT8s.js';
3
3
  import { S as StructuredLogger } from './types-B32wDMLO.js';
4
4
 
5
5
  /** Finite, non-customer-facing failure taxonomy for Commerce hosts and logs. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@modainteract/moda-interact-shared",
3
- "version": "5.7.0",
3
+ "version": "5.8.0",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/commerce/selection.ts","../src/commerce/product-context.ts"],"sourcesContent":["import { IdSchema } from \"./primitives\";\nimport {\n type CommerceManifest,\n CommerceManifestSchema,\n type CommerceConversationGrant,\n CommerceConversationGrantSchema,\n} from \"./schemas\";\nimport { GrantedToolsSchema, PublishedToolDescriptorSchema, type GrantedTool, type PublishedGrantedTool, type PublishedToolDescriptor, type CommerceBuiltInToolDescriptor, isBuiltInTool } from \"./definitions\";\nimport { isTrustedCommerceBuiltInDescriptor, isTrustedCommerceBuiltInGrant } from \"./built-in-tools\";\nimport { canonicalJson } from \"./canonical-json\";\nexport type FeatureFacts = {\n id: string;\n active: boolean;\n planMappingEnabled: boolean;\n mode: \"ALWAYS_ENABLED\" | \"MERCHANT_OPT_IN\";\n preferenceEnabled: boolean | null;\n};\nexport function selectCapabilities(\n candidates: Array<{\n key: string;\n featureId: string;\n enabled: boolean;\n position: number;\n }>,\n facts: {\n features: FeatureFacts[];\n },\n) {\n for (const candidate of candidates) {\n IdSchema.parse(candidate.key);\n IdSchema.parse(candidate.featureId);\n if (!Number.isSafeInteger(candidate.position) || candidate.position < 0)\n throw new TypeError(\"Invalid capability position\");\n }\n const selected = candidates\n .filter((c) => {\n if (!c.enabled) return false;\n const f = facts.features.find((f) => f.id === c.featureId);\n return (\n !!f &&\n f.active &&\n f.planMappingEnabled &&\n (f.mode === \"ALWAYS_ENABLED\" || f.preferenceEnabled === true)\n );\n })\n .sort((a, b) => a.position - b.position);\n if (\n new Set(selected.map((c) => c.key)).size !== selected.length ||\n new Set(selected.map((c) => c.position)).size !== selected.length\n )\n throw new TypeError(\"Duplicate release membership\");\n return selected.map((c) => c.key);\n}\nexport function deduplicateTools(\n capabilities: Array<{ key: string; toolDescriptor: PublishedToolDescriptor }>,\n builtInTools: readonly CommerceBuiltInToolDescriptor[] = [],\n): GrantedTool[] {\n const byId = new Map<string, { tool: PublishedGrantedTool; descriptor: string }>();\n const names = new Map<string, string>();\n for (const cap of capabilities) {\n const d = PublishedToolDescriptorSchema.parse(cap.toolDescriptor);\n const previous = byId.get(d.toolId);\n const descriptor = canonicalJson(d);\n if (\n (previous && previous.descriptor !== descriptor) ||\n (names.has(d.name) && names.get(d.name) !== d.toolId)\n )\n throw new TypeError(\"Conflicting tool association\");\n names.set(d.name, d.toolId);\n if (previous)\n previous.tool.capabilityKeys = [\n ...new Set([...previous.tool.capabilityKeys, cap.key]),\n ].sort();\n else\n byId.set(d.toolId, {\n descriptor,\n tool: {\n toolId: d.toolId,\n toolRevisionId: d.toolRevisionId,\n toolName: d.name,\n definitionVersion: d.definitionVersion,\n capabilityKeys: [cap.key],\n },\n });\n }\n if (builtInTools.some(tool => !isTrustedCommerceBuiltInDescriptor(tool)))\n throw new TypeError(\"Untrusted built-in descriptor\");\n return GrantedToolsSchema.parse([\n ...[...byId.values()].map(value => value.tool),\n ...builtInTools.map(tool => ({\n kind: \"BUILT_IN\" as const, toolName: tool.name,\n definitionVersion: tool.definitionVersion,\n })),\n ]).sort((a, b) => a.toolName.localeCompare(b.toolName, \"en\"));\n}\nexport function manifestMatchesGrant(\n manifest: CommerceManifest,\n grant: CommerceConversationGrant,\n) {\n if (!CommerceManifestSchema.safeParse(manifest).success || !CommerceConversationGrantSchema.safeParse(grant).success) return false;\n return (\n manifest.releaseId === grant.releaseId &&\n canonicalJson(manifest.purposeProfile ?? null) === canonicalJson(grant.purposeProfile ?? null) &&\n canonicalJson(manifest.selectedCapabilityKeys) ===\n canonicalJson(grant.selectedCapabilityKeys) &&\n canonicalJson(\n [...manifest.grantedTools].sort((a, b) =>\n a.toolName.localeCompare(b.toolName),\n ),\n ) ===\n canonicalJson(\n [...grant.grantedTools].sort((a, b) =>\n a.toolName.localeCompare(b.toolName),\n ),\n )\n );\n}\nexport const parseCommerceManifest = (raw: unknown) =>\n CommerceManifestSchema.parse(raw);\nexport function currentlyGrantedTools(\n grant: CommerceConversationGrant,\n eligibleCapabilityKeys: ReadonlySet<string>,\n enabledToolIds: ReadonlySet<string>,\n allowedBuiltInTools: readonly CommerceBuiltInToolDescriptor[] = [],\n) {\n return grant.grantedTools.filter(\n (t) =>\n isBuiltInTool(t)\n ? isTrustedCommerceBuiltInGrant(t) && allowedBuiltInTools.some(descriptor =>\n isTrustedCommerceBuiltInDescriptor(descriptor) && descriptor.name === t.toolName &&\n descriptor.definitionVersion === t.definitionVersion)\n : enabledToolIds.has(t.toolId) && t.capabilityKeys.some((k) => eligibleCapabilityKeys.has(k)),\n );\n}\n","import { z } from \"zod\";\nimport { CommerceProductSchema } from \"./schemas.js\";\nconst id = z.string().min(1).max(128);\nconst date = z.iso.datetime({offset:false});\nexport const CommerceConversationProductContextSchema = z.strictObject({schemaVersion:z.literal(1),shopId:id,conversationId:id,platform:z.enum([\"SHOPIFY\",\"WOOCOMMERCE\"]),references:z.array(z.strictObject({productId:id,variantId:id.nullable(),title:z.string().min(1).max(512),observedAt:date})).max(20),updatedAt:date}).superRefine((v,c)=>{\n const valid=(value:string,kind:string)=>v.platform === \"SHOPIFY\" ? new RegExp(`^gid://shopify/${kind}/[1-9][0-9]*$`).test(value) : /^[1-9][0-9]*$/.test(value) && Number.isSafeInteger(Number(value));\n if(v.references.some(r=>!valid(r.productId,\"Product\")||(r.variantId!==null&&!valid(r.variantId,\"ProductVariant\")))||new TextEncoder().encode(JSON.stringify(v)).length>32768)c.addIssue({code:\"custom\",message:\"Invalid product context\"});\n});\nexport type CommerceConversationProductContext = z.infer<typeof CommerceConversationProductContextSchema>;\nexport type CommerceProductObservation = {toolName:string;products:z.infer<typeof CommerceProductSchema>[];observedAt:string};\nexport type CommerceProductContextIdentity = {shopId:string;conversationId:string;platform:\"SHOPIFY\"|\"WOOCOMMERCE\";now:number};\nexport function mergeConversationProductContext(previous:CommerceConversationProductContext|null,observations:readonly CommerceProductObservation[],identity:CommerceProductContextIdentity):CommerceConversationProductContext {\n id.parse(identity.shopId);id.parse(identity.conversationId);z.enum([\"SHOPIFY\",\"WOOCOMMERCE\"]).parse(identity.platform);if(!Number.isFinite(identity.now))throw new Error(\"PRODUCT_CONTEXT_TIME_INVALID\");\n let admitted=false;\n if(previous){previous=CommerceConversationProductContextSchema.parse(previous);if(previous.shopId!==identity.shopId||previous.conversationId!==identity.conversationId||previous.platform!==identity.platform)throw new Error(\"PRODUCT_CONTEXT_IDENTITY_MISMATCH\");}\n const fresh=(time:string)=>Number.isFinite(Date.parse(time))&&Date.parse(time)<=identity.now&&Date.parse(time)>=identity.now-86400000;\n const entries=new Map<string,CommerceConversationProductContext[\"references\"][number]>();\n const add=(r:CommerceConversationProductContext[\"references\"][number])=>{if(!fresh(r.observedAt))return;const key=JSON.stringify([r.productId,r.variantId]);const old=entries.get(key);if(!old||Date.parse(r.observedAt)>=Date.parse(old.observedAt))entries.set(key,r);};\n if(previous&&fresh(previous.updatedAt))previous.references.forEach(add);\n for(const o of observations){if(![\"commerce_search_products\",\"commerce_get_product\"].includes(o.toolName)||!fresh(o.observedAt))continue;for(const raw of o.products){const p=CommerceProductSchema.parse(raw);admitted=true;add({productId:p.productId,variantId:p.variantId,title:p.title,observedAt:o.observedAt});}}\n const references=[...entries.values()].sort((a,b)=>Date.parse(b.observedAt)-Date.parse(a.observedAt)||(a.productId<b.productId?-1:a.productId>b.productId?1:0)||((a.variantId??\"\")<(b.variantId??\"\")?-1:(a.variantId??\"\")>(b.variantId??\"\")?1:0)).slice(0,20);\n const result={schemaVersion:1 as const,shopId:identity.shopId,conversationId:identity.conversationId,platform:identity.platform,references,updatedAt:admitted?new Date(identity.now).toISOString():previous&&fresh(previous.updatedAt)?previous.updatedAt:new Date(identity.now).toISOString()};\n while(references.length&&new TextEncoder().encode(JSON.stringify(result)).length>32768)references.pop();\n return CommerceConversationProductContextSchema.parse(result);\n}\nexport function resolveConversationProductReference(context:CommerceConversationProductContext,reference:{productId?:string;variantId?:string|null;title?:string}):{kind:\"MATCH\";productId:string;variantId:string|null}|{kind:\"AMBIGUOUS\"}|{kind:\"MISSING\"}{\n const parsed=CommerceConversationProductContextSchema.parse(context);\n const matches=parsed.references.filter(r=>(reference.productId!==undefined?r.productId===reference.productId:reference.title!==undefined&&r.title.trim().toLowerCase()===reference.title.trim().toLowerCase())&&(reference.variantId===undefined||r.variantId===reference.variantId));\n const unique=[...new Map(matches.map(r=>[JSON.stringify([r.productId,r.variantId]),r])).values()];return unique.length===1?{kind:\"MATCH\",productId:unique[0]!.productId,variantId:unique[0]!.variantId}:unique.length>1?{kind:\"AMBIGUOUS\"}:{kind:\"MISSING\"};\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAiBO,SAAS,mBACd,YAMA,OAGA;AACA,aAAW,aAAa,YAAY;AAClC,aAAS,MAAM,UAAU,GAAG;AAC5B,aAAS,MAAM,UAAU,SAAS;AAClC,QAAI,CAAC,OAAO,cAAc,UAAU,QAAQ,KAAK,UAAU,WAAW;AACpE,YAAM,IAAI,UAAU,6BAA6B;AAAA,EACrD;AACA,QAAM,WAAW,WACd,OAAO,CAAC,MAAM;AACb,QAAI,CAAC,EAAE,QAAS,QAAO;AACvB,UAAM,IAAI,MAAM,SAAS,KAAK,CAACA,OAAMA,GAAE,OAAO,EAAE,SAAS;AACzD,WACE,CAAC,CAAC,KACF,EAAE,UACF,EAAE,uBACD,EAAE,SAAS,oBAAoB,EAAE,sBAAsB;AAAA,EAE5D,CAAC,EACA,KAAK,CAAC,GAAG,MAAM,EAAE,WAAW,EAAE,QAAQ;AACzC,MACE,IAAI,IAAI,SAAS,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,SAAS,SAAS,UACtD,IAAI,IAAI,SAAS,IAAI,CAAC,MAAM,EAAE,QAAQ,CAAC,EAAE,SAAS,SAAS;AAE3D,UAAM,IAAI,UAAU,8BAA8B;AACpD,SAAO,SAAS,IAAI,CAAC,MAAM,EAAE,GAAG;AAClC;AACO,SAAS,iBACd,cACA,eAAyD,CAAC,GAC3C;AACf,QAAM,OAAO,oBAAI,IAAgE;AACjF,QAAM,QAAQ,oBAAI,IAAoB;AAC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