@canonry/canonry 7.53.0 → 7.55.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/assets/agent-workspace/skills/canonry/references/canonry-cli.md +13 -0
  2. package/assets/assets/AgentSetupPage-Dr7UsGcq.js +17 -0
  3. package/assets/assets/AuditHistoryPanel-Dg9ZNNQw.js +1 -0
  4. package/assets/assets/BacklinksPage-DSgwyFCi.js +1 -0
  5. package/assets/assets/{HistoryPage-D2DOk7ms.js → HistoryPage-DaX20IWP.js} +1 -1
  6. package/assets/assets/MeasurementPropertyPage-FGhKdZAP.js +4 -0
  7. package/assets/assets/ProjectPage-BTJYS9gc.js +7 -0
  8. package/assets/assets/RunsPage-D06GJ47B.js +1 -0
  9. package/assets/assets/SettingsPage-MSgC8Zrc.js +1 -0
  10. package/assets/assets/SiteHealthSection-4PXTNjon.js +2 -0
  11. package/assets/assets/ToneBadge-AoUA_EpE.js +60 -0
  12. package/assets/assets/TrafficPage-DikPWmaU.js +40 -0
  13. package/assets/assets/TrafficSourceDetailPage-C1hfimWW.js +1 -0
  14. package/assets/assets/account-context-CHtJm4fz.js +1 -0
  15. package/assets/assets/card-BO6dtEV9.js +1 -0
  16. package/assets/assets/extract-error-message-Q9pkEqUE.js +1 -0
  17. package/assets/assets/{format-helpers-B_2jkVGI.js → format-helpers-Gj1ekh6p.js} +1 -1
  18. package/assets/assets/{index-DgS5TTSb.css → index-B8W65ejO.css} +1 -1
  19. package/assets/assets/index-BBfEsbxI.js +56 -0
  20. package/assets/assets/query-client-C22j0Z7h.js +1 -0
  21. package/assets/assets/react-query-BLKqSvlU.js +1 -0
  22. package/assets/assets/{react-sigma_core.esm.min-Bjux3j_1.js → react-sigma_core.esm.min-j5DWE8Rk.js} +1 -1
  23. package/assets/assets/service-2DEngBCR.js +1 -0
  24. package/assets/demo-og.png +0 -0
  25. package/assets/index.html +8 -7
  26. package/dist/{ads-S4S74OXM.js → ads-A5S2NQBZ.js} +3 -3
  27. package/dist/{agent-JZWKCI5V.js → agent-BV7G7QN7.js} +7 -7
  28. package/dist/{agent-ask-N2DG5ZLZ.js → agent-ask-5ALAHZ6T.js} +3 -3
  29. package/dist/{agent-conversations-7UDNE7YI.js → agent-conversations-MJPQCJYR.js} +3 -3
  30. package/dist/{agent-memory-I74OWTU7.js → agent-memory-Z3VPA5KH.js} +3 -3
  31. package/dist/{agent-providers-MEMCZPGE.js → agent-providers-FP3LAZPG.js} +3 -3
  32. package/dist/{agent-transcript-Z7VTL7PY.js → agent-transcript-4GXCOC73.js} +3 -3
  33. package/dist/{analytics-4NUSNTKT.js → analytics-TOLSUYSN.js} +3 -3
  34. package/dist/{apply-OZKQK3YF.js → apply-EU5JAFVZ.js} +3 -3
  35. package/dist/{backfill-PLY2NOOY.js → backfill-3263IYJH.js} +9 -9
  36. package/dist/{backlinks-2CMRJFWO.js → backlinks-XQ5JTN6W.js} +3 -3
  37. package/dist/{bing-RD3DDESD.js → bing-LYHRD7BF.js} +3 -3
  38. package/dist/{bootstrap-JOYV4SWM.js → bootstrap-AKWTIMMH.js} +17 -9
  39. package/dist/{cdp-LUGL3CT6.js → cdp-N4PQJWGQ.js} +7 -7
  40. package/dist/{chunk-QNU7IIO7.js → chunk-2OB7YQEZ.js} +324 -324
  41. package/dist/{chunk-U7JJKXLA.js → chunk-4LVJFSPH.js} +5 -5
  42. package/dist/{chunk-C5GCRQ66.js → chunk-6WTSWWP6.js} +2 -2
  43. package/dist/{chunk-LGU3O5YP.js → chunk-75CFTTBF.js} +2 -2
  44. package/dist/{chunk-NKSASP4U.js → chunk-B37SDIGU.js} +1 -1
  45. package/dist/{chunk-N3WQHLDI.js → chunk-BQKKAPMW.js} +13 -1
  46. package/dist/{chunk-BQT7VLGM.js → chunk-D234NBWI.js} +1 -1
  47. package/dist/{chunk-DFQHGWPB.js → chunk-EIG2V6UI.js} +1 -1
  48. package/dist/{chunk-3DO3CS7Y.js → chunk-F5XONXGH.js} +4 -4
  49. package/dist/{chunk-BH274VEO.js → chunk-GFRIXUDK.js} +36 -2
  50. package/dist/{chunk-LYCYSM6O.js → chunk-H6EQMYGT.js} +1 -1
  51. package/dist/{chunk-23UZNTF4.js → chunk-J7VN3FZ3.js} +1 -1
  52. package/dist/{chunk-IWQGZQHE.js → chunk-K5MBEK4S.js} +8 -8
  53. package/dist/{chunk-6VSKBVB3.js → chunk-LCTYTGSE.js} +3 -3
  54. package/dist/{chunk-ZXH5IFIA.js → chunk-MARVEIWH.js} +4 -4
  55. package/dist/{chunk-SZG7S7TE.js → chunk-OHVXKFQI.js} +1 -1
  56. package/dist/{chunk-2GAXZAQJ.js → chunk-OMXWBR2R.js} +7227 -6562
  57. package/dist/{chunk-JZARXJV6.js → chunk-PRNO5TLE.js} +456 -249
  58. package/dist/{chunk-6ZCZRZ66.js → chunk-QFKDFU73.js} +2 -2
  59. package/dist/chunk-R4AFXPM4.js +959 -0
  60. package/dist/{chunk-O3OTW7F4.js → chunk-RHCDUPD6.js} +2 -2
  61. package/dist/{chunk-P4SXRRB4.js → chunk-RHO7UNXA.js} +298 -110
  62. package/dist/{chunk-N6MS4VG2.js → chunk-SKZVEZZK.js} +7 -2
  63. package/dist/{chunk-2XDGFHPM.js → chunk-T63KVDWY.js} +3 -3
  64. package/dist/{chunk-F55ER5RQ.js → chunk-VB47PTY7.js} +3 -3
  65. package/dist/{chunk-QARV5HVI.js → chunk-VCTP2RG6.js} +5 -5
  66. package/dist/{chunk-RVBGFWJ3.js → chunk-VF7XGX2I.js} +1 -1
  67. package/dist/{chunk-QXJ356KK.js → chunk-VMCVLESK.js} +4 -4
  68. package/dist/{chunk-WNXKW3NS.js → chunk-WDJMIIY2.js} +1 -1
  69. package/dist/{chunk-2HWY4NRQ.js → chunk-XJVCTI2N.js} +3 -3
  70. package/dist/{chunk-XTIP5WSA.js → chunk-Y2YBRLSS.js} +3 -3
  71. package/dist/{chunk-VEH4YLWR.js → chunk-YOZ35ZTT.js} +1 -1
  72. package/dist/{chunk-2EYBZYDG.js → chunk-ZA7D7CCN.js} +2 -2
  73. package/dist/{chunk-BGZL5RCP.js → chunk-ZILJZNMQ.js} +1 -1
  74. package/dist/{citations-GMLBTNLW.js → citations-JK3ZMAR7.js} +3 -3
  75. package/dist/{cli-catalog-WKUCQEWA.js → cli-catalog-P2I6IYNI.js} +3 -3
  76. package/dist/{cli-commands-YCHQWUNK.js → cli-commands-U6NDGGK2.js} +7 -7
  77. package/dist/cli.js +13 -13
  78. package/dist/{competitor-QNPVJFEI.js → competitor-5CJPM36M.js} +3 -3
  79. package/dist/{content-NFTC74HD.js → content-5FEDXNHR.js} +3 -3
  80. package/dist/{dashboard-TMUQT5H5.js → dashboard-ME7MBJTX.js} +6 -6
  81. package/dist/{demo-O5SPVLZZ.js → demo-J3QCDV43.js} +1 -1
  82. package/dist/{demo-server-WKZ53RGK.js → demo-server-FJLSYQXZ.js} +49 -16
  83. package/dist/{discover-LTTO7KHN.js → discover-EAISVTA6.js} +3 -3
  84. package/dist/{discover-eval-QRDNMDUE.js → discover-eval-JIBKK44Q.js} +3 -3
  85. package/dist/{doctor-SFL5FOW4.js → doctor-HSQYOZ4C.js} +3 -3
  86. package/dist/{evidence-J6WZ767P.js → evidence-PSYAWKPP.js} +3 -3
  87. package/dist/{export-cmd-D3JDTBDV.js → export-cmd-MWJN6H7W.js} +3 -3
  88. package/dist/{ga-N56LXQUN.js → ga-WSQWECYY.js} +3 -3
  89. package/dist/{gbp-7WVJYWDR.js → gbp-OD26AEPF.js} +3 -3
  90. package/dist/{google-YLRVXYVJ.js → google-FMJ7IWAF.js} +4 -4
  91. package/dist/{google-marketing-4DGX3RBB.js → google-marketing-66JL4V24.js} +1 -1
  92. package/dist/{health-cmd-PK3BASF6.js → health-cmd-2RO5LAI4.js} +3 -3
  93. package/dist/{history-UWTEZ626.js → history-X6CNPW7G.js} +3 -3
  94. package/dist/index.d.ts +449 -14
  95. package/dist/index.js +24 -23
  96. package/dist/{init-RBI2IOBY.js → init-EDSKLFUY.js} +11 -11
  97. package/dist/{insights-ZUC5XHFD.js → insights-6IWWA6JU.js} +3 -3
  98. package/dist/intelligence-service-N334P6FH.js +15 -0
  99. package/dist/{keys-NOG3M76V.js → keys-ABXAPISY.js} +3 -3
  100. package/dist/{keyword-HD57L76I.js → keyword-LERAVMI3.js} +3 -3
  101. package/dist/{logs-VAB7ITBS.js → logs-BTAB5SNZ.js} +3 -3
  102. package/dist/{mcp-HYHIL5FB.js → mcp-5E42RT6R.js} +2 -2
  103. package/dist/mcp.js +9 -9
  104. package/dist/{measurement-plan-GEHOHCH3.js → measurement-plan-MRZRNBJG.js} +5 -5
  105. package/dist/{notify-VQ2ZDGN4.js → notify-YQYGC5UZ.js} +3 -3
  106. package/dist/{organic-evidence-6TX627YW.js → organic-evidence-6QT4YT3K.js} +3 -3
  107. package/dist/{overview-XBO7WYAV.js → overview-EHZ3FTS2.js} +4 -4
  108. package/dist/{project-DR6744WZ.js → project-RNLV2ARE.js} +3 -3
  109. package/dist/{query-OGVTCPG5.js → query-IM2RXI4L.js} +3 -3
  110. package/dist/{research-B2TGKSMC.js → research-4FALR336.js} +25 -10
  111. package/dist/{results-export-K7PAYPWQ.js → results-export-4ETSRUGO.js} +3 -3
  112. package/dist/{run-Y6LUMCVL.js → run-QL7226N7.js} +4 -4
  113. package/dist/{schedule-PNAUJ5FX.js → schedule-GJE634VO.js} +3 -3
  114. package/dist/{search-PMVOGL4U.js → search-7OQL67R6.js} +3 -3
  115. package/dist/{serve-PQHXSS5T.js → serve-VJ3M7FAT.js} +25 -24
  116. package/dist/{session-S5NDMMKF.js → session-5M54TVY5.js} +12 -12
  117. package/dist/{settings-AL7E7QUK.js → settings-2QOL7YBM.js} +15 -3
  118. package/dist/{skills-GQOOTDR7.js → skills-GPLAAU3I.js} +2 -2
  119. package/dist/{snapshot-W3FXRTZM.js → snapshot-5YMJFRJS.js} +8 -6
  120. package/dist/{src-WZLTQFCH.js → src-YF3JLURF.js} +2 -2
  121. package/dist/{status-MBJVN4W5.js → status-WGWC6FLN.js} +33 -5
  122. package/dist/{technical-aeo-Y4RFST72.js → technical-aeo-RNMLD7OL.js} +3 -3
  123. package/dist/{telemetry-VK6F5QSZ.js → telemetry-7U3ZICU4.js} +4 -4
  124. package/dist/{tools-W3AQY5TY.js → tools-CSKTZTKT.js} +11 -11
  125. package/dist/{traffic-ER4I6V3B.js → traffic-QIAXLW6J.js} +5 -5
  126. package/dist/{users-KZK2OF4L.js → users-I6X5P5AO.js} +3 -3
  127. package/dist/{visibility-stats-CR7BUG5G.js → visibility-stats-33OUKQQL.js} +3 -3
  128. package/dist/{wordpress-DG5JUCAC.js → wordpress-3IO3O27D.js} +3 -3
  129. package/package.json +2 -1
  130. package/assets/assets/AccessControls-B-5YUuLE.js +0 -1
  131. package/assets/assets/AuditHistoryPanel-BkCUPvPv.js +0 -1
  132. package/assets/assets/BacklinksPage-BMgHZKuw.js +0 -1
  133. package/assets/assets/MeasurementPropertyPage-Bwv8nKS7.js +0 -4
  134. package/assets/assets/ProjectPage-CsJfGPx3.js +0 -7
  135. package/assets/assets/RunsPage-DSHDuj9b.js +0 -1
  136. package/assets/assets/SettingsPage-BDRdWk5X.js +0 -1
  137. package/assets/assets/SiteHealthSection-DV06NTxC.js +0 -2
  138. package/assets/assets/TrafficPage-CBMMwRfw.js +0 -40
  139. package/assets/assets/TrafficSourceDetailPage-Czpt0S7j.js +0 -1
  140. package/assets/assets/card-CVejjbhs.js +0 -60
  141. package/assets/assets/extract-error-message-Co6zPipR.js +0 -1
  142. package/assets/assets/index-BnS2Vuv0.js +0 -40
  143. package/assets/assets/query-client-BKJLgjJd.js +0 -1
  144. package/assets/assets/react-query-ltP1RErY.js +0 -1
  145. package/assets/assets/service-CDsqgNrS.js +0 -1
  146. package/dist/intelligence-service-JXXB43RB.js +0 -15
@@ -0,0 +1,959 @@
1
+ import {
2
+ ANSWER_EVIDENCE_VERSION,
3
+ CompletionStatuses,
4
+ CostBases,
5
+ DisclosedModelKinds,
6
+ IncompleteAnswerError,
7
+ ProviderKinds,
8
+ ProviderWorkflows,
9
+ RetrievalContracts,
10
+ SourceRelationships,
11
+ answerServiceRouteFamily,
12
+ answerServiceRouteName,
13
+ asRecord,
14
+ citationBasisFor,
15
+ clampAnswerSourceExcerpts,
16
+ createSseParser,
17
+ deriveCitedDomains,
18
+ deriveRetrievalStatus,
19
+ describeError,
20
+ escapeRegExp,
21
+ finalizeLocationTreatment,
22
+ groundingSourcesFromEvidence,
23
+ isRetryableHttpError,
24
+ normalizeServedModel,
25
+ resolveLocationTreatment,
26
+ retryAfterDelayMs,
27
+ routeSelection,
28
+ unknownUsageObservation,
29
+ usdToMicros,
30
+ withRetry
31
+ } from "./chunk-OMXWBR2R.js";
32
+
33
+ // ../provider-answer-services/src/core/http.ts
34
+ var MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
35
+ var MAX_UPSTREAM_MESSAGE_CHARS = 300;
36
+ var AnswerServiceHttpError = class extends Error {
37
+ constructor(service, status, upstreamMessage, retryAfter, requestId = null) {
38
+ super(`${service} request failed (HTTP ${status})${upstreamMessage ? `: ${upstreamMessage}` : ""}`);
39
+ this.service = service;
40
+ this.status = status;
41
+ this.upstreamMessage = upstreamMessage;
42
+ this.retryAfter = retryAfter;
43
+ this.requestId = requestId;
44
+ this.name = "AnswerServiceHttpError";
45
+ }
46
+ service;
47
+ status;
48
+ upstreamMessage;
49
+ retryAfter;
50
+ requestId;
51
+ };
52
+ function authHeaders(descriptor, apiKey) {
53
+ return descriptor.auth.scheme === "bearer" ? { Authorization: `Bearer ${apiKey}` } : { [descriptor.auth.header]: apiKey };
54
+ }
55
+ function requestUrl(descriptor, path) {
56
+ if (!path.startsWith("/")) throw new Error(`${descriptor.displayName} request path must start with /`);
57
+ return `${descriptor.baseUrl.replace(/\/+$/, "")}${path}`;
58
+ }
59
+ function signalFor(options) {
60
+ const deadline = AbortSignal.timeout(options.timeoutMs);
61
+ return options.signal ? AbortSignal.any([options.signal, deadline]) : deadline;
62
+ }
63
+ function requestIdOf(response) {
64
+ return response.headers.get("x-request-id") ?? response.headers.get("request-id");
65
+ }
66
+ async function readBounded(response) {
67
+ const declared = Number(response.headers.get("content-length"));
68
+ if (Number.isFinite(declared) && declared > MAX_RESPONSE_BYTES) throw new Error(`response exceeds ${MAX_RESPONSE_BYTES} bytes`);
69
+ if (!response.body) return { text: "", bytes: 0 };
70
+ const reader = response.body.getReader();
71
+ const decoder = new TextDecoder();
72
+ let bytes = 0;
73
+ let text = "";
74
+ for (; ; ) {
75
+ const { done, value } = await reader.read();
76
+ if (done) break;
77
+ bytes += value.byteLength;
78
+ if (bytes > MAX_RESPONSE_BYTES) {
79
+ await reader.cancel().catch(() => void 0);
80
+ throw new Error(`response exceeds ${MAX_RESPONSE_BYTES} bytes`);
81
+ }
82
+ text += decoder.decode(value, { stream: true });
83
+ }
84
+ return { text: text + decoder.decode(), bytes };
85
+ }
86
+ function parseJsonText(text) {
87
+ try {
88
+ return JSON.parse(text);
89
+ } catch {
90
+ return null;
91
+ }
92
+ }
93
+ function boundedMessage(value) {
94
+ const trimmed = value?.replace(/\s+/g, " ").trim();
95
+ if (!trimmed) return null;
96
+ return trimmed.length > MAX_UPSTREAM_MESSAGE_CHARS ? `${trimmed.slice(0, MAX_UPSTREAM_MESSAGE_CHARS)}\u2026` : trimmed;
97
+ }
98
+ async function failure(descriptor, response, errorMessage) {
99
+ let message = null;
100
+ try {
101
+ const { text } = await readBounded(response);
102
+ const parsed = parseJsonText(text);
103
+ message = errorMessage ? errorMessage(parsed) : null;
104
+ } catch {
105
+ message = null;
106
+ }
107
+ return new AnswerServiceHttpError(
108
+ descriptor.displayName,
109
+ response.status,
110
+ boundedMessage(message),
111
+ response.headers.get("retry-after") ?? void 0,
112
+ requestIdOf(response)
113
+ );
114
+ }
115
+ async function open(descriptor, request, options, signal, accept) {
116
+ const fetchImpl = options.fetchImpl ?? fetch;
117
+ return fetchImpl(requestUrl(descriptor, request.path), {
118
+ method: request.method,
119
+ headers: {
120
+ ...request.headers,
121
+ ...authHeaders(descriptor, options.apiKey),
122
+ Accept: accept,
123
+ ...request.body ? { "Content-Type": "application/json" } : {}
124
+ },
125
+ ...request.body ? { body: JSON.stringify(request.body) } : {},
126
+ signal
127
+ });
128
+ }
129
+ async function fetchJsonOnce(descriptor, request, options, errorMessage) {
130
+ const signal = signalFor(options);
131
+ const response = await open(descriptor, request, options, signal, "application/json");
132
+ if (!response.ok) throw await failure(descriptor, response, errorMessage);
133
+ const { text, bytes } = await readBounded(response);
134
+ const body = asRecord(parseJsonText(text));
135
+ if (!body) throw new Error(`${descriptor.displayName} returned a response that is not a JSON object`);
136
+ return { body, requestId: requestIdOf(response), bytes };
137
+ }
138
+ async function fetchStreamOnce(descriptor, request, options, isTerminal, errorMessage) {
139
+ const signal = signalFor(options);
140
+ const response = await open(descriptor, request, options, signal, "text/event-stream");
141
+ if (!response.ok) throw await failure(descriptor, response, errorMessage);
142
+ const requestId = requestIdOf(response);
143
+ const events = [];
144
+ if (!response.body) return { events, ended: "eof", unterminated: false, requestId, bytes: 0 };
145
+ const parser = createSseParser();
146
+ const reader = response.body.getReader();
147
+ const decoder = new TextDecoder();
148
+ let bytes = 0;
149
+ let ended = "eof";
150
+ try {
151
+ reading: for (; ; ) {
152
+ const { done, value } = await reader.read();
153
+ if (done) break;
154
+ bytes += value.byteLength;
155
+ if (bytes > MAX_RESPONSE_BYTES) throw new Error(`response exceeds ${MAX_RESPONSE_BYTES} bytes`);
156
+ for (const event of parser.push(decoder.decode(value, { stream: true }))) {
157
+ events.push(event);
158
+ if (isTerminal(event)) {
159
+ ended = "terminal";
160
+ break reading;
161
+ }
162
+ }
163
+ }
164
+ } catch (error) {
165
+ if (!signal.aborted) throw new AnswerServiceStreamError(descriptor.displayName, describeError(error), events, requestId);
166
+ ended = "aborted";
167
+ } finally {
168
+ await reader.cancel().catch(() => void 0);
169
+ }
170
+ const tail = ended === "eof" ? parser.push(decoder.decode()) : [];
171
+ events.push(...tail);
172
+ const { unterminated } = parser.end();
173
+ return { events, ended, unterminated, requestId, bytes };
174
+ }
175
+ var AnswerServiceStreamError = class extends Error {
176
+ constructor(service, cause, events, requestId) {
177
+ super(`${service} stream failed after it began: ${cause}`);
178
+ this.events = events;
179
+ this.requestId = requestId;
180
+ this.name = "AnswerServiceStreamError";
181
+ }
182
+ events;
183
+ requestId;
184
+ };
185
+ function isRetryableAnswerRequest(descriptor, error) {
186
+ return error instanceof AnswerServiceHttpError && descriptor.retry.statuses.includes(error.status);
187
+ }
188
+ function retryOptions(options, isRetryable) {
189
+ return {
190
+ maxRetries: 2,
191
+ baseDelayMs: 2e3,
192
+ isRetryable: (error) => !options.signal?.aborted && isRetryable(error),
193
+ computeDelayMs: (_attempt, error, delay) => retryAfterDelayMs(error) ?? delay,
194
+ ...options.sleep ? { sleep: options.sleep } : {}
195
+ };
196
+ }
197
+ function requestJson(descriptor, request, options, errorMessage) {
198
+ return withRetry(
199
+ () => fetchJsonOnce(descriptor, request, options, errorMessage),
200
+ retryOptions(options, (error) => isRetryableAnswerRequest(descriptor, error))
201
+ );
202
+ }
203
+ function requestStream(descriptor, request, options, isTerminal, errorMessage) {
204
+ return withRetry(
205
+ () => fetchStreamOnce(descriptor, request, options, isTerminal, errorMessage),
206
+ retryOptions(options, (error) => isRetryableAnswerRequest(descriptor, error))
207
+ );
208
+ }
209
+ function requestKeyCheck(descriptor, request, options) {
210
+ return withRetry(
211
+ () => fetchJsonOnce(descriptor, request, options, void 0),
212
+ retryOptions(options, isRetryableHttpError)
213
+ );
214
+ }
215
+
216
+ // ../provider-answer-services/src/core/evidence.ts
217
+ var MAX_STORED_RAW_BYTES = 1024 * 1024;
218
+ function boundRawResponse(raw, bytes) {
219
+ if (bytes <= MAX_STORED_RAW_BYTES) return { raw, truncated: false };
220
+ return {
221
+ raw: { truncated: true, originalBytes: bytes, note: `Raw response exceeded ${MAX_STORED_RAW_BYTES} bytes and was not stored.` },
222
+ truncated: true
223
+ };
224
+ }
225
+ function enforceStreamCompletion(parsed, ended) {
226
+ if (ended === "terminal" || parsed.completion.status !== CompletionStatuses.complete) return parsed;
227
+ return {
228
+ ...parsed,
229
+ completion: {
230
+ ...parsed.completion,
231
+ status: CompletionStatuses.partial,
232
+ error: parsed.completion.error ?? (ended === "aborted" ? "The stream stopped before its final event." : "The stream ended before its final event.")
233
+ }
234
+ };
235
+ }
236
+ function enforceAnswerPresent(parsed) {
237
+ if (parsed.completion.status !== CompletionStatuses.complete || parsed.answerText?.trim()) return parsed;
238
+ return { ...parsed, completion: { ...parsed.completion, status: CompletionStatuses.failed, error: parsed.completion.error ?? "The response carried no answer text." } };
239
+ }
240
+ function assembleEvidence(input) {
241
+ const { descriptor, profile: profile3, parsed } = input;
242
+ const citationBasis = citationBasisFor(profile3.capabilities.evidence.relationships);
243
+ const sources = clampAnswerSourceExcerpts(parsed.sources);
244
+ return {
245
+ version: ANSWER_EVIDENCE_VERSION,
246
+ identity: {
247
+ connection: descriptor.id,
248
+ route: answerServiceRouteName(descriptor.id, profile3.id),
249
+ service: descriptor.id,
250
+ product: profile3.product,
251
+ profile: profile3.id,
252
+ settings: { ...profile3.settings },
253
+ requestedServiceModel: profile3.requestedServiceModel,
254
+ disclosedModel: parsed.disclosedModel,
255
+ disclosedModelKind: parsed.disclosedModel === null ? null : profile3.capabilities.disclosedModelKind,
256
+ requestPolicy: profile3.requestPolicyVersion,
257
+ parserVersion: descriptor.parserVersion
258
+ },
259
+ completion: parsed.completion,
260
+ usage: parsed.usage,
261
+ sources,
262
+ searchQueries: parsed.searchQueries,
263
+ retrievalStatus: deriveRetrievalStatus({
264
+ sources,
265
+ searchEventCount: parsed.searchEventCount,
266
+ reportedSearchCount: parsed.usage.searches.basis === "reported" ? parsed.usage.searches.count : null,
267
+ observability: profile3.capabilities.evidence.retrievalObservability,
268
+ completion: parsed.completion
269
+ }),
270
+ citationBasis,
271
+ citationMeasurable: citationBasis !== "none",
272
+ directSourceUrls: profile3.capabilities.evidence.directUrls,
273
+ location: input.location,
274
+ rawTruncated: input.rawTruncated
275
+ };
276
+ }
277
+ function providerUsageFromEvidence(evidence) {
278
+ const { tokens, searches } = evidence.usage;
279
+ if (tokens.basis !== "reported" || tokens.input === null || tokens.output === null) return void 0;
280
+ if (searches.basis === "unknown" || searches.count === null) return void 0;
281
+ return {
282
+ inputTokens: tokens.input,
283
+ cachedInputTokens: 0,
284
+ cacheWriteTokens: 0,
285
+ outputTokens: tokens.output,
286
+ searchCount: searches.count
287
+ };
288
+ }
289
+ function rawQueryResult(input) {
290
+ const { evidence } = input;
291
+ const servedModel = evidence.identity.disclosedModelKind === DisclosedModelKinds["foundation-model"] ? normalizeServedModel(evidence.identity.disclosedModel) : void 0;
292
+ const usage = providerUsageFromEvidence(evidence);
293
+ return {
294
+ provider: evidence.identity.route,
295
+ rawResponse: input.raw,
296
+ model: evidence.identity.profile,
297
+ ...servedModel ? { servedModel } : {},
298
+ answerText: input.answerText,
299
+ groundingSources: groundingSourcesFromEvidence(evidence.sources),
300
+ searchQueries: evidence.searchQueries,
301
+ retrievalStatus: evidence.retrievalStatus,
302
+ retrievalContract: RetrievalContracts["service-native-v1"],
303
+ ...usage ? { usage } : {},
304
+ ...evidence.completion.finishReason ? { stopReason: evidence.completion.finishReason } : {},
305
+ evidence,
306
+ citationMeasurable: evidence.citationMeasurable
307
+ };
308
+ }
309
+
310
+ // ../provider-answer-services/src/core/adapter.ts
311
+ var AnswerServiceQueryTooLongError = class extends Error {
312
+ constructor(service, maxQueryChars, queryChars) {
313
+ super(`${service} accepts queries up to ${maxQueryChars} characters; this query has ${queryChars}. Shorten it or choose another engine.`);
314
+ this.service = service;
315
+ this.maxQueryChars = maxQueryChars;
316
+ this.queryChars = queryChars;
317
+ this.name = "AnswerServiceQueryTooLongError";
318
+ }
319
+ service;
320
+ maxQueryChars;
321
+ queryChars;
322
+ };
323
+ function profileOf(descriptor, providerName) {
324
+ const selection = routeSelection(providerName, answerServiceRouteFamily(descriptor));
325
+ const profile3 = selection === void 0 ? void 0 : descriptor.profiles.find((item) => item.id === selection);
326
+ if (!profile3) {
327
+ throw new Error(`Select a ${descriptor.displayName} profile (${descriptor.profiles.map((item) => answerServiceRouteName(descriptor.id, item.id)).join(", ")}); the connection alone is not an engine.`);
328
+ }
329
+ return profile3;
330
+ }
331
+ function configProblem(descriptor, config) {
332
+ if (!config.apiKey?.trim()) return `Missing ${descriptor.displayName} API key`;
333
+ if (config.baseUrl) return `${descriptor.displayName} uses a fixed endpoint; remove the base URL`;
334
+ return null;
335
+ }
336
+ function assertRouteModel(profile3, config) {
337
+ if (config.model !== void 0 && config.model !== profile3.id) {
338
+ throw new Error(`Route profile "${profile3.id}" cannot be overridden with "${config.model}".`);
339
+ }
340
+ }
341
+ function incompleteMessage(descriptor, parsed) {
342
+ const { completion } = parsed;
343
+ switch (completion.status) {
344
+ case CompletionStatuses.pending:
345
+ return `${descriptor.displayName} returned a pending job (${completion.upstreamJobId}), not an answer.`;
346
+ case CompletionStatuses.partial:
347
+ return `${descriptor.displayName} returned a partial answer${completion.error ? `: ${completion.error}` : ""}.`;
348
+ case CompletionStatuses.failed:
349
+ return `${descriptor.displayName} reported a failure${completion.error ? `: ${completion.error}` : ""}.`;
350
+ case CompletionStatuses.complete:
351
+ return `${descriptor.displayName} answer is complete.`;
352
+ }
353
+ }
354
+ function createAnswerServiceAdapter(definition, options = {}) {
355
+ const { descriptor } = definition;
356
+ const family = answerServiceRouteFamily(descriptor);
357
+ const profileIds = descriptor.profiles.map((profile3) => profile3.id);
358
+ const profilePattern = new RegExp(`^(?:${profileIds.map(escapeRegExp).join("|")})$`);
359
+ const transport = (config, profile3) => ({
360
+ apiKey: config.apiKey ?? "",
361
+ timeoutMs: profile3.timeoutMs,
362
+ ...options.fetchImpl ? { fetchImpl: options.fetchImpl } : {},
363
+ ...options.sleep ? { sleep: options.sleep } : {}
364
+ });
365
+ async function execute(input, config) {
366
+ const profile3 = profileOf(descriptor, config.provider);
367
+ assertRouteModel(profile3, config);
368
+ const problem = configProblem(descriptor, config);
369
+ if (problem) throw new Error(problem);
370
+ if (profile3.execution === "job") {
371
+ throw new Error(`${descriptor.displayName} profile "${profile3.id}" runs as an upstream job, which this release cannot run yet.`);
372
+ }
373
+ const maxQueryChars = profile3.capabilities.maxQueryChars;
374
+ const queryChars = [...input.query].length;
375
+ if (maxQueryChars !== null && queryChars > maxQueryChars) {
376
+ throw new AnswerServiceQueryTooLongError(descriptor.displayName, maxQueryChars, queryChars);
377
+ }
378
+ const offered = resolveLocationTreatment(input.location, profile3.capabilities.location, profile3.capabilities.location.serviceDefault ?? null);
379
+ const built = definition.buildRequest({ query: input.query, profile: profile3, location: offered });
380
+ const { request } = built;
381
+ const location = finalizeLocationTreatment(offered, built.sentLocation);
382
+ let parsed;
383
+ let raw;
384
+ let bytes;
385
+ if (profile3.transport === "sse") {
386
+ if (!definition.parseEvents || !definition.isTerminalEvent) throw new Error(`${descriptor.displayName} has no stream parser`);
387
+ let events;
388
+ let ended;
389
+ let requestId;
390
+ try {
391
+ const streamed = await requestStream(descriptor, request, transport(config, profile3), definition.isTerminalEvent, definition.errorMessage);
392
+ events = streamed.events;
393
+ ended = streamed.ended;
394
+ requestId = streamed.requestId;
395
+ bytes = streamed.bytes;
396
+ } catch (error) {
397
+ if (!(error instanceof AnswerServiceStreamError)) throw error;
398
+ events = [...error.events];
399
+ ended = "aborted";
400
+ requestId = error.requestId;
401
+ bytes = events.reduce((total, event) => total + event.data.length, 0);
402
+ }
403
+ parsed = enforceStreamCompletion(definition.parseEvents(events, { profile: profile3, headerRequestId: requestId, ended }), ended);
404
+ raw = { events: events.map((event) => ({ event: event.event, data: event.data })), ended };
405
+ } else {
406
+ if (!definition.parseResponse) throw new Error(`${descriptor.displayName} has no response parser`);
407
+ const response = await requestJson(descriptor, request, transport(config, profile3), definition.errorMessage);
408
+ parsed = definition.parseResponse(response.body, { profile: profile3, headerRequestId: response.requestId });
409
+ raw = response.body;
410
+ bytes = response.bytes;
411
+ }
412
+ parsed = enforceAnswerPresent(parsed);
413
+ const stored = boundRawResponse(raw, bytes);
414
+ const evidence = assembleEvidence({ descriptor, profile: profile3, parsed, location, rawTruncated: stored.truncated });
415
+ if (evidence.completion.status !== CompletionStatuses.complete) {
416
+ throw new IncompleteAnswerError(incompleteMessage(descriptor, parsed), evidence, parsed.answerText, stored.raw, { resumable: false });
417
+ }
418
+ return rawQueryResult({ evidence, answerText: parsed.answerText ?? "", raw: stored.raw });
419
+ }
420
+ function normalize(raw) {
421
+ const sources = raw.evidence?.sources ?? [];
422
+ return {
423
+ provider: raw.provider,
424
+ answerText: raw.answerText ?? "",
425
+ citedDomains: raw.evidence ? deriveCitedDomains(sources) : [],
426
+ groundingSources: raw.groundingSources,
427
+ searchQueries: raw.searchQueries,
428
+ retrievalStatus: raw.retrievalStatus,
429
+ ...raw.evidence ? { evidence: raw.evidence } : {},
430
+ citationMeasurable: raw.citationMeasurable ?? raw.evidence?.citationMeasurable ?? false
431
+ };
432
+ }
433
+ async function healthcheck(config) {
434
+ const problem = configProblem(descriptor, config);
435
+ if (problem) return { ok: false, provider: config.provider, message: problem };
436
+ const keyCheck = descriptor.settings.keyCheck;
437
+ if (!keyCheck) {
438
+ return { ok: true, provider: config.provider, message: `${descriptor.displayName} key saved, not verified: the service documents no free key check.` };
439
+ }
440
+ try {
441
+ await requestKeyCheck(descriptor, { method: keyCheck.method, path: keyCheck.path }, {
442
+ apiKey: config.apiKey ?? "",
443
+ timeoutMs: 15e3,
444
+ ...options.fetchImpl ? { fetchImpl: options.fetchImpl } : {},
445
+ ...options.sleep ? { sleep: options.sleep } : {}
446
+ });
447
+ return { ok: true, provider: config.provider, message: `${descriptor.displayName} connected` };
448
+ } catch (error) {
449
+ return { ok: false, provider: config.provider, message: error instanceof AnswerServiceHttpError ? error.message : describeError(error) };
450
+ }
451
+ }
452
+ function routeAdapter(route) {
453
+ const profile3 = profileOf(descriptor, route.name);
454
+ return {
455
+ ...connection,
456
+ name: route.name,
457
+ displayName: `${profile3.displayName} \xB7 ${descriptor.displayName}`,
458
+ // Only a service that sends every requested field may claim the answer was measured from there.
459
+ supportsLocationContext: profile3.capabilities.location.granularity === "full",
460
+ capabilities: { textGeneration: false, groundedAnswer: true, workflows: [...profile3.workflows] },
461
+ modelRegistry: { ...connection.modelRegistry, defaultModel: profile3.id }
462
+ };
463
+ }
464
+ const connection = {
465
+ name: descriptor.id,
466
+ displayName: descriptor.displayName,
467
+ mode: "api",
468
+ kind: ProviderKinds["answer-service"],
469
+ // The connection is never a target, so it runs no workflow; each route declares its profile's.
470
+ capabilities: { textGeneration: false, groundedAnswer: true, workflows: [] },
471
+ routes: family,
472
+ defaultQuota: { ...descriptor.defaultQuota },
473
+ supportsLocationContext: false,
474
+ keyUrl: descriptor.keyUrl,
475
+ modelRegistry: {
476
+ defaultModel: "",
477
+ knownModels: descriptor.profiles.map((profile3) => ({ id: profile3.id, displayName: profile3.displayName, tier: "standard" })),
478
+ validationPattern: profilePattern,
479
+ validationHint: `one of the ${descriptor.displayName} profiles: ${profileIds.join(", ")}`
480
+ },
481
+ forRoute: routeAdapter,
482
+ validateConfig(config) {
483
+ const problem = configProblem(descriptor, config);
484
+ if (problem) return { ok: false, provider: config.provider, message: problem };
485
+ return { ok: true, provider: config.provider, message: "Configuration valid" };
486
+ },
487
+ healthcheck,
488
+ executeTrackedQuery: execute,
489
+ normalizeResult: normalize
490
+ };
491
+ return connection;
492
+ }
493
+
494
+ // ../provider-answer-services/src/services/exa/descriptor.ts
495
+ var CAPABILITIES = {
496
+ groundedAnswer: true,
497
+ textGeneration: false,
498
+ // Exa documents `outputSchema`, but these profiles never send one and the
499
+ // parser refuses a structured answer rather than inventing text from it.
500
+ structuredOutput: false,
501
+ evidence: {
502
+ // `citations` are documented as "search results used to generate the
503
+ // answer", with no markers or spans in the text.
504
+ relationships: [SourceRelationships["answer-support"]],
505
+ spans: false,
506
+ // No search events are reported; only the returned citations show retrieval.
507
+ retrievalObservability: "sources",
508
+ directUrls: true
509
+ },
510
+ // `userLocation` takes a two-letter country that "localizes results"; city
511
+ // and region have no field, and coordinates are not sent.
512
+ location: { granularity: "country", strength: "hint" },
513
+ filters: { includeDomains: "none", excludeDomains: "none" },
514
+ // The schema sets only a minimum length for `query`.
515
+ maxQueryChars: null,
516
+ // The response has no model field.
517
+ disclosedModelKind: DisclosedModelKinds.unknown,
518
+ // `costDollars` is documented as an estimate, not an invoice.
519
+ costBasis: CostBases.estimated
520
+ };
521
+ function profile(input) {
522
+ return {
523
+ id: input.id,
524
+ displayName: input.displayName,
525
+ description: input.description,
526
+ product: "answer",
527
+ execution: "sync",
528
+ transport: "json",
529
+ timeoutMs: input.timeoutMs,
530
+ requestedServiceModel: input.model,
531
+ // Sent verbatim as the request body next to the query (see request.ts).
532
+ settings: { model: input.model, stream: false, text: false },
533
+ requestPolicyVersion: "exa-answer-v1",
534
+ capabilities: CAPABILITIES,
535
+ workflows: [ProviderWorkflows.research, ProviderWorkflows.snapshot, ProviderWorkflows["visibility-sweep"]]
536
+ };
537
+ }
538
+ var exaDescriptor = {
539
+ id: "exa",
540
+ displayName: "Exa",
541
+ keyUrl: "https://dashboard.exa.ai/api-keys",
542
+ vendorDocsUrl: "https://exa.ai/docs/reference/answer",
543
+ docsPath: "docs/providers/answer-services/exa.md",
544
+ auth: { scheme: "header", header: "x-api-key" },
545
+ baseUrl: "https://api.exa.ai",
546
+ settings: {
547
+ fields: [{ key: "apiKey", kind: "secret", required: true, env: "EXA_API_KEY", label: "API key" }],
548
+ allowBaseUrl: false,
549
+ allowModel: false,
550
+ // Exa documents no free request that proves a key, so a saved key stays "not verified".
551
+ keyCheck: null
552
+ },
553
+ // The same limits Canonry applies to any provider without its own.
554
+ defaultQuota: { maxConcurrency: 2, maxRequestsPerMinute: 10, maxRequestsPerDay: 1e3 },
555
+ // 429 is a rejection and 503 is documented as "not processed, not billed".
556
+ // 500 and 504 are not retried: Exa does not say they were unbilled.
557
+ retry: { statuses: [429, 503] },
558
+ parserVersion: "exa-answer-1",
559
+ profiles: [
560
+ profile({ id: "fast", displayName: "Fast", model: "exa-fast", timeoutMs: 6e4, description: "Exa Answer with the exa-fast model." }),
561
+ profile({ id: "standard", displayName: "Standard", model: "exa", timeoutMs: 12e4, description: "Exa Answer with the default exa model." }),
562
+ profile({ id: "pro", displayName: "Pro", model: "exa-pro", timeoutMs: 18e4, description: "Exa Answer with the exa-pro model." }),
563
+ profile({ id: "research", displayName: "Research", model: "exa-research", timeoutMs: 3e5, description: "Exa Answer with the exa-research model. Waits up to five minutes per query." })
564
+ ]
565
+ };
566
+
567
+ // ../provider-answer-services/src/services/exa/parse.ts
568
+ function nonEmptyString(value) {
569
+ return typeof value === "string" && value.trim() ? value : null;
570
+ }
571
+ function sourcesOf(citations) {
572
+ if (!Array.isArray(citations)) return [];
573
+ const sources = [];
574
+ for (const item of citations) {
575
+ const citation = asRecord(item);
576
+ const url = nonEmptyString(citation?.url);
577
+ if (!citation || !url) continue;
578
+ sources.push({
579
+ url,
580
+ title: nonEmptyString(citation.title),
581
+ relationship: SourceRelationships["answer-support"],
582
+ // The list order is not documented as a ranking.
583
+ rank: null,
584
+ publishedAt: nonEmptyString(citation.publishedDate),
585
+ upstreamId: nonEmptyString(citation.id)
586
+ });
587
+ }
588
+ return sources;
589
+ }
590
+ function usageOf(costDollars) {
591
+ const usage = unknownUsageObservation();
592
+ const micros = usdToMicros(asRecord(costDollars)?.total);
593
+ if (micros !== null) usage.cost = { micros, currency: "USD", basis: CostBases.estimated, estimatedBy: "provider" };
594
+ return usage;
595
+ }
596
+ var STRUCTURED_ANSWER_ERROR = "Exa returned a structured answer. Canonry sends no output schema and measures text answers only.";
597
+ function parseExaAnswer(body, context) {
598
+ const answerText = typeof body.answer === "string" ? body.answer : null;
599
+ const completion = {
600
+ status: answerText === null ? CompletionStatuses.failed : CompletionStatuses.complete,
601
+ finishReason: null,
602
+ upstreamStatus: null,
603
+ upstreamRequestId: nonEmptyString(body.requestId) ?? context.headerRequestId,
604
+ upstreamJobId: null,
605
+ error: answerText !== null ? null : asRecord(body.answer) ? STRUCTURED_ANSWER_ERROR : "The response carried no answer."
606
+ };
607
+ return {
608
+ answerText,
609
+ sources: sourcesOf(body.citations),
610
+ searchQueries: [],
611
+ searchEventCount: 0,
612
+ completion,
613
+ usage: usageOf(body.costDollars),
614
+ disclosedModel: null
615
+ };
616
+ }
617
+ var TAG_EXPLANATIONS = {
618
+ INVALID_API_KEY: "The Exa API key is missing or invalid",
619
+ NO_MORE_CREDITS: "The Exa account is out of credits",
620
+ API_KEY_BUDGET_EXCEEDED: "This Exa key is over its spending budget",
621
+ TEAM_BUDGET_EXCEEDED: "The Exa team is over its spending budget",
622
+ FEATURE_DISABLED: "The Exa plan does not include this feature"
623
+ };
624
+ function exaErrorMessage(body) {
625
+ const record = asRecord(body);
626
+ const message = nonEmptyString(record?.error);
627
+ const tag = nonEmptyString(record?.tag);
628
+ const detail = message && tag ? `${message} (${tag})` : message ?? tag;
629
+ const explanation = tag ? TAG_EXPLANATIONS[tag] : void 0;
630
+ if (explanation) return detail ? `${explanation}. Exa said: ${detail}` : explanation;
631
+ return detail;
632
+ }
633
+
634
+ // ../provider-answer-services/src/services/exa/request.ts
635
+ function buildExaAnswerRequest({ query, profile: profile3, location }) {
636
+ const country = location.sent?.country;
637
+ return {
638
+ request: {
639
+ method: "POST",
640
+ path: "/answer",
641
+ body: {
642
+ query,
643
+ ...profile3.settings,
644
+ ...country ? { userLocation: { country } } : {}
645
+ }
646
+ },
647
+ sentLocation: country ? { country } : null
648
+ };
649
+ }
650
+
651
+ // ../provider-answer-services/src/services/exa/index.ts
652
+ var exaAnswerService = {
653
+ descriptor: exaDescriptor,
654
+ buildRequest: buildExaAnswerRequest,
655
+ parseResponse: parseExaAnswer,
656
+ errorMessage: exaErrorMessage
657
+ };
658
+
659
+ // ../provider-answer-services/src/services/parallel/descriptor.ts
660
+ var PARALLEL_EFFORT_SETTING = "reasoning.effort";
661
+ var CAPABILITIES2 = {
662
+ groundedAnswer: true,
663
+ textGeneration: false,
664
+ // Parallel documents structured output through `text.format`, but these
665
+ // profiles never send one and measure the answer text only.
666
+ structuredOutput: false,
667
+ evidence: {
668
+ // `url_citation` annotations mark the span of answer text each source
669
+ // supports; `web_search_call` items with `open_page` are pages it read.
670
+ // `action.sources` on searches is documented as always null, so no
671
+ // search results are returned.
672
+ relationships: [SourceRelationships["explicit-citation"], SourceRelationships["page-read"]],
673
+ spans: true,
674
+ // "Every response reports the searches the model ran and the pages it
675
+ // read as web_search_call output items", and a run that does neither
676
+ // returns none.
677
+ retrievalObservability: "events",
678
+ directUrls: true
679
+ },
680
+ // The request has no location field; the web_search tool's `user_location`
681
+ // is documented as accepted and ignored, so nothing is sent.
682
+ location: { granularity: "none", strength: null },
683
+ // Domain filters exist on the web_search tool, but these profiles send no tools.
684
+ filters: { includeDomains: "none", excludeDomains: "none" },
685
+ // "`input` and `instructions` together may total at most 20,000 characters";
686
+ // no instructions are sent, so the query may use all of it.
687
+ maxQueryChars: 2e4,
688
+ // The response `model` is always `parallel`: the service name, not a model.
689
+ disclosedModelKind: DisclosedModelKinds["service-tier"],
690
+ // The response carries no amount; Parallel bills per successful request.
691
+ costBasis: CostBases.unknown
692
+ };
693
+ function profile2(input) {
694
+ return {
695
+ id: input.effort,
696
+ displayName: input.displayName,
697
+ description: input.description,
698
+ product: "responses",
699
+ execution: "sync",
700
+ transport: "json",
701
+ timeoutMs: input.timeoutMs,
702
+ requestedServiceModel: "parallel",
703
+ // Sent as `model`, `reasoning.effort` and `stream` (see request.ts).
704
+ settings: { model: "parallel", [PARALLEL_EFFORT_SETTING]: input.effort, stream: false },
705
+ requestPolicyVersion: "parallel-responses-v1",
706
+ capabilities: CAPABILITIES2,
707
+ workflows: [ProviderWorkflows.research, ProviderWorkflows.snapshot, ProviderWorkflows["visibility-sweep"]]
708
+ };
709
+ }
710
+ var parallelDescriptor = {
711
+ id: "parallel",
712
+ displayName: "Parallel",
713
+ keyUrl: "https://platform.parallel.ai",
714
+ vendorDocsUrl: "https://docs.parallel.ai/responses-api/responses-quickstart",
715
+ docsPath: "docs/providers/answer-services/parallel.md",
716
+ // Every Responses example sends `Authorization: Bearer`, the OpenAI-compatible
717
+ // form. The OpenAPI spec also names an `x-api-key` header for the same key.
718
+ auth: { scheme: "bearer" },
719
+ baseUrl: "https://api.parallel.ai",
720
+ settings: {
721
+ fields: [{ key: "apiKey", kind: "secret", required: true, env: "PARALLEL_API_KEY", label: "API key" }],
722
+ allowBaseUrl: false,
723
+ allowModel: false,
724
+ // Parallel documents no free request that proves a key, so a saved key stays "not verified".
725
+ keyCheck: null
726
+ },
727
+ // Parallel publishes no Responses rate limit; these are Canonry's defaults for any provider.
728
+ defaultQuota: { maxConcurrency: 2, maxRequestsPerMinute: 10, maxRequestsPerDay: 1e3 },
729
+ // The Responses pages say to back off and retry a 429 only. The general
730
+ // error table that also lists 500, 502 and 503 describes the Task API.
731
+ retry: { statuses: [429] },
732
+ parserVersion: "parallel-responses-1",
733
+ // Deadlines leave headroom over the documented latency (about 5 to 10, 15
734
+ // to 20 and 30 to 60 seconds), because a request Canonry abandons may still
735
+ // finish upstream and be charged.
736
+ profiles: [
737
+ profile2({ effort: "low", displayName: "Low effort", timeoutMs: 6e4, description: "Parallel Responses with low reasoning effort, for simple fact questions." }),
738
+ profile2({ effort: "medium", displayName: "Medium effort", timeoutMs: 12e4, description: "Parallel Responses with medium reasoning effort (Parallel's default), for questions that need several searches." }),
739
+ profile2({ effort: "high", displayName: "High effort", timeoutMs: 18e4, description: "Parallel Responses with high reasoning effort, for deep research. Waits up to three minutes per query." })
740
+ ]
741
+ };
742
+
743
+ // ../provider-answer-services/src/services/parallel/parse.ts
744
+ function nonEmptyString2(value) {
745
+ return typeof value === "string" && value.trim() ? value : null;
746
+ }
747
+ function count(value) {
748
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : null;
749
+ }
750
+ function records(value) {
751
+ if (!Array.isArray(value)) return [];
752
+ return value.map(asRecord).filter((item) => item !== null);
753
+ }
754
+ function answerMessages(output) {
755
+ return output.filter((item) => item.type === "message" && item.phase !== "commentary");
756
+ }
757
+ function readAnswer(messages) {
758
+ const byUrl = /* @__PURE__ */ new Map();
759
+ let text = null;
760
+ for (const message of messages) {
761
+ let messageStarted = false;
762
+ for (const part of records(message.content)) {
763
+ if (part.type !== "output_text" || typeof part.text !== "string") continue;
764
+ if (text === null) text = "";
765
+ else if (!messageStarted) text += "\n\n";
766
+ messageStarted = true;
767
+ const offset = text.length;
768
+ text += part.text;
769
+ for (const annotation of records(part.annotations)) {
770
+ const url = nonEmptyString2(annotation.url);
771
+ if (annotation.type !== "url_citation" || !url) continue;
772
+ const cited = byUrl.get(url) ?? { title: null, spans: [] };
773
+ byUrl.set(url, cited);
774
+ cited.title ??= nonEmptyString2(annotation.title);
775
+ const start = count(annotation.start_index);
776
+ const end = count(annotation.end_index);
777
+ if (start === null || end === null || end < start) continue;
778
+ if (!cited.spans.some((span) => span.start === offset + start && span.end === offset + end)) {
779
+ cited.spans.push({ start: offset + start, end: offset + end, basis: "upstream" });
780
+ }
781
+ }
782
+ }
783
+ }
784
+ const citations = [...byUrl].map(([url, cited]) => ({
785
+ url,
786
+ title: cited.title,
787
+ relationship: SourceRelationships["explicit-citation"],
788
+ rank: null,
789
+ spans: cited.spans,
790
+ publishedAt: null,
791
+ upstreamId: null
792
+ }));
793
+ return { text, citations };
794
+ }
795
+ function readSearchTrail(output) {
796
+ const trail = { pageReads: [], pageReadCount: 0, searchQueries: [], searchCount: 0 };
797
+ for (const item of output) {
798
+ if (item.type !== "web_search_call") continue;
799
+ const action = asRecord(item.action);
800
+ if (action?.type === "search") {
801
+ trail.searchCount++;
802
+ const queries = Array.isArray(action.queries) ? action.queries.map(nonEmptyString2).filter((query) => query !== null) : [];
803
+ const single = nonEmptyString2(action.query);
804
+ trail.searchQueries.push(...queries.length > 0 ? queries : single ? [single] : []);
805
+ } else if (action?.type === "open_page") {
806
+ trail.pageReadCount++;
807
+ const url = nonEmptyString2(action.url);
808
+ if (!url) continue;
809
+ trail.pageReads.push({
810
+ url,
811
+ title: null,
812
+ relationship: SourceRelationships["page-read"],
813
+ rank: null,
814
+ publishedAt: null,
815
+ upstreamId: nonEmptyString2(item.id),
816
+ status: nonEmptyString2(item.status)
817
+ });
818
+ }
819
+ }
820
+ return trail;
821
+ }
822
+ function messageStatus(messages) {
823
+ if (messages.length === 0) return null;
824
+ const unfinished = messages.find((message) => message.status !== "completed");
825
+ return unfinished ? nonEmptyString2(unfinished.status) ?? "missing a status" : "completed";
826
+ }
827
+ function failureMessage(error) {
828
+ const record = asRecord(error);
829
+ const message = nonEmptyString2(record?.message);
830
+ const code = nonEmptyString2(record?.code);
831
+ if (message && code) return `${message} (${code})`;
832
+ return message ?? code ?? "Parallel reported a failure without a message.";
833
+ }
834
+ function completionOf(body, messages, context) {
835
+ const status = nonEmptyString2(body.status);
836
+ const id = nonEmptyString2(body.id);
837
+ const base = {
838
+ status: CompletionStatuses.failed,
839
+ finishReason: null,
840
+ upstreamStatus: status,
841
+ upstreamRequestId: id ?? context.headerRequestId,
842
+ upstreamJobId: null,
843
+ error: null
844
+ };
845
+ const answerStatus = messageStatus(messages);
846
+ switch (status) {
847
+ case "completed":
848
+ if (answerStatus === null) return { ...base, error: "Parallel returned no answer message." };
849
+ if (answerStatus !== "completed") return { ...base, status: CompletionStatuses.partial, error: `The answer message is ${answerStatus}, although the response is completed.` };
850
+ return { ...base, status: CompletionStatuses.complete };
851
+ case "incomplete": {
852
+ const reason = nonEmptyString2(asRecord(body.incomplete_details)?.reason);
853
+ return { ...base, status: CompletionStatuses.partial, finishReason: reason, error: `Parallel stopped before the answer was finished (${reason ?? "no reason given"}).` };
854
+ }
855
+ case "failed":
856
+ return { ...base, error: failureMessage(body.error) };
857
+ case "cancelled":
858
+ return { ...base, error: "Parallel cancelled the response." };
859
+ case "queued":
860
+ case "in_progress":
861
+ if (!id) return { ...base, error: `Parallel returned an unfinished response (${status}) without an id.` };
862
+ return { ...base, status: CompletionStatuses.pending, upstreamJobId: id, error: `Parallel had not finished (${status}). The Responses API offers no way to fetch the answer later.` };
863
+ case null:
864
+ if (answerStatus === "completed") return { ...base, status: CompletionStatuses.complete };
865
+ if (answerStatus === "incomplete") return { ...base, status: CompletionStatuses.partial, error: "The answer message is incomplete." };
866
+ return { ...base, error: "The response carried no status and no completed answer message." };
867
+ default:
868
+ return { ...base, error: `Parallel returned an unrecognized status "${status}".` };
869
+ }
870
+ }
871
+ function usageOf2(body, trail, complete) {
872
+ const usage = unknownUsageObservation();
873
+ const reported = asRecord(body.usage);
874
+ if (reported) {
875
+ const input = count(reported.input_tokens);
876
+ const output = count(reported.output_tokens);
877
+ const reasoning = count(asRecord(reported.output_tokens_details)?.reasoning_tokens);
878
+ if (input !== null || output !== null || reasoning !== null) usage.tokens = { input, output, reasoning, basis: "approximate" };
879
+ }
880
+ if (complete || trail.searchCount > 0) usage.searches = { count: trail.searchCount, basis: "derived-from-evidence" };
881
+ if (complete || trail.pageReadCount > 0) usage.pageReads = { count: trail.pageReadCount, basis: "derived-from-evidence" };
882
+ return usage;
883
+ }
884
+ function parseParallelResponse(body, context) {
885
+ const output = records(body.output);
886
+ const messages = answerMessages(output);
887
+ const answer = readAnswer(messages);
888
+ const trail = readSearchTrail(output);
889
+ const completion = completionOf(body, messages, context);
890
+ return {
891
+ answerText: answer.text,
892
+ sources: [...answer.citations, ...trail.pageReads],
893
+ searchQueries: trail.searchQueries,
894
+ searchEventCount: trail.searchCount,
895
+ completion,
896
+ usage: usageOf2(body, trail, completion.status === CompletionStatuses.complete),
897
+ disclosedModel: nonEmptyString2(body.model)
898
+ };
899
+ }
900
+ function parallelErrorMessage(body) {
901
+ const record = asRecord(body);
902
+ if (!record) return null;
903
+ const error = asRecord(record.error);
904
+ if (error) {
905
+ const message = nonEmptyString2(error.message);
906
+ const kind = [nonEmptyString2(error.type), nonEmptyString2(error.code)].filter((value) => value !== null);
907
+ if (message && kind.length > 0) return `${message} (${kind.join(", ")})`;
908
+ return message ?? (kind.length > 0 ? kind.join(", ") : null);
909
+ }
910
+ if (Array.isArray(record.detail)) {
911
+ const problems = records(record.detail).map((item) => {
912
+ const message = nonEmptyString2(item.msg);
913
+ const where = Array.isArray(item.loc) ? item.loc.filter((part) => typeof part === "string" || typeof part === "number").join(".") : "";
914
+ return message && where ? `${where}: ${message}` : message;
915
+ }).filter((problem) => problem !== null);
916
+ return problems.length > 0 ? problems.join("; ") : null;
917
+ }
918
+ return nonEmptyString2(record.error) ?? nonEmptyString2(record.detail);
919
+ }
920
+
921
+ // ../provider-answer-services/src/services/parallel/request.ts
922
+ function buildParallelResponsesRequest({ query, profile: profile3 }) {
923
+ const { model, stream } = profile3.settings;
924
+ const effort = profile3.settings[PARALLEL_EFFORT_SETTING];
925
+ if (typeof model !== "string" || typeof effort !== "string" || typeof stream !== "boolean") {
926
+ throw new Error(`Parallel profile "${profile3.id}" is missing its model, effort or stream setting.`);
927
+ }
928
+ return {
929
+ request: {
930
+ method: "POST",
931
+ path: "/v1/responses",
932
+ body: { model, input: query, reasoning: { effort }, stream }
933
+ },
934
+ sentLocation: null
935
+ };
936
+ }
937
+
938
+ // ../provider-answer-services/src/services/parallel/index.ts
939
+ var parallelResponsesService = {
940
+ descriptor: parallelDescriptor,
941
+ buildRequest: buildParallelResponsesRequest,
942
+ parseResponse: parseParallelResponse,
943
+ errorMessage: parallelErrorMessage
944
+ };
945
+
946
+ // ../provider-answer-services/src/services/index.ts
947
+ var ANSWER_SERVICES = [
948
+ exaAnswerService,
949
+ parallelResponsesService
950
+ ];
951
+
952
+ // ../provider-answer-services/src/index.ts
953
+ var answerServiceAdapters = ANSWER_SERVICES.map((service) => createAnswerServiceAdapter(service));
954
+ var answerServiceDescriptors = ANSWER_SERVICES.map((service) => service.descriptor);
955
+
956
+ export {
957
+ answerServiceAdapters,
958
+ answerServiceDescriptors
959
+ };