@ouispec/agent-worker 0.13.1 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +83 -4
  2. package/dist/approvals/client.d.ts +14 -1
  3. package/dist/approvals/client.d.ts.map +1 -1
  4. package/dist/approvals/client.js +9 -0
  5. package/dist/approvals/client.js.map +1 -1
  6. package/dist/container/server.d.ts +14 -0
  7. package/dist/container/server.d.ts.map +1 -1
  8. package/dist/container/server.js +35 -16
  9. package/dist/container/server.js.map +1 -1
  10. package/dist/emit/tee.d.ts +18 -0
  11. package/dist/emit/tee.d.ts.map +1 -0
  12. package/dist/emit/tee.js +19 -0
  13. package/dist/emit/tee.js.map +1 -0
  14. package/dist/index.d.ts +11 -4
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +8 -2
  17. package/dist/index.js.map +1 -1
  18. package/dist/live-call/event-stream.d.ts +20 -0
  19. package/dist/live-call/event-stream.d.ts.map +1 -0
  20. package/dist/live-call/event-stream.js +43 -0
  21. package/dist/live-call/event-stream.js.map +1 -0
  22. package/dist/live-call/handler.d.ts +121 -0
  23. package/dist/live-call/handler.d.ts.map +1 -0
  24. package/dist/live-call/handler.js +338 -0
  25. package/dist/live-call/handler.js.map +1 -0
  26. package/dist/live-call/protocol.d.ts +131 -0
  27. package/dist/live-call/protocol.d.ts.map +1 -0
  28. package/dist/live-call/protocol.js +138 -0
  29. package/dist/live-call/protocol.js.map +1 -0
  30. package/dist/orchestrator.d.ts.map +1 -1
  31. package/dist/orchestrator.js +39 -6
  32. package/dist/orchestrator.js.map +1 -1
  33. package/dist/prompt/spoken-reply.d.ts +28 -0
  34. package/dist/prompt/spoken-reply.d.ts.map +1 -0
  35. package/dist/prompt/spoken-reply.js +37 -0
  36. package/dist/prompt/spoken-reply.js.map +1 -0
  37. package/dist/reasoning-relay.d.ts +32 -0
  38. package/dist/reasoning-relay.d.ts.map +1 -0
  39. package/dist/reasoning-relay.js +96 -0
  40. package/dist/reasoning-relay.js.map +1 -0
  41. package/dist/runtime/turn-runner.d.ts +28 -4
  42. package/dist/runtime/turn-runner.d.ts.map +1 -1
  43. package/dist/runtime/turn-runner.js +93 -35
  44. package/dist/runtime/turn-runner.js.map +1 -1
  45. package/dist/runtime/turn-slots.d.ts +30 -0
  46. package/dist/runtime/turn-slots.d.ts.map +1 -0
  47. package/dist/runtime/turn-slots.js +36 -0
  48. package/dist/runtime/turn-slots.js.map +1 -0
  49. package/dist/runtime/types.d.ts +10 -0
  50. package/dist/runtime/types.d.ts.map +1 -1
  51. package/dist/stop/turn-stop.d.ts +12 -1
  52. package/dist/stop/turn-stop.d.ts.map +1 -1
  53. package/dist/stop/turn-stop.js +47 -0
  54. package/dist/stop/turn-stop.js.map +1 -1
  55. package/dist/types.d.ts +10 -0
  56. package/dist/types.d.ts.map +1 -1
  57. package/dist/ui/snapshot.d.ts +6 -4
  58. package/dist/ui/snapshot.d.ts.map +1 -1
  59. package/dist/ui/snapshot.js +8 -6
  60. package/dist/ui/snapshot.js.map +1 -1
  61. package/package.json +5 -5
@@ -0,0 +1,43 @@
1
+ /** How long the stream may be silent before a `: keep-alive` comment is sent. */
2
+ export const DEFAULT_KEEP_ALIVE_MS = 5_000;
3
+ /** Answers `200 text/event-stream` on `res` at once, and returns the stream. */
4
+ export function openLiveCallEventStream(res, keepAliveMs = DEFAULT_KEEP_ALIVE_MS) {
5
+ res.writeHead(200, {
6
+ 'content-type': 'text/event-stream; charset=utf-8',
7
+ 'cache-control': 'no-cache, no-transform',
8
+ connection: 'keep-alive',
9
+ // A proxy in front of the product must pass each event on as it is written.
10
+ 'x-accel-buffering': 'no',
11
+ });
12
+ res.flushHeaders();
13
+ // Each event is written as soon as it is produced: a reply's first words are what the caller waits on.
14
+ res.socket?.setNoDelay(true);
15
+ const open = () => !res.writableEnded && !res.destroyed;
16
+ const keepAlive = setTimeout(function beat() {
17
+ if (!open())
18
+ return;
19
+ res.write(': keep-alive\n\n');
20
+ keepAlive.refresh();
21
+ }, keepAliveMs);
22
+ const stop = () => clearTimeout(keepAlive);
23
+ res.once('close', stop);
24
+ const write = (chunk) => {
25
+ if (!open())
26
+ return;
27
+ res.write(chunk);
28
+ // The silence is counted from the last thing written.
29
+ keepAlive.refresh();
30
+ };
31
+ return {
32
+ send(event, data) {
33
+ write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
34
+ },
35
+ end() {
36
+ stop();
37
+ if (open())
38
+ res.end();
39
+ },
40
+ open,
41
+ };
42
+ }
43
+ //# sourceMappingURL=event-stream.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"event-stream.js","sourceRoot":"","sources":["../../src/live-call/event-stream.ts"],"names":[],"mappings":"AAQA,iFAAiF;AACjF,MAAM,CAAC,MAAM,qBAAqB,GAAG,KAAK,CAAC;AAW3C,gFAAgF;AAChF,MAAM,UAAU,uBAAuB,CAAC,GAAmB,EAAE,cAAsB,qBAAqB;IACtG,GAAG,CAAC,SAAS,CAAC,GAAG,EAAE;QACjB,cAAc,EAAE,kCAAkC;QAClD,eAAe,EAAE,wBAAwB;QACzC,UAAU,EAAE,YAAY;QACxB,4EAA4E;QAC5E,mBAAmB,EAAE,IAAI;KAC1B,CAAC,CAAC;IACH,GAAG,CAAC,YAAY,EAAE,CAAC;IACnB,uGAAuG;IACvG,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,IAAI,CAAC,CAAC;IAE7B,MAAM,IAAI,GAAG,GAAG,EAAE,CAAC,CAAC,GAAG,CAAC,aAAa,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC;IACxD,MAAM,SAAS,GAAG,UAAU,CAAC,SAAS,IAAI;QACxC,IAAI,CAAC,IAAI,EAAE;YAAE,OAAO;QACpB,GAAG,CAAC,KAAK,CAAC,kBAAkB,CAAC,CAAC;QAC9B,SAAS,CAAC,OAAO,EAAE,CAAC;IACtB,CAAC,EAAE,WAAW,CAAC,CAAC;IAChB,MAAM,IAAI,GAAG,GAAG,EAAE,CAAC,YAAY,CAAC,SAAS,CAAC,CAAC;IAC3C,GAAG,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IAExB,MAAM,KAAK,GAAG,CAAC,KAAa,EAAE,EAAE;QAC9B,IAAI,CAAC,IAAI,EAAE;YAAE,OAAO;QACpB,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC;QACjB,sDAAsD;QACtD,SAAS,CAAC,OAAO,EAAE,CAAC;IACtB,CAAC,CAAC;IAEF,OAAO;QACL,IAAI,CAAC,KAAK,EAAE,IAAI;YACd,KAAK,CAAC,UAAU,KAAK,WAAW,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAC9D,CAAC;QACD,GAAG;YACD,IAAI,EAAE,CAAC;YACP,IAAI,IAAI,EAAE;gBAAE,GAAG,CAAC,GAAG,EAAE,CAAC;QACxB,CAAC;QACD,IAAI;KACL,CAAC;AACJ,CAAC"}
@@ -0,0 +1,121 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import { type ApprovalContinuation } from '@ouispec/agent-core';
3
+ import { type AgentTurnRunner, type TurnOutcome } from '../runtime/turn-runner.js';
4
+ import { type TurnSlots } from '../runtime/turn-slots.js';
5
+ import { type LiveCallTurnRequest } from './protocol.js';
6
+ /** Who and where a live-call turn is, in the product: what the host resolves a call's `clientRef` to. */
7
+ export interface LiveCallTurnTarget {
8
+ /** The product's conversation: the call is one more way to reach it. */
9
+ conversationId: string;
10
+ /** The user the turn acts as: the conversation's principal. */
11
+ userId: string;
12
+ accountId: string;
13
+ /** The conversation's realtime room: the turn streams there, and its UI actions reach every page joined to it. */
14
+ socketRoom: string;
15
+ /** Passed to the turn's tools as the payload's `userToken`. */
16
+ userToken?: string;
17
+ /**
18
+ * The turn's context, as the product would send it for a typed message on
19
+ * the conversation's page: its OUI snapshot, its knowledge, its page
20
+ * context. `input` and `output` are the request's, and are set by the handler.
21
+ */
22
+ context?: Record<string, unknown> | null;
23
+ /**
24
+ * The decision on an approval the agent read back, when the host takes this
25
+ * message as the answer to it: the host classified the person's words, and
26
+ * decided as the user (`ApprovalStoreClient.decide` with a conversation
27
+ * channel). With `approve`, its `token`: the turn redeems it and runs
28
+ * exactly the stored call.
29
+ */
30
+ approval?: ApprovalContinuation;
31
+ }
32
+ /** What the host's callbacks are told beside the request. */
33
+ export interface LiveCallTurnCallContext {
34
+ /** Aborts when the call service closes the connection: the person spoke again. */
35
+ signal: AbortSignal;
36
+ }
37
+ /** The live-call route's own settings, wherever it is mounted. */
38
+ export interface LiveCallTurnOptions {
39
+ /**
40
+ * The credential the call service sends as `Authorization: Bearer …`, from
41
+ * the product's secret store. Several are accepted while one is rotated.
42
+ * Required.
43
+ */
44
+ credential: string | readonly string[];
45
+ /**
46
+ * Resolves the call's `clientRef` to the turn's conversation, user and room,
47
+ * or null when the product has no such conversation (answered `404`).
48
+ * Required.
49
+ *
50
+ * This is where the product does what its API does for a message from its
51
+ * own chat: store the person's message (`request.text`, entered as
52
+ * `request.input`) in the conversation, or for an `opening` turn
53
+ * `LIVE_CALL_OPENING_MESSAGE`; claim the turn record; and, when a readback
54
+ * is waiting, decide on it from what the person said. What it throws is
55
+ * answered `500`, and nothing runs.
56
+ */
57
+ resolveTurn: (request: LiveCallTurnRequest, call: LiveCallTurnCallContext) => LiveCallTurnTarget | null | Promise<LiveCallTurnTarget | null>;
58
+ /**
59
+ * A greeting for an `opening` turn from the product's template, instead of
60
+ * the model's: the turn's reply is this text, streamed and stored as the
61
+ * model's would be. Null, undefined or blank lets the model greet. What it
62
+ * throws fails the turn (`error` event); the model does not greet instead.
63
+ */
64
+ opening?: (request: LiveCallTurnRequest, target: LiveCallTurnTarget, call: LiveCallTurnCallContext) => string | null | undefined | Promise<string | null | undefined>;
65
+ /** How long the response may be silent before a `: keep-alive` comment. Default 5 s, well inside the call service's 15 s. */
66
+ keepAliveMs?: number;
67
+ }
68
+ /** `createLiveCallTurnHandler`'s configuration: the route's settings and the runtime that runs its turns. */
69
+ export interface LiveCallTurnHandlerConfig extends LiveCallTurnOptions {
70
+ /** The runtime (`createAgentTurnRunner`): the same one that runs the product's other turns. Required. */
71
+ runner: AgentTurnRunner;
72
+ /** Turns run at once; more are answered `503`. Default 8. */
73
+ maxConcurrentTurns?: number;
74
+ /** Largest request body, in bytes. Default 64 KiB. */
75
+ maxBodyBytes?: number;
76
+ /** Called with each turn's outcome, after it ends. */
77
+ onTurnEnd?: (outcome: TurnOutcome) => void;
78
+ }
79
+ /** A Node request handler: mount it on a `POST` route of the product's own server. */
80
+ export interface LiveCallTurnHandler {
81
+ (req: IncomingMessage, res: ServerResponse): void;
82
+ /** Turns running now. */
83
+ running(): number;
84
+ /** Takes no more turns, and resolves once every running one has ended. */
85
+ close(): Promise<void>;
86
+ }
87
+ /** What the route needs from its host: the runtime and the process's turn slots. */
88
+ interface LiveCallRouteHost {
89
+ runner: AgentTurnRunner;
90
+ slots: TurnSlots;
91
+ maxBodyBytes: number;
92
+ onTurnEnd?: (outcome: TurnOutcome) => void;
93
+ }
94
+ /**
95
+ * Creates the live-call turn handler.
96
+ *
97
+ * @example
98
+ * ```ts
99
+ * const runner = createAgentTurnRunner(runtimeConfig);
100
+ * const liveCall = createLiveCallTurnHandler({
101
+ * runner,
102
+ * credential: env.LIVE_CALL_BRAIN_CREDENTIAL,
103
+ * resolveTurn: async (request) => {
104
+ * const conversation = await db.conversation.findUnique({ where: { callRef: request.clientRef } });
105
+ * if (!conversation) return null;
106
+ * await db.message.create({ data: { conversationId: conversation.id, role: 'user', content: request.text, input: request.input } });
107
+ * return { conversationId: conversation.id, userId: conversation.userId, accountId: conversation.accountId, socketRoom: `conversation:${conversation.id}` };
108
+ * },
109
+ * });
110
+ * app.post('/agent/live-call/turns', liveCall);
111
+ * process.on('SIGTERM', () => liveCall.close());
112
+ * ```
113
+ */
114
+ export declare function createLiveCallTurnHandler(config: LiveCallTurnHandlerConfig): LiveCallTurnHandler;
115
+ /**
116
+ * The route, for a host that already runs turns (the container adapter): it
117
+ * shares that host's runtime and slots.
118
+ */
119
+ export declare function liveCallRoute(options: LiveCallTurnOptions, host: LiveCallRouteHost): (req: IncomingMessage, res: ServerResponse) => void;
120
+ export {};
121
+ //# sourceMappingURL=handler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../../src/live-call/handler.ts"],"names":[],"mappings":"AAwBA,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AACjE,OAAO,EAIL,KAAK,oBAAoB,EAE1B,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAkB,KAAK,eAAe,EAAE,KAAK,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACnG,OAAO,EAAmB,KAAK,SAAS,EAAE,MAAM,0BAA0B,CAAC;AAI3E,OAAO,EAAgG,KAAK,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAEvJ,yGAAyG;AACzG,MAAM,WAAW,kBAAkB;IACjC,wEAAwE;IACxE,cAAc,EAAE,MAAM,CAAC;IACvB,+DAA+D;IAC/D,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,kHAAkH;IAClH,UAAU,EAAE,MAAM,CAAC;IACnB,+DAA+D;IAC/D,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB;;;;OAIG;IACH,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IACzC;;;;;;OAMG;IACH,QAAQ,CAAC,EAAE,oBAAoB,CAAC;CACjC;AAED,6DAA6D;AAC7D,MAAM,WAAW,uBAAuB;IACtC,kFAAkF;IAClF,MAAM,EAAE,WAAW,CAAC;CACrB;AAED,kEAAkE;AAClE,MAAM,WAAW,mBAAmB;IAClC;;;;OAIG;IACH,UAAU,EAAE,MAAM,GAAG,SAAS,MAAM,EAAE,CAAC;IACvC;;;;;;;;;;;OAWG;I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AmB,CAehG;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,mBAAmB,EAAE,IAAI,EAAE,iBAAiB,GAAG,CAAC,GAAG,EAAE,eAAe,EAAE,GAAG,EAAE,cAAc,KAAK,IAAI,CA4IxI"}
@@ -0,0 +1,338 @@
1
+ /**
2
+ * The live-call turn handler: one route a product mounts so that the
3
+ * service running a live call reaches the product's own agent.
4
+ *
5
+ * Each request is one turn (protocol.ts). The handler checks the bearer
6
+ * credential, asks the host which conversation, user and realtime room the
7
+ * call's `clientRef` is, and runs the turn on the same runtime as every other
8
+ * turn (runtime/turn-runner.ts). So the turn still streams to the
9
+ * conversation's room, and every page joined to it receives the reply and
10
+ * every UI action, as for a typed message. The handler sees the turn's events
11
+ * as the room does (emit/tee.ts) and writes the reply's text, an approval's
12
+ * readback and the turn's end to the response as server-sent events: one
13
+ * stream of events, two destinations, no second model call.
14
+ *
15
+ * A closed connection is the call service's barge-in: the person spoke over
16
+ * the reply. The turn is stopped as a superseding message stops it, and the
17
+ * next request names it in `supersedes`.
18
+ *
19
+ * POST <path> 200 text/event-stream the turn
20
+ * 400 not a turn · 401 wrong credential · 404 unknown clientRef
21
+ * 405 not POST · 409 turn already running · 413 too large
22
+ * 415 not JSON · 500 the host's resolver failed · 503 at capacity or closing
23
+ */
24
+ import crypto from 'node:crypto';
25
+ import { AGENT_SOCKET_EVENTS, MESSAGE_INPUT_CONTEXT_KEY, REPLY_OUTPUT_CONTEXT_KEY, } from '@ouispec/agent-core';
26
+ import { payloadRefusal } from '../runtime/turn-runner.js';
27
+ import { createTurnSlots } from '../runtime/turn-slots.js';
28
+ import { DEFAULT_KEEP_ALIVE_MS, openLiveCallEventStream } from './event-stream.js';
29
+ import { LIVE_CALL_OPENING_MESSAGE, liveCallError, readLiveCallTurnRequest } from './protocol.js';
30
+ const DEFAULT_MAX_BODY_BYTES = 64 * 1024;
31
+ /**
32
+ * Creates the live-call turn handler.
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * const runner = createAgentTurnRunner(runtimeConfig);
37
+ * const liveCall = createLiveCallTurnHandler({
38
+ * runner,
39
+ * credential: env.LIVE_CALL_BRAIN_CREDENTIAL,
40
+ * resolveTurn: async (request) => {
41
+ * const conversation = await db.conversation.findUnique({ where: { callRef: request.clientRef } });
42
+ * if (!conversation) return null;
43
+ * await db.message.create({ data: { conversationId: conversation.id, role: 'user', content: request.text, input: request.input } });
44
+ * return { conversationId: conversation.id, userId: conversation.userId, accountId: conversation.accountId, socketRoom: `conversation:${conversation.id}` };
45
+ * },
46
+ * });
47
+ * app.post('/agent/live-call/turns', liveCall);
48
+ * process.on('SIGTERM', () => liveCall.close());
49
+ * ```
50
+ */
51
+ export function createLiveCallTurnHandler(config) {
52
+ if (!config?.runner || typeof config.runner.run !== 'function' || typeof config.runner.reply !== 'function') {
53
+ throw new Error('[agent-sdk] Missing required configuration: runner (createAgentTurnRunner(config))');
54
+ }
55
+ const slots = createTurnSlots(config.maxConcurrentTurns ?? 8);
56
+ const handle = liveCallRoute(config, {
57
+ runner: config.runner,
58
+ slots,
59
+ maxBodyBytes: config.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES,
60
+ onTurnEnd: config.onTurnEnd,
61
+ });
62
+ return Object.assign((req, res) => handle(req, res), {
63
+ running: () => slots.running(),
64
+ close: () => slots.drain(),
65
+ });
66
+ }
67
+ /**
68
+ * The route, for a host that already runs turns (the container adapter): it
69
+ * shares that host's runtime and slots.
70
+ */
71
+ export function liveCallRoute(options, host) {
72
+ const credentials = (typeof options?.credential === 'string' ? [options.credential] : [...(options?.credential ?? [])]).filter((c) => typeof c === 'string' && c.length > 0);
73
+ const missing = [
74
+ credentials.length === 0 && 'credential (the bearer credential the call service sends)',
75
+ typeof options?.resolveTurn !== 'function' && 'resolveTurn (the call’s clientRef → its conversation, user and room)',
76
+ ].filter(Boolean);
77
+ if (missing.length > 0)
78
+ throw new Error(`[agent-sdk] Missing required configuration for the live-call route: ${missing.join('; ')}`);
79
+ const keepAliveMs = options.keepAliveMs ?? DEFAULT_KEEP_ALIVE_MS;
80
+ if (!(Number.isFinite(keepAliveMs) && keepAliveMs > 0))
81
+ throw new Error(`[agent-sdk] keepAliveMs must be a positive number of ms, not ${keepAliveMs}`);
82
+ const { runner, slots, maxBodyBytes } = host;
83
+ const logger = runner.logger;
84
+ // Compared as digests: equal length whatever was presented, so the comparison takes the same time.
85
+ const expected = credentials.map(digest);
86
+ const isCredential = (header) => {
87
+ const presented = /^Bearer[ ]+(\S+)\s*$/i.exec(header ?? '')?.[1];
88
+ if (!presented)
89
+ return false;
90
+ const given = digest(presented);
91
+ // Every credential is compared, matched or not.
92
+ return expected.map((e) => crypto.timingSafeEqual(given, e)).includes(true);
93
+ };
94
+ /** The hang-up of each running live-call turn, by turn id: a newer turn that supersedes one stops it here at once. */
95
+ const hangUps = new Map();
96
+ return (req, res) => {
97
+ if (req.method !== 'POST') {
98
+ res.setHeader('allow', 'POST');
99
+ refuse(res, 405, 'METHOD_NOT_ALLOWED', 'Use POST');
100
+ return;
101
+ }
102
+ if (!isCredential(req.headers.authorization)) {
103
+ res.setHeader('www-authenticate', 'Bearer');
104
+ refuse(res, 401, 'UNAUTHORIZED', 'Invalid or missing credential');
105
+ return;
106
+ }
107
+ const type = req.headers['content-type'];
108
+ if (type && !/^application\/json\s*(;|$)/i.test(type)) {
109
+ refuse(res, 415, 'UNSUPPORTED_MEDIA_TYPE', 'The body must be application/json');
110
+ return;
111
+ }
112
+ void readJsonBody(req, maxBodyBytes).then((body) => {
113
+ if (res.writableEnded)
114
+ return;
115
+ if (body.status !== 'ok') {
116
+ if (body.status === 'too_large')
117
+ refuse(res, 413, 'BODY_TOO_LARGE', `The body is larger than ${maxBodyBytes} bytes`);
118
+ else
119
+ refuse(res, 400, 'INVALID_REQUEST', 'The body is not JSON');
120
+ return;
121
+ }
122
+ const reading = readLiveCallTurnRequest(body.value);
123
+ if (!reading.ok) {
124
+ refuse(res, 400, 'INVALID_REQUEST', reading.error);
125
+ return;
126
+ }
127
+ const request = reading.request;
128
+ // The turns this one replaces stop now, if they still run here: their connections closed, or are closing.
129
+ for (const id of request.supersedes)
130
+ hangUps.get(id)?.abort('superseded');
131
+ const refusal = slots.take(request.turnId, () => serve(request, res));
132
+ if (refusal)
133
+ refuse(res, refusal.status, refusal.status === 409 ? 'TURN_RUNNING' : 'UNAVAILABLE', refusal.error);
134
+ });
135
+ };
136
+ async function serve(request, res) {
137
+ const { turnId } = request;
138
+ const hangUp = new AbortController();
139
+ // The caller closed the connection before the turn's answer ended: it stops the turn.
140
+ const onClose = () => {
141
+ if (!res.writableEnded)
142
+ hangUp.abort('superseded');
143
+ };
144
+ res.once('close', onClose);
145
+ hangUps.set(turnId, hangUp);
146
+ const call = { signal: hangUp.signal };
147
+ try {
148
+ let target;
149
+ try {
150
+ target = await options.resolveTurn(request, call);
151
+ }
152
+ catch (error) {
153
+ logger.error('[agent-sdk] The live-call turn could not be resolved; nothing was run', {
154
+ turnId,
155
+ sessionId: request.sessionId,
156
+ error: messageOf(error),
157
+ });
158
+ refuse(res, 500, 'RESOLVE_FAILED', 'The turn could not be resolved');
159
+ return;
160
+ }
161
+ if (!target) {
162
+ refuse(res, 404, 'UNKNOWN_CLIENT_REF', 'No conversation for this clientRef');
163
+ return;
164
+ }
165
+ const payload = turnPayload(request, target);
166
+ const invalid = payloadRefusal(payload);
167
+ if (invalid) {
168
+ logger.error('[agent-sdk] resolveTurn answered a turn that cannot run; nothing was run', { turnId, error: invalid });
169
+ refuse(res, 500, 'RESOLVE_FAILED', 'The turn could not be resolved');
170
+ return;
171
+ }
172
+ const stream = openLiveCallEventStream(res, keepAliveMs);
173
+ const relay = relayTurn(turnId, stream);
174
+ logger.info('[agent-sdk] Live-call turn', {
175
+ turnId,
176
+ sessionId: request.sessionId,
177
+ kind: request.kind,
178
+ conversationId: target.conversationId,
179
+ ...(request.supersedes.length ? { supersedes: request.supersedes } : {}),
180
+ });
181
+ let outcome;
182
+ try {
183
+ const greeting = request.kind === 'opening' && options.opening ? (await options.opening(request, target, call))?.trim() : null;
184
+ // A caller already gone gets no greeting: the turn stops before it starts, and stores only that.
185
+ outcome = greeting && !hangUp.signal.aborted
186
+ ? await runner.reply(payload, greeting, { observe: relay.observe })
187
+ : await runner.run(payload, { observe: relay.observe, stopSignal: hangUp.signal });
188
+ }
189
+ catch (error) {
190
+ // A turn's own failure is an outcome; this is the host's opening template, or the runtime around the turn.
191
+ logger.error('[agent-sdk] The live-call turn could not run', { turnId, error: messageOf(error) });
192
+ outcome = { status: 'failed', turnId, error: { code: 'WORKER_ERROR', message: messageOf(error), recoverable: false }, cause: error };
193
+ }
194
+ try {
195
+ host.onTurnEnd?.(outcome);
196
+ }
197
+ catch (error) {
198
+ logger.warn('[agent-sdk] onTurnEnd threw', { turnId, error: messageOf(error) });
199
+ }
200
+ if (outcome.status === 'failed')
201
+ stream.send('error', liveCallError(outcome.error.code));
202
+ else if (outcome.status === 'refused')
203
+ stream.send('error', liveCallError('TURN_REFUSED'));
204
+ else if (outcome.status === 'stopped' && outcome.stored === false)
205
+ stream.send('error', liveCallError('TURN_DEADLINE_EXCEEDED'));
206
+ else
207
+ stream.send('done', relay.ended() ?? (outcome.status === 'stopped' ? { stopReason: outcome.stopReason } : {}));
208
+ stream.end();
209
+ }
210
+ finally {
211
+ res.off('close', onClose);
212
+ if (hangUps.get(turnId) === hangUp)
213
+ hangUps.delete(turnId);
214
+ }
215
+ }
216
+ }
217
+ /** The turn as the runtime takes it: the host's target, and what the request says. */
218
+ function turnPayload(request, target) {
219
+ const context = { ...(target.context ?? {}) };
220
+ // How the message was entered and how the reply reaches the person are the request's to say.
221
+ delete context[MESSAGE_INPUT_CONTEXT_KEY];
222
+ delete context[REPLY_OUTPUT_CONTEXT_KEY];
223
+ if (request.input)
224
+ context[MESSAGE_INPUT_CONTEXT_KEY] = request.input;
225
+ if (request.output)
226
+ context[REPLY_OUTPUT_CONTEXT_KEY] = request.output;
227
+ return {
228
+ turnId: request.turnId,
229
+ conversationId: target.conversationId,
230
+ userId: target.userId,
231
+ accountId: target.accountId,
232
+ socketRoom: target.socketRoom,
233
+ content: request.kind === 'opening' ? LIVE_CALL_OPENING_MESSAGE : request.text,
234
+ context,
235
+ ...(target.userToken ? { userToken: target.userToken } : {}),
236
+ ...(target.approval ? { approval: target.approval } : {}),
237
+ ...(request.supersedes.length > 0 ? { supersedes: request.supersedes } : {}),
238
+ };
239
+ }
240
+ /**
241
+ * The turn's events, as the response carries them: its text as `text`, an
242
+ * approval's readback as `readback`, and how it ended, for `done`.
243
+ *
244
+ * The readback is sent when the turn has ended, after every piece of its
245
+ * text: it is spoken after what the model said before the call. A turn that
246
+ * was stopped instead withdrew its approval, so its readback is never sent.
247
+ */
248
+ function relayTurn(turnId, stream) {
249
+ let ended = null;
250
+ let readback = null;
251
+ const ofTurn = (data) => !!data && typeof data === 'object' && data.turnId === turnId;
252
+ return {
253
+ observe(event, data) {
254
+ if (!ofTurn(data))
255
+ return;
256
+ switch (event) {
257
+ case AGENT_SOCKET_EVENTS.TOKEN: {
258
+ const text = data.text;
259
+ if (typeof text === 'string' && text)
260
+ stream.send('text', { text });
261
+ return;
262
+ }
263
+ case AGENT_SOCKET_EVENTS.APPROVAL_REQUIRED: {
264
+ const approval = data;
265
+ readback = { approvalId: approval.approvalId, text: approval.preview.readback, expiresAt: new Date(approval.expiresAt).toISOString() };
266
+ return;
267
+ }
268
+ case AGENT_SOCKET_EVENTS.TURN_COMPLETE: {
269
+ if (readback && data.stopReason === undefined)
270
+ stream.send('readback', readback);
271
+ const reason = data.stopReason ?? data.endReason;
272
+ ended = typeof reason === 'string' ? { stopReason: reason } : {};
273
+ return;
274
+ }
275
+ }
276
+ },
277
+ ended: () => ended,
278
+ };
279
+ }
280
+ /**
281
+ * The request's JSON body. A body a framework has already parsed (Express's
282
+ * `json()`) is taken as it is.
283
+ */
284
+ function readJsonBody(req, maxBytes) {
285
+ const parsed = req.body;
286
+ if (req.readableEnded && parsed !== undefined) {
287
+ if (typeof parsed === 'string' || Buffer.isBuffer(parsed))
288
+ return Promise.resolve(parseJson(String(parsed), maxBytes));
289
+ return Promise.resolve({ status: 'ok', value: parsed });
290
+ }
291
+ return new Promise((resolve) => {
292
+ let size = 0;
293
+ const chunks = [];
294
+ let done = false;
295
+ const finish = (reading) => {
296
+ if (done)
297
+ return;
298
+ done = true;
299
+ resolve(reading);
300
+ };
301
+ req.on('data', (chunk) => {
302
+ size += chunk.length;
303
+ // Past the limit, the rest is read and dropped, so the refusal can still be answered.
304
+ if (size > maxBytes) {
305
+ finish({ status: 'too_large' });
306
+ return;
307
+ }
308
+ if (!done)
309
+ chunks.push(chunk);
310
+ });
311
+ req.on('end', () => finish(parseJson(Buffer.concat(chunks).toString('utf8'), maxBytes)));
312
+ req.on('error', () => finish({ status: 'not_json' }));
313
+ });
314
+ }
315
+ function parseJson(text, maxBytes) {
316
+ if (Buffer.byteLength(text) > maxBytes)
317
+ return { status: 'too_large' };
318
+ try {
319
+ return { status: 'ok', value: JSON.parse(text) };
320
+ }
321
+ catch {
322
+ return { status: 'not_json' };
323
+ }
324
+ }
325
+ /** A refusal before the stream opens: a status and `{ error: { code, message } }`. Nothing once the caller has gone. */
326
+ function refuse(res, status, code, message) {
327
+ if (res.headersSent || res.writableEnded || res.destroyed)
328
+ return;
329
+ res.writeHead(status, { 'content-type': 'application/json' });
330
+ res.end(JSON.stringify({ error: { code, message } }));
331
+ }
332
+ function digest(value) {
333
+ return crypto.createHash('sha256').update(value).digest();
334
+ }
335
+ function messageOf(err) {
336
+ return err instanceof Error ? err.message : String(err);
337
+ }
338
+ //# sourceMappingURL=handler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"handler.js","sourceRoot":"","sources":["../../src/live-call/handler.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,OAAO,MAAM,MAAM,aAAa,CAAC;AAEjC,OAAO,EACL,mBAAmB,EACnB,yBAAyB,EACzB,wBAAwB,GAGz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