@capybara-hq/kernel 0.1.0-rc.107 → 0.1.0-rc.109

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 (100) hide show
  1. package/bootstrap.json +13 -13
  2. package/dist/automations/acceptance.controller.d.ts +29 -0
  3. package/dist/automations/acceptance.controller.js +87 -0
  4. package/dist/automations/automations.module.js +4 -1
  5. package/dist/automations/automations.schemas.d.ts +46 -0
  6. package/dist/automations/automations.schemas.js +31 -0
  7. package/dist/automations/automations.service.js +10 -1
  8. package/dist/automations/errors.d.ts +5 -0
  9. package/dist/automations/errors.js +5 -0
  10. package/dist/automations/events/acceptance.d.ts +205 -0
  11. package/dist/automations/events/acceptance.js +822 -0
  12. package/dist/automations/events/deliver.d.ts +39 -0
  13. package/dist/automations/events/deliver.js +112 -0
  14. package/dist/automations/events/dispatcher.d.ts +26 -10
  15. package/dist/automations/events/dispatcher.js +98 -99
  16. package/dist/automations/events/sweep.job.d.ts +104 -18
  17. package/dist/automations/events/sweep.job.js +311 -45
  18. package/dist/automations/events/trigger-events.service.d.ts +31 -2
  19. package/dist/automations/events/trigger-events.service.js +113 -30
  20. package/dist/automations/store.d.ts +7 -3
  21. package/dist/automations/store.js +6 -0
  22. package/dist/automations/types.d.ts +5 -0
  23. package/dist/catalog/marketplaces.service.d.ts +1 -1
  24. package/dist/config/schema.d.ts +3 -0
  25. package/dist/config/schema.js +14 -0
  26. package/dist/ctx/create-ctx.d.ts +24 -4
  27. package/dist/ctx/create-ctx.js +119 -6
  28. package/dist/db/kernel-schema.d.ts +89 -1
  29. package/dist/errors.d.ts +18 -0
  30. package/dist/errors.js +18 -0
  31. package/dist/extensions/hooks.d.ts +8 -5
  32. package/dist/extensions/hooks.js +2 -1
  33. package/dist/extensions/host.d.ts +12 -2
  34. package/dist/extensions/host.js +21 -1
  35. package/dist/extensions/lifecycle-hooks.d.ts +21 -7
  36. package/dist/extensions/lifecycle-hooks.js +51 -3
  37. package/dist/extensions/permission-set.d.ts +33 -1
  38. package/dist/extensions/permission-set.js +28 -1
  39. package/dist/extensions/permission-view.d.ts +1 -1
  40. package/dist/extensions/permission-view.js +24 -1
  41. package/dist/extensions/run-lifecycle-owe.d.ts +67 -0
  42. package/dist/extensions/run-lifecycle-owe.js +84 -0
  43. package/dist/http/api.module.js +4 -0
  44. package/dist/inbox/inbox-item-actions.d.ts +37 -0
  45. package/dist/inbox/inbox-item-actions.js +69 -0
  46. package/dist/inbox/inbox-items.controller.d.ts +27 -0
  47. package/dist/inbox/inbox-items.controller.js +80 -0
  48. package/dist/inbox/inbox-items.service.d.ts +110 -0
  49. package/dist/inbox/inbox-items.service.js +324 -0
  50. package/dist/inbox/inbox.module.d.ts +2 -1
  51. package/dist/inbox/inbox.module.js +15 -4
  52. package/dist/inbox/inbox.schemas.d.ts +20 -1
  53. package/dist/inbox/inbox.schemas.js +16 -1
  54. package/dist/inbox/inbox.service.d.ts +29 -7
  55. package/dist/inbox/inbox.service.js +29 -8
  56. package/dist/inbox/token.d.ts +5 -0
  57. package/dist/inbox/token.js +5 -0
  58. package/dist/infra/config/kernel-config.service.js +2 -0
  59. package/dist/infra/outbox/registry.d.ts +17 -0
  60. package/dist/infra/outbox/registry.js +15 -0
  61. package/dist/kernel.module.js +6 -0
  62. package/dist/orgs/settings.service.d.ts +20 -0
  63. package/dist/orgs/settings.service.js +4 -0
  64. package/dist/platform/exclusions.js +15 -0
  65. package/dist/platform/operation.d.ts +8 -0
  66. package/dist/platform/ops/automations.ops.d.ts +3 -1
  67. package/dist/platform/ops/automations.ops.js +45 -3
  68. package/dist/platform/ops/inbox.ops.d.ts +3 -1
  69. package/dist/platform/ops/inbox.ops.js +69 -4
  70. package/dist/platform/ops/platform.ops.js +4 -3
  71. package/dist/plugin-reads/plugin-reads.service.d.ts +29 -0
  72. package/dist/plugin-reads/plugin-reads.service.js +210 -0
  73. package/dist/plugin-reads/token.d.ts +5 -0
  74. package/dist/plugin-reads/token.js +5 -0
  75. package/dist/push/jobs.d.ts +5 -0
  76. package/dist/push/jobs.js +2 -0
  77. package/dist/push/preferences.service.d.ts +2 -2
  78. package/dist/push/preferences.service.js +9 -3
  79. package/dist/push/push-owed.d.ts +2 -0
  80. package/dist/push/push-owed.js +10 -1
  81. package/dist/push/push.schemas.d.ts +5 -2
  82. package/dist/push/push.schemas.js +4 -3
  83. package/dist/push/recipients.d.ts +2 -0
  84. package/dist/push/recipients.js +44 -3
  85. package/dist/push/texts.d.ts +14 -5
  86. package/dist/push/texts.js +2 -1
  87. package/dist/push/triggers.d.ts +1 -1
  88. package/dist/runtime/run-finish.js +19 -1
  89. package/dist/runtime/run-jobs.d.ts +12 -2
  90. package/dist/runtime/run-jobs.js +41 -4
  91. package/dist/runtime/run-queue.js +10 -0
  92. package/dist/runtime/waits.js +24 -1
  93. package/dist/tools/builtins/platform.js +2 -0
  94. package/dist/tools/pipeline.d.ts +5 -0
  95. package/dist/tools/pipeline.js +13 -1
  96. package/dist/tools/registry.d.ts +6 -0
  97. package/package.json +3 -3
  98. package/src/migrations/0192_inbox_items.sql +50 -0
  99. package/src/migrations/0193_trigger_cause_handles.sql +49 -0
  100. package/src/migrations/0194_automation_acceptance.sql +83 -0
@@ -1,4 +1,4 @@
1
- import { type TriggerEvent } from "@capybara-hq/plugin-sdk";
1
+ import { type ToolCallContext, type TriggerEvent } from "@capybara-hq/plugin-sdk";
2
2
  import { KernelDb } from "../../infra/database/kernel-db.js";
3
3
  import { TransactionHost } from "../../infra/database/transaction-host.js";
4
4
  import { OutboxService } from "../../infra/outbox/outbox.service.js";
@@ -14,11 +14,16 @@ export declare const TRIGGER_TITLE_MAX_BYTES = 1024;
14
14
  export declare const TRIGGER_URL_MAX_BYTES = 2048;
15
15
  /** Most items of one `string[]` fact. */
16
16
  export declare const TRIGGER_FACT_LIST_MAX_ITEMS = 64;
17
+ /** How long a cause handle (`ctx.triggers.causeOf`) is accepted. */
18
+ export declare const TRIGGER_CAUSE_HANDLE_TTL_MS: number;
17
19
  /**
18
20
  * Stores the events extensions emit (`ctx.triggers.emit`, collaboration spec §4.2) and owes their
19
21
  * dispatch. The emitting extension, the event types it may emit (its approved manifest's
20
22
  * `permissions.triggers.emit`) and the cause's run and depth are the kernel's: an extension cannot
21
23
  * name another plugin, an undeclared type, a run of another org or a chain depth of its choosing.
24
+ * A cause outlives its tool call as a handle (`causeOf`): a `trigger_cause_handles` row the kernel
25
+ * binds to the org, the plugin and the run, so an event emitted later from a queue job keeps the
26
+ * call's depth; the extension holds only the row's id.
22
27
  */
23
28
  export declare class TriggerEventsService {
24
29
  private readonly kdb;
@@ -30,7 +35,9 @@ export declare class TriggerEventsService {
30
35
  * enabled in the event's org and verifies the cause: a tool call context must be one the tool
31
36
  * pipeline made (its run read from the call scope, never from the context's own fields) for a
32
37
  * run of the event's org, and the event's depth is that run's trigger event's depth + 1 (0 when
33
- * the run started from no event); an account must be an active member of the org (depth 0).
38
+ * the run started from no event); a handle ({@link causeOf}) must be an unexpired one this plugin
39
+ * made in the event's org whose run is still the org's, and gives the run, account and depth it
40
+ * recorded when it was made; an account must be an active member of the org (depth 0).
34
41
  * Then inserts the `trigger_events` row and owes its `trigger-dispatch` job in the same
35
42
  * transaction. An event already stored for (org, plugin, dedupe key) is a duplicate: its id comes
36
43
  * back with `duplicate: true` and nothing is owed. The caller runs it in the event's org scope.
@@ -42,6 +49,28 @@ export declare class TriggerEventsService {
42
49
  eventId: string;
43
50
  duplicate: boolean;
44
51
  }>;
52
+ /**
53
+ * A handle for the cause `call` (`ctx.triggers.causeOf`, collaboration spec §4.2) that `plugin`
54
+ * may pass later as `cause: { handle }`: `call` is verified as `emit` verifies `cause.call` (a
55
+ * context the pipeline made, for a run of `orgId`, the call's org as the ctx read it once), then
56
+ * a `trigger_cause_handles` row binds the org, the plugin and the run, with the depth and trigger
57
+ * account the run gives an event now (the retention sweep may delete the run's trigger event
58
+ * before the handle is used), for {@link TRIGGER_CAUSE_HANDLE_TTL_MS}. The caller runs it in
59
+ * `orgId`'s scope. Throws `TriggerError("invalid_event")` for any other context.
60
+ */
61
+ causeOf(plugin: string, orgId: string, call: ToolCallContext): Promise<string>;
62
+ /**
63
+ * The run id of `call` when it is a context the pipeline made (read from the call scope, never
64
+ * from the context's own fields); `invalid_event` otherwise. Its org is checked by
65
+ * {@link causeOfRun}.
66
+ */
67
+ private runIdOfCall;
45
68
  /** The verified cause of `e` (see {@link emit}); no cause is depth 0 with nobody behind it. */
46
69
  private verifyCause;
70
+ /**
71
+ * The cause of an event emitted for run `runId` of `orgId`: the run, its trigger account, and
72
+ * its trigger event's depth + 1 (0 when it started from no event, or from one no longer stored).
73
+ * A run gone from the org (a handle outliving its conversation) is `invalid_event`.
74
+ */
75
+ private causeOfRun;
47
76
  }
@@ -10,6 +10,7 @@ var __param = (this && this.__param) || function (paramIndex, decorator) {
10
10
  import { randomUUID } from "node:crypto";
11
11
  import { TriggerError, validateTriggerEvent, } from "@capybara-hq/plugin-sdk";
12
12
  import { Inject, Injectable } from "@nestjs/common";
13
+ import { sql } from "kysely";
13
14
  import { isExtensionEnabled } from "../../extensions/enabled.js";
14
15
  import { KernelDb } from "../../infra/database/kernel-db.js";
15
16
  import { TransactionHost } from "../../infra/database/transaction-host.js";
@@ -30,6 +31,8 @@ export const TRIGGER_TITLE_MAX_BYTES = 1024;
30
31
  export const TRIGGER_URL_MAX_BYTES = 2048;
31
32
  /** Most items of one `string[]` fact. */
32
33
  export const TRIGGER_FACT_LIST_MAX_ITEMS = 64;
34
+ /** How long a cause handle (`ctx.triggers.causeOf`) is accepted. */
35
+ export const TRIGGER_CAUSE_HANDLE_TTL_MS = 24 * 3_600_000;
33
36
  const bytes = (s) => Buffer.byteLength(s, "utf8");
34
37
  const isPlainObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
35
38
  const nonEmpty = (v) => typeof v === "string" && v !== "";
@@ -42,7 +45,7 @@ const invalid = (message) => new TriggerError("invalid_event", message);
42
45
  * of at most {@link TRIGGER_MAX_FACTS} values, each a string (at most
43
46
  * {@link TRIGGER_FACT_STRING_MAX_BYTES} bytes), a finite number, a boolean or a list of such
44
47
  * strings (at most {@link TRIGGER_FACT_LIST_MAX_ITEMS}); `subject.url` is a string when given;
45
- * `audience` names an account and an agent; `cause` is one of its two shapes.
48
+ * `audience` names an account and an agent; `cause` is one of its three shapes.
46
49
  */
47
50
  /** An absolute `http:` or `https:` URL. */
48
51
  function isWebUrl(url) {
@@ -95,10 +98,11 @@ function checkShape(e) {
95
98
  }
96
99
  if (e.cause !== undefined) {
97
100
  const c = e.cause;
98
- const call = isPlainObject(c) && "call" in c;
99
- const account = isPlainObject(c) && "accountId" in c;
100
- if (call === account)
101
- throw invalid("cause must be { call } (a tool call context) or { accountId }");
101
+ const shapes = isPlainObject(c)
102
+ ? ["call", "handle", "accountId"].filter((k) => Object.hasOwn(c, k)).length
103
+ : 0;
104
+ if (shapes !== 1)
105
+ throw invalid("cause must be { call } (a tool call context), { handle } (from ctx.triggers.causeOf) or { accountId }");
102
106
  }
103
107
  }
104
108
  /**
@@ -106,6 +110,9 @@ function checkShape(e) {
106
110
  * dispatch. The emitting extension, the event types it may emit (its approved manifest's
107
111
  * `permissions.triggers.emit`) and the cause's run and depth are the kernel's: an extension cannot
108
112
  * name another plugin, an undeclared type, a run of another org or a chain depth of its choosing.
113
+ * A cause outlives its tool call as a handle (`causeOf`): a `trigger_cause_handles` row the kernel
114
+ * binds to the org, the plugin and the run, so an event emitted later from a queue job keeps the
115
+ * call's depth; the extension holds only the row's id.
109
116
  */
110
117
  let TriggerEventsService = class TriggerEventsService {
111
118
  kdb;
@@ -121,7 +128,9 @@ let TriggerEventsService = class TriggerEventsService {
121
128
  * enabled in the event's org and verifies the cause: a tool call context must be one the tool
122
129
  * pipeline made (its run read from the call scope, never from the context's own fields) for a
123
130
  * run of the event's org, and the event's depth is that run's trigger event's depth + 1 (0 when
124
- * the run started from no event); an account must be an active member of the org (depth 0).
131
+ * the run started from no event); a handle ({@link causeOf}) must be an unexpired one this plugin
132
+ * made in the event's org whose run is still the org's, and gives the run, account and depth it
133
+ * recorded when it was made; an account must be an active member of the org (depth 0).
125
134
  * Then inserts the `trigger_events` row and owes its `trigger-dispatch` job in the same
126
135
  * transaction. An event already stored for (org, plugin, dedupe key) is a duplicate: its id comes
127
136
  * back with `duplicate: true` and nothing is owed. The caller runs it in the event's org scope.
@@ -141,7 +150,7 @@ let TriggerEventsService = class TriggerEventsService {
141
150
  const db = this.kdb.db;
142
151
  if (!(await isExtensionEnabled(db, e.orgId, plugin)))
143
152
  throw new TriggerError("org_disabled", `${plugin} is not enabled in org ${e.orgId}`);
144
- const cause = await this.verifyCause(e);
153
+ const cause = await this.verifyCause(plugin, e);
145
154
  const subject = {
146
155
  kind: e.subject.kind,
147
156
  id: e.subject.id,
@@ -190,40 +199,80 @@ let TriggerEventsService = class TriggerEventsService {
190
199
  });
191
200
  return { eventId: id, duplicate: false };
192
201
  }
202
+ /**
203
+ * A handle for the cause `call` (`ctx.triggers.causeOf`, collaboration spec §4.2) that `plugin`
204
+ * may pass later as `cause: { handle }`: `call` is verified as `emit` verifies `cause.call` (a
205
+ * context the pipeline made, for a run of `orgId`, the call's org as the ctx read it once), then
206
+ * a `trigger_cause_handles` row binds the org, the plugin and the run, with the depth and trigger
207
+ * account the run gives an event now (the retention sweep may delete the run's trigger event
208
+ * before the handle is used), for {@link TRIGGER_CAUSE_HANDLE_TTL_MS}. The caller runs it in
209
+ * `orgId`'s scope. Throws `TriggerError("invalid_event")` for any other context.
210
+ */
211
+ async causeOf(plugin, orgId, call) {
212
+ if (!nonEmpty(orgId) || !isPlainObject(call))
213
+ throw invalid("causeOf takes the tool call context the kernel passed to the handler");
214
+ // the run must be one of the call's org (as for cause.call)
215
+ const cause = await this.causeOfRun(orgId, this.runIdOfCall(call));
216
+ const id = randomUUID();
217
+ await this.kdb.db
218
+ .insertInto("trigger_cause_handles")
219
+ .values({
220
+ id,
221
+ org_id: orgId,
222
+ plugin,
223
+ run_id: cause.runId,
224
+ depth: cause.depth,
225
+ cause_account_id: cause.accountId,
226
+ expires_at: new Date(Date.now() + TRIGGER_CAUSE_HANDLE_TTL_MS),
227
+ })
228
+ .execute();
229
+ return id;
230
+ }
231
+ /**
232
+ * The run id of `call` when it is a context the pipeline made (read from the call scope, never
233
+ * from the context's own fields); `invalid_event` otherwise. Its org is checked by
234
+ * {@link causeOfRun}.
235
+ */
236
+ runIdOfCall(call) {
237
+ // only the pipeline attaches run facts: a context built by the extension has none
238
+ const facts = isPlainObject(call) ? callScopeOf(call)?.facts : undefined;
239
+ if (facts === undefined)
240
+ throw invalid("cause.call must be the tool call context the kernel passed to the handler");
241
+ return facts.runId;
242
+ }
193
243
  /** The verified cause of `e` (see {@link emit}); no cause is depth 0 with nobody behind it. */
194
- async verifyCause(e) {
244
+ async verifyCause(plugin, e) {
195
245
  const cause = e.cause;
196
246
  if (cause === undefined)
197
247
  return { runId: null, accountId: null, depth: 0 };
198
248
  const db = this.kdb.db;
199
- if ("call" in cause) {
200
- // only the pipeline attaches run facts: a context built by the extension has none
201
- const facts = isPlainObject(cause.call) ? callScopeOf(cause.call)?.facts : undefined;
202
- if (facts === undefined)
203
- throw invalid("cause.call must be the tool call context the kernel passed to the handler");
249
+ if ("call" in cause)
250
+ return this.causeOfRun(e.orgId, this.runIdOfCall(cause.call));
251
+ if ("handle" in cause) {
252
+ // the kernel's row, not the extension's word: this org, this plugin, still valid
253
+ const row = nonEmpty(cause.handle)
254
+ ? await db
255
+ .selectFrom("trigger_cause_handles")
256
+ .select(["run_id", "depth", "cause_account_id"])
257
+ .where("id", "=", cause.handle)
258
+ .where("org_id", "=", e.orgId)
259
+ .where("plugin", "=", plugin)
260
+ .where("expires_at", ">", sql `now()`)
261
+ .executeTakeFirst()
262
+ : undefined;
263
+ if (row === undefined)
264
+ throw invalid("cause.handle is unknown, expired, or of another org or extension");
265
+ // the run must still be one of the event's org; the depth and account are the ones minted
204
266
  const run = await db
205
267
  .selectFrom("runs")
206
268
  .innerJoin("conversations", "conversations.id", "runs.conversation_id")
207
- .select(["runs.id", "runs.trigger_account_id", "runs.trigger_event_id"])
208
- .where("runs.id", "=", facts.runId)
269
+ .select("runs.id")
270
+ .where("runs.id", "=", row.run_id)
209
271
  .where("conversations.org_id", "=", e.orgId)
210
272
  .executeTakeFirst();
211
273
  if (run === undefined)
212
- throw invalid("cause.call is a run of another org");
213
- let depth = 0;
214
- if (run.trigger_event_id !== null) {
215
- const from = await db
216
- .selectFrom("trigger_events")
217
- .select("depth")
218
- .where("id", "=", run.trigger_event_id)
219
- .where("org_id", "=", e.orgId)
220
- .executeTakeFirst();
221
- // the column has no foreign key: an event no longer stored (the trigger event sweep deletes
222
- // settled events after `automations.eventRetentionDays`) cannot extend a chain, which
223
- // restarts at 0
224
- depth = from === undefined ? 0 : from.depth + 1;
225
- }
226
- return { runId: run.id, accountId: run.trigger_account_id, depth };
274
+ throw invalid("the cause's run is not one of the event's org");
275
+ return { runId: run.id, accountId: row.cause_account_id, depth: row.depth };
227
276
  }
228
277
  if (!nonEmpty(cause.accountId))
229
278
  throw invalid("cause.accountId must be an account id");
@@ -241,10 +290,44 @@ let TriggerEventsService = class TriggerEventsService {
241
290
  throw invalid("cause.accountId is not an active member of the event's org");
242
291
  return { runId: null, accountId: cause.accountId, depth: 0 };
243
292
  }
293
+ /**
294
+ * The cause of an event emitted for run `runId` of `orgId`: the run, its trigger account, and
295
+ * its trigger event's depth + 1 (0 when it started from no event, or from one no longer stored).
296
+ * A run gone from the org (a handle outliving its conversation) is `invalid_event`.
297
+ */
298
+ async causeOfRun(orgId, runId) {
299
+ const db = this.kdb.db;
300
+ const run = await db
301
+ .selectFrom("runs")
302
+ .innerJoin("conversations", "conversations.id", "runs.conversation_id")
303
+ .select(["runs.id", "runs.trigger_account_id", "runs.trigger_event_id"])
304
+ .where("runs.id", "=", runId)
305
+ .where("conversations.org_id", "=", orgId)
306
+ .executeTakeFirst();
307
+ if (run === undefined)
308
+ throw invalid("the cause's run is not one of the event's org");
309
+ let depth = 0;
310
+ if (run.trigger_event_id !== null) {
311
+ const from = await db
312
+ .selectFrom("trigger_events")
313
+ .select("depth")
314
+ .where("id", "=", run.trigger_event_id)
315
+ .where("org_id", "=", orgId)
316
+ .executeTakeFirst();
317
+ // the column has no foreign key: an event no longer stored (the trigger event sweep deletes
318
+ // settled events after `automations.eventRetentionDays`) cannot extend a chain, which
319
+ // restarts at 0
320
+ depth = from === undefined ? 0 : from.depth + 1;
321
+ }
322
+ return { runId: run.id, accountId: run.trigger_account_id, depth };
323
+ }
244
324
  };
245
325
  __decorate([
246
326
  Transactional()
247
327
  ], TriggerEventsService.prototype, "emit", null);
328
+ __decorate([
329
+ Transactional()
330
+ ], TriggerEventsService.prototype, "causeOf", null);
248
331
  TriggerEventsService = __decorate([
249
332
  Injectable(),
250
333
  __param(0, Inject(KernelDb)),
@@ -1,11 +1,15 @@
1
1
  import type { KernelSchemaDb } from "../db/kernel-schema.js";
2
- import type { Automation, AutomationGrant, TaskRun, TaskRunStatus, TimedTaskRun } from "./types.js";
2
+ import type { Automation, AutomationGrant, AutomationPrincipal, TaskRun, TaskRunStatus, TimedTaskRun } from "./types.js";
3
3
  /** What a caller supplies to create a task; the counters, pause fields and timestamps default. */
4
- export type AutomationInsert = Omit<Automation, "pauseReason" | "pausedBy" | "consecutiveFailures" | "createdAt" | "updatedAt" | "unattendedAsk"> & {
4
+ export type AutomationInsert = Omit<Automation, "pauseReason" | "pausedBy" | "consecutiveFailures" | "createdAt" | "updatedAt" | "unattendedAsk" | "origin"> & {
5
5
  unattendedAsk?: Automation["unattendedAsk"];
6
+ /** Default `person`. */
7
+ origin?: Automation["origin"];
8
+ /** Whom it acts as; null (the default) = the member `accountId`. */
9
+ principal?: AutomationPrincipal | null;
6
10
  };
7
11
  /** The fields a task update may change (`updated_at` is always refreshed). */
8
- export type AutomationPatch = Partial<Omit<Automation, "id" | "orgId" | "accountId" | "createdAt" | "updatedAt">>;
12
+ export type AutomationPatch = Partial<Omit<Automation, "id" | "orgId" | "accountId" | "origin" | "createdAt" | "updatedAt">>;
9
13
  /** The fields of a task run insert either kind of run has; it starts `pending`. */
10
14
  interface TaskRunInsertBase {
11
15
  id: string;
@@ -30,6 +30,7 @@ const toTask = (r) => ({
30
30
  effort: r.effort,
31
31
  deviceId: r.device_id,
32
32
  unattendedAsk: r.unattended_ask,
33
+ origin: r.origin,
33
34
  status: r.status,
34
35
  pauseReason: r.pause_reason,
35
36
  pausedBy: r.paused_by,
@@ -129,6 +130,8 @@ let AutomationStore = class AutomationStore {
129
130
  effort: task.effort,
130
131
  device_id: task.deviceId,
131
132
  unattended_ask: task.unattendedAsk ?? null,
133
+ origin: task.origin ?? "person",
134
+ principal: task.principal == null ? null : JSON.stringify(task.principal),
132
135
  status: task.status,
133
136
  next_run_at: task.nextRunAt,
134
137
  jitter_seconds: task.jitterSeconds,
@@ -220,6 +223,9 @@ let AutomationStore = class AutomationStore {
220
223
  .select((eb) => eb.fn.countAll().as("n"))
221
224
  .where("org_id", "=", orgId)
222
225
  .where("deleted_at", "is", null)
226
+ // acceptance automations are the kernel's (collaboration spec §4.4): they use up none of the
227
+ // person's or the org's own limits
228
+ .where("origin", "=", "person")
223
229
  .where("status", "in", ["active", "paused"]);
224
230
  if (accountId !== undefined)
225
231
  q = q.where("account_id", "=", accountId);
@@ -87,6 +87,11 @@ export interface Automation {
87
87
  deviceId: string | null;
88
88
  /** What a question in an unattended run does; null = the org's default. */
89
89
  unattendedAsk: AutomationUnattendedAsk | null;
90
+ /**
91
+ * Who made it: its owner, or the kernel from the owner's acceptance rule for the trigger source
92
+ * (an acceptance automation receives that source's directed events for its agent, §4.4).
93
+ */
94
+ origin: AutomationOrigin;
90
95
  status: AutomationStatus;
91
96
  pauseReason: AutomationPauseReason | null;
92
97
  /** The account that paused the task (creator or admin); null when not paused by a person. */
@@ -208,7 +208,7 @@ export declare function headsToResolve(entries: readonly MarketplaceEntry[], imp
208
208
  /** The host versions (an entry's `minKernel` is judged against them). */
209
209
  export declare const HOST_VERSIONS: {
210
210
  readonly kernel: string;
211
- readonly sdk: "0.1.0-rc.86";
211
+ readonly sdk: "0.1.0-rc.87";
212
212
  };
213
213
  /** Whether this deployment satisfies the entry's `minKernel`. */
214
214
  export declare const entryCompatible: (e: Pick<MarketplaceEntry, "minKernel">) => boolean;
@@ -226,6 +226,9 @@ export declare const KernelConfigSchema: z.ZodObject<{
226
226
  titles: "titles";
227
227
  }>>;
228
228
  }, z.core.$strict>>;
229
+ inbox: z.ZodPrefault<z.ZodObject<{
230
+ retentionDays: z.ZodDefault<z.ZodNumber>;
231
+ }, z.core.$strict>>;
229
232
  subagents: z.ZodPrefault<z.ZodObject<{
230
233
  maxDepth: z.ZodDefault<z.ZodNumber>;
231
234
  maxConcurrentPerConversation: z.ZodDefault<z.ZodNumber>;
@@ -1302,6 +1302,20 @@ export const KernelConfigSchema = z.strictObject({
1302
1302
  })),
1303
1303
  })
1304
1304
  .prefault({}),
1305
+ /** People's inbox items (collaboration spec §4.9); platform only. */
1306
+ inbox: z
1307
+ .strictObject({
1308
+ retentionDays: z
1309
+ .number()
1310
+ .int()
1311
+ .positive()
1312
+ .default(30)
1313
+ .meta(meta({
1314
+ hot: true,
1315
+ description: "Days an inbox item is kept once it is closed: an item resolved or closed as expired more than this many days ago, or whose expiry passed more than this many days ago, is deleted by the trigger event sweep (every five minutes)",
1316
+ })),
1317
+ })
1318
+ .prefault({}),
1305
1319
  subagents: z
1306
1320
  .strictObject({
1307
1321
  maxDepth: z
@@ -6,10 +6,12 @@ import type { DeviceAccessService } from "../device-access/device-access.service
6
6
  import type { DialInAccess } from "../dial-in/access.js";
7
7
  import { type RegisteredHook } from "../extensions/hooks.js";
8
8
  import { RegistrationLedger } from "../extensions/ledger.js";
9
+ import type { InboxItemsService } from "../inbox/inbox-items.service.js";
9
10
  import type { LockService } from "../infra/lock/lock.service.js";
10
11
  import type { ModelEmbeddings } from "../models/embeddings.js";
11
12
  import type { ModelImages } from "../models/images.js";
12
13
  import { type OrgRole } from "../orgs/roles.js";
14
+ import type { PluginReadsService } from "../plugin-reads/plugin-reads.service.js";
13
15
  import type { HookRunner } from "../runtime/hook-calls.js";
14
16
  import type { DeviceReports } from "../sandbox/device-reports.js";
15
17
  import type { ShareLiveness } from "../shares/liveness.js";
@@ -83,6 +85,17 @@ export interface KernelDeps {
83
85
  * `ctx.triggers.emit` rejects.
84
86
  */
85
87
  triggers?: () => TriggersBackend | undefined;
88
+ /**
89
+ * What `ctx.inbox` calls through (`InboxItemsService`), found at the time of use like
90
+ * `deviceAccess`. Absent, or resolving to undefined (a ctx built alone in a test, the CLI):
91
+ * `ctx.inbox` calls reject.
92
+ */
93
+ inbox?: () => InboxBackend | undefined;
94
+ /**
95
+ * What `ctx.agents`, `ctx.conversations` and `ctx.people` call through (`PluginReadsService`),
96
+ * found at the time of use like `inbox`. Absent, or resolving to undefined: those calls reject.
97
+ */
98
+ pluginReads?: () => PluginReadsBackend | undefined;
86
99
  runWorkers: boolean;
87
100
  /** 内核 logger(`debug` 可选:插件 Logger 没有它,测试可不给)。 */
88
101
  log: Logger & {
@@ -92,7 +105,11 @@ export interface KernelDeps {
92
105
  /** What `ctx.deviceAccess` calls through (`DeviceAccessService`). */
93
106
  export type DeviceAccessBackend = Pick<DeviceAccessService, "ensureService" | "request" | "reportBlockedHosts" | "streamTicket" | "addNetworkHosts" | "answerHandoff">;
94
107
  /** What `ctx.triggers` calls through (`TriggerEventsService`). */
95
- export type TriggersBackend = Pick<TriggerEventsService, "emit">;
108
+ export type TriggersBackend = Pick<TriggerEventsService, "emit" | "causeOf">;
109
+ /** What `ctx.inbox` calls through (`InboxItemsService`). */
110
+ export type InboxBackend = Pick<InboxItemsService, "post" | "resolveForPlugin">;
111
+ /** What `ctx.agents`, `ctx.conversations` and `ctx.people` call through. */
112
+ export type PluginReadsBackend = Pick<PluginReadsService, "usableBy" | "bySubject" | "peopleGet" | "peopleSearch">;
96
113
  /**
97
114
  * A plain-data copy of an emitted event, taken once at the ctx boundary (check-then-use): every
98
115
  * own enumerable field is read once (a getter cannot change a value after it was validated),
@@ -207,8 +224,9 @@ export type KernelExtensionContext = ExtensionContext & {
207
224
  close(): Promise<void>;
208
225
  };
209
226
  /**
210
- * 插件实例的部署配置(已校验):`ctx.config` 是读它的 getter。hot 字段改动时宿主替换 `value`(C10),
211
- * 插件下次读 `ctx.config` 就是新值;非 hot 改动重新加载实例(新 ctx)。
227
+ * An extension instance's deployment config (validated): `ctx.config` is a getter that reads it.
228
+ * When a hot field changes the host replaces `value` (C10) and the extension's next read of
229
+ * `ctx.config` sees the new value; a change to a non-hot field reloads the instance (a new ctx).
212
230
  */
213
231
  export declare class LiveConfig {
214
232
  value: unknown;
@@ -229,7 +247,9 @@ export declare class LiveConfig {
229
247
  * an extension that provides `device-provider@1`, `reportChanged` only for a live device bound to
230
248
  * this extension (through `deps.devices`; another device throws `ExtensionPermissionError`);
231
249
  * `triggers` only with `permissions.triggers`, each emit only of a declared event type, stored
232
- * in the event's org scope (through `deps.triggers`);
250
+ * in the event's org scope, and `causeOf` handles bound to this extension (through
251
+ * `deps.triggers`); `inbox` only with `permissions.inbox`,
252
+ * posting and resolving only as this extension, in the item's org scope (through `deps.inbox`);
233
253
  * `http.route`
234
254
  * only the method + path declared in `permissions.http` (the record carries the declared access and
235
255
  * its mount, see {@link Route}); `tools.register` only names declared in
@@ -1,4 +1,4 @@
1
- import { DEVICE_PROVIDER_EXTENSION_POINT, DeviceAccessError, EXTENSION_POINTS, ExtensionPermissionError, ExtensionPointUnavailableError, FILE_PREVIEW_EXTENSION_POINT, OBJECT_STORE_EXTENSION_POINT, parseExtensionPoint, resolveUiSlots, SETUP_CHECK_ID_RE, SETUP_GUIDE_PLACES, TriggerError, validateFilePreviewProvider, validateToolSpec, } from "@capybara-hq/plugin-sdk";
1
+ import { CtxReadError, DEVICE_PROVIDER_EXTENSION_POINT, DeviceAccessError, EXTENSION_POINTS, ExtensionPermissionError, ExtensionPointUnavailableError, FILE_PREVIEW_EXTENSION_POINT, InboxError, OBJECT_STORE_EXTENSION_POINT, parseExtensionPoint, resolveUiSlots, SETUP_CHECK_ID_RE, SETUP_GUIDE_PLACES, TriggerError, validateFilePreviewProvider, validateToolSpec, } from "@capybara-hq/plugin-sdk";
2
2
  import { Command, ConnectionBuilder, ControlledTransactionBuilder, Kysely, TransactionBuilder, } from "kysely";
3
3
  import { conversationTopic } from "../conversations/event-log.js";
4
4
  import { kernelDb } from "../db/kernel-schema.js";
@@ -204,8 +204,9 @@ const noProviders = (deps) => ({
204
204
  configOk: async () => true,
205
205
  });
206
206
  /**
207
- * 插件实例的部署配置(已校验):`ctx.config` 是读它的 getter。hot 字段改动时宿主替换 `value`(C10),
208
- * 插件下次读 `ctx.config` 就是新值;非 hot 改动重新加载实例(新 ctx)。
207
+ * An extension instance's deployment config (validated): `ctx.config` is a getter that reads it.
208
+ * When a hot field changes the host replaces `value` (C10) and the extension's next read of
209
+ * `ctx.config` sees the new value; a change to a non-hot field reloads the instance (a new ctx).
209
210
  */
210
211
  export class LiveConfig {
211
212
  value;
@@ -228,7 +229,9 @@ export class LiveConfig {
228
229
  * an extension that provides `device-provider@1`, `reportChanged` only for a live device bound to
229
230
  * this extension (through `deps.devices`; another device throws `ExtensionPermissionError`);
230
231
  * `triggers` only with `permissions.triggers`, each emit only of a declared event type, stored
231
- * in the event's org scope (through `deps.triggers`);
232
+ * in the event's org scope, and `causeOf` handles bound to this extension (through
233
+ * `deps.triggers`); `inbox` only with `permissions.inbox`,
234
+ * posting and resolving only as this extension, in the item's org scope (through `deps.inbox`);
232
235
  * `http.route`
233
236
  * only the method + path declared in `permissions.http` (the record carries the declared access and
234
237
  * its mount, see {@link Route}); `tools.register` only names declared in
@@ -449,9 +452,114 @@ identity = { sha256: null }) {
449
452
  throw new TriggerError("invalid_event", "invalid event: missing_org_id");
450
453
  return withOrgScope(snap.orgId, () => b.emit(name, declared, snap));
451
454
  },
455
+ // a handle bound to this extension and the call's run, in the call's org (the service
456
+ // checks the context is the pipeline's and its run is of that org)
457
+ causeOf: async (call) => {
458
+ const b = deps.triggers?.();
459
+ if (!b)
460
+ throw new Error("Trigger events are not available in this process.");
461
+ const orgId = typeof call === "object" && call !== null ? call.orgId : "";
462
+ if (typeof orgId !== "string" || orgId === "")
463
+ throw new TriggerError("invalid_event", "causeOf takes the tool call context the kernel passed to the handler");
464
+ // read once: the scope and the service get the same org
465
+ return withOrgScope(orgId, () => b.causeOf(name, orgId, call));
466
+ },
452
467
  };
453
468
  })()
454
469
  : undefined;
470
+ // ctx.inbox: only with permissions.inbox; items are posted and resolved as this extension (the
471
+ // kernel checks the link is one of its own pages), in the item's org scope, from a plain-data
472
+ // copy read once (what is checked is what is stored)
473
+ const inboxApi = perms.inbox
474
+ ? {
475
+ post: async (p) => {
476
+ const b = deps.inbox?.();
477
+ if (!b)
478
+ throw new Error("The inbox is not available in this process.");
479
+ let snap;
480
+ try {
481
+ snap = structuredClone(p);
482
+ }
483
+ catch (err) {
484
+ throw new InboxError("invalid_item", "the item must be plain data", { cause: err });
485
+ }
486
+ if (typeof snap !== "object" ||
487
+ snap === null ||
488
+ typeof snap.orgId !== "string" ||
489
+ snap.orgId === "")
490
+ throw new InboxError("invalid_item", "invalid inbox item: missing_org_id");
491
+ const orgId = snap.orgId;
492
+ return withOrgScope(orgId, () => b.post({ kind: "plugin", plugin: name }, snap));
493
+ },
494
+ resolve: async (args) => {
495
+ const b = deps.inbox?.();
496
+ if (!b)
497
+ throw new Error("The inbox is not available in this process.");
498
+ const orgId = args?.orgId;
499
+ const itemId = args?.itemId;
500
+ if (typeof orgId !== "string" || orgId === "" || typeof itemId !== "string")
501
+ throw new InboxError("not_found", "inbox item not found");
502
+ await withOrgScope(orgId, () => b.resolveForPlugin(name, orgId, itemId));
503
+ },
504
+ }
505
+ : undefined;
506
+ // ctx.agents / ctx.conversations / ctx.people: read-only, each only with its permission; every
507
+ // call runs in the named org's scope and the backend checks the extension is enabled there
508
+ const readsBackend = () => {
509
+ const b = deps.pluginReads?.();
510
+ if (!b)
511
+ throw new Error("Agent, conversation and people reads are not available in this process.");
512
+ return b;
513
+ };
514
+ const readArgs = (args) => {
515
+ const a = args;
516
+ if (typeof a !== "object" || a === null || typeof a.orgId !== "string" || a.orgId === "")
517
+ throw new CtxReadError("invalid_args", "orgId is required");
518
+ return a;
519
+ };
520
+ const agentsApi = perms.agents
521
+ ? {
522
+ usableBy: async (args) => {
523
+ const a = readArgs(args);
524
+ if (typeof a.accountId !== "string" || a.accountId === "")
525
+ throw new CtxReadError("invalid_args", "accountId is required");
526
+ const accountId = a.accountId;
527
+ return withOrgScope(a.orgId, () => readsBackend().usableBy(name, a.orgId, accountId));
528
+ },
529
+ }
530
+ : undefined;
531
+ const conversationsApi = perms.conversations
532
+ ? {
533
+ bySubject: async (args) => {
534
+ const a = readArgs(args);
535
+ const s = a.subject;
536
+ if (typeof s !== "object" ||
537
+ s === null ||
538
+ typeof s.kind !== "string" ||
539
+ s.kind === "" ||
540
+ typeof s.id !== "string" ||
541
+ s.id === "")
542
+ throw new CtxReadError("invalid_args", "subject needs a kind and an id");
543
+ const subject = { kind: s.kind, id: s.id };
544
+ return withOrgScope(a.orgId, () => readsBackend().bySubject(name, a.orgId, subject));
545
+ },
546
+ }
547
+ : undefined;
548
+ const peopleApi = perms.people
549
+ ? {
550
+ get: async (args) => {
551
+ const a = readArgs(args);
552
+ const ids = a.accountIds;
553
+ if (!Array.isArray(ids))
554
+ throw new CtxReadError("invalid_args", "accountIds must be a list");
555
+ return withOrgScope(a.orgId, () => readsBackend().peopleGet(name, a.orgId, [...ids]));
556
+ },
557
+ search: async (args) => {
558
+ const a = readArgs(args);
559
+ return withOrgScope(a.orgId, () => readsBackend().peopleSearch(name, a.orgId, a.query, a.limit));
560
+ },
561
+ }
562
+ : undefined;
455
563
  // "METHOD path" -> the access the manifest declares for it (the approved manifest)
456
564
  const declaredRoutes = new Map((perms.http ?? []).map((r) => [`${r.method} ${r.path}`, r.access]));
457
565
  const declaredTools = new Set(perms.tools ?? []);
@@ -925,8 +1033,9 @@ identity = { sha256: null }) {
925
1033
  return closing;
926
1034
  },
927
1035
  };
928
- // secrets / storage / models / dialIn / devices / deviceAccess / triggers: a plain property when declared; otherwise a
929
- // non-enumerable getter that throws, so spreading or printing ctx triggers no denial and no audit
1036
+ // secrets / storage / models / dialIn / devices / deviceAccess / triggers / inbox / agents /
1037
+ // conversations / people: a plain property when declared; otherwise a non-enumerable getter
1038
+ // that throws, so spreading or printing ctx triggers no denial and no audit
930
1039
  const gated = (key, api, item = `permissions.${key}`) => {
931
1040
  if (api) {
932
1041
  Object.assign(ctx, { [key]: api });
@@ -945,6 +1054,10 @@ identity = { sha256: null }) {
945
1054
  gated("devices", devicesApi, `provides ${DEVICE_PROVIDER_EXTENSION_POINT}`);
946
1055
  gated("deviceAccess", deviceAccessApi);
947
1056
  gated("triggers", triggersApi);
1057
+ gated("inbox", inboxApi);
1058
+ gated("agents", agentsApi);
1059
+ gated("conversations", conversationsApi);
1060
+ gated("people", peopleApi);
948
1061
  return ctx;
949
1062
  }
950
1063
  /**