@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
@@ -0,0 +1,210 @@
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 { CONVERSATIONS_BY_SUBJECT_MAX, CtxReadError, PEOPLE_GET_MAX, PEOPLE_SEARCH_MAX, } from "@capybara-hq/plugin-sdk";
11
+ import { Inject, Injectable, Module } from "@nestjs/common";
12
+ import { sql } from "kysely";
13
+ import { AgentLookup, AgentLookupModule } from "../agents/agent-lookup.js";
14
+ import { isExtensionEnabled } from "../extensions/enabled.js";
15
+ import { avatarColumns, personAvatarUrl } from "../identity/account-avatar.js";
16
+ import { KernelDb } from "../infra/database/kernel-db.js";
17
+ import { PLUGIN_READS_BACKEND } from "./token.js";
18
+ const SEARCH_DEFAULT = 20;
19
+ /** Escapes `%`, `_` and `\` so a name search matches the text literally. */
20
+ const likeLiteral = (s) => s.replace(/[\\%_]/g, (c) => `\\${c}`);
21
+ /**
22
+ * The reads behind `ctx.agents`, `ctx.conversations` and `ctx.people` (collaboration spec; people
23
+ * data: plugin full pages spec §8). Every call runs in the org scope the ctx set, requires the
24
+ * calling extension to be enabled in the org (`org_disabled`), and returns metadata only: no
25
+ * conversation content, no email.
26
+ */
27
+ let PluginReadsService = class PluginReadsService {
28
+ kdb;
29
+ agents;
30
+ constructor(kdb, agents) {
31
+ this.kdb = kdb;
32
+ this.agents = agents;
33
+ }
34
+ async requireEnabled(plugin, orgId) {
35
+ if (!(await isExtensionEnabled(this.kdb.db, orgId, plugin)))
36
+ throw new CtxReadError("org_disabled", `${plugin} is not enabled in org ${orgId}`);
37
+ }
38
+ /** The agents `accountId` may use in the org; `[]` unless it is an active member. */
39
+ async usableBy(plugin, orgId, accountId) {
40
+ await this.requireEnabled(plugin, orgId);
41
+ const member = await this.kdb.db
42
+ .selectFrom("memberships")
43
+ .innerJoin("accounts", "accounts.id", "memberships.account_id")
44
+ .select("accounts.id")
45
+ .where("memberships.org_id", "=", orgId)
46
+ .where("memberships.account_id", "=", accountId)
47
+ .where("accounts.status", "=", "active")
48
+ .executeTakeFirst();
49
+ if (member === undefined)
50
+ return [];
51
+ const views = await this.agents.listVisible(orgId, accountId);
52
+ return views.map((v) => ({
53
+ id: v.id,
54
+ name: v.definition.name,
55
+ avatar: agentAvatar(orgId, v),
56
+ }));
57
+ }
58
+ /** The live conversations of the org whose subject is `plugin`'s `{ kind, id }`. */
59
+ async bySubject(plugin, orgId, subject) {
60
+ await this.requireEnabled(plugin, orgId);
61
+ const db = this.kdb.db;
62
+ const convs = await db
63
+ .selectFrom("conversations")
64
+ .select(["id", "account_id", "agent_id", "updated_at"])
65
+ .where("org_id", "=", orgId)
66
+ .where("deleted_at", "is", null)
67
+ .where(sql `subject->>'source'`, "=", plugin)
68
+ .where(sql `subject->>'kind'`, "=", subject.kind)
69
+ .where(sql `subject->>'id'`, "=", subject.id)
70
+ .orderBy("updated_at", "desc")
71
+ .orderBy("id")
72
+ .limit(CONVERSATIONS_BY_SUBJECT_MAX)
73
+ .execute();
74
+ if (convs.length === 0)
75
+ return [];
76
+ const runs = await db
77
+ .selectFrom("runs")
78
+ .select(["conversation_id", "status", "waiting_since"])
79
+ .distinctOn("conversation_id")
80
+ .where("conversation_id", "in", convs.map((c) => c.id))
81
+ .orderBy("conversation_id")
82
+ .orderBy("created_at", "desc")
83
+ .orderBy("id", "desc")
84
+ .execute();
85
+ const latest = new Map(runs.map((r) => [r.conversation_id, r]));
86
+ return convs.map((c) => {
87
+ const r = latest.get(c.id);
88
+ let state = "idle";
89
+ if (r?.status === "waiting" || (r?.status === "running" && r.waiting_since !== null))
90
+ state = "waiting";
91
+ else if (r?.status === "queued" || r?.status === "running")
92
+ state = "running";
93
+ return {
94
+ id: c.id,
95
+ ownerAccountId: c.account_id,
96
+ agentId: c.agent_id,
97
+ state,
98
+ lastActivityAt: c.updated_at.toISOString(),
99
+ };
100
+ });
101
+ }
102
+ /** The given accounts that are members of the org (others dropped). */
103
+ async peopleGet(plugin, orgId, accountIds) {
104
+ if (!Array.isArray(accountIds) || accountIds.some((i) => typeof i !== "string"))
105
+ throw new CtxReadError("invalid_args", "accountIds must be a list of strings");
106
+ if (accountIds.length > PEOPLE_GET_MAX)
107
+ throw new CtxReadError("invalid_args", `at most ${PEOPLE_GET_MAX} account ids per call`);
108
+ await this.requireEnabled(plugin, orgId);
109
+ const ids = [...new Set(accountIds)];
110
+ if (ids.length === 0)
111
+ return [];
112
+ const rows = await this.kdb.db
113
+ .selectFrom("memberships")
114
+ .innerJoin("accounts", "accounts.id", "memberships.account_id")
115
+ .select((eb) => [
116
+ "accounts.id",
117
+ "accounts.display_name",
118
+ "accounts.status",
119
+ ...avatarColumns(eb, "accounts", "account"),
120
+ ])
121
+ .where("memberships.org_id", "=", orgId)
122
+ .where("memberships.account_id", "in", ids)
123
+ .execute();
124
+ const byId = new Map(rows.map((r) => [r.id, r]));
125
+ return ids.flatMap((id) => {
126
+ const r = byId.get(id);
127
+ if (!r)
128
+ return [];
129
+ return [
130
+ {
131
+ id: r.id,
132
+ name: r.display_name,
133
+ avatar: avatarValue(personAvatarUrl(r, "account", r.id)),
134
+ active: r.status === "active",
135
+ },
136
+ ];
137
+ });
138
+ }
139
+ /** Active members whose display name contains `query`, by name. */
140
+ async peopleSearch(plugin, orgId, query, limit) {
141
+ if (typeof query !== "string")
142
+ throw new CtxReadError("invalid_args", "query must be a string");
143
+ if (limit !== undefined && (typeof limit !== "number" || !Number.isFinite(limit)))
144
+ throw new CtxReadError("invalid_args", "limit must be a number");
145
+ await this.requireEnabled(plugin, orgId);
146
+ const n = Math.min(Math.max(Math.floor(limit ?? SEARCH_DEFAULT), 1), PEOPLE_SEARCH_MAX);
147
+ const q = query.trim();
148
+ let sel = this.kdb.db
149
+ .selectFrom("memberships")
150
+ .innerJoin("accounts", "accounts.id", "memberships.account_id")
151
+ .select((eb) => [
152
+ "accounts.id",
153
+ "accounts.display_name",
154
+ ...avatarColumns(eb, "accounts", "account"),
155
+ ])
156
+ .where("memberships.org_id", "=", orgId)
157
+ .where("accounts.status", "=", "active");
158
+ if (q !== "")
159
+ sel = sel.where(sql `accounts.display_name ilike ${`%${likeLiteral(q)}%`} escape '\\'`);
160
+ const rows = await sel
161
+ .orderBy("accounts.display_name")
162
+ .orderBy("accounts.id")
163
+ .limit(n)
164
+ .execute();
165
+ return rows.map((r) => ({
166
+ id: r.id,
167
+ name: r.display_name,
168
+ avatar: avatarValue(personAvatarUrl(r, "account", r.id)),
169
+ }));
170
+ }
171
+ };
172
+ PluginReadsService = __decorate([
173
+ Injectable(),
174
+ __param(0, Inject(KernelDb)),
175
+ __param(1, Inject(AgentLookup))
176
+ ], PluginReadsService);
177
+ export { PluginReadsService };
178
+ const avatarValue = (src) => src === null ? null : { kind: "image", src };
179
+ /**
180
+ * An agent's avatar for a page, the same mapping as the web's `avatarValue`: a preset stays one, a
181
+ * theme preset is its immutable asset URL, an upload or migrated external image goes through the
182
+ * agent avatar route (`v` busts caches when the profile changes).
183
+ */
184
+ function agentAvatar(orgId, v) {
185
+ const a = v.profile.avatar;
186
+ if (a === null)
187
+ return null;
188
+ if (a.kind === "preset")
189
+ return { kind: "preset", id: a.id };
190
+ if (a.kind === "theme")
191
+ return { kind: "image", src: a.url };
192
+ return {
193
+ kind: "image",
194
+ src: `/api/v1/orgs/${encodeURIComponent(orgId)}/agents/${encodeURIComponent(v.id)}/avatar?v=${encodeURIComponent(v.profile.updatedAt)}`,
195
+ };
196
+ }
197
+ /** `PluginReadsService`, found by the extension host through {@link PLUGIN_READS_BACKEND}. */
198
+ let PluginReadsModule = class PluginReadsModule {
199
+ };
200
+ PluginReadsModule = __decorate([
201
+ Module({
202
+ imports: [AgentLookupModule],
203
+ providers: [
204
+ PluginReadsService,
205
+ { provide: PLUGIN_READS_BACKEND, useExisting: PluginReadsService },
206
+ ],
207
+ exports: [PluginReadsService, PLUGIN_READS_BACKEND],
208
+ })
209
+ ], PluginReadsModule);
210
+ export { PluginReadsModule };
@@ -0,0 +1,5 @@
1
+ /**
2
+ * The token the extension host finds `PluginReadsService` by at the time of use (`ModuleRef`): a
3
+ * symbol in a file of its own, so the host never imports the service's module graph.
4
+ */
5
+ export declare const PLUGIN_READS_BACKEND: unique symbol;
@@ -0,0 +1,5 @@
1
+ /**
2
+ * The token the extension host finds `PluginReadsService` by at the time of use (`ModuleRef`): a
3
+ * symbol in a file of its own, so the host never imports the service's module graph.
4
+ */
5
+ export const PLUGIN_READS_BACKEND = Symbol("PLUGIN_READS_BACKEND");
@@ -14,6 +14,8 @@ export declare const PUSH_DELIVER_JOB = "push-deliver";
14
14
  export declare const conversationEventId: (conversationId: string, seq: number) => string;
15
15
  /** The event id of an automation run's settle (`automation-<taskRunId>`). */
16
16
  export declare const automationRunEventId: (taskRunId: string) => string;
17
+ /** The event id of a personal inbox item's post (`inbox-<itemId>`). */
18
+ export declare const inboxItemEventId: (itemId: string) => string;
17
19
  /** One fanout per event: `push-fanout-<eventId>`. */
18
20
  export declare const pushFanoutJobId: (eventId: string) => string;
19
21
  /** One delivery per event and registration: `push-<eventId>-<registrationId>`. */
@@ -28,6 +30,9 @@ export type PushFanoutData = {
28
30
  } | {
29
31
  kind: "automation";
30
32
  taskRunId: string;
33
+ } | {
34
+ kind: "inbox";
35
+ itemId: string;
31
36
  };
32
37
  };
33
38
  /**
package/dist/push/jobs.js CHANGED
@@ -13,6 +13,8 @@ export const PUSH_DELIVER_JOB = "push-deliver";
13
13
  export const conversationEventId = (conversationId, seq) => `conv-${conversationId}-${seq}`;
14
14
  /** The event id of an automation run's settle (`automation-<taskRunId>`). */
15
15
  export const automationRunEventId = (taskRunId) => `automation-${taskRunId}`;
16
+ /** The event id of a personal inbox item's post (`inbox-<itemId>`). */
17
+ export const inboxItemEventId = (itemId) => `inbox-${itemId}`;
16
18
  /** One fanout per event: `push-fanout-<eventId>`. */
17
19
  export const pushFanoutJobId = (eventId) => `push-fanout-${eventId}`;
18
20
  /** One delivery per event and registration: `push-<eventId>-<registrationId>`. */
@@ -9,9 +9,9 @@ export declare class PushPreferencesService {
9
9
  private readonly db;
10
10
  readonly txHost: TransactionHost;
11
11
  constructor(db: KernelDb, txHost: TransactionHost);
12
- /** The four switches of `accountId`. */
12
+ /** The switches of `accountId`. */
13
13
  get(accountId: string): Promise<PushPreferences>;
14
- /** Sets the switches given (the others keep their value) and answers all four. */
14
+ /** Sets the switches given (the others keep their value) and answers them all. */
15
15
  set(accountId: string, patch: PushPreferencesPatch): Promise<PushPreferences>;
16
16
  /** The accounts among `accountIds` that have `category` on. */
17
17
  enabledFor(accountIds: readonly string[], category: PushCategory): Promise<Set<string>>;
@@ -24,19 +24,25 @@ let PushPreferencesService = class PushPreferencesService {
24
24
  this.db = db;
25
25
  this.txHost = txHost;
26
26
  }
27
- /** The four switches of `accountId`. */
27
+ /** The switches of `accountId`. */
28
28
  async get(accountId) {
29
29
  const rows = await this.db
30
30
  .selectFrom("push_preferences")
31
31
  .select(["category", "enabled"])
32
32
  .where("account_id", "=", accountId)
33
33
  .execute();
34
- const out = { waiting: true, replies: true, tasks: true, automations: true };
34
+ const out = {
35
+ waiting: true,
36
+ replies: true,
37
+ tasks: true,
38
+ automations: true,
39
+ inbox: true,
40
+ };
35
41
  for (const r of rows)
36
42
  out[r.category] = r.enabled;
37
43
  return out;
38
44
  }
39
- /** Sets the switches given (the others keep their value) and answers all four. */
45
+ /** Sets the switches given (the others keep their value) and answers them all. */
40
46
  async set(accountId, patch) {
41
47
  const values = PUSH_CATEGORIES.flatMap((category) => {
42
48
  const enabled = patch[category];
@@ -24,6 +24,8 @@ export declare class PushOwed {
24
24
  * transaction.
25
25
  */
26
26
  oweAutomationRun(taskRunId: string, orgId: string): Promise<void>;
27
+ /** The fanout of a personal inbox item just posted, in the caller's transaction. */
28
+ oweInboxItem(itemId: string, orgId: string): Promise<void>;
27
29
  }
28
30
  /**
29
31
  * {@link PushOwed}: infra and the extension registry only, so the event log and the automation
@@ -11,7 +11,7 @@ import { Inject, Injectable, Module } from "@nestjs/common";
11
11
  import { TransactionHost } from "../infra/database/transaction-host.js";
12
12
  import { Transactional } from "../infra/database/transactional.decorator.js";
13
13
  import { OutboxService } from "../infra/outbox/outbox.service.js";
14
- import { automationRunEventId, conversationEventId, PUSH_FANOUT_JOB, PUSH_QUEUE, pushFanoutJobId, } from "./jobs.js";
14
+ import { automationRunEventId, conversationEventId, inboxItemEventId, PUSH_FANOUT_JOB, PUSH_QUEUE, pushFanoutJobId, } from "./jobs.js";
15
15
  import { PushHostModule, PushProviderHost } from "./provider-host.js";
16
16
  import { pushTriggerOf } from "./triggers.js";
17
17
  /**
@@ -58,6 +58,12 @@ let PushOwed = class PushOwed {
58
58
  return;
59
59
  await this.outbox.add(fanoutJob(automationRunEventId(taskRunId), orgId, { kind: "automation", taskRunId }));
60
60
  }
61
+ /** The fanout of a personal inbox item just posted, in the caller's transaction. */
62
+ async oweInboxItem(itemId, orgId) {
63
+ if (!this.host.any())
64
+ return;
65
+ await this.outbox.add(fanoutJob(inboxItemEventId(itemId), orgId, { kind: "inbox", itemId }));
66
+ }
61
67
  };
62
68
  __decorate([
63
69
  Transactional({ propagation: "mandatory" })
@@ -65,6 +71,9 @@ __decorate([
65
71
  __decorate([
66
72
  Transactional({ propagation: "mandatory" })
67
73
  ], PushOwed.prototype, "oweAutomationRun", null);
74
+ __decorate([
75
+ Transactional({ propagation: "mandatory" })
76
+ ], PushOwed.prototype, "oweInboxItem", null);
68
77
  PushOwed = __decorate([
69
78
  Injectable(),
70
79
  __param(0, Inject(OutboxService)),
@@ -1,7 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import type { RouteSchemas } from "../platform/route-schemas.js";
3
3
  /** The push categories a person switches (mobile app spec §9.4); an absent preference is on. */
4
- export declare const PUSH_CATEGORIES: readonly ["waiting", "replies", "tasks", "automations"];
4
+ export declare const PUSH_CATEGORIES: readonly ["waiting", "replies", "tasks", "automations", "inbox"];
5
5
  export type PushCategory = (typeof PUSH_CATEGORIES)[number];
6
6
  /**
7
7
  * `POST /me/push-registrations`: what the app's shell returns from `push@1.register()`, plus the
@@ -59,12 +59,13 @@ export interface PushRegistrationView {
59
59
  /** Posted by the session making the request. */
60
60
  current: boolean;
61
61
  }
62
- /** The person's four push switches, as `GET` / `PUT /me/push-preferences` answer them. */
62
+ /** The person's five push switches, as `GET` / `PUT /me/push-preferences` answer them. */
63
63
  export declare const PushPreferencesSchema: z.ZodObject<{
64
64
  waiting: z.ZodBoolean;
65
65
  replies: z.ZodBoolean;
66
66
  tasks: z.ZodBoolean;
67
67
  automations: z.ZodBoolean;
68
+ inbox: z.ZodBoolean;
68
69
  }, z.core.$strict>;
69
70
  export type PushPreferences = z.infer<typeof PushPreferencesSchema>;
70
71
  /** `PUT /me/push-preferences`: the switches to change, at least one. */
@@ -73,6 +74,7 @@ export declare const PushPreferencesPatchSchema: z.ZodObject<{
73
74
  replies: z.ZodOptional<z.ZodBoolean>;
74
75
  tasks: z.ZodOptional<z.ZodBoolean>;
75
76
  automations: z.ZodOptional<z.ZodBoolean>;
77
+ inbox: z.ZodOptional<z.ZodBoolean>;
76
78
  }, z.core.$strict>;
77
79
  export type PushPreferencesPatch = z.infer<typeof PushPreferencesPatchSchema>;
78
80
  declare const PushPreferencesPatchDto_base: import("../infra/validation/create-zod-dto.js").ZodDtoClass<z.ZodObject<{
@@ -80,6 +82,7 @@ declare const PushPreferencesPatchDto_base: import("../infra/validation/create-z
80
82
  replies: z.ZodOptional<z.ZodBoolean>;
81
83
  tasks: z.ZodOptional<z.ZodBoolean>;
82
84
  automations: z.ZodOptional<z.ZodBoolean>;
85
+ inbox: z.ZodOptional<z.ZodBoolean>;
83
86
  }, z.core.$strict>>;
84
87
  export declare class PushPreferencesPatchDto extends PushPreferencesPatchDto_base {
85
88
  }
@@ -2,7 +2,7 @@ import { PUSH_LIMITS } from "@capybara-hq/plugin-sdk";
2
2
  import { z } from "zod";
3
3
  import { createZodDto } from "../infra/validation/create-zod-dto.js";
4
4
  /** The push categories a person switches (mobile app spec §9.4); an absent preference is on. */
5
- export const PUSH_CATEGORIES = ["waiting", "replies", "tasks", "automations"];
5
+ export const PUSH_CATEGORIES = ["waiting", "replies", "tasks", "automations", "inbox"];
6
6
  /**
7
7
  * `POST /me/push-registrations`: what the app's shell returns from `push@1.register()`, plus the
8
8
  * person's locale and a device name. The token is sealed at rest and never echoed.
@@ -33,17 +33,18 @@ export class PushRegistrationDto extends createZodDto(PushRegistrationSchema, "P
33
33
  export const PushRegistrationParams = z.object({ id: z.string().min(1).max(100) }).strict();
34
34
  export class PushRegistrationParamsDto extends createZodDto(PushRegistrationParams, "PushRegistrationParams") {
35
35
  }
36
- /** The person's four push switches, as `GET` / `PUT /me/push-preferences` answer them. */
36
+ /** The person's five push switches, as `GET` / `PUT /me/push-preferences` answer them. */
37
37
  export const PushPreferencesSchema = z
38
38
  .object({
39
39
  waiting: z.boolean(),
40
40
  replies: z.boolean(),
41
41
  tasks: z.boolean(),
42
42
  automations: z.boolean(),
43
+ inbox: z.boolean(),
43
44
  })
44
45
  .strict();
45
46
  /** `PUT /me/push-preferences`: the switches to change, at least one. */
46
- export const PushPreferencesPatchSchema = PushPreferencesSchema.partial().refine((p) => Object.values(p).some((v) => v !== undefined), { message: "give at least one of waiting, replies, tasks, automations" });
47
+ export const PushPreferencesPatchSchema = PushPreferencesSchema.partial().refine((p) => Object.values(p).some((v) => v !== undefined), { message: "give at least one of waiting, replies, tasks, automations, inbox" });
47
48
  export class PushPreferencesPatchDto extends createZodDto(PushPreferencesPatchSchema, "PushPreferencesPatch") {
48
49
  }
49
50
  /** The push routes the Platform operations mirror (`check:platform-ops` keys). */
@@ -18,6 +18,8 @@ export type ResolvedRecipients = Omit<ResolvedPush, "eventId">;
18
18
  * automation (that pushes as `automations`);
19
19
  * - `tasks`: the root conversation's owner;
20
20
  * - `automations`: the task's owner, for a task run `completed` or `failed` of a task not deleted;
21
+ * - `inbox`: the item's person, while the item is open and unexpired (a plugin item only while
22
+ * its plugin is enabled in the org);
21
23
  * - eval conversations (a sub-agent under an eval root too) and deleted conversations never push;
22
24
  * - an escalated approval whose run is gone pushes nothing (its initiator is unknown).
23
25
  *
@@ -1,5 +1,7 @@
1
+ import { isExtensionEnabled } from "../extensions/enabled.js";
1
2
  import { ORG_ROLES, roleAtLeast } from "../orgs/roles.js";
2
3
  import { rootConversationOf } from "../runtime/subagents/child.js";
4
+ import { pluginDisplayNames } from "../tools/display-names.js";
3
5
  import { pushTriggerOf } from "./triggers.js";
4
6
  /**
5
7
  * Who an event's push reaches, read when the fanout runs (mobile app spec §9.4, the plan's
@@ -16,6 +18,8 @@ import { pushTriggerOf } from "./triggers.js";
16
18
  * automation (that pushes as `automations`);
17
19
  * - `tasks`: the root conversation's owner;
18
20
  * - `automations`: the task's owner, for a task run `completed` or `failed` of a task not deleted;
21
+ * - `inbox`: the item's person, while the item is open and unexpired (a plugin item only while
22
+ * its plugin is enabled in the org);
19
23
  * - eval conversations (a sub-agent under an eval root too) and deleted conversations never push;
20
24
  * - an escalated approval whose run is gone pushes nothing (its initiator is unknown).
21
25
  *
@@ -25,9 +29,46 @@ import { pushTriggerOf } from "./triggers.js";
25
29
  * (the task's name).
26
30
  */
27
31
  export async function resolveRecipients(db, source) {
28
- return source.kind === "automation"
29
- ? resolveAutomation(db, source.taskRunId)
30
- : resolveConversation(db, source.conversationId, source.seq);
32
+ switch (source.kind) {
33
+ case "automation":
34
+ return resolveAutomation(db, source.taskRunId);
35
+ case "inbox":
36
+ return resolveInboxItem(db, source.itemId);
37
+ default:
38
+ return resolveConversation(db, source.conversationId, source.seq);
39
+ }
40
+ }
41
+ async function resolveInboxItem(db, itemId) {
42
+ // org-filter: itemId comes from the kernel-written push fan-out job; this read learns the item's
43
+ // org, which every later read filters by
44
+ const item = await db
45
+ .selectFrom("inbox_items")
46
+ .select(["org_id", "account_id", "plugin", "title", "state", "expires_at"])
47
+ .where("id", "=", itemId)
48
+ .executeTakeFirst();
49
+ if (!item || item.state !== "open" || item.expires_at.getTime() <= Date.now())
50
+ return null;
51
+ const orgId = item.org_id;
52
+ if (!(await orgLive(db, orgId)))
53
+ return null;
54
+ if (item.plugin !== null && !(await isExtensionEnabled(db, orgId, item.plugin)))
55
+ return null;
56
+ const accountIds = await activeMembers(db, orgId, [item.account_id]);
57
+ if (accountIds.length === 0)
58
+ return null;
59
+ const title = item.plugin === null
60
+ ? "Capybara"
61
+ : ((await pluginDisplayNames(db, [item.plugin])).get(item.plugin) ?? item.plugin);
62
+ return {
63
+ orgId,
64
+ accountIds,
65
+ category: "inbox",
66
+ path: `/inbox?org=${encodeURIComponent(orgId)}#item=${encodeURIComponent(itemId)}`,
67
+ threadId: "inbox",
68
+ title,
69
+ conversationTitle: item.title,
70
+ text: "inboxItem",
71
+ };
31
72
  }
32
73
  async function resolveConversation(db, conversationId, seq) {
33
74
  const event = await db
@@ -6,18 +6,27 @@ export declare const PUSH_TEXT_KEYS: readonly PushTextKey[];
6
6
  export declare function pushText(key: PushTextKey, locale: "zh" | "en"): string;
7
7
  /** An event's push as the fanout resolved it (`recipients.ts`), with the event id. */
8
8
  export interface ResolvedPush {
9
- /** `conv-<conversationId>-<seq>` or `automation-<taskRunId>`: the message's collapse id. */
9
+ /**
10
+ * `conv-<conversationId>-<seq>`, `automation-<taskRunId>` or `inbox-<itemId>`: the message's
11
+ * collapse id.
12
+ */
10
13
  eventId: string;
11
14
  orgId: string;
12
15
  accountIds: string[];
13
16
  category: PushCategory;
14
17
  /** In-app path with `?org=` (plan decision 8). */
15
18
  path: string;
16
- /** The root conversation id, or `automation-<taskId>`. */
19
+ /** The root conversation id, `automation-<taskId>`, or `inbox` for an inbox item. */
17
20
  threadId: string;
18
- /** The agent's display name (the task's name for an automation). */
19
- title: string;
20
- /** Shown only with `push.previews: "titles"`. */
21
+ /**
22
+ * The agent's display name (the task's name for an automation, the plugin's display name or
23
+ * `Capybara` for an inbox item; a localized name is shown in the registration's locale).
24
+ */
25
+ title: string | {
26
+ zh: string;
27
+ en: string;
28
+ };
29
+ /** Shown only with `push.previews: "titles"` (an inbox item's title). */
21
30
  conversationTitle: string | null;
22
31
  text: PushTextKey;
23
32
  }
@@ -10,6 +10,7 @@ const PUSH_TEXTS = {
10
10
  subagentFinished: { en: "a sub-agent finished", zh: "子智能体已完成" },
11
11
  automationRan: { en: "your automation ran", zh: "你的自动化已运行" },
12
12
  automationFailed: { en: "your automation failed", zh: "你的自动化运行失败" },
13
+ inboxItem: { en: "a new item in your inbox", zh: "收件箱有新事项" },
13
14
  };
14
15
  /** Every push text key. */
15
16
  export const PUSH_TEXT_KEYS = Object.keys(PUSH_TEXTS);
@@ -36,7 +37,7 @@ export function renderPushMessage(r, locale, previews, origin) {
36
37
  const lead = previews === "titles" && r.conversationTitle ? r.conversationTitle : null;
37
38
  const body = lead === null ? sentence : `${lead}${locale === "zh" ? ":" : ": "}${sentence}`;
38
39
  return {
39
- title: cut(r.title, PUSH_LIMITS.titleChars),
40
+ title: cut(typeof r.title === "string" ? r.title : r.title[locale], PUSH_LIMITS.titleChars),
40
41
  body: cut(body, PUSH_LIMITS.bodyChars),
41
42
  path: r.path,
42
43
  threadId: r.threadId,
@@ -2,7 +2,7 @@ import type { ConversationEvent } from "../conversations/events.js";
2
2
  import type { PushCategory } from "./push.schemas.js";
3
3
  export type { PushCategory } from "./push.schemas.js";
4
4
  /** The fixed sentences of a push body (`texts.ts` holds the copy). */
5
- export type PushTextKey = "approval" | "question" | "connect" | "runFinished" | "runFailed" | "backgroundFinished" | "subagentFinished" | "automationRan" | "automationFailed";
5
+ export type PushTextKey = "approval" | "question" | "connect" | "runFinished" | "runFailed" | "backgroundFinished" | "subagentFinished" | "automationRan" | "automationFailed" | "inboxItem";
6
6
  /** What one event pushes: its category (the person's switch) and its sentence. */
7
7
  export interface PushTrigger {
8
8
  category: PushCategory;
@@ -12,6 +12,7 @@ import { sql } from "kysely";
12
12
  import { AutomationRunTracker } from "../automations/run-tracker.js";
13
13
  import { EventLog } from "../conversations/event-log.js";
14
14
  import { pauseQueueIn } from "../conversations/queue.js";
15
+ import { oweRunLifecycleFor } from "../extensions/run-lifecycle-owe.js";
15
16
  import { GitRunEnd } from "../git/run-end.js";
16
17
  import { afterCommit } from "../infra/database/after-commit.js";
17
18
  import { KernelDb } from "../infra/database/kernel-db.js";
@@ -94,6 +95,8 @@ let RunFinish = class RunFinish {
94
95
  "kind",
95
96
  "org_id",
96
97
  "deleted_at",
98
+ "agent_id",
99
+ "subject",
97
100
  eb
98
101
  .exists(eb
99
102
  .selectFrom("orgs")
@@ -108,7 +111,7 @@ let RunFinish = class RunFinish {
108
111
  const pending = await lockWaitRowsIn(t, a.runId);
109
112
  const run = await t
110
113
  .selectFrom("runs")
111
- .select("status")
114
+ .select(["status", "agent_version", "trigger_account_id", "compact"])
112
115
  .where("id", "=", a.runId)
113
116
  .forUpdate()
114
117
  .executeTakeFirst();
@@ -142,6 +145,21 @@ let RunFinish = class RunFinish {
142
145
  .where("id", "=", a.runId)
143
146
  .execute();
144
147
  await this.taskRuns.onRunFinished(a.runId, a.status, failureMessage(a.event));
148
+ // the subject's plugin hears of the end in this transaction (observe-only, delivered later);
149
+ // a compact run was never announced, so it has no end to tell
150
+ if (conv?.subject && !run.compact) {
151
+ await oweRunLifecycleFor(t, this.outbox, {
152
+ orgId: conv.org_id,
153
+ conversationId: a.conversationId,
154
+ runId: a.runId,
155
+ agentId: conv.agent_id,
156
+ agentVersion: run.agent_version,
157
+ accountId: run.trigger_account_id,
158
+ subject: conv.subject,
159
+ }, {
160
+ phase: a.status === "completed" ? "finished" : a.status === "aborted" ? "aborted" : "failed",
161
+ });
162
+ }
145
163
  // the terminal status is committed first, then the tickets go (the one place runs end)
146
164
  afterCommit(() => this.gitRunEnd.onRunFinished(a.runId));
147
165
  // a failed or stopped run pauses the queued messages until the person resumes (spec §5.7)
@@ -1,5 +1,6 @@
1
1
  import type { Job, Queue } from "bullmq";
2
2
  import type { ConversationKind, KernelSchemaDb } from "../db/kernel-schema.js";
3
+ import { type RunLifecycleFacts } from "../extensions/run-lifecycle-owe.js";
3
4
  import { KernelDb } from "../infra/database/kernel-db.js";
4
5
  import { TransactionHost } from "../infra/database/transaction-host.js";
5
6
  import { OutboxService } from "../infra/outbox/outbox.service.js";
@@ -84,6 +85,11 @@ export declare class RunJobs {
84
85
  * false when the same job id is already owed (nothing written; the caller creates no run).
85
86
  */
86
87
  owe(data: RunJobData, jobId: string, kind: ConversationKind, orgId: string): Promise<boolean>;
88
+ /**
89
+ * Owes the `started` notice of a new run to the plugin of its conversation's subject, in the
90
+ * caller's transaction; nothing when the conversation has none (no query then).
91
+ */
92
+ oweRunStarted(db: KernelSchemaDb, facts: RunLifecycleFacts): Promise<void>;
87
93
  /** {@link oweEnsureRun} in the caller's transaction. */
88
94
  oweEnsureRun(conversationId: string, seq: number | string, orgId: string): Promise<boolean>;
89
95
  /**
@@ -130,10 +136,14 @@ export declare class RunResume {
130
136
  * Locks the run row (`FOR UPDATE`); when it is `waiting` and waits on nothing else (no pending
131
137
  * approval or input request, no active fork sub-agent), sets it `queued` (adding this wait's
132
138
  * time to `waited_ms`, recording the resume job id) and owes the resume job
133
- * {@link resumeJobId}`(conversation, waitId)` on its conversation kind's run queue. A `running`
134
- * run is left alone: its suspend has not set `waiting` yet and re-checks the wait after.
139
+ * {@link resumeJobId}`(conversation, waitId)` on its conversation kind's run queue, and, when
140
+ * the wait was on a person and the conversation has a subject, `run.lifecycle` `resumed` (not
141
+ * for compact runs). A `running` run is left alone: its suspend has not set `waiting` yet and
142
+ * re-checks the wait after.
135
143
  */
136
144
  resumeIn(runId: string, waitId: string): Promise<ResumeOutcome>;
145
+ /** What the cleared wait `waitId` of `runId` was: an approval (a permission one too), else input. */
146
+ private waitKind;
137
147
  }
138
148
  /**
139
149
  * The run queues' producer (the sub-agent dispatch, the run queue and the waits use it), the