@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
@@ -9,7 +9,7 @@ export declare const AGENT_REVISION_ROUTE = "/eve/segmentstream/v1/reviews/revis
9
9
  /**
10
10
  * Hands a reply the agent held for review back to it with a member's note: the agent redrafts it in
11
11
  * a session of its own, acting as the person the reply is for and reading only, and reports the new
12
- * draft to `POST /api/ontology/agent/reviews/revision`, where it replaces the review while the review
12
+ * draft to `POST /api/ontology/agent/drafts/revision`, where it replaces the draft while the draft
13
13
  * still waits and this is the last redraft asked for. The request is recorded before the agent is
14
14
  * called, so however soon the agent reports, its report finds it, and it names everything the agent
15
15
  * needs: the agent never looks the review up.
@@ -13,14 +13,14 @@ const text = (value) => typeof value === "string" && value !== "" ? value : null
13
13
  /**
14
14
  * Hands a reply the agent held for review back to it with a member's note: the agent redrafts it in
15
15
  * a session of its own, acting as the person the reply is for and reading only, and reports the new
16
- * draft to `POST /api/ontology/agent/reviews/revision`, where it replaces the review while the review
16
+ * draft to `POST /api/ontology/agent/drafts/revision`, where it replaces the draft while the draft
17
17
  * still waits and this is the last redraft asked for. The request is recorded before the agent is
18
18
  * called, so however soon the agent reports, its report finds it, and it names everything the agent
19
19
  * needs: the agent never looks the review up.
20
20
  */
21
21
  export function reviewReviser(input) {
22
22
  const { backend, principal, agent } = input;
23
- const report = (phase, cause) => Effect.logWarning("ontology.agent_review.revision_diagnostic").pipe(Effect.annotateLogs({
23
+ const report = (phase, cause) => Effect.logWarning("ontology.agent_draft.revision_diagnostic").pipe(Effect.annotateLogs({
24
24
  phase,
25
25
  requestId: input.requestId,
26
26
  error: describeChatError(cause, (value) => agent.identityToken ? value.split(agent.identityToken).join("[redacted]") : value),
@@ -28,29 +28,29 @@ export function reviewReviser(input) {
28
28
  return (revise) => Effect.gen(function* () {
29
29
  // The call happens before the action's transaction, whose write guard comes too late for it:
30
30
  // a review outside the scope is refused here, read through the request's own scope.
31
- const revisable = effectiveScope("agent_review:revise", principal);
31
+ const revisable = effectiveScope("agent_draft:revise", principal);
32
32
  if (revisable !== undefined) {
33
33
  yield* backend
34
34
  .get({
35
- entity: "agent_review",
35
+ entity: "agent_draft",
36
36
  id: revise.review,
37
37
  reader: {
38
38
  ...principal,
39
- permissions: ["agent_review:read"],
40
- scopes: [{ permission: "agent_review:read", where: revisable }],
39
+ permissions: ["agent_draft:read"],
40
+ scopes: [{ permission: "agent_draft:read", where: revisable }],
41
41
  },
42
42
  })
43
43
  .pipe(Effect.mapError(() => new PermissionDenied({
44
- message: "The review is outside the records agent_review:revise covers.",
45
- permission: "agent_review:revise",
44
+ message: "The draft is outside the records agent_draft:revise covers.",
45
+ permission: "agent_draft:revise",
46
46
  })));
47
47
  }
48
48
  if (principal.kind === "guest") {
49
49
  return yield* new PermissionDenied({ message: "The member is unknown." });
50
50
  }
51
51
  const review = yield* backend
52
- .get({ entity: "agent_review", id: revise.review })
53
- .pipe(Effect.mapError(() => new ActionRejected({ message: "The review does not exist." })));
52
+ .get({ entity: "agent_draft", id: revise.review })
53
+ .pipe(Effect.mapError(() => new ActionRejected({ message: "The draft does not exist." })));
54
54
  if (review.status !== "pending") {
55
55
  return yield* new ActionRejected({
56
56
  message: "Only a reply that still waits for a member can be redrafted.",
@@ -83,7 +83,7 @@ export function reviewReviser(input) {
83
83
  break;
84
84
  }
85
85
  const found = yield* backend
86
- .get({ entity: "agent_review", id: earlier })
86
+ .get({ entity: "agent_draft", id: earlier })
87
87
  .pipe(Effect.option);
88
88
  if (Option.isNone(found)) {
89
89
  break;
@@ -115,8 +115,8 @@ export function reviewReviser(input) {
115
115
  roles: person.principal.roles,
116
116
  session_id: String(review.session_id),
117
117
  key: String(first.key),
118
- provider: String(review.provider),
119
- channel: text(review.channel) ?? String(review.provider),
118
+ provider: String(review.channel_kind),
119
+ channel: text(review.channel) ?? String(review.channel_kind),
120
120
  chat_id: String(review.chat_id),
121
121
  thread_id: text(review.thread_id),
122
122
  chat_kind: review.chat_kind === "group" ? "group" : "private",
@@ -39,7 +39,7 @@ export function requireRuntimeOperation(operation) {
39
39
  if (deployment) {
40
40
  yield* Effect.sync(() => requireDeploymentCapability(deployment, invokesAgent(operation) ||
41
41
  operation.entity === "agent_chat" ||
42
- operation.entity === "agent_review"
42
+ operation.entity === "agent_draft"
43
43
  ? "agents"
44
44
  : undefined));
45
45
  }
@@ -2,6 +2,7 @@ import { Cause, Data, Effect, Layer, Option, Redacted, Schema, SchemaTransformat
2
2
  import { HttpRouter, HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
3
3
  import { HttpApiBuilder, HttpApiSecurity } from "effect/unstable/httpapi";
4
4
  import { ActionRejected } from "../../errors.js";
5
+ import { currentToolName } from "../../earlier-entity-names.js";
5
6
  import { DeploymentAdmissionError } from "../../deployment.js";
6
7
  import { effectivePermissions } from "../../permissions.js";
7
8
  import { declaredChatRetentionDaysOf, encodeManifest } from "../../manifest.js";
@@ -527,7 +528,14 @@ function callTool(server, params, request, preview) {
527
528
  const requestId = yield* RequestId;
528
529
  const caller = yield* currentCaller;
529
530
  const principal = yield* CurrentPrincipal;
530
- const call = params;
531
+ // @legacy ontology.agent-review-entity-name
532
+ // A tool named by a built-in entity's earlier name is called under its current name.
533
+ // A tool the server has by the name given is that tool, whatever its name starts with.
534
+ const call = typeof params.name === "string" &&
535
+ !server.tools.some((candidate) => candidate.name === params.name) &&
536
+ currentToolName(params.name) !== params.name
537
+ ? { ...params, name: currentToolName(params.name) }
538
+ : params;
531
539
  const tool = server.tools.find((candidate) => candidate.name === call.name);
532
540
  const allowed = yield* requireRuntimeOperation({
533
541
  ...(typeof call.name === "string" ? { name: call.name } : {}),
@@ -836,7 +836,7 @@ export function mcpTools(built, chatHistory = false, storage = {}, navigation =
836
836
  "agent_chat:read) and DMs in which you participated. Dates are ISO 8601; before is the " +
837
837
  "nextCursor of the previous page. " +
838
838
  "Workspace administrators can read all DMs through the platform API."
839
- : "Search retained chat messages. Requires an available archive and chat archive read access.",
839
+ : "Search retained chat messages. Requires an available chat store and chat read access.",
840
840
  inputSchema: encodedJsonSchema(ChatSearch),
841
841
  annotations: READ,
842
842
  permissions: [],
@@ -20,6 +20,9 @@ import { InvalidActionInput, RequestId } from "./errors.js";
20
20
  import { recordReads } from "./record-reads.js";
21
21
  import { runToolsetToolOf } from "./toolsets.js";
22
22
  import { AGENT_TASK_AUTHENTICATION } from "./agent/task-caller.js";
23
+ import { AgentDraft } from "../agent-draft.js";
24
+ import { currentActionInput } from "../earlier-entity-names.js";
25
+ const AGENT_DRAFT = AgentDraft.name;
23
26
  /**
24
27
  * What the service does for a caller, whatever the transport: the reads and actions of every entity
25
28
  * and the caller's own account. The HTTP routes and the MCP tools both call these, so a permission
@@ -241,20 +244,23 @@ function runActionOf(backend, plan, hooks, connections, replicate, chatDelivery)
241
244
  }
242
245
  input = { ...values, idempotency_key: envelope.operation_id };
243
246
  }
244
- // Approving a held reply sends it to a person: a member, or the agent acting for one with
247
+ // Approving a draft sends it to a person: a member, or the agent acting for one with
245
248
  // their confirmation, decides; an agent task has no one to confirm it.
246
- if (planned.name === "agent_review" &&
249
+ if (planned.name === AGENT_DRAFT &&
247
250
  name === "approve" &&
248
251
  principal.authenticatedVia === AGENT_TASK_AUTHENTICATION) {
249
252
  return yield* new ActionRejected({
250
- message: "Agent tasks cannot approve a held reply: agent_review.approve needs a member to " +
253
+ message: "Agent tasks cannot approve a draft: agent_draft.approve needs a member to " +
251
254
  "confirm the text the person receives.",
252
255
  });
253
256
  }
257
+ // @legacy ontology.agent-review-entity-name
258
+ // Callers written for the entity's earlier name still send its input keys.
259
+ input = currentActionInput(planned.name, input);
254
260
  const requestId = yield* RequestId;
255
- // Every action of the chat registry and of held replies reaches chats through the service:
261
+ // Every action of the chat registry and of drafts reaches chats through the service:
256
262
  // posts, takeovers, imports, approvals and redrafts.
257
- const delivery = planned.name === "agent_chat" || planned.name === "agent_review"
263
+ const delivery = planned.name === "agent_chat" || planned.name === AGENT_DRAFT
258
264
  ? chatDelivery?.({
259
265
  backend,
260
266
  principal,
@@ -689,7 +689,7 @@ export interface AgentStore {
689
689
  */
690
690
  readonly seeGuestChat?: (guestId: string) => Effect.Effect<SeenChat | undefined>;
691
691
  /**
692
- * A reply the agent held for review becomes a pending `agent_review` for the member it answers,
692
+ * A reply the agent kept for review becomes a pending `agent_draft` for the member it answers,
693
693
  * once per `key`: a repeated report answers the review it created. `undefined` when the member is
694
694
  * not an active member of the app. Absent on stores that predate reviews.
695
695
  */
@@ -733,7 +733,7 @@ export interface AgentStore {
733
733
  /** The chats' messages, in `_chat_messages`. Absent on stores that predate the chat store. */
734
734
  readonly chatMessages?: import("../runtime/chat-messages.js").ChatMessageStore;
735
735
  }
736
- /** A reply the agent held for review, as `POST /api/ontology/agent/reviews` reports it. */
736
+ /** A reply the agent held for review, as `POST /api/ontology/agent/drafts` reports it. */
737
737
  export interface HeldReplyInput {
738
738
  readonly key: string;
739
739
  /** The kind of channel the chat is on, such as whatsapp. */
@@ -760,7 +760,7 @@ export interface HeldReplyInput {
760
760
  readonly mode: "always" | "whenUnsure";
761
761
  readonly confidence: number | null;
762
762
  }
763
- /** A reply the agent redrafted, as `POST /api/ontology/agent/reviews/revision` reports it. */
763
+ /** A reply the agent redrafted, as `POST /api/ontology/agent/drafts/revision` reports it. */
764
764
  export interface RevisedReplyInput {
765
765
  /** The review the redraft replaces. */
766
766
  readonly review: string;
@@ -19,3 +19,9 @@ export interface OntologyService {
19
19
  * and `x-request-id`; failures answer with a JSON error and never a stack or SQL.
20
20
  */
21
21
  export declare function createOntologyService(ontology: Ontology, config: OntologyServiceConfig): OntologyService;
22
+ /**
23
+ * The request with a path that names a built-in entity by its earlier name, `/api/ontology/<earlier>/…`,
24
+ * under the current one, so that callers written for the earlier name reach the entity's routes;
25
+ * any other request as it is. Only the current names are listed in the catalog and the docs.
26
+ */
27
+ export declare function withCurrentEntityPath(request: Request): Request;
@@ -30,7 +30,7 @@ import { agentTasksLayer } from "./agent/tasks.js";
30
30
  import { makeMetricQueries } from "./metric-query.js";
31
31
  import { platformMetricQueries } from "./metric-query-platform.js";
32
32
  import { platformWarehouseQueries, WarehouseQueries } from "./warehouse-platform.js";
33
- import { ErrorResponsesLive, buildApi } from "./api.js";
33
+ import { BASE_PATH, ErrorResponsesLive, buildApi } from "./api.js";
34
34
  import { CurrentPrincipal, authenticationLayer, neonAuthSessionExchange, tokenVerifier, withPrincipal, } from "./authentication.js";
35
35
  import { currentCaller } from "./caller-context.js";
36
36
  import { OntologyServiceConfigError, } from "./config.js";
@@ -55,6 +55,7 @@ import { neonEmailCodes } from "./agent/guest-sign-up.js";
55
55
  import { vercelWorkflowEngine, workflowStarter, workflowsLayer } from "./workflows.js";
56
56
  import { deploymentWorkflowEngine } from "./workflow-deployment.js";
57
57
  import { OntologyBackend } from "./runtime-contract.js";
58
+ import { currentEntityPath } from "../earlier-entity-names.js";
58
59
  import { runtimeCredential, runtimeTokenVerifier, } from "./runtime-identity.js";
59
60
  /** The header every response carries: the hash of the manifest the service serves. */
60
61
  export const ONTOLOGY_HASH_HEADER = "x-ontology-hash";
@@ -518,7 +519,9 @@ export function createOntologyService(ontology, config) {
518
519
  const hash = ontology.manifest.hash;
519
520
  // Only names from the deployed plan enter diagnostics; arbitrary path segments may be private.
520
521
  function operationOf(request) {
521
- const path = new URL(request.url).pathname;
522
+ const requested = new URL(request.url).pathname;
523
+ // @legacy ontology.agent-review-entity-name
524
+ const path = currentEntityPath(requested, BASE_PATH) ?? requested;
522
525
  const parts = path.split("/");
523
526
  const entity = plan.entities.find((candidate) => candidate.name === parts[3]);
524
527
  if (parts[1] === "api" && parts[2] === "ontology" && entity !== undefined) {
@@ -555,7 +558,7 @@ export function createOntologyService(ontology, config) {
555
558
  throw new DeploymentAdmissionError("preview_authentication_unavailable");
556
559
  }
557
560
  }
558
- response = await web.handler(request, Context.make(RequestId, requestId));
561
+ response = await web.handler(withCurrentEntityPath(request), Context.make(RequestId, requestId));
559
562
  }
560
563
  catch (error) {
561
564
  if (error instanceof DeploymentAdmissionError) {
@@ -588,3 +591,18 @@ export function createOntologyService(ontology, config) {
588
591
  },
589
592
  };
590
593
  }
594
+ // @legacy ontology.agent-review-entity-name
595
+ /**
596
+ * The request with a path that names a built-in entity by its earlier name, `/api/ontology/<earlier>/…`,
597
+ * under the current one, so that callers written for the earlier name reach the entity's routes;
598
+ * any other request as it is. Only the current names are listed in the catalog and the docs.
599
+ */
600
+ export function withCurrentEntityPath(request) {
601
+ const url = new URL(request.url);
602
+ const current = currentEntityPath(url.pathname, BASE_PATH);
603
+ if (current === undefined) {
604
+ return request;
605
+ }
606
+ url.pathname = current;
607
+ return new Request(url, request);
608
+ }
@@ -0,0 +1,53 @@
1
+ import { type ChannelFile, type ChannelPart, type ChannelRequest, type DefiniteFailure } from "./channel-files.js";
2
+ /**
3
+ * Slack's message with files, which the agent's `attachments_send` and the ontology's delivery of
4
+ * an approved draft both send, with Slack's external upload: each file's bytes go to the address
5
+ * `files.getUploadURLExternal` answers, then one `files.completeUploadExternal` shares all of them
6
+ * in the chat with the text, as one visible message. Nothing is visible until that share, so a
7
+ * file that fails to upload is left out without anything reaching the person. The Web API calls
8
+ * go on the connection's `web` API and the bytes on its `files` API.
9
+ */
10
+ /** The most bytes of one file a single connection request carries to Slack. */
11
+ export declare const SLACK_FILE_BYTES: number;
12
+ /** The most files one `files.completeUploadExternal` shares. */
13
+ export declare const SLACK_FILES_PER_MESSAGE = 10;
14
+ /** Why Slack cannot take this file through one connection request, or undefined when it can. */
15
+ export declare function slackFileRefusal(file: {
16
+ readonly size: number;
17
+ }): {
18
+ readonly code: "too_large" | "empty";
19
+ readonly message: string;
20
+ } | undefined;
21
+ /** What Slack's upload of the files and its share became. */
22
+ export interface SlackFilesResult {
23
+ /**
24
+ * Each file's upload in the order given, which nobody sees: Slack's file id, or why it did not
25
+ * upload. A file that did not upload is not shared.
26
+ */
27
+ readonly uploads: ReadonlyArray<{
28
+ readonly index: number;
29
+ readonly slackFileId: string;
30
+ } | {
31
+ readonly index: number;
32
+ readonly code: string;
33
+ readonly cause: unknown;
34
+ }>;
35
+ /** The one visible message, absent when no file uploaded. */
36
+ readonly share?: ChannelPart;
37
+ }
38
+ /**
39
+ * Uploads `files`, then shares those that uploaded in `channel`, in `threadTs` when given, with
40
+ * `text` as the message's text. The share is `sent` when Slack confirms it, `failed` when Slack
41
+ * refused it with a code that proves nothing was posted, otherwise `uncertain`. Nothing is
42
+ * retried.
43
+ */
44
+ export declare function sendSlackFiles(options: {
45
+ readonly request: ChannelRequest;
46
+ readonly channel: string;
47
+ readonly threadTs?: string;
48
+ readonly files: ReadonlyArray<ChannelFile & {
49
+ readonly index?: number;
50
+ }>;
51
+ readonly text?: string;
52
+ readonly definite?: DefiniteFailure;
53
+ }): Promise<SlackFilesResult>;
@@ -0,0 +1,183 @@
1
+ import { ChannelAnswerError, isRecord, replyJson, unrelayed, } from "./channel-files.js";
2
+ import { MAXIMUM_CONNECTION_BODY_BYTES } from "./connection.js";
3
+ /**
4
+ * Slack's message with files, which the agent's `attachments_send` and the ontology's delivery of
5
+ * an approved draft both send, with Slack's external upload: each file's bytes go to the address
6
+ * `files.getUploadURLExternal` answers, then one `files.completeUploadExternal` shares all of them
7
+ * in the chat with the text, as one visible message. Nothing is visible until that share, so a
8
+ * file that fails to upload is left out without anything reaching the person. The Web API calls
9
+ * go on the connection's `web` API and the bytes on its `files` API.
10
+ */
11
+ /** The most bytes of one file a single connection request carries to Slack. */
12
+ export const SLACK_FILE_BYTES = MAXIMUM_CONNECTION_BODY_BYTES;
13
+ /** The most files one `files.completeUploadExternal` shares. */
14
+ export const SLACK_FILES_PER_MESSAGE = 10;
15
+ /** Where Slack's upload addresses are, which the connection's `files` API reaches. */
16
+ const SLACK_FILES = "https://files.slack.com/";
17
+ /**
18
+ * Slack's `ok: false` codes that do not prove the share was not posted: Slack says some of the
19
+ * operation may have succeeded before the error.
20
+ */
21
+ const POSSIBLY_POSTED = new Set([
22
+ "internal_error",
23
+ "fatal_error",
24
+ "service_unavailable",
25
+ ]);
26
+ /** Why Slack cannot take this file through one connection request, or undefined when it can. */
27
+ export function slackFileRefusal(file) {
28
+ if (file.size > SLACK_FILE_BYTES) {
29
+ return {
30
+ code: "too_large",
31
+ message: `The connection takes at most ${SLACK_FILE_BYTES} bytes per upload.`,
32
+ };
33
+ }
34
+ if (file.size === 0) {
35
+ return { code: "empty", message: "Slack cannot share an empty file." };
36
+ }
37
+ return undefined;
38
+ }
39
+ /** A Web API call's refusal code, by Slack's own error code. */
40
+ function refusalCode(error) {
41
+ return error === "missing_scope" || error === "not_in_channel" ? "forbidden" : "send_failed";
42
+ }
43
+ class SlackCallError extends Error {
44
+ code;
45
+ status;
46
+ answer;
47
+ name = "SlackCallError";
48
+ constructor(message, code, status,
49
+ /** Slack's answer, kept for operators. */
50
+ answer) {
51
+ super(message);
52
+ this.code = code;
53
+ this.status = status;
54
+ this.answer = answer;
55
+ }
56
+ }
57
+ /**
58
+ * Uploads `files`, then shares those that uploaded in `channel`, in `threadTs` when given, with
59
+ * `text` as the message's text. The share is `sent` when Slack confirms it, `failed` when Slack
60
+ * refused it with a code that proves nothing was posted, otherwise `uncertain`. Nothing is
61
+ * retried.
62
+ */
63
+ export async function sendSlackFiles(options) {
64
+ /** One Web API call; Slack's own refusal (`ok: false`) throws with its error code. */
65
+ async function call(method, contentType, body) {
66
+ const reply = await options.request({
67
+ api: "web",
68
+ method: "POST",
69
+ path: `/${method}`,
70
+ headers: [["content-type", contentType]],
71
+ body: new TextEncoder().encode(body),
72
+ });
73
+ const answer = replyJson(reply);
74
+ if (reply.status < 200 || reply.status >= 300 || !isRecord(answer) || answer.ok !== true) {
75
+ const code = isRecord(answer) && typeof answer.error === "string" ? answer.error : "";
76
+ throw new SlackCallError(`Slack refused ${method}${code === "" ? "" : `: ${code}`}.`, refusalCode(code), reply.status, answer);
77
+ }
78
+ return answer;
79
+ }
80
+ const uploads = [];
81
+ const uploaded = [];
82
+ for (const [position, file] of options.files.entries()) {
83
+ const index = file.index ?? position;
84
+ try {
85
+ const ticket = await call("files.getUploadURLExternal", "application/x-www-form-urlencoded", new URLSearchParams({
86
+ filename: file.filename,
87
+ length: String(file.bytes.byteLength),
88
+ }).toString());
89
+ if (typeof ticket.upload_url !== "string" ||
90
+ !ticket.upload_url.startsWith(SLACK_FILES) ||
91
+ typeof ticket.file_id !== "string") {
92
+ throw new SlackCallError("Slack answered no upload address.", "invalid_response", 200);
93
+ }
94
+ const reply = await options.request({
95
+ api: "files",
96
+ method: "POST",
97
+ path: `/${ticket.upload_url.slice(SLACK_FILES.length)}`,
98
+ headers: [["content-type", file.contentType]],
99
+ body: file.bytes,
100
+ });
101
+ if (reply.status < 200 || reply.status >= 300) {
102
+ throw new SlackCallError("Slack refused the file's bytes.", "send_failed", reply.status, replyJson(reply) ?? new TextDecoder().decode(reply.body).slice(0, 2000));
103
+ }
104
+ uploads.push({ index, slackFileId: ticket.file_id });
105
+ uploaded.push({ index, id: ticket.file_id, title: file.filename });
106
+ }
107
+ catch (error) {
108
+ uploads.push({
109
+ index,
110
+ code: error instanceof SlackCallError ? error.code : "send_failed",
111
+ cause: error,
112
+ });
113
+ }
114
+ }
115
+ if (uploaded.length === 0) {
116
+ return { uploads };
117
+ }
118
+ const part = { files: uploaded.map(({ index }) => index), text: options.text !== undefined };
119
+ let reply;
120
+ try {
121
+ reply = await options.request({
122
+ api: "web",
123
+ method: "POST",
124
+ path: "/files.completeUploadExternal",
125
+ headers: [["content-type", "application/json; charset=utf-8"]],
126
+ body: new TextEncoder().encode(JSON.stringify({
127
+ files: uploaded.map(({ id, title }) => ({ id, title })),
128
+ channel_id: options.channel,
129
+ ...(options.threadTs === undefined || options.threadTs === ""
130
+ ? {}
131
+ : { thread_ts: options.threadTs }),
132
+ ...(options.text === undefined ? {} : { initial_comment: options.text }),
133
+ })),
134
+ });
135
+ }
136
+ catch (error) {
137
+ return { uploads, share: unrelayed(part, error, options.definite) };
138
+ }
139
+ const answer = replyJson(reply);
140
+ if (reply.status >= 200 &&
141
+ reply.status < 300 &&
142
+ isRecord(answer) &&
143
+ answer.ok === true &&
144
+ Array.isArray(answer.files)) {
145
+ return {
146
+ uploads,
147
+ share: { ...part, status: "sent", messageIds: shareTs(answer.files, options.channel) },
148
+ };
149
+ }
150
+ const error = isRecord(answer) && typeof answer.error === "string" ? answer.error : "";
151
+ const definite = reply.status < 500 &&
152
+ isRecord(answer) &&
153
+ answer.ok === false &&
154
+ error !== "" &&
155
+ !POSSIBLY_POSTED.has(error);
156
+ return {
157
+ uploads,
158
+ share: {
159
+ ...part,
160
+ status: definite ? "failed" : "uncertain",
161
+ messageIds: [],
162
+ code: reply.status >= 200 && reply.status < 300 && answer !== undefined && error === ""
163
+ ? "invalid_response"
164
+ : refusalCode(error),
165
+ cause: new ChannelAnswerError(`Slack answered files.completeUploadExternal with status ${reply.status}` +
166
+ (error === "" ? "." : `: ${error}.`), reply.status, reply),
167
+ },
168
+ };
169
+ }
170
+ /** The message's `ts` in `channel`, when Slack's answer names the share. */
171
+ function shareTs(files, channel) {
172
+ for (const file of files) {
173
+ const shares = isRecord(file) && isRecord(file.shares) ? file.shares : {};
174
+ for (const scope of [shares.public, shares.private]) {
175
+ const list = isRecord(scope) ? scope[channel] : undefined;
176
+ const ts = Array.isArray(list) && isRecord(list[0]) ? list[0].ts : undefined;
177
+ if (typeof ts === "string" && ts !== "") {
178
+ return [ts];
179
+ }
180
+ }
181
+ }
182
+ return [];
183
+ }
package/dist/slack.d.ts CHANGED
@@ -13,3 +13,6 @@ export declare function escapeSlackMarkdown(text: string): string;
13
13
  * Markdown.
14
14
  */
15
15
  export declare function renderSlack(markdown: string, attribution: string, separator?: string): string;
16
+ export type { ChannelCall, ChannelFile, ChannelPart, ChannelReply, ChannelRequest, DefiniteFailure, } from "./channel-files.js";
17
+ export { ChannelAnswerError } from "./channel-files.js";
18
+ export { sendSlackFiles, slackFileRefusal, SLACK_FILE_BYTES, SLACK_FILES_PER_MESSAGE, type SlackFilesResult, } from "./slack-files.js";
package/dist/slack.js CHANGED
@@ -21,3 +21,5 @@ export function renderSlack(markdown, attribution, separator = "\n\n") {
21
21
  ? markdown
22
22
  : `${markdown}${escapeSlackMarkdown(separator)}_${escapeSlackMarkdown(attribution)}_`;
23
23
  }
24
+ export { ChannelAnswerError } from "./channel-files.js";
25
+ export { sendSlackFiles, slackFileRefusal, SLACK_FILE_BYTES, SLACK_FILES_PER_MESSAGE, } from "./slack-files.js";
@@ -36,8 +36,7 @@ export const ATTACHMENT_TTL_HOURS = 24;
36
36
  export const MAX_LIVE_ATTACHMENTS = 50;
37
37
  export { ATTACHMENT_SOURCES };
38
38
  const SHA256 = /^[0-9a-f]{64}$/;
39
- // @legacy ontology.attachment-conversation-column: the SQL here names the chat column `conversation`.
40
- const SELECT = `SELECT a.id::text, a.blob_id::text, b.key, a.owner_id::text, a.conversation AS chat,
39
+ const SELECT = `SELECT a.id::text, a.blob_id::text, b.key, a.owner_id::text, a.chat,
41
40
  a.session_id, a.filename, a.content_type, a.size::text, a.sha256, a.state, a.provider_upload_id,
42
41
  a.promotion,
43
42
  to_char(a.created_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"') AS created_at,
@@ -204,7 +203,7 @@ export function attachmentRuntime(ontology, sql, provider) {
204
203
  if (access === "denied") {
205
204
  return yield* missing(id);
206
205
  }
207
- const rows = yield* sql.unsafe(`${SELECT} WHERE a.id = $1::uuid AND (a.owner_id = $2::uuid OR $5) AND a.conversation = $3
206
+ const rows = yield* sql.unsafe(`${SELECT} WHERE a.id = $1::uuid AND (a.owner_id = $2::uuid OR $5) AND a.chat = $3
208
207
  AND a.branch_id = $4 FOR UPDATE OF a, b`, [
209
208
  id,
210
209
  caller.principal.id,
@@ -262,7 +261,7 @@ export function attachmentRuntime(ontology, sql, provider) {
262
261
  yield* authorizeBlobOperation(ontology, sql, caller.principal.id, [], caller.principal.execution);
263
262
  yield* sql.unsafe(`SELECT pg_advisory_xact_lock(818724)`);
264
263
  const [existing] = yield* sql.unsafe(`SELECT id::text FROM "${ATTACHMENTS_TABLE}"
265
- WHERE owner_id = $1::uuid AND conversation = $2 AND source_ref = $3`, [caller.principal.id, caller.chat, input.sourceRef]);
264
+ WHERE owner_id = $1::uuid AND chat = $2 AND source_ref = $3`, [caller.principal.id, caller.chat, input.sourceRef]);
266
265
  if (existing) {
267
266
  const row = yield* load(existing.id, caller, "source");
268
267
  if (row.sha256 !== input.sha256 || Number(row.size) !== input.size) {
@@ -304,7 +303,7 @@ export function attachmentRuntime(ontology, sql, provider) {
304
303
  input.size,
305
304
  ]);
306
305
  yield* sql.unsafe(`INSERT INTO "${ATTACHMENTS_TABLE}"
307
- (id, blob_id, branch_id, owner_id, conversation, session_id, source, source_ref,
306
+ (id, blob_id, branch_id, owner_id, chat, session_id, source, source_ref,
308
307
  filename, content_type, size, sha256, state, expires_at)
309
308
  VALUES ($1::uuid, $2::uuid, $3, $4::uuid, $5, $6, $7, $8, $9, $10, $11::bigint, $12,
310
309
  'received', ${expiry(caller.chat, "now()")})`, [
@@ -394,7 +393,7 @@ export function attachmentRuntime(ontology, sql, provider) {
394
393
  if (access === "denied") {
395
394
  return [];
396
395
  }
397
- const rows = yield* sql.unsafe(`${SELECT} WHERE (a.owner_id = $1::uuid OR $5) AND a.conversation = $2 AND a.branch_id = $3
396
+ const rows = yield* sql.unsafe(`${SELECT} WHERE (a.owner_id = $1::uuid OR $5) AND a.chat = $2 AND a.branch_id = $3
398
397
  AND a.state IN ('ready', 'promoted') AND a.expires_at > now()
399
398
  AND ($5 OR a.session_id IS NULL OR a.session_id = $4)
400
399
  ORDER BY a.created_at DESC LIMIT ${MAX_LIVE_ATTACHMENTS}`, [
@@ -499,7 +498,7 @@ export function attachmentRuntime(ontology, sql, provider) {
499
498
  const [earlier] = yield* sql.unsafe(`SELECT id::text, promotion FROM "${ATTACHMENTS_TABLE}"
500
499
  WHERE sha256 = $1 AND branch_id = $2 AND state = 'promoted' AND id <> $3::uuid
501
500
  AND promotion->>'action' = $4 AND promotion->>'deduplicated_from' IS NULL
502
- AND conversation = $5 AND (owner_id = $6::uuid OR $7)
501
+ AND chat = $5 AND (owner_id = $6::uuid OR $7)
503
502
  AND ($7 OR $9 OR session_id IS NULL OR session_id = $8)
504
503
  ORDER BY created_at LIMIT 1`, [
505
504
  row.sha256,
@@ -640,7 +639,7 @@ export function attachmentRuntime(ontology, sql, provider) {
640
639
  // The attachment an earlier import made of the upload, which only the same message's file
641
640
  // replays: a consumed upload is no other message's file.
642
641
  const adopted = (blobId) => Effect.gen(function* () {
643
- const [row] = yield* sql.unsafe(`${SELECT.replace("SELECT ", "SELECT (a.owner_id = $3::uuid AND a.conversation = $4 AND a.source_ref = $5) AS same, ")} WHERE a.blob_id = $1::uuid AND a.branch_id = $2`, [blobId, binding.branchId, input.ownerId, input.chat, input.sourceRef]);
642
+ const [row] = yield* sql.unsafe(`${SELECT.replace("SELECT ", "SELECT (a.owner_id = $3::uuid AND a.chat = $4 AND a.source_ref = $5) AS same, ")} WHERE a.blob_id = $1::uuid AND a.branch_id = $2`, [blobId, binding.branchId, input.ownerId, input.chat, input.sourceRef]);
644
643
  if (row !== undefined && row.same !== true) {
645
644
  return yield* new Conflict({
646
645
  entity: "upload",
@@ -688,13 +687,13 @@ export function attachmentRuntime(ontology, sql, provider) {
688
687
  : { attachment: view(held), adopted: true };
689
688
  }
690
689
  const [inserted] = yield* sql.unsafe(`INSERT INTO "${ATTACHMENTS_TABLE}"
691
- (id, blob_id, branch_id, owner_id, conversation, session_id, source, source_ref,
690
+ (id, blob_id, branch_id, owner_id, chat, session_id, source, source_ref,
692
691
  filename, content_type, size, sha256, state, created_at, expires_at)
693
692
  SELECT $1::uuid, u.blob_id, u.branch_id, $3::uuid, $4, NULL, $5, $6, u.filename,
694
693
  u.content_type, u.size, $7, 'ready', $8::timestamptz,
695
694
  ${expiry(input.chat, "$8::timestamptz")}
696
695
  FROM "_blob_uploads" u WHERE u.id = $2::uuid
697
- ON CONFLICT ("owner_id", "conversation", "source_ref") DO NOTHING
696
+ ON CONFLICT ("owner_id", "chat", "source_ref") DO NOTHING
698
697
  RETURNING id::text`, [
699
698
  randomUUID(),
700
699
  upload.id,
@@ -706,7 +705,7 @@ export function attachmentRuntime(ontology, sql, provider) {
706
705
  input.at,
707
706
  ]);
708
707
  if (inserted === undefined) {
709
- const [held] = yield* sql.unsafe(`${SELECT} WHERE a.owner_id = $1::uuid AND a.conversation = $2
708
+ const [held] = yield* sql.unsafe(`${SELECT} WHERE a.owner_id = $1::uuid AND a.chat = $2
710
709
  AND a.source_ref = $3 AND a.branch_id = $4`, [input.ownerId, input.chat, input.sourceRef, binding.branchId]);
711
710
  return { attachment: view(held), adopted: false };
712
711
  }
@@ -723,7 +722,7 @@ export function attachmentRuntime(ontology, sql, provider) {
723
722
  if (!/^[0-9a-f-]{36}$/i.test(id)) {
724
723
  return yield* missing(id);
725
724
  }
726
- const [row] = yield* sql.unsafe(`SELECT conversation AS chat FROM "${ATTACHMENTS_TABLE}" WHERE id = $1::uuid AND branch_id = $2`, [id, binding.branchId]);
725
+ const [row] = yield* sql.unsafe(`SELECT chat FROM "${ATTACHMENTS_TABLE}" WHERE id = $1::uuid AND branch_id = $2`, [id, binding.branchId]);
727
726
  if (!row) {
728
727
  return yield* missing(id);
729
728
  }
@@ -771,7 +770,7 @@ export function attachmentRuntime(ontology, sql, provider) {
771
770
  }
772
771
  reads = scope === "reader";
773
772
  if (scope === "private") {
774
- const [sent] = yield* sql.unsafe(`SELECT 1 FROM "${ATTACHMENTS_TABLE}" WHERE branch_id = $1 AND conversation = $2
773
+ const [sent] = yield* sql.unsafe(`SELECT 1 FROM "${ATTACHMENTS_TABLE}" WHERE branch_id = $1 AND chat = $2
775
774
  AND owner_id = $3::uuid LIMIT 1`, [binding.branchId, filters.chat, principal.id]);
776
775
  if (sent === undefined) {
777
776
  return yield* missing("chat");
@@ -782,13 +781,13 @@ export function attachmentRuntime(ontology, sql, provider) {
782
781
  const rows = yield* sql.unsafe(`${SELECT} WHERE a.branch_id = $1
783
782
  AND ($2 OR EXISTS (
784
783
  SELECT 1 FROM "agent_chat" c JOIN "agent_chat_members" m ON m.agent_chat_id = c.id
785
- WHERE c.provider || ':' || c.external_id = a.conversation AND c.kind::text = 'group'
784
+ WHERE c.provider || ':' || c.external_id = a.chat AND c.kind::text = 'group'
786
785
  AND m.user_id = $3::uuid
787
786
  ) OR (a.owner_id = $3::uuid AND NOT EXISTS (
788
787
  SELECT 1 FROM "agent_chat" c
789
- WHERE c.provider || ':' || c.external_id = a.conversation AND c.kind::text = 'group'
788
+ WHERE c.provider || ':' || c.external_id = a.chat AND c.kind::text = 'group'
790
789
  )))
791
- AND ($4::text IS NULL OR a.conversation = $4)
790
+ AND ($4::text IS NULL OR a.chat = $4)
792
791
  AND ($5::uuid IS NULL OR a.owner_id = $5::uuid)
793
792
  AND ($6::timestamptz IS NULL OR a.created_at >= $6::timestamptz)
794
793
  AND ($7::timestamptz IS NULL OR a.created_at <= $7::timestamptz)