@openlegion/platform 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/README.md +1189 -2
- package/dist/body.d.ts +9 -0
- package/dist/body.js +28 -0
- package/dist/chat-history.d.ts +53 -0
- package/dist/chat-history.js +11 -0
- package/dist/client.d.ts +217 -0
- package/dist/client.js +367 -0
- package/dist/core.d.ts +47 -0
- package/dist/core.js +1 -0
- package/dist/crypto.d.ts +25 -0
- package/dist/crypto.js +81 -0
- package/dist/errors.d.ts +111 -0
- package/dist/errors.js +134 -0
- package/dist/events.d.ts +131 -0
- package/dist/events.js +5 -0
- package/dist/generated/api.d.ts +5505 -0
- package/dist/generated/api.js +446 -0
- package/dist/handler.d.ts +201 -0
- package/dist/handler.js +682 -0
- package/dist/index.d.ts +24 -0
- package/dist/index.js +12 -0
- package/dist/kit-agents.d.ts +95 -0
- package/dist/kit-agents.js +280 -0
- package/dist/kit-codes.d.ts +279 -0
- package/dist/kit-codes.js +44 -0
- package/dist/kit-connections.d.ts +21 -0
- package/dist/kit-connections.js +189 -0
- package/dist/kit-files.d.ts +8 -0
- package/dist/kit-files.js +117 -0
- package/dist/kit-model-keys.d.ts +8 -0
- package/dist/kit-model-keys.js +86 -0
- package/dist/kit-threads.d.ts +3 -0
- package/dist/kit-threads.js +92 -0
- package/dist/kit-tools.d.ts +21 -0
- package/dist/kit-tools.js +47 -0
- package/dist/kit.d.ts +130 -0
- package/dist/kit.js +155 -0
- package/dist/mcp-server.d.ts +27 -0
- package/dist/mcp-server.js +166 -0
- package/dist/next.d.ts +24 -0
- package/dist/next.js +6 -0
- package/dist/ol-signed.d.ts +82 -0
- package/dist/ol-signed.js +115 -0
- package/dist/react/add-server.d.ts +90 -0
- package/dist/react/add-server.js +183 -0
- package/dist/react/agent-chat.d.ts +925 -0
- package/dist/react/agent-chat.js +1917 -0
- package/dist/react/agent-editor.d.ts +133 -0
- package/dist/react/agent-editor.js +222 -0
- package/dist/react/agent-kit.d.ts +160 -0
- package/dist/react/agent-kit.js +279 -0
- package/dist/react/agent-list.d.ts +247 -0
- package/dist/react/agent-list.js +248 -0
- package/dist/react/approval-card.d.ts +272 -0
- package/dist/react/approval-card.js +372 -0
- package/dist/react/artifact-card.d.ts +38 -0
- package/dist/react/artifact-card.js +39 -0
- package/dist/react/avatar.d.ts +21 -0
- package/dist/react/avatar.js +33 -0
- package/dist/react/card-ledger.d.ts +30 -0
- package/dist/react/card-ledger.js +49 -0
- package/dist/react/chat-timing.d.ts +121 -0
- package/dist/react/chat-timing.js +229 -0
- package/dist/react/computer-view.d.ts +309 -0
- package/dist/react/computer-view.js +543 -0
- package/dist/react/computer-viewer.d.ts +175 -0
- package/dist/react/computer-viewer.js +555 -0
- package/dist/react/computer-wire.d.ts +178 -0
- package/dist/react/computer-wire.js +244 -0
- package/dist/react/connect-button.d.ts +145 -0
- package/dist/react/connect-button.js +212 -0
- package/dist/react/connection-request.d.ts +16 -0
- package/dist/react/connection-request.js +18 -0
- package/dist/react/connections-list.d.ts +90 -0
- package/dist/react/connections-list.js +76 -0
- package/dist/react/errors.d.ts +250 -0
- package/dist/react/errors.js +146 -0
- package/dist/react/files.d.ts +41 -0
- package/dist/react/files.js +78 -0
- package/dist/react/index.d.ts +35 -0
- package/dist/react/index.js +26 -0
- package/dist/react/limit-words.d.ts +80 -0
- package/dist/react/limit-words.js +53 -0
- package/dist/react/markdown.d.ts +42 -0
- package/dist/react/markdown.js +56 -0
- package/dist/react/md-parse.d.ts +106 -0
- package/dist/react/md-parse.js +638 -0
- package/dist/react/model-keys-card.d.ts +94 -0
- package/dist/react/model-keys-card.js +123 -0
- package/dist/react/reload.d.ts +211 -0
- package/dist/react/reload.js +339 -0
- package/dist/react/reveal.d.ts +17 -0
- package/dist/react/reveal.js +22 -0
- package/dist/react/schedule-editor.d.ts +107 -0
- package/dist/react/schedule-editor.js +172 -0
- package/dist/react/schedule-time.d.ts +66 -0
- package/dist/react/schedule-time.js +90 -0
- package/dist/react/styles.css +1274 -0
- package/dist/react/transport.d.ts +49 -0
- package/dist/react/transport.js +380 -0
- package/dist/react/use-connections.d.ts +155 -0
- package/dist/react/use-connections.js +231 -0
- package/dist/react/use-model-keys.d.ts +47 -0
- package/dist/react/use-model-keys.js +57 -0
- package/dist/react/use-threads.d.ts +63 -0
- package/dist/react/use-threads.js +73 -0
- package/dist/react/vault-form.d.ts +92 -0
- package/dist/react/vault-form.js +151 -0
- package/dist/schema.d.ts +47 -0
- package/dist/schema.js +16 -0
- package/dist/secrets.d.ts +15 -0
- package/dist/secrets.js +18 -0
- package/dist/stream.d.ts +129 -0
- package/dist/stream.js +192 -0
- package/dist/testing.d.ts +33 -0
- package/dist/testing.js +40 -0
- package/dist/webhooks.d.ts +31 -0
- package/dist/webhooks.js +72 -0
- package/package.json +85 -3
package/README.md
CHANGED
|
@@ -1,3 +1,1190 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @openlegion/platform
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The OpenLegion Platform API client, and the kit that puts an agent in your app: your own functions as
|
|
4
|
+
its tools, your webhooks, and the chat stream, all in one route.
|
|
5
|
+
|
|
6
|
+
## Quickstart
|
|
7
|
+
|
|
8
|
+
You need an OpenLegion account: [sign up or sign in](https://platform.openlegion.ai/sign-in?for=developers).
|
|
9
|
+
Then, with Node 22 or later:
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npx openlegion init my-app # a new Next.js app with an agent in it; signs you in for test-mode keys
|
|
13
|
+
cd my-app
|
|
14
|
+
npm run dev # your app, on http://localhost:3000
|
|
15
|
+
npx openlegion dev # in a second terminal: keeps your agent live in test mode
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Open http://localhost:3000/agent and talk to your agent. When you save a change to its tools, `npx openlegion dev`
|
|
19
|
+
picks it up.
|
|
20
|
+
|
|
21
|
+
To add an agent to a Next.js app you already have, run `npx openlegion init` in its folder instead. It adds this
|
|
22
|
+
package, one route, a tool, an agent and a page with `<AgentChat>`, and prints the commands for your package
|
|
23
|
+
manager. The rest of this page is what those files do.
|
|
24
|
+
|
|
25
|
+
## About this package
|
|
26
|
+
|
|
27
|
+
- Web-standard only (fetch, Request/Response, ReadableStream, Web Crypto), so it runs on Node >= 22 and on
|
|
28
|
+
edge runtimes. There are no runtime dependencies.
|
|
29
|
+
- The types are generated from the Platform API's OpenAPI document (`API_VERSION`).
|
|
30
|
+
- The API key (`OPENLEGION_API_KEY`, `olp_test_…` or `olp_live_…`) stays on your server. Nothing in this
|
|
31
|
+
package ever sends it to a browser.
|
|
32
|
+
- The test key `npx openlegion init` writes to `.env.local` has the scopes this kit uses: `workspaces:read`,
|
|
33
|
+
`workspaces:write`, `messages`, `act_as`, `vault`, `approvals`, `inbound`, `sessions`, `connections` and `usage:read`.
|
|
34
|
+
It can't change a limit or grant credits (`limits:write`): make a key with that scope in the console for the
|
|
35
|
+
server code that does. Templates, connectors and
|
|
36
|
+
webhook endpoints are the CLI's job (`npx openlegion dev`, `npx openlegion deploy`, `npx openlegion templates push`), with its own key.
|
|
37
|
+
|
|
38
|
+
To add the package by hand, without `init`:
|
|
39
|
+
|
|
40
|
+
```sh
|
|
41
|
+
pnpm add @openlegion/platform
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
## An agent in your app
|
|
45
|
+
|
|
46
|
+
### 1. Your function, as a tool
|
|
47
|
+
|
|
48
|
+
```ts
|
|
49
|
+
import { defineTool, refuse } from "@openlegion/platform";
|
|
50
|
+
import { z } from "zod";
|
|
51
|
+
|
|
52
|
+
export const lookupOrder = defineTool({
|
|
53
|
+
description: "Look up one of the customer's orders by its number: its status and when it should arrive.",
|
|
54
|
+
input: z.object({ number: z.string().describe("The order number, e.g. A-1001") }),
|
|
55
|
+
trust: "tool_verified", // your own data. "web_low": it carries other people's words
|
|
56
|
+
effect: "read", // read | draft | write | egress
|
|
57
|
+
run: async ({ number }, ctx) => {
|
|
58
|
+
// ctx.external_ref is the customer OpenLegion signed this call for. Scope every read by it.
|
|
59
|
+
const order = await db.orders.find({ customer: ctx.external_ref, number });
|
|
60
|
+
return order ?? refuse(`There is no order ${number} for this customer.`, "order_not_found");
|
|
61
|
+
},
|
|
62
|
+
});
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
- `input` is zod 4, or any schema that implements Standard Schema together with its JSON Schema extension.
|
|
66
|
+
The arguments are validated before `run` sees them.
|
|
67
|
+
- `run` returns one of three things:
|
|
68
|
+
- a string;
|
|
69
|
+
- an object, which the model gets as JSON (a plain object also goes out as `structuredContent`);
|
|
70
|
+
- `refuse(message, code?)`, a refusal the model reads. The `code` is for you: `GET /connectors/{id}/calls` lists it as `tool_refusal_code` (`npx openlegion dev` prints it too).
|
|
71
|
+
- If `run` throws, the model is told only that the tool failed. The error itself goes to your `onError`.
|
|
72
|
+
- `ctx` holds the signed call context: `org`, `workspace`, `external_ref`, `agent`, `run`, `action`,
|
|
73
|
+
`subject`, `tainted`, `taint_sources`, plus `request` and `signal`.
|
|
74
|
+
- `subject` is your user id of the one person the run acts for (the `subject` your chat route or
|
|
75
|
+
`OpenLegion-Subject` named), so you can apply that person's permissions. It is `null` when there is no
|
|
76
|
+
single signed-in person: a schedule, an inbound event, a hand-off, several people in one run, your service
|
|
77
|
+
principal, or a user being erased. Treat `null` as the least-privileged case, never as an admin.
|
|
78
|
+
- `run` is the `run_…` id that `GET /runs/{id}` (`ol.workspace(id).runs.retrieve(run)`) and the action's `run` use.
|
|
79
|
+
- `action` (`act_…`) stays the same when OpenLegion retries the same action, so you can use it as your
|
|
80
|
+
idempotency key.
|
|
81
|
+
- `tainted: true` means the run has already read untrusted content. Wrap anything you store from such a
|
|
82
|
+
call in `markUntrusted(item)`: whoever reads it later is tainted in turn.
|
|
83
|
+
- `taint_sources` says which content, as ids, never text or URLs: `event:<type>` (an event the run
|
|
84
|
+
started from), `tool:<tool id>` (a result it read, such as `tool:mcp.yourapp.list_comments` or
|
|
85
|
+
`tool:web.fetch`), `memory` (a recalled note), `conversation` (earlier turns), `classifier` or
|
|
86
|
+
`unknown`. It is `[]` when the run is clean.
|
|
87
|
+
- `requiresApproval: true` holds every call to the tool until a person approves it, tainted or not.
|
|
88
|
+
`approver: "admin"` keeps that tool's approvals for the workspace's owners and admins; without it, the
|
|
89
|
+
member whose conversation asked for the call may decide too. What the person reads on the card is yours:
|
|
90
|
+
`title` is the tool's name in a person's words ("Email you"), and `approvalTitle` is the card's whole
|
|
91
|
+
sentence, with values from the call's input (`Email you "{subject}"?`). `approvalFields` says which of the
|
|
92
|
+
input's fields the card shows up front, in order; the rest stay on the card behind its details. `description` is for the model
|
|
93
|
+
and is never shown to a person. Every
|
|
94
|
+
other tool runs, tainted or not: `ctx.tainted` and `ctx.taint_sources` tell you, and what your tool does
|
|
95
|
+
with a tainted call is yours to decide: refuse it (`refuseIfTainted(ctx, message?)` returns a refusal with
|
|
96
|
+
the code `tainted`, listed as `tool_refusal_code`, or `null` when the run is clean), hold it in your product,
|
|
97
|
+
or mark what you store.
|
|
98
|
+
- On a run that has read untrusted content and private data, `web.fetch` opens only links the agent could
|
|
99
|
+
not have written:
|
|
100
|
+
- a person's message, your inbound fact or run input;
|
|
101
|
+
- the template's instructions;
|
|
102
|
+
- a search result, or a page it fetched and that page's links.
|
|
103
|
+
|
|
104
|
+
A link your own tools return does not count, and neither do the agent's replies, files, notes or
|
|
105
|
+
schedules, another agent's hand-off, or a sandbox's output. **If your tools return links the agent should
|
|
106
|
+
open, allowlist those hosts:** `allowHosts` in `policy_envelope.tools["web.fetch"]` (`status: "limited"`),
|
|
107
|
+
then publish and promote the version. `web.fetch` then opens only the hosts `allowHosts` lists, on every
|
|
108
|
+
run: a search result or any other site is refused. An allowlisted host passes whatever the URL carries, so
|
|
109
|
+
allowlist only hosts you control.
|
|
110
|
+
|
|
111
|
+
### 2. The agent's template, as code
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
import { defineTemplate } from "@openlegion/platform";
|
|
115
|
+
|
|
116
|
+
export const template = defineTemplate({
|
|
117
|
+
slug: "support",
|
|
118
|
+
name: "Support",
|
|
119
|
+
tools: { lookup_order: lookupOrder },
|
|
120
|
+
spec: {
|
|
121
|
+
name: "Support",
|
|
122
|
+
role: "Answers a customer's questions about their orders",
|
|
123
|
+
instructions: "Look an order up before you answer anything about it.",
|
|
124
|
+
model_tier: "fast",
|
|
125
|
+
tools: ["agent.finish"],
|
|
126
|
+
},
|
|
127
|
+
});
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
A template is what you publish; each customer's workspace gets an agent made from it (`ws.agents.list()`).
|
|
131
|
+
`spec` is a template spec (`TemplateSpec`). `template.toTemplateSpec(connector)` turns it into the version you
|
|
132
|
+
push. It declares your connector and its tools, and when a tool requires approval it also writes the
|
|
133
|
+
policy envelope that holds it (step 5).
|
|
134
|
+
|
|
135
|
+
A template with several agents (`spec.agents`) gives each of your tools to all of them. To give one to some
|
|
136
|
+
agents only, name them by key: `toolAgents: { refund_order: ["support"] }` beside `tools`. An agent that is
|
|
137
|
+
not named is never offered that tool. A tool you leave out of `toolAgents` is every agent's.
|
|
138
|
+
|
|
139
|
+
#### Platform tools
|
|
140
|
+
|
|
141
|
+
`spec.tools` lists OpenLegion's own tools, by id, beside yours (yours come from `tools` and need no listing).
|
|
142
|
+
|
|
143
|
+
- **`agent.finish`: list it on every agent.** It is how a run says it is done. The agent is told to call it
|
|
144
|
+
when there is nothing left to do, and a run that hasn't called it by 60 % of its step cap counts as
|
|
145
|
+
struggling (on automatic model choice, it moves up a model).
|
|
146
|
+
- The `starter` template that every organization starts with lists `agent.finish`, `memory.search`,
|
|
147
|
+
`memory.timeline` and `memory.write_candidate`.
|
|
148
|
+
- `memory.search`: what the agent remembers about this customer, as true now.
|
|
149
|
+
- `memory.timeline`: the same, as of a past time, superseded versions included.
|
|
150
|
+
- `memory.write_candidate`: propose a memory. It is reviewed before it lasts.
|
|
151
|
+
- `web.search` (priced per search) and `web.fetch` (a public https page, as text): their results are
|
|
152
|
+
untrusted content, other people's words.
|
|
153
|
+
|
|
154
|
+
**Resident or deferred.** OpenLegion keeps at most 15 tools resident: `agent.finish`, `agent.schedule`,
|
|
155
|
+
`agent.note_to_user`, `memory.search`, `memory.timeline`, `memory.write_candidate`, `web.search`, `web.fetch`,
|
|
156
|
+
`files.read`, `files.write`, `sandbox.run`, `sandbox.code_run`, `team.hand_off`, `team.ask` and `team.complete`.
|
|
157
|
+
Each of these you list is sent, definition and all, with every step of every run. Every other tool is deferred,
|
|
158
|
+
such as `files.read_attachment` or `files.deliver`: a run starts with a short index that names it, the agent's
|
|
159
|
+
first call to it runs at once, and its definitions are sent from the next step. `spec.tools` takes at most 64
|
|
160
|
+
ids, and at most 15 of them resident.
|
|
161
|
+
|
|
162
|
+
A tool id OpenLegion doesn't have, or doesn't offer yet, is refused when you push the version, with the
|
|
163
|
+
reason and the nearest id that exists. Every id, with whether it is resident, what the chat draws for it
|
|
164
|
+
and whether a call waits for approval, is on [Platform tools](https://platform.openlegion.ai/docs/platform-tools).
|
|
165
|
+
|
|
166
|
+
### 3. One route
|
|
167
|
+
|
|
168
|
+
Next.js (App Router), in `app/api/openlegion/[...route]/route.ts`:
|
|
169
|
+
|
|
170
|
+
```ts
|
|
171
|
+
import { createNextHandler } from "@openlegion/platform/next";
|
|
172
|
+
import { template } from "@/openlegion/template";
|
|
173
|
+
|
|
174
|
+
export const maxDuration = 300;
|
|
175
|
+
|
|
176
|
+
export const { GET, POST, DELETE } = createNextHandler({
|
|
177
|
+
template,
|
|
178
|
+
// REQUIRED for the browser routes (chat, runs, vault). YOUR session decides whose workspace this
|
|
179
|
+
// browser may talk to; the browser only ever names a thread inside it.
|
|
180
|
+
resolve: async (req) => {
|
|
181
|
+
const user = await getSignedInUser(req); // your auth, e.g. your session cookie
|
|
182
|
+
if (!user) return null; // 401
|
|
183
|
+
return { workspace: user.account.openlegionWorkspaceId, subject: user.id };
|
|
184
|
+
},
|
|
185
|
+
webhooks: {
|
|
186
|
+
// Every run that ends fires exactly one of these three.
|
|
187
|
+
"run.completed": async (event) => {
|
|
188
|
+
// Narrow on `truncated`: a large run arrives as a reference, { object, id }, with no status.
|
|
189
|
+
const run = event.data.truncated ? null : event.data.object;
|
|
190
|
+
await markConversationAnswered(event.data.object?.id, run?.status);
|
|
191
|
+
},
|
|
192
|
+
"run.failed": async (event) => {
|
|
193
|
+
await logRunFailure(event.data.object?.id); // event.data.object.error has the code
|
|
194
|
+
},
|
|
195
|
+
"run.cancelled": async (event) => {
|
|
196
|
+
await markConversationAnswered(event.data.object?.id);
|
|
197
|
+
},
|
|
198
|
+
},
|
|
199
|
+
});
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
A large object arrives as `{ object: { object, id }, truncated: true }`: fetch it by its id.
|
|
203
|
+
|
|
204
|
+
- **Errors your code throws** (a tool's `run`, a webhook handler) go to `onError`, beside `template`:
|
|
205
|
+
`createNextHandler({ template, onError: (err, where) => logger.error({ err, where }) })`. Without it they
|
|
206
|
+
go to `console.error`. Neither the model nor your user sees them.
|
|
207
|
+
- **A webhook that doesn't answer `2xx` within 5 seconds is retried** after 1 min, 5 min, 30 min, 2 h, 6 h,
|
|
208
|
+
12 h, 24 h and 24 h: 9 attempts over about 2.9 days, each with the same event `id` (dedupe on it). While
|
|
209
|
+
your app or `npx openlegion dev` is down, deliveries fail and wait in that schedule; `GET /events` has every event
|
|
210
|
+
either way. An endpoint is disabled only after 20 failures in a row spanning at least 72 hours.
|
|
211
|
+
|
|
212
|
+
| Route (under `/api/openlegion`) | What it is |
|
|
213
|
+
| --- | --- |
|
|
214
|
+
| `POST /mcp` | Your tool server. It answers only calls signed with your connector secret (`OPENLEGION_CONNECTOR_SECRET`, or `connectorSecret`). Anything else gets 401. |
|
|
215
|
+
| `POST /template` | Your template's definition, for `npx openlegion templates push` and `npx openlegion dev`: `{object: "template_definition", slug, name, version, tools, hash}`, where `version` is `template.toTemplateSpec(connector)` for the `{connector: {id, slug}}` posted and `hash` is the sha256 (hex) of `canonicalJson(version)`; `canonicalJson`, exported, is JSON with every object's keys sorted. Signed like `/mcp` (your connector secret) and verified before the body is parsed; it reads at most 64 KiB, and a call that is not signed gets 401. With no `template`, a signed call gets 404. It is served in production too, so CI can push after a deploy (`npx openlegion templates push --app https://your.app/api/openlegion`). The secret's holder can already call every tool; this route tells them less. |
|
|
216
|
+
| `POST /webhooks` | Your webhook endpoint (`OPENLEGION_WEBHOOK_SECRET`, or `webhookSecret`). A bad signature gets 400. A type with no handler gets 200 `{received: true, handled: false}`: it is acknowledged and dropped, and `npx openlegion dev` says so. A handler that throws gets 500, and OpenLegion retries. |
|
|
217
|
+
| `POST /chat`, `GET /chat/{thread}/stream`, `GET /runs/{run}/stream` | The chat stream for `useChat`. These routes exist **only with `resolve`**: without it they answer 404. When `resolve` returns null the answer is 401. A browser request from another origin gets 403, before `resolve` runs, unless you list that origin in `allowedOrigins` (exact origins such as `https://admin.example.com`: no path, no trailing slash, no `*`). The check is Go's `CrossOriginProtection`, applied to every method: the browser's `Sec-Fetch-Site` decides when it is sent; otherwise `Origin` must match the request's `Host` header. A request with neither header (your server, `curl`) passes to `resolve`. It works behind a proxy or `next dev --hostname 127.0.0.1` that rewrites the URL. |
|
|
218
|
+
| `GET /threads`, `POST /threads` | Your user's conversations, for your conversation list (`useThreads()`), with the same rules as the chat routes. `GET` answers them newest message first (`order=last_message_at`; one with no message yet by when it was made), as the person `resolve` answered, so the API decides which they see; it takes `agent`, `limit` (1–100) and `starting_after` (a `thr_…`), and drops anything else. `POST {agent, home?}` starts one (`home: true`: the agent's home conversation, 200 when it exists). Your `metadata` is never in an answer, and a page can't set it. A double submit is one conversation (the hook's `Idempotency-Key`). |
|
|
219
|
+
| `GET /runs/{run}`, `GET /vault`, `GET /chat/{thread}/messages` | What `<AgentChat>` reads once when it loads a thread's history, with the same rules as the chat routes. `GET /chat/{thread}/messages` answers the thread's newest messages, as the chat draws them, read as the person `resolve` answered; the chat reads it again when it finds no running answer, so a reply that finished just after the page read its history still appears. `GET /runs/{run}` says how a run that left no answer ended: its status, the end user's sentence (`error.message`) when it failed, and once it ended, each action's tool, status and outcome. It never includes the run's `partner_message`, an action's input, receipt or policy. It reads the run as the person `resolve` answered, so another person's run answers as a missing one. `GET /vault?thread=thr_…&message=msg_…&name=…` answers one bit, `{saved}`: true only when the item the agent asked for in that message of that thread is saved, of the kind asked, on every site asked. Every other case answers `{saved: false}` the same way: an unknown name, a site not covered, no such ask or message, another person's thread. It never includes a value. |
|
|
220
|
+
| `POST /vault` | The save of `<VaultSecretForm>`, when an agent asks your user for a login or an API key (`vault_ask_user`). Same rules as the chat routes: only with `resolve`, the same origin check. The form names the ask it answers, `ask: {thread, message}` (`<AgentChat>` passes it; a form you draw yourself takes it as `ask`), and the route makes one `ol.workspace(ws, { subject }).vaultItems.create({ ..., ask })` in the workspace `resolve` returned: the item is created, or, for a name already saved, given the site the agent asked for. The API reads what was asked from that message's run, never from the body, so a member saves only what their own conversation asked for. A save over an item someone else saved is `403 insufficient_role`, and the form says an owner or admin saved it. A reply drawn live has the chat's own id: the route finds the message that asked in the thread (`409 vault_ask_missing` until it is stored). `GET /vault` reads the ask's own items (`ask[thread]`, `ask[message]`). It reads at most 16 KiB and never passes the body to `onError`. Your app key needs the `vault` scope (keys from `npx openlegion login` have it). |
|
|
221
|
+
| `GET /approvals/{apr}`, `POST /approvals/{apr}/decide` | The approval card `<AgentChat>` draws in place of a tool call held for a person's approval. `GET` answers what the card shows: the approval's `title` and `fields` in a person's words, `expires_at`, `action_hash`, and `can_decide`, whether the person `resolve` answered may decide it. An approved card also carries `action`: its `status`, its `outcome` (null while it waits or runs) and, when it did not succeed, `message`, the end user's sentence (never the operator's). It never answers the action's input, its cost or your `metadata`. `decide` takes `{decision: "approve" \| "reject", action_hash}` as the person `resolve` answered. An owner or admin may decide every approval; a member decides one their own conversation asked for, unless the tool says `approver: "admin"`. Anyone else, or a `resolve` with no `subject`, gets `403 insufficient_role`. Its answer is the decided card, with `run_refused` (`code`, `message` and, on `cap_reached`, `limit`; never the API's `partner_message`) when the decision was taken but no run follows it now. Same rules as the chat routes. |
|
|
222
|
+
|
|
223
|
+
- **The chat's look, and its 204.** `GET /chat/{thread}/stream` reads the thread once (`GET /threads/{id}`). If
|
|
224
|
+
a run is answering, it streams that run. If not, it answers 204 with `openlegion-last-message-at`: the thread's
|
|
225
|
+
`last_message_at`, empty before its first message. The chat reads `GET /chat/{thread}/messages` only when that
|
|
226
|
+
stamp has moved since its last look, so an open conversation that looks now and then costs one request per
|
|
227
|
+
look and no extra platform call. If you serve the route yourself, send the header the same way; without it,
|
|
228
|
+
the chat draws only a run that is still answering.
|
|
229
|
+
- **Other frameworks.** `createHandler(options)` is the same handler as a plain
|
|
230
|
+
`(req: Request) => Promise<Response>`. Mount it at `basePath` (default `/api/openlegion`).
|
|
231
|
+
- **`resolve` and the request body.** `resolve` gets the request, but must not read its body.
|
|
232
|
+
- **`resolve` and your user's name.**
|
|
233
|
+
- Return `displayName` from `resolve` and OpenLegion keeps it as that user's name in your organization: the agent is told it, and history and the audit trail show it. Pass a name of 1–120 characters, as your product shows it, never an email address.
|
|
234
|
+
- OpenLegion changes the name only on a call that is not a `GET` (your user's next message or decision, say). A new or different `displayName` is saved: the kit sends it as `OpenLegion-Subject-Name`. Leave `displayName` out and the name stays. Return `displayName: null` and OpenLegion forgets it: the kit sends `OpenLegion-Subject-Name-Clear: true` instead.
|
|
235
|
+
- The kit sends a name only with `subject`, skips a blank one, and never shortens or invents one. A name that is not a string, is over 120 characters once trimmed, or holds a control character is left out: the request goes on without it, and `onError` is told why. Calling the API yourself, pass `subjectName` beside `subject` in any of three places: `new OpenLegion({ subject, subjectName })`, `ol.workspace(ws, { subject, subjectName })`, or a call's options. `null` clears it there too, and a name OpenLegion would refuse throws a `TypeError` before the request goes.
|
|
236
|
+
- **Rotating secrets.** During a rotation, either secret option takes two values: the new secret first,
|
|
237
|
+
then `{ secret: old, expires }`.
|
|
238
|
+
- **The route's own error codes.** A route that refuses answers `{error: {code, message}}`. Every code it
|
|
239
|
+
can answer is in `KIT_ROUTE_CODES` (exported from `@openlegion/platform`), with its status, what it means
|
|
240
|
+
and what to do: `invalid_thread`, `agent_unavailable`, `handler_failed` and the rest. When the API
|
|
241
|
+
refuses a person's request (a 4xx such as `insufficient_role`), the route passes the API's own code on,
|
|
242
|
+
and the [error catalog](https://platform.openlegion.ai/docs/errors) has it.
|
|
243
|
+
|
|
244
|
+
#### Approvals
|
|
245
|
+
|
|
246
|
+
A tool with `requiresApproval: true` (or held by the template's `policy_envelope`) doesn't run until a
|
|
247
|
+
person decides.
|
|
248
|
+
|
|
249
|
+
- **The event is `action.requires_approval`**, with the action in `data.object` and the approval to decide
|
|
250
|
+
in **`data.approval`** (`apr_…`). It is there even when the action is truncated. `approval.requested` is a
|
|
251
|
+
different thing: the agent asking a person a question.
|
|
252
|
+
- **Decide** with the `approvals` scope, as a person who may: an owner or admin decides every approval, and
|
|
253
|
+
a member decides one that a conversation they started asked for (and answers questions). An approval from
|
|
254
|
+
a run in no conversation a person started (a schedule's, a background run's, an inbound event's; these
|
|
255
|
+
report to the agent's home conversation) is an owner's or admin's. The role comes from `POST /sessions` or the template's `default_subject_role`; with no subject
|
|
256
|
+
the call is refused `subject_required`:
|
|
257
|
+
|
|
258
|
+
```ts
|
|
259
|
+
webhooks: {
|
|
260
|
+
"action.requires_approval": async (event) => {
|
|
261
|
+
const action = event.data.truncated ? await ol.workspace(event.workspace!).actions.retrieve(event.data.object.id!) : event.data.object!;
|
|
262
|
+
if (await yourPolicySays(action)) {
|
|
263
|
+
await ol.workspace(event.workspace!, { subject: yourAdmin.id }).approvals.decide(event.data.approval, {
|
|
264
|
+
decision: "approve",
|
|
265
|
+
action_hash: action.action_hash,
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
},
|
|
269
|
+
},
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
- Then `approval.decided` (or `approval.expired`, 24 hours after the request) fires, and the approved
|
|
273
|
+
action runs in a **later run**: the run that asked has already ended.
|
|
274
|
+
- `<AgentChat>` draws an approval card in place of the held call, where the person who asked, an owner or
|
|
275
|
+
an admin can decide (step 4, below); you can also decide from your own UI or backend.
|
|
276
|
+
- **Who sees what.** A member sees only the conversations they started. Owners and admins can read every
|
|
277
|
+
conversation in a workspace: tell your users so if several of them share one. Give your customer's
|
|
278
|
+
account owner the admin role with `ol.sessions.create({ workspace, subject, role: "admin" })`, so that
|
|
279
|
+
someone can decide a background run's approvals and edit agents and schedules.
|
|
280
|
+
|
|
281
|
+
### 4. The browser
|
|
282
|
+
|
|
283
|
+
```tsx
|
|
284
|
+
"use client";
|
|
285
|
+
import { AgentChat } from "@openlegion/platform/react";
|
|
286
|
+
|
|
287
|
+
// threadId: thr_…, one your server found or created in the workspace resolve() returns.
|
|
288
|
+
// history: the thread's messages, from toAgentChatMessages on your server (below).
|
|
289
|
+
<AgentChat threadId={threadId} initialMessages={history} />;
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
On your server, pass the thread's messages through `toAgentChatMessages`:
|
|
293
|
+
|
|
294
|
+
```ts
|
|
295
|
+
import { toAgentChatMessages } from "@openlegion/platform";
|
|
296
|
+
|
|
297
|
+
const page = await ol.workspace(workspace, { subject }).messages.list(threadId, { limit: 100 });
|
|
298
|
+
const history = toAgentChatMessages(page.data);
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
It puts them oldest first, leaves out system messages, and keeps what the chat reads:
|
|
302
|
+
- Each reply's `tainted` (see "Rendering replies safely"). Without it, every past reply counts as tainted.
|
|
303
|
+
- Each person's message's `run`. When a run left no answer, because it was refused or failed, or it ended
|
|
304
|
+
with actions and no words, the chat asks how it ended and shows that under the message after a reload.
|
|
305
|
+
- Each reply's `stopped`. A reply its person stopped says "Stopped." after a reload, under whatever it had
|
|
306
|
+
written or done. `isMessageStopped(message)` reads it for your own UI.
|
|
307
|
+
Without it, nothing is shown there.
|
|
308
|
+
- Each message's `trigger` and `schedule`: what started the run that wrote it (`schedule`, `message`, and so
|
|
309
|
+
on; null on a person's message) and the schedule (`sch_…`) when one did. A reply a schedule started gets its
|
|
310
|
+
line (below). An engine that does not send them gives null, and the chat draws as before.
|
|
311
|
+
|
|
312
|
+
`@openlegion/platform/react` needs `react` (19), `@ai-sdk/react` (4) and `ai` (7): optional peers of the
|
|
313
|
+
package, so a server that never imports it installs none of them.
|
|
314
|
+
|
|
315
|
+
**The page talks to your routes, never to `api.openlegion.ai`.** The API sends no CORS headers, so a
|
|
316
|
+
browser page can't call it directly. `<AgentChat>` posts to the chat route `createHandler({ resolve })`
|
|
317
|
+
opens on your server, which calls OpenLegion with your key. In a browser page, `new OpenLegion()` refuses
|
|
318
|
+
an org key, and any base URL on another origin; a session token (`POST /sessions`) is for your server, or
|
|
319
|
+
for a route on your own origin that forwards to the API.
|
|
320
|
+
|
|
321
|
+
- **One POST per message.** A cut stream (a deploy, the function's deadline, the network) re-attaches to
|
|
322
|
+
the run after its last numbered part, so the reply continues in place; it never re-sends the message.
|
|
323
|
+
Three re-attaches in a row that bring nothing show "The reply was interrupted." with a Reconnect button.
|
|
324
|
+
A run that waits its turn, or works without words for a while, keeps its stream open with a comment line
|
|
325
|
+
every 20 seconds, and a re-attach that finds it still waiting does not count toward the three. A
|
|
326
|
+
Reconnect that cannot reach the run keeps the reply so far and can be tried again.
|
|
327
|
+
- **A message that did not go says so.** A send that was refused, or that could not reach your route, marks
|
|
328
|
+
the message "Not sent." with a "Send again" button; its words and files are kept (labels `notSent`,
|
|
329
|
+
`sendAgain`). A send a spending limit refused is the exception: the limit's sentence is a quiet note, not an
|
|
330
|
+
error, and "Send again" is not offered until the limit resets, since it could not work before then. The note
|
|
331
|
+
says why in `data-ol-unsent-why`: `failed` (it did not go: offline, a 5xx), `refused` (a refusal, such as a
|
|
332
|
+
plan or credits) or `limit` (a spending limit); the kit's stylesheet draws "Not sent." in the danger color
|
|
333
|
+
for `failed` only (`useAgentChat().unsentReasons` has the same by message id). When the send may have reached
|
|
334
|
+
OpenLegion all the same (no answer came, or a 5xx), Send again
|
|
335
|
+
sends it under the same message id, which your route's send is keyed by: OpenLegion replays the first send
|
|
336
|
+
and the chat follows its run, so it never starts or bills a second one. After a refusal it is a new message.
|
|
337
|
+
- **The box is never locked by a reply.** A message sent while the agent is still answering is sent at once:
|
|
338
|
+
OpenLegion answers it after the current reply. Until then it sits after the transcript, marked
|
|
339
|
+
`data-ol-waiting`, with "Your message will be answered after the current reply." (`labels.queuedReasons.thread_busy`).
|
|
340
|
+
When the reply ends it takes its place in the transcript and its answer streams in. Messages that waited
|
|
341
|
+
behind the same reply are answered together.
|
|
342
|
+
- **Stop.** While the agent works, Stop (`labels.stop`) takes Send's place, so the box keeps one button; typing
|
|
343
|
+
the next message brings Send back. A tap before your route has answered is remembered and sent as soon as the
|
|
344
|
+
run has an id. It cancels the run through your kit
|
|
345
|
+
route (`POST /runs/{run}/cancel`), as the signed-in person: the agent starts no new work, and the answer the model
|
|
346
|
+
is writing is cut within about 2 seconds (a tool call already running finishes first). The tap is immediate all the same:
|
|
347
|
+
Send is back at once, the box is yours (a message sent now waits its turn, as one sent while the agent works),
|
|
348
|
+
and the reply says "Stopping…" (`labels.stopping`, `data-ol-stopping`) where "Stopped." will go. What still
|
|
349
|
+
arrives meanwhile is drawn, except a step the model begins after the tap: it never runs, so no line says it
|
|
350
|
+
does (and a stopped reply shows no step as still in progress, nor a call the platform kept no record of: one
|
|
351
|
+
the cut step named that never ran). Once the run ends, the words it had written stay, and that line says "Stopped."
|
|
352
|
+
(`labels.stopped`), whatever the reply already holds. When a stop lands in the run's last model call and its
|
|
353
|
+
stream ends without saying so, the chat asks the run itself (`GET /runs/{run}`, at most twice, a second apart)
|
|
354
|
+
and says "Stopped." if it was cancelled. A reply that finished before the stop
|
|
355
|
+
reached it is shown whole, with no such line. If the run can't be stopped, one line says so and the reply
|
|
356
|
+
carries on (`labels.stopFailed`). After a reload the stopped reply still says "Stopped.", from its
|
|
357
|
+
`stopped` in the history; a message whose run was stopped before it wrote or did anything says it too.
|
|
358
|
+
Live or after a reload, "Stopped." is drawn in one place: inside the reply's row (`data-ol-stopped`), or an
|
|
359
|
+
Agent row of its own when nothing was written.
|
|
360
|
+
- **Suggestions, and the cursor in the box.** `suggestions={["Plan my week", "Summarize my unread email"]}`
|
|
361
|
+
draws the empty conversation's first messages as chips (`data-ol-suggestion`); tapping one sends it. They sit
|
|
362
|
+
above the transcript; `suggestionsAt="end"` puts them right under the message box. `autoFocus` puts the
|
|
363
|
+
cursor in the message box when the chat appears.
|
|
364
|
+
- **Your own lines by the box.** `beforeComposer` is drawn right above the message box (after the chat's status
|
|
365
|
+
lines), `afterComposer` right under it (after suggestions at the "end"): a spending meter, a line that says
|
|
366
|
+
approvals come first. Inside the chat's own `<div data-ol-chat>`, so no `display: contents` or `order` is needed.
|
|
367
|
+
- **The message box off, when a person may read and not send** (no plan, say). Pass `composerOff={{ text:
|
|
368
|
+
"Your agents run once you have a plan.", link: { href: "/plans", text: "See plans" } }}` and your sentence,
|
|
369
|
+
then your link, is drawn where the box was (`data-ol-composer-note`, said politely), at the box's height, so
|
|
370
|
+
the page doesn't move. The box, Send and attach stay hidden in that footprint, out of the tab order and
|
|
371
|
+
disabled. Nothing the kit sends itself goes: no suggestion chips, no "Send again", no carry-on message after a
|
|
372
|
+
card's save or connect. The history, its cards and their buttons stay usable. An approval card can still be
|
|
373
|
+
approved or rejected: it answers what was already asked, and a person can always say no. Your server is still
|
|
374
|
+
the gate. With `now: false` and `code: "plan_required"`, the box stays on until a send is refused with that
|
|
375
|
+
`error.code` (your 402). Then the box turns off with your sentence, not a failure line, until `now` changes.
|
|
376
|
+
Without `composerOff` the chat is drawn exactly as before.
|
|
377
|
+
- **When a reply ends, `onFinish`** (on `<AgentChat>` and `useAgentChat`) is told `{ message, status }`, once
|
|
378
|
+
the reply is drawn as the conversation holds it (below): `status` is "finished" (also a reply that stopped at
|
|
379
|
+
its limit and says so), "stopped" (a person stopped it) or "failed". Read your page's frame again on
|
|
380
|
+
"finished" (a first file, a new title); a refresh after a failed send with no network would replace the page.
|
|
381
|
+
- **It picks a running answer back up after a reload** (`resume`, default true), and a message queued
|
|
382
|
+
behind the agent's current task shows "Waiting for the agent to finish its current task". A message sent
|
|
383
|
+
while the chat is still looking for that answer (sent the moment the conversation opens, or the chat is
|
|
384
|
+
remounted on it) keeps Stop and "Thinking…" until its reply ends: the look's "none" waits for the reply,
|
|
385
|
+
and a look that finds the reply's own run does not read it a second time. A message refused then (a paused
|
|
386
|
+
agent, the spending limit) says why, as one sent later does.
|
|
387
|
+
- **When a reply ends, it is drawn as the conversation holds it.** The chat reads the thread once through
|
|
388
|
+
your kit route (`GET {basePath}/chat/{thread}/messages`) and puts that run's reply in place of the one it
|
|
389
|
+
drew: words the stream did not carry appear (a summary the agent ended its run with), and the steps and
|
|
390
|
+
their order are what a reload shows. A reply that already agrees is not drawn again; a read that fails
|
|
391
|
+
leaves the reply as it was drawn.
|
|
392
|
+
- **No raw error reaches the page.** A refusal shows its own message, which is written for your user and
|
|
393
|
+
names neither OpenLegion nor your plumbing ("This assistant isn't available right now…"). Put your own
|
|
394
|
+
words per code in `labels={{ refusals: { credits_exhausted: "…" } }}`. A reply that stopped at its limit
|
|
395
|
+
(`run_budget_exhausted`, `run_step_limit`) and says so in its own words is not given the platform's sentence
|
|
396
|
+
for the same stop under them (`stopAlreadySaid`); with no words, or with your sentence for the code, it is drawn.
|
|
397
|
+
Such a stop is not a failure (`replyFailed`).
|
|
398
|
+
A spending limit that refused a message (`cap_reached` with its `limit`: which limit, why, when it resets) is
|
|
399
|
+
said in your user's own time zone: "You've used today's limit. It resets at 7:00 PM." or "What's left of
|
|
400
|
+
today's limit isn't enough for this request. It resets tomorrow at 9:00 AM."; read after the reset, "Today's
|
|
401
|
+
limit has reset. Send it again." Every word is a label (`labels.limits`), and `labels.refusals.cap_reached`
|
|
402
|
+
still replaces the whole sentence. Only you know whether your user may raise a limit, so a line for it is
|
|
403
|
+
yours to turn on: `labels.limits.raise = { text: "You can raise your limit in Settings.", href }`. Drawn on
|
|
404
|
+
a server, the sentence is the platform's, which names its zone, until the page is live. `limitWords()` gives
|
|
405
|
+
the words for your own UI; `OpenLegionError.limit` carries the limit on your server. Anything else shows one of the
|
|
406
|
+
kit's sentences (a run that fails mid-reply: "Something went wrong. Please try again."), and the error
|
|
407
|
+
itself goes to `onError` for your logs. `agentChatErrorText(err)` gives the same words for your own UI.
|
|
408
|
+
The server page that opens the chat is yours, so catch there too: a wrong `OPENLEGION_API_KEY` otherwise
|
|
409
|
+
shows your customer Next's error page. The `/agent` page `npx openlegion init` writes shows how: one white-label line
|
|
410
|
+
("This assistant isn't available right now. Please try again later."), the error in your server's log,
|
|
411
|
+
and, under `next dev` only, the reason and the fix on the page. The chat routes answer a key OpenLegion
|
|
412
|
+
refuses, even inside your `resolve`, with 502 `agent_unavailable` and an `onError` line.
|
|
413
|
+
- **A reply on the agent's usual model says so, once.** When the run's budget couldn't cover the model your
|
|
414
|
+
user chose, the reply runs on the agent's own, and a quiet note under it says: "This reply used your agent's
|
|
415
|
+
usual model. The budget for this run couldn't cover the one you chose." It is not an error, and the reply has not
|
|
416
|
+
failed. Your words per reason go in `labels={{ modelNotes: { run_budget: "…" } }}`; a reason you leave out keeps
|
|
417
|
+
the platform's sentence. The part is `data-model-note` (`ModelNotePart`).
|
|
418
|
+
- **One rule: `message` is for your user, `partner_message` is for you, on every refusal and every run
|
|
419
|
+
error.** A run's `error` (on `GET /runs/{id}` and `run.failed`) always has both: `error.message` is
|
|
420
|
+
white-label ("This reply didn't go through. Please send your message again."), and
|
|
421
|
+
`error.partner_message` says what happened and what to do ("The run stopped with an error."). Show the
|
|
422
|
+
first, log the second.
|
|
423
|
+
- **Unstyled, with an optional look.** Semantic markup with `data-ol-*` attributes
|
|
424
|
+
(`[data-ol-message][data-ol-role="user"]`, …), with no layout set inline (the optional stylesheet has it,
|
|
425
|
+
so any rule of yours wins without `!important`; only state is inline: an empty transcript is hidden, a long
|
|
426
|
+
approval value is clamped, a person's line breaks are kept),
|
|
427
|
+
`labels` for every visible string (including the "Thinking…" status line while a reply has no words yet,
|
|
428
|
+
and the empty transcript's line). The agent's words are drawn as Markdown (see "Rendering replies safely");
|
|
429
|
+
`renderText` replaces that with your own renderer. For a presentable start, see
|
|
430
|
+
[The default look](#the-default-look). Tool calls show a plain label and what happened ("Done: Refund
|
|
431
|
+
order", "Waiting for approval: Cancel plan"), never their input or output. A call that did not work in a reply
|
|
432
|
+
that went on (the agent read another page, then answered) is a quiet step in its own words ("Couldn't open a
|
|
433
|
+
page", `labels.toolSkipped` for yours; `data-ol-tool-recovered`); only in a reply that ended in failure (one
|
|
434
|
+
carrying a `data-refusal` other than a stop at its limit; its row has `data-ol-reply-failed`) is it the platform's sentence, and the default
|
|
435
|
+
look draws it in the danger color. While a reply is still being written, a call that did not work is not shown
|
|
436
|
+
as such: it reads as in progress ("Checking your connected apps…") while it is the newest step, since the agent
|
|
437
|
+
may try it again, and is not drawn once a later step is there; the quiet line is in the folded steps once the
|
|
438
|
+
reply ends. OpenLegion's own tools read as what the agent did ("Searched the web", "Read a page",
|
|
439
|
+
"Sent an email"). `labels.tools` sets your own label for a tool, by its name, mine or yours (`web_search`,
|
|
440
|
+
`refund_order`); a tool you label goes through your `toolDone`, `toolCalling`, … sentences, or give it its two
|
|
441
|
+
lines as they read: `tools: { email_me: { running: "Emailing you", done: "Emailed you" } }` (the running
|
|
442
|
+
words are its label in the other sentences). `showToolCalls={false}` hides the lines. The platform sends no tool output anyway: a tool part's `output` is
|
|
443
|
+
`{action, status, outcome}`, with `approval: "apr_…"` while it waits for a person, and a call that did not
|
|
444
|
+
work is a `tool-output-error` whose `errorText` is safe to show; `agent.finish`, which ends every run, is never shown. In your own UI
|
|
445
|
+
(`useAgentChat`) it is a tool part of type `tool-agent_finish`: skip it by that type.
|
|
446
|
+
- **Simple by default.** A reply's steps are one line. While the agent works, the chat shows the step it is
|
|
447
|
+
on. When the reply is done, its steps are one line, "2 steps" (`labels.steps`), that opens to the list;
|
|
448
|
+
`steps="list"` keeps every step on its own line. A single step stays as its line, a reply with no words
|
|
449
|
+
keeps its list, and a card (an approval, a Connect button, a secure form) is never folded.
|
|
450
|
+
- **An approval card when a tool call waits for a person.** In place of a held call (its tool part's `output`
|
|
451
|
+
is `{status: "requires_approval", approval: "apr_…"}`), `<AgentChat>` draws a card: what the agent wants to
|
|
452
|
+
do in a person's words, with Approve and Reject. It is a card from the first moment: while its approval is read,
|
|
453
|
+
its frame stands there, busy (`data-ol-approval-loading`, `aria-busy`), with the call's line in it, never a
|
|
454
|
+
step's line. After Approve, the card follows the approval until the approved action has an outcome (soon, then
|
|
455
|
+
less often, for ten minutes at most). If it then did not work, the card says so in place of "carries on", in
|
|
456
|
+
the failure look (`data-ol-approval-failed`): "Approved." and the platform's sentence for the person, such as
|
|
457
|
+
"Approved. The connected service could not be reached." (`labels.actionFailedWith`, the sentence in `{message}`),
|
|
458
|
+
or "Approved, but it didn't work." when the platform gives none (`labels.actionFailed`). Under the sentence it shows the facts your tool put
|
|
459
|
+
up front (`approvalFields` on `defineTool`), or the approval's first two when your tool names none, and
|
|
460
|
+
"Details" opens the rest and then reads "Hide details" (`labels.details`,
|
|
461
|
+
`labels.hideDetails`); `approvalFields="all"` shows
|
|
462
|
+
every fact. A decision goes to your kit route as the signed-in person,
|
|
463
|
+
and the chat then follows the run that carries on (it keeps looking for about two minutes, every second for
|
|
464
|
+
the first 30 s). Until the platform answers, the card says "Approving…" or "Rejecting…" where its buttons were
|
|
465
|
+
(`labels.approving`, `labels.rejecting`); from then until that reply ends
|
|
466
|
+
the chat shows it is working, Stop and "Thinking…", for 30 s at most when no reply is found; a Stop in that gap
|
|
467
|
+
is sent as soon as the run is found. When the platform took the decision but no run follows it now (the
|
|
468
|
+
workspace can't run, or the agent is paused), the chat never shows it working: after Reject the card stands
|
|
469
|
+
alone, and after Approve the card says "Approved." with a note under it. The decision is kept, and the agent acts
|
|
470
|
+
on it once it can run, so the note is not a refused message's "send it again": for a paused agent it is "This
|
|
471
|
+
agent is paused. It will act on this when you resume it."; for any other code it is the note a message sent now
|
|
472
|
+
would get (your `labels.refusals`, the platform's sentence, or the limit and when it resets). Your words for it
|
|
473
|
+
by code go in `labels.decisionRefusals`, read first. Tapped while the
|
|
474
|
+
reply that asked is still being written, the run that carries on cannot start before that reply ends, so the
|
|
475
|
+
looks and the 30 s count from its end. When the first look finds no run (it may have come and gone already), the chat reads
|
|
476
|
+
the conversation once and draws a reply it holds that the chat has not; and once more if no look ever finds one
|
|
477
|
+
(`useAgentChat().awaitingReply`, `afterDecision`; `<AgentChatView onApprovalDeciding awaitingWords>`). An owner or
|
|
478
|
+
admin may decide, and so may a member for what their own conversation asked for, unless the tool says
|
|
479
|
+
`approver: "admin"`. Anyone else sees one line in place of the buttons, "Waiting for an admin to decide this.",
|
|
480
|
+
as soon as the card is read and again after a reload. **A decided card stays a card**: after a reload, a call
|
|
481
|
+
that needed approval is drawn in place as its card, decided (its title, its facts behind Details, and
|
|
482
|
+
"Approved." or "Rejected." in place of the buttons: `labels.wasApproved`, `labels.wasRejected`), never a step
|
|
483
|
+
among the others. Each approval is one card, at the newest call that asked for it: when the agent asks again for the same thing in a later reply (a new call, or the same call repeated while it waits), the card moves down to that reply and the earlier call says "Asked again in a later reply: {tool}" (`labels.toolApprovalBelow`, `data-ol-approval-below`). That line stands for the card, so it is never folded
|
|
484
|
+
into the reply's steps. A reply that reuses the call with its result, as the one after a decision does, moves nothing, so a decided card stays where it was decided. Only a waiting approval follows its newest ask: a card decided in this chat stays in the reply it was decided in, whatever names its approval later, and keeps saying "Approved. The agent carries on." until the reply the decision started has ended (or the chat stops looking for one, after 30 s), then "Approved.", as a reload says it ("Rejected. The agent won't do this." stays); it is not mounted again when that reply settles; a later call naming it that still says it waits is not drawn. A call is one action whether it carries the model's id (live) or its `act_` id (the conversation read again), and a look after a decision that finds a reply already drawn (a run that has not closed yet) draws nothing twice. A line that waits for approval carries `data-ol-tool-waiting`, so you can style it apart from a done step (both have `data-ol-tool-state="output-available"`). A card that cannot be read shows "This request couldn't
|
|
485
|
+
be loaded." with "Try again". A decision your route refuses (a 402 or 409, or a 4xx whose `error.type` is
|
|
486
|
+
`"refusal"`) shows the refusal's `error.message` on the card, as text, with Approve and Reject still there. For
|
|
487
|
+
example, your plan check: `402 {error: {code: "plan_required", message: "Your agents run once you have a
|
|
488
|
+
plan."}}`. Write that message for the person. A 5xx, another 4xx, or no network gets "Something went wrong.
|
|
489
|
+
Please try again." (`labels.generic`). Every string is a label (`approve`, `reject`, `approved`, `rejected`,
|
|
490
|
+
`approvalExpired`, `approvalChanged`, `approvalNotAllowed`, `approvalUnavailable`, `retry`).
|
|
491
|
+
- **A waiting approval is never out of sight.** When the agent goes on writing under its card and the chat
|
|
492
|
+
follows the end, the card can scroll away. While a card the person can decide has its buttons off screen, a
|
|
493
|
+
one-line bar sits right above the message box: "Waiting for your OK" ("2 waiting for your OK" when more wait)
|
|
494
|
+
and "Review", which brings the newest card into view and puts focus on it (`data-ol-approval-bar`,
|
|
495
|
+
`data-ol-approval-review`; labels `approvalBar`, `approvalBarMany`, `approvalReview`). It goes when nothing waits
|
|
496
|
+
or a card is in view. From the tap on Approve or Reject the card is not waiting: it carries
|
|
497
|
+
`data-ol-approval-deciding` until the platform answers, and the bar does not count it. `approvalBar={false}` turns it off.
|
|
498
|
+
A card that turns up waiting after the chat opened is also said to assistive technology, "Waiting for your OK:
|
|
499
|
+
<its title>", by a status line out of view beside the transcript (`data-ol-announce`; label `approvalAnnounce`),
|
|
500
|
+
since the transcript is `aria-busy` while a reply streams. After Approve or Reject, focus goes to the card (the
|
|
501
|
+
button pressed is gone), without moving the transcript.
|
|
502
|
+
- **A reply nobody asked for says what started it.** A reply a schedule started (the history's `trigger` is
|
|
503
|
+
`schedule`) has one quiet line above it, "From your schedule" (`data-ol-from-schedule`; label
|
|
504
|
+
`fromSchedule`), so it does not read as an answer to the person's last message. No other trigger gets a line.
|
|
505
|
+
`fromSchedule={false}` turns it off.
|
|
506
|
+
- **Files, both ways.** An Attach button uploads up to 5 files (each at most 4 MB) to your kit route as the
|
|
507
|
+
signed-in person; they show as chips, and go with the message in a `data-attachments` part (ids only). A
|
|
508
|
+
message sent while a file still uploads is held, not dropped: the status line says "Sending when the upload
|
|
509
|
+
finishes…" (`data-ol-send-held`), and it goes when the upload ends, with every file. Escape in the box, removing
|
|
510
|
+
a chip, or an upload that fails lets it go, and the words and files stay in the box. The
|
|
511
|
+
files the agent delivered are cards in its replies (below); `showFiles` also lists them above the message
|
|
512
|
+
box, and without it the list is never requested. Each download link goes through your kit route, and only for a file delivered in that person's own
|
|
513
|
+
conversation. A file the
|
|
514
|
+
agent wrote after reading outside content carries `data-ol-tainted="true"` and a line saying so. The strings
|
|
515
|
+
are labels (`attach`, `uploading`, `sendWhenUploaded`, `removeFile`, `fileTooLarge`, `uploadFailed`, `uploadLimit`, `files`, `fileUntrusted`).
|
|
516
|
+
In your own UI, `useAgentChat()` gives `attach(file)`, `send(text, files)` and `artifactHref(id)`; with
|
|
517
|
+
`useAgentChat({ showFiles: true })` it also reads the conversation's files into `artifacts`, for a list of your own.
|
|
518
|
+
- **A delivered file is a card where the agent delivered it.** The `data-artifact` part that follows the call
|
|
519
|
+
draws `<ArtifactCard>` in the reply: the file's name as its download link, its size, and the same line when
|
|
520
|
+
it was written after reading outside content. An image (PNG, JPEG, WebP, GIF) shows at once. A PDF, and a
|
|
521
|
+
Markdown or plain-text file, wait behind a Preview button, so nothing loads that was not asked for; text is
|
|
522
|
+
read through your kit route (`GET /artifacts/{art}/text`, at most 256 KB, plain text) and drawn by your
|
|
523
|
+
`renderText`, which is told when the file is tainted; without one, a Markdown file is drawn as the chat draws
|
|
524
|
+
the agent's words and a plain-text file as it is. Nothing in a file is ever interpreted: no SVG, no
|
|
525
|
+
HTML. Any other type is the card with its download link. The card is the file's one place: the list above the message box is off unless you pass `showFiles`. The strings
|
|
526
|
+
are labels (`preview`, `hidePreview`, `previewLoading`, `previewFailed`). In your own UI:
|
|
527
|
+
`<ArtifactCard artifact={artifactOf(part.data)} href={chat.artifactHref(id)} loadText={() => chat.artifactText(id)} />`.
|
|
528
|
+
- **A secure form when the agent needs a login or a key.** An agent that may use the vault asks your user
|
|
529
|
+
with `vault_ask_user`; in place of that tool call `<AgentChat>` draws `<VaultSecretForm>`: the site it will
|
|
530
|
+
be used on first (in ASCII, so a look-alike name shows as one), the agent's reason, a caution when the agent
|
|
531
|
+
read outside content before asking, and the fields. It posts to `/vault`, never to the chat, and then sends
|
|
532
|
+
"I saved it." (`labels.vaultSaved`) so the agent carries on. That message is your user's, with their trust,
|
|
533
|
+
so it never carries the agent's words: not the form's label, not the handle (`vault://…`). It has no slot.
|
|
534
|
+
Which item was saved is data: `<VaultSecretForm onSaved>` and `<AgentChatView onVaultSaved>` get the handle
|
|
535
|
+
and the request. The agent never sees what was typed. The value does pass
|
|
536
|
+
through your page and your server. The request arrives as its own part, `data-vault-request`:
|
|
537
|
+
`<VaultSecretForm request={vaultRequestOf(part.data)} />` draws it in your own UI. A reloaded page redraws a
|
|
538
|
+
form from history only while the item is not saved: once it is, on every site asked, the form is not drawn
|
|
539
|
+
again (`GET /vault`, once per form on the page). A form never submits by itself.
|
|
540
|
+
- **A reload says how a message with no answer ended.** History has no reply for a message whose run was
|
|
541
|
+
refused before it started, or ended with tool calls and no words. For the messages on the page it was
|
|
542
|
+
given, `<AgentChat>` reads `GET /runs/{run}` once, two at a time and at most eight. What it finds is
|
|
543
|
+
drawn after the person's message as an Agent row, where the live stream draws it. For a run that
|
|
544
|
+
failed it draws the end user's sentence, or your words for its code (`labels.refusals`). For a run that
|
|
545
|
+
ended with tool calls it draws one tool line per call, as the live stream did, and the approval card for a
|
|
546
|
+
call still waiting for a person. A run still going draws
|
|
547
|
+
nothing here, because the resumed stream shows it. A read that fails leaves the page as history drew it,
|
|
548
|
+
with no error and no retry.
|
|
549
|
+
- **Not in v1:** regenerating a reply, editing a message, and AI SDK `file` parts (the transport refuses
|
|
550
|
+
them with no request; files go through Attach).
|
|
551
|
+
- **`<AgentChat>` plus one thing.** `<AgentChat>` is `<AgentChatView>` with the props `agentChatViewProps`
|
|
552
|
+
makes from `useAgentChat`'s result, so a chat of yours with one more control is the same call and never
|
|
553
|
+
lacks what `<AgentChat>` wires (the carry-on after a saved key, a finished connect or an approval; Stop;
|
|
554
|
+
Send again). `useAgentChat` serves one thread for its life, so mount yours with `key={threadId}`
|
|
555
|
+
(`<HomeChat key={thread.id} … />`); `<AgentChat>` keys itself, so a new `threadId` is a new chat:
|
|
556
|
+
|
|
557
|
+
```tsx
|
|
558
|
+
function HomeChat(props: AgentChatProps) {
|
|
559
|
+
const chat = useAgentChat(props);
|
|
560
|
+
return (
|
|
561
|
+
<>
|
|
562
|
+
<AgentChatView {...agentChatViewProps(chat, props)} />
|
|
563
|
+
<button onClick={() => void chat.send("Plan my week")}>Plan my week</button>
|
|
564
|
+
</>
|
|
565
|
+
);
|
|
566
|
+
}
|
|
567
|
+
```
|
|
568
|
+
|
|
569
|
+
- **Your own UI:** `useAgentChat({ threadId, initialMessages })` is `useChat` with the same transport, plus
|
|
570
|
+
`queued`, `send(text, files)` (while a reply is on its way too: the message is then in `waiting`, by id,
|
|
571
|
+
and at the end of `messages`), `stop()` and `stopState` (`stopping`, `stopped`, `failed`; `stop()` cancels
|
|
572
|
+
the run, where `useChat`'s own only stopped reading), `reconnect()`, and what the reload found:
|
|
573
|
+
`runOutcomes` (by the person's message id) and `savedAsks` (`<message id>:<part index>`).
|
|
574
|
+
`<AgentChatView>` draws them from its props of the same names. `createAgentChatTransport()` is the
|
|
575
|
+
transport alone, with `sendWaiting` and `stop` beside `useChat`'s two methods.
|
|
576
|
+
|
|
577
|
+
#### Rendering replies safely
|
|
578
|
+
|
|
579
|
+
A reply can be steered by what the agent read: a web page, a customer's forwarded email, a comment your own
|
|
580
|
+
tool returned. Every message says whether that happened. A stored message has `tainted` (from
|
|
581
|
+
`GET /threads/{id}/messages`), and a streamed reply ends with a `message-metadata` part `{ tainted }`.
|
|
582
|
+
`renderText(text, { tainted, role })` receives it, the message element carries `data-ol-tainted`, and
|
|
583
|
+
`isMessageTainted(message)` reads it for your own UI. A reply that is still streaming counts as tainted
|
|
584
|
+
until its closing part says otherwise.
|
|
585
|
+
|
|
586
|
+
**The kit draws the agent's Markdown itself**, a safe subset with no dependency (`<MarkdownText>`, and
|
|
587
|
+
`renderMarkdown(text)` for a renderer of yours that adds to it): paragraphs, bold, italics, inline and fenced
|
|
588
|
+
code, links, nested lists, headings (as bold lines), block quotes, rules and tables (a table scrolls sideways
|
|
589
|
+
inside the reply on a phone). Hooks `data-ol-md`, `data-ol-md-p`, `-strong`, `-em`, `-code`, `-pre`, `-link`,
|
|
590
|
+
`-host`, `-ul`, `-ol`, `-li`, `-heading`, `-quote`, `-rule`, `-table`, `-align`; variables `--ol-md-gap`, `--ol-md-mono`.
|
|
591
|
+
What it never does, tainted or not:
|
|
592
|
+
|
|
593
|
+
- **No HTML.** `<b>`, `<script>` and every other tag are shown as the text they are. The kit makes React
|
|
594
|
+
elements only and never sets `dangerouslySetInnerHTML`.
|
|
595
|
+
- **No image is ever loaded.** `` is a link to the url, the alt text its words: an image the model
|
|
596
|
+
was talked into writing would be a request your user's browser makes, unasked, to whoever chose the URL.
|
|
597
|
+
- **Links only to `http:`, `https:` and `mailto:`**, opened in a new tab with `rel="noopener noreferrer"`. Any
|
|
598
|
+
other link (`javascript:`, `data:`, a relative path) is the text it was written as. Each link's address is
|
|
599
|
+
its title, and when a link's words do not name its host, the host follows them in quiet text
|
|
600
|
+
(`data-ol-md-host`, in its `xn--` form for an international name), so "sign in here" cannot hide where it
|
|
601
|
+
goes. Links are drawn in every reply, tainted or not: a research answer's sources are its point. A tainted
|
|
602
|
+
reply's words are drawn with `data-ol-md-tainted`, and the chat passes each reply's `tainted` to `<MarkdownText>`.
|
|
603
|
+
- **Half-arrived Markdown does not jump**: an unclosed `**` or `[text](` stays text until it closes. Once a
|
|
604
|
+
reply is no longer streaming (it finished, or was stopped mid-sentence), its last block draws no marker that
|
|
605
|
+
never closed: an opening `**` or `*`, a `` ` `` or a `[` (and a link whose address never closed is its words);
|
|
606
|
+
the words after it are drawn. `renderMarkdown(text, { ended: true })` and `<MarkdownText ended>` do the same
|
|
607
|
+
for yours.
|
|
608
|
+
|
|
609
|
+
A person's own messages stay plain text. If you pass your own `renderText`, it is told `info.tainted`. Whatever
|
|
610
|
+
you draw, load no remote image from a tainted reply: an image URL is a request your user's browser makes, unasked,
|
|
611
|
+
to the page that wrote it. Its links are your call. The kit draws them with their hosts shown. To draw them as
|
|
612
|
+
words, with the host and nothing to click, use the kit's renderer with `taintedLinks="text"`:
|
|
613
|
+
|
|
614
|
+
```tsx
|
|
615
|
+
<AgentChat
|
|
616
|
+
threadId={thread.id}
|
|
617
|
+
renderText={(text, info) =>
|
|
618
|
+
info.role === "assistant" ? <MarkdownText text={text} tainted={info.tainted} taintedLinks="text" /> : text
|
|
619
|
+
}
|
|
620
|
+
/>
|
|
621
|
+
```
|
|
622
|
+
|
|
623
|
+
`renderMarkdown(text, { tainted, taintedLinks })` does the same for a renderer of your own. The same choice applies
|
|
624
|
+
when you render a reply on your server, in an email or a notification.
|
|
625
|
+
|
|
626
|
+
#### Show one approval anywhere
|
|
627
|
+
|
|
628
|
+
The card `<AgentChat>` draws for a held call is yours to draw anywhere else, by the approval's id: an inbox, a
|
|
629
|
+
notification's landing page, or a card older than the chat holds (`onOpenAtMissing`).
|
|
630
|
+
|
|
631
|
+
```tsx
|
|
632
|
+
import { ApprovalCard } from "@openlegion/platform/react";
|
|
633
|
+
|
|
634
|
+
<ApprovalCard id="apr_…" fallbackTitle="Waiting for approval" />
|
|
635
|
+
```
|
|
636
|
+
|
|
637
|
+
- `id` is the approval's `apr_…` (from `GET /approvals`, an `approval.requested` event, or `onOpenAtMissing`).
|
|
638
|
+
`fallbackTitle` is the line shown while it is read, and if it cannot be (with Try again).
|
|
639
|
+
- It reads and decides through the same routes as the chat (`GET /approvals/{apr}`, `POST /approvals/{apr}/decide`,
|
|
640
|
+
above), as the person `resolve` answers. `base` is your route's base path (default `/api/openlegion`), and
|
|
641
|
+
`fetch` is the `fetch` its calls go through (a header of yours on each).
|
|
642
|
+
- Approve and Reject show only to someone who may decide it (`can_decide`). Anyone else reads its facts and
|
|
643
|
+
"Waiting for an admin to decide this." (`labels.approvalNotAllowed`). Decided or expired, it says so in place of
|
|
644
|
+
the buttons.
|
|
645
|
+
- While it waits for a decision, it reads its approval again when the tab comes back, so one decided elsewhere
|
|
646
|
+
stops offering its buttons.
|
|
647
|
+
- `labels` takes any of the chat's approval labels (`ApprovalLabels`); the rest are `DEFAULT_LABELS`. `fields="all"`
|
|
648
|
+
shows every fact up front. `onDecided(decision, { runRefused })` runs once the platform took a decision;
|
|
649
|
+
`runRefused` (`ApprovalRunRefused`: `code`, `message`, `limit`) says no run follows it now, as a message sent
|
|
650
|
+
now would be refused, else null. The card then says "Approved." or "Rejected. …" and nothing more: what to say
|
|
651
|
+
under it is yours.
|
|
652
|
+
|
|
653
|
+
#### The agent's browser: watch, take over, give back
|
|
654
|
+
|
|
655
|
+
When an agent uses a browser, its stream carries a `data-computer` part, and `<AgentChat>`
|
|
656
|
+
draws it as one line: what the agent is doing, the site, and **Watch**. Watch opens `<ComputerView>` in place: the
|
|
657
|
+
page live, and **Take over** to drive it yourself, then **Give back**. There is no live thumbnail in the
|
|
658
|
+
conversation; nothing is streamed until a person asks to watch.
|
|
659
|
+
|
|
660
|
+
```tsx
|
|
661
|
+
import { AgentChat, readViewerGrant } from "@openlegion/platform/react";
|
|
662
|
+
|
|
663
|
+
<AgentChat
|
|
664
|
+
computer={{
|
|
665
|
+
fetchViewer: ({ session, control, signal }) =>
|
|
666
|
+
fetch("/api/computer-viewer", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ session, control }), signal }).then(readViewerGrant),
|
|
667
|
+
}}
|
|
668
|
+
/>
|
|
669
|
+
```
|
|
670
|
+
|
|
671
|
+
- **Your server mints, the component asks.** Your route calls `POST /computer_sessions/{session}/viewer` with
|
|
672
|
+
`{ origin, control }` as the person asking, and returns the platform's answer (`{ url, token, expires_at }`) as it
|
|
673
|
+
is. `origin` is your page's origin from your own configuration, never the browser's word for it. Only the person
|
|
674
|
+
the conversation belongs to may watch or take over; in a conversation nobody started (the agent's home
|
|
675
|
+
conversation), the workspace's owners and admins. Refuse anyone else with a 4xx and your own `error.message`:
|
|
676
|
+
`readViewerGrant` turns it into `ComputerViewRefused`, and the view shows your words. A 429 is a refusal the person
|
|
677
|
+
may try again, so the view adds Try again. A 409 from the platform means the browser's state changed while the grant was being made
|
|
678
|
+
(Take over pressed just as the run ended, say), so no token was made: pass it on as it is, and the view asks once
|
|
679
|
+
more by itself, half a second later. If that meets a 409 too, it shows its words with Try again. Your own
|
|
680
|
+
`fetchViewer` says the same with `new ComputerViewRefused(words, { conflict: true, retry: true })`.
|
|
681
|
+
- **When it asks.** `control: false` when Watch opens the view, and again on every reconnect (a view token works
|
|
682
|
+
once). `control: true` only when the person presses Take over, so no control token exists until someone asks.
|
|
683
|
+
- **What it says.** One sentence above the picture, for where things stand: connecting, the agent working, waiting
|
|
684
|
+
for your answer to its request, stopped at a security check or for a sign-in (Take over is then the filled
|
|
685
|
+
button), you have control (and two minutes before it runs out), someone else has control, you gave it back,
|
|
686
|
+
reconnecting, can't be reached (Try again), and why it ended. Every sentence is a label
|
|
687
|
+
(`DEFAULT_COMPUTER_VIEW_LABELS`, `computer.labels`). None carries a page's words, and the site line is a checked
|
|
688
|
+
hostname. The sentence is the view's one status, said once each time it changes and not on each new frame.
|
|
689
|
+
Until a frame of the page shows, the picture's box is hidden from screen readers, so they hear the sentence
|
|
690
|
+
and not a picture that isn't there.
|
|
691
|
+
- **The picture's shape is the page's.** The box takes each frame's own width and height as its aspect ratio, set
|
|
692
|
+
on the box itself, so the page is never letterboxed and no stylesheet of yours can get it wrong. Before the first
|
|
693
|
+
frame it holds a 16:10 place. Style its border and background, never its height or ratio.
|
|
694
|
+
- **When the browser waits for your user.** A run that stops at a security check or a sign-in, or that your user
|
|
695
|
+
holds when it ends, leaves the browser waiting (`parked` with `waiting_for`, up to 15 minutes), and the next
|
|
696
|
+
message in the conversation takes it back. Nothing carries on by itself then:
|
|
697
|
+
- the check's or sign-in's sentence is followed by "Then tell your agent to go on." (`thenGoOn`), with Watch and
|
|
698
|
+
Take over filled;
|
|
699
|
+
- Give back says "You gave control back. Tell your agent to go on." (`gaveBackWaiting`).
|
|
700
|
+
- Control that ran out, or a view that dropped, says so, then "Tell your agent to go on." (`expiredWaiting`,
|
|
701
|
+
`droppedWaiting`): nobody has it then. While a run is live, the agent really does have it again, so those
|
|
702
|
+
keep their sentences.
|
|
703
|
+
- For a browser your user held as the run ended, the row says "Your agent's browser is waiting for you. When
|
|
704
|
+
you're done, give control back, then tell your agent to go on." (`waitingForYou`). The platform knows only who
|
|
705
|
+
held it then, so the row never says who holds it now; the open view reads that from the browser itself.
|
|
706
|
+
|
|
707
|
+
- **Go on, in one tap.** In those three (gave back, ran out, dropped), and for a browser your user held that nobody
|
|
708
|
+
holds now, the view's filled button is **Go on** (`labels.goOn`), with Take over beside it, outlined. It sends
|
|
709
|
+
"Go on." (`labels.goOnMessage`) through the chat's own send, exactly as if your user typed it. It is their
|
|
710
|
+
click on a button that says what it sends, so it is their message. The view only shows it where the chat can
|
|
711
|
+
send (no reply running, the box on); it never sends by itself, and once pressed it goes until things change.
|
|
712
|
+
`<ComputerView>` on its own shows it only with `onGoOn`.
|
|
713
|
+
|
|
714
|
+
A park for a held act reads as before. A park that runs out reads "The browser closed while it waited for you."
|
|
715
|
+
The labels are optional, so labels you wrote before them keep ours.
|
|
716
|
+
- **Closing it.** The view's close button says **Stop watching** while it connects, reconnects or shows the page,
|
|
717
|
+
and **Dismiss** where nothing is being watched: the browser can't be reached, or watching was refused
|
|
718
|
+
(`labels.dismiss`). Either one closes the view, never the agent's browser, and puts focus back on Watch.
|
|
719
|
+
- **Nobody watches "Connecting…" forever.** A connection that gets no first frame of the page within 15 seconds (a grant, a
|
|
720
|
+
kernel or a stream that never answers, or a first frame that stops partway) counts as a drop: the view reconnects with a fresh grant, and after three
|
|
721
|
+
tries says it can't reach the browser, with Try again. A live view that has nothing new to show stays live: the
|
|
722
|
+
browser's server writes a keep-alive at least every 15 seconds. A live stream with no bytes at all for 45 seconds
|
|
723
|
+
(three missed keep-alives) is a drop, handled the same way.
|
|
724
|
+
- **When a connection stalls.** `onTiming(step, at)` on `<ComputerView>` or `computer` reports each step as it
|
|
725
|
+
happens: `view_asked`, `view_granted`, `stream_opened`, `first_bytes`, `first_state`, `first_frame`,
|
|
726
|
+
`first_picture`, or `watchdog` or `silence`. The last step before a gap is the layer that waited. Keys that did not
|
|
727
|
+
all land name why: `input_partial`, `input_token`, `input_conflict`, `input_gone`, `input_refused`, `input_failed`,
|
|
728
|
+
`input_network` or `input_unsent`. It carries step names and times only, never a key.
|
|
729
|
+
- **Taking over.** The agent's own steps wait while a person holds the browser. The picture takes the pointer and
|
|
730
|
+
the keys, Tab and Esc included; **Esc, then Tab** leaves it. On a phone a tap is a click, a one-finger drag
|
|
731
|
+
scrolls, a pinch zooms, and Keyboard brings up the on-screen keyboard. Control ends at Give back, when its
|
|
732
|
+
token runs out (up to 20 minutes), or when the connection drops, and the view says which.
|
|
733
|
+
- **What your user typed is never lost silently.** Keys go to the browser one request at a time, in order. Give back
|
|
734
|
+
and Stop watching send what was already typed first, and only then give control back. They keep sending while the
|
|
735
|
+
browser keeps answering, and give up when one request has gone unanswered for 8 seconds, or after 20 seconds in all.
|
|
736
|
+
Meanwhile the button reads "Giving back…" (`labels.givingBack`). A request the browser refused before applying it (its token) is sent once more, with a fresh grant. One that failed
|
|
737
|
+
partway or got no answer is never sent again, because that could type a key twice. Then, or when control ends with
|
|
738
|
+
keys still on their way, control goes back to the agent and the view says "Your last keys may not have reached the
|
|
739
|
+
page, and your agent has control again. Take over to check them." (`labels.inputLost`), with Take over filled. In
|
|
740
|
+
a browser that waits for your user, it says "Your last keys may not have reached the page. Take over to check them,
|
|
741
|
+
then give control back." (`labels.inputLostWaiting`), with no Go on until they have looked.
|
|
742
|
+
`computer.canTakeOver: false` hides Take over; your server must refuse the control token as well.
|
|
743
|
+
- **Keep the token to the component.** It is held in memory, sent in `Authorization` only, and never put in a
|
|
744
|
+
URL, storage, a cookie or a `postMessage`. Keep third-party scripts off the page that shows the viewer (no
|
|
745
|
+
analytics or error tracker that records request headers), and set a CSP whose `connect-src` allows the viewer's
|
|
746
|
+
origin. Only the current picture is kept, and none after the view closes.
|
|
747
|
+
- **On its own:** `<ComputerView session={computerSessionOf(part.data)} fetchViewer={…} />`, with `onControlChange`,
|
|
748
|
+
`onClose` and `labels`. Until your platform serves the browser, no `data-computer` part arrives and nothing is
|
|
749
|
+
drawn.
|
|
750
|
+
- **A held browser act** is an approval card like any other. The page's words on it (the control's name, the form
|
|
751
|
+
it is in, the page's address) are values the platform marks `from_page`, drawn in quotes and read as "The page's
|
|
752
|
+
words" (`labels.pageWords`), so a page can never pass for the card's own words. The text the agent will type is
|
|
753
|
+
its own, an ordinary value. `createHandler`'s approval route passes the mark on.
|
|
754
|
+
- **Approve waits while your user holds that browser.** The act can't run while a person holds the browser, and an
|
|
755
|
+
approval given then would be used up. So while a view open in the chat holds control of the browser the act
|
|
756
|
+
belongs to (the card's `computer_session`, the platform's `action.computer_session`), Approve is disabled (not
|
|
757
|
+
hidden), and one line under the card says why: "You have control of this browser. Give control back first, then
|
|
758
|
+
approve." (`labels.approveHeldBack`). The line is the button's description. Approve comes back the moment control
|
|
759
|
+
is given back, or the view closes. Reject stays usable. With no view open here the chat can't know, and the
|
|
760
|
+
platform's refusal stands. `<ApprovalCard heldSessions>` does the same on its own.
|
|
761
|
+
- **The browser's steps in words:** opening a website, using it, reading the page, closing the browser, and filling
|
|
762
|
+
in your user's saved login. That one never says the agent saw the login.
|
|
763
|
+
- **Its row keeps the newest words.** When a later reply closes the browser, the row (drawn where the session first
|
|
764
|
+
showed) says so, both live and after the chat reads the thread again when the reply ends.
|
|
765
|
+
- **A later reply that takes the browser back.** The next message in a conversation can take a waiting browser
|
|
766
|
+
back, and a later run can park it again, for a sign-in, say. The browser keeps its one row, where it first
|
|
767
|
+
showed, and an open view there reads the new state: what the view said itself (you gave control back, your time
|
|
768
|
+
ran out, the connection dropped) ends once the browser's state changes or a newer reply uses it, so it never
|
|
769
|
+
offers Go on for a step that has passed.
|
|
770
|
+
- The newest reply that used the browser, when its row is further up, gets one compact line: the browser's
|
|
771
|
+
sentence and **Show the browser** (`labels.showBrowser`), which scrolls to the row, opens it, and puts focus on
|
|
772
|
+
its first control. There is never a second view, and the open one never moves (moving it would reconnect it
|
|
773
|
+
and give back control your user holds).
|
|
774
|
+
- The line is there while the browser exists, and only as the reply streams in and after it ends. A conversation
|
|
775
|
+
reloaded later shows the browser at its first reply only.
|
|
776
|
+
- Style it with `[data-ol-computer-pointer]`.
|
|
777
|
+
|
|
778
|
+
#### Assistants and schedules your users change
|
|
779
|
+
|
|
780
|
+
```tsx
|
|
781
|
+
"use client";
|
|
782
|
+
import { AgentEditor, ScheduleEditor, useAgents } from "@openlegion/platform/react";
|
|
783
|
+
|
|
784
|
+
const { agents } = useAgents();
|
|
785
|
+
<AgentEditor />; // make one from a template agent marked creatable
|
|
786
|
+
<AgentEditor agent={agents[0]} />; // change one
|
|
787
|
+
<ScheduleEditor agent={agents[0]} />; // its schedules, and a day-and-time picker
|
|
788
|
+
```
|
|
789
|
+
|
|
790
|
+
The same `createHandler({ resolve })` serves them: `{basePath}/agents`, `/agents/{id}`, `/template_agents`, `/model_presets`,
|
|
791
|
+
`/schedules`, `/schedules/{id}` and `/schedules/{id}/pause|resume`, each as the user your `resolve()`
|
|
792
|
+
answers. The API's rules decide, not the page:
|
|
793
|
+
|
|
794
|
+
- **Only what your template's `customizable` admits is drawn**, and the API refuses anything else
|
|
795
|
+
(`409 outside_template_bounds`, with `param` naming the field, which the editor marks).
|
|
796
|
+
- **Speed and depth, when there is a choice.** With two or more model presets to choose between (the template
|
|
797
|
+
agent's own and its `customizable.model_tier.allowed`), the editor and the create form show "Speed and depth":
|
|
798
|
+
"Default (Fast)", "Thorough", "Most capable" (`labels.models`, `labels.modelDefaultKnown`). With one, it says
|
|
799
|
+
that one in plain text; with none allowed, nothing. Which presets a person may choose is yours to say:
|
|
800
|
+
`createHandler({ allowModelTier: (who, tier, req) => planOf(who).tiers.includes(tier) })`. The routes then
|
|
801
|
+
offer only those, and refuse a save naming another (403 `model_tier_not_allowed`): "That choice isn't
|
|
802
|
+
available to you here. Choose another." Going back to the template's own preset is never asked. The API's
|
|
803
|
+
bounds stay the backstop. `<AgentList models={useAgents().agents}>` puts each agent's preset under its name.
|
|
804
|
+
**When what a person may use changes, save their agents again: a stored choice, and an Auto agent's set of models, stay as they were saved.** Your hook is asked when a person saves, never on a run.
|
|
805
|
+
`<AgentEditor showModelNames>` puts beside each preset the model it runs on now, by the name
|
|
806
|
+
`{basePath}/model_presets` answers ("Thorough · " and that name; none is written in the kit), and one line
|
|
807
|
+
under the choice on what the chosen preset is for (`labels.modelHints`), with "Runs on your own model key."
|
|
808
|
+
when the workspace's assistants run on one. Off by default. One read per page; until it answers, or when it
|
|
809
|
+
fails, the choice is as it is without the prop.
|
|
810
|
+
**Auto** comes first where your template allows it (`customizable.model_tier.auto`) and `allowModelTier` says yes
|
|
811
|
+
to `"auto"`: "Chooses a model for each task from the ones available to you." (`labels.modelAuto`,
|
|
812
|
+
`labels.modelAutoHint`). It is never offered on a workspace's own model key, which makes no routing call. A save to
|
|
813
|
+
Auto routes among exactly the presets your hook allows this person. The handler sets `auto_presets` from your
|
|
814
|
+
answers and drops any a page sent.
|
|
815
|
+
- **A member can look, an owner or admin can change.** A member's save shows "Only an account admin can
|
|
816
|
+
change this." (`insufficient_role`); give your users the role you mean with `POST /sessions {role}`.
|
|
817
|
+
- **The page never reads or writes your `metadata` or `external_ref`.** The routes drop them from what a
|
|
818
|
+
page sends and take them out of what it gets back. Set them from your server with your key.
|
|
819
|
+
- **One save is one write.** The editors send an `Idempotency-Key` per submission, namespaced by user, so a
|
|
820
|
+
double click doesn't make two assistants.
|
|
821
|
+
- **Schedules follow their origin.** Your user's own can be changed, paused and removed; your template's
|
|
822
|
+
can only be paused and resumed; one the assistant set itself can be paused or removed. The picker writes a
|
|
823
|
+
weekly time (days and a time of day) in the workspace's time zone, offers only the days and hours inside
|
|
824
|
+
`customizable.schedules`, and says why a choice is out before saving. Any other cron is shown as
|
|
825
|
+
"Custom schedule" and never redrawn.
|
|
826
|
+
- **Each schedule says what it does.** A row is titled by its name (`description`), else by when it runs, and
|
|
827
|
+
its `instructions`, when it has them, are a line of their own ("What it does: …", `data-ol-schedule-does`,
|
|
828
|
+
`labels.does`): three lines at most in the default look (`--ol-schedule-does-lines`), all of it on hover.
|
|
829
|
+
- **At the limit, the sentence comes first.** When the workspace has made as many assistants as your
|
|
830
|
+
template's `customizable.agents.max` allows, the create form gives way to "You have 2 of 2 assistants.
|
|
831
|
+
Remove one to add another." (`GET /template_agents`' `agent_limit`). `POST /agents` still decides: a
|
|
832
|
+
create that loses a race gets the same sentence. Making or removing one through the kit updates every
|
|
833
|
+
`useAgents` and `useTemplateAgents` on the page.
|
|
834
|
+
- **Times read as your user's.** The next run shows in the workspace's time zone, named in words, on the
|
|
835
|
+
page's own clock: "Next run: Mon, Nov 16, 9:00 AM Eastern Time" for `locale="en-US"`, "09:00" where the clock
|
|
836
|
+
is 24-hour; "UTC" only when that is the zone. Pass `locale` so your server and the browser agree.
|
|
837
|
+
- **The schedule words are yours to reuse**, so a header of your own never copies them. All four are pure
|
|
838
|
+
(their arguments in, a string out, nothing kept), safe in a client component:
|
|
839
|
+
|
|
840
|
+
```tsx
|
|
841
|
+
import { scheduleWhen, inZone, zoneName } from "@openlegion/platform/react";
|
|
842
|
+
// s from ws.schedules.list(): "Every Mon at 9:00 AM · next: Mon, Nov 23, 9:00 AM Eastern Time"
|
|
843
|
+
const line = `${scheduleWhen(s, { when: "Every {days} at {time}" }, "en-US")} · next: ${inZone(s.next_run_at!, s.time_zone, "en-US")} ${zoneName(s.time_zone, "en-US")}`;
|
|
844
|
+
```
|
|
845
|
+
|
|
846
|
+
`scheduleWhen(schedule, labels?, locale?)` ("Mon at 9:00 AM", "Once, …", "Custom schedule"),
|
|
847
|
+
`describeWeekly(weekly, labels?, locale?)`, `inZone(iso, zone, locale?)` and `zoneName(zone, locale?, at?)`;
|
|
848
|
+
`labels` takes any of `DEFAULT_SCHEDULE_EDITOR_LABELS`. `clock(hour, minute, locale?)` and
|
|
849
|
+
`timeOfDay(date, {locale, timeZone})` are the one time-of-day helper they all use.
|
|
850
|
+
- **Unstyled**, like `<AgentChat>`: `data-ol-agent-*` and `data-ol-schedule-*` hooks, `--ol-*` variables,
|
|
851
|
+
`labels` for every string. Your own UI: `useAgents()`, `useTemplateAgents()` (with `agentLimit`),
|
|
852
|
+
`useSchedules(agentId)`, and `agentKitErrorText(err)` for the same words.
|
|
853
|
+
- **Starters are blueprints.** A template agent with `blueprint: true` is one no workspace has until someone
|
|
854
|
+
makes it. `useTemplateAgents().templateAgents?.filter((t) => t.blueprint)` is your "start from one of these"
|
|
855
|
+
list, and `useAgents().create({ template_agent: t.key })` makes one, with the blueprint's name and role unless
|
|
856
|
+
you pass your own. [Starters your customers pick from](https://platform.openlegion.ai/docs/guides/assistant-in-your-product#6-starters-your-customers-pick-from)
|
|
857
|
+
has the template's lines.
|
|
858
|
+
- **A list of agents is one call.** Each agent `useAgents()` lists carries its `role`, the one line on what
|
|
859
|
+
it is for: the person's own when they changed it, else its template agent's. `pause(id)` and `resume(id)`
|
|
860
|
+
stop and restart one (an owner or admin; a paused agent starts nothing until it is resumed), beside
|
|
861
|
+
`create`, `update` and `remove`.
|
|
862
|
+
|
|
863
|
+
#### The default look
|
|
864
|
+
|
|
865
|
+
The components work unstyled. For a presentable start, import one stylesheet once, in your root layout
|
|
866
|
+
(`npx openlegion init` does this in a new app, and the /agent page it writes imports it in any app):
|
|
867
|
+
|
|
868
|
+
```tsx
|
|
869
|
+
import "@openlegion/platform/react/styles.css";
|
|
870
|
+
```
|
|
871
|
+
|
|
872
|
+
- **Your CSS wins.** Every rule sits in `@layer openlegion` and every selector in `:where()`, so any rule of
|
|
873
|
+
yours outside a layer overrides it, at any specificity. It also holds the chat's layout (a column with
|
|
874
|
+
gaps, the message box in a row), which the components no longer set inline: without the import the chat is
|
|
875
|
+
plain blocks in your page's flow, for your own CSS to lay out.
|
|
876
|
+
- **It follows your page, not the visitor's system.** Colors come from the text color around a component
|
|
877
|
+
and from your page's `color-scheme`. A light page stays light; for dark mode, declare
|
|
878
|
+
`color-scheme: light dark` (Next.js: `export const viewport = { colorScheme: "light dark" }`).
|
|
879
|
+
- **Theme it with variables** on `:root` or on any element around a component: `--ol-accent`,
|
|
880
|
+
`--ol-on-accent`, `--ol-danger`, `--ol-border`, `--ol-control-border`, `--ol-muted`, `--ol-surface`,
|
|
881
|
+
`--ol-field`, `--ol-radius`, `--ol-gap`, `--ol-field-gap`, `--ol-small`, `--ol-control-height`,
|
|
882
|
+
`--ol-chat-height` and `--ol-chat-padding` (the transcript's scroll box and the space inside it),
|
|
883
|
+
`--ol-chat-gap`, `--ol-chat-part-gap` and `--ol-chat-tool-opacity`. A note shown after a press (a refusal,
|
|
884
|
+
"Saved.") is scrolled just into view, then stops `--ol-note-scroll-margin` (8px) from the screen's edge, plus
|
|
885
|
+
the phone's safe area at the foot. A bar of yours fixed over that edge needs more: set the variable, or your own
|
|
886
|
+
`scroll-margin` on the note. The app catalog's rows have
|
|
887
|
+
`data-ol-catalog-name` and `data-ol-catalog-icon` (the logo, or the initial when there is none).
|
|
888
|
+
- **Know when the person saw the newest message.** `onSeen({ message, at })`, on `<AgentChat>` and
|
|
889
|
+
`<AgentChatView>`, is called when the newest drawn message is in view while the page is visible and focused:
|
|
890
|
+
once per message, and again when a newer one is drawn and in view. A reply being written counts once it has
|
|
891
|
+
ended. Nothing is called while the tab is hidden, the window is not focused, or the message is scrolled out of
|
|
892
|
+
view. `message` is its id, and `at` is when it was seen. A message sent in this visit carries the chat's own id
|
|
893
|
+
until the page loads again. Each drawn message carries its id as `data-ol-message-id`. Use it for your Inbox and
|
|
894
|
+
notifications in place of watching the chat's markup.
|
|
895
|
+
- **Messages the agent sends while it works.** An agent can send your user a message while it works on their request, for example a
|
|
896
|
+
number every few seconds. Each one is its own message in the chat, where it fell in the run, with the agent's
|
|
897
|
+
reply last. The step that sent a note shows no line of its own, because the message is what your user sees. After
|
|
898
|
+
a reload, the conversation lists each message as its own row, before the reply, and the chat draws each one once:
|
|
899
|
+
on the live stream, after a reload, and when it follows a run that was already going. Each message carries its own
|
|
900
|
+
id as `data-ol-message-id` and its own `data-ol-tainted`. The bubbles of one reply also carry
|
|
901
|
+
`data-ol-part-of` with the reply's id.
|
|
902
|
+
- **An open conversation shows what arrives by itself.** A schedule's reply, a hand-off, a decision made
|
|
903
|
+
elsewhere, or a message the person sent from another tab or device (drawn with its reply under it) can land
|
|
904
|
+
while the page is open. The chat looks when the tab is shown or the window is focused, and
|
|
905
|
+
every 30 s while the tab is visible and the chat is idle. A run that is answering is followed and drawn live. If
|
|
906
|
+
nothing is running but the thread changed, the chat reads it once and draws what is new. A look is one request
|
|
907
|
+
to your route (the 204 above). There are no looks while the tab is hidden, or while a reply is being written,
|
|
908
|
+
sent or awaited. The person typing, or scrolling up to read, does not stop them. A look missed while the chat was
|
|
909
|
+
busy is taken as soon as it is idle again. After a look that found a run, or whose read did not come back, the
|
|
910
|
+
chat looks again 2 s later, so what a run wrote is read once it ends. An approval card still waiting for a
|
|
911
|
+
decision reads its approval again at each look and when the tab comes back: one request per waiting card, at
|
|
912
|
+
most one every 2 s. Decided in another tab or on the console, or expired, it says so in place of its buttons,
|
|
913
|
+
as after a reload. A decided card reads nothing. `lookEveryMs` sets the interval; `lookEveryMs={0}` turns the
|
|
914
|
+
looks off (a waiting card still reads again when the tab comes back).
|
|
915
|
+
- **The transcript stays at its newest content.** When it is a scroll box, whatever grows after it opens (a
|
|
916
|
+
card that reads itself, an image that loads, a line added on load) is followed to the end, until the person
|
|
917
|
+
scrolls up to read; then it leaves them where they are until they scroll back down. A move up lets go of the
|
|
918
|
+
end unless a row changed size in the frames just before or after it: then it is the layout's, such as the
|
|
919
|
+
browser holding what is on screen still as rows above change size, and the end is taken back. Without such a
|
|
920
|
+
change, a move is the person's whatever made it: Tab or Shift+Tab to an older link or button, find-in-page, a
|
|
921
|
+
screen reader or magnifier, or your own `scrollTo` or `scrollIntoView`. The person's own wheel, touch, scroll
|
|
922
|
+
keys, scrollbar or keyboard focus let go even while the content grows. A tap on a card's button does not
|
|
923
|
+
count. Approve or Reject on a card takes the end again once the platform
|
|
924
|
+
has the decision, wherever the card was reached from, so the reply it starts is drawn in view.
|
|
925
|
+
- **Older messages, as the person scrolls up.** When the person scrolls to the top, the chat reads the 20 messages before the oldest it shows and keeps the message they were reading where it was.
|
|
926
|
+
- A line at the top says "Loading earlier messages…" meanwhile (`earlierLoading`), and "This is the start of
|
|
927
|
+
the conversation." once there is nothing older (`earlierStart`). A page that didn't load says so, with Try
|
|
928
|
+
again (`earlierFailed`, `earlierRetry`). A screen reader hears that line, not the older messages it adds.
|
|
929
|
+
- Without the stylesheet the transcript doesn't scroll in its own box, so a "Show earlier messages" button
|
|
930
|
+
(`earlierShow`) reads the next page instead.
|
|
931
|
+
- It reads `GET {basePath}/chat/{thread}/messages?before=msg_…` as the person. A conversation that began in
|
|
932
|
+
this visit has nothing older to read, and shows no line.
|
|
933
|
+
- **Your conversation list.** `useThreads()` lists your user's conversations newest message first, so one they
|
|
934
|
+
wrote in again is at the top however old it is: `threads` (`id`, `agent`, `title`, `last_message_at`, `home`),
|
|
935
|
+
`hasMore` and `loadMore()`, `refresh()`, and `create(agent)`, which starts one and puts it first. Pass a
|
|
936
|
+
conversation's `id` to `<AgentChat threadId>`. `agent` keeps the list to one agent's.
|
|
937
|
+
- **Your agent list.** `<AgentList>` lists your user's agents for a left bar, in one read of `GET {basePath}/agents/summary`: each with its name, one unseen badge and a working mark, the open one marked.
|
|
938
|
+
- `const list = useAgentList()`, then `<AgentList list={list} open={agent} onOpen={(agent, thread) => …} onNew={…} />`. Select opens that agent's one ongoing conversation through `POST {basePath}/threads {agent, ongoing: true}` and hands it to `onOpen`: pass `thread.id` to `<AgentChat threadId>`. "New agent" is your own flow (`onNew`); without it there is no button.
|
|
939
|
+
- The badge counts the messages your user hasn't seen in that agent's conversation: the number up to 99, then "99+". The conversation open now shows none. Counting news in the agent's other conversations yourself? Pass `unseen={(agent) => count}`: your number for every row, the open one too, drawn there as on any other, so leave out the conversation on screen (0 draws none). When the newest message is in view (the moment `onSeen` is called), `<AgentChat>` records it for your user (`POST {basePath}/threads/{thread}/seen`), and every list on the page takes the new count at once. With a chat of your own, call `markSeen(thread, message)` (or `list.markSeen`) with the message's `msg_…` id. Sending a message counts as seeing everything before it.
|
|
940
|
+
- Each agent also carries `waiting` (approvals waiting for your user) and `status`. The list is read again every 30 s while the page is visible (`lookEveryMs`) and when the page comes back. Already read the agents on your server? In your server component, `const page = await ol.agents.summary()` as your user; hand the client component `{ data: page.data, has_more: page.has_more }` (plain data: the page itself carries its response), and there `useAgentList({ initial })` draws them at once, with no "Loading your agents…" before them. The next read is the usual one. A paused agent with no conversation yet can't open one, and the row says so.
|
|
941
|
+
- **Your bar around it.** `header` is drawn above the list, inside its landmark but outside the list and its keys: your mark, a name, a link home. `lastRow={{ label: "New agent", icon, onSelect }}` is your action as the list's last row, after every agent and after "Show more agents", so it stays last as pages load: a button with `onSelect` (it opens something of yours), a link with `href` (it goes somewhere). It is never an agent: no badge, never marked open. Its `ref` is the element: before a dialog of yours opens, put the focus on it, and the browser gives the focus back to it when the dialog closes. When `onSelect` opens a dialog or a menu, say so with `opens: "dialog"` (or `"menu"`): a screen reader hears it on the button (`aria-haspopup`). The kit never guesses it.
|
|
942
|
+
- **Arrow keys.** Up and Down move between the rows, your last row included; Home and End go to the first and the last. Tab still goes through them in order.
|
|
943
|
+
- **Rows as your links.** `` rowHref={(agent) => agent.ongoing_thread ? `/chat/${agent.ongoing_thread}` : null} `` makes a row your link, so a click is a navigation your app owns; pass your router's link as `linkAs` (`Link` from next/link). A row whose `rowHref` answers null stays a button that opens the conversation (making it the first time) and calls `onOpen`.
|
|
944
|
+
- **Avatars: the art is yours, never the kit's.** `avatar={(agent) => <img src={yourPictureFor(agent.agent)} alt="" />}` draws your picture before each name, in a fixed box (`--ol-avatar-size`, 1.75rem), so nothing beside it moves when the picture loads or fails. Without it, the name's first letter in a circle (`--ol-avatar-bg`, `--ol-avatar-fg`); your function answering null gets the letter too; `avatar={null}` draws none. `<AgentChat agentName="Ana" avatar={…}>` signs the agent's messages with its name after the same picture (smaller); without `agentName` they say "Agent" with no picture, as before.
|
|
945
|
+
- **Open the chat at a message or a card.** `<AgentChat openAt="apr_…">` (or a message's id) brings that card
|
|
946
|
+
or message into view once it is drawn, for example from an Inbox row. Later, `ref.current.bringIntoView(id)`
|
|
947
|
+
does the same and returns false while it is not drawn (`const ref = useRef<AgentChatHandle>(null)`, then
|
|
948
|
+
`<AgentChat ref={ref}>`). A card that fits is shown whole, else its buttons; a long message is shown from its
|
|
949
|
+
start. Either move counts as the person's own: the chat stops following the end, and follows again once they
|
|
950
|
+
scroll back to it. `openAt` does not move the chat if the person has scrolled by hand before the target was
|
|
951
|
+
drawn. A card carries its approval's id as `data-ol-approval-id`. `openAt` looks only in what the chat has
|
|
952
|
+
loaded (the newest messages, and any older pages the person scrolled back to): it doesn't page back for its
|
|
953
|
+
target, and `bringIntoView` returns false for a target not loaded. Once the history is in, `onOpenAtMissing(id)` is called, once per id, for an `openAt` the chat does not
|
|
954
|
+
hold, so you can show that approval on its own or say it could not be found.
|
|
955
|
+
- **One `fetch` for all of it.** `<AgentChat fetch={…}>` is the `fetch` every call the chat makes goes through:
|
|
956
|
+
its sends and reads, Stop, Approve and Reject, and the Connect button and vault form drawn in a reply. If your
|
|
957
|
+
route needs a header (a session token, say), add it there. It may be written inline.
|
|
958
|
+
- **Your own controls can match.** Buttons and inputs inside an element with `data-ol-theme` are drawn the
|
|
959
|
+
same way (`init` puts it on `<body>` in a new app; the /agent page it writes loads the stylesheet in any app). A form's submit button is filled, as its one action. For a
|
|
960
|
+
button that is not (a list where each row is its own small form: Talk, Pause, Forget), add
|
|
961
|
+
`data-ol-button="secondary"` and it is outlined like the rest: `<button type="submit" data-ol-button="secondary">Pause</button>`.
|
|
962
|
+
|
|
963
|
+
### 5. Wire it once
|
|
964
|
+
|
|
965
|
+
While you develop, `npx openlegion dev` does all of this for you, through your terminal. A deployed app needs its own
|
|
966
|
+
connector and webhook endpoint, and their two secrets in its env. `npx openlegion deploy` does that with the CLI's key,
|
|
967
|
+
and never prints a secret:
|
|
968
|
+
|
|
969
|
+
1. `npx openlegion deploy --url https://your.app --prepare` makes the connector and the webhook endpoint. Each secret
|
|
970
|
+
goes to your linked Vercel project's env, or to a 0600 file outside your project.
|
|
971
|
+
2. Redeploy, so your app runs with both secrets.
|
|
972
|
+
3. `npx openlegion deploy --url https://your.app` runs Test connection, pins your tools, and pushes and promotes your
|
|
973
|
+
template.
|
|
974
|
+
|
|
975
|
+
`npx openlegion deploy --url https://your.app --prepare --wait` does all three in one go: it waits for your redeploy.
|
|
976
|
+
The CLI's README has the rest.
|
|
977
|
+
|
|
978
|
+
#### Without the CLI
|
|
979
|
+
|
|
980
|
+
The same steps through this package, with a key from the console's Keys page: the `npx openlegion init` app key can't,
|
|
981
|
+
because templates, connectors and webhook endpoints are not its scopes.
|
|
982
|
+
|
|
983
|
+
1. `ol.templates.create({ slug, name })`.
|
|
984
|
+
2. `ol.connectors.create({ type: "mcp", url: "https://your.app/api/openlegion/mcp", auth: { mode: "ol_signed" }, name, slug })`.
|
|
985
|
+
Its `secret` is shown once: it is your `OPENLEGION_CONNECTOR_SECRET`.
|
|
986
|
+
3. `ol.webhookEndpoints.create({ url: "https://your.app/api/openlegion/webhooks", events: ["run.completed", "run.failed", "run.cancelled", "action.requires_approval"] })`.
|
|
987
|
+
Its `secret` is your `OPENLEGION_WEBHOOK_SECRET`.
|
|
988
|
+
4. Deploy with both secrets, then run:
|
|
989
|
+
- `ol.connectors.pin(connector.id)`, where OpenLegion lists your tools;
|
|
990
|
+
- `ol.connectors.test(connector.id)`, which checks that signed calls are answered and that a mis-signed
|
|
991
|
+
one gets 401.
|
|
992
|
+
5. `ol.templates.versions.create(slug, template.toTemplateSpec(connector))`, then `ol.templates.promote(slug, { version })`.
|
|
993
|
+
|
|
994
|
+
A complete script, run twice. The first run writes each new secret to its own 0600 file outside your
|
|
995
|
+
project and prints only its name and last 4 characters. Set both on your deployment from those files,
|
|
996
|
+
deploy, and run it again: it pins, tests, and pushes and promotes your template, and once Test connection
|
|
997
|
+
passes it deletes the files. `OPENLEGION_SECRETS_DIR` is the script's own name for where it writes them:
|
|
998
|
+
neither the SDK nor the CLI reads it, so rename it or drop it freely.
|
|
999
|
+
|
|
1000
|
+
<!-- checked: examples/next-quickstart/scripts/deploy-setup.ts -->
|
|
1001
|
+
```ts
|
|
1002
|
+
// scripts/deploy-setup.ts: APP_URL=https://your.app npx tsx scripts/deploy-setup.ts
|
|
1003
|
+
import { mkdir, rm, writeFile } from "node:fs/promises";
|
|
1004
|
+
import { homedir } from "node:os";
|
|
1005
|
+
import { join } from "node:path";
|
|
1006
|
+
import { OpenLegion, type Connector } from "@openlegion/platform";
|
|
1007
|
+
import { template } from "../openlegion/template";
|
|
1008
|
+
|
|
1009
|
+
const app = (process.env["APP_URL"] ?? "").replace(/\/+$/, "");
|
|
1010
|
+
const slug = "myapp"; // the connector's: your tools are mcp.myapp.<name>
|
|
1011
|
+
// Outside your project, so a secret is never committed or deployed as a file.
|
|
1012
|
+
const dir = process.env["OPENLEGION_SECRETS_DIR"] ?? join(homedir(), ".config", "openlegion", "secrets", slug);
|
|
1013
|
+
const ol = new OpenLegion(); // a console key: templates, connectors, webhooks
|
|
1014
|
+
|
|
1015
|
+
async function find<T>(items: AsyncIterable<T>, match: (t: T) => boolean): Promise<T | null> {
|
|
1016
|
+
for await (const t of items) if (match(t)) return t;
|
|
1017
|
+
return null;
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
/** Writes a new secret to its own 0600 file and prints only its name and last 4 characters. */
|
|
1021
|
+
async function keep(name: string, secret: string | null): Promise<void> {
|
|
1022
|
+
if (!secret) throw new Error(`No ${name} came back: rotate it (see below) and run this again.`);
|
|
1023
|
+
await mkdir(dir, { recursive: true, mode: 0o700 });
|
|
1024
|
+
const file = join(dir, name);
|
|
1025
|
+
await rm(file, { force: true }); // a new file, so it is 0600 from its first byte
|
|
1026
|
+
await writeFile(file, secret, { mode: 0o600, flag: "wx" });
|
|
1027
|
+
console.log(`${name} …${secret.slice(-4)} is in ${file}. Set it on your deployment, e.g. vercel env add ${name} production < ${file}`);
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
async function main(): Promise<void> {
|
|
1031
|
+
if (!app.startsWith("https://")) throw new Error("Set APP_URL to your deployment's https URL.");
|
|
1032
|
+
if (!(await find(ol.templates.list(), (t) => t.slug === template.slug))) await ol.templates.create({ slug: template.slug, name: template.name });
|
|
1033
|
+
|
|
1034
|
+
let made = false;
|
|
1035
|
+
let connector: Connector | null = await find(ol.connectors.list(), (c) => c.slug === slug);
|
|
1036
|
+
if (!connector) {
|
|
1037
|
+
const created = await ol.connectors.create({ type: "mcp", url: `${app}/api/openlegion/mcp`, auth: { mode: "ol_signed" }, name: "My app", slug });
|
|
1038
|
+
connector = created;
|
|
1039
|
+
await keep("OPENLEGION_CONNECTOR_SECRET", created.secret);
|
|
1040
|
+
made = true;
|
|
1041
|
+
}
|
|
1042
|
+
const hooks = `${app}/api/openlegion/webhooks`;
|
|
1043
|
+
if (!(await ol.webhookEndpoints.list()).data.some((e) => e.url === hooks)) {
|
|
1044
|
+
const created = await ol.webhookEndpoints.create({ url: hooks, events: ["run.completed", "run.failed", "run.cancelled", "action.requires_approval"] });
|
|
1045
|
+
await keep("OPENLEGION_WEBHOOK_SECRET", created.secret);
|
|
1046
|
+
made = true;
|
|
1047
|
+
}
|
|
1048
|
+
if (made) {
|
|
1049
|
+
console.log("Deploy with these secrets, then run this again.");
|
|
1050
|
+
return;
|
|
1051
|
+
}
|
|
1052
|
+
|
|
1053
|
+
await ol.connectors.pin(connector.id);
|
|
1054
|
+
const test = await ol.connectors.test(connector.id);
|
|
1055
|
+
if (!test.ok) throw new Error("Test connection failed: is the deployment using the connector's secret?");
|
|
1056
|
+
await rm(dir, { recursive: true, force: true }); // your deployment holds them now: the files go
|
|
1057
|
+
const version = await ol.templates.versions.create(template.slug, template.toTemplateSpec(connector));
|
|
1058
|
+
await ol.templates.promote(template.slug, { version: version.version });
|
|
1059
|
+
console.log(`Promoted ${template.slug}@${version.version}.`);
|
|
1060
|
+
}
|
|
1061
|
+
|
|
1062
|
+
main().catch((err: unknown) => {
|
|
1063
|
+
console.error(err instanceof Error ? err.message : err);
|
|
1064
|
+
process.exitCode = 1;
|
|
1065
|
+
});
|
|
1066
|
+
```
|
|
1067
|
+
|
|
1068
|
+
A lost secret is replaced with `ol.connectors.rotateSecret(id, { expires_in_seconds: 0 })` or
|
|
1069
|
+
`ol.webhookEndpoints.rotateSecret(id, { expires_in_seconds: 0 })`. Don't print a secret, even once: it
|
|
1070
|
+
stays in your terminal's scrollback and in any CI log.
|
|
1071
|
+
|
|
1072
|
+
## The client
|
|
1073
|
+
|
|
1074
|
+
```ts
|
|
1075
|
+
import { OpenLegion } from "@openlegion/platform";
|
|
1076
|
+
|
|
1077
|
+
const ol = new OpenLegion(); // env OPENLEGION_API_KEY; OPENLEGION_BASE_URL, default https://api.openlegion.ai/platform/v1
|
|
1078
|
+
|
|
1079
|
+
// Create-or-get on external_ref: safe to repeat. Keep ws.id on your customer's row.
|
|
1080
|
+
const ws = await ol.workspaces.create({ external_ref: customer.id, name: customer.name, template: "support" });
|
|
1081
|
+
|
|
1082
|
+
const scoped = ol.workspace(ws.id, { subject: user.id }); // OpenLegion-Workspace (+ OpenLegion-Subject) on every call
|
|
1083
|
+
const thread = await scoped.threads.create({ agent: agentId });
|
|
1084
|
+
|
|
1085
|
+
const page = await scoped.threads.list({ limit: 10 }); // one page: page.data, page.has_more
|
|
1086
|
+
for await (const t of scoped.threads.list()) {
|
|
1087
|
+
// every item, page after page
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
// What a run's agent did, newest first: tool calls with their status and receipt.
|
|
1091
|
+
const actions = await scoped.actions.list({ run: runId });
|
|
1092
|
+
// Your template's versions, newest first: what `npx openlegion dev` and `npx openlegion templates push` made.
|
|
1093
|
+
const versions = await ol.templates.versions.list(template.slug);
|
|
1094
|
+
```
|
|
1095
|
+
|
|
1096
|
+
- **Money.** A credit is $0.001 (1,000 µ$). What you set and read in limits, grants, budgets and balances is in
|
|
1097
|
+
credits (`period_credit_cap`, `budget.run_credits`). What something actually cost is `cost_micro`, in
|
|
1098
|
+
millionths of a dollar, on a run, an action's receipt and a usage row: `cost_micro: 432` is 0.432
|
|
1099
|
+
credits. A usage row carries both: `credits`, rounded up, and the exact `cost_micro`. A run carries both
|
|
1100
|
+
too, its `credits` exact (`cost_micro / 1000`), so runs add up; usage adds work that belongs to no run
|
|
1101
|
+
(memory upkeep, voice). A running run reads its spend so far, and when one reply answered several
|
|
1102
|
+
messages the earliest run carries the charge and the others read 0.
|
|
1103
|
+
|
|
1104
|
+
- **Retries.** A call that is safe to retry is retried (`maxRetries`, default 2). A POST is retried with
|
|
1105
|
+
the same `Idempotency-Key`. To make a POST idempotent across your own retries, pass
|
|
1106
|
+
`{ idempotencyKey }`.
|
|
1107
|
+
- **Errors.** Every error is an `OpenLegionError`. The subclass says which kind:
|
|
1108
|
+
- `InvalidRequestError` (look at `param`), `NotFoundError`, `ConflictError`;
|
|
1109
|
+
- `AuthenticationError`, `PermissionError`;
|
|
1110
|
+
- `RateLimitError`;
|
|
1111
|
+
- `RefusalError`;
|
|
1112
|
+
- `APIConnectionError`.
|
|
1113
|
+
|
|
1114
|
+
Each error carries `type`, `code`, `status` and `request_id`. Quote `request_id` to support. A
|
|
1115
|
+
`RefusalError`'s `message` is written for your end user; its `partner_message` is written for you (what
|
|
1116
|
+
happened, what to do: top up, resume). Log that one.
|
|
1117
|
+
- **Response details.** Every result except a stream has `lastResponse`, with `status`, `requestId`, `idempotentReplayed`
|
|
1118
|
+
and `headers`.
|
|
1119
|
+
|
|
1120
|
+
### Streams
|
|
1121
|
+
|
|
1122
|
+
```ts
|
|
1123
|
+
const stream = await scoped.messages.stream(thread.id, { content: "Where is order A-1001?" });
|
|
1124
|
+
for await (const part of stream) {
|
|
1125
|
+
if (part.type === "text-delta") process.stdout.write(String(part.delta));
|
|
1126
|
+
}
|
|
1127
|
+
// or, from your own route, straight to useChat:
|
|
1128
|
+
return stream.toResponse();
|
|
1129
|
+
```
|
|
1130
|
+
|
|
1131
|
+
- A stream is the AI SDK UI message stream, so the parts are AI SDK UI message chunks. It carries no
|
|
1132
|
+
reasoning: the model's reasoning is not sent, live or on a replay. A finished stream ends with a
|
|
1133
|
+
`message-metadata` part `{ tainted }` (see "Rendering replies safely").
|
|
1134
|
+
- When the connection is cut short, the reader re-attaches by itself (`Last-Event-ID`). You see each part
|
|
1135
|
+
once, in order.
|
|
1136
|
+
- `scoped.runs.stream(runId)` follows a run you started elsewhere.
|
|
1137
|
+
- `scoped.threads.attach(threadId)` returns the thread's running answer, or null if there is none.
|
|
1138
|
+
- Closing a stream never cancels its run. Only `runs.cancel(id)` does.
|
|
1139
|
+
|
|
1140
|
+
### Files a person attaches
|
|
1141
|
+
|
|
1142
|
+
```ts
|
|
1143
|
+
const file = await scoped.files.create({ thread: thread.id, name: "receipt.pdf", type: "application/pdf", body: bytes });
|
|
1144
|
+
await scoped.messages.create(thread.id, { content: "Here is my receipt.", attachments: [file.id] });
|
|
1145
|
+
```
|
|
1146
|
+
|
|
1147
|
+
- A file is an image (PNG, JPEG, WebP or GIF), a PDF, or a text file (plain text, Markdown, CSV or JSON), at
|
|
1148
|
+
most 4 MB. The type is checked against the bytes. A message carries at most 5. A workspace uploads at most
|
|
1149
|
+
500 files in any 24 hours; past that, the upload is `429 rate_limited`.
|
|
1150
|
+
- Upload it for the thread it goes in, as the person who sends it. A file is sent once.
|
|
1151
|
+
- The agent needs `files.read_attachment` in its template's tools (the starter and the template `openlegion
|
|
1152
|
+
init` writes have it). It reads a file as untrusted content: nothing in the file counts as your user's
|
|
1153
|
+
instruction, and the run is marked tainted from that read on. For OpenLegion's built-in tools a tainted run is
|
|
1154
|
+
contained tool by tool: each one either waits for a person's approval, runs under the egress rules, or is
|
|
1155
|
+
refused, and [the tools reference](https://platform.openlegion.ai/docs/platform-tools) says which. A tool of
|
|
1156
|
+
yours follows what it declares: with `requiresApproval: true` every call waits for a person; without it the
|
|
1157
|
+
call runs with `ctx.tainted` true, so your tool can refuse it (`refuseIfTainted(ctx)`) or hold it in your
|
|
1158
|
+
product.
|
|
1159
|
+
- Erasing the person (`ol.subjects.delete`) deletes their files.
|
|
1160
|
+
|
|
1161
|
+
## Verifying OpenLegion yourself
|
|
1162
|
+
|
|
1163
|
+
The route does all of this for you. To verify by hand:
|
|
1164
|
+
|
|
1165
|
+
```ts
|
|
1166
|
+
import { verifyOpenLegionRequest, webhooks } from "@openlegion/platform";
|
|
1167
|
+
|
|
1168
|
+
// A webhook: the raw body, exactly as received.
|
|
1169
|
+
const event = await webhooks.constructEvent(await req.text(), req.headers, process.env.OPENLEGION_WEBHOOK_SECRET!);
|
|
1170
|
+
|
|
1171
|
+
// A call to your own MCP server (OpenLegion-Signature over the exact bytes).
|
|
1172
|
+
const verified = await verifyOpenLegionRequest(req, process.env.OPENLEGION_CONNECTOR_SECRET!);
|
|
1173
|
+
if (!verified.ok) return new Response(null, { status: 401 });
|
|
1174
|
+
verified.context.external_ref; // the customer the call is for
|
|
1175
|
+
```
|
|
1176
|
+
|
|
1177
|
+
- `constructEvent` throws `SignatureVerificationError`, whose `reason` says what was wrong.
|
|
1178
|
+
- `verifyOpenLegionRequest` returns `{ ok: false, reason }` and never throws on a bad signature.
|
|
1179
|
+
|
|
1180
|
+
## Testing
|
|
1181
|
+
|
|
1182
|
+
`@openlegion/platform/testing` signs requests the way OpenLegion does, so you can test your route
|
|
1183
|
+
in-process:
|
|
1184
|
+
|
|
1185
|
+
- `signOpenLegionRequestForTest({ secret, body, context })`;
|
|
1186
|
+
- `signWebhookForTest({ payload, secret })`.
|
|
1187
|
+
|
|
1188
|
+
## License
|
|
1189
|
+
|
|
1190
|
+
Apache-2.0
|