@voicethere/agent 0.25.0 → 0.27.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 (195) hide show
  1. package/README.md +49 -0
  2. package/dist/agent.js +78 -1
  3. package/dist/cli.d.ts +1 -0
  4. package/dist/cli.d.ts.map +1 -1
  5. package/dist/cli.js +11 -0
  6. package/dist/cli.js.map +1 -1
  7. package/dist/flow/classify.d.ts +12 -0
  8. package/dist/flow/classify.d.ts.map +1 -0
  9. package/dist/flow/classify.js +37 -0
  10. package/dist/flow/classify.js.map +1 -0
  11. package/dist/flow/cli-flow.d.ts +19 -0
  12. package/dist/flow/cli-flow.d.ts.map +1 -0
  13. package/dist/flow/cli-flow.js +566 -0
  14. package/dist/flow/cli-flow.js.map +1 -0
  15. package/dist/flow/core/compile.d.ts +131 -0
  16. package/dist/flow/core/compile.d.ts.map +1 -0
  17. package/dist/flow/core/compile.js +197 -0
  18. package/dist/flow/core/compile.js.map +1 -0
  19. package/dist/flow/core/conditions.d.ts +5 -0
  20. package/dist/flow/core/conditions.d.ts.map +1 -0
  21. package/dist/flow/core/conditions.js +70 -0
  22. package/dist/flow/core/conditions.js.map +1 -0
  23. package/dist/flow/core/effects.d.ts +105 -0
  24. package/dist/flow/core/effects.d.ts.map +1 -0
  25. package/dist/flow/core/effects.js +2 -0
  26. package/dist/flow/core/effects.js.map +1 -0
  27. package/dist/flow/core/generate-mock.d.ts +16 -0
  28. package/dist/flow/core/generate-mock.d.ts.map +1 -0
  29. package/dist/flow/core/generate-mock.js +206 -0
  30. package/dist/flow/core/generate-mock.js.map +1 -0
  31. package/dist/flow/core/host.d.ts +9 -0
  32. package/dist/flow/core/host.d.ts.map +1 -0
  33. package/dist/flow/core/host.js +99 -0
  34. package/dist/flow/core/host.js.map +1 -0
  35. package/dist/flow/core/index.d.ts +17 -0
  36. package/dist/flow/core/index.d.ts.map +1 -0
  37. package/dist/flow/core/index.js +17 -0
  38. package/dist/flow/core/index.js.map +1 -0
  39. package/dist/flow/core/interpreter.d.ts +69 -0
  40. package/dist/flow/core/interpreter.d.ts.map +1 -0
  41. package/dist/flow/core/interpreter.js +738 -0
  42. package/dist/flow/core/interpreter.js.map +1 -0
  43. package/dist/flow/core/json-pointer.d.ts +6 -0
  44. package/dist/flow/core/json-pointer.d.ts.map +1 -0
  45. package/dist/flow/core/json-pointer.js +28 -0
  46. package/dist/flow/core/json-pointer.js.map +1 -0
  47. package/dist/flow/core/migrate.d.ts +16 -0
  48. package/dist/flow/core/migrate.d.ts.map +1 -0
  49. package/dist/flow/core/migrate.js +29 -0
  50. package/dist/flow/core/migrate.js.map +1 -0
  51. package/dist/flow/core/mock-effects.d.ts +14 -0
  52. package/dist/flow/core/mock-effects.d.ts.map +1 -0
  53. package/dist/flow/core/mock-effects.js +90 -0
  54. package/dist/flow/core/mock-effects.js.map +1 -0
  55. package/dist/flow/core/mocks.d.ts +55 -0
  56. package/dist/flow/core/mocks.d.ts.map +1 -0
  57. package/dist/flow/core/mocks.js +73 -0
  58. package/dist/flow/core/mocks.js.map +1 -0
  59. package/dist/flow/core/route.d.ts +29 -0
  60. package/dist/flow/core/route.d.ts.map +1 -0
  61. package/dist/flow/core/route.js +61 -0
  62. package/dist/flow/core/route.js.map +1 -0
  63. package/dist/flow/core/schema.d.ts +19 -0
  64. package/dist/flow/core/schema.d.ts.map +1 -0
  65. package/dist/flow/core/schema.js +317 -0
  66. package/dist/flow/core/schema.js.map +1 -0
  67. package/dist/flow/core/template.d.ts +16 -0
  68. package/dist/flow/core/template.d.ts.map +1 -0
  69. package/dist/flow/core/template.js +65 -0
  70. package/dist/flow/core/template.js.map +1 -0
  71. package/dist/flow/core/trace.d.ts +26 -0
  72. package/dist/flow/core/trace.d.ts.map +1 -0
  73. package/dist/flow/core/trace.js +2 -0
  74. package/dist/flow/core/trace.js.map +1 -0
  75. package/dist/flow/core/types.d.ts +159 -0
  76. package/dist/flow/core/types.d.ts.map +1 -0
  77. package/dist/flow/core/types.js +2 -0
  78. package/dist/flow/core/types.js.map +1 -0
  79. package/dist/flow/core/validate.d.ts +3 -0
  80. package/dist/flow/core/validate.d.ts.map +1 -0
  81. package/dist/flow/core/validate.js +550 -0
  82. package/dist/flow/core/validate.js.map +1 -0
  83. package/dist/flow/create-flow-agent.d.ts +36 -0
  84. package/dist/flow/create-flow-agent.d.ts.map +1 -0
  85. package/dist/flow/create-flow-agent.js +175 -0
  86. package/dist/flow/create-flow-agent.js.map +1 -0
  87. package/dist/flow/effects-node.d.ts +21 -0
  88. package/dist/flow/effects-node.d.ts.map +1 -0
  89. package/dist/flow/effects-node.js +189 -0
  90. package/dist/flow/effects-node.js.map +1 -0
  91. package/dist/flow/index.d.ts +12 -0
  92. package/dist/flow/index.d.ts.map +1 -0
  93. package/dist/flow/index.js +7 -0
  94. package/dist/flow/index.js.map +1 -0
  95. package/dist/flow/llm-node.d.ts +24 -0
  96. package/dist/flow/llm-node.d.ts.map +1 -0
  97. package/dist/flow/llm-node.js +251 -0
  98. package/dist/flow/llm-node.js.map +1 -0
  99. package/dist/flow/record.d.ts +22 -0
  100. package/dist/flow/record.d.ts.map +1 -0
  101. package/dist/flow/record.js +126 -0
  102. package/dist/flow/record.js.map +1 -0
  103. package/dist/index.d.ts +2 -2
  104. package/dist/index.d.ts.map +1 -1
  105. package/dist/index.js +1 -1
  106. package/dist/index.js.map +1 -1
  107. package/dist/llm/agent/build-tool-registry.d.ts +26 -0
  108. package/dist/llm/agent/build-tool-registry.d.ts.map +1 -0
  109. package/dist/llm/agent/build-tool-registry.js +106 -0
  110. package/dist/llm/agent/build-tool-registry.js.map +1 -0
  111. package/dist/llm/agent/create-llm-agent.d.ts +5 -0
  112. package/dist/llm/agent/create-llm-agent.d.ts.map +1 -1
  113. package/dist/llm/agent/create-llm-agent.js +38 -103
  114. package/dist/llm/agent/create-llm-agent.js.map +1 -1
  115. package/dist/llm/agent/define-tool.d.ts +2 -0
  116. package/dist/llm/agent/define-tool.d.ts.map +1 -1
  117. package/dist/llm/agent/define-tool.js +1 -0
  118. package/dist/llm/agent/define-tool.js.map +1 -1
  119. package/dist/llm/agent/redact.d.ts.map +1 -1
  120. package/dist/llm/agent/redact.js +1 -0
  121. package/dist/llm/agent/redact.js.map +1 -1
  122. package/dist/llm/anthropic-provider.d.ts.map +1 -1
  123. package/dist/llm/anthropic-provider.js +10 -0
  124. package/dist/llm/anthropic-provider.js.map +1 -1
  125. package/dist/llm/catalog.d.ts +4 -0
  126. package/dist/llm/catalog.d.ts.map +1 -1
  127. package/dist/llm/catalog.js +7 -0
  128. package/dist/llm/catalog.js.map +1 -1
  129. package/dist/llm/end-user/end-user-tools.d.ts +10 -0
  130. package/dist/llm/end-user/end-user-tools.d.ts.map +1 -0
  131. package/dist/llm/end-user/end-user-tools.js +50 -0
  132. package/dist/llm/end-user/end-user-tools.js.map +1 -0
  133. package/dist/llm/gemini-provider.d.ts.map +1 -1
  134. package/dist/llm/gemini-provider.js +12 -0
  135. package/dist/llm/gemini-provider.js.map +1 -1
  136. package/dist/llm/index.d.ts +3 -0
  137. package/dist/llm/index.d.ts.map +1 -1
  138. package/dist/llm/index.js +2 -0
  139. package/dist/llm/index.js.map +1 -1
  140. package/dist/llm/mcp/tool-registry.d.ts +10 -1
  141. package/dist/llm/mcp/tool-registry.d.ts.map +1 -1
  142. package/dist/llm/mcp/tool-registry.js +10 -3
  143. package/dist/llm/mcp/tool-registry.js.map +1 -1
  144. package/dist/llm/openai-provider.d.ts.map +1 -1
  145. package/dist/llm/openai-provider.js +10 -0
  146. package/dist/llm/openai-provider.js.map +1 -1
  147. package/dist/llm/types.d.ts +7 -2
  148. package/dist/llm/types.d.ts.map +1 -1
  149. package/dist/llm/types.js.map +1 -1
  150. package/dist/protocol.d.ts +53 -3
  151. package/dist/protocol.d.ts.map +1 -1
  152. package/dist/protocol.js +2 -0
  153. package/dist/protocol.js.map +1 -1
  154. package/dist/runtime.d.ts +34 -1
  155. package/dist/runtime.d.ts.map +1 -1
  156. package/dist/runtime.js +133 -0
  157. package/dist/runtime.js.map +1 -1
  158. package/dist/templates/echo/agent.js +87 -1
  159. package/dist/templates/echo-dc/agent.js +87 -1
  160. package/dist/templates/flow-agent/agent.js +49176 -0
  161. package/dist/templates/game-sync/agent.js +87 -1
  162. package/dist/templates/language-switch/agent.js +87 -1
  163. package/dist/templates/llm-agent/agent.js +299 -105
  164. package/dist/templates/llm-docs-rag/agent.js +299 -105
  165. package/dist/templates/llm-mcp-service/agent.js +299 -105
  166. package/dist/templates/llm-support-sticky-user/agent.js +60690 -0
  167. package/dist/templates/positional-tts/agent.js +87 -1
  168. package/dist/templates/recording-consent/agent.js +87 -1
  169. package/dist/templates/registry.d.ts.map +1 -1
  170. package/dist/templates/registry.js +49 -0
  171. package/dist/templates/registry.js.map +1 -1
  172. package/dist/templates/spatial-showcase/agent.js +87 -1
  173. package/dist/templates/voice-showcase/agent.js +87 -1
  174. package/dist/templates/voice-starter/agent.js +87 -1
  175. package/dist/templates/webhooks/agent.js +87 -1
  176. package/dist/templates/webhooks-redis/agent.js +87 -1
  177. package/dist/templates/world-sync/agent.js +87 -1
  178. package/dist/templates/world-sync-binary/agent.js +87 -1
  179. package/eject/llm/loop.ts +44 -102
  180. package/package.json +19 -2
  181. package/schema/voicethere.flow.schema.json +681 -0
  182. package/templates/README.md +1 -0
  183. package/templates/flow-agent/README.md +38 -0
  184. package/templates/flow-agent/agent.ts +14 -0
  185. package/templates/flow-agent/tools.ts +5 -0
  186. package/templates/flow-agent/voicethere.flow.json +80 -0
  187. package/templates/flow-agent/voicethere.flow.mocks.json +17 -0
  188. package/templates/llm-support-sticky-user/README.md +68 -0
  189. package/templates/llm-support-sticky-user/agent.ts +29 -0
  190. package/templates/llm-support-sticky-user/hooks.ts +188 -0
  191. package/templates/llm-support-sticky-user/md.d.ts +4 -0
  192. package/templates/llm-support-sticky-user/mock-crm.ts +75 -0
  193. package/templates/llm-support-sticky-user/prompt.md +21 -0
  194. package/templates/llm-support-sticky-user/tools.ts +244 -0
  195. package/templates/llm-support-sticky-user/voicethere.llm.json +52 -0
@@ -30848,6 +30848,12 @@ function isConversationHistoryControlAckMessage(value) {
30848
30848
  const msg = value;
30849
30849
  return msg.type === "conversation_history_control_ack" && typeof msg.requestId === "string";
30850
30850
  }
30851
+ function isUserHistoryResponseMessage(value) {
30852
+ if (!value || typeof value !== "object")
30853
+ return false;
30854
+ const msg = value;
30855
+ return msg.type === "user_history_response" && typeof msg.requestId === "string";
30856
+ }
30851
30857
  function isMixControlAckMessage(value) {
30852
30858
  if (!value || typeof value !== "object")
30853
30859
  return false;
@@ -30920,7 +30926,7 @@ function isParentMessage(value) {
30920
30926
  if (!value || typeof value !== "object")
30921
30927
  return false;
30922
30928
  const msg = value;
30923
- return msg.type === "session_start" || msg.type === "speech_event" || msg.type === "session_end" || msg.type === "data_channel_message" || msg.type === "data_channel_binary" || msg.type === "idle_timeout" || msg.type === "session_time_limit" || msg.type === "session_time_limit_control_ack" || msg.type === "recording_control_ack" || msg.type === "conversation_history_control_ack" || msg.type === "play_ack" || msg.type === "play_status_ack" || msg.type === "play_stop_ack" || msg.type === "play_pose_ack" || msg.type === "mix_control_ack" || msg.type === "stt_control_ack" || msg.type === "voice_language_control_ack" || msg.type === "voice_language_prepare_result" || msg.type === "voice_replay_last_result" || msg.type === "speak_result" || msg.type === "barge_in_control_ack" || msg.type === "agent_interrupted" || msg.type === "webhook";
30929
+ return msg.type === "session_start" || msg.type === "speech_event" || msg.type === "session_end" || msg.type === "data_channel_message" || msg.type === "data_channel_binary" || msg.type === "idle_timeout" || msg.type === "session_time_limit" || msg.type === "session_time_limit_control_ack" || msg.type === "recording_control_ack" || msg.type === "conversation_history_control_ack" || msg.type === "user_identified" || msg.type === "user_history_response" || msg.type === "play_ack" || msg.type === "play_status_ack" || msg.type === "play_stop_ack" || msg.type === "play_pose_ack" || msg.type === "mix_control_ack" || msg.type === "stt_control_ack" || msg.type === "voice_language_control_ack" || msg.type === "voice_language_prepare_result" || msg.type === "voice_replay_last_result" || msg.type === "speak_result" || msg.type === "barge_in_control_ack" || msg.type === "agent_interrupted" || msg.type === "webhook";
30924
30930
  }
30925
30931
  function isSessionScopedParentMessage(value) {
30926
30932
  return isParentMessage(value) && !isWebhookMessage(value);
@@ -30935,6 +30941,7 @@ function parseDataChannelPayload(raw) {
30935
30941
  var peerEnvBySessionId = /* @__PURE__ */ new Map();
30936
30942
  var recordingAvailableBySessionId = /* @__PURE__ */ new Map();
30937
30943
  var conversationHistoryAvailableBySessionId = /* @__PURE__ */ new Map();
30944
+ var endUserBySessionId = /* @__PURE__ */ new Map();
30938
30945
  var mixAvailableBySessionId = /* @__PURE__ */ new Map();
30939
30946
  var voiceLanguageSwitchAvailableBySessionId = /* @__PURE__ */ new Map();
30940
30947
  var lastVoiceLanguageBySessionId = /* @__PURE__ */ new Map();
@@ -30944,6 +30951,7 @@ var sessionTimeLimitAvailableBySessionId = /* @__PURE__ */ new Map();
30944
30951
  var sessionTimeLimitWarnedSessionIds = /* @__PURE__ */ new Set();
30945
30952
  var speakControlWarnedSessionIds = /* @__PURE__ */ new Set();
30946
30953
  var endedSessionIds = /* @__PURE__ */ new Set();
30954
+ var USER_HISTORY_TIMEOUT_MS = 5e3;
30947
30955
  var BARGE_IN_CONTROL_ACK_TIMEOUT_MS = 5e3;
30948
30956
  var SPEAK_RESULT_SAFETY_TIMEOUT_MS = 6e5;
30949
30957
  var pendingSpeakResults = /* @__PURE__ */ new Map();
@@ -31024,6 +31032,7 @@ function clearPendingSpeakForSession(sessionId, errorCode) {
31024
31032
  var PLAY_BYTES_MAX_DECODED_LENGTH = 64 * 1024;
31025
31033
  var pendingRecordingAcks = /* @__PURE__ */ new Map();
31026
31034
  var pendingConversationHistoryAcks = /* @__PURE__ */ new Map();
31035
+ var pendingUserHistory = /* @__PURE__ */ new Map();
31027
31036
  var pendingPlayAcks = /* @__PURE__ */ new Map();
31028
31037
  var pendingPlayStatusAcks = /* @__PURE__ */ new Map();
31029
31038
  var pendingPlayStopAcks = /* @__PURE__ */ new Map();
@@ -31058,6 +31067,27 @@ function handleConversationHistoryControlAck(message) {
31058
31067
  requestId: message.requestId
31059
31068
  });
31060
31069
  }
31070
+ function handleUserHistoryResponse(message) {
31071
+ const pending = pendingUserHistory.get(message.requestId);
31072
+ if (!pending)
31073
+ return;
31074
+ clearTimeout(pending.timer);
31075
+ pendingUserHistory.delete(message.requestId);
31076
+ pending.resolve({
31077
+ ok: message.ok,
31078
+ ...message.reason ? { reason: message.reason } : {},
31079
+ conversations: Array.isArray(message.conversations) ? message.conversations : []
31080
+ });
31081
+ }
31082
+ function clearPendingUserHistoryForSession(sessionId, reason) {
31083
+ for (const [requestId, pending] of pendingUserHistory) {
31084
+ if (pending.sessionId !== sessionId)
31085
+ continue;
31086
+ clearTimeout(pending.timer);
31087
+ pendingUserHistory.delete(requestId);
31088
+ pending.resolve({ ok: false, reason, conversations: [] });
31089
+ }
31090
+ }
31061
31091
  function handlePlayAck(message) {
31062
31092
  const pending = pendingPlayAcks.get(message.requestId);
31063
31093
  if (!pending)
@@ -31378,6 +31408,11 @@ async function handleParentMessage(message, handlers) {
31378
31408
  peerEnvBySessionId.set(message.sessionId, message.env);
31379
31409
  recordingAvailableBySessionId.set(message.sessionId, message.recordingAvailable ?? false);
31380
31410
  conversationHistoryAvailableBySessionId.set(message.sessionId, message.conversationHistoryAvailable ?? false);
31411
+ const startUser = parseEndUserInfo(message.endUser) ?? parseEndUserEnv(message.env?.AGENT_END_USER);
31412
+ if (startUser)
31413
+ endUserBySessionId.set(message.sessionId, startUser);
31414
+ else
31415
+ endUserBySessionId.delete(message.sessionId);
31381
31416
  mixAvailableBySessionId.set(message.sessionId, message.mixAvailable ?? false);
31382
31417
  voiceLanguageSwitchAvailableBySessionId.set(message.sessionId, message.voiceLanguageSwitchAvailable ?? false);
31383
31418
  ttsPoseAvailableBySessionId.set(message.sessionId, message.ttsPoseAvailable ?? false);
@@ -31395,6 +31430,7 @@ async function handleParentMessage(message, handlers) {
31395
31430
  await (handlers.onClientJoin ?? handlers.onSessionStart)?.({
31396
31431
  sessionId: message.sessionId,
31397
31432
  env: message.env,
31433
+ ...startUser ? { user: startUser } : {},
31398
31434
  recordingAvailable: message.recordingAvailable ?? false,
31399
31435
  conversationHistoryAvailable: message.conversationHistoryAvailable ?? false,
31400
31436
  mixAvailable: message.mixAvailable ?? false,
@@ -31408,6 +31444,27 @@ async function handleParentMessage(message, handlers) {
31408
31444
  sessionId: message.sessionId
31409
31445
  });
31410
31446
  break;
31447
+ case "user_identified": {
31448
+ if (endedSessionIds.has(message.sessionId))
31449
+ break;
31450
+ const user = parseEndUserInfo(message.endUser);
31451
+ if (!user)
31452
+ break;
31453
+ endUserBySessionId.set(message.sessionId, user);
31454
+ await handlers.onUserIdentified?.({
31455
+ sessionId: message.sessionId,
31456
+ env: peerEnvBySessionId.get(message.sessionId) ?? {},
31457
+ recordingAvailable: recordingAvailableBySessionId.get(message.sessionId) ?? false,
31458
+ conversationHistoryAvailable: conversationHistoryAvailableBySessionId.get(message.sessionId) ?? false,
31459
+ mixAvailable: mixAvailableBySessionId.get(message.sessionId) ?? false,
31460
+ voiceLanguageSwitchAvailable: voiceLanguageSwitchAvailableBySessionId.get(message.sessionId) ?? false,
31461
+ ttsPoseAvailable: ttsPoseAvailableBySessionId.get(message.sessionId) ?? false,
31462
+ speakControlAvailable: speakControlAvailableBySessionId.get(message.sessionId) ?? false,
31463
+ sessionTimeLimitAvailable: sessionTimeLimitAvailableBySessionId.get(message.sessionId) ?? false,
31464
+ user
31465
+ });
31466
+ break;
31467
+ }
31411
31468
  case "speech_event":
31412
31469
  await handlers.onSpeechEvent?.({ sessionId: message.sessionId }, message.event);
31413
31470
  if (message.event.type === "user_speech_final" && typeof message.event.text === "string" && message.event.text.trim()) {
@@ -31470,6 +31527,7 @@ async function handleParentMessage(message, handlers) {
31470
31527
  peerEnvBySessionId.delete(message.sessionId);
31471
31528
  recordingAvailableBySessionId.delete(message.sessionId);
31472
31529
  conversationHistoryAvailableBySessionId.delete(message.sessionId);
31530
+ endUserBySessionId.delete(message.sessionId);
31473
31531
  mixAvailableBySessionId.delete(message.sessionId);
31474
31532
  voiceLanguageSwitchAvailableBySessionId.delete(message.sessionId);
31475
31533
  voiceLanguageSwitchSettingsBySessionId.delete(message.sessionId);
@@ -31504,6 +31562,10 @@ function defineAgent(handlers) {
31504
31562
  handleConversationHistoryControlAck(message);
31505
31563
  return;
31506
31564
  }
31565
+ if (isUserHistoryResponseMessage(message)) {
31566
+ handleUserHistoryResponse(message);
31567
+ return;
31568
+ }
31507
31569
  if (isSpeakResultMessage(message)) {
31508
31570
  handleSpeakResult(message);
31509
31571
  return;
@@ -31563,6 +31625,7 @@ function defineAgent(handlers) {
31563
31625
  clearPendingSpeakForSession(message.sessionId, "session_ended");
31564
31626
  clearPendingRecordingAcksForSession(message.sessionId, "session_ended");
31565
31627
  clearPendingConversationHistoryAcksForSession(message.sessionId, "session_ended");
31628
+ clearPendingUserHistoryForSession(message.sessionId, "session_ended");
31566
31629
  inboundBySession.clear(message.sessionId);
31567
31630
  }
31568
31631
  if (message.type === "session_start") {
@@ -31635,6 +31698,30 @@ function parseCustomerContext(raw) {
31635
31698
  }
31636
31699
  return void 0;
31637
31700
  }
31701
+ function parseEndUserInfo(value) {
31702
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
31703
+ return void 0;
31704
+ }
31705
+ const v = value;
31706
+ if (typeof v.id !== "string" || v.id.length === 0)
31707
+ return void 0;
31708
+ const isObj2 = (x) => !!x && typeof x === "object" && !Array.isArray(x);
31709
+ return {
31710
+ id: v.id,
31711
+ verified: v.verified === true,
31712
+ ...isObj2(v.attributes) ? { attributes: v.attributes } : {},
31713
+ ...isObj2(v.sessionContext) ? { sessionContext: v.sessionContext } : {}
31714
+ };
31715
+ }
31716
+ function parseEndUserEnv(raw) {
31717
+ if (!raw?.trim())
31718
+ return void 0;
31719
+ try {
31720
+ return parseEndUserInfo(JSON.parse(raw));
31721
+ } catch {
31722
+ return void 0;
31723
+ }
31724
+ }
31638
31725
  async function runErrorHook(handlers, ctx) {
31639
31726
  if (!handlers.errorHook)
31640
31727
  return;
@@ -31862,6 +31949,32 @@ function setAgentState(sessionId, state2, options) {
31862
31949
  ...detail ? { detail: detail.slice(0, 64) } : {}
31863
31950
  });
31864
31951
  }
31952
+ function getSessionUser(sessionId) {
31953
+ return endUserBySessionId.get(sessionId);
31954
+ }
31955
+ async function getUserHistory(sessionId, opts = {}) {
31956
+ if (!allowOutboundForSession(sessionId)) {
31957
+ return { ok: false, reason: "session_ended", conversations: [] };
31958
+ }
31959
+ if (!isVoicethereAgentChild()) {
31960
+ return { ok: true, reason: "local_mock", conversations: [] };
31961
+ }
31962
+ const requestId = randomUUID();
31963
+ return new Promise((resolve) => {
31964
+ const timer = setTimeout(() => {
31965
+ pendingUserHistory.delete(requestId);
31966
+ resolve({ ok: false, reason: "timeout", conversations: [] });
31967
+ }, USER_HISTORY_TIMEOUT_MS);
31968
+ pendingUserHistory.set(requestId, { sessionId, resolve, timer });
31969
+ sendParentMessage({
31970
+ type: "user_history_request",
31971
+ requestId,
31972
+ sessionId,
31973
+ limit: opts.limit ?? 5,
31974
+ maxTurnsPerConversation: opts.maxTurnsPerConversation ?? 50
31975
+ });
31976
+ });
31977
+ }
31865
31978
  function sendToClient(sessionId, payload) {
31866
31979
  sendParentMessage({ type: "send_to_client", sessionId, payload });
31867
31980
  }
@@ -32250,12 +32363,14 @@ var LLM_PROVIDERS = {
32250
32363
  openai: {
32251
32364
  title: "OpenAI",
32252
32365
  defaultModel: "gpt-4o-mini",
32366
+ cheapModel: "gpt-4o-mini",
32253
32367
  apiKeyEnv: "AGENT_OPENAI_API_KEY",
32254
32368
  docsUrl: "https://platform.openai.com/docs/api-reference/chat"
32255
32369
  },
32256
32370
  anthropic: {
32257
32371
  title: "Anthropic",
32258
32372
  defaultModel: "claude-haiku-5-5",
32373
+ cheapModel: "claude-haiku-5-5",
32259
32374
  apiKeyEnv: "AGENT_ANTHROPIC_API_KEY",
32260
32375
  docsUrl: "https://docs.anthropic.com/en/api/messages"
32261
32376
  },
@@ -32271,6 +32386,7 @@ var LLM_PROVIDERS = {
32271
32386
  // toolChoice "required-first-round"). amazon/nova-micro-v1, the previous
32272
32387
  // default, does not list tool_choice and skipped tools it was told to call.
32273
32388
  defaultModel: "anthropic/claude-haiku-5.5",
32389
+ cheapModel: "anthropic/claude-haiku-5.5",
32274
32390
  apiKeyEnv: "AGENT_OPENROUTER_API_KEY",
32275
32391
  docsUrl: "https://openrouter.ai/docs/api-reference/overview"
32276
32392
  }
@@ -32666,6 +32782,7 @@ function isPhone(m) {
32666
32782
  }
32667
32783
  var NON_SECRET_AGENT_KEYS = /* @__PURE__ */ new Set([
32668
32784
  "AGENT_CUSTOMER_CONTEXT",
32785
+ "AGENT_END_USER",
32669
32786
  "AGENT_SERVICE_URL"
32670
32787
  ]);
32671
32788
  function secretValuesFromEnv(env, referenced) {
@@ -32837,6 +32954,7 @@ function buildToolCallFields(a) {
32837
32954
  var MAX_TOOLS = 128;
32838
32955
  var MAX_RESULT_BYTES = 16384;
32839
32956
  var NAME_RE = /^[a-zA-Z0-9_-]{1,64}$/;
32957
+ var VERIFIED_USER_REQUIRED_MESSAGE = "this tool needs a verified user";
32840
32958
  var ToolNameConflictError = class extends Error {
32841
32959
  code = "LLM_TOOL_NAME_CONFLICT";
32842
32960
  constructor(name) {
@@ -32888,8 +33006,9 @@ var ToolRegistry = class {
32888
33006
  addSource(source) {
32889
33007
  this.sources.push(source);
32890
33008
  }
32891
- list() {
32892
- return this.build().map(({ spec, owner }) => ({ spec, owner }));
33009
+ /** Tools the model may see. Pass the session user: verified-user tools show only for a verified one. */
33010
+ list(opts = {}) {
33011
+ return this.build().filter((e) => !e.custom?.requiresVerifiedUser || opts.user?.verified === true).map(({ spec, owner }) => ({ spec, owner }));
32893
33012
  }
32894
33013
  async call(exposedName, args, opts) {
32895
33014
  const entry = this.build().find((e) => e.spec.name === exposedName);
@@ -32906,7 +33025,9 @@ var ToolRegistry = class {
32906
33025
  const startedAt = clock();
32907
33026
  let result;
32908
33027
  try {
32909
- if (entry.custom) {
33028
+ if (entry.custom?.requiresVerifiedUser && opts.user?.verified !== true) {
33029
+ result = { isError: true, content: VERIFIED_USER_REQUIRED_MESSAGE };
33030
+ } else if (entry.custom) {
32910
33031
  result = await this.callCustom(entry.custom, args, opts);
32911
33032
  } else {
32912
33033
  result = await entry.source.callTool(entry.mcpName, args, {
@@ -33802,6 +33923,7 @@ function defineTool(t) {
33802
33923
  name: t.name,
33803
33924
  description: t.description,
33804
33925
  inputSchema: t.inputSchema,
33926
+ ...t.requiresVerifiedUser ? { requiresVerifiedUser: true } : {},
33805
33927
  handler: async (args, ctx) => String(await t.handler(args, ctx))
33806
33928
  };
33807
33929
  }
@@ -33845,6 +33967,45 @@ ${h.text}`).join("\n\n");
33845
33967
  });
33846
33968
  }
33847
33969
 
33970
+ // dist/llm/end-user/end-user-tools.js
33971
+ var MAX_CHARS = 6e3;
33972
+ function endUserTools(load = getUserHistory) {
33973
+ return [
33974
+ defineTool({
33975
+ name: "get_previous_conversations",
33976
+ description: "Read earlier conversations with this verified user, to avoid repeating questions or steps they already went through.",
33977
+ inputSchema: {
33978
+ type: "object",
33979
+ additionalProperties: false,
33980
+ properties: { limit: { type: "integer", minimum: 1, maximum: 10 } }
33981
+ },
33982
+ requiresVerifiedUser: true,
33983
+ handler: async (args, ctx) => {
33984
+ const limit2 = typeof args.limit === "number" && Number.isInteger(args.limit) ? Math.min(10, Math.max(1, args.limit)) : 3;
33985
+ const res = await load(ctx.sessionId, { limit: limit2 });
33986
+ if (!res.ok)
33987
+ return "Earlier conversations are unavailable right now.";
33988
+ if (res.conversations.length === 0) {
33989
+ return "No earlier conversations with this user.";
33990
+ }
33991
+ const text = res.conversations.map((c, i) => `Conversation ${i + 1} (${c.sessionStartedAt}):
33992
+ ` + c.turns.map((t) => `${t.role}: ${t.text}`).join("\n")).join("\n\n");
33993
+ return text.length > MAX_CHARS ? text.slice(0, MAX_CHARS) : text;
33994
+ }
33995
+ }),
33996
+ defineTool({
33997
+ name: "get_current_user",
33998
+ description: "Who the current user is: their id, whether they are verified, and the attributes the customer's system gave.",
33999
+ inputSchema: { type: "object", additionalProperties: false },
34000
+ handler: (_args, ctx) => JSON.stringify(ctx.user ? {
34001
+ id: ctx.user.id,
34002
+ verified: ctx.user.verified,
34003
+ attributes: ctx.user.attributes ?? {}
34004
+ } : { id: null, verified: false, attributes: {} })
34005
+ })
34006
+ ];
34007
+ }
34008
+
33848
34009
  // dist/llm/agent/config.js
33849
34010
  var LLM_AGENT_CONFIG_DEFAULTS = {
33850
34011
  maxOutputTokens: 512,
@@ -34926,6 +35087,101 @@ var LLM_AGENT_CONFIG_JSON_SCHEMA = {
34926
35087
  }
34927
35088
  };
34928
35089
 
35090
+ // dist/llm/agent/build-tool-registry.js
35091
+ function nonEmpty(v) {
35092
+ return v !== void 0 && v.length > 0;
35093
+ }
35094
+ function buildToolRegistry(o) {
35095
+ const { env } = o;
35096
+ const makeSource = o.makeSource ?? ((x) => new McpToolSource(x));
35097
+ const reg = new ToolRegistry({
35098
+ log: (level, message, fields) => agentLog(level, message, fields ?? {}),
35099
+ toolCallLog: {
35100
+ mode: o.toolCallLogs,
35101
+ secretValues: secretValuesFromEnv(env, [
35102
+ ...o.secretNames,
35103
+ ...o.toolSources.flatMap((src) => {
35104
+ if (src.kind !== "mcp" || !src.auth)
35105
+ return [];
35106
+ if (src.auth.type === "bearer")
35107
+ return [src.auth.secret];
35108
+ if (src.auth.type === "headers")
35109
+ return Object.values(src.auth.headers);
35110
+ return [];
35111
+ })
35112
+ ]),
35113
+ emit: (fields, sid) => agentLog("info", "llm tool call", { ...fields }, sid)
35114
+ }
35115
+ });
35116
+ for (const tool of o.customTools)
35117
+ reg.addCustomTool(tool);
35118
+ let serviceSource;
35119
+ const sources = [];
35120
+ for (const src of o.toolSources) {
35121
+ if (src.kind === "service") {
35122
+ const base = env.AGENT_SERVICE_URL;
35123
+ if (!nonEmpty(base)) {
35124
+ agentLog("warn", "toolSources: service configured but this project has no service");
35125
+ continue;
35126
+ }
35127
+ const headers = {};
35128
+ const token = env.AGENT_SERVICE_TOKEN;
35129
+ if (nonEmpty(token)) {
35130
+ headers.Authorization = `Bearer ${token}`;
35131
+ } else {
35132
+ agentLog("warn", "toolSources: AGENT_SERVICE_TOKEN is not set");
35133
+ }
35134
+ const source = makeSource({
35135
+ name: "service",
35136
+ kind: "service",
35137
+ url: `${base}${src.path ?? o.servicePath}`,
35138
+ headers,
35139
+ allow: src.allow,
35140
+ deny: src.deny,
35141
+ log: (level, message, fields) => agentLog(level, message, fields ?? {})
35142
+ });
35143
+ serviceSource = source;
35144
+ sources.push(source);
35145
+ } else {
35146
+ const headers = {};
35147
+ let missing;
35148
+ const auth2 = src.auth ?? { type: "none" };
35149
+ if (auth2.type === "bearer") {
35150
+ const v = env[auth2.secret];
35151
+ if (nonEmpty(v))
35152
+ headers.Authorization = `Bearer ${v}`;
35153
+ else
35154
+ missing = auth2.secret;
35155
+ } else if (auth2.type === "headers") {
35156
+ for (const [header, envName2] of Object.entries(auth2.headers)) {
35157
+ const v = env[envName2];
35158
+ if (nonEmpty(v))
35159
+ headers[header] = v;
35160
+ else
35161
+ missing = envName2;
35162
+ }
35163
+ }
35164
+ if (missing) {
35165
+ agentLog("warn", `toolSources: ${src.name} skipped, environment variable ${missing} is not set`);
35166
+ continue;
35167
+ }
35168
+ sources.push(makeSource({
35169
+ name: src.name,
35170
+ url: src.url,
35171
+ headers,
35172
+ allow: src.allow,
35173
+ deny: src.deny,
35174
+ log: (level, message, fields) => agentLog(level, message, fields ?? {})
35175
+ }));
35176
+ }
35177
+ }
35178
+ for (const source of sources) {
35179
+ reg.addSource(source);
35180
+ source.start();
35181
+ }
35182
+ return { registry: reg, serviceSource };
35183
+ }
35184
+
34929
35185
  // dist/llm/agent/history.js
34930
35186
  var ConversationHistory = class {
34931
35187
  maxTurns;
@@ -35453,7 +35709,7 @@ function checkContent(content) {
35453
35709
  function interruptionNote(played, unplayed) {
35454
35710
  return `(The caller interrupted your previous reply after: "${played}". They did not hear: "${unplayed}".)`;
35455
35711
  }
35456
- function nonEmpty(v) {
35712
+ function nonEmpty2(v) {
35457
35713
  return v !== void 0 && v.length > 0;
35458
35714
  }
35459
35715
  function createLlmAgent(opts) {
@@ -35751,7 +36007,7 @@ ${validated.errors.map((e) => `${e.path || "(root)"}: ${e.message}`).join("\n")}
35751
36007
  if (!emb)
35752
36008
  return;
35753
36009
  const apiKey = env[emb.apiKeySecret];
35754
- if (!nonEmpty(apiKey)) {
36010
+ if (!nonEmpty2(apiKey)) {
35755
36011
  agentLog("warn", `knowledge: ${emb.apiKeySecret} is not set, search_knowledge disabled`);
35756
36012
  return;
35757
36013
  }
@@ -35761,7 +36017,7 @@ ${validated.errors.map((e) => `${e.path || "(root)"}: ${e.message}`).join("\n")}
35761
36017
  const dims = emb.dimensions ?? DEFAULT_EMBEDDING_DIMS;
35762
36018
  const redisUrl = env.AGENT_REDIS_URL;
35763
36019
  if (kc.store === "redis") {
35764
- if (!nonEmpty(redisUrl)) {
36020
+ if (!nonEmpty2(redisUrl)) {
35765
36021
  agentLog("info", "knowledge: AGENT_REDIS_URL unset (enable Project Redis)");
35766
36022
  return;
35767
36023
  }
@@ -35783,7 +36039,7 @@ ${validated.errors.map((e) => `${e.path || "(root)"}: ${e.message}`).join("\n")}
35783
36039
  const sb = kc.supabase;
35784
36040
  const url2 = sb ? env[sb.urlSecret] : void 0;
35785
36041
  const key = sb ? env[sb.keySecret] : void 0;
35786
- if (!sb || !nonEmpty(url2) || !nonEmpty(key)) {
36042
+ if (!sb || !nonEmpty2(url2) || !nonEmpty2(key)) {
35787
36043
  agentLog("info", "knowledge: Supabase URL or key secret is not set, search_knowledge disabled");
35788
36044
  return;
35789
36045
  }
@@ -35803,7 +36059,7 @@ ${validated.errors.map((e) => `${e.path || "(root)"}: ${e.message}`).join("\n")}
35803
36059
  embedder: createLlmEmbedder({ provider: emb.provider, apiKey }, opts.providers ?? []),
35804
36060
  model,
35805
36061
  dims,
35806
- cache: nonEmpty(redisUrl) ? {
36062
+ cache: nonEmpty2(redisUrl) ? {
35807
36063
  redisUrl,
35808
36064
  ttlSeconds: sb.cacheTtlSeconds,
35809
36065
  namespace: kc.redis?.namespace
@@ -35822,99 +36078,30 @@ ${validated.errors.map((e) => `${e.path || "(root)"}: ${e.message}`).join("\n")}
35822
36078
  knowledgeTool = searchKnowledgeTool(base, { topK, log: logCode });
35823
36079
  }
35824
36080
  function buildRegistry(env) {
35825
- const reg = new ToolRegistry({
35826
- log: (level, message, fields) => agentLog(level, message, fields ?? {}),
35827
- toolCallLog: {
35828
- mode: config2.toolCallLogs ?? D.toolCallLogs,
35829
- secretValues: secretValuesFromEnv(env, [
35830
- config2.apiKeySecret,
35831
- "AGENT_SERVICE_TOKEN",
35832
- ...config2.knowledge?.embeddings ? [config2.knowledge.embeddings.apiKeySecret] : [],
35833
- ...config2.knowledge?.supabase ? [
35834
- config2.knowledge.supabase.keySecret,
35835
- config2.knowledge.supabase.urlSecret
35836
- ] : [],
35837
- ...(config2.toolSources ?? []).flatMap((src) => {
35838
- if (src.kind !== "mcp" || !src.auth)
35839
- return [];
35840
- if (src.auth.type === "bearer")
35841
- return [src.auth.secret];
35842
- if (src.auth.type === "headers")
35843
- return Object.values(src.auth.headers);
35844
- return [];
35845
- })
35846
- ]),
35847
- emit: (fields, sid) => agentLog("info", "llm tool call", { ...fields }, sid)
35848
- }
35849
- });
35850
- for (const tool of opts.tools ?? [])
35851
- reg.addCustomTool(tool);
35852
- if (knowledgeTool)
35853
- reg.addCustomTool(knowledgeTool);
35854
- const sources = [];
35855
- for (const src of config2.toolSources ?? []) {
35856
- if (src.kind === "service") {
35857
- const base = env.AGENT_SERVICE_URL;
35858
- if (!nonEmpty(base)) {
35859
- agentLog("warn", "toolSources: service configured but this project has no service");
35860
- continue;
35861
- }
35862
- const headers = {};
35863
- const token = env.AGENT_SERVICE_TOKEN;
35864
- if (nonEmpty(token)) {
35865
- headers.Authorization = `Bearer ${token}`;
35866
- } else {
35867
- agentLog("warn", "toolSources: AGENT_SERVICE_TOKEN is not set");
35868
- }
35869
- const source = makeSource({
35870
- name: "service",
35871
- kind: "service",
35872
- url: `${base}${src.path ?? D.servicePath}`,
35873
- headers,
35874
- allow: src.allow,
35875
- deny: src.deny,
35876
- log: (level, message, fields) => agentLog(level, message, fields ?? {})
35877
- });
35878
- serviceSource = source;
35879
- sources.push(source);
35880
- } else {
35881
- const headers = {};
35882
- let missing;
35883
- const auth2 = src.auth ?? { type: "none" };
35884
- if (auth2.type === "bearer") {
35885
- const v = env[auth2.secret];
35886
- if (nonEmpty(v))
35887
- headers.Authorization = `Bearer ${v}`;
35888
- else
35889
- missing = auth2.secret;
35890
- } else if (auth2.type === "headers") {
35891
- for (const [header, envName2] of Object.entries(auth2.headers)) {
35892
- const v = env[envName2];
35893
- if (nonEmpty(v))
35894
- headers[header] = v;
35895
- else
35896
- missing = envName2;
35897
- }
35898
- }
35899
- if (missing) {
35900
- agentLog("warn", `toolSources: ${src.name} skipped, environment variable ${missing} is not set`);
35901
- continue;
35902
- }
35903
- sources.push(makeSource({
35904
- name: src.name,
35905
- url: src.url,
35906
- headers,
35907
- allow: src.allow,
35908
- deny: src.deny,
35909
- log: (level, message, fields) => agentLog(level, message, fields ?? {})
35910
- }));
35911
- }
35912
- }
35913
- for (const source of sources) {
35914
- reg.addSource(source);
35915
- source.start();
35916
- }
35917
- registry2 = reg;
36081
+ const built = buildToolRegistry({
36082
+ env,
36083
+ toolSources: config2.toolSources ?? [],
36084
+ customTools: [
36085
+ ...opts.tools ?? [],
36086
+ ...opts.endUserTools === true ? endUserTools() : [],
36087
+ ...knowledgeTool ? [knowledgeTool] : []
36088
+ ],
36089
+ secretNames: [
36090
+ config2.apiKeySecret,
36091
+ "AGENT_SERVICE_TOKEN",
36092
+ ...config2.knowledge?.embeddings ? [config2.knowledge.embeddings.apiKeySecret] : [],
36093
+ ...config2.knowledge?.supabase ? [
36094
+ config2.knowledge.supabase.keySecret,
36095
+ config2.knowledge.supabase.urlSecret
36096
+ ] : []
36097
+ ],
36098
+ toolCallLogs: config2.toolCallLogs ?? D.toolCallLogs,
36099
+ servicePath: D.servicePath,
36100
+ makeSource
36101
+ });
36102
+ if (built.serviceSource)
36103
+ serviceSource = built.serviceSource;
36104
+ registry2 = built.registry;
35918
36105
  }
35919
36106
  async function runTools(s, t, ctx, calls) {
35920
36107
  const signal = t.controller.signal;
@@ -35953,7 +36140,8 @@ ${validated.errors.map((e) => `${e.path || "(root)"}: ${e.message}`).join("\n")}
35953
36140
  timeoutMs: toolTimeoutMs,
35954
36141
  sessionId: s.sessionId,
35955
36142
  turnId: t.turnId,
35956
- callId: call.id
36143
+ callId: call.id,
36144
+ ...getSessionUser(s.sessionId) ? { user: getSessionUser(s.sessionId) } : {}
35957
36145
  });
35958
36146
  })();
35959
36147
  const raced = await Promise.race([work, aborted2]);
@@ -36038,7 +36226,7 @@ ${validated.errors.map((e) => `${e.path || "(root)"}: ${e.message}`).join("\n")}
36038
36226
  model: resolveModel(config2.provider, config2.model),
36039
36227
  system: opts.systemPrompt,
36040
36228
  messages,
36041
- tools: registry2 ? registry2.list().map((e) => e.spec) : [],
36229
+ tools: registry2 ? registry2.list({ user: getSessionUser(s.sessionId) }).map((e) => e.spec) : [],
36042
36230
  ...config2.toolChoice === "required-first-round" && t.llmCalls === 1 ? { toolChoice: "required" } : {},
36043
36231
  temperature: config2.temperature,
36044
36232
  maxOutputTokens: config2.maxOutputTokens ?? D.maxOutputTokens,
@@ -36454,7 +36642,7 @@ ${t.inputText}` : t.inputText, {
36454
36642
  }
36455
36643
  const env = getEnv();
36456
36644
  const apiKey = env[config2.apiKeySecret];
36457
- if (!nonEmpty(apiKey)) {
36645
+ if (!nonEmpty2(apiKey)) {
36458
36646
  throw configError(`environment variable ${config2.apiKeySecret} is not set`, "LLM_API_KEY_MISSING");
36459
36647
  }
36460
36648
  if (!provider) {
@@ -59926,6 +60114,12 @@ function createOpenAiCompatibleProvider(config2) {
59926
60114
  stream_options: { include_usage: true },
59927
60115
  ...tools2.length > 0 ? { tools: tools2 } : {},
59928
60116
  ...tools2.length > 0 && req.toolChoice === "required" ? { tool_choice: "required" } : {},
60117
+ ...tools2.length > 0 && typeof req.toolChoice === "object" && req.toolChoice !== null ? {
60118
+ tool_choice: {
60119
+ type: "function",
60120
+ function: { name: req.toolChoice.name }
60121
+ }
60122
+ } : {},
59929
60123
  ...req.temperature !== void 0 ? { temperature: req.temperature } : {},
59930
60124
  ...req.maxOutputTokens !== void 0 ? config2.id === "openai" ? { max_completion_tokens: req.maxOutputTokens } : { max_tokens: req.maxOutputTokens } : {}
59931
60125
  };