@cosmicdrift/kumiko-samples 0.410.0 → 0.412.0

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 (122) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +31 -1
  3. package/packages/bundled-features/src/agent-tools/agent-doc-lint.ts +64 -3
  4. package/packages/bundled-features/src/agent-tools/agent-manifest.ts +13 -130
  5. package/packages/bundled-features/src/agent-tools/api-docs/anchors.ts +60 -0
  6. package/packages/bundled-features/src/agent-tools/api-docs/check.ts +25 -0
  7. package/packages/bundled-features/src/agent-tools/api-docs/collect-events.ts +140 -0
  8. package/packages/bundled-features/src/agent-tools/api-docs/collect.ts +175 -0
  9. package/packages/bundled-features/src/agent-tools/api-docs/curl.ts +28 -0
  10. package/packages/bundled-features/src/agent-tools/api-docs/error-table.ts +45 -0
  11. package/packages/bundled-features/src/agent-tools/api-docs/examples.ts +43 -0
  12. package/packages/bundled-features/src/agent-tools/api-docs/generate.ts +179 -0
  13. package/packages/bundled-features/src/agent-tools/api-docs/index-json.ts +29 -0
  14. package/packages/bundled-features/src/agent-tools/api-docs/index.ts +21 -0
  15. package/packages/bundled-features/src/agent-tools/api-docs/list-parameters.ts +38 -0
  16. package/packages/bundled-features/src/agent-tools/api-docs/markdown.ts +70 -0
  17. package/packages/bundled-features/src/agent-tools/api-docs/menu-path.ts +82 -0
  18. package/packages/bundled-features/src/agent-tools/api-docs/model.ts +83 -0
  19. package/packages/bundled-features/src/agent-tools/api-docs/problems.ts +58 -0
  20. package/packages/bundled-features/src/agent-tools/api-docs/render-events.ts +76 -0
  21. package/packages/bundled-features/src/agent-tools/api-docs/render-openapi.ts +216 -0
  22. package/packages/bundled-features/src/agent-tools/api-docs/render-overview.ts +86 -0
  23. package/packages/bundled-features/src/agent-tools/api-docs/render-reference.ts +79 -0
  24. package/packages/bundled-features/src/agent-tools/api-docs/render-tokens.ts +136 -0
  25. package/packages/bundled-features/src/agent-tools/api-docs/schema-fields.ts +167 -0
  26. package/packages/bundled-features/src/agent-tools/api-docs/section-ids.ts +28 -0
  27. package/packages/bundled-features/src/agent-tools/api-docs/system-only.ts +11 -0
  28. package/packages/bundled-features/src/agent-tools/api-docs/texts/de.ts +166 -0
  29. package/packages/bundled-features/src/agent-tools/api-docs/texts/en.ts +159 -0
  30. package/packages/bundled-features/src/agent-tools/api-docs/texts/es.ts +162 -0
  31. package/packages/bundled-features/src/agent-tools/api-docs/texts/fr.ts +169 -0
  32. package/packages/bundled-features/src/agent-tools/api-docs/texts/index.ts +67 -0
  33. package/packages/bundled-features/src/agent-tools/api-docs/texts/it.ts +165 -0
  34. package/packages/bundled-features/src/agent-tools/api-docs/texts/types.ts +130 -0
  35. package/packages/bundled-features/src/agent-tools/api-docs/ui-writes.ts +81 -0
  36. package/packages/bundled-features/src/agent-tools/changes.json +24 -0
  37. package/packages/bundled-features/src/agent-tools/handler-schema.ts +45 -0
  38. package/packages/bundled-features/src/agent-tools/index.ts +24 -0
  39. package/packages/bundled-features/src/agent-tools/labels.ts +181 -0
  40. package/packages/bundled-features/src/auth-email-password/changes.json +24 -0
  41. package/packages/bundled-features/src/auth-email-password/seeding.ts +84 -6
  42. package/packages/bundled-features/src/auth-email-password/web/i18n.ts +1 -0
  43. package/packages/bundled-features/src/auth-email-password/web/signup-screen.tsx +48 -3
  44. package/packages/bundled-features/src/auth-email-password/web/static-account.ts +190 -0
  45. package/packages/bundled-features/src/auth-email-password/web/static-client.ts +226 -0
  46. package/packages/bundled-features/src/foundation-shared/demo-admin-env.ts +11 -0
  47. package/packages/bundled-features/src/foundation-shared/index.ts +5 -1
  48. package/packages/bundled-features/src/inbound-mail-foundation/changes.json +6 -0
  49. package/packages/bundled-features/src/inbound-mail-foundation/entities.ts +99 -71
  50. package/packages/bundled-features/src/inbound-mail-foundation/feature.ts +2 -2
  51. package/packages/bundled-features/src/inbound-provider-imap/changes.json +6 -0
  52. package/packages/bundled-features/src/inbound-provider-imap/imap-client.ts +3 -1
  53. package/packages/bundled-features/src/personal-access-tokens/changes.json +6 -0
  54. package/packages/bundled-features/src/personal-access-tokens/feature.ts +5 -2
  55. package/packages/bundled-features/src/personal-access-tokens/handlers/create.write.ts +7 -2
  56. package/packages/bundled-features/src/personal-access-tokens/i18n.ts +6 -1
  57. package/packages/bundled-features/src/personal-access-tokens/index.ts +37 -2
  58. package/packages/bundled-features/src/personal-access-tokens/scope-events-check.ts +28 -0
  59. package/packages/bundled-features/src/personal-access-tokens/screens.ts +9 -1
  60. package/packages/bundled-features/src/personal-access-tokens/web/constants.ts +1 -0
  61. package/packages/bundled-features/src/personal-access-tokens/web/scopes.ts +14 -0
  62. package/packages/bundled-features/src/presence/changes.json +8 -0
  63. package/packages/bundled-features/src/presence/feature.ts +25 -0
  64. package/packages/bundled-features/src/presence/handlers/heartbeat.write.ts +52 -0
  65. package/packages/bundled-features/src/presence/handlers/leave.write.ts +41 -0
  66. package/packages/bundled-features/src/presence/handlers/list.query.ts +39 -0
  67. package/packages/bundled-features/src/presence/index.ts +7 -0
  68. package/packages/bundled-features/src/presence/options.ts +30 -0
  69. package/packages/bundled-features/src/presence/payloads.ts +26 -0
  70. package/packages/bundled-features/src/presence/room.ts +65 -0
  71. package/packages/bundled-features/src/presence/store.ts +185 -0
  72. package/packages/bundled-features/src/sessions/feature.ts +6 -2
  73. package/packages/bundled-features/src/sessions/handlers/last-activity-probe.route.ts +19 -0
  74. package/packages/bundled-features/src/tenant-inactivity/changes.json +12 -0
  75. package/packages/bundled-features/src/tenant-inactivity/check-inactive-tenants.ts +14 -6
  76. package/packages/bundled-features/src/tenant-inactivity/constants.ts +4 -1
  77. package/packages/bundled-features/src/tenant-inactivity/handlers/inactivity-state.query.ts +2 -1
  78. package/packages/bundled-features/src/tenant-inactivity/handlers/keep-account.write.ts +2 -1
  79. package/packages/bundled-features/src/tenant-inactivity/options.ts +1 -0
  80. package/packages/bundled-features/src/tenant-inactivity/remote-activity.ts +6 -1
  81. package/packages/bundled-features/src/tenant-inactivity/static-keep-account.ts +37 -0
  82. package/packages/bundled-features/src/tenant-lifecycle/constants.ts +2 -0
  83. package/packages/bundled-features/src/tenant-lifecycle/handlers/cancel-destruction.write.ts +6 -2
  84. package/packages/bundled-features/src/tenant-lifecycle/handlers/request-destruction.write.ts +2 -1
  85. package/packages/bundled-features/src/tenant-lifecycle/index.ts +1 -0
  86. package/packages/bundled-features/src/waitlist/changes.json +6 -0
  87. package/packages/bundled-features/src/waitlist/static-submit.ts +56 -0
  88. package/samples/apps/styleguide/src/features/widgets/i18n.ts +143 -0
  89. package/samples/apps/styleguide/src/features/widgets/web/VariantsDemo.tsx +276 -0
  90. package/samples/apps/styleguide/src/features/widgets/web/Widgets.tsx +3 -0
  91. package/samples/apps/styleguide/src/features/workboard/feature.ts +1 -0
  92. package/samples/apps/use-all-bundled/feature-manifest.json +23 -1
  93. package/samples/apps/use-all-bundled/src/run-config.ts +3 -0
  94. package/samples/recipes/api-docs/README.md +52 -0
  95. package/samples/recipes/api-docs/api-docs/de/events.md +62 -0
  96. package/samples/recipes/api-docs/api-docs/de/overview.md +100 -0
  97. package/samples/recipes/api-docs/api-docs/de/reference/tickets.md +305 -0
  98. package/samples/recipes/api-docs/api-docs/de/tokens.md +66 -0
  99. package/samples/recipes/api-docs/api-docs/en/events.md +62 -0
  100. package/samples/recipes/api-docs/api-docs/en/overview.md +100 -0
  101. package/samples/recipes/api-docs/api-docs/en/reference/tickets.md +305 -0
  102. package/samples/recipes/api-docs/api-docs/en/tokens.md +66 -0
  103. package/samples/recipes/api-docs/api-docs/index.json +371 -0
  104. package/samples/recipes/api-docs/api-docs/openapi.json +982 -0
  105. package/samples/recipes/api-docs/api-examples/ticket-close.json +21 -0
  106. package/samples/recipes/api-docs/api-examples/ticket-create.json +42 -0
  107. package/samples/recipes/api-docs/api-examples/ticket-detail.json +28 -0
  108. package/samples/recipes/api-docs/api-examples/ticket-list.json +31 -0
  109. package/samples/recipes/api-docs/api-examples/ticket-update.json +54 -0
  110. package/samples/recipes/api-docs/api-examples/webhooks/ticket-closed.json +8 -0
  111. package/samples/recipes/api-docs/api-examples/webhooks/ticket-created.json +10 -0
  112. package/samples/recipes/api-docs/kumiko.config.ts +33 -0
  113. package/samples/recipes/api-docs/package.json +14 -0
  114. package/samples/recipes/api-docs/src/feature.ts +218 -0
  115. package/samples/recipes/api-docs/tsconfig.json +22 -0
  116. package/samples/recipes/realtime-sse/README.md +1 -0
  117. package/samples/recipes/realtime-sse/package.json +1 -0
  118. package/samples/recipes/realtime-sse/src/feature.ts +9 -0
  119. package/samples/recipes/record-detail-layout/README.md +1 -0
  120. package/samples/recipes/record-detail-layout/src/feature.ts +10 -0
  121. package/samples/recipes/wizard-form/README.md +9 -0
  122. package/samples/recipes/wizard-form/src/feature.ts +13 -2
@@ -1,5 +1,6 @@
1
1
  import type { FeatureDefinition } from "@cosmicdrift/kumiko-framework/engine";
2
2
  import { PAT_DEFAULT_RATE_LIMIT, type PatRateLimit } from "./web/constants.ts";
3
+ import type { PatScopeConfig, PatScopeDef } from "./web/scopes.ts";
3
4
 
4
5
  export type { BindPatAutoRevokeOnPasswordChange, PersonalAccessTokensOptions } from "./feature.ts";
5
6
  export {
@@ -20,9 +21,43 @@ export { createPatResolver } from "./resolver.ts";
20
21
  export { revokeAllPatTokensForUser } from "./revoke-for-user.ts";
21
22
  export { apiTokenEntity, apiTokenTable } from "./schema/api-token.ts";
22
23
  export type { PatRateLimit } from "./web/constants.ts";
23
- export { PAT_DEFAULT_RATE_LIMIT, PAT_FEATURE, PatHandlers, PatQueries } from "./web/constants.ts";
24
+ export {
25
+ PAT_DEFAULT_EXPIRES_IN_DAYS,
26
+ PAT_DEFAULT_RATE_LIMIT,
27
+ PAT_FEATURE,
28
+ PAT_MAX_EXPIRES_IN_DAYS,
29
+ PAT_SCREEN_ID,
30
+ PatHandlers,
31
+ PatQueries,
32
+ } from "./web/constants.ts";
24
33
  export type { PatScopeConfig, PatScopeDef } from "./web/scopes.ts";
25
- export { expandScopes } from "./web/scopes.ts";
34
+ export { expandScopeEvents, expandScopes } from "./web/scopes.ts";
35
+
36
+ function isStringArray(value: unknown): value is readonly string[] {
37
+ return Array.isArray(value) && value.every((entry) => typeof entry === "string");
38
+ }
39
+
40
+ function isPatScopeDef(value: unknown): value is PatScopeDef {
41
+ if (!value || typeof value !== "object") return false;
42
+ if (!("label" in value) || typeof value.label !== "string") return false;
43
+ if (!("read" in value) || !isStringArray(value.read)) return false;
44
+ if ("write" in value && value.write !== undefined && !isStringArray(value.write)) return false;
45
+ return !("events" in value) || value.events === undefined || isStringArray(value.events);
46
+ }
47
+
48
+ function isPatScopeConfig(value: unknown): value is PatScopeConfig {
49
+ return !!value && typeof value === "object" && Object.values(value).every(isPatScopeDef);
50
+ }
51
+
52
+ // Reads the scope catalog off a mounted PAT feature's exports; undefined for any other feature.
53
+ export function patScopesFromFeature(feature: FeatureDefinition): PatScopeConfig | undefined {
54
+ const exports = feature.exports;
55
+ if (exports && typeof exports === "object" && "scopes" in exports) {
56
+ const { scopes } = exports;
57
+ if (isPatScopeConfig(scopes)) return scopes;
58
+ }
59
+ return undefined;
60
+ }
26
61
 
27
62
  // Reads the per-token rate-limit config off a mounted PAT feature's exports.
28
63
  // Falls back to the default when absent. run-prod-app uses this to build the
@@ -0,0 +1,28 @@
1
+ import {
2
+ createWebhookContractResolver,
3
+ type FeatureDefinition,
4
+ } from "@cosmicdrift/kumiko-framework/engine";
5
+ import { PAT_FEATURE } from "./web/constants.ts";
6
+ import type { PatScopeConfig } from "./web/scopes.ts";
7
+
8
+ function entityNameOf(qualifiedName: string): string {
9
+ const dot = qualifiedName.lastIndexOf(".");
10
+ return dot > 0 ? qualifiedName.slice(0, dot) : qualifiedName;
11
+ }
12
+
13
+ export function validateScopeEventContracts(
14
+ scopes: PatScopeConfig,
15
+ features: readonly FeatureDefinition[],
16
+ ): void {
17
+ const resolver = createWebhookContractResolver(features);
18
+ for (const [domain, def] of Object.entries(scopes)) {
19
+ for (const qn of def.events ?? []) {
20
+ if (resolver.get(qn)) continue;
21
+ throw new Error(
22
+ `[${PAT_FEATURE}] scope "${domain}" lists event "${qn}" without a public contract. ` +
23
+ "Declare it with r.defineWebhookEvent(...), or set webhookEvents: true on the entity to release its <entity>.created/.updated/.deleted events " +
24
+ `(entity "${entityNameOf(qn)}" has no such opt-in); internal r.defineEvent events are never released.`,
25
+ );
26
+ }
27
+ }
28
+ }
@@ -7,7 +7,9 @@ import {
7
7
  import { ACTION_FORM_ENTITY } from "@cosmicdrift/kumiko-framework/ui-types";
8
8
  import { fieldOptionLabelKeyPrefix } from "@cosmicdrift/kumiko-renderer/headless";
9
9
  import {
10
+ PAT_DEFAULT_EXPIRES_IN_DAYS,
10
11
  PAT_FEATURE,
12
+ PAT_MAX_EXPIRES_IN_DAYS,
11
13
  PAT_MINT_SCREEN_ID,
12
14
  PAT_SCREEN_ID,
13
15
  PatHandlers,
@@ -136,7 +138,13 @@ export function createPatMintScreen(scopes: PatScopeConfig): SecretMintScreenDef
136
138
  display: "checkboxes",
137
139
  options: patGrantOptions(scopes),
138
140
  },
139
- expiresInDays: { type: "number", integer: true, min: 1, max: 3650, default: 90 },
141
+ expiresInDays: {
142
+ type: "number",
143
+ integer: true,
144
+ min: 1,
145
+ max: PAT_MAX_EXPIRES_IN_DAYS,
146
+ default: PAT_DEFAULT_EXPIRES_IN_DAYS,
147
+ },
140
148
  currentPassword: { type: "text", required: true, format: "password", sensitive: true },
141
149
  mfaCode: { type: "text" },
142
150
  },
@@ -15,6 +15,7 @@ export const PatErrors = {
15
15
  // default is a standing-credential risk; the existing 3650-day cap still
16
16
  // lets callers who genuinely want a long-lived token pass it explicitly.
17
17
  export const PAT_DEFAULT_EXPIRES_IN_DAYS = 90;
18
+ export const PAT_MAX_EXPIRES_IN_DAYS = 3650;
18
19
 
19
20
  // Declarative projectionList screen id — the caller's own tokens, revoke as a
20
21
  // row action. The app places it via r.nav.
@@ -10,6 +10,9 @@ export type PatScopeDef = {
10
10
  readonly read: readonly string[];
11
11
  // Omit for a read-only domain — the UI then offers only "no access" / "read".
12
12
  readonly write?: readonly string[];
13
+ // Exact webhook event QNs (no globs): a subscriber must know exactly what it gets. Every entry
14
+ // needs a public contract (r.defineWebhookEvent or an entity event); the boot check enforces it.
15
+ readonly events?: readonly string[];
13
16
  };
14
17
 
15
18
  export type PatScopeConfig = Readonly<Record<string, PatScopeDef>>;
@@ -24,6 +27,17 @@ export function parseGrant(grant: string): { domain: string; level: string } | n
24
27
  return { domain: grant.slice(0, idx), level: grant.slice(idx + 1) };
25
28
  }
26
29
 
30
+ // Union of the webhook events of every granted domain; read level already suffices to subscribe.
31
+ export function expandScopeEvents(config: PatScopeConfig, granted: readonly string[]): string[] {
32
+ const out = new Set<string>();
33
+ for (const grant of granted) {
34
+ const parsed = parseGrant(grant);
35
+ if (!parsed) continue;
36
+ for (const qn of config[parsed.domain]?.events ?? []) out.add(qn);
37
+ }
38
+ return [...out];
39
+ }
40
+
27
41
  // Expand granted "<domain>:<level>" entries into the union of QN globs: read
28
42
  // always grants the read QNs; write additionally grants the write QNs. Unknown
29
43
  // domains contribute nothing (fail-closed — a scope dropped from config after a
@@ -0,0 +1,8 @@
1
+ [
2
+ {
3
+ "version": "0.411.0",
4
+ "type": "improvement",
5
+ "title": "New bundled feature presence: who else is on this record right now",
6
+ "detail": "`createPresenceFeature({ entities, roles?, ttlSeconds? })` lets a browser announce that the user is viewing or editing one row of an allow-listed entity (`presence:write:heartbeat` every 15 seconds, `presence:write:leave` on close) and answers with the other people on it; `presence:query:list` returns them for up to 100 rows of a list. It only informs and never locks. State is ephemeral in a Redis hash per session tenant, entity and row (in memory without Redis), holds user ids only and expires after `ttlSeconds` (default 45) without a heartbeat; display names are resolved per response. A caller sees presence only for rows they can read; other rows answer 404. Defaults to TenantAdmin and TenantMember, entities default to none, the handlers are hidden from the AI agent. A Redis or SSE outage logs a warning and answers with an empty room. On a change the other people on the row get an addressed live signal through the new handler service `ctx.services.userLiveSignals`, which pushes SSE frames to named users of the caller's own tenant. The renderer hooks `usePresence` and `usePresenceList` and the widgets `PresenceNotice` and `PresenceAvatars` stay silent when the feature is not mounted."
7
+ }
8
+ ]
@@ -0,0 +1,25 @@
1
+ import { defineFeature, type FeatureDefinition } from "@cosmicdrift/kumiko-framework/engine";
2
+ import { PRESENCE_FEATURE } from "@cosmicdrift/kumiko-types/presence-types";
3
+ import { createHeartbeatHandler } from "./handlers/heartbeat.write.ts";
4
+ import { createLeaveHandler } from "./handlers/leave.write.ts";
5
+ import { createListQuery } from "./handlers/list.query.ts";
6
+ import { type PresenceOptions, resolvePresenceSettings } from "./options.ts";
7
+ import type { PresenceRuntime } from "./room.ts";
8
+ import { createMemoryPresenceStore } from "./store.ts";
9
+
10
+ export function createPresenceFeature(options: PresenceOptions = {}): FeatureDefinition {
11
+ const settings = resolvePresenceSettings(options);
12
+ // Without Redis the room lives in this process only, which is right for a single instance.
13
+ const runtime: PresenceRuntime = { settings, memoryStore: createMemoryPresenceStore() };
14
+ const access = { roles: settings.roles };
15
+
16
+ return defineFeature(PRESENCE_FEATURE, (r) => {
17
+ r.describe(
18
+ 'Who else is on this record right now: a browser sends a heartbeat every 15 seconds for one row of an allow-listed entity and gets the other viewers and editors back, with a live signal to them on a change. State is ephemeral (Redis hash per tenant, entity and row, in-memory without Redis), keyed by the session tenant, expires after ttlSeconds without a heartbeat and holds user ids only; display names are looked up per response. A caller sees presence only for rows visible to them. Mount with createPresenceFeature({ entities: ["task"] }).',
19
+ );
20
+ r.uiHints({ displayLabel: "Presence", category: "communication", recommended: false });
21
+ r.writeHandler(createHeartbeatHandler(runtime, access));
22
+ r.writeHandler(createLeaveHandler(runtime, access));
23
+ r.queryHandler(createListQuery(runtime, access));
24
+ });
25
+ }
@@ -0,0 +1,52 @@
1
+ import { type AccessRule, defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
2
+ import { NotFoundError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
3
+ import {
4
+ PRESENCE_CHANGED_EVENT,
5
+ type PresenceHeartbeatResult,
6
+ } from "@cosmicdrift/kumiko-types/presence-types";
7
+ import { HeartbeatSchema } from "../payloads.ts";
8
+ import {
9
+ canUseRoom,
10
+ othersOf,
11
+ type PresenceRuntime,
12
+ roomKey,
13
+ storeFor,
14
+ toEntries,
15
+ } from "../room.ts";
16
+
17
+ export function createHeartbeatHandler(runtime: PresenceRuntime, access: AccessRule) {
18
+ return defineWriteHandler<"heartbeat", typeof HeartbeatSchema, PresenceHeartbeatResult>({
19
+ name: "heartbeat",
20
+ schema: HeartbeatSchema,
21
+ access,
22
+ agent: { expose: false },
23
+ // Presence lives in Redis or memory, never Postgres: no transaction per 15 s heartbeat.
24
+ transaction: "perCommand",
25
+ description:
26
+ "Announces that the caller is looking at or editing one row and answers with the other people currently on it; the browser sends it every 15 seconds while a record is open.",
27
+ handler: async (event, ctx) => {
28
+ const { entity, id, activity, focus } = event.payload;
29
+ if (!(await canUseRoom(runtime, ctx, entity, id))) {
30
+ return writeFailure(new NotFoundError(entity, id));
31
+ }
32
+ const store = storeFor(runtime, ctx);
33
+ const key = roomKey(ctx, entity, id);
34
+ const nowMs = ctx.tz.now().epochMilliseconds;
35
+ const { changed } = await store.touch(
36
+ key,
37
+ event.user.id,
38
+ { activity, ...(focus !== undefined && { focus }) },
39
+ nowMs,
40
+ runtime.settings.ttlMs,
41
+ );
42
+ const others = othersOf(await store.list(key, nowMs, runtime.settings.ttlMs), event.user.id);
43
+ if (changed && others.length > 0) {
44
+ await ctx.services.userLiveSignals?.push(
45
+ others.map((record) => record.userId),
46
+ { type: PRESENCE_CHANGED_EVENT, entity, id },
47
+ );
48
+ }
49
+ return { isSuccess: true, data: { others: await toEntries(ctx, others) } };
50
+ },
51
+ });
52
+ }
@@ -0,0 +1,41 @@
1
+ import { type AccessRule, defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
2
+ import { NotFoundError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
3
+ import { PRESENCE_CHANGED_EVENT } from "@cosmicdrift/kumiko-types/presence-types";
4
+ import { LeaveSchema } from "../payloads.ts";
5
+ import { canUseRoom, othersOf, type PresenceRuntime, roomKey, storeFor } from "../room.ts";
6
+
7
+ export function createLeaveHandler(runtime: PresenceRuntime, access: AccessRule) {
8
+ return defineWriteHandler<"leave", typeof LeaveSchema, { readonly left: boolean }>({
9
+ name: "leave",
10
+ schema: LeaveSchema,
11
+ access,
12
+ agent: { expose: false },
13
+ // Presence lives in Redis or memory, never Postgres: no transaction per 15 s heartbeat.
14
+ transaction: "perCommand",
15
+ description:
16
+ "Removes the caller from one row's presence list right away, so others do not wait for the entry to expire; the browser sends it when a record is closed.",
17
+ handler: async (event, ctx) => {
18
+ const { entity, id } = event.payload;
19
+ if (!(await canUseRoom(runtime, ctx, entity, id))) {
20
+ return writeFailure(new NotFoundError(entity, id));
21
+ }
22
+ const store = storeFor(runtime, ctx);
23
+ const key = roomKey(ctx, entity, id);
24
+ const { existed } = await store.remove(key, event.user.id);
25
+ if (existed) {
26
+ const nowMs = ctx.tz.now().epochMilliseconds;
27
+ const others = othersOf(
28
+ await store.list(key, nowMs, runtime.settings.ttlMs),
29
+ event.user.id,
30
+ );
31
+ if (others.length > 0) {
32
+ await ctx.services.userLiveSignals?.push(
33
+ others.map((record) => record.userId),
34
+ { type: PRESENCE_CHANGED_EVENT, entity, id },
35
+ );
36
+ }
37
+ }
38
+ return { isSuccess: true, data: { left: existed } };
39
+ },
40
+ });
41
+ }
@@ -0,0 +1,39 @@
1
+ import { type AccessRule, defineQueryHandler } from "@cosmicdrift/kumiko-framework/engine";
2
+ import type { PresenceEntry, PresenceListResult } from "@cosmicdrift/kumiko-types/presence-types";
3
+ import { ListSchema } from "../payloads.ts";
4
+ import {
5
+ canUseRoom,
6
+ othersOf,
7
+ type PresenceRuntime,
8
+ roomKey,
9
+ storeFor,
10
+ toEntries,
11
+ } from "../room.ts";
12
+
13
+ export function createListQuery(runtime: PresenceRuntime, access: AccessRule) {
14
+ return defineQueryHandler({
15
+ name: "list",
16
+ schema: ListSchema,
17
+ access,
18
+ agent: { expose: false },
19
+ description:
20
+ "Lists the other people currently on each of up to 100 rows of one entity, for badges in a list; rows the caller cannot see are left out without a hint.",
21
+ handler: async (event, ctx): Promise<PresenceListResult> => {
22
+ const { entity, ids } = event.payload;
23
+ if (!runtime.settings.entities.has(entity)) return { byId: {} };
24
+ const store = storeFor(runtime, ctx);
25
+ const nowMs = ctx.tz.now().epochMilliseconds;
26
+ const byId: Record<string, readonly PresenceEntry[]> = {};
27
+ for (const id of new Set(ids)) {
28
+ const others = othersOf(
29
+ await store.list(roomKey(ctx, entity, id), nowMs, runtime.settings.ttlMs),
30
+ event.user.id,
31
+ );
32
+ // Visibility is checked only where someone is present, so an empty row costs no lookup.
33
+ if (others.length === 0 || !(await canUseRoom(runtime, ctx, entity, id))) continue;
34
+ byId[id] = await toEntries(ctx, others);
35
+ }
36
+ return { byId };
37
+ },
38
+ });
39
+ }
@@ -0,0 +1,7 @@
1
+ export { createPresenceFeature } from "./feature.ts";
2
+ export type { PresenceOptions } from "./options.ts";
3
+ export {
4
+ createMemoryPresenceStore,
5
+ createRedisPresenceStore,
6
+ type PresenceStore,
7
+ } from "./store.ts";
@@ -0,0 +1,30 @@
1
+ export const PRESENCE_DEFAULT_ROLES: readonly string[] = ["TenantAdmin", "TenantMember"];
2
+ export const PRESENCE_DEFAULT_TTL_SECONDS = 45;
3
+
4
+ export type PresenceOptions = {
5
+ /** Entities whose rows may carry presence. Default none: a heartbeat for an entity that is not
6
+ * listed is rejected. */
7
+ readonly entities?: readonly string[];
8
+ /** Roles allowed to send heartbeats and read presence. Default TenantAdmin and TenantMember. */
9
+ readonly roles?: readonly string[];
10
+ /** Seconds a user stays listed without a heartbeat. Default 45 (three missed 15 s beats). */
11
+ readonly ttlSeconds?: number;
12
+ };
13
+
14
+ export type PresenceSettings = {
15
+ readonly entities: ReadonlySet<string>;
16
+ readonly roles: readonly string[];
17
+ readonly ttlMs: number;
18
+ };
19
+
20
+ export function resolvePresenceSettings(options: PresenceOptions): PresenceSettings {
21
+ const ttlSeconds = options.ttlSeconds ?? PRESENCE_DEFAULT_TTL_SECONDS;
22
+ if (!Number.isFinite(ttlSeconds) || ttlSeconds <= 0) {
23
+ throw new Error(`presence: ttlSeconds must be a positive number, got ${ttlSeconds}`);
24
+ }
25
+ return {
26
+ entities: new Set(options.entities ?? []),
27
+ roles: options.roles ?? PRESENCE_DEFAULT_ROLES,
28
+ ttlMs: ttlSeconds * 1000,
29
+ };
30
+ }
@@ -0,0 +1,26 @@
1
+ import {
2
+ PRESENCE_FOCUS_MAX_LENGTH,
3
+ PRESENCE_LIST_MAX_IDS,
4
+ } from "@cosmicdrift/kumiko-types/presence-types";
5
+ import * as z from "zod";
6
+
7
+ const ENTITY_NAME_MAX = 64;
8
+ const ROW_ID_MAX = 64;
9
+ const FOCUS_PATTERN = /^[\w:.-]+$/;
10
+
11
+ const entity = z.string().min(1).max(ENTITY_NAME_MAX);
12
+ const rowId = z.string().min(1).max(ROW_ID_MAX);
13
+
14
+ export const HeartbeatSchema = z.object({
15
+ entity,
16
+ id: rowId,
17
+ activity: z.enum(["viewing", "editing"]),
18
+ focus: z.string().max(PRESENCE_FOCUS_MAX_LENGTH).regex(FOCUS_PATTERN).optional(),
19
+ });
20
+
21
+ export const LeaveSchema = z.object({ entity, id: rowId });
22
+
23
+ export const ListSchema = z.object({
24
+ entity,
25
+ ids: z.array(rowId).min(1).max(PRESENCE_LIST_MAX_IDS),
26
+ });
@@ -0,0 +1,65 @@
1
+ import type { HandlerContext } from "@cosmicdrift/kumiko-framework/engine";
2
+ import type { PresenceEntry } from "@cosmicdrift/kumiko-types/presence-types";
3
+ import { parentRowIsVisible } from "../shared/index.ts";
4
+ import { resolveUserDisplayNames, USER_FEATURE } from "../user/index.ts";
5
+ import type { PresenceSettings } from "./options.ts";
6
+ import {
7
+ createRedisPresenceStore,
8
+ type PresenceRecord,
9
+ type PresenceStore,
10
+ presenceKey,
11
+ } from "./store.ts";
12
+
13
+ export type PresenceRuntime = {
14
+ readonly settings: PresenceSettings;
15
+ readonly memoryStore: PresenceStore;
16
+ };
17
+
18
+ export function storeFor(runtime: PresenceRuntime, ctx: HandlerContext): PresenceStore {
19
+ const redis = ctx.services.redis;
20
+ return redis ? createRedisPresenceStore(redis, ctx.obs.log) : runtime.memoryStore;
21
+ }
22
+
23
+ export function roomKey(ctx: HandlerContext, entity: string, id: string): string {
24
+ return presenceKey(ctx.user.tenantId, entity, id);
25
+ }
26
+
27
+ // Not-allowed and not-visible are indistinguishable to the caller, so the endpoint is no
28
+ // existence oracle for rows or entity names.
29
+ export async function canUseRoom(
30
+ runtime: PresenceRuntime,
31
+ ctx: HandlerContext,
32
+ entity: string,
33
+ id: string,
34
+ ): Promise<boolean> {
35
+ if (!runtime.settings.entities.has(entity)) return false;
36
+ return parentRowIsVisible(ctx.registry, entity, id, ctx.user, ctx.db);
37
+ }
38
+
39
+ export function othersOf(
40
+ records: readonly PresenceRecord[],
41
+ userId: string,
42
+ ): readonly PresenceRecord[] {
43
+ return records.filter((record) => record.userId !== userId);
44
+ }
45
+
46
+ // Names are looked up per response and never stored, so an erased user leaves no name behind.
47
+ export async function toEntries(
48
+ ctx: HandlerContext,
49
+ records: readonly PresenceRecord[],
50
+ ): Promise<readonly PresenceEntry[]> {
51
+ if (records.length === 0) return [];
52
+ const names = ctx.registry.getFeature(USER_FEATURE)
53
+ ? await resolveUserDisplayNames(
54
+ ctx.db,
55
+ records.map((record) => record.userId),
56
+ )
57
+ : new Map<string, string>();
58
+ return records.map((record) => ({
59
+ userId: record.userId,
60
+ displayName: names.get(record.userId) ?? record.userId,
61
+ activity: record.activity,
62
+ ...(record.focus !== undefined && { focus: record.focus }),
63
+ since: Temporal.Instant.fromEpochMilliseconds(record.since).toString(),
64
+ }));
65
+ }
@@ -0,0 +1,185 @@
1
+ import type { Logger } from "@cosmicdrift/kumiko-framework/logging";
2
+ import type { PresenceActivity } from "@cosmicdrift/kumiko-types/presence-types";
3
+ import type { Redis } from "ioredis";
4
+ import * as z from "zod";
5
+
6
+ export type PresenceRecord = {
7
+ readonly userId: string;
8
+ readonly activity: PresenceActivity;
9
+ readonly focus?: string;
10
+ readonly since: number;
11
+ readonly seenAt: number;
12
+ };
13
+
14
+ export type PresenceState = {
15
+ readonly activity: PresenceActivity;
16
+ readonly focus?: string;
17
+ };
18
+
19
+ // Presence is ephemeral and best-effort: implementations must never throw, a store that
20
+ // cannot answer behaves like an empty room.
21
+ export type PresenceStore = {
22
+ /** `changed` is true for a new entry or a changed activity/focus, false for a plain keep-alive. */
23
+ touch(
24
+ key: string,
25
+ userId: string,
26
+ state: PresenceState,
27
+ nowMs: number,
28
+ ttlMs: number,
29
+ ): Promise<{ readonly changed: boolean }>;
30
+ remove(key: string, userId: string): Promise<{ readonly existed: boolean }>;
31
+ /** Live entries only; expired ones are dropped on read. */
32
+ list(key: string, nowMs: number, ttlMs: number): Promise<readonly PresenceRecord[]>;
33
+ };
34
+
35
+ export function presenceKey(tenantId: string, entity: string, id: string): string {
36
+ return `presence:${tenantId}:${entity}:${id}`;
37
+ }
38
+
39
+ function isExpired(record: PresenceRecord, nowMs: number, ttlMs: number): boolean {
40
+ return record.seenAt + ttlMs < nowMs;
41
+ }
42
+
43
+ function sameState(record: PresenceRecord, state: PresenceState): boolean {
44
+ return record.activity === state.activity && record.focus === state.focus;
45
+ }
46
+
47
+ function nextRecord(
48
+ userId: string,
49
+ state: PresenceState,
50
+ previous: PresenceRecord | undefined,
51
+ nowMs: number,
52
+ ): PresenceRecord {
53
+ const unchanged = previous !== undefined && sameState(previous, state);
54
+ return {
55
+ userId,
56
+ activity: state.activity,
57
+ ...(state.focus !== undefined && { focus: state.focus }),
58
+ since: unchanged ? previous.since : nowMs,
59
+ seenAt: nowMs,
60
+ };
61
+ }
62
+
63
+ export type MemoryPresenceStore = PresenceStore & {
64
+ /** Rooms currently held, expired or not; lets tests observe the sweep. */
65
+ roomCount(): number;
66
+ };
67
+
68
+ export function createMemoryPresenceStore(): MemoryPresenceStore {
69
+ const rooms = new Map<string, Map<string, PresenceRecord>>();
70
+ let lastSweepMs = 0;
71
+
72
+ // Rooms whose last user left without a leave are never read again, so reads alone would keep
73
+ // them forever; a sweep per ttl on write bounds the map.
74
+ function sweepExpired(nowMs: number, ttlMs: number): void {
75
+ // skip: the last sweep is still within one ttl
76
+ if (nowMs - lastSweepMs < ttlMs) return;
77
+ lastSweepMs = nowMs;
78
+ for (const [key, room] of rooms) {
79
+ for (const [userId, record] of room) {
80
+ if (isExpired(record, nowMs, ttlMs)) room.delete(userId);
81
+ }
82
+ if (room.size === 0) rooms.delete(key);
83
+ }
84
+ }
85
+
86
+ return {
87
+ roomCount: () => rooms.size,
88
+ async touch(key, userId, state, nowMs, ttlMs) {
89
+ sweepExpired(nowMs, ttlMs);
90
+ const room = rooms.get(key) ?? new Map<string, PresenceRecord>();
91
+ rooms.set(key, room);
92
+ const existing = room.get(userId);
93
+ const previous = existing && !isExpired(existing, nowMs, ttlMs) ? existing : undefined;
94
+ room.set(userId, nextRecord(userId, state, previous, nowMs));
95
+ return { changed: previous === undefined || !sameState(previous, state) };
96
+ },
97
+ async remove(key, userId) {
98
+ const room = rooms.get(key);
99
+ const existed = room?.delete(userId) ?? false;
100
+ if (room?.size === 0) rooms.delete(key);
101
+ return { existed };
102
+ },
103
+ async list(key, nowMs, ttlMs) {
104
+ const room = rooms.get(key);
105
+ if (!room) return [];
106
+ for (const [userId, record] of room) {
107
+ if (isExpired(record, nowMs, ttlMs)) room.delete(userId);
108
+ }
109
+ if (room.size === 0) rooms.delete(key);
110
+ return [...room.values()];
111
+ },
112
+ };
113
+ }
114
+
115
+ const KEY_TTL_FACTOR = 2;
116
+
117
+ const storedRecordSchema = z.object({
118
+ activity: z.enum(["viewing", "editing"]),
119
+ focus: z.string().optional(),
120
+ since: z.number(),
121
+ seenAt: z.number(),
122
+ });
123
+
124
+ // Stored value carries no display name: Redis and the live frames hold ids only.
125
+ function parseRecord(userId: string, raw: string): PresenceRecord | undefined {
126
+ try {
127
+ const parsed = storedRecordSchema.safeParse(JSON.parse(raw));
128
+ if (!parsed.success) return undefined;
129
+ const { activity, focus, since, seenAt } = parsed.data;
130
+ return { userId, activity, ...(focus !== undefined && { focus }), since, seenAt };
131
+ } catch {
132
+ return undefined;
133
+ }
134
+ }
135
+
136
+ export function createRedisPresenceStore(redis: Redis, log: Logger): PresenceStore {
137
+ async function guarded<T>(fallback: T, run: () => Promise<T>): Promise<T> {
138
+ if (redis.status !== "ready") {
139
+ log.warn("presence store skipped: redis connection not ready", { status: redis.status });
140
+ return fallback;
141
+ }
142
+ try {
143
+ return await run();
144
+ } catch (err) {
145
+ log.warn("presence store command failed", { err });
146
+ return fallback;
147
+ }
148
+ }
149
+
150
+ async function read(key: string, userId: string): Promise<PresenceRecord | undefined> {
151
+ const raw = await redis.hget(key, userId);
152
+ return raw === null ? undefined : parseRecord(userId, raw);
153
+ }
154
+
155
+ return {
156
+ touch: (key, userId, state, nowMs, ttlMs) =>
157
+ guarded({ changed: false }, async () => {
158
+ const existing = await read(key, userId);
159
+ const previous = existing && !isExpired(existing, nowMs, ttlMs) ? existing : undefined;
160
+ const record = nextRecord(userId, state, previous, nowMs);
161
+ const { userId: _omit, ...stored } = record;
162
+ await redis
163
+ .multi()
164
+ .hset(key, userId, JSON.stringify(stored))
165
+ .expire(key, Math.ceil((ttlMs * KEY_TTL_FACTOR) / 1000))
166
+ .exec();
167
+ return { changed: previous === undefined || !sameState(previous, state) };
168
+ }),
169
+ remove: (key, userId) =>
170
+ guarded({ existed: false }, async () => ({ existed: (await redis.hdel(key, userId)) > 0 })),
171
+ list: (key, nowMs, ttlMs) =>
172
+ guarded<readonly PresenceRecord[]>([], async () => {
173
+ const all = await redis.hgetall(key);
174
+ const live: PresenceRecord[] = [];
175
+ const expired: string[] = [];
176
+ for (const [userId, raw] of Object.entries(all)) {
177
+ const record = parseRecord(userId, raw);
178
+ if (record && !isExpired(record, nowMs, ttlMs)) live.push(record);
179
+ else expired.push(userId);
180
+ }
181
+ if (expired.length > 0) await redis.hdel(key, ...expired);
182
+ return live;
183
+ }),
184
+ };
185
+ }
@@ -14,7 +14,10 @@ import { createLateBoundSlot, readFeatureExportFn } from "../shared/index.ts";
14
14
  import { USER_SESSION_ENTITY_NAME } from "./constants.ts";
15
15
  import { cleanupJob } from "./handlers/cleanup.job.ts";
16
16
  import { createDetailQuery } from "./handlers/detail.query.ts";
17
- import { registerLastActivityProbe } from "./handlers/last-activity-probe.route.ts";
17
+ import {
18
+ readProbeSecretFromEnv,
19
+ registerLastActivityProbe,
20
+ } from "./handlers/last-activity-probe.route.ts";
18
21
  import { createListQuery } from "./handlers/list.query.ts";
19
22
  import { mineQuery } from "./handlers/mine.query.ts";
20
23
  import { revokeWrite } from "./handlers/revoke.write.ts";
@@ -64,6 +67,7 @@ export type SessionsFeatureOptions = {
64
67
  readonly clock?: Clock;
65
68
  // Opt-in: serves GET /sessions/last-activity to a sibling app presenting this secret as a
66
69
  // Bearer token. Answers the newest session activity across every tenant of this app.
70
+ // Unset: falls back to the SESSIONS_LAST_ACTIVITY_PROBE_SECRET env (min. 32 characters).
67
71
  readonly lastActivityProbeSecret?: string;
68
72
  };
69
73
 
@@ -199,7 +203,7 @@ export function createSessionsFeature(options?: SessionsFeatureOptions): Feature
199
203
  ),
200
204
  });
201
205
 
202
- const probeSecret = options?.lastActivityProbeSecret;
206
+ const probeSecret = options?.lastActivityProbeSecret ?? readProbeSecretFromEnv();
203
207
  if (probeSecret !== undefined) registerLastActivityProbe(r, probeSecret);
204
208
 
205
209
  // Cross-feature entity hook on "user". `r.entityHook` (NOT `r.hook`) is