@lambforge/agents 0.0.0-stage → 0.0.3
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 +91 -2
- package/dist/client.d.ts +103 -0
- package/dist/client.js +303 -0
- package/dist/client.js.map +1 -0
- package/dist/documents.d.ts +19 -0
- package/dist/documents.js +30 -0
- package/dist/documents.js.map +1 -0
- package/dist/errors.d.ts +16 -0
- package/dist/errors.js +42 -0
- package/dist/errors.js.map +1 -0
- package/dist/http.d.ts +24 -0
- package/dist/http.js +60 -0
- package/dist/http.js.map +1 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +31 -0
- package/dist/index.js.map +1 -0
- package/dist/lambforge.d.ts +38 -0
- package/dist/lambforge.js +46 -0
- package/dist/lambforge.js.map +1 -0
- package/dist/node.d.ts +33 -0
- package/dist/node.js +110 -0
- package/dist/node.js.map +1 -0
- package/dist/types.d.ts +128 -0
- package/dist/types.js +3 -0
- package/dist/types.js.map +1 -0
- package/dist/ws.d.ts +44 -0
- package/dist/ws.js +118 -0
- package/dist/ws.js.map +1 -0
- package/package.json +45 -4
package/README.md
CHANGED
|
@@ -1,3 +1,92 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @lambforge/agents
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Put your [Lambforge](https://lambforge.com) agents on your own site or API.
|
|
4
|
+
Your server mints a short-lived session for each of your users; the browser
|
|
5
|
+
(or any Node process) chats with the agent and gets the answer as live
|
|
6
|
+
events. Every method returns an RxJS `Observable`.
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
npm install @lambforge/agents rxjs
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
## On your server: sessions (and agents)
|
|
13
|
+
|
|
14
|
+
Create a **secret** agent key (`lfk_...`) in the dashboard with the scopes you
|
|
15
|
+
need (`agents:session` to mint sessions, `agents:manage` to manage agents).
|
|
16
|
+
It never leaves your server.
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
import { Lambforge } from '@lambforge/agents';
|
|
20
|
+
|
|
21
|
+
const lf = new Lambforge({ apiKey: process.env.LAMBFORGE_KEY, projectId: '...' });
|
|
22
|
+
|
|
23
|
+
// e.g. GET /agent-token for a signed-in user
|
|
24
|
+
lf.sessions
|
|
25
|
+
.create({ subject: user.id, claims: { companyId: user.companyId } })
|
|
26
|
+
.subscribe(({ token, expiresAt }) => res.json({ token, expiresAt }));
|
|
27
|
+
|
|
28
|
+
lf.agents.list(); // create / get / update / delete / embed (publish)
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## In the browser: chat
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
import { AgentClient } from '@lambforge/agents';
|
|
35
|
+
|
|
36
|
+
const client = new AgentClient({
|
|
37
|
+
getToken: () => fetch('/agent-token').then((r) => r.json()),
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
const chat = client.agent('Support').conversation(); // a new conversation
|
|
41
|
+
chat.send('Which invoices are overdue?').subscribe((event) => {
|
|
42
|
+
if (event.type === 'message' && event.data.role === 'assistant') show(event.data.text);
|
|
43
|
+
if (event.type === 'error') showError(event.data.code); // limit-reached, cap-reached, ...
|
|
44
|
+
});
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
`send` emits that run's events (your message, `run-started`, the answer,
|
|
48
|
+
then `done` or `error`) and completes. Events arrive in order without
|
|
49
|
+
duplicates; a dropped connection reconnects and catches up. Without a
|
|
50
|
+
WebSocket (`WebSocket: false`, or Node < 22 without the `ws` package) the
|
|
51
|
+
client polls.
|
|
52
|
+
|
|
53
|
+
Other ways to get a session:
|
|
54
|
+
|
|
55
|
+
```ts
|
|
56
|
+
// the visitor's own sign-in token (an identity provider of your project)
|
|
57
|
+
new AgentClient({ exchange: { projectId, idToken: () => auth.currentUser.getIdToken() } });
|
|
58
|
+
|
|
59
|
+
// (each message then carries a fresh idToken as the credential, so agents whose
|
|
60
|
+
// MCP server receives `forward` get the user's own token; `credential: false` = never)
|
|
61
|
+
|
|
62
|
+
// anonymous visitors: a publishable key (lfp_...) + a Cloudflare Turnstile token
|
|
63
|
+
new AgentClient({ anonymous: { publishableKey: 'lfp_...', turnstileToken: () => turnstile.getResponse() } });
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
More: `client.agents()`, `client.conversations()`,
|
|
67
|
+
`client.agent(name).conversation(id).history() / .events() / .abort()`,
|
|
68
|
+
`send(text, { credential })` for `forward` agents (your user's own token
|
|
69
|
+
goes to your MCP server only, never stored).
|
|
70
|
+
|
|
71
|
+
## On your MCP server: who is asking (`signed` agents)
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
import { verifyAgentAssertion } from '@lambforge/agents/node';
|
|
75
|
+
|
|
76
|
+
verifyAgentAssertion(req.headers.authorization, {
|
|
77
|
+
projectId: '...',
|
|
78
|
+
audience: 'https://your-mcp-url', // optional
|
|
79
|
+
}).subscribe(({ subject, claims, agent }) => ...);
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
Checks the ES256 signature against
|
|
83
|
+
`https://api.lambforge.com/agents/jwks.json` (cached, refetched for a new
|
|
84
|
+
key), the issuer, the expiry, your project and the audience.
|
|
85
|
+
|
|
86
|
+
## Errors
|
|
87
|
+
|
|
88
|
+
Failures are `LambforgeError` with a `code`: `limit-reached`,
|
|
89
|
+
`cap-reached`, `agent-unavailable`, `session-expired`,
|
|
90
|
+
`credential-expired`, `aborted`, `internal`, `unauthorized`,
|
|
91
|
+
`bad-request`, `network`. A refused session is renewed once
|
|
92
|
+
automatically; a message is never resent.
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { Observable } from 'rxjs';
|
|
2
|
+
import { Endpoint, FetchLike } from './http';
|
|
3
|
+
import { AgentEvent, ConversationDetail, ConversationSummary, EmbedAgent, SessionToken } from './types';
|
|
4
|
+
import { WebSocketConstructor } from './ws';
|
|
5
|
+
/** A value now, later (Promise) or as an Observable. */
|
|
6
|
+
export type Lazy<T> = () => T | Promise<T> | Observable<T>;
|
|
7
|
+
export interface AgentClientOptions {
|
|
8
|
+
/** default https://api.lambforge.com */
|
|
9
|
+
url?: string;
|
|
10
|
+
/** Your backend mints the session (`Lambforge.sessions.create`) and returns it. */
|
|
11
|
+
getToken?: Lazy<SessionToken | string>;
|
|
12
|
+
/** The visitor's own sign-in token -> a session (an identity provider of the project). */
|
|
13
|
+
exchange?: {
|
|
14
|
+
projectId: string;
|
|
15
|
+
idToken: Lazy<string>;
|
|
16
|
+
agents?: string[];
|
|
17
|
+
};
|
|
18
|
+
/** Anonymous visitors: a publishable key (`lfp_`) + a Turnstile token. */
|
|
19
|
+
anonymous?: {
|
|
20
|
+
publishableKey: string;
|
|
21
|
+
turnstileToken: Lazy<string>;
|
|
22
|
+
/** 16-128 of A-Z a-z 0-9 _ - ; default: one per browser (localStorage) */
|
|
23
|
+
deviceId?: string;
|
|
24
|
+
agents?: string[];
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* The visitor's own token, sent with every message so an agent whose MCP
|
|
28
|
+
* server receives `forward` (or `auto`) gets it. Default with `exchange`:
|
|
29
|
+
* its `idToken` (fetched fresh per message). `false` = never send one.
|
|
30
|
+
*/
|
|
31
|
+
credential?: Lazy<string | null | undefined> | false;
|
|
32
|
+
fetch?: FetchLike;
|
|
33
|
+
/** WebSocket implementation (Node < 22: `require('ws')`); `false` = poll */
|
|
34
|
+
WebSocket?: WebSocketConstructor | false;
|
|
35
|
+
/** polling interval without a WebSocket, default 1500 ms */
|
|
36
|
+
pollIntervalMs?: number;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The visitor side, browser or Node: the agents of a session, their
|
|
40
|
+
* conversations and live events. Holds the session token and renews it
|
|
41
|
+
* shortly before it expires (or once when the server says it expired).
|
|
42
|
+
* Never give it a secret key - mint sessions on your server.
|
|
43
|
+
*/
|
|
44
|
+
export declare class AgentClient {
|
|
45
|
+
private readonly options;
|
|
46
|
+
readonly endpoint: Endpoint;
|
|
47
|
+
private current;
|
|
48
|
+
private pending$;
|
|
49
|
+
constructor(options: AgentClientOptions);
|
|
50
|
+
/** The current session token (renewed when needed). */
|
|
51
|
+
token$(): Observable<string>;
|
|
52
|
+
/** Forget the session (the next call gets a new one). */
|
|
53
|
+
invalidate(): void;
|
|
54
|
+
/** The credential for one message (see `credential`); undefined = none. */
|
|
55
|
+
credential$(): Observable<string | undefined>;
|
|
56
|
+
private session$;
|
|
57
|
+
/** One operation with the session; a refused session is renewed once. */
|
|
58
|
+
call$<T>(query: string, variables: Record<string, unknown>, field: string): Observable<T>;
|
|
59
|
+
/** The agents this session may use. */
|
|
60
|
+
agents(): Observable<EmbedAgent[]>;
|
|
61
|
+
/** The visitor's conversations (newest first), optionally of one agent. */
|
|
62
|
+
conversations(agent?: string): Observable<ConversationSummary[]>;
|
|
63
|
+
/** A chat with one agent (id or name); `conversationId` continues one. */
|
|
64
|
+
agent(agent: string): {
|
|
65
|
+
conversation: (conversationId?: string) => AgentConversation;
|
|
66
|
+
conversations: () => Observable<ConversationSummary[]>;
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* Every event of a conversation after `afterSeq`, in order, without
|
|
70
|
+
* duplicates and without gaps: live over the WebSocket (reconnecting with
|
|
71
|
+
* backoff, catching up after each start) or polled without one. Never
|
|
72
|
+
* completes by itself.
|
|
73
|
+
*/
|
|
74
|
+
events(conversationId: string, afterSeq?: number): Observable<AgentEvent>;
|
|
75
|
+
private webSocket;
|
|
76
|
+
}
|
|
77
|
+
/** One conversation with one agent. */
|
|
78
|
+
export declare class AgentConversation {
|
|
79
|
+
private readonly client;
|
|
80
|
+
readonly agent: string;
|
|
81
|
+
/** null until the first message creates it */
|
|
82
|
+
id: string | null;
|
|
83
|
+
constructor(client: AgentClient, agent: string,
|
|
84
|
+
/** null until the first message creates it */
|
|
85
|
+
id: string | null);
|
|
86
|
+
/**
|
|
87
|
+
* Send a message; emits the events of THAT run - the stored visitor
|
|
88
|
+
* message, `run-started`, the answer, then `done` or `error` - and
|
|
89
|
+
* completes. A failed send (limits, caps, an unavailable agent) errors
|
|
90
|
+
* instead. Nothing is resent automatically.
|
|
91
|
+
*/
|
|
92
|
+
send(text: string, options?: {
|
|
93
|
+
credential?: string;
|
|
94
|
+
}): Observable<AgentEvent>;
|
|
95
|
+
/** Live events from now on (or after `afterSeq`). */
|
|
96
|
+
events(afterSeq?: number): Observable<AgentEvent>;
|
|
97
|
+
/** The stored messages (and `lastSeq` / `answering` to resume). */
|
|
98
|
+
history(): Observable<ConversationDetail>;
|
|
99
|
+
/** Stop the answer in progress. */
|
|
100
|
+
abort(): Observable<boolean>;
|
|
101
|
+
}
|
|
102
|
+
/** One id per browser (localStorage), else a fresh one per client. */
|
|
103
|
+
export declare function deviceId(): string;
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.AgentConversation = exports.AgentClient = void 0;
|
|
4
|
+
exports.deviceId = deviceId;
|
|
5
|
+
const rxjs_1 = require("rxjs");
|
|
6
|
+
const operators_1 = require("rxjs/operators");
|
|
7
|
+
const documents_1 = require("./documents");
|
|
8
|
+
const errors_1 = require("./errors");
|
|
9
|
+
const http_1 = require("./http");
|
|
10
|
+
const ws_1 = require("./ws");
|
|
11
|
+
const lazy$ = (source) => (0, rxjs_1.defer)(() => {
|
|
12
|
+
const value = source();
|
|
13
|
+
return (0, rxjs_1.isObservable)(value) ? value.pipe((0, operators_1.take)(1)) : (0, rxjs_1.from)(Promise.resolve(value));
|
|
14
|
+
});
|
|
15
|
+
/** Renew this long before the session expires. */
|
|
16
|
+
const RENEW_BEFORE_MS = 60_000;
|
|
17
|
+
const DEVICE_KEY = 'lambforge.agents.device';
|
|
18
|
+
const RECONNECT_MAX_MS = 15_000;
|
|
19
|
+
/**
|
|
20
|
+
* The visitor side, browser or Node: the agents of a session, their
|
|
21
|
+
* conversations and live events. Holds the session token and renews it
|
|
22
|
+
* shortly before it expires (or once when the server says it expired).
|
|
23
|
+
* Never give it a secret key - mint sessions on your server.
|
|
24
|
+
*/
|
|
25
|
+
class AgentClient {
|
|
26
|
+
options;
|
|
27
|
+
endpoint;
|
|
28
|
+
current = null;
|
|
29
|
+
pending$ = null;
|
|
30
|
+
constructor(options) {
|
|
31
|
+
this.options = options;
|
|
32
|
+
const sources = [options.getToken, options.exchange, options.anonymous].filter(Boolean).length;
|
|
33
|
+
if (sources !== 1) {
|
|
34
|
+
throw new errors_1.LambforgeError('AgentClient: give exactly one of getToken, exchange or anonymous', 'bad-request');
|
|
35
|
+
}
|
|
36
|
+
if (options.anonymous && !options.anonymous.publishableKey.startsWith('lfp_')) {
|
|
37
|
+
throw new errors_1.LambforgeError('AgentClient: anonymous visitors need a publishable key (lfp_...)', 'bad-request');
|
|
38
|
+
}
|
|
39
|
+
this.endpoint = { url: options.url ?? http_1.DEFAULT_URL, fetch: options.fetch };
|
|
40
|
+
}
|
|
41
|
+
// ------------------------------------------------------------- session
|
|
42
|
+
/** The current session token (renewed when needed). */
|
|
43
|
+
token$() {
|
|
44
|
+
if (this.current && Date.now() < this.current.renewAt) {
|
|
45
|
+
return (0, rxjs_1.of)(this.current.token);
|
|
46
|
+
}
|
|
47
|
+
if (!this.pending$) {
|
|
48
|
+
this.pending$ = this.session$().pipe((0, operators_1.tap)((s) => {
|
|
49
|
+
const expires = s.expiresAt ? Date.parse(s.expiresAt) : NaN;
|
|
50
|
+
this.current = {
|
|
51
|
+
token: s.token,
|
|
52
|
+
renewAt: Number.isFinite(expires)
|
|
53
|
+
? Math.max(Date.now() + 30_000, expires - RENEW_BEFORE_MS)
|
|
54
|
+
: Date.now() + 50 * 60_000,
|
|
55
|
+
};
|
|
56
|
+
}), (0, operators_1.map)((s) => s.token), (0, operators_1.finalize)(() => (this.pending$ = null)), (0, operators_1.shareReplay)(1));
|
|
57
|
+
}
|
|
58
|
+
return this.pending$;
|
|
59
|
+
}
|
|
60
|
+
/** Forget the session (the next call gets a new one). */
|
|
61
|
+
invalidate() {
|
|
62
|
+
this.current = null;
|
|
63
|
+
}
|
|
64
|
+
/** The credential for one message (see `credential`); undefined = none. */
|
|
65
|
+
credential$() {
|
|
66
|
+
const o = this.options;
|
|
67
|
+
const source = o.credential === false
|
|
68
|
+
? null
|
|
69
|
+
: o.credential ?? (o.exchange ? o.exchange.idToken : null);
|
|
70
|
+
if (!source)
|
|
71
|
+
return (0, rxjs_1.of)(undefined);
|
|
72
|
+
return lazy$(source).pipe((0, operators_1.map)((t) => t || undefined));
|
|
73
|
+
}
|
|
74
|
+
session$() {
|
|
75
|
+
const o = this.options;
|
|
76
|
+
if (o.getToken) {
|
|
77
|
+
return lazy$(o.getToken).pipe((0, operators_1.map)((t) => (typeof t === 'string' ? { token: t } : t)));
|
|
78
|
+
}
|
|
79
|
+
if (o.exchange) {
|
|
80
|
+
const { projectId, idToken, agents } = o.exchange;
|
|
81
|
+
return lazy$(idToken).pipe((0, operators_1.switchMap)((token) => (0, http_1.request$)(this.endpoint, null, documents_1.DOCS.exchangeSession, { projectId, token, agents }, 'exchangeAgentSession')));
|
|
82
|
+
}
|
|
83
|
+
const a = o.anonymous;
|
|
84
|
+
return lazy$(a.turnstileToken).pipe((0, operators_1.switchMap)((turnstileToken) => (0, http_1.request$)(this.endpoint, a.publishableKey, documents_1.DOCS.anonymousSession, {
|
|
85
|
+
deviceId: a.deviceId ?? deviceId(),
|
|
86
|
+
turnstileToken,
|
|
87
|
+
agents: a.agents,
|
|
88
|
+
}, 'createAnonymousAgentSession')));
|
|
89
|
+
}
|
|
90
|
+
/** One operation with the session; a refused session is renewed once. */
|
|
91
|
+
call$(query, variables, field) {
|
|
92
|
+
const once = () => this.token$().pipe((0, operators_1.switchMap)((token) => (0, http_1.request$)(this.endpoint, token, query, variables, field)));
|
|
93
|
+
return once().pipe((0, operators_1.catchError)((e) => {
|
|
94
|
+
if (e?.code !== 'session-expired' && e?.code !== 'unauthorized') {
|
|
95
|
+
return (0, rxjs_1.throwError)(() => e);
|
|
96
|
+
}
|
|
97
|
+
this.invalidate();
|
|
98
|
+
return once();
|
|
99
|
+
}));
|
|
100
|
+
}
|
|
101
|
+
// -------------------------------------------------------------- reading
|
|
102
|
+
/** The agents this session may use. */
|
|
103
|
+
agents() {
|
|
104
|
+
return this.call$(documents_1.DOCS.sessionAgents, {}, 'sessionAgents');
|
|
105
|
+
}
|
|
106
|
+
/** The visitor's conversations (newest first), optionally of one agent. */
|
|
107
|
+
conversations(agent) {
|
|
108
|
+
return this.call$(documents_1.DOCS.conversations, { agent }, 'agentConversations');
|
|
109
|
+
}
|
|
110
|
+
/** A chat with one agent (id or name); `conversationId` continues one. */
|
|
111
|
+
agent(agent) {
|
|
112
|
+
return {
|
|
113
|
+
conversation: (conversationId) => new AgentConversation(this, agent, conversationId ?? null),
|
|
114
|
+
conversations: () => this.conversations(agent),
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
// --------------------------------------------------------------- events
|
|
118
|
+
/**
|
|
119
|
+
* Every event of a conversation after `afterSeq`, in order, without
|
|
120
|
+
* duplicates and without gaps: live over the WebSocket (reconnecting with
|
|
121
|
+
* backoff, catching up after each start) or polled without one. Never
|
|
122
|
+
* completes by itself.
|
|
123
|
+
*/
|
|
124
|
+
events(conversationId, afterSeq = 0) {
|
|
125
|
+
return new rxjs_1.Observable((subscriber) => {
|
|
126
|
+
let last = afterSeq;
|
|
127
|
+
const held = new Map();
|
|
128
|
+
const subs = new rxjs_1.Subscription();
|
|
129
|
+
let catching = false;
|
|
130
|
+
let again = false;
|
|
131
|
+
const flush = () => {
|
|
132
|
+
while (held.has(last + 1)) {
|
|
133
|
+
const e = held.get(last + 1);
|
|
134
|
+
held.delete(last + 1);
|
|
135
|
+
last = e.seq;
|
|
136
|
+
subscriber.next(e);
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
const accept = (e) => {
|
|
140
|
+
if (!e || e.seq <= last)
|
|
141
|
+
return;
|
|
142
|
+
held.set(e.seq, e);
|
|
143
|
+
flush();
|
|
144
|
+
if (held.size)
|
|
145
|
+
catchUp(); // a gap: ask the server what is missing
|
|
146
|
+
};
|
|
147
|
+
const catchUp = () => {
|
|
148
|
+
if (catching) {
|
|
149
|
+
again = true;
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
catching = true;
|
|
153
|
+
subs.add(this.call$(documents_1.DOCS.events, { conversationId, afterSeq: last }, 'agentConversationEvents').subscribe({
|
|
154
|
+
next: (list) => {
|
|
155
|
+
list.forEach((e) => held.set(e.seq, e));
|
|
156
|
+
flush();
|
|
157
|
+
// the server has nothing in between: deliver what is held
|
|
158
|
+
if (held.size && !list.length) {
|
|
159
|
+
last = Math.min(...held.keys()) - 1;
|
|
160
|
+
flush();
|
|
161
|
+
}
|
|
162
|
+
},
|
|
163
|
+
error: (e) => {
|
|
164
|
+
catching = false;
|
|
165
|
+
subscriber.error(e);
|
|
166
|
+
},
|
|
167
|
+
complete: () => {
|
|
168
|
+
catching = false;
|
|
169
|
+
if (again) {
|
|
170
|
+
again = false;
|
|
171
|
+
catchUp();
|
|
172
|
+
}
|
|
173
|
+
},
|
|
174
|
+
}));
|
|
175
|
+
};
|
|
176
|
+
const WS = this.webSocket();
|
|
177
|
+
if (!WS) {
|
|
178
|
+
catchUp();
|
|
179
|
+
subs.add((0, rxjs_1.timer)(this.options.pollIntervalMs ?? 1500, this.options.pollIntervalMs ?? 1500).subscribe(() => catchUp()));
|
|
180
|
+
return subs;
|
|
181
|
+
}
|
|
182
|
+
let attempt = 0;
|
|
183
|
+
let renewed = false;
|
|
184
|
+
const connect = () => {
|
|
185
|
+
subs.add(this.token$()
|
|
186
|
+
.pipe((0, operators_1.switchMap)((token) => (0, ws_1.subscription$)({
|
|
187
|
+
url: (0, http_1.subscriptionsUrl)(this.endpoint.url),
|
|
188
|
+
WebSocket: WS,
|
|
189
|
+
connectionParams: { agentSession: token },
|
|
190
|
+
query: documents_1.DOCS.liveEvents,
|
|
191
|
+
variables: { conversationId },
|
|
192
|
+
field: 'agentEvents',
|
|
193
|
+
onStarted: () => {
|
|
194
|
+
attempt = 0;
|
|
195
|
+
renewed = false;
|
|
196
|
+
catchUp();
|
|
197
|
+
},
|
|
198
|
+
})))
|
|
199
|
+
.subscribe({
|
|
200
|
+
next: accept,
|
|
201
|
+
error: (e) => {
|
|
202
|
+
if (e?.code === 'unauthorized' && !renewed) {
|
|
203
|
+
renewed = true;
|
|
204
|
+
this.invalidate();
|
|
205
|
+
connect();
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
if (e?.code !== 'network') {
|
|
209
|
+
subscriber.error(e);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
const wait = Math.min(RECONNECT_MAX_MS, 1000 * 2 ** attempt++);
|
|
213
|
+
subs.add((0, rxjs_1.timer)(wait * (0.75 + Math.random() / 2)).subscribe(connect));
|
|
214
|
+
},
|
|
215
|
+
complete: () => subscriber.complete(),
|
|
216
|
+
}));
|
|
217
|
+
};
|
|
218
|
+
connect();
|
|
219
|
+
return subs;
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
webSocket() {
|
|
223
|
+
if (this.options.WebSocket === false)
|
|
224
|
+
return null;
|
|
225
|
+
return (this.options.WebSocket ??
|
|
226
|
+
(globalThis.WebSocket || null));
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
exports.AgentClient = AgentClient;
|
|
230
|
+
/** One conversation with one agent. */
|
|
231
|
+
class AgentConversation {
|
|
232
|
+
client;
|
|
233
|
+
agent;
|
|
234
|
+
id;
|
|
235
|
+
constructor(client, agent,
|
|
236
|
+
/** null until the first message creates it */
|
|
237
|
+
id) {
|
|
238
|
+
this.client = client;
|
|
239
|
+
this.agent = agent;
|
|
240
|
+
this.id = id;
|
|
241
|
+
}
|
|
242
|
+
/**
|
|
243
|
+
* Send a message; emits the events of THAT run - the stored visitor
|
|
244
|
+
* message, `run-started`, the answer, then `done` or `error` - and
|
|
245
|
+
* completes. A failed send (limits, caps, an unavailable agent) errors
|
|
246
|
+
* instead. Nothing is resent automatically.
|
|
247
|
+
*/
|
|
248
|
+
send(text, options = {}) {
|
|
249
|
+
const credential$ = options.credential !== undefined
|
|
250
|
+
? (0, rxjs_1.of)(options.credential)
|
|
251
|
+
: this.client.credential$();
|
|
252
|
+
return credential$
|
|
253
|
+
.pipe((0, operators_1.switchMap)((credential) => this.client.call$(documents_1.DOCS.send, { agent: this.agent, conversationId: this.id, text, credential }, 'sendAgentMessage')))
|
|
254
|
+
.pipe((0, operators_1.tap)((sent) => (this.id = sent.conversationId)), (0, operators_1.switchMap)((sent) =>
|
|
255
|
+
// seq = run-started; seq - 1 = the visitor's message
|
|
256
|
+
this.client.events(sent.conversationId, Math.max(0, sent.seq - 2)).pipe((0, operators_1.takeWhile)((e) => !((e.type === 'done' || e.type === 'error') &&
|
|
257
|
+
e.runId === sent.runId), true))));
|
|
258
|
+
}
|
|
259
|
+
/** Live events from now on (or after `afterSeq`). */
|
|
260
|
+
events(afterSeq) {
|
|
261
|
+
if (!this.id) {
|
|
262
|
+
return (0, rxjs_1.throwError)(() => new errors_1.LambforgeError('No conversation yet - send a message first', 'bad-request'));
|
|
263
|
+
}
|
|
264
|
+
return afterSeq === undefined
|
|
265
|
+
? this.history().pipe((0, operators_1.switchMap)((c) => this.client.events(this.id, c.lastSeq ?? 0)))
|
|
266
|
+
: this.client.events(this.id, afterSeq);
|
|
267
|
+
}
|
|
268
|
+
/** The stored messages (and `lastSeq` / `answering` to resume). */
|
|
269
|
+
history() {
|
|
270
|
+
if (!this.id) {
|
|
271
|
+
return (0, rxjs_1.throwError)(() => new errors_1.LambforgeError('No conversation yet - send a message first', 'bad-request'));
|
|
272
|
+
}
|
|
273
|
+
return this.client.call$(documents_1.DOCS.conversation, { id: this.id }, 'agentConversation');
|
|
274
|
+
}
|
|
275
|
+
/** Stop the answer in progress. */
|
|
276
|
+
abort() {
|
|
277
|
+
if (!this.id)
|
|
278
|
+
return (0, rxjs_1.of)(false);
|
|
279
|
+
return this.client.call$(documents_1.DOCS.abort, { conversationId: this.id }, 'abortAgentRun');
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
exports.AgentConversation = AgentConversation;
|
|
283
|
+
/** One id per browser (localStorage), else a fresh one per client. */
|
|
284
|
+
function deviceId() {
|
|
285
|
+
const storage = globalThis.localStorage;
|
|
286
|
+
try {
|
|
287
|
+
const stored = storage?.getItem(DEVICE_KEY);
|
|
288
|
+
if (stored && /^[A-Za-z0-9_-]{16,128}$/.test(stored))
|
|
289
|
+
return stored;
|
|
290
|
+
}
|
|
291
|
+
catch {
|
|
292
|
+
/* storage blocked */
|
|
293
|
+
}
|
|
294
|
+
const id = globalThis.crypto.randomUUID().replace(/-/g, '');
|
|
295
|
+
try {
|
|
296
|
+
storage?.setItem(DEVICE_KEY, id);
|
|
297
|
+
}
|
|
298
|
+
catch {
|
|
299
|
+
/* storage blocked */
|
|
300
|
+
}
|
|
301
|
+
return id;
|
|
302
|
+
}
|
|
303
|
+
//# sourceMappingURL=client.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":";;;AA8cA,4BAeC;AA7dD,+BASc;AACd,8CASwB;AAExB,2CAAmC;AACnC,qCAA0C;AAC1C,iCAMgB;AAShB,6BAA2D;AAK3D,MAAM,KAAK,GAAG,CAAI,MAAe,EAAiB,EAAE,CAClD,IAAA,YAAK,EAAC,GAAG,EAAE;IACT,MAAM,KAAK,GAAG,MAAM,EAAE,CAAC;IACvB,OAAO,IAAA,mBAAY,EAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,IAAA,gBAAI,EAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAA,WAAI,EAAC,OAAO,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;AAClF,CA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AAU,EAAE,EAAE,CAAC,CAAC;IACnC,CAAC;IAAC,MAAM,CAAC;QACP,qBAAqB;IACvB,CAAC;IACD,OAAO,EAAE,CAAC;AACZ,CAAC"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** The GraphQL operations this package sends (one place to keep in sync). */
|
|
2
|
+
export declare const DOCS: {
|
|
3
|
+
listAgents: string;
|
|
4
|
+
getAgent: string;
|
|
5
|
+
createAgent: string;
|
|
6
|
+
updateAgent: string;
|
|
7
|
+
deleteAgent: string;
|
|
8
|
+
updateEmbed: string;
|
|
9
|
+
createSession: string;
|
|
10
|
+
exchangeSession: string;
|
|
11
|
+
anonymousSession: string;
|
|
12
|
+
sessionAgents: string;
|
|
13
|
+
conversations: string;
|
|
14
|
+
conversation: string;
|
|
15
|
+
events: string;
|
|
16
|
+
send: string;
|
|
17
|
+
abort: string;
|
|
18
|
+
liveEvents: string;
|
|
19
|
+
};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/** The GraphQL operations this package sends (one place to keep in sync). */
|
|
3
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
4
|
+
exports.DOCS = void 0;
|
|
5
|
+
const AGENT = `id name type description instructions tools isActive modelName mcpLambdaId mcpLambdaName createdAt updatedAt
|
|
6
|
+
embed { published identity allowedOrigins welcome suggestions showToolDetails maxMessagesPerConversation retentionDays publishedAt }`;
|
|
7
|
+
const EMBED_AGENT = 'id name description welcome suggestions';
|
|
8
|
+
const SESSION = `token expiresAt agents { ${EMBED_AGENT} }`;
|
|
9
|
+
const SUMMARY = 'id agentId title messageCount lastSeq answering lastMessageAt createdAt';
|
|
10
|
+
const MESSAGE = 'id role text toolCalls { name status } createdAt';
|
|
11
|
+
const EVENT = 'conversationId seq type runId data createdAt';
|
|
12
|
+
exports.DOCS = {
|
|
13
|
+
listAgents: `query ($projectId: String!) { listProjectAgents(projectId: $projectId) { ${AGENT} } }`,
|
|
14
|
+
getAgent: `query ($id: String!) { getProjectAgent(id: $id) { ${AGENT} } }`,
|
|
15
|
+
createAgent: `mutation ($projectId: String!, $payload: CreateProjectAgentInput!) { createProjectAgent(projectId: $projectId, payload: $payload) { ${AGENT} } }`,
|
|
16
|
+
updateAgent: `mutation ($id: String!, $payload: UpdateProjectAgentInput!) { updateProjectAgent(id: $id, payload: $payload) { ${AGENT} } }`,
|
|
17
|
+
deleteAgent: `mutation ($id: String!) { deleteProjectAgent(id: $id) }`,
|
|
18
|
+
updateEmbed: `mutation ($agentId: String!, $embed: AgentEmbedInput!) { updateAgentEmbed(agentId: $agentId, embed: $embed) { ${AGENT} } }`,
|
|
19
|
+
createSession: `mutation ($subject: String!, $agents: [String], $claims: JSON, $ttlSeconds: Int, $origin: String) { createAgentSession(subject: $subject, agents: $agents, claims: $claims, ttlSeconds: $ttlSeconds, origin: $origin) { ${SESSION} } }`,
|
|
20
|
+
exchangeSession: `mutation ($projectId: String!, $token: String!, $agents: [String]) { exchangeAgentSession(projectId: $projectId, token: $token, agents: $agents) { ${SESSION} } }`,
|
|
21
|
+
anonymousSession: `mutation ($deviceId: String!, $turnstileToken: String!, $agents: [String]) { createAnonymousAgentSession(deviceId: $deviceId, turnstileToken: $turnstileToken, agents: $agents) { ${SESSION} } }`,
|
|
22
|
+
sessionAgents: `query { sessionAgents { ${EMBED_AGENT} } }`,
|
|
23
|
+
conversations: `query ($agent: String) { agentConversations(agent: $agent) { ${SUMMARY} } }`,
|
|
24
|
+
conversation: `query ($id: String!) { agentConversation(id: $id) { ${SUMMARY} messages { ${MESSAGE} } } }`,
|
|
25
|
+
events: `query ($conversationId: String!, $afterSeq: Int) { agentConversationEvents(conversationId: $conversationId, afterSeq: $afterSeq) { ${EVENT} } }`,
|
|
26
|
+
send: `mutation ($agent: String!, $conversationId: String, $text: String!, $credential: String) { sendAgentMessage(agent: $agent, conversationId: $conversationId, text: $text, credential: $credential) { conversationId runId seq } }`,
|
|
27
|
+
abort: `mutation ($conversationId: String!) { abortAgentRun(conversationId: $conversationId) }`,
|
|
28
|
+
liveEvents: `subscription ($conversationId: String!) { agentEvents(conversationId: $conversationId) { ${EVENT} } }`,
|
|
29
|
+
};
|
|
30
|
+
//# sourceMappingURL=documents.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"documents.js","sourceRoot":"","sources":["../src/documents.ts"],"names":[],"mappings":";AAAA,6EAA6E;;;AAE7E,MAAM,KAAK,GAAG;uIACyH,CAAC;AACxI,MAAM,WAAW,GAAG,yCAAyC,CAAC;AAC9D,MAAM,OAAO,GAAG,4BAA4B,WAAW,IAAI,CAAC;AAC5D,MAAM,OAAO,GACX,yEAAyE,CAAC;AAC5E,MAAM,OAAO,GAAG,kDAAkD,CAAC;AACnE,MAAM,KAAK,GAAG,8CAA8C,CAAC;AAEhD,QAAA,IAAI,GAAG;IAClB,UAAU,EAAE,4EAA4E,KAAK,MAAM;IACnG,QAAQ,EAAE,qDAAqD,KAAK,MAAM;IAC1E,WAAW,EAAE,uIAAuI,KAAK,MAAM;IAC/J,WAAW,EAAE,kHAAkH,KAAK,MAAM;IAC1I,WAAW,EAAE,yDAAyD;IACtE,WAAW,EAAE,iHAAiH,KAAK,MAAM;IACzI,aAAa,EAAE,2NAA2N,OAAO,MAAM;IACvP,eAAe,EAAE,sJAAsJ,OAAO,MAAM;IACpL,gBAAgB,EAAE,qLAAqL,OAAO,MAAM;IACpN,aAAa,EAAE,2BAA2B,WAAW,MAAM;IAC3D,aAAa,EAAE,gEAAgE,OAAO,MAAM;IAC5F,YAAY,EAAE,uDAAuD,OAAO,eAAe,OAAO,QAAQ;IAC1G,MAAM,EAAE,sIAAsI,KAAK,MAAM;IACzJ,IAAI,EAAE,kOAAkO;IACxO,KAAK,EAAE,wFAAwF;IAC/F,UAAU,EAAE,4FAA4F,KAAK,MAAM;CACpH,CAAC"}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** Why a call or a run was refused - stable codes a UI can switch on. */
|
|
2
|
+
export type AgentErrorCode = 'limit-reached' | 'cap-reached' | 'agent-unavailable' | 'session-expired' | 'credential-expired' | 'aborted' | 'internal' | 'unauthorized' | 'bad-request' | 'network';
|
|
3
|
+
export declare class LambforgeError extends Error {
|
|
4
|
+
readonly code: AgentErrorCode;
|
|
5
|
+
readonly status?: number | undefined;
|
|
6
|
+
constructor(message: string, code: AgentErrorCode, status?: number | undefined);
|
|
7
|
+
}
|
|
8
|
+
interface GraphQLErrorLike {
|
|
9
|
+
message?: string;
|
|
10
|
+
extensions?: {
|
|
11
|
+
code?: string;
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
/** The first GraphQL error as a LambforgeError with a usable code. */
|
|
15
|
+
export declare function errorFromGraphQL(errors: GraphQLErrorLike[], status?: number): LambforgeError;
|
|
16
|
+
export {};
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.LambforgeError = void 0;
|
|
4
|
+
exports.errorFromGraphQL = errorFromGraphQL;
|
|
5
|
+
const SERVER_CODES = [
|
|
6
|
+
'limit-reached',
|
|
7
|
+
'cap-reached',
|
|
8
|
+
'agent-unavailable',
|
|
9
|
+
'session-expired',
|
|
10
|
+
'credential-expired',
|
|
11
|
+
'aborted',
|
|
12
|
+
'internal',
|
|
13
|
+
];
|
|
14
|
+
class LambforgeError extends Error {
|
|
15
|
+
code;
|
|
16
|
+
status;
|
|
17
|
+
constructor(message, code, status) {
|
|
18
|
+
super(message);
|
|
19
|
+
this.code = code;
|
|
20
|
+
this.status = status;
|
|
21
|
+
this.name = 'LambforgeError';
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
exports.LambforgeError = LambforgeError;
|
|
25
|
+
/** The first GraphQL error as a LambforgeError with a usable code. */
|
|
26
|
+
function errorFromGraphQL(errors, status) {
|
|
27
|
+
const first = errors?.[0] ?? {};
|
|
28
|
+
const message = String(first.message ?? 'Request failed');
|
|
29
|
+
const prefix = message.match(/^([a-z-]+):/)?.[1];
|
|
30
|
+
if (prefix && SERVER_CODES.includes(prefix)) {
|
|
31
|
+
return new LambforgeError(message, prefix, status);
|
|
32
|
+
}
|
|
33
|
+
if (message === 'session-expired') {
|
|
34
|
+
return new LambforgeError(message, 'session-expired', status);
|
|
35
|
+
}
|
|
36
|
+
if (first.extensions?.code === 'UNAUTHENTICATED' ||
|
|
37
|
+
/not authorized|unauthorized|invalid sign-in token/i.test(message)) {
|
|
38
|
+
return new LambforgeError(message, 'unauthorized', status);
|
|
39
|
+
}
|
|
40
|
+
return new LambforgeError(message, 'bad-request', status);
|
|
41
|
+
}
|
|
42
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":";;;AAwCA,4CAoBC;AA/CD,MAAM,YAAY,GAAqB;IACrC,eAAe;IACf,aAAa;IACb,mBAAmB;IACnB,iBAAiB;IACjB,oBAAoB;IACpB,SAAS;IACT,UAAU;CACX,CAAC;AAEF,MAAa,cAAe,SAAQ,KAAK;IAG5B;IACA;IAHX,YACE,OAAe,EACN,IAAoB,EACpB,MAAe;QAExB,KAAK,CAAC,OAAO,CAAC,CAAC;QAHN,SAAI,GAAJ,IAAI,CAAgB;QACpB,WAAM,GAAN,MAAM,CAAS;QAGxB,IAAI,CAAC,IAAI,GAAG,gBAAgB,CAAC;IAC/B,CAAC;CACF;AATD,wCASC;AAOD,sEAAsE;AACtE,SAAgB,gBAAgB,CAC9B,MAA0B,EAC1B,MAAe;IAEf,MAAM,KAAK,GAAG,MAAM,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;IAChC,MAAM,OAAO,GAAG,MAAM,CAAC,KAAK,CAAC,OAAO,IAAI,gBAAgB,CAAC,CAAC;IAC1D,MAAM,MAAM,GAAG,OAAO,CAAC,KAAK,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