@openlegion/platform 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/README.md +1189 -2
- package/dist/body.d.ts +9 -0
- package/dist/body.js +28 -0
- package/dist/chat-history.d.ts +53 -0
- package/dist/chat-history.js +11 -0
- package/dist/client.d.ts +217 -0
- package/dist/client.js +367 -0
- package/dist/core.d.ts +47 -0
- package/dist/core.js +1 -0
- package/dist/crypto.d.ts +25 -0
- package/dist/crypto.js +81 -0
- package/dist/errors.d.ts +111 -0
- package/dist/errors.js +134 -0
- package/dist/events.d.ts +131 -0
- package/dist/events.js +5 -0
- package/dist/generated/api.d.ts +5505 -0
- package/dist/generated/api.js +446 -0
- package/dist/handler.d.ts +201 -0
- package/dist/handler.js +682 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.js +12 -0
- package/dist/kit-agents.d.ts +95 -0
- package/dist/kit-agents.js +280 -0
- package/dist/kit-codes.d.ts +279 -0
- package/dist/kit-codes.js +44 -0
- package/dist/kit-connections.d.ts +21 -0
- package/dist/kit-connections.js +189 -0
- package/dist/kit-files.d.ts +8 -0
- package/dist/kit-files.js +117 -0
- package/dist/kit-model-keys.d.ts +8 -0
- package/dist/kit-model-keys.js +86 -0
- package/dist/kit-threads.d.ts +3 -0
- package/dist/kit-threads.js +92 -0
- package/dist/kit-tools.d.ts +21 -0
- package/dist/kit-tools.js +47 -0
- package/dist/kit.d.ts +130 -0
- package/dist/kit.js +155 -0
- package/dist/mcp-server.d.ts +27 -0
- package/dist/mcp-server.js +166 -0
- package/dist/next.d.ts +24 -0
- package/dist/next.js +6 -0
- package/dist/ol-signed.d.ts +82 -0
- package/dist/ol-signed.js +115 -0
- package/dist/react/add-server.d.ts +90 -0
- package/dist/react/add-server.js +183 -0
- package/dist/react/agent-chat.d.ts +925 -0
- package/dist/react/agent-chat.js +1917 -0
- package/dist/react/agent-editor.d.ts +133 -0
- package/dist/react/agent-editor.js +222 -0
- package/dist/react/agent-kit.d.ts +160 -0
- package/dist/react/agent-kit.js +279 -0
- package/dist/react/agent-list.d.ts +247 -0
- package/dist/react/agent-list.js +248 -0
- package/dist/react/approval-card.d.ts +272 -0
- package/dist/react/approval-card.js +372 -0
- package/dist/react/artifact-card.d.ts +38 -0
- package/dist/react/artifact-card.js +39 -0
- package/dist/react/avatar.d.ts +21 -0
- package/dist/react/avatar.js +33 -0
- package/dist/react/card-ledger.d.ts +30 -0
- package/dist/react/card-ledger.js +49 -0
- package/dist/react/chat-timing.d.ts +121 -0
- package/dist/react/chat-timing.js +229 -0
- package/dist/react/computer-view.d.ts +309 -0
- package/dist/react/computer-view.js +543 -0
- package/dist/react/computer-viewer.d.ts +175 -0
- package/dist/react/computer-viewer.js +555 -0
- package/dist/react/computer-wire.d.ts +178 -0
- package/dist/react/computer-wire.js +244 -0
- package/dist/react/connect-button.d.ts +145 -0
- package/dist/react/connect-button.js +212 -0
- package/dist/react/connection-request.d.ts +16 -0
- package/dist/react/connection-request.js +18 -0
- package/dist/react/connections-list.d.ts +90 -0
- package/dist/react/connections-list.js +76 -0
- package/dist/react/errors.d.ts +250 -0
- package/dist/react/errors.js +146 -0
- package/dist/react/files.d.ts +41 -0
- package/dist/react/files.js +78 -0
- package/dist/react/index.d.ts +35 -0
- package/dist/react/index.js +26 -0
- package/dist/react/limit-words.d.ts +80 -0
- package/dist/react/limit-words.js +53 -0
- package/dist/react/markdown.d.ts +42 -0
- package/dist/react/markdown.js +56 -0
- package/dist/react/md-parse.d.ts +106 -0
- package/dist/react/md-parse.js +638 -0
- package/dist/react/model-keys-card.d.ts +94 -0
- package/dist/react/model-keys-card.js +123 -0
- package/dist/react/reload.d.ts +211 -0
- package/dist/react/reload.js +339 -0
- package/dist/react/reveal.d.ts +17 -0
- package/dist/react/reveal.js +22 -0
- package/dist/react/schedule-editor.d.ts +107 -0
- package/dist/react/schedule-editor.js +172 -0
- package/dist/react/schedule-time.d.ts +66 -0
- package/dist/react/schedule-time.js +90 -0
- package/dist/react/styles.css +1274 -0
- package/dist/react/transport.d.ts +49 -0
- package/dist/react/transport.js +380 -0
- package/dist/react/use-connections.d.ts +155 -0
- package/dist/react/use-connections.js +231 -0
- package/dist/react/use-model-keys.d.ts +47 -0
- package/dist/react/use-model-keys.js +57 -0
- package/dist/react/use-threads.d.ts +63 -0
- package/dist/react/use-threads.js +73 -0
- package/dist/react/vault-form.d.ts +92 -0
- package/dist/react/vault-form.js +151 -0
- package/dist/schema.d.ts +47 -0
- package/dist/schema.js +16 -0
- package/dist/secrets.d.ts +15 -0
- package/dist/secrets.js +18 -0
- package/dist/stream.d.ts +129 -0
- package/dist/stream.js +192 -0
- package/dist/testing.d.ts +33 -0
- package/dist/testing.js +40 -0
- package/dist/webhooks.d.ts +31 -0
- package/dist/webhooks.js +72 -0
- package/package.json +85 -3
package/dist/client.js
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
1
|
+
import { APIConnectionError, errorFromResponse, OpenLegionError, retryAfterMs } from "./errors.js";
|
|
2
|
+
import { API_VERSION, DEFAULT_BASE_URL, GeneratedResources, OPERATIONS, } from "./generated/api.js";
|
|
3
|
+
import { RunStream } from "./stream.js";
|
|
4
|
+
export const SDK_VERSION = "0.1.0";
|
|
5
|
+
const PRINTABLE = /^[\x21-\x7e]+$/;
|
|
6
|
+
const BACKOFF_BASE_MS = 500;
|
|
7
|
+
const BACKOFF_CAP_MS = 8_000;
|
|
8
|
+
const RETRY_AFTER_CAP_MS = 60_000;
|
|
9
|
+
export function envVar(name) {
|
|
10
|
+
const env = globalThis.process?.env;
|
|
11
|
+
const v = env?.[name];
|
|
12
|
+
return v === undefined || v === "" ? undefined : v;
|
|
13
|
+
}
|
|
14
|
+
export function inBrowser() {
|
|
15
|
+
return typeof globalThis.window !== "undefined" && typeof globalThis.document !== "undefined";
|
|
16
|
+
}
|
|
17
|
+
function sameOriginAsPage(baseUrl) {
|
|
18
|
+
const here = globalThis.location;
|
|
19
|
+
if (typeof here?.href !== "string" || typeof here.origin !== "string")
|
|
20
|
+
return false;
|
|
21
|
+
try {
|
|
22
|
+
return new URL(baseUrl, here.href).origin === here.origin;
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
return false;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
export function shouldRetry(method, idempotencyKey, failure) {
|
|
29
|
+
const replaySafe = method === "GET" || method === "DELETE" || (method === "POST" && idempotencyKey);
|
|
30
|
+
if (failure === "network")
|
|
31
|
+
return replaySafe;
|
|
32
|
+
if (failure.status === 429)
|
|
33
|
+
return true;
|
|
34
|
+
if (failure.status === 409)
|
|
35
|
+
return failure.code === "idempotency_in_flight";
|
|
36
|
+
if (failure.status >= 500)
|
|
37
|
+
return replaySafe;
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
function backoffMs(attempt) {
|
|
41
|
+
const base = Math.min(BACKOFF_CAP_MS, BACKOFF_BASE_MS * 2 ** attempt);
|
|
42
|
+
return base * (0.75 + Math.random() * 0.25);
|
|
43
|
+
}
|
|
44
|
+
function sleep(ms, signal) {
|
|
45
|
+
return new Promise((resolve, reject) => {
|
|
46
|
+
if (signal?.aborted)
|
|
47
|
+
return reject(signal.reason);
|
|
48
|
+
const t = setTimeout(() => {
|
|
49
|
+
signal?.removeEventListener("abort", onAbort);
|
|
50
|
+
resolve();
|
|
51
|
+
}, ms);
|
|
52
|
+
const onAbort = () => {
|
|
53
|
+
clearTimeout(t);
|
|
54
|
+
reject(signal.reason);
|
|
55
|
+
};
|
|
56
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
function attemptSignal(outer, ms) {
|
|
60
|
+
const c = new AbortController();
|
|
61
|
+
let timedOut = false;
|
|
62
|
+
const t = setTimeout(() => {
|
|
63
|
+
timedOut = true;
|
|
64
|
+
c.abort(new Error(`OpenLegion: no response within ${ms} ms`));
|
|
65
|
+
}, ms);
|
|
66
|
+
const onAbort = () => c.abort(outer.reason);
|
|
67
|
+
if (outer?.aborted)
|
|
68
|
+
c.abort(outer.reason);
|
|
69
|
+
else
|
|
70
|
+
outer?.addEventListener("abort", onAbort, { once: true });
|
|
71
|
+
return {
|
|
72
|
+
signal: c.signal,
|
|
73
|
+
timedOut: () => timedOut,
|
|
74
|
+
done: () => {
|
|
75
|
+
clearTimeout(t);
|
|
76
|
+
outer?.removeEventListener("abort", onAbort);
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
export function withResponse(value, meta) {
|
|
81
|
+
const target = (typeof value === "object" && value !== null ? value : {});
|
|
82
|
+
Object.defineProperty(target, "lastResponse", { value: meta, enumerable: false, configurable: true });
|
|
83
|
+
return target;
|
|
84
|
+
}
|
|
85
|
+
export function responseMeta(res) {
|
|
86
|
+
return { status: res.status, requestId: res.headers.get("request-id"), idempotentReplayed: res.headers.get("idempotent-replayed") === "true", headers: res.headers };
|
|
87
|
+
}
|
|
88
|
+
export class Transport {
|
|
89
|
+
config;
|
|
90
|
+
constructor(config) {
|
|
91
|
+
this.config = config;
|
|
92
|
+
}
|
|
93
|
+
url(op, pathParams, query) {
|
|
94
|
+
const spec = OPERATIONS[op];
|
|
95
|
+
if (pathParams.length !== spec.pathParams.length)
|
|
96
|
+
throw new TypeError(`OpenLegion: ${op} takes ${spec.pathParams.length} path parameter(s)`);
|
|
97
|
+
let i = 0;
|
|
98
|
+
const path = spec.path.replace(/\{[A-Za-z_]+\}/g, () => {
|
|
99
|
+
const v = pathParams[i++];
|
|
100
|
+
if (typeof v !== "string" || v.length === 0)
|
|
101
|
+
throw new TypeError(`OpenLegion: ${op} needs ${spec.pathParams[i - 1]}`);
|
|
102
|
+
return encodeURIComponent(v);
|
|
103
|
+
});
|
|
104
|
+
const qs = new URLSearchParams();
|
|
105
|
+
for (const [k, v] of Object.entries(query ?? {}))
|
|
106
|
+
if (v !== undefined && v !== null)
|
|
107
|
+
qs.append(k, String(v));
|
|
108
|
+
const s = qs.toString();
|
|
109
|
+
return `${this.config.baseUrl}${path}${s ? `?${s}` : ""}`;
|
|
110
|
+
}
|
|
111
|
+
async send(op, pathParams, payload, options, extra) {
|
|
112
|
+
const spec = OPERATIONS[op];
|
|
113
|
+
const o = options ?? {};
|
|
114
|
+
const raw = extra?.rawBody;
|
|
115
|
+
const hasBody = raw === undefined && (spec.method === "POST" ? spec.body : false);
|
|
116
|
+
const query = hasBody || raw !== undefined ? extra?.query : { ...payload, ...extra?.query };
|
|
117
|
+
const url = this.url(op, pathParams, query);
|
|
118
|
+
const headers = {
|
|
119
|
+
authorization: `Bearer ${this.config.apiKey}`,
|
|
120
|
+
"openlegion-version": o.apiVersion ?? this.config.apiVersion,
|
|
121
|
+
accept: extra?.accept ?? "application/json",
|
|
122
|
+
...extra?.headers,
|
|
123
|
+
};
|
|
124
|
+
if (!inBrowser())
|
|
125
|
+
headers["user-agent"] = `openlegion-platform-js/${SDK_VERSION}`;
|
|
126
|
+
if (hasBody)
|
|
127
|
+
headers["content-type"] = "application/json";
|
|
128
|
+
if (spec.idempotencyKey) {
|
|
129
|
+
const key = o.idempotencyKey ?? crypto.randomUUID();
|
|
130
|
+
if (key.length > 255 || !PRINTABLE.test(key))
|
|
131
|
+
throw new TypeError("OpenLegion: an Idempotency-Key is 1-255 printable ASCII characters");
|
|
132
|
+
headers["idempotency-key"] = key;
|
|
133
|
+
}
|
|
134
|
+
if (spec.workspace) {
|
|
135
|
+
const ws = o.workspace ?? this.config.workspace;
|
|
136
|
+
const subject = o.subject ?? this.config.subject;
|
|
137
|
+
if (ws)
|
|
138
|
+
headers["openlegion-workspace"] = ws;
|
|
139
|
+
if (subject)
|
|
140
|
+
headers["openlegion-subject"] = subject;
|
|
141
|
+
const given = o.subject !== undefined || o.subjectName !== undefined ? o.subjectName : this.config.subjectName;
|
|
142
|
+
if (subject && given === null)
|
|
143
|
+
headers["openlegion-subject-name-clear"] = "true";
|
|
144
|
+
const name = given === null ? null : subjectNameOf(given);
|
|
145
|
+
if (subject && name)
|
|
146
|
+
headers["openlegion-subject-name"] = name;
|
|
147
|
+
}
|
|
148
|
+
const body = raw !== undefined ? raw : hasBody ? JSON.stringify(payload ?? {}) : undefined;
|
|
149
|
+
const maxRetries = o.maxRetries ?? this.config.maxRetries;
|
|
150
|
+
const timeoutMs = o.timeoutMs ?? this.config.timeoutMs;
|
|
151
|
+
for (let attempt = 0;; attempt++) {
|
|
152
|
+
const a = attemptSignal(o.signal, timeoutMs);
|
|
153
|
+
let res;
|
|
154
|
+
try {
|
|
155
|
+
res = await this.config.fetch(url, { method: spec.method, headers, body, signal: a.signal });
|
|
156
|
+
}
|
|
157
|
+
catch (err) {
|
|
158
|
+
a.done();
|
|
159
|
+
if (o.signal?.aborted)
|
|
160
|
+
throw err;
|
|
161
|
+
const failure = new APIConnectionError({
|
|
162
|
+
type: "connection_error",
|
|
163
|
+
code: a.timedOut() ? "timeout" : "connection_failed",
|
|
164
|
+
message: `${a.timedOut() ? `OpenLegion: no response from ${this.config.baseUrl} within ${timeoutMs} ms` : `OpenLegion: could not reach ${this.config.baseUrl}`} (${spec.method} ${spec.path}). Set baseUrl, or OPENLEGION_BASE_URL, if your API is elsewhere.`,
|
|
165
|
+
cause: err,
|
|
166
|
+
});
|
|
167
|
+
if (attempt < maxRetries && shouldRetry(spec.method, spec.idempotencyKey, "network")) {
|
|
168
|
+
await sleep(backoffMs(attempt), o.signal);
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
throw failure;
|
|
172
|
+
}
|
|
173
|
+
if (res.ok) {
|
|
174
|
+
if (extra?.untilRead) {
|
|
175
|
+
extra.untilRead(a);
|
|
176
|
+
return res;
|
|
177
|
+
}
|
|
178
|
+
a.done();
|
|
179
|
+
return res;
|
|
180
|
+
}
|
|
181
|
+
const text = await res.text().catch(() => "");
|
|
182
|
+
a.done();
|
|
183
|
+
const error = errorFromResponse(res.status, res.headers, text);
|
|
184
|
+
if (attempt < maxRetries && shouldRetry(spec.method, spec.idempotencyKey, { status: res.status, code: error.code })) {
|
|
185
|
+
const after = retryAfterMs(res.headers);
|
|
186
|
+
await sleep(after === null ? backoffMs(attempt) : Math.min(after, RETRY_AFTER_CAP_MS), o.signal);
|
|
187
|
+
continue;
|
|
188
|
+
}
|
|
189
|
+
throw error;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
async request(op, pathParams, payload, options) {
|
|
193
|
+
const held = [];
|
|
194
|
+
const res = await this.send(op, pathParams, payload, options, { untilRead: (a) => held.push(a) });
|
|
195
|
+
const timer = held[0];
|
|
196
|
+
try {
|
|
197
|
+
return withResponse(await readJson(res), responseMeta(res));
|
|
198
|
+
}
|
|
199
|
+
catch (err) {
|
|
200
|
+
if (!timer?.timedOut())
|
|
201
|
+
throw err;
|
|
202
|
+
const timeoutMs = options?.timeoutMs ?? this.config.timeoutMs;
|
|
203
|
+
throw new APIConnectionError({ type: "connection_error", code: "timeout", message: `OpenLegion: the answer from ${this.config.baseUrl} did not finish within ${timeoutMs} ms (${op}).`, cause: err });
|
|
204
|
+
}
|
|
205
|
+
finally {
|
|
206
|
+
timer?.done();
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
list(op, pathParams, query, options) {
|
|
210
|
+
const first = this.request(op, pathParams, query, options);
|
|
211
|
+
const q = { ...query };
|
|
212
|
+
const backward = typeof q["ending_before"] === "string";
|
|
213
|
+
const next = (cursor) => {
|
|
214
|
+
const { starting_after: _a, ending_before: _b, ...rest } = q;
|
|
215
|
+
return this.request(op, pathParams, { ...rest, [backward ? "ending_before" : "starting_after"]: cursor }, options);
|
|
216
|
+
};
|
|
217
|
+
async function* iterate() {
|
|
218
|
+
let page = await first;
|
|
219
|
+
for (;;) {
|
|
220
|
+
yield* backward ? [...page.data].reverse() : page.data;
|
|
221
|
+
if (!page.has_more || page.data.length === 0)
|
|
222
|
+
return;
|
|
223
|
+
const edge = (backward ? page.data[0] : page.data[page.data.length - 1]);
|
|
224
|
+
const cursor = edge?.object === "billing_preview_line" ? edge.workspace : edge?.id;
|
|
225
|
+
if (typeof cursor !== "string")
|
|
226
|
+
return;
|
|
227
|
+
page = await next(cursor);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
return Object.assign(first, { [Symbol.asyncIterator]: iterate });
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
async function readJson(res) {
|
|
234
|
+
const text = await res.text();
|
|
235
|
+
if (text === "")
|
|
236
|
+
return {};
|
|
237
|
+
try {
|
|
238
|
+
return JSON.parse(text);
|
|
239
|
+
}
|
|
240
|
+
catch (err) {
|
|
241
|
+
throw new OpenLegionError({
|
|
242
|
+
type: "api_error",
|
|
243
|
+
code: "unexpected_response",
|
|
244
|
+
message: `OpenLegion answered HTTP ${res.status} with a body that is not JSON.`,
|
|
245
|
+
request_id: res.headers.get("request-id"),
|
|
246
|
+
status: res.status,
|
|
247
|
+
headers: res.headers,
|
|
248
|
+
cause: err,
|
|
249
|
+
});
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
const SUBJECT_NAME_MAX = 120;
|
|
253
|
+
export function subjectNameProblem(name) {
|
|
254
|
+
if (typeof name !== "string")
|
|
255
|
+
return { why: `it is not a string (${name === null ? "null" : typeof name})`, fix: "string" };
|
|
256
|
+
const trimmed = name.trim();
|
|
257
|
+
if (trimmed.length > SUBJECT_NAME_MAX)
|
|
258
|
+
return { why: `it is ${trimmed.length} characters once trimmed, and OpenLegion keeps at most ${SUBJECT_NAME_MAX}`, fix: "shorter" };
|
|
259
|
+
if (/\p{Cc}/u.test(trimmed))
|
|
260
|
+
return { why: "it holds a control character, which OpenLegion refuses", fix: "remove" };
|
|
261
|
+
try {
|
|
262
|
+
encodeURIComponent(trimmed);
|
|
263
|
+
}
|
|
264
|
+
catch {
|
|
265
|
+
return { why: "it is not valid text (it holds a lone surrogate)", fix: "remove" };
|
|
266
|
+
}
|
|
267
|
+
return null;
|
|
268
|
+
}
|
|
269
|
+
const DIRECT_FIX = { string: "Send a string", shorter: "Send a shorter name", remove: "Remove it" };
|
|
270
|
+
function subjectNameOf(name) {
|
|
271
|
+
if (name === undefined)
|
|
272
|
+
return null;
|
|
273
|
+
const problem = subjectNameProblem(name);
|
|
274
|
+
if (problem !== null)
|
|
275
|
+
throw new TypeError(`OpenLegion: subjectName can't be sent: ${problem.why}. ${DIRECT_FIX[problem.fix]}, or leave subjectName out.`);
|
|
276
|
+
const trimmed = name.trim();
|
|
277
|
+
return trimmed === "" ? null : encodeURIComponent(trimmed);
|
|
278
|
+
}
|
|
279
|
+
function resolve(opts) {
|
|
280
|
+
const apiKey = opts.apiKey ?? envVar("OPENLEGION_API_KEY");
|
|
281
|
+
if (!apiKey)
|
|
282
|
+
throw new TypeError("OpenLegion: no API key. Pass { apiKey } or set OPENLEGION_API_KEY.");
|
|
283
|
+
if (inBrowser() && apiKey.startsWith("olp_")) {
|
|
284
|
+
throw new TypeError("OpenLegion: an org key (olp_…) must never reach a browser. Call OpenLegion from your server; the kit's createHandler({ resolve }) is the browser's door.");
|
|
285
|
+
}
|
|
286
|
+
const baseUrl = (opts.baseUrl ?? envVar("OPENLEGION_BASE_URL") ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
287
|
+
if (inBrowser() && !sameOriginAsPage(baseUrl)) {
|
|
288
|
+
throw new TypeError("OpenLegion: the API sends no CORS headers, so a browser page can't call it directly. Call it from your server, or from a route on this origin that forwards to it (the kit's createHandler({ resolve }) is one).");
|
|
289
|
+
}
|
|
290
|
+
if (typeof (opts.fetch ?? globalThis.fetch) !== "function")
|
|
291
|
+
throw new TypeError("OpenLegion: no fetch available; pass { fetch }.");
|
|
292
|
+
return {
|
|
293
|
+
apiKey,
|
|
294
|
+
baseUrl,
|
|
295
|
+
apiVersion: opts.apiVersion ?? API_VERSION,
|
|
296
|
+
workspace: opts.workspace,
|
|
297
|
+
subject: opts.subject,
|
|
298
|
+
subjectName: opts.subjectName === null ? null : subjectNameOf(opts.subjectName) === null ? undefined : opts.subjectName,
|
|
299
|
+
maxRetries: opts.maxRetries ?? 2,
|
|
300
|
+
timeoutMs: opts.timeoutMs ?? 60_000,
|
|
301
|
+
fetch: opts.fetch ?? ((input, init) => globalThis.fetch(input, init)),
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
function isAnswerHeader(name) {
|
|
305
|
+
const n = name.toLowerCase();
|
|
306
|
+
return n === "content-type" || n.startsWith("mcp-");
|
|
307
|
+
}
|
|
308
|
+
export class OpenLegion extends GeneratedResources {
|
|
309
|
+
files;
|
|
310
|
+
transport;
|
|
311
|
+
#options;
|
|
312
|
+
constructor(options = {}) {
|
|
313
|
+
const transport = new Transport(resolve(options));
|
|
314
|
+
super(transport);
|
|
315
|
+
this.transport = transport;
|
|
316
|
+
this.#options = options;
|
|
317
|
+
const runsStream = async (runId, opts = {}) => {
|
|
318
|
+
const { after = -1, reattach, ...req } = opts;
|
|
319
|
+
const headers = after >= 0 ? { "last-event-id": String(after) } : {};
|
|
320
|
+
const first = await transport.send("runs.stream", [runId], undefined, req, { accept: "text/event-stream", headers });
|
|
321
|
+
return new RunStream({ transport, run: runId, first, after, options: req, reattach });
|
|
322
|
+
};
|
|
323
|
+
Object.assign(this.runs, { stream: runsStream });
|
|
324
|
+
Object.assign(this.messages, {
|
|
325
|
+
stream: (async (threadId, body, opts = {}) => {
|
|
326
|
+
const { reattach, ...req } = opts;
|
|
327
|
+
const res = await transport.send("messages.create", [threadId], body, req, { query: { stream: "true" }, accept: "text/event-stream" });
|
|
328
|
+
const run = res.headers.get("openlegion-run");
|
|
329
|
+
if ((res.headers.get("content-type") ?? "").includes("text/event-stream") && run)
|
|
330
|
+
return new RunStream({ transport, run, first: res, options: req, reattach });
|
|
331
|
+
const replay = (await res.json());
|
|
332
|
+
await res.body?.cancel().catch(() => undefined);
|
|
333
|
+
return new RunStream({ transport, run: replay.run.id, first: null, after: -1, options: req, reattach });
|
|
334
|
+
}),
|
|
335
|
+
});
|
|
336
|
+
Object.assign(this.devSessions.requests, {
|
|
337
|
+
respond: (async (sessionId, requestId, answer, opts) => {
|
|
338
|
+
if (!Number.isInteger(answer.status) || answer.status < 200 || answer.status > 599)
|
|
339
|
+
throw new TypeError("OpenLegion: an answer's status is an HTTP status from 200 to 599");
|
|
340
|
+
const headers = { "openlegion-dev-status": String(answer.status) };
|
|
341
|
+
for (const [name, value] of Object.entries(answer.headers ?? {}))
|
|
342
|
+
if (isAnswerHeader(name))
|
|
343
|
+
headers[name.toLowerCase()] = value;
|
|
344
|
+
const rawBody = typeof answer.body === "string" ? new TextEncoder().encode(answer.body) : answer.body;
|
|
345
|
+
const res = await transport.send("dev_sessions.requests.respond", [sessionId, requestId], undefined, opts, { headers, rawBody });
|
|
346
|
+
return withResponse(await readJson(res), responseMeta(res));
|
|
347
|
+
}),
|
|
348
|
+
});
|
|
349
|
+
this.files = {
|
|
350
|
+
create: async (input, opts) => {
|
|
351
|
+
const rawBody = typeof input.body === "string" ? new TextEncoder().encode(input.body) : input.body;
|
|
352
|
+
const res = await transport.send("files.create", [], undefined, opts, { query: { thread: input.thread, name: input.name }, headers: { "content-type": input.type }, rawBody });
|
|
353
|
+
return withResponse(await readJson(res), responseMeta(res));
|
|
354
|
+
},
|
|
355
|
+
};
|
|
356
|
+
Object.assign(this.threads, {
|
|
357
|
+
attach: (async (threadId, opts = {}) => {
|
|
358
|
+
const { reattach, ...req } = opts;
|
|
359
|
+
const thread = await this.threads.retrieve(threadId, req);
|
|
360
|
+
return thread.active_run ? runsStream(thread.active_run, { ...req, reattach }) : null;
|
|
361
|
+
}),
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
workspace(id, opts = {}) {
|
|
365
|
+
return new OpenLegion({ ...this.#options, apiKey: this.transport.config.apiKey, workspace: id, subject: opts.subject, subjectName: opts.subjectName });
|
|
366
|
+
}
|
|
367
|
+
}
|
package/dist/core.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The types the generated namespaces call through (`src/generated/api.ts` imports them). The client
|
|
3
|
+
* (`client.ts`) implements `Caller`.
|
|
4
|
+
*/
|
|
5
|
+
import type { List, OperationId } from "./generated/api.ts";
|
|
6
|
+
/** Per-call options; each overrides the client's default for this call only. */
|
|
7
|
+
export interface RequestOptions {
|
|
8
|
+
/** Sent as Idempotency-Key on a POST. Default: a fresh UUID per call, the same on every retry of it. */
|
|
9
|
+
idempotencyKey?: string;
|
|
10
|
+
/** OpenLegion-Workspace (ws_…) for a workspace-scoped operation. */
|
|
11
|
+
workspace?: string;
|
|
12
|
+
/** OpenLegion-Subject: your user's id, to act as them (the act_as scope). */
|
|
13
|
+
subject?: string;
|
|
14
|
+
/**
|
|
15
|
+
* OpenLegion-Subject-Name: that user's name, which OpenLegion keeps as their name in your organization. Only with
|
|
16
|
+
* `subject` (this call's; a call for another subject does not carry the client's). 1-120 characters once trimmed;
|
|
17
|
+
* blank is not sent. Pass a name, never an email address. `null` clears it: OpenLegion-Subject-Name-Clear: true is
|
|
18
|
+
* sent instead, and OpenLegion forgets that user's name. Left out (undefined), the name stays.
|
|
19
|
+
*/
|
|
20
|
+
subjectName?: string | null;
|
|
21
|
+
/** OpenLegion-Version. Default: the version this SDK was generated for. */
|
|
22
|
+
apiVersion?: string;
|
|
23
|
+
signal?: AbortSignal;
|
|
24
|
+
/** Per attempt. For a stream, until its headers arrive. */
|
|
25
|
+
timeoutMs?: number;
|
|
26
|
+
maxRetries?: number;
|
|
27
|
+
}
|
|
28
|
+
/** What the HTTP response said, beyond its body. */
|
|
29
|
+
export interface ResponseMeta {
|
|
30
|
+
status: number;
|
|
31
|
+
/** Request-Id (req_…): quote it to support. */
|
|
32
|
+
requestId: string | null;
|
|
33
|
+
/** Idempotent-Replayed: true, an Idempotency-Key replay of an earlier answer. */
|
|
34
|
+
idempotentReplayed: boolean;
|
|
35
|
+
headers: Headers;
|
|
36
|
+
}
|
|
37
|
+
/** An API object with its response attached as a non-enumerable `lastResponse` (Stripe's shape). */
|
|
38
|
+
export type WithResponse<T> = T & {
|
|
39
|
+
readonly lastResponse: ResponseMeta;
|
|
40
|
+
};
|
|
41
|
+
/** One page (await it), or every item across pages (iterate it with `for await`). */
|
|
42
|
+
export type ListPromise<T> = Promise<WithResponse<List<T>>> & AsyncIterable<T>;
|
|
43
|
+
/** How a generated method sends its call. */
|
|
44
|
+
export interface Caller {
|
|
45
|
+
request<T>(op: OperationId, pathParams: readonly string[], payload: object | undefined, options: RequestOptions | undefined): Promise<WithResponse<T>>;
|
|
46
|
+
list<T>(op: OperationId, pathParams: readonly string[], query: object | undefined, options: RequestOptions | undefined): ListPromise<T>;
|
|
47
|
+
}
|
package/dist/core.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/crypto.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Web Crypto and byte helpers, so the verifiers run on Node >= 22 and on every edge runtime alike (no
|
|
3
|
+
* `node:crypto`, no Buffer). HMAC-SHA256 comparison goes through `crypto.subtle.verify`, which compares
|
|
4
|
+
* in constant time.
|
|
5
|
+
*/
|
|
6
|
+
export declare function utf8(text: string): Uint8Array<ArrayBuffer>;
|
|
7
|
+
/** UTF-8 bytes to text, replacing invalid sequences with U+FFFD (as Node's Buffer#toString does). */
|
|
8
|
+
export declare function fromUtf8(bytes: Uint8Array): string;
|
|
9
|
+
export declare function concat(...parts: Uint8Array[]): Uint8Array<ArrayBuffer>;
|
|
10
|
+
/** Text, bytes or an ArrayBuffer, as bytes. */
|
|
11
|
+
export declare function toBytes(body: string | Uint8Array | ArrayBuffer): Uint8Array;
|
|
12
|
+
/** 64 lower-case hex characters (already checked by the caller) to 32 bytes. */
|
|
13
|
+
export declare function hexToBytes(hex: string): Uint8Array<ArrayBuffer>;
|
|
14
|
+
export declare function bytesToHex(bytes: ArrayBuffer | Uint8Array): string;
|
|
15
|
+
export declare function base64urlEncode(bytes: Uint8Array): string;
|
|
16
|
+
/**
|
|
17
|
+
* base64url (no padding) to bytes, decoding the way Node's `Buffer.from(s, "base64url")` does for the
|
|
18
|
+
* alphabet: whole bytes only, a trailing partial byte's bits dropped. The caller has checked the alphabet.
|
|
19
|
+
*/
|
|
20
|
+
export declare function base64urlDecode(text: string): Uint8Array<ArrayBuffer>;
|
|
21
|
+
/** An HMAC-SHA256 key over the secret's UTF-8 bytes (the platform keys both signatures this way). */
|
|
22
|
+
export declare function hmacKey(secret: string): Promise<CryptoKey>;
|
|
23
|
+
export declare function hmacHex(secret: string, data: Uint8Array<ArrayBuffer>): Promise<string>;
|
|
24
|
+
/** Whether `macHex` (64 hex characters) is the HMAC of `data` under `key`. Constant-time. */
|
|
25
|
+
export declare function hmacMatches(key: CryptoKey, macHex: string, data: Uint8Array<ArrayBuffer>): Promise<boolean>;
|
package/dist/crypto.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
const encoder = new TextEncoder();
|
|
2
|
+
const decoder = new TextDecoder("utf-8");
|
|
3
|
+
export function utf8(text) {
|
|
4
|
+
return encoder.encode(text);
|
|
5
|
+
}
|
|
6
|
+
export function fromUtf8(bytes) {
|
|
7
|
+
return decoder.decode(bytes);
|
|
8
|
+
}
|
|
9
|
+
export function concat(...parts) {
|
|
10
|
+
const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
|
|
11
|
+
let at = 0;
|
|
12
|
+
for (const p of parts) {
|
|
13
|
+
out.set(p, at);
|
|
14
|
+
at += p.length;
|
|
15
|
+
}
|
|
16
|
+
return out;
|
|
17
|
+
}
|
|
18
|
+
export function toBytes(body) {
|
|
19
|
+
if (typeof body === "string")
|
|
20
|
+
return utf8(body);
|
|
21
|
+
return body instanceof Uint8Array ? body : new Uint8Array(body);
|
|
22
|
+
}
|
|
23
|
+
export function hexToBytes(hex) {
|
|
24
|
+
const out = new Uint8Array(hex.length / 2);
|
|
25
|
+
for (let i = 0; i < out.length; i++)
|
|
26
|
+
out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
27
|
+
return out;
|
|
28
|
+
}
|
|
29
|
+
export function bytesToHex(bytes) {
|
|
30
|
+
const b = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
|
|
31
|
+
let s = "";
|
|
32
|
+
for (const x of b)
|
|
33
|
+
s += x.toString(16).padStart(2, "0");
|
|
34
|
+
return s;
|
|
35
|
+
}
|
|
36
|
+
const B64URL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
|
37
|
+
const B64URL_INDEX = new Map([...B64URL].map((c, i) => [c, i]));
|
|
38
|
+
export function base64urlEncode(bytes) {
|
|
39
|
+
let out = "";
|
|
40
|
+
let i = 0;
|
|
41
|
+
for (; i + 2 < bytes.length; i += 3) {
|
|
42
|
+
const n = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2];
|
|
43
|
+
out += B64URL[(n >> 18) & 63] + B64URL[(n >> 12) & 63] + B64URL[(n >> 6) & 63] + B64URL[n & 63];
|
|
44
|
+
}
|
|
45
|
+
const rest = bytes.length - i;
|
|
46
|
+
if (rest === 1) {
|
|
47
|
+
const n = bytes[i] << 16;
|
|
48
|
+
out += B64URL[(n >> 18) & 63] + B64URL[(n >> 12) & 63];
|
|
49
|
+
}
|
|
50
|
+
else if (rest === 2) {
|
|
51
|
+
const n = (bytes[i] << 16) | (bytes[i + 1] << 8);
|
|
52
|
+
out += B64URL[(n >> 18) & 63] + B64URL[(n >> 12) & 63] + B64URL[(n >> 6) & 63];
|
|
53
|
+
}
|
|
54
|
+
return out;
|
|
55
|
+
}
|
|
56
|
+
export function base64urlDecode(text) {
|
|
57
|
+
const out = [];
|
|
58
|
+
let acc = 0;
|
|
59
|
+
let bits = 0;
|
|
60
|
+
for (const c of text) {
|
|
61
|
+
const v = B64URL_INDEX.get(c);
|
|
62
|
+
if (v === undefined)
|
|
63
|
+
break;
|
|
64
|
+
acc = ((acc << 6) | v) & 0xffffff;
|
|
65
|
+
bits += 6;
|
|
66
|
+
if (bits >= 8) {
|
|
67
|
+
bits -= 8;
|
|
68
|
+
out.push((acc >> bits) & 0xff);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return new Uint8Array(out);
|
|
72
|
+
}
|
|
73
|
+
export function hmacKey(secret) {
|
|
74
|
+
return crypto.subtle.importKey("raw", utf8(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
|
|
75
|
+
}
|
|
76
|
+
export async function hmacHex(secret, data) {
|
|
77
|
+
return bytesToHex(await crypto.subtle.sign("HMAC", await hmacKey(secret), data));
|
|
78
|
+
}
|
|
79
|
+
export function hmacMatches(key, macHex, data) {
|
|
80
|
+
return crypto.subtle.verify("HMAC", key, hexToBytes(macHex), data);
|
|
81
|
+
}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Typed errors. Every API error is the envelope
|
|
3
|
+
* `{error: {type, code, param, message, doc_url, request_id}}`; the SDK throws one class per `type`,
|
|
4
|
+
* with the envelope's fields as they are on the wire, plus the HTTP status and headers.
|
|
5
|
+
*
|
|
6
|
+
* A `refusal` (402, or a 409 such as workspace_suspended) is the platform saying no to a valid
|
|
7
|
+
* request: its `message` is written for your end user and safe to show them, its `partner_message` is
|
|
8
|
+
* written for you (what happened and what to do: top up, resume), and retrying it never helps.
|
|
9
|
+
*/
|
|
10
|
+
/** The envelope's `type`, plus the SDK's own two. */
|
|
11
|
+
export type OpenLegionErrorType = "invalid_request_error" | "authentication_error" | "permission_error" | "not_found_error" | "conflict_error" | "refusal" | "rate_limit_error" | "api_error" | "connection_error" | "signature_verification_error";
|
|
12
|
+
/**
|
|
13
|
+
* RUN16 (A): which spending limit refused (`cap_reached` only): the day's, the period's or the assistant's own daily one;
|
|
14
|
+
* `used_up` (nothing usable left) or `too_small` (less than this request needs); when it resets (RFC 3339), or null.
|
|
15
|
+
*/
|
|
16
|
+
export interface OpenLegionErrorLimit {
|
|
17
|
+
cap: "daily" | "period" | "agent_daily";
|
|
18
|
+
why: "used_up" | "too_small";
|
|
19
|
+
resets_at: string | null;
|
|
20
|
+
}
|
|
21
|
+
/** A refusal's `limit` as the API sends it, read whole or not at all. */
|
|
22
|
+
export declare function errorLimitOf(raw: unknown): OpenLegionErrorLimit | null;
|
|
23
|
+
export interface OpenLegionErrorInit {
|
|
24
|
+
type: OpenLegionErrorType;
|
|
25
|
+
code: string;
|
|
26
|
+
message: string;
|
|
27
|
+
param?: string | null;
|
|
28
|
+
partner_message?: string | null;
|
|
29
|
+
limit?: OpenLegionErrorLimit | null;
|
|
30
|
+
doc_url?: string | null;
|
|
31
|
+
request_id?: string | null;
|
|
32
|
+
status?: number | null;
|
|
33
|
+
headers?: Headers | null;
|
|
34
|
+
cause?: unknown;
|
|
35
|
+
}
|
|
36
|
+
export declare class OpenLegionError extends Error {
|
|
37
|
+
name: string;
|
|
38
|
+
readonly type: OpenLegionErrorType;
|
|
39
|
+
/** Machine-readable, e.g. `parameter_missing`, `credits_exhausted`. */
|
|
40
|
+
readonly code: string;
|
|
41
|
+
/** The parameter at fault, or null. */
|
|
42
|
+
readonly param: string | null;
|
|
43
|
+
/**
|
|
44
|
+
* Refusals only: the operator's sentence (what happened, what to do). Log it; show your end user
|
|
45
|
+
* `message`. Always present on a refusal (the one rule); null on every other error.
|
|
46
|
+
*/
|
|
47
|
+
readonly partner_message: string | null;
|
|
48
|
+
/** `cap_reached` only: which limit refused, why, and when it resets (RUN16 (A)); null on every other error. */
|
|
49
|
+
readonly limit: OpenLegionErrorLimit | null;
|
|
50
|
+
/** The error's page in the docs. */
|
|
51
|
+
readonly doc_url: string | null;
|
|
52
|
+
/** req_…: quote it to support. */
|
|
53
|
+
readonly request_id: string | null;
|
|
54
|
+
/** HTTP status; null when no response arrived. */
|
|
55
|
+
readonly status: number | null;
|
|
56
|
+
readonly headers: Headers | null;
|
|
57
|
+
constructor(init: OpenLegionErrorInit);
|
|
58
|
+
}
|
|
59
|
+
/** 400 (also 405 and 422 idempotency_key_reused): a missing, unknown or invalid parameter. */
|
|
60
|
+
export declare class InvalidRequestError extends OpenLegionError {
|
|
61
|
+
name: string;
|
|
62
|
+
}
|
|
63
|
+
/** 401: no key, an invalid, revoked or expired key (or session token). Never a working credential of the wrong kind: that is a 403 `PermissionError`. */
|
|
64
|
+
export declare class AuthenticationError extends OpenLegionError {
|
|
65
|
+
name: string;
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* 403: the key lacks the operation's scope, the org is suspended or not approved for live mode, or a session token
|
|
69
|
+
* was sent to a route that takes an org key only (`session_not_allowed`: the token is fine, the credential kind is
|
|
70
|
+
* wrong).
|
|
71
|
+
*/
|
|
72
|
+
export declare class PermissionError extends OpenLegionError {
|
|
73
|
+
name: string;
|
|
74
|
+
}
|
|
75
|
+
/** 404: no such object in this org and mode. */
|
|
76
|
+
export declare class NotFoundError extends OpenLegionError {
|
|
77
|
+
name: string;
|
|
78
|
+
}
|
|
79
|
+
/** 409: a conflict (idempotency_in_flight, connector_changed, …). */
|
|
80
|
+
export declare class ConflictError extends OpenLegionError {
|
|
81
|
+
name: string;
|
|
82
|
+
}
|
|
83
|
+
/** 402 or 409: a limit, a cap, a pause or a policy said no. Show `message` to an end user; log `partner_message`. */
|
|
84
|
+
export declare class RefusalError extends OpenLegionError {
|
|
85
|
+
name: string;
|
|
86
|
+
}
|
|
87
|
+
/** 429. `retryAfterSeconds` is Retry-After, when sent. */
|
|
88
|
+
export declare class RateLimitError extends OpenLegionError {
|
|
89
|
+
name: string;
|
|
90
|
+
get retryAfterSeconds(): number | null;
|
|
91
|
+
}
|
|
92
|
+
/** 5xx, or an answer the SDK could not read. */
|
|
93
|
+
export declare class APIError extends OpenLegionError {
|
|
94
|
+
name: string;
|
|
95
|
+
}
|
|
96
|
+
/** No response: the network failed or the attempt timed out. */
|
|
97
|
+
export declare class APIConnectionError extends OpenLegionError {
|
|
98
|
+
name: string;
|
|
99
|
+
}
|
|
100
|
+
/** Why a webhook or ol_signed signature did not verify. */
|
|
101
|
+
export type SignatureFailure = "missing_headers" | "malformed_signature" | "stale" | "bad_signature" | "malformed_context" | "no_secret";
|
|
102
|
+
/** A webhook (or ol_signed request) whose signature did not verify. Never process its body. */
|
|
103
|
+
export declare class SignatureVerificationError extends OpenLegionError {
|
|
104
|
+
name: string;
|
|
105
|
+
readonly reason: SignatureFailure;
|
|
106
|
+
constructor(reason: SignatureFailure, message: string);
|
|
107
|
+
}
|
|
108
|
+
/** The typed error for a non-2xx answer. `text` is the raw body (it may not be JSON at all). */
|
|
109
|
+
export declare function errorFromResponse(status: number, headers: Headers, text: string): OpenLegionError;
|
|
110
|
+
/** Retry-After as milliseconds (delta-seconds or an HTTP date), or null. */
|
|
111
|
+
export declare function retryAfterMs(headers: Headers | null, now?: number): number | null;
|