@ouispec/agent-worker 0.15.0 → 0.17.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 (79) hide show
  1. package/README.md +78 -14
  2. package/dist/approvals/client.d.ts +5 -1
  3. package/dist/approvals/client.d.ts.map +1 -1
  4. package/dist/approvals/client.js +3 -2
  5. package/dist/approvals/client.js.map +1 -1
  6. package/dist/approvals/continuation.d.ts +2 -1
  7. package/dist/approvals/continuation.d.ts.map +1 -1
  8. package/dist/approvals/continuation.js +1 -1
  9. package/dist/approvals/continuation.js.map +1 -1
  10. package/dist/approvals/hooks.d.ts +82 -0
  11. package/dist/approvals/hooks.d.ts.map +1 -0
  12. package/dist/approvals/hooks.js +94 -0
  13. package/dist/approvals/hooks.js.map +1 -0
  14. package/dist/container/server.js +1 -1
  15. package/dist/container/server.js.map +1 -1
  16. package/dist/emit/filter.d.ts +23 -0
  17. package/dist/emit/filter.d.ts.map +1 -0
  18. package/dist/emit/filter.js +27 -0
  19. package/dist/emit/filter.js.map +1 -0
  20. package/dist/index.d.ts +10 -4
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +6 -2
  23. package/dist/index.js.map +1 -1
  24. package/dist/lambda/handler.d.ts.map +1 -1
  25. package/dist/lambda/handler.js +4 -1
  26. package/dist/lambda/handler.js.map +1 -1
  27. package/dist/live-call/handler.d.ts +34 -2
  28. package/dist/live-call/handler.d.ts.map +1 -1
  29. package/dist/live-call/handler.js +91 -13
  30. package/dist/live-call/handler.js.map +1 -1
  31. package/dist/live-call/protocol.d.ts +29 -3
  32. package/dist/live-call/protocol.d.ts.map +1 -1
  33. package/dist/live-call/protocol.js +32 -2
  34. package/dist/live-call/protocol.js.map +1 -1
  35. package/dist/openapi/executor.d.ts +0 -7
  36. package/dist/openapi/executor.d.ts.map +1 -1
  37. package/dist/openapi/executor.js +17 -0
  38. package/dist/openapi/executor.js.map +1 -1
  39. package/dist/openapi/loader.d.ts +2 -1
  40. package/dist/openapi/loader.d.ts.map +1 -1
  41. package/dist/openapi/loader.js +8 -1
  42. package/dist/openapi/loader.js.map +1 -1
  43. package/dist/orchestrator.d.ts +5 -0
  44. package/dist/orchestrator.d.ts.map +1 -1
  45. package/dist/orchestrator.js +166 -30
  46. package/dist/orchestrator.js.map +1 -1
  47. package/dist/prompt/builder.d.ts +1 -1
  48. package/dist/prompt/builder.d.ts.map +1 -1
  49. package/dist/prompt/builder.js +8 -2
  50. package/dist/prompt/builder.js.map +1 -1
  51. package/dist/prompt/rules/base.js +4 -4
  52. package/dist/prompt/spoken-reply.d.ts +1 -1
  53. package/dist/prompt/spoken-reply.d.ts.map +1 -1
  54. package/dist/prompt/spoken-reply.js +14 -2
  55. package/dist/prompt/spoken-reply.js.map +1 -1
  56. package/dist/prompt/types.d.ts +12 -0
  57. package/dist/prompt/types.d.ts.map +1 -1
  58. package/dist/runtime/turn-info.d.ts +28 -0
  59. package/dist/runtime/turn-info.d.ts.map +1 -0
  60. package/dist/runtime/turn-info.js +23 -0
  61. package/dist/runtime/turn-info.js.map +1 -0
  62. package/dist/runtime/turn-runner.d.ts +15 -2
  63. package/dist/runtime/turn-runner.d.ts.map +1 -1
  64. package/dist/runtime/turn-runner.js +65 -10
  65. package/dist/runtime/turn-runner.js.map +1 -1
  66. package/dist/runtime/types.d.ts +45 -4
  67. package/dist/runtime/types.d.ts.map +1 -1
  68. package/dist/tools/types.d.ts +31 -4
  69. package/dist/tools/types.d.ts.map +1 -1
  70. package/dist/tools/types.js.map +1 -1
  71. package/dist/turn-policy.d.ts +8 -1
  72. package/dist/turn-policy.d.ts.map +1 -1
  73. package/dist/turn-policy.js.map +1 -1
  74. package/dist/types.d.ts +12 -0
  75. package/dist/types.d.ts.map +1 -1
  76. package/dist/ui/ui-tools.d.ts.map +1 -1
  77. package/dist/ui/ui-tools.js +2 -1
  78. package/dist/ui/ui-tools.js.map +1 -1
  79. package/package.json +5 -5
@@ -19,7 +19,7 @@
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, isTurnEndReason, turnStoppedNote, } from '@ouispec/agent-core';
22
+ import { AGENT_SOCKET_EVENTS, argsHash, approvalReceiptAudience, 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';
@@ -48,6 +48,8 @@ import { createTurnLedger } from './turn-ledger.js';
48
48
  import { DEFAULT_PAGE_STATE_CHARS, observationSchemas, observationsText } from './ui/observations.js';
49
49
  import { approvalRequirement, APPROVAL_TOOL_NOTE } from './approvals/requirement.js';
50
50
  import { buildApprovalPreview, declaredTitle } from './approvals/preview.js';
51
+ import { readHostPreview, readValidation } from './approvals/hooks.js';
52
+ import { turnInfoOf } from './runtime/turn-info.js';
51
53
  import { approvalMarker, approvedExpiredMarker, expiredNote, markedResult, notRunResult, ranNote, refusedNote, resolveContinuation, unavailableNote, waitingCalls, withdrawnMarker, } from './approvals/continuation.js';
52
54
  const DEFAULT_MAX_ROUNDS = 12;
53
55
  /**
@@ -77,7 +79,7 @@ const UI_ANSWER_MARGIN_MS = 45_000;
77
79
  * Tools that hand the turn back to the user. The turn stops after any of them:
78
80
  * the model must not carry on as if the user had already answered.
79
81
  */
80
- const USER_INPUT_TOOLS = ['present_options', 'confirm_action', 'request_user_decision'];
82
+ export const USER_INPUT_TOOLS = ['present_options', 'confirm_action', 'request_user_decision'];
81
83
  function log(level, ns, message, data) {
82
84
  const entry = { level, ns, message, timestamp: new Date().toISOString(), ...data };
83
85
  if (level === 'error')
@@ -112,6 +114,8 @@ export async function runAgentTurn(config, input) {
112
114
  throw new Error('[agent-sdk] config.model is required: pass an `ai` library model');
113
115
  }
114
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);
115
119
  log('info', 'agent:turn', 'Turn started', {
116
120
  turnId,
117
121
  conversationId: input.conversationId,
@@ -187,7 +191,7 @@ export async function runAgentTurn(config, input) {
187
191
  role: m.role,
188
192
  content: 'content' in m ? (m.content ?? '') : '',
189
193
  })) ?? [];
190
- const turnClass = turnPolicy.classifyTurn(input.content, historyForClassify);
194
+ const turnClass = turnPolicy.classifyTurn(input.content, historyForClassify, turnInfo);
191
195
  // Let the policy perform side effects (e.g. deterministic navigation emit)
192
196
  if (turnPolicy.onTurnClassified) {
193
197
  await turnPolicy.onTurnClassified({
@@ -195,6 +199,7 @@ export async function runAgentTurn(config, input) {
195
199
  content: input.content,
196
200
  emit: config.emit,
197
201
  socketRoom,
202
+ turn: turnInfo,
198
203
  });
199
204
  }
200
205
  log('info', 'agent:turn', 'Turn classified', { turnId, turnClass });
@@ -315,11 +320,33 @@ export async function runAgentTurn(config, input) {
315
320
  // What each call of the turn did: said back to the model before every step
316
321
  // after one did not succeed, so its reply matches it.
317
322
  const ledger = createTurnLedger();
318
- // ─── Approvals ──────────────────────────────────────────────────
319
- // The first call in a turn that needs the user's approval stops the turn:
320
- // it is stored as a pending approval, the card is shown, and nothing else
321
- // runs until they decide. Each call is approved separately.
322
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
+ };
323
350
  // jsonSchema() carries no validator, so a call's arguments are whatever the
324
351
  // model produced. Each tool's declared schema is compiled once per turn.
325
352
  const validators = new WeakMap();
@@ -556,6 +583,9 @@ export async function runAgentTurn(config, input) {
556
583
  // ── Approval ──
557
584
  // Checked and set with no await in between, so of the calls in one
558
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;
559
589
  if (approvalHold && !approved) {
560
590
  const error = `Not run: this turn is waiting for the user's approval of "${approvalHold.title}". ` +
561
591
  'Nothing else runs until they decide; ask again afterwards if it is still needed.';
@@ -563,8 +593,25 @@ export async function runAgentTurn(config, input) {
563
593
  return notRun({ success: false, notRun: true, error });
564
594
  }
565
595
  if ((requirement.required || policyRequiresApproval) && !approved) {
566
- ledger.record({ tool: t.name, ok: false, error: 'Not run: it waits for the user’s approval on the card' });
567
- 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
+ }
568
615
  }
569
616
  if (t.name === UI_DESCRIBE_TOOL)
570
617
  uiCounts.describes++;
@@ -599,7 +646,10 @@ export async function runAgentTurn(config, input) {
599
646
  ...toolCtx,
600
647
  toolCallId: toolUseId,
601
648
  ...(uiSlot ? { uiSlot } : {}),
602
- ...(approved ? { approval: approved } : {}),
649
+ // Only this call carries its approval. A UI action gets no receipt: the browser checks its own grant.
650
+ ...(approved
651
+ ? { approval: isUI ? { approvalId: approved.approvalId, argsHash: approved.argsHash } : approved }
652
+ : {}),
603
653
  }),
604
654
  new Promise((_, reject) => {
605
655
  timer = setTimeout(() => reject(new Error(`Tool ${t.name} timed out after ${timeoutMs}ms`)), timeoutMs);
@@ -702,21 +752,50 @@ export async function runAgentTurn(config, input) {
702
752
  * stores it as a pending approval, shows the card, and tells the model only
703
753
  * that it is waiting. The model never sees a token.
704
754
  */
705
- const requestApproval = async (t, args, toolUseId, requirement, files) => {
755
+ const requestApproval = async (t, args, toolUseId, requirement, files, hold) => {
706
756
  // A file is shown by its name and size; the approval stays bound to its id.
707
- const preview = buildApprovalPreview(t, args, files);
708
- approvalHold = { approvalId: toolUseId, title: preview.title };
757
+ const built = buildApprovalPreview(t, args, files);
709
758
  const refuse = (why) => {
710
- approvalHold = null;
759
+ if (approvalHold === hold)
760
+ approvalHold = null;
711
761
  log('error', 'agent:tool', 'Approval could not be requested; the call was not run', { turnId, toolName: t.name, why });
712
762
  return JSON.stringify({
713
763
  success: false,
714
764
  notRun: true,
715
- error: `"${preview.title}" needs the user's approval, which could not be asked for (${why}). It was not run.`,
765
+ error: `"${built.title}" needs the user's approval, which could not be asked for (${why}). It was not run.`,
716
766
  });
717
767
  };
718
768
  if (!config.approvals)
719
769
  return refuse('this assistant has no approval store');
770
+ // The host's display copy, when it writes one: stored, shown and read back in place of the built one.
771
+ // The arguments stored and hashed are the call's own.
772
+ let preview = built;
773
+ const writePreview = config.approvalHooks?.preview;
774
+ if (writePreview) {
775
+ let written;
776
+ try {
777
+ written = readHostPreview(await writePreview(t, args, { ...approvalHookContext, built }));
778
+ }
779
+ catch (err) {
780
+ log('error', 'agent:tool', 'The host’s approval preview threw', { turnId, toolName: t.name, error: err instanceof Error ? err.message : String(err) });
781
+ return refuse('its preview could not be written');
782
+ }
783
+ if (!written.ok) {
784
+ log('error', 'agent:tool', 'The host’s approval preview is not one', { turnId, toolName: t.name, problem: written.error });
785
+ return refuse('its preview could not be written');
786
+ }
787
+ preview = written.preview;
788
+ hold.title = preview.title;
789
+ }
790
+ // The receipt's audience is fixed now, with the call: the API the tool calls. A UI action gets no receipt.
791
+ const isUI = t.kind === 'ui';
792
+ let audience;
793
+ if (!isUI && t.approvalAudience !== undefined) {
794
+ const origin = approvalReceiptAudience(t.approvalAudience);
795
+ if (!origin)
796
+ return refuse(`its approvalAudience "${t.approvalAudience}" is not an origin such as https://api.example.com`);
797
+ audience = origin;
798
+ }
720
799
  const expiresAt = Date.now() + requirement.ttlMs;
721
800
  try {
722
801
  const hash = await argsHash(args);
@@ -726,7 +805,11 @@ export async function runAgentTurn(config, input) {
726
805
  conversationId: input.conversationId,
727
806
  turnId,
728
807
  userId: input.userId,
808
+ ...(input.accountId ? { accountId: input.accountId } : {}),
729
809
  tool: t.name,
810
+ toolKind: isUI ? 'ui' : 'backend',
811
+ ...(!isUI && t.operationId ? { operationId: t.operationId } : {}),
812
+ ...(audience ? { audience } : {}),
730
813
  args,
731
814
  argsHash: hash,
732
815
  effect: requirement.effectName,
@@ -1012,6 +1095,7 @@ export async function runAgentTurn(config, input) {
1012
1095
  const executed = await executeCall(tool, call.args, call.approvalId, uiSlot, {
1013
1096
  approvalId: call.approvalId,
1014
1097
  argsHash: call.argsHash,
1098
+ ...(outcome.receipt ? { receipt: outcome.receipt } : {}),
1015
1099
  }).finally(() => uiSlot?.release());
1016
1100
  const { ran } = executed;
1017
1101
  // The result says it was approved by the person and run once (or not run), for this turn and every later one.
@@ -1059,10 +1143,19 @@ export async function runAgentTurn(config, input) {
1059
1143
  // text ends, not when its end is reported. The break is only streamed; what
1060
1144
  // the model said is recorded as it said it.
1061
1145
  const ROUND_BREAK = '\n\n';
1062
- /** Where, in the turn's text, a round that said something and then called tools ended. */
1063
- const roundBreaks = [];
1064
1146
  /** The turn's text the steps have reported so far. */
1065
1147
  let stepTextReported = 0;
1148
+ /** Rounds whose end has been reported and not yet sent: the stream has not reached it. */
1149
+ const roundEnds = [];
1150
+ /** The round whose text is being streamed (and is in the coalescing buffer): every round before it has been sent as ended. */
1151
+ let streamingStep = 0;
1152
+ /** Text that follows starts a new paragraph. */
1153
+ let paragraphPending = false;
1154
+ /**
1155
+ * Whether the turn ends after a round that called these tools: the
1156
+ * conditions `stopWhen` holds the model to, beside the step count.
1157
+ */
1158
+ const endsAfterRound = (toolNames) => approvalHold !== null || handedBackForTime || toolNames.some((name) => USER_INPUT_TOOLS.includes(name));
1066
1159
  // ─── Coalesce token deltas ─────────────────────────────────────────────────
1067
1160
  // Buffer for 50ms or 32 chars, whichever comes first, to avoid one HTTP POST
1068
1161
  // per token delta to the realtime server.
@@ -1082,10 +1175,46 @@ export async function runAgentTurn(config, input) {
1082
1175
  await config.emit.emit(socketRoom, AGENT_SOCKET_EVENTS.TOKEN, {
1083
1176
  turnId,
1084
1177
  text,
1178
+ step: streamingStep,
1085
1179
  timestamp: Date.now(),
1086
1180
  });
1087
1181
  }
1088
1182
  };
1183
+ /**
1184
+ * Sends the end of every round the text stream has delivered all of: what
1185
+ * is left of its text, then its end. Each emit is made before anything is
1186
+ * awaited, so the room and a host observing the turn get them in order.
1187
+ */
1188
+ const endReachedRounds = async () => {
1189
+ const sends = [];
1190
+ while (roundEnds.length > 0 && streamedText.length >= roundEnds[0].at) {
1191
+ const end = roundEnds.shift();
1192
+ sends.push(flushTokenBuffer());
1193
+ sends.push(config.emit.emit(socketRoom, AGENT_SOCKET_EVENTS.ROUND_END, {
1194
+ turnId,
1195
+ step: streamingStep,
1196
+ calledTools: end.calledTools,
1197
+ final: end.final,
1198
+ timestamp: Date.now(),
1199
+ }));
1200
+ streamingStep += 1;
1201
+ paragraphPending ||= end.paragraph;
1202
+ }
1203
+ await Promise.all(sends);
1204
+ };
1205
+ /**
1206
+ * Streams text the worker itself says, not the model (the reply when every
1207
+ * attempt was cut off at the output limit), as a round of its own: the
1208
+ * turn's last word.
1209
+ */
1210
+ const sayAsFinalRound = async (text) => {
1211
+ const reply = (streamedText ? ROUND_BREAK : '') + text;
1212
+ paragraphPending = false;
1213
+ streamedText += reply;
1214
+ tokenBuffer += reply;
1215
+ roundEnds.push({ at: streamedText.length, calledTools: false, final: true, paragraph: false });
1216
+ await endReachedRounds();
1217
+ };
1089
1218
  /**
1090
1219
  * A turn event that comes after what the model has said so far: the text
1091
1220
  * still held for coalescing is sent first. A tool's call and an approval's
@@ -1439,6 +1568,7 @@ export async function runAgentTurn(config, input) {
1439
1568
  ...Object.keys(aiTools).map((name) => describeStepTool(name)),
1440
1569
  ...actionIds.map((name) => ({ name, kind: 'ui' })),
1441
1570
  ],
1571
+ turn: turnInfo,
1442
1572
  });
1443
1573
  const { note, ...policy } = stepPolicy;
1444
1574
  // What it constrained, in the model's terms: an action is run through
@@ -1509,8 +1639,7 @@ export async function runAgentTurn(config, input) {
1509
1639
  },
1510
1640
  onStepEnd: async ({ text, toolCalls, usage: stepUsage, finishReason }) => {
1511
1641
  stepTextReported += text?.length ?? 0;
1512
- if (text && (toolCalls?.length ?? 0) > 0)
1513
- roundBreaks.push(stepTextReported);
1642
+ const calledTools = (toolCalls?.length ?? 0) > 0;
1514
1643
  recordedSteps.push({
1515
1644
  text: text ?? '',
1516
1645
  toolCalls: (toolCalls ?? []).map((tc) => ({ toolCallId: tc.toolCallId, toolName: tc.toolName, input: tc.input })),
@@ -1519,6 +1648,14 @@ export async function runAgentTurn(config, input) {
1519
1648
  cacheReadTokens: stepUsage?.inputTokenDetails?.cacheReadTokens ?? 0,
1520
1649
  cacheWriteTokens: stepUsage?.inputTokenDetails?.cacheWriteTokens ?? 0,
1521
1650
  });
1651
+ // A round that called tools is the last when the turn stops after it (an approval, a choice, the
1652
+ // hand-back for time) or it was the last step allowed. A round cut off at the output limit having
1653
+ // said and called nothing never is: it runs again, or the person is told (below).
1654
+ const cutOff = finishReason === 'length' && !text && !calledTools;
1655
+ const final = !cutOff && (!calledTools || recordedSteps.length >= maxRounds || endsAfterRound((toolCalls ?? []).map((tc) => tc.toolName)));
1656
+ roundEnds.push({ at: stepTextReported, calledTools, final, paragraph: !!text && calledTools });
1657
+ // Sent now when the stream has already delivered the round's text; else when it has.
1658
+ await endReachedRounds();
1522
1659
  log('info', 'agent:llm', 'Step completed', {
1523
1660
  turnId,
1524
1661
  turnClass,
@@ -1542,27 +1679,30 @@ export async function runAgentTurn(config, input) {
1542
1679
  for await (const textPart of result.textStream) {
1543
1680
  let rest = textPart;
1544
1681
  while (rest) {
1682
+ // The rounds whose text has all been delivered end before any of the next round's.
1683
+ await endReachedRounds();
1545
1684
  // Text after a round that ended in tool calls starts a new paragraph.
1546
- if (roundBreaks.length > 0 && streamedText.length >= roundBreaks[0]) {
1547
- roundBreaks.shift();
1685
+ if (paragraphPending) {
1686
+ paragraphPending = false;
1548
1687
  if (streamedText.length > 0)
1549
1688
  tokenBuffer += ROUND_BREAK;
1550
- continue;
1551
1689
  }
1552
- // A piece never runs past the next break, should one reach across it.
1553
- const upTo = roundBreaks.length > 0 ? roundBreaks[0] - streamedText.length : rest.length;
1690
+ // A piece never runs past the end of its round, should one reach across it.
1691
+ const upTo = roundEnds.length > 0 ? roundEnds[0].at - streamedText.length : rest.length;
1554
1692
  const piece = rest.slice(0, upTo);
1555
1693
  rest = rest.slice(piece.length);
1556
1694
  streamedText += piece;
1557
1695
  tokenBuffer += piece;
1558
1696
  }
1697
+ await endReachedRounds();
1559
1698
  if (tokenBuffer.length >= COALESCE_CHARS) {
1560
1699
  await flushTokenBuffer();
1561
1700
  }
1562
- else if (!flushTimer) {
1701
+ else if (!flushTimer && tokenBuffer.length > 0) {
1563
1702
  flushTimer = setTimeout(() => flushTokenBuffer(), COALESCE_MS);
1564
1703
  }
1565
1704
  }
1705
+ await endReachedRounds();
1566
1706
  await flushTokenBuffer();
1567
1707
  if (stopOf(abortController.signal))
1568
1708
  break;
@@ -1613,11 +1753,7 @@ export async function runAgentTurn(config, input) {
1613
1753
  }
1614
1754
  // Every attempt was cut off: the person hears so, rather than nothing.
1615
1755
  if (outputLimited && !stopOf(abortController.signal)) {
1616
- const reply = (streamedText ? ROUND_BREAK : '') + OUTPUT_LIMIT_REPLY;
1617
- roundBreaks.length = 0;
1618
- streamedText += reply;
1619
- tokenBuffer += reply;
1620
- await flushTokenBuffer();
1756
+ await sayAsFinalRound(OUTPUT_LIMIT_REPLY);
1621
1757
  }
1622
1758
  // ─── Stopped, or ending ────────────────────────────────────────────────────
1623
1759
  // Decided here with nothing awaited in between: either the stop was heard