@kennra/app-sdk 0.1.0 → 0.3.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.
@@ -0,0 +1,321 @@
1
+ /**
2
+ * Building blocks for capture apps that read each member's own calendar and mailbox (docs/15
3
+ * §9.3): a per-member throttle that waits out a provider's rate limit within a run's budget, a
4
+ * bounded pool, and the rules for reading an email that do not depend on the provider (addresses
5
+ * and display names in a header, the new part of a reply, HTML to text, automated mail and
6
+ * internal-only messages). Pure and provider-neutral: each app keeps its provider's API, error
7
+ * classes and wording, and decides which errors are a rate limit.
8
+ */
9
+ export const DEFAULT_THROTTLE = {
10
+ unitsPerSecond: 50,
11
+ burst: 250,
12
+ concurrency: 4,
13
+ maxBackoffMs: 45_000,
14
+ now: () => Date.now(),
15
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
16
+ random: Math.random,
17
+ };
18
+ /** One member's token bucket and in-flight limit. */
19
+ export class UserThrottle {
20
+ o;
21
+ tokens;
22
+ last;
23
+ active = 0;
24
+ waiting = [];
25
+ pausedUntil = 0;
26
+ constructor(o) {
27
+ this.o = o;
28
+ this.tokens = o.burst;
29
+ this.last = o.now();
30
+ }
31
+ refill() {
32
+ const now = this.o.now();
33
+ this.tokens = Math.min(this.o.burst, this.tokens + ((now - this.last) / 1000) * this.o.unitsPerSecond);
34
+ this.last = now;
35
+ }
36
+ /** Waits for a free slot and `cost` units. Call `release` when the call is done. */
37
+ async acquire(cost) {
38
+ if (this.active >= this.o.concurrency)
39
+ await new Promise((r) => this.waiting.push(r));
40
+ this.active++;
41
+ const need = Math.min(cost, this.o.burst);
42
+ for (;;) {
43
+ this.refill();
44
+ const paused = this.pausedUntil - this.o.now();
45
+ if (paused > 0) {
46
+ await this.o.sleep(paused);
47
+ continue;
48
+ }
49
+ if (this.tokens >= need) {
50
+ this.tokens -= need;
51
+ return;
52
+ }
53
+ await this.o.sleep(Math.ceil(((need - this.tokens) / this.o.unitsPerSecond) * 1000));
54
+ }
55
+ }
56
+ release() {
57
+ this.active--;
58
+ this.waiting.shift()?.();
59
+ }
60
+ /** The provider said to slow down: no call for this member for `ms`. */
61
+ pause(ms) {
62
+ this.pausedUntil = Math.max(this.pausedUntil, this.o.now() + ms);
63
+ this.tokens = 0;
64
+ }
65
+ }
66
+ /**
67
+ * Runs one provider call through the member's throttle, and tries again after a rate limit
68
+ * (Retry-After, else exponential backoff with jitter) while the run's budget lasts. When the
69
+ * budget is spent the error goes up, so the run stops with its progress saved.
70
+ */
71
+ export async function throttledCall(t, o, budget, cost, call, rateLimitOf) {
72
+ for (let attempt = 0;; attempt++) {
73
+ await t.acquire(cost);
74
+ try {
75
+ return await call();
76
+ }
77
+ catch (err) {
78
+ const limit = rateLimitOf(err);
79
+ if (!limit)
80
+ throw err;
81
+ const backoff = Math.min(32_000, 1000 * 2 ** attempt) * (0.5 + o.random() / 2);
82
+ const wait = Math.max(limit.retryAfterMs ?? 0, backoff);
83
+ if (budget.spentMs + wait > o.maxBackoffMs)
84
+ throw err;
85
+ budget.spentMs += wait;
86
+ t.pause(wait);
87
+ }
88
+ finally {
89
+ t.release();
90
+ }
91
+ }
92
+ }
93
+ /** Runs `fn` over `items` with at most `n` at a time; the results keep the items' order. */
94
+ export async function pool(items, n, fn) {
95
+ const out = new Array(items.length);
96
+ let next = 0;
97
+ let failed = null;
98
+ const worker = async () => {
99
+ while (next < items.length && failed === null) {
100
+ const i = next++;
101
+ try {
102
+ out[i] = await fn(items[i]);
103
+ }
104
+ catch (e) {
105
+ failed ??= e;
106
+ }
107
+ }
108
+ };
109
+ await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker));
110
+ if (failed !== null)
111
+ throw failed;
112
+ return out;
113
+ }
114
+ /** A Retry-After header in seconds or as an HTTP date, in milliseconds (null when absent). */
115
+ export function retryAfterHeader(header, now = Date.now()) {
116
+ const h = header?.trim();
117
+ if (h && /^\d+$/.test(h))
118
+ return Number(h) * 1000;
119
+ const at = h ? Date.parse(h) : Number.NaN;
120
+ return Number.isNaN(at) ? null : Math.max(0, at - now);
121
+ }
122
+ // ---------------------------------------------------------------------------
123
+ // Reading an email
124
+ /** The addresses in an address header (`"Kari, N." <kari@x.no>, per@x.no`), lower case. */
125
+ export function addresses(value) {
126
+ if (!value)
127
+ return [];
128
+ const out = new Set();
129
+ for (const m of value.matchAll(/[^\s<>",;:()]+@[^\s<>",;:()]+\.[^\s<>",;:()]+/g))
130
+ out.add(m[0].toLowerCase());
131
+ return [...out];
132
+ }
133
+ /**
134
+ * Display names in an address header, by address (`"Nordmann, Kari" <kari@x.no>` → kari@x.no:
135
+ * Nordmann, Kari). Only names given with an address in angle brackets; bare addresses have none.
136
+ */
137
+ export function displayNames(value) {
138
+ const out = new Map();
139
+ if (!value)
140
+ return out;
141
+ for (const m of value.matchAll(/(?:"((?:[^"\\]|\\.)*)"|([^<>",;]*?))\s*<([^\s<>",;:()]+@[^\s<>",;:()]+)>/g)) {
142
+ const name = (m[1] ?? m[2] ?? '').replace(/\\(.)/g, '$1').trim();
143
+ const email = (m[3] ?? '').toLowerCase();
144
+ if (name && email && !name.includes('@'))
145
+ out.set(email, name.slice(0, 200));
146
+ }
147
+ return out;
148
+ }
149
+ /** HTML as plain text: no styles or scripts, line breaks kept, entities decoded. */
150
+ export const htmlToText = (html) => html
151
+ .replace(/<(style|script)[\s\S]*?<\/\1>/gi, ' ')
152
+ .replace(/<br\s*\/?>|<\/p>|<\/div>|<\/tr>|<\/li>|<hr\b[^>]*>/gi, '\n')
153
+ .replace(/<[^>]+>/g, ' ')
154
+ .replace(/&nbsp;/g, ' ')
155
+ .replace(/&amp;/g, '&')
156
+ .replace(/&lt;/g, '<')
157
+ .replace(/&gt;/g, '>')
158
+ .replace(/&quot;/g, '"')
159
+ .replace(/&#39;/g, "'")
160
+ .replace(/[ \t]+/g, ' ')
161
+ .replace(/\n\s*\n+/g, '\n\n')
162
+ .trim();
163
+ /*
164
+ * Where the quoted part of an email starts (decision 27 November 2026), in the languages Kennra's
165
+ * customers write: nb, nn, sv, da, en, de, nl, fi (and fr, es, it for the attribution line).
166
+ */
167
+ /** "On … wrote:", "Den … skrev …:", "11 maj 2024 kl. 10:00 skrev …:", "… kirjoitti:". */
168
+ const ATTRIBUTION_VERB = /\b(wrote|writes|skrev|skreiv|schrieb|schreef|kirjoitti|a écrit|escribió|ha scritto|escreveu)\b.{0,200}:\s*$/i;
169
+ /** An attribution line names a date, a time or an address; prose that ends in "skrev:" does not. */
170
+ const ATTRIBUTION_EVIDENCE = /@|\b\d{1,2}[:.]\d{2}\b|\b(19|20)\d{2}\b|^(On|Den|Am|Op|Le|El|Il|På|Em)\s/i;
171
+ /** Forwarded and original-message markers, with or without dashes around them. */
172
+ const MARKER = /^[-_=*\s]*(original message|opprinnelig melding|opprinneleg melding|opphavleg melding|ursprungligt meddelande|originalmeddelande|oprindelig meddelelse|originalmeddelelse|ursprüngliche nachricht|originalnachricht|oorspronkelijk bericht|origineel bericht|alkuperäinen viesti|forwarded message|videresendt melding|vidaresendt melding|vidarebefordrat meddelande|vidarebefordrat brev|videresendt meddelelse|videresendt besked|weitergeleitete nachricht|doorgestuurd bericht|välitetty viesti|edelleenlähetetty viesti|begin forwarded message|start på videresendt melding|start på videresendt besked|anfang der weitergeleiteten (nachricht|e-mail)|begin doorgestuurd bericht|välitetty viesti alkaa|message transféré)\b[-_=*\s:]*$/i;
173
+ /** A quoted header block's first line: `From:` (and its translations), with a value. */
174
+ const HEADER_FROM = /^[*\s]*(From|Fra|Frå|Från|Afsender|Avsender|Avsändare|Von|Van|Lähettäjä|De|Da)\s*:[*\s]*\S/i;
175
+ /** The lines that follow `From:` in a quoted header block. */
176
+ const HEADER_NEXT = /^[*\s]*(Sent|Date|To|Cc|Subject|Sendt|Dato|Til|Kopi|Emne|Skickat|Datum|Till|Kopia|Ämne|Gesendet|An|Betreff|Kopie|Verzonden|Verstuurd|Aan|Onderwerp|Lähetetty|Päivämäärä|Päiväys|Vastaanottaja|Kopio|Aihe|Envoyé|À|Objet)\s*:/i;
177
+ /** A header block flattened onto one line: `From: … Sent: … To: …`. */
178
+ const HEADER_INLINE = /^[*\s]*(From|Fra|Frå|Från|Von|Van|Lähettäjä|De)\s*:.{1,300}?\s(Sent|Date|Sendt|Dato|Skickat|Datum|Gesendet|Verzonden|Verstuurd|Lähetetty|Päivämäärä|Envoyé)\s*:/i;
179
+ /**
180
+ * Whether the quoted part starts at `lines[i]`: a `>` line, an attribution line (also when the
181
+ * client wrapped it over two lines), a forwarded or original-message marker, the underline before
182
+ * a quoted header block, or the header block itself (`From:` followed within three lines by `Sent:`,
183
+ * `Date:` or `To:`, or all on one line).
184
+ */
185
+ export function isQuoteStart(lines, i) {
186
+ const t = (lines[i] ?? '').trim();
187
+ if (!t)
188
+ return false;
189
+ if (t.startsWith('>') || /^_{10,}$/.test(t) || MARKER.test(t) || HEADER_INLINE.test(t))
190
+ return true;
191
+ if (t.length <= 400 && ATTRIBUTION_VERB.test(t) && ATTRIBUTION_EVIDENCE.test(t))
192
+ return true;
193
+ const next = (lines[i + 1] ?? '').trim();
194
+ if (next && !next.startsWith('>')) {
195
+ const joined = `${t} ${next}`;
196
+ if (joined.length <= 400 && ATTRIBUTION_VERB.test(next) && ATTRIBUTION_EVIDENCE.test(t)) {
197
+ // Only when the verb is in the joined line's tail: "…Kari <" + "kari@x.no> wrote:".
198
+ if (ATTRIBUTION_VERB.test(joined) && /[<(@\d]/.test(t))
199
+ return true;
200
+ }
201
+ }
202
+ if (HEADER_FROM.test(t))
203
+ return lines.slice(i + 1, i + 5).some((l) => HEADER_NEXT.test(l.trim()) && !HEADER_FROM.test(l.trim()));
204
+ return false;
205
+ }
206
+ /** The index of the first quoted line, or `lines.length` when nothing is quoted. */
207
+ export function quoteStart(lines) {
208
+ for (let i = 0; i < lines.length; i++)
209
+ if (isQuoteStart(lines, i))
210
+ return i;
211
+ return lines.length;
212
+ }
213
+ /**
214
+ * The new part of a reply: the body up to the quoted earlier messages (`isQuoteStart`). Only this
215
+ * is sent to the core for the summary.
216
+ */
217
+ export function newText(body) {
218
+ const lines = body.split(/\r?\n/);
219
+ return lines.slice(0, quoteStart(lines)).join('\n').trim();
220
+ }
221
+ /**
222
+ * The containers mail clients put a quoted message in: `<blockquote>`, a quote class (`…_quote`,
223
+ * `…_quoted`, `moz-cite-prefix`), the reply header's container (`divRplyFwdMsg`, `appendonsend`,
224
+ * the reference message container), a citation (`type="cite"`), and the top-bordered div a desktop
225
+ * client opens the reply header with.
226
+ */
227
+ const QUOTE_CONTAINERS = [
228
+ /<blockquote\b/i,
229
+ /<[a-z]+\b[^>]*\bclass\s*=\s*["'][^"']*\b[a-z]+_quoted?(_container)?\b/i,
230
+ /<[a-z]+\b[^>]*\bclass\s*=\s*["'][^"']*\bmoz-cite-prefix\b/i,
231
+ /<[a-z]+\b[^>]*\bid\s*=\s*["']?(divRplyFwdMsg|appendonsend|mail-editor-reference-message-container)\b/i,
232
+ /<[a-z]+\b[^>]*\btype\s*=\s*["']?cite\b/i,
233
+ /<div\b[^>]*\bstyle\s*=\s*["'][^"']*border\s*:\s*none\s*;\s*border-top\s*:\s*solid/i,
234
+ ];
235
+ /**
236
+ * The new part of an HTML reply as text: the HTML is cut before its first quote container, then
237
+ * converted, then cut by the text rules (`newText`) too.
238
+ */
239
+ export function htmlNewText(html) {
240
+ let cut = html.length;
241
+ for (const re of QUOTE_CONTAINERS) {
242
+ const m = re.exec(html);
243
+ if (m && m.index < cut)
244
+ cut = m.index;
245
+ }
246
+ return newText(htmlToText(html.slice(0, cut)));
247
+ }
248
+ /**
249
+ * The new part of a message that has a text and an HTML body: each is cut by its own rules, and
250
+ * the shorter wins (the cut that found the quote earliest). Either may be empty.
251
+ */
252
+ export function newPart(text, html) {
253
+ const a = text ? newText(text) : '';
254
+ const b = html ? htmlNewText(html) : '';
255
+ if (a && b)
256
+ return b.length < a.length ? b : a;
257
+ return a || b;
258
+ }
259
+ /**
260
+ * Mailing lists and automated mail, by their headers (`List-Id`, `List-Unsubscribe`,
261
+ * `Precedence: bulk|list|junk`, `Auto-Submitted` other than `no`). `header` reads one header by
262
+ * name, case-insensitively.
263
+ */
264
+ export function isAutomatedMail(header) {
265
+ const precedence = header('Precedence')?.toLowerCase() ?? '';
266
+ const auto = header('Auto-Submitted')?.toLowerCase().trim() ?? '';
267
+ return !!(header('List-Id') ||
268
+ header('List-Unsubscribe') ||
269
+ ['bulk', 'list', 'junk'].includes(precedence) ||
270
+ (auto && auto !== 'no'));
271
+ }
272
+ /** Every participant other than the mailbox's owner is on the workspace's own domains. */
273
+ export function isInternalOnly(participants, mailbox, internalDomains) {
274
+ const internal = new Set(internalDomains.map((d) => d.toLowerCase()));
275
+ const others = participants.map((a) => a.toLowerCase()).filter((a) => a !== mailbox.toLowerCase());
276
+ return !others.some((a) => !internal.has(a.split('@')[1] ?? ''));
277
+ }
278
+ /**
279
+ * Subjects that calendars put on invitations, updates, replies and cancellations, in English and
280
+ * Norwegian (the common calendars' wording and variants). Matched at the start of the subject only:
281
+ * "Re: Invitation: …" is a person replying, and is kept.
282
+ */
283
+ export const CALENDAR_NOTICE_SUBJECTS = [
284
+ // English
285
+ /^invitation:/i,
286
+ /^updated invitation\b/i,
287
+ /^invitation updated\b/i,
288
+ /^new event:/i,
289
+ /^updated event:/i,
290
+ /^accepted:/i,
291
+ /^declined:/i,
292
+ /^tentatively accepted:/i,
293
+ /^canceled event\b/i,
294
+ /^cancelled event\b/i,
295
+ /^event canceled:/i,
296
+ /^event cancelled:/i,
297
+ // Norwegian (bokmål)
298
+ /^invitasjon:/i,
299
+ /^oppdatert invitasjon\b/i,
300
+ /^invitasjonen er oppdatert\b/i,
301
+ /^ny hendelse:/i,
302
+ /^oppdatert hendelse:/i,
303
+ /^godtatt:/i,
304
+ /^akseptert:/i,
305
+ /^avslått:/i,
306
+ /^foreløpig godtatt:/i,
307
+ /^kanskje:/i,
308
+ /^avlyst hendelse\b/i,
309
+ /^avlyst arrangement\b/i,
310
+ /^hendelsen er avlyst\b/i,
311
+ ];
312
+ /** Whether a subject starts like a calendar's notification (`extra`: an app's own wording on top). */
313
+ export function isCalendarNoticeSubject(subject, extra = []) {
314
+ const s = (subject ?? '').trim();
315
+ return CALENDAR_NOTICE_SUBJECTS.some((r) => r.test(s)) || extra.some((r) => r.test(s));
316
+ }
317
+ /** The workspace's own email domains from a comma-separated setting (`internalDomains`). */
318
+ export const domainsOf = (setting) => String(setting ?? '')
319
+ .split(',')
320
+ .map((d) => d.trim().toLowerCase())
321
+ .filter(Boolean);
package/dist/client.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { CaptureBackfillReport, CaptureBackfillRequest, ConsentChangeInput, EngagementSignalInput, Fetch, IngestItem, IngestResponse, InstallationInfo, Lane, SetupReport, SyncRunAck, SyncRunReport, UserConnectionReport } from './protocol.js';
1
+ import type { CaptureBackfillReport, CaptureBackfillRequest, ConsentChangeInput, DocumentLinkRequest, DocumentLinkResult, EngagementSignalInput, Fetch, IngestItem, IngestResponse, InstallationInfo, Lane, SetupReport, SyncRunAck, SyncRunReport, UserConnectionReport } from './protocol.js';
2
2
  export interface KennraClientOptions {
3
3
  /** The Kennra API, e.g. `http://localhost:4000` from `bun run dev`. */
4
4
  baseUrl: string;
@@ -80,6 +80,12 @@ export declare class InstallationClient {
80
80
  * consent purpose, idempotency key `consent:<externalRef>:<purpose>:<channel>`. Withdrawals and
81
81
  * suppressions always apply; a grant only with `kennra:consent:grant` and only when it is newer
82
82
  * than Kennra's own latest consent event (else `outcome: ignored`).
83
+ *
84
+ * Historical changes (`historical: true`, a list moved from another tool) may be older than 30
85
+ * days: a grant needs `kennra:consent:import` and `evidence`, and never wins over a newer
86
+ * withdrawal (`NEWER_WITHDRAWAL_WINS`). Their key is per person too
87
+ * (`consent-import:<person>:<purpose>:<channel>:<externalRef>`), and a batch of only historical
88
+ * changes goes in the import lane.
83
89
  */
84
90
  recordConsentChanges(changes: ConsentChangeInput[]): Promise<IngestResponse['results']>;
85
91
  /**
@@ -108,8 +114,13 @@ export declare class InstallationClient {
108
114
  * The app's setup flow is done (`capabilities.setup`): the consent record (who approved which
109
115
  * provider scopes) and detected settings. The ticket names the admin; the core verifies it.
110
116
  */
117
+ /**
118
+ * Links documents a member picked on the app's picker page (docs/15 §4.13) to the record the
119
+ * ticket names, as that member. `transientText` is read for suggested terms and dropped.
120
+ */
121
+ linkDocuments(req: DocumentLinkRequest): Promise<DocumentLinkResult>;
111
122
  completeSetup(report: SetupReport): Promise<void>;
112
- /** The installation's per-employee connections, with status and share level (the core decides). */
123
+ /** The installation's per-member connections, with status and share level (the core decides). */
113
124
  userConnections(): Promise<{
114
125
  userId: string;
115
126
  connectionKey: string;
@@ -119,7 +130,7 @@ export declare class InstallationClient {
119
130
  /** The last error the app reported for the connection (null once it synced again). */
120
131
  error: string | null;
121
132
  }[]>;
122
- /** Secrets the app keeps in its installation store (e.g. an employee's refresh token). Never shown to admins. */
133
+ /** Secrets the app keeps in its installation store (e.g. a member's refresh token). Never shown to admins. */
123
134
  readonly secrets: {
124
135
  put: (key: string, value: string | null) => Promise<void>;
125
136
  };
package/dist/client.js CHANGED
@@ -138,10 +138,19 @@ export class InstallationClient {
138
138
  * consent purpose, idempotency key `consent:<externalRef>:<purpose>:<channel>`. Withdrawals and
139
139
  * suppressions always apply; a grant only with `kennra:consent:grant` and only when it is newer
140
140
  * than Kennra's own latest consent event (else `outcome: ignored`).
141
+ *
142
+ * Historical changes (`historical: true`, a list moved from another tool) may be older than 30
143
+ * days: a grant needs `kennra:consent:import` and `evidence`, and never wins over a newer
144
+ * withdrawal (`NEWER_WITHDRAWAL_WINS`). Their key is per person too
145
+ * (`consent-import:<person>:<purpose>:<channel>:<externalRef>`), and a batch of only historical
146
+ * changes goes in the import lane.
141
147
  */
142
148
  async recordConsentChanges(changes) {
143
- return this.ingest('live', changes.map((c) => ({
144
- idempotencyKey: `consent:${c.externalRef}:${c.purpose}:${c.channel}`,
149
+ const lane = changes.length && changes.every((c) => c.historical) ? 'import' : 'live';
150
+ return this.ingest(lane, changes.map((c) => ({
151
+ idempotencyKey: c.historical
152
+ ? `consent-import:${personKey(c)}:${c.purpose}:${c.channel}:${c.externalRef}`
153
+ : `consent:${c.externalRef}:${c.purpose}:${c.channel}`,
145
154
  purpose: c.purpose,
146
155
  command: 'recordConsentChange',
147
156
  input: c,
@@ -188,15 +197,22 @@ export class InstallationClient {
188
197
  * The app's setup flow is done (`capabilities.setup`): the consent record (who approved which
189
198
  * provider scopes) and detected settings. The ticket names the admin; the core verifies it.
190
199
  */
200
+ /**
201
+ * Links documents a member picked on the app's picker page (docs/15 §4.13) to the record the
202
+ * ticket names, as that member. `transientText` is read for suggested terms and dropped.
203
+ */
204
+ async linkDocuments(req) {
205
+ return this.request('POST', '/apps/documents/link', req);
206
+ }
191
207
  async completeSetup(report) {
192
208
  await this.request('POST', '/apps/installation/setup', report);
193
209
  this.info = null;
194
210
  }
195
- /** The installation's per-employee connections, with status and share level (the core decides). */
211
+ /** The installation's per-member connections, with status and share level (the core decides). */
196
212
  async userConnections() {
197
213
  return (await this.request('GET', '/apps/user-connections')).connections;
198
214
  }
199
- /** Secrets the app keeps in its installation store (e.g. an employee's refresh token). Never shown to admins. */
215
+ /** Secrets the app keeps in its installation store (e.g. a member's refresh token). Never shown to admins. */
200
216
  secrets = {
201
217
  put: async (key, value) => {
202
218
  await this.request('PUT', `/apps/installation/secrets/${encodeURIComponent(key)}`, { value });
@@ -261,3 +277,24 @@ export class KennraAppClient {
261
277
  return c;
262
278
  }
263
279
  }
280
+ /**
281
+ * A short, stable key for the person a consent change is about (no address in the key itself):
282
+ * the party id, or a 64-bit hash (two FNV-1a passes) of the identifier.
283
+ */
284
+ function personKey(ref) {
285
+ if ('partyId' in ref && ref.partyId)
286
+ return ref.partyId;
287
+ const id = 'identifier' in ref ? ref.identifier : null;
288
+ const text = id
289
+ ? JSON.stringify([id.type, 'issuer' in id ? id.issuer : '', id.value.trim().toLowerCase()])
290
+ : '';
291
+ const fnv = (seed) => {
292
+ let h = seed;
293
+ for (let i = 0; i < text.length; i++) {
294
+ h ^= text.charCodeAt(i);
295
+ h = Math.imul(h, 0x01000193) >>> 0;
296
+ }
297
+ return h.toString(16).padStart(8, '0');
298
+ };
299
+ return `id-${fnv(0x811c9dc5)}${fnv(0x01000193)}`;
300
+ }
package/dist/index.d.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  * Bun, Deno, serverless functions and edge runtimes. Uses only Kennra's public API.
4
4
  */
5
5
  import type { Fetch } from './protocol.js';
6
+ export * from './admin-links.js';
6
7
  export * from './app.js';
7
8
  export * from './client.js';
8
9
  export type * from './hosting.js';
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ export * from "./admin-links.js";
1
2
  export * from "./app.js";
2
3
  export * from "./client.js";
3
4
  export * from "./manifest.js";
@@ -6,7 +6,7 @@ export type ManifestPiiLevel = (typeof PII_LEVELS)[number];
6
6
  * Scopes an app may request. `kennra:privacy`, workspace scopes and publishing the schema are never
7
7
  * granted to apps; proposing schema changes (`kennra:schema:draft`) is.
8
8
  */
9
- export declare const APP_SCOPES: readonly ["kennra:read", "kennra:party:write", "kennra:commerce:write", "kennra:interaction:write", "kennra:trait:write", "kennra:deal:write", "kennra:work:write", "kennra:consent:write", "kennra:import:backdate", "kennra:export", "kennra:segment:read", "kennra:schema:draft", "kennra:suggestions:decide", "kennra:consent:grant", "kennra:engagement:write"];
9
+ export declare const APP_SCOPES: readonly ["kennra:read", "kennra:party:write", "kennra:commerce:write", "kennra:interaction:write", "kennra:trait:write", "kennra:deal:write", "kennra:work:write", "kennra:consent:write", "kennra:import:backdate", "kennra:export", "kennra:segment:read", "kennra:schema:draft", "kennra:suggestions:decide", "kennra:consent:grant", "kennra:engagement:write", "kennra:consent:import", "kennra:events:read"];
10
10
  export type AppScope = (typeof APP_SCOPES)[number];
11
11
  /** The scope that lets an app pass on a member's decision on a suggestion (21 November 2026). */
12
12
  export declare const SUGGESTIONS_DECIDE_SCOPE = "kennra:suggestions:decide";
@@ -14,6 +14,11 @@ export declare const SUGGESTIONS_DECIDE_SCOPE = "kennra:suggestions:decide";
14
14
  export declare const SENSITIVE_SCOPES: readonly string[];
15
15
  /** The scope that lets an app record consent a person gave in it (decision 21 November 2026). */
16
16
  export declare const CONSENT_GRANT_SCOPE = "kennra:consent:grant";
17
+ /**
18
+ * The scope that lets an app import consent a person gave before Kennra knew them, with evidence
19
+ * (decision 21 November 2026, docs/15 §4.10). Apps only: agents and roles never hold it.
20
+ */
21
+ export declare const CONSENT_IMPORT_SCOPE = "kennra:consent:import";
17
22
  /** The scope for engagement signals (decision 21 November 2026). */
18
23
  export declare const ENGAGEMENT_WRITE_SCOPE = "kennra:engagement:write";
19
24
  /** Engagement signals an app can report (`recordEngagement`). */
@@ -25,8 +30,10 @@ export declare const TARGET_CONTACT_CHANNELS: readonly ["email", "sms"];
25
30
  * `organization.search` is a search in a public company register: the ref is
26
31
  * `<country>:<text>` (ISO 3166-1 alpha-2 and what a person typed), e.g. `NO:fjellsport`.
27
32
  */
28
- export declare const LOOKUP_OBJECTS: readonly ["order.details", "subscription.details", "interaction.details", "organization.search", "organization.profile", "organization.logo"];
33
+ export declare const LOOKUP_OBJECTS: readonly ["order.details", "subscription.details", "invoice.details", "interaction.details", "organization.search", "organization.profile", "organization.logo", "document.details", "person.photo", "object.search", "object.resolve"];
29
34
  export type LookupObject = (typeof LOOKUP_OBJECTS)[number];
35
+ /** The envelope every external object has; typed fields can't reuse these keys. */
36
+ export declare const ENVELOPE_KEYS: readonly string[];
30
37
  /** Kinds an app may declare it writes. */
31
38
  export declare const WRITABLE_KINDS: readonly ["Person", "Organization", "CommerceFact", "Interaction", "Deal", "Task", "Note"];
32
39
  /** The Kinds a deep link (`capabilities.ui.links`) can be declared on. */
@@ -45,6 +52,60 @@ export declare function localize(label: ManifestLabel | undefined, lang: string
45
52
  * settings in production workspaces.
46
53
  */
47
54
  export declare const SETTING_VISIBILITY: readonly ["default", "advanced", "demo"];
55
+ /** The types a typed field of an external object can have (docs/15 §4.14). */
56
+ export declare const OBJECT_FIELD_TYPES: readonly ["text", "number", "boolean", "date", "money", "textList", "attributes"];
57
+ export type ObjectFieldType = (typeof OBJECT_FIELD_TYPES)[number];
58
+ /**
59
+ * An object type the app provides (`capabilities.objects`, decision 27 November 2026): a value of
60
+ * an `external` trait field points at one object of this type in the app's system. `contract` is
61
+ * versioned (`<app id>.<type>@<n>`): a later version that changes the meaning of a field is a new
62
+ * contract. `fields` are the typed snapshot fields Kennra keeps next to the envelope (id, title,
63
+ * subtitle, image, link); `scope` the filters a field may set (pickers use them, writes are
64
+ * checked against them on the snapshot field they name).
65
+ */
66
+ declare const ObjectType: z.ZodObject<{
67
+ type: z.ZodString;
68
+ contract: z.ZodString;
69
+ label: z.ZodObject<{
70
+ en: z.ZodString;
71
+ }, z.core.$catchall<z.ZodString>>;
72
+ description: z.ZodOptional<z.ZodObject<{
73
+ en: z.ZodString;
74
+ }, z.core.$catchall<z.ZodString>>>;
75
+ fields: z.ZodDefault<z.ZodArray<z.ZodObject<{
76
+ key: z.ZodString;
77
+ type: z.ZodEnum<{
78
+ number: "number";
79
+ boolean: "boolean";
80
+ date: "date";
81
+ text: "text";
82
+ money: "money";
83
+ textList: "textList";
84
+ attributes: "attributes";
85
+ }>;
86
+ label: z.ZodObject<{
87
+ en: z.ZodString;
88
+ }, z.core.$catchall<z.ZodString>>;
89
+ description: z.ZodOptional<z.ZodObject<{
90
+ en: z.ZodString;
91
+ }, z.core.$catchall<z.ZodString>>>;
92
+ }, z.core.$strip>>>;
93
+ scope: z.ZodDefault<z.ZodArray<z.ZodObject<{
94
+ key: z.ZodString;
95
+ label: z.ZodObject<{
96
+ en: z.ZodString;
97
+ }, z.core.$catchall<z.ZodString>>;
98
+ description: z.ZodOptional<z.ZodObject<{
99
+ en: z.ZodString;
100
+ }, z.core.$catchall<z.ZodString>>>;
101
+ field: z.ZodString;
102
+ match: z.ZodEnum<{
103
+ equals: "equals";
104
+ prefix: "prefix";
105
+ }>;
106
+ }, z.core.$strip>>>;
107
+ }, z.core.$strip>;
108
+ export type ManifestObjectType = z.infer<typeof ObjectType>;
48
109
  /** A run's maximum duration when its schedule declares none (docs/15 §4.7). */
49
110
  export declare const DEFAULT_MAX_RUN_SECONDS = 600;
50
111
  /** How long a run's lease lasts after its start or its last heartbeat. */
@@ -129,8 +190,8 @@ export declare const AppManifestSchema: z.ZodObject<{
129
190
  digits: "digits";
130
191
  }>>;
131
192
  piiClass: z.ZodDefault<z.ZodEnum<{
132
- none: "none";
133
193
  contact: "contact";
194
+ none: "none";
134
195
  }>>;
135
196
  legacyTypes: z.ZodDefault<z.ZodArray<z.ZodString>>;
136
197
  }, z.core.$strip>>;
@@ -141,6 +202,7 @@ export declare const AppManifestSchema: z.ZodObject<{
141
202
  ORDER: "ORDER";
142
203
  QUOTE: "QUOTE";
143
204
  SUBSCRIPTION: "SUBSCRIPTION";
205
+ INVOICE: "INVOICE";
144
206
  INTERACTION: "INTERACTION";
145
207
  }>>>;
146
208
  sourceSystem: z.ZodString;
@@ -158,10 +220,15 @@ export declare const AppManifestSchema: z.ZodObject<{
158
220
  object: z.ZodEnum<{
159
221
  "order.details": "order.details";
160
222
  "subscription.details": "subscription.details";
223
+ "invoice.details": "invoice.details";
161
224
  "interaction.details": "interaction.details";
162
225
  "organization.search": "organization.search";
163
226
  "organization.profile": "organization.profile";
164
227
  "organization.logo": "organization.logo";
228
+ "document.details": "document.details";
229
+ "person.photo": "person.photo";
230
+ "object.search": "object.search";
231
+ "object.resolve": "object.resolve";
165
232
  }>;
166
233
  refPattern: z.ZodString;
167
234
  url: z.ZodString;
@@ -170,6 +237,48 @@ export declare const AppManifestSchema: z.ZodObject<{
170
237
  purposes: z.ZodArray<z.ZodString>;
171
238
  delegated: z.ZodDefault<z.ZodBoolean>;
172
239
  }, z.core.$strip>>>;
240
+ objects: z.ZodDefault<z.ZodArray<z.ZodObject<{
241
+ type: z.ZodString;
242
+ contract: z.ZodString;
243
+ label: z.ZodObject<{
244
+ en: z.ZodString;
245
+ }, z.core.$catchall<z.ZodString>>;
246
+ description: z.ZodOptional<z.ZodObject<{
247
+ en: z.ZodString;
248
+ }, z.core.$catchall<z.ZodString>>>;
249
+ fields: z.ZodDefault<z.ZodArray<z.ZodObject<{
250
+ key: z.ZodString;
251
+ type: z.ZodEnum<{
252
+ number: "number";
253
+ boolean: "boolean";
254
+ date: "date";
255
+ text: "text";
256
+ money: "money";
257
+ textList: "textList";
258
+ attributes: "attributes";
259
+ }>;
260
+ label: z.ZodObject<{
261
+ en: z.ZodString;
262
+ }, z.core.$catchall<z.ZodString>>;
263
+ description: z.ZodOptional<z.ZodObject<{
264
+ en: z.ZodString;
265
+ }, z.core.$catchall<z.ZodString>>>;
266
+ }, z.core.$strip>>>;
267
+ scope: z.ZodDefault<z.ZodArray<z.ZodObject<{
268
+ key: z.ZodString;
269
+ label: z.ZodObject<{
270
+ en: z.ZodString;
271
+ }, z.core.$catchall<z.ZodString>>;
272
+ description: z.ZodOptional<z.ZodObject<{
273
+ en: z.ZodString;
274
+ }, z.core.$catchall<z.ZodString>>>;
275
+ field: z.ZodString;
276
+ match: z.ZodEnum<{
277
+ equals: "equals";
278
+ prefix: "prefix";
279
+ }>;
280
+ }, z.core.$strip>>>;
281
+ }, z.core.$strip>>>;
173
282
  schedules: z.ZodDefault<z.ZodArray<z.ZodObject<{
174
283
  id: z.ZodString;
175
284
  every: z.ZodOptional<z.ZodString>;
@@ -303,6 +412,19 @@ export declare const AppManifestSchema: z.ZodObject<{
303
412
  transcripts: "transcripts";
304
413
  }>>;
305
414
  }, z.core.$strip>>;
415
+ documents: z.ZodOptional<z.ZodObject<{
416
+ label: z.ZodObject<{
417
+ en: z.ZodString;
418
+ }, z.core.$catchall<z.ZodString>>;
419
+ hosts: z.ZodDefault<z.ZodArray<z.ZodString>>;
420
+ picker: z.ZodOptional<z.ZodObject<{
421
+ url: z.ZodString;
422
+ label: z.ZodOptional<z.ZodObject<{
423
+ en: z.ZodString;
424
+ }, z.core.$catchall<z.ZodString>>>;
425
+ requiresSetting: z.ZodOptional<z.ZodString>;
426
+ }, z.core.$strip>>;
427
+ }, z.core.$strip>>;
306
428
  mcpClient: z.ZodOptional<z.ZodObject<{
307
429
  clientIds: z.ZodDefault<z.ZodArray<z.ZodString>>;
308
430
  redirectUris: z.ZodDefault<z.ZodArray<z.ZodString>>;
@@ -334,6 +456,7 @@ export declare const AppManifestSchema: z.ZodObject<{
334
456
  ORDER: "ORDER";
335
457
  QUOTE: "QUOTE";
336
458
  SUBSCRIPTION: "SUBSCRIPTION";
459
+ INVOICE: "INVOICE";
337
460
  }>>, unknown>;
338
461
  }, z.core.$strip>>;
339
462
  }, z.core.$strip>>>;
@@ -432,7 +555,7 @@ export declare function defineManifest(input: AppManifestInput | string): AppMan
432
555
  /** Whether a boolean setting is on: the saved value, else the schema's default. */
433
556
  export declare function settingOn(m: Pick<AppManifest, 'settings'>, settings: Record<string, unknown> | null | undefined, key: string): boolean;
434
557
  /**
435
- * The `userConnections` kinds employees can connect now: a kind with `requiresSetting` only while
558
+ * The `userConnections` kinds members can connect now: a kind with `requiresSetting` only while
436
559
  * that setting is on.
437
560
  */
438
561
  export declare function availableConnectionKinds(m: Pick<AppManifest, 'capabilities' | 'settings'>, settings: Record<string, unknown> | null | undefined): string[];