@nylorun/agents 0.9.0-beta → 0.11.0-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/CHANGELOG.md +165 -0
  2. package/README.md +296 -77
  3. package/dist/a2a/handler.d.ts +59 -0
  4. package/dist/a2a/handler.js +178 -0
  5. package/dist/a2a/index.d.ts +8 -0
  6. package/dist/a2a/index.js +7 -0
  7. package/dist/access.d.ts +101 -0
  8. package/dist/access.js +111 -0
  9. package/dist/action-handler.d.ts +63 -0
  10. package/dist/action-handler.js +279 -0
  11. package/dist/ag-ui/handler.d.ts +12 -4
  12. package/dist/ag-ui/handler.js +87 -281
  13. package/dist/ag-ui/index.d.ts +2 -1
  14. package/dist/ag-ui/index.js +2 -1
  15. package/dist/browser.d.ts +97 -0
  16. package/dist/browser.js +277 -0
  17. package/dist/client.d.ts +3 -230
  18. package/dist/client.js +3 -361
  19. package/dist/connection.d.ts +4 -4
  20. package/dist/connection.js +16 -25
  21. package/dist/delivery-token.d.ts +62 -0
  22. package/dist/delivery-token.js +159 -0
  23. package/dist/execute-action.d.ts +6 -0
  24. package/dist/execute-action.js +24 -0
  25. package/dist/http.d.ts +34 -3
  26. package/dist/http.js +68 -16
  27. package/dist/index.d.ts +10 -8
  28. package/dist/index.js +4 -4
  29. package/dist/sandbox/client.d.ts +4 -5
  30. package/dist/sandbox/client.js +4 -8
  31. package/dist/sandbox/index.d.ts +0 -2
  32. package/dist/sandbox/index.js +0 -1
  33. package/dist/served-definitions.d.ts +20 -0
  34. package/dist/served-definitions.js +100 -0
  35. package/dist/session-client.d.ts +282 -0
  36. package/dist/session-client.js +375 -0
  37. package/dist/sse.js +12 -0
  38. package/dist/studio-embed.d.ts +9 -0
  39. package/dist/studio-embed.js +8 -0
  40. package/dist/token-endpoint.d.ts +23 -0
  41. package/dist/token-endpoint.js +30 -0
  42. package/package.json +15 -8
  43. package/dist/ag-ui/history.d.ts +0 -7
  44. package/dist/ag-ui/history.js +0 -60
  45. package/dist/ag-ui/sse.d.ts +0 -9
  46. package/dist/ag-ui/sse.js +0 -7
  47. package/dist/ag-ui/translate.d.ts +0 -38
  48. package/dist/ag-ui/translate.js +0 -222
  49. package/dist/derived-credentials.d.ts +0 -5
  50. package/dist/derived-credentials.js +0 -17
  51. package/dist/executor.d.ts +0 -20
  52. package/dist/executor.js +0 -417
package/README.md CHANGED
@@ -1,44 +1,64 @@
1
1
  # @nylorun/agents
2
2
 
3
- Tenant API client package: definition authoring, a session client, and a
4
- connected customer executor. Depends only on `@nylorun/core` among Nylorun
3
+ Tenant API client package: definition authoring, a session client, and the
4
+ Action endpoint that runs your tools (`createActionHandler`). Depends only on `@nylorun/core` among Nylorun
5
5
  packages. A developer application's production tree should contain only this
6
6
  package and `@nylorun/core` from Nylorun. Vocabulary:
7
7
  [runtime/src/CONTEXT.md](../runtime/src/CONTEXT.md).
8
8
 
9
- ## Application entry (preferred)
9
+ ## Application entry (preferred): an Action endpoint
10
10
 
11
11
  ```ts
12
12
  // src/main.ts
13
- import { connectAgents } from "@nylorun/agents";
13
+ import { createServer } from "node:http";
14
+ import { createActionHandler } from "@nylorun/agents";
14
15
  import { agents } from "../agents/index.js";
15
16
 
16
- await connectAgents({ agents }).ready;
17
+ const url = process.env.NYLORUN_ACTIONS_URL ?? "http://localhost:3001/nylorun/actions";
18
+ const actions = createActionHandler({ agents, url });
19
+ createServer(actions.node).listen(3001); // or actions.fetch in Hono, Next.js, Workers, Bun
20
+ await actions.register({ url });
17
21
  ```
18
22
 
19
- Application mode saves definitions, registers **derived** executor credentials
20
- (HMAC of the application key + Tenant + agent id), and connects. Restarts and
21
- replicas re-register the same hashes; tokens are never stored in the Project.
22
- The same entry runs under the project's `npm run dev` (`tsx watch`) and as
23
- `node dist/src/main.js` (`npm start`). It finds the Runtime through the three
24
- `NYLORUN_*` variables or the Project link that `npx @nylorun/cli tenant create`
25
- writes; with neither, it fails with `connection_missing` and names those steps. See [MIGRATION.md](../MIGRATION.md#runtime-clients-and-admin-api-breaking-beta)
23
+ The Runtime delivers each tool call, hook and workflow function of these agents
24
+ to `url`, signed with a short-lived **delivery token** that the handler checks
25
+ (Tenant, URL, Action, generation and body) before any code runs. `register`
26
+ saves the definitions, registers the URL and pings it through the Runtime. A
27
+ process that only serves Actions needs no key: pass `runtime: { url }` and it
28
+ reads the Tenant's public keys. Mark a long tool
29
+ `tool({ …, background: true })`: the handler answers at once, heartbeats and
30
+ posts the result. `npx @nylorun/cli endpoints` shows each endpoint and how its
31
+ deliveries are doing.
32
+
33
+ The URL must be one the Runtime can reach: `localhost` on the local stack
34
+ (its Runtime runs in Docker and maps `localhost` to this machine), a public URL
35
+ in production, or a tunnel (ngrok, Cloudflare Tunnel) for a remote Runtime.
36
+
37
+ `connectAgents` and executors were removed in protocol 3: mount
38
+ `createActionHandler` instead (see [MIGRATION.md](../MIGRATION.md)). The handler
39
+ finds the Runtime through the two `NYLORUN_*` variables or the Project link
40
+ that `npx nylorun start` writes; with neither, `register` fails with
41
+ `connection_missing` and names those steps. See [MIGRATION.md](../MIGRATION.md#runtime-clients-and-admin-api-breaking-beta)
26
42
  for upgrading from `nylorun serve`.
27
43
 
28
44
  ## Connection resolution
29
45
 
30
- `resolveConnection` / `createClient()` / `connectAgents({ agents })`:
46
+ `resolveConnection` / `createClient()` / `createActionHandler({ agents })`:
31
47
 
32
- 1. Explicit `{ url, tenant, key }`
33
- 2. Environment — if any of `NYLORUN_RUNTIME_URL`, `NYLORUN_TENANT`,
34
- `NYLORUN_SERVER_KEY` or `NYLORUN_EXECUTOR_KEY` is set, all required pieces
35
- must be present (role `executor` when `NYLORUN_EXECUTOR_KEY` is set)
36
- 3. Project link — `.nylorun/link.json` + `credentials.json` (application role)
48
+ 1. Explicit `{ url, key }`
49
+ 2. Environment — if `NYLORUN_RUNTIME_URL` or `NYLORUN_SERVER_KEY` is set, both
50
+ must be present
51
+ 3. Project link — `.nylorun/link.json` + `credentials.json` (the application
52
+ key), written by `npx nylorun start`. A link from before one Tenant per
53
+ installation (format 0 or 1) fails with `connection_missing`: run
54
+ `npx nylorun start` in the project again.
37
55
 
38
- Sources never mix. Partial environment fails with `connection_missing`.
56
+ Sources never mix. Partial environment fails with `connection_missing`. A
57
+ Runtime serves one Tenant, so nothing names it: the `tenant` option and
58
+ `NYLORUN_TENANT` are gone (protocol 5).
39
59
 
40
60
  ```ts
41
- import { Agent, createClient, connectAgents, tool } from "@nylorun/agents";
61
+ import { Agent, createActionHandler, createClient, tool } from "@nylorun/agents";
42
62
  import { z } from "zod";
43
63
 
44
64
  const assistant = Agent({ id: "assistant", name: "Assistant" })
@@ -57,7 +77,6 @@ const assistant = Agent({ id: "assistant", name: "Assistant" })
57
77
  const client = createClient({
58
78
  url: process.env.NYLORUN_RUNTIME_URL,
59
79
  key: process.env.NYLORUN_SERVER_KEY,
60
- tenant: process.env.NYLORUN_TENANT,
61
80
  });
62
81
  await client.saveAgent(assistant, { implementationVersion: "app-1" });
63
82
  const session = await client.createSession({
@@ -67,28 +86,28 @@ const session = await client.createSession({
67
86
  await session.input("Look up item 123", { idempotencyKey: requestId });
68
87
  const history = await session.history();
69
88
 
70
- // Executor-only mode when you already hold an executor key:
71
- const connection = connectAgents({
89
+ // A process that only serves Actions holds no key: it reads the Tenant's public keys.
90
+ const actions = createActionHandler({
72
91
  agents: [assistant],
73
92
  implementationVersion: "app-1",
74
- runtime: {
75
- url: process.env.NYLORUN_RUNTIME_URL,
76
- key: process.env.NYLORUN_EXECUTOR_KEY,
77
- tenant: process.env.NYLORUN_TENANT,
78
- },
93
+ runtime: { url: process.env.NYLORUN_RUNTIME_URL! },
94
+ url: "https://app.example.com/nylorun/actions",
79
95
  onError: console.error,
80
96
  });
81
- await connection.ready;
82
- await connection.close();
97
+ app.post("/nylorun/actions", actions.node);
98
+ // A deploy step with the application key registers the URL once:
99
+ await createActionHandler({ agents: [assistant], client }).register({
100
+ url: "https://app.example.com/nylorun/actions",
101
+ });
83
102
  ```
84
103
 
85
104
  ```sh
86
105
  eval "$(npx @nylorun/cli env)"
87
- # → NYLORUN_RUNTIME_URL, NYLORUN_SERVER_KEY, NYLORUN_TENANT
106
+ # → NYLORUN_RUNTIME_URL, NYLORUN_SERVER_KEY
88
107
  ```
89
108
 
90
- Every request sets `Nylorun-Tenant` and `Nylorun-Protocol`. A `tenant` field in a
91
- body or query is never read from caller input. Before the first authenticated
109
+ Every request sets `Nylorun-Protocol` (5) and no `Nylorun-Tenant`: the Runtime
110
+ serves one Tenant. Before the first authenticated
92
111
  request, `Transport` fetches `/health` once, checks protocol compatibility, and
93
112
  throws `IncompatibleRuntimeError` / `incompatible_host` when the Host range or
94
113
  required features do not match. Re-exports include `PROTOCOL_FEATURES`,
@@ -121,28 +140,22 @@ const assistant = Agent({ id: "assistant", name: "Assistant" })
121
140
 
122
141
  Each key names a server; its `name` defaults to the key and, when given, must equal it. Repeated `.mcp()` calls add servers to the same capability. Transports follow [Agent Plugins MCP servers](https://agent-plugins.org/plugin-authors/mcp-servers): `stdio`, `streamable-http`, and `sse`. Attach an Agent Plugin package with `.plugin(path)`.
123
142
 
124
- Give an agent an isolated computer with `.sandbox()`:
143
+ Give a session a sandbox when you open it. The agent declares nothing, so the same agent runs with or without one, in any Tenant:
125
144
 
126
145
  ```ts
127
- import { Agent } from "@nylorun/agents";
128
-
129
- const analyst = Agent({ id: "analyst" })
130
- .instructions("Analyse the data the user gives you. Use Python.")
131
- .sandbox();
146
+ const session = await client.createSession({
147
+ agentId: "analyst",
148
+ ownerUserId,
149
+ sandbox: {
150
+ network: { allow: ["pypi.org", "files.pythonhosted.org"] }, // no egress unless you list hosts
151
+ resources: { cpus: 2, memory: "2GiB" },
152
+ },
153
+ });
132
154
  ```
133
155
 
134
- The model gets `bash`, `read`, `write`, `edit`, `grep` and `glob` on a Linux machine with a persistent `/workspace`. These tools run in the Runtime, not in your process, so sandbox-only agents need no connected executor. The agent declares what it needs; the Runtime decides where it runs (today an emulated shell in the Runtime process). Every option is optional plain data:
156
+ The model gets `bash`, `read`, `write`, `edit`, `grep` and `glob` on a persistent `/workspace`. These tools run in the Runtime, not in your process, so sandbox-only agents need no Action endpoint. The Runtime decides where the sandbox runs: today an emulated shell in the Runtime process, which is not a VM boundary and takes no `image`.
135
157
 
136
- ```ts
137
- .sandbox({
138
- image: "python:3.13", // any OCI image; default python:3.13-slim
139
- network: { preset: "dev", allow: ["api.example.com"] }, // "none" | "dev" (default) | "open"
140
- resources: { cpus: 2, memory: "2GiB" },
141
- idle: "15m", // stop compute when idle; files persist
142
- })
143
- ```
144
-
145
- The `dev` preset allows package registries and code hosts. Private networks, loopback, the host and cloud metadata endpoints are always blocked. Options from the full design that are not in this version (`setup`, `files`, `secrets`, `mount`, `onStart`, …) throw a `SandboxError` that says so.
158
+ `sandbox` takes `false` for none, `{ session }` to share another session's sandbox, or an inline sandbox as above; omit it for the Tenant's default. The Runtime checks it against the Tenant's limits (`GET`/`PUT /v1/tenant/sandbox`: a network ceiling, a resource maximum, the idle timeout) and answers `400` with every problem it finds. A caller acting for a user (`app.as(...)`) can't define one inline; it gets the Tenant's default or `false`. Private networks, loopback, the host and cloud metadata endpoints are always blocked.
146
159
 
147
160
  Add an agent with `.subagents()` to let the model delegate to it:
148
161
 
@@ -167,9 +180,9 @@ const support = Agent({ id: "support" })
167
180
  .subagents(researcher);
168
181
  ```
169
182
 
170
- The tool is named after the agent's `id` and takes `{ task: string }`; the agent's `description` (required) is what the parent's model reads to decide when to delegate. The child starts with a fresh context: it sees its own instructions and the task, nothing of the parent's conversation, and only its final text (or `outputSchema` result) comes back. It keeps its own tools, hooks, skills and MCP servers, served by the executor you already run for the parent (`connectAgents({ agents: [support] })` serves both), shares the session's sandbox, and starts with empty `ctx.state`. Tools can read `ctx.agent` (`{ id, path, delegationId }`). Several delegation calls in one model response run in parallel. An empty answer, a failure (with the child's last text marked as evidence) or a cancelled child reaches the parent's model as a failed tool result, never as success. The Runtime emits `delegation.started` and `delegation.completed`; `session.history({ agent })` filters by `delegationId` (one child invocation) or by path such as `support/researcher` (every concurrent child that shares that path).
183
+ The tool is named after the agent's `id` and takes `{ task: string }`; the agent's `description` (required) is what the parent's model reads to decide when to delegate. The child starts with a fresh context: it sees its own instructions and the task, nothing of the parent's conversation, and only its final text (or `outputSchema` result) comes back. It keeps its own tools, hooks, skills and MCP servers, served by the Action endpoint you already mount for the parent (`createActionHandler({ agents: [support] })` serves both), shares the session's sandbox, and starts with empty `ctx.state`. Tools can read `ctx.agent` (`{ id, path, delegationId }`). Several delegation calls in one model response run in parallel. An empty answer, a failure (with the child's last text marked as evidence) or a cancelled child reaches the parent's model as a failed tool result, never as success. The Runtime emits `delegation.started` and `delegation.completed`; `session.history({ agent })` filters by `delegationId` (one child invocation) or by path such as `support/researcher` (every concurrent child that shares that path).
171
184
 
172
- A flow agent can be a subagent too: `.subagents(researchFlow)` with a `description` like any other. Its manifest is inlined in the parent's, so it is saved with the parent and served by the parent's executor. When the model calls it, the flow runs on the Runtime in its own linked session (a fresh one per call, linked from the parent's with a `node.agent` event at `support/<flow id>`), its agents in theirs, and the flow's output comes back as the tool result; a failed flow is a failed tool result. Cancelling the parent cancels the flow. Flow agents as subagents run on the Runtime only, not in a local `run()`. An approval asked for inside the flow waits on the flow's own session.
185
+ A flow agent can be a subagent too: `.subagents(researchFlow)` with a `description` like any other. Its manifest is inlined in the parent's, so it is saved with the parent and served by the parent's Action endpoint. When the model calls it, the flow runs on the Runtime in its own linked session (a fresh one per call, linked from the parent's with a `node.agent` event at `support/<flow id>`), its agents in theirs, and the flow's output comes back as the tool result; a failed flow is a failed tool result. Cancelling the parent cancels the flow. Flow agents as subagents run on the Runtime only, not in a local `run()`. An approval asked for inside the flow waits on the flow's own session.
173
186
 
174
187
  Delegate when the parent should keep the answer. When a specialist should own the rest of the conversation, switch capabilities with a `.beforeModel()` patch instead. This version is one level deep and non-interactive: a delegated agent cannot use agents as tools, its tools cannot declare `approval` (keep those on the parent), and `ctx.ask`, `ctx.approve`, `ctx.sleep` or `ctx.waitFor` inside it fail with `delegation.interaction-unsupported`. Delegation is not an approval boundary; approvals live on tools.
175
188
 
@@ -247,10 +260,10 @@ Name the stages you may reorder.
247
260
  `Chain`, `Switch`, `Parallel`, `Map` and `Loop` still build workflow manifest v1
248
261
  directly and run as before; a flow agent can't be a child of them.
249
262
 
250
- The agents in a flow share one sandbox: declare it with `.sandbox(spec)` on the
251
- flow agent and give the agents that use it `.sandbox()` with no options (an agent
252
- that declares its own spec must match), attach with `createSession({ …, sandbox: { session } })`, call
253
- built-ins via `session.sandbox` (application) or `ctx.sandbox` (executor).
263
+ The agents in a flow share one sandbox: open the flow's session with it,
264
+ `createSession({ …, sandbox: { … } })`, and every agent, tool step and `verify` in the
265
+ flow uses it. Share it with another session with `sandbox: { session }`, and call
266
+ built-ins via `session.sandbox` (application) or `ctx.sandbox` (a tool).
254
267
  Observe with `session.observe({ follow: true })` to merge linked agent streams;
255
268
  `pending()` lists waits across the tree. Studio renders the manifest tree and
256
269
  live node status. Source examples:
@@ -263,23 +276,32 @@ Use `session.observe({ cursor, signal })` for resumable canonical events, `sessi
263
276
 
264
277
  Connection defaults follow `resolveConnection` (options → environment → Project
265
278
  link). Implementation version defaults from `NYLORUN_IMPLEMENTATION_VERSION`,
266
- then `dev`. Application mode of `connectAgents({ agents })` registers derived
267
- executor principals; executor-only mode still takes an explicit executor key.
268
- Agents do not hash the manifest, and an in-flight action stays claimable after
279
+ then `dev`. `register` saves the definitions and registers one endpoint per
280
+ served agent with the application key; serving deliveries needs no key.
281
+ Agents do not hash the manifest, and an in-flight action is still delivered after
269
282
  the registered digest changes. Model selection and model credentials belong to
270
283
  the Tenant.
271
284
 
272
- After registration, `connectAgents` opens authenticated fetch SSE before discovering actions, rediscovers after reconnection, and claims pending actions for a connected agent id. It renews leases while executing, then retries HTTP result delivery with the same recorded outcome and idempotency key. Reconnect delay is bounded at 30 seconds. Notifications confer no execution authority. There is no periodic action-discovery polling. Close aborts the stream, HTTP requests and lease timers and signals running functions; JavaScript cannot forcibly terminate a function that ignores its signal. The host makes expired in-flight actions uncertain instead of automatically repeating external effects.
285
+ After registration, the Runtime POSTs each Action to the endpoint with a delivery token signed by the Tenant's key; the handler verifies it before any code runs and answers with the outcome. A background tool answers `202`, heartbeats with the newest token and posts its result. A cancel aborts the request, which reaches the tool as `ctx.signal`; JavaScript cannot forcibly terminate a function that ignores its signal. The host makes lost in-flight deliveries uncertain instead of automatically repeating external effects.
273
286
 
274
- Tools receive state, info, identity, resume, signal, approval/response helpers and memoized `step`. Step outcomes survive a persisted wait result; they do not establish exactly-once external effects after an unacknowledged crash. `sleep` and `waitFor` currently return inspectable deferred outcomes; automatic timer/event wakeups remain runtime implementation work. Remote `onModelCall` convenience and progress-event transport are not supplied in this pass. Arbitrary middleware closures are rejected for durable definitions; use `before`/`after` hooks. The executor runs every capability registered at a hook point in one action. Agent definitions have no `.run()`; explicit local execution is available through `@nylorun/harness/run`.
287
+ Tools receive state, info, identity, resume, signal, approval/response helpers and memoized `step`. Step outcomes survive a persisted wait result; they do not establish exactly-once external effects after an unacknowledged crash. `sleep` and `waitFor` currently return inspectable deferred outcomes; automatic timer/event wakeups remain runtime implementation work. Remote `onModelCall` convenience and progress-event transport are not supplied in this pass. Arbitrary middleware closures are rejected for durable definitions; use `before`/`after` hooks. The Action endpoint runs every capability registered at a hook point in one action. Agent definitions have no `.run()`; explicit local execution is available through `@nylorun/harness/run`.
275
288
 
276
289
  ## AG-UI
277
290
 
278
- `@nylorun/agents/ag-ui` serves the Tenant's agents to any
279
- [AG-UI](https://docs.ag-ui.com) client (`@ag-ui/client`'s `HttpAgent`,
280
- CopilotKit, a desktop renderer) from your own server. Your server signs people
281
- in and names the person each request is for; the handler maps each AG-UI thread
282
- to one session per person, agent and thread, and streams it as AG-UI events.
291
+ The Runtime serves the Tenant's agents to any [AG-UI](https://docs.ag-ui.com)
292
+ client (`@ag-ui/client`'s `HttpAgent`, CopilotKit, a desktop renderer) at
293
+ `/v1/ag-ui/agents/{agentId}` (optional feature `ag-ui-endpoint`). Each AG-UI
294
+ thread is one session per person, agent and thread. There are two ways in:
295
+
296
+ - **From your own server**, with `@nylorun/agents/ag-ui` (below): your server
297
+ signs people in and the handler forwards each request to the Runtime acting
298
+ for that person. The browser never sees the Runtime.
299
+ - **From the page itself**, with `@nylorun/agents/browser`'s `agUi()` and a
300
+ subject token ([In the browser](#in-the-browser)). No chat traffic passes
301
+ through your server.
302
+
303
+ Both reach the same threads: one started through the handler continues from
304
+ the page.
283
305
 
284
306
  ```ts
285
307
  import { createServer } from "node:http";
@@ -305,9 +327,10 @@ createServer(toNodeListener(agui)).listen(3000);
305
327
 
306
328
  `run`, `history`, `reattach` and `cancel` are also on the handler for your own
307
329
  routing. The default `client` is `createClient()`; pass `client` to use another
308
- one, and `session(subject, agentId)` to add the person's `vaultIds` or
309
- `credentialSelections` (keep `info` stable: it is part of the session's
310
- identity).
330
+ one, and `session(subject, agentId)` to add the person's `vaultIds`,
331
+ `credentialSelections` or `info`. They apply when the thread's session is
332
+ created, on its first run; later runs keep them. Whatever the browser sends in
333
+ `forwardedProps.nylorun` is replaced.
311
334
 
312
335
  - Each AG-UI message id is the command's idempotency key: a retried run replays
313
336
  the same turn instead of starting a second one.
@@ -325,9 +348,9 @@ identity).
325
348
  `scopes` defaults to `["sessions:own"]`; add `"vaults:own"` when `session()`
326
349
  attaches the person's vaults. A `subject` the Runtime cannot name (see below)
327
350
  answers `500` (`subject_invalid`).
328
- - The handler needs a Runtime with the optional features `transcript-events`
329
- and `subject-headers` and answers `502` (`runtime_feature_missing`) without
330
- them.
351
+ - The handler needs a Runtime with the optional feature `ag-ui-endpoint` and
352
+ answers `502` (`runtime_feature_missing`) without it. It loads no AG-UI
353
+ package itself: the Runtime does the protocol work.
331
354
 
332
355
  A complete web backend with a test is in
333
356
  [examples/src/ag-ui](../examples/README.md#an-agent-in-your-web-app-ag-ui).
@@ -336,8 +359,71 @@ Limitations: assistant text arrives once per model step (no token streaming);
336
359
  no reasoning, state, activity or subagent events, and an agent used as a tool
337
360
  shows only its result; frontend tools in `RunAgentInput.tools` are rejected
338
361
  (`400`); one text part per user message; earlier messages cannot be edited or
339
- regenerated. Browsers always go through your server: never let one call the
340
- Runtime directly.
362
+ regenerated. A browser reaches the Runtime only with a subject token and a
363
+ publishable key, never with a Tenant key.
364
+
365
+ ## A2A
366
+
367
+ `@nylorun/agents/a2a` serves the Tenant's agents to other agents over
368
+ [A2A](https://a2a-protocol.org) 1.0 (JSON-RPC) from your own server: the
369
+ gateway. Your server authenticates each partner and names the subject its tasks
370
+ belong to. The handler forwards each request to the Runtime, which speaks A2A,
371
+ so the handler loads no A2A package and parses no message.
372
+
373
+ ```ts
374
+ import { createServer } from "node:http";
375
+ import { createA2aHandler, toNodeListener } from "@nylorun/agents/a2a";
376
+ import support from "./agents/support.js";
377
+
378
+ const a2a = createA2aHandler({
379
+ basePath: "/a2a",
380
+ agents: [support], // nothing else is reachable
381
+ // undefined → 401; return { subject, agents } to give a partner fewer agents
382
+ subject: (request) => partnerFor(request.headers.get("x-partner-key"))?.subject,
383
+ publicUrl: "https://api.example.com/a2a", // for the card; default: the request's origin
384
+ card: {
385
+ provider: { organization: "Example Inc.", url: "https://example.com" },
386
+ securitySchemes: {
387
+ partnerKey: { apiKeySecurityScheme: { location: "header", name: "X-Partner-Key" } },
388
+ },
389
+ securityRequirements: [{ schemes: { partnerKey: { list: [] } } }],
390
+ },
391
+ });
392
+
393
+ createServer(toNodeListener(a2a)).listen(3000);
394
+ ```
395
+
396
+ | Method and path under `basePath` | Operation |
397
+ | --- | --- |
398
+ | `GET /{agentId}/.well-known/agent-card.json` | The Agent Card: name, description and one skill from the manifest, with this endpoint's URL and your provider and security schemes. Public; `subject` is not called |
399
+ | `POST /{agentId}` | One A2A JSON-RPC request, answered by the Runtime |
400
+
401
+ What the Runtime answers (Host feature `a2a-endpoint`):
402
+
403
+ - `SendMessage` waits until the task completes, fails, is canceled or asks
404
+ for input, for at most 5 minutes (then it returns `WORKING`); with
405
+ `configuration.returnImmediately` it returns at once and the partner polls
406
+ `GetTask`. `CancelTask` works on a running task.
407
+ - A `contextId` is one session per partner, agent and context; a task is one
408
+ turn. A message without `taskId` starts a task (one at a time per context).
409
+ A question from the agent pauses the task as `TASK_STATE_INPUT_REQUIRED`
410
+ with the question as the status message; the partner answers with a message
411
+ on the same `taskId`.
412
+ - The `messageId` is the idempotency key: a retried message returns the same
413
+ task.
414
+ - Text parts, or a single data part, in; the turn's output as the artifact
415
+ `output` (text, or JSON as a data part). Files are
416
+ `ContentTypeNotSupportedError`.
417
+ - Clients must send `A2A-Version: 1.0` (header or `?A2A-Version=`).
418
+ - Not yet: `ListTasks`, streaming and `SubscribeToTask`
419
+ (`UnsupportedOperationError`; the card says `streaming: false`), push
420
+ notifications, the extended card, and approvals. An agent that pauses for an
421
+ approval shows `INPUT_REQUIRED`, refuses a reply, and can be canceled, so do
422
+ not publish agents with approval-gated tools yet.
423
+ - The handler calls the Runtime as the partner's subject with the scope
424
+ `sessions:own` only, so one partner never reaches another's tasks. It sends
425
+ no header the partner chose except `A2A-Version` and `A2A-Extensions`. Without
426
+ `a2a-endpoint` on the Runtime it answers `502` (`runtime_feature_missing`).
341
427
 
342
428
  ## Acting for a person (app servers)
343
429
 
@@ -370,10 +456,143 @@ compatibility check, so calling `as()` per request is cheap.
370
456
  | `agents:write` | Saving agents; listing agents, models and providers |
371
457
  | `tenant:settings` | The Tenant's status, model provider and sandbox settings |
372
458
 
373
- No scope reaches Tenant reset, config seed, executors, actions or the sandbox
459
+ No scope reaches Tenant reset, config seed, Action endpoints, actions or the sandbox
374
460
  tool routes; call those without `as()`. A subject is 1–200 visible ASCII
375
461
  characters (spaces only inside) and `host` is reserved. Your server must drop
376
462
  any `Nylorun-*` header its own clients send, and only an application key can act
377
- for a subject: an executor key that tries is `403`.
463
+ for a subject.
464
+
465
+ ## Minting subject tokens (app servers)
466
+
467
+ To let a person's browser or app call the Runtime directly, your server mints a
468
+ short-lived **subject token** for them instead of carrying their requests
469
+ (optional feature `subject-tokens`). What a token may do comes from the Tenant's
470
+ access policy, not from the caller:
471
+
472
+ ```ts
473
+ import { createClient } from "@nylorun/agents";
474
+
475
+ const app = createClient(); // the Tenant key, on the server only
476
+
477
+ // Once: roles, their agents and limits (or `nylo access policy init`).
478
+ await app.access.putPolicy({
479
+ version: 1,
480
+ roles: {
481
+ user: {
482
+ scopes: ["sessions:own", "agents:read"],
483
+ agents: ["support"],
484
+ limits: { turnsPerHour: 60, concurrentTurns: 2 },
485
+ },
486
+ },
487
+ anon: { scopes: [], agents: [] },
488
+ tokens: { maxTtlSeconds: 600 },
489
+ });
490
+
491
+ // Per signed-in person, from a same-origin POST route:
492
+ const { token, expiresAt } = await app.tokens.create({
493
+ subject: `app:${user.id}`,
494
+ role: "user",
495
+ });
496
+ ```
497
+
498
+ The client sends it as `Authorization: Bearer <token>`.
499
+ Tokens carry only `sessions:own`, `vaults:own` and `agents:read`, live at most
500
+ 15 minutes, and see only `{ agentId, name, description }` of their role's
501
+ agents. A token that expired or was revoked answers `401` with
502
+ `code: "token_expired"`: fetch a new one and retry. Starting more turns than the
503
+ role allows answers `429` with `code: "limit_exceeded"` and `Retry-After`.
504
+
505
+ | Call | Does |
506
+ | --- | --- |
507
+ | `app.access.revokeSubject(subject)` | Ends every token minted so far for the person and their open event streams |
508
+ | `app.access.signingKeys.rotate()` | Rotates the Tenant's signing keys without signing anyone out (`{ force: true }` for incidents) |
509
+ | `app.access.signingKeys.list()`, `.revoke(kid)`, `app.access.jwks()` | Inspect and retire keys; the public keys |
510
+
511
+ Keep tokens in memory on the client, never in `localStorage`, and serve the
512
+ minting route without CORS. `nylo access …` does the same from the terminal.
513
+
514
+ `createTokenEndpoint` is that route, ready to mount (Next.js, Hono or any
515
+ `Request` → `Response` handler):
516
+
517
+ ```ts
518
+ import { createTokenEndpoint } from "@nylorun/agents";
519
+
520
+ export const POST = createTokenEndpoint({
521
+ client: app,
522
+ role: "user",
523
+ subject: (request) => userFromCookie(request)?.id,
524
+ });
525
+ ```
526
+
527
+ ## In the browser
528
+
529
+ `@nylorun/agents/browser` calls the Runtime from a web page or an app with a
530
+ publishable key and the token route above (optional feature `browser-access`).
531
+ It loads no Node module.
532
+
533
+ ```ts
534
+ import { createBrowserClient } from "@nylorun/agents/browser";
535
+
536
+ const nylo = createBrowserClient({
537
+ url: "https://runtime.example.com",
538
+ publishableKey: "nr_pub_tn_…", // app.access.publishableKeys.create({ name, origins })
539
+ token: () => fetch("/api/nylorun/token", { method: "POST" }).then((r) => r.json()),
540
+ });
541
+
542
+ const session = await nylo.createSession({ agentId: "support" }); // owned by the token's subject
543
+ await session.input("Where is my order?", { idempotencyKey: crypto.randomUUID() });
544
+ for await (const event of session.observe()) console.log(event.type);
545
+ ```
546
+
547
+ For a chat UI, `agUi()` gives `@ag-ui/client`'s `HttpAgent` a `fetch` with the
548
+ key and a current token:
549
+
550
+ ```ts
551
+ import { HttpAgent } from "@ag-ui/client";
552
+
553
+ const { url, fetch } = nylo.agUi("support");
554
+ const agent = new HttpAgent({
555
+ url,
556
+ fetch,
557
+ threadId,
558
+ initialMessages: await nylo.agUiHistory("support", threadId),
559
+ });
560
+ ```
561
+
562
+ When the Runtime ends a run's stream because the token expired or was revoked,
563
+ that `fetch` reattaches from the last event with a new token, so the agent sees
564
+ one run. A person's token may attach their own vaults to a new thread
565
+ (`forwardedProps: { nylorun: { session: { vaultIds } } }`) but not set `info`.
566
+
567
+ The client keeps the token in memory, fetches a new one a minute before it
568
+ expires or when the Runtime answers `401 token_expired`, and never asks for two
569
+ at once. Event streams that the Runtime ends at token expiry or revocation
570
+ reconnect from their last event with a new token. Create a publishable key per
571
+ app with the origins that serve it (`http://localhost:*` for development);
572
+ requests from other origins get the opaque `404`.
573
+
574
+ The SDK depends only on core within the Nylorun packages; installing it does not install harness or any AG-UI or A2A package. Use `/define`, `/client`, `/ag-ui`, `/a2a` or `/browser` for focused imports, or the root for convenience. Studio uses `/client`. See [the adopted host contract](../harness/HOST_CONTRACT.md).
575
+
576
+ ## Embedding Studio (desktop apps)
577
+
578
+ `@nylorun/agents/studio-embed` is the contract between Studio and an app that
579
+ shows it in an iframe, such as Babai. It exports the message schema
580
+ (`StudioEmbedMessageSchema`, envelope `{ type: "nylorun.studio", protocol, kind }`),
581
+ the login-token and session schemas, `STUDIO_EMBED_PROTOCOLS` and
582
+ `parseFrameAncestors`.
583
+
584
+ ```ts
585
+ import { StudioEmbedMessageSchema } from "@nylorun/agents/studio-embed";
586
+
587
+ window.addEventListener("message", (event) => {
588
+ if (event.source !== frame.contentWindow || event.origin !== studioOrigin) return;
589
+ const message = StudioEmbedMessageSchema.safeParse(event.data);
590
+ if (!message.success) return;
591
+ if (message.data.kind === "ready") frame.contentWindow!.postMessage(init, studioOrigin);
592
+ });
593
+ ```
378
594
 
379
- The SDK depends only on core within the Nylorun packages; installing it does not install harness. `/ag-ui` adds `@ag-ui/core`; nothing else imports it. Use `/define`, `/client`, `/executor` or `/ag-ui` for focused imports, or the root for convenience. Studio uses `/client`. See [the adopted host contract](../harness/HOST_CONTRACT.md).
595
+ The embedder's backend mints the login token with the admin key
596
+ (`mintStudioLoginToken` in `@nylorun/admin`) and the page passes it to Studio in
597
+ `init`. No key reaches the page. Studio's origin allowlist is
598
+ `NYLORUN_STUDIO_FRAME_ANCESTORS`.
@@ -0,0 +1,59 @@
1
+ /**
2
+ * An A2A endpoint over the Tenant's agents, as a web-standard `Request` → `Response` handler
3
+ * (gateway mode). The host authenticates each partner (`subject`); the handler forwards the
4
+ * partner's JSON-RPC request to the Runtime as that subject, and the Runtime speaks A2A (Host
5
+ * feature `a2a-endpoint`). It parses no A2A message and sends no header the partner chose
6
+ * except `A2A-Version` and `A2A-Extensions`, so a partner can never name a subject or scopes.
7
+ * The Agent Card comes from the Runtime, with this endpoint's URL and the host's provider and
8
+ * security schemes added.
9
+ */
10
+ import type { BuiltWorkflow } from "@nylorun/core/define";
11
+ import { type AgentSource, type AgentsClient } from "../client.js";
12
+ /** A partner as the host authenticated it: its subject, and optionally fewer agents. */
13
+ export interface A2aCaller {
14
+ /** Owner of the partner's tasks, e.g. `a2a:acme`. Keep it stable for a partner. */
15
+ subject: string;
16
+ /** Agents this partner may use, among the handler's `agents`. Default: all of them. */
17
+ agents?: readonly string[];
18
+ }
19
+ /** What the published Agent Card adds to the Runtime's: who serves it and how to authenticate. */
20
+ export interface A2aCardOptions {
21
+ provider?: {
22
+ organization: string;
23
+ url: string;
24
+ };
25
+ documentationUrl?: string;
26
+ iconUrl?: string;
27
+ /** A2A `securitySchemes`, e.g. `{ partnerKey: { apiKeySecurityScheme: { location: "header", name: "X-Partner-Key" } } }`. */
28
+ securitySchemes?: Record<string, unknown>;
29
+ /** A2A `securityRequirements`, e.g. `[{ schemes: { partnerKey: { list: [] } } }]`. */
30
+ securityRequirements?: readonly unknown[];
31
+ }
32
+ export interface A2aHandlerOptions {
33
+ /** Agents this endpoint serves: built agents, workflows or their ids. Nothing else is reachable. */
34
+ agents: readonly (AgentSource | BuiltWorkflow | string)[];
35
+ /**
36
+ * The partner the request is from, authenticated by the host. `undefined` answers `401`;
37
+ * there is no anonymous mode. Not called for the Agent Card, which is public.
38
+ */
39
+ subject(request: Request): string | A2aCaller | undefined | Promise<string | A2aCaller | undefined>;
40
+ /** Where `fetch` is mounted, e.g. `/a2a`. Default `/`. */
41
+ basePath?: string;
42
+ /**
43
+ * The public URL of `basePath` as partners reach it, e.g. `https://api.example.com/a2a`.
44
+ * Default: the origin of each card request. Set it behind a proxy.
45
+ */
46
+ publicUrl?: string;
47
+ /** Application client. Default: `createClient()`, from the environment or the Project link. */
48
+ client?: AgentsClient | Promise<AgentsClient>;
49
+ card?: A2aCardOptions;
50
+ }
51
+ export interface A2aHandler {
52
+ /** One entry point that routes by method and path under `basePath`. Bound. */
53
+ readonly fetch: (request: Request) => Promise<Response>;
54
+ /** `POST {basePath}/{agent}`: one A2A JSON-RPC request, forwarded. */
55
+ call(request: Request, agentId: string): Promise<Response>;
56
+ /** `GET {basePath}/{agent}/.well-known/agent-card.json`: the agent's card. */
57
+ card(request: Request, agentId: string): Promise<Response>;
58
+ }
59
+ export declare function createA2aHandler(options: A2aHandlerOptions): A2aHandler;