@useago/sdk 1.5.5 → 1.5.6

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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,13 @@ All notable changes to `@useago/sdk` are documented here.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.5.6] - 2026-07-29
9
+
10
+ ### Fixed
11
+
12
+ - `getConversation` now maps each message's `follow_up_replies`, so follow-up
13
+ pills survive a reload instead of disappearing on a reopened thread.
14
+
8
15
  ## [1.5.5] - 2026-07-28
9
16
 
10
17
  ### Added
@@ -1336,7 +1336,8 @@ var Pt = "activity:recent", Ot = "state:delta", Gt = class U {
1336
1336
  createdAt: new Date(n.created_at),
1337
1337
  hidden: n.hidden,
1338
1338
  toolCalls: U.mapPersistedToolCalls(n.tool_call_data),
1339
- attachments: n.attachments && n.attachments.length > 0 ? n.attachments.map(xt) : void 0
1339
+ attachments: n.attachments && n.attachments.length > 0 ? n.attachments.map(xt) : void 0,
1340
+ followUpReplies: n.follow_up_replies && n.follow_up_replies.length > 0 ? n.follow_up_replies : void 0
1340
1341
  }))
1341
1342
  };
1342
1343
  return this.eventEmitter.emit("conversation:loaded", i), i;
@@ -1,7 +1,7 @@
1
1
  var X=10,T=1e3;function Y(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function b(e,t){if(typeof e=="string"){if(e.length<=1e3)return e;const i=e.length-T;return e.slice(0,T)+`…[truncated ${i} chars]`}if(Array.isArray(e)){if(t.has(e))return"…[circular]";t.add(e);const i=e.slice(0,50).map(s=>b(s,t));return e.length>50&&i.push(`…[+${e.length-50} more]`),t.delete(e),i}if(Y(e)){if(t.has(e))return"…[circular]";t.add(e);const i={};for(const[s,n]of Object.entries(e))i[s]=b(n,t);return t.delete(e),i}return e}function J(e){return b(e,new WeakSet)}var D=class{constructor(e=10){this.entries=[];const t=Math.floor(e);this.maxEntries=Number.isFinite(t)?Math.max(1,t):10}add(e){const t={ts:e.ts??Date.now(),actor:e.actor??"user",name:e.name,summary:e.summary,...e.data!==void 0?{data:J(e.data)}:{}};this.entries.push(t);const i=this.entries.length-this.maxEntries;return i>0&&this.entries.splice(0,i),t}getRecent(){return[...this.entries]}get size(){return this.entries.length}clear(){this.entries=[]}},d=class extends Error{constructor(e,t,i){super(e),this.code=t,this.statusCode=i,this.name="AgoError"}},p=class U extends d{constructor(t,i,s,n,o,a){super(t,i,s),this.type=n,this.param=o,this.docUrl=a,this.name="AgoApiError"}static fromResponse(t,i){const s=t.error;return new U(s.doc_url?`${s.message} See ${s.doc_url}`:s.message,s.code,i,s.type,s.param,s.doc_url)}},y=class extends d{constructor(e,t){super(e,"network_error"),this.originalError=t,this.name="AgoNetworkError"}},A=class extends d{constructor(e,t="stream_error"){super(e,t),this.name="AgoStreamError"}},E=class extends d{constructor(e,t,i){super(e,"function_error"),this.functionName=t,this.originalError=i,this.name="AgoFunctionError"}},V=class{constructor(e=!1){this.enabled=e}enable(){this.enabled=!0}disable(){this.enabled=!1}log(...e){this.enabled&&console.log("[AGO SDK]",...e)}warn(...e){this.enabled&&console.warn("[AGO SDK]",...e)}error(...e){console.error("[AGO SDK]",...e)}debug(...e){this.enabled&&console.debug("[AGO SDK]",...e)}},c=new V,F="ago_widget_id";function Q(){if(typeof localStorage<"u"){const t=localStorage.getItem(F);if(t)return t}const e=typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`ago-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`;if(typeof localStorage<"u")try{localStorage.setItem(F,e)}catch{}return e}var Z=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.headers={"X-User-Anon-Id":e.widgetId||Q()},e.userEmail&&(this.headers["X-User-Email"]=e.userEmail),e.userJwt&&(this.headers.Authorization=`Bearer ${e.userJwt}`),e.permission&&(this.headers["X-Widget-Permission"]=e.permission)}updateConfig(e){e.baseUrl&&(this.baseUrl=e.baseUrl.replace(/\/$/,"")),e.widgetId&&(this.headers["X-User-Anon-Id"]=e.widgetId),e.userEmail&&(this.headers["X-User-Email"]=e.userEmail),e.userJwt&&(this.headers.Authorization=`Bearer ${e.userJwt}`),e.permission!==void 0&&(e.permission?this.headers["X-Widget-Permission"]=e.permission:delete this.headers["X-Widget-Permission"])}async get(e){return this.request("GET",e)}async post(e,t,i){return this.request("POST",e,t,i)}async postStream(e,t){const i=`${this.baseUrl}${e}`;c.debug("POST (stream)",i,t);try{const s=await fetch(i,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:t?JSON.stringify(t):void 0});return s.ok||await this.handleErrorResponse(s),s}catch(s){throw s instanceof p?s:new y(`Network error: ${s instanceof Error?s.message:"Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`,s instanceof Error?s:void 0)}}async postFormData(e,t){const i=`${this.baseUrl}${e}`;c.debug("POST (formData)",i);const s={...this.headers};try{const n=await fetch(i,{method:"POST",headers:s,body:t});return n.ok||await this.handleErrorResponse(n),n}catch(n){throw n instanceof p?n:new y(`Network error: ${n instanceof Error?n.message:"Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`,n instanceof Error?n:void 0)}}async request(e,t,i,s){const n=`${this.baseUrl}${t}`;c.debug(e,n,i);try{const o=await fetch(n,{method:e,headers:{...this.headers,"Content-Type":"application/json"},body:i?JSON.stringify(i):void 0,...s?.keepalive?{keepalive:!0}:{}});return o.ok||await this.handleErrorResponse(o),o.status===204?void 0:o.json()}catch(o){throw o instanceof p?o:new y(`Network error: ${o instanceof Error?o.message:"Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`,o instanceof Error?o:void 0)}}async handleErrorResponse(e){let t;try{t=await e.json()}catch{}if(t?.error)throw p.fromResponse(t,e.status);let i="";throw e.status===401||e.status===403?i=" Check `userJwt` (and that it has not expired).":e.status===404&&(i=" Check that `baseUrl` points at your AGO API root."),new p(`HTTP ${e.status}: ${e.statusText}.${i}`,"http_error",e.status,"api_error")}},ee=5e4,te=2e4,ie=2e3,M=class{constructor(e){this.functions=new Map,this.defaultMaxResultBytes=e?.maxResultBytes??ee}setDefaultMaxResultBytes(e){this.defaultMaxResultBytes=e}register(e,t,i){if(typeof e=="object"){const{name:r,handler:l,description:u,parameters:h,maxResultBytes:g,requiresApproval:m}=e;return this.register(r,l,{description:u,parameters:h,maxResultBytes:g,requiresApproval:m})}const s=e;if(!t||!i)throw new d(`registerFunction("${s}"): both a handler and a schema are required. Pass them as arguments or use the single-object form: registerFunction({ name, parameters, handler }).`,"function_invalid_registration");this.functions.has(s)&&c.warn(`Function "${s}" is being overwritten`);const{maxResultBytes:n,requiresApproval:o,...a}=i;this.functions.set(s,{schema:{...a,name:s},handler:t,maxResultBytes:n,requiresApproval:o}),c.log(`Registered function: ${s}`)}unregister(e){const t=this.functions.delete(e);return t&&c.log(`Unregistered function: ${e}`),t}get(e){return this.functions.get(e)}has(e){return this.functions.has(e)}getSchemas(){return Array.from(this.functions.values()).map(e=>e.schema)}async execute(e,t){const i=this.functions.get(e);if(!i)throw new E(`Function "${e}" is not registered`,e);c.log(`Executing function: ${e}`,t);try{const s=await i.handler(t);return c.log(`Function ${e} completed:`,s),this.guardResultSize(e,s,i.maxResultBytes)}catch(s){throw c.error(`Function ${e} failed:`,s),new E(`Function "${e}" execution failed: ${s instanceof Error?s.message:"Unknown error"}`,e,s instanceof Error?s:void 0)}}guardResultSize(e,t,i){let s;try{s=JSON.stringify(t)}catch{return t}if(s===void 0)return t;const n=new TextEncoder().encode(s).length,o=i??this.defaultMaxResultBytes;return n>o?(c.warn(`Function "${e}" result is ${n} bytes, over the ${o}-byte limit; a truncated preview was sent to the agent instead. Return fewer fields, paginate, or raise maxResultBytes for this function.`),{truncated:!0,originalBytes:n,maxBytes:o,preview:s.slice(0,ie),hint:`The result of "${e}" exceeded the ${o}-byte limit and was truncated. Request less data (use limit or filter parameters if available), or tell the user the result is too large to process.`}):(n>te&&c.warn(`Function "${e}" returned a large result (${Math.round(n/1024)} KB). Large results consume LLM context: return fewer fields, paginate, or push the data to the UI and return a summary.`),t)}clear(){this.functions.clear(),c.log("Cleared all registered functions")}get size(){return this.functions.size}},se=250,ne=3,re=1e3,oe=24,ae=10,ce=50,le=["mousemove","mousedown","keydown","scroll","touchstart"],j=class{constructor(e={}){this.started=!1,this.teardowns=[],this.route="",this.routeEnteredAt=0,this.lastActivityAt=0,this.lastHeavyActivityAt=0,this.recentRoutes=[],this.routeBounces=0,this.rageClicks=0,this.fieldErrors={},this.recentClicks=[],this.signals=[],this.listeners=new Set,this.getPageState=e.getPageState,this.activityThrottleMs=e.activityThrottleMs??se,this.rageClickCount=e.rageClickCount??ne,this.rageClickWindowMs=e.rageClickWindowMs??re,this.rageClickRadiusPx=e.rageClickRadiusPx??oe,this.maxRecentRoutes=e.maxRecentRoutes??ae,this.maxSignals=e.maxSignals??ce}start(){if(this.started||typeof window>"u"||typeof document>"u")return;this.started=!0;const e=Date.now();this.route=this.currentPathname(),this.routeEnteredAt=e,this.lastActivityAt=e,this.recentRoutes=[this.route];const t=(s,n,o)=>{s.addEventListener(n,o,{passive:!0}),this.teardowns.push(()=>s.removeEventListener(n,o))},i=()=>this.recordActivity();for(const s of le)t(window,s,i);t(document,"visibilitychange",()=>{document.visibilityState==="visible"&&this.recordActivity()}),t(window,"popstate",()=>this.checkRoute()),t(window,"hashchange",()=>this.checkRoute()),t(window,"click",s=>this.onClick(s)),c.log("SignalCollector started")}destroy(){for(const e of this.teardowns)e();this.teardowns=[],this.listeners.clear(),this.recentClicks=[],this.started=!1,c.log("SignalCollector destroyed")}signalFieldError(e){this.checkRoute();const t=(this.fieldErrors[e]??0)+1;this.fieldErrors[e]=t,this.pushSignal({type:"field_error",route:this.route,at:Date.now(),count:t,meta:{field:e}})}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}getSignals(){return[...this.signals]}getSnapshot(e){this.checkRoute();const t=Date.now();return{route:this.route,dwellMs:this.started?t-this.routeEnteredAt:0,idleMs:this.started?t-this.lastActivityAt:0,rageClicks:this.rageClicks,routeBounces:this.routeBounces,fieldErrors:{...this.fieldErrors},recentRoutes:[...this.recentRoutes],pageState:e?.pageState===!1?null:this.readPageState()}}currentPathname(){return typeof window<"u"&&window.location?window.location.pathname:""}readPageState(){if(!this.getPageState)return null;try{return this.getPageState()??null}catch(e){return c.warn("SignalCollector getPageState threw:",e),null}}recordActivity(){const e=Date.now();this.lastActivityAt=e,e-this.lastHeavyActivityAt>=this.activityThrottleMs&&(this.lastHeavyActivityAt=e,this.checkRoute())}checkRoute(){if(!this.started)return;const e=this.currentPathname();if(e===this.route)return;const t=Date.now(),i=this.route;this.route=e,this.routeEnteredAt=t,this.rageClicks=0,this.fieldErrors={},this.recentClicks=[],this.recentRoutes.push(e),this.recentRoutes.length>this.maxRecentRoutes&&this.recentRoutes.splice(0,this.recentRoutes.length-this.maxRecentRoutes),this.pushSignal({type:"route_change",route:e,at:t,meta:{from:i}});const s=this.recentRoutes,n=s.length;n>=4&&s[n-1]===s[n-3]&&s[n-2]===s[n-4]&&s[n-1]!==s[n-2]&&(this.routeBounces+=1,this.pushSignal({type:"route_bounce",route:e,at:t,count:this.routeBounces,meta:{between:`${s[n-2]}↔${s[n-1]}`}}))}onClick(e){this.recordActivity();const t=Date.now(),i=this.pageStateKey(),s={at:t,x:e.clientX,y:e.clientY,stateKey:i};this.recentClicks=this.recentClicks.filter(r=>t-r.at<=this.rageClickWindowMs);const n=this.recentClicks[0],o=!n||Math.abs(s.x-n.x)<=this.rageClickRadiusPx&&Math.abs(s.y-n.y)<=this.rageClickRadiusPx,a=!n||n.stateKey===i;if(!o||!a){this.recentClicks=[s];return}this.recentClicks.push(s),this.recentClicks.length>=this.rageClickCount&&(this.rageClicks+=1,this.recentClicks=[],this.pushSignal({type:"rage_click",route:this.route,at:t,count:this.rageClicks}))}pageStateKey(){const e=this.readPageState();if(!e)return"";try{return JSON.stringify(e)}catch{return""}}pushSignal(e){this.signals.push(e),this.signals.length>this.maxSignals&&this.signals.splice(0,this.signals.length-this.maxSignals);for(const t of this.listeners)try{t(e)}catch(i){c.error("Signal listener threw:",i)}}};function L(e,t){const i=t?t.storage??(typeof localStorage<"u"?localStorage:void 0):void 0;let s=e;if(t&&i)try{const r=i.getItem(t.key);r!=null&&(s=JSON.parse(r))}catch{}const n=new Set,o=()=>n.forEach(r=>r(s));function a(){if(t&&i)try{i.setItem(t.key,JSON.stringify(s))}catch{}}return{get:()=>s,set:r=>{s=r,a(),o()},subscribe:r=>(n.add(r),()=>{n.delete(r)})}}var ue=6e4,he=1440*60*1e3,de="ago_proactive";function C(e){const t=new Date(e),i=String(t.getMonth()+1).padStart(2,"0"),s=String(t.getDate()).padStart(2,"0");return`${t.getFullYear()}-${i}-${s}`}var ge=class{constructor(e={}){this.killSwitchEnabled=!1,this.engaged=!1,this.turnInFlight=!1,this.slotOccupied=!1,this.sessionCount=0,this.perSessionCap=e.frequencyCap?.perSession,this.perDayCap=e.frequencyCap?.perDay,this.store=L({optOut:!1,lastFiredAt:{},dismissedAt:{},day:{date:C(Date.now()),count:0}},{key:e.storageKey??de,storage:e.storage})}setKillSwitch(e){this.killSwitchEnabled=e}optOut(){this.store.set({...this.store.get(),optOut:!0})}optIn(){this.store.set({...this.store.get(),optOut:!1})}isOptedOut(){return this.store.get().optOut}setEngaged(e){this.engaged=e}setTurnInFlight(e){this.turnInFlight=e}isSlotOccupied(){return this.slotOccupied}occupySlot(){this.slotOccupied=!0}releaseSlot(){this.slotOccupied=!1}canFire(e,t=Date.now()){if(!this.killSwitchEnabled)return this.deny(e,"kill-switch (proactive disabled server-side)");const i=this.store.get();if(i.optOut)return this.deny(e,"user opted out");if(this.engaged)return this.deny(e,"user engaged (widget open)");if(this.turnInFlight)return this.deny(e,"message turn in flight");if(this.slotOccupied)return this.deny(e,"nudge slot occupied");const s=i.lastFiredAt[e.id],n=e.cooldownMs??ue;if(s!==void 0&&t-s<n)return this.deny(e,"cooldown");const o=i.dismissedAt[e.id],a=e.resurfaceAfterMs??he;return o!==void 0&&t-o<a?this.deny(e,"dismissed recently"):this.perSessionCap!==void 0&&this.sessionCount>=this.perSessionCap?this.deny(e,"perSession cap"):this.perDayCap!==void 0&&this.dayCount(t)>=this.perDayCap?this.deny(e,"perDay cap"):!0}recordFired(e,t=Date.now()){const i=this.store.get();this.store.set({...i,lastFiredAt:{...i.lastFiredAt,[e]:t}})}recordNudgeShown(e=Date.now()){this.sessionCount+=1;const t=this.store.get(),i=C(e),s=t.day.date===i?{date:i,count:t.day.count+1}:{date:i,count:1};this.store.set({...t,day:s})}recordDismissed(e,t=Date.now()){const i=this.store.get();this.store.set({...i,dismissedAt:{...i.dismissedAt,[e]:t}})}dayCount(e){const t=this.store.get();return t.day.date===C(e)?t.day.count:0}deny(e,t){return c.debug(`NudgeGovernor: trigger "${e.id}" blocked — ${t}`),!1}};function P(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const t=Math.floor(Math.random()*16);return(e==="x"?t:t&3|8).toString(16)})}function fe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function B(e,t){if(e==="*"||e===t)return!0;const i=e.split("/"),s=i.map((n,o)=>{const a=o===i.length-1;return n==="*"?a?"[^/]+(?:/[^/]+)*":"[^/]+":n.startsWith(":")?"[^/]+":fe(n)});return new RegExp("^"+s.join("/")+"/?$").test(t)}function x(e,t){return e===t?!0:e===null||t===null?!1:Array.isArray(e)?!Array.isArray(t)||t.length!==e.length?!1:e.every((i,s)=>_(i,t[s])):typeof e=="object"?typeof t!="object"||Array.isArray(t)?!1:Object.entries(e).every(([i,s])=>x(s,t[i])):!1}function _(e,t){if(e===t)return!0;if(e===null||t===null||typeof e!=typeof t)return!1;if(Array.isArray(e))return!Array.isArray(t)||e.length!==t.length?!1:e.every((i,s)=>_(i,t[s]));if(typeof e=="object"){const i=Object.keys(e),s=Object.keys(t);return i.length!==s.length?!1:i.every(n=>_(e[n],t[n]))}return!1}function G(e,t){if(e.route!==void 0&&!B(e.route,t.route)||e.idleMs!==void 0&&t.idleMs<e.idleMs||e.dwellMs!==void 0&&t.dwellMs<e.dwellMs||e.rageClicks!==void 0&&t.rageClicks<e.rageClicks||e.routeBounces!==void 0&&t.routeBounces<e.routeBounces)return!1;if(e.fieldErrors!==void 0){for(const[i,s]of Object.entries(e.fieldErrors))if((t.fieldErrors[i]??0)<s)return!1}return!(e.pageState!==void 0&&!x(e.pageState,t.pageState??{}))}var pe=1e3,me="/api/sdk/v1/config",ye="/api/sdk/v1/proactive/evaluate",ve=class{constructor(e){this.tickTimer=null,this.teardowns=[],this.started=!1,this.activeNudge=null,this.lastConversationId=null,this.shownIds=new Set,this.resolvedIds=new Set,this.lastEvaluationAt=0,this.client=e.client,this.collector=e.collector,this.governor=e.governor,this.tracker=e.tracker,this.options=e.options,this.tickMs=e.options.tickMs??pe}start(){if(this.started)return;this.started=!0,this.options.enabledOverride!==void 0?this.governor.setKillSwitch(this.options.enabledOverride):this.loadKillSwitch();const e=n=>{n.conversationId&&(this.lastConversationId=n.conversationId),this.governor.setTurnInFlight(!0)},t=()=>this.governor.setTurnInFlight(!1),i=()=>this.governor.setTurnInFlight(!1),s=n=>{n?.id&&(this.lastConversationId=n.id)};this.client.on("message:start",e),this.client.on("message:complete",t),this.client.on("message:error",i),this.client.on("conversation:loaded",s),this.teardowns.push(()=>{this.client.off("message:start",e),this.client.off("message:complete",t),this.client.off("message:error",i),this.client.off("conversation:loaded",s)}),this.tickTimer=setInterval(()=>this.evaluate(),this.tickMs),this.teardowns.push(this.collector.subscribe(()=>{Date.now()-this.lastEvaluationAt>=this.tickMs&&this.evaluate()}))}stop(){this.tickTimer!==null&&(clearInterval(this.tickTimer),this.tickTimer=null);for(const e of this.teardowns)e();this.teardowns=[],this.started=!1}getActiveNudge(){return this.activeNudge}async loadKillSwitch(){try{const e=await this.client.getHttp().get(me);this.governor.setKillSwitch(e?.proactive?.enabled===!0)}catch(e){c.debug("Proactive config fetch failed; staying disabled:",e),this.governor.setKillSwitch(!1)}}evaluate(){if(this.lastEvaluationAt=Date.now(),typeof document<"u"&&document.visibilityState==="hidden"||this.governor.isSlotOccupied())return;const e=this.collector.getSnapshot();for(const t of this.options.triggers)if(G(t.when,e)&&this.governor.canFire(t)){this.fire(t);return}}fire(e){if(this.governor.recordFired(e.id),this.governor.occupySlot(),e.intervene==="agent"){this.evaluateWithAgent(e);return}this.setReady({id:P(),triggerId:e.id,source:"static",message:e.intervene.message,action:e.intervene.action,goal:e.goal,kickoff:e.kickoff,createdAt:new Date})}async evaluateWithAgent(e){const t=P(),i={client_nudge_id:t,trigger_id:e.id,goal:e.goal??"",agent:this.client.getConfiguredAgent(),signals:this.collector.getSnapshot(),client_context:this.client.getContextSnapshot()??{entries:{}},client_functions:this.client.getRegisteredFunctions()};let s;try{s=await this.client.getHttp().post(ye,i)}catch(n){c.debug("Proactive evaluate failed (treated as no-intervene):",n),this.governor.releaseSlot();return}if(!s?.intervene||!s.message){this.governor.releaseSlot();return}this.setReady({id:t,triggerId:e.id,source:"agent",message:s.message,action:we(s.action),goal:e.goal,kickoff:e.kickoff,createdAt:new Date,serverNudgeId:s.nudge_id})}setReady(e){this.activeNudge=e,this.client.emitProactiveEvent("nudge:ready",e)}shown(e){this.shownIds.has(e.id)||(this.shownIds.add(e.id),this.governor.recordNudgeShown(),this.tracker.track({clientNudgeId:e.id,triggerId:e.triggerId,source:e.source,type:"shown",message:e.message,occurredAt:Date.now()}),this.client.emitProactiveEvent("nudge:shown",{nudge:e}))}dismiss(e){this.resolvedIds.has(e.id)||(this.resolvedIds.add(e.id),this.governor.recordDismissed(e.triggerId),this.tracker.track({clientNudgeId:e.id,triggerId:e.triggerId,source:e.source,type:"dismissed",occurredAt:Date.now()}),this.clearActive(e),this.client.emitProactiveEvent("nudge:dismissed",{nudge:e}))}async accept(e){this.resolvedIds.has(e.id)||(this.resolvedIds.add(e.id),this.tracker.track({clientNudgeId:e.id,triggerId:e.triggerId,source:e.source,type:"accepted",occurredAt:Date.now()}),this.clearActive(e),this.client.emitProactiveEvent("nudge:accepted",{nudge:e}),(e.source==="agent"||e.goal)&&(this.lastConversationId?this.client.sendMessage(Ce(e),{hidden:!0,conversationId:this.lastConversationId}).catch(t=>c.debug("Nudge kickoff message failed:",t)):e.kickoff?this.client.sendMessage(e.kickoff).catch(t=>c.debug("Nudge kickoff message failed:",t)):c.debug("Nudge accepted with no open conversation and no trigger.kickoff; skipping the chat pre-seed (a hidden message cannot open a conversation).")),e.action&&await this.runAction(e.action))}markConverted(e){this.tracker.track({clientNudgeId:e.id,triggerId:e.triggerId,source:e.source,type:"converted",occurredAt:Date.now()})}clearActive(e){this.activeNudge?.id===e.id&&(this.activeNudge=null),this.governor.releaseSlot()}async runAction(e){try{"functionName"in e?await this.client.executeClientFunction(e.functionName,e.arguments??{}):await this.client.executeClientFunction("setPageState",e.setPageState)}catch(t){c.warn("Nudge action failed:",t)}}};function we(e){if(e)return{label:e.label,functionName:e.function_name,arguments:e.arguments}}function Ce(e){const t=e.goal?` Goal: ${e.goal}.`:"";return`The user accepted a proactive nudge that said: "${e.message}".${t} Recent friction signals are in the client context (friction_signals). Start helping with this now: briefly explain what you can do and take the first concrete step.`}var Se=5e3,be="/api/sdk/v1/proactive/events",Ae=class{constructor(e){if(this.queue=[],this.flushTimer=null,this.teardowns=[],this.destroyed=!1,this.post=e.post,this.agent=e.agent,this.flushIntervalMs=e.flushIntervalMs??Se,typeof document<"u"){const t=()=>{document.visibilityState==="hidden"&&this.flush({keepalive:!0})};document.addEventListener("visibilitychange",t),this.teardowns.push(()=>document.removeEventListener("visibilitychange",t))}if(typeof window<"u"){const t=()=>this.flush({keepalive:!0});window.addEventListener("pagehide",t),this.teardowns.push(()=>window.removeEventListener("pagehide",t))}}track(e){this.destroyed||(this.queue.push(e),this.flushTimer===null&&(this.flushTimer=setTimeout(()=>this.flush(),this.flushIntervalMs)))}flush(e){if(this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null),this.queue.length===0)return;const t=this.queue;this.queue=[];const i={events:t.map(s=>({client_nudge_id:s.clientNudgeId,trigger_id:s.triggerId,source:s.source,type:s.type,...s.message!==void 0?{message:s.message}:{},...this.agent?{agent:this.agent}:{},occurred_at:new Date(s.occurredAt).toISOString()}))};this.post(be,i,e).catch(s=>{c.debug("Proactive event batch failed:",s)})}destroy(){if(!this.destroyed){this.flush({keepalive:!0}),this.destroyed=!0;for(const e of this.teardowns)e();this.teardowns=[]}}},O="friction_signals";function k(e,t){e.proactive&&(c.warn("createAgoProactive: a proactive controller is already attached; replacing it."),e.proactive.destroy());const i=new j({...t.signals,getPageState:()=>{const r=e.getContextSnapshot();if(!r)return null;const l={};for(const[u,h]of Object.entries(r.entries))u.startsWith("page-state:")&&h.data&&Object.assign(l,h.data);return Object.keys(l).length>0?l:null}});i.start(),e.addDynamicContext(O,()=>{const{pageState:r,...l}=i.getSnapshot({pageState:!1});return{name:"Friction signals",description:"Behavioral friction observed on the current page: dwell/idle times, rage clicks, route bounces, repeated field errors (names and counters only).",data:l}});const s=new ge({frequencyCap:t.frequencyCap,storage:t.storage,storageKey:t.storageKey}),n=new Ae({post:(r,l,u)=>e.getHttp().post(r,l,u),agent:e.getConfiguredAgent()}),o=new ve({client:e,collector:i,governor:s,tracker:n,options:t});o.start();const a={optOut:()=>s.optOut(),optIn:()=>s.optIn(),isOptedOut:()=>s.isOptedOut(),setEngaged:r=>s.setEngaged(r),signalFieldError:r=>i.signalFieldError(r),getSignalsSnapshot:()=>i.getSnapshot(),getActiveNudge:()=>o.getActiveNudge(),shown:r=>o.shown(r),accept:r=>o.accept(r),dismiss:r=>o.dismiss(r),markConverted:r=>o.markConverted(r),destroy:()=>{o.stop(),n.destroy(),i.destroy(),e.removeDynamicContext(O),e.proactive===a&&(e.proactive=null)}};return e.proactive=a,a}var W=class{constructor(){this.entries=new Map,this.dynamicProviders=new Map}set(e,t){this.entries.set(e,t),c.log(`ClientContext set: ${e}`)}remove(e){const t=this.entries.delete(e);return t&&c.log(`ClientContext removed: ${e}`),t}addDynamicProvider(e,t){this.dynamicProviders.set(e,t),c.log(`DynamicContext provider added: ${e}`)}removeDynamicProvider(e){const t=this.dynamicProviders.delete(e);return t&&c.log(`DynamicContext provider removed: ${e}`),t}getSnapshot(){if(this.entries.size===0&&this.dynamicProviders.size===0)return null;const e={};for(const[t,i]of this.entries)e[t]=i;for(const[t,i]of this.dynamicProviders)try{const s=i();s&&(e[t]=s)}catch(s){c.error(`DynamicContext provider "${t}" threw:`,s)}return Object.keys(e).length===0?null:{entries:e}}clear(){this.entries.clear(),this.dynamicProviders.clear(),c.log("ClientContext cleared")}},Ee="page-state:";function _e(e){const t={};for(const[i,s]of Object.entries(e))i.startsWith(Ee)&&s.data&&Object.assign(t,s.data);return t}function ke(e){const t=e["current-page"]?.data;return t?.page?t.page:t?.url?t.url:e["browser-page"]?.data?.url}function Re(e,t){return e===t?!0:JSON.stringify(e)===JSON.stringify(t)}function Ie(e,t){const i=[];for(const s of Object.keys(t))s in e&&(Re(e[s],t[s])||i.push({field:s,from:e[s],to:t[s]}));return i}function xe(e,t){const i=_e(t),s=ke(t);return{changes:e&&e.page===s?Ie(e.state,i):[],baseline:{page:s,state:i}}}function R(e){return e===null||typeof e!="object"?JSON.stringify(e)??"null":Array.isArray(e)?`[${e.map(R).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${R(e[t])}`).join(",")}}`}var K=class{constructor(e){this.callbacks=e,this.buffer="",this.message={},this.toolCalls=[],this.sources=[],this.followUpReplies=[],this.isFirstChunk=!0,this.answerCompleteEmitted=!1,this.waitingClientEmitted=!1,this.firedClientFunctions=new Set}async processStream(e){if(!e.body)throw new A("Response has no body. The endpoint did not return a stream: check that `baseUrl` points at an AGO API and nothing (proxy, mock) strips the SSE body.","stream_no_body");const t=e.body.getReader(),i=new TextDecoder;try{for(;;){const{done:s,value:n}=await t.read();if(s)break;const o=i.decode(n,{stream:!0});this.buffer+=o,this.processBuffer()}return this.buffer.trim()&&this.processBuffer(),this.buildFinalMessage()}catch(s){const n=s instanceof Error?s:new A("Stream processing failed mid-flight. The connection may have dropped; retry the message.");throw this.callbacks.onError?.(n),n}finally{t.releaseLock()}}processBuffer(){const e=this.buffer.split(`
2
2
 
3
3
  `);this.buffer=e.pop()||"";for(const t of e){if(!t.trim())continue;const i=t.split(`
4
- `);for(const s of i)if(!s.startsWith(": ")&&s.startsWith("data: ")){const n=s.slice(6);try{const o=JSON.parse(n);this.handleChunk(o)}catch(o){c.warn("Failed to parse SSE data:",n,o)}}}}handleChunk(e){if(this.callbacks.onRawChunk?.(e),e.message_id&&!this.message.id&&(this.message.id=e.message_id),e.thread?.id&&(this.message.conversationId=e.thread.id,this.isFirstChunk&&this.message.id&&(this.isFirstChunk=!1,this.callbacks.onStart?.({conversationId:this.message.conversationId,messageId:this.message.id}))),e.title&&this.message.conversationId&&this.callbacks.onTitle?.({conversationId:this.message.conversationId,title:e.title}),e.content!==void 0&&(this.message.content=(this.message.content||"")+e.content,this.message.conversationId&&this.message.id&&this.callbacks.onChunk?.({content:e.content,conversationId:this.message.conversationId,messageId:this.message.id})),e.full_content!==void 0&&(this.message.content=e.full_content),e.status&&(this.message.status=e.status),e.agent&&(this.message.agent={id:e.agent.id,name:e.agent.name,displayName:e.agent.display_name}),e.knowledge_sources&&(this.sources=e.knowledge_sources.map(t=>{const i=t.knowledge_document;return{id:i.id,title:i.title,url:i.use_external_link?i.external_link_url:i.internal_link_url}})),e.type==="client_function"&&e.function_name){const t=`${e.function_name}::${R(e.arguments??{})}`;this.firedClientFunctions.has(t)||(this.firedClientFunctions.add(t),this.callbacks.onClientFunction?.({invocationId:e.id||"",functionName:e.function_name,arguments:e.arguments||{},conversationId:this.message.conversationId||""}))}if(e.tool_call_data&&e.type&&e.type!=="client_function"){const t=this.parseToolCall(e);this.callbacks.onToolCall?.(t);const i=this.toolCalls.findIndex(s=>s.id===t.id);i>=0?this.toolCalls[i]=t:this.toolCalls.push(t)}e.follow_up_replies&&(this.followUpReplies=e.follow_up_replies),this.message.status==="DONE"&&!this.answerCompleteEmitted&&this.message.id&&(this.answerCompleteEmitted=!0,this.callbacks.onAnswerComplete?.(this.buildMessage())),this.message.status==="WAITING_CLIENT"&&!this.waitingClientEmitted&&this.message.id&&(this.waitingClientEmitted=!0,this.callbacks.onWaitingClient?.({conversationId:this.message.conversationId||"",messageId:this.message.id,waitingToolCallIds:e.waiting_tool_call_ids??[]}))}parseToolCall(e){return{id:e.id||"",type:e.type||"status_message",status:e.status||"unknown",toolName:e.tool_name||"",toolDisplayName:e.tool_display_name,message:e.message,formSchema:e.form_schema,data:e.data,functionName:e.function_name,arguments:e.arguments}}buildMessage(){return{id:this.message.id||"",conversationId:this.message.conversationId||"",content:this.message.content||"",role:"assistant",status:this.message.status||"DONE",agent:this.message.agent,sources:this.sources.length>0?this.sources:void 0,toolCalls:this.toolCalls.length>0?this.toolCalls:void 0,followUpReplies:this.followUpReplies.length>0?this.followUpReplies:void 0,createdAt:new Date}}buildFinalMessage(){const e=this.buildMessage();return e.status!=="WAITING_CLIENT"&&this.callbacks.onComplete?.(e),e}};function Te(e){const t=e.message.toLowerCase();return t.includes("load failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("abort")}var Fe=new Set(["image/jpeg","image/png","image/gif","image/webp","image/bmp","image/tiff"]);function q(e){if(!e)return;const t=typeof window<"u"&&window.location?window.location.href:"https://ago.local/";try{const i=new URL(e,t);if(i.protocol==="http:"||i.protocol==="https:"||i.protocol==="blob:")return e}catch{}}function Pe(e){return e.isSafeImage===!0&&typeof e.contentType=="string"&&e.contentType.startsWith("image/")&&q(e.url)!==void 0}function Oe(e){if(e==null||e<0)return"";if(e<1024)return`${e} B`;const t=e/1024;return t<1024?`${t.toFixed(1)} KB`:`${(t/1024).toFixed(1)} MB`}function $e(e){return{id:String(e.id??""),name:typeof e.name=="string"&&e.name?e.name:"file",contentType:typeof e.content_type=="string"?e.content_type:void 0,fileSize:typeof e.file_size=="number"?e.file_size:void 0,url:typeof e.file_url=="string"?e.file_url:void 0,isSafeImage:e.is_safe_image===!0}}function Ne(e){return e.map((t,i)=>({id:`local-${i}-${t.name}`,name:t.name,contentType:t.type||void 0,fileSize:t.size,url:typeof URL<"u"&&URL.createObjectURL?URL.createObjectURL(t):void 0,isSafeImage:Fe.has(t.type)}))}var H=class{constructor(){this.handlers=new Map}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t)}off(e,t){const i=this.handlers.get(e);i&&i.delete(t)}emit(e,t){const i=this.handlers.get(e);i&&i.forEach(s=>{try{s(t)}catch(n){console.error(`Error in event handler for ${String(e)}:`,n)}})}once(e,t){const i=(s=>{this.off(e,i),t(s)});this.on(e,i)}waitFor(e,t){return new Promise((i,s)=>{let n;const o=(a=>{n&&clearTimeout(n),i(a)});this.once(e,o),t?.timeout&&(n=setTimeout(()=>{this.off(e,o),s(new Error(`waitFor("${String(e)}") timed out after ${t.timeout}ms`))},t.timeout))})}removeAllListeners(e){e?this.handlers.delete(e):this.handlers.clear()}},$='`baseUrl` is required, e.g. new AgoClient({ baseUrl: "https://YOUR-DOMAIN.api.useago.com" }). Try the live demo endpoint https://playground.api.useago.com. See docs/general/configuration.md#error-codes (config_missing_base_url).',De=/^[a-z][a-z0-9+.-]*:\/\//i,N=!1;function I(e,t="AgoClient"){if(typeof e!="object"||e===null)throw new d(`${t}: ${$}`,"config_missing_base_url");const i=e.baseUrl;if(typeof i!="string"||i.trim()==="")throw new d(`${t}: ${$}`,"config_missing_base_url");!i.startsWith("/")&&!De.test(i)&&(N||(N=!0,console.warn(`[AGO] ${t}: \`baseUrl\` has no protocol and is not a relative path (config_suspect_base_url). Requests will fail: Node throws a URL parse error, browsers fetch it as a relative path. Use "https://..." (or a "/path" for a same-origin proxy).`)))}function Ue(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function S(e){return e.split("/").filter(t=>t.startsWith(":")).map(t=>t.slice(1))}function Me(e,t){const i=[];return{path:e.split("/").map(s=>{if(!s.startsWith(":"))return s;const n=s.slice(1),o=t[n];return o==null||o===""?(i.push(n),s):encodeURIComponent(String(o))}).join("/"),missing:i}}function je(e,t){const i=t.find(n=>n.path===e);if(i)return i;const s=t.find(n=>{if(!n.path.includes(":"))return!1;const o="^"+n.path.split("/").map(a=>a.startsWith(":")?"[^/]+":Ue(a)).join("/")+"/?$";return new RegExp(o).test(e)});return s||t.filter(n=>n.path!=="/"&&e.startsWith(n.path)).sort((n,o)=>o.path.length-n.path.length)[0]}var Le="activity:recent",Be="state:delta",Ge=class z{constructor(t){this.lastSentPageState=null,this.warnedEmptyConversations=new Set,this.pendingResumes=new Map,this.pendingApprovals=new Map,this.resumeGate=null,this.proactive=null,I(t,"AgoClient"),this.config=t,this.activityLedger=new D(t.maxActivityEntries),this.httpClient=new Z(t),this.functionRegistry=new M({maxResultBytes:t.maxFunctionResultBytes}),this.contextRegistry=new W,this.eventEmitter=new H,this.registerActivityContext(),t.debug&&c.enable(),t.proactive&&k(this,t.proactive),c.log("AgoClient initialized")}async sendMessage(t,i){const s=this.functionRegistry.getSchemas(),n=this.buildSendContext(),o=this.config.agent||this.config.defaultAgentId,a=this.resolveClientFunctionsMode(i),r={content:t,conversation_id:i?.conversationId,agent_id:i?.agentId||o};s.length>0&&(r.client_functions=s,a==="pause"&&(r.client_functions_mode=a)),n&&(r.client_context=n),i?.hidden&&(r.hidden=!0);let l;if(i?.files&&i.files.length>0){const u=new FormData;u.append("content",t),i.conversationId&&u.append("conversation_id",i.conversationId),(i.agentId||o)&&u.append("agent_id",i.agentId||o||""),s.length>0&&(u.append("client_functions",JSON.stringify(s)),a==="pause"&&u.append("client_functions_mode",a)),n&&u.append("client_context",JSON.stringify(n)),i.hidden&&u.append("hidden","true");for(const h of i.files)u.append("files",h);l=await this.httpClient.postFormData("/api/sdk/v1/messages",u)}else l=await this.httpClient.postStream("/api/sdk/v1/messages",r);return this.processSSEResponse(l)}async processSSEResponse(t){let i=!1;const s=await new K({onRawChunk:n=>{this.eventEmitter.emit("stream:message",n)},onStart:n=>{this.eventEmitter.emit("message:start",n)},onChunk:n=>{this.eventEmitter.emit("message:chunk",n)},onToolCall:n=>{this.eventEmitter.emit("toolCall:received",n),n.type==="form"&&this.eventEmitter.emit("toolCall:form",n)},onClientFunction:async n=>{if(i=!0,this.eventEmitter.emit("function:invoke",n),this.recordAgentAction(n),n.invocationId&&this.requiresApproval(n)){this.pendingApprovals.set(n.invocationId,n),this.eventEmitter.emit("function:awaiting-approval",n);return}await this.handleClientFunctionInvocation(n)},onTitle:n=>{this.eventEmitter.emit("conversation:title",n)},onAnswerComplete:n=>{this.eventEmitter.emit("message:answer-complete",n)},onWaitingClient:n=>{this.eventEmitter.emit("message:waiting-client",n),this.markResumeSignal(n.messageId,n.conversationId,"waitingConfirmed")},onComplete:n=>{this.eventEmitter.emit("message:complete",n)},onError:n=>{this.eventEmitter.emit("message:error",{error:n.message,code:n instanceof d?n.code:void 0})}}).processStream(t);return s.status!=="WAITING_CLIENT"&&this.maybeFlagEmptyReply(s,i),s}resolveClientFunctionsMode(t){return t?.clientFunctionsMode??this.config.clientFunctionsMode??"pause"}registerResumeGate(t){return this.resumeGate=t,()=>{this.resumeGate===t&&(this.resumeGate=null)}}async continueMessage(t){const i=this.functionRegistry.getSchemas(),s=this.buildSendContext(),n={};i.length>0&&(n.client_functions=i),s&&(n.client_context=s);const o=await this.httpClient.postStream(`/api/sdk/v1/messages/${t}/continue`,n);return this.processSSEResponse(o)}markResumeSignal(t,i,s){if(!t)return;const n=this.pendingResumes.get(t)??{conversationId:i,waitingConfirmed:!1,resultsReady:!1,started:!1};n[s]=!0,i&&(n.conversationId=i),this.pendingResumes.set(t,n),!(!n.waitingConfirmed||!n.resultsReady||n.started)&&(n.started=!0,this.runAutoResume(t,n.conversationId))}async runAutoResume(t,i){try{this.resumeGate&&await this.resumeGate({conversationId:i,messageId:t})}catch(s){c.warn("Resume gate threw; resuming anyway:",s)}this.pendingResumes.delete(t);try{await this.continueMessage(t)}catch(s){c.warn("Auto-resume of paused turn failed:",s)}}maybeFlagEmptyReply(t,i){t.status==="DONE"&&(t.content??"").trim()===""&&!i&&!(t.toolCalls&&t.toolCalls.length>0)&&!(t.followUpReplies&&t.followUpReplies.length>0)&&setTimeout(()=>{if(this.eventEmitter.emit("message:empty",{conversationId:t.conversationId??"",messageId:t.id??""}),this.config.warnOnEmptyReply===!1)return;const s=t.conversationId||"(no conversation)";if(this.warnedEmptyConversations.has(s))return;this.warnedEmptyConversations.add(s);const n=this.config.agent||this.config.defaultAgentId;t.id?console.warn("[AGO] Reply completed with empty content. Possible causes: "+(n?`the agent "${n}" may not exist for this tenant, `:"an unknown `agent` slug, ")+"or the agent replied with no text. Listen for the `message:empty` event to handle this in your app; silence this warning with `warnOnEmptyReply: false`."):console.warn("[AGO] The stream completed without any message data. Possible causes: "+(n?`the agent "${n}" may not exist for this tenant, or `:"")+"`baseUrl` does not point at an AGO endpoint that returns server-sent events. Listen for the `message:empty` event to handle this in your app; silence this warning with `warnOnEmptyReply: false`.")},0)}async handleClientFunctionInvocation(t){let i,s;try{i=await this.functionRegistry.execute(t.functionName,t.arguments)}catch(n){s=n instanceof Error?n.message:"Unknown error",c.error("Client function execution failed:",n)}if(t.invocationId)try{const n=await this.submitToolCallForm(t.invocationId,{result:i,error:s,_type:"client_function_result"});n?.resume?.ready&&this.markResumeSignal(n.resume.message_id,t.conversationId,"resultsReady")}catch(n){c.error("Failed to submit function result:",n)}this.eventEmitter.emit("function:result",{invocationId:t.invocationId,result:i,error:s})}requiresApproval(t){const i=this.config.approvalPolicy;if(i)try{if(i(t))return!0}catch(s){c.warn("approvalPolicy threw; not gating this call:",s)}return this.functionRegistry.get(t.functionName)?.requiresApproval===!0}async approveFunction(t){const i=this.pendingApprovals.get(t);i&&(this.pendingApprovals.delete(t),await this.handleClientFunctionInvocation(i))}async rejectFunction(t){const i=this.pendingApprovals.get(t);if(!i)return;this.pendingApprovals.delete(t);const s={approved:!1,reason:"user_rejected"};try{const n=await this.submitToolCallForm(t,{result:s,_type:"client_function_result"});n?.resume?.ready&&this.markResumeSignal(n.resume.message_id,i.conversationId,"resultsReady")}catch(n){c.error("Failed to submit function rejection:",n)}this.eventEmitter.emit("function:result",{invocationId:t,result:s})}async getConversations(t){const i=new URLSearchParams;t?.page!==void 0&&i.set("page",String(t.page)),t?.pageSize!==void 0&&i.set("page_size",String(t.pageSize));const s=i.toString(),n=await this.httpClient.get(`/api/sdk/v1/conversations${s?`?${s}`:""}`),o=(Array.isArray(n.data)?n.data:[]).map(a=>({id:String(a.id),title:a.title??"",lastMessageDate:new Date(a.last_message_at??a.created_at??0)}));return{data:o,hasMore:n.has_more??!1,total:n.total??o.length}}async getConversation(t){const i=await this.httpClient.get(`/api/sdk/v1/conversations/${t}`),s={id:i.id,title:i.title,lastMessageDate:new Date(i.last_message_at??i.created_at??0),messages:i.messages.map(n=>({id:n.id,conversationId:i.id,content:n.content,role:n.role,status:n.status,createdAt:new Date(n.created_at),hidden:n.hidden,toolCalls:z.mapPersistedToolCalls(n.tool_call_data),attachments:n.attachments&&n.attachments.length>0?n.attachments.map($e):void 0}))};return this.eventEmitter.emit("conversation:loaded",s),s}static mapPersistedToolCalls(t){if(!(!t||t.length===0))return t.map(i=>({id:String(i.id??""),type:i.type??"status_message",status:String(i.status??"unknown"),toolName:i.tool_name??"",toolDisplayName:i.tool_display_name,message:i.message,formSchema:i.form_schema,data:i.data,functionName:i.function_name,arguments:i.arguments}))}async getMessages(t){return(await this.getConversation(t)).messages||[]}async resumePendingClientFunctions(t){const i=[...t.messages??[]].reverse().find(r=>r.role==="assistant"&&r.status==="WAITING_CLIENT");if(!i)return null;const s=(i.toolCalls??[]).filter(r=>r.type==="client_function"&&r.status==="waiting_input"&&r.functionName),n=new Set(this.functionRegistry.getSchemas().map(r=>r.name)),o=s.filter(r=>!n.has(r.functionName));if(o.length>0)return c.warn("Cannot resume paused turn: function(s) not registered on this page:",o.map(r=>r.functionName)),null;let a=s.length===0;for(const r of s){const l={invocationId:r.id,functionName:r.functionName,arguments:r.arguments??{},conversationId:t.id};if(this.requiresApproval(l)){this.pendingApprovals.set(r.id,l),this.markResumeSignal(i.id,t.id,"waitingConfirmed"),this.eventEmitter.emit("function:awaiting-approval",l),a=!1;continue}let u,h;try{u=await this.functionRegistry.execute(r.functionName,r.arguments??{})}catch(g){h=g instanceof Error?g.message:"Unknown error",c.error("Client function execution failed:",g)}a=(await this.submitToolCallForm(r.id,{result:u,error:h,_type:"client_function_result"}))?.resume?.ready??a}return a?this.continueMessage(i.id):null}async submitToolCallForm(t,i){return this.httpClient.post(`/api/sdk/v1/tool-calls/${t}/submit`,{formData:i})}async confirmToolCall(t){await this.httpClient.post(`/api/tool-calls/${t}/confirm/`)}async rejectToolCall(t){await this.httpClient.post(`/api/tool-calls/${t}/reject/`)}async getFormCollector(t){const i=await this.httpClient.get(`/api/sdk/v1/forms/${encodeURIComponent(t)}`);return{name:i.name,description:i.description,schema:i.schema,submit:i.submit??void 0}}async submitFormCollector(t,i){return this.httpClient.post("/api/sdk/v1/forms/submit",{name:t,values:i})}async submitFeedback(t,i){await this.httpClient.post(`/api/sdk/v1/messages/${t}/feedback`,{rating:i})}registerFunction(t,i,s){typeof t=="object"?this.functionRegistry.register(t):this.functionRegistry.register(t,i,s)}register(t){if(Array.isArray(t))for(const i of t)this.functionRegistry.register(i);else this.functionRegistry.register(t)}unregisterFunction(t){return this.functionRegistry.unregister(t)}getRegisteredFunctions(){return this.functionRegistry.getSchemas()}async executeClientFunction(t,i){return this.functionRegistry.execute(t,i)}registerNavigationFunction(t,i){const s=i.map(r=>r.name),n=i.map(r=>{const l=S(r.path),u=l.length>0?` (requires ${l.map(h=>`"${h}"`).join(", ")})`:"";return`- "${r.name}"${u}: ${r.description}`}).join(`
4
+ `);for(const s of i)if(!s.startsWith(": ")&&s.startsWith("data: ")){const n=s.slice(6);try{const o=JSON.parse(n);this.handleChunk(o)}catch(o){c.warn("Failed to parse SSE data:",n,o)}}}}handleChunk(e){if(this.callbacks.onRawChunk?.(e),e.message_id&&!this.message.id&&(this.message.id=e.message_id),e.thread?.id&&(this.message.conversationId=e.thread.id,this.isFirstChunk&&this.message.id&&(this.isFirstChunk=!1,this.callbacks.onStart?.({conversationId:this.message.conversationId,messageId:this.message.id}))),e.title&&this.message.conversationId&&this.callbacks.onTitle?.({conversationId:this.message.conversationId,title:e.title}),e.content!==void 0&&(this.message.content=(this.message.content||"")+e.content,this.message.conversationId&&this.message.id&&this.callbacks.onChunk?.({content:e.content,conversationId:this.message.conversationId,messageId:this.message.id})),e.full_content!==void 0&&(this.message.content=e.full_content),e.status&&(this.message.status=e.status),e.agent&&(this.message.agent={id:e.agent.id,name:e.agent.name,displayName:e.agent.display_name}),e.knowledge_sources&&(this.sources=e.knowledge_sources.map(t=>{const i=t.knowledge_document;return{id:i.id,title:i.title,url:i.use_external_link?i.external_link_url:i.internal_link_url}})),e.type==="client_function"&&e.function_name){const t=`${e.function_name}::${R(e.arguments??{})}`;this.firedClientFunctions.has(t)||(this.firedClientFunctions.add(t),this.callbacks.onClientFunction?.({invocationId:e.id||"",functionName:e.function_name,arguments:e.arguments||{},conversationId:this.message.conversationId||""}))}if(e.tool_call_data&&e.type&&e.type!=="client_function"){const t=this.parseToolCall(e);this.callbacks.onToolCall?.(t);const i=this.toolCalls.findIndex(s=>s.id===t.id);i>=0?this.toolCalls[i]=t:this.toolCalls.push(t)}e.follow_up_replies&&(this.followUpReplies=e.follow_up_replies),this.message.status==="DONE"&&!this.answerCompleteEmitted&&this.message.id&&(this.answerCompleteEmitted=!0,this.callbacks.onAnswerComplete?.(this.buildMessage())),this.message.status==="WAITING_CLIENT"&&!this.waitingClientEmitted&&this.message.id&&(this.waitingClientEmitted=!0,this.callbacks.onWaitingClient?.({conversationId:this.message.conversationId||"",messageId:this.message.id,waitingToolCallIds:e.waiting_tool_call_ids??[]}))}parseToolCall(e){return{id:e.id||"",type:e.type||"status_message",status:e.status||"unknown",toolName:e.tool_name||"",toolDisplayName:e.tool_display_name,message:e.message,formSchema:e.form_schema,data:e.data,functionName:e.function_name,arguments:e.arguments}}buildMessage(){return{id:this.message.id||"",conversationId:this.message.conversationId||"",content:this.message.content||"",role:"assistant",status:this.message.status||"DONE",agent:this.message.agent,sources:this.sources.length>0?this.sources:void 0,toolCalls:this.toolCalls.length>0?this.toolCalls:void 0,followUpReplies:this.followUpReplies.length>0?this.followUpReplies:void 0,createdAt:new Date}}buildFinalMessage(){const e=this.buildMessage();return e.status!=="WAITING_CLIENT"&&this.callbacks.onComplete?.(e),e}};function Te(e){const t=e.message.toLowerCase();return t.includes("load failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("abort")}var Fe=new Set(["image/jpeg","image/png","image/gif","image/webp","image/bmp","image/tiff"]);function q(e){if(!e)return;const t=typeof window<"u"&&window.location?window.location.href:"https://ago.local/";try{const i=new URL(e,t);if(i.protocol==="http:"||i.protocol==="https:"||i.protocol==="blob:")return e}catch{}}function Pe(e){return e.isSafeImage===!0&&typeof e.contentType=="string"&&e.contentType.startsWith("image/")&&q(e.url)!==void 0}function Oe(e){if(e==null||e<0)return"";if(e<1024)return`${e} B`;const t=e/1024;return t<1024?`${t.toFixed(1)} KB`:`${(t/1024).toFixed(1)} MB`}function $e(e){return{id:String(e.id??""),name:typeof e.name=="string"&&e.name?e.name:"file",contentType:typeof e.content_type=="string"?e.content_type:void 0,fileSize:typeof e.file_size=="number"?e.file_size:void 0,url:typeof e.file_url=="string"?e.file_url:void 0,isSafeImage:e.is_safe_image===!0}}function Ne(e){return e.map((t,i)=>({id:`local-${i}-${t.name}`,name:t.name,contentType:t.type||void 0,fileSize:t.size,url:typeof URL<"u"&&URL.createObjectURL?URL.createObjectURL(t):void 0,isSafeImage:Fe.has(t.type)}))}var H=class{constructor(){this.handlers=new Map}on(e,t){this.handlers.has(e)||this.handlers.set(e,new Set),this.handlers.get(e).add(t)}off(e,t){const i=this.handlers.get(e);i&&i.delete(t)}emit(e,t){const i=this.handlers.get(e);i&&i.forEach(s=>{try{s(t)}catch(n){console.error(`Error in event handler for ${String(e)}:`,n)}})}once(e,t){const i=(s=>{this.off(e,i),t(s)});this.on(e,i)}waitFor(e,t){return new Promise((i,s)=>{let n;const o=(a=>{n&&clearTimeout(n),i(a)});this.once(e,o),t?.timeout&&(n=setTimeout(()=>{this.off(e,o),s(new Error(`waitFor("${String(e)}") timed out after ${t.timeout}ms`))},t.timeout))})}removeAllListeners(e){e?this.handlers.delete(e):this.handlers.clear()}},$='`baseUrl` is required, e.g. new AgoClient({ baseUrl: "https://YOUR-DOMAIN.api.useago.com" }). Try the live demo endpoint https://playground.api.useago.com. See docs/general/configuration.md#error-codes (config_missing_base_url).',De=/^[a-z][a-z0-9+.-]*:\/\//i,N=!1;function I(e,t="AgoClient"){if(typeof e!="object"||e===null)throw new d(`${t}: ${$}`,"config_missing_base_url");const i=e.baseUrl;if(typeof i!="string"||i.trim()==="")throw new d(`${t}: ${$}`,"config_missing_base_url");!i.startsWith("/")&&!De.test(i)&&(N||(N=!0,console.warn(`[AGO] ${t}: \`baseUrl\` has no protocol and is not a relative path (config_suspect_base_url). Requests will fail: Node throws a URL parse error, browsers fetch it as a relative path. Use "https://..." (or a "/path" for a same-origin proxy).`)))}function Ue(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function S(e){return e.split("/").filter(t=>t.startsWith(":")).map(t=>t.slice(1))}function Me(e,t){const i=[];return{path:e.split("/").map(s=>{if(!s.startsWith(":"))return s;const n=s.slice(1),o=t[n];return o==null||o===""?(i.push(n),s):encodeURIComponent(String(o))}).join("/"),missing:i}}function je(e,t){const i=t.find(n=>n.path===e);if(i)return i;const s=t.find(n=>{if(!n.path.includes(":"))return!1;const o="^"+n.path.split("/").map(a=>a.startsWith(":")?"[^/]+":Ue(a)).join("/")+"/?$";return new RegExp(o).test(e)});return s||t.filter(n=>n.path!=="/"&&e.startsWith(n.path)).sort((n,o)=>o.path.length-n.path.length)[0]}var Le="activity:recent",Be="state:delta",Ge=class z{constructor(t){this.lastSentPageState=null,this.warnedEmptyConversations=new Set,this.pendingResumes=new Map,this.pendingApprovals=new Map,this.resumeGate=null,this.proactive=null,I(t,"AgoClient"),this.config=t,this.activityLedger=new D(t.maxActivityEntries),this.httpClient=new Z(t),this.functionRegistry=new M({maxResultBytes:t.maxFunctionResultBytes}),this.contextRegistry=new W,this.eventEmitter=new H,this.registerActivityContext(),t.debug&&c.enable(),t.proactive&&k(this,t.proactive),c.log("AgoClient initialized")}async sendMessage(t,i){const s=this.functionRegistry.getSchemas(),n=this.buildSendContext(),o=this.config.agent||this.config.defaultAgentId,a=this.resolveClientFunctionsMode(i),r={content:t,conversation_id:i?.conversationId,agent_id:i?.agentId||o};s.length>0&&(r.client_functions=s,a==="pause"&&(r.client_functions_mode=a)),n&&(r.client_context=n),i?.hidden&&(r.hidden=!0);let l;if(i?.files&&i.files.length>0){const u=new FormData;u.append("content",t),i.conversationId&&u.append("conversation_id",i.conversationId),(i.agentId||o)&&u.append("agent_id",i.agentId||o||""),s.length>0&&(u.append("client_functions",JSON.stringify(s)),a==="pause"&&u.append("client_functions_mode",a)),n&&u.append("client_context",JSON.stringify(n)),i.hidden&&u.append("hidden","true");for(const h of i.files)u.append("files",h);l=await this.httpClient.postFormData("/api/sdk/v1/messages",u)}else l=await this.httpClient.postStream("/api/sdk/v1/messages",r);return this.processSSEResponse(l)}async processSSEResponse(t){let i=!1;const s=await new K({onRawChunk:n=>{this.eventEmitter.emit("stream:message",n)},onStart:n=>{this.eventEmitter.emit("message:start",n)},onChunk:n=>{this.eventEmitter.emit("message:chunk",n)},onToolCall:n=>{this.eventEmitter.emit("toolCall:received",n),n.type==="form"&&this.eventEmitter.emit("toolCall:form",n)},onClientFunction:async n=>{if(i=!0,this.eventEmitter.emit("function:invoke",n),this.recordAgentAction(n),n.invocationId&&this.requiresApproval(n)){this.pendingApprovals.set(n.invocationId,n),this.eventEmitter.emit("function:awaiting-approval",n);return}await this.handleClientFunctionInvocation(n)},onTitle:n=>{this.eventEmitter.emit("conversation:title",n)},onAnswerComplete:n=>{this.eventEmitter.emit("message:answer-complete",n)},onWaitingClient:n=>{this.eventEmitter.emit("message:waiting-client",n),this.markResumeSignal(n.messageId,n.conversationId,"waitingConfirmed")},onComplete:n=>{this.eventEmitter.emit("message:complete",n)},onError:n=>{this.eventEmitter.emit("message:error",{error:n.message,code:n instanceof d?n.code:void 0})}}).processStream(t);return s.status!=="WAITING_CLIENT"&&this.maybeFlagEmptyReply(s,i),s}resolveClientFunctionsMode(t){return t?.clientFunctionsMode??this.config.clientFunctionsMode??"pause"}registerResumeGate(t){return this.resumeGate=t,()=>{this.resumeGate===t&&(this.resumeGate=null)}}async continueMessage(t){const i=this.functionRegistry.getSchemas(),s=this.buildSendContext(),n={};i.length>0&&(n.client_functions=i),s&&(n.client_context=s);const o=await this.httpClient.postStream(`/api/sdk/v1/messages/${t}/continue`,n);return this.processSSEResponse(o)}markResumeSignal(t,i,s){if(!t)return;const n=this.pendingResumes.get(t)??{conversationId:i,waitingConfirmed:!1,resultsReady:!1,started:!1};n[s]=!0,i&&(n.conversationId=i),this.pendingResumes.set(t,n),!(!n.waitingConfirmed||!n.resultsReady||n.started)&&(n.started=!0,this.runAutoResume(t,n.conversationId))}async runAutoResume(t,i){try{this.resumeGate&&await this.resumeGate({conversationId:i,messageId:t})}catch(s){c.warn("Resume gate threw; resuming anyway:",s)}this.pendingResumes.delete(t);try{await this.continueMessage(t)}catch(s){c.warn("Auto-resume of paused turn failed:",s)}}maybeFlagEmptyReply(t,i){t.status==="DONE"&&(t.content??"").trim()===""&&!i&&!(t.toolCalls&&t.toolCalls.length>0)&&!(t.followUpReplies&&t.followUpReplies.length>0)&&setTimeout(()=>{if(this.eventEmitter.emit("message:empty",{conversationId:t.conversationId??"",messageId:t.id??""}),this.config.warnOnEmptyReply===!1)return;const s=t.conversationId||"(no conversation)";if(this.warnedEmptyConversations.has(s))return;this.warnedEmptyConversations.add(s);const n=this.config.agent||this.config.defaultAgentId;t.id?console.warn("[AGO] Reply completed with empty content. Possible causes: "+(n?`the agent "${n}" may not exist for this tenant, `:"an unknown `agent` slug, ")+"or the agent replied with no text. Listen for the `message:empty` event to handle this in your app; silence this warning with `warnOnEmptyReply: false`."):console.warn("[AGO] The stream completed without any message data. Possible causes: "+(n?`the agent "${n}" may not exist for this tenant, or `:"")+"`baseUrl` does not point at an AGO endpoint that returns server-sent events. Listen for the `message:empty` event to handle this in your app; silence this warning with `warnOnEmptyReply: false`.")},0)}async handleClientFunctionInvocation(t){let i,s;try{i=await this.functionRegistry.execute(t.functionName,t.arguments)}catch(n){s=n instanceof Error?n.message:"Unknown error",c.error("Client function execution failed:",n)}if(t.invocationId)try{const n=await this.submitToolCallForm(t.invocationId,{result:i,error:s,_type:"client_function_result"});n?.resume?.ready&&this.markResumeSignal(n.resume.message_id,t.conversationId,"resultsReady")}catch(n){c.error("Failed to submit function result:",n)}this.eventEmitter.emit("function:result",{invocationId:t.invocationId,result:i,error:s})}requiresApproval(t){const i=this.config.approvalPolicy;if(i)try{if(i(t))return!0}catch(s){c.warn("approvalPolicy threw; not gating this call:",s)}return this.functionRegistry.get(t.functionName)?.requiresApproval===!0}async approveFunction(t){const i=this.pendingApprovals.get(t);i&&(this.pendingApprovals.delete(t),await this.handleClientFunctionInvocation(i))}async rejectFunction(t){const i=this.pendingApprovals.get(t);if(!i)return;this.pendingApprovals.delete(t);const s={approved:!1,reason:"user_rejected"};try{const n=await this.submitToolCallForm(t,{result:s,_type:"client_function_result"});n?.resume?.ready&&this.markResumeSignal(n.resume.message_id,i.conversationId,"resultsReady")}catch(n){c.error("Failed to submit function rejection:",n)}this.eventEmitter.emit("function:result",{invocationId:t,result:s})}async getConversations(t){const i=new URLSearchParams;t?.page!==void 0&&i.set("page",String(t.page)),t?.pageSize!==void 0&&i.set("page_size",String(t.pageSize));const s=i.toString(),n=await this.httpClient.get(`/api/sdk/v1/conversations${s?`?${s}`:""}`),o=(Array.isArray(n.data)?n.data:[]).map(a=>({id:String(a.id),title:a.title??"",lastMessageDate:new Date(a.last_message_at??a.created_at??0)}));return{data:o,hasMore:n.has_more??!1,total:n.total??o.length}}async getConversation(t){const i=await this.httpClient.get(`/api/sdk/v1/conversations/${t}`),s={id:i.id,title:i.title,lastMessageDate:new Date(i.last_message_at??i.created_at??0),messages:i.messages.map(n=>({id:n.id,conversationId:i.id,content:n.content,role:n.role,status:n.status,createdAt:new Date(n.created_at),hidden:n.hidden,toolCalls:z.mapPersistedToolCalls(n.tool_call_data),attachments:n.attachments&&n.attachments.length>0?n.attachments.map($e):void 0,followUpReplies:n.follow_up_replies&&n.follow_up_replies.length>0?n.follow_up_replies:void 0}))};return this.eventEmitter.emit("conversation:loaded",s),s}static mapPersistedToolCalls(t){if(!(!t||t.length===0))return t.map(i=>({id:String(i.id??""),type:i.type??"status_message",status:String(i.status??"unknown"),toolName:i.tool_name??"",toolDisplayName:i.tool_display_name,message:i.message,formSchema:i.form_schema,data:i.data,functionName:i.function_name,arguments:i.arguments}))}async getMessages(t){return(await this.getConversation(t)).messages||[]}async resumePendingClientFunctions(t){const i=[...t.messages??[]].reverse().find(r=>r.role==="assistant"&&r.status==="WAITING_CLIENT");if(!i)return null;const s=(i.toolCalls??[]).filter(r=>r.type==="client_function"&&r.status==="waiting_input"&&r.functionName),n=new Set(this.functionRegistry.getSchemas().map(r=>r.name)),o=s.filter(r=>!n.has(r.functionName));if(o.length>0)return c.warn("Cannot resume paused turn: function(s) not registered on this page:",o.map(r=>r.functionName)),null;let a=s.length===0;for(const r of s){const l={invocationId:r.id,functionName:r.functionName,arguments:r.arguments??{},conversationId:t.id};if(this.requiresApproval(l)){this.pendingApprovals.set(r.id,l),this.markResumeSignal(i.id,t.id,"waitingConfirmed"),this.eventEmitter.emit("function:awaiting-approval",l),a=!1;continue}let u,h;try{u=await this.functionRegistry.execute(r.functionName,r.arguments??{})}catch(g){h=g instanceof Error?g.message:"Unknown error",c.error("Client function execution failed:",g)}a=(await this.submitToolCallForm(r.id,{result:u,error:h,_type:"client_function_result"}))?.resume?.ready??a}return a?this.continueMessage(i.id):null}async submitToolCallForm(t,i){return this.httpClient.post(`/api/sdk/v1/tool-calls/${t}/submit`,{formData:i})}async confirmToolCall(t){await this.httpClient.post(`/api/tool-calls/${t}/confirm/`)}async rejectToolCall(t){await this.httpClient.post(`/api/tool-calls/${t}/reject/`)}async getFormCollector(t){const i=await this.httpClient.get(`/api/sdk/v1/forms/${encodeURIComponent(t)}`);return{name:i.name,description:i.description,schema:i.schema,submit:i.submit??void 0}}async submitFormCollector(t,i){return this.httpClient.post("/api/sdk/v1/forms/submit",{name:t,values:i})}async submitFeedback(t,i){await this.httpClient.post(`/api/sdk/v1/messages/${t}/feedback`,{rating:i})}registerFunction(t,i,s){typeof t=="object"?this.functionRegistry.register(t):this.functionRegistry.register(t,i,s)}register(t){if(Array.isArray(t))for(const i of t)this.functionRegistry.register(i);else this.functionRegistry.register(t)}unregisterFunction(t){return this.functionRegistry.unregister(t)}getRegisteredFunctions(){return this.functionRegistry.getSchemas()}async executeClientFunction(t,i){return this.functionRegistry.execute(t,i)}registerNavigationFunction(t,i){const s=i.map(r=>r.name),n=i.map(r=>{const l=S(r.path),u=l.length>0?` (requires ${l.map(h=>`"${h}"`).join(", ")})`:"";return`- "${r.name}"${u}: ${r.description}`}).join(`
5
5
  `),o=new Map;for(const r of i)for(const l of S(r.path))o.set(l,[...o.get(l)??[],r.name]);const a={page:{type:"string",description:"The page to navigate to",enum:s}};for(const[r,l]of o){if(r==="page"){c.error('registerNavigationFunction: a ":page" placeholder collides with the "page" argument and is ignored. Rename the placeholder.');continue}a[r]={type:"string",description:`Value for ":${r}" in the page path. Required when page is ${l.map(u=>`"${u}"`).join(" or ")}.`}}this.registerFunction("navigateToPage",async r=>{const l=r.page,u=i.find(f=>f.name===l);if(!u)return{success:!1,error:`Unknown page: ${l}`};let h={};if(typeof r.params=="string")try{h=JSON.parse(r.params)}catch{}else r.params&&typeof r.params=="object"&&(h=r.params);const g={};for(const f of S(u.path))g[f]=r[f]??h[f];const{path:m,missing:v}=Me(u.path,g);if(v.length>0){const f=v.map(w=>`"${w}": "..."`).join(", ");return{success:!1,error:`Page "${l}" needs ${v.map(w=>`"${w}"`).join(", ")}. Retry with { "page": "${l}", ${f} }.`}}return t(m),{success:!0,navigatedTo:m}},{description:`Navigate the user to a page in the application. Available pages:
6
6
  ${n}`,parameters:{type:"object",properties:a,required:["page"]}}),this.addDynamicContext("current-page",()=>{if(typeof window>"u"||!window.location)return null;const r=window.location.href,l=typeof document<"u"?document.title:void 0,u=je(window.location.pathname,i),h={url:r};return u&&(h.page=u.name),l&&(h.title=l),{name:"Current page",description:"The page the user is currently viewing.",data:h}})}unregisterNavigationFunction(){this.unregisterFunction("navigateToPage"),this.removeDynamicContext("current-page")}registerPageStateFunction(t,i){const s=i?.functionName??"setPageState",n=new Map(t.map(a=>[a.name,a])),o=t.map(a=>`- "${a.name}": ${a.description}`).join(`
7
7
  `);this.registerFunction(s,async a=>{const r={};for(const[l,u]of Object.entries(a)){if(u===void 0)continue;const h=n.get(l);h&&(await h.set(u),r[l]=u)}return{success:!0,applied:r}},{description:`Change the state of the current page. Set ONLY the controls the user explicitly asked for; leave the others unset. Available controls:
package/dist/angular.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./AgoClient-CQh8YovA.cjs"),c=require("./autoContinue-CP9pJR-V.cjs");var n=class{constructor(t){this.client=new o.AgoClient(t),this.messages$=this.fromEvent("message:complete"),this.chunks$=this.fromEvent("message:chunk"),this.errors$=this.fromEvent("message:error"),this.messageStart$=this.fromEvent("message:start")}fromEvent(t){const e=this.client;return{subscribe(i){const r=s=>{i.next?.(s)};return e.on(t,r),{unsubscribe:()=>e.off(t,r)}}}}sendMessage(t,e){return this.client.sendMessage(t,e)}getConversations(){return this.client.getConversations().then(t=>t.data)}getConversation(t){return this.client.getConversation(t)}getMessages(t){return this.client.getMessages(t)}submitToolCallForm(t,e){return this.client.submitToolCallForm(t,e)}confirmToolCall(t){return this.client.confirmToolCall(t)}rejectToolCall(t){return this.client.rejectToolCall(t)}submitFeedback(t,e){return this.client.submitFeedback(t,e)}registerFunction(t,e,i){typeof t=="object"?this.client.registerFunction(t):this.client.registerFunction(t,e,i)}unregisterFunction(t){return this.client.unregisterFunction(t)}registerNavigationFunction(t,e){this.client.registerNavigationFunction(t,e)}unregisterNavigationFunction(){this.client.unregisterNavigationFunction()}enableAutoContinueAfterNavigation(t){return c.attachAutoContinueAfterNavigation(this.client,t)}registerPageStateFunction(t,e){this.client.registerPageStateFunction(t,e)}unregisterPageStateFunction(t){this.client.unregisterPageStateFunction(t)}on(t,e){this.client.on(t,e)}off(t,e){this.client.off(t,e)}updateConfig(t){this.client.updateConfig(t)}getClient(){return this.client}destroy(){this.client.destroy()}};function u(t){return{provide:n,useValue:new n(t)}}exports.AgoService=n;exports.provideAgo=u;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./AgoClient-DLB9icvv.cjs"),c=require("./autoContinue-CP9pJR-V.cjs");var n=class{constructor(t){this.client=new o.AgoClient(t),this.messages$=this.fromEvent("message:complete"),this.chunks$=this.fromEvent("message:chunk"),this.errors$=this.fromEvent("message:error"),this.messageStart$=this.fromEvent("message:start")}fromEvent(t){const e=this.client;return{subscribe(i){const r=s=>{i.next?.(s)};return e.on(t,r),{unsubscribe:()=>e.off(t,r)}}}}sendMessage(t,e){return this.client.sendMessage(t,e)}getConversations(){return this.client.getConversations().then(t=>t.data)}getConversation(t){return this.client.getConversation(t)}getMessages(t){return this.client.getMessages(t)}submitToolCallForm(t,e){return this.client.submitToolCallForm(t,e)}confirmToolCall(t){return this.client.confirmToolCall(t)}rejectToolCall(t){return this.client.rejectToolCall(t)}submitFeedback(t,e){return this.client.submitFeedback(t,e)}registerFunction(t,e,i){typeof t=="object"?this.client.registerFunction(t):this.client.registerFunction(t,e,i)}unregisterFunction(t){return this.client.unregisterFunction(t)}registerNavigationFunction(t,e){this.client.registerNavigationFunction(t,e)}unregisterNavigationFunction(){this.client.unregisterNavigationFunction()}enableAutoContinueAfterNavigation(t){return c.attachAutoContinueAfterNavigation(this.client,t)}registerPageStateFunction(t,e){this.client.registerPageStateFunction(t,e)}unregisterPageStateFunction(t){this.client.unregisterPageStateFunction(t)}on(t,e){this.client.on(t,e)}off(t,e){this.client.off(t,e)}updateConfig(t){this.client.updateConfig(t)}getClient(){return this.client}destroy(){this.client.destroy()}};function u(t){return{provide:n,useValue:new n(t)}}exports.AgoService=n;exports.provideAgo=u;
package/dist/angular.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as o } from "./AgoClient-BI5esqbd.js";
1
+ import { t as o } from "./AgoClient-B_R_qi2s.js";
2
2
  import { t as c } from "./autoContinue-CC8K9mBU.js";
3
3
  var s = class {
4
4
  constructor(t) {
@@ -1,4 +1,4 @@
1
- import { h as d } from "./AgoClient-BI5esqbd.js";
1
+ import { h as d } from "./AgoClient-B_R_qi2s.js";
2
2
  var f = "ago_widget_id", g = "ago_last_thread", y = 7200 * 1e3;
3
3
  function v() {
4
4
  return typeof crypto < "u" && typeof crypto.randomUUID == "function" ? crypto.randomUUID() : "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (e) => {
@@ -1 +1 @@
1
- const d=require("./AgoClient-CQh8YovA.cjs");var f="ago_widget_id",g="ago_last_thread",y=7200*1e3;function v(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const r=Math.floor(Math.random()*16);return(e==="x"?r:r&3|8).toString(16)})}function _(e={}){const r=e.key??f,i=e.threadKey??g,u=e.ttlMs??y,l=e.storage??(typeof localStorage<"u"?localStorage:void 0);let n=e.widgetId??"";if(!n&&l)try{n=l.getItem(r)??""}catch{}if(n||(n=v()),l)try{l.setItem(r,n)}catch{}const o=d.createStore({value:null,lastMessageAt:null},{key:i,storage:l}),s=o.get();s.value!==null&&c(s.lastMessageAt)&&o.set({value:null,lastMessageAt:null});function c(t){return t===null?!0:Number.isFinite(u)?Date.now()-t>u:!1}return{widgetId:n,key:r,getLastActiveThread(){const{value:t,lastMessageAt:a}=o.get();return t===null||c(a)?null:t},setActiveThread(t,a){const x=a==null?null:a instanceof Date?a.getTime():a;o.set({value:t,lastMessageAt:x})},clear(){o.set({value:null,lastMessageAt:null})}}}Object.defineProperty(exports,"createConversationSession",{enumerable:!0,get:function(){return _}});
1
+ const d=require("./AgoClient-DLB9icvv.cjs");var f="ago_widget_id",g="ago_last_thread",y=7200*1e3;function v(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{const r=Math.floor(Math.random()*16);return(e==="x"?r:r&3|8).toString(16)})}function _(e={}){const r=e.key??f,i=e.threadKey??g,u=e.ttlMs??y,l=e.storage??(typeof localStorage<"u"?localStorage:void 0);let n=e.widgetId??"";if(!n&&l)try{n=l.getItem(r)??""}catch{}if(n||(n=v()),l)try{l.setItem(r,n)}catch{}const o=d.createStore({value:null,lastMessageAt:null},{key:i,storage:l}),s=o.get();s.value!==null&&c(s.lastMessageAt)&&o.set({value:null,lastMessageAt:null});function c(t){return t===null?!0:Number.isFinite(u)?Date.now()-t>u:!1}return{widgetId:n,key:r,getLastActiveThread(){const{value:t,lastMessageAt:a}=o.get();return t===null||c(a)?null:t},setActiveThread(t,a){const x=a==null?null:a instanceof Date?a.getTime():a;o.set({value:t,lastMessageAt:x})},clear(){o.set({value:null,lastMessageAt:null})}}}Object.defineProperty(exports,"createConversationSession",{enumerable:!0,get:function(){return _}});
@@ -1 +1 @@
1
- const C=require("./AgoClient-CQh8YovA.cjs");var W=/^[a-zA-Z0-9_-]{1,40}$/,A=n=>n==null||n==="";function S(n,e){if("anyOf"in n)return n.anyOf.some(c=>S(c,e));if("allOf"in n)return n.allOf.every(c=>S(c,e));const l=e[n.property];if(A(l))return!1;if(Array.isArray(n.value))return n.value.some(c=>String(l)===String(c));if(!n.op)return String(l)===String(n.value);const i=Number(l),a=Number(n.value);if(Number.isNaN(i)||Number.isNaN(a))return!1;switch(n.op){case">=":return i>=a;case"<=":return i<=a;case">":return i>a;case"<":return i<a;default:return C.logger.warn(`Unknown requiredWhen op "${n.op}"; treating as not required.`),!1}}function h(n,e){const l=n.properties??{},i=new Set;for(const c of n.required??[]){const d=l[c]?.requiredWhen;(!d||S(d,e))&&i.add(c)}for(const[c,d]of Object.entries(l))d.requiredWhen&&S(d.requiredWhen,e)&&i.add(c);const a=[...i].filter(c=>A(e[c]));return{missing:a,complete:a.length===0}}function B(n){const e={};for(const[l,i]of Object.entries(n.properties??{}))e[l]={type:i.type,...i.description!=null&&{description:i.description},...i.enum&&{enum:i.enum},...i.default!==void 0&&{default:i.default}};return{type:"object",properties:e,required:[]}}function V(n){const{name:e,description:l,schema:i}=n;if(!W.test(e))throw new Error(`Invalid form collector name "${e}": must match ${W} (it becomes the update_/submit_ function names).`);const a=typeof n.submit=="string"?n.submit?{via:"client",url:n.submit}:!1:n.submit??!1;n.autoSubmit===!0&&!a&&C.logger.warn(`FormCollector "${e}": autoSubmit is ignored because no submit target is configured.`);const c=(n.autoSubmit??!0)&&!!a,d=i.properties??{},$=t=>{const r={};for(const[o,s]of Object.entries(t)){const u=d[o];if(u)if(s==null)r[o]=s;else if(u.type==="number"||u.type==="integer"){const f=typeof s=="number"?s:Number(s);r[o]=Number.isNaN(f)?s:f}else u.type==="boolean"?r[o]=typeof s=="boolean"?s:s==="true"?!0:s==="false"?!1:!!s:r[o]=s}return r},N=n.initialValues??{},m=C.createStore({values:N,submitted:!1}),w=t=>{const r=m.get(),o={...r,values:{...r.values,...t}};return m.set(o),o};let b=null;const k=(t,r)=>{b?.emitFormEvent("form:error",{name:e,values:t,error:r})};let p=null;const I=async()=>{const{values:t}=m.get(),{complete:r,missing:o}=h(i,t);if(!r)return{ok:!1,missing:o};if(!a)return{ok:!1,error:"No submit target configured for this form collector."};const s=t;try{let u;if(a.via==="client")if("handler"in a)u=await a.handler(s);else{const f=await fetch(a.url,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(s)});if(!f.ok){const j=`Submit failed: HTTP ${f.status}`;return k(s,j),{ok:!1,error:j}}u=await f.json().catch(()=>{})}else{if(!b)return{ok:!1,error:"Backend submit requires install(client) (or useFormCollector) first."};u=await b.submitFormCollector(e,s)}return m.set({...m.get(),submitted:!0,submitResult:u}),b?.emitFormEvent("form:submitted",{name:e,values:s,result:u}),{ok:!0,result:u}}catch(u){const f=u instanceof Error?u.message:"Submit failed";return C.logger.error(`FormCollector "${e}" submit failed:`,u),k(s,f),{ok:!1,error:f}}},F=()=>p||(p=(async()=>{try{return await I()}finally{p=null}})(),p),q=async()=>{if(!c||!a)return null;const{values:t,submitted:r}=m.get();return r||!h(i,t).complete?null:F()},O={name:`update_${e}`,description:`Fill or update fields of the "${e}" form. ${l} Pass any subset of fields; call it repeatedly to fill the form as the user provides information. Returns the current values and which required fields are still missing.`,parameters:B(i),handler:async t=>{const r=w($(t)),{missing:o}=h(i,r.values),s=await q();return s?s.ok?{ok:!0,values:r.values,missing:o,submitted:!0}:{ok:!0,values:r.values,missing:o,submitted:!1,submitError:s.error}:{ok:!0,values:r.values,missing:o}}},y=[O];a&&!c&&y.push({name:`submit_${e}`,description:`Submit the completed "${e}" form. Only call this once every required field is collected and the user has confirmed. If fields are missing it returns them instead of submitting.`,parameters:{type:"object",properties:{}},handler:()=>F()});const D="client__",_=a?`submit_${e}`:null,R=t=>{const r=t.functionName??t.toolName;if(r)return r.startsWith(D)?r.slice(8):r},x=t=>{let r={...N},o=!1;for(const s of t){const u=R(s);u===O.name?s.arguments&&(r={...r,...$(s.arguments)}):_&&u===_&&s.status?.toLowerCase()==="done"&&(o=!0)}m.set({values:r,submitted:o})},g=`form:${e}`,v=`${g}:definition`,P=()=>({name:`Form definition: ${e}`,description:`${l} Some fields are conditionally required; the requiredWhen field in the schema tells you when each becomes required. The form schema is the following: ${JSON.stringify(i)}.`,stable:!0}),T=()=>{const{values:t,submitted:r}=m.get(),{missing:o,complete:s}=h(i,t),u=a?c?" The form is submitted automatically as soon as every required field is filled, so there is no submit function to call.":` When nothing is missing and the user confirms, call submit_${e}.`:"",f=r?`The "${e}" form has been submitted.`:`You are currently collecting information from the user to fill the "${e}" form.`;return{name:`Form: ${e}`,description:`${f} The form's schema and field requirements are in the "${v}" client context. Call update_${e} with any fields the user provides; ask only for what is still missing.${u}`,data:{values:t,missing:o,complete:s,submitted:r}}},E=t=>{x((t.messages??[]).flatMap(r=>r.toolCalls??[]))};return{name:e,store:m,functions:y,contextKey:g,contextProvider:T,definitionContextKey:v,definitionContextProvider:P,install:t=>{b=t;for(const o of y)t.register(o);t.addDynamicContext(v,P),t.addDynamicContext(g,T);const r=m.subscribe(()=>t.notifyContextChanged());return t.on("conversation:loaded",E),()=>{r();for(const o of y)t.unregisterFunction(o.name);t.removeDynamicContext(g),t.removeDynamicContext(v),t.off("conversation:loaded",E),b===t&&(b=null)}},hydrate:x,submit:F,getValues:()=>m.get().values,setValues:t=>{w($(t)),q()},reset:()=>{m.set({values:N,submitted:!1})},getStatus:()=>h(i,m.get().values)}}async function L(n,e){const l=await n.getFormCollector(e.name);return V({name:l.name,description:e.description??l.description,schema:e.schema??l.schema,submit:e.submit??l.submit,initialValues:e.initialValues,autoSubmit:e.autoSubmit??l.autoSubmit})}Object.defineProperty(exports,"createFormCollector",{enumerable:!0,get:function(){return V}});Object.defineProperty(exports,"deriveFormStatus",{enumerable:!0,get:function(){return h}});Object.defineProperty(exports,"loadFormCollector",{enumerable:!0,get:function(){return L}});
1
+ const C=require("./AgoClient-DLB9icvv.cjs");var W=/^[a-zA-Z0-9_-]{1,40}$/,A=n=>n==null||n==="";function S(n,e){if("anyOf"in n)return n.anyOf.some(c=>S(c,e));if("allOf"in n)return n.allOf.every(c=>S(c,e));const l=e[n.property];if(A(l))return!1;if(Array.isArray(n.value))return n.value.some(c=>String(l)===String(c));if(!n.op)return String(l)===String(n.value);const i=Number(l),a=Number(n.value);if(Number.isNaN(i)||Number.isNaN(a))return!1;switch(n.op){case">=":return i>=a;case"<=":return i<=a;case">":return i>a;case"<":return i<a;default:return C.logger.warn(`Unknown requiredWhen op "${n.op}"; treating as not required.`),!1}}function h(n,e){const l=n.properties??{},i=new Set;for(const c of n.required??[]){const d=l[c]?.requiredWhen;(!d||S(d,e))&&i.add(c)}for(const[c,d]of Object.entries(l))d.requiredWhen&&S(d.requiredWhen,e)&&i.add(c);const a=[...i].filter(c=>A(e[c]));return{missing:a,complete:a.length===0}}function B(n){const e={};for(const[l,i]of Object.entries(n.properties??{}))e[l]={type:i.type,...i.description!=null&&{description:i.description},...i.enum&&{enum:i.enum},...i.default!==void 0&&{default:i.default}};return{type:"object",properties:e,required:[]}}function V(n){const{name:e,description:l,schema:i}=n;if(!W.test(e))throw new Error(`Invalid form collector name "${e}": must match ${W} (it becomes the update_/submit_ function names).`);const a=typeof n.submit=="string"?n.submit?{via:"client",url:n.submit}:!1:n.submit??!1;n.autoSubmit===!0&&!a&&C.logger.warn(`FormCollector "${e}": autoSubmit is ignored because no submit target is configured.`);const c=(n.autoSubmit??!0)&&!!a,d=i.properties??{},$=t=>{const r={};for(const[o,s]of Object.entries(t)){const u=d[o];if(u)if(s==null)r[o]=s;else if(u.type==="number"||u.type==="integer"){const f=typeof s=="number"?s:Number(s);r[o]=Number.isNaN(f)?s:f}else u.type==="boolean"?r[o]=typeof s=="boolean"?s:s==="true"?!0:s==="false"?!1:!!s:r[o]=s}return r},N=n.initialValues??{},m=C.createStore({values:N,submitted:!1}),w=t=>{const r=m.get(),o={...r,values:{...r.values,...t}};return m.set(o),o};let b=null;const k=(t,r)=>{b?.emitFormEvent("form:error",{name:e,values:t,error:r})};let p=null;const I=async()=>{const{values:t}=m.get(),{complete:r,missing:o}=h(i,t);if(!r)return{ok:!1,missing:o};if(!a)return{ok:!1,error:"No submit target configured for this form collector."};const s=t;try{let u;if(a.via==="client")if("handler"in a)u=await a.handler(s);else{const f=await fetch(a.url,{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify(s)});if(!f.ok){const j=`Submit failed: HTTP ${f.status}`;return k(s,j),{ok:!1,error:j}}u=await f.json().catch(()=>{})}else{if(!b)return{ok:!1,error:"Backend submit requires install(client) (or useFormCollector) first."};u=await b.submitFormCollector(e,s)}return m.set({...m.get(),submitted:!0,submitResult:u}),b?.emitFormEvent("form:submitted",{name:e,values:s,result:u}),{ok:!0,result:u}}catch(u){const f=u instanceof Error?u.message:"Submit failed";return C.logger.error(`FormCollector "${e}" submit failed:`,u),k(s,f),{ok:!1,error:f}}},F=()=>p||(p=(async()=>{try{return await I()}finally{p=null}})(),p),q=async()=>{if(!c||!a)return null;const{values:t,submitted:r}=m.get();return r||!h(i,t).complete?null:F()},O={name:`update_${e}`,description:`Fill or update fields of the "${e}" form. ${l} Pass any subset of fields; call it repeatedly to fill the form as the user provides information. Returns the current values and which required fields are still missing.`,parameters:B(i),handler:async t=>{const r=w($(t)),{missing:o}=h(i,r.values),s=await q();return s?s.ok?{ok:!0,values:r.values,missing:o,submitted:!0}:{ok:!0,values:r.values,missing:o,submitted:!1,submitError:s.error}:{ok:!0,values:r.values,missing:o}}},y=[O];a&&!c&&y.push({name:`submit_${e}`,description:`Submit the completed "${e}" form. Only call this once every required field is collected and the user has confirmed. If fields are missing it returns them instead of submitting.`,parameters:{type:"object",properties:{}},handler:()=>F()});const D="client__",_=a?`submit_${e}`:null,R=t=>{const r=t.functionName??t.toolName;if(r)return r.startsWith(D)?r.slice(8):r},x=t=>{let r={...N},o=!1;for(const s of t){const u=R(s);u===O.name?s.arguments&&(r={...r,...$(s.arguments)}):_&&u===_&&s.status?.toLowerCase()==="done"&&(o=!0)}m.set({values:r,submitted:o})},g=`form:${e}`,v=`${g}:definition`,P=()=>({name:`Form definition: ${e}`,description:`${l} Some fields are conditionally required; the requiredWhen field in the schema tells you when each becomes required. The form schema is the following: ${JSON.stringify(i)}.`,stable:!0}),T=()=>{const{values:t,submitted:r}=m.get(),{missing:o,complete:s}=h(i,t),u=a?c?" The form is submitted automatically as soon as every required field is filled, so there is no submit function to call.":` When nothing is missing and the user confirms, call submit_${e}.`:"",f=r?`The "${e}" form has been submitted.`:`You are currently collecting information from the user to fill the "${e}" form.`;return{name:`Form: ${e}`,description:`${f} The form's schema and field requirements are in the "${v}" client context. Call update_${e} with any fields the user provides; ask only for what is still missing.${u}`,data:{values:t,missing:o,complete:s,submitted:r}}},E=t=>{x((t.messages??[]).flatMap(r=>r.toolCalls??[]))};return{name:e,store:m,functions:y,contextKey:g,contextProvider:T,definitionContextKey:v,definitionContextProvider:P,install:t=>{b=t;for(const o of y)t.register(o);t.addDynamicContext(v,P),t.addDynamicContext(g,T);const r=m.subscribe(()=>t.notifyContextChanged());return t.on("conversation:loaded",E),()=>{r();for(const o of y)t.unregisterFunction(o.name);t.removeDynamicContext(g),t.removeDynamicContext(v),t.off("conversation:loaded",E),b===t&&(b=null)}},hydrate:x,submit:F,getValues:()=>m.get().values,setValues:t=>{w($(t)),q()},reset:()=>{m.set({values:N,submitted:!1})},getStatus:()=>h(i,m.get().values)}}async function L(n,e){const l=await n.getFormCollector(e.name);return V({name:l.name,description:e.description??l.description,schema:e.schema??l.schema,submit:e.submit??l.submit,initialValues:e.initialValues,autoSubmit:e.autoSubmit??l.autoSubmit})}Object.defineProperty(exports,"createFormCollector",{enumerable:!0,get:function(){return V}});Object.defineProperty(exports,"deriveFormStatus",{enumerable:!0,get:function(){return h}});Object.defineProperty(exports,"loadFormCollector",{enumerable:!0,get:function(){return L}});
@@ -1,4 +1,4 @@
1
- import { h as R, v as w } from "./AgoClient-BI5esqbd.js";
1
+ import { h as R, v as w } from "./AgoClient-B_R_qi2s.js";
2
2
  var j = /^[a-zA-Z0-9_-]{1,40}$/, V = (s) => s == null || s === "";
3
3
  function S(s, e) {
4
4
  if ("anyOf" in s) return s.anyOf.some((c) => S(c, e));
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./AgoClient-CQh8YovA.cjs"),C=require("./autoContinue-CP9pJR-V.cjs"),p=require("./createConversationSession-0zVkMdYj.cjs"),f=require("./createFormCollector-DiCe_8ik.cjs"),E=require("./createMockClient-Dw-cyISN.cjs");require("./testing.cjs");const g=require("./functions-CPs7omgM.cjs");function S(e){return e}function w(e,o){return e.on("message:complete",o),()=>e.off("message:complete",o)}function y(e,o){return e.on("message:chunk",o),()=>e.off("message:chunk",o)}function v(e,o){return e.on("message:start",o),()=>e.off("message:start",o)}function F(e,o){return e.on("message:error",o),()=>e.off("message:error",o)}function b(e,o){return e.on("toolCall:received",o),()=>e.off("toolCall:received",o)}function M(e,o){return e.on("form:submitted",o),()=>e.off("form:submitted",o)}function T(e,o){return e.on("form:error",o),()=>e.off("form:error",o)}function q(e,o){return e.on("function:invoke",o),()=>e.off("function:invoke",o)}async function*I(e,o,l){const a=[];let n=null,i=!1;const c=s=>{a.push(s),n?.()},m=s=>c({type:"start",data:s}),r=s=>c({type:"chunk",data:s}),u=s=>{c({type:"complete",data:s}),i=!0,n?.()},d=s=>{c({type:"error",data:s}),i=!0,n?.()},A=s=>c({type:"toolCall",data:s});e.on("message:start",m),e.on("message:chunk",r),e.on("message:complete",u),e.on("message:error",d),e.on("toolCall:received",A),e.sendMessage(o,l).catch(()=>{i=!0,n?.()});try{for(;!i||a.length>0;)a.length>0?yield a.shift():(await new Promise(s=>{n=s}),n=null)}finally{e.off("message:start",m),e.off("message:chunk",r),e.off("message:complete",u),e.off("message:error",d),e.off("toolCall:received",A)}}function h(e){let o,l,a,n,i,c;if(typeof window<"u"&&window.AGO){const r=window.AGO;o=r.basepath,l=r.widgetId,a=r.agent||r.defaultAgent,n=r.permission,i=r.email,c=r.jwt}if(typeof document<"u"){const r=u=>document.querySelector(`meta[name="${u}"]`)?.getAttribute("content")||void 0;o=o||r("ago-base-url"),l=l||r("ago-widget-id"),a=a||r("ago-agent")||r("ago-agent-id"),n=n||r("ago-permission"),i=i||r("ago-user-email")}if(typeof document<"u"){const r=[document.body,...Array.from(document.querySelectorAll("script[data-ago-base-url]"))].filter(Boolean);for(const u of r)u&&(o=o||u.getAttribute("data-ago-base-url")||void 0,l=l||u.getAttribute("data-ago-widget-id")||void 0,a=a||u.getAttribute("data-ago-agent")||u.getAttribute("data-ago-agent-id")||void 0,n=n||u.getAttribute("data-ago-permission")||void 0,i=i||u.getAttribute("data-ago-user-email")||void 0)}o=e?.baseUrl||o,l=e?.widgetId||l,a=e?.agent||e?.defaultAgentId||a,n=e?.permission||n,i=e?.userEmail||i,c=e?.userJwt||c;const m=e?.debug;return o?{baseUrl:o,widgetId:l,agent:a,permission:n,userEmail:i,userJwt:c,debug:m}:null}function _(e){const o=h(e);if(!o)throw new t.AgoError('createAgo(): could not detect AGO configuration. Set window.AGO, add <meta name="ago-base-url">, or pass { baseUrl } explicitly.',"config_missing_base_url");return new t.AgoClient(o)}function k(e,o){return{...e,handler:o}}exports.ActivityLedger=t.ActivityLedger;exports.AgoApiError=t.AgoApiError;exports.AgoClient=t.AgoClient;exports.AgoError=t.AgoError;exports.AgoFunctionError=t.AgoFunctionError;exports.AgoNetworkError=t.AgoNetworkError;exports.AgoStreamError=t.AgoStreamError;exports.ClientContextRegistry=t.ClientContextRegistry;exports.DEFAULT_MAX_ACTIVITY_ENTRIES=t.DEFAULT_MAX_ACTIVITY_ENTRIES;exports.EventEmitter=t.EventEmitter;exports.FunctionRegistry=t.FunctionRegistry;exports.SSEHandler=t.SSEHandler;exports.SignalCollector=t.SignalCollector;exports.attachAutoContinueAfterNavigation=C.attachAutoContinueAfterNavigation;exports.autoDetectConfig=h;exports.canInlineImage=t.canInlineImage;exports.copyToClipboard=g.copyToClipboard;exports.createAgo=_;exports.createAgoProactive=t.createAgoProactive;exports.createConversationSession=p.createConversationSession;exports.createFormCollector=f.createFormCollector;exports.createMessageStream=I;exports.createMockClient=E.createMockClient;exports.createStore=t.createStore;exports.defineFunction=S;exports.deriveFormStatus=f.deriveFormStatus;exports.formatFileSize=t.formatFileSize;exports.getLocalStorage=g.getLocalStorage;exports.getUserLocation=g.getUserLocation;exports.highlightElement=g.highlightElement;exports.isStreamNetworkError=t.isStreamNetworkError;exports.loadFormCollector=f.loadFormCollector;exports.logger=t.logger;exports.matchesRoutePattern=t.matchesRoutePattern;exports.matchesWhen=t.matchesWhen;exports.onFormError=T;exports.onFormSubmitted=M;exports.onFunctionInvoke=q;exports.onMessage=w;exports.onMessageChunk=y;exports.onMessageError=F;exports.onMessageStart=v;exports.onToolCall=b;exports.openUrl=g.openUrl;exports.partialDeepMatch=t.partialDeepMatch;exports.safeAttachmentUrl=t.safeAttachmentUrl;exports.scrollToElement=g.scrollToElement;exports.setLocalStorage=g.setLocalStorage;exports.setTheme=g.setTheme;exports.showConfirmDialog=g.showConfirmDialog;exports.showNotification=g.showNotification;exports.showToast=g.showToast;exports.submitForm=g.submitForm;exports.trackEvent=g.trackEvent;exports.validateConfig=t.validateConfig;exports.withHandler=k;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./AgoClient-DLB9icvv.cjs"),C=require("./autoContinue-CP9pJR-V.cjs"),p=require("./createConversationSession-Dqh7NXK4.cjs"),f=require("./createFormCollector-BjO3oB63.cjs"),E=require("./createMockClient-Dw-cyISN.cjs");require("./testing.cjs");const g=require("./functions-CPs7omgM.cjs");function S(e){return e}function w(e,o){return e.on("message:complete",o),()=>e.off("message:complete",o)}function y(e,o){return e.on("message:chunk",o),()=>e.off("message:chunk",o)}function v(e,o){return e.on("message:start",o),()=>e.off("message:start",o)}function F(e,o){return e.on("message:error",o),()=>e.off("message:error",o)}function b(e,o){return e.on("toolCall:received",o),()=>e.off("toolCall:received",o)}function M(e,o){return e.on("form:submitted",o),()=>e.off("form:submitted",o)}function T(e,o){return e.on("form:error",o),()=>e.off("form:error",o)}function q(e,o){return e.on("function:invoke",o),()=>e.off("function:invoke",o)}async function*I(e,o,l){const a=[];let n=null,i=!1;const c=s=>{a.push(s),n?.()},m=s=>c({type:"start",data:s}),r=s=>c({type:"chunk",data:s}),u=s=>{c({type:"complete",data:s}),i=!0,n?.()},d=s=>{c({type:"error",data:s}),i=!0,n?.()},A=s=>c({type:"toolCall",data:s});e.on("message:start",m),e.on("message:chunk",r),e.on("message:complete",u),e.on("message:error",d),e.on("toolCall:received",A),e.sendMessage(o,l).catch(()=>{i=!0,n?.()});try{for(;!i||a.length>0;)a.length>0?yield a.shift():(await new Promise(s=>{n=s}),n=null)}finally{e.off("message:start",m),e.off("message:chunk",r),e.off("message:complete",u),e.off("message:error",d),e.off("toolCall:received",A)}}function h(e){let o,l,a,n,i,c;if(typeof window<"u"&&window.AGO){const r=window.AGO;o=r.basepath,l=r.widgetId,a=r.agent||r.defaultAgent,n=r.permission,i=r.email,c=r.jwt}if(typeof document<"u"){const r=u=>document.querySelector(`meta[name="${u}"]`)?.getAttribute("content")||void 0;o=o||r("ago-base-url"),l=l||r("ago-widget-id"),a=a||r("ago-agent")||r("ago-agent-id"),n=n||r("ago-permission"),i=i||r("ago-user-email")}if(typeof document<"u"){const r=[document.body,...Array.from(document.querySelectorAll("script[data-ago-base-url]"))].filter(Boolean);for(const u of r)u&&(o=o||u.getAttribute("data-ago-base-url")||void 0,l=l||u.getAttribute("data-ago-widget-id")||void 0,a=a||u.getAttribute("data-ago-agent")||u.getAttribute("data-ago-agent-id")||void 0,n=n||u.getAttribute("data-ago-permission")||void 0,i=i||u.getAttribute("data-ago-user-email")||void 0)}o=e?.baseUrl||o,l=e?.widgetId||l,a=e?.agent||e?.defaultAgentId||a,n=e?.permission||n,i=e?.userEmail||i,c=e?.userJwt||c;const m=e?.debug;return o?{baseUrl:o,widgetId:l,agent:a,permission:n,userEmail:i,userJwt:c,debug:m}:null}function _(e){const o=h(e);if(!o)throw new t.AgoError('createAgo(): could not detect AGO configuration. Set window.AGO, add <meta name="ago-base-url">, or pass { baseUrl } explicitly.',"config_missing_base_url");return new t.AgoClient(o)}function k(e,o){return{...e,handler:o}}exports.ActivityLedger=t.ActivityLedger;exports.AgoApiError=t.AgoApiError;exports.AgoClient=t.AgoClient;exports.AgoError=t.AgoError;exports.AgoFunctionError=t.AgoFunctionError;exports.AgoNetworkError=t.AgoNetworkError;exports.AgoStreamError=t.AgoStreamError;exports.ClientContextRegistry=t.ClientContextRegistry;exports.DEFAULT_MAX_ACTIVITY_ENTRIES=t.DEFAULT_MAX_ACTIVITY_ENTRIES;exports.EventEmitter=t.EventEmitter;exports.FunctionRegistry=t.FunctionRegistry;exports.SSEHandler=t.SSEHandler;exports.SignalCollector=t.SignalCollector;exports.attachAutoContinueAfterNavigation=C.attachAutoContinueAfterNavigation;exports.autoDetectConfig=h;exports.canInlineImage=t.canInlineImage;exports.copyToClipboard=g.copyToClipboard;exports.createAgo=_;exports.createAgoProactive=t.createAgoProactive;exports.createConversationSession=p.createConversationSession;exports.createFormCollector=f.createFormCollector;exports.createMessageStream=I;exports.createMockClient=E.createMockClient;exports.createStore=t.createStore;exports.defineFunction=S;exports.deriveFormStatus=f.deriveFormStatus;exports.formatFileSize=t.formatFileSize;exports.getLocalStorage=g.getLocalStorage;exports.getUserLocation=g.getUserLocation;exports.highlightElement=g.highlightElement;exports.isStreamNetworkError=t.isStreamNetworkError;exports.loadFormCollector=f.loadFormCollector;exports.logger=t.logger;exports.matchesRoutePattern=t.matchesRoutePattern;exports.matchesWhen=t.matchesWhen;exports.onFormError=T;exports.onFormSubmitted=M;exports.onFunctionInvoke=q;exports.onMessage=w;exports.onMessageChunk=y;exports.onMessageError=F;exports.onMessageStart=v;exports.onToolCall=b;exports.openUrl=g.openUrl;exports.partialDeepMatch=t.partialDeepMatch;exports.safeAttachmentUrl=t.safeAttachmentUrl;exports.scrollToElement=g.scrollToElement;exports.setLocalStorage=g.setLocalStorage;exports.setTheme=g.setTheme;exports.showConfirmDialog=g.showConfirmDialog;exports.showNotification=g.showNotification;exports.showToast=g.showToast;exports.submitForm=g.submitForm;exports.trackEvent=g.trackEvent;exports.validateConfig=t.validateConfig;exports.withHandler=k;
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { a as h, c as w, d as C, f as y, i as E, l as S, m as b, o as v, p as F, r as T, s as I, t as M, u as U } from "./functions-tzyOZNp6.js";
2
- import { C as k, S as L, T as N, _ as x, a as D, b as d, c as G, d as O, f as R, g as q, h as P, l as H, m as J, n as j, o as z, p as B, r as V, s as W, t as c, u as X, v as Y, w as $, x as K, y as Q } from "./AgoClient-BI5esqbd.js";
2
+ import { C as k, S as L, T as N, _ as x, a as D, b as d, c as G, d as O, f as R, g as q, h as P, l as H, m as J, n as j, o as z, p as B, r as V, s as W, t as c, u as X, v as Y, w as $, x as K, y as Q } from "./AgoClient-B_R_qi2s.js";
3
3
  import { t as ee } from "./autoContinue-CC8K9mBU.js";
4
- import { t as oe } from "./createConversationSession-BlYTpxwz.js";
5
- import { n as ae, r as ne, t as se } from "./createFormCollector-Bgs94NyR.js";
4
+ import { t as oe } from "./createConversationSession-CdtI4vrf.js";
5
+ import { n as ae, r as ne, t as se } from "./createFormCollector-YwaZ78wU.js";
6
6
  import { t as ue } from "./createMockClient-DcuNlufr.js";
7
7
  import "./testing.js";
8
8
  function fe(e) {
package/dist/react.cjs CHANGED
@@ -1,4 +1,4 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var Q=Object.create,T=Object.defineProperty,ee=Object.getOwnPropertyDescriptor,te=Object.getOwnPropertyNames,ne=Object.getPrototypeOf,re=Object.prototype.hasOwnProperty,oe=(e,n)=>{let t={};for(var o in e)T(t,o,{get:e[o],enumerable:!0});return n||T(t,Symbol.toStringTag,{value:"Module"}),t},se=(e,n,t,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(var r=te(n),i=0,u=r.length,s;i<u;i++)s=r[i],!re.call(e,s)&&s!==t&&T(e,s,{get:(f=>n[f]).bind(null,s),enumerable:!(o=ee(n,s))||o.enumerable});return e},O=(e,n,t)=>(t=e!=null?Q(ne(e)):{},se(n||!e||!e.__esModule?T(t,"default",{value:e,enumerable:!0}):t,e));const _=require("./AgoClient-CQh8YovA.cjs"),ae=require("./autoContinue-CP9pJR-V.cjs"),M=require("./createFormCollector-DiCe_8ik.cjs"),ie=require("./createMockClient-Dw-cyISN.cjs");let a=require("react");a=O(a,1);let l=require("react/jsx-runtime"),D=require("react-markdown");D=O(D,1);let W=require("remark-gfm");W=O(W,1);function B(e){const[n,t]=(0,a.useState)(!1),o=(0,a.useRef)(null),r=(0,a.useMemo)(()=>{if(o.current&&(o.current.destroy(),o.current=null),!e)return null;const i=new _.AgoClient(e);return o.current=i,i},[e?.baseUrl,e?.widgetId]);return(0,a.useEffect)(()=>(r&&o.current===null&&(o.current=r,r.reviveAfterDestroy()),t(!0),()=>{o.current?.destroy(),o.current=null}),[r]),(0,a.useEffect)(()=>{o.current&&e&&o.current.updateConfig({agent:e.agent,defaultAgentId:e.defaultAgentId,permission:e.permission,userEmail:e.userEmail,userJwt:e.userJwt,debug:e.debug,warnOnEmptyReply:e.warnOnEmptyReply})},[e?.agent,e?.defaultAgentId,e?.permission,e?.userEmail,e?.userJwt,e?.debug,e?.warnOnEmptyReply]),{client:r,isReady:n}}var q=(0,a.createContext)(null),le=({children:e,client:n,tools:t,helpers:o,pageContext:r,...i})=>{const{client:u}=B(n?null:i),s=n||u;return(0,a.useEffect)(()=>{if(!(!t||t.length===0)){for(const f of t)s.register(f);return()=>{for(const f of t)s.unregisterFunction(f.name)}}},[s,t]),(0,a.useEffect)(()=>{if(!o)return;const f=[];return Promise.resolve().then(()=>require("./functions-CPs7omgM.cjs")).then(d=>d.functions_exports).then(d=>{for(const[m,S]of Object.entries(o)){const I=d[m];if(!I){console.warn(`[AGO] Unknown helper: "${m}"`);continue}const A=S===!0?I:{...I,handler:S};s.register(A),f.push(A.name)}}),()=>{for(const d of f)s.unregisterFunction(d)}},[s,o]),(0,a.useEffect)(()=>{r==="auto"&&s.enableAutoPageContext()},[s,r]),(0,l.jsx)(q.Provider,{value:s,children:e})};function F(){const e=(0,a.useContext)(q);if(!e)throw new Error('useAgoClient must be used within an <AgoProvider>. Wrap your component tree with <AgoProvider baseUrl="...">.');return e}function E(){return(0,a.useContext)(q)}function z({client:e,conversationId:n}={}){const t=E(),o=e||t;if(!o)throw new Error("useMessages requires an AgoClient. Either pass it as options.client or wrap your app in <AgoProvider>.");const[r,i]=(0,a.useState)([]),[u,s]=(0,a.useState)(n),[f,d]=(0,a.useState)(!1),[m,S]=(0,a.useState)(null);(0,a.useEffect)(()=>{n&&n!==u&&(s(n),I(n))},[n]);const I=async A=>{try{i((await o.getMessages(A)).filter(k=>!k.hidden))}catch(k){S(k instanceof Error?k:new Error("Failed to load messages"))}};return(0,a.useEffect)(()=>{const A=p=>p==="IN_PROGRESS"||p==="WAITING_CLIENT",k=p=>{u||s(p.conversationId),d(!0),i(y=>{const w=y.findIndex(C=>C.id===p.messageId);return w>=0?y.map((C,R)=>R===w?{...C,status:"IN_PROGRESS"}:C):y.some(C=>C.role==="assistant"&&A(C.status))?y:[...y,{id:p.messageId,conversationId:p.conversationId,content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date}]})},g=p=>{i(y=>{const w=y.findIndex(C=>C.id===p.messageId);return w<0?y:y.map((C,R)=>R===w?{...C,content:C.content+p.content}:C)})},h=p=>{i(y=>{let w=-1;for(let C=y.length-1;C>=0;C--)if(y[C].role==="assistant"&&A(y[C].status)){w=C;break}return w<0?y:[...y.slice(0,w),{...y[w],...p},...y.slice(w+1)]})},c=p=>{i(y=>{const w=y.findIndex(C=>C.id===p.id);return w>=0?[...y.slice(0,w),p,...y.slice(w+1)]:[...y,p]}),d(!1)},b=p=>{S(new Error(p.error)),d(!1)};return o.on("message:start",k),o.on("message:chunk",g),o.on("message:answer-complete",h),o.on("message:complete",c),o.on("message:error",b),()=>{o.off("message:start",k),o.off("message:chunk",g),o.off("message:answer-complete",h),o.off("message:complete",c),o.off("message:error",b)}},[o,u]),{messages:r,isLoading:f,error:m,sendMessage:(0,a.useCallback)(async(A,k)=>{d(!0),S(null);const g={id:`temp-${Date.now()}`,conversationId:u||"",content:A,role:"user",status:"DONE",attachments:k&&k.length>0?_.attachmentsFromFiles(k):void 0,createdAt:new Date},h={id:`temp-assistant-${Date.now()}`,conversationId:u||"",content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date};i(c=>[...c,g,h]);try{const c=await o.sendMessage(A,{conversationId:u,files:k});return c.conversationId&&!u&&s(c.conversationId),i(b=>{const p=b.filter(w=>!w.id.startsWith("temp-")),y={...g,id:g.id.replace("temp-","user-"),conversationId:c.conversationId};return p.some(w=>w.id===c.id)?[...p,y].sort((w,C)=>new Date(w.createdAt).getTime()-new Date(C.createdAt).getTime()):[...p,y,c]}),c}catch(c){return S(c instanceof Error?c:new Error("Failed to send message")),d(!1),i(b=>b.filter(p=>!p.id.startsWith("temp-"))),null}},[o,u]),clearMessages:(0,a.useCallback)(()=>{i([]),s(void 0),S(null)},[]),conversationId:u}}var U=({onSend:e,disabled:n=!1,placeholder:t="Type a message...",allowFiles:o=!1,className:r=""})=>{const[i,u]=(0,a.useState)(""),[s,f]=(0,a.useState)([]),d=(0,a.useRef)(null),m=(0,a.useRef)(null),S=(0,a.useCallback)(()=>{const c=m.current;if(!c)return;const b=110;c.style.height="auto",c.style.height=`${Math.min(c.scrollHeight+2,b)}px`,c.style.overflowY=c.scrollHeight+2>b?"auto":"hidden"},[]),I=(0,a.useCallback)(c=>{c.preventDefault(),(i.trim()||s.length>0)&&(e(i.trim(),s.length>0?s:void 0),u(""),f([]),requestAnimationFrame(S))},[i,s,e,S]),A=(0,a.useCallback)(c=>{c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),I(c))},[I]),k=(0,a.useCallback)(c=>{const b=Array.from(c.target.files||[]);f(p=>[...p,...b])},[]),g=(0,a.useCallback)(c=>{f(b=>b.filter((p,y)=>y!==c))},[]),h=i.trim()||s.length>0;return(0,l.jsxs)("form",{onSubmit:I,className:`ago-chat-input ${r}`,style:{display:"flex",flexDirection:"column",gap:"8px",padding:"12px 16px",borderTop:"1px solid #dee3e8",backgroundColor:"#fff"},children:[s.length>0&&(0,l.jsx)("div",{className:"ago-chat-input__files",style:{display:"flex",flexWrap:"wrap",gap:"6px"},children:s.map((c,b)=>(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"6px",padding:"4px 10px",backgroundColor:"#f0f2f5",borderRadius:"6px",fontSize:"12px",color:"#30373e"},children:[(0,l.jsx)("span",{style:{maxWidth:"120px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:c.name}),(0,l.jsx)("button",{type:"button",onClick:()=>g(b),"aria-label":`Remove ${c.name}`,style:{border:"none",background:"none",cursor:"pointer",padding:"0",color:"#6b6d6f",fontSize:"14px",lineHeight:1},children:"×"})]},b))}),(0,l.jsxs)("div",{style:{display:"flex",gap:"8px",alignItems:"flex-end"},children:[o&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("button",{type:"button",onClick:()=>d.current?.click(),disabled:n,"aria-label":"Attach file",style:{padding:"8px",border:"1px solid #dee3e8",borderRadius:"8px",backgroundColor:"#fff",cursor:n?"not-allowed":"pointer",color:"#6b6d6f",fontSize:"16px",lineHeight:1},children:"+"}),(0,l.jsx)("input",{ref:d,type:"file",multiple:!0,onChange:k,style:{display:"none"}})]}),(0,l.jsx)("textarea",{ref:m,value:i,onChange:c=>{u(c.target.value),S()},onKeyDown:A,placeholder:t,"aria-label":t,disabled:n,rows:1,style:{flex:1,padding:"10px 14px",border:"1px solid #dee3e8",borderRadius:"20px",resize:"none",outline:"none",boxSizing:"border-box",maxHeight:"110px",overflowY:"hidden",fontFamily:"inherit",fontSize:"16px",lineHeight:1.4,color:"#30373e",backgroundColor:"#f8f8f8",transition:"border-color 0.15s"},onFocus:c=>{c.currentTarget.style.borderColor="#1b5fc4"},onBlur:c=>{c.currentTarget.style.borderColor="#dee3e8"}}),(0,l.jsx)("button",{type:"submit",disabled:n||!h,style:{padding:"10px 18px",border:"none",borderRadius:"20px",backgroundColor:n||!h?"#b5bfc8":"#03182f",color:"#fff",cursor:n||!h?"not-allowed":"pointer",fontWeight:500,fontSize:"16px",transition:"background-color 0.15s"},children:"Send"})]})]})},ce=({href:e,children:n,...t})=>(0,l.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",style:{color:"#1b5fc4",textDecoration:"underline"},...t,children:n}),ue=({children:e,...n})=>(0,l.jsx)("p",{style:{margin:"0 0 8px 0",lineHeight:"1.6"},...n,children:e}),P=(e,n)=>{const t=({children:o,...r})=>a.default.createElement(`h${e}`,{style:{margin:"16px 0 8px 0",fontSize:n,fontWeight:600,lineHeight:"1.3"},...r},o);return t.displayName=`MarkdownHeading${e}`,t},de=({children:e,...n})=>(0,l.jsx)("ul",{style:{margin:"0 0 8px 0",paddingLeft:"20px",listStyleType:"disc",listStylePosition:"outside"},...n,children:e}),fe=({children:e,...n})=>(0,l.jsx)("ol",{style:{margin:"0 0 8px 0",paddingLeft:"20px",listStyleType:"decimal",listStylePosition:"outside"},...n,children:e}),ge=({children:e,...n})=>(0,l.jsx)("li",{style:{display:"list-item",margin:"2px 0",lineHeight:"1.6"},...n,children:e}),pe=({className:e,children:n,...t})=>e!==void 0||String(n).includes(`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var Q=Object.create,T=Object.defineProperty,ee=Object.getOwnPropertyDescriptor,te=Object.getOwnPropertyNames,ne=Object.getPrototypeOf,re=Object.prototype.hasOwnProperty,oe=(e,n)=>{let t={};for(var o in e)T(t,o,{get:e[o],enumerable:!0});return n||T(t,Symbol.toStringTag,{value:"Module"}),t},se=(e,n,t,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(var r=te(n),i=0,u=r.length,s;i<u;i++)s=r[i],!re.call(e,s)&&s!==t&&T(e,s,{get:(f=>n[f]).bind(null,s),enumerable:!(o=ee(n,s))||o.enumerable});return e},O=(e,n,t)=>(t=e!=null?Q(ne(e)):{},se(n||!e||!e.__esModule?T(t,"default",{value:e,enumerable:!0}):t,e));const _=require("./AgoClient-DLB9icvv.cjs"),ae=require("./autoContinue-CP9pJR-V.cjs"),M=require("./createFormCollector-BjO3oB63.cjs"),ie=require("./createMockClient-Dw-cyISN.cjs");let a=require("react");a=O(a,1);let l=require("react/jsx-runtime"),D=require("react-markdown");D=O(D,1);let W=require("remark-gfm");W=O(W,1);function B(e){const[n,t]=(0,a.useState)(!1),o=(0,a.useRef)(null),r=(0,a.useMemo)(()=>{if(o.current&&(o.current.destroy(),o.current=null),!e)return null;const i=new _.AgoClient(e);return o.current=i,i},[e?.baseUrl,e?.widgetId]);return(0,a.useEffect)(()=>(r&&o.current===null&&(o.current=r,r.reviveAfterDestroy()),t(!0),()=>{o.current?.destroy(),o.current=null}),[r]),(0,a.useEffect)(()=>{o.current&&e&&o.current.updateConfig({agent:e.agent,defaultAgentId:e.defaultAgentId,permission:e.permission,userEmail:e.userEmail,userJwt:e.userJwt,debug:e.debug,warnOnEmptyReply:e.warnOnEmptyReply})},[e?.agent,e?.defaultAgentId,e?.permission,e?.userEmail,e?.userJwt,e?.debug,e?.warnOnEmptyReply]),{client:r,isReady:n}}var q=(0,a.createContext)(null),le=({children:e,client:n,tools:t,helpers:o,pageContext:r,...i})=>{const{client:u}=B(n?null:i),s=n||u;return(0,a.useEffect)(()=>{if(!(!t||t.length===0)){for(const f of t)s.register(f);return()=>{for(const f of t)s.unregisterFunction(f.name)}}},[s,t]),(0,a.useEffect)(()=>{if(!o)return;const f=[];return Promise.resolve().then(()=>require("./functions-CPs7omgM.cjs")).then(d=>d.functions_exports).then(d=>{for(const[m,S]of Object.entries(o)){const I=d[m];if(!I){console.warn(`[AGO] Unknown helper: "${m}"`);continue}const A=S===!0?I:{...I,handler:S};s.register(A),f.push(A.name)}}),()=>{for(const d of f)s.unregisterFunction(d)}},[s,o]),(0,a.useEffect)(()=>{r==="auto"&&s.enableAutoPageContext()},[s,r]),(0,l.jsx)(q.Provider,{value:s,children:e})};function F(){const e=(0,a.useContext)(q);if(!e)throw new Error('useAgoClient must be used within an <AgoProvider>. Wrap your component tree with <AgoProvider baseUrl="...">.');return e}function E(){return(0,a.useContext)(q)}function z({client:e,conversationId:n}={}){const t=E(),o=e||t;if(!o)throw new Error("useMessages requires an AgoClient. Either pass it as options.client or wrap your app in <AgoProvider>.");const[r,i]=(0,a.useState)([]),[u,s]=(0,a.useState)(n),[f,d]=(0,a.useState)(!1),[m,S]=(0,a.useState)(null);(0,a.useEffect)(()=>{n&&n!==u&&(s(n),I(n))},[n]);const I=async A=>{try{i((await o.getMessages(A)).filter(k=>!k.hidden))}catch(k){S(k instanceof Error?k:new Error("Failed to load messages"))}};return(0,a.useEffect)(()=>{const A=p=>p==="IN_PROGRESS"||p==="WAITING_CLIENT",k=p=>{u||s(p.conversationId),d(!0),i(y=>{const w=y.findIndex(C=>C.id===p.messageId);return w>=0?y.map((C,R)=>R===w?{...C,status:"IN_PROGRESS"}:C):y.some(C=>C.role==="assistant"&&A(C.status))?y:[...y,{id:p.messageId,conversationId:p.conversationId,content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date}]})},g=p=>{i(y=>{const w=y.findIndex(C=>C.id===p.messageId);return w<0?y:y.map((C,R)=>R===w?{...C,content:C.content+p.content}:C)})},h=p=>{i(y=>{let w=-1;for(let C=y.length-1;C>=0;C--)if(y[C].role==="assistant"&&A(y[C].status)){w=C;break}return w<0?y:[...y.slice(0,w),{...y[w],...p},...y.slice(w+1)]})},c=p=>{i(y=>{const w=y.findIndex(C=>C.id===p.id);return w>=0?[...y.slice(0,w),p,...y.slice(w+1)]:[...y,p]}),d(!1)},b=p=>{S(new Error(p.error)),d(!1)};return o.on("message:start",k),o.on("message:chunk",g),o.on("message:answer-complete",h),o.on("message:complete",c),o.on("message:error",b),()=>{o.off("message:start",k),o.off("message:chunk",g),o.off("message:answer-complete",h),o.off("message:complete",c),o.off("message:error",b)}},[o,u]),{messages:r,isLoading:f,error:m,sendMessage:(0,a.useCallback)(async(A,k)=>{d(!0),S(null);const g={id:`temp-${Date.now()}`,conversationId:u||"",content:A,role:"user",status:"DONE",attachments:k&&k.length>0?_.attachmentsFromFiles(k):void 0,createdAt:new Date},h={id:`temp-assistant-${Date.now()}`,conversationId:u||"",content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date};i(c=>[...c,g,h]);try{const c=await o.sendMessage(A,{conversationId:u,files:k});return c.conversationId&&!u&&s(c.conversationId),i(b=>{const p=b.filter(w=>!w.id.startsWith("temp-")),y={...g,id:g.id.replace("temp-","user-"),conversationId:c.conversationId};return p.some(w=>w.id===c.id)?[...p,y].sort((w,C)=>new Date(w.createdAt).getTime()-new Date(C.createdAt).getTime()):[...p,y,c]}),c}catch(c){return S(c instanceof Error?c:new Error("Failed to send message")),d(!1),i(b=>b.filter(p=>!p.id.startsWith("temp-"))),null}},[o,u]),clearMessages:(0,a.useCallback)(()=>{i([]),s(void 0),S(null)},[]),conversationId:u}}var U=({onSend:e,disabled:n=!1,placeholder:t="Type a message...",allowFiles:o=!1,className:r=""})=>{const[i,u]=(0,a.useState)(""),[s,f]=(0,a.useState)([]),d=(0,a.useRef)(null),m=(0,a.useRef)(null),S=(0,a.useCallback)(()=>{const c=m.current;if(!c)return;const b=110;c.style.height="auto",c.style.height=`${Math.min(c.scrollHeight+2,b)}px`,c.style.overflowY=c.scrollHeight+2>b?"auto":"hidden"},[]),I=(0,a.useCallback)(c=>{c.preventDefault(),(i.trim()||s.length>0)&&(e(i.trim(),s.length>0?s:void 0),u(""),f([]),requestAnimationFrame(S))},[i,s,e,S]),A=(0,a.useCallback)(c=>{c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),I(c))},[I]),k=(0,a.useCallback)(c=>{const b=Array.from(c.target.files||[]);f(p=>[...p,...b])},[]),g=(0,a.useCallback)(c=>{f(b=>b.filter((p,y)=>y!==c))},[]),h=i.trim()||s.length>0;return(0,l.jsxs)("form",{onSubmit:I,className:`ago-chat-input ${r}`,style:{display:"flex",flexDirection:"column",gap:"8px",padding:"12px 16px",borderTop:"1px solid #dee3e8",backgroundColor:"#fff"},children:[s.length>0&&(0,l.jsx)("div",{className:"ago-chat-input__files",style:{display:"flex",flexWrap:"wrap",gap:"6px"},children:s.map((c,b)=>(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"6px",padding:"4px 10px",backgroundColor:"#f0f2f5",borderRadius:"6px",fontSize:"12px",color:"#30373e"},children:[(0,l.jsx)("span",{style:{maxWidth:"120px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:c.name}),(0,l.jsx)("button",{type:"button",onClick:()=>g(b),"aria-label":`Remove ${c.name}`,style:{border:"none",background:"none",cursor:"pointer",padding:"0",color:"#6b6d6f",fontSize:"14px",lineHeight:1},children:"×"})]},b))}),(0,l.jsxs)("div",{style:{display:"flex",gap:"8px",alignItems:"flex-end"},children:[o&&(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("button",{type:"button",onClick:()=>d.current?.click(),disabled:n,"aria-label":"Attach file",style:{padding:"8px",border:"1px solid #dee3e8",borderRadius:"8px",backgroundColor:"#fff",cursor:n?"not-allowed":"pointer",color:"#6b6d6f",fontSize:"16px",lineHeight:1},children:"+"}),(0,l.jsx)("input",{ref:d,type:"file",multiple:!0,onChange:k,style:{display:"none"}})]}),(0,l.jsx)("textarea",{ref:m,value:i,onChange:c=>{u(c.target.value),S()},onKeyDown:A,placeholder:t,"aria-label":t,disabled:n,rows:1,style:{flex:1,padding:"10px 14px",border:"1px solid #dee3e8",borderRadius:"20px",resize:"none",outline:"none",boxSizing:"border-box",maxHeight:"110px",overflowY:"hidden",fontFamily:"inherit",fontSize:"16px",lineHeight:1.4,color:"#30373e",backgroundColor:"#f8f8f8",transition:"border-color 0.15s"},onFocus:c=>{c.currentTarget.style.borderColor="#1b5fc4"},onBlur:c=>{c.currentTarget.style.borderColor="#dee3e8"}}),(0,l.jsx)("button",{type:"submit",disabled:n||!h,style:{padding:"10px 18px",border:"none",borderRadius:"20px",backgroundColor:n||!h?"#b5bfc8":"#03182f",color:"#fff",cursor:n||!h?"not-allowed":"pointer",fontWeight:500,fontSize:"16px",transition:"background-color 0.15s"},children:"Send"})]})]})},ce=({href:e,children:n,...t})=>(0,l.jsx)("a",{href:e,target:"_blank",rel:"noopener noreferrer",style:{color:"#1b5fc4",textDecoration:"underline"},...t,children:n}),ue=({children:e,...n})=>(0,l.jsx)("p",{style:{margin:"0 0 8px 0",lineHeight:"1.6"},...n,children:e}),P=(e,n)=>{const t=({children:o,...r})=>a.default.createElement(`h${e}`,{style:{margin:"16px 0 8px 0",fontSize:n,fontWeight:600,lineHeight:"1.3"},...r},o);return t.displayName=`MarkdownHeading${e}`,t},de=({children:e,...n})=>(0,l.jsx)("ul",{style:{margin:"0 0 8px 0",paddingLeft:"20px",listStyleType:"disc",listStylePosition:"outside"},...n,children:e}),fe=({children:e,...n})=>(0,l.jsx)("ol",{style:{margin:"0 0 8px 0",paddingLeft:"20px",listStyleType:"decimal",listStylePosition:"outside"},...n,children:e}),ge=({children:e,...n})=>(0,l.jsx)("li",{style:{display:"list-item",margin:"2px 0",lineHeight:"1.6"},...n,children:e}),pe=({className:e,children:n,...t})=>e!==void 0||String(n).includes(`
2
2
  `)?(0,l.jsx)("code",{style:{display:"block",background:"#f5f5f5",padding:"8px 12px",borderRadius:"6px",fontSize:"13px",overflowX:"auto",fontFamily:'"IBM Plex Mono", monospace'},...t,children:n}):(0,l.jsx)("code",{style:{background:"#f0f2f5",padding:"2px 5px",borderRadius:"4px",fontSize:"13px",fontFamily:'"IBM Plex Mono", monospace'},...t,children:n}),me=({children:e,...n})=>(0,l.jsx)("pre",{style:{margin:"0 0 8px 0"},...n,children:e}),xe=({children:e,...n})=>(0,l.jsx)("blockquote",{style:{borderLeft:"4px solid #dee3e8",paddingLeft:"12px",margin:"0 0 8px 0",fontStyle:"italic",color:"#6b6d6f"},...n,children:e}),he=({children:e,...n})=>(0,l.jsx)("div",{style:{overflowX:"auto",margin:"0 0 8px 0"},children:(0,l.jsx)("table",{style:{borderCollapse:"collapse",width:"100%",fontSize:"13px"},...n,children:e})}),ye=({children:e,...n})=>(0,l.jsx)("th",{style:{border:"1px solid #dee3e8",padding:"6px 10px",textAlign:"left",backgroundColor:"#f5f7fa",fontWeight:600},...n,children:e}),ve=({children:e,...n})=>(0,l.jsx)("td",{style:{border:"1px solid #dee3e8",padding:"6px 10px"},...n,children:e}),be=({alt:e,...n})=>(0,l.jsx)("img",{alt:e??"",style:{maxWidth:"100%",borderRadius:"8px",margin:"4px 0"},...n}),Ce=e=>(0,l.jsx)("hr",{style:{border:"none",borderTop:"1px solid #dee3e8",margin:"12px 0"},...e}),we={a:ce,p:ue,h1:P(1,"20px"),h2:P(2,"18px"),h3:P(3,"16px"),h4:P(4,"15px"),h5:P(5,"14px"),h6:P(6,"13px"),ul:de,ol:fe,li:ge,code:pe,pre:me,blockquote:xe,table:he,th:ye,td:ve,img:be,hr:Ce},Se=[W.default],G=({content:e})=>(0,l.jsx)(D.default,{remarkPlugins:Se,components:we,children:e}),Ae=({attachment:e,isUser:n})=>{const t=_.safeAttachmentUrl(e.url);if(_.canInlineImage(e))return(0,l.jsx)("a",{href:t,target:"_blank",rel:"noopener noreferrer",style:{display:"inline-block",textDecoration:"none"},children:(0,l.jsx)("img",{src:t,alt:e.name,loading:"lazy",style:{maxWidth:"180px",maxHeight:"160px",objectFit:"cover",borderRadius:"10px",border:"1px solid #dee3e8",display:"block"}})});const o=_.formatFileSize(e.fileSize),r=(0,l.jsxs)(l.Fragment,{children:[(0,l.jsx)("span",{style:{fontSize:"16px",lineHeight:1,flexShrink:0},"aria-hidden":!0,children:"📄"}),(0,l.jsxs)("span",{style:{display:"flex",flexDirection:"column",minWidth:0},children:[(0,l.jsx)("span",{style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:"160px"},title:e.name,children:e.name}),o&&(0,l.jsx)("span",{style:{fontSize:"11px",color:"#6b6d6f"},children:o})]})]}),i={display:"inline-flex",alignItems:"center",gap:"8px",padding:"8px 12px",borderRadius:"10px",border:"1px solid #dee3e8",backgroundColor:n?"rgba(255,255,255,0.12)":"#fff",color:n?"#fff":"#30373e",fontSize:"13px",textDecoration:"none",maxWidth:"220px"};return t?(0,l.jsx)("a",{href:t,target:"_blank",rel:"noopener noreferrer",style:i,children:r}):(0,l.jsx)("div",{style:i,children:r})},ke=({source:e,index:n})=>{const t=(0,l.jsxs)("div",{style:{display:"flex",alignItems:"center",gap:"8px",width:"100%",minWidth:0},children:[(0,l.jsx)("div",{style:{flexShrink:0,width:"18px",height:"18px",borderRadius:"3px",border:"1px solid #1b5fc4",color:"#1b5fc4",fontSize:"11px",fontWeight:500,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:"#f0f4ff"},children:n+1}),(0,l.jsx)("div",{style:{fontSize:"12px",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",color:"#30373e"},title:e.title,children:e.title})]}),o={display:"flex",alignItems:"center",padding:"8px 10px",border:"1px solid #dee3e8",borderRadius:"8px",backgroundColor:"#fff",cursor:e.url?"pointer":"default",textDecoration:"none",color:"inherit",minWidth:0,transition:"border-color 0.15s"};return e.url?(0,l.jsx)("a",{href:e.url,target:"_blank",rel:"noopener noreferrer",style:o,onMouseEnter:r=>{r.currentTarget.style.borderColor="#1b5fc4"},onMouseLeave:r=>{r.currentTarget.style.borderColor="#dee3e8"},children:t}):(0,l.jsx)("div",{style:o,children:t})},je=()=>(0,l.jsxs)("div",{style:{display:"flex",gap:"4px",padding:"4px 0"},children:[[0,1,2].map(e=>(0,l.jsx)("div",{style:{width:"6px",height:"6px",borderRadius:"50%",backgroundColor:"#b5bfc8",animation:"ago-pulse 1.2s ease-in-out infinite",animationDelay:`${e*.2}s`}},e)),(0,l.jsx)("style",{children:`
3
3
  @keyframes ago-pulse {
4
4
  0%, 80%, 100% { opacity: 0.3; transform: scale(0.8); }
package/dist/react.js CHANGED
@@ -1,6 +1,6 @@
1
- import { a as Y, b as L, h as X, i as Z, o as Q, s as ee, t as te } from "./AgoClient-BI5esqbd.js";
1
+ import { a as Y, b as L, h as X, i as Z, o as Q, s as ee, t as te } from "./AgoClient-B_R_qi2s.js";
2
2
  import { t as ne } from "./autoContinue-CC8K9mBU.js";
3
- import { n as He, r as j, t as B } from "./createFormCollector-Bgs94NyR.js";
3
+ import { n as He, r as j, t as B } from "./createFormCollector-YwaZ78wU.js";
4
4
  import { t as Oe } from "./createMockClient-DcuNlufr.js";
5
5
  import re, { createContext as oe, useCallback as R, useContext as G, useEffect as I, useId as ae, useMemo as D, useRef as M, useState as E, useSyncExternalStore as se } from "react";
6
6
  import { Fragment as U, jsx as l, jsxs as _ } from "react/jsx-runtime";
package/dist/vue.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const I=require("./AgoClient-CQh8YovA.cjs");let o=require("vue");var w=Symbol("ago-client"),N={install(t,e){const n=new I.AgoClient(e);t.provide(w,n)}};function v(t){if(t)return new I.AgoClient(t);const e=(0,o.inject)(w);if(!e)throw new Error("useAgo(): no AgoClient found. Either pass config or install AgoPlugin.");return e}function M(t={}){const e=t.client??v(),n=(0,o.ref)([]),s=(0,o.ref)(t.conversationId),a=(0,o.ref)(!1),u=(0,o.ref)(null),c=r=>{s.value||(s.value=r.conversationId)},f=r=>{const i=n.value.findIndex(d=>d.id===r.messageId);i>=0&&(n.value[i]={...n.value[i],content:n.value[i].content+r.content})},m=r=>{const i=n.value.findIndex(d=>d.id===r.id);i>=0?n.value[i]=r:n.value.push(r),a.value=!1},C=r=>{u.value=new Error(r.error),a.value=!1};(0,o.onMounted)(()=>{e.on("message:start",c),e.on("message:chunk",f),e.on("message:complete",m),e.on("message:error",C)}),(0,o.onUnmounted)(()=>{e.off("message:start",c),e.off("message:chunk",f),e.off("message:complete",m),e.off("message:error",C)});async function g(r,i){a.value=!0,u.value=null;const d={id:`temp-${Date.now()}`,conversationId:s.value||"",content:r,role:"user",status:"DONE",createdAt:new Date},y={id:`temp-assistant-${Date.now()}`,conversationId:s.value||"",content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date};n.value.push(d,y);try{const l=await e.sendMessage(r,{conversationId:s.value,files:i});l.conversationId&&!s.value&&(s.value=l.conversationId),n.value=n.value.filter(A=>!A.id.startsWith("temp-"));const p={...d,id:d.id.replace("temp-","user-"),conversationId:l.conversationId};return n.value.some(A=>A.id===l.id)?n.value.push(p):n.value.push(p,l),l}catch(l){return u.value=l instanceof Error?l:new Error("Failed to send"),a.value=!1,n.value=n.value.filter(p=>!p.id.startsWith("temp-")),null}}function h(){n.value=[],s.value=void 0,u.value=null}return{messages:n,isLoading:a,error:u,conversationId:s,sendMessage:g,clearMessages:h}}function E(t={}){const e=t.client??v(),n=t.autoLoad??!0,s=(0,o.ref)([]),a=(0,o.ref)(null),u=(0,o.ref)(!1),c=(0,o.ref)(null);async function f(){u.value=!0,c.value=null;try{s.value=(await e.getConversations()).data}catch(g){c.value=g instanceof Error?g:new Error("Failed to load conversations")}finally{u.value=!1}}async function m(g){u.value=!0,c.value=null;try{a.value=await e.getConversation(g)}catch(h){c.value=h instanceof Error?h:new Error("Failed to load conversation")}finally{u.value=!1}}function C(){a.value=null}return(0,o.onMounted)(()=>{n&&f()}),{conversations:s,currentConversation:a,isLoading:u,error:c,selectConversation:m,startNewConversation:C,refreshConversations:f}}function S(t={}){const e=M({client:t.client,conversationId:t.conversationId}),n=E({client:t.client,autoLoad:t.autoLoad}),s=(0,o.computed)(()=>e.error.value||n.error.value);return{messages:e.messages,isLoading:e.isLoading,error:s,sendMessage:e.sendMessage,clearMessages:e.clearMessages,conversationId:e.conversationId,conversations:n.conversations,currentConversation:n.currentConversation,isConversationsLoading:n.isLoading,selectConversation:n.selectConversation,startNewConversation:n.startNewConversation,refreshConversations:n.refreshConversations}}function L(t,e){const n=v();(0,o.onMounted)(()=>{n.registerFunction(t,e.handler,{description:e.description,parameters:e.parameters,maxResultBytes:e.maxResultBytes})}),(0,o.onUnmounted)(()=>{n.unregisterFunction(t)})}function P(t,e){const n=v();(0,o.onMounted)(()=>{n.registerNavigationFunction(t,e)}),(0,o.onUnmounted)(()=>{n.unregisterNavigationFunction()})}function F(t,e){const n=v(),s=e?.functionName??"setPageState";(0,o.onMounted)(()=>{n.registerPageStateFunction(t,{functionName:s})}),(0,o.onUnmounted)(()=>{n.unregisterPageStateFunction(s)})}function R(t,e){const n=v();(0,o.onMounted)(()=>{n.on(t,e)}),(0,o.onUnmounted)(()=>{n.off(t,e)})}function U(t){const e=(0,o.shallowRef)(t.get());return(0,o.onScopeDispose)(t.subscribe(n=>{e.value=n})),e}function D(){const t=v(),e=(0,o.shallowRef)(null),n=a=>{e.value=a,t.proactive?.shown(a)},s=({nudge:a})=>{e.value?.id===a.id&&(e.value=null)};return(0,o.onMounted)(()=>{t.on("nudge:ready",n),t.on("nudge:accepted",s),t.on("nudge:dismissed",s)}),(0,o.onUnmounted)(()=>{t.off("nudge:ready",n),t.off("nudge:accepted",s),t.off("nudge:dismissed",s)}),{nudge:e,accept:async()=>{const a=e.value;a&&(e.value=null,await t.proactive?.accept(a))},dismiss:()=>{const a=e.value;a&&(e.value=null,t.proactive?.dismiss(a))}}}exports.AGO_CLIENT_KEY=w;exports.AgoPlugin=N;exports.useAgo=v;exports.useAgoEvents=R;exports.useAgoFunction=L;exports.useAgoNavigation=P;exports.useAgoPageState=F;exports.useAgoStore=U;exports.useChat=S;exports.useConversation=E;exports.useMessages=M;exports.useProactiveNudge=D;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const I=require("./AgoClient-DLB9icvv.cjs");let o=require("vue");var w=Symbol("ago-client"),N={install(t,e){const n=new I.AgoClient(e);t.provide(w,n)}};function v(t){if(t)return new I.AgoClient(t);const e=(0,o.inject)(w);if(!e)throw new Error("useAgo(): no AgoClient found. Either pass config or install AgoPlugin.");return e}function M(t={}){const e=t.client??v(),n=(0,o.ref)([]),s=(0,o.ref)(t.conversationId),a=(0,o.ref)(!1),u=(0,o.ref)(null),c=r=>{s.value||(s.value=r.conversationId)},f=r=>{const i=n.value.findIndex(d=>d.id===r.messageId);i>=0&&(n.value[i]={...n.value[i],content:n.value[i].content+r.content})},m=r=>{const i=n.value.findIndex(d=>d.id===r.id);i>=0?n.value[i]=r:n.value.push(r),a.value=!1},C=r=>{u.value=new Error(r.error),a.value=!1};(0,o.onMounted)(()=>{e.on("message:start",c),e.on("message:chunk",f),e.on("message:complete",m),e.on("message:error",C)}),(0,o.onUnmounted)(()=>{e.off("message:start",c),e.off("message:chunk",f),e.off("message:complete",m),e.off("message:error",C)});async function g(r,i){a.value=!0,u.value=null;const d={id:`temp-${Date.now()}`,conversationId:s.value||"",content:r,role:"user",status:"DONE",createdAt:new Date},y={id:`temp-assistant-${Date.now()}`,conversationId:s.value||"",content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date};n.value.push(d,y);try{const l=await e.sendMessage(r,{conversationId:s.value,files:i});l.conversationId&&!s.value&&(s.value=l.conversationId),n.value=n.value.filter(A=>!A.id.startsWith("temp-"));const p={...d,id:d.id.replace("temp-","user-"),conversationId:l.conversationId};return n.value.some(A=>A.id===l.id)?n.value.push(p):n.value.push(p,l),l}catch(l){return u.value=l instanceof Error?l:new Error("Failed to send"),a.value=!1,n.value=n.value.filter(p=>!p.id.startsWith("temp-")),null}}function h(){n.value=[],s.value=void 0,u.value=null}return{messages:n,isLoading:a,error:u,conversationId:s,sendMessage:g,clearMessages:h}}function E(t={}){const e=t.client??v(),n=t.autoLoad??!0,s=(0,o.ref)([]),a=(0,o.ref)(null),u=(0,o.ref)(!1),c=(0,o.ref)(null);async function f(){u.value=!0,c.value=null;try{s.value=(await e.getConversations()).data}catch(g){c.value=g instanceof Error?g:new Error("Failed to load conversations")}finally{u.value=!1}}async function m(g){u.value=!0,c.value=null;try{a.value=await e.getConversation(g)}catch(h){c.value=h instanceof Error?h:new Error("Failed to load conversation")}finally{u.value=!1}}function C(){a.value=null}return(0,o.onMounted)(()=>{n&&f()}),{conversations:s,currentConversation:a,isLoading:u,error:c,selectConversation:m,startNewConversation:C,refreshConversations:f}}function S(t={}){const e=M({client:t.client,conversationId:t.conversationId}),n=E({client:t.client,autoLoad:t.autoLoad}),s=(0,o.computed)(()=>e.error.value||n.error.value);return{messages:e.messages,isLoading:e.isLoading,error:s,sendMessage:e.sendMessage,clearMessages:e.clearMessages,conversationId:e.conversationId,conversations:n.conversations,currentConversation:n.currentConversation,isConversationsLoading:n.isLoading,selectConversation:n.selectConversation,startNewConversation:n.startNewConversation,refreshConversations:n.refreshConversations}}function L(t,e){const n=v();(0,o.onMounted)(()=>{n.registerFunction(t,e.handler,{description:e.description,parameters:e.parameters,maxResultBytes:e.maxResultBytes})}),(0,o.onUnmounted)(()=>{n.unregisterFunction(t)})}function P(t,e){const n=v();(0,o.onMounted)(()=>{n.registerNavigationFunction(t,e)}),(0,o.onUnmounted)(()=>{n.unregisterNavigationFunction()})}function F(t,e){const n=v(),s=e?.functionName??"setPageState";(0,o.onMounted)(()=>{n.registerPageStateFunction(t,{functionName:s})}),(0,o.onUnmounted)(()=>{n.unregisterPageStateFunction(s)})}function R(t,e){const n=v();(0,o.onMounted)(()=>{n.on(t,e)}),(0,o.onUnmounted)(()=>{n.off(t,e)})}function U(t){const e=(0,o.shallowRef)(t.get());return(0,o.onScopeDispose)(t.subscribe(n=>{e.value=n})),e}function D(){const t=v(),e=(0,o.shallowRef)(null),n=a=>{e.value=a,t.proactive?.shown(a)},s=({nudge:a})=>{e.value?.id===a.id&&(e.value=null)};return(0,o.onMounted)(()=>{t.on("nudge:ready",n),t.on("nudge:accepted",s),t.on("nudge:dismissed",s)}),(0,o.onUnmounted)(()=>{t.off("nudge:ready",n),t.off("nudge:accepted",s),t.off("nudge:dismissed",s)}),{nudge:e,accept:async()=>{const a=e.value;a&&(e.value=null,await t.proactive?.accept(a))},dismiss:()=>{const a=e.value;a&&(e.value=null,t.proactive?.dismiss(a))}}}exports.AGO_CLIENT_KEY=w;exports.AgoPlugin=N;exports.useAgo=v;exports.useAgoEvents=R;exports.useAgoFunction=L;exports.useAgoNavigation=P;exports.useAgoPageState=F;exports.useAgoStore=U;exports.useChat=S;exports.useConversation=E;exports.useMessages=M;exports.useProactiveNudge=D;
package/dist/vue.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as E } from "./AgoClient-BI5esqbd.js";
1
+ import { t as E } from "./AgoClient-B_R_qi2s.js";
2
2
  import { computed as M, inject as F, onMounted as d, onScopeDispose as S, onUnmounted as m, ref as l, shallowRef as A } from "vue";
3
3
  var N = /* @__PURE__ */ Symbol("ago-client"), b = { install(t, e) {
4
4
  const n = new E(e);
package/dist/widget.cjs CHANGED
@@ -1,4 +1,4 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const se=require("./AgoClient-CQh8YovA.cjs"),Xt=require("./createConversationSession-0zVkMdYj.cjs"),mt=require("./createFormCollector-DiCe_8ik.cjs");var Yt='"IBM Plex Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',Ie=`var(--ago-font, ${Yt})`,gt={font:"--ago-font",radius:"--ago-radius",messageRadius:"--ago-message-radius",brand:"--ago-brand-color",brandText:"--ago-brand-text-color",headerBg:"--ago-header-background",headerText:"--ago-header-text-color",panelBg:"--ago-panel-background",messagesBg:"--ago-messages-background",text:"--ago-text-color",mutedText:"--ago-muted-text-color",border:"--ago-border-color",accent:"--ago-accent-color",agentBubbleBg:"--ago-agent-bubble-background"},_e="var(--ago-brand-color, #03182f)",Le="var(--ago-brand-text-color, #fff)",Qt="var(--ago-header-background, var(--ago-brand-color, #03182f))",ht="var(--ago-header-text-color, #e8f0fe)",te="var(--ago-panel-background, #fff)",Ct="var(--ago-messages-background, #fbfbfb)",ee="var(--ago-text-color, #30373e)",Et="var(--ago-muted-text-color, #6b6d6f)",N="var(--ago-border-color, #dee3e8)",Fe="var(--ago-accent-color, #1b5fc4)",xt="var(--ago-agent-bubble-background, #f1f3f5)",Zt="var(--ago-radius, 16px)",Pe="var(--ago-message-radius, 16px)",Jt="var(--ago-message-radius, 20px)";function en(t,o){if(o)for(const i of Object.keys(gt)){const r=o[i];r!=null&&t.style.setProperty(gt[i],r)}}function v(t,o){Object.assign(t.style,o)}function h(t={}){const o=document.createElement("div");return v(o,t),o}var bt="ago-chat-widget-keyframes";function tn(){if(typeof document>"u"||document.getElementById(bt))return;const t=document.createElement("style");t.id=bt,t.textContent="@keyframes ago-pulse { 0%, 80%, 100% { opacity: 0.3; transform: scale(0.8); } 40% { opacity: 1; transform: scale(1); } }@keyframes ago-spin { to { transform: rotate(360deg); } }",document.head.appendChild(t)}function nn(t){let o=[];const i=document.createElement("form");v(i,{display:"flex",flexDirection:"column",gap:"8px",padding:"12px",borderTop:`1px solid ${N}`,backgroundColor:te}),i.className="ago-chat-input";const r=h({display:"flex",flexWrap:"wrap",gap:"6px"}),b=h({display:"flex",gap:"8px",alignItems:"flex-end"}),a=document.createElement("textarea");a.placeholder=t.placeholder,a.setAttribute("aria-label",t.placeholder),a.rows=1,v(a,{flex:"1",resize:"none",boxSizing:"border-box",padding:"10px 12px",border:`1px solid ${N}`,borderRadius:"12px",fontSize:"16px",fontFamily:Ie,lineHeight:"1.4",maxHeight:"110px",overflowY:"hidden"});const C=()=>{a.style.height="auto";const c=Math.min(a.scrollHeight+2,110);a.style.height=`${c}px`,a.style.overflowY=a.scrollHeight+2>110?"auto":"hidden"};a.addEventListener("input",()=>{C(),I()});const m='<svg width="18" height="18" viewBox="0 -960 960 960" fill="currentColor" aria-hidden="true"><path d="M440-160v-487L216-423l-56-57 320-320 320 320-56 57-224-224v487h-80Z"/></svg>',x='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true" style="animation: ago-spin 0.8s linear infinite"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',p=document.createElement("button");p.type="submit",p.setAttribute("aria-label","Send"),p.innerHTML=m,v(p,{flexShrink:"0",width:"40px",height:"40px",padding:"0",border:"none",borderRadius:"50%",backgroundColor:_e,color:Le,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer"});let f=!1;const I=()=>{const l=a.value.trim()!==""||o.length>0,c=f||!l;p.disabled=c,p.innerHTML=f?x:m,p.style.opacity=c&&!f?"0.5":"1",p.style.cursor=c?"default":"pointer"};let R=null,A=null;t.allowFiles&&(R=document.createElement("input"),R.type="file",R.multiple=!0,v(R,{display:"none"}),A=document.createElement("button"),A.type="button",A.setAttribute("aria-label","Attach file"),A.textContent="📎",v(A,{padding:"10px 12px",border:`1px solid ${N}`,borderRadius:"12px",backgroundColor:te,cursor:"pointer",fontSize:"14px"}),A.addEventListener("click",()=>R?.click()),R.addEventListener("change",()=>{o=[...o,...Array.from(R?.files??[])],Q()}));function Q(){r.replaceChildren(),o.forEach((l,c)=>{const w=h({display:"flex",alignItems:"center",gap:"4px",padding:"4px 8px",backgroundColor:"#f0f4ff",border:`1px solid ${N}`,borderRadius:"8px",fontSize:"12px"}),B=document.createElement("span");B.textContent=l.name;const k=document.createElement("button");k.type="button",k.setAttribute("aria-label",`Remove ${l.name}`),k.textContent="×",v(k,{border:"none",background:"transparent",cursor:"pointer",fontSize:"14px",lineHeight:"1"}),k.addEventListener("click",()=>{o=o.filter((j,V)=>V!==c),Q()}),w.append(B,k),r.appendChild(w)}),I()}const D=()=>{const l=a.value,c=o;return a.value="",C(),o=[],Q(),{content:l,files:c}},g=()=>{const{content:l,files:c}=D();(l.trim()||c.length>0)&&t.onSend(l.trim(),c.length>0?c:void 0)};return i.addEventListener("submit",l=>{l.preventDefault(),g()}),a.addEventListener("keydown",l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),g())}),A&&b.appendChild(A),b.append(a,p),R&&i.appendChild(R),i.append(r,b),I(),{inputRow:i,getValueAndClear:D,setDisabled:l=>{a.disabled=l,f=l,I()},focus:()=>a.focus()}}var on={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function ae(t){return t.replace(/[&<>"']/g,o=>on[o])}function vt(t){const o=t.trim();return/^(https?:|mailto:|tel:|#|\/|\.\/|\.\.\/)/i.test(o)||!/^[a-z][a-z0-9+.-]*:/i.test(o)?o:null}var St='"IBM Plex Mono", ui-monospace, SFMono-Regular, Menlo, monospace',Re="";function ne(t){const o=[],i=b=>(o.push(b),`${Re}${o.length-1}${Re}`);let r=t;return r=r.replace(/`([^`]+)`/g,(b,a)=>i(`<code style="background:#f0f2f5;padding:2px 5px;border-radius:4px;font-size:13px;font-family:${St}">${ae(a)}</code>`)),r=r.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g,(b,a,C)=>{const m=vt(C);return m?i(`<img alt="${ae(a)}" src="${ae(m)}" style="max-width:100%;border-radius:8px;margin:4px 0" />`):b}),r=r.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,(b,a,C)=>{const m=vt(C);return m?i(`<a href="${ae(m)}" target="_blank" rel="noopener noreferrer" style="color:#1b5fc4;text-decoration:underline">${ne(a)}</a>`):b}),r=ae(r),r=r.replace(/\*\*([^*]+?)\*\*/g,"<strong>$1</strong>").replace(/__([^_]+?)__/g,"<strong>$1</strong>").replace(/~~([^~]+?)~~/g,"<del>$1</del>").replace(/(^|[^*])\*(?!\s)([^*]+?)\*/g,"$1<em>$2</em>").replace(/(^|[^\w_])_(?!\s)([^_]+?)_/g,"$1<em>$2</em>"),r=r.replace(new RegExp(`${Re}(\\d+)${Re}`,"g"),(b,a)=>o[Number(a)]),r}function O(t,o,i){const r=document.createElement(t);return Object.assign(r.style,o),i!==void 0&&(r.innerHTML=i),r}var Rt=/^ {0,3}([-*_])( *\1){2,} *$/,kt=/^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$/,It=/^ {0,3}(```+|~~~+)/,Ae=/^ {0,3}>\s?/,le=/^(\s*)([-*+]|\d+[.)])\s+(.*)$/,rn=["20px","18px","16px","15px","14px","13px"],He=t=>t.match(/^\s*/)?.[0].length??0;function an(t){return t.trim()===""||Rt.test(t)||kt.test(t)||It.test(t)||Ae.test(t)||le.test(t)}function At(t){const o=t[0].match(le),i=o[1].length,r=/\d/.test(o[2]),b=O(r?"ol":"ul",{margin:"0 0 8px 0",paddingLeft:"20px",listStyleType:r?"decimal":"disc",listStylePosition:"outside"});let a=0;for(;a<t.length;){const C=t[a].match(le),m=[];for(a++;a<t.length&&He(t[a])>i;)m.push(t[a]),a++;const x=O("li",{display:"list-item",margin:"2px 0",lineHeight:"1.6"}),p=C[3].match(/^\[([ xX])\]\s+(.*)$/);p?(x.style.listStyleType="none",x.style.marginLeft="-20px",x.innerHTML=`<span style="margin-right:6px">${p[1].toLowerCase()==="x"?"☑":"☐"}</span>${ne(p[2])}`):x.innerHTML=ne(C[3]),m.filter(f=>le.test(f)).length>0&&x.appendChild(At(m.filter(f=>f.trim()!==""))),b.appendChild(x)}return b}function sn(t){const o=m=>m.replace(/^\s*\|?/,"").replace(/\|?\s*$/,"").split("|").map(x=>x.trim()),i=O("div",{overflowX:"auto",margin:"0 0 8px 0"}),r=O("table",{borderCollapse:"collapse",width:"100%",fontSize:"13px"}),b=document.createElement("thead"),a=document.createElement("tr");for(const m of o(t[0]))a.appendChild(O("th",{border:"1px solid #dee3e8",padding:"6px 10px",textAlign:"left",backgroundColor:"#f5f7fa",fontWeight:"600"},ne(m)));b.appendChild(a),r.appendChild(b);const C=document.createElement("tbody");for(const m of t.slice(2)){const x=document.createElement("tr");for(const p of o(m))x.appendChild(O("td",{border:"1px solid #dee3e8",padding:"6px 10px"},ne(p)));C.appendChild(x)}return r.appendChild(C),i.appendChild(r),i}var ln=t=>!!t&&/^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/.test(t);function Ne(t){const o=document.createDocumentFragment(),i=t.replace(/\r\n?/g,`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const se=require("./AgoClient-DLB9icvv.cjs"),Xt=require("./createConversationSession-Dqh7NXK4.cjs"),mt=require("./createFormCollector-BjO3oB63.cjs");var Yt='"IBM Plex Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',Ie=`var(--ago-font, ${Yt})`,gt={font:"--ago-font",radius:"--ago-radius",messageRadius:"--ago-message-radius",brand:"--ago-brand-color",brandText:"--ago-brand-text-color",headerBg:"--ago-header-background",headerText:"--ago-header-text-color",panelBg:"--ago-panel-background",messagesBg:"--ago-messages-background",text:"--ago-text-color",mutedText:"--ago-muted-text-color",border:"--ago-border-color",accent:"--ago-accent-color",agentBubbleBg:"--ago-agent-bubble-background"},_e="var(--ago-brand-color, #03182f)",Le="var(--ago-brand-text-color, #fff)",Qt="var(--ago-header-background, var(--ago-brand-color, #03182f))",ht="var(--ago-header-text-color, #e8f0fe)",te="var(--ago-panel-background, #fff)",Ct="var(--ago-messages-background, #fbfbfb)",ee="var(--ago-text-color, #30373e)",Et="var(--ago-muted-text-color, #6b6d6f)",N="var(--ago-border-color, #dee3e8)",Fe="var(--ago-accent-color, #1b5fc4)",xt="var(--ago-agent-bubble-background, #f1f3f5)",Zt="var(--ago-radius, 16px)",Pe="var(--ago-message-radius, 16px)",Jt="var(--ago-message-radius, 20px)";function en(t,o){if(o)for(const i of Object.keys(gt)){const r=o[i];r!=null&&t.style.setProperty(gt[i],r)}}function v(t,o){Object.assign(t.style,o)}function h(t={}){const o=document.createElement("div");return v(o,t),o}var bt="ago-chat-widget-keyframes";function tn(){if(typeof document>"u"||document.getElementById(bt))return;const t=document.createElement("style");t.id=bt,t.textContent="@keyframes ago-pulse { 0%, 80%, 100% { opacity: 0.3; transform: scale(0.8); } 40% { opacity: 1; transform: scale(1); } }@keyframes ago-spin { to { transform: rotate(360deg); } }",document.head.appendChild(t)}function nn(t){let o=[];const i=document.createElement("form");v(i,{display:"flex",flexDirection:"column",gap:"8px",padding:"12px",borderTop:`1px solid ${N}`,backgroundColor:te}),i.className="ago-chat-input";const r=h({display:"flex",flexWrap:"wrap",gap:"6px"}),b=h({display:"flex",gap:"8px",alignItems:"flex-end"}),a=document.createElement("textarea");a.placeholder=t.placeholder,a.setAttribute("aria-label",t.placeholder),a.rows=1,v(a,{flex:"1",resize:"none",boxSizing:"border-box",padding:"10px 12px",border:`1px solid ${N}`,borderRadius:"12px",fontSize:"16px",fontFamily:Ie,lineHeight:"1.4",maxHeight:"110px",overflowY:"hidden"});const C=()=>{a.style.height="auto";const c=Math.min(a.scrollHeight+2,110);a.style.height=`${c}px`,a.style.overflowY=a.scrollHeight+2>110?"auto":"hidden"};a.addEventListener("input",()=>{C(),I()});const m='<svg width="18" height="18" viewBox="0 -960 960 960" fill="currentColor" aria-hidden="true"><path d="M440-160v-487L216-423l-56-57 320-320 320 320-56 57-224-224v487h-80Z"/></svg>',x='<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true" style="animation: ago-spin 0.8s linear infinite"><path d="M21 12a9 9 0 1 1-6.219-8.56"/></svg>',p=document.createElement("button");p.type="submit",p.setAttribute("aria-label","Send"),p.innerHTML=m,v(p,{flexShrink:"0",width:"40px",height:"40px",padding:"0",border:"none",borderRadius:"50%",backgroundColor:_e,color:Le,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer"});let f=!1;const I=()=>{const l=a.value.trim()!==""||o.length>0,c=f||!l;p.disabled=c,p.innerHTML=f?x:m,p.style.opacity=c&&!f?"0.5":"1",p.style.cursor=c?"default":"pointer"};let R=null,A=null;t.allowFiles&&(R=document.createElement("input"),R.type="file",R.multiple=!0,v(R,{display:"none"}),A=document.createElement("button"),A.type="button",A.setAttribute("aria-label","Attach file"),A.textContent="📎",v(A,{padding:"10px 12px",border:`1px solid ${N}`,borderRadius:"12px",backgroundColor:te,cursor:"pointer",fontSize:"14px"}),A.addEventListener("click",()=>R?.click()),R.addEventListener("change",()=>{o=[...o,...Array.from(R?.files??[])],Q()}));function Q(){r.replaceChildren(),o.forEach((l,c)=>{const w=h({display:"flex",alignItems:"center",gap:"4px",padding:"4px 8px",backgroundColor:"#f0f4ff",border:`1px solid ${N}`,borderRadius:"8px",fontSize:"12px"}),B=document.createElement("span");B.textContent=l.name;const k=document.createElement("button");k.type="button",k.setAttribute("aria-label",`Remove ${l.name}`),k.textContent="×",v(k,{border:"none",background:"transparent",cursor:"pointer",fontSize:"14px",lineHeight:"1"}),k.addEventListener("click",()=>{o=o.filter((j,V)=>V!==c),Q()}),w.append(B,k),r.appendChild(w)}),I()}const D=()=>{const l=a.value,c=o;return a.value="",C(),o=[],Q(),{content:l,files:c}},g=()=>{const{content:l,files:c}=D();(l.trim()||c.length>0)&&t.onSend(l.trim(),c.length>0?c:void 0)};return i.addEventListener("submit",l=>{l.preventDefault(),g()}),a.addEventListener("keydown",l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),g())}),A&&b.appendChild(A),b.append(a,p),R&&i.appendChild(R),i.append(r,b),I(),{inputRow:i,getValueAndClear:D,setDisabled:l=>{a.disabled=l,f=l,I()},focus:()=>a.focus()}}var on={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function ae(t){return t.replace(/[&<>"']/g,o=>on[o])}function vt(t){const o=t.trim();return/^(https?:|mailto:|tel:|#|\/|\.\/|\.\.\/)/i.test(o)||!/^[a-z][a-z0-9+.-]*:/i.test(o)?o:null}var St='"IBM Plex Mono", ui-monospace, SFMono-Regular, Menlo, monospace',Re="";function ne(t){const o=[],i=b=>(o.push(b),`${Re}${o.length-1}${Re}`);let r=t;return r=r.replace(/`([^`]+)`/g,(b,a)=>i(`<code style="background:#f0f2f5;padding:2px 5px;border-radius:4px;font-size:13px;font-family:${St}">${ae(a)}</code>`)),r=r.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g,(b,a,C)=>{const m=vt(C);return m?i(`<img alt="${ae(a)}" src="${ae(m)}" style="max-width:100%;border-radius:8px;margin:4px 0" />`):b}),r=r.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,(b,a,C)=>{const m=vt(C);return m?i(`<a href="${ae(m)}" target="_blank" rel="noopener noreferrer" style="color:#1b5fc4;text-decoration:underline">${ne(a)}</a>`):b}),r=ae(r),r=r.replace(/\*\*([^*]+?)\*\*/g,"<strong>$1</strong>").replace(/__([^_]+?)__/g,"<strong>$1</strong>").replace(/~~([^~]+?)~~/g,"<del>$1</del>").replace(/(^|[^*])\*(?!\s)([^*]+?)\*/g,"$1<em>$2</em>").replace(/(^|[^\w_])_(?!\s)([^_]+?)_/g,"$1<em>$2</em>"),r=r.replace(new RegExp(`${Re}(\\d+)${Re}`,"g"),(b,a)=>o[Number(a)]),r}function O(t,o,i){const r=document.createElement(t);return Object.assign(r.style,o),i!==void 0&&(r.innerHTML=i),r}var Rt=/^ {0,3}([-*_])( *\1){2,} *$/,kt=/^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$/,It=/^ {0,3}(```+|~~~+)/,Ae=/^ {0,3}>\s?/,le=/^(\s*)([-*+]|\d+[.)])\s+(.*)$/,rn=["20px","18px","16px","15px","14px","13px"],He=t=>t.match(/^\s*/)?.[0].length??0;function an(t){return t.trim()===""||Rt.test(t)||kt.test(t)||It.test(t)||Ae.test(t)||le.test(t)}function At(t){const o=t[0].match(le),i=o[1].length,r=/\d/.test(o[2]),b=O(r?"ol":"ul",{margin:"0 0 8px 0",paddingLeft:"20px",listStyleType:r?"decimal":"disc",listStylePosition:"outside"});let a=0;for(;a<t.length;){const C=t[a].match(le),m=[];for(a++;a<t.length&&He(t[a])>i;)m.push(t[a]),a++;const x=O("li",{display:"list-item",margin:"2px 0",lineHeight:"1.6"}),p=C[3].match(/^\[([ xX])\]\s+(.*)$/);p?(x.style.listStyleType="none",x.style.marginLeft="-20px",x.innerHTML=`<span style="margin-right:6px">${p[1].toLowerCase()==="x"?"☑":"☐"}</span>${ne(p[2])}`):x.innerHTML=ne(C[3]),m.filter(f=>le.test(f)).length>0&&x.appendChild(At(m.filter(f=>f.trim()!==""))),b.appendChild(x)}return b}function sn(t){const o=m=>m.replace(/^\s*\|?/,"").replace(/\|?\s*$/,"").split("|").map(x=>x.trim()),i=O("div",{overflowX:"auto",margin:"0 0 8px 0"}),r=O("table",{borderCollapse:"collapse",width:"100%",fontSize:"13px"}),b=document.createElement("thead"),a=document.createElement("tr");for(const m of o(t[0]))a.appendChild(O("th",{border:"1px solid #dee3e8",padding:"6px 10px",textAlign:"left",backgroundColor:"#f5f7fa",fontWeight:"600"},ne(m)));b.appendChild(a),r.appendChild(b);const C=document.createElement("tbody");for(const m of t.slice(2)){const x=document.createElement("tr");for(const p of o(m))x.appendChild(O("td",{border:"1px solid #dee3e8",padding:"6px 10px"},ne(p)));C.appendChild(x)}return r.appendChild(C),i.appendChild(r),i}var ln=t=>!!t&&/^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/.test(t);function Ne(t){const o=document.createDocumentFragment(),i=t.replace(/\r\n?/g,`
2
2
  `).split(`
3
3
  `);let r=0;for(;r<i.length;){const a=i[r];if(a.trim()===""){r++;continue}const C=a.match(It);if(C){const p=C[1][0],f=[];for(r++;r<i.length&&!new RegExp(`^ {0,3}${p==="`"?"`{3,}":"~{3,}"}\\s*$`).test(i[r]);)f.push(i[r]),r++;r++;const I=O("pre",{margin:"0 0 8px 0"});I.appendChild(O("code",{display:"block",background:"#f5f5f5",padding:"8px 12px",borderRadius:"6px",fontSize:"13px",overflowX:"auto",fontFamily:St,whiteSpace:"pre"},ae(f.join(`
4
4
  `)))),o.appendChild(I);continue}if(Rt.test(a)){o.appendChild(O("hr",{border:"none",borderTop:"1px solid #dee3e8",margin:"12px 0"})),r++;continue}const m=a.match(kt);if(m){const p=m[1].length;o.appendChild(O(`h${p}`,{margin:"16px 0 8px 0",fontSize:rn[p-1],fontWeight:"600",lineHeight:"1.3"},ne(m[2]))),r++;continue}if(Ae.test(a)){const p=[];for(;r<i.length&&Ae.test(i[r]);)p.push(i[r].replace(Ae,"")),r++;const f=O("blockquote",{borderLeft:"4px solid #dee3e8",paddingLeft:"12px",margin:"0 0 8px 0",fontStyle:"italic",color:"#6b6d6f"});f.appendChild(Ne(p.join(`
package/dist/widget.js CHANGED
@@ -1,6 +1,6 @@
1
- import { a as qt, b as Kt, i as Xt, o as Yt, s as Qt, t as Zt } from "./AgoClient-BI5esqbd.js";
2
- import { t as Jt } from "./createConversationSession-BlYTpxwz.js";
3
- import { r as en, t as tn } from "./createFormCollector-Bgs94NyR.js";
1
+ import { a as qt, b as Kt, i as Xt, o as Yt, s as Qt, t as Zt } from "./AgoClient-B_R_qi2s.js";
2
+ import { t as Jt } from "./createConversationSession-CdtI4vrf.js";
3
+ import { r as en, t as tn } from "./createFormCollector-YwaZ78wU.js";
4
4
  var nn = '"IBM Plex Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif', ke = `var(--ago-font, ${nn})`, ut = {
5
5
  font: "--ago-font",
6
6
  radius: "--ago-radius",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@useago/sdk",
3
- "version": "1.5.5",
3
+ "version": "1.5.6",
4
4
  "description": "Create In-APP AI agents that answers question and performs actions. Works with React, Vue, Angular and vanilla JS/TS.",
5
5
  "type": "module",
6
6
  "sideEffects": false,