@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.
@@ -0,0 +1,564 @@
1
+ import { CONTRACT_VERSION, } from "@littlepress/ui-foundation-contracts";
2
+ import { CloudProtocolError } from "./cloud.js";
3
+ /*
4
+ * Whole answers, Host side. The Host's own model writes Markdown; `AnswerStream` sends the
5
+ * text so far to `POST /v1/answers/compile` (one request in flight, the newest text waiting),
6
+ * and turns each compiled artifact into either the first snapshot or a `SurfaceUpdate` for the
7
+ * app that draws it. The app applies updates with `LittlePressSurfaceStream` and asks for a
8
+ * snapshot when it cannot; call `resync()` then.
9
+ */
10
+ /*
11
+ * The prompt for an LP-MDX answer. `CloudAnswerCompiler.getAuthoringGuide()` reads the guide;
12
+ * `answerSystemPrompt` puts it together with the Host's own section, which `answerHostSection`
13
+ * renders from the Host's instructions, actions, data and exports. The Python SDK writes the same text
14
+ * (`answer_host_section`, `answer_system_prompt`).
15
+ */
16
+ /** How many top-level keys of `data`, and keys of one object, the Host's section describes. */
17
+ const MAX_DATA_KEYS = 40;
18
+ const MAX_OBJECT_KEYS = 12;
19
+ const MAX_DEPTH = 3;
20
+ /**
21
+ * What `AnswerCompileRequest.exports` accepts: at most 16 unique JSON Pointers below `/data/`,
22
+ * each at most 512 characters, with no empty segment and only `~0`/`~1` escapes.
23
+ */
24
+ const MAX_EXPORTS = 16;
25
+ const MAX_EXPORT_LENGTH = 512;
26
+ const EXPORT_PATH = /^\/data(?:\/(?:[^/~]|~[01])+)+$/u;
27
+ /**
28
+ * Object keys in Unicode code-point order, as the Python SDK sorts them. JSON key order is not
29
+ * kept alike: JavaScript puts integer-like keys such as `"1"` first, and its default sort
30
+ * compares UTF-16 code units, not code points.
31
+ */
32
+ function sortedKeys(value) {
33
+ return codePointSorted(Object.keys(value));
34
+ }
35
+ function codePointSorted(values) {
36
+ const points = (key) => Array.from(key, (character) => character.codePointAt(0));
37
+ return [...values].sort((a, b) => {
38
+ const left = points(a);
39
+ const right = points(b);
40
+ for (let at = 0; at < Math.min(left.length, right.length); at += 1) {
41
+ if (left[at] !== right[at])
42
+ return left[at] - right[at];
43
+ }
44
+ return left.length - right.length;
45
+ });
46
+ }
47
+ /**
48
+ * `exports` as given, checked by the rules of `AnswerCompileRequest.exports`, so a bad path
49
+ * fails here rather than on every compile. The Python SDK checks the same rules.
50
+ */
51
+ function exportPaths(exports) {
52
+ if (exports === null || exports === undefined)
53
+ return [];
54
+ if (typeof exports === "string")
55
+ throw new TypeError("exports is a list of /data/ paths, not one path.");
56
+ const paths = [...exports];
57
+ if (paths.length > MAX_EXPORTS)
58
+ throw new TypeError(`exports lists at most ${MAX_EXPORTS} paths.`);
59
+ for (const path of paths) {
60
+ if (typeof path !== "string" || Array.from(path).length > MAX_EXPORT_LENGTH || !EXPORT_PATH.test(path)) {
61
+ throw new TypeError(`exports: ${JSON.stringify(path)} is not a JSON Pointer below /data/ of at most ${MAX_EXPORT_LENGTH} characters.`);
62
+ }
63
+ }
64
+ if (new Set(paths).size !== paths.length)
65
+ throw new TypeError("exports: export paths must be unique.");
66
+ return paths;
67
+ }
68
+ function fieldType(schema) {
69
+ if (!isRecord(schema))
70
+ return "any";
71
+ if ("const" in schema)
72
+ return JSON.stringify(schema.const);
73
+ if (Array.isArray(schema.enum))
74
+ return schema.enum.map((value) => JSON.stringify(value)).join("|");
75
+ if (Array.isArray(schema.type))
76
+ return schema.type.map(String).join("|");
77
+ return typeof schema.type === "string" ? schema.type : "any";
78
+ }
79
+ function payloadFields(schema) {
80
+ const properties = schema.properties;
81
+ if (!isRecord(properties) || !Object.keys(properties).length)
82
+ return "{}";
83
+ const needed = new Set(Array.isArray(schema.required) ? schema.required : []);
84
+ const fields = sortedKeys(properties).map((name) => `${name}${needed.has(name) ? "" : "?"}: ${fieldType(properties[name])}`);
85
+ return `{${fields.join(", ")}}`;
86
+ }
87
+ /** What a JSON value looks like, without its values. */
88
+ function shape(value, depth = 0) {
89
+ if (value === null || value === undefined)
90
+ return "null";
91
+ if (typeof value === "boolean")
92
+ return "boolean";
93
+ if (typeof value === "number")
94
+ return "number";
95
+ if (typeof value === "string")
96
+ return value.startsWith("https://") ? "URL" : "string";
97
+ if (Array.isArray(value))
98
+ return value.length ? `list of ${value.length} × ${shape(value[0], depth + 1)}` : "empty list";
99
+ if (isRecord(value)) {
100
+ if (depth >= MAX_DEPTH)
101
+ return "object";
102
+ const keys = sortedKeys(value);
103
+ const fields = keys.slice(0, MAX_OBJECT_KEYS).map((key) => `${key}: ${shape(value[key], depth + 1)}`);
104
+ if (keys.length > MAX_OBJECT_KEYS)
105
+ fields.push("…");
106
+ return `{${fields.join(", ")}}`;
107
+ }
108
+ return "any";
109
+ }
110
+ /**
111
+ * The Host's part of the prompt for an LP-MDX answer, written after the authoring guide: the
112
+ * `instructions` as written, each action an answer may name with its payload fields (`?` marks
113
+ * an optional one), and each top-level key of `data` as a `/data/` path with the shape of its
114
+ * value, never the value itself. Keys are listed in Unicode code-point order at every level,
115
+ * before the lists are cut to their limits. `exports` (the `/data/` paths the reader may save
116
+ * with `<download>`) are listed after the data, as written and in code-point order, only when
117
+ * there are any; a path the compile request would refuse throws a `TypeError`.
118
+ */
119
+ function oneLine(value) {
120
+ return value.trim().split(/\s+/u).filter(Boolean).join(" ");
121
+ }
122
+ export function answerHostSection(options = {}) {
123
+ const lines = ["## From the Host"];
124
+ const instructions = options.instructions?.trim();
125
+ if (instructions)
126
+ lines.push("", instructions);
127
+ const actions = options.actions ?? [];
128
+ lines.push("", actions.length ? "Actions you may name:" : "Actions: none.");
129
+ for (const action of actions)
130
+ lines.push(`- \`${action.name}\` ${payloadFields(action.payload_schema)}`);
131
+ const data = options.data ?? {};
132
+ const keys = sortedKeys(data);
133
+ lines.push("", keys.length ? "Data you may read (shapes, not values):" : "Data: none.");
134
+ for (const key of keys.slice(0, MAX_DATA_KEYS))
135
+ lines.push(`- \`/data/${escape(key)}\`: ${shape(data[key], 1)}`);
136
+ if (keys.length > MAX_DATA_KEYS)
137
+ lines.push(`- and ${keys.length - MAX_DATA_KEYS} more`);
138
+ const paths = codePointSorted(exportPaths(options.exports));
139
+ if (paths.length)
140
+ lines.push("", "Data you may offer for download (with <download>):", ...paths.map((path) => `- \`${path}\``));
141
+ const sources = options.sources ?? [];
142
+ if (sources.length) {
143
+ lines.push("", "Sources you may cite (`<cite source=\"id\"/>`):");
144
+ for (const source of sources) {
145
+ let label;
146
+ if (source.kind === "code" && source.path && typeof source.line_start === "number") {
147
+ const range = typeof source.line_end === "number" && source.line_end > source.line_start
148
+ ? `${source.line_start}-${source.line_end}`
149
+ : `${source.line_start}`;
150
+ label = oneLine(`${source.path}:${range}`);
151
+ }
152
+ else if (source.kind === "file" && source.file_name) {
153
+ label = oneLine(source.file_name);
154
+ }
155
+ else {
156
+ label = oneLine(source.site ?? source.title);
157
+ }
158
+ lines.push(`- \`${source.id}\`: ${oneLine(source.title)} (${label})`);
159
+ }
160
+ }
161
+ const entities = options.entities ?? [];
162
+ if (entities.length) {
163
+ lines.push("", "Entities you may tag (`<entity id=\"id\"/>`):");
164
+ for (const entity of entities)
165
+ lines.push(`- \`${entity.id}\`: ${oneLine(entity.name)} (${oneLine(entity.category)})`);
166
+ }
167
+ return `${lines.join("\n")}\n`;
168
+ }
169
+ /** The system prompt section for an LP-MDX answer: the guide, then the Host's section. */
170
+ export function answerSystemPrompt(guide, options = {}) {
171
+ return `${guide.trimEnd()}\n\n${answerHostSection(options)}`;
172
+ }
173
+ /** The shortest gap between two compile requests; slower compiles set a slower pace. */
174
+ export const DEFAULT_ANSWER_INTERVAL_MS = 150;
175
+ function createOf(artifact) {
176
+ const create = artifact.messages[0]?.createSurface;
177
+ if (!create || typeof create !== "object")
178
+ throw new CloudProtocolError("An answer artifact starts with one createSurface.");
179
+ return create;
180
+ }
181
+ function isRecord(value) {
182
+ return typeof value === "object" && value !== null && !Array.isArray(value);
183
+ }
184
+ function same(a, b) {
185
+ return JSON.stringify(a) === JSON.stringify(b);
186
+ }
187
+ function escape(token) {
188
+ return token.replace(/~/gu, "~0").replace(/\//gu, "~1");
189
+ }
190
+ function unescape(token) {
191
+ return token.replace(/~1/gu, "/").replace(/~0/gu, "~");
192
+ }
193
+ // The renderer's JSON Pointer rules (renderer-web `pointer.ts`), so a Widget folds here as it
194
+ // draws there: a missing container is an array when the next token is a number, `-` appends.
195
+ const index = (token) => /^\d+$/u.test(token);
196
+ function readToken(container, token) {
197
+ if (Array.isArray(container))
198
+ return index(token) ? container[Number(token)] : undefined;
199
+ return isRecord(container) ? container[token] : undefined;
200
+ }
201
+ function cloneContainer(container, next) {
202
+ if (Array.isArray(container))
203
+ return [...container];
204
+ if (isRecord(container))
205
+ return { ...container };
206
+ return index(next) ? [] : {};
207
+ }
208
+ function assign(container, token, value) {
209
+ if (Array.isArray(container))
210
+ container[token === "-" ? container.length : Number(token)] = value;
211
+ else
212
+ container[token] = value;
213
+ }
214
+ /** `root` with `value` written at `pointer`; `null` deletes, as an A2UI data update does. */
215
+ function writePointer(root, pointer, value) {
216
+ const path = pointer === "/" ? "" : pointer;
217
+ if (path === "")
218
+ return value === null ? {} : value;
219
+ if (!path.startsWith("/"))
220
+ return root;
221
+ const tokens = path.slice(1).split("/").map(unescape);
222
+ const result = cloneContainer(root, tokens[0]);
223
+ let cursor = result;
224
+ for (let position = 0; position < tokens.length - 1; position += 1) {
225
+ const child = cloneContainer(readToken(cursor, tokens[position]), tokens[position + 1]);
226
+ assign(cursor, tokens[position], child);
227
+ cursor = child;
228
+ }
229
+ const last = tokens[tokens.length - 1];
230
+ if (value !== null)
231
+ assign(cursor, last, value);
232
+ else if (Array.isArray(cursor)) {
233
+ const at = Number(last);
234
+ if (Number.isInteger(at) && at >= 0 && at < cursor.length)
235
+ cursor.splice(at, 1);
236
+ }
237
+ else
238
+ delete cursor[last];
239
+ return result;
240
+ }
241
+ /** A Widget's `/data` after all of its messages, as the compiler folds them into the answer. */
242
+ function widgetData(widget) {
243
+ let model = {};
244
+ for (const message of widget.messages) {
245
+ const create = message.createSurface;
246
+ const update = message.updateDataModel;
247
+ if (create)
248
+ model = create.dataModel ?? {};
249
+ else if (update)
250
+ model = writePointer(model, update.path ?? "", update.value ?? null);
251
+ }
252
+ return isRecord(model) ? model.data : undefined;
253
+ }
254
+ /**
255
+ * The answer's `/data` once its Widget's data goes from `before` to `after` (`undefined` is no
256
+ * `data` at all). An LP-MDX answer keeps its own keys in `/data` next to the Widget's (the
257
+ * compiler merges them and refuses a key both use). A refresh replaces only the Widget's keys
258
+ * and keeps the answer's; a refreshed Widget that now uses one of the answer's keys is refused,
259
+ * as the compiler refuses it.
260
+ */
261
+ function refreshedData(current, before, after) {
262
+ const widgetKeys = new Set(isRecord(before) ? Object.keys(before) : []);
263
+ const own = {};
264
+ if (isRecord(current) && (before === undefined || isRecord(before))) {
265
+ for (const [key, value] of Object.entries(current))
266
+ if (!widgetKeys.has(key))
267
+ own[key] = value;
268
+ }
269
+ if (!Object.keys(own).length)
270
+ return after;
271
+ if (after === undefined)
272
+ return own;
273
+ if (!isRecord(after))
274
+ throw new Error("refreshWidget(): the Widget's data would replace the answer's `/data`.");
275
+ const shared = Object.keys(own).filter((key) => key in after).sort();
276
+ if (shared.length)
277
+ throw new Error(`refreshWidget(): the Widget's data \`/data/${shared[0]}\` would replace the answer's.`);
278
+ return { ...own, ...after };
279
+ }
280
+ /**
281
+ * Data-model writes that turn `before` into `after`, or `false` when only a whole snapshot can.
282
+ * A write of `null` deletes a field, so a field that becomes `null` is written with its whole
283
+ * parent object instead; at the root that would replace the whole model, which a finished
284
+ * answer refuses, so it needs a snapshot.
285
+ */
286
+ function dataWrites(before, after, path, out) {
287
+ if (same(before, after))
288
+ return true;
289
+ if (!isRecord(before) || !isRecord(after)) {
290
+ if (path === "")
291
+ return false;
292
+ out.push({ path, value: after });
293
+ return true;
294
+ }
295
+ const becomesNull = Object.keys(after).some((key) => after[key] === null && !(key in before && before[key] === null));
296
+ if (becomesNull) {
297
+ if (path === "")
298
+ return false;
299
+ out.push({ path, value: after });
300
+ return true;
301
+ }
302
+ for (const key of new Set([...Object.keys(before), ...Object.keys(after)])) {
303
+ const child = `${path}/${escape(key)}`;
304
+ if (!(key in after))
305
+ out.push({ path: child, value: null });
306
+ else if (!dataWrites(before[key], after[key], child, out))
307
+ return false;
308
+ }
309
+ return true;
310
+ }
311
+ /** Everything `createSurface` says besides its components and data: catalog, renderer hints. */
312
+ function surfaceSettings(create) {
313
+ const settings = { ...create };
314
+ delete settings.components;
315
+ delete settings.dataModel;
316
+ return settings;
317
+ }
318
+ /**
319
+ * The update that turns `previous` into `next`, or `"snapshot"` when it cannot be expressed
320
+ * as updates of the same surface (another surface, catalog or renderer hints, a field of the
321
+ * root that becomes `null`), or `null` when nothing changed. Both are compile results: one
322
+ * `createSurface` each.
323
+ */
324
+ export function diffArtifacts(previous, next) {
325
+ const before = createOf(previous);
326
+ const after = createOf(next);
327
+ // Updates carry only components and data: anything else createSurface says (the catalog, the
328
+ // renderer hints such as mode or style pack) changes only with a snapshot.
329
+ if (previous.surface_id !== next.surface_id || next.revision <= previous.revision
330
+ || previous.messages.length !== 1 || next.messages.length !== 1
331
+ || !same(surfaceSettings(before), surfaceSettings(after))) {
332
+ return "snapshot";
333
+ }
334
+ const old = new Map(before.components.map((component) => [String(component.id), component]));
335
+ const changed = after.components.filter((component) => !same(old.get(String(component.id)), component));
336
+ const writes = [];
337
+ if (!dataWrites(before.dataModel ?? {}, after.dataModel ?? {}, "", writes))
338
+ return "snapshot";
339
+ if (!changed.length && !writes.length)
340
+ return null;
341
+ const messages = [];
342
+ if (changed.length) {
343
+ messages.push({ version: "v1.0", updateComponents: { surfaceId: next.surface_id, components: changed } });
344
+ }
345
+ for (const write of writes) {
346
+ messages.push({ version: "v1.0", updateDataModel: { surfaceId: next.surface_id, path: write.path, value: write.value } });
347
+ }
348
+ return {
349
+ contract_version: CONTRACT_VERSION,
350
+ surface_id: next.surface_id,
351
+ base_revision: previous.revision,
352
+ revision: next.revision,
353
+ messages,
354
+ };
355
+ }
356
+ /** The longest id the contracts accept. */
357
+ const MAX_ID_LENGTH = 160;
358
+ /** `<surface>.r<revision>`, the surface part shortened when the whole would be too long. */
359
+ function defaultRequestId(surfaceId, revision) {
360
+ const suffix = `.r${revision}`;
361
+ return `${surfaceId.slice(0, MAX_ID_LENGTH - suffix.length)}${suffix}`;
362
+ }
363
+ /**
364
+ * Sends the answer as it grows and hands the app snapshots and updates. One compile is in
365
+ * flight at a time; text that arrives meanwhile waits, and only the newest text is sent next.
366
+ * Updates are computed against the last artifact actually handed out, never one that was not.
367
+ *
368
+ * An artifact that brings a script-block program the Host has not been handed yet (an asset
369
+ * key in `scripts` not seen before) is always handed out as a snapshot, so the Host receives
370
+ * the program's bytes in the same callback as the block that runs it, and can store them before
371
+ * it forwards the snapshot to the app.
372
+ */
373
+ export class AnswerStream {
374
+ #options;
375
+ #snapshotListeners = [];
376
+ #updateListeners = [];
377
+ #text = "";
378
+ #revision = 0;
379
+ #inFlight = false;
380
+ #pending = false;
381
+ #finishing = null;
382
+ #done = false;
383
+ #disposed = false;
384
+ #lastSent = null;
385
+ #latest = null;
386
+ #lastStarted = -Infinity;
387
+ #widgetRevision = null;
388
+ /** The Widget's `/data` as last handed out, so a refresh knows which keys are its own. */
389
+ #widgetData = undefined;
390
+ /** Asset keys of the script-block programs handed out so far, in snapshots. */
391
+ #handedScripts = new Set();
392
+ constructor(options) {
393
+ this.#options = options;
394
+ }
395
+ onSnapshot(listener) { this.#snapshotListeners.push(listener); }
396
+ onUpdate(listener) { this.#updateListeners.push(listener); }
397
+ /** Add model text. Sends at most one compile at a time, no faster than `minIntervalMs`. */
398
+ append(text) {
399
+ if (this.#disposed || this.#done)
400
+ return;
401
+ this.#text += text;
402
+ this.#request();
403
+ }
404
+ /** The model is done: compile once more with `done` and resolve with the final artifact. */
405
+ finish() {
406
+ if (this.#disposed)
407
+ return Promise.reject(new Error("The answer stream was cancelled."));
408
+ if (this.#finishing)
409
+ return Promise.reject(new Error("finish() was already called."));
410
+ this.#done = true;
411
+ return new Promise((resolve, reject) => {
412
+ this.#finishing = { resolve, reject };
413
+ this.#request(true);
414
+ });
415
+ }
416
+ /**
417
+ * The Widget after the finished answer was refreshed (the artifact `updateData` returns): hand
418
+ * the app its new data as an update of the answer, on top of the last revision handed out.
419
+ * Only the Widget's `/data` changes, which a done answer still takes; returns the update, or
420
+ * `null` when the data is the same or the refresh is not newer than the last one taken. It
421
+ * must be the same Widget: its request, run and surface. Attach the refreshed artifact with
422
+ * `attachAnswer` so its actions carry its new revision.
423
+ */
424
+ refreshWidget(widget) {
425
+ const current = this.#lastSent;
426
+ const state = current ? createOf(current).dataModel : undefined;
427
+ if (this.#disposed || !current || state?.runtimeState?.answerState !== "done" || this.#finishing) {
428
+ throw new Error("refreshWidget() needs a finished answer.");
429
+ }
430
+ const original = this.#options.widget;
431
+ if (!original || widget.surface_id !== original.surface_id || widget.request_id !== original.request_id
432
+ || widget.run_id !== original.run_id) {
433
+ throw new Error("refreshWidget() takes the Widget this answer was compiled with.");
434
+ }
435
+ // A late or repeated refresh is not newer than the Widget already handed out: nothing to send.
436
+ if (widget.revision <= (this.#widgetRevision ?? original.revision))
437
+ return null;
438
+ const next = JSON.parse(JSON.stringify(current));
439
+ // After everything sent so far, whatever the compiles numbered.
440
+ next.revision = Math.max(this.#revision, current.revision) + 1;
441
+ const model = createOf(next).dataModel;
442
+ const before = this.#widgetRevision === null ? widgetData(original) : this.#widgetData;
443
+ const after = widgetData(widget);
444
+ // Throws before anything changes when the Widget now uses one of the answer's keys.
445
+ const data = refreshedData("data" in model ? model.data : undefined, before, after);
446
+ this.#widgetRevision = widget.revision;
447
+ this.#widgetData = after;
448
+ if (data === undefined)
449
+ delete model.data;
450
+ else
451
+ model.data = data;
452
+ const update = diffArtifacts(current, next);
453
+ if (update === null)
454
+ return null;
455
+ this.#revision = next.revision;
456
+ this.#latest = next;
457
+ this.#handOut(next);
458
+ return update === "snapshot" ? null : update;
459
+ }
460
+ /** The app asked for a snapshot: hand out the newest artifact whole. */
461
+ resync() {
462
+ if (this.#disposed || !this.#latest)
463
+ return;
464
+ this.#snapshot(this.#latest);
465
+ }
466
+ /** Stop: no more requests and no more callbacks. */
467
+ cancel() {
468
+ this.#disposed = true;
469
+ this.#finishing?.reject(new Error("The answer stream was cancelled."));
470
+ this.#finishing = null;
471
+ }
472
+ #request(immediate = false) {
473
+ if (this.#inFlight) {
474
+ this.#pending = true;
475
+ return;
476
+ }
477
+ const now = this.#options.now?.() ?? Date.now();
478
+ const wait = immediate ? 0 : Math.max(0, this.#lastStarted + (this.#options.minIntervalMs ?? DEFAULT_ANSWER_INTERVAL_MS) - now);
479
+ this.#inFlight = true;
480
+ this.#pending = false;
481
+ const schedule = this.#options.schedule ?? ((run, delay) => setTimeout(run, delay));
482
+ schedule(() => void this.#send(), wait);
483
+ }
484
+ async #send() {
485
+ if (this.#disposed)
486
+ return;
487
+ this.#lastStarted = this.#options.now?.() ?? Date.now();
488
+ const done = this.#done;
489
+ const revision = ++this.#revision;
490
+ const request = {
491
+ contract_version: CONTRACT_VERSION,
492
+ request_id: this.#options.createRequestId?.(revision) ?? defaultRequestId(this.#options.surfaceId, revision),
493
+ surface_id: this.#options.surfaceId,
494
+ revision,
495
+ answer: this.#text,
496
+ done,
497
+ locale: this.#options.locale,
498
+ ...(done && this.#options.widget ? { widget: this.#options.widget } : {}),
499
+ ...(this.#options.format && this.#options.format !== "markdown" ? { format: this.#options.format } : {}),
500
+ ...(this.#options.actions ? { actions: this.#options.actions } : {}),
501
+ ...(this.#options.data ? { data: this.#options.data } : {}),
502
+ ...(this.#options.exports ? { exports: [...this.#options.exports] } : {}),
503
+ ...(this.#options.sources ? { sources: this.#options.sources } : {}),
504
+ ...(this.#options.entities ? { entities: this.#options.entities } : {}),
505
+ };
506
+ try {
507
+ const artifact = await this.#options.compiler.compile(request);
508
+ if (this.#disposed)
509
+ return;
510
+ if (!this.#latest || artifact.revision > this.#latest.revision)
511
+ this.#latest = artifact;
512
+ this.#handOut(artifact);
513
+ if (done) {
514
+ this.#finishing?.resolve(artifact);
515
+ this.#finishing = null;
516
+ this.#inFlight = false;
517
+ return;
518
+ }
519
+ }
520
+ catch (error) {
521
+ if (this.#disposed)
522
+ return;
523
+ if (done) {
524
+ this.#finishing?.reject(error);
525
+ this.#finishing = null;
526
+ this.#inFlight = false;
527
+ return;
528
+ }
529
+ // A failed in-progress compile is skipped; the next text (or finish) sends again.
530
+ }
531
+ this.#inFlight = false;
532
+ if (this.#done && this.#finishing)
533
+ this.#request(true);
534
+ else if (this.#pending)
535
+ this.#request();
536
+ }
537
+ #snapshot(artifact) {
538
+ this.#lastSent = artifact;
539
+ for (const script of artifact.scripts ?? [])
540
+ this.#handedScripts.add(script.asset_key);
541
+ for (const listener of this.#snapshotListeners)
542
+ listener(artifact);
543
+ }
544
+ #handOut(artifact) {
545
+ if (!this.#lastSent) {
546
+ this.#snapshot(artifact);
547
+ return;
548
+ }
549
+ if (artifact.revision <= this.#lastSent.revision)
550
+ return;
551
+ const update = diffArtifacts(this.#lastSent, artifact);
552
+ if (update === null)
553
+ return; // Nothing changed: the base stays the last artifact handed out.
554
+ const bringsScripts = (artifact.scripts ?? []).some((script) => !this.#handedScripts.has(script.asset_key));
555
+ if (update === "snapshot" || bringsScripts) {
556
+ // A block whose program the Host does not have yet comes with that program.
557
+ this.#snapshot(artifact);
558
+ return;
559
+ }
560
+ this.#lastSent = artifact;
561
+ for (const listener of this.#updateListeners)
562
+ listener(update);
563
+ }
564
+ }
@@ -0,0 +1,112 @@
1
+ import { type AnswerCompileRequest, type GenerateRequest, type GenerationError, type GenerationEvent, type Generator, type SurfaceArtifact } from "@littlepress/ui-foundation-contracts";
2
+ export declare const CLOUD_API_VERSION: "v1";
3
+ export declare const DEFAULT_GENERATION_PATH: "/v1/widget-generations";
4
+ export declare const DEFAULT_MODELS_PATH: "/v1/models";
5
+ export type FetchTransport = (input: string, init: RequestInit) => Promise<Response>;
6
+ export type CloudGeneratorOptions = {
7
+ baseUrl: string;
8
+ apiToken?: string;
9
+ fetch?: FetchTransport;
10
+ generationPath?: string;
11
+ headers?: Readonly<Record<string, string>>;
12
+ /**
13
+ * `true` asks Cloud to also emit partial artifacts as sections of the widget complete
14
+ * (progress events with stage `streaming`); the validated surface still ends the run.
15
+ * Default `false`: final surface only.
16
+ */
17
+ partialUi?: boolean;
18
+ /**
19
+ * `"offline"` asks for the deterministic engine: no model call and no cost, for your own
20
+ * tests and CI. Unset sends nothing and Cloud runs `live`, which answers 501
21
+ * `engine_not_configured` on a deployment with no model configured.
22
+ */
23
+ engine?: "live" | "offline";
24
+ /**
25
+ * How many times to resume a stream that closes before a terminal event, sending
26
+ * `Last-Event-ID` so the server replays retained events after that sequence. Cloud Run caps how long one
27
+ * request may live and replaces instances on deploy, and asks clients to reconnect.
28
+ * Early EOF, transport failures and retryable HTTP errors on the event stream (429, 5xx)
29
+ * share this budget. Protocol errors, other HTTP errors, and caller cancellation are not
30
+ * retried. Default 5; `0` fails immediately.
31
+ */
32
+ maxReconnects?: number;
33
+ };
34
+ export type ModelSummary = {
35
+ readonly id: string;
36
+ readonly provider: string;
37
+ readonly model: string;
38
+ };
39
+ export type ModelDefaults = {
40
+ readonly widget: string | null;
41
+ readonly report: string | null;
42
+ };
43
+ export type ModelCatalog = {
44
+ readonly models: readonly ModelSummary[];
45
+ readonly defaults: ModelDefaults;
46
+ };
47
+ export declare class CloudProtocolError extends Error {
48
+ readonly name = "CloudProtocolError";
49
+ }
50
+ export declare class CloudHttpError extends Error {
51
+ readonly status: number;
52
+ /**
53
+ * The `error` object Cloud sent, the same shape as a `failed` event's `error`:
54
+ * `code`, `retryable`, `retry_after_ms` and `details[]` for a program to branch on.
55
+ * `undefined` when the body was not a Cloud error, for example a proxy's HTML page.
56
+ */
57
+ readonly error?: GenerationError | undefined;
58
+ readonly name = "CloudHttpError";
59
+ constructor(status: number, message: string,
60
+ /**
61
+ * The `error` object Cloud sent, the same shape as a `failed` event's `error`:
62
+ * `code`, `retryable`, `retry_after_ms` and `details[]` for a program to branch on.
63
+ * `undefined` when the body was not a Cloud error, for example a proxy's HTML page.
64
+ */
65
+ error?: GenerationError | undefined);
66
+ }
67
+ export declare class CloudGenerator implements Generator {
68
+ #private;
69
+ constructor(options: CloudGeneratorOptions);
70
+ /**
71
+ * Create a run and yield its events. `request.request_id` is also the `Idempotency-Key`,
72
+ * so it names one attempt: sending it again returns that run, even one that failed. To
73
+ * generate again, send a new `request_id`.
74
+ */
75
+ generate(request: GenerateRequest, signal?: AbortSignal): AsyncIterable<GenerationEvent>;
76
+ /** Return model IDs accepted by this deployment and both product defaults. */
77
+ listModels(signal?: AbortSignal): Promise<ModelCatalog>;
78
+ /** Recover the latest complete artifact after a refresh response or connection was lost. */
79
+ getArtifact(request: GenerateRequest, runId: string, signal?: AbortSignal): Promise<SurfaceArtifact>;
80
+ /** Refresh raw JSON, then recover the complete artifact to pass to HostBridge.attach().
81
+ * A failed POST or GET leaves the caller's previous artifact untouched. A network error
82
+ * may follow a committed POST: use getArtifact() to recover before retrying the write.
83
+ */
84
+ updateData(request: GenerateRequest, runId: string, data: GenerateRequest["data"], signal?: AbortSignal): Promise<SurfaceArtifact>;
85
+ }
86
+ export declare const DEFAULT_ANSWER_COMPILE_PATH: "/v1/answers/compile";
87
+ export declare const DEFAULT_ANSWER_GUIDE_PATH: "/v1/answers/authoring-guide";
88
+ export type AnswerCompilerOptions = {
89
+ baseUrl: string;
90
+ apiToken?: string;
91
+ fetch?: FetchTransport;
92
+ headers?: Readonly<Record<string, string>>;
93
+ compilePath?: string;
94
+ guidePath?: string;
95
+ };
96
+ /**
97
+ * One stateless call to `POST /v1/answers/compile`: the Markdown answer written so far in, the
98
+ * complete `SurfaceArtifact` for its revision out. A retry is the same request again.
99
+ * `AnswerStream` makes these calls as the answer grows.
100
+ */
101
+ export declare class CloudAnswerCompiler {
102
+ #private;
103
+ constructor(options: AnswerCompilerOptions);
104
+ /**
105
+ * The LP-MDX authoring guide, Markdown for the system prompt of the model that writes the
106
+ * answer (`GET /v1/answers/authoring-guide`). The same text on every call until the service
107
+ * is updated, so read it once and keep it. It names no action and no data key:
108
+ * `answerSystemPrompt` adds the Host's section.
109
+ */
110
+ getAuthoringGuide(signal?: AbortSignal): Promise<string>;
111
+ compile(request: AnswerCompileRequest, signal?: AbortSignal): Promise<SurfaceArtifact>;
112
+ }