@cerebro-labs/agentnava-sdk 0.53.2 → 0.75.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 +3 -2
- package/agent.d.ts +57 -7
- package/agent.js +69 -9
- package/agent.js.map +1 -1
- package/attach.d.ts +3 -0
- package/attach.js.map +1 -1
- package/connection.d.ts +10 -0
- package/connection.js +13 -2
- package/connection.js.map +1 -1
- package/conversation.d.ts +37 -1
- package/conversation.js +28 -2
- package/conversation.js.map +1 -1
- package/end-user.d.ts +10 -0
- package/end-user.js +7 -0
- package/end-user.js.map +1 -1
- package/errors.d.ts +20 -0
- package/errors.js +24 -0
- package/errors.js.map +1 -1
- package/http.d.ts +4 -1
- package/http.js +21 -9
- package/http.js.map +1 -1
- package/import-tools.d.ts +5 -0
- package/import-tools.js +47 -6
- package/import-tools.js.map +1 -1
- package/index.d.ts +4 -3
- package/index.js +2 -1
- package/index.js.map +1 -1
- package/knowledge-base.d.ts +18 -18
- package/knowledge-base.js +28 -0
- package/knowledge-base.js.map +1 -1
- package/package.json +1 -1
- package/partner-app.d.ts +70 -0
- package/partner-app.js +125 -0
- package/partner-app.js.map +1 -0
- package/react.css +177 -28
- package/react.js +142 -22
- package/react.js.map +1 -1
- package/secret.d.ts +6 -0
- package/secret.js +15 -0
- package/secret.js.map +1 -1
- package/turn.js +6 -0
- package/turn.js.map +1 -1
- package/types.d.ts +144 -0
- package/types.js.map +1 -1
- package/version.d.ts +1 -1
- package/version.js +1 -1
- package/version.js.map +1 -1
- package/workspace.d.ts +35 -1
- package/workspace.js +35 -0
- package/workspace.js.map +1 -1
package/README.md
CHANGED
|
@@ -109,6 +109,7 @@ were removed rather than deprecated.
|
|
|
109
109
|
| `agent.attach(connection)` | `agent.connections.add(Connection.creatorAccount(app, account, { name? }))` |
|
|
110
110
|
| none | `agent.connections.add(Connection.endUserAccount(app, { name? }))` |
|
|
111
111
|
| none | `agent.connections.change(name, { account })` or `(name, { endUser: true })` |
|
|
112
|
+
| none | `agent.connections.change(name, { tools })`: which of the app's own tools it may use, ids from `ws.apps.tools(app)`; `null` for the app's default |
|
|
112
113
|
| `agent.disconnect(provider)`, which deleted the shared account | `agent.connections.remove(name)`, which never touches the account |
|
|
113
114
|
| `agent.connections()` | `agent.connections.list()` |
|
|
114
115
|
| `agent.attach(secret)`, which was accepted and did nothing | refused with `not_a_secret`; attach a stored secret to a conversation instead |
|
|
@@ -118,8 +119,8 @@ were removed rather than deprecated.
|
|
|
118
119
|
| `endUser.connections.create({ provider })` | `endUser.accounts.connect({ app })` |
|
|
119
120
|
| `endUser.connections.list()` | `endUser.accounts.list()` |
|
|
120
121
|
| `endUser.revokeConnections()` | `endUser.accounts.disconnectAll()`, returns `{ disconnected }` |
|
|
121
|
-
| setup `connections: [{ provider, scope: 'fixed', connectionId }]` | `Connection.creatorAccount(app, account, { name? })`, which is `{ name?, app, account: '<id>' }` |
|
|
122
|
-
| setup `connections: [{ provider, scope: 'conversation' }]` | `Connection.endUserAccount(app, { name? })`, which is `{ name?, app, endUser: true }` |
|
|
122
|
+
| setup `connections: [{ provider, scope: 'fixed', connectionId }]` | `Connection.creatorAccount(app, account, { name?, tools? })`, which is `{ name?, app, account: '<id>', tools? }` |
|
|
123
|
+
| setup `connections: [{ provider, scope: 'conversation' }]` | `Connection.endUserAccount(app, { name?, tools? })`, which is `{ name?, app, endUser: true, tools? }` |
|
|
123
124
|
| type `ConnectionRequirement` | `AgentConnection` (as read back) and `Connection` (as you send it), with `CreatorAccountConnection` and `EndUserAccountConnection` |
|
|
124
125
|
| type `ConnectionStatus`, keyed by `provider` | `ConnectionStatus`, keyed by `name`: `{ name, app, account?, endUser?, status, inDraft, removedInDraft }` |
|
|
125
126
|
| type `CredentialOwner` | removed: `AccountData.owner` is `'workspace'` or `'end-user'` |
|
package/agent.d.ts
CHANGED
|
@@ -2,8 +2,9 @@ import { type Account } from './account.ts';
|
|
|
2
2
|
import { Conversation } from './conversation.ts';
|
|
3
3
|
import type { Http } from './http.ts';
|
|
4
4
|
import type { Secret } from './secret.ts';
|
|
5
|
+
import { type Turn } from './turn.ts';
|
|
5
6
|
import { type Connection } from './connection.ts';
|
|
6
|
-
import type { AgentData, AgentFields, Bindings, ConnectionStatus, FileEntry, Trigger, WebsiteChat, WebsiteChatAccess, Workflow, WebhookDelivery } from './types.ts';
|
|
7
|
+
import type { AgentData, AgentDraft, AgentFields, Bindings, ConnectionStatus, FileEntry, Trigger, WebsiteChat, WebsiteChatAccess, Workflow, WebhookDelivery } from './types.ts';
|
|
7
8
|
export interface StartOptions {
|
|
8
9
|
/**
|
|
9
10
|
* Stored secrets to attach AS THE CONVERSATION STARTS.
|
|
@@ -21,6 +22,11 @@ export interface StartOptions {
|
|
|
21
22
|
* closes a real window: between `start` and the attach, the conversation
|
|
22
23
|
* exists and can be asked something, and it would answer without it.
|
|
23
24
|
*
|
|
25
|
+
* The conversation keeps a POINTER to the secret, never a copy. Replacing
|
|
26
|
+
* its value (`secret.update(value)`) reaches the conversation on its next
|
|
27
|
+
* tool call, and deleting the secret stops the conversation using it at
|
|
28
|
+
* once.
|
|
29
|
+
*
|
|
24
30
|
* ACCOUNTS ARE NOT ATTACHED HERE any more (0.44), and one handed in is
|
|
25
31
|
* refused. The agent's setup names the account each connection uses; for a
|
|
26
32
|
* connection to the end user's account (`Connection.endUserAccount`), the
|
|
@@ -35,8 +41,17 @@ export interface StartOptions {
|
|
|
35
41
|
* Not `attach`, because a secret has no id you can hand over: binding one
|
|
36
42
|
* takes the value itself. That asymmetry is in the product, not in this
|
|
37
43
|
* naming, and hiding it behind the same word would not remove it.
|
|
44
|
+
*
|
|
45
|
+
* A value given here EXPIRES, after `secretsExpireIn` seconds (one hour by
|
|
46
|
+
* default). After that the agent's tools say the sign-in expired, the
|
|
47
|
+
* conversation lists the name in `requires`, and a turn starts with a
|
|
48
|
+
* `credential_needed` event. Push a fresh value with
|
|
49
|
+
* `conversation.ask(text, { secrets })` or `conversation.attach({ secrets })`.
|
|
38
50
|
*/
|
|
39
51
|
secrets?: Record<string, string>;
|
|
52
|
+
/** How long the values in `secrets` stay usable, in seconds. Default 3600
|
|
53
|
+
* (one hour), at most 86400 (one day). */
|
|
54
|
+
secretsExpireIn?: number;
|
|
40
55
|
/** Pin a specific version. Defaults to the latest at the moment of starting.
|
|
41
56
|
*
|
|
42
57
|
* A conversation pins its version for life: publishing afterwards does not
|
|
@@ -136,6 +151,26 @@ export declare class Agent {
|
|
|
136
151
|
* over the wire as its id (`Account.toJSON`). */
|
|
137
152
|
update(fields: AgentFields): Promise<Agent>;
|
|
138
153
|
delete(): Promise<void>;
|
|
154
|
+
/**
|
|
155
|
+
* The Agent Builder, the one behind the portal's Configure chat, working on
|
|
156
|
+
* this agent. Most of what it changes lands in the agent's DRAFT, read with
|
|
157
|
+
* `draft()`; two of its tools act at once, renaming the agent and importing
|
|
158
|
+
* a website into the agent's files. The draft is the one the portal edits,
|
|
159
|
+
* shared with anyone changing the agent there, and each message joins the
|
|
160
|
+
* agent's one Configure conversation. So to take only part of what it writes,
|
|
161
|
+
* run it on an agent nobody else edits (a copy made for the purpose), read
|
|
162
|
+
* that copy's draft, publish what you keep on the real agent with
|
|
163
|
+
* `update()`, and delete the copy. Builder messages cost no credits and
|
|
164
|
+
* count towards a daily limit per workspace.
|
|
165
|
+
*/
|
|
166
|
+
readonly builder: {
|
|
167
|
+
/** Send the Builder one message. Await the turn for its reply, or iterate it for the events. `signal` stops waiting for it. */
|
|
168
|
+
ask: (message: string, options?: {
|
|
169
|
+
signal?: AbortSignal;
|
|
170
|
+
}) => Turn;
|
|
171
|
+
};
|
|
172
|
+
/** The agent as its draft holds it, and whether that draft has changes not yet published. With no draft, the live version. */
|
|
173
|
+
draft(): Promise<AgentDraft>;
|
|
139
174
|
/**
|
|
140
175
|
* Add a workflow, or replace the one with the same name.
|
|
141
176
|
*
|
|
@@ -351,6 +386,11 @@ export declare class Agent {
|
|
|
351
386
|
* for each end user's own. The name and the app stay; an account of a
|
|
352
387
|
* different app is refused (`account_app_mismatch`).
|
|
353
388
|
*
|
|
389
|
+
* `tools` changes which of the app's own tools the agent may use (a list
|
|
390
|
+
* of ids, `[]` for none, `null` for the app's default), alone or with the
|
|
391
|
+
* account. It is set for every connection of that app on the agent,
|
|
392
|
+
* which share one list. Left out, the tools stay as they are.
|
|
393
|
+
*
|
|
354
394
|
* READ-MODIFY-WRITE, unlike `add` and `remove`, because there is no
|
|
355
395
|
* route that changes one connection in place: this reads the current
|
|
356
396
|
* version and publishes it again with the one connection changed. Two
|
|
@@ -358,12 +398,17 @@ export declare class Agent {
|
|
|
358
398
|
* other. A name the agent does not have throws
|
|
359
399
|
* (`connection_not_found`) before anything is sent.
|
|
360
400
|
*/
|
|
361
|
-
change: (name: string, change: {
|
|
401
|
+
change: (name: string, change: ({
|
|
362
402
|
account: Account | string;
|
|
363
403
|
endUser?: never;
|
|
364
404
|
} | {
|
|
365
405
|
endUser: true;
|
|
366
406
|
account?: never;
|
|
407
|
+
} | {
|
|
408
|
+
account?: never;
|
|
409
|
+
endUser?: never;
|
|
410
|
+
}) & {
|
|
411
|
+
tools?: string[] | null;
|
|
367
412
|
}) => Promise<Agent>;
|
|
368
413
|
/** Remove one connection by name. Publishes a version. NEVER touches the
|
|
369
414
|
* account: it stays connected for every other agent that names it, and
|
|
@@ -430,22 +475,27 @@ export declare class Agent {
|
|
|
430
475
|
* any single call (apps/api/src/state.ts listAgentSessions, and the Durable
|
|
431
476
|
* Object twin beside it, clamp identically).
|
|
432
477
|
*
|
|
433
|
-
*
|
|
434
|
-
*
|
|
435
|
-
*
|
|
436
|
-
* have not added. `ws.endUser(id).conversations()` DOES have a cursor, if
|
|
437
|
-
* the question is one person's history rather than one agent's.
|
|
478
|
+
* For the next page, pass `before`: the `startedAt` of the last conversation
|
|
479
|
+
* you got. `ws.endUser(id).conversations()` also pages, if the question is
|
|
480
|
+
* one person's history rather than one agent's.
|
|
438
481
|
*
|
|
439
482
|
* `endUser` narrows to one of YOUR end users, which is what you want for a
|
|
440
483
|
* "your conversations" list. Leaving it out returns everyone's, so leave it
|
|
441
484
|
* out only for an operator view.
|
|
442
485
|
*
|
|
486
|
+
* `of: 'customers'` keeps only your end users' conversations, leaving out
|
|
487
|
+
* the team's own (members trying the agent, jobs, webhooks); `of: 'team'`
|
|
488
|
+
* is the other half. Left out, both.
|
|
489
|
+
*
|
|
443
490
|
* ```ts
|
|
444
491
|
* const mine = await agent.conversations({ endUser: row.userId });
|
|
492
|
+
* const shoppers = await agent.conversations({ of: 'customers', limit: 5 });
|
|
445
493
|
* ```
|
|
446
494
|
*/
|
|
447
495
|
conversations(options?: {
|
|
448
496
|
limit?: number;
|
|
449
497
|
endUser?: string;
|
|
498
|
+
before?: string;
|
|
499
|
+
of?: 'customers' | 'team';
|
|
450
500
|
}): Promise<Conversation[]>;
|
|
451
501
|
}
|
package/agent.js
CHANGED
|
@@ -4,6 +4,7 @@ import { accountIdOf } from "./account.js";
|
|
|
4
4
|
import { isBindings, refuseConnections, secretIdsOf, secretsIn } from "./attach.js";
|
|
5
5
|
import { Conversation } from "./conversation.js";
|
|
6
6
|
import { AgentNavaError } from "./errors.js";
|
|
7
|
+
import { makeTurn } from "./turn.js";
|
|
7
8
|
import { connectionForWire } from "./connection.js";
|
|
8
9
|
/**
|
|
9
10
|
* An agent you can configure and start conversations from.
|
|
@@ -59,6 +60,32 @@ export class Agent {
|
|
|
59
60
|
async delete() {
|
|
60
61
|
await this.#http.delete(this.base);
|
|
61
62
|
}
|
|
63
|
+
// ----------------------------------------------------- draft and builder
|
|
64
|
+
/**
|
|
65
|
+
* The Agent Builder, the one behind the portal's Configure chat, working on
|
|
66
|
+
* this agent. Most of what it changes lands in the agent's DRAFT, read with
|
|
67
|
+
* `draft()`; two of its tools act at once, renaming the agent and importing
|
|
68
|
+
* a website into the agent's files. The draft is the one the portal edits,
|
|
69
|
+
* shared with anyone changing the agent there, and each message joins the
|
|
70
|
+
* agent's one Configure conversation. So to take only part of what it writes,
|
|
71
|
+
* run it on an agent nobody else edits (a copy made for the purpose), read
|
|
72
|
+
* that copy's draft, publish what you keep on the real agent with
|
|
73
|
+
* `update()`, and delete the copy. Builder messages cost no credits and
|
|
74
|
+
* count towards a daily limit per workspace.
|
|
75
|
+
*/
|
|
76
|
+
builder = {
|
|
77
|
+
/** Send the Builder one message. Await the turn for its reply, or iterate it for the events. `signal` stops waiting for it. */
|
|
78
|
+
ask: (message, options = {}) => makeTurn(this.#http.send(`${this.base}/build`, { method: 'POST', body: { message }, ...(options.signal && { signal: options.signal }) })),
|
|
79
|
+
};
|
|
80
|
+
/** The agent as its draft holds it, and whether that draft has changes not yet published. With no draft, the live version. */
|
|
81
|
+
async draft() {
|
|
82
|
+
const res = await this.#http.get(`${this.base}/spec`);
|
|
83
|
+
return {
|
|
84
|
+
exists: res.isDraft === true,
|
|
85
|
+
hasUnpublishedChanges: res.hasUnpublishedChanges === true,
|
|
86
|
+
config: res.spec,
|
|
87
|
+
};
|
|
88
|
+
}
|
|
62
89
|
// --------------------------------------------------------------- workflows
|
|
63
90
|
/**
|
|
64
91
|
* Add a workflow, or replace the one with the same name.
|
|
@@ -356,6 +383,11 @@ export class Agent {
|
|
|
356
383
|
* for each end user's own. The name and the app stay; an account of a
|
|
357
384
|
* different app is refused (`account_app_mismatch`).
|
|
358
385
|
*
|
|
386
|
+
* `tools` changes which of the app's own tools the agent may use (a list
|
|
387
|
+
* of ids, `[]` for none, `null` for the app's default), alone or with the
|
|
388
|
+
* account. It is set for every connection of that app on the agent,
|
|
389
|
+
* which share one list. Left out, the tools stay as they are.
|
|
390
|
+
*
|
|
359
391
|
* READ-MODIFY-WRITE, unlike `add` and `remove`, because there is no
|
|
360
392
|
* route that changes one connection in place: this reads the current
|
|
361
393
|
* version and publishes it again with the one connection changed. Two
|
|
@@ -374,10 +406,31 @@ export class Agent {
|
|
|
374
406
|
status: 404,
|
|
375
407
|
});
|
|
376
408
|
}
|
|
377
|
-
const
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
409
|
+
const target = current.find((c) => c.name === name);
|
|
410
|
+
const whose = change.endUser === true
|
|
411
|
+
? { endUser: true }
|
|
412
|
+
: change.account !== undefined
|
|
413
|
+
? { account: accountIdOf(change.account) }
|
|
414
|
+
: target.endUser === true
|
|
415
|
+
? { endUser: true }
|
|
416
|
+
: { account: target.account };
|
|
417
|
+
// The tools as they were, unless this changes them; a change reaches
|
|
418
|
+
// every connection of the app, which share one list.
|
|
419
|
+
const toolsOf = (c) => change.tools === undefined
|
|
420
|
+
? c.tools && { tools: c.tools }
|
|
421
|
+
: c.app === target.app && change.tools !== null
|
|
422
|
+
? { tools: [...change.tools] }
|
|
423
|
+
: c.app === target.app
|
|
424
|
+
? {}
|
|
425
|
+
: c.tools && { tools: c.tools };
|
|
426
|
+
// Every other connection goes back as it was read, its tools aside:
|
|
427
|
+
// this changes one, and must not reinterpret the rest.
|
|
428
|
+
const connections = current.map((c) => {
|
|
429
|
+
const { tools: _tools, ...rest } = c;
|
|
430
|
+
if (c.name === name)
|
|
431
|
+
return { name: c.name, app: c.app, ...whose, ...toolsOf(c) };
|
|
432
|
+
return { ...rest, ...toolsOf(c) };
|
|
433
|
+
});
|
|
381
434
|
const data = await this.#http.post(`${this.base}/versions`, { connections });
|
|
382
435
|
this.snapshot = data;
|
|
383
436
|
return this;
|
|
@@ -475,6 +528,7 @@ export class Agent {
|
|
|
475
528
|
const bindings = options.secrets || secretIds
|
|
476
529
|
? {
|
|
477
530
|
...(options.secrets && { secrets: options.secrets }),
|
|
531
|
+
...(options.secrets && options.secretsExpireIn !== undefined && { expiresInSeconds: options.secretsExpireIn }),
|
|
478
532
|
...(secretIds && { secretIds }),
|
|
479
533
|
}
|
|
480
534
|
: undefined;
|
|
@@ -540,28 +594,34 @@ export class Agent {
|
|
|
540
594
|
* any single call (apps/api/src/state.ts listAgentSessions, and the Durable
|
|
541
595
|
* Object twin beside it, clamp identically).
|
|
542
596
|
*
|
|
543
|
-
*
|
|
544
|
-
*
|
|
545
|
-
*
|
|
546
|
-
* have not added. `ws.endUser(id).conversations()` DOES have a cursor, if
|
|
547
|
-
* the question is one person's history rather than one agent's.
|
|
597
|
+
* For the next page, pass `before`: the `startedAt` of the last conversation
|
|
598
|
+
* you got. `ws.endUser(id).conversations()` also pages, if the question is
|
|
599
|
+
* one person's history rather than one agent's.
|
|
548
600
|
*
|
|
549
601
|
* `endUser` narrows to one of YOUR end users, which is what you want for a
|
|
550
602
|
* "your conversations" list. Leaving it out returns everyone's, so leave it
|
|
551
603
|
* out only for an operator view.
|
|
552
604
|
*
|
|
605
|
+
* `of: 'customers'` keeps only your end users' conversations, leaving out
|
|
606
|
+
* the team's own (members trying the agent, jobs, webhooks); `of: 'team'`
|
|
607
|
+
* is the other half. Left out, both.
|
|
608
|
+
*
|
|
553
609
|
* ```ts
|
|
554
610
|
* const mine = await agent.conversations({ endUser: row.userId });
|
|
611
|
+
* const shoppers = await agent.conversations({ of: 'customers', limit: 5 });
|
|
555
612
|
* ```
|
|
556
613
|
*/
|
|
557
614
|
async conversations(options = {}) {
|
|
558
615
|
const res = await this.#http.get('/v1/conversations', {
|
|
559
616
|
agentId: this.id,
|
|
560
617
|
...(options.limit !== undefined && { limit: options.limit }),
|
|
618
|
+
// The next page, newest first: pass the `startedAt` of the last one you got.
|
|
619
|
+
...(options.before !== undefined && { before: options.before }),
|
|
561
620
|
// One end user's history. Sending this used to be silently ignored on
|
|
562
621
|
// this route, which answered with everyone's conversations, so an
|
|
563
622
|
// application rendering "your chats" showed somebody else's.
|
|
564
623
|
...(options.endUser !== undefined && { end_user_id: options.endUser }),
|
|
624
|
+
...(options.of !== undefined && { of: options.of }),
|
|
565
625
|
});
|
|
566
626
|
return (res.conversations ?? []).map((c) => new Conversation(this.#http, c.id, c));
|
|
567
627
|
}
|
package/agent.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"AAAA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AAC,CAAC,CAAC;IACpF,CAAC;CACD;;AASD,SAAS,aAAa,CAAC,IAAqB;IAC3C,OAAO,EAAE,MAAM,EAAE,IAAI,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,OAAO,EAAE,YAAY,EAAE,IAAI,CAAC,OAAO,EAAE,CAAC;AACnF,CAAC;AAED,wGAAwG;AACxG,SAAS,gBAAgB,CAAC,KAAc;IACvC,uEAAuE;IACvE,6EAA6E;IAC7E,qEAAqE;IACrE,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,CAAC,IAAI,EAAE;QAAE,OAAO,KAAK,CAAC,IAAI,EAAE,CAAC;IACnE,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\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 open 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 * Draw them with `ReplyView` from `@cerebro-labs/agentnava-sdk/react`, or your own components.\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/** Upload a logo for the chat's look: PNG, JPG, WebP or SVG, up to 1 MB\n\t\t * (an SVG carrying script is refused). Returns its id, to set as\n\t\t * `appearance.logo` with `update()`, and where it is served. The same\n\t\t * bytes always give the same id. */\n\t\tuploadLogo: async (bytes: Uint8Array | ArrayBuffer, contentType?: string): Promise<{ id: string; url: string }> =>\n\t\t\tthis.#http.request<{ id: string; url: string }>(`${this.base}/images`, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbytes,\n\t\t\t\t...(contentType && { contentType }),\n\t\t\t}),\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"]}
|
|
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,EAAE,QAAQ,EAAa,MAAM,WAAW,CAAC;AAChD,OAAO,EAA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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 { makeTurn, type Turn } from './turn.ts';\nimport { type Connection, connectionForWire } from './connection.ts';\nimport type {\n\tAgentConnection,\n\tAgentConversationData,\n\tAgentData,\n\tAgentDraft,\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 * The conversation keeps a POINTER to the secret, never a copy. Replacing\n\t * its value (`secret.update(value)`) reaches the conversation on its next\n\t * tool call, and deleting the secret stops the conversation using it at\n\t * once.\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\t * A value given here EXPIRES, after `secretsExpireIn` seconds (one hour by\n\t * default). After that the agent's tools say the sign-in expired, the\n\t * conversation lists the name in `requires`, and a turn starts with a\n\t * `credential_needed` event. Push a fresh value with\n\t * `conversation.ask(text, { secrets })` or `conversation.attach({ secrets })`.\n\t */\n\tsecrets?: Record<string, string>;\n\n\t/** How long the values in `secrets` stay usable, in seconds. Default 3600\n\t * (one hour), at most 86400 (one day). */\n\tsecretsExpireIn?: number;\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 open 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 * Draw them with `ReplyView` from `@cerebro-labs/agentnava-sdk/react`, or your own components.\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// ----------------------------------------------------- draft and builder\n\n\t/**\n\t * The Agent Builder, the one behind the portal's Configure chat, working on\n\t * this agent. Most of what it changes lands in the agent's DRAFT, read with\n\t * `draft()`; two of its tools act at once, renaming the agent and importing\n\t * a website into the agent's files. The draft is the one the portal edits,\n\t * shared with anyone changing the agent there, and each message joins the\n\t * agent's one Configure conversation. So to take only part of what it writes,\n\t * run it on an agent nobody else edits (a copy made for the purpose), read\n\t * that copy's draft, publish what you keep on the real agent with\n\t * `update()`, and delete the copy. Builder messages cost no credits and\n\t * count towards a daily limit per workspace.\n\t */\n\treadonly builder = {\n\t\t/** Send the Builder one message. Await the turn for its reply, or iterate it for the events. `signal` stops waiting for it. */\n\t\task: (message: string, options: { signal?: AbortSignal } = {}): Turn =>\n\t\t\tmakeTurn(this.#http.send(`${this.base}/build`, { method: 'POST', body: { message }, ...(options.signal && { signal: options.signal }) })),\n\t};\n\n\t/** The agent as its draft holds it, and whether that draft has changes not yet published. With no draft, the live version. */\n\tasync draft(): Promise<AgentDraft> {\n\t\tconst res = await this.#http.get<DraftWire>(`${this.base}/spec`);\n\t\treturn {\n\t\t\texists: res.isDraft === true,\n\t\t\thasUnpublishedChanges: res.hasUnpublishedChanges === true,\n\t\t\tconfig: res.spec,\n\t\t};\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/** Upload a logo for the chat's look: PNG, JPG, WebP or SVG, up to 1 MB\n\t\t * (an SVG carrying script is refused). Returns its id, to set as\n\t\t * `appearance.logo` with `update()`, and where it is served. The same\n\t\t * bytes always give the same id. */\n\t\tuploadLogo: async (bytes: Uint8Array | ArrayBuffer, contentType?: string): Promise<{ id: string; url: string }> =>\n\t\t\tthis.#http.request<{ id: string; url: string }>(`${this.base}/images`, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\tbytes,\n\t\t\t\t...(contentType && { contentType }),\n\t\t\t}),\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 * `tools` changes which of the app's own tools the agent may use (a list\n\t\t * of ids, `[]` for none, `null` for the app's default), alone or with the\n\t\t * account. It is set for every connection of that app on the agent,\n\t\t * which share one list. Left out, the tools stay as they are.\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: (\n\t\t\t\t| { account: Account | string; endUser?: never }\n\t\t\t\t| { endUser: true; account?: never }\n\t\t\t\t| { account?: never; endUser?: never }\n\t\t\t) & { tools?: string[] | null },\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 target = current.find((c) => c.name === name) as AgentConnection;\n\t\t\tconst whose =\n\t\t\t\tchange.endUser === true\n\t\t\t\t\t? { endUser: true as const }\n\t\t\t\t\t: change.account !== undefined\n\t\t\t\t\t\t? { account: accountIdOf(change.account) }\n\t\t\t\t\t\t: target.endUser === true\n\t\t\t\t\t\t\t? { endUser: true as const }\n\t\t\t\t\t\t\t: { account: target.account as string };\n\t\t\t// The tools as they were, unless this changes them; a change reaches\n\t\t\t// every connection of the app, which share one list.\n\t\t\tconst toolsOf = (c: AgentConnection) =>\n\t\t\t\tchange.tools === undefined\n\t\t\t\t\t? c.tools && { tools: c.tools }\n\t\t\t\t\t: c.app === target.app && change.tools !== null\n\t\t\t\t\t\t? { tools: [...change.tools] }\n\t\t\t\t\t\t: c.app === target.app\n\t\t\t\t\t\t\t? {}\n\t\t\t\t\t\t\t: c.tools && { tools: c.tools };\n\t\t\t// Every other connection goes back as it was read, its tools aside:\n\t\t\t// this changes one, and must not reinterpret the rest.\n\t\t\tconst connections = current.map((c) => {\n\t\t\t\tconst { tools: _tools, ...rest } = c;\n\t\t\t\tif (c.name === name) return { name: c.name, app: c.app, ...whose, ...toolsOf(c) };\n\t\t\t\treturn { ...rest, ...toolsOf(c) };\n\t\t\t});\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...(options.secrets && options.secretsExpireIn !== undefined && { expiresInSeconds: options.secretsExpireIn }),\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 * For the next page, pass `before`: the `startedAt` of the last conversation\n\t * you got. `ws.endUser(id).conversations()` also pages, if the question is\n\t * 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 * `of: 'customers'` keeps only your end users' conversations, leaving out\n\t * the team's own (members trying the agent, jobs, webhooks); `of: 'team'`\n\t * is the other half. Left out, both.\n\t *\n\t * ```ts\n\t * const mine = await agent.conversations({ endUser: row.userId });\n\t * const shoppers = await agent.conversations({ of: 'customers', limit: 5 });\n\t * ```\n\t */\n\tasync conversations(options: { limit?: number; endUser?: string; before?: string; of?: 'customers' | 'team' } = {}): 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// The next page, newest first: pass the `startedAt` of the last one you got.\n\t\t\t...(options.before !== undefined && { before: options.before }),\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\t...(options.of !== undefined && { of: options.of }),\n\t\t});\n\t\treturn (res.conversations ?? []).map((c) => new Conversation(this.#http, c.id, c));\n\t}\n}\n\n/** What GET /v1/agents/:id/spec answers, as far as `draft()` reads it. */\ninterface DraftWire {\n\tisDraft?: boolean;\n\thasUnpublishedChanges?: boolean;\n\tspec: AgentFields;\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/attach.d.ts
CHANGED
|
@@ -5,6 +5,9 @@ import type { Bindings } from './types.ts';
|
|
|
5
5
|
export interface SessionBindings {
|
|
6
6
|
secrets?: Record<string, string>;
|
|
7
7
|
secretIds?: Record<string, string>;
|
|
8
|
+
/** How long the values in `secrets` stay usable, in seconds (the API's
|
|
9
|
+
* default is one hour, its maximum one day). */
|
|
10
|
+
expiresInSeconds?: number;
|
|
8
11
|
}
|
|
9
12
|
/**
|
|
10
13
|
* Distinguish `attach({ secrets })` from `attach(secret)`.
|
package/attach.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"attach.js","sourceRoot":"","sources":["../src/attach.ts"],"names":[],"mappings":"AAAA,qEAAqE;AACrE,EAAE;AACF,4EAA4E;AAC5E,0EAA0E;AAC1E,4EAA4E;AAC5E,gFAAgF;AAChF,gDAAgD;AAChD,EAAE;AACF,+EAA+E;AAC/E,2EAA2E;AAC3E,6EAA6E;AAC7E,8EAA8E;AAC9E,+EAA+E;AAC/E,WAAW;AAEX,OAAO,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AAC7C,6EAA6E;AAC7E,8DAA8D;AAC9D,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"attach.js","sourceRoot":"","sources":["../src/attach.ts"],"names":[],"mappings":"AAAA,qEAAqE;AACrE,EAAE;AACF,4EAA4E;AAC5E,0EAA0E;AAC1E,4EAA4E;AAC5E,gFAAgF;AAChF,gDAAgD;AAChD,EAAE;AACF,+EAA+E;AAC/E,2EAA2E;AAC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,cAAc,CAAC;gBACxB,OAAO,EAAE,0BAA0B,cAAc,EAAE;gBACnD,IAAI,EAAE,cAAc;gBACpB,MAAM,EAAE,GAAG;aACX,CAAC,CAAC;QACJ,CAAC;IACF,CAAC;IACD,OAAO,IAAI,CAAC;AACb,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,KAAK,UAAU,WAAW,CAChC,IAAmC;IAEnC,IAAI,CAAC,IAAI;QAAE,OAAO,SAAS,CAAC;IAC5B,MAAM,IAAI,GAAG,KAAK,CAAC,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;IACjD,IAAI,IAAI,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,SAAS,CAAC;IACxC,MAAM,GAAG,GAA2B,EAAE,CAAC;IACvC,KAAK,MAAM,MAAM,IAAI,IAAI,EAAE,CAAC;QAC3B,MAAM,IAAI,GAAG,MAAM,CAAC,IAAI,IAAI,CAAC,MAAM,MAAM,CAAC,GAAG,EAAE,CAAC,CAAC,IAAI,CAAC;QACtD,oEAAoE;QACpE,wEAAwE;QACxE,sCAAsC;QACtC,IAAI,GAAG,CAAC,IAAI,CAAC,IAAI,GAAG,CAAC,IAAI,CAAC,KAAK,MAAM,CAAC,EAAE,EAAE,CAAC;YAC1C,MAAM,IAAI,KAAK,CACd,0CAA0C,IAAI,KAAK,GAAG,CAAC,IAAI,CAAC,QAAQ,MAAM,CAAC,EAAE,EAAE,CAC/E,CAAC;QACH,CAAC;QACD,GAAG,CAAC,IAAI,CAAC,GAAG,MAAM,CAAC,EAAE,CAAC;IACvB,CAAC;IACD,OAAO,GAAG,CAAC;AACZ,CAAC","sourcesContent":["// Turning the secrets a caller is holding into what the wire speaks.\n//\n// ITS OWN MODULE because `agent.ts` already imports `conversation.ts`, so a\n// helper living in either one and used by both is a cycle. Shared so that\n// `agent.start`, `agent.attach` and `conversation.attach` cannot drift: all\n// three had to agree on this shape, and when they did not, the disagreement was\n// invisible until a turn failed somewhere else.\n//\n// SECRETS ONLY, since 0.44. Accounts used to be attached here too, to an agent\n// or to one conversation, and a turn then had to work out which of several\n// attached and owned accounts to use. An agent's setup now names the account\n// each connection uses (`agent.connections.add`), so there is nothing left to\n// attach, and an account handed to any of these is refused by name rather than\n// dropped.\n\nimport { AgentNavaError } from './errors.ts';\n// A VALUE import, not type-only, because the check below is an `instanceof`.\n// secret.ts imports nothing but types, so this adds no cycle.\nimport { Secret } from './secret.ts';\nimport type { Bindings } from './types.ts';\n\n/** What the launch and the conversation's bindings route take: secret VALUES\n * by declared name, and stored secrets by id. */\nexport interface SessionBindings {\n\tsecrets?: Record<string, string>;\n\tsecretIds?: Record<string, string>;\n\t/** How long the values in `secrets` stay usable, in seconds (the API's\n\t * default is one hour, its maximum one day). */\n\texpiresInSeconds?: number;\n}\n\n/**\n * Distinguish `attach({ secrets })` from `attach(secret)`.\n *\n * Structural rather than `instanceof`, so a plain object built anywhere is\n * still recognised. A Secret always has an `id`; a Bindings object does not.\n * `connections` is recognised too, only so it can be refused by name below.\n */\nexport function isBindings(what: unknown): what is Bindings {\n\tif (Array.isArray(what) || what === null || typeof what !== 'object') return false;\n\tconst o = what as Record<string, unknown>;\n\treturn !('id' in o) && ('secrets' in o || 'connections' in o);\n}\n\n/** The words every refusal below uses, so an upgrader reads one explanation. */\nconst ACCOUNTS_MOVED =\n\t'Accounts are not attached any more (0.44): name the account in the agent\\'s setup with ' +\n\t'agent.connections.add(Connection.creatorAccount(app, account)), or use ' +\n\t'Connection.endUserAccount(app) so each person signs in with their own.';\n\n/** Refuse `{ connections }`. A JavaScript caller still holding 0.43 code would\n * otherwise have it dropped in silence, and the agent would answer without the\n * account it was plainly given. */\nexport function refuseConnections(bindings: Bindings): void {\n\tif ('connections' in (bindings as Record<string, unknown>)) {\n\t\tthrow new AgentNavaError({ message: ACCOUNTS_MOVED, code: 'not_a_secret', status: 400 });\n\t}\n}\n\n/**\n * Check that everything handed to `attach` is a Secret, and hand back the list.\n *\n * BY `instanceof`, not by duck-typing: a Secret addressed with `ws.secret(id)`\n * has no `name` until it reads one, so \"has a name\" answers wrongly for exactly\n * the handles that need it most.\n *\n * Refused rather than ignored. Silently dropping an unrecognised attachment is\n * how a conversation starts without the credential its caller plainly\n * attached, and the failure then appears one layer down as a tool that cannot\n * authenticate.\n */\nexport function secretsIn(what: Secret | Secret[] | undefined): Secret[] {\n\tconst list = what === undefined ? [] : Array.isArray(what) ? what : [what];\n\tfor (const item of list) {\n\t\tif (!(item instanceof Secret)) {\n\t\t\tthrow new AgentNavaError({\n\t\t\t\tmessage: `attach takes a Secret. ${ACCOUNTS_MOVED}`,\n\t\t\t\tcode: 'not_a_secret',\n\t\t\t\tstatus: 400,\n\t\t\t});\n\t\t}\n\t}\n\treturn list;\n}\n\n/**\n * Turn stored secrets into the `{ DECLARED_NAME: secretId }` map the wire\n * speaks.\n *\n * THE POINT OF SENDING AN ID RATHER THAN A VALUE. A secret stored against one\n * of your end users has no value you hold: the platform encrypted it when you\n * created it and never hands it back. Sending the id lets the launch resolve it\n * server-side, so attaching a credential does not require your process to have\n * read it.\n *\n * The NAME comes from the secret, because that is the name the agent declared\n * and the only thing it will look under. A handle you created carries it; one\n * you addressed by id has to read it, and that read is the only request here.\n */\nexport async function secretIdsOf(\n\twhat: Secret | Secret[] | undefined,\n): Promise<Record<string, string> | undefined> {\n\tif (!what) return undefined;\n\tconst list = Array.isArray(what) ? what : [what];\n\tif (list.length === 0) return undefined;\n\tconst out: Record<string, string> = {};\n\tfor (const secret of list) {\n\t\tconst name = secret.name ?? (await secret.get()).name;\n\t\t// Two different secrets under one name in a single call is a caller\n\t\t// mistake, and last-one-wins would surface much later as a tool failing\n\t\t// on a credential that looks present.\n\t\tif (out[name] && out[name] !== secret.id) {\n\t\t\tthrow new Error(\n\t\t\t\t`two different secrets were attached as ${name}: ${out[name]} and ${secret.id}`,\n\t\t\t);\n\t\t}\n\t\tout[name] = secret.id;\n\t}\n\treturn out;\n}\n"]}
|