@segmentstream/agent 0.52.1 → 0.54.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 (98) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/README.md +17 -4
  3. package/dist/_chunks/{build-metadata-DJ3WHCte.mjs → build-metadata-2TyBXJEt.mjs} +1 -1
  4. package/dist/_chunks/{principal-JoaOmdFL.mjs → principal-DUla0Xge.mjs} +53 -23
  5. package/dist/extension/config.d.ts +23 -1
  6. package/dist/extension/config.mjs +37 -3
  7. package/dist/extension/connections/ontology.mjs +1 -1
  8. package/dist/extension/hooks/authorization.mjs +1 -1
  9. package/dist/extension/hooks/guest-usage.d.ts +3 -0
  10. package/dist/extension/hooks/guest-usage.mjs +11 -0
  11. package/dist/extension/instructions/persona.mjs +1 -1
  12. package/dist/extension/instructions.md +8 -5
  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.d.ts +84 -0
  16. package/dist/extension/lib/attachments-send.mjs +88 -0
  17. package/dist/extension/lib/attachments.d.ts +1 -2
  18. package/dist/extension/lib/attachments.mjs +1 -1
  19. package/dist/extension/lib/build-metadata.mjs +1 -1
  20. package/dist/extension/lib/chat-address.d.ts +11 -0
  21. package/dist/extension/lib/chat-address.mjs +1 -1
  22. package/dist/extension/lib/chat-archive.d.ts +35 -0
  23. package/dist/extension/lib/chat-archive.mjs +37 -1
  24. package/dist/extension/lib/chat-context.d.ts +1 -1
  25. package/dist/extension/lib/chat-context.mjs +4 -3
  26. package/dist/extension/lib/chat-recorder.mjs +3 -2
  27. package/dist/extension/lib/confirmations.d.ts +6 -1
  28. package/dist/extension/lib/confirmations.mjs +1 -1
  29. package/dist/extension/lib/email/attachments-send.d.ts +43 -0
  30. package/dist/extension/lib/email/attachments-send.mjs +130 -0
  31. package/dist/extension/lib/email/channel.d.ts +7 -1
  32. package/dist/extension/lib/email/channel.mjs +222 -53
  33. package/dist/extension/lib/email/gmail.d.ts +22 -6
  34. package/dist/extension/lib/email/gmail.mjs +101 -5
  35. package/dist/extension/lib/email/message.d.ts +19 -0
  36. package/dist/extension/lib/email/message.mjs +22 -1
  37. package/dist/extension/lib/guest-usage.d.ts +53 -0
  38. package/dist/extension/lib/guest-usage.mjs +52 -0
  39. package/dist/extension/lib/inbound-media/files.mjs +1 -1
  40. package/dist/extension/lib/inbound-media/index.mjs +1 -1
  41. package/dist/extension/lib/ontology-connection.mjs +1 -1
  42. package/dist/extension/lib/ontology-file-call.mjs +2 -1
  43. package/dist/extension/lib/ontology-tools.d.ts +2 -0
  44. package/dist/extension/lib/ontology-tools.mjs +1 -1
  45. package/dist/extension/lib/review/hold.mjs +1 -1
  46. package/dist/extension/lib/review/judge.mjs +2 -2
  47. package/dist/extension/lib/review/reply.mjs +1 -1
  48. package/dist/extension/lib/role-skill.mjs +1 -1
  49. package/dist/extension/lib/runtime-envelope.mjs +1 -1
  50. package/dist/extension/lib/sent-files.d.ts +29 -9
  51. package/dist/extension/lib/sent-files.mjs +36 -14
  52. package/dist/extension/lib/slack/adapter.mjs +1 -1
  53. package/dist/extension/lib/slack/attachments-send.d.ts +6 -14
  54. package/dist/extension/lib/slack/attachments-send.mjs +128 -170
  55. package/dist/extension/lib/stored-files.mjs +1 -1
  56. package/dist/extension/lib/telegram/adapter.mjs +2 -2
  57. package/dist/extension/lib/telegram/attachment-description.mjs +1 -1
  58. package/dist/extension/lib/telegram/attachments-send.mjs +9 -12
  59. package/dist/extension/lib/telegram/callbacks.mjs +1 -1
  60. package/dist/extension/lib/telegram/chat-archive.mjs +1 -1
  61. package/dist/extension/lib/telegram/confirmations.mjs +2 -2
  62. package/dist/extension/lib/telegram/customer-text.mjs +1 -1
  63. package/dist/extension/lib/telegram/files.mjs +1 -1
  64. package/dist/extension/lib/telegram/health.mjs +1 -1
  65. package/dist/extension/lib/telegram/held-approvals.mjs +1 -1
  66. package/dist/extension/lib/telegram/inbound-request.mjs +1 -1
  67. package/dist/extension/lib/telegram/inbound.mjs +1 -1
  68. package/dist/extension/lib/telegram/lifecycle.mjs +2 -2
  69. package/dist/extension/lib/telegram/principal.mjs +1 -1
  70. package/dist/extension/lib/telegram/session-recovery.mjs +1 -1
  71. package/dist/extension/lib/telegram/silent.mjs +1 -1
  72. package/dist/extension/lib/telegram/structured.mjs +1 -1
  73. package/dist/extension/lib/telegram/turn-errors.mjs +1 -1
  74. package/dist/extension/lib/telegram/workspace-action.mjs +1 -1
  75. package/dist/extension/lib/web/auth.d.ts +18 -4
  76. package/dist/extension/lib/web/auth.mjs +1 -1
  77. package/dist/extension/lib/web/channel.d.ts +10 -3
  78. package/dist/extension/lib/web/channel.mjs +10 -3
  79. package/dist/extension/lib/whatsapp/adapter.mjs +1 -1
  80. package/dist/extension/lib/whatsapp/attachments-send.d.ts +35 -0
  81. package/dist/extension/lib/whatsapp/attachments-send.mjs +117 -0
  82. package/dist/extension/lib/whatsapp/files.mjs +1 -1
  83. package/dist/extension/lib/workspace-source.mjs +1 -1
  84. package/dist/extension/model.mjs +1 -1
  85. package/dist/extension/tools/attachments_discard.mjs +1 -1
  86. package/dist/extension/tools/attachments_list.mjs +1 -1
  87. package/dist/extension/tools/attachments_promote.mjs +1 -1
  88. package/dist/extension/tools/attachments_read.mjs +1 -1
  89. package/dist/extension/tools/attachments_send.mjs +18 -7
  90. package/dist/extension/tools/attachments_stage.mjs +1 -1
  91. package/dist/extension/tools/attachments_table.mjs +1 -1
  92. package/dist/extension/tools/questions_ask.mjs +1 -1
  93. package/dist/extension/tools/unanswered.d.ts +2 -0
  94. package/dist/extension/tools/unanswered.mjs +39 -0
  95. package/dist/extension/tools/workspace_source.mjs +1 -1
  96. package/dist/tools/index.d.ts +1 -0
  97. package/dist/tools/index.mjs +2 -1
  98. package/package.json +2 -2
@@ -0,0 +1,84 @@
1
+ import type { SessionAuthContext } from "eve/context";
2
+ import { type AttachmentOwner } from "./attachments.js";
3
+ import { type ChatAddress } from "./chat-address.js";
4
+ import { type Environment } from "./environment.js";
5
+ import { type RuntimeToken } from "./runtime-token.js";
6
+ import type { SendAttachmentsInput } from "./telegram/attachments-send.js";
7
+ /**
8
+ * What `attachments_send` does the same way in every channel. The channel must be configured in
9
+ * production and the turn must have its chat; the files are read as the turn's member in that
10
+ * chat; nothing throws: each failure is logged with a reference for operators and answered as a
11
+ * refusal code with the workspace's attachment failure text, the whole call's when nothing could
12
+ * be tried and each file's otherwise. Files are never held for review, and the chat recorder keeps
13
+ * the call and its answer. A channel supplies only how it sends what it read.
14
+ */
15
+ /** Why one requested file did not reach the chat. */
16
+ export interface AttachmentSendFailure {
17
+ readonly error: string;
18
+ /** The workspace's attachment failure text, which the person may be shown. */
19
+ readonly detail: string;
20
+ /** The logged diagnostic's reference. */
21
+ readonly reference: string;
22
+ /** The ontology's status for a file it did not grant, and whether a later try may pass. */
23
+ readonly status?: number;
24
+ readonly retryable?: boolean;
25
+ readonly requestId?: string;
26
+ }
27
+ /** The answer when nothing was tried: the channel is not set up or the turn is not in its chat. */
28
+ export interface AttachmentSendRefusal {
29
+ readonly error: string;
30
+ readonly detail: string;
31
+ readonly reference: string;
32
+ }
33
+ /** Logs a redacted diagnostic for operators and answers its reference. */
34
+ export type AttachmentReport = (operation: string, error: unknown, metadata: Readonly<Record<string, unknown>>, secrets: ReadonlySet<string>) => string;
35
+ /** What a channel's sender gets once the turn may send files. */
36
+ export interface AttachmentSendContext {
37
+ readonly input: SendAttachmentsInput;
38
+ readonly chat: ChatAddress;
39
+ readonly connection: string;
40
+ readonly owner: AttachmentOwner;
41
+ /** The deployment's own origin, where the ontology service answers. */
42
+ readonly origin: string;
43
+ readonly environment: Environment;
44
+ readonly principal: SessionAuthContext;
45
+ readonly fetch: typeof fetch;
46
+ /** The deployment's runtime token; each value is kept in `secrets`. */
47
+ readonly token: () => Promise<string>;
48
+ /** Values no diagnostic may show, such as tokens and grant URLs. */
49
+ readonly secrets: Set<string>;
50
+ /** Logs `error` under `operation` and answers the failure a file's result carries. */
51
+ readonly failed: (error: unknown, operation: string, metadata?: Readonly<Record<string, unknown>>) => AttachmentSendFailure;
52
+ }
53
+ /**
54
+ * A file's failure: its refusal code, the workspace's text with the logged reference and, for a
55
+ * file the ontology did not grant, its status, whether a later try may pass and its request id.
56
+ */
57
+ export declare function attachmentFailure(input: {
58
+ readonly error: unknown;
59
+ readonly reference: string;
60
+ readonly locale: string | undefined;
61
+ /** The code of a failure that names none. */
62
+ readonly fallback?: string;
63
+ }): AttachmentSendFailure;
64
+ /**
65
+ * Sends the requested files in the turn's chat of `provider` through the channel's connection, by
66
+ * `send`, after the checks every channel makes: production, the configured connection, the
67
+ * turn's chat on the provider and a member to read the files as.
68
+ */
69
+ export declare function sendStoredAttachments<Result>(options: {
70
+ readonly input: SendAttachmentsInput;
71
+ readonly principal: SessionAuthContext | null;
72
+ readonly sessionId: string;
73
+ /** The channel's connection, from `channels.<provider>.connection`. */
74
+ readonly connection: string | undefined;
75
+ /** The provider of the chat the channel sends to; refusals name it. */
76
+ readonly provider: ChatAddress["provider"];
77
+ /** The channel's name, as `channels` and refusals give it: `Slack`, `email`, `WhatsApp`. */
78
+ readonly channel: string;
79
+ readonly report: AttachmentReport;
80
+ readonly send: (context: AttachmentSendContext) => Promise<Result>;
81
+ readonly environment?: Environment;
82
+ readonly token?: RuntimeToken;
83
+ readonly fetch?: typeof fetch;
84
+ }): Promise<Result | AttachmentSendRefusal>;
@@ -0,0 +1,88 @@
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 { attachmentOwner } from "./attachment-tools.mjs";
8
+ import { Et as failureText, _ as AttachmentError, gt as chatAddressOf } from "../../_chunks/principal-DUla0Xge.mjs";
9
+ import { appOrigin, channelsEnabled } from "./environment.mjs";
10
+ import { transientFileStatus } from "./file-grant.mjs";
11
+ import { runtimeToken } from "./runtime-token.mjs";
12
+ import { StoredFileError } from "./sent-files.mjs";
13
+ import { confirmationLocale } from "./telegram/confirmation-text.mjs";
14
+ function failureCode(error, fallback) {
15
+ return error instanceof AttachmentError ? error.code : fallback;
16
+ }
17
+ function attachmentFailure(input) {
18
+ const { error } = input;
19
+ const stored = error instanceof StoredFileError ? error : void 0;
20
+ return {
21
+ error: failureCode(error, input.fallback ?? "send_failed"),
22
+ detail: failureText(input.reference, "attachment", input.locale),
23
+ reference: input.reference,
24
+ ...error instanceof AttachmentError && error.status !== void 0 ? {
25
+ status: error.status,
26
+ retryable: transientFileStatus(error.status)
27
+ } : {},
28
+ ...stored?.requestId === void 0 ? {} : { requestId: stored.requestId }
29
+ };
30
+ }
31
+ async function sendStoredAttachments(options) {
32
+ const environment = options.environment ?? process.env;
33
+ const principal = options.principal;
34
+ const locale = confirmationLocale(principal);
35
+ const secrets = new Set();
36
+ const refuse = (error, diagnostic) => {
37
+ const reference = options.report("attachment_send_refused", typeof diagnostic === "string" ? {
38
+ error,
39
+ diagnostic
40
+ } : diagnostic, {}, secrets);
41
+ return {
42
+ error,
43
+ detail: failureText(reference, "attachment", locale),
44
+ reference
45
+ };
46
+ };
47
+ const chat = chatAddressOf(principal);
48
+ if (!channelsEnabled(environment)) return refuse("channels_disabled", "Attachments can be sent only in production.");
49
+ if (options.connection === void 0) return refuse("unsupported", `The ${options.channel} channel is not configured.`);
50
+ if (principal === null || chat?.provider !== options.provider) return refuse(`no_${options.provider}_chat`, `This turn has no ${options.channel} chat.`);
51
+ let owner;
52
+ try {
53
+ owner = attachmentOwner({
54
+ principal,
55
+ sessionId: options.sessionId
56
+ });
57
+ } catch (error) {
58
+ const reference = options.report("attachment_owner_refused", error, {}, secrets);
59
+ return {
60
+ error: "forbidden",
61
+ detail: failureText(reference, "attachment", locale),
62
+ reference
63
+ };
64
+ }
65
+ const runtimeToken$1 = options.token ?? runtimeToken;
66
+ return options.send({
67
+ input: options.input,
68
+ chat,
69
+ connection: options.connection,
70
+ owner,
71
+ origin: appOrigin(environment),
72
+ environment,
73
+ principal,
74
+ fetch: options.fetch ?? fetch,
75
+ token: async () => {
76
+ const value = await runtimeToken$1();
77
+ secrets.add(value);
78
+ return value;
79
+ },
80
+ secrets,
81
+ failed: (error, operation, metadata = {}) => attachmentFailure({
82
+ error,
83
+ reference: options.report(operation, error, metadata, secrets),
84
+ locale
85
+ })
86
+ });
87
+ }
88
+ export { attachmentFailure, sendStoredAttachments };
@@ -11,13 +11,12 @@ import type { RuntimeToken } from "./runtime-token.js";
11
11
  export declare const MAXIMUM_ATTACHMENT_BYTES: number;
12
12
  /** How long an attachment stays available. */
13
13
  export declare const ATTACHMENT_TTL_HOURS = 24;
14
- export declare const CHAT_HEADER = "X-SegmentStream-Agent-Chat";
14
+ export { CHAT_HEADER, SESSION_HEADER } from "./chat-address.js";
15
15
  /**
16
16
  * @legacy agent.conversation-header
17
17
  * The chat's header for ontology services built before it took the name chat; sent alongside.
18
18
  */
19
19
  export declare const EARLIER_CHAT_HEADER = "X-SegmentStream-Agent-Conversation";
20
- export declare const SESSION_HEADER = "X-SegmentStream-Agent-Session";
21
20
  /** The URL protocol of a file part that names a stored attachment instead of a Telegram file. */
22
21
  export declare const ATTACHMENT_URL_PROTOCOL = "segmentstream-attachment:";
23
22
  /** Where an attachment comes from: a channel's message, or the agent's sandbox. */
@@ -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, v as CHAT_HEADER, y as EARLIER_CHAT_HEADER, b as MAXIMUM_ATTACHMENT_BYTES, x as SESSION_HEADER, S as agentAttachments, C as attachmentUrl, w as fetchStoredAttachment, T as parseAttachmentUrl } from "../../_chunks/principal-JoaOmdFL.mjs";
7
+ export { h as ATTACHMENT_TTL_HOURS, g as ATTACHMENT_URL_PROTOCOL, _ as AttachmentError, mt as CHAT_HEADER, v as EARLIER_CHAT_HEADER, y as MAXIMUM_ATTACHMENT_BYTES, ht as SESSION_HEADER, b as agentAttachments, x as attachmentUrl, S as fetchStoredAttachment, C as parseAttachmentUrl } from "../../_chunks/principal-DUla0Xge.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-DJ3WHCte.mjs";
7
+ export { t as agentBuild } from "../../_chunks/build-metadata-2TyBXJEt.mjs";
@@ -12,6 +12,10 @@ export interface ChatAddress {
12
12
  readonly kind: "private" | "group";
13
13
  readonly peer?: string;
14
14
  }
15
+ /** The header that names the chat an ontology request comes from: `<provider>:<chat id>`. */
16
+ export declare const CHAT_HEADER = "X-SegmentStream-Agent-Chat";
17
+ /** The header that names the agent's session in that chat. */
18
+ export declare const SESSION_HEADER = "X-SegmentStream-Agent-Session";
15
19
  /** The session attribute that carries a non-Telegram channel's chat, as JSON. */
16
20
  export declare const CHAT_ATTRIBUTE = "segmentstreamChat";
17
21
  /** A channel's principal with the chat its message came from. */
@@ -22,6 +26,13 @@ export declare function withChatAddress(principal: SessionAuthContext, chat: Cha
22
26
  * carried, so sessions from before this attribute keep working.
23
27
  */
24
28
  export declare function chatAddressOf(principal?: SessionAuthContext | null): ChatAddress | undefined;
29
+ /**
30
+ * The headers that name the chat a session's principal speaks from, and the agent's session there,
31
+ * as the chat archive names them. The ontology keeps them with the history of every action the
32
+ * agent runs for the principal, a guest's included, so that a record leads back to its chat; a web
33
+ * chat counts only as the member's or guest's own. A task has no chat, and sends none.
34
+ */
35
+ export declare function chatHeaders(principal: SessionAuthContext | null | undefined, sessionId?: string): Record<string, string>;
25
36
  /**
26
37
  * Whether a destination is the chat itself. A private destination names its person, not
27
38
  * the chat: a Slack direct message is `D…` while its person is `U…`.
@@ -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 { pt as CHAT_ATTRIBUTE, mt as chatAddressOf, ht as isSameChat, gt as withChatAddress } from "../../_chunks/principal-JoaOmdFL.mjs";
7
+ export { pt as CHAT_ATTRIBUTE, mt as CHAT_HEADER, ht as SESSION_HEADER, gt as chatAddressOf, _t as chatHeaders, vt as isSameChat, yt as withChatAddress } from "../../_chunks/principal-DUla0Xge.mjs";
@@ -70,7 +70,42 @@ export interface ChatArchive {
70
70
  readonly senderId?: string;
71
71
  readonly messageId?: string;
72
72
  }): Promise<ChatPage>;
73
+ /**
74
+ * The channel's replies still to deliver, in every chat of `provider`, newest first: reply
75
+ * operations (`operationId` `reply:<key>`) whose newest state is `requested`. Archives that
76
+ * predate it have none.
77
+ */
78
+ /**
79
+ * A channel's replies still `requested`, newest first, of those requested no later than
80
+ * `requestedBefore` (an ISO time): the ones due for another attempt.
81
+ */
82
+ pendingReplies?(input: {
83
+ readonly provider: string;
84
+ readonly limit: number;
85
+ readonly requestedBefore?: string;
86
+ }): Promise<ChatPage>;
73
87
  }
88
+ /** The archive operation of a channel's reply, which its states share: see {@link replyEvent}. */
89
+ export declare function replyOperation(key: string): string;
90
+ /**
91
+ * One state of a channel's reply in its chat (`docs/agent-chat-storage.md`, "Channel replies"):
92
+ * `requested` before the channel sends it, then `sent` with the provider's message id, or `failed`
93
+ * when the provider refused it or it waited too long. The chat shows a reply once it is sent; a
94
+ * `requested` one is still to deliver, and the channel tries it again later.
95
+ */
96
+ export declare function replyEvent(input: {
97
+ readonly key: string;
98
+ readonly provider: string;
99
+ readonly chatId: string;
100
+ readonly threadId: string | null;
101
+ readonly participantIds: ReadonlyArray<string>;
102
+ readonly sessionId: string | null;
103
+ readonly turnId: string | null;
104
+ readonly text: string;
105
+ readonly status: "requested" | "sent" | "failed";
106
+ readonly messageId?: string;
107
+ readonly at?: string;
108
+ }): ChatEvent;
74
109
  /**
75
110
  * One chat or forum topic of the archive, newest first. The archive reads every topic when no topic
76
111
  * is named, so a message without a topic, such as one in a forum's General topic, collects the rows
@@ -7,6 +7,29 @@ __eveCreateRequire(import.meta.url);
7
7
  import { proxyEnvironment } from "./environment.mjs";
8
8
  import { runtimeToken } from "./runtime-token.mjs";
9
9
  import { r as workflowValue } from "../../_chunks/workflow-serializable-DU7WeCIW.mjs";
10
+ function replyOperation(key) {
11
+ return `reply:${key}`;
12
+ }
13
+ function replyEvent(input) {
14
+ return chatEvent({
15
+ eventId: `${input.provider}:reply:${input.key}:${input.status}`,
16
+ operationId: replyOperation(input.key),
17
+ provider: input.provider,
18
+ chatId: input.chatId,
19
+ chatType: "private",
20
+ threadId: input.threadId,
21
+ participantIds: input.participantIds,
22
+ sessionId: input.sessionId,
23
+ turnId: input.turnId,
24
+ kind: "outbound",
25
+ text: input.text,
26
+ senderId: "agent",
27
+ senderIsBot: true,
28
+ status: input.status,
29
+ messageId: input.messageId ?? null,
30
+ ...input.at === void 0 ? {} : { at: input.at }
31
+ });
32
+ }
10
33
  const TOPIC_PAGES = 5;
11
34
  const TOPIC_PAGE_SIZE = 100;
12
35
  async function topicContext(archive, input) {
@@ -112,6 +135,19 @@ function chatArchive(input = {}) {
112
135
  groups: includeDecisions === true,
113
136
  admin: false
114
137
  }
138
+ }),
139
+ pendingReplies: async ({ provider, limit, requestedBefore }) => await call("search", {
140
+ search: {
141
+ provider,
142
+ pending: true,
143
+ limit,
144
+ ...requestedBefore === void 0 ? {} : { to: requestedBefore }
145
+ },
146
+ reader: {
147
+ participantId: null,
148
+ groups: false,
149
+ admin: false
150
+ }
115
151
  })
116
152
  };
117
153
  }
@@ -126,4 +162,4 @@ function summarizeArguments(value) {
126
162
  };
127
163
  return JSON.stringify(workflowValue(visit(value, 0), { boundary: "chat arguments" })).slice(0, 4e3);
128
164
  }
129
- export { chatArchive, chatEvent, collapseChatEvents, sessionFailureEventId, summarizeArguments, topicContext };
165
+ export { chatArchive, chatEvent, collapseChatEvents, replyEvent, replyOperation, sessionFailureEventId, summarizeArguments, topicContext };
@@ -84,7 +84,7 @@ export declare function readChatContext(input: {
84
84
  readonly guidance?: string;
85
85
  readonly now: Date;
86
86
  }): Promise<ChatContextRead>;
87
- /** The Telegram chat a session belongs to; agent tasks and other channels have none. */
87
+ /** The Telegram or email chat a session belongs to; agent tasks and other channels have none. */
88
88
  export declare function chatOf(context: {
89
89
  readonly session: {
90
90
  readonly auth: HookContext["session"]["auth"];
@@ -7,7 +7,7 @@ __eveCreateRequire(import.meta.url);
7
7
  import { agentTaskIdOf } from "./agent-task.mjs";
8
8
  import { chatCoordinates } from "./chat-recorder.mjs";
9
9
  import { chatArchive, collapseChatEvents, topicContext } from "./chat-archive.mjs";
10
- import { Tt as reportTelegramError } from "../../_chunks/principal-JoaOmdFL.mjs";
10
+ import { Ot as reportTelegramError } from "../../_chunks/principal-DUla0Xge.mjs";
11
11
  import { createHash } from "node:crypto";
12
12
  import { deliveries, runs, turns } from "eve/events";
13
13
  import { defineState } from "eve/context";
@@ -61,7 +61,7 @@ function entryOf(event) {
61
61
  return {
62
62
  at: event.at,
63
63
  sender: typeof author === "string" ? author : event.senderName ?? event.senderId,
64
- ...event.kind === "outbound" || event.senderIsBot ? { bot: true } : {},
64
+ ...event.kind === "outbound" && !event.senderIsBot ? { staff: true } : event.kind === "outbound" || event.senderIsBot ? { bot: true } : {},
65
65
  text: event.text?.slice(0, MAXIMUM_TEXT) ?? null,
66
66
  ...event.attachments.length === 0 ? {} : { attachments: event.attachments.slice(0, 10) },
67
67
  ...Array.isArray(files) && files.length > 0 ? { files: files.slice(0, 10) } : {},
@@ -142,9 +142,10 @@ function legacySince(context, turnId) {
142
142
  const at = started.length === 0 ? context.now.getTime() : Math.max(...started);
143
143
  return new Date(at - LEGACY_OVERLAP_MS).toISOString();
144
144
  }
145
+ const CONTEXT_CHANNELS = new Set(["telegram", "email"]);
145
146
  function chatOf(context) {
146
147
  const coordinates = chatCoordinates(context);
147
- return coordinates === void 0 || coordinates.provider !== "telegram" || agentTaskIdOf(context.session.auth.current) !== void 0 ? void 0 : coordinates;
148
+ return coordinates === void 0 || !CONTEXT_CHANNELS.has(coordinates.provider) || agentTaskIdOf(context.session.auth.current) !== void 0 ? void 0 : coordinates;
148
149
  }
149
150
  function chatContextHook(archive = chatArchive()) {
150
151
  return {
@@ -7,7 +7,7 @@ __eveCreateRequire(import.meta.url);
7
7
  import { n as contentText, t as CONTENT_CAPS } from "../../_chunks/content-cDtVnr8Y.mjs";
8
8
  import { chatArchive, chatEvent, sessionFailureEventId, summarizeArguments } from "./chat-archive.mjs";
9
9
  import { agentTaskIdOf } from "./agent-task.mjs";
10
- import { i as memberIdOf, mt as chatAddressOf, ot as guestIdOf } from "../../_chunks/principal-JoaOmdFL.mjs";
10
+ import { gt as chatAddressOf, i as memberIdOf, ot as guestIdOf } from "../../_chunks/principal-DUla0Xge.mjs";
11
11
  import { parseAddress } from "./telegram/sessions.mjs";
12
12
  import { completionKind } from "./telegram/silent.mjs";
13
13
  import { recordModelServiceAlert } from "./model-service-alert.mjs";
@@ -70,6 +70,7 @@ function chatCoordinates(context) {
70
70
  senderId: principal?.subject ?? null
71
71
  };
72
72
  }
73
+ const RECORDS_REPLIES = new Set(["telegram", "email"]);
73
74
  const UNADDRESSED_SESSIONS_REMEMBERED = 1e3;
74
75
  function reportUnaddressed(event, context, reported) {
75
76
  const sessionId = context.session.id;
@@ -172,7 +173,7 @@ function chatRecorder(archive = chatArchive(), reviewed = () => false) {
172
173
  phase: event.data.phase
173
174
  })
174
175
  }));
175
- if (coordinates.provider !== "telegram" && !silent && !reviewed(context.session.auth.current)) await archive.append(chatEvent({
176
+ if (!RECORDS_REPLIES.has(coordinates.provider) && !silent && !reviewed(context.session.auth.current)) await archive.append(chatEvent({
176
177
  ...base,
177
178
  eventId: `${eventId}:outbound`,
178
179
  kind: "outbound",
@@ -19,8 +19,13 @@ export interface ActionAnnotations {
19
19
  /** Safety comes from the authenticated ontology, never from the name or model prose. */
20
20
  export declare function needsConfirmation(labels: ActionAnnotations): boolean;
21
21
  export declare function inputHash(input: unknown): string;
22
+ /**
23
+ * A confirmation requested by a member, or by a guest whom the ontology lets confirm: only they
24
+ * may confirm or cancel it. A member's names `memberId`; a guest's names `guestId` alone.
25
+ */
22
26
  export interface Confirmation {
23
- readonly memberId: string;
27
+ readonly memberId?: string;
28
+ readonly guestId?: string;
24
29
  readonly action: string;
25
30
  readonly inputHash: string;
26
31
  readonly expiresAt: number;
@@ -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 { F as CONFIRMATION_TTL_MS, I as actionApproval, L as confirmations, R as inputHash, z as needsConfirmation } from "../../_chunks/principal-JoaOmdFL.mjs";
7
+ export { N as CONFIRMATION_TTL_MS, P as actionApproval, F as confirmations, I as inputHash, L as needsConfirmation } from "../../_chunks/principal-DUla0Xge.mjs";
@@ -0,0 +1,43 @@
1
+ import type { SessionAuthContext } from "eve/context";
2
+ import { type AttachmentSendFailure, type AttachmentSendRefusal } from "../attachments-send.js";
3
+ import { type Environment } from "../environment.js";
4
+ import type { RuntimeToken } from "../runtime-token.js";
5
+ import type { SendAttachmentsInput } from "../telegram/attachments-send.js";
6
+ import { type Gmail } from "./gmail.js";
7
+ /**
8
+ * `attachments_send` in an email chat: the stored files go in one reply in the person's Gmail
9
+ * thread, from the channel's mailbox, as the channel's text replies go: under the thread's last
10
+ * message, marked `Auto-Submitted: auto-replied`, and named by a key of the session and the tool
11
+ * call, so a call run again finds the reply it sent rather than sending it twice. The caption is
12
+ * the reply's text. The checks and failures are every channel's (`../attachments-send.ts`).
13
+ */
14
+ /**
15
+ * The most bytes of files one reply carries, together: below the 25 MB Gmail takes, with room for
16
+ * the text and the encoding. A message larger than one proxied request is uploaded in chunks.
17
+ */
18
+ export declare const MAXIMUM_EMAIL_ATTACHMENT_BYTES: number;
19
+ /** What became of one requested file. */
20
+ export interface EmailSentFile extends Partial<AttachmentSendFailure> {
21
+ readonly id: string;
22
+ readonly filename: string;
23
+ /** Gmail's id of the reply that carries it. */
24
+ readonly emailMessageId?: string;
25
+ }
26
+ type EmailSendResult = {
27
+ readonly files: ReadonlyArray<EmailSentFile>;
28
+ } | AttachmentSendRefusal;
29
+ export declare function sendEmailAttachments(options: {
30
+ readonly input: SendAttachmentsInput;
31
+ readonly principal: SessionAuthContext | null;
32
+ readonly sessionId: string;
33
+ /** The tool call: with the session, it names the reply in the thread. */
34
+ readonly callId: string;
35
+ /** The workspace's `channels.email.connection`. */
36
+ readonly connection: string | undefined;
37
+ readonly environment?: Environment;
38
+ readonly token?: RuntimeToken;
39
+ readonly fetch?: typeof fetch;
40
+ /** Tests pass a fake mailbox. */
41
+ readonly gmail?: Gmail;
42
+ }): Promise<EmailSendResult>;
43
+ export {};
@@ -0,0 +1,130 @@
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 { _ as AttachmentError } from "../../../_chunks/principal-DUla0Xge.mjs";
8
+ import { sendStoredAttachments } from "../attachments-send.mjs";
9
+ import { ConnectionProxyError, connectionProxy } from "../connection-proxy.mjs";
10
+ import { redactDiagnostic } from "../diagnostics.mjs";
11
+ import { proxyEnvironment } from "../environment.mjs";
12
+ import { StoredFileError, fetchStoredFile } from "../sent-files.mjs";
13
+ import { GmailError, gmail, replyKeyOf } from "./gmail.mjs";
14
+ import { randomUUID } from "node:crypto";
15
+ const MAXIMUM_EMAIL_ATTACHMENT_BYTES = 20971520;
16
+ const TOO_LARGE = `One email carries at most ${MAXIMUM_EMAIL_ATTACHMENT_BYTES / 1024 / 1024} MiB of files.`;
17
+ function reportEmailError(operation, error, secrets) {
18
+ const reference = randomUUID();
19
+ console.error("[segmentstream] email delivery diagnostic", {
20
+ operation,
21
+ reference,
22
+ error: redactDiagnostic(error, secrets)
23
+ });
24
+ return reference;
25
+ }
26
+ function sendFailure(error) {
27
+ const code = error instanceof GmailError ? error.status === 413 ? "too_large" : error.status === 401 || error.status === 403 ? "forbidden" : "send_failed" : error instanceof ConnectionProxyError && error.code === "invalid_request" ? "too_large" : "send_failed";
28
+ return new AttachmentError({
29
+ code,
30
+ message: "Gmail did not take the reply.",
31
+ cause: error
32
+ });
33
+ }
34
+ async function sendEmailAttachments(options) {
35
+ return sendStoredAttachments({
36
+ ...options,
37
+ provider: "email",
38
+ channel: "email",
39
+ report: (operation, error, _metadata, secrets) => reportEmailError(operation, error, secrets),
40
+ async send(context) {
41
+ const { input, chat, owner, origin, fetch, token, secrets, failed } = context;
42
+ const results = input.documentIds.map(({ id }) => ({
43
+ id,
44
+ filename: ""
45
+ }));
46
+ const read = [];
47
+ let total = 0;
48
+ if (chat.peer === void 0 || chat.threadId === "") {
49
+ const failure = failed(new AttachmentError({
50
+ code: "no_email_chat",
51
+ message: "The chat has no thread."
52
+ }), "attachment_send_refused");
53
+ return { files: results.map((result) => ({
54
+ ...result,
55
+ ...failure
56
+ })) };
57
+ }
58
+ for (const [index, reference] of input.documentIds.entries()) try {
59
+ const file = await fetchStoredFile({
60
+ reference,
61
+ owner,
62
+ origin,
63
+ token,
64
+ fetch,
65
+ secrets,
66
+ tooLarge: () => new AttachmentError({
67
+ code: "too_large",
68
+ message: TOO_LARGE
69
+ }),
70
+ limit: ({ size }) => {
71
+ if (total + size > 20971520) throw new AttachmentError({
72
+ code: "too_large",
73
+ message: TOO_LARGE
74
+ });
75
+ return MAXIMUM_EMAIL_ATTACHMENT_BYTES - total;
76
+ }
77
+ });
78
+ total += file.bytes.byteLength;
79
+ read.push({
80
+ index,
81
+ file
82
+ });
83
+ results[index] = {
84
+ id: reference.id,
85
+ filename: file.filename
86
+ };
87
+ } catch (error) {
88
+ results[index] = {
89
+ id: reference.id,
90
+ filename: error instanceof StoredFileError ? error.filename : "",
91
+ ...failed(error, "stored_attachment_fetch_failed")
92
+ };
93
+ }
94
+ if (read.length === 0) return { files: results };
95
+ const mailbox = options.gmail ?? gmail(() => connectionProxy({
96
+ environment: proxyEnvironment(context.environment),
97
+ connection: context.connection,
98
+ token,
99
+ fetch
100
+ }));
101
+ try {
102
+ const id = await mailbox.reply({
103
+ threadId: chat.threadId,
104
+ to: chat.peer,
105
+ text: input.caption ?? "",
106
+ key: replyKeyOf(options.sessionId, options.callId, "files"),
107
+ attachments: read.map(({ file }) => ({
108
+ filename: file.filename,
109
+ contentType: file.contentType,
110
+ bytes: file.bytes
111
+ }))
112
+ });
113
+ for (const { index } of read) results[index] = {
114
+ ...results[index],
115
+ emailMessageId: id
116
+ };
117
+ } catch (error) {
118
+ const failure = failed(sendFailure(error), "attachment_upload_failed");
119
+ for (const { index } of read) results[index] = {
120
+ ...results[index],
121
+ error: failure.error,
122
+ detail: failure.detail,
123
+ reference: failure.reference
124
+ };
125
+ }
126
+ return { files: results };
127
+ }
128
+ });
129
+ }
130
+ export { MAXIMUM_EMAIL_ATTACHMENT_BYTES, sendEmailAttachments };
@@ -21,6 +21,11 @@ import { type Gmail } from "./gmail.js";
21
21
  * reads what the mailbox received since, starts a turn per message in the person's thread, and
22
22
  * answers the next cursor. One Gmail thread is one chat with one person. The reply leaves in the
23
23
  * same thread, or waits for a member when the person's review holds it.
24
+ *
25
+ * A reply is an operation of the chat archive, `requested` before it is sent, then `sent` or
26
+ * `failed`. One Gmail does not take for a while waits there, out of the 16 KiB cursor, and each
27
+ * wake tries the replies still waiting, finding by its key one an earlier attempt sent. Mail staff
28
+ * send from the mailbox in a thread where the agent has a chat joins that chat as their message.
24
29
  */
25
30
  /** Where SegmentStream wakes the channel. */
26
31
  export declare const EMAIL_ROUTE = "/eve/segmentstream/v1/email";
@@ -46,8 +51,9 @@ export interface EmailChannelOptions {
46
51
  readonly environment?: Environment;
47
52
  readonly token?: RuntimeToken;
48
53
  readonly fetch?: typeof fetch;
49
- /** Tests pass fakes for the mailbox, the ontology's identities and attachments. */
54
+ /** Tests pass fakes for the mailbox, the chat archive, the ontology's identities and attachments. */
50
55
  readonly gmail?: Gmail;
56
+ readonly archive?: ChatArchive;
51
57
  readonly identities?: AgentIdentities;
52
58
  readonly attachments?: AgentAttachments;
53
59
  readonly transcribe?: Transcriber;