@theokit/agents 15.1.1 → 16.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/CHANGELOG.md +71 -0
- package/README.md +48 -1
- package/dist/a2a.d.ts +37 -0
- package/dist/a2a.js +90 -0
- package/dist/a2a.js.map +1 -0
- package/dist/{agent-compiler-DMQcLHIs.d.ts → agent-compiler-JSYkHpa7.d.ts} +2 -2
- package/dist/agent-orchestrator-BFWg2URC.d.ts +449 -0
- package/dist/agent-runner-BUJKNNuI.d.ts +364 -0
- package/dist/agent-sse-handler-BRp9vHrb.d.ts +348 -0
- package/dist/{bridge-entry-CDFRjtbb.d.ts → bridge-entry-BNWDrPzg.d.ts} +8 -422
- package/dist/bridge.d.ts +8 -5
- package/dist/bridge.js +21 -15
- package/dist/{chunk-RAN4PBUL.js → chunk-3TE4PJZL.js} +569 -1526
- package/dist/chunk-3TE4PJZL.js.map +1 -0
- package/dist/{chunk-ULC47RCQ.js → chunk-4SXVNI5O.js} +7 -7
- package/dist/{chunk-ULC47RCQ.js.map → chunk-4SXVNI5O.js.map} +1 -1
- package/dist/chunk-A2UVVEB3.js +799 -0
- package/dist/chunk-A2UVVEB3.js.map +1 -0
- package/dist/chunk-FBCT4B2L.js +86 -0
- package/dist/chunk-FBCT4B2L.js.map +1 -0
- package/dist/{chunk-DZH5F4PP.js → chunk-KXE52FP2.js} +12 -67
- package/dist/chunk-KXE52FP2.js.map +1 -0
- package/dist/chunk-Z5SYU6Z6.js +353 -0
- package/dist/chunk-Z5SYU6Z6.js.map +1 -0
- package/dist/client-react.js +2 -1
- package/dist/client-react.js.map +1 -1
- package/dist/client.d.ts +12 -2
- package/dist/client.js +5 -3
- package/dist/delegation-scoring-Cn5eM4lQ.d.ts +79 -0
- package/dist/evals.d.ts +84 -0
- package/dist/evals.js +191 -0
- package/dist/evals.js.map +1 -0
- package/dist/handoff.d.ts +91 -0
- package/dist/handoff.js +268 -0
- package/dist/handoff.js.map +1 -0
- package/dist/index.d.ts +61 -401
- package/dist/index.js +142 -111
- package/dist/index.js.map +1 -1
- package/dist/mcp-health.d.ts +1 -1
- package/dist/sdk-adapter-DQnKx7bA.d.ts +435 -0
- package/dist/testing.d.ts +2 -2
- package/dist/tools.d.ts +5 -3
- package/dist/tools.js +10 -6
- package/dist/tools.js.map +1 -1
- package/dist/{types-CxI2x6mU.d.ts → types-D5cHmSLi.d.ts} +10 -4
- package/docs/capability-map.md +44 -5
- package/package.json +16 -2
- package/dist/chunk-DZH5F4PP.js.map +0 -1
- package/dist/chunk-RAN4PBUL.js.map +0 -1
- package/dist/delegation-scoring-CSe_C-iX.d.ts +0 -809
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,76 @@
|
|
|
1
1
|
# @theokit/agents
|
|
2
2
|
|
|
3
|
+
## 16.1.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- 159d559: New subpath `@theokit/agents/evals`. `runAgentEvals({ agent, apiKey, approvals, cases, scorers })` runs each case against your agent definition, on a fresh agent per case, and returns a verdict per case: `pass` or `fail` against `threshold` (default 0.5), or `error`. Each case result carries the output, the scores, the mean score and the duration, and the result counts each verdict. (B-413)
|
|
8
|
+
|
|
9
|
+
`approvals` is required, as it is on `toAgentFactory`: an eval runs with nobody watching, so you say what a gated tool's approval request gets. A case is `error`, never `fail`, when its run did not finish, a guard blocked the input or the output, the agent could not be built, a scorer threw, or a scorer returned a malformed score, a score outside [0, 1] or a reason that is not a string; `error` carries the reason. A scorer's own `reason` text never makes a case an `error`. Options it cannot run (no cases, a case without a string `input`, no scorers, a threshold outside [0, 1]) throw `EvalConfigError` before any agent is built. Unnamed runs get a fresh name, so two runs never collide. The subpath re-exports `Scorers` and `EvalAlreadyRunningError` from `@theokit/sdk/eval`.
|
|
10
|
+
|
|
11
|
+
The result type of `SdkTurnHandle.wait()` gains two optional fields, `status` and `error`, which the SDK eval runner reads.
|
|
12
|
+
|
|
13
|
+
- 8617aa5: New subpath `@theokit/agents/handoff`. `createHandoffConversation({ agents, initial, conversationId? })` holds a roster of compiled agents and the name of the one that answers. The answering agent gets a `transfer_to_agent` tool that names only the other agents. When it calls the tool, it still answers the current message, and your next `send()` is answered by the receiver, which reads the transferring agent's note before your message. (B-410)
|
|
14
|
+
|
|
15
|
+
Each agent runs on its own session, `<conversationId>:<agentName>`. A transfer counts only when the run returns normally: a run that throws, or whose `signal` was aborted, leaves the responder where it was. `send()` takes the `AgentRunner.run` options except `sessionId`, `tools`, `streamFactory` and `maxIterations`, which the conversation owns, and drops them at run time if they arrive through a wider object. `handoffTo(name, note?)` moves the next turn from your code. A roster below two agents, a duplicate name, an unknown agent, an agent whose `maxIterations` is 1 and an agent that already has a tool named `transfer_to_agent` (`reserved_tool_name`) and an agent name that contains `:` (`invalid_agent_name`, since each session id is `<conversationId>:<agentName>`) throw `HandoffError` with a `code`. So do `send()` and `handoffTo()` while a turn is running (`turn_in_progress`), `send()` while another conversation runs a turn on the same `conversationId`, a per-run `sdkTools` entry named `transfer_to_agent`, and `handoffTo()` with a note for the agent that already answers (`already_responder`), which would otherwise drop the note.
|
|
16
|
+
|
|
17
|
+
The note is written by a model and the message by the user, so `[Handoff from` inside either one, and its lookalikes (fullwidth or accented letters, Cyrillic or Greek letters that look Latin, zero-width characters, another opening bracket, `_` or `-` for the space), is rewritten to `[quoted: Handoff from`. A spelling outside those classes still arrives as written. The responder and a waiting note live in memory. To resume after a restart while the receiver has not answered, create the conversation with `initial` set to the last transfer's `from` and call `handoffTo(handoff.to, handoff.note)`; once the receiver has answered, set `initial` to its `to`.
|
|
18
|
+
|
|
19
|
+
`@theokit/sdk-handoff` stays call-and-return: there the caller keeps the turn.
|
|
20
|
+
|
|
21
|
+
### Patch Changes
|
|
22
|
+
|
|
23
|
+
- 72cff7f: An agent on an Anthropic model now reads its system prompt from the provider cache on later turns. `@theokit/agents` requires `@theokit/sdk` `^5.11.0`, the release that marks the configured prompt with `cache_control` for model ids starting with `anthropic/` or `claude` (also behind `openrouter/` or `vertex/`; Bedrock ids such as `bedrock/us.anthropic.claude-…` are not matched and their requests do not change) and reports the cache counters Anthropic returns. A consumer on @theokit/sdk 5.3 to 5.10 must upgrade to 5.11.0. Measured through OpenRouter on `anthropic/claude-haiku-4.5` with a 12 261-token cached prefix: the second turn reported `cacheReadTokens` 12 261. (B-412)
|
|
24
|
+
|
|
25
|
+
Two things a caller sees change with that SDK. On the chat-completions client (OpenRouter included) `tokensInput` is now the uncached part of the prompt, so the whole prompt is `tokensInput + cacheReadTokens + cacheWriteTokens`. `tokens` and the `done` event's `usage.totalTokens` stay input plus output, so they leave the cached prompt out too. And the first turn of an Anthropic run pays the cache-write premium (1.25 times the input price); a run with one turn never reads it back.
|
|
26
|
+
|
|
27
|
+
- 0e692a2: An agent from `toAgentFactory` can be served over ACP by `@theokit/acp` when it declares guardrails or a step ceiling. Its turn now has `stream()`, which the server reads: it yields one assistant message with the text after the output guards, and shares one guard run with `wait()`. When the run ends with status `error` or a guard blocks, the stream ends with `{ type: 'status', status: 'ERROR', message }`, as the SDK's own stream does, and any other error is rethrown from `stream()`. Both wrappers now forward `pluginManager`, so the server's default `ask` mode can install its permission plugin instead of refusing the prompt with `permission enforcement unavailable on this runtime (no plugin manager)`. A guarded agent served this way sends its text once the turn completes, with no token streaming and no tool activity, because streaming the raw text would pass it before the output guards ran. `SdkTurnHandle.stream` and `SdkAgentHandle.pluginManager` are new optional members.
|
|
28
|
+
|
|
29
|
+
## 16.0.0
|
|
30
|
+
|
|
31
|
+
### Major Changes
|
|
32
|
+
|
|
33
|
+
- cd10c2a: **Breaking:** `createA2ATool` now reads the remote agent's reply as a UIMessage event stream. A remote that answers the `{ message }` POST with a JSON body carrying `response` or `text` is no longer supported; the call rejects, naming the tool, `0 chunks` and the response content type. (B-407)
|
|
34
|
+
|
|
35
|
+
Every agent route this framework serves, from `generateAgentRoutes` or `mountAgent`, answers with an event stream, and the tool used to call `res.json()` on that response, so it failed on the first byte of a real reply. The tool now returns the text of the streamed assistant message. A stream that carries an error frame, or that ends before its `finish` frame, rejects with an error naming the tool instead of returning partial text.
|
|
36
|
+
|
|
37
|
+
**Migration:** answer the `{ message }` POST with the event stream `generateAgentRoutes` or `mountAgent` produce, or stay on 15.x.
|
|
38
|
+
|
|
39
|
+
**Breaking:** `createA2ATool` and its `A2AToolConfig` and `A2AAuth` types now import from `@theokit/agents/a2a`, not from the package root. Change `import { createA2ATool } from '@theokit/agents'` to `import { createA2ATool } from '@theokit/agents/a2a'`. The root bundle was at its size cap, and an app that does not delegate to a remote agent no longer loads the client. (B-407)
|
|
40
|
+
|
|
41
|
+
### Minor Changes
|
|
42
|
+
|
|
43
|
+
- 876af25: `createA2ATool` no longer returns an empty string when the remote's frames could not be read. The wire parser drops a frame with invalid JSON or an unknown variant; when every content frame was dropped and the stream still finished, the tool returned `''`, the same answer as an agent that chose to say nothing. A turn that finished with no text after dropped frames now rejects with `A2A call to "<name>" failed: no text after <n> unreadable frames`. A turn with text beside a dropped frame still returns the text.
|
|
44
|
+
|
|
45
|
+
`ChunkStreamOutcome` (`@theokit/agents/client`) gains an optional `framesDropped`, the count of frames the wire parser discarded, which `consumeUIMessageStream` reports; `responseToChunkStream` accepts an optional `onWarn` that hears each discarded frame. (B-407)
|
|
46
|
+
|
|
47
|
+
- aeb4aba: `AcpTransport` gains an optional `onClose(listener)`, through which a transport reports a channel that closed on its own (the agent process exited or failed). `AcpClient` registers on it: when it fires, every request in flight rejects with the new `AcpConnectionClosedError`, whose message names the cause and whose `cause` is the error the transport reported, and every later request rejects with the same error without being sent. A transport without `onClose` behaves as before. In `theokit`, `AcpToolTransport` now inherits that `onClose` instead of redeclaring it, so its listener receives an `Error`; `NodeAcpTransport` still reports an `AcpTransportClosedError`, and a plain `AcpTransport` still fits where an `AcpToolTransport` is expected. (B-434)
|
|
48
|
+
- 166d8ea: An ACP tool call opens a session before prompting. The tool returned by `createACPTool` sent a single `session/prompt` and read `result.text`, so an ACP agent that enforces the protocol refused the call, and even a tolerant one gave back an empty string, because ACP streams the reply as `session/update` notifications. Each call now sends `initialize`, `session/new` and `session/prompt`, and returns the text of the `agent_message_chunk` updates for its session. A step the agent refuses rejects with an error that names the method, and nothing after it is sent. A `session/request_permission` request is still decided by `onPermissionRequest`, but the reply on the wire is now an ACP `outcome` (`selected` with the option chosen by kind, or `cancelled`) instead of `{ granted }`. `AcpClient` gains `onNotification(method, handler)`, which delivers JSON-RPC notifications to a registered handler.
|
|
49
|
+
- c8e7f87: The run option `budget` now also accepts `{ maxCostUsd }`, which is the run's USD ceiling; `window` is refused before any round with a `DelegationError`, because a single run cannot keep a rolling budget. A run that used to finish one round over its ceiling now stops one round earlier: before each round after the first, the loop assumes the next round costs what the last one did and refuses it when that would pass the ceiling, with a `DelegationBudgetExceededError` whose message names the spend, the projection and the limit. The first round always runs, because no earlier round exists to project its cost from: a ceiling below that round's cost is spent once, and the run then stops with `DelegationBudgetExceededError`. A run with a ceiling now also stops after a round whose cost is not known, with the new `DelegationBudgetCostUnknownError`, a subclass of `DelegationBudgetExceededError`, exported from the package root and from `@theokit/agents/bridge` (#970). The ceiling reads the cost each round's `done` event reports, which through the SDK adapter is the SDK's `amountUsd` (#969); a round from a custom `streamFactory` that ends with no `done`, or with no finite numeric `cost`, counts as a round whose cost is not known.
|
|
50
|
+
|
|
51
|
+
The ceiling is now checked before any round, in both spellings and in `delegate()`'s `budget` and `parentBudgetRemaining` (B-433). `NaN`, for example from `Number(process.env.MAX_COST)` on an unset variable, used to read as a ceiling and enforce none; it now throws a `DelegationError` naming the field. A ceiling of 0 or below still ends in `DelegationBudgetExceededError`, but before the first round instead of after paying for it, so a parent that has spent its budget stops a delegation without charging it, and the delegate tool still reports `delegation_budget_exceeded`. `Infinity` still means no ceiling. See `docs/adr/0023`.
|
|
52
|
+
|
|
53
|
+
`DelegationResult` gains `costUnknown?: true`, set when at least one round of the run reported no finite cost. The loop folds such a round into `cost` as 0, so `cost` is the spend of the priced rounds, and a run on a model the SDK cannot price returned `{ cost: 0 }` with nothing saying the 0 was not a price. A run whose every round was priced returns the same result as before, with no `costUnknown` key. A consumer summing `cost` across runs should check `costUnknown` first. (B-409)
|
|
54
|
+
|
|
55
|
+
### Patch Changes
|
|
56
|
+
|
|
57
|
+
- 8e0e657: A run reports the cost the SDK priced, and none when it has no price. The SDK adapter read `cost.amount`, a field the SDK's `CostBreakdown` does not carry (its USD field is `amountUsd`), so `DoneEvent.cost` and the served finish metadata reported 0 on every run. They now report `amountUsd`. When the SDK has no price for the model, the `cost` key is absent, so an unpriced run no longer reads as a free one; a consumer summing runs must handle the absent key (#969). The `agent.run` span that `@theokit/theo` exports follows the metadata: its `cost.usd` attribute is now absent for an unpriced run, where it used to be 0.
|
|
58
|
+
|
|
59
|
+
`translateSdkEvent` (from `@theokit/agents/bridge`) follows the same rule and no longer reports a FINISHED or CANCELLED run as free. Its `done` event carried a hard-coded `cost: 0`, which under the `DoneEvent` contract means "priced at zero", so a stream built on it folded an unpriced run as a known $0 round and the USD ceiling's fail-closed `DelegationBudgetCostUnknownError` never fired. Now a status message whose `result.cost.amountUsd` is a finite number reports that as `cost`, and otherwise the `done` event has no `cost` key. (B-424)
|
|
60
|
+
|
|
61
|
+
- 0f1664b: `AcpClient` answers every request the agent sends and checks the `error` of a response. A server request whose handler result cannot be serialized (a `BigInt`, for example) used to leave the agent without an answer and the host with an unhandled rejection; it is now answered with JSON-RPC error -32603, and a reply the transport cannot send is logged with `console.warn`. A response whose `error` is not an object with a numeric `code` and a string `message` used to resolve the request with `undefined` (`"error": null`) or reject it with an empty message; it now fails the requests in flight with `AcpProtocolError`, naming the line. (B-408)
|
|
62
|
+
- 232e464: `AcpProtocolError` and `AcpConnectionClosedError` now extend `TheokitAgentError`, with the stable codes `ACP_PROTOCOL_ERROR` and `ACP_CONNECTION_CLOSED` and `isRetryable: false`, so a caller can tell a broken agent channel from other failures through `code` and `isTransientError` instead of the message text. Their `name`, message, `line` and `cause` are unchanged.
|
|
63
|
+
- 223ef38: `AcpClient` now fails the requests in flight with `AcpProtocolError` when the agent writes an object that is not a JSON-RPC response, request or notification it can dispatch (an `id` with neither `result` nor `error`, a string `id`, a notification carrying `id: null`), and logs a warning when no request is in flight. Such a line used to be dropped, and the request it was meant to answer stayed pending until the transport closed.
|
|
64
|
+
- ad383eb: `@theokit/agents` builds and type-checks against every `@theokit/sdk` its `^5.3.0` range admits again. The A2A client imported `ToolContext`, which the SDK root exports only from 5.8.0, so an install resolving 5.3 to 5.7 failed with `Module '"@theokit/sdk"' has no exported member 'ToolContext'`. It now declares the one field it reads, `signal` (#977)
|
|
65
|
+
- ddc8eb1: The tool `createA2ATool` returns now stops when its run is cancelled. Its handler ignored the run's `AbortSignal` (`ctx.signal`), so a cancelled run kept the HTTP connection and the remote agent's turn open until the remote finished, and the call stayed pending. The signal now reaches `fetch`, so a cancellation aborts the request and the event stream it holds, and the call rejects with the signal's abort reason instead of an `A2A call ... failed` error. (B-407)
|
|
66
|
+
- f8e6c5b: `createA2ATool` cancels the response body before it rejects on a non-2xx answer. The body was left unread, so the connection stayed checked out until the `Response` was garbage-collected, and a remote answering 403 or 502 under load held sockets longer than needed. The rejection message is unchanged. (B-407)
|
|
67
|
+
- e15b79b: `createA2ATool` rejects when the remote agent parks its turn on a tool approval. A served route emits `tool-approval-request` and holds the stream open until its approve endpoint is called, which an A2A call cannot do, so the delegating call used to wait for the remote gate's timeout, or forever when it had none. The call now rejects as soon as the gate appears, with `A2A call to "<name>" failed: the remote awaits approval of "<tool>", which A2A cannot give`, and cancels the stream. A remote whose tools need approval is not supported over A2A. (B-407)
|
|
68
|
+
- 19a9e25: `createA2ATool` returns the remote turn's text parts one per line. A remote that speaks before and after a tool call answers with two text parts, and they were joined with nothing, so the calling model read `Let me check.The answer is 4`. They are now joined with a newline, and empty parts are skipped. A turn with a single text part returns the same string as before. (B-407)
|
|
69
|
+
- accb29e: `AcpClient` handles what a coding agent writes to stdout one line at a time. A line that is valid JSON but not an object (`null`, a number, a string, an array) used to reach dispatch: `null` threw a `TypeError` that failed every request in flight with no hint of a protocol error, and the others were dropped in silence. It now fails the requests in flight like a line that is not JSON, and both reject with the new `AcpProtocolError`, which carries the offending `line`. A bad line no longer discards the well-formed messages of the same chunk: a response, a server request (which still gets its reply) or a notification before or after it is dispatched, and only the requests in flight when the bad line arrives are rejected. A notification handler that returns a promise which rejects is now reported with `console.warn`, like one that throws, instead of becoming an unhandled rejection. (B-408)
|
|
70
|
+
- 51bd671: `AcpClient` no longer lets what a coding agent writes to stdout throw out of the transport callback. A line that is not JSON used to throw from the stdout `data` listener of the Node transport, an uncaught exception that ended the host process; it now rejects every request in flight with the decode error, naming the line, and is logged with `console.warn` when nothing is in flight. A notification handler that throws is logged with `console.warn` and the rest of the chunk is still dispatched, where it used to throw into the transport and drop the messages after it. (B-408)
|
|
71
|
+
- 98571e6: An ACP tool call rejects a turn the agent did not finish, and `AcpClient` answers a request with a string id. The tool returned by `createACPTool` dropped the `session/prompt` result, so a turn the agent ended with `stopReason` `max_tokens`, `max_turn_requests`, `refusal` or `cancelled` came back as a finished answer. Only `end_turn` resolves now. Any other stop reason rejects with the new `AcpTurnStoppedError` (exported from `theokit/server/agent`), which carries `stopReason` and the text streamed before the stop as `partialText`; a result with no string `stopReason` rejects naming `session/prompt` (ADR 0025). `AcpClient` failed every request in flight when the agent sent a JSON-RPC request whose id is a string, which JSON-RPC 2.0 allows; it now answers that request with the same id. (B-408)
|
|
72
|
+
- b8cb6c4: `HttpTransport` now treats a caller header that differs from one of its defaults only in letter case as the same header. A header such as `x-theo-action: 0` used to travel beside the default `X-Theo-Action: 1`, and `fetch` sent the joined value `1, 0`; the caller's value now replaces the default, as it already did in `createA2ATool`. Both clients build their headers in one place, so the two cannot drift again. (B-407)
|
|
73
|
+
|
|
3
74
|
## 15.1.1
|
|
4
75
|
|
|
5
76
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -29,7 +29,7 @@ you mount HTTP surfaces).
|
|
|
29
29
|
|
|
30
30
|
## Subpath map
|
|
31
31
|
|
|
32
|
-
Twenty entry points. Import the one you need — the barrel is not the API.
|
|
32
|
+
Twenty-three entry points. Import the one you need — the barrel is not the API.
|
|
33
33
|
|
|
34
34
|
| Subpath | What lives there |
|
|
35
35
|
|---|---|
|
|
@@ -49,10 +49,13 @@ Twenty entry points. Import the one you need — the barrel is not the API.
|
|
|
49
49
|
| `./hooks` | The lifecycle-hook engine and its fingerprint gate |
|
|
50
50
|
| `./ask` | The human-in-the-loop rendezvous — ask a question, settle it, abandon it safely |
|
|
51
51
|
| `./tool-scope` | `bindToolScope` — bind `{projectRoot, writeRoot, sandbox}` once so an unconfined shell is unrepresentable |
|
|
52
|
+
| `./a2a` | `createA2ATool` — call a remote agent over HTTP as a tool |
|
|
52
53
|
| `./mcp-health` | MCP server health probing |
|
|
53
54
|
| `./commands` | Command routing and the shutdown/cleanup contract |
|
|
54
55
|
| `./doctor` | Environment diagnostics |
|
|
55
56
|
| `./usage` | Token and cost accounting |
|
|
57
|
+
| `./evals` | `runAgentEvals` — run cases against an agent and read pass, fail or error per case |
|
|
58
|
+
| `./handoff` | `createHandoffConversation`: one agent hands the conversation to another, and the next turn is answered by the receiver |
|
|
56
59
|
|
|
57
60
|
## The shapes worth knowing before you start
|
|
58
61
|
|
|
@@ -74,6 +77,50 @@ never subtractive.
|
|
|
74
77
|
matters more than it looks: without provenance, "why is it calling Anthropic?" has no answer in the
|
|
75
78
|
data, and a user cannot tell an explicit choice from a precedence fallback.
|
|
76
79
|
|
|
80
|
+
## Handing a conversation to another agent
|
|
81
|
+
|
|
82
|
+
`@theokit/agents/handoff` keeps a roster of compiled agents and the name of the one that answers.
|
|
83
|
+
|
|
84
|
+
```ts
|
|
85
|
+
import { createHandoffConversation } from '@theokit/agents/handoff'
|
|
86
|
+
|
|
87
|
+
const conversation = createHandoffConversation({ agents: [triage, billing], initial: 'triage' })
|
|
88
|
+
const first = await conversation.send('I want a refund', { apiKey })
|
|
89
|
+
// triage called transfer_to_agent: first.handoff is { from: 'triage', to: 'billing', note }
|
|
90
|
+
const second = await conversation.send('It was a gift', { apiKey })
|
|
91
|
+
// second.responder is 'billing'
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
The answering agent gets a `transfer_to_agent` tool for its run. The transfer takes effect when that
|
|
95
|
+
run returns normally, so a run that throws, or whose `signal` was aborted, leaves the responder where
|
|
96
|
+
it was. Each agent keeps its own session, and the receiver reads the transferring agent's note before
|
|
97
|
+
the next message. `handoffTo(name, note?)` moves the next turn from your code; it replaces any note
|
|
98
|
+
still waiting. Naming the agent that already answers changes nothing, and naming it with a note
|
|
99
|
+
throws `already_responder`, since no transfer would deliver the note.
|
|
100
|
+
|
|
101
|
+
The note opens the receiver's message as `[Handoff from <agent>] <note>`. A model wrote the note
|
|
102
|
+
and the user wrote the message, so neither is trusted: `[Handoff from` inside either one is rewritten
|
|
103
|
+
to `[quoted: Handoff from`, and so are its lookalikes (fullwidth or accented letters, Cyrillic or
|
|
104
|
+
Greek letters that look Latin, zero-width characters, another opening bracket, `_` or `-` for the
|
|
105
|
+
space). This narrows the forgery but does not close it: a spelling outside those classes still
|
|
106
|
+
arrives as written, so a receiver with tools that matter should not act on a note alone.
|
|
107
|
+
|
|
108
|
+
The responder and a waiting note are kept in the conversation object's memory. One `conversationId`
|
|
109
|
+
belongs to one conversation at a time: a second conversation on the same id cannot run a turn while
|
|
110
|
+
the first one is running (`turn_in_progress`). Each agent's session id is
|
|
111
|
+
`<conversationId>:<agentName>`, so an agent name that contains `:` is refused with
|
|
112
|
+
`invalid_agent_name`; a `conversationId` may contain one.
|
|
113
|
+
|
|
114
|
+
To resume after a restart, store the last `turn.handoff`. If the receiver has not answered yet,
|
|
115
|
+
create the conversation with `initial` set to its `from` and call
|
|
116
|
+
`handoffTo(handoff.to, handoff.note)`: the receiver's next message opens with
|
|
117
|
+
`[Handoff from <from>] <note>`, as it would have before the restart. Once the receiver has answered,
|
|
118
|
+
create the conversation with `initial` set to its `to`. A roster agent, or a per-run `sdkTools`
|
|
119
|
+
entry, that brings its own `transfer_to_agent` tool is refused with `reserved_tool_name`.
|
|
120
|
+
|
|
121
|
+
`@theokit/sdk-handoff` and `createDelegateTool` work differently. They are call-and-return: the
|
|
122
|
+
agent you call answers the caller, and the caller keeps the turn.
|
|
123
|
+
|
|
77
124
|
## What changed recently
|
|
78
125
|
|
|
79
126
|
See [`CHANGELOG.md`](./CHANGELOG.md) — shipped inside this package, so `node_modules` answers the
|
package/dist/a2a.d.ts
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { CustomTool } from '@theokit/sdk';
|
|
2
|
+
|
|
3
|
+
/** How to authenticate to the remote agent. */
|
|
4
|
+
interface A2AAuth {
|
|
5
|
+
/** Bearer token → `Authorization: Bearer <token>`. */
|
|
6
|
+
bearer?: string;
|
|
7
|
+
/** API-key header pair → `<name>: <value>` (e.g. `x-api-key`). */
|
|
8
|
+
apiKey?: {
|
|
9
|
+
header: string;
|
|
10
|
+
value: string;
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
interface A2AToolConfig {
|
|
14
|
+
/** Remote agent endpoint URL (POST target). */
|
|
15
|
+
url: string;
|
|
16
|
+
/** Tool name the model calls. */
|
|
17
|
+
name: string;
|
|
18
|
+
/** Tool description surfaced to the model. */
|
|
19
|
+
description: string;
|
|
20
|
+
/** Static headers merged into every request. */
|
|
21
|
+
headers?: Record<string, string>;
|
|
22
|
+
/** Auth applied to every request. */
|
|
23
|
+
auth?: A2AAuth;
|
|
24
|
+
/** Injected fetch (defaults to the global). Narrowed to the call shape this client uses. */
|
|
25
|
+
fetchImpl?: (url: string, init: RequestInit) => Promise<Response>;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Create a tool that delegates to a remote A2A agent. The remote answers the `{ message }` POST with
|
|
29
|
+
* a UIMessage event stream, as the routes `generateAgentRoutes` and `mountAgent` serve do; the tool
|
|
30
|
+
* returns the text of the streamed assistant message. A stream that carries an error frame, or that
|
|
31
|
+
* ends before its `finish` frame, rejects naming the tool rather than returning partial text; so
|
|
32
|
+
* does a turn that finished with no text after frames the reader could not read. A remote whose
|
|
33
|
+
* turn waits on a tool approval rejects when the gate appears: an A2A call cannot answer it.
|
|
34
|
+
*/
|
|
35
|
+
declare function createA2ATool(config: A2AToolConfig): CustomTool;
|
|
36
|
+
|
|
37
|
+
export { type A2AAuth, type A2AToolConfig, createA2ATool };
|
package/dist/a2a.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AGENT_ACTION_HEADERS,
|
|
3
|
+
agentRequestHeaders,
|
|
4
|
+
consumeUIMessageStream
|
|
5
|
+
} from "./chunk-FBCT4B2L.js";
|
|
6
|
+
import {
|
|
7
|
+
__name
|
|
8
|
+
} from "./chunk-Z4QWC7IK.js";
|
|
9
|
+
|
|
10
|
+
// src/a2a/a2a-client.ts
|
|
11
|
+
function failure(name, reason, options) {
|
|
12
|
+
return new Error(`A2A call to "${name}" failed: ${reason}`, options);
|
|
13
|
+
}
|
|
14
|
+
__name(failure, "failure");
|
|
15
|
+
async function readReply(name, res, signal) {
|
|
16
|
+
let parts = [];
|
|
17
|
+
let outcome;
|
|
18
|
+
try {
|
|
19
|
+
outcome = await consumeUIMessageStream(res, (m) => {
|
|
20
|
+
parts = m.parts;
|
|
21
|
+
const gate = parts.find((part) => part.state === "approval-requested");
|
|
22
|
+
if (gate) {
|
|
23
|
+
throw new Error(`the remote awaits approval of "${String(gate.toolName)}", which A2A cannot give`);
|
|
24
|
+
}
|
|
25
|
+
});
|
|
26
|
+
} catch (err) {
|
|
27
|
+
signal?.throwIfAborted();
|
|
28
|
+
throw failure(name, err instanceof Error ? err.message : String(err), {
|
|
29
|
+
cause: err
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
signal?.throwIfAborted();
|
|
33
|
+
const chunks = outcome.chunksReceived;
|
|
34
|
+
if (!outcome.terminated) {
|
|
35
|
+
const type = chunks > 0 ? "" : ` (response content-type ${res.headers.get("content-type") ?? "none"})`;
|
|
36
|
+
throw failure(name, `the stream ended before its finish frame after ${chunks} chunks${type}`);
|
|
37
|
+
}
|
|
38
|
+
const text = parts.map((part) => part.type === "text" && typeof part.text === "string" ? part.text : "").filter(Boolean).join("\n");
|
|
39
|
+
const dropped = outcome.framesDropped;
|
|
40
|
+
if (!text && dropped) {
|
|
41
|
+
throw failure(name, `no text after ${dropped} unreadable frames`);
|
|
42
|
+
}
|
|
43
|
+
return text;
|
|
44
|
+
}
|
|
45
|
+
__name(readReply, "readReply");
|
|
46
|
+
function createA2ATool(config) {
|
|
47
|
+
const { name, auth } = config;
|
|
48
|
+
const doFetch = config.fetchImpl ?? fetch;
|
|
49
|
+
return {
|
|
50
|
+
name,
|
|
51
|
+
description: config.description,
|
|
52
|
+
inputSchema: {
|
|
53
|
+
type: "object",
|
|
54
|
+
properties: {
|
|
55
|
+
message: {
|
|
56
|
+
type: "string",
|
|
57
|
+
description: "The message to send to the remote agent."
|
|
58
|
+
}
|
|
59
|
+
},
|
|
60
|
+
required: [
|
|
61
|
+
"message"
|
|
62
|
+
]
|
|
63
|
+
},
|
|
64
|
+
async handler(input, ctx) {
|
|
65
|
+
const message = typeof input.message === "string" ? input.message : "";
|
|
66
|
+
const res = await doFetch(config.url, {
|
|
67
|
+
method: "POST",
|
|
68
|
+
headers: agentRequestHeaders(AGENT_ACTION_HEADERS, config.headers, auth?.bearer ? {
|
|
69
|
+
authorization: `Bearer ${auth.bearer}`
|
|
70
|
+
} : void 0, auth?.apiKey ? {
|
|
71
|
+
[auth.apiKey.header]: auth.apiKey.value
|
|
72
|
+
} : void 0),
|
|
73
|
+
body: JSON.stringify({
|
|
74
|
+
message
|
|
75
|
+
}),
|
|
76
|
+
signal: ctx?.signal
|
|
77
|
+
});
|
|
78
|
+
if (!res.ok) {
|
|
79
|
+
await res.body?.cancel().catch(() => void 0);
|
|
80
|
+
throw failure(name, `${res.status} ${res.statusText}`);
|
|
81
|
+
}
|
|
82
|
+
return readReply(name, res, ctx?.signal);
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
__name(createA2ATool, "createA2ATool");
|
|
87
|
+
export {
|
|
88
|
+
createA2ATool
|
|
89
|
+
};
|
|
90
|
+
//# sourceMappingURL=a2a.js.map
|
package/dist/a2a.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/a2a/a2a-client.ts"],"mappings":";;;;;;;;;;AA+CA,SAASA,QAAQC,MAAcC,QAAgBC,SAAsB;AACnE,SAAO,IAAIC,MAAM,gBAAgBH,IAAAA,aAAiBC,MAAAA,IAAUC,OAAAA;AAC9D;AAFSH;AAST,eAAeK,UAAUJ,MAAcK,KAAeC,QAAoB;AACxE,MAAIC,QAA8B,CAAA;AAClC,MAAIC;AACJ,MAAI;AACFA,cAAU,MAAMC,uBAAuBJ,KAAK,CAACK,MAAAA;AAC3CH,cAAQG,EAAEH;AAGV,YAAMI,OAAOJ,MAAMK,KAAK,CAACC,SAASA,KAAKC,UAAU,oBAAA;AACjD,UAAIH,MAAM;AACR,cAAM,IAAIR,MACR,kCAAkCY,OAAOJ,KAAKK,QAAQ,CAAA,0BAA2B;MAErF;IACF,CAAA;EACF,SAASC,KAAK;AACZX,YAAQY,eAAAA;AACR,UAAMnB,QAAQC,MAAMiB,eAAed,QAAQc,IAAIE,UAAUJ,OAAOE,GAAAA,GAAM;MAAEG,OAAOH;IAAI,CAAA;EACrF;AAGAX,UAAQY,eAAAA;AACR,QAAMG,SAASb,QAAQc;AACvB,MAAI,CAACd,QAAQe,YAAY;AAEvB,UAAMC,OACJH,SAAS,IAAI,KAAK,2BAA2BhB,IAAIoB,QAAQC,IAAI,cAAA,KAAmB,MAAA;AAClF,UAAM3B,QAAQC,MAAM,kDAAkDqB,MAAAA,UAAgBG,IAAAA,EAAM;EAC9F;AAKA,QAAMG,OAAOpB,MACVqB,IAAI,CAACf,SAAUA,KAAKW,SAAS,UAAU,OAAOX,KAAKc,SAAS,WAAWd,KAAKc,OAAO,EAAA,EACnFE,OAAOC,OAAAA,EACPC,KAAK,IAAA;AACR,QAAMC,UAAUxB,QAAQyB;AACxB,MAAI,CAACN,QAAQK,SAAS;AACpB,UAAMjC,QAAQC,MAAM,iBAAiBgC,OAAAA,oBAA2B;EAClE;AACA,SAAOL;AACT;AA1CevB;AAoDR,SAAS8B,cAAcC,QAAqB;AACjD,QAAM,EAAEnC,MAAMoC,KAAI,IAAKD;AACvB,QAAME,UAAUF,OAAOG,aAAaC;AACpC,SAAO;IACLvC;IACAwC,aAAaL,OAAOK;IACpBC,aAAa;MACXjB,MAAM;MACNkB,YAAY;QACVvB,SAAS;UAAEK,MAAM;UAAUgB,aAAa;QAA2C;MACrF;MACAG,UAAU;QAAC;;IACb;IACA,MAAMC,QAAQC,OAAgCC,KAAoB;AAEhE,YAAM3B,UAAU,OAAO0B,MAAM1B,YAAY,WAAW0B,MAAM1B,UAAU;AAMpE,YAAMd,MAAM,MAAMgC,QAAQF,OAAOY,KAAK;QACpCC,QAAQ;QACRvB,SAASwB,oBACPC,sBACAf,OAAOV,SACPW,MAAMe,SAAS;UAAEC,eAAe,UAAUhB,KAAKe,MAAM;QAAG,IAAIE,QAC5DjB,MAAMkB,SAAS;UAAE,CAAClB,KAAKkB,OAAOC,MAAM,GAAGnB,KAAKkB,OAAOE;QAAM,IAAIH,MAAAA;QAE/DI,MAAMC,KAAKC,UAAU;UAAExC;QAAQ,CAAA;QAC/Bb,QAAQwC,KAAKxC;MACf,CAAA;AACA,UAAI,CAACD,IAAIuD,IAAI;AAGX,cAAMvD,IAAIoD,MAAMI,OAAAA,EAASC,MAAM,MAAMT,MAAAA;AACrC,cAAMtD,QAAQC,MAAM,GAAGK,IAAI0D,MAAM,IAAI1D,IAAI2D,UAAU,EAAE;MACvD;AACA,aAAO5D,UAAUJ,MAAMK,KAAKyC,KAAKxC,MAAAA;IACnC;EACF;AACF;AAzCgB4B;","names":["failure","name","reason","options","Error","readReply","res","signal","parts","outcome","consumeUIMessageStream","m","gate","find","part","state","String","toolName","err","throwIfAborted","message","cause","chunks","chunksReceived","terminated","type","headers","get","text","map","filter","Boolean","join","dropped","framesDropped","createA2ATool","config","auth","doFetch","fetchImpl","fetch","description","inputSchema","properties","required","handler","input","ctx","url","method","agentRequestHeaders","AGENT_ACTION_HEADERS","bearer","authorization","undefined","apiKey","header","value","body","JSON","stringify","ok","cancel","catch","status","statusText"]}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { InlineSkill, CustomTool, MemorySettings, TelemetrySettings, SystemPromptResolver, SessionStore, PermissionGate, SkillsSettings, ContextSettings } from '@theokit/sdk';
|
|
2
2
|
import { AgentDefinition as AgentDefinition$1 } from '@theokit/sdk/subagents-loader';
|
|
3
3
|
import { TheokitAgentError } from '@theokit/sdk/errors';
|
|
4
|
-
import { R as ReasoningEffort, H as HumanInTheLoopOptions,
|
|
4
|
+
import { R as ReasoningEffort, H as HumanInTheLoopOptions, a as McpServersMap, b as MemoryOptions, P as ProjectContextOptions, C as CheckpointOptions, T as ToolOptions, A as ApprovalOptions, B as BudgetOptions } from './types-D5cHmSLi.js';
|
|
5
5
|
import { z } from 'zod';
|
|
6
6
|
import { S as SettingSourcesSelection, G as GatedSettingSource, a as GatedCompatSource } from './setting-sources-gate-BJJiKq33.js';
|
|
7
7
|
import { H as HookHandlers } from './hook-handlers-Cw2FsnE5.js';
|
|
@@ -695,4 +695,4 @@ interface CompiledAgentOptions {
|
|
|
695
695
|
skillsResolver?: SkillsSelection;
|
|
696
696
|
}
|
|
697
697
|
|
|
698
|
-
export { type AgentDefinition as A, type
|
|
698
|
+
export { type AgentDefinition as A, type CompiledTool as C, type DefineAgentConfig as D, type Guardrail as G, type HookApprovalGate as H, type InferAgentInput as I, MalformedGuardrailResultError as M, type SkillsRequestContext as S, type ToolWalkResult as T, UnreadableTextPayloadError as U, type CompiledAgentOptions as a, AGENT_BRAND as b, CompatImportUnsupportedError as c, CostBudgetExceededError as d, type GuardrailAction as e, GuardrailError as f, type GuardrailPhase as g, type GuardrailResult as h, GuardrailViolationError as i, type HookApprovalRequest as j, HookGateUnsupportedError as k, type InferAgentToolNames as l, type SkillsSelection as m, type ToolboxWalkResult as n, compileAgentDefinition as o, compileTools as p, isAgentDefinition as q, resolveEnabledSkills as r, type SubagentAgentDefinition as s, type CodePlugin as t };
|