@useago/sdk 1.4.4 → 1.5.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 +63 -1
- package/dist/AgoClient-5VGybmvz.cjs +8 -0
- package/dist/AgoClient-DXrH2AMi.js +964 -0
- package/dist/angular.cjs +1 -1
- package/dist/angular.d.cts +124 -5
- package/dist/angular.d.ts +124 -5
- package/dist/angular.js +5 -1
- package/dist/autoContinue-CC8K9mBU.js +63 -0
- package/dist/autoContinue-CP9pJR-V.cjs +1 -0
- package/dist/{createConversationSession-CUkNp6mZ.cjs → createConversationSession-0WTqcCLK.cjs} +1 -1
- package/dist/{createConversationSession-QIBN0gLx.js → createConversationSession-DPrrr70o.js} +1 -1
- package/dist/createFormCollector-1GKKwQV_.cjs +1 -0
- package/dist/{createFormCollector-F3YJfsbg.js → createFormCollector-DYh90kiG.js} +97 -91
- package/dist/devtools.d.cts +82 -5
- package/dist/devtools.d.ts +82 -5
- package/dist/functions-CPs7omgM.cjs +1 -0
- package/dist/helpers.cjs +1 -1
- package/dist/helpers.d.cts +5 -0
- package/dist/helpers.d.ts +5 -0
- package/dist/helpers.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +147 -7
- package/dist/index.d.ts +147 -7
- package/dist/index.js +45 -43
- package/dist/react.cjs +3 -3
- package/dist/react.d.cts +191 -21
- package/dist/react.d.ts +191 -21
- package/dist/react.js +666 -529
- package/dist/testing.cjs +1 -1
- package/dist/testing.d.cts +82 -5
- package/dist/testing.d.ts +82 -5
- package/dist/testing.js +1 -1
- package/dist/vue.cjs +1 -1
- package/dist/vue.d.cts +82 -5
- package/dist/vue.d.ts +82 -5
- package/dist/vue.js +1 -1
- package/dist/widget.cjs +4 -4
- package/dist/widget.d.cts +82 -5
- package/dist/widget.d.ts +82 -5
- package/dist/widget.js +437 -423
- package/llms-full.txt +100 -6
- package/package.json +1 -1
- package/dist/AgoClient-CLmtYTJx.cjs +0 -8
- package/dist/AgoClient-Ozz2b1dQ.js +0 -912
- package/dist/createFormCollector-DHT1ObOb.cjs +0 -1
- package/dist/functions-Djnq-JAo.cjs +0 -1
- package/dist/rolldown-runtime-16Nf8qvH.cjs +0 -1
- /package/dist/{createMockClient-BSr-UV8R.cjs → createMockClient-C-wrjb2C.cjs} +0 -0
- /package/dist/{createMockClient-bAZ9KBHC.js → createMockClient-we-XoPom.js} +0 -0
- /package/dist/{functions-CApuQZ2b.js → functions-tzyOZNp6.js} +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -5,10 +5,66 @@ 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
|
-
## [
|
|
8
|
+
## [1.5.2] - 2026-07-13
|
|
9
9
|
|
|
10
10
|
### Added
|
|
11
11
|
|
|
12
|
+
- `ContextEntry.stable`: mark a client-context entry as constant for the whole
|
|
13
|
+
conversation. The backend pins stable entries right after the system prompt,
|
|
14
|
+
where LLM providers cache them across turns, instead of re-sending them next
|
|
15
|
+
to every new user message. Backends without support ignore the flag.
|
|
16
|
+
|
|
17
|
+
### Changed
|
|
18
|
+
|
|
19
|
+
- Form collectors register two context entries instead of one: a stable
|
|
20
|
+
`form:<name>:definition` entry carrying the description and full schema
|
|
21
|
+
(cached across turns), and the existing `form:<name>` entry carrying only
|
|
22
|
+
the live state (values, missing, complete, submitted). The agent sees the
|
|
23
|
+
same information; the schema just stops being re-processed on every message.
|
|
24
|
+
The duplicated "Data collected so far" copy of the values was dropped from
|
|
25
|
+
the description (they ride in `data`). `FormCollector` exposes the new
|
|
26
|
+
`definitionContextKey` / `definitionContextProvider`; `install` registers
|
|
27
|
+
and removes both entries.
|
|
28
|
+
|
|
29
|
+
### Fixed
|
|
30
|
+
|
|
31
|
+
- Widget: lock background scroll on mobile full-screen panels so the page behind
|
|
32
|
+
the sheet no longer scrolls or rubber-bands (notably iOS Safari, where
|
|
33
|
+
`overflow: hidden` does not stop touch scrolling). The body is pinned with the
|
|
34
|
+
fixed-body method and its scroll position restored on close; ref-counted so
|
|
35
|
+
stacked widgets don't clobber each other's saved offset.
|
|
36
|
+
|
|
37
|
+
## [1.5.1] - 2026-07-08
|
|
38
|
+
|
|
39
|
+
### Added
|
|
40
|
+
|
|
41
|
+
- Approval gate for client functions (pause mode): `AgoConfig.approvalPolicy`
|
|
42
|
+
and a per-function `requiresApproval: true` flag (on `registerFunction`,
|
|
43
|
+
`useAgoFunction`, and `useAgoPageState`) hold a call at `WAITING_CLIENT`
|
|
44
|
+
instead of running it. The SDK emits `function:awaiting-approval`; call
|
|
45
|
+
`client.approveFunction(invocationId)` to run and resume the turn, or
|
|
46
|
+
`client.rejectFunction(invocationId)` to submit a rejection the agent sees.
|
|
47
|
+
Placeholder mode has no paused turn to hold, so the gate is a no-op there. The
|
|
48
|
+
gate also applies after a page reload: `resumePendingClientFunctions` holds a
|
|
49
|
+
gated call for approval instead of re-running it unattended.
|
|
50
|
+
- React: `useAgoActivity()` hook, a normalized live feed of the agent's actions
|
|
51
|
+
(navigations, page-state changes, forms, confirmations, status, progress)
|
|
52
|
+
with `approve` / `reject` / `submitForm` controls for items awaiting the user.
|
|
53
|
+
The feed survives a page refresh, rebuilding the resolved activity from a
|
|
54
|
+
restored conversation.
|
|
55
|
+
|
|
56
|
+
## [1.5.0] - 2026-07-07
|
|
57
|
+
|
|
58
|
+
### Added
|
|
59
|
+
|
|
60
|
+
- `attachAutoContinueAfterNavigation(client, options?)`: the auto-continue
|
|
61
|
+
behavior ("go to page B and change X" in one user message) is now a
|
|
62
|
+
framework-agnostic core export, returning a detach function. The React hook
|
|
63
|
+
keeps its API and delegates to it.
|
|
64
|
+
- Angular: `AgoService.enableAutoContinueAfterNavigation(options?)` enables
|
|
65
|
+
auto-continue after navigation and returns the disable function (call it in
|
|
66
|
+
`ngOnDestroy`). `AgoAutoContinueOptions` is exported from
|
|
67
|
+
`@useago/sdk/angular`.
|
|
12
68
|
- `AgoConfig.warnOnEmptyReply` (default `true`) and a `message:empty` event:
|
|
13
69
|
a reply that completes `DONE` with no content, tool calls, or follow-ups
|
|
14
70
|
(usually an unknown `agent` slug) now warns on the console once per
|
|
@@ -25,6 +81,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
25
81
|
|
|
26
82
|
### Changed
|
|
27
83
|
|
|
84
|
+
- `clientFunctionsMode` now defaults to `"pause"`: with client functions
|
|
85
|
+
registered, the turn stops on the client function call(s) and resumes the
|
|
86
|
+
SAME turn once the results are submitted, so the agent sees the real
|
|
87
|
+
results. Backends without pause/resume support ignore the flag and keep the
|
|
88
|
+
old placeholder behavior. Set `clientFunctionsMode: "placeholder"` (config
|
|
89
|
+
or per message) to opt back into the legacy mode.
|
|
28
90
|
- `new AgoClient({})` (or missing/empty `baseUrl`) now throws an actionable
|
|
29
91
|
`AgoError` (`config_missing_base_url`) instead of a raw `TypeError`.
|
|
30
92
|
Same-origin `/path` baseUrls remain supported; a baseUrl with no protocol
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
var d=class extends Error{constructor(t,e,n){super(t),this.code=e,this.statusCode=n,this.name="AgoError"}},g=class x extends d{constructor(e,n,i,s,o,a){super(e,n,i),this.type=s,this.param=o,this.docUrl=a,this.name="AgoApiError"}static fromResponse(e,n){const i=e.error;return new x(i.doc_url?`${i.message} See ${i.doc_url}`:i.message,i.code,n,i.type,i.param,i.doc_url)}},y=class extends d{constructor(t,e){super(t,"network_error"),this.originalError=e,this.name="AgoNetworkError"}},C=class extends d{constructor(t,e="stream_error"){super(t,e),this.name="AgoStreamError"}},E=class extends d{constructor(t,e,n){super(t,"function_error"),this.functionName=e,this.originalError=n,this.name="AgoFunctionError"}},P=class{constructor(t=!1){this.enabled=t}enable(){this.enabled=!0}disable(){this.enabled=!1}log(...t){this.enabled&&console.log("[AGO SDK]",...t)}warn(...t){this.enabled&&console.warn("[AGO SDK]",...t)}error(...t){console.error("[AGO SDK]",...t)}debug(...t){this.enabled&&console.debug("[AGO SDK]",...t)}},c=new P,S="ago_widget_id";function j(){if(typeof localStorage<"u"){const e=localStorage.getItem(S);if(e)return e}const t=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(S,t)}catch{}return t}var O=class{constructor(t){this.baseUrl=t.baseUrl.replace(/\/$/,""),this.headers={"X-User-Anon-Id":t.widgetId||j()},t.userEmail&&(this.headers["X-User-Email"]=t.userEmail),t.userJwt&&(this.headers.Authorization=`Bearer ${t.userJwt}`),t.permission&&(this.headers["X-Widget-Permission"]=t.permission)}updateConfig(t){t.baseUrl&&(this.baseUrl=t.baseUrl.replace(/\/$/,"")),t.widgetId&&(this.headers["X-User-Anon-Id"]=t.widgetId),t.userEmail&&(this.headers["X-User-Email"]=t.userEmail),t.userJwt&&(this.headers.Authorization=`Bearer ${t.userJwt}`),t.permission!==void 0&&(t.permission?this.headers["X-Widget-Permission"]=t.permission:delete this.headers["X-Widget-Permission"])}async get(t){return this.request("GET",t)}async post(t,e){return this.request("POST",t,e)}async postStream(t,e){const n=`${this.baseUrl}${t}`;c.debug("POST (stream)",n,e);try{const i=await fetch(n,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:e?JSON.stringify(e):void 0});return i.ok||await this.handleErrorResponse(i),i}catch(i){throw i instanceof g?i:new y(`Network error: ${i instanceof Error?i.message:"Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`,i instanceof Error?i:void 0)}}async postFormData(t,e){const n=`${this.baseUrl}${t}`;c.debug("POST (formData)",n);const i={...this.headers};try{const s=await fetch(n,{method:"POST",headers:i,body:e});return s.ok||await this.handleErrorResponse(s),s}catch(s){throw s instanceof g?s:new y(`Network error: ${s instanceof Error?s.message:"Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`,s instanceof Error?s:void 0)}}async request(t,e,n){const i=`${this.baseUrl}${e}`;c.debug(t,i,n);try{const s=await fetch(i,{method:t,headers:{...this.headers,"Content-Type":"application/json"},body:n?JSON.stringify(n):void 0});return s.ok||await this.handleErrorResponse(s),s.status===204?void 0:s.json()}catch(s){throw s instanceof g?s:new y(`Network error: ${s instanceof Error?s.message:"Unknown error"}. Check that \`baseUrl\` is reachable and includes the protocol (https://).`,s instanceof Error?s:void 0)}}async handleErrorResponse(t){let e;try{e=await t.json()}catch{}if(e?.error)throw g.fromResponse(e,t.status);let n="";throw t.status===401||t.status===403?n=" Check `userJwt` (and that it has not expired).":t.status===404&&(n=" Check that `baseUrl` points at your AGO API root."),new g(`HTTP ${t.status}: ${t.statusText}.${n}`,"http_error",t.status,"api_error")}},D=5e4,M=2e4,B=2e3,F=class{constructor(t){this.functions=new Map,this.defaultMaxResultBytes=t?.maxResultBytes??D}setDefaultMaxResultBytes(t){this.defaultMaxResultBytes=t}register(t,e,n){if(typeof t=="object"){const{name:r,handler:l,description:u,parameters:h,maxResultBytes:m,requiresApproval:p}=t;return this.register(r,l,{description:u,parameters:h,maxResultBytes:m,requiresApproval:p})}const i=t;if(!e||!n)throw new d(`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)&&c.warn(`Function "${i}" is being overwritten`);const{maxResultBytes:s,requiresApproval:o,...a}=n;this.functions.set(i,{schema:{...a,name:i},handler:e,maxResultBytes:s,requiresApproval:o}),c.log(`Registered function: ${i}`)}unregister(t){const e=this.functions.delete(t);return e&&c.log(`Unregistered function: ${t}`),e}get(t){return this.functions.get(t)}has(t){return this.functions.has(t)}getSchemas(){return Array.from(this.functions.values()).map(t=>t.schema)}async execute(t,e){const n=this.functions.get(t);if(!n)throw new E(`Function "${t}" is not registered`,t);c.log(`Executing function: ${t}`,e);try{const i=await n.handler(e);return c.log(`Function ${t} completed:`,i),this.guardResultSize(t,i,n.maxResultBytes)}catch(i){throw c.error(`Function ${t} failed:`,i),new E(`Function "${t}" execution failed: ${i instanceof Error?i.message:"Unknown error"}`,t,i instanceof Error?i:void 0)}}guardResultSize(t,e,n){let i;try{i=JSON.stringify(e)}catch{return e}if(i===void 0)return e;const s=new TextEncoder().encode(i).length,o=n??this.defaultMaxResultBytes;return s>o?(c.warn(`Function "${t}" result is ${s} bytes, over the ${o}-byte limit; a truncated preview was sent to the agent instead. Return fewer fields, paginate, or raise maxResultBytes for this function.`),{truncated:!0,originalBytes:s,maxBytes:o,preview:i.slice(0,B),hint:`The result of "${t}" exceeded the ${o}-byte limit and was truncated. Request less data (use limit or filter parameters if available), or tell the user the result is too large to process.`}):(s>M&&c.warn(`Function "${t}" returned a large result (${Math.round(s/1024)} KB). Large results consume LLM context: return fewer fields, paginate, or push the data to the UI and return a summary.`),e)}clear(){this.functions.clear(),c.log("Cleared all registered functions")}get size(){return this.functions.size}},k=class{constructor(){this.entries=new Map,this.dynamicProviders=new Map}set(t,e){this.entries.set(t,e),c.log(`ClientContext set: ${t}`)}remove(t){const e=this.entries.delete(t);return e&&c.log(`ClientContext removed: ${t}`),e}addDynamicProvider(t,e){this.dynamicProviders.set(t,e),c.log(`DynamicContext provider added: ${t}`)}removeDynamicProvider(t){const e=this.dynamicProviders.delete(t);return e&&c.log(`DynamicContext provider removed: ${t}`),e}getSnapshot(){if(this.entries.size===0&&this.dynamicProviders.size===0)return null;const t={};for(const[e,n]of this.entries)t[e]=n;for(const[e,n]of this.dynamicProviders)try{const i=n();i&&(t[e]=i)}catch(i){c.error(`DynamicContext provider "${e}" threw:`,i)}return Object.keys(t).length===0?null:{entries:t}}clear(){this.entries.clear(),this.dynamicProviders.clear(),c.log("ClientContext cleared")}};function _(t){return t===null||typeof t!="object"?JSON.stringify(t)??"null":Array.isArray(t)?`[${t.map(_).join(",")}]`:`{${Object.keys(t).sort().map(e=>`${JSON.stringify(e)}:${_(t[e])}`).join(",")}}`}var I=class{constructor(t){this.callbacks=t,this.buffer="",this.message={},this.toolCalls=[],this.sources=[],this.followUpReplies=[],this.isFirstChunk=!0,this.answerCompleteEmitted=!1,this.waitingClientEmitted=!1,this.firedClientFunctions=new Set}async processStream(t){if(!t.body)throw new C("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 e=t.body.getReader(),n=new TextDecoder;try{for(;;){const{done:i,value:s}=await e.read();if(i)break;const o=n.decode(s,{stream:!0});this.buffer+=o,this.processBuffer()}return this.buffer.trim()&&this.processBuffer(),this.buildFinalMessage()}catch(i){const s=i instanceof Error?i:new C("Stream processing failed mid-flight. The connection may have dropped; retry the message.");throw this.callbacks.onError?.(s),s}finally{e.releaseLock()}}processBuffer(){const t=this.buffer.split(`
|
|
2
|
+
|
|
3
|
+
`);this.buffer=t.pop()||"";for(const e of t){if(!e.trim())continue;const n=e.split(`
|
|
4
|
+
`);for(const i of n)if(!i.startsWith(": ")&&i.startsWith("data: ")){const s=i.slice(6);try{const o=JSON.parse(s);this.handleChunk(o)}catch(o){c.warn("Failed to parse SSE data:",s,o)}}}}handleChunk(t){if(this.callbacks.onRawChunk?.(t),t.message_id&&!this.message.id&&(this.message.id=t.message_id),t.thread?.id&&(this.message.conversationId=t.thread.id,this.isFirstChunk&&this.message.id&&(this.isFirstChunk=!1,this.callbacks.onStart?.({conversationId:this.message.conversationId,messageId:this.message.id}))),t.content!==void 0&&(this.message.content=(this.message.content||"")+t.content,this.message.conversationId&&this.message.id&&this.callbacks.onChunk?.({content:t.content,conversationId:this.message.conversationId,messageId:this.message.id})),t.full_content!==void 0&&(this.message.content=t.full_content),t.status&&(this.message.status=t.status),t.agent&&(this.message.agent={id:t.agent.id,name:t.agent.name,displayName:t.agent.display_name}),t.knowledge_sources&&(this.sources=t.knowledge_sources.map(e=>{const n=e.knowledge_document;return{id:n.id,title:n.title,url:n.use_external_link?n.external_link_url:n.internal_link_url}})),t.type==="client_function"&&t.function_name){const e=`${t.function_name}::${_(t.arguments??{})}`;this.firedClientFunctions.has(e)||(this.firedClientFunctions.add(e),this.callbacks.onClientFunction?.({invocationId:t.id||"",functionName:t.function_name,arguments:t.arguments||{},conversationId:this.message.conversationId||""}))}if(t.tool_call_data&&t.type&&t.type!=="client_function"){const e=this.parseToolCall(t);this.callbacks.onToolCall?.(e);const n=this.toolCalls.findIndex(i=>i.id===e.id);n>=0?this.toolCalls[n]=e:this.toolCalls.push(e)}t.follow_up_replies&&(this.followUpReplies=t.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:t.waiting_tool_call_ids??[]}))}parseToolCall(t){return{id:t.id||"",type:t.type||"status_message",status:t.status||"unknown",toolName:t.tool_name||"",toolDisplayName:t.tool_display_name,message:t.message,formSchema:t.form_schema,data:t.data,functionName:t.function_name,arguments:t.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 t=this.buildMessage();return t.status!=="WAITING_CLIENT"&&this.callbacks.onComplete?.(t),t}};function L(t){const e=t.message.toLowerCase();return e.includes("load failed")||e.includes("failed to fetch")||e.includes("network")||e.includes("abort")}var G=new Set(["image/jpeg","image/png","image/gif","image/webp","image/bmp","image/tiff"]);function U(t){if(!t)return;const e=typeof window<"u"&&window.location?window.location.href:"https://ago.local/";try{const n=new URL(t,e);if(n.protocol==="http:"||n.protocol==="https:"||n.protocol==="blob:")return t}catch{}}function W(t){return t.isSafeImage===!0&&typeof t.contentType=="string"&&t.contentType.startsWith("image/")&&U(t.url)!==void 0}function q(t){if(t==null||t<0)return"";if(t<1024)return`${t} B`;const e=t/1024;return e<1024?`${e.toFixed(1)} KB`:`${(e/1024).toFixed(1)} MB`}function z(t){return{id:String(t.id??""),name:typeof t.name=="string"&&t.name?t.name:"file",contentType:typeof t.content_type=="string"?t.content_type:void 0,fileSize:typeof t.file_size=="number"?t.file_size:void 0,url:typeof t.file_url=="string"?t.file_url:void 0,isSafeImage:t.is_safe_image===!0}}function J(t){return t.map((e,n)=>({id:`local-${n}-${e.name}`,name:e.name,contentType:e.type||void 0,fileSize:e.size,url:typeof URL<"u"&&URL.createObjectURL?URL.createObjectURL(e):void 0,isSafeImage:G.has(e.type)}))}var N=class{constructor(){this.handlers=new Map}on(t,e){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t).add(e)}off(t,e){const n=this.handlers.get(t);n&&n.delete(e)}emit(t,e){const n=this.handlers.get(t);n&&n.forEach(i=>{try{i(e)}catch(s){console.error(`Error in event handler for ${String(t)}:`,s)}})}once(t,e){const n=(i=>{this.off(t,n),e(i)});this.on(t,n)}waitFor(t,e){return new Promise((n,i)=>{let s;const o=(a=>{s&&clearTimeout(s),n(a)});this.once(t,o),e?.timeout&&(s=setTimeout(()=>{this.off(t,o),i(new Error(`waitFor("${String(t)}") timed out after ${e.timeout}ms`))},e.timeout))})}removeAllListeners(t){t?this.handlers.delete(t):this.handlers.clear()}},A='`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).',H=/^[a-z][a-z0-9+.-]*:\/\//i,$=!1;function R(t,e="AgoClient"){if(typeof t!="object"||t===null)throw new d(`${e}: ${A}`,"config_missing_base_url");const n=t.baseUrl;if(typeof n!="string"||n.trim()==="")throw new d(`${e}: ${A}`,"config_missing_base_url");!n.startsWith("/")&&!H.test(n)&&($||($=!0,console.warn(`[AGO] ${e}: \`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 K(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function b(t){return t.split("/").filter(e=>e.startsWith(":")).map(e=>e.slice(1))}function X(t,e){const n=[];return{path:t.split("/").map(i=>{if(!i.startsWith(":"))return i;const s=i.slice(1),o=e[s];return o==null||o===""?(n.push(s),i):encodeURIComponent(String(o))}).join("/"),missing:n}}function Y(t,e){const n=e.find(s=>s.path===t);if(n)return n;const i=e.find(s=>{if(!s.path.includes(":"))return!1;const o="^"+s.path.split("/").map(a=>a.startsWith(":")?"[^/]+":K(a)).join("/")+"/?$";return new RegExp(o).test(t)});return i||e.filter(s=>s.path!=="/"&&t.startsWith(s.path)).sort((s,o)=>o.path.length-s.path.length)[0]}var V=class T{constructor(e){this.warnedEmptyConversations=new Set,this.pendingResumes=new Map,this.pendingApprovals=new Map,this.resumeGate=null,R(e,"AgoClient"),this.config=e,this.httpClient=new O(e),this.functionRegistry=new F({maxResultBytes:e.maxFunctionResultBytes}),this.contextRegistry=new k,this.eventEmitter=new N,e.debug&&c.enable(),c.log("AgoClient initialized")}async sendMessage(e,n){const i=this.functionRegistry.getSchemas(),s=this.contextRegistry.getSnapshot(),o=this.config.agent||this.config.defaultAgentId,a=this.resolveClientFunctionsMode(n),r={content:e,conversation_id:n?.conversationId,agent_id:n?.agentId||o};i.length>0&&(r.client_functions=i,a==="pause"&&(r.client_functions_mode=a)),s&&(r.client_context=s),n?.hidden&&(r.hidden=!0);let l;if(n?.files&&n.files.length>0){const u=new FormData;u.append("content",e),n.conversationId&&u.append("conversation_id",n.conversationId),(n.agentId||o)&&u.append("agent_id",n.agentId||o||""),i.length>0&&(u.append("client_functions",JSON.stringify(i)),a==="pause"&&u.append("client_functions_mode",a)),s&&u.append("client_context",JSON.stringify(s)),n.hidden&&u.append("hidden","true");for(const h of n.files)u.append("files",h);l=await this.httpClient.postFormData("/api/sdk/v1/messages",u)}else l=await this.httpClient.postStream("/api/sdk/v1/messages",r);return this.processSSEResponse(l)}async processSSEResponse(e){let n=!1;const i=await new I({onRawChunk:s=>{this.eventEmitter.emit("stream:message",s)},onStart:s=>{this.eventEmitter.emit("message:start",s)},onChunk:s=>{this.eventEmitter.emit("message:chunk",s)},onToolCall:s=>{this.eventEmitter.emit("toolCall:received",s),s.type==="form"&&this.eventEmitter.emit("toolCall:form",s)},onClientFunction:async s=>{if(n=!0,this.eventEmitter.emit("function:invoke",s),s.invocationId&&this.requiresApproval(s)){this.pendingApprovals.set(s.invocationId,s),this.eventEmitter.emit("function:awaiting-approval",s);return}await this.handleClientFunctionInvocation(s)},onAnswerComplete:s=>{this.eventEmitter.emit("message:answer-complete",s)},onWaitingClient:s=>{this.eventEmitter.emit("message:waiting-client",s),this.markResumeSignal(s.messageId,s.conversationId,"waitingConfirmed")},onComplete:s=>{this.eventEmitter.emit("message:complete",s)},onError:s=>{this.eventEmitter.emit("message:error",{error:s.message,code:s instanceof d?s.code:void 0})}}).processStream(e);return i.status!=="WAITING_CLIENT"&&this.maybeFlagEmptyReply(i,n),i}resolveClientFunctionsMode(e){return e?.clientFunctionsMode??this.config.clientFunctionsMode??"pause"}registerResumeGate(e){return this.resumeGate=e,()=>{this.resumeGate===e&&(this.resumeGate=null)}}async continueMessage(e){const n=this.functionRegistry.getSchemas(),i=this.contextRegistry.getSnapshot(),s={};n.length>0&&(s.client_functions=n),i&&(s.client_context=i);const o=await this.httpClient.postStream(`/api/sdk/v1/messages/${e}/continue`,s);return this.processSSEResponse(o)}markResumeSignal(e,n,i){if(!e)return;const s=this.pendingResumes.get(e)??{conversationId:n,waitingConfirmed:!1,resultsReady:!1,started:!1};s[i]=!0,n&&(s.conversationId=n),this.pendingResumes.set(e,s),!(!s.waitingConfirmed||!s.resultsReady||s.started)&&(s.started=!0,this.runAutoResume(e,s.conversationId))}async runAutoResume(e,n){try{this.resumeGate&&await this.resumeGate({conversationId:n,messageId:e})}catch(i){c.warn("Resume gate threw; resuming anyway:",i)}this.pendingResumes.delete(e);try{await this.continueMessage(e)}catch(i){c.warn("Auto-resume of paused turn failed:",i)}}maybeFlagEmptyReply(e,n){e.status==="DONE"&&(e.content??"").trim()===""&&!n&&!(e.toolCalls&&e.toolCalls.length>0)&&!(e.followUpReplies&&e.followUpReplies.length>0)&&setTimeout(()=>{if(this.eventEmitter.emit("message:empty",{conversationId:e.conversationId??"",messageId:e.id??""}),this.config.warnOnEmptyReply===!1)return;const i=e.conversationId||"(no conversation)";if(this.warnedEmptyConversations.has(i))return;this.warnedEmptyConversations.add(i);const s=this.config.agent||this.config.defaultAgentId;e.id?console.warn("[AGO] Reply completed with empty content. Possible causes: "+(s?`the agent "${s}" 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: "+(s?`the agent "${s}" 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(e){let n,i;try{n=await this.functionRegistry.execute(e.functionName,e.arguments)}catch(s){i=s instanceof Error?s.message:"Unknown error",c.error("Client function execution failed:",s)}if(e.invocationId)try{const s=await this.submitToolCallForm(e.invocationId,{result:n,error:i,_type:"client_function_result"});s?.resume?.ready&&this.markResumeSignal(s.resume.message_id,e.conversationId,"resultsReady")}catch(s){c.error("Failed to submit function result:",s)}this.eventEmitter.emit("function:result",{invocationId:e.invocationId,result:n,error:i})}requiresApproval(e){const n=this.config.approvalPolicy;if(n)try{if(n(e))return!0}catch(i){c.warn("approvalPolicy threw; not gating this call:",i)}return this.functionRegistry.get(e.functionName)?.requiresApproval===!0}async approveFunction(e){const n=this.pendingApprovals.get(e);n&&(this.pendingApprovals.delete(e),await this.handleClientFunctionInvocation(n))}async rejectFunction(e){const n=this.pendingApprovals.get(e);if(!n)return;this.pendingApprovals.delete(e);const i={approved:!1,reason:"user_rejected"};try{const s=await this.submitToolCallForm(e,{result:i,_type:"client_function_result"});s?.resume?.ready&&this.markResumeSignal(s.resume.message_id,n.conversationId,"resultsReady")}catch(s){c.error("Failed to submit function rejection:",s)}this.eventEmitter.emit("function:result",{invocationId:e,result:i})}async getConversations(){return(await this.httpClient.get("/api/sdk/v1/conversations")).items.map(e=>({id:e.id,title:e.title,lastMessageDate:new Date(e.last_message_date)}))}async getConversation(e){const n=await this.httpClient.get(`/api/sdk/v1/conversations/${e}`),i={id:n.id,title:n.title,lastMessageDate:new Date(n.last_message_date),messages:n.messages.map(s=>({id:s.id,conversationId:n.id,content:s.content,role:s.role,status:s.status,createdAt:new Date(s.created_at),hidden:s.hidden,toolCalls:T.mapPersistedToolCalls(s.tool_call_data),attachments:s.attachments&&s.attachments.length>0?s.attachments.map(z):void 0}))};return this.eventEmitter.emit("conversation:loaded",i),i}static mapPersistedToolCalls(e){if(!(!e||e.length===0))return e.map(n=>({id:String(n.id??""),type:n.type??"status_message",status:String(n.status??"unknown"),toolName:n.tool_name??"",toolDisplayName:n.tool_display_name,message:n.message,formSchema:n.form_schema,data:n.data,functionName:n.function_name,arguments:n.arguments}))}async getMessages(e){return(await this.getConversation(e)).messages||[]}async resumePendingClientFunctions(e){const n=[...e.messages??[]].reverse().find(r=>r.role==="assistant"&&r.status==="WAITING_CLIENT");if(!n)return null;const i=(n.toolCalls??[]).filter(r=>r.type==="client_function"&&r.status==="waiting_input"&&r.functionName),s=new Set(this.functionRegistry.getSchemas().map(r=>r.name)),o=i.filter(r=>!s.has(r.functionName));if(o.length>0)return c.warn("Cannot resume paused turn: function(s) not registered on this page:",o.map(r=>r.functionName)),null;let a=i.length===0;for(const r of i){const l={invocationId:r.id,functionName:r.functionName,arguments:r.arguments??{},conversationId:e.id};if(this.requiresApproval(l)){this.pendingApprovals.set(r.id,l),this.markResumeSignal(n.id,e.id,"waitingConfirmed"),this.eventEmitter.emit("function:awaiting-approval",l),a=!1;continue}let u,h;try{u=await this.functionRegistry.execute(r.functionName,r.arguments??{})}catch(m){h=m instanceof Error?m.message:"Unknown error",c.error("Client function execution failed:",m)}a=(await this.submitToolCallForm(r.id,{result:u,error:h,_type:"client_function_result"}))?.resume?.ready??a}return a?this.continueMessage(n.id):null}async submitToolCallForm(e,n){return this.httpClient.post(`/api/sdk/v1/tool-calls/${e}/submit`,{formData:n})}async confirmToolCall(e){await this.httpClient.post(`/api/tool-calls/${e}/confirm/`)}async rejectToolCall(e){await this.httpClient.post(`/api/tool-calls/${e}/reject/`)}async getFormCollector(e){const n=await this.httpClient.get(`/api/sdk/v1/forms/${encodeURIComponent(e)}`);return{name:n.name,description:n.description,schema:n.schema,submit:n.submit??void 0}}async submitFormCollector(e,n){return this.httpClient.post("/api/sdk/v1/forms/submit",{name:e,values:n})}async submitFeedback(e,n){await this.httpClient.post(`/api/sdk/v1/messages/${e}/feedback`,{rating:n})}registerFunction(e,n,i){typeof e=="object"?this.functionRegistry.register(e):this.functionRegistry.register(e,n,i)}register(e){if(Array.isArray(e))for(const n of e)this.functionRegistry.register(n);else this.functionRegistry.register(e)}unregisterFunction(e){return this.functionRegistry.unregister(e)}getRegisteredFunctions(){return this.functionRegistry.getSchemas()}registerNavigationFunction(e,n){const i=n.map(r=>r.name),s=n.map(r=>{const l=b(r.path),u=l.length>0?` (requires ${l.map(h=>`"${h}"`).join(", ")})`:"";return`- "${r.name}"${u}: ${r.description}`}).join(`
|
|
5
|
+
`),o=new Map;for(const r of n)for(const l of b(r.path))o.set(l,[...o.get(l)??[],r.name]);const a={page:{type:"string",description:"The page to navigate to",enum:i}};for(const[r,l]of o){if(r==="page"){c.error('registerNavigationFunction: a ":page" placeholder collides with the "page" argument and is ignored. Rename the placeholder.');continue}a[r]={type:"string",description:`Value for ":${r}" in the page path. Required when page is ${l.map(u=>`"${u}"`).join(" or ")}.`}}this.registerFunction("navigateToPage",async r=>{const l=r.page,u=n.find(f=>f.name===l);if(!u)return{success:!1,error:`Unknown page: ${l}`};let h={};if(typeof r.params=="string")try{h=JSON.parse(r.params)}catch{}else r.params&&typeof r.params=="object"&&(h=r.params);const m={};for(const f of b(u.path))m[f]=r[f]??h[f];const{path:p,missing:w}=X(u.path,m);if(w.length>0){const f=w.map(v=>`"${v}": "..."`).join(", ");return{success:!1,error:`Page "${l}" needs ${w.map(v=>`"${v}"`).join(", ")}. Retry with { "page": "${l}", ${f} }.`}}return e(p),{success:!0,navigatedTo:p}},{description:`Navigate the user to a page in the application. Available pages:
|
|
6
|
+
${s}`,parameters:{type:"object",properties:a,required:["page"]}}),this.addDynamicContext("current-page",()=>{if(typeof window>"u"||!window.location)return null;const r=window.location.href,l=typeof document<"u"?document.title:void 0,u=Y(window.location.pathname,n),h={url:r};return u&&(h.page=u.name),l&&(h.title=l),{name:"Current page",description:"The page the user is currently viewing.",data:h}})}unregisterNavigationFunction(){this.unregisterFunction("navigateToPage"),this.removeDynamicContext("current-page")}registerPageStateFunction(e,n){const i=n?.functionName??"setPageState",s=new Map(e.map(a=>[a.name,a])),o=e.map(a=>`- "${a.name}": ${a.description}`).join(`
|
|
7
|
+
`);this.registerFunction(i,async a=>{const r={};for(const[l,u]of Object.entries(a)){if(u===void 0)continue;const h=s.get(l);h&&(await h.set(u),r[l]=u)}return{success:!0,applied:r}},{description:`Change the state of the current page. Set ONLY the controls the user explicitly asked for; leave the others unset. Available controls:
|
|
8
|
+
${o}`,parameters:{type:"object",properties:Object.fromEntries(e.map(a=>[a.name,{...a.schema,description:a.description}]))},requiresApproval:n?.requiresApproval}),this.addDynamicContext(`page-state:${i}`,()=>{const a=e.filter(l=>typeof l.get=="function");if(a.length===0)return null;const r={};for(const l of a)r[l.name]=l.get();return{name:"Page state",description:"Current, editable state of the page the user is viewing.",data:r}})}unregisterPageStateFunction(e){const n=e??"setPageState";this.unregisterFunction(n),this.removeDynamicContext(`page-state:${n}`)}setContext(e,n){this.contextRegistry.set(e,n),this.notifyContextChanged()}removeContext(e){const n=this.contextRegistry.remove(e);return n&&this.notifyContextChanged(),n}addDynamicContext(e,n){this.contextRegistry.addDynamicProvider(e,n),this.notifyContextChanged()}removeDynamicContext(e){const n=this.contextRegistry.removeDynamicProvider(e);return n&&this.notifyContextChanged(),n}notifyContextChanged(){this.eventEmitter.emit("context:changed",this.contextRegistry.getSnapshot())}emitFormEvent(e,n){this.eventEmitter.emit(e,n)}enableAutoPageContext(){this.addDynamicContext("browser-page",()=>{const e=typeof window<"u"?window.location.href:void 0,n=typeof document<"u"?document.title:void 0;return!e&&!n?null:{name:"Browser page",description:"Current page the user is viewing",data:{url:e,title:n}}})}getContextSnapshot(){return this.contextRegistry.getSnapshot()}on(e,n){this.eventEmitter.on(e,n)}off(e,n){this.eventEmitter.off(e,n)}once(e,n){this.eventEmitter.once(e,n)}waitFor(e,n){return this.eventEmitter.waitFor(e,n)}updateConfig(e){const n={};for(const[s,o]of Object.entries(e))o!==void 0&&(n[s]=o);const i={...this.config,...n};R(i,"AgoClient.updateConfig"),this.config=i,this.httpClient.updateConfig(n),n.debug!==void 0&&(n.debug?c.enable():c.disable()),n.maxFunctionResultBytes!==void 0&&this.functionRegistry.setDefaultMaxResultBytes(n.maxFunctionResultBytes)}destroy(){this.eventEmitter.removeAllListeners(),this.functionRegistry.clear(),this.contextRegistry.clear(),this.pendingResumes.clear(),this.pendingApprovals.clear(),this.resumeGate=null,c.log("AgoClient destroyed")}};Object.defineProperty(exports,"AgoApiError",{enumerable:!0,get:function(){return g}});Object.defineProperty(exports,"AgoClient",{enumerable:!0,get:function(){return V}});Object.defineProperty(exports,"AgoError",{enumerable:!0,get:function(){return d}});Object.defineProperty(exports,"AgoFunctionError",{enumerable:!0,get:function(){return E}});Object.defineProperty(exports,"AgoNetworkError",{enumerable:!0,get:function(){return y}});Object.defineProperty(exports,"AgoStreamError",{enumerable:!0,get:function(){return C}});Object.defineProperty(exports,"ClientContextRegistry",{enumerable:!0,get:function(){return k}});Object.defineProperty(exports,"EventEmitter",{enumerable:!0,get:function(){return N}});Object.defineProperty(exports,"FunctionRegistry",{enumerable:!0,get:function(){return F}});Object.defineProperty(exports,"SSEHandler",{enumerable:!0,get:function(){return I}});Object.defineProperty(exports,"attachmentsFromFiles",{enumerable:!0,get:function(){return J}});Object.defineProperty(exports,"canInlineImage",{enumerable:!0,get:function(){return W}});Object.defineProperty(exports,"formatFileSize",{enumerable:!0,get:function(){return q}});Object.defineProperty(exports,"isStreamNetworkError",{enumerable:!0,get:function(){return L}});Object.defineProperty(exports,"logger",{enumerable:!0,get:function(){return c}});Object.defineProperty(exports,"safeAttachmentUrl",{enumerable:!0,get:function(){return U}});Object.defineProperty(exports,"validateConfig",{enumerable:!0,get:function(){return R}});
|