@segmentstream/agent 0.72.4 → 0.73.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/CHANGELOG.md +57 -0
- package/dist/_chunks/{build-metadata-BuLFK152.mjs → build-metadata-CvUZSH8c.mjs} +1 -1
- package/dist/_chunks/chat-archive-BCPLSZeK.mjs +585 -0
- package/dist/_chunks/chat-archive-DK7uCgff.mjs +1337 -0
- package/dist/_chunks/{principal-Cw1NtCkj.mjs → principal-Zf42Yf4r.mjs} +1 -1
- package/dist/extension/config.d.ts +8 -0
- package/dist/extension/config.mjs +12 -0
- package/dist/extension/connections/ontology.mjs +1 -1
- package/dist/extension/hooks/authorization.mjs +1 -1
- package/dist/extension/hooks/chat-context.mjs +1 -1
- package/dist/extension/hooks/chat-recorder.mjs +1 -1
- package/dist/extension/instructions/persona.mjs +1 -1
- package/dist/extension/lib/actor.mjs +1 -1
- package/dist/extension/lib/attachment-tools.mjs +1 -1
- package/dist/extension/lib/attachments-send.mjs +1 -1
- package/dist/extension/lib/attachments.mjs +1 -1
- package/dist/extension/lib/build-metadata.mjs +1 -1
- package/dist/extension/lib/chat-address.mjs +1 -1
- package/dist/extension/lib/chat-archive.d.ts +50 -0
- package/dist/extension/lib/chat-archive.mjs +1 -188
- package/dist/extension/lib/chat-context.d.ts +10 -2
- package/dist/extension/lib/chat-context.mjs +48 -9
- package/dist/extension/lib/chat-messages.mjs +13 -1
- package/dist/extension/lib/chat-recorder.d.ts +2 -0
- package/dist/extension/lib/chat-recorder.mjs +105 -4
- package/dist/extension/lib/chat-store.d.ts +212 -0
- package/dist/extension/lib/chat-store.mjs +103 -0
- package/dist/extension/lib/confirmations.mjs +1 -1
- package/dist/extension/lib/email/attachments-send.mjs +1 -1
- package/dist/extension/lib/email/channel.mjs +2 -2
- package/dist/extension/lib/group-routing/routing-context.mjs +21 -11
- package/dist/extension/lib/guest-usage.mjs +1 -1
- package/dist/extension/lib/inbound-media/files.mjs +1 -1
- package/dist/extension/lib/inbound-media/index.mjs +1 -1
- package/dist/extension/lib/model-service-alert.mjs +14 -1
- package/dist/extension/lib/ontology-connection.mjs +1 -1
- package/dist/extension/lib/ontology-file-call.mjs +1 -1
- package/dist/extension/lib/ontology-tools.mjs +1 -1
- package/dist/extension/lib/review/hold.mjs +1 -1
- package/dist/extension/lib/review/judge.mjs +1 -1
- package/dist/extension/lib/review/reply.mjs +2 -2
- package/dist/extension/lib/review/revision-channel.mjs +1 -1
- package/dist/extension/lib/role-skill.mjs +1 -1
- package/dist/extension/lib/runtime-envelope.mjs +1 -1
- package/dist/extension/lib/sent-files.mjs +1 -1
- package/dist/extension/lib/slack/adapter.mjs +2 -2
- package/dist/extension/lib/slack/attachments-send.mjs +1 -1
- package/dist/extension/lib/slack/callbacks.mjs +1 -1
- package/dist/extension/lib/stored-files.mjs +1 -1
- package/dist/extension/lib/telegram/adapter.mjs +4 -4
- package/dist/extension/lib/telegram/attachment-description.mjs +1 -1
- package/dist/extension/lib/telegram/attachments-send.mjs +1 -1
- package/dist/extension/lib/telegram/callbacks.mjs +1 -1
- package/dist/extension/lib/telegram/chat-archive.d.ts +32 -3
- package/dist/extension/lib/telegram/chat-archive.mjs +1 -703
- package/dist/extension/lib/telegram/confirmations.mjs +2 -2
- package/dist/extension/lib/telegram/customer-text.mjs +1 -1
- package/dist/extension/lib/telegram/delivery-diagnostics.mjs +1 -1
- package/dist/extension/lib/telegram/files.mjs +1 -1
- package/dist/extension/lib/telegram/health.mjs +1 -1
- package/dist/extension/lib/telegram/held-approvals.mjs +1 -1
- package/dist/extension/lib/telegram/inbound-request.d.ts +2 -1
- package/dist/extension/lib/telegram/inbound-request.mjs +1 -1
- package/dist/extension/lib/telegram/inbound.mjs +2 -2
- package/dist/extension/lib/telegram/lifecycle.mjs +2 -2
- package/dist/extension/lib/telegram/principal.mjs +1 -1
- package/dist/extension/lib/telegram/session-recovery.mjs +1 -1
- package/dist/extension/lib/telegram/silent.mjs +1 -1
- package/dist/extension/lib/telegram/store-capture.d.ts +37 -0
- package/dist/extension/lib/telegram/store-capture.mjs +7 -0
- package/dist/extension/lib/telegram/structured.mjs +1 -1
- package/dist/extension/lib/telegram/turn-errors.mjs +2 -2
- package/dist/extension/lib/traces.d.ts +21 -0
- package/dist/extension/lib/traces.mjs +16 -0
- package/dist/extension/lib/web/auth.mjs +1 -1
- package/dist/extension/lib/web/channel.mjs +1 -1
- package/dist/extension/lib/whatsapp/adapter.mjs +2 -2
- package/dist/extension/lib/whatsapp/attachments-send.mjs +2 -2
- package/dist/extension/lib/whatsapp/callbacks.mjs +1 -1
- package/dist/extension/lib/whatsapp/files.mjs +1 -1
- package/dist/extension/lib/whatsapp/sent.mjs +1 -1
- package/dist/extension/lib/workspace-action.mjs +1 -1
- package/dist/extension/lib/workspace-channel/attachments-send.mjs +1 -1
- package/dist/extension/lib/workspace-channel/channel.mjs +2 -2
- package/dist/extension/lib/workspace-chat-archive.d.ts +41 -0
- package/dist/extension/lib/workspace-chat-archive.mjs +7 -0
- package/dist/extension/lib/workspace-source.mjs +1 -1
- package/dist/extension/model.mjs +1 -1
- package/dist/extension/tools/attachments_discard.mjs +1 -1
- package/dist/extension/tools/attachments_list.mjs +1 -1
- package/dist/extension/tools/attachments_promote.mjs +1 -1
- package/dist/extension/tools/attachments_read.mjs +1 -1
- package/dist/extension/tools/attachments_send.mjs +1 -1
- package/dist/extension/tools/attachments_stage.mjs +1 -1
- package/dist/extension/tools/attachments_table.mjs +1 -1
- package/dist/extension/tools/handoff.mjs +1 -1
- package/dist/extension/tools/questions_ask.mjs +1 -1
- package/dist/extension/tools/workspace_source.mjs +1 -1
- package/package.json +6 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,62 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.73.0
|
|
4
|
+
|
|
5
|
+
The agent keeps its chats in the workspace's own database, the chat store, once its ontology
|
|
6
|
+
service has one: one row per message with its latest state. It asks the ontology service once per
|
|
7
|
+
process; an ontology SDK released before the chat store keeps the agent on the platform's chat
|
|
8
|
+
archive exactly as before, so the agent and the ontology can be upgraded in either order.
|
|
9
|
+
|
|
10
|
+
On the chat store the agent records messages only. What it did with a person's message is the
|
|
11
|
+
message's own state: a turn, or skipped with a reason code such as `not_addressed`,
|
|
12
|
+
`identity_unknown`, `chat_handled` or `silent`, with the session and turn of the turn it started.
|
|
13
|
+
A reply is one row, the agent's, even when WhatsApp reports the agent's message back before the
|
|
14
|
+
agent recorded it. A confirmation card's state is kept on the card. A question the agent could not
|
|
15
|
+
answer (`segmentstream__unanswered`) is kept as an internal message of its turn. Tool calls, the
|
|
16
|
+
model's decisions and failures are no longer stored with the chat: they are the turn's trace and
|
|
17
|
+
the runtime's logs. Until Cloud reads a turn from its trace, `segmentstream agent logs` shows no
|
|
18
|
+
tool calls, decisions or failures of an agent on the chat store, and the chat figures do not count
|
|
19
|
+
the questions it could not answer.
|
|
20
|
+
|
|
21
|
+
Telegram's dispatch keeps its guarantee on the chat store: a message starts at most one turn,
|
|
22
|
+
however often Telegram delivers it and however many processes receive it; a failure before the
|
|
23
|
+
dispatch lets Telegram's retry take the message at once, and an abandoned claim expires after ten
|
|
24
|
+
minutes. A structured input's edits each dispatch once per revision. The files Telegram stores for
|
|
25
|
+
a message are the message's files in the chat store, which the inbox reads, and a voice message's
|
|
26
|
+
transcript is its text, after its caption, kept once, so a long transcript never fails to be
|
|
27
|
+
recorded. What a request read of a message is kept only while the message holds the revision it
|
|
28
|
+
read: a newer edit that arrives meanwhile keeps its own text, files and routing state. A Telegram
|
|
29
|
+
edit, its routing state and its files are one write, as is a confirmation card's text and state,
|
|
30
|
+
so a stopped request never leaves a message between two revisions; an edit that replaced a file
|
|
31
|
+
clears the file it replaced; and a turn that reads more than 500 changes of a chat reads the rest
|
|
32
|
+
on its next turn. Group routing and each
|
|
33
|
+
turn's chat context read the chat store; a message the session saw that was since edited or
|
|
34
|
+
deleted comes again, marked, even one the session was sent and answered, and a deleted one comes
|
|
35
|
+
without its text, its files or what was read of it. A Telegram edit older than the one a message
|
|
36
|
+
already holds, which Telegram may retry late, and an edit of a deleted message are not processed:
|
|
37
|
+
the message keeps the newer revision's text and routing state.
|
|
38
|
+
|
|
39
|
+
Turn traces are the SDK's own decision: `traces()` from the new `@segmentstream/agent/traces`
|
|
40
|
+
export traces every turn of every chat, private ones included, with its content (messages, model
|
|
41
|
+
input and output, tool arguments and results), and `"traces": { "content": false }` in
|
|
42
|
+
`agent/segmentstream.json` keeps the steps and timings without the content. The starter exports it
|
|
43
|
+
from `agent/agent/instrumentation/otel.ts`; an agent without that file keeps the runtime's default,
|
|
44
|
+
which keeps content for public chats alone. Keeping content also keeps a finished session's run
|
|
45
|
+
data for the runtime's default period unless `agent.ts` sets its retention.
|
|
46
|
+
|
|
47
|
+
Action required: to trace every turn with the SDK's policy, add
|
|
48
|
+
`agent/agent/instrumentation/otel.ts`, which `segmentstream upgrade` does not write, with
|
|
49
|
+
`import { traces } from "@segmentstream/agent/traces";`,
|
|
50
|
+
`import config from "../../segmentstream.json";` and `export default traces(config);`, as the
|
|
51
|
+
starter does; set `"traces": { "content": false }` in `agent/segmentstream.json` to keep content
|
|
52
|
+
out of traces.
|
|
53
|
+
|
|
54
|
+
Pins @segmentstream/ontology 0.150.0.
|
|
55
|
+
|
|
56
|
+
## 0.72.5
|
|
57
|
+
|
|
58
|
+
Pins @segmentstream/ontology 0.149.0.
|
|
59
|
+
|
|
3
60
|
## 0.72.4
|
|
4
61
|
|
|
5
62
|
`segmentstream__browser` tells SegmentStream how long each script may run, so the agent's browser
|
|
@@ -4,7 +4,7 @@ import { createRequire as __eveCreateRequire } from "node:module";
|
|
|
4
4
|
const __filename = __eveFileURLToPath(import.meta.url);
|
|
5
5
|
__eveDirname(__filename);
|
|
6
6
|
__eveCreateRequire(import.meta.url);
|
|
7
|
-
var version = "0.
|
|
7
|
+
var version = "0.73.0";
|
|
8
8
|
function agentBuild(environment = process.env) {
|
|
9
9
|
return {
|
|
10
10
|
agent: version,
|
|
@@ -0,0 +1,585 @@
|
|
|
1
|
+
import { fileURLToPath as __eveFileURLToPath } from "node:url";
|
|
2
|
+
import { dirname as __eveDirname } from "node:path";
|
|
3
|
+
import { createRequire as __eveCreateRequire } from "node:module";
|
|
4
|
+
const __filename = __eveFileURLToPath(import.meta.url);
|
|
5
|
+
__eveDirname(__filename);
|
|
6
|
+
__eveCreateRequire(import.meta.url);
|
|
7
|
+
import { channelKey } from "../extension/lib/channel-scope.mjs";
|
|
8
|
+
import { ChatStoreError, chatStore, storeAvailable } from "../extension/lib/chat-store.mjs";
|
|
9
|
+
import { appOrigin, proxyEnvironment } from "../extension/lib/environment.mjs";
|
|
10
|
+
import { runtimeToken } from "../extension/lib/runtime-token.mjs";
|
|
11
|
+
import { r as workflowValue } from "./workflow-serializable-gzv5MZ5P.mjs";
|
|
12
|
+
import { createHash } from "node:crypto";
|
|
13
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
|
|
14
|
+
const BOUNDS = {
|
|
15
|
+
id: 512,
|
|
16
|
+
chat: 256,
|
|
17
|
+
sender: 256,
|
|
18
|
+
name: 200,
|
|
19
|
+
text: 1e5
|
|
20
|
+
};
|
|
21
|
+
function reasonCode(value) {
|
|
22
|
+
if (value === null || value === void 0) return;
|
|
23
|
+
const code = value.toLowerCase().replace(/[^a-z0-9_]+/gu, "_").replace(/^[^a-z]+/u, "").slice(0, 64);
|
|
24
|
+
return code === "" ? void 0 : code;
|
|
25
|
+
}
|
|
26
|
+
function bounded(value, maximum) {
|
|
27
|
+
return value === null || value === void 0 || value === "" ? void 0 : value.slice(0, maximum);
|
|
28
|
+
}
|
|
29
|
+
const META_BUDGET = 61440;
|
|
30
|
+
const CUT = "…";
|
|
31
|
+
const KEPT_LENGTH = 256;
|
|
32
|
+
function cutText(value, length) {
|
|
33
|
+
const code = value.charCodeAt(length - 1);
|
|
34
|
+
return value.slice(0, code >= 55296 && code <= 56319 ? length - 1 : length);
|
|
35
|
+
}
|
|
36
|
+
function longestString(value) {
|
|
37
|
+
if (value === null || typeof value !== "object") return;
|
|
38
|
+
let longest;
|
|
39
|
+
for (const [key, item] of Object.entries(value)) {
|
|
40
|
+
const found = typeof item === "string" ? item.length > 257 ? {
|
|
41
|
+
holder: value,
|
|
42
|
+
key,
|
|
43
|
+
value: item
|
|
44
|
+
} : void 0 : longestString(item);
|
|
45
|
+
if (found !== void 0 && found.value.length > (longest?.value.length ?? 0)) longest = found;
|
|
46
|
+
}
|
|
47
|
+
return longest;
|
|
48
|
+
}
|
|
49
|
+
function boundedMeta(meta) {
|
|
50
|
+
let size = JSON.stringify(meta ?? null).length;
|
|
51
|
+
if (size <= META_BUDGET) return meta;
|
|
52
|
+
const bounded = structuredClone(meta);
|
|
53
|
+
while (size > META_BUDGET) {
|
|
54
|
+
const longest = longestString(bounded);
|
|
55
|
+
if (longest === void 0) break;
|
|
56
|
+
const kept = Math.max(KEPT_LENGTH, longest.value.length - (size - META_BUDGET) - 1);
|
|
57
|
+
longest.holder[longest.key] = `${cutText(longest.value, kept)}${CUT}`;
|
|
58
|
+
size = JSON.stringify(bounded).length;
|
|
59
|
+
}
|
|
60
|
+
return bounded;
|
|
61
|
+
}
|
|
62
|
+
const FILE_BOUNDS = {
|
|
63
|
+
files: 50,
|
|
64
|
+
id: 256,
|
|
65
|
+
name: 1024,
|
|
66
|
+
type: 255
|
|
67
|
+
};
|
|
68
|
+
function storedFiles(attachments) {
|
|
69
|
+
return attachments.filter((file) => file.id !== "" && file.id.length <= FILE_BOUNDS.id).slice(0, FILE_BOUNDS.files).map((file) => {
|
|
70
|
+
const name = bounded(file.filename, FILE_BOUNDS.name);
|
|
71
|
+
const type = bounded(file.contentType, FILE_BOUNDS.type);
|
|
72
|
+
return {
|
|
73
|
+
id: file.id,
|
|
74
|
+
...name === void 0 ? {} : { name },
|
|
75
|
+
...type === void 0 ? {} : { type },
|
|
76
|
+
...file.size !== void 0 && Number.isSafeInteger(file.size) && file.size >= 0 ? { size: file.size } : {}
|
|
77
|
+
};
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
function object(value) {
|
|
81
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
82
|
+
}
|
|
83
|
+
function metaOf(event) {
|
|
84
|
+
let summary;
|
|
85
|
+
try {
|
|
86
|
+
summary = object(JSON.parse(event.argsSummary ?? "null"));
|
|
87
|
+
} catch {
|
|
88
|
+
summary = void 0;
|
|
89
|
+
}
|
|
90
|
+
const meta = {
|
|
91
|
+
...summary,
|
|
92
|
+
...event.attachments.length === 0 ? {} : { attachments: event.attachments }
|
|
93
|
+
};
|
|
94
|
+
return Object.keys(meta).length === 0 ? void 0 : meta;
|
|
95
|
+
}
|
|
96
|
+
const PRIVATE_KEYS = new Set([
|
|
97
|
+
"attachments",
|
|
98
|
+
"fences",
|
|
99
|
+
"held",
|
|
100
|
+
"previous"
|
|
101
|
+
]);
|
|
102
|
+
function storedMessageId(event) {
|
|
103
|
+
return (event.messageId ?? event.eventId).slice(0, BOUNDS.id);
|
|
104
|
+
}
|
|
105
|
+
function messageInput(event) {
|
|
106
|
+
const author = event.kind === "inbound" ? event.senderIsBot ? "bot" : "human" : chatAuthor(event);
|
|
107
|
+
const senderId = author === "agent" ? void 0 : bounded(event.senderId, BOUNDS.sender);
|
|
108
|
+
const senderName = author === "agent" ? void 0 : bounded(event.senderName, BOUNDS.name);
|
|
109
|
+
const threadId = bounded(event.threadId, BOUNDS.chat);
|
|
110
|
+
const replyTo = bounded(event.replyToMessageId, BOUNDS.id);
|
|
111
|
+
const text = bounded(event.text, BOUNDS.text);
|
|
112
|
+
const meta = boundedMeta(metaOf(event));
|
|
113
|
+
return {
|
|
114
|
+
channel: event.provider,
|
|
115
|
+
chatId: event.chatId.slice(0, BOUNDS.chat),
|
|
116
|
+
...threadId === void 0 ? {} : { threadId },
|
|
117
|
+
chatType: event.chatType,
|
|
118
|
+
participants: event.participantIds.filter((id) => UUID.test(id)),
|
|
119
|
+
direction: event.kind === "inbound" ? "inbound" : "outbound",
|
|
120
|
+
author,
|
|
121
|
+
...senderId === void 0 ? {} : { senderId },
|
|
122
|
+
...senderName === void 0 ? {} : { senderName },
|
|
123
|
+
...event.userId == null || !UUID.test(event.userId) ? {} : { userId: event.userId },
|
|
124
|
+
messageId: storedMessageId(event),
|
|
125
|
+
...replyTo === void 0 ? {} : { replyTo },
|
|
126
|
+
...text === void 0 ? {} : { text },
|
|
127
|
+
at: event.at,
|
|
128
|
+
...event.kind === "outbound" ? { status: storedStatus(event.status) } : {},
|
|
129
|
+
...event.sessionId === null ? {} : { sessionId: event.sessionId.slice(0, BOUNDS.id) },
|
|
130
|
+
...event.turnId === null ? {} : { turnId: event.turnId.slice(0, BOUNDS.id) },
|
|
131
|
+
...meta === void 0 ? {} : { meta }
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
function storedStatus(status) {
|
|
135
|
+
switch (status) {
|
|
136
|
+
case "requested": return "pending";
|
|
137
|
+
case "failed":
|
|
138
|
+
case "rejected":
|
|
139
|
+
case "cancelled": return "failed";
|
|
140
|
+
case "unknown":
|
|
141
|
+
case "uncertain": return "uncertain";
|
|
142
|
+
default: return "sent";
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
function sendFingerprint(input) {
|
|
146
|
+
return createHash("sha256").update(JSON.stringify([
|
|
147
|
+
input.operation,
|
|
148
|
+
input.chatId,
|
|
149
|
+
input.threadId,
|
|
150
|
+
input.text
|
|
151
|
+
])).digest("hex");
|
|
152
|
+
}
|
|
153
|
+
function eventOf(row) {
|
|
154
|
+
const meta = row.deletedAt === null ? object(row.meta) : void 0;
|
|
155
|
+
const summary = meta === void 0 ? null : JSON.stringify(Object.fromEntries(Object.entries(meta).filter(([key]) => !PRIVATE_KEYS.has(key))));
|
|
156
|
+
const references = Array.isArray(meta?.attachments) ? meta.attachments : row.files.map((file) => ({
|
|
157
|
+
id: file.id,
|
|
158
|
+
kind: "file",
|
|
159
|
+
...file.name === void 0 ? {} : { filename: file.name },
|
|
160
|
+
...file.type === void 0 ? {} : { contentType: file.type },
|
|
161
|
+
...file.size === void 0 ? {} : { size: file.size }
|
|
162
|
+
}));
|
|
163
|
+
const agent = row.author === "agent";
|
|
164
|
+
const retained = object(meta?.routing)?.retainedText;
|
|
165
|
+
return {
|
|
166
|
+
eventId: row.id,
|
|
167
|
+
provider: row.channel,
|
|
168
|
+
chatId: row.chatId,
|
|
169
|
+
chatType: row.chatType,
|
|
170
|
+
threadId: row.threadId,
|
|
171
|
+
participantIds: row.participants,
|
|
172
|
+
senderId: agent ? AGENT_SENDER : row.senderId,
|
|
173
|
+
senderName: agent ? row.senderName ?? "agent" : row.senderName,
|
|
174
|
+
senderIsBot: row.author !== "human",
|
|
175
|
+
kind: row.direction === "inbound" ? "inbound" : "outbound",
|
|
176
|
+
messageId: row.messageId,
|
|
177
|
+
replyToMessageId: row.replyTo,
|
|
178
|
+
sessionId: row.sessionId,
|
|
179
|
+
turnId: row.turnId,
|
|
180
|
+
text: typeof retained === "string" ? retained : row.text,
|
|
181
|
+
decision: null,
|
|
182
|
+
reason: row.reason,
|
|
183
|
+
toolCallId: null,
|
|
184
|
+
toolName: null,
|
|
185
|
+
argsSummary: summary,
|
|
186
|
+
status: row.direction === "inbound" ? null : row.status === "pending" ? "requested" : row.status === "failed" ? "failed" : row.status === "uncertain" ? "uncertain" : "sent",
|
|
187
|
+
operationId: row.operation,
|
|
188
|
+
attachments: references,
|
|
189
|
+
at: row.at,
|
|
190
|
+
disposition: row.disposition,
|
|
191
|
+
userId: row.userId,
|
|
192
|
+
edited: row.editedAt !== null,
|
|
193
|
+
deleted: row.deletedAt !== null,
|
|
194
|
+
sequence: row.revision,
|
|
195
|
+
storedAt: row.at
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
const CONTEXT_PAGES = 5;
|
|
199
|
+
function shown(row) {
|
|
200
|
+
return row.direction === "inbound" || row.direction === "outbound" && (row.status === null || [
|
|
201
|
+
"sent",
|
|
202
|
+
"delivered",
|
|
203
|
+
"read"
|
|
204
|
+
].includes(row.status));
|
|
205
|
+
}
|
|
206
|
+
function workspaceChatArchive(store) {
|
|
207
|
+
async function receipt(event, operation) {
|
|
208
|
+
if (event.status === "requested") try {
|
|
209
|
+
return (await store.record({
|
|
210
|
+
...messageInput(event),
|
|
211
|
+
messageId: void 0,
|
|
212
|
+
status: "pending",
|
|
213
|
+
operation,
|
|
214
|
+
fingerprint: sendFingerprint({
|
|
215
|
+
operation,
|
|
216
|
+
...event
|
|
217
|
+
})
|
|
218
|
+
})).first;
|
|
219
|
+
} catch (error) {
|
|
220
|
+
if (error instanceof ChatStoreError && error.code === "operation_conflict") return false;
|
|
221
|
+
throw error;
|
|
222
|
+
}
|
|
223
|
+
const status = storedStatus(event.status);
|
|
224
|
+
const failure = status === "failed" ? reasonCode(event.reason) : void 0;
|
|
225
|
+
const { applied } = await store.change({
|
|
226
|
+
change: "sent",
|
|
227
|
+
channel: event.provider,
|
|
228
|
+
chatId: event.chatId,
|
|
229
|
+
operation,
|
|
230
|
+
status: status === "failed" ? "failed" : status === "uncertain" ? "uncertain" : "sent",
|
|
231
|
+
...event.messageId === null ? {} : { providerMessageId: event.messageId },
|
|
232
|
+
...failure === void 0 ? {} : { failure }
|
|
233
|
+
});
|
|
234
|
+
return applied;
|
|
235
|
+
}
|
|
236
|
+
return {
|
|
237
|
+
store: async () => store,
|
|
238
|
+
append: async (event) => {
|
|
239
|
+
if (event.kind === "outbound" && event.operationId != null) return receipt(event, event.operationId);
|
|
240
|
+
if (event.kind !== "inbound" && event.kind !== "outbound") return false;
|
|
241
|
+
if (event.kind === "outbound" && chatAuthor(event) === "agent" && event.messageId !== null) {
|
|
242
|
+
const operation = `sent:${event.provider}:${event.chatId}:${event.messageId}`.slice(0, 512);
|
|
243
|
+
const sent = await receipt({
|
|
244
|
+
...event,
|
|
245
|
+
status: "requested"
|
|
246
|
+
}, operation);
|
|
247
|
+
try {
|
|
248
|
+
await receipt({
|
|
249
|
+
...event,
|
|
250
|
+
status: event.status === "requested" ? "uncertain" : event.status
|
|
251
|
+
}, operation);
|
|
252
|
+
} catch (error) {
|
|
253
|
+
if (error instanceof ChatStoreError && error.code === "message_conflict") {
|
|
254
|
+
await store.change({
|
|
255
|
+
change: "sent",
|
|
256
|
+
channel: event.provider,
|
|
257
|
+
chatId: event.chatId,
|
|
258
|
+
operation,
|
|
259
|
+
status: "failed",
|
|
260
|
+
failure: "duplicate"
|
|
261
|
+
});
|
|
262
|
+
return false;
|
|
263
|
+
}
|
|
264
|
+
throw error;
|
|
265
|
+
}
|
|
266
|
+
return sent;
|
|
267
|
+
}
|
|
268
|
+
return (await store.record(messageInput(event))).first;
|
|
269
|
+
},
|
|
270
|
+
context: async ({ includeDecisions, signal, ...search }) => {
|
|
271
|
+
const limit = Math.min(search.limit ?? 50, 200);
|
|
272
|
+
const from = search.from === void 0 ? void 0 : Date.parse(search.from);
|
|
273
|
+
const kept = [];
|
|
274
|
+
let before = search.before;
|
|
275
|
+
let more = true;
|
|
276
|
+
let examined;
|
|
277
|
+
for (let page = 0; page < CONTEXT_PAGES && more && kept.length < limit; page += 1) {
|
|
278
|
+
const read = await store.read({
|
|
279
|
+
channel: search.provider,
|
|
280
|
+
chatId: search.chatId,
|
|
281
|
+
...search.threadId === void 0 ? {} : { threadId: search.threadId },
|
|
282
|
+
...before === void 0 ? {} : { before },
|
|
283
|
+
...search.messageId === void 0 ? {} : { messageId: search.messageId },
|
|
284
|
+
limit
|
|
285
|
+
}, signal);
|
|
286
|
+
let rest = false;
|
|
287
|
+
for (const row of read.messages) {
|
|
288
|
+
if (kept.length === limit) {
|
|
289
|
+
rest = true;
|
|
290
|
+
break;
|
|
291
|
+
}
|
|
292
|
+
examined = row;
|
|
293
|
+
if (row.direction !== "internal" && (includeDecisions === true || shown(row)) && (search.senderId === void 0 || row.senderId === search.senderId) && (from === void 0 || Date.parse(row.at) >= from)) kept.push(row);
|
|
294
|
+
}
|
|
295
|
+
more = rest || read.nextCursor !== null;
|
|
296
|
+
before = read.nextCursor ?? void 0;
|
|
297
|
+
}
|
|
298
|
+
return {
|
|
299
|
+
events: kept.map(eventOf),
|
|
300
|
+
nextCursor: !more || examined === void 0 ? null : `${examined.at}~${examined.id}`
|
|
301
|
+
};
|
|
302
|
+
},
|
|
303
|
+
changes: async ({ provider, chatId, threadId, after, limit, signal }) => {
|
|
304
|
+
const page = await store.read({
|
|
305
|
+
channel: provider,
|
|
306
|
+
chatId,
|
|
307
|
+
...threadId === void 0 ? {} : { threadId },
|
|
308
|
+
after,
|
|
309
|
+
limit: Math.min(limit ?? 100, 200)
|
|
310
|
+
}, signal);
|
|
311
|
+
return {
|
|
312
|
+
events: page.messages.filter((row) => row.direction !== "internal" && (row.replacedBy ?? null) === null).map(eventOf),
|
|
313
|
+
nextCursor: page.nextCursor
|
|
314
|
+
};
|
|
315
|
+
},
|
|
316
|
+
pendingReplies: async ({ provider, limit, requestedBefore }) => {
|
|
317
|
+
const page = await store.read({
|
|
318
|
+
channel: provider,
|
|
319
|
+
pending: true,
|
|
320
|
+
...requestedBefore === void 0 ? {} : { pendingBefore: requestedBefore },
|
|
321
|
+
limit: Math.min(limit, 200)
|
|
322
|
+
});
|
|
323
|
+
return {
|
|
324
|
+
events: page.messages.map(eventOf),
|
|
325
|
+
nextCursor: page.nextCursor
|
|
326
|
+
};
|
|
327
|
+
},
|
|
328
|
+
lastChat: async ({ provider, senderId, participantId }) => {
|
|
329
|
+
const [latest] = (await store.read({
|
|
330
|
+
channel: provider,
|
|
331
|
+
senderId,
|
|
332
|
+
limit: 1
|
|
333
|
+
})).messages;
|
|
334
|
+
return latest !== void 0 && latest.participants.includes(participantId) ? latest.chatId : void 0;
|
|
335
|
+
}
|
|
336
|
+
};
|
|
337
|
+
}
|
|
338
|
+
async function storeOf(archive) {
|
|
339
|
+
return archive.store === void 0 ? void 0 : archive.store();
|
|
340
|
+
}
|
|
341
|
+
function replyOperation(key) {
|
|
342
|
+
return `reply:${key}`;
|
|
343
|
+
}
|
|
344
|
+
function replyEvent(input) {
|
|
345
|
+
const kind = input.kind ?? input.provider;
|
|
346
|
+
return chatEvent({
|
|
347
|
+
eventId: channelKey(kind, input.provider, `${kind}:reply:${input.key}:${input.status}`),
|
|
348
|
+
operationId: replyOperation(input.key),
|
|
349
|
+
provider: input.provider,
|
|
350
|
+
chatId: input.chatId,
|
|
351
|
+
chatType: "private",
|
|
352
|
+
threadId: input.threadId,
|
|
353
|
+
participantIds: input.participantIds,
|
|
354
|
+
sessionId: input.sessionId,
|
|
355
|
+
turnId: input.turnId,
|
|
356
|
+
kind: "outbound",
|
|
357
|
+
text: input.text,
|
|
358
|
+
senderId: AGENT_SENDER,
|
|
359
|
+
senderIsBot: true,
|
|
360
|
+
status: input.status,
|
|
361
|
+
messageId: input.messageId ?? null,
|
|
362
|
+
...input.at === void 0 ? {} : { at: input.at }
|
|
363
|
+
});
|
|
364
|
+
}
|
|
365
|
+
const TOPIC_PAGES = 5;
|
|
366
|
+
const TOPIC_PAGE_SIZE = 100;
|
|
367
|
+
async function topicContext(archive, input) {
|
|
368
|
+
const { threadId, ...search } = input;
|
|
369
|
+
if (threadId !== null) return archive.context({
|
|
370
|
+
...search,
|
|
371
|
+
threadId
|
|
372
|
+
});
|
|
373
|
+
const limit = search.limit ?? 50;
|
|
374
|
+
const events = [];
|
|
375
|
+
let before = search.before;
|
|
376
|
+
let page;
|
|
377
|
+
for (let scanned = 0; scanned < TOPIC_PAGES; scanned += 1) {
|
|
378
|
+
page = await archive.context({
|
|
379
|
+
...search,
|
|
380
|
+
limit: Math.max(limit, TOPIC_PAGE_SIZE),
|
|
381
|
+
...before === void 0 ? {} : { before }
|
|
382
|
+
});
|
|
383
|
+
events.push(...page.events.filter((event) => event.threadId === null));
|
|
384
|
+
if (page.nextCursor === null || events.length >= limit) break;
|
|
385
|
+
before = page.nextCursor;
|
|
386
|
+
}
|
|
387
|
+
return {
|
|
388
|
+
...page,
|
|
389
|
+
events
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
function isTelegramMessage(event) {
|
|
393
|
+
return event.provider === "telegram" || event.eventId.startsWith(channelKey("telegram", event.provider, "telegram:"));
|
|
394
|
+
}
|
|
395
|
+
const AGENT_SENDER = "agent";
|
|
396
|
+
function chatAuthor(event) {
|
|
397
|
+
return !event.senderIsBot ? "human" : event.kind === "outbound" && event.senderId === "agent" ? "agent" : "bot";
|
|
398
|
+
}
|
|
399
|
+
function archiveSequence(value) {
|
|
400
|
+
return /^-?\d+$/u.test(value) ? BigInt(value) : void 0;
|
|
401
|
+
}
|
|
402
|
+
function collapseChatEvents(events) {
|
|
403
|
+
const latest = new Map();
|
|
404
|
+
for (const event of events) {
|
|
405
|
+
const key = event.kind === "outbound" && event.operationId != null ? `chat-delivery:${event.operationId}` : event.kind === "inbound" && isTelegramMessage(event) && event.messageId !== null ? channelKey("telegram", event.provider, `telegram:${event.chatId}:${event.messageId}:message`) : event.kind === "outbound" && /^telegram:(send|edit):/u.test(event.eventId) ? event.eventId.replace(/:result$/u, "") : event.eventId;
|
|
406
|
+
const previous = latest.get(key);
|
|
407
|
+
const current = archiveSequence(event.sequence);
|
|
408
|
+
const earlier = previous === void 0 ? void 0 : archiveSequence(previous.sequence);
|
|
409
|
+
if (previous === void 0 || (current !== void 0 && earlier !== void 0 ? current > earlier : event.storedAt > previous.storedAt)) latest.set(key, {
|
|
410
|
+
...event,
|
|
411
|
+
eventId: key,
|
|
412
|
+
...event.kind === "outbound" && event.operationId != null && event.status === "requested" ? { status: "uncertain" } : {}
|
|
413
|
+
});
|
|
414
|
+
}
|
|
415
|
+
return [...latest.values()];
|
|
416
|
+
}
|
|
417
|
+
function sessionFailureEventId(sessionId) {
|
|
418
|
+
return `eve:${sessionId}:session.failed`;
|
|
419
|
+
}
|
|
420
|
+
function chatEvent(input) {
|
|
421
|
+
return workflowValue({
|
|
422
|
+
threadId: null,
|
|
423
|
+
participantIds: [],
|
|
424
|
+
senderId: null,
|
|
425
|
+
senderName: null,
|
|
426
|
+
senderIsBot: false,
|
|
427
|
+
messageId: null,
|
|
428
|
+
replyToMessageId: null,
|
|
429
|
+
sessionId: null,
|
|
430
|
+
turnId: null,
|
|
431
|
+
text: null,
|
|
432
|
+
decision: null,
|
|
433
|
+
reason: null,
|
|
434
|
+
toolCallId: null,
|
|
435
|
+
toolName: null,
|
|
436
|
+
argsSummary: null,
|
|
437
|
+
status: null,
|
|
438
|
+
attachments: [],
|
|
439
|
+
at: new Date().toISOString(),
|
|
440
|
+
...input
|
|
441
|
+
}, {
|
|
442
|
+
boundary: "SDK chat event",
|
|
443
|
+
eventType: input.kind,
|
|
444
|
+
toolName: input.toolName ?? void 0,
|
|
445
|
+
toolCallId: input.toolCallId ?? void 0
|
|
446
|
+
});
|
|
447
|
+
}
|
|
448
|
+
const stores = new WeakMap();
|
|
449
|
+
function forgetChatStores(fetchImpl = fetch) {
|
|
450
|
+
stores.delete(fetchImpl);
|
|
451
|
+
}
|
|
452
|
+
function chatArchive(input = {}) {
|
|
453
|
+
const environment = input.environment ?? process.env;
|
|
454
|
+
const token = input.token ?? runtimeToken;
|
|
455
|
+
const fetchImpl = input.fetch ?? fetch;
|
|
456
|
+
let workspace;
|
|
457
|
+
let cloud;
|
|
458
|
+
async function selected() {
|
|
459
|
+
let origins = stores.get(fetchImpl);
|
|
460
|
+
if (origins === void 0) {
|
|
461
|
+
origins = new Map();
|
|
462
|
+
stores.set(fetchImpl, origins);
|
|
463
|
+
}
|
|
464
|
+
let origin;
|
|
465
|
+
try {
|
|
466
|
+
origin = appOrigin(environment);
|
|
467
|
+
} catch {
|
|
468
|
+
origin = "";
|
|
469
|
+
}
|
|
470
|
+
let available = origins.get(origin);
|
|
471
|
+
if (available === void 0) {
|
|
472
|
+
const asked = storeAvailable({
|
|
473
|
+
environment,
|
|
474
|
+
token,
|
|
475
|
+
fetch: fetchImpl
|
|
476
|
+
});
|
|
477
|
+
available = asked;
|
|
478
|
+
origins.set(origin, asked);
|
|
479
|
+
asked.catch(() => {
|
|
480
|
+
if (origins.get(origin) === asked) origins.delete(origin);
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
if (await available) return workspace ??= workspaceChatArchive(chatStore({
|
|
484
|
+
environment,
|
|
485
|
+
token,
|
|
486
|
+
fetch: fetchImpl
|
|
487
|
+
}));
|
|
488
|
+
return cloud ??= cloudChatArchive(input);
|
|
489
|
+
}
|
|
490
|
+
return {
|
|
491
|
+
append: async (event) => (await selected()).append(event),
|
|
492
|
+
context: async (search) => (await selected()).context(search),
|
|
493
|
+
pendingReplies: async (search) => {
|
|
494
|
+
const archive = await selected();
|
|
495
|
+
return archive.pendingReplies === void 0 ? {
|
|
496
|
+
events: [],
|
|
497
|
+
nextCursor: null
|
|
498
|
+
} : archive.pendingReplies(search);
|
|
499
|
+
},
|
|
500
|
+
lastChat: async (search) => (await selected()).lastChat?.(search),
|
|
501
|
+
store: async () => storeOf(await selected()),
|
|
502
|
+
changes: async (search) => {
|
|
503
|
+
const archive = await selected();
|
|
504
|
+
if (archive.changes === void 0) throw new Error("The chat archive in Cloud has no change feed.");
|
|
505
|
+
return archive.changes(search);
|
|
506
|
+
}
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
function cloudChatArchive(input = {}) {
|
|
510
|
+
const environment = input.environment ?? process.env;
|
|
511
|
+
const token = input.token ?? runtimeToken;
|
|
512
|
+
const fetchImpl = input.fetch ?? fetch;
|
|
513
|
+
async function call(path, body, signal) {
|
|
514
|
+
const env = proxyEnvironment(environment);
|
|
515
|
+
const identity = await token();
|
|
516
|
+
const base = `${env.segmentstreamUrl}/api/internal/v1/workspaces/${encodeURIComponent(env.workspaceId)}`;
|
|
517
|
+
const response = await fetchImpl(`${base}/agent/chats/${path}`, {
|
|
518
|
+
method: "POST",
|
|
519
|
+
redirect: "error",
|
|
520
|
+
headers: {
|
|
521
|
+
"content-type": "application/json",
|
|
522
|
+
"x-segmentstream-organization-id": env.organizationId,
|
|
523
|
+
"x-segmentstream-runtime-identity": identity
|
|
524
|
+
},
|
|
525
|
+
body: JSON.stringify(workflowValue(body, { boundary: "chat archive" })),
|
|
526
|
+
signal: signal === void 0 ? AbortSignal.timeout(15e3) : AbortSignal.any([signal, AbortSignal.timeout(15e3)])
|
|
527
|
+
});
|
|
528
|
+
if (!response.ok) throw new Error(`Chat archive ${path} failed (${response.status}); request ${response.headers.get("x-request-id") ?? "unknown"}.`);
|
|
529
|
+
return response.json();
|
|
530
|
+
}
|
|
531
|
+
return {
|
|
532
|
+
append: async (event) => {
|
|
533
|
+
return (await call("events", event)).stored;
|
|
534
|
+
},
|
|
535
|
+
context: async ({ includeDecisions, participantId, signal, ...search }) => await call("search", {
|
|
536
|
+
search,
|
|
537
|
+
context: !includeDecisions,
|
|
538
|
+
reader: {
|
|
539
|
+
participantId: participantId ?? null,
|
|
540
|
+
groups: includeDecisions === true,
|
|
541
|
+
admin: false
|
|
542
|
+
}
|
|
543
|
+
}, signal),
|
|
544
|
+
lastChat: async ({ provider, senderId, participantId }) => {
|
|
545
|
+
return (await call("search", {
|
|
546
|
+
search: {
|
|
547
|
+
provider,
|
|
548
|
+
senderId,
|
|
549
|
+
messagesOnly: true,
|
|
550
|
+
limit: 1
|
|
551
|
+
},
|
|
552
|
+
reader: {
|
|
553
|
+
participantId,
|
|
554
|
+
groups: false,
|
|
555
|
+
admin: false
|
|
556
|
+
}
|
|
557
|
+
})).events[0]?.chatId;
|
|
558
|
+
},
|
|
559
|
+
pendingReplies: async ({ provider, limit, requestedBefore }) => await call("search", {
|
|
560
|
+
search: {
|
|
561
|
+
provider,
|
|
562
|
+
pending: true,
|
|
563
|
+
limit,
|
|
564
|
+
...requestedBefore === void 0 ? {} : { to: requestedBefore }
|
|
565
|
+
},
|
|
566
|
+
reader: {
|
|
567
|
+
participantId: null,
|
|
568
|
+
groups: false,
|
|
569
|
+
admin: false
|
|
570
|
+
}
|
|
571
|
+
})
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
function summarizeArguments(value) {
|
|
575
|
+
const sensitive = /token|password|secret|authorization|cookie|credential|api.?key|bytes|base64/i;
|
|
576
|
+
const visit = (item, depth) => {
|
|
577
|
+
if (depth > 4) return "[nested]";
|
|
578
|
+
if (item instanceof Uint8Array || typeof item === "string" && /^data:/iu.test(item)) return "[binary data]";
|
|
579
|
+
if (Array.isArray(item)) return item.slice(0, 20).map((entry) => visit(entry, depth + 1));
|
|
580
|
+
if (item !== null && typeof item === "object") return Object.fromEntries(Object.entries(item).slice(0, 30).map(([key, entry]) => [key, sensitive.test(key) ? "[redacted]" : visit(entry, depth + 1)]));
|
|
581
|
+
return typeof item === "string" ? item.replace(/(https?:\/\/)[^/@\s]+:[^/@\s]+@/gu, "$1[redacted]@").replace(/([?&](?:token|access_token|api_key|signature|secret|password)=)[^&#\s]*/giu, "$1[redacted]").replace(/\bBearer [A-Za-z0-9_.~+/-]+=*/giu, "Bearer [redacted]").slice(0, 500) : item;
|
|
582
|
+
};
|
|
583
|
+
return JSON.stringify(workflowValue(visit(value, 0), { boundary: "chat arguments" })).slice(0, 4e3);
|
|
584
|
+
}
|
|
585
|
+
export { storedMessageId as C, storedFiles as S, eventOf as _, chatEvent as a, reasonCode as b, forgetChatStores as c, sessionFailureEventId as d, storeOf as f, cutText as g, boundedMeta as h, chatAuthor as i, replyEvent as l, topicContext as m, archiveSequence as n, cloudChatArchive as o, summarizeArguments as p, chatArchive as r, collapseChatEvents as s, AGENT_SENDER as t, replyOperation as u, messageInput as v, workspaceChatArchive as w, sendFingerprint as x, metaOf as y };
|