@capybara-hq/kernel 0.1.0-rc.134 → 0.1.0-rc.136

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 (113) hide show
  1. package/bootstrap.json +1 -1
  2. package/dist/admin/admin.module.js +3 -0
  3. package/dist/admin/health.service.d.ts +2 -2
  4. package/dist/admin/health.service.js +6 -2
  5. package/dist/catalog/marketplaces.service.d.ts +1 -1
  6. package/dist/config/schema.d.ts +7 -0
  7. package/dist/config/schema.js +60 -2
  8. package/dist/conversations/access.d.ts +15 -7
  9. package/dist/conversations/access.js +59 -10
  10. package/dist/conversations/conversation-agent.d.ts +18 -0
  11. package/dist/conversations/conversation-agent.js +23 -0
  12. package/dist/conversations/conversation-ref.d.ts +3 -2
  13. package/dist/conversations/conversation-ref.js +6 -1
  14. package/dist/conversations/conversations.controller.d.ts +28 -5
  15. package/dist/conversations/conversations.controller.js +99 -10
  16. package/dist/conversations/conversations.module.js +10 -0
  17. package/dist/conversations/conversations.schemas.d.ts +6 -0
  18. package/dist/conversations/conversations.schemas.js +15 -0
  19. package/dist/conversations/conversations.service.d.ts +125 -21
  20. package/dist/conversations/conversations.service.js +260 -90
  21. package/dist/conversations/event-log.d.ts +9 -1
  22. package/dist/conversations/event-log.js +2 -0
  23. package/dist/conversations/events.d.ts +57 -0
  24. package/dist/conversations/events.js +73 -1
  25. package/dist/conversations/external/external-calls.d.ts +75 -0
  26. package/dist/conversations/external/external-calls.js +91 -0
  27. package/dist/conversations/external/external-calls.processor.d.ts +45 -0
  28. package/dist/conversations/external/external-calls.processor.js +144 -0
  29. package/dist/conversations/external/external-conversations.service.d.ts +266 -0
  30. package/dist/conversations/external/external-conversations.service.js +1138 -0
  31. package/dist/conversations/external/external.schemas.d.ts +63 -0
  32. package/dist/conversations/external/external.schemas.js +52 -0
  33. package/dist/conversations/external/token.d.ts +6 -0
  34. package/dist/conversations/external/token.js +6 -0
  35. package/dist/conversations/permission-profile-store.d.ts +4 -1
  36. package/dist/conversations/permission-profiles.controller.d.ts +33 -9
  37. package/dist/conversations/permission-profiles.controller.js +86 -6
  38. package/dist/conversations/prompt-suggestions.js +2 -1
  39. package/dist/conversations/queue.js +2 -1
  40. package/dist/conversations/titles.js +4 -3
  41. package/dist/ctx/create-ctx.d.ts +7 -0
  42. package/dist/ctx/create-ctx.js +45 -2
  43. package/dist/db/extension-db.d.ts +8 -3
  44. package/dist/db/extension-db.js +107 -7
  45. package/dist/db/extension-role-provision.d.ts +9 -0
  46. package/dist/db/extension-role-provision.js +89 -0
  47. package/dist/db/extension-schema-transfer.d.ts +2 -1
  48. package/dist/db/extension-schema-transfer.js +103 -19
  49. package/dist/db/kernel-schema.d.ts +31 -4
  50. package/dist/db/migrator.d.ts +2 -0
  51. package/dist/db/migrator.js +4 -3
  52. package/dist/device-access/host-services.js +3 -2
  53. package/dist/device-access/person-handles.d.ts +16 -7
  54. package/dist/device-access/person-handles.js +14 -9
  55. package/dist/devices/conversation-devices.d.ts +5 -0
  56. package/dist/devices/conversation-devices.js +16 -0
  57. package/dist/erasure/org-catalog.js +2 -2
  58. package/dist/errors.d.ts +34 -0
  59. package/dist/errors.js +34 -0
  60. package/dist/evals/snapshot.js +3 -1
  61. package/dist/evals/trajectory.service.d.ts +2 -2
  62. package/dist/evals/trajectory.service.js +11 -7
  63. package/dist/extensions/admin-ops.js +17 -1
  64. package/dist/extensions/extensions.module.js +3 -0
  65. package/dist/extensions/host.d.ts +9 -1
  66. package/dist/extensions/host.js +14 -2
  67. package/dist/extensions/migrate-lock.js +1 -0
  68. package/dist/extensions/permission-view.d.ts +3 -1
  69. package/dist/extensions/permission-view.js +4 -1
  70. package/dist/extensions/point-defaults.d.ts +13 -21
  71. package/dist/extensions/point-defaults.js +32 -72
  72. package/dist/extensions/point-serving.d.ts +56 -0
  73. package/dist/extensions/point-serving.js +120 -0
  74. package/dist/inbox/inbox-items.service.d.ts +11 -0
  75. package/dist/inbox/inbox-items.service.js +39 -0
  76. package/dist/index.d.ts +3 -1
  77. package/dist/index.js +3 -1
  78. package/dist/infra/database/rls-role.d.ts +4 -11
  79. package/dist/infra/database/rls-role.js +71 -27
  80. package/dist/infra/outbox/registry.d.ts +70 -0
  81. package/dist/infra/outbox/registry.js +44 -0
  82. package/dist/infra/queue/queue-names.d.ts +1 -1
  83. package/dist/infra/queue/queue-names.js +1 -0
  84. package/dist/kernel.d.ts +2 -0
  85. package/dist/kernel.js +12 -2
  86. package/dist/kernel.module.js +4 -0
  87. package/dist/lifecycle/kernel-lifecycle.js +2 -3
  88. package/dist/platform/exclusions.js +10 -0
  89. package/dist/platform/ops/conversations.ops.d.ts +8 -1
  90. package/dist/platform/ops/conversations.ops.js +52 -14
  91. package/dist/plugin-reads/plugin-reads.service.js +4 -1
  92. package/dist/push/recipients.js +5 -2
  93. package/dist/retention/worker.js +2 -1
  94. package/dist/roles/worker-role.d.ts +3 -1
  95. package/dist/roles/worker-role.js +8 -2
  96. package/dist/roles/worker.module.js +3 -0
  97. package/dist/runtime/context/build.js +8 -0
  98. package/dist/runtime/context/compaction.js +7 -0
  99. package/dist/runtime/idle-arm.js +3 -1
  100. package/dist/runtime/idle-compaction.js +2 -1
  101. package/dist/runtime/run-finish.js +2 -1
  102. package/dist/runtime/run-jobs.js +2 -1
  103. package/dist/runtime/run-queue.js +4 -2
  104. package/dist/runtime/run-worker.js +5 -2
  105. package/dist/runtime/stream.js +10 -0
  106. package/dist/runtime/usage-report.js +2 -1
  107. package/dist/runtime/waits.js +2 -1
  108. package/dist/tools/approvals.service.js +6 -2
  109. package/dist/tools/builtins/skill-load.js +3 -2
  110. package/dist/tools/tool-watch.service.js +3 -1
  111. package/package.json +3 -3
  112. package/src/migrations/0226_enable_kernel_rls.sql +30 -0
  113. package/src/migrations/0227_external_conversations.sql +33 -0
@@ -52,6 +52,10 @@ export declare const conversationTopic: (conversationId: string) => string;
52
52
  * SSE forwards the flat data as `event: compaction`. Ephemeral, display-only, not in the log.
53
53
  * - `prompt_suggestion`: a completed run's prompt suggestion was stored (prompt suggestions spec
54
54
  * §4, `PromptSuggestionStore`). Ephemeral, display-only, not in the log.
55
+ * - `external_delta`: the partial text so far of an external conversation's message `messageId`
56
+ * (`ctx.conversations.streamExternalText`, local agents spec Part 2); the SSE forwards it as
57
+ * `event: external_draft`. A hint, never stored: the completed message arrives as an
58
+ * `external_message` event.
55
59
  */
56
60
  export type ConversationBusMessage = {
57
61
  kind: "events";
@@ -101,12 +105,16 @@ export type ConversationBusMessage = {
101
105
  runId: string;
102
106
  afterSeq: number;
103
107
  text: string;
108
+ } | {
109
+ kind: "external_delta";
110
+ messageId: string;
111
+ text: string;
104
112
  };
105
113
  /**
106
114
  * What changed about a conversation outside its event log (UI refresh B): the SSE stream sends it as
107
115
  * `event: changed` with `{ what }`, and the web refetches that part. Never model-visible.
108
116
  */
109
- export declare const CONVERSATION_CHANGES: readonly ["title", "queue", "selection", "files", "archived", "deleted", "background"];
117
+ export declare const CONVERSATION_CHANGES: readonly ["title", "queue", "selection", "files", "archived", "deleted", "background", "external_state"];
110
118
  export type ConversationChange = (typeof CONVERSATION_CHANGES)[number];
111
119
  /**
112
120
  * 会话事件日志:只追加,是 agent 运行的唯一事实来源。
@@ -58,6 +58,8 @@ export const CONVERSATION_CHANGES = [
58
58
  "deleted",
59
59
  // the conversation's background tasks (or its sub-agents')
60
60
  "background",
61
+ // the state an external conversation's target reported (`external_state`)
62
+ "external_state",
61
63
  ];
62
64
  const notFound = () => new ApiError("conversation.not_found", "Conversation not found");
63
65
  function toEvent(r, withUsagePricing = false) {
@@ -2176,6 +2176,63 @@ export declare const ConversationEventSchema: z.ZodDiscriminatedUnion<[z.ZodObje
2176
2176
  wait_timeout: "wait_timeout";
2177
2177
  }>>;
2178
2178
  }, z.core.$strip>;
2179
+ }, z.core.$strip>, z.ZodObject<{
2180
+ type: z.ZodLiteral<"external_user_message">;
2181
+ payload: z.ZodObject<{
2182
+ messageId: z.ZodString;
2183
+ text: z.ZodString;
2184
+ interrupt: z.ZodBoolean;
2185
+ deliverySeq: z.ZodNumber;
2186
+ }, z.core.$strip>;
2187
+ }, z.core.$strip>, z.ZodObject<{
2188
+ type: z.ZodLiteral<"external_message">;
2189
+ payload: z.ZodObject<{
2190
+ messageId: z.ZodString;
2191
+ role: z.ZodLiteral<"assistant">;
2192
+ text: z.ZodString;
2193
+ }, z.core.$strip>;
2194
+ }, z.core.$strip>, z.ZodObject<{
2195
+ type: z.ZodLiteral<"external_activity">;
2196
+ payload: z.ZodObject<{
2197
+ activityId: z.ZodString;
2198
+ title: z.ZodString;
2199
+ detail: z.ZodOptional<z.ZodString>;
2200
+ status: z.ZodEnum<{
2201
+ done: "done";
2202
+ failed: "failed";
2203
+ running: "running";
2204
+ }>;
2205
+ }, z.core.$strip>;
2206
+ }, z.core.$strip>, z.ZodObject<{
2207
+ type: z.ZodLiteral<"external_request">;
2208
+ payload: z.ZodObject<{
2209
+ requestId: z.ZodString;
2210
+ title: z.ZodString;
2211
+ detail: z.ZodOptional<z.ZodString>;
2212
+ options: z.ZodArray<z.ZodObject<{
2213
+ id: z.ZodString;
2214
+ label: z.ZodObject<{
2215
+ zh: z.ZodString;
2216
+ en: z.ZodString;
2217
+ }, z.core.$strip>;
2218
+ }, z.core.$strip>>;
2219
+ }, z.core.$strip>;
2220
+ }, z.core.$strip>, z.ZodObject<{
2221
+ type: z.ZodLiteral<"external_request_answered">;
2222
+ payload: z.ZodObject<{
2223
+ requestId: z.ZodString;
2224
+ optionId: z.ZodString;
2225
+ byAccountId: z.ZodString;
2226
+ }, z.core.$strip>;
2227
+ }, z.core.$strip>, z.ZodObject<{
2228
+ type: z.ZodLiteral<"external_turn">;
2229
+ payload: z.ZodObject<{
2230
+ state: z.ZodEnum<{
2231
+ ended: "ended";
2232
+ failed: "failed";
2233
+ }>;
2234
+ error: z.ZodOptional<z.ZodString>;
2235
+ }, z.core.$strip>;
2179
2236
  }, z.core.$strip>], "type">;
2180
2237
  /** 事件体:`{ type, payload }` 的判别联合。 */
2181
2238
  export type ConversationEventBody = z.infer<typeof ConversationEventSchema>;
@@ -1,5 +1,5 @@
1
1
  import { posix } from "node:path";
2
- import { CARD_BADGE_MAX, CARD_TEXT_MAX, CONTEXT_LIMITS, DOCUMENT_MEDIA_TYPES, hasControlChars, IMAGE_MEDIA_TYPES, isAttachmentId, isFileId, isSkillName, MEDIA_NAME_MAX_CHARS, SITE_ACCESS_ACTIONS, validateAllowHost, validateSandboxPathShape, } from "@capybara-hq/plugin-sdk";
2
+ import { CARD_BADGE_MAX, CARD_TEXT_MAX, CONTEXT_LIMITS, DOCUMENT_MEDIA_TYPES, EXTERNAL_EVENT_ID_RE, EXTERNAL_EVENT_LIMITS, EXTERNAL_OPTION_ID_RE, hasControlChars, IMAGE_MEDIA_TYPES, isAttachmentId, isFileId, isSkillName, MEDIA_NAME_MAX_CHARS, SITE_ACCESS_ACTIONS, validateAllowHost, validateSandboxPathShape, } from "@capybara-hq/plugin-sdk";
3
3
  import { z } from "zod";
4
4
  import { AgentDefinitionSchema, DisabledSkillRef, DisabledToolRef, ModelRef, } from "../agents/definition.js";
5
5
  import { PriceSnapshotSchema } from "../models/price-snapshot.js";
@@ -778,6 +778,15 @@ export const PluginContextSchema = z.object({
778
778
  }),
779
779
  hash: z.string().regex(/^[0-9a-f]{64}$/),
780
780
  });
781
+ /** A text of an external event: at most `EXTERNAL_EVENT_LIMITS.textBytes` UTF-8 bytes. */
782
+ const externalText = z
783
+ .string()
784
+ .refine((t) => Buffer.byteLength(t, "utf8") <= EXTERNAL_EVENT_LIMITS.textBytes, {
785
+ message: `at most ${EXTERNAL_EVENT_LIMITS.textBytes} UTF-8 bytes`,
786
+ });
787
+ const externalTitle = z.string().min(1).max(EXTERNAL_EVENT_LIMITS.titleChars);
788
+ /** An id a target chooses, as `parseExternalEvents` takes it (`EXTERNAL_EVENT_ID_RE`). */
789
+ const externalId = z.string().regex(EXTERNAL_EVENT_ID_RE);
781
790
  /**
782
791
  * 会话事件(`type` + `payload`)的判别联合。事件日志只追加,写入前用它校验 payload;
783
792
  * 读出时按写入时的形状原样返回。
@@ -1990,6 +1999,69 @@ export const ConversationEventSchema = z.discriminatedUnion("type", [
1990
1999
  .enum(["cancelled", "capped", "too_many_errors", "claim_lost", "shutdown", "wait_timeout"])
1991
2000
  .optional(),
1992
2001
  })),
2002
+ // External conversations (local agents spec Part 2): the log mirrors a conversation held with a
2003
+ // `conversation-target@1` target. None of these events is model-visible: external conversations
2004
+ // have no runs, so request building and compaction skip them and they need no DriftReason.
2005
+ /**
2006
+ * The person's message to the target, written by the kernel. `deliverySeq` orders the messages
2007
+ * the target receives (1 = the first message, delivered with `start`); `interrupt` asks the
2008
+ * target to stop its current turn. Not model-visible; external conversations have no runs, no
2009
+ * DriftReason.
2010
+ */
2011
+ ev("external_user_message", z.object({
2012
+ messageId: externalId,
2013
+ text: externalText,
2014
+ interrupt: z.boolean(),
2015
+ deliverySeq: z.number().int().positive(),
2016
+ })),
2017
+ /**
2018
+ * A completed message of the target (`ExternalEvent`). Not model-visible; external conversations
2019
+ * have no runs, no DriftReason.
2020
+ */
2021
+ ev("external_message", z.object({ messageId: externalId, role: z.literal("assistant"), text: externalText })),
2022
+ /**
2023
+ * What the target is doing or did (a command, an edit). Not model-visible; external
2024
+ * conversations have no runs, no DriftReason.
2025
+ */
2026
+ ev("external_activity", z.object({
2027
+ activityId: externalId,
2028
+ title: externalTitle,
2029
+ detail: externalText.optional(),
2030
+ status: z.enum(["running", "done", "failed"]),
2031
+ })),
2032
+ /**
2033
+ * A choice the target asks the person to make. Not model-visible; external conversations have
2034
+ * no runs, no DriftReason.
2035
+ */
2036
+ ev("external_request", z.object({
2037
+ requestId: externalId,
2038
+ title: externalTitle,
2039
+ detail: externalText.optional(),
2040
+ options: z
2041
+ .array(z.object({
2042
+ id: z.string().regex(EXTERNAL_OPTION_ID_RE),
2043
+ label: z.object({
2044
+ zh: z.string().max(EXTERNAL_EVENT_LIMITS.titleChars),
2045
+ en: z.string().max(EXTERNAL_EVENT_LIMITS.titleChars),
2046
+ }),
2047
+ }))
2048
+ .min(1)
2049
+ .max(EXTERNAL_EVENT_LIMITS.options),
2050
+ })),
2051
+ /**
2052
+ * The person's answer to an `external_request`, written by the kernel once per request. Not
2053
+ * model-visible; external conversations have no runs, no DriftReason.
2054
+ */
2055
+ ev("external_request_answered", z.object({
2056
+ requestId: externalId,
2057
+ optionId: z.string().regex(EXTERNAL_OPTION_ID_RE),
2058
+ byAccountId: z.string(),
2059
+ })),
2060
+ /**
2061
+ * The end of the target's turn: `ended`, or `failed` with the error shown to the person. Not
2062
+ * model-visible; external conversations have no runs, no DriftReason.
2063
+ */
2064
+ ev("external_turn", z.object({ state: z.enum(["ended", "failed"]), error: externalText.optional() })),
1993
2065
  ]);
1994
2066
  /**
1995
2067
  * Whether `e` is absorbed like an interjection (spec 2026-11-05-background-bash-design §2.4): the
@@ -0,0 +1,75 @@
1
+ import type { KernelSchemaDb } from "../../db/kernel-schema.js";
2
+ import type { ExtensionPointDefaults } from "../../extensions/point-defaults.js";
3
+ import type { OutboxJob } from "../../infra/outbox/outbox.service.js";
4
+ /**
5
+ * The calls the kernel owes a conversation target (local agents spec Part 2): their queue, job
6
+ * names, data and deterministic ids, and the lookup of an external conversation for its owner.
7
+ * Kept apart from the service so `ConversationsService` (the deletion owes `deleted`) and the
8
+ * service share them without importing each other.
9
+ */
10
+ /** The `conversation-target@1` point as `ExtensionPointDefaults` names it (without the major). */
11
+ export declare const TARGET_POINT = "conversation-target";
12
+ /** The queue of the owed target calls (one consumer, `ExternalCallsProcessor`). */
13
+ export declare const EXTERNAL_CALLS_QUEUE = "cap-external-calls";
14
+ /** The target methods the kernel calls through the outbox. */
15
+ export type ExternalCall = "start" | "send" | "answer" | "stop" | "deleted";
16
+ /** The job name of each call (registered in `infra/outbox/registry.ts`). */
17
+ export declare const EXTERNAL_CALL_JOBS: {
18
+ readonly start: "external-start";
19
+ readonly send: "external-send";
20
+ readonly answer: "external-answer";
21
+ readonly stop: "external-stop";
22
+ readonly deleted: "external-deleted";
23
+ };
24
+ /** The data of an owed call; `orgId` gives the job its org scope (`runJob`). */
25
+ export interface ExternalCallJobData {
26
+ orgId: string;
27
+ conversationId: string;
28
+ call: ExternalCall;
29
+ /**
30
+ * `start` / `send`: the `deliverySeq` of the `external_user_message` it delivers; `stop` /
31
+ * `deleted`: the conversation's last event seq when it was owed (only its job id uses it).
32
+ */
33
+ seq?: number;
34
+ /** `answer`: the request and the chosen option. */
35
+ requestId?: string;
36
+ optionId?: string;
37
+ }
38
+ /**
39
+ * The outbox job of an owed call, under `ext-<call>-<conversationId>-<seq or requestId>`; a
40
+ * message owed again adds a suffix: `next` (chained by the delivery before it), `tail` (after a
41
+ * delivery released the conversation's lock) or `stall<window>` (the stall sweep). See
42
+ * `ExternalConversationsService.deliver`.
43
+ */
44
+ export declare function externalCallJob(d: ExternalCallJobData, suffix?: "next" | "tail" | `stall${number}`): OutboxJob<ExternalCallJobData>;
45
+ /**
46
+ * The dedupe key of the owner's inbox item for a target's request (at most 182 characters: ids
47
+ * are bounded); with an empty `requestId`, the prefix of every request item of the conversation.
48
+ */
49
+ export declare const requestItemKey: (conversationId: string, requestId: string) => string;
50
+ /** An external conversation as its owner reaches it ({@link ownedExternal}). */
51
+ export interface OwnedExternal {
52
+ id: string;
53
+ extension: string;
54
+ targetKey: string;
55
+ deviceId: string | null;
56
+ /** Whether the extension serves `conversation-target@1` in the org now. */
57
+ serves: boolean;
58
+ }
59
+ /**
60
+ * The live external conversation `conversationId` of `accountId` in `orgId`, with whether its
61
+ * extension serves the point there now; null when it is not one (another kind, another person's,
62
+ * deleted, missing): the caller then treats it as any other conversation.
63
+ */
64
+ export declare function ownedExternal(db: KernelSchemaDb, points: Pick<ExtensionPointDefaults, "serves">, orgId: string, conversationId: string, accountId: string): Promise<OwnedExternal | null>;
65
+ /** The `conversationId` of a ctx call's arguments (`invalid_args` when missing). */
66
+ export declare function conversationIdOf(args: {
67
+ conversationId?: unknown;
68
+ } | null): string;
69
+ /** The checks `ctx.conversations.streamExternalText` makes before the call (it returns nothing). */
70
+ export declare function checkExternalText(args: unknown): {
71
+ orgId: string;
72
+ conversationId: string;
73
+ messageId: string;
74
+ text: string;
75
+ };
@@ -0,0 +1,91 @@
1
+ import { createHash } from "node:crypto";
2
+ import { CtxReadError, EXTERNAL_EVENT_LIMITS } from "@capybara-hq/plugin-sdk";
3
+ /**
4
+ * The calls the kernel owes a conversation target (local agents spec Part 2): their queue, job
5
+ * names, data and deterministic ids, and the lookup of an external conversation for its owner.
6
+ * Kept apart from the service so `ConversationsService` (the deletion owes `deleted`) and the
7
+ * service share them without importing each other.
8
+ */
9
+ /** The `conversation-target@1` point as `ExtensionPointDefaults` names it (without the major). */
10
+ export const TARGET_POINT = "conversation-target";
11
+ /** The queue of the owed target calls (one consumer, `ExternalCallsProcessor`). */
12
+ export const EXTERNAL_CALLS_QUEUE = "cap-external-calls";
13
+ /** The job name of each call (registered in `infra/outbox/registry.ts`). */
14
+ export const EXTERNAL_CALL_JOBS = {
15
+ start: "external-start",
16
+ send: "external-send",
17
+ answer: "external-answer",
18
+ stop: "external-stop",
19
+ deleted: "external-deleted",
20
+ };
21
+ /** A part of a job id taken from a target's own id: kept when plain, else a digest (no `:`). */
22
+ const idPart = (s) => /^[A-Za-z0-9_-]{1,80}$/.test(s)
23
+ ? s
24
+ : `h${createHash("sha256").update(s).digest("hex").slice(0, 32)}`;
25
+ /**
26
+ * The outbox job of an owed call, under `ext-<call>-<conversationId>-<seq or requestId>`; a
27
+ * message owed again adds a suffix: `next` (chained by the delivery before it), `tail` (after a
28
+ * delivery released the conversation's lock) or `stall<window>` (the stall sweep). See
29
+ * `ExternalConversationsService.deliver`.
30
+ */
31
+ export function externalCallJob(d, suffix) {
32
+ const key = d.call === "answer" ? idPart(d.requestId ?? "") : String(d.seq ?? 0);
33
+ return {
34
+ queue: EXTERNAL_CALLS_QUEUE,
35
+ name: EXTERNAL_CALL_JOBS[d.call],
36
+ jobId: `ext-${d.call}-${d.conversationId}-${key}${suffix === undefined ? "" : `-${suffix}`}`,
37
+ data: d,
38
+ orgId: d.orgId,
39
+ };
40
+ }
41
+ /**
42
+ * The dedupe key of the owner's inbox item for a target's request (at most 182 characters: ids
43
+ * are bounded); with an empty `requestId`, the prefix of every request item of the conversation.
44
+ */
45
+ export const requestItemKey = (conversationId, requestId) => `external-request-${conversationId}-${requestId}`;
46
+ /**
47
+ * The live external conversation `conversationId` of `accountId` in `orgId`, with whether its
48
+ * extension serves the point there now; null when it is not one (another kind, another person's,
49
+ * deleted, missing): the caller then treats it as any other conversation.
50
+ */
51
+ export async function ownedExternal(db, points, orgId, conversationId, accountId) {
52
+ const row = await db
53
+ .selectFrom("conversations")
54
+ .select(["id", "external", "device_id"])
55
+ .where("id", "=", conversationId)
56
+ .where("org_id", "=", orgId)
57
+ .where("account_id", "=", accountId)
58
+ .where("kind", "=", "external")
59
+ .where("deleted_at", "is", null)
60
+ .executeTakeFirst();
61
+ if (!row || row.external === null)
62
+ return null;
63
+ return {
64
+ id: row.id,
65
+ extension: row.external.extension,
66
+ targetKey: row.external.targetKey,
67
+ deviceId: row.device_id,
68
+ serves: await points.serves(orgId, TARGET_POINT, row.external.extension),
69
+ };
70
+ }
71
+ /** The `conversationId` of a ctx call's arguments (`invalid_args` when missing). */
72
+ export function conversationIdOf(args) {
73
+ const id = args?.conversationId;
74
+ if (typeof id !== "string" || id === "")
75
+ throw new CtxReadError("invalid_args", "conversationId is required");
76
+ return id;
77
+ }
78
+ /** The checks `ctx.conversations.streamExternalText` makes before the call (it returns nothing). */
79
+ export function checkExternalText(args) {
80
+ const a = args;
81
+ if (typeof a !== "object" || a === null || typeof a.orgId !== "string" || a.orgId === "")
82
+ throw new CtxReadError("invalid_args", "orgId is required");
83
+ const conversationId = conversationIdOf(a);
84
+ if (typeof a.messageId !== "string" || a.messageId === "")
85
+ throw new CtxReadError("invalid_args", "messageId is required");
86
+ if (typeof a.text !== "string")
87
+ throw new CtxReadError("invalid_args", "text must be a string");
88
+ if (Buffer.byteLength(a.text, "utf8") > EXTERNAL_EVENT_LIMITS.textBytes)
89
+ throw new CtxReadError("invalid_args", `text is over ${EXTERNAL_EVENT_LIMITS.textBytes} bytes`);
90
+ return { orgId: a.orgId, conversationId, messageId: a.messageId, text: a.text };
91
+ }
@@ -0,0 +1,45 @@
1
+ import { WorkerHost } from "@nestjs/bullmq";
2
+ import type { Job, Worker } from "bullmq";
3
+ import { LockService } from "../../infra/lock/lock.service.js";
4
+ import type { KernelLogger } from "../../log.js";
5
+ import { type ExternalCallJobData } from "./external-calls.js";
6
+ import { ExternalConversationsService } from "./external-conversations.service.js";
7
+ /**
8
+ * The consumer of {@link EXTERNAL_CALLS_QUEUE}: each owed target call
9
+ * ({@link ExternalConversationsService.deliver}), with whether this is its last attempt (then a
10
+ * failing call is dropped with a failed turn instead of failing the job). Worker role only
11
+ * (`ExternalCallWorkersModule`); built with `autorun: false`, started by the worker role after
12
+ * the extensions loaded (the providers are registered at their setup).
13
+ */
14
+ export declare class ExternalCallsProcessor extends WorkerHost<Worker<ExternalCallJobData>> {
15
+ private readonly external;
16
+ private readonly log;
17
+ private readonly stopping;
18
+ constructor(external: Pick<ExternalConversationsService, "deliver">, log: Pick<KernelLogger, "warn" | "error">);
19
+ process(job: Job<ExternalCallJobData>): Promise<void>;
20
+ /** Starts consuming (worker role, after the extensions loaded). */
21
+ start(): void;
22
+ /** Aborts the calls in flight (retried) and closes the worker. */
23
+ close(): Promise<void>;
24
+ failed(job: Job<ExternalCallJobData> | undefined, err: Error): void;
25
+ error(err: Error): void;
26
+ }
27
+ /** The stall sweep's scheduler key and lock (no `:`). */
28
+ export declare const EXTERNAL_CALLS_SWEEP_JOB = "external-calls-sweep";
29
+ /**
30
+ * The external calls' stall sweep, every minute (a `@LockedCron`, once per tick across replicas,
31
+ * under `WorkerModule`): owes again the next delivery of every conversation stalled for longer
32
+ * than `EXTERNAL_STALL_MS` ({@link ExternalConversationsService.resumeStalled}).
33
+ */
34
+ export declare class ExternalCallsSweepJob {
35
+ private readonly external;
36
+ readonly lockService: LockService;
37
+ readonly log: KernelLogger;
38
+ constructor(external: Pick<ExternalConversationsService, "resumeStalled">, lockService: LockService, log: KernelLogger);
39
+ sweep(signal?: AbortSignal): Promise<void>;
40
+ /** One sweep (the test seam): how many stalled conversations were owed again. */
41
+ runOnce(signal?: AbortSignal): Promise<number>;
42
+ }
43
+ /** The external calls' consumer and stall sweep; imported only by the worker role (`WorkerModule`). */
44
+ export declare class ExternalCallWorkersModule {
45
+ }
@@ -0,0 +1,144 @@
1
+ var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
2
+ var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
3
+ if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
4
+ else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
5
+ return c > 3 && r && Object.defineProperty(target, key, r), r;
6
+ };
7
+ var __param = (this && this.__param) || function (paramIndex, decorator) {
8
+ return function (target, key) { decorator(target, key, paramIndex); }
9
+ };
10
+ import { OnWorkerEvent, Processor, WorkerHost } from "@nestjs/bullmq";
11
+ import { Inject, Injectable, Module } from "@nestjs/common";
12
+ import { LockService } from "../../infra/lock/lock.service.js";
13
+ import { runJob } from "../../infra/queue/run-job.js";
14
+ import { LockedCron } from "../../infra/schedule/locked-cron.decorator.js";
15
+ import { KERNEL_LOGGER } from "../../infra/tokens.js";
16
+ import { EXTERNAL_CALLS_QUEUE, } from "./external-calls.js";
17
+ import { ExternalConversationsModule, ExternalConversationsService, } from "./external-conversations.service.js";
18
+ /** Concurrent target calls per worker replica. */
19
+ const CALL_CONCURRENCY = 8;
20
+ /** The call each job name of the queue runs (`EXTERNAL_CALL_JOBS` the other way round). */
21
+ const CALL_OF_JOB = {
22
+ "external-start": "start",
23
+ "external-send": "send",
24
+ "external-answer": "answer",
25
+ "external-stop": "stop",
26
+ "external-deleted": "deleted",
27
+ };
28
+ const errMsg = (e) => (e instanceof Error ? e.message : String(e));
29
+ /**
30
+ * The consumer of {@link EXTERNAL_CALLS_QUEUE}: each owed target call
31
+ * ({@link ExternalConversationsService.deliver}), with whether this is its last attempt (then a
32
+ * failing call is dropped with a failed turn instead of failing the job). Worker role only
33
+ * (`ExternalCallWorkersModule`); built with `autorun: false`, started by the worker role after
34
+ * the extensions loaded (the providers are registered at their setup).
35
+ */
36
+ let ExternalCallsProcessor = class ExternalCallsProcessor extends WorkerHost {
37
+ external;
38
+ log;
39
+ stopping = new AbortController();
40
+ constructor(external, log) {
41
+ super();
42
+ this.external = external;
43
+ this.log = log;
44
+ }
45
+ async process(job) {
46
+ // only the queue's own jobs; anything else (a malformed add) is never run without its org
47
+ const d = job.data;
48
+ if (typeof d?.orgId !== "string" ||
49
+ d.orgId === "" ||
50
+ typeof d.conversationId !== "string" ||
51
+ d.conversationId === "" ||
52
+ CALL_OF_JOB[job.name] === undefined ||
53
+ CALL_OF_JOB[job.name] !== d.call) {
54
+ this.log.error("external call job ignored: not an owed call", {
55
+ jobId: job.id,
56
+ name: job.name,
57
+ });
58
+ return;
59
+ }
60
+ const last = job.attemptsMade + 1 >= (job.opts.attempts ?? 1);
61
+ return runJob(EXTERNAL_CALLS_QUEUE, job, () => this.external.deliver(job.data, last, this.stopping.signal));
62
+ }
63
+ /** Starts consuming (worker role, after the extensions loaded). */
64
+ start() {
65
+ void this.worker.run().catch((err) => this.error(err));
66
+ }
67
+ /** Aborts the calls in flight (retried) and closes the worker. */
68
+ async close() {
69
+ this.stopping.abort(new Error("replica stopping"));
70
+ await this.worker.close();
71
+ }
72
+ failed(job, err) {
73
+ if (!job)
74
+ return;
75
+ this.log.warn("external call failed; retrying", {
76
+ jobId: job.id,
77
+ conversationId: job.data.conversationId,
78
+ call: job.data.call,
79
+ attempt: job.attemptsMade,
80
+ error: errMsg(err),
81
+ });
82
+ }
83
+ error(err) {
84
+ this.log.error("external call worker error", { err });
85
+ }
86
+ };
87
+ __decorate([
88
+ OnWorkerEvent("failed")
89
+ ], ExternalCallsProcessor.prototype, "failed", null);
90
+ __decorate([
91
+ OnWorkerEvent("error")
92
+ ], ExternalCallsProcessor.prototype, "error", null);
93
+ ExternalCallsProcessor = __decorate([
94
+ Injectable(),
95
+ Processor(EXTERNAL_CALLS_QUEUE, { autorun: false, concurrency: CALL_CONCURRENCY }),
96
+ __param(0, Inject(ExternalConversationsService)),
97
+ __param(1, Inject(KERNEL_LOGGER))
98
+ ], ExternalCallsProcessor);
99
+ export { ExternalCallsProcessor };
100
+ /** The stall sweep's scheduler key and lock (no `:`). */
101
+ export const EXTERNAL_CALLS_SWEEP_JOB = "external-calls-sweep";
102
+ /**
103
+ * The external calls' stall sweep, every minute (a `@LockedCron`, once per tick across replicas,
104
+ * under `WorkerModule`): owes again the next delivery of every conversation stalled for longer
105
+ * than `EXTERNAL_STALL_MS` ({@link ExternalConversationsService.resumeStalled}).
106
+ */
107
+ let ExternalCallsSweepJob = class ExternalCallsSweepJob {
108
+ external;
109
+ lockService;
110
+ log;
111
+ constructor(external, lockService, log) {
112
+ this.external = external;
113
+ this.lockService = lockService;
114
+ this.log = log;
115
+ }
116
+ async sweep(signal) {
117
+ await this.runOnce(signal);
118
+ }
119
+ /** One sweep (the test seam): how many stalled conversations were owed again. */
120
+ runOnce(signal) {
121
+ return this.external.resumeStalled(signal);
122
+ }
123
+ };
124
+ __decorate([
125
+ LockedCron("* * * * *", { name: EXTERNAL_CALLS_SWEEP_JOB })
126
+ ], ExternalCallsSweepJob.prototype, "sweep", null);
127
+ ExternalCallsSweepJob = __decorate([
128
+ Injectable(),
129
+ __param(0, Inject(ExternalConversationsService)),
130
+ __param(1, Inject(LockService)),
131
+ __param(2, Inject(KERNEL_LOGGER))
132
+ ], ExternalCallsSweepJob);
133
+ export { ExternalCallsSweepJob };
134
+ /** The external calls' consumer and stall sweep; imported only by the worker role (`WorkerModule`). */
135
+ let ExternalCallWorkersModule = class ExternalCallWorkersModule {
136
+ };
137
+ ExternalCallWorkersModule = __decorate([
138
+ Module({
139
+ imports: [ExternalConversationsModule],
140
+ providers: [ExternalCallsProcessor, ExternalCallsSweepJob],
141
+ exports: [ExternalCallsProcessor],
142
+ })
143
+ ], ExternalCallWorkersModule);
144
+ export { ExternalCallWorkersModule };