@ouispec/agent-worker 0.16.0 → 0.18.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 (82) hide show
  1. package/README.md +42 -2
  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 +2 -1
  9. package/dist/approvals/continuation.js.map +1 -1
  10. package/dist/approvals/requirement.d.ts +29 -1
  11. package/dist/approvals/requirement.d.ts.map +1 -1
  12. package/dist/approvals/requirement.js +29 -1
  13. package/dist/approvals/requirement.js.map +1 -1
  14. package/dist/conversations/client.d.ts +44 -0
  15. package/dist/conversations/client.d.ts.map +1 -0
  16. package/dist/conversations/client.js +49 -0
  17. package/dist/conversations/client.js.map +1 -0
  18. package/dist/history.d.ts +10 -1
  19. package/dist/history.d.ts.map +1 -1
  20. package/dist/history.js +20 -6
  21. package/dist/history.js.map +1 -1
  22. package/dist/index.d.ts +8 -5
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +7 -3
  25. package/dist/index.js.map +1 -1
  26. package/dist/live-call/handler.d.ts +12 -2
  27. package/dist/live-call/handler.d.ts.map +1 -1
  28. package/dist/live-call/handler.js +31 -3
  29. package/dist/live-call/handler.js.map +1 -1
  30. package/dist/live-call/protocol.d.ts +5 -2
  31. package/dist/live-call/protocol.d.ts.map +1 -1
  32. package/dist/live-call/protocol.js.map +1 -1
  33. package/dist/openapi/executor.d.ts +0 -7
  34. package/dist/openapi/executor.d.ts.map +1 -1
  35. package/dist/openapi/executor.js +17 -0
  36. package/dist/openapi/executor.js.map +1 -1
  37. package/dist/openapi/loader.d.ts +2 -1
  38. package/dist/openapi/loader.d.ts.map +1 -1
  39. package/dist/openapi/loader.js +8 -1
  40. package/dist/openapi/loader.js.map +1 -1
  41. package/dist/orchestrator.d.ts.map +1 -1
  42. package/dist/orchestrator.js +103 -12
  43. package/dist/orchestrator.js.map +1 -1
  44. package/dist/runtime/turn-info.d.ts +22 -2
  45. package/dist/runtime/turn-info.d.ts.map +1 -1
  46. package/dist/runtime/turn-info.js +6 -11
  47. package/dist/runtime/turn-info.js.map +1 -1
  48. package/dist/runtime/turn-runner.d.ts +15 -2
  49. package/dist/runtime/turn-runner.d.ts.map +1 -1
  50. package/dist/runtime/turn-runner.js +38 -8
  51. package/dist/runtime/turn-runner.js.map +1 -1
  52. package/dist/runtime/types.d.ts +16 -2
  53. package/dist/runtime/types.d.ts.map +1 -1
  54. package/dist/stop/partial.d.ts +3 -1
  55. package/dist/stop/partial.d.ts.map +1 -1
  56. package/dist/stop/partial.js +10 -5
  57. package/dist/stop/partial.js.map +1 -1
  58. package/dist/stop/turn-stop.d.ts +9 -4
  59. package/dist/stop/turn-stop.d.ts.map +1 -1
  60. package/dist/stop/turn-stop.js +14 -9
  61. package/dist/stop/turn-stop.js.map +1 -1
  62. package/dist/testing/cassette.d.ts +44 -0
  63. package/dist/testing/cassette.d.ts.map +1 -0
  64. package/dist/testing/cassette.js +72 -0
  65. package/dist/testing/cassette.js.map +1 -0
  66. package/dist/testing/index.d.ts +7 -1
  67. package/dist/testing/index.d.ts.map +1 -1
  68. package/dist/testing/index.js +5 -1
  69. package/dist/testing/index.js.map +1 -1
  70. package/dist/testing/scripted.d.ts +64 -0
  71. package/dist/testing/scripted.d.ts.map +1 -0
  72. package/dist/testing/scripted.js +89 -0
  73. package/dist/testing/scripted.js.map +1 -0
  74. package/dist/tools/types.d.ts +31 -4
  75. package/dist/tools/types.d.ts.map +1 -1
  76. package/dist/tools/types.js.map +1 -1
  77. package/dist/types.d.ts +21 -1
  78. package/dist/types.d.ts.map +1 -1
  79. package/dist/ui/ui-tools.d.ts.map +1 -1
  80. package/dist/ui/ui-tools.js +2 -1
  81. package/dist/ui/ui-tools.js.map +1 -1
  82. 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, staffMessageNote, takeoverNote, 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';
@@ -46,7 +46,7 @@ import { describeSchema } from './ui/outline.js';
46
46
  import { createUISequence } from './ui/ui-sequence.js';
47
47
  import { createTurnLedger } from './turn-ledger.js';
48
48
  import { DEFAULT_PAGE_STATE_CHARS, observationSchemas, observationsText } from './ui/observations.js';
49
- import { approvalRequirement, APPROVAL_TOOL_NOTE } from './approvals/requirement.js';
49
+ import { approvalRequirement, approvalToolNote, VOICE_APPROVAL_CHANNELS } from './approvals/requirement.js';
50
50
  import { buildApprovalPreview, declaredTitle } from './approvals/preview.js';
51
51
  import { readHostPreview, readValidation } from './approvals/hooks.js';
52
52
  import { turnInfoOf } from './runtime/turn-info.js';
@@ -115,7 +115,15 @@ export async function runAgentTurn(config, input) {
115
115
  }
116
116
  const { turnId, socketRoom } = input;
117
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);
118
+ const turnInfo = turnInfoOf(input, input.channel, input.approvalChannel);
119
+ // Where the person is: in a UI an approval is the card; on a conversation channel, the readback.
120
+ const approvalChannel = input.approvalChannel ?? 'ui';
121
+ /**
122
+ * How a call's approval is given: a UI action's always by its card, on every
123
+ * channel, since the person's page runs it only on its own grant from that
124
+ * card; any other tool's in the turn's channel.
125
+ */
126
+ const confirmedBy = (t) => (t.kind === 'ui' ? 'ui' : approvalChannel);
119
127
  log('info', 'agent:turn', 'Turn started', {
120
128
  turnId,
121
129
  conversationId: input.conversationId,
@@ -189,7 +197,7 @@ export async function runAgentTurn(config, input) {
189
197
  const turnPolicy = config.turnPolicy ?? defaultTurnPolicy;
190
198
  const historyForClassify = input.history?.map((m) => ({
191
199
  role: m.role,
192
- content: 'content' in m ? (m.content ?? '') : '',
200
+ content: m.role === 'staff' ? staffEntryText(m) : 'content' in m ? (m.content ?? '') : '',
193
201
  })) ?? [];
194
202
  const turnClass = turnPolicy.classifyTurn(input.content, historyForClassify, turnInfo);
195
203
  // Let the policy perform side effects (e.g. deterministic navigation emit)
@@ -222,7 +230,8 @@ export async function runAgentTurn(config, input) {
222
230
  // aborts the turn's signal with a typed reason, which is what everything that
223
231
  // waits (the model stream, a UI action's answer, a job's outcome) already
224
232
  // honours. What the turn had produced is then stored and announced (below).
225
- const stopWatch = input.stopWatch ?? watchTurnStop(config.stops, turnId, input.userId);
233
+ // It hears a person on the staff taking the conversation over, too.
234
+ const stopWatch = input.stopWatch ?? watchTurnStop(config.stops, turnId, input.userId, input.conversationId);
226
235
  /** Set when the turn begins its own end: a stop that lands after is not one. */
227
236
  let ending = false;
228
237
  /** Kept back from a stopped turn's grace for storing and announcing it. */
@@ -595,7 +604,12 @@ export async function runAgentTurn(config, input) {
595
604
  if ((requirement.required || policyRequiresApproval) && !approved) {
596
605
  // Claimed before anything is awaited (above).
597
606
  let prepared;
598
- const hold = { approvalId: toolUseId, title: declaredTitle(t).title, preparing: new Promise((resolve) => (prepared = resolve)) };
607
+ const hold = {
608
+ approvalId: toolUseId,
609
+ title: declaredTitle(t).title,
610
+ readback: null,
611
+ preparing: new Promise((resolve) => (prepared = resolve)),
612
+ };
599
613
  approvalHold = hold;
600
614
  try {
601
615
  const checked = await validateForApproval(t, args);
@@ -605,7 +619,11 @@ export async function runAgentTurn(config, input) {
605
619
  log('info', 'agent:tool', 'The host refused the call before it was asked for', { turnId, toolName: t.name });
606
620
  return refused({ error: checked.error, notRun: true, refusedBeforeApproval: true }, args);
607
621
  }
608
- ledger.record({ tool: t.name, ok: false, error: 'Not run: it waits for the user’s approval on the card' });
622
+ ledger.record({
623
+ tool: t.name,
624
+ ok: false,
625
+ error: confirmedBy(t) === 'ui' ? 'Not run: it waits for the user’s approval on the card' : 'Not run: it waits for the customer to confirm its readback',
626
+ });
609
627
  return { text: await requestApproval(t, args, toolUseId, requirement, callFiles, hold), ran: false };
610
628
  }
611
629
  finally {
@@ -646,7 +664,10 @@ export async function runAgentTurn(config, input) {
646
664
  ...toolCtx,
647
665
  toolCallId: toolUseId,
648
666
  ...(uiSlot ? { uiSlot } : {}),
649
- ...(approved ? { approval: approved } : {}),
667
+ // Only this call carries its approval. A UI action gets no receipt: the browser checks its own grant.
668
+ ...(approved
669
+ ? { approval: isUI ? { approvalId: approved.approvalId, argsHash: approved.argsHash } : approved }
670
+ : {}),
650
671
  }),
651
672
  new Promise((_, reject) => {
652
673
  timer = setTimeout(() => reject(new Error(`Tool ${t.name} timed out after ${timeoutMs}ms`)), timeoutMs);
@@ -784,6 +805,19 @@ export async function runAgentTurn(config, input) {
784
805
  preview = written.preview;
785
806
  hold.title = preview.title;
786
807
  }
808
+ // On a conversation channel the readback is the confirmation: a voice says the host's spoken words when it wrote them.
809
+ const by = confirmedBy(t);
810
+ if (by !== 'ui')
811
+ hold.readback = (VOICE_APPROVAL_CHANNELS.has(by) ? (preview.spokenReadback ?? preview.readback) : preview.readback).trim() || null;
812
+ // The receipt's audience is fixed now, with the call: the API the tool calls. A UI action gets no receipt.
813
+ const isUI = t.kind === 'ui';
814
+ let audience;
815
+ if (!isUI && t.approvalAudience !== undefined) {
816
+ const origin = approvalReceiptAudience(t.approvalAudience);
817
+ if (!origin)
818
+ return refuse(`its approvalAudience "${t.approvalAudience}" is not an origin such as https://api.example.com`);
819
+ audience = origin;
820
+ }
787
821
  const expiresAt = Date.now() + requirement.ttlMs;
788
822
  try {
789
823
  const hash = await argsHash(args);
@@ -793,7 +827,11 @@ export async function runAgentTurn(config, input) {
793
827
  conversationId: input.conversationId,
794
828
  turnId,
795
829
  userId: input.userId,
830
+ ...(input.accountId ? { accountId: input.accountId } : {}),
796
831
  tool: t.name,
832
+ toolKind: isUI ? 'ui' : 'backend',
833
+ ...(!isUI && t.operationId ? { operationId: t.operationId } : {}),
834
+ ...(audience ? { audience } : {}),
797
835
  args,
798
836
  argsHash: hash,
799
837
  effect: requirement.effectName,
@@ -828,8 +866,16 @@ export async function runAgentTurn(config, input) {
828
866
  success: false,
829
867
  awaitingApproval: true,
830
868
  approvalId: toolUseId,
831
- message: `Waiting for the user to approve "${preview.title}" on the approval card. It has not run. ` +
832
- 'The turn ends here: it runs only if they approve it there, and the next turn tells you the outcome.',
869
+ message: hold.readback === null && approvalChannel === 'ui'
870
+ ? `Waiting for the user to approve "${preview.title}" on the approval card. It has not run. ` +
871
+ 'The turn ends here: it runs only if they approve it there, and the next turn tells you the outcome.'
872
+ : hold.readback === null
873
+ ? `Waiting for the user to approve "${preview.title}" on the approval card on their screen. It has not run. ` +
874
+ 'The turn ends here: it runs only if they approve it there, and the next turn tells you the outcome. A yes they say or ' +
875
+ 'send in this conversation does not approve it, so tell them the card is on their screen.'
876
+ : `Waiting for the customer to confirm "${preview.title}". They are sent this readback, word for word, after your reply: ` +
877
+ `"${hold.readback}" It has not run. The turn ends here: it runs only if they confirm it in their next message, ` +
878
+ 'and the next turn tells you the outcome. Do not repeat the readback.',
833
879
  });
834
880
  };
835
881
  // Convert a RegisteredTool to an AI SDK tool. Our tools have runtime-defined
@@ -856,7 +902,7 @@ export async function runAgentTurn(config, input) {
856
902
  };
857
903
  // A call that needs approval says so in its description, in place of any
858
904
  // "confirm first" instruction: the card is the confirmation.
859
- const description = approvalRequirement(t).required ? `${t.description}\n\n${APPROVAL_TOOL_NOTE}` : t.description;
905
+ const description = approvalRequirement(t).required ? `${t.description}\n\n${approvalToolNote(approvalChannel, t.kind)}` : t.description;
860
906
  return dynamicTool({
861
907
  description,
862
908
  inputSchema: jsonSchema(rawSchema),
@@ -1079,6 +1125,7 @@ export async function runAgentTurn(config, input) {
1079
1125
  const executed = await executeCall(tool, call.args, call.approvalId, uiSlot, {
1080
1126
  approvalId: call.approvalId,
1081
1127
  argsHash: call.argsHash,
1128
+ ...(outcome.receipt ? { receipt: outcome.receipt } : {}),
1082
1129
  }).finally(() => uiSlot?.release());
1083
1130
  const { ran } = executed;
1084
1131
  // The result says it was approved by the person and run once (or not run), for this turn and every later one.
@@ -1825,6 +1872,17 @@ export async function runAgentTurn(config, input) {
1825
1872
  ...(continued?.persisted ?? []),
1826
1873
  ...convertResponseToTurnMessages({ steps: outputLimited ? [...steps, { text: OUTPUT_LIMIT_REPLY, toolCalls: [] }] : steps }, executedToolResults),
1827
1874
  ];
1875
+ // On a conversation channel there is no card: the readback is what the customer is sent, verbatim, as the turn's
1876
+ // last words. Sent and stored like the agent's own text, so every channel's adapter delivers it and the next turn
1877
+ // reads it; written by the declaration (or the host's preview), never by the model. Its pieces say they are the
1878
+ // readback, so a consumer that delivers it its own way (the live-call relay's `readback` event) does not say it twice.
1879
+ const readback = approvalHold?.readback ?? null;
1880
+ if (readback) {
1881
+ const text = `${streamedText.trim() ? '\n\n' : ''}${readback}`;
1882
+ streamedText += text;
1883
+ await config.emit.emit(socketRoom, AGENT_SOCKET_EVENTS.TOKEN, { turnId, text, readback: true, timestamp: Date.now() });
1884
+ newMessages.push({ role: 'assistant', content: readback });
1885
+ }
1828
1886
  // The host stores the turn before the client hears it is complete: a message sent the moment
1829
1887
  // it completes must be answered from a history that holds this turn.
1830
1888
  if (config.beforeTurnComplete) {
@@ -1911,7 +1969,9 @@ export async function runAgentTurn(config, input) {
1911
1969
  const held = approvalHold;
1912
1970
  if (held && config.approvals?.withdraw) {
1913
1971
  try {
1914
- await config.approvals.withdraw(held.approvalId, { userId: input.userId, conversationId: input.conversationId }, 'stopped');
1972
+ // Taken over, the person now answering did not ask for it.
1973
+ const why = stopped.reason === 'taken_over' ? 'taken_over' : 'stopped';
1974
+ await config.approvals.withdraw(held.approvalId, { userId: input.userId, conversationId: input.conversationId }, why);
1915
1975
  }
1916
1976
  catch (err) {
1917
1977
  log('warn', 'agent:tool', 'Could not withdraw the stopped turn’s approval; it lasts until its time limit', {
@@ -2047,6 +2107,8 @@ function convertHistoryToCoreMessages(history, currentContent,
2047
2107
  /** The history's copy of the turn's own message, whose files the turn gives with their lines. */
2048
2108
  turnMessageAt = null) {
2049
2109
  const messages = [];
2110
+ /** The messages made from a person's entries, which a following entry joins. */
2111
+ const staffMessages = new Set();
2050
2112
  // First pass: collect all tool_call_ids that have results in history
2051
2113
  // AND all tool call IDs from assistant messages (to validate results)
2052
2114
  const answeredToolCallIds = new Set();
@@ -2087,6 +2149,23 @@ turnMessageAt = null) {
2087
2149
  });
2088
2150
  for (let idx = 0; idx < history.length; idx++) {
2089
2151
  const msg = history[idx];
2152
+ if (msg.role === 'staff') {
2153
+ // A person on the staff: the business's side of the conversation, under their name, in the
2154
+ // assistant's role, where no customer's text ever reaches. A run of entries is one message.
2155
+ const text = staffEntryText(msg);
2156
+ if (!text)
2157
+ continue;
2158
+ const previous = messages[messages.length - 1];
2159
+ if (previous && staffMessages.has(previous) && typeof previous.content === 'string') {
2160
+ previous.content = `${previous.content}\n\n${text}`;
2161
+ }
2162
+ else {
2163
+ const entry = { role: 'assistant', content: text };
2164
+ staffMessages.add(entry);
2165
+ messages.push(entry);
2166
+ }
2167
+ continue;
2168
+ }
2090
2169
  if (msg.role === 'user') {
2091
2170
  // A message's files are in history as their reference lines, never their content.
2092
2171
  messages.push({ role: 'user', content: idx === turnMessageAt ? msg.content : withReferenceLines(msg.content, msg.attachments ?? undefined) });
@@ -2260,4 +2339,16 @@ function convertResponseToTurnMessages(result, executedToolResults) {
2260
2339
  }
2261
2340
  return turnMessages;
2262
2341
  }
2342
+ /**
2343
+ * What the model reads for one of a person's entries: their
2344
+ * message under the line that says whose it is, or the line that says they
2345
+ * took the conversation over or handed it back. Empty for an entry with
2346
+ * neither, which says nothing.
2347
+ */
2348
+ function staffEntryText(entry) {
2349
+ if (entry.takeover)
2350
+ return takeoverNote(entry.takeover, entry.speaker);
2351
+ const said = entry.content?.trim() ? entry.content : null;
2352
+ return said ? `${staffMessageNote(entry.speaker)}\n${said}` : '';
2353
+ }
2263
2354
  //# sourceMappingURL=orchestrator.js.map