@segmentstream/ontology 0.156.1 → 0.159.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 (67) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/README.md +12 -9
  3. package/dist/agent-chat.d.ts +1 -1
  4. package/dist/agent-chat.js +8 -8
  5. package/dist/agent-draft.d.ts +287 -0
  6. package/dist/{agent-review.js → agent-draft.js} +103 -82
  7. package/dist/analyze.d.ts +1 -1
  8. package/dist/analyze.js +71 -14
  9. package/dist/channel-files.d.ts +70 -0
  10. package/dist/channel-files.js +58 -0
  11. package/dist/chat.d.ts +2 -2
  12. package/dist/earlier-entity-names.d.ts +35 -0
  13. package/dist/earlier-entity-names.js +88 -0
  14. package/dist/email.d.ts +2 -0
  15. package/dist/email.js +1 -0
  16. package/dist/gmail-send.d.ts +39 -0
  17. package/dist/gmail-send.js +179 -0
  18. package/dist/index.d.ts +1 -1
  19. package/dist/index.js +3 -1
  20. package/dist/migrate/apply.d.ts +3 -2
  21. package/dist/migrate/apply.js +11 -4
  22. package/dist/migrate/plan.js +42 -8
  23. package/dist/migrate/preview.js +4 -1
  24. package/dist/permissions.d.ts +5 -5
  25. package/dist/permissions.js +13 -10
  26. package/dist/replicated-entities.d.ts +1 -1
  27. package/dist/replicated-entities.js +4 -1
  28. package/dist/replication/bigquery.d.ts +24 -2
  29. package/dist/replication/bigquery.js +72 -12
  30. package/dist/runtime/agents.d.ts +1 -1
  31. package/dist/runtime/agents.js +43 -38
  32. package/dist/runtime/chat-messages.d.ts +2 -2
  33. package/dist/runtime/chat-messages.js +1 -1
  34. package/dist/runtime/service-binding.js +1 -1
  35. package/dist/service/agent/protocol.d.ts +4 -4
  36. package/dist/service/agent/protocol.js +7 -7
  37. package/dist/service/agent/server.js +14 -9
  38. package/dist/service/chat/envelope.d.ts +12 -12
  39. package/dist/service/chat/review-delivery.js +23 -22
  40. package/dist/service/chat/review-revision.d.ts +1 -1
  41. package/dist/service/chat/review-revision.js +13 -13
  42. package/dist/service/mcp/runtime-policy.js +1 -1
  43. package/dist/service/mcp/server.js +9 -1
  44. package/dist/service/mcp/tools.js +1 -1
  45. package/dist/service/operations.js +11 -5
  46. package/dist/service/runtime-contract.d.ts +3 -3
  47. package/dist/service/service.d.ts +6 -0
  48. package/dist/service/service.js +21 -3
  49. package/dist/slack-files.d.ts +53 -0
  50. package/dist/slack-files.js +183 -0
  51. package/dist/slack.d.ts +3 -0
  52. package/dist/slack.js +2 -0
  53. package/dist/storage/attachments.js +15 -16
  54. package/dist/storage/tables.d.ts +18 -11
  55. package/dist/storage/tables.js +87 -12
  56. package/dist/telegram-files.d.ts +81 -0
  57. package/dist/telegram-files.js +244 -0
  58. package/dist/telegram.d.ts +3 -1
  59. package/dist/telegram.js +2 -0
  60. package/dist/whatsapp-files.d.ts +54 -0
  61. package/dist/whatsapp-files.js +138 -0
  62. package/dist/whatsapp.d.ts +3 -0
  63. package/dist/whatsapp.js +2 -0
  64. package/dist/workspace-channel.d.ts +20 -0
  65. package/dist/workspace-channel.js +10 -0
  66. package/package.json +1 -1
  67. package/dist/agent-review.d.ts +0 -154
@@ -0,0 +1,70 @@
1
+ /**
2
+ * What every channel's "message with files" sender shares: the one request it makes through a
3
+ * connection and what became of each visible part it sent. The agent's `attachments_send` and the
4
+ * ontology's delivery of an approved draft call the same sender, each over its own transport: the
5
+ * agent's connection proxy, or the ontology's connection transport. The sender never retries, and
6
+ * it reports per part what the provider's answer proves.
7
+ */
8
+ /** One HTTP request through a connection: one of its APIs, a path relative to its base URL. */
9
+ export interface ChannelCall {
10
+ readonly api: string;
11
+ readonly method: "GET" | "POST" | "PUT";
12
+ readonly path: string;
13
+ readonly headers: ReadonlyArray<readonly [string, string]>;
14
+ readonly body: Uint8Array;
15
+ }
16
+ /** The provider's answer, as the connection relayed it. */
17
+ export interface ChannelReply {
18
+ readonly status: number;
19
+ readonly headers: ReadonlyArray<readonly [string, string]>;
20
+ readonly body: Uint8Array;
21
+ }
22
+ /**
23
+ * Sends one call. It rejects when the connection could not relay it; whether that proves the
24
+ * provider never saw it is for the caller's `definite` to say.
25
+ */
26
+ export type ChannelRequest = (call: ChannelCall) => Promise<ChannelReply>;
27
+ /** A file read from storage, which the channel uploads. */
28
+ export interface ChannelFile {
29
+ readonly filename: string;
30
+ readonly contentType: string;
31
+ readonly bytes: Uint8Array;
32
+ }
33
+ /**
34
+ * What became of one visible message, or one step before any, a sender attempted:
35
+ * - `sent`: the provider's answer proves it;
36
+ * - `failed`: nothing of it reached the person;
37
+ * - `uncertain`: it may have.
38
+ */
39
+ export interface ChannelPart {
40
+ /** The indexes of the files it carried, in the order given; empty for a text alone. */
41
+ readonly files: ReadonlyArray<number>;
42
+ /** Whether it carried the text or caption. */
43
+ readonly text: boolean;
44
+ readonly status: "sent" | "failed" | "uncertain";
45
+ /** The provider's ids of the messages it posted, when the provider named them. */
46
+ readonly messageIds: ReadonlyArray<string>;
47
+ /** A failure's code: `too_large`, `forbidden`, `unsupported`, `invalid_response`, `send_failed`. */
48
+ readonly code?: string;
49
+ readonly cause?: unknown;
50
+ }
51
+ /**
52
+ * The provider's answer to a call that did not prove its message sent, kept whole for operators:
53
+ * its status and its body, such as Telegram's `description` or Meta's error. Whoever logs it
54
+ * redacts it.
55
+ */
56
+ export declare class ChannelAnswerError extends Error {
57
+ readonly status: number;
58
+ readonly name = "ChannelAnswerError";
59
+ readonly answer: unknown;
60
+ constructor(message: string, status: number, reply: Pick<ChannelReply, "body">);
61
+ }
62
+ /** Whether a request the connection did not relay proves the provider never saw it. */
63
+ export type DefiniteFailure = (error: unknown) => boolean;
64
+ export declare function isRecord(value: unknown): value is Record<string, unknown>;
65
+ /** A reply's body as JSON, or undefined when it is none. */
66
+ export declare function replyJson(reply: ChannelReply): unknown;
67
+ /** The part of a call the connection did not relay. */
68
+ export declare function unrelayed(part: Pick<ChannelPart, "files" | "text">, error: unknown, definite: DefiniteFailure | undefined): ChannelPart;
69
+ /** A request with JSON as its body. */
70
+ export declare function jsonCall(api: string, path: string, body: unknown, contentType?: string): ChannelCall;
@@ -0,0 +1,58 @@
1
+ /**
2
+ * What every channel's "message with files" sender shares: the one request it makes through a
3
+ * connection and what became of each visible part it sent. The agent's `attachments_send` and the
4
+ * ontology's delivery of an approved draft call the same sender, each over its own transport: the
5
+ * agent's connection proxy, or the ontology's connection transport. The sender never retries, and
6
+ * it reports per part what the provider's answer proves.
7
+ */
8
+ /** At most this many characters of an answer that is not JSON are kept on an error. */
9
+ const ANSWER_TEXT_LIMIT = 2000;
10
+ /**
11
+ * The provider's answer to a call that did not prove its message sent, kept whole for operators:
12
+ * its status and its body, such as Telegram's `description` or Meta's error. Whoever logs it
13
+ * redacts it.
14
+ */
15
+ export class ChannelAnswerError extends Error {
16
+ status;
17
+ name = "ChannelAnswerError";
18
+ answer;
19
+ constructor(message, status, reply) {
20
+ super(message);
21
+ this.status = status;
22
+ const json = replyJson(reply);
23
+ this.answer =
24
+ json === undefined ? new TextDecoder().decode(reply.body).slice(0, ANSWER_TEXT_LIMIT) : json;
25
+ }
26
+ }
27
+ export function isRecord(value) {
28
+ return typeof value === "object" && value !== null && !Array.isArray(value);
29
+ }
30
+ /** A reply's body as JSON, or undefined when it is none. */
31
+ export function replyJson(reply) {
32
+ try {
33
+ return JSON.parse(new TextDecoder().decode(reply.body));
34
+ }
35
+ catch {
36
+ return undefined;
37
+ }
38
+ }
39
+ /** The part of a call the connection did not relay. */
40
+ export function unrelayed(part, error, definite) {
41
+ return {
42
+ ...part,
43
+ status: definite?.(error) === true ? "failed" : "uncertain",
44
+ messageIds: [],
45
+ code: "send_failed",
46
+ cause: error,
47
+ };
48
+ }
49
+ /** A request with JSON as its body. */
50
+ export function jsonCall(api, path, body, contentType = "application/json") {
51
+ return {
52
+ api,
53
+ method: "POST",
54
+ path,
55
+ headers: [["content-type", contentType]],
56
+ body: new TextEncoder().encode(JSON.stringify(body)),
57
+ };
58
+ }
package/dist/chat.d.ts CHANGED
@@ -203,7 +203,7 @@ export declare const ChatHistoryImportResult: Schema.Struct<{
203
203
  export type ChatHistoryImportResult = typeof ChatHistoryImportResult.Type;
204
204
  /** A member's approval of a reply the agent held for review: the draft, or their edit of it. */
205
205
  export interface ReviewSendInput {
206
- /** The `agent_review` record's id. */
206
+ /** The `agent_draft` record's id. */
207
207
  readonly review: string;
208
208
  readonly text?: string;
209
209
  /** A reply to mail: the addresses it goes to, in place of the review's own. */
@@ -226,7 +226,7 @@ export interface ReviewSendResult {
226
226
  }
227
227
  /** A member's request that the agent redraft a reply it held for review. */
228
228
  export interface ReviewReviseInput {
229
- /** The `agent_review` record's id. */
229
+ /** The `agent_draft` record's id. */
230
230
  readonly review: string;
231
231
  /** What the agent should change, in the member's words. */
232
232
  readonly note: string;
@@ -0,0 +1,35 @@
1
+ /** A built-in entity's earlier name and the name that replaced it, both in snake_case. */
2
+ export interface EarlierEntityName {
3
+ readonly earlier: string;
4
+ readonly current: string;
5
+ /** Action input keys the rename replaced: the earlier key and the current one. */
6
+ readonly inputKeys?: ReadonlyArray<{
7
+ readonly earlier: string;
8
+ readonly current: string;
9
+ }>;
10
+ }
11
+ /** Every built-in entity's earlier name. A rename adds one entry. */
12
+ export declare const EARLIER_ENTITY_NAMES: ReadonlyArray<EarlierEntityName>;
13
+ /** The current name of an entity named by its earlier name; any other name as it is. */
14
+ export declare function currentEntityName(name: string): string;
15
+ /** The earlier name of an entity a release renamed, or `undefined`. */
16
+ export declare function earlierEntityName(name: string): string | undefined;
17
+ /** Whether a name is an earlier entity name. */
18
+ export declare function isEarlierEntityName(name: string): boolean;
19
+ /**
20
+ * `<earlier>:<verb>` as `<current>:<verb>`; any other value as it is. Wildcards, workflow
21
+ * permissions and values that are no permission are kept.
22
+ */
23
+ export declare function currentPermissionName(permission: string): string;
24
+ /** An MCP tool named `<earlier>_<verb>` as `<current>_<verb>`; any other name as it is. */
25
+ export declare function currentToolName(name: string): string;
26
+ /**
27
+ * A path under `base` that names an entity by its earlier name, `…/<earlier>` or `…/<earlier>/…`,
28
+ * with the current one; `undefined` when it names none.
29
+ */
30
+ export declare function currentEntityPath(path: string, base: string): string | undefined;
31
+ /**
32
+ * An action's input with the keys the entity's rename replaced under their current names, when
33
+ * the input names them only by the earlier ones; any other input as it is.
34
+ */
35
+ export declare function currentActionInput(entity: string, input: unknown): unknown;
@@ -0,0 +1,88 @@
1
+ /**
2
+ * @legacy ontology.agent-review-entity-name
3
+ * Built-in entities an SDK release renamed. The entity keeps its id, so the workspace's next deploy
4
+ * renames its storage; until the entry's removal the earlier name still works wherever a caller
5
+ * or workspace code names the entity: in a role's permissions, which `check` rewrites with a
6
+ * warning; in a permission a credential holds; in the HTTP routes `/api/ontology/<earlier>/…`; in
7
+ * the MCP tools `<earlier>_<verb>`; and in an action input key the rename replaced. Discovery,
8
+ * the catalog and the manifest list only the current names.
9
+ */
10
+ import { toSnakeCase } from "./names.js";
11
+ /** Every built-in entity's earlier name. A rename adds one entry. */
12
+ export const EARLIER_ENTITY_NAMES = [
13
+ {
14
+ earlier: "agent_review",
15
+ current: "agent_draft",
16
+ inputKeys: [{ earlier: "review", current: "draft" }],
17
+ },
18
+ ];
19
+ const byEarlier = new Map(EARLIER_ENTITY_NAMES.map((entry) => [entry.earlier, entry]));
20
+ const byCurrent = new Map(EARLIER_ENTITY_NAMES.map((entry) => [entry.current, entry]));
21
+ /** The current name of an entity named by its earlier name; any other name as it is. */
22
+ export function currentEntityName(name) {
23
+ return byEarlier.get(toSnakeCase(name))?.current ?? name;
24
+ }
25
+ /** The earlier name of an entity a release renamed, or `undefined`. */
26
+ export function earlierEntityName(name) {
27
+ return byCurrent.get(toSnakeCase(name))?.earlier;
28
+ }
29
+ /** Whether a name is an earlier entity name. */
30
+ export function isEarlierEntityName(name) {
31
+ return byEarlier.has(toSnakeCase(name));
32
+ }
33
+ /**
34
+ * `<earlier>:<verb>` as `<current>:<verb>`; any other value as it is. Wildcards, workflow
35
+ * permissions and values that are no permission are kept.
36
+ */
37
+ export function currentPermissionName(permission) {
38
+ const separator = permission.indexOf(":");
39
+ if (separator <= 0 || permission.startsWith("workflow:")) {
40
+ return permission;
41
+ }
42
+ const entity = permission.slice(0, separator);
43
+ const current = currentEntityName(entity);
44
+ return current === entity ? permission : `${current}${permission.slice(separator)}`;
45
+ }
46
+ /** An MCP tool named `<earlier>_<verb>` as `<current>_<verb>`; any other name as it is. */
47
+ export function currentToolName(name) {
48
+ for (const { earlier, current } of EARLIER_ENTITY_NAMES) {
49
+ if (name.startsWith(`${earlier}_`)) {
50
+ return `${current}${name.slice(earlier.length)}`;
51
+ }
52
+ }
53
+ return name;
54
+ }
55
+ /**
56
+ * A path under `base` that names an entity by its earlier name, `…/<earlier>` or `…/<earlier>/…`,
57
+ * with the current one; `undefined` when it names none.
58
+ */
59
+ export function currentEntityPath(path, base) {
60
+ if (!path.startsWith(`${base}/`)) {
61
+ return undefined;
62
+ }
63
+ const rest = path.slice(base.length + 1);
64
+ const end = rest.indexOf("/");
65
+ const segment = end === -1 ? rest : rest.slice(0, end);
66
+ const entry = byEarlier.get(segment);
67
+ return entry === undefined
68
+ ? undefined
69
+ : `${base}/${entry.current}${end === -1 ? "" : rest.slice(end)}`;
70
+ }
71
+ /**
72
+ * An action's input with the keys the entity's rename replaced under their current names, when
73
+ * the input names them only by the earlier ones; any other input as it is.
74
+ */
75
+ export function currentActionInput(entity, input) {
76
+ const keys = byCurrent.get(entity)?.inputKeys;
77
+ if (keys === undefined ||
78
+ typeof input !== "object" ||
79
+ input === null ||
80
+ Array.isArray(input) ||
81
+ !keys.some(({ earlier, current }) => Object.hasOwn(input, earlier) && !Object.hasOwn(input, current))) {
82
+ return input;
83
+ }
84
+ return Object.fromEntries(Object.entries(input).map(([key, value]) => {
85
+ const renamed = keys.find(({ earlier, current }) => key === earlier && !Object.hasOwn(input, current));
86
+ return [renamed === undefined ? key : renamed.current, value];
87
+ }));
88
+ }
package/dist/email.d.ts CHANGED
@@ -77,3 +77,5 @@ export declare const REPLY_KEY_HEADER = "X-SegmentStream-Reply";
77
77
  export declare function emailReplyMessage(reply: EmailReply): string;
78
78
  /** Bytes as URL-safe base64 without padding, as the Gmail API takes a raw message. */
79
79
  export declare function base64Url(text: string): string;
80
+ export type { ChannelCall, ChannelReply, ChannelRequest } from "./channel-files.js";
81
+ export { EMAIL_FILES_BYTES, GmailError, gmailExplanation, gmailJson, sendGmailMessage, } from "./gmail-send.js";
package/dist/email.js CHANGED
@@ -210,3 +210,4 @@ export function emailReplyMessage(reply) {
210
210
  export function base64Url(text) {
211
211
  return Buffer.from(text, "utf8").toString("base64url");
212
212
  }
213
+ export { EMAIL_FILES_BYTES, GmailError, gmailExplanation, gmailJson, sendGmailMessage, } from "./gmail-send.js";
@@ -0,0 +1,39 @@
1
+ import type { ChannelReply, ChannelRequest } from "./channel-files.js";
2
+ /**
3
+ * Gmail's message with files, which the agent's email channel and the ontology's delivery of an
4
+ * approved draft both send: one RFC 822 message (`emailReplyMessage`), as JSON on the connection's
5
+ * `gmail` API when one request carries it, otherwise with Gmail's resumable upload on its `upload`
6
+ * API, in chunks one request carries.
7
+ */
8
+ /**
9
+ * The most bytes of files one email carries, together: below the 25 MB Gmail takes, with room for
10
+ * the text and the encoding.
11
+ */
12
+ export declare const EMAIL_FILES_BYTES: number;
13
+ /**
14
+ * Gmail answered with a status the sender does not continue from. `detail` keeps Google's own
15
+ * explanation, such as a missing scope, for operators; whoever logs it redacts it.
16
+ */
17
+ export declare class GmailError extends Error {
18
+ readonly operation: string;
19
+ readonly status: number;
20
+ readonly detail?: string | undefined;
21
+ readonly name = "GmailError";
22
+ constructor(operation: string, status: number, detail?: string | undefined);
23
+ }
24
+ /** A reply's body as a JSON object, or an empty one. */
25
+ export declare function gmailJson(reply: Pick<ChannelReply, "body">): Record<string, unknown>;
26
+ /** Google's explanation of a refused call: its error message and reasons. */
27
+ export declare function gmailExplanation(reply: Pick<ChannelReply, "body">): string | undefined;
28
+ /**
29
+ * Sends `message`, an RFC 822 message, in `threadId` and resolves Gmail's answer, which names the
30
+ * message's `id`. A message one JSON request carries goes at once; a larger one is uploaded. A
31
+ * chunk whose answer was lost asks Gmail how much it holds and goes on from there, so no byte is
32
+ * sent twice and no message twice. Throws {@link GmailError} for a status it does not continue
33
+ * from.
34
+ */
35
+ export declare function sendGmailMessage(options: {
36
+ readonly request: ChannelRequest;
37
+ readonly message: Uint8Array;
38
+ readonly threadId: string;
39
+ }): Promise<Record<string, unknown>>;
@@ -0,0 +1,179 @@
1
+ import { MAXIMUM_CONNECTION_BODY_BYTES } from "./connection.js";
2
+ /**
3
+ * Gmail's message with files, which the agent's email channel and the ontology's delivery of an
4
+ * approved draft both send: one RFC 822 message (`emailReplyMessage`), as JSON on the connection's
5
+ * `gmail` API when one request carries it, otherwise with Gmail's resumable upload on its `upload`
6
+ * API, in chunks one request carries.
7
+ */
8
+ /**
9
+ * The most bytes of files one email carries, together: below the 25 MB Gmail takes, with room for
10
+ * the text and the encoding.
11
+ */
12
+ export const EMAIL_FILES_BYTES = 20 * 1024 * 1024;
13
+ /** At most this many characters of Gmail's own explanation are kept on an error. */
14
+ const DETAIL_LIMIT = 1000;
15
+ /**
16
+ * Gmail answered with a status the sender does not continue from. `detail` keeps Google's own
17
+ * explanation, such as a missing scope, for operators; whoever logs it redacts it.
18
+ */
19
+ export class GmailError extends Error {
20
+ operation;
21
+ status;
22
+ detail;
23
+ name = "GmailError";
24
+ constructor(operation, status, detail) {
25
+ super(`Gmail answered ${operation} with status ${status}` +
26
+ (detail === undefined ? "." : `: ${detail}`));
27
+ this.operation = operation;
28
+ this.status = status;
29
+ this.detail = detail;
30
+ }
31
+ }
32
+ /** A reply's body as a JSON object, or an empty one. */
33
+ export function gmailJson(reply) {
34
+ try {
35
+ const value = JSON.parse(new TextDecoder().decode(reply.body));
36
+ return typeof value === "object" && value !== null && !Array.isArray(value)
37
+ ? value
38
+ : {};
39
+ }
40
+ catch {
41
+ return {};
42
+ }
43
+ }
44
+ /** Google's explanation of a refused call: its error message and reasons. */
45
+ export function gmailExplanation(reply) {
46
+ const error = (gmailJson(reply).error ?? {});
47
+ const reasons = Array.isArray(error.errors)
48
+ ? error.errors.flatMap((item) => {
49
+ const reason = item?.reason;
50
+ return typeof reason === "string" ? [reason] : [];
51
+ })
52
+ : [];
53
+ const text = [typeof error.message === "string" ? error.message : "", ...reasons]
54
+ .filter((part) => part !== "")
55
+ .join("; ");
56
+ return text === "" ? undefined : text.slice(0, DETAIL_LIMIT);
57
+ }
58
+ /** The most bytes of an RFC 822 message one chunk of an upload carries. */
59
+ const UPLOAD_CHUNK_BYTES = MAXIMUM_CONNECTION_BODY_BYTES;
60
+ /** How many times an upload asks how much Gmail holds before it gives up. */
61
+ const UPLOAD_RECOVERIES = 3;
62
+ /** The connection API that reaches each host Gmail names an upload session on. */
63
+ const UPLOAD_APIS = {
64
+ "gmail.googleapis.com": "upload",
65
+ "www.googleapis.com": "upload_legacy",
66
+ };
67
+ /** The send paths an upload session may be on. */
68
+ const UPLOAD_PATH = /^\/(?:resumable\/)?upload\/gmail\/v1\/users\/me\/messages\/send$/u;
69
+ /** An upload session's API and path, from the `Location` Gmail answered, when it is one. */
70
+ function uploadSession(location) {
71
+ if (location === undefined) {
72
+ return undefined;
73
+ }
74
+ try {
75
+ const url = new URL(location);
76
+ const api = UPLOAD_APIS[url.hostname];
77
+ return url.protocol === "https:" &&
78
+ url.port === "" &&
79
+ api !== undefined &&
80
+ UPLOAD_PATH.test(url.pathname) &&
81
+ url.searchParams.has("upload_id")
82
+ ? { api, path: `${url.pathname}${url.search}` }
83
+ : undefined;
84
+ }
85
+ catch {
86
+ return undefined;
87
+ }
88
+ }
89
+ /** A reply header, by name in any case. */
90
+ function replyHeader(reply, name) {
91
+ return reply.headers.find(([key]) => key.toLowerCase() === name)?.[1];
92
+ }
93
+ /**
94
+ * Sends `message`, an RFC 822 message, in `threadId` and resolves Gmail's answer, which names the
95
+ * message's `id`. A message one JSON request carries goes at once; a larger one is uploaded. A
96
+ * chunk whose answer was lost asks Gmail how much it holds and goes on from there, so no byte is
97
+ * sent twice and no message twice. Throws {@link GmailError} for a status it does not continue
98
+ * from.
99
+ */
100
+ export async function sendGmailMessage(options) {
101
+ const { request, message, threadId } = options;
102
+ const body = JSON.stringify({ raw: Buffer.from(message).toString("base64url"), threadId });
103
+ if (body.length <= MAXIMUM_CONNECTION_BODY_BYTES) {
104
+ const reply = await request({
105
+ api: "gmail",
106
+ method: "POST",
107
+ path: "/users/me/messages/send",
108
+ headers: [["content-type", "application/json"]],
109
+ body: new TextEncoder().encode(body),
110
+ });
111
+ if (reply.status < 200 || reply.status >= 300) {
112
+ throw new GmailError("messages.send", reply.status, gmailExplanation(reply));
113
+ }
114
+ return gmailJson(reply);
115
+ }
116
+ const started = await request({
117
+ api: "upload",
118
+ method: "POST",
119
+ path: "/upload/gmail/v1/users/me/messages/send?uploadType=resumable",
120
+ headers: [
121
+ ["content-type", "application/json; charset=UTF-8"],
122
+ ["x-upload-content-type", "message/rfc822"],
123
+ ["x-upload-content-length", String(message.byteLength)],
124
+ ],
125
+ body: new TextEncoder().encode(JSON.stringify({ threadId })),
126
+ });
127
+ if (started.status < 200 || started.status >= 300) {
128
+ throw new GmailError("messages.send", started.status, gmailExplanation(started));
129
+ }
130
+ const session = uploadSession(replyHeader(started, "location"));
131
+ if (session === undefined) {
132
+ throw new GmailError("messages.send", 502, "Gmail named no upload session it may use.");
133
+ }
134
+ const total = message.byteLength;
135
+ let offset = 0;
136
+ let recoveries = 0;
137
+ for (;;) {
138
+ const end = Math.min(offset + UPLOAD_CHUNK_BYTES, total);
139
+ let reply;
140
+ try {
141
+ reply = await request({
142
+ api: session.api,
143
+ method: "PUT",
144
+ path: session.path,
145
+ headers: [
146
+ ["content-type", "message/rfc822"],
147
+ ["content-range", `bytes ${offset}-${end - 1}/${total}`],
148
+ ],
149
+ body: message.subarray(offset, end),
150
+ });
151
+ if (reply.status === 408 || reply.status === 429 || reply.status >= 500) {
152
+ throw new GmailError("messages.send", reply.status, gmailExplanation(reply));
153
+ }
154
+ }
155
+ catch (error) {
156
+ // The chunk may or may not have arrived: Gmail says how much it holds.
157
+ recoveries += 1;
158
+ if (recoveries > UPLOAD_RECOVERIES) {
159
+ throw error;
160
+ }
161
+ reply = await request({
162
+ api: session.api,
163
+ method: "PUT",
164
+ path: session.path,
165
+ headers: [["content-range", `bytes */${total}`]],
166
+ body: new Uint8Array(),
167
+ });
168
+ }
169
+ if (reply.status === 200 || reply.status === 201) {
170
+ return gmailJson(reply);
171
+ }
172
+ if (reply.status !== 308) {
173
+ throw new GmailError("messages.send", reply.status, gmailExplanation(reply));
174
+ }
175
+ // `Range: bytes=0-N` is what Gmail holds; without it, nothing yet.
176
+ const held = /^bytes=0-(\d+)$/u.exec(replyHeader(reply, "range") ?? "")?.[1];
177
+ offset = held === undefined ? 0 : Number(held) + 1;
178
+ }
179
+ }
package/dist/index.d.ts CHANGED
@@ -59,7 +59,7 @@ export type { BatchOptions, BatchRecordResult, BatchResult, BatchReturning, Batc
59
59
  export { User } from "./user.js";
60
60
  export type { UserHandle, UserMemberWrites } from "./user.js";
61
61
  export { AgentChat } from "./agent-chat.js";
62
- export { AgentReview, AGENT_REVIEW_MODES, AGENT_REVIEW_STATUSES, AGENT_REVIEW_TEXT_LIMIT, } from "./agent-review.js";
62
+ export { AgentDraft, AGENT_DRAFT_MODES, AGENT_DRAFT_STATUSES, AGENT_DRAFT_TEXT_LIMIT, AgentReview, AGENT_REVIEW_MODES, AGENT_REVIEW_STATUSES, AGENT_REVIEW_TEXT_LIMIT, } from "./agent-draft.js";
63
63
  export { ATTACHABLE_IDENTITY_PROVIDERS, UserIdentity, USER_IDENTITY_ORIGINS, } from "./user-identity.js";
64
64
  export type { AttachableIdentityProvider, UserIdentityOrigin } from "./user-identity.js";
65
65
  export { AppFeedback, AppFeedbackFile, APP_FEEDBACK_ENTITIES, APP_FEEDBACK_FILE_MAX_BYTES, } from "./app-feedback.js";
package/dist/index.js CHANGED
@@ -34,7 +34,9 @@ export { EMAIL_MARKUP_VALUES, isEmailDocument, unsafeEmailHtml } from "./emails.
34
34
  export { OntologyActions, OntologyReads, OntologyRuntime, OntologyWrites } from "./runtime.js";
35
35
  export { User } from "./user.js";
36
36
  export { AgentChat } from "./agent-chat.js";
37
- export { AgentReview, AGENT_REVIEW_MODES, AGENT_REVIEW_STATUSES, AGENT_REVIEW_TEXT_LIMIT, } from "./agent-review.js";
37
+ export { AgentDraft, AGENT_DRAFT_MODES, AGENT_DRAFT_STATUSES, AGENT_DRAFT_TEXT_LIMIT,
38
+ // @legacy ontology.agent-review-entity-name
39
+ AgentReview, AGENT_REVIEW_MODES, AGENT_REVIEW_STATUSES, AGENT_REVIEW_TEXT_LIMIT, } from "./agent-draft.js";
38
40
  export { ATTACHABLE_IDENTITY_PROVIDERS, UserIdentity, USER_IDENTITY_ORIGINS, } from "./user-identity.js";
39
41
  export { AppFeedback, AppFeedbackFile, APP_FEEDBACK_ENTITIES, APP_FEEDBACK_FILE_MAX_BYTES, } from "./app-feedback.js";
40
42
  export { ChatDelivery, ChatHistoryImportInput, ChatHistoryImportResult, ChatHistoryMessage, ChatPostInput, ChatSendInput, ChatTemplate, ChatTemplateMedia, ChatPostResult, } from "./chat.js";
@@ -90,8 +90,9 @@ export declare const RUNTIME_TABLES: ReadonlyArray<string>;
90
90
  * A grants table without app-session binding is reported incomplete so the idempotent OAuth DDL
91
91
  * also upgrades an unchanged manifest, and so is an action attribution table without `chat`, an
92
92
  * API keys table without `delegation` and an attachments table whose source check predates one of
93
- * {@link ATTACHMENT_SOURCES}, which the idempotent attribution, API key and attachment DDL add and
94
- * widen.
93
+ * {@link ATTACHMENT_SOURCES} or that lacks the view of its earlier name, which the idempotent
94
+ * attribution, API key and attachment DDL add and widen. A table still named
95
+ * {@link LEGACY_ATTACHMENTS_TABLE} is reported under that name, so that the plan renames it.
95
96
  */
96
97
  export declare const readRuntimeTables: (input: CatalogInput) => Effect.Effect<ReadonlySet<string>, SqlError>;
97
98
  /** Only valid, complete covering indexes satisfy the upgrade; failed builds are retried. */
@@ -15,7 +15,7 @@ import { randomUUID } from "node:crypto";
15
15
  import { recordWorkflowCatalog } from "../runtime/workflow-admission.js";
16
16
  import { prepareReplicationEvolution, dropsServingReplicationStorage, refreshReplicationProjection, retainReplicationHistory, renameReplicationHistory, } from "../replication/evolution.js";
17
17
  import { migratedReplicationFills } from "../replication/migrate.js";
18
- import { AGENT_TASKS_TABLE, ATTACHMENT_SOURCE_CHECK, ATTACHMENT_SOURCES, ATTACHMENTS_TABLE, SIGN_IN_EMAILS_TABLE, WORKFLOW_STARTS_TABLE, } from "../storage/tables.js";
18
+ import { AGENT_TASKS_TABLE, ATTACHMENT_SOURCE_CHECK, ATTACHMENT_SOURCES, ATTACHMENTS_TABLE, LEGACY_ATTACHMENTS_TABLE, SIGN_IN_EMAILS_TABLE, WORKFLOW_STARTS_TABLE, } from "../storage/tables.js";
19
19
  import { principalsOntology, reconcileWorkflowUsers } from "../runtime/principals.js";
20
20
  import { FEDERATION_TABLES } from "../runtime/federation-tables.js";
21
21
  import { syncUserIdentities, USER_IDENTITY_ENTITY_ID } from "../runtime/user-identities.js";
@@ -488,13 +488,15 @@ export const RUNTIME_TABLES = [
488
488
  * A grants table without app-session binding is reported incomplete so the idempotent OAuth DDL
489
489
  * also upgrades an unchanged manifest, and so is an action attribution table without `chat`, an
490
490
  * API keys table without `delegation` and an attachments table whose source check predates one of
491
- * {@link ATTACHMENT_SOURCES}, which the idempotent attribution, API key and attachment DDL add and
492
- * widen.
491
+ * {@link ATTACHMENT_SOURCES} or that lacks the view of its earlier name, which the idempotent
492
+ * attribution, API key and attachment DDL add and widen. A table still named
493
+ * {@link LEGACY_ATTACHMENTS_TABLE} is reported under that name, so that the plan renames it.
493
494
  */
494
495
  export const readRuntimeTables = (input) => input.sql
495
496
  .unsafe(`SELECT "tablename" AS "name" FROM "pg_catalog"."pg_tables" ` +
496
497
  `WHERE "schemaname" = current_schema() ` +
497
- `AND "tablename" IN (${RUNTIME_TABLES.map(quoteLiteral).join(", ")}) ` +
498
+ // @legacy ontology.agent-attachments-view: a table still under its earlier name is renamed.
499
+ `AND "tablename" IN (${[...RUNTIME_TABLES, LEGACY_ATTACHMENTS_TABLE].map(quoteLiteral).join(", ")}) ` +
498
500
  `AND ("tablename" <> '_oauth_grants' OR EXISTS (` +
499
501
  `SELECT 1 FROM information_schema.columns WHERE table_schema = current_schema() ` +
500
502
  `AND table_name = '_oauth_grants' AND column_name = 'identity_id')) ` +
@@ -516,6 +518,11 @@ export const readRuntimeTables = (input) => input.sql
516
518
  `AND ("tablename" <> ${quoteLiteral(API_KEYS_TABLE)} OR EXISTS (` +
517
519
  `SELECT 1 FROM information_schema.columns WHERE table_schema = current_schema() ` +
518
520
  `AND table_name = ${quoteLiteral(API_KEYS_TABLE)} AND column_name = 'delegation')) ` +
521
+ // @legacy ontology.agent-attachments-view
522
+ // Without the view of the table's earlier name, the attachment DDL runs again and adds it.
523
+ `AND ("tablename" <> ${quoteLiteral(ATTACHMENTS_TABLE)} OR EXISTS (` +
524
+ `SELECT 1 FROM pg_catalog.pg_views WHERE schemaname = current_schema() ` +
525
+ `AND viewname = ${quoteLiteral(LEGACY_ATTACHMENTS_TABLE)})) ` +
519
526
  `AND ("tablename" <> ${quoteLiteral(ATTACHMENTS_TABLE)} OR EXISTS (` +
520
527
  `SELECT 1 FROM pg_catalog.pg_constraint c ` +
521
528
  `JOIN pg_catalog.pg_class t ON t.oid = c.conrelid ` +