@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,279 @@
1
+ /**
2
+ * THE KIT ROUTE CODES: every `error.code` the kit's own routes answer, once, with what it means and what to do.
3
+ *
4
+ * These are the handler's (`createHandler`, `openlegion()` for Next, and the tool server), answered by YOUR
5
+ * server, in its small envelope `{error: {code, message}}`: to your own browser on the chat, vault, agent and
6
+ * schedule routes, and to OpenLegion on the signed ones (webhooks, the template, the tool server). They are
7
+ * not the Platform API's error catalogue (https://platform.openlegion.ai/docs/errors). When the API refuses a
8
+ * person's request (a 4xx such as `insufficient_role` or `schedule_limit_reached`), the routes pass that
9
+ * code on as the API answered it, with its `type` and `param`, and the catalogue documents it.
10
+ *
11
+ * `kit-codes.test.ts` holds that every code the routes answer is here, with its status, and nothing here is
12
+ * stale. Wording: `next` is for you, the developer, never for your end user.
13
+ */
14
+ /** Which routes answer it: your browser's (chat, vault, agents, schedules), or the signed ones OpenLegion calls. */
15
+ export type KitRouteKind = "browser" | "signed";
16
+ export interface KitRouteCodeDoc {
17
+ where: readonly KitRouteKind[];
18
+ /** The HTTP statuses it is answered with. */
19
+ status: readonly number[];
20
+ /** What happened, in one line. */
21
+ meaning: string;
22
+ /** What to do next. */
23
+ next: string;
24
+ }
25
+ export declare const KIT_ROUTE_CODES: {
26
+ readonly unauthorized: {
27
+ readonly where: readonly ["browser"];
28
+ readonly status: readonly [401];
29
+ readonly meaning: "Your resolve found no signed-in person for this request.";
30
+ readonly next: "Sign the person in before showing the kit.";
31
+ };
32
+ readonly cross_origin: {
33
+ readonly where: readonly ["browser"];
34
+ readonly status: readonly [403];
35
+ readonly meaning: "The browser call came from an origin the handler doesn't allow.";
36
+ readonly next: "Call the routes from your own site, or add the origin to allowedOrigins.";
37
+ };
38
+ readonly resolve_failed: {
39
+ readonly where: readonly ["browser"];
40
+ readonly status: readonly [500];
41
+ readonly meaning: "Your resolve threw, or answered without a workspace id (ws_…).";
42
+ readonly next: "Fix resolve: it answers { workspace: \"ws_…\" } or null, and the error went to onError.";
43
+ };
44
+ readonly agent_unavailable: {
45
+ readonly where: readonly ["browser"];
46
+ readonly status: readonly [502];
47
+ readonly meaning: "OpenLegion refused or failed the call your server made for this route: your key was refused, or the API failed. It says nothing about the agent itself: a paused agent is agent_paused, passed on with its own status. The reason went to onError.";
48
+ readonly next: "Read onError's reason: a wrong or revoked key (OPENLEGION_API_KEY, or the client you passed), or retry later.";
49
+ };
50
+ readonly invalid_thread: {
51
+ readonly where: readonly ["browser"];
52
+ readonly status: readonly [400];
53
+ readonly meaning: "The thread id isn't a thread id (thr_…).";
54
+ readonly next: "Pass the thread's id: useChat({ id }), or <AgentChat threadId>.";
55
+ };
56
+ readonly invalid_run: {
57
+ readonly where: readonly ["browser"];
58
+ readonly status: readonly [400];
59
+ readonly meaning: "The run id in the path isn't a run id (run_…).";
60
+ readonly next: "Use the run id the chat answered with, or the run of a message in the thread's history.";
61
+ };
62
+ readonly invalid_before: {
63
+ readonly where: readonly ["browser"];
64
+ readonly status: readonly [400];
65
+ readonly meaning: "GET /chat/{thread}/messages's before isn't a message id (msg_…).";
66
+ readonly next: "Let <AgentChat> ask it: it passes the oldest message it shows, then the next_before the route answered.";
67
+ };
68
+ readonly invalid_trigger: {
69
+ readonly where: readonly ["browser"];
70
+ readonly status: readonly [400];
71
+ readonly meaning: "The chat request's trigger isn't submit-message.";
72
+ readonly next: "Send messages with useChat's sendMessage, or <AgentChat>.";
73
+ };
74
+ readonly invalid_message: {
75
+ readonly where: readonly ["browser"];
76
+ readonly status: readonly [400];
77
+ readonly meaning: "The chat message isn't one the route can send (the message says why).";
78
+ readonly next: "Send one person's message with text parts, as useChat does.";
79
+ };
80
+ readonly not_supported: {
81
+ readonly where: readonly ["browser"];
82
+ readonly status: readonly [400];
83
+ readonly meaning: "The chat asked to regenerate an answer or to edit a sent message, which the kit doesn't do yet.";
84
+ readonly next: "Send a new message instead.";
85
+ };
86
+ readonly invalid_vault_item: {
87
+ readonly where: readonly ["browser"];
88
+ readonly status: readonly [400];
89
+ readonly meaning: "The secure form's item isn't one the vault takes (the message says why).";
90
+ readonly next: "Send it from <VaultSecretForm>, which sends the right shape.";
91
+ };
92
+ readonly invalid_vault_query: {
93
+ readonly where: readonly ["browser"];
94
+ readonly status: readonly [400];
95
+ readonly meaning: "GET /vault needs the thread (thr_…), the message (msg_…) and a vault name.";
96
+ readonly next: "Let <AgentChat> ask it: it reads the form's own message from the thread's history.";
97
+ };
98
+ readonly vault_kind_mismatch: {
99
+ readonly where: readonly ["browser"];
100
+ readonly status: readonly [409];
101
+ readonly meaning: "A vault item with this name is already saved as another kind.";
102
+ readonly next: "Ask the agent to use another name.";
103
+ };
104
+ readonly vault_ask_missing: {
105
+ readonly where: readonly ["browser"];
106
+ readonly status: readonly [409];
107
+ readonly meaning: "The secure form answers a reply drawn live, and the conversation's newest 100 messages have no ask for this item yet.";
108
+ readonly next: "Save again in a moment, once the reply is stored.";
109
+ };
110
+ readonly model_tier_not_allowed: {
111
+ readonly where: readonly ["browser"];
112
+ readonly status: readonly [403];
113
+ readonly meaning: "A save or create named a model preset your allowModelTier said no to for this person (or threw for). The API was not called.";
114
+ readonly next: "Nothing, if your plans meant it: <AgentEditor> offers only the presets allowModelTier allows, so this is a race (the plan changed after the form was drawn) or a page of your own sending another preset. A throw went to onError.";
115
+ };
116
+ readonly invalid_agent: {
117
+ readonly where: readonly ["browser"];
118
+ readonly status: readonly [400];
119
+ readonly meaning: "The agent id in the path or the body isn't an agent id (agt_…).";
120
+ readonly next: "Pass an id from the agents list (useAgents).";
121
+ };
122
+ readonly invalid_schedule: {
123
+ readonly where: readonly ["browser"];
124
+ readonly status: readonly [400];
125
+ readonly meaning: "The schedule id in the path isn't a schedule id (sch_…).";
126
+ readonly next: "Pass an id from the schedules list (useSchedules).";
127
+ };
128
+ readonly invalid_app: {
129
+ readonly where: readonly ["browser"];
130
+ readonly status: readonly [400];
131
+ readonly meaning: "The app isn't a catalog app id (lower case, such as google).";
132
+ readonly next: "Pass an app id from the catalog (useCatalog), or the app an agent asked for.";
133
+ };
134
+ readonly invalid_connection: {
135
+ readonly where: readonly ["browser"];
136
+ readonly status: readonly [400];
137
+ readonly meaning: "The connection id in the path isn't a connection id (cxn_…).";
138
+ readonly next: "Pass an id from the connections list (useConnections).";
139
+ };
140
+ readonly invalid_server: {
141
+ readonly where: readonly ["browser"];
142
+ readonly status: readonly [400];
143
+ readonly meaning: "The server to add isn't {url, name?} with an https url of at most 2048 characters and a name of 1 to 80 characters.";
144
+ readonly next: "Send {server: {url: \"https://…\", name?}} alone, as <AddServerForm> does (useConnections().connectServer).";
145
+ };
146
+ readonly invalid_connect_session: {
147
+ readonly where: readonly ["browser"];
148
+ readonly status: readonly [400];
149
+ readonly meaning: "The connect session id in the path isn't one (cxs_…).";
150
+ readonly next: "Pass the id connect() answered (useConnections).";
151
+ };
152
+ readonly invalid_vendor: {
153
+ readonly where: readonly ["browser"];
154
+ readonly status: readonly [400];
155
+ readonly meaning: "The vendor in the model key's path isn't anthropic or openai.";
156
+ readonly next: "Pass the vendor of the saved key (useModelKeys).";
157
+ };
158
+ readonly invalid_approval: {
159
+ readonly where: readonly ["browser"];
160
+ readonly status: readonly [400];
161
+ readonly meaning: "The approval id in the path isn't an approval id (apr_…).";
162
+ readonly next: "Use the approval id of a held tool call in the chat (its output's approval).";
163
+ };
164
+ readonly invalid_decision: {
165
+ readonly where: readonly ["browser"];
166
+ readonly status: readonly [400];
167
+ readonly meaning: "The decision isn't approve or reject, or its action_hash isn't a string or null.";
168
+ readonly next: "Send {decision: \"approve\" | \"reject\", action_hash} with the card's action_hash.";
169
+ };
170
+ readonly insufficient_role: {
171
+ readonly where: readonly ["browser"];
172
+ readonly status: readonly [403];
173
+ readonly meaning: "The person resolve() answered may not decide this approval, or resolve answered no subject. A member decides only what their own conversation asked for, and not a tool whose approvals the template keeps for admins. Also a member's vault save over an item someone else saved (the form says so).";
174
+ readonly next: "Return the person's subject from resolve. An owner or admin decides every approval, and adds a site to any vault item: give a user that role in the workspace if they should.";
175
+ };
176
+ readonly invalid_body: {
177
+ readonly where: readonly ["browser", "signed"];
178
+ readonly status: readonly [400];
179
+ readonly meaning: "The body isn't JSON, isn't an object, or isn't the shape the route takes (the message says what).";
180
+ readonly next: "Send what the message asks for. The kit's hooks and components, and OpenLegion's own calls, send the right shape.";
181
+ };
182
+ readonly invalid_file_name: {
183
+ readonly where: readonly ["browser"];
184
+ readonly status: readonly [400];
185
+ readonly meaning: "An upload's name is empty or over 200 characters.";
186
+ readonly next: "Send the file's own name: <AgentChat> does.";
187
+ };
188
+ readonly invalid_file_type: {
189
+ readonly where: readonly ["browser"];
190
+ readonly status: readonly [400];
191
+ readonly meaning: "An upload's Content-Type doesn't name a type.";
192
+ readonly next: "Send the file's type as Content-Type (the browser's File.type); OpenLegion reads the type from the bytes.";
193
+ };
194
+ readonly invalid_artifact: {
195
+ readonly where: readonly ["browser"];
196
+ readonly status: readonly [400];
197
+ readonly meaning: "The artifact id in the path isn't an artifact id (art_…).";
198
+ readonly next: "Use an id from GET {basePath}/artifacts?thread=….";
199
+ };
200
+ readonly preview_not_text: {
201
+ readonly where: readonly ["browser"];
202
+ readonly status: readonly [415];
203
+ readonly meaning: "The file isn't Markdown or plain text, so it has no text preview.";
204
+ readonly next: "Offer the download link instead.";
205
+ };
206
+ readonly preview_too_large: {
207
+ readonly where: readonly ["browser"];
208
+ readonly status: readonly [413];
209
+ readonly meaning: "The file is over 256 KB, the most a text preview shows.";
210
+ readonly next: "Offer the download link instead.";
211
+ };
212
+ readonly download_unavailable: {
213
+ readonly where: readonly ["browser"];
214
+ readonly status: readonly [503];
215
+ readonly meaning: "OpenLegion could not make a download link for the file just now.";
216
+ readonly next: "Try the download again in a moment.";
217
+ };
218
+ readonly body_too_large: {
219
+ readonly where: readonly ["browser", "signed"];
220
+ readonly status: readonly [413];
221
+ readonly meaning: "The body is over the route's limit.";
222
+ readonly next: "Send less: the message says the limit.";
223
+ };
224
+ readonly method_not_allowed: {
225
+ readonly where: readonly ["browser", "signed"];
226
+ readonly status: readonly [405];
227
+ readonly meaning: "The route doesn't answer this HTTP method.";
228
+ readonly next: "Use the method the message names.";
229
+ };
230
+ readonly resource_missing: {
231
+ readonly where: readonly ["browser", "signed"];
232
+ readonly status: readonly [404];
233
+ readonly meaning: "No kit route answers at this path, or the browser routes have no resolve to serve them.";
234
+ readonly next: "Check that basePath matches where you mounted the handler, and pass resolve for the chat, vault, agent and schedule routes.";
235
+ };
236
+ readonly signature_invalid: {
237
+ readonly where: readonly ["signed"];
238
+ readonly status: readonly [400, 401];
239
+ readonly meaning: "A call that must be signed by OpenLegion didn't verify (the reason field says why).";
240
+ readonly next: "If you didn't send it, nothing to do. If OpenLegion's own calls fail, check the secret matches the console's (OPENLEGION_WEBHOOK_SECRET or OPENLEGION_CONNECTOR_SECRET).";
241
+ };
242
+ readonly not_configured: {
243
+ readonly where: readonly ["signed"];
244
+ readonly status: readonly [500];
245
+ readonly meaning: "A signed route has no secret to verify with.";
246
+ readonly next: "Set OPENLEGION_WEBHOOK_SECRET or OPENLEGION_CONNECTOR_SECRET, or pass webhookSecret or connectorSecret to createHandler.";
247
+ };
248
+ readonly handler_failed: {
249
+ readonly where: readonly ["signed"];
250
+ readonly status: readonly [500];
251
+ readonly meaning: "Your webhook handler threw, so the delivery wasn't acknowledged.";
252
+ readonly next: "Fix the handler (the error went to onError); OpenLegion retries the delivery.";
253
+ };
254
+ readonly no_template: {
255
+ readonly where: readonly ["signed"];
256
+ readonly status: readonly [404];
257
+ readonly meaning: "OpenLegion asked for your template, but the handler has none.";
258
+ readonly next: "Pass template to createHandler.";
259
+ };
260
+ readonly invalid_connector: {
261
+ readonly where: readonly ["signed"];
262
+ readonly status: readonly [400];
263
+ readonly meaning: "The template request's connector isn't {id, slug}, or the template's tools don't fit it (the message says what).";
264
+ readonly next: "Name the connector that serves the tools as {id, slug}.";
265
+ };
266
+ readonly connector_required: {
267
+ readonly where: readonly ["signed"];
268
+ readonly status: readonly [400];
269
+ readonly meaning: "The template has tools, but the template request named no connector to serve them.";
270
+ readonly next: "Name the connector that serves them ({connector: {id, slug}}).";
271
+ };
272
+ readonly template_failed: {
273
+ readonly where: readonly ["signed"];
274
+ readonly status: readonly [500];
275
+ readonly meaning: "Building your template's definition threw.";
276
+ readonly next: "Fix the template: the error went to onError.";
277
+ };
278
+ };
279
+ export type KitRouteCode = keyof typeof KIT_ROUTE_CODES;
@@ -0,0 +1,44 @@
1
+ export const KIT_ROUTE_CODES = {
2
+ unauthorized: { where: ["browser"], status: [401], meaning: "Your resolve found no signed-in person for this request.", next: "Sign the person in before showing the kit." },
3
+ cross_origin: { where: ["browser"], status: [403], meaning: "The browser call came from an origin the handler doesn't allow.", next: "Call the routes from your own site, or add the origin to allowedOrigins." },
4
+ resolve_failed: { where: ["browser"], status: [500], meaning: "Your resolve threw, or answered without a workspace id (ws_…).", next: "Fix resolve: it answers { workspace: \"ws_…\" } or null, and the error went to onError." },
5
+ agent_unavailable: { where: ["browser"], status: [502], meaning: "OpenLegion refused or failed the call your server made for this route: your key was refused, or the API failed. It says nothing about the agent itself: a paused agent is agent_paused, passed on with its own status. The reason went to onError.", next: "Read onError's reason: a wrong or revoked key (OPENLEGION_API_KEY, or the client you passed), or retry later." },
6
+ invalid_thread: { where: ["browser"], status: [400], meaning: "The thread id isn't a thread id (thr_…).", next: "Pass the thread's id: useChat({ id }), or <AgentChat threadId>." },
7
+ invalid_run: { where: ["browser"], status: [400], meaning: "The run id in the path isn't a run id (run_…).", next: "Use the run id the chat answered with, or the run of a message in the thread's history." },
8
+ invalid_before: { where: ["browser"], status: [400], meaning: "GET /chat/{thread}/messages's before isn't a message id (msg_…).", next: "Let <AgentChat> ask it: it passes the oldest message it shows, then the next_before the route answered." },
9
+ invalid_trigger: { where: ["browser"], status: [400], meaning: "The chat request's trigger isn't submit-message.", next: "Send messages with useChat's sendMessage, or <AgentChat>." },
10
+ invalid_message: { where: ["browser"], status: [400], meaning: "The chat message isn't one the route can send (the message says why).", next: "Send one person's message with text parts, as useChat does." },
11
+ not_supported: { where: ["browser"], status: [400], meaning: "The chat asked to regenerate an answer or to edit a sent message, which the kit doesn't do yet.", next: "Send a new message instead." },
12
+ invalid_vault_item: { where: ["browser"], status: [400], meaning: "The secure form's item isn't one the vault takes (the message says why).", next: "Send it from <VaultSecretForm>, which sends the right shape." },
13
+ invalid_vault_query: { where: ["browser"], status: [400], meaning: "GET /vault needs the thread (thr_…), the message (msg_…) and a vault name.", next: "Let <AgentChat> ask it: it reads the form's own message from the thread's history." },
14
+ vault_kind_mismatch: { where: ["browser"], status: [409], meaning: "A vault item with this name is already saved as another kind.", next: "Ask the agent to use another name." },
15
+ vault_ask_missing: { where: ["browser"], status: [409], meaning: "The secure form answers a reply drawn live, and the conversation's newest 100 messages have no ask for this item yet.", next: "Save again in a moment, once the reply is stored." },
16
+ model_tier_not_allowed: { where: ["browser"], status: [403], meaning: "A save or create named a model preset your allowModelTier said no to for this person (or threw for). The API was not called.", next: "Nothing, if your plans meant it: <AgentEditor> offers only the presets allowModelTier allows, so this is a race (the plan changed after the form was drawn) or a page of your own sending another preset. A throw went to onError." },
17
+ invalid_agent: { where: ["browser"], status: [400], meaning: "The agent id in the path or the body isn't an agent id (agt_…).", next: "Pass an id from the agents list (useAgents)." },
18
+ invalid_schedule: { where: ["browser"], status: [400], meaning: "The schedule id in the path isn't a schedule id (sch_…).", next: "Pass an id from the schedules list (useSchedules)." },
19
+ invalid_app: { where: ["browser"], status: [400], meaning: "The app isn't a catalog app id (lower case, such as google).", next: "Pass an app id from the catalog (useCatalog), or the app an agent asked for." },
20
+ invalid_connection: { where: ["browser"], status: [400], meaning: "The connection id in the path isn't a connection id (cxn_…).", next: "Pass an id from the connections list (useConnections)." },
21
+ invalid_server: { where: ["browser"], status: [400], meaning: "The server to add isn't {url, name?} with an https url of at most 2048 characters and a name of 1 to 80 characters.", next: "Send {server: {url: \"https://…\", name?}} alone, as <AddServerForm> does (useConnections().connectServer)." },
22
+ invalid_connect_session: { where: ["browser"], status: [400], meaning: "The connect session id in the path isn't one (cxs_…).", next: "Pass the id connect() answered (useConnections)." },
23
+ invalid_vendor: { where: ["browser"], status: [400], meaning: "The vendor in the model key's path isn't anthropic or openai.", next: "Pass the vendor of the saved key (useModelKeys)." },
24
+ invalid_approval: { where: ["browser"], status: [400], meaning: "The approval id in the path isn't an approval id (apr_…).", next: "Use the approval id of a held tool call in the chat (its output's approval)." },
25
+ invalid_decision: { where: ["browser"], status: [400], meaning: "The decision isn't approve or reject, or its action_hash isn't a string or null.", next: "Send {decision: \"approve\" | \"reject\", action_hash} with the card's action_hash." },
26
+ insufficient_role: { where: ["browser"], status: [403], meaning: "The person resolve() answered may not decide this approval, or resolve answered no subject. A member decides only what their own conversation asked for, and not a tool whose approvals the template keeps for admins. Also a member's vault save over an item someone else saved (the form says so).", next: "Return the person's subject from resolve. An owner or admin decides every approval, and adds a site to any vault item: give a user that role in the workspace if they should." },
27
+ invalid_body: { where: ["browser", "signed"], status: [400], meaning: "The body isn't JSON, isn't an object, or isn't the shape the route takes (the message says what).", next: "Send what the message asks for. The kit's hooks and components, and OpenLegion's own calls, send the right shape." },
28
+ invalid_file_name: { where: ["browser"], status: [400], meaning: "An upload's name is empty or over 200 characters.", next: "Send the file's own name: <AgentChat> does." },
29
+ invalid_file_type: { where: ["browser"], status: [400], meaning: "An upload's Content-Type doesn't name a type.", next: "Send the file's type as Content-Type (the browser's File.type); OpenLegion reads the type from the bytes." },
30
+ invalid_artifact: { where: ["browser"], status: [400], meaning: "The artifact id in the path isn't an artifact id (art_…).", next: "Use an id from GET {basePath}/artifacts?thread=…." },
31
+ preview_not_text: { where: ["browser"], status: [415], meaning: "The file isn't Markdown or plain text, so it has no text preview.", next: "Offer the download link instead." },
32
+ preview_too_large: { where: ["browser"], status: [413], meaning: "The file is over 256 KB, the most a text preview shows.", next: "Offer the download link instead." },
33
+ download_unavailable: { where: ["browser"], status: [503], meaning: "OpenLegion could not make a download link for the file just now.", next: "Try the download again in a moment." },
34
+ body_too_large: { where: ["browser", "signed"], status: [413], meaning: "The body is over the route's limit.", next: "Send less: the message says the limit." },
35
+ method_not_allowed: { where: ["browser", "signed"], status: [405], meaning: "The route doesn't answer this HTTP method.", next: "Use the method the message names." },
36
+ resource_missing: { where: ["browser", "signed"], status: [404], meaning: "No kit route answers at this path, or the browser routes have no resolve to serve them.", next: "Check that basePath matches where you mounted the handler, and pass resolve for the chat, vault, agent and schedule routes." },
37
+ signature_invalid: { where: ["signed"], status: [400, 401], meaning: "A call that must be signed by OpenLegion didn't verify (the reason field says why).", next: "If you didn't send it, nothing to do. If OpenLegion's own calls fail, check the secret matches the console's (OPENLEGION_WEBHOOK_SECRET or OPENLEGION_CONNECTOR_SECRET)." },
38
+ not_configured: { where: ["signed"], status: [500], meaning: "A signed route has no secret to verify with.", next: "Set OPENLEGION_WEBHOOK_SECRET or OPENLEGION_CONNECTOR_SECRET, or pass webhookSecret or connectorSecret to createHandler." },
39
+ handler_failed: { where: ["signed"], status: [500], meaning: "Your webhook handler threw, so the delivery wasn't acknowledged.", next: "Fix the handler (the error went to onError); OpenLegion retries the delivery." },
40
+ no_template: { where: ["signed"], status: [404], meaning: "OpenLegion asked for your template, but the handler has none.", next: "Pass template to createHandler." },
41
+ invalid_connector: { where: ["signed"], status: [400], meaning: "The template request's connector isn't {id, slug}, or the template's tools don't fit it (the message says what).", next: "Name the connector that serves the tools as {id, slug}." },
42
+ connector_required: { where: ["signed"], status: [400], meaning: "The template has tools, but the template request named no connector to serve them.", next: "Name the connector that serves them ({connector: {id, slug}})." },
43
+ template_failed: { where: ["signed"], status: [500], meaning: "Building your template's definition threw.", next: "Fix the template: the error went to onError." },
44
+ };
@@ -0,0 +1,21 @@
1
+ import type { KitRouteContext } from "./kit-agents.ts";
2
+ /** The channel the return page posts on and `useConnections` listens on: one per mount point. */
3
+ export declare function connectChannelName(basePath: string): string;
4
+ /** A server the person named: `{url, name?}` from the body, trimmed, or why not. The API checks the address itself. */
5
+ export declare function serverOf(v: unknown): {
6
+ url: string;
7
+ name?: string;
8
+ } | {
9
+ problem: string;
10
+ };
11
+ /** The return page: fixed words, one nonce'd script, nothing from the query in the document. */
12
+ export declare function connectReturnPage(channel: string): Response;
13
+ export interface KitConnectionOptions {
14
+ basePath: string;
15
+ /** The URL the hosted page sends the person back to. Default: the calling page's origin + `{basePath}/connect_return`. */
16
+ connectReturnUrl?: string | undefined;
17
+ }
18
+ /** The routes, as one dispatcher: the response for `route`, or null when the route isn't one of these. */
19
+ export declare function createKitConnectionRoutes<Scope extends {
20
+ workspace: string;
21
+ }>(ctx: KitRouteContext<Scope>, opts: KitConnectionOptions): (route: string, req: Request) => Promise<Response | null>;
@@ -0,0 +1,189 @@
1
+ import { OpenLegionError } from "./errors.js";
2
+ const APP_ID = /^[a-z][a-z0-9-]{1,47}$/;
3
+ const AGENT_ID = /^agt_[0-9A-Za-z]{1,64}$/;
4
+ const CONNECTION_ID = /^cxn_[0-9A-Za-z]{1,64}$/;
5
+ const SESSION_ID = /^cxs_[0-9A-Za-z]{1,64}$/;
6
+ const SESSION_STATUSES = ["open", "completed", "cancelled", "failed", "expired"];
7
+ const MAX_BODY_BYTES = 4 * 1024;
8
+ const MAX_SERVER_URL = 2048;
9
+ const MAX_SERVER_NAME = 80;
10
+ const RETURN_PATH = /^\/(?![/\\])[^\s\\]{0,2000}$/;
11
+ export function connectChannelName(basePath) {
12
+ return `openlegion-connect:${basePath.replace(/\/+$/, "")}`;
13
+ }
14
+ function connectionForBrowser(c) {
15
+ return {
16
+ object: "connection",
17
+ id: c.id,
18
+ app: c.app,
19
+ source: c.source,
20
+ status: c.status,
21
+ account: { label: c.account.label },
22
+ agents: c.agents,
23
+ created: c.created,
24
+ last_used_at: c.last_used_at,
25
+ server: c.server ? { host: c.server.host, custody: c.server.custody } : null,
26
+ };
27
+ }
28
+ export function serverOf(v) {
29
+ if (!v || typeof v !== "object" || Array.isArray(v))
30
+ return { problem: "server is {url, name?}: the MCP server's https address, and what to call it." };
31
+ const o = v;
32
+ const url = typeof o["url"] === "string" ? o["url"].trim() : null;
33
+ if (url === null || !url.startsWith("https://") || url.length > MAX_SERVER_URL)
34
+ return { problem: `server.url is the server's https address, at most ${MAX_SERVER_URL} characters.` };
35
+ if (o["name"] === undefined || o["name"] === null)
36
+ return { url };
37
+ const name = typeof o["name"] === "string" ? o["name"].trim() : "";
38
+ if (name.length < 1 || name.length > MAX_SERVER_NAME)
39
+ return { problem: `server.name is 1 to ${MAX_SERVER_NAME} characters, or left out (the address's host).` };
40
+ return { url, name };
41
+ }
42
+ function sessionForBrowser(s, withUrl) {
43
+ return {
44
+ object: "connect_session",
45
+ id: s.id,
46
+ app: s.app,
47
+ server: s.server ? { url: s.server.url, name: s.server.name } : null,
48
+ status: s.status,
49
+ failure_code: s.failure_code,
50
+ connection: s.connection,
51
+ expires_at: s.expires_at,
52
+ ...(withUrl ? { url: s.url } : {}),
53
+ };
54
+ }
55
+ const json = (body, status = 200) => Response.json(body, { status, headers: { "cache-control": "no-store" } });
56
+ export function connectReturnPage(channel) {
57
+ const nonce = btoa(String.fromCharCode(...crypto.getRandomValues(new Uint8Array(16))));
58
+ const script = `(function(){var q=new URLSearchParams(location.search),id=q.get("connect_session")||"",st=q.get("status")||"";
59
+ var ok=/^cxs_[0-9A-Za-z]{1,64}$/.test(id)&&${JSON.stringify(SESSION_STATUSES)}.indexOf(st)>=0;
60
+ if(ok&&typeof BroadcastChannel==="function"){var c=new BroadcastChannel(${JSON.stringify(channel)});c.postMessage({connect_session:id,status:st});c.close();}
61
+ var w={completed:"done",cancelled:"stopped",failed:"failed",expired:"failed"}[ok?st:""]||"back";
62
+ document.getElementById(w).hidden=false;setTimeout(function(){window.close();},50);})();`;
63
+ const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="robots" content="noindex"><title>Connect</title>
64
+ <style>body{font:16px/1.5 system-ui,sans-serif;margin:0;display:grid;place-items:center;min-height:100vh;color:#1a1a1a;background:#fff}p{margin:24px;max-width:28em;text-align:center}</style></head>
65
+ <body><p id="done" hidden>Connected. You can close this window and go back to the chat.</p><p id="stopped" hidden>Nothing was connected. You can close this window.</p><p id="failed" hidden>That didn't work. Close this window and try again from the chat.</p><p id="back" hidden>You can close this window and go back to the chat.</p>
66
+ <script nonce="${nonce}">${script}</script></body></html>`;
67
+ return new Response(html, {
68
+ status: 200,
69
+ headers: {
70
+ "content-type": "text/html; charset=utf-8",
71
+ "cache-control": "no-store",
72
+ "content-security-policy": `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`,
73
+ "referrer-policy": "no-referrer",
74
+ "x-content-type-options": "nosniff",
75
+ },
76
+ });
77
+ }
78
+ export function createKitConnectionRoutes(ctx, opts) {
79
+ const { error } = ctx;
80
+ const method = (req, allowed) => allowed.includes(req.method) ? null : error(405, "method_not_allowed", `${allowed.join(" or ")} only.`);
81
+ async function withScope(req, where, run) {
82
+ const s = await ctx.scope(req);
83
+ if (s instanceof Response)
84
+ return s;
85
+ try {
86
+ return await run(ctx.client(s), s);
87
+ }
88
+ catch (err) {
89
+ if (err instanceof OpenLegionError && err.status === 403 && err.code === "insufficient_role")
90
+ return error(403, err.code, err.message, { type: err.type });
91
+ if (err instanceof OpenLegionError && err.status === 400 && err.param)
92
+ return error(400, err.code ?? err.type, err.message, { type: err.type, param: err.param });
93
+ return ctx.upstream(err, where);
94
+ }
95
+ }
96
+ async function catalog(ol, category) {
97
+ const page = await ol.connections.apps();
98
+ const custom = page.custom_servers ? { count: page.custom_servers.count, max: page.custom_servers.max } : null;
99
+ const data = page.data
100
+ .filter((e) => e.status === "available" && (category === null || e.categories.includes(category)))
101
+ .map((e) => ({ object: "catalog_entry", id: e.id, name: e.name, description: e.description, categories: e.categories, logo: e.logo, auth: { kind: e.auth.kind } }));
102
+ return json({ object: "list", data, has_more: false, custom_servers: custom });
103
+ }
104
+ async function liveConnection(ol, app) {
105
+ const page = await ol.connections.list({ app, limit: 100 });
106
+ return page.data.find((c) => c.status !== "revoked") ?? null;
107
+ }
108
+ return async (route, req) => {
109
+ const url = new URL(req.url);
110
+ if (route === "/catalog") {
111
+ const category = url.searchParams.get("category");
112
+ return method(req, ["GET"]) ?? withScope(req, "catalog", (ol) => catalog(ol, category !== null && APP_ID.test(category) ? category : null));
113
+ }
114
+ if (route === "/connections") {
115
+ const bad = method(req, ["GET"]);
116
+ if (bad)
117
+ return bad;
118
+ const app = url.searchParams.get("app");
119
+ if (app !== null && !APP_ID.test(app))
120
+ return error(400, "invalid_app", "app must be a catalog app id, such as google.");
121
+ return withScope(req, "connections", async (ol) => {
122
+ const page = await ol.connections.list({ limit: 100, ...(app ? { app } : {}) });
123
+ return json({ object: "list", data: page.data.filter((c) => c.status !== "revoked").map(connectionForBrowser), has_more: false });
124
+ });
125
+ }
126
+ const one = /^\/connections\/([^/]+)$/.exec(route);
127
+ if (one) {
128
+ const id = one[1];
129
+ if (!CONNECTION_ID.test(id))
130
+ return error(400, "invalid_connection", "Not a connection id (cxn_…).");
131
+ const bad = method(req, ["GET", "DELETE"]);
132
+ if (bad)
133
+ return bad;
134
+ if (req.method === "GET")
135
+ return withScope(req, "connection", async (ol) => json(connectionForBrowser(await ol.connections.retrieve(id))));
136
+ return withScope(req, "connection", async (ol) => json({ ...connectionForBrowser(await ol.connections.delete(id)), deleted: true }));
137
+ }
138
+ if (route === "/connect_sessions") {
139
+ const bad = method(req, ["POST"]);
140
+ if (bad)
141
+ return bad;
142
+ return withScope(req, "connect_sessions", async (ol) => {
143
+ const parsed = await ctx.readJson(req, MAX_BODY_BYTES);
144
+ if (!parsed.ok)
145
+ return parsed.response;
146
+ const b = parsed.value;
147
+ if (!b || typeof b !== "object" || Array.isArray(b))
148
+ return error(400, "invalid_body", "The body must be a JSON object.");
149
+ const app = b["app"];
150
+ const named = b["server"];
151
+ if (app !== undefined && named !== undefined)
152
+ return error(400, "invalid_body", "Send app or server, not both.");
153
+ const server = named === undefined ? null : serverOf(named);
154
+ if (server !== null && "problem" in server)
155
+ return error(400, "invalid_server", server.problem, { param: "server" });
156
+ if (server === null && (typeof app !== "string" || !APP_ID.test(app)))
157
+ return error(400, "invalid_app", "app must be a catalog app id, such as google.");
158
+ const agent = b["agent"] ?? null;
159
+ if (agent !== null && (typeof agent !== "string" || !AGENT_ID.test(agent)))
160
+ return error(400, "invalid_agent", "agent must be an agent id (agt_…).");
161
+ const origin = req.headers.get("origin");
162
+ if (!origin || origin === "null")
163
+ return error(403, "cross_origin", "Start connecting from your page.");
164
+ const returnPath = b["return_path"];
165
+ if (returnPath !== undefined && (typeof returnPath !== "string" || !RETURN_PATH.test(returnPath)))
166
+ return error(400, "invalid_body", "return_path is a path on this page's own origin, such as /chat?thread=1.");
167
+ const returnUrl = typeof returnPath === "string" ? `${origin}${returnPath}` : (opts.connectReturnUrl ?? `${origin}${opts.basePath}/connect_return`);
168
+ let agents = null;
169
+ if (agent !== null) {
170
+ const live = server === null ? await liveConnection(ol, app) : null;
171
+ agents = live === null ? [agent] : live.agents === null ? null : [...new Set([...live.agents, agent])];
172
+ }
173
+ const session = await ol.connectSessions.create(server === null ? { app: app, return_url: returnUrl, agents } : { server, return_url: returnUrl, agents });
174
+ return json(sessionForBrowser(session, true), 201);
175
+ });
176
+ }
177
+ const session = /^\/connect_sessions\/([^/]+)$/.exec(route);
178
+ if (session) {
179
+ const id = session[1];
180
+ if (!SESSION_ID.test(id))
181
+ return error(400, "invalid_connect_session", "Not a connect session id (cxs_…).");
182
+ return method(req, ["GET"]) ?? withScope(req, "connect_session", async (ol) => json(sessionForBrowser(await ol.connectSessions.retrieve(id), false)));
183
+ }
184
+ if (route === "/connect_return") {
185
+ return method(req, ["GET"]) ?? connectReturnPage(connectChannelName(opts.basePath));
186
+ }
187
+ return null;
188
+ };
189
+ }
@@ -0,0 +1,8 @@
1
+ import type { KitRouteContext } from "./kit-agents.ts";
2
+ /** The most of a text file the preview route answers. */
3
+ export declare const MAX_KIT_ARTIFACT_TEXT_BYTES: number;
4
+ /** The most a file may be: the API's own cap (a function takes at most 4.5 MB of body). */
5
+ export declare const MAX_KIT_FILE_BYTES: number;
6
+ export declare function createKitFileRoutes<Scope extends {
7
+ workspace: string;
8
+ }>(ctx: KitRouteContext<Scope>): (route: string, req: Request) => Promise<Response | null>;