@littlepress/harness-integrations 0.0.0-stage → 1.0.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.
package/dist/cloud.js ADDED
@@ -0,0 +1,672 @@
1
+ import { CONTRACT_VERSION, validateContract, } from "@littlepress/ui-foundation-contracts";
2
+ export const CLOUD_API_VERSION = "v1";
3
+ export const DEFAULT_GENERATION_PATH = "/v1/widget-generations";
4
+ export const DEFAULT_MODELS_PATH = "/v1/models";
5
+ const DEFAULT_MAX_RECONNECTS = 5;
6
+ const RECONNECT_BACKOFF_MS = 250;
7
+ const CANCEL_CLEANUP_TIMEOUT_MS = 1_000;
8
+ // Allow 32 error details with 500-character paths and messages, including JSON escapes.
9
+ const ERROR_BODY_LIMIT_BYTES = 256 * 1024;
10
+ const ERROR_MESSAGE_LIMIT = 500;
11
+ export class CloudProtocolError extends Error {
12
+ name = "CloudProtocolError";
13
+ }
14
+ export class CloudHttpError extends Error {
15
+ status;
16
+ error;
17
+ name = "CloudHttpError";
18
+ constructor(status, message,
19
+ /**
20
+ * The `error` object Cloud sent, the same shape as a `failed` event's `error`:
21
+ * `code`, `retryable`, `retry_after_ms` and `details[]` for a program to branch on.
22
+ * `undefined` when the body was not a Cloud error, for example a proxy's HTML page.
23
+ */
24
+ error) {
25
+ super(message);
26
+ this.status = status;
27
+ this.error = error;
28
+ }
29
+ }
30
+ function formatIssues(label, issues) {
31
+ const first = issues[0];
32
+ return `${label} is invalid at ${first?.path ?? "<root>"}: ${first?.message ?? "unknown error"}`;
33
+ }
34
+ function readModelCatalog(payload) {
35
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload)) {
36
+ throw new CloudProtocolError("Cloud models query must return an object.");
37
+ }
38
+ const value = payload;
39
+ if (!Array.isArray(value.models)) {
40
+ throw new CloudProtocolError("Cloud models query has an invalid models array.");
41
+ }
42
+ const models = value.models.map((entry, index) => {
43
+ if (typeof entry !== "object" || entry === null || Array.isArray(entry)) {
44
+ throw new CloudProtocolError(`Cloud models query has an invalid model at index ${index}.`);
45
+ }
46
+ const model = entry;
47
+ if (typeof model.id !== "string" || typeof model.provider !== "string" || typeof model.model !== "string") {
48
+ throw new CloudProtocolError(`Cloud models query has an invalid model at index ${index}.`);
49
+ }
50
+ return { id: model.id, provider: model.provider, model: model.model };
51
+ });
52
+ if (typeof value.defaults !== "object" || value.defaults === null || Array.isArray(value.defaults)) {
53
+ throw new CloudProtocolError("Cloud models query has invalid defaults.");
54
+ }
55
+ const defaults = value.defaults;
56
+ if ((defaults.widget !== null && typeof defaults.widget !== "string")
57
+ || (defaults.report !== null && typeof defaults.report !== "string")) {
58
+ throw new CloudProtocolError("Cloud models query has invalid defaults.");
59
+ }
60
+ return {
61
+ models,
62
+ defaults: { widget: defaults.widget, report: defaults.report },
63
+ };
64
+ }
65
+ /** Refresh validates JSON and its input budget, without the initial material rule. */
66
+ function dataUpdateBody(data) {
67
+ const value = { data };
68
+ const stack = [[value, 0]];
69
+ while (stack.length) {
70
+ const [item, depth] = stack.pop();
71
+ if (Array.isArray(item) || (typeof item === "object" && item !== null)) {
72
+ if (depth >= 200)
73
+ throw new CloudProtocolError("Refresh JSON exceeds 200 container levels.");
74
+ if (!Array.isArray(item) && ![Object.prototype, null].includes(Object.getPrototypeOf(item))) {
75
+ throw new CloudProtocolError("Replacement data must contain only JSON values.");
76
+ }
77
+ for (const child of Object.values(item))
78
+ stack.push([child, depth + 1]);
79
+ }
80
+ else if ((typeof item === "number" && !Number.isFinite(item)) ||
81
+ (item !== null && !["string", "number", "boolean"].includes(typeof item))) {
82
+ throw new CloudProtocolError("Replacement data must contain finite JSON values.");
83
+ }
84
+ }
85
+ let body;
86
+ try {
87
+ body = JSON.stringify(value);
88
+ }
89
+ catch (error) {
90
+ throw new CloudProtocolError("Replacement data must contain only JSON values.", { cause: error });
91
+ }
92
+ if (new TextEncoder().encode(body).length > 1024 * 1024) {
93
+ throw new CloudProtocolError("The complete refresh JSON exceeds 1 MiB.");
94
+ }
95
+ return body;
96
+ }
97
+ function apiUrl(baseUrl, path) {
98
+ const normalizedBase = baseUrl.replace(/\/+$/u, "");
99
+ const normalizedPath = path.startsWith("/") ? path : `/${path}`;
100
+ return `${normalizedBase}${normalizedPath}`;
101
+ }
102
+ function linkedUrl(baseUrl, path, label) {
103
+ const base = new URL(baseUrl);
104
+ const linked = new URL(path, base);
105
+ if (linked.origin !== base.origin) {
106
+ throw new CloudProtocolError(`${label} must stay on the configured Cloud origin.`);
107
+ }
108
+ return linked.toString();
109
+ }
110
+ function parseOperation(payload, request) {
111
+ if (typeof payload !== "object" || payload === null) {
112
+ throw new CloudProtocolError("Cloud create response must be a generation operation object.");
113
+ }
114
+ const operation = payload;
115
+ for (const field of ["run_id", "request_id", "event_url", "status_url"]) {
116
+ if (typeof operation[field] !== "string" || operation[field].length === 0) {
117
+ throw new CloudProtocolError(`Cloud create response is missing ${field}.`);
118
+ }
119
+ }
120
+ if (operation.request_id !== request.request_id) {
121
+ throw new CloudProtocolError("Cloud operation request_id does not match the GenerateRequest.");
122
+ }
123
+ return operation;
124
+ }
125
+ function takeLines(buffer, atEnd) {
126
+ const lines = [];
127
+ let start = 0;
128
+ for (let index = 0; index < buffer.length; index += 1) {
129
+ const character = buffer[index];
130
+ if (character !== "\r" && character !== "\n")
131
+ continue;
132
+ if (character === "\r" && index === buffer.length - 1 && !atEnd)
133
+ break;
134
+ lines.push(buffer.slice(start, index));
135
+ if (character === "\r" && buffer[index + 1] === "\n")
136
+ index += 1;
137
+ start = index + 1;
138
+ }
139
+ if (atEnd && start < buffer.length) {
140
+ lines.push(buffer.slice(start));
141
+ start = buffer.length;
142
+ }
143
+ return { lines, rest: buffer.slice(start) };
144
+ }
145
+ /**
146
+ * Turn a Cloud refusal into a `CloudHttpError` that keeps what Cloud said.
147
+ *
148
+ * Every Cloud refusal is `{"error": {"code", "message", ...}}`. Anything else (a proxy's HTML
149
+ * page, an empty body) is not a sentence Cloud wrote for the caller, so only the status code
150
+ * is reported. A message without the rest of the contract is still shown, but only an
151
+ * object that matches `GenerationError` is handed over for a program to branch on.
152
+ */
153
+ async function httpError(label, response) {
154
+ const payload = await errorPayload(response);
155
+ const error = typeof payload === "object" && payload !== null && "error" in payload
156
+ ? payload.error
157
+ : undefined;
158
+ const raw = typeof error === "object" && error !== null && "message" in error
159
+ ? error.message
160
+ : undefined;
161
+ const message = typeof raw === "string" && raw
162
+ ? Array.from(raw).slice(0, ERROR_MESSAGE_LIMIT).join("")
163
+ : undefined;
164
+ const cloudError = error !== undefined && validateContract("GenerationError", error).length === 0
165
+ ? error
166
+ : undefined;
167
+ return new CloudHttpError(response.status, `${label} failed with HTTP ${response.status}${message ? `: ${message}` : "."}`, cloudError);
168
+ }
169
+ /** Cloud says whether to retry; without a Cloud body, 429 and 5xx other than 501 are temporary. */
170
+ function isRetryable(error) {
171
+ return error.error?.retryable ?? (error.status === 429 || (error.status >= 500 && error.status !== 501));
172
+ }
173
+ async function errorPayload(response) {
174
+ const reader = response.body?.getReader();
175
+ if (!reader)
176
+ return undefined;
177
+ let payload;
178
+ try {
179
+ const chunks = [];
180
+ let size = 0;
181
+ while (true) {
182
+ const { done, value } = await reader.read();
183
+ if (done)
184
+ break;
185
+ size += value.byteLength;
186
+ if (size > ERROR_BODY_LIMIT_BYTES)
187
+ return undefined;
188
+ chunks.push(value);
189
+ }
190
+ const bytes = new Uint8Array(size);
191
+ let offset = 0;
192
+ for (const chunk of chunks) {
193
+ bytes.set(chunk, offset);
194
+ offset += chunk.byteLength;
195
+ }
196
+ payload = JSON.parse(new TextDecoder().decode(bytes));
197
+ }
198
+ catch {
199
+ return undefined;
200
+ }
201
+ finally {
202
+ try {
203
+ await reader.cancel();
204
+ }
205
+ catch {
206
+ // Closing must not replace the HTTP error we are reporting.
207
+ }
208
+ reader.releaseLock();
209
+ }
210
+ return payload;
211
+ }
212
+ function isAbortError(error, signal) {
213
+ if (signal?.aborted)
214
+ return true;
215
+ return typeof error === "object"
216
+ && error !== null
217
+ && "name" in error
218
+ && error.name === "AbortError";
219
+ }
220
+ function abortReason(signal) {
221
+ return signal.reason ?? new DOMException("Cloud generation was cancelled.", "AbortError");
222
+ }
223
+ async function waitBeforeReconnect(attempts, maxReconnects, reason, signal, cause, retryAfterMs) {
224
+ const nextAttempt = attempts + 1;
225
+ if (nextAttempt > maxReconnects) {
226
+ throw new CloudProtocolError(`${reason}, and reconnecting ${maxReconnects} time(s) did not reach a terminal event.`, { cause });
227
+ }
228
+ if (signal?.aborted)
229
+ throw abortReason(signal);
230
+ const delay = Math.max(Math.min(RECONNECT_BACKOFF_MS * nextAttempt, 2_000), retryAfterMs ?? 0);
231
+ await new Promise((resolve, reject) => {
232
+ const timer = setTimeout(finish, delay);
233
+ const onAbort = () => {
234
+ clearTimeout(timer);
235
+ signal?.removeEventListener("abort", onAbort);
236
+ reject(signal ? abortReason(signal) : new DOMException("Cloud generation was cancelled.", "AbortError"));
237
+ };
238
+ function finish() {
239
+ signal?.removeEventListener("abort", onAbort);
240
+ resolve();
241
+ }
242
+ signal?.addEventListener("abort", onAbort, { once: true });
243
+ });
244
+ return nextAttempt;
245
+ }
246
+ async function* sseData(body) {
247
+ const reader = body.getReader();
248
+ const decoder = new TextDecoder();
249
+ let buffer = "";
250
+ let dataLines = [];
251
+ let reachedEnd = false;
252
+ const processLine = (line) => {
253
+ if (line === "") {
254
+ if (dataLines.length === 0)
255
+ return undefined;
256
+ const payload = dataLines.join("\n");
257
+ dataLines = [];
258
+ return payload;
259
+ }
260
+ if (line.startsWith(":"))
261
+ return undefined;
262
+ const separator = line.indexOf(":");
263
+ const field = separator === -1 ? line : line.slice(0, separator);
264
+ let value = separator === -1 ? "" : line.slice(separator + 1);
265
+ if (value.startsWith(" "))
266
+ value = value.slice(1);
267
+ if (field === "data")
268
+ dataLines.push(value);
269
+ return undefined;
270
+ };
271
+ try {
272
+ while (true) {
273
+ const chunk = await reader.read();
274
+ if (chunk.done) {
275
+ reachedEnd = true;
276
+ buffer += decoder.decode();
277
+ const drained = takeLines(buffer, true);
278
+ buffer = drained.rest;
279
+ for (const line of drained.lines) {
280
+ const payload = processLine(line);
281
+ if (payload !== undefined)
282
+ yield payload;
283
+ }
284
+ if (dataLines.length > 0)
285
+ yield dataLines.join("\n");
286
+ return;
287
+ }
288
+ buffer += decoder.decode(chunk.value, { stream: true });
289
+ const drained = takeLines(buffer, false);
290
+ buffer = drained.rest;
291
+ for (const line of drained.lines) {
292
+ const payload = processLine(line);
293
+ if (payload !== undefined)
294
+ yield payload;
295
+ }
296
+ }
297
+ }
298
+ finally {
299
+ try {
300
+ if (!reachedEnd)
301
+ await reader.cancel();
302
+ }
303
+ catch {
304
+ // Closing is best effort and must not replace the read or protocol error.
305
+ }
306
+ finally {
307
+ reader.releaseLock();
308
+ }
309
+ }
310
+ }
311
+ export class CloudGenerator {
312
+ #baseUrl;
313
+ #createUrl;
314
+ #generationUrl;
315
+ #modelsUrl;
316
+ #apiToken;
317
+ #fetch;
318
+ #headers;
319
+ #maxReconnects;
320
+ constructor(options) {
321
+ if (!/^https?:\/\//u.test(options.baseUrl)) {
322
+ throw new TypeError("Cloud baseUrl must be an absolute HTTP(S) URL.");
323
+ }
324
+ const transport = options.fetch ?? globalThis.fetch;
325
+ if (!transport)
326
+ throw new TypeError("CloudGenerator requires a fetch transport.");
327
+ this.#baseUrl = options.baseUrl;
328
+ const createUrl = apiUrl(options.baseUrl, options.generationPath ?? DEFAULT_GENERATION_PATH);
329
+ const endpoint = new URL(createUrl);
330
+ this.#generationUrl = `${endpoint.origin}${endpoint.pathname.replace(/\/$/u, "")}`;
331
+ this.#modelsUrl = apiUrl(options.baseUrl, DEFAULT_MODELS_PATH);
332
+ if (options.partialUi)
333
+ endpoint.searchParams.set("partial_ui", "true");
334
+ if (options.engine)
335
+ endpoint.searchParams.set("engine", options.engine);
336
+ this.#createUrl = endpoint.toString();
337
+ this.#apiToken = options.apiToken;
338
+ this.#fetch = transport;
339
+ this.#headers = options.headers ?? {};
340
+ const maxReconnects = options.maxReconnects ?? DEFAULT_MAX_RECONNECTS;
341
+ if (!Number.isInteger(maxReconnects) || maxReconnects < 0) {
342
+ throw new TypeError("Cloud maxReconnects must be a non-negative integer.");
343
+ }
344
+ this.#maxReconnects = maxReconnects;
345
+ }
346
+ /**
347
+ * Create a run and yield its events. `request.request_id` is also the `Idempotency-Key`,
348
+ * so it names one attempt: sending it again returns that run, even one that failed. To
349
+ * generate again, send a new `request_id`.
350
+ */
351
+ generate(request, signal) {
352
+ const issues = validateContract("GenerateRequest", request);
353
+ if (issues.length > 0)
354
+ throw new CloudProtocolError(formatIssues("GenerateRequest", issues));
355
+ return this.#stream(request, signal);
356
+ }
357
+ /** Return model IDs accepted by this deployment and both product defaults. */
358
+ async listModels(signal) {
359
+ const response = await this.#fetch(this.#modelsUrl, {
360
+ method: "GET", headers: this.#jsonHeaders(), signal,
361
+ });
362
+ if (!response.ok)
363
+ throw await httpError("Cloud models query", response);
364
+ let payload;
365
+ try {
366
+ payload = await response.json();
367
+ }
368
+ catch (error) {
369
+ throw new CloudProtocolError("Cloud models query is not valid JSON.", { cause: error });
370
+ }
371
+ return readModelCatalog(payload);
372
+ }
373
+ /** Recover the latest complete artifact after a refresh response or connection was lost. */
374
+ async getArtifact(request, runId, signal) {
375
+ const response = await this.#fetch(`${this.#generationUrl}/${encodeURIComponent(runId)}`, {
376
+ method: "GET", headers: this.#jsonHeaders(), signal,
377
+ });
378
+ if (!response.ok)
379
+ throw await httpError("Cloud generation query", response);
380
+ let payload;
381
+ try {
382
+ payload = await response.json();
383
+ }
384
+ catch (error) {
385
+ throw new CloudProtocolError("Cloud generation query is not valid JSON.", { cause: error });
386
+ }
387
+ if (typeof payload !== "object" || payload === null)
388
+ throw new CloudProtocolError("Cloud generation query must be an operation object.");
389
+ const operation = payload;
390
+ if (operation.run_id !== runId || operation.request_id !== request.request_id) {
391
+ throw new CloudProtocolError("Cloud generation query correlation does not match the request and run.");
392
+ }
393
+ const issues = validateContract("SurfaceArtifact", operation.artifact);
394
+ if (issues.length)
395
+ throw new CloudProtocolError(formatIssues("SurfaceArtifact", issues));
396
+ const artifact = operation.artifact;
397
+ if (artifact.run_id !== runId || artifact.request_id !== request.request_id) {
398
+ throw new CloudProtocolError("Cloud artifact correlation does not match the request and run.");
399
+ }
400
+ return artifact;
401
+ }
402
+ /** Refresh raw JSON, then recover the complete artifact to pass to HostBridge.attach().
403
+ * A failed POST or GET leaves the caller's previous artifact untouched. A network error
404
+ * may follow a committed POST: use getArtifact() to recover before retrying the write.
405
+ */
406
+ async updateData(request, runId, data, signal) {
407
+ const body = dataUpdateBody(data);
408
+ const response = await this.#fetch(`${this.#generationUrl}/${encodeURIComponent(runId)}/data-updates`, {
409
+ method: "POST", headers: { ...this.#jsonHeaders(), "Content-Type": "application/json" },
410
+ body, signal,
411
+ });
412
+ if (!response.ok)
413
+ throw await httpError("Cloud data update", response);
414
+ let payload;
415
+ try {
416
+ payload = await response.json();
417
+ }
418
+ catch (error) {
419
+ throw new CloudProtocolError("Cloud data update is not valid JSON.", { cause: error });
420
+ }
421
+ if (typeof payload !== "object" || payload === null)
422
+ throw new CloudProtocolError("Cloud data update must be an object.");
423
+ const update = payload;
424
+ if (update.run_id !== runId || update.request_id !== request.request_id || !Number.isInteger(update.revision)) {
425
+ throw new CloudProtocolError("Cloud data update correlation or revision is invalid.");
426
+ }
427
+ const artifact = await this.getArtifact(request, runId, signal);
428
+ if (artifact.surface_id !== update.surface_id || artifact.revision < update.revision) {
429
+ throw new CloudProtocolError("Cloud query did not return the committed surface revision.");
430
+ }
431
+ return artifact;
432
+ }
433
+ #jsonHeaders() {
434
+ return {
435
+ ...this.#headers, "X-LittlePress-Contract-Version": CONTRACT_VERSION, Accept: "application/json",
436
+ ...(this.#apiToken ? { Authorization: `Bearer ${this.#apiToken}` } : {}),
437
+ };
438
+ }
439
+ async *#stream(request, signal) {
440
+ const commonHeaders = {
441
+ ...this.#headers,
442
+ "X-LittlePress-Contract-Version": CONTRACT_VERSION,
443
+ };
444
+ if (this.#apiToken)
445
+ commonHeaders.Authorization = `Bearer ${this.#apiToken}`;
446
+ const createResponse = await this.#fetch(this.#createUrl, {
447
+ method: "POST",
448
+ headers: {
449
+ ...commonHeaders,
450
+ Accept: "application/json",
451
+ "Content-Type": "application/json",
452
+ "Idempotency-Key": request.request_id,
453
+ // Answer 202 at once; the events are read from event_url below.
454
+ Prefer: "respond-async",
455
+ },
456
+ body: JSON.stringify(request),
457
+ signal,
458
+ });
459
+ if (!createResponse.ok)
460
+ throw await httpError("Cloud generation request", createResponse);
461
+ let operationPayload;
462
+ try {
463
+ operationPayload = await createResponse.json();
464
+ }
465
+ catch (error) {
466
+ throw new CloudProtocolError(`Cloud create response is not valid JSON: ${String(error)}`);
467
+ }
468
+ const operation = parseOperation(operationPayload, request);
469
+ const eventUrl = linkedUrl(this.#baseUrl, operation.event_url, "event_url");
470
+ const statusUrl = linkedUrl(this.#baseUrl, operation.status_url, "status_url");
471
+ let terminal = false;
472
+ let previousSequence;
473
+ let attempts = 0;
474
+ try {
475
+ // A closed stream is expected rather than exceptional. Cloud Run caps how long one
476
+ // request may live and replaces instances on deploy; its guidance is that clients
477
+ // reconnect. Resume from the last delivered sequence; the server can replay only
478
+ // retained events, which may be terminal-only after a restart.
479
+ while (!terminal) {
480
+ const headers = { ...commonHeaders, Accept: "text/event-stream" };
481
+ if (previousSequence !== undefined)
482
+ headers["Last-Event-ID"] = String(previousSequence);
483
+ let response;
484
+ try {
485
+ response = await this.#fetch(eventUrl, { method: "GET", headers, signal });
486
+ }
487
+ catch (error) {
488
+ if (!(error instanceof TypeError) || isAbortError(error, signal))
489
+ throw error;
490
+ attempts = await waitBeforeReconnect(attempts, this.#maxReconnects, "Cloud SSE transport failed", signal, error);
491
+ continue;
492
+ }
493
+ if (!response.ok) {
494
+ // The run is still going. Cancelling it over a temporary error would leave the
495
+ // caller nothing to come back to, so treat it like an early close.
496
+ const error = await httpError("Cloud event stream", response);
497
+ if (!isRetryable(error))
498
+ throw error;
499
+ attempts = await waitBeforeReconnect(attempts, this.#maxReconnects, "Cloud event stream answered a retryable HTTP error", signal, error, error.error?.retry_after_ms);
500
+ continue;
501
+ }
502
+ const contentType = response.headers.get("content-type")?.toLowerCase() ?? "";
503
+ if (!contentType.startsWith("text/event-stream")) {
504
+ try {
505
+ await response.body?.cancel();
506
+ }
507
+ catch {
508
+ // The media-type error remains the useful failure.
509
+ }
510
+ throw new CloudProtocolError(`Cloud response must be text/event-stream, received ${contentType || "no content type"}.`);
511
+ }
512
+ if (!response.body)
513
+ throw new CloudProtocolError("Cloud response has no SSE body.");
514
+ try {
515
+ for await (const data of sseData(response.body)) {
516
+ if (terminal)
517
+ throw new CloudProtocolError("Cloud stream sent an event after a terminal event.");
518
+ let payload;
519
+ try {
520
+ payload = JSON.parse(data);
521
+ }
522
+ catch (error) {
523
+ throw new CloudProtocolError(`Cloud SSE data is not valid JSON: ${String(error)}`);
524
+ }
525
+ const issues = validateContract("GenerationEvent", payload);
526
+ if (issues.length > 0)
527
+ throw new CloudProtocolError(formatIssues("GenerationEvent", issues));
528
+ const event = payload;
529
+ if (event.request_id !== request.request_id) {
530
+ throw new CloudProtocolError("Cloud event request_id does not match the GenerateRequest.");
531
+ }
532
+ if (event.run_id !== operation.run_id) {
533
+ throw new CloudProtocolError("Cloud event run_id does not match the generation operation.");
534
+ }
535
+ if (previousSequence !== undefined && event.sequence <= previousSequence) {
536
+ throw new CloudProtocolError("Cloud event sequence must strictly increase.");
537
+ }
538
+ previousSequence = event.sequence;
539
+ terminal = event.event === "completed" || event.event === "failed" || event.event === "cancelled";
540
+ yield event;
541
+ }
542
+ }
543
+ catch (error) {
544
+ if (!(error instanceof TypeError) || isAbortError(error, signal))
545
+ throw error;
546
+ attempts = await waitBeforeReconnect(attempts, this.#maxReconnects, "Cloud SSE transport failed", signal, error);
547
+ continue;
548
+ }
549
+ if (terminal)
550
+ break;
551
+ attempts = await waitBeforeReconnect(attempts, this.#maxReconnects, "Cloud SSE stream ended before a terminal event", signal);
552
+ }
553
+ }
554
+ finally {
555
+ if (!terminal) {
556
+ const cancelController = new AbortController();
557
+ let cancelTimer;
558
+ const timeout = new Promise((resolve) => {
559
+ cancelTimer = setTimeout(() => {
560
+ cancelController.abort(new DOMException("Cloud cancellation request timed out.", "TimeoutError"));
561
+ resolve();
562
+ }, CANCEL_CLEANUP_TIMEOUT_MS);
563
+ });
564
+ try {
565
+ const cancelRequest = this.#fetch(`${statusUrl}/cancel`, {
566
+ method: "POST",
567
+ headers: { ...commonHeaders, Accept: "application/json" },
568
+ signal: cancelController.signal,
569
+ }).then(async (cancelResponse) => cancelResponse.body?.cancel());
570
+ await Promise.race([cancelRequest, timeout]);
571
+ }
572
+ catch {
573
+ // Best effort: cancellation must not hide the stream's original error.
574
+ }
575
+ finally {
576
+ if (cancelTimer !== undefined)
577
+ clearTimeout(cancelTimer);
578
+ }
579
+ }
580
+ }
581
+ }
582
+ }
583
+ export const DEFAULT_ANSWER_COMPILE_PATH = "/v1/answers/compile";
584
+ export const DEFAULT_ANSWER_GUIDE_PATH = "/v1/answers/authoring-guide";
585
+ /**
586
+ * One stateless call to `POST /v1/answers/compile`: the Markdown answer written so far in, the
587
+ * complete `SurfaceArtifact` for its revision out. A retry is the same request again.
588
+ * `AnswerStream` makes these calls as the answer grows.
589
+ */
590
+ export class CloudAnswerCompiler {
591
+ #url;
592
+ #guideUrl;
593
+ #apiToken;
594
+ #fetch;
595
+ #headers;
596
+ constructor(options) {
597
+ if (!/^https?:\/\//u.test(options.baseUrl))
598
+ throw new TypeError("Cloud baseUrl must be an absolute HTTP(S) URL.");
599
+ const transport = options.fetch ?? globalThis.fetch;
600
+ if (!transport)
601
+ throw new TypeError("CloudAnswerCompiler requires a fetch transport.");
602
+ this.#url = new URL(options.compilePath ?? DEFAULT_ANSWER_COMPILE_PATH, options.baseUrl).toString();
603
+ this.#guideUrl = new URL(options.guidePath ?? DEFAULT_ANSWER_GUIDE_PATH, options.baseUrl).toString();
604
+ this.#apiToken = options.apiToken;
605
+ this.#fetch = transport;
606
+ this.#headers = options.headers ?? {};
607
+ }
608
+ /**
609
+ * The LP-MDX authoring guide, Markdown for the system prompt of the model that writes the
610
+ * answer (`GET /v1/answers/authoring-guide`). The same text on every call until the service
611
+ * is updated, so read it once and keep it. It names no action and no data key:
612
+ * `answerSystemPrompt` adds the Host's section.
613
+ */
614
+ async getAuthoringGuide(signal) {
615
+ const response = await this.#fetch(this.#guideUrl, {
616
+ method: "GET",
617
+ headers: {
618
+ ...this.#headers,
619
+ Accept: "application/json",
620
+ ...(this.#apiToken ? { Authorization: `Bearer ${this.#apiToken}` } : {}),
621
+ },
622
+ signal,
623
+ });
624
+ if (!response.ok)
625
+ throw await httpError("Cloud authoring guide", response);
626
+ let payload;
627
+ try {
628
+ payload = await response.json();
629
+ }
630
+ catch (error) {
631
+ throw new CloudProtocolError("Cloud authoring guide is not valid JSON.", { cause: error });
632
+ }
633
+ const body = (typeof payload === "object" && payload !== null ? payload : {});
634
+ if (body.format !== "lp-mdx" || typeof body.guide !== "string" || !body.guide) {
635
+ throw new CloudProtocolError("Cloud authoring guide has no LP-MDX guide.");
636
+ }
637
+ return body.guide;
638
+ }
639
+ async compile(request, signal) {
640
+ const issues = validateContract("AnswerCompileRequest", request);
641
+ if (issues.length)
642
+ throw new CloudProtocolError(formatIssues("AnswerCompileRequest", issues));
643
+ const response = await this.#fetch(this.#url, {
644
+ method: "POST",
645
+ headers: {
646
+ ...this.#headers,
647
+ Accept: "application/json",
648
+ "Content-Type": "application/json",
649
+ ...(this.#apiToken ? { Authorization: `Bearer ${this.#apiToken}` } : {}),
650
+ },
651
+ body: JSON.stringify(request),
652
+ signal,
653
+ });
654
+ if (!response.ok)
655
+ throw await httpError("Cloud answer compile", response);
656
+ let artifact;
657
+ try {
658
+ artifact = await response.json();
659
+ }
660
+ catch (error) {
661
+ throw new CloudProtocolError("Cloud answer compile is not valid JSON.", { cause: error });
662
+ }
663
+ const artifactIssues = validateContract("SurfaceArtifact", artifact);
664
+ if (artifactIssues.length)
665
+ throw new CloudProtocolError(formatIssues("SurfaceArtifact", artifactIssues));
666
+ const typed = artifact;
667
+ if (typed.surface_id !== request.surface_id || typed.revision !== request.revision || typed.request_id !== request.request_id) {
668
+ throw new CloudProtocolError("Cloud answer compile correlation does not match the request.");
669
+ }
670
+ return typed;
671
+ }
672
+ }