eve 0.40.0 → 0.42.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 (72) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/dist/src/channel/channel-operations.d.ts +2 -2
  3. package/dist/src/channel/channel-operations.js +1 -1
  4. package/dist/src/channel/session.d.ts +2 -2
  5. package/dist/src/channel/session.js +1 -1
  6. package/dist/src/chunks/{use-eve-agent-CTI9fHaO.js → use-eve-agent-C0SG1Ttk.js} +4 -1
  7. package/dist/src/chunks/{use-eve-agent-DlkXRQVo.js → use-eve-agent-D71oDil7.js} +4 -1
  8. package/dist/src/cli/dev/tui/tool-presentation.js +1 -1
  9. package/dist/src/client/index.d.ts +1 -1
  10. package/dist/src/client/index.js +1 -1
  11. package/dist/src/client/session.js +1 -1
  12. package/dist/src/compiled/.vendor-stamp.json +2 -1
  13. package/dist/src/compiled/@linqapp/chat-sdk-adapter/LICENSE +201 -0
  14. package/dist/src/compiled/@linqapp/chat-sdk-adapter/index.d.ts +3 -0
  15. package/dist/src/compiled/@linqapp/chat-sdk-adapter/index.js +8 -0
  16. package/dist/src/compiler/extension-compatibility.d.ts +4 -4
  17. package/dist/src/compiler/extension-compatibility.js +1 -1
  18. package/dist/src/execution/tasks/parent/hitl-proxy-steps.js +1 -1
  19. package/dist/src/execution/wire/session-inbox-wire.v1.js +1 -1
  20. package/dist/src/internal/application/package.js +1 -1
  21. package/dist/src/packages/eve-catalog/src/index.js +1 -1
  22. package/dist/src/public/channels/discord/hitl.d.ts +3 -3
  23. package/dist/src/public/channels/discord/hitl.js +1 -1
  24. package/dist/src/public/channels/eve.js +1 -1
  25. package/dist/src/public/channels/linq/inboundContent.d.ts +4 -0
  26. package/dist/src/public/channels/linq/inboundContent.js +1 -0
  27. package/dist/src/public/channels/linq/index.d.ts +1 -0
  28. package/dist/src/public/channels/linq/index.js +1 -0
  29. package/dist/src/public/channels/linq/linqChannel.d.ts +66 -0
  30. package/dist/src/public/channels/linq/linqChannel.js +1 -0
  31. package/dist/src/public/channels/mcp.js +1 -1
  32. package/dist/src/public/channels/slack/hitl.d.ts +4 -5
  33. package/dist/src/public/channels/slack/hitl.js +2 -2
  34. package/dist/src/public/channels/slack/interactions.js +1 -1
  35. package/dist/src/public/channels/slack/session-operations.d.ts +2 -2
  36. package/dist/src/public/channels/slack/slackChannel.d.ts +4 -4
  37. package/dist/src/public/channels/teams/api.js +2 -2
  38. package/dist/src/public/channels/teams/defaults.js +1 -1
  39. package/dist/src/public/channels/teams/hitl.d.ts +11 -2
  40. package/dist/src/public/channels/teams/hitl.js +1 -1
  41. package/dist/src/public/channels/teams/index.d.ts +1 -1
  42. package/dist/src/public/channels/teams/index.js +1 -1
  43. package/dist/src/public/channels/teams/teamsChannel.d.ts +8 -0
  44. package/dist/src/public/channels/teams/teamsChannel.js +1 -1
  45. package/dist/src/public/channels/telegram/hitl.d.ts +4 -4
  46. package/dist/src/public/channels/telegram/hitl.js +1 -1
  47. package/dist/src/runtime/framework-tools/ask-question.js +1 -1
  48. package/dist/src/runtime/framework-tools/tasks.d.ts +3 -11
  49. package/dist/src/runtime/framework-tools/tasks.js +1 -1
  50. package/dist/src/runtime/input/types.d.ts +19 -1
  51. package/dist/src/runtime/input/types.js +1 -1
  52. package/dist/src/runtime/prompt/compose.js +1 -1
  53. package/dist/src/runtime/session-callback-route.js +1 -1
  54. package/dist/src/setup/integrations/linq/connect.d.ts +32 -0
  55. package/dist/src/setup/integrations/linq/connect.js +1 -0
  56. package/dist/src/setup/integrations/linq/setup.d.ts +22 -0
  57. package/dist/src/setup/integrations/linq/setup.js +15 -0
  58. package/dist/src/setup/integrations/registry.js +1 -1
  59. package/dist/src/setup/scaffold/create/project.js +1 -1
  60. package/dist/src/setup/scaffold/create/web-template.d.ts +2 -2
  61. package/dist/src/setup/scaffold/create/web-template.js +74 -50
  62. package/dist/src/svelte/index.js +1 -1
  63. package/dist/src/svelte/use-eve-agent.js +1 -1
  64. package/dist/src/vue/index.js +1 -1
  65. package/dist/src/vue/use-eve-agent.js +1 -1
  66. package/docs/channels/custom.mdx +12 -0
  67. package/docs/channels/linq.mdx +67 -0
  68. package/docs/channels/meta.json +1 -0
  69. package/docs/channels/overview.mdx +3 -2
  70. package/docs/channels/teams.mdx +2 -0
  71. package/docs/guides/client/streaming.mdx +1 -1
  72. package/package.json +7 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # eve
2
2
 
3
+ ## 0.42.0
4
+
5
+ ### Minor Changes
6
+
7
+ - a43e14f: Prevent channel HITL responses from carrying channel-local metadata into strict session-inbox payloads. Channel and session `respond()` calls now accept exact response literals or values proven by `parseInputResponses()`, rejecting imprecise `InputResponse[]` values that could have erased extra keys.
8
+
9
+ ### Patch Changes
10
+
11
+ - f2169fa: Remove the `task_sleep` framework tool. Task-mode parents now rely on lifecycle notifications instead of model-paced waits.
12
+
13
+ ## 0.41.0
14
+
15
+ ### Minor Changes
16
+
17
+ - 0569638: Add a first-class Linq iMessage and SMS channel with managed Vercel Connect and portable credential setup paths. Connect setup can provision a new Linq account and line or connect an existing account with its partner API token.
18
+
19
+ ### Patch Changes
20
+
21
+ - bdf5f63: Improve the generated web chat experience with immediate thinking feedback, a disabled composer while responses stream, clearer cancellation controls, and visible turn failures.
22
+ - c47350f: Rebuild untransformed session-scoped dynamic tool executors and approval policies on durable continuations so dependency-created tools remain available after replay.
23
+ - c47350f: Update Teams tool-approval cards only after approval settlement, with the outcome and the Teams responder who acted.
24
+ - 9e19fa4: Keep active client streams attached across authorization parking boundaries so connection callbacks resume browser chats automatically.
25
+
3
26
  ## 0.40.0
4
27
 
5
28
  ### Minor Changes
@@ -5,7 +5,7 @@ import { type ChannelAddressDeliveryOptions } from "#channel/channel-address.js"
5
5
  import type { SendPayload } from "#channel/routes.js";
6
6
  import type { Session } from "#channel/session.js";
7
7
  import type { CancelTurnResult, ClearSessionResult, CompactSessionResult, ResetSessionResult, Runtime, SessionAuthContext, SessionCallback, TurnPolicy } from "#channel/types.js";
8
- import type { InputResponse } from "#runtime/input/types.js";
8
+ import { type InputResponse, type StrictInputResponses } from "#runtime/input/types.js";
9
9
  import type { JsonObject } from "#shared/json.js";
10
10
  import type { RunMode } from "#shared/run-mode.js";
11
11
  interface BaseChannelSendOptions {
@@ -35,7 +35,7 @@ export interface ChannelSource<TState = undefined> {
35
35
  /** Starts or resumes a turn with a user message. May create a session. */
36
36
  send(message: string | UserContent, options: ChannelSendOptions<TState>): Promise<Session>;
37
37
  /** Answers pending input requests. Never creates a session. */
38
- respond(inputResponses: readonly InputResponse[], options: ChannelRespondOptions<TState>): Promise<Session>;
38
+ respond<const TResponses extends readonly InputResponse[]>(inputResponses: StrictInputResponses<TResponses>, options: ChannelRespondOptions<TState>): Promise<Session>;
39
39
  /** Cooperatively cancels the active turn without creating a session. */
40
40
  cancel(options?: {
41
41
  readonly turnId?: string;
@@ -1 +1 @@
1
- import{createChannelAddressFn}from"#channel/channel-address.js";const INTERNAL_CHANNEL_DELIVER=Symbol(`eve.internal.channel-deliver`);function createChannelOperations(n){let r=createChannelAddressFn(n);return{from(e){let n=r(e);return{async send(e,t){return await n.deliver({context:t.context,message:e,outputSchema:t.outputSchema},t)},async respond(e,t){if(e.length===0)throw Error(`respond() requires at least one input response.`);return await n.deliver({context:t.context,inputResponses:e,outputSchema:t.outputSchema,state:t.state},t)},async cancel(e){return await n.cancel(e)},async compact(){return await n.compact()},async clear(){return await n.clear()},async reset(e){return await n.reset(e)},async[INTERNAL_CHANNEL_DELIVER](e,t){return await n.deliver(e,t)}}},async resolveSession(e){return await r(e).resolveSession()}}}export{INTERNAL_CHANNEL_DELIVER,createChannelOperations};
1
+ import{createChannelAddressFn}from"#channel/channel-address.js";import{parseInputResponses}from"#runtime/input/types.js";const INTERNAL_CHANNEL_DELIVER=Symbol(`eve.internal.channel-deliver`);function createChannelOperations(r){let i=createChannelAddressFn(r);return{from(e){let r=i(e);return{async send(e,t){return await r.deliver({context:t.context,message:e,outputSchema:t.outputSchema},t)},async respond(e,n){if(e.length===0)throw Error(`respond() requires at least one input response.`);let i=parseInputResponses(e);return await r.deliver({context:n.context,inputResponses:i,outputSchema:n.outputSchema,state:n.state},n)},async cancel(e){return await r.cancel(e)},async compact(){return await r.compact()},async clear(){return await r.clear()},async reset(e){return await r.reset(e)},async[INTERNAL_CHANNEL_DELIVER](e,t){return await r.deliver(e,t)}}},async resolveSession(e){return await i(e).resolveSession()}}}export{INTERNAL_CHANNEL_DELIVER,createChannelOperations};
@@ -4,7 +4,7 @@ import type { MessageStreamEvent } from "#protocol/message.js";
4
4
  import type { UserContent } from "ai";
5
5
  import type { CancelTurnResult, ClearSessionResult, CompactSessionResult, ResetSessionResult, Runtime, SessionAuthContext, SessionCallback, SessionSendCommandResult, TurnPolicy, TurnCaller } from "#channel/types.js";
6
6
  import type { SessionAuth } from "#context/keys.js";
7
- import type { InputResponse } from "#runtime/input/types.js";
7
+ import { type InputResponse, type StrictInputResponses } from "#runtime/input/types.js";
8
8
  import type { JsonObject } from "#shared/json.js";
9
9
  /** Immutable-ID handle for one exact durable session. */
10
10
  export interface Session {
@@ -12,7 +12,7 @@ export interface Session {
12
12
  /** Sends a message to this exact session ID without creating or following a replacement. */
13
13
  send(message: string | UserContent, options: SessionSendOptions): Promise<SessionSendCommandResult>;
14
14
  /** Answers pending input requests on this exact session ID. */
15
- respond(inputResponses: readonly InputResponse[], options: SessionRespondOptions): Promise<SessionSendCommandResult>;
15
+ respond<const TResponses extends readonly InputResponse[]>(inputResponses: StrictInputResponses<TResponses>, options: SessionRespondOptions): Promise<SessionSendCommandResult>;
16
16
  /** Requests cancellation of this exact session's active turn or one owned task. */
17
17
  cancel(options?: {
18
18
  taskId?: string;
@@ -1 +1 @@
1
- import{createChannelDeliveryMetadata}from"#channel/delivery-metadata.js";import{serializeUrlFilePartsInMessage}from"#channel/send-input.js";import{DEFAULT_TURN_POLICY}from"#channel/types.js";import{AuthKey,ContinuationTokenKey,InitiatorAuthKey,SessionIdKey}from"#context/keys.js";import{toChannelLocalContinuationToken}from"#shared/continuation-token.js";function createSession(e,r,i={}){return{id:e,async send(a,o){let s=createDelivery(i),c=sessionCallbackToTurnCaller(o.callback),l={message:serializeUrlFilePartsInMessage(a)};o.context!==void 0&&(l.context=o.context),o.outputSchema!==void 0&&(l.outputSchema=o.outputSchema);let u={auth:o.auth,delivery:s,kind:`send`,payload:l,requestId:i.requestId,turnPolicy:o.turnPolicy??i.turnPolicy??DEFAULT_TURN_POLICY};return await r.dispatchSession({command:c===void 0?u:{...u,caller:c},sessionId:e})},async respond(t,n){if(t.length===0)throw Error(`respond() requires at least one input response.`);let a=sessionCallbackToTurnCaller(n.callback),o=createDelivery(i),s={inputResponses:t};n.context!==void 0&&(s.context=n.context),n.outputSchema!==void 0&&(s.outputSchema=n.outputSchema);let c={auth:n.auth,delivery:o,kind:`send`,payload:s,requestId:i.requestId};return await r.dispatchSession({command:a===void 0?c:{...c,caller:a},sessionId:e})},async cancel(t){return await r.dispatchSession({command:{kind:`cancel`,taskId:t?.taskId,turnId:t?.turnId},sessionId:e})},async compact(){return await r.dispatchSession({command:{kind:`compact`},sessionId:e})},async clear(){return await r.dispatchSession({command:{kind:`clear`},sessionId:e})},async reset(t){return await r.dispatchSession({command:{kind:`reset`,reason:t?.reason},sessionId:e})},async getEventStream(t){return r.getEventStream(e,t)},async getStreamTailIndex(){return r.getStreamTailIndex(e)}}}function createAttachSessionFn(e,t={}){return n=>createSession(n,e,t)}function createDelivery(t){return t.channelKind!==void 0&&t.channelName!==void 0?createChannelDeliveryMetadata(t):void 0}function buildSessionHandle(e){return{get id(){return e.get(SessionIdKey)??``},get auth(){return{current:e.get(AuthKey)??null,initiator:e.get(InitiatorAuthKey)??null}},get continuation(){let t=e.get(ContinuationTokenKey);if(!(t===void 0||t.length===0))return{token:toChannelLocalContinuationToken(t),rekey(n){let r=namespaceContinuationToken(t,n);t!==r&&e.set(ContinuationTokenKey,r)}}}}}function namespaceContinuationToken(e,t){let n=e.indexOf(`:`);if(n<=0)throw Error(`Cannot set session continuation token without an existing namespaced continuation token. Start the session with a placeholder continuationToken.`);return`${e.slice(0,n+1)}${t}`}function sessionCallbackToTurnCaller(e){return e===void 0?void 0:{callId:e.callId,replyTo:{kind:`callback`,token:e.token,url:e.url},subagentName:e.subagentName,taskId:e.taskId}}export{buildSessionHandle,createAttachSessionFn,createSession,sessionCallbackToTurnCaller};
1
+ import{createChannelDeliveryMetadata}from"#channel/delivery-metadata.js";import{serializeUrlFilePartsInMessage}from"#channel/send-input.js";import{DEFAULT_TURN_POLICY}from"#channel/types.js";import{parseInputResponses}from"#runtime/input/types.js";import{AuthKey,ContinuationTokenKey,InitiatorAuthKey,SessionIdKey}from"#context/keys.js";import{toChannelLocalContinuationToken}from"#shared/continuation-token.js";function createSession(e,i,a={}){return{id:e,async send(r,o){let s=createDelivery(a),c=sessionCallbackToTurnCaller(o.callback),l={message:serializeUrlFilePartsInMessage(r)};o.context!==void 0&&(l.context=o.context),o.outputSchema!==void 0&&(l.outputSchema=o.outputSchema);let u={auth:o.auth,delivery:s,kind:`send`,payload:l,requestId:a.requestId,turnPolicy:o.turnPolicy??a.turnPolicy??DEFAULT_TURN_POLICY};return await i.dispatchSession({command:c===void 0?u:{...u,caller:c},sessionId:e})},async respond(t,n){if(t.length===0)throw Error(`respond() requires at least one input response.`);let o=parseInputResponses(t),s=sessionCallbackToTurnCaller(n.callback),c=createDelivery(a),l={inputResponses:o};n.context!==void 0&&(l.context=n.context),n.outputSchema!==void 0&&(l.outputSchema=n.outputSchema);let u={auth:n.auth,delivery:c,kind:`send`,payload:l,requestId:a.requestId};return await i.dispatchSession({command:s===void 0?u:{...u,caller:s},sessionId:e})},async cancel(t){return await i.dispatchSession({command:{kind:`cancel`,taskId:t?.taskId,turnId:t?.turnId},sessionId:e})},async compact(){return await i.dispatchSession({command:{kind:`compact`},sessionId:e})},async clear(){return await i.dispatchSession({command:{kind:`clear`},sessionId:e})},async reset(t){return await i.dispatchSession({command:{kind:`reset`,reason:t?.reason},sessionId:e})},async getEventStream(t){return i.getEventStream(e,t)},async getStreamTailIndex(){return i.getStreamTailIndex(e)}}}function createAttachSessionFn(e,t={}){return n=>createSession(n,e,t)}function createDelivery(t){return t.channelKind!==void 0&&t.channelName!==void 0?createChannelDeliveryMetadata(t):void 0}function buildSessionHandle(e){return{get id(){return e.get(SessionIdKey)??``},get auth(){return{current:e.get(AuthKey)??null,initiator:e.get(InitiatorAuthKey)??null}},get continuation(){let t=e.get(ContinuationTokenKey);if(!(t===void 0||t.length===0))return{token:toChannelLocalContinuationToken(t),rekey(n){let r=namespaceContinuationToken(t,n);t!==r&&e.set(ContinuationTokenKey,r)}}}}}function namespaceContinuationToken(e,t){let n=e.indexOf(`:`);if(n<=0)throw Error(`Cannot set session continuation token without an existing namespaced continuation token. Start the session with a placeholder continuationToken.`);return`${e.slice(0,n+1)}${t}`}function sessionCallbackToTurnCaller(e){return e===void 0?void 0:{callId:e.callId,replyTo:{kind:`callback`,token:e.token,url:e.url},subagentName:e.subagentName,taskId:e.taskId}}export{buildSessionHandle,createAttachSessionFn,createSession,sessionCallbackToTurnCaller};
@@ -1075,6 +1075,7 @@ var ClientSession = class ClientSession {
1075
1075
  }
1076
1076
  async *#createEventStream(initialStreamIndex, input) {
1077
1077
  let eventCount = 0;
1078
+ const pendingAuthorizations = /* @__PURE__ */ new Set();
1078
1079
  try {
1079
1080
  for await (const event of this.#readStream({
1080
1081
  headers: input.headers,
@@ -1084,8 +1085,10 @@ var ClientSession = class ClientSession {
1084
1085
  streamReconnectPolicy: input.streamReconnectPolicy
1085
1086
  })) {
1086
1087
  eventCount += 1;
1088
+ if (event.type === "authorization.required" && event.data.webhookUrl !== void 0) pendingAuthorizations.add(event.data.name);
1089
+ else if (event.type === "authorization.completed") pendingAuthorizations.delete(event.data.name);
1087
1090
  yield event;
1088
- if (isCurrentTurnBoundaryEvent(event)) break;
1091
+ if (isCurrentTurnBoundaryEvent(event) && (event.type !== "session.waiting" || pendingAuthorizations.size === 0)) break;
1089
1092
  }
1090
1093
  } finally {
1091
1094
  this.#state = {
@@ -1075,6 +1075,7 @@ var ClientSession = class ClientSession {
1075
1075
  }
1076
1076
  async *#createEventStream(initialStreamIndex, input) {
1077
1077
  let eventCount = 0;
1078
+ const pendingAuthorizations = /* @__PURE__ */ new Set();
1078
1079
  try {
1079
1080
  for await (const event of this.#readStream({
1080
1081
  headers: input.headers,
@@ -1084,8 +1085,10 @@ var ClientSession = class ClientSession {
1084
1085
  streamReconnectPolicy: input.streamReconnectPolicy
1085
1086
  })) {
1086
1087
  eventCount += 1;
1088
+ if (event.type === "authorization.required" && event.data.webhookUrl !== void 0) pendingAuthorizations.add(event.data.name);
1089
+ else if (event.type === "authorization.completed") pendingAuthorizations.delete(event.data.name);
1087
1090
  yield event;
1088
- if (isCurrentTurnBoundaryEvent(event)) break;
1091
+ if (isCurrentTurnBoundaryEvent(event) && (event.type !== "session.waiting" || pendingAuthorizations.size === 0)) break;
1089
1092
  }
1090
1093
  } finally {
1091
1094
  this.#state = {
@@ -1 +1 @@
1
- import{summarizeToolArgs,summarizeToolResult}from"./tool-format.js";import{diffWriteDetail}from"./line-diff.js";import{stripTerminalControls}from"#cli/ui/terminal-text.js";const WRITE_FILE_VERB=`Write`,DELEGATE_VERB=`Delegate`,FINAL_OUTPUT_TITLE=`Return final output`,BUILTIN_TOOL_COPY={agent:{verb:`Delegate`,pastVerb:`Delegated`,argKey:`message`,singularNoun:`task`,pluralNoun:`tasks`},ask_question:{verb:`Ask`,pastVerb:`Asked`,argKey:`prompt`,singularNoun:`question`,pluralNoun:`questions`},bash:{verb:`Run`,pastVerb:`Ran`,argKey:`command`,singularNoun:`command`,pluralNoun:`commands`},connection_search:{verb:`Discover`,pastVerb:`Discovered`,argKey:`keywords`,singularNoun:`tool search`,pluralNoun:`tool searches`},glob:{verb:`Glob`,pastVerb:`Globbed`,argKey:`pattern`,singularNoun:`pattern`,pluralNoun:`patterns`},grep:{verb:`Grep`,pastVerb:`Grepped`,argKey:`pattern`,singularNoun:`pattern`,pluralNoun:`patterns`},load_skill:{verb:`Load`,pastVerb:`Loaded`,argKey:`skill`,singularNoun:`skill`,pluralNoun:`skills`},read_file:{verb:`Read`,pastVerb:`Read`,argKey:`filePath`,singularNoun:`file`,pluralNoun:`files`},task_cancel:{verb:`Cancel`,pastVerb:`Cancelled`,argKey:`taskIds`,extractItem:taskIdsArg,singularNoun:`task`,pluralNoun:`tasks`},task_sleep:{verb:`Pause`,pastVerb:`Paused`,argKey:`seconds`,extractItem:sleepSecondsArg,singularNoun:`pause`,pluralNoun:`pauses`},task_update:{verb:`Update`,pastVerb:`Updated`,argKey:`message`,singularNoun:`parent`,pluralNoun:`parents`},web_fetch:{verb:`Fetch`,pastVerb:`Fetched`,argKey:`url`,singularNoun:`URL`,pluralNoun:`URLs`},web_search:{verb:`Search`,pastVerb:`Searched`,argKey:`query`,extractItem:e=>salientArg(e,`objective`)??salientArg(e,`search_query`)??salientArg(e,`searchQuery`)??webSearchActionArg(e),singularNoun:`query`,pluralNoun:`queries`}};function presentWriteFileTool(a,o,s){let c=readWriteFileInput(a,o);if(c===void 0)return{title:a,subtitle:summarizeToolArgs(o),summarizeResult:summarizeToolResult};let l=diffWriteDetail(s?.previousContent,c.content,s?.existed).map(e=>e.kind===`gap`?e:{...e,text:stripTerminalControls(e.text)});return{title:`${WRITE_FILE_VERB} ${salientLine(c.path)??c.path}`,doneTitle:`Wrote ${salientLine(c.path)??c.path}`,subtitle:``,summarizeResult:()=>void 0,detail:l,keepDetailWhenDone:!0}}function readWriteFileInput(e,t){if(toolBaseName(e)!==`write_file`||typeof t!=`object`||!t||Array.isArray(t))return;let n=t,r=n.filePath,i=n.content;if(!(typeof r!=`string`||r.trim().length===0)&&typeof i==`string`)return{path:r,content:i}}function presentTool(n,r,i){let c=toolBaseName(n);if(c===`todo`)return presentTodoTool(r);if(c===`write_file`)return presentWriteFileTool(n,r,i);if(i?.isSubagent===!0)return{title:`${DELEGATE_VERB} ${c}`,doneTitle:`Delegated ${c}`,subtitle:salientArg(r,`message`)??``,summarizeResult:()=>void 0};if(c===`final_output`)return{title:FINAL_OUTPUT_TITLE,subtitle:``,summarizeResult:()=>void 0};let l=BUILTIN_TOOL_COPY[c];if(l!==void 0){let e=salientArg(r,l.argKey)??l.extractItem?.(r);if(e!==void 0)return{title:`${l.verb} ${e}`,doneTitle:`${l.pastVerb} ${e}`,subtitle:``,summarizeResult:()=>void 0,group:{verb:l.verb,pastVerb:l.pastVerb,singularNoun:l.singularNoun,pluralNoun:l.pluralNoun,item:e}}}return{title:n,subtitle:summarizeToolArgs(r),summarizeResult:summarizeToolResult}}function presentPreparingTool(e,t){let n=toolBaseName(e);if(n===`final_output`)return{title:FINAL_OUTPUT_TITLE,subtitle:``,summarizeResult:()=>void 0};if(t?.isSubagent===!0)return{title:`${DELEGATE_VERB} ${n} …`,subtitle:``,summarizeResult:()=>void 0};let r=n===`write_file`?WRITE_FILE_VERB:BUILTIN_TOOL_COPY[n]?.verb;return{title:r===void 0?e:`${r} …`,subtitle:r===void 0?`preparing…`:``,summarizeResult:()=>void 0}}function isPanelRoutedTool(e){let t=toolBaseName(e);return t===`todo`||t===`ask_question`}function toolBaseName(e){return e.split(/[.:/]/u).at(-1)??e}function presentTodoTool(e){let t=typeof e==`object`&&e&&!Array.isArray(e)?e.todos:void 0;return Array.isArray(t)?{title:`Update todo list`,subtitle:`${t.length} task${t.length===1?``:`s`}`,summarizeResult:()=>void 0}:{title:`Read todo list`,subtitle:``,summarizeResult:()=>void 0}}function webSearchActionArg(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e.action;if(typeof t!=`object`||!t||Array.isArray(t))return;let n=t,r=n.queries;if(Array.isArray(r)){let e=r.filter(e=>typeof e==`string`).map(salientLine).filter(e=>e!==void 0).join(`, `);if(e.length>0)return e}for(let e of[`query`,`url`,`pattern`]){let t=n[e];if(typeof t==`string`){let e=salientLine(t);if(e!==void 0)return e}}}function taskIdsArg(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e.taskIds;if(!Array.isArray(t))return;let n=t.filter(e=>typeof e==`string`);if(n.length!==0)return salientLine(n.join(`, `))}function sleepSecondsArg(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e.seconds;if(!(typeof t!=`number`||!Number.isFinite(t)))return`${String(t)}s`}function salientArg(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return;let n=e[t];if(typeof n==`string`)return salientLine(n)}function salientLine(e){let t=stripTerminalControls(e).split(/\r?\n/u).find(e=>e.trim().length>0)?.trim()??``;return t.length>0?t:void 0}export{isPanelRoutedTool,presentPreparingTool,presentTool,readWriteFileInput,toolBaseName};
1
+ import{summarizeToolArgs,summarizeToolResult}from"./tool-format.js";import{diffWriteDetail}from"./line-diff.js";import{stripTerminalControls}from"#cli/ui/terminal-text.js";const WRITE_FILE_VERB=`Write`,DELEGATE_VERB=`Delegate`,FINAL_OUTPUT_TITLE=`Return final output`,BUILTIN_TOOL_COPY={agent:{verb:`Delegate`,pastVerb:`Delegated`,argKey:`message`,singularNoun:`task`,pluralNoun:`tasks`},ask_question:{verb:`Ask`,pastVerb:`Asked`,argKey:`prompt`,singularNoun:`question`,pluralNoun:`questions`},bash:{verb:`Run`,pastVerb:`Ran`,argKey:`command`,singularNoun:`command`,pluralNoun:`commands`},connection_search:{verb:`Discover`,pastVerb:`Discovered`,argKey:`keywords`,singularNoun:`tool search`,pluralNoun:`tool searches`},glob:{verb:`Glob`,pastVerb:`Globbed`,argKey:`pattern`,singularNoun:`pattern`,pluralNoun:`patterns`},grep:{verb:`Grep`,pastVerb:`Grepped`,argKey:`pattern`,singularNoun:`pattern`,pluralNoun:`patterns`},load_skill:{verb:`Load`,pastVerb:`Loaded`,argKey:`skill`,singularNoun:`skill`,pluralNoun:`skills`},read_file:{verb:`Read`,pastVerb:`Read`,argKey:`filePath`,singularNoun:`file`,pluralNoun:`files`},task_cancel:{verb:`Cancel`,pastVerb:`Cancelled`,argKey:`taskIds`,extractItem:taskIdsArg,singularNoun:`task`,pluralNoun:`tasks`},task_update:{verb:`Update`,pastVerb:`Updated`,argKey:`message`,singularNoun:`parent`,pluralNoun:`parents`},web_fetch:{verb:`Fetch`,pastVerb:`Fetched`,argKey:`url`,singularNoun:`URL`,pluralNoun:`URLs`},web_search:{verb:`Search`,pastVerb:`Searched`,argKey:`query`,extractItem:e=>salientArg(e,`objective`)??salientArg(e,`search_query`)??salientArg(e,`searchQuery`)??webSearchActionArg(e),singularNoun:`query`,pluralNoun:`queries`}};function presentWriteFileTool(a,o,s){let c=readWriteFileInput(a,o);if(c===void 0)return{title:a,subtitle:summarizeToolArgs(o),summarizeResult:summarizeToolResult};let l=diffWriteDetail(s?.previousContent,c.content,s?.existed).map(e=>e.kind===`gap`?e:{...e,text:stripTerminalControls(e.text)});return{title:`${WRITE_FILE_VERB} ${salientLine(c.path)??c.path}`,doneTitle:`Wrote ${salientLine(c.path)??c.path}`,subtitle:``,summarizeResult:()=>void 0,detail:l,keepDetailWhenDone:!0}}function readWriteFileInput(e,t){if(toolBaseName(e)!==`write_file`||typeof t!=`object`||!t||Array.isArray(t))return;let n=t,r=n.filePath,i=n.content;if(!(typeof r!=`string`||r.trim().length===0)&&typeof i==`string`)return{path:r,content:i}}function presentTool(n,r,i){let c=toolBaseName(n);if(c===`todo`)return presentTodoTool(r);if(c===`write_file`)return presentWriteFileTool(n,r,i);if(i?.isSubagent===!0)return{title:`${DELEGATE_VERB} ${c}`,doneTitle:`Delegated ${c}`,subtitle:salientArg(r,`message`)??``,summarizeResult:()=>void 0};if(c===`final_output`)return{title:FINAL_OUTPUT_TITLE,subtitle:``,summarizeResult:()=>void 0};let l=BUILTIN_TOOL_COPY[c];if(l!==void 0){let e=salientArg(r,l.argKey)??l.extractItem?.(r);if(e!==void 0)return{title:`${l.verb} ${e}`,doneTitle:`${l.pastVerb} ${e}`,subtitle:``,summarizeResult:()=>void 0,group:{verb:l.verb,pastVerb:l.pastVerb,singularNoun:l.singularNoun,pluralNoun:l.pluralNoun,item:e}}}return{title:n,subtitle:summarizeToolArgs(r),summarizeResult:summarizeToolResult}}function presentPreparingTool(e,t){let n=toolBaseName(e);if(n===`final_output`)return{title:FINAL_OUTPUT_TITLE,subtitle:``,summarizeResult:()=>void 0};if(t?.isSubagent===!0)return{title:`${DELEGATE_VERB} ${n} …`,subtitle:``,summarizeResult:()=>void 0};let r=n===`write_file`?WRITE_FILE_VERB:BUILTIN_TOOL_COPY[n]?.verb;return{title:r===void 0?e:`${r} …`,subtitle:r===void 0?`preparing…`:``,summarizeResult:()=>void 0}}function isPanelRoutedTool(e){let t=toolBaseName(e);return t===`todo`||t===`ask_question`}function toolBaseName(e){return e.split(/[.:/]/u).at(-1)??e}function presentTodoTool(e){let t=typeof e==`object`&&e&&!Array.isArray(e)?e.todos:void 0;return Array.isArray(t)?{title:`Update todo list`,subtitle:`${t.length} task${t.length===1?``:`s`}`,summarizeResult:()=>void 0}:{title:`Read todo list`,subtitle:``,summarizeResult:()=>void 0}}function webSearchActionArg(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e.action;if(typeof t!=`object`||!t||Array.isArray(t))return;let n=t,r=n.queries;if(Array.isArray(r)){let e=r.filter(e=>typeof e==`string`).map(salientLine).filter(e=>e!==void 0).join(`, `);if(e.length>0)return e}for(let e of[`query`,`url`,`pattern`]){let t=n[e];if(typeof t==`string`){let e=salientLine(t);if(e!==void 0)return e}}}function taskIdsArg(e){if(typeof e!=`object`||!e||Array.isArray(e))return;let t=e.taskIds;if(!Array.isArray(t))return;let n=t.filter(e=>typeof e==`string`);if(n.length!==0)return salientLine(n.join(`, `))}function salientArg(e,t){if(typeof e!=`object`||!e||Array.isArray(e))return;let n=e[t];if(typeof n==`string`)return salientLine(n)}function salientLine(e){let t=stripTerminalControls(e).split(/\r?\n/u).find(e=>e.trim().length>0)?.trim()??``;return t.length>0?t:void 0}export{isPanelRoutedTool,presentPreparingTool,presentTool,readWriteFileInput,toolBaseName};
@@ -14,5 +14,5 @@ export type { EveAuthorizationChallenge, EveAuthorizationOutcome, EveAuthorizati
14
14
  export type { ActionPartialStreamEvent, ActionResultStreamEvent, ActionsRequestedStreamEvent, AssistantStepFinishReason, AuthorizationOutcome, CompactionCompletedStreamEvent, CompactionRequestedStreamEvent, AuthorizationCompletedStreamEvent, ConnectionAuthorizationOutcome, AuthorizationRequiredStreamEvent, HandleMessageStreamEvent, MessageStreamEventMeta, InputResolution, InputResolutionOutcome, InputResolvedStreamEvent, InputRequestedStreamEvent, MessageAppendedStreamEvent, MessageCompletedStreamEvent, MessageReceivedPart, MessageReceivedStreamEvent, ReasoningAppendedStreamEvent, ReasoningCompletedStreamEvent, ResultCompletedStreamEvent, RuntimeTraceContext, SessionCompletedStreamEvent, SessionFailedStreamEvent, SessionStartedStreamEvent, SessionWaitingStreamEvent, MessageStreamEvent, StepCompletedStreamEvent, StepFailedStreamEvent, StepStartedStreamEvent, SubagentCalledStreamEvent, SubagentChildEventStreamEvent, SubagentCompletedStreamEvent, SubagentStartedStreamEvent, TurnCancelledStreamEvent, TurnCompletedStreamEvent, TurnFailedStreamEvent, TurnStartedStreamEvent, TurnFailureStreamEvent, } from "#protocol/message.js";
15
15
  export { isCurrentTurnBoundaryEvent, isTurnFailureEvent } from "#protocol/message.js";
16
16
  export type { InputOption, InputRequest, InputRequestKind, InputResponse, } from "#runtime/input/types.js";
17
- export { inputOptionSchema, inputRequestKindSchema, inputRequestSchema, inputResponseSchema, isInputRequest, isInputResponse, } from "#runtime/input/types.js";
17
+ export { inputOptionSchema, inputRequestKindSchema, inputRequestSchema, inputResponseSchema, isInputRequest, isInputResponse, parseInputResponse, parseInputResponses, } from "#runtime/input/types.js";
18
18
  export { resolveTextToResponse, resolveTextToResponses } from "#channel/resolve-text.js";
@@ -1 +1 @@
1
- import{isCurrentTurnBoundaryEvent,isTurnFailureEvent}from"#protocol/message.js";import{AgentInfoResponseError}from"#client/agent-info-error.js";import{ClientError}from"#client/client-error.js";import{ClientSessions}from"#client/sessions.js";import{Client}from"#client/client.js";import{EveAgentStore}from"#client/eve-agent-store.js";import{defaultMessageReducer}from"#client/message-reducer.js";import{createDataUrlFilePart,createTextWithFileContent}from"#client/file-parts.js";import{MessageResponse}from"#client/message-response.js";import{ClientSession}from"#client/session.js";import{inputOptionSchema,inputRequestKindSchema,inputRequestSchema,inputResponseSchema,isInputRequest,isInputResponse}from"#runtime/input/types.js";import{resolveTextToResponse,resolveTextToResponses}from"#channel/resolve-text.js";export{AgentInfoResponseError,Client,ClientError,ClientSession,ClientSessions,EveAgentStore,MessageResponse,createDataUrlFilePart,createTextWithFileContent,defaultMessageReducer,inputOptionSchema,inputRequestKindSchema,inputRequestSchema,inputResponseSchema,isCurrentTurnBoundaryEvent,isInputRequest,isInputResponse,isTurnFailureEvent,resolveTextToResponse,resolveTextToResponses};
1
+ import{inputOptionSchema,inputRequestKindSchema,inputRequestSchema,inputResponseSchema,isInputRequest,isInputResponse,parseInputResponse,parseInputResponses}from"#runtime/input/types.js";import{isCurrentTurnBoundaryEvent,isTurnFailureEvent}from"#protocol/message.js";import{AgentInfoResponseError}from"#client/agent-info-error.js";import{ClientError}from"#client/client-error.js";import{ClientSessions}from"#client/sessions.js";import{Client}from"#client/client.js";import{EveAgentStore}from"#client/eve-agent-store.js";import{defaultMessageReducer}from"#client/message-reducer.js";import{createDataUrlFilePart,createTextWithFileContent}from"#client/file-parts.js";import{MessageResponse}from"#client/message-response.js";import{ClientSession}from"#client/session.js";import{resolveTextToResponse,resolveTextToResponses}from"#channel/resolve-text.js";export{AgentInfoResponseError,Client,ClientError,ClientSession,ClientSessions,EveAgentStore,MessageResponse,createDataUrlFilePart,createTextWithFileContent,defaultMessageReducer,inputOptionSchema,inputRequestKindSchema,inputRequestSchema,inputResponseSchema,isCurrentTurnBoundaryEvent,isInputRequest,isInputResponse,isTurnFailureEvent,parseInputResponse,parseInputResponses,resolveTextToResponse,resolveTextToResponses};
@@ -1 +1 @@
1
- import{EVE_SESSION_ROUTE_PATH,createEveSessionRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER,isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{ClientError}from"#client/client-error.js";import{createClientUrl}from"#client/url.js";import{MessageResponse}from"#client/message-response.js";import{followStreamIterable}from"#client/open-stream.js";import{cancelClientSession,clearClientSession,compactClientSession,resetClientSession}from"#client/session-controls.js";import{serializeOutputSchema}from"#shared/tool-schema.js";var ClientSession=class ClientSession{#e;#t;constructor(e,t){this.#e=e,this.#t=t}static async create(t,n){let r=await postTurn(t,EVE_SESSION_ROUTE_PATH,n,!0),i=await readSessionId(r),a=new ClientSession(t,{sessionId:i,streamIndex:0});return{response:a.#r(r,n,0),session:a}}get state(){return this.#t}async snapshot(e){e?.signal?.throwIfAborted();let t=[];for await(let n of this.#o({follow:!1,signal:e?.signal,startIndex:0}))t.push(n);return e?.signal?.throwIfAborted(),{events:t,session:{sessionId:this.#t.sessionId,streamIndex:t.length}}}async send(e,t={}){return await this.#n({...t,message:e})}async respond(e,t={}){if(e.length===0)throw Error(`ClientSession.respond() requires at least one input response.`);return await this.#n({...t,inputResponses:e})}async#n(e){let n=this.#t.streamIndex,r=await postTurn(this.#e,createEveSessionRoutePath(this.#t.sessionId),e,!1);if(await readSessionId(r,this.#t.sessionId)!==this.#t.sessionId)throw Error(`Message route returned a different session id.`);return this.#r(r,e,n)}async cancel(e){return await cancelClientSession({context:this.#e,options:e,sessionId:this.#t.sessionId})}async clear(){return await clearClientSession({context:this.#e,sessionId:this.#t.sessionId})}async compact(){return await compactClientSession({context:this.#e,sessionId:this.#t.sessionId})}async reset(e){return await resetClientSession({context:this.#e,options:e,sessionId:this.#t.sessionId})}stream(e){if(e?.follow===!1&&(e.startIndex??this.#t.streamIndex)<0)throw Error(`stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.`);return this.#a(e)}#r(e,t,n){return e.body?.cancel().catch(()=>{}),new MessageResponse({cancelTurn:async e=>await this.cancel({turnId:e}),createStream:()=>this.#i(n,t),sessionId:this.#t.sessionId})}async*#i(e,t){let n=0;try{for await(let i of this.#o({headers:t.headers,keepAlive:shouldKeepActiveTurnAlive(t.streamReconnectPolicy),signal:t.signal,startIndex:e,streamReconnectPolicy:t.streamReconnectPolicy}))if(n+=1,yield i,isCurrentTurnBoundaryEvent(i))break}finally{this.#t={sessionId:this.#t.sessionId,streamIndex:e+n}}}async*#a(e){let t=e?.startIndex??this.#t.streamIndex,n=0;try{for await(let r of this.#o({follow:e?.follow,signal:e?.signal,startIndex:t,streamReconnectPolicy:e?.streamReconnectPolicy}))n+=1,yield r}finally{t>=0&&(this.#t={sessionId:this.#t.sessionId,streamIndex:t+n})}}#o(e){return followStreamIterable({follow:e.follow,host:this.#e.host,keepAlive:e.keepAlive,resolveHeaders:()=>this.#e.resolveHeaders(e.headers),redirect:this.#e.redirect,sessionId:this.#t.sessionId,signal:e.signal,startIndex:e.startIndex,streamReconnectPolicy:e.streamReconnectPolicy})}};function shouldKeepActiveTurnAlive(e){return e&&`reconnect`in e?!1:e?.streamIdleReconnectPolicy?.maxAttempts===void 0}async function postTurn(e,t,n,r){let o=createMessageBody(n,r);if(o===null)throw Error(r?`Creating a session requires a non-empty message.`:`A session turn requires a non-empty message or inputResponses.`);let s=await e.resolveHeaders(n.headers);s.set(`content-type`,`application/json`);let c=await fetch(createClientUrl(e.host,t),{body:JSON.stringify(o),headers:s,method:`POST`,redirect:e.redirect,signal:n.signal??null});if(!c.ok){let e=await c.text();throw new ClientError(c.status,e,c.headers)}return c}async function readSessionId(e,t){let r=await e.json(),i=(typeof r.sessionId==`string`?r.sessionId:void 0)??e.headers.get(EVE_SESSION_ID_HEADER)?.trim()??t;if(!i)throw Error(`Message route did not return a session id.`);return i}function createMessageBody(e,t){let n={};e.message!==void 0&&(n.message=e.message),e.inputResponses!==void 0&&e.inputResponses.length>0&&(n.inputResponses=e.inputResponses),!t&&e.message!==void 0&&e.turnPolicy!==void 0&&(n.turnPolicy=e.turnPolicy),e.clientContext!==void 0&&(n.clientContext=e.clientContext);let r=serializeOutputSchema(e.outputSchema);return r!==void 0&&(n.outputSchema=r),t&&n.message===void 0||n.message===void 0&&n.inputResponses===void 0?null:n}export{ClientSession};
1
+ import{EVE_SESSION_ROUTE_PATH,createEveSessionRoutePath}from"#protocol/routes.js";import{EVE_SESSION_ID_HEADER,isCurrentTurnBoundaryEvent}from"#protocol/message.js";import{ClientError}from"#client/client-error.js";import{createClientUrl}from"#client/url.js";import{MessageResponse}from"#client/message-response.js";import{followStreamIterable}from"#client/open-stream.js";import{cancelClientSession,clearClientSession,compactClientSession,resetClientSession}from"#client/session-controls.js";import{serializeOutputSchema}from"#shared/tool-schema.js";var ClientSession=class ClientSession{#e;#t;constructor(e,t){this.#e=e,this.#t=t}static async create(t,n){let r=await postTurn(t,EVE_SESSION_ROUTE_PATH,n,!0),i=await readSessionId(r),a=new ClientSession(t,{sessionId:i,streamIndex:0});return{response:a.#r(r,n,0),session:a}}get state(){return this.#t}async snapshot(e){e?.signal?.throwIfAborted();let t=[];for await(let n of this.#o({follow:!1,signal:e?.signal,startIndex:0}))t.push(n);return e?.signal?.throwIfAborted(),{events:t,session:{sessionId:this.#t.sessionId,streamIndex:t.length}}}async send(e,t={}){return await this.#n({...t,message:e})}async respond(e,t={}){if(e.length===0)throw Error(`ClientSession.respond() requires at least one input response.`);return await this.#n({...t,inputResponses:e})}async#n(e){let n=this.#t.streamIndex,r=await postTurn(this.#e,createEveSessionRoutePath(this.#t.sessionId),e,!1);if(await readSessionId(r,this.#t.sessionId)!==this.#t.sessionId)throw Error(`Message route returned a different session id.`);return this.#r(r,e,n)}async cancel(e){return await cancelClientSession({context:this.#e,options:e,sessionId:this.#t.sessionId})}async clear(){return await clearClientSession({context:this.#e,sessionId:this.#t.sessionId})}async compact(){return await compactClientSession({context:this.#e,sessionId:this.#t.sessionId})}async reset(e){return await resetClientSession({context:this.#e,options:e,sessionId:this.#t.sessionId})}stream(e){if(e?.follow===!1&&(e.startIndex??this.#t.streamIndex)<0)throw Error(`stream({ follow: false }) requires a nonnegative startIndex; a tail-relative cursor cannot be bounded.`);return this.#a(e)}#r(e,t,n){return e.body?.cancel().catch(()=>{}),new MessageResponse({cancelTurn:async e=>await this.cancel({turnId:e}),createStream:()=>this.#i(n,t),sessionId:this.#t.sessionId})}async*#i(e,t){let n=0,i=new Set;try{for await(let a of this.#o({headers:t.headers,keepAlive:shouldKeepActiveTurnAlive(t.streamReconnectPolicy),signal:t.signal,startIndex:e,streamReconnectPolicy:t.streamReconnectPolicy}))if(n+=1,a.type===`authorization.required`&&a.data.webhookUrl!==void 0?i.add(a.data.name):a.type===`authorization.completed`&&i.delete(a.data.name),yield a,isCurrentTurnBoundaryEvent(a)&&(a.type!==`session.waiting`||i.size===0))break}finally{this.#t={sessionId:this.#t.sessionId,streamIndex:e+n}}}async*#a(e){let t=e?.startIndex??this.#t.streamIndex,n=0;try{for await(let r of this.#o({follow:e?.follow,signal:e?.signal,startIndex:t,streamReconnectPolicy:e?.streamReconnectPolicy}))n+=1,yield r}finally{t>=0&&(this.#t={sessionId:this.#t.sessionId,streamIndex:t+n})}}#o(e){return followStreamIterable({follow:e.follow,host:this.#e.host,keepAlive:e.keepAlive,resolveHeaders:()=>this.#e.resolveHeaders(e.headers),redirect:this.#e.redirect,sessionId:this.#t.sessionId,signal:e.signal,startIndex:e.startIndex,streamReconnectPolicy:e.streamReconnectPolicy})}};function shouldKeepActiveTurnAlive(e){return e&&`reconnect`in e?!1:e?.streamIdleReconnectPolicy?.maxAttempts===void 0}async function postTurn(e,t,n,r){let o=createMessageBody(n,r);if(o===null)throw Error(r?`Creating a session requires a non-empty message.`:`A session turn requires a non-empty message or inputResponses.`);let s=await e.resolveHeaders(n.headers);s.set(`content-type`,`application/json`);let c=await fetch(createClientUrl(e.host,t),{body:JSON.stringify(o),headers:s,method:`POST`,redirect:e.redirect,signal:n.signal??null});if(!c.ok){let e=await c.text();throw new ClientError(c.status,e,c.headers)}return c}async function readSessionId(e,t){let r=await e.json(),i=(typeof r.sessionId==`string`?r.sessionId:void 0)??e.headers.get(EVE_SESSION_ID_HEADER)?.trim()??t;if(!i)throw Error(`Message route did not return a session id.`);return i}function createMessageBody(e,t){let n={};e.message!==void 0&&(n.message=e.message),e.inputResponses!==void 0&&e.inputResponses.length>0&&(n.inputResponses=e.inputResponses),!t&&e.message!==void 0&&e.turnPolicy!==void 0&&(n.turnPolicy=e.turnPolicy),e.clientContext!==void 0&&(n.clientContext=e.clientContext);let r=serializeOutputSchema(e.outputSchema);return r!==void 0&&(n.outputSchema=r),t&&n.message===void 0||n.message===void 0&&n.inputResponses===void 0?null:n}export{ClientSession};
@@ -24,6 +24,7 @@
24
24
  "@opentelemetry/otlp-transformer": "0.214.0",
25
25
  "@ai-sdk/otel": "1.0.58",
26
26
  "@photon-ai/chat-adapter-imessage": "3.2.0",
27
+ "@linqapp/chat-sdk-adapter": "0.3.0",
27
28
  "picocolors": "1.1.1",
28
29
  "@ai-sdk/provider": "4.0.7",
29
30
  "@ai-sdk/provider-utils": "5.0.25",
@@ -45,7 +46,7 @@
45
46
  "zod": "4.4.3",
46
47
  "zod-validation-error": "5.0.0"
47
48
  },
48
- "scriptHash": "e66658986492437f65202c761d4df792eeb66bdfe9f2d3cf35b76a395ea0834f",
49
+ "scriptHash": "3df641b560424ccb204931fa6e23d3cfbb23d4068df6a553db4574dda958a32a",
49
50
  "toolVersions": {
50
51
  "rolldown": "1.1.5"
51
52
  }
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Linq
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,3 @@
1
+ export { createLinqAdapter } from "./adapter.js";
2
+ export type { LinqAdapterConfig, LinqCredentialProvider, LinqCredentials, LinqWebhookVerifier, } from "./adapter.js";
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,8 @@
1
+ import{t as e}from"../../_chunks/node/rolldown-runtime-DaDcL9Zw.js";import{B as t,C as n,Et as r,K as i,Pt as a,b as o,jt as s,kt as c,q as l,tt as u,u as d,wt as f}from"../../_chunks/node/dist-C3lNQvLX.js";function p(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function m(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}let h=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return h=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))};function g(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}const _=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};var v=class extends Error{},y=class e extends v{constructor(t,n,r,i){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.error=n;let a=n;this.code=a?.code,this.doc_url=a?.doc_url,this.retry_after=a?.retry_after}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new x({message:r,cause:_(n)});let a=n?.error;return t===400?new C(t,a,r,i):t===401?new w(t,a,r,i):t===403?new T(t,a,r,i):t===404?new E(t,a,r,i):t===409?new D(t,a,r,i):t===422?new ee(t,a,r,i):t===429?new te(t,a,r,i):t>=500?new ne(t,a,r,i):new e(t,a,r,i)}},b=class extends y{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},x=class extends y{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},S=class extends x{constructor({message:e}={}){super({message:e??`Request timed out.`})}},C=class extends y{},w=class extends y{},T=class extends y{},E=class extends y{},D=class extends y{},ee=class extends y{},te=class extends y{},ne=class extends y{};const re=/^[a-z][a-z0-9+.-]*:/i,ie=e=>re.test(e);let O=e=>(O=Array.isArray,O(e)),ae=O;function oe(e){return typeof e==`object`?e??{}:{}}function se(e){if(!e)return!0;for(let t in e)return!1;return!0}function ce(e,t){return Object.prototype.hasOwnProperty.call(e,t)}const le=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new v(`${e} must be an integer`);if(t<0)throw new v(`${e} must be a positive integer`);return t},ue=e=>{try{return JSON.parse(e)}catch{return}},de=e=>new Promise(t=>setTimeout(t,e)),k=`0.40.0`;function fe(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}const pe=()=>{let e=fe();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":k,"X-Stainless-OS":ge(Deno.build.os),"X-Stainless-Arch":he(Deno.build.arch),"X-Stainless-Runtime":`deno`,"X-Stainless-Runtime-Version":typeof Deno.version==`string`?Deno.version:Deno.version?.deno??`unknown`};if(typeof EdgeRuntime<`u`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":k,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":k,"X-Stainless-OS":ge(globalThis.process.platform??`unknown`),"X-Stainless-Arch":he(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=me();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":k,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":k,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function me(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{key:`edge`,pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`ie`,pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`chrome`,pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`firefox`,pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:`safari`,pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}const he=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,ge=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`);let _e;const ve=()=>_e??=pe();function ye(){if(typeof fetch<`u`)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new LinqAPIV3({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function be(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function xe(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return be({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}async function Se(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}const Ce=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)}),we=`RFC3986`,Te=e=>String(e),Ee={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:Te};let A=(e,t)=>(A=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),A(e,t));const j=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),M=1024,De=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,function(e){return`%26%23`+parseInt(e.slice(2),16)+`%3B`});let o=``;for(let e=0;e<a.length;e+=M){let t=a.length>=M?a.slice(e,e+M):a,n=[];for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r===45||r===46||r===95||r===126||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||i===`RFC1738`&&(r===40||r===41)){n[n.length]=t.charAt(e);continue}if(r<128){n[n.length]=j[r];continue}if(r<2048){n[n.length]=j[192|r>>6]+j[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=j[224|r>>12]+j[128|r>>6&63]+j[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=j[240|r>>18]+j[128|r>>12&63]+j[128|r>>6&63]+j[128|r&63]}o+=n.join(``)}return o};function Oe(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function ke(e,t){if(O(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}const Ae={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},je=function(e,t){Array.prototype.push.apply(e,O(t)?t:[t])};let Me;const N={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:De,encodeValuesOnly:!1,format:we,formatter:Te,indices:!1,serializeDate(e){return(Me??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function Ne(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}const P={};function Pe(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){let v=e,y=_,b=0,x=!1;for(;(y=y.get(P))!==void 0&&!x;){let t=y.get(e);if(b+=1,t!==void 0){if(t===b)throw RangeError(`Cyclic object value`);x=!0}y.get(P)===void 0&&(b=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&O(v)&&(v=ke(v,function(e){return e instanceof Date?f?.(e):e})),v===null){if(a)return c&&!h?c(t,N.encoder,g,`key`,p):t;v=``}if(Ne(v)||Oe(v)){if(c){let e=h?t:c(t,N.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,N.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let S=[];if(v===void 0)return S;let C;if(n===`comma`&&O(v))h&&c&&(v=ke(v,c)),C=[{value:v.length>0?v.join(`,`)||null:void 0}];else if(O(l))C=l;else{let e=Object.keys(v);C=u?e.sort(u):e}let w=s?String(t).replace(/\./g,`%2E`):String(t),T=r&&O(v)&&v.length===1?w+`[]`:w;if(i&&O(v)&&v.length===0)return T+`[]`;for(let t=0;t<C.length;++t){let y=C[t],x=typeof y==`object`&&y.value!==void 0?y.value:v[y];if(o&&x===null)continue;let w=d&&s?y.replace(/\./g,`%2E`):y,E=O(v)?typeof n==`function`?n(T,w):T:T+(d?`.`+w:`[`+w+`]`);_.set(e,b);let D=new WeakMap;D.set(P,_),je(S,Pe(x,E,n,r,i,a,o,s,n===`comma`&&h&&O(v)?null:c,l,u,d,f,p,m,h,g,D))}return S}function Fe(e=N){if(e.allowEmptyArrays!==void 0&&typeof e.allowEmptyArrays!=`boolean`)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(e.encodeDotInKeys!==void 0&&typeof e.encodeDotInKeys!=`boolean`)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&e.encoder!==void 0&&typeof e.encoder!=`function`)throw TypeError(`Encoder has to be a function.`);let t=e.charset||N.charset;if(e.charset!==void 0&&e.charset!==`utf-8`&&e.charset!==`iso-8859-1`)throw TypeError(`The charset option must be either utf-8, iso-8859-1, or undefined`);let n=we;if(e.format!==void 0){if(!A(Ee,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=Ee[n],i=N.filter;(typeof e.filter==`function`||O(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in Ae?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:N.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o=e.allowDots===void 0?e.encodeDotInKeys?!0:N.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:N.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:N.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:N.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?N.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:N.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:N.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:N.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:N.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:N.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:N.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:N.strictNullHandling}}function Ie(e,t={}){let n=e,r=Fe(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):O(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=Ae[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||=Object.keys(n),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e=0;e<i.length;++e){let t=i[e];r.skipNulls&&n[t]===null||je(o,Pe(n[t],t,s,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l))}let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(r.charset===`iso-8859-1`?d+=`utf8=%26%2310003%3B&`:d+=`utf8=%E2%9C%93&`),u.length>0?d+u:``}function Le(e){return Ie(e,{arrayFormat:`comma`})}const F={off:0,error:200,warn:300,info:400,debug:500},Re=(e,t,n)=>{if(e){if(ce(F,e))return e;R(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(F))}`)}};function I(){}function L(e,t,n){return!t||F[e]>F[n]?I:t[e].bind(t)}const ze={error:I,warn:I,info:I,debug:I};let Be=new WeakMap;function R(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return ze;let r=Be.get(t);if(r&&r[0]===n)return r[1];let i={error:L(`error`,t,n),warn:L(`warn`,t,n),info:L(`info`,t,n),debug:L(`debug`,t,n)};return Be.set(t,[n,i]),i}const z=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`authorization`||e.toLowerCase()===`api-key`||e.toLowerCase()===`x-api-key`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);async function Ve(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(n.status===204)return null;if(t.options.__binaryResponse)return n;let e=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return e?.includes(`application/json`)||e?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:await n.json():await n.text()})();return R(e).debug(`[${r}] response parsed`,z({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}var B,He=class e extends Promise{constructor(e,t,n=Ve){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,B.set(this,void 0),p(this,B,e,`f`)}_thenUnwrap(t){return new e(m(this,B,`f`),this.responsePromise,async(e,n)=>t(await this.parseResponse(e,n),n))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(m(this,B,`f`),e)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};B=new WeakMap;var V,Ue=class{constructor(e,t,n,r){V.set(this,void 0),p(this,V,e,`f`),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new v("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await m(this,V,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(V=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},We=class extends He{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await Ve(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},Ge=class extends Ue{constructor(e,t,n,r){super(e,t,n,r),this.chats=n.chats||[],this.next_cursor=n.next_cursor||``}getPaginatedItems(){return this.chats??[]}nextPageRequestOptions(){let e=this.next_cursor;return e?{...this.options,query:{...oe(this.options.query),cursor:e}}:null}},Ke=class extends Ue{constructor(e,t,n,r){super(e,t,n,r),this.messages=n.messages||[],this.next_cursor=n.next_cursor||``}getPaginatedItems(){return this.messages??[]}nextPageRequestOptions(){let e=this.next_cursor;return e?{...this.options,query:{...oe(this.options.query),cursor:e}}:null}};const qe=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function H(e,t,n){return qe(),new File(e,t??`unknown_file`,n)}function Je(e){return(typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``).split(/[\\/]/).pop()||void 0}const Ye=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,Xe=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,Ze=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&Xe(e),Qe=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function $e(e,t,n){if(qe(),e=await e,Ze(e))return e instanceof File?e:H([await e.arrayBuffer()],e.name);if(Qe(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),H(await U(r),t,n)}let r=await U(e);if(t||=Je(e),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return H(r,t,n)}async function U(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Xe(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(Ye(e))for await(let n of e)t.push(...await U(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${et(e)}`)}return t}function et(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var W=class{constructor(e){this._client=e}};const tt=Symbol(`brand.privateNullableHeaders`);function*nt(e){if(!e)return;if(tt in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():ae(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=ae(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}const G=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of nt(r)){let r=i.toLowerCase();e.has(r)||(t.delete(i),e.add(r)),a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r))}}return{[tt]:!0,values:t,nulls:n}};function rt(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const it=Object.freeze(Object.create(null)),K=((e=rt)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],a=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??it)??it)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),o=a.split(/[?#]/,1)[0],s=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=s.exec(o))!==null;)i.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can\'t be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new v(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
2
+ `)}\n${a}\n${t}`)}return a})(rt);var at=class extends W{create(e,t){return this._client.post(`/v3/attachments`,{body:e,...t})}retrieve(e,t){return this._client.get(K`/v3/attachments/${e}`,t)}delete(e,t){return this._client.delete(K`/v3/attachments/${e}`,{...t,headers:G([{Accept:`*/*`},t?.headers])})}},ot=class extends W{retrieve(e={},t){return this._client.get(`/v3/available_number`,{query:e,...t})}},st=class extends W{list(e){return this._client.get(`/v3/blocked_handles`,e)}block(e,t){return this._client.post(`/v3/blocked_handles`,{body:e,...t})}unblock(e,t){return this._client.delete(`/v3/blocked_handles`,{body:e,...t,headers:G([{Accept:`*/*`},t?.headers])})}},ct=class extends W{checkIMessage(e,t){return this._client.post(`/v3/capability/check_imessage`,{body:e,...t})}checkRCS(e,t){return this._client.post(`/v3/capability/check_rcs`,{body:e,...t})}},lt=class extends W{remove(e,t){return this._client.delete(K`/v3/chats/${e}/background`,{...t,headers:G([{Accept:`*/*`},t?.headers])})}set(e,t,n){return this._client.post(K`/v3/chats/${e}/background`,{body:t,...n,headers:G([{Accept:`*/*`},n?.headers])})}},ut=class extends W{retrieve(e,t){return this._client.get(K`/v3/chats/${e}/location`,{...t,headers:G([{Accept:`application/geo+json`},t?.headers])})}request(e,t){return this._client.post(K`/v3/chats/${e}/location/request`,t)}},dt=class extends W{list(e,t={},n){return this._client.getAPIList(K`/v3/chats/${e}/messages`,Ke,{query:t,...n})}send(e,t,n){return this._client.post(K`/v3/chats/${e}/messages`,{body:t,...n})}},ft=class extends W{add(e,t,n){return this._client.post(K`/v3/chats/${e}/participants`,{body:t,...n})}remove(e,t,n){return this._client.delete(K`/v3/chats/${e}/participants`,{body:t,...n})}},pt=class extends W{create(e,t,n){return this._client.post(K`/v3/chats/${e}/polls`,{body:t,...n})}},mt=class extends W{start(e,t){return this._client.post(K`/v3/chats/${e}/typing`,{...t,headers:G([{Accept:`*/*`},t?.headers])})}stop(e,t){return this._client.delete(K`/v3/chats/${e}/typing`,{...t,headers:G([{Accept:`*/*`},t?.headers])})}},q=class extends W{constructor(){super(...arguments),this.participants=new ft(this._client),this.typing=new mt(this._client),this.messages=new dt(this._client),this.location=new ut(this._client),this.polls=new pt(this._client),this.background=new lt(this._client)}create(e,t){return this._client.post(`/v3/chats`,{body:e,...t})}retrieve(e,t){return this._client.get(K`/v3/chats/${e}`,t)}update(e,t,n){return this._client.put(K`/v3/chats/${e}`,{body:t,...n})}leaveChat(e,t){return this._client.post(K`/v3/chats/${e}/leave`,t)}listChats(e={},t){return this._client.getAPIList(`/v3/chats`,Ge,{query:e,...t})}markAsRead(e,t){return this._client.post(K`/v3/chats/${e}/read`,{...t,headers:G([{Accept:`*/*`},t?.headers])})}sendVoicememo(e,t,n){return this._client.post(K`/v3/chats/${e}/voicememo`,{body:t,...n})}shareContactCard(e,t){return this._client.post(K`/v3/chats/${e}/share_contact_card`,{...t,headers:G([{Accept:`*/*`},t?.headers])})}};q.Participants=ft,q.Typing=mt,q.Messages=dt,q.Location=ut,q.Polls=pt,q.Background=lt;var ht=class extends W{create(e,t){return this._client.post(`/v3/contact_card`,{body:e,...t})}retrieve(e={},t){return this._client.get(`/v3/contact_card`,{query:e,...t})}update(e,t){let{phone_number:n,...r}=e;return this._client.patch(`/v3/contact_card`,{query:{phone_number:n},body:r,...t})}},gt=class extends W{retrieve(e,t){return this._client.get(K`/v3/experiences/${e}`,t)}list(e){return this._client.get(`/v3/experiences`,e)}},_t=class extends W{retrieve(e,t){return this._client.get(K`/v3/messages/${e}/poll`,t)}addOptions(e,t,n){return this._client.post(K`/v3/messages/${e}/poll/options`,{body:t,...n})}vote(e,t,n){return this._client.post(K`/v3/messages/${e}/poll/votes`,{body:t,...n})}},J=class extends W{constructor(){super(...arguments),this.poll=new _t(this._client)}create(e,t){let{"Idempotency-Key":n,...r}=e;return this._client.post(`/v3/messages`,{body:r,...t,headers:G([{...n==null?void 0:{"Idempotency-Key":n}},t?.headers])})}retrieve(e,t){return this._client.get(K`/v3/messages/${e}`,t)}update(e,t,n){return this._client.patch(K`/v3/messages/${e}`,{body:t,...n})}delete(e,t){return this._client.delete(K`/v3/messages/${e}`,{...t,headers:G([{Accept:`*/*`},t?.headers])})}addReaction(e,t,n){return this._client.post(K`/v3/messages/${e}/reactions`,{body:t,...n})}listMessagesThread(e,t={},n){return this._client.getAPIList(K`/v3/messages/${e}/thread`,Ke,{query:t,...n})}updateAppCard(e,t,n){return this._client.post(K`/v3/messages/${e}/update`,{body:t,...n})}};J.Poll=_t;var vt=class extends W{connect(e,t){return this._client.post(K`/v3/payments/handles/${e}/connect`,t)}connection(e,t){return this._client.get(K`/v3/payments/handles/${e}/connection`,t)}revoke(e,t){return this._client.delete(K`/v3/payments/handles/${e}/connection`,t)}verify(e,t,n){return this._client.post(K`/v3/payments/handles/${e}/verify`,{body:t,...n})}},yt=class extends W{retrieve(e,t){return this._client.get(K`/v3/payments/providers/${e}`,t)}connect(e,t,n){return this._client.post(K`/v3/payments/providers/${e}/connect`,{body:t,...n})}},bt=class extends W{create(e,t){let{"Idempotency-Key":n,...r}=e;return this._client.post(`/v3/payment_requests`,{body:r,...t,headers:G([{...n==null?void 0:{"Idempotency-Key":n}},t?.headers])})}retrieve(e,t){return this._client.get(K`/v3/payment_requests/${e}`,t)}list(e={},t){return this._client.get(`/v3/payment_requests`,{query:e,...t})}cancel(e,t){return this._client.post(K`/v3/payment_requests/${e}/cancel`,t)}},xt=class extends W{create(e,t){return this._client.post(`/v3/payments`,{body:e,...t})}retrieve(e,t){return this._client.get(K`/v3/payments/${e}`,t)}cancel(e,t){return this._client.post(K`/v3/payments/${e}/cancel`,t)}credentials(e,t){return this._client.get(K`/v3/payments/${e}/credentials`,t)}},St=class extends W{update(e,t,n){return this._client.put(K`/v3/phone_numbers/${e}`,{body:t,...n})}list(e){return this._client.get(`/v3/phone_numbers`,e)}getReputationAudit(e,t,n){let{phoneNumber:r}=t;return this._client.get(K`/v3/phone_numbers/${r}/reputation_audit/${e}`,n)}startReputationAudit(e,t){return this._client.post(K`/v3/phone_numbers/${e}/reputation_audit`,t)}},Ct=class extends W{list(e){return this._client.get(`/v3/phonenumbers`,e)}},wt=class extends W{list(e){return this._client.get(`/v3/webhook-events`,e)}},Tt=class extends W{create(e,t){return this._client.post(`/v3/webhook-subscriptions`,{body:e,...t})}retrieve(e,t){return this._client.get(K`/v3/webhook-subscriptions/${e}`,t)}update(e,t,n){return this._client.put(K`/v3/webhook-subscriptions/${e}`,{body:t,...n})}list(e){return this._client.get(`/v3/webhook-subscriptions`,e)}delete(e,t){return this._client.delete(K`/v3/webhook-subscriptions/${e}`,{...t,headers:G([{Accept:`*/*`},t?.headers])})}},Et=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.timingSafeEqual=void 0;function t(e,t=``){if(!e)throw Error(t)}function n(e,n){if(e.byteLength!==n.byteLength)return!1;e instanceof DataView||(e=new DataView(ArrayBuffer.isView(e)?e.buffer:e)),n instanceof DataView||(n=new DataView(ArrayBuffer.isView(n)?n.buffer:n)),t(e instanceof DataView),t(n instanceof DataView);let r=e.byteLength,i=0,a=-1;for(;++a<r;)i|=e.getUint8(a)^n.getUint8(a);return i===0}e.timingSafeEqual=n})),Dt=e((e=>{var t=e&&e.__extends||(function(){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n])},e(t,n)};return function(t,n){e(t,n);function r(){this.constructor=t}t.prototype=n===null?Object.create(n):(r.prototype=n.prototype,new r)}})();Object.defineProperty(e,"__esModule",{value:!0});var n=256,r=function(){function e(e){e===void 0&&(e=`=`),this._paddingCharacter=e}return e.prototype.encodedLength=function(e){return this._paddingCharacter?(e+2)/3*4|0:(e*8+5)/6|0},e.prototype.encode=function(e){for(var t=``,n=0;n<e.length-2;n+=3){var r=e[n]<<16|e[n+1]<<8|e[n+2];t+=this._encodeByte(r>>>18&63),t+=this._encodeByte(r>>>12&63),t+=this._encodeByte(r>>>6&63),t+=this._encodeByte(r>>>0&63)}var i=e.length-n;if(i>0){var r=e[n]<<16|(i===2?e[n+1]<<8:0);t+=this._encodeByte(r>>>18&63),t+=this._encodeByte(r>>>12&63),i===2?t+=this._encodeByte(r>>>6&63):t+=this._paddingCharacter||``,t+=this._paddingCharacter||``}return t},e.prototype.maxDecodedLength=function(e){return this._paddingCharacter?e/4*3|0:(e*6+7)/8|0},e.prototype.decodedLength=function(e){return this.maxDecodedLength(e.length-this._getPaddingLength(e))},e.prototype.decode=function(e){if(e.length===0)return new Uint8Array;for(var t=this._getPaddingLength(e),r=e.length-t,i=new Uint8Array(this.maxDecodedLength(r)),a=0,o=0,s=0,c=0,l=0,u=0,d=0;o<r-4;o+=4)c=this._decodeChar(e.charCodeAt(o+0)),l=this._decodeChar(e.charCodeAt(o+1)),u=this._decodeChar(e.charCodeAt(o+2)),d=this._decodeChar(e.charCodeAt(o+3)),i[a++]=c<<2|l>>>4,i[a++]=l<<4|u>>>2,i[a++]=u<<6|d,s|=c&n,s|=l&n,s|=u&n,s|=d&n;if(o<r-1&&(c=this._decodeChar(e.charCodeAt(o)),l=this._decodeChar(e.charCodeAt(o+1)),i[a++]=c<<2|l>>>4,s|=c&n,s|=l&n),o<r-2&&(u=this._decodeChar(e.charCodeAt(o+2)),i[a++]=l<<4|u>>>2,s|=u&n),o<r-3&&(d=this._decodeChar(e.charCodeAt(o+3)),i[a++]=u<<6|d,s|=d&n),s!==0)throw Error(`Base64Coder: incorrect characters for decoding`);return i},e.prototype._encodeByte=function(e){var t=e;return t+=65,t+=25-e>>>8&6,t+=51-e>>>8&-75,t+=61-e>>>8&-15,t+=62-e>>>8&3,String.fromCharCode(t)},e.prototype._decodeChar=function(e){var t=n;return t+=(42-e&e-44)>>>8&-n+e-43+62,t+=(46-e&e-48)>>>8&-n+e-47+63,t+=(47-e&e-58)>>>8&-n+e-48+52,t+=(64-e&e-91)>>>8&-n+e-65+0,t+=(96-e&e-123)>>>8&-n+e-97+26,t},e.prototype._getPaddingLength=function(e){var t=0;if(this._paddingCharacter){for(var n=e.length-1;n>=0&&e[n]===this._paddingCharacter;n--)t++;if(e.length<4||t>2)throw Error(`Base64Coder: incorrect padding`)}return t},e}();e.Coder=r;var i=new r;function a(e){return i.encode(e)}e.encode=a;function o(e){return i.decode(e)}e.decode=o;var s=function(e){t(r,e);function r(){return e!==null&&e.apply(this,arguments)||this}return r.prototype._encodeByte=function(e){var t=e;return t+=65,t+=25-e>>>8&6,t+=51-e>>>8&-75,t+=61-e>>>8&-13,t+=62-e>>>8&49,String.fromCharCode(t)},r.prototype._decodeChar=function(e){var t=n;return t+=(44-e&e-46)>>>8&-n+e-45+62,t+=(94-e&e-96)>>>8&-n+e-95+63,t+=(47-e&e-58)>>>8&-n+e-48+52,t+=(64-e&e-91)>>>8&-n+e-65+0,t+=(96-e&e-123)>>>8&-n+e-97+26,t},r}(r);e.URLSafeCoder=s;var c=new s;function l(e){return c.encode(e)}e.encodeURLSafe=l;function u(e){return c.decode(e)}e.decodeURLSafe=u,e.encodedLength=function(e){return i.encodedLength(e)},e.maxDecodedLength=function(e){return i.maxDecodedLength(e)},e.decodedLength=function(e){return i.decodedLength(e)}})),Ot=e(((e,t)=>{(function(e,n){var r={};n(r);var i=r.default;for(var a in r)i[a]=r[a];typeof t==`object`&&typeof t.exports==`object`?t.exports=i:typeof define==`function`&&define.amd?define(function(){return i}):e.sha256=i})(e,function(e){e.__esModule=!0,e.digestLength=32,e.blockSize=64;var t=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);function n(e,n,r,i,a){for(var o,s,c,l,u,d,f,p,m,h,g,_,v;a>=64;){for(o=n[0],s=n[1],c=n[2],l=n[3],u=n[4],d=n[5],f=n[6],p=n[7],h=0;h<16;h++)g=i+h*4,e[h]=(r[g]&255)<<24|(r[g+1]&255)<<16|(r[g+2]&255)<<8|r[g+3]&255;for(h=16;h<64;h++)m=e[h-2],_=(m>>>17|m<<15)^(m>>>19|m<<13)^m>>>10,m=e[h-15],v=(m>>>7|m<<25)^(m>>>18|m<<14)^m>>>3,e[h]=(_+e[h-7]|0)+(v+e[h-16]|0);for(h=0;h<64;h++)_=(((u>>>6|u<<26)^(u>>>11|u<<21)^(u>>>25|u<<7))+(u&d^~u&f)|0)+(p+(t[h]+e[h]|0)|0)|0,v=((o>>>2|o<<30)^(o>>>13|o<<19)^(o>>>22|o<<10))+(o&s^o&c^s&c)|0,p=f,f=d,d=u,u=l+_|0,l=c,c=s,s=o,o=_+v|0;n[0]+=o,n[1]+=s,n[2]+=c,n[3]+=l,n[4]+=u,n[5]+=d,n[6]+=f,n[7]+=p,i+=64,a-=64}return i}var r=function(){function t(){this.digestLength=e.digestLength,this.blockSize=e.blockSize,this.state=new Int32Array(8),this.temp=new Int32Array(64),this.buffer=new Uint8Array(128),this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this.reset()}return t.prototype.reset=function(){return this.state[0]=1779033703,this.state[1]=3144134277,this.state[2]=1013904242,this.state[3]=2773480762,this.state[4]=1359893119,this.state[5]=2600822924,this.state[6]=528734635,this.state[7]=1541459225,this.bufferLength=0,this.bytesHashed=0,this.finished=!1,this},t.prototype.clean=function(){for(var e=0;e<this.buffer.length;e++)this.buffer[e]=0;for(var e=0;e<this.temp.length;e++)this.temp[e]=0;this.reset()},t.prototype.update=function(e,t){if(t===void 0&&(t=e.length),this.finished)throw Error(`SHA256: can't update because hash was finished.`);var r=0;if(this.bytesHashed+=t,this.bufferLength>0){for(;this.bufferLength<64&&t>0;)this.buffer[this.bufferLength++]=e[r++],t--;this.bufferLength===64&&(n(this.temp,this.state,this.buffer,0,64),this.bufferLength=0)}for(t>=64&&(r=n(this.temp,this.state,e,r,t),t%=64);t>0;)this.buffer[this.bufferLength++]=e[r++],t--;return this},t.prototype.finish=function(e){if(!this.finished){var t=this.bytesHashed,r=this.bufferLength,i=t/536870912|0,a=t<<3,o=t%64<56?64:128;this.buffer[r]=128;for(var s=r+1;s<o-8;s++)this.buffer[s]=0;this.buffer[o-8]=i>>>24&255,this.buffer[o-7]=i>>>16&255,this.buffer[o-6]=i>>>8&255,this.buffer[o-5]=i>>>0&255,this.buffer[o-4]=a>>>24&255,this.buffer[o-3]=a>>>16&255,this.buffer[o-2]=a>>>8&255,this.buffer[o-1]=a>>>0&255,n(this.temp,this.state,this.buffer,0,o),this.finished=!0}for(var s=0;s<8;s++)e[s*4+0]=this.state[s]>>>24&255,e[s*4+1]=this.state[s]>>>16&255,e[s*4+2]=this.state[s]>>>8&255,e[s*4+3]=this.state[s]>>>0&255;return this},t.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},t.prototype._saveState=function(e){for(var t=0;t<this.state.length;t++)e[t]=this.state[t]},t.prototype._restoreState=function(e,t){for(var n=0;n<this.state.length;n++)this.state[n]=e[n];this.bytesHashed=t,this.finished=!1,this.bufferLength=0},t}();e.Hash=r;var i=function(){function e(e){this.inner=new r,this.outer=new r,this.blockSize=this.inner.blockSize,this.digestLength=this.inner.digestLength;var t=new Uint8Array(this.blockSize);if(e.length>this.blockSize)new r().update(e).finish(t).clean();else for(var n=0;n<e.length;n++)t[n]=e[n];for(var n=0;n<t.length;n++)t[n]^=54;this.inner.update(t);for(var n=0;n<t.length;n++)t[n]^=106;this.outer.update(t),this.istate=new Uint32Array(8),this.ostate=new Uint32Array(8),this.inner._saveState(this.istate),this.outer._saveState(this.ostate);for(var n=0;n<t.length;n++)t[n]=0}return e.prototype.reset=function(){return this.inner._restoreState(this.istate,this.inner.blockSize),this.outer._restoreState(this.ostate,this.outer.blockSize),this},e.prototype.clean=function(){for(var e=0;e<this.istate.length;e++)this.ostate[e]=this.istate[e]=0;this.inner.clean(),this.outer.clean()},e.prototype.update=function(e){return this.inner.update(e),this},e.prototype.finish=function(e){return this.outer.finished?this.outer.finish(e):(this.inner.finish(e),this.outer.update(e,this.digestLength).finish(e)),this},e.prototype.digest=function(){var e=new Uint8Array(this.digestLength);return this.finish(e),e},e}();e.HMAC=i;function a(e){var t=new r().update(e),n=t.digest();return t.clean(),n}e.hash=a,e.default=a;function o(e,t){var n=new i(e).update(t),r=n.digest();return n.clean(),r}e.hmac=o;function s(e,t,n,r){var i=r[0];if(i===0)throw Error(`hkdf: cannot expand more`);t.reset(),i>1&&t.update(e),n&&t.update(n),t.update(r),t.finish(e),r[0]++}var c=new Uint8Array(e.digestLength);function l(e,t,n,r){t===void 0&&(t=c),r===void 0&&(r=32);for(var a=new Uint8Array([1]),l=new i(o(t,e)),u=new Uint8Array(l.digestLength),d=u.length,f=new Uint8Array(r),p=0;p<r;p++)d===u.length&&(s(u,l,n,a),d=0),f[p]=u[d++];return l.clean(),u.fill(0),a.fill(0),f}e.hkdf=l;function u(e,t,n,r){for(var a=new i(e),o=a.digestLength,s=new Uint8Array(4),c=new Uint8Array(o),l=new Uint8Array(o),u=new Uint8Array(r),d=0;d*o<r;d++){var f=d+1;s[0]=f>>>24&255,s[1]=f>>>16&255,s[2]=f>>>8&255,s[3]=f>>>0&255,a.reset(),a.update(t),a.update(s),a.finish(l);for(var p=0;p<o;p++)c[p]=l[p];for(var p=2;p<=n;p++){a.reset(),a.update(l).finish(l);for(var m=0;m<o;m++)c[m]^=l[m]}for(var p=0;p<o&&d*o+p<r;p++)u[d*o+p]=c[p]}for(var d=0;d<o;d++)c[d]=l[d]=0;for(var d=0;d<4;d++)s[d]=0;return a.clean(),u}e.pbkdf2=u})})),kt=e((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.Webhook=e.WebhookVerificationError=void 0;let t=Et(),n=Dt(),r=Ot();var i=class e extends Error{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype),this.name=`ExtendableError`,this.stack=Error(t).stack}},a=class e extends i{constructor(t){super(t),Object.setPrototypeOf(this,e.prototype),this.name=`WebhookVerificationError`}};e.WebhookVerificationError=a;var o=class e{constructor(t,r){if(!t)throw Error(`Secret can't be empty.`);if(r?.format===`raw`)t instanceof Uint8Array?this.key=t:this.key=Uint8Array.from(t,e=>e.charCodeAt(0));else{if(typeof t!=`string`)throw Error(`Expected secret to be of type string`);t.startsWith(e.prefix)&&(t=t.substring(e.prefix.length)),this.key=n.decode(t)}}verify(e,n){let r={};for(let e of Object.keys(n))r[e.toLowerCase()]=n[e];let i=r[`webhook-id`],o=r[`webhook-signature`],s=r[`webhook-timestamp`];if(!o||!i||!s)throw new a(`Missing required headers`);let c=this.verifyTimestamp(s),l=this.sign(i,c,e).split(`,`)[1],u=o.split(` `),d=new globalThis.TextEncoder;for(let n of u){let[r,i]=n.split(`,`);if(r===`v1`&&(0,t.timingSafeEqual)(d.encode(i),d.encode(l)))return JSON.parse(e.toString())}throw new a(`No matching signature found`)}sign(e,t,i){if(typeof i!=`string`)if(i.constructor.name===`Buffer`)i=i.toString();else throw Error(`Expected payload to be of type string or Buffer.`);let a=new TextEncoder,o=Math.floor(t.getTime()/1e3),s=a.encode(`${e}.${o}.${i}`);return`v1,${n.encode(r.hmac(this.key,s))}`}verifyTimestamp(e){let t=Math.floor(Date.now()/1e3),n=parseInt(e,10);if(isNaN(n))throw new a(`Invalid Signature Headers`);if(t-n>300)throw new a(`Message timestamp too old`);if(n>t+300)throw new a(`Message timestamp too new`);return new Date(n*1e3)}};e.Webhook=o,o.prefix=`whsec_`}))(),At=class extends W{unwrap(e,{headers:t,key:n}){if(t!==void 0){let r=n===void 0?this._client.webhookSecret:n;if(r===null)throw Error(`Webhook key must not be null in order to unwrap`);new kt.Webhook(r).verify(e,t)}return JSON.parse(e)}};const Y=e=>{if(globalThis.process!==void 0)return globalThis.process.env?.[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0};var X,jt,Z,Mt,Q=class{constructor({baseURL:e=Y(`LINQ_API_V3_BASE_URL`),apiKey:t=Y(`LINQ_API_V3_API_KEY`),webhookSecret:n=Y(`LINQ_WEBHOOK_SECRET`)??null,...r}={}){if(X.add(this),Z.set(this,void 0),this.chats=new q(this),this.messages=new J(this),this.attachments=new at(this),this.phonenumbers=new Ct(this),this.phoneNumbers=new St(this),this.availableNumber=new ot(this),this.paymentRequests=new bt(this),this.paymentProviders=new yt(this),this.paymentHandles=new vt(this),this.payments=new xt(this),this.blockedHandles=new st(this),this.experiences=new gt(this),this.webhookEvents=new wt(this),this.webhookSubscriptions=new Tt(this),this.capability=new ct(this),this.webhooks=new At(this),this.contactCard=new ht(this),t===void 0)throw new v(`The LINQ_API_V3_API_KEY environment variable is missing or empty; either provide it, or instantiate the LinqAPIV3 client with an apiKey option, like new LinqAPIV3({ apiKey: 'My API Key' }).`);let i={apiKey:t,webhookSecret:n,...r,baseURL:e||`https://api.linqapp.com/api/partner`};this.baseURL=i.baseURL,this.timeout=i.timeout??jt.DEFAULT_TIMEOUT,this.logger=i.logger??console;let a=`warn`;this.logLevel=a,this.logLevel=Re(i.logLevel,`ClientOptions.logLevel`,this)??Re(Y(`LINQ_API_V3_LOG`),`process.env['LINQ_API_V3_LOG']`,this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??ye(),p(this,Z,Ce,`f`);let o=Y(`LINQ_API_V3_CUSTOM_HEADERS`);if(o){let e={};for(let t of o.split(`
3
+ `)){let n=t.indexOf(`:`);n>=0&&(e[t.substring(0,n).trim()]=t.substring(n+1).trim())}i.defaultHeaders={...e,...i.defaultHeaders}}this._options=i,this.apiKey=t,this.webhookSecret=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return G([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Le(e)}getUserAgent(){return`${this.constructor.name}/JS ${k}`}defaultIdempotencyKey(){return`stainless-node-retry-${h()}`}makeStatusError(e,t,n,r){return y.generate(e,t,n,r)}buildURL(e,t,n){let r=!m(this,X,`m`,Mt).call(this)&&n||this.baseURL,i=ie(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!se(a)||!se(o))&&(t={...o,...a,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new He(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let r=await e,i=r.maxRetries??this.maxRetries;t??=i,await this.prepareOptions(r);let{req:a,url:o,timeout:s}=await this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(a,{url:o,options:r});let c=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),l=n===void 0?``:`, retryOf: ${n}`,u=Date.now();if(R(this).debug(`[${c}] sending request`,z({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new b;let d=new AbortController,f=await this.fetchWithTimeout(o,a,s,d).catch(_),p=Date.now();if(f instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new b;let i=g(f)||/timed? ?out/i.test(String(f)+(`cause`in f?String(f.cause):``));if(t)return R(this).info(`[${c}] connection ${i?`timed out`:`failed`} - ${e}`),R(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (${e})`,z({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),this.retryRequest(r,t,n??c);throw R(this).info(`[${c}] connection ${i?`timed out`:`failed`} - error; no more retries left`),R(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,z({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),i?new S:new x({cause:f})}let m=`[${c}${l}] ${a.method} ${o} ${f.ok?`succeeded`:`failed`} with status ${f.status} in ${p-u}ms`;if(!f.ok){let e=await this.shouldRetry(f);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await Se(f.body),R(this).info(`${m} - ${e}`),R(this).debug(`[${c}] response error (${e})`,z({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:p-u})),this.retryRequest(r,t,n??c,f.headers)}let i=e?`error; no more retries left`:`error; not retryable`;R(this).info(`${m} - ${i}`);let a=await f.text().catch(e=>_(e).message),o=ue(a),s=o?void 0:a;throw R(this).debug(`[${c}] response error (${i})`,z({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:s,durationMs:Date.now()-u})),this.makeStatusError(f.status,o,s,f.headers)}return R(this).info(m),R(this).debug(`[${c}] response start`,z({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:p-u})),{response:f,options:r,controller:d,requestLogID:c,retryOfRequestLogID:n,startTime:u}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new We(this,n,e)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{},s=this._makeAbort(r);i&&i.addEventListener(`abort`,s,{once:!0});let c=setTimeout(s,n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:r.signal,...l?{duplex:`half`}:{},method:`GET`,...o};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await de(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&le(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l}=this.buildBody({options:n});return{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=G([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...ve()},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:t,headers:n}=e;if(!t)return t==null&&`body`in e?m(this,Z,`f`).call(this,{body:t,headers:G([n])}):{bodyHeaders:void 0,body:void 0};let r=G([n]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t==`string`&&r.values.has(`content-type`)||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t==`object`&&(Symbol.asyncIterator in t||Symbol.iterator in t&&`next`in t&&typeof t.next==`function`)?{bodyHeaders:void 0,body:xe(t)}:typeof t==`object`&&r.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(t)}:m(this,Z,`f`).call(this,{body:t,headers:r})}};jt=Q,Z=new WeakMap,X=new WeakSet,Mt=function(){return this.baseURL!==`https://api.linqapp.com/api/partner`},Q.LinqAPIV3=jt,Q.DEFAULT_TIMEOUT=6e4,Q.LinqAPIV3Error=v,Q.APIError=y,Q.APIConnectionError=x,Q.APIConnectionTimeoutError=S,Q.APIUserAbortError=b,Q.NotFoundError=E,Q.ConflictError=D,Q.RateLimitError=te,Q.BadRequestError=C,Q.AuthenticationError=w,Q.InternalServerError=ne,Q.PermissionDeniedError=T,Q.UnprocessableEntityError=ee,Q.toFile=$e,Q.Chats=q,Q.Messages=J,Q.Attachments=at,Q.Phonenumbers=Ct,Q.PhoneNumbers=St,Q.AvailableNumber=ot,Q.PaymentRequests=bt,Q.PaymentProviders=yt,Q.PaymentHandles=vt,Q.Payments=xt,Q.BlockedHandles=st,Q.Experiences=gt,Q.WebhookEvents=wt,Q.WebhookSubscriptions=Tt,Q.Capability=ct,Q.Webhooks=At,Q.ContactCard=ht;function $(e){return typeof e==`object`&&!!e}function Nt(e){return typeof e==`string`||!$(e)?null:l(e)?e:l(e.card)?e.card:null}function Pt(e){return e.startsWith(`https://`)}function Ft(e){let t=[];return e.imageUrl&&Pt(e.imageUrl)&&t.push(e.imageUrl),It(e.children,t),t}function It(e,t){for(let n of e)n.type===`image`&&Pt(n.url)?t.push(n.url):n.type===`section`&&It(n.children,t)}function Lt(e){let t=[];e.title&&t.push(e.title),e.subtitle&&t.push(e.subtitle);for(let n of e.children){let e=Rt(n);e&&t.push(e)}return t.join(`
4
+ `)}function Rt(e){switch(e.type){case`text`:return f(e.content).trim()||null;case`fields`:return e.children.map(e=>`${e.label}: ${e.value}`).join(`
5
+ `);case`link`:return Bt(e.label,e.url);case`divider`:return`———`;case`image`:return Pt(e.url)?null:Bt(e.alt,e.url);case`table`:return s(e.headers,e.rows);case`section`:{let t=e.children.map(e=>Rt(e)).filter(e=>!!e);return t.length>0?t.join(`
6
+ `):null}case`actions`:return zt(e);default:return null}}function zt(e){let t=[],n=[];for(let r of e.children)switch(r.type){case`button`:n.push(r.label);break;case`link-button`:{let e=Bt(r.label,r.url);e&&t.push(e);break}case`select`:case`radio_select`:{let e=r.options.map(e=>e.label).join(`, `);t.push(e?`${r.label}: ${e}`:r.label);break}default:break}return n.length>0&&t.unshift(`Options: ${n.join(`, `)}`),t.length>0?t.join(`
7
+ `):null}function Bt(e,t){return e&&e!==t?`${e}: ${t}`:t}function Vt(e){return Ht(e.children)}function Ht(e){return e.some(e=>e.type===`section`?Ht(e.children):e.type===`actions`&&e.children.some(e=>e.type===`button`||e.type===`select`||e.type===`radio_select`))}var Ut=class extends u{toAst(e){return r(e)}fromAst(e){return a(e)}cardToFallbackText(e){return Lt(e)}};function Wt(e,t){let n=qt(e),i=n.parts.flatMap(e=>e.type===`media`?[en(e)]:[]),a=Qt(n.parts,i),s=$t(n.parts),c=n.isMe,l=n.sender?.id||n.sender?.handle||`unknown`,u=n.sender?.handle||n.sender?.id||`unknown`;return new o({id:n.id,threadId:t({chatId:n.chatId,isGroup:n.isGroup}),text:a,formatted:r(a),raw:e,author:{userId:l,userName:u,fullName:u,isBot:c,isMe:c},metadata:{dateSent:Zt(n.sentAt),edited:n.edited,editedAt:n.editedAt?Zt(n.editedAt):void 0},attachments:i,links:s})}function Gt(e){return e.event_type===`message.received`}function Kt(e){return e.event_type===`reaction.added`||e.event_type===`reaction.removed`}function qt(e){if(Jt(e))return{id:e.id,chatId:e.chat.id,isGroup:e.chat.is_group??void 0,parts:e.parts,isMe:e.direction===`outbound`||e.sender_handle.is_me===!0,sender:e.sender_handle,sentAt:e.sent_at,edited:!1};if(Yt(e))return{id:e.message.id,chatId:e.chat_id,isGroup:void 0,parts:e.message.parts,isMe:!0,sender:e.message.from_handle,sentAt:e.message.sent_at||e.message.created_at,edited:!1};if(Xt(e)){let t=e.updated_at!==e.created_at;return{id:e.id,chatId:e.chat_id,isGroup:void 0,parts:e.parts??[],isMe:e.is_from_me||e.from_handle?.is_me===!0,sender:e.from_handle,sentAt:e.sent_at||e.created_at,edited:t,editedAt:t?e.updated_at:void 0}}throw new n(`parseMessage only supports Linq message payloads`)}function Jt(e){return $(e)&&`chat`in e&&`direction`in e&&`sender_handle`in e}function Yt(e){return $(e)&&`chat_id`in e&&`message`in e&&$(e.message)}function Xt(e){return $(e)&&`chat_id`in e&&`is_from_me`in e&&`created_at`in e}function Zt(e){if(e){let t=new Date(e);if(!Number.isNaN(t.getTime()))return t}return new Date}function Qt(e,t){let n=e.flatMap(e=>(e.type===`text`||e.type===`link`)&&typeof e.value==`string`?[e.value]:[]),r=t.map(e=>{let t=e.name||e.mimeType||e.type;return`[${e.type} attachment: ${t}]`});return[...n,...r].join(`
8
+ `).trim()}function $t(e){let t=new Set;for(let n of e){if(n.type===`link`){t.add(n.value);continue}if(n.type===`text`)for(let e of nn(n.value))t.add(e)}return[...t].map(e=>({url:e}))}function en(e){return{type:tn(e.mime_type),url:e.url,name:e.filename,mimeType:e.mime_type,size:e.size_bytes,width:e.width??e.width_px,height:e.height??e.height_px,fetchMetadata:{url:e.url},fetchData:async()=>{let t=await fetch(e.url);if(!t.ok)throw Error(`Failed to fetch Linq attachment ${e.id||e.url}: ${t.status}`);return Buffer.from(await t.arrayBuffer())}}}function tn(e){return e.startsWith(`image/`)?`image`:e.startsWith(`video/`)?`video`:e.startsWith(`audio/`)?`audio`:`file`}function nn(e){return(e.match(/https?:\/\/[^\s<>()]+/gi)??[]).map(e=>e.replace(/[.,!?;:]+$/g,``))}const rn={jpg:`image/jpeg`,jpeg:`image/jpeg`,png:`image/png`,gif:`image/gif`,heic:`image/heic`,heif:`image/heif`,bmp:`image/bmp`,tif:`image/tiff`,tiff:`image/tiff`,webp:`image/webp`,mp4:`video/mp4`,mov:`video/quicktime`,m4v:`video/x-m4v`,"3gp":`video/3gpp`,m4a:`audio/x-m4a`,mp3:`audio/mpeg`,aac:`audio/aac`,wav:`audio/x-wav`,aiff:`audio/x-aiff`,caf:`audio/x-caf`,amr:`audio/amr`,pdf:`application/pdf`,txt:`text/plain`,csv:`text/csv`,rtf:`text/rtf`,vcf:`text/vcard`,ics:`text/calendar`,html:`text/html`,htm:`text/html`,json:`application/json`,zip:`application/zip`,doc:`application/msword`,docx:`application/vnd.openxmlformats-officedocument.wordprocessingml.document`,xls:`application/vnd.ms-excel`,xlsx:`application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`,ppt:`application/vnd.ms-powerpoint`,pptx:`application/vnd.openxmlformats-officedocument.presentationml.presentation`};function an(e){return typeof e==`string`||!$(e)?{attachments:[],files:[]}:{attachments:Array.isArray(e.attachments)?e.attachments:[],files:Array.isArray(e.files)?e.files:[]}}async function on(e,t){let{attachments:n,files:r}=an(t);if(n.length===0&&r.length===0)return[];let i=[];for(let t of n)i.push(await sn(e,t));for(let t of r)i.push(await cn(e,t));return i}async function sn(e,t){if(t.url&&t.url.startsWith(`https://`)&&!fn(t.size))return{type:`media`,url:t.url};let n=await un(t),r=t.name??hn(t.mimeType);return{type:`media`,attachment_id:await ln(e,n,r,pn(t.mimeType,r))}}async function cn(e,t){let n=await dn(t.data),r=pn(t.mimeType,t.filename);return{type:`media`,attachment_id:await ln(e,n,t.filename,r)}}async function ln(e,t,n,r){let i=await e.attachments.create({filename:n,content_type:r,size_bytes:t.byteLength}),a=await fetch(i.upload_url,{method:i.http_method,headers:i.required_headers,body:t});if(!a.ok)throw Error(`Failed to upload Linq attachment ${n}: ${a.status} ${a.statusText}`);return i.attachment_id}async function un(e){if(e.data!=null)return dn(e.data);if(typeof e.fetchData==`function`)return dn(await e.fetchData());if(e.url){let t=await fetch(e.url);if(!t.ok)throw Error(`Failed to download Linq attachment ${e.name??e.url}: ${t.status}`);return new Uint8Array(await t.arrayBuffer())}throw Error(`Outbound attachment ${e.name??`(unnamed)`} has no data, fetchData, or url to send`)}async function dn(e){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return new Uint8Array(e);if(typeof Blob<`u`&&e instanceof Blob)return new Uint8Array(await e.arrayBuffer());throw Error(`Unsupported attachment data type; expected Buffer, Blob, or ArrayBuffer`)}function fn(e){return typeof e==`number`&&e>10485760}function pn(e,t){if(e&&e.trim())return mn(e.trim());let n=t.split(`.`).pop()?.toLowerCase(),r=n?rn[n]:void 0;if(r)return r;throw Error(`Cannot determine content type for attachment "${t}"; set mimeType on the attachment`)}function mn(e){let t=e.toLowerCase();return t===`image/jpg`?`image/jpeg`:t}function hn(e){let t=e?gn(e):void 0;return t?`attachment.${t}`:`attachment`}function gn(e){let t=mn(e);for(let[e,n]of Object.entries(rn))if(n===t)return e}const _n={like:`thumbs_up`,dislike:`thumbs_down`,love:`heart`,laugh:`laugh`,emphasize:`exclamation`,question:`question`};function vn(e){if(e.reaction_type===`custom`)return e.custom_emoji?{emoji:t.fromGChat(e.custom_emoji),rawEmoji:e.custom_emoji}:null;let n=_n[e.reaction_type];return n?{emoji:i(n),rawEmoji:e.reaction_type}:null}function yn(e){let n=typeof e==`string`?e:e.name,r=n.trim().replace(/^\{\{emoji:/,``).replace(/\}\}$/,``).replace(/^:+|:+$/g,``).toLowerCase();return[`thumbs_up`,`thumbsup`,`+1`,`like`,`👍`].includes(r)?{type:`like`}:[`thumbs_down`,`thumbsdown`,`-1`,`dislike`,`👎`].includes(r)?{type:`dislike`}:[`heart`,`love`,`❤️`,`❤`].includes(r)?{type:`love`}:[`laugh`,`joy`,`rofl`,`😂`,`🤣`].includes(r)?{type:`laugh`}:[`exclamation`,`emphasize`,`!!`,`!`,`‼️`,`‼`,`❗`].includes(r)?{type:`emphasize`}:[`question`,`?`,`❓`].includes(r)?{type:`question`}:{type:`custom`,custom_emoji:t.toDiscord(n)}}async function bn(e,t){if(!t)return{ok:!1,response:new Response(`Linq webhook signing secret is not configured`,{status:503})};let n=await e.text();try{new kt.Webhook(t).verify(n,Object.fromEntries(e.headers))}catch{return{ok:!1,response:new Response(`Invalid Linq webhook`,{status:401})}}try{return{ok:!0,event:JSON.parse(n)}}catch{return{ok:!1,response:new Response(`Invalid JSON`,{status:400})}}}var xn=class{name=`linq`;userName=`linq`;apiClient;baseURL;converter=new Ut;credentials;signingSecret;webhookVerifier;chat=null;logger;chatKinds=new Map;constructor(e){if(!e.credentials&&!e.apiKey)throw Error(`Linq requires apiKey or a credentials provider.`);if(!e.webhookVerifier&&!e.credentials&&!e.signingSecret)throw Error(`Linq requires signingSecret or a webhookVerifier.`);this.apiClient=e.apiKey?new Q({apiKey:e.apiKey,baseURL:e.baseURL}):null,this.baseURL=e.baseURL,this.credentials=e.credentials,this.signingSecret=e.signingSecret,this.webhookVerifier=e.webhookVerifier,this.logger=new d}async getApiClient(){if(this.apiClient)return this.apiClient;let e=await this.credentials?.();if(!e?.apiKey)throw Error(`Linq credentials did not provide an API key.`);return new Q({apiKey:e.apiKey,baseURL:this.baseURL})}async getSigningSecret(){if(this.signingSecret)return this.signingSecret;let e=await this.credentials?.();if(!e?.signingSecret)throw Error(`Linq credentials did not provide a webhook signing secret.`);return e.signingSecret}async initialize(e){this.chat=e,this.logger=e.getLogger(`linq`)}encodeThreadId(e){return e.pendingHandle?`linq:pending:${e.pendingHandle}`:(e.isGroup!==void 0&&this.chatKinds.set(e.chatId,e.isGroup),`linq:${e.chatId}`)}decodeThreadId(e){let[t,n,r]=e.split(`:`);if(t!==`linq`||!n)throw Error(`Invalid Linq thread ID: ${e}`);if(n===`pending`){let t=e.slice(13);if(!t)throw Error(`Invalid Linq thread ID: ${e}`);return{chatId:``,pendingHandle:t,isGroup:!1}}if(r===`group`||r===`dm`){let e=r===`group`;return this.chatKinds.set(n,e),{chatId:n,isGroup:e}}if(r!==void 0)throw Error(`Invalid Linq thread ID: ${e}`);return{chatId:n,isGroup:this.chatKinds.get(n)}}async fetchMessages(e,t){let n=this.requireChatId(e),r=await(await this.getApiClient()).chats.messages.list(n,{cursor:t?.cursor,limit:t?.limit});return{messages:r.messages.map(e=>this.parseMessage(e)).sort(function(e,t){return e.metadata.dateSent.getTime()-t.metadata.dateSent.getTime()}),nextCursor:r.next_cursor||void 0}}async fetchMessage(e,t){try{let e=await(await this.getApiClient()).messages.retrieve(t);return this.parseMessage(e)}catch(e){if($(e)&&e.status===404)return null;throw e}}async postMessage(e,t){let{chatId:n,pendingHandle:r}=this.decodeThreadId(e),i=this.converter.renderPostable(t).trim(),a=await on(await this.getApiClient(),t),o=[];i&&o.push({type:`text`,value:i});let s=Nt(t);if(s){Vt(s)&&this.logger.warn(`Card buttons/selects were flattened to text — onAction() handlers never fire over iMessage/SMS. Use LinkButton/CardLink URLs or handle plain-text replies instead.`);for(let e of Ft(s))o.push({type:`media`,url:e})}if(o.push(...a),o.length===0)throw Error(`Linq message must include text or media.`);let c=await this.getApiClient();if(r){let e=await c.messages.create({to:[r],message:{parts:o}});return{id:e.message.id,threadId:this.encodeThreadId({chatId:e.chat_id}),raw:e}}let l=await c.chats.messages.send(n,{message:{parts:o}});return{id:l.message.id,threadId:this.encodeThreadId({chatId:l.chat_id||n}),raw:l}}requireChatId(e){let{chatId:t,pendingHandle:n}=this.decodeThreadId(e);if(n)throw Error(`Linq thread ${e} has no chat yet — send a message first to create it.`);return t}async openDM(e){let t=e.trim();if(!t)throw Error(`Linq openDM requires a handle.`);return this.encodeThreadId({chatId:``,pendingHandle:t})}async editMessage(e,t,n){let r=this.requireChatId(e),i=this.converter.renderPostable(n).trim();if(!i)throw Error(`Linq message text cannot be empty.`);let a=await(await this.getApiClient()).messages.update(t,{text:i,part_index:0});return{id:a.id,threadId:this.encodeThreadId({chatId:a.chat_id||r}),raw:a}}deleteMessage(e,t){throw new n(`deleteMessage is not implemented`)}async addReaction(e,t,n){await(await this.getApiClient()).messages.addReaction(t,{operation:`add`,...yn(n)})}async removeReaction(e,t,n){await(await this.getApiClient()).messages.addReaction(t,{operation:`remove`,...yn(n)})}async fetchThread(e){let t=this.requireChatId(e),n=await(await this.getApiClient()).chats.retrieve(t);return{id:this.encodeThreadId({chatId:n.id,isGroup:n.is_group}),channelId:this.encodeThreadId({chatId:n.id,isGroup:n.is_group}),channelName:n.display_name??void 0,isDM:!n.is_group,metadata:{chat:n}}}async startTyping(e,t){let n=this.requireChatId(e),{isGroup:r}=this.decodeThreadId(e);if(r!==!0)try{await(await this.getApiClient()).chats.typing.start(n)}catch(e){if($(e)&&e.status===403)return;throw e}}async markRead(e,t){let{chatId:n}=this.decodeThreadId(e);await(await this.getApiClient()).chats.markAsRead(n)}async stream(e,t){let n=``;for await(let e of t){if(typeof e==`string`){n+=e;continue}e.type===`markdown_text`&&(n+=e.text)}return this.postMessage(e,n.trim()?{markdown:n}:` `)}async handleWebhook(e,t){let n=this.webhookVerifier?await this.verifyTrustedWebhook(e):await bn(e,await this.getSigningSecret());if(!n.ok)return n.response;let{event:r}=n;if(this.chat&&Gt(r)&&r.data.direction===`inbound`){let e=r.data.chat.id,n=r.data.chat.is_group??void 0;if(n===void 0&&!this.chatKinds.has(e))try{let t=await(await this.getApiClient()).chats.retrieve(e);this.chatKinds.set(e,t.is_group)}catch(t){this.logger.warn(`Failed to resolve Linq chat kind for ${e}`,{error:t})}let i=this.encodeThreadId({chatId:e,isGroup:n});this.chat.processMessage(this,i,async()=>this.parseMessage(r.data),t)}else this.chat&&Kt(r)&&this.processReactionWebhook(this.chat,r,t);return new Response(`OK`,{status:200})}async verifyTrustedWebhook(e){let t=new Uint8Array(await e.arrayBuffer());try{if(await this.webhookVerifier?.(e,t)===!1)return{ok:!1,response:new Response(`Invalid Linq webhook`,{status:401})}}catch{return{ok:!1,response:new Response(`Invalid Linq webhook`,{status:401})}}try{return{ok:!0,event:JSON.parse(new TextDecoder().decode(t))}}catch{return{ok:!1,response:new Response(`Invalid JSON`,{status:400})}}}processReactionWebhook(e,t,n){let{chat_id:r,message_id:i}=t.data;if(!r||!i){this.logger.debug(`Ignoring Linq ${t.event_type} webhook without chat/message ID`);return}let a=vn(t.data);if(!a){this.logger.debug(`Ignoring Linq ${t.event_type} webhook with unsupported reaction type ${t.data.reaction_type}`);return}let o=t.data.from_handle,s=t.data.is_from_me||o?.is_me===!0,c=o?.id||o?.handle||t.data.from||`unknown`,l=o?.handle||t.data.from||c;e.processReaction({adapter:this,added:t.event_type===`reaction.added`,emoji:a.emoji,rawEmoji:a.rawEmoji,messageId:i,threadId:this.encodeThreadId({chatId:r}),raw:t,user:{userId:c,userName:l,fullName:l,isBot:s,isMe:s}},n)}parseMessage(e){return Wt(e,e=>this.encodeThreadId(e))}rehydrateAttachment(e){let t=e.fetchMetadata?.url??e.url;return t?{...e,fetchData:async()=>{let e=await fetch(t);if(!e.ok)throw Error(`Failed to fetch Linq attachment ${t}: ${e.status}`);return Buffer.from(await e.arrayBuffer())}}:e}renderFormatted(e){return c(e).trim()}channelIdFromThreadId(e){return e}isDM(e){return this.decodeThreadId(e).isGroup===!1}};function Sn(e){return new xn(e)}export{Sn as createLinqAdapter};
@@ -21,13 +21,13 @@ declare const EXTENSION_CAPABILITY_CONTRACTS: {
21
21
  readonly dropped: {};
22
22
  };
23
23
  readonly channel: {
24
- readonly current: 4;
25
- readonly supported: readonly [1, 2, 3, 4];
24
+ readonly current: 5;
25
+ readonly supported: readonly [1, 2, 3, 4, 5];
26
26
  readonly dropped: {};
27
27
  };
28
28
  readonly schedule: {
29
- readonly current: 2;
30
- readonly supported: readonly [1, 2];
29
+ readonly current: 3;
30
+ readonly supported: readonly [1, 2, 3];
31
31
  readonly dropped: {};
32
32
  };
33
33
  readonly subagent: {