@cerebro-labs/agentnava-sdk 0.46.1 → 0.50.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -173,11 +173,18 @@ const reply = await conversation.ask('...'); // just the answer
173
173
 
174
174
  ```ts
175
175
  for await (const e of conversation.ask('...')) { // as it happens
176
+ if (e.type === 'progress') showSteps(e.steps); // the whole list, each time
176
177
  if (e.type === 'text') append(e.text);
178
+ if (e.type === 'file') show(await conversation.readFile(e.path));
177
179
  if (e.type === 'done') save(e.reply);
178
180
  }
179
181
  ```
180
182
 
183
+ `progress` lists the steps the AgentNava app shows while the agent works, in
184
+ the same words ("Searching the web: steel tariffs"), each `active`, `done` or
185
+ `error`. Replace what you show with each one. `file` names a file the agent
186
+ wrote, once per file.
187
+
181
188
  **The message is sent when you call `ask`**, not when you await or iterate it.
182
189
  Calling `ask` twice generates two submission keys and asks twice. If you need
183
190
  to identify an explicit retry after a lost response, save a key before sending:
@@ -400,6 +407,10 @@ explicit patent grant. Section 6 grants no rights to the names: "AgentNava"
400
407
  and "Cerebro Labs" remain trademarks of Cerebro Labs, Inc.
401
408
 
402
409
 
410
+ ### Widgets in replies (0.50)
411
+
412
+ `agent.start({ endUserId, widgets: true })` says your screen can draw cards, tables and charts. Each turn then streams `widget` events (a whole widget each time, replace it by `surfaceId`), `done` carries the final `widgets`, and `messages()` returns them on each reply. Continue one with `agent.conversation(id, { widgets: true })`. Widgets are Google's A2UI format (`Widget`, `WidgetPart`); draw them with any A2UI renderer. An agent's own `widgets: false` turns them off for it. The agent field's old meaning, a list of widget kinds nothing read, is gone, and so is the `widgets.json` file `loadAgentDir` used to load.
413
+
403
414
  ### Where an agent is live (0.41)
404
415
 
405
416
  `agent.get()` and `ws.agents.list()` carry a read-only `status`: where the agent is live, by the rule the API runs it by, and in `needs` any required account or secret not set up yet (it still runs; the tools that use them fail until they are).
package/agent.d.ts CHANGED
@@ -3,7 +3,7 @@ import { Conversation } from './conversation.ts';
3
3
  import type { Http } from './http.ts';
4
4
  import type { Secret } from './secret.ts';
5
5
  import { type Connection } from './connection.ts';
6
- import type { AgentData, AgentFields, Bindings, ConnectionStatus, FileEntry, Trigger, WebsiteChat, Workflow, WebhookDelivery } from './types.ts';
6
+ import type { AgentData, AgentFields, Bindings, ConnectionStatus, FileEntry, Trigger, WebsiteChat, WebsiteChatAccess, Workflow, WebhookDelivery } from './types.ts';
7
7
  export interface StartOptions {
8
8
  /**
9
9
  * Stored secrets to attach AS THE CONVERSATION STARTS.
@@ -95,6 +95,15 @@ export interface StartOptions {
95
95
  * conversation with a colleague's internal id and looked fine.
96
96
  */
97
97
  endUserId: string;
98
+ /**
99
+ * This conversation's screen can draw widgets: cards, tables and charts the
100
+ * agent writes inside its replies, in Google's A2UI format. Off unless set.
101
+ * When on, each turn's stream carries `widget` events and `done.widgets`,
102
+ * and `messages()` returns each reply's `widgets`. The agent draws only if
103
+ * its own "Answer with widgets" setting is on (it is, unless turned off).
104
+ * The SDK ships no screens: draw them with any A2UI renderer.
105
+ */
106
+ widgets?: boolean;
98
107
  }
99
108
  /**
100
109
  * An agent you can configure and start conversations from.
@@ -163,41 +172,43 @@ export declare class Agent {
163
172
  conversationId?: string;
164
173
  }>;
165
174
  /**
166
- * The agent's website chat: a public chat page, and the embed script that
167
- * puts it on your website. ON from the moment the agent is created, for
168
- * every agent, however it was made (here, through the API, or in the portal),
169
- * until you turn it off. The one exception is an agent that needs each
170
- * user's own account or secret, which a visitor cannot bring: it has none.
175
+ * The agent's website chat: its chat page on AgentNava (the share link),
176
+ * and the embed script that puts it on your website. Every agent has one
177
+ * from the moment it is created, however it was made (here, through the
178
+ * API, or in the portal), except an agent that needs each user's own
179
+ * account or secret, which a visitor cannot bring.
180
+ *
181
+ * Who can chat is one setting, `access`:
182
+ *
183
+ * 'restricted' the default. The share link works for members of your
184
+ * workspace who are signed in to AgentNava, so your team can
185
+ * pass it around to test. The chat shows on another website
186
+ * only when that website is on `allowedWebsites`.
187
+ * 'anyone' anyone with the link can chat, and any website can show
188
+ * the chat. Each visitor's turns are charged to your
189
+ * workspace.
171
190
  *
172
191
  * You never need it to use the agent from code: the agent answers your API
173
- * key, and the portal's Test, as soon as it exists.
174
- *
175
- * Anyone with the page link can talk to the agent, and each of their turns is
176
- * charged to your workspace, so turn it off for an agent only your own code
177
- * should reach. `turnOn()` on a new agent changes nothing and hands back what
178
- * to put on a website. The portal has no switch for it; its Website chat panel
179
- * holds the share link and the allowed websites (`allowedWebsites` below).
180
- * Publishing a newer version does not move the page: call `turnOn()` while it
181
- * is on to serve the newer one. Turned off and on again, it serves the
182
- * version it served before.
192
+ * key, and the portal's Test, as soon as it exists. Publishing a new version
193
+ * moves the website chat to it, as it moves new conversations.
183
194
  */
184
195
  readonly websiteChat: {
185
- /** Turn it on and get what to put on a website. The first time, and when
186
- * it is already on, the page serves the current version; after
187
- * `turnOff()`, the version it served before. Refused (400) for an agent
188
- * that needs each user's own account or secret, which a visitor cannot
189
- * bring. */
190
- turnOn: () => Promise<WebsiteChat>;
191
- /** Turn it off. Visitors are refused from the next message, follow-ups a
192
- * visitor's conversation booked are cancelled, and nothing more is
193
- * charged for them. The agent keeps answering your API key, its schedules
194
- * and its webhooks. The publishable token is kept, so turning it on again
195
- * revives a snippet already on a website. Turning off a chat that is
196
- * already off is not an error. */
197
- turnOff: () => Promise<void>;
198
- /** The websites the chat may be shown on through the embed script. A
199
- * domain covers its subdomains; an empty list means no other website.
200
- * The share link opened directly always works. */
196
+ /** Who can chat, the share link, and the id the embed script's
197
+ * `data-agent-id` takes. */
198
+ get: () => Promise<WebsiteChat>;
199
+ /** Who can chat: 'restricted' (your workspace's signed-in members, and
200
+ * the allowed websites) or 'anyone' (anyone with the link). */
201
+ access: {
202
+ /** The setting as it stands. */
203
+ get: () => Promise<WebsiteChatAccess>;
204
+ /** Change it. Returns the setting as stored. Anything but 'restricted'
205
+ * or 'anyone' is refused (400). */
206
+ set: (access: WebsiteChatAccess) => Promise<WebsiteChatAccess>;
207
+ };
208
+ /** The websites a Restricted agent's chat may be shown on through the
209
+ * embed script, where visitors chat without signing in. A domain covers
210
+ * its subdomains; an empty list means no other website. While access is
211
+ * 'anyone' the list is kept and not needed. */
201
212
  allowedWebsites: {
202
213
  /** The list as it stands. */
203
214
  get: () => Promise<string[]>;
@@ -388,6 +399,9 @@ export declare class Agent {
388
399
  /**
389
400
  * Address one of this agent's conversations by id. No request.
390
401
  *
402
+ * Pass `{ widgets: true }` when the screen continuing it can draw widgets,
403
+ * as on `start`: the choice belongs to the screen, so it is made per handle.
404
+ *
391
405
  * Here rather than on the workspace because a conversation belongs to an
392
406
  * agent. You already hold the agent: it is a constant in your own code, not
393
407
  * a per-row value, so naming it costs nothing and the ownership is visible.
@@ -396,7 +410,9 @@ export declare class Agent {
396
410
  * await ws.agent(AGENT).conversation(row.conversationId).ask('carry on');
397
411
  * ```
398
412
  */
399
- conversation(conversationId: string): Conversation;
413
+ conversation(conversationId: string, options?: {
414
+ widgets?: boolean;
415
+ }): Conversation;
400
416
  /**
401
417
  * This agent's most recent conversations, newest first.
402
418
  *
package/agent.js CHANGED
@@ -120,51 +120,43 @@ export class Agent {
120
120
  }
121
121
  // ------------------------------------------------------------ website chat
122
122
  /**
123
- * The agent's website chat: a public chat page, and the embed script that
124
- * puts it on your website. ON from the moment the agent is created, for
125
- * every agent, however it was made (here, through the API, or in the portal),
126
- * until you turn it off. The one exception is an agent that needs each
127
- * user's own account or secret, which a visitor cannot bring: it has none.
123
+ * The agent's website chat: its chat page on AgentNava (the share link),
124
+ * and the embed script that puts it on your website. Every agent has one
125
+ * from the moment it is created, however it was made (here, through the
126
+ * API, or in the portal), except an agent that needs each user's own
127
+ * account or secret, which a visitor cannot bring.
128
128
  *
129
- * You never need it to use the agent from code: the agent answers your API
130
- * key, and the portal's Test, as soon as it exists.
129
+ * Who can chat is one setting, `access`:
130
+ *
131
+ * 'restricted' the default. The share link works for members of your
132
+ * workspace who are signed in to AgentNava, so your team can
133
+ * pass it around to test. The chat shows on another website
134
+ * only when that website is on `allowedWebsites`.
135
+ * 'anyone' anyone with the link can chat, and any website can show
136
+ * the chat. Each visitor's turns are charged to your
137
+ * workspace.
131
138
  *
132
- * Anyone with the page link can talk to the agent, and each of their turns is
133
- * charged to your workspace, so turn it off for an agent only your own code
134
- * should reach. `turnOn()` on a new agent changes nothing and hands back what
135
- * to put on a website. The portal has no switch for it; its Website chat panel
136
- * holds the share link and the allowed websites (`allowedWebsites` below).
137
- * Publishing a newer version does not move the page: call `turnOn()` while it
138
- * is on to serve the newer one. Turned off and on again, it serves the
139
- * version it served before.
139
+ * You never need it to use the agent from code: the agent answers your API
140
+ * key, and the portal's Test, as soon as it exists. Publishing a new version
141
+ * moves the website chat to it, as it moves new conversations.
140
142
  */
141
143
  websiteChat = {
142
- /** Turn it on and get what to put on a website. The first time, and when
143
- * it is already on, the page serves the current version; after
144
- * `turnOff()`, the version it served before. Refused (400) for an agent
145
- * that needs each user's own account or secret, which a visitor cannot
146
- * bring. */
147
- turnOn: async () => {
148
- const res = await this.#http.post(`${this.base}/activate`, {});
149
- return {
150
- chatUrl: res.chatUrl,
151
- publicToken: res.publicToken,
152
- embedAgentId: res.agentId,
153
- versionNumber: res.versionNumber,
154
- };
144
+ /** Who can chat, the share link, and the id the embed script's
145
+ * `data-agent-id` takes. */
146
+ get: async () => toWebsiteChat(await this.#http.get(`${this.base}/website-chat-access`)),
147
+ /** Who can chat: 'restricted' (your workspace's signed-in members, and
148
+ * the allowed websites) or 'anyone' (anyone with the link). */
149
+ access: {
150
+ /** The setting as it stands. */
151
+ get: async () => (await this.#http.get(`${this.base}/website-chat-access`)).access,
152
+ /** Change it. Returns the setting as stored. Anything but 'restricted'
153
+ * or 'anyone' is refused (400). */
154
+ set: async (access) => (await this.#http.put(`${this.base}/website-chat-access`, { access })).access,
155
155
  },
156
- /** Turn it off. Visitors are refused from the next message, follow-ups a
157
- * visitor's conversation booked are cancelled, and nothing more is
158
- * charged for them. The agent keeps answering your API key, its schedules
159
- * and its webhooks. The publishable token is kept, so turning it on again
160
- * revives a snippet already on a website. Turning off a chat that is
161
- * already off is not an error. */
162
- turnOff: async () => {
163
- await this.#http.post(`${this.base}/deactivate`, {});
164
- },
165
- /** The websites the chat may be shown on through the embed script. A
166
- * domain covers its subdomains; an empty list means no other website.
167
- * The share link opened directly always works. */
156
+ /** The websites a Restricted agent's chat may be shown on through the
157
+ * embed script, where visitors chat without signing in. A domain covers
158
+ * its subdomains; an empty list means no other website. While access is
159
+ * 'anyone' the list is kept and not needed. */
168
160
  allowedWebsites: {
169
161
  /** The list as it stands. */
170
162
  get: async () => (await this.#http.get(`${this.base}/allowed-websites`)).websites,
@@ -511,11 +503,14 @@ export class Agent {
511
503
  // continue a conversation, hold its id: `agent.conversation(id)`.
512
504
  fresh: true,
513
505
  });
514
- return new Conversation(this.#http, data.id, data);
506
+ return new Conversation(this.#http, data.id, data, { widgets: options.widgets === true });
515
507
  }
516
508
  /**
517
509
  * Address one of this agent's conversations by id. No request.
518
510
  *
511
+ * Pass `{ widgets: true }` when the screen continuing it can draw widgets,
512
+ * as on `start`: the choice belongs to the screen, so it is made per handle.
513
+ *
519
514
  * Here rather than on the workspace because a conversation belongs to an
520
515
  * agent. You already hold the agent: it is a constant in your own code, not
521
516
  * a per-row value, so naming it costs nothing and the ownership is visible.
@@ -524,8 +519,8 @@ export class Agent {
524
519
  * await ws.agent(AGENT).conversation(row.conversationId).ask('carry on');
525
520
  * ```
526
521
  */
527
- conversation(conversationId) {
528
- return new Conversation(this.#http, conversationId);
522
+ conversation(conversationId, options = {}) {
523
+ return new Conversation(this.#http, conversationId, undefined, { widgets: options.widgets === true });
529
524
  }
530
525
  /**
531
526
  * This agent's most recent conversations, newest first.
@@ -563,6 +558,9 @@ export class Agent {
563
558
  }
564
559
  }
565
560
  _a = Agent;
561
+ function toWebsiteChat(wire) {
562
+ return { access: wire.access, chatUrl: wire.chatUrl, embedAgentId: wire.agentId };
563
+ }
566
564
  /** The end user a conversation belongs to: a non-empty string, or a thrown error before any request. */
567
565
  function requireEndUserId(value) {
568
566
  // Checked at RUNTIME as well as in the type: a JavaScript caller, or a
package/agent.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,0DAA0D;;AAE1D,OAAO,EAAgB,WAAW,EAAE,MAAM,cAAc,CAAC;AACzD,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACpF,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAG7C,OAAO,EAAmB,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AA8GrE;;;;;;;;;;;GAWG;AACH,MAAM,OAAO,KAAK;IACR,EAAE,CAAS;IACX,KAAK,CAAO;IACb,QAAQ,CAAa;IAE7B,YAAY,IAAU,EAAE,EAAU,EAAE,QAAoB;QACvD,IAAI,CAAC,KAAK,GAAG,IAAI,CAAC;QAClB,IAAI,CAAC,EAAE,GAAG,EAAE,CAAC;QACb,IAAI,QAAQ;YAAE,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;IACxC,CAAC;IAED,IAAY,IAAI;QACf,OAAO,cAAc,kBAAkB,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,CAAC;IACpD,CAAC;IAED;uEACmE;IACnE,IAAI,IAAI;QACP,OAAO,IAAI,CAAC,QAAQ,CAAC;IACtB,CAAC;IAED,KAAK,CAAC,GAAG,CAAC,UAAgC,EAAE;QAC3C,MAAM,IAAI,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,GAAG,CAChC,IAAI,CAAC,IAAI,EACT,OAAO,CAAC,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,S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MAAM,IAAI,cAAc,CAAC;QACxB,OAAO,EAAE,mIAAmI;QAC5I,IAAI,EAAE,mBAAmB;QACzB,MAAM,EAAE,GAAG;KACX,CAAC,CAAC;AACJ,CAAC","sourcesContent":["// An agent: a configuration you start conversations from.\n\nimport { type Account, accountIdOf } from './account.ts';\nimport { isBindings, refuseConnections, secretIdsOf, secretsIn } from './attach.ts';\nimport { Conversation } from './conversation.ts';\nimport { AgentNavaError } from './errors.ts';\nimport type { Http } from './http.ts';\nimport type { Secret } from './secret.ts';\nimport { type Connection, connectionForWire } from './connection.ts';\nimport type {\n\tAgentConversationData,\n\tAgentData,\n\tAgentFields,\n\tBindings,\n\tConnectionStatus,\n\tFileEntry,\n\tTrigger,\n\tWebsiteChat,\n\tWorkflow,\n\tWebhookDelivery,\n} from './types.ts';\n\nexport interface StartOptions {\n\t/**\n\t * Stored secrets to attach AS THE CONVERSATION STARTS.\n\t *\n\t * A `Secret` from `ws.endUser(id).secrets.create(...)` attaches by id, which\n\t * is the only way a stored per-person credential can reach a turn: you never\n\t * hold its value.\n\t *\n\t * ```ts\n\t * const key = await ws.endUser(row.userId).secrets.create({ name: 'ZENDESK_TOKEN', value });\n\t * const conversation = await agent.start({ endUserId: row.userId, attach: key });\n\t * ```\n\t *\n\t * Doing it here rather than with a second `conversation.attach()` call\n\t * closes a real window: between `start` and the attach, the conversation\n\t * exists and can be asked something, and it would answer without it.\n\t *\n\t * ACCOUNTS ARE NOT ATTACHED HERE any more (0.44), and one handed in is\n\t * refused. The agent's setup names the account each connection uses; for a\n\t * connection to the end user's account (`Connection.endUserAccount`), the\n\t * turn uses the account of the person this conversation is for, found by\n\t * `endUserId`. Ask\n\t * `conversation.accountsNeeded()` for the ones they have not connected yet.\n\t */\n\tattach?: Secret | Secret[];\n\n\t/**\n\t * Secret VALUES for this conversation only.\n\t *\n\t * Not `attach`, because a secret has no id you can hand over: binding one\n\t * takes the value itself. That asymmetry is in the product, not in this\n\t * naming, and hiding it behind the same word would not remove it.\n\t */\n\tsecrets?: Record<string, string>;\n\n\t/** Pin a specific version. Defaults to the latest at the moment of starting.\n\t *\n\t * A conversation pins its version for life: publishing afterwards does not\n\t * move a conversation that is already open. The one exception is a schedule\n\t * or webhook that names the conversation (`conversationId`): each firing\n\t * moves it to the latest version, so a fix you publish reaches it. */\n\tversion?: number;\n\tparameters?: Record<string, string | number>;\n\n\t/**\n\t * WHO this conversation is for: one of YOUR users, not one of ours.\n\t *\n\t * REQUIRED, and never null. Every conversation belongs to someone. The id\n\t * is yours to choose: a user's row id, an anonymous visitor's random id, or\n\t * a name for a job such as `'nightly-report'`. Only a non-empty string is\n\t * accepted; anything else throws before a request is sent. (Decided\n\t * 2026-09-26, AGE-161: a conversation with no owner cannot be listed back to\n\t * the person it was for, and the accounts connected inside it could not be\n\t * revoked with that person.)\n\t *\n\t * It LABELS the conversation, and it decides one thing more: a connection\n\t * to the end user's account (`Connection.endUserAccount`) uses THIS\n\t * person's account for that app.\n\t * It does not decide which conversation you get, because `start` always\n\t * starts a new one. Later you can ask for everything belonging to that\n\t * person:\n\t *\n\t * ```ts\n\t * const conversation = await agent.start({ endUserId: row.userId });\n\t * const nightly = await agent.start({ endUserId: 'nightly-report' }); // a job has an id too\n\t * const theirs = await agent.conversations({ endUser: row.userId });\n\t * ```\n\t *\n\t * To CONTINUE a conversation, keep its id and address it directly. That is\n\t * the only way to continue one, on purpose:\n\t *\n\t * ```ts\n\t * await ws.agent(AGENT).conversation(row.conversationId).ask('and the rest?');\n\t * ```\n\t *\n\t * The id is YOURS and opaque to us: a row id from your database, not an\n\t * email and not something we authenticate. We never verify it, so it is\n\t * exactly as trustworthy as whatever holds your API key.\n\t *\n\t * The platform's prefixes are refused with a 400 (`end_user_reserved`):\n\t * `member:`, `visitor:` and `job:`, which name a member in the web app, an\n\t * embed visitor and work nobody is typing, and the older `webhook:`,\n\t * `builder:` and `librarian:`. Case and spacing do not matter to the check\n\t * (`MEMBER:x` is refused too). An id you chose must never be mistaken for\n\t * one of ours.\n\t *\n\t * NOT A WORKSPACE MEMBER'S ID. `ws.members()` lists the colleagues who share\n\t * this account, and their `userId` is a platform id we issued. This field is\n\t * a different namespace entirely. Both were once spelled `userId`, so\n\t * passing a member id here was a call that could not fail: there is nothing\n\t * for an end-user id to be checked against, so it just labelled the\n\t * conversation with a colleague's internal id and looked fine.\n\t */\n\tendUserId: string;\n}\n\n/**\n * An agent you can configure and start conversations from.\n *\n * Holding one makes NO request: `ws.agent(id)` is free and the first call on it\n * is the first round trip.\n *\n * EVERY METHOD THAT CHANGES THE AGENT PUBLISHES A VERSION. There is no separate\n * save. What you do not send is inherited from the current version, which is the\n * only reason changing one field is safe: a resend that rebuilt the whole\n * configuration would drop whatever the caller forgot, and that bug has shipped\n * here four separate times.\n */\nexport class Agent {\n\treadonly id: string;\n\treadonly #http: Http;\n\tprivate snapshot?: AgentData;\n\n\tconstructor(http: Http, id: string, snapshot?: AgentData) {\n\t\tthis.#http = http;\n\t\tthis.id = id;\n\t\tif (snapshot) this.snapshot = snapshot;\n\t}\n\n\tprivate get base(): string {\n\t\treturn `/v1/agents/${encodeURIComponent(this.id)}`;\n\t}\n\n\t/** The last-known configuration, from whatever call produced this object.\n\t * Undefined on an agent you addressed by id and have not read. */\n\tget data(): AgentData | undefined {\n\t\treturn this.snapshot;\n\t}\n\n\tasync get(options: { version?: number } = {}): Promise<AgentData> {\n\t\tconst data = await this.#http.get<AgentData>(\n\t\t\tthis.base,\n\t\t\toptions.version !== undefined ? { version: options.version } : undefined,\n\t\t);\n\t\t// Only cache the CURRENT configuration. Caching a historical version would\n\t\t// make `agent.data` mean different things depending on the last call.\n\t\tif (options.version === undefined) this.snapshot = data;\n\t\treturn data;\n\t}\n\n\t/** Every version, newest first. */\n\tasync versions(): Promise<AgentData[]> {\n\t\tconst res = await this.#http.get<{ versions: AgentData[] }>(`${this.base}/versions`);\n\t\treturn res.versions ?? [];\n\t}\n\n\t/** Publish a new version with these fields changed and everything else kept.\n\t * `connections`, when sent, replaces the whole list; an `Account` in it goes\n\t * over the wire as its id (`Account.toJSON`). */\n\tasync update(fields: AgentFields): Promise<Agent> {\n\t\tconst data = await this.#http.post<AgentData>(`${this.base}/versions`, fields);\n\t\tthis.snapshot = data;\n\t\treturn new Agent(this.#http, this.id, data);\n\t}\n\n\tasync delete(): Promise<void> {\n\t\tawait this.#http.delete(this.base);\n\t}\n\n\t// --------------------------------------------------------------- workflows\n\n\t/**\n\t * Add a workflow, or replace the one with the same name.\n\t *\n\t * Reads the current list and sends it back with this one in place, because\n\t * the API replaces the whole list: a workflow set is a list, and there is no\n\t * \"merge one item\" that does not have to decide what a duplicate name means.\n\t * Deciding it here, once, is better than every caller deciding it.\n\t */\n\tasync setWorkflow(workflow: Workflow): Promise<Agent> {\n\t\tconst current = this.snapshot?.workflows ?? (await this.get()).workflows;\n\t\tconst next = current.filter((w) => w.name !== workflow.name).concat(workflow);\n\t\treturn this.update({ workflows: next });\n\t}\n\n\tasync removeWorkflow(name: string): Promise<Agent> {\n\t\tconst current = this.snapshot?.workflows ?? (await this.get()).workflows;\n\t\treturn this.update({ workflows: current.filter((w) => w.name !== name) });\n\t}\n\n\t/** Replace the trigger list. Sending `[]` removes every trigger, including\n\t * `chat`, which is what leaves an agent that only runs on a schedule. */\n\tasync setTriggers(triggers: Trigger[]): Promise<Agent> {\n\t\treturn this.update({ triggers });\n\t}\n\n\t/**\n\t * Replace the webhook's URL and return the new one.\n\t *\n\t * The old URL stops working the moment this returns, so update the system\n\t * that calls it. Use it when a URL leaked. The webhook's `message` and who it\n\t * runs for are kept. Publishes a version. Throws `no_webhook` (409) when the\n\t * agent has no webhook trigger.\n\t */\n\tasync rotateWebhookUrl(): Promise<string> {\n\t\tconst data = await this.#http.post<AgentData>(`${this.base}/webhook/rotate`, {});\n\t\tthis.snapshot = data;\n\t\tconst webhook = data.triggers.find((t) => t.kind === 'webhook');\n\t\tif (webhook?.kind !== 'webhook' || !webhook.url) {\n\t\t\tthrow new AgentNavaError({\n\t\t\t\tmessage: 'The webhook was rotated but no URL came back. Read it with agent.get().',\n\t\t\t\tcode: 'webhook_url_missing',\n\t\t\t\tstatus: 502,\n\t\t\t});\n\t\t}\n\t\treturn webhook.url;\n\t}\n\n\t/** What the webhook received, newest first: accepted, refused (and why), a\n\t * sender's retry recognised as a repeat, or a test. Up to `limit` (200). */\n\tasync webhookDeliveries(options: { limit?: number } = {}): Promise<WebhookDelivery[]> {\n\t\tconst res = await this.#http.get<{ deliveries: WebhookDelivery[] }>(\n\t\t\t`${this.base}/webhook/deliveries`,\n\t\t\toptions.limit !== undefined ? { limit: options.limit } : undefined,\n\t\t);\n\t\treturn res.deliveries ?? [];\n\t}\n\n\t/**\n\t * Send the webhook a sample event and run the agent on it, the way a real\n\t * delivery would (the signature check aside). A real turn, charged like\n\t * one. Returns the conversation it ran in.\n\t */\n\tasync sendTestWebhook(): Promise<{ conversationId?: string }> {\n\t\tconst res = await this.#http.post<{ conversationId?: string }>(`${this.base}/webhook/test`, {});\n\t\treturn res.conversationId ? { conversationId: res.conversationId } : {};\n\t}\n\n\t// ------------------------------------------------------------ website chat\n\n\t/**\n\t * The agent's website chat: a public chat page, and the embed script that\n\t * puts it on your website. ON from the moment the agent is created, for\n\t * every agent, however it was made (here, through the API, or in the portal),\n\t * until you turn it off. The one exception is an agent that needs each\n\t * user's own account or secret, which a visitor cannot bring: it has none.\n\t *\n\t * You never need it to use the agent from code: the agent answers your API\n\t * key, and the portal's Test, as soon as it exists.\n\t *\n\t * Anyone with the page link can talk to the agent, and each of their turns is\n\t * charged to your workspace, so turn it off for an agent only your own code\n\t * should reach. `turnOn()` on a new agent changes nothing and hands back what\n\t * to put on a website. The portal has no switch for it; its Website chat panel\n\t * holds the share link and the allowed websites (`allowedWebsites` below).\n\t * Publishing a newer version does not move the page: call `turnOn()` while it\n\t * is on to serve the newer one. Turned off and on again, it serves the\n\t * version it served before.\n\t */\n\treadonly websiteChat = {\n\t\t/** Turn it on and get what to put on a website. The first time, and when\n\t\t * it is already on, the page serves the current version; after\n\t\t * `turnOff()`, the version it served before. Refused (400) for an agent\n\t\t * that needs each user's own account or secret, which a visitor cannot\n\t\t * bring. */\n\t\tturnOn: async (): Promise<WebsiteChat> => {\n\t\t\tconst res = await this.#http.post<{\n\t\t\t\tagentId: string;\n\t\t\t\tversionNumber: number;\n\t\t\t\tpublicToken: string;\n\t\t\t\tchatUrl: string;\n\t\t\t}>(`${this.base}/activate`, {});\n\t\t\treturn {\n\t\t\t\tchatUrl: res.chatUrl,\n\t\t\t\tpublicToken: res.publicToken,\n\t\t\t\tembedAgentId: res.agentId,\n\t\t\t\tversionNumber: res.versionNumber,\n\t\t\t};\n\t\t},\n\t\t/** Turn it off. Visitors are refused from the next message, follow-ups a\n\t\t * visitor's conversation booked are cancelled, and nothing more is\n\t\t * charged for them. The agent keeps answering your API key, its schedules\n\t\t * and its webhooks. The publishable token is kept, so turning it on again\n\t\t * revives a snippet already on a website. Turning off a chat that is\n\t\t * already off is not an error. */\n\t\tturnOff: async (): Promise<void> => {\n\t\t\tawait this.#http.post(`${this.base}/deactivate`, {});\n\t\t},\n\t\t/** The websites the chat may be shown on through the embed script. A\n\t\t * domain covers its subdomains; an empty list means no other website.\n\t\t * The share link opened directly always works. */\n\t\tallowedWebsites: {\n\t\t\t/** The list as it stands. */\n\t\t\tget: async (): Promise<string[]> =>\n\t\t\t\t(await this.#http.get<{ websites: string[] }>(`${this.base}/allowed-websites`)).websites,\n\t\t\t/** Replace the list. Each entry is normalised (\"https://acme.com/page\"\n\t\t\t * becomes \"acme.com\"; \"localhost\" is allowed for testing), and one that\n\t\t\t * is not a website is refused (400). Returns the list as stored. */\n\t\t\tset: async (websites: string[]): Promise<string[]> =>\n\t\t\t\t(await this.#http.put<{ websites: string[] }>(`${this.base}/allowed-websites`, { websites })).websites,\n\t\t},\n\t};\n\n\t// --------------------------------------------------------------- knowledge\n\n\t#readKnowledgeResponse(path: string): Promise<Response> {\n\t\treturn this.#http.send(`${this.base}/knowledge/files/content`, { query: { path } });\n\t}\n\n\t/**\n\t * The agent's knowledge: files every conversation can read.\n\t *\n\t * BY REFERENCE, not by copy. A conversation reads the knowledge as it is now,\n\t * so replacing a file changes what open conversations see on their next turn.\n\t * That is the opposite of how a version works, and it is deliberate: a price\n\t * list that could not be corrected without republishing the agent would be\n\t * useless.\n\t */\n\treadonly knowledge = {\n\t\tput: async (path: string, bytes: Uint8Array | ArrayBuffer, contentType?: string): Promise<FileEntry> =>\n\t\t\tthis.#http.request<FileEntry>(`${this.base}/knowledge/files`, {\n\t\t\t\tmethod: 'PUT',\n\t\t\t\tbytes,\n\t\t\t\tquery: { path },\n\t\t\t\t...(contentType && { contentType }),\n\t\t\t}),\n\t\t/** Read an agent-owned knowledge file as bytes, without starting a turn. */\n\t\tget: async (path: string): Promise<Uint8Array> => {\n\t\t\tconst res = await this.#readKnowledgeResponse(path);\n\t\t\treturn new Uint8Array(await res.arrayBuffer());\n\t\t},\n\t\t/** Read UTF-8 text. JSON files remain text rather than being parsed. */\n\t\ttext: async (path: string): Promise<string> => {\n\t\t\tconst res = await this.#readKnowledgeResponse(path);\n\t\t\treturn res.text();\n\t\t},\n\t\tlist: async (path = '/'): Promise<FileEntry[]> => {\n\t\t\t// The route returns EVERY knowledge file for the agent; it takes no\n\t\t\t// directory parameter. Filtering here rather than sending one the server\n\t\t\t// ignores, because a call that looks filtered and is not is worse than\n\t\t\t// no filter at all. Knowledge sets are small, so one read is right.\n\t\t\tconst res = await this.#http.get<{ files: (FileEntry & { path: string })[] }>(\n\t\t\t\t`${this.base}/knowledge/files`,\n\t\t\t);\n\t\t\tconst prefix = path === '/' ? '/' : `${path.replace(/\\/+$/, '')}/`;\n\t\t\treturn (res.files ?? []).filter((f) => f.path?.startsWith(prefix));\n\t\t},\n\t\tremove: async (path: string): Promise<void> => {\n\t\t\tawait this.#http.delete(`${this.base}/knowledge/files`, { path });\n\t\t},\n\t};\n\n\t// -------------------------------------------------------- knowledge bases\n\n\t/**\n\t * The WORKSPACE knowledge bases this agent reads.\n\t *\n\t * Different from `knowledge` above, and the distinction is the whole point.\n\t * `agent.knowledge` is files this agent owns; nobody else has them. A\n\t * knowledge base is shared: one price list, attached to nine agents, corrected\n\t * in one place.\n\t *\n\t * Each attached base is mounted read-only at `/knowledge/<key>/` when a turn\n\t * starts, so the agent reads it with `ls`, `grep` and `cat`.\n\t *\n\t * ATTACHING PUBLISHES A VERSION. Which bases an agent reads is part of its\n\t * configuration, so the change is diffable and reversible like any other\n\t * configuration change. The CONTENTS of a base are not versioned: correcting\n\t * a file changes what every attached agent sees on its next turn.\n\t */\n\treadonly knowledgeBases = {\n\t\t/**\n\t\t * Attach one base by key.\n\t\t *\n\t\t * One call, not read-modify-write, deliberately. Two attaches racing\n\t\t * through a read of the current list and a write of the whole list would\n\t\t * lose one of them silently, and losing an attachment looks exactly like\n\t\t * an agent that cannot find its knowledge. The server appends.\n\t\t *\n\t\t * Attaching a key that names no base is refused, naming the key. Attaching\n\t\t * one that is already attached is a no-op, not an error.\n\t\t */\n\t\tattach: async (key: string): Promise<Agent> => {\n\t\t\tconst res = await this.#http.post<AgentData>(`${this.base}/knowledge-bases`, { key });\n\t\t\tthis.snapshot = res;\n\t\t\treturn this;\n\t\t},\n\n\t\t/** Detach one base. The base itself and its files are untouched: this only\n\t\t * stops THIS agent from reading it. Detaching one that is not attached is\n\t\t * a no-op. */\n\t\tdetach: async (key: string): Promise<Agent> => {\n\t\t\tconst res = await this.#http.delete<AgentData>(\n\t\t\t\t`${this.base}/knowledge-bases/${encodeURIComponent(key)}`,\n\t\t\t);\n\t\t\tif (res) this.snapshot = res;\n\t\t\treturn this;\n\t\t},\n\n\t\t/** The keys this agent currently reads, in configuration order. */\n\t\tlist: async (): Promise<string[]> => {\n\t\t\tconst current = this.snapshot ?? (await this.get());\n\t\t\treturn current.knowledgeBases ?? [];\n\t\t},\n\t};\n\n\t// -------------------------------------------------------------- databases\n\n\t/**\n\t * The WORKSPACE databases this agent may query, by key.\n\t *\n\t * Register a database first with `ws.databases.create()`, which gives it its\n\t * key; attaching names that key in this agent's configuration. Naming it is\n\t * the grant: the database answers this agent's `sql_*` calls and no agent\n\t * that does not name it, and the agent's prompt lists it by key.\n\t *\n\t * ATTACHING PUBLISHES A VERSION, like a knowledge base: which databases an\n\t * agent reaches is part of its configuration, so the change is diffable and\n\t * reversible. Detaching takes effect on the agent's next query, including in\n\t * a conversation already under way.\n\t */\n\treadonly databases = {\n\t\t/** Attach one database by key. The server appends, so two attaches cannot\n\t\t * lose each other. A key that names no database is refused; one already\n\t\t * attached is a no-op. */\n\t\tattach: async (key: string): Promise<Agent> => {\n\t\t\tconst res = await this.#http.post<AgentData>(`${this.base}/databases`, { key });\n\t\t\tthis.snapshot = res;\n\t\t\treturn this;\n\t\t},\n\n\t\t/** Stop this agent querying one database. The database stays registered\n\t\t * for every other agent that names it. */\n\t\tdetach: async (key: string): Promise<Agent> => {\n\t\t\tconst res = await this.#http.delete<AgentData>(`${this.base}/databases/${encodeURIComponent(key)}`);\n\t\t\tif (res) this.snapshot = res;\n\t\t\treturn this;\n\t\t},\n\n\t\t/** The keys this agent may query, in configuration order. */\n\t\tlist: async (): Promise<string[]> => {\n\t\t\tconst current = this.snapshot ?? (await this.get());\n\t\t\treturn current.databases ?? [];\n\t\t},\n\t};\n\n\t// ------------------------------------------------------------ connections\n\n\t/**\n\t * The apps this agent uses: each a NAMED connection that says WHOSE ACCOUNT\n\t * it uses, built the way the portal's Add a connection screen asks.\n\t *\n\t * | built with | whose account | the person signs in |\n\t * |---|---|---|\n\t * | `Connection.creatorAccount(app, account)` | the agent creator's, from `ws.accounts.connect()` | once, and every conversation uses it |\n\t * | `Connection.endUserAccount(app)` | the end user's: each person talking to the agent | once each, remembered for them |\n\t *\n\t * ```ts\n\t * const { account: work } = await ws.accounts.connect({ app: App.GMAIL, nickname: 'Work' });\n\t * await agent.connections.add(Connection.creatorAccount(App.GMAIL, work, { name: 'work-gmail' }));\n\t * await agent.connections.add(Connection.endUserAccount(App.GOOGLE_CALENDAR));\n\t * ```\n\t *\n\t * A turn uses EXACTLY the account the setup names, and never another one.\n\t * There is no fallback to whichever account of that app happens to exist:\n\t * that fallback is what this replaced, and it meant reading an agent's code\n\t * told you nothing about whose mailbox it read.\n\t *\n\t * EVERY CHANGE PUBLISHES A VERSION, like `databases`: which accounts an\n\t * agent reaches is part of its configuration, so the change is diffable and\n\t * reversible. A conversation uses the connections of the version it runs.\n\t * The ACCOUNTS are not versioned: signing one in again reaches every agent\n\t * that names it, from the next turn.\n\t *\n\t * Removing a connection never touches the account. Disconnecting an account\n\t * is the other operation, on the account: `account.disconnect()`.\n\t */\n\treadonly connections = {\n\t\t/**\n\t\t * Add one connection. One call that publishes, not read-modify-write, so\n\t\t * two adds racing cannot lose each other.\n\t\t *\n\t\t * Takes what `Connection.creatorAccount()` or `Connection.endUserAccount()`\n\t\t * builds, or the same plain object. Refused, naming the problem, when the\n\t\t * name is taken on this agent (`connection_name_taken`), when the account\n\t\t * is of a different app (`account_app_mismatch`), or when no account has\n\t\t * that id (`account_not_found`).\n\t\t */\n\t\tadd: async (connection: Connection): Promise<Agent> => {\n\t\t\tconst res = await this.#http.post<AgentData>(`${this.base}/connections`, connectionForWire(connection));\n\t\t\tthis.snapshot = res;\n\t\t\treturn this;\n\t\t},\n\n\t\t/**\n\t\t * Point one connection at another account: `{ account }` for the agent\n\t\t * creator's (the `Account` you hold, or its id), or `{ endUser: true }`\n\t\t * for each end user's own. The name and the app stay; an account of a\n\t\t * different app is refused (`account_app_mismatch`).\n\t\t *\n\t\t * READ-MODIFY-WRITE, unlike `add` and `remove`, because there is no\n\t\t * route that changes one connection in place: this reads the current\n\t\t * version and publishes it again with the one connection changed. Two\n\t\t * changes racing can therefore lose one, so make them one after the\n\t\t * other. A name the agent does not have throws\n\t\t * (`connection_not_found`) before anything is sent.\n\t\t */\n\t\tchange: async (\n\t\t\tname: string,\n\t\t\tchange: { account: Account | string; endUser?: never } | { endUser: true; account?: never },\n\t\t): Promise<Agent> => {\n\t\t\t// Read FRESH, never from the snapshot. A stale list sent back whole\n\t\t\t// would silently undo whatever changed since it was read.\n\t\t\tconst current = (await this.get()).connections ?? [];\n\t\t\tif (!current.some((c) => c.name === name)) {\n\t\t\t\tthrow new AgentNavaError({\n\t\t\t\t\tmessage: `This agent has no connection named \"${name}\". It has: ${\n\t\t\t\t\t\tcurrent.map((c) => c.name).join(', ') || 'none'\n\t\t\t\t\t}.`,\n\t\t\t\t\tcode: 'connection_not_found',\n\t\t\t\t\tstatus: 404,\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst whose =\n\t\t\t\tchange.endUser === true ? { endUser: true as const } : { account: accountIdOf(change.account as Account | string) };\n\t\t\t// Every other connection goes back exactly as it was read: this changes\n\t\t\t// one, and must not reinterpret the rest.\n\t\t\tconst connections = current.map((c) => (c.name === name ? { name: c.name, app: c.app, ...whose } : c));\n\t\t\tconst data = await this.#http.post<AgentData>(`${this.base}/versions`, { connections });\n\t\t\tthis.snapshot = data;\n\t\t\treturn this;\n\t\t},\n\n\t\t/** Remove one connection by name. Publishes a version. NEVER touches the\n\t\t * account: it stays connected for every other agent that names it, and\n\t\t * for this one if you add it back. */\n\t\tremove: async (name: string): Promise<Agent> => {\n\t\t\tconst res = await this.#http.delete<AgentData>(`${this.base}/connections/${encodeURIComponent(name)}`);\n\t\t\tif (res) this.snapshot = res;\n\t\t\treturn this;\n\t\t},\n\n\t\t/**\n\t\t * Each connection with the account it uses and whether that account works\n\t\t * now: DECLARED IS NOT CONNECTED. An agent can name an account nobody has\n\t\t * finished signing in to, or one that was disconnected since, and that is\n\t\t * the state a setup checklist has to show.\n\t\t *\n\t\t * Includes what an unpublished draft adds (`inDraft`) and removes\n\t\t * (`removedInDraft`), so it matches the portal.\n\t\t */\n\t\tlist: async (): Promise<ConnectionStatus[]> => {\n\t\t\tconst res = await this.#http.get<{ connections: ConnectionStatus[] }>(`${this.base}/connections`);\n\t\t\treturn res.connections ?? [];\n\t\t},\n\t};\n\n\t// ------------------------------------------------------ secrets, agent tier\n\n\t/**\n\t * Write secret VALUES to this agent's own scope: readable by this agent and\n\t * nothing else in the workspace, overriding a workspace secret of the same\n\t * name. Writing one twice replaces the value rather than failing, because\n\t * attaching means \"this is the credential now\".\n\t *\n\t * This used to POST the whole object to `/v1/agents/:id/bindings`, which\n\t * answers only to `{kind, decl}` and records a DECLARATION, never a value. So\n\t * the call 400'd, and had it not, it would have stored the fact that a secret\n\t * is wanted rather than the secret.\n\t */\n\tasync #applyBindings(bindings: Bindings): Promise<Agent> {\n\t\tfor (const [name, value] of Object.entries(bindings.secrets ?? {})) {\n\t\t\tconst mine = (await this.#http.get<{ secrets: { id: string; name: string; agentId?: string | null }[] }>(\n\t\t\t\t'/v1/secrets',\n\t\t\t\t{ agentId: this.id },\n\t\t\t)).secrets ?? [];\n\t\t\tconst existing = mine.find((s) => s.name === name && s.agentId);\n\t\t\tif (existing) await this.#http.patch(`/v1/secrets/${encodeURIComponent(existing.id)}`, { value });\n\t\t\telse await this.#http.post('/v1/secrets', { name, value, agentId: this.id });\n\t\t}\n\t\tconst data = await this.get();\n\t\tthis.snapshot = data;\n\t\treturn new Agent(this.#http, this.id, data);\n\t}\n\n\t/**\n\t * Give this agent secret values, so every conversation with it can use them.\n\t *\n\t * ```ts\n\t * await agent.attach({ secrets: { APOLLO_API_KEY: value } });\n\t * ```\n\t *\n\t * SECRETS ONLY, since 0.44. Accounts used to be attached here, and a turn\n\t * then had to guess which of the accounts attached and owned around it to\n\t * use. The agent's setup now names them: `agent.connections.add()`. One\n\t * handed in here is refused by name (`not_a_secret`) rather than dropped.\n\t *\n\t * A stored `Secret` is not attached to an agent either. It never was: one\n\t * was accepted here and nothing was done with it. Store one for the agent\n\t * with `ws.secrets.create({ name, value, agentId })`, or attach one of your\n\t * end user's to their conversation with `conversation.attach(secret)`.\n\t */\n\tasync attach(bindings: Bindings): Promise<Agent> {\n\t\tif (!isBindings(bindings)) {\n\t\t\tthrow new AgentNavaError({\n\t\t\t\tmessage:\n\t\t\t\t\t'agent.attach takes { secrets: { NAME: value } }. Accounts go in the agent\\'s setup ' +\n\t\t\t\t\t'(agent.connections.add), and a stored secret attaches to a conversation ' +\n\t\t\t\t\t'(conversation.attach).',\n\t\t\t\tcode: 'not_a_secret',\n\t\t\t\tstatus: 400,\n\t\t\t});\n\t\t}\n\t\trefuseConnections(bindings);\n\t\treturn this.#applyBindings(bindings);\n\t}\n\n\t// ----------------------------------------------------------- conversations\n\n\t/** Start a conversation. It pins the agent's version now and keeps it.\n\t *\n\t * Nothing about accounts is passed here: the version's connections name\n\t * them, and a connection to the end user's account uses the account of\n\t * the person named by `endUserId`. */\n\tasync start(options: StartOptions): Promise<Conversation> {\n\t\tconst endUserId = requireEndUserId(options?.endUserId);\n\t\t// Resolved BEFORE the launch: a Secret is named on the wire by the\n\t\t// declared NAME it fills, and a handle addressed by id may not know its\n\t\t// own yet. Anything that is not a Secret is refused here, by name.\n\t\tconst secretIds = await secretIdsOf(secretsIn(options.attach));\n\t\tconst bindings =\n\t\t\toptions.secrets || secretIds\n\t\t\t\t? {\n\t\t\t\t\t\t...(options.secrets && { secrets: options.secrets }),\n\t\t\t\t\t\t...(secretIds && { secretIds }),\n\t\t\t\t\t}\n\t\t\t\t: undefined;\n\t\tconst data = await this.#http.post<AgentConversationData>('/v1/conversations', {\n\t\t\tagentId: this.id,\n\t\t\t...(options.version !== undefined && { version: options.version }),\n\t\t\t...(options.parameters && { parameters: options.parameters }),\n\t\t\t// `sessionBindings`, NOT `secrets` at the top level.\n\t\t\t//\n\t\t\t// This sent them at the top level and the launch route reads\n\t\t\t// `body.sessionBindings`, so they were dropped in silence: the route's\n\t\t\t// own body type has no top-level `secrets` to read. A conversation\n\t\t\t// started with a credential began without it, and the first turn\n\t\t\t// failed somewhere else entirely.\n\t\t\t//\n\t\t\t// Third place this exact envelope mistake was found in one afternoon,\n\t\t\t// after `agent.bind` and `conversation.bind`. The shape of the bug is\n\t\t\t// always the same: the SDK agrees with itself, the route agrees with\n\t\t\t// itself, and nothing compares the two.\n\t\t\t...(bindings && { sessionBindings: bindings }),\n\t\t\t// Always present: requireEndUserId() above has already refused\n\t\t\t// anything that is not a non-empty string.\n\t\t\tuser: { id: endUserId },\n\t\t\t// ALWAYS a new conversation, even when a user is named.\n\t\t\t//\n\t\t\t// The route resumes that user's most recent conversation when it is\n\t\t\t// given an identity and not told otherwise. That default exists for\n\t\t\t// our own web app, where a page reload must not leave a trail of empty\n\t\t\t// conversations, and it is wrong for a method called `start`: a verb\n\t\t\t// that sometimes does not do the thing is worse than two verbs. It is\n\t\t\t// also ambiguous the moment a user has more than one conversation,\n\t\t\t// since it silently picks the newest.\n\t\t\t//\n\t\t\t// So the SDK does not rely on that default. `start` starts. To\n\t\t\t// continue a conversation, hold its id: `agent.conversation(id)`.\n\t\t\tfresh: true,\n\t\t});\n\t\treturn new Conversation(this.#http, data.id, data);\n\t}\n\n\t/**\n\t * Address one of this agent's conversations by id. No request.\n\t *\n\t * Here rather than on the workspace because a conversation belongs to an\n\t * agent. You already hold the agent: it is a constant in your own code, not\n\t * a per-row value, so naming it costs nothing and the ownership is visible.\n\t *\n\t * ```ts\n\t * await ws.agent(AGENT).conversation(row.conversationId).ask('carry on');\n\t * ```\n\t */\n\tconversation(conversationId: string): Conversation {\n\t\treturn new Conversation(this.#http, conversationId);\n\t}\n\n\t/**\n\t * This agent's most recent conversations, newest first.\n\t *\n\t * NOT ALL OF THEM, and the previous sentence here said \"every\", which was\n\t * wrong in the way that costs someone an afternoon. The server returns the\n\t * newest 50 unless you ask for more, and refuses to return more than 200 on\n\t * any single call (apps/api/src/state.ts listAgentSessions, and the Durable\n\t * Object twin beside it, clamp identically).\n\t *\n\t * There is no cursor on this route yet, so an agent with more than 200\n\t * conversations CANNOT be fully enumerated through this method. If you are\n\t * counting or exporting, do not build on it; that needs a paginated route we\n\t * have not added. `ws.endUser(id).conversations()` DOES have a cursor, if\n\t * the question is one person's history rather than one agent's.\n\t *\n\t * `endUser` narrows to one of YOUR end users, which is what you want for a\n\t * \"your conversations\" list. Leaving it out returns everyone's, so leave it\n\t * out only for an operator view.\n\t *\n\t * ```ts\n\t * const mine = await agent.conversations({ endUser: row.userId });\n\t * ```\n\t */\n\tasync conversations(options: { limit?: number; endUser?: string } = {}): Promise<Conversation[]> {\n\t\tconst res = await this.#http.get<{ conversations: AgentConversationData[] }>('/v1/conversations', {\n\t\t\tagentId: this.id,\n\t\t\t...(options.limit !== undefined && { limit: options.limit }),\n\t\t\t// One end user's history. Sending this used to be silently ignored on\n\t\t\t// this route, which answered with everyone's conversations, so an\n\t\t\t// application rendering \"your chats\" showed somebody else's.\n\t\t\t...(options.endUser !== undefined && { end_user_id: options.endUser }),\n\t\t});\n\t\treturn (res.conversations ?? []).map((c) => new Conversation(this.#http, c.id, c));\n\t}\n}\n\n/** The end user a conversation belongs to: a non-empty string, or a thrown error before any request. */\nfunction requireEndUserId(value: unknown): string {\n\t// Checked at RUNTIME as well as in the type: a JavaScript caller, or a\n\t// TypeScript one reading a nullable column, can still pass null, a number or\n\t// ''. Each used to start an ownerless conversation that looked fine.\n\tif (typeof value === 'string' && value.trim()) return value.trim();\n\tthrow new AgentNavaError({\n\t\tmessage: 'agent.start() needs endUserId: a non-empty string naming who the conversation is for (your user id, a visitor id, or a job name).',\n\t\tcode: 'end_user_required',\n\t\tstatus: 400,\n\t});\n}\n"]}
1
+ {"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA,0DAA0D;;AAE1D,OAAO,EAAgB,WAAW,EAAE,MAAM,cAAc,CAAC;AACzD,OAAO,EAAE,UAAU,EAAE,iBAAiB,EAAE,WAAW,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AACpF,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AACjD,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAG7C,OAAO,EAAmB,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAwHrE;;;;;;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.\n\nimport { type Account, accountIdOf } from './account.ts';\nimport { isBindings, refuseConnections, secretIdsOf, secretsIn } from './attach.ts';\nimport { Conversation } from './conversation.ts';\nimport { AgentNavaError } from './errors.ts';\nimport type { Http } from './http.ts';\nimport type { Secret } from './secret.ts';\nimport { type Connection, connectionForWire } from './connection.ts';\nimport type {\n\tAgentConversationData,\n\tAgentData,\n\tAgentFields,\n\tBindings,\n\tConnectionStatus,\n\tFileEntry,\n\tTrigger,\n\tWebsiteChat,\n\tWebsiteChatAccess,\n\tWorkflow,\n\tWebhookDelivery,\n} from './types.ts';\n\nexport interface StartOptions {\n\t/**\n\t * Stored secrets to attach AS THE CONVERSATION STARTS.\n\t *\n\t * A `Secret` from `ws.endUser(id).secrets.create(...)` attaches by id, which\n\t * is the only way a stored per-person credential can reach a turn: you never\n\t * hold its value.\n\t *\n\t * ```ts\n\t * const key = await ws.endUser(row.userId).secrets.create({ name: 'ZENDESK_TOKEN', value });\n\t * const conversation = await agent.start({ endUserId: row.userId, attach: key });\n\t * ```\n\t *\n\t * Doing it here rather than with a second `conversation.attach()` call\n\t * closes a real window: between `start` and the attach, the conversation\n\t * exists and can be asked something, and it would answer without it.\n\t *\n\t * ACCOUNTS ARE NOT ATTACHED HERE any more (0.44), and one handed in is\n\t * refused. The agent's setup names the account each connection uses; for a\n\t * connection to the end user's account (`Connection.endUserAccount`), the\n\t * turn uses the account of the person this conversation is for, found by\n\t * `endUserId`. Ask\n\t * `conversation.accountsNeeded()` for the ones they have not connected yet.\n\t */\n\tattach?: Secret | Secret[];\n\n\t/**\n\t * Secret VALUES for this conversation only.\n\t *\n\t * Not `attach`, because a secret has no id you can hand over: binding one\n\t * takes the value itself. That asymmetry is in the product, not in this\n\t * naming, and hiding it behind the same word would not remove it.\n\t */\n\tsecrets?: Record<string, string>;\n\n\t/** Pin a specific version. Defaults to the latest at the moment of starting.\n\t *\n\t * A conversation pins its version for life: publishing afterwards does not\n\t * move a conversation that is already open. The one exception is a schedule\n\t * or webhook that names the conversation (`conversationId`): each firing\n\t * moves it to the latest version, so a fix you publish reaches it. */\n\tversion?: number;\n\tparameters?: Record<string, string | number>;\n\n\t/**\n\t * WHO this conversation is for: one of YOUR users, not one of ours.\n\t *\n\t * REQUIRED, and never null. Every conversation belongs to someone. The id\n\t * is yours to choose: a user's row id, an anonymous visitor's random id, or\n\t * a name for a job such as `'nightly-report'`. Only a non-empty string is\n\t * accepted; anything else throws before a request is sent. (Decided\n\t * 2026-09-26, AGE-161: a conversation with no owner cannot be listed back to\n\t * the person it was for, and the accounts connected inside it could not be\n\t * revoked with that person.)\n\t *\n\t * It LABELS the conversation, and it decides one thing more: a connection\n\t * to the end user's account (`Connection.endUserAccount`) uses THIS\n\t * person's account for that app.\n\t * It does not decide which conversation you get, because `start` always\n\t * starts a new one. Later you can ask for everything belonging to that\n\t * person:\n\t *\n\t * ```ts\n\t * const conversation = await agent.start({ endUserId: row.userId });\n\t * const nightly = await agent.start({ endUserId: 'nightly-report' }); // a job has an id too\n\t * const theirs = await agent.conversations({ endUser: row.userId });\n\t * ```\n\t *\n\t * To CONTINUE a conversation, keep its id and address it directly. That is\n\t * the only way to continue one, on purpose:\n\t *\n\t * ```ts\n\t * await ws.agent(AGENT).conversation(row.conversationId).ask('and the rest?');\n\t * ```\n\t *\n\t * The id is YOURS and opaque to us: a row id from your database, not an\n\t * email and not something we authenticate. We never verify it, so it is\n\t * exactly as trustworthy as whatever holds your API key.\n\t *\n\t * The platform's prefixes are refused with a 400 (`end_user_reserved`):\n\t * `member:`, `visitor:` and `job:`, which name a member in the web app, an\n\t * embed visitor and work nobody is typing, and the older `webhook:`,\n\t * `builder:` and `librarian:`. Case and spacing do not matter to the check\n\t * (`MEMBER:x` is refused too). An id you chose must never be mistaken for\n\t * one of ours.\n\t *\n\t * NOT A WORKSPACE MEMBER'S ID. `ws.members()` lists the colleagues who share\n\t * this account, and their `userId` is a platform id we issued. This field is\n\t * a different namespace entirely. Both were once spelled `userId`, so\n\t * passing a member id here was a call that could not fail: there is nothing\n\t * for an end-user id to be checked against, so it just labelled the\n\t * conversation with a colleague's internal id and looked fine.\n\t */\n\tendUserId: string;\n\t/**\n\t * This conversation's screen can draw widgets: cards, tables and charts the\n\t * agent writes inside its replies, in Google's A2UI format. Off unless set.\n\t * When on, each turn's stream carries `widget` events and `done.widgets`,\n\t * and `messages()` returns each reply's `widgets`. The agent draws only if\n\t * its own \"Answer with widgets\" setting is on (it is, unless turned off).\n\t * The SDK ships no screens: draw them with any A2UI renderer.\n\t */\n\twidgets?: boolean;\n}\n\n/**\n * An agent you can configure and start conversations from.\n *\n * Holding one makes NO request: `ws.agent(id)` is free and the first call on it\n * is the first round trip.\n *\n * EVERY METHOD THAT CHANGES THE AGENT PUBLISHES A VERSION. There is no separate\n * save. What you do not send is inherited from the current version, which is the\n * only reason changing one field is safe: a resend that rebuilt the whole\n * configuration would drop whatever the caller forgot, and that bug has shipped\n * here four separate times.\n */\nexport class Agent {\n\treadonly id: string;\n\treadonly #http: Http;\n\tprivate snapshot?: AgentData;\n\n\tconstructor(http: Http, id: string, snapshot?: AgentData) {\n\t\tthis.#http = http;\n\t\tthis.id = id;\n\t\tif (snapshot) this.snapshot = snapshot;\n\t}\n\n\tprivate get base(): string {\n\t\treturn `/v1/agents/${encodeURIComponent(this.id)}`;\n\t}\n\n\t/** The last-known configuration, from whatever call produced this object.\n\t * Undefined on an agent you addressed by id and have not read. */\n\tget data(): AgentData | undefined {\n\t\treturn this.snapshot;\n\t}\n\n\tasync get(options: { version?: number } = {}): Promise<AgentData> {\n\t\tconst data = await this.#http.get<AgentData>(\n\t\t\tthis.base,\n\t\t\toptions.version !== undefined ? { version: options.version } : undefined,\n\t\t);\n\t\t// Only cache the CURRENT configuration. Caching a historical version would\n\t\t// make `agent.data` mean different things depending on the last call.\n\t\tif (options.version === undefined) this.snapshot = data;\n\t\treturn data;\n\t}\n\n\t/** Every version, newest first. */\n\tasync versions(): Promise<AgentData[]> {\n\t\tconst res = await this.#http.get<{ versions: AgentData[] }>(`${this.base}/versions`);\n\t\treturn res.versions ?? [];\n\t}\n\n\t/** Publish a new version with these fields changed and everything else kept.\n\t * `connections`, when sent, replaces the whole list; an `Account` in it goes\n\t * over the wire as its id (`Account.toJSON`). */\n\tasync update(fields: AgentFields): Promise<Agent> {\n\t\tconst data = await this.#http.post<AgentData>(`${this.base}/versions`, fields);\n\t\tthis.snapshot = data;\n\t\treturn new Agent(this.#http, this.id, data);\n\t}\n\n\tasync delete(): Promise<void> {\n\t\tawait this.#http.delete(this.base);\n\t}\n\n\t// --------------------------------------------------------------- workflows\n\n\t/**\n\t * Add a workflow, or replace the one with the same name.\n\t *\n\t * Reads the current list and sends it back with this one in place, because\n\t * the API replaces the whole list: a workflow set is a list, and there is no\n\t * \"merge one item\" that does not have to decide what a duplicate name means.\n\t * Deciding it here, once, is better than every caller deciding it.\n\t */\n\tasync setWorkflow(workflow: Workflow): Promise<Agent> {\n\t\tconst current = this.snapshot?.workflows ?? (await this.get()).workflows;\n\t\tconst next = current.filter((w) => w.name !== workflow.name).concat(workflow);\n\t\treturn this.update({ workflows: next });\n\t}\n\n\tasync removeWorkflow(name: string): Promise<Agent> {\n\t\tconst current = this.snapshot?.workflows ?? (await this.get()).workflows;\n\t\treturn this.update({ workflows: current.filter((w) => w.name !== name) });\n\t}\n\n\t/** Replace the trigger list. Sending `[]` removes every trigger, including\n\t * `chat`, which is what leaves an agent that only runs on a schedule. */\n\tasync setTriggers(triggers: Trigger[]): Promise<Agent> {\n\t\treturn this.update({ triggers });\n\t}\n\n\t/**\n\t * Replace the webhook's URL and return the new one.\n\t *\n\t * The old URL stops working the moment this returns, so update the system\n\t * that calls it. Use it when a URL leaked. The webhook's `message` and who it\n\t * runs for are kept. Publishes a version. Throws `no_webhook` (409) when the\n\t * agent has no webhook trigger.\n\t */\n\tasync rotateWebhookUrl(): Promise<string> {\n\t\tconst data = await this.#http.post<AgentData>(`${this.base}/webhook/rotate`, {});\n\t\tthis.snapshot = data;\n\t\tconst webhook = data.triggers.find((t) => t.kind === 'webhook');\n\t\tif (webhook?.kind !== 'webhook' || !webhook.url) {\n\t\t\tthrow new AgentNavaError({\n\t\t\t\tmessage: 'The webhook was rotated but no URL came back. Read it with agent.get().',\n\t\t\t\tcode: 'webhook_url_missing',\n\t\t\t\tstatus: 502,\n\t\t\t});\n\t\t}\n\t\treturn webhook.url;\n\t}\n\n\t/** What the webhook received, newest first: accepted, refused (and why), a\n\t * sender's retry recognised as a repeat, or a test. Up to `limit` (200). */\n\tasync webhookDeliveries(options: { limit?: number } = {}): Promise<WebhookDelivery[]> {\n\t\tconst res = await this.#http.get<{ deliveries: WebhookDelivery[] }>(\n\t\t\t`${this.base}/webhook/deliveries`,\n\t\t\toptions.limit !== undefined ? { limit: options.limit } : undefined,\n\t\t);\n\t\treturn res.deliveries ?? [];\n\t}\n\n\t/**\n\t * Send the webhook a sample event and run the agent on it, the way a real\n\t * delivery would (the signature check aside). A real turn, charged like\n\t * one. Returns the conversation it ran in.\n\t */\n\tasync sendTestWebhook(): Promise<{ conversationId?: string }> {\n\t\tconst res = await this.#http.post<{ conversationId?: string }>(`${this.base}/webhook/test`, {});\n\t\treturn res.conversationId ? { conversationId: res.conversationId } : {};\n\t}\n\n\t// ------------------------------------------------------------ website chat\n\n\t/**\n\t * The agent's website chat: its chat page on AgentNava (the share link),\n\t * and the embed script that puts it on your website. Every agent has one\n\t * from the moment it is created, however it was made (here, through the\n\t * API, or in the portal), except an agent that needs each user's own\n\t * account or secret, which a visitor cannot bring.\n\t *\n\t * Who can chat is one setting, `access`:\n\t *\n\t * 'restricted' the default. The share link works for members of your\n\t * workspace who are signed in to AgentNava, so your team can\n\t * pass it around to test. The chat shows on another website\n\t * only when that website is on `allowedWebsites`.\n\t * 'anyone' anyone with the link can chat, and any website can show\n\t * the chat. Each visitor's turns are charged to your\n\t * workspace.\n\t *\n\t * You never need it to use the agent from code: the agent answers your API\n\t * key, and the portal's Test, as soon as it exists. Publishing a new version\n\t * moves the website chat to it, as it moves new conversations.\n\t */\n\treadonly websiteChat = {\n\t\t/** Who can chat, the share link, and the id the embed script's\n\t\t * `data-agent-id` takes. */\n\t\tget: async (): Promise<WebsiteChat> => toWebsiteChat(\n\t\t\tawait this.#http.get<WebsiteChatWire>(`${this.base}/website-chat-access`),\n\t\t),\n\t\t/** Who can chat: 'restricted' (your workspace's signed-in members, and\n\t\t * the allowed websites) or 'anyone' (anyone with the link). */\n\t\taccess: {\n\t\t\t/** The setting as it stands. */\n\t\t\tget: async (): Promise<WebsiteChatAccess> =>\n\t\t\t\t(await this.#http.get<WebsiteChatWire>(`${this.base}/website-chat-access`)).access,\n\t\t\t/** Change it. Returns the setting as stored. Anything but 'restricted'\n\t\t\t * or 'anyone' is refused (400). */\n\t\t\tset: async (access: WebsiteChatAccess): Promise<WebsiteChatAccess> =>\n\t\t\t\t(await this.#http.put<WebsiteChatWire>(`${this.base}/website-chat-access`, { access })).access,\n\t\t},\n\t\t/** The websites a Restricted agent's chat may be shown on through the\n\t\t * embed script, where visitors chat without signing in. A domain covers\n\t\t * its subdomains; an empty list means no other website. While access is\n\t\t * 'anyone' the list is kept and not needed. */\n\t\tallowedWebsites: {\n\t\t\t/** The list as it stands. */\n\t\t\tget: async (): Promise<string[]> =>\n\t\t\t\t(await this.#http.get<{ websites: string[] }>(`${this.base}/allowed-websites`)).websites,\n\t\t\t/** Replace the list. Each entry is normalised (\"https://acme.com/page\"\n\t\t\t * becomes \"acme.com\"; \"localhost\" is allowed for testing), and one that\n\t\t\t * is not a website is refused (400). Returns the list as stored. */\n\t\t\tset: async (websites: string[]): Promise<string[]> =>\n\t\t\t\t(await this.#http.put<{ websites: string[] }>(`${this.base}/allowed-websites`, { websites })).websites,\n\t\t},\n\t};\n\n\t// --------------------------------------------------------------- knowledge\n\n\t#readKnowledgeResponse(path: string): Promise<Response> {\n\t\treturn this.#http.send(`${this.base}/knowledge/files/content`, { query: { path } });\n\t}\n\n\t/**\n\t * The agent's knowledge: files every conversation can read.\n\t *\n\t * BY REFERENCE, not by copy. A conversation reads the knowledge as it is now,\n\t * so replacing a file changes what open conversations see on their next turn.\n\t * That is the opposite of how a version works, and it is deliberate: a price\n\t * list that could not be corrected without republishing the agent would be\n\t * useless.\n\t */\n\treadonly knowledge = {\n\t\tput: async (path: string, bytes: Uint8Array | ArrayBuffer, contentType?: string): Promise<FileEntry> =>\n\t\t\tthis.#http.request<FileEntry>(`${this.base}/knowledge/files`, {\n\t\t\t\tmethod: 'PUT',\n\t\t\t\tbytes,\n\t\t\t\tquery: { path },\n\t\t\t\t...(contentType && { contentType }),\n\t\t\t}),\n\t\t/** Read an agent-owned knowledge file as bytes, without starting a turn. */\n\t\tget: async (path: string): Promise<Uint8Array> => {\n\t\t\tconst res = await this.#readKnowledgeResponse(path);\n\t\t\treturn new Uint8Array(await res.arrayBuffer());\n\t\t},\n\t\t/** Read UTF-8 text. JSON files remain text rather than being parsed. */\n\t\ttext: async (path: string): Promise<string> => {\n\t\t\tconst res = await this.#readKnowledgeResponse(path);\n\t\t\treturn res.text();\n\t\t},\n\t\tlist: async (path = '/'): Promise<FileEntry[]> => {\n\t\t\t// The route returns EVERY knowledge file for the agent; it takes no\n\t\t\t// directory parameter. Filtering here rather than sending one the server\n\t\t\t// ignores, because a call that looks filtered and is not is worse than\n\t\t\t// no filter at all. Knowledge sets are small, so one read is right.\n\t\t\tconst res = await this.#http.get<{ files: (FileEntry & { path: string })[] }>(\n\t\t\t\t`${this.base}/knowledge/files`,\n\t\t\t);\n\t\t\tconst prefix = path === '/' ? '/' : `${path.replace(/\\/+$/, '')}/`;\n\t\t\treturn (res.files ?? []).filter((f) => f.path?.startsWith(prefix));\n\t\t},\n\t\tremove: async (path: string): Promise<void> => {\n\t\t\tawait this.#http.delete(`${this.base}/knowledge/files`, { path });\n\t\t},\n\t};\n\n\t// -------------------------------------------------------- knowledge bases\n\n\t/**\n\t * The WORKSPACE knowledge bases this agent reads.\n\t *\n\t * Different from `knowledge` above, and the distinction is the whole point.\n\t * `agent.knowledge` is files this agent owns; nobody else has them. A\n\t * knowledge base is shared: one price list, attached to nine agents, corrected\n\t * in one place.\n\t *\n\t * Each attached base is mounted read-only at `/knowledge/<key>/` when a turn\n\t * starts, so the agent reads it with `ls`, `grep` and `cat`.\n\t *\n\t * ATTACHING PUBLISHES A VERSION. Which bases an agent reads is part of its\n\t * configuration, so the change is diffable and reversible like any other\n\t * configuration change. The CONTENTS of a base are not versioned: correcting\n\t * a file changes what every attached agent sees on its next turn.\n\t */\n\treadonly knowledgeBases = {\n\t\t/**\n\t\t * Attach one base by key.\n\t\t *\n\t\t * One call, not read-modify-write, deliberately. Two attaches racing\n\t\t * through a read of the current list and a write of the whole list would\n\t\t * lose one of them silently, and losing an attachment looks exactly like\n\t\t * an agent that cannot find its knowledge. The server appends.\n\t\t *\n\t\t * Attaching a key that names no base is refused, naming the key. Attaching\n\t\t * one that is already attached is a no-op, not an error.\n\t\t */\n\t\tattach: async (key: string): Promise<Agent> => {\n\t\t\tconst res = await this.#http.post<AgentData>(`${this.base}/knowledge-bases`, { key });\n\t\t\tthis.snapshot = res;\n\t\t\treturn this;\n\t\t},\n\n\t\t/** Detach one base. The base itself and its files are untouched: this only\n\t\t * stops THIS agent from reading it. Detaching one that is not attached is\n\t\t * a no-op. */\n\t\tdetach: async (key: string): Promise<Agent> => {\n\t\t\tconst res = await this.#http.delete<AgentData>(\n\t\t\t\t`${this.base}/knowledge-bases/${encodeURIComponent(key)}`,\n\t\t\t);\n\t\t\tif (res) this.snapshot = res;\n\t\t\treturn this;\n\t\t},\n\n\t\t/** The keys this agent currently reads, in configuration order. */\n\t\tlist: async (): Promise<string[]> => {\n\t\t\tconst current = this.snapshot ?? (await this.get());\n\t\t\treturn current.knowledgeBases ?? [];\n\t\t},\n\t};\n\n\t// -------------------------------------------------------------- databases\n\n\t/**\n\t * The WORKSPACE databases this agent may query, by key.\n\t *\n\t * Register a database first with `ws.databases.create()`, which gives it its\n\t * key; attaching names that key in this agent's configuration. Naming it is\n\t * the grant: the database answers this agent's `sql_*` calls and no agent\n\t * that does not name it, and the agent's prompt lists it by key.\n\t *\n\t * ATTACHING PUBLISHES A VERSION, like a knowledge base: which databases an\n\t * agent reaches is part of its configuration, so the change is diffable and\n\t * reversible. Detaching takes effect on the agent's next query, including in\n\t * a conversation already under way.\n\t */\n\treadonly databases = {\n\t\t/** Attach one database by key. The server appends, so two attaches cannot\n\t\t * lose each other. A key that names no database is refused; one already\n\t\t * attached is a no-op. */\n\t\tattach: async (key: string): Promise<Agent> => {\n\t\t\tconst res = await this.#http.post<AgentData>(`${this.base}/databases`, { key });\n\t\t\tthis.snapshot = res;\n\t\t\treturn this;\n\t\t},\n\n\t\t/** Stop this agent querying one database. The database stays registered\n\t\t * for every other agent that names it. */\n\t\tdetach: async (key: string): Promise<Agent> => {\n\t\t\tconst res = await this.#http.delete<AgentData>(`${this.base}/databases/${encodeURIComponent(key)}`);\n\t\t\tif (res) this.snapshot = res;\n\t\t\treturn this;\n\t\t},\n\n\t\t/** The keys this agent may query, in configuration order. */\n\t\tlist: async (): Promise<string[]> => {\n\t\t\tconst current = this.snapshot ?? (await this.get());\n\t\t\treturn current.databases ?? [];\n\t\t},\n\t};\n\n\t// ------------------------------------------------------------ connections\n\n\t/**\n\t * The apps this agent uses: each a NAMED connection that says WHOSE ACCOUNT\n\t * it uses, built the way the portal's Add a connection screen asks.\n\t *\n\t * | built with | whose account | the person signs in |\n\t * |---|---|---|\n\t * | `Connection.creatorAccount(app, account)` | the agent creator's, from `ws.accounts.connect()` | once, and every conversation uses it |\n\t * | `Connection.endUserAccount(app)` | the end user's: each person talking to the agent | once each, remembered for them |\n\t *\n\t * ```ts\n\t * const { account: work } = await ws.accounts.connect({ app: App.GMAIL, nickname: 'Work' });\n\t * await agent.connections.add(Connection.creatorAccount(App.GMAIL, work, { name: 'work-gmail' }));\n\t * await agent.connections.add(Connection.endUserAccount(App.GOOGLE_CALENDAR));\n\t * ```\n\t *\n\t * A turn uses EXACTLY the account the setup names, and never another one.\n\t * There is no fallback to whichever account of that app happens to exist:\n\t * that fallback is what this replaced, and it meant reading an agent's code\n\t * told you nothing about whose mailbox it read.\n\t *\n\t * EVERY CHANGE PUBLISHES A VERSION, like `databases`: which accounts an\n\t * agent reaches is part of its configuration, so the change is diffable and\n\t * reversible. A conversation uses the connections of the version it runs.\n\t * The ACCOUNTS are not versioned: signing one in again reaches every agent\n\t * that names it, from the next turn.\n\t *\n\t * Removing a connection never touches the account. Disconnecting an account\n\t * is the other operation, on the account: `account.disconnect()`.\n\t */\n\treadonly connections = {\n\t\t/**\n\t\t * Add one connection. One call that publishes, not read-modify-write, so\n\t\t * two adds racing cannot lose each other.\n\t\t *\n\t\t * Takes what `Connection.creatorAccount()` or `Connection.endUserAccount()`\n\t\t * builds, or the same plain object. Refused, naming the problem, when the\n\t\t * name is taken on this agent (`connection_name_taken`), when the account\n\t\t * is of a different app (`account_app_mismatch`), or when no account has\n\t\t * that id (`account_not_found`).\n\t\t */\n\t\tadd: async (connection: Connection): Promise<Agent> => {\n\t\t\tconst res = await this.#http.post<AgentData>(`${this.base}/connections`, connectionForWire(connection));\n\t\t\tthis.snapshot = res;\n\t\t\treturn this;\n\t\t},\n\n\t\t/**\n\t\t * Point one connection at another account: `{ account }` for the agent\n\t\t * creator's (the `Account` you hold, or its id), or `{ endUser: true }`\n\t\t * for each end user's own. The name and the app stay; an account of a\n\t\t * different app is refused (`account_app_mismatch`).\n\t\t *\n\t\t * READ-MODIFY-WRITE, unlike `add` and `remove`, because there is no\n\t\t * route that changes one connection in place: this reads the current\n\t\t * version and publishes it again with the one connection changed. Two\n\t\t * changes racing can therefore lose one, so make them one after the\n\t\t * other. A name the agent does not have throws\n\t\t * (`connection_not_found`) before anything is sent.\n\t\t */\n\t\tchange: async (\n\t\t\tname: string,\n\t\t\tchange: { account: Account | string; endUser?: never } | { endUser: true; account?: never },\n\t\t): Promise<Agent> => {\n\t\t\t// Read FRESH, never from the snapshot. A stale list sent back whole\n\t\t\t// would silently undo whatever changed since it was read.\n\t\t\tconst current = (await this.get()).connections ?? [];\n\t\t\tif (!current.some((c) => c.name === name)) {\n\t\t\t\tthrow new AgentNavaError({\n\t\t\t\t\tmessage: `This agent has no connection named \"${name}\". It has: ${\n\t\t\t\t\t\tcurrent.map((c) => c.name).join(', ') || 'none'\n\t\t\t\t\t}.`,\n\t\t\t\t\tcode: 'connection_not_found',\n\t\t\t\t\tstatus: 404,\n\t\t\t\t});\n\t\t\t}\n\t\t\tconst whose =\n\t\t\t\tchange.endUser === true ? { endUser: true as const } : { account: accountIdOf(change.account as Account | string) };\n\t\t\t// Every other connection goes back exactly as it was read: this changes\n\t\t\t// one, and must not reinterpret the rest.\n\t\t\tconst connections = current.map((c) => (c.name === name ? { name: c.name, app: c.app, ...whose } : c));\n\t\t\tconst data = await this.#http.post<AgentData>(`${this.base}/versions`, { connections });\n\t\t\tthis.snapshot = data;\n\t\t\treturn this;\n\t\t},\n\n\t\t/** Remove one connection by name. Publishes a version. NEVER touches the\n\t\t * account: it stays connected for every other agent that names it, and\n\t\t * for this one if you add it back. */\n\t\tremove: async (name: string): Promise<Agent> => {\n\t\t\tconst res = await this.#http.delete<AgentData>(`${this.base}/connections/${encodeURIComponent(name)}`);\n\t\t\tif (res) this.snapshot = res;\n\t\t\treturn this;\n\t\t},\n\n\t\t/**\n\t\t * Each connection with the account it uses and whether that account works\n\t\t * now: DECLARED IS NOT CONNECTED. An agent can name an account nobody has\n\t\t * finished signing in to, or one that was disconnected since, and that is\n\t\t * the state a setup checklist has to show.\n\t\t *\n\t\t * Includes what an unpublished draft adds (`inDraft`) and removes\n\t\t * (`removedInDraft`), so it matches the portal.\n\t\t */\n\t\tlist: async (): Promise<ConnectionStatus[]> => {\n\t\t\tconst res = await this.#http.get<{ connections: ConnectionStatus[] }>(`${this.base}/connections`);\n\t\t\treturn res.connections ?? [];\n\t\t},\n\t};\n\n\t// ------------------------------------------------------ secrets, agent tier\n\n\t/**\n\t * Write secret VALUES to this agent's own scope: readable by this agent and\n\t * nothing else in the workspace, overriding a workspace secret of the same\n\t * name. Writing one twice replaces the value rather than failing, because\n\t * attaching means \"this is the credential now\".\n\t *\n\t * This used to POST the whole object to `/v1/agents/:id/bindings`, which\n\t * answers only to `{kind, decl}` and records a DECLARATION, never a value. So\n\t * the call 400'd, and had it not, it would have stored the fact that a secret\n\t * is wanted rather than the secret.\n\t */\n\tasync #applyBindings(bindings: Bindings): Promise<Agent> {\n\t\tfor (const [name, value] of Object.entries(bindings.secrets ?? {})) {\n\t\t\tconst mine = (await this.#http.get<{ secrets: { id: string; name: string; agentId?: string | null }[] }>(\n\t\t\t\t'/v1/secrets',\n\t\t\t\t{ agentId: this.id },\n\t\t\t)).secrets ?? [];\n\t\t\tconst existing = mine.find((s) => s.name === name && s.agentId);\n\t\t\tif (existing) await this.#http.patch(`/v1/secrets/${encodeURIComponent(existing.id)}`, { value });\n\t\t\telse await this.#http.post('/v1/secrets', { name, value, agentId: this.id });\n\t\t}\n\t\tconst data = await this.get();\n\t\tthis.snapshot = data;\n\t\treturn new Agent(this.#http, this.id, data);\n\t}\n\n\t/**\n\t * Give this agent secret values, so every conversation with it can use them.\n\t *\n\t * ```ts\n\t * await agent.attach({ secrets: { APOLLO_API_KEY: value } });\n\t * ```\n\t *\n\t * SECRETS ONLY, since 0.44. Accounts used to be attached here, and a turn\n\t * then had to guess which of the accounts attached and owned around it to\n\t * use. The agent's setup now names them: `agent.connections.add()`. One\n\t * handed in here is refused by name (`not_a_secret`) rather than dropped.\n\t *\n\t * A stored `Secret` is not attached to an agent either. It never was: one\n\t * was accepted here and nothing was done with it. Store one for the agent\n\t * with `ws.secrets.create({ name, value, agentId })`, or attach one of your\n\t * end user's to their conversation with `conversation.attach(secret)`.\n\t */\n\tasync attach(bindings: Bindings): Promise<Agent> {\n\t\tif (!isBindings(bindings)) {\n\t\t\tthrow new AgentNavaError({\n\t\t\t\tmessage:\n\t\t\t\t\t'agent.attach takes { secrets: { NAME: value } }. Accounts go in the agent\\'s setup ' +\n\t\t\t\t\t'(agent.connections.add), and a stored secret attaches to a conversation ' +\n\t\t\t\t\t'(conversation.attach).',\n\t\t\t\tcode: 'not_a_secret',\n\t\t\t\tstatus: 400,\n\t\t\t});\n\t\t}\n\t\trefuseConnections(bindings);\n\t\treturn this.#applyBindings(bindings);\n\t}\n\n\t// ----------------------------------------------------------- conversations\n\n\t/** Start a conversation. It pins the agent's version now and keeps it.\n\t *\n\t * Nothing about accounts is passed here: the version's connections name\n\t * them, and a connection to the end user's account uses the account of\n\t * the person named by `endUserId`. */\n\tasync start(options: StartOptions): Promise<Conversation> {\n\t\tconst endUserId = requireEndUserId(options?.endUserId);\n\t\t// Resolved BEFORE the launch: a Secret is named on the wire by the\n\t\t// declared NAME it fills, and a handle addressed by id may not know its\n\t\t// own yet. Anything that is not a Secret is refused here, by name.\n\t\tconst secretIds = await secretIdsOf(secretsIn(options.attach));\n\t\tconst bindings =\n\t\t\toptions.secrets || secretIds\n\t\t\t\t? {\n\t\t\t\t\t\t...(options.secrets && { secrets: options.secrets }),\n\t\t\t\t\t\t...(secretIds && { secretIds }),\n\t\t\t\t\t}\n\t\t\t\t: undefined;\n\t\tconst data = await this.#http.post<AgentConversationData>('/v1/conversations', {\n\t\t\tagentId: this.id,\n\t\t\t...(options.version !== undefined && { version: options.version }),\n\t\t\t...(options.parameters && { parameters: options.parameters }),\n\t\t\t// `sessionBindings`, NOT `secrets` at the top level.\n\t\t\t//\n\t\t\t// This sent them at the top level and the launch route reads\n\t\t\t// `body.sessionBindings`, so they were dropped in silence: the route's\n\t\t\t// own body type has no top-level `secrets` to read. A conversation\n\t\t\t// started with a credential began without it, and the first turn\n\t\t\t// failed somewhere else entirely.\n\t\t\t//\n\t\t\t// Third place this exact envelope mistake was found in one afternoon,\n\t\t\t// after `agent.bind` and `conversation.bind`. The shape of the bug is\n\t\t\t// always the same: the SDK agrees with itself, the route agrees with\n\t\t\t// itself, and nothing compares the two.\n\t\t\t...(bindings && { sessionBindings: bindings }),\n\t\t\t// Always present: requireEndUserId() above has already refused\n\t\t\t// anything that is not a non-empty string.\n\t\t\tuser: { id: endUserId },\n\t\t\t// ALWAYS a new conversation, even when a user is named.\n\t\t\t//\n\t\t\t// The route resumes that user's most recent conversation when it is\n\t\t\t// given an identity and not told otherwise. That default exists for\n\t\t\t// our own web app, where a page reload must not leave a trail of empty\n\t\t\t// conversations, and it is wrong for a method called `start`: a verb\n\t\t\t// that sometimes does not do the thing is worse than two verbs. It is\n\t\t\t// also ambiguous the moment a user has more than one conversation,\n\t\t\t// since it silently picks the newest.\n\t\t\t//\n\t\t\t// So the SDK does not rely on that default. `start` starts. To\n\t\t\t// continue a conversation, hold its id: `agent.conversation(id)`.\n\t\t\tfresh: true,\n\t\t});\n\t\treturn new Conversation(this.#http, data.id, data, { widgets: options.widgets === true });\n\t}\n\n\t/**\n\t * Address one of this agent's conversations by id. No request.\n\t *\n\t * Pass `{ widgets: true }` when the screen continuing it can draw widgets,\n\t * as on `start`: the choice belongs to the screen, so it is made per handle.\n\t *\n\t * Here rather than on the workspace because a conversation belongs to an\n\t * agent. You already hold the agent: it is a constant in your own code, not\n\t * a per-row value, so naming it costs nothing and the ownership is visible.\n\t *\n\t * ```ts\n\t * await ws.agent(AGENT).conversation(row.conversationId).ask('carry on');\n\t * ```\n\t */\n\tconversation(conversationId: string, options: { widgets?: boolean } = {}): Conversation {\n\t\treturn new Conversation(this.#http, conversationId, undefined, { widgets: options.widgets === true });\n\t}\n\n\t/**\n\t * This agent's most recent conversations, newest first.\n\t *\n\t * NOT ALL OF THEM, and the previous sentence here said \"every\", which was\n\t * wrong in the way that costs someone an afternoon. The server returns the\n\t * newest 50 unless you ask for more, and refuses to return more than 200 on\n\t * any single call (apps/api/src/state.ts listAgentSessions, and the Durable\n\t * Object twin beside it, clamp identically).\n\t *\n\t * There is no cursor on this route yet, so an agent with more than 200\n\t * conversations CANNOT be fully enumerated through this method. If you are\n\t * counting or exporting, do not build on it; that needs a paginated route we\n\t * have not added. `ws.endUser(id).conversations()` DOES have a cursor, if\n\t * the question is one person's history rather than one agent's.\n\t *\n\t * `endUser` narrows to one of YOUR end users, which is what you want for a\n\t * \"your conversations\" list. Leaving it out returns everyone's, so leave it\n\t * out only for an operator view.\n\t *\n\t * ```ts\n\t * const mine = await agent.conversations({ endUser: row.userId });\n\t * ```\n\t */\n\tasync conversations(options: { limit?: number; endUser?: string } = {}): Promise<Conversation[]> {\n\t\tconst res = await this.#http.get<{ conversations: AgentConversationData[] }>('/v1/conversations', {\n\t\t\tagentId: this.id,\n\t\t\t...(options.limit !== undefined && { limit: options.limit }),\n\t\t\t// One end user's history. Sending this used to be silently ignored on\n\t\t\t// this route, which answered with everyone's conversations, so an\n\t\t\t// application rendering \"your chats\" showed somebody else's.\n\t\t\t...(options.endUser !== undefined && { end_user_id: options.endUser }),\n\t\t});\n\t\treturn (res.conversations ?? []).map((c) => new Conversation(this.#http, c.id, c));\n\t}\n}\n\n/** GET and PUT /v1/agents/:id/website-chat-access, as sent. */\ninterface WebsiteChatWire {\n\tagentId: string;\n\taccess: WebsiteChatAccess;\n\tchatUrl: string;\n}\n\nfunction toWebsiteChat(wire: WebsiteChatWire): WebsiteChat {\n\treturn { access: wire.access, chatUrl: wire.chatUrl, embedAgentId: wire.agentId };\n}\n\n/** The end user a conversation belongs to: a non-empty string, or a thrown error before any request. */\nfunction requireEndUserId(value: unknown): string {\n\t// Checked at RUNTIME as well as in the type: a JavaScript caller, or a\n\t// TypeScript one reading a nullable column, can still pass null, a number or\n\t// ''. Each used to start an ownerless conversation that looked fine.\n\tif (typeof value === 'string' && value.trim()) return value.trim();\n\tthrow new AgentNavaError({\n\t\tmessage: 'agent.start() needs endUserId: a non-empty string naming who the conversation is for (your user id, a visitor id, or a job name).',\n\t\tcode: 'end_user_required',\n\t\tstatus: 400,\n\t});\n}\n"]}
package/conversation.d.ts CHANGED
@@ -47,7 +47,9 @@ export declare class Conversation {
47
47
  * came from `agent.start()`, absent when it came from `agent.conversation(id)`,
48
48
  * which is exactly the difference between having made a request and not. */
49
49
  private snapshot?;
50
- constructor(http: Http, id: string, snapshot?: AgentConversationData);
50
+ constructor(http: Http, id: string, snapshot?: AgentConversationData, options?: {
51
+ widgets?: boolean;
52
+ });
51
53
  private get base();
52
54
  /**
53
55
  * The agent whose conversation this is.
package/conversation.js CHANGED
@@ -29,11 +29,15 @@ export class Conversation {
29
29
  * came from `agent.start()`, absent when it came from `agent.conversation(id)`,
30
30
  * which is exactly the difference between having made a request and not. */
31
31
  snapshot;
32
- constructor(http, id, snapshot) {
32
+ /** This handle's screen can draw widgets (`start` or `conversation(id)` with
33
+ * `widgets: true`). Sent with every turn, since the screen is what decides. */
34
+ #widgets;
35
+ constructor(http, id, snapshot, options = {}) {
33
36
  this.#http = http;
34
37
  this.id = id;
35
38
  if (snapshot)
36
39
  this.snapshot = snapshot;
40
+ this.#widgets = options.widgets === true;
37
41
  }
38
42
  get base() {
39
43
  return `/v1/conversations/${encodeURIComponent(this.id)}`;
@@ -102,6 +106,7 @@ export class Conversation {
102
106
  body: {
103
107
  content: text,
104
108
  ...(options.attachments?.length && { attachments: options.attachments }),
109
+ ...(this.#widgets && { widgets: true }),
105
110
  },
106
111
  ...(options.signal && { signal: options.signal }),
107
112
  });