@originatedev/run-sdk 0.1.0 → 0.1.2
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/README.md +35 -1
- package/dist/cjs/ai.d.ts +13 -0
- package/dist/cjs/ai.js +308 -0
- package/dist/cjs/ai.js.map +1 -0
- package/dist/cjs/cli.d.ts +18 -0
- package/dist/cjs/cli.js +162 -0
- package/dist/cjs/cli.js.map +1 -0
- package/dist/cjs/express.d.ts +30 -0
- package/dist/cjs/express.js +54 -0
- package/dist/cjs/express.js.map +1 -0
- package/dist/cjs/fastify.d.ts +32 -0
- package/dist/cjs/fastify.js +38 -0
- package/dist/cjs/fastify.js.map +1 -0
- package/dist/cjs/index.d.ts +139 -0
- package/dist/cjs/index.js +653 -0
- package/dist/cjs/index.js.map +1 -0
- package/dist/cjs/metrics.d.ts +33 -0
- package/dist/cjs/metrics.js +120 -0
- package/dist/cjs/metrics.js.map +1 -0
- package/dist/cjs/otel.d.ts +43 -0
- package/dist/cjs/otel.js +111 -0
- package/dist/cjs/otel.js.map +1 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/transport.d.ts +53 -0
- package/dist/cjs/transport.js +139 -0
- package/dist/cjs/transport.js.map +1 -0
- package/dist/cjs/types.d.ts +240 -0
- package/dist/cjs/types.js +18 -0
- package/dist/cjs/types.js.map +1 -0
- package/package.json +40 -18
|
@@ -0,0 +1,653 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* @originatedev/run-sdk: the backend SDK for Run, Originate's managed service.
|
|
4
|
+
*
|
|
5
|
+
* Everything here is fire-and-forget and bounded. No method throws into the
|
|
6
|
+
* host application; delivery problems reach `onError` and nothing else.
|
|
7
|
+
* Prompts, completions and request bodies are never read or sent.
|
|
8
|
+
*/
|
|
9
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
12
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
13
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
14
|
+
}
|
|
15
|
+
Object.defineProperty(o, k2, desc);
|
|
16
|
+
}) : (function(o, m, k, k2) {
|
|
17
|
+
if (k2 === undefined) k2 = k;
|
|
18
|
+
o[k2] = m[k];
|
|
19
|
+
}));
|
|
20
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
21
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
22
|
+
};
|
|
23
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
24
|
+
exports.consent = exports.policy = exports.audit = exports.health = exports.backup = exports.deploy = exports.metrics = exports.ai = exports.shutdown = exports.flush = exports.heartbeat = exports.meter = exports.track = exports.RunClient = exports.routeKey = exports.percentile = exports.templatePath = exports.MetricsAggregator = void 0;
|
|
25
|
+
exports.init = init;
|
|
26
|
+
exports.getClient = getClient;
|
|
27
|
+
exports.flattenProps = flattenProps;
|
|
28
|
+
exports.evaluatePolicies = evaluatePolicies;
|
|
29
|
+
const node_crypto_1 = require("node:crypto");
|
|
30
|
+
const ai_js_1 = require("./ai.js");
|
|
31
|
+
const metrics_js_1 = require("./metrics.js");
|
|
32
|
+
const transport_js_1 = require("./transport.js");
|
|
33
|
+
const types_js_1 = require("./types.js");
|
|
34
|
+
__exportStar(require("./types.js"), exports);
|
|
35
|
+
var metrics_js_2 = require("./metrics.js");
|
|
36
|
+
Object.defineProperty(exports, "MetricsAggregator", { enumerable: true, get: function () { return metrics_js_2.MetricsAggregator; } });
|
|
37
|
+
Object.defineProperty(exports, "templatePath", { enumerable: true, get: function () { return metrics_js_2.templatePath; } });
|
|
38
|
+
Object.defineProperty(exports, "percentile", { enumerable: true, get: function () { return metrics_js_2.percentile; } });
|
|
39
|
+
Object.defineProperty(exports, "routeKey", { enumerable: true, get: function () { return metrics_js_2.routeKey; } });
|
|
40
|
+
const POLICY_CACHE_MS = 5 * 60 * 1000;
|
|
41
|
+
const MAX_QUEUED_EVENTS = 5000;
|
|
42
|
+
const MAX_QUEUED_AI_CALLS = 5000;
|
|
43
|
+
const MAX_QUEUED_MINUTES = 5000;
|
|
44
|
+
const MAX_CONSENT_CACHE = 2000;
|
|
45
|
+
const MAX_DECISION_COUNTERS = 1000;
|
|
46
|
+
const PROP_STRING_MAX = 1000;
|
|
47
|
+
class RunClient {
|
|
48
|
+
options;
|
|
49
|
+
version = types_js_1.SDK_VERSION;
|
|
50
|
+
transport;
|
|
51
|
+
onError;
|
|
52
|
+
events;
|
|
53
|
+
aiCalls;
|
|
54
|
+
minutes;
|
|
55
|
+
aggregator = new metrics_js_1.MetricsAggregator();
|
|
56
|
+
checks = new Map();
|
|
57
|
+
startedAt = Date.now();
|
|
58
|
+
flushTimer = null;
|
|
59
|
+
heartbeatTimer = null;
|
|
60
|
+
policyCache = null;
|
|
61
|
+
policyInflight = null;
|
|
62
|
+
consentCache = new Map();
|
|
63
|
+
/** policy.check() outcomes per policy key and UTC day, flushed with the batches. */
|
|
64
|
+
decisionCounts = new Map();
|
|
65
|
+
stopped = false;
|
|
66
|
+
constructor(options) {
|
|
67
|
+
const onError = options.onError ?? (() => undefined);
|
|
68
|
+
this.onError = (error) => {
|
|
69
|
+
try {
|
|
70
|
+
onError(error);
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
// The error hook itself failed; nothing more to do.
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
const key = (options.key ?? '').trim();
|
|
77
|
+
const disabled = options.disabled === true || key === '';
|
|
78
|
+
if (!disabled && !key.startsWith('opk_')) {
|
|
79
|
+
this.onError(new Error('Originate Run: the key does not look like an application public key (opk_...)'));
|
|
80
|
+
}
|
|
81
|
+
if (options.disabled !== true && key === '') {
|
|
82
|
+
this.onError(new Error('Originate Run: no key given; the SDK is disabled'));
|
|
83
|
+
}
|
|
84
|
+
this.options = {
|
|
85
|
+
key,
|
|
86
|
+
apiBase: (options.apiBase ?? process.env.ORIGINATE_API_BASE ?? types_js_1.DEFAULT_API_BASE).replace(/\/+$/, ''),
|
|
87
|
+
release: options.release ?? process.env.ORIGINATE_RUN_RELEASE ?? undefined,
|
|
88
|
+
service: options.service,
|
|
89
|
+
flushIntervalMs: options.flushIntervalMs ?? 5000,
|
|
90
|
+
heartbeatIntervalMs: options.heartbeatIntervalMs ?? 60000,
|
|
91
|
+
disabled,
|
|
92
|
+
requestTimeoutMs: options.requestTimeoutMs ?? 10000,
|
|
93
|
+
};
|
|
94
|
+
this.transport = new transport_js_1.Transport({
|
|
95
|
+
apiBase: this.options.apiBase,
|
|
96
|
+
key,
|
|
97
|
+
fetch: options.fetch ?? globalThis.fetch,
|
|
98
|
+
requestTimeoutMs: this.options.requestTimeoutMs,
|
|
99
|
+
onError: this.onError,
|
|
100
|
+
});
|
|
101
|
+
this.events = new transport_js_1.BatchQueue(types_js_1.EVENT_BATCH_MAX, MAX_QUEUED_EVENTS, (batch) => this.transport.post('/collect', { key, events: batch, release: this.options.release }));
|
|
102
|
+
this.aiCalls = new transport_js_1.BatchQueue(types_js_1.AI_CALL_BATCH_MAX, MAX_QUEUED_AI_CALLS, (batch) => this.transport.post('/sdk/ai-calls', { key, calls: batch }));
|
|
103
|
+
this.minutes = new transport_js_1.BatchQueue(types_js_1.METRIC_BATCH_MAX, MAX_QUEUED_MINUTES, (batch) => this.transport.post('/sdk/metrics', { key, service: this.options.service, minutes: batch }));
|
|
104
|
+
if (!disabled) {
|
|
105
|
+
if (this.options.flushIntervalMs > 0) {
|
|
106
|
+
this.flushTimer = setInterval(() => void this.flush(), this.options.flushIntervalMs);
|
|
107
|
+
(0, transport_js_1.unrefTimer)(this.flushTimer);
|
|
108
|
+
}
|
|
109
|
+
if (this.options.heartbeatIntervalMs > 0) {
|
|
110
|
+
void this.heartbeat();
|
|
111
|
+
this.heartbeatTimer = setInterval(() => void this.heartbeat(), this.options.heartbeatIntervalMs);
|
|
112
|
+
(0, transport_js_1.unrefTimer)(this.heartbeatTimer);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
get disabled() {
|
|
117
|
+
return this.options.disabled || this.stopped;
|
|
118
|
+
}
|
|
119
|
+
// ── Events ───────────────────────────────────────────────────────────
|
|
120
|
+
/** Queues a product or business event. Names are lower snake case. */
|
|
121
|
+
track(name, props = {}, options = {}) {
|
|
122
|
+
if (this.disabled)
|
|
123
|
+
return;
|
|
124
|
+
try {
|
|
125
|
+
if (!types_js_1.EVENT_NAME_PATTERN.test(name)) {
|
|
126
|
+
this.onError(new Error(`Originate Run: event name "${name}" must match ${types_js_1.EVENT_NAME_PATTERN}`));
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
const event = { name, ts: options.ts ?? new Date().toISOString(), props: flattenProps(props) };
|
|
130
|
+
if (options.accountId)
|
|
131
|
+
event.accountId = options.accountId;
|
|
132
|
+
if (options.sessionId)
|
|
133
|
+
event.sessionId = options.sessionId;
|
|
134
|
+
this.events.push(event);
|
|
135
|
+
}
|
|
136
|
+
catch (error) {
|
|
137
|
+
this.onError(error);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
/** Records a metered external call (an SMS, a minute of voice, a geocode) as an `external_call` event. */
|
|
141
|
+
meter(service, quantity, unit, options = {}) {
|
|
142
|
+
const props = { ...(options.props ?? {}), service, quantity, unit };
|
|
143
|
+
if (typeof options.costUsd === 'number')
|
|
144
|
+
props.cost_usd = options.costUsd;
|
|
145
|
+
this.track('external_call', props, { accountId: options.accountId, sessionId: options.sessionId });
|
|
146
|
+
}
|
|
147
|
+
audit = {
|
|
148
|
+
/** Records an `audit_event`: who did what to which target. Detail is dimensions only, never content. */
|
|
149
|
+
log: (action, target, detail = {}, options = {}) => {
|
|
150
|
+
this.track('audit_event', { ...detail, action, target }, options);
|
|
151
|
+
},
|
|
152
|
+
};
|
|
153
|
+
// ── AI calls ─────────────────────────────────────────────────────────
|
|
154
|
+
ai = {
|
|
155
|
+
/** Queues one run_ai_calls row. Content fields do not exist on purpose. */
|
|
156
|
+
record: (call) => {
|
|
157
|
+
if (this.disabled)
|
|
158
|
+
return;
|
|
159
|
+
try {
|
|
160
|
+
if (!call || typeof call.provider !== 'string' || typeof call.model !== 'string') {
|
|
161
|
+
this.onError(new Error('Originate Run: ai.record needs provider and model'));
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
this.aiCalls.push({
|
|
165
|
+
...call,
|
|
166
|
+
occurredAt: call.occurredAt ?? new Date().toISOString(),
|
|
167
|
+
operation: call.operation ?? 'chat',
|
|
168
|
+
source: call.source ?? 'sdk',
|
|
169
|
+
inputTokens: call.inputTokens ?? 0,
|
|
170
|
+
cachedTokens: call.cachedTokens ?? 0,
|
|
171
|
+
outputTokens: call.outputTokens ?? 0,
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
catch (error) {
|
|
175
|
+
this.onError(error);
|
|
176
|
+
}
|
|
177
|
+
},
|
|
178
|
+
/** Patches chat.completions.create, responses.create and embeddings.create on an OpenAI client. */
|
|
179
|
+
wrapOpenAI: (client, options = {}) => {
|
|
180
|
+
if (this.options.disabled)
|
|
181
|
+
return client;
|
|
182
|
+
try {
|
|
183
|
+
return (0, ai_js_1.wrapOpenAI)(client, this.ai.record, this.onError, options);
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
this.onError(error);
|
|
187
|
+
return client;
|
|
188
|
+
}
|
|
189
|
+
},
|
|
190
|
+
/** Patches messages.create on an Anthropic client. */
|
|
191
|
+
wrapAnthropic: (client, options = {}) => {
|
|
192
|
+
if (this.options.disabled)
|
|
193
|
+
return client;
|
|
194
|
+
try {
|
|
195
|
+
return (0, ai_js_1.wrapAnthropic)(client, this.ai.record, this.onError, options);
|
|
196
|
+
}
|
|
197
|
+
catch (error) {
|
|
198
|
+
this.onError(error);
|
|
199
|
+
return client;
|
|
200
|
+
}
|
|
201
|
+
},
|
|
202
|
+
};
|
|
203
|
+
// ── Request metrics ──────────────────────────────────────────────────
|
|
204
|
+
metrics = {
|
|
205
|
+
/**
|
|
206
|
+
* Records one finished response. Pass the framework's route template
|
|
207
|
+
* when it has one; a raw path is templated (ids become `:id`).
|
|
208
|
+
*/
|
|
209
|
+
record: (method, route, statusCode, durationMs, templated = false) => {
|
|
210
|
+
if (this.disabled)
|
|
211
|
+
return;
|
|
212
|
+
try {
|
|
213
|
+
this.aggregator.record(method, templated ? route : (0, metrics_js_1.templatePath)(route), statusCode, durationMs);
|
|
214
|
+
}
|
|
215
|
+
catch (error) {
|
|
216
|
+
this.onError(error);
|
|
217
|
+
}
|
|
218
|
+
},
|
|
219
|
+
};
|
|
220
|
+
// ── Backups ──────────────────────────────────────────────────────────
|
|
221
|
+
backup = {
|
|
222
|
+
/**
|
|
223
|
+
* Reports a backup or a restore test right away (not batched): Run
|
|
224
|
+
* never takes backups, it records that they happened and derives RPO
|
|
225
|
+
* and RTO from the reports. Resolves true when accepted.
|
|
226
|
+
*/
|
|
227
|
+
report: async (report) => {
|
|
228
|
+
if (this.disabled)
|
|
229
|
+
return false;
|
|
230
|
+
try {
|
|
231
|
+
const list = (Array.isArray(report) ? report : [report]).slice(0, 50).map((r) => ({
|
|
232
|
+
...r,
|
|
233
|
+
takenAt: r.takenAt instanceof Date ? r.takenAt.toISOString() : r.takenAt,
|
|
234
|
+
}));
|
|
235
|
+
if (list.some((r) => typeof r.datastore !== 'string' || !r.datastore.trim())) {
|
|
236
|
+
this.onError(new Error('Originate Run: backup.report needs a datastore name'));
|
|
237
|
+
return false;
|
|
238
|
+
}
|
|
239
|
+
return await this.transport.post('/sdk/backup', { key: this.options.key, version: types_js_1.SDK_VERSION, reports: list });
|
|
240
|
+
}
|
|
241
|
+
catch (error) {
|
|
242
|
+
this.onError(error);
|
|
243
|
+
return false;
|
|
244
|
+
}
|
|
245
|
+
},
|
|
246
|
+
};
|
|
247
|
+
// ── Deploys and heartbeats ───────────────────────────────────────────
|
|
248
|
+
deploy = {
|
|
249
|
+
/** Sends a deploy report right away (not batched). Resolves true when accepted. */
|
|
250
|
+
report: async (report) => {
|
|
251
|
+
if (this.disabled)
|
|
252
|
+
return false;
|
|
253
|
+
try {
|
|
254
|
+
return await this.transport.post('/sdk/deploy', { key: this.options.key, ...report });
|
|
255
|
+
}
|
|
256
|
+
catch (error) {
|
|
257
|
+
this.onError(error);
|
|
258
|
+
return false;
|
|
259
|
+
}
|
|
260
|
+
},
|
|
261
|
+
};
|
|
262
|
+
/** Sends a heartbeat with the SDK version, the release and the health checks. */
|
|
263
|
+
async heartbeat() {
|
|
264
|
+
if (this.disabled)
|
|
265
|
+
return false;
|
|
266
|
+
try {
|
|
267
|
+
const body = {
|
|
268
|
+
key: this.options.key,
|
|
269
|
+
version: types_js_1.SDK_VERSION,
|
|
270
|
+
release: this.options.release ?? null,
|
|
271
|
+
service: this.options.service ?? null,
|
|
272
|
+
};
|
|
273
|
+
if (this.checks.size > 0) {
|
|
274
|
+
const report = await this.health.run();
|
|
275
|
+
const checks = {};
|
|
276
|
+
for (const [name, result] of Object.entries(report.checks))
|
|
277
|
+
checks[name] = result.status;
|
|
278
|
+
body.health = { status: report.status, checks };
|
|
279
|
+
}
|
|
280
|
+
return await this.transport.post('/sdk/heartbeat', body);
|
|
281
|
+
}
|
|
282
|
+
catch (error) {
|
|
283
|
+
this.onError(error);
|
|
284
|
+
return false;
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
// ── Health ───────────────────────────────────────────────────────────
|
|
288
|
+
health = {
|
|
289
|
+
/** Registers a dependency check by name. Registering the same name again replaces it. */
|
|
290
|
+
register: (name, fn, options = {}) => {
|
|
291
|
+
this.checks.set(name, { fn, critical: options.critical ?? true, timeoutMs: options.timeoutMs ?? 3000 });
|
|
292
|
+
},
|
|
293
|
+
unregister: (name) => {
|
|
294
|
+
this.checks.delete(name);
|
|
295
|
+
},
|
|
296
|
+
/** Runs every check and returns the body of a health endpoint. */
|
|
297
|
+
run: async () => {
|
|
298
|
+
const checks = {};
|
|
299
|
+
let status = 'ok';
|
|
300
|
+
await Promise.all([...this.checks.entries()].map(async ([name, check]) => {
|
|
301
|
+
const result = await runCheck(check);
|
|
302
|
+
checks[name] = result;
|
|
303
|
+
if (result.status === 'down')
|
|
304
|
+
status = check.critical ? 'down' : worst(status, 'degraded');
|
|
305
|
+
else if (result.status === 'degraded')
|
|
306
|
+
status = worst(status, 'degraded');
|
|
307
|
+
}));
|
|
308
|
+
return {
|
|
309
|
+
status,
|
|
310
|
+
checks,
|
|
311
|
+
release: this.options.release ?? null,
|
|
312
|
+
service: this.options.service ?? null,
|
|
313
|
+
uptimeSeconds: Math.round((Date.now() - this.startedAt) / 1000),
|
|
314
|
+
};
|
|
315
|
+
},
|
|
316
|
+
/**
|
|
317
|
+
* A request handler body builder: returns the report and the HTTP status
|
|
318
|
+
* to send with it (200 for ok and degraded, 503 for down).
|
|
319
|
+
*/
|
|
320
|
+
handler: async () => {
|
|
321
|
+
const body = await this.health.run();
|
|
322
|
+
return { statusCode: body.status === 'down' ? 503 : 200, body };
|
|
323
|
+
},
|
|
324
|
+
};
|
|
325
|
+
// ── Policies and consent ─────────────────────────────────────────────
|
|
326
|
+
policy = {
|
|
327
|
+
/**
|
|
328
|
+
* Evaluates the application's enabled policies against the input. Deny
|
|
329
|
+
* wins over mask, mask over allow. With no matching policy, or before
|
|
330
|
+
* the policies endpoint exists (404), the call is allowed.
|
|
331
|
+
*/
|
|
332
|
+
check: async (input = {}) => {
|
|
333
|
+
if (this.disabled)
|
|
334
|
+
return { allowed: true, effect: null, policyKey: null, reason: 'no_policy' };
|
|
335
|
+
let response;
|
|
336
|
+
try {
|
|
337
|
+
response = await this.loadPolicies();
|
|
338
|
+
}
|
|
339
|
+
catch (error) {
|
|
340
|
+
this.onError(error);
|
|
341
|
+
return { allowed: true, effect: null, policyKey: null, reason: 'unavailable' };
|
|
342
|
+
}
|
|
343
|
+
const decision = evaluatePolicies(response?.policies ?? [], input);
|
|
344
|
+
this.countDecision(decision);
|
|
345
|
+
return decision;
|
|
346
|
+
},
|
|
347
|
+
/** The decision counts not yet sent (for tests and diagnostics). */
|
|
348
|
+
pending: () => [...this.decisionCounts.values()].map((c) => ({ ...c })),
|
|
349
|
+
/** Clears the cache so the next check refetches. */
|
|
350
|
+
refresh: () => {
|
|
351
|
+
this.policyCache = null;
|
|
352
|
+
this.consentCache.clear();
|
|
353
|
+
},
|
|
354
|
+
};
|
|
355
|
+
consent = {
|
|
356
|
+
/**
|
|
357
|
+
* Whether the subject (the application's own account id) has granted a
|
|
358
|
+
* purpose. The id is hashed before it leaves the process. Implicit
|
|
359
|
+
* consent mode allows every purpose; an unknown subject is not allowed
|
|
360
|
+
* unless the endpoint does not exist yet.
|
|
361
|
+
*/
|
|
362
|
+
allows: async (purpose, subjectId) => {
|
|
363
|
+
if (this.disabled)
|
|
364
|
+
return { allowed: true, reason: 'no_policy' };
|
|
365
|
+
try {
|
|
366
|
+
const subject = hashSubject(subjectId);
|
|
367
|
+
const response = await this.loadPolicies(subject);
|
|
368
|
+
if (response === null)
|
|
369
|
+
return { allowed: true, reason: 'no_policy' };
|
|
370
|
+
if (response.consentMode === 'implicit')
|
|
371
|
+
return { allowed: true, reason: 'implicit' };
|
|
372
|
+
if (!response.consent)
|
|
373
|
+
return { allowed: false, reason: 'unknown' };
|
|
374
|
+
if (response.consent.state === 'withdrawn')
|
|
375
|
+
return { allowed: false, reason: 'withdrawn' };
|
|
376
|
+
const granted = response.consent.purposes.includes(purpose) || response.consent.purposes.includes('all');
|
|
377
|
+
return granted ? { allowed: true, reason: 'granted' } : { allowed: false, reason: 'unknown' };
|
|
378
|
+
}
|
|
379
|
+
catch (error) {
|
|
380
|
+
this.onError(error);
|
|
381
|
+
return { allowed: false, reason: 'unavailable' };
|
|
382
|
+
}
|
|
383
|
+
},
|
|
384
|
+
};
|
|
385
|
+
/** One more allow, deny or mask for the policy that decided, today (UTC). */
|
|
386
|
+
countDecision(decision) {
|
|
387
|
+
if (!decision.policyKey || !decision.effect)
|
|
388
|
+
return;
|
|
389
|
+
const day = new Date().toISOString().slice(0, 10);
|
|
390
|
+
const key = `${decision.policyKey}|${day}`;
|
|
391
|
+
let c = this.decisionCounts.get(key);
|
|
392
|
+
if (!c) {
|
|
393
|
+
if (this.decisionCounts.size >= MAX_DECISION_COUNTERS)
|
|
394
|
+
return;
|
|
395
|
+
c = { policyKey: decision.policyKey, day, allowed: 0, denied: 0, masked: 0 };
|
|
396
|
+
this.decisionCounts.set(key, c);
|
|
397
|
+
}
|
|
398
|
+
if (decision.effect === 'deny')
|
|
399
|
+
c.denied++;
|
|
400
|
+
else if (decision.effect === 'mask')
|
|
401
|
+
c.masked++;
|
|
402
|
+
else
|
|
403
|
+
c.allowed++;
|
|
404
|
+
}
|
|
405
|
+
/** POST /sdk/policy-decisions with the counts gathered since the last flush. */
|
|
406
|
+
async flushDecisions() {
|
|
407
|
+
if (this.decisionCounts.size === 0)
|
|
408
|
+
return;
|
|
409
|
+
const decisions = [...this.decisionCounts.values()];
|
|
410
|
+
this.decisionCounts.clear();
|
|
411
|
+
const ok = await this.transport.post('/sdk/policy-decisions', { key: this.options.key, version: types_js_1.SDK_VERSION, decisions });
|
|
412
|
+
if (!ok) {
|
|
413
|
+
// Put the counts back so the next flush carries them, within the cap.
|
|
414
|
+
for (const d of decisions) {
|
|
415
|
+
const key = `${d.policyKey}|${d.day}`;
|
|
416
|
+
const c = this.decisionCounts.get(key);
|
|
417
|
+
if (c) {
|
|
418
|
+
c.allowed += d.allowed;
|
|
419
|
+
c.denied += d.denied;
|
|
420
|
+
c.masked += d.masked;
|
|
421
|
+
}
|
|
422
|
+
else if (this.decisionCounts.size < MAX_DECISION_COUNTERS)
|
|
423
|
+
this.decisionCounts.set(key, d);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
/**
|
|
428
|
+
* GET /api/v1/run/sdk/policies?key=opk_...[&subject=sha256]. A 404 (an
|
|
429
|
+
* api without Run) is treated as the application having no policies.
|
|
430
|
+
*/
|
|
431
|
+
async loadPolicies(subject) {
|
|
432
|
+
const now = Date.now();
|
|
433
|
+
if (subject) {
|
|
434
|
+
const cached = this.consentCache.get(subject);
|
|
435
|
+
if (cached && now - cached.fetchedAt < POLICY_CACHE_MS)
|
|
436
|
+
return cached.value;
|
|
437
|
+
const value = await this.transport.getJson('/sdk/policies', { key: this.options.key, subject });
|
|
438
|
+
if (this.consentCache.size >= MAX_CONSENT_CACHE) {
|
|
439
|
+
const oldest = this.consentCache.keys().next().value;
|
|
440
|
+
if (oldest !== undefined)
|
|
441
|
+
this.consentCache.delete(oldest);
|
|
442
|
+
}
|
|
443
|
+
this.consentCache.set(subject, { fetchedAt: now, value });
|
|
444
|
+
if (!this.policyCache)
|
|
445
|
+
this.policyCache = { fetchedAt: now, value };
|
|
446
|
+
return value;
|
|
447
|
+
}
|
|
448
|
+
if (this.policyCache && now - this.policyCache.fetchedAt < POLICY_CACHE_MS)
|
|
449
|
+
return this.policyCache.value;
|
|
450
|
+
if (!this.policyInflight) {
|
|
451
|
+
this.policyInflight = this.transport
|
|
452
|
+
.getJson('/sdk/policies', { key: this.options.key })
|
|
453
|
+
.then((value) => {
|
|
454
|
+
this.policyCache = { fetchedAt: Date.now(), value };
|
|
455
|
+
return value;
|
|
456
|
+
})
|
|
457
|
+
.finally(() => {
|
|
458
|
+
this.policyInflight = null;
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
return this.policyInflight;
|
|
462
|
+
}
|
|
463
|
+
// ── Lifecycle ────────────────────────────────────────────────────────
|
|
464
|
+
/** Sends everything queued. Finished metric minutes are included; the current minute only on shutdown. */
|
|
465
|
+
async flush(all = false) {
|
|
466
|
+
if (this.options.disabled)
|
|
467
|
+
return;
|
|
468
|
+
try {
|
|
469
|
+
for (const minute of this.aggregator.drain(Date.now(), all))
|
|
470
|
+
this.minutes.push(minute);
|
|
471
|
+
await Promise.all([this.events.flush(), this.aiCalls.flush(), this.minutes.flush(), this.flushDecisions()]);
|
|
472
|
+
}
|
|
473
|
+
catch (error) {
|
|
474
|
+
this.onError(error);
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
/** Stops the timers and flushes. Call it from your process shutdown hook. */
|
|
478
|
+
async shutdown() {
|
|
479
|
+
if (this.flushTimer)
|
|
480
|
+
clearInterval(this.flushTimer);
|
|
481
|
+
if (this.heartbeatTimer)
|
|
482
|
+
clearInterval(this.heartbeatTimer);
|
|
483
|
+
this.flushTimer = null;
|
|
484
|
+
this.heartbeatTimer = null;
|
|
485
|
+
await this.flush(true);
|
|
486
|
+
this.stopped = true;
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
exports.RunClient = RunClient;
|
|
490
|
+
// ── Module-level singleton ───────────────────────────────────────────────
|
|
491
|
+
let current = null;
|
|
492
|
+
let fallback = null;
|
|
493
|
+
/** Creates the client and makes it the module-level singleton. */
|
|
494
|
+
function init(options) {
|
|
495
|
+
current = new RunClient(options);
|
|
496
|
+
return current;
|
|
497
|
+
}
|
|
498
|
+
/** The singleton, or a disabled no-op client before init() ran. */
|
|
499
|
+
function getClient() {
|
|
500
|
+
if (current)
|
|
501
|
+
return current;
|
|
502
|
+
if (!fallback)
|
|
503
|
+
fallback = new RunClient({ key: '', disabled: true });
|
|
504
|
+
return fallback;
|
|
505
|
+
}
|
|
506
|
+
const track = (name, props, options) => getClient().track(name, props, options);
|
|
507
|
+
exports.track = track;
|
|
508
|
+
const meter = (service, quantity, unit, options) => getClient().meter(service, quantity, unit, options);
|
|
509
|
+
exports.meter = meter;
|
|
510
|
+
const heartbeat = () => getClient().heartbeat();
|
|
511
|
+
exports.heartbeat = heartbeat;
|
|
512
|
+
const flush = (all) => getClient().flush(all);
|
|
513
|
+
exports.flush = flush;
|
|
514
|
+
const shutdown = () => getClient().shutdown();
|
|
515
|
+
exports.shutdown = shutdown;
|
|
516
|
+
exports.ai = {
|
|
517
|
+
record: (call) => getClient().ai.record(call),
|
|
518
|
+
wrapOpenAI: (client, options) => getClient().ai.wrapOpenAI(client, options),
|
|
519
|
+
wrapAnthropic: (client, options) => getClient().ai.wrapAnthropic(client, options),
|
|
520
|
+
};
|
|
521
|
+
exports.metrics = {
|
|
522
|
+
record: (method, route, statusCode, durationMs, templated) => getClient().metrics.record(method, route, statusCode, durationMs, templated),
|
|
523
|
+
};
|
|
524
|
+
exports.deploy = {
|
|
525
|
+
report: (report) => getClient().deploy.report(report),
|
|
526
|
+
};
|
|
527
|
+
exports.backup = {
|
|
528
|
+
report: (report) => getClient().backup.report(report),
|
|
529
|
+
};
|
|
530
|
+
exports.health = {
|
|
531
|
+
register: (name, fn, options) => getClient().health.register(name, fn, options),
|
|
532
|
+
unregister: (name) => getClient().health.unregister(name),
|
|
533
|
+
run: () => getClient().health.run(),
|
|
534
|
+
handler: () => getClient().health.handler(),
|
|
535
|
+
};
|
|
536
|
+
exports.audit = {
|
|
537
|
+
log: (action, target, detail, options) => getClient().audit.log(action, target, detail, options),
|
|
538
|
+
};
|
|
539
|
+
exports.policy = {
|
|
540
|
+
check: (input) => getClient().policy.check(input),
|
|
541
|
+
refresh: () => getClient().policy.refresh(),
|
|
542
|
+
pending: () => getClient().policy.pending(),
|
|
543
|
+
};
|
|
544
|
+
exports.consent = {
|
|
545
|
+
allows: (purpose, subjectId) => getClient().consent.allows(purpose, subjectId),
|
|
546
|
+
};
|
|
547
|
+
// ── Helpers ──────────────────────────────────────────────────────────────
|
|
548
|
+
/** Keeps primitive props; serializes anything else to a bounded string. */
|
|
549
|
+
function flattenProps(props) {
|
|
550
|
+
const out = {};
|
|
551
|
+
for (const [key, value] of Object.entries(props)) {
|
|
552
|
+
if (value === undefined)
|
|
553
|
+
continue;
|
|
554
|
+
if (value === null || typeof value === 'boolean') {
|
|
555
|
+
out[key] = value;
|
|
556
|
+
}
|
|
557
|
+
else if (typeof value === 'number') {
|
|
558
|
+
out[key] = Number.isFinite(value) ? value : null;
|
|
559
|
+
}
|
|
560
|
+
else if (typeof value === 'string') {
|
|
561
|
+
out[key] = value.length > PROP_STRING_MAX ? value.slice(0, PROP_STRING_MAX) : value;
|
|
562
|
+
}
|
|
563
|
+
else if (value instanceof Date) {
|
|
564
|
+
out[key] = value.toISOString();
|
|
565
|
+
}
|
|
566
|
+
else {
|
|
567
|
+
try {
|
|
568
|
+
const text = JSON.stringify(value);
|
|
569
|
+
out[key] = text.length > PROP_STRING_MAX ? text.slice(0, PROP_STRING_MAX) : text;
|
|
570
|
+
}
|
|
571
|
+
catch {
|
|
572
|
+
out[key] = String(value);
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
return out;
|
|
577
|
+
}
|
|
578
|
+
/** Deny wins over mask, mask over allow; the first matching policy of the winning effect names the decision. */
|
|
579
|
+
function evaluatePolicies(policies, input) {
|
|
580
|
+
let decision = { allowed: true, effect: null, policyKey: null, reason: 'no_policy' };
|
|
581
|
+
const rank = { allow: 1, mask: 2, deny: 3 };
|
|
582
|
+
for (const policy of policies) {
|
|
583
|
+
if (policy.enabled === false)
|
|
584
|
+
continue;
|
|
585
|
+
if (!policyMatches(policy, input))
|
|
586
|
+
continue;
|
|
587
|
+
const effect = policy.effect;
|
|
588
|
+
if ((rank[effect] ?? 0) > (decision.effect ? rank[decision.effect] ?? 0 : 0)) {
|
|
589
|
+
decision = { allowed: effect !== 'deny', effect, policyKey: policy.key, reason: effect };
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
return decision;
|
|
593
|
+
}
|
|
594
|
+
function policyMatches(policy, input) {
|
|
595
|
+
const rule = policy.rule ?? {};
|
|
596
|
+
const dimensions = [
|
|
597
|
+
[rule.dataClasses, input.dataClasses ?? []],
|
|
598
|
+
[rule.regions, input.region ? [input.region] : []],
|
|
599
|
+
[rule.purposes, input.purpose ? [input.purpose] : []],
|
|
600
|
+
[rule.features, input.feature ? [input.feature] : []],
|
|
601
|
+
[rule.providers, input.provider ? [input.provider] : []],
|
|
602
|
+
[rule.models, input.model ? [input.model] : []],
|
|
603
|
+
[rule.actions, input.action ? [input.action] : []],
|
|
604
|
+
];
|
|
605
|
+
for (const [wanted, given] of dimensions) {
|
|
606
|
+
if (!Array.isArray(wanted) || wanted.length === 0)
|
|
607
|
+
continue;
|
|
608
|
+
if (wanted.includes('*'))
|
|
609
|
+
continue;
|
|
610
|
+
if (!given.some((value) => wanted.includes(value)))
|
|
611
|
+
return false;
|
|
612
|
+
}
|
|
613
|
+
return true;
|
|
614
|
+
}
|
|
615
|
+
function hashSubject(subjectId) {
|
|
616
|
+
return (0, node_crypto_1.createHash)('sha256').update(subjectId).digest('hex');
|
|
617
|
+
}
|
|
618
|
+
async function runCheck(check) {
|
|
619
|
+
let timer = null;
|
|
620
|
+
const timeout = new Promise((resolve) => {
|
|
621
|
+
timer = setTimeout(() => resolve({ status: 'down', detail: 'timed out' }), check.timeoutMs);
|
|
622
|
+
(0, transport_js_1.unrefTimer)(timer);
|
|
623
|
+
});
|
|
624
|
+
try {
|
|
625
|
+
const result = await Promise.race([Promise.resolve().then(() => check.fn()), timeout]);
|
|
626
|
+
return normalizeCheck(result);
|
|
627
|
+
}
|
|
628
|
+
catch (error) {
|
|
629
|
+
return { status: 'down', detail: error instanceof Error ? error.message : String(error) };
|
|
630
|
+
}
|
|
631
|
+
finally {
|
|
632
|
+
if (timer)
|
|
633
|
+
clearTimeout(timer);
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
function normalizeCheck(result) {
|
|
637
|
+
if (result === undefined || result === true)
|
|
638
|
+
return { status: 'ok' };
|
|
639
|
+
if (result === false)
|
|
640
|
+
return { status: 'down' };
|
|
641
|
+
if (result === 'ok' || result === 'degraded' || result === 'down')
|
|
642
|
+
return { status: result };
|
|
643
|
+
if (typeof result === 'object' && result !== null && 'status' in result) {
|
|
644
|
+
const r = result;
|
|
645
|
+
return { status: r.status === 'ok' || r.status === 'degraded' ? r.status : 'down', detail: r.detail };
|
|
646
|
+
}
|
|
647
|
+
return { status: 'ok' };
|
|
648
|
+
}
|
|
649
|
+
function worst(a, b) {
|
|
650
|
+
const order = { ok: 0, degraded: 1, down: 2 };
|
|
651
|
+
return order[b] > order[a] ? b : a;
|
|
652
|
+
}
|
|
653
|
+
//# sourceMappingURL=index.js.map
|