@capybara-hq/kernel 0.1.0-rc.60 → 0.1.0-rc.62
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.
- package/dist/admin/admin.module.js +3 -0
- package/dist/admin/extensions.controller.d.ts +32 -1
- package/dist/admin/extensions.controller.js +72 -3
- package/dist/admin/health.service.d.ts +2 -2
- package/dist/admin/health.service.js +6 -2
- package/dist/catalog/marketplaces.service.d.ts +1 -1
- package/dist/config/schema.d.ts +6 -0
- package/dist/config/schema.js +12 -0
- package/dist/conversations/attachments.controller.d.ts +11 -3
- package/dist/conversations/attachments.controller.js +18 -5
- package/dist/conversations/conversations.controller.d.ts +11 -2
- package/dist/conversations/conversations.controller.js +17 -4
- package/dist/conversations/conversations.schemas.d.ts +8 -0
- package/dist/conversations/conversations.schemas.js +6 -0
- package/dist/conversations/event-log.d.ts +12 -3
- package/dist/conversations/event-log.js +17 -5
- package/dist/ctx/secrets.d.ts +10 -5
- package/dist/ctx/secrets.js +16 -5
- package/dist/db/kernel-schema.d.ts +34 -2
- package/dist/errors.d.ts +7 -0
- package/dist/errors.js +7 -0
- package/dist/extensions/config-hash.d.ts +2 -0
- package/dist/extensions/config-hash.js +1 -1
- package/dist/extensions/guide-places.d.ts +5 -1
- package/dist/extensions/guide-places.js +9 -2
- package/dist/extensions/permission-view.d.ts +6 -4
- package/dist/extensions/permission-view.js +6 -3
- package/dist/extensions/plugin-guides.d.ts +20 -0
- package/dist/extensions/plugin-guides.js +49 -1
- package/dist/extensions/registry.js +1 -0
- package/dist/http/api.module.js +7 -0
- package/dist/http/meta.controller.d.ts +7 -1
- package/dist/http/meta.controller.js +14 -3
- package/dist/identity/accounts.js +5 -0
- package/dist/identity/sessions.d.ts +7 -0
- package/dist/identity/sessions.js +26 -4
- package/dist/inbox/platform-inbox.service.d.ts +21 -11
- package/dist/inbox/platform-inbox.service.js +27 -12
- package/dist/inbox/platform-notices.d.ts +15 -1
- package/dist/inbox/platform-notices.js +20 -0
- package/dist/infra/config/kernel-config.service.js +2 -0
- package/dist/infra/outbox/registry.d.ts +36 -0
- package/dist/infra/outbox/registry.js +30 -0
- package/dist/infra/queue/queue-names.d.ts +1 -1
- package/dist/infra/queue/queue-names.js +1 -0
- package/dist/orgs/offboarding.js +3 -0
- package/dist/overrides.d.ts +4 -0
- package/dist/overrides.js +2 -0
- package/dist/platform/exclusions.js +15 -0
- package/dist/platform/ops/extensions-admin.ops.d.ts +5 -1
- package/dist/platform/ops/extensions-admin.ops.js +97 -2
- package/dist/platform/ops/inbox.ops.d.ts +1 -1
- package/dist/platform/ops/inbox.ops.js +17 -7
- package/dist/platform/ops/platform.ops.d.ts +4 -2
- package/dist/platform/ops/platform.ops.js +55 -3
- package/dist/platform/platform-ops.module.js +2 -0
- package/dist/platform/route-schemas.js +3 -0
- package/dist/push/delivery.d.ts +88 -0
- package/dist/push/delivery.js +269 -0
- package/dist/push/fanout.d.ts +29 -0
- package/dist/push/fanout.js +95 -0
- package/dist/push/jobs.d.ts +43 -0
- package/dist/push/jobs.js +19 -0
- package/dist/push/preferences.service.d.ts +18 -0
- package/dist/push/preferences.service.js +82 -0
- package/dist/push/provider-host.d.ts +34 -0
- package/dist/push/provider-host.js +94 -0
- package/dist/push/push-owed.d.ts +33 -0
- package/dist/push/push-owed.js +93 -0
- package/dist/push/push-processor.d.ts +40 -0
- package/dist/push/push-processor.js +114 -0
- package/dist/push/push.controller.d.ts +28 -0
- package/dist/push/push.controller.js +92 -0
- package/dist/push/push.module.d.ts +6 -0
- package/dist/push/push.module.js +29 -0
- package/dist/push/push.schemas.d.ts +88 -0
- package/dist/push/push.schemas.js +53 -0
- package/dist/push/recipients.d.ts +29 -0
- package/dist/push/recipients.js +263 -0
- package/dist/push/registration-cleanup.d.ts +9 -0
- package/dist/push/registration-cleanup.js +16 -0
- package/dist/push/registrations.service.d.ts +55 -0
- package/dist/push/registrations.service.js +254 -0
- package/dist/push/stale.job.d.ts +25 -0
- package/dist/push/stale.job.js +76 -0
- package/dist/push/texts.d.ts +31 -0
- package/dist/push/texts.js +46 -0
- package/dist/push/token-store.d.ts +31 -0
- package/dist/push/token-store.js +52 -0
- package/dist/push/triggers.d.ts +19 -0
- package/dist/push/triggers.js +30 -0
- package/dist/roles/worker-role.d.ts +7 -4
- package/dist/roles/worker-role.js +12 -5
- package/dist/roles/worker.module.d.ts +1 -1
- package/dist/roles/worker.module.js +4 -1
- package/dist/schedules/run-tracker.d.ts +10 -2
- package/dist/schedules/run-tracker.js +18 -4
- package/dist/setup/setup-checks.schemas.d.ts +29 -0
- package/dist/setup/setup-checks.schemas.js +32 -0
- package/dist/setup/setup-checks.service.d.ts +36 -3
- package/dist/setup/setup-checks.service.js +137 -29
- package/package.json +4 -4
- package/src/migrations/0172_push.sql +40 -0
- package/src/migrations/0173_push_auth_notice.sql +10 -0
|
@@ -0,0 +1,29 @@
|
|
|
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
|
+
import { Module } from "@nestjs/common";
|
|
8
|
+
import { QueueModule } from "../infra/queue/queue.module.js";
|
|
9
|
+
import { PUSH_QUEUE } from "./jobs.js";
|
|
10
|
+
import { PushPreferencesService } from "./preferences.service.js";
|
|
11
|
+
import { PushHostModule } from "./provider-host.js";
|
|
12
|
+
import { PushRegistrationsService } from "./registrations.service.js";
|
|
13
|
+
import { PushTokenStore } from "./token-store.js";
|
|
14
|
+
/** The push queue (`cap-push-deliver`): registered on every role, since every role owes jobs. */
|
|
15
|
+
const PUSH_QUEUE_MODULE = QueueModule.registerQueue(PUSH_QUEUE);
|
|
16
|
+
/**
|
|
17
|
+
* Push registrations and preferences (mobile app spec §9.3, §9.4) and the push queue; the
|
|
18
|
+
* controller is the API's, the queue's consumer the worker role's (`PushWorkersModule`).
|
|
19
|
+
*/
|
|
20
|
+
let PushModule = class PushModule {
|
|
21
|
+
};
|
|
22
|
+
PushModule = __decorate([
|
|
23
|
+
Module({
|
|
24
|
+
imports: [PushHostModule, PUSH_QUEUE_MODULE],
|
|
25
|
+
providers: [PushTokenStore, PushRegistrationsService, PushPreferencesService],
|
|
26
|
+
exports: [PushTokenStore, PushRegistrationsService, PushPreferencesService, PUSH_QUEUE_MODULE],
|
|
27
|
+
})
|
|
28
|
+
], PushModule);
|
|
29
|
+
export { PushModule };
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import type { RouteSchemas } from "../platform/route-schemas.js";
|
|
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", "schedules"];
|
|
5
|
+
export type PushCategory = (typeof PUSH_CATEGORIES)[number];
|
|
6
|
+
/**
|
|
7
|
+
* `POST /me/push-registrations`: what the app's shell returns from `push@1.register()`, plus the
|
|
8
|
+
* person's locale and a device name. The token is sealed at rest and never echoed.
|
|
9
|
+
*/
|
|
10
|
+
export declare const PushRegistrationSchema: z.ZodObject<{
|
|
11
|
+
platform: z.ZodEnum<{
|
|
12
|
+
android: "android";
|
|
13
|
+
ios: "ios";
|
|
14
|
+
}>;
|
|
15
|
+
appId: z.ZodString;
|
|
16
|
+
provider: z.ZodString;
|
|
17
|
+
token: z.ZodString;
|
|
18
|
+
locale: z.ZodEnum<{
|
|
19
|
+
en: "en";
|
|
20
|
+
zh: "zh";
|
|
21
|
+
}>;
|
|
22
|
+
deviceName: z.ZodString;
|
|
23
|
+
}, z.core.$strict>;
|
|
24
|
+
export type PushRegistrationBody = z.infer<typeof PushRegistrationSchema>;
|
|
25
|
+
declare const PushRegistrationDto_base: import("../infra/validation/create-zod-dto.js").ZodDtoClass<z.ZodObject<{
|
|
26
|
+
platform: z.ZodEnum<{
|
|
27
|
+
android: "android";
|
|
28
|
+
ios: "ios";
|
|
29
|
+
}>;
|
|
30
|
+
appId: z.ZodString;
|
|
31
|
+
provider: z.ZodString;
|
|
32
|
+
token: z.ZodString;
|
|
33
|
+
locale: z.ZodEnum<{
|
|
34
|
+
en: "en";
|
|
35
|
+
zh: "zh";
|
|
36
|
+
}>;
|
|
37
|
+
deviceName: z.ZodString;
|
|
38
|
+
}, z.core.$strict>>;
|
|
39
|
+
export declare class PushRegistrationDto extends PushRegistrationDto_base {
|
|
40
|
+
}
|
|
41
|
+
export declare const PushRegistrationParams: z.ZodObject<{
|
|
42
|
+
id: z.ZodString;
|
|
43
|
+
}, z.core.$strict>;
|
|
44
|
+
declare const PushRegistrationParamsDto_base: import("../infra/validation/create-zod-dto.js").ZodDtoClass<z.ZodObject<{
|
|
45
|
+
id: z.ZodString;
|
|
46
|
+
}, z.core.$strict>>;
|
|
47
|
+
export declare class PushRegistrationParamsDto extends PushRegistrationParamsDto_base {
|
|
48
|
+
}
|
|
49
|
+
/** One of the person's registrations as the settings page lists it (never the token). */
|
|
50
|
+
export interface PushRegistrationView {
|
|
51
|
+
id: string;
|
|
52
|
+
platform: "ios" | "android";
|
|
53
|
+
appId: string;
|
|
54
|
+
provider: string;
|
|
55
|
+
deviceName: string;
|
|
56
|
+
locale: "zh" | "en";
|
|
57
|
+
createdAt: string;
|
|
58
|
+
lastSeenAt: string;
|
|
59
|
+
/** Posted by the session making the request. */
|
|
60
|
+
current: boolean;
|
|
61
|
+
}
|
|
62
|
+
/** The person's four push switches, as `GET` / `PUT /me/push-preferences` answer them. */
|
|
63
|
+
export declare const PushPreferencesSchema: z.ZodObject<{
|
|
64
|
+
waiting: z.ZodBoolean;
|
|
65
|
+
replies: z.ZodBoolean;
|
|
66
|
+
tasks: z.ZodBoolean;
|
|
67
|
+
schedules: z.ZodBoolean;
|
|
68
|
+
}, z.core.$strict>;
|
|
69
|
+
export type PushPreferences = z.infer<typeof PushPreferencesSchema>;
|
|
70
|
+
/** `PUT /me/push-preferences`: the switches to change, at least one. */
|
|
71
|
+
export declare const PushPreferencesPatchSchema: z.ZodObject<{
|
|
72
|
+
waiting: z.ZodOptional<z.ZodBoolean>;
|
|
73
|
+
replies: z.ZodOptional<z.ZodBoolean>;
|
|
74
|
+
tasks: z.ZodOptional<z.ZodBoolean>;
|
|
75
|
+
schedules: z.ZodOptional<z.ZodBoolean>;
|
|
76
|
+
}, z.core.$strict>;
|
|
77
|
+
export type PushPreferencesPatch = z.infer<typeof PushPreferencesPatchSchema>;
|
|
78
|
+
declare const PushPreferencesPatchDto_base: import("../infra/validation/create-zod-dto.js").ZodDtoClass<z.ZodObject<{
|
|
79
|
+
waiting: z.ZodOptional<z.ZodBoolean>;
|
|
80
|
+
replies: z.ZodOptional<z.ZodBoolean>;
|
|
81
|
+
tasks: z.ZodOptional<z.ZodBoolean>;
|
|
82
|
+
schedules: z.ZodOptional<z.ZodBoolean>;
|
|
83
|
+
}, z.core.$strict>>;
|
|
84
|
+
export declare class PushPreferencesPatchDto extends PushPreferencesPatchDto_base {
|
|
85
|
+
}
|
|
86
|
+
/** The push routes the Platform operations mirror (`check:platform-ops` keys). */
|
|
87
|
+
export declare const PUSH_ROUTES: readonly RouteSchemas[];
|
|
88
|
+
export {};
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { PUSH_LIMITS } from "@capybara-hq/plugin-sdk";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
import { createZodDto } from "../infra/validation/create-zod-dto.js";
|
|
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", "schedules"];
|
|
6
|
+
/**
|
|
7
|
+
* `POST /me/push-registrations`: what the app's shell returns from `push@1.register()`, plus the
|
|
8
|
+
* person's locale and a device name. The token is sealed at rest and never echoed.
|
|
9
|
+
*/
|
|
10
|
+
export const PushRegistrationSchema = z
|
|
11
|
+
.object({
|
|
12
|
+
platform: z.enum(["ios", "android"]),
|
|
13
|
+
/** The bundle id / application id of the app build. */
|
|
14
|
+
appId: z
|
|
15
|
+
.string()
|
|
16
|
+
.min(1)
|
|
17
|
+
.max(PUSH_LIMITS.appIdChars)
|
|
18
|
+
.regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/),
|
|
19
|
+
/** The push-provider extension (plugin name) the token belongs to. */
|
|
20
|
+
provider: z.string().regex(/^[a-z][a-z0-9-]{0,63}$/),
|
|
21
|
+
token: z.string().min(1).max(PUSH_LIMITS.tokenChars),
|
|
22
|
+
locale: z.enum(["zh", "en"]),
|
|
23
|
+
/** Shown in the person's notification settings; no control or format characters. */
|
|
24
|
+
deviceName: z
|
|
25
|
+
.string()
|
|
26
|
+
.min(1)
|
|
27
|
+
.max(PUSH_LIMITS.deviceNameChars)
|
|
28
|
+
.regex(/^[^\p{Cc}\p{Cf}\p{Zl}\p{Zp}]+$/u),
|
|
29
|
+
})
|
|
30
|
+
.strict();
|
|
31
|
+
export class PushRegistrationDto extends createZodDto(PushRegistrationSchema, "PushRegistrationBody") {
|
|
32
|
+
}
|
|
33
|
+
export const PushRegistrationParams = z.object({ id: z.string().min(1).max(100) }).strict();
|
|
34
|
+
export class PushRegistrationParamsDto extends createZodDto(PushRegistrationParams, "PushRegistrationParams") {
|
|
35
|
+
}
|
|
36
|
+
/** The person's four push switches, as `GET` / `PUT /me/push-preferences` answer them. */
|
|
37
|
+
export const PushPreferencesSchema = z
|
|
38
|
+
.object({
|
|
39
|
+
waiting: z.boolean(),
|
|
40
|
+
replies: z.boolean(),
|
|
41
|
+
tasks: z.boolean(),
|
|
42
|
+
schedules: z.boolean(),
|
|
43
|
+
})
|
|
44
|
+
.strict();
|
|
45
|
+
/** `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, schedules" });
|
|
47
|
+
export class PushPreferencesPatchDto extends createZodDto(PushPreferencesPatchSchema, "PushPreferencesPatch") {
|
|
48
|
+
}
|
|
49
|
+
/** The push routes the Platform operations mirror (`check:platform-ops` keys). */
|
|
50
|
+
export const PUSH_ROUTES = [
|
|
51
|
+
{ route: "GET /api/v1/me/push-preferences" },
|
|
52
|
+
{ route: "PUT /api/v1/me/push-preferences", body: PushPreferencesPatchSchema },
|
|
53
|
+
];
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { KernelSchemaDb } from "../db/kernel-schema.js";
|
|
2
|
+
import type { PushFanoutData } from "./jobs.js";
|
|
3
|
+
import type { ResolvedPush } from "./texts.js";
|
|
4
|
+
/** An event's push before the event id is attached: who receives it and what it says. */
|
|
5
|
+
export type ResolvedRecipients = Omit<ResolvedPush, "eventId">;
|
|
6
|
+
/**
|
|
7
|
+
* Who an event's push reaches, read when the fanout runs (mobile app spec §9.4, the plan's
|
|
8
|
+
* Triggers table), or null when nothing is pushed. Every check is made now, not when the event was
|
|
9
|
+
* written (review focus 1):
|
|
10
|
+
*
|
|
11
|
+
* - the org is not deleted, and every recipient is an `active` account that is still a member of
|
|
12
|
+
* the event's org (an account of another org never qualifies, whatever a row names);
|
|
13
|
+
* - `waiting`: an approval goes to `requested_for`, else to every member whose role is at least
|
|
14
|
+
* `approver_role` except the run's trigger account (as `canHandle`, review focus 2), and only
|
|
15
|
+
* while it is still `pending`; a question only while pending; both, and a connect request, go to
|
|
16
|
+
* the run's trigger account (an approval assigned to someone goes to that person);
|
|
17
|
+
* - `replies`: chat conversations only, to the conversation's owner, never for a run serving a
|
|
18
|
+
* scheduled task (that pushes as `schedules`);
|
|
19
|
+
* - `tasks`: the root conversation's owner;
|
|
20
|
+
* - `schedules`: the task's owner, for a task run `completed` or `failed` of a task not deleted;
|
|
21
|
+
* - eval conversations (a sub-agent under an eval root too) and deleted conversations never push;
|
|
22
|
+
* - an escalated approval whose run is gone pushes nothing (its initiator is unknown).
|
|
23
|
+
*
|
|
24
|
+
* The path carries the org (`/chat/<root>?org=<orgId>`, `&subagent=<child>` for an event of a
|
|
25
|
+
* sub-agent's log; a schedule run without a conversation opens `/inbox?org=<orgId>`), the thread
|
|
26
|
+
* is the root conversation (`schedule-<taskId>` for a schedule), the title the root's agent name
|
|
27
|
+
* (the task's name).
|
|
28
|
+
*/
|
|
29
|
+
export declare function resolveRecipients(db: KernelSchemaDb, source: PushFanoutData["source"]): Promise<ResolvedRecipients | null>;
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
import { ORG_ROLES, roleAtLeast } from "../orgs/roles.js";
|
|
2
|
+
import { rootConversationOf } from "../runtime/subagents/child.js";
|
|
3
|
+
import { pushTriggerOf } from "./triggers.js";
|
|
4
|
+
/**
|
|
5
|
+
* Who an event's push reaches, read when the fanout runs (mobile app spec §9.4, the plan's
|
|
6
|
+
* Triggers table), or null when nothing is pushed. Every check is made now, not when the event was
|
|
7
|
+
* written (review focus 1):
|
|
8
|
+
*
|
|
9
|
+
* - the org is not deleted, and every recipient is an `active` account that is still a member of
|
|
10
|
+
* the event's org (an account of another org never qualifies, whatever a row names);
|
|
11
|
+
* - `waiting`: an approval goes to `requested_for`, else to every member whose role is at least
|
|
12
|
+
* `approver_role` except the run's trigger account (as `canHandle`, review focus 2), and only
|
|
13
|
+
* while it is still `pending`; a question only while pending; both, and a connect request, go to
|
|
14
|
+
* the run's trigger account (an approval assigned to someone goes to that person);
|
|
15
|
+
* - `replies`: chat conversations only, to the conversation's owner, never for a run serving a
|
|
16
|
+
* scheduled task (that pushes as `schedules`);
|
|
17
|
+
* - `tasks`: the root conversation's owner;
|
|
18
|
+
* - `schedules`: the task's owner, for a task run `completed` or `failed` of a task not deleted;
|
|
19
|
+
* - eval conversations (a sub-agent under an eval root too) and deleted conversations never push;
|
|
20
|
+
* - an escalated approval whose run is gone pushes nothing (its initiator is unknown).
|
|
21
|
+
*
|
|
22
|
+
* The path carries the org (`/chat/<root>?org=<orgId>`, `&subagent=<child>` for an event of a
|
|
23
|
+
* sub-agent's log; a schedule run without a conversation opens `/inbox?org=<orgId>`), the thread
|
|
24
|
+
* is the root conversation (`schedule-<taskId>` for a schedule), the title the root's agent name
|
|
25
|
+
* (the task's name).
|
|
26
|
+
*/
|
|
27
|
+
export async function resolveRecipients(db, source) {
|
|
28
|
+
return source.kind === "schedule"
|
|
29
|
+
? resolveSchedule(db, source.taskRunId)
|
|
30
|
+
: resolveConversation(db, source.conversationId, source.seq);
|
|
31
|
+
}
|
|
32
|
+
async function resolveConversation(db, conversationId, seq) {
|
|
33
|
+
const event = await db
|
|
34
|
+
.selectFrom("conversation_events")
|
|
35
|
+
.select(["type", "payload", "run_id"])
|
|
36
|
+
.where("conversation_id", "=", conversationId)
|
|
37
|
+
.where("seq", "=", String(seq))
|
|
38
|
+
.executeTakeFirst();
|
|
39
|
+
if (!event)
|
|
40
|
+
return null;
|
|
41
|
+
const trigger = pushTriggerOf({ type: event.type, payload: event.payload });
|
|
42
|
+
if (trigger === null)
|
|
43
|
+
return null;
|
|
44
|
+
const conv = await db
|
|
45
|
+
.selectFrom("conversations")
|
|
46
|
+
.select(["org_id", "kind", "account_id", "deleted_at"])
|
|
47
|
+
.where("id", "=", conversationId)
|
|
48
|
+
.executeTakeFirst();
|
|
49
|
+
if (!conv || conv.kind === "eval" || conv.deleted_at !== null)
|
|
50
|
+
return null;
|
|
51
|
+
if (trigger.category === "replies" && conv.kind !== "chat")
|
|
52
|
+
return null;
|
|
53
|
+
const orgId = conv.org_id;
|
|
54
|
+
if (!(await orgLive(db, orgId)))
|
|
55
|
+
return null;
|
|
56
|
+
const rootId = conv.kind === "subagent" ? await rootConversationOf(db, conversationId) : conversationId;
|
|
57
|
+
const root = rootId === conversationId
|
|
58
|
+
? null
|
|
59
|
+
: await db
|
|
60
|
+
.selectFrom("conversations")
|
|
61
|
+
.select(["org_id", "kind", "account_id", "deleted_at"])
|
|
62
|
+
.where("id", "=", rootId)
|
|
63
|
+
.executeTakeFirst();
|
|
64
|
+
if (root !== null &&
|
|
65
|
+
(root === undefined ||
|
|
66
|
+
root.org_id !== orgId ||
|
|
67
|
+
root.kind === "eval" ||
|
|
68
|
+
root.deleted_at !== null)) {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
const owner = root?.account_id ?? conv.account_id;
|
|
72
|
+
const payload = event.payload;
|
|
73
|
+
let candidates;
|
|
74
|
+
switch (trigger.text) {
|
|
75
|
+
case "approval": {
|
|
76
|
+
if (typeof payload.approvalId !== "string")
|
|
77
|
+
return null;
|
|
78
|
+
const approval = await db
|
|
79
|
+
.selectFrom("approvals")
|
|
80
|
+
.select(["run_id", "requested_for", "approver_role", "status"])
|
|
81
|
+
.where("id", "=", payload.approvalId)
|
|
82
|
+
.where("org_id", "=", orgId)
|
|
83
|
+
.where("conversation_id", "=", conversationId)
|
|
84
|
+
.executeTakeFirst();
|
|
85
|
+
if (approval?.status !== "pending")
|
|
86
|
+
return null;
|
|
87
|
+
if (approval.requested_for !== null) {
|
|
88
|
+
candidates = [approval.requested_for];
|
|
89
|
+
break;
|
|
90
|
+
}
|
|
91
|
+
const role = approval.approver_role;
|
|
92
|
+
if (role === null || !ORG_ROLES.includes(role))
|
|
93
|
+
return null;
|
|
94
|
+
// without its run the initiator is unknown, and only `canHandle` with it may decide
|
|
95
|
+
const initiator = await triggerAccountOf(db, approval.run_id);
|
|
96
|
+
if (initiator === null)
|
|
97
|
+
return null;
|
|
98
|
+
const roles = ORG_ROLES.filter((r) => roleAtLeast(r, role));
|
|
99
|
+
const rows = await db
|
|
100
|
+
.selectFrom("memberships")
|
|
101
|
+
.select("account_id")
|
|
102
|
+
.where("org_id", "=", orgId)
|
|
103
|
+
.where("role", "in", roles)
|
|
104
|
+
.execute();
|
|
105
|
+
candidates = rows.map((r) => r.account_id).filter((a) => a !== initiator);
|
|
106
|
+
break;
|
|
107
|
+
}
|
|
108
|
+
case "question": {
|
|
109
|
+
if (typeof payload.questionId !== "string")
|
|
110
|
+
return null;
|
|
111
|
+
const question = await db
|
|
112
|
+
.selectFrom("questions")
|
|
113
|
+
.select(["run_id", "status"])
|
|
114
|
+
.where("id", "=", payload.questionId)
|
|
115
|
+
.where("org_id", "=", orgId)
|
|
116
|
+
.where("conversation_id", "=", conversationId)
|
|
117
|
+
.executeTakeFirst();
|
|
118
|
+
if (question?.status !== "pending")
|
|
119
|
+
return null;
|
|
120
|
+
candidates = optional(await triggerAccountOf(db, question.run_id));
|
|
121
|
+
break;
|
|
122
|
+
}
|
|
123
|
+
case "connect":
|
|
124
|
+
candidates = event.run_id === null ? [] : optional(await triggerAccountOf(db, event.run_id));
|
|
125
|
+
break;
|
|
126
|
+
case "runFinished":
|
|
127
|
+
case "runFailed": {
|
|
128
|
+
if (event.run_id === null)
|
|
129
|
+
return null;
|
|
130
|
+
const run = await db
|
|
131
|
+
.selectFrom("runs")
|
|
132
|
+
.select("scheduled_task_run_id")
|
|
133
|
+
.where("id", "=", event.run_id)
|
|
134
|
+
.where("conversation_id", "=", conversationId)
|
|
135
|
+
.executeTakeFirst();
|
|
136
|
+
if (!run || run.scheduled_task_run_id !== null)
|
|
137
|
+
return null;
|
|
138
|
+
candidates = [owner];
|
|
139
|
+
break;
|
|
140
|
+
}
|
|
141
|
+
default:
|
|
142
|
+
candidates = [owner];
|
|
143
|
+
}
|
|
144
|
+
const accountIds = await activeMembers(db, orgId, candidates);
|
|
145
|
+
if (accountIds.length === 0)
|
|
146
|
+
return null;
|
|
147
|
+
const rootRow = await db
|
|
148
|
+
.selectFrom("conversations")
|
|
149
|
+
.select(["agent_id", "title"])
|
|
150
|
+
.where("id", "=", rootId)
|
|
151
|
+
.executeTakeFirstOrThrow();
|
|
152
|
+
const org = encodeURIComponent(orgId);
|
|
153
|
+
const path = rootId === conversationId
|
|
154
|
+
? `/chat/${rootId}?org=${org}`
|
|
155
|
+
: `/chat/${rootId}?org=${org}&subagent=${conversationId}`;
|
|
156
|
+
return {
|
|
157
|
+
orgId,
|
|
158
|
+
accountIds,
|
|
159
|
+
category: trigger.category,
|
|
160
|
+
path,
|
|
161
|
+
threadId: rootId,
|
|
162
|
+
title: await agentName(db, rootRow.agent_id),
|
|
163
|
+
conversationTitle: rootRow.title,
|
|
164
|
+
text: trigger.text,
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
async function resolveSchedule(db, taskRunId) {
|
|
168
|
+
const row = await db
|
|
169
|
+
.selectFrom("scheduled_task_runs")
|
|
170
|
+
.innerJoin("scheduled_tasks", "scheduled_tasks.id", "scheduled_task_runs.task_id")
|
|
171
|
+
.select([
|
|
172
|
+
"scheduled_task_runs.org_id",
|
|
173
|
+
"scheduled_task_runs.status",
|
|
174
|
+
"scheduled_task_runs.conversation_id",
|
|
175
|
+
"scheduled_tasks.id as task_id",
|
|
176
|
+
"scheduled_tasks.org_id as task_org_id",
|
|
177
|
+
"scheduled_tasks.account_id",
|
|
178
|
+
"scheduled_tasks.name",
|
|
179
|
+
])
|
|
180
|
+
.where("scheduled_task_runs.id", "=", taskRunId)
|
|
181
|
+
// a deleted task pushes nothing
|
|
182
|
+
.where("scheduled_tasks.deleted_at", "is", null)
|
|
183
|
+
.executeTakeFirst();
|
|
184
|
+
if (!row || row.org_id !== row.task_org_id)
|
|
185
|
+
return null;
|
|
186
|
+
if (row.status !== "completed" && row.status !== "failed")
|
|
187
|
+
return null;
|
|
188
|
+
const orgId = row.org_id;
|
|
189
|
+
if (!(await orgLive(db, orgId)))
|
|
190
|
+
return null;
|
|
191
|
+
const accountIds = await activeMembers(db, orgId, [row.account_id]);
|
|
192
|
+
if (accountIds.length === 0)
|
|
193
|
+
return null;
|
|
194
|
+
const conv = row.conversation_id === null
|
|
195
|
+
? undefined
|
|
196
|
+
: await db
|
|
197
|
+
.selectFrom("conversations")
|
|
198
|
+
.select(["title"])
|
|
199
|
+
.where("id", "=", row.conversation_id)
|
|
200
|
+
.where("org_id", "=", orgId)
|
|
201
|
+
.where("deleted_at", "is", null)
|
|
202
|
+
.executeTakeFirst();
|
|
203
|
+
const org = encodeURIComponent(orgId);
|
|
204
|
+
return {
|
|
205
|
+
orgId,
|
|
206
|
+
accountIds,
|
|
207
|
+
category: "schedules",
|
|
208
|
+
path: conv === undefined ? `/inbox?org=${org}` : `/chat/${row.conversation_id}?org=${org}`,
|
|
209
|
+
threadId: `schedule-${row.task_id}`,
|
|
210
|
+
title: row.name,
|
|
211
|
+
conversationTitle: conv?.title ?? null,
|
|
212
|
+
text: row.status === "completed" ? "scheduleRan" : "scheduleFailed",
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
const optional = (id) => (id === null ? [] : [id]);
|
|
216
|
+
/** Whether the org exists and is not deleted. */
|
|
217
|
+
async function orgLive(db, orgId) {
|
|
218
|
+
const org = await db
|
|
219
|
+
.selectFrom("orgs")
|
|
220
|
+
.select("id")
|
|
221
|
+
.where("id", "=", orgId)
|
|
222
|
+
.where("deleted_at", "is", null)
|
|
223
|
+
.executeTakeFirst();
|
|
224
|
+
return org !== undefined;
|
|
225
|
+
}
|
|
226
|
+
/** The trigger account of a run, or null when the run is gone. */
|
|
227
|
+
async function triggerAccountOf(db, runId) {
|
|
228
|
+
const run = await db
|
|
229
|
+
.selectFrom("runs")
|
|
230
|
+
.select("trigger_account_id")
|
|
231
|
+
.where("id", "=", runId)
|
|
232
|
+
.executeTakeFirst();
|
|
233
|
+
return run?.trigger_account_id ?? null;
|
|
234
|
+
}
|
|
235
|
+
/** The accounts among `ids` that are active and members of `orgId`, sorted. */
|
|
236
|
+
async function activeMembers(db, orgId, ids) {
|
|
237
|
+
const unique = [...new Set(ids)];
|
|
238
|
+
if (unique.length === 0)
|
|
239
|
+
return [];
|
|
240
|
+
const rows = await db
|
|
241
|
+
.selectFrom("memberships")
|
|
242
|
+
.innerJoin("accounts", "accounts.id", "memberships.account_id")
|
|
243
|
+
.select("accounts.id")
|
|
244
|
+
.where("memberships.org_id", "=", orgId)
|
|
245
|
+
.where("memberships.account_id", "in", unique)
|
|
246
|
+
.where("accounts.status", "=", "active")
|
|
247
|
+
.orderBy("accounts.id")
|
|
248
|
+
.execute();
|
|
249
|
+
return rows.map((r) => r.id);
|
|
250
|
+
}
|
|
251
|
+
/** The agent's name in its current version (empty when it has none). */
|
|
252
|
+
async function agentName(db, agentId) {
|
|
253
|
+
const row = await db
|
|
254
|
+
.selectFrom("agents")
|
|
255
|
+
.innerJoin("agent_versions", (j) => j
|
|
256
|
+
.onRef("agent_versions.agent_id", "=", "agents.id")
|
|
257
|
+
.onRef("agent_versions.version", "=", "agents.current_version"))
|
|
258
|
+
.select("agent_versions.definition")
|
|
259
|
+
.where("agents.id", "=", agentId)
|
|
260
|
+
.executeTakeFirst();
|
|
261
|
+
const name = row?.definition?.name;
|
|
262
|
+
return typeof name === "string" ? name : "";
|
|
263
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { KernelSchemaDb } from "../db/kernel-schema.js";
|
|
2
|
+
/**
|
|
3
|
+
* Deletes the push registrations the given sessions posted (mobile app plan decision 3: a
|
|
4
|
+
* registration follows its session). Session revocation calls it in the transaction that sets
|
|
5
|
+
* `revoked_at`: the foreign key is `ON DELETE SET NULL` and revocation keeps the session row, so
|
|
6
|
+
* nothing else removes them. No person audit entry is written (`session_revoked` is implied by the
|
|
7
|
+
* revocation). Infra dependencies only, so `identity/sessions.ts` imports it without a cycle.
|
|
8
|
+
*/
|
|
9
|
+
export declare function deletePushRegistrationsForSessions(db: KernelSchemaDb, sessionIds: readonly string[]): Promise<number>;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deletes the push registrations the given sessions posted (mobile app plan decision 3: a
|
|
3
|
+
* registration follows its session). Session revocation calls it in the transaction that sets
|
|
4
|
+
* `revoked_at`: the foreign key is `ON DELETE SET NULL` and revocation keeps the session row, so
|
|
5
|
+
* nothing else removes them. No person audit entry is written (`session_revoked` is implied by the
|
|
6
|
+
* revocation). Infra dependencies only, so `identity/sessions.ts` imports it without a cycle.
|
|
7
|
+
*/
|
|
8
|
+
export async function deletePushRegistrationsForSessions(db, sessionIds) {
|
|
9
|
+
if (sessionIds.length === 0)
|
|
10
|
+
return 0;
|
|
11
|
+
const r = await db
|
|
12
|
+
.deleteFrom("push_registrations")
|
|
13
|
+
.where("session_id", "in", [...sessionIds])
|
|
14
|
+
.executeTakeFirst();
|
|
15
|
+
return Number(r.numDeletedRows);
|
|
16
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import { type Selectable } from "kysely";
|
|
2
|
+
import type { PushRegistrationsTable } from "../db/kernel-schema.js";
|
|
3
|
+
import { KernelDb } from "../infra/database/kernel-db.js";
|
|
4
|
+
import { TransactionHost } from "../infra/database/transaction-host.js";
|
|
5
|
+
import { PushProviderHost } from "./provider-host.js";
|
|
6
|
+
import type { PushRegistrationBody, PushRegistrationView } from "./push.schemas.js";
|
|
7
|
+
import { PushTokenStore } from "./token-store.js";
|
|
8
|
+
/** A stored registration, its token still sealed. */
|
|
9
|
+
export type PushRegistrationRow = Selectable<PushRegistrationsTable>;
|
|
10
|
+
/**
|
|
11
|
+
* A person's app installs that receive push (mobile app spec §9.3). A registration belongs to the
|
|
12
|
+
* account, not an org, and follows the session that posted it (plan decision 3). A token posted
|
|
13
|
+
* again, by anyone, updates the one row of `(provider, app_id, token_hash)` and keeps its id, so
|
|
14
|
+
* the sealed token (AAD bound to the id) still opens; a phone that changes hands stops reaching its
|
|
15
|
+
* previous account (decision 5). The token is never logged, audited or answered.
|
|
16
|
+
*/
|
|
17
|
+
export declare class PushRegistrationsService {
|
|
18
|
+
private readonly db;
|
|
19
|
+
readonly txHost: TransactionHost;
|
|
20
|
+
private readonly tokens;
|
|
21
|
+
private readonly providers;
|
|
22
|
+
constructor(db: KernelDb, txHost: TransactionHost, tokens: PushTokenStore, providers: PushProviderHost);
|
|
23
|
+
/**
|
|
24
|
+
* Registers (or refreshes) an install for `accountId` from `sessionId`. A provider that is not
|
|
25
|
+
* loaded or does not cover the app id → 422 `push.provider_unavailable`; a session revoked
|
|
26
|
+
* since the request was authenticated → 401 `auth.session_revoked`. Beyond
|
|
27
|
+
* `PUSH_LIMITS.registrationsPerAccount` the least recently seen of the account are deleted.
|
|
28
|
+
* Audited (`push.registered`) for a new row or a row taken from another account.
|
|
29
|
+
*/
|
|
30
|
+
register(accountId: string, sessionId: string, body: PushRegistrationBody): Promise<{
|
|
31
|
+
id: string;
|
|
32
|
+
}>;
|
|
33
|
+
/** Removes one of the person's registrations; another account's id → 404. Audited. */
|
|
34
|
+
remove(accountId: string, id: string): Promise<void>;
|
|
35
|
+
/** The person's registrations, newest `last_seen_at` first; `current` = posted by `sessionId`. */
|
|
36
|
+
list(accountId: string, sessionId: string): Promise<PushRegistrationView[]>;
|
|
37
|
+
/** The registrations of these accounts, tokens still sealed (the fanout opens them per send). */
|
|
38
|
+
forAccounts(accountIds: readonly string[]): Promise<PushRegistrationRow[]>;
|
|
39
|
+
/**
|
|
40
|
+
* Updates the row of this token in place (keeping its id) or inserts a sealed new one; null
|
|
41
|
+
* when the insert lost a unique conflict to a row that is already gone again.
|
|
42
|
+
*/
|
|
43
|
+
private place;
|
|
44
|
+
private lockExisting;
|
|
45
|
+
/** Points an existing row at the caller and its session; the id and the sealed token stay. */
|
|
46
|
+
private refresh;
|
|
47
|
+
/**
|
|
48
|
+
* Deletes the account's registrations beyond the cap, least recently seen first. Rows locked by
|
|
49
|
+
* another transaction are skipped (`FOR UPDATE SKIP LOCKED`), never waited for: a concurrent
|
|
50
|
+
* revoke of another session deleting its rows would otherwise deadlock with this (40P01). A
|
|
51
|
+
* skipped row is on its way out (a revoke) or to another account (a reassignment), so it does
|
|
52
|
+
* not count toward the 20 kept; the cap stays exact once those commit.
|
|
53
|
+
*/
|
|
54
|
+
private evictBeyondCap;
|
|
55
|
+
}
|