@modainteract/moda-interact-shared 5.11.1 → 5.12.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -0
- package/dist/{chunk-5BIYNMMT.js → chunk-JWX4ZVKK.js} +2 -101
- package/dist/chunk-JWX4ZVKK.js.map +1 -0
- package/dist/chunk-SOAGFZ7A.js +184 -0
- package/dist/chunk-SOAGFZ7A.js.map +1 -0
- package/dist/chunk-VJNXWDA5.js +105 -0
- package/dist/chunk-VJNXWDA5.js.map +1 -0
- package/dist/{chunk-WONND3OK.js → chunk-ZIUKIZTK.js} +3 -1
- package/dist/chunk-ZIUKIZTK.js.map +1 -0
- package/dist/commerce/index.js +6 -4
- package/dist/commerce/index.js.map +1 -1
- package/dist/commerce/model/node.d.ts +1 -1
- package/dist/commerce/model/node.js +1 -1
- package/dist/commerce/outreach/index.d.ts +1 -1
- package/dist/commerce/outreach/index.js +1 -1
- package/dist/commerce/presentation/index.d.ts +5 -78
- package/dist/commerce/presentation/index.js +37 -87
- package/dist/commerce/presentation/index.js.map +1 -1
- package/dist/commerce/presentation/node/index.d.ts +186 -0
- package/dist/commerce/presentation/node/index.js +976 -0
- package/dist/commerce/presentation/node/index.js.map +1 -0
- package/dist/commerce/runner/index.d.ts +2 -2
- package/dist/commerce/runner/index.js +13 -8
- package/dist/commerce/runner/index.js.map +1 -1
- package/dist/{types-CxiCD8Pw.d.ts → types-CGf6Mppg.d.ts} +1 -1
- package/dist/wrapper-contracts-BcxDQPon.d.ts +243 -0
- package/package.json +9 -2
- package/dist/chunk-5BIYNMMT.js.map +0 -1
- package/dist/chunk-WONND3OK.js.map +0 -1
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
|
|
3
|
+
/** Admin's documented stable JSON hashing protocol, without importing its AST/compiler. */
|
|
4
|
+
declare function stableJson(value: unknown): string;
|
|
5
|
+
type PresentationDigest = (value: string) => string;
|
|
6
|
+
declare function digest(value: string, sha256: PresentationDigest): string;
|
|
7
|
+
/** Never parse localeAst.authoring. Fail closed if the compiled runtime projection is absent. */
|
|
8
|
+
declare function readPreparedWrapper(localeAst: unknown, contentHash: string | null, sha256: PresentationDigest): {
|
|
9
|
+
kind: "ok";
|
|
10
|
+
prepared: PreparedWrapper;
|
|
11
|
+
} | {
|
|
12
|
+
kind: "missing" | "invalid";
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
declare const Platform: z.ZodEnum<{
|
|
16
|
+
SHOPIFY: "SHOPIFY";
|
|
17
|
+
WOOCOMMERCE: "WOOCOMMERCE";
|
|
18
|
+
}>;
|
|
19
|
+
declare const ConversationProductImageBindingSchema: z.ZodObject<{
|
|
20
|
+
variable: z.ZodLiteral<"response.productImage">;
|
|
21
|
+
placement: z.ZodLiteral<"BEFORE_BODY">;
|
|
22
|
+
optional: z.ZodLiteral<true>;
|
|
23
|
+
}, z.core.$strict>;
|
|
24
|
+
type ConversationProductImageBinding = z.infer<typeof ConversationProductImageBindingSchema>;
|
|
25
|
+
declare const ConversationProductPairSchema: z.ZodObject<{
|
|
26
|
+
productId: z.ZodString;
|
|
27
|
+
variantId: z.ZodNullable<z.ZodString>;
|
|
28
|
+
}, z.core.$strict>;
|
|
29
|
+
type ConversationProductPair = z.infer<typeof ConversationProductPairSchema>;
|
|
30
|
+
declare const ConversationVerifiedProductsSchema: z.ZodObject<{
|
|
31
|
+
shopId: z.ZodString;
|
|
32
|
+
platform: z.ZodEnum<{
|
|
33
|
+
SHOPIFY: "SHOPIFY";
|
|
34
|
+
WOOCOMMERCE: "WOOCOMMERCE";
|
|
35
|
+
}>;
|
|
36
|
+
products: z.ZodArray<z.ZodObject<{
|
|
37
|
+
stock: z.ZodOptional<z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
38
|
+
status: z.ZodLiteral<"KNOWN">;
|
|
39
|
+
quantity: z.ZodNumber;
|
|
40
|
+
scope: z.ZodEnum<{
|
|
41
|
+
PRODUCT: "PRODUCT";
|
|
42
|
+
VARIANT: "VARIANT";
|
|
43
|
+
}>;
|
|
44
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
45
|
+
status: z.ZodLiteral<"NOT_TRACKED">;
|
|
46
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
47
|
+
status: z.ZodLiteral<"UNAVAILABLE">;
|
|
48
|
+
}, z.core.$strict>], "status">>;
|
|
49
|
+
description: z.ZodOptional<z.ZodPreprocess<z.ZodObject<{
|
|
50
|
+
status: z.ZodEnum<{
|
|
51
|
+
AVAILABLE: "AVAILABLE";
|
|
52
|
+
NOT_PROVIDED: "NOT_PROVIDED";
|
|
53
|
+
PARTIAL: "PARTIAL";
|
|
54
|
+
}>;
|
|
55
|
+
text: z.ZodString;
|
|
56
|
+
}, z.core.$strict>>>;
|
|
57
|
+
attributes: z.ZodOptional<z.ZodPreprocess<z.ZodObject<{
|
|
58
|
+
status: z.ZodEnum<{
|
|
59
|
+
AVAILABLE: "AVAILABLE";
|
|
60
|
+
NOT_PROVIDED: "NOT_PROVIDED";
|
|
61
|
+
PARTIAL: "PARTIAL";
|
|
62
|
+
}>;
|
|
63
|
+
items: z.ZodArray<z.ZodObject<{
|
|
64
|
+
name: z.ZodString;
|
|
65
|
+
values: z.ZodArray<z.ZodString>;
|
|
66
|
+
}, z.core.$strict>>;
|
|
67
|
+
}, z.core.$strict>>>;
|
|
68
|
+
options: z.ZodOptional<z.ZodPreprocess<z.ZodObject<{
|
|
69
|
+
status: z.ZodEnum<{
|
|
70
|
+
AVAILABLE: "AVAILABLE";
|
|
71
|
+
NOT_PROVIDED: "NOT_PROVIDED";
|
|
72
|
+
PARTIAL: "PARTIAL";
|
|
73
|
+
}>;
|
|
74
|
+
items: z.ZodArray<z.ZodObject<{
|
|
75
|
+
name: z.ZodPipe<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>, z.ZodString>;
|
|
76
|
+
values: z.ZodArray<z.ZodPipe<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>, z.ZodString>>;
|
|
77
|
+
usedForVariants: z.ZodNullable<z.ZodBoolean>;
|
|
78
|
+
}, z.core.$strict>>;
|
|
79
|
+
}, z.core.$strict>>>;
|
|
80
|
+
selectedOptions: z.ZodOptional<z.ZodPreprocess<z.ZodArray<z.ZodObject<{
|
|
81
|
+
name: z.ZodPipe<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>, z.ZodString>;
|
|
82
|
+
value: z.ZodPipe<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>, z.ZodString>;
|
|
83
|
+
}, z.core.$strict>>>>;
|
|
84
|
+
productId: z.ZodString;
|
|
85
|
+
variantId: z.ZodNullable<z.ZodString>;
|
|
86
|
+
title: z.ZodString;
|
|
87
|
+
url: z.ZodNullable<z.ZodURL>;
|
|
88
|
+
available: z.ZodNullable<z.ZodBoolean>;
|
|
89
|
+
unitPrice: z.ZodNullable<z.ZodString>;
|
|
90
|
+
currency: z.ZodNullable<z.ZodString>;
|
|
91
|
+
productType: z.ZodNullable<z.ZodString>;
|
|
92
|
+
vendor: z.ZodNullable<z.ZodString>;
|
|
93
|
+
categories: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
94
|
+
categoryIds: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
95
|
+
collectionIds: z.ZodOptional<z.ZodArray<z.ZodString>>;
|
|
96
|
+
imageUrl: z.ZodOptional<z.ZodNullable<z.ZodString>>;
|
|
97
|
+
saleEvidence: z.ZodOptional<z.ZodNullable<z.ZodObject<{
|
|
98
|
+
regularPrice: z.ZodNullable<z.ZodString>;
|
|
99
|
+
salePrice: z.ZodNullable<z.ZodString>;
|
|
100
|
+
observedAt: z.ZodISODateTime;
|
|
101
|
+
}, z.core.$strict>>>;
|
|
102
|
+
observedAt: z.ZodISODateTime;
|
|
103
|
+
}, z.core.$strict>>;
|
|
104
|
+
}, z.core.$strict>;
|
|
105
|
+
type ConversationVerifiedProducts = z.infer<typeof ConversationVerifiedProductsSchema>;
|
|
106
|
+
declare const ConversationProductImageSourceSchema: z.ZodObject<{
|
|
107
|
+
kind: z.ZodLiteral<"SOURCE">;
|
|
108
|
+
shopId: z.ZodString;
|
|
109
|
+
platform: z.ZodEnum<{
|
|
110
|
+
SHOPIFY: "SHOPIFY";
|
|
111
|
+
WOOCOMMERCE: "WOOCOMMERCE";
|
|
112
|
+
}>;
|
|
113
|
+
productId: z.ZodString;
|
|
114
|
+
variantId: z.ZodNullable<z.ZodString>;
|
|
115
|
+
sourceUrl: z.ZodString;
|
|
116
|
+
}, z.core.$strict>;
|
|
117
|
+
type ConversationProductImageSource = z.infer<typeof ConversationProductImageSourceSchema>;
|
|
118
|
+
declare const ConversationPreparedProductImageSchema: z.ZodObject<{
|
|
119
|
+
schemaVersion: z.ZodLiteral<1>;
|
|
120
|
+
shopId: z.ZodString;
|
|
121
|
+
productId: z.ZodString;
|
|
122
|
+
variantId: z.ZodNullable<z.ZodString>;
|
|
123
|
+
publicUrl: z.ZodString;
|
|
124
|
+
objectKey: z.ZodString;
|
|
125
|
+
contentSha256: z.ZodString;
|
|
126
|
+
contentType: z.ZodLiteral<"image/jpeg">;
|
|
127
|
+
byteLength: z.ZodNumber;
|
|
128
|
+
width: z.ZodLiteral<1125>;
|
|
129
|
+
height: z.ZodLiteral<600>;
|
|
130
|
+
}, z.core.$strict>;
|
|
131
|
+
type ConversationPreparedProductImage = z.infer<typeof ConversationPreparedProductImageSchema>;
|
|
132
|
+
declare const ConversationDeliveryPlanSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
133
|
+
schemaVersion: z.ZodLiteral<1>;
|
|
134
|
+
kind: z.ZodLiteral<"TEXT">;
|
|
135
|
+
body: z.ZodString;
|
|
136
|
+
}, z.core.$strict>, z.ZodObject<{
|
|
137
|
+
schemaVersion: z.ZodLiteral<1>;
|
|
138
|
+
kind: z.ZodLiteral<"IMAGE">;
|
|
139
|
+
body: z.ZodString;
|
|
140
|
+
image: z.ZodObject<{
|
|
141
|
+
schemaVersion: z.ZodLiteral<1>;
|
|
142
|
+
shopId: z.ZodString;
|
|
143
|
+
productId: z.ZodString;
|
|
144
|
+
variantId: z.ZodNullable<z.ZodString>;
|
|
145
|
+
publicUrl: z.ZodString;
|
|
146
|
+
objectKey: z.ZodString;
|
|
147
|
+
contentSha256: z.ZodString;
|
|
148
|
+
contentType: z.ZodLiteral<"image/jpeg">;
|
|
149
|
+
byteLength: z.ZodNumber;
|
|
150
|
+
width: z.ZodLiteral<1125>;
|
|
151
|
+
height: z.ZodLiteral<600>;
|
|
152
|
+
}, z.core.$strict>;
|
|
153
|
+
}, z.core.$strict>], "kind">;
|
|
154
|
+
type ConversationDeliveryPlan = z.infer<typeof ConversationDeliveryPlanSchema>;
|
|
155
|
+
declare function chooseConversationProductImageSource(input: {
|
|
156
|
+
shopId: string;
|
|
157
|
+
platform: z.infer<typeof Platform>;
|
|
158
|
+
displayedPairs: readonly ConversationProductPair[];
|
|
159
|
+
verifiedProducts: ConversationVerifiedProducts;
|
|
160
|
+
}): ConversationProductImageSource | {
|
|
161
|
+
kind: 'OMITTED';
|
|
162
|
+
reason: 'NO_PRESENTED_PRODUCT' | 'NO_PRODUCT_IMAGE' | 'PRODUCT_NOT_VERIFIED';
|
|
163
|
+
};
|
|
164
|
+
type ConversationMediaOmission = 'BINDING_DISABLED' | 'NO_PRESENTED_PRODUCT' | 'CAPTION_TOO_LONG' | 'IMAGE_UNAVAILABLE' | 'IMAGE_IDENTITY_MISMATCH';
|
|
165
|
+
declare function buildConversationDeliveryPlan(input: {
|
|
166
|
+
body: string;
|
|
167
|
+
binding?: ConversationProductImageBinding;
|
|
168
|
+
image?: ConversationPreparedProductImage | null;
|
|
169
|
+
shopId: string;
|
|
170
|
+
displayedPairs: readonly ConversationProductPair[];
|
|
171
|
+
}): {
|
|
172
|
+
plan: ConversationDeliveryPlan;
|
|
173
|
+
mediaOmission: ConversationMediaOmission | null;
|
|
174
|
+
};
|
|
175
|
+
declare function digestConversationDeliveryPlan(plan: ConversationDeliveryPlan, sha256: PresentationDigest): string;
|
|
176
|
+
|
|
177
|
+
/** Pure immutable wrapper projections. Host-owned persistence and sending stay outside Shared. */
|
|
178
|
+
type WrapperSource = "AI" | "HUMAN";
|
|
179
|
+
type WrapperAudience = "SHARED" | WrapperSource;
|
|
180
|
+
type WrapperVariable = "customer.firstName" | "shop.name" | "checkout.url" | "shopBrand.brandName" | "shopBrand.logoUrl" | "shopBrand.logoAltText" | "shopBrand.logoWidth" | "shopBrand.logoHeight" | "shopBrand.squareLogoUrl" | "shopBrand.squareLogoAltText" | "shopBrand.coverImageUrl";
|
|
181
|
+
type PreparedToken = Readonly<{
|
|
182
|
+
kind: "text";
|
|
183
|
+
value: string;
|
|
184
|
+
}> | Readonly<{
|
|
185
|
+
kind: "variable";
|
|
186
|
+
name: WrapperVariable;
|
|
187
|
+
}> | Readonly<{
|
|
188
|
+
kind: "responseSlot";
|
|
189
|
+
name: "response.body";
|
|
190
|
+
}>;
|
|
191
|
+
/** Admin emits this immutable projection in WhatsAppTemplateLocale.localeAst.prepared. */
|
|
192
|
+
type PreparedWrapper = Readonly<{
|
|
193
|
+
schemaVersion: 1;
|
|
194
|
+
family: "MODA_CONVERSATION_WRAPPER";
|
|
195
|
+
responseSlot: "response.body";
|
|
196
|
+
productImage?: ConversationProductImageBinding;
|
|
197
|
+
header: readonly PreparedToken[];
|
|
198
|
+
body: readonly PreparedToken[];
|
|
199
|
+
footer: readonly PreparedToken[];
|
|
200
|
+
conditionals: readonly Readonly<{
|
|
201
|
+
when: "checkout.available";
|
|
202
|
+
tokens: readonly PreparedToken[];
|
|
203
|
+
}>[];
|
|
204
|
+
}>;
|
|
205
|
+
type VerifiedWrapperContext = Readonly<{
|
|
206
|
+
conversationId: string;
|
|
207
|
+
shopId: string;
|
|
208
|
+
conversationLanguageTag: string | null;
|
|
209
|
+
merchantLanguageTag: string | null;
|
|
210
|
+
variables: Partial<Record<WrapperVariable, string>>;
|
|
211
|
+
checkoutAvailable: boolean;
|
|
212
|
+
}>;
|
|
213
|
+
type WrapperDefinition = Readonly<{
|
|
214
|
+
id: string;
|
|
215
|
+
kind: string;
|
|
216
|
+
audience: string | null;
|
|
217
|
+
status: string;
|
|
218
|
+
sourceLanguageTag: string;
|
|
219
|
+
astSchemaVersion: number;
|
|
220
|
+
sourceHash: string;
|
|
221
|
+
publishedAt: Date | null;
|
|
222
|
+
retiredAt: Date | null;
|
|
223
|
+
createdByAdminId: string;
|
|
224
|
+
locales: readonly Readonly<{
|
|
225
|
+
id: string;
|
|
226
|
+
languageTag: string;
|
|
227
|
+
status: string;
|
|
228
|
+
providerLanguageCode: string | null;
|
|
229
|
+
localeAst: unknown;
|
|
230
|
+
contentHash: string | null;
|
|
231
|
+
reviewedAt: Date | null;
|
|
232
|
+
reviewedByAdminId: string | null;
|
|
233
|
+
}>[];
|
|
234
|
+
}>;
|
|
235
|
+
type WrapperSlot = Readonly<{
|
|
236
|
+
audience: string;
|
|
237
|
+
definitionId: string;
|
|
238
|
+
editVersion: number;
|
|
239
|
+
definition: WrapperDefinition;
|
|
240
|
+
}>;
|
|
241
|
+
type WrapperRefusal = "INVALID_INPUT" | "INVALID_LANGUAGE" | "CONVERSATION_UNAVAILABLE" | "TENANT_MISMATCH" | "NOT_CONFIGURED" | "DEFINITION_UNAVAILABLE" | "LOCALE_UNAVAILABLE" | "PREPARED_MISSING" | "PREPARED_INVALID" | "VARIABLE_UNAVAILABLE" | "ALREADY_WRAPPED" | "OUTPUT_TOO_LONG" | "REPLAY_MISMATCH";
|
|
242
|
+
|
|
243
|
+
export { type ConversationPreparedProductImage as C, type PreparedWrapper as P, type VerifiedWrapperContext as V, type WrapperRefusal as W, type ConversationProductImageSource as a, type WrapperSlot as b, type WrapperDefinition as c, type PresentationDigest as d, type ConversationDeliveryPlan as e, ConversationDeliveryPlanSchema as f, type ConversationMediaOmission as g, ConversationPreparedProductImageSchema as h, type ConversationProductImageBinding as i, ConversationProductImageBindingSchema as j, ConversationProductImageSourceSchema as k, type ConversationProductPair as l, ConversationProductPairSchema as m, type ConversationVerifiedProducts as n, ConversationVerifiedProductsSchema as o, type PreparedToken as p, type WrapperAudience as q, type WrapperSource as r, type WrapperVariable as s, buildConversationDeliveryPlan as t, chooseConversationProductImageSource as u, digest as v, digestConversationDeliveryPlan as w, readPreparedWrapper as x, stableJson as y };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@modainteract/moda-interact-shared",
|
|
3
|
-
"version": "5.
|
|
3
|
+
"version": "5.12.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -138,6 +138,10 @@
|
|
|
138
138
|
"./commerce/outreach": {
|
|
139
139
|
"types": "./dist/commerce/outreach/index.d.ts",
|
|
140
140
|
"import": "./dist/commerce/outreach/index.js"
|
|
141
|
+
},
|
|
142
|
+
"./commerce/presentation/node": {
|
|
143
|
+
"types": "./dist/commerce/presentation/node/index.d.ts",
|
|
144
|
+
"import": "./dist/commerce/presentation/node/index.js"
|
|
141
145
|
}
|
|
142
146
|
},
|
|
143
147
|
"files": [
|
|
@@ -165,9 +169,11 @@
|
|
|
165
169
|
"validate:arch047-whatsapp-template-events": "node scripts/validate-whatsapp-template-events-entrypoint.mjs",
|
|
166
170
|
"test:product-discovery-contracts": "tsx --test src/commerce/product-discovery-contracts.test.ts src/commerce/product-discovery-projection.test.ts src/commerce/runner/built-in-tools.test.ts src/commerce/runner/runner.test.ts",
|
|
167
171
|
"validate:commerce-presentation": "node scripts/validate-commerce-presentation.mjs",
|
|
168
|
-
"validate:commerce-outreach": "node scripts/validate-commerce-outreach.mjs"
|
|
172
|
+
"validate:commerce-outreach": "node scripts/validate-commerce-outreach.mjs",
|
|
173
|
+
"validate:conversation-product-image-node": "node scripts/validate-conversation-product-image-node.mjs"
|
|
169
174
|
},
|
|
170
175
|
"dependencies": {
|
|
176
|
+
"@aws-sdk/client-s3": "3.1143.0",
|
|
171
177
|
"@langchain/core": "1.2.13",
|
|
172
178
|
"@langchain/langgraph": "1.4.15",
|
|
173
179
|
"@langchain/openrouter": "0.4.15",
|
|
@@ -190,6 +196,7 @@
|
|
|
190
196
|
"libphonenumber-js": "1.12.30",
|
|
191
197
|
"parse5": "8.0.1",
|
|
192
198
|
"semver": "7.8.5",
|
|
199
|
+
"sharp": "0.35.4",
|
|
193
200
|
"winston": "3.19.0",
|
|
194
201
|
"winston-loki": "6.1.7",
|
|
195
202
|
"zod": "^4.0.0"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commerce/selection.ts","../src/commerce/product-context.ts"],"sourcesContent":["import { IdSchema } from \"./primitives\";\nimport {\n CommerceAnswerPresentationSelectionSchema,\n type CommerceAnswerPresentationSelection,\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\n/** Validate model-selected identities; hosts must still authorize and freshly verify facts. */\nexport function verifyCommerceAnswerPresentationSelection(raw: unknown):\n | { kind: \"verified\"; selection: CommerceAnswerPresentationSelection }\n | { kind: \"limitation\"; reason: \"INVALID_SELECTION\" } {\n const parsed = CommerceAnswerPresentationSelectionSchema.safeParse(raw);\n if (!parsed.success || (parsed.data.productOptionSelections?.length && parsed.data.productDetailSelections?.length))\n return { kind: \"limitation\", reason: \"INVALID_SELECTION\" };\n return { kind: \"verified\", selection: parsed.data };\n}\n","import { z } from \"zod\";\nimport { CommerceProductSchema, CommerceProductSelectedOptionsSchema } 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),selectedOptions:CommerceProductSelectedOptionsSchema.optional(),observedAt:date})).max(20),presentation:z.strictObject({references:z.array(z.strictObject({productId:id,variantId:id.nullable()})).max(3),presentedAt:date}).optional(),updatedAt:date}).superRefine((v,c)=>{\n const pairs=v.presentation?.references??[];\n if(new Set(pairs.map(r=>JSON.stringify([r.productId,r.variantId]))).size!==pairs.length||pairs.some(p=>!v.references.some(r=>r.productId===p.productId&&r.variantId===p.variantId)))c.addIssue({code:'custom',message:'Invalid product presentation'});\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,...(p.selectedOptions!==undefined?{selectedOptions:p.selectedOptions}:{}),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:CommerceConversationProductContext={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 if(previous?.presentation&&fresh(previous.presentation.presentedAt)&&previous.presentation.references.every(p=>references.some(r=>r.productId===p.productId&&r.variantId===p.variantId)))result.presentation=previous.presentation;\n while(references.length&&new TextEncoder().encode(JSON.stringify(result)).length>32768){references.pop();if(result.presentation?.references.some(p=>!references.some(r=>r.productId===p.productId&&r.variantId===p.variantId)))delete result.presentation;}\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\n/** Record only exact pairs actually composed by the host; references remain stale labels. */\nexport function recordCommerceProductPresentation(context:CommerceConversationProductContext,pairs:readonly {productId:string;variantId:string|null}[],identity:CommerceProductContextIdentity):CommerceConversationProductContext {\n const fresh=mergeConversationProductContext(context,[],identity);\n const parsed=z.array(z.strictObject({productId:id,variantId:id.nullable()})).max(3).safeParse(pairs);\n if(!parsed.success||new Set(pairs.map(p=>JSON.stringify([p.productId,p.variantId]))).size!==pairs.length||pairs.some(p=>!fresh.references.some(r=>r.productId===p.productId&&r.variantId===p.variantId)))throw new Error('PRODUCT_PRESENTATION_INVALID');\n const result:CommerceConversationProductContext={...fresh,presentation:{references:parsed.data,presentedAt:new Date(identity.now).toISOString()}};\n while(result.references.length&&new TextEncoder().encode(JSON.stringify(result)).length>32768){result.references.pop();if(result.presentation?.references.some(p=>!result.references.some(r=>r.productId===p.productId&&r.variantId===p.variantId)))delete result.presentation;}\n return CommerceConversationProductContextSchema.parse(result);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAmBO,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,OAA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,WAAU,WAAU,OAAO,CAAC,EAAG,UAAS,IAAE,OAAO,SAAO,IAAE,EAAC,MAAK,YAAW,IAAE,EAAC,MAAK,UAAS;AAC3P;AAGO,SAAS,kCAAkC,SAA2C,OAA0D,UAA4E;AAClO,QAAM,QAAM,gCAAgC,SAAQ,CAAC,GAAE,QAAQ;AAC/D,QAAM,SAAO,EAAE,MAAM,EAAE,aAAa,EAAC,WAAU,IAAG,WAAU,GAAG,SAAS,EAAC,CAAC,CAAC,EAAE,IAAI,CAAC,EAAE,UAAU,KAAK;AACnG,MAAG,CAAC,OAAO,WAAS,IAAI,IAAI,MAAM,IAAI,OAAG,KAAK,UAAU,CAAC,EAAE,WAAU,EAAE,SAAS,CAAC,CAAC,CAAC,EAAE,SAAO,MAAM,UAAQ,MAAM,KAAK,OAAG,CAAC,MAAM,WAAW,KAAK,OAAG,EAAE,cAAY,EAAE,aAAW,EAAE,cAAY,EAAE,SAAS,CAAC,EAAE,OAAM,IAAI,MAAM,8BAA8B;AACvP,QAAM,SAA0C,EAAC,GAAG,OAAM,cAAa,EAAC,YAAW,OAAO,MAAK,aAAY,IAAI,KAAK,SAAS,GAAG,EAAE,YAAY,EAAC,EAAC;AAChJ,SAAM,OAAO,WAAW,UAAQ,IAAI,YAAY,EAAE,OAAO,KAAK,UAAU,MAAM,CAAC,EAAE,SAAO,OAAM;AAAC,WAAO,WAAW,IAAI;AAAE,QAAG,OAAO,cAAc,WAAW,KAAK,OAAG,CAAC,OAAO,WAAW,KAAK,OAAG,EAAE,cAAY,EAAE,aAAW,EAAE,cAAY,EAAE,SAAS,CAAC,EAAE,QAAO,OAAO;AAAA,EAAa;AAC/Q,SAAO,yCAAyC,MAAM,MAAM;AAC7D;","names":["f"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commerce/runner/diagnostic-messages.ts","../src/commerce/runner/diagnostics.ts","../src/commerce/runner/failure.ts"],"sourcesContent":["import type { RunnerDiagnosticReason, RunnerTransportCode } from \"./diagnostics.js\";\n\ntype Explanation = Readonly<{ message: string; action: string }>;\n\n/** Fixed operator-facing explanations. No provider-supplied or customer-supplied text is interpolated. */\nconst explanations = {\n MODEL_OUTPUT_TOKENS_EXHAUSTED: [\"The provider exhausted output tokens without visible text or tool calls.\", \"Inspect token usage and provider response; do not fabricate a reply or retry silently.\"],\n CANCELLED_BY_CALLER: [\"The calling service cancelled this conversation turn.\", \"Inspect caller cancellation and superseded-message handling.\"],\n TURN_DEADLINE_EXCEEDED: [\"The conversation turn exceeded its overall deadline.\", \"Inspect elapsed time across the model and tool calls.\"],\n OPERATION_TIMEOUT: [\"One model or tool operation exceeded its per-operation time limit.\", \"Inspect the operation stage, provider latency and timeout configuration.\"],\n UPSTREAM_OPERATION_FAILED: [\"A model or tool operation threw an exception before returning a usable result.\", \"Inspect the stage, exceptionName and transportCode; check upstream service health.\"],\n UNEXPECTED_EXCEPTION: [\"The runner encountered an unexpected exception.\", \"Inspect the failing stage and exceptionName; investigate the owning service.\"],\n INPUT_TOO_LARGE: [\"The manifest or conversation grant exceeded the allowed payload size.\", \"Reduce the manifest or grant size and check the producer's limits.\"],\n TURN_INVALID: [\"The supplied conversation-turn identity failed schema validation.\", \"Inspect the reported schema issue paths and the turn producer.\"],\n GRANT_INVALID: [\"The supplied conversation grant failed schema validation.\", \"Inspect the reported schema issue paths and grant issuer.\"],\n MANIFEST_INVALID: [\"The supplied capability manifest failed schema validation.\", \"Verify manifest version and schema fields against the published contract.\"],\n GRANT_MISMATCH: [\"The turn identity, grant and manifest do not belong to the same authorised conversation.\", \"Check shop, conversation, grant and inbound-version correlation; do not bypass authorization.\"],\n RUNNER_VERSION_INCOMPATIBLE: [\"The release manifest requires a different runner version.\", \"Align the deployed Shared runner version with the release's compatibility range.\"],\n RESPONSE_CONTRACT_INVALID: [\"The trusted final-response contract failed integrity or compatibility verification.\", \"Recheck the published release and contract digest.\"],\n LANGUAGE_INVALID: [\"The supplied conversation language or language-source fields are invalid.\", \"Check the host language configuration and supported locale values.\"],\n BUDGET_INVALID: [\"A configured model, remote-call, deadline or token budget is invalid.\", \"Supply positive safe integers for each budget; the caller owns budget policy.\"],\n CONTEXT_INVALID: [\"The trusted instructions, history or context failed size or shape constraints.\", \"Inspect context construction and trim oversized history or instructions.\"],\n TOOL_REGISTRATION_INVALID: [\"The host registered duplicate or otherwise invalid tools.\", \"Check the tool registry supplied to the runner.\"],\n MODEL_STEP_BUDGET_EXHAUSTED: [\"The model used every allowed reasoning step without reaching a valid final answer.\", \"Inspect model routing and tool-call loops; reassess the configured step budget.\"],\n MODEL_INVOCATION_FAILED: [\"The model invocation failed without a provider-specific diagnostic.\", \"Inspect the model host and preserve a typed provider failure at its boundary.\"],\n MODEL_STEP_NOT_OBJECT: [\"The model step was not a non-null object.\", \"Check the model adapter's returned step type.\"],\n MODEL_STEP_CALLS_MISSING: [\"The model step did not contain a calls field.\", \"Ensure the model adapter returns a calls array, even when empty.\"],\n MODEL_STEP_CALLS_NOT_ARRAY: [\"The model step's calls field was not an array.\", \"Ensure the model adapter maps provider tool calls to an array.\"],\n MODEL_OUTPUT_TOKENS_MISSING: [\"The model step did not contain an outputTokens field.\", \"Ensure the adapter includes the provider's output-token usage count.\"],\n MODEL_OUTPUT_TOKENS_NOT_SAFE_INTEGER: [\"The model step's outputTokens was not a safe integer.\", \"Ensure the adapter returns a finite, whole-number output token count.\"],\n MODEL_OUTPUT_TOKENS_NEGATIVE: [\"The model step's outputTokens was negative.\", \"Correct the model adapter's token-usage mapping; token counts cannot be negative.\"],\n MODEL_OUTPUT_TOKENS_OVER_BUDGET: [\"The model step's outputTokens exceeded the configured output-token budget.\", \"Inspect the model's maxOutputTokens enforcement and returned usage count.\"],\n MODEL_TOOL_CALL_LIMIT_EXCEEDED: [\"The model step contained more than 32 tool calls.\", \"Limit provider tool-call output to the runner's maximum of 32 calls.\"],\n MODEL_TOOL_CALL_NULL: [\"The model returned a null tool-call entry.\", \"Check the model adapter's tool-call conversion; each entry must have a name and arguments object.\"],\n MODEL_TOOL_CALL_NOT_OBJECT: [\"The model returned a tool-call entry that was not an object.\", \"Check the model adapter's tool-call conversion; arrays and primitive entries are invalid.\"],\n MODEL_TOOL_CALL_NAME_MISSING: [\"The model returned a tool call without a name field.\", \"Include a non-empty name string in every model tool call.\"],\n MODEL_TOOL_CALL_NAME_NOT_STRING: [\"The model returned a tool call whose name was not a string.\", \"Ensure the tool-call name is a string in the model adapter.\"],\n MODEL_TOOL_CALL_NAME_EMPTY: [\"The model returned a tool call with an empty name.\", \"Check provider tool naming and model adapter normalization.\"],\n MODEL_TOOL_CALL_NAME_TOO_LONG: [\"The model returned a tool-call name longer than 128 characters.\", \"Limit each tool-call name to 128 characters in the model adapter.\"],\n MODEL_TOOL_CALL_ARGUMENTS_MISSING: [\"The model returned a tool call without an arguments field.\", \"Include an arguments object for every model tool call.\"],\n MODEL_TOOL_CALL_ARGUMENTS_NULL: [\"The model returned a tool call with null arguments.\", \"Return an object, including an empty object when appropriate, instead of null arguments.\"],\n MODEL_TOOL_CALL_ARGUMENTS_NOT_OBJECT: [\"The model returned tool-call arguments that were not an object.\", \"Convert provider tool-call arguments to a non-array object in the model adapter.\"],\n MODEL_TEXT_NOT_STRING: [\"The model's candidate reply was not text.\", \"Check the model adapter's conversion of the provider response content.\"],\n MODEL_TEXT_TOO_LONG: [\"The model's candidate reply exceeded 4096 characters.\", \"Limit the natural-language reply to the response contract's maximum length.\"],\n MODEL_STEP_TOO_LARGE: [\"The model step exceeded the 262144-byte serialized payload limit.\", \"Reduce tool-call argument payload size before returning the model step.\"],\n MODEL_STEP_NOT_SERIALIZABLE: [\"The model step could not be encoded as canonical JSON.\", \"Inspect model-step data for cycles, invalid Unicode or unsupported JSON values.\"],\n MODEL_STEP_VALIDATION_FAILED: [\"The runner threw an exception while reading or checking the model step.\", \"Inspect the safe exception metadata and model-step adapter implementation.\"],\n MODEL_CALL_ROUTE_INVALID: [\"The model produced neither a usable reply nor an allowed tool-call route, or mixed finalResponse with other calls.\", \"Inspect provider finish conditions, reply content and tool-call routing.\"],\n MODEL_RESULT_MISSING: [\"The runner graph finished without producing a final response.\", \"Inspect graph termination and the preceding model/tool steps.\"],\n REQUEST_INVALID: [\"The model adapter received an invalid invocation request.\", \"Inspect the model request construction and trusted payload validation.\"],\n MODEL_REQUEST_HISTORY_INVALID: [\"A history entry sent to the model was malformed or exceeded its text limit.\", \"Inspect the history formatter and permitted role/text shape.\"],\n MODEL_REQUEST_TOOL_RESULT_INVALID: [\"A tool-result message sent to the model failed the expected contract.\", \"Inspect the tool-result formatter and CommerceToolResult schema.\"],\n MODEL_CONFIGURATION_INVALID: [\"The configured model provider, model ID, options or schema version is invalid.\", \"Correct model selection and published configuration before invoking the model.\"],\n MODEL_CREDENTIAL_INVALID: [\"The model adapter received an empty or invalid credential value.\", \"Check secret resolution, credential availability and injection into the model host.\"],\n MODEL_ADAPTER_INITIALIZATION_FAILED: [\"The model client could not be constructed from its validated configuration.\", \"Inspect model SDK initialization and dependency compatibility.\"],\n MODEL_REQUEST_CANCELLED: [\"The model request was cancelled before invocation.\", \"Inspect caller cancellation; do not interpret this as provider downtime.\"],\n TOOL_BIND_FAILED: [\"The model client rejected the supplied tool definitions during binding.\", \"Check provider tool-calling support and function schemas.\"],\n PROVIDER_AUTH_FAILED: [\"The model provider rejected authentication or access to the requested resource.\", \"Check the provider credential, permissions and selected model.\"],\n PROVIDER_RATE_LIMITED: [\"The model provider returned HTTP 429: requests are being rate-limited or the quota is exhausted.\", \"Check provider usage, billing/quota and any Retry-After guidance; use bounded backoff.\"],\n PROVIDER_HTTP_ERROR: [\"The model provider returned an unsuccessful HTTP response.\", \"Inspect statusCode and check provider availability, model access and request compatibility.\"],\n PROVIDER_REQUEST_FAILED: [\"The model provider request failed before a usable HTTP response was received.\", \"Inspect transportCode and exceptionName; check DNS, connectivity, TLS and provider availability.\"],\n PROVIDER_RESPONSE_INVALID: [\"The model provider returned a response that the adapter cannot interpret.\", \"Check the provider SDK response shape and model adapter compatibility.\"],\n PROVIDER_RESPONSE_USAGE_INVALID: [\"The model response is missing a valid output-token usage count.\", \"Inspect provider usage_metadata.output_tokens and SDK response mapping.\"],\n PROVIDER_RESPONSE_TOOL_CALL_INVALID: [\"The model response contains a malformed tool call name or arguments object.\", \"Inspect provider tool-call formatting and SDK response mapping.\"],\n TOOL_DESCRIPTOR_MISMATCH: [\"The requested tool does not match an authorised published tool descriptor.\", \"Check published tool revisions and descriptor hashes.\"],\n TOOL_AUTHORIZATION_FAILED: [\"The host failed while checking whether a requested tool remains authorised.\", \"Inspect authorization-service availability and the requested tool.\"],\n TOOL_INPUT_INVALID: [\"The model supplied tool arguments that do not satisfy the tool input schema.\", \"Inspect issuePaths and the model's tool schema; do not invoke the tool.\"],\n TOOL_CALL_BUDGET_EXHAUSTED: [\"The turn exhausted its remote-call allowance before the next tool request.\", \"Inspect repeated tool calls, retry attempts and budget settings.\"],\n TOOL_EXECUTION_FAILED: [\"An authorised tool threw an exception during execution.\", \"Inspect the toolName, attempt, transportCode and owning tool service.\"],\n TOOL_RESULT_TOO_LARGE: [\"A tool returned more data than the runner permits.\", \"Reduce or paginate tool output before returning it to the runner.\"],\n TOOL_RESULT_INVALID: [\"A tool returned a result that failed serialization or schema validation.\", \"Inspect issuePaths and the tool adapter's CommerceToolResult output.\"],\n TOOL_RESULT_MISSING: [\"The tool execution loop ended without receiving a result.\", \"Inspect tool execution lifecycle and retry completion.\"],\n TOOL_STALE_TURN: [\"The tool reported that the conversation turn is no longer current.\", \"Inspect conversation versioning and abandon this obsolete turn.\"],\n EVIDENCE_INVALID: [\"Tool evidence failed its integrity, grant or freshness checks.\", \"Inspect tool evidence generation and turn/grant correlation.\"],\n FINAL_SCHEMA_INVALID: [\"The model's finalResponse failed runtime schema validation.\", \"Inspect issueCodes and issuePaths; correct response formatting or tool instructions.\"],\n FINAL_LANGUAGE_MISMATCH: [\"The final answer included language detection despite an explicit customer language.\", \"Check model instructions governing language metadata.\"],\n FINAL_REFERRAL_REQUIRED: [\"The model did not produce the mandatory store referral after a denied or failed tool.\", \"Check final-response referral rules and the recorded tool outcome.\"],\n FINAL_EVIDENCE_INVALID: [\"The final answer cited absent, unqualified or incorrectly scoped evidence.\", \"Inspect evidence identity, qualification and answer construction.\"],\n FINAL_EVIDENCE_EXPIRED: [\"The final answer cited evidence that expired during the turn.\", \"Refresh evidence and reconsider the turn's remaining deadline.\"],\n EVIDENCE_RESERVATION_EXCEEDED: [\"The final answer cited more evidence than the remaining remote-call reservation allows.\", \"Inspect evidence references and the remote-call budget reservation contract.\"],\n} as const satisfies Record<RunnerDiagnosticReason, readonly [string, string]>;\n\nconst transports = {\n ENOTFOUND: [\"The provider hostname could not be resolved by DNS.\", \"Check the configured hostname and DNS resolver.\"],\n EAI_AGAIN: [\"The provider DNS lookup temporarily failed.\", \"Check DNS availability and retry after a short delay.\"],\n ECONNREFUSED: [\"The provider connection was actively refused.\", \"Check the host, port and service listener.\"],\n ECONNRESET: [\"The provider connection was reset before the request finished.\", \"Check upstream restarts, proxies and connection stability.\"],\n ETIMEDOUT: [\"The network connection to the provider timed out.\", \"Check network reachability and upstream latency.\"],\n ENETUNREACH: [\"The network route to the provider is unreachable.\", \"Check egress routes, firewall and network configuration.\"],\n EHOSTUNREACH: [\"The provider host is unreachable.\", \"Check provider host, routing and firewall rules.\"],\n EPIPE: [\"The network connection closed while data was being written.\", \"Check upstream connection stability and proxy timeouts.\"],\n UND_ERR_CONNECT_TIMEOUT: [\"The HTTP client timed out establishing a provider connection.\", \"Check egress connectivity and provider latency.\"],\n UND_ERR_HEADERS_TIMEOUT: [\"The HTTP client timed out waiting for provider response headers.\", \"Check provider availability and response latency.\"],\n UND_ERR_SOCKET: [\"The HTTP client reported a socket failure.\", \"Check network and upstream connection stability.\"],\n CERT_HAS_EXPIRED: [\"The remote TLS certificate has expired.\", \"Check the certificate chain and provider endpoint.\"],\n UNABLE_TO_VERIFY_LEAF_SIGNATURE: [\"TLS certificate chain verification failed.\", \"Check trusted roots and certificate chain; do not disable TLS validation.\"],\n DEPTH_ZERO_SELF_SIGNED_CERT: [\"TLS rejected an untrusted self-signed certificate.\", \"Check trusted roots and proxy certificates; do not disable TLS validation.\"],\n ERR_TLS_CERT_ALTNAME_INVALID: [\"The provider TLS certificate does not match its hostname.\", \"Check endpoint hostname and certificate SANs.\"],\n} as const satisfies Record<RunnerTransportCode, readonly [string, string]>;\n\n/** HTTP descriptions are based on status alone and make no claims about hidden provider response bodies. */\nconst httpDetails: Readonly<Record<number, Explanation>> = {\n 400: { message: \"The provider rejected the request as invalid (HTTP 400).\", action: \"Check request parameters and provider model capabilities.\" },\n 402: { message: \"The provider returned HTTP 402 (payment or credits required).\", action: \"Check provider billing, available credits and account limits.\" },\n 404: { message: \"The provider returned HTTP 404 (endpoint or model not found).\", action: \"Check provider model ID, permissions and API route.\" },\n 413: { message: \"The provider rejected an oversized request (HTTP 413).\", action: \"Reduce request size and review model context limits.\" },\n 422: { message: \"The provider could not process the request parameters (HTTP 422).\", action: \"Check model input and tool schema compatibility.\" },\n 500: { message: \"The provider returned an internal server error (HTTP 500).\", action: \"Check provider status and use bounded retries.\" },\n 502: { message: \"The provider gateway reported an upstream error (HTTP 502).\", action: \"Check provider status, gateway health and bounded retries.\" },\n 503: { message: \"The provider is temporarily unavailable (HTTP 503).\", action: \"Check provider availability and backoff guidance.\" },\n 504: { message: \"The provider gateway timed out (HTTP 504).\", action: \"Check upstream latency and provider availability.\" },\n};\n\nexport function describeRunnerDiagnostic(input: {\n reasonCode: RunnerDiagnosticReason;\n statusCode?: number;\n transportCode?: RunnerTransportCode;\n callIndex?: number;\n}): Explanation {\n if (\n input.transportCode &&\n [\"PROVIDER_REQUEST_FAILED\", \"UPSTREAM_OPERATION_FAILED\", \"MODEL_INVOCATION_FAILED\", \"TOOL_EXECUTION_FAILED\", \"TOOL_AUTHORIZATION_FAILED\"].includes(input.reasonCode)\n ) {\n const explanation = transports[input.transportCode];\n return { message: `${explanation[0]} (${input.transportCode})`, action: explanation[1] };\n }\n if (input.reasonCode === \"PROVIDER_HTTP_ERROR\" && input.statusCode !== undefined && httpDetails[input.statusCode])\n return httpDetails[input.statusCode];\n const explanation = explanations[input.reasonCode];\n if (input.reasonCode === \"MODEL_TOOL_CALL_NULL\" && input.callIndex !== undefined)\n return {\n message: `The model returned a null tool-call entry at index ${input.callIndex}. Each tool call must contain a non-empty name and an arguments object.`,\n action: explanation[1],\n };\n if (input.reasonCode.startsWith(\"MODEL_TOOL_CALL_\") && input.callIndex !== undefined)\n return { message: `${explanation[0].replace(/\\.$/, \"\")} (index ${input.callIndex}).`, action: explanation[1] };\n return { message: explanation[0], action: explanation[1] };\n}\n","import type { ZodError } from \"zod\";\nimport { describeRunnerDiagnostic } from \"./diagnostic-messages.js\";\n\n/** Finite, non-customer-facing failure taxonomy for Commerce hosts and logs. */\nexport const RUNNER_DIAGNOSTIC_STAGES = [\n \"preflight.validate\", \"preflight.contract\", \"runtime.cancellation\", \"runtime.deadline\",\n \"runtime.operation\", \"tools.resolve\", \"model.invoke\", \"model.validate\", \"model.route\",\n \"tool.authorize\", \"tool.validate\", \"tool.execute\", \"tool.result\", \"evidence.validate\",\n \"final.validate\", \"graph.execute\",\n] as const;\nexport type RunnerDiagnosticStage = typeof RUNNER_DIAGNOSTIC_STAGES[number];\n\nexport const RUNNER_DIAGNOSTIC_REASONS = [\n \"CANCELLED_BY_CALLER\", \"TURN_DEADLINE_EXCEEDED\", \"OPERATION_TIMEOUT\",\n \"UPSTREAM_OPERATION_FAILED\", \"UNEXPECTED_EXCEPTION\",\n \"INPUT_TOO_LARGE\", \"TURN_INVALID\", \"GRANT_INVALID\", \"MANIFEST_INVALID\",\n \"GRANT_MISMATCH\", \"RUNNER_VERSION_INCOMPATIBLE\", \"RESPONSE_CONTRACT_INVALID\",\n \"LANGUAGE_INVALID\", \"BUDGET_INVALID\", \"CONTEXT_INVALID\", \"TOOL_REGISTRATION_INVALID\",\n \"MODEL_STEP_BUDGET_EXHAUSTED\", \"MODEL_INVOCATION_FAILED\",\n \"MODEL_STEP_NOT_OBJECT\", \"MODEL_STEP_CALLS_MISSING\", \"MODEL_STEP_CALLS_NOT_ARRAY\",\n \"MODEL_OUTPUT_TOKENS_MISSING\", \"MODEL_OUTPUT_TOKENS_NOT_SAFE_INTEGER\",\n \"MODEL_OUTPUT_TOKENS_EXHAUSTED\", \"MODEL_OUTPUT_TOKENS_NEGATIVE\", \"MODEL_OUTPUT_TOKENS_OVER_BUDGET\",\n \"MODEL_TOOL_CALL_LIMIT_EXCEEDED\", \"MODEL_TOOL_CALL_NULL\", \"MODEL_TOOL_CALL_NOT_OBJECT\",\n \"MODEL_TOOL_CALL_NAME_MISSING\", \"MODEL_TOOL_CALL_NAME_NOT_STRING\", \"MODEL_TOOL_CALL_NAME_EMPTY\",\n \"MODEL_TOOL_CALL_NAME_TOO_LONG\", \"MODEL_TOOL_CALL_ARGUMENTS_MISSING\",\n \"MODEL_TOOL_CALL_ARGUMENTS_NULL\", \"MODEL_TOOL_CALL_ARGUMENTS_NOT_OBJECT\",\n \"MODEL_TEXT_NOT_STRING\", \"MODEL_TEXT_TOO_LONG\",\n \"MODEL_STEP_TOO_LARGE\", \"MODEL_STEP_NOT_SERIALIZABLE\", \"MODEL_STEP_VALIDATION_FAILED\",\n \"MODEL_CALL_ROUTE_INVALID\", \"MODEL_RESULT_MISSING\",\n \"REQUEST_INVALID\", \"MODEL_REQUEST_HISTORY_INVALID\", \"MODEL_REQUEST_TOOL_RESULT_INVALID\",\n \"MODEL_CONFIGURATION_INVALID\", \"MODEL_CREDENTIAL_INVALID\", \"MODEL_ADAPTER_INITIALIZATION_FAILED\",\n \"MODEL_REQUEST_CANCELLED\", \"TOOL_BIND_FAILED\", \"PROVIDER_AUTH_FAILED\", \"PROVIDER_RATE_LIMITED\",\n \"PROVIDER_HTTP_ERROR\", \"PROVIDER_REQUEST_FAILED\", \"PROVIDER_RESPONSE_INVALID\",\n \"PROVIDER_RESPONSE_USAGE_INVALID\", \"PROVIDER_RESPONSE_TOOL_CALL_INVALID\",\n \"TOOL_DESCRIPTOR_MISMATCH\", \"TOOL_AUTHORIZATION_FAILED\", \"TOOL_INPUT_INVALID\",\n \"TOOL_CALL_BUDGET_EXHAUSTED\", \"TOOL_EXECUTION_FAILED\", \"TOOL_RESULT_TOO_LARGE\",\n \"TOOL_RESULT_INVALID\", \"TOOL_RESULT_MISSING\", \"TOOL_STALE_TURN\",\n \"EVIDENCE_INVALID\", \"FINAL_SCHEMA_INVALID\", \"FINAL_LANGUAGE_MISMATCH\",\n \"FINAL_REFERRAL_REQUIRED\", \"FINAL_EVIDENCE_INVALID\", \"FINAL_EVIDENCE_EXPIRED\",\n \"EVIDENCE_RESERVATION_EXCEEDED\",\n] as const;\nexport type RunnerDiagnosticReason = typeof RUNNER_DIAGNOSTIC_REASONS[number];\n\n/** Recognised transport failures, never arbitrary OS/provider error codes. */\nexport const RUNNER_TRANSPORT_CODES = [\n \"ENOTFOUND\", \"EAI_AGAIN\", \"ECONNREFUSED\", \"ECONNRESET\", \"ETIMEDOUT\",\n \"ENETUNREACH\", \"EHOSTUNREACH\", \"EPIPE\", \"UND_ERR_CONNECT_TIMEOUT\",\n \"UND_ERR_HEADERS_TIMEOUT\", \"UND_ERR_SOCKET\", \"CERT_HAS_EXPIRED\",\n \"UNABLE_TO_VERIFY_LEAF_SIGNATURE\", \"DEPTH_ZERO_SELF_SIGNED_CERT\",\n \"ERR_TLS_CERT_ALTNAME_INVALID\",\n] as const;\nexport type RunnerTransportCode = typeof RUNNER_TRANSPORT_CODES[number];\n\nconst recognizedExceptionNames = new Set([\n \"TypeError\", \"ReferenceError\", \"SyntaxError\", \"RangeError\", \"URIError\",\n \"EvalError\", \"AggregateError\", \"AbortError\", \"TimeoutError\",\n]);\nconst recognizedTransportCodes = new Set<string>(RUNNER_TRANSPORT_CODES);\n\n\n/** All optional fields are allowlisted; never include free-form provider or exception text. */\nexport type RunnerDiagnostic = Readonly<{\n stage: RunnerDiagnosticStage;\n reasonCode: RunnerDiagnosticReason;\n /** Fixed, safe operator explanation; computed from the validated code and detail. */\n reasonMessage?: string;\n /** Fixed, safe next step for the operator; never provider-supplied. */\n operatorAction?: string;\n /** Transport/exception details are from a fixed allowlist, not error.message. */\n transportCode?: RunnerTransportCode;\n exceptionName?: string;\n statusCode?: number;\n providerCode?: number;\n providerStage?: \"request\" | \"binding\" | \"provider\" | \"response\";\n modelStep?: number;\n /** Zero-based index for a rejected tool call. Never includes user content. */\n callIndex?: number;\n remoteCallNumber?: number;\n attempt?: number;\n toolName?: string;\n issueCount?: number;\n issueCodes?: readonly string[];\n issuePaths?: readonly string[];\n}>;\n\nconst stages = new Set<string>(RUNNER_DIAGNOSTIC_STAGES);\nconst reasons = new Set<string>(RUNNER_DIAGNOSTIC_REASONS);\nconst issueCodes = new Set([\n \"invalid_type\", \"too_big\", \"too_small\", \"invalid_format\", \"invalid_value\",\n \"unrecognized_keys\", \"invalid_union\", \"invalid_key\", \"invalid_element\", \"custom\",\n]);\nconst knownPathParts = new Set([\n \"turn\", \"grant\", \"manifest\", \"shopId\", \"conversationId\", \"checkoutRecoveryId\",\n \"inboundVersion\", \"initialInboundVersion\", \"id\", \"releaseId\", \"responseContract\",\n \"responseContractHash\", \"runnerCompatibility\", \"grantedTools\", \"capabilities\",\n \"featureBehaviours\", \"language\", \"tag\", \"source\", \"budget\", \"modelSteps\",\n \"remoteCalls\", \"deadlineMs\", \"outputTokens\", \"history\", \"context\", \"instructions\",\n \"answerKind\", \"referralReason\", \"replyText\", \"detectedLanguageTag\", \"evidenceIds\",\n \"details\", \"contractVersion\", \"status\", \"data\", \"renderedText\", \"calls\",\n \"name\", \"arguments\", \"toolName\", \"toolId\", \"toolRevisionId\", \"definitionVersion\",\n]);\n\nfunction boundedInt(value: unknown, minimum: number, maximum: number): number | undefined {\n return Number.isSafeInteger(value) && (value as number) >= minimum && (value as number) <= maximum\n ? value as number\n : undefined;\n}\n\n/** Also sanitize internally constructed diagnostics before exposing them to hosts or logs. */\nexport function safeRunnerDiagnostic(diagnostic: RunnerDiagnostic): RunnerDiagnostic {\n const fields: RunnerDiagnostic = {\n stage: stages.has(diagnostic.stage) ? diagnostic.stage : \"graph.execute\",\n reasonCode: reasons.has(diagnostic.reasonCode) ? diagnostic.reasonCode : \"UNEXPECTED_EXCEPTION\",\n ...(recognizedTransportCodes.has(diagnostic.transportCode ?? \"\") ? { transportCode: diagnostic.transportCode } : {}),\n ...(recognizedExceptionNames.has(diagnostic.exceptionName ?? \"\") ? { exceptionName: diagnostic.exceptionName } : {}),\n ...(boundedInt(diagnostic.statusCode, 100, 599) === undefined ? {} : { statusCode: diagnostic.statusCode }),\n ...(boundedInt(diagnostic.providerCode, 0, 999999) === undefined ? {} : { providerCode: diagnostic.providerCode }),\n ...([\"request\", \"binding\", \"provider\", \"response\"].includes(diagnostic.providerStage ?? \"\")\n ? { providerStage: diagnostic.providerStage } : {}),\n ...(boundedInt(diagnostic.modelStep, 1, 12) === undefined ? {} : { modelStep: diagnostic.modelStep }),\n ...(boundedInt(diagnostic.callIndex, 0, 31) === undefined ? {} : { callIndex: diagnostic.callIndex }),\n ...(boundedInt(diagnostic.remoteCallNumber, 1, 10) === undefined ? {} : { remoteCallNumber: diagnostic.remoteCallNumber }),\n ...(boundedInt(diagnostic.attempt, 1, 2) === undefined ? {} : { attempt: diagnostic.attempt }),\n ...(typeof diagnostic.toolName === \"string\" && /^[a-z][a-z0-9_]{0,127}$/.test(diagnostic.toolName)\n ? { toolName: diagnostic.toolName } : {}),\n ...(boundedInt(diagnostic.issueCount, 0, 10000) === undefined ? {} : { issueCount: diagnostic.issueCount }),\n ...(Array.isArray(diagnostic.issueCodes) ? {\n issueCodes: [...new Set(diagnostic.issueCodes.filter((code) => issueCodes.has(code)))].slice(0, 5),\n } : {}),\n ...(Array.isArray(diagnostic.issuePaths) ? {\n issuePaths: [...new Set(diagnostic.issuePaths.filter((path) =>\n typeof path === \"string\" && path.length <= 80 && path.split(\".\").every((part) => knownPathParts.has(part)),\n ))].slice(0, 5),\n } : {}),\n };\n const explanation = describeRunnerDiagnostic(fields);\n return Object.freeze({ ...fields, reasonMessage: explanation.message, operatorAction: explanation.action });\n}\n\n/** Extract only known error names and network codes from a bounded cause chain. */\nexport function safeRunnerCauseMetadata(error: unknown): Pick<RunnerDiagnostic, \"transportCode\" | \"exceptionName\"> {\n const visited = new Set<unknown>();\n let current = error;\n let transportCode: RunnerTransportCode | undefined;\n let exceptionName: string | undefined;\n for (let depth = 0; depth < 6 && current instanceof Error && !visited.has(current); depth += 1) {\n visited.add(current);\n try {\n const code = (current as Error & { code?: unknown }).code;\n if (typeof code === \"string\" && recognizedTransportCodes.has(code))\n transportCode = code as RunnerTransportCode;\n if (!exceptionName && recognizedExceptionNames.has(current.name)) exceptionName = current.name;\n current = current.cause;\n } catch {\n break; // A hostile error object/getter must not interrupt the original failure path.\n }\n }\n return {\n ...(transportCode ? { transportCode } : {}),\n ...(exceptionName ? { exceptionName } : {}),\n };\n}\n\n/** Only static schema keys and Zod's finite issue-code vocabulary may leave this boundary. */\nexport function schemaIssueMetadata(error: ZodError): Pick<RunnerDiagnostic, \"issueCount\" | \"issueCodes\" | \"issuePaths\"> {\n const paths = error.issues.map((issue) =>\n issue.path.filter((part): part is string => typeof part === \"string\")\n .filter((part) => knownPathParts.has(part)).slice(0, 3).join(\".\"),\n ).filter(Boolean);\n return {\n issueCount: Math.min(error.issues.length, 10000),\n issueCodes: [...new Set(error.issues.map((issue) => issue.code).filter((code) => issueCodes.has(code)))].slice(0, 5),\n issuePaths: [...new Set(paths)].slice(0, 5),\n };\n}\n","import type { RunCommerceTurnInput, RunnerErrorCode, RunCommerceTurnResult } from \"./types.js\";\nimport { safeRunnerCauseMetadata, safeRunnerDiagnostic, type RunnerDiagnostic, type RunnerDiagnosticStage } from \"./diagnostics.js\";\n\nexport class RunnerFailure extends Error {\n readonly diagnostic: RunnerDiagnostic;\n\n constructor(readonly code: RunnerErrorCode, diagnostic: RunnerDiagnostic, cause?: unknown) {\n super(code, { cause });\n this.name = \"RunnerFailure\";\n this.diagnostic = safeRunnerDiagnostic({ ...safeRunnerCauseMetadata(cause), ...diagnostic });\n }\n}\n\n/** Typed, provider-independent cause that model invokers may throw. */\nexport class CommerceModelInvocationFailure extends Error {\n readonly diagnostic: RunnerDiagnostic;\n\n constructor(diagnostic: RunnerDiagnostic, cause?: unknown) {\n super(\"Commerce model unavailable\", { cause });\n this.name = \"CommerceModelInvocationFailure\";\n this.diagnostic = safeRunnerDiagnostic({ ...safeRunnerCauseMetadata(cause), ...diagnostic });\n }\n}\n\nfunction findRunnerFailure(error: unknown): RunnerFailure | undefined {\n const visited = new Set<unknown>();\n let current = error;\n for (let depth = 0; depth < 6 && current instanceof Error && !visited.has(current); depth += 1) {\n visited.add(current);\n if (current instanceof RunnerFailure) return current;\n current = current.cause;\n }\n return undefined;\n}\n\nexport function mapRunnerFailure(\n error: unknown, signal?: AbortSignal, fallbackStage: RunnerDiagnosticStage = \"graph.execute\",\n): RunCommerceTurnResult {\n const failure = findRunnerFailure(error);\n const code = failure?.code ?? (signal?.aborted ? \"CANCELLED\" : \"INVALID_INPUT\");\n const diagnostic = failure?.diagnostic ?? safeRunnerDiagnostic(signal?.aborted\n ? { stage: \"runtime.cancellation\", reasonCode: \"CANCELLED_BY_CALLER\" }\n : { stage: fallbackStage, reasonCode: \"UNEXPECTED_EXCEPTION\", ...safeRunnerCauseMetadata(error) });\n return {\n ok: false,\n error: { code, retryable: code === \"UNAVAILABLE\" || code === \"DEADLINE\", diagnostic },\n };\n}\n\nexport function failureCode(error: unknown): RunnerErrorCode {\n return findRunnerFailure(error)?.code ?? \"INVALID_INPUT\";\n}\n\nexport function inputSignal(input: RunCommerceTurnInput): AbortSignal {\n return input.signal;\n}\n"],"mappings":";AAKA,IAAM,eAAe;AAAA,EACnB,+BAA+B,CAAC,4EAA4E,wFAAwF;AAAA,EACpM,qBAAqB,CAAC,yDAAyD,8DAA8D;AAAA,EAC7I,wBAAwB,CAAC,wDAAw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