@karpoland/sdk 0.0.0-stage → 1.0.1

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,450 @@
1
+ import { v as ClientContext, ak as RequestOptions, M as MeResponse, I as Id, T as Install, C as Call, J as Json, w as CompleteOptions, x as CreateSessionInput, aN as WriteOptions, at as Session, _ as ListSessionsQuery, aL as UpdateSessionInput, G as EndSessionInput, a9 as Participant, aj as RematchResponse, aF as ShareVisibility, aE as ShareResponse, ab as ParticipantRole, c as AddParticipantResponse, aC as SetParticipantInput, aq as ScoreRow, m as BoardWhere, a7 as OpenBoardInput, k as Board, N as GetBoardQuery, Z as ListBoardsQuery, ar as SendMessageInput, as as SendMessageResponse, aD as SetTimerInput, aH as Timer, aJ as TimerWhere, ad as PostInput, ai as Relative, ae as QuotaResult, al as Resident, D as DecideJoinRequestInput, X as JoinDecision, R as RetryOptions, F as FetchLike, U as InstallRef, ax as SessionRef, e as AppErrorStatus, g as AppReason, aK as ToolCallDelivery, Q as HookEvent, S as HookEvents, P as HookDelivery, L as GateDecision } from './types-VExoR9cc.cjs';
2
+
3
+ /** At most this many ids per residents lookup. */
4
+ declare const MAX_RESIDENT_IDS = 100;
5
+ interface ClientOptions {
6
+ /** The app's key, kap_… (issued with POST /v1/apps/:app/keys). */
7
+ appKey: string;
8
+ /** The Karpo Land API origin, e.g. https://im.karpo.land. */
9
+ platform: string;
10
+ /** Act in a tool call's context (MP-Karpo-Call). */
11
+ callId?: Id;
12
+ /** Act in a hook delivery's context (MP-Karpo-Delivery). */
13
+ deliveryId?: Id;
14
+ /** Retry policy; false turns retries off. */
15
+ retry?: RetryOptions | false;
16
+ fetch?: FetchLike;
17
+ /** Extra headers on every request. */
18
+ headers?: Record<string, string>;
19
+ }
20
+ /** A join request's answer: approve or reject (remove a participant with sessions.participants.remove). */
21
+ type DecideAction = "approve" | "reject";
22
+ /**
23
+ * The platform client. Every method throws PlatformError on an error answer.
24
+ *
25
+ * Writes the platform runs at most once per key (messages.send, posts.create,
26
+ * sessions.create / end / rematch, boards.submit / publishTop) send an
27
+ * Idempotency-Key: a random one per call, reused on its retries, or
28
+ * opts.idempotencyKey. Retryable answers (retry / retry_later, 429, 503) and
29
+ * network failures of requests safe to repeat are retried up to 3 times,
30
+ * waiting at most 10 s each. Every request sends User-Agent
31
+ * karpoland-sdk-ts/<version>.
32
+ */
33
+ interface Client {
34
+ /** The context this client acts in. */
35
+ readonly context: ClientContext;
36
+ /** A copy of this client acting in another context ({} for the app's own). */
37
+ withContext(ctx: ClientContext): Client;
38
+ /** Any /v1/app-service route: request("GET", "/me"). */
39
+ request<T = unknown>(method: string, path: string, opts?: RequestOptions): Promise<T>;
40
+ /** The app itself, its live tools and session kinds. */
41
+ me(): Promise<MeResponse>;
42
+ installs: {
43
+ get(installId: Id): Promise<Install>;
44
+ };
45
+ calls: {
46
+ get(callId: Id): Promise<Call>;
47
+ /**
48
+ * Fill in an accepted (202) call's result. opts.text is posted in the room
49
+ * in the app's name when the tool is room-visible, like a prompt answer's.
50
+ * Safe to retry: a network failure is retried, and a retry that finds the
51
+ * call already finished (app.ALREADY_DONE) resolves with the call.
52
+ */
53
+ complete(callId: Id, result: Json | unknown, opts?: CompleteOptions): Promise<Call>;
54
+ /** Fail an accepted call with an app error; retried like complete. */
55
+ fail(callId: Id, error: {
56
+ status: string;
57
+ reason: string;
58
+ message?: string;
59
+ }): Promise<Call>;
60
+ };
61
+ sessions: {
62
+ create(input: CreateSessionInput, opts?: WriteOptions): Promise<Session>;
63
+ get(sessionId: Id): Promise<Session>;
64
+ /** query.status filters by state: ["open", "running"]; an unknown state is a 400. */
65
+ list(query?: ListSessionsQuery): Promise<Session[]>;
66
+ /** display.actions are the card's buttons; the platform checks them (detail.field names the bad one). */
67
+ update(sessionId: Id, input: UpdateSessionInput): Promise<Session>;
68
+ start(sessionId: Id): Promise<Session>;
69
+ pause(sessionId: Id, reason?: string): Promise<Session>;
70
+ resume(sessionId: Id): Promise<Session>;
71
+ cancel(sessionId: Id, reason?: string): Promise<Session>;
72
+ end(sessionId: Id, summary?: EndSessionInput, opts?: WriteOptions): Promise<Session>;
73
+ invite(sessionId: Id, residentIds: Id[]): Promise<Participant[]>;
74
+ /**
75
+ * Start a session like an ended or cancelled one (same install, rooms,
76
+ * kind, title, capacity, join mode, listing and host) and invite its
77
+ * players; observers and those who withdrew or were removed are not.
78
+ */
79
+ rematch(sessionId: Id, opts?: WriteOptions): Promise<RematchResponse>;
80
+ /**
81
+ * Get an invite link: always a new one, the previous link stops working
82
+ * (audited). visibility lists or unlists the session; left out, the
83
+ * listing stays as it is.
84
+ */
85
+ share(sessionId: Id, visibility?: ShareVisibility): Promise<ShareResponse>;
86
+ /** Approve or reject a join request. */
87
+ decide(sessionId: Id, residentId: Id, action: DecideAction): Promise<Participant>;
88
+ participants: {
89
+ list(sessionId: Id): Promise<Participant[]>;
90
+ /**
91
+ * Seat a resident directly (the host or the app), under the join rules:
92
+ * a member of the session's rooms, not blocking the app, a free seat.
93
+ */
94
+ add(sessionId: Id, residentId: Id, role?: ParticipantRole): Promise<AddParticipantResponse>;
95
+ set(sessionId: Id, residentId: Id, input: SetParticipantInput): Promise<Participant>;
96
+ remove(sessionId: Id, residentId: Id): Promise<Participant>;
97
+ };
98
+ };
99
+ boards: {
100
+ /** Write scores to a full board (overwrite per resident, ≤ 1000 rows). board: a key or full identifier. */
101
+ submit(board: string, rows: ScoreRow[], where?: BoardWhere, opts?: WriteOptions): Promise<string>;
102
+ /** Replace a top-only board's rows (≤ 100). */
103
+ publishTop(board: string, rows: ScoreRow[], where?: BoardWhere, opts?: WriteOptions): Promise<string>;
104
+ /** Open the next period of a manual board. */
105
+ open(board: string, input?: OpenBoardInput): Promise<Board>;
106
+ close(board: string, where?: BoardWhere): Promise<Board>;
107
+ /** Reveal a blind (app_only) board. */
108
+ reveal(board: string, where?: BoardWhere): Promise<Board>;
109
+ get(ref: string, query?: GetBoardQuery): Promise<Board>;
110
+ list(query?: ListBoardsQuery): Promise<Board[]>;
111
+ };
112
+ messages: {
113
+ send(input: SendMessageInput, opts?: WriteOptions): Promise<SendMessageResponse>;
114
+ };
115
+ timers: {
116
+ /** Set or replace the timer under key. */
117
+ set(key: string, input: SetTimerInput): Promise<Timer>;
118
+ cancel(key: string, where?: TimerWhere): Promise<void>;
119
+ list(where?: TimerWhere): Promise<Timer[]>;
120
+ };
121
+ posts: {
122
+ /** Post text to a room in the app's name (scope room:post); in_reply_to posts in that message's thread. */
123
+ create(input: PostInput, opts?: WriteOptions): Promise<Id>;
124
+ };
125
+ relations: {
126
+ /** Whether the caller and other share an owner (call context). */
127
+ sameOwner(otherId: Id): Promise<boolean>;
128
+ /** Members of an install's room. */
129
+ members(installId: Id): Promise<Relative[]>;
130
+ /** The caller's contacts, once they granted them (call context). */
131
+ contacts(): Promise<Relative[]>;
132
+ /**
133
+ * Record one use of a per-owner quota for the resident of the call or
134
+ * delivery context: a person and every agent of the same owner share
135
+ * the count. Allowed (and recorded) while fewer than n uses exist.
136
+ * key: a-z, 0-9 and _, starting with a letter, ≤ 48. Scope relation:read.
137
+ */
138
+ quota(key: string, n: number): Promise<QuotaResult>;
139
+ };
140
+ residents: {
141
+ /**
142
+ * Names and avatars of residents the app may see (members of rooms it is
143
+ * installed in, participants of its sessions, residents who called it);
144
+ * others are left out. More than 100 ids are fetched in batches.
145
+ */
146
+ get(ids: Id[]): Promise<Resident[]>;
147
+ };
148
+ joinRequests: {
149
+ /**
150
+ * Decide a room join request the app's gate left pending.
151
+ * Approving counts as the app's approval (the request is approved once
152
+ * every gate and check agrees); rejecting shows reason to the applicant.
153
+ */
154
+ decide(requestId: Id, decision: DecideJoinRequestInput): Promise<JoinDecision>;
155
+ };
156
+ }
157
+ /** createClient builds a platform client for an app's service. */
158
+ declare function createClient(opts: ClientOptions): Client;
159
+
160
+ /** Largest request body a service accepts by default (413 above). */
161
+ declare const MAX_BODY_BYTES: number;
162
+ /**
163
+ * How long a DedupeStore keeps first answers by default: 24 hours, longer
164
+ * than any platform redelivery of the same call id or delivery id (hook
165
+ * retries end after about 36 minutes; a caller's retry with the same
166
+ * idempotency key redelivers a call the platform failed to deliver).
167
+ */
168
+ declare const DEDUPE_TTL_SECONDS: number;
169
+ /** A first answer a DedupeStore keeps: the HTTP status and the body text ("" for none). */
170
+ interface DedupeAnswer {
171
+ status: number;
172
+ body: string;
173
+ }
174
+ /** What a DedupeStore knows about a key. */
175
+ type DedupeClaim =
176
+ /** Not seen: handle it now; the caller holds the claim until end(). */
177
+ {
178
+ state: "new";
179
+ }
180
+ /** Another request is handling it: answered 503, the platform retries later. */
181
+ | {
182
+ state: "in_flight";
183
+ }
184
+ /** Answered already: the first answer is replayed, the handler does not run. */
185
+ | {
186
+ state: "done";
187
+ answer: DedupeAnswer;
188
+ };
189
+ /**
190
+ * Remembers tool calls, hook deliveries and gate deliveries (the platform
191
+ * delivers at least once): a repeat within the TTL gets the first answer
192
+ * replayed, and one that arrives while the first is still running is
193
+ * answered 503 so the platform retries it later. Keys are "call:<call id>"
194
+ * and "delivery:<delivery id>". Implement it on a shared store (Redis SET NX
195
+ * with a TTL, a database row) when several instances serve the app.
196
+ */
197
+ interface DedupeStore {
198
+ /** Claim a key. */
199
+ begin(key: string): DedupeClaim | Promise<DedupeClaim>;
200
+ /**
201
+ * Record how a claimed key ended: an answer (2xx, 202 or 4xx) is kept and
202
+ * replayed; null (a 5xx or an error) releases the claim, so the platform's
203
+ * retry runs the handler again.
204
+ */
205
+ end(key: string, answer: DedupeAnswer | null): void | Promise<void>;
206
+ }
207
+ /** Options of memoryDedupe. */
208
+ interface MemoryDedupeOptions {
209
+ /** How many answers it keeps; default 10 000. */
210
+ max?: number;
211
+ /** How long it keeps each answer, in seconds; default DEDUPE_TTL_SECONDS (24 h). */
212
+ ttlSeconds?: number;
213
+ }
214
+ /** An in-memory DedupeStore: the last max answers, each kept ttlSeconds (default 10 000, 24 h). */
215
+ declare function memoryDedupe(opts?: MemoryDedupeOptions): DedupeStore;
216
+ interface Logger {
217
+ error(...args: unknown[]): void;
218
+ warn?(...args: unknown[]): void;
219
+ info?(...args: unknown[]): void;
220
+ }
221
+ interface AppOptions {
222
+ /** The Karpo Land API origin, e.g. https://api.karpo.land. */
223
+ platform?: string;
224
+ /**
225
+ * The app's service key, kap_…. With platform it is all an app needs: the
226
+ * app reads its signing secret and domain token with it (GET
227
+ * /v1/app-service/signing) at startup, and again after a delivery's
228
+ * signature fails (at most once a minute), so a rotated secret is picked
229
+ * up without a restart. ctx.karpo acts with it too.
230
+ */
231
+ appKey?: string;
232
+ /**
233
+ * Verify deliveries with this secret instead of reading it from the
234
+ * platform with appKey. For tests, and for platforms that don't serve
235
+ * GET /v1/app-service/signing yet. With it the app serves no domain
236
+ * token. It will be removed in a future major version.
237
+ */
238
+ signingSecret?: string;
239
+ /** Path prefix the service is mounted under (service_url's path), e.g. "/karpo". */
240
+ basePath?: string;
241
+ /** Largest accepted clock difference for MP-Karpo-Timestamp; default 300 s. */
242
+ maxSkewSeconds?: number;
243
+ /**
244
+ * A path prefix a reverse proxy strips before requests reach this service
245
+ * (the signature covers the path the platform posted to, i.e. the
246
+ * service_url's path). Not needed for basePath, which the service sees.
247
+ */
248
+ signaturePathPrefix?: string;
249
+ /**
250
+ * Deduplication of tool calls, hooks and gates; default in memory
251
+ * (memoryDedupe(), 24 h). Use a shared store when several instances serve
252
+ * the app; false turns it off.
253
+ */
254
+ dedupe?: DedupeStore | false;
255
+ /** Largest accepted request body; default 1 MiB (MAX_BODY_BYTES). */
256
+ maxBodyBytes?: number;
257
+ logger?: Logger;
258
+ /** Client settings for ctx.karpo (and the signing secret read). */
259
+ retry?: RetryOptions | false;
260
+ fetch?: FetchLike;
261
+ }
262
+ /** The fewest seconds between two reads of the signing secret. */
263
+ declare const SIGNING_REREAD_SECONDS = 60;
264
+ /** Returned by ctx.accepted(): the call is answered later (HTTP 202). */
265
+ declare const ACCEPTED: unique symbol;
266
+ type Accepted = typeof ACCEPTED;
267
+ /** A tool's explicit answer: the result, and text posted to the room for room-visible tools. */
268
+ interface ToolReply<R = unknown> {
269
+ result?: R;
270
+ /** At most 4000 characters; posted in the app's name when the tool is room-visible. */
271
+ text?: string;
272
+ }
273
+ /** The call a tool handler answers. */
274
+ interface CallInfo<A = Record<string, Json>> {
275
+ id: Id;
276
+ tool: string;
277
+ args: A;
278
+ idempotencyKey?: string;
279
+ /** The caller's first call to the app. */
280
+ firstSeen: boolean;
281
+ }
282
+ interface ToolContext<A = Record<string, Json>> {
283
+ /** The app's slug. */
284
+ app: string;
285
+ call: CallInfo<A>;
286
+ /** The arguments, validated by the platform against the tool's schema. */
287
+ args: A;
288
+ /** Who called; null when the platform called in the app's own context. */
289
+ caller: Resident | null;
290
+ install: InstallRef | null;
291
+ session: SessionRef | null;
292
+ /** The event that made the platform call the tool in the app's own context, or null. */
293
+ event: string | null;
294
+ /** The room message whose command ran the tool. */
295
+ commandMessageId: Id | null;
296
+ /** The platform client in this call's context (acts for the caller). */
297
+ karpo: Client;
298
+ /** Answer later: `return ctx.accepted()`, then ctx.complete(result) within 10 minutes. */
299
+ accepted(): Accepted;
300
+ /**
301
+ * Fill in this call's result after ctx.accepted(); opts.text is posted in
302
+ * the room like a prompt answer's (room-visible tools). Safe to retry.
303
+ */
304
+ complete(result: unknown, opts?: CompleteOptions): Promise<void>;
305
+ /** Fail this call after ctx.accepted(). */
306
+ fail(status: AppErrorStatus, reason: AppReason, message?: string): Promise<void>;
307
+ /**
308
+ * Accept now and run work after the response: its return value completes
309
+ * the call, an AppError fails it. `return ctx.defer(async () => …)`.
310
+ */
311
+ defer(work: () => Promise<unknown>): Accepted;
312
+ /** Keep the runtime alive for p after responding (serverless waitUntil). */
313
+ waitUntil(p: Promise<unknown>): void;
314
+ /** The raw delivery. */
315
+ raw: ToolCallDelivery;
316
+ }
317
+ interface HookContext<E extends string = string> {
318
+ app: string;
319
+ event: E;
320
+ deliveryId: Id;
321
+ /** 1 on the first attempt. */
322
+ attempt: number;
323
+ install: InstallRef | null;
324
+ sessionId: Id | null;
325
+ /** The resident the hook may act for (sender, member, timer resident…). */
326
+ residentId: Id | null;
327
+ data: E extends HookEvent ? HookEvents[E] : Record<string, unknown>;
328
+ /** The platform client in this delivery's context. */
329
+ karpo: Client;
330
+ waitUntil(p: Promise<unknown>): void;
331
+ raw: HookDelivery;
332
+ }
333
+ type ToolHandler<A = Record<string, Json>> = (ctx: ToolContext<A>, args: A) => unknown | Promise<unknown>;
334
+ type HookHandler<E extends string = string> = (ctx: HookContext<E>, data: HookContext<E>["data"]) => unknown | Promise<unknown>;
335
+ /** A room join request gate's context: residentId is the applicant. */
336
+ type GateContext = HookContext<"member.join">;
337
+ /**
338
+ * A gate's answer: a decision, or one with a reason (≤ 200 characters, shown
339
+ * to the applicant on reject). "pending" decides later with
340
+ * karpo.joinRequests.decide. undefined gives no decision: the room's admins
341
+ * decide. The first answer is replayed when the platform redelivers.
342
+ */
343
+ type GateAnswer = GateDecision | {
344
+ decision: GateDecision;
345
+ reason?: string;
346
+ } | undefined | null | void;
347
+ type GateHandler = (ctx: GateContext, data: GateContext["data"]) => GateAnswer | Promise<GateAnswer>;
348
+ /** A transport-neutral request. */
349
+ interface CoreRequest {
350
+ method: string;
351
+ /** Path without query, e.g. /tools/roll. */
352
+ path: string;
353
+ /**
354
+ * The full path the platform posted to, when a router stripped a mount
355
+ * prefix from path (Express originalUrl); default path, with basePath put
356
+ * back if missing.
357
+ */
358
+ signedPath?: string;
359
+ headers: {
360
+ get(name: string): string | null | undefined;
361
+ };
362
+ body: Uint8Array;
363
+ }
364
+ interface CoreResponse {
365
+ status: number;
366
+ headers: Record<string, string>;
367
+ body: string;
368
+ }
369
+ type WaitUntil = (p: Promise<unknown>) => void;
370
+ /** A running HTTP server (app.listen). */
371
+ interface Server {
372
+ /** The port it listens on. */
373
+ port: number;
374
+ /** http://host:port */
375
+ url: string;
376
+ /** Stop listening; resolves once open connections are done. */
377
+ close(): Promise<void>;
378
+ /** Resolves when the server stops. */
379
+ wait(): Promise<void>;
380
+ }
381
+ interface App {
382
+ /** Register a tool handler. */
383
+ tool<A = Record<string, Json>>(name: string, handler: ToolHandler<A>): App;
384
+ /** Register a hook handler; declare it in the manifest with handler: true. */
385
+ hook<E extends HookEvent>(event: E, handler: HookHandler<E>): App;
386
+ hook(event: string, handler: HookHandler<string>): App;
387
+ /**
388
+ * Decide room join requests: the manifest's {on: "member.join", gate: true}.
389
+ * Deliveries under /hooks/member.join and /hooks/join.requested (the name
390
+ * the platform moves to) both reach it. Without a decision the room's
391
+ * admins decide.
392
+ */
393
+ gate(handler: GateHandler): App;
394
+ /** Fetch-style handler: Request → Response (Workers, Deno, Bun, Vercel, Next.js). Pass the runtime's ctx to get waitUntil. */
395
+ fetch(request: Request, ...rest: unknown[]): Promise<Response>;
396
+ /** Node http handler; with Express, mount it before any body parser (or set req.rawBody). */
397
+ handler(req: NodeRequestLike, res: NodeResponseLike, next?: (err?: unknown) => void): Promise<void>;
398
+ /** Start a Node http server. */
399
+ listen(port?: number, host?: string): Promise<Server>;
400
+ /** The transport-neutral core. */
401
+ handle(req: CoreRequest, waitUntil?: WaitUntil): Promise<CoreResponse>;
402
+ /** A platform client in a context ({} for the app's own). */
403
+ client(ctx?: ClientContext): Client;
404
+ /** Change settings later; a new appKey or platform reads the signing secret again. */
405
+ configure(opts: Partial<AppOptions>): App;
406
+ /**
407
+ * Compare the handlers with the manifest; throws listing every tool and
408
+ * handler hook (handler: true) declared without a registered handler,
409
+ * every handler registered but not declared, and a gate hook ({on:
410
+ * "member.join", gate: true}) without app.gate or app.gate without one.
411
+ * Call it at startup with the manifest you publish. The publish handshake
412
+ * runs the same check on the platform's lists (missing handlers fail the
413
+ * publish).
414
+ */
415
+ check(manifest: CheckedManifest): void;
416
+ readonly tools: string[];
417
+ readonly hooks: string[];
418
+ }
419
+ /** The parts of a manifest app.check reads. */
420
+ interface CheckedManifest {
421
+ tools?: {
422
+ name: string;
423
+ }[];
424
+ hooks?: {
425
+ on: string;
426
+ handler?: boolean;
427
+ gate?: boolean;
428
+ verify?: unknown;
429
+ }[];
430
+ }
431
+ interface NodeRequestLike {
432
+ method?: string;
433
+ url?: string;
434
+ headers: Record<string, string | string[] | undefined>;
435
+ rawBody?: Uint8Array | string;
436
+ on(event: string, fn: (...a: any[]) => void): unknown;
437
+ }
438
+ interface NodeResponseLike {
439
+ writeHead(status: number, headers?: Record<string, string>): unknown;
440
+ end(body?: string): unknown;
441
+ headersSent?: boolean;
442
+ }
443
+ /**
444
+ * createApp builds an app's service. createApp({platform, appKey}) is all
445
+ * the configuration it needs; the library reads no environment variables.
446
+ */
447
+ declare function createApp(options?: AppOptions): App;
448
+
449
+ export { ACCEPTED as A, DEDUPE_TTL_SECONDS as D, MAX_BODY_BYTES as M, SIGNING_REREAD_SECONDS as S, MAX_RESIDENT_IDS as p, createApp as u, createClient as v, memoryDedupe as w };
450
+ export type { CallInfo as C, GateAnswer as G, HookContext as H, Logger as L, ToolContext as T, Accepted as a, App as b, AppOptions as c, CheckedManifest as d, Client as e, ClientOptions as f, CoreRequest as g, CoreResponse as h, DecideAction as i, DedupeAnswer as j, DedupeClaim as k, DedupeStore as l, GateContext as m, GateHandler as n, HookHandler as o, MemoryDedupeOptions as q, Server as r, ToolHandler as s, ToolReply as t };