@karpoland/sdk 1.0.0 → 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.
- package/README.ja.md +6 -6
- package/README.md +6 -6
- package/README.zh-CN.md +6 -6
- package/dist/cli.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/version.ts","../src/client.ts","../src/app.ts","../src/developer.ts","../src/manifest.ts","../src/index.ts"],"sourcesContent":["// The SDK's version; the same number in every language (spec/api.json\n// sdk_version) and in package.json.\n\nexport const SDK_VERSION = \"1.0.0\";\n\n/** What the server-side clients send as User-Agent (the page client sends none). */\nexport const USER_AGENT = `karpoland-sdk-ts/${SDK_VERSION}`;\n","// The platform client for an app's service: every /v1/app-service/* route, with the\n// app's kap_ key. Bound to a call or delivery (MP-Karpo-Call /\n// MP-Karpo-Delivery) it acts in that resident's context.\n\nimport { ALREADY_DONE, createTransport, enc, idempotencyHeader, rfc3339, type FetchLike, type RequestOptions, type RetryOptions } from \"./http.js\";\nimport { USER_AGENT } from \"./version.js\";\nimport {\n type AddParticipantResponse,\n type Board,\n type BoardWhere,\n type Call,\n type ClientContext,\n type CompleteOptions,\n type CreateSessionInput,\n type DecideJoinRequestInput,\n type EndSessionInput,\n type GetBoardQuery,\n type Id,\n type Install,\n type JoinDecision,\n type Json,\n type ListBoardsQuery,\n type ListSessionsQuery,\n type MeResponse,\n type OpenBoardInput,\n type Participant,\n type ParticipantRole,\n type PostInput,\n type QuotaResult,\n type Relative,\n type RematchResponse,\n type Resident,\n type ScoreRow,\n type SendMessageInput,\n type SendMessageResponse,\n type Session,\n type SetParticipantInput,\n type SetTimerInput,\n type ShareResponse,\n type ShareVisibility,\n type Timer,\n type TimerWhere,\n type UpdateSessionInput,\n type WriteOptions,\n} from \"./types.js\";\n\n/** At most this many ids per residents lookup. */\nexport const MAX_RESIDENT_IDS = 100;\n\nexport interface ClientOptions {\n /** The app's key, kap_… (issued with POST /v1/apps/:app/keys). */\n appKey: string;\n /** The Karpo Land API origin, e.g. https://im.karpo.land. */\n platform: string;\n /** Act in a tool call's context (MP-Karpo-Call). */\n callId?: Id;\n /** Act in a hook delivery's context (MP-Karpo-Delivery). */\n deliveryId?: Id;\n /** Retry policy; false turns retries off. */\n retry?: RetryOptions | false;\n fetch?: FetchLike;\n /** Extra headers on every request. */\n headers?: Record<string, string>;\n}\n\n/** A join request's answer: approve or reject (remove a participant with sessions.participants.remove). */\nexport type DecideAction = \"approve\" | \"reject\";\n\n/**\n * The platform client. Every method throws PlatformError on an error answer.\n *\n * Writes the platform runs at most once per key (messages.send, posts.create,\n * sessions.create / end / rematch, boards.submit / publishTop) send an\n * Idempotency-Key: a random one per call, reused on its retries, or\n * opts.idempotencyKey. Retryable answers (retry / retry_later, 429, 503) and\n * network failures of requests safe to repeat are retried up to 3 times,\n * waiting at most 10 s each. Every request sends User-Agent\n * karpoland-sdk-ts/<version>.\n */\nexport interface Client {\n /** The context this client acts in. */\n readonly context: ClientContext;\n /** A copy of this client acting in another context ({} for the app's own). */\n withContext(ctx: ClientContext): Client;\n /** Any /v1/app-service route: request(\"GET\", \"/me\"). */\n request<T = unknown>(method: string, path: string, opts?: RequestOptions): Promise<T>;\n\n /** The app itself, its live tools and session kinds. */\n me(): Promise<MeResponse>;\n installs: {\n get(installId: Id): Promise<Install>;\n };\n calls: {\n get(callId: Id): Promise<Call>;\n /**\n * Fill in an accepted (202) call's result. opts.text is posted in the room\n * in the app's name when the tool is room-visible, like a prompt answer's.\n * Safe to retry: a network failure is retried, and a retry that finds the\n * call already finished (app.ALREADY_DONE) resolves with the call.\n */\n complete(callId: Id, result: Json | unknown, opts?: CompleteOptions): Promise<Call>;\n /** Fail an accepted call with an app error; retried like complete. */\n fail(callId: Id, error: { status: string; reason: string; message?: string }): Promise<Call>;\n };\n sessions: {\n create(input: CreateSessionInput, opts?: WriteOptions): Promise<Session>;\n get(sessionId: Id): Promise<Session>;\n /** query.status filters by state: [\"open\", \"running\"]; an unknown state is a 400. */\n list(query?: ListSessionsQuery): Promise<Session[]>;\n /** display.actions are the card's buttons; the platform checks them (detail.field names the bad one). */\n update(sessionId: Id, input: UpdateSessionInput): Promise<Session>;\n start(sessionId: Id): Promise<Session>;\n pause(sessionId: Id, reason?: string): Promise<Session>;\n resume(sessionId: Id): Promise<Session>;\n cancel(sessionId: Id, reason?: string): Promise<Session>;\n end(sessionId: Id, summary?: EndSessionInput, opts?: WriteOptions): Promise<Session>;\n invite(sessionId: Id, residentIds: Id[]): Promise<Participant[]>;\n /**\n * Start a session like an ended or cancelled one (same install, rooms,\n * kind, title, capacity, join mode, listing and host) and invite its\n * players; observers and those who withdrew or were removed are not.\n */\n rematch(sessionId: Id, opts?: WriteOptions): Promise<RematchResponse>;\n /**\n * Get an invite link: always a new one, the previous link stops working\n * (audited). visibility lists or unlists the session; left out, the\n * listing stays as it is.\n */\n share(sessionId: Id, visibility?: ShareVisibility): Promise<ShareResponse>;\n /** Approve or reject a join request. */\n decide(sessionId: Id, residentId: Id, action: DecideAction): Promise<Participant>;\n participants: {\n list(sessionId: Id): Promise<Participant[]>;\n /**\n * Seat a resident directly (the host or the app), under the join rules:\n * a member of the session's rooms, not blocking the app, a free seat.\n */\n add(sessionId: Id, residentId: Id, role?: ParticipantRole): Promise<AddParticipantResponse>;\n set(sessionId: Id, residentId: Id, input: SetParticipantInput): Promise<Participant>;\n remove(sessionId: Id, residentId: Id): Promise<Participant>;\n };\n };\n boards: {\n /** Write scores to a full board (overwrite per resident, ≤ 1000 rows). board: a key or full identifier. */\n submit(board: string, rows: ScoreRow[], where?: BoardWhere, opts?: WriteOptions): Promise<string>;\n /** Replace a top-only board's rows (≤ 100). */\n publishTop(board: string, rows: ScoreRow[], where?: BoardWhere, opts?: WriteOptions): Promise<string>;\n /** Open the next period of a manual board. */\n open(board: string, input?: OpenBoardInput): Promise<Board>;\n close(board: string, where?: BoardWhere): Promise<Board>;\n /** Reveal a blind (app_only) board. */\n reveal(board: string, where?: BoardWhere): Promise<Board>;\n get(ref: string, query?: GetBoardQuery): Promise<Board>;\n list(query?: ListBoardsQuery): Promise<Board[]>;\n };\n messages: {\n send(input: SendMessageInput, opts?: WriteOptions): Promise<SendMessageResponse>;\n };\n timers: {\n /** Set or replace the timer under key. */\n set(key: string, input: SetTimerInput): Promise<Timer>;\n cancel(key: string, where?: TimerWhere): Promise<void>;\n list(where?: TimerWhere): Promise<Timer[]>;\n };\n posts: {\n /** Post text to a room in the app's name (scope room:post); in_reply_to posts in that message's thread. */\n create(input: PostInput, opts?: WriteOptions): Promise<Id>;\n };\n relations: {\n /** Whether the caller and other share an owner (call context). */\n sameOwner(otherId: Id): Promise<boolean>;\n /** Members of an install's room. */\n members(installId: Id): Promise<Relative[]>;\n /** The caller's contacts, once they granted them (call context). */\n contacts(): Promise<Relative[]>;\n /**\n * Record one use of a per-owner quota for the resident of the call or\n * delivery context: a person and every agent of the same owner share\n * the count. Allowed (and recorded) while fewer than n uses exist.\n * key: a-z, 0-9 and _, starting with a letter, ≤ 48. Scope relation:read.\n */\n quota(key: string, n: number): Promise<QuotaResult>;\n };\n residents: {\n /**\n * Names and avatars of residents the app may see (members of rooms it is\n * installed in, participants of its sessions, residents who called it);\n * others are left out. More than 100 ids are fetched in batches.\n */\n get(ids: Id[]): Promise<Resident[]>;\n };\n joinRequests: {\n /**\n * Decide a room join request the app's gate left pending.\n * Approving counts as the app's approval (the request is approved once\n * every gate and check agrees); rejecting shows reason to the applicant.\n */\n decide(requestId: Id, decision: DecideJoinRequestInput): Promise<JoinDecision>;\n };\n}\n\n/** createClient builds a platform client for an app's service. */\nexport function createClient(opts: ClientOptions): Client {\n // A service runs before it has a key (it serves its domain token first):\n // a client without one fails on use, not on creation.\n if (!opts.platform) throw new TypeError(\"createClient: platform (the API origin) is required\");\n const context = { callId: opts.callId, deliveryId: opts.deliveryId };\n const t = createTransport({\n base: opts.platform.replace(/\\/+$/, \"\") + \"/v1/app-service\",\n fetch: opts.fetch,\n retry: opts.retry,\n userAgent: USER_AGENT,\n headers: () => {\n if (!opts.appKey) throw new TypeError(\"karpoland client: no appKey (kap_…) yet; issue one and configure the app\");\n const h: Record<string, string> = { Authorization: `Bearer ${opts.appKey}`, ...opts.headers };\n if (context.callId) h[\"MP-Karpo-Call\"] = String(context.callId);\n if (context.deliveryId) h[\"MP-Karpo-Delivery\"] = String(context.deliveryId);\n return h;\n },\n });\n const req = <T>(method: string, path: string, o?: RequestOptions) => t.request<T>(method, path, o);\n const post = <T>(path: string, body: unknown = {}) => req<T>(\"POST\", path, { body });\n // A write the platform runs once per key: the key is made here, once, so\n // every retry of this call carries the same one.\n const once = async <T>(method: string, path: string, body: unknown, o?: WriteOptions) =>\n req<T>(method, path, { body, headers: idempotencyHeader(o?.idempotencyKey), idempotent: true });\n const s = (id: Id) => `/sessions/${enc(id)}`;\n\n async function residentsGet(ids: Id[]): Promise<Resident[]> {\n const want = [...new Set(ids.filter(Boolean).map(String))];\n const out: Resident[] = [];\n for (let i = 0; i < want.length; i += MAX_RESIDENT_IDS) {\n const r = await req<{ residents?: Resident[] }>(\"GET\", \"/residents\", { query: { ids: want.slice(i, i + MAX_RESIDENT_IDS).join(\",\") } });\n out.push(...(r.residents ?? []));\n }\n return out;\n }\n\n const relations = (path: string, query: Record<string, unknown> = {}) => req<any>(\"GET\", `/relations/${path}`, { query });\n // The result of an accepted call; network failures retried, and a retry\n // that finds the call finished counts as done.\n const finish = async (id: Id, body: unknown): Promise<Call> => {\n const r = await req<{ call: Call } | typeof ALREADY_DONE>(\"POST\", `/calls/${enc(id)}/result`, { body, idempotent: true, doneOnRetry: \"app.ALREADY_DONE\" });\n return r === ALREADY_DONE ? getCall(id) : r.call;\n };\n // Single-object answers are unwrapped: {session} → the session.\n const one = async <T>(key: string, p: Promise<unknown>): Promise<T> => ((await p) as Record<string, unknown>)?.[key] as T;\n const list = async <T>(key: string, p: Promise<unknown>): Promise<T[]> => (((await p) as Record<string, unknown>)?.[key] as T[] | undefined) ?? [];\n const getCall = (id: Id) => one<Call>(\"call\", req(\"GET\", `/calls/${enc(id)}`));\n const session = (p: Promise<unknown>) => one<Session>(\"session\", p);\n const participant = (p: Promise<unknown>) => one<Participant>(\"participant\", p);\n const board = (p: Promise<unknown>) => one<Board>(\"board\", p);\n\n return {\n context,\n withContext: (ctx) => createClient({ ...opts, callId: ctx.callId, deliveryId: ctx.deliveryId }),\n request: (method, path, o) => req(method, path, o),\n me: () => req(\"GET\", \"/me\"),\n installs: { get: (id) => one(\"install\", req(\"GET\", `/installs/${enc(id)}`)) },\n calls: {\n get: getCall,\n complete: (id, result, o = {}) => finish(id, { result: result === undefined ? null : result, ...(o.text ? { text: o.text } : {}) }),\n fail: (id, error) => finish(id, { error }),\n },\n sessions: {\n create: (input, o) => session(once(\"POST\", \"/sessions\", input, o)),\n get: (id) => session(req(\"GET\", s(id))),\n list: (query = {}) => {\n const { status, ...rest } = query;\n return list<Session>(\"sessions\", req(\"GET\", \"/sessions\", { query: { ...rest, status: Array.isArray(status) ? status.join(\",\") : status } }));\n },\n update: (id, input) => session(req(\"PATCH\", s(id), { body: input })),\n start: (id) => session(post(`${s(id)}/start`)),\n pause: (id, reason) => session(post(`${s(id)}/pause`, { reason })),\n resume: (id) => session(post(`${s(id)}/resume`)),\n cancel: (id, reason) => session(post(`${s(id)}/cancel`, { reason })),\n end: (id, summary = {}, o) => session(once(\"POST\", `${s(id)}/end`, summary, o)),\n invite: (id, residentIds) => list<Participant>(\"invited\", post(`${s(id)}/invite`, { resident_ids: residentIds })),\n rematch: (id, o) => once(\"POST\", `${s(id)}/rematch`, {}, o),\n share: (id, visibility) => post(`${s(id)}/share`, visibility ? { visibility } : {}),\n decide: (id, resident, action) => participant(post(`${s(id)}/participants/${enc(resident)}/${action}`)),\n participants: {\n list: (id) => list<Participant>(\"participants\", req(\"GET\", `${s(id)}/participants`)),\n add: (id, resident, role = \"player\") => post(`${s(id)}/participants`, { resident_id: resident, role }),\n set: (id, resident, input) => participant(req(\"PUT\", `${s(id)}/participants/${enc(resident)}`, { body: input })),\n remove: (id, resident) => participant(req(\"DELETE\", `${s(id)}/participants/${enc(resident)}`)),\n },\n },\n boards: {\n // Full identifiers carry \"/\" and go in the body or ?ref=.\n submit: (b, rows, where = {}, o) => one<string>(\"ref\", once(\"POST\", \"/scores\", { board: b, rows, ...where }, o)),\n publishTop: (b, rows, where = {}, o) => one<string>(\"ref\", once(\"PUT\", \"/top\", { board: b, rows, ...where }, o)),\n open: (b, input = {}) => board(post(\"/periods\", { board: b, op: \"open\", ...input })),\n close: (b, where = {}) => board(post(\"/periods\", { board: b, op: \"close\", ...where })),\n reveal: (b, where = {}) => board(post(\"/periods\", { board: b, op: \"reveal\", ...where })),\n get: (ref, query = {}) => board(req(\"GET\", \"/boards\", { query: { ref, ...query } })),\n list: (query = {}) => list<Board>(\"boards\", req(\"GET\", \"/boards\", { query: query as Record<string, unknown> })),\n },\n messages: {\n send: (input, o) => once(\"POST\", \"/messages\", { ...input, due_at: rfc3339(input.due_at) }, o),\n },\n timers: {\n set: (key, input) => one<Timer>(\"timer\", req(\"PUT\", `/timers/${enc(key)}`, { body: { ...input, at: rfc3339(input.at) } })),\n cancel: async (key, where = {}) => void (await req(\"DELETE\", `/timers/${enc(key)}`, { query: where as Record<string, unknown> })),\n list: (where = {}) => list<Timer>(\"timers\", req(\"GET\", \"/timers\", { query: where as Record<string, unknown> })),\n },\n posts: { create: (input, o) => one<Id>(\"message_id\", once(\"POST\", \"/posts\", input, o)) },\n relations: {\n sameOwner: async (otherId) => (await relations(\"same-owner\", { other_id: otherId })).same_owner === true,\n members: async (installId) => (await relations(\"members\", { install_id: installId })).residents ?? [],\n contacts: async () => (await relations(\"contacts\")).residents ?? [],\n quota: (key, n) => post(\"/relations/quota\", { key, n }),\n },\n residents: { get: residentsGet },\n joinRequests: {\n decide: (id, d) => post(`/join-requests/${enc(id)}/${d.approve ? \"approve\" : \"reject\"}`, { reason: d.reason ?? \"\" }),\n },\n };\n}\n","// The app's service: answers the platform's signed deliveries (tool calls,\n// hooks, the publish handshake) and serves the domain verification file.\n// One core (handle) with two adapters: fetch-style (Request → Response, for\n// serverless and edge) and Node http (handler / listen).\n\nimport { createClient, type Client, type ClientOptions } from \"./client.js\";\nimport { AppError, PlatformError, isReason, type AppErrorStatus, type AppReason } from \"./errors.js\";\nimport { shouldRetry, type FetchLike, type RetryOptions } from \"./http.js\";\nimport { SIGNATURE_HEADER, TIMESTAMP_HEADER, verifySignature } from \"./signing.js\";\nimport type {\n ClientContext,\n CompleteOptions,\n GateDecision,\n HandshakeDelivery,\n HookDelivery,\n HookEvent,\n HookEvents,\n Id,\n InstallRef,\n Json,\n Resident,\n SessionRef,\n ToolCallDelivery,\n} from \"./types.js\";\n\n// ----------------------------------------------------------------- options\n\n/** Largest request body a service accepts by default (413 above). */\nexport const MAX_BODY_BYTES = 1 << 20;\n\n/**\n * How long a DedupeStore keeps first answers by default: 24 hours, longer\n * than any platform redelivery of the same call id or delivery id (hook\n * retries end after about 36 minutes; a caller's retry with the same\n * idempotency key redelivers a call the platform failed to deliver).\n */\nexport const DEDUPE_TTL_SECONDS = 24 * 3600;\n\n/** A first answer a DedupeStore keeps: the HTTP status and the body text (\"\" for none). */\nexport interface DedupeAnswer {\n status: number;\n body: string;\n}\n\n/** What a DedupeStore knows about a key. */\nexport type DedupeClaim =\n /** Not seen: handle it now; the caller holds the claim until end(). */\n | { state: \"new\" }\n /** Another request is handling it: answered 503, the platform retries later. */\n | { state: \"in_flight\" }\n /** Answered already: the first answer is replayed, the handler does not run. */\n | { state: \"done\"; answer: DedupeAnswer };\n\n/**\n * Remembers tool calls, hook deliveries and gate deliveries (the platform\n * delivers at least once): a repeat within the TTL gets the first answer\n * replayed, and one that arrives while the first is still running is\n * answered 503 so the platform retries it later. Keys are \"call:<call id>\"\n * and \"delivery:<delivery id>\". Implement it on a shared store (Redis SET NX\n * with a TTL, a database row) when several instances serve the app.\n */\nexport interface DedupeStore {\n /** Claim a key. */\n begin(key: string): DedupeClaim | Promise<DedupeClaim>;\n /**\n * Record how a claimed key ended: an answer (2xx, 202 or 4xx) is kept and\n * replayed; null (a 5xx or an error) releases the claim, so the platform's\n * retry runs the handler again.\n */\n end(key: string, answer: DedupeAnswer | null): void | Promise<void>;\n}\n\n/** Options of memoryDedupe. */\nexport interface MemoryDedupeOptions {\n /** How many answers it keeps; default 10 000. */\n max?: number;\n /** How long it keeps each answer, in seconds; default DEDUPE_TTL_SECONDS (24 h). */\n ttlSeconds?: number;\n}\n\n/** An in-memory DedupeStore: the last max answers, each kept ttlSeconds (default 10 000, 24 h). */\nexport function memoryDedupe(opts: MemoryDedupeOptions = {}): DedupeStore {\n const max = opts.max ?? 10_000;\n const ttl = (opts.ttlSeconds ?? DEDUPE_TTL_SECONDS) * 1000;\n const done = new Map<string, { at: number; answer: DedupeAnswer }>();\n const inFlight = new Set<string>();\n return {\n begin(key) {\n const hit = done.get(key);\n if (hit) {\n if (Date.now() - hit.at <= ttl) return { state: \"done\", answer: hit.answer };\n done.delete(key);\n }\n if (inFlight.has(key)) return { state: \"in_flight\" };\n inFlight.add(key);\n return { state: \"new\" };\n },\n end(key, answer) {\n inFlight.delete(key);\n if (!answer) return;\n done.delete(key);\n done.set(key, { at: Date.now(), answer });\n while (done.size > max) done.delete(done.keys().next().value as string);\n },\n };\n}\n\nexport interface Logger {\n error(...args: unknown[]): void;\n warn?(...args: unknown[]): void;\n info?(...args: unknown[]): void;\n}\n\nexport interface AppOptions {\n /** The Karpo Land API origin, e.g. https://api.karpo.land. */\n platform?: string;\n /**\n * The app's service key, kap_…. With platform it is all an app needs: the\n * app reads its signing secret and domain token with it (GET\n * /v1/app-service/signing) at startup, and again after a delivery's\n * signature fails (at most once a minute), so a rotated secret is picked\n * up without a restart. ctx.karpo acts with it too.\n */\n appKey?: string;\n /**\n * Verify deliveries with this secret instead of reading it from the\n * platform with appKey. For tests, and for platforms that don't serve\n * GET /v1/app-service/signing yet. With it the app serves no domain\n * token. It will be removed in a future major version.\n */\n signingSecret?: string;\n /** Path prefix the service is mounted under (service_url's path), e.g. \"/karpo\". */\n basePath?: string;\n /** Largest accepted clock difference for MP-Karpo-Timestamp; default 300 s. */\n maxSkewSeconds?: number;\n /**\n * A path prefix a reverse proxy strips before requests reach this service\n * (the signature covers the path the platform posted to, i.e. the\n * service_url's path). Not needed for basePath, which the service sees.\n */\n signaturePathPrefix?: string;\n /**\n * Deduplication of tool calls, hooks and gates; default in memory\n * (memoryDedupe(), 24 h). Use a shared store when several instances serve\n * the app; false turns it off.\n */\n dedupe?: DedupeStore | false;\n /** Largest accepted request body; default 1 MiB (MAX_BODY_BYTES). */\n maxBodyBytes?: number;\n logger?: Logger;\n /** Client settings for ctx.karpo (and the signing secret read). */\n retry?: RetryOptions | false;\n fetch?: FetchLike;\n}\n\n/** The fewest seconds between two reads of the signing secret. */\nexport const SIGNING_REREAD_SECONDS = 60;\n\n/** Both names of the room join request event: member.join and join.requested. */\nconst JOIN_EVENTS = new Set([\"member.join\", \"join.requested\"]);\nconst eventKey = (e: string) => (JOIN_EVENTS.has(e) ? \"member.join\" : e);\n\n// ----------------------------------------------------------------- contexts\n\n/** Returned by ctx.accepted(): the call is answered later (HTTP 202). */\nexport const ACCEPTED: unique symbol = Symbol.for(\"karpoland.accepted\");\nexport type Accepted = typeof ACCEPTED;\n\n/** A tool's explicit answer: the result, and text posted to the room for room-visible tools. */\nexport interface ToolReply<R = unknown> {\n result?: R;\n /** At most 4000 characters; posted in the app's name when the tool is room-visible. */\n text?: string;\n}\n\n/** The call a tool handler answers. */\nexport interface CallInfo<A = Record<string, Json>> {\n id: Id;\n tool: string;\n args: A;\n idempotencyKey?: string;\n /** The caller's first call to the app. */\n firstSeen: boolean;\n}\n\nexport interface ToolContext<A = Record<string, Json>> {\n /** The app's slug. */\n app: string;\n call: CallInfo<A>;\n /** The arguments, validated by the platform against the tool's schema. */\n args: A;\n /** Who called; null when the platform called in the app's own context. */\n caller: Resident | null;\n install: InstallRef | null;\n session: SessionRef | null;\n /** The event that made the platform call the tool in the app's own context, or null. */\n event: string | null;\n /** The room message whose command ran the tool. */\n commandMessageId: Id | null;\n /** The platform client in this call's context (acts for the caller). */\n karpo: Client;\n /** Answer later: `return ctx.accepted()`, then ctx.complete(result) within 10 minutes. */\n accepted(): Accepted;\n /**\n * Fill in this call's result after ctx.accepted(); opts.text is posted in\n * the room like a prompt answer's (room-visible tools). Safe to retry.\n */\n complete(result: unknown, opts?: CompleteOptions): Promise<void>;\n /** Fail this call after ctx.accepted(). */\n fail(status: AppErrorStatus, reason: AppReason, message?: string): Promise<void>;\n /**\n * Accept now and run work after the response: its return value completes\n * the call, an AppError fails it. `return ctx.defer(async () => …)`.\n */\n defer(work: () => Promise<unknown>): Accepted;\n /** Keep the runtime alive for p after responding (serverless waitUntil). */\n waitUntil(p: Promise<unknown>): void;\n /** The raw delivery. */\n raw: ToolCallDelivery;\n}\n\nexport interface HookContext<E extends string = string> {\n app: string;\n event: E;\n deliveryId: Id;\n /** 1 on the first attempt. */\n attempt: number;\n install: InstallRef | null;\n sessionId: Id | null;\n /** The resident the hook may act for (sender, member, timer resident…). */\n residentId: Id | null;\n data: E extends HookEvent ? HookEvents[E] : Record<string, unknown>;\n /** The platform client in this delivery's context. */\n karpo: Client;\n waitUntil(p: Promise<unknown>): void;\n raw: HookDelivery;\n}\n\nexport type ToolHandler<A = Record<string, Json>> = (\n ctx: ToolContext<A>,\n args: A,\n) => unknown | Promise<unknown>;\n\nexport type HookHandler<E extends string = string> = (\n ctx: HookContext<E>,\n data: HookContext<E>[\"data\"],\n) => unknown | Promise<unknown>;\n\n/** A room join request gate's context: residentId is the applicant. */\nexport type GateContext = HookContext<\"member.join\">;\n\n/**\n * A gate's answer: a decision, or one with a reason (≤ 200 characters, shown\n * to the applicant on reject). \"pending\" decides later with\n * karpo.joinRequests.decide. undefined gives no decision: the room's admins\n * decide. The first answer is replayed when the platform redelivers.\n */\nexport type GateAnswer = GateDecision | { decision: GateDecision; reason?: string } | undefined | null | void;\n\nexport type GateHandler = (ctx: GateContext, data: GateContext[\"data\"]) => GateAnswer | Promise<GateAnswer>;\n\nconst GATE_DECISIONS = new Set<string>([\"approve\", \"reject\", \"pending\"]);\n\n// ------------------------------------------------------------------ core io\n\n/** A transport-neutral request. */\nexport interface CoreRequest {\n method: string;\n /** Path without query, e.g. /tools/roll. */\n path: string;\n /**\n * The full path the platform posted to, when a router stripped a mount\n * prefix from path (Express originalUrl); default path, with basePath put\n * back if missing.\n */\n signedPath?: string;\n headers: { get(name: string): string | null | undefined };\n body: Uint8Array;\n}\n\nexport interface CoreResponse {\n status: number;\n headers: Record<string, string>;\n body: string;\n}\n\ntype WaitUntil = (p: Promise<unknown>) => void;\n\n/** A running HTTP server (app.listen). */\nexport interface Server {\n /** The port it listens on. */\n port: number;\n /** http://host:port */\n url: string;\n /** Stop listening; resolves once open connections are done. */\n close(): Promise<void>;\n /** Resolves when the server stops. */\n wait(): Promise<void>;\n}\n\nexport interface App {\n /** Register a tool handler. */\n tool<A = Record<string, Json>>(name: string, handler: ToolHandler<A>): App;\n /** Register a hook handler; declare it in the manifest with handler: true. */\n hook<E extends HookEvent>(event: E, handler: HookHandler<E>): App;\n hook(event: string, handler: HookHandler<string>): App;\n /**\n * Decide room join requests: the manifest's {on: \"member.join\", gate: true}.\n * Deliveries under /hooks/member.join and /hooks/join.requested (the name\n * the platform moves to) both reach it. Without a decision the room's\n * admins decide.\n */\n gate(handler: GateHandler): App;\n /** Fetch-style handler: Request → Response (Workers, Deno, Bun, Vercel, Next.js). Pass the runtime's ctx to get waitUntil. */\n fetch(request: Request, ...rest: unknown[]): Promise<Response>;\n /** Node http handler; with Express, mount it before any body parser (or set req.rawBody). */\n handler(req: NodeRequestLike, res: NodeResponseLike, next?: (err?: unknown) => void): Promise<void>;\n /** Start a Node http server. */\n listen(port?: number, host?: string): Promise<Server>;\n /** The transport-neutral core. */\n handle(req: CoreRequest, waitUntil?: WaitUntil): Promise<CoreResponse>;\n /** A platform client in a context ({} for the app's own). */\n client(ctx?: ClientContext): Client;\n /** Change settings later; a new appKey or platform reads the signing secret again. */\n configure(opts: Partial<AppOptions>): App;\n /**\n * Compare the handlers with the manifest; throws listing every tool and\n * handler hook (handler: true) declared without a registered handler,\n * every handler registered but not declared, and a gate hook ({on:\n * \"member.join\", gate: true}) without app.gate or app.gate without one.\n * Call it at startup with the manifest you publish. The publish handshake\n * runs the same check on the platform's lists (missing handlers fail the\n * publish).\n */\n check(manifest: CheckedManifest): void;\n readonly tools: string[];\n readonly hooks: string[];\n}\n\n/** The parts of a manifest app.check reads. */\nexport interface CheckedManifest {\n tools?: { name: string }[];\n hooks?: { on: string; handler?: boolean; gate?: boolean; verify?: unknown }[];\n}\n\n/**\n * checkHandlers lists what differs between a manifest and the registered\n * handlers, as app.check reports it: \"no handler for …\" (declared, not\n * registered) and \"not in the manifest: …\" (registered, not declared), each\n * a sorted list of \"tool <name>\", \"hook <event>\" and \"gate member.join\".\n */\nexport function checkHandlers(manifest: CheckedManifest, registered: { tools: Iterable<string>; hooks: Iterable<string>; gate: boolean }): string[] {\n const tools = new Set(registered.tools);\n const hooks = new Set(registered.hooks);\n // A gate hook (gate: true, no verify) is answered by app.gate, not app.hook.\n const isGate = (h: { gate?: boolean; verify?: unknown }) => !!h.gate && h.verify == null;\n const declaredTools = new Set((manifest.tools ?? []).map((t) => t.name));\n const declaredHooks = new Set((manifest.hooks ?? []).filter((h) => h.handler && !isGate(h)).map((h) => eventKey(h.on)));\n const gated = (manifest.hooks ?? []).some(isGate);\n for (const h of [...hooks]) if (JOIN_EVENTS.has(h)) (hooks.delete(h), hooks.add(\"member.join\"));\n const missing: string[] = [];\n const extra: string[] = [];\n for (const t of declaredTools) if (!tools.has(t)) missing.push(`tool ${t}`);\n for (const t of tools) if (!declaredTools.has(t)) extra.push(`tool ${t}`);\n for (const h of declaredHooks) if (!hooks.has(h)) missing.push(`hook ${h}`);\n for (const h of hooks) if (!declaredHooks.has(h)) extra.push(`hook ${h}`);\n if (gated && !registered.gate) missing.push(\"gate member.join\");\n if (registered.gate && !gated) extra.push(\"gate member.join\");\n const problems: string[] = [];\n if (missing.length) problems.push(\"no handler for \" + missing.sort().join(\", \"));\n if (extra.length) problems.push(\"not in the manifest: \" + extra.sort().join(\", \"));\n return problems;\n}\n\nexport interface NodeRequestLike {\n method?: string;\n url?: string;\n headers: Record<string, string | string[] | undefined>;\n rawBody?: Uint8Array | string;\n on(event: string, fn: (...a: any[]) => void): unknown;\n}\nexport interface NodeResponseLike {\n writeHead(status: number, headers?: Record<string, string>): unknown;\n end(body?: string): unknown;\n headersSent?: boolean;\n}\n\nconst json = (status: number, body?: unknown): CoreResponse => ({\n status,\n headers: body === undefined ? {} : { \"Content-Type\": \"application/json; charset=utf-8\" },\n body: body === undefined ? \"\" : JSON.stringify(body),\n});\n\nconst REPLY_KEYS = new Set([\"result\", \"text\"]);\n\n/** A handler's return value as the platform reads it: {result, text}. */\nexport function toReply(out: unknown): ToolReply {\n if (out === undefined) return { result: null };\n if (out && typeof out === \"object\" && !Array.isArray(out) && Object.getPrototypeOf(out) === Object.prototype) {\n const keys = Object.keys(out);\n if (keys.length > 0 && keys.every((k) => REPLY_KEYS.has(k))) {\n const r = out as ToolReply;\n return { result: r.result === undefined ? null : r.result, ...(r.text !== undefined ? { text: r.text } : {}) };\n }\n }\n return { result: out };\n}\n\n/** How an error thrown in a handler is answered. */\nexport function errorResponse(e: unknown, kind: \"tool\" | \"hook\", log?: Logger): CoreResponse {\n if (e instanceof AppError) return json(e.httpStatus, e.toJSON());\n if (e instanceof PlatformError) {\n // The app's own key failed on a platform call (key.INVALID: revoked or\n // unknown, or another 401): a temporary failure of this service, never\n // the 401 a bad signature gets, so the platform retries.\n if (e.httpStatus === 401) {\n log?.error(isReason(e, \"key.INVALID\") ? \"karpoland: the app key is invalid or revoked (key.INVALID); issue a new key and configure the app\" : \"karpoland: the platform refused the app key\", e);\n return json(503, { status: \"UNAVAILABLE\", reason: e.reason, message: e.message });\n }\n if (kind === \"hook\" && shouldRetry(e)) return json(503, { status: e.status, reason: e.reason, message: e.message });\n // A platform refusal the handler did not catch: pass it on, so the caller\n // reads why (the platform keeps the reasons apps may return and turns the\n // rest into app.RULE_VIOLATION with the message kept).\n if (e.httpStatus >= 400 && e.httpStatus < 500) {\n return json(e.httpStatus, { status: e.status, reason: e.reason, message: e.message, action: e.action });\n }\n }\n log?.error(\"karpoland: handler failed\", e);\n return json(500, { error: \"app error\" });\n}\n\n// ------------------------------------------------------------------- create\n\n/**\n * createApp builds an app's service. createApp({platform, appKey}) is all\n * the configuration it needs; the library reads no environment variables.\n */\nexport function createApp(options: AppOptions = {}): App {\n const opts: AppOptions = { ...options };\n const tools = new Map<string, ToolHandler<any>>();\n const hooks = new Map<string, HookHandler<any>>();\n let gate: GateHandler | undefined;\n let dedupe: DedupeStore | false = opts.dedupe === undefined ? memoryDedupe() : opts.dedupe;\n const log: Logger = opts.logger ?? console;\n\n const client = (ctx: ClientContext = {}): Client => {\n if (!opts.appKey || !opts.platform) {\n return new Proxy({} as Client, {\n get(_, prop) {\n if (prop === \"then\") return undefined;\n throw new Error(`karpoland: set appKey and platform in createApp() to use the platform client (karpo.${String(prop)})`);\n },\n });\n }\n const c: ClientOptions = { appKey: opts.appKey, platform: opts.platform, retry: opts.retry, fetch: opts.fetch, ...ctx };\n return createClient(c);\n };\n\n // The signing secret and domain token, read with the app key (GET\n // /v1/app-service/signing): at startup, and again after a signature\n // fails, at most once a minute. signingSecret overrides it.\n let signing: { secret: string; domainToken: string } | null = null;\n let signingReadAt = 0;\n let signingRead: Promise<void> | null = null;\n const canReadSigning = () => !opts.signingSecret && !!opts.platform && !!opts.appKey;\n const readSigning = (): Promise<void> => {\n if (!canReadSigning()) return Promise.resolve();\n if (signingRead) return signingRead;\n if (signingReadAt && Date.now() - signingReadAt < SIGNING_REREAD_SECONDS * 1000) return Promise.resolve();\n signingReadAt = Date.now();\n signingRead = (async () => {\n try {\n const r = await client().request<Record<string, unknown>>(\"GET\", \"/signing\");\n const b = (r && typeof r.signing === \"object\" && r.signing ? r.signing : r) as Record<string, unknown>;\n if (typeof b.signing_secret === \"string\" && b.signing_secret) {\n signing = { secret: b.signing_secret, domainToken: typeof b.domain_token === \"string\" ? b.domain_token : \"\" };\n } else log.error(\"karpoland: GET /v1/app-service/signing answered without signing_secret\");\n } catch (e) {\n if (e instanceof PlatformError && isReason(e, \"key.INVALID\")) log.error(\"karpoland: the app key is invalid or revoked (key.INVALID); issue a new key and configure the app\");\n else log.error(\"karpoland: could not read the signing secret (GET /v1/app-service/signing); deliveries are answered 503 until it can. On a platform without that route, set signingSecret\", e);\n } finally {\n signingRead = null;\n }\n })();\n return signingRead;\n };\n const secret = async (): Promise<string | undefined> => {\n if (opts.signingSecret) return opts.signingSecret;\n if (!signing) await readSigning();\n return signing?.secret;\n };\n\n const stripBase = (path: string): string | null => {\n const base = (opts.basePath ?? \"\").replace(/\\/+$/, \"\");\n if (!base) return path;\n if (path === base) return \"/\";\n return path.startsWith(base + \"/\") ? path.slice(base.length) : null;\n };\n // The path the platform posted to (and signed): a prefix a proxy stripped\n // put back.\n const signedPath = (path: string): string => (opts.signaturePathPrefix ?? \"\").replace(/\\/+$/, \"\") + path;\n\n // Runs a delivery once per key: a repeat gets the first answer, one that\n // comes while the first runs gets 503. 5xx answers are not kept.\n async function once(key: string, run: () => Promise<CoreResponse>): Promise<CoreResponse> {\n const store = dedupe || null;\n if (!store) return run();\n let claim: DedupeClaim;\n try {\n claim = await store.begin(key);\n } catch (e) {\n log.error(\"karpoland: dedupe store failed\", e);\n return json(503, { error: \"dedupe unavailable\" });\n }\n if (claim.state === \"done\") {\n const a = claim.answer;\n return { status: a.status, headers: a.body ? { \"Content-Type\": \"application/json; charset=utf-8\" } : {}, body: a.body };\n }\n if (claim.state === \"in_flight\") return json(503, { error: \"delivery in progress\" });\n let res: CoreResponse;\n try {\n res = await run();\n } catch (e) {\n log.error(\"karpoland: handler failed\", e);\n res = json(500, { error: \"app error\" });\n }\n try {\n await store.end(key, res.status < 500 ? { status: res.status, body: res.body } : null);\n } catch (e) {\n log.error(\"karpoland: dedupe store failed\", e);\n }\n return res;\n }\n\n async function handle(req: CoreRequest, waitUntil?: WaitUntil): Promise<CoreResponse> {\n const method = req.method.toUpperCase();\n if (method === \"GET\" && (req.path === \"/.well-known/karpo-app.txt\" || stripBase(req.path) === \"/.well-known/karpo-app.txt\")) {\n if (!signing) await readSigning();\n if (!signing?.domainToken || opts.signingSecret) return { status: 404, headers: { \"Content-Type\": \"text/plain\" }, body: \"\" };\n return { status: 200, headers: { \"Content-Type\": \"text/plain; charset=utf-8\" }, body: signing.domainToken };\n }\n const path = stripBase(req.path);\n if (path === null) return json(404, { error: \"not found\" });\n if (method === \"GET\" && path === \"/healthz\") return json(200, { ok: true });\n const route = path === \"/.karpo/handshake\" ? \"handshake\" : path.startsWith(\"/tools/\") ? \"tool\" : path.startsWith(\"/hooks/\") ? \"hook\" : null;\n if (!route) return json(404, { error: \"not found\" });\n if (method !== \"POST\") return json(405, { error: \"use POST\" });\n if (req.body.length > (opts.maxBodyBytes ?? MAX_BODY_BYTES)) return json(413, { error: \"body too large\" });\n\n const signature = req.headers.get(SIGNATURE_HEADER);\n const headerId = String(req.headers.get(\"mp-karpo-call\") || req.headers.get(\"mp-karpo-delivery\") || \"\");\n const signed = { method, path: req.signedPath ?? signedPath(req.path), id: headerId };\n const verify = (key: string | undefined) => verifySignature(key ?? \"\", req.headers.get(TIMESTAMP_HEADER), signed, req.body, signature, { maxSkewSeconds: opts.maxSkewSeconds });\n let key = await secret();\n if (!key && canReadSigning()) return json(503, { error: \"signing secret unavailable\" });\n let why = await verify(key);\n if (why === \"mismatch\" && canReadSigning()) {\n // The secret may have been rotated: read it again (at most once a minute).\n await readSigning();\n if (signing && signing.secret !== key) {\n key = signing.secret;\n why = await verify(key);\n }\n }\n if (why) {\n if (!key) log.warn?.(\"karpoland: no signing secret (set platform and appKey); refusing deliveries\");\n return json(401, { status: \"UNAUTHENTICATED\", reason: \"auth.TOKEN_INVALID\", message: why === \"skew\" ? \"stale timestamp\" : \"bad signature\" });\n }\n let msg: any;\n try {\n msg = JSON.parse(new TextDecoder().decode(req.body));\n } catch {\n return json(400, { status: \"INVALID_ARGUMENT\", reason: \"request.BAD_TYPE\", message: \"body is not JSON\" });\n }\n if (!msg || typeof msg !== \"object\" || Array.isArray(msg)) return json(400, { status: \"INVALID_ARGUMENT\", reason: \"request.BAD_TYPE\", message: \"body is not an object\" });\n\n // Node keeps running after the response; serverless runtimes need waitUntil.\n const keepAlive: WaitUntil = (p) => {\n const guarded = p.catch((e) => log.error(\"karpoland: background work failed\", e));\n waitUntil?.(guarded);\n };\n\n // Ids come from the signed body; the signature also names the id, which\n // must be the body's.\n const bodyId = route === \"tool\" ? String((msg as ToolCallDelivery).call?.id ?? \"\") : route === \"hook\" ? String((msg as HookDelivery).delivery_id ?? \"\") : \"\";\n if (headerId !== bodyId) {\n return json(401, { status: \"UNAUTHENTICATED\", reason: \"auth.TOKEN_INVALID\", message: \"signed id differs from the body's\" });\n }\n\n if (route === \"handshake\") return handshake(msg as HandshakeDelivery);\n if (route === \"tool\") {\n const name = decodeURIComponent(path.slice(\"/tools/\".length));\n const run = () => runTool(name, msg as ToolCallDelivery, bodyId, keepAlive);\n return bodyId ? once(\"call:\" + bodyId, run) : run();\n }\n const event = decodeURIComponent(path.slice(\"/hooks/\".length));\n const run = () => (JOIN_EVENTS.has(event) && (msg as HookDelivery).gate === true ? runGate(event, msg as HookDelivery, bodyId, keepAlive) : runHook(event, msg as HookDelivery, bodyId, keepAlive));\n return bodyId ? once(\"delivery:\" + bodyId, run) : run();\n }\n\n // The publish handshake: echo the challenge. When the platform lists the\n // manifest's tools and handler hooks, every one needs a registered handler.\n function handshake(msg: HandshakeDelivery): CoreResponse {\n const missing: string[] = [];\n if (Array.isArray(msg.tools)) for (const t of msg.tools) if (!tools.has(t)) missing.push(`tool ${t}`);\n if (Array.isArray(msg.hooks)) {\n for (const h of msg.hooks) {\n const k = eventKey(h);\n if (k === \"member.join\" ? !gate && !hooks.has(\"member.join\") && !hooks.has(\"join.requested\") : !hooks.has(h)) missing.push(`hook ${h}`);\n }\n }\n if (missing.length) {\n missing.sort();\n return json(422, { status: \"FAILED_PRECONDITION\", reason: \"app.HANDSHAKE_FAILED\", message: \"no handler for \" + missing.join(\", \"), detail: { items: missing } });\n }\n return json(200, { challenge: msg.challenge });\n }\n\n async function runTool(name: string, msg: ToolCallDelivery, callId: string, keepAlive: WaitUntil): Promise<CoreResponse> {\n const fn = tools.get(name);\n if (!fn) return json(404, { status: \"NOT_FOUND\", reason: \"request.UNKNOWN_TOOL\", message: `no tool ${name} here` });\n const args = (msg.call?.args ?? {}) as Record<string, Json>;\n let accepted = false;\n const base = () => client();\n const ctx: ToolContext<any> = {\n app: msg.app,\n call: { id: callId, tool: name, args, idempotencyKey: msg.call?.idempotency_key || undefined, firstSeen: !!msg.call?.first_seen },\n args,\n caller: msg.caller ?? null,\n install: msg.install ?? null,\n session: msg.session ?? null,\n event: msg.event ?? null,\n commandMessageId: msg.command_message_id ?? null,\n karpo: client({ callId }),\n accepted() {\n accepted = true;\n return ACCEPTED;\n },\n async complete(result, opts) {\n await base().calls.complete(callId, result, opts);\n },\n async fail(status, reason, message = \"\") {\n await base().calls.fail(callId, { status, reason, message });\n },\n defer(work) {\n accepted = true;\n keepAlive(\n (async () => {\n let out: unknown;\n try {\n out = await work();\n } catch (e) {\n if (e instanceof AppError) return base().calls.fail(callId, e.toJSON());\n log.error(`karpoland: deferred work for ${name} failed`, e);\n return base().calls.fail(callId, { status: \"FAILED_PRECONDITION\", reason: \"app.RULE_VIOLATION\", message: \"the app could not finish this call\" });\n }\n const r = toReply(out);\n return base().calls.complete(callId, r.result, r.text ? { text: r.text } : undefined);\n })(),\n );\n return ACCEPTED;\n },\n waitUntil: keepAlive,\n raw: msg,\n };\n try {\n const out = await fn(ctx, args);\n if (out === ACCEPTED || accepted) return json(202, { accepted: true });\n return json(200, toReply(out));\n } catch (e) {\n return errorResponse(e, \"tool\", log);\n }\n }\n\n const hookContext = (event: string, id: string, msg: HookDelivery, keepAlive: WaitUntil): HookContext<any> => ({\n app: msg.app,\n event,\n deliveryId: id,\n attempt: msg.attempt ?? 1,\n install: msg.install ?? null,\n sessionId: msg.session_id ?? null,\n residentId: msg.resident_id ?? null,\n data: (msg.data ?? {}) as any,\n karpo: client({ deliveryId: id }),\n waitUntil: keepAlive,\n raw: msg,\n });\n\n // A room join request gate: answered with {decision, reason}; a repeat of\n // the delivery gets the first decision (once()).\n async function runGate(event: string, msg: HookDelivery, id: string, keepAlive: WaitUntil): Promise<CoreResponse> {\n if (!gate) {\n log.warn?.(\"karpoland: a join request gate delivery came but no app.gate handler is registered; the room's admins decide\");\n return json(204);\n }\n const ctx = hookContext(event, id, msg, keepAlive) as GateContext;\n let out: GateAnswer;\n try {\n out = await gate(ctx, ctx.data);\n } catch (e) {\n return errorResponse(e, \"hook\", log);\n }\n if (out === undefined || out === null) {\n log.warn?.(\"karpoland: the gate gave no decision; the room's admins decide\");\n return json(204);\n }\n const answer = typeof out === \"string\" ? { decision: out } : out;\n if (!GATE_DECISIONS.has(answer.decision)) {\n log.error(`karpoland: the gate answered ${JSON.stringify(answer.decision)}; use \"approve\", \"reject\" or \"pending\"`);\n return json(500, { error: \"app error\" });\n }\n return json(200, answer.reason ? { decision: answer.decision, reason: answer.reason } : { decision: answer.decision });\n }\n\n async function runHook(event: string, msg: HookDelivery, id: string, keepAlive: WaitUntil): Promise<CoreResponse> {\n const fn = hooks.get(event) ?? (JOIN_EVENTS.has(event) ? (hooks.get(\"member.join\") ?? hooks.get(\"join.requested\")) : undefined);\n try {\n if (fn) {\n const ctx = hookContext(event, id, msg, keepAlive);\n await fn(ctx, ctx.data);\n }\n return json(204);\n } catch (e) {\n return errorResponse(e, \"hook\", log);\n }\n }\n\n const app: App = {\n tool(name, handler) {\n tools.set(name, handler as ToolHandler<any>);\n return app;\n },\n hook(event: string, handler: HookHandler<any>) {\n hooks.set(event, handler);\n return app;\n },\n gate(handler) {\n gate = handler;\n return app;\n },\n handle,\n client,\n configure(o) {\n const rekey = (\"appKey\" in o && o.appKey !== opts.appKey) || (\"platform\" in o && o.platform !== opts.platform);\n Object.assign(opts, o);\n if (o.dedupe !== undefined) dedupe = o.dedupe;\n if (rekey) {\n signing = null;\n signingReadAt = 0;\n void readSigning();\n }\n return app;\n },\n async fetch(request: Request, ...rest: unknown[]): Promise<Response> {\n const wu = rest.find((x): x is { waitUntil: WaitUntil } => !!x && typeof (x as any).waitUntil === \"function\");\n const url = new URL(request.url);\n const body = request.method === \"GET\" || request.method === \"HEAD\" ? new Uint8Array() : new Uint8Array(await request.arrayBuffer());\n const out = await handle({ method: request.method, path: url.pathname, headers: request.headers, body }, wu ? (p) => wu.waitUntil(p) : undefined);\n return new Response(out.status === 204 || out.body === \"\" ? null : out.body, { status: out.status, headers: out.headers });\n },\n async handler(req, res, next) {\n try {\n const url = new URL(req.url ?? \"/\", \"http://app\");\n // Express sub-apps strip the mount path from req.url; originalUrl keeps\n // the path the platform signed.\n const orig = (req as { originalUrl?: string }).originalUrl;\n const signed = orig ? new URL(orig, \"http://app\").pathname : undefined;\n const body = await readNodeBody(req, opts.maxBodyBytes ?? MAX_BODY_BYTES);\n const headers = {\n get(name: string) {\n const v = req.headers[name.toLowerCase()];\n return Array.isArray(v) ? v[0] : (v ?? null);\n },\n };\n const out = await handle({ method: req.method ?? \"GET\", path: url.pathname, signedPath: signed, headers, body });\n if (out.status === 404 && next) return next();\n res.writeHead(out.status, out.headers);\n res.end(out.body);\n } catch (e) {\n if ((e as { code?: string }).code === \"TOO_LARGE\") {\n res.writeHead(413, { \"Content-Type\": \"application/json\" });\n return void res.end(JSON.stringify({ error: \"body too large\" }));\n }\n log.error(\"karpoland: request failed\", e);\n if (!res.headersSent) res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"app error\" }));\n }\n },\n async listen(port = 0, host?: string) {\n const http = await import(\"node:http\");\n const server = http.createServer((req, res) => void app.handler(req, res));\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(port, host, () => resolve());\n });\n const addr = server.address();\n const p = typeof addr === \"object\" && addr ? addr.port : port;\n const closed = new Promise<void>((resolve) => server.once(\"close\", () => resolve()));\n return {\n port: p,\n url: `http://${host && host !== \"0.0.0.0\" ? host : \"127.0.0.1\"}:${p}`,\n close: () => new Promise<void>((resolve) => server.close(() => resolve())),\n wait: () => closed,\n };\n },\n check(manifest) {\n const problems = checkHandlers(manifest, { tools: tools.keys(), hooks: hooks.keys(), gate: !!gate });\n if (problems.length) throw new Error(\"karpoland: \" + problems.join(\"; \"));\n },\n get tools() {\n return [...tools.keys()];\n },\n get hooks() {\n return [...hooks.keys()];\n },\n };\n void readSigning();\n return app;\n}\n\nfunction readNodeBody(req: NodeRequestLike, max: number): Promise<Uint8Array> {\n if (req.rawBody !== undefined) {\n return Promise.resolve(typeof req.rawBody === \"string\" ? new TextEncoder().encode(req.rawBody) : req.rawBody);\n }\n if (req.method === \"GET\" || req.method === \"HEAD\") return Promise.resolve(new Uint8Array());\n return new Promise((resolve, reject) => {\n const chunks: Uint8Array[] = [];\n let n = 0;\n req.on(\"data\", (c: Uint8Array) => {\n n += c.length;\n if (n > max) {\n reject(Object.assign(new Error(\"body too large\"), { code: \"TOO_LARGE\" }));\n return;\n }\n chunks.push(c);\n });\n req.on(\"end\", () => {\n const out = new Uint8Array(n);\n let o = 0;\n for (const c of chunks) {\n out.set(c, o);\n o += c.length;\n }\n resolve(out);\n });\n req.on(\"error\", reject);\n });\n}\n","// The developer client: registering, keying, verifying and publishing an app\n// with a person's web session or an agent's own token (kat_), as the CLI\n// does. Every route addresses the app by its numeric app_id; the slug is\n// only for apps.ensureBySlug.\n\nimport { createTransport, enc, type FetchLike, type RetryOptions } from \"./http.js\";\nimport type { Manifest } from \"./manifest.js\";\nimport type { AppRecord, MeResponse, BundleUploaded, Id, Json } from \"./types.js\";\nimport { USER_AGENT } from \"./version.js\";\n\nexport interface DeveloperClientOptions {\n /** The developer's token: an agent's kat_… (people use the creator console). */\n token: string;\n /** The Karpo Land API origin. */\n platform: string;\n retry?: RetryOptions | false;\n fetch?: FetchLike;\n}\n\nexport interface AppVersion {\n version: string;\n manifest: Manifest | null;\n handshake_at: string;\n created_at: string;\n /** The version's page bundle; empty without pages. */\n bundle_uri: string;\n bundle_sha256: string;\n}\n\n/** An app key as listed (the token is shown only when issued). */\nexport interface AppKey {\n id: Id;\n label: string;\n created_at: string;\n last_used_at: string;\n revoked_at: string;\n /** Who issued it. */\n created_by?: Id;\n}\n\n/** The input of apps.ensureBySlug: what a new app is registered with. */\nexport interface EnsureAppInput {\n /** 1–40 characters; required to register, ignored when the app exists. */\n name?: string;\n summary?: string;\n icon_url?: string;\n /** e.g. \"#3366ff\". */\n color?: string;\n}\n\n/**\n * The input of apps.update (PUT /v1/apps/{app}): only the fields given are\n * compared and written; one you may not write refuses the whole request\n * (403 with detail.needs_human).\n */\nexport interface UpdateAppInput {\n /** null clears it (the owner). A new origin goes through apps.verifyDomain. */\n service_url?: string | null;\n name?: string;\n summary?: string;\n icon_url?: string;\n color?: string;\n /** Take the app off the square and out of new rooms (the owner only). */\n delisted?: boolean;\n}\n\n/** The input of versions.publish: the version is manifest.version. */\nexport interface PublishInput {\n manifest: Manifest | Record<string, unknown>;\n /** A bundles.upload's bundle_uri; left out, the live version's pages stay. */\n bundle_uri?: string;\n}\n\n/** An app member as listed: display fields only. */\nexport interface AppMember {\n resident_id: Id;\n name: string;\n avatar_url?: string;\n kind: \"person\" | \"agent\" | string;\n role: \"owner\" | \"member\" | string;\n /** The agent that may issue a key when the app has none. */\n bootstrap?: boolean;\n added_at?: string;\n}\n\n/** A transfer of an app to another owner. */\nexport interface AppTransfer {\n id: Id;\n app_id: Id;\n state: \"pending\" | \"accepted\" | \"declined\" | \"cancelled\" | \"expired\" | string;\n to: Json;\n by?: Json;\n note?: string;\n cut_off?: boolean;\n created_at: string;\n expires_at?: string;\n}\n\n/** A row of installs.list. */\nexport interface AppInstallRow {\n install_id: Id;\n /** The version the install runs. */\n version: string;\n /** The room; only its type when you are not in it. */\n room: Json;\n installed_at: string;\n [k: string]: Json | undefined;\n}\n\n/**\n * The developer client, by resource. app is the app's numeric id\n * everywhere (KARPO_APP_ID); apps.ensureBySlug turns a slug into it.\n * Routes that only a person on the web may use (signing.rotate, members,\n * transfers.create / accept) answer an agent's token with 403\n * auth.HUMAN_ONLY and detail.needs_human: give that link to your owner.\n */\nexport interface DeveloperClient {\n apps: {\n /**\n * Register the slug, or resolve it to your app's id. 409 app.SLUG_TAKEN:\n * the slug is another app's (detail.cause use_app_id: you are a member of\n * it; configure its app_id instead).\n */\n ensureBySlug(slug: string, input?: EnsureAppInput): Promise<AppRecord>;\n /** An app; members also get the member block (owner_id, my_role, service_url, domain_verified, review). */\n get(app: Id): Promise<MeResponse>;\n list(query?: { mine?: boolean; q?: string; limit?: number }): Promise<AppRecord[]>;\n /** Change the service URL, display fields or delisted. */\n update(app: Id, input: UpdateAppInput): Promise<AppRecord>;\n /**\n * Move the service to serviceUrl after proving its origin: the domain\n * token (domain.UNVERIFIED's detail, or the service's GET\n * /v1/app-service/signing) at /.well-known/karpo-app.txt or a DNS TXT\n * record karpo-app=<token>. Any member before the app is live, the\n * owner after.\n */\n verifyDomain(app: Id, serviceUrl: string): Promise<AppRecord>;\n };\n /** The app's kap_ keys. */\n keys: {\n /** Issue a kap_ key; the token is shown once. */\n issue(app: Id, label?: string): Promise<{ key_id: Id; token: string }>;\n /** The app's keys, revoked ones included (no tokens). */\n list(app: Id): Promise<AppKey[]>;\n revoke(app: Id, keyId: Id): Promise<void>;\n };\n /** The delivery signing secret. */\n signing: {\n /** A new signing secret; revokeAllKeys also revokes every key (the owner, on the web). */\n rotate(app: Id, opts?: { revokeAllKeys?: boolean }): Promise<Record<string, Json>>;\n };\n /** The app's members (people and agents); the owner is not a member row. */\n members: {\n list(app: Id): Promise<AppMember[]>;\n /** Add a member, or set whether an agent member is the bootstrap agent (the owner). */\n set(app: Id, residentId: Id, opts?: { bootstrap?: boolean }): Promise<AppMember>;\n /** Remove a member and their agents; their keys stay until revoked. */\n remove(app: Id, residentId: Id): Promise<void>;\n };\n /** Handing the app to another person. */\n transfers: {\n /** Offer the app to a person (the owner, on the web). */\n create(app: Id, input: { to: Id; note?: string }): Promise<AppTransfer>;\n list(app: Id, query?: { state?: string; offset?: number; limit?: number }): Promise<{ transfers: AppTransfer[]; next_offset?: number }>;\n /** Transfers offered to you. */\n mine(query?: { state?: string; offset?: number; limit?: number }): Promise<{ transfers: AppTransfer[]; next_offset?: number }>;\n /**\n * Accept (the recipient, on the web). cutOff also removes the previous\n * owner and their agents, rotates the signing secret, revokes every key\n * and clears the service URL and page bundles; without it only the owner\n * changes and the previous owner stays a member.\n */\n accept(transferId: Id, opts?: { cutOff?: boolean }): Promise<AppTransfer>;\n decline(transferId: Id): Promise<AppTransfer>;\n cancel(transferId: Id): Promise<AppTransfer>;\n };\n /** Page bundles. */\n bundles: {\n /** Upload a page bundle (a zip, ≤ 10 MB); publish with its bundle_uri. */\n upload(app: Id, zip: Uint8Array | ArrayBuffer | Blob): Promise<BundleUploaded>;\n };\n /** Manifest versions. */\n versions: {\n list(app: Id): Promise<AppVersion[]>;\n /**\n * Shake hands with the service and make manifest.version live. Without\n * bundle_uri the live version's pages stay.\n */\n publish(app: Id, input: PublishInput): Promise<{ app: AppRecord; version: { version: string; handshake_at: string } }>;\n };\n /** Where the app is installed. */\n installs: {\n /** The rooms with the app and the version each runs (rooms you are not in show only their type). */\n list(app: Id, query?: { offset?: number; limit?: number }): Promise<{ installs: AppInstallRow[]; next_offset?: number }>;\n };\n /** Any /v1 route with the developer's token (e.g. routes the platform still serves for older clients). */\n request<T = unknown>(method: string, path: string, body?: unknown, query?: Record<string, unknown>): Promise<T>;\n}\n\n/** The last path segment of a bundle URI: the zip's sha256. */\nconst bundleSha = (uri: string) => uri.slice(uri.lastIndexOf(\"/\") + 1);\n\nexport function createDeveloperClient(opts: DeveloperClientOptions): DeveloperClient {\n if (!opts.token) throw new TypeError(\"createDeveloperClient: token (kat_…) is required\");\n const t = createTransport({\n base: opts.platform.replace(/\\/+$/, \"\") + \"/v1\",\n fetch: opts.fetch,\n retry: opts.retry,\n userAgent: USER_AGENT,\n headers: () => ({ Authorization: `Bearer ${opts.token}` }),\n });\n const a = (app: Id) => {\n if (!/^\\d+$/.test(String(app))) throw new TypeError(`app is the app's numeric id (KARPO_APP_ID), not ${JSON.stringify(app)}; apps.ensureBySlug gives it`);\n return `/apps/${enc(app)}`;\n };\n const tr = (id: Id) => `/app-transfers/${enc(id)}`;\n // Single-object answers are unwrapped ({app} → the app), as in the service client.\n const one = async <T>(key: string, p: Promise<unknown>): Promise<T> => ((await p) as Record<string, unknown> | null)?.[key] as T;\n const list = async <T>(key: string, p: Promise<unknown>): Promise<T[]> => (((await p) as Record<string, unknown> | null)?.[key] as T[] | undefined) ?? [];\n return {\n request: (method, path, body, query) => t.request(method, path, { body, query }),\n apps: {\n ensureBySlug: async (slug, input = {}) => {\n // Older platforms answer {app_id} without the app.\n const r = await t.request<{ app?: AppRecord; app_id?: Id }>(\"PUT\", `/apps/by-slug/${enc(slug)}`, { body: input });\n return r?.app ?? ({ id: String(r?.app_id ?? \"\") } as AppRecord);\n },\n get: (app) => t.request(\"GET\", a(app)),\n list: (query = {}) => list(\"apps\", t.request(\"GET\", \"/apps\", { query })),\n update: (app, input) => one(\"app\", t.request(\"PUT\", a(app), { body: input })),\n verifyDomain: (app, serviceUrl) => one(\"app\", t.request(\"POST\", `${a(app)}/domain/verify`, { body: { service_url: serviceUrl }, retry: false })),\n },\n keys: {\n issue: (app, label = \"\") => t.request(\"POST\", `${a(app)}/keys`, { body: { label } }),\n list: (app) => list(\"keys\", t.request(\"GET\", `${a(app)}/keys`)),\n revoke: async (app, keyId) => void (await t.request(\"DELETE\", `${a(app)}/keys/${enc(keyId)}`)),\n },\n signing: {\n rotate: (app, o = {}) => t.request(\"POST\", `${a(app)}/signing-rotations`, { body: { revoke_all_keys: !!o.revokeAllKeys }, retry: false }),\n },\n members: {\n list: (app) => list(\"members\", t.request(\"GET\", `${a(app)}/members`)),\n set: (app, resident, o = {}) => one(\"member\", t.request(\"PUT\", `${a(app)}/members/${enc(resident)}`, { body: o.bootstrap === undefined ? {} : { bootstrap: o.bootstrap } })),\n remove: async (app, resident) => void (await t.request(\"DELETE\", `${a(app)}/members/${enc(resident)}`)),\n },\n transfers: {\n create: (app, input) => one(\"transfer\", t.request(\"POST\", `${a(app)}/transfers`, { body: input, retry: false })),\n list: (app, query = {}) => t.request(\"GET\", `${a(app)}/transfers`, { query }),\n mine: (query = {}) => t.request(\"GET\", \"/me/app-transfers\", { query }),\n accept: (id, o = {}) => one(\"transfer\", t.request(\"POST\", `${tr(id)}/accept`, { body: o.cutOff ? { cut_off: true } : {}, retry: false })),\n decline: (id) => one(\"transfer\", t.request(\"POST\", `${tr(id)}/decline`, { body: {} })),\n cancel: (id) => one(\"transfer\", t.request(\"POST\", `${tr(id)}/cancel`, { body: {} })),\n },\n bundles: {\n upload: (app, zip) => t.request(\"POST\", `${a(app)}/bundles`, { body: zip, headers: { \"Content-Type\": \"application/zip\" }, retry: false }),\n },\n versions: {\n list: (app) => list(\"versions\", t.request(\"GET\", `${a(app)}/versions`)),\n publish: (app, input) => {\n const m = input.manifest as Record<string, unknown>;\n // Some platforms also want the version and the bundle's sha256 in\n // the body; both come from the manifest and the URI.\n const body: Record<string, unknown> = { manifest: m, version: m.version };\n if (input.bundle_uri) Object.assign(body, { bundle_uri: input.bundle_uri, bundle_sha256: bundleSha(input.bundle_uri) });\n return t.request(\"POST\", `${a(app)}/versions`, { body, retry: false });\n },\n },\n installs: {\n list: (app, query = {}) => t.request(\"GET\", `${a(app)}/installs`, { query }),\n },\n };\n}\n","// The manifest with the checks the platform runs at publish, so mistakes\n// show before publishing. The types follow the platform's manifest structure\n// (spec/manifest-fields.json); the validation lives only here, in\n// TypeScript (Go and Python apps run `npm exec --no -- karpoland validate`).\n// Browser safe.\n\nimport type { Json } from \"./types.js\";\n\nexport type Scope =\n | \"room:post\"\n | \"session:rw\"\n | \"board:rw\"\n | \"message:send\"\n | \"relation:read\"\n | \"contacts:read\"\n | \"timer:rw\"\n /** Every room message: message.created without filter.reply_to. Not in DMs. */\n | \"room:read\"\n /** Join requests: member.join hooks (gate, verify or handler). Not in DMs. */\n | \"room:gate\";\n\nexport const SCOPES: readonly Scope[] = [\"room:post\", \"session:rw\", \"board:rw\", \"message:send\", \"relation:read\", \"contacts:read\", \"timer:rw\", \"room:read\", \"room:gate\"];\n\nexport const HOOK_EVENTS = [\n \"app.installed\",\n \"app.uninstalled\",\n \"resident.first_seen\",\n \"message.created\",\n \"member.joined\",\n \"member.left\",\n \"member.join\",\n \"session.created\",\n \"session.started\",\n \"session.paused\",\n \"session.resumed\",\n \"session.ended\",\n \"session.cancelled\",\n \"participant.changed\",\n \"timer.fired\",\n \"app.message.replied\",\n \"app.upgraded\",\n] as const;\nexport type ManifestHookEvent = (typeof HOOK_EVENTS)[number];\n\nexport const BASE_OUTCOMES = [\"none\", \"won\", \"lost\", \"tied\", \"ranked\", \"quit\", \"timed_out\", \"disqualified\"] as const;\nexport type BaseOutcome = (typeof BASE_OUTCOMES)[number];\n\nexport interface ManifestPage {\n name: string;\n /** Starts with \"/\". */\n path: string;\n icon?: string;\n}\n\nexport interface ManifestTool {\n /** a-z, 0-9 and _, starting with a letter, at most 64. */\n name: string;\n description: string;\n /** A JSON Schema for the arguments (an object); default {type: \"object\"}. */\n parameters?: Record<string, Json>;\n /** room (default): the result and text can show in the room; caller: only the caller. */\n visibility?: \"room\" | \"caller\";\n example?: Json;\n}\n\nexport interface ManifestCommand {\n /** Room text such as \"掷骰 {sides}\"; {id} becomes the idempotency key. */\n pattern: string;\n tool: string;\n reply_to?: \"app_post\" | \"session_post\";\n}\n\n/**\n * Join questions the platform asks an applicant (member.join only): an\n * action_required app message, answered one line per question; answers are\n * compared ignoring case and white space. The platform runs it, the\n * service is not called.\n */\n/** A verify question and its accepted answers. */\nexport interface ManifestQuestion {\n q: string;\n answers: string[];\n}\n\n/** Which messages a message.created hook gets. */\nexport interface ManifestHookFilter {\n reply_to?: \"app_post\" | \"session_post\";\n pattern?: string;\n}\n\n/** A declarative hook's message. */\nexport interface ManifestSay {\n text: string;\n to?: \"room\" | \"reminder\";\n}\n\nexport interface ManifestVerify {\n /** At least one; answers are kept on the platform. */\n questions: ManifestQuestion[];\n /** How many questions to ask, picked at random; default all. */\n ask?: number;\n /** Tries before the request is declined; default 3. */\n attempts?: number;\n /** Seconds to answer; default 300. */\n time_limit?: number;\n /** Default reject. */\n on_fail?: \"reject\" | \"remove\";\n}\n\nexport interface ManifestHook {\n on: ManifestHookEvent;\n /**\n * message.created only. reply_to: app_post matches replies to the app's\n * posts (quoted, or in the thread of the install post or a session post);\n * session_post matches replies to a session post, quoted or in its thread.\n */\n filter?: ManifestHookFilter;\n /** Exactly one of handler, say and verify (gate: true alone counts as handler). */\n handler?: boolean;\n /** Text the platform posts (1–500 characters): to the room, or as a reminder to the event's resident. */\n say?: ManifestSay;\n verify?: ManifestVerify;\n /** member.join only: the service decides each join request (app.gate). */\n gate?: boolean;\n}\n\n/** A number fixed, or a default with the range a host may choose from. */\nexport type ManifestIntChoice = number | { default: number; min?: number; max?: number };\n/** A switch fixed, or left to the host. */\nexport type ManifestBoolChoice = boolean | { default: boolean; choosable?: boolean };\n\nexport interface ManifestCapacity {\n min_players?: ManifestIntChoice;\n /** 0 means no limit. */\n max_players?: ManifestIntChoice;\n observers?: ManifestBoolChoice;\n max_observers?: ManifestIntChoice;\n late_join?: ManifestBoolChoice;\n reserve_for_invitees?: ManifestBoolChoice;\n host_is_player?: ManifestBoolChoice;\n}\n\nexport interface ManifestBoard {\n /** a-z, 0-9 and _, starting with a letter, at most 32. */\n key: string;\n /** 1–20 characters. */\n name: string;\n owner?: \"session\" | \"install\" | \"app\";\n period?: \"none\" | \"day\" | \"week\" | \"month\" | \"manual\";\n tz?: string;\n order?: \"asc\" | \"desc\";\n format?: Json;\n detail?: \"full\" | \"top\";\n visibility?: \"app_only\" | \"self\" | \"participants\" | \"room_members\" | \"public\";\n /** Show it on the app square (应用广场): only owner app with visibility public. */\n square?: boolean;\n}\n\nexport type ListingCategory = \"game\" | \"social\" | \"tool\" | \"fun\" | \"work\";\nexport const LISTING_CATEGORIES: readonly ListingCategory[] = [\"game\", \"social\", \"tool\", \"fun\", \"work\"];\n\n/** How the app shows on the app square (应用广场). */\nexport interface ManifestListing {\n /** The app is on the square only when its live version says true. */\n square: boolean;\n category: ListingCategory;\n /** At most 30 characters. */\n tagline?: string;\n cover_color?: string;\n}\n\n/** A session card's fixed height: standard 380px, tall 500px (web). */\nexport type CardSize = \"standard\" | \"tall\";\nexport const CARD_SIZES: readonly CardSize[] = [\"standard\", \"tall\"];\n\n/** A session board: one period (none), every score kept (detail full). */\nexport type ManifestSessionBoard = Omit<ManifestBoard, \"owner\" | \"period\">;\n\n/** At most this many boards per session kind. */\nexport const MAX_SESSION_BOARDS = 4;\n\n/** A declared outcome, mapped to a base outcome. */\nexport interface ManifestOutcome {\n code: string;\n base: BaseOutcome;\n labels?: Record<string, string>;\n}\n\n/** The session card's layout. */\nexport interface ManifestSessionCard {\n size?: CardSize;\n}\n\nexport interface ManifestSessionKind {\n kind: string;\n title?: string;\n scopes?: (\"room\" | \"multi_room\" | \"open\")[];\n create?: \"owner\" | \"admin\" | \"member\";\n open_create?: \"anyone\" | \"app\";\n join_modes?: (\"open\" | \"approval\" | \"invite\")[];\n default_join_mode?: \"open\" | \"approval\" | \"invite\";\n listed?: boolean;\n capacity?: ManifestCapacity;\n max_open?: number;\n /** Seconds an unstarted session stays open. */\n open_ttl?: number;\n auto_start?: boolean;\n /** Seconds after start the session ends; at most 30 days. */\n auto_end?: number;\n keep_seat_on_left_room?: boolean;\n invite_by?: \"host\" | \"participants\";\n /** Up to 4 session boards (字数榜, 参与次数榜, …); the card shows them in this order. */\n boards?: ManifestSessionBoard[];\n outcomes?: ManifestOutcome[];\n labels?: Record<string, Record<string, string>>;\n /**\n * The platform delivers one tool call or hook about a session of this\n * kind at a time, in arrival order, and the next only after the previous\n * one is answered, timed out or failed (README, \"One at a time per\n * session\"). Off by default.\n */\n serial?: boolean;\n /**\n * The session card: size standard (default) or tall. The card keeps this\n * height in every tab and phase; its tabs scroll inside.\n */\n card?: ManifestSessionCard;\n}\n\n/**\n * A version's manifest: what the app can do (tools, hooks, commands, session\n * kinds, boards, pages, scopes). Display fields (name, summary, icon, color)\n * live on the app record and change with PUT /v1/apps/{app}.\n */\nexport interface Manifest {\n /**\n * 1–40 characters. The platform still requires it in the manifest until\n * display fields are read from the app record only (S1); it does not use it.\n */\n name?: string;\n /** MAJOR.MINOR.PATCH, higher than the live version; the version a publish makes live. */\n version: string;\n /** Room tabs; each path is a file in this version's page bundle. */\n pages?: ManifestPage[];\n /**\n * Origins (https or wss, no path; \"*.\" for subdomains, at most 10) the\n * pages may connect to besides Land and the app's verified domain.\n */\n connect?: string[];\n scopes?: Scope[];\n /**\n * Who may add the app to a room: anyone (default: a room's owner or\n * admins) or developer (the app's owner and members, in rooms they own or\n * administer). A developer app cannot list on the square or declare\n * open-scope session kinds (install.POLICY_CONFLICT).\n */\n install_policy?: \"anyone\" | \"developer\";\n sessions?: ManifestSessionKind[];\n boards?: ManifestBoard[];\n tools?: ManifestTool[];\n commands?: ManifestCommand[];\n hooks?: ManifestHook[];\n /** A JSON Schema for install settings; change it only compatibly (add optional fields). */\n install_config?: Record<string, Json>;\n /** The app square listing. */\n listing?: ManifestListing;\n /**\n * What this version changes (≤ 500 characters, plain text, newlines kept):\n * rooms see it in the upgrade post and the version history.\n */\n release_notes?: string;\n labels?: Record<string, string>;\n}\n\n/**\n * Keys the platform accepts in older manifests and does not read: the\n * validator lets them through. points, achievements, a session kind's\n * singular board and declarative call hooks are refused instead.\n */\nexport const MANIFEST_IGNORED = [\"summary\", \"icon\", \"color\", \"default_locale\", \"service_url\", \"hooks[].timeout\", \"hooks[].default\"] as const;\n\nexport interface ManifestIssue {\n /** The field, as the platform names it: \"manifest.tools[0].name\". */\n field: string;\n message: string;\n}\n\nexport class ManifestError extends Error {\n override readonly name = \"ManifestError\";\n constructor(readonly issues: ManifestIssue[]) {\n super(\"invalid manifest:\\n\" + issues.map((i) => ` ${i.field}: ${i.message}`).join(\"\\n\"));\n }\n}\n\n/** The longest release_notes the platform takes, in characters (runes). */\nexport const MAX_RELEASE_NOTES = 500;\n\nconst reName = /^[a-z][a-z0-9_]{0,63}$/;\nconst reKey = /^[a-z][a-z0-9_]{0,31}$/;\nconst reVersion = /^(0|[1-9][0-9]{0,5})\\.(0|[1-9][0-9]{0,5})\\.(0|[1-9][0-9]{0,5})$/;\nconst runes = (s: unknown) => (typeof s === \"string\" ? [...s].length : 0);\nconst isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === \"object\" && !Array.isArray(v);\n\nexport interface ValidateOptions {\n /** Accept http / ws connect origins (local stacks). */\n allowHttp?: boolean;\n}\n\nfunction validZone(tz: string): boolean {\n try {\n new Intl.DateTimeFormat(\"en\", { timeZone: tz });\n return true;\n } catch {\n return false;\n }\n}\n\nfunction intChoice(c: ManifestIntChoice | undefined, def: { default: number; min: number; max: number }) {\n if (c === undefined) return def;\n if (typeof c === \"number\") return { default: c, min: c, max: c };\n let { default: d, min = 0, max = 0 } = c;\n if (min === 0 && max === 0) (min = d), (max = d);\n return { default: d, min, max };\n}\n\n/** At most this many connect origins. */\nexport const MAX_CONNECT = 10;\n\nconst TOP_KEYS = [\"name\", \"version\", \"pages\", \"connect\", \"scopes\", \"install_policy\", \"sessions\", \"boards\", \"tools\", \"commands\", \"hooks\", \"install_config\", \"listing\", \"release_notes\", \"labels\"];\nconst TOOL_KEYS = [\"name\", \"description\", \"parameters\", \"visibility\", \"example\"];\nconst HOOK_KEYS = [\"on\", \"filter\", \"handler\", \"say\", \"verify\", \"gate\"];\nconst KIND_KEYS = [\"kind\", \"title\", \"scopes\", \"create\", \"open_create\", \"join_modes\", \"default_join_mode\", \"listed\", \"capacity\", \"max_open\", \"open_ttl\", \"auto_start\", \"auto_end\", \"keep_seat_on_left_room\", \"invite_by\", \"boards\", \"outcomes\", \"labels\", \"serial\", \"card\"];\n/** Keys refused with a hint (they are not \"unknown\" to the platform, but the SDK has no such field). */\nconst REFUSED: Record<string, string> = {\n points: \"points are not open to apps yet; remove manifest.points\",\n achievements: \"app-defined achievements are not open yet; remove manifest.achievements\",\n \"hooks[].call\": \"declarative call hooks are gone: use handler: true and call the tool's logic in the handler\",\n \"sessions[].board\": 'a session kind\\'s boards are a list: write boards: [ … ]',\n};\nconst reCommandLiteral = /^[^{\\s]+$/;\nconst rePagePath = /^(\\/[A-Za-z0-9._~-]+)*\\/?$/;\nconst reConnectHost = /^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;\n/** Karpo Land's own hosts: pages reach them anyway, connect cannot name them. */\nconst LAND_DOMAINS = [\"karpo.land\", \"karpo.ai\"];\n\nfunction oneEdit(a: string, b: string): boolean {\n if (Math.abs(a.length - b.length) > 1 || a === b) return false;\n let i = 0;\n let j = 0;\n let edits = 0;\n while (i < a.length && j < b.length) {\n if (a[i] === b[j]) (i++, j++);\n else {\n if (++edits > 1) return false;\n if (a.length > b.length) i++;\n else if (b.length > a.length) j++;\n else (i++, j++);\n }\n }\n return edits + (a.length - i) + (b.length - j) <= 1;\n}\n\n/** The unknown-field message, with a \"did you mean\" for a near or plural name. */\nfunction unknownKey(key: string, known: readonly string[]): string {\n const near = known.find((k) => k === key + \"s\" || oneEdit(key, k));\n return `unknown field \"${key}\"` + (near ? `; did you mean \"${near}\"?` : \"\");\n}\n\n/**\n * checkKeys reports keys of obj outside known (unknown), except the ones the\n * platform ignores; refused keys get their hint.\n */\nfunction checkKeys(obj: Record<string, unknown>, known: readonly string[], at: string, ignored: readonly string[], refusedAt: string, bad: (field: string, message: string) => void) {\n for (const k of Object.keys(obj)) {\n if (known.includes(k) || ignored.includes(k)) continue;\n const field = at ? `${at}.${k}` : k;\n bad(field, REFUSED[refusedAt ? `${refusedAt}.${k}` : k] ?? unknownKey(k, known));\n }\n}\n\n/** checkConnectOrigin returns why s is not a connect origin, or null. */\nexport function checkConnectOrigin(s: unknown, allowHttp = false): string | null {\n const want = \"an origin is https:// or wss:// and a host, e.g. https://api.example.com or https://*.example.com\";\n if (typeof s !== \"string\") return want;\n const m = s.toLowerCase().replace(/\\/$/, \"\").match(/^([a-z]+):\\/\\/([^/?#@]+)$/);\n if (!m) return want;\n const [, scheme, hostport] = m as unknown as [string, string, string];\n if (scheme !== \"https\" && scheme !== \"wss\" && !(allowHttp && (scheme === \"http\" || scheme === \"ws\"))) return want;\n const host = hostport.replace(/:\\d+$/, \"\").replace(/^\\*\\./, \"\");\n if (!reConnectHost.test(host)) return want;\n if (LAND_DOMAINS.some((d) => host === d || host.endsWith(\".\" + d))) return `${s} is Karpo Land's own host: pages reach Land without connect`;\n return null;\n}\n\n/** validateManifest returns every problem the platform would refuse at publish. */\nexport function validateManifest(m: Manifest | Record<string, unknown>, opts: ValidateOptions = {}): ManifestIssue[] {\n const issues: ManifestIssue[] = [];\n const bad = (field: string, message: string) => issues.push({ field: \"manifest\" + (field ? \".\" + field : \"\"), message });\n if (!isObj(m)) {\n bad(\"\", \"manifest is a JSON object\");\n return issues;\n }\n const man = m as unknown as Manifest;\n checkKeys(m as Record<string, unknown>, TOP_KEYS, \"\", [\"summary\", \"icon\", \"color\", \"default_locale\", \"service_url\"], \"\", bad);\n if (runes(man.name) === 0 || runes(man.name) > 40) bad(\"name\", \"name must be 1 to 40 characters (the platform still requires it in the manifest)\");\n if (typeof man.version !== \"string\" || !reVersion.test(man.version)) bad(\"version\", \"version must be MAJOR.MINOR.PATCH, e.g. 1.2.0\");\n if (man.install_policy !== undefined && man.install_policy !== \"anyone\" && man.install_policy !== \"developer\") bad(\"install_policy\", \"install_policy is anyone or developer\");\n if (man.connect !== undefined) {\n if (!Array.isArray(man.connect)) bad(\"connect\", \"connect is a list of origins\");\n else {\n if (man.connect.length > MAX_CONNECT) bad(\"connect\", `connect lists at most ${MAX_CONNECT} origins`);\n man.connect.forEach((o, i) => {\n const e = checkConnectOrigin(o, !!opts.allowHttp);\n if (e) bad(`connect[${i}]`, e);\n });\n }\n }\n (man.pages ?? []).forEach((p, i) => {\n if (!p?.name || typeof p.path !== \"string\" || !p.path.startsWith(\"/\")) return bad(`pages[${i}]`, \"a page needs a name and a path starting with /\");\n const segs = p.path.split(\"/\");\n if (!rePagePath.test(p.path) || segs.includes(\".\") || segs.includes(\"..\")) bad(`pages[${i}]`, \"a page path is plain segments of A-Z a-z 0-9 . _ ~ - (no . or .. segments, no %, \\\\, ? or #)\");\n });\n (man.scopes ?? []).forEach((s, i) => {\n if (!SCOPES.includes(s)) bad(`scopes[${i}]`, `unknown scope \"${s}\"`);\n });\n\n const tools = new Set<string>();\n if ((man.tools ?? []).length > 100) bad(\"tools\", \"at most 100 tools\");\n (man.tools ?? []).forEach((t, i) => {\n const f = `tools[${i}]`;\n if (isObj(t)) checkKeys(t, TOOL_KEYS, f, [], \"tools[]\", bad);\n if (typeof t?.name !== \"string\" || !reName.test(t.name)) bad(f + \".name\", \"tool names are a-z, 0-9 and _, starting with a letter\");\n else if (tools.has(t.name)) bad(f + \".name\", `tool \"${t.name}\" is declared twice`);\n else tools.add(t.name);\n if (t?.visibility !== undefined && t.visibility !== \"room\" && t.visibility !== \"caller\") bad(f + \".visibility\", \"visibility is room or caller\");\n if (t?.parameters !== undefined) {\n if (!isObj(t.parameters)) bad(f + \".parameters\", \"parameters is not a valid JSON Schema: must be an object\");\n else if (t.parameters.type !== undefined && t.parameters.type !== \"object\") bad(f + \".parameters\", \"arguments are a JSON object: parameters.type must be \\\"object\\\"\");\n }\n });\n\n const boards = new Set<string>();\n const addBoard = (b: ManifestBoard | undefined, field: string, sessionBoard: boolean) => {\n if (!isObj(b)) return bad(field, \"a board is an object\");\n if (typeof b.key !== \"string\" || !reKey.test(b.key)) return bad(field, \"board keys are a-z, 0-9 and _, starting with a letter, at most 32\");\n if (boards.has(b.key)) return bad(field, `board \"${b.key}\" is declared twice`);\n if (runes(b.name) === 0 || runes(b.name) > 20) return bad(field, \"board name is 1 to 20 characters\");\n const owner = sessionBoard ? \"session\" : (b.owner ?? \"install\");\n if (![\"session\", \"install\", \"app\"].includes(owner)) return bad(field, \"an app's board belongs to a session, an install or the app\");\n const period = b.period ?? \"none\";\n if (![\"none\", \"day\", \"week\", \"month\", \"manual\"].includes(period)) return bad(field, \"period is none, day, week, month or manual\");\n if (owner === \"session\" && period !== \"none\") return bad(field, \"a session board has one period\");\n if (b.order !== undefined && b.order !== \"asc\" && b.order !== \"desc\") return bad(field, \"order is asc or desc\");\n const detail = b.detail ?? \"full\";\n if (detail !== \"full\" && detail !== \"top\") return bad(field, \"detail is full or top\");\n if (owner === \"session\" && detail !== \"full\") return bad(field, \"a session board keeps every score\");\n if (b.visibility !== undefined && ![\"app_only\", \"self\", \"participants\", \"room_members\", \"public\"].includes(b.visibility)) return bad(field, `unknown visibility \"${b.visibility}\"`);\n if (b.tz && !validZone(b.tz)) return bad(field, `unknown time zone \"${b.tz}\"`);\n if (b.square !== undefined && b.square !== null && typeof b.square !== \"boolean\") return bad(field, \"square is true or false\");\n // App boards are public unless they say otherwise.\n if (b.square && (owner !== \"app\" || (b.visibility ?? \"public\") !== \"public\")) return bad(field, \"only a public app board shows on the square\");\n boards.add(b.key);\n };\n\n const kinds = new Set<string>();\n (man.sessions ?? []).forEach((k, i) => {\n const f = `sessions[${i}]`;\n if (isObj(k)) checkKeys(k, KIND_KEYS, f, [], \"sessions[]\", bad);\n const err = sessionKindError(k);\n if (err) return bad(f, err);\n if (kinds.has(k.kind)) return bad(f + \".kind\", `session kind \"${k.kind}\" is declared twice`);\n if (k.card !== undefined && k.card !== null) {\n if (!isObj(k.card)) return bad(f + \".card\", \"card is an object\");\n if (k.card.size !== undefined && !(CARD_SIZES as readonly unknown[]).includes(k.card.size)) return bad(f + \".card.size\", \"card.size is standard or tall\");\n }\n kinds.add(k.kind);\n if (k.boards !== undefined) {\n if (!Array.isArray(k.boards)) return bad(f + \".boards\", \"boards is a list\");\n if (k.boards.length > MAX_SESSION_BOARDS) return bad(f + \".boards\", `at most ${MAX_SESSION_BOARDS} boards per session kind`);\n k.boards.forEach((b, j) => addBoard({ ...b, owner: \"session\" }, `${f}.boards[${j}]`, true));\n }\n });\n (man.boards ?? []).forEach((b, i) => addBoard(b, `boards[${i}]`, false));\n\n (man.commands ?? []).forEach((c, i) => {\n const f = `commands[${i}]`;\n if (!tools.has(c?.tool)) return bad(f + \".tool\", `command calls unknown tool \"${c?.tool}\"`);\n if (c.reply_to !== undefined && c.reply_to !== \"app_post\" && c.reply_to !== \"session_post\") return bad(f + \".reply_to\", \"reply_to is app_post or session_post\");\n const p = typeof c.pattern === \"string\" ? c.pattern.trim() : \"\";\n if (p === \"\" || runes(p) > 100) return bad(f + \".pattern\", \"a command pattern is 1 to 100 characters\");\n // A room command without reply_to starts with a literal word; other text\n // goes to reply_to or a message.created hook with room:read.\n if (c.reply_to === undefined && !reCommandLiteral.test(p.split(/\\s+/)[0] ?? \"\")) bad(f + \".pattern\", \"a command without reply_to starts with a literal word (no {variable}); for any text use reply_to or a message.created hook with room:read\");\n });\n\n (man.hooks ?? []).forEach((h, i) => {\n const f = `hooks[${i}]`;\n if (isObj(h)) checkKeys(h, HOOK_KEYS, f, [\"timeout\", \"default\"], \"hooks[]\", bad);\n if (!(HOOK_EVENTS as readonly string[]).includes(h?.on)) return bad(f + \".on\", `unknown event \"${h?.on}\"`);\n let forms = [!!h.handler, h.say != null, h.verify != null].filter(Boolean).length;\n // {on: \"member.join\", gate: true}: the service decides.\n if (h.gate && forms === 0) forms = 1;\n if (forms !== 1 && (h as { call?: unknown }).call == null) return bad(f, \"a hook has exactly one of handler, say and verify\");\n if (h.verify) {\n if (h.on !== \"member.join\") return bad(f + \".verify\", \"verify answers member.join only\");\n if (!h.verify.questions?.length) return bad(f + \".verify.questions\", \"verify needs at least one question\");\n }\n if (h.say && (!h.say.text || runes(h.say.text) > 500)) return bad(f + \".say.text\", \"say text is 1 to 500 characters\");\n if (h.gate && h.on !== \"member.join\") return bad(f + \".gate\", \"only member.join hooks gate\");\n if (h.filter?.pattern) {\n try {\n new RegExp(h.filter.pattern);\n } catch (e) {\n return bad(f + \".filter.pattern\", (e as Error).message);\n }\n }\n // The platform refuses to publish these without their scope.\n if (h.on === \"message.created\" && !h.filter?.reply_to && !(man.scopes ?? []).includes(\"room:read\"))\n return bad(f, \"a message.created hook without filter.reply_to receives every room message: declare the room:read scope\");\n if (h.on === \"member.join\" && !(man.scopes ?? []).includes(\"room:gate\")) return bad(f, \"member.join hooks see join requests: declare the room:gate scope\");\n });\n if (man.listing !== undefined && man.listing !== null) {\n const l = man.listing as unknown;\n if (!isObj(l)) bad(\"listing\", \"listing is an object\");\n else {\n if (l.square !== undefined && typeof l.square !== \"boolean\") bad(\"listing.square\", \"square is true or false\");\n if (!(LISTING_CATEGORIES as readonly unknown[]).includes(l.category)) bad(\"listing.category\", \"category is game, social, tool, fun or work\");\n if (l.tagline !== undefined && (typeof l.tagline !== \"string\" || runes(l.tagline) > 30)) bad(\"listing.tagline\", \"tagline is at most 30 characters\");\n if (l.cover_color !== undefined && typeof l.cover_color !== \"string\") bad(\"listing.cover_color\", \"cover_color is a string\");\n }\n }\n if (man.install_policy === \"developer\") {\n // install.POLICY_CONFLICT: a developer app stays in its developers' rooms.\n if (isObj(man.listing) && man.listing.square === true) bad(\"install_policy\", \"install_policy developer keeps the app in its developers' rooms: it cannot list on the square (listing.square)\");\n else if ((man.sessions ?? []).some((k) => isObj(k) && Array.isArray(k.scopes) && k.scopes.includes(\"open\")))\n bad(\"install_policy\", \"install_policy developer keeps the app in its developers' rooms: it cannot declare an open-scope session kind\");\n }\n if (man.release_notes !== undefined && man.release_notes !== null) {\n if (typeof man.release_notes !== \"string\") bad(\"release_notes\", \"release_notes is text\");\n else if (runes(man.release_notes) > MAX_RELEASE_NOTES) bad(\"release_notes\", `release_notes is at most ${MAX_RELEASE_NOTES} characters`);\n }\n if (man.install_config !== undefined && man.install_config !== null && !isObj(man.install_config)) bad(\"install_config\", \"install_config is not a valid JSON Schema: must be an object\");\n return issues;\n}\n\nfunction sessionKindError(k: ManifestSessionKind): string | null {\n if (!isObj(k) || typeof k.kind !== \"string\" || !reKey.test(k.kind)) return \"kind is a-z, 0-9 and _, starting with a letter\";\n for (const s of k.scopes ?? []) if (![\"room\", \"multi_room\", \"open\"].includes(s)) return \"scopes are room, multi_room and open\";\n if (k.create !== undefined && ![\"owner\", \"admin\", \"member\"].includes(k.create)) return \"create is owner, admin or member\";\n if (k.open_create !== undefined && ![\"anyone\", \"app\"].includes(k.open_create)) return \"open_create is anyone or app\";\n const modes = k.join_modes?.length ? k.join_modes : [\"open\", \"approval\", \"invite\"];\n for (const j of modes) if (![\"open\", \"approval\", \"invite\"].includes(j)) return \"join modes are open, approval and invite\";\n if (k.default_join_mode !== undefined && !modes.includes(k.default_join_mode)) return \"default_join_mode must be one of join_modes\";\n if (k.invite_by !== undefined && ![\"host\", \"participants\"].includes(k.invite_by)) return \"invite_by is host or participants\";\n const c = k.capacity ?? {};\n const ranges = [\n intChoice(c.min_players, { default: 1, min: 1, max: 1000 }),\n intChoice(c.max_players, { default: 0, min: 0, max: 1000 }),\n intChoice(c.max_observers, { default: 0, min: 0, max: 1000 }),\n ];\n for (const r of ranges) {\n if (r.min > r.default || (r.max > 0 && r.default > r.max) || r.max > 1000 || r.min < 0) return \"capacity defaults must lie within their ranges, at most 1000\";\n }\n if (k.auto_end !== undefined && (k.auto_end < 0 || k.auto_end > 30 * 24 * 3600)) return \"auto_end is at most 30 days\";\n if (k.serial !== undefined && typeof k.serial !== \"boolean\") return \"serial is true or false\";\n if ((k.outcomes ?? []).length > 10) return \"at most 10 custom outcomes\";\n for (const o of k.outcomes ?? []) {\n if (!(BASE_OUTCOMES as readonly string[]).includes(o?.base) || !reKey.test(o?.code ?? \"\")) return \"a custom outcome has a code and a base outcome\";\n }\n return null;\n}\n\n/**\n * defineManifest checks a manifest and returns it unchanged, typed. It\n * throws ManifestError listing every problem the platform would refuse.\n */\nexport function defineManifest<M extends Manifest>(manifest: M, opts?: ValidateOptions): M {\n const issues = validateManifest(manifest, opts);\n if (issues.length) throw new ManifestError(issues);\n return manifest;\n}\n","// @karpoland/sdk: the official SDK for Karpo Land mini apps.\n//\n// import { createApp, AppError } from \"@karpoland/sdk\";\n// const app = createApp({ platform: process.env.KARPO_API!, appKey: process.env.KARPO_APP_KEY! });\n// app.tool(\"roll\", (ctx, args) => ({ result: { n: 4 }, text: `${ctx.caller?.name} 掷出了 4` }));\n// await app.listen(8787);\n//\n// The page client is a separate entry: import { createPageClient } from \"@karpoland/sdk/page\";\n// so is the test kit: import { simulate, mockPlatform } from \"@karpoland/sdk/testing\".\n//\n// The names here are the same in the Go and Python SDKs (spec/api.json).\n\nexport {\n ACCEPTED,\n DEDUPE_TTL_SECONDS,\n MAX_BODY_BYTES,\n SIGNING_REREAD_SECONDS,\n createApp,\n memoryDedupe,\n type Accepted,\n type App,\n type AppOptions,\n type CallInfo,\n type CheckedManifest,\n type CoreRequest,\n type CoreResponse,\n type DedupeAnswer,\n type DedupeClaim,\n type DedupeStore,\n type GateAnswer,\n type GateContext,\n type GateHandler,\n type HookContext,\n type HookHandler,\n type Logger,\n type MemoryDedupeOptions,\n type Server,\n type ToolContext,\n type ToolHandler,\n type ToolReply,\n} from \"./app.js\";\nexport { createClient, MAX_RESIDENT_IDS, type Client, type ClientOptions, type DecideAction } from \"./client.js\";\nexport {\n createDeveloperClient,\n type AppInstallRow,\n type AppKey,\n type AppMember,\n type AppTransfer,\n type AppVersion,\n type DeveloperClient,\n type DeveloperClientOptions,\n type EnsureAppInput,\n type PublishInput,\n type UpdateAppInput,\n} from \"./developer.js\";\nexport {\n APP_REASONS,\n AppError,\n PlatformError,\n Reasons,\n STATUSES,\n isPlatformError,\n isReason,\n statusOfHttp,\n type Action,\n type AppErrorStatus,\n type AppReason,\n type ErrorBody,\n type ErrorDetail,\n type Reason,\n type Status,\n} from \"./errors.js\";\nexport { MAX_IDEMPOTENCY_KEY, shouldRetry, type FetchLike, type RequestOptions, type RetryOptions } from \"./http.js\";\nexport {\n BASE_OUTCOMES,\n CARD_SIZES,\n HOOK_EVENTS,\n LISTING_CATEGORIES,\n MANIFEST_IGNORED,\n MAX_CONNECT,\n MAX_RELEASE_NOTES,\n MAX_SESSION_BOARDS,\n ManifestError,\n SCOPES,\n checkConnectOrigin,\n defineManifest,\n validateManifest,\n type BaseOutcome,\n type CardSize,\n type ListingCategory,\n type Manifest,\n type ManifestBoard,\n type ManifestBoolChoice,\n type ManifestCapacity,\n type ManifestCommand,\n type ManifestHook,\n type ManifestHookEvent,\n type ManifestHookFilter,\n type ManifestIntChoice,\n type ManifestIssue,\n type ManifestListing,\n type ManifestOutcome,\n type ManifestPage,\n type ManifestQuestion,\n type ManifestSay,\n type ManifestSessionBoard,\n type ManifestSessionCard,\n type ManifestSessionKind,\n type ManifestTool,\n type ManifestVerify,\n type Scope,\n type ValidateOptions,\n} from \"./manifest.js\";\nexport {\n MAX_SKEW_SECONDS,\n SIGNATURE_HEADER,\n TIMESTAMP_HEADER,\n sign,\n signedHeaders,\n verifySignature,\n type SignedHeadersOptions,\n type SignedRequest,\n type VerifyFailure,\n type VerifyOptions,\n} from \"./signing.js\";\nexport * from \"./types.js\";\nexport { SDK_VERSION, USER_AGENT } from \"./version.js\";\n\n/** The parts of a board's full identifier (boardRef). */\nexport interface BoardRefParts {\n /** The namespace: an app's slug, a room id, or the platform's. */\n app?: string;\n room?: string;\n platform?: boolean;\n key: string;\n /** The part: a session's or an install's board. */\n session?: string;\n install?: string;\n /** A period's sequence number. */\n seq?: number;\n}\n\n/**\n * boardRef builds a board's full identifier: {namespace}/{key}[/{part}][@{seq}],\n * e.g. boardRef({ app: \"dice\", key: \"luck\", session: \"31\" }) → \"app:dice/luck/ss_31\".\n */\nexport function boardRef(p: BoardRefParts): string {\n const ns = p.platform ? \"platform\" : p.room ? `room:${p.room}` : `app:${p.app}`;\n const part = p.session ? `/ss_${p.session}` : p.install ? `/in_${p.install}` : \"\";\n return `${ns}/${p.key}${part}${p.seq ? `@${p.seq}` : \"\"}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAGO,IAAM,cAAc;AAGpB,IAAM,aAAa,oBAAoB,WAAW;;;ACyClD,IAAM,mBAAmB;AA2JzB,SAAS,aAAa,MAA6B;AAGxD,MAAI,CAAC,KAAK,SAAU,OAAM,IAAI,UAAU,qDAAqD;AAC7F,QAAM,UAAU,EAAE,QAAQ,KAAK,QAAQ,YAAY,KAAK,WAAW;AACnE,QAAM,IAAI,gBAAgB;AAAA,IACxB,MAAM,KAAK,SAAS,QAAQ,QAAQ,EAAE,IAAI;AAAA,IAC1C,OAAO,KAAK;AAAA,IACZ,OAAO,KAAK;AAAA,IACZ,WAAW;AAAA,IACX,SAAS,MAAM;AACb,UAAI,CAAC,KAAK,OAAQ,OAAM,IAAI,UAAU,+EAA0E;AAChH,YAAM,IAA4B,EAAE,eAAe,UAAU,KAAK,MAAM,IAAI,GAAG,KAAK,QAAQ;AAC5F,UAAI,QAAQ,OAAQ,GAAE,eAAe,IAAI,OAAO,QAAQ,MAAM;AAC9D,UAAI,QAAQ,WAAY,GAAE,mBAAmB,IAAI,OAAO,QAAQ,UAAU;AAC1E,aAAO;AAAA,IACT;AAAA,EACF,CAAC;AACD,QAAM,MAAM,CAAI,QAAgB,MAAc,MAAuB,EAAE,QAAW,QAAQ,MAAM,CAAC;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,CAAC,MAAM,KAAK,GAAG,QAAQ,EAAE,EAAG,QAAO;AAAA,EACpG;AACA,SAAO;AACT;AAMO,SAAS,eAAmC,UAAa,MAA2B;AACzF,QAAM,SAAS,iBAAiB,UAAU,IAAI;AAC9C,MAAI,OAAO,OAAQ,OAAM,IAAI,cAAc,MAAM;AACjD,SAAO;AACT;;;AClbO,SAAS,SAAS,GAA0B;AACjD,QAAM,KAAK,EAAE,WAAW,aAAa,EAAE,OAAO,QAAQ,EAAE,IAAI,KAAK,OAAO,EAAE,GAAG;AAC7E,QAAM,OAAO,EAAE,UAAU,OAAO,EAAE,OAAO,KAAK,EAAE,UAAU,OAAO,EAAE,OAAO,KAAK;AAC/E,SAAO,GAAG,EAAE,IAAI,EAAE,GAAG,GAAG,IAAI,GAAG,EAAE,MAAM,IAAI,EAAE,GAAG,KAAK,EAAE;AACzD;","names":["key","run","opts"]}
|
|
1
|
+
{"version":3,"sources":["../src/version.ts","../src/client.ts","../src/app.ts","../src/developer.ts","../src/manifest.ts","../src/index.ts"],"sourcesContent":["// The SDK's version; the same number in every language (spec/api.json\n// sdk_version) and in package.json.\n\nexport const SDK_VERSION = \"1.0.1\";\n\n/** What the server-side clients send as User-Agent (the page client sends none). */\nexport const USER_AGENT = `karpoland-sdk-ts/${SDK_VERSION}`;\n","// The platform client for an app's service: every /v1/app-service/* route, with the\n// app's kap_ key. Bound to a call or delivery (MP-Karpo-Call /\n// MP-Karpo-Delivery) it acts in that resident's context.\n\nimport { ALREADY_DONE, createTransport, enc, idempotencyHeader, rfc3339, type FetchLike, type RequestOptions, type RetryOptions } from \"./http.js\";\nimport { USER_AGENT } from \"./version.js\";\nimport {\n type AddParticipantResponse,\n type Board,\n type BoardWhere,\n type Call,\n type ClientContext,\n type CompleteOptions,\n type CreateSessionInput,\n type DecideJoinRequestInput,\n type EndSessionInput,\n type GetBoardQuery,\n type Id,\n type Install,\n type JoinDecision,\n type Json,\n type ListBoardsQuery,\n type ListSessionsQuery,\n type MeResponse,\n type OpenBoardInput,\n type Participant,\n type ParticipantRole,\n type PostInput,\n type QuotaResult,\n type Relative,\n type RematchResponse,\n type Resident,\n type ScoreRow,\n type SendMessageInput,\n type SendMessageResponse,\n type Session,\n type SetParticipantInput,\n type SetTimerInput,\n type ShareResponse,\n type ShareVisibility,\n type Timer,\n type TimerWhere,\n type UpdateSessionInput,\n type WriteOptions,\n} from \"./types.js\";\n\n/** At most this many ids per residents lookup. */\nexport const MAX_RESIDENT_IDS = 100;\n\nexport interface ClientOptions {\n /** The app's key, kap_… (issued with POST /v1/apps/:app/keys). */\n appKey: string;\n /** The Karpo Land API origin, e.g. https://im.karpo.land. */\n platform: string;\n /** Act in a tool call's context (MP-Karpo-Call). */\n callId?: Id;\n /** Act in a hook delivery's context (MP-Karpo-Delivery). */\n deliveryId?: Id;\n /** Retry policy; false turns retries off. */\n retry?: RetryOptions | false;\n fetch?: FetchLike;\n /** Extra headers on every request. */\n headers?: Record<string, string>;\n}\n\n/** A join request's answer: approve or reject (remove a participant with sessions.participants.remove). */\nexport type DecideAction = \"approve\" | \"reject\";\n\n/**\n * The platform client. Every method throws PlatformError on an error answer.\n *\n * Writes the platform runs at most once per key (messages.send, posts.create,\n * sessions.create / end / rematch, boards.submit / publishTop) send an\n * Idempotency-Key: a random one per call, reused on its retries, or\n * opts.idempotencyKey. Retryable answers (retry / retry_later, 429, 503) and\n * network failures of requests safe to repeat are retried up to 3 times,\n * waiting at most 10 s each. Every request sends User-Agent\n * karpoland-sdk-ts/<version>.\n */\nexport interface Client {\n /** The context this client acts in. */\n readonly context: ClientContext;\n /** A copy of this client acting in another context ({} for the app's own). */\n withContext(ctx: ClientContext): Client;\n /** Any /v1/app-service route: request(\"GET\", \"/me\"). */\n request<T = unknown>(method: string, path: string, opts?: RequestOptions): Promise<T>;\n\n /** The app itself, its live tools and session kinds. */\n me(): Promise<MeResponse>;\n installs: {\n get(installId: Id): Promise<Install>;\n };\n calls: {\n get(callId: Id): Promise<Call>;\n /**\n * Fill in an accepted (202) call's result. opts.text is posted in the room\n * in the app's name when the tool is room-visible, like a prompt answer's.\n * Safe to retry: a network failure is retried, and a retry that finds the\n * call already finished (app.ALREADY_DONE) resolves with the call.\n */\n complete(callId: Id, result: Json | unknown, opts?: CompleteOptions): Promise<Call>;\n /** Fail an accepted call with an app error; retried like complete. */\n fail(callId: Id, error: { status: string; reason: string; message?: string }): Promise<Call>;\n };\n sessions: {\n create(input: CreateSessionInput, opts?: WriteOptions): Promise<Session>;\n get(sessionId: Id): Promise<Session>;\n /** query.status filters by state: [\"open\", \"running\"]; an unknown state is a 400. */\n list(query?: ListSessionsQuery): Promise<Session[]>;\n /** display.actions are the card's buttons; the platform checks them (detail.field names the bad one). */\n update(sessionId: Id, input: UpdateSessionInput): Promise<Session>;\n start(sessionId: Id): Promise<Session>;\n pause(sessionId: Id, reason?: string): Promise<Session>;\n resume(sessionId: Id): Promise<Session>;\n cancel(sessionId: Id, reason?: string): Promise<Session>;\n end(sessionId: Id, summary?: EndSessionInput, opts?: WriteOptions): Promise<Session>;\n invite(sessionId: Id, residentIds: Id[]): Promise<Participant[]>;\n /**\n * Start a session like an ended or cancelled one (same install, rooms,\n * kind, title, capacity, join mode, listing and host) and invite its\n * players; observers and those who withdrew or were removed are not.\n */\n rematch(sessionId: Id, opts?: WriteOptions): Promise<RematchResponse>;\n /**\n * Get an invite link: always a new one, the previous link stops working\n * (audited). visibility lists or unlists the session; left out, the\n * listing stays as it is.\n */\n share(sessionId: Id, visibility?: ShareVisibility): Promise<ShareResponse>;\n /** Approve or reject a join request. */\n decide(sessionId: Id, residentId: Id, action: DecideAction): Promise<Participant>;\n participants: {\n list(sessionId: Id): Promise<Participant[]>;\n /**\n * Seat a resident directly (the host or the app), under the join rules:\n * a member of the session's rooms, not blocking the app, a free seat.\n */\n add(sessionId: Id, residentId: Id, role?: ParticipantRole): Promise<AddParticipantResponse>;\n set(sessionId: Id, residentId: Id, input: SetParticipantInput): Promise<Participant>;\n remove(sessionId: Id, residentId: Id): Promise<Participant>;\n };\n };\n boards: {\n /** Write scores to a full board (overwrite per resident, ≤ 1000 rows). board: a key or full identifier. */\n submit(board: string, rows: ScoreRow[], where?: BoardWhere, opts?: WriteOptions): Promise<string>;\n /** Replace a top-only board's rows (≤ 100). */\n publishTop(board: string, rows: ScoreRow[], where?: BoardWhere, opts?: WriteOptions): Promise<string>;\n /** Open the next period of a manual board. */\n open(board: string, input?: OpenBoardInput): Promise<Board>;\n close(board: string, where?: BoardWhere): Promise<Board>;\n /** Reveal a blind (app_only) board. */\n reveal(board: string, where?: BoardWhere): Promise<Board>;\n get(ref: string, query?: GetBoardQuery): Promise<Board>;\n list(query?: ListBoardsQuery): Promise<Board[]>;\n };\n messages: {\n send(input: SendMessageInput, opts?: WriteOptions): Promise<SendMessageResponse>;\n };\n timers: {\n /** Set or replace the timer under key. */\n set(key: string, input: SetTimerInput): Promise<Timer>;\n cancel(key: string, where?: TimerWhere): Promise<void>;\n list(where?: TimerWhere): Promise<Timer[]>;\n };\n posts: {\n /** Post text to a room in the app's name (scope room:post); in_reply_to posts in that message's thread. */\n create(input: PostInput, opts?: WriteOptions): Promise<Id>;\n };\n relations: {\n /** Whether the caller and other share an owner (call context). */\n sameOwner(otherId: Id): Promise<boolean>;\n /** Members of an install's room. */\n members(installId: Id): Promise<Relative[]>;\n /** The caller's contacts, once they granted them (call context). */\n contacts(): Promise<Relative[]>;\n /**\n * Record one use of a per-owner quota for the resident of the call or\n * delivery context: a person and every agent of the same owner share\n * the count. Allowed (and recorded) while fewer than n uses exist.\n * key: a-z, 0-9 and _, starting with a letter, ≤ 48. Scope relation:read.\n */\n quota(key: string, n: number): Promise<QuotaResult>;\n };\n residents: {\n /**\n * Names and avatars of residents the app may see (members of rooms it is\n * installed in, participants of its sessions, residents who called it);\n * others are left out. More than 100 ids are fetched in batches.\n */\n get(ids: Id[]): Promise<Resident[]>;\n };\n joinRequests: {\n /**\n * Decide a room join request the app's gate left pending.\n * Approving counts as the app's approval (the request is approved once\n * every gate and check agrees); rejecting shows reason to the applicant.\n */\n decide(requestId: Id, decision: DecideJoinRequestInput): Promise<JoinDecision>;\n };\n}\n\n/** createClient builds a platform client for an app's service. */\nexport function createClient(opts: ClientOptions): Client {\n // A service runs before it has a key (it serves its domain token first):\n // a client without one fails on use, not on creation.\n if (!opts.platform) throw new TypeError(\"createClient: platform (the API origin) is required\");\n const context = { callId: opts.callId, deliveryId: opts.deliveryId };\n const t = createTransport({\n base: opts.platform.replace(/\\/+$/, \"\") + \"/v1/app-service\",\n fetch: opts.fetch,\n retry: opts.retry,\n userAgent: USER_AGENT,\n headers: () => {\n if (!opts.appKey) throw new TypeError(\"karpoland client: no appKey (kap_…) yet; issue one and configure the app\");\n const h: Record<string, string> = { Authorization: `Bearer ${opts.appKey}`, ...opts.headers };\n if (context.callId) h[\"MP-Karpo-Call\"] = String(context.callId);\n if (context.deliveryId) h[\"MP-Karpo-Delivery\"] = String(context.deliveryId);\n return h;\n },\n });\n const req = <T>(method: string, path: string, o?: RequestOptions) => t.request<T>(method, path, o);\n const post = <T>(path: string, body: unknown = {}) => req<T>(\"POST\", path, { body });\n // A write the platform runs once per key: the key is made here, once, so\n // every retry of this call carries the same one.\n const once = async <T>(method: string, path: string, body: unknown, o?: WriteOptions) =>\n req<T>(method, path, { body, headers: idempotencyHeader(o?.idempotencyKey), idempotent: true });\n const s = (id: Id) => `/sessions/${enc(id)}`;\n\n async function residentsGet(ids: Id[]): Promise<Resident[]> {\n const want = [...new Set(ids.filter(Boolean).map(String))];\n const out: Resident[] = [];\n for (let i = 0; i < want.length; i += MAX_RESIDENT_IDS) {\n const r = await req<{ residents?: Resident[] }>(\"GET\", \"/residents\", { query: { ids: want.slice(i, i + MAX_RESIDENT_IDS).join(\",\") } });\n out.push(...(r.residents ?? []));\n }\n return out;\n }\n\n const relations = (path: string, query: Record<string, unknown> = {}) => req<any>(\"GET\", `/relations/${path}`, { query });\n // The result of an accepted call; network failures retried, and a retry\n // that finds the call finished counts as done.\n const finish = async (id: Id, body: unknown): Promise<Call> => {\n const r = await req<{ call: Call } | typeof ALREADY_DONE>(\"POST\", `/calls/${enc(id)}/result`, { body, idempotent: true, doneOnRetry: \"app.ALREADY_DONE\" });\n return r === ALREADY_DONE ? getCall(id) : r.call;\n };\n // Single-object answers are unwrapped: {session} → the session.\n const one = async <T>(key: string, p: Promise<unknown>): Promise<T> => ((await p) as Record<string, unknown>)?.[key] as T;\n const list = async <T>(key: string, p: Promise<unknown>): Promise<T[]> => (((await p) as Record<string, unknown>)?.[key] as T[] | undefined) ?? [];\n const getCall = (id: Id) => one<Call>(\"call\", req(\"GET\", `/calls/${enc(id)}`));\n const session = (p: Promise<unknown>) => one<Session>(\"session\", p);\n const participant = (p: Promise<unknown>) => one<Participant>(\"participant\", p);\n const board = (p: Promise<unknown>) => one<Board>(\"board\", p);\n\n return {\n context,\n withContext: (ctx) => createClient({ ...opts, callId: ctx.callId, deliveryId: ctx.deliveryId }),\n request: (method, path, o) => req(method, path, o),\n me: () => req(\"GET\", \"/me\"),\n installs: { get: (id) => one(\"install\", req(\"GET\", `/installs/${enc(id)}`)) },\n calls: {\n get: getCall,\n complete: (id, result, o = {}) => finish(id, { result: result === undefined ? null : result, ...(o.text ? { text: o.text } : {}) }),\n fail: (id, error) => finish(id, { error }),\n },\n sessions: {\n create: (input, o) => session(once(\"POST\", \"/sessions\", input, o)),\n get: (id) => session(req(\"GET\", s(id))),\n list: (query = {}) => {\n const { status, ...rest } = query;\n return list<Session>(\"sessions\", req(\"GET\", \"/sessions\", { query: { ...rest, status: Array.isArray(status) ? status.join(\",\") : status } }));\n },\n update: (id, input) => session(req(\"PATCH\", s(id), { body: input })),\n start: (id) => session(post(`${s(id)}/start`)),\n pause: (id, reason) => session(post(`${s(id)}/pause`, { reason })),\n resume: (id) => session(post(`${s(id)}/resume`)),\n cancel: (id, reason) => session(post(`${s(id)}/cancel`, { reason })),\n end: (id, summary = {}, o) => session(once(\"POST\", `${s(id)}/end`, summary, o)),\n invite: (id, residentIds) => list<Participant>(\"invited\", post(`${s(id)}/invite`, { resident_ids: residentIds })),\n rematch: (id, o) => once(\"POST\", `${s(id)}/rematch`, {}, o),\n share: (id, visibility) => post(`${s(id)}/share`, visibility ? { visibility } : {}),\n decide: (id, resident, action) => participant(post(`${s(id)}/participants/${enc(resident)}/${action}`)),\n participants: {\n list: (id) => list<Participant>(\"participants\", req(\"GET\", `${s(id)}/participants`)),\n add: (id, resident, role = \"player\") => post(`${s(id)}/participants`, { resident_id: resident, role }),\n set: (id, resident, input) => participant(req(\"PUT\", `${s(id)}/participants/${enc(resident)}`, { body: input })),\n remove: (id, resident) => participant(req(\"DELETE\", `${s(id)}/participants/${enc(resident)}`)),\n },\n },\n boards: {\n // Full identifiers carry \"/\" and go in the body or ?ref=.\n submit: (b, rows, where = {}, o) => one<string>(\"ref\", once(\"POST\", \"/scores\", { board: b, rows, ...where }, o)),\n publishTop: (b, rows, where = {}, o) => one<string>(\"ref\", once(\"PUT\", \"/top\", { board: b, rows, ...where }, o)),\n open: (b, input = {}) => board(post(\"/periods\", { board: b, op: \"open\", ...input })),\n close: (b, where = {}) => board(post(\"/periods\", { board: b, op: \"close\", ...where })),\n reveal: (b, where = {}) => board(post(\"/periods\", { board: b, op: \"reveal\", ...where })),\n get: (ref, query = {}) => board(req(\"GET\", \"/boards\", { query: { ref, ...query } })),\n list: (query = {}) => list<Board>(\"boards\", req(\"GET\", \"/boards\", { query: query as Record<string, unknown> })),\n },\n messages: {\n send: (input, o) => once(\"POST\", \"/messages\", { ...input, due_at: rfc3339(input.due_at) }, o),\n },\n timers: {\n set: (key, input) => one<Timer>(\"timer\", req(\"PUT\", `/timers/${enc(key)}`, { body: { ...input, at: rfc3339(input.at) } })),\n cancel: async (key, where = {}) => void (await req(\"DELETE\", `/timers/${enc(key)}`, { query: where as Record<string, unknown> })),\n list: (where = {}) => list<Timer>(\"timers\", req(\"GET\", \"/timers\", { query: where as Record<string, unknown> })),\n },\n posts: { create: (input, o) => one<Id>(\"message_id\", once(\"POST\", \"/posts\", input, o)) },\n relations: {\n sameOwner: async (otherId) => (await relations(\"same-owner\", { other_id: otherId })).same_owner === true,\n members: async (installId) => (await relations(\"members\", { install_id: installId })).residents ?? [],\n contacts: async () => (await relations(\"contacts\")).residents ?? [],\n quota: (key, n) => post(\"/relations/quota\", { key, n }),\n },\n residents: { get: residentsGet },\n joinRequests: {\n decide: (id, d) => post(`/join-requests/${enc(id)}/${d.approve ? \"approve\" : \"reject\"}`, { reason: d.reason ?? \"\" }),\n },\n };\n}\n","// The app's service: answers the platform's signed deliveries (tool calls,\n// hooks, the publish handshake) and serves the domain verification file.\n// One core (handle) with two adapters: fetch-style (Request → Response, for\n// serverless and edge) and Node http (handler / listen).\n\nimport { createClient, type Client, type ClientOptions } from \"./client.js\";\nimport { AppError, PlatformError, isReason, type AppErrorStatus, type AppReason } from \"./errors.js\";\nimport { shouldRetry, type FetchLike, type RetryOptions } from \"./http.js\";\nimport { SIGNATURE_HEADER, TIMESTAMP_HEADER, verifySignature } from \"./signing.js\";\nimport type {\n ClientContext,\n CompleteOptions,\n GateDecision,\n HandshakeDelivery,\n HookDelivery,\n HookEvent,\n HookEvents,\n Id,\n InstallRef,\n Json,\n Resident,\n SessionRef,\n ToolCallDelivery,\n} from \"./types.js\";\n\n// ----------------------------------------------------------------- options\n\n/** Largest request body a service accepts by default (413 above). */\nexport const MAX_BODY_BYTES = 1 << 20;\n\n/**\n * How long a DedupeStore keeps first answers by default: 24 hours, longer\n * than any platform redelivery of the same call id or delivery id (hook\n * retries end after about 36 minutes; a caller's retry with the same\n * idempotency key redelivers a call the platform failed to deliver).\n */\nexport const DEDUPE_TTL_SECONDS = 24 * 3600;\n\n/** A first answer a DedupeStore keeps: the HTTP status and the body text (\"\" for none). */\nexport interface DedupeAnswer {\n status: number;\n body: string;\n}\n\n/** What a DedupeStore knows about a key. */\nexport type DedupeClaim =\n /** Not seen: handle it now; the caller holds the claim until end(). */\n | { state: \"new\" }\n /** Another request is handling it: answered 503, the platform retries later. */\n | { state: \"in_flight\" }\n /** Answered already: the first answer is replayed, the handler does not run. */\n | { state: \"done\"; answer: DedupeAnswer };\n\n/**\n * Remembers tool calls, hook deliveries and gate deliveries (the platform\n * delivers at least once): a repeat within the TTL gets the first answer\n * replayed, and one that arrives while the first is still running is\n * answered 503 so the platform retries it later. Keys are \"call:<call id>\"\n * and \"delivery:<delivery id>\". Implement it on a shared store (Redis SET NX\n * with a TTL, a database row) when several instances serve the app.\n */\nexport interface DedupeStore {\n /** Claim a key. */\n begin(key: string): DedupeClaim | Promise<DedupeClaim>;\n /**\n * Record how a claimed key ended: an answer (2xx, 202 or 4xx) is kept and\n * replayed; null (a 5xx or an error) releases the claim, so the platform's\n * retry runs the handler again.\n */\n end(key: string, answer: DedupeAnswer | null): void | Promise<void>;\n}\n\n/** Options of memoryDedupe. */\nexport interface MemoryDedupeOptions {\n /** How many answers it keeps; default 10 000. */\n max?: number;\n /** How long it keeps each answer, in seconds; default DEDUPE_TTL_SECONDS (24 h). */\n ttlSeconds?: number;\n}\n\n/** An in-memory DedupeStore: the last max answers, each kept ttlSeconds (default 10 000, 24 h). */\nexport function memoryDedupe(opts: MemoryDedupeOptions = {}): DedupeStore {\n const max = opts.max ?? 10_000;\n const ttl = (opts.ttlSeconds ?? DEDUPE_TTL_SECONDS) * 1000;\n const done = new Map<string, { at: number; answer: DedupeAnswer }>();\n const inFlight = new Set<string>();\n return {\n begin(key) {\n const hit = done.get(key);\n if (hit) {\n if (Date.now() - hit.at <= ttl) return { state: \"done\", answer: hit.answer };\n done.delete(key);\n }\n if (inFlight.has(key)) return { state: \"in_flight\" };\n inFlight.add(key);\n return { state: \"new\" };\n },\n end(key, answer) {\n inFlight.delete(key);\n if (!answer) return;\n done.delete(key);\n done.set(key, { at: Date.now(), answer });\n while (done.size > max) done.delete(done.keys().next().value as string);\n },\n };\n}\n\nexport interface Logger {\n error(...args: unknown[]): void;\n warn?(...args: unknown[]): void;\n info?(...args: unknown[]): void;\n}\n\nexport interface AppOptions {\n /** The Karpo Land API origin, e.g. https://api.karpo.land. */\n platform?: string;\n /**\n * The app's service key, kap_…. With platform it is all an app needs: the\n * app reads its signing secret and domain token with it (GET\n * /v1/app-service/signing) at startup, and again after a delivery's\n * signature fails (at most once a minute), so a rotated secret is picked\n * up without a restart. ctx.karpo acts with it too.\n */\n appKey?: string;\n /**\n * Verify deliveries with this secret instead of reading it from the\n * platform with appKey. For tests, and for platforms that don't serve\n * GET /v1/app-service/signing yet. With it the app serves no domain\n * token. It will be removed in a future major version.\n */\n signingSecret?: string;\n /** Path prefix the service is mounted under (service_url's path), e.g. \"/karpo\". */\n basePath?: string;\n /** Largest accepted clock difference for MP-Karpo-Timestamp; default 300 s. */\n maxSkewSeconds?: number;\n /**\n * A path prefix a reverse proxy strips before requests reach this service\n * (the signature covers the path the platform posted to, i.e. the\n * service_url's path). Not needed for basePath, which the service sees.\n */\n signaturePathPrefix?: string;\n /**\n * Deduplication of tool calls, hooks and gates; default in memory\n * (memoryDedupe(), 24 h). Use a shared store when several instances serve\n * the app; false turns it off.\n */\n dedupe?: DedupeStore | false;\n /** Largest accepted request body; default 1 MiB (MAX_BODY_BYTES). */\n maxBodyBytes?: number;\n logger?: Logger;\n /** Client settings for ctx.karpo (and the signing secret read). */\n retry?: RetryOptions | false;\n fetch?: FetchLike;\n}\n\n/** The fewest seconds between two reads of the signing secret. */\nexport const SIGNING_REREAD_SECONDS = 60;\n\n/** Both names of the room join request event: member.join and join.requested. */\nconst JOIN_EVENTS = new Set([\"member.join\", \"join.requested\"]);\nconst eventKey = (e: string) => (JOIN_EVENTS.has(e) ? \"member.join\" : e);\n\n// ----------------------------------------------------------------- contexts\n\n/** Returned by ctx.accepted(): the call is answered later (HTTP 202). */\nexport const ACCEPTED: unique symbol = Symbol.for(\"karpoland.accepted\");\nexport type Accepted = typeof ACCEPTED;\n\n/** A tool's explicit answer: the result, and text posted to the room for room-visible tools. */\nexport interface ToolReply<R = unknown> {\n result?: R;\n /** At most 4000 characters; posted in the app's name when the tool is room-visible. */\n text?: string;\n}\n\n/** The call a tool handler answers. */\nexport interface CallInfo<A = Record<string, Json>> {\n id: Id;\n tool: string;\n args: A;\n idempotencyKey?: string;\n /** The caller's first call to the app. */\n firstSeen: boolean;\n}\n\nexport interface ToolContext<A = Record<string, Json>> {\n /** The app's slug. */\n app: string;\n call: CallInfo<A>;\n /** The arguments, validated by the platform against the tool's schema. */\n args: A;\n /** Who called; null when the platform called in the app's own context. */\n caller: Resident | null;\n install: InstallRef | null;\n session: SessionRef | null;\n /** The event that made the platform call the tool in the app's own context, or null. */\n event: string | null;\n /** The room message whose command ran the tool. */\n commandMessageId: Id | null;\n /** The platform client in this call's context (acts for the caller). */\n karpo: Client;\n /** Answer later: `return ctx.accepted()`, then ctx.complete(result) within 10 minutes. */\n accepted(): Accepted;\n /**\n * Fill in this call's result after ctx.accepted(); opts.text is posted in\n * the room like a prompt answer's (room-visible tools). Safe to retry.\n */\n complete(result: unknown, opts?: CompleteOptions): Promise<void>;\n /** Fail this call after ctx.accepted(). */\n fail(status: AppErrorStatus, reason: AppReason, message?: string): Promise<void>;\n /**\n * Accept now and run work after the response: its return value completes\n * the call, an AppError fails it. `return ctx.defer(async () => …)`.\n */\n defer(work: () => Promise<unknown>): Accepted;\n /** Keep the runtime alive for p after responding (serverless waitUntil). */\n waitUntil(p: Promise<unknown>): void;\n /** The raw delivery. */\n raw: ToolCallDelivery;\n}\n\nexport interface HookContext<E extends string = string> {\n app: string;\n event: E;\n deliveryId: Id;\n /** 1 on the first attempt. */\n attempt: number;\n install: InstallRef | null;\n sessionId: Id | null;\n /** The resident the hook may act for (sender, member, timer resident…). */\n residentId: Id | null;\n data: E extends HookEvent ? HookEvents[E] : Record<string, unknown>;\n /** The platform client in this delivery's context. */\n karpo: Client;\n waitUntil(p: Promise<unknown>): void;\n raw: HookDelivery;\n}\n\nexport type ToolHandler<A = Record<string, Json>> = (\n ctx: ToolContext<A>,\n args: A,\n) => unknown | Promise<unknown>;\n\nexport type HookHandler<E extends string = string> = (\n ctx: HookContext<E>,\n data: HookContext<E>[\"data\"],\n) => unknown | Promise<unknown>;\n\n/** A room join request gate's context: residentId is the applicant. */\nexport type GateContext = HookContext<\"member.join\">;\n\n/**\n * A gate's answer: a decision, or one with a reason (≤ 200 characters, shown\n * to the applicant on reject). \"pending\" decides later with\n * karpo.joinRequests.decide. undefined gives no decision: the room's admins\n * decide. The first answer is replayed when the platform redelivers.\n */\nexport type GateAnswer = GateDecision | { decision: GateDecision; reason?: string } | undefined | null | void;\n\nexport type GateHandler = (ctx: GateContext, data: GateContext[\"data\"]) => GateAnswer | Promise<GateAnswer>;\n\nconst GATE_DECISIONS = new Set<string>([\"approve\", \"reject\", \"pending\"]);\n\n// ------------------------------------------------------------------ core io\n\n/** A transport-neutral request. */\nexport interface CoreRequest {\n method: string;\n /** Path without query, e.g. /tools/roll. */\n path: string;\n /**\n * The full path the platform posted to, when a router stripped a mount\n * prefix from path (Express originalUrl); default path, with basePath put\n * back if missing.\n */\n signedPath?: string;\n headers: { get(name: string): string | null | undefined };\n body: Uint8Array;\n}\n\nexport interface CoreResponse {\n status: number;\n headers: Record<string, string>;\n body: string;\n}\n\ntype WaitUntil = (p: Promise<unknown>) => void;\n\n/** A running HTTP server (app.listen). */\nexport interface Server {\n /** The port it listens on. */\n port: number;\n /** http://host:port */\n url: string;\n /** Stop listening; resolves once open connections are done. */\n close(): Promise<void>;\n /** Resolves when the server stops. */\n wait(): Promise<void>;\n}\n\nexport interface App {\n /** Register a tool handler. */\n tool<A = Record<string, Json>>(name: string, handler: ToolHandler<A>): App;\n /** Register a hook handler; declare it in the manifest with handler: true. */\n hook<E extends HookEvent>(event: E, handler: HookHandler<E>): App;\n hook(event: string, handler: HookHandler<string>): App;\n /**\n * Decide room join requests: the manifest's {on: \"member.join\", gate: true}.\n * Deliveries under /hooks/member.join and /hooks/join.requested (the name\n * the platform moves to) both reach it. Without a decision the room's\n * admins decide.\n */\n gate(handler: GateHandler): App;\n /** Fetch-style handler: Request → Response (Workers, Deno, Bun, Vercel, Next.js). Pass the runtime's ctx to get waitUntil. */\n fetch(request: Request, ...rest: unknown[]): Promise<Response>;\n /** Node http handler; with Express, mount it before any body parser (or set req.rawBody). */\n handler(req: NodeRequestLike, res: NodeResponseLike, next?: (err?: unknown) => void): Promise<void>;\n /** Start a Node http server. */\n listen(port?: number, host?: string): Promise<Server>;\n /** The transport-neutral core. */\n handle(req: CoreRequest, waitUntil?: WaitUntil): Promise<CoreResponse>;\n /** A platform client in a context ({} for the app's own). */\n client(ctx?: ClientContext): Client;\n /** Change settings later; a new appKey or platform reads the signing secret again. */\n configure(opts: Partial<AppOptions>): App;\n /**\n * Compare the handlers with the manifest; throws listing every tool and\n * handler hook (handler: true) declared without a registered handler,\n * every handler registered but not declared, and a gate hook ({on:\n * \"member.join\", gate: true}) without app.gate or app.gate without one.\n * Call it at startup with the manifest you publish. The publish handshake\n * runs the same check on the platform's lists (missing handlers fail the\n * publish).\n */\n check(manifest: CheckedManifest): void;\n readonly tools: string[];\n readonly hooks: string[];\n}\n\n/** The parts of a manifest app.check reads. */\nexport interface CheckedManifest {\n tools?: { name: string }[];\n hooks?: { on: string; handler?: boolean; gate?: boolean; verify?: unknown }[];\n}\n\n/**\n * checkHandlers lists what differs between a manifest and the registered\n * handlers, as app.check reports it: \"no handler for …\" (declared, not\n * registered) and \"not in the manifest: …\" (registered, not declared), each\n * a sorted list of \"tool <name>\", \"hook <event>\" and \"gate member.join\".\n */\nexport function checkHandlers(manifest: CheckedManifest, registered: { tools: Iterable<string>; hooks: Iterable<string>; gate: boolean }): string[] {\n const tools = new Set(registered.tools);\n const hooks = new Set(registered.hooks);\n // A gate hook (gate: true, no verify) is answered by app.gate, not app.hook.\n const isGate = (h: { gate?: boolean; verify?: unknown }) => !!h.gate && h.verify == null;\n const declaredTools = new Set((manifest.tools ?? []).map((t) => t.name));\n const declaredHooks = new Set((manifest.hooks ?? []).filter((h) => h.handler && !isGate(h)).map((h) => eventKey(h.on)));\n const gated = (manifest.hooks ?? []).some(isGate);\n for (const h of [...hooks]) if (JOIN_EVENTS.has(h)) (hooks.delete(h), hooks.add(\"member.join\"));\n const missing: string[] = [];\n const extra: string[] = [];\n for (const t of declaredTools) if (!tools.has(t)) missing.push(`tool ${t}`);\n for (const t of tools) if (!declaredTools.has(t)) extra.push(`tool ${t}`);\n for (const h of declaredHooks) if (!hooks.has(h)) missing.push(`hook ${h}`);\n for (const h of hooks) if (!declaredHooks.has(h)) extra.push(`hook ${h}`);\n if (gated && !registered.gate) missing.push(\"gate member.join\");\n if (registered.gate && !gated) extra.push(\"gate member.join\");\n const problems: string[] = [];\n if (missing.length) problems.push(\"no handler for \" + missing.sort().join(\", \"));\n if (extra.length) problems.push(\"not in the manifest: \" + extra.sort().join(\", \"));\n return problems;\n}\n\nexport interface NodeRequestLike {\n method?: string;\n url?: string;\n headers: Record<string, string | string[] | undefined>;\n rawBody?: Uint8Array | string;\n on(event: string, fn: (...a: any[]) => void): unknown;\n}\nexport interface NodeResponseLike {\n writeHead(status: number, headers?: Record<string, string>): unknown;\n end(body?: string): unknown;\n headersSent?: boolean;\n}\n\nconst json = (status: number, body?: unknown): CoreResponse => ({\n status,\n headers: body === undefined ? {} : { \"Content-Type\": \"application/json; charset=utf-8\" },\n body: body === undefined ? \"\" : JSON.stringify(body),\n});\n\nconst REPLY_KEYS = new Set([\"result\", \"text\"]);\n\n/** A handler's return value as the platform reads it: {result, text}. */\nexport function toReply(out: unknown): ToolReply {\n if (out === undefined) return { result: null };\n if (out && typeof out === \"object\" && !Array.isArray(out) && Object.getPrototypeOf(out) === Object.prototype) {\n const keys = Object.keys(out);\n if (keys.length > 0 && keys.every((k) => REPLY_KEYS.has(k))) {\n const r = out as ToolReply;\n return { result: r.result === undefined ? null : r.result, ...(r.text !== undefined ? { text: r.text } : {}) };\n }\n }\n return { result: out };\n}\n\n/** How an error thrown in a handler is answered. */\nexport function errorResponse(e: unknown, kind: \"tool\" | \"hook\", log?: Logger): CoreResponse {\n if (e instanceof AppError) return json(e.httpStatus, e.toJSON());\n if (e instanceof PlatformError) {\n // The app's own key failed on a platform call (key.INVALID: revoked or\n // unknown, or another 401): a temporary failure of this service, never\n // the 401 a bad signature gets, so the platform retries.\n if (e.httpStatus === 401) {\n log?.error(isReason(e, \"key.INVALID\") ? \"karpoland: the app key is invalid or revoked (key.INVALID); issue a new key and configure the app\" : \"karpoland: the platform refused the app key\", e);\n return json(503, { status: \"UNAVAILABLE\", reason: e.reason, message: e.message });\n }\n if (kind === \"hook\" && shouldRetry(e)) return json(503, { status: e.status, reason: e.reason, message: e.message });\n // A platform refusal the handler did not catch: pass it on, so the caller\n // reads why (the platform keeps the reasons apps may return and turns the\n // rest into app.RULE_VIOLATION with the message kept).\n if (e.httpStatus >= 400 && e.httpStatus < 500) {\n return json(e.httpStatus, { status: e.status, reason: e.reason, message: e.message, action: e.action });\n }\n }\n log?.error(\"karpoland: handler failed\", e);\n return json(500, { error: \"app error\" });\n}\n\n// ------------------------------------------------------------------- create\n\n/**\n * createApp builds an app's service. createApp({platform, appKey}) is all\n * the configuration it needs; the library reads no environment variables.\n */\nexport function createApp(options: AppOptions = {}): App {\n const opts: AppOptions = { ...options };\n const tools = new Map<string, ToolHandler<any>>();\n const hooks = new Map<string, HookHandler<any>>();\n let gate: GateHandler | undefined;\n let dedupe: DedupeStore | false = opts.dedupe === undefined ? memoryDedupe() : opts.dedupe;\n const log: Logger = opts.logger ?? console;\n\n const client = (ctx: ClientContext = {}): Client => {\n if (!opts.appKey || !opts.platform) {\n return new Proxy({} as Client, {\n get(_, prop) {\n if (prop === \"then\") return undefined;\n throw new Error(`karpoland: set appKey and platform in createApp() to use the platform client (karpo.${String(prop)})`);\n },\n });\n }\n const c: ClientOptions = { appKey: opts.appKey, platform: opts.platform, retry: opts.retry, fetch: opts.fetch, ...ctx };\n return createClient(c);\n };\n\n // The signing secret and domain token, read with the app key (GET\n // /v1/app-service/signing): at startup, and again after a signature\n // fails, at most once a minute. signingSecret overrides it.\n let signing: { secret: string; domainToken: string } | null = null;\n let signingReadAt = 0;\n let signingRead: Promise<void> | null = null;\n const canReadSigning = () => !opts.signingSecret && !!opts.platform && !!opts.appKey;\n const readSigning = (): Promise<void> => {\n if (!canReadSigning()) return Promise.resolve();\n if (signingRead) return signingRead;\n if (signingReadAt && Date.now() - signingReadAt < SIGNING_REREAD_SECONDS * 1000) return Promise.resolve();\n signingReadAt = Date.now();\n signingRead = (async () => {\n try {\n const r = await client().request<Record<string, unknown>>(\"GET\", \"/signing\");\n const b = (r && typeof r.signing === \"object\" && r.signing ? r.signing : r) as Record<string, unknown>;\n if (typeof b.signing_secret === \"string\" && b.signing_secret) {\n signing = { secret: b.signing_secret, domainToken: typeof b.domain_token === \"string\" ? b.domain_token : \"\" };\n } else log.error(\"karpoland: GET /v1/app-service/signing answered without signing_secret\");\n } catch (e) {\n if (e instanceof PlatformError && isReason(e, \"key.INVALID\")) log.error(\"karpoland: the app key is invalid or revoked (key.INVALID); issue a new key and configure the app\");\n else log.error(\"karpoland: could not read the signing secret (GET /v1/app-service/signing); deliveries are answered 503 until it can. On a platform without that route, set signingSecret\", e);\n } finally {\n signingRead = null;\n }\n })();\n return signingRead;\n };\n const secret = async (): Promise<string | undefined> => {\n if (opts.signingSecret) return opts.signingSecret;\n if (!signing) await readSigning();\n return signing?.secret;\n };\n\n const stripBase = (path: string): string | null => {\n const base = (opts.basePath ?? \"\").replace(/\\/+$/, \"\");\n if (!base) return path;\n if (path === base) return \"/\";\n return path.startsWith(base + \"/\") ? path.slice(base.length) : null;\n };\n // The path the platform posted to (and signed): a prefix a proxy stripped\n // put back.\n const signedPath = (path: string): string => (opts.signaturePathPrefix ?? \"\").replace(/\\/+$/, \"\") + path;\n\n // Runs a delivery once per key: a repeat gets the first answer, one that\n // comes while the first runs gets 503. 5xx answers are not kept.\n async function once(key: string, run: () => Promise<CoreResponse>): Promise<CoreResponse> {\n const store = dedupe || null;\n if (!store) return run();\n let claim: DedupeClaim;\n try {\n claim = await store.begin(key);\n } catch (e) {\n log.error(\"karpoland: dedupe store failed\", e);\n return json(503, { error: \"dedupe unavailable\" });\n }\n if (claim.state === \"done\") {\n const a = claim.answer;\n return { status: a.status, headers: a.body ? { \"Content-Type\": \"application/json; charset=utf-8\" } : {}, body: a.body };\n }\n if (claim.state === \"in_flight\") return json(503, { error: \"delivery in progress\" });\n let res: CoreResponse;\n try {\n res = await run();\n } catch (e) {\n log.error(\"karpoland: handler failed\", e);\n res = json(500, { error: \"app error\" });\n }\n try {\n await store.end(key, res.status < 500 ? { status: res.status, body: res.body } : null);\n } catch (e) {\n log.error(\"karpoland: dedupe store failed\", e);\n }\n return res;\n }\n\n async function handle(req: CoreRequest, waitUntil?: WaitUntil): Promise<CoreResponse> {\n const method = req.method.toUpperCase();\n if (method === \"GET\" && (req.path === \"/.well-known/karpo-app.txt\" || stripBase(req.path) === \"/.well-known/karpo-app.txt\")) {\n if (!signing) await readSigning();\n if (!signing?.domainToken || opts.signingSecret) return { status: 404, headers: { \"Content-Type\": \"text/plain\" }, body: \"\" };\n return { status: 200, headers: { \"Content-Type\": \"text/plain; charset=utf-8\" }, body: signing.domainToken };\n }\n const path = stripBase(req.path);\n if (path === null) return json(404, { error: \"not found\" });\n if (method === \"GET\" && path === \"/healthz\") return json(200, { ok: true });\n const route = path === \"/.karpo/handshake\" ? \"handshake\" : path.startsWith(\"/tools/\") ? \"tool\" : path.startsWith(\"/hooks/\") ? \"hook\" : null;\n if (!route) return json(404, { error: \"not found\" });\n if (method !== \"POST\") return json(405, { error: \"use POST\" });\n if (req.body.length > (opts.maxBodyBytes ?? MAX_BODY_BYTES)) return json(413, { error: \"body too large\" });\n\n const signature = req.headers.get(SIGNATURE_HEADER);\n const headerId = String(req.headers.get(\"mp-karpo-call\") || req.headers.get(\"mp-karpo-delivery\") || \"\");\n const signed = { method, path: req.signedPath ?? signedPath(req.path), id: headerId };\n const verify = (key: string | undefined) => verifySignature(key ?? \"\", req.headers.get(TIMESTAMP_HEADER), signed, req.body, signature, { maxSkewSeconds: opts.maxSkewSeconds });\n let key = await secret();\n if (!key && canReadSigning()) return json(503, { error: \"signing secret unavailable\" });\n let why = await verify(key);\n if (why === \"mismatch\" && canReadSigning()) {\n // The secret may have been rotated: read it again (at most once a minute).\n await readSigning();\n if (signing && signing.secret !== key) {\n key = signing.secret;\n why = await verify(key);\n }\n }\n if (why) {\n if (!key) log.warn?.(\"karpoland: no signing secret (set platform and appKey); refusing deliveries\");\n return json(401, { status: \"UNAUTHENTICATED\", reason: \"auth.TOKEN_INVALID\", message: why === \"skew\" ? \"stale timestamp\" : \"bad signature\" });\n }\n let msg: any;\n try {\n msg = JSON.parse(new TextDecoder().decode(req.body));\n } catch {\n return json(400, { status: \"INVALID_ARGUMENT\", reason: \"request.BAD_TYPE\", message: \"body is not JSON\" });\n }\n if (!msg || typeof msg !== \"object\" || Array.isArray(msg)) return json(400, { status: \"INVALID_ARGUMENT\", reason: \"request.BAD_TYPE\", message: \"body is not an object\" });\n\n // Node keeps running after the response; serverless runtimes need waitUntil.\n const keepAlive: WaitUntil = (p) => {\n const guarded = p.catch((e) => log.error(\"karpoland: background work failed\", e));\n waitUntil?.(guarded);\n };\n\n // Ids come from the signed body; the signature also names the id, which\n // must be the body's.\n const bodyId = route === \"tool\" ? String((msg as ToolCallDelivery).call?.id ?? \"\") : route === \"hook\" ? String((msg as HookDelivery).delivery_id ?? \"\") : \"\";\n if (headerId !== bodyId) {\n return json(401, { status: \"UNAUTHENTICATED\", reason: \"auth.TOKEN_INVALID\", message: \"signed id differs from the body's\" });\n }\n\n if (route === \"handshake\") return handshake(msg as HandshakeDelivery);\n if (route === \"tool\") {\n const name = decodeURIComponent(path.slice(\"/tools/\".length));\n const run = () => runTool(name, msg as ToolCallDelivery, bodyId, keepAlive);\n return bodyId ? once(\"call:\" + bodyId, run) : run();\n }\n const event = decodeURIComponent(path.slice(\"/hooks/\".length));\n const run = () => (JOIN_EVENTS.has(event) && (msg as HookDelivery).gate === true ? runGate(event, msg as HookDelivery, bodyId, keepAlive) : runHook(event, msg as HookDelivery, bodyId, keepAlive));\n return bodyId ? once(\"delivery:\" + bodyId, run) : run();\n }\n\n // The publish handshake: echo the challenge. When the platform lists the\n // manifest's tools and handler hooks, every one needs a registered handler.\n function handshake(msg: HandshakeDelivery): CoreResponse {\n const missing: string[] = [];\n if (Array.isArray(msg.tools)) for (const t of msg.tools) if (!tools.has(t)) missing.push(`tool ${t}`);\n if (Array.isArray(msg.hooks)) {\n for (const h of msg.hooks) {\n const k = eventKey(h);\n if (k === \"member.join\" ? !gate && !hooks.has(\"member.join\") && !hooks.has(\"join.requested\") : !hooks.has(h)) missing.push(`hook ${h}`);\n }\n }\n if (missing.length) {\n missing.sort();\n return json(422, { status: \"FAILED_PRECONDITION\", reason: \"app.HANDSHAKE_FAILED\", message: \"no handler for \" + missing.join(\", \"), detail: { items: missing } });\n }\n return json(200, { challenge: msg.challenge });\n }\n\n async function runTool(name: string, msg: ToolCallDelivery, callId: string, keepAlive: WaitUntil): Promise<CoreResponse> {\n const fn = tools.get(name);\n if (!fn) return json(404, { status: \"NOT_FOUND\", reason: \"request.UNKNOWN_TOOL\", message: `no tool ${name} here` });\n const args = (msg.call?.args ?? {}) as Record<string, Json>;\n let accepted = false;\n const base = () => client();\n const ctx: ToolContext<any> = {\n app: msg.app,\n call: { id: callId, tool: name, args, idempotencyKey: msg.call?.idempotency_key || undefined, firstSeen: !!msg.call?.first_seen },\n args,\n caller: msg.caller ?? null,\n install: msg.install ?? null,\n session: msg.session ?? null,\n event: msg.event ?? null,\n commandMessageId: msg.command_message_id ?? null,\n karpo: client({ callId }),\n accepted() {\n accepted = true;\n return ACCEPTED;\n },\n async complete(result, opts) {\n await base().calls.complete(callId, result, opts);\n },\n async fail(status, reason, message = \"\") {\n await base().calls.fail(callId, { status, reason, message });\n },\n defer(work) {\n accepted = true;\n keepAlive(\n (async () => {\n let out: unknown;\n try {\n out = await work();\n } catch (e) {\n if (e instanceof AppError) return base().calls.fail(callId, e.toJSON());\n log.error(`karpoland: deferred work for ${name} failed`, e);\n return base().calls.fail(callId, { status: \"FAILED_PRECONDITION\", reason: \"app.RULE_VIOLATION\", message: \"the app could not finish this call\" });\n }\n const r = toReply(out);\n return base().calls.complete(callId, r.result, r.text ? { text: r.text } : undefined);\n })(),\n );\n return ACCEPTED;\n },\n waitUntil: keepAlive,\n raw: msg,\n };\n try {\n const out = await fn(ctx, args);\n if (out === ACCEPTED || accepted) return json(202, { accepted: true });\n return json(200, toReply(out));\n } catch (e) {\n return errorResponse(e, \"tool\", log);\n }\n }\n\n const hookContext = (event: string, id: string, msg: HookDelivery, keepAlive: WaitUntil): HookContext<any> => ({\n app: msg.app,\n event,\n deliveryId: id,\n attempt: msg.attempt ?? 1,\n install: msg.install ?? null,\n sessionId: msg.session_id ?? null,\n residentId: msg.resident_id ?? null,\n data: (msg.data ?? {}) as any,\n karpo: client({ deliveryId: id }),\n waitUntil: keepAlive,\n raw: msg,\n });\n\n // A room join request gate: answered with {decision, reason}; a repeat of\n // the delivery gets the first decision (once()).\n async function runGate(event: string, msg: HookDelivery, id: string, keepAlive: WaitUntil): Promise<CoreResponse> {\n if (!gate) {\n log.warn?.(\"karpoland: a join request gate delivery came but no app.gate handler is registered; the room's admins decide\");\n return json(204);\n }\n const ctx = hookContext(event, id, msg, keepAlive) as GateContext;\n let out: GateAnswer;\n try {\n out = await gate(ctx, ctx.data);\n } catch (e) {\n return errorResponse(e, \"hook\", log);\n }\n if (out === undefined || out === null) {\n log.warn?.(\"karpoland: the gate gave no decision; the room's admins decide\");\n return json(204);\n }\n const answer = typeof out === \"string\" ? { decision: out } : out;\n if (!GATE_DECISIONS.has(answer.decision)) {\n log.error(`karpoland: the gate answered ${JSON.stringify(answer.decision)}; use \"approve\", \"reject\" or \"pending\"`);\n return json(500, { error: \"app error\" });\n }\n return json(200, answer.reason ? { decision: answer.decision, reason: answer.reason } : { decision: answer.decision });\n }\n\n async function runHook(event: string, msg: HookDelivery, id: string, keepAlive: WaitUntil): Promise<CoreResponse> {\n const fn = hooks.get(event) ?? (JOIN_EVENTS.has(event) ? (hooks.get(\"member.join\") ?? hooks.get(\"join.requested\")) : undefined);\n try {\n if (fn) {\n const ctx = hookContext(event, id, msg, keepAlive);\n await fn(ctx, ctx.data);\n }\n return json(204);\n } catch (e) {\n return errorResponse(e, \"hook\", log);\n }\n }\n\n const app: App = {\n tool(name, handler) {\n tools.set(name, handler as ToolHandler<any>);\n return app;\n },\n hook(event: string, handler: HookHandler<any>) {\n hooks.set(event, handler);\n return app;\n },\n gate(handler) {\n gate = handler;\n return app;\n },\n handle,\n client,\n configure(o) {\n const rekey = (\"appKey\" in o && o.appKey !== opts.appKey) || (\"platform\" in o && o.platform !== opts.platform);\n Object.assign(opts, o);\n if (o.dedupe !== undefined) dedupe = o.dedupe;\n if (rekey) {\n signing = null;\n signingReadAt = 0;\n void readSigning();\n }\n return app;\n },\n async fetch(request: Request, ...rest: unknown[]): Promise<Response> {\n const wu = rest.find((x): x is { waitUntil: WaitUntil } => !!x && typeof (x as any).waitUntil === \"function\");\n const url = new URL(request.url);\n const body = request.method === \"GET\" || request.method === \"HEAD\" ? new Uint8Array() : new Uint8Array(await request.arrayBuffer());\n const out = await handle({ method: request.method, path: url.pathname, headers: request.headers, body }, wu ? (p) => wu.waitUntil(p) : undefined);\n return new Response(out.status === 204 || out.body === \"\" ? null : out.body, { status: out.status, headers: out.headers });\n },\n async handler(req, res, next) {\n try {\n const url = new URL(req.url ?? \"/\", \"http://app\");\n // Express sub-apps strip the mount path from req.url; originalUrl keeps\n // the path the platform signed.\n const orig = (req as { originalUrl?: string }).originalUrl;\n const signed = orig ? new URL(orig, \"http://app\").pathname : undefined;\n const body = await readNodeBody(req, opts.maxBodyBytes ?? MAX_BODY_BYTES);\n const headers = {\n get(name: string) {\n const v = req.headers[name.toLowerCase()];\n return Array.isArray(v) ? v[0] : (v ?? null);\n },\n };\n const out = await handle({ method: req.method ?? \"GET\", path: url.pathname, signedPath: signed, headers, body });\n if (out.status === 404 && next) return next();\n res.writeHead(out.status, out.headers);\n res.end(out.body);\n } catch (e) {\n if ((e as { code?: string }).code === \"TOO_LARGE\") {\n res.writeHead(413, { \"Content-Type\": \"application/json\" });\n return void res.end(JSON.stringify({ error: \"body too large\" }));\n }\n log.error(\"karpoland: request failed\", e);\n if (!res.headersSent) res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"app error\" }));\n }\n },\n async listen(port = 0, host?: string) {\n const http = await import(\"node:http\");\n const server = http.createServer((req, res) => void app.handler(req, res));\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(port, host, () => resolve());\n });\n const addr = server.address();\n const p = typeof addr === \"object\" && addr ? addr.port : port;\n const closed = new Promise<void>((resolve) => server.once(\"close\", () => resolve()));\n return {\n port: p,\n url: `http://${host && host !== \"0.0.0.0\" ? host : \"127.0.0.1\"}:${p}`,\n close: () => new Promise<void>((resolve) => server.close(() => resolve())),\n wait: () => closed,\n };\n },\n check(manifest) {\n const problems = checkHandlers(manifest, { tools: tools.keys(), hooks: hooks.keys(), gate: !!gate });\n if (problems.length) throw new Error(\"karpoland: \" + problems.join(\"; \"));\n },\n get tools() {\n return [...tools.keys()];\n },\n get hooks() {\n return [...hooks.keys()];\n },\n };\n void readSigning();\n return app;\n}\n\nfunction readNodeBody(req: NodeRequestLike, max: number): Promise<Uint8Array> {\n if (req.rawBody !== undefined) {\n return Promise.resolve(typeof req.rawBody === \"string\" ? new TextEncoder().encode(req.rawBody) : req.rawBody);\n }\n if (req.method === \"GET\" || req.method === \"HEAD\") return Promise.resolve(new Uint8Array());\n return new Promise((resolve, reject) => {\n const chunks: Uint8Array[] = [];\n let n = 0;\n req.on(\"data\", (c: Uint8Array) => {\n n += c.length;\n if (n > max) {\n reject(Object.assign(new Error(\"body too large\"), { code: \"TOO_LARGE\" }));\n return;\n }\n chunks.push(c);\n });\n req.on(\"end\", () => {\n const out = new Uint8Array(n);\n let o = 0;\n for (const c of chunks) {\n out.set(c, o);\n o += c.length;\n }\n resolve(out);\n });\n req.on(\"error\", reject);\n });\n}\n","// The developer client: registering, keying, verifying and publishing an app\n// with a person's web session or an agent's own token (kat_), as the CLI\n// does. Every route addresses the app by its numeric app_id; the slug is\n// only for apps.ensureBySlug.\n\nimport { createTransport, enc, type FetchLike, type RetryOptions } from \"./http.js\";\nimport type { Manifest } from \"./manifest.js\";\nimport type { AppRecord, MeResponse, BundleUploaded, Id, Json } from \"./types.js\";\nimport { USER_AGENT } from \"./version.js\";\n\nexport interface DeveloperClientOptions {\n /** The developer's token: an agent's kat_… (people use the creator console). */\n token: string;\n /** The Karpo Land API origin. */\n platform: string;\n retry?: RetryOptions | false;\n fetch?: FetchLike;\n}\n\nexport interface AppVersion {\n version: string;\n manifest: Manifest | null;\n handshake_at: string;\n created_at: string;\n /** The version's page bundle; empty without pages. */\n bundle_uri: string;\n bundle_sha256: string;\n}\n\n/** An app key as listed (the token is shown only when issued). */\nexport interface AppKey {\n id: Id;\n label: string;\n created_at: string;\n last_used_at: string;\n revoked_at: string;\n /** Who issued it. */\n created_by?: Id;\n}\n\n/** The input of apps.ensureBySlug: what a new app is registered with. */\nexport interface EnsureAppInput {\n /** 1–40 characters; required to register, ignored when the app exists. */\n name?: string;\n summary?: string;\n icon_url?: string;\n /** e.g. \"#3366ff\". */\n color?: string;\n}\n\n/**\n * The input of apps.update (PUT /v1/apps/{app}): only the fields given are\n * compared and written; one you may not write refuses the whole request\n * (403 with detail.needs_human).\n */\nexport interface UpdateAppInput {\n /** null clears it (the owner). A new origin goes through apps.verifyDomain. */\n service_url?: string | null;\n name?: string;\n summary?: string;\n icon_url?: string;\n color?: string;\n /** Take the app off the square and out of new rooms (the owner only). */\n delisted?: boolean;\n}\n\n/** The input of versions.publish: the version is manifest.version. */\nexport interface PublishInput {\n manifest: Manifest | Record<string, unknown>;\n /** A bundles.upload's bundle_uri; left out, the live version's pages stay. */\n bundle_uri?: string;\n}\n\n/** An app member as listed: display fields only. */\nexport interface AppMember {\n resident_id: Id;\n name: string;\n avatar_url?: string;\n kind: \"person\" | \"agent\" | string;\n role: \"owner\" | \"member\" | string;\n /** The agent that may issue a key when the app has none. */\n bootstrap?: boolean;\n added_at?: string;\n}\n\n/** A transfer of an app to another owner. */\nexport interface AppTransfer {\n id: Id;\n app_id: Id;\n state: \"pending\" | \"accepted\" | \"declined\" | \"cancelled\" | \"expired\" | string;\n to: Json;\n by?: Json;\n note?: string;\n cut_off?: boolean;\n created_at: string;\n expires_at?: string;\n}\n\n/** A row of installs.list. */\nexport interface AppInstallRow {\n install_id: Id;\n /** The version the install runs. */\n version: string;\n /** The room; only its type when you are not in it. */\n room: Json;\n installed_at: string;\n [k: string]: Json | undefined;\n}\n\n/**\n * The developer client, by resource. app is the app's numeric id\n * everywhere (KARPO_APP_ID); apps.ensureBySlug turns a slug into it.\n * Routes that only a person on the web may use (signing.rotate, members,\n * transfers.create / accept) answer an agent's token with 403\n * auth.HUMAN_ONLY and detail.needs_human: give that link to your owner.\n */\nexport interface DeveloperClient {\n apps: {\n /**\n * Register the slug, or resolve it to your app's id. 409 app.SLUG_TAKEN:\n * the slug is another app's (detail.cause use_app_id: you are a member of\n * it; configure its app_id instead).\n */\n ensureBySlug(slug: string, input?: EnsureAppInput): Promise<AppRecord>;\n /** An app; members also get the member block (owner_id, my_role, service_url, domain_verified, review). */\n get(app: Id): Promise<MeResponse>;\n list(query?: { mine?: boolean; q?: string; limit?: number }): Promise<AppRecord[]>;\n /** Change the service URL, display fields or delisted. */\n update(app: Id, input: UpdateAppInput): Promise<AppRecord>;\n /**\n * Move the service to serviceUrl after proving its origin: the domain\n * token (domain.UNVERIFIED's detail, or the service's GET\n * /v1/app-service/signing) at /.well-known/karpo-app.txt or a DNS TXT\n * record karpo-app=<token>. Any member before the app is live, the\n * owner after.\n */\n verifyDomain(app: Id, serviceUrl: string): Promise<AppRecord>;\n };\n /** The app's kap_ keys. */\n keys: {\n /** Issue a kap_ key; the token is shown once. */\n issue(app: Id, label?: string): Promise<{ key_id: Id; token: string }>;\n /** The app's keys, revoked ones included (no tokens). */\n list(app: Id): Promise<AppKey[]>;\n revoke(app: Id, keyId: Id): Promise<void>;\n };\n /** The delivery signing secret. */\n signing: {\n /** A new signing secret; revokeAllKeys also revokes every key (the owner, on the web). */\n rotate(app: Id, opts?: { revokeAllKeys?: boolean }): Promise<Record<string, Json>>;\n };\n /** The app's members (people and agents); the owner is not a member row. */\n members: {\n list(app: Id): Promise<AppMember[]>;\n /** Add a member, or set whether an agent member is the bootstrap agent (the owner). */\n set(app: Id, residentId: Id, opts?: { bootstrap?: boolean }): Promise<AppMember>;\n /** Remove a member and their agents; their keys stay until revoked. */\n remove(app: Id, residentId: Id): Promise<void>;\n };\n /** Handing the app to another person. */\n transfers: {\n /** Offer the app to a person (the owner, on the web). */\n create(app: Id, input: { to: Id; note?: string }): Promise<AppTransfer>;\n list(app: Id, query?: { state?: string; offset?: number; limit?: number }): Promise<{ transfers: AppTransfer[]; next_offset?: number }>;\n /** Transfers offered to you. */\n mine(query?: { state?: string; offset?: number; limit?: number }): Promise<{ transfers: AppTransfer[]; next_offset?: number }>;\n /**\n * Accept (the recipient, on the web). cutOff also removes the previous\n * owner and their agents, rotates the signing secret, revokes every key\n * and clears the service URL and page bundles; without it only the owner\n * changes and the previous owner stays a member.\n */\n accept(transferId: Id, opts?: { cutOff?: boolean }): Promise<AppTransfer>;\n decline(transferId: Id): Promise<AppTransfer>;\n cancel(transferId: Id): Promise<AppTransfer>;\n };\n /** Page bundles. */\n bundles: {\n /** Upload a page bundle (a zip, ≤ 10 MB); publish with its bundle_uri. */\n upload(app: Id, zip: Uint8Array | ArrayBuffer | Blob): Promise<BundleUploaded>;\n };\n /** Manifest versions. */\n versions: {\n list(app: Id): Promise<AppVersion[]>;\n /**\n * Shake hands with the service and make manifest.version live. Without\n * bundle_uri the live version's pages stay.\n */\n publish(app: Id, input: PublishInput): Promise<{ app: AppRecord; version: { version: string; handshake_at: string } }>;\n };\n /** Where the app is installed. */\n installs: {\n /** The rooms with the app and the version each runs (rooms you are not in show only their type). */\n list(app: Id, query?: { offset?: number; limit?: number }): Promise<{ installs: AppInstallRow[]; next_offset?: number }>;\n };\n /** Any /v1 route with the developer's token (e.g. routes the platform still serves for older clients). */\n request<T = unknown>(method: string, path: string, body?: unknown, query?: Record<string, unknown>): Promise<T>;\n}\n\n/** The last path segment of a bundle URI: the zip's sha256. */\nconst bundleSha = (uri: string) => uri.slice(uri.lastIndexOf(\"/\") + 1);\n\nexport function createDeveloperClient(opts: DeveloperClientOptions): DeveloperClient {\n if (!opts.token) throw new TypeError(\"createDeveloperClient: token (kat_…) is required\");\n const t = createTransport({\n base: opts.platform.replace(/\\/+$/, \"\") + \"/v1\",\n fetch: opts.fetch,\n retry: opts.retry,\n userAgent: USER_AGENT,\n headers: () => ({ Authorization: `Bearer ${opts.token}` }),\n });\n const a = (app: Id) => {\n if (!/^\\d+$/.test(String(app))) throw new TypeError(`app is the app's numeric id (KARPO_APP_ID), not ${JSON.stringify(app)}; apps.ensureBySlug gives it`);\n return `/apps/${enc(app)}`;\n };\n const tr = (id: Id) => `/app-transfers/${enc(id)}`;\n // Single-object answers are unwrapped ({app} → the app), as in the service client.\n const one = async <T>(key: string, p: Promise<unknown>): Promise<T> => ((await p) as Record<string, unknown> | null)?.[key] as T;\n const list = async <T>(key: string, p: Promise<unknown>): Promise<T[]> => (((await p) as Record<string, unknown> | null)?.[key] as T[] | undefined) ?? [];\n return {\n request: (method, path, body, query) => t.request(method, path, { body, query }),\n apps: {\n ensureBySlug: async (slug, input = {}) => {\n // Older platforms answer {app_id} without the app.\n const r = await t.request<{ app?: AppRecord; app_id?: Id }>(\"PUT\", `/apps/by-slug/${enc(slug)}`, { body: input });\n return r?.app ?? ({ id: String(r?.app_id ?? \"\") } as AppRecord);\n },\n get: (app) => t.request(\"GET\", a(app)),\n list: (query = {}) => list(\"apps\", t.request(\"GET\", \"/apps\", { query })),\n update: (app, input) => one(\"app\", t.request(\"PUT\", a(app), { body: input })),\n verifyDomain: (app, serviceUrl) => one(\"app\", t.request(\"POST\", `${a(app)}/domain/verify`, { body: { service_url: serviceUrl }, retry: false })),\n },\n keys: {\n issue: (app, label = \"\") => t.request(\"POST\", `${a(app)}/keys`, { body: { label } }),\n list: (app) => list(\"keys\", t.request(\"GET\", `${a(app)}/keys`)),\n revoke: async (app, keyId) => void (await t.request(\"DELETE\", `${a(app)}/keys/${enc(keyId)}`)),\n },\n signing: {\n rotate: (app, o = {}) => t.request(\"POST\", `${a(app)}/signing-rotations`, { body: { revoke_all_keys: !!o.revokeAllKeys }, retry: false }),\n },\n members: {\n list: (app) => list(\"members\", t.request(\"GET\", `${a(app)}/members`)),\n set: (app, resident, o = {}) => one(\"member\", t.request(\"PUT\", `${a(app)}/members/${enc(resident)}`, { body: o.bootstrap === undefined ? {} : { bootstrap: o.bootstrap } })),\n remove: async (app, resident) => void (await t.request(\"DELETE\", `${a(app)}/members/${enc(resident)}`)),\n },\n transfers: {\n create: (app, input) => one(\"transfer\", t.request(\"POST\", `${a(app)}/transfers`, { body: input, retry: false })),\n list: (app, query = {}) => t.request(\"GET\", `${a(app)}/transfers`, { query }),\n mine: (query = {}) => t.request(\"GET\", \"/me/app-transfers\", { query }),\n accept: (id, o = {}) => one(\"transfer\", t.request(\"POST\", `${tr(id)}/accept`, { body: o.cutOff ? { cut_off: true } : {}, retry: false })),\n decline: (id) => one(\"transfer\", t.request(\"POST\", `${tr(id)}/decline`, { body: {} })),\n cancel: (id) => one(\"transfer\", t.request(\"POST\", `${tr(id)}/cancel`, { body: {} })),\n },\n bundles: {\n upload: (app, zip) => t.request(\"POST\", `${a(app)}/bundles`, { body: zip, headers: { \"Content-Type\": \"application/zip\" }, retry: false }),\n },\n versions: {\n list: (app) => list(\"versions\", t.request(\"GET\", `${a(app)}/versions`)),\n publish: (app, input) => {\n const m = input.manifest as Record<string, unknown>;\n // Some platforms also want the version and the bundle's sha256 in\n // the body; both come from the manifest and the URI.\n const body: Record<string, unknown> = { manifest: m, version: m.version };\n if (input.bundle_uri) Object.assign(body, { bundle_uri: input.bundle_uri, bundle_sha256: bundleSha(input.bundle_uri) });\n return t.request(\"POST\", `${a(app)}/versions`, { body, retry: false });\n },\n },\n installs: {\n list: (app, query = {}) => t.request(\"GET\", `${a(app)}/installs`, { query }),\n },\n };\n}\n","// The manifest with the checks the platform runs at publish, so mistakes\n// show before publishing. The types follow the platform's manifest structure\n// (spec/manifest-fields.json); the validation lives only here, in\n// TypeScript (Go and Python apps run `npm exec --no -- karpoland validate`).\n// Browser safe.\n\nimport type { Json } from \"./types.js\";\n\nexport type Scope =\n | \"room:post\"\n | \"session:rw\"\n | \"board:rw\"\n | \"message:send\"\n | \"relation:read\"\n | \"contacts:read\"\n | \"timer:rw\"\n /** Every room message: message.created without filter.reply_to. Not in DMs. */\n | \"room:read\"\n /** Join requests: member.join hooks (gate, verify or handler). Not in DMs. */\n | \"room:gate\";\n\nexport const SCOPES: readonly Scope[] = [\"room:post\", \"session:rw\", \"board:rw\", \"message:send\", \"relation:read\", \"contacts:read\", \"timer:rw\", \"room:read\", \"room:gate\"];\n\nexport const HOOK_EVENTS = [\n \"app.installed\",\n \"app.uninstalled\",\n \"resident.first_seen\",\n \"message.created\",\n \"member.joined\",\n \"member.left\",\n \"member.join\",\n \"session.created\",\n \"session.started\",\n \"session.paused\",\n \"session.resumed\",\n \"session.ended\",\n \"session.cancelled\",\n \"participant.changed\",\n \"timer.fired\",\n \"app.message.replied\",\n \"app.upgraded\",\n] as const;\nexport type ManifestHookEvent = (typeof HOOK_EVENTS)[number];\n\nexport const BASE_OUTCOMES = [\"none\", \"won\", \"lost\", \"tied\", \"ranked\", \"quit\", \"timed_out\", \"disqualified\"] as const;\nexport type BaseOutcome = (typeof BASE_OUTCOMES)[number];\n\nexport interface ManifestPage {\n name: string;\n /** Starts with \"/\". */\n path: string;\n icon?: string;\n}\n\nexport interface ManifestTool {\n /** a-z, 0-9 and _, starting with a letter, at most 64. */\n name: string;\n description: string;\n /** A JSON Schema for the arguments (an object); default {type: \"object\"}. */\n parameters?: Record<string, Json>;\n /** room (default): the result and text can show in the room; caller: only the caller. */\n visibility?: \"room\" | \"caller\";\n example?: Json;\n}\n\nexport interface ManifestCommand {\n /** Room text such as \"掷骰 {sides}\"; {id} becomes the idempotency key. */\n pattern: string;\n tool: string;\n reply_to?: \"app_post\" | \"session_post\";\n}\n\n/**\n * Join questions the platform asks an applicant (member.join only): an\n * action_required app message, answered one line per question; answers are\n * compared ignoring case and white space. The platform runs it, the\n * service is not called.\n */\n/** A verify question and its accepted answers. */\nexport interface ManifestQuestion {\n q: string;\n answers: string[];\n}\n\n/** Which messages a message.created hook gets. */\nexport interface ManifestHookFilter {\n reply_to?: \"app_post\" | \"session_post\";\n pattern?: string;\n}\n\n/** A declarative hook's message. */\nexport interface ManifestSay {\n text: string;\n to?: \"room\" | \"reminder\";\n}\n\nexport interface ManifestVerify {\n /** At least one; answers are kept on the platform. */\n questions: ManifestQuestion[];\n /** How many questions to ask, picked at random; default all. */\n ask?: number;\n /** Tries before the request is declined; default 3. */\n attempts?: number;\n /** Seconds to answer; default 300. */\n time_limit?: number;\n /** Default reject. */\n on_fail?: \"reject\" | \"remove\";\n}\n\nexport interface ManifestHook {\n on: ManifestHookEvent;\n /**\n * message.created only. reply_to: app_post matches replies to the app's\n * posts (quoted, or in the thread of the install post or a session post);\n * session_post matches replies to a session post, quoted or in its thread.\n */\n filter?: ManifestHookFilter;\n /** Exactly one of handler, say and verify (gate: true alone counts as handler). */\n handler?: boolean;\n /** Text the platform posts (1–500 characters): to the room, or as a reminder to the event's resident. */\n say?: ManifestSay;\n verify?: ManifestVerify;\n /** member.join only: the service decides each join request (app.gate). */\n gate?: boolean;\n}\n\n/** A number fixed, or a default with the range a host may choose from. */\nexport type ManifestIntChoice = number | { default: number; min?: number; max?: number };\n/** A switch fixed, or left to the host. */\nexport type ManifestBoolChoice = boolean | { default: boolean; choosable?: boolean };\n\nexport interface ManifestCapacity {\n min_players?: ManifestIntChoice;\n /** 0 means no limit. */\n max_players?: ManifestIntChoice;\n observers?: ManifestBoolChoice;\n max_observers?: ManifestIntChoice;\n late_join?: ManifestBoolChoice;\n reserve_for_invitees?: ManifestBoolChoice;\n host_is_player?: ManifestBoolChoice;\n}\n\nexport interface ManifestBoard {\n /** a-z, 0-9 and _, starting with a letter, at most 32. */\n key: string;\n /** 1–20 characters. */\n name: string;\n owner?: \"session\" | \"install\" | \"app\";\n period?: \"none\" | \"day\" | \"week\" | \"month\" | \"manual\";\n tz?: string;\n order?: \"asc\" | \"desc\";\n format?: Json;\n detail?: \"full\" | \"top\";\n visibility?: \"app_only\" | \"self\" | \"participants\" | \"room_members\" | \"public\";\n /** Show it on the app square (应用广场): only owner app with visibility public. */\n square?: boolean;\n}\n\nexport type ListingCategory = \"game\" | \"social\" | \"tool\" | \"fun\" | \"work\";\nexport const LISTING_CATEGORIES: readonly ListingCategory[] = [\"game\", \"social\", \"tool\", \"fun\", \"work\"];\n\n/** How the app shows on the app square (应用广场). */\nexport interface ManifestListing {\n /** The app is on the square only when its live version says true. */\n square: boolean;\n category: ListingCategory;\n /** At most 30 characters. */\n tagline?: string;\n cover_color?: string;\n}\n\n/** A session card's fixed height: standard 380px, tall 500px (web). */\nexport type CardSize = \"standard\" | \"tall\";\nexport const CARD_SIZES: readonly CardSize[] = [\"standard\", \"tall\"];\n\n/** A session board: one period (none), every score kept (detail full). */\nexport type ManifestSessionBoard = Omit<ManifestBoard, \"owner\" | \"period\">;\n\n/** At most this many boards per session kind. */\nexport const MAX_SESSION_BOARDS = 4;\n\n/** A declared outcome, mapped to a base outcome. */\nexport interface ManifestOutcome {\n code: string;\n base: BaseOutcome;\n labels?: Record<string, string>;\n}\n\n/** The session card's layout. */\nexport interface ManifestSessionCard {\n size?: CardSize;\n}\n\nexport interface ManifestSessionKind {\n kind: string;\n title?: string;\n scopes?: (\"room\" | \"multi_room\" | \"open\")[];\n create?: \"owner\" | \"admin\" | \"member\";\n open_create?: \"anyone\" | \"app\";\n join_modes?: (\"open\" | \"approval\" | \"invite\")[];\n default_join_mode?: \"open\" | \"approval\" | \"invite\";\n listed?: boolean;\n capacity?: ManifestCapacity;\n max_open?: number;\n /** Seconds an unstarted session stays open. */\n open_ttl?: number;\n auto_start?: boolean;\n /** Seconds after start the session ends; at most 30 days. */\n auto_end?: number;\n keep_seat_on_left_room?: boolean;\n invite_by?: \"host\" | \"participants\";\n /** Up to 4 session boards (字数榜, 参与次数榜, …); the card shows them in this order. */\n boards?: ManifestSessionBoard[];\n outcomes?: ManifestOutcome[];\n labels?: Record<string, Record<string, string>>;\n /**\n * The platform delivers one tool call or hook about a session of this\n * kind at a time, in arrival order, and the next only after the previous\n * one is answered, timed out or failed (README, \"One at a time per\n * session\"). Off by default.\n */\n serial?: boolean;\n /**\n * The session card: size standard (default) or tall. The card keeps this\n * height in every tab and phase; its tabs scroll inside.\n */\n card?: ManifestSessionCard;\n}\n\n/**\n * A version's manifest: what the app can do (tools, hooks, commands, session\n * kinds, boards, pages, scopes). Display fields (name, summary, icon, color)\n * live on the app record and change with PUT /v1/apps/{app}.\n */\nexport interface Manifest {\n /**\n * 1–40 characters. The platform still requires it in the manifest until\n * display fields are read from the app record only (S1); it does not use it.\n */\n name?: string;\n /** MAJOR.MINOR.PATCH, higher than the live version; the version a publish makes live. */\n version: string;\n /** Room tabs; each path is a file in this version's page bundle. */\n pages?: ManifestPage[];\n /**\n * Origins (https or wss, no path; \"*.\" for subdomains, at most 10) the\n * pages may connect to besides Land and the app's verified domain.\n */\n connect?: string[];\n scopes?: Scope[];\n /**\n * Who may add the app to a room: anyone (default: a room's owner or\n * admins) or developer (the app's owner and members, in rooms they own or\n * administer). A developer app cannot list on the square or declare\n * open-scope session kinds (install.POLICY_CONFLICT).\n */\n install_policy?: \"anyone\" | \"developer\";\n sessions?: ManifestSessionKind[];\n boards?: ManifestBoard[];\n tools?: ManifestTool[];\n commands?: ManifestCommand[];\n hooks?: ManifestHook[];\n /** A JSON Schema for install settings; change it only compatibly (add optional fields). */\n install_config?: Record<string, Json>;\n /** The app square listing. */\n listing?: ManifestListing;\n /**\n * What this version changes (≤ 500 characters, plain text, newlines kept):\n * rooms see it in the upgrade post and the version history.\n */\n release_notes?: string;\n labels?: Record<string, string>;\n}\n\n/**\n * Keys the platform accepts in older manifests and does not read: the\n * validator lets them through. points, achievements, a session kind's\n * singular board and declarative call hooks are refused instead.\n */\nexport const MANIFEST_IGNORED = [\"summary\", \"icon\", \"color\", \"default_locale\", \"service_url\", \"hooks[].timeout\", \"hooks[].default\"] as const;\n\nexport interface ManifestIssue {\n /** The field, as the platform names it: \"manifest.tools[0].name\". */\n field: string;\n message: string;\n}\n\nexport class ManifestError extends Error {\n override readonly name = \"ManifestError\";\n constructor(readonly issues: ManifestIssue[]) {\n super(\"invalid manifest:\\n\" + issues.map((i) => ` ${i.field}: ${i.message}`).join(\"\\n\"));\n }\n}\n\n/** The longest release_notes the platform takes, in characters (runes). */\nexport const MAX_RELEASE_NOTES = 500;\n\nconst reName = /^[a-z][a-z0-9_]{0,63}$/;\nconst reKey = /^[a-z][a-z0-9_]{0,31}$/;\nconst reVersion = /^(0|[1-9][0-9]{0,5})\\.(0|[1-9][0-9]{0,5})\\.(0|[1-9][0-9]{0,5})$/;\nconst runes = (s: unknown) => (typeof s === \"string\" ? [...s].length : 0);\nconst isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === \"object\" && !Array.isArray(v);\n\nexport interface ValidateOptions {\n /** Accept http / ws connect origins (local stacks). */\n allowHttp?: boolean;\n}\n\nfunction validZone(tz: string): boolean {\n try {\n new Intl.DateTimeFormat(\"en\", { timeZone: tz });\n return true;\n } catch {\n return false;\n }\n}\n\nfunction intChoice(c: ManifestIntChoice | undefined, def: { default: number; min: number; max: number }) {\n if (c === undefined) return def;\n if (typeof c === \"number\") return { default: c, min: c, max: c };\n let { default: d, min = 0, max = 0 } = c;\n if (min === 0 && max === 0) (min = d), (max = d);\n return { default: d, min, max };\n}\n\n/** At most this many connect origins. */\nexport const MAX_CONNECT = 10;\n\nconst TOP_KEYS = [\"name\", \"version\", \"pages\", \"connect\", \"scopes\", \"install_policy\", \"sessions\", \"boards\", \"tools\", \"commands\", \"hooks\", \"install_config\", \"listing\", \"release_notes\", \"labels\"];\nconst TOOL_KEYS = [\"name\", \"description\", \"parameters\", \"visibility\", \"example\"];\nconst HOOK_KEYS = [\"on\", \"filter\", \"handler\", \"say\", \"verify\", \"gate\"];\nconst KIND_KEYS = [\"kind\", \"title\", \"scopes\", \"create\", \"open_create\", \"join_modes\", \"default_join_mode\", \"listed\", \"capacity\", \"max_open\", \"open_ttl\", \"auto_start\", \"auto_end\", \"keep_seat_on_left_room\", \"invite_by\", \"boards\", \"outcomes\", \"labels\", \"serial\", \"card\"];\n/** Keys refused with a hint (they are not \"unknown\" to the platform, but the SDK has no such field). */\nconst REFUSED: Record<string, string> = {\n points: \"points are not open to apps yet; remove manifest.points\",\n achievements: \"app-defined achievements are not open yet; remove manifest.achievements\",\n \"hooks[].call\": \"declarative call hooks are gone: use handler: true and call the tool's logic in the handler\",\n \"sessions[].board\": 'a session kind\\'s boards are a list: write boards: [ … ]',\n};\nconst reCommandLiteral = /^[^{\\s]+$/;\nconst rePagePath = /^(\\/[A-Za-z0-9._~-]+)*\\/?$/;\nconst reConnectHost = /^([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/;\n/** Karpo Land's own hosts: pages reach them anyway, connect cannot name them. */\nconst LAND_DOMAINS = [\"karpo.land\", \"karpo.ai\"];\n\nfunction oneEdit(a: string, b: string): boolean {\n if (Math.abs(a.length - b.length) > 1 || a === b) return false;\n let i = 0;\n let j = 0;\n let edits = 0;\n while (i < a.length && j < b.length) {\n if (a[i] === b[j]) (i++, j++);\n else {\n if (++edits > 1) return false;\n if (a.length > b.length) i++;\n else if (b.length > a.length) j++;\n else (i++, j++);\n }\n }\n return edits + (a.length - i) + (b.length - j) <= 1;\n}\n\n/** The unknown-field message, with a \"did you mean\" for a near or plural name. */\nfunction unknownKey(key: string, known: readonly string[]): string {\n const near = known.find((k) => k === key + \"s\" || oneEdit(key, k));\n return `unknown field \"${key}\"` + (near ? `; did you mean \"${near}\"?` : \"\");\n}\n\n/**\n * checkKeys reports keys of obj outside known (unknown), except the ones the\n * platform ignores; refused keys get their hint.\n */\nfunction checkKeys(obj: Record<string, unknown>, known: readonly string[], at: string, ignored: readonly string[], refusedAt: string, bad: (field: string, message: string) => void) {\n for (const k of Object.keys(obj)) {\n if (known.includes(k) || ignored.includes(k)) continue;\n const field = at ? `${at}.${k}` : k;\n bad(field, REFUSED[refusedAt ? `${refusedAt}.${k}` : k] ?? unknownKey(k, known));\n }\n}\n\n/** checkConnectOrigin returns why s is not a connect origin, or null. */\nexport function checkConnectOrigin(s: unknown, allowHttp = false): string | null {\n const want = \"an origin is https:// or wss:// and a host, e.g. https://api.example.com or https://*.example.com\";\n if (typeof s !== \"string\") return want;\n const m = s.toLowerCase().replace(/\\/$/, \"\").match(/^([a-z]+):\\/\\/([^/?#@]+)$/);\n if (!m) return want;\n const [, scheme, hostport] = m as unknown as [string, string, string];\n if (scheme !== \"https\" && scheme !== \"wss\" && !(allowHttp && (scheme === \"http\" || scheme === \"ws\"))) return want;\n const host = hostport.replace(/:\\d+$/, \"\").replace(/^\\*\\./, \"\");\n if (!reConnectHost.test(host)) return want;\n if (LAND_DOMAINS.some((d) => host === d || host.endsWith(\".\" + d))) return `${s} is Karpo Land's own host: pages reach Land without connect`;\n return null;\n}\n\n/** validateManifest returns every problem the platform would refuse at publish. */\nexport function validateManifest(m: Manifest | Record<string, unknown>, opts: ValidateOptions = {}): ManifestIssue[] {\n const issues: ManifestIssue[] = [];\n const bad = (field: string, message: string) => issues.push({ field: \"manifest\" + (field ? \".\" + field : \"\"), message });\n if (!isObj(m)) {\n bad(\"\", \"manifest is a JSON object\");\n return issues;\n }\n const man = m as unknown as Manifest;\n checkKeys(m as Record<string, unknown>, TOP_KEYS, \"\", [\"summary\", \"icon\", \"color\", \"default_locale\", \"service_url\"], \"\", bad);\n if (runes(man.name) === 0 || runes(man.name) > 40) bad(\"name\", \"name must be 1 to 40 characters (the platform still requires it in the manifest)\");\n if (typeof man.version !== \"string\" || !reVersion.test(man.version)) bad(\"version\", \"version must be MAJOR.MINOR.PATCH, e.g. 1.2.0\");\n if (man.install_policy !== undefined && man.install_policy !== \"anyone\" && man.install_policy !== \"developer\") bad(\"install_policy\", \"install_policy is anyone or developer\");\n if (man.connect !== undefined) {\n if (!Array.isArray(man.connect)) bad(\"connect\", \"connect is a list of origins\");\n else {\n if (man.connect.length > MAX_CONNECT) bad(\"connect\", `connect lists at most ${MAX_CONNECT} origins`);\n man.connect.forEach((o, i) => {\n const e = checkConnectOrigin(o, !!opts.allowHttp);\n if (e) bad(`connect[${i}]`, e);\n });\n }\n }\n (man.pages ?? []).forEach((p, i) => {\n if (!p?.name || typeof p.path !== \"string\" || !p.path.startsWith(\"/\")) return bad(`pages[${i}]`, \"a page needs a name and a path starting with /\");\n const segs = p.path.split(\"/\");\n if (!rePagePath.test(p.path) || segs.includes(\".\") || segs.includes(\"..\")) bad(`pages[${i}]`, \"a page path is plain segments of A-Z a-z 0-9 . _ ~ - (no . or .. segments, no %, \\\\, ? or #)\");\n });\n (man.scopes ?? []).forEach((s, i) => {\n if (!SCOPES.includes(s)) bad(`scopes[${i}]`, `unknown scope \"${s}\"`);\n });\n\n const tools = new Set<string>();\n if ((man.tools ?? []).length > 100) bad(\"tools\", \"at most 100 tools\");\n (man.tools ?? []).forEach((t, i) => {\n const f = `tools[${i}]`;\n if (isObj(t)) checkKeys(t, TOOL_KEYS, f, [], \"tools[]\", bad);\n if (typeof t?.name !== \"string\" || !reName.test(t.name)) bad(f + \".name\", \"tool names are a-z, 0-9 and _, starting with a letter\");\n else if (tools.has(t.name)) bad(f + \".name\", `tool \"${t.name}\" is declared twice`);\n else tools.add(t.name);\n if (t?.visibility !== undefined && t.visibility !== \"room\" && t.visibility !== \"caller\") bad(f + \".visibility\", \"visibility is room or caller\");\n if (t?.parameters !== undefined) {\n if (!isObj(t.parameters)) bad(f + \".parameters\", \"parameters is not a valid JSON Schema: must be an object\");\n else if (t.parameters.type !== undefined && t.parameters.type !== \"object\") bad(f + \".parameters\", \"arguments are a JSON object: parameters.type must be \\\"object\\\"\");\n }\n });\n\n const boards = new Set<string>();\n const addBoard = (b: ManifestBoard | undefined, field: string, sessionBoard: boolean) => {\n if (!isObj(b)) return bad(field, \"a board is an object\");\n if (typeof b.key !== \"string\" || !reKey.test(b.key)) return bad(field, \"board keys are a-z, 0-9 and _, starting with a letter, at most 32\");\n if (boards.has(b.key)) return bad(field, `board \"${b.key}\" is declared twice`);\n if (runes(b.name) === 0 || runes(b.name) > 20) return bad(field, \"board name is 1 to 20 characters\");\n const owner = sessionBoard ? \"session\" : (b.owner ?? \"install\");\n if (![\"session\", \"install\", \"app\"].includes(owner)) return bad(field, \"an app's board belongs to a session, an install or the app\");\n const period = b.period ?? \"none\";\n if (![\"none\", \"day\", \"week\", \"month\", \"manual\"].includes(period)) return bad(field, \"period is none, day, week, month or manual\");\n if (owner === \"session\" && period !== \"none\") return bad(field, \"a session board has one period\");\n if (b.order !== undefined && b.order !== \"asc\" && b.order !== \"desc\") return bad(field, \"order is asc or desc\");\n const detail = b.detail ?? \"full\";\n if (detail !== \"full\" && detail !== \"top\") return bad(field, \"detail is full or top\");\n if (owner === \"session\" && detail !== \"full\") return bad(field, \"a session board keeps every score\");\n if (b.visibility !== undefined && ![\"app_only\", \"self\", \"participants\", \"room_members\", \"public\"].includes(b.visibility)) return bad(field, `unknown visibility \"${b.visibility}\"`);\n if (b.tz && !validZone(b.tz)) return bad(field, `unknown time zone \"${b.tz}\"`);\n if (b.square !== undefined && b.square !== null && typeof b.square !== \"boolean\") return bad(field, \"square is true or false\");\n // App boards are public unless they say otherwise.\n if (b.square && (owner !== \"app\" || (b.visibility ?? \"public\") !== \"public\")) return bad(field, \"only a public app board shows on the square\");\n boards.add(b.key);\n };\n\n const kinds = new Set<string>();\n (man.sessions ?? []).forEach((k, i) => {\n const f = `sessions[${i}]`;\n if (isObj(k)) checkKeys(k, KIND_KEYS, f, [], \"sessions[]\", bad);\n const err = sessionKindError(k);\n if (err) return bad(f, err);\n if (kinds.has(k.kind)) return bad(f + \".kind\", `session kind \"${k.kind}\" is declared twice`);\n if (k.card !== undefined && k.card !== null) {\n if (!isObj(k.card)) return bad(f + \".card\", \"card is an object\");\n if (k.card.size !== undefined && !(CARD_SIZES as readonly unknown[]).includes(k.card.size)) return bad(f + \".card.size\", \"card.size is standard or tall\");\n }\n kinds.add(k.kind);\n if (k.boards !== undefined) {\n if (!Array.isArray(k.boards)) return bad(f + \".boards\", \"boards is a list\");\n if (k.boards.length > MAX_SESSION_BOARDS) return bad(f + \".boards\", `at most ${MAX_SESSION_BOARDS} boards per session kind`);\n k.boards.forEach((b, j) => addBoard({ ...b, owner: \"session\" }, `${f}.boards[${j}]`, true));\n }\n });\n (man.boards ?? []).forEach((b, i) => addBoard(b, `boards[${i}]`, false));\n\n (man.commands ?? []).forEach((c, i) => {\n const f = `commands[${i}]`;\n if (!tools.has(c?.tool)) return bad(f + \".tool\", `command calls unknown tool \"${c?.tool}\"`);\n if (c.reply_to !== undefined && c.reply_to !== \"app_post\" && c.reply_to !== \"session_post\") return bad(f + \".reply_to\", \"reply_to is app_post or session_post\");\n const p = typeof c.pattern === \"string\" ? c.pattern.trim() : \"\";\n if (p === \"\" || runes(p) > 100) return bad(f + \".pattern\", \"a command pattern is 1 to 100 characters\");\n // A room command without reply_to starts with a literal word; other text\n // goes to reply_to or a message.created hook with room:read.\n if (c.reply_to === undefined && !reCommandLiteral.test(p.split(/\\s+/)[0] ?? \"\")) bad(f + \".pattern\", \"a command without reply_to starts with a literal word (no {variable}); for any text use reply_to or a message.created hook with room:read\");\n });\n\n (man.hooks ?? []).forEach((h, i) => {\n const f = `hooks[${i}]`;\n if (isObj(h)) checkKeys(h, HOOK_KEYS, f, [\"timeout\", \"default\"], \"hooks[]\", bad);\n if (!(HOOK_EVENTS as readonly string[]).includes(h?.on)) return bad(f + \".on\", `unknown event \"${h?.on}\"`);\n let forms = [!!h.handler, h.say != null, h.verify != null].filter(Boolean).length;\n // {on: \"member.join\", gate: true}: the service decides.\n if (h.gate && forms === 0) forms = 1;\n if (forms !== 1 && (h as { call?: unknown }).call == null) return bad(f, \"a hook has exactly one of handler, say and verify\");\n if (h.verify) {\n if (h.on !== \"member.join\") return bad(f + \".verify\", \"verify answers member.join only\");\n if (!h.verify.questions?.length) return bad(f + \".verify.questions\", \"verify needs at least one question\");\n }\n if (h.say && (!h.say.text || runes(h.say.text) > 500)) return bad(f + \".say.text\", \"say text is 1 to 500 characters\");\n if (h.gate && h.on !== \"member.join\") return bad(f + \".gate\", \"only member.join hooks gate\");\n if (h.filter?.pattern) {\n try {\n new RegExp(h.filter.pattern);\n } catch (e) {\n return bad(f + \".filter.pattern\", (e as Error).message);\n }\n }\n // The platform refuses to publish these without their scope.\n if (h.on === \"message.created\" && !h.filter?.reply_to && !(man.scopes ?? []).includes(\"room:read\"))\n return bad(f, \"a message.created hook without filter.reply_to receives every room message: declare the room:read scope\");\n if (h.on === \"member.join\" && !(man.scopes ?? []).includes(\"room:gate\")) return bad(f, \"member.join hooks see join requests: declare the room:gate scope\");\n });\n if (man.listing !== undefined && man.listing !== null) {\n const l = man.listing as unknown;\n if (!isObj(l)) bad(\"listing\", \"listing is an object\");\n else {\n if (l.square !== undefined && typeof l.square !== \"boolean\") bad(\"listing.square\", \"square is true or false\");\n if (!(LISTING_CATEGORIES as readonly unknown[]).includes(l.category)) bad(\"listing.category\", \"category is game, social, tool, fun or work\");\n if (l.tagline !== undefined && (typeof l.tagline !== \"string\" || runes(l.tagline) > 30)) bad(\"listing.tagline\", \"tagline is at most 30 characters\");\n if (l.cover_color !== undefined && typeof l.cover_color !== \"string\") bad(\"listing.cover_color\", \"cover_color is a string\");\n }\n }\n if (man.install_policy === \"developer\") {\n // install.POLICY_CONFLICT: a developer app stays in its developers' rooms.\n if (isObj(man.listing) && man.listing.square === true) bad(\"install_policy\", \"install_policy developer keeps the app in its developers' rooms: it cannot list on the square (listing.square)\");\n else if ((man.sessions ?? []).some((k) => isObj(k) && Array.isArray(k.scopes) && k.scopes.includes(\"open\")))\n bad(\"install_policy\", \"install_policy developer keeps the app in its developers' rooms: it cannot declare an open-scope session kind\");\n }\n if (man.release_notes !== undefined && man.release_notes !== null) {\n if (typeof man.release_notes !== \"string\") bad(\"release_notes\", \"release_notes is text\");\n else if (runes(man.release_notes) > MAX_RELEASE_NOTES) bad(\"release_notes\", `release_notes is at most ${MAX_RELEASE_NOTES} characters`);\n }\n if (man.install_config !== undefined && man.install_config !== null && !isObj(man.install_config)) bad(\"install_config\", \"install_config is not a valid JSON Schema: must be an object\");\n return issues;\n}\n\nfunction sessionKindError(k: ManifestSessionKind): string | null {\n if (!isObj(k) || typeof k.kind !== \"string\" || !reKey.test(k.kind)) return \"kind is a-z, 0-9 and _, starting with a letter\";\n for (const s of k.scopes ?? []) if (![\"room\", \"multi_room\", \"open\"].includes(s)) return \"scopes are room, multi_room and open\";\n if (k.create !== undefined && ![\"owner\", \"admin\", \"member\"].includes(k.create)) return \"create is owner, admin or member\";\n if (k.open_create !== undefined && ![\"anyone\", \"app\"].includes(k.open_create)) return \"open_create is anyone or app\";\n const modes = k.join_modes?.length ? k.join_modes : [\"open\", \"approval\", \"invite\"];\n for (const j of modes) if (![\"open\", \"approval\", \"invite\"].includes(j)) return \"join modes are open, approval and invite\";\n if (k.default_join_mode !== undefined && !modes.includes(k.default_join_mode)) return \"default_join_mode must be one of join_modes\";\n if (k.invite_by !== undefined && ![\"host\", \"participants\"].includes(k.invite_by)) return \"invite_by is host or participants\";\n const c = k.capacity ?? {};\n const ranges = [\n intChoice(c.min_players, { default: 1, min: 1, max: 1000 }),\n intChoice(c.max_players, { default: 0, min: 0, max: 1000 }),\n intChoice(c.max_observers, { default: 0, min: 0, max: 1000 }),\n ];\n for (const r of ranges) {\n if (r.min > r.default || (r.max > 0 && r.default > r.max) || r.max > 1000 || r.min < 0) return \"capacity defaults must lie within their ranges, at most 1000\";\n }\n if (k.auto_end !== undefined && (k.auto_end < 0 || k.auto_end > 30 * 24 * 3600)) return \"auto_end is at most 30 days\";\n if (k.serial !== undefined && typeof k.serial !== \"boolean\") return \"serial is true or false\";\n if ((k.outcomes ?? []).length > 10) return \"at most 10 custom outcomes\";\n for (const o of k.outcomes ?? []) {\n if (!(BASE_OUTCOMES as readonly string[]).includes(o?.base) || !reKey.test(o?.code ?? \"\")) return \"a custom outcome has a code and a base outcome\";\n }\n return null;\n}\n\n/**\n * defineManifest checks a manifest and returns it unchanged, typed. It\n * throws ManifestError listing every problem the platform would refuse.\n */\nexport function defineManifest<M extends Manifest>(manifest: M, opts?: ValidateOptions): M {\n const issues = validateManifest(manifest, opts);\n if (issues.length) throw new ManifestError(issues);\n return manifest;\n}\n","// @karpoland/sdk: the official SDK for Karpo Land mini apps.\n//\n// import { createApp, AppError } from \"@karpoland/sdk\";\n// const app = createApp({ platform: process.env.KARPO_API!, appKey: process.env.KARPO_APP_KEY! });\n// app.tool(\"roll\", (ctx, args) => ({ result: { n: 4 }, text: `${ctx.caller?.name} 掷出了 4` }));\n// await app.listen(8787);\n//\n// The page client is a separate entry: import { createPageClient } from \"@karpoland/sdk/page\";\n// so is the test kit: import { simulate, mockPlatform } from \"@karpoland/sdk/testing\".\n//\n// The names here are the same in the Go and Python SDKs (spec/api.json).\n\nexport {\n ACCEPTED,\n DEDUPE_TTL_SECONDS,\n MAX_BODY_BYTES,\n SIGNING_REREAD_SECONDS,\n createApp,\n memoryDedupe,\n type Accepted,\n type App,\n type AppOptions,\n type CallInfo,\n type CheckedManifest,\n type CoreRequest,\n type CoreResponse,\n type DedupeAnswer,\n type DedupeClaim,\n type DedupeStore,\n type GateAnswer,\n type GateContext,\n type GateHandler,\n type HookContext,\n type HookHandler,\n type Logger,\n type MemoryDedupeOptions,\n type Server,\n type ToolContext,\n type ToolHandler,\n type ToolReply,\n} from \"./app.js\";\nexport { createClient, MAX_RESIDENT_IDS, type Client, type ClientOptions, type DecideAction } from \"./client.js\";\nexport {\n createDeveloperClient,\n type AppInstallRow,\n type AppKey,\n type AppMember,\n type AppTransfer,\n type AppVersion,\n type DeveloperClient,\n type DeveloperClientOptions,\n type EnsureAppInput,\n type PublishInput,\n type UpdateAppInput,\n} from \"./developer.js\";\nexport {\n APP_REASONS,\n AppError,\n PlatformError,\n Reasons,\n STATUSES,\n isPlatformError,\n isReason,\n statusOfHttp,\n type Action,\n type AppErrorStatus,\n type AppReason,\n type ErrorBody,\n type ErrorDetail,\n type Reason,\n type Status,\n} from \"./errors.js\";\nexport { MAX_IDEMPOTENCY_KEY, shouldRetry, type FetchLike, type RequestOptions, type RetryOptions } from \"./http.js\";\nexport {\n BASE_OUTCOMES,\n CARD_SIZES,\n HOOK_EVENTS,\n LISTING_CATEGORIES,\n MANIFEST_IGNORED,\n MAX_CONNECT,\n MAX_RELEASE_NOTES,\n MAX_SESSION_BOARDS,\n ManifestError,\n SCOPES,\n checkConnectOrigin,\n defineManifest,\n validateManifest,\n type BaseOutcome,\n type CardSize,\n type ListingCategory,\n type Manifest,\n type ManifestBoard,\n type ManifestBoolChoice,\n type ManifestCapacity,\n type ManifestCommand,\n type ManifestHook,\n type ManifestHookEvent,\n type ManifestHookFilter,\n type ManifestIntChoice,\n type ManifestIssue,\n type ManifestListing,\n type ManifestOutcome,\n type ManifestPage,\n type ManifestQuestion,\n type ManifestSay,\n type ManifestSessionBoard,\n type ManifestSessionCard,\n type ManifestSessionKind,\n type ManifestTool,\n type ManifestVerify,\n type Scope,\n type ValidateOptions,\n} from \"./manifest.js\";\nexport {\n MAX_SKEW_SECONDS,\n SIGNATURE_HEADER,\n TIMESTAMP_HEADER,\n sign,\n signedHeaders,\n verifySignature,\n type SignedHeadersOptions,\n type SignedRequest,\n type VerifyFailure,\n type VerifyOptions,\n} from \"./signing.js\";\nexport * from \"./types.js\";\nexport { SDK_VERSION, USER_AGENT } from \"./version.js\";\n\n/** The parts of a board's full identifier (boardRef). */\nexport interface BoardRefParts {\n /** The namespace: an app's slug, a room id, or the platform's. */\n app?: string;\n room?: string;\n platform?: boolean;\n key: string;\n /** The part: a session's or an install's board. */\n session?: string;\n install?: string;\n /** A period's sequence number. */\n seq?: number;\n}\n\n/**\n * boardRef builds a board's full identifier: {namespace}/{key}[/{part}][@{seq}],\n * e.g. boardRef({ app: \"dice\", key: \"luck\", session: \"31\" }) → \"app:dice/luck/ss_31\".\n */\nexport function boardRef(p: BoardRefParts): string {\n const ns = p.platform ? \"platform\" : p.room ? `room:${p.room}` : `app:${p.app}`;\n const part = p.session ? `/ss_${p.session}` : p.install ? `/in_${p.install}` : \"\";\n return `${ns}/${p.key}${part}${p.seq ? `@${p.seq}` : \"\"}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAGO,IAAM,cAAc;AAGpB,IAAM,aAAa,oBAAoB,WAAW;;;ACyClD,IAAM,mBAAmB;AA2JzB,SAAS,aAAa,MAA6B;AAGxD,MAAI,CAAC,KAAK,SAAU,OAAM,IAAI,UAAU,qDAAqD;AAC7F,QAAM,UAAU,EAAE,QAAQ,KAAK,QAAQ,YAAY,KAAK,WAAW;AACnE,QAAM,IAAI,gBAAgB;AAAA,IACxB,MAAM,KAAK,SAAS,QAAQ,QAAQ,EAAE,IAAI;AAAA,IAC1C,OAAO,KAAK;AAAA,IACZ,OAAO,KAAK;AAAA,IACZ,WAAW;AAAA,IACX,SAAS,MAAM;AACb,UAAI,CAAC,KAAK,OAAQ,OAAM,IAAI,UAAU,+EAA0E;AAChH,YAAM,IAA4B,EAAE,eAAe,UAAU,KAAK,MAAM,IAAI,GAAG,KAAK,QAAQ;AAC5F,UAAI,QAAQ,OAAQ,GAAE,eAAe,IAAI,OAAO,QAAQ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