@capybara-hq/kernel 0.1.0-rc.135 → 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 (92) hide show
  1. package/dist/admin/admin.module.js +3 -0
  2. package/dist/admin/health.service.d.ts +2 -2
  3. package/dist/admin/health.service.js +6 -2
  4. package/dist/catalog/marketplaces.service.d.ts +1 -1
  5. package/dist/conversations/access.d.ts +15 -7
  6. package/dist/conversations/access.js +59 -10
  7. package/dist/conversations/conversation-agent.d.ts +18 -0
  8. package/dist/conversations/conversation-agent.js +23 -0
  9. package/dist/conversations/conversation-ref.d.ts +3 -2
  10. package/dist/conversations/conversation-ref.js +6 -1
  11. package/dist/conversations/conversations.controller.d.ts +28 -5
  12. package/dist/conversations/conversations.controller.js +99 -10
  13. package/dist/conversations/conversations.module.js +10 -0
  14. package/dist/conversations/conversations.schemas.d.ts +6 -0
  15. package/dist/conversations/conversations.schemas.js +15 -0
  16. package/dist/conversations/conversations.service.d.ts +125 -21
  17. package/dist/conversations/conversations.service.js +260 -90
  18. package/dist/conversations/event-log.d.ts +9 -1
  19. package/dist/conversations/event-log.js +2 -0
  20. package/dist/conversations/events.d.ts +57 -0
  21. package/dist/conversations/events.js +73 -1
  22. package/dist/conversations/external/external-calls.d.ts +75 -0
  23. package/dist/conversations/external/external-calls.js +91 -0
  24. package/dist/conversations/external/external-calls.processor.d.ts +45 -0
  25. package/dist/conversations/external/external-calls.processor.js +144 -0
  26. package/dist/conversations/external/external-conversations.service.d.ts +266 -0
  27. package/dist/conversations/external/external-conversations.service.js +1138 -0
  28. package/dist/conversations/external/external.schemas.d.ts +63 -0
  29. package/dist/conversations/external/external.schemas.js +52 -0
  30. package/dist/conversations/external/token.d.ts +6 -0
  31. package/dist/conversations/external/token.js +6 -0
  32. package/dist/conversations/permission-profile-store.d.ts +4 -1
  33. package/dist/conversations/permission-profiles.controller.d.ts +33 -9
  34. package/dist/conversations/permission-profiles.controller.js +86 -6
  35. package/dist/conversations/prompt-suggestions.js +2 -1
  36. package/dist/conversations/queue.js +2 -1
  37. package/dist/conversations/titles.js +4 -3
  38. package/dist/ctx/create-ctx.d.ts +7 -0
  39. package/dist/ctx/create-ctx.js +45 -2
  40. package/dist/db/kernel-schema.d.ts +31 -4
  41. package/dist/device-access/host-services.js +3 -2
  42. package/dist/device-access/person-handles.d.ts +16 -7
  43. package/dist/device-access/person-handles.js +14 -9
  44. package/dist/devices/conversation-devices.d.ts +5 -0
  45. package/dist/devices/conversation-devices.js +16 -0
  46. package/dist/erasure/org-catalog.js +2 -2
  47. package/dist/errors.d.ts +34 -0
  48. package/dist/errors.js +34 -0
  49. package/dist/evals/snapshot.js +3 -1
  50. package/dist/evals/trajectory.service.d.ts +2 -2
  51. package/dist/evals/trajectory.service.js +11 -7
  52. package/dist/extensions/extensions.module.js +3 -0
  53. package/dist/extensions/host.d.ts +7 -0
  54. package/dist/extensions/host.js +11 -0
  55. package/dist/extensions/permission-view.d.ts +3 -1
  56. package/dist/extensions/permission-view.js +4 -1
  57. package/dist/extensions/point-defaults.d.ts +13 -21
  58. package/dist/extensions/point-defaults.js +32 -72
  59. package/dist/extensions/point-serving.d.ts +56 -0
  60. package/dist/extensions/point-serving.js +120 -0
  61. package/dist/inbox/inbox-items.service.d.ts +11 -0
  62. package/dist/inbox/inbox-items.service.js +39 -0
  63. package/dist/infra/outbox/registry.d.ts +70 -0
  64. package/dist/infra/outbox/registry.js +44 -0
  65. package/dist/infra/queue/queue-names.d.ts +1 -1
  66. package/dist/infra/queue/queue-names.js +1 -0
  67. package/dist/kernel.module.js +4 -0
  68. package/dist/platform/exclusions.js +10 -0
  69. package/dist/platform/ops/conversations.ops.d.ts +8 -1
  70. package/dist/platform/ops/conversations.ops.js +52 -14
  71. package/dist/plugin-reads/plugin-reads.service.js +4 -1
  72. package/dist/push/recipients.js +5 -2
  73. package/dist/retention/worker.js +2 -1
  74. package/dist/roles/worker-role.d.ts +3 -1
  75. package/dist/roles/worker-role.js +8 -2
  76. package/dist/roles/worker.module.js +3 -0
  77. package/dist/runtime/context/build.js +8 -0
  78. package/dist/runtime/context/compaction.js +7 -0
  79. package/dist/runtime/idle-arm.js +3 -1
  80. package/dist/runtime/idle-compaction.js +2 -1
  81. package/dist/runtime/run-finish.js +2 -1
  82. package/dist/runtime/run-jobs.js +2 -1
  83. package/dist/runtime/run-queue.js +4 -2
  84. package/dist/runtime/run-worker.js +5 -2
  85. package/dist/runtime/stream.js +10 -0
  86. package/dist/runtime/usage-report.js +2 -1
  87. package/dist/runtime/waits.js +2 -1
  88. package/dist/tools/approvals.service.js +6 -2
  89. package/dist/tools/builtins/skill-load.js +3 -2
  90. package/dist/tools/tool-watch.service.js +3 -1
  91. package/package.json +3 -3
  92. package/src/migrations/0227_external_conversations.sql +33 -0
@@ -0,0 +1,1138 @@
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 { randomUUID } from "node:crypto";
11
+ import { CtxReadError, EXTERNAL_EVENT_LIMITS, INBOX_LIMITS, InboxError, parseExternalEvents, } from "@capybara-hq/plugin-sdk";
12
+ import { Inject, Injectable, Module, Optional } from "@nestjs/common";
13
+ import { sql } from "kysely";
14
+ import { issuePersonHandle, revokePersonHandle } from "../../device-access/person-handles.js";
15
+ import { ConversationDevices } from "../../devices/conversation-devices.js";
16
+ import { DeviceProjectsService } from "../../devices/device-projects.service.js";
17
+ import { DevicesModule } from "../../devices/devices.module.js";
18
+ import { ApiError } from "../../errors.js";
19
+ import { ExtensionDisplayNames } from "../../extensions/display-name.js";
20
+ import { ExtensionsModule } from "../../extensions/extensions.module.js";
21
+ import { ExtensionPointDefaults } from "../../extensions/point-defaults.js";
22
+ import { InboxItemsModule, InboxItemsService } from "../../inbox/inbox-items.service.js";
23
+ import { KernelConfigService } from "../../infra/config/kernel-config.service.js";
24
+ import { KernelDb } from "../../infra/database/kernel-db.js";
25
+ import { asPlatform, withOrgScope } from "../../infra/database/org-scope.js";
26
+ import { TransactionHost } from "../../infra/database/transaction-host.js";
27
+ import { Transactional } from "../../infra/database/transactional.decorator.js";
28
+ import { LockService } from "../../infra/lock/lock.service.js";
29
+ import { OutboxService } from "../../infra/outbox/outbox.service.js";
30
+ import { QueueModule } from "../../infra/queue/queue.module.js";
31
+ import { KERNEL_BUS, KERNEL_LOGGER } from "../../infra/tokens.js";
32
+ import { untilAborted } from "../../until-aborted.js";
33
+ import { toView, viewColumns } from "../conversations.service.js";
34
+ import { conversationTopic, EventLog, EventLogModule, } from "../event-log.js";
35
+ import { userMessageIdemKey } from "../idem-keys.js";
36
+ import { ConversationTargetInfoSchema } from "./external.schemas.js";
37
+ import { conversationIdOf, EXTERNAL_CALLS_QUEUE, externalCallJob, ownedExternal, requestItemKey, TARGET_POINT, } from "./external-calls.js";
38
+ import { EXTERNAL_CONVERSATIONS_BACKEND } from "./token.js";
39
+ /** The longest title an external conversation takes from its first prompt (characters). */
40
+ export const EXTERNAL_TITLE_CHARS = 80;
41
+ /** What a failed turn says when a call could not reach the target within its retries. */
42
+ export const TARGET_UNAVAILABLE_TEXT = "The local agent is unavailable";
43
+ /** What the failed turn says when the conversation's `start` was dropped after its retries. */
44
+ export const START_FAILED_TEXT = "The local agent could not start this conversation.";
45
+ /**
46
+ * How old a conversation's next undelivered message may get before the stall sweep owes its
47
+ * delivery again (a lost job, or one whose retries ran out before its cursor moved).
48
+ */
49
+ export const EXTERNAL_STALL_MS = 2 * 60_000;
50
+ /** Stalled conversations owed again per sweep (the next sweep takes the rest). */
51
+ const STALL_BATCH = 1_000;
52
+ /**
53
+ * The delivery cursor of a conversation whose `start` was dropped after its retries. Only the
54
+ * kernel writes the cursor ({@link ExternalConversationsService.dropIn}), so an extension's own
55
+ * `ended` during the start never reads as a dropped start.
56
+ */
57
+ const START_DROPPED_SEQ = -1;
58
+ /**
59
+ * Whether the conversation's `start` was dropped (its cursor is {@link START_DROPPED_SEQ}).
60
+ * Nothing is delivered to it any more but its `deleted`, and the person's sends are refused.
61
+ */
62
+ const startDropped = (c) => Number(c.external_delivered_seq) === START_DROPPED_SEQ;
63
+ /**
64
+ * A message to a target is stored as an `external_user_message`, whose text has the external
65
+ * event limit ({@link EXTERNAL_EVENT_LIMITS}.textBytes, UTF-8): a longer one is refused up front.
66
+ */
67
+ function assertTextFits(text) {
68
+ if (Buffer.byteLength(text, "utf8") > EXTERNAL_EVENT_LIMITS.textBytes)
69
+ throw new ApiError("validation_failed", `A message to a local agent is at most ${EXTERNAL_EVENT_LIMITS.textBytes} bytes (UTF-8); shorten it or send it in parts`, [{ path: ["text"], message: `over ${EXTERNAL_EVENT_LIMITS.textBytes} bytes` }]);
70
+ }
71
+ /**
72
+ * The start options must be ones the target offers on the conversation's device (its
73
+ * `models[].id`, `efforts`, `modes[].id`), else `conversation.target_fields`.
74
+ */
75
+ function assertOptionsFit(target, deviceId, req) {
76
+ const offered = target.devices.find((d) => d.deviceId === deviceId);
77
+ const wrong = [];
78
+ if (req.model !== undefined && !offered?.models.some((m) => m.id === req.model))
79
+ wrong.push({ path: ["model"], message: "not a model the target offers on the device" });
80
+ if (req.effort !== undefined && !offered?.efforts.includes(req.effort))
81
+ wrong.push({ path: ["effort"], message: "not an effort the target offers on the device" });
82
+ if (req.mode !== undefined && !offered?.modes.some((m) => m.id === req.mode))
83
+ wrong.push({ path: ["mode"], message: "not a mode the target offers on the device" });
84
+ if (wrong.length > 0)
85
+ throw new ApiError("conversation.target_fields", `The local agent does not offer ${wrong.map((w) => w.path[0]).join(", ")} on the conversation's device; choose from the options it lists there`, wrong);
86
+ }
87
+ const notFound = () => new ApiError("conversation.not_found", "Conversation not found");
88
+ const targetUnavailable = (why) => new ApiError("conversation.target_unavailable", `The conversation target is unavailable: ${why}`);
89
+ const targetDevice = (why) => new ApiError("conversation.target_device", `No device for the conversation target: ${why}`);
90
+ const externalEnded = () => new ApiError("conversation.external_ended", "The local agent never started this conversation; start a new one");
91
+ const errMsg = (e) => (e instanceof Error ? e.message : String(e));
92
+ /** The fixed title of a request's inbox item (an empty title, or the item's shortest form). */
93
+ const REQUEST_ITEM_TITLE = {
94
+ zh: "本地智能体在等你做决定",
95
+ en: "A local agent is waiting for your decision",
96
+ };
97
+ /**
98
+ * `s` cut to at most `max` UTF-16 code units (what the inbox counts), never splitting a surrogate
99
+ * pair.
100
+ */
101
+ const cutUtf16 = (s, max) => {
102
+ if (s.length <= max)
103
+ return s;
104
+ const out = s.slice(0, max);
105
+ return /[\uD800-\uDBFF]$/.test(out) ? out.slice(0, -1) : out;
106
+ };
107
+ /** The idempotency key of an event a target appends: its own id (an activity's per status). */
108
+ function externalIdemKey(e) {
109
+ switch (e.type) {
110
+ case "external_message":
111
+ return `external-message:${e.payload.messageId}`;
112
+ case "external_activity":
113
+ return `external-activity:${e.payload.activityId}:${e.payload.status}`;
114
+ case "external_request":
115
+ return `external-request:${e.payload.requestId}`;
116
+ case "external_turn":
117
+ return undefined;
118
+ }
119
+ }
120
+ /**
121
+ * The event as stored: rebuilt from its type's known fields only, whatever else the target's
122
+ * object carried (`parseExternalEvents` already drops unknown keys; this is the kernel's own
123
+ * projection, so nothing an extension adds reaches the log).
124
+ */
125
+ function projectExternal(e) {
126
+ switch (e.type) {
127
+ case "external_message": {
128
+ const { messageId, text } = e.payload;
129
+ return { type: e.type, payload: { messageId, role: "assistant", text } };
130
+ }
131
+ case "external_activity": {
132
+ const { activityId, title, detail, status } = e.payload;
133
+ return {
134
+ type: e.type,
135
+ payload: { activityId, title, ...(detail !== undefined && { detail }), status },
136
+ };
137
+ }
138
+ case "external_request": {
139
+ const { requestId, title, detail } = e.payload;
140
+ const options = e.payload.options.map((o) => ({
141
+ id: o.id,
142
+ label: { zh: o.label.zh, en: o.label.en },
143
+ }));
144
+ return {
145
+ type: e.type,
146
+ payload: { requestId, title, ...(detail !== undefined && { detail }), options },
147
+ };
148
+ }
149
+ case "external_turn": {
150
+ const { state, error } = e.payload;
151
+ return { type: e.type, payload: { state, ...(error !== undefined && { error }) } };
152
+ }
153
+ }
154
+ }
155
+ const answerIdemKey = (requestId) => `external-answer:${requestId}`;
156
+ /** The lock the deliveries of one conversation's messages take turns on (no `:`). */
157
+ const deliveryLockKey = (conversationId) => `external-calls-${conversationId}`;
158
+ /** The lifetime of a delivery lock without renewal (renewed while held). */
159
+ const DELIVERY_LOCK_TTL_MS = 30_000;
160
+ /** The first prompt as a title: trimmed, cut to {@link EXTERNAL_TITLE_CHARS} characters. */
161
+ const titleOf = (text) => {
162
+ const t = Array.from(text.trim()).slice(0, EXTERNAL_TITLE_CHARS).join("").trim();
163
+ return t === "" ? null : t;
164
+ };
165
+ /**
166
+ * External conversations (local agents spec Part 2, calls 6, 7, 10a, 11): conversations a person
167
+ * holds with a `conversation-target@1` target (a local agent on their device) instead of an agent.
168
+ * The kernel log mirrors them; the kernel never runs a model on them.
169
+ *
170
+ * - **Targets** ({@link targets}): each serving provider's `targets()` for the person.
171
+ * - **Writes** ({@link createWithMessage}, {@link send}, {@link answer}, {@link stop}): the
172
+ * person's message or answer is written to the log and the target call is owed through the
173
+ * outbox in the same transaction (`cap-external-calls`), at least once.
174
+ * - **Delivery** ({@link deliver}, the worker's `ExternalCallsProcessor`): `start` and `send` go
175
+ * strictly by `deliverySeq` after `external_delivered_seq`; the cursor moves in the transaction
176
+ * that marks a message delivered, which also owes the next one. A call that keeps failing (the
177
+ * target errors or no longer serves the org) is dropped after its retries with an
178
+ * `external_turn` `failed` in the log.
179
+ * - **Mirror** (`ctx.conversations.appendExternal` / `setExternalState` / `streamExternalText`):
180
+ * only the providing extension, on its own conversations, in their org.
181
+ *
182
+ * Every target call carries a person handle the kernel issued for the conversation's owner (bound
183
+ * to the conversation's device), revoked when the call settles.
184
+ */
185
+ let ExternalConversationsService = class ExternalConversationsService {
186
+ db;
187
+ txHost;
188
+ eventLog;
189
+ outbox;
190
+ points;
191
+ displayNames;
192
+ devices;
193
+ projects;
194
+ config;
195
+ locks;
196
+ log;
197
+ inbox;
198
+ bus;
199
+ constructor(db, txHost, eventLog, outbox, points, displayNames, devices, projects, config, locks, log,
200
+ /** The owner's inbox item for each request (spec call 8). */
201
+ inbox,
202
+ // Optional: the Redis-free CLI has no bus; a partial text is a hint whose loss is harmless
203
+ bus) {
204
+ this.db = db;
205
+ this.txHost = txHost;
206
+ this.eventLog = eventLog;
207
+ this.outbox = outbox;
208
+ this.points = points;
209
+ this.displayNames = displayNames;
210
+ this.devices = devices;
211
+ this.projects = projects;
212
+ this.config = config;
213
+ this.locks = locks;
214
+ this.log = log;
215
+ this.inbox = inbox;
216
+ this.bus = bus;
217
+ }
218
+ // ---- targets ----
219
+ /**
220
+ * The targets `accountId` can start an external conversation with: every provider serving the
221
+ * point in the org, asked within `tools.timeoutMs`; a provider that fails, times out or answers
222
+ * nothing usable is left out (logged), a target that does not parse too.
223
+ */
224
+ async targets(orgId, accountId) {
225
+ const { providers } = await this.points.providersFor(orgId, TARGET_POINT);
226
+ const names = await this.displayNames.many(providers.map((p) => p.extension));
227
+ const lists = await Promise.all(providers.map(async (p) => {
228
+ try {
229
+ const raw = await this.call(p, { orgId, accountId }, (a) => p.impl.targets(a));
230
+ return { p, targets: this.validTargets(p.extension, raw) };
231
+ }
232
+ catch (err) {
233
+ this.log.warn("conversation target provider left out of the list", {
234
+ orgId,
235
+ plugin: p.extension,
236
+ err: errMsg(err),
237
+ });
238
+ return null;
239
+ }
240
+ }));
241
+ return lists.flatMap((l) => {
242
+ if (l === null)
243
+ return [];
244
+ const displayName = names.get(l.p.extension) ?? null;
245
+ return l.targets.map((target) => ({
246
+ extension: l.p.extension,
247
+ label: displayName?.en || l.p.extension,
248
+ displayName,
249
+ target,
250
+ }));
251
+ });
252
+ }
253
+ /** The targets of one provider's answer that parse, each key once. */
254
+ validTargets(extension, raw) {
255
+ if (!Array.isArray(raw))
256
+ throw new TypeError("targets() did not return an array");
257
+ const out = [];
258
+ const seen = new Set();
259
+ for (const t of raw) {
260
+ const parsed = ConversationTargetInfoSchema.safeParse(t);
261
+ if (!parsed.success || seen.has(parsed.data.key)) {
262
+ this.log.warn("conversation target left out: not a valid target or a repeated key", {
263
+ plugin: extension,
264
+ ...(parsed.success
265
+ ? { key: parsed.data.key }
266
+ : { problem: parsed.error.issues[0]?.message }),
267
+ });
268
+ continue;
269
+ }
270
+ seen.add(parsed.data.key);
271
+ out.push(parsed.data);
272
+ }
273
+ return out;
274
+ }
275
+ /**
276
+ * One call to a provider within `tools.timeoutMs`, with a person handle for `who` (bound to
277
+ * `who.deviceId` when given; null binds it to no device) that is revoked once the call settles.
278
+ */
279
+ async call(provider, who, fn, outer) {
280
+ const timeout = AbortSignal.timeout(this.config.get().tools.timeoutMs);
281
+ const signal = outer === undefined ? timeout : AbortSignal.any([outer, timeout]);
282
+ const person = issuePersonHandle(who.orgId, who.accountId, who.deviceId);
283
+ try {
284
+ return await untilAborted(Promise.resolve().then(() => fn({
285
+ orgId: who.orgId,
286
+ accountId: who.accountId,
287
+ person,
288
+ config: provider.config,
289
+ signal,
290
+ })), signal);
291
+ }
292
+ finally {
293
+ revokePersonHandle(person);
294
+ }
295
+ }
296
+ // ---- the person's writes ----
297
+ /**
298
+ * Creates an external conversation with its first message: the target must be listed by its
299
+ * provider serving the org now (`conversation.target_unavailable`), and the device is one the
300
+ * target lists ({@link deviceFor}). The project binds as for a chat conversation. Writes the row
301
+ * (`kind = 'external'`, the title from the prompt), the `external_user_message` (deliverySeq 1)
302
+ * and the owed `start` in one transaction; a retry with the same `clientMessageId` answers with
303
+ * the conversation it created (`created: false`).
304
+ */
305
+ async createWithMessage(orgId, accountId, req) {
306
+ if (req.text.trim() === "")
307
+ throw new ApiError("validation_failed", "A local agent's first message needs text");
308
+ assertTextFits(req.text);
309
+ const prior = await this.findCreated(orgId, accountId, req);
310
+ if (prior)
311
+ return prior;
312
+ const provider = await this.points.providerOf(orgId, TARGET_POINT, req.extension);
313
+ if (!provider)
314
+ throw targetUnavailable("its extension does not serve the organization");
315
+ // a chosen device is checked for the person first; without one, the target's list decides
316
+ const chosen = req.deviceId === undefined
317
+ ? undefined
318
+ : await this.devices.forNew(orgId, accountId, { deviceId: req.deviceId });
319
+ let listed;
320
+ try {
321
+ listed = this.validTargets(req.extension,
322
+ // a chosen device bounds the handle; otherwise it is the person's, as on the targets route
323
+ await this.call(provider, { orgId, accountId, ...(chosen !== undefined && { deviceId: chosen }) }, (a) => provider.impl.targets(a)));
324
+ }
325
+ catch (err) {
326
+ this.log.warn("conversation target did not list its targets", {
327
+ orgId,
328
+ plugin: req.extension,
329
+ err: errMsg(err),
330
+ });
331
+ throw targetUnavailable("its extension did not answer");
332
+ }
333
+ const target = listed.find((t) => t.key === req.targetKey);
334
+ if (!target)
335
+ throw targetUnavailable("its extension does not list it");
336
+ const deviceId = await this.deviceFor(orgId, accountId, target, chosen);
337
+ assertOptionsFit(target, deviceId, req);
338
+ const label = target.label[req.locale ?? "en"] || target.label.en || req.targetKey;
339
+ const id = randomUUID();
340
+ let event;
341
+ try {
342
+ event = await this.createIn({ id, orgId, accountId, deviceId, label }, req);
343
+ }
344
+ catch (e) {
345
+ // a concurrent first send with this id created it while this one resolved the binding
346
+ if (!(e instanceof ApiError))
347
+ throw e;
348
+ const raced = await this.findCreated(orgId, accountId, req);
349
+ if (!raced)
350
+ throw e;
351
+ return raced;
352
+ }
353
+ if (!event) {
354
+ const raced = await this.findCreated(orgId, accountId, req);
355
+ if (!raced)
356
+ throw new ApiError("conflict", "The conversation is being created; retry");
357
+ return raced;
358
+ }
359
+ await this.eventLog.notify(id, event.seq);
360
+ return { conversation: await this.view(orgId, id), event, events: [event], created: true };
361
+ }
362
+ /**
363
+ * The device a new external conversation binds to: always one the target lists. A chosen one
364
+ * must be listed; without a choice, the person's existing default device when the target lists
365
+ * it, else the target's first listed device that is not `ready: false` (checked for the person as
366
+ * a choice would be). None → `conversation.target_device`. Never makes a device: a default device
367
+ * is not created as a side effect of choosing a target.
368
+ */
369
+ async deviceFor(orgId, accountId, target, chosen) {
370
+ const listed = (id) => target.devices.some((d) => d.deviceId === id);
371
+ if (chosen !== undefined) {
372
+ if (chosen !== null && listed(chosen))
373
+ return chosen;
374
+ throw targetDevice("the target is not added on that device");
375
+ }
376
+ const fallback = await this.devices.existingDefault(orgId, accountId);
377
+ if (fallback !== null && listed(fallback)) {
378
+ const usable = await this.devices.forNew(orgId, accountId, { deviceId: fallback });
379
+ if (usable !== null)
380
+ return usable;
381
+ }
382
+ const ready = target.devices.find((d) => d.ready !== false);
383
+ if (!ready)
384
+ throw targetDevice("the target is not ready on any of your devices; add it on one first");
385
+ const id = await this.devices.forNew(orgId, accountId, { deviceId: ready.deviceId });
386
+ if (id === null)
387
+ throw targetDevice("the target's device cannot be used");
388
+ return id;
389
+ }
390
+ /** The row, its first message and the owed `start` (undefined: a concurrent retry was first). */
391
+ async createIn(conv, req) {
392
+ const { id, orgId, accountId, deviceId } = conv;
393
+ let project;
394
+ if (req.project !== undefined) {
395
+ project = await this.projects.resolveForBinding(orgId, deviceId, accountId, req.project);
396
+ }
397
+ const title = titleOf(req.text);
398
+ // kept with the target: every delivery of the start (a retry, the stall sweep's) reads them
399
+ const options = {
400
+ ...(req.model !== undefined && { model: req.model }),
401
+ ...(req.effort !== undefined && { effort: req.effort }),
402
+ ...(req.mode !== undefined && { mode: req.mode }),
403
+ };
404
+ const row = await this.db
405
+ .insertInto("conversations")
406
+ .values({
407
+ id,
408
+ org_id: orgId,
409
+ kind: "external",
410
+ agent_id: null,
411
+ account_id: accountId,
412
+ device_id: deviceId,
413
+ project_name: project?.name ?? null,
414
+ project_path: project?.path ?? null,
415
+ title,
416
+ title_source: title === null ? null : "generated",
417
+ create_request_id: req.clientMessageId,
418
+ source: "web",
419
+ external: JSON.stringify({
420
+ extension: req.extension,
421
+ targetKey: req.targetKey,
422
+ label: conv.label,
423
+ options,
424
+ }),
425
+ })
426
+ .onConflict((oc) => oc
427
+ .columns(["org_id", "account_id", "create_request_id"])
428
+ .where("create_request_id", "is not", null)
429
+ .doNothing())
430
+ .returning("id")
431
+ .executeTakeFirst();
432
+ if (!row)
433
+ return undefined;
434
+ const [event] = await this.eventLog.appendIn(id, [
435
+ {
436
+ type: "external_user_message",
437
+ idemKey: userMessageIdemKey(req.clientMessageId),
438
+ payload: { messageId: randomUUID(), text: req.text, interrupt: false, deliverySeq: 1 },
439
+ },
440
+ ]);
441
+ await this.outbox.add(externalCallJob({ orgId, conversationId: id, call: "start", seq: 1 }));
442
+ return event;
443
+ }
444
+ /**
445
+ * What an earlier first message with this `clientMessageId` created; the id used for another
446
+ * conversation (another kind or target) → `conflict`.
447
+ */
448
+ async findCreated(orgId, accountId, req) {
449
+ const row = await this.db
450
+ .selectFrom("conversations")
451
+ .select(viewColumns())
452
+ .where("org_id", "=", orgId)
453
+ .where("account_id", "=", accountId)
454
+ .where("create_request_id", "=", req.clientMessageId)
455
+ .executeTakeFirst();
456
+ if (!row)
457
+ return null;
458
+ if (row.kind !== "external" ||
459
+ row.external?.extension !== req.extension ||
460
+ row.external.targetKey !== req.targetKey)
461
+ throw new ApiError("conflict", "This clientMessageId was already used for another conversation");
462
+ const event = await this.eventLog.findByIdem(row.id, userMessageIdemKey(req.clientMessageId));
463
+ if (!event)
464
+ return null;
465
+ return { conversation: toView(row), event, events: [event], created: false };
466
+ }
467
+ async view(orgId, id) {
468
+ return toView(await this.db
469
+ .selectFrom("conversations")
470
+ .select(viewColumns())
471
+ .where("id", "=", id)
472
+ .where("org_id", "=", orgId)
473
+ .executeTakeFirstOrThrow());
474
+ }
475
+ /**
476
+ * The person's external conversation, if `conversationId` is one (null: another kind, or not
477
+ * theirs: the caller treats it as any conversation).
478
+ */
479
+ find(orgId, conversationId, accountId) {
480
+ return ownedExternal(this.db.db, this.points, orgId, conversationId, accountId);
481
+ }
482
+ /** {@link find} for a write: not an external conversation of theirs → not found; not served → unavailable. */
483
+ async writableExternal(orgId, conversationId, accountId) {
484
+ const ext = await this.find(orgId, conversationId, accountId);
485
+ if (!ext)
486
+ throw notFound();
487
+ if (!ext.serves)
488
+ throw targetUnavailable("its extension does not serve the organization");
489
+ return ext;
490
+ }
491
+ /**
492
+ * A later message (`POST …/messages` on an external conversation): written as an
493
+ * `external_user_message` with the next `deliverySeq`, `send` owed in the same transaction. A
494
+ * retry with the same `clientMessageId` answers with the message it wrote and owes nothing.
495
+ */
496
+ async send(orgId, conversationId, accountId, input) {
497
+ if (input.text.trim() === "")
498
+ throw new ApiError("validation_failed", "A message to a local agent needs text");
499
+ assertTextFits(input.text);
500
+ await this.writableExternal(orgId, conversationId, accountId);
501
+ const { event, fresh } = await this.sendIn(orgId, conversationId, input);
502
+ if (fresh)
503
+ await this.eventLog.notify(conversationId, event.seq);
504
+ return event;
505
+ }
506
+ async sendIn(orgId, conversationId, input) {
507
+ // the row lock orders the delivery seqs (and the delivery's cursor move, which takes it too)
508
+ const live = await this.lockLive(orgId, conversationId);
509
+ // a session that never started takes no messages: none would reach it as a `send`
510
+ if (startDropped(live))
511
+ throw externalEnded();
512
+ const { max } = await this.db
513
+ .selectFrom("conversation_events")
514
+ .select(sql `max((payload->>'deliverySeq')::bigint)`.as("max"))
515
+ .where("conversation_id", "=", conversationId)
516
+ .where("org_id", "=", orgId)
517
+ .where("type", "=", "external_user_message")
518
+ .executeTakeFirstOrThrow();
519
+ const seq = Number(max ?? 0) + 1;
520
+ const r = await this.eventLog.appendInReport(conversationId, [
521
+ {
522
+ type: "external_user_message",
523
+ ...(input.clientMessageId !== undefined && {
524
+ idemKey: userMessageIdemKey(input.clientMessageId),
525
+ }),
526
+ payload: {
527
+ messageId: randomUUID(),
528
+ text: input.text,
529
+ interrupt: input.interrupt,
530
+ deliverySeq: seq,
531
+ },
532
+ },
533
+ ]);
534
+ const event = r.events[0];
535
+ const fresh = r.fresh[0] === true;
536
+ if (fresh)
537
+ await this.outbox.add(externalCallJob({ orgId, conversationId, call: "send", seq }));
538
+ return { event, fresh };
539
+ }
540
+ /**
541
+ * The person's answer to a target's `external_request`: `external_request_answered` written once
542
+ * (a second answer → 409 `conversation.request_answered`), `answer` owed. An unknown request →
543
+ * 404 `conversation.request_not_found`; an option it does not offer → 400.
544
+ */
545
+ async answer(orgId, conversationId, accountId, requestId, optionId) {
546
+ await this.writableExternal(orgId, conversationId, accountId);
547
+ const event = await this.answerIn(orgId, conversationId, accountId, requestId, optionId);
548
+ await this.eventLog.notify(conversationId, event.seq);
549
+ return event;
550
+ }
551
+ async answerIn(orgId, conversationId, accountId, requestId, optionId) {
552
+ await this.lockLive(orgId, conversationId);
553
+ const req = await this.db
554
+ .selectFrom("conversation_events")
555
+ .select("payload")
556
+ .where("conversation_id", "=", conversationId)
557
+ .where("org_id", "=", orgId)
558
+ .where("type", "=", "external_request")
559
+ .where(sql `payload->>'requestId'`, "=", requestId)
560
+ .orderBy("seq", "desc")
561
+ .executeTakeFirst();
562
+ if (!req)
563
+ throw new ApiError("conversation.request_not_found", "The conversation has no such request");
564
+ const options = req.payload.options;
565
+ if (!options.some((o) => o.id === optionId))
566
+ throw new ApiError("validation_failed", "The request does not offer that option", [
567
+ { path: ["optionId"], message: "not one of the request's options" },
568
+ ]);
569
+ const r = await this.eventLog.appendInReport(conversationId, [
570
+ {
571
+ type: "external_request_answered",
572
+ idemKey: answerIdemKey(requestId),
573
+ payload: { requestId, optionId, byAccountId: accountId },
574
+ },
575
+ ]);
576
+ if (r.fresh[0] !== true)
577
+ throw new ApiError("conversation.request_answered", "The request was already answered");
578
+ await this.inbox.resolveKernelItem(orgId, accountId, requestItemKey(conversationId, requestId));
579
+ await this.outbox.add(externalCallJob({ orgId, conversationId, call: "answer", requestId, optionId }));
580
+ return r.events[0];
581
+ }
582
+ /** Stop (`POST …/abort` on an external conversation): `stop` owed. */
583
+ async stop(orgId, conversationId, accountId) {
584
+ await this.writableExternal(orgId, conversationId, accountId);
585
+ await this.stopIn(orgId, conversationId);
586
+ }
587
+ async stopIn(orgId, conversationId) {
588
+ const { lastSeq: seq } = await this.lockLive(orgId, conversationId);
589
+ await this.outbox.add(externalCallJob({ orgId, conversationId, call: "stop", seq }));
590
+ }
591
+ /** Locks the live external conversation's row; returns its last event seq and delivery state. */
592
+ async lockLive(orgId, conversationId) {
593
+ const row = await this.db
594
+ .selectFrom("conversations")
595
+ .select(["last_seq", "external_state", "external_delivered_seq"])
596
+ .where("id", "=", conversationId)
597
+ .where("org_id", "=", orgId)
598
+ .where("kind", "=", "external")
599
+ .where("deleted_at", "is", null)
600
+ .forUpdate()
601
+ .executeTakeFirst();
602
+ if (!row)
603
+ throw notFound();
604
+ return { ...row, lastSeq: Number(row.last_seq) };
605
+ }
606
+ // ---- delivery (the worker's `ExternalCallsProcessor`) ----
607
+ /**
608
+ * One owed call. `start` / `send` go one at a time per conversation (a lock, only tried: a
609
+ * delivery that finds it held ends at once without spending an attempt; the holder looks again
610
+ * after releasing it and owes the next message as a `-tail` job), and only when their
611
+ * `deliverySeq` is the next after the conversation's cursor: an earlier one is a repeat (done),
612
+ * a later one waits (the delivery of the one before owes it again; the stall sweep backs that
613
+ * up). `answer` and `stop` wait for the start. Only `deleted` goes to a deleted conversation or
614
+ * one whose start was dropped. A provider that does not serve the org, or a call that fails,
615
+ * fails the job (retried); on the `last` attempt the call is dropped (logged) and, but for
616
+ * `deleted`, the log gets an `external_turn` `failed` ({@link dropIn}).
617
+ */
618
+ async deliver(d, last, signal) {
619
+ if (d.call !== "start" && d.call !== "send")
620
+ return this.deliverOne(d, last, signal);
621
+ const lock = await this.locks.acquire(deliveryLockKey(d.conversationId), {
622
+ ttlMs: DELIVERY_LOCK_TTL_MS,
623
+ waitMs: 0,
624
+ signal,
625
+ });
626
+ // another delivery of the conversation holds it: that one looks again once it releases it
627
+ if (!lock)
628
+ return;
629
+ try {
630
+ await this.deliverOne(d, last, AbortSignal.any([signal, lock.lost]));
631
+ }
632
+ finally {
633
+ await lock.release();
634
+ }
635
+ await this.oweTailIfDeliverable(d);
636
+ }
637
+ /**
638
+ * After a delivery released the conversation's lock: when the next message after the cursor is
639
+ * written (a delivery of it may have found the lock held and ended), owes it once more as a
640
+ * `-tail` job. Nothing for a deleted conversation or one whose start was dropped.
641
+ */
642
+ async oweTailIfDeliverable(d) {
643
+ const conv = await this.db
644
+ .selectFrom("conversations")
645
+ .select(["external_delivered_seq", "external_state"])
646
+ .where("id", "=", d.conversationId)
647
+ .where("org_id", "=", d.orgId)
648
+ .where("kind", "=", "external")
649
+ .where("deleted_at", "is", null)
650
+ .executeTakeFirst();
651
+ if (!conv || startDropped(conv))
652
+ return;
653
+ const next = Number(conv.external_delivered_seq) + 1;
654
+ if (!(await this.userMessage(d.orgId, d.conversationId, next)))
655
+ return;
656
+ await this.oweMessage(d.orgId, d.conversationId, next, "tail");
657
+ }
658
+ /** Owes the delivery of message `seq` (the start for seq 1) under the given id suffix. */
659
+ async oweMessage(orgId, conversationId, seq, suffix) {
660
+ await this.outbox.add(externalCallJob({ orgId, conversationId, call: seq === 1 ? "start" : "send", seq }, suffix));
661
+ }
662
+ /**
663
+ * The stall sweep (`ExternalCallsSweepJob`): every live external conversation whose next
664
+ * undelivered message is older than {@link EXTERNAL_STALL_MS} (its job lost, or failed for good
665
+ * before the cursor moved) gets that delivery owed again, under one id per stall window. Returns
666
+ * how many were owed.
667
+ */
668
+ async resumeStalled(signal) {
669
+ // org-filter: deployment-wide scan for stalled external deliveries, in every org; each one is
670
+ // owed again in its own org's scope
671
+ const stalled = await asPlatform("find stalled external conversation deliveries", () => sql `
672
+ SELECT c.org_id, c.id, c.external_delivered_seq + 1 AS next
673
+ FROM capybara.conversations c
674
+ WHERE c.kind = 'external' AND c.deleted_at IS NULL
675
+ AND c.external_delivered_seq <> ${START_DROPPED_SEQ}
676
+ AND EXISTS (
677
+ SELECT 1 FROM capybara.conversation_events e
678
+ WHERE e.conversation_id = c.id AND e.org_id = c.org_id
679
+ AND e.type = 'external_user_message'
680
+ AND (e.payload->>'deliverySeq')::bigint = c.external_delivered_seq + 1
681
+ AND e.created_at < now() - make_interval(secs => ${EXTERNAL_STALL_MS / 1000}))
682
+ ORDER BY c.id
683
+ LIMIT ${STALL_BATCH}`.execute(this.db.db));
684
+ const windowId = Math.floor(Date.now() / EXTERNAL_STALL_MS);
685
+ for (const r of stalled.rows) {
686
+ signal?.throwIfAborted();
687
+ await withOrgScope(r.org_id, () => this.oweMessage(r.org_id, r.id, Number(r.next), `stall${windowId}`));
688
+ this.log.warn("external conversation delivery stalled; owed again", {
689
+ orgId: r.org_id,
690
+ conversationId: r.id,
691
+ seq: Number(r.next),
692
+ });
693
+ }
694
+ return stalled.rows.length;
695
+ }
696
+ async deliverOne(d, last, signal) {
697
+ const conv = await this.db
698
+ .selectFrom("conversations")
699
+ .select([
700
+ "account_id",
701
+ "device_id",
702
+ "project_name",
703
+ "project_path",
704
+ "external",
705
+ "external_delivered_seq",
706
+ "external_state",
707
+ "deleted_at",
708
+ ])
709
+ .where("id", "=", d.conversationId)
710
+ .where("org_id", "=", d.orgId)
711
+ .where("kind", "=", "external")
712
+ .executeTakeFirst();
713
+ const fields = { orgId: d.orgId, conversationId: d.conversationId, call: d.call };
714
+ if (!conv || conv.external === null) {
715
+ this.log.warn("external call dropped: the conversation is gone", fields);
716
+ return;
717
+ }
718
+ if (d.call !== "deleted" && conv.deleted_at !== null)
719
+ return;
720
+ if (d.call !== "deleted" && startDropped(conv)) {
721
+ this.log.info("external call dropped: the conversation never started", fields);
722
+ return;
723
+ }
724
+ const cursor = Number(conv.external_delivered_seq);
725
+ const seq = d.seq ?? 0;
726
+ let message;
727
+ if (d.call === "start" || d.call === "send") {
728
+ if (seq <= cursor)
729
+ return;
730
+ if (seq > cursor + 1) {
731
+ this.log.info("external send waits for the one before it", { ...fields, seq, cursor });
732
+ return;
733
+ }
734
+ message = await this.userMessage(d.orgId, d.conversationId, seq);
735
+ if (!message) {
736
+ this.log.error("external call dropped: its message is not in the log", { ...fields, seq });
737
+ return;
738
+ }
739
+ }
740
+ const ext = conv.external;
741
+ try {
742
+ if ((d.call === "answer" || d.call === "stop") && cursor < 1)
743
+ throw new Error("the conversation's start is not delivered yet");
744
+ const provider = await this.points.providerOf(d.orgId, TARGET_POINT, ext.extension);
745
+ if (!provider)
746
+ throw new Error(`${ext.extension} does not serve conversation-target@1 in the org`);
747
+ const who = { orgId: d.orgId, accountId: conv.account_id, deviceId: conv.device_id };
748
+ const at = { conversationId: d.conversationId, deviceId: conv.device_id };
749
+ await this.call(provider, who, (a) => {
750
+ switch (d.call) {
751
+ case "start": {
752
+ const m = message;
753
+ return provider.impl.start({
754
+ ...a,
755
+ ...at,
756
+ targetKey: ext.targetKey,
757
+ project: conv.project_name !== null && conv.project_path !== null
758
+ ? { name: conv.project_name, path: conv.project_path }
759
+ : null,
760
+ ...ext.options,
761
+ text: m.text,
762
+ messageId: m.messageId,
763
+ });
764
+ }
765
+ case "send": {
766
+ const m = message;
767
+ return provider.impl.send({
768
+ ...a,
769
+ ...at,
770
+ text: m.text,
771
+ messageId: m.messageId,
772
+ interrupt: m.interrupt,
773
+ });
774
+ }
775
+ case "answer":
776
+ return provider.impl.answer({
777
+ ...a,
778
+ ...at,
779
+ requestId: d.requestId ?? "",
780
+ optionId: d.optionId ?? "",
781
+ });
782
+ case "stop":
783
+ return provider.impl.stop({ ...a, ...at });
784
+ case "deleted":
785
+ return provider.impl.deleted({ ...a, ...at });
786
+ }
787
+ }, signal);
788
+ }
789
+ catch (err) {
790
+ if (!last)
791
+ throw err;
792
+ this.log.error("external call dropped after its retries", {
793
+ ...fields,
794
+ seq,
795
+ err: errMsg(err),
796
+ });
797
+ if (d.call === "deleted")
798
+ return;
799
+ const toSeq = await this.dropIn(d, seq);
800
+ if (toSeq !== null)
801
+ await this.eventLog.notify(d.conversationId, toSeq);
802
+ await this.eventLog.publishChanged(d.conversationId, "external_state");
803
+ return;
804
+ }
805
+ if (d.call === "start" || d.call === "send")
806
+ await this.markDelivered(d, seq);
807
+ }
808
+ /** The `external_user_message` of `deliverySeq`, as the target receives it. */
809
+ async userMessage(orgId, conversationId, deliverySeq) {
810
+ const row = await this.db
811
+ .selectFrom("conversation_events")
812
+ .select("payload")
813
+ .where("conversation_id", "=", conversationId)
814
+ .where("org_id", "=", orgId)
815
+ .where("type", "=", "external_user_message")
816
+ .where(sql `(payload->>'deliverySeq')::bigint`, "=", deliverySeq)
817
+ .executeTakeFirst();
818
+ return row?.payload;
819
+ }
820
+ /**
821
+ * Marks message `seq` delivered: the cursor moves to it (only from `seq - 1`), then, under the
822
+ * row lock that move took (a send takes it before choosing its seq), the next message, if one is
823
+ * written, is owed again under `-next`: its own job may have run and waited before this commit.
824
+ */
825
+ async markDelivered(d, seq) {
826
+ const moved = await this.db
827
+ .updateTable("conversations")
828
+ .set({ external_delivered_seq: seq })
829
+ .where("id", "=", d.conversationId)
830
+ .where("org_id", "=", d.orgId)
831
+ .where("external_delivered_seq", "=", String(seq - 1))
832
+ .executeTakeFirst();
833
+ if (Number(moved.numUpdatedRows) === 0)
834
+ return false;
835
+ if (await this.userMessage(d.orgId, d.conversationId, seq + 1))
836
+ await this.outbox.add(externalCallJob({ orgId: d.orgId, conversationId: d.conversationId, call: "send", seq: seq + 1 }, "next"));
837
+ return true;
838
+ }
839
+ /**
840
+ * A call dropped after its retries. A dropped `send` still moves the cursor (the next message is
841
+ * not held behind it), the state goes back to `idle`. A dropped `start` moves the cursor from 0
842
+ * to {@link START_DROPPED_SEQ} and ends the conversation (`ended`): no later message is ever
843
+ * delivered as a `send` to a session that never started, and the person's sends are refused
844
+ * (`conversation.external_ended`).
845
+ * The log gets an `external_turn` `failed` saying which. Returns the seq to notify (null:
846
+ * nothing written).
847
+ */
848
+ async dropIn(d, seq) {
849
+ const started = d.call !== "start";
850
+ if (d.call === "send")
851
+ await this.markDelivered(d, seq);
852
+ const row = await this.db
853
+ .selectFrom("conversations")
854
+ .select("id")
855
+ .where("id", "=", d.conversationId)
856
+ .where("org_id", "=", d.orgId)
857
+ .where("deleted_at", "is", null)
858
+ .executeTakeFirst();
859
+ if (!row)
860
+ return null;
861
+ let update = this.db
862
+ .updateTable("conversations")
863
+ .set({ external_state: started ? "idle" : "ended" })
864
+ .where("id", "=", d.conversationId)
865
+ .where("org_id", "=", d.orgId);
866
+ if (!started)
867
+ update = update
868
+ .set({ external_delivered_seq: START_DROPPED_SEQ })
869
+ .where("external_delivered_seq", "=", "0");
870
+ const changed = await update.executeTakeFirst();
871
+ // a start delivered meanwhile (a concurrent delivery moved the cursor) is not dropped
872
+ if (!started && Number(changed.numUpdatedRows) === 0)
873
+ return null;
874
+ const [event] = await this.eventLog.appendIn(d.conversationId, [
875
+ {
876
+ type: "external_turn",
877
+ payload: {
878
+ state: "failed",
879
+ error: started ? TARGET_UNAVAILABLE_TEXT : START_FAILED_TEXT,
880
+ },
881
+ },
882
+ ]);
883
+ return event?.seq ?? null;
884
+ }
885
+ // ---- the mirror (ctx.conversations, for the providing extension) ----
886
+ /**
887
+ * `ctx.conversations.appendExternal` of `extension`: the events are copied, checked
888
+ * (`parseExternalEvents`) and appended in one transaction, each idempotent by its own id (an
889
+ * activity by id and status); refused (`CtxReadError`) unless the conversation is a live
890
+ * external conversation of `extension` in `orgId` and `extension` serves the org.
891
+ */
892
+ async appendExternal(extension, args) {
893
+ const conversationId = conversationIdOf(args);
894
+ let events;
895
+ try {
896
+ events = parseExternalEvents(structuredClone(args.events));
897
+ }
898
+ catch (e) {
899
+ throw new CtxReadError("invalid_args", errMsg(e));
900
+ }
901
+ await this.assertServes(extension, args.orgId);
902
+ if (events.length === 0)
903
+ return;
904
+ const toSeq = await this.appendIn(extension, args.orgId, conversationId, events);
905
+ if (toSeq !== null)
906
+ await this.eventLog.notify(conversationId, toSeq);
907
+ }
908
+ async appendIn(extension, orgId, conversationId, events) {
909
+ const { accountId } = await this.ownRow(extension, orgId, conversationId, true);
910
+ const appends = events.map((e) => {
911
+ const idemKey = externalIdemKey(e);
912
+ return { ...projectExternal(e), ...(idemKey !== undefined && { idemKey }) };
913
+ });
914
+ const r = await this.eventLog.appendInReport(conversationId, appends);
915
+ const written = r.events.filter((_, i) => r.fresh[i] === true);
916
+ // a new request also reaches the owner's inbox (spec call 8), in the same transaction
917
+ for (const e of written)
918
+ if (e.type === "external_request")
919
+ await this.postRequestItem(orgId, accountId, conversationId, e.payload);
920
+ return written.length === 0 ? null : Math.max(...written.map((e) => e.seq));
921
+ }
922
+ /**
923
+ * The owner's personal inbox item for a target's request (local agents spec call 8): a kernel
924
+ * item of kind `external_request` (title = the request's title, body = its detail, each cut to
925
+ * the inbox limits) linking to the conversation, where the request is answered; its push is owed
926
+ * with it. One per request (dedupe key), resolved when the request is answered ({@link answerIn})
927
+ * or the conversation is deleted (`ConversationsService.markDeleted`). An item the inbox refuses is
928
+ * posted again in its shortest form (the fixed title, no body); only an owner who cannot take
929
+ * items at all (no longer an active member) gets none, logged: the card in the conversation stays.
930
+ */
931
+ async postRequestItem(orgId, accountId, conversationId, req) {
932
+ const title = cutUtf16(req.title.trim(), INBOX_LIMITS.titleChars);
933
+ const body = cutUtf16(req.detail ?? "", INBOX_LIMITS.bodyChars);
934
+ const base = {
935
+ orgId,
936
+ accountId,
937
+ kind: "external_request",
938
+ link: `/chat/${conversationId}`,
939
+ dedupeKey: requestItemKey(conversationId, req.requestId),
940
+ };
941
+ try {
942
+ await this.inbox.post({ kind: "kernel" }, {
943
+ ...base,
944
+ title: title === "" ? REQUEST_ITEM_TITLE : title,
945
+ ...(body.trim() !== "" && { body }),
946
+ });
947
+ return;
948
+ }
949
+ catch (err) {
950
+ if (!(err instanceof InboxError))
951
+ throw err;
952
+ this.log.error("external request inbox item refused; posting its shortest form", {
953
+ orgId,
954
+ conversationId,
955
+ requestId: req.requestId,
956
+ err: errMsg(err),
957
+ });
958
+ }
959
+ try {
960
+ await this.inbox.post({ kind: "kernel" }, { ...base, title: REQUEST_ITEM_TITLE });
961
+ }
962
+ catch (err) {
963
+ if (!(err instanceof InboxError))
964
+ throw err;
965
+ this.log.warn("external request inbox item not posted", {
966
+ orgId,
967
+ conversationId,
968
+ requestId: req.requestId,
969
+ err: errMsg(err),
970
+ });
971
+ }
972
+ }
973
+ /** `ctx.conversations.setExternalState` of `extension` (refused as {@link appendExternal}). */
974
+ async setExternalState(extension, args) {
975
+ const conversationId = conversationIdOf(args);
976
+ const state = args.state;
977
+ if (typeof state !== "string" || !EXTERNAL_STATES.includes(state))
978
+ throw new CtxReadError("invalid_args", `state must be one of ${EXTERNAL_STATES.join(", ")}`);
979
+ await this.assertServes(extension, args.orgId);
980
+ const changed = await this.setStateIn(extension, args.orgId, conversationId, state);
981
+ if (changed)
982
+ await this.eventLog.publishChanged(conversationId, "external_state");
983
+ }
984
+ async setStateIn(extension, orgId, conversationId, state) {
985
+ const { state: current } = await this.ownRow(extension, orgId, conversationId, true);
986
+ if (current === state)
987
+ return false;
988
+ // a conversation whose start the kernel dropped stays `ended`
989
+ const r = await this.db
990
+ .updateTable("conversations")
991
+ .set({ external_state: state })
992
+ .where("id", "=", conversationId)
993
+ .where("org_id", "=", orgId)
994
+ .where("external_delivered_seq", "<>", String(START_DROPPED_SEQ))
995
+ .executeTakeFirst();
996
+ return Number(r.numUpdatedRows) > 0;
997
+ }
998
+ /**
999
+ * `ctx.conversations.streamExternalText` of `extension` (the ctx checks the arguments): a bus
1000
+ * hint `external_delta` on the conversation's topic, never stored; dropped (logged) for a
1001
+ * conversation that is not a live one of `extension` in the org.
1002
+ */
1003
+ async streamExternalText(extension, args) {
1004
+ if (!this.bus)
1005
+ return;
1006
+ try {
1007
+ await this.assertServes(extension, args.orgId);
1008
+ await this.ownRow(extension, args.orgId, args.conversationId, false);
1009
+ }
1010
+ catch (err) {
1011
+ this.log.warn("external partial text dropped", {
1012
+ plugin: extension,
1013
+ orgId: args.orgId,
1014
+ conversationId: args.conversationId,
1015
+ err: errMsg(err),
1016
+ });
1017
+ return;
1018
+ }
1019
+ const msg = {
1020
+ kind: "external_delta",
1021
+ messageId: args.messageId,
1022
+ text: args.text,
1023
+ };
1024
+ try {
1025
+ await this.bus.publish(conversationTopic(args.conversationId), msg);
1026
+ }
1027
+ catch (err) {
1028
+ this.log.warn("external partial text publish failed", {
1029
+ conversationId: args.conversationId,
1030
+ err: errMsg(err),
1031
+ });
1032
+ }
1033
+ }
1034
+ /** Refuses an extension that does not serve the point in the org. */
1035
+ async assertServes(extension, orgId) {
1036
+ if (!(await this.points.serves(orgId, TARGET_POINT, extension)))
1037
+ throw new CtxReadError("org_disabled", `${extension} does not serve conversation-target@1 in the organization`);
1038
+ }
1039
+ /**
1040
+ * The live external conversation of `extension` in `orgId` (row-locked when `lock`), its state;
1041
+ * anything else is `invalid_args`, alike for another extension's, another org's or none.
1042
+ */
1043
+ async ownRow(extension, orgId, conversationId, lock) {
1044
+ let q = this.db
1045
+ .selectFrom("conversations")
1046
+ .select(["external_state", "account_id"])
1047
+ .where("id", "=", conversationId)
1048
+ .where("org_id", "=", orgId)
1049
+ .where("kind", "=", "external")
1050
+ .where("deleted_at", "is", null)
1051
+ .where(sql `external->>'extension'`, "=", extension);
1052
+ if (lock)
1053
+ q = q.forUpdate();
1054
+ const row = await q.executeTakeFirst();
1055
+ if (!row)
1056
+ throw new CtxReadError("invalid_args", "conversationId is not a live external conversation of this extension in the organization");
1057
+ return { state: row.external_state, accountId: row.account_id };
1058
+ }
1059
+ };
1060
+ __decorate([
1061
+ Transactional({ propagation: "requires_new" })
1062
+ ], ExternalConversationsService.prototype, "createIn", null);
1063
+ __decorate([
1064
+ Transactional()
1065
+ ], ExternalConversationsService.prototype, "sendIn", null);
1066
+ __decorate([
1067
+ Transactional()
1068
+ ], ExternalConversationsService.prototype, "answerIn", null);
1069
+ __decorate([
1070
+ Transactional()
1071
+ ], ExternalConversationsService.prototype, "stopIn", null);
1072
+ __decorate([
1073
+ Transactional()
1074
+ ], ExternalConversationsService.prototype, "oweMessage", null);
1075
+ __decorate([
1076
+ Transactional()
1077
+ ], ExternalConversationsService.prototype, "markDelivered", null);
1078
+ __decorate([
1079
+ Transactional()
1080
+ ], ExternalConversationsService.prototype, "dropIn", null);
1081
+ __decorate([
1082
+ Transactional()
1083
+ ], ExternalConversationsService.prototype, "appendIn", null);
1084
+ __decorate([
1085
+ Transactional()
1086
+ ], ExternalConversationsService.prototype, "setStateIn", null);
1087
+ ExternalConversationsService = __decorate([
1088
+ Injectable(),
1089
+ __param(0, Inject(KernelDb)),
1090
+ __param(1, Inject(TransactionHost)),
1091
+ __param(2, Inject(EventLog)),
1092
+ __param(3, Inject(OutboxService)),
1093
+ __param(4, Inject(ExtensionPointDefaults)),
1094
+ __param(5, Inject(ExtensionDisplayNames)),
1095
+ __param(6, Inject(ConversationDevices)),
1096
+ __param(7, Inject(DeviceProjectsService)),
1097
+ __param(8, Inject(KernelConfigService)),
1098
+ __param(9, Inject(LockService)),
1099
+ __param(10, Inject(KERNEL_LOGGER)),
1100
+ __param(11, Inject(InboxItemsService)),
1101
+ __param(12, Optional()),
1102
+ __param(12, Inject(KERNEL_BUS))
1103
+ ], ExternalConversationsService);
1104
+ export { ExternalConversationsService };
1105
+ const EXTERNAL_STATES = [
1106
+ "running",
1107
+ "waiting",
1108
+ "idle",
1109
+ "ended",
1110
+ ];
1111
+ const EXTERNAL_CALLS_QUEUE_MODULE = QueueModule.registerQueue(EXTERNAL_CALLS_QUEUE);
1112
+ /**
1113
+ * External conversations on every role: the service (routes, the ctx mirror through
1114
+ * {@link EXTERNAL_CONVERSATIONS_BACKEND}) and the queue the outbox adds their calls to.
1115
+ */
1116
+ let ExternalConversationsModule = class ExternalConversationsModule {
1117
+ };
1118
+ ExternalConversationsModule = __decorate([
1119
+ Module({
1120
+ imports: [
1121
+ ExtensionsModule,
1122
+ EventLogModule,
1123
+ DevicesModule,
1124
+ InboxItemsModule,
1125
+ EXTERNAL_CALLS_QUEUE_MODULE,
1126
+ ],
1127
+ providers: [
1128
+ ExternalConversationsService,
1129
+ { provide: EXTERNAL_CONVERSATIONS_BACKEND, useExisting: ExternalConversationsService },
1130
+ ],
1131
+ exports: [
1132
+ ExternalConversationsService,
1133
+ EXTERNAL_CONVERSATIONS_BACKEND,
1134
+ EXTERNAL_CALLS_QUEUE_MODULE,
1135
+ ],
1136
+ })
1137
+ ], ExternalConversationsModule);
1138
+ export { ExternalConversationsModule };