@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,49 @@
1
+ import type { ChatTransport, UIMessage } from "ai";
2
+ import { type QueuedReason } from "../stream.ts";
3
+ export interface AgentChatTransportOptions {
4
+ /** The kit's chat route. Default "/api/openlegion/chat". */
5
+ api?: string;
6
+ /** The kit's runs route, for re-attaching. Default: `api` with its last segment replaced by "runs". */
7
+ runsApi?: string;
8
+ fetch?: typeof fetch;
9
+ /** While the message waits: its place in the queue and why it waits; both null once its run starts. */
10
+ onQueued?: (position: number | null, reason: QueuedReason | null) => void;
11
+ /** Wait before the 2nd and 3rd re-attach in a row with no progress: this, then twice this (ms). Default 500. */
12
+ reattachDelayMs?: number;
13
+ /**
14
+ * A look for the thread's running answer found none (204): the chat may read its history again. `lastMessageAt`:
15
+ * the route's `openlegion-last-message-at` (the thread's `last_message_at`, "" before its first message), or null
16
+ * from a route that does not say it.
17
+ */
18
+ onIdle?: (lastMessageAt: string | null) => void;
19
+ /** The run being followed was stopped (its stream said `abort`): by `stop`, or by anyone else who may. */
20
+ onStopped?: () => void;
21
+ }
22
+ /** The kit's transport: `useChat`'s, plus the two things a chat does beside a reply on its way. */
23
+ export interface AgentChatTransport extends ChatTransport<UIMessage> {
24
+ /**
25
+ * Send a message while a reply is on its way. It is posted at once, as a send is; the platform answers it
26
+ * after the current reply, and the chat follows that answer when its turn comes. Resolves to its run (null
27
+ * if the route named none); throws as a send does when it is refused or does not go.
28
+ */
29
+ sendWaiting(chatId: string, message: UIMessage): Promise<string | null>;
30
+ /**
31
+ * Stop the run this chat is following. Asked while a send's answer is not in yet, it waits for the run to be
32
+ * named and is sent then. False, with no request, when there is no run to stop. Throws when the stop is refused
33
+ * (`run_not_cancellable`) or does not go; the reply is still followed.
34
+ */
35
+ stop(chatId: string): Promise<boolean>;
36
+ /** The run of the last stream this chat followed (still named once it has ended), else null. */
37
+ followedRun(chatId: string): string | null;
38
+ /**
39
+ * The run a message of the person's sent through this transport started (by the message's id), once the route
40
+ * named it; else null. How the chat tells its own messages in the thread from another tab's (they keep its ids).
41
+ */
42
+ runOfSend(messageId: string): string | null;
43
+ /**
44
+ * The reply already drawn answered the messages sent while it was on its way: their run is not replayed when
45
+ * the thread is next found idle.
46
+ */
47
+ forgetWaiting(chatId: string): void;
48
+ }
49
+ export declare function createAgentChatTransport(opts?: AgentChatTransportOptions): AgentChatTransport;
@@ -0,0 +1,380 @@
1
+ import { limitOf } from "./limit-words.js";
2
+ import { parseSse } from "../stream.js";
3
+ import { AgentChatError } from "./errors.js";
4
+ const MAX_EMPTY_REATTACHES = 3;
5
+ const MAX_ERROR_BODY = 64 * 1024;
6
+ const RUN_RE = /^run_[0-9A-Za-z]{1,64}$/;
7
+ const QUEUED_REASONS = new Set(["thread_busy", "agent_busy", "workspace_busy", "agent_paused", "credit_wait"]);
8
+ async function failure(res, run = null) {
9
+ const text = (await res.text().catch(() => "")).slice(0, MAX_ERROR_BODY);
10
+ let env = {};
11
+ try {
12
+ const parsed = JSON.parse(text);
13
+ if (parsed && typeof parsed.error === "object" && parsed.error !== null)
14
+ env = parsed.error;
15
+ }
16
+ catch {
17
+ }
18
+ const type = typeof env["type"] === "string" ? env["type"] : null;
19
+ const message = typeof env["message"] === "string" ? env["message"] : `HTTP ${res.status}`;
20
+ const code = typeof env["code"] === "string" ? env["code"] : `http_${res.status}`;
21
+ return new AgentChatError(code, message, { status: res.status, type, run, displayMessage: type === "refusal" ? message : null, limit: type === "refusal" ? limitOf(env["limit"]) : null });
22
+ }
23
+ const sleep = (ms, signal) => ms <= 0
24
+ ? Promise.resolve()
25
+ : new Promise((resolve) => {
26
+ const t = setTimeout(resolve, ms);
27
+ signal?.addEventListener("abort", () => (clearTimeout(t), resolve()), { once: true });
28
+ });
29
+ export function createAgentChatTransport(opts = {}) {
30
+ const api = (opts.api ?? "/api/openlegion/chat").replace(/\/+$/, "");
31
+ const runsApi = (opts.runsApi ?? api.replace(/\/[^/]*$/, "/runs")).replace(/\/+$/, "");
32
+ const doFetch = opts.fetch ?? ((input, init) => globalThis.fetch(input, init));
33
+ const base = opts.reattachDelayMs ?? 500;
34
+ const interrupted = new Map();
35
+ const following = new Map();
36
+ const lastFollowed = new Map();
37
+ const readToEnd = new Map();
38
+ const sending = new Map();
39
+ const waited = new Map();
40
+ const sentRuns = new Map();
41
+ const sends = new Map();
42
+ let sendCount = 0;
43
+ const nextSend = new Map();
44
+ async function get(url, headers, signal) {
45
+ try {
46
+ return await doFetch(url, { method: "GET", headers: { accept: "text/event-stream", ...headers }, signal });
47
+ }
48
+ catch (err) {
49
+ if (signal?.aborted)
50
+ throw err;
51
+ throw new AgentChatError("network", `Could not reach ${url}.`, { cause: err });
52
+ }
53
+ }
54
+ function follow(first, run, chatId, signal, onEnd) {
55
+ let last = -1;
56
+ let queued = false;
57
+ let refused = false;
58
+ const out = [];
59
+ const emit = (part) => {
60
+ if (part.type === "error" && refused)
61
+ return;
62
+ if (part.type === "data-refusal")
63
+ refused = true;
64
+ if (part.type === "abort")
65
+ opts.onStopped?.();
66
+ if (part.type === "data-queued") {
67
+ const data = part.data;
68
+ const position = data?.position;
69
+ const reason = typeof data?.reason === "string" && QUEUED_REASONS.has(data.reason) ? data.reason : null;
70
+ queued = true;
71
+ opts.onQueued?.(typeof position === "number" ? position : 0, reason);
72
+ return;
73
+ }
74
+ if (queued) {
75
+ queued = false;
76
+ opts.onQueued?.(null, null);
77
+ }
78
+ out.push(part);
79
+ };
80
+ async function* parts() {
81
+ let res = first;
82
+ let empty = 0;
83
+ let reattaching = false;
84
+ for (;;) {
85
+ const before = last;
86
+ let held = null;
87
+ let done = false;
88
+ let stillWaiting = false;
89
+ try {
90
+ if (!res.body)
91
+ throw new TypeError("no body");
92
+ for await (const frame of parseSse(res.body, signal)) {
93
+ if (frame.data === "[DONE]") {
94
+ done = true;
95
+ break;
96
+ }
97
+ let part;
98
+ try {
99
+ part = JSON.parse(frame.data);
100
+ }
101
+ catch {
102
+ continue;
103
+ }
104
+ if (!part || typeof part !== "object" || typeof part.type !== "string")
105
+ continue;
106
+ if (part.type === "data-queued")
107
+ stillWaiting = true;
108
+ const id = frame.id !== null && /^\d{1,9}$/.test(frame.id) ? Number(frame.id) : null;
109
+ if (held) {
110
+ emit(held);
111
+ held = null;
112
+ }
113
+ if (id !== null) {
114
+ if (id <= last)
115
+ continue;
116
+ last = id;
117
+ emit(part);
118
+ }
119
+ else if (part.type === "error")
120
+ held = part;
121
+ else
122
+ emit(part);
123
+ yield* out.splice(0);
124
+ }
125
+ }
126
+ catch {
127
+ if (signal?.aborted)
128
+ return;
129
+ }
130
+ if (done) {
131
+ await res.body?.cancel().catch(() => undefined);
132
+ if (run)
133
+ readToEnd.set(chatId, new Set([...(readToEnd.get(chatId) ?? []), run]));
134
+ if (held)
135
+ emit(held);
136
+ yield* out.splice(0);
137
+ return;
138
+ }
139
+ if (signal?.aborted)
140
+ return;
141
+ if (reattaching)
142
+ empty = last > before ? 0 : stillWaiting && queued ? empty : empty + 1;
143
+ if (!run || empty >= MAX_EMPTY_REATTACHES) {
144
+ if (run)
145
+ interrupted.set(chatId, run);
146
+ throw new AgentChatError("stream_interrupted", run ? `The stream of ${run} was cut ${empty} times in a row with nothing new.` : "The stream was cut, and named no run to re-attach to.", { run });
147
+ }
148
+ await sleep(empty === 0 ? (stillWaiting ? base : 0) : base * 2 ** (empty - 1), signal);
149
+ if (signal?.aborted)
150
+ return;
151
+ reattaching = true;
152
+ try {
153
+ res = await get(`${runsApi}/${run}/stream`, last >= 0 ? { "last-event-id": String(last) } : {}, signal);
154
+ }
155
+ catch (err) {
156
+ if (signal?.aborted)
157
+ return;
158
+ res = new Response(null, { status: 200 });
159
+ void err;
160
+ continue;
161
+ }
162
+ if (!res.ok)
163
+ throw await failure(res, run);
164
+ }
165
+ }
166
+ if (run)
167
+ following.set(chatId, run);
168
+ if (run)
169
+ lastFollowed.set(chatId, run);
170
+ async function* followed() {
171
+ let failed = null;
172
+ try {
173
+ yield* parts();
174
+ }
175
+ catch (err) {
176
+ failed = err;
177
+ throw err;
178
+ }
179
+ finally {
180
+ if (run && following.get(chatId) === run)
181
+ following.delete(chatId);
182
+ onEnd?.(failed);
183
+ }
184
+ }
185
+ const it = followed();
186
+ return new ReadableStream({
187
+ async pull(controller) {
188
+ try {
189
+ const { done, value } = await it.next();
190
+ if (done)
191
+ controller.close();
192
+ else
193
+ controller.enqueue(value);
194
+ }
195
+ catch (err) {
196
+ controller.error(err);
197
+ }
198
+ },
199
+ cancel() {
200
+ if (run && following.get(chatId) === run)
201
+ following.delete(chatId);
202
+ onEnd?.(null);
203
+ void it.return(undefined);
204
+ },
205
+ });
206
+ }
207
+ function runOf(res) {
208
+ const run = res.headers.get("openlegion-run");
209
+ return run && RUN_RE.test(run) ? run : null;
210
+ }
211
+ async function post(chatId, message, signal) {
212
+ if (!message || message.role !== "user")
213
+ throw new AgentChatError("invalid_message", "The last message must be the user's.");
214
+ if (message.parts.some((p) => p.type === "file"))
215
+ throw new AgentChatError("not_supported", "Attachments are not supported yet.");
216
+ let res;
217
+ try {
218
+ res = await doFetch(api, {
219
+ method: "POST",
220
+ headers: { "content-type": "application/json", accept: "text/event-stream" },
221
+ body: JSON.stringify({ id: chatId, messages: [message], trigger: "submit-message" }),
222
+ signal,
223
+ });
224
+ }
225
+ catch (err) {
226
+ if (signal?.aborted)
227
+ throw err;
228
+ throw new AgentChatError("network", "Could not reach the chat route.", { cause: err });
229
+ }
230
+ if (!res.ok)
231
+ throw await failure(res);
232
+ return res;
233
+ }
234
+ return {
235
+ async sendMessages({ trigger, chatId, messageId, messages, abortSignal }) {
236
+ if (trigger !== "submit-message")
237
+ throw new AgentChatError("not_supported", "Regenerating an answer is not supported: send the message again.");
238
+ if (messageId !== undefined && messageId !== null)
239
+ throw new AgentChatError("not_supported", "Editing a sent message is not supported: send a new one.");
240
+ interrupted.delete(chatId);
241
+ sending.set(chatId, []);
242
+ let named;
243
+ let end;
244
+ const mine = { n: ++sendCount, open: true, run: new Promise((r) => (named = r)), ended: new Promise((r) => (end = r)) };
245
+ sends.set(chatId, mine);
246
+ for (const tell of nextSend.get(chatId) ?? [])
247
+ tell();
248
+ nextSend.delete(chatId);
249
+ const ended = (failed) => {
250
+ mine.open = false;
251
+ end(failed);
252
+ };
253
+ const answered = (run) => {
254
+ const stops = sending.get(chatId) ?? [];
255
+ sending.delete(chatId);
256
+ for (const tell of stops)
257
+ tell(run);
258
+ named(run);
259
+ };
260
+ let res;
261
+ try {
262
+ res = await post(chatId, messages[messages.length - 1], abortSignal);
263
+ }
264
+ catch (err) {
265
+ answered(null);
266
+ ended(err);
267
+ throw err;
268
+ }
269
+ const run = runOf(res);
270
+ const sent = messages[messages.length - 1];
271
+ if (run && sent)
272
+ sentRuns.set(sent.id, run);
273
+ const stream = follow(res, run, chatId, abortSignal, ended);
274
+ answered(run);
275
+ return stream;
276
+ },
277
+ async sendWaiting(chatId, message) {
278
+ const letGo = new AbortController();
279
+ const res = await post(chatId, message, letGo.signal);
280
+ await res.body?.cancel().catch(() => undefined);
281
+ letGo.abort();
282
+ const run = runOf(res);
283
+ if (run) {
284
+ waited.set(chatId, run);
285
+ sentRuns.set(message.id, run);
286
+ }
287
+ return run;
288
+ },
289
+ runOfSend(messageId) {
290
+ return sentRuns.get(messageId) ?? null;
291
+ },
292
+ followedRun(chatId) {
293
+ return lastFollowed.get(chatId) ?? null;
294
+ },
295
+ forgetWaiting(chatId) {
296
+ waited.delete(chatId);
297
+ },
298
+ async stop(chatId) {
299
+ let run = following.get(chatId) ?? null;
300
+ const stops = sending.get(chatId);
301
+ if (!run && stops)
302
+ run = await new Promise((tell) => stops.push(tell));
303
+ if (!run)
304
+ return false;
305
+ let res;
306
+ try {
307
+ res = await doFetch(`${runsApi}/${run}/cancel`, { method: "POST", headers: { accept: "application/json" } });
308
+ }
309
+ catch (err) {
310
+ throw new AgentChatError("network", "Could not reach the runs route.", { run, cause: err });
311
+ }
312
+ if (!res.ok)
313
+ throw await failure(res, run);
314
+ await res.body?.cancel().catch(() => undefined);
315
+ return true;
316
+ },
317
+ async reconnectToStream({ chatId, abortSignal }) {
318
+ const replay = interrupted.get(chatId);
319
+ if (!replay) {
320
+ const since = sends.get(chatId)?.n ?? 0;
321
+ const res = await get(`${api}/${encodeURIComponent(chatId)}/stream`, {}, abortSignal);
322
+ const missed = waited.get(chatId);
323
+ waited.delete(chatId);
324
+ let reply = missed ? undefined : sends.get(chatId);
325
+ if (reply && (reply.open || reply.n > since) && (res.status === 204 || (res.ok && runOf(res) !== null && runOf(res) === (await reply.run)))) {
326
+ await res.body?.cancel().catch(() => undefined);
327
+ const letGo = (until) => new Promise((done) => {
328
+ if (abortSignal?.aborted)
329
+ return done(null);
330
+ abortSignal?.addEventListener("abort", () => done(null), { once: true });
331
+ void until.then(done);
332
+ });
333
+ for (;;) {
334
+ const failed = await letGo(reply.ended);
335
+ if (failed === null || abortSignal?.aborted)
336
+ return null;
337
+ await letGo(new Promise((told) => nextSend.set(chatId, [...(nextSend.get(chatId) ?? []), told])));
338
+ if (abortSignal?.aborted)
339
+ return null;
340
+ reply = sends.get(chatId);
341
+ }
342
+ }
343
+ if (res.status === 204) {
344
+ if (!missed) {
345
+ opts.onIdle?.(res.headers.get("openlegion-last-message-at"));
346
+ return null;
347
+ }
348
+ const again = await get(`${runsApi}/${missed}/stream`, {}, abortSignal);
349
+ if (!again.ok)
350
+ throw await failure(again, missed);
351
+ return follow(again, missed, chatId, abortSignal);
352
+ }
353
+ if (!res.ok)
354
+ throw await failure(res);
355
+ const found = runOf(res);
356
+ if (found !== null && readToEnd.get(chatId)?.has(found)) {
357
+ await res.body?.cancel().catch(() => undefined);
358
+ return null;
359
+ }
360
+ return follow(res, found, chatId, abortSignal);
361
+ }
362
+ const stillInterrupted = (cause) => new AgentChatError("stream_interrupted", `Could not re-attach to ${replay}.`, { run: replay, cause });
363
+ let res;
364
+ try {
365
+ res = await get(`${runsApi}/${replay}/stream`, {}, abortSignal);
366
+ }
367
+ catch (err) {
368
+ if (abortSignal?.aborted)
369
+ throw err;
370
+ throw stillInterrupted(err);
371
+ }
372
+ if (res.status >= 500)
373
+ throw stillInterrupted(await failure(res, replay));
374
+ interrupted.delete(chatId);
375
+ if (!res.ok)
376
+ throw await failure(res, replay);
377
+ return follow(res, replay, chatId, abortSignal);
378
+ },
379
+ };
380
+ }
@@ -0,0 +1,155 @@
1
+ import { AgentKitError, type KitRequestOptions, type UseAgentKitOptions } from "./agent-kit.ts";
2
+ /** A connection as the kit's route answers it. */
3
+ export interface KitConnection {
4
+ object: "connection";
5
+ /** cxn_… */
6
+ id: string;
7
+ app: string;
8
+ status: "active" | "needs_reauth";
9
+ account: {
10
+ label: string | null;
11
+ };
12
+ /** agt_… ids that may use it; null: every agent the template allows. */
13
+ agents: string[] | null;
14
+ created: string;
15
+ last_used_at: string | null;
16
+ /** Where its tools come from: `custom` for a server your user added by its address. */
17
+ source?: string;
18
+ /** A server added by its address: its host, and `aggregator` when it reaches other apps through a third party. Else null. */
19
+ server?: {
20
+ host: string;
21
+ custody: "unknown" | "aggregator";
22
+ } | null;
23
+ }
24
+ /** Whether the workspace's people may add a server by its address, and how many they have (null: they may not). */
25
+ export interface KitCustomServers {
26
+ count: number;
27
+ max: number;
28
+ }
29
+ export type ConnectSessionStatus = "open" | "completed" | "cancelled" | "failed" | "expired";
30
+ /** One attempt to connect, as the kit's route answers it. `url` only on the answer to `connect()`. */
31
+ export interface KitConnectSession {
32
+ object: "connect_session";
33
+ /** cxs_… */
34
+ id: string;
35
+ app: string;
36
+ /** A server named by its address: its address and name. Null for a catalog app. */
37
+ server?: {
38
+ url: string;
39
+ name: string;
40
+ } | null;
41
+ status: ConnectSessionStatus;
42
+ failure_code: string | null;
43
+ /** cxn_…, once completed. */
44
+ connection: string | null;
45
+ expires_at: string;
46
+ /** Where to send the person, once: open it in a new window. */
47
+ url?: string | null;
48
+ }
49
+ /** An app the workspace's people may connect. */
50
+ export interface KitCatalogApp {
51
+ object: "catalog_entry";
52
+ id: string;
53
+ name: string;
54
+ description: string;
55
+ categories: string[];
56
+ /** A logo OpenLegion hosts, or null: draw the name's initial. */
57
+ logo: string | null;
58
+ auth: {
59
+ kind: "oauth2" | "api_key" | "none";
60
+ };
61
+ }
62
+ /**
63
+ * A refusal to start connecting that only YOUR setup can fix, so no retry by the person ever will (otherwise the
64
+ * window opens and then closes). From POST /connect_sessions: 400 `parameter_invalid` on `return_url` (the page's origin
65
+ * isn't one of your organization's return origins, or isn't https), on `app` (no such catalog app) or on `server`
66
+ * (both or neither of app and server), `app_not_enabled` (the workspace's template version doesn't list the app),
67
+ * `app_needs_oauth_app`. From the kit's own route: `invalid_app`, `invalid_agent`, `invalid_body` (what your page
68
+ * passed), and 403 `cross_origin`. NOT setup: what the person typed (`invalid_server`, `parameter_invalid` on
69
+ * `server.url`), their role (403 `insufficient_role`), the server limit (409), 429, 5xx and the network.
70
+ */
71
+ export declare function isSetupRefusal(err: unknown): err is AgentKitError;
72
+ /**
73
+ * The developer's line for a setup refusal: the code, the engine's own words, and the fix. Never the key (the
74
+ * browser has none) and nothing the person typed (their refusals are never setup ones).
75
+ */
76
+ export declare function setupRefusalMessage(err: AgentKitError, pageOrigin: string | null): string;
77
+ /** Tell the developer (console.error, once per refusal) when `err` is a setup refusal. True when it was one. */
78
+ export declare function reportSetupRefusal(err: unknown): boolean;
79
+ /** The channel the return page posts on: the same name `createHandler` uses for this base path. */
80
+ export declare function connectChannelName(api?: string): string;
81
+ /** What a session watch listens to besides its own timer: the return page's channel and the window's focus. */
82
+ interface WatchSources {
83
+ channel?: {
84
+ addEventListener(type: "message", fn: (e: MessageEvent) => void): void;
85
+ close(): void;
86
+ } | null;
87
+ focus?: {
88
+ addEventListener(type: "focus", fn: () => void): void;
89
+ removeEventListener(type: "focus", fn: () => void): void;
90
+ } | null;
91
+ }
92
+ /**
93
+ * Read a session from the server until it is no longer open: every `intervalMs`, on the window's focus, and when
94
+ * the return page posts this session's id. `onChange` gets each read. A message's own status is never used.
95
+ * Returns stop().
96
+ */
97
+ export declare function watchConnectSession(id: string, opts: KitRequestOptions & {
98
+ onChange: (s: KitConnectSession) => void;
99
+ onError?: (err: Error) => void;
100
+ intervalMs?: number;
101
+ immediate?: boolean;
102
+ } & WatchSources): () => void;
103
+ /**
104
+ * The workspace's connections (one app's with `app`), with `connect(app, {agent})` and `disconnect(id)`.
105
+ * `connect` answers the session with its `url`: open that in a new window from the click itself (a window opened
106
+ * later is blocked). `session` then follows it until it ends; a completed one reloads the list. Every
107
+ * `useConnections` on the page hears a connect that completed and a disconnect, and reads again: a catalog and a
108
+ * connections list side by side agree at once.
109
+ */
110
+ export declare function useConnections(opts?: UseAgentKitOptions & {
111
+ app?: string | undefined;
112
+ enabled?: boolean;
113
+ }): {
114
+ connections: KitConnection[] | null;
115
+ session: KitConnectSession | null;
116
+ error: Error | null;
117
+ loading: boolean;
118
+ refresh: () => Promise<void>;
119
+ /**
120
+ * Start connecting `app`; with `agent`, the connection is open to that agent (and stays open to any it was).
121
+ * With `returnPath` (redirect mode), the hosted page sends the person back to that path on this page's origin.
122
+ */
123
+ connect: (app: string, o?: {
124
+ agent?: string | null;
125
+ returnPath?: string;
126
+ }) => Promise<KitConnectSession>;
127
+ /**
128
+ * Start adding a server your user named by its address: `{url, name?}`. Answers the session with
129
+ * its `url`, as `connect` does; a server is never connected at once (the page says it hasn't been checked).
130
+ */
131
+ connectServer: (server: {
132
+ url: string;
133
+ name?: string;
134
+ }, o?: {
135
+ agent?: string | null;
136
+ }) => Promise<KitConnectSession>;
137
+ /** Follow a session by id (a page the hosted page sent back here): its status is read from the server. */
138
+ resume: (id: string) => void;
139
+ disconnect: (id: string) => Promise<void>;
140
+ };
141
+ /** The apps this workspace's people may connect, filtered on the page by `search` (name and description). */
142
+ export declare function filterCatalog(apps: readonly KitCatalogApp[], search: string | undefined): KitCatalogApp[];
143
+ export declare function useCatalog(opts?: UseAgentKitOptions & {
144
+ category?: string | undefined;
145
+ search?: string | undefined;
146
+ enabled?: boolean;
147
+ }): {
148
+ apps: KitCatalogApp[] | null;
149
+ /** Whether your user may add a server by its address, and how many they have: null when they may not; undefined before the first read. */
150
+ customServers: KitCustomServers | null | undefined;
151
+ error: Error | null;
152
+ loading: boolean;
153
+ refresh: () => Promise<void>;
154
+ };
155
+ export {};