@constellationspace/client 0.0.0-stage → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,125 @@
1
+ import { Manifest, Client, Result, RunInfo } from './index.js';
2
+ export { ActionState, actionState } from './index.js';
3
+
4
+ /**
5
+ * Where a bridge keeps the last cursor it applied and the approvals it already carried out (by
6
+ * actionKey, each with when it may be forgotten: actedUntil), so neither a restart nor a later run
7
+ * that sends an approval again acts twice. Keep both in your system if it can hold them.
8
+ */
9
+ interface CursorStore {
10
+ load(): Promise<string>;
11
+ save(cursor: string): Promise<void>;
12
+ /** actionKey to actedUntil ("" for never). */
13
+ acted(): Promise<Map<string, string>>;
14
+ saveActed(acted: Map<string, string>): Promise<void>;
15
+ }
16
+ declare class MemoryCursorStore implements CursorStore {
17
+ cursor: string;
18
+ actedKeys: Map<string, string>;
19
+ constructor(cursor?: string, actedKeys?: Map<string, string>);
20
+ load(): Promise<string>;
21
+ save(cursor: string): Promise<void>;
22
+ acted(): Promise<Map<string, string>>;
23
+ saveActed(acted: Map<string, string>): Promise<void>;
24
+ }
25
+ /**
26
+ * Keeps the cursor in the file `path`, and the approvals carried out beside it (`path`.acted). With
27
+ * `apiUrl`, the API it reads is kept beside them too (`path`.api), and a cursor read from another API
28
+ * (the mock) is refused, never resumed against this one.
29
+ */
30
+ declare class FileCursorStore implements CursorStore {
31
+ readonly path: string;
32
+ readonly apiUrl?: string | undefined;
33
+ constructor(path: string, apiUrl?: string | undefined);
34
+ load(): Promise<string>;
35
+ save(cursor: string): Promise<void>;
36
+ /** Kept beside the cursor, a line per key: the key, a tab, actedUntil; as the Python and Go bridges keep it. */
37
+ acted(): Promise<Map<string, string>>;
38
+ saveActed(acted: Map<string, string>): Promise<void>;
39
+ }
40
+ /**
41
+ * Names the decision to carry out an action: its decision_id, which a standing approval keeps in
42
+ * every run and a new approval of the same action changes. Without one, its content, as
43
+ * Constellation keys an action: the same verb on the same entity to the same target.
44
+ */
45
+ declare function actionKey(item: Result): string;
46
+ /** How long an acted key is kept once its action is over: past it, no run sends the action again. */
47
+ declare const KEEP_ACTED_MS: number;
48
+ /** How often a bridge checks in again; one that failed is tried again at the next poll. */
49
+ declare const CHECKIN_MS: number;
50
+ /**
51
+ * When an acted key may be forgotten: the latest of the item's time, its end (a pass's end), its
52
+ * action's cancel deadline and now, plus KEEP_ACTED_MS, so a key is never dropped as soon as it is
53
+ * written; "" (kept for good) when none of the item's is a time.
54
+ */
55
+ declare function actedUntil(item: Result): string;
56
+ interface BridgeOptions {
57
+ manifest: Manifest;
58
+ client?: Client;
59
+ /** Defaults to a FileCursorStore at CURSOR_FILE, or ./cursor.txt, for the client's API. */
60
+ store?: CursorStore;
61
+ /** Defaults to POLL_SECONDS (15). */
62
+ pollMs?: number;
63
+ /** JSON-lines log of every item applied; defaults to CONSTELLATION_CONFORMANCE_LOG, off when unset. */
64
+ conformanceLog?: string;
65
+ /**
66
+ * With no saved cursor, apply the whole history the feed holds instead of starting at its newest
67
+ * run. Defaults to BACKFILL=1.
68
+ */
69
+ backfill?: boolean;
70
+ log?: (message: string) => void;
71
+ }
72
+ /**
73
+ * A Constellation connector for your own system: subclass it, implement apply() (and act() for
74
+ * approved actions), call run(). Checking in, pulling and joining runs, reporting, cursor
75
+ * persistence, acting on each approved action exactly once and never dying on a bad poll are done
76
+ * here; a refused key or plan (401/403) stops run() with a ConstellationError, and a cursor it cannot
77
+ * save stops it too.
78
+ */
79
+ declare abstract class Bridge {
80
+ readonly manifest: Manifest;
81
+ readonly client: Client;
82
+ readonly store: CursorStore;
83
+ readonly pollMs: number;
84
+ readonly conformanceLog: string | undefined;
85
+ private checkedIn;
86
+ private nextCheckIn;
87
+ private readonly backfill;
88
+ private started;
89
+ private readonly unreported;
90
+ private actedKeys;
91
+ constructor(options: BridgeOptions);
92
+ /**
93
+ * Write one run's items into your system; return what you wrote, e.g. {passes: 12}. Throw when
94
+ * your system is unreachable: the run is retried. `run` is the whole answer for its window, so
95
+ * withdraw what you wrote earlier for the same workflow inside the window that `items` no
96
+ * longer carries. Carry out approved actions in act(), not here.
97
+ */
98
+ abstract apply(items: Result[], settings: Record<string, unknown>, run: RunInfo): Promise<Record<string, number>> | Record<string, number>;
99
+ /**
100
+ * Carry out an approved action (cancel the pass, book the backup); return true once done.
101
+ * Called after apply(), once per approval, never for any other state, and never again for the
102
+ * same approval (actionKey) in a later run or after a restart. Throw when your system is
103
+ * failing: the run is retried, without acting again on what was done. The default does nothing.
104
+ */
105
+ act(_item: Result, _settings: Record<string, unknown>, _run: RunInfo): Promise<boolean> | boolean;
106
+ log(message: string): void;
107
+ /** Applies every run with results after the saved cursor; returns how many it applied. */
108
+ poll(): Promise<number>;
109
+ /**
110
+ * Polls until `signal` aborts. A failed poll is logged and retried; a refusal, state it cannot
111
+ * save, or no key (unless the API is the mock on this machine) is thrown.
112
+ */
113
+ run(signal?: AbortSignal): Promise<void>;
114
+ /** Carries out an approved action unless it was carried out before or is past its cancel deadline; says whether it did. */
115
+ private carryOut;
116
+ /**
117
+ * Saves the cursor or the approvals carried out. A bridge that cannot would repeat its work after
118
+ * every poll or restart, so a failure to stops run().
119
+ */
120
+ private keep;
121
+ /** One line per item applied, for `constellation conformance`. */
122
+ private record;
123
+ }
124
+
125
+ export { Bridge, type BridgeOptions, CHECKIN_MS, type CursorStore, FileCursorStore, KEEP_ACTED_MS, Manifest, MemoryCursorStore, Result, RunInfo, actedUntil, actionKey };
package/dist/bridge.js ADDED
@@ -0,0 +1,272 @@
1
+ import {
2
+ Client,
3
+ actionState,
4
+ loopback,
5
+ origin,
6
+ site
7
+ } from "./chunk-Y42SVCFF.js";
8
+
9
+ // src/bridge.ts
10
+ import { appendFile, mkdir, readFile, rename, writeFile } from "fs/promises";
11
+ import { dirname } from "path";
12
+ var MemoryCursorStore = class {
13
+ constructor(cursor = "", actedKeys = /* @__PURE__ */ new Map()) {
14
+ this.cursor = cursor;
15
+ this.actedKeys = actedKeys;
16
+ }
17
+ cursor;
18
+ actedKeys;
19
+ async load() {
20
+ return this.cursor;
21
+ }
22
+ async save(cursor) {
23
+ this.cursor = cursor;
24
+ }
25
+ async acted() {
26
+ return new Map(this.actedKeys);
27
+ }
28
+ async saveActed(acted) {
29
+ this.actedKeys = new Map(acted);
30
+ }
31
+ };
32
+ var FileCursorStore = class {
33
+ constructor(path, apiUrl) {
34
+ this.path = path;
35
+ this.apiUrl = apiUrl;
36
+ }
37
+ path;
38
+ apiUrl;
39
+ async load() {
40
+ const there = (await readFile(`${this.path}.api`, "utf8").catch(() => "")).trim();
41
+ const here = this.apiUrl && origin(this.apiUrl);
42
+ if (here && there && there !== here)
43
+ throw Object.assign(
44
+ new Error(`${this.path} is where this bridge read ${there} up to, and it now reads ${here}. Delete ${this.path}* to start afresh on ${here}, or set CURSOR_FILE to another file`),
45
+ { fatal: true }
46
+ );
47
+ try {
48
+ return (await readFile(this.path, "utf8")).trim();
49
+ } catch (error) {
50
+ if (error.code === "ENOENT") return "";
51
+ throw error;
52
+ }
53
+ }
54
+ async save(cursor) {
55
+ await mkdir(dirname(this.path), { recursive: true });
56
+ if (this.apiUrl) await writeFile(`${this.path}.api`, origin(this.apiUrl));
57
+ await writeFile(`${this.path}.tmp`, cursor);
58
+ await rename(`${this.path}.tmp`, this.path);
59
+ }
60
+ /** Kept beside the cursor, a line per key: the key, a tab, actedUntil; as the Python and Go bridges keep it. */
61
+ async acted() {
62
+ let text = "";
63
+ try {
64
+ text = await readFile(`${this.path}.acted`, "utf8");
65
+ } catch (error) {
66
+ if (error.code !== "ENOENT") throw error;
67
+ }
68
+ const acted = /* @__PURE__ */ new Map();
69
+ for (const line of text.split("\n")) {
70
+ const tab = line.indexOf(" ");
71
+ if (line) acted.set(tab < 0 ? line : line.slice(0, tab), tab < 0 ? "" : line.slice(tab + 1));
72
+ }
73
+ return acted;
74
+ }
75
+ async saveActed(acted) {
76
+ await mkdir(dirname(this.path), { recursive: true });
77
+ const lines = [...acted].map(([key, until]) => `${key} ${until}
78
+ `).join("");
79
+ await writeFile(`${this.path}.acted.tmp`, lines);
80
+ await rename(`${this.path}.acted.tmp`, `${this.path}.acted`);
81
+ }
82
+ };
83
+ function actionKey(item) {
84
+ if (typeof item.decision_id === "string" && item.decision_id) return item.decision_id;
85
+ return `${item.entity.id}|${item.action?.verb ?? ""}|${item.action?.to ?? ""}`;
86
+ }
87
+ var KEEP_ACTED_MS = 7 * 24 * 3600 * 1e3;
88
+ var CHECKIN_MS = 5 * 60 * 1e3;
89
+ function actedUntil(item) {
90
+ const times = [item.target_at, item.until, item.action?.deadline].map((t) => Date.parse(t ?? "")).filter((t) => !Number.isNaN(t));
91
+ return times.length ? new Date(Math.max(...times, Date.now()) + KEEP_ACTED_MS).toISOString() : "";
92
+ }
93
+ function malformed(item) {
94
+ const i = item;
95
+ if (typeof i?.entity?.id !== "string" || typeof i.entity.type !== "string") return "no entity with an id and a type";
96
+ const times = [["target_at", i.target_at], ["until", i.until ?? void 0], ["action.deadline", i.action?.deadline ?? void 0]];
97
+ for (const [name, t] of times) {
98
+ if (name !== "target_at" && t === void 0) continue;
99
+ if (typeof t !== "string" || Number.isNaN(Date.parse(t))) return `${name} is not a time`;
100
+ }
101
+ return "";
102
+ }
103
+ function pastDeadline(item) {
104
+ const deadline = Date.parse(item.action?.deadline ?? "");
105
+ return !Number.isNaN(deadline) && deadline <= Date.now();
106
+ }
107
+ async function startCursor(client, consumer) {
108
+ const page = await client.resultsPage({ from: "latest", consumer, limit: 20, pageRecords: 1 });
109
+ if (page.entries.length)
110
+ throw new Error("the API ignored GET /predictions/feed?from=latest, so a first start cannot find the newest run: this bridge needs an API serving contract 1.5.0 or later");
111
+ return page.next;
112
+ }
113
+ function prune(acted) {
114
+ const over = [...acted].filter(([, until]) => until && Date.parse(until) < Date.now());
115
+ for (const [key] of over) acted.delete(key);
116
+ return over.length > 0;
117
+ }
118
+ var Bridge = class {
119
+ manifest;
120
+ client;
121
+ store;
122
+ pollMs;
123
+ conformanceLog;
124
+ checkedIn = false;
125
+ nextCheckIn = 0;
126
+ backfill;
127
+ started = false;
128
+ unreported = /* @__PURE__ */ new Map();
129
+ actedKeys;
130
+ constructor(options) {
131
+ this.manifest = options.manifest;
132
+ this.log = options.log ?? this.log;
133
+ this.client = options.client ?? new Client({ log: (m) => this.log(m) });
134
+ this.store = options.store ?? new FileCursorStore(process.env.CURSOR_FILE ?? "cursor.txt", this.client.baseUrl);
135
+ this.pollMs = options.pollMs ?? Number(process.env.POLL_SECONDS ?? 15) * 1e3;
136
+ this.conformanceLog = options.conformanceLog ?? (process.env.CONSTELLATION_CONFORMANCE_LOG || void 0);
137
+ this.backfill = options.backfill ?? process.env.BACKFILL === "1";
138
+ }
139
+ /**
140
+ * Carry out an approved action (cancel the pass, book the backup); return true once done.
141
+ * Called after apply(), once per approval, never for any other state, and never again for the
142
+ * same approval (actionKey) in a later run or after a restart. Throw when your system is
143
+ * failing: the run is retried, without acting again on what was done. The default does nothing.
144
+ */
145
+ act(_item, _settings, _run) {
146
+ return false;
147
+ }
148
+ log(message) {
149
+ console.log(`${this.manifest.name}: ${message}`);
150
+ }
151
+ /** Applies every run with results after the saved cursor; returns how many it applied. */
152
+ async poll() {
153
+ const { name, title } = this.manifest;
154
+ if (Date.now() >= this.nextCheckIn) {
155
+ await this.client.checkIn(this.manifest);
156
+ this.nextCheckIn = Date.now() + CHECKIN_MS;
157
+ if (!this.checkedIn) this.log("checked in; approve it on Integrations if it is new or its manifest changed");
158
+ this.checkedIn = true;
159
+ }
160
+ let after = await this.store.load();
161
+ if (!this.started && !after && !this.backfill) {
162
+ after = await startCursor(this.client, name);
163
+ if (after) await this.keep(() => this.store.save(after));
164
+ this.log(`first start: reading after ${after || "the start"}`);
165
+ }
166
+ this.started = true;
167
+ let applied = 0;
168
+ for await (const entry of this.client.results({ after, consumer: name })) {
169
+ if (after && entry.cursor <= after) {
170
+ this.log(`skipped ${entry.cursor}: already applied`);
171
+ continue;
172
+ }
173
+ const done = this.unreported.get(entry.cursor) ?? [];
174
+ this.unreported.set(entry.cursor, done);
175
+ for (const [n, part] of entry.parts.entries()) {
176
+ if (n === done.length) {
177
+ const items2 = part.items.filter((item, i) => {
178
+ const why = malformed(item);
179
+ if (why) this.log(`skipped item ${i} of run ${part.run.run_id}: it is malformed (${why})`);
180
+ return !why;
181
+ });
182
+ const counts2 = { ...await this.apply(items2, part.settings, part.run) };
183
+ if (items2.length < part.items.length) counts2.malformed = part.items.length - items2.length;
184
+ const acted2 = [];
185
+ for (const item of items2)
186
+ acted2.push(actionState(item) === "approved" && await this.carryOut(item, part.settings, part.run));
187
+ if (acted2.some(Boolean)) counts2.acted = acted2.filter(Boolean).length;
188
+ done.push({ counts: counts2, acted: acted2, items: items2 });
189
+ }
190
+ const { counts, acted, items } = done[n];
191
+ await this.client.report(name, entry.cursor, counts, title);
192
+ await this.record(items, acted);
193
+ this.log(`applied ${JSON.stringify(counts)}, ${entry.cursor}`);
194
+ }
195
+ this.unreported.delete(entry.cursor);
196
+ await this.keep(() => this.store.save(entry.cursor));
197
+ after = entry.cursor;
198
+ applied++;
199
+ }
200
+ return applied;
201
+ }
202
+ /**
203
+ * Polls until `signal` aborts. A failed poll is logged and retried; a refusal, state it cannot
204
+ * save, or no key (unless the API is the mock on this machine) is thrown.
205
+ */
206
+ async run(signal) {
207
+ if (!this.client.hasKey && !loopback(this.client.baseUrl))
208
+ throw new Error(`CONSTELLATION_API_KEY is not set: make a key with predictions:read on ${site(this.client.baseUrl)}/keys and set it`);
209
+ this.log(`${this.client.baseUrl} as ${this.manifest.name}, from cursor ${await this.store.load() || (this.backfill ? "the start" : "its newest run")}`);
210
+ while (!signal?.aborted) {
211
+ try {
212
+ await this.poll();
213
+ } catch (error) {
214
+ if (error?.refused || error?.fatal) throw error;
215
+ this.log(error instanceof Error ? `${error.name}: ${error.message}` : String(error));
216
+ }
217
+ await new Promise((resolve) => setTimeout(resolve, this.pollMs));
218
+ }
219
+ }
220
+ /** Carries out an approved action unless it was carried out before or is past its cancel deadline; says whether it did. */
221
+ async carryOut(item, settings, run) {
222
+ if (pastDeadline(item)) {
223
+ this.log(`not acting on ${item.entity.id}: its cancel deadline has passed`);
224
+ return false;
225
+ }
226
+ if (!this.actedKeys) {
227
+ this.actedKeys = await this.store.acted();
228
+ if (prune(this.actedKeys)) await this.store.saveActed(this.actedKeys);
229
+ }
230
+ const key = actionKey(item);
231
+ if (this.actedKeys.has(key) || !await this.act(item, settings, run)) return false;
232
+ this.actedKeys.set(key, actedUntil(item));
233
+ prune(this.actedKeys);
234
+ await this.keep(() => this.store.saveActed(this.actedKeys));
235
+ return true;
236
+ }
237
+ /**
238
+ * Saves the cursor or the approvals carried out. A bridge that cannot would repeat its work after
239
+ * every poll or restart, so a failure to stops run().
240
+ */
241
+ async keep(save) {
242
+ try {
243
+ await save();
244
+ } catch (error) {
245
+ const why = error instanceof Error ? error.message : String(error);
246
+ throw Object.assign(new Error(`cannot keep its state, so it would repeat its work: ${why} (make CURSOR_FILE's folder writable)`), { fatal: true });
247
+ }
248
+ }
249
+ /** One line per item applied, for `constellation conformance`. */
250
+ async record(items, acted) {
251
+ if (!this.conformanceLog) return;
252
+ const lines = items.map(
253
+ (item, i) => JSON.stringify({
254
+ item_id: item.entity.id,
255
+ state: actionState(item) ?? "forecast",
256
+ acted: acted[i],
257
+ verb: item.action?.verb ?? null
258
+ })
259
+ );
260
+ if (lines.length) await appendFile(this.conformanceLog, lines.join("\n") + "\n");
261
+ }
262
+ };
263
+ export {
264
+ Bridge,
265
+ CHECKIN_MS,
266
+ FileCursorStore,
267
+ KEEP_ACTED_MS,
268
+ MemoryCursorStore,
269
+ actedUntil,
270
+ actionKey,
271
+ actionState
272
+ };
@@ -0,0 +1,277 @@
1
+ // src/results.ts
2
+ var SCHEMA = "constellation.item/v2";
3
+ var PAGE_RECORDS = 400;
4
+ function actionState(item) {
5
+ const status = item.action_status ?? null;
6
+ if (status !== null && status !== "approved") return status === "rejected" ? "rejected" : "pending";
7
+ const action = item.action;
8
+ if (!action || Object.keys(action).length === 0) return status === null ? null : "pending";
9
+ return status === "approved" ? "approved" : "advice";
10
+ }
11
+ function plain(value) {
12
+ if ("kvlistValue" in value)
13
+ return Object.fromEntries((value.kvlistValue.values ?? []).map((kv) => [kv.key, plain(kv.value)]));
14
+ if ("arrayValue" in value) return (value.arrayValue.values ?? []).map(plain);
15
+ if ("intValue" in value) return Number(value.intValue);
16
+ for (const key of ["doubleValue", "boolValue", "stringValue"]) if (key in value) return value[key];
17
+ return null;
18
+ }
19
+ var attributes = (kvs = []) => Object.fromEntries(kvs.map((kv) => [kv.key, plain(kv.value)]));
20
+ function unpack(entry, consumer, log) {
21
+ const parts = [];
22
+ for (const logs of entry.otlp.resourceLogs) {
23
+ const resource = attributes(logs.resource?.attributes);
24
+ if (consumer && resource["constellation.connection"] !== consumer) continue;
25
+ const records = (logs.scopeLogs ?? []).flatMap((s) => s.logRecords ?? []);
26
+ const newer = new Set(records.map((r) => attributes(r.attributes)["constellation.schema"]));
27
+ newer.delete(SCHEMA);
28
+ if (newer.size) {
29
+ log(`skipped run ${resource["constellation.run_id"]}: its items are ${[...newer].join(", ")} and this client reads ${SCHEMA}`);
30
+ continue;
31
+ }
32
+ const output = JSON.parse(resource["constellation.output"] || "{}");
33
+ parts.push({
34
+ resource,
35
+ items: records.map((r) => plain(r.body)),
36
+ settings: output?.mapping?.settings ?? {},
37
+ run: {
38
+ workflow: resource["constellation.workflow"],
39
+ workflow_version: resource["constellation.workflow_version"],
40
+ run_id: resource["constellation.run_id"],
41
+ window_from: resource["constellation.window.from"],
42
+ window_to: resource["constellation.window.to"]
43
+ }
44
+ });
45
+ }
46
+ return parts;
47
+ }
48
+ async function whole(entry, fetchPage) {
49
+ const resourceLogs = entry.otlp.resourceLogs.map((l) => ({
50
+ ...l,
51
+ scopeLogs: (l.scopeLogs ?? []).map((s) => ({ ...s, logRecords: [...s.logRecords ?? []] }))
52
+ }));
53
+ const byResource = new Map(resourceLogs.map((l) => [JSON.stringify(l.resource), l]));
54
+ let next = entry.next_page;
55
+ while (next) {
56
+ const more = await fetchPage(entry.cursor, next);
57
+ for (const logs of more.otlp.resourceLogs) {
58
+ const key = JSON.stringify(logs.resource);
59
+ const known = byResource.get(key)?.scopeLogs?.[0];
60
+ if (known) known.logRecords.push(...logs.scopeLogs?.[0]?.logRecords ?? []);
61
+ else {
62
+ resourceLogs.push(logs);
63
+ byResource.set(key, logs);
64
+ }
65
+ }
66
+ next = more.next_page;
67
+ }
68
+ return { cursor: entry.cursor, otlp: { ...entry.otlp, resourceLogs } };
69
+ }
70
+
71
+ // src/client.ts
72
+ var DEFAULT_API_URL = "https://api.constellation.space";
73
+ function site(apiUrl) {
74
+ let host = "";
75
+ try {
76
+ host = new URL(apiUrl ?? "").hostname;
77
+ } catch {
78
+ }
79
+ if (host.startsWith("api.")) return `https://platform.${host.slice(4)}`;
80
+ const at = host.indexOf(".api.");
81
+ if (at > 0) return `https://${host.slice(0, at)}-platform.${host.slice(at + 5)}`;
82
+ return "https://platform.constellation.space";
83
+ }
84
+ function loopback(url) {
85
+ let host = "";
86
+ try {
87
+ host = new URL(url).hostname.replace(/^\[|\]$/g, "");
88
+ } catch {
89
+ }
90
+ return host === "localhost" || host === "::1" || /^127\.\d+\.\d+\.\d+$/.test(host);
91
+ }
92
+ function origin(url) {
93
+ const u = new URL(url);
94
+ if (loopback(url)) u.hostname = "localhost";
95
+ return u.origin;
96
+ }
97
+ function keySafe(url) {
98
+ let scheme = "";
99
+ try {
100
+ scheme = new URL(url).protocol;
101
+ } catch {
102
+ }
103
+ return scheme === "https:" || scheme === "http:" && loopback(url);
104
+ }
105
+ var env = (name) => globalThis.process?.env[name];
106
+ var MAX_RETRY_AFTER_S = 60;
107
+ var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
108
+ var ConstellationError = class extends Error {
109
+ constructor(status, body, apiUrl) {
110
+ const b = body;
111
+ const inner = b && typeof b === "object" ? typeof b.detail === "object" && b.detail ? b.detail : b : {};
112
+ super(describe(status, inner, b, site(apiUrl)));
113
+ this.status = status;
114
+ this.body = body;
115
+ this.name = "ConstellationError";
116
+ this.detail = inner;
117
+ this.code = typeof inner.error === "string" ? inner.error : void 0;
118
+ }
119
+ status;
120
+ body;
121
+ /** The API's machine error, e.g. plan_required, insufficient_scope, unknown_cursor. */
122
+ code;
123
+ /** The error object: the body's `detail` when it is an object, else the body. */
124
+ detail;
125
+ /** 401 or 403: neither clears by asking again, so a bridge stops on one. */
126
+ get refused() {
127
+ return this.status === 401 || this.status === 403;
128
+ }
129
+ };
130
+ function describe(status, d, body, home) {
131
+ const fix = `make a key with predictions:read on ${home}/keys and set it as CONSTELLATION_API_KEY`;
132
+ if (status === 401) return `Constellation does not accept the API key (HTTP 401; wrong, revoked or expired): ${fix}`;
133
+ if (status === 403) {
134
+ if (d.error === "plan_required")
135
+ return `this account's plan does not include ${d.feature} (HTTP 403 plan_required); the ${d.plan} plan does. Upgrade on ${home}/billing`;
136
+ if (d.error === "insufficient_scope") return `the API key lacks ${d.required} (HTTP 403): ${fix}`;
137
+ if (d.error === "live_key_required") return `the API key is a test key; this takes a live one (HTTP 403): ${fix}`;
138
+ return `Constellation refused the API key (HTTP 403 ${d.error ?? "forbidden"}): ${fix}`;
139
+ }
140
+ return `Constellation answered ${status}: ${JSON.stringify(body)?.slice(0, 300)}`;
141
+ }
142
+ var Client = class {
143
+ baseUrl;
144
+ apiKey;
145
+ retries;
146
+ retryDelayMs;
147
+ timeoutMs;
148
+ fetchFn;
149
+ log;
150
+ constructor(options = {}) {
151
+ this.apiKey = (options.apiKey ?? env("CONSTELLATION_API_KEY") ?? "").trim();
152
+ this.baseUrl = (options.baseUrl ?? env("CONSTELLATION_API_URL") ?? DEFAULT_API_URL).replace(/\/+$/, "");
153
+ this.retries = options.retries ?? 4;
154
+ this.retryDelayMs = options.retryDelayMs ?? 500;
155
+ this.timeoutMs = options.timeoutMs ?? 6e4;
156
+ this.fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);
157
+ this.log = options.log ?? ((m) => console.warn(`constellation: ${m}`));
158
+ }
159
+ /** Whether it has an API key to send. */
160
+ get hasKey() {
161
+ return this.apiKey !== "";
162
+ }
163
+ /** Any API call: `query` values left undefined are dropped. Returns the parsed JSON body, or undefined. */
164
+ async request(method, path, options = {}) {
165
+ const query = Object.entries(options.query ?? {}).filter(([, v]) => v !== void 0);
166
+ const url = `${this.baseUrl}${path}${query.length ? `?${new URLSearchParams(query.map(([k, v]) => [k, String(v)]))}` : ""}`;
167
+ if (this.apiKey && !keySafe(this.baseUrl))
168
+ throw new Error(`not sending the API key to ${this.baseUrl}: it is not https (plain http only to localhost)`);
169
+ const init = {
170
+ method,
171
+ headers: { ...this.apiKey && { "x-api-key": this.apiKey }, "content-type": "application/json", accept: "application/json" },
172
+ body: options.body === void 0 ? void 0 : JSON.stringify(options.body)
173
+ };
174
+ for (let attempt = 0; ; attempt++) {
175
+ let response;
176
+ let text;
177
+ try {
178
+ response = await this.fetchFn(url, { ...init, signal: AbortSignal.timeout(this.timeoutMs) });
179
+ text = await response.text();
180
+ } catch (error) {
181
+ if (attempt >= this.retries) throw error;
182
+ await sleep(this.retryDelayMs * 2 ** attempt);
183
+ continue;
184
+ }
185
+ const body = text ? parse(text) : void 0;
186
+ if (response.ok) return body;
187
+ const retryable = response.status === 429 || response.status >= 500;
188
+ if (!retryable || attempt >= this.retries) throw new ConstellationError(response.status, body, this.baseUrl);
189
+ const after = Math.min(Number(response.headers.get("retry-after")), MAX_RETRY_AFTER_S);
190
+ if (after > 0) this.log(`answered ${response.status}; retrying in ${after} s (Retry-After)`);
191
+ await sleep(after > 0 ? after * 1e3 : this.retryDelayMs * 2 ** attempt);
192
+ }
193
+ }
194
+ /**
195
+ * One page of workflow results after `after`: whole entries, or first pages when `pageRecords` is set.
196
+ * `from: "latest"` asks where a first start reads from instead: no entries, and `next` just before
197
+ * the newest run with something for `consumer`.
198
+ */
199
+ resultsPage(options = {}) {
200
+ return this.request("GET", "/predictions/feed", {
201
+ query: {
202
+ from: options.from,
203
+ after: options.after ?? "",
204
+ limit: options.limit,
205
+ consumer: options.consumer,
206
+ page_records: options.pageRecords
207
+ }
208
+ });
209
+ }
210
+ /**
211
+ * Runs with results after `after`, oldest first, each joined whole and unpacked; a cursor older than
212
+ * the oldest entry the feed holds is logged (the runs between expired unread). Ends when the API
213
+ * has no more, unless `pollMs` is set: then it waits that long and asks again, for as long as the
214
+ * caller iterates or until `signal` aborts.
215
+ */
216
+ async *results(options = {}) {
217
+ const { consumer } = options;
218
+ let after = options.after ?? "";
219
+ while (!options.signal?.aborted) {
220
+ const page = await this.resultsPage({ after, consumer, limit: 1, pageRecords: PAGE_RECORDS });
221
+ if (after && page.oldest && after < page.oldest)
222
+ this.log(`the feed no longer holds cursor ${after}: any runs after it and before the oldest it holds, ${page.oldest}, expired unread; reading on from there`);
223
+ for (const entry of page.entries) {
224
+ const full = await whole(
225
+ entry,
226
+ (cursor, n) => this.request("GET", "/predictions/feed", {
227
+ query: { cursor, page: n, page_records: PAGE_RECORDS, consumer }
228
+ })
229
+ );
230
+ yield { cursor: entry.cursor, parts: unpack(full, consumer, this.log) };
231
+ after = entry.cursor;
232
+ }
233
+ if (page.entries.length) continue;
234
+ if (options.pollMs === void 0) return;
235
+ await sleep(options.pollMs);
236
+ }
237
+ }
238
+ /** Registers a custom bridge's manifest; it waits for approval on Integrations. */
239
+ checkIn(manifest) {
240
+ const { name, title, description, settings } = manifest;
241
+ const body = {
242
+ consumer: name,
243
+ system: "custom",
244
+ manifest: { name, title, ...description !== void 0 && { description }, ...settings && { settings } },
245
+ bridge_version: manifest.version ?? "0.1.0",
246
+ target: title
247
+ };
248
+ return this.request("POST", "/predictions/feed/checkin", { body });
249
+ }
250
+ /** Tells Constellation what the run at `cursor` became in the system, shown in Constellation. */
251
+ report(consumer, cursor, applied, target) {
252
+ const body = { consumer, run_id: cursor.slice(cursor.indexOf("#") + 1), cursor, applied, target };
253
+ return this.request("POST", "/predictions/feed/deliveries", { body });
254
+ }
255
+ };
256
+ function parse(text) {
257
+ try {
258
+ return JSON.parse(text);
259
+ } catch {
260
+ return text;
261
+ }
262
+ }
263
+
264
+ export {
265
+ SCHEMA,
266
+ PAGE_RECORDS,
267
+ actionState,
268
+ plain,
269
+ unpack,
270
+ whole,
271
+ DEFAULT_API_URL,
272
+ site,
273
+ loopback,
274
+ origin,
275
+ ConstellationError,
276
+ Client
277
+ };