@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.
Files changed (99) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/dist/_chunks/{build-metadata-BuLFK152.mjs → build-metadata-CvUZSH8c.mjs} +1 -1
  3. package/dist/_chunks/chat-archive-BCPLSZeK.mjs +585 -0
  4. package/dist/_chunks/chat-archive-DK7uCgff.mjs +1337 -0
  5. package/dist/_chunks/{principal-Cw1NtCkj.mjs → principal-Zf42Yf4r.mjs} +1 -1
  6. package/dist/extension/config.d.ts +8 -0
  7. package/dist/extension/config.mjs +12 -0
  8. package/dist/extension/connections/ontology.mjs +1 -1
  9. package/dist/extension/hooks/authorization.mjs +1 -1
  10. package/dist/extension/hooks/chat-context.mjs +1 -1
  11. package/dist/extension/hooks/chat-recorder.mjs +1 -1
  12. package/dist/extension/instructions/persona.mjs +1 -1
  13. package/dist/extension/lib/actor.mjs +1 -1
  14. package/dist/extension/lib/attachment-tools.mjs +1 -1
  15. package/dist/extension/lib/attachments-send.mjs +1 -1
  16. package/dist/extension/lib/attachments.mjs +1 -1
  17. package/dist/extension/lib/build-metadata.mjs +1 -1
  18. package/dist/extension/lib/chat-address.mjs +1 -1
  19. package/dist/extension/lib/chat-archive.d.ts +50 -0
  20. package/dist/extension/lib/chat-archive.mjs +1 -188
  21. package/dist/extension/lib/chat-context.d.ts +10 -2
  22. package/dist/extension/lib/chat-context.mjs +48 -9
  23. package/dist/extension/lib/chat-messages.mjs +13 -1
  24. package/dist/extension/lib/chat-recorder.d.ts +2 -0
  25. package/dist/extension/lib/chat-recorder.mjs +105 -4
  26. package/dist/extension/lib/chat-store.d.ts +212 -0
  27. package/dist/extension/lib/chat-store.mjs +103 -0
  28. package/dist/extension/lib/confirmations.mjs +1 -1
  29. package/dist/extension/lib/email/attachments-send.mjs +1 -1
  30. package/dist/extension/lib/email/channel.mjs +2 -2
  31. package/dist/extension/lib/group-routing/routing-context.mjs +21 -11
  32. package/dist/extension/lib/guest-usage.mjs +1 -1
  33. package/dist/extension/lib/inbound-media/files.mjs +1 -1
  34. package/dist/extension/lib/inbound-media/index.mjs +1 -1
  35. package/dist/extension/lib/model-service-alert.mjs +14 -1
  36. package/dist/extension/lib/ontology-connection.mjs +1 -1
  37. package/dist/extension/lib/ontology-file-call.mjs +1 -1
  38. package/dist/extension/lib/ontology-tools.mjs +1 -1
  39. package/dist/extension/lib/review/hold.mjs +1 -1
  40. package/dist/extension/lib/review/judge.mjs +1 -1
  41. package/dist/extension/lib/review/reply.mjs +2 -2
  42. package/dist/extension/lib/review/revision-channel.mjs +1 -1
  43. package/dist/extension/lib/role-skill.mjs +1 -1
  44. package/dist/extension/lib/runtime-envelope.mjs +1 -1
  45. package/dist/extension/lib/sent-files.mjs +1 -1
  46. package/dist/extension/lib/slack/adapter.mjs +2 -2
  47. package/dist/extension/lib/slack/attachments-send.mjs +1 -1
  48. package/dist/extension/lib/slack/callbacks.mjs +1 -1
  49. package/dist/extension/lib/stored-files.mjs +1 -1
  50. package/dist/extension/lib/telegram/adapter.mjs +4 -4
  51. package/dist/extension/lib/telegram/attachment-description.mjs +1 -1
  52. package/dist/extension/lib/telegram/attachments-send.mjs +1 -1
  53. package/dist/extension/lib/telegram/callbacks.mjs +1 -1
  54. package/dist/extension/lib/telegram/chat-archive.d.ts +32 -3
  55. package/dist/extension/lib/telegram/chat-archive.mjs +1 -703
  56. package/dist/extension/lib/telegram/confirmations.mjs +2 -2
  57. package/dist/extension/lib/telegram/customer-text.mjs +1 -1
  58. package/dist/extension/lib/telegram/delivery-diagnostics.mjs +1 -1
  59. package/dist/extension/lib/telegram/files.mjs +1 -1
  60. package/dist/extension/lib/telegram/health.mjs +1 -1
  61. package/dist/extension/lib/telegram/held-approvals.mjs +1 -1
  62. package/dist/extension/lib/telegram/inbound-request.d.ts +2 -1
  63. package/dist/extension/lib/telegram/inbound-request.mjs +1 -1
  64. package/dist/extension/lib/telegram/inbound.mjs +2 -2
  65. package/dist/extension/lib/telegram/lifecycle.mjs +2 -2
  66. package/dist/extension/lib/telegram/principal.mjs +1 -1
  67. package/dist/extension/lib/telegram/session-recovery.mjs +1 -1
  68. package/dist/extension/lib/telegram/silent.mjs +1 -1
  69. package/dist/extension/lib/telegram/store-capture.d.ts +37 -0
  70. package/dist/extension/lib/telegram/store-capture.mjs +7 -0
  71. package/dist/extension/lib/telegram/structured.mjs +1 -1
  72. package/dist/extension/lib/telegram/turn-errors.mjs +2 -2
  73. package/dist/extension/lib/traces.d.ts +21 -0
  74. package/dist/extension/lib/traces.mjs +16 -0
  75. package/dist/extension/lib/web/auth.mjs +1 -1
  76. package/dist/extension/lib/web/channel.mjs +1 -1
  77. package/dist/extension/lib/whatsapp/adapter.mjs +2 -2
  78. package/dist/extension/lib/whatsapp/attachments-send.mjs +2 -2
  79. package/dist/extension/lib/whatsapp/callbacks.mjs +1 -1
  80. package/dist/extension/lib/whatsapp/files.mjs +1 -1
  81. package/dist/extension/lib/whatsapp/sent.mjs +1 -1
  82. package/dist/extension/lib/workspace-action.mjs +1 -1
  83. package/dist/extension/lib/workspace-channel/attachments-send.mjs +1 -1
  84. package/dist/extension/lib/workspace-channel/channel.mjs +2 -2
  85. package/dist/extension/lib/workspace-chat-archive.d.ts +41 -0
  86. package/dist/extension/lib/workspace-chat-archive.mjs +7 -0
  87. package/dist/extension/lib/workspace-source.mjs +1 -1
  88. package/dist/extension/model.mjs +1 -1
  89. package/dist/extension/tools/attachments_discard.mjs +1 -1
  90. package/dist/extension/tools/attachments_list.mjs +1 -1
  91. package/dist/extension/tools/attachments_promote.mjs +1 -1
  92. package/dist/extension/tools/attachments_read.mjs +1 -1
  93. package/dist/extension/tools/attachments_send.mjs +1 -1
  94. package/dist/extension/tools/attachments_stage.mjs +1 -1
  95. package/dist/extension/tools/attachments_table.mjs +1 -1
  96. package/dist/extension/tools/handoff.mjs +1 -1
  97. package/dist/extension/tools/questions_ask.mjs +1 -1
  98. package/dist/extension/tools/workspace_source.mjs +1 -1
  99. package/package.json +6 -2
@@ -1988,7 +1988,7 @@ function withReplacedText(source, request) {
1988
1988
  throw error;
1989
1989
  }
1990
1990
  try {
1991
- await request.finishClaim?.(true);
1991
+ await request.finishClaim?.(true, result.sessionId);
1992
1992
  } catch (error) {
1993
1993
  reportTelegramError("turn_admission_recording_failed", error);
1994
1994
  }
@@ -143,6 +143,12 @@ export interface SegmentStreamAgentConfigInput {
143
143
  * Off when absent.
144
144
  */
145
145
  readonly handoff?: boolean;
146
+ /**
147
+ * What the agent's turn traces record (`docs/agent.md`, "Traces"). Every turn is traced, with its
148
+ * content (messages, model input and output, tool arguments and results) unless `content` is
149
+ * false; `agent/instrumentation/otel.ts` passes this to `segmentstream.traces`.
150
+ */
151
+ readonly traces?: import("./lib/traces.js").TraceSettings;
146
152
  /**
147
153
  * The routine ontology action a press of a workspace button calls, in every channel, as the
148
154
  * member who pressed it: a button the workspace sent with `agent_chat.send` and its `buttons`,
@@ -518,6 +524,8 @@ export interface SegmentStreamAgentConfig extends AdmissionSettings {
518
524
  * {@link SegmentStreamAgentConfigInput.handoff}.
519
525
  */
520
526
  readonly handoff?: boolean;
527
+ /** What turn traces record; absent when the workspace declares nothing. */
528
+ readonly traces?: import("./lib/traces.js").TraceSettings;
521
529
  /** The action a press of a workspace button calls, in every channel; absent without one. */
522
530
  readonly buttons?: WorkspaceActionHook;
523
531
  /** The web tools' settings; absent without web tools. See {@link WebSettings}. */
@@ -1044,6 +1044,7 @@ function validateConfig(input, options = {}) {
1044
1044
  "workspaceSource",
1045
1045
  "unanswered",
1046
1046
  "handoff",
1047
+ "traces",
1047
1048
  "buttons",
1048
1049
  "web",
1049
1050
  "browser",
@@ -1251,6 +1252,16 @@ function validateConfig(input, options = {}) {
1251
1252
  message: "must be true or false",
1252
1253
  path: ["handoff"]
1253
1254
  });
1255
+ const tracesInput = section({
1256
+ value: root?.traces,
1257
+ path: ["traces"],
1258
+ allowed: ["content"],
1259
+ issues
1260
+ });
1261
+ if (tracesInput?.content !== void 0 && typeof tracesInput.content !== "boolean") issues.push({
1262
+ message: "must be true or false",
1263
+ path: ["traces", "content"]
1264
+ });
1254
1265
  const buttons = workspaceHook(root?.buttons, ["buttons"], issues);
1255
1266
  for (const [name, channel] of Object.entries(declared)) {
1256
1267
  const own = channel !== null && "callbacks" in channel ? channel.callbacks : void 0;
@@ -1294,6 +1305,7 @@ function validateConfig(input, options = {}) {
1294
1305
  ...workspaceSource === true ? { workspaceSource: true } : {},
1295
1306
  ...unanswered === true ? { unanswered: true } : {},
1296
1307
  ...handoff === true ? { handoff: true } : {},
1308
+ ...tracesInput === void 0 ? {} : { traces: tracesInput.content === void 0 ? {} : { content: tracesInput.content === true } },
1297
1309
  ...buttons === void 0 ? {} : { buttons },
1298
1310
  ...web === null ? {} : { web },
1299
1311
  ...browser === null ? {} : { browser },
@@ -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 { T as ontologyConnection } from "../../_chunks/principal-Cw1NtCkj.mjs";
8
+ import { T as ontologyConnection } from "../../_chunks/principal-Zf42Yf4r.mjs";
9
9
  import { defineDynamic } from "eve/connections";
10
10
  var ontology_default = defineDynamic(async (context) => {
11
11
  if (!segmentstream.config.ontology.connection) return null;
@@ -7,7 +7,7 @@ __eveCreateRequire(import.meta.url);
7
7
  import segmentstream from "../extension.mjs";
8
8
  import { localizedText } from "../lib/admission.mjs";
9
9
  import { confirmationLocale } from "../lib/telegram/confirmation-text.mjs";
10
- import "../../_chunks/principal-Cw1NtCkj.mjs";
10
+ import "../../_chunks/principal-Zf42Yf4r.mjs";
11
11
  import { defineHook } from "eve/hooks";
12
12
  var authorization_default = defineHook({ events: { "interaction.opened": (event, context) => {
13
13
  const principal = context.session.auth.current;
@@ -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 { chatArchive } from "../lib/chat-archive.mjs";
8
+ import { r as chatArchive } from "../../_chunks/chat-archive-BCPLSZeK.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 { chatArchive } from "../lib/chat-archive.mjs";
9
+ import { r as chatArchive } from "../../_chunks/chat-archive-BCPLSZeK.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)) } });
@@ -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 { a as rolesOf } from "../../_chunks/principal-Cw1NtCkj.mjs";
8
+ import { a as rolesOf } from "../../_chunks/principal-Zf42Yf4r.mjs";
9
9
  import { personaFor } from "../personas.mjs";
10
10
  import { defineDynamic, defineInstructions } from "eve/instructions";
11
11
  var persona_default = defineDynamic((context) => {
@@ -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 { R as ACT_AS_HEADER, z as ActorRequiredError, B as actorHeaders, V as actorKey, H as actorOf, U as isGuestSession, W as member, G as memberTool, K as notForGuests } from "../../_chunks/principal-Cw1NtCkj.mjs";
7
+ export { R as ACT_AS_HEADER, z as ActorRequiredError, B as actorHeaders, V as actorKey, H as actorOf, U as isGuestSession, W as member, G as memberTool, K as notForGuests } from "../../_chunks/principal-Zf42Yf4r.mjs";
@@ -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
- import { Ft as chatChannel, Pt as chatAddressOf, b as agentAttachments, i as memberIdOf } from "../../_chunks/principal-Cw1NtCkj.mjs";
7
+ import { Ft as chatChannel, Pt as chatAddressOf, b as agentAttachments, i as memberIdOf } from "../../_chunks/principal-Zf42Yf4r.mjs";
8
8
  import { detectFile, documentText } from "./attachment-formats.mjs";
9
9
  import { readSheets, typedTable } from "./attachment-tables.mjs";
10
10
  import { appOrigin } from "./environment.mjs";
@@ -5,7 +5,7 @@ const __filename = __eveFileURLToPath(import.meta.url);
5
5
  __eveDirname(__filename);
6
6
  __eveCreateRequire(import.meta.url);
7
7
  import { attachmentOwner } from "./attachment-tools.mjs";
8
- import { Pt as chatAddressOf, _ as AttachmentError, yt as failureText } from "../../_chunks/principal-Cw1NtCkj.mjs";
8
+ import { Pt as chatAddressOf, _ as AttachmentError, yt as failureText } from "../../_chunks/principal-Zf42Yf4r.mjs";
9
9
  import { appOrigin, channelsEnabled } from "./environment.mjs";
10
10
  import { transientFileStatus } from "./file-grant.mjs";
11
11
  import { runtimeToken } from "./runtime-token.mjs";
@@ -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 { h as ATTACHMENT_TTL_HOURS, g as ATTACHMENT_URL_PROTOCOL, _ as AttachmentError, jt as CHAT_HEADER, v as EARLIER_CHAT_HEADER, y as MAXIMUM_ATTACHMENT_BYTES, Nt as SESSION_HEADER, b as agentAttachments, x as attachmentUrl, S as fetchStoredAttachment, C as parseAttachmentUrl } from "../../_chunks/principal-Cw1NtCkj.mjs";
7
+ export { h as ATTACHMENT_TTL_HOURS, g as ATTACHMENT_URL_PROTOCOL, _ as AttachmentError, jt as CHAT_HEADER, v as EARLIER_CHAT_HEADER, y as MAXIMUM_ATTACHMENT_BYTES, Nt as SESSION_HEADER, b as agentAttachments, x as attachmentUrl, S as fetchStoredAttachment, C as parseAttachmentUrl } from "../../_chunks/principal-Zf42Yf4r.mjs";
@@ -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-BuLFK152.mjs";
7
+ export { t as agentBuild } from "../../_chunks/build-metadata-CvUZSH8c.mjs";
@@ -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 { At as CHAT_ATTRIBUTE, jt as CHAT_HEADER, Mt as RUNTIME_SOURCE_ATTRIBUTE, Nt as SESSION_HEADER, Pt as chatAddressOf, Ft as chatChannel, It as chatHeaders, Lt as chatRuntimeSource, Rt as isSameChat, zt as withChatAddress, Bt as workspaceIdentityProvider } from "../../_chunks/principal-Cw1NtCkj.mjs";
7
+ export { At as CHAT_ATTRIBUTE, jt as CHAT_HEADER, Mt as RUNTIME_SOURCE_ATTRIBUTE, Nt as SESSION_HEADER, Pt as chatAddressOf, Ft as chatChannel, It as chatHeaders, Lt as chatRuntimeSource, Rt as isSameChat, zt as withChatAddress, Bt as workspaceIdentityProvider } from "../../_chunks/principal-Zf42Yf4r.mjs";
@@ -1,3 +1,4 @@
1
+ import { type ChatStore } from "./chat-store.js";
1
2
  import { type Environment } from "./environment.js";
2
3
  import { type RuntimeToken } from "./runtime-token.js";
3
4
  /** Provider-neutral platform archive. Content uses the shared redaction and byte-limit policy. */
@@ -46,6 +47,16 @@ export interface ChatEvent {
46
47
  readonly uniqueId?: string;
47
48
  }>;
48
49
  readonly at: string;
50
+ /**
51
+ * What the agent did with an inbound message, as the workspace chat store keeps it on the
52
+ * message; absent from the chat archive in Cloud, whose decisions are rows of their own.
53
+ */
54
+ readonly disposition?: "claimed" | "turn" | "skipped" | null;
55
+ /** The member who wrote the message, as the workspace chat store keeps it. */
56
+ readonly userId?: string | null;
57
+ /** The message was edited, or deleted, since it was written: the store keeps its latest state. */
58
+ readonly edited?: boolean;
59
+ readonly deleted?: boolean;
49
60
  }
50
61
  export interface ChatPage {
51
62
  readonly events: ReadonlyArray<ChatEvent & {
@@ -93,7 +104,28 @@ export interface ChatArchive {
93
104
  readonly senderId: string;
94
105
  readonly participantId: string;
95
106
  }): Promise<string | undefined>;
107
+ /**
108
+ * The workspace chat store this archive keeps the chats in, where a channel sets what the agent
109
+ * did with each inbound message; undefined for the chat archive in Cloud. Archives that predate
110
+ * it have none.
111
+ */
112
+ store?(): Promise<ChatStore | undefined>;
113
+ /**
114
+ * One chat's messages changed after `after`, a revision of the workspace chat store, oldest
115
+ * change first: new messages, and edits and deletions of earlier ones. The chat archive in Cloud
116
+ * has none.
117
+ */
118
+ changes?(input: {
119
+ readonly provider: string;
120
+ readonly chatId: string;
121
+ readonly threadId?: string | null;
122
+ readonly after: string;
123
+ readonly limit?: number;
124
+ readonly signal?: AbortSignal;
125
+ }): Promise<ChatPage>;
96
126
  }
127
+ /** The workspace chat store an archive keeps its chats in, or undefined for the one in Cloud. */
128
+ export declare function storeOf(archive: ChatArchive): Promise<ChatStore | undefined>;
97
129
  /** The archive operation of a channel's reply, which its states share: see {@link replyEvent}. */
98
130
  export declare function replyOperation(key: string): string;
99
131
  /**
@@ -158,10 +190,28 @@ export declare function collapseChatEvents(events: ChatPage["events"]): ChatPage
158
190
  */
159
191
  export declare function sessionFailureEventId(sessionId: string): string;
160
192
  export declare function chatEvent(input: Pick<ChatEvent, "eventId" | "provider" | "chatId" | "chatType" | "kind"> & Partial<ChatEvent>): ChatEvent;
193
+ /** Forgets which store each ontology service keeps the chats in, for tests. */
194
+ export declare function forgetChatStores(fetchImpl?: typeof fetch): void;
195
+ /**
196
+ * The chat archive of the deployment: the workspace chat store when its ontology service keeps one,
197
+ * else the chat archive in Cloud (`docs/agent-chat-storage.md`, "The agent on the chat store").
198
+ * Which one is asked of the ontology service once per process, before the first read or write,
199
+ * so every write of a message goes to the same store.
200
+ */
161
201
  export declare function chatArchive(input?: {
162
202
  readonly environment?: Environment;
163
203
  readonly token?: RuntimeToken;
164
204
  readonly fetch?: typeof fetch;
165
205
  }): ChatArchive;
206
+ /**
207
+ * The chat archive in Cloud, under backend-next's runtime routes.
208
+ * @legacy agent.cloud-chat-archive The agent's archive before the workspace chat store, for an
209
+ * ontology service that keeps none.
210
+ */
211
+ export declare function cloudChatArchive(input?: {
212
+ readonly environment?: Environment;
213
+ readonly token?: RuntimeToken;
214
+ readonly fetch?: typeof fetch;
215
+ }): ChatArchive;
166
216
  /** Summaries retain useful scalar arguments, redact credentials, and never include file bytes. */
167
217
  export declare function summarizeArguments(value: unknown): string;
@@ -4,191 +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
- import { channelKey } from "./channel-scope.mjs";
8
- import { proxyEnvironment } from "./environment.mjs";
9
- import { runtimeToken } from "./runtime-token.mjs";
10
- import { r as workflowValue } from "../../_chunks/workflow-serializable-gzv5MZ5P.mjs";
11
- function replyOperation(key) {
12
- return `reply:${key}`;
13
- }
14
- function replyEvent(input) {
15
- const kind = input.kind ?? input.provider;
16
- return chatEvent({
17
- eventId: channelKey(kind, input.provider, `${kind}:reply:${input.key}:${input.status}`),
18
- operationId: replyOperation(input.key),
19
- provider: input.provider,
20
- chatId: input.chatId,
21
- chatType: "private",
22
- threadId: input.threadId,
23
- participantIds: input.participantIds,
24
- sessionId: input.sessionId,
25
- turnId: input.turnId,
26
- kind: "outbound",
27
- text: input.text,
28
- senderId: AGENT_SENDER,
29
- senderIsBot: true,
30
- status: input.status,
31
- messageId: input.messageId ?? null,
32
- ...input.at === void 0 ? {} : { at: input.at }
33
- });
34
- }
35
- const TOPIC_PAGES = 5;
36
- const TOPIC_PAGE_SIZE = 100;
37
- async function topicContext(archive, input) {
38
- const { threadId, ...search } = input;
39
- if (threadId !== null) return archive.context({
40
- ...search,
41
- threadId
42
- });
43
- const limit = search.limit ?? 50;
44
- const events = [];
45
- let before = search.before;
46
- let page;
47
- for (let scanned = 0; scanned < TOPIC_PAGES; scanned += 1) {
48
- page = await archive.context({
49
- ...search,
50
- limit: Math.max(limit, TOPIC_PAGE_SIZE),
51
- ...before === void 0 ? {} : { before }
52
- });
53
- events.push(...page.events.filter((event) => event.threadId === null));
54
- if (page.nextCursor === null || events.length >= limit) break;
55
- before = page.nextCursor;
56
- }
57
- return {
58
- ...page,
59
- events
60
- };
61
- }
62
- function isTelegramMessage(event) {
63
- return event.provider === "telegram" || event.eventId.startsWith(channelKey("telegram", event.provider, "telegram:"));
64
- }
65
- const AGENT_SENDER = "agent";
66
- function chatAuthor(event) {
67
- return !event.senderIsBot ? "human" : event.kind === "outbound" && event.senderId === "agent" ? "agent" : "bot";
68
- }
69
- function archiveSequence(value) {
70
- return /^-?\d+$/u.test(value) ? BigInt(value) : void 0;
71
- }
72
- function collapseChatEvents(events) {
73
- const latest = new Map();
74
- for (const event of events) {
75
- 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;
76
- const previous = latest.get(key);
77
- const current = archiveSequence(event.sequence);
78
- const earlier = previous === void 0 ? void 0 : archiveSequence(previous.sequence);
79
- if (previous === void 0 || (current !== void 0 && earlier !== void 0 ? current > earlier : event.storedAt > previous.storedAt)) latest.set(key, {
80
- ...event,
81
- eventId: key,
82
- ...event.kind === "outbound" && event.operationId != null && event.status === "requested" ? { status: "uncertain" } : {}
83
- });
84
- }
85
- return [...latest.values()];
86
- }
87
- function sessionFailureEventId(sessionId) {
88
- return `eve:${sessionId}:session.failed`;
89
- }
90
- function chatEvent(input) {
91
- return workflowValue({
92
- threadId: null,
93
- participantIds: [],
94
- senderId: null,
95
- senderName: null,
96
- senderIsBot: false,
97
- messageId: null,
98
- replyToMessageId: null,
99
- sessionId: null,
100
- turnId: null,
101
- text: null,
102
- decision: null,
103
- reason: null,
104
- toolCallId: null,
105
- toolName: null,
106
- argsSummary: null,
107
- status: null,
108
- attachments: [],
109
- at: new Date().toISOString(),
110
- ...input
111
- }, {
112
- boundary: "SDK chat event",
113
- eventType: input.kind,
114
- toolName: input.toolName ?? void 0,
115
- toolCallId: input.toolCallId ?? void 0
116
- });
117
- }
118
- function chatArchive(input = {}) {
119
- const environment = input.environment ?? process.env;
120
- const token = input.token ?? runtimeToken;
121
- const fetchImpl = input.fetch ?? fetch;
122
- async function call(path, body, signal) {
123
- const env = proxyEnvironment(environment);
124
- const identity = await token();
125
- const base = `${env.segmentstreamUrl}/api/internal/v1/workspaces/${encodeURIComponent(env.workspaceId)}`;
126
- const response = await fetchImpl(`${base}/agent/chats/${path}`, {
127
- method: "POST",
128
- redirect: "error",
129
- headers: {
130
- "content-type": "application/json",
131
- "x-segmentstream-organization-id": env.organizationId,
132
- "x-segmentstream-runtime-identity": identity
133
- },
134
- body: JSON.stringify(workflowValue(body, { boundary: "chat archive" })),
135
- signal: signal === void 0 ? AbortSignal.timeout(15e3) : AbortSignal.any([signal, AbortSignal.timeout(15e3)])
136
- });
137
- if (!response.ok) throw new Error(`Chat archive ${path} failed (${response.status}); request ${response.headers.get("x-request-id") ?? "unknown"}.`);
138
- return response.json();
139
- }
140
- return {
141
- append: async (event) => {
142
- return (await call("events", event)).stored;
143
- },
144
- context: async ({ includeDecisions, participantId, signal, ...search }) => await call("search", {
145
- search,
146
- context: !includeDecisions,
147
- reader: {
148
- participantId: participantId ?? null,
149
- groups: includeDecisions === true,
150
- admin: false
151
- }
152
- }, signal),
153
- lastChat: async ({ provider, senderId, participantId }) => {
154
- return (await call("search", {
155
- search: {
156
- provider,
157
- senderId,
158
- messagesOnly: true,
159
- limit: 1
160
- },
161
- reader: {
162
- participantId,
163
- groups: false,
164
- admin: false
165
- }
166
- })).events[0]?.chatId;
167
- },
168
- pendingReplies: async ({ provider, limit, requestedBefore }) => await call("search", {
169
- search: {
170
- provider,
171
- pending: true,
172
- limit,
173
- ...requestedBefore === void 0 ? {} : { to: requestedBefore }
174
- },
175
- reader: {
176
- participantId: null,
177
- groups: false,
178
- admin: false
179
- }
180
- })
181
- };
182
- }
183
- function summarizeArguments(value) {
184
- const sensitive = /token|password|secret|authorization|cookie|credential|api.?key|bytes|base64/i;
185
- const visit = (item, depth) => {
186
- if (depth > 4) return "[nested]";
187
- if (item instanceof Uint8Array || typeof item === "string" && /^data:/iu.test(item)) return "[binary data]";
188
- if (Array.isArray(item)) return item.slice(0, 20).map((entry) => visit(entry, depth + 1));
189
- 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)]));
190
- 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;
191
- };
192
- return JSON.stringify(workflowValue(visit(value, 0), { boundary: "chat arguments" })).slice(0, 4e3);
193
- }
194
- export { AGENT_SENDER, archiveSequence, chatArchive, chatAuthor, chatEvent, collapseChatEvents, replyEvent, replyOperation, sessionFailureEventId, summarizeArguments, topicContext };
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";
@@ -19,11 +19,14 @@ import type { ReadSessionReviews, SessionReview } from "./review/client.js";
19
19
  export type ChatContextStart =
20
20
  /**
21
21
  * Archive rows after this sequence, a decimal string, and the unseen rows stored since
22
- * `overlapSince`: a lower sequence can commit after a higher one was read.
22
+ * `overlapSince`: a lower sequence can commit after a higher one was read. `store` names the
23
+ * workspace chat store, whose sequence is its revisions; without it the sequence is the chat
24
+ * archive's in Cloud.
23
25
  */
24
26
  {
25
27
  readonly cursor: string;
26
28
  readonly overlapSince?: string;
29
+ readonly store?: "workspace";
27
30
  }
28
31
  /** Rows stored since this time: a session from before the bookmark, whose history holds the rest. */
29
32
  | {
@@ -102,8 +105,13 @@ export declare function readChatContext(input: {
102
105
  };
103
106
  readonly from: ChatContextBookmark;
104
107
  readonly sessionId: string;
105
- /** Telegram messages the session already holds: delivered to it, not shown as chat. */
108
+ /**
109
+ * Telegram messages the session already holds: delivered to it, not shown as chat until they are
110
+ * edited or deleted.
111
+ */
106
112
  readonly delivered: ReadonlyArray<string>;
113
+ /** The messages this turn delivers, as they are now: never shown beside it. */
114
+ readonly delivering?: ReadonlyArray<string>;
107
115
  readonly guidance?: string;
108
116
  readonly now: Date;
109
117
  }): Promise<ChatContextRead>;
@@ -6,8 +6,8 @@ __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 { archiveSequence, chatArchive, chatAuthor, collapseChatEvents, topicContext } from "./chat-archive.mjs";
10
- import { xt as reportTelegramError } from "../../_chunks/principal-Cw1NtCkj.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";
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";
13
13
  import { defineState } from "eve/context";
@@ -85,7 +85,7 @@ function routingOf(event) {
85
85
  }
86
86
  }
87
87
  function edited(event) {
88
- return routingOf(event).revision?.edited === true;
88
+ return routingOf(event).revision?.edited === true || event.edited === true;
89
89
  }
90
90
  function entryOf(event) {
91
91
  const evidence = retainedInboundEvidence(event);
@@ -98,7 +98,31 @@ function entryOf(event) {
98
98
  ...event.attachments.length === 0 ? {} : { attachments: event.attachments.slice(0, 10) },
99
99
  ...Array.isArray(files) && files.length > 0 ? { files: files.slice(0, 10) } : {},
100
100
  ...evidence === void 0 ? {} : { evidence },
101
- ...event.kind === "inbound" && edited(event) ? { edited: true } : {}
101
+ ...event.kind === "inbound" && edited(event) ? { edited: true } : {},
102
+ ...event.deleted === true ? { deleted: true } : {}
103
+ };
104
+ }
105
+ async function readChanges(archive, coordinates, after) {
106
+ const events = [];
107
+ let from = after;
108
+ for (let page = 0; page < MAXIMUM_PAGES && archive.changes !== void 0; page += 1) {
109
+ const result = await archive.changes({
110
+ ...coordinates,
111
+ after: from,
112
+ limit: PAGE_SIZE
113
+ });
114
+ events.push(...result.events);
115
+ if (result.nextCursor === null) return {
116
+ events,
117
+ through: BigInt(from),
118
+ complete: true
119
+ };
120
+ from = result.nextCursor;
121
+ }
122
+ return {
123
+ events,
124
+ through: BigInt(from),
125
+ complete: archive.changes === void 0
102
126
  };
103
127
  }
104
128
  function digest(text) {
@@ -128,16 +152,28 @@ async function readTopic(archive, coordinates, enough) {
128
152
  };
129
153
  }
130
154
  async function readChatContext(input) {
131
- const { start } = input.from;
155
+ const workspace = await storeOf(input.archive) !== void 0;
156
+ const switched = "cursor" in input.from.start && input.from.start.store === "workspace" !== workspace;
157
+ const start = switched ? { since: input.from.start.overlapSince ?? new Date(input.now.getTime() - 6e5).toISOString() } : input.from.start;
132
158
  const bootstrap = "bootstrap" in start;
133
159
  const cursor = "cursor" in start ? BigInt(start.cursor) : void 0;
134
160
  const overlapSince = "cursor" in start && start.overlapSince !== void 0 ? Date.parse(start.overlapSince) : void 0;
135
- const seen = new Set(input.from.seen ?? []);
161
+ const seen = new Set(switched ? [] : input.from.seen ?? []);
136
162
  const since = "since" in start ? Date.parse(start.since) : void 0;
137
163
  const read = await readTopic(input.archive, input.coordinates, (events) => cursor !== void 0 ? events.some((event) => sequence(event) <= cursor && (overlapSince === void 0 || Date.parse(event.storedAt) < overlapSince)) : since !== void 0 ? events.some((event) => Date.parse(event.storedAt) < since) : collapseChatEvents(events).length > BOOTSTRAP_MESSAGES);
138
- const unread = read.events.filter((event) => cursor === void 0 || sequence(event) > cursor || overlapSince !== void 0 && sequence(event) >= 0n && Date.parse(event.storedAt) >= overlapSince && !seen.has(event.sequence)).sort((first, second) => sequence(first) < sequence(second) ? -1 : sequence(first) > sequence(second) ? 1 : 0);
164
+ const changes = workspace && cursor !== void 0 ? await readChanges(input.archive, input.coordinates, String(cursor)) : void 0;
165
+ const latest = new Map();
166
+ for (const event of [...read.events, ...changes?.events ?? []]) {
167
+ const known = latest.get(event.eventId);
168
+ if (known === void 0 || sequence(event) > sequence(known)) latest.set(event.eventId, event);
169
+ }
170
+ const unread = [...latest.values()].filter((event) => cursor === void 0 || sequence(event) > cursor && !seen.has(event.sequence) || overlapSince !== void 0 && sequence(event) >= 0n && Date.parse(event.storedAt) >= overlapSince && !seen.has(event.sequence)).sort((first, second) => sequence(first) < sequence(second) ? -1 : sequence(first) > sequence(second) ? 1 : 0);
139
171
  const delivered = new Set(input.delivered);
140
- const messages = collapseChatEvents(unread.filter((event) => since === void 0 || Date.parse(event.storedAt) >= since)).filter((event) => (event.kind === "inbound" || event.kind === "outbound" && ["completed", "sent"].includes(event.status ?? "")) && !(event.kind === "inbound" && event.messageId !== null && delivered.has(event.messageId) && !edited(event)) && (bootstrap || event.sessionId !== input.sessionId)).sort((first, second) => sequence(first) < sequence(second) ? 1 : -1);
172
+ const delivering = new Set(input.delivering);
173
+ const messages = collapseChatEvents(unread.filter((event) => since === void 0 || Date.parse(event.storedAt) >= since)).filter((event) => {
174
+ const changed = event.kind === "inbound" && (edited(event) || event.deleted === true);
175
+ return (event.kind === "inbound" || event.kind === "outbound" && ["completed", "sent"].includes(event.status ?? "")) && !(event.kind === "inbound" && event.messageId !== null && delivering.has(event.messageId)) && (changed || !(event.kind === "inbound" && event.messageId !== null && delivered.has(event.messageId)) && (bootstrap || event.sessionId !== input.sessionId));
176
+ }).sort((first, second) => sequence(first) < sequence(second) ? 1 : -1);
141
177
  const budget = bootstrap ? BOOTSTRAP_CHARACTERS : TURN_CHARACTERS;
142
178
  const selected = [];
143
179
  let characters = 2;
@@ -151,13 +187,15 @@ async function readChatContext(input) {
151
187
  const omitted = selected.length < messages.length || !bootstrap && !read.complete;
152
188
  const guidanceDigest = input.guidance === void 0 ? void 0 : digest(input.guidance);
153
189
  const blocks = [...input.guidance !== void 0 && guidanceDigest !== input.from.guidance ? [input.guidance] : [], ...selected.length === 0 ? [] : [`<chat_messages${omitted ? " earlier_omitted=\"true\"" : ""}>\n${JSON.stringify(selected.reverse())}\n</chat_messages>`]];
154
- const highest = unread.reduce((current, event) => sequence(event) > current ? sequence(event) : current, cursor ?? 0n);
190
+ const newestRead = unread.reduce((current, event) => sequence(event) > current ? sequence(event) : current, cursor ?? 0n);
191
+ const highest = changes === void 0 || changes.complete || changes.through >= newestRead ? newestRead : changes.through;
155
192
  const newest = Math.max(...unread.map((event) => Date.parse(event.storedAt)).filter((at) => !Number.isNaN(at)));
156
193
  return {
157
194
  content: blocks.length === 0 ? null : blocks.join("\n"),
158
195
  bookmark: {
159
196
  start: unread.length === 0 ? start : {
160
197
  cursor: String(highest),
198
+ ...workspace ? { store: "workspace" } : {},
161
199
  overlapSince: new Date(Number.isFinite(newest) ? Math.max(newest - OVERLAP_MS, overlapSince ?? Number.NEGATIVE_INFINITY) : overlapSince ?? input.now.getTime() - 6e5).toISOString()
162
200
  },
163
201
  seen: [...new Set([...seen, ...unread.map((event) => event.sequence)])].slice(-500),
@@ -211,6 +249,7 @@ function chatContextHook(archive = chatArchive(), reviews, holding = () => true)
211
249
  coordinates,
212
250
  from,
213
251
  sessionId: context.session.id,
252
+ delivering: deliveredMessages(context.view, turnId),
214
253
  delivered: [
215
254
  ...from.delivered,
216
255
  ...deliveredMessages(context.view, bootstrap ? turnId : void 0),
@@ -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
- import { chatEvent } from "./chat-archive.mjs";
7
+ import { a as chatEvent, f as storeOf } from "../../_chunks/chat-archive-BCPLSZeK.mjs";
8
8
  async function recordChatMessage(archive, message) {
9
9
  const { eventId } = message;
10
10
  return archive.append(chatEvent({
@@ -72,6 +72,18 @@ async function recordHandledMessage(archive, input) {
72
72
  text: input.text,
73
73
  ...input.files === void 0 ? {} : { files: input.files }
74
74
  });
75
+ const store = await storeOf(archive);
76
+ if (store !== void 0) {
77
+ await store.change({
78
+ channel: chat.channel,
79
+ chatId: chat.chatId,
80
+ messageId: input.messageId,
81
+ change: "disposition",
82
+ disposition: "skipped",
83
+ reason: "chat_handled"
84
+ });
85
+ return;
86
+ }
75
87
  await archive.append(chatEvent({
76
88
  eventId: `${eventId}:decision`,
77
89
  provider: chat.channel,
@@ -66,4 +66,6 @@ export declare function chatRecorder(archive?: ChatArchive,
66
66
  * held reply is not sent, so the recorder records no outbound message for them.
67
67
  */
68
68
  reviewed?: (principal: HookContext["session"]["auth"]["current"]) => boolean): (event: HookEvent, context: HookContext) => Promise<void>;
69
+ /** The store's id of a message eve delivered to a session, which has no provider id of its own. */
70
+ export declare function deliveredMessageId(sessionId: string, deliveryId: string): string;
69
71
  export {};