@useago/sdk 1.7.1 → 1.7.2

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,25 @@ 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.7.2] - 2026-08-10
9
+
10
+ ### Changed
11
+
12
+ - Every "try the SDK" instruction now points at the same public demo account
13
+ (`https://playground.api.useago.com`, agent `generic-guide`). The examples
14
+ under `examples/` still pointed at a second backend, so a reader following the
15
+ README and a reader cloning an example were testing against different
16
+ tenants. Docs, README, and examples now agree, and the wording is "demo
17
+ account" everywhere instead of a mix of "live demo", "demo backend", and
18
+ "demo endpoint".
19
+ - The `config_missing_base_url` error hint names the demo account and its agent
20
+ slug, so the message is copy-pasteable on its own.
21
+ - The copy-paste prompt for coding agents in the README now installs the SDK and
22
+ names the demo agent to wire up (`https://playground.api.useago.com`, agent
23
+ `generic-guide`). It only told the agent to read `llms-full.txt` and
24
+ integrate, so the install was implicit and the agent had to pick a `baseUrl`
25
+ and slug on its own. Pasting the prompt now ends on a chat that answers.
26
+
8
27
  ## [1.7.1] - 2026-08-10
9
28
 
10
29
  ### Fixed
package/README.md CHANGED
@@ -24,8 +24,11 @@ resolve customer needs, without rebuilding the full customer-facing agent platfo
24
24
  > this into your agent and let it do the integration:
25
25
  >
26
26
  > ```text
27
- > Read https://raw.githubusercontent.com/useago/ago-sdk/refs/heads/main/llms-full.txt
28
- > and integrate the AGO chat SDK into this app.
27
+ > Install the AGO chat SDK in this app: npm install @useago/sdk
28
+ > Then read https://raw.githubusercontent.com/useago/ago-sdk/refs/heads/main/llms-full.txt
29
+ > and wire up a working chat against the public demo agent:
30
+ > baseUrl https://playground.api.useago.com, agent generic-guide.
31
+ > It answers straight away, with no signup and no API key.
29
32
  > ```
30
33
 
31
34
  In two minutes you'll have a working chat on your page and an agent that can
@@ -64,8 +67,10 @@ export default function App() {
64
67
  ```
65
68
 
66
69
  Start your dev server. A chat panel renders on the page; type a message and
67
- watch the reply stream in. That's a complete integration. (`generic-guide` is a
68
- public demo agent; swap `baseUrl` and `agent` for your own once you have a tenant.)
70
+ watch the reply stream in. That's a complete integration. (This is the public
71
+ demo account: `https://playground.api.useago.com` with agent `generic-guide`. It
72
+ needs no signup and no API key. Swap `baseUrl` and `agent` for your own once you
73
+ have a tenant.)
69
74
 
70
75
  `ChatWidget` is the high-level component to get started in minutes. Everything it
71
76
  does is also exposed through hooks and APIs (`useChat`, `useMessages`, the raw
@@ -313,7 +318,7 @@ cd examples/simple-react
313
318
  npm install && npm run dev
314
319
  ```
315
320
 
316
- The examples ship pre-configured against the demo backend, so they answer
321
+ The examples ship pre-configured against the demo account, so they answer
317
322
  immediately. [`examples/`](examples/) has one per stack: React (with
318
323
  react-router navigation), Vue, Angular, plain TypeScript, and no-build HTML.
319
324
 
@@ -1,7 +1,7 @@
1
1
  var ie=10,$=1e3;function ne(e){if(typeof e!="object"||e===null)return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function E(e,t){if(typeof e=="string"){if(e.length<=1e3)return e;const s=e.length-$;return e.slice(0,$)+`…[truncated ${s} chars]`}if(Array.isArray(e)){if(t.has(e))return"…[circular]";t.add(e);const s=e.slice(0,50).map(i=>E(i,t));return e.length>50&&s.push(`…[+${e.length-50} more]`),t.delete(e),s}if(ne(e)){if(t.has(e))return"…[circular]";t.add(e);const s={};for(const[i,n]of Object.entries(e))s[i]=E(n,t);return t.delete(e),s}return e}function re(e){return E(e,new WeakSet)}var K=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:re(e.data)}:{}};this.entries.push(t);const s=this.entries.length-this.maxEntries;return s>0&&this.entries.splice(0,s),t}getRecent(){return[...this.entries]}get size(){return this.entries.length}clear(){this.entries=[]}},g=class extends Error{constructor(e,t,s){super(e),this.code=t,this.statusCode=s,this.name="AgoError"}},y=class H extends g{constructor(t,s,i,n,r,c){super(t,s,i),this.type=n,this.param=r,this.docUrl=c,this.name="AgoApiError"}static fromResponse(t,s){const i=t.error;return new H(i.doc_url?`${i.message} See ${i.doc_url}`:i.message,i.code,s,i.type,i.param,i.doc_url)}},w=class extends g{constructor(e,t){super(e,"network_error"),this.originalError=t,this.name="AgoNetworkError"}},_=class extends g{constructor(e,t="stream_error"){super(e,t),this.name="AgoStreamError"}},I=class extends g{constructor(e,t,s){super(e,"function_error"),this.functionName=t,this.originalError=s,this.name="AgoFunctionError"}},oe=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)}},l=new oe,N="ago_widget_id";function R(e){return typeof DOMException<"u"&&e instanceof DOMException&&e.name==="AbortError"||e instanceof Error&&e.name==="AbortError"}function ae(){if(typeof localStorage<"u"){const t=localStorage.getItem(N);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(N,e)}catch{}return e}var ce=class{constructor(e){this.baseUrl=e.baseUrl.replace(/\/$/,""),this.headers={"X-User-Anon-Id":e.widgetId||ae()},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,s){return this.request("POST",e,t,s)}async postStream(e,t,s){const i=`${this.baseUrl}${e}`;l.debug("POST (stream)",i,t);try{const n=await fetch(i,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:t?JSON.stringify(t):void 0,signal:s?.signal});return n.ok||await this.handleErrorResponse(n),n}catch(n){throw n instanceof y||R(n)?n:new w(`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 postFormData(e,t,s){const i=`${this.baseUrl}${e}`;l.debug("POST (formData)",i);const n={...this.headers};try{const r=await fetch(i,{method:"POST",headers:n,body:t,signal:s?.signal});return r.ok||await this.handleErrorResponse(r),r}catch(r){throw r instanceof y||R(r)?r:new w(`Network error: ${r instanceof Error?r.message:"Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`,r instanceof Error?r:void 0)}}async request(e,t,s,i){const n=`${this.baseUrl}${t}`;l.debug(e,n,s);try{const r=await fetch(n,{method:e,headers:{...this.headers,"Content-Type":"application/json"},body:s?JSON.stringify(s):void 0,...i?.keepalive?{keepalive:!0}:{}});return r.ok||await this.handleErrorResponse(r),r.status===204?void 0:r.json()}catch(r){throw r instanceof y?r:new w(`Network error: ${r instanceof Error?r.message:"Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`,r instanceof Error?r:void 0)}}async handleErrorResponse(e){let t;try{t=await e.json()}catch{}if(t?.error)throw y.fromResponse(t,e.status);let s="";throw e.status===401||e.status===403?s=" Check `userJwt` (and that it has not expired).":e.status===404&&(s=" Check that `baseUrl` points at your AGO API root."),new y(`HTTP ${e.status}: ${e.statusText}.${s}`,"http_error",e.status,"api_error")}},le=5e4,ue=2e4,he=2e3,z=class{constructor(e){this.functions=new Map,this.defaultMaxResultBytes=e?.maxResultBytes??le}setDefaultMaxResultBytes(e){this.defaultMaxResultBytes=e}getDefaultMaxResultBytes(){return this.defaultMaxResultBytes}register(e,t,s){if(typeof e=="object"){const{name:o,handler:a,description:h,parameters:u,maxResultBytes:d,requiresApproval:f}=e;return this.register(o,a,{description:h,parameters:u,maxResultBytes:d,requiresApproval:f})}const i=e;if(!t||!s)throw new g(`registerFunction("${i}"): 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(i)&&l.warn(`Function "${i}" is being overwritten`);const{maxResultBytes:n,requiresApproval:r,...c}=s;this.functions.set(i,{schema:{...c,name:i},handler:t,maxResultBytes:n,requiresApproval:r}),l.log(`Registered function: ${i}`)}unregister(e){const t=this.functions.delete(e);return t&&l.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 s=this.functions.get(e);if(!s)throw new I(`Function "${e}" is not registered`,e);l.log(`Executing function: ${e}`,t);try{const i=await s.handler(t);return l.log(`Function ${e} completed:`,i),this.guardResultSize(e,i,s.maxResultBytes)}catch(i){throw l.error(`Function ${e} failed:`,i),new I(`Function "${e}" execution failed: ${i instanceof Error?i.message:"Unknown error"}`,e,i instanceof Error?i:void 0)}}guardResultSize(e,t,s){let i;try{i=JSON.stringify(t)}catch{return t}if(i===void 0)return t;const n=new TextEncoder().encode(i).length,r=s??this.defaultMaxResultBytes;return n>r?(l.warn(`Function "${e}" result is ${n} bytes, over the ${r}-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:r,preview:i.slice(0,he),hint:`The result of "${e}" exceeded the ${r}-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>ue&&l.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(),l.log("Cleared all registered functions")}get size(){return this.functions.size}},de=50,ge=2;var fe=2e3,pe=new TextEncoder;function m(e){return pe.encode(e).length}function v(e){try{return JSON.stringify(e)}catch{return}}var k=Symbol("ago.pageData.timeout");function me(e,t){return t<=0?Promise.resolve(k):new Promise((s,i)=>{const n=setTimeout(()=>s(k),t);e.then(r=>{clearTimeout(n),s(r)},r=>{clearTimeout(n),i(r)})})}async function ye(e,t){const s=Date.now()+t;let i=0;for(;Date.now()<s&&i<ge;)i=e().isLoading?.()?0:i+1,await new Promise(o=>setTimeout(o,de));const n=e().get();if(!M(n))return n;const r=await me(Promise.resolve(n),s-Date.now());if(r!==k)return r;l.warn("Page data did not resolve within the settle timeout; returning what the page has now. Raise settleTimeoutMs if the work legitimately takes longer.");const c=e().get();if(!M(c))return c;Promise.resolve(c).catch(()=>{})}function M(e){return typeof e=="object"&&e!==null&&typeof e.then=="function"}function ve(e){if(typeof e!="object"||e===null||Array.isArray(e))return;const t=e;let s;for(const i of Object.keys(t)){const n=t[i];Array.isArray(n)&&(s===void 0||n.length>t[s].length)&&(s=i)}return s}function we(e,t){let s=2,i=0;for(const n of e){const r=m(v(n)??"null")+(i>0?1:0);if(s+r>t)break;s+=r,i++}return i}function Ce(e,t){if(t<=0)return"";const s=r=>m(JSON.stringify(r))-2;let i=e.slice(0,t),n=s(i);for(;n>t&&i.length>0;)i=i.slice(0,Math.max(0,Math.floor(i.length*t/n)-1)),n=s(i);return i}function T(e){return`The page data returned by "${e}" was too large to send in full. Only the first items are included: ask for fewer rows or narrow the filters to see the rest.`}function Se(e,t,s,i){const n={truncated:!0,originalBytes:s,maxBytes:i,preview:"",hint:T(e)},r=m(v(n)??"{}");return{...n,preview:Ce(t,Math.min(fe,i-r))}}function be(e,t,s,i,n){const r=s===void 0?{}:{...t},c=s??"items",o=m(v({...r,[c]:[],truncation:{truncated:!0,returnedItems:i.length,totalItems:i.length,hint:T(e)}})??"{}")-2;if(o>=n)return;const a=i.slice(0,we(i,n-o));return{...r,[c]:a,truncation:{truncated:!0,returnedItems:a.length,totalItems:i.length,hint:T(e)}}}function U(e,t,s){const i=v(t);if(i===void 0)return t;const n=m(i);if(n<=s)return t;l.warn(`Page data for "${e}" is ${n} bytes, over the ${s}-byte limit; it was truncated to the first items that fit. Return fewer fields per item, paginate, or raise maxResultBytes on the data source.`);const r=ve(t),c=Array.isArray(t)?t:r!==void 0?t[r]:void 0;if(c){const o=be(e,t,r,c,s),a=m(v(o)??"");if(o!==void 0&&a<=s)return o}return Se(e,i,n,s)}var Ae=250,Ee=3,_e=1e3,Ie=24,Re=10,ke=50,Te=["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??Ae,this.rageClickCount=e.rageClickCount??Ee,this.rageClickWindowMs=e.rageClickWindowMs??_e,this.rageClickRadiusPx=e.rageClickRadiusPx??Ie,this.maxRecentRoutes=e.maxRecentRoutes??Re,this.maxSignals=e.maxSignals??ke}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=(i,n,r)=>{i.addEventListener(n,r,{passive:!0}),this.teardowns.push(()=>i.removeEventListener(n,r))},s=()=>this.recordActivity();for(const i of Te)t(window,i,s);t(document,"visibilitychange",()=>{document.visibilityState==="visible"&&this.recordActivity()}),t(window,"popstate",()=>this.checkRoute()),t(window,"hashchange",()=>this.checkRoute()),t(window,"click",i=>this.onClick(i)),l.log("SignalCollector started")}destroy(){for(const e of this.teardowns)e();this.teardowns=[],this.listeners.clear(),this.recentClicks=[],this.started=!1,l.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 l.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(),s=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:s}});const i=this.recentRoutes,n=i.length;n>=4&&i[n-1]===i[n-3]&&i[n-2]===i[n-4]&&i[n-1]!==i[n-2]&&(this.routeBounces+=1,this.pushSignal({type:"route_bounce",route:e,at:t,count:this.routeBounces,meta:{between:`${i[n-2]}↔${i[n-1]}`}}))}onClick(e){this.recordActivity();const t=Date.now(),s=this.pageStateKey(),i={at:t,x:e.clientX,y:e.clientY,stateKey:s};this.recentClicks=this.recentClicks.filter(o=>t-o.at<=this.rageClickWindowMs);const n=this.recentClicks[0],r=!n||Math.abs(i.x-n.x)<=this.rageClickRadiusPx&&Math.abs(i.y-n.y)<=this.rageClickRadiusPx,c=!n||n.stateKey===s;if(!r||!c){this.recentClicks=[i];return}this.recentClicks.push(i),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(s){l.error("Signal listener threw:",s)}}};function X(e,t){const s=t?t.storage??(typeof localStorage<"u"?localStorage:void 0):void 0;let i=e;if(t&&s)try{const o=s.getItem(t.key);o!=null&&(i=JSON.parse(o))}catch{}const n=new Set,r=()=>n.forEach(o=>o(i));function c(){if(t&&s)try{s.setItem(t.key,JSON.stringify(i))}catch{}}return{get:()=>i,set:o=>{i=o,c(),r()},subscribe:o=>(n.add(o),()=>{n.delete(o)})}}var xe=6e4,Pe=1440*60*1e3,Fe="ago_proactive";function b(e){const t=new Date(e),s=String(t.getMonth()+1).padStart(2,"0"),i=String(t.getDate()).padStart(2,"0");return`${t.getFullYear()}-${s}-${i}`}var Oe=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=X({optOut:!1,lastFiredAt:{},dismissedAt:{},day:{date:b(Date.now()),count:0}},{key:e.storageKey??Fe,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 s=this.store.get();if(s.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 i=s.lastFiredAt[e.id],n=e.cooldownMs??xe;if(i!==void 0&&t-i<n)return this.deny(e,"cooldown");const r=s.dismissedAt[e.id],c=e.resurfaceAfterMs??Pe;return r!==void 0&&t-r<c?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 s=this.store.get();this.store.set({...s,lastFiredAt:{...s.lastFiredAt,[e]:t}})}recordNudgeShown(e=Date.now()){this.sessionCount+=1;const t=this.store.get(),s=b(e),i=t.day.date===s?{date:s,count:t.day.count+1}:{date:s,count:1};this.store.set({...t,day:i})}recordDismissed(e,t=Date.now()){const s=this.store.get();this.store.set({...s,dismissedAt:{...s.dismissedAt,[e]:t}})}dayCount(e){const t=this.store.get();return t.day.date===b(e)?t.day.count:0}deny(e,t){return l.debug(`NudgeGovernor: trigger "${e.id}" blocked — ${t}`),!1}};function j(){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 De(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Y(e,t){if(e==="*"||e===t)return!0;const s=e.split("/"),i=s.map((n,r)=>{const c=r===s.length-1;return n==="*"?c?"[^/]+(?:/[^/]+)*":"[^/]+":n.startsWith(":")?"[^/]+":De(n)});return new RegExp("^"+i.join("/")+"/?$").test(t)}function D(e,t){return e===t?!0:e===null||t===null?!1:Array.isArray(e)?!Array.isArray(t)||t.length!==e.length?!1:e.every((s,i)=>x(s,t[i])):typeof e=="object"?typeof t!="object"||Array.isArray(t)?!1:Object.entries(e).every(([s,i])=>D(i,t[s])):!1}function x(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((s,i)=>x(s,t[i]));if(typeof e=="object"){const s=Object.keys(e),i=Object.keys(t);return s.length!==i.length?!1:s.every(n=>x(e[n],t[n]))}return!1}function V(e,t){if(e.route!==void 0&&!Y(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[s,i]of Object.entries(e.fieldErrors))if((t.fieldErrors[s]??0)<i)return!1}return!(e.pageState!==void 0&&!D(e.pageState,t.pageState??{}))}var $e=1e3,Ne="/api/sdk/v1/config",Me="/api/sdk/v1/proactive/evaluate",Ue=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??$e}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),s=()=>this.governor.setTurnInFlight(!1),i=n=>{n?.id&&(this.lastConversationId=n.id)};this.client.on("message:start",e),this.client.on("message:complete",t),this.client.on("message:error",s),this.client.on("conversation:loaded",i),this.teardowns.push(()=>{this.client.off("message:start",e),this.client.off("message:complete",t),this.client.off("message:error",s),this.client.off("conversation:loaded",i)}),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(Ne);this.governor.setKillSwitch(e?.proactive?.enabled===!0)}catch(e){l.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(V(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:j(),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=j(),s={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 i;try{i=await this.client.getHttp().post(Me,s)}catch(n){l.debug("Proactive evaluate failed (treated as no-intervene):",n),this.governor.releaseSlot();return}if(!i?.intervene||!i.message){this.governor.releaseSlot();return}this.setReady({id:t,triggerId:e.id,source:"agent",message:i.message,action:je(i.action),goal:e.goal,kickoff:e.kickoff,createdAt:new Date,serverNudgeId:i.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(Le(e),{hidden:!0,conversationId:this.lastConversationId}).catch(t=>l.debug("Nudge kickoff message failed:",t)):e.kickoff?this.client.sendMessage(e.kickoff).catch(t=>l.debug("Nudge kickoff message failed:",t)):l.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){l.warn("Nudge action failed:",t)}}};function je(e){if(e)return{label:e.label,functionName:e.function_name,arguments:e.arguments}}function Le(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 Be=5e3,qe="/api/sdk/v1/proactive/events",Ge=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??Be,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 s={events:t.map(i=>({client_nudge_id:i.clientNudgeId,trigger_id:i.triggerId,source:i.source,type:i.type,...i.message!==void 0?{message:i.message}:{},...this.agent?{agent:this.agent}:{},occurred_at:new Date(i.occurredAt).toISOString()}))};this.post(qe,s,e).catch(i=>{l.debug("Proactive event batch failed:",i)})}destroy(){if(!this.destroyed){this.flush({keepalive:!0}),this.destroyed=!0;for(const e of this.teardowns)e();this.teardowns=[]}}},L="friction_signals";function P(e,t){e.proactive&&(l.warn("createAgoProactive: a proactive controller is already attached; replacing it."),e.proactive.destroy());const s=new J({...t.signals,getPageState:()=>{const o=e.getContextSnapshot();if(!o)return null;const a={};for(const[h,u]of Object.entries(o.entries))h.startsWith("page-state:")&&u.data&&Object.assign(a,u.data);return Object.keys(a).length>0?a:null}});s.start(),e.addDynamicContext(L,()=>{const{pageState:o,...a}=s.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:a}});const i=new Oe({frequencyCap:t.frequencyCap,storage:t.storage,storageKey:t.storageKey}),n=new Ge({post:(o,a,h)=>e.getHttp().post(o,a,h),agent:e.getConfiguredAgent()}),r=new Ue({client:e,collector:s,governor:i,tracker:n,options:t});r.start();const c={optOut:()=>i.optOut(),optIn:()=>i.optIn(),isOptedOut:()=>i.isOptedOut(),setEngaged:o=>i.setEngaged(o),signalFieldError:o=>s.signalFieldError(o),getSignalsSnapshot:()=>s.getSnapshot(),getActiveNudge:()=>r.getActiveNudge(),shown:o=>r.shown(o),accept:o=>r.accept(o),dismiss:o=>r.dismiss(o),markConverted:o=>r.markConverted(o),destroy:()=>{r.stop(),n.destroy(),s.destroy(),e.removeDynamicContext(L),e.proactive===c&&(e.proactive=null)}};return e.proactive=c,c}var Q=class{constructor(){this.entries=new Map,this.dynamicProviders=new Map}set(e,t){this.entries.set(e,t),l.log(`ClientContext set: ${e}`)}remove(e){const t=this.entries.delete(e);return t&&l.log(`ClientContext removed: ${e}`),t}addDynamicProvider(e,t){this.dynamicProviders.set(e,t),l.log(`DynamicContext provider added: ${e}`)}removeDynamicProvider(e){const t=this.dynamicProviders.delete(e);return t&&l.log(`DynamicContext provider removed: ${e}`),t}getSnapshot(){if(this.entries.size===0&&this.dynamicProviders.size===0)return null;const e={};for(const[t,s]of this.entries)e[t]=s;for(const[t,s]of this.dynamicProviders)try{const i=s();i&&(e[t]=i)}catch(i){l.error(`DynamicContext provider "${t}" threw:`,i)}return Object.keys(e).length===0?null:{entries:e}}clear(){this.entries.clear(),this.dynamicProviders.clear(),l.log("ClientContext cleared")}},We="page-state:";function Ke(e){const t={};for(const[s,i]of Object.entries(e))s.startsWith(We)&&i.data&&Object.assign(t,i.data);return t}function He(e){const t=e["current-page"]?.data;return t?.page?t.page:t?.url?t.url:e["browser-page"]?.data?.url}function ze(e,t){return e===t?!0:JSON.stringify(e)===JSON.stringify(t)}function Je(e,t){const s=[];for(const i of Object.keys(t))i in e&&(ze(e[i],t[i])||s.push({field:i,from:e[i],to:t[i]}));return s}function Xe(e,t){const s=Ke(t),i=He(t);return{changes:e&&e.page===i?Je(e.state,s):[],baseline:{page:i,state:s}}}function F(e){return e===null||typeof e!="object"?JSON.stringify(e)??"null":Array.isArray(e)?`[${e.map(F).join(",")}]`:`{${Object.keys(e).sort().map(t=>`${JSON.stringify(t)}:${F(e[t])}`).join(",")}}`}var B="",Z=class{constructor(e,t={}){this.callbacks=e,this.options=t,this.buffer="",this.message={},this.toolCalls=[],this.sources=[],this.followUpReplies=[],this.isFirstChunk=!0,this.answerCompleteEmitted=!1,this.waitingClientEmitted=!1,this.firedClientFunctions=new Map}async processStream(e){if(!e.body)throw new _("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(),s=new TextDecoder;try{for(;;){const{done:i,value:n}=await t.read();if(i)break;const r=s.decode(n,{stream:!0});this.buffer+=r,this.processBuffer()}return this.buffer.trim()&&this.processBuffer(),this.buildFinalMessage()}catch(i){if(this.options.signal?.aborted)return this.message.status="CANCELED",this.buildFinalMessage();const n=i instanceof Error?i:new _("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 s=t.split(`
4
- `);for(const i of s)if(!i.startsWith(": ")&&i.startsWith("data: ")){const n=i.slice(6);try{const r=JSON.parse(n);this.handleChunk(r)}catch(r){l.warn("Failed to parse SSE data:",n,r)}}}}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 s=t.knowledge_document;return{id:s.id,title:s.title,url:s.use_external_link?s.external_link_url:s.internal_link_url}})),e.type==="client_function"&&e.function_name){const t=`${e.function_name}::${F(e.arguments??{})}`,s=e.id||"",i=this.firedClientFunctions.get(t);let n=!1;i?s&&!i.has(s)&&(i.has(B)?(i.delete(B),i.add(s)):(i.add(s),n=!0)):(this.firedClientFunctions.set(t,new Set([s])),n=!0),n&&this.callbacks.onClientFunction?.({invocationId:s,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 s=this.toolCalls.findIndex(i=>i.id===t.id);s>=0?this.toolCalls[s]=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 Ye(e){const t=e.message.toLowerCase();return t.includes("load failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("abort")}var Ve=new Set(["image/jpeg","image/png","image/gif","image/webp","image/bmp","image/tiff"]);function ee(e){if(!e)return;const t=typeof window<"u"&&window.location?window.location.href:"https://ago.local/";try{const s=new URL(e,t);if(s.protocol==="http:"||s.protocol==="https:"||s.protocol==="blob:")return e}catch{}}function Qe(e){return e.isSafeImage===!0&&typeof e.contentType=="string"&&e.contentType.startsWith("image/")&&ee(e.url)!==void 0}function Ze(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 et(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 tt(e){return e.map((t,s)=>({id:`local-${s}-${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:Ve.has(t.type)}))}var te=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 s=this.handlers.get(e);s&&s.delete(t)}emit(e,t){const s=this.handlers.get(e);s&&s.forEach(i=>{try{i(t)}catch(n){console.error(`Error in event handler for ${String(e)}:`,n)}})}once(e,t){const s=(i=>{this.off(e,s),t(i)});this.on(e,s)}waitFor(e,t){return new Promise((s,i)=>{let n;const r=(c=>{n&&clearTimeout(n),s(c)});this.once(e,r),t?.timeout&&(n=setTimeout(()=>{this.off(e,r),i(new Error(`waitFor("${String(e)}") timed out after ${t.timeout}ms`))},t.timeout))})}removeAllListeners(e){e?this.handlers.delete(e):this.handlers.clear()}},q='`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).',st=/^[a-z][a-z0-9+.-]*:\/\//i,G=!1;function O(e,t="AgoClient"){if(typeof e!="object"||e===null)throw new g(`${t}: ${q}`,"config_missing_base_url");const s=e.baseUrl;if(typeof s!="string"||s.trim()==="")throw new g(`${t}: ${q}`,"config_missing_base_url");!s.startsWith("/")&&!st.test(s)&&(G||(G=!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 it(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function A(e){return e.split("/").filter(t=>t.startsWith(":")).map(t=>t.slice(1))}function nt(e,t){const s=[];return{path:e.split("/").map(i=>{if(!i.startsWith(":"))return i;const n=i.slice(1),r=t[n];return r==null||r===""?(s.push(n),i):encodeURIComponent(String(r))}).join("/"),missing:s}}function rt(e,t){const s=t.find(n=>n.path===e);if(s)return s;const i=t.find(n=>{if(!n.path.includes(":"))return!1;const r="^"+n.path.split("/").map(c=>c.startsWith(":")?"[^/]+":it(c)).join("/")+"/?$";return new RegExp(r).test(e)});return i||t.filter(n=>n.path!=="/"&&e.startsWith(n.path)).sort((n,r)=>r.path.length-n.path.length)[0]}var ot="activity:recent",at="state:delta";function W(e){return e==="setPageState"?"readPageData":`read${e.charAt(0).toUpperCase()}${e.slice(1)}Data`}var ct=class se{constructor(t){this.lastSentPageState=null,this.warnedEmptyConversations=new Set,this.warnedPageDataPlaceholder=!1,this.pageDataCompanions=new Set,this.pendingResumes=new Map,this.pendingApprovals=new Map,this.resumeGate=null,this.activeTurn=null,this.pausedTurn=null,this.stoppedTurnIds=new Set,this.proactive=null,O(t,"AgoClient"),this.config=t,this.activityLedger=new K(t.maxActivityEntries),this.httpClient=new ce(t),this.functionRegistry=new z({maxResultBytes:t.maxFunctionResultBytes}),this.contextRegistry=new Q,this.eventEmitter=new te,this.registerActivityContext(),t.debug&&l.enable(),t.proactive&&P(this,t.proactive),l.log("AgoClient initialized")}async sendMessage(t,s){const i=this.functionRegistry.getSchemas(),n=this.buildSendContext(),r=this.config.agent||this.config.defaultAgentId,c=this.resolveClientFunctionsMode(s),o={content:t,conversation_id:s?.conversationId,agent_id:s?.agentId||r};i.length>0&&(o.client_functions=i,c==="pause"&&(o.client_functions_mode=c)),n&&(o.client_context=n),s?.hidden&&(o.hidden=!0);const a=this.beginTurn();let h;if(s?.files&&s.files.length>0){const u=new FormData;u.append("content",t),s.conversationId&&u.append("conversation_id",s.conversationId),(s.agentId||r)&&u.append("agent_id",s.agentId||r||""),i.length>0&&(u.append("client_functions",JSON.stringify(i)),c==="pause"&&u.append("client_functions_mode",c)),n&&u.append("client_context",JSON.stringify(n)),s.hidden&&u.append("hidden","true");for(const d of s.files)u.append("files",d);h=await this.sendRequest(a,()=>this.httpClient.postFormData("/api/sdk/v1/messages",u,{signal:a.controller.signal}))}else h=await this.sendRequest(a,()=>this.httpClient.postStream("/api/sdk/v1/messages",o,{signal:a.controller.signal}));return h?this.processSSEResponse(h,a):this.buildStoppedMessage(a)}async sendRequest(t,s){try{return await s()}catch(i){if(this.endTurn(t),R(i))return null;throw i}}async processSSEResponse(t,s){let i=!1;const n=new Z({onRawChunk:r=>{s&&(r.message_id&&!s.messageId&&(s.messageId=r.message_id),r.thread?.id&&(s.conversationId=r.thread.id)),this.eventEmitter.emit("stream:message",r)},onStart:r=>{this.eventEmitter.emit("message:start",r)},onChunk:r=>{this.eventEmitter.emit("message:chunk",r)},onToolCall:r=>{this.eventEmitter.emit("toolCall:received",r),r.type==="form"&&this.eventEmitter.emit("toolCall:form",r)},onClientFunction:async r=>{if(i=!0,this.eventEmitter.emit("function:invoke",r),this.recordAgentAction(r),r.invocationId&&this.requiresApproval(r)){this.pendingApprovals.set(r.invocationId,r),this.eventEmitter.emit("function:awaiting-approval",r);return}await this.handleClientFunctionInvocation(r)},onTitle:r=>{this.eventEmitter.emit("conversation:title",r)},onAnswerComplete:r=>{this.eventEmitter.emit("message:answer-complete",r)},onWaitingClient:r=>{this.pausedTurn={messageId:r.messageId,conversationId:r.conversationId},this.eventEmitter.emit("message:waiting-client",r),this.markResumeSignal(r.messageId,r.conversationId,"waitingConfirmed")},onComplete:r=>{s?.stopRequested&&!r.id||this.eventEmitter.emit("message:complete",r)},onError:r=>{this.eventEmitter.emit("message:error",{error:r.message,code:r instanceof g?r.code:void 0})}},{signal:s?.controller.signal});try{const r=await n.processStream(t);return s?.stopRequested&&(this.postStopForTurn(s,s.messageId??r.id),this.eventEmitter.emit("message:stopped",{conversationId:s.conversationId??r.conversationId??"",messageId:s.messageId??r.id??""})),r.status!=="WAITING_CLIENT"&&this.maybeFlagEmptyReply(r,i),r}finally{s&&this.endTurn(s)}}async stop(){const t=this.activeTurn;if(t){t.stopRequested=!0;const n=t.messageId;return t.controller.abort(),n?this.postStopForTurn(t,n):null}const s=this.pausedTurn;if(!s)return null;this.pausedTurn=null,this.pendingResumes.delete(s.messageId),this.stoppedTurnIds.add(s.messageId);let i=null;try{i=await this.stopMessage(s.messageId)}catch(n){l.warn("Failed to stop the paused turn:",n)}return this.eventEmitter.emit("message:stopped",{conversationId:s.conversationId,messageId:s.messageId}),i}async stopMessage(t){const s=await this.httpClient.post(`/api/sdk/v1/messages/${t}/stop`);return{status:s.status,messageStatus:s.message_status}}isGenerating(){return this.activeTurn!==null||this.pausedTurn!==null}beginTurn(){this.pausedTurn=null;const t={controller:new AbortController,messageId:null,conversationId:null,stopRequested:!1,stopPosted:!1};return this.activeTurn=t,t}endTurn(t){this.activeTurn===t&&(this.activeTurn=null)}async postStopForTurn(t,s){if(!s||t.stopPosted)return null;t.stopPosted=!0;try{return await this.stopMessage(s)}catch(i){return l.warn("Failed to stop the turn server-side:",i),null}}buildStoppedMessage(t){const s={id:t.messageId??"",conversationId:t.conversationId??"",content:"",role:"assistant",status:"CANCELED",createdAt:new Date};return s.id&&this.eventEmitter.emit("message:complete",s),this.eventEmitter.emit("message:stopped",{conversationId:s.conversationId,messageId:s.id}),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 s=this.functionRegistry.getSchemas(),i=this.buildSendContext(),n={};s.length>0&&(n.client_functions=s),i&&(n.client_context=i);const r=this.beginTurn();r.messageId=t;const c=await this.sendRequest(r,()=>this.httpClient.postStream(`/api/sdk/v1/messages/${t}/continue`,n,{signal:r.controller.signal}));return c?this.processSSEResponse(c,r):this.buildStoppedMessage(r)}markResumeSignal(t,s,i){if(!t)return;const n=this.pendingResumes.get(t)??{conversationId:s,waitingConfirmed:!1,resultsReady:!1,started:!1};n[i]=!0,s&&(n.conversationId=s),this.pendingResumes.set(t,n),!(!n.waitingConfirmed||!n.resultsReady||n.started)&&(n.started=!0,this.runAutoResume(t,n.conversationId))}async runAutoResume(t,s){try{this.resumeGate&&await this.resumeGate({conversationId:s,messageId:t})}catch(i){l.warn("Resume gate threw; resuming anyway:",i)}if(this.pendingResumes.delete(t),!this.stoppedTurnIds.delete(t))try{await this.continueMessage(t)}catch(i){l.warn("Auto-resume of paused turn failed:",i)}}maybeFlagEmptyReply(t,s){t.status==="DONE"&&(t.content??"").trim()===""&&!s&&!(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 i=t.conversationId||"(no conversation)";if(this.warnedEmptyConversations.has(i))return;this.warnedEmptyConversations.add(i);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 s,i;try{s=await this.functionRegistry.execute(t.functionName,t.arguments)}catch(n){i=n instanceof Error?n.message:"Unknown error",l.error("Client function execution failed:",n)}if(t.invocationId)try{const n=await this.submitToolCallForm(t.invocationId,{result:s,error:i,_type:"client_function_result"});n?.resume?.ready&&this.markResumeSignal(n.resume.message_id,t.conversationId,"resultsReady")}catch(n){l.error("Failed to submit function result:",n)}this.eventEmitter.emit("function:result",{invocationId:t.invocationId,result:s,error:i})}requiresApproval(t){const s=this.config.approvalPolicy;if(s)try{if(s(t))return!0}catch(i){l.warn("approvalPolicy threw; not gating this call:",i)}return this.functionRegistry.get(t.functionName)?.requiresApproval===!0}async approveFunction(t){const s=this.pendingApprovals.get(t);s&&(this.pendingApprovals.delete(t),await this.handleClientFunctionInvocation(s))}async rejectFunction(t){const s=this.pendingApprovals.get(t);if(!s)return;this.pendingApprovals.delete(t);const i={approved:!1,reason:"user_rejected"};try{const n=await this.submitToolCallForm(t,{result:i,_type:"client_function_result"});n?.resume?.ready&&this.markResumeSignal(n.resume.message_id,s.conversationId,"resultsReady")}catch(n){l.error("Failed to submit function rejection:",n)}this.eventEmitter.emit("function:result",{invocationId:t,result:i})}async getConversations(t){const s=new URLSearchParams;t?.page!==void 0&&s.set("page",String(t.page)),t?.pageSize!==void 0&&s.set("page_size",String(t.pageSize));const i=s.toString(),n=await this.httpClient.get(`/api/sdk/v1/conversations${i?`?${i}`:""}`),r=(Array.isArray(n.data)?n.data:[]).map(c=>({id:String(c.id),title:c.title??"",lastMessageDate:new Date(c.last_message_at??c.created_at??0)}));return{data:r,hasMore:n.has_more??!1,total:n.total??r.length}}async getConversation(t){const s=await this.httpClient.get(`/api/sdk/v1/conversations/${t}`),i={id:s.id,title:s.title,lastMessageDate:new Date(s.last_message_at??s.created_at??0),messages:s.messages.map(n=>({id:n.id,conversationId:s.id,content:n.content,role:n.role,status:n.status,createdAt:new Date(n.created_at),hidden:n.hidden,toolCalls:se.mapPersistedToolCalls(n.tool_call_data),attachments:n.attachments&&n.attachments.length>0?n.attachments.map(et):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",i),i}static mapPersistedToolCalls(t){if(!(!t||t.length===0))return t.map(s=>({id:String(s.id??""),type:s.type??"status_message",status:String(s.status??"unknown"),toolName:s.tool_name??"",toolDisplayName:s.tool_display_name,message:s.message,formSchema:s.form_schema,data:s.data,functionName:s.function_name,arguments:s.arguments}))}async getMessages(t){return(await this.getConversation(t)).messages||[]}async resumePendingClientFunctions(t){const s=[...t.messages??[]].reverse().find(o=>o.role==="assistant"&&o.status==="WAITING_CLIENT");if(!s)return null;const i=(s.toolCalls??[]).filter(o=>o.type==="client_function"&&o.status==="waiting_input"&&o.functionName),n=new Set(this.functionRegistry.getSchemas().map(o=>o.name)),r=i.filter(o=>!n.has(o.functionName));if(r.length>0)return l.warn("Cannot resume paused turn: function(s) not registered on this page:",r.map(o=>o.functionName)),null;let c=i.length===0;for(const o of i){const a={invocationId:o.id,functionName:o.functionName,arguments:o.arguments??{},conversationId:t.id};if(this.requiresApproval(a)){this.pendingApprovals.set(o.id,a),this.markResumeSignal(s.id,t.id,"waitingConfirmed"),this.eventEmitter.emit("function:awaiting-approval",a),c=!1;continue}this.eventEmitter.emit("function:invoke",a);let h,u;try{h=await this.functionRegistry.execute(o.functionName,o.arguments??{})}catch(d){u=d instanceof Error?d.message:"Unknown error",l.error("Client function execution failed:",d)}this.eventEmitter.emit("function:result",{invocationId:o.id,result:h,error:u}),c=(await this.submitToolCallForm(o.id,{result:h,error:u,_type:"client_function_result"}))?.resume?.ready??c}return c?this.continueMessage(s.id):null}async submitToolCallForm(t,s){return this.httpClient.post(`/api/sdk/v1/tool-calls/${t}/submit`,{formData:s})}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 s=await this.httpClient.get(`/api/sdk/v1/forms/${encodeURIComponent(t)}`);return{name:s.name,description:s.description,schema:s.schema,submit:s.submit??void 0}}async submitFormCollector(t,s){return this.httpClient.post("/api/sdk/v1/forms/submit",{name:t,values:s})}async submitFeedback(t,s){await this.httpClient.post(`/api/sdk/v1/messages/${t}/feedback`,{rating:s})}registerFunction(t,s,i){typeof t=="object"?this.functionRegistry.register(t):this.functionRegistry.register(t,s,i)}register(t){if(Array.isArray(t))for(const s of t)this.functionRegistry.register(s);else this.functionRegistry.register(t)}unregisterFunction(t){return this.functionRegistry.unregister(t)}getRegisteredFunctions(){return this.functionRegistry.getSchemas()}async executeClientFunction(t,s){return this.functionRegistry.execute(t,s)}registerNavigationFunction(t,s){const i=s.map(o=>o.name),n=s.map(o=>{const a=A(o.path),h=a.length>0?` (requires ${a.map(u=>`"${u}"`).join(", ")})`:"";return`- "${o.name}"${h}: ${o.description}`}).join(`
4
+ `);for(const i of s)if(!i.startsWith(": ")&&i.startsWith("data: ")){const n=i.slice(6);try{const r=JSON.parse(n);this.handleChunk(r)}catch(r){l.warn("Failed to parse SSE data:",n,r)}}}}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 s=t.knowledge_document;return{id:s.id,title:s.title,url:s.use_external_link?s.external_link_url:s.internal_link_url}})),e.type==="client_function"&&e.function_name){const t=`${e.function_name}::${F(e.arguments??{})}`,s=e.id||"",i=this.firedClientFunctions.get(t);let n=!1;i?s&&!i.has(s)&&(i.has(B)?(i.delete(B),i.add(s)):(i.add(s),n=!0)):(this.firedClientFunctions.set(t,new Set([s])),n=!0),n&&this.callbacks.onClientFunction?.({invocationId:s,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 s=this.toolCalls.findIndex(i=>i.id===t.id);s>=0?this.toolCalls[s]=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 Ye(e){const t=e.message.toLowerCase();return t.includes("load failed")||t.includes("failed to fetch")||t.includes("network")||t.includes("abort")}var Ve=new Set(["image/jpeg","image/png","image/gif","image/webp","image/bmp","image/tiff"]);function ee(e){if(!e)return;const t=typeof window<"u"&&window.location?window.location.href:"https://ago.local/";try{const s=new URL(e,t);if(s.protocol==="http:"||s.protocol==="https:"||s.protocol==="blob:")return e}catch{}}function Qe(e){return e.isSafeImage===!0&&typeof e.contentType=="string"&&e.contentType.startsWith("image/")&&ee(e.url)!==void 0}function Ze(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 et(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 tt(e){return e.map((t,s)=>({id:`local-${s}-${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:Ve.has(t.type)}))}var te=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 s=this.handlers.get(e);s&&s.delete(t)}emit(e,t){const s=this.handlers.get(e);s&&s.forEach(i=>{try{i(t)}catch(n){console.error(`Error in event handler for ${String(e)}:`,n)}})}once(e,t){const s=(i=>{this.off(e,s),t(i)});this.on(e,s)}waitFor(e,t){return new Promise((s,i)=>{let n;const r=(c=>{n&&clearTimeout(n),s(c)});this.once(e,r),t?.timeout&&(n=setTimeout(()=>{this.off(e,r),i(new Error(`waitFor("${String(e)}") timed out after ${t.timeout}ms`))},t.timeout))})}removeAllListeners(e){e?this.handlers.delete(e):this.handlers.clear()}},q='`baseUrl` is required, e.g. new AgoClient({ baseUrl: "https://YOUR-DOMAIN.api.useago.com" }). Try the public demo account https://playground.api.useago.com (agent generic-guide). See docs/general/configuration.md#error-codes (config_missing_base_url).',st=/^[a-z][a-z0-9+.-]*:\/\//i,G=!1;function O(e,t="AgoClient"){if(typeof e!="object"||e===null)throw new g(`${t}: ${q}`,"config_missing_base_url");const s=e.baseUrl;if(typeof s!="string"||s.trim()==="")throw new g(`${t}: ${q}`,"config_missing_base_url");!s.startsWith("/")&&!st.test(s)&&(G||(G=!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 it(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function A(e){return e.split("/").filter(t=>t.startsWith(":")).map(t=>t.slice(1))}function nt(e,t){const s=[];return{path:e.split("/").map(i=>{if(!i.startsWith(":"))return i;const n=i.slice(1),r=t[n];return r==null||r===""?(s.push(n),i):encodeURIComponent(String(r))}).join("/"),missing:s}}function rt(e,t){const s=t.find(n=>n.path===e);if(s)return s;const i=t.find(n=>{if(!n.path.includes(":"))return!1;const r="^"+n.path.split("/").map(c=>c.startsWith(":")?"[^/]+":it(c)).join("/")+"/?$";return new RegExp(r).test(e)});return i||t.filter(n=>n.path!=="/"&&e.startsWith(n.path)).sort((n,r)=>r.path.length-n.path.length)[0]}var ot="activity:recent",at="state:delta";function W(e){return e==="setPageState"?"readPageData":`read${e.charAt(0).toUpperCase()}${e.slice(1)}Data`}var ct=class se{constructor(t){this.lastSentPageState=null,this.warnedEmptyConversations=new Set,this.warnedPageDataPlaceholder=!1,this.pageDataCompanions=new Set,this.pendingResumes=new Map,this.pendingApprovals=new Map,this.resumeGate=null,this.activeTurn=null,this.pausedTurn=null,this.stoppedTurnIds=new Set,this.proactive=null,O(t,"AgoClient"),this.config=t,this.activityLedger=new K(t.maxActivityEntries),this.httpClient=new ce(t),this.functionRegistry=new z({maxResultBytes:t.maxFunctionResultBytes}),this.contextRegistry=new Q,this.eventEmitter=new te,this.registerActivityContext(),t.debug&&l.enable(),t.proactive&&P(this,t.proactive),l.log("AgoClient initialized")}async sendMessage(t,s){const i=this.functionRegistry.getSchemas(),n=this.buildSendContext(),r=this.config.agent||this.config.defaultAgentId,c=this.resolveClientFunctionsMode(s),o={content:t,conversation_id:s?.conversationId,agent_id:s?.agentId||r};i.length>0&&(o.client_functions=i,c==="pause"&&(o.client_functions_mode=c)),n&&(o.client_context=n),s?.hidden&&(o.hidden=!0);const a=this.beginTurn();let h;if(s?.files&&s.files.length>0){const u=new FormData;u.append("content",t),s.conversationId&&u.append("conversation_id",s.conversationId),(s.agentId||r)&&u.append("agent_id",s.agentId||r||""),i.length>0&&(u.append("client_functions",JSON.stringify(i)),c==="pause"&&u.append("client_functions_mode",c)),n&&u.append("client_context",JSON.stringify(n)),s.hidden&&u.append("hidden","true");for(const d of s.files)u.append("files",d);h=await this.sendRequest(a,()=>this.httpClient.postFormData("/api/sdk/v1/messages",u,{signal:a.controller.signal}))}else h=await this.sendRequest(a,()=>this.httpClient.postStream("/api/sdk/v1/messages",o,{signal:a.controller.signal}));return h?this.processSSEResponse(h,a):this.buildStoppedMessage(a)}async sendRequest(t,s){try{return await s()}catch(i){if(this.endTurn(t),R(i))return null;throw i}}async processSSEResponse(t,s){let i=!1;const n=new Z({onRawChunk:r=>{s&&(r.message_id&&!s.messageId&&(s.messageId=r.message_id),r.thread?.id&&(s.conversationId=r.thread.id)),this.eventEmitter.emit("stream:message",r)},onStart:r=>{this.eventEmitter.emit("message:start",r)},onChunk:r=>{this.eventEmitter.emit("message:chunk",r)},onToolCall:r=>{this.eventEmitter.emit("toolCall:received",r),r.type==="form"&&this.eventEmitter.emit("toolCall:form",r)},onClientFunction:async r=>{if(i=!0,this.eventEmitter.emit("function:invoke",r),this.recordAgentAction(r),r.invocationId&&this.requiresApproval(r)){this.pendingApprovals.set(r.invocationId,r),this.eventEmitter.emit("function:awaiting-approval",r);return}await this.handleClientFunctionInvocation(r)},onTitle:r=>{this.eventEmitter.emit("conversation:title",r)},onAnswerComplete:r=>{this.eventEmitter.emit("message:answer-complete",r)},onWaitingClient:r=>{this.pausedTurn={messageId:r.messageId,conversationId:r.conversationId},this.eventEmitter.emit("message:waiting-client",r),this.markResumeSignal(r.messageId,r.conversationId,"waitingConfirmed")},onComplete:r=>{s?.stopRequested&&!r.id||this.eventEmitter.emit("message:complete",r)},onError:r=>{this.eventEmitter.emit("message:error",{error:r.message,code:r instanceof g?r.code:void 0})}},{signal:s?.controller.signal});try{const r=await n.processStream(t);return s?.stopRequested&&(this.postStopForTurn(s,s.messageId??r.id),this.eventEmitter.emit("message:stopped",{conversationId:s.conversationId??r.conversationId??"",messageId:s.messageId??r.id??""})),r.status!=="WAITING_CLIENT"&&this.maybeFlagEmptyReply(r,i),r}finally{s&&this.endTurn(s)}}async stop(){const t=this.activeTurn;if(t){t.stopRequested=!0;const n=t.messageId;return t.controller.abort(),n?this.postStopForTurn(t,n):null}const s=this.pausedTurn;if(!s)return null;this.pausedTurn=null,this.pendingResumes.delete(s.messageId),this.stoppedTurnIds.add(s.messageId);let i=null;try{i=await this.stopMessage(s.messageId)}catch(n){l.warn("Failed to stop the paused turn:",n)}return this.eventEmitter.emit("message:stopped",{conversationId:s.conversationId,messageId:s.messageId}),i}async stopMessage(t){const s=await this.httpClient.post(`/api/sdk/v1/messages/${t}/stop`);return{status:s.status,messageStatus:s.message_status}}isGenerating(){return this.activeTurn!==null||this.pausedTurn!==null}beginTurn(){this.pausedTurn=null;const t={controller:new AbortController,messageId:null,conversationId:null,stopRequested:!1,stopPosted:!1};return this.activeTurn=t,t}endTurn(t){this.activeTurn===t&&(this.activeTurn=null)}async postStopForTurn(t,s){if(!s||t.stopPosted)return null;t.stopPosted=!0;try{return await this.stopMessage(s)}catch(i){return l.warn("Failed to stop the turn server-side:",i),null}}buildStoppedMessage(t){const s={id:t.messageId??"",conversationId:t.conversationId??"",content:"",role:"assistant",status:"CANCELED",createdAt:new Date};return s.id&&this.eventEmitter.emit("message:complete",s),this.eventEmitter.emit("message:stopped",{conversationId:s.conversationId,messageId:s.id}),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 s=this.functionRegistry.getSchemas(),i=this.buildSendContext(),n={};s.length>0&&(n.client_functions=s),i&&(n.client_context=i);const r=this.beginTurn();r.messageId=t;const c=await this.sendRequest(r,()=>this.httpClient.postStream(`/api/sdk/v1/messages/${t}/continue`,n,{signal:r.controller.signal}));return c?this.processSSEResponse(c,r):this.buildStoppedMessage(r)}markResumeSignal(t,s,i){if(!t)return;const n=this.pendingResumes.get(t)??{conversationId:s,waitingConfirmed:!1,resultsReady:!1,started:!1};n[i]=!0,s&&(n.conversationId=s),this.pendingResumes.set(t,n),!(!n.waitingConfirmed||!n.resultsReady||n.started)&&(n.started=!0,this.runAutoResume(t,n.conversationId))}async runAutoResume(t,s){try{this.resumeGate&&await this.resumeGate({conversationId:s,messageId:t})}catch(i){l.warn("Resume gate threw; resuming anyway:",i)}if(this.pendingResumes.delete(t),!this.stoppedTurnIds.delete(t))try{await this.continueMessage(t)}catch(i){l.warn("Auto-resume of paused turn failed:",i)}}maybeFlagEmptyReply(t,s){t.status==="DONE"&&(t.content??"").trim()===""&&!s&&!(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 i=t.conversationId||"(no conversation)";if(this.warnedEmptyConversations.has(i))return;this.warnedEmptyConversations.add(i);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 s,i;try{s=await this.functionRegistry.execute(t.functionName,t.arguments)}catch(n){i=n instanceof Error?n.message:"Unknown error",l.error("Client function execution failed:",n)}if(t.invocationId)try{const n=await this.submitToolCallForm(t.invocationId,{result:s,error:i,_type:"client_function_result"});n?.resume?.ready&&this.markResumeSignal(n.resume.message_id,t.conversationId,"resultsReady")}catch(n){l.error("Failed to submit function result:",n)}this.eventEmitter.emit("function:result",{invocationId:t.invocationId,result:s,error:i})}requiresApproval(t){const s=this.config.approvalPolicy;if(s)try{if(s(t))return!0}catch(i){l.warn("approvalPolicy threw; not gating this call:",i)}return this.functionRegistry.get(t.functionName)?.requiresApproval===!0}async approveFunction(t){const s=this.pendingApprovals.get(t);s&&(this.pendingApprovals.delete(t),await this.handleClientFunctionInvocation(s))}async rejectFunction(t){const s=this.pendingApprovals.get(t);if(!s)return;this.pendingApprovals.delete(t);const i={approved:!1,reason:"user_rejected"};try{const n=await this.submitToolCallForm(t,{result:i,_type:"client_function_result"});n?.resume?.ready&&this.markResumeSignal(n.resume.message_id,s.conversationId,"resultsReady")}catch(n){l.error("Failed to submit function rejection:",n)}this.eventEmitter.emit("function:result",{invocationId:t,result:i})}async getConversations(t){const s=new URLSearchParams;t?.page!==void 0&&s.set("page",String(t.page)),t?.pageSize!==void 0&&s.set("page_size",String(t.pageSize));const i=s.toString(),n=await this.httpClient.get(`/api/sdk/v1/conversations${i?`?${i}`:""}`),r=(Array.isArray(n.data)?n.data:[]).map(c=>({id:String(c.id),title:c.title??"",lastMessageDate:new Date(c.last_message_at??c.created_at??0)}));return{data:r,hasMore:n.has_more??!1,total:n.total??r.length}}async getConversation(t){const s=await this.httpClient.get(`/api/sdk/v1/conversations/${t}`),i={id:s.id,title:s.title,lastMessageDate:new Date(s.last_message_at??s.created_at??0),messages:s.messages.map(n=>({id:n.id,conversationId:s.id,content:n.content,role:n.role,status:n.status,createdAt:new Date(n.created_at),hidden:n.hidden,toolCalls:se.mapPersistedToolCalls(n.tool_call_data),attachments:n.attachments&&n.attachments.length>0?n.attachments.map(et):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",i),i}static mapPersistedToolCalls(t){if(!(!t||t.length===0))return t.map(s=>({id:String(s.id??""),type:s.type??"status_message",status:String(s.status??"unknown"),toolName:s.tool_name??"",toolDisplayName:s.tool_display_name,message:s.message,formSchema:s.form_schema,data:s.data,functionName:s.function_name,arguments:s.arguments}))}async getMessages(t){return(await this.getConversation(t)).messages||[]}async resumePendingClientFunctions(t){const s=[...t.messages??[]].reverse().find(o=>o.role==="assistant"&&o.status==="WAITING_CLIENT");if(!s)return null;const i=(s.toolCalls??[]).filter(o=>o.type==="client_function"&&o.status==="waiting_input"&&o.functionName),n=new Set(this.functionRegistry.getSchemas().map(o=>o.name)),r=i.filter(o=>!n.has(o.functionName));if(r.length>0)return l.warn("Cannot resume paused turn: function(s) not registered on this page:",r.map(o=>o.functionName)),null;let c=i.length===0;for(const o of i){const a={invocationId:o.id,functionName:o.functionName,arguments:o.arguments??{},conversationId:t.id};if(this.requiresApproval(a)){this.pendingApprovals.set(o.id,a),this.markResumeSignal(s.id,t.id,"waitingConfirmed"),this.eventEmitter.emit("function:awaiting-approval",a),c=!1;continue}this.eventEmitter.emit("function:invoke",a);let h,u;try{h=await this.functionRegistry.execute(o.functionName,o.arguments??{})}catch(d){u=d instanceof Error?d.message:"Unknown error",l.error("Client function execution failed:",d)}this.eventEmitter.emit("function:result",{invocationId:o.id,result:h,error:u}),c=(await this.submitToolCallForm(o.id,{result:h,error:u,_type:"client_function_result"}))?.resume?.ready??c}return c?this.continueMessage(s.id):null}async submitToolCallForm(t,s){return this.httpClient.post(`/api/sdk/v1/tool-calls/${t}/submit`,{formData:s})}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 s=await this.httpClient.get(`/api/sdk/v1/forms/${encodeURIComponent(t)}`);return{name:s.name,description:s.description,schema:s.schema,submit:s.submit??void 0}}async submitFormCollector(t,s){return this.httpClient.post("/api/sdk/v1/forms/submit",{name:t,values:s})}async submitFeedback(t,s){await this.httpClient.post(`/api/sdk/v1/messages/${t}/feedback`,{rating:s})}registerFunction(t,s,i){typeof t=="object"?this.functionRegistry.register(t):this.functionRegistry.register(t,s,i)}register(t){if(Array.isArray(t))for(const s of t)this.functionRegistry.register(s);else this.functionRegistry.register(t)}unregisterFunction(t){return this.functionRegistry.unregister(t)}getRegisteredFunctions(){return this.functionRegistry.getSchemas()}async executeClientFunction(t,s){return this.functionRegistry.execute(t,s)}registerNavigationFunction(t,s){const i=s.map(o=>o.name),n=s.map(o=>{const a=A(o.path),h=a.length>0?` (requires ${a.map(u=>`"${u}"`).join(", ")})`:"";return`- "${o.name}"${h}: ${o.description}`}).join(`
5
5
  `),r=new Map;for(const o of s)for(const a of A(o.path))r.set(a,[...r.get(a)??[],o.name]);const c={page:{type:"string",description:"The page to navigate to",enum:i}};for(const[o,a]of r){if(o==="page"){l.error('registerNavigationFunction: a ":page" placeholder collides with the "page" argument and is ignored. Rename the placeholder.');continue}c[o]={type:"string",description:`Value for ":${o}" in the page path. Required when page is ${a.map(h=>`"${h}"`).join(" or ")}.`}}this.registerFunction("navigateToPage",async o=>{const a=o.page,h=s.find(p=>p.name===a);if(!h)return{success:!1,error:`Unknown page: ${a}`};let u={};if(typeof o.params=="string")try{u=JSON.parse(o.params)}catch{}else o.params&&typeof o.params=="object"&&(u=o.params);const d={};for(const p of A(h.path))d[p]=o[p]??u[p];const{path:f,missing:C}=nt(h.path,d);if(C.length>0){const p=C.map(S=>`"${S}": "..."`).join(", ");return{success:!1,error:`Page "${a}" needs ${C.map(S=>`"${S}"`).join(", ")}. Retry with { "page": "${a}", ${p} }.`}}return t(f),{success:!0,navigatedTo:f}},{description:`Navigate the user to a page in the application. Available pages:
6
6
  ${n}`,parameters:{type:"object",properties:c,required:["page"]}}),this.addDynamicContext("current-page",()=>{if(typeof window>"u"||!window.location)return null;const o=window.location.href,a=typeof document<"u"?document.title:void 0,h=rt(window.location.pathname,s),u={url:o};return h&&(u.page=h.name),a&&(u.title=a),{name:"Current page",description:"The page the user is currently viewing.",data:u}})}unregisterNavigationFunction(){this.unregisterFunction("navigateToPage"),this.removeDynamicContext("current-page")}registerPageStateFunction(t,s){const i=s?.functionName??"setPageState",n=new Map(t.map(a=>[a.name,a])),r=s?.data,c=t.map(a=>`- "${a.name}": ${a.description}`).join(`
7
7
  `);this.registerFunction(i,async a=>{const h={};for(const[u,d]of Object.entries(a)){if(d===void 0)continue;const f=n.get(u);f&&(await f.set(d),h[u]=d)}return r?{success:!0,applied:h,data:U(i,await this.readPageData(i,r,s),this.pageDataBudget(r)-this.envelopeBytes({success:!0,applied:h}))}:{success:!0,applied:h}},{description:`Change the state of the current page. Set ONLY the controls the user explicitly asked for; leave the others unset. Available controls:
@@ -1232,7 +1232,7 @@ var Yt = class {
1232
1232
  removeAllListeners(t) {
1233
1233
  t ? this.handlers.delete(t) : this.handlers.clear();
1234
1234
  }
1235
- }, j = '`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).', Vt = /^[a-z][a-z0-9+.-]*:\/\//i, B = !1;
1235
+ }, j = '`baseUrl` is required, e.g. new AgoClient({ baseUrl: "https://YOUR-DOMAIN.api.useago.com" }). Try the public demo account https://playground.api.useago.com (agent generic-guide). See docs/general/configuration.md#error-codes (config_missing_base_url).', Vt = /^[a-z][a-z0-9+.-]*:\/\//i, B = !1;
1236
1236
  function q(t, e = "AgoClient") {
1237
1237
  if (typeof t != "object" || t === null) throw new g(`${e}: ${j}`, "config_missing_base_url");
1238
1238
  const s = t.baseUrl;
package/dist/angular.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const o=require("./AgoClient-B_u_d-XS.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 s=r=>{i.next?.(r)};return e.on(t,s),{unsubscribe:()=>e.off(t,s)}}}}sendMessage(t,e){return this.client.sendMessage(t,e)}stop(){return this.client.stop()}stopMessage(t){return this.client.stopMessage(t)}isGenerating(){return this.client.isGenerating()}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-7yXQ6R3O.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 s=r=>{i.next?.(r)};return e.on(t,s),{unsubscribe:()=>e.off(t,s)}}}}sendMessage(t,e){return this.client.sendMessage(t,e)}stop(){return this.client.stop()}stopMessage(t){return this.client.stopMessage(t)}isGenerating(){return this.client.isGenerating()}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-BJjLTOw4.js";
1
+ import { t as o } from "./AgoClient-DTkBRGFE.js";
2
2
  import { t as c } from "./autoContinue-CC8K9mBU.js";
3
3
  var s = class {
4
4
  constructor(t) {
@@ -1 +1 @@
1
- const d=require("./AgoClient-B_u_d-XS.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-7yXQ6R3O.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,4 +1,4 @@
1
- import { h as d } from "./AgoClient-BJjLTOw4.js";
1
+ import { h as d } from "./AgoClient-DTkBRGFE.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,4 +1,4 @@
1
- import { h as R, v as w } from "./AgoClient-BJjLTOw4.js";
1
+ import { h as R, v as w } from "./AgoClient-DTkBRGFE.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));
@@ -1 +1 @@
1
- const C=require("./AgoClient-B_u_d-XS.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-7yXQ6R3O.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}});
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./AgoClient-B_u_d-XS.cjs"),p=require("./autoContinue-CP9pJR-V.cjs"),E=require("./createConversationSession-BCdwAhLF.cjs"),f=require("./createFormCollector-ssBP8u0p.cjs"),S=require("./createMockClient-BSNuN3ys.cjs");require("./testing.cjs");const g=require("./functions-CPs7omgM.cjs");function w(e){return e}function y(e,o){return e.on("message:complete",o),()=>e.off("message:complete",o)}function v(e,o){return e.on("message:chunk",o),()=>e.off("message:chunk",o)}function F(e,o){return e.on("message:start",o),()=>e.off("message:start",o)}function b(e,o){return e.on("message:error",o),()=>e.off("message:error",o)}function M(e,o){return e.on("toolCall:received",o),()=>e.off("toolCall:received",o)}function T(e,o){return e.on("form:submitted",o),()=>e.off("form:submitted",o)}function q(e,o){return e.on("form:error",o),()=>e.off("form:error",o)}function I(e,o){return e.on("function:invoke",o),()=>e.off("function:invoke",o)}async function*_(e,o,l){const i=[];let n=null,a=!1;const c=s=>{i.push(s),n?.()},m=s=>c({type:"start",data:s}),r=s=>c({type:"chunk",data:s}),u=s=>{c({type:"complete",data:s}),a=!0,n?.()},d=s=>{c({type:"error",data:s}),a=!0,n?.()},A=s=>c({type:"toolCall",data:s}),h=()=>{a=!0,n?.()};e.on("message:start",m),e.on("message:chunk",r),e.on("message:complete",u),e.on("message:error",d),e.on("message:stopped",h),e.on("toolCall:received",A),e.sendMessage(o,l).catch(()=>{a=!0,n?.()});try{for(;!a||i.length>0;)i.length>0?yield i.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("message:stopped",h),e.off("toolCall:received",A)}}function C(e){let o,l,i,n,a,c;if(typeof window<"u"&&window.AGO){const r=window.AGO;o=r.basepath,l=r.widgetId,i=r.agent||r.defaultAgent,n=r.permission,a=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"),i=i||r("ago-agent")||r("ago-agent-id"),n=n||r("ago-permission"),a=a||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,i=i||u.getAttribute("data-ago-agent")||u.getAttribute("data-ago-agent-id")||void 0,n=n||u.getAttribute("data-ago-permission")||void 0,a=a||u.getAttribute("data-ago-user-email")||void 0)}o=e?.baseUrl||o,l=e?.widgetId||l,i=e?.agent||e?.defaultAgentId||i,n=e?.permission||n,a=e?.userEmail||a,c=e?.userJwt||c;const m=e?.debug;return o?{baseUrl:o,widgetId:l,agent:i,permission:n,userEmail:a,userJwt:c,debug:m}:null}function k(e){const o=C(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 U(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=p.attachAutoContinueAfterNavigation;exports.autoDetectConfig=C;exports.canInlineImage=t.canInlineImage;exports.copyToClipboard=g.copyToClipboard;exports.createAgo=k;exports.createAgoProactive=t.createAgoProactive;exports.createConversationSession=E.createConversationSession;exports.createFormCollector=f.createFormCollector;exports.createMessageStream=_;exports.createMockClient=S.createMockClient;exports.createStore=t.createStore;exports.defineFunction=w;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=q;exports.onFormSubmitted=T;exports.onFunctionInvoke=I;exports.onMessage=y;exports.onMessageChunk=v;exports.onMessageError=b;exports.onMessageStart=F;exports.onToolCall=M;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=U;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("./AgoClient-7yXQ6R3O.cjs"),p=require("./autoContinue-CP9pJR-V.cjs"),E=require("./createConversationSession-Bv6a15E0.cjs"),f=require("./createFormCollector-CwfiYn0V.cjs"),S=require("./createMockClient-BSNuN3ys.cjs");require("./testing.cjs");const g=require("./functions-CPs7omgM.cjs");function w(e){return e}function y(e,o){return e.on("message:complete",o),()=>e.off("message:complete",o)}function v(e,o){return e.on("message:chunk",o),()=>e.off("message:chunk",o)}function F(e,o){return e.on("message:start",o),()=>e.off("message:start",o)}function b(e,o){return e.on("message:error",o),()=>e.off("message:error",o)}function M(e,o){return e.on("toolCall:received",o),()=>e.off("toolCall:received",o)}function T(e,o){return e.on("form:submitted",o),()=>e.off("form:submitted",o)}function q(e,o){return e.on("form:error",o),()=>e.off("form:error",o)}function I(e,o){return e.on("function:invoke",o),()=>e.off("function:invoke",o)}async function*_(e,o,l){const i=[];let n=null,a=!1;const c=s=>{i.push(s),n?.()},m=s=>c({type:"start",data:s}),r=s=>c({type:"chunk",data:s}),u=s=>{c({type:"complete",data:s}),a=!0,n?.()},d=s=>{c({type:"error",data:s}),a=!0,n?.()},A=s=>c({type:"toolCall",data:s}),h=()=>{a=!0,n?.()};e.on("message:start",m),e.on("message:chunk",r),e.on("message:complete",u),e.on("message:error",d),e.on("message:stopped",h),e.on("toolCall:received",A),e.sendMessage(o,l).catch(()=>{a=!0,n?.()});try{for(;!a||i.length>0;)i.length>0?yield i.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("message:stopped",h),e.off("toolCall:received",A)}}function C(e){let o,l,i,n,a,c;if(typeof window<"u"&&window.AGO){const r=window.AGO;o=r.basepath,l=r.widgetId,i=r.agent||r.defaultAgent,n=r.permission,a=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"),i=i||r("ago-agent")||r("ago-agent-id"),n=n||r("ago-permission"),a=a||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,i=i||u.getAttribute("data-ago-agent")||u.getAttribute("data-ago-agent-id")||void 0,n=n||u.getAttribute("data-ago-permission")||void 0,a=a||u.getAttribute("data-ago-user-email")||void 0)}o=e?.baseUrl||o,l=e?.widgetId||l,i=e?.agent||e?.defaultAgentId||i,n=e?.permission||n,a=e?.userEmail||a,c=e?.userJwt||c;const m=e?.debug;return o?{baseUrl:o,widgetId:l,agent:i,permission:n,userEmail:a,userJwt:c,debug:m}:null}function k(e){const o=C(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 U(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=p.attachAutoContinueAfterNavigation;exports.autoDetectConfig=C;exports.canInlineImage=t.canInlineImage;exports.copyToClipboard=g.copyToClipboard;exports.createAgo=k;exports.createAgoProactive=t.createAgoProactive;exports.createConversationSession=E.createConversationSession;exports.createFormCollector=f.createFormCollector;exports.createMessageStream=_;exports.createMockClient=S.createMockClient;exports.createStore=t.createStore;exports.defineFunction=w;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=q;exports.onFormSubmitted=T;exports.onFunctionInvoke=I;exports.onMessage=y;exports.onMessageChunk=v;exports.onMessageError=b;exports.onMessageStart=F;exports.onToolCall=M;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=U;
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import { a as w, c as C, d as y, f as S, i as E, l as b, m as v, o as F, p as T, r as I, s as M, t as U, u as _ } from "./functions-tzyOZNp6.js";
2
- import { C as L, S as N, T as x, _ as D, a as G, b as c, c as O, d as R, f as q, g as P, h as H, l as J, m as j, n as z, o as B, p as V, r as W, s as X, t as p, u as Y, v as $, w as K, x as Q, y as Z } from "./AgoClient-BJjLTOw4.js";
2
+ import { C as L, S as N, T as x, _ as D, a as G, b as c, c as O, d as R, f as q, g as P, h as H, l as J, m as j, n as z, o as B, p as V, r as W, s as X, t as p, u as Y, v as $, w as K, x as Q, y as Z } from "./AgoClient-DTkBRGFE.js";
3
3
  import { t as oe } from "./autoContinue-CC8K9mBU.js";
4
- import { t as re } from "./createConversationSession-Bgvx753t.js";
5
- import { n as ne, r as se, t as ie } from "./createFormCollector-CM3qjGcM.js";
4
+ import { t as re } from "./createConversationSession-DP90nY71.js";
5
+ import { n as ne, r as se, t as ie } from "./createFormCollector-BivHRIAe.js";
6
6
  import { t as ge } from "./createMockClient-BDLW6tVc.js";
7
7
  import "./testing.js";
8
8
  function me(e) {
package/dist/react.cjs CHANGED
@@ -1,4 +1,4 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var Pe=Object.create,G=Object.defineProperty,We=Object.getOwnPropertyDescriptor,Oe=Object.getOwnPropertyNames,ze=Object.getPrototypeOf,De=Object.prototype.hasOwnProperty,Le=(e,n)=>{let t={};for(var o in e)G(t,o,{get:e[o],enumerable:!0});return n||G(t,Symbol.toStringTag,{value:"Module"}),t},He=(e,n,t,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(var r=Oe(n),c=0,i=r.length,l;c<i;c++)l=r[c],!De.call(e,l)&&l!==t&&G(e,l,{get:(u=>n[u]).bind(null,l),enumerable:!(o=We(n,l))||o.enumerable});return e},Q=(e,n,t)=>(t=e!=null?Pe(ze(e)):{},He(n||!e||!e.__esModule?G(t,"default",{value:e,enumerable:!0}):t,e));const P=require("./AgoClient-B_u_d-XS.cjs"),qe=require("./autoContinue-CP9pJR-V.cjs"),z=require("./createFormCollector-ssBP8u0p.cjs"),Be=require("./createMockClient-BSNuN3ys.cjs"),Y=require("./sheetController-DY-sC13T.cjs");let s=require("react");s=Q(s,1);let a=require("react/jsx-runtime"),X=require("react-markdown");X=Q(X,1);let Z=require("remark-gfm");Z=Q(Z,1);function pe(e){const[n,t]=(0,s.useState)(!1),o=(0,s.useRef)(null),r=(0,s.useMemo)(()=>{if(o.current&&(o.current.destroy(),o.current=null),!e)return null;const c=new P.AgoClient(e);return o.current=c,c},[e?.baseUrl,e?.widgetId]);return(0,s.useEffect)(()=>(r&&o.current===null&&(o.current=r,r.reviveAfterDestroy()),t(!0),()=>{o.current?.destroy(),o.current=null}),[r]),(0,s.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 ee=(0,s.createContext)(null),$e=({children:e,client:n,tools:t,helpers:o,pageContext:r,...c})=>{const{client:i}=pe(n?null:c),l=n||i;return(0,s.useEffect)(()=>{if(!(!t||t.length===0)){for(const u of t)l.register(u);return()=>{for(const u of t)l.unregisterFunction(u.name)}}},[l,t]),(0,s.useEffect)(()=>{if(!o)return;const u=[];return Promise.resolve().then(()=>require("./functions-CPs7omgM.cjs")).then(p=>p.functions_exports).then(p=>{for(const[g,S]of Object.entries(o)){const R=p[g];if(!R){console.warn(`[AGO] Unknown helper: "${g}"`);continue}const k=S===!0?R:{...R,handler:S};l.register(k),u.push(k.name)}}),()=>{for(const p of u)l.unregisterFunction(p)}},[l,o]),(0,s.useEffect)(()=>{r==="auto"&&l.enableAutoPageContext()},[l,r]),(0,a.jsx)(ee.Provider,{value:l,children:e})};function D(){const e=(0,s.useContext)(ee);if(!e)throw new Error('useAgoClient must be used within an <AgoProvider>. Wrap your component tree with <AgoProvider baseUrl="...">.');return e}function W(){return(0,s.useContext)(ee)}var Ke=new Set(["awaiting-approval"]);function ge(e){switch(e){case"progress_indicator":return"progress";case"reasoning":return"reasoning";case"confirmation_input":return"confirmation";case"form":return"form";default:return"status"}}function Ue(e){return e.type==="client_function"?e.functionName==="navigateToPage"?"navigation":"action":ge(e.type)}function ce(e,n){const t=(e??"").toLowerCase();return t.includes("reject")?"rejected":t.includes("error")||t.includes("fail")?"error":t.includes("done")||t.includes("complet")?"done":(t.includes("waiting")||t.includes("pending"))&&(n==="confirmation"||n==="form")?"awaiting-approval":"running"}function ue(e){return typeof e!="string"||!e?"page":e.replace(/[-_]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/\b\w/g,n=>n.toUpperCase()).trim()}function Ge(e){switch(e.kind){case"navigation":return`Navigating to ${ue(e.arguments?.page)}`;case"action":return e.functionName==="setPageState"?"Updating the page":e.functionName==="openFilteredConversations"?"Opening conversations":e.toolDisplayName||e.message||ue(e.functionName)||"Working";case"progress":return e.message||"Working";case"reasoning":return e.message||"Thinking";case"confirmation":return e.message||"Waiting for your confirmation";case"form":return e.message||e.toolDisplayName||"Please fill in the form";default:return e.message||e.toolDisplayName||e.toolName||"Working"}}function xe(e={}){const{includeReasoning:n=!1,labelFor:t}=e,o=W(),r=e.client||o;if(!r)throw new P.AgoError("useAgoActivity requires an AgoClient. Either pass it as options.client or wrap your app in <AgoProvider>.","provider_missing_client");const[c,i]=(0,s.useState)([]),l=(0,s.useRef)(new Set),u=(0,s.useRef)(void 0),p=(0,s.useRef)(t);p.current=t;const g=(0,s.useCallback)((f,A)=>{i(C=>{const d=C.findIndex(m=>m.id===f),b={...d>=0?C[d]:{id:f,kind:"status",label:"",status:"running",requiresApproval:!1,createdAt:new Date},...A};return b.label=p.current?.(b)??Ge(b),d>=0?[...C.slice(0,d),b,...C.slice(d+1)]:[...C,b]})},[]);(0,s.useEffect)(()=>{const f=y=>{u.current=y.messageId},A=y=>{const N=ge(y.type);N==="reasoning"&&!n||g(y.id,{kind:N,status:ce(y.status,N),messageId:u.current,toolName:y.toolName,toolDisplayName:y.toolDisplayName,message:y.message,data:y.data,formSchema:y.formSchema,requiresApproval:N==="confirmation"||N==="form"})},C=y=>{y.invocationId&&g(y.invocationId,{kind:y.functionName==="navigateToPage"?"navigation":"action",status:"running",messageId:u.current,functionName:y.functionName,arguments:y.arguments})},d=y=>{y.invocationId&&g(y.invocationId,{kind:y.functionName==="navigateToPage"?"navigation":"action",status:"awaiting-approval",messageId:u.current,functionName:y.functionName,arguments:y.arguments,requiresApproval:!0})},b=y=>{if(!y.invocationId)return;const N=y.result,v=typeof y.result=="object"&&N!==null&&N.approved===!1&&N.reason==="user_rejected";g(y.invocationId,{status:y.error?"error":v?"rejected":"done",requiresApproval:!1})},m=y=>{for(const N of y.messages??[])if(N.role==="assistant")for(const v of N.toolCalls??[]){const T=Ue(v);T==="reasoning"&&!n||/waiting/i.test(v.status??"")||g(v.id,{kind:T,status:ce(v.status,T),messageId:N.id,toolName:v.toolName,toolDisplayName:v.toolDisplayName,functionName:v.functionName,arguments:v.arguments,message:v.message,data:v.data,formSchema:v.formSchema,requiresApproval:T==="confirmation"||T==="form"})}},x=y=>{i(N=>N.map(v=>v.status==="running"||v.status==="awaiting-approval"?{...v,status:y}:v))},w=()=>x("done"),j=()=>x("error");return r.on("message:start",f),r.on("toolCall:received",A),r.on("function:invoke",C),r.on("function:awaiting-approval",d),r.on("function:result",b),r.on("conversation:loaded",m),r.on("message:complete",w),r.on("message:error",j),()=>{r.off("message:start",f),r.off("toolCall:received",A),r.off("function:invoke",C),r.off("function:awaiting-approval",d),r.off("function:result",b),r.off("conversation:loaded",m),r.off("message:complete",w),r.off("message:error",j)}},[r,n,g]);const S=(0,s.useCallback)(async f=>{const A=c.find(C=>C.id===f);!A||A.status!=="awaiting-approval"||l.current.has(f)||A.kind!=="form"&&(l.current.add(f),g(f,{status:"running",requiresApproval:!1}),A.functionName?await r.approveFunction(f):await r.confirmToolCall(f))},[r,c,g]),R=(0,s.useCallback)(async f=>{const A=c.find(C=>C.id===f);!A||A.status!=="awaiting-approval"||l.current.has(f)||(l.current.add(f),g(f,{status:"rejected",requiresApproval:!1}),A.functionName?await r.rejectFunction(f):await r.rejectToolCall(f))},[r,c,g]),k=(0,s.useCallback)(async(f,A)=>{g(f,{status:"running",requiresApproval:!1}),await r.submitToolCallForm(f,A),g(f,{status:"done"})},[r,g]),_=(0,s.useCallback)(()=>{l.current.clear(),i([])},[]);return{items:c,latest:c.length>0?c[c.length-1]:void 0,isAwaitingApproval:c.some(f=>Ke.has(f.status)),approve:S,reject:R,submitForm:k,clear:_}}function te({client:e,conversationId:n}={}){const t=W(),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,c]=(0,s.useState)([]),[i,l]=(0,s.useState)(n),[u,p]=(0,s.useState)(!1),[g,S]=(0,s.useState)(null);(0,s.useEffect)(()=>{n&&n!==i&&(l(n),R(n))},[n]);const R=async k=>{try{c((await o.getMessages(k)).filter(_=>!_.hidden))}catch(_){S(_ instanceof Error?_:new Error("Failed to load messages"))}};return(0,s.useEffect)(()=>{const k=m=>m==="IN_PROGRESS"||m==="WAITING_CLIENT",_=m=>{i||l(m.conversationId),p(!0),c(x=>{const w=x.findIndex(j=>j.id===m.messageId);return w>=0?x.map((j,y)=>y===w?{...j,status:"IN_PROGRESS"}:j):x.some(j=>j.role==="assistant"&&k(j.status))?x:[...x,{id:m.messageId,conversationId:m.conversationId,content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date}]})},f=m=>{c(x=>{const w=x.findIndex(j=>j.id===m.messageId);return w<0?x:x.map((j,y)=>y===w?{...j,content:j.content+m.content}:j)})},A=m=>{c(x=>{let w=-1;for(let j=x.length-1;j>=0;j--)if(x[j].role==="assistant"&&k(x[j].status)){w=j;break}return w<0?x:[...x.slice(0,w),{...x[w],...m},...x.slice(w+1)]})},C=m=>{c(x=>{const w=x.findIndex(j=>j.id===m.id);return w>=0?[...x.slice(0,w),m,...x.slice(w+1)]:[...x,m]}),p(!1)},d=m=>{S(new Error(m.error)),p(!1)},b=()=>{c(m=>{let x=-1;for(let w=m.length-1;w>=0;w--)if(m[w].role==="assistant"&&k(m[w].status)){x=w;break}return x<0?m:m[x].content?m.map((w,j)=>j===x?{...w,status:"CANCELED"}:w):m.filter((w,j)=>j!==x)}),p(!1)};return o.on("message:start",_),o.on("message:chunk",f),o.on("message:answer-complete",A),o.on("message:complete",C),o.on("message:error",d),o.on("message:stopped",b),()=>{o.off("message:start",_),o.off("message:chunk",f),o.off("message:answer-complete",A),o.off("message:complete",C),o.off("message:error",d),o.off("message:stopped",b)}},[o,i]),{messages:r,isLoading:u,error:g,sendMessage:(0,s.useCallback)(async(k,_)=>{p(!0),S(null);const f={id:`temp-${Date.now()}`,conversationId:i||"",content:k,role:"user",status:"DONE",attachments:_&&_.length>0?P.attachmentsFromFiles(_):void 0,createdAt:new Date},A={id:`temp-assistant-${Date.now()}`,conversationId:i||"",content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date};c(C=>[...C,f,A]);try{const C=await o.sendMessage(k,{conversationId:i,files:_});return C.conversationId&&!i&&l(C.conversationId),c(d=>{const b=d.filter(x=>!x.id.startsWith("temp-")),m={...f,id:f.id.replace("temp-","user-"),conversationId:C.conversationId};return b.some(x=>x.id===C.id)?[...b,m].sort((x,w)=>new Date(x.createdAt).getTime()-new Date(w.createdAt).getTime()):[...b,m,C]}),C}catch(C){return S(C instanceof Error?C:new Error("Failed to send message")),p(!1),c(d=>d.filter(b=>!b.id.startsWith("temp-"))),null}},[o,i]),stop:(0,s.useCallback)(async()=>{await o.stop()},[o]),clearMessages:(0,s.useCallback)(()=>{c([]),l(void 0),S(null)},[]),conversationId:i}}var de={compact:!1,state:"peek",isModal:!1,surface:{style:{},attrs:{}}},Je={tabindex:"tabIndex"};function Ve(e){const n={};for(const[t,o]of Object.entries(e))n[Je[t]??t]=o;return n}function me(e){const n=e!==!1,t=n?e??{}:void 0,o=(0,s.useRef)(t?.onStateChange);o.current=t?.onStateChange;const r=(0,s.useMemo)(()=>{if(n)return Y.createSheetController({breakpoint:t?.breakpoint,initialState:t?.initialState,bottomOffset:t?.bottomOffset,peekHeight:t?.peekHeight,onStateChange:(i,l)=>o.current?.(i,l)})},[n,t?.breakpoint,t?.initialState,t?.bottomOffset,t?.peekHeight]),c=(0,s.useSyncExternalStore)((0,s.useCallback)(i=>r?.subscribe(i)??(()=>{}),[r]),(0,s.useCallback)(()=>r?.getSnapshot()??de,[r]),(0,s.useCallback)(()=>r?.getServerSnapshot()??de,[r]));return{sheet:(0,s.useMemo)(()=>({...c,surface:{...c.surface,attrs:Ve(c.surface.attrs)}}),[c]),expand:(0,s.useCallback)(i=>r?.expand(i),[r]),collapse:(0,s.useCallback)(i=>r?.collapse(i),[r]),toggle:(0,s.useCallback)(i=>r?.toggle(i),[r])}}var Ye=/(`[^`\n]+`|\*\*[^*\n]+\*\*|\*[^*\n]+\*|_[^_\n]+_)/g;function he(e){const n=e.split(Ye);return n.length===1?e:n.map((t,o)=>o%2===0||!t?t:t.startsWith("`")?(0,a.jsx)("code",{style:{fontFamily:"ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",fontSize:"0.92em",padding:"0 3px",borderRadius:"3px",backgroundColor:"rgba(0, 0, 0, 0.06)"},children:t.slice(1,-1)},o):t.startsWith("**")?(0,a.jsx)("strong",{style:{fontWeight:600},children:t.slice(2,-2)},o):(0,a.jsx)("em",{children:t.slice(1,-1)},o))}var Xe=`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var Pe=Object.create,G=Object.defineProperty,We=Object.getOwnPropertyDescriptor,Oe=Object.getOwnPropertyNames,ze=Object.getPrototypeOf,De=Object.prototype.hasOwnProperty,Le=(e,n)=>{let t={};for(var o in e)G(t,o,{get:e[o],enumerable:!0});return n||G(t,Symbol.toStringTag,{value:"Module"}),t},He=(e,n,t,o)=>{if(n&&typeof n=="object"||typeof n=="function")for(var r=Oe(n),c=0,i=r.length,l;c<i;c++)l=r[c],!De.call(e,l)&&l!==t&&G(e,l,{get:(u=>n[u]).bind(null,l),enumerable:!(o=We(n,l))||o.enumerable});return e},Q=(e,n,t)=>(t=e!=null?Pe(ze(e)):{},He(n||!e||!e.__esModule?G(t,"default",{value:e,enumerable:!0}):t,e));const P=require("./AgoClient-7yXQ6R3O.cjs"),qe=require("./autoContinue-CP9pJR-V.cjs"),z=require("./createFormCollector-CwfiYn0V.cjs"),Be=require("./createMockClient-BSNuN3ys.cjs"),Y=require("./sheetController-DY-sC13T.cjs");let s=require("react");s=Q(s,1);let a=require("react/jsx-runtime"),X=require("react-markdown");X=Q(X,1);let Z=require("remark-gfm");Z=Q(Z,1);function pe(e){const[n,t]=(0,s.useState)(!1),o=(0,s.useRef)(null),r=(0,s.useMemo)(()=>{if(o.current&&(o.current.destroy(),o.current=null),!e)return null;const c=new P.AgoClient(e);return o.current=c,c},[e?.baseUrl,e?.widgetId]);return(0,s.useEffect)(()=>(r&&o.current===null&&(o.current=r,r.reviveAfterDestroy()),t(!0),()=>{o.current?.destroy(),o.current=null}),[r]),(0,s.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 ee=(0,s.createContext)(null),$e=({children:e,client:n,tools:t,helpers:o,pageContext:r,...c})=>{const{client:i}=pe(n?null:c),l=n||i;return(0,s.useEffect)(()=>{if(!(!t||t.length===0)){for(const u of t)l.register(u);return()=>{for(const u of t)l.unregisterFunction(u.name)}}},[l,t]),(0,s.useEffect)(()=>{if(!o)return;const u=[];return Promise.resolve().then(()=>require("./functions-CPs7omgM.cjs")).then(p=>p.functions_exports).then(p=>{for(const[g,S]of Object.entries(o)){const R=p[g];if(!R){console.warn(`[AGO] Unknown helper: "${g}"`);continue}const k=S===!0?R:{...R,handler:S};l.register(k),u.push(k.name)}}),()=>{for(const p of u)l.unregisterFunction(p)}},[l,o]),(0,s.useEffect)(()=>{r==="auto"&&l.enableAutoPageContext()},[l,r]),(0,a.jsx)(ee.Provider,{value:l,children:e})};function D(){const e=(0,s.useContext)(ee);if(!e)throw new Error('useAgoClient must be used within an <AgoProvider>. Wrap your component tree with <AgoProvider baseUrl="...">.');return e}function W(){return(0,s.useContext)(ee)}var Ke=new Set(["awaiting-approval"]);function ge(e){switch(e){case"progress_indicator":return"progress";case"reasoning":return"reasoning";case"confirmation_input":return"confirmation";case"form":return"form";default:return"status"}}function Ue(e){return e.type==="client_function"?e.functionName==="navigateToPage"?"navigation":"action":ge(e.type)}function ce(e,n){const t=(e??"").toLowerCase();return t.includes("reject")?"rejected":t.includes("error")||t.includes("fail")?"error":t.includes("done")||t.includes("complet")?"done":(t.includes("waiting")||t.includes("pending"))&&(n==="confirmation"||n==="form")?"awaiting-approval":"running"}function ue(e){return typeof e!="string"||!e?"page":e.replace(/[-_]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/\b\w/g,n=>n.toUpperCase()).trim()}function Ge(e){switch(e.kind){case"navigation":return`Navigating to ${ue(e.arguments?.page)}`;case"action":return e.functionName==="setPageState"?"Updating the page":e.functionName==="openFilteredConversations"?"Opening conversations":e.toolDisplayName||e.message||ue(e.functionName)||"Working";case"progress":return e.message||"Working";case"reasoning":return e.message||"Thinking";case"confirmation":return e.message||"Waiting for your confirmation";case"form":return e.message||e.toolDisplayName||"Please fill in the form";default:return e.message||e.toolDisplayName||e.toolName||"Working"}}function xe(e={}){const{includeReasoning:n=!1,labelFor:t}=e,o=W(),r=e.client||o;if(!r)throw new P.AgoError("useAgoActivity requires an AgoClient. Either pass it as options.client or wrap your app in <AgoProvider>.","provider_missing_client");const[c,i]=(0,s.useState)([]),l=(0,s.useRef)(new Set),u=(0,s.useRef)(void 0),p=(0,s.useRef)(t);p.current=t;const g=(0,s.useCallback)((f,A)=>{i(C=>{const d=C.findIndex(m=>m.id===f),b={...d>=0?C[d]:{id:f,kind:"status",label:"",status:"running",requiresApproval:!1,createdAt:new Date},...A};return b.label=p.current?.(b)??Ge(b),d>=0?[...C.slice(0,d),b,...C.slice(d+1)]:[...C,b]})},[]);(0,s.useEffect)(()=>{const f=y=>{u.current=y.messageId},A=y=>{const N=ge(y.type);N==="reasoning"&&!n||g(y.id,{kind:N,status:ce(y.status,N),messageId:u.current,toolName:y.toolName,toolDisplayName:y.toolDisplayName,message:y.message,data:y.data,formSchema:y.formSchema,requiresApproval:N==="confirmation"||N==="form"})},C=y=>{y.invocationId&&g(y.invocationId,{kind:y.functionName==="navigateToPage"?"navigation":"action",status:"running",messageId:u.current,functionName:y.functionName,arguments:y.arguments})},d=y=>{y.invocationId&&g(y.invocationId,{kind:y.functionName==="navigateToPage"?"navigation":"action",status:"awaiting-approval",messageId:u.current,functionName:y.functionName,arguments:y.arguments,requiresApproval:!0})},b=y=>{if(!y.invocationId)return;const N=y.result,v=typeof y.result=="object"&&N!==null&&N.approved===!1&&N.reason==="user_rejected";g(y.invocationId,{status:y.error?"error":v?"rejected":"done",requiresApproval:!1})},m=y=>{for(const N of y.messages??[])if(N.role==="assistant")for(const v of N.toolCalls??[]){const T=Ue(v);T==="reasoning"&&!n||/waiting/i.test(v.status??"")||g(v.id,{kind:T,status:ce(v.status,T),messageId:N.id,toolName:v.toolName,toolDisplayName:v.toolDisplayName,functionName:v.functionName,arguments:v.arguments,message:v.message,data:v.data,formSchema:v.formSchema,requiresApproval:T==="confirmation"||T==="form"})}},x=y=>{i(N=>N.map(v=>v.status==="running"||v.status==="awaiting-approval"?{...v,status:y}:v))},w=()=>x("done"),j=()=>x("error");return r.on("message:start",f),r.on("toolCall:received",A),r.on("function:invoke",C),r.on("function:awaiting-approval",d),r.on("function:result",b),r.on("conversation:loaded",m),r.on("message:complete",w),r.on("message:error",j),()=>{r.off("message:start",f),r.off("toolCall:received",A),r.off("function:invoke",C),r.off("function:awaiting-approval",d),r.off("function:result",b),r.off("conversation:loaded",m),r.off("message:complete",w),r.off("message:error",j)}},[r,n,g]);const S=(0,s.useCallback)(async f=>{const A=c.find(C=>C.id===f);!A||A.status!=="awaiting-approval"||l.current.has(f)||A.kind!=="form"&&(l.current.add(f),g(f,{status:"running",requiresApproval:!1}),A.functionName?await r.approveFunction(f):await r.confirmToolCall(f))},[r,c,g]),R=(0,s.useCallback)(async f=>{const A=c.find(C=>C.id===f);!A||A.status!=="awaiting-approval"||l.current.has(f)||(l.current.add(f),g(f,{status:"rejected",requiresApproval:!1}),A.functionName?await r.rejectFunction(f):await r.rejectToolCall(f))},[r,c,g]),k=(0,s.useCallback)(async(f,A)=>{g(f,{status:"running",requiresApproval:!1}),await r.submitToolCallForm(f,A),g(f,{status:"done"})},[r,g]),_=(0,s.useCallback)(()=>{l.current.clear(),i([])},[]);return{items:c,latest:c.length>0?c[c.length-1]:void 0,isAwaitingApproval:c.some(f=>Ke.has(f.status)),approve:S,reject:R,submitForm:k,clear:_}}function te({client:e,conversationId:n}={}){const t=W(),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,c]=(0,s.useState)([]),[i,l]=(0,s.useState)(n),[u,p]=(0,s.useState)(!1),[g,S]=(0,s.useState)(null);(0,s.useEffect)(()=>{n&&n!==i&&(l(n),R(n))},[n]);const R=async k=>{try{c((await o.getMessages(k)).filter(_=>!_.hidden))}catch(_){S(_ instanceof Error?_:new Error("Failed to load messages"))}};return(0,s.useEffect)(()=>{const k=m=>m==="IN_PROGRESS"||m==="WAITING_CLIENT",_=m=>{i||l(m.conversationId),p(!0),c(x=>{const w=x.findIndex(j=>j.id===m.messageId);return w>=0?x.map((j,y)=>y===w?{...j,status:"IN_PROGRESS"}:j):x.some(j=>j.role==="assistant"&&k(j.status))?x:[...x,{id:m.messageId,conversationId:m.conversationId,content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date}]})},f=m=>{c(x=>{const w=x.findIndex(j=>j.id===m.messageId);return w<0?x:x.map((j,y)=>y===w?{...j,content:j.content+m.content}:j)})},A=m=>{c(x=>{let w=-1;for(let j=x.length-1;j>=0;j--)if(x[j].role==="assistant"&&k(x[j].status)){w=j;break}return w<0?x:[...x.slice(0,w),{...x[w],...m},...x.slice(w+1)]})},C=m=>{c(x=>{const w=x.findIndex(j=>j.id===m.id);return w>=0?[...x.slice(0,w),m,...x.slice(w+1)]:[...x,m]}),p(!1)},d=m=>{S(new Error(m.error)),p(!1)},b=()=>{c(m=>{let x=-1;for(let w=m.length-1;w>=0;w--)if(m[w].role==="assistant"&&k(m[w].status)){x=w;break}return x<0?m:m[x].content?m.map((w,j)=>j===x?{...w,status:"CANCELED"}:w):m.filter((w,j)=>j!==x)}),p(!1)};return o.on("message:start",_),o.on("message:chunk",f),o.on("message:answer-complete",A),o.on("message:complete",C),o.on("message:error",d),o.on("message:stopped",b),()=>{o.off("message:start",_),o.off("message:chunk",f),o.off("message:answer-complete",A),o.off("message:complete",C),o.off("message:error",d),o.off("message:stopped",b)}},[o,i]),{messages:r,isLoading:u,error:g,sendMessage:(0,s.useCallback)(async(k,_)=>{p(!0),S(null);const f={id:`temp-${Date.now()}`,conversationId:i||"",content:k,role:"user",status:"DONE",attachments:_&&_.length>0?P.attachmentsFromFiles(_):void 0,createdAt:new Date},A={id:`temp-assistant-${Date.now()}`,conversationId:i||"",content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date};c(C=>[...C,f,A]);try{const C=await o.sendMessage(k,{conversationId:i,files:_});return C.conversationId&&!i&&l(C.conversationId),c(d=>{const b=d.filter(x=>!x.id.startsWith("temp-")),m={...f,id:f.id.replace("temp-","user-"),conversationId:C.conversationId};return b.some(x=>x.id===C.id)?[...b,m].sort((x,w)=>new Date(x.createdAt).getTime()-new Date(w.createdAt).getTime()):[...b,m,C]}),C}catch(C){return S(C instanceof Error?C:new Error("Failed to send message")),p(!1),c(d=>d.filter(b=>!b.id.startsWith("temp-"))),null}},[o,i]),stop:(0,s.useCallback)(async()=>{await o.stop()},[o]),clearMessages:(0,s.useCallback)(()=>{c([]),l(void 0),S(null)},[]),conversationId:i}}var de={compact:!1,state:"peek",isModal:!1,surface:{style:{},attrs:{}}},Je={tabindex:"tabIndex"};function Ve(e){const n={};for(const[t,o]of Object.entries(e))n[Je[t]??t]=o;return n}function me(e){const n=e!==!1,t=n?e??{}:void 0,o=(0,s.useRef)(t?.onStateChange);o.current=t?.onStateChange;const r=(0,s.useMemo)(()=>{if(n)return Y.createSheetController({breakpoint:t?.breakpoint,initialState:t?.initialState,bottomOffset:t?.bottomOffset,peekHeight:t?.peekHeight,onStateChange:(i,l)=>o.current?.(i,l)})},[n,t?.breakpoint,t?.initialState,t?.bottomOffset,t?.peekHeight]),c=(0,s.useSyncExternalStore)((0,s.useCallback)(i=>r?.subscribe(i)??(()=>{}),[r]),(0,s.useCallback)(()=>r?.getSnapshot()??de,[r]),(0,s.useCallback)(()=>r?.getServerSnapshot()??de,[r]));return{sheet:(0,s.useMemo)(()=>({...c,surface:{...c.surface,attrs:Ve(c.surface.attrs)}}),[c]),expand:(0,s.useCallback)(i=>r?.expand(i),[r]),collapse:(0,s.useCallback)(i=>r?.collapse(i),[r]),toggle:(0,s.useCallback)(i=>r?.toggle(i),[r])}}var Ye=/(`[^`\n]+`|\*\*[^*\n]+\*\*|\*[^*\n]+\*|_[^_\n]+_)/g;function he(e){const n=e.split(Ye);return n.length===1?e:n.map((t,o)=>o%2===0||!t?t:t.startsWith("`")?(0,a.jsx)("code",{style:{fontFamily:"ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",fontSize:"0.92em",padding:"0 3px",borderRadius:"3px",backgroundColor:"rgba(0, 0, 0, 0.06)"},children:t.slice(1,-1)},o):t.startsWith("**")?(0,a.jsx)("strong",{style:{fontWeight:600},children:t.slice(2,-2)},o):(0,a.jsx)("em",{children:t.slice(1,-1)},o))}var Xe=`
2
2
  @keyframes ago-activity-enter {
3
3
  from { opacity: 0; transform: translateY(4px); }
4
4
  to { opacity: 1; transform: none; }
package/dist/react.js CHANGED
@@ -1,6 +1,6 @@
1
- import { a as Ee, b as Z, h as Me, i as Te, o as Fe, s as We, t as ze } from "./AgoClient-BJjLTOw4.js";
1
+ import { a as Ee, b as Z, h as Me, i as Te, o as Fe, s as We, t as ze } from "./AgoClient-DTkBRGFE.js";
2
2
  import { t as Pe } from "./autoContinue-CC8K9mBU.js";
3
- import { n as Et, r as ue, t as pe } from "./createFormCollector-CM3qjGcM.js";
3
+ import { n as Et, r as ue, t as pe } from "./createFormCollector-BivHRIAe.js";
4
4
  import { t as Tt } from "./createMockClient-BDLW6tVc.js";
5
5
  import { C as De, S as Le, n as He } from "./sheetController-CBUVOroo.js";
6
6
  import Be, { createContext as Oe, forwardRef as je, useCallback as R, useContext as fe, useEffect as N, useId as $e, useImperativeHandle as qe, useMemo as H, useRef as W, useState as z, useSyncExternalStore as ge } from "react";
package/dist/vue.cjs CHANGED
@@ -1 +1 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("./AgoClient-B_u_d-XS.cjs");let o=require("vue");var I=Symbol("ago-client"),L={install(t,e){const n=new w.AgoClient(e);t.provide(I,n)}};function d(t){if(t)return new w.AgoClient(t);const e=(0,o.inject)(I);if(!e)throw new Error("useAgo(): no AgoClient found. Either pass config or install AgoPlugin.");return e}function E(t={}){const e=t.client??d(),n=(0,o.ref)([]),s=(0,o.ref)(t.conversationId),a=(0,o.ref)(!1),i=(0,o.ref)(null),v=r=>{s.value||(s.value=r.conversationId)},f=r=>{const u=n.value.findIndex(l=>l.id===r.messageId);u>=0&&(n.value[u]={...n.value[u],content:n.value[u].content+r.content})},m=r=>{const u=n.value.findIndex(l=>l.id===r.id);u>=0?n.value[u]=r:n.value.push(r),a.value=!1},p=r=>{i.value=new Error(r.error),a.value=!1},g=()=>{let r=-1;for(let u=n.value.length-1;u>=0;u--){const l=n.value[u];if(l.role==="assistant"&&(l.status==="IN_PROGRESS"||l.status==="WAITING_CLIENT")){r=u;break}}r>=0&&(n.value[r].content?n.value[r]={...n.value[r],status:"CANCELED"}:n.value.splice(r,1)),a.value=!1};(0,o.onMounted)(()=>{e.on("message:start",v),e.on("message:chunk",f),e.on("message:complete",m),e.on("message:error",p),e.on("message:stopped",g)}),(0,o.onUnmounted)(()=>{e.off("message:start",v),e.off("message:chunk",f),e.off("message:complete",m),e.off("message:error",p),e.off("message:stopped",g)});async function C(r,u){a.value=!0,i.value=null;const l={id:`temp-${Date.now()}`,conversationId:s.value||"",content:r,role:"user",status:"DONE",createdAt:new Date},S={id:`temp-assistant-${Date.now()}`,conversationId:s.value||"",content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date};n.value.push(l,S);try{const c=await e.sendMessage(r,{conversationId:s.value,files:u});c.conversationId&&!s.value&&(s.value=c.conversationId),n.value=n.value.filter(A=>!A.id.startsWith("temp-"));const h={...l,id:l.id.replace("temp-","user-"),conversationId:c.conversationId};return n.value.some(A=>A.id===c.id)?n.value.push(h):n.value.push(h,c),c}catch(c){return i.value=c instanceof Error?c:new Error("Failed to send"),a.value=!1,n.value=n.value.filter(h=>!h.id.startsWith("temp-")),null}}async function M(){await e.stop()}function y(){n.value=[],s.value=void 0,i.value=null}return{messages:n,isLoading:a,error:i,conversationId:s,sendMessage:C,stop:M,clearMessages:y}}function N(t={}){const e=t.client??d(),n=t.autoLoad??!0,s=(0,o.ref)([]),a=(0,o.ref)(null),i=(0,o.ref)(!1),v=(0,o.ref)(null);async function f(){i.value=!0,v.value=null;try{s.value=(await e.getConversations()).data}catch(g){v.value=g instanceof Error?g:new Error("Failed to load conversations")}finally{i.value=!1}}async function m(g){i.value=!0,v.value=null;try{a.value=await e.getConversation(g)}catch(C){v.value=C instanceof Error?C:new Error("Failed to load conversation")}finally{i.value=!1}}function p(){a.value=null}return(0,o.onMounted)(()=>{n&&f()}),{conversations:s,currentConversation:a,isLoading:i,error:v,selectConversation:m,startNewConversation:p,refreshConversations:f}}function P(t={}){const e=E({client:t.client,conversationId:t.conversationId}),n=N({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,stop:e.stop,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 R(t,e){const n=d();(0,o.onMounted)(()=>{n.registerFunction(t,e.handler,{description:e.description,parameters:e.parameters,maxResultBytes:e.maxResultBytes})}),(0,o.onUnmounted)(()=>{n.unregisterFunction(t)})}function F(t,e){const n=d();(0,o.onMounted)(()=>{n.registerNavigationFunction(t,e)}),(0,o.onUnmounted)(()=>{n.unregisterNavigationFunction()})}function _(t,e){const n=d(),s=e?.functionName??"setPageState";(0,o.onMounted)(()=>{n.registerPageStateFunction(t,{...e,functionName:s})}),(0,o.onUnmounted)(()=>{n.unregisterPageStateFunction(s)})}function D(t,e){const n=d();(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 b(){const t=d(),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=I;exports.AgoPlugin=L;exports.useAgo=d;exports.useAgoEvents=D;exports.useAgoFunction=R;exports.useAgoNavigation=F;exports.useAgoPageState=_;exports.useAgoStore=U;exports.useChat=P;exports.useConversation=N;exports.useMessages=E;exports.useProactiveNudge=b;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("./AgoClient-7yXQ6R3O.cjs");let o=require("vue");var I=Symbol("ago-client"),L={install(t,e){const n=new w.AgoClient(e);t.provide(I,n)}};function d(t){if(t)return new w.AgoClient(t);const e=(0,o.inject)(I);if(!e)throw new Error("useAgo(): no AgoClient found. Either pass config or install AgoPlugin.");return e}function E(t={}){const e=t.client??d(),n=(0,o.ref)([]),s=(0,o.ref)(t.conversationId),a=(0,o.ref)(!1),i=(0,o.ref)(null),v=r=>{s.value||(s.value=r.conversationId)},f=r=>{const u=n.value.findIndex(l=>l.id===r.messageId);u>=0&&(n.value[u]={...n.value[u],content:n.value[u].content+r.content})},m=r=>{const u=n.value.findIndex(l=>l.id===r.id);u>=0?n.value[u]=r:n.value.push(r),a.value=!1},p=r=>{i.value=new Error(r.error),a.value=!1},g=()=>{let r=-1;for(let u=n.value.length-1;u>=0;u--){const l=n.value[u];if(l.role==="assistant"&&(l.status==="IN_PROGRESS"||l.status==="WAITING_CLIENT")){r=u;break}}r>=0&&(n.value[r].content?n.value[r]={...n.value[r],status:"CANCELED"}:n.value.splice(r,1)),a.value=!1};(0,o.onMounted)(()=>{e.on("message:start",v),e.on("message:chunk",f),e.on("message:complete",m),e.on("message:error",p),e.on("message:stopped",g)}),(0,o.onUnmounted)(()=>{e.off("message:start",v),e.off("message:chunk",f),e.off("message:complete",m),e.off("message:error",p),e.off("message:stopped",g)});async function C(r,u){a.value=!0,i.value=null;const l={id:`temp-${Date.now()}`,conversationId:s.value||"",content:r,role:"user",status:"DONE",createdAt:new Date},S={id:`temp-assistant-${Date.now()}`,conversationId:s.value||"",content:"",role:"assistant",status:"IN_PROGRESS",createdAt:new Date};n.value.push(l,S);try{const c=await e.sendMessage(r,{conversationId:s.value,files:u});c.conversationId&&!s.value&&(s.value=c.conversationId),n.value=n.value.filter(A=>!A.id.startsWith("temp-"));const h={...l,id:l.id.replace("temp-","user-"),conversationId:c.conversationId};return n.value.some(A=>A.id===c.id)?n.value.push(h):n.value.push(h,c),c}catch(c){return i.value=c instanceof Error?c:new Error("Failed to send"),a.value=!1,n.value=n.value.filter(h=>!h.id.startsWith("temp-")),null}}async function M(){await e.stop()}function y(){n.value=[],s.value=void 0,i.value=null}return{messages:n,isLoading:a,error:i,conversationId:s,sendMessage:C,stop:M,clearMessages:y}}function N(t={}){const e=t.client??d(),n=t.autoLoad??!0,s=(0,o.ref)([]),a=(0,o.ref)(null),i=(0,o.ref)(!1),v=(0,o.ref)(null);async function f(){i.value=!0,v.value=null;try{s.value=(await e.getConversations()).data}catch(g){v.value=g instanceof Error?g:new Error("Failed to load conversations")}finally{i.value=!1}}async function m(g){i.value=!0,v.value=null;try{a.value=await e.getConversation(g)}catch(C){v.value=C instanceof Error?C:new Error("Failed to load conversation")}finally{i.value=!1}}function p(){a.value=null}return(0,o.onMounted)(()=>{n&&f()}),{conversations:s,currentConversation:a,isLoading:i,error:v,selectConversation:m,startNewConversation:p,refreshConversations:f}}function P(t={}){const e=E({client:t.client,conversationId:t.conversationId}),n=N({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,stop:e.stop,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 R(t,e){const n=d();(0,o.onMounted)(()=>{n.registerFunction(t,e.handler,{description:e.description,parameters:e.parameters,maxResultBytes:e.maxResultBytes})}),(0,o.onUnmounted)(()=>{n.unregisterFunction(t)})}function F(t,e){const n=d();(0,o.onMounted)(()=>{n.registerNavigationFunction(t,e)}),(0,o.onUnmounted)(()=>{n.unregisterNavigationFunction()})}function _(t,e){const n=d(),s=e?.functionName??"setPageState";(0,o.onMounted)(()=>{n.registerPageStateFunction(t,{...e,functionName:s})}),(0,o.onUnmounted)(()=>{n.unregisterPageStateFunction(s)})}function D(t,e){const n=d();(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 b(){const t=d(),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=I;exports.AgoPlugin=L;exports.useAgo=d;exports.useAgoEvents=D;exports.useAgoFunction=R;exports.useAgoNavigation=F;exports.useAgoPageState=_;exports.useAgoStore=U;exports.useChat=P;exports.useConversation=N;exports.useMessages=E;exports.useProactiveNudge=b;
package/dist/vue.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as N } from "./AgoClient-BJjLTOw4.js";
1
+ import { t as N } from "./AgoClient-DTkBRGFE.js";
2
2
  import { computed as R, inject as F, onMounted as f, onScopeDispose as P, onUnmounted as m, ref as v, shallowRef as y } from "vue";
3
3
  var A = /* @__PURE__ */ Symbol("ago-client"), k = { install(t, e) {
4
4
  const n = new N(e);
package/dist/widget.cjs CHANGED
@@ -1,4 +1,4 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ae=require("./AgoClient-B_u_d-XS.cjs"),en=require("./createConversationSession-BCdwAhLF.cjs"),Ct=require("./createFormCollector-ssBP8u0p.cjs"),t=require("./sheetController-DY-sC13T.cjs");function tn(o){let i=[];const s=document.createElement("form");t.css(s,{display:"flex",flexDirection:"column",gap:"8px",padding:"12px",borderTop:`1px solid ${t.BORDER_COLOR}`,backgroundColor:t.PANEL_BACKGROUND}),s.className="ago-chat-input";const r=t.div({display:"flex",flexWrap:"wrap",gap:"6px"}),C=t.div({display:"flex",gap:"8px",alignItems:"flex-end"}),a=document.createElement("textarea");a.placeholder=o.placeholder,a.setAttribute("aria-label",o.placeholder),a.rows=1,t.css(a,{flex:"1",resize:"none",boxSizing:"border-box",padding:"10px 12px",border:`1px solid ${t.BORDER_COLOR}`,borderRadius:"12px",fontSize:"16px",fontFamily:t.FONT_VAR,lineHeight:"1.4",maxHeight:"110px",overflowY:"hidden"});const _=()=>{a.style.height="auto";const g=Math.min(a.scrollHeight+2,110);a.style.height=`${g}px`,a.style.overflowY=a.scrollHeight+2>110?"auto":"hidden"};a.addEventListener("input",()=>{_(),H()});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>',y='<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>',u='<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><rect x="5" y="5" width="14" height="14" rx="2"/></svg>',p=document.createElement("button");p.type="submit",p.setAttribute("aria-label","Send"),p.innerHTML=m,t.css(p,{flexShrink:"0",width:"44px",height:"44px",padding:"0",border:"none",borderRadius:"50%",backgroundColor:t.BRAND_COLOR,color:t.BRAND_TEXT_COLOR,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer"});let R=!1;const M=()=>R&&!!o.onStop,H=()=>{const c=a.value.trim()!==""||i.length>0,g=M(),A=!g&&(R||!c);p.disabled=A,p.type=g?"button":"submit",p.setAttribute("aria-label",g?"Stop generating":"Send"),p.innerHTML=g?u:R?y:m,p.style.opacity=A&&!R?"0.5":"1",p.style.cursor=A?"default":"pointer"};p.addEventListener("click",()=>{M()&&o.onStop?.()});let B=null,O=null;o.allowFiles&&(B=document.createElement("input"),B.type="file",B.multiple=!0,t.css(B,{display:"none"}),O=document.createElement("button"),O.type="button",O.setAttribute("aria-label","Attach file"),O.textContent="📎",t.css(O,{flexShrink:"0",minWidth:"44px",minHeight:"44px",display:"flex",alignItems:"center",justifyContent:"center",padding:"0 12px",border:`1px solid ${t.BORDER_COLOR}`,borderRadius:"12px",backgroundColor:t.PANEL_BACKGROUND,cursor:"pointer",fontSize:"14px"}),O.addEventListener("click",()=>B?.click()),B.addEventListener("change",()=>{i=[...i,...Array.from(B?.files??[])],h()}));function h(){r.replaceChildren(),i.forEach((c,g)=>{const A=t.div({display:"flex",alignItems:"center",gap:"4px",padding:"4px 8px",backgroundColor:"#f0f4ff",border:`1px solid ${t.BORDER_COLOR}`,borderRadius:"8px",fontSize:"12px"}),q=document.createElement("span");q.textContent=c.name;const D=document.createElement("button");D.type="button",D.setAttribute("aria-label",`Remove ${c.name}`),D.textContent="×",t.css(D,{flexShrink:"0",width:"44px",height:"44px",margin:"-14px -12px -14px -4px",display:"flex",alignItems:"center",justifyContent:"center",border:"none",background:"transparent",cursor:"pointer",fontSize:"14px",lineHeight:"1"}),D.addEventListener("click",()=>{i=i.filter((N,G)=>G!==g),h()}),A.append(q,D),r.appendChild(A)}),H()}const x=()=>{const c=a.value,g=i;return a.value="",_(),i=[],h(),{content:c,files:g}},v=()=>{const{content:c,files:g}=x();(c.trim()||g.length>0)&&o.onSend(c.trim(),g.length>0?g:void 0)};return s.addEventListener("submit",c=>{c.preventDefault(),v()}),a.addEventListener("keydown",c=>{c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),v())}),O&&C.appendChild(O),C.append(a,p),B&&s.appendChild(B),s.append(r,C),H(),{inputRow:s,getValueAndClear:x,setDisabled:c=>{a.disabled=c,R=c,H()},focus:()=>a.focus(),restoreDraft:(c,g)=>{c&&!a.value.trim()&&(a.value=c,_()),g?.length&&(i=[...g,...i],h()),H()}}}var nn={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function se(o){return o.replace(/[&<>"']/g,i=>nn[i])}function yt(o){const i=o.trim();return/^(https?:|mailto:|tel:|#|\/|\.\/|\.\.\/)/i.test(i)||!/^[a-z][a-z0-9+.-]*:/i.test(i)?i:null}var Rt='"IBM Plex Mono", ui-monospace, SFMono-Regular, Menlo, monospace',Oe="";function ee(o){const i=[],s=C=>(i.push(C),`${Oe}${i.length-1}${Oe}`);let r=o;return r=r.replace(/`([^`]+)`/g,(C,a)=>s(`<code style="background:#f0f2f5;padding:2px 5px;border-radius:4px;font-size:13px;font-family:${Rt}">${se(a)}</code>`)),r=r.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g,(C,a,_)=>{const m=yt(_);return m?s(`<img alt="${se(a)}" src="${se(m)}" style="max-width:100%;border-radius:8px;margin:4px 0" />`):C}),r=r.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,(C,a,_)=>{const m=yt(_);return m?s(`<a href="${se(m)}" target="_blank" rel="noopener noreferrer" style="color:#1b5fc4;text-decoration:underline">${ee(a)}</a>`):C}),r=se(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(`${Oe}(\\d+)${Oe}`,"g"),(C,a)=>i[Number(a)]),r}function U(o,i,s){const r=document.createElement(o);return Object.assign(r.style,i),s!==void 0&&(r.innerHTML=s),r}var St=/^ {0,3}([-*_])( *\1){2,} *$/,_t=/^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$/,Ot=/^ {0,3}(```+|~~~+)/,Ae=/^ {0,3}>\s?/,le=/^(\s*)([-*+]|\d+[.)])\s+(.*)$/,on=["20px","18px","16px","15px","14px","13px"],Xe=o=>o.match(/^\s*/)?.[0].length??0;function rn(o){return o.trim()===""||St.test(o)||_t.test(o)||Ot.test(o)||Ae.test(o)||le.test(o)}function At(o){const i=o[0].match(le),s=i[1].length,r=/\d/.test(i[2]),C=U(r?"ol":"ul",{margin:"0 0 8px 0",paddingLeft:"20px",listStyleType:r?"decimal":"disc",listStylePosition:"outside"});let a=0;for(;a<o.length;){const _=o[a].match(le),m=[];for(a++;a<o.length&&Xe(o[a])>s;)m.push(o[a]),a++;const y=U("li",{display:"list-item",margin:"2px 0",lineHeight:"1.6"}),u=_[3].match(/^\[([ xX])\]\s+(.*)$/);u?(y.style.listStyleType="none",y.style.marginLeft="-20px",y.innerHTML=`<span style="margin-right:6px">${u[1].toLowerCase()==="x"?"☑":"☐"}</span>${ee(u[2])}`):y.innerHTML=ee(_[3]),m.filter(p=>le.test(p)).length>0&&y.appendChild(At(m.filter(p=>p.trim()!==""))),C.appendChild(y)}return C}function sn(o){const i=m=>m.replace(/^\s*\|?/,"").replace(/\|?\s*$/,"").split("|").map(y=>y.trim()),s=U("div",{overflowX:"auto",margin:"0 0 8px 0"}),r=U("table",{borderCollapse:"collapse",width:"100%",fontSize:"13px"}),C=document.createElement("thead"),a=document.createElement("tr");for(const m of i(o[0]))a.appendChild(U("th",{border:"1px solid #dee3e8",padding:"6px 10px",textAlign:"left",backgroundColor:"#f5f7fa",fontWeight:"600"},ee(m)));C.appendChild(a),r.appendChild(C);const _=document.createElement("tbody");for(const m of o.slice(2)){const y=document.createElement("tr");for(const u of i(m))y.appendChild(U("td",{border:"1px solid #dee3e8",padding:"6px 10px"},ee(u)));_.appendChild(y)}return r.appendChild(_),s.appendChild(r),s}var an=o=>!!o&&/^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/.test(o);function Le(o){const i=document.createDocumentFragment(),s=o.replace(/\r\n?/g,`
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const ae=require("./AgoClient-7yXQ6R3O.cjs"),en=require("./createConversationSession-Bv6a15E0.cjs"),Ct=require("./createFormCollector-CwfiYn0V.cjs"),t=require("./sheetController-DY-sC13T.cjs");function tn(o){let i=[];const s=document.createElement("form");t.css(s,{display:"flex",flexDirection:"column",gap:"8px",padding:"12px",borderTop:`1px solid ${t.BORDER_COLOR}`,backgroundColor:t.PANEL_BACKGROUND}),s.className="ago-chat-input";const r=t.div({display:"flex",flexWrap:"wrap",gap:"6px"}),C=t.div({display:"flex",gap:"8px",alignItems:"flex-end"}),a=document.createElement("textarea");a.placeholder=o.placeholder,a.setAttribute("aria-label",o.placeholder),a.rows=1,t.css(a,{flex:"1",resize:"none",boxSizing:"border-box",padding:"10px 12px",border:`1px solid ${t.BORDER_COLOR}`,borderRadius:"12px",fontSize:"16px",fontFamily:t.FONT_VAR,lineHeight:"1.4",maxHeight:"110px",overflowY:"hidden"});const _=()=>{a.style.height="auto";const g=Math.min(a.scrollHeight+2,110);a.style.height=`${g}px`,a.style.overflowY=a.scrollHeight+2>110?"auto":"hidden"};a.addEventListener("input",()=>{_(),H()});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>',y='<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>',u='<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><rect x="5" y="5" width="14" height="14" rx="2"/></svg>',p=document.createElement("button");p.type="submit",p.setAttribute("aria-label","Send"),p.innerHTML=m,t.css(p,{flexShrink:"0",width:"44px",height:"44px",padding:"0",border:"none",borderRadius:"50%",backgroundColor:t.BRAND_COLOR,color:t.BRAND_TEXT_COLOR,display:"flex",alignItems:"center",justifyContent:"center",cursor:"pointer"});let R=!1;const M=()=>R&&!!o.onStop,H=()=>{const c=a.value.trim()!==""||i.length>0,g=M(),A=!g&&(R||!c);p.disabled=A,p.type=g?"button":"submit",p.setAttribute("aria-label",g?"Stop generating":"Send"),p.innerHTML=g?u:R?y:m,p.style.opacity=A&&!R?"0.5":"1",p.style.cursor=A?"default":"pointer"};p.addEventListener("click",()=>{M()&&o.onStop?.()});let B=null,O=null;o.allowFiles&&(B=document.createElement("input"),B.type="file",B.multiple=!0,t.css(B,{display:"none"}),O=document.createElement("button"),O.type="button",O.setAttribute("aria-label","Attach file"),O.textContent="📎",t.css(O,{flexShrink:"0",minWidth:"44px",minHeight:"44px",display:"flex",alignItems:"center",justifyContent:"center",padding:"0 12px",border:`1px solid ${t.BORDER_COLOR}`,borderRadius:"12px",backgroundColor:t.PANEL_BACKGROUND,cursor:"pointer",fontSize:"14px"}),O.addEventListener("click",()=>B?.click()),B.addEventListener("change",()=>{i=[...i,...Array.from(B?.files??[])],h()}));function h(){r.replaceChildren(),i.forEach((c,g)=>{const A=t.div({display:"flex",alignItems:"center",gap:"4px",padding:"4px 8px",backgroundColor:"#f0f4ff",border:`1px solid ${t.BORDER_COLOR}`,borderRadius:"8px",fontSize:"12px"}),q=document.createElement("span");q.textContent=c.name;const D=document.createElement("button");D.type="button",D.setAttribute("aria-label",`Remove ${c.name}`),D.textContent="×",t.css(D,{flexShrink:"0",width:"44px",height:"44px",margin:"-14px -12px -14px -4px",display:"flex",alignItems:"center",justifyContent:"center",border:"none",background:"transparent",cursor:"pointer",fontSize:"14px",lineHeight:"1"}),D.addEventListener("click",()=>{i=i.filter((N,G)=>G!==g),h()}),A.append(q,D),r.appendChild(A)}),H()}const x=()=>{const c=a.value,g=i;return a.value="",_(),i=[],h(),{content:c,files:g}},v=()=>{const{content:c,files:g}=x();(c.trim()||g.length>0)&&o.onSend(c.trim(),g.length>0?g:void 0)};return s.addEventListener("submit",c=>{c.preventDefault(),v()}),a.addEventListener("keydown",c=>{c.key==="Enter"&&!c.shiftKey&&(c.preventDefault(),v())}),O&&C.appendChild(O),C.append(a,p),B&&s.appendChild(B),s.append(r,C),H(),{inputRow:s,getValueAndClear:x,setDisabled:c=>{a.disabled=c,R=c,H()},focus:()=>a.focus(),restoreDraft:(c,g)=>{c&&!a.value.trim()&&(a.value=c,_()),g?.length&&(i=[...g,...i],h()),H()}}}var nn={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"};function se(o){return o.replace(/[&<>"']/g,i=>nn[i])}function yt(o){const i=o.trim();return/^(https?:|mailto:|tel:|#|\/|\.\/|\.\.\/)/i.test(i)||!/^[a-z][a-z0-9+.-]*:/i.test(i)?i:null}var Rt='"IBM Plex Mono", ui-monospace, SFMono-Regular, Menlo, monospace',Oe="";function ee(o){const i=[],s=C=>(i.push(C),`${Oe}${i.length-1}${Oe}`);let r=o;return r=r.replace(/`([^`]+)`/g,(C,a)=>s(`<code style="background:#f0f2f5;padding:2px 5px;border-radius:4px;font-size:13px;font-family:${Rt}">${se(a)}</code>`)),r=r.replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g,(C,a,_)=>{const m=yt(_);return m?s(`<img alt="${se(a)}" src="${se(m)}" style="max-width:100%;border-radius:8px;margin:4px 0" />`):C}),r=r.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g,(C,a,_)=>{const m=yt(_);return m?s(`<a href="${se(m)}" target="_blank" rel="noopener noreferrer" style="color:#1b5fc4;text-decoration:underline">${ee(a)}</a>`):C}),r=se(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(`${Oe}(\\d+)${Oe}`,"g"),(C,a)=>i[Number(a)]),r}function U(o,i,s){const r=document.createElement(o);return Object.assign(r.style,i),s!==void 0&&(r.innerHTML=s),r}var St=/^ {0,3}([-*_])( *\1){2,} *$/,_t=/^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$/,Ot=/^ {0,3}(```+|~~~+)/,Ae=/^ {0,3}>\s?/,le=/^(\s*)([-*+]|\d+[.)])\s+(.*)$/,on=["20px","18px","16px","15px","14px","13px"],Xe=o=>o.match(/^\s*/)?.[0].length??0;function rn(o){return o.trim()===""||St.test(o)||_t.test(o)||Ot.test(o)||Ae.test(o)||le.test(o)}function At(o){const i=o[0].match(le),s=i[1].length,r=/\d/.test(i[2]),C=U(r?"ol":"ul",{margin:"0 0 8px 0",paddingLeft:"20px",listStyleType:r?"decimal":"disc",listStylePosition:"outside"});let a=0;for(;a<o.length;){const _=o[a].match(le),m=[];for(a++;a<o.length&&Xe(o[a])>s;)m.push(o[a]),a++;const y=U("li",{display:"list-item",margin:"2px 0",lineHeight:"1.6"}),u=_[3].match(/^\[([ xX])\]\s+(.*)$/);u?(y.style.listStyleType="none",y.style.marginLeft="-20px",y.innerHTML=`<span style="margin-right:6px">${u[1].toLowerCase()==="x"?"☑":"☐"}</span>${ee(u[2])}`):y.innerHTML=ee(_[3]),m.filter(p=>le.test(p)).length>0&&y.appendChild(At(m.filter(p=>p.trim()!==""))),C.appendChild(y)}return C}function sn(o){const i=m=>m.replace(/^\s*\|?/,"").replace(/\|?\s*$/,"").split("|").map(y=>y.trim()),s=U("div",{overflowX:"auto",margin:"0 0 8px 0"}),r=U("table",{borderCollapse:"collapse",width:"100%",fontSize:"13px"}),C=document.createElement("thead"),a=document.createElement("tr");for(const m of i(o[0]))a.appendChild(U("th",{border:"1px solid #dee3e8",padding:"6px 10px",textAlign:"left",backgroundColor:"#f5f7fa",fontWeight:"600"},ee(m)));C.appendChild(a),r.appendChild(C);const _=document.createElement("tbody");for(const m of o.slice(2)){const y=document.createElement("tr");for(const u of i(m))y.appendChild(U("td",{border:"1px solid #dee3e8",padding:"6px 10px"},ee(u)));_.appendChild(y)}return r.appendChild(_),s.appendChild(r),s}var an=o=>!!o&&/^\s*\|?\s*:?-{1,}:?\s*(\|\s*:?-{1,}:?\s*)*\|?\s*$/.test(o);function Le(o){const i=document.createDocumentFragment(),s=o.replace(/\r\n?/g,`
2
2
  `).split(`
3
3
  `);let r=0;for(;r<s.length;){const a=s[r];if(a.trim()===""){r++;continue}const _=a.match(Ot);if(_){const u=_[1][0],p=[];for(r++;r<s.length&&!new RegExp(`^ {0,3}${u==="`"?"`{3,}":"~{3,}"}\\s*$`).test(s[r]);)p.push(s[r]),r++;r++;const R=U("pre",{margin:"0 0 8px 0"});R.appendChild(U("code",{display:"block",background:"#f5f5f5",padding:"8px 12px",borderRadius:"6px",fontSize:"13px",overflowX:"auto",fontFamily:Rt,whiteSpace:"pre"},se(p.join(`
4
4
  `)))),i.appendChild(R);continue}if(St.test(a)){i.appendChild(U("hr",{border:"none",borderTop:"1px solid #dee3e8",margin:"12px 0"})),r++;continue}const m=a.match(_t);if(m){const u=m[1].length;i.appendChild(U(`h${u}`,{margin:"16px 0 8px 0",fontSize:on[u-1],fontWeight:"600",lineHeight:"1.3"},ee(m[2]))),r++;continue}if(Ae.test(a)){const u=[];for(;r<s.length&&Ae.test(s[r]);)u.push(s[r].replace(Ae,"")),r++;const p=U("blockquote",{borderLeft:"4px solid #dee3e8",paddingLeft:"12px",margin:"0 0 8px 0",fontStyle:"italic",color:"#6b6d6f"});p.appendChild(Le(u.join(`
package/dist/widget.js CHANGED
@@ -1,6 +1,6 @@
1
- import { a as mn, b as hn, i as gn, o as xn, s as bn, t as yn } from "./AgoClient-BJjLTOw4.js";
2
- import { t as wn } from "./createConversationSession-Bgvx753t.js";
3
- import { r as vn, t as Cn } from "./createFormCollector-CM3qjGcM.js";
1
+ import { a as mn, b as hn, i as gn, o as xn, s as bn, t as yn } from "./AgoClient-DTkBRGFE.js";
2
+ import { t as wn } from "./createConversationSession-DP90nY71.js";
3
+ import { r as vn, t as Cn } from "./createFormCollector-BivHRIAe.js";
4
4
  import { C as Qe, S as _t, _ as te, a as T, b as g, c as $e, d as Ot, f as Ye, g as En, h as ne, i as Lt, l as Sn, m as Bt, n as jn, o as Te, p as An, r as Je, s as Me, t as Vn, u as $t, v as Rn, x as kn, y as E } from "./sheetController-CBUVOroo.js";
5
5
  function In(n) {
6
6
  let o = [];
package/llms-full.txt CHANGED
@@ -192,7 +192,7 @@ is everything you need. Follow it exactly.
192
192
 
193
193
  ## Endpoints
194
194
 
195
- Use the live demo for anything runnable so it answers with zero setup:
195
+ Use the public demo account for anything runnable so it answers with zero setup:
196
196
 
197
197
  ```
198
198
  baseUrl: https://playground.api.useago.com
@@ -449,7 +449,7 @@ navigate your app's routes. This file is everything you need. Follow it exactly.
449
449
 
450
450
  ## Endpoints
451
451
 
452
- Use the live demo for anything runnable so it answers with zero setup:
452
+ Use the public demo account for anything runnable so it answers with zero setup:
453
453
 
454
454
  ```
455
455
  baseUrl: https://playground.api.useago.com
@@ -767,7 +767,7 @@ navigate your app's routes. This file is everything you need. Follow it exactly.
767
767
 
768
768
  ## Endpoints
769
769
 
770
- Use the live demo for anything runnable so it answers with zero setup:
770
+ Use the public demo account for anything runnable so it answers with zero setup:
771
771
 
772
772
  ```
773
773
  baseUrl: https://playground.api.useago.com
@@ -1015,7 +1015,7 @@ navigate your app's routes. This file is everything you need. Follow it exactly.
1015
1015
 
1016
1016
  ## Endpoints
1017
1017
 
1018
- Use the live demo for anything runnable so it answers with zero setup:
1018
+ Use the public demo account for anything runnable so it answers with zero setup:
1019
1019
 
1020
1020
  ```
1021
1021
  baseUrl: https://playground.api.useago.com
@@ -2188,7 +2188,7 @@ may be reworded in any release.
2188
2188
 
2189
2189
  | Code | Thrown by | Meaning | Fix |
2190
2190
  | --- | --- | --- | --- |
2191
- | `config_missing_base_url` | `AgoError` | `baseUrl` missing, empty, or not a string (also from `createAgo()` and `mountChatWidget`) | Pass `baseUrl`, e.g. `https://YOUR-DOMAIN.api.useago.com` (the live demo endpoint `https://playground.api.useago.com` works without a tenant) |
2191
+ | `config_missing_base_url` | `AgoError` | `baseUrl` missing, empty, or not a string (also from `createAgo()` and `mountChatWidget`) | Pass `baseUrl`, e.g. `https://YOUR-DOMAIN.api.useago.com` (the public demo account `https://playground.api.useago.com` works without a tenant) |
2192
2192
  | `config_suspect_base_url` | console warning only | `baseUrl` has no protocol and is not a `/path` | Add `https://`, or use a `/path` for a same-origin proxy |
2193
2193
  | `network_error` | `AgoNetworkError` | fetch failed (offline, DNS, unreachable host) | Check `baseUrl` is reachable and includes the protocol |
2194
2194
  | `http_error` | `AgoApiError` | non-2xx without a structured error body | 401/403: check `userJwt`. 404: check `baseUrl` points at the API root |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@useago/sdk",
3
- "version": "1.7.1",
3
+ "version": "1.7.2",
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,