@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,131 @@
1
+ /**
2
+ * The live-call turn: what the service running a call sends for each turn,
3
+ * and the event stream the agent answers with.
4
+ *
5
+ * The call service hears the person, transcribes them, and speaks the reply in
6
+ * the character's voice. The agent is the product's: it holds the
7
+ * conversation, its tools, its UI actions and its approvals. Each turn is one
8
+ * request:
9
+ *
10
+ * POST <the product's route>
11
+ * Authorization: Bearer <credential>
12
+ * Content-Type: application/json
13
+ * Accept: text/event-stream
14
+ *
15
+ * { sessionId, clientRef, turnId, kind, text, input?, output?, supersedes? }
16
+ *
17
+ * `input` is `{ mode: 'voice', language? }` for what the person said and
18
+ * `{ mode: 'text' }` for what they typed during the call.
19
+ *
20
+ * and the answer is `200 text/event-stream`:
21
+ *
22
+ * event: text data: { "text": "…" } the reply, piece by piece
23
+ * event: readback data: { "approvalId", "text", "expiresAt" } an approval's readback, verbatim
24
+ * event: done data: { "stopReason"?: "…" } the turn is over
25
+ * event: error data: { "code": "…", "message": "…" } the turn failed
26
+ *
27
+ * with `: keep-alive` comments while nothing else is sent.
28
+ */
29
+ import { type MessageInput, type ReplyOutput } from '@ouispec/agent-core';
30
+ /** `message`: the person said `text`. `opening`: the call has just connected; nothing has been said, and the agent greets. */
31
+ export declare const LIVE_CALL_TURN_KINDS: readonly ["message", "opening"];
32
+ export type LiveCallTurnKind = (typeof LIVE_CALL_TURN_KINDS)[number];
33
+ /** A live-call turn request, as read: every field checked, `input` and `output` kept only as far as they are known. */
34
+ export interface LiveCallTurnRequest {
35
+ /** The call service's session. */
36
+ sessionId: string;
37
+ /** The product's own conversation reference, set when the call was created: the host resolves its conversation, user and room from it. */
38
+ clientRef: string;
39
+ /** Unique per turn; the turn runs under this id. */
40
+ turnId: string;
41
+ kind: LiveCallTurnKind;
42
+ /** What the person said, as transcribed. Empty for `opening`. */
43
+ text: string;
44
+ /**
45
+ * How `text` was entered: `{ mode: 'voice', language? }` for what the person
46
+ * said. Null for a message they typed during the call (`{ mode: 'text' }` on
47
+ * the wire), for `opening`, and when not said: a typed message is read as
48
+ * typed, with no spoken-input line.
49
+ */
50
+ input: MessageInput | null;
51
+ /** How the reply reaches the person: `{ mode: 'voice' }` when a voice reads it out. */
52
+ output: ReplyOutput | null;
53
+ /** Turns this one replaces: the call service closed their streams because the person spoke again. */
54
+ supersedes: string[];
55
+ }
56
+ /** The events of a live-call turn's response stream. */
57
+ export interface LiveCallStreamEvents {
58
+ /** A piece of the reply's text. Pieces are concatenated in order. */
59
+ text: {
60
+ text: string;
61
+ };
62
+ /**
63
+ * The turn stopped at a call that needs the person's approval: `text` is its
64
+ * readback, built from the action's declaration, to be spoken verbatim after
65
+ * any text already sent. The person's next utterance comes as an ordinary
66
+ * `message`; the host decides whether it approves.
67
+ */
68
+ readback: {
69
+ approvalId: string;
70
+ text: string;
71
+ expiresAt: string;
72
+ };
73
+ /**
74
+ * The turn is over. `stopReason` is how it ended: `complete`,
75
+ * `awaiting_approval`, `present_options`, `time_limit`, `output_limit` or
76
+ * `step_count` for a turn that ended by itself; `user_stop`, `superseded`
77
+ * or `deadline` (and any later stop reason) for one that was stopped.
78
+ */
79
+ done: {
80
+ stopReason?: string;
81
+ };
82
+ /** The turn failed. `message` is a fixed line for the code; the cause is in the host's logs, never on the wire. */
83
+ error: {
84
+ code: string;
85
+ message: string;
86
+ };
87
+ }
88
+ export type LiveCallStreamEventName = keyof LiveCallStreamEvents;
89
+ /**
90
+ * The person's message for an `opening` turn: an instruction to greet, which
91
+ * the model reads where the person's words would be. A host that stores the
92
+ * person's messages stores this one for the opening turn, so the conversation
93
+ * keeps the turn the greeting answers.
94
+ */
95
+ export declare const LIVE_CALL_OPENING_MESSAGE: string;
96
+ /**
97
+ * The `input` mode of a message the person typed during the call. It is read
98
+ * as typed: the turn's context carries no `input`, as for a message typed in
99
+ * the product's own chat.
100
+ */
101
+ export declare const LIVE_CALL_TYPED_INPUT_MODE = "text";
102
+ /** Limits on a request. */
103
+ export declare const LIVE_CALL_LIMITS: {
104
+ /** The longest `sessionId`, `turnId`, or turn id in `supersedes`. */
105
+ readonly idChars: 128;
106
+ /** The longest `clientRef`. */
107
+ readonly clientRefChars: 512;
108
+ /** The longest `text`. */
109
+ readonly textChars: 8000;
110
+ /** The most turn ids in `supersedes`. */
111
+ readonly supersedes: 32;
112
+ };
113
+ /** A request read, or why it is not one. */
114
+ export type LiveCallRequestReading = {
115
+ ok: true;
116
+ request: LiveCallTurnRequest;
117
+ } | {
118
+ ok: false;
119
+ error: string;
120
+ };
121
+ /** Reads a live-call turn request's body. Every refusal names the field. */
122
+ export declare function readLiveCallTurnRequest(body: unknown): LiveCallRequestReading;
123
+ /**
124
+ * What a failed turn's `error` event says, by code. Fixed lines: the call
125
+ * service records the code and speaks its own apology, and the cause (a
126
+ * provider's error text, a stack) stays in the host's logs.
127
+ */
128
+ export declare const LIVE_CALL_ERROR_MESSAGES: Readonly<Record<string, string>>;
129
+ /** The `error` event for a failure code. */
130
+ export declare function liveCallError(code: string): LiveCallStreamEvents['error'];
131
+ //# sourceMappingURL=protocol.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.d.ts","sourceRoot":"","sources":["../../src/live-call/protocol.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,OAAO,EAAqC,KAAK,YAAY,EAAE,KAAK,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAE7G,8HAA8H;AAC9H,eAAO,MAAM,oBAAoB,iCAAkC,CAAC;AAEpE,MAAM,MAAM,gBAAgB,GAAG,CAAC,OAAO,oBAAoB,CAAC,CAAC,MAAM,CAAC,CAAC;AAErE,uHAAuH;AACvH,MAAM,WAAW,mBAAmB;IAClC,kCAAkC;IAClC,SAAS,EAAE,MAAM,CAAC;IAClB,0IAA0I;IAC1I,SAAS,EAAE,MAAM,CAAC;IAClB,oDAAoD;IACpD,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,gBAAgB,CAAC;IACvB,iEAAiE;IACjE,IAAI,EAAE,MAAM,CAAC;IACb;;;;;OAKG;IACH,KAAK,EAAE,YAAY,GAAG,IAAI,CAAC;IAC3B,uFAAuF;IACvF,MAAM,EAAE,WAAW,GAAG,IAAI,CAAC;IAC3B,qGAAqG;IACrG,UAAU,EAAE,MAAM,EAAE,CAAC;CACtB;AAED,wDAAwD;AACxD,MAAM,WAAW,oBAAoB;IACnC,qEAAqE;IACrE,IAAI,EAAE;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;IACvB;;;;;OAKG;IACH,QAAQ,EAAE;QAAE,UAAU,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE,CAAC;IAClE;;;;;OAKG;IACH,IAAI,EAAE;QAAE,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IAC9B,mHAAmH;IACnH,KAAK,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC;CAC1C;AAED,MAAM,MAAM,uBAAuB,GAAG,MAAM,oBAAoB,CAAC;AAEjE;;;;;GAKG;AACH,eAAO,MAAM,yBAAyB,QAE0F,CAAC;AAEjI;;;;GAIG;AACH,eAAO,MAAM,0BAA0B,SAAS,CAAC;AAEjD,2BAA2B;AAC3B,eAAO,MAAM,gBAAgB;IAC3B,qEAAqE;;IAErE,+BAA+B;;IAE/B,0BAA0B;;IAE1B,yCAAyC;;CAEjC,CAAC;AAQX,4CAA4C;AAC5C,MAAM,MAAM,sBAAsB,GAAG;IAAE,EAAE,EAAE,IAAI,CAAC;IAAC,OAAO,EAAE,mBAAmB,CAAA;CAAE,GAAG;IAAE,EAAE,EAAE,KAAK,CAAC;IAAC,KAAK,EAAE,MAAM,CAAA;CAAE,CAAC;AAE/G,4EAA4E;AAC5E,wBAAgB,uBAAuB,CAAC,IAAI,EAAE,OAAO,GAAG,sBAAsB,CAiD7E;AAOD;;;;GAIG;AACH,eAAO,MAAM,wBAAwB,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAQrE,CAAC;AAEF,4CAA4C;AAC5C,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,oBAAoB,CAAC,OAAO,CAAC,CAEzE"}
@@ -0,0 +1,138 @@
1
+ /**
2
+ * The live-call turn: what the service running a call sends for each turn,
3
+ * and the event stream the agent answers with.
4
+ *
5
+ * The call service hears the person, transcribes them, and speaks the reply in
6
+ * the character's voice. The agent is the product's: it holds the
7
+ * conversation, its tools, its UI actions and its approvals. Each turn is one
8
+ * request:
9
+ *
10
+ * POST <the product's route>
11
+ * Authorization: Bearer <credential>
12
+ * Content-Type: application/json
13
+ * Accept: text/event-stream
14
+ *
15
+ * { sessionId, clientRef, turnId, kind, text, input?, output?, supersedes? }
16
+ *
17
+ * `input` is `{ mode: 'voice', language? }` for what the person said and
18
+ * `{ mode: 'text' }` for what they typed during the call.
19
+ *
20
+ * and the answer is `200 text/event-stream`:
21
+ *
22
+ * event: text data: { "text": "…" } the reply, piece by piece
23
+ * event: readback data: { "approvalId", "text", "expiresAt" } an approval's readback, verbatim
24
+ * event: done data: { "stopReason"?: "…" } the turn is over
25
+ * event: error data: { "code": "…", "message": "…" } the turn failed
26
+ *
27
+ * with `: keep-alive` comments while nothing else is sent.
28
+ */
29
+ import { readMessageInput, readReplyOutput } from '@ouispec/agent-core';
30
+ /** `message`: the person said `text`. `opening`: the call has just connected; nothing has been said, and the agent greets. */
31
+ export const LIVE_CALL_TURN_KINDS = ['message', 'opening'];
32
+ /**
33
+ * The person's message for an `opening` turn: an instruction to greet, which
34
+ * the model reads where the person's words would be. A host that stores the
35
+ * person's messages stores this one for the opening turn, so the conversation
36
+ * keeps the turn the greeting answers.
37
+ */
38
+ export const LIVE_CALL_OPENING_MESSAGE = '<call_opening>A live call with the user has just connected, and they have not said anything yet. ' +
39
+ 'Greet them in a sentence or two, and ask what they would like help with. This is not a message from the user.</call_opening>';
40
+ /**
41
+ * The `input` mode of a message the person typed during the call. It is read
42
+ * as typed: the turn's context carries no `input`, as for a message typed in
43
+ * the product's own chat.
44
+ */
45
+ export const LIVE_CALL_TYPED_INPUT_MODE = 'text';
46
+ /** Limits on a request. */
47
+ export const LIVE_CALL_LIMITS = {
48
+ /** The longest `sessionId`, `turnId`, or turn id in `supersedes`. */
49
+ idChars: 128,
50
+ /** The longest `clientRef`. */
51
+ clientRefChars: 512,
52
+ /** The longest `text`. */
53
+ textChars: 8_000,
54
+ /** The most turn ids in `supersedes`. */
55
+ supersedes: 32,
56
+ };
57
+ /** An id: letters, digits and `.` `_` `:` `-`, starting with a letter or digit. */
58
+ const ID = new RegExp(`^[A-Za-z0-9][A-Za-z0-9._:-]{0,${LIVE_CALL_LIMITS.idChars - 1}}$`);
59
+ /** Any control character. */
60
+ // eslint-disable-next-line no-control-regex
61
+ const CONTROL = /[\u0000-\u001f\u007f]/;
62
+ /** Reads a live-call turn request's body. Every refusal names the field. */
63
+ export function readLiveCallTurnRequest(body) {
64
+ const refuse = (error) => ({ ok: false, error });
65
+ if (!body || typeof body !== 'object' || Array.isArray(body))
66
+ return refuse('the body must be a JSON object');
67
+ const b = body;
68
+ for (const field of ['sessionId', 'turnId']) {
69
+ if (typeof b[field] !== 'string' || !ID.test(b[field])) {
70
+ return refuse(`${field} must be an id of 1–${LIVE_CALL_LIMITS.idChars} letters, digits, '.', '_', ':' or '-'`);
71
+ }
72
+ }
73
+ const clientRef = b.clientRef;
74
+ if (typeof clientRef !== 'string' || !clientRef.trim() || clientRef.length > LIVE_CALL_LIMITS.clientRefChars || CONTROL.test(clientRef)) {
75
+ return refuse(`clientRef must be a string of 1–${LIVE_CALL_LIMITS.clientRefChars} characters with no control characters`);
76
+ }
77
+ if (typeof b.kind !== 'string' || !LIVE_CALL_TURN_KINDS.includes(b.kind)) {
78
+ return refuse(`kind must be one of ${LIVE_CALL_TURN_KINDS.join(', ')}`);
79
+ }
80
+ const kind = b.kind;
81
+ const text = b.text === undefined && kind === 'opening' ? '' : b.text;
82
+ if (typeof text !== 'string')
83
+ return refuse('text must be a string');
84
+ if (text.length > LIVE_CALL_LIMITS.textChars)
85
+ return refuse(`text is longer than ${LIVE_CALL_LIMITS.textChars} characters`);
86
+ if (kind === 'message' && !text.trim())
87
+ return refuse('a message turn needs the text the person said');
88
+ if (kind === 'opening' && text.trim())
89
+ return refuse('an opening turn carries no text');
90
+ for (const field of ['input', 'output']) {
91
+ const value = b[field];
92
+ if (value !== undefined && value !== null && (typeof value !== 'object' || Array.isArray(value)))
93
+ return refuse(`${field} must be an object`);
94
+ }
95
+ const supersedes = b.supersedes ?? [];
96
+ if (!Array.isArray(supersedes) || !supersedes.every((id) => typeof id === 'string' && ID.test(id))) {
97
+ return refuse('supersedes must be a list of turn ids');
98
+ }
99
+ if (supersedes.length > LIVE_CALL_LIMITS.supersedes)
100
+ return refuse(`supersedes names more than ${LIVE_CALL_LIMITS.supersedes} turns`);
101
+ return {
102
+ ok: true,
103
+ request: {
104
+ sessionId: b.sessionId,
105
+ clientRef,
106
+ turnId: b.turnId,
107
+ kind,
108
+ text: kind === 'opening' ? '' : text,
109
+ // Nothing was said on an opening turn, so nothing was entered; a typed message is read as typed.
110
+ input: kind === 'opening' || isTyped(b.input) ? null : readMessageInput(b.input),
111
+ output: readReplyOutput(b.output),
112
+ supersedes: [...new Set(supersedes)].filter((id) => id !== b.turnId),
113
+ },
114
+ };
115
+ }
116
+ /** Whether `input` says the message was typed during the call. */
117
+ function isTyped(input) {
118
+ return !!input && typeof input === 'object' && input.mode === LIVE_CALL_TYPED_INPUT_MODE;
119
+ }
120
+ /**
121
+ * What a failed turn's `error` event says, by code. Fixed lines: the call
122
+ * service records the code and speaks its own apology, and the cause (a
123
+ * provider's error text, a stack) stays in the host's logs.
124
+ */
125
+ export const LIVE_CALL_ERROR_MESSAGES = {
126
+ RATE_LIMIT: 'The model provider is rate-limiting requests.',
127
+ SERVICE_UNAVAILABLE: 'The model provider is unavailable.',
128
+ MODEL_TIMEOUT: 'The model timed out.',
129
+ TURN_TIMEOUT: 'The turn timed out.',
130
+ TURN_DEADLINE_EXCEEDED: 'The turn ran out of time.',
131
+ TURN_REFUSED: 'The turn was refused by its record: it already ended or was given up on.',
132
+ WORKER_ERROR: 'The turn failed.',
133
+ };
134
+ /** The `error` event for a failure code. */
135
+ export function liveCallError(code) {
136
+ return { code, message: LIVE_CALL_ERROR_MESSAGES[code] ?? LIVE_CALL_ERROR_MESSAGES.WORKER_ERROR };
137
+ }
138
+ //# sourceMappingURL=protocol.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.js","sourceRoot":"","sources":["../../src/live-call/protocol.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAuC,MAAM,qBAAqB,CAAC;AAE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,CAAC,CAAC,MAAM,CAAC;YACjC,UAAU,EAAE,CAAC,GAAG,IAAI,GAAG,CAAC,UAAsB,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,KAAK,CAAC,CAAC,MAAM,CAAC;SACjF;KACF,CAAC;AACJ,CAAC;AAED,kEAAkE;AAClE,SAAS,OAAO,CAAC,KAAc;IAC7B,OAAO,CAAC,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAK,KAA4B,CAAC,IAAI,KAAK,0BAA0B,CAAC;AACnH,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,wBAAwB,GAAqC;IACxE,UAAU,EAAE,+CAA+C;IAC3D,mBAAmB,EAAE,oCAAoC;IACzD,aAAa,EAAE,sBAAsB;IACrC,YAAY,EAAE,qBAAqB;IACnC,sBAAsB,EAAE,2BAA2B;IACnD,YAAY,EAAE,0EAA0E;IACxF,YAAY,EAAE,kBAAkB;CACjC,CAAC;AAEF,4CAA4C;AAC5C,MAAM,UAAU,aAAa,CAAC,IAAY;IACxC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,wBAAwB,CAAC,IAAI,CAAC,IAAI,wBAAwB,CAAC,YAAY,EAAE,CAAC;AACpG,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"orchestrator.d.ts","sourceRoot":"","sources":["../src/orchestrator.ts"],"names":[],"mappings":"AAkCA,OAAO,KAAK,EAAE,iBAAiB,EAAE,cAAc,EAAE,eAAe,EAAmC,MAAM,YAAY,CAAC;AAyGtH;;;;;;;;GAQG;AACH,wBAAsB,YAAY,CAChC,MAAM,EAAE,iBAAiB,EACzB,KAAK,EAAE,cAAc,GACpB,OAAO,CAAC,eAAe,CAAC,CAu4D1B"}
1
+ {"version":3,"file":"orchestrator.d.ts","sourceRoot":"","sources":["../src/orchestrator.ts"],"names":[],"mappings":"AAmCA,OAAO,KAAK,EAAE,iBAAiB,EAAE,cAAc,EAAE,eAAe,EAAmC,MAAM,YAAY,CAAC;AA2GtH;;;;;;;;GAQG;AACH,wBAAsB,YAAY,CAChC,MAAM,EAAE,iBAAiB,EACzB,KAAK,EAAE,cAAc,GACpB,OAAO,CAAC,eAAe,CAAC,CAw6D1B"}
@@ -19,12 +19,13 @@
19
19
  * - Configurable TurnPolicy for product-specific step control
20
20
  */
21
21
  import { streamText, dynamicTool, jsonSchema, isStepCount, hasToolCall } from 'ai';
22
- import { AGENT_SOCKET_EVENTS, argsHash, canonicalJson, turnStoppedNote, } from '@ouispec/agent-core';
22
+ import { AGENT_SOCKET_EVENTS, argsHash, canonicalJson, isTurnEndReason, turnStoppedNote, } from '@ouispec/agent-core';
23
23
  import { DEFAULT_STOP_GRACE_MS, TurnStopped, stopOf, watchTurnStop } from './stop/turn-stop.js';
24
24
  import { stoppedTurnMessages } from './stop/partial.js';
25
25
  import { resultText, stoppedNotRun, stoppedWhileRunning } from './stop/results.js';
26
26
  import { defaultTurnPolicy } from './turn-policy.js';
27
27
  import { createStepClock, timeHandBackNote } from './time-hand-back.js';
28
+ import { createReasoningRelay } from './reasoning-relay.js';
28
29
  import { evaluateToolPolicySafe } from './authz/tool-policy.js';
29
30
  import { createToolInputValidator } from './tools/input-validation.js';
30
31
  import { readClientPage, withoutClientUI } from './ui/snapshot.js';
@@ -33,6 +34,7 @@ import { answerWithoutState, withStatesAtEnd } from './ui/page-state-at-end.js';
33
34
  import { stepMessages as forStep, STEP_NOTE_CLOSE, STEP_NOTE_OPEN } from './step-messages.js';
34
35
  import { clockText, readClientTimeZone } from './prompt/clock.js';
35
36
  import { readClientMessageInput, spokenInputText } from './prompt/spoken-input.js';
37
+ import { readClientReplyOutput, spokenReplyText } from './prompt/spoken-reply.js';
36
38
  import { AttachmentGuard } from './attachments/guard.js';
37
39
  import { ATTACHMENT_DATA_NOTE, turnAttachmentParts, withReferenceLines, withTurnAttachments, withoutLeftOut } from './attachments/content.js';
38
40
  import { attachmentTools } from './attachments/tools.js';
@@ -353,14 +355,14 @@ export async function runAgentTurn(config, input) {
353
355
  const refused = async (payload, given) => {
354
356
  ledger.record({ tool: t.name, ok: false, error: payload.error });
355
357
  const now = Date.now();
356
- await config.emit.emit(socketRoom, AGENT_SOCKET_EVENTS.TOOL_CALL_STARTED, {
358
+ await emitAfterText(AGENT_SOCKET_EVENTS.TOOL_CALL_STARTED, {
357
359
  turnId,
358
360
  toolUseId,
359
361
  name: t.name,
360
362
  input: given,
361
363
  timestamp: now,
362
364
  });
363
- await config.emit.emit(socketRoom, AGENT_SOCKET_EVENTS.TOOL_CALL_COMPLETE, {
365
+ await emitAfterText(AGENT_SOCKET_EVENTS.TOOL_CALL_COMPLETE, {
364
366
  turnId,
365
367
  toolUseId,
366
368
  name: t.name,
@@ -581,7 +583,7 @@ export async function runAgentTurn(config, input) {
581
583
  ...(approved ? { approvalId: approved.approvalId } : {}),
582
584
  });
583
585
  // Emit tool call started BEFORE execution
584
- await config.emit.emit(socketRoom, AGENT_SOCKET_EVENTS.TOOL_CALL_STARTED, {
586
+ await emitAfterText(AGENT_SOCKET_EVENTS.TOOL_CALL_STARTED, {
585
587
  turnId,
586
588
  toolUseId,
587
589
  name: t.name,
@@ -641,7 +643,7 @@ export async function runAgentTurn(config, input) {
641
643
  durationMs,
642
644
  ...(isUI && !resultSuccess ? { error: isWrapped ? result.error : undefined } : {}),
643
645
  });
644
- await config.emit.emit(socketRoom, AGENT_SOCKET_EVENTS.TOOL_CALL_COMPLETE, {
646
+ await emitAfterText(AGENT_SOCKET_EVENTS.TOOL_CALL_COMPLETE, {
645
647
  turnId,
646
648
  toolUseId,
647
649
  name: t.name,
@@ -737,7 +739,7 @@ export async function runAgentTurn(config, input) {
737
739
  catch (err) {
738
740
  return refuse(err instanceof Error ? err.message : String(err));
739
741
  }
740
- await config.emit.emit(socketRoom, AGENT_SOCKET_EVENTS.APPROVAL_REQUIRED, {
742
+ await emitAfterText(AGENT_SOCKET_EVENTS.APPROVAL_REQUIRED, {
741
743
  turnId,
742
744
  conversationId: input.conversationId,
743
745
  approvalId: toolUseId,
@@ -1084,6 +1086,24 @@ export async function runAgentTurn(config, input) {
1084
1086
  });
1085
1087
  }
1086
1088
  };
1089
+ /**
1090
+ * A turn event that comes after what the model has said so far: the text
1091
+ * still held for coalescing is sent first. A tool's call and an approval's
1092
+ * preview then reach the room, and a host observing the turn's events, after
1093
+ * the words the model said before them, as they were said.
1094
+ */
1095
+ const emitAfterText = async (event, data) => {
1096
+ await flushTokenBuffer();
1097
+ await config.emit.emit(socketRoom, event, data);
1098
+ };
1099
+ // The model's thinking, relayed to the room: its start and end, and its
1100
+ // summary when the host asked the model for one (reasoning-relay.ts).
1101
+ const reasoningRelay = createReasoningRelay({
1102
+ turnId,
1103
+ emit: (event, data) => config.emit.emit(socketRoom, event, data),
1104
+ coalesceMs: COALESCE_MS,
1105
+ coalesceChars: COALESCE_CHARS,
1106
+ });
1087
1107
  // Run the multi-round generation
1088
1108
  try {
1089
1109
  // ─── Prompt cache breakpoints ──────────────────────────────────────────────
@@ -1292,6 +1312,8 @@ export async function runAgentTurn(config, input) {
1292
1312
  const turnMessageAt = messages.map((m) => m.role).lastIndexOf('user');
1293
1313
  const turnClock = clockText(new Date(), readClientTimeZone(input.context ?? null));
1294
1314
  const turnSpoken = input.approval ? null : readClientMessageInput(input.context ?? null);
1315
+ // The reply is spoken on every turn of a call, the turn an approval continues included.
1316
+ const turnSpokenReply = readClientReplyOutput(input.context ?? null);
1295
1317
  const turnPageValues = client && client.page.length > 0
1296
1318
  ? [
1297
1319
  observationsText(client.observations, config.ui?.maxObservationChars ?? DEFAULT_PAGE_STATE_CHARS, {
@@ -1322,6 +1344,8 @@ export async function runAgentTurn(config, input) {
1322
1344
  // A message the person spoke may hold a mis-heard word (prompt/spoken-input.ts). A click on an
1323
1345
  // approval card is not a message, so it says nothing.
1324
1346
  ...(turnSpoken ? [spokenInputText(turnSpoken)] : []),
1347
+ // A reply a voice will read out is written for the ear (prompt/spoken-reply.ts).
1348
+ ...(turnSpokenReply ? [spokenReplyText(turnSpokenReply)] : []),
1325
1349
  ...(expired.outcomes.length > 0 ? [expiredNote(expired)] : []),
1326
1350
  ...(input.stepContext?.trim() ? [input.stepContext.trim()] : []),
1327
1351
  ...(notes.length > 0 ? [[STEP_NOTE_OPEN, ...notes, STEP_NOTE_CLOSE].join('\n')] : []),
@@ -1360,6 +1384,9 @@ export async function runAgentTurn(config, input) {
1360
1384
  maxOutputTokens: maxTokens,
1361
1385
  maxRetries: retries,
1362
1386
  abortSignal: abortController.signal,
1387
+ // The host's, the same for every call (a thinking setting that changes invalidates the cache).
1388
+ ...(config.modelProviderOptions ? { providerOptions: config.modelProviderOptions } : {}),
1389
+ onChunk: ({ chunk }) => reasoningRelay.onPart(chunk),
1363
1390
  stopWhen: [
1364
1391
  isStepCount(maxRounds - allSteps.length),
1365
1392
  ...USER_INPUT_TOOLS.map((name) => hasToolCall(name)),
@@ -1692,10 +1719,14 @@ export async function runAgentTurn(config, input) {
1692
1719
  });
1693
1720
  }
1694
1721
  }
1722
+ // Everything before the turn's end has been sent: its thinking too.
1723
+ await reasoningRelay.settle();
1695
1724
  await config.emit.emit(socketRoom, AGENT_SOCKET_EVENTS.TURN_COMPLETE, {
1696
1725
  turnId,
1697
1726
  rounds: steps.length,
1698
1727
  usage,
1728
+ // How it ended, so a view can tell an answer from a cut-off or a hand-back.
1729
+ ...(isTurnEndReason(stopReason) ? { endReason: stopReason } : {}),
1699
1730
  timestamp: Date.now(),
1700
1731
  });
1701
1732
  log('info', 'agent:turn', 'Turn completed', {
@@ -1850,6 +1881,8 @@ export async function runAgentTurn(config, input) {
1850
1881
  });
1851
1882
  }
1852
1883
  }
1884
+ // A block the stop cut off is ended; its emits are not waited for, as the announcement is time-boxed.
1885
+ void reasoningRelay.settle();
1853
1886
  try {
1854
1887
  await within('announcement', STOP_STEP_FLOOR_MS, () => config.emit.emit(socketRoom, AGENT_SOCKET_EVENTS.TURN_COMPLETE, {
1855
1888
  turnId,