@kennra/app-sdk 0.0.0 → 0.2.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,1105 @@
1
+ /**
2
+ * The wire contract between the Kennra core and apps (docs/15 §3–4). Types only; the core and the
3
+ * SDK both use them, so a change here is a contract change.
4
+ */
5
+ export type Lane = 'live' | 'import';
6
+ /** `POST /apps/token`: client credentials for one installation (dev; the identity provider in production). */
7
+ export interface TokenRequest {
8
+ /**
9
+ * `client_credentials`: the installation acts as itself. Token exchange (RFC 8693): the app acts
10
+ * for the member whose Kennra token is `subject_token` (manifest `access.actsForMembers`), or,
11
+ * for a private app with delegation, for the member named in `requested_subject`.
12
+ */
13
+ grant_type: 'client_credentials' | 'urn:ietf:params:oauth:grant-type:token-exchange';
14
+ client_id: string;
15
+ client_secret: string;
16
+ installation: string;
17
+ subject_token?: string;
18
+ /**
19
+ * Delegation (private apps): the member's email or user id (`usr_…`). Kennra trusts the app's
20
+ * own sign-in; the member must be active and on the app's delegation list.
21
+ */
22
+ requested_subject?: string;
23
+ /**
24
+ * Space-separated scopes the token should carry: narrows the grant (OAuth semantics). Without
25
+ * it, the token carries the whole grant, except that a private app's `kennra:import:backdate`
26
+ * (Keep original dates) applies only when it is asked for here. Asking for a scope outside the
27
+ * grant is refused with `invalid_scope`.
28
+ */
29
+ scope?: string;
30
+ }
31
+ export interface TokenResponse {
32
+ access_token: string;
33
+ token_type: 'Bearer';
34
+ expires_in: number;
35
+ workspace: string;
36
+ installation: string;
37
+ /** The member the token acts for (token exchange and delegation). */
38
+ on_behalf_of?: string;
39
+ /** The scopes the token carries, space-separated. */
40
+ scope?: string;
41
+ }
42
+ /** `GET /apps/installation`: what the installation token may read about its installation. */
43
+ export interface InstallationInfo {
44
+ installationId: string;
45
+ workspace: string;
46
+ app: {
47
+ id: string;
48
+ version: string;
49
+ };
50
+ status: 'active' | 'paused' | 'suspended' | 'uninstalled';
51
+ settings: Record<string, unknown>;
52
+ /**
53
+ * The app's secrets (e.g. an API key, members' refresh tokens). Only when asked for
54
+ * (`GET /apps/installation?include=secrets`); empty otherwise.
55
+ */
56
+ secrets: Record<string, string>;
57
+ /** The names of the stored secrets (always). */
58
+ secretKeys: string[];
59
+ /** Verifies requests from Kennra (Standard Webhooks). Current first, then the previous during rotation. */
60
+ signingSecrets: string[];
61
+ grant: {
62
+ scopes: {
63
+ scope: string;
64
+ purposes: string[];
65
+ }[];
66
+ piiLevel: string;
67
+ };
68
+ }
69
+ export type ExternalIdentifierInput = {
70
+ type: 'external';
71
+ issuer: string;
72
+ scheme: string;
73
+ value: string;
74
+ };
75
+ export type IdentifierInput = ExternalIdentifierInput | {
76
+ type: 'email' | 'phone';
77
+ value: string;
78
+ }
79
+ /**
80
+ * A company registration identifier: `country` ISO 3166-1 alpha-2 (omitted: NO, deprecated),
81
+ * `scheme` national (default), lei, vat, duns or ein.
82
+ */
83
+ | {
84
+ type: 'org_number';
85
+ value: string;
86
+ country?: string;
87
+ scheme?: string;
88
+ } | {
89
+ type: 'auth_subject';
90
+ issuer: string;
91
+ value: string;
92
+ };
93
+ /** One item in `POST /ingest`. Each carries one semantic command. */
94
+ export type IngestItem = {
95
+ /**
96
+ * Stable across retries and versions: `(installation, idempotencyKey)` is idempotent, per member
97
+ * for a delegated token (the app for itself and for each member have separate keys).
98
+ */
99
+ idempotencyKey: string;
100
+ /** The purpose the write is for; must be granted with the command's scope. Default: the first granted. */
101
+ purpose?: string;
102
+ /** Valid time in the world. A past time needs `kennra:import:backdate`. */
103
+ occurredAt?: string;
104
+ /** Provenance: the object in the source system. */
105
+ sourceRef?: string;
106
+ sourceTenant?: string;
107
+ } & ({
108
+ command: 'resolveIdentity';
109
+ input: {
110
+ partyType: 'person' | 'organization';
111
+ identifiers: IdentifierInput[];
112
+ givenName?: string;
113
+ familyName?: string;
114
+ legalName?: string;
115
+ createIfMissing?: boolean;
116
+ /**
117
+ * A person who is a contact at a company (role, default `user`): the company with this
118
+ * identifier, or the company that has this business domain (e.g. the part after `@` of
119
+ * the person's address). Consumer mail domains and unknown domains attach nothing; no
120
+ * company is created.
121
+ */
122
+ memberOf?: {
123
+ identifier: IdentifierInput;
124
+ role?: string;
125
+ } | {
126
+ domain: string;
127
+ role?: string;
128
+ };
129
+ };
130
+ } | {
131
+ command: 'recordMirroredFact';
132
+ input: {
133
+ snapshot: Record<string, unknown>;
134
+ sourceVersion: number;
135
+ observedAt?: string;
136
+ };
137
+ } | {
138
+ command: 'attributeMirroredFacts';
139
+ input: {
140
+ partyId: string;
141
+ };
142
+ } | {
143
+ command: 'captureInteraction';
144
+ input: CaptureInput;
145
+ } | {
146
+ command: 'captureMeetingNotes';
147
+ input: MeetingNotesCapture;
148
+ } | {
149
+ command: 'setTraitValues';
150
+ input: {
151
+ entityId: string;
152
+ trait: string;
153
+ values: {
154
+ field: string;
155
+ value: unknown;
156
+ itemKey?: string;
157
+ }[];
158
+ };
159
+ } | {
160
+ command: 'linkIdentifier';
161
+ input: {
162
+ partyId: string;
163
+ identifier: IdentifierInput;
164
+ verified?: boolean;
165
+ };
166
+ } | {
167
+ command: 'recordConsentChange';
168
+ input: ConsentChangeInput;
169
+ } | {
170
+ command: 'recordEngagement';
171
+ input: EngagementSignalInput;
172
+ });
173
+ /** Who an app's consent change or engagement signal is about: a party id or an identifier. */
174
+ export type PersonRef = {
175
+ partyId: string;
176
+ } | {
177
+ identifier: IdentifierInput;
178
+ };
179
+ /**
180
+ * `recordConsentChange` (scope `kennra:consent:write`, purpose = the consent purpose, decision 21
181
+ * November 2026): a person changed their consent in the app (unsubscribed, resubscribed, a bounce or
182
+ * complaint the app suppressed). Rules in the core:
183
+ * - `withdrawn` and `suppressed` always apply (a suppression is recorded as a withdrawal with
184
+ * `suppression` set);
185
+ * - `granted` applies only when the grant also holds `kennra:consent:grant` for the purpose, and
186
+ * the change is newer than the latest consent event Kennra has for the purpose and channel, so it
187
+ * never overrides a newer withdrawal. Otherwise the result is `ignored` with a reason.
188
+ */
189
+ export type ConsentChangeInput = PersonRef & {
190
+ channel: 'email' | 'sms';
191
+ /** The consent purpose, e.g. `marketing.email`. Also the item's `purpose` (default). */
192
+ purpose: string;
193
+ state: 'granted' | 'withdrawn' | 'suppressed';
194
+ /** For `suppressed`: why the app stopped sending. */
195
+ suppression?: 'bounce' | 'complaint';
196
+ /** The change in the app (e.g. its webhook event id), kept as evidence. */
197
+ externalRef: string;
198
+ /** When it happened in the app (ISO 8601). Never in the future. */
199
+ occurredAt: string;
200
+ /** For `granted`: the notice the person accepted (`notice:<name>@v<n>`); default `notice:app-<appId>@v1`. */
201
+ noticeRef?: string;
202
+ /**
203
+ * A change from before Kennra knew the person (decision 21 November 2026, docs/15 §4.10): a
204
+ * list moved from another sending tool. `occurredAt` may then be older than 30 days.
205
+ * - a historical `granted` needs `kennra:consent:import` for the purpose (else `SCOPE_REQUIRED`)
206
+ * and `evidence` (else `EVIDENCE_REQUIRED`), and is refused when Kennra has a newer
207
+ * withdrawal for the purpose and channel (`NEWER_WITHDRAWAL_WINS`);
208
+ * - a historical `withdrawn` or `suppressed` only narrows, so it needs no more than
209
+ * `kennra:consent:write`.
210
+ * Idempotent per person, purpose, channel and `externalRef` (send the provider's own record id).
211
+ */
212
+ historical?: boolean;
213
+ /** The proof of a historical opt-in. Required for a historical `granted`. */
214
+ evidence?: ConsentEvidence;
215
+ };
216
+ /**
217
+ * The proof of an opt-in that happened in another tool (decision 21 November 2026). `provider` and
218
+ * at least one of `ipAddress`, `source` / `form` / `url`, `confirmedAt` or `providerRecordId`.
219
+ * `occurredAt` on the change is the opt-in time (for double opt-in, the confirmation). Kennra keeps
220
+ * the evidence with the consent event: IP addresses encrypted with the person's key (gone when
221
+ * the person is erased), a URL without its query string, and returns it in a data subject export.
222
+ */
223
+ export interface ConsentEvidence {
224
+ /** The tool the opt-in happened in, as a display name (e.g. the sending tool's name). */
225
+ provider: string;
226
+ /** The provider's own id of the subscriber or opt-in record. */
227
+ providerRecordId?: string;
228
+ /** The IP address the opt-in came from. */
229
+ ipAddress?: string;
230
+ /** How the person signed up in the provider (e.g. `form`, `api`, `import`, `checkout`). */
231
+ source?: string;
232
+ /** The name of the signup form. */
233
+ form?: string;
234
+ /** The page the signup form was on (stored without query string or fragment). */
235
+ url?: string;
236
+ /** When the person submitted the signup (before a double opt-in confirmation). */
237
+ signupAt?: string;
238
+ /** The IP address of the signup, when it differs from the opt-in. */
239
+ signupIpAddress?: string;
240
+ /** When the person confirmed a double opt-in. */
241
+ confirmedAt?: string;
242
+ /** The text or version of the consent the person accepted in the provider, if known. */
243
+ consentText?: string;
244
+ }
245
+ /** One of `ENGAGEMENT_SIGNALS` (manifest.ts). */
246
+ export type EngagementSignal = 'delivered' | 'opened' | 'clicked' | 'bounced' | 'complained' | 'unsubscribed';
247
+ /**
248
+ * `recordEngagement` (scope `kennra:engagement:write`): one signal from a sending tool. The core
249
+ * keeps aggregates per person and channel (counts per day, last engaged, last campaign), never one
250
+ * record per message. Deduplicated by `eventId` per installation (send it as the item's
251
+ * idempotencyKey too).
252
+ */
253
+ export type EngagementSignalInput = PersonRef & {
254
+ channel: 'email' | 'sms';
255
+ signal: EngagementSignal;
256
+ /** The app's own id of the event (e.g. its webhook event id). */
257
+ eventId: string;
258
+ occurredAt: string;
259
+ /** The campaign, broadcast or flow the message belonged to. */
260
+ campaignRef?: string;
261
+ /** A display name for the campaign (no personal data). */
262
+ campaignName?: string;
263
+ /** The message in the app (not stored per message; used for dedup only). */
264
+ messageRef?: string;
265
+ };
266
+ /**
267
+ * A captured meeting or message in source-neutral form. The core decides what is stored
268
+ * (docs/15 §9.3): the member must have connected, private and internal items are skipped,
269
+ * only items with known external people or companies are kept, the text is summarized and dropped.
270
+ */
271
+ export interface CaptureInput {
272
+ /** The member whose calendar or mailbox it came from (their Kennra user id). */
273
+ userId: string;
274
+ /** The member's connection in this installation (as reported with reportUserConnection). */
275
+ connectionKey: string;
276
+ sourceRef: string;
277
+ sourceVersion: number;
278
+ kind?: 'meeting' | 'video' | 'email' | 'call';
279
+ status: 'confirmed' | 'cancelled';
280
+ /** Marked private or confidential in the source: never captured (and removed if it was). */
281
+ private?: boolean;
282
+ startsAt?: string;
283
+ endsAt?: string;
284
+ subject?: string;
285
+ attendees: {
286
+ email: string;
287
+ /**
288
+ * The display name as the provider gave it (`"Kari Nordmann" <kari@…>`, a calendar attendee's
289
+ * displayName). Used only for a suggested contact the mailbox owner sees (docs/15 §9.3), never
290
+ * stored with the interaction.
291
+ */
292
+ name?: string;
293
+ responseStatus?: string;
294
+ organizer?: boolean;
295
+ self?: boolean;
296
+ resource?: boolean;
297
+ }[];
298
+ organizerEmail?: string;
299
+ organizerSelf?: boolean;
300
+ conference?: boolean;
301
+ attachmentCount?: number;
302
+ /** Description or body: summarized by the core's LLM gateway and discarded, never stored. */
303
+ transientText?: string;
304
+ /**
305
+ * The source's own id of the message or event, the same in every mailbox or calendar that has a
306
+ * copy (an email's RFC 822 `Message-ID`, a calendar event's iCalendar UID). Metadata, never
307
+ * content. The core summarizes one message once: a copy with the same id and text reuses the
308
+ * summary and costs no AI credit.
309
+ */
310
+ contentId?: string;
311
+ }
312
+ /** One spoken turn of a meeting transcript, as the source recorded it. */
313
+ export interface TranscriptTurn {
314
+ /** The speaker's name as the source shows it (masked by the core before any model sees it). */
315
+ speaker?: string;
316
+ /** The speaker's email when the app could match them to an attendee. */
317
+ speakerEmail?: string;
318
+ text: string;
319
+ startsAt?: string;
320
+ }
321
+ /**
322
+ * `captureMeetingNotes`: the transcript of a meeting that ended, for a meeting the app already
323
+ * captured with `captureInteraction` (the same member's `interactionSourceRef`). The core
324
+ * decides: the member must have connected (`userId` + `connectionKey`), the meeting must be a
325
+ * captured, not cancelled interaction they own. It summarizes the transcript with its own LLM
326
+ * gateway (summary, decisions, next steps), writes the summary as a note marked aiGenerated on the
327
+ * interaction and its companies, people and deals, and suggests a task per next step (never
328
+ * accepted on its own). The transcript is never stored; `transcriptUrl` (a link to it in the
329
+ * source) is.
330
+ */
331
+ export interface MeetingNotesCapture {
332
+ userId: string;
333
+ /** The member's transcripts connection in this installation (reportUserConnection). */
334
+ connectionKey: string;
335
+ /** The `sourceRef` the meeting was captured with (`captureInteraction`). */
336
+ interactionSourceRef: string;
337
+ /** The source's own id of this recording or transcript (idempotency and the source trail). */
338
+ sourceRef: string;
339
+ /** The turns, in order. Summarized and dropped, never stored. At most 2,000 turns. */
340
+ turns: TranscriptTurn[];
341
+ /** Where people with access read the transcript in the source. Stored and shown as a link. */
342
+ transcriptUrl?: string;
343
+ /** The transcript's language (BCP 47), when the source says. */
344
+ language?: string;
345
+ endedAt?: string;
346
+ }
347
+ export interface IngestRequest {
348
+ lane?: Lane;
349
+ items: IngestItem[];
350
+ }
351
+ export interface IngestItemResult {
352
+ idempotencyKey: string;
353
+ ok: boolean;
354
+ replay?: boolean;
355
+ outcome?: string;
356
+ entityId?: string;
357
+ data?: Record<string, unknown>;
358
+ error?: {
359
+ code: string;
360
+ message: string;
361
+ problems?: {
362
+ path: string;
363
+ code: string;
364
+ message: string;
365
+ }[];
366
+ };
367
+ }
368
+ export interface IngestResponse {
369
+ batchId: string;
370
+ lane: Lane;
371
+ results: IngestItemResult[];
372
+ }
373
+ /**
374
+ * How a run ended (docs/15 §4.7). `partial`: it stopped before it was done (its maximum duration
375
+ * or the app asked it to) and saved its cursor, so the next tick goes on. `interrupted`: the app's
376
+ * host shut down (a deploy) and the run saved its cursor first. `abandoned` is set by Kennra only,
377
+ * when a run's lease ran out without a heartbeat.
378
+ */
379
+ export type SyncRunStatus = 'completed' | 'failed' | 'partial' | 'interrupted';
380
+ /**
381
+ * `POST /apps/runs`: the outcome of a schedule tick or a sync (reportSyncRun). Status `running`
382
+ * is a heartbeat: it extends the run's lease, and `counters` are its progress so far.
383
+ */
384
+ export interface SyncRunReport {
385
+ runId: string;
386
+ scheduleId?: string;
387
+ status: SyncRunStatus | 'running';
388
+ counters?: Record<string, number | Record<string, number>>;
389
+ errors?: {
390
+ stream?: string;
391
+ sourceId?: string;
392
+ message: string;
393
+ code?: string;
394
+ }[];
395
+ }
396
+ /**
397
+ * The answer to `POST /apps/runs`. `status` is the run's status in Kennra after the report:
398
+ * `abandoned` means its lease ran out, and the report was kept as information only (the run
399
+ * stays abandoned; the app should stop). `leaseExpiresAt` while it runs.
400
+ */
401
+ export interface SyncRunAck {
402
+ ok: true;
403
+ runId: string;
404
+ status: SyncRunStatus | 'running' | 'abandoned' | 'unknown';
405
+ leaseExpiresAt?: string;
406
+ }
407
+ /**
408
+ * `GET /apps/capture-backfills` (capabilities.ingest.backfill, docs/15 §9.3): a person or company
409
+ * that became known, whose history the app should look for. `emails` only when the grant's PII
410
+ * level allows contact data; `domains` are business domains only. Report on `backfillId`.
411
+ */
412
+ export interface CaptureBackfillRequest {
413
+ backfillId: string;
414
+ partyId: string;
415
+ partyType: 'person' | 'organization';
416
+ reason: string;
417
+ requestedAt: string;
418
+ emails: string[];
419
+ domains: string[];
420
+ /** What this installation reported on this request so far (a resumed run). */
421
+ progress: {
422
+ status: string;
423
+ counters: Record<string, number>;
424
+ } | null;
425
+ }
426
+ /**
427
+ * `POST /apps/capture-backfills/report`: progress on a request. `counters.meetings` and
428
+ * `counters.emails` are what members see ("found 14 meetings and 32 emails so far"): the items
429
+ * now in Kennra, captured in this run or already there.
430
+ */
431
+ export interface CaptureBackfillReport {
432
+ backfillId: string;
433
+ /**
434
+ * `running`: the app is working on it. `partial`: the app did what it could for now and the rest
435
+ * waits for the provider (say which in `waiting`); it goes on by itself on later runs, so Kennra
436
+ * keeps serving the request. `done` and `failed` are final.
437
+ */
438
+ status: 'running' | 'partial' | 'done' | 'failed';
439
+ counters?: Record<string, number>;
440
+ /** What is still waiting for the provider (a rate limit): meetings, emails or both. */
441
+ waiting?: ('meetings' | 'emails')[];
442
+ /** How far back the app looks (ISO time). */
443
+ since?: string;
444
+ error?: string;
445
+ }
446
+ /**
447
+ * `capabilities.connectionTest`: an admin tests the settings in the form before (or without)
448
+ * saving them. `settings` are the values typed in the form; `secrets` only the secrets typed
449
+ * there (the app uses the saved ones for the rest). Nothing is stored.
450
+ */
451
+ export interface ConnectionTestRequest {
452
+ type: 'connection.test';
453
+ installationId: string;
454
+ workspace: string;
455
+ settings: Record<string, unknown>;
456
+ secrets: Record<string, string>;
457
+ }
458
+ /**
459
+ * The answer to a connection test. `code` is one of a small vendor-neutral set the admin explains
460
+ * in its own words: `ok`, `invalid_credentials`, `forbidden`, `not_found`, `unreachable`,
461
+ * `invalid_settings`, `error`. `details` are short facts to show (never secrets or personal data).
462
+ */
463
+ export interface ConnectionTestResult {
464
+ ok: boolean;
465
+ code: 'ok' | 'invalid_credentials' | 'forbidden' | 'not_found' | 'unreachable' | 'invalid_settings' | 'error';
466
+ message?: string;
467
+ details?: {
468
+ key: string;
469
+ value: string;
470
+ }[];
471
+ }
472
+ /** `POST /apps/user-connections` (reportUserConnection). */
473
+ export interface UserConnectionReport {
474
+ userId: string;
475
+ connectionKey: string;
476
+ kind: 'calendar' | 'mailbox' | 'drive' | 'transcripts';
477
+ status: 'connected' | 'revoked' | 'error';
478
+ shareLevel?: 'private' | 'metadata' | 'summary' | 'full';
479
+ error?: string;
480
+ /**
481
+ * The member's profile photo at the provider (for example the `picture` claim of the ID token
482
+ * the connection already returned; never a new scope for it). https on a host in the app's
483
+ * `capabilities.ui.domains`: Kennra fetches it once with the image proxy's rules, keeps a scaled
484
+ * copy and shows it as the member's avatar. Ignored unless `status` is `connected`.
485
+ */
486
+ photoUrl?: string;
487
+ }
488
+ /**
489
+ * `POST /apps/installation/setup`: the app finished its own setup flow (`capabilities.setup`)
490
+ * for the admin named in the setup ticket. The core verifies the ticket, records who approved
491
+ * which provider scopes and when (the consent record), and stores the settings the app detected
492
+ * (validated against the manifest; secrets never).
493
+ */
494
+ export interface SetupReport {
495
+ /** The setup ticket Kennra gave the admin (signed with the installation's secret). */
496
+ ticket: string;
497
+ /** Scopes the admin approved at the provider (e.g. OAuth scopes), for the consent record. */
498
+ externalScopes: string[];
499
+ /** The provider organization the admin signed in to (e.g. a Workspace domain). Not personal data. */
500
+ externalOrganization?: string;
501
+ /** Settings the app detected (only keys the manifest declares; never secrets). */
502
+ settings?: Record<string, unknown>;
503
+ }
504
+ /**
505
+ * A member disconnected in Kennra (`userConnections[].disconnectUrl`): revoke the token at the
506
+ * provider and delete it. The core has already stopped capture for the connection.
507
+ */
508
+ export interface DisconnectRequest {
509
+ type: 'user_connection.disconnected';
510
+ installationId: string;
511
+ workspace: string;
512
+ userId: string;
513
+ connectionKey: string;
514
+ kind: string;
515
+ /** Why: the member disconnected (default), or the app is being uninstalled (revoke everything). */
516
+ reason?: 'user' | 'app_uninstalled';
517
+ }
518
+ export interface LifecycleEvent {
519
+ type: 'app.installed' | 'app.updated' | 'app.paused' | 'app.resumed'
520
+ /** Sent before the uninstall, while the installation can still be read: clean up at the provider. */
521
+ | 'app.uninstalling' | 'app.uninstalled'
522
+ /** An admin saved new settings or secrets: reconnect with them. */
523
+ | 'app.settings_updated' | 'workspace.redact';
524
+ installationId: string;
525
+ workspace: string;
526
+ appId: string;
527
+ appVersion: string;
528
+ at: string;
529
+ }
530
+ export interface LookupRequest {
531
+ type: 'lookup';
532
+ object: string;
533
+ ref: string;
534
+ /**
535
+ * The structured question for objects that are looked up by attributes rather than a source ref
536
+ * (`organization.profile`: `{ domain?, identifier?: { type, country, value } }`). `ref` then
537
+ * carries the same question as a string (`domain:acme.no`, `identifier:ORG_NUMBER:NO:923609016`),
538
+ * which is what `refPattern` matches and the cache keys on.
539
+ */
540
+ query?: Record<string, unknown>;
541
+ installationId: string;
542
+ workspace: string;
543
+ purposeClass: string;
544
+ /** A stable pseudonym for the caller, never the identity. */
545
+ requestedBy: {
546
+ type: string;
547
+ pseudonym: string;
548
+ };
549
+ /** Delegated lookups: the member's connection the app answers with. */
550
+ onBehalfOf?: {
551
+ userId: string;
552
+ connectionKey: string;
553
+ };
554
+ deadline: string;
555
+ }
556
+ export interface LookupResponse<T = unknown> {
557
+ data: T;
558
+ fetchedAt?: string;
559
+ }
560
+ export interface ScheduleTick {
561
+ type: 'schedule.tick';
562
+ scheduleId: string;
563
+ runId: string;
564
+ lane: Lane;
565
+ installationId: string;
566
+ workspace: string;
567
+ lastRunId?: string;
568
+ manual?: boolean;
569
+ /**
570
+ * The longest the run may take (the schedule's `maxRunSeconds`, default 600). The SDK aborts
571
+ * the handler's signal then; the run saves its cursor and reports `partial`.
572
+ */
573
+ maxRunSeconds?: number;
574
+ /** When the run's lease runs out unless the app sends a heartbeat (`run.heartbeat()`). */
575
+ leaseExpiresAt?: string;
576
+ }
577
+ export interface WebhookEvent {
578
+ specversion: '1.0';
579
+ id: string;
580
+ type: string;
581
+ source: string;
582
+ subject?: string;
583
+ time: string;
584
+ installationId: string;
585
+ workspace: string;
586
+ data: Record<string, unknown>;
587
+ /**
588
+ * The event type declares no personal data fields and the installation's PII level is below
589
+ * `full`: `data` is withheld (fail-closed) rather than sent unfiltered.
590
+ */
591
+ dataWithheld?: true;
592
+ /**
593
+ * A test event a person sent from Developers → Webhooks or `kennra webhooks test`: sample data,
594
+ * no recorded event behind it. Signed like real deliveries; don't act on it in production.
595
+ */
596
+ test?: true;
597
+ }
598
+ /** A member in a delta: the party id and its identifiers under the app's own issuer. */
599
+ export interface SegmentSyncMember {
600
+ partyId: string;
601
+ identifiers: {
602
+ scheme: string;
603
+ value: string;
604
+ }[];
605
+ /**
606
+ * The member's usable address on the channels the target declares (`contactPoints`), when the
607
+ * grant's PII level allows contact data. A removed member carries it too while Kennra still has it.
608
+ */
609
+ contact?: {
610
+ email?: string;
611
+ phone?: string;
612
+ };
613
+ /** The person's given name, for personalization (target with contactPoints, PII level allowing). */
614
+ givenName?: string;
615
+ familyName?: string;
616
+ }
617
+ /**
618
+ * Membership changes for one sync target. Kennra resends a delivery with the same `deliveryId`
619
+ * and `idempotencyKey` until it gets a receipt, so applying it must be idempotent.
620
+ */
621
+ export interface SegmentSyncDelta {
622
+ type: 'segment.delta';
623
+ deliveryId: string;
624
+ idempotencyKey: string;
625
+ sequence: number;
626
+ installationId: string;
627
+ workspace: string;
628
+ segment: {
629
+ id: string;
630
+ name: string;
631
+ version: number;
632
+ purpose: string;
633
+ kind: 'person' | 'organization';
634
+ };
635
+ /** `id` is the sync target (one per segment and connection); `kind` the target the manifest declares. */
636
+ target: {
637
+ id: string;
638
+ kind: string;
639
+ config: Record<string, string>;
640
+ };
641
+ added: SegmentSyncMember[];
642
+ removed: SegmentSyncMember[];
643
+ /** The target was removed (or the segment archived): this delta removes everything it held. */
644
+ final?: boolean;
645
+ }
646
+ /** The app's answer: what it applied, and members it could not place (with a reason). */
647
+ export interface SegmentSyncReceipt {
648
+ deliveryId: string;
649
+ applied: {
650
+ added: number;
651
+ removed: number;
652
+ };
653
+ skipped: {
654
+ partyId: string;
655
+ reason: string;
656
+ }[];
657
+ externalRef?: string;
658
+ }
659
+ /** An enrollment in a program delta. */
660
+ export interface ProgramTargetMember extends SegmentSyncMember {
661
+ enrollmentId: string;
662
+ /** The stage the enrollment is at now (for `left`: the stage it was at). */
663
+ stage: string;
664
+ }
665
+ /**
666
+ * Enrollments that entered the target (a new active enrollment, or one that moved into the
667
+ * target's stage), moved between stages (a target for the whole program), or left it (moved
668
+ * out, completed, dropped, unenrolled, or lost the required consent). Resent unchanged until the
669
+ * app answers with a receipt; apply it idempotently.
670
+ */
671
+ export interface ProgramTargetDelta {
672
+ type: 'program.delta';
673
+ deliveryId: string;
674
+ idempotencyKey: string;
675
+ sequence: number;
676
+ installationId: string;
677
+ workspace: string;
678
+ program: {
679
+ id: string;
680
+ name: string;
681
+ version: number;
682
+ purpose: string;
683
+ };
684
+ target: {
685
+ id: string;
686
+ kind: string;
687
+ config: Record<string, string>;
688
+ stage: string | null;
689
+ };
690
+ entered: ProgramTargetMember[];
691
+ moved: ProgramTargetMember[];
692
+ left: ProgramTargetMember[];
693
+ /** The target was removed (or the program archived): this delta lets everyone leave. */
694
+ final?: boolean;
695
+ }
696
+ export interface ProgramTargetReceipt {
697
+ deliveryId: string;
698
+ applied: {
699
+ entered: number;
700
+ moved: number;
701
+ left: number;
702
+ };
703
+ skipped: {
704
+ partyId: string;
705
+ reason: string;
706
+ }[];
707
+ externalRef?: string;
708
+ }
709
+ /**
710
+ * `kennra.consent.changed` (webhook, decision 21 November 2026): a consent change for a person the
711
+ * installation holds in a segment sync or program target. No personal data beyond the app's own
712
+ * identifiers; the app stops sending at once and the next delta removes the person.
713
+ */
714
+ export interface ConsentChangedData {
715
+ partyId: string;
716
+ purpose: string;
717
+ channels: string[];
718
+ status: 'granted' | 'withdrawn';
719
+ suppression?: 'bounce' | 'complaint';
720
+ /** The app that reported the change, when an app did. */
721
+ sourceApp?: string;
722
+ occurredAt: string;
723
+ identifiers: {
724
+ scheme: string;
725
+ value: string;
726
+ }[];
727
+ }
728
+ export interface Money {
729
+ amountMinor: number;
730
+ currency: string;
731
+ }
732
+ /**
733
+ * A booked line (a rental, a reservation): the period (ISO 8601) and the source's id of the booked
734
+ * unit, when the line names one.
735
+ */
736
+ export interface LineBooking {
737
+ start: string;
738
+ end: string;
739
+ unitId?: string | null;
740
+ }
741
+ export interface OrderDetails {
742
+ paymentStatus: string | null;
743
+ paymentProviders: string[];
744
+ lines: {
745
+ name: string | null;
746
+ sku: string | null;
747
+ quantity: number;
748
+ imageUrl: string | null;
749
+ unitPrice: Money | null;
750
+ subTotal: Money | null;
751
+ /** Set when the line books something for a period (a rental). */
752
+ booking?: LineBooking | null;
753
+ }[];
754
+ meta: {
755
+ key: string;
756
+ value: string | null;
757
+ }[];
758
+ /** The order in the app's own UI ("Open in <app>"): https, on the manifest's declared hosts. */
759
+ url?: string | null;
760
+ }
761
+ export interface SubscriptionDetails {
762
+ state: string;
763
+ renewAt: string | null;
764
+ activeUntil: string | null;
765
+ item: {
766
+ sku: string;
767
+ name: string | null;
768
+ quantity: number | null;
769
+ imageUrl: string | null;
770
+ };
771
+ phases: {
772
+ name: string;
773
+ price: Money;
774
+ period: number;
775
+ unit: string;
776
+ }[];
777
+ meta: {
778
+ key: string;
779
+ value: string | null;
780
+ }[];
781
+ /** The contract in the app's own UI ("Open in <app>"): https, on the manifest's declared hosts. */
782
+ url?: string | null;
783
+ }
784
+ /**
785
+ * `invoice.details` (decision 21 November 2026): what an accounting app answers about an invoice
786
+ * now. Nothing of it is stored. `pdfUrl` is a short-lived link the app serves itself (https on the
787
+ * manifest's declared hosts); `url` is the invoice in the app's own UI, when there is one.
788
+ */
789
+ export interface InvoiceDetails {
790
+ lines: {
791
+ description: string | null;
792
+ sku: string | null;
793
+ quantity: number | null;
794
+ unitPrice: Money | null;
795
+ /** Percent, e.g. 25. */
796
+ vatRate?: number | null;
797
+ net: Money | null;
798
+ }[];
799
+ payments: {
800
+ date: string;
801
+ amount: Money;
802
+ method: string | null;
803
+ }[];
804
+ reminders: {
805
+ date: string;
806
+ kind: 'soft_reminder' | 'reminder' | 'notice_of_debt_collection' | 'debt_collection' | 'other';
807
+ fee?: Money | null;
808
+ }[];
809
+ /** The payment reference (KID in Norway), when the invoice has one. */
810
+ kid?: string | null;
811
+ pdfUrl?: string | null;
812
+ url?: string | null;
813
+ }
814
+ /**
815
+ * `interaction.details`: what the source shows of a captured meeting or email now, read with the
816
+ * owner's own connection (delegated) and never stored. For an email, `description` is the body as
817
+ * plain text; Kennra renders it as text, never as HTML.
818
+ */
819
+ export interface InteractionDetails {
820
+ /** A meeting's description or agenda; an email's body as plain text. */
821
+ description: string | null;
822
+ location: string | null;
823
+ conferenceUrl: string | null;
824
+ /** Deprecated: use `url`. */
825
+ htmlLink: string | null;
826
+ attendeeCount: number;
827
+ /** The meeting or message in the app's own UI ("Open in <app>"): https, on the manifest's declared hosts. */
828
+ url?: string | null;
829
+ /** An email's attachments: names and sizes only, never their content. */
830
+ attachments?: {
831
+ name: string;
832
+ size: number | null;
833
+ mimeType: string | null;
834
+ }[];
835
+ /** A meeting's attendees as the calendar has them now, with their responses. */
836
+ attendees?: {
837
+ name: string | null;
838
+ email: string | null;
839
+ responseStatus: 'accepted' | 'declined' | 'tentative' | 'needsAction' | null;
840
+ organizer?: boolean;
841
+ }[];
842
+ }
843
+ /**
844
+ * `document.details` (docs/15 §4.13): a document in the app's file store, live. `url` opens it in
845
+ * the app (https on the app's `ui.domains`); `thumbnailUrl` is an image Kennra shows through its
846
+ * media proxy (https on `ui.domains`) or a `data:image/…` URL; `downloadUrl` like `url`.
847
+ */
848
+ export interface DocumentDetails {
849
+ title: string;
850
+ mimeType?: string | null;
851
+ sizeBytes?: number | null;
852
+ modifiedAt?: string | null;
853
+ owner?: string | null;
854
+ url?: string | null;
855
+ thumbnailUrl?: string | null;
856
+ downloadUrl?: string | null;
857
+ }
858
+ /** One file a member picked, as the app links it (`POST /apps/documents/link`). */
859
+ export interface PickedDocument {
860
+ /** The file's id in the app (stable). */
861
+ externalId: string;
862
+ title: string;
863
+ /** The ref the app's `document.details` lookup answers. */
864
+ lookupRef?: string;
865
+ url?: string;
866
+ mimeType?: string;
867
+ sizeBytes?: number;
868
+ modifiedAt?: string;
869
+ owner?: string;
870
+ kind?: 'contract' | 'proposal' | 'other';
871
+ /** The member's connection in the app the file was picked with (delegated lookups use it). */
872
+ connectionKey?: string;
873
+ /** The document's text, in transit only: Kennra reads suggested contract terms and drops it. */
874
+ transientText?: string;
875
+ }
876
+ /** `POST /apps/documents/link`: what a member picked on the app's picker page (signed ticket). */
877
+ export interface DocumentLinkRequest {
878
+ ticket: string;
879
+ documents: PickedDocument[];
880
+ }
881
+ export interface DocumentLinkResult {
882
+ documents: {
883
+ externalId: string;
884
+ documentId: string | null;
885
+ ok: boolean;
886
+ error?: string;
887
+ }[];
888
+ /** Where to send the member back in Kennra (the record), when the ticket named it. */
889
+ returnTo?: string;
890
+ }
891
+ /**
892
+ * `organization.search`: companies in a public register that match what a person typed (a name
893
+ * or an organization number), at most 10, best match first. Public register data only.
894
+ */
895
+ export interface OrganizationSearchResult {
896
+ results: OrganizationSearchHit[];
897
+ }
898
+ export interface OrganizationSearchHit {
899
+ /** The registered legal name. */
900
+ name: string;
901
+ /** The national organization number, digits only. */
902
+ orgNumber: string;
903
+ /** ISO 3166-1 alpha-2. */
904
+ country: string;
905
+ /** The legal form's code and name in the register (e.g. `AS`, `Aksjeselskap`). */
906
+ organizationFormCode: string | null;
907
+ organizationFormName: string | null;
908
+ /** The town of the business address (or the postal address). */
909
+ city: string | null;
910
+ /** The main industry code's text. */
911
+ industry: string | null;
912
+ employees: number | null;
913
+ /** `active`, or why the company no longer trades normally. */
914
+ status: 'active' | 'bankrupt' | 'liquidation' | 'deleted';
915
+ }
916
+ /**
917
+ * A filter value of a field's scope: one value or several (any of them matches). The keys are the
918
+ * filters the object type declares (`capabilities.objects[].scope`), e.g. `{ folder: '/machines' }`.
919
+ */
920
+ export type ExternalObjectScope = Record<string, string | string[]>;
921
+ /**
922
+ * `object.search` (the picker of an `external` field): `LookupRequest.query` is
923
+ * `{ type, text, scope, limit }` and `ref` is `<type>:<text>` with the scope, for the cache. The
924
+ * answer is at most `limit` (≤ 20) objects inside the scope, best match first. An empty `text`
925
+ * asks for the first objects in the scope.
926
+ */
927
+ export interface ExternalObjectSearchQuery {
928
+ type: string;
929
+ text: string;
930
+ scope: ExternalObjectScope;
931
+ limit: number;
932
+ }
933
+ export interface ExternalObjectSearchResult {
934
+ results: ExternalObject[];
935
+ }
936
+ /**
937
+ * `object.resolve` (live data, writes and refresh): `query` is `{ type, ids }` (at most 50 ids)
938
+ * and `ref` is `<type>:<ids, sorted, comma separated>`. The answer has the objects that exist; an
939
+ * id that is not in `objects` no longer exists at the source (Kennra shows "no longer exists" and
940
+ * keeps the value).
941
+ */
942
+ export interface ExternalObjectResolveQuery {
943
+ type: string;
944
+ ids: string[];
945
+ }
946
+ export interface ExternalObjectResolveResult {
947
+ objects: ExternalObject[];
948
+ }
949
+ /**
950
+ * An object in the app's system: the envelope every object has (`id`, `title`, and optionally
951
+ * `subtitle`, `imageUrl`, `url`), the typed fields its type declares (`fields`, others are
952
+ * dropped), and for live answers the objects it is made of (`related`, e.g. a product's variants).
953
+ * `url` must be https on the app's declared hosts; `imageUrl` too, or a `data:image/…` URL: Kennra
954
+ * never hands it to a browser as is, it serves a signed short-lived link through its media proxy.
955
+ * Keep the data minimal: product data, never personal data.
956
+ */
957
+ export interface ExternalObject {
958
+ id: string;
959
+ title: string;
960
+ subtitle?: string | null;
961
+ imageUrl?: string | null;
962
+ url?: string | null;
963
+ fields?: Record<string, unknown>;
964
+ related?: {
965
+ type: string;
966
+ items: ExternalObjectRef[];
967
+ } | null;
968
+ }
969
+ export interface ExternalObjectRef {
970
+ id: string;
971
+ title: string;
972
+ subtitle?: string | null;
973
+ imageUrl?: string | null;
974
+ }
975
+ export interface MirroredFactLine {
976
+ productRef?: string;
977
+ sku?: string;
978
+ quantity: number;
979
+ netMinor?: number;
980
+ grossMinor?: number;
981
+ categoryPath?: string;
982
+ /** Set when the line books something for a period (a rental): the period and the unit. */
983
+ booking?: {
984
+ start: string;
985
+ end: string;
986
+ unitId?: string;
987
+ };
988
+ }
989
+ export interface MirroredFactSnapshot {
990
+ contract: string;
991
+ factType: 'order' | 'quote' | 'subscription' | 'invoice';
992
+ /** Must equal the app's `capabilities.ingest.sourceSystem`. */
993
+ sourceSystem: string;
994
+ sourceTenant: string;
995
+ sourceId: string;
996
+ /** `{system}:{tenant}:{type}:{id}` */
997
+ ref: string;
998
+ /** The customer's id in the source (personal data for individuals; encrypted by the core). */
999
+ customerRef?: string;
1000
+ customerType?: 'individual' | 'organization';
1001
+ organizationRef?: string;
1002
+ /** The issuer of customerRef/organizationRef: the app's registered issuer. */
1003
+ identifierIssuer?: string;
1004
+ customerScheme?: string;
1005
+ organizationScheme?: string;
1006
+ status: string;
1007
+ occurredAt: string;
1008
+ updatedAt?: string;
1009
+ orderType?: string;
1010
+ reference?: string;
1011
+ channel?: string;
1012
+ storeId?: string;
1013
+ amounts?: {
1014
+ currency: string;
1015
+ netMinor?: number;
1016
+ grossMinor?: number;
1017
+ taxMinor?: number;
1018
+ discountMinor?: number;
1019
+ shippingMinor?: number;
1020
+ };
1021
+ lines: MirroredFactLine[];
1022
+ validUntil?: string;
1023
+ /** A Kennra deal id carried by a quote. */
1024
+ dealRef?: string;
1025
+ relatedRefs?: string[];
1026
+ subscription?: {
1027
+ planRef: string;
1028
+ planName?: string;
1029
+ periodName?: string;
1030
+ sku?: string;
1031
+ quantity?: number;
1032
+ priceMinor: number;
1033
+ currency: string;
1034
+ period: number;
1035
+ unit: 'day' | 'week' | 'month' | 'year';
1036
+ state: 'active' | 'cancelled' | 'paused' | 'pendingActivation' | 'pendingDeactivation';
1037
+ recurringMrrMinor: number;
1038
+ mrrMinor: number;
1039
+ startsAt?: string;
1040
+ renewAt?: string;
1041
+ activeUntil?: string;
1042
+ /**
1043
+ * When a cancelled contract stopped (valid time), from the best source the app has. Leave it
1044
+ * out when the source gives no date: Kennra then ends the contract at its last evidence of
1045
+ * payment, never at the time it read it.
1046
+ */
1047
+ cancelledAt?: string;
1048
+ /**
1049
+ * How `cancelledAt` is known: `exact` (the source's cancellation date or event),
1050
+ * `activeUntil` (the end of the paid period), `lastRenewal` (last renewal order + one period),
1051
+ * `updatedAt` (the contract's last change), `unknown` (no date). Only the first two are not
1052
+ * estimates.
1053
+ */
1054
+ endDateSource?: 'exact' | 'activeUntil' | 'lastRenewal' | 'updatedAt' | 'unknown';
1055
+ };
1056
+ /**
1057
+ * Invoices and credit notes (factType `invoice`, decision 21 November 2026). `status` is one of
1058
+ * draft, sent, paid, partially_paid, overdue, credited, cancelled; amounts go in `amounts`
1059
+ * (negative for a credit note).
1060
+ */
1061
+ invoice?: {
1062
+ number: string;
1063
+ kind?: 'invoice' | 'credit_note';
1064
+ /** ISO dates (YYYY-MM-DD). */
1065
+ issueDate: string;
1066
+ dueDate?: string;
1067
+ /** Still to be paid, minor units of `amounts.currency`. */
1068
+ outstandingMinor: number;
1069
+ remindersSent?: number;
1070
+ lastReminderAt?: string;
1071
+ paidAt?: string;
1072
+ /** A credit note: the ref of the invoice it credits. */
1073
+ creditedInvoiceRef?: string;
1074
+ };
1075
+ }
1076
+ /** Kennra asks an app to erase a person (docs/16 §6.2). Signed like every call to the app. */
1077
+ export interface ErasureRequest {
1078
+ type: 'privacy.erasure_requested';
1079
+ requestId: string;
1080
+ installationId: string;
1081
+ workspace: string;
1082
+ partyId: string;
1083
+ /** The person's external identifiers (e.g. the app's own customer id), sent before Kennra shreds them. */
1084
+ identifiers: {
1085
+ issuer: string | null;
1086
+ scheme: string | null;
1087
+ value: string | null;
1088
+ }[];
1089
+ at: string;
1090
+ }
1091
+ /** The app's answer: done, anonymized, not found, failed, or pending (it will report later). */
1092
+ export interface ErasureReceipt {
1093
+ status: 'completed' | 'anonymized' | 'not_found' | 'failed' | 'pending';
1094
+ detail?: string;
1095
+ }
1096
+ /** A later receipt from the app (POST /apps/privacy/receipts). */
1097
+ export interface ErasureReceiptReport extends ErasureReceipt {
1098
+ requestId: string;
1099
+ }
1100
+ /**
1101
+ * A `fetch`-compatible function: what Kennra clients call and what tests inject. Narrower than
1102
+ * `typeof fetch`, whose runtime typings add extras (Bun's `fetch.preconnect`) that a plain
1103
+ * function or a test double does not have.
1104
+ */
1105
+ export type Fetch = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;