@onlyworlds/sdk 4.136.0 → 4.138.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,26 @@ earlier history lives in git log only.
5
5
 
6
6
  ## [Unreleased]
7
7
 
8
+ ## [4.138.0] - 2026-11-10
9
+
10
+ ### Added
11
+
12
+ - An AI door token: an `ow_a_` token that opens only `aiUses()` and the AI uses it names, as the person and on their token rating, until midnight UTC at the latest. Another use answers 403 `use_not_granted`, every other route 401 `wrong_audience`.
13
+ - `completeSignIn({ ..., aiUses, aiLifetimeMinutes })` asks the sign-in's code exchange for one beside the account token; the result's new `aiToken` (`OwAiToken`: `token`, `tokenId`, `tokenType`, `audience`, `aiUses`, `expiresAt`) carries it, and is null when none was asked or the server answered none. The exchange spends its code whatever it answers, so a list the SDK can see is wrong (not 1 to 8 names, a name that is not one path segment, a lifetime outside 1 to 1440 minutes or without `aiUses`) is refused before anything is sent and before the pending sign-in is touched. A name the server does not run is its 422, and the code is then spent. Both options are optional, and every field the result had stays as it was.
14
+ - `mintAiToken(uses, { lifetimeMinutes, name })`: `POST /account/tokens` with `ai_uses`, trading an account token down to an AI door token (`OwMintedAiToken`, the token's row with the token once). It belongs to the token that minted it: revoking that one revokes it too. The uses are required, so a call without them never reaches the route that would mint a full account token.
15
+ - `OwApiError.isUseNotGranted` (403 `use_not_granted`) and `isWrongAudience` (401 `wrong_audience`).
16
+ - `OwAccountToken.ai_uses`, on an `ai` token's row.
17
+
18
+ ## [4.137.0] - 2026-11-09
19
+
20
+ ### Added
21
+
22
+ - `aiUses()`: `GET /account/ai`, the AI uses onlyworlds.com runs, each a named call a tool makes: its owner, provider, model and effort, the hash of its system prompt, what its body may hold, its answer cap, its price, its daily ceiling, this account's calls left today, and whether it is on (`OwAiUse`). Reading it spends nothing. Needs an account token.
23
+ - `ai(use, body, { idempotencyKey, signal })`: `POST /account/ai/{use}`, one call of a listed use, metered on the account's token rating and then its own saved AI key, as `ask()` and `sort()` are. The body is the use's own, in its wire spelling, sent as given (`{world_id, question, context}` for `ask`, `{world_id, notes, slice}` for `sort`); typed for those two (`OwAiAskBody`, `OwAiSortBody`, answered as `OwAiAskAnswer` and `OwAiSortAnswer`) and open for any other use. The answer adds `use_remaining` (null when the use has no daily ceiling) and `wasReplay`, read from `Idempotent-Replay`. The use's name is checked as one path segment and the key as 1 to 200 characters before anything is sent; the client's name goes as `X-OW-Client`.
24
+ - With an `idempotencyKey`, a retry is safe: the same key and body answer the first answer again and bill nothing. A key whose first call is still running answers 409 `idempotency_in_flight`; retry with the same key and body a few times at most, and never mint a new key to get past it, since a key whose answer could not be stored stays in flight for a day although the call ran and was billed. The client never retries on its own.
25
+ - `OwApiError.isUseCeiling` (429 `use_ceiling`: the use's calls for the day are made) and `isUseInFlight` (429 `use_in_flight`: another call to this use is running; wait `retryAfter`). A 503 `ask_unavailable` with `param` `use` is still `isAskUnavailable`.
26
+ - `ask()` and `sort()` keep calling their own routes, unchanged.
27
+
8
28
  ## [4.136.0] - 2026-11-09
9
29
 
10
30
  ### Added
package/dist/index.d.ts CHANGED
@@ -3128,6 +3128,78 @@ interface OwAllowance {
3128
3128
  } | null;
3129
3129
  [k: string]: unknown;
3130
3130
  }
3131
+ /**
3132
+ * One AI use, as GET /account/ai lists it: a named call a tool may make at POST /account/ai/{slug}.
3133
+ * A tool calls a use by its name and sends the use's own body; it never sends a prompt.
3134
+ */
3135
+ interface OwAiUse {
3136
+ /** The use's name in its route: POST /account/ai/{slug}. */
3137
+ slug: string;
3138
+ /** The tool that answers for its prompt and caps. */
3139
+ owner: string;
3140
+ provider: string;
3141
+ /** The model a call on the platform's key runs. */
3142
+ model: string;
3143
+ effort: string;
3144
+ /** The sha256 of the use's system prompt, hex: two calls with the same hash ran the same prompt. */
3145
+ prompt_sha256: string;
3146
+ /** The body names a world this account owns or is a member of. */
3147
+ needs_world: boolean;
3148
+ /** What the body may hold, by name. */
3149
+ input_caps: Record<string, number>;
3150
+ /** The most tokens one answer may take; a call needs at least this much rating left (or a saved own key). */
3151
+ output_cap: number;
3152
+ /** The answer is checked JSON, not text. */
3153
+ structured: boolean;
3154
+ /** A fixed price per call in rating tokens, or null: the call's actual tokens are spent. */
3155
+ price_tokens: number | null;
3156
+ /** Calls per account per UTC day, or null. Past it, 429 `use_ceiling` until midnight UTC; a use with a
3157
+ * ceiling runs one call at a time, and a second call while one runs is 429 `use_in_flight`. */
3158
+ ceiling: number | null;
3159
+ /** This account's calls left today, or null when the use has no ceiling. */
3160
+ calls_left: number | null;
3161
+ /** False while the use is switched off or has spent its own budget for today (its calls answer 503
3162
+ * `ask_unavailable` with param `use`). */
3163
+ on: boolean;
3164
+ [k: string]: unknown;
3165
+ }
3166
+ /** What every answer of an AI use adds to the use's own answer. */
3167
+ interface OwAiMeter {
3168
+ /** Calls to this use this account has left today; null when the use has no daily ceiling (the token
3169
+ * rating is then the only limit). */
3170
+ use_remaining: number | null;
3171
+ /** Read from the `Idempotent-Replay` header: true when this answer is the stored first answer for the
3172
+ * call's idempotency key, billed nothing this time. Set by the client, never sent by the server. */
3173
+ wasReplay: boolean;
3174
+ }
3175
+ /** POST /account/ai/ask: the ask use's answer, the same as ask()'s, with the use's meter. */
3176
+ interface OwAiAskAnswer extends OwAskAnswer {
3177
+ /** Calls to this use this account has left today; null when the use has no daily ceiling. */
3178
+ use_remaining: number | null;
3179
+ /** True when this answer is the stored first answer for the call's idempotency key (billed nothing). */
3180
+ wasReplay: boolean;
3181
+ }
3182
+ /** POST /account/ai/sort: the sort use's answer, the same as sort()'s, with the use's meter. */
3183
+ interface OwAiSortAnswer extends OwSortAnswer {
3184
+ /** Calls to this use this account has left today; null when the use has no daily ceiling. */
3185
+ use_remaining: number | null;
3186
+ /** True when this answer is the stored first answer for the call's idempotency key (billed nothing). */
3187
+ wasReplay: boolean;
3188
+ }
3189
+ /** The `ask` use's body (POST /account/ai/ask), in its own wire spelling: the same fields as ask(). */
3190
+ interface OwAiAskBody {
3191
+ world_id: string;
3192
+ /** 1 to 500 characters. */
3193
+ question: string;
3194
+ /** 1 to 8 elements as text, each up to 2,000 characters, 12,000 in all (buildAskContext makes it). */
3195
+ context: string[];
3196
+ }
3197
+ /** The `sort` use's body (POST /account/ai/sort), in its own wire spelling: the same fields as sort(). */
3198
+ interface OwAiSortBody {
3199
+ world_id: string;
3200
+ notes: OwSortNote[];
3201
+ slice?: OwSortRef[];
3202
+ }
3131
3203
  /** POST /join/preview: what a join code holds, read without using it. */
3132
3204
  interface OwJoinPreview {
3133
3205
  /** `person`: an invite link, accepted with acceptJoin. `agent`: redeemed by an AI agent at POST /join. `player`: a friend with no account redeems it with redeemJoin for a read key. */
@@ -3623,13 +3695,27 @@ interface OwAccountToken {
3623
3695
  expires_at: string | null;
3624
3696
  /** How many live world keys this token minted. */
3625
3697
  keys_minted: number;
3626
- /** Who the token is for: empty for a token made by hand or a sign-in tool's; `mcp` for a hosted client's grant on the MCP server. */
3698
+ /** Who the token is for: empty for a token made by hand or a sign-in tool's; `mcp` for a hosted client's grant on the MCP server; `ai` for an AI door token (mintAiToken, or the sign-in's `aiUses`). */
3627
3699
  audience: string;
3700
+ /** On an `ai` token only: the AI uses it opens (`ai(use, …)`). */
3701
+ ai_uses?: string[];
3628
3702
  /** On an `mcp` token only: the client's name, as it registered itself, or its id when it is no longer registered. */
3629
3703
  client?: string;
3630
3704
  /** On an `mcp` token only: the host the client returns the person to. */
3631
3705
  return_host?: string;
3632
3706
  }
3707
+ /**
3708
+ * An AI door token as minted by mintAiToken (POST /account/tokens with `ai_uses`): its row, as the
3709
+ * account's token list shows it, plus the token itself once in `token` (never shown again).
3710
+ */
3711
+ interface OwMintedAiToken extends OwAccountToken {
3712
+ audience: 'ai';
3713
+ ai_uses: string[];
3714
+ /** When it stops working: midnight UTC at the latest. */
3715
+ expires_at: string;
3716
+ /** The `ow_a_` AI door token, shown only here. */
3717
+ token: string;
3718
+ }
3633
3719
  interface OwSeat {
3634
3720
  /** The seat's membership id: removeSeat takes it, and GET /members names the seat by it. */
3635
3721
  id: string;
@@ -4139,6 +4225,26 @@ declare class OwApiError extends Error {
4139
4225
  get isOwnKeyRefused(): boolean;
4140
4226
  /** ask: the proxy is switched off, or paused for the day by the server-wide cap (503 `ask_unavailable`). Not counted. */
4141
4227
  get isAskUnavailable(): boolean;
4228
+ /**
4229
+ * ai: this use's calls for the day are made (429 `use_ceiling`, param `use`): the use's own daily
4230
+ * ceiling per account, not the token rating (isQuotaExceeded). Retry-After runs to midnight UTC.
4231
+ */
4232
+ get isUseCeiling(): boolean;
4233
+ /**
4234
+ * ai: another call to this use is running for this account (429 `use_in_flight`, param `use`): a use
4235
+ * with a ceiling runs one call at a time. Wait `retryAfter` seconds (a short wait) and send again.
4236
+ */
4237
+ get isUseInFlight(): boolean;
4238
+ /**
4239
+ * ai: an AI door token called a use it was not minted for (403 `use_not_granted`, param `use`).
4240
+ * Nothing was counted. Mint one that names this use (mintAiToken), or call with an account token.
4241
+ */
4242
+ get isUseNotGranted(): boolean;
4243
+ /**
4244
+ * The account token works on some routes only (401 `wrong_audience`): an AI door token on any route
4245
+ * but `aiUses()`, its uses and its own revoke, or a hosted MCP client's token anywhere but /mcp.
4246
+ */
4247
+ get isWrongAudience(): boolean;
4142
4248
  /** ask: the model gave no answer (502 `ask_failed`). Not counted; try again in a moment. */
4143
4249
  get isAskFailed(): boolean;
4144
4250
  /**
@@ -4351,6 +4457,34 @@ interface OwSignInComplete {
4351
4457
  * the window's history is left alone.
4352
4458
  */
4353
4459
  url?: string;
4460
+ /**
4461
+ * Also ask the exchange for an AI door token for these AI uses (their slugs, as `aiUses()` lists
4462
+ * them): 1 to 8, each one path segment. It comes back as `aiToken`. The exchange spends the code
4463
+ * whatever it answers, so a list the SDK can see is wrong is refused before anything is sent; a
4464
+ * name the server does not run is its 422, and then the code is spent.
4465
+ */
4466
+ aiUses?: string[];
4467
+ /** With `aiUses` only: the AI door token ends this many minutes after the exchange (1 to 1440), or at midnight UTC if that comes first. */
4468
+ aiLifetimeMinutes?: number;
4469
+ }
4470
+ /**
4471
+ * An AI door token: an `ow_a_` token that opens only `aiUses()` and the AI uses it names (`ai()`),
4472
+ * as the person and on their token rating; another use answers 403 `use_not_granted`
4473
+ * (`err.isUseNotGranted`), every other route 401 `wrong_audience` (`err.isWrongAudience`). It ends at
4474
+ * `expiresAt` (midnight UTC at the latest), then answers 401 `key_revoked`. A client built on it may
4475
+ * revoke it with `revokeAccountToken(tokenId)`; revoking it touches no other token, and revoking the
4476
+ * account token beside it leaves it live.
4477
+ */
4478
+ interface OwAiToken {
4479
+ /** The `ow_a_` AI door token, shown only here. */
4480
+ token: string;
4481
+ tokenId: string;
4482
+ tokenType: 'bearer';
4483
+ audience: 'ai';
4484
+ /** The uses it opens, as the server took them (each once, in the order sent). */
4485
+ aiUses: string[];
4486
+ /** When it stops working (ISO 8601). */
4487
+ expiresAt: string;
4354
4488
  }
4355
4489
  /** What `completeSignIn` returns: the account token, shown only here, and what the tool parked. */
4356
4490
  interface OwSignInResult {
@@ -4373,6 +4507,11 @@ interface OwSignInResult {
4373
4507
  };
4374
4508
  /** The `resume` given to `beginSignIn`, or null. */
4375
4509
  resume: unknown;
4510
+ /**
4511
+ * The AI door token, when `aiUses` asked for one; null when none was asked, and from a server that
4512
+ * answered none (the account token above is good either way).
4513
+ */
4514
+ aiToken: OwAiToken | null;
4376
4515
  }
4377
4516
  /** Base64url without padding (RFC 4648 §5), as PKCE wants it. */
4378
4517
  declare function base64url(bytes: Uint8Array): string;
@@ -5232,6 +5371,22 @@ declare class OwV2Client {
5232
5371
  signal?: AbortSignal;
5233
5372
  keepalive?: boolean;
5234
5373
  }): Promise<void>;
5374
+ /**
5375
+ * POST /account/tokens with `ai_uses` -- trade this client's account token down to an AI door
5376
+ * token: an `ow_a_` token that opens only `aiUses()` and the uses named here (1 to 8, by slug, as
5377
+ * `aiUses()` lists them), as this account and on its token rating. Another use answers 403
5378
+ * `use_not_granted` (`err.isUseNotGranted`), every other route 401 `wrong_audience`
5379
+ * (`err.isWrongAudience`). It ends at midnight UTC, or `lifetimeMinutes` (1 to 1440) after the mint
5380
+ * if that comes first, then answers 401 `key_revoked`. It belongs to the token that minted it:
5381
+ * revoking this client's token revokes it too, while revoking it leaves this one live. A client
5382
+ * built on it revokes it with `revokeAccountToken(minted.id)`. The answer is the token's row with
5383
+ * the token itself, shown only here. A name the server does not run is a 422 (`err.code` `invalid_request`, `err.param` `ai_uses`).
5384
+ * Account token only; the AI door token itself mints nothing (401 `wrong_audience`).
5385
+ */
5386
+ mintAiToken(uses: string[], opts?: {
5387
+ lifetimeMinutes?: number;
5388
+ name?: string;
5389
+ }): Promise<OwMintedAiToken>;
5235
5390
  /**
5236
5391
  * Start Sign in with OnlyWorlds from a tool's page: mint `state` and a PKCE verifier, keep them
5237
5392
  * under `clientId` in `storage` (sessionStorage by default; in Node pass one), and send the
@@ -5302,6 +5457,52 @@ declare class OwV2Client {
5302
5457
  * client's `ow_a_` token.
5303
5458
  */
5304
5459
  allowance(): Promise<OwAllowance>;
5460
+ /**
5461
+ * GET /account/ai -- the AI uses onlyworlds.com runs, each a named call a tool makes with ai():
5462
+ * its owner, provider, model and effort, the hash of its system prompt, what its body may hold, its
5463
+ * answer cap, its price, its daily ceiling, this account's calls left today, and whether it is on.
5464
+ * Reading it spends nothing. Needs the client's `ow_a_` token.
5465
+ */
5466
+ aiUses(opts?: {
5467
+ signal?: AbortSignal;
5468
+ }): Promise<OwAiUse[]>;
5469
+ /**
5470
+ * POST /account/ai/{use} -- one call of an AI use (aiUses lists them), metered on the account's
5471
+ * daily token rating, then its own saved AI key, as ask and sort are. `body` is the use's own body in
5472
+ * its wire spelling, sent as given: `{world_id, question, context}` for `ask`, `{world_id, notes,
5473
+ * slice}` for `sort`; another use's body is the one its listing describes. The answer is the use's
5474
+ * own, its meter whole (`paid_by`, `model`, `usage`, `remaining`, `tokens_remaining`, `token_rating`),
5475
+ * with `use_remaining` (null when the use has no daily ceiling) and `wasReplay`. The use's name is
5476
+ * checked as one path segment before sending. Needs the client's `ow_a_` token.
5477
+ *
5478
+ * With an `idempotencyKey`, a retry is safe: the same key and body answer the first answer again
5479
+ * (`wasReplay` true) and bill nothing; the same key with another body is 409 `idempotency_error`, and
5480
+ * a key whose first call is still running is 409 `idempotency_in_flight` (retry after `retryAfter`).
5481
+ * Retry with the same key and body, a few times at most, and never mint a new key to get past an
5482
+ * in-flight answer: when the server cannot store an answer, the key is held for a day and keeps
5483
+ * answering `idempotency_in_flight` although the call ran and was billed. The client never retries
5484
+ * on its own.
5485
+ *
5486
+ * Refusals, none of them counted: 429 `use_ceiling` (`err.isUseCeiling`: the use's calls for the day
5487
+ * are made), 429 `use_in_flight` (`err.isUseInFlight`: another call to this use is running; wait
5488
+ * `retryAfter`), 429 `quota_exceeded` (`err.isQuotaExceeded`: the token rating is spent and no own key
5489
+ * is saved), 422 `own_key_refused` (`err.isOwnKeyRefused`), 503 `ask_unavailable`
5490
+ * (`err.isAskUnavailable`; with `param` `use`, this use is switched off or spent its own budget
5491
+ * today), 502 `ask_failed` (`err.isAskFailed`), 404 `not_found` (a use that is not listed, `param`
5492
+ * `use`, or a world the account is not in), 422 for a body past the use's limits (`param` names it).
5493
+ */
5494
+ ai(use: 'ask', body: OwAiAskBody, opts?: {
5495
+ idempotencyKey?: string;
5496
+ signal?: AbortSignal;
5497
+ }): Promise<OwAiAskAnswer>;
5498
+ ai(use: 'sort', body: OwAiSortBody, opts?: {
5499
+ idempotencyKey?: string;
5500
+ signal?: AbortSignal;
5501
+ }): Promise<OwAiSortAnswer>;
5502
+ ai(use: string, body: Record<string, unknown>, opts?: {
5503
+ idempotencyKey?: string;
5504
+ signal?: AbortSignal;
5505
+ }): Promise<Record<string, unknown> & OwAiMeter>;
5305
5506
  /**
5306
5507
  * Raw authenticated request against this client's baseUrl. Public since 4.0
5307
5508
  * so auxiliary resources can ride the same transport — it structurally
@@ -5319,7 +5520,7 @@ declare class OwV2Client {
5319
5520
  /** A `change_seq` to send as `If-Match`; a whole number, else TypeError before sending. */
5320
5521
  /** A write keel's document lists X-OW-Agent on (the element writes, the links route, bulk, adopt, the file ticket): where an agent client sends it. Hide, unhide, setMyCharacter and mintWorldKey are not, and keel reads no agent there. */
5321
5522
  write?: boolean;
5322
- /** One of the writes keel reads X-OW-Client on (create, put, patch, delete, links, bulk, adopt, propose, accept): where the client's name goes. */
5523
+ /** One of the writes keel reads X-OW-Client on (create, put, patch, delete, links, bulk, adopt, propose, accept, review, and an AI use's call): where the client's name goes. */
5323
5524
  elementWrite?: boolean;
5324
5525
  /**
5325
5526
  * A write keel may answer 202 with `{proposal}` (put, patch, links): a 202 then
@@ -7343,4 +7544,4 @@ declare class TokenResource {
7343
7544
  getEncryptionInfo(): Promise<EncryptionInfo>;
7344
7545
  }
7345
7546
 
7346
- export { AGENT_DOORS, ASK_LIMITS, type AccessKeyResponse, CALENDAR_FIELD, CALENDAR_SUPERTYPE, CHARTER_PAIRS, type CalendarConfig, type CalendarEra, type CalendarIntercalary, type CalendarMonths, type CalendarWeek, DATE_FIELD, ELEMENT_FAMILIES, ELEMENT_GROUPS, ELEMENT_ICONS, ELEMENT_LABELS, ELEMENT_SECTIONS, ELEMENT_TYPES, type ElementFamily, type ElementGroup, type ElementType, type EncryptionInfo, type EraDomain, FAMILY_COLORS, FAMILY_ORDER, FIELD_ACRONYMS, FIELD_SCHEMA, FILE_EXTENSIONS, type FieldInfo, type FieldType, GROUP_COLORS, GROUP_ORDER, GameTier, type ListParams, MESSAGE_PAIR, NOTE_PAIR, ONLYWORLDS_VERSION, type OwAccountToken, type OwAccountWorld, type OwAddress, OwAddressError, type OwAddressForm, type OwAddressReading, type OwAddressReason, type OwAddressingOptions, type OwAgentJoined, type OwAllowance, OwApiError, type OwAskAnswer, type OwAskContext, type OwAskContextOptions, type OwAskLeftOut, type OwAuthErrorCode, type OwBulkItem, type OwBulkItemResult, type OwBulkResponse, type OwCalendarElement, type OwChange, type OwChangeDelete, type OwChangeUpsert, type OwChangesPage, type OwCharterWorld, type OwClientConfig, type OwCreateAccountWorldInput, type OwCreatedAccountWorld, type OwCreatedWorldLink, type OwDeleteReason, type OwDoor, type OwDragField, type OwDraught, type OwDraughtCompact, type OwDraughtComponent, type OwDraughtItem, type OwDraughtLens, type OwDraughtPolicy, type OwEdited, type OwElement, type OwElementBase, type OwElementMark, type OwErrorBody, type OwFileAddedBy, type OwFileDownload, type OwFileKind, type OwFileRow, type OwFileTicket, type OwFrontDoor, type OwGraphCutReason, type OwGraphEdge, type OwGraphMark, type OwGraphNode, type OwGraphOptions, type OwHiddenRow, type OwJoinPreview, type OwJoined, type OwJoinedMembership, type OwKeyKind, type OwLanding, type OwLandingCluster, type OwLandingGap, type OwLandingGapKind, type OwLandingMember, type OwLandingMode, type OwLandingOptions, type OwLensCutReason, type OwLensMail, type OwLensOptions, type OwLensReader, type OwLensReading, type OwLensWorld, type OwLinkEdit, type OwLookupElement, type OwLookupHit, type OwLookupLink, type OwLookupOptions, type OwLookupReason, type OwMapSpace, type OwMapSpaceMap, type OwMapSpaceOutReason, type OwMapSpaceOutline, type OwMapSpacePin, type OwMapSpacePoint, type OwMe, type OwMediaTicket, type OwMember, type OwMemberLenses, type OwMemberRole, type OwMessageMember, type OwMintedKey, type OwMySeat, type OwNamesMap, OwNetworkError, type OwOpener, type OwOpenerKind, type OwOpenerState, type OwOpenerSurface, type OwOpenersOptions, type OwPage, type OwPaidBy, type OwPhotoOptions, type OwPhotoPlan, type OwPlayerJoined, OwPreconditionFailedError, type OwPreparedPhoto, type OwProposal, type OwProposalAccepted, type OwProposalConflict, type OwProposalList, type OwProposalQuery, type OwProposalState, type OwProposeInput, type OwProposed, OwProposedError, type OwProposedMark, type OwProposedNewElement, type OwReadWorldFile, type OwReadWorldFileOptions, type OwReadingAids, type OwReadingAidsCharter, type OwReadingAidsDomain, type OwReadingAidsGuide, type OwReadingAidsHub, type OwRecord, type OwRecordMark, type OwRecordStory, type OwRemovalTicket, type OwRemovedImage, type OwRenderOptions, type OwResyncReason, type OwReviewInput, type OwReviewed, type OwSeat, type OwSeatCreated, type OwSender, type OwSenderStatus, type OwServedReadingAids, type OwSignInBegin, type OwSignInBegun, type OwSignInComplete, OwSignInError, type OwSignInReason, type OwSignInResult, type OwSignInStorage, type OwSignedIn, type OwSortAddToRow, type OwSortAnswer, type OwSortAskRow, type OwSortLinkRow, type OwSortMakeRow, type OwSortNote, type OwSortRef, type OwSortRow, OwStaleProposalError, type OwStrand, type OwStrandSlot, type OwStrandWorld, type OwTool, type OwToolNeeds, type OwToolOpen, type OwTrailGround, type OwTrailHanger, type OwTrailInput, type OwTrailLayout, type OwTrailPin, type OwTrailPlace, type OwTrailSettings, type OwTrailSpiral, type OwTrailTier, type OwUploadedFile, type OwUploadedImage, OwV2Client, type OwWordPair, type OwWorldFileEntry, OwWorldFileError, type OwWorldFileReason, type OwWorldFileRow, type OwWorldFiles, type OwWorldGraph, type OwWorldIndex, type OwWorldKeyMember, type OwWorldKeyRow, type OwWorldLens, type OwWorldLensReading, type OwWorldLenses, type OwWorldLink, type OwWorldMeta, type OwWorldOrigin, type OwWorldProducer, type OwWorldProposalList, type OwWorldProposalQuery, type OwWorldProposalRow, type OwWorldPublicPage, type OwWorldSource, type OwWriteDoor, type OwWriteWorldFileOptions, type OwWriteWorldFileReport, PHOTO_MAX_BYTES, PHOTO_TYPES, PROPOSED_MARK, PUBLIC_FIELDS, type ParseError, type ParseOptions, type ParseResult, RECORD_FIELD, REVIEW_PROPOSED_LABEL, ROOM_PAIRS, type RevokeAllSessionsResponse, type RevokeSessionResponse, SPATIAL_TYPES, STRAND_FIELD, type SectionInfo, type StepBreakdown, TOOLS, TRAIL_TIERS, type TokenConsumeParams, type TokenConsumeResponse, TokenResource, type TokenStatus, type TokenTransport, WORLD_FILE_MAX_BYTES, WORLD_FILE_MAX_ENTRIES, WORLD_FILE_MEDIA_TYPE, type WorldCalendar, absYearForEraYear, absoluteYear, approxYearLength, base64url, breakdownStep, buildAskContext, buildWorldIndex, charterOf, dateOf, degreeOf, detectKeyKind, displayYear, domainsOf, doorWhere, doorsOf, dragField, draughtText, editedBy, elementAddress, elementColor, eraForStep, errorFromResponse, familyOf, fieldLabel, fileKindOf, floorDiv, floorMod, formatDuration, formatMidLabel, formatStep, formatYearLabel, getElementIcon, getElementLabel, groupOf, handsOnAsProposed, hasUnseenRecipients, intercalaryInYear, isAddressedTo, isAgentDoor, isCharterElement, isDemoKey, isKnownOf, isLeapYear, isLens, isMessage, isNote, isParseError, isRoomElement, isSentBy, isTemplate, isToEveryone, kindCanWrite, landingOf, lensesInUse, lookupWorld, mapSpace, monthStartSteps, nfc, noteOf, openersFor, outDegreeOf, parseDate, parseErrorEnvelope, parseOwLink, pinExpectation, pkceChallenge, planPhoto, preparePhoto, proposedMarkOf, readCalendarConfig, readCalendarValue, readMarkOf, readWorldFile, readingAidOf, recipientsOf, recordMarkOf, recordsOf, renderElement, resolveCalendar, resolveCalendarLens, resolveEraDomains, resolveLens, roundHalfEven, senderStatus, simpleCaseFold, strandOf, threadOf, trailByPlace, typeWord, unreadFor, validateCalendarConfig, weekdayForStep, worldCalendars, worldGraph, writeWorldFile, yearLength, yearStartStep };
7547
+ export { AGENT_DOORS, ASK_LIMITS, type AccessKeyResponse, CALENDAR_FIELD, CALENDAR_SUPERTYPE, CHARTER_PAIRS, type CalendarConfig, type CalendarEra, type CalendarIntercalary, type CalendarMonths, type CalendarWeek, DATE_FIELD, ELEMENT_FAMILIES, ELEMENT_GROUPS, ELEMENT_ICONS, ELEMENT_LABELS, ELEMENT_SECTIONS, ELEMENT_TYPES, type ElementFamily, type ElementGroup, type ElementType, type EncryptionInfo, type EraDomain, FAMILY_COLORS, FAMILY_ORDER, FIELD_ACRONYMS, FIELD_SCHEMA, FILE_EXTENSIONS, type FieldInfo, type FieldType, GROUP_COLORS, GROUP_ORDER, GameTier, type ListParams, MESSAGE_PAIR, NOTE_PAIR, ONLYWORLDS_VERSION, type OwAccountToken, type OwAccountWorld, type OwAddress, OwAddressError, type OwAddressForm, type OwAddressReading, type OwAddressReason, type OwAddressingOptions, type OwAgentJoined, type OwAiAskAnswer, type OwAiAskBody, type OwAiMeter, type OwAiSortAnswer, type OwAiSortBody, type OwAiToken, type OwAiUse, type OwAllowance, OwApiError, type OwAskAnswer, type OwAskContext, type OwAskContextOptions, type OwAskLeftOut, type OwAuthErrorCode, type OwBulkItem, type OwBulkItemResult, type OwBulkResponse, type OwCalendarElement, type OwChange, type OwChangeDelete, type OwChangeUpsert, type OwChangesPage, type OwCharterWorld, type OwClientConfig, type OwCreateAccountWorldInput, type OwCreatedAccountWorld, type OwCreatedWorldLink, type OwDeleteReason, type OwDoor, type OwDragField, type OwDraught, type OwDraughtCompact, type OwDraughtComponent, type OwDraughtItem, type OwDraughtLens, type OwDraughtPolicy, type OwEdited, type OwElement, type OwElementBase, type OwElementMark, type OwErrorBody, type OwFileAddedBy, type OwFileDownload, type OwFileKind, type OwFileRow, type OwFileTicket, type OwFrontDoor, type OwGraphCutReason, type OwGraphEdge, type OwGraphMark, type OwGraphNode, type OwGraphOptions, type OwHiddenRow, type OwJoinPreview, type OwJoined, type OwJoinedMembership, type OwKeyKind, type OwLanding, type OwLandingCluster, type OwLandingGap, type OwLandingGapKind, type OwLandingMember, type OwLandingMode, type OwLandingOptions, type OwLensCutReason, type OwLensMail, type OwLensOptions, type OwLensReader, type OwLensReading, type OwLensWorld, type OwLinkEdit, type OwLookupElement, type OwLookupHit, type OwLookupLink, type OwLookupOptions, type OwLookupReason, type OwMapSpace, type OwMapSpaceMap, type OwMapSpaceOutReason, type OwMapSpaceOutline, type OwMapSpacePin, type OwMapSpacePoint, type OwMe, type OwMediaTicket, type OwMember, type OwMemberLenses, type OwMemberRole, type OwMessageMember, type OwMintedAiToken, type OwMintedKey, type OwMySeat, type OwNamesMap, OwNetworkError, type OwOpener, type OwOpenerKind, type OwOpenerState, type OwOpenerSurface, type OwOpenersOptions, type OwPage, type OwPaidBy, type OwPhotoOptions, type OwPhotoPlan, type OwPlayerJoined, OwPreconditionFailedError, type OwPreparedPhoto, type OwProposal, type OwProposalAccepted, type OwProposalConflict, type OwProposalList, type OwProposalQuery, type OwProposalState, type OwProposeInput, type OwProposed, OwProposedError, type OwProposedMark, type OwProposedNewElement, type OwReadWorldFile, type OwReadWorldFileOptions, type OwReadingAids, type OwReadingAidsCharter, type OwReadingAidsDomain, type OwReadingAidsGuide, type OwReadingAidsHub, type OwRecord, type OwRecordMark, type OwRecordStory, type OwRemovalTicket, type OwRemovedImage, type OwRenderOptions, type OwResyncReason, type OwReviewInput, type OwReviewed, type OwSeat, type OwSeatCreated, type OwSender, type OwSenderStatus, type OwServedReadingAids, type OwSignInBegin, type OwSignInBegun, type OwSignInComplete, OwSignInError, type OwSignInReason, type OwSignInResult, type OwSignInStorage, type OwSignedIn, type OwSortAddToRow, type OwSortAnswer, type OwSortAskRow, type OwSortLinkRow, type OwSortMakeRow, type OwSortNote, type OwSortRef, type OwSortRow, OwStaleProposalError, type OwStrand, type OwStrandSlot, type OwStrandWorld, type OwTool, type OwToolNeeds, type OwToolOpen, type OwTrailGround, type OwTrailHanger, type OwTrailInput, type OwTrailLayout, type OwTrailPin, type OwTrailPlace, type OwTrailSettings, type OwTrailSpiral, type OwTrailTier, type OwUploadedFile, type OwUploadedImage, OwV2Client, type OwWordPair, type OwWorldFileEntry, OwWorldFileError, type OwWorldFileReason, type OwWorldFileRow, type OwWorldFiles, type OwWorldGraph, type OwWorldIndex, type OwWorldKeyMember, type OwWorldKeyRow, type OwWorldLens, type OwWorldLensReading, type OwWorldLenses, type OwWorldLink, type OwWorldMeta, type OwWorldOrigin, type OwWorldProducer, type OwWorldProposalList, type OwWorldProposalQuery, type OwWorldProposalRow, type OwWorldPublicPage, type OwWorldSource, type OwWriteDoor, type OwWriteWorldFileOptions, type OwWriteWorldFileReport, PHOTO_MAX_BYTES, PHOTO_TYPES, PROPOSED_MARK, PUBLIC_FIELDS, type ParseError, type ParseOptions, type ParseResult, RECORD_FIELD, REVIEW_PROPOSED_LABEL, ROOM_PAIRS, type RevokeAllSessionsResponse, type RevokeSessionResponse, SPATIAL_TYPES, STRAND_FIELD, type SectionInfo, type StepBreakdown, TOOLS, TRAIL_TIERS, type TokenConsumeParams, type TokenConsumeResponse, TokenResource, type TokenStatus, type TokenTransport, WORLD_FILE_MAX_BYTES, WORLD_FILE_MAX_ENTRIES, WORLD_FILE_MEDIA_TYPE, type WorldCalendar, absYearForEraYear, absoluteYear, approxYearLength, base64url, breakdownStep, buildAskContext, buildWorldIndex, charterOf, dateOf, degreeOf, detectKeyKind, displayYear, domainsOf, doorWhere, doorsOf, dragField, draughtText, editedBy, elementAddress, elementColor, eraForStep, errorFromResponse, familyOf, fieldLabel, fileKindOf, floorDiv, floorMod, formatDuration, formatMidLabel, formatStep, formatYearLabel, getElementIcon, getElementLabel, groupOf, handsOnAsProposed, hasUnseenRecipients, intercalaryInYear, isAddressedTo, isAgentDoor, isCharterElement, isDemoKey, isKnownOf, isLeapYear, isLens, isMessage, isNote, isParseError, isRoomElement, isSentBy, isTemplate, isToEveryone, kindCanWrite, landingOf, lensesInUse, lookupWorld, mapSpace, monthStartSteps, nfc, noteOf, openersFor, outDegreeOf, parseDate, parseErrorEnvelope, parseOwLink, pinExpectation, pkceChallenge, planPhoto, preparePhoto, proposedMarkOf, readCalendarConfig, readCalendarValue, readMarkOf, readWorldFile, readingAidOf, recipientsOf, recordMarkOf, recordsOf, renderElement, resolveCalendar, resolveCalendarLens, resolveEraDomains, resolveLens, roundHalfEven, senderStatus, simpleCaseFold, strandOf, threadOf, trailByPlace, typeWord, unreadFor, validateCalendarConfig, weekdayForStep, worldCalendars, worldGraph, writeWorldFile, yearLength, yearStartStep };
package/dist/index.js CHANGED
@@ -335,6 +335,34 @@ var OwApiError = class extends Error {
335
335
  get isAskUnavailable() {
336
336
  return this.status === 503 && this.code === "ask_unavailable";
337
337
  }
338
+ /**
339
+ * ai: this use's calls for the day are made (429 `use_ceiling`, param `use`): the use's own daily
340
+ * ceiling per account, not the token rating (isQuotaExceeded). Retry-After runs to midnight UTC.
341
+ */
342
+ get isUseCeiling() {
343
+ return this.status === 429 && this.code === "use_ceiling";
344
+ }
345
+ /**
346
+ * ai: another call to this use is running for this account (429 `use_in_flight`, param `use`): a use
347
+ * with a ceiling runs one call at a time. Wait `retryAfter` seconds (a short wait) and send again.
348
+ */
349
+ get isUseInFlight() {
350
+ return this.status === 429 && this.code === "use_in_flight";
351
+ }
352
+ /**
353
+ * ai: an AI door token called a use it was not minted for (403 `use_not_granted`, param `use`).
354
+ * Nothing was counted. Mint one that names this use (mintAiToken), or call with an account token.
355
+ */
356
+ get isUseNotGranted() {
357
+ return this.status === 403 && this.code === "use_not_granted";
358
+ }
359
+ /**
360
+ * The account token works on some routes only (401 `wrong_audience`): an AI door token on any route
361
+ * but `aiUses()`, its uses and its own revoke, or a hosted MCP client's token anywhere but /mcp.
362
+ */
363
+ get isWrongAudience() {
364
+ return this.status === 401 && this.code === "wrong_audience";
365
+ }
338
366
  /** ask: the model gave no answer (502 `ask_failed`). Not counted; try again in a moment. */
339
367
  get isAskFailed() {
340
368
  return this.status === 502 && this.code === "ask_failed";
@@ -504,6 +532,36 @@ function pinExpectation(kind) {
504
532
  }
505
533
 
506
534
  // src/v2/oauth.ts
535
+ var AI_USES_MAX = 8;
536
+ var AI_LIFETIME_MAX_MINUTES = 1440;
537
+ var AI_USE_SLUG = /^[A-Za-z0-9][A-Za-z0-9_.-]*$/;
538
+ function aiTokenParams(method, uses, minutes) {
539
+ if (uses === void 0) {
540
+ if (minutes !== void 0) throw new TypeError(`${method}: the AI token's lifetime goes with its uses: send aiUses too. Nothing was sent.`);
541
+ return {};
542
+ }
543
+ if (!Array.isArray(uses) || uses.length < 1 || uses.length > AI_USES_MAX) {
544
+ throw new TypeError(`${method}: the AI uses are a list of 1 to ${AI_USES_MAX} use names, got ${JSON.stringify(uses)}. Nothing was sent.`);
545
+ }
546
+ for (const u of uses) {
547
+ if (typeof u !== "string" || !AI_USE_SLUG.test(u)) {
548
+ throw new TypeError(`${method}: ${JSON.stringify(u)} is not an AI use's name (one path segment, as aiUses() lists them). Nothing was sent.`);
549
+ }
550
+ }
551
+ const body = { ai_uses: [...uses] };
552
+ if (minutes !== void 0) {
553
+ if (typeof minutes !== "number" || !Number.isInteger(minutes) || minutes < 1 || minutes > AI_LIFETIME_MAX_MINUTES) {
554
+ throw new TypeError(`${method}: the AI token's lifetime is a whole number of minutes, 1 to ${AI_LIFETIME_MAX_MINUTES}, got ${JSON.stringify(minutes)}. Nothing was sent.`);
555
+ }
556
+ body.ai_lifetime_minutes = minutes;
557
+ }
558
+ return body;
559
+ }
560
+ function readAiToken(v) {
561
+ const t = v;
562
+ if (!t || typeof t !== "object" || typeof t.token !== "string" || t.token === "" || typeof t.token_id !== "string" || t.token_id === "" || !Array.isArray(t.ai_uses) || !t.ai_uses.every((u) => typeof u === "string") || typeof t.expires_at !== "string" || t.expires_at === "") return null;
563
+ return { token: t.token, tokenId: t.token_id, tokenType: "bearer", audience: "ai", aiUses: [...t.ai_uses], expiresAt: t.expires_at };
564
+ }
507
565
  var RECORD_PREFIX = "ow_signin:";
508
566
  function defaultStorage(name) {
509
567
  const ss = globalThis.sessionStorage;
@@ -632,6 +690,7 @@ function samePage(a, b) {
632
690
  async function completeSignIn(baseUrl, fetchImpl, opts) {
633
691
  const { clientId } = opts ?? {};
634
692
  if (typeof clientId !== "string" || clientId === "") throw new TypeError("completeSignIn needs clientId");
693
+ const ai = aiTokenParams("completeSignIn", opts.aiUses, opts.aiLifetimeMinutes);
635
694
  const storage = opts.storage ?? defaultStorage("completeSignIn");
636
695
  const here = opts.url ?? globalThis.location?.href;
637
696
  if (typeof here !== "string") throw new TypeError("completeSignIn: no location here; pass url (the callback page's address)");
@@ -680,7 +739,8 @@ async function completeSignIn(baseUrl, fetchImpl, opts) {
680
739
  code,
681
740
  code_verifier: record.verifier,
682
741
  client_id: clientId,
683
- redirect_uri: record.redirectUri
742
+ redirect_uri: record.redirectUri,
743
+ ...ai
684
744
  })
685
745
  });
686
746
  } catch {
@@ -712,7 +772,8 @@ async function completeSignIn(baseUrl, fetchImpl, opts) {
712
772
  expiresAt: typeof ok.expires_at === "string" && ok.expires_at !== "" ? ok.expires_at : null,
713
773
  tokenType: "bearer",
714
774
  account: { id: ok.account.id, username: typeof ok.account.username === "string" ? ok.account.username : "" },
715
- resume: record.resume ?? null
775
+ resume: record.resume ?? null,
776
+ aiToken: "ai_uses" in ai ? readAiToken(ok.ai_token) : null
716
777
  };
717
778
  }
718
779
 
@@ -2061,6 +2122,32 @@ var OwV2Client = class {
2061
2122
  if (opts.keepalive !== void 0) send.keepalive = opts.keepalive;
2062
2123
  await this.request("DELETE", `/account/tokens/${seg("tokenId", tokenId)}`, send);
2063
2124
  }
2125
+ /**
2126
+ * POST /account/tokens with `ai_uses` -- trade this client's account token down to an AI door
2127
+ * token: an `ow_a_` token that opens only `aiUses()` and the uses named here (1 to 8, by slug, as
2128
+ * `aiUses()` lists them), as this account and on its token rating. Another use answers 403
2129
+ * `use_not_granted` (`err.isUseNotGranted`), every other route 401 `wrong_audience`
2130
+ * (`err.isWrongAudience`). It ends at midnight UTC, or `lifetimeMinutes` (1 to 1440) after the mint
2131
+ * if that comes first, then answers 401 `key_revoked`. It belongs to the token that minted it:
2132
+ * revoking this client's token revokes it too, while revoking it leaves this one live. A client
2133
+ * built on it revokes it with `revokeAccountToken(minted.id)`. The answer is the token's row with
2134
+ * the token itself, shown only here. A name the server does not run is a 422 (`err.code` `invalid_request`, `err.param` `ai_uses`).
2135
+ * Account token only; the AI door token itself mints nothing (401 `wrong_audience`).
2136
+ */
2137
+ async mintAiToken(uses, opts = {}) {
2138
+ only("mintAiToken", opts, ["lifetimeMinutes", "name"]);
2139
+ if (this.keyKind !== "account") {
2140
+ throw new TypeError("mintAiToken needs an account token (ow_a_)");
2141
+ }
2142
+ const body = aiTokenParams("mintAiToken", uses ?? null, opts.lifetimeMinutes);
2143
+ if (opts.name !== void 0) {
2144
+ if (typeof opts.name !== "string" || opts.name.length > 255) {
2145
+ throw new TypeError(`mintAiToken: name is a string of at most 255 characters, got ${JSON.stringify(opts.name)}. Nothing was sent.`);
2146
+ }
2147
+ body.name = opts.name;
2148
+ }
2149
+ return this.request("POST", "/account/tokens", { body });
2150
+ }
2064
2151
  // -- Sign in with OnlyWorlds (OAuth 2.1 code + PKCE) ----------------------
2065
2152
  /**
2066
2153
  * Start Sign in with OnlyWorlds from a tool's page: mint `state` and a PKCE verifier, keep them
@@ -2091,7 +2178,7 @@ var OwV2Client = class {
2091
2178
  * 400: used, expired, or another client's code), `rate_limited`, `offline`, `failed`.
2092
2179
  */
2093
2180
  async completeSignIn(opts) {
2094
- only("completeSignIn", opts, ["clientId", "storage", "url"]);
2181
+ only("completeSignIn", opts, ["clientId", "storage", "url", "aiUses", "aiLifetimeMinutes"]);
2095
2182
  return completeSignIn(this.baseUrl, this.fetchImpl, opts);
2096
2183
  }
2097
2184
  // -- Ask your world -------------------------------------------
@@ -2152,6 +2239,40 @@ var OwV2Client = class {
2152
2239
  }
2153
2240
  return this.request("GET", "/account/allowance");
2154
2241
  }
2242
+ /**
2243
+ * GET /account/ai -- the AI uses onlyworlds.com runs, each a named call a tool makes with ai():
2244
+ * its owner, provider, model and effort, the hash of its system prompt, what its body may hold, its
2245
+ * answer cap, its price, its daily ceiling, this account's calls left today, and whether it is on.
2246
+ * Reading it spends nothing. Needs the client's `ow_a_` token.
2247
+ */
2248
+ async aiUses(opts = {}) {
2249
+ only("aiUses", opts, ["signal"]);
2250
+ if (this.keyKind !== "account") {
2251
+ throw new TypeError("aiUses needs an account token (ow_a_): the uses and their calls left are per account");
2252
+ }
2253
+ const body = await this.request("GET", "/account/ai", { signal: opts.signal });
2254
+ return body.uses;
2255
+ }
2256
+ async ai(use, body, opts = {}) {
2257
+ only("ai", opts, ["idempotencyKey", "signal"]);
2258
+ if (this.keyKind !== "account") {
2259
+ throw new TypeError("ai needs an account token (ow_a_): every AI use is metered per account");
2260
+ }
2261
+ const path = `/account/ai/${seg("use", use)}`;
2262
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
2263
+ throw new TypeError(`ai: the body is the use's own object, got ${body === null ? "null" : Array.isArray(body) ? "an array" : typeof body}. Nothing was sent.`);
2264
+ }
2265
+ if (opts.idempotencyKey !== void 0 && (typeof opts.idempotencyKey !== "string" || opts.idempotencyKey === "" || opts.idempotencyKey.length > 200)) {
2266
+ throw new TypeError(`ai: idempotencyKey is a string of 1 to 200 characters, got ${JSON.stringify(opts.idempotencyKey)}. Nothing was sent.`);
2267
+ }
2268
+ return this.request("POST", path, {
2269
+ body,
2270
+ idempotencyKey: opts.idempotencyKey,
2271
+ signal: opts.signal,
2272
+ elementWrite: true,
2273
+ replayAware: true
2274
+ });
2275
+ }
2155
2276
  // -- Core request machinery ----------------------------------------------
2156
2277
  /**
2157
2278
  * Raw authenticated request against this client's baseUrl. Public since 4.0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@onlyworlds/sdk",
3
- "version": "4.136.0",
3
+ "version": "4.138.0",
4
4
  "description": "TypeScript SDK for the OnlyWorlds API - build world-building applications with type safety",
5
5
  "type": "module",
6
6
  "exports": {