@superbased/sdk 0.0.0-stage → 0.1.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/LICENSE +202 -0
- package/NOTICE +4 -0
- package/README.md +438 -2
- package/dist/cjs/admit.d.ts +139 -0
- package/dist/cjs/admit.js +442 -0
- package/dist/cjs/admit.js.map +1 -0
- package/dist/cjs/attrs.d.ts +113 -0
- package/dist/cjs/attrs.js +183 -0
- package/dist/cjs/attrs.js.map +1 -0
- package/dist/cjs/config.d.ts +202 -0
- package/dist/cjs/config.js +386 -0
- package/dist/cjs/config.js.map +1 -0
- package/dist/cjs/context.d.ts +102 -0
- package/dist/cjs/context.js +234 -0
- package/dist/cjs/context.js.map +1 -0
- package/dist/cjs/control.d.ts +99 -0
- package/dist/cjs/control.js +243 -0
- package/dist/cjs/control.js.map +1 -0
- package/dist/cjs/cost.d.ts +108 -0
- package/dist/cjs/cost.js +211 -0
- package/dist/cjs/cost.js.map +1 -0
- package/dist/cjs/destination.d.ts +125 -0
- package/dist/cjs/destination.js +357 -0
- package/dist/cjs/destination.js.map +1 -0
- package/dist/cjs/experiments.d.ts +237 -0
- package/dist/cjs/experiments.js +678 -0
- package/dist/cjs/experiments.js.map +1 -0
- package/dist/cjs/export.d.ts +84 -0
- package/dist/cjs/export.js +328 -0
- package/dist/cjs/export.js.map +1 -0
- package/dist/cjs/index.d.ts +168 -0
- package/dist/cjs/index.js +581 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/instrument.d.ts +88 -0
- package/dist/cjs/instrument.js +397 -0
- package/dist/cjs/instrument.js.map +1 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/policy.d.ts +77 -0
- package/dist/cjs/policy.js +252 -0
- package/dist/cjs/policy.js.map +1 -0
- package/dist/cjs/prompts.d.ts +175 -0
- package/dist/cjs/prompts.js +476 -0
- package/dist/cjs/prompts.js.map +1 -0
- package/dist/cjs/propagation.d.ts +34 -0
- package/dist/cjs/propagation.js +151 -0
- package/dist/cjs/propagation.js.map +1 -0
- package/dist/cjs/req.d.ts +10 -0
- package/dist/cjs/req.js +3 -0
- package/dist/cjs/req.js.map +1 -0
- package/dist/cjs/runtime.d.ts +44 -0
- package/dist/cjs/runtime.js +67 -0
- package/dist/cjs/runtime.js.map +1 -0
- package/dist/cjs/scores.d.ts +102 -0
- package/dist/cjs/scores.js +226 -0
- package/dist/cjs/scores.js.map +1 -0
- package/dist/cjs/spans.d.ts +193 -0
- package/dist/cjs/spans.js +398 -0
- package/dist/cjs/spans.js.map +1 -0
- package/dist/cjs/vendor.d.ts +33 -0
- package/dist/cjs/vendor.js +67 -0
- package/dist/cjs/vendor.js.map +1 -0
- package/dist/esm/admit.d.ts +139 -0
- package/dist/esm/admit.js +432 -0
- package/dist/esm/admit.js.map +1 -0
- package/dist/esm/attrs.d.ts +113 -0
- package/dist/esm/attrs.js +179 -0
- package/dist/esm/attrs.js.map +1 -0
- package/dist/esm/config.d.ts +202 -0
- package/dist/esm/config.js +364 -0
- package/dist/esm/config.js.map +1 -0
- package/dist/esm/context.d.ts +102 -0
- package/dist/esm/context.js +221 -0
- package/dist/esm/context.js.map +1 -0
- package/dist/esm/control.d.ts +99 -0
- package/dist/esm/control.js +230 -0
- package/dist/esm/control.js.map +1 -0
- package/dist/esm/cost.d.ts +108 -0
- package/dist/esm/cost.js +202 -0
- package/dist/esm/cost.js.map +1 -0
- package/dist/esm/destination.d.ts +125 -0
- package/dist/esm/destination.js +346 -0
- package/dist/esm/destination.js.map +1 -0
- package/dist/esm/experiments.d.ts +237 -0
- package/dist/esm/experiments.js +666 -0
- package/dist/esm/experiments.js.map +1 -0
- package/dist/esm/export.d.ts +84 -0
- package/dist/esm/export.js +314 -0
- package/dist/esm/export.js.map +1 -0
- package/dist/esm/index.d.ts +168 -0
- package/dist/esm/index.js +500 -0
- package/dist/esm/index.js.map +1 -0
- package/dist/esm/instrument.d.ts +88 -0
- package/dist/esm/instrument.js +391 -0
- package/dist/esm/instrument.js.map +1 -0
- package/dist/esm/policy.d.ts +77 -0
- package/dist/esm/policy.js +240 -0
- package/dist/esm/policy.js.map +1 -0
- package/dist/esm/prompts.d.ts +175 -0
- package/dist/esm/prompts.js +460 -0
- package/dist/esm/prompts.js.map +1 -0
- package/dist/esm/propagation.d.ts +34 -0
- package/dist/esm/propagation.js +145 -0
- package/dist/esm/propagation.js.map +1 -0
- package/dist/esm/req.d.ts +10 -0
- package/dist/esm/req.js +2 -0
- package/dist/esm/req.js.map +1 -0
- package/dist/esm/runtime.d.ts +44 -0
- package/dist/esm/runtime.js +59 -0
- package/dist/esm/runtime.js.map +1 -0
- package/dist/esm/scores.d.ts +102 -0
- package/dist/esm/scores.js +219 -0
- package/dist/esm/scores.js.map +1 -0
- package/dist/esm/spans.d.ts +193 -0
- package/dist/esm/spans.js +378 -0
- package/dist/esm/spans.js.map +1 -0
- package/dist/esm/vendor.d.ts +33 -0
- package/dist/esm/vendor.js +61 -0
- package/dist/esm/vendor.js.map +1 -0
- package/package.json +130 -4
|
@@ -0,0 +1,476 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Prompt registry client (W3-3; contract `contracts/prompts.md`, lane B8).
|
|
4
|
+
*
|
|
5
|
+
* - Fetch: online `GET <org>/v1/sdk/prompts/{name}` (scope `sdk:read`),
|
|
6
|
+
* local `GET <machine>/api/obs/sdk/prompts/{name}`; `both` prefers online
|
|
7
|
+
* and falls back to local. `?label=` or `?version=`, never both; neither is
|
|
8
|
+
* `label=production`.
|
|
9
|
+
* - Cache per (endpoint, name, selector): fresh for `cacheTtlMs` (default
|
|
10
|
+
* 60 s, `SUPERBASED_PROMPT_CACHE_TTL_MS`). After that the cached prompt is
|
|
11
|
+
* returned at once and revalidated in the background with `If-None-Match`
|
|
12
|
+
* (stale-while-revalidate); a 304 renews it, a 404 drops it, any other
|
|
13
|
+
* failure keeps serving it.
|
|
14
|
+
* - A first fetch that fails throws {@link PromptNotFound}, unless you pass a
|
|
15
|
+
* `fallback`, which is returned marked `isFallback` and never cached.
|
|
16
|
+
* - `compile(values)` fills `{{name}}` placeholders in one pass (a value is
|
|
17
|
+
* never re-scanned) and throws {@link PromptCompileError} naming every
|
|
18
|
+
* missing variable. `prompt.compile()`, `getPrompt()` inside a span and
|
|
19
|
+
* `withLlmSpan(..., { promptRef })` stamp `sbo.prompt.name`,
|
|
20
|
+
* `sbo.prompt.version` and (for a label fetch) `sbo.prompt.label` on the
|
|
21
|
+
* span. A fallback stamps nothing.
|
|
22
|
+
*/
|
|
23
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
24
|
+
exports.Prompt = exports.PromptCompileError = exports.PromptFetchError = exports.PromptNotFound = exports.PromptError = exports.PROMPT_LABELS = exports.DEFAULT_PROMPT_LABEL = void 0;
|
|
25
|
+
exports.promptVariables = promptVariables;
|
|
26
|
+
exports.compilePrompt = compilePrompt;
|
|
27
|
+
exports.parsePrompt = parsePrompt;
|
|
28
|
+
exports.cohortHash = cohortHash;
|
|
29
|
+
exports.rolloutBucket = rolloutBucket;
|
|
30
|
+
exports.clearPromptCache = clearPromptCache;
|
|
31
|
+
exports.promptCacheSize = promptCacheSize;
|
|
32
|
+
exports.getPrompt = getPrompt;
|
|
33
|
+
const node_crypto_1 = require("node:crypto");
|
|
34
|
+
const api_1 = require("@opentelemetry/api");
|
|
35
|
+
const attrs_js_1 = require("./attrs.js");
|
|
36
|
+
const control_js_1 = require("./control.js");
|
|
37
|
+
const context_js_1 = require("./context.js");
|
|
38
|
+
const runtime_js_1 = require("./runtime.js");
|
|
39
|
+
exports.DEFAULT_PROMPT_LABEL = "production";
|
|
40
|
+
exports.PROMPT_LABELS = ["production", "staging"];
|
|
41
|
+
/** The base of every prompt error (contract sdk-api-surface.md section 7.3). */
|
|
42
|
+
class PromptError extends Error {
|
|
43
|
+
status;
|
|
44
|
+
code;
|
|
45
|
+
constructor(message, status = 0, code = "") {
|
|
46
|
+
super(message);
|
|
47
|
+
this.status = status;
|
|
48
|
+
this.code = code;
|
|
49
|
+
this.name = "PromptError";
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
exports.PromptError = PromptError;
|
|
53
|
+
/** Thrown when no destination has the prompt (404 / not implemented everywhere) and there is no fallback. */
|
|
54
|
+
class PromptNotFound extends PromptError {
|
|
55
|
+
constructor(message, status = 0, code = "") {
|
|
56
|
+
super(message, status, code);
|
|
57
|
+
this.name = "PromptNotFound";
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
exports.PromptNotFound = PromptNotFound;
|
|
61
|
+
/** Thrown when a destination failed otherwise (transport, timeout, 5xx, a bad body) and there is no fallback. */
|
|
62
|
+
class PromptFetchError extends PromptError {
|
|
63
|
+
constructor(message, status = 0, code = "") {
|
|
64
|
+
super(message, status, code);
|
|
65
|
+
this.name = "PromptFetchError";
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
exports.PromptFetchError = PromptFetchError;
|
|
69
|
+
/** Thrown by compile() when a placeholder has no value; `missing` is sorted. */
|
|
70
|
+
class PromptCompileError extends PromptError {
|
|
71
|
+
missing;
|
|
72
|
+
constructor(missing) {
|
|
73
|
+
super(`prompt variables missing: ${missing.join(", ")}`, 0, "missing_variables");
|
|
74
|
+
this.missing = missing;
|
|
75
|
+
this.name = "PromptCompileError";
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
exports.PromptCompileError = PromptCompileError;
|
|
79
|
+
const PLACEHOLDER = /\{\{[ \t]*([A-Za-z_][A-Za-z0-9_]*)[ \t]*\}\}/g;
|
|
80
|
+
/** The distinct placeholder names in a body, sorted by byte order. */
|
|
81
|
+
function promptVariables(body) {
|
|
82
|
+
const texts = typeof body === "string" ? [body] : body.map((m) => m.content);
|
|
83
|
+
const names = new Set();
|
|
84
|
+
for (const t of texts)
|
|
85
|
+
for (const m of t.matchAll(PLACEHOLDER))
|
|
86
|
+
names.add(m[1]);
|
|
87
|
+
return [...names].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));
|
|
88
|
+
}
|
|
89
|
+
function valueText(v) {
|
|
90
|
+
return typeof v === "string" ? v : JSON.stringify(v);
|
|
91
|
+
}
|
|
92
|
+
/** Fill placeholders in one left-to-right pass; throws PromptCompileError naming every missing name. */
|
|
93
|
+
function compilePrompt(body, values) {
|
|
94
|
+
const missing = promptVariables(body).filter((n) => !Object.prototype.hasOwnProperty.call(values, n) || values[n] === undefined);
|
|
95
|
+
if (missing.length)
|
|
96
|
+
throw new PromptCompileError(missing);
|
|
97
|
+
// null renders as JSON null ("null"), as Python json.dumps(None) does (R-B19).
|
|
98
|
+
const one = (t) => t.replace(PLACEHOLDER, (_w, name) => valueText(values[name]));
|
|
99
|
+
return typeof body === "string" ? one(body) : body.map((m) => ({ ...m, content: one(m.content) }));
|
|
100
|
+
}
|
|
101
|
+
/** A fetched (or fallback) prompt. */
|
|
102
|
+
class Prompt {
|
|
103
|
+
name;
|
|
104
|
+
version;
|
|
105
|
+
label;
|
|
106
|
+
type;
|
|
107
|
+
prompt;
|
|
108
|
+
config;
|
|
109
|
+
labels;
|
|
110
|
+
digest;
|
|
111
|
+
isFallback;
|
|
112
|
+
rollout;
|
|
113
|
+
/** How the registry resolved it: `label:<name>` or `version:<n>` ("" for a fallback). */
|
|
114
|
+
resolvedBy;
|
|
115
|
+
/** The version's commit message ("" when none). */
|
|
116
|
+
commitMessage;
|
|
117
|
+
/** When the version was created (RFC 3339 UTC; "" for a fallback). */
|
|
118
|
+
createdAt;
|
|
119
|
+
/** Where this copy came from: `online`, `local` or `fallback` ("" when built by hand). */
|
|
120
|
+
source;
|
|
121
|
+
constructor(name, version,
|
|
122
|
+
/** The label it was resolved by ("" for a version fetch or a fallback). */
|
|
123
|
+
label, type, prompt,
|
|
124
|
+
/** Model parameters or other config stored with the version (`{}` when none). */
|
|
125
|
+
config = {},
|
|
126
|
+
/** The labels that point at this version now. */
|
|
127
|
+
labels = [],
|
|
128
|
+
/** `sha256:<hex>` of the version's canonical content. */
|
|
129
|
+
digest = "",
|
|
130
|
+
/** True when this is the caller's fallback, not a registry copy. */
|
|
131
|
+
isFallback = false,
|
|
132
|
+
/** The label's staged rollout, when it has one (the version above is the one SERVED). */
|
|
133
|
+
rollout = null, details = {}) {
|
|
134
|
+
this.name = name;
|
|
135
|
+
this.version = version;
|
|
136
|
+
this.label = label;
|
|
137
|
+
this.type = type;
|
|
138
|
+
this.prompt = prompt;
|
|
139
|
+
this.config = config;
|
|
140
|
+
this.labels = labels;
|
|
141
|
+
this.digest = digest;
|
|
142
|
+
this.isFallback = isFallback;
|
|
143
|
+
this.rollout = rollout;
|
|
144
|
+
this.resolvedBy = details.resolvedBy ?? "";
|
|
145
|
+
this.commitMessage = details.commitMessage ?? "";
|
|
146
|
+
this.createdAt = details.createdAt ?? "";
|
|
147
|
+
this.source = details.source ?? (isFallback ? "fallback" : "");
|
|
148
|
+
}
|
|
149
|
+
/** Which rollout side served this copy (`candidate`, `base`, `unkeyed`), "" when the label has no rollout. */
|
|
150
|
+
get cohort() {
|
|
151
|
+
return this.rollout?.cohort ?? "";
|
|
152
|
+
}
|
|
153
|
+
/** The body of a text prompt ("" for a chat prompt). */
|
|
154
|
+
get text() {
|
|
155
|
+
return typeof this.prompt === "string" ? this.prompt : "";
|
|
156
|
+
}
|
|
157
|
+
/** The messages of a chat prompt ([] for a text prompt). */
|
|
158
|
+
get messages() {
|
|
159
|
+
return typeof this.prompt === "string" ? [] : this.prompt.map((m) => ({ ...m }));
|
|
160
|
+
}
|
|
161
|
+
/** The placeholder names, sorted. */
|
|
162
|
+
get variables() {
|
|
163
|
+
return promptVariables(this.prompt);
|
|
164
|
+
}
|
|
165
|
+
/** Fill the variables and stamp the active span. A text prompt gives a string, a chat prompt a message list. */
|
|
166
|
+
compile(values = {}) {
|
|
167
|
+
const out = compilePrompt(this.prompt, values);
|
|
168
|
+
this.stamp();
|
|
169
|
+
return out;
|
|
170
|
+
}
|
|
171
|
+
/** Stamp this prompt's identity on `span` (default: the active span). Fallbacks stamp nothing. */
|
|
172
|
+
stamp(span = api_1.trace.getActiveSpan()) {
|
|
173
|
+
if (!span || this.isFallback)
|
|
174
|
+
return;
|
|
175
|
+
try {
|
|
176
|
+
if (!span.isRecording())
|
|
177
|
+
return;
|
|
178
|
+
span.setAttribute(attrs_js_1.K.promptName, this.name);
|
|
179
|
+
if (this.version)
|
|
180
|
+
span.setAttribute(attrs_js_1.K.promptVersion, this.version);
|
|
181
|
+
if (this.label)
|
|
182
|
+
span.setAttribute(attrs_js_1.K.promptLabel, this.label);
|
|
183
|
+
if (this.rollout)
|
|
184
|
+
span.setAttribute(attrs_js_1.K.promptCohort, this.rollout.cohort);
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
// ignore
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
exports.Prompt = Prompt;
|
|
192
|
+
function isMessages(v) {
|
|
193
|
+
return Array.isArray(v) && v.every((m) => m && typeof m === "object" && typeof m.content === "string" && typeof m.role === "string");
|
|
194
|
+
}
|
|
195
|
+
/** Parse a registry 200 body into a Prompt; null when it is not one. `source`: the destination that answered. */
|
|
196
|
+
function parsePrompt(body, fallbackName = "", source = "") {
|
|
197
|
+
if (body === null || typeof body !== "object" || Array.isArray(body))
|
|
198
|
+
return null;
|
|
199
|
+
const d = body;
|
|
200
|
+
let prompt;
|
|
201
|
+
if (typeof d.prompt === "string")
|
|
202
|
+
prompt = d.prompt;
|
|
203
|
+
else if (isMessages(d.prompt))
|
|
204
|
+
prompt = d.prompt.map((m) => ({ role: m.role, content: m.content }));
|
|
205
|
+
else
|
|
206
|
+
return null;
|
|
207
|
+
const resolved = typeof d.resolved_by === "string" ? d.resolved_by : "";
|
|
208
|
+
const label = resolved.startsWith("label:") ? resolved.slice("label:".length) : "";
|
|
209
|
+
const version = typeof d.version === "number" && Number.isInteger(d.version) ? d.version : 0;
|
|
210
|
+
const ro = d.rollout && typeof d.rollout === "object" && !Array.isArray(d.rollout) ? d.rollout : null;
|
|
211
|
+
const int = (v) => (typeof v === "number" && Number.isInteger(v) ? v : 0);
|
|
212
|
+
const rollout = ro && typeof ro.salt === "string" && ["candidate", "base", "unkeyed"].includes(String(ro.cohort))
|
|
213
|
+
? {
|
|
214
|
+
baseVersion: int(ro.base_version),
|
|
215
|
+
candidateVersion: int(ro.candidate_version),
|
|
216
|
+
percent: int(ro.percent),
|
|
217
|
+
cohort: ro.cohort,
|
|
218
|
+
key: ro.key === "user" || ro.key === "session" ? ro.key : "",
|
|
219
|
+
salt: ro.salt,
|
|
220
|
+
}
|
|
221
|
+
: null;
|
|
222
|
+
return new Prompt(typeof d.name === "string" && d.name ? d.name : fallbackName, version, label, d.type === "chat" || Array.isArray(prompt) ? "chat" : "text", prompt, d.config && typeof d.config === "object" && !Array.isArray(d.config) ? d.config : {}, Array.isArray(d.labels) ? d.labels.map(String) : [], typeof d.digest === "string" ? d.digest : "", false, rollout, {
|
|
223
|
+
resolvedBy: resolved,
|
|
224
|
+
commitMessage: typeof d.commit_message === "string" ? d.commit_message : "",
|
|
225
|
+
createdAt: typeof d.created_at === "string" ? d.created_at : "",
|
|
226
|
+
source,
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* The cache: per (destination, name, selector) a group of at most three
|
|
231
|
+
* entries keyed by side (prompts.md v2 section 9.4): `all` for an answer
|
|
232
|
+
* with no rollout, else the side the answer names (`candidate`, `base`,
|
|
233
|
+
* `unkeyed`).
|
|
234
|
+
*/
|
|
235
|
+
const cache = new Map();
|
|
236
|
+
/** Lowercase hex SHA-256 of a string's UTF-8 bytes (what the SDK sends as user_hash / session_hash). */
|
|
237
|
+
function cohortHash(id) {
|
|
238
|
+
return (0, node_crypto_1.createHash)("sha256").update(id, "utf8").digest("hex");
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* The rollout bucket of a subject (`user:<hash>` / `session:<hash>`):
|
|
242
|
+
* uint32 big-endian of the first 4 bytes of SHA-256(salt + "|" + subject),
|
|
243
|
+
* mod 100 (rolloutcore.HashBucket; pinned by sdk/contract/prompt-rollout-cases.json).
|
|
244
|
+
*/
|
|
245
|
+
function rolloutBucket(salt, subject) {
|
|
246
|
+
return (0, node_crypto_1.createHash)("sha256").update(`${salt}|${subject}`, "utf8").digest().readUInt32BE(0) % 100;
|
|
247
|
+
}
|
|
248
|
+
function cohortOf(opts, sel) {
|
|
249
|
+
if (sel.startsWith("version="))
|
|
250
|
+
return { subject: "", query: "" }; // a version fetch names its version
|
|
251
|
+
const cur = (0, context_js_1.getCurrentAttributes)();
|
|
252
|
+
const user = opts.user ?? cur.user ?? "";
|
|
253
|
+
if (user) {
|
|
254
|
+
const h = cohortHash(user);
|
|
255
|
+
return { subject: `user:${h}`, query: `&user_hash=${h}` };
|
|
256
|
+
}
|
|
257
|
+
const session = opts.sessionId ?? cur.sessionId ?? "";
|
|
258
|
+
if (session) {
|
|
259
|
+
const h = cohortHash(session);
|
|
260
|
+
return { subject: `session:${h}`, query: `&session_hash=${h}` };
|
|
261
|
+
}
|
|
262
|
+
return { subject: "", query: "" };
|
|
263
|
+
}
|
|
264
|
+
const sideOf = (p) => p.rollout?.cohort ?? "all";
|
|
265
|
+
const rolloutSig = (p) => (p.rollout ? `${p.rollout.candidateVersion}|${p.rollout.percent}|${p.rollout.salt}` : "");
|
|
266
|
+
/** The side this cohort is served from a group (section 9.4): bucket with a cached rollout, else `all`. */
|
|
267
|
+
function sideFor(group, c) {
|
|
268
|
+
const withRollout = [...group.values()].find((e) => e.prompt.rollout);
|
|
269
|
+
if (!withRollout)
|
|
270
|
+
return "all";
|
|
271
|
+
if (!c.subject)
|
|
272
|
+
return "unkeyed";
|
|
273
|
+
const r = withRollout.prompt.rollout;
|
|
274
|
+
return rolloutBucket(r.salt, c.subject) < r.percent ? "candidate" : "base";
|
|
275
|
+
}
|
|
276
|
+
/** Store an answer under the side it names; a changed rollout drops the other sides. */
|
|
277
|
+
function store(key, p, etag, query) {
|
|
278
|
+
let group = cache.get(key);
|
|
279
|
+
if (!group)
|
|
280
|
+
cache.set(key, (group = new Map()));
|
|
281
|
+
const sig = rolloutSig(p);
|
|
282
|
+
for (const [side, e] of group)
|
|
283
|
+
if (rolloutSig(e.prompt) !== sig)
|
|
284
|
+
group.delete(side);
|
|
285
|
+
group.set(sideOf(p), { prompt: p, etag, fetchedAt: Date.now(), refreshing: null, query });
|
|
286
|
+
}
|
|
287
|
+
function clearPromptCache() {
|
|
288
|
+
cache.clear();
|
|
289
|
+
}
|
|
290
|
+
/** How many entries the prompt cache holds (tests and diagnostics). */
|
|
291
|
+
function promptCacheSize() {
|
|
292
|
+
let n = 0;
|
|
293
|
+
for (const g of cache.values())
|
|
294
|
+
n += g.size;
|
|
295
|
+
return n;
|
|
296
|
+
}
|
|
297
|
+
function selector(opts) {
|
|
298
|
+
if (opts.version !== undefined && opts.label !== undefined) {
|
|
299
|
+
throw new TypeError("@superbased/sdk: getPrompt takes label or version, not both");
|
|
300
|
+
}
|
|
301
|
+
if (opts.version !== undefined) {
|
|
302
|
+
if (!Number.isInteger(opts.version) || opts.version < 1)
|
|
303
|
+
throw new RangeError("@superbased/sdk: prompt version must be a positive integer");
|
|
304
|
+
return `version=${opts.version}`;
|
|
305
|
+
}
|
|
306
|
+
const label = opts.label || exports.DEFAULT_PROMPT_LABEL;
|
|
307
|
+
if (!exports.PROMPT_LABELS.includes(label)) {
|
|
308
|
+
throw new RangeError(`@superbased/sdk: prompt label must be one of ${exports.PROMPT_LABELS.join(", ")}, got ${JSON.stringify(label)}`);
|
|
309
|
+
}
|
|
310
|
+
return `label=${label}`;
|
|
311
|
+
}
|
|
312
|
+
/** The envelope codes that mean "this server has no such prompt" (contract prompts.md). */
|
|
313
|
+
const NOT_FOUND_CODES = new Set(["prompt_not_found", "version_not_found", "label_not_set", "not_implemented"]);
|
|
314
|
+
/** The prompt name rule (contract sdk-api-surface.md section 7.3). */
|
|
315
|
+
const PROMPT_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
|
|
316
|
+
function envelopeCode(r) {
|
|
317
|
+
const b = r.body;
|
|
318
|
+
return b && typeof b === "object" && typeof b.error === "string" ? b.error : "";
|
|
319
|
+
}
|
|
320
|
+
/**
|
|
321
|
+
* Whether a response means "this server has no such prompt": a 404 or 501
|
|
322
|
+
* with a not-found code, or without an envelope (an older machine or org
|
|
323
|
+
* stub with no registry route). The same rule as Python's `_not_found`.
|
|
324
|
+
*/
|
|
325
|
+
function notFound(r) {
|
|
326
|
+
if (r.status !== 404 && r.status !== 501)
|
|
327
|
+
return false;
|
|
328
|
+
const code = envelopeCode(r);
|
|
329
|
+
return !code || NOT_FOUND_CODES.has(code);
|
|
330
|
+
}
|
|
331
|
+
function describe(r) {
|
|
332
|
+
if (r.status === 501 || (r.status === 404 && !envelopeCode(r)))
|
|
333
|
+
return `${r.target}: this server has no prompt registry`;
|
|
334
|
+
return `${r.target}: ${r.status ? `HTTP ${r.status} ` : ""}${r.error}${r.message ? `: ${r.message}` : ""}`;
|
|
335
|
+
}
|
|
336
|
+
/** One GET of the prompt on one destination (never rejects). */
|
|
337
|
+
function fetchOne(t, name, sel, opts, etag, query = "") {
|
|
338
|
+
const n = encodeURIComponent(name);
|
|
339
|
+
const route = { online: `/prompts/${n}?${sel}${query}`, local: `/api/obs/sdk/prompts/${n}?${sel}${query}` };
|
|
340
|
+
return (0, control_js_1.call)(t, "GET", route, { headers: etag ? { "If-None-Match": etag } : {}, timeoutMs: (0, control_js_1.apiTimeout)(opts), quiet404: true });
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* The cache key: ONE destination (its name and base URL), the name and the
|
|
344
|
+
* selector. Each destination keeps its own entry and revalidates against
|
|
345
|
+
* itself only, so under `both` a gateway that blips during revalidation
|
|
346
|
+
* can never drop a prompt the machine (or the gateway itself) served
|
|
347
|
+
* (review finding R-B08; Python keys the same way).
|
|
348
|
+
*/
|
|
349
|
+
function keyOf(t, name, sel) {
|
|
350
|
+
return JSON.stringify([t.name, t.base, name, sel]);
|
|
351
|
+
}
|
|
352
|
+
/**
|
|
353
|
+
* Revalidate one entry against the destination that served it, with its
|
|
354
|
+
* stored ETag: 304 renews it, 200 replaces it, that destination's own 404
|
|
355
|
+
* (a not-found code, or no registry) drops it, and any other failure keeps
|
|
356
|
+
* serving the cached copy (the failure is logged by `call`, at most once a
|
|
357
|
+
* minute).
|
|
358
|
+
*/
|
|
359
|
+
function refresh(key, side, t, name, sel, opts, e) {
|
|
360
|
+
if (e.refreshing)
|
|
361
|
+
return e.refreshing;
|
|
362
|
+
e.refreshing = (0, control_js_1.track)(fetchOne(t, name, sel, opts, e.etag, e.query).then((r) => {
|
|
363
|
+
if (r.status === 304) {
|
|
364
|
+
e.fetchedAt = Date.now();
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
if (r.ok) {
|
|
368
|
+
const p = parsePrompt(r.body, name, t.name);
|
|
369
|
+
if (p) {
|
|
370
|
+
const group = cache.get(key);
|
|
371
|
+
if (group && sideOf(p) !== side)
|
|
372
|
+
group.delete(side); // this key's side changed
|
|
373
|
+
store(key, p, r.etag, e.query);
|
|
374
|
+
}
|
|
375
|
+
return; // a 200 that is not a prompt keeps the cached copy
|
|
376
|
+
}
|
|
377
|
+
if (notFound(r)) {
|
|
378
|
+
const group = cache.get(key);
|
|
379
|
+
group?.delete(side);
|
|
380
|
+
if (group && !group.size)
|
|
381
|
+
cache.delete(key);
|
|
382
|
+
}
|
|
383
|
+
})).finally(() => {
|
|
384
|
+
e.refreshing = null;
|
|
385
|
+
});
|
|
386
|
+
return e.refreshing;
|
|
387
|
+
}
|
|
388
|
+
function stampIfInSpan(p) {
|
|
389
|
+
p.stamp();
|
|
390
|
+
return p;
|
|
391
|
+
}
|
|
392
|
+
/**
|
|
393
|
+
* Get a prompt from the registry.
|
|
394
|
+
*
|
|
395
|
+
* ```ts
|
|
396
|
+
* const p = await getPrompt("support-reply", { fallback: "Answer: {{question}}" });
|
|
397
|
+
* const text = p.compile({ question }); // also stamps the active span
|
|
398
|
+
* ```
|
|
399
|
+
*
|
|
400
|
+
* The destinations are asked in order (`both`: the gateway, then the
|
|
401
|
+
* machine); the first one holding a cached copy serves it, else the first
|
|
402
|
+
* one that answers 200. Fresh for `cacheTtlMs`; stale, the cached copy is
|
|
403
|
+
* returned at once and revalidated in the background against the same
|
|
404
|
+
* destination (`cacheTtlMs: 0` revalidates before returning). With nothing
|
|
405
|
+
* cached and no destination answering: `fallback` when given, else
|
|
406
|
+
* `PromptNotFound` (every destination said not found) or `PromptFetchError`.
|
|
407
|
+
*/
|
|
408
|
+
async function getPrompt(name, opts = {}) {
|
|
409
|
+
if (typeof name !== "string" || !PROMPT_NAME.test(name)) {
|
|
410
|
+
throw new TypeError(`@superbased/sdk: prompt name ${JSON.stringify(name)} must match ${PROMPT_NAME.source}`);
|
|
411
|
+
}
|
|
412
|
+
const sel = selector(opts);
|
|
413
|
+
const ttl = Math.max(0, opts.cacheTtlMs ?? runtime_js_1.runtime.settings?.promptCacheTtlMs ?? envTtl());
|
|
414
|
+
const errors = [];
|
|
415
|
+
let allNotFound = true;
|
|
416
|
+
let last = null;
|
|
417
|
+
const cohort = cohortOf(opts, sel);
|
|
418
|
+
await (0, runtime_js_1.destinationKnown)();
|
|
419
|
+
const sides = (0, control_js_1.targets)("read", opts);
|
|
420
|
+
// A degraded online has no target: that is a fetch failure (the reason
|
|
421
|
+
// says why), never "not found" (contract section 6; as Python).
|
|
422
|
+
if (!sides.length)
|
|
423
|
+
allNotFound = false;
|
|
424
|
+
for (const t of sides) {
|
|
425
|
+
const key = keyOf(t, name, sel);
|
|
426
|
+
const group = cache.get(key);
|
|
427
|
+
const side = group ? sideFor(group, cohort) : "";
|
|
428
|
+
const hit = group?.get(side);
|
|
429
|
+
if (hit) {
|
|
430
|
+
if (Date.now() - hit.fetchedAt < ttl)
|
|
431
|
+
return stampIfInSpan(hit.prompt);
|
|
432
|
+
if (ttl > 0) {
|
|
433
|
+
void refresh(key, side, t, name, sel, opts, hit); // stale-while-revalidate
|
|
434
|
+
return stampIfInSpan(hit.prompt);
|
|
435
|
+
}
|
|
436
|
+
await refresh(key, side, t, name, sel, opts, hit);
|
|
437
|
+
const now = cache.get(key)?.get(sideFor(cache.get(key) ?? new Map(), cohort));
|
|
438
|
+
if (now)
|
|
439
|
+
return stampIfInSpan(now.prompt);
|
|
440
|
+
// this destination dropped it (its own 404): ask the next one
|
|
441
|
+
continue;
|
|
442
|
+
}
|
|
443
|
+
const r = await fetchOne(t, name, sel, opts, "", cohort.query);
|
|
444
|
+
last = r;
|
|
445
|
+
if (r.ok && r.status !== 304) {
|
|
446
|
+
const p = parsePrompt(r.body, name, t.name);
|
|
447
|
+
if (p) {
|
|
448
|
+
store(key, p, r.etag, cohort.query);
|
|
449
|
+
return stampIfInSpan(p);
|
|
450
|
+
}
|
|
451
|
+
allNotFound = false;
|
|
452
|
+
errors.push(`${t.name}: the body is not a prompt`);
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
455
|
+
if (notFound(r)) {
|
|
456
|
+
errors.push(describe(r));
|
|
457
|
+
continue;
|
|
458
|
+
}
|
|
459
|
+
allNotFound = false;
|
|
460
|
+
errors.push(describe(r));
|
|
461
|
+
}
|
|
462
|
+
if (opts.fallback !== undefined) {
|
|
463
|
+
const type = Array.isArray(opts.fallback) ? "chat" : "text";
|
|
464
|
+
return new Prompt(name, 0, "", type, opts.fallback, {}, [], "", true);
|
|
465
|
+
}
|
|
466
|
+
const detail = errors.join("; ") || (0, control_js_1.noTargetReason)();
|
|
467
|
+
if (allNotFound)
|
|
468
|
+
throw new PromptNotFound(`prompt ${JSON.stringify(name)} (${sel}) not found: ${detail}`, last?.status ?? 0, last?.error ?? "no_target");
|
|
469
|
+
throw new PromptFetchError(`prompt ${JSON.stringify(name)} (${sel}) could not be fetched: ${detail}`, last?.status ?? 0, last?.error ?? "");
|
|
470
|
+
}
|
|
471
|
+
function envTtl() {
|
|
472
|
+
const raw = ((typeof process !== "undefined" ? process.env.SUPERBASED_PROMPT_CACHE_TTL_MS : "") ?? "").trim();
|
|
473
|
+
const n = Number(raw);
|
|
474
|
+
return raw && Number.isFinite(n) && n >= 0 ? n : 60_000;
|
|
475
|
+
}
|
|
476
|
+
//# sourceMappingURL=prompts.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prompts.js","sourceRoot":"","sources":["../../src/prompts.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;;;AA2FH,0CAKC;AAOD,sCAMC;AAiGD,kCAyCC;AAoBD,gCAEC;AAOD,sCAEC;AA8CD,4CAEC;AAGD,0CAIC;AAuHD,8BA0DC;AA5fD,6CAAyC;AAEzC,4CAAsD;AAEtD,yCAA+B;AAC/B,6CAAwI;AACxI,6CAAoD;AACpD,6CAAyD;AAE5C,QAAA,oBAAoB,GAAG,YAAY,CAAC;AACpC,QAAA,aAAa,GAAG,CAAC,YAAY,EAAE,SAAS,CAAU,CAAC;AAwChE,gFAAgF;AAChF,MAAa,WAAY,SAAQ,KAAK;IAGzB;IACA;IAHX,YACE,OAAe,EACN,SAAS,CAAC,EACV,OAAO,EAAE;QAElB,KAAK,CAAC,OAAO,CAAC,CAAC;QAHN,WAAM,GAAN,MAAM,CAAI;QACV,SAAI,GAAJ,IAAI,CAAK;QAGlB,IAAI,CAAC,IAAI,GAAG,aAAa,CAAC;IAC5B,CAAC;CACF;AATD,kCASC;AAED,6GAA6G;AAC7G,MAAa,cAAe,SAAQ,WAAW;IAC7C,YAAY,OAAe,EAAE,MAAM,GAAG,CAAC,EAAE,IAAI,GAAG,EAAE;QAChD,KAAK,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC;QAC7B,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAC;IAC/B,CAAC;CACF;AALD,wCAKC;AAED,iHAAiH;AACjH,MAAa,gBAAiB,SAAQ,WAAW;IAC/C,YAAY,OAAe,EAAE,MAAM,GAAG,CAAC,EAAE,IA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AG,2BAA2B,MAAM,EAAE,EAAE,IAAI,EAAE,MAAM,IAAI,CAAC,EAAE,IAAI,EAAE,KAAK,IAAI,EAAE,CAAC,CAAC;AAC9I,CAAC;AAED,SAAS,MAAM;IACb,MAAM,GAAG,GAAG,CAAC,CAAC,OAAO,OAAO,KAAK,WAAW,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,8BAA8B,CAAC,CAAC,CAAC,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC;IAC9G,MAAM,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;IACtB,OAAO,GAAG,IAAI,MAAM,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC;AAC1D,CAAC","sourcesContent":["/**\n * Prompt registry client (W3-3; contract `contracts/prompts.md`, lane B8).\n *\n * - Fetch: online `GET <org>/v1/sdk/prompts/{name}` (scope `sdk:read`),\n * local `GET <machine>/api/obs/sdk/prompts/{name}`; `both` prefers online\n * and falls back to local. `?label=` or `?version=`, never both; neither is\n * `label=production`.\n * - Cache per (endpoint, name, selector): fresh for `cacheTtlMs` (default\n * 60 s, `SUPERBASED_PROMPT_CACHE_TTL_MS`). After that the cached prompt is\n * returned at once and revalidated in the background with `If-None-Match`\n * (stale-while-revalidate); a 304 renews it, a 404 drops it, any other\n * failure keeps serving it.\n * - A first fetch that fails throws {@link PromptNotFound}, unless you pass a\n * `fallback`, which is returned marked `isFallback` and never cached.\n * - `compile(values)` fills `{{name}}` placeholders in one pass (a value is\n * never re-scanned) and throws {@link PromptCompileError} naming every\n * missing variable. `prompt.compile()`, `getPrompt()` inside a span and\n * `withLlmSpan(..., { promptRef })` stamp `sbo.prompt.name`,\n * `sbo.prompt.version` and (for a label fetch) `sbo.prompt.label` on the\n * span. A fallback stamps nothing.\n */\n\nimport { createHash } from \"node:crypto\";\n\nimport { trace, type Span } from \"@opentelemetry/api\";\n\nimport { K } from \"./attrs.js\";\nimport { apiTimeout, call, noTargetReason, targets, track, type ControlOptions, type ControlResponse, type Target } from \"./control.js\";\nimport { getCurrentAttributes } from \"./context.js\";\nimport { destinationKnown, runtime } from \"./runtime.js\";\n\nexport const DEFAULT_PROMPT_LABEL = \"production\";\nexport const PROMPT_LABELS = [\"production\", \"staging\"] as const;\n\nexport interface ChatMessage {\n role: string;\n content: string;\n}\n\nexport type PromptBody = string | ChatMessage[];\n\nexport interface GetPromptOptions extends ControlOptions {\n /** `production` (default) or `staging`. Exclusive with `version`. */\n label?: string;\n /** An exact version number. Exclusive with `label`. */\n version?: number;\n /** Cache freshness in ms (default: the promptCacheTtlMs setting, 60 000). 0 revalidates on every call. */\n cacheTtlMs?: number;\n /** Returned (marked isFallback, never cached) when the prompt cannot be fetched and nothing is cached. */\n fallback?: PromptBody;\n /**\n * The end user that picks the side of a staged rollout (prompts.md v2\n * section 9.2). Default: the current trace's user (`propagateAttributes`\n * / `identify`). Only its SHA-256 is sent.\n */\n user?: string;\n /** The session that picks the side when there is no user. Default: the current trace's session. */\n sessionId?: string;\n}\n\n/** A label's staged rollout as the server reported it (prompts.md v2 section 9.3). */\nexport interface PromptRollout {\n baseVersion: number;\n candidateVersion: number;\n percent: number;\n /** Which side this key was served: `candidate`, `base` or `unkeyed`. */\n cohort: \"candidate\" | \"base\" | \"unkeyed\";\n /** Which key decided: `user`, `session` or \"\". */\n key: \"user\" | \"session\" | \"\";\n salt: string;\n}\n\n/** The base of every prompt error (contract sdk-api-surface.md section 7.3). */\nexport class PromptError extends Error {\n constructor(\n message: string,\n readonly status = 0,\n readonly code = \"\",\n ) {\n super(message);\n this.name = \"PromptError\";\n }\n}\n\n/** Thrown when no destination has the prompt (404 / not implemented everywhere) and there is no fallback. */\nexport class PromptNotFound extends PromptError {\n constructor(message: string, status = 0, code = \"\") {\n super(message, status, code);\n this.name = \"PromptNotFound\";\n }\n}\n\n/** Thrown when a destination failed otherwise (transport, timeout, 5xx, a bad body) and there is no fallback. */\nexport class PromptFetchError extends PromptError {\n constructor(message: string, status = 0, code = \"\") {\n super(message, status, code);\n this.name = \"PromptFetchError\";\n }\n}\n\n/** Thrown by compile() when a placeholder has no value; `missing` is sorted. */\nexport class PromptCompileError extends PromptError {\n constructor(readonly missing: string[]) {\n super(`prompt variables missing: ${missing.join(\", \")}`, 0, \"missing_variables\");\n this.name = \"PromptCompileError\";\n }\n}\n\nconst PLACEHOLDER = /\\{\\{[ \\t]*([A-Za-z_][A-Za-z0-9_]*)[ \\t]*\\}\\}/g;\n\n/** The distinct placeholder names in a body, sorted by byte order. */\nexport function promptVariables(body: PromptBody): string[] {\n const texts = typeof body === \"string\" ? [body] : body.map((m) => m.content);\n const names = new Set<string>();\n for (const t of texts) for (const m of t.matchAll(PLACEHOLDER)) names.add(m[1]);\n return [...names].sort((a, b) => (a < b ? -1 : a > b ? 1 : 0));\n}\n\nfunction valueText(v: unknown): string {\n return typeof v === \"string\" ? v : JSON.stringify(v);\n}\n\n/** Fill placeholders in one left-to-right pass; throws PromptCompileError naming every missing name. */\nexport function compilePrompt(body: PromptBody, values: Record<string, unknown>): PromptBody {\n const missing = promptVariables(body).filter((n) => !Object.prototype.hasOwnProperty.call(values, n) || values[n] === undefined);\n if (missing.length) throw new PromptCompileError(missing);\n // null renders as JSON null (\"null\"), as Python json.dumps(None) does (R-B19).\n const one = (t: string) => t.replace(PLACEHOLDER, (_w, name: string) => valueText(values[name]));\n return typeof body === \"string\" ? one(body) : body.map((m) => ({ ...m, content: one(m.content) }));\n}\n\n/** Registry fields Python's Prompt also carries (contract prompts.md). */\nexport interface PromptDetails {\n /** How the registry resolved it: `label:<name>` or `version:<n>` (\"\" for a fallback). */\n resolvedBy?: string;\n /** The version's commit message (\"\" when none). */\n commitMessage?: string;\n /** When the version was created (RFC 3339 UTC; \"\" for a fallback). */\n createdAt?: string;\n /** Where this copy came from: `online`, `local` or `fallback`. */\n source?: string;\n}\n\n/** A fetched (or fallback) prompt. */\nexport class Prompt {\n /** How the registry resolved it: `label:<name>` or `version:<n>` (\"\" for a fallback). */\n readonly resolvedBy: string;\n /** The version's commit message (\"\" when none). */\n readonly commitMessage: string;\n /** When the version was created (RFC 3339 UTC; \"\" for a fallback). */\n readonly createdAt: string;\n /** Where this copy came from: `online`, `local` or `fallback` (\"\" when built by hand). */\n readonly source: string;\n\n constructor(\n readonly name: string,\n readonly version: number,\n /** The label it was resolved by (\"\" for a version fetch or a fallback). */\n readonly label: string,\n readonly type: \"text\" | \"chat\",\n readonly prompt: PromptBody,\n /** Model parameters or other config stored with the version (`{}` when none). */\n readonly config: Record<string, unknown> = {},\n /** The labels that point at this version now. */\n readonly labels: string[] = [],\n /** `sha256:<hex>` of the version's canonical content. */\n readonly digest = \"\",\n /** True when this is the caller's fallback, not a registry copy. */\n readonly isFallback = false,\n /** The label's staged rollout, when it has one (the version above is the one SERVED). */\n readonly rollout: PromptRollout | null = null,\n details: PromptDetails = {},\n ) {\n this.resolvedBy = details.resolvedBy ?? \"\";\n this.commitMessage = details.commitMessage ?? \"\";\n this.createdAt = details.createdAt ?? \"\";\n this.source = details.source ?? (isFallback ? \"fallback\" : \"\");\n }\n\n /** Which rollout side served this copy (`candidate`, `base`, `unkeyed`), \"\" when the label has no rollout. */\n get cohort(): string {\n return this.rollout?.cohort ?? \"\";\n }\n\n /** The body of a text prompt (\"\" for a chat prompt). */\n get text(): string {\n return typeof this.prompt === \"string\" ? this.prompt : \"\";\n }\n\n /** The messages of a chat prompt ([] for a text prompt). */\n get messages(): ChatMessage[] {\n return typeof this.prompt === \"string\" ? [] : this.prompt.map((m) => ({ ...m }));\n }\n\n /** The placeholder names, sorted. */\n get variables(): string[] {\n return promptVariables(this.prompt);\n }\n\n /** Fill the variables and stamp the active span. A text prompt gives a string, a chat prompt a message list. */\n compile(values: Record<string, unknown> = {}): PromptBody {\n const out = compilePrompt(this.prompt, values);\n this.stamp();\n return out;\n }\n\n /** Stamp this prompt's identity on `span` (default: the active span). Fallbacks stamp nothing. */\n stamp(span: Span | undefined = trace.getActiveSpan()): void {\n if (!span || this.isFallback) return;\n try {\n if (!span.isRecording()) return;\n span.setAttribute(K.promptName, this.name);\n if (this.version) span.setAttribute(K.promptVersion, this.version);\n if (this.label) span.setAttribute(K.promptLabel, this.label);\n if (this.rollout) span.setAttribute(K.promptCohort, this.rollout.cohort);\n } catch {\n // ignore\n }\n }\n}\n\nfunction isMessages(v: unknown): v is ChatMessage[] {\n return Array.isArray(v) && v.every((m) => m && typeof m === \"object\" && typeof (m as ChatMessage).content === \"string\" && typeof (m as ChatMessage).role === \"string\");\n}\n\n/** Parse a registry 200 body into a Prompt; null when it is not one. `source`: the destination that answered. */\nexport function parsePrompt(body: unknown, fallbackName = \"\", source = \"\"): Prompt | null {\n if (body === null || typeof body !== \"object\" || Array.isArray(body)) return null;\n const d = body as Record<string, unknown>;\n let prompt: PromptBody;\n if (typeof d.prompt === \"string\") prompt = d.prompt;\n else if (isMessages(d.prompt)) prompt = d.prompt.map((m) => ({ role: m.role, content: m.content }));\n else return null;\n const resolved = typeof d.resolved_by === \"string\" ? d.resolved_by : \"\";\n const label = resolved.startsWith(\"label:\") ? resolved.slice(\"label:\".length) : \"\";\n const version = typeof d.version === \"number\" && Number.isInteger(d.version) ? d.version : 0;\n const ro = d.rollout && typeof d.rollout === \"object\" && !Array.isArray(d.rollout) ? (d.rollout as Record<string, unknown>) : null;\n const int = (v: unknown) => (typeof v === \"number\" && Number.isInteger(v) ? v : 0);\n const rollout: PromptRollout | null =\n ro && typeof ro.salt === \"string\" && [\"candidate\", \"base\", \"unkeyed\"].includes(String(ro.cohort))\n ? {\n baseVersion: int(ro.base_version),\n candidateVersion: int(ro.candidate_version),\n percent: int(ro.percent),\n cohort: ro.cohort as PromptRollout[\"cohort\"],\n key: ro.key === \"user\" || ro.key === \"session\" ? ro.key : \"\",\n salt: ro.salt,\n }\n : null;\n return new Prompt(\n typeof d.name === \"string\" && d.name ? d.name : fallbackName,\n version,\n label,\n d.type === \"chat\" || Array.isArray(prompt) ? \"chat\" : \"text\",\n prompt,\n d.config && typeof d.config === \"object\" && !Array.isArray(d.config) ? (d.config as Record<string, unknown>) : {},\n Array.isArray(d.labels) ? d.labels.map(String) : [],\n typeof d.digest === \"string\" ? d.digest : \"\",\n false,\n rollout,\n {\n resolvedBy: resolved,\n commitMessage: typeof d.commit_message === \"string\" ? d.commit_message : \"\",\n createdAt: typeof d.created_at === \"string\" ? d.created_at : \"\",\n source,\n },\n );\n}\n\ninterface Entry {\n prompt: Prompt;\n etag: string;\n fetchedAt: number;\n refreshing: Promise<void> | null;\n /** The cohort query that filled this entry (revalidated with the same key, section 9.4). */\n query: string;\n}\n\n/**\n * The cache: per (destination, name, selector) a group of at most three\n * entries keyed by side (prompts.md v2 section 9.4): `all` for an answer\n * with no rollout, else the side the answer names (`candidate`, `base`,\n * `unkeyed`).\n */\nconst cache = new Map<string, Map<string, Entry>>();\n\n/** Lowercase hex SHA-256 of a string's UTF-8 bytes (what the SDK sends as user_hash / session_hash). */\nexport function cohortHash(id: string): string {\n return createHash(\"sha256\").update(id, \"utf8\").digest(\"hex\");\n}\n\n/**\n * The rollout bucket of a subject (`user:<hash>` / `session:<hash>`):\n * uint32 big-endian of the first 4 bytes of SHA-256(salt + \"|\" + subject),\n * mod 100 (rolloutcore.HashBucket; pinned by sdk/contract/prompt-rollout-cases.json).\n */\nexport function rolloutBucket(salt: string, subject: string): number {\n return createHash(\"sha256\").update(`${salt}|${subject}`, \"utf8\").digest().readUInt32BE(0) % 100;\n}\n\ninterface Cohort {\n /** `user:<hash>`, `session:<hash>` or \"\" (unkeyed). */\n subject: string;\n /** The query parameter that carries it (\"\" when unkeyed). */\n query: string;\n}\n\nfunction cohortOf(opts: GetPromptOptions, sel: string): Cohort {\n if (sel.startsWith(\"version=\")) return { subject: \"\", query: \"\" }; // a version fetch names its version\n const cur = getCurrentAttributes() as { user?: string; sessionId?: string };\n const user = opts.user ?? cur.user ?? \"\";\n if (user) {\n const h = cohortHash(user);\n return { subject: `user:${h}`, query: `&user_hash=${h}` };\n }\n const session = opts.sessionId ?? cur.sessionId ?? \"\";\n if (session) {\n const h = cohortHash(session);\n return { subject: `session:${h}`, query: `&session_hash=${h}` };\n }\n return { subject: \"\", query: \"\" };\n}\n\nconst sideOf = (p: Prompt) => p.rollout?.cohort ?? \"all\";\nconst rolloutSig = (p: Prompt) => (p.rollout ? `${p.rollout.candidateVersion}|${p.rollout.percent}|${p.rollout.salt}` : \"\");\n\n/** The side this cohort is served from a group (section 9.4): bucket with a cached rollout, else `all`. */\nfunction sideFor(group: Map<string, Entry>, c: Cohort): string {\n const withRollout = [...group.values()].find((e) => e.prompt.rollout);\n if (!withRollout) return \"all\";\n if (!c.subject) return \"unkeyed\";\n const r = withRollout.prompt.rollout!;\n return rolloutBucket(r.salt, c.subject) < r.percent ? \"candidate\" : \"base\";\n}\n\n/** Store an answer under the side it names; a changed rollout drops the other sides. */\nfunction store(key: string, p: Prompt, etag: string, query: string): void {\n let group = cache.get(key);\n if (!group) cache.set(key, (group = new Map()));\n const sig = rolloutSig(p);\n for (const [side, e] of group) if (rolloutSig(e.prompt) !== sig) group.delete(side);\n group.set(sideOf(p), { prompt: p, etag, fetchedAt: Date.now(), refreshing: null, query });\n}\n\nexport function clearPromptCache(): void {\n cache.clear();\n}\n\n/** How many entries the prompt cache holds (tests and diagnostics). */\nexport function promptCacheSize(): number {\n let n = 0;\n for (const g of cache.values()) n += g.size;\n return n;\n}\n\nfunction selector(opts: GetPromptOptions): string {\n if (opts.version !== undefined && opts.label !== undefined) {\n throw new TypeError(\"@superbased/sdk: getPrompt takes label or version, not both\");\n }\n if (opts.version !== undefined) {\n if (!Number.isInteger(opts.version) || opts.version < 1) throw new RangeError(\"@superbased/sdk: prompt version must be a positive integer\");\n return `version=${opts.version}`;\n }\n const label = opts.label || DEFAULT_PROMPT_LABEL;\n if (!(PROMPT_LABELS as readonly string[]).includes(label)) {\n throw new RangeError(`@superbased/sdk: prompt label must be one of ${PROMPT_LABELS.join(\", \")}, got ${JSON.stringify(label)}`);\n }\n return `label=${label}`;\n}\n\n/** The envelope codes that mean \"this server has no such prompt\" (contract prompts.md). */\nconst NOT_FOUND_CODES = new Set([\"prompt_not_found\", \"version_not_found\", \"label_not_set\", \"not_implemented\"]);\n\n/** The prompt name rule (contract sdk-api-surface.md section 7.3). */\nconst PROMPT_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;\n\nfunction envelopeCode(r: ControlResponse): string {\n const b = r.body;\n return b && typeof b === \"object\" && typeof (b as { error?: unknown }).error === \"string\" ? (b as { error: string }).error : \"\";\n}\n\n/**\n * Whether a response means \"this server has no such prompt\": a 404 or 501\n * with a not-found code, or without an envelope (an older machine or org\n * stub with no registry route). The same rule as Python's `_not_found`.\n */\nfunction notFound(r: ControlResponse): boolean {\n if (r.status !== 404 && r.status !== 501) return false;\n const code = envelopeCode(r);\n return !code || NOT_FOUND_CODES.has(code);\n}\n\nfunction describe(r: ControlResponse): string {\n if (r.status === 501 || (r.status === 404 && !envelopeCode(r))) return `${r.target}: this server has no prompt registry`;\n return `${r.target}: ${r.status ? `HTTP ${r.status} ` : \"\"}${r.error}${r.message ? `: ${r.message}` : \"\"}`;\n}\n\n/** One GET of the prompt on one destination (never rejects). */\nfunction fetchOne(t: Target, name: string, sel: string, opts: GetPromptOptions, etag: string, query = \"\"): Promise<ControlResponse> {\n const n = encodeURIComponent(name);\n const route = { online: `/prompts/${n}?${sel}${query}`, local: `/api/obs/sdk/prompts/${n}?${sel}${query}` };\n return call(t, \"GET\", route, { headers: etag ? { \"If-None-Match\": etag } : {}, timeoutMs: apiTimeout(opts), quiet404: true });\n}\n\n/**\n * The cache key: ONE destination (its name and base URL), the name and the\n * selector. Each destination keeps its own entry and revalidates against\n * itself only, so under `both` a gateway that blips during revalidation\n * can never drop a prompt the machine (or the gateway itself) served\n * (review finding R-B08; Python keys the same way).\n */\nfunction keyOf(t: Target, name: string, sel: string): string {\n return JSON.stringify([t.name, t.base, name, sel]);\n}\n\n/**\n * Revalidate one entry against the destination that served it, with its\n * stored ETag: 304 renews it, 200 replaces it, that destination's own 404\n * (a not-found code, or no registry) drops it, and any other failure keeps\n * serving the cached copy (the failure is logged by `call`, at most once a\n * minute).\n */\nfunction refresh(key: string, side: string, t: Target, name: string, sel: string, opts: GetPromptOptions, e: Entry): Promise<void> {\n if (e.refreshing) return e.refreshing;\n e.refreshing = track(\n fetchOne(t, name, sel, opts, e.etag, e.query).then((r) => {\n if (r.status === 304) {\n e.fetchedAt = Date.now();\n return;\n }\n if (r.ok) {\n const p = parsePrompt(r.body, name, t.name);\n if (p) {\n const group = cache.get(key);\n if (group && sideOf(p) !== side) group.delete(side); // this key's side changed\n store(key, p, r.etag, e.query);\n }\n return; // a 200 that is not a prompt keeps the cached copy\n }\n if (notFound(r)) {\n const group = cache.get(key);\n group?.delete(side);\n if (group && !group.size) cache.delete(key);\n }\n }),\n ).finally(() => {\n e.refreshing = null;\n });\n return e.refreshing;\n}\n\nfunction stampIfInSpan(p: Prompt): Prompt {\n p.stamp();\n return p;\n}\n\n/**\n * Get a prompt from the registry.\n *\n * ```ts\n * const p = await getPrompt(\"support-reply\", { fallback: \"Answer: {{question}}\" });\n * const text = p.compile({ question }); // also stamps the active span\n * ```\n *\n * The destinations are asked in order (`both`: the gateway, then the\n * machine); the first one holding a cached copy serves it, else the first\n * one that answers 200. Fresh for `cacheTtlMs`; stale, the cached copy is\n * returned at once and revalidated in the background against the same\n * destination (`cacheTtlMs: 0` revalidates before returning). With nothing\n * cached and no destination answering: `fallback` when given, else\n * `PromptNotFound` (every destination said not found) or `PromptFetchError`.\n */\nexport async function getPrompt(name: string, opts: GetPromptOptions = {}): Promise<Prompt> {\n if (typeof name !== \"string\" || !PROMPT_NAME.test(name)) {\n throw new TypeError(`@superbased/sdk: prompt name ${JSON.stringify(name)} must match ${PROMPT_NAME.source}`);\n }\n const sel = selector(opts);\n const ttl = Math.max(0, opts.cacheTtlMs ?? runtime.settings?.promptCacheTtlMs ?? envTtl());\n const errors: string[] = [];\n let allNotFound = true;\n let last: ControlResponse | null = null;\n const cohort = cohortOf(opts, sel);\n await destinationKnown();\n const sides = targets(\"read\", opts);\n // A degraded online has no target: that is a fetch failure (the reason\n // says why), never \"not found\" (contract section 6; as Python).\n if (!sides.length) allNotFound = false;\n for (const t of sides) {\n const key = keyOf(t, name, sel);\n const group = cache.get(key);\n const side = group ? sideFor(group, cohort) : \"\";\n const hit = group?.get(side);\n if (hit) {\n if (Date.now() - hit.fetchedAt < ttl) return stampIfInSpan(hit.prompt);\n if (ttl > 0) {\n void refresh(key, side, t, name, sel, opts, hit); // stale-while-revalidate\n return stampIfInSpan(hit.prompt);\n }\n await refresh(key, side, t, name, sel, opts, hit);\n const now = cache.get(key)?.get(sideFor(cache.get(key) ?? new Map(), cohort));\n if (now) return stampIfInSpan(now.prompt);\n // this destination dropped it (its own 404): ask the next one\n continue;\n }\n const r = await fetchOne(t, name, sel, opts, \"\", cohort.query);\n last = r;\n if (r.ok && r.status !== 304) {\n const p = parsePrompt(r.body, name, t.name);\n if (p) {\n store(key, p, r.etag, cohort.query);\n return stampIfInSpan(p);\n }\n allNotFound = false;\n errors.push(`${t.name}: the body is not a prompt`);\n continue;\n }\n if (notFound(r)) {\n errors.push(describe(r));\n continue;\n }\n allNotFound = false;\n errors.push(describe(r));\n }\n if (opts.fallback !== undefined) {\n const type = Array.isArray(opts.fallback) ? \"chat\" : \"text\";\n return new Prompt(name, 0, \"\", type, opts.fallback, {}, [], \"\", true);\n }\n const detail = errors.join(\"; \") || noTargetReason();\n if (allNotFound) throw new PromptNotFound(`prompt ${JSON.stringify(name)} (${sel}) not found: ${detail}`, last?.status ?? 0, last?.error ?? \"no_target\");\n throw new PromptFetchError(`prompt ${JSON.stringify(name)} (${sel}) could not be fetched: ${detail}`, last?.status ?? 0, last?.error ?? \"\");\n}\n\nfunction envTtl(): number {\n const raw = ((typeof process !== \"undefined\" ? process.env.SUPERBASED_PROMPT_CACHE_TTL_MS : \"\") ?? \"\").trim();\n const n = Number(raw);\n return raw && Number.isFinite(n) && n >= 0 ? n : 60_000;\n}\n"]}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* W3C trace-context helpers (contract sdk-api-surface.md section 4), for
|
|
3
|
+
* joining a trace across a process boundary the SDK does not instrument (a
|
|
4
|
+
* queue message, a job, a hand-rolled HTTP call). They always use the W3C
|
|
5
|
+
* propagators, whatever global propagator the host has configured.
|
|
6
|
+
*
|
|
7
|
+
* `inject()` also writes `baggage` when per-request values were set with
|
|
8
|
+
* `propagateAttributes({ ..., asBaggage: true })`; `continueTrace()` restores
|
|
9
|
+
* them into the attribute scope on the other side.
|
|
10
|
+
*/
|
|
11
|
+
import { type Context } from "@opentelemetry/api";
|
|
12
|
+
/** A header bag: a plain object (string or string[] values) or a fetch `Headers`. */
|
|
13
|
+
export type Carrier = Record<string, string | string[] | undefined> | {
|
|
14
|
+
get(name: string): string | null;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Write `traceparent` (+ `tracestate`, + `baggage` when per-request values
|
|
18
|
+
* were set `asBaggage`) for the current context into `carrier` (a new object
|
|
19
|
+
* when omitted) and return it.
|
|
20
|
+
*
|
|
21
|
+
* ```ts
|
|
22
|
+
* await queue.send({ body, headers: inject() });
|
|
23
|
+
* ```
|
|
24
|
+
*/
|
|
25
|
+
export declare function inject<T extends Record<string, string>>(carrier?: T): T;
|
|
26
|
+
/** The context the W3C headers in `carrier` describe (case-insensitive); the active context when there are none. */
|
|
27
|
+
export declare function extract(carrier: Carrier): Context;
|
|
28
|
+
/**
|
|
29
|
+
* Run `fn` as part of the trace `carrier` names (spans inside join the
|
|
30
|
+
* caller's trace), restoring per-request values the caller sent as baggage.
|
|
31
|
+
*/
|
|
32
|
+
export declare function continueTrace<T>(carrier: Carrier, fn: () => T): T;
|
|
33
|
+
/** The `traceparent` value of the active span ("" outside a span). */
|
|
34
|
+
export declare function getTraceparent(): string;
|