@capybara-hq/kernel 0.1.0-rc.60 → 0.1.0-rc.61

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 (98) hide show
  1. package/dist/admin/admin.module.js +3 -0
  2. package/dist/admin/extensions.controller.d.ts +32 -1
  3. package/dist/admin/extensions.controller.js +72 -3
  4. package/dist/admin/health.service.d.ts +2 -2
  5. package/dist/admin/health.service.js +6 -2
  6. package/dist/catalog/marketplaces.service.d.ts +1 -1
  7. package/dist/config/schema.d.ts +6 -0
  8. package/dist/config/schema.js +12 -0
  9. package/dist/conversations/event-log.d.ts +12 -3
  10. package/dist/conversations/event-log.js +17 -5
  11. package/dist/ctx/secrets.d.ts +10 -5
  12. package/dist/ctx/secrets.js +16 -5
  13. package/dist/db/kernel-schema.d.ts +34 -2
  14. package/dist/errors.d.ts +7 -0
  15. package/dist/errors.js +7 -0
  16. package/dist/extensions/config-hash.d.ts +2 -0
  17. package/dist/extensions/config-hash.js +1 -1
  18. package/dist/extensions/guide-places.d.ts +5 -1
  19. package/dist/extensions/guide-places.js +9 -2
  20. package/dist/extensions/permission-view.d.ts +6 -4
  21. package/dist/extensions/permission-view.js +6 -3
  22. package/dist/extensions/plugin-guides.d.ts +20 -0
  23. package/dist/extensions/plugin-guides.js +49 -1
  24. package/dist/extensions/registry.js +1 -0
  25. package/dist/http/api.module.js +7 -0
  26. package/dist/http/meta.controller.d.ts +7 -1
  27. package/dist/http/meta.controller.js +14 -3
  28. package/dist/identity/accounts.js +5 -0
  29. package/dist/identity/sessions.d.ts +7 -0
  30. package/dist/identity/sessions.js +26 -4
  31. package/dist/inbox/platform-inbox.service.d.ts +21 -11
  32. package/dist/inbox/platform-inbox.service.js +27 -12
  33. package/dist/inbox/platform-notices.d.ts +15 -1
  34. package/dist/inbox/platform-notices.js +20 -0
  35. package/dist/infra/config/kernel-config.service.js +2 -0
  36. package/dist/infra/outbox/registry.d.ts +36 -0
  37. package/dist/infra/outbox/registry.js +30 -0
  38. package/dist/infra/queue/queue-names.d.ts +1 -1
  39. package/dist/infra/queue/queue-names.js +1 -0
  40. package/dist/orgs/offboarding.js +3 -0
  41. package/dist/overrides.d.ts +4 -0
  42. package/dist/overrides.js +2 -0
  43. package/dist/platform/exclusions.js +15 -0
  44. package/dist/platform/ops/extensions-admin.ops.d.ts +5 -1
  45. package/dist/platform/ops/extensions-admin.ops.js +97 -2
  46. package/dist/platform/ops/inbox.ops.d.ts +1 -1
  47. package/dist/platform/ops/inbox.ops.js +17 -7
  48. package/dist/platform/ops/platform.ops.d.ts +4 -2
  49. package/dist/platform/ops/platform.ops.js +55 -3
  50. package/dist/platform/platform-ops.module.js +2 -0
  51. package/dist/platform/route-schemas.js +3 -0
  52. package/dist/push/delivery.d.ts +88 -0
  53. package/dist/push/delivery.js +269 -0
  54. package/dist/push/fanout.d.ts +29 -0
  55. package/dist/push/fanout.js +95 -0
  56. package/dist/push/jobs.d.ts +43 -0
  57. package/dist/push/jobs.js +19 -0
  58. package/dist/push/preferences.service.d.ts +18 -0
  59. package/dist/push/preferences.service.js +82 -0
  60. package/dist/push/provider-host.d.ts +34 -0
  61. package/dist/push/provider-host.js +94 -0
  62. package/dist/push/push-owed.d.ts +33 -0
  63. package/dist/push/push-owed.js +93 -0
  64. package/dist/push/push-processor.d.ts +40 -0
  65. package/dist/push/push-processor.js +114 -0
  66. package/dist/push/push.controller.d.ts +28 -0
  67. package/dist/push/push.controller.js +92 -0
  68. package/dist/push/push.module.d.ts +6 -0
  69. package/dist/push/push.module.js +29 -0
  70. package/dist/push/push.schemas.d.ts +88 -0
  71. package/dist/push/push.schemas.js +53 -0
  72. package/dist/push/recipients.d.ts +29 -0
  73. package/dist/push/recipients.js +263 -0
  74. package/dist/push/registration-cleanup.d.ts +9 -0
  75. package/dist/push/registration-cleanup.js +16 -0
  76. package/dist/push/registrations.service.d.ts +55 -0
  77. package/dist/push/registrations.service.js +254 -0
  78. package/dist/push/stale.job.d.ts +25 -0
  79. package/dist/push/stale.job.js +76 -0
  80. package/dist/push/texts.d.ts +31 -0
  81. package/dist/push/texts.js +46 -0
  82. package/dist/push/token-store.d.ts +31 -0
  83. package/dist/push/token-store.js +52 -0
  84. package/dist/push/triggers.d.ts +19 -0
  85. package/dist/push/triggers.js +30 -0
  86. package/dist/roles/worker-role.d.ts +7 -4
  87. package/dist/roles/worker-role.js +12 -5
  88. package/dist/roles/worker.module.d.ts +1 -1
  89. package/dist/roles/worker.module.js +4 -1
  90. package/dist/schedules/run-tracker.d.ts +10 -2
  91. package/dist/schedules/run-tracker.js +18 -4
  92. package/dist/setup/setup-checks.schemas.d.ts +29 -0
  93. package/dist/setup/setup-checks.schemas.js +32 -0
  94. package/dist/setup/setup-checks.service.d.ts +36 -3
  95. package/dist/setup/setup-checks.service.js +137 -29
  96. package/package.json +4 -4
  97. package/src/migrations/0172_push.sql +40 -0
  98. package/src/migrations/0173_push_auth_notice.sql +10 -0
@@ -0,0 +1,254 @@
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 { PUSH_LIMITS } from "@capybara-hq/plugin-sdk";
12
+ import { Inject, Injectable } from "@nestjs/common";
13
+ import { sql } from "kysely";
14
+ import { ApiError } from "../errors.js";
15
+ import { audit } from "../identity/audit.js";
16
+ import { KernelDb } from "../infra/database/kernel-db.js";
17
+ import { TransactionHost } from "../infra/database/transaction-host.js";
18
+ import { Transactional } from "../infra/database/transactional.decorator.js";
19
+ import { PushProviderHost } from "./provider-host.js";
20
+ import { PushTokenStore } from "./token-store.js";
21
+ /** Every column but the sealed token, for the reads that never need it. */
22
+ const VIEW_COLUMNS = [
23
+ "id",
24
+ "session_id",
25
+ "platform",
26
+ "app_id",
27
+ "provider",
28
+ "device_name",
29
+ "locale",
30
+ "created_at",
31
+ "last_seen_at",
32
+ ];
33
+ /**
34
+ * A person's app installs that receive push (mobile app spec §9.3). A registration belongs to the
35
+ * account, not an org, and follows the session that posted it (plan decision 3). A token posted
36
+ * again, by anyone, updates the one row of `(provider, app_id, token_hash)` and keeps its id, so
37
+ * the sealed token (AAD bound to the id) still opens; a phone that changes hands stops reaching its
38
+ * previous account (decision 5). The token is never logged, audited or answered.
39
+ */
40
+ let PushRegistrationsService = class PushRegistrationsService {
41
+ db;
42
+ txHost;
43
+ tokens;
44
+ providers;
45
+ constructor(db, txHost, tokens, providers) {
46
+ this.db = db;
47
+ this.txHost = txHost;
48
+ this.tokens = tokens;
49
+ this.providers = providers;
50
+ }
51
+ /**
52
+ * Registers (or refreshes) an install for `accountId` from `sessionId`. A provider that is not
53
+ * loaded or does not cover the app id → 422 `push.provider_unavailable`; a session revoked
54
+ * since the request was authenticated → 401 `auth.session_revoked`. Beyond
55
+ * `PUSH_LIMITS.registrationsPerAccount` the least recently seen of the account are deleted.
56
+ * Audited (`push.registered`) for a new row or a row taken from another account.
57
+ */
58
+ async register(accountId, sessionId, body) {
59
+ if (!this.providers.covers(body.provider, body.appId)) {
60
+ throw new ApiError("push.provider_unavailable", "No enabled push provider of that name covers this app id");
61
+ }
62
+ // The account row first (registrations of one account are serialized, so the cap holds),
63
+ // then the session row. Safe against the revoke paths: a disable updates the account row
64
+ // before its sessions, the same order; a password change holds only KEY SHARE on the account
65
+ // (through the foreign key; it updates the row, before its sessions, only while
66
+ // must_change_password is set), which does not conflict with FOR NO KEY UPDATE.
67
+ await this.db
68
+ .selectFrom("accounts")
69
+ .select("id")
70
+ .where("id", "=", accountId)
71
+ .forNoKeyUpdate()
72
+ .executeTakeFirst();
73
+ // Locked against revocation: a revoke that commits first is seen here, one that comes after
74
+ // waits and then deletes this registration with the session's others.
75
+ const session = await this.db
76
+ .selectFrom("sessions")
77
+ .select("id")
78
+ .where("id", "=", sessionId)
79
+ .where("account_id", "=", accountId)
80
+ .where("revoked_at", "is", null)
81
+ .where("expires_at", ">", sql `now()`)
82
+ .forShare()
83
+ .executeTakeFirst();
84
+ if (!session)
85
+ throw new ApiError("auth.session_revoked", "Session has been revoked");
86
+ const tokenHash = PushTokenStore.hash(body.token);
87
+ // a unique conflict whose winning row is gone again (a revoke deleted it) is retried once
88
+ const placed = (await this.place(accountId, sessionId, body, tokenHash)) ??
89
+ (await this.place(accountId, sessionId, body, tokenHash));
90
+ if (!placed)
91
+ throw new Error("push registration conflicted twice with a deleted row");
92
+ const { id, changedHands } = placed;
93
+ await this.evictBeyondCap(accountId);
94
+ if (changedHands) {
95
+ await audit(this.db.db, {
96
+ actorAccountId: accountId,
97
+ action: "push.registered",
98
+ target: id,
99
+ detail: {
100
+ registrationId: id,
101
+ platform: body.platform,
102
+ appId: body.appId,
103
+ provider: body.provider,
104
+ deviceName: body.deviceName,
105
+ },
106
+ });
107
+ }
108
+ return { id };
109
+ }
110
+ /** Removes one of the person's registrations; another account's id → 404. Audited. */
111
+ async remove(accountId, id) {
112
+ const row = await this.db
113
+ .deleteFrom("push_registrations")
114
+ .where("id", "=", id)
115
+ .where("account_id", "=", accountId)
116
+ .returning("id")
117
+ .executeTakeFirst();
118
+ if (!row)
119
+ throw new ApiError("push.registration_not_found", "Push registration not found");
120
+ await audit(this.db.db, {
121
+ actorAccountId: accountId,
122
+ action: "push.unregistered",
123
+ target: id,
124
+ detail: { registrationId: id, reason: "person" },
125
+ });
126
+ }
127
+ /** The person's registrations, newest `last_seen_at` first; `current` = posted by `sessionId`. */
128
+ async list(accountId, sessionId) {
129
+ const rows = await this.db
130
+ .selectFrom("push_registrations")
131
+ .select(VIEW_COLUMNS)
132
+ .where("account_id", "=", accountId)
133
+ .orderBy("last_seen_at", "desc")
134
+ .orderBy("id")
135
+ .execute();
136
+ return rows.map((r) => ({
137
+ id: r.id,
138
+ platform: r.platform,
139
+ appId: r.app_id,
140
+ provider: r.provider,
141
+ deviceName: r.device_name,
142
+ locale: r.locale,
143
+ createdAt: r.created_at.toISOString(),
144
+ lastSeenAt: r.last_seen_at.toISOString(),
145
+ current: r.session_id === sessionId,
146
+ }));
147
+ }
148
+ /** The registrations of these accounts, tokens still sealed (the fanout opens them per send). */
149
+ async forAccounts(accountIds) {
150
+ if (accountIds.length === 0)
151
+ return [];
152
+ return this.db
153
+ .selectFrom("push_registrations")
154
+ .selectAll()
155
+ .where("account_id", "in", [...accountIds])
156
+ .orderBy("id")
157
+ .execute();
158
+ }
159
+ /**
160
+ * Updates the row of this token in place (keeping its id) or inserts a sealed new one; null
161
+ * when the insert lost a unique conflict to a row that is already gone again.
162
+ */
163
+ async place(accountId, sessionId, body, tokenHash) {
164
+ const existing = await this.lockExisting(body.provider, body.appId, tokenHash);
165
+ if (existing) {
166
+ await this.refresh(existing.id, accountId, sessionId, body);
167
+ return { id: existing.id, changedHands: existing.account_id !== accountId };
168
+ }
169
+ const id = randomUUID();
170
+ const sealed = this.tokens.seal(id, body.token);
171
+ // ON CONFLICT waits for a concurrent insert of the same token; on its commit this inserts
172
+ // nothing and the caller's retry finds and takes that row
173
+ const inserted = await this.db
174
+ .insertInto("push_registrations")
175
+ .values({
176
+ id,
177
+ account_id: accountId,
178
+ session_id: sessionId,
179
+ platform: body.platform,
180
+ app_id: body.appId,
181
+ provider: body.provider,
182
+ token_hash: sealed.tokenHash,
183
+ master_key_id: sealed.masterKeyId,
184
+ token_ciphertext: sealed.ciphertext,
185
+ locale: body.locale,
186
+ device_name: body.deviceName,
187
+ })
188
+ .onConflict((oc) => oc.columns(["provider", "app_id", "token_hash"]).doNothing())
189
+ .returning("id")
190
+ .executeTakeFirst();
191
+ return inserted ? { id, changedHands: true } : null;
192
+ }
193
+ lockExisting(provider, appId, tokenHash) {
194
+ return this.db
195
+ .selectFrom("push_registrations")
196
+ .select(["id", "account_id"])
197
+ .where("provider", "=", provider)
198
+ .where("app_id", "=", appId)
199
+ .where("token_hash", "=", tokenHash)
200
+ .forUpdate()
201
+ .executeTakeFirst();
202
+ }
203
+ /** Points an existing row at the caller and its session; the id and the sealed token stay. */
204
+ async refresh(id, accountId, sessionId, body) {
205
+ await this.db
206
+ .updateTable("push_registrations")
207
+ .set({
208
+ account_id: accountId,
209
+ session_id: sessionId,
210
+ platform: body.platform,
211
+ locale: body.locale,
212
+ device_name: body.deviceName,
213
+ last_seen_at: sql `now()`,
214
+ })
215
+ .where("id", "=", id)
216
+ .execute();
217
+ }
218
+ /**
219
+ * Deletes the account's registrations beyond the cap, least recently seen first. Rows locked by
220
+ * another transaction are skipped (`FOR UPDATE SKIP LOCKED`), never waited for: a concurrent
221
+ * revoke of another session deleting its rows would otherwise deadlock with this (40P01). A
222
+ * skipped row is on its way out (a revoke) or to another account (a reassignment), so it does
223
+ * not count toward the 20 kept; the cap stays exact once those commit.
224
+ */
225
+ async evictBeyondCap(accountId) {
226
+ await this.db
227
+ .deleteFrom("push_registrations")
228
+ .where("id", "in", (eb) => eb
229
+ .selectFrom("push_registrations")
230
+ .select("id")
231
+ .where("account_id", "=", accountId)
232
+ .orderBy("last_seen_at", "desc")
233
+ .orderBy("created_at", "desc")
234
+ .orderBy("id", "desc")
235
+ .offset(PUSH_LIMITS.registrationsPerAccount)
236
+ .forUpdate()
237
+ .skipLocked())
238
+ .execute();
239
+ }
240
+ };
241
+ __decorate([
242
+ Transactional()
243
+ ], PushRegistrationsService.prototype, "register", null);
244
+ __decorate([
245
+ Transactional()
246
+ ], PushRegistrationsService.prototype, "remove", null);
247
+ PushRegistrationsService = __decorate([
248
+ Injectable(),
249
+ __param(0, Inject(KernelDb)),
250
+ __param(1, Inject(TransactionHost)),
251
+ __param(2, Inject(PushTokenStore)),
252
+ __param(3, Inject(PushProviderHost))
253
+ ], PushRegistrationsService);
254
+ export { PushRegistrationsService };
@@ -0,0 +1,25 @@
1
+ import { KernelDb } from "../infra/database/kernel-db.js";
2
+ import { LockService } from "../infra/lock/lock.service.js";
3
+ import type { KernelLogger } from "../log.js";
4
+ /** The daily prune's name (scheduler key and lock; no `:`). */
5
+ export declare const PUSH_STALE_JOB = "push-stale-registrations";
6
+ /**
7
+ * Deletes push registrations not seen for {@link STALE_DAYS} days (mobile app spec §9.3): the web
8
+ * re-posts a registration on each app start, which refreshes `last_seen_at`, so an app unused that
9
+ * long (or uninstalled without a sign-out) stops being pushed to. Once per tick across replicas
10
+ * (`@LockedCron`, provided only under `WorkerModule`); no audit entry (`push.unregistered` is
11
+ * written only for a person's removal). Nothing is kept between runs: a run stopped midway is
12
+ * finished by the next one.
13
+ */
14
+ export declare class PushStaleJob {
15
+ private readonly db;
16
+ readonly lockService: LockService;
17
+ readonly log: KernelLogger;
18
+ constructor(db: KernelDb, lockService: LockService, log: KernelLogger);
19
+ sweep(signal?: AbortSignal): Promise<void>;
20
+ /**
21
+ * One prune without the tick lock (the cron body; tests call it directly): deletes in batches
22
+ * of {@link BATCH} until none is left or `signal` aborts; returns how many it deleted.
23
+ */
24
+ prune(signal?: AbortSignal): Promise<number>;
25
+ }
@@ -0,0 +1,76 @@
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 { Inject, Injectable } from "@nestjs/common";
11
+ import { sql } from "kysely";
12
+ import { KernelDb } from "../infra/database/kernel-db.js";
13
+ import { LockService } from "../infra/lock/lock.service.js";
14
+ import { LockedCron } from "../infra/schedule/locked-cron.decorator.js";
15
+ import { KERNEL_LOGGER } from "../infra/tokens.js";
16
+ /** The daily prune's name (scheduler key and lock; no `:`). */
17
+ export const PUSH_STALE_JOB = "push-stale-registrations";
18
+ /** Registrations not seen for this many days are deleted. */
19
+ const STALE_DAYS = 60;
20
+ /** Rows per delete statement. */
21
+ const BATCH = 500;
22
+ /**
23
+ * Deletes push registrations not seen for {@link STALE_DAYS} days (mobile app spec §9.3): the web
24
+ * re-posts a registration on each app start, which refreshes `last_seen_at`, so an app unused that
25
+ * long (or uninstalled without a sign-out) stops being pushed to. Once per tick across replicas
26
+ * (`@LockedCron`, provided only under `WorkerModule`); no audit entry (`push.unregistered` is
27
+ * written only for a person's removal). Nothing is kept between runs: a run stopped midway is
28
+ * finished by the next one.
29
+ */
30
+ let PushStaleJob = class PushStaleJob {
31
+ db;
32
+ lockService;
33
+ log;
34
+ constructor(db, lockService, log) {
35
+ this.db = db;
36
+ this.lockService = lockService;
37
+ this.log = log;
38
+ }
39
+ async sweep(signal) {
40
+ const deleted = await this.prune(signal);
41
+ if (deleted > 0)
42
+ this.log.info("stale push registrations deleted", { deleted });
43
+ }
44
+ /**
45
+ * One prune without the tick lock (the cron body; tests call it directly): deletes in batches
46
+ * of {@link BATCH} until none is left or `signal` aborts; returns how many it deleted.
47
+ */
48
+ async prune(signal) {
49
+ let deleted = 0;
50
+ while (!signal?.aborted) {
51
+ const r = await this.db.db
52
+ .deleteFrom("push_registrations")
53
+ .where("id", "in", (eb) => eb
54
+ .selectFrom("push_registrations")
55
+ .select("id")
56
+ .where("last_seen_at", "<", sql `now() - make_interval(days => ${STALE_DAYS})`)
57
+ .limit(BATCH))
58
+ .executeTakeFirst();
59
+ const n = Number(r.numDeletedRows);
60
+ deleted += n;
61
+ if (n < BATCH)
62
+ break;
63
+ }
64
+ return deleted;
65
+ }
66
+ };
67
+ __decorate([
68
+ LockedCron("40 3 * * *", { name: PUSH_STALE_JOB })
69
+ ], PushStaleJob.prototype, "sweep", null);
70
+ PushStaleJob = __decorate([
71
+ Injectable(),
72
+ __param(0, Inject(KernelDb)),
73
+ __param(1, Inject(LockService)),
74
+ __param(2, Inject(KERNEL_LOGGER))
75
+ ], PushStaleJob);
76
+ export { PushStaleJob };
@@ -0,0 +1,31 @@
1
+ import { type PushMessage } from "@capybara-hq/plugin-sdk";
2
+ import type { PushCategory, PushTextKey } from "./triggers.js";
3
+ /** Every push text key. */
4
+ export declare const PUSH_TEXT_KEYS: readonly PushTextKey[];
5
+ /** The sentence of `key` in `locale`. */
6
+ export declare function pushText(key: PushTextKey, locale: "zh" | "en"): string;
7
+ /** An event's push as the fanout resolved it (`recipients.ts`), with the event id. */
8
+ export interface ResolvedPush {
9
+ /** `conv-<conversationId>-<seq>` or `sched-<taskRunId>`: the message's collapse id. */
10
+ eventId: string;
11
+ orgId: string;
12
+ accountIds: string[];
13
+ category: PushCategory;
14
+ /** In-app path with `?org=` (plan decision 8). */
15
+ path: string;
16
+ /** The root conversation id, or `schedule-<taskId>`. */
17
+ threadId: string;
18
+ /** The agent's display name (the task's name for a schedule). */
19
+ title: string;
20
+ /** Shown only with `push.previews: "titles"`. */
21
+ conversationTitle: string | null;
22
+ text: PushTextKey;
23
+ }
24
+ /**
25
+ * The message of `r` for one registration's locale. `title` is the agent's (or task's) name cut
26
+ * to `PUSH_LIMITS.titleChars`; `body` is the fixed sentence, led by the conversation title only
27
+ * with previews `titles` (`<title>: <sentence>`; zh joins them with a full-width colon), cut to
28
+ * `PUSH_LIMITS.bodyChars`. Message and tool text are never part of it. `collapseId` is the event
29
+ * id, so a resend of the same event replaces the notification on the device. No badge (decision 7).
30
+ */
31
+ export declare function renderPushMessage(r: ResolvedPush, locale: "zh" | "en", previews: "off" | "titles", origin: string): PushMessage;
@@ -0,0 +1,46 @@
1
+ import { PUSH_LIMITS } from "@capybara-hq/plugin-sdk";
2
+ /** The push copy (mobile app spec §9.5): the body's fixed sentence per key and locale. */
3
+ const PUSH_TEXTS = {
4
+ approval: { en: "needs your approval", zh: "需要你的审批" },
5
+ question: { en: "has a question for you", zh: "有问题需要你回答" },
6
+ connect: { en: "needs you to connect an account", zh: "需要你连接账号" },
7
+ runFinished: { en: "finished", zh: "已完成" },
8
+ runFailed: { en: "failed", zh: "运行失败" },
9
+ backgroundFinished: { en: "a background task ended", zh: "后台任务已结束" },
10
+ subagentFinished: { en: "a sub-agent finished", zh: "子智能体已完成" },
11
+ scheduleRan: { en: "your scheduled task ran", zh: "你的定时任务已运行" },
12
+ scheduleFailed: { en: "your scheduled task failed", zh: "你的定时任务运行失败" },
13
+ };
14
+ /** Every push text key. */
15
+ export const PUSH_TEXT_KEYS = Object.keys(PUSH_TEXTS);
16
+ /** The sentence of `key` in `locale`. */
17
+ export function pushText(key, locale) {
18
+ return PUSH_TEXTS[key][locale];
19
+ }
20
+ /** `s` cut to `max` UTF-16 units, never splitting a surrogate pair. */
21
+ function cut(s, max) {
22
+ if (s.length <= max)
23
+ return s;
24
+ const out = s.slice(0, max);
25
+ return /[\uD800-\uDBFF]$/.test(out) ? out.slice(0, -1) : out;
26
+ }
27
+ /**
28
+ * The message of `r` for one registration's locale. `title` is the agent's (or task's) name cut
29
+ * to `PUSH_LIMITS.titleChars`; `body` is the fixed sentence, led by the conversation title only
30
+ * with previews `titles` (`<title>: <sentence>`; zh joins them with a full-width colon), cut to
31
+ * `PUSH_LIMITS.bodyChars`. Message and tool text are never part of it. `collapseId` is the event
32
+ * id, so a resend of the same event replaces the notification on the device. No badge (decision 7).
33
+ */
34
+ export function renderPushMessage(r, locale, previews, origin) {
35
+ const sentence = pushText(r.text, locale);
36
+ const lead = previews === "titles" && r.conversationTitle ? r.conversationTitle : null;
37
+ const body = lead === null ? sentence : `${lead}${locale === "zh" ? ":" : ": "}${sentence}`;
38
+ return {
39
+ title: cut(r.title, PUSH_LIMITS.titleChars),
40
+ body: cut(body, PUSH_LIMITS.bodyChars),
41
+ path: r.path,
42
+ threadId: r.threadId,
43
+ collapseId: r.eventId,
44
+ origin,
45
+ };
46
+ }
@@ -0,0 +1,31 @@
1
+ import { type Keyring } from "../ctx/secrets.js";
2
+ /** A push token sealed for one registration, as `push_registrations` stores it. */
3
+ export interface SealedPushToken {
4
+ masterKeyId: string;
5
+ ciphertext: Buffer;
6
+ /** sha256 hex of the token: the uniqueness key, never the token itself. */
7
+ tokenHash: string;
8
+ }
9
+ /**
10
+ * Seals and opens a device's push token (mobile app spec §9.3) with the master keyring, bound to
11
+ * its registration id: a ciphertext moved to another row fails to open. The token never leaves
12
+ * this store except to the push provider that delivers to it: never a log line, an error message,
13
+ * the audit, job data or an API answer.
14
+ */
15
+ export declare class PushTokenStore {
16
+ private readonly keyring;
17
+ constructor(keyring: Keyring);
18
+ /** The sha256 hex of a token (64 characters), the column that keeps registrations unique. */
19
+ static hash(token: string): string;
20
+ /** Seals `token` for the registration with the current master key. */
21
+ seal(registrationId: string, token: string): SealedPushToken;
22
+ /**
23
+ * Opens a registration's token. Throws when the master key is not in the keyring or the
24
+ * ciphertext does not belong to this registration; the error names ids only.
25
+ */
26
+ open(row: {
27
+ id: string;
28
+ master_key_id: string;
29
+ token_ciphertext: Uint8Array;
30
+ }): string;
31
+ }
@@ -0,0 +1,52 @@
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
+ var PushTokenStore_1;
11
+ import { createHash } from "node:crypto";
12
+ import { Inject, Injectable } from "@nestjs/common";
13
+ import { pushTokenAad } from "../ctx/secrets.js";
14
+ import { KEYRING } from "../infra/tokens.js";
15
+ /**
16
+ * Seals and opens a device's push token (mobile app spec §9.3) with the master keyring, bound to
17
+ * its registration id: a ciphertext moved to another row fails to open. The token never leaves
18
+ * this store except to the push provider that delivers to it: never a log line, an error message,
19
+ * the audit, job data or an API answer.
20
+ */
21
+ let PushTokenStore = PushTokenStore_1 = class PushTokenStore {
22
+ keyring;
23
+ constructor(keyring) {
24
+ this.keyring = keyring;
25
+ }
26
+ /** The sha256 hex of a token (64 characters), the column that keeps registrations unique. */
27
+ static hash(token) {
28
+ return createHash("sha256").update(token, "utf8").digest("hex");
29
+ }
30
+ /** Seals `token` for the registration with the current master key. */
31
+ seal(registrationId, token) {
32
+ const plain = Buffer.from(token, "utf8");
33
+ const { data, masterKeyId } = this.keyring.wrap(plain, pushTokenAad(registrationId));
34
+ plain.fill(0);
35
+ return { masterKeyId, ciphertext: data, tokenHash: PushTokenStore_1.hash(token) };
36
+ }
37
+ /**
38
+ * Opens a registration's token. Throws when the master key is not in the keyring or the
39
+ * ciphertext does not belong to this registration; the error names ids only.
40
+ */
41
+ open(row) {
42
+ const plain = this.keyring.unwrap(row.master_key_id, Buffer.from(row.token_ciphertext), pushTokenAad(row.id));
43
+ const token = plain.toString("utf8");
44
+ plain.fill(0);
45
+ return token;
46
+ }
47
+ };
48
+ PushTokenStore = PushTokenStore_1 = __decorate([
49
+ Injectable(),
50
+ __param(0, Inject(KEYRING))
51
+ ], PushTokenStore);
52
+ export { PushTokenStore };
@@ -0,0 +1,19 @@
1
+ import type { ConversationEvent } from "../conversations/events.js";
2
+ import type { PushCategory } from "./push.schemas.js";
3
+ export type { PushCategory } from "./push.schemas.js";
4
+ /** The fixed sentences of a push body (`texts.ts` holds the copy). */
5
+ export type PushTextKey = "approval" | "question" | "connect" | "runFinished" | "runFailed" | "backgroundFinished" | "subagentFinished" | "scheduleRan" | "scheduleFailed";
6
+ /** What one event pushes: its category (the person's switch) and its sentence. */
7
+ export interface PushTrigger {
8
+ category: PushCategory;
9
+ text: PushTextKey;
10
+ }
11
+ /**
12
+ * The push an event of a conversation log triggers (mobile app spec §9.4, the plan's Triggers
13
+ * table), or null. Pure: who receives it and whether it still applies (an approval still pending,
14
+ * a chat conversation, a person's run) is decided when the fanout runs. A background task that a
15
+ * person, a deletion or its sub-agent's end stopped pushes nothing; `run_aborted` (someone stopped
16
+ * the run), `approval_decided` and `subagent_waiting` (the child's own `approval_requested` pushes)
17
+ * push nothing.
18
+ */
19
+ export declare function pushTriggerOf(e: Pick<ConversationEvent, "type" | "payload">): PushTrigger | null;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * The push an event of a conversation log triggers (mobile app spec §9.4, the plan's Triggers
3
+ * table), or null. Pure: who receives it and whether it still applies (an approval still pending,
4
+ * a chat conversation, a person's run) is decided when the fanout runs. A background task that a
5
+ * person, a deletion or its sub-agent's end stopped pushes nothing; `run_aborted` (someone stopped
6
+ * the run), `approval_decided` and `subagent_waiting` (the child's own `approval_requested` pushes)
7
+ * push nothing.
8
+ */
9
+ export function pushTriggerOf(e) {
10
+ switch (e.type) {
11
+ case "approval_requested":
12
+ return { category: "waiting", text: "approval" };
13
+ case "question_asked":
14
+ return { category: "waiting", text: "question" };
15
+ case "connection_required":
16
+ return { category: "waiting", text: "connect" };
17
+ case "run_finished":
18
+ return { category: "replies", text: "runFinished" };
19
+ case "run_failed":
20
+ return { category: "replies", text: "runFailed" };
21
+ case "background_task_finished":
22
+ return e.payload.stoppedBy === undefined
23
+ ? { category: "tasks", text: "backgroundFinished" }
24
+ : null;
25
+ case "subagent_finished":
26
+ return { category: "tasks", text: "subagentFinished" };
27
+ default:
28
+ return null;
29
+ }
30
+ }
@@ -10,6 +10,7 @@ import { KernelConfigService } from "../infra/config/kernel-config.service.js";
10
10
  import { LockedIntervalScheduler } from "../infra/schedule/locked-interval.js";
11
11
  import { ScheduledRuns } from "../infra/schedule/scheduled-runs.js";
12
12
  import type { KernelLogger } from "../log.js";
13
+ import { PushProcessor } from "../push/push-processor.js";
13
14
  import { MaintenanceProcessor } from "../runtime/maintenance.js";
14
15
  import { PromptSuggestionProcessor, RunsProcessor, SubagentRunsProcessor, TitleProcessor, UsageReportProcessor } from "../runtime/run-processors.js";
15
16
  import { RunWorker } from "../runtime/run-worker.js";
@@ -18,7 +19,7 @@ import { UsageReporter } from "../runtime/usage-report.js";
18
19
  * The worker role's parts, driven by `KernelLifecycle` at fixed points of its start order and stop
19
20
  * phases (so they stay ordered after the extension load and before the extension host closes): the
20
21
  * queue consumers (runs, sub-agent runs, evals, maintenance, the plugin scope sync, lifecycle
21
- * hook deliveries, channel deliveries, `usage.report`, titles, prompt suggestions) and the schedulers of the `@LockedCron` / `@LockedInterval` jobs. Provided only by
22
+ * hook deliveries, push deliveries, channel deliveries, `usage.report`, titles, prompt suggestions) and the schedulers of the `@LockedCron` / `@LockedInterval` jobs. Provided only by
22
23
  * `WorkerModule`, so a process without the worker role has none of them.
23
24
  */
24
25
  export declare class WorkerRole {
@@ -41,13 +42,14 @@ export declare class WorkerRole {
41
42
  private readonly maintenanceProcessor;
42
43
  private readonly scopeProcessor;
43
44
  private readonly lifecycleProcessor;
45
+ private readonly pushProcessor;
44
46
  /** The startup config (the roles). */
45
47
  private readonly config;
46
48
  /** The run worker was started: the runs phase drains it. */
47
49
  private runsStarted;
48
50
  /** The eval worker was started: the runs phase drains it. */
49
51
  private evalsStarted;
50
- constructor(config: KernelConfigService, log: KernelLogger, intervals: LockedIntervalScheduler, scheduledRuns: ScheduledRuns, runWorker: RunWorker, evalWorker: EvalWorker, usageReport: UsageReporter, titles: TitleQueue, suggestions: PromptSuggestionQueue, channelOutbound: ChannelOutbound, runsProcessor: RunsProcessor, subagentRunsProcessor: SubagentRunsProcessor, usageProcessor: UsageReportProcessor, titleProcessor: TitleProcessor, suggestionProcessor: PromptSuggestionProcessor, channelsProcessor: ChannelsProcessor, evalsProcessor: EvalsProcessor, maintenanceProcessor: MaintenanceProcessor, scopeProcessor: PluginScopeSyncProcessor, lifecycleProcessor: LifecycleHooksProcessor);
52
+ constructor(config: KernelConfigService, log: KernelLogger, intervals: LockedIntervalScheduler, scheduledRuns: ScheduledRuns, runWorker: RunWorker, evalWorker: EvalWorker, usageReport: UsageReporter, titles: TitleQueue, suggestions: PromptSuggestionQueue, channelOutbound: ChannelOutbound, runsProcessor: RunsProcessor, subagentRunsProcessor: SubagentRunsProcessor, usageProcessor: UsageReportProcessor, titleProcessor: TitleProcessor, suggestionProcessor: PromptSuggestionProcessor, channelsProcessor: ChannelsProcessor, evalsProcessor: EvalsProcessor, maintenanceProcessor: MaintenanceProcessor, scopeProcessor: PluginScopeSyncProcessor, lifecycleProcessor: LifecycleHooksProcessor, pushProcessor: PushProcessor);
51
53
  /**
52
54
  * Starts the queue consumers (after the extension load), then opens the schedules' start gate:
53
55
  * the cron and interval timers were armed at application bootstrap, but every tick before this
@@ -65,8 +67,9 @@ export declare class WorkerRole {
65
67
  /** The eval cases in progress stop (undefined: never started). */
66
68
  drainEvals(budgetMs: number): Promise<void> | undefined;
67
69
  /**
68
- * Closes the maintenance queue's worker, the plugin scope sync's (it stops between pairs) and
69
- * the lifecycle hook deliveries' (calls in flight are aborted and retried).
70
+ * Closes the maintenance queue's worker, the plugin scope sync's (it stops between pairs), the
71
+ * lifecycle hook deliveries' (calls in flight are aborted and retried) and the push deliveries'
72
+ * (sends in flight finish, each bounded by the send time limit).
70
73
  */
71
74
  closeMaintenance(): Promise<void>;
72
75
  }