@ouispec/agent-worker 0.15.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 (57) hide show
  1. package/README.md +51 -12
  2. package/dist/approvals/hooks.d.ts +82 -0
  3. package/dist/approvals/hooks.d.ts.map +1 -0
  4. package/dist/approvals/hooks.js +94 -0
  5. package/dist/approvals/hooks.js.map +1 -0
  6. package/dist/container/server.js +1 -1
  7. package/dist/container/server.js.map +1 -1
  8. package/dist/emit/filter.d.ts +23 -0
  9. package/dist/emit/filter.d.ts.map +1 -0
  10. package/dist/emit/filter.js +27 -0
  11. package/dist/emit/filter.js.map +1 -0
  12. package/dist/index.d.ts +9 -3
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +6 -2
  15. package/dist/index.js.map +1 -1
  16. package/dist/lambda/handler.d.ts.map +1 -1
  17. package/dist/lambda/handler.js +4 -1
  18. package/dist/lambda/handler.js.map +1 -1
  19. package/dist/live-call/handler.d.ts +34 -2
  20. package/dist/live-call/handler.d.ts.map +1 -1
  21. package/dist/live-call/handler.js +91 -13
  22. package/dist/live-call/handler.js.map +1 -1
  23. package/dist/live-call/protocol.d.ts +29 -3
  24. package/dist/live-call/protocol.d.ts.map +1 -1
  25. package/dist/live-call/protocol.js +32 -2
  26. package/dist/live-call/protocol.js.map +1 -1
  27. package/dist/orchestrator.d.ts +5 -0
  28. package/dist/orchestrator.d.ts.map +1 -1
  29. package/dist/orchestrator.js +147 -28
  30. package/dist/orchestrator.js.map +1 -1
  31. package/dist/prompt/builder.d.ts +1 -1
  32. package/dist/prompt/builder.d.ts.map +1 -1
  33. package/dist/prompt/builder.js +8 -2
  34. package/dist/prompt/builder.js.map +1 -1
  35. package/dist/prompt/rules/base.js +4 -4
  36. package/dist/prompt/spoken-reply.d.ts +1 -1
  37. package/dist/prompt/spoken-reply.d.ts.map +1 -1
  38. package/dist/prompt/spoken-reply.js +14 -2
  39. package/dist/prompt/spoken-reply.js.map +1 -1
  40. package/dist/prompt/types.d.ts +12 -0
  41. package/dist/prompt/types.d.ts.map +1 -1
  42. package/dist/runtime/turn-info.d.ts +28 -0
  43. package/dist/runtime/turn-info.d.ts.map +1 -0
  44. package/dist/runtime/turn-info.js +23 -0
  45. package/dist/runtime/turn-info.js.map +1 -0
  46. package/dist/runtime/turn-runner.d.ts +15 -2
  47. package/dist/runtime/turn-runner.d.ts.map +1 -1
  48. package/dist/runtime/turn-runner.js +65 -10
  49. package/dist/runtime/turn-runner.js.map +1 -1
  50. package/dist/runtime/types.d.ts +45 -4
  51. package/dist/runtime/types.d.ts.map +1 -1
  52. package/dist/turn-policy.d.ts +8 -1
  53. package/dist/turn-policy.d.ts.map +1 -1
  54. package/dist/turn-policy.js.map +1 -1
  55. package/dist/types.d.ts +12 -0
  56. package/dist/types.d.ts.map +1 -1
  57. package/package.json +5 -5
@@ -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++;
@@ -702,21 +749,41 @@ export async function runAgentTurn(config, input) {
702
749
  * stores it as a pending approval, shows the card, and tells the model only
703
750
  * that it is waiting. The model never sees a token.
704
751
  */
705
- const requestApproval = async (t, args, toolUseId, requirement, files) => {
752
+ const requestApproval = async (t, args, toolUseId, requirement, files, hold) => {
706
753
  // 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 };
754
+ const built = buildApprovalPreview(t, args, files);
709
755
  const refuse = (why) => {
710
- approvalHold = null;
756
+ if (approvalHold === hold)
757
+ approvalHold = null;
711
758
  log('error', 'agent:tool', 'Approval could not be requested; the call was not run', { turnId, toolName: t.name, why });
712
759
  return JSON.stringify({
713
760
  success: false,
714
761
  notRun: true,
715
- 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.`,
716
763
  });
717
764
  };
718
765
  if (!config.approvals)
719
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
+ }
720
787
  const expiresAt = Date.now() + requirement.ttlMs;
721
788
  try {
722
789
  const hash = await argsHash(args);
@@ -1059,10 +1126,19 @@ export async function runAgentTurn(config, input) {
1059
1126
  // text ends, not when its end is reported. The break is only streamed; what
1060
1127
  // the model said is recorded as it said it.
1061
1128
  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
1129
  /** The turn's text the steps have reported so far. */
1065
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));
1066
1142
  // ─── Coalesce token deltas ─────────────────────────────────────────────────
1067
1143
  // Buffer for 50ms or 32 chars, whichever comes first, to avoid one HTTP POST
1068
1144
  // per token delta to the realtime server.
@@ -1082,10 +1158,46 @@ export async function runAgentTurn(config, input) {
1082
1158
  await config.emit.emit(socketRoom, AGENT_SOCKET_EVENTS.TOKEN, {
1083
1159
  turnId,
1084
1160
  text,
1161
+ step: streamingStep,
1085
1162
  timestamp: Date.now(),
1086
1163
  });
1087
1164
  }
1088
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
+ };
1089
1201
  /**
1090
1202
  * A turn event that comes after what the model has said so far: the text
1091
1203
  * still held for coalescing is sent first. A tool's call and an approval's
@@ -1439,6 +1551,7 @@ export async function runAgentTurn(config, input) {
1439
1551
  ...Object.keys(aiTools).map((name) => describeStepTool(name)),
1440
1552
  ...actionIds.map((name) => ({ name, kind: 'ui' })),
1441
1553
  ],
1554
+ turn: turnInfo,
1442
1555
  });
1443
1556
  const { note, ...policy } = stepPolicy;
1444
1557
  // What it constrained, in the model's terms: an action is run through
@@ -1509,8 +1622,7 @@ export async function runAgentTurn(config, input) {
1509
1622
  },
1510
1623
  onStepEnd: async ({ text, toolCalls, usage: stepUsage, finishReason }) => {
1511
1624
  stepTextReported += text?.length ?? 0;
1512
- if (text && (toolCalls?.length ?? 0) > 0)
1513
- roundBreaks.push(stepTextReported);
1625
+ const calledTools = (toolCalls?.length ?? 0) > 0;
1514
1626
  recordedSteps.push({
1515
1627
  text: text ?? '',
1516
1628
  toolCalls: (toolCalls ?? []).map((tc) => ({ toolCallId: tc.toolCallId, toolName: tc.toolName, input: tc.input })),
@@ -1519,6 +1631,14 @@ export async function runAgentTurn(config, input) {
1519
1631
  cacheReadTokens: stepUsage?.inputTokenDetails?.cacheReadTokens ?? 0,
1520
1632
  cacheWriteTokens: stepUsage?.inputTokenDetails?.cacheWriteTokens ?? 0,
1521
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();
1522
1642
  log('info', 'agent:llm', 'Step completed', {
1523
1643
  turnId,
1524
1644
  turnClass,
@@ -1542,27 +1662,30 @@ export async function runAgentTurn(config, input) {
1542
1662
  for await (const textPart of result.textStream) {
1543
1663
  let rest = textPart;
1544
1664
  while (rest) {
1665
+ // The rounds whose text has all been delivered end before any of the next round's.
1666
+ await endReachedRounds();
1545
1667
  // 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();
1668
+ if (paragraphPending) {
1669
+ paragraphPending = false;
1548
1670
  if (streamedText.length > 0)
1549
1671
  tokenBuffer += ROUND_BREAK;
1550
- continue;
1551
1672
  }
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;
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;
1554
1675
  const piece = rest.slice(0, upTo);
1555
1676
  rest = rest.slice(piece.length);
1556
1677
  streamedText += piece;
1557
1678
  tokenBuffer += piece;
1558
1679
  }
1680
+ await endReachedRounds();
1559
1681
  if (tokenBuffer.length >= COALESCE_CHARS) {
1560
1682
  await flushTokenBuffer();
1561
1683
  }
1562
- else if (!flushTimer) {
1684
+ else if (!flushTimer && tokenBuffer.length > 0) {
1563
1685
  flushTimer = setTimeout(() => flushTokenBuffer(), COALESCE_MS);
1564
1686
  }
1565
1687
  }
1688
+ await endReachedRounds();
1566
1689
  await flushTokenBuffer();
1567
1690
  if (stopOf(abortController.signal))
1568
1691
  break;
@@ -1613,11 +1736,7 @@ export async function runAgentTurn(config, input) {
1613
1736
  }
1614
1737
  // Every attempt was cut off: the person hears so, rather than nothing.
1615
1738
  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();
1739
+ await sayAsFinalRound(OUTPUT_LIMIT_REPLY);
1621
1740
  }
1622
1741
  // ─── Stopped, or ending ────────────────────────────────────────────────────
1623
1742
  // Decided here with nothing awaited in between: either the stop was heard