@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.
Files changed (120) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +1189 -2
  3. package/dist/body.d.ts +9 -0
  4. package/dist/body.js +28 -0
  5. package/dist/chat-history.d.ts +53 -0
  6. package/dist/chat-history.js +11 -0
  7. package/dist/client.d.ts +217 -0
  8. package/dist/client.js +367 -0
  9. package/dist/core.d.ts +47 -0
  10. package/dist/core.js +1 -0
  11. package/dist/crypto.d.ts +25 -0
  12. package/dist/crypto.js +81 -0
  13. package/dist/errors.d.ts +111 -0
  14. package/dist/errors.js +134 -0
  15. package/dist/events.d.ts +131 -0
  16. package/dist/events.js +5 -0
  17. package/dist/generated/api.d.ts +5505 -0
  18. package/dist/generated/api.js +446 -0
  19. package/dist/handler.d.ts +201 -0
  20. package/dist/handler.js +682 -0
  21. package/dist/index.d.ts +24 -0
  22. package/dist/index.js +12 -0
  23. package/dist/kit-agents.d.ts +95 -0
  24. package/dist/kit-agents.js +280 -0
  25. package/dist/kit-codes.d.ts +279 -0
  26. package/dist/kit-codes.js +44 -0
  27. package/dist/kit-connections.d.ts +21 -0
  28. package/dist/kit-connections.js +189 -0
  29. package/dist/kit-files.d.ts +8 -0
  30. package/dist/kit-files.js +117 -0
  31. package/dist/kit-model-keys.d.ts +8 -0
  32. package/dist/kit-model-keys.js +86 -0
  33. package/dist/kit-threads.d.ts +3 -0
  34. package/dist/kit-threads.js +92 -0
  35. package/dist/kit-tools.d.ts +21 -0
  36. package/dist/kit-tools.js +47 -0
  37. package/dist/kit.d.ts +130 -0
  38. package/dist/kit.js +155 -0
  39. package/dist/mcp-server.d.ts +27 -0
  40. package/dist/mcp-server.js +166 -0
  41. package/dist/next.d.ts +24 -0
  42. package/dist/next.js +6 -0
  43. package/dist/ol-signed.d.ts +82 -0
  44. package/dist/ol-signed.js +115 -0
  45. package/dist/react/add-server.d.ts +90 -0
  46. package/dist/react/add-server.js +183 -0
  47. package/dist/react/agent-chat.d.ts +925 -0
  48. package/dist/react/agent-chat.js +1917 -0
  49. package/dist/react/agent-editor.d.ts +133 -0
  50. package/dist/react/agent-editor.js +222 -0
  51. package/dist/react/agent-kit.d.ts +160 -0
  52. package/dist/react/agent-kit.js +279 -0
  53. package/dist/react/agent-list.d.ts +247 -0
  54. package/dist/react/agent-list.js +248 -0
  55. package/dist/react/approval-card.d.ts +272 -0
  56. package/dist/react/approval-card.js +372 -0
  57. package/dist/react/artifact-card.d.ts +38 -0
  58. package/dist/react/artifact-card.js +39 -0
  59. package/dist/react/avatar.d.ts +21 -0
  60. package/dist/react/avatar.js +33 -0
  61. package/dist/react/card-ledger.d.ts +30 -0
  62. package/dist/react/card-ledger.js +49 -0
  63. package/dist/react/chat-timing.d.ts +121 -0
  64. package/dist/react/chat-timing.js +229 -0
  65. package/dist/react/computer-view.d.ts +309 -0
  66. package/dist/react/computer-view.js +543 -0
  67. package/dist/react/computer-viewer.d.ts +175 -0
  68. package/dist/react/computer-viewer.js +555 -0
  69. package/dist/react/computer-wire.d.ts +178 -0
  70. package/dist/react/computer-wire.js +244 -0
  71. package/dist/react/connect-button.d.ts +145 -0
  72. package/dist/react/connect-button.js +212 -0
  73. package/dist/react/connection-request.d.ts +16 -0
  74. package/dist/react/connection-request.js +18 -0
  75. package/dist/react/connections-list.d.ts +90 -0
  76. package/dist/react/connections-list.js +76 -0
  77. package/dist/react/errors.d.ts +250 -0
  78. package/dist/react/errors.js +146 -0
  79. package/dist/react/files.d.ts +41 -0
  80. package/dist/react/files.js +78 -0
  81. package/dist/react/index.d.ts +35 -0
  82. package/dist/react/index.js +26 -0
  83. package/dist/react/limit-words.d.ts +80 -0
  84. package/dist/react/limit-words.js +53 -0
  85. package/dist/react/markdown.d.ts +42 -0
  86. package/dist/react/markdown.js +56 -0
  87. package/dist/react/md-parse.d.ts +106 -0
  88. package/dist/react/md-parse.js +638 -0
  89. package/dist/react/model-keys-card.d.ts +94 -0
  90. package/dist/react/model-keys-card.js +123 -0
  91. package/dist/react/reload.d.ts +211 -0
  92. package/dist/react/reload.js +339 -0
  93. package/dist/react/reveal.d.ts +17 -0
  94. package/dist/react/reveal.js +22 -0
  95. package/dist/react/schedule-editor.d.ts +107 -0
  96. package/dist/react/schedule-editor.js +172 -0
  97. package/dist/react/schedule-time.d.ts +66 -0
  98. package/dist/react/schedule-time.js +90 -0
  99. package/dist/react/styles.css +1274 -0
  100. package/dist/react/transport.d.ts +49 -0
  101. package/dist/react/transport.js +380 -0
  102. package/dist/react/use-connections.d.ts +155 -0
  103. package/dist/react/use-connections.js +231 -0
  104. package/dist/react/use-model-keys.d.ts +47 -0
  105. package/dist/react/use-model-keys.js +57 -0
  106. package/dist/react/use-threads.d.ts +63 -0
  107. package/dist/react/use-threads.js +73 -0
  108. package/dist/react/vault-form.d.ts +92 -0
  109. package/dist/react/vault-form.js +151 -0
  110. package/dist/schema.d.ts +47 -0
  111. package/dist/schema.js +16 -0
  112. package/dist/secrets.d.ts +15 -0
  113. package/dist/secrets.js +18 -0
  114. package/dist/stream.d.ts +129 -0
  115. package/dist/stream.js +192 -0
  116. package/dist/testing.d.ts +33 -0
  117. package/dist/testing.js +40 -0
  118. package/dist/webhooks.d.ts +31 -0
  119. package/dist/webhooks.js +72 -0
  120. package/package.json +85 -3
@@ -0,0 +1,151 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
3
+ import { useContext, useEffect, useState } from "react";
4
+ import { CardLedgerContext, vaultKey } from "./card-ledger.js";
5
+ import { useNoteInView } from "./reveal.js";
6
+ const NAME_RE = /^[a-z0-9][a-z0-9_-]{0,47}$/;
7
+ const strings = (v) => (Array.isArray(v) && v.every((x) => typeof x === "string") ? v : null);
8
+ export function vaultRequestOf(data) {
9
+ if (!data || typeof data !== "object" || Array.isArray(data))
10
+ return null;
11
+ const o = data;
12
+ if (o["object"] !== "vault_request")
13
+ return null;
14
+ const name = o["name"];
15
+ const kind = o["kind"];
16
+ const origins = strings(o["origins"]);
17
+ const hosts = strings(o["hosts"]);
18
+ const added = strings(o["added"] ?? []);
19
+ if (typeof name !== "string" || !NAME_RE.test(name) || (kind !== "login" && kind !== "api_key" && kind !== "secret") || !origins || !hosts || !added)
20
+ return null;
21
+ if (origins.length + hosts.length === 0)
22
+ return null;
23
+ return {
24
+ name,
25
+ handle: `vault://${name}`,
26
+ kind,
27
+ label: typeof o["label"] === "string" && o["label"] !== "" ? o["label"].slice(0, 200) : name,
28
+ origins,
29
+ hosts,
30
+ existing: o["existing"] === true,
31
+ addsNewSite: o["adds_new_site"] === true,
32
+ added,
33
+ needsTotp: kind === "login" && o["needs_totp"] === true,
34
+ tainted: o["tainted"] === true,
35
+ reason: typeof o["reason"] === "string" ? o["reason"].slice(0, 500) : "",
36
+ };
37
+ }
38
+ export const DEFAULT_VAULT_LABELS = {
39
+ title: "Save {label} for your agent",
40
+ usedOn: "It will be used only on",
41
+ reason: "Your agent says:",
42
+ tainted: "Your agent asked after reading content from outside. Check that the address is the one you expect before you save.",
43
+ addsSite: "{label} is already saved. Saving this also lets it be used on {sites}.",
44
+ username: "User name or email",
45
+ password: "Password",
46
+ totp: "Authenticator key (optional)",
47
+ totpHint: "Lets your agent pass two-step sign-in by itself. It also keeps both steps in one place, so leave it empty to keep that step with you.",
48
+ totpRequired: "Authenticator key",
49
+ totpRequiredHint: "This login already has one saved. Enter its setup key again so it can be used on the new site too.",
50
+ value: "Key",
51
+ save: "Save",
52
+ saving: "Saving…",
53
+ saved: "Saved. Your agent can use it from its next reply. It never sees what you typed.",
54
+ failed: "That did not save. Check what you typed and try again.",
55
+ notYours: "An owner or admin saved this one. Ask them to add it here.",
56
+ notYet: "Your agent is still working on this reply. Save again in a moment.",
57
+ };
58
+ export function vaultSaveBody(r, secret, ask) {
59
+ return JSON.stringify({ name: r.name, kind: r.kind, label: r.label, ...(r.origins.length ? { origins: r.origins } : {}), ...(r.hosts.length ? { hosts: r.hosts } : {}), secret, ...(ask ? { ask } : {}) });
60
+ }
61
+ export function vaultSaveState(status, code) {
62
+ if (status >= 200 && status < 300)
63
+ return "saved";
64
+ if (status === 403)
65
+ return "notYours";
66
+ return status === 409 && code === "vault_ask_missing" ? "notYet" : "failed";
67
+ }
68
+ async function errorCode(res) {
69
+ if (res.ok)
70
+ return null;
71
+ try {
72
+ const code = (await res.clone().json()).error?.code;
73
+ return typeof code === "string" ? code : null;
74
+ }
75
+ catch {
76
+ return null;
77
+ }
78
+ }
79
+ export const ASK_WAIT = { every: 2000, upTo: 20_000 };
80
+ export async function saveUntilAsked(send, wait = (ms) => new Promise((r) => setTimeout(r, ms))) {
81
+ for (let waited = 0;; waited += ASK_WAIT.every) {
82
+ const res = await send();
83
+ if (res.status !== 409 || (await errorCode(res)) !== "vault_ask_missing" || waited >= ASK_WAIT.upTo)
84
+ return res;
85
+ await wait(ASK_WAIT.every);
86
+ }
87
+ }
88
+ function asciiSite(site) {
89
+ try {
90
+ return site.includes("://") ? new URL(site).origin : new URL(`https://${site}`).host;
91
+ }
92
+ catch {
93
+ return site;
94
+ }
95
+ }
96
+ const field = { display: "flex", flexDirection: "column", gap: "var(--ol-vault-gap, 0.5rem)" };
97
+ const box = { display: "flex", flexDirection: "column", gap: "var(--ol-vault-gap, 0.5rem)", border: "1px solid var(--ol-vault-border, currentColor)", borderRadius: "var(--ol-vault-radius, 0.5rem)", padding: "var(--ol-vault-padding, 0.75rem)" };
98
+ const fill = (text, r, sites) => text.replace("{label}", r.label).replace("{handle}", r.handle).replace("{sites}", sites);
99
+ export function VaultSecretForm(props) {
100
+ const l = { ...DEFAULT_VAULT_LABELS, ...props.labels };
101
+ const r = props.request;
102
+ const [username, setUsername] = useState("");
103
+ const [password, setPassword] = useState("");
104
+ const [totp, setTotp] = useState("");
105
+ const [value, setValue] = useState("");
106
+ const ledger = useContext(CardLedgerContext);
107
+ const key = ledger && props.ask ? vaultKey(props.ask, r.handle) : null;
108
+ const [state, setShown] = useState(() => (ledger && key ? ledger.vaultState(key) : undefined) ?? "idle");
109
+ useEffect(() => (ledger && key ? ledger.vaultWatch(key, setShown) : undefined), [ledger, key]);
110
+ const setState = (next) => {
111
+ setShown(next);
112
+ if (ledger && key)
113
+ ledger.vaultSet(key, next);
114
+ };
115
+ const sites = [...r.origins, ...r.hosts].map(asciiSite);
116
+ const login = r.kind === "login";
117
+ const ready = login ? username.trim() !== "" && password !== "" && (!r.needsTotp || totp.trim() !== "") : value !== "";
118
+ const savedInView = useNoteInView();
119
+ const errorInView = useNoteInView(state);
120
+ const submit = async (e) => {
121
+ e.preventDefault();
122
+ if (!ready || state === "saving" || state === "saved")
123
+ return;
124
+ setState("saving");
125
+ const secret = login ? { username: username.trim(), password, ...(totp.trim() ? { totp: totp.trim() } : {}) } : { value };
126
+ const body = vaultSaveBody(r, secret, props.ask);
127
+ setPassword("");
128
+ setTotp("");
129
+ setValue("");
130
+ try {
131
+ const f = props.fetch ?? fetch;
132
+ const res = await saveUntilAsked(() => f(props.api ?? "/api/openlegion/vault", { method: "POST", headers: { "content-type": "application/json" }, body, credentials: "same-origin" }));
133
+ const next = vaultSaveState(res.status, await errorCode(res));
134
+ if (next !== "saved") {
135
+ setState(next);
136
+ props.onError?.(new Error(`vault save answered ${res.status}`));
137
+ return;
138
+ }
139
+ setState("saved");
140
+ props.onSaved?.(r.handle, r);
141
+ }
142
+ catch (err) {
143
+ setState("failed");
144
+ props.onError?.(err instanceof Error ? err : new Error(String(err)));
145
+ }
146
+ };
147
+ if (state === "saved") {
148
+ return (_jsx("p", { "data-ol-vault-saved": true, role: "status", className: props.className, style: { margin: 0 }, ref: savedInView, children: fill(l.saved, r, sites.join(", ")) }));
149
+ }
150
+ return (_jsxs("form", { "data-ol-vault-form": true, "data-ol-vault-kind": r.kind, className: props.className, style: box, onSubmit: (e) => void submit(e), autoComplete: "off", children: [_jsx("strong", { "data-ol-vault-title": true, children: fill(l.title, r, sites.join(", ")) }), _jsxs("div", { "data-ol-vault-sites": true, children: [_jsx("span", { children: l.usedOn }), sites.map((s) => (_jsx("code", { "data-ol-vault-site": true, style: { display: "block", fontSize: "var(--ol-vault-site-size, 1.25em)", fontWeight: 600, wordBreak: "break-all" }, children: s }, s)))] }), r.reason ? (_jsxs("p", { "data-ol-vault-reason": true, style: { margin: 0 }, children: [l.reason, " ", _jsx("q", { children: r.reason })] })) : null, r.tainted ? (_jsx("p", { "data-ol-vault-tainted": true, role: "note", style: { margin: 0, color: "var(--ol-vault-caution, inherit)", fontWeight: 600 }, children: l.tainted })) : null, r.addsNewSite ? (_jsx("p", { "data-ol-vault-adds-site": true, role: "note", style: { margin: 0, color: "var(--ol-vault-caution, inherit)", fontWeight: 600 }, children: fill(l.addsSite, r, r.added.map(asciiSite).join(", ")) })) : null, login ? (_jsxs(_Fragment, { children: [_jsxs("label", { "data-ol-vault-field": true, style: field, children: [l.username, _jsx("input", { "data-ol-vault-username": true, type: "text", autoComplete: "off", spellCheck: false, value: username, onChange: (e) => setUsername(e.target.value) })] }), _jsxs("label", { "data-ol-vault-field": true, style: field, children: [l.password, _jsx("input", { "data-ol-vault-password": true, type: "password", autoComplete: "new-password", value: password, onChange: (e) => setPassword(e.target.value) })] }), _jsxs("label", { "data-ol-vault-field": true, style: field, children: [r.needsTotp ? l.totpRequired : l.totp, _jsx("input", { "data-ol-vault-totp": true, type: "password", autoComplete: "off", required: r.needsTotp, value: totp, onChange: (e) => setTotp(e.target.value) }), _jsx("small", { "data-ol-vault-totp-hint": true, children: r.needsTotp ? l.totpRequiredHint : l.totpHint })] })] })) : (_jsxs("label", { "data-ol-vault-field": true, style: field, children: [l.value, _jsx("input", { "data-ol-vault-value": true, type: "password", autoComplete: "off", value: value, onChange: (e) => setValue(e.target.value) })] })), state === "failed" || state === "notYours" || state === "notYet" ? (_jsx("p", { "data-ol-vault-error": true, role: "alert", style: { margin: 0 }, ref: errorInView, children: state === "notYours" ? l.notYours : state === "notYet" ? l.notYet : l.failed })) : null, _jsx("button", { type: "submit", "data-ol-vault-save": true, disabled: !ready || state === "saving", children: state === "saving" ? l.saving : l.save })] }));
151
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Standard Schema (https://standardschema.dev): the kit takes any validator that implements it AND its
3
+ * JSON Schema extension, so it never imports one. zod 4 (`z.object(…)`) does both; so do Valibot and
4
+ * ArkType with their JSON Schema adapters. The interfaces below are the spec's, restated (the spec asks
5
+ * implementers to copy them rather than depend on a package).
6
+ */
7
+ export interface StandardSchemaIssue {
8
+ readonly message: string;
9
+ readonly path?: ReadonlyArray<PropertyKey | {
10
+ readonly key: PropertyKey;
11
+ }> | undefined;
12
+ }
13
+ export type StandardSchemaResult<Output> = {
14
+ readonly value: Output;
15
+ readonly issues?: undefined;
16
+ } | {
17
+ readonly issues: ReadonlyArray<StandardSchemaIssue>;
18
+ };
19
+ /** A schema that validates (`~standard.validate`) and describes itself as JSON Schema (`~standard.jsonSchema`). */
20
+ export interface StandardSchemaWithJSON<Input = unknown, Output = Input> {
21
+ readonly "~standard": {
22
+ readonly version: 1;
23
+ readonly vendor: string;
24
+ readonly validate: (value: unknown, options?: {
25
+ readonly libraryOptions?: Record<string, unknown> | undefined;
26
+ }) => StandardSchemaResult<Output> | Promise<StandardSchemaResult<Output>>;
27
+ readonly jsonSchema: {
28
+ readonly input: (options: {
29
+ readonly target: "draft-2020-12" | "draft-07" | "openapi-3.0" | ({} & string);
30
+ }) => Record<string, unknown>;
31
+ readonly output: (options: {
32
+ readonly target: "draft-2020-12" | "draft-07" | "openapi-3.0" | ({} & string);
33
+ }) => Record<string, unknown>;
34
+ };
35
+ readonly types?: {
36
+ readonly input: Input;
37
+ readonly output: Output;
38
+ } | undefined;
39
+ };
40
+ }
41
+ /** What a schema validates to. */
42
+ export type InferOutput<S extends StandardSchemaWithJSON> = NonNullable<S["~standard"]["types"]>["output"];
43
+ export declare function isStandardSchemaWithJSON(value: unknown): value is StandardSchemaWithJSON;
44
+ /** The schema's input as JSON Schema 2020-12 (what MCP's tools/list carries), without `$schema`. */
45
+ export declare function inputJsonSchema(schema: StandardSchemaWithJSON): Record<string, unknown>;
46
+ /** One line per issue: `path: message`. */
47
+ export declare function issuesText(issues: ReadonlyArray<StandardSchemaIssue>): string;
package/dist/schema.js ADDED
@@ -0,0 +1,16 @@
1
+ export function isStandardSchemaWithJSON(value) {
2
+ const std = value?.["~standard"];
3
+ return !!std && std.version === 1 && typeof std.validate === "function" && typeof std.jsonSchema?.input === "function";
4
+ }
5
+ export function inputJsonSchema(schema) {
6
+ const { $schema: _drop, ...rest } = schema["~standard"].jsonSchema.input({ target: "draft-2020-12" });
7
+ return rest;
8
+ }
9
+ export function issuesText(issues) {
10
+ return issues
11
+ .map((i) => {
12
+ const path = (i.path ?? []).map((p) => (typeof p === "object" && p !== null ? String(p.key) : String(p))).join(".");
13
+ return path ? `${path}: ${i.message}` : i.message;
14
+ })
15
+ .join("; ");
16
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The secrets a verifier holds. During a rotation's grace a receiver holds two: the new one, and the old
3
+ * one until `previous_secret_expires_at` from the rotate_secret answer (webhook endpoints and connectors alike).
4
+ * Give the old one its expiry, and it stops verifying at that instant whatever the request says, so a
5
+ * leaked old secret is worth nothing after the grace.
6
+ */
7
+ export interface SecretEntry {
8
+ secret: string;
9
+ /** When this secret stops verifying (RFC 3339 or a Date). Absent: it does not expire. */
10
+ expires?: string | Date | null;
11
+ }
12
+ /** One secret, one with an expiry, or several (newest first, as rotate_secret leaves them). */
13
+ export type SecretInput = string | SecretEntry | ReadonlyArray<string | SecretEntry>;
14
+ /** The secrets still live at `nowMs`. An unreadable expiry counts as expired (fail closed). */
15
+ export declare function liveSecrets(input: SecretInput | undefined | null, nowMs: number): string[];
@@ -0,0 +1,18 @@
1
+ export function liveSecrets(input, nowMs) {
2
+ if (input === undefined || input === null)
3
+ return [];
4
+ const list = typeof input === "string" || !Array.isArray(input) ? [input] : input;
5
+ const out = [];
6
+ for (const item of list) {
7
+ const entry = typeof item === "string" ? { secret: item } : item;
8
+ if (typeof entry.secret !== "string" || entry.secret.length === 0)
9
+ continue;
10
+ if (entry.expires !== undefined && entry.expires !== null) {
11
+ const at = entry.expires instanceof Date ? entry.expires.getTime() : Date.parse(entry.expires);
12
+ if (Number.isNaN(at) || nowMs >= at)
13
+ continue;
14
+ }
15
+ out.push(entry.secret);
16
+ }
17
+ return out;
18
+ }
@@ -0,0 +1,129 @@
1
+ /**
2
+ * THE RUN STREAM READER.
3
+ *
4
+ * The platform streams a run as Server-Sent Events carrying the AI SDK UI message stream:
5
+ *
6
+ * id: N\ndata: <json part>\n\n a part of the run, numbered from 0 (the same numbers live and replayed)
7
+ * data: <json part>\n\n a status part with no number (data-queued, error, abort, finish, and the
8
+ * data-refusal of a run that waited and never started)
9
+ * data: [DONE]\n\n the end
10
+ *
11
+ * A stream that closes WITHOUT [DONE] was cut short (the 270 s follow deadline, a deploy, a dropped
12
+ * connection), and the run goes on. The reader then RE-ATTACHES with `GET /runs/{id}/stream` and
13
+ * `Last-Event-ID: <the last N it saw>`, and drops any part numbered at or below it, so a consumer sees each
14
+ * part once, in order, across cuts. It never re-sends the message: that would start a second run.
15
+ *
16
+ * The platform's interruption notice (an id-less `error` part, "Re-attach with Last-Event-ID", then a
17
+ * close without [DONE]) is held: if the connection simply ends after it, it is dropped and the reader
18
+ * re-attaches; if anything follows it, it is passed on.
19
+ *
20
+ * CLOSING NEVER CANCELS. `close()`, an abort signal, or `break` in a `for await` only stops reading. The
21
+ * run is cancelled by `ol.runs.cancel(id)` and nothing else.
22
+ */
23
+ import { type OpenLegionErrorLimit } from "./errors.ts";
24
+ import type { RequestOptions } from "./core.ts";
25
+ import type { Transport } from "./client.ts";
26
+ /**
27
+ * Why a run waits: its thread's previous run is still going (`thread_busy`), the agent is at its limit on runs
28
+ * at once (`agent_busy`), the agent is paused (`agent_paused`), the workspace is at its limit (`workspace_busy`),
29
+ * or the organization's credits are held by runs in flight (`credit_wait`). The run object's `waiting.reason`
30
+ * uses the same values.
31
+ */
32
+ export type QueuedReason = "thread_busy" | "agent_busy" | "workspace_busy" | "agent_paused" | "credit_wait";
33
+ /** Waiting for the run to start (transient: not part of the message). `position` 1 starts next. */
34
+ export interface QueuedPart {
35
+ type: "data-queued";
36
+ data: {
37
+ position: number;
38
+ reason: QueuedReason;
39
+ };
40
+ transient?: boolean;
41
+ [key: string]: unknown;
42
+ }
43
+ /**
44
+ * The run did not succeed, and says why: it stopped after it started (run_budget_exhausted,
45
+ * workspace_suspended, …), or it waited and never started (refused when its turn came: cap_reached,
46
+ * credits_exhausted, …; or closed by the 40-minute expiry: run_failed). For a run that never started, an
47
+ * `error` part with the same sentence follows it. `message` is your end user's sentence; the run's
48
+ * `error.partner_message` is yours.
49
+ */
50
+ export interface RefusalPart {
51
+ type: "data-refusal";
52
+ /** `limit`: a cap refusal's (RUN16 (A)): which limit, why, when it resets. */
53
+ data: {
54
+ code: string;
55
+ message: string;
56
+ limit?: OpenLegionErrorLimit | null;
57
+ };
58
+ [key: string]: unknown;
59
+ }
60
+ /**
61
+ * The reply ran on the agent's usual model, not the one the person chose: the run's budget couldn't cover it
62
+ * (`reason: "run_budget"`; more reasons may come). Not a failure. Sent unnumbered at the stream's end, after the
63
+ * files and before the taint part, so a re-attach may send it again; in a thread's history it is the reply's last
64
+ * part. Only for a model the person picked, never for Auto. `message` is your end user's sentence.
65
+ */
66
+ export interface ModelNotePart {
67
+ type: "data-model-note";
68
+ data: {
69
+ object: "model_note";
70
+ model_tier: string;
71
+ model_requested: string;
72
+ reason: string;
73
+ message: string;
74
+ };
75
+ [key: string]: unknown;
76
+ }
77
+ /** Any other AI SDK UI message chunk (text-delta, tool-input-available, finish, …), passed through as sent. The run stream sends no reasoning chunks. */
78
+ export interface OtherPart {
79
+ type: string;
80
+ [key: string]: unknown;
81
+ }
82
+ export type RunStreamPart = QueuedPart | RefusalPart | ModelNotePart | OtherPart;
83
+ /** One SSE event as the platform sent it: its number (null for a status part) and its part. */
84
+ export interface RunStreamEvent {
85
+ id: number | null;
86
+ part: RunStreamPart;
87
+ }
88
+ /**
89
+ * `no-transform`: nothing between the kit and the browser may re-encode the stream. From Next 16.4.6, `next start`
90
+ * compresses route handler responses, and a compressor that holds chunks back would hold the chat back with them.
91
+ */
92
+ export declare const SSE_RESPONSE_HEADERS: Readonly<Record<string, string>>;
93
+ /** Parse an SSE byte stream into events (id, data). Handles any chunking; ignores comments and other fields. */
94
+ export declare function parseSse(body: ReadableStream<Uint8Array>, signal?: AbortSignal): AsyncGenerator<{
95
+ id: string | null;
96
+ data: string;
97
+ }>;
98
+ export interface RunStreamInit {
99
+ transport: Transport;
100
+ run: string;
101
+ /** The first response (a messages.stream POST), or null to attach from `after`. */
102
+ first: Response | null;
103
+ /** Start after this part number (-1: from the start). */
104
+ after?: number;
105
+ options?: RequestOptions;
106
+ /** Re-attach when a stream is cut short. Default true. */
107
+ reattach?: boolean;
108
+ }
109
+ /**
110
+ * A run's stream: iterate its parts (`for await (const part of stream)`), or hand it to the browser with
111
+ * `toResponse()` (SSE, ids kept, for useChat).
112
+ */
113
+ export declare class RunStream implements AsyncIterable<RunStreamPart> {
114
+ #private;
115
+ /** run_…: the run this stream follows. */
116
+ readonly run: string;
117
+ constructor(init: RunStreamInit);
118
+ /** The number of the last part read: re-attach after it with `ol.runs.stream(run, { after })`. */
119
+ get lastEventId(): number;
120
+ /** Stop reading. The run goes on; cancel it with `ol.runs.cancel(run)`. */
121
+ close(): void;
122
+ /** Every event, numbered parts once each, across re-attaches. Single use. */
123
+ events(): AsyncGenerator<RunStreamEvent>;
124
+ [Symbol.asyncIterator](): AsyncGenerator<RunStreamPart>;
125
+ /** The stream re-encoded as SSE (the same numbers, then [DONE]): what useChat reads. */
126
+ toReadableStream(): ReadableStream<Uint8Array>;
127
+ /** A Response carrying the stream, for a route handler to return to the browser. */
128
+ toResponse(init?: ResponseInit): Response;
129
+ }
package/dist/stream.js ADDED
@@ -0,0 +1,192 @@
1
+ import { APIConnectionError } from "./errors.js";
2
+ export const SSE_RESPONSE_HEADERS = {
3
+ "content-type": "text/event-stream",
4
+ "cache-control": "no-cache, no-transform",
5
+ connection: "keep-alive",
6
+ "x-vercel-ai-ui-message-stream": "v1",
7
+ "x-accel-buffering": "no",
8
+ };
9
+ const MAX_IDLE_REATTACHES = 3;
10
+ export async function* parseSse(body, signal) {
11
+ const reader = body.getReader();
12
+ const decoder = new TextDecoder();
13
+ let buffer = "";
14
+ let id = null;
15
+ let data = [];
16
+ const onAbort = () => void reader.cancel().catch(() => undefined);
17
+ signal?.addEventListener("abort", onAbort, { once: true });
18
+ try {
19
+ for (;;) {
20
+ const { done, value } = await reader.read();
21
+ buffer += done ? decoder.decode() : decoder.decode(value, { stream: true });
22
+ let nl;
23
+ while ((nl = buffer.search(/\r\n|\r|\n/)) >= 0) {
24
+ const line = buffer.slice(0, nl);
25
+ buffer = buffer.slice(nl + (buffer.startsWith("\r\n", nl) ? 2 : 1));
26
+ if (line === "") {
27
+ if (data.length > 0)
28
+ yield { id, data: data.join("\n") };
29
+ id = null;
30
+ data = [];
31
+ continue;
32
+ }
33
+ if (line.startsWith(":"))
34
+ continue;
35
+ const colon = line.indexOf(":");
36
+ const field = colon < 0 ? line : line.slice(0, colon);
37
+ let value = colon < 0 ? "" : line.slice(colon + 1);
38
+ if (value.startsWith(" "))
39
+ value = value.slice(1);
40
+ if (field === "data")
41
+ data.push(value);
42
+ else if (field === "id")
43
+ id = value;
44
+ }
45
+ if (done)
46
+ return;
47
+ }
48
+ }
49
+ finally {
50
+ signal?.removeEventListener("abort", onAbort);
51
+ reader.releaseLock();
52
+ }
53
+ }
54
+ export class RunStream {
55
+ run;
56
+ #lastEventId;
57
+ #first;
58
+ #started = false;
59
+ #init;
60
+ #abort = new AbortController();
61
+ constructor(init) {
62
+ this.run = init.run;
63
+ this.#init = init;
64
+ this.#first = init.first;
65
+ this.#lastEventId = init.after ?? -1;
66
+ const outer = init.options?.signal;
67
+ if (outer?.aborted)
68
+ this.#abort.abort(outer.reason);
69
+ else
70
+ outer?.addEventListener("abort", () => this.#abort.abort(outer.reason), { once: true });
71
+ }
72
+ get lastEventId() {
73
+ return this.#lastEventId;
74
+ }
75
+ close() {
76
+ this.#abort.abort(new Error("RunStream closed"));
77
+ }
78
+ async #attach() {
79
+ const headers = {};
80
+ if (this.#lastEventId >= 0)
81
+ headers["last-event-id"] = String(this.#lastEventId);
82
+ return this.#init.transport.send("runs.stream", [this.run], undefined, { ...this.#init.options, signal: this.#abort.signal }, { accept: "text/event-stream", headers });
83
+ }
84
+ async *events() {
85
+ if (this.#started)
86
+ throw new TypeError("RunStream: already being read (a stream can be read once).");
87
+ this.#started = true;
88
+ const reattach = this.#init.reattach !== false;
89
+ let idle = 0;
90
+ let res = this.#first ?? (await this.#attach());
91
+ this.#first = null;
92
+ for (;;) {
93
+ if (!res.body)
94
+ throw new APIConnectionError({ type: "connection_error", code: "empty_stream", message: "OpenLegion: the run stream had no body." });
95
+ let held = null;
96
+ let done = false;
97
+ const before = this.#lastEventId;
98
+ try {
99
+ for await (const frame of parseSse(res.body, this.#abort.signal)) {
100
+ if (frame.data === "[DONE]") {
101
+ done = true;
102
+ break;
103
+ }
104
+ let part;
105
+ try {
106
+ part = JSON.parse(frame.data);
107
+ }
108
+ catch {
109
+ continue;
110
+ }
111
+ const id = frame.id !== null && /^\d{1,9}$/.test(frame.id) ? Number(frame.id) : null;
112
+ if (held) {
113
+ yield held;
114
+ held = null;
115
+ }
116
+ if (id !== null) {
117
+ if (id <= this.#lastEventId)
118
+ continue;
119
+ this.#lastEventId = id;
120
+ yield { id, part };
121
+ }
122
+ else if (part.type === "error") {
123
+ held = { id: null, part };
124
+ }
125
+ else {
126
+ yield { id: null, part };
127
+ }
128
+ }
129
+ }
130
+ catch (err) {
131
+ if (this.#abort.signal.aborted)
132
+ return;
133
+ void err;
134
+ }
135
+ if (done) {
136
+ void res.body.cancel().catch(() => undefined);
137
+ if (held)
138
+ yield held;
139
+ return;
140
+ }
141
+ if (this.#abort.signal.aborted)
142
+ return;
143
+ if (!reattach) {
144
+ if (held)
145
+ yield held;
146
+ return;
147
+ }
148
+ idle = this.#lastEventId > before ? 0 : idle + 1;
149
+ if (idle > MAX_IDLE_REATTACHES) {
150
+ throw new APIConnectionError({ type: "connection_error", code: "stream_stalled", message: `OpenLegion: the stream of ${this.run} was cut ${idle} times without progress; re-attach later with ol.runs.stream("${this.run}", { after: ${this.#lastEventId} }).` });
151
+ }
152
+ res = await this.#attach();
153
+ }
154
+ }
155
+ async *[Symbol.asyncIterator]() {
156
+ for await (const e of this.events())
157
+ yield e.part;
158
+ }
159
+ toReadableStream() {
160
+ const enc = new TextEncoder();
161
+ const events = this.events();
162
+ return new ReadableStream({
163
+ pull: async (controller) => {
164
+ try {
165
+ const { done, value } = await events.next();
166
+ if (done) {
167
+ controller.enqueue(enc.encode("data: [DONE]\n\n"));
168
+ controller.close();
169
+ return;
170
+ }
171
+ controller.enqueue(enc.encode(`${value.id === null ? "" : `id: ${value.id}\n`}data: ${JSON.stringify(value.part)}\n\n`));
172
+ }
173
+ catch {
174
+ controller.enqueue(enc.encode(`data: ${JSON.stringify({ type: "error", errorText: "The stream was interrupted. Re-attach with Last-Event-ID." })}\n\n`));
175
+ controller.close();
176
+ }
177
+ },
178
+ cancel: () => {
179
+ this.close();
180
+ void events.return(undefined);
181
+ },
182
+ });
183
+ }
184
+ toResponse(init = {}) {
185
+ const headers = new Headers(init.headers);
186
+ for (const [k, v] of Object.entries(SSE_RESPONSE_HEADERS))
187
+ if (!headers.has(k))
188
+ headers.set(k, v);
189
+ headers.set("openlegion-run", this.run);
190
+ return new Response(this.toReadableStream(), { status: init.status ?? 200, statusText: init.statusText, headers });
191
+ }
192
+ }
@@ -0,0 +1,33 @@
1
+ import { type OpenLegionContext } from "./ol-signed.ts";
2
+ /**
3
+ * A webhook delivery as OpenLegion sends it: the body and the headers (`OpenLegion-Signature` with one
4
+ * `v1=` per secret, newest first, as during a rotation).
5
+ */
6
+ export declare function signWebhookForTest(input: {
7
+ payload: string | {
8
+ type?: string;
9
+ [key: string]: unknown;
10
+ };
11
+ secret: string | readonly string[];
12
+ /** Unix seconds. Default: now. */
13
+ timestamp?: number;
14
+ /** The `OpenLegion-Delivery` header: a `whd_…` id. Default: a random one. */
15
+ delivery?: string;
16
+ }): Promise<{
17
+ body: string;
18
+ headers: Record<string, string>;
19
+ }>;
20
+ /**
21
+ * The two `ol_signed` headers OpenLegion puts on a call to your connector. `context` fills in the rest
22
+ * with an org-level call's nulls; set `workspace`, `external_ref` and `action` for a tools/call (one without them is refused).
23
+ */
24
+ export declare function signOpenLegionRequestForTest(input: {
25
+ secret: string | readonly string[];
26
+ context?: Partial<Omit<OpenLegionContext, "iat">>;
27
+ body: string;
28
+ /** Unix seconds. Default: now. */
29
+ timestamp?: number;
30
+ }): Promise<{
31
+ "openlegion-context": string;
32
+ "openlegion-signature": string;
33
+ }>;
@@ -0,0 +1,40 @@
1
+ import { hmacHex, utf8 } from "./crypto.js";
2
+ import { encodeContext } from "./ol-signed.js";
3
+ const nowSeconds = () => Math.floor(Date.now() / 1000);
4
+ const list = (secret) => (typeof secret === "string" ? [secret] : secret);
5
+ const BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
6
+ const testDeliveryId = () => `whd_${Array.from(crypto.getRandomValues(new Uint8Array(22)), (b) => BASE62[b % 62]).join("")}`;
7
+ export async function signWebhookForTest(input) {
8
+ const body = typeof input.payload === "string" ? input.payload : JSON.stringify(input.payload);
9
+ const t = input.timestamp ?? nowSeconds();
10
+ const macs = await Promise.all(list(input.secret).map((s) => hmacHex(s, utf8(`${t}.${body}`))));
11
+ const type = typeof input.payload === "string" ? null : (input.payload.type ?? null);
12
+ return {
13
+ body,
14
+ headers: {
15
+ "content-type": "application/json",
16
+ "user-agent": "OpenLegion-Webhooks/1",
17
+ ...(type ? { "openlegion-event": type } : {}),
18
+ "openlegion-delivery": input.delivery ?? testDeliveryId(),
19
+ "openlegion-signature": [`t=${t}`, ...macs.map((m) => `v1=${m}`)].join(","),
20
+ },
21
+ };
22
+ }
23
+ export async function signOpenLegionRequestForTest(input) {
24
+ const t = input.timestamp ?? nowSeconds();
25
+ const context = encodeContext({
26
+ org: "org_test",
27
+ workspace: null,
28
+ external_ref: null,
29
+ agent: null,
30
+ run: null,
31
+ action: null,
32
+ subject: null,
33
+ livemode: false,
34
+ tainted: false,
35
+ ...input.context,
36
+ iat: t,
37
+ });
38
+ const macs = await Promise.all(list(input.secret).map((s) => hmacHex(s, utf8(`${t}.${context}.${input.body}`))));
39
+ return { "openlegion-context": context, "openlegion-signature": [`t=${t}`, ...macs.map((m) => `v1=${m}`)].join(",") };
40
+ }