@oxy.so/contracts 4.6.0 → 4.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.normalizedAppEventSchema = exports.catalogRegistrationSchema = exports.appCapabilityCatalogSchema = exports.catalogEventSchema = exports.catalogToolSchema = exports.auditEventSchema = exports.auditResultSchema = exports.policyDecisionSchema = exports.capabilityTicketClaimsSchema = exports.automationDefinitionSchema = exports.automationDataFlowSchema = exports.automationActorSelectionSchema = exports.automationTriggerSchema = exports.delegationGrantSchema = exports.capabilityCoordinatorSchema = exports.executionAuthorizationRefSchema = exports.capabilityCatalogBindingSchema = exports.grantLimitSchema = exports.toolGrantOverrideSchema = exports.resourceRefSchema = exports.actorRefSchema = exports.capabilityPackageSchema = exports.CAPABILITY_PACKAGES = exports.autonomyLevelSchema = exports.AUTONOMY_LEVELS = void 0;
4
4
  const zod_1 = require("zod");
5
+ const capabilityInvocation_1 = require("./capabilityInvocation");
5
6
  const nonEmptyStringSchema = zod_1.z.string().trim().min(1);
6
7
  const identifierSchema = zod_1.z.string().trim().min(1).max(255);
7
8
  const limitKeySchema = zod_1.z.string().regex(/^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)*$/, 'limit keys must be dot-separated input property names').max(255);
@@ -349,6 +350,42 @@ exports.catalogToolSchema = zod_1.z.object({
349
350
  path: ['invocation', 'method'],
350
351
  });
351
352
  }
353
+ // The invocation template is how a coordinator turns arguments into a
354
+ // request (`resolveCatalogInvocation`). A `{param}` the input schema does
355
+ // not declare as a REQUIRED property can never be filled, and a GET input
356
+ // that is not a scalar has no query-string form — both are refused here so
357
+ // the builder never has to guess.
358
+ const declared = typeof tool.inputSchema.properties === 'object'
359
+ && tool.inputSchema.properties !== null
360
+ && !Array.isArray(tool.inputSchema.properties)
361
+ ? tool.inputSchema.properties
362
+ : {};
363
+ const required = Array.isArray(tool.inputSchema.required) ? tool.inputSchema.required : [];
364
+ const parameters = (0, capabilityInvocation_1.catalogInvocationPathParameters)(tool.invocation.path);
365
+ requireUnique(parameters, 'invocation.path parameters');
366
+ for (const parameter of parameters) {
367
+ if (!Object.prototype.hasOwnProperty.call(declared, parameter) || !required.includes(parameter)) {
368
+ context.addIssue({
369
+ code: zod_1.z.ZodIssueCode.custom,
370
+ message: `Path parameter {${parameter}} must be a required input property`,
371
+ path: ['invocation', 'path'],
372
+ });
373
+ }
374
+ }
375
+ if (tool.invocation.method === 'GET') {
376
+ for (const [key, property] of Object.entries(declared)) {
377
+ const type = typeof property === 'object' && property !== null
378
+ ? property.type
379
+ : undefined;
380
+ if (type !== 'string' && type !== 'number' && type !== 'integer' && type !== 'boolean') {
381
+ context.addIssue({
382
+ code: zod_1.z.ZodIssueCode.custom,
383
+ message: `GET input ${key} must be a string, number, integer or boolean`,
384
+ path: ['inputSchema', 'properties', key],
385
+ });
386
+ }
387
+ }
388
+ }
352
389
  });
353
390
  exports.catalogEventSchema = zod_1.z.object({
354
391
  type: identifierSchema,
@@ -416,6 +453,18 @@ exports.appCapabilityCatalogSchema = zod_1.z.object({
416
453
  }
417
454
  names.add(tool.name);
418
455
  }
456
+ // Matching an incoming request back to its tool must have ONE answer that
457
+ // does not depend on the order tools are listed in — see
458
+ // `matchCatalogInvocation`. Two templates that one request could satisfy
459
+ // (`/messages/{id}` beside `/messages/unread`) make that impossible.
460
+ for (const [left, right] of (0, capabilityInvocation_1.findOverlappingCatalogInvocations)(catalog.tools)) {
461
+ context.addIssue({
462
+ code: zod_1.z.ZodIssueCode.custom,
463
+ message: `Tools ${left.name} and ${right.name} have overlapping invocations `
464
+ + `(${left.invocation.method} ${left.invocation.path} / ${right.invocation.method} ${right.invocation.path})`,
465
+ path: ['tools'],
466
+ });
467
+ }
419
468
  const eventTypes = new Set();
420
469
  for (const [index, event] of catalog.events.entries()) {
421
470
  if (eventTypes.has(event.type)) {
@@ -0,0 +1,173 @@
1
+ "use strict";
2
+ /**
3
+ * How a catalog tool call travels over HTTP, in both directions.
4
+ *
5
+ * A capability catalog names each tool's `invocation` as a method plus a path
6
+ * template (`/email/messages/{emailId}`). Two parties have to agree on what
7
+ * that means: the coordinator that BUILDS the request from the model's
8
+ * arguments (Alia), and the app that MATCHES an incoming request back to the
9
+ * one tool its ticket was signed for (the Inbox capability middleware). Each
10
+ * used to carry its own copy of the rules, and the matcher walked the tool list
11
+ * in array order, so a literal segment (`/messages/unread`) and a parameter
12
+ * (`/messages/{id}`) in the same position resolved to whichever tool happened to
13
+ * be declared first. Both halves live here now, next to the catalog schema that
14
+ * refuses a catalog whose templates could ever match the same request — so a
15
+ * match is unique by construction, not by ordering.
16
+ */
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.catalogInvocationPathParameters = catalogInvocationPathParameters;
19
+ exports.catalogInvocationsOverlap = catalogInvocationsOverlap;
20
+ exports.catalogInvocationTemplatesEquivalent = catalogInvocationTemplatesEquivalent;
21
+ exports.findOverlappingCatalogInvocations = findOverlappingCatalogInvocations;
22
+ exports.matchCatalogInvocation = matchCatalogInvocation;
23
+ exports.resolveCatalogInvocation = resolveCatalogInvocation;
24
+ const PARAMETER_SEGMENT = /^\{([A-Za-z][A-Za-z0-9_]*)\}$/;
25
+ function pathSegments(path) {
26
+ return path.split('/').filter(Boolean);
27
+ }
28
+ /** The `{name}` placeholders of a path template, in order. */
29
+ function catalogInvocationPathParameters(path) {
30
+ return pathSegments(path).flatMap((segment) => {
31
+ const parameter = PARAMETER_SEGMENT.exec(segment)?.[1];
32
+ return parameter ? [parameter] : [];
33
+ });
34
+ }
35
+ /**
36
+ * Whether one concrete request could match BOTH templates.
37
+ *
38
+ * Same method, same number of segments, and at every position either the same
39
+ * literal or a parameter on at least one side. `/messages/{id}` and
40
+ * `/messages/unread` overlap (the request `/messages/unread` fits both);
41
+ * `/messages/{id}` and `/messages/{id}/thread` do not.
42
+ */
43
+ function catalogInvocationsOverlap(left, right) {
44
+ if (left.method.toUpperCase() !== right.method.toUpperCase())
45
+ return false;
46
+ const leftSegments = pathSegments(left.path);
47
+ const rightSegments = pathSegments(right.path);
48
+ if (leftSegments.length !== rightSegments.length)
49
+ return false;
50
+ return leftSegments.every((segment, index) => {
51
+ const other = rightSegments[index] ?? '';
52
+ return segment === other || PARAMETER_SEGMENT.test(segment) || PARAMETER_SEGMENT.test(other);
53
+ });
54
+ }
55
+ /**
56
+ * Whether two templates name the same ADDRESS: same method, and at every
57
+ * position the same literal or a parameter on both sides — parameter names do
58
+ * not matter (`/messages/{id}` and `/messages/{emailId}` are one address;
59
+ * `/messages/{id}` and `/messages/bundled` are not, though they overlap).
60
+ * Used to say which documented REST operation shares its address with a tool.
61
+ */
62
+ function catalogInvocationTemplatesEquivalent(left, right) {
63
+ if (left.method.toUpperCase() !== right.method.toUpperCase())
64
+ return false;
65
+ const leftSegments = pathSegments(left.path);
66
+ const rightSegments = pathSegments(right.path);
67
+ if (leftSegments.length !== rightSegments.length)
68
+ return false;
69
+ return leftSegments.every((segment, index) => {
70
+ const other = rightSegments[index] ?? '';
71
+ const leftIsParameter = PARAMETER_SEGMENT.test(segment);
72
+ return leftIsParameter ? PARAMETER_SEGMENT.test(other) : segment === other;
73
+ });
74
+ }
75
+ /** Every pair of tools whose invocations overlap — empty for a valid catalog. */
76
+ function findOverlappingCatalogInvocations(tools) {
77
+ const overlaps = [];
78
+ for (let left = 0; left < tools.length; left += 1) {
79
+ for (let right = left + 1; right < tools.length; right += 1) {
80
+ const a = tools[left];
81
+ const b = tools[right];
82
+ if (a && b && catalogInvocationsOverlap(a.invocation, b.invocation))
83
+ overlaps.push([a, b]);
84
+ }
85
+ }
86
+ return overlaps;
87
+ }
88
+ function matchTemplate(template, method, requestSegments) {
89
+ if (template.method.toUpperCase() !== method.toUpperCase())
90
+ return null;
91
+ const templateSegments = pathSegments(template.path);
92
+ if (templateSegments.length !== requestSegments.length)
93
+ return null;
94
+ const params = {};
95
+ for (const [index, templateSegment] of templateSegments.entries()) {
96
+ const requestSegment = requestSegments[index];
97
+ if (!requestSegment)
98
+ return null;
99
+ const parameter = PARAMETER_SEGMENT.exec(templateSegment)?.[1];
100
+ if (!parameter) {
101
+ if (templateSegment !== requestSegment)
102
+ return null;
103
+ continue;
104
+ }
105
+ try {
106
+ params[parameter] = decodeURIComponent(requestSegment);
107
+ }
108
+ catch {
109
+ return null;
110
+ }
111
+ }
112
+ return params;
113
+ }
114
+ /**
115
+ * The ONE tool whose invocation matches `method` + `path` (the full app-local
116
+ * path, e.g. `/email/messages/abc`), or null.
117
+ *
118
+ * Every tool is tried, not the first hit, so the answer cannot depend on the
119
+ * order the catalog lists its tools in. A second hit means the catalog should
120
+ * never have validated — `appCapabilityCatalogSchema` refuses overlapping
121
+ * templates — so it throws rather than guessing which tool the ticket meant.
122
+ */
123
+ function matchCatalogInvocation(tools, method, path) {
124
+ const requestSegments = pathSegments(path);
125
+ const matches = [];
126
+ for (const tool of tools) {
127
+ const params = matchTemplate(tool.invocation, method, requestSegments);
128
+ if (params)
129
+ matches.push({ tool, params });
130
+ }
131
+ if (matches.length > 1) {
132
+ throw new Error(`Ambiguous catalog invocation ${method} ${path}: ${matches.map(({ tool }) => tool.name).join(', ')}`);
133
+ }
134
+ return matches[0] ?? null;
135
+ }
136
+ /**
137
+ * Build the HTTP request for a tool call from the model's arguments.
138
+ *
139
+ * Path parameters are substituted (and removed from the remaining arguments);
140
+ * GET sends the rest as query parameters, everything else as a JSON body. A GET
141
+ * argument that is not a scalar is refused instead of being stringified into
142
+ * `[object Object]` — the catalog schema only lets GET tools declare scalar
143
+ * inputs, so reaching that branch means the arguments did not come from the
144
+ * tool's own schema. The resolved URL must stay on `internalBaseUrl`'s origin.
145
+ */
146
+ function resolveCatalogInvocation(catalog, tool, args) {
147
+ const remaining = { ...args };
148
+ const path = tool.invocation.path.replace(/\{(\w+)\}/g, (_match, parameter) => {
149
+ const value = Object.prototype.hasOwnProperty.call(remaining, parameter) ? remaining[parameter] : undefined;
150
+ delete remaining[parameter];
151
+ if (value === undefined || value === null || value === '') {
152
+ throw new Error(`Missing required path parameter: ${parameter}`);
153
+ }
154
+ return encodeURIComponent(String(value));
155
+ });
156
+ const baseUrl = new URL(catalog.internalBaseUrl);
157
+ const url = new URL(path, `${baseUrl.origin}/`);
158
+ if (url.origin !== baseUrl.origin) {
159
+ throw new Error(`Catalog invocation for ${tool.name} escapes its registered app origin`);
160
+ }
161
+ const method = tool.invocation.method.toUpperCase();
162
+ if (method !== 'GET')
163
+ return { method, url, body: remaining };
164
+ for (const [key, value] of Object.entries(remaining)) {
165
+ if (value === undefined || value === null)
166
+ continue;
167
+ if (typeof value !== 'string' && typeof value !== 'number' && typeof value !== 'boolean') {
168
+ throw new Error(`GET argument ${key} of ${tool.name} must be a string, number or boolean`);
169
+ }
170
+ url.searchParams.set(key, String(value));
171
+ }
172
+ return { method, url };
173
+ }
package/dist/cjs/index.js CHANGED
@@ -37,7 +37,7 @@ exports.MAX_REALTIME_AUDIO_FRAME_BASE64_LENGTH = exports.inferenceStreamEventSch
37
37
  exports.realtimeTextDeltaEventSchema = exports.realtimeTranscriptDoneEventSchema = exports.realtimeTranscriptDeltaEventSchema = exports.realtimeTranscriptSourceSchema = exports.realtimeOutputAudioDoneEventSchema = exports.realtimeOutputAudioDeltaEventSchema = exports.realtimeResponseCreatedEventSchema = exports.realtimeInputAudioClearedEventSchema = exports.realtimeInputAudioCommittedEventSchema = exports.realtimeSpeechStoppedEventSchema = exports.realtimeSpeechStartedEventSchema = exports.realtimeItemTruncatedEventSchema = exports.realtimeItemDeletedEventSchema = exports.realtimeItemDoneEventSchema = exports.realtimeItemAddedEventSchema = exports.realtimeCommandAcceptedEventSchema = exports.realtimeSessionResumedEventSchema = exports.realtimeSessionUpdatedEventSchema = exports.realtimeSessionCreatedEventSchema = exports.realtimeClientCommandSchema = exports.realtimeSessionCloseCommandSchema = exports.realtimeSessionResumeCommandSchema = exports.realtimeResponseCancelCommandSchema = exports.realtimeResponseCreateCommandSchema = exports.realtimeInputAudioClearCommandSchema = exports.realtimeInputAudioCommitCommandSchema = exports.realtimeInputAudioAppendCommandSchema = exports.realtimeItemTruncateCommandSchema = exports.realtimeItemDeleteCommandSchema = exports.realtimeItemCreateCommandSchema = exports.realtimeSessionUpdateCommandSchema = exports.realtimeResponseParametersSchema = exports.realtimeConversationItemSchema = exports.realtimeContentPartSchema = exports.realtimeSessionRequestSchema = exports.realtimeClientMetadataSchema = exports.realtimeSessionLimitsSchema = exports.realtimeSessionConfigUpdateSchema = exports.realtimeSessionConfigSchema = exports.realtimeTranslationSchema = exports.realtimeInputTranscriptionSchema = exports.realtimeTurnDetectionSchema = exports.realtimeOutputModalitySchema = exports.realtimeAudioFormatSchema = exports.realtimeResponseIdSchema = exports.realtimeItemIdSchema = exports.realtimeCommandIdSchema = exports.MAX_REALTIME_RESUME_WINDOW_MS = exports.MAX_REALTIME_SESSION_AUDIO_BYTES = exports.MAX_REALTIME_SESSION_DURATION_MS = void 0;
38
38
  exports.BILLING_INVOICE_STATUSES = exports.accountBillingStateSchema = exports.billingProfileSchema = exports.autoRechargeSchema = exports.billingProfileStatusSchema = exports.BILLING_PROFILE_STATUSES = exports.billingModeSchema = exports.BILLING_MODES = exports.providerConnectionSchema = exports.providerConnectionStatusSchema = exports.providerConnectionValidationSchema = exports.providerCredentialCustodyStateSchema = exports.providerCredentialValidationDeploymentSchema = exports.providerCredentialValidationOperationSchema = exports.kaanaCredentialValidationOutcomeSchema = exports.kaanaCredentialValidationFailureCodeSchema = exports.kaanaCredentialValidationOutcomeStateSchema = exports.kaanaCredentialValidationTaskSchema = exports.kaanaCredentialOutcomeSchema = exports.kaanaCredentialConflictOutcomeSchema = exports.kaanaCredentialAppliedOutcomeSchema = exports.kaanaCredentialOutcomeRequestSchema = exports.kaanaCredentialRevokeOutcomeRequestSchema = exports.kaanaCredentialRotateOutcomeRequestSchema = exports.kaanaCredentialCreateOutcomeRequestSchema = exports.kaanaCredentialMutationSchema = exports.kaanaCredentialRevokeMutationSchema = exports.kaanaCredentialRotateMutationSchema = exports.kaanaCredentialCreateMutationSchema = exports.kaanaCredentialIdentitySchema = exports.kaanaCredentialOperationActionSchema = exports.kaanaCredentialOperationIdSchema = exports.kaanaCredentialHandleSchema = exports.providerConnectionScopeSchema = exports.usageRefundSchema = exports.usageRefundReasonSchema = exports.usageRefundSubjectSchema = exports.usageReceiptSchema = exports.normalizedUsageReportSchema = exports.inferenceRequestOutcomeSchema = exports.usageReservationSchema = exports.usageReservationStatusSchema = exports.usageReservationRequestSchema = exports.realtimeServerEventSchema = exports.realtimeSessionClosedEventSchema = exports.realtimeSessionCloseReasonSchema = exports.realtimeErrorEventSchema = exports.realtimeResponseDoneEventSchema = exports.realtimeResponseStatusSchema = exports.realtimeToolCallEventSchema = void 0;
39
39
  exports.catalogEventSchema = exports.catalogToolSchema = exports.auditEventSchema = exports.auditResultSchema = exports.policyDecisionSchema = exports.capabilityTicketClaimsSchema = exports.automationDefinitionSchema = exports.automationDataFlowSchema = exports.automationActorSelectionSchema = exports.automationTriggerSchema = exports.delegationGrantSchema = exports.capabilityCoordinatorSchema = exports.executionAuthorizationRefSchema = exports.capabilityCatalogBindingSchema = exports.grantLimitSchema = exports.toolGrantOverrideSchema = exports.resourceRefSchema = exports.actorRefSchema = exports.capabilityPackageSchema = exports.autonomyLevelSchema = exports.CAPABILITY_PACKAGES = exports.AUTONOMY_LEVELS = exports.productEntitlementSchema = exports.costCenterSpendSchema = exports.costCenterSchema = exports.costCenterStatusSchema = exports.COST_CENTER_STATUSES = exports.payAsYouGoEntitlementSchema = exports.productPlanSchema = exports.planAllowanceSchema = exports.LIVE_PRODUCT_PLAN_STATUSES = exports.productPlanStatusSchema = exports.PRODUCT_PLAN_STATUSES = exports.reconciliationReportSchema = exports.reconciliationRunSchema = exports.reconciliationDiscrepancySchema = exports.reconciliationRunStatusSchema = exports.RECONCILIATION_RUN_STATUSES = exports.reconciliationDiscrepancyKindSchema = exports.RECONCILIATION_DISCREPANCY_KINDS = exports.autoRechargeAttemptSchema = exports.autoRechargeStatusSchema = exports.AUTO_RECHARGE_STATUSES = exports.externalPaymentSchema = exports.externalPaymentKindSchema = exports.EXTERNAL_PAYMENT_KINDS = exports.externalPaymentProviderSchema = exports.EXTERNAL_PAYMENT_PROVIDERS = exports.billingInvoiceSchema = exports.billingInvoiceStatusSchema = void 0;
40
- exports.inboxInferenceStreamEventSchema = exports.inboxThreadSummaryResponseSchema = exports.inboxSmartRepliesResponseSchema = exports.inboxNaturalSearchResponseSchema = exports.inboxInferenceTextResponseSchema = exports.inboxMessageInferenceParamsSchema = exports.inboxNaturalSearchRequestSchema = exports.inboxDailyBriefRequestSchema = exports.inboxComposeRequestSchema = exports.emailAgentContextSchema = exports.emailContextMessageSchema = exports.emailContextMailboxSchema = exports.emailContextAddressSchema = exports.normalizedAppEventSchema = exports.catalogRegistrationSchema = exports.appCapabilityCatalogSchema = void 0;
40
+ exports.decisionAnswersMatch = exports.decisionFitsGateway = exports.decisionInputBudget = exports.decisionFailureSchema = exports.decisionSuccessSchema = exports.decisionResultSchema = exports.decisionAnswerSchema = exports.decisionRequestSchema = exports.decisionInputSchema = exports.decisionQuestionSchema = exports.decisionEffortSchema = exports.inboxInferenceStreamEventSchema = exports.inboxThreadSummaryResponseSchema = exports.inboxSmartRepliesResponseSchema = exports.inboxNaturalSearchResponseSchema = exports.inboxInferenceTextResponseSchema = exports.inboxMessageInferenceParamsSchema = exports.inboxNaturalSearchRequestSchema = exports.inboxDailyBriefRequestSchema = exports.inboxComposeRequestSchema = exports.emailAgentContextSchema = exports.emailContextMessageSchema = exports.emailContextMailboxSchema = exports.emailContextAddressSchema = exports.resolveCatalogInvocation = exports.matchCatalogInvocation = exports.findOverlappingCatalogInvocations = exports.catalogInvocationTemplatesEquivalent = exports.catalogInvocationsOverlap = exports.catalogInvocationPathParameters = exports.normalizedAppEventSchema = exports.catalogRegistrationSchema = exports.appCapabilityCatalogSchema = void 0;
41
41
  var accountGraph_1 = require("./accountGraph");
42
42
  Object.defineProperty(exports, "ACCOUNT_KINDS", { enumerable: true, get: function () { return accountGraph_1.ACCOUNT_KINDS; } });
43
43
  Object.defineProperty(exports, "accountKindSchema", { enumerable: true, get: function () { return accountGraph_1.accountKindSchema; } });
@@ -753,6 +753,13 @@ Object.defineProperty(exports, "catalogEventSchema", { enumerable: true, get: fu
753
753
  Object.defineProperty(exports, "appCapabilityCatalogSchema", { enumerable: true, get: function () { return agency_1.appCapabilityCatalogSchema; } });
754
754
  Object.defineProperty(exports, "catalogRegistrationSchema", { enumerable: true, get: function () { return agency_1.catalogRegistrationSchema; } });
755
755
  Object.defineProperty(exports, "normalizedAppEventSchema", { enumerable: true, get: function () { return agency_1.normalizedAppEventSchema; } });
756
+ var capabilityInvocation_1 = require("./capabilityInvocation");
757
+ Object.defineProperty(exports, "catalogInvocationPathParameters", { enumerable: true, get: function () { return capabilityInvocation_1.catalogInvocationPathParameters; } });
758
+ Object.defineProperty(exports, "catalogInvocationsOverlap", { enumerable: true, get: function () { return capabilityInvocation_1.catalogInvocationsOverlap; } });
759
+ Object.defineProperty(exports, "catalogInvocationTemplatesEquivalent", { enumerable: true, get: function () { return capabilityInvocation_1.catalogInvocationTemplatesEquivalent; } });
760
+ Object.defineProperty(exports, "findOverlappingCatalogInvocations", { enumerable: true, get: function () { return capabilityInvocation_1.findOverlappingCatalogInvocations; } });
761
+ Object.defineProperty(exports, "matchCatalogInvocation", { enumerable: true, get: function () { return capabilityInvocation_1.matchCatalogInvocation; } });
762
+ Object.defineProperty(exports, "resolveCatalogInvocation", { enumerable: true, get: function () { return capabilityInvocation_1.resolveCatalogInvocation; } });
756
763
  var emailAgentContext_1 = require("./emailAgentContext");
757
764
  Object.defineProperty(exports, "emailContextAddressSchema", { enumerable: true, get: function () { return emailAgentContext_1.emailContextAddressSchema; } });
758
765
  Object.defineProperty(exports, "emailContextMailboxSchema", { enumerable: true, get: function () { return emailAgentContext_1.emailContextMailboxSchema; } });
@@ -774,3 +781,15 @@ __exportStar(require("./federationInstanceFetch"), exports);
774
781
  __exportStar(require("./notifications"), exports);
775
782
  __exportStar(require("./email/messages"), exports);
776
783
  __exportStar(require("./stickers"), exports);
784
+ var decisions_1 = require("./inference/decisions");
785
+ Object.defineProperty(exports, "decisionEffortSchema", { enumerable: true, get: function () { return decisions_1.decisionEffortSchema; } });
786
+ Object.defineProperty(exports, "decisionQuestionSchema", { enumerable: true, get: function () { return decisions_1.decisionQuestionSchema; } });
787
+ Object.defineProperty(exports, "decisionInputSchema", { enumerable: true, get: function () { return decisions_1.decisionInputSchema; } });
788
+ Object.defineProperty(exports, "decisionRequestSchema", { enumerable: true, get: function () { return decisions_1.decisionRequestSchema; } });
789
+ Object.defineProperty(exports, "decisionAnswerSchema", { enumerable: true, get: function () { return decisions_1.decisionAnswerSchema; } });
790
+ Object.defineProperty(exports, "decisionResultSchema", { enumerable: true, get: function () { return decisions_1.decisionResultSchema; } });
791
+ Object.defineProperty(exports, "decisionSuccessSchema", { enumerable: true, get: function () { return decisions_1.decisionSuccessSchema; } });
792
+ Object.defineProperty(exports, "decisionFailureSchema", { enumerable: true, get: function () { return decisions_1.decisionFailureSchema; } });
793
+ Object.defineProperty(exports, "decisionInputBudget", { enumerable: true, get: function () { return decisions_1.decisionInputBudget; } });
794
+ Object.defineProperty(exports, "decisionFitsGateway", { enumerable: true, get: function () { return decisions_1.decisionFitsGateway; } });
795
+ Object.defineProperty(exports, "decisionAnswersMatch", { enumerable: true, get: function () { return decisions_1.decisionAnswersMatch; } });
@@ -58,7 +58,8 @@ exports.reasoningEffortSchema = zod_1.z.enum(['low', 'medium', 'high']);
58
58
  * 3.4.0). Ordered cheapest first; `auto` asks Oxy to pick the cheapest level
59
59
  * that suffices for the request.
60
60
  *
61
- * - `instant` — very cheap, fast small models; no reasoning effort requested
61
+ * - `instant` — very cheap, fast small models; the least reasoning each model
62
+ * accepts (`low` on a reasoning model, nothing on one without effort control)
62
63
  * - `medium` — mid-size models, low reasoning effort
63
64
  * - `high` — strong models, medium reasoning effort
64
65
  * - `xhigh` — strong models, high reasoning effort
@@ -96,6 +97,7 @@ exports.inferenceApiFormatSchema = zod_1.z.enum([
96
97
  'responses',
97
98
  'chat_completions',
98
99
  'embeddings',
100
+ 'decisions',
99
101
  'images_generations',
100
102
  'audio_transcriptions',
101
103
  'audio_speech',
@@ -583,7 +585,9 @@ exports.routingProfileSchema = zod_1.z.object({
583
585
  powerLevel: exports.powerLevelSchema.optional(),
584
586
  /**
585
587
  * The reasoning effort a power level asks for when the request names none,
586
- * applied only on a model that advertises it. Absent: none is requested.
588
+ * clamped to the nearest effort the chosen model accepts (the lowest at or
589
+ * above it, else the highest). Absent: the level asks for no reasoning, sent
590
+ * as the least effort a reasoning model accepts.
587
591
  */
588
592
  reasoningEffort: exports.reasoningEffortSchema.optional(),
589
593
  });
@@ -0,0 +1,245 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.decisionSuccessSchema = exports.decisionFailureSchema = exports.decisionResultSchema = exports.decisionAnswerSchema = exports.decisionRequestSchema = exports.decisionInputSchema = exports.decisionQuestionSchema = exports.decisionEffortSchema = void 0;
4
+ exports.decisionInputBudget = decisionInputBudget;
5
+ exports.decisionFitsGateway = decisionFitsGateway;
6
+ exports.decisionAnswersMatch = decisionAnswersMatch;
7
+ const zod_1 = require("zod");
8
+ const errors_1 = require("./errors");
9
+ const identifiers_1 = require("./identifiers");
10
+ const money_1 = require("./money");
11
+ const routingPolicy_1 = require("./routingPolicy");
12
+ const usage_1 = require("./usage");
13
+ const probability = zod_1.z.number().finite().min(0).max(1);
14
+ const text = zod_1.z.string().min(1).max(65536);
15
+ const id = zod_1.z.string().min(1).max(128);
16
+ const tolerance = 1e-6;
17
+ exports.decisionEffortSchema = zod_1.z.enum([
18
+ "instant",
19
+ "low",
20
+ "medium",
21
+ "high",
22
+ "xhigh",
23
+ ]);
24
+ const common = { id, question: text, criteria: text.optional() };
25
+ exports.decisionQuestionSchema = zod_1.z.discriminatedUnion("kind", [
26
+ zod_1.z
27
+ .object({
28
+ ...common,
29
+ kind: zod_1.z.literal("choice"),
30
+ options: zod_1.z.array(text).min(2).max(255),
31
+ })
32
+ .strict(),
33
+ zod_1.z
34
+ .object({
35
+ ...common,
36
+ kind: zod_1.z.literal("score"),
37
+ levels: zod_1.z.array(text).min(2).max(10),
38
+ })
39
+ .strict(),
40
+ zod_1.z.object({ ...common, kind: zod_1.z.literal("noul") }).strict(),
41
+ ]);
42
+ const payloadFields = {
43
+ state: zod_1.z.string().max(65536),
44
+ instructions: text.optional(),
45
+ questions: zod_1.z.array(exports.decisionQuestionSchema).min(1).max(255),
46
+ effort: exports.decisionEffortSchema.optional(),
47
+ };
48
+ /**
49
+ * Conservative serialized input accounting, including escaping and structure.
50
+ * Measures both the normalized payload and the provider's structured-question
51
+ * representation. Common instructions repeat per question there. A 255-byte
52
+ * model identity and 4096-byte gateway-policy allowance bound adapter metadata.
53
+ * Kaana must also check its final serialized body before sending it.
54
+ */
55
+ function decisionInputBudget(payload) {
56
+ const bytes = (value) => new TextEncoder().encode(JSON.stringify(value).replace(/[<>&\u2028\u2029]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`)).length;
57
+ const model = "x".repeat(255);
58
+ const measure = (questions) => {
59
+ const wireQuestions = Object.fromEntries(questions.map((q) => [q.id, {
60
+ type: q.kind,
61
+ instructions: {
62
+ question: q.question,
63
+ ...(payload.instructions === undefined ? {} : { instructions: payload.instructions }),
64
+ ...(q.criteria === undefined ? {} : { criteria: q.criteria }),
65
+ },
66
+ ...(q.kind === "choice" ? { criteria: Object.fromEntries(q.options.map((label) => [label, null])) } :
67
+ q.kind === "score" ? { criteria: q.levels } : {}),
68
+ }]));
69
+ return Math.max(bytes({ ...payload, model, questions }), bytes({ model, state: payload.state, questions: wireQuestions, ...(payload.effort === undefined ? {} : { effort: payload.effort }) }));
70
+ };
71
+ const total = measure(payload.questions);
72
+ return { total, context: Math.max(...payload.questions.map((q) => measure([q]))), gateway: total + 4096 };
73
+ }
74
+ /** OpenRouter's TOTAL limit is separate from direct state-plus-longest context. */
75
+ function decisionFitsGateway(payload) {
76
+ return decisionInputBudget(payload).gateway <= 32000;
77
+ }
78
+ function validateInput(payload, ctx) {
79
+ if (new Set(payload.questions.map((q) => q.id)).size !==
80
+ payload.questions.length)
81
+ ctx.addIssue({
82
+ code: "custom",
83
+ path: ["questions"],
84
+ message: "Question IDs must be unique.",
85
+ });
86
+ for (const [index, question] of payload.questions.entries()) {
87
+ const labels = question.kind === "choice"
88
+ ? question.options
89
+ : question.kind === "score"
90
+ ? question.levels
91
+ : [];
92
+ if (new Set(labels).size !== labels.length)
93
+ ctx.addIssue({
94
+ code: "custom",
95
+ path: ["questions", index],
96
+ message: "Options and levels must be unique.",
97
+ });
98
+ }
99
+ const budget = decisionInputBudget(payload);
100
+ if (budget.total > 64000 || budget.context > 32000)
101
+ ctx.addIssue({
102
+ code: "custom",
103
+ path: ["state"],
104
+ message: "Decisions exceed the serialized 64000-byte total or 32000-byte per-question context budget.",
105
+ });
106
+ }
107
+ exports.decisionInputSchema = zod_1.z
108
+ .object(payloadFields)
109
+ .strict()
110
+ .superRefine(validateInput);
111
+ exports.decisionRequestSchema = zod_1.z
112
+ .object({
113
+ model: identifiers_1.modelReferenceSchema.refine((model) => model.includes("@"), "Decisions require a revision-pinned model."),
114
+ ...payloadFields,
115
+ })
116
+ .strict()
117
+ .superRefine(validateInput);
118
+ exports.decisionAnswerSchema = zod_1.z
119
+ .discriminatedUnion("kind", [
120
+ zod_1.z
121
+ .object({
122
+ id,
123
+ kind: zod_1.z.literal("choice"),
124
+ /** Actual provider-selected option. Never reconstructed from probabilities. */
125
+ reply: text,
126
+ /** Provider-returned confidence, not a correctness probability. */
127
+ confidence: probability,
128
+ probabilities: zod_1.z.array(probability).min(2).max(255),
129
+ })
130
+ .strict(),
131
+ zod_1.z
132
+ .object({
133
+ id,
134
+ kind: zod_1.z.literal("score"),
135
+ /** Actual provider score. Kept separate from the validated expected index. */
136
+ reply: zod_1.z.number().finite().min(0).max(9),
137
+ confidence: probability,
138
+ mean: zod_1.z.number().finite().min(0).max(9),
139
+ distribution: zod_1.z.array(probability).min(2).max(10),
140
+ })
141
+ .strict(),
142
+ zod_1.z.object({ id, kind: zod_1.z.literal("noul"), probability }).strict(),
143
+ ])
144
+ .superRefine((answer, ctx) => {
145
+ if (answer.kind === "noul")
146
+ return;
147
+ if (answer.kind === "score" && Math.abs(answer.reply - answer.mean) > tolerance) {
148
+ ctx.addIssue({ code: "custom", path: ["reply"], message: "Provider score must match the expected level index." });
149
+ }
150
+ const distribution = answer.kind === "choice" ? answer.probabilities : answer.distribution;
151
+ if (Math.abs(distribution.reduce((sum, value) => sum + value, 0) - 1) >
152
+ tolerance)
153
+ ctx.addIssue({
154
+ code: "custom",
155
+ message: "Probabilities must sum to one.",
156
+ });
157
+ if (answer.kind === "score" &&
158
+ Math.abs(distribution.reduce((sum, value, index) => sum + index * value, 0) -
159
+ answer.mean) > tolerance)
160
+ ctx.addIssue({
161
+ code: "custom",
162
+ path: ["mean"],
163
+ message: "Mean must equal the expected zero-based level index.",
164
+ });
165
+ });
166
+ const resultFields = {
167
+ schemaVersion: zod_1.z.literal(1),
168
+ requestId: identifiers_1.requestIdSchema,
169
+ model: identifiers_1.modelReferenceSchema.refine((model) => model.includes("@"), "Decisions require an immutable model revision."),
170
+ data: zod_1.z.array(exports.decisionAnswerSchema).min(1).max(255),
171
+ };
172
+ function uniqueAnswers(result, ctx) {
173
+ if (new Set(result.data.map((answer) => answer.id)).size !== result.data.length)
174
+ ctx.addIssue({
175
+ code: "custom",
176
+ path: ["data"],
177
+ message: "Answer IDs must be unique.",
178
+ });
179
+ }
180
+ exports.decisionResultSchema = zod_1.z
181
+ .object({ ...resultFields, usage: usage_1.normalizedUsageReportSchema })
182
+ .strict()
183
+ .superRefine(uniqueAnswers)
184
+ .superRefine((result, ctx) => {
185
+ if (result.usage.requestId !== result.requestId ||
186
+ result.usage.resolvedModelReference !== result.model ||
187
+ result.usage.outcome !== "completed") {
188
+ ctx.addIssue({
189
+ code: "custom",
190
+ path: ["usage"],
191
+ message: "Decision usage must describe this completed request and immutable model.",
192
+ });
193
+ }
194
+ });
195
+ /**
196
+ * Kaana's typed decisions failure. `usage` is present only when the provider
197
+ * measured something before failing; its absence means nothing was measured,
198
+ * never that the cost was zero. A failure carrying usage did execute.
199
+ */
200
+ exports.decisionFailureSchema = zod_1.z
201
+ .object({
202
+ schemaVersion: zod_1.z.literal(1),
203
+ requestId: identifiers_1.requestIdSchema,
204
+ error: errors_1.inferenceErrorSchema,
205
+ usage: usage_1.normalizedUsageReportSchema.optional(),
206
+ })
207
+ .strict()
208
+ .superRefine((failure, ctx) => {
209
+ if (failure.error.requestId !== failure.requestId) {
210
+ ctx.addIssue({ code: "custom", path: ["error", "requestId"], message: "The error must answer this request." });
211
+ }
212
+ if (failure.usage !== undefined &&
213
+ (failure.usage.requestId !== failure.requestId || failure.usage.outcome === "completed")) {
214
+ ctx.addIssue({ code: "custom", path: ["usage"], message: "Failure usage must describe this request and an incomplete outcome." });
215
+ }
216
+ });
217
+ exports.decisionSuccessSchema = zod_1.z
218
+ .object({
219
+ ...resultFields,
220
+ usage: zod_1.z.array(money_1.usageQuantitySchema),
221
+ routingPolicy: routingPolicy_1.routingPolicyReferenceSchema,
222
+ })
223
+ .strict()
224
+ .superRefine(uniqueAnswers);
225
+ /** Bind output to the exact request. Provider order is not semantic. */
226
+ function decisionAnswersMatch(input, answers) {
227
+ if (answers.length !== input.questions.length ||
228
+ new Set(answers.map((a) => a.id)).size !== answers.length)
229
+ return false;
230
+ return input.questions.every((question) => {
231
+ const answer = answers.find((candidate) => candidate.id === question.id);
232
+ if (!answer ||
233
+ !exports.decisionAnswerSchema.safeParse(answer).success ||
234
+ answer.kind !== question.kind)
235
+ return false;
236
+ if (question.kind === "choice" && answer.kind === "choice") {
237
+ const index = question.options.indexOf(answer.reply);
238
+ return question.options.length === answer.probabilities.length && index >= 0 &&
239
+ answer.probabilities[index] + tolerance >= Math.max(...answer.probabilities);
240
+ }
241
+ if (question.kind === "score" && answer.kind === "score")
242
+ return question.levels.length === answer.distribution.length;
243
+ return question.kind === "noul";
244
+ });
245
+ }
@@ -26,6 +26,7 @@
26
26
  */
27
27
  Object.defineProperty(exports, "__esModule", { value: true });
28
28
  exports.inferenceRequestSchema = exports.inferenceAudioOutputParametersSchema = exports.inferenceSpeechParametersSchema = exports.clientRequestMetadataSchema = exports.inferenceReasoningSchema = exports.responseFormatSchema = exports.toolChoiceSchema = exports.toolDefinitionSchema = exports.samplingParametersSchema = exports.inferenceInputSchema = exports.inferenceMessageSchema = exports.inferenceMessageRoleSchema = exports.inferenceToolCallSchema = exports.inferenceContentPartSchema = exports.inferenceContentSourceSchema = void 0;
29
+ const decisions_1 = require("./decisions");
29
30
  const zod_1 = require("zod");
30
31
  const attribution_1 = require("./attribution");
31
32
  const catalogue_1 = require("./catalogue");
@@ -198,6 +199,7 @@ exports.inferenceMessageSchema = zod_1.z
198
199
  * that both metering and provider translation depend on.
199
200
  */
200
201
  exports.inferenceInputSchema = zod_1.z.discriminatedUnion("format", [
202
+ zod_1.z.object({ format: zod_1.z.literal("decisions"), decisions: decisions_1.decisionInputSchema }).strict(),
201
203
  zod_1.z
202
204
  .object({
203
205
  format: zod_1.z.literal("messages"),
@@ -406,6 +408,17 @@ exports.inferenceRequestSchema = zod_1.z
406
408
  authorizedRoutes: zod_1.z.array(routingPolicy_1.authorizedRouteSchema).min(1).optional(),
407
409
  })
408
410
  .superRefine((request, ctx) => {
411
+ if (request.input.format === "decisions" || request.client.apiFormat === "decisions") {
412
+ const exactModel = request.target.kind === "model" && request.target.modelReference.includes('@');
413
+ const foreignRoute = request.authorizedRoutes?.some((route) => request.target.kind !== "model" || route.modelReference !== request.target.modelReference || route.substitution !== "same_model");
414
+ if (request.input.format !== "decisions" || request.client.apiFormat !== "decisions" ||
415
+ request.modality !== "text" || request.stream || !exactModel || foreignRoute ||
416
+ request.maxOutputTokens !== undefined || Object.keys(request.sampling).length > 0 ||
417
+ request.tools.length > 0 || request.toolChoice !== undefined || request.responseFormat !== undefined ||
418
+ request.reasoning !== undefined || request.speech !== undefined || request.audioOutput !== undefined) {
419
+ ctx.addIssue({ code: zod_1.z.ZodIssueCode.custom, path: ["input"], message: "Decisions require exact-model typed nonstreaming input without generation controls or model substitution." });
420
+ }
421
+ }
409
422
  const isSpeech = request.client.apiFormat === "audio_speech";
410
423
  if (isSpeech && request.speech !== undefined && (request.modality !== "audio" || request.input.format !== "text" || request.stream)) {
411
424
  ctx.addIssue({ code: zod_1.z.ZodIssueCode.custom, path: ["speech"], message: "speech requires audio modality, text input, parameters and non-streaming output" });
@@ -102,4 +102,4 @@ exports.INFERENCE_CONTRACT_VERSION = void 0;
102
102
  * change to, say, the catalogue reject every in-flight inference request; the
103
103
  * per-shape `schemaVersion` is what a message is validated against.
104
104
  */
105
- exports.INFERENCE_CONTRACT_VERSION = '3.4.0';
105
+ exports.INFERENCE_CONTRACT_VERSION = '3.5.0';