@segmentstream/agent 0.73.1 → 0.74.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.
Files changed (43) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/dist/_chunks/{build-metadata-B-1ohlK8.mjs → build-metadata-Cq9R60V5.mjs} +1 -1
  3. package/dist/_chunks/{chat-archive-BCPLSZeK.mjs → chat-archive-BgxTGPKZ.mjs} +4 -1
  4. package/dist/_chunks/{chat-archive-DK7uCgff.mjs → chat-archive-oJWmk8wm.mjs} +1 -1
  5. package/dist/extension/extension.d.ts +1 -1
  6. package/dist/extension/hooks/chat-context.mjs +1 -1
  7. package/dist/extension/hooks/chat-recorder.mjs +1 -1
  8. package/dist/extension/lib/build-metadata.mjs +1 -1
  9. package/dist/extension/lib/chat-archive.d.ts +6 -1
  10. package/dist/extension/lib/chat-archive.mjs +1 -1
  11. package/dist/extension/lib/chat-context.mjs +1 -1
  12. package/dist/extension/lib/chat-messages.d.ts +102 -0
  13. package/dist/extension/lib/chat-messages.mjs +168 -4
  14. package/dist/extension/lib/chat-recorder.mjs +44 -13
  15. package/dist/extension/lib/chat-store.d.ts +23 -1
  16. package/dist/extension/lib/email/channel.mjs +1 -1
  17. package/dist/extension/lib/group-routing/routing-context.mjs +1 -1
  18. package/dist/extension/lib/model-service-alert.mjs +1 -1
  19. package/dist/extension/lib/review/judge.mjs +1 -1
  20. package/dist/extension/lib/review/reply.mjs +1 -1
  21. package/dist/extension/lib/review/revision-channel.mjs +1 -1
  22. package/dist/extension/lib/slack/adapter.mjs +1 -1
  23. package/dist/extension/lib/telegram/adapter.mjs +3 -3
  24. package/dist/extension/lib/telegram/chat-archive.mjs +1 -1
  25. package/dist/extension/lib/telegram/confirmations.mjs +1 -1
  26. package/dist/extension/lib/telegram/delivery-diagnostics.mjs +1 -1
  27. package/dist/extension/lib/telegram/health.mjs +1 -1
  28. package/dist/extension/lib/telegram/inbound.mjs +1 -1
  29. package/dist/extension/lib/telegram/lifecycle.mjs +1 -1
  30. package/dist/extension/lib/telegram/store-capture.mjs +1 -1
  31. package/dist/extension/lib/telegram/turn-errors.mjs +1 -1
  32. package/dist/extension/lib/whatsapp/adapter.d.ts +21 -1
  33. package/dist/extension/lib/whatsapp/adapter.mjs +82 -13
  34. package/dist/extension/lib/whatsapp/attachments-send.mjs +1 -1
  35. package/dist/extension/lib/whatsapp/changes.d.ts +46 -0
  36. package/dist/extension/lib/whatsapp/changes.mjs +212 -0
  37. package/dist/extension/lib/whatsapp/sent.mjs +1 -1
  38. package/dist/extension/lib/whatsapp/statuses.d.ts +9 -0
  39. package/dist/extension/lib/whatsapp/statuses.mjs +9 -0
  40. package/dist/extension/lib/workspace-channel/channel.d.ts +68 -7
  41. package/dist/extension/lib/workspace-channel/channel.mjs +149 -33
  42. package/dist/extension/lib/workspace-chat-archive.mjs +1 -1
  43. package/package.json +2 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,37 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.74.0
4
+
5
+ A chat keeps what providers report of its messages beside new ones, on an agent whose ontology
6
+ keeps the workspace chat store. No change starts a turn, and a change to a message the chat does
7
+ not hold changes nothing.
8
+
9
+ - A workspace channel's `parse` returns events (`ChannelEvent`): messages as before, which may now
10
+ carry `replyTo` (the message they quote), `at` and `parts` (`ChatPart`: a location or a contact
11
+ card), and changes to earlier messages, each naming its message by the provider's id in
12
+ `target`: `{ type: "reaction", chatId, sender, target, emoji }` (an empty emoji removes the
13
+ sender's), `{ type: "edit", chatId, target, text, at? }`, `{ type: "deletion", chatId, target,
14
+ at? }` and `{ type: "status", chatId, target, status: "delivered" | "read" | "failed", reason? }`.
15
+ A parse that returns plain messages keeps working. A message's `text` may be empty when it has
16
+ files or parts; one whose only content is a part joins the chat and starts no turn. The 50
17
+ messages a delivery or a read may hold count messages only. Webhooks and polls carry both.
18
+ - The channel records each person's message by the provider's id, with what it quotes, its parts,
19
+ its time and the files it stored, so a later reaction, edit or deletion finds it.
20
+ - WhatsApp keeps Meta's delivery statuses on the messages the number sent (`delivered`, `read`, or
21
+ `failed` with Meta's refusal as a code such as `recipient_unreachable`), people's reactions, the
22
+ message a person quotes, a location's place, and a contact card, which joins the chat without a
23
+ turn. On a number in Coexistence with the WhatsApp Business app it keeps a person's edits and
24
+ deletions, and the business's own from the app. Once it kept a delivery's statuses, the channel
25
+ says so to SegmentStream, which then records the failure nowhere else.
26
+
27
+ An agent whose ontology keeps no chat store records none of these and works as before.
28
+
29
+ Pins @segmentstream/ontology 0.150.2.
30
+
31
+ ## 0.73.2
32
+
33
+ Pins @segmentstream/ontology 0.150.1.
34
+
3
35
  ## 0.73.1
4
36
 
5
37
  A file sent with `segmentstream__attachments_send` to Telegram keeps its caption's links and
@@ -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.73.1";
7
+ var version = "0.74.0";
8
8
  function agentBuild(environment = process.env) {
9
9
  return {
10
10
  agent: version,
@@ -95,6 +95,7 @@ function metaOf(event) {
95
95
  }
96
96
  const PRIVATE_KEYS = new Set([
97
97
  "attachments",
98
+ "delivery",
98
99
  "fences",
99
100
  "held",
100
101
  "previous"
@@ -124,6 +125,7 @@ function messageInput(event) {
124
125
  messageId: storedMessageId(event),
125
126
  ...replyTo === void 0 ? {} : { replyTo },
126
127
  ...text === void 0 ? {} : { text },
128
+ ...event.parts === void 0 || event.parts.length === 0 ? {} : { parts: event.parts.slice(0, 20) },
127
129
  at: event.at,
128
130
  ...event.kind === "outbound" ? { status: storedStatus(event.status) } : {},
129
131
  ...event.sessionId === null ? {} : { sessionId: event.sessionId.slice(0, BOUNDS.id) },
@@ -530,7 +532,8 @@ function cloudChatArchive(input = {}) {
530
532
  }
531
533
  return {
532
534
  append: async (event) => {
533
- return (await call("events", event)).stored;
535
+ const { parts, ...archived } = event;
536
+ return (await call("events", archived)).stored;
534
537
  },
535
538
  context: async ({ includeDecisions, participantId, signal, ...search }) => await call("search", {
536
539
  search,
@@ -7,7 +7,7 @@ __eveCreateRequire(import.meta.url);
7
7
  import { parseArchivedMessage } from "../extension/lib/telegram/archive-message.mjs";
8
8
  import { currentChannel, currentKey } from "../extension/lib/channel-scope.mjs";
9
9
  import { n as contentText, t as CONTENT_CAPS } from "./content-cDtVnr8Y.mjs";
10
- import { S as storedFiles, a as chatEvent, b as reasonCode, d as sessionFailureEventId, f as storeOf, g as cutText, h as boundedMeta, v as messageInput, x as sendFingerprint, y as metaOf } from "./chat-archive-BCPLSZeK.mjs";
10
+ import { S as storedFiles, a as chatEvent, b as reasonCode, d as sessionFailureEventId, f as storeOf, g as cutText, h as boundedMeta, v as messageInput, x as sendFingerprint, y as metaOf } from "./chat-archive-BgxTGPKZ.mjs";
11
11
  import { ChatStoreError } from "../extension/lib/chat-store.mjs";
12
12
  import { c as currentInboundRequest, ht as currentThreadId, xt as reportTelegramError } from "./principal-Zf42Yf4r.mjs";
13
13
  import { currentConfirmationPrompt } from "../extension/lib/group-routing/messages.mjs";
@@ -30,7 +30,7 @@ export { DEFAULT_DECISION_MODEL, DEFAULT_STT_MODEL, DEFAULT_ADMISSION_LIMITS, Se
30
30
  * Defines a channel in the workspace's own code, `agent/agent/channels/<name>.ts`, for a provider
31
31
  * the platform has no channel for: the code receives, reads and sends, the platform does the rest.
32
32
  */
33
- export { defineChannel, type ChannelChecks, type ChannelContext, type ChannelDefinition, type ChannelFile, type ChannelMessage, type ChannelRead, type ChannelReply, type ChannelReplyFile, type ChannelRequest, type ChannelSender, } from "./lib/workspace-channel/channel.js";
33
+ export { defineChannel, type ChannelChecks, type ChannelContext, type ChannelDefinition, type ChannelEvent, type ChannelFile, type ChannelMessage, type ChannelMessageEvent, type ChannelRead, type ChannelReply, type ChannelReplyFile, type ChannelRequest, type ChannelSender, type ChatPart, } from "./lib/workspace-channel/channel.js";
34
34
  export type { ChannelConnection, ChannelConnectionRequest, ChannelConnectionRequestOptions, ChannelConnectionResponse, } from "./lib/workspace-channel/connection.js";
35
35
  export { chooseModel, model, type DynamicModel, type ModelChoice } from "./model.js";
36
36
  export { forRoles } from "./lib/role-skill.js";
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import segmentstream from "../extension.mjs";
8
- import { r as chatArchive } from "../../_chunks/chat-archive-BCPLSZeK.mjs";
8
+ import { r as chatArchive } from "../../_chunks/chat-archive-BgxTGPKZ.mjs";
9
9
  import { chatContextHook } from "../lib/chat-context.mjs";
10
10
  import { appOrigin } from "../lib/environment.mjs";
11
11
  import { agentSessionReviews } from "../lib/review/client.mjs";
@@ -6,7 +6,7 @@ __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import segmentstream from "../extension.mjs";
8
8
  import { chatRecorder } from "../lib/chat-recorder.mjs";
9
- import { r as chatArchive } from "../../_chunks/chat-archive-BCPLSZeK.mjs";
9
+ import { r as chatArchive } from "../../_chunks/chat-archive-BgxTGPKZ.mjs";
10
10
  import { repliesReviewed } from "../lib/review/hold.mjs";
11
11
  import { defineHook } from "eve/hooks";
12
12
  var chat_recorder_default = defineHook({ events: { "*": chatRecorder(chatArchive(), (principal) => repliesReviewed(segmentstream.config.review, principal)) } });
@@ -4,4 +4,4 @@ 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
- export { t as agentBuild } from "../../_chunks/build-metadata-B-1ohlK8.mjs";
7
+ export { t as agentBuild } from "../../_chunks/build-metadata-Cq9R60V5.mjs";
@@ -1,4 +1,4 @@
1
- import { type ChatStore } from "./chat-store.js";
1
+ import { type ChatPart, type ChatStore } from "./chat-store.js";
2
2
  import { type Environment } from "./environment.js";
3
3
  import { type RuntimeToken } from "./runtime-token.js";
4
4
  /** Provider-neutral platform archive. Content uses the shared redaction and byte-limit policy. */
@@ -57,6 +57,11 @@ export interface ChatEvent {
57
57
  /** The message was edited, or deleted, since it was written: the store keeps its latest state. */
58
58
  readonly edited?: boolean;
59
59
  readonly deleted?: boolean;
60
+ /**
61
+ * What the message carries beside its text, such as a location: kept by the workspace chat store
62
+ * alone, never sent to the chat archive in Cloud.
63
+ */
64
+ readonly parts?: ReadonlyArray<ChatPart>;
60
65
  }
61
66
  export interface ChatPage {
62
67
  readonly events: ReadonlyArray<ChatEvent & {
@@ -4,4 +4,4 @@ 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
- export { t as AGENT_SENDER, n as archiveSequence, r as chatArchive, i as chatAuthor, a as chatEvent, o as cloudChatArchive, s as collapseChatEvents, c as forgetChatStores, l as replyEvent, u as replyOperation, d as sessionFailureEventId, f as storeOf, p as summarizeArguments, m as topicContext } from "../../_chunks/chat-archive-BCPLSZeK.mjs";
7
+ export { t as AGENT_SENDER, n as archiveSequence, r as chatArchive, i as chatAuthor, a as chatEvent, o as cloudChatArchive, s as collapseChatEvents, c as forgetChatStores, l as replyEvent, u as replyOperation, d as sessionFailureEventId, f as storeOf, p as summarizeArguments, m as topicContext } from "../../_chunks/chat-archive-BgxTGPKZ.mjs";
@@ -6,7 +6,7 @@ __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { agentTaskIdOf } from "./agent-task.mjs";
8
8
  import { chatCoordinates, sessionKind } from "./chat-recorder.mjs";
9
- import { f as storeOf, i as chatAuthor, m as topicContext, n as archiveSequence, r as chatArchive, s as collapseChatEvents } from "../../_chunks/chat-archive-BCPLSZeK.mjs";
9
+ import { f as storeOf, i as chatAuthor, m as topicContext, n as archiveSequence, r as chatArchive, s as collapseChatEvents } from "../../_chunks/chat-archive-BgxTGPKZ.mjs";
10
10
  import { xt as reportTelegramError } from "../../_chunks/principal-Zf42Yf4r.mjs";
11
11
  import { createHash } from "node:crypto";
12
12
  import { deliveries, runs, turns } from "eve/events";
@@ -1,5 +1,8 @@
1
1
  import type { AdmittedChat } from "./admission.js";
2
2
  import { type ChatArchive, type ChatAuthor } from "./chat-archive.js";
3
+ import type { ChatPart, StoredFile } from "./chat-store.js";
4
+ import type { StagedFile } from "./inbound-media/files.js";
5
+ export type { ChatPart } from "./chat-store.js";
3
6
  /**
4
7
  * Messages in a chat that start no turn (docs/agent-chat-storage.md, "Messages without a turn").
5
8
  * Every channel records them here, in one shape: the archive keeps them under the chat's
@@ -12,6 +15,91 @@ export interface RecordedFile {
12
15
  readonly mimeType?: string;
13
16
  readonly size?: number;
14
17
  }
18
+ /** The most parts one message keeps, as the store takes them. */
19
+ export declare const MAXIMUM_PARTS = 20;
20
+ /** One part as the store keeps it, or undefined for a value that is none. */
21
+ export declare function chatPart(value: unknown): ChatPart | undefined;
22
+ /** The parts of a message as the store keeps them; undefined when any of them is none. */
23
+ export declare function chatParts(value: unknown): ReadonlyArray<ChatPart> | undefined;
24
+ /** The files of a message the inbound media pipeline stored, by their attachments' ids. */
25
+ export declare function stagedFiles(files: ReadonlyMap<string, StagedFile>): ReadonlyArray<StoredFile>;
26
+ /**
27
+ * A person's message a channel recorded itself, by the provider's id of it, in the workspace chat
28
+ * store: with what the provider says of it beside its text (the message it quotes, its parts, its
29
+ * time), so that a later change to it, a reaction, an edit or a deletion, finds it.
30
+ */
31
+ export interface ReceivedMessage {
32
+ readonly channel: string;
33
+ readonly chatId: string;
34
+ /** The member who wrote it, who reads it. */
35
+ readonly memberId: string;
36
+ /** The person's account at the provider. */
37
+ readonly senderId: string;
38
+ readonly senderName?: string | null;
39
+ readonly messageId: string;
40
+ readonly replyTo?: string;
41
+ /** The text the agent read of it: its text, and what was transcribed of its speech. */
42
+ readonly text: string;
43
+ readonly parts?: ReadonlyArray<ChatPart>;
44
+ /** Its files as they were stored, by their attachments' ids. */
45
+ readonly files?: ReadonlyArray<StoredFile>;
46
+ /** When it was written, if not now. */
47
+ readonly at?: string;
48
+ /**
49
+ * What the agent did with it: the turn eve's inbox took it into, by the delivery the session
50
+ * received, or the reason it started none.
51
+ */
52
+ readonly outcome: {
53
+ readonly turn: {
54
+ readonly sessionId: string;
55
+ readonly deliveryId: string;
56
+ };
57
+ } | {
58
+ readonly skipped: string;
59
+ };
60
+ }
61
+ /**
62
+ * Records a person's message by its provider id in the workspace chat store, with what the agent
63
+ * did with it. A message that started a turn keeps the delivery eve took it in (`meta.delivery`),
64
+ * by which the recorder links it to the turn. Recording it again changes nothing. On the chat
65
+ * archive in Cloud nothing is recorded here: the recorder keeps the message eve delivered there,
66
+ * as before, and answers false.
67
+ */
68
+ export declare function recordReceivedMessage(archive: ChatArchive, message: ReceivedMessage): Promise<boolean>;
69
+ /**
70
+ * One change a provider reports to a message of a chat, found by the provider's id of it, the
71
+ * target: a reaction (an empty emoji removes the sender's), an edit, a deletion, or a delivery
72
+ * status of a message the workspace's side sent. None starts a turn.
73
+ */
74
+ export type ChatChange = {
75
+ readonly channel: string;
76
+ readonly chatId: string;
77
+ readonly target: string;
78
+ } & ({
79
+ readonly change: "reaction";
80
+ readonly senderId: string;
81
+ readonly emoji: string;
82
+ } | {
83
+ readonly change: "edit";
84
+ readonly text: string;
85
+ readonly at?: string;
86
+ } | {
87
+ readonly change: "delete";
88
+ readonly at?: string;
89
+ } | {
90
+ readonly change: "status";
91
+ readonly status: "sent" | "delivered" | "read" | "failed";
92
+ /** The provider's refusal, as a code: lower case, digits and underscores. */
93
+ readonly failure?: string;
94
+ });
95
+ /** What became of a change: `dropped` on the chat archive in Cloud, which keeps no changes. */
96
+ export type ChatChangeOutcome = "applied" | "unchanged" | "dropped";
97
+ /**
98
+ * Applies one change to its message in the workspace chat store: `unchanged` when the store holds
99
+ * no such message, or the change changes nothing, such as a status older than the message's. On
100
+ * the chat archive in Cloud a change is dropped: it writes nothing new there.
101
+ */
102
+ export declare function applyChatChange(archive: ChatArchive, change: ChatChange): Promise<ChatChangeOutcome>;
15
103
  /** A message the archive keeps without a turn. */
16
104
  export interface RecordedMessage {
17
105
  /** The channel's name, as the archive keys its chats. */
@@ -36,6 +124,10 @@ export interface RecordedMessage {
36
124
  readonly messageId: string;
37
125
  readonly text: string;
38
126
  readonly files?: ReadonlyArray<RecordedFile>;
127
+ /** The provider's id of the message it quotes. */
128
+ readonly replyTo?: string;
129
+ /** What it carries beside its text: kept by the workspace chat store alone. */
130
+ readonly parts?: ReadonlyArray<ChatPart>;
39
131
  /** A group's chat, such as a thread in a Slack channel; by default a person's private chat. */
40
132
  readonly chatType?: "private" | "group";
41
133
  /** When the message was written, if not now. */
@@ -59,6 +151,13 @@ export type SentOutsideOutcome =
59
151
  * the archive. A message the archive holds by its provider id is skipped.
60
152
  */
61
153
  export declare function recordSentOutside(archive: ChatArchive, message: Omit<RecordedMessage, "participantIds" | "direction">): Promise<SentOutsideOutcome>;
154
+ /**
155
+ * Records a person's message the agent cannot read, such as a contact card on a channel that
156
+ * reads only text and files, in the chat the agent has with them, by the same rule as
157
+ * {@link recordSentOutside}, with `reason` as what the agent did with it: it starts no turn. Only
158
+ * the workspace chat store keeps it; nothing is written to the chat archive in Cloud.
159
+ */
160
+ export declare function recordUnreadMessage(archive: ChatArchive, message: Omit<RecordedMessage, "participantIds" | "direction" | "by">, reason: string): Promise<SentOutsideOutcome | "dropped">;
62
161
  /**
63
162
  * Records a person's message in a private chat a member of the workspace took over, which starts
64
163
  * no turn: the inbox shows it, and the agent reads it in its context once the chat is handed back.
@@ -74,4 +173,7 @@ export declare function recordHandledMessage(archive: ChatArchive, input: {
74
173
  readonly messageId: string;
75
174
  readonly text: string;
76
175
  readonly files?: ReadonlyArray<RecordedFile>;
176
+ readonly replyTo?: string;
177
+ readonly parts?: ReadonlyArray<ChatPart>;
178
+ readonly at?: string;
77
179
  }): Promise<void>;
@@ -4,7 +4,143 @@ 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
- import { a as chatEvent, f as storeOf } from "../../_chunks/chat-archive-BCPLSZeK.mjs";
7
+ import { S as storedFiles, a as chatEvent, f as storeOf } from "../../_chunks/chat-archive-BgxTGPKZ.mjs";
8
+ const MAXIMUM_PARTS = 20;
9
+ const PART_BOUNDS = {
10
+ text: 1024,
11
+ values: 20,
12
+ value: 320
13
+ };
14
+ function partRecord(value) {
15
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : void 0;
16
+ }
17
+ function partText(value) {
18
+ return typeof value === "string" && value.trim() !== "" ? value.trim().slice(0, PART_BOUNDS.text) : void 0;
19
+ }
20
+ function partValues(value) {
21
+ const values = (Array.isArray(value) ? value : []).flatMap((item) => typeof item === "string" && item.trim() !== "" ? [item.trim().slice(0, PART_BOUNDS.value)] : []).slice(0, PART_BOUNDS.values);
22
+ return values.length === 0 ? void 0 : values;
23
+ }
24
+ function degrees(value, bound) {
25
+ const number = typeof value === "string" && value.trim() !== "" ? Number(value) : value;
26
+ return typeof number === "number" && Number.isFinite(number) && Math.abs(number) <= bound ? number : void 0;
27
+ }
28
+ function chatPart(value) {
29
+ const part = partRecord(value);
30
+ if (part?.type === "location") {
31
+ const latitude = degrees(part.latitude, 90);
32
+ const longitude = degrees(part.longitude, 180);
33
+ const name = partText(part.name);
34
+ const address = partText(part.address);
35
+ return latitude === void 0 || longitude === void 0 ? void 0 : {
36
+ type: "location",
37
+ latitude,
38
+ longitude,
39
+ ...name === void 0 ? {} : { name },
40
+ ...address === void 0 ? {} : { address }
41
+ };
42
+ }
43
+ if (part?.type === "contact") {
44
+ const name = partText(part.name);
45
+ const phones = partValues(part.phones);
46
+ const emails = partValues(part.emails);
47
+ const organization = partText(part.organization);
48
+ return name === void 0 ? void 0 : {
49
+ type: "contact",
50
+ name,
51
+ ...phones === void 0 ? {} : { phones },
52
+ ...emails === void 0 ? {} : { emails },
53
+ ...organization === void 0 ? {} : { organization }
54
+ };
55
+ }
56
+ }
57
+ function chatParts(value) {
58
+ if (!Array.isArray(value) || value.length > 20) return;
59
+ const parts = value.map(chatPart);
60
+ return parts.every((part) => part !== void 0) ? parts : void 0;
61
+ }
62
+ function stagedFiles(files) {
63
+ return storedFiles([...files.values()].flatMap((file) => file.status === "stored" && typeof file.attachment?.id === "string" ? [{
64
+ id: file.attachment.id,
65
+ filename: file.attachment.filename,
66
+ contentType: file.attachment.contentType,
67
+ size: file.attachment.size
68
+ }] : []));
69
+ }
70
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu;
71
+ async function recordReceivedMessage(archive, message) {
72
+ const store = await storeOf(archive);
73
+ if (store === void 0) return false;
74
+ const target = {
75
+ channel: message.channel,
76
+ chatId: message.chatId.slice(0, 256),
77
+ messageId: message.messageId.slice(0, 512)
78
+ };
79
+ const senderName = message.senderName?.trim().slice(0, 200);
80
+ const turn = "turn" in message.outcome ? message.outcome.turn : void 0;
81
+ await store.record({
82
+ ...target,
83
+ chatType: "private",
84
+ participants: UUID.test(message.memberId) ? [message.memberId] : [],
85
+ direction: "inbound",
86
+ author: "human",
87
+ senderId: message.senderId.slice(0, 256),
88
+ ...senderName === void 0 || senderName === "" ? {} : { senderName },
89
+ ...UUID.test(message.memberId) ? { userId: message.memberId } : {},
90
+ ...message.replyTo === void 0 ? {} : { replyTo: message.replyTo.slice(0, 512) },
91
+ ...message.text === "" ? {} : { text: message.text.slice(0, 1e5) },
92
+ ...message.parts === void 0 || message.parts.length === 0 ? {} : { parts: message.parts.slice(0, 20) },
93
+ ...message.files === void 0 || message.files.length === 0 ? {} : { files: message.files.slice(0, 50) },
94
+ ...message.at === void 0 ? {} : { at: message.at },
95
+ ...turn === void 0 ? {} : {
96
+ sessionId: turn.sessionId.slice(0, 512),
97
+ meta: { delivery: turn.deliveryId }
98
+ }
99
+ });
100
+ await store.change({
101
+ ...target,
102
+ change: "disposition",
103
+ ...turn === void 0 ? {
104
+ disposition: "skipped",
105
+ reason: message.outcome.skipped
106
+ } : {
107
+ disposition: "turn",
108
+ sessionId: turn.sessionId.slice(0, 512)
109
+ }
110
+ });
111
+ return true;
112
+ }
113
+ const CODE = /^[a-z][a-z0-9_]{0,63}$/u;
114
+ async function applyChatChange(archive, change) {
115
+ const store = await storeOf(archive);
116
+ if (store === void 0) return "dropped";
117
+ const target = {
118
+ channel: change.channel,
119
+ chatId: change.chatId.slice(0, 256),
120
+ messageId: change.target.slice(0, 512)
121
+ };
122
+ const { applied } = await store.change(change.change === "reaction" ? {
123
+ ...target,
124
+ change: "reaction",
125
+ senderId: change.senderId.slice(0, 256),
126
+ emoji: change.emoji.slice(0, 64)
127
+ } : change.change === "edit" ? {
128
+ ...target,
129
+ change: "edit",
130
+ text: change.text.slice(0, 1e5),
131
+ ...change.at === void 0 ? {} : { at: change.at }
132
+ } : change.change === "delete" ? {
133
+ ...target,
134
+ change: "delete",
135
+ ...change.at === void 0 ? {} : { at: change.at }
136
+ } : {
137
+ ...target,
138
+ change: "status",
139
+ status: change.status,
140
+ ...change.failure !== void 0 && CODE.test(change.failure) ? { failure: change.failure } : {}
141
+ });
142
+ return applied ? "applied" : "unchanged";
143
+ }
8
144
  async function recordChatMessage(archive, message) {
9
145
  const { eventId } = message;
10
146
  return archive.append(chatEvent({
@@ -19,7 +155,9 @@ async function recordChatMessage(archive, message) {
19
155
  senderIsBot: message.by === "bot",
20
156
  kind: message.direction,
21
157
  messageId: message.messageId,
158
+ ...message.replyTo === void 0 ? {} : { replyToMessageId: message.replyTo },
22
159
  text: message.text,
160
+ ...message.parts === void 0 || message.parts.length === 0 ? {} : { parts: message.parts },
23
161
  ...message.direction === "outbound" ? { status: "completed" } : {},
24
162
  ...message.at === void 0 ? {} : { at: message.at },
25
163
  attachments: (message.files ?? []).map((file, index) => ({
@@ -32,6 +170,30 @@ async function recordChatMessage(archive, message) {
32
170
  }));
33
171
  }
34
172
  async function recordSentOutside(archive, message) {
173
+ return recordInChat(archive, {
174
+ ...message,
175
+ direction: "outbound"
176
+ });
177
+ }
178
+ async function recordUnreadMessage(archive, message, reason) {
179
+ const store = await storeOf(archive);
180
+ if (store === void 0) return "dropped";
181
+ const outcome = await recordInChat(archive, {
182
+ ...message,
183
+ direction: "inbound",
184
+ by: "human"
185
+ });
186
+ if (outcome === "recorded") await store.change({
187
+ channel: message.provider,
188
+ chatId: message.chatId,
189
+ messageId: message.messageId,
190
+ change: "disposition",
191
+ disposition: "skipped",
192
+ reason
193
+ });
194
+ return outcome;
195
+ }
196
+ async function recordInChat(archive, message) {
35
197
  const chat = {
36
198
  provider: message.provider,
37
199
  chatId: message.chatId,
@@ -50,7 +212,6 @@ async function recordSentOutside(archive, message) {
50
212
  if (known !== void 0) return "known";
51
213
  await recordChatMessage(archive, {
52
214
  ...message,
53
- direction: "outbound",
54
215
  participantIds: latest.participantIds
55
216
  });
56
217
  return "recorded";
@@ -70,7 +231,10 @@ async function recordHandledMessage(archive, input) {
70
231
  senderName: input.senderName ?? null,
71
232
  messageId: input.messageId,
72
233
  text: input.text,
73
- ...input.files === void 0 ? {} : { files: input.files }
234
+ ...input.files === void 0 ? {} : { files: input.files },
235
+ ...input.replyTo === void 0 ? {} : { replyTo: input.replyTo },
236
+ ...input.parts === void 0 ? {} : { parts: input.parts },
237
+ ...input.at === void 0 ? {} : { at: input.at }
74
238
  });
75
239
  const store = await storeOf(archive);
76
240
  if (store !== void 0) {
@@ -99,4 +263,4 @@ async function recordHandledMessage(archive, input) {
99
263
  status: "completed"
100
264
  }));
101
265
  }
102
- export { recordChatMessage, recordHandledMessage, recordSentOutside };
266
+ export { MAXIMUM_PARTS, applyChatChange, chatPart, chatParts, recordChatMessage, recordHandledMessage, recordReceivedMessage, recordSentOutside, recordUnreadMessage, stagedFiles };
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { n as contentText, t as CONTENT_CAPS } from "../../_chunks/content-cDtVnr8Y.mjs";
8
- import { a as chatEvent, d as sessionFailureEventId, f as storeOf, p as summarizeArguments, r as chatArchive } from "../../_chunks/chat-archive-BCPLSZeK.mjs";
8
+ import { a as chatEvent, d as sessionFailureEventId, f as storeOf, p as summarizeArguments, r as chatArchive } from "../../_chunks/chat-archive-BgxTGPKZ.mjs";
9
9
  import { agentTaskIdOf } from "./agent-task.mjs";
10
10
  import { revisionOf } from "./review/revision.mjs";
11
11
  import { Ft as chatChannel, Pt as chatAddressOf, i as memberIdOf, ot as guestIdOf } from "../../_chunks/principal-Zf42Yf4r.mjs";
@@ -252,14 +252,30 @@ function deliveredMessageId(sessionId, deliveryId) {
252
252
  }
253
253
  const TRIGGER_MARKER = /^\[source-message:\d+;trigger:(\d+)\]/u;
254
254
  function turnMessages(context, turnId, telegram) {
255
- return deliveries(context.view, { turnId }).flatMap((delivery) => {
256
- if (delivery.outcome === "refused" || delivery.outcome === "ignored") return [];
255
+ return turnDeliveries(context, turnId).flatMap((delivery) => {
257
256
  if (!telegram) return [deliveredMessageId(context.session.id, delivery.deliveryId)];
258
257
  const first = delivery.parts?.find((part) => part.kind === "text");
259
258
  const trigger = first?.kind === "text" ? TRIGGER_MARKER.exec(first.text)?.[1] : void 0;
260
259
  return trigger === void 0 ? [] : [trigger];
261
260
  });
262
261
  }
262
+ function turnDeliveries(context, turnId) {
263
+ return deliveries(context.view, { turnId }).filter((delivery) => delivery.outcome !== "refused" && delivery.outcome !== "ignored");
264
+ }
265
+ const RECORDS_MESSAGES = new Set(["custom", "whatsapp"]);
266
+ const DELIVERED_WINDOW = 100;
267
+ async function deliveredMessages(store, chat, deliveryIds) {
268
+ if (deliveryIds.length === 0) return [];
269
+ const { messages } = await store.read({
270
+ channel: chat.provider,
271
+ chatId: chat.chatId,
272
+ limit: DELIVERED_WINDOW
273
+ });
274
+ return messages.flatMap((row) => {
275
+ const delivery = row.meta?.delivery;
276
+ return row.direction === "inbound" && row.messageId !== null && typeof delivery === "string" && deliveryIds.includes(delivery) ? [row.messageId] : [];
277
+ });
278
+ }
263
279
  async function recordMessages(input) {
264
280
  const { archive, store, event, context, base, eventId } = input;
265
281
  if (event.type === "call.requested" && event.data.capability.name === UNANSWERED_TOOL) {
@@ -285,6 +301,18 @@ async function recordMessages(input) {
285
301
  await recordModelServiceAlert(archive, base, event.data.error);
286
302
  return;
287
303
  }
304
+ if (event.type === "delivery.consumed" && RECORDS_MESSAGES.has(sessionKind(context) ?? "")) {
305
+ for (const messageId of await deliveredMessages(store, base, [event.data.deliveryId])) await store.change({
306
+ channel: base.provider,
307
+ chatId: base.chatId,
308
+ messageId,
309
+ change: "disposition",
310
+ disposition: "turn",
311
+ sessionId: context.session.id,
312
+ turnId: event.data.turnId
313
+ });
314
+ return;
315
+ }
288
316
  if (event.type === "delivery.consumed" && !isTelegram(context)) {
289
317
  const messageId = deliveredMessageId(context.session.id, event.data.deliveryId);
290
318
  await archive.append(chatEvent({
@@ -316,16 +344,19 @@ async function recordMessages(input) {
316
344
  const message = typeof event.data.value === "string" ? event.data.value : "";
317
345
  const silent = completionKind(message) !== "reply";
318
346
  const turnId = event.scope?.turnId ?? context.session.turn.id;
319
- if (turnId !== void 0 && turnId !== null) for (const messageId of turnMessages(context, turnId, isTelegram(context))) await store.change({
320
- channel: base.provider,
321
- chatId: base.chatId,
322
- messageId,
323
- change: "disposition",
324
- disposition: "turn",
325
- sessionId: context.session.id,
326
- turnId,
327
- ...silent ? { reason: "silent" } : {}
328
- });
347
+ if (turnId !== void 0 && turnId !== null) {
348
+ const answered = RECORDS_MESSAGES.has(sessionKind(context) ?? "") ? await deliveredMessages(store, base, turnDeliveries(context, turnId).map((delivery) => delivery.deliveryId)) : turnMessages(context, turnId, isTelegram(context));
349
+ for (const messageId of answered) await store.change({
350
+ channel: base.provider,
351
+ chatId: base.chatId,
352
+ messageId,
353
+ change: "disposition",
354
+ disposition: "turn",
355
+ sessionId: context.session.id,
356
+ turnId,
357
+ ...silent ? { reason: "silent" } : {}
358
+ });
359
+ }
329
360
  if (!RECORDS_REPLIES.has(sessionKind(context) ?? "") && !silent && !input.reviewed(context.session.auth.current)) await archive.append(chatEvent({
330
361
  ...base,
331
362
  eventId: `${eventId}:outbound`,
@@ -19,6 +19,27 @@ export interface StoredFile {
19
19
  readonly type?: string;
20
20
  readonly size?: number;
21
21
  }
22
+ /**
23
+ * What a message carries beside its text and files, as the workspace chat store keeps it in the
24
+ * message's `parts` and the inbox shows it: a place, or a person's contact card.
25
+ */
26
+ export type ChatPart = {
27
+ readonly type: "location";
28
+ /** Degrees, from -90 to 90. */
29
+ readonly latitude: number;
30
+ /** Degrees, from -180 to 180. */
31
+ readonly longitude: number;
32
+ /** The place's name, when the provider gives one. */
33
+ readonly name?: string;
34
+ readonly address?: string;
35
+ } | {
36
+ readonly type: "contact";
37
+ /** The name the card shows. */
38
+ readonly name: string;
39
+ readonly phones?: ReadonlyArray<string>;
40
+ readonly emails?: ReadonlyArray<string>;
41
+ readonly organization?: string;
42
+ };
22
43
  /** One message as the store holds it. Times are ISO 8601; `revision` is a decimal. */
23
44
  export interface StoredMessage {
24
45
  readonly id: string;
@@ -35,6 +56,7 @@ export interface StoredMessage {
35
56
  readonly messageId: string | null;
36
57
  readonly replyTo: string | null;
37
58
  readonly text: string | null;
59
+ /** What it carries beside its text: {@link ChatPart}s, and kinds a later SDK adds. */
38
60
  readonly parts: ReadonlyArray<unknown>;
39
61
  readonly files: ReadonlyArray<StoredFile>;
40
62
  /** The reactions the message carries now, one per sender. */
@@ -79,7 +101,7 @@ export interface MessageInput {
79
101
  readonly messageId?: string;
80
102
  readonly replyTo?: string;
81
103
  readonly text?: string;
82
- readonly parts?: ReadonlyArray<Readonly<Record<string, unknown>>>;
104
+ readonly parts?: ReadonlyArray<ChatPart>;
83
105
  readonly files?: ReadonlyArray<StoredFile>;
84
106
  readonly at?: string;
85
107
  readonly status?: StoredStatus;
@@ -10,7 +10,7 @@ import { agentToolsAttribute } from "../agent-tools.mjs";
10
10
  import { providerChat } from "../attachment-tools.mjs";
11
11
  import { Pt as chatAddressOf, S as fetchStoredAttachment, b as agentAttachments, d as prepareInboundMedia, i as memberIdOf, m as turnContent, zt as withChatAddress } from "../../../_chunks/principal-Zf42Yf4r.mjs";
12
12
  import { channelAttributes, currentChannel, currentKey, inHandlerChannels, withNamedRoutes } from "../channel-scope.mjs";
13
- import { l as replyEvent, r as chatArchive } from "../../../_chunks/chat-archive-BCPLSZeK.mjs";
13
+ import { l as replyEvent, r as chatArchive } from "../../../_chunks/chat-archive-BgxTGPKZ.mjs";
14
14
  import { recordHandledMessage, recordSentOutside } from "../chat-messages.mjs";
15
15
  import { ConnectionProxyError, connectionProxy } from "../connection-proxy.mjs";
16
16
  import { redactDiagnostic } from "../diagnostics.mjs";
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { agentMessage } from "./messages.mjs";
8
- import { s as collapseChatEvents } from "../../../_chunks/chat-archive-BCPLSZeK.mjs";
8
+ import { s as collapseChatEvents } from "../../../_chunks/chat-archive-BgxTGPKZ.mjs";
9
9
  function archivedMetadata(event) {
10
10
  try {
11
11
  return JSON.parse(event.argsSummary ?? "null")?.routing ?? {};