@ouispec/agent-worker 0.14.0 → 0.16.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/README.md +123 -6
- package/dist/approvals/client.d.ts +14 -1
- package/dist/approvals/client.d.ts.map +1 -1
- package/dist/approvals/client.js +9 -0
- package/dist/approvals/client.js.map +1 -1
- package/dist/approvals/hooks.d.ts +82 -0
- package/dist/approvals/hooks.d.ts.map +1 -0
- package/dist/approvals/hooks.js +94 -0
- package/dist/approvals/hooks.js.map +1 -0
- package/dist/container/server.d.ts +14 -0
- package/dist/container/server.d.ts.map +1 -1
- package/dist/container/server.js +36 -17
- package/dist/container/server.js.map +1 -1
- package/dist/emit/filter.d.ts +23 -0
- package/dist/emit/filter.d.ts.map +1 -0
- package/dist/emit/filter.js +27 -0
- package/dist/emit/filter.js.map +1 -0
- package/dist/emit/tee.d.ts +18 -0
- package/dist/emit/tee.d.ts.map +1 -0
- package/dist/emit/tee.js +19 -0
- package/dist/emit/tee.js.map +1 -0
- package/dist/index.d.ts +17 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +12 -2
- package/dist/index.js.map +1 -1
- package/dist/lambda/handler.d.ts.map +1 -1
- package/dist/lambda/handler.js +4 -1
- package/dist/lambda/handler.js.map +1 -1
- package/dist/live-call/event-stream.d.ts +20 -0
- package/dist/live-call/event-stream.d.ts.map +1 -0
- package/dist/live-call/event-stream.js +43 -0
- package/dist/live-call/event-stream.js.map +1 -0
- package/dist/live-call/handler.d.ts +153 -0
- package/dist/live-call/handler.d.ts.map +1 -0
- package/dist/live-call/handler.js +416 -0
- package/dist/live-call/handler.js.map +1 -0
- package/dist/live-call/protocol.d.ts +157 -0
- package/dist/live-call/protocol.d.ts.map +1 -0
- package/dist/live-call/protocol.js +168 -0
- package/dist/live-call/protocol.js.map +1 -0
- package/dist/orchestrator.d.ts +5 -0
- package/dist/orchestrator.d.ts.map +1 -1
- package/dist/orchestrator.js +167 -33
- package/dist/orchestrator.js.map +1 -1
- package/dist/prompt/builder.d.ts +1 -1
- package/dist/prompt/builder.d.ts.map +1 -1
- package/dist/prompt/builder.js +8 -2
- package/dist/prompt/builder.js.map +1 -1
- package/dist/prompt/rules/base.js +4 -4
- package/dist/prompt/spoken-reply.d.ts +28 -0
- package/dist/prompt/spoken-reply.d.ts.map +1 -0
- package/dist/prompt/spoken-reply.js +49 -0
- package/dist/prompt/spoken-reply.js.map +1 -0
- package/dist/prompt/types.d.ts +12 -0
- package/dist/prompt/types.d.ts.map +1 -1
- package/dist/runtime/turn-info.d.ts +28 -0
- package/dist/runtime/turn-info.d.ts.map +1 -0
- package/dist/runtime/turn-info.js +23 -0
- package/dist/runtime/turn-info.js.map +1 -0
- package/dist/runtime/turn-runner.d.ts +42 -5
- package/dist/runtime/turn-runner.d.ts.map +1 -1
- package/dist/runtime/turn-runner.js +148 -36
- package/dist/runtime/turn-runner.js.map +1 -1
- package/dist/runtime/turn-slots.d.ts +30 -0
- package/dist/runtime/turn-slots.d.ts.map +1 -0
- package/dist/runtime/turn-slots.js +36 -0
- package/dist/runtime/turn-slots.js.map +1 -0
- package/dist/runtime/types.d.ts +45 -4
- package/dist/runtime/types.d.ts.map +1 -1
- package/dist/stop/turn-stop.d.ts +12 -1
- package/dist/stop/turn-stop.d.ts.map +1 -1
- package/dist/stop/turn-stop.js +47 -0
- package/dist/stop/turn-stop.js.map +1 -1
- package/dist/turn-policy.d.ts +8 -1
- package/dist/turn-policy.d.ts.map +1 -1
- package/dist/turn-policy.js.map +1 -1
- package/dist/types.d.ts +12 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/ui/snapshot.d.ts +6 -4
- package/dist/ui/snapshot.d.ts.map +1 -1
- package/dist/ui/snapshot.js +8 -6
- package/dist/ui/snapshot.js.map +1 -1
- package/package.json +5 -5
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @ouispec/agent-worker
|
|
2
2
|
|
|
3
|
-
The agent runtime. One core runs a turn: the model, the tool loop, UI actions answered by the user's own tab, streaming, retries and deadlines. Two host adapters run that core: Lambda + SQS, and a long-running container.
|
|
3
|
+
The agent runtime. One core runs a turn: the model, the tool loop, UI actions answered by the user's own tab, streaming, retries and deadlines. Two host adapters run that core: Lambda + SQS, and a long-running container. A third entry point, the live-call handler, lets a service that runs a voice call reach the same agent ("Live calls").
|
|
4
4
|
|
|
5
5
|
## What the host supplies
|
|
6
6
|
|
|
@@ -28,23 +28,49 @@ Optional tuning, with its defaults:
|
|
|
28
28
|
|
|
29
29
|
A host that fits its stored history loads `@ouispec/agent-worker/history` (`answerWithoutState`): a module with no runtime imports, which also answers a CommonJS resolver.
|
|
30
30
|
|
|
31
|
-
Policy hooks: `turnPolicy`, `toolPolicy`, `uiActions`, `approvals`, `stops`, `logger
|
|
31
|
+
Policy hooks: `turnPolicy`, `toolPolicy`, `uiActions`, `approvals`, `stops`, `logger`, and the hooks every turn passes through, `beforeTurn` and `filterEvent` ("Hooks on every turn").
|
|
32
32
|
|
|
33
33
|
## What a UI client sends with a turn
|
|
34
34
|
|
|
35
|
-
|
|
35
|
+
Four keys on the turn's `context` are for the worker itself, and your persona or `systemPrompt` callback never sees them:
|
|
36
36
|
|
|
37
37
|
| Key | What the tab puts there | What the worker does with it |
|
|
38
38
|
|---|---|---|
|
|
39
39
|
| `oui` | Its surface snapshot: `ouiRuntime.snapshot()` | Builds the turn's UI tools from it, and from nothing else |
|
|
40
40
|
| `uiKnowledge` | Its generated knowledge for the page the user is on: `resolveKnowledge(generatedKnowledge, path)` from `@ouispec/bindings` | Renders it after your prompt: each entry under "Platform Knowledge", then each recipe under "Active Workflows" |
|
|
41
|
-
| `input` | How the person entered the message, when they did not type it: `{ mode: 'voice', language }` for one they spoke, with the language the recogniser detected. `@ouispec/agent-react` sets it from `sendMessage(text, { input })` | Adds one line
|
|
41
|
+
| `input` | How the person entered the message, when they did not type it: `{ mode: 'voice', language }` for one they spoke, with the language the recogniser detected. `@ouispec/agent-react` sets it from `sendMessage(text, { input })` | Adds one line after the conversation: the message was spoken and machine-transcribed, so it may contain recognition errors; the language; and to ask rather than guess when a likely mis-hearing makes the request ambiguous. An unknown mode is read as typed, and a language that is not a BCP 47 tag of at most 16 characters is left out (`readMessageInput` in `@ouispec/agent-core`). A typed message, and the turn an approval card's click starts, get nothing |
|
|
42
|
+
| `output` | How the reply reaches the person, when it is not shown as text: `{ mode: 'voice' }` when a voice reads it out, with `voiceDirections: { engine, tags, guidance }` when that voice can be directed by inline tags. The live-call handler sets it from the call's request | Adds one line after the conversation: the reply will be heard, not read, so short plain sentences; no markdown, lists, headings, links, code or emoji; numbers, prices, dates and times written as they are said; anything the person should look at shown through the page's actions rather than read out; and a few words before a slow lookup. With `voiceDirections`, the same line offers the engine's tags, written exactly as given, says they are performed rather than read out and that no other tags are used, and ends with the service's `guidance`. An unknown mode is read as a shown reply, which gets nothing, and malformed directions (an empty tag list, a tag or engine with a control character, guidance over 2,000 characters; `VOICE_DIRECTIONS_LIMITS`) are left out while the reply is still spoken (`readReplyOutput` in `@ouispec/agent-core`). It applies on every turn of a call, the turn that continues an approval included |
|
|
42
43
|
|
|
43
44
|
`timeZone` (the user's IANA zone, which `@ouispec/agent-react` sends with every turn) is read by the worker too: the date and time on the user's clock are added to the turn's user message.
|
|
44
45
|
|
|
45
|
-
What
|
|
46
|
+
What is true only for this turn (the clock, how the message was entered, how the reply is delivered) goes after the conversation, never in the system prompt or on a message. The system prompt, the tools and every message are the cached prefix, and stay byte for byte the same whatever the turn says, so a conversation's chat turns and call turns read the same prefix. Store `input` with the user's message if your chat shows how a message was entered (`AgentStoredMessage.input`); the history the worker reads needs no copy of it.
|
|
46
47
|
|
|
47
|
-
Every other key is the page's context, which a persona prompt shows as the current UI state. A malformed `oui` or `uiKnowledge` fails the turn, naming the bad field. The worker logs `UI surfaces for this turn` with the surface ids and the knowledge's entry and workflow counts.
|
|
48
|
+
Every other key is the page's context, which a persona prompt shows as the current UI state ("CURRENT UI CONTEXT", as JSON). A persona whose context is not a page renders it itself: `persona.renderContext(ctx)` returns the section to end the system prompt with, or null (or blank) for none, and is given the context without the four keys above. It renders into the system prompt, the start of the cached prefix, so render nothing that changes from turn to turn unless the conversation's context did. A malformed `oui` or `uiKnowledge` fails the turn, naming the bad field. The worker logs `UI surfaces for this turn` with the surface ids and the knowledge's entry and workflow counts.
|
|
49
|
+
|
|
50
|
+
## Hooks on every turn
|
|
51
|
+
|
|
52
|
+
Every turn reaches the runtime one of four ways: the Lambda adapter, the container's `/turns`, the live-call handler, or your own code calling `runner.run`. Each hook below runs for all of them, and is told which turn it is called for (`AgentTurnInfo`):
|
|
53
|
+
|
|
54
|
+
| Field | |
|
|
55
|
+
|---|---|
|
|
56
|
+
| `id` | The turn's id. |
|
|
57
|
+
| `channel` | How it came: `lambda`, `container`, `live-call`, or what you pass as `runner.run(payload, { channel })` when you call it yourself (`sms`, `chat`); `direct` when you pass none. |
|
|
58
|
+
| `inputMode` | `voice` when the person's message was spoken and transcribed (its context's `input`), else `text`. |
|
|
59
|
+
| `language` | The language it was recognised in, a BCP 47 tag, when spoken and the recogniser said; else null. |
|
|
60
|
+
|
|
61
|
+
**`beforeTurn(payload, info)`**, on the runtime config, runs before anything else. Return the payload to run, changed or not: the person's words with a card number redacted before the model reads them (`content`), a reshaped context. Store the same redacted copy yourself. Return null to refuse the turn: nothing is read, run, stored or sent to the room, and the runner's outcome is `{ status: 'refused', refusedBy: 'beforeTurn' }` (a live call is answered `error` `TURN_DECLINED`); tell your own client why. The turn's `turnId`, `conversationId`, `userId`, `accountId` and `socketRoom` are not the hook's to change: a returned turn that changes one, or is not a turn, fails it, as a throw does (`agent:turn_error` to the turn's own room).
|
|
62
|
+
|
|
63
|
+
**`filterEvent(event, data, turn)`**, on the runtime config, decides what of each turn event leaves the runtime: return the payload to send (it is given a copy, so change it freely), or null to send nothing. It runs before the room, before a host that observes the turn, and so before the live-call handler speaks anything: one filter covers the page, the call and the room alike. Mask a phone number in a tool call's `input`, in a readback, or in the reply's text; drop `agent:reasoning_*`. It is synchronous, so events keep their order. It fails closed: a throw, or a return that is neither a payload nor null, drops that event and logs `The host’s event filter failed; the event was not sent`. A tool still runs with the arguments the model gave it: the filter governs what is sent, not what runs. The UI action requests the worker sends the user's own tab are not turn events, and do not pass through it.
|
|
64
|
+
|
|
65
|
+
**The turn policy** is told the turn too: `classifyTurn(content, history, turn)`, and `turn` on the context of `prepareStep` and `onTurnClassified`.
|
|
66
|
+
|
|
67
|
+
### The rounds of a turn
|
|
68
|
+
|
|
69
|
+
The model writes a reply in rounds: text, tool calls, more text. Each `agent:token` names its round (`step`, from 0), and each round's end is sent once all of its text has been: `agent:round_end { turnId, step, calledTools, final, timestamp }`. `calledTools` says the round called tools; `final` says no round follows it, so its text is the turn's last word. A round that ended at an approval, at a choice for the person (`present_options`), at the hand-back for time or at the last step allowed is final though it called a tool; a round cut off at the output limit having said nothing never is. A round's tool calls (`agent:tool_call_started`) are sent after its text and before its end. A host reply (`runner.reply`) is one final round, and so is the line the person is told when every attempt at a step was cut off.
|
|
70
|
+
|
|
71
|
+
A consumer that shows or speaks only what the turn ends with, never what the model wrote before a tool call, holds each round's text until its `round_end` and keeps it when `final`. The live-call handler does this with `speak: 'final-round'` ("Live calls"). Text before a tool call is otherwise shown and spoken as it streams, and the shipped prompt tells the model so: at most one brief line for the person before a tool call, or nothing, and never its reasoning.
|
|
72
|
+
|
|
73
|
+
Update the realtime server with the worker: a server on an older `@ouispec/agent-events` refuses `agent:round_end` as undeclared, and the worker logs each refused emit.
|
|
48
74
|
|
|
49
75
|
## Approvals
|
|
50
76
|
|
|
@@ -64,8 +90,17 @@ What happens:
|
|
|
64
90
|
|
|
65
91
|
In a browser, the turn after the decision comes from `ApprovalCard` (`@ouispec/agent-react`). Your `sendMessage` callback receives `approval` beside an empty `content`. Pass it unchanged to the worker as the turn payload's `approval`: `{ approvalId, decision: 'approve', token }` or `{ approvalId, decision: 'decline' }`. A UI action declares its effect on its OUI surface (`effect: 'transaction'`, or `confirm: true` for a destructive one). The tab's OUI runtime runs it only on the grant from the user's own click, which `grantApproval` in the client config hands it.
|
|
66
92
|
|
|
93
|
+
On a call there is no card. The live-call handler sends the preview's `readback`, verbatim, after the turn's text, and the person answers in words. Their next utterance comes as an ordinary message, and your `resolveTurn` decides whether it approves: classify the words, then decide as the user on a conversation channel with the approval store client (`createHttpApprovalStoreClient(...).decide(approvalId, { userId, decision, channel: 'voice' })`). An `approve` answers with the token; return `approval: { approvalId, decision: 'approve', token }` on the turn's target, and the turn runs exactly the stored call, once. Anything else (a no, a correction, a new request) leaves the approval to expire, or decline it with `decision: 'decline'`. A UI action that needs approval still runs only on the grant from the tab's own card click: the tab's OUI runtime refuses one approved by voice, so on a call put irreversible acts in host or API tools, or let the page show the card.
|
|
94
|
+
|
|
67
95
|
Declare a host tool's approval needs on the tool itself: `effect`, `destructive`, `title`, `consequence`, and `argsSensitive: false` when its arguments may be logged. Without an approval store, such a call is refused and never runs. The runtime uses the realtime server's store unless you pass `approvals.store`.
|
|
68
96
|
|
|
97
|
+
Two hooks give you a say before an approval is asked for. Both are told the turn (`turn`, `channel`), the user, account and conversation, and `locale`: the language the person's message was recognised in (on a call, the request's `input.language`), null for a typed message.
|
|
98
|
+
|
|
99
|
+
- **`approvals.validateBeforeApproval(tool, args, ctx)`** checks the call before it is read back: `{ ok: true }`, or `{ ok: false, error }` to refuse it. A refused call is not stored or shown; the model gets `error` as the call's result (`refusedBeforeApproval: true`) and can correct it, so a booking for a time you never offered is caught before the person approves it, not after. A throw refuses the call too.
|
|
100
|
+
- **`approvals.preview(tool, args, ctx)`** writes the approval's display copy in place of the one built from the declaration (`ctx.built`): `{ title, consequence?, arguments, readback, spokenReadback? }`. Redact a value there, and write it in the person's language with dates, times and numbers as words; `spokenReadback` is the readback as a voice should say it, digits grouped for speech, and a live call speaks it in place of `readback`. That copy is what the approval store keeps with the call, what `agent:approval_required` carries to the card, and what is read back. The call that runs is still exactly the model's: the store keeps its original arguments and `argsHash` is over them, so a decision redeems exactly the call the model made. A throw, or an answer that is not a preview within the store's limits (`APPROVAL_PREVIEW_LIMITS`), means the approval cannot be asked for, and the call is not run: the built preview, with the values you meant to remove, is never the fallback.
|
|
101
|
+
|
|
102
|
+
Of the calls in one response, only the first that needs approval is asked for. While its check and preview are written, a call that arrives waits for the outcome: if the first is refused, the next is checked as if it had come first.
|
|
103
|
+
|
|
69
104
|
## Stopping a turn
|
|
70
105
|
|
|
71
106
|
A turn can be stopped by the person, or superseded by their next message. The request is kept by the realtime server (`@ouispec/agent-realtime`, "Stopping a turn"), and the turn asks for it there for as long as it runs. Nothing needs configuring: the runtime uses the realtime server you already gave it. `stops.graceMs` (default 2 s) is how long an answer already on its way is still waited for.
|
|
@@ -166,10 +201,92 @@ Your API sends turns to the worker's HTTP endpoints:
|
|
|
166
201
|
| Request | Responses |
|
|
167
202
|
|---|---|
|
|
168
203
|
| `POST /turns` with an `AgentTurnPayload` and `x-api-key` | `202` once accepted. `400` if the body is not a turn, `401` for a wrong key, `409` if that turn is already running, `503` at capacity (`maxConcurrentTurns`, default 8) or while shutting down. |
|
|
204
|
+
| `POST /live-call/turns` with a live-call turn and `Authorization: Bearer` | Only with `liveCall` configured (below, and "Live calls"). `200 text/event-stream`. |
|
|
169
205
|
| `GET /health` | The worker's status, running turns, capacity and model. |
|
|
170
206
|
|
|
171
207
|
`onTurnEnd` receives each turn's outcome.
|
|
172
208
|
|
|
209
|
+
`liveCall: { credential, resolveTurn, opening?, speak?, holdingLine?, keepAliveMs?, path? }` serves the live-call route on the same server, runtime and slots: `maxConcurrentTurns` bounds both routes together, a turn id runs once whichever route it came by, and `close` waits for both. Its requests carry the call service's credential, never `workerApiKey`. `path` defaults to `/live-call/turns`.
|
|
210
|
+
|
|
211
|
+
## Live calls
|
|
212
|
+
|
|
213
|
+
A service that runs a voice call (it hears the person, transcribes them, and speaks the reply in a character's voice) can be answered by your own agent: its persona, tools, UI actions, approvals and records. Each turn of the call is one HTTP request to a route you mount, and the reply streams back as server-sent events. The turn runs on the same runtime as every other turn, so it still streams to the conversation's realtime room: every page joined to that conversation receives the reply and every UI action, as for a typed message, and the call page can show what the agent is talking about.
|
|
214
|
+
|
|
215
|
+
```ts
|
|
216
|
+
import { createAgentTurnRunner, createLiveCallTurnHandler, liveCallOpeningMessage } from '@ouispec/agent-worker';
|
|
217
|
+
|
|
218
|
+
const runner = createAgentTurnRunner(runtimeConfig); // the same config as your other turns
|
|
219
|
+
const liveCall = createLiveCallTurnHandler({
|
|
220
|
+
runner,
|
|
221
|
+
credential: env.LIVE_CALL_CREDENTIAL, // or [current, next] while rotating
|
|
222
|
+
resolveTurn: async (request, { signal }) => {
|
|
223
|
+
const conversation = await findConversationByCallRef(request.clientRef);
|
|
224
|
+
if (!conversation) return null; // answered 404
|
|
225
|
+
const said = request.kind === 'opening' ? liveCallOpeningMessage(request) : redactCardNumbers(request.text);
|
|
226
|
+
await storeUserMessage(conversation.id, said, request.input);
|
|
227
|
+
return {
|
|
228
|
+
conversationId: conversation.id,
|
|
229
|
+
userId: conversation.userId,
|
|
230
|
+
accountId: conversation.accountId,
|
|
231
|
+
socketRoom: `conversation:${conversation.id}`,
|
|
232
|
+
context: conversation.pageContext, // the call page's OUI snapshot and knowledge, as for a typed turn
|
|
233
|
+
content: said, // what the model reads: your redacted copy
|
|
234
|
+
};
|
|
235
|
+
},
|
|
236
|
+
opening: (request, target) => greetingTemplateFor(target.accountId), // optional; null lets the model greet
|
|
237
|
+
speak: 'final-round', // optional; only the round the turn ends with is spoken
|
|
238
|
+
holdingLine: (request) => (request.input?.language === 'es' ? 'Un momento.' : 'One moment.'),
|
|
239
|
+
});
|
|
240
|
+
app.post('/agent/live-call/turns', liveCall); // any Node server: (req, res)
|
|
241
|
+
process.on('SIGTERM', () => liveCall.close()); // waits for running turns
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
`createLiveCallTurnHandler(config)` returns a Node `(req, res)` handler with `running()` and `close()`. A body that Express's `json()` already parsed is taken as it is.
|
|
245
|
+
|
|
246
|
+
| Config | |
|
|
247
|
+
|---|---|
|
|
248
|
+
| `runner` | Required. `createAgentTurnRunner(...)`: the runtime that runs your other turns. |
|
|
249
|
+
| `credential` | Required. The bearer credential the call service sends, from your secret store; a list while one is rotated. Compared in constant time. |
|
|
250
|
+
| `resolveTurn(request, { signal })` | Required. The call's `clientRef` → the turn's `conversationId`, `userId`, `accountId` and `socketRoom`, with optional `context`, `userToken`, `approval` and `content`; null when you have no such conversation. `content` is what the model reads in place of `request.text`: your redacted copy (the runtime's `beforeTurn` can do the same on every channel). Do here what your API does for a chat message: store the person's message (your redacted copy; for an `opening`, `liveCallOpeningMessage(request)`), claim the turn, and decide on a waiting readback ("Approvals"). `signal` aborts if the caller hangs up meanwhile. |
|
|
251
|
+
| `opening(request, target, { signal })` | Optional. A greeting from your template for an `opening` turn: streamed, sent to the room and stored as the turn's one assistant message (`runner.reply`), with no model call. Null, undefined or blank lets the model greet. A throw fails the turn. |
|
|
252
|
+
| `speak` | `all` (the default): every round of the reply is spoken as the model writes it, its words before a tool call included. `final-round`: only the round the turn ends with ("The rounds of a turn"): each round's text is held until it ends and sent only when it is final, so nothing written before a tool call is spoken. The reply then starts when its last round is written, not with its first words. |
|
|
253
|
+
| `holdingLine` | With `final-round` only: a line of yours spoken once, as the turn's first tool starts (not a choice the turn ends with), so the caller does not wait in silence. A string, or `(request, target)` returning one (localise from `request.input.language`); null or blank says nothing; a throw fails the turn. Set with `all`, the handler refuses to start: there the model's own words before a tool call are spoken. |
|
|
254
|
+
| `keepAliveMs` | Default 5 s: a `: keep-alive` comment after this long with nothing written. |
|
|
255
|
+
| `maxConcurrentTurns` | Default 8; more are answered `503`. |
|
|
256
|
+
| `maxBodyBytes` | Default 64 KiB. |
|
|
257
|
+
| `onTurnEnd(outcome)` | Each turn's outcome, after it ends. |
|
|
258
|
+
|
|
259
|
+
**The request.** `POST`, `Content-Type: application/json`, `Authorization: Bearer <credential>`:
|
|
260
|
+
|
|
261
|
+
| Field | |
|
|
262
|
+
|---|---|
|
|
263
|
+
| `sessionId` | The call service's session. |
|
|
264
|
+
| `clientRef` | Your conversation reference, given to the call service when the call was created. |
|
|
265
|
+
| `turnId` | Unique per turn; the turn runs under it. |
|
|
266
|
+
| `kind` | `message`: the person said `text`. `opening`: the call has just connected, `text` is empty, and the agent greets: the model reads `liveCallOpeningMessage(request)` where the person's words would be (`LIVE_CALL_OPENING_MESSAGE` when no disclosure was sent). |
|
|
267
|
+
| `text` | What the person said, as transcribed; at most 8,000 characters. |
|
|
268
|
+
| `input` | `{ mode: 'voice', language? }` for what the person said: set as the turn's `context.input`, so the model is told it was transcribed. `{ mode: 'text' }` for a message they typed during the call: read as typed, with no `context.input`. Dropped on an `opening`. |
|
|
269
|
+
| `output` | `{ mode: 'voice', voiceDirections? }`: set as the turn's `context.output`, so the model writes for the ear, and may use the voice's tags when `voiceDirections: { engine, tags, guidance }` offers them ("What a UI client sends with a turn"). |
|
|
270
|
+
| `disclosureLine` | On an `opening`: what the call service has just said to the person before the greeting (that they are talking with an AI assistant), as spoken; at most 1,000 characters. The model is told it was said, and greets following on from it without repeating it. Not read on a `message`. |
|
|
271
|
+
| `supersedes` | Turns this one replaces. Each still running in this process is stopped at once, and the turn's `getHistory` is given them to wait for, as for any superseding message. |
|
|
272
|
+
|
|
273
|
+
`readLiveCallTurnRequest` reads a body as the handler does, and `LIVE_CALL_LIMITS` holds its limits.
|
|
274
|
+
|
|
275
|
+
**The response.** `200 text/event-stream`, flushed event by event:
|
|
276
|
+
|
|
277
|
+
| Event | Data | |
|
|
278
|
+
|---|---|---|
|
|
279
|
+
| `text` | `{ text }` | The reply; concatenate the pieces. With `speak: 'all'`, as the model writes it: rounds written between tool calls are separated by a blank line, as in the room. With `final-round`, the holding line and the turn's last round. |
|
|
280
|
+
| `readback` | `{ approvalId, text, expiresAt }` | The turn stopped at a call that needs approval. `text` is the preview's `spokenReadback` when your `approvals.preview` wrote one, else its `readback`, verbatim; `expiresAt` is ISO 8601. Sent once the turn has ended by itself, after all of its text. A turn that was stopped withdrew its approval, and sends none. |
|
|
281
|
+
| `done` | `{ stopReason? }` | The turn is over: `complete`, `awaiting_approval`, `present_options`, `time_limit`, `output_limit` or `step_count` when it ended by itself; `user_stop`, `superseded` or `deadline` when it was stopped. |
|
|
282
|
+
| `error` | `{ code, message }` | The turn failed or did not run: `RATE_LIMIT`, `SERVICE_UNAVAILABLE`, `MODEL_TIMEOUT`, `TURN_TIMEOUT`, `TURN_DEADLINE_EXCEEDED`, `TURN_REFUSED` (your turn record refused it), `TURN_DECLINED` (your `beforeTurn` refused it) or `WORKER_ERROR`. `message` is a fixed line for the code; the cause stays in your logs. |
|
|
283
|
+
|
|
284
|
+
The stream is written from the turn's own events as the room receives them (`TurnHost.observe`): the same text, from the same model call. Before the stream opens, a refusal is a status and `{ error: { code, message } }`: `400 INVALID_REQUEST` naming the field, `401 UNAUTHORIZED`, `404 UNKNOWN_CLIENT_REF`, `405`, `409 TURN_RUNNING`, `413 BODY_TOO_LARGE`, `415`, `500 RESOLVE_FAILED` (your `resolveTurn` threw, or returned a target that is not a turn; nothing ran) and `503 UNAVAILABLE`.
|
|
285
|
+
|
|
286
|
+
**Barge-in.** When the person speaks over the reply, the call service closes the connection. The turn is stopped as a superseding message stops it (`stopReason: 'superseded'`): what it had produced is stored with the mark and announced to the room, and the next request names it in `supersedes`. A stop asked for through the realtime server (the person's Stop on a page) is heard too, and that stream ends with `done`.
|
|
287
|
+
|
|
288
|
+
Keep the turn's deadline (`turnDeadlineMs`) and the model to a call's pace: a voice turn waits on its first `text` event, so run it on the container adapter, never behind a queue.
|
|
289
|
+
|
|
173
290
|
## Conversation history in the browser
|
|
174
291
|
|
|
175
292
|
`agent-sdk-react` restores a tab's conversation after a reload, and lists or switches conversations, when your API provides two endpoints behind `AgentClientConfig`. Both must be filtered by the signed-in user:
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* pending approval when it stops a turn, redeems the token the next turn
|
|
5
5
|
* carries, and reads a decline.
|
|
6
6
|
*/
|
|
7
|
-
import type { ApprovalOwner, ApprovalRedeemResult, ApprovalSettlement, ApprovalStatus, ApprovalWithdrawal, ApprovalWithdrawReason, PendingApprovalInput } from '@ouispec/agent-core';
|
|
7
|
+
import type { ApprovalChannel, ApprovalDecideResult, ApprovalDecision, ApprovalOwner, ApprovalRedeemResult, ApprovalSettlement, ApprovalStatus, ApprovalWithdrawal, ApprovalWithdrawReason, PendingApprovalInput } from '@ouispec/agent-core';
|
|
8
8
|
export interface ApprovalStoreClient {
|
|
9
9
|
/** Store a pending approval. Rejects when it was not stored: the call must then not wait on it. */
|
|
10
10
|
create(pending: PendingApprovalInput): Promise<void>;
|
|
@@ -34,6 +34,19 @@ export interface ApprovalStoreClient {
|
|
|
34
34
|
* cannot be reached.
|
|
35
35
|
*/
|
|
36
36
|
withdraw?(approvalId: string, owner: ApprovalOwner, reason: ApprovalWithdrawReason): Promise<ApprovalWithdrawal>;
|
|
37
|
+
/**
|
|
38
|
+
* A conversation channel's decision (voice, phone, SMS, chat): the host
|
|
39
|
+
* delivered the approval's readback, and decides as the user from their
|
|
40
|
+
* answer. An `approve` answers with the single-use token the next turn
|
|
41
|
+
* carries as `approval`. A UI approval is decided only by the user's click
|
|
42
|
+
* on their own socket, and the store refuses `ui` here. Optional; rejects
|
|
43
|
+
* when the store cannot be reached.
|
|
44
|
+
*/
|
|
45
|
+
decide?(approvalId: string, by: {
|
|
46
|
+
userId: string;
|
|
47
|
+
decision: ApprovalDecision;
|
|
48
|
+
channel: Exclude<ApprovalChannel, 'ui'>;
|
|
49
|
+
}): Promise<ApprovalDecideResult>;
|
|
37
50
|
}
|
|
38
51
|
export interface HttpApprovalStoreClientConfig {
|
|
39
52
|
/** The realtime server's base URL. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/approvals/client.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,KAAK,EACV,aAAa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MAAM,EAAE,6BAA6B,GAAG,mBAAmB,CAgFxG"}
|
package/dist/approvals/client.js
CHANGED
|
@@ -62,6 +62,15 @@ export function createHttpApprovalStoreClient(config) {
|
|
|
62
62
|
return { approvalId, outcome: 'unknown' };
|
|
63
63
|
throw new Error(`[agent-sdk] The approval store could not withdraw approval ${approvalId}: HTTP ${status}`);
|
|
64
64
|
},
|
|
65
|
+
async decide(approvalId, by) {
|
|
66
|
+
const { status, json } = await call(`/internal/approvals/${encodeURIComponent(approvalId)}/decide`, by);
|
|
67
|
+
if (status === 200 && json.ok === true)
|
|
68
|
+
return json;
|
|
69
|
+
if (status >= 400 && status < 500 && typeof json.reason === 'string') {
|
|
70
|
+
return { ok: false, reason: json.reason, error: String(json.error ?? json.reason) };
|
|
71
|
+
}
|
|
72
|
+
throw new Error(`[agent-sdk] The approval store could not decide approval ${approvalId}: HTTP ${status}`);
|
|
73
|
+
},
|
|
65
74
|
async status(approvalId, userId) {
|
|
66
75
|
const { status, json } = await call(`/internal/approvals/${encodeURIComponent(approvalId)}?${new URLSearchParams({ userId })}`);
|
|
67
76
|
if (status === 200)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/approvals/client.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/approvals/client.ts"],"names":[],"mappings":"AAoBA,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAgD1D,8DAA8D;AAC9D,MAAM,UAAU,6BAA6B,CAAC,MAAqC;IACjF,MAAM,EAAE,GAAG,EAAE,MAAM,EAAE,GAAG,MAAM,CAAC;IAC/B,eAAe,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;IAC7B,MAAM,SAAS,GAAG,MAAM,CAAC,SAAS,IAAI,KAAK,CAAC;IAE5C,MAAM,IAAI,GAAG,KAAK,EAAE,IAAY,EAAE,IAAc,EAAE,EAAE;QAClD,MAAM,GAAG,G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AAE,KAAK,EAAE,MAAM,EAAE,IAAI,CAAC,MAA+B,EAAE,KAAK,EAAE,MAAM,CAAC,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,MAAM,CAAC,EAAE,CAAC;YAC/G,CAAC;YACD,MAAM,IAAI,KAAK,CAAC,4DAA4D,UAAU,UAAU,MAAM,EAAE,CAAC,CAAC;QAC5G,CAAC;QAED,KAAK,CAAC,MAAM,CAAC,UAAU,EAAE,MAAM;YAC7B,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,IAAI,CAAC,uBAAuB,kBAAkB,CAAC,UAAU,CAAC,IAAI,IAAI,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,CAAC,CAAC;YAChI,IAAI,MAAM,KAAK,GAAG;gBAAE,OAAO,IAAiC,CAAC;YAC7D,IAAI,MAAM,KAAK,GAAG;gBAAE,OAAO,IAAI,CAAC;YAChC,MAAM,IAAI,KAAK,CAAC,4DAA4D,UAAU,UAAU,MAAM,EAAE,CAAC,CAAC;QAC5G,CAAC;KACF,CAAC;AACJ,CAAC"}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The host's say over an approval before it is asked for: whether the call
|
|
3
|
+
* may be asked for at all, and the words the person is shown and told.
|
|
4
|
+
*
|
|
5
|
+
* - **`validateBeforeApproval`** checks a call before it is read back. A
|
|
6
|
+
* booking for a time the product never offered is refused here, and the
|
|
7
|
+
* model is told why as the call's error and can correct it, instead of the
|
|
8
|
+
* person approving a readback the tool then refuses.
|
|
9
|
+
* - **`preview`** writes the approval's display copy: what the card shows, the
|
|
10
|
+
* readback a conversation channel reads or sends, and the readback a voice
|
|
11
|
+
* speaks. A host redacts a value there (an account number, a phone number),
|
|
12
|
+
* or writes it in the person's language, with dates, times and numbers as
|
|
13
|
+
* words. The call that runs is still exactly the model's: the approval store
|
|
14
|
+
* keeps the original arguments, and the args hash it is bound to is theirs.
|
|
15
|
+
* Only the preview stored with it, sent to the room and spoken is the
|
|
16
|
+
* host's.
|
|
17
|
+
*
|
|
18
|
+
* Both fail closed. A validator that throws refuses the call; a preview hook
|
|
19
|
+
* that throws, or returns something that is not a preview, means the approval
|
|
20
|
+
* cannot be asked for, so the call is not run. Falling back to the built
|
|
21
|
+
* preview would show the very values a redacting host removed.
|
|
22
|
+
*/
|
|
23
|
+
import { type ApprovalPreview } from '@ouispec/agent-core';
|
|
24
|
+
import type { RegisteredTool } from '../tools/types.js';
|
|
25
|
+
import type { AgentTurnChannel, AgentTurnInfo } from '../runtime/turn-info.js';
|
|
26
|
+
/** What a host's approval hooks are told of the call's turn. */
|
|
27
|
+
export interface ApprovalHookContext {
|
|
28
|
+
turn: AgentTurnInfo;
|
|
29
|
+
/** How the turn reached the runtime: `turn.channel`. */
|
|
30
|
+
channel: AgentTurnChannel;
|
|
31
|
+
/**
|
|
32
|
+
* The language to write the person's copy in, as a BCP 47 tag: the
|
|
33
|
+
* language their message was recognised in (on a call, the request's
|
|
34
|
+
* `input.language`). Null when the turn does not say: a typed message.
|
|
35
|
+
*/
|
|
36
|
+
locale: string | null;
|
|
37
|
+
userId: string;
|
|
38
|
+
accountId: string;
|
|
39
|
+
conversationId: string;
|
|
40
|
+
}
|
|
41
|
+
/** What `approvals.preview` is told: the turn, and the preview the SDK built from the action's declaration. */
|
|
42
|
+
export interface ApprovalPreviewContext extends ApprovalHookContext {
|
|
43
|
+
/** The SDK's preview, built from the declaration and the call's raw arguments. */
|
|
44
|
+
built: ApprovalPreview;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Writes an approval's display copy. Return the preview to store, show and
|
|
48
|
+
* read back: `readback` for the card's line and for text channels,
|
|
49
|
+
* `spokenReadback` for a voice (the live-call handler speaks it in place of
|
|
50
|
+
* `readback`). Return `built` unchanged to keep the SDK's.
|
|
51
|
+
*/
|
|
52
|
+
export type ApprovalPreviewHook = (tool: RegisteredTool, args: Record<string, unknown>, ctx: ApprovalPreviewContext) => ApprovalPreview | Promise<ApprovalPreview>;
|
|
53
|
+
/** Whether a call may be asked for: `{ ok: false, error }` refuses it, and `error` is the model's to read. */
|
|
54
|
+
export type ApprovalValidation = {
|
|
55
|
+
ok: true;
|
|
56
|
+
} | {
|
|
57
|
+
ok: false;
|
|
58
|
+
error: string;
|
|
59
|
+
};
|
|
60
|
+
/** Checks a call that needs approval before its readback is shown or spoken. */
|
|
61
|
+
export type ValidateBeforeApproval = (tool: RegisteredTool, args: Record<string, unknown>, ctx: ApprovalHookContext) => ApprovalValidation | Promise<ApprovalValidation>;
|
|
62
|
+
/** The approval hooks the orchestrator runs. */
|
|
63
|
+
export interface ApprovalHooks {
|
|
64
|
+
preview?: ApprovalPreviewHook;
|
|
65
|
+
validateBeforeApproval?: ValidateBeforeApproval;
|
|
66
|
+
}
|
|
67
|
+
/** The longest refusal a validator's error is given to the model as. */
|
|
68
|
+
export declare const MAX_VALIDATION_ERROR_CHARS = 2000;
|
|
69
|
+
/** A validator's answer as the orchestrator acts on it: refused with the model's reason, or not. */
|
|
70
|
+
export declare function readValidation(value: unknown): ApprovalValidation;
|
|
71
|
+
/**
|
|
72
|
+
* A host's preview, checked against what the approval store accepts: the
|
|
73
|
+
* preview, or why it is not one.
|
|
74
|
+
*/
|
|
75
|
+
export declare function readHostPreview(value: unknown): {
|
|
76
|
+
ok: true;
|
|
77
|
+
preview: ApprovalPreview;
|
|
78
|
+
} | {
|
|
79
|
+
ok: false;
|
|
80
|
+
error: string;
|
|
81
|
+
};
|
|
82
|
+
//# sourceMappingURL=hooks.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../../src/approvals/hooks.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,OAAO,EAAgC,KAAK,eAAe,EAAE,MAAM,qBAAqB,CAAC;AACzF,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACxD,OAAO,K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AAK,EAAE,OAAO,GAAG,kBAAkB,CAOjE;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,KAAK,EAAE,OAAO,GAAG;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,OAAO,EAAE,eAAe,CAAA;CAAE,GAAG;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAyCrH"}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The host's say over an approval before it is asked for: whether the call
|
|
3
|
+
* may be asked for at all, and the words the person is shown and told.
|
|
4
|
+
*
|
|
5
|
+
* - **`validateBeforeApproval`** checks a call before it is read back. A
|
|
6
|
+
* booking for a time the product never offered is refused here, and the
|
|
7
|
+
* model is told why as the call's error and can correct it, instead of the
|
|
8
|
+
* person approving a readback the tool then refuses.
|
|
9
|
+
* - **`preview`** writes the approval's display copy: what the card shows, the
|
|
10
|
+
* readback a conversation channel reads or sends, and the readback a voice
|
|
11
|
+
* speaks. A host redacts a value there (an account number, a phone number),
|
|
12
|
+
* or writes it in the person's language, with dates, times and numbers as
|
|
13
|
+
* words. The call that runs is still exactly the model's: the approval store
|
|
14
|
+
* keeps the original arguments, and the args hash it is bound to is theirs.
|
|
15
|
+
* Only the preview stored with it, sent to the room and spoken is the
|
|
16
|
+
* host's.
|
|
17
|
+
*
|
|
18
|
+
* Both fail closed. A validator that throws refuses the call; a preview hook
|
|
19
|
+
* that throws, or returns something that is not a preview, means the approval
|
|
20
|
+
* cannot be asked for, so the call is not run. Falling back to the built
|
|
21
|
+
* preview would show the very values a redacting host removed.
|
|
22
|
+
*/
|
|
23
|
+
import { APPROVAL_PREVIEW_LIMITS as L } from '@ouispec/agent-core';
|
|
24
|
+
/** The longest refusal a validator's error is given to the model as. */
|
|
25
|
+
export const MAX_VALIDATION_ERROR_CHARS = 2_000;
|
|
26
|
+
/** A validator's answer as the orchestrator acts on it: refused with the model's reason, or not. */
|
|
27
|
+
export function readValidation(value) {
|
|
28
|
+
if (value && typeof value === 'object' && value.ok === true)
|
|
29
|
+
return { ok: true };
|
|
30
|
+
const error = value && typeof value === 'object' ? value.error : undefined;
|
|
31
|
+
if (value && typeof value === 'object' && value.ok === false && typeof error === 'string' && error.trim()) {
|
|
32
|
+
return { ok: false, error: error.trim().slice(0, MAX_VALIDATION_ERROR_CHARS) };
|
|
33
|
+
}
|
|
34
|
+
return { ok: false, error: 'It could not be checked, so it was not asked for.' };
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* A host's preview, checked against what the approval store accepts: the
|
|
38
|
+
* preview, or why it is not one.
|
|
39
|
+
*/
|
|
40
|
+
export function readHostPreview(value) {
|
|
41
|
+
const refuse = (error) => ({ ok: false, error });
|
|
42
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
43
|
+
return refuse('it is not an object');
|
|
44
|
+
const v = value;
|
|
45
|
+
const text = (field, max, required, nonBlank = false) => {
|
|
46
|
+
const s = v[field];
|
|
47
|
+
if (s === undefined && !required)
|
|
48
|
+
return null;
|
|
49
|
+
if (typeof s !== 'string')
|
|
50
|
+
return `${field} must be a string`;
|
|
51
|
+
if (s.length > max)
|
|
52
|
+
return `${field} is longer than ${max} characters`;
|
|
53
|
+
if (nonBlank && !s.trim())
|
|
54
|
+
return `${field} is blank`;
|
|
55
|
+
return null;
|
|
56
|
+
};
|
|
57
|
+
const problem = text('title', L.title, true, true) ??
|
|
58
|
+
text('consequence', L.consequence, false) ??
|
|
59
|
+
text('readback', L.readback, true, true) ??
|
|
60
|
+
text('spokenReadback', L.readback, false, true);
|
|
61
|
+
if (problem)
|
|
62
|
+
return refuse(problem);
|
|
63
|
+
const args = v.arguments;
|
|
64
|
+
if (!Array.isArray(args))
|
|
65
|
+
return refuse('arguments must be a list');
|
|
66
|
+
if (args.length > L.arguments)
|
|
67
|
+
return refuse(`arguments holds more than ${L.arguments} entries`);
|
|
68
|
+
for (const [i, a] of args.entries()) {
|
|
69
|
+
const entry = a;
|
|
70
|
+
if (!entry || typeof entry !== 'object' || Array.isArray(entry))
|
|
71
|
+
return refuse(`arguments[${i}] is not an object`);
|
|
72
|
+
if (typeof entry.name !== 'string' || !entry.name || entry.name.length > L.argumentName)
|
|
73
|
+
return refuse(`arguments[${i}].name must be 1–${L.argumentName} characters`);
|
|
74
|
+
if (typeof entry.label !== 'string' || !entry.label || entry.label.length > L.argumentLabel)
|
|
75
|
+
return refuse(`arguments[${i}].label must be 1–${L.argumentLabel} characters`);
|
|
76
|
+
if (typeof entry.value !== 'string' || entry.value.length > L.argumentValue)
|
|
77
|
+
return refuse(`arguments[${i}].value must be a string of at most ${L.argumentValue} characters`);
|
|
78
|
+
}
|
|
79
|
+
const known = new Set(['title', 'consequence', 'arguments', 'readback', 'spokenReadback']);
|
|
80
|
+
const unknown = Object.keys(v).filter((k) => !known.has(k));
|
|
81
|
+
if (unknown.length > 0)
|
|
82
|
+
return refuse(`it has fields a preview does not: ${unknown.join(', ')}`);
|
|
83
|
+
return {
|
|
84
|
+
ok: true,
|
|
85
|
+
preview: {
|
|
86
|
+
title: v.title,
|
|
87
|
+
...(typeof v.consequence === 'string' ? { consequence: v.consequence } : {}),
|
|
88
|
+
arguments: args.map((a) => ({ name: a.name, label: a.label, value: a.value })),
|
|
89
|
+
readback: v.readback,
|
|
90
|
+
...(typeof v.spokenReadback === 'string' ? { spokenReadback: v.spokenReadback } : {}),
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
//# sourceMappingURL=hooks.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hooks.js","sourceRoot":"","sources":["../../src/approvals/hooks.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,OAAO,EAAE,uBAAuB,IAAI,CAAC,EAAwB,MAAM,qBAAqB,CAAC;AAsDzF,wEAAwE;AACxE,MAAM,CAAC,MAAM,0BAA0B,GAAG,KAAK,CAAC;AAEhD,oGA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AW,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YAC5E,SAAS,EAAG,IAAsC,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC;YACjH,QAAQ,EAAE,CAAC,CAAC,QAAkB;YAC9B,GAAG,CAAC,OAAO,CAAC,CAAC,cAAc,KAAK,QAAQ,CAAC,CAAC,CAAC,EAAE,cAAc,EAAE,CAAC,CAAC,cAAc,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SACtF;KACF,CAAC;AACJ,CAAC"}
|
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
import { type TurnOutcome } from '../runtime/turn-runner.js';
|
|
2
2
|
import type { AgentRuntimeConfig } from '../runtime/types.js';
|
|
3
|
+
import { type LiveCallTurnOptions } from '../live-call/handler.js';
|
|
4
|
+
/** The live-call route on the container: its settings, and where it is served. */
|
|
5
|
+
export interface ContainerLiveCallRoute extends LiveCallTurnOptions {
|
|
6
|
+
/** The path it is served at. Default `/live-call/turns`. */
|
|
7
|
+
path?: string;
|
|
8
|
+
}
|
|
9
|
+
/** Where the container serves the live-call route unless told otherwise. */
|
|
10
|
+
export declare const DEFAULT_LIVE_CALL_PATH = "/live-call/turns";
|
|
3
11
|
export interface ContainerAgentConfig<TDb> extends AgentRuntimeConfig<TDb> {
|
|
4
12
|
/** The port to listen on. `0` picks a free one. Required. */
|
|
5
13
|
port: number;
|
|
@@ -11,6 +19,12 @@ export interface ContainerAgentConfig<TDb> extends AgentRuntimeConfig<TDb> {
|
|
|
11
19
|
maxBodyBytes?: number;
|
|
12
20
|
/** Called with each turn's outcome, after it ends. */
|
|
13
21
|
onTurnEnd?: (outcome: TurnOutcome) => void;
|
|
22
|
+
/**
|
|
23
|
+
* Serves live-call turns too (`createLiveCallTurnHandler`), on the
|
|
24
|
+
* same runtime and slots. Its requests carry the call service's bearer
|
|
25
|
+
* credential, not `workerApiKey`.
|
|
26
|
+
*/
|
|
27
|
+
liveCall?: ContainerLiveCallRoute;
|
|
14
28
|
}
|
|
15
29
|
export interface ContainerAgentWorker {
|
|
16
30
|
/** The port the server listens on (the one picked, when configured with 0). */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/container/server.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../../src/container/server.ts"],"names":[],"mappings":"AAqBA,OAAO,EAAyC,KAAK,WAAW,EAAE,MAAM,2BAA2B,CAAC;AAEpG,OAAO,KAAK,EAAE,kBAAkB,EAAoB,MAAM,qBAAqB,CAAC;AAChF,OAAO,EAAiB,KAAK,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAElF,kFAAkF;AAClF,MAAM,WAAW,sBAAuB,SAAQ,mBAAmB;IACjE,4DAA4D;IAC5D,IAAI,CAAC,EAAE,MAAM,CAAC;CACf;AAED,4EAA4E;AAC5E,eAAO,MAAM,sBAAsB,qBAAqB,CAAC;AAEzD,MAAM,WAAW,oBAAoB,CAAC,GAAG,CAAE,SAAQ,kBAAkB,CAAC,GAAG,CAAC;IACxE,6DAA6D;IAC7D,IAAI,EAAE,MAAM,CAAC;IACb,kGAAkG;IAClG,YAAY,EAAE,MAAM,CAAC;IACrB,+DAA+D;IAC/D,kBAAkB,CAAC,EAAE,MAAM,CAAC;IAC5B,qDAAqD;IACrD,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,sDAAsD;IACtD,SAAS,CAAC,EAAE,CAAC,OAAO,EAAE,WAAW,KAAK,IAAI,CAAC;IAC3C;;;;OAIG;IACH,QAAQ,CAAC,EAAE,sBAAsB,CAAC;CACnC;AAED,MAAM,WAAW,oBAAoB;IACnC,+EAA+E;IAC/E,IAAI,EAAE,MAAM,CAAC;IACb,yBAAyB;IACzB,OAAO,IAAI,MAAM,CAAC;IAClB,0EAA0E;IAC1E,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB;AAED,wBAAsB,yBAAyB,CAAC,GAAG,EAAE,MAAM,EAAE,oBAAoB,CAAC,GAAG,CAAC,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAkHrH"}
|
package/dist/container/server.js
CHANGED
|
@@ -9,11 +9,20 @@
|
|
|
9
9
|
* POST /turns AgentTurnPayload → 202 { turnId }
|
|
10
10
|
* 400 not a turn · 401 wrong key · 409 turn already running
|
|
11
11
|
* 503 at capacity or shutting down (retry later)
|
|
12
|
+
* POST <liveCall.path> a live-call turn → 200 text/event-stream (live-call/handler.ts),
|
|
13
|
+
* when `liveCall` is configured
|
|
12
14
|
* GET /health 200 { status, running, capacity, model }
|
|
15
|
+
*
|
|
16
|
+
* Both routes take turns from one set of slots: `maxConcurrentTurns` bounds
|
|
17
|
+
* them together, and closing waits for both.
|
|
13
18
|
*/
|
|
14
19
|
import http from 'node:http';
|
|
15
20
|
import crypto from 'node:crypto';
|
|
16
21
|
import { createAgentTurnRunner, payloadRefusal } from '../runtime/turn-runner.js';
|
|
22
|
+
import { createTurnSlots } from '../runtime/turn-slots.js';
|
|
23
|
+
import { liveCallRoute } from '../live-call/handler.js';
|
|
24
|
+
/** Where the container serves the live-call route unless told otherwise. */
|
|
25
|
+
export const DEFAULT_LIVE_CALL_PATH = '/live-call/turns';
|
|
17
26
|
export async function startContainerAgentWorker(config) {
|
|
18
27
|
const missing = [
|
|
19
28
|
!(Number.isInteger(config?.port) && config.port >= 0) && 'port (the port to listen on, 0 for any free port)',
|
|
@@ -21,14 +30,21 @@ export async function startContainerAgentWorker(config) {
|
|
|
21
30
|
].filter(Boolean);
|
|
22
31
|
if (missing.length > 0)
|
|
23
32
|
throw new Error(`[agent-sdk] Missing required configuration: ${missing.join('; ')}`);
|
|
33
|
+
const liveCallPath = config.liveCall ? (config.liveCall.path ?? DEFAULT_LIVE_CALL_PATH) : null;
|
|
34
|
+
if (liveCallPath !== null && (!liveCallPath.startsWith('/') || liveCallPath === '/turns' || liveCallPath === '/health')) {
|
|
35
|
+
throw new Error(`[agent-sdk] liveCall.path must be a path of its own beginning with '/', not ${JSON.stringify(liveCallPath)}`);
|
|
36
|
+
}
|
|
24
37
|
const runner = createAgentTurnRunner(config);
|
|
25
38
|
const capacity = config.maxConcurrentTurns ?? 8;
|
|
39
|
+
const slots = createTurnSlots(capacity);
|
|
26
40
|
const maxBodyBytes = config.maxBodyBytes ?? 1024 * 1024;
|
|
41
|
+
const liveCall = config.liveCall
|
|
42
|
+
? liveCallRoute(config.liveCall, { runner, slots, maxBodyBytes: Math.min(maxBodyBytes, 64 * 1024), onTurnEnd: config.onTurnEnd })
|
|
43
|
+
: null;
|
|
27
44
|
const expectedKey = crypto.createHash('sha256').update(config.workerApiKey).digest();
|
|
28
45
|
const isKey = (presented) => typeof presented === 'string' &&
|
|
29
46
|
presented.length > 0 &&
|
|
30
47
|
crypto.timingSafeEqual(crypto.createHash('sha256').update(presented).digest(), expectedKey);
|
|
31
|
-
const inFlight = new Map();
|
|
32
48
|
let closing = false;
|
|
33
49
|
const send = (res, status, body) => {
|
|
34
50
|
res.writeHead(status, { 'content-type': 'application/json' });
|
|
@@ -36,7 +52,11 @@ export async function startContainerAgentWorker(config) {
|
|
|
36
52
|
};
|
|
37
53
|
const server = http.createServer((req, res) => {
|
|
38
54
|
if (req.method === 'GET' && req.url === '/health') {
|
|
39
|
-
send(res, closing ? 503 : 200, { status: closing ? 'closing' : 'ok', running:
|
|
55
|
+
send(res, closing ? 503 : 200, { status: closing ? 'closing' : 'ok', running: slots.running(), capacity, model: runner.model });
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
if (liveCall && pathOf(req.url) === liveCallPath) {
|
|
59
|
+
liveCall(req, res);
|
|
40
60
|
return;
|
|
41
61
|
}
|
|
42
62
|
if (req.method !== 'POST' || req.url !== '/turns') {
|
|
@@ -74,16 +94,8 @@ export async function startContainerAgentWorker(config) {
|
|
|
74
94
|
send(res, 400, { error: refusal });
|
|
75
95
|
return;
|
|
76
96
|
}
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
return;
|
|
80
|
-
}
|
|
81
|
-
if (closing || inFlight.size >= capacity) {
|
|
82
|
-
send(res, 503, { error: closing ? 'shutting down' : 'at capacity' });
|
|
83
|
-
return;
|
|
84
|
-
}
|
|
85
|
-
const run = runner
|
|
86
|
-
.run(payload)
|
|
97
|
+
const busy = slots.take(payload.turnId, () => runner
|
|
98
|
+
.run(payload, { channel: 'container' })
|
|
87
99
|
.then((outcome) => config.onTurnEnd?.(outcome))
|
|
88
100
|
.catch((err) => {
|
|
89
101
|
// A turn's own failure is an outcome, not a throw; this is the
|
|
@@ -93,9 +105,11 @@ export async function startContainerAgentWorker(config) {
|
|
|
93
105
|
turnId: payload.turnId,
|
|
94
106
|
error: err instanceof Error ? err.message : String(err),
|
|
95
107
|
});
|
|
96
|
-
})
|
|
97
|
-
|
|
98
|
-
|
|
108
|
+
}));
|
|
109
|
+
if (busy) {
|
|
110
|
+
send(res, busy.status, { error: busy.error });
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
99
113
|
send(res, 202, { turnId: payload.turnId });
|
|
100
114
|
});
|
|
101
115
|
});
|
|
@@ -108,12 +122,17 @@ export async function startContainerAgentWorker(config) {
|
|
|
108
122
|
});
|
|
109
123
|
return {
|
|
110
124
|
port: server.address().port,
|
|
111
|
-
running: () =>
|
|
125
|
+
running: () => slots.running(),
|
|
112
126
|
async close() {
|
|
113
127
|
closing = true;
|
|
114
|
-
await
|
|
128
|
+
await slots.drain();
|
|
115
129
|
await new Promise((resolve) => server.close(() => resolve()));
|
|
116
130
|
},
|
|
117
131
|
};
|
|
118
132
|
}
|
|
133
|
+
/** The path of a request URL, without its query. */
|
|
134
|
+
function pathOf(url) {
|
|
135
|
+
const end = (url ?? '').search(/[?#]/);
|
|
136
|
+
return end === -1 ? (url ?? '') : (url ?? '').slice(0, end);
|
|
137
|
+
}
|
|
119
138
|
//# sourceMappingURL=server.js.map
|