@raisindb/client 0.5.9 → 0.5.10
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 +32 -0
- package/dist/{chunk-IFV4ECHC.mjs → chunk-ASOWGNQZ.mjs} +3 -3
- package/dist/{chunk-ZUUSBLVP.mjs → chunk-FYWYSNQG.mjs} +3 -3
- package/dist/{chunk-765DLJMZ.mjs → chunk-NOPZAMIV.mjs} +31 -2
- package/dist/chunk-NOPZAMIV.mjs.map +1 -0
- package/dist/{chunk-AULHRX5C.mjs → chunk-TPZNJNZR.mjs} +2 -2
- package/dist/{chunk-VMUT6PIO.mjs → chunk-ZCRYQCXS.mjs} +2 -2
- package/dist/{conversation-list-store-CHaqGtSi.d.mts → conversation-list-store-CqgIk8Rn.d.mts} +179 -3
- package/dist/{conversation-list-store-CHaqGtSi.d.ts → conversation-list-store-CqgIk8Rn.d.ts} +179 -3
- package/dist/{index-AobOnS4A.d.mts → index-BD3rutlF.d.mts} +1 -1
- package/dist/{index-DiL2gplR.d.ts → index-CDUAMIub.d.ts} +1 -1
- package/dist/index.d.mts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js +383 -6
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +356 -10
- package/dist/index.mjs.map +1 -1
- package/dist/react.d.mts +2 -2
- package/dist/react.d.ts +2 -2
- package/dist/react.js +30 -1
- package/dist/react.js.map +1 -1
- package/dist/react.mjs +3 -3
- package/dist/{svelte-sql-FQqis53r.d.ts → svelte-sql-D9YU1wYS.d.ts} +1 -1
- package/dist/{svelte-sql-BUrNcoHR.d.mts → svelte-sql-l1wmTWM4.d.mts} +1 -1
- package/dist/svelte.d.mts +2 -2
- package/dist/svelte.d.ts +2 -2
- package/dist/svelte.js +30 -1
- package/dist/svelte.js.map +1 -1
- package/dist/svelte.mjs +3 -3
- package/dist/vue.d.mts +2 -2
- package/dist/vue.d.ts +2 -2
- package/dist/vue.js +30 -1
- package/dist/vue.js.map +1 -1
- package/dist/vue.mjs +2 -2
- package/package.json +1 -1
- package/dist/chunk-765DLJMZ.mjs.map +0 -1
- /package/dist/{chunk-IFV4ECHC.mjs.map → chunk-ASOWGNQZ.mjs.map} +0 -0
- /package/dist/{chunk-ZUUSBLVP.mjs.map → chunk-FYWYSNQG.mjs.map} +0 -0
- /package/dist/{chunk-AULHRX5C.mjs.map → chunk-TPZNJNZR.mjs.map} +0 -0
- /package/dist/{chunk-VMUT6PIO.mjs.map → chunk-ZCRYQCXS.mjs.map} +0 -0
package/dist/index.mjs
CHANGED
|
@@ -3,13 +3,13 @@ import {
|
|
|
3
3
|
useConversation,
|
|
4
4
|
useConversationList,
|
|
5
5
|
useFlow
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-ASOWGNQZ.mjs";
|
|
7
7
|
import {
|
|
8
8
|
RAISIN_CONTEXT_KEY,
|
|
9
9
|
createConversationAdapter,
|
|
10
10
|
createConversationListAdapter,
|
|
11
11
|
createFlowAdapter
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-FYWYSNQG.mjs";
|
|
13
13
|
import {
|
|
14
14
|
FlowClient,
|
|
15
15
|
RaisinAbortError,
|
|
@@ -20,10 +20,10 @@ import {
|
|
|
20
20
|
RaisinTimeoutError,
|
|
21
21
|
SSEClient,
|
|
22
22
|
classifyHttpError
|
|
23
|
-
} from "./chunk-
|
|
23
|
+
} from "./chunk-TPZNJNZR.mjs";
|
|
24
24
|
import {
|
|
25
25
|
createRaisinVue
|
|
26
|
-
} from "./chunk-
|
|
26
|
+
} from "./chunk-ZCRYQCXS.mjs";
|
|
27
27
|
import {
|
|
28
28
|
createAuthAdapter,
|
|
29
29
|
createConnectionAdapter,
|
|
@@ -48,7 +48,7 @@ import {
|
|
|
48
48
|
normalizeHomePath,
|
|
49
49
|
projectPlansFromMessages,
|
|
50
50
|
setLogLevel
|
|
51
|
-
} from "./chunk-
|
|
51
|
+
} from "./chunk-NOPZAMIV.mjs";
|
|
52
52
|
|
|
53
53
|
// src/client.ts
|
|
54
54
|
import { EventEmitter as EventEmitter2 } from "events";
|
|
@@ -506,6 +506,8 @@ var RequestType = /* @__PURE__ */ ((RequestType2) => {
|
|
|
506
506
|
RequestType2["ScheduledInvocationCancel"] = "scheduled_invocation_cancel";
|
|
507
507
|
RequestType2["ScheduledInvocationList"] = "scheduled_invocation_list";
|
|
508
508
|
RequestType2["ScheduledInvocationGet"] = "scheduled_invocation_get";
|
|
509
|
+
RequestType2["VisitorChatStart"] = "visitor_chat_start";
|
|
510
|
+
RequestType2["VisitorChatSend"] = "visitor_chat_send";
|
|
509
511
|
return RequestType2;
|
|
510
512
|
})(RequestType || {});
|
|
511
513
|
var ResponseStatus = /* @__PURE__ */ ((ResponseStatus2) => {
|
|
@@ -789,7 +791,8 @@ var EventHandler = class {
|
|
|
789
791
|
this.filterSubscriptions.set(hash, {
|
|
790
792
|
serverId: subscriptionId,
|
|
791
793
|
filters: {},
|
|
792
|
-
callbacks: /* @__PURE__ */ new Set([callback])
|
|
794
|
+
callbacks: /* @__PURE__ */ new Set([callback]),
|
|
795
|
+
synthetic: true
|
|
793
796
|
});
|
|
794
797
|
this.subscriptions.set(subscriptionId, hash);
|
|
795
798
|
this.callbackToHash.set(callback, hash);
|
|
@@ -824,11 +827,12 @@ var EventHandler = class {
|
|
|
824
827
|
async restoreSubscriptions(options) {
|
|
825
828
|
if (!options?.retry) {
|
|
826
829
|
for (const entry of this.filterSubscriptions.values()) {
|
|
830
|
+
if (entry.synthetic) continue;
|
|
827
831
|
this.subscriptions.delete(entry.serverId);
|
|
828
832
|
entry.restorePending = true;
|
|
829
833
|
}
|
|
830
834
|
}
|
|
831
|
-
const entriesToRestore = Array.from(this.filterSubscriptions.entries()).filter(([, entry]) => entry.restorePending);
|
|
835
|
+
const entriesToRestore = Array.from(this.filterSubscriptions.entries()).filter(([, entry]) => entry.restorePending && !entry.synthetic);
|
|
832
836
|
let failureCount = 0;
|
|
833
837
|
let lastError;
|
|
834
838
|
for (const [hash, entry] of entriesToRestore) {
|
|
@@ -3585,7 +3589,8 @@ var SearchApi = class {
|
|
|
3585
3589
|
// src/conversations.ts
|
|
3586
3590
|
var DEFAULT_SEND_MESSAGE_INACTIVITY_TIMEOUT_MS = 12e4;
|
|
3587
3591
|
var ConversationManager = class {
|
|
3588
|
-
constructor(baseUrl, repository, authManager, options = {}, executeSql) {
|
|
3592
|
+
constructor(baseUrl, repository, authManager, options = {}, executeSql, visitor) {
|
|
3593
|
+
this.visitor = visitor;
|
|
3589
3594
|
this.baseUrl = baseUrl.replace(/\/$/, "");
|
|
3590
3595
|
this.repository = repository;
|
|
3591
3596
|
this.authManager = authManager;
|
|
@@ -3706,6 +3711,45 @@ var ConversationManager = class {
|
|
|
3706
3711
|
]
|
|
3707
3712
|
};
|
|
3708
3713
|
}
|
|
3714
|
+
/**
|
|
3715
|
+
* Start (or resume) an ANONYMOUS conversation with an agent — a public
|
|
3716
|
+
* website's chat, without login.
|
|
3717
|
+
*
|
|
3718
|
+
* Works on an anonymous connection only, and only with an agent that allows
|
|
3719
|
+
* anonymous visitors (`anonymous.enabled: true` on its raisin:AIAgent). The
|
|
3720
|
+
* server keeps the conversation in an ephemeral visitor session that only
|
|
3721
|
+
* this browser session can read; the session secret is kept in
|
|
3722
|
+
* sessionStorage (override with `options.store`), so a reload continues the
|
|
3723
|
+
* same conversation. Then use `sendMessage`, `getMessages`, `subscribe` and
|
|
3724
|
+
* `ConversationStore` / `useConversation` exactly as for a signed-in user.
|
|
3725
|
+
*
|
|
3726
|
+
* @example
|
|
3727
|
+
* ```typescript
|
|
3728
|
+
* const convo = await db.conversations.startAnonymous('/agents/website-assistant');
|
|
3729
|
+
* for await (const ev of db.conversations.sendMessage(convo.conversationPath, 'Hello')) {
|
|
3730
|
+
* if (ev.type === 'text_chunk') append(ev.text);
|
|
3731
|
+
* if (ev.type === 'failed') showLimit(ev.code); // e.g. RATE_LIMITED, LIMIT_REACHED
|
|
3732
|
+
* }
|
|
3733
|
+
* ```
|
|
3734
|
+
*/
|
|
3735
|
+
async startAnonymous(agent, options) {
|
|
3736
|
+
if (!this.visitor) {
|
|
3737
|
+
throw new Error("Anonymous chat needs a WebSocket database: use client.database(repo).");
|
|
3738
|
+
}
|
|
3739
|
+
return this.visitor.start(this.normalizeAgentPath(agent), options);
|
|
3740
|
+
}
|
|
3741
|
+
/** Forget the stored anonymous session for `agent` (the next start begins a new one). */
|
|
3742
|
+
forgetAnonymous(agent, options) {
|
|
3743
|
+
this.visitor?.forget(this.normalizeAgentPath(agent), options);
|
|
3744
|
+
}
|
|
3745
|
+
/** Whether this tab remembers an anonymous conversation with `agent`. */
|
|
3746
|
+
hasStoredAnonymous(agent, options) {
|
|
3747
|
+
return this.visitor?.remembers(this.normalizeAgentPath(agent), options) ?? false;
|
|
3748
|
+
}
|
|
3749
|
+
/** Whether `conversationPath` is an anonymous conversation of this client. */
|
|
3750
|
+
isAnonymous(conversationPath) {
|
|
3751
|
+
return this.visitor?.isAnonymous(conversationPath) ?? false;
|
|
3752
|
+
}
|
|
3709
3753
|
/**
|
|
3710
3754
|
* Open an existing conversation by path.
|
|
3711
3755
|
* Returns null if not found.
|
|
@@ -3751,6 +3795,7 @@ var ConversationManager = class {
|
|
|
3751
3795
|
* Mark a conversation as read by setting unread_count to 0.
|
|
3752
3796
|
*/
|
|
3753
3797
|
async markAsRead(conversationPath) {
|
|
3798
|
+
if (this.isAnonymous(conversationPath)) return;
|
|
3754
3799
|
const workspace = "raisin:access_control";
|
|
3755
3800
|
await this.sqlQuery(
|
|
3756
3801
|
`UPDATE '${workspace}' SET properties = jsonb_set(properties, '{unread_count}', '0'::jsonb) WHERE path = $1 AND node_type = 'raisin:Conversation'`,
|
|
@@ -3761,6 +3806,7 @@ var ConversationManager = class {
|
|
|
3761
3806
|
* Mark a single message as read by the current user.
|
|
3762
3807
|
*/
|
|
3763
3808
|
async markMessageAsRead(messagePath) {
|
|
3809
|
+
if (messagePath.startsWith("/visitors/")) return;
|
|
3764
3810
|
const workspace = "raisin:access_control";
|
|
3765
3811
|
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
3766
3812
|
await this.sqlQuery(
|
|
@@ -3785,6 +3831,18 @@ var ConversationManager = class {
|
|
|
3785
3831
|
*/
|
|
3786
3832
|
async *sendMessage(conversationPath, content, options) {
|
|
3787
3833
|
const shouldStream = options?.stream !== false;
|
|
3834
|
+
if (this.visitor?.isAnonymous(conversationPath)) {
|
|
3835
|
+
if (!shouldStream) {
|
|
3836
|
+
await this.visitor.post(conversationPath, content);
|
|
3837
|
+
yield { type: "waiting", timestamp: (/* @__PURE__ */ new Date()).toISOString() };
|
|
3838
|
+
return;
|
|
3839
|
+
}
|
|
3840
|
+
yield* this.visitor.stream(conversationPath, content, {
|
|
3841
|
+
signal: options?.signal,
|
|
3842
|
+
inactivityTimeoutMs: options?.inactivityTimeoutMs ?? DEFAULT_SEND_MESSAGE_INACTIVITY_TIMEOUT_MS
|
|
3843
|
+
});
|
|
3844
|
+
return;
|
|
3845
|
+
}
|
|
3788
3846
|
logger.debug("[ConversationManager] Starting SSE stream for message send");
|
|
3789
3847
|
if (!shouldStream) {
|
|
3790
3848
|
await this.createUserMessage(conversationPath, content);
|
|
@@ -3872,6 +3930,10 @@ var ConversationManager = class {
|
|
|
3872
3930
|
*/
|
|
3873
3931
|
async createUserMessage(conversationPath, content) {
|
|
3874
3932
|
logger.debug("[ConversationManager] Creating user message", { path: conversationPath });
|
|
3933
|
+
if (this.visitor?.isAnonymous(conversationPath)) {
|
|
3934
|
+
await this.visitor.post(conversationPath, content);
|
|
3935
|
+
return;
|
|
3936
|
+
}
|
|
3875
3937
|
const workspace = "raisin:access_control";
|
|
3876
3938
|
const properties = await this.loadConversationProperties(conversationPath, workspace);
|
|
3877
3939
|
const flowInstanceId = typeof properties?.flow_instance_id === "string" ? properties.flow_instance_id.trim() : "";
|
|
@@ -3923,6 +3985,12 @@ var ConversationManager = class {
|
|
|
3923
3985
|
* initiated messages, etc.). Auto-reconnects on disconnect.
|
|
3924
3986
|
*/
|
|
3925
3987
|
subscribe(conversationPath, onEvent, options) {
|
|
3988
|
+
if (this.visitor?.isAnonymous(conversationPath)) {
|
|
3989
|
+
const stop = this.visitor.listen(conversationPath, onEvent);
|
|
3990
|
+
options?.signal?.addEventListener("abort", stop, { once: true });
|
|
3991
|
+
return { unsubscribe: stop, waitUntilConnected: async () => {
|
|
3992
|
+
} };
|
|
3993
|
+
}
|
|
3926
3994
|
logger.info("[ConversationManager] Subscribing to SSE", { path: conversationPath });
|
|
3927
3995
|
const sseUrl = `${this.baseUrl}/api/conversations/${this.repository}/events`;
|
|
3928
3996
|
const headers = {};
|
|
@@ -4362,6 +4430,272 @@ var ConversationManager = class {
|
|
|
4362
4430
|
}
|
|
4363
4431
|
};
|
|
4364
4432
|
|
|
4433
|
+
// src/visitor-chat.ts
|
|
4434
|
+
function defaultVisitorSessionStore() {
|
|
4435
|
+
const memory = /* @__PURE__ */ new Map();
|
|
4436
|
+
const storage = () => {
|
|
4437
|
+
try {
|
|
4438
|
+
return typeof sessionStorage !== "undefined" ? sessionStorage : null;
|
|
4439
|
+
} catch {
|
|
4440
|
+
return null;
|
|
4441
|
+
}
|
|
4442
|
+
};
|
|
4443
|
+
return {
|
|
4444
|
+
get(key) {
|
|
4445
|
+
try {
|
|
4446
|
+
return storage()?.getItem(key) ?? memory.get(key) ?? null;
|
|
4447
|
+
} catch {
|
|
4448
|
+
return memory.get(key) ?? null;
|
|
4449
|
+
}
|
|
4450
|
+
},
|
|
4451
|
+
set(key, value) {
|
|
4452
|
+
memory.set(key, value);
|
|
4453
|
+
try {
|
|
4454
|
+
storage()?.setItem(key, value);
|
|
4455
|
+
} catch {
|
|
4456
|
+
}
|
|
4457
|
+
},
|
|
4458
|
+
remove(key) {
|
|
4459
|
+
memory.delete(key);
|
|
4460
|
+
try {
|
|
4461
|
+
storage()?.removeItem(key);
|
|
4462
|
+
} catch {
|
|
4463
|
+
}
|
|
4464
|
+
}
|
|
4465
|
+
};
|
|
4466
|
+
}
|
|
4467
|
+
var VisitorChatError = class extends Error {
|
|
4468
|
+
constructor(message, code) {
|
|
4469
|
+
super(message);
|
|
4470
|
+
this.name = "VisitorChatError";
|
|
4471
|
+
this.code = code;
|
|
4472
|
+
}
|
|
4473
|
+
};
|
|
4474
|
+
var REBIND_CODES = /* @__PURE__ */ new Set(["NO_SESSION", "UNKNOWN_CONVERSATION"]);
|
|
4475
|
+
function asError(err) {
|
|
4476
|
+
const e = err;
|
|
4477
|
+
return new VisitorChatError(e?.message ?? String(err), e?.code ?? "UNAVAILABLE");
|
|
4478
|
+
}
|
|
4479
|
+
var VisitorChat = class {
|
|
4480
|
+
constructor(repository, send, events, onReconnected) {
|
|
4481
|
+
this.repository = repository;
|
|
4482
|
+
this.send = send;
|
|
4483
|
+
this.events = events;
|
|
4484
|
+
this.byPath = /* @__PURE__ */ new Map();
|
|
4485
|
+
this.token = null;
|
|
4486
|
+
onReconnected?.(() => {
|
|
4487
|
+
void this.rebindAll();
|
|
4488
|
+
});
|
|
4489
|
+
}
|
|
4490
|
+
/** Whether `conversationPath` is a visitor conversation started here. */
|
|
4491
|
+
isAnonymous(conversationPath) {
|
|
4492
|
+
return this.byPath.has(conversationPath);
|
|
4493
|
+
}
|
|
4494
|
+
storeOf(options) {
|
|
4495
|
+
if (options.store === false) return null;
|
|
4496
|
+
return options.store ?? defaultVisitorSessionStore();
|
|
4497
|
+
}
|
|
4498
|
+
keyOf(agent, options) {
|
|
4499
|
+
return options.storageKey ?? `raisindb:visitor:${this.repository}:${agent}`;
|
|
4500
|
+
}
|
|
4501
|
+
/** Start (or resume) a visitor conversation with `agent` (`/agents/<name>`). */
|
|
4502
|
+
async start(agent, options = {}) {
|
|
4503
|
+
const store = this.storeOf(options);
|
|
4504
|
+
const key = this.keyOf(agent, options);
|
|
4505
|
+
const sessionToken = options.sessionToken ?? this.token ?? store?.get(`${key}:session`) ?? void 0;
|
|
4506
|
+
const conversationId = options.newConversation ? void 0 : options.conversationId ?? store?.get(`${key}:conversation`) ?? void 0;
|
|
4507
|
+
let res;
|
|
4508
|
+
try {
|
|
4509
|
+
res = await this.send(
|
|
4510
|
+
{ agent, session_token: sessionToken, conversation_id: conversationId },
|
|
4511
|
+
"visitor_chat_start"
|
|
4512
|
+
);
|
|
4513
|
+
} catch (err) {
|
|
4514
|
+
const e = asError(err);
|
|
4515
|
+
if ((conversationId || sessionToken) && !options.conversationId && !options.sessionToken && ["UNKNOWN_CONVERSATION", "INVALID_CONVERSATION", "SESSION_EXPIRED", "SESSION_MISMATCH"].includes(e.code)) {
|
|
4516
|
+
store?.remove(`${key}:conversation`);
|
|
4517
|
+
if (e.code !== "UNKNOWN_CONVERSATION" && e.code !== "INVALID_CONVERSATION") {
|
|
4518
|
+
store?.remove(`${key}:session`);
|
|
4519
|
+
this.token = null;
|
|
4520
|
+
}
|
|
4521
|
+
return this.start(agent, { ...options, newConversation: true });
|
|
4522
|
+
}
|
|
4523
|
+
throw e;
|
|
4524
|
+
}
|
|
4525
|
+
const token = res.session_token ?? sessionToken ?? this.token;
|
|
4526
|
+
if (!token) throw new VisitorChatError("the server returned no session", "UNAVAILABLE");
|
|
4527
|
+
this.token = token;
|
|
4528
|
+
store?.set(`${key}:session`, token);
|
|
4529
|
+
store?.set(`${key}:conversation`, res.conversation_id);
|
|
4530
|
+
const path = res.conversation_path;
|
|
4531
|
+
let entry = this.byPath.get(path);
|
|
4532
|
+
if (!entry) {
|
|
4533
|
+
entry = {
|
|
4534
|
+
agent: res.agent,
|
|
4535
|
+
conversationId: res.conversation_id,
|
|
4536
|
+
subscriptionId: res.subscription_id,
|
|
4537
|
+
listeners: /* @__PURE__ */ new Set(),
|
|
4538
|
+
options
|
|
4539
|
+
};
|
|
4540
|
+
this.byPath.set(path, entry);
|
|
4541
|
+
}
|
|
4542
|
+
this.route(entry);
|
|
4543
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
4544
|
+
return {
|
|
4545
|
+
id: res.conversation_id,
|
|
4546
|
+
type: "ai_chat",
|
|
4547
|
+
agentRef: res.agent,
|
|
4548
|
+
conversationPath: path,
|
|
4549
|
+
conversationWorkspace: res.conversation_workspace,
|
|
4550
|
+
anonymous: true,
|
|
4551
|
+
conversationId: res.conversation_id,
|
|
4552
|
+
sessionToken: token,
|
|
4553
|
+
limits: res.limits,
|
|
4554
|
+
initialEvents: [{ type: "waiting", timestamp: now }]
|
|
4555
|
+
};
|
|
4556
|
+
}
|
|
4557
|
+
/** Route the server's forwarded events for this conversation to its listeners. */
|
|
4558
|
+
route(entry) {
|
|
4559
|
+
this.events.removeFlowEventListener(entry.subscriptionId);
|
|
4560
|
+
this.events.addFlowEventListener(entry.subscriptionId, (msg) => {
|
|
4561
|
+
const event = msg.payload;
|
|
4562
|
+
if (!event || typeof event.type !== "string") return;
|
|
4563
|
+
for (const listener of entry.listeners) {
|
|
4564
|
+
try {
|
|
4565
|
+
listener(event);
|
|
4566
|
+
} catch (err) {
|
|
4567
|
+
logger.error("[VisitorChat] listener failed", err);
|
|
4568
|
+
}
|
|
4569
|
+
}
|
|
4570
|
+
});
|
|
4571
|
+
}
|
|
4572
|
+
/** Re-prove the session on a new connection, for every conversation started here. */
|
|
4573
|
+
async rebindAll() {
|
|
4574
|
+
for (const entry of this.byPath.values()) {
|
|
4575
|
+
try {
|
|
4576
|
+
await this.send(
|
|
4577
|
+
{ agent: entry.agent, session_token: this.token, conversation_id: entry.conversationId },
|
|
4578
|
+
"visitor_chat_start"
|
|
4579
|
+
);
|
|
4580
|
+
this.route(entry);
|
|
4581
|
+
} catch (err) {
|
|
4582
|
+
logger.warn("[VisitorChat] could not resume a conversation after reconnect", err);
|
|
4583
|
+
}
|
|
4584
|
+
}
|
|
4585
|
+
}
|
|
4586
|
+
/** Listen to a visitor conversation's events. Returns an unsubscribe function. */
|
|
4587
|
+
listen(conversationPath, listener) {
|
|
4588
|
+
const entry = this.require(conversationPath);
|
|
4589
|
+
entry.listeners.add(listener);
|
|
4590
|
+
return () => {
|
|
4591
|
+
entry.listeners.delete(listener);
|
|
4592
|
+
};
|
|
4593
|
+
}
|
|
4594
|
+
require(conversationPath) {
|
|
4595
|
+
const entry = this.byPath.get(conversationPath);
|
|
4596
|
+
if (!entry) {
|
|
4597
|
+
throw new VisitorChatError(
|
|
4598
|
+
"not a visitor conversation of this client; call startAnonymous first",
|
|
4599
|
+
"UNKNOWN_CONVERSATION"
|
|
4600
|
+
);
|
|
4601
|
+
}
|
|
4602
|
+
return entry;
|
|
4603
|
+
}
|
|
4604
|
+
/** Make sure this connection is bound (after a reconnect nothing else may read the home). */
|
|
4605
|
+
async ensureBound(conversationPath) {
|
|
4606
|
+
const entry = this.require(conversationPath);
|
|
4607
|
+
await this.send(
|
|
4608
|
+
{ agent: entry.agent, session_token: this.token, conversation_id: entry.conversationId },
|
|
4609
|
+
"visitor_chat_start"
|
|
4610
|
+
).catch((err) => {
|
|
4611
|
+
throw asError(err);
|
|
4612
|
+
});
|
|
4613
|
+
}
|
|
4614
|
+
/** Send one visitor message. Events arrive through {@link listen}. */
|
|
4615
|
+
async post(conversationPath, text) {
|
|
4616
|
+
const entry = this.require(conversationPath);
|
|
4617
|
+
const once = async () => await this.send(
|
|
4618
|
+
{ conversation_id: entry.conversationId, text },
|
|
4619
|
+
"visitor_chat_send"
|
|
4620
|
+
);
|
|
4621
|
+
try {
|
|
4622
|
+
const res = await once();
|
|
4623
|
+
return { messageId: res.message_id, messagesLeft: res.messages_left };
|
|
4624
|
+
} catch (err) {
|
|
4625
|
+
const e = asError(err);
|
|
4626
|
+
if (!REBIND_CODES.has(e.code)) throw e;
|
|
4627
|
+
await this.ensureBound(conversationPath);
|
|
4628
|
+
this.route(entry);
|
|
4629
|
+
const res = await once().catch((again) => {
|
|
4630
|
+
throw asError(again);
|
|
4631
|
+
});
|
|
4632
|
+
return { messageId: res.message_id, messagesLeft: res.messages_left };
|
|
4633
|
+
}
|
|
4634
|
+
}
|
|
4635
|
+
/**
|
|
4636
|
+
* Send one visitor message and stream the turn: `text_chunk`,
|
|
4637
|
+
* `tool_call_started`, `tool_call_completed`, … until `done`. A refusal
|
|
4638
|
+
* ends the stream with `failed` (its `code` says why). No event for
|
|
4639
|
+
* `inactivityTimeoutMs` ends it with a synthetic `waiting`.
|
|
4640
|
+
*/
|
|
4641
|
+
async *stream(conversationPath, text, options = {}) {
|
|
4642
|
+
const queue = [];
|
|
4643
|
+
let wake = null;
|
|
4644
|
+
const push = (event) => {
|
|
4645
|
+
queue.push(event);
|
|
4646
|
+
wake?.();
|
|
4647
|
+
};
|
|
4648
|
+
const stop = this.listen(conversationPath, push);
|
|
4649
|
+
const onAbort = () => push({ type: "failed", error: "aborted", code: "ABORTED", timestamp: (/* @__PURE__ */ new Date()).toISOString() });
|
|
4650
|
+
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
4651
|
+
const timeout = options.inactivityTimeoutMs ?? 12e4;
|
|
4652
|
+
try {
|
|
4653
|
+
try {
|
|
4654
|
+
await this.post(conversationPath, text);
|
|
4655
|
+
} catch (err) {
|
|
4656
|
+
const e = asError(err);
|
|
4657
|
+
yield { type: "failed", error: e.message, code: e.code, timestamp: (/* @__PURE__ */ new Date()).toISOString() };
|
|
4658
|
+
return;
|
|
4659
|
+
}
|
|
4660
|
+
for (; ; ) {
|
|
4661
|
+
if (!queue.length) {
|
|
4662
|
+
const idle = await new Promise((resolve) => {
|
|
4663
|
+
const timer = timeout > 0 ? setTimeout(() => resolve(true), timeout) : null;
|
|
4664
|
+
wake = () => {
|
|
4665
|
+
if (timer) clearTimeout(timer);
|
|
4666
|
+
resolve(false);
|
|
4667
|
+
};
|
|
4668
|
+
});
|
|
4669
|
+
wake = null;
|
|
4670
|
+
if (idle && !queue.length) {
|
|
4671
|
+
yield { type: "waiting", timestamp: (/* @__PURE__ */ new Date()).toISOString() };
|
|
4672
|
+
return;
|
|
4673
|
+
}
|
|
4674
|
+
}
|
|
4675
|
+
const event = queue.shift();
|
|
4676
|
+
yield event;
|
|
4677
|
+
if (event.type === "done" || event.type === "failed" || event.type === "waiting") return;
|
|
4678
|
+
}
|
|
4679
|
+
} finally {
|
|
4680
|
+
stop();
|
|
4681
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
4682
|
+
}
|
|
4683
|
+
}
|
|
4684
|
+
/** Whether the store remembers a conversation with `agent`. */
|
|
4685
|
+
remembers(agent, options = {}) {
|
|
4686
|
+
const store = this.storeOf(options);
|
|
4687
|
+
return !!store?.get(`${this.keyOf(agent, options)}:conversation`);
|
|
4688
|
+
}
|
|
4689
|
+
/** Forget the stored session (e.g. a "new chat" button that should start a new session). */
|
|
4690
|
+
forget(agent, options = {}) {
|
|
4691
|
+
const store = this.storeOf(options);
|
|
4692
|
+
const key = this.keyOf(agent, options);
|
|
4693
|
+
store?.remove(`${key}:session`);
|
|
4694
|
+
store?.remove(`${key}:conversation`);
|
|
4695
|
+
this.token = null;
|
|
4696
|
+
}
|
|
4697
|
+
};
|
|
4698
|
+
|
|
4365
4699
|
// src/inbox.ts
|
|
4366
4700
|
var InboxApi = class {
|
|
4367
4701
|
constructor(baseUrl, repository, authManager, options = {}) {
|
|
@@ -4816,7 +5150,13 @@ var Database = class _Database {
|
|
|
4816
5150
|
this.repository,
|
|
4817
5151
|
this.httpOptions.authManager,
|
|
4818
5152
|
{},
|
|
4819
|
-
(query, params) => this.executeSql(query, params)
|
|
5153
|
+
(query, params) => this.executeSql(query, params),
|
|
5154
|
+
new VisitorChat(
|
|
5155
|
+
this.repository,
|
|
5156
|
+
(payload, requestType) => this.sendRequest(payload, requestType),
|
|
5157
|
+
this.eventHandler,
|
|
5158
|
+
this.httpOptions.onReconnected
|
|
5159
|
+
)
|
|
4820
5160
|
);
|
|
4821
5161
|
}
|
|
4822
5162
|
return this._conversationManager;
|
|
@@ -8683,7 +9023,11 @@ var _RaisinClient = class _RaisinClient extends EventEmitter2 {
|
|
|
8683
9023
|
void 0,
|
|
8684
9024
|
() => this.getUploadManager(),
|
|
8685
9025
|
(options) => this.signAssetUrl(options),
|
|
8686
|
-
{
|
|
9026
|
+
{
|
|
9027
|
+
httpBaseUrl: this._httpBaseUrl,
|
|
9028
|
+
authManager: this.authManager,
|
|
9029
|
+
onReconnected: (callback) => this.onReconnected(callback)
|
|
9030
|
+
}
|
|
8687
9031
|
);
|
|
8688
9032
|
}
|
|
8689
9033
|
/**
|
|
@@ -9940,6 +10284,7 @@ export {
|
|
|
9940
10284
|
UploadErrorCode,
|
|
9941
10285
|
UploadManager,
|
|
9942
10286
|
Uploader,
|
|
10287
|
+
VisitorChatError,
|
|
9943
10288
|
WorkspaceClient,
|
|
9944
10289
|
WorkspaceManager,
|
|
9945
10290
|
calculateChunkCount,
|
|
@@ -9961,6 +10306,7 @@ export {
|
|
|
9961
10306
|
createSqlHandler,
|
|
9962
10307
|
createSubscriptionAdapter,
|
|
9963
10308
|
decodeMessage,
|
|
10309
|
+
defaultVisitorSessionStore,
|
|
9964
10310
|
encodeMessage,
|
|
9965
10311
|
getChunkRange,
|
|
9966
10312
|
getContentType,
|