@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.
Files changed (83) hide show
  1. package/README.md +123 -6
  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/approvals/hooks.d.ts +82 -0
  7. package/dist/approvals/hooks.d.ts.map +1 -0
  8. package/dist/approvals/hooks.js +94 -0
  9. package/dist/approvals/hooks.js.map +1 -0
  10. package/dist/container/server.d.ts +14 -0
  11. package/dist/container/server.d.ts.map +1 -1
  12. package/dist/container/server.js +36 -17
  13. package/dist/container/server.js.map +1 -1
  14. package/dist/emit/filter.d.ts +23 -0
  15. package/dist/emit/filter.d.ts.map +1 -0
  16. package/dist/emit/filter.js +27 -0
  17. package/dist/emit/filter.js.map +1 -0
  18. package/dist/emit/tee.d.ts +18 -0
  19. package/dist/emit/tee.d.ts.map +1 -0
  20. package/dist/emit/tee.js +19 -0
  21. package/dist/emit/tee.js.map +1 -0
  22. package/dist/index.d.ts +17 -4
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +12 -2
  25. package/dist/index.js.map +1 -1
  26. package/dist/lambda/handler.d.ts.map +1 -1
  27. package/dist/lambda/handler.js +4 -1
  28. package/dist/lambda/handler.js.map +1 -1
  29. package/dist/live-call/event-stream.d.ts +20 -0
  30. package/dist/live-call/event-stream.d.ts.map +1 -0
  31. package/dist/live-call/event-stream.js +43 -0
  32. package/dist/live-call/event-stream.js.map +1 -0
  33. package/dist/live-call/handler.d.ts +153 -0
  34. package/dist/live-call/handler.d.ts.map +1 -0
  35. package/dist/live-call/handler.js +416 -0
  36. package/dist/live-call/handler.js.map +1 -0
  37. package/dist/live-call/protocol.d.ts +157 -0
  38. package/dist/live-call/protocol.d.ts.map +1 -0
  39. package/dist/live-call/protocol.js +168 -0
  40. package/dist/live-call/protocol.js.map +1 -0
  41. package/dist/orchestrator.d.ts +5 -0
  42. package/dist/orchestrator.d.ts.map +1 -1
  43. package/dist/orchestrator.js +167 -33
  44. package/dist/orchestrator.js.map +1 -1
  45. package/dist/prompt/builder.d.ts +1 -1
  46. package/dist/prompt/builder.d.ts.map +1 -1
  47. package/dist/prompt/builder.js +8 -2
  48. package/dist/prompt/builder.js.map +1 -1
  49. package/dist/prompt/rules/base.js +4 -4
  50. package/dist/prompt/spoken-reply.d.ts +28 -0
  51. package/dist/prompt/spoken-reply.d.ts.map +1 -0
  52. package/dist/prompt/spoken-reply.js +49 -0
  53. package/dist/prompt/spoken-reply.js.map +1 -0
  54. package/dist/prompt/types.d.ts +12 -0
  55. package/dist/prompt/types.d.ts.map +1 -1
  56. package/dist/runtime/turn-info.d.ts +28 -0
  57. package/dist/runtime/turn-info.d.ts.map +1 -0
  58. package/dist/runtime/turn-info.js +23 -0
  59. package/dist/runtime/turn-info.js.map +1 -0
  60. package/dist/runtime/turn-runner.d.ts +42 -5
  61. package/dist/runtime/turn-runner.d.ts.map +1 -1
  62. package/dist/runtime/turn-runner.js +148 -36
  63. package/dist/runtime/turn-runner.js.map +1 -1
  64. package/dist/runtime/turn-slots.d.ts +30 -0
  65. package/dist/runtime/turn-slots.d.ts.map +1 -0
  66. package/dist/runtime/turn-slots.js +36 -0
  67. package/dist/runtime/turn-slots.js.map +1 -0
  68. package/dist/runtime/types.d.ts +45 -4
  69. package/dist/runtime/types.d.ts.map +1 -1
  70. package/dist/stop/turn-stop.d.ts +12 -1
  71. package/dist/stop/turn-stop.d.ts.map +1 -1
  72. package/dist/stop/turn-stop.js +47 -0
  73. package/dist/stop/turn-stop.js.map +1 -1
  74. package/dist/turn-policy.d.ts +8 -1
  75. package/dist/turn-policy.d.ts.map +1 -1
  76. package/dist/turn-policy.js.map +1 -1
  77. package/dist/types.d.ts +12 -0
  78. package/dist/types.d.ts.map +1 -1
  79. package/dist/ui/snapshot.d.ts +6 -4
  80. package/dist/ui/snapshot.d.ts.map +1 -1
  81. package/dist/ui/snapshot.js +8 -6
  82. package/dist/ui/snapshot.js.map +1 -1
  83. package/package.json +5 -5
@@ -0,0 +1,168 @@
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?, disclosureLine? }
16
+ *
17
+ * `input` is `{ mode: 'voice', language? }` for what the person said and
18
+ * `{ mode: 'text' }` for what they typed during the call. `output` is
19
+ * `{ mode: 'voice', voiceDirections? }` when a voice reads the reply out, with
20
+ * the tags that voice can be directed with. `disclosureLine`, on an `opening`
21
+ * turn, is what the call service has just said to the person before the
22
+ * agent's greeting (that they are talking with an AI assistant), as spoken.
23
+ *
24
+ * and the answer is `200 text/event-stream`:
25
+ *
26
+ * event: text data: { "text": "…" } the reply, piece by piece
27
+ * event: readback data: { "approvalId", "text", "expiresAt" } an approval's readback, verbatim
28
+ * event: done data: { "stopReason"?: "…" } the turn is over
29
+ * event: error data: { "code": "…", "message": "…" } the turn failed
30
+ *
31
+ * with `: keep-alive` comments while nothing else is sent.
32
+ */
33
+ import { readMessageInput, readReplyOutput } from '@ouispec/agent-core';
34
+ /** `message`: the person said `text`. `opening`: the call has just connected; nothing has been said, and the agent greets. */
35
+ export const LIVE_CALL_TURN_KINDS = ['message', 'opening'];
36
+ /**
37
+ * The person's message for an `opening` turn: an instruction to greet, which
38
+ * the model reads where the person's words would be. A host that stores the
39
+ * person's messages stores this one for the opening turn, so the conversation
40
+ * keeps the turn the greeting answers.
41
+ */
42
+ export const LIVE_CALL_OPENING_MESSAGE = '<call_opening>A live call with the user has just connected, and they have not said anything yet. ' +
43
+ '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>';
44
+ /**
45
+ * The person's message for an `opening` turn, as the model reads it: an
46
+ * instruction to greet, and, when the call service sent one, the disclosure
47
+ * it has just spoken, so the greeting follows on from it rather than repeating
48
+ * it. Without a disclosure it is `LIVE_CALL_OPENING_MESSAGE`. A host that
49
+ * stores the person's messages stores this for the opening turn.
50
+ */
51
+ export function liveCallOpeningMessage(request) {
52
+ const disclosure = request.disclosureLine?.trim();
53
+ if (!disclosure)
54
+ return LIVE_CALL_OPENING_MESSAGE;
55
+ return ('<call_opening>A live call with the user has just connected, and they have not said anything yet. ' +
56
+ `The call has already told them, in its own voice: "${disclosure}" ` +
57
+ 'Greet them in a sentence or two, following on from that without repeating it, and ask what they would like help with. ' +
58
+ 'This is not a message from the user.</call_opening>');
59
+ }
60
+ /**
61
+ * The `input` mode of a message the person typed during the call. It is read
62
+ * as typed: the turn's context carries no `input`, as for a message typed in
63
+ * the product's own chat.
64
+ */
65
+ export const LIVE_CALL_TYPED_INPUT_MODE = 'text';
66
+ /** Limits on a request. */
67
+ export const LIVE_CALL_LIMITS = {
68
+ /** The longest `sessionId`, `turnId`, or turn id in `supersedes`. */
69
+ idChars: 128,
70
+ /** The longest `clientRef`. */
71
+ clientRefChars: 512,
72
+ /** The longest `text`. */
73
+ textChars: 8_000,
74
+ /** The most turn ids in `supersedes`. */
75
+ supersedes: 32,
76
+ /** The longest `disclosureLine`. */
77
+ disclosureLineChars: 1_000,
78
+ };
79
+ /** An id: letters, digits and `.` `_` `:` `-`, starting with a letter or digit. */
80
+ const ID = new RegExp(`^[A-Za-z0-9][A-Za-z0-9._:-]{0,${LIVE_CALL_LIMITS.idChars - 1}}$`);
81
+ /** Any control character. */
82
+ // eslint-disable-next-line no-control-regex
83
+ const CONTROL = /[\u0000-\u001f\u007f]/;
84
+ /** Reads a live-call turn request's body. Every refusal names the field. */
85
+ export function readLiveCallTurnRequest(body) {
86
+ const refuse = (error) => ({ ok: false, error });
87
+ if (!body || typeof body !== 'object' || Array.isArray(body))
88
+ return refuse('the body must be a JSON object');
89
+ const b = body;
90
+ for (const field of ['sessionId', 'turnId']) {
91
+ if (typeof b[field] !== 'string' || !ID.test(b[field])) {
92
+ return refuse(`${field} must be an id of 1–${LIVE_CALL_LIMITS.idChars} letters, digits, '.', '_', ':' or '-'`);
93
+ }
94
+ }
95
+ const clientRef = b.clientRef;
96
+ if (typeof clientRef !== 'string' || !clientRef.trim() || clientRef.length > LIVE_CALL_LIMITS.clientRefChars || CONTROL.test(clientRef)) {
97
+ return refuse(`clientRef must be a string of 1–${LIVE_CALL_LIMITS.clientRefChars} characters with no control characters`);
98
+ }
99
+ if (typeof b.kind !== 'string' || !LIVE_CALL_TURN_KINDS.includes(b.kind)) {
100
+ return refuse(`kind must be one of ${LIVE_CALL_TURN_KINDS.join(', ')}`);
101
+ }
102
+ const kind = b.kind;
103
+ const text = b.text === undefined && kind === 'opening' ? '' : b.text;
104
+ if (typeof text !== 'string')
105
+ return refuse('text must be a string');
106
+ if (text.length > LIVE_CALL_LIMITS.textChars)
107
+ return refuse(`text is longer than ${LIVE_CALL_LIMITS.textChars} characters`);
108
+ if (kind === 'message' && !text.trim())
109
+ return refuse('a message turn needs the text the person said');
110
+ if (kind === 'opening' && text.trim())
111
+ return refuse('an opening turn carries no text');
112
+ for (const field of ['input', 'output']) {
113
+ const value = b[field];
114
+ if (value !== undefined && value !== null && (typeof value !== 'object' || Array.isArray(value)))
115
+ return refuse(`${field} must be an object`);
116
+ }
117
+ const supersedes = b.supersedes ?? [];
118
+ if (!Array.isArray(supersedes) || !supersedes.every((id) => typeof id === 'string' && ID.test(id))) {
119
+ return refuse('supersedes must be a list of turn ids');
120
+ }
121
+ if (supersedes.length > LIVE_CALL_LIMITS.supersedes)
122
+ return refuse(`supersedes names more than ${LIVE_CALL_LIMITS.supersedes} turns`);
123
+ const disclosureLine = b.disclosureLine ?? null;
124
+ if (disclosureLine !== null &&
125
+ (typeof disclosureLine !== 'string' || disclosureLine.length > LIVE_CALL_LIMITS.disclosureLineChars || CONTROL.test(disclosureLine))) {
126
+ return refuse(`disclosureLine must be a string of at most ${LIVE_CALL_LIMITS.disclosureLineChars} characters with no control characters`);
127
+ }
128
+ return {
129
+ ok: true,
130
+ request: {
131
+ sessionId: b.sessionId,
132
+ clientRef,
133
+ turnId: b.turnId,
134
+ kind,
135
+ text: kind === 'opening' ? '' : text,
136
+ // Nothing was said on an opening turn, so nothing was entered; a typed message is read as typed.
137
+ input: kind === 'opening' || isTyped(b.input) ? null : readMessageInput(b.input),
138
+ output: readReplyOutput(b.output),
139
+ supersedes: [...new Set(supersedes)].filter((id) => id !== b.turnId),
140
+ // Said before the greeting: an opening turn's alone.
141
+ disclosureLine: kind === 'opening' && disclosureLine?.trim() ? disclosureLine.trim() : null,
142
+ },
143
+ };
144
+ }
145
+ /** Whether `input` says the message was typed during the call. */
146
+ function isTyped(input) {
147
+ return !!input && typeof input === 'object' && input.mode === LIVE_CALL_TYPED_INPUT_MODE;
148
+ }
149
+ /**
150
+ * What a failed turn's `error` event says, by code. Fixed lines: the call
151
+ * service records the code and speaks its own apology, and the cause (a
152
+ * provider's error text, a stack) stays in the host's logs.
153
+ */
154
+ export const LIVE_CALL_ERROR_MESSAGES = {
155
+ RATE_LIMIT: 'The model provider is rate-limiting requests.',
156
+ SERVICE_UNAVAILABLE: 'The model provider is unavailable.',
157
+ MODEL_TIMEOUT: 'The model timed out.',
158
+ TURN_TIMEOUT: 'The turn timed out.',
159
+ TURN_DEADLINE_EXCEEDED: 'The turn ran out of time.',
160
+ TURN_REFUSED: 'The turn was refused by its record: it already ended or was given up on.',
161
+ TURN_DECLINED: 'The product declined to run the turn.',
162
+ WORKER_ERROR: 'The turn failed.',
163
+ };
164
+ /** The `error` event for a failure code. */
165
+ export function liveCallError(code) {
166
+ return { code, message: LIVE_CALL_ERROR_MESSAGES[code] ?? LIVE_CALL_ERROR_MESSAGES.WORKER_ERROR };
167
+ }
168
+ //# sourceMappingURL=protocol.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"protocol.js","sourceRoot":"","sources":["../../src/live-call/protocol.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,OAAO,EAAE,gBAAgB,EAAE,eAAe,EAAuC,MAAM,qBAAqB,CAAC;AAE7G,8HAA8H;AAC9H,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,SAAS,EAAE,SAAS,CAAU,CAAC;AAgEpE;;;;;GAKG;AACH,MAAM,CAAC,MAAM,yBAAyB,GACpC,mGAAmG;IACnG,8HAA8H,CAAC;AAEjI;;;;;;GAMG;AACH,MAAM,UAAU,sBAAsB,CAAC,OAAoD;IACzF,MAAM,UAAU,GAAG,OAAO,CAAC,cAAc,EAAE,IAAI,EAAE,CAAC;IAClD,IAAI,CAAC,UAAU;QAAE,OAAO,yBAAyB,CAAC;IAClD,OAAO,CACL,mGAAmG;QACnG,sDAAsD,UAAU,IAAI;QACpE,wHAAwH;QACxH,qDAAqD,CACtD,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,0BAA0B,GAAG,MAAM,CAAC;AAEjD,2BAA2B;AAC3B,MAAM,CAAC,MAAM,gBAAgB,GAAG;IAC9B,qEAAqE;IACrE,OAAO,EAAE,GAAG;IACZ,+BAA+B;IAC/B,cAAc,EAAE,GAAG;IACnB,0BAA0B;IAC1B,SAAS,EAAE,KAAK;IAChB,yCAAyC;IACzC,UAAU,EAAE,EAAE;IACd,oCAAoC;IACpC,mBAAmB,EAAE,KAAK;CAClB,CAAC;AAEX,mFAAmF;AACnF,MAAM,EAAE,GAAG,IAAI,MAAM,CAAC,iCAAiC,gBAAgB,CAAC,OAAO,GAAG,CAAC,IAAI,CAAC,CAAC;AACzF,6BAA6B;AAC7B,4CAA4C;AAC5C,MAAM,OAAO,GAAG,uBAAuB,CAAC;A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SAC5F;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,aAAa,EAAE,uCAAuC;IACtD,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,4 +1,9 @@
1
1
  import type { AgentWorkerConfig, AgentTurnInput, AgentTurnResult } from './types.js';
2
+ /**
3
+ * Tools that hand the turn back to the user. The turn stops after any of them:
4
+ * the model must not carry on as if the user had already answered.
5
+ */
6
+ export declare const USER_INPUT_TOOLS: readonly ["present_options", "confirm_action", "request_user_decision"];
2
7
  /**
3
8
  * Run a complete agent turn using the Vercel AI SDK.
4
9
  *
@@ -1 +1 @@
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;AA0GtH;;;;;;;;GAQG;AACH,wBAAsB,YAAY,CAChC,MAAM,EAAE,iBAAiB,EACzB,KAAK,EAAE,cAAc,GACpB,OAAO,CAAC,eAAe,CAAC,CAy5D1B"}
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;AAgFtH;;;GAGG;AACH,eAAO,MAAM,gBAAgB,yEAA0E,CAAC;AAyBxG;;;;;;;;GAQG;AACH,wBAAsB,YAAY,CAChC,MAAM,EAAE,iBAAiB,EACzB,KAAK,EAAE,cAAc,GACpB,OAAO,CAAC,eAAe,CAAC,CA4jE1B"}
@@ -34,6 +34,7 @@ import { answerWithoutState, withStatesAtEnd } from './ui/page-state-at-end.js';
34
34
  import { stepMessages as forStep, STEP_NOTE_CLOSE, STEP_NOTE_OPEN } from './step-messages.js';
35
35
  import { clockText, readClientTimeZone } from './prompt/clock.js';
36
36
  import { readClientMessageInput, spokenInputText } from './prompt/spoken-input.js';
37
+ import { readClientReplyOutput, spokenReplyText } from './prompt/spoken-reply.js';
37
38
  import { AttachmentGuard } from './attachments/guard.js';
38
39
  import { ATTACHMENT_DATA_NOTE, turnAttachmentParts, withReferenceLines, withTurnAttachments, withoutLeftOut } from './attachments/content.js';
39
40
  import { attachmentTools } from './attachments/tools.js';
@@ -47,6 +48,8 @@ import { createTurnLedger } from './turn-ledger.js';
47
48
  import { DEFAULT_PAGE_STATE_CHARS, observationSchemas, observationsText } from './ui/observations.js';
48
49
  import { approvalRequirement, APPROVAL_TOOL_NOTE } from './approvals/requirement.js';
49
50
  import { buildApprovalPreview, declaredTitle } from './approvals/preview.js';
51
+ import { readHostPreview, readValidation } from './approvals/hooks.js';
52
+ import { turnInfoOf } from './runtime/turn-info.js';
50
53
  import { approvalMarker, approvedExpiredMarker, expiredNote, markedResult, notRunResult, ranNote, refusedNote, resolveContinuation, unavailableNote, waitingCalls, withdrawnMarker, } from './approvals/continuation.js';
51
54
  const DEFAULT_MAX_ROUNDS = 12;
52
55
  /**
@@ -76,7 +79,7 @@ const UI_ANSWER_MARGIN_MS = 45_000;
76
79
  * Tools that hand the turn back to the user. The turn stops after any of them:
77
80
  * the model must not carry on as if the user had already answered.
78
81
  */
79
- const USER_INPUT_TOOLS = ['present_options', 'confirm_action', 'request_user_decision'];
82
+ export const USER_INPUT_TOOLS = ['present_options', 'confirm_action', 'request_user_decision'];
80
83
  function log(level, ns, message, data) {
81
84
  const entry = { level, ns, message, timestamp: new Date().toISOString(), ...data };
82
85
  if (level === 'error')
@@ -111,6 +114,8 @@ export async function runAgentTurn(config, input) {
111
114
  throw new Error('[agent-sdk] config.model is required: pass an `ai` library model');
112
115
  }
113
116
  const { turnId, socketRoom } = input;
117
+ // The turn as every host hook is told of it: its id, its channel, how its message was entered.
118
+ const turnInfo = turnInfoOf(input, input.channel);
114
119
  log('info', 'agent:turn', 'Turn started', {
115
120
  turnId,
116
121
  conversationId: input.conversationId,
@@ -186,7 +191,7 @@ export async function runAgentTurn(config, input) {
186
191
  role: m.role,
187
192
  content: 'content' in m ? (m.content ?? '') : '',
188
193
  })) ?? [];
189
- const turnClass = turnPolicy.classifyTurn(input.content, historyForClassify);
194
+ const turnClass = turnPolicy.classifyTurn(input.content, historyForClassify, turnInfo);
190
195
  // Let the policy perform side effects (e.g. deterministic navigation emit)
191
196
  if (turnPolicy.onTurnClassified) {
192
197
  await turnPolicy.onTurnClassified({
@@ -194,6 +199,7 @@ export async function runAgentTurn(config, input) {
194
199
  content: input.content,
195
200
  emit: config.emit,
196
201
  socketRoom,
202
+ turn: turnInfo,
197
203
  });
198
204
  }
199
205
  log('info', 'agent:turn', 'Turn classified', { turnId, turnClass });
@@ -314,11 +320,33 @@ export async function runAgentTurn(config, input) {
314
320
  // What each call of the turn did: said back to the model before every step
315
321
  // after one did not succeed, so its reply matches it.
316
322
  const ledger = createTurnLedger();
317
- // ─── Approvals ──────────────────────────────────────────────────
318
- // The first call in a turn that needs the user's approval stops the turn:
319
- // it is stored as a pending approval, the card is shown, and nothing else
320
- // runs until they decide. Each call is approved separately.
321
323
  let approvalHold = null;
324
+ /** What the host's approval hooks are told of this turn. */
325
+ const approvalHookContext = {
326
+ turn: turnInfo,
327
+ channel: turnInfo.channel,
328
+ locale: turnInfo.language,
329
+ userId: input.userId,
330
+ accountId: input.accountId,
331
+ conversationId: input.conversationId,
332
+ };
333
+ /** The host's check of a call before it is asked for; a throw refuses it. */
334
+ const validateForApproval = async (t, args) => {
335
+ const validate = config.approvalHooks?.validateBeforeApproval;
336
+ if (!validate)
337
+ return { ok: true };
338
+ try {
339
+ return readValidation(await validate(t, args, approvalHookContext));
340
+ }
341
+ catch (err) {
342
+ log('error', 'agent:tool', 'The host’s check before approval threw; the call was not asked for', {
343
+ turnId,
344
+ toolName: t.name,
345
+ error: err instanceof Error ? err.message : String(err),
346
+ });
347
+ return readValidation(null);
348
+ }
349
+ };
322
350
  // jsonSchema() carries no validator, so a call's arguments are whatever the
323
351
  // model produced. Each tool's declared schema is compiled once per turn.
324
352
  const validators = new WeakMap();
@@ -354,14 +382,14 @@ export async function runAgentTurn(config, input) {
354
382
  const refused = async (payload, given) => {
355
383
  ledger.record({ tool: t.name, ok: false, error: payload.error });
356
384
  const now = Date.now();
357
- await config.emit.emit(socketRoom, AGENT_SOCKET_EVENTS.TOOL_CALL_STARTED, {
385
+ await emitAfterText(AGENT_SOCKET_EVENTS.TOOL_CALL_STARTED, {
358
386
  turnId,
359
387
  toolUseId,
360
388
  name: t.name,
361
389
  input: given,
362
390
  timestamp: now,
363
391
  });
364
- await config.emit.emit(socketRoom, AGENT_SOCKET_EVENTS.TOOL_CALL_COMPLETE, {
392
+ await emitAfterText(AGENT_SOCKET_EVENTS.TOOL_CALL_COMPLETE, {
365
393
  turnId,
366
394
  toolUseId,
367
395
  name: t.name,
@@ -555,6 +583,9 @@ export async function runAgentTurn(config, input) {
555
583
  // ── Approval ──
556
584
  // Checked and set with no await in between, so of the calls in one
557
585
  // response exactly the first that needs approval stops the turn.
586
+ // A call another one's approval is being prepared for waits to see whether that one is asked for.
587
+ while (approvalHold?.preparing && !approved)
588
+ await approvalHold.preparing;
558
589
  if (approvalHold && !approved) {
559
590
  const error = `Not run: this turn is waiting for the user's approval of "${approvalHold.title}". ` +
560
591
  'Nothing else runs until they decide; ask again afterwards if it is still needed.';
@@ -562,8 +593,25 @@ export async function runAgentTurn(config, input) {
562
593
  return notRun({ success: false, notRun: true, error });
563
594
  }
564
595
  if ((requirement.required || policyRequiresApproval) && !approved) {
565
- ledger.record({ tool: t.name, ok: false, error: 'Not run: it waits for the user’s approval on the card' });
566
- return { text: await requestApproval(t, args, toolUseId, requirement, callFiles), ran: false };
596
+ // Claimed before anything is awaited (above).
597
+ let prepared;
598
+ const hold = { approvalId: toolUseId, title: declaredTitle(t).title, preparing: new Promise((resolve) => (prepared = resolve)) };
599
+ approvalHold = hold;
600
+ try {
601
+ const checked = await validateForApproval(t, args);
602
+ if (!checked.ok) {
603
+ if (approvalHold === hold)
604
+ approvalHold = null;
605
+ log('info', 'agent:tool', 'The host refused the call before it was asked for', { turnId, toolName: t.name });
606
+ return refused({ error: checked.error, notRun: true, refusedBeforeApproval: true }, args);
607
+ }
608
+ ledger.record({ tool: t.name, ok: false, error: 'Not run: it waits for the user’s approval on the card' });
609
+ return { text: await requestApproval(t, args, toolUseId, requirement, callFiles, hold), ran: false };
610
+ }
611
+ finally {
612
+ hold.preparing = undefined;
613
+ prepared();
614
+ }
567
615
  }
568
616
  if (t.name === UI_DESCRIBE_TOOL)
569
617
  uiCounts.describes++;
@@ -582,7 +630,7 @@ export async function runAgentTurn(config, input) {
582
630
  ...(approved ? { approvalId: approved.approvalId } : {}),
583
631
  });
584
632
  // Emit tool call started BEFORE execution
585
- await config.emit.emit(socketRoom, AGENT_SOCKET_EVENTS.TOOL_CALL_STARTED, {
633
+ await emitAfterText(AGENT_SOCKET_EVENTS.TOOL_CALL_STARTED, {
586
634
  turnId,
587
635
  toolUseId,
588
636
  name: t.name,
@@ -642,7 +690,7 @@ export async function runAgentTurn(config, input) {
642
690
  durationMs,
643
691
  ...(isUI && !resultSuccess ? { error: isWrapped ? result.error : undefined } : {}),
644
692
  });
645
- await config.emit.emit(socketRoom, AGENT_SOCKET_EVENTS.TOOL_CALL_COMPLETE, {
693
+ await emitAfterText(AGENT_SOCKET_EVENTS.TOOL_CALL_COMPLETE, {
646
694
  turnId,
647
695
  toolUseId,
648
696
  name: t.name,
@@ -701,21 +749,41 @@ export async function runAgentTurn(config, input) {
701
749
  * stores it as a pending approval, shows the card, and tells the model only
702
750
  * that it is waiting. The model never sees a token.
703
751
  */
704
- const requestApproval = async (t, args, toolUseId, requirement, files) => {
752
+ const requestApproval = async (t, args, toolUseId, requirement, files, hold) => {
705
753
  // A file is shown by its name and size; the approval stays bound to its id.
706
- const preview = buildApprovalPreview(t, args, files);
707
- approvalHold = { approvalId: toolUseId, title: preview.title };
754
+ const built = buildApprovalPreview(t, args, files);
708
755
  const refuse = (why) => {
709
- approvalHold = null;
756
+ if (approvalHold === hold)
757
+ approvalHold = null;
710
758
  log('error', 'agent:tool', 'Approval could not be requested; the call was not run', { turnId, toolName: t.name, why });
711
759
  return JSON.stringify({
712
760
  success: false,
713
761
  notRun: true,
714
- error: `"${preview.title}" needs the user's approval, which could not be asked for (${why}). It was not run.`,
762
+ error: `"${built.title}" needs the user's approval, which could not be asked for (${why}). It was not run.`,
715
763
  });
716
764
  };
717
765
  if (!config.approvals)
718
766
  return refuse('this assistant has no approval store');
767
+ // The host's display copy, when it writes one: stored, shown and read back in place of the built one.
768
+ // The arguments stored and hashed are the call's own.
769
+ let preview = built;
770
+ const writePreview = config.approvalHooks?.preview;
771
+ if (writePreview) {
772
+ let written;
773
+ try {
774
+ written = readHostPreview(await writePreview(t, args, { ...approvalHookContext, built }));
775
+ }
776
+ catch (err) {
777
+ log('error', 'agent:tool', 'The host’s approval preview threw', { turnId, toolName: t.name, error: err instanceof Error ? err.message : String(err) });
778
+ return refuse('its preview could not be written');
779
+ }
780
+ if (!written.ok) {
781
+ log('error', 'agent:tool', 'The host’s approval preview is not one', { turnId, toolName: t.name, problem: written.error });
782
+ return refuse('its preview could not be written');
783
+ }
784
+ preview = written.preview;
785
+ hold.title = preview.title;
786
+ }
719
787
  const expiresAt = Date.now() + requirement.ttlMs;
720
788
  try {
721
789
  const hash = await argsHash(args);
@@ -738,7 +806,7 @@ export async function runAgentTurn(config, input) {
738
806
  catch (err) {
739
807
  return refuse(err instanceof Error ? err.message : String(err));
740
808
  }
741
- await config.emit.emit(socketRoom, AGENT_SOCKET_EVENTS.APPROVAL_REQUIRED, {
809
+ await emitAfterText(AGENT_SOCKET_EVENTS.APPROVAL_REQUIRED, {
742
810
  turnId,
743
811
  conversationId: input.conversationId,
744
812
  approvalId: toolUseId,
@@ -1058,10 +1126,19 @@ export async function runAgentTurn(config, input) {
1058
1126
  // text ends, not when its end is reported. The break is only streamed; what
1059
1127
  // the model said is recorded as it said it.
1060
1128
  const ROUND_BREAK = '\n\n';
1061
- /** Where, in the turn's text, a round that said something and then called tools ended. */
1062
- const roundBreaks = [];
1063
1129
  /** The turn's text the steps have reported so far. */
1064
1130
  let stepTextReported = 0;
1131
+ /** Rounds whose end has been reported and not yet sent: the stream has not reached it. */
1132
+ const roundEnds = [];
1133
+ /** The round whose text is being streamed (and is in the coalescing buffer): every round before it has been sent as ended. */
1134
+ let streamingStep = 0;
1135
+ /** Text that follows starts a new paragraph. */
1136
+ let paragraphPending = false;
1137
+ /**
1138
+ * Whether the turn ends after a round that called these tools: the
1139
+ * conditions `stopWhen` holds the model to, beside the step count.
1140
+ */
1141
+ const endsAfterRound = (toolNames) => approvalHold !== null || handedBackForTime || toolNames.some((name) => USER_INPUT_TOOLS.includes(name));
1065
1142
  // ─── Coalesce token deltas ─────────────────────────────────────────────────
1066
1143
  // Buffer for 50ms or 32 chars, whichever comes first, to avoid one HTTP POST
1067
1144
  // per token delta to the realtime server.
@@ -1081,10 +1158,56 @@ export async function runAgentTurn(config, input) {
1081
1158
  await config.emit.emit(socketRoom, AGENT_SOCKET_EVENTS.TOKEN, {
1082
1159
  turnId,
1083
1160
  text,
1161
+ step: streamingStep,
1084
1162
  timestamp: Date.now(),
1085
1163
  });
1086
1164
  }
1087
1165
  };
1166
+ /**
1167
+ * Sends the end of every round the text stream has delivered all of: what
1168
+ * is left of its text, then its end. Each emit is made before anything is
1169
+ * awaited, so the room and a host observing the turn get them in order.
1170
+ */
1171
+ const endReachedRounds = async () => {
1172
+ const sends = [];
1173
+ while (roundEnds.length > 0 && streamedText.length >= roundEnds[0].at) {
1174
+ const end = roundEnds.shift();
1175
+ sends.push(flushTokenBuffer());
1176
+ sends.push(config.emit.emit(socketRoom, AGENT_SOCKET_EVENTS.ROUND_END, {
1177
+ turnId,
1178
+ step: streamingStep,
1179
+ calledTools: end.calledTools,
1180
+ final: end.final,
1181
+ timestamp: Date.now(),
1182
+ }));
1183
+ streamingStep += 1;
1184
+ paragraphPending ||= end.paragraph;
1185
+ }
1186
+ await Promise.all(sends);
1187
+ };
1188
+ /**
1189
+ * Streams text the worker itself says, not the model (the reply when every
1190
+ * attempt was cut off at the output limit), as a round of its own: the
1191
+ * turn's last word.
1192
+ */
1193
+ const sayAsFinalRound = async (text) => {
1194
+ const reply = (streamedText ? ROUND_BREAK : '') + text;
1195
+ paragraphPending = false;
1196
+ streamedText += reply;
1197
+ tokenBuffer += reply;
1198
+ roundEnds.push({ at: streamedText.length, calledTools: false, final: true, paragraph: false });
1199
+ await endReachedRounds();
1200
+ };
1201
+ /**
1202
+ * A turn event that comes after what the model has said so far: the text
1203
+ * still held for coalescing is sent first. A tool's call and an approval's
1204
+ * preview then reach the room, and a host observing the turn's events, after
1205
+ * the words the model said before them, as they were said.
1206
+ */
1207
+ const emitAfterText = async (event, data) => {
1208
+ await flushTokenBuffer();
1209
+ await config.emit.emit(socketRoom, event, data);
1210
+ };
1088
1211
  // The model's thinking, relayed to the room: its start and end, and its
1089
1212
  // summary when the host asked the model for one (reasoning-relay.ts).
1090
1213
  const reasoningRelay = createReasoningRelay({
@@ -1301,6 +1424,8 @@ export async function runAgentTurn(config, input) {
1301
1424
  const turnMessageAt = messages.map((m) => m.role).lastIndexOf('user');
1302
1425
  const turnClock = clockText(new Date(), readClientTimeZone(input.context ?? null));
1303
1426
  const turnSpoken = input.approval ? null : readClientMessageInput(input.context ?? null);
1427
+ // The reply is spoken on every turn of a call, the turn an approval continues included.
1428
+ const turnSpokenReply = readClientReplyOutput(input.context ?? null);
1304
1429
  const turnPageValues = client && client.page.length > 0
1305
1430
  ? [
1306
1431
  observationsText(client.observations, config.ui?.maxObservationChars ?? DEFAULT_PAGE_STATE_CHARS, {
@@ -1331,6 +1456,8 @@ export async function runAgentTurn(config, input) {
1331
1456
  // A message the person spoke may hold a mis-heard word (prompt/spoken-input.ts). A click on an
1332
1457
  // approval card is not a message, so it says nothing.
1333
1458
  ...(turnSpoken ? [spokenInputText(turnSpoken)] : []),
1459
+ // A reply a voice will read out is written for the ear (prompt/spoken-reply.ts).
1460
+ ...(turnSpokenReply ? [spokenReplyText(turnSpokenReply)] : []),
1334
1461
  ...(expired.outcomes.length > 0 ? [expiredNote(expired)] : []),
1335
1462
  ...(input.stepContext?.trim() ? [input.stepContext.trim()] : []),
1336
1463
  ...(notes.length > 0 ? [[STEP_NOTE_OPEN, ...notes, STEP_NOTE_CLOSE].join('\n')] : []),
@@ -1424,6 +1551,7 @@ export async function runAgentTurn(config, input) {
1424
1551
  ...Object.keys(aiTools).map((name) => describeStepTool(name)),
1425
1552
  ...actionIds.map((name) => ({ name, kind: 'ui' })),
1426
1553
  ],
1554
+ turn: turnInfo,
1427
1555
  });
1428
1556
  const { note, ...policy } = stepPolicy;
1429
1557
  // What it constrained, in the model's terms: an action is run through
@@ -1494,8 +1622,7 @@ export async function runAgentTurn(config, input) {
1494
1622
  },
1495
1623
  onStepEnd: async ({ text, toolCalls, usage: stepUsage, finishReason }) => {
1496
1624
  stepTextReported += text?.length ?? 0;
1497
- if (text && (toolCalls?.length ?? 0) > 0)
1498
- roundBreaks.push(stepTextReported);
1625
+ const calledTools = (toolCalls?.length ?? 0) > 0;
1499
1626
  recordedSteps.push({
1500
1627
  text: text ?? '',
1501
1628
  toolCalls: (toolCalls ?? []).map((tc) => ({ toolCallId: tc.toolCallId, toolName: tc.toolName, input: tc.input })),
@@ -1504,6 +1631,14 @@ export async function runAgentTurn(config, input) {
1504
1631
  cacheReadTokens: stepUsage?.inputTokenDetails?.cacheReadTokens ?? 0,
1505
1632
  cacheWriteTokens: stepUsage?.inputTokenDetails?.cacheWriteTokens ?? 0,
1506
1633
  });
1634
+ // A round that called tools is the last when the turn stops after it (an approval, a choice, the
1635
+ // hand-back for time) or it was the last step allowed. A round cut off at the output limit having
1636
+ // said and called nothing never is: it runs again, or the person is told (below).
1637
+ const cutOff = finishReason === 'length' && !text && !calledTools;
1638
+ const final = !cutOff && (!calledTools || recordedSteps.length >= maxRounds || endsAfterRound((toolCalls ?? []).map((tc) => tc.toolName)));
1639
+ roundEnds.push({ at: stepTextReported, calledTools, final, paragraph: !!text && calledTools });
1640
+ // Sent now when the stream has already delivered the round's text; else when it has.
1641
+ await endReachedRounds();
1507
1642
  log('info', 'agent:llm', 'Step completed', {
1508
1643
  turnId,
1509
1644
  turnClass,
@@ -1527,27 +1662,30 @@ export async function runAgentTurn(config, input) {
1527
1662
  for await (const textPart of result.textStream) {
1528
1663
  let rest = textPart;
1529
1664
  while (rest) {
1665
+ // The rounds whose text has all been delivered end before any of the next round's.
1666
+ await endReachedRounds();
1530
1667
  // Text after a round that ended in tool calls starts a new paragraph.
1531
- if (roundBreaks.length > 0 && streamedText.length >= roundBreaks[0]) {
1532
- roundBreaks.shift();
1668
+ if (paragraphPending) {
1669
+ paragraphPending = false;
1533
1670
  if (streamedText.length > 0)
1534
1671
  tokenBuffer += ROUND_BREAK;
1535
- continue;
1536
1672
  }
1537
- // A piece never runs past the next break, should one reach across it.
1538
- const upTo = roundBreaks.length > 0 ? roundBreaks[0] - streamedText.length : rest.length;
1673
+ // A piece never runs past the end of its round, should one reach across it.
1674
+ const upTo = roundEnds.length > 0 ? roundEnds[0].at - streamedText.length : rest.length;
1539
1675
  const piece = rest.slice(0, upTo);
1540
1676
  rest = rest.slice(piece.length);
1541
1677
  streamedText += piece;
1542
1678
  tokenBuffer += piece;
1543
1679
  }
1680
+ await endReachedRounds();
1544
1681
  if (tokenBuffer.length >= COALESCE_CHARS) {
1545
1682
  await flushTokenBuffer();
1546
1683
  }
1547
- else if (!flushTimer) {
1684
+ else if (!flushTimer && tokenBuffer.length > 0) {
1548
1685
  flushTimer = setTimeout(() => flushTokenBuffer(), COALESCE_MS);
1549
1686
  }
1550
1687
  }
1688
+ await endReachedRounds();
1551
1689
  await flushTokenBuffer();
1552
1690
  if (stopOf(abortController.signal))
1553
1691
  break;
@@ -1598,11 +1736,7 @@ export async function runAgentTurn(config, input) {
1598
1736
  }
1599
1737
  // Every attempt was cut off: the person hears so, rather than nothing.
1600
1738
  if (outputLimited && !stopOf(abortController.signal)) {
1601
- const reply = (streamedText ? ROUND_BREAK : '') + OUTPUT_LIMIT_REPLY;
1602
- roundBreaks.length = 0;
1603
- streamedText += reply;
1604
- tokenBuffer += reply;
1605
- await flushTokenBuffer();
1739
+ await sayAsFinalRound(OUTPUT_LIMIT_REPLY);
1606
1740
  }
1607
1741
  // ─── Stopped, or ending ────────────────────────────────────────────────────
1608
1742
  // Decided here with nothing awaited in between: either the stop was heard