@volter/twin-xai 0.1.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.
Files changed (56) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +246 -0
  3. package/client/xai-device-auth.css +246 -0
  4. package/client/xai-device-auth.tsx +138 -0
  5. package/dist/client/xai-device-auth.bundle.js +18 -0
  6. package/dist/client/xai-device-auth.css +246 -0
  7. package/dist/client/xai-device-auth.d.ts +19 -0
  8. package/dist/client/xai-device-auth.js +50 -0
  9. package/dist/client/xai-device-auth.tsx +138 -0
  10. package/dist/src/cli.d.ts +2 -0
  11. package/dist/src/cli.js +28 -0
  12. package/dist/src/index.d.ts +17 -0
  13. package/dist/src/index.js +70 -0
  14. package/dist/src/xai-budget.d.ts +60 -0
  15. package/dist/src/xai-budget.js +139 -0
  16. package/dist/src/xai-capabilities.d.ts +4 -0
  17. package/dist/src/xai-capabilities.js +1072 -0
  18. package/dist/src/xai-conformance.d.ts +13 -0
  19. package/dist/src/xai-conformance.js +148 -0
  20. package/dist/src/xai-connector.d.ts +82 -0
  21. package/dist/src/xai-connector.js +174 -0
  22. package/dist/src/xai-device-auth-css.gen.d.ts +1 -0
  23. package/dist/src/xai-device-auth-css.gen.js +6 -0
  24. package/dist/src/xai-device-auth-ui.d.ts +13 -0
  25. package/dist/src/xai-device-auth-ui.js +72 -0
  26. package/dist/src/xai-models.d.ts +57 -0
  27. package/dist/src/xai-models.js +102 -0
  28. package/dist/src/xai-oauth.d.ts +30 -0
  29. package/dist/src/xai-oauth.js +279 -0
  30. package/dist/src/xai-scenario.d.ts +33 -0
  31. package/dist/src/xai-scenario.js +139 -0
  32. package/dist/src/xai-server.d.ts +36 -0
  33. package/dist/src/xai-server.js +232 -0
  34. package/dist/src/xai-stub.d.ts +69 -0
  35. package/dist/src/xai-stub.js +210 -0
  36. package/dist/src/xai-twin.d.ts +89 -0
  37. package/dist/src/xai-twin.js +883 -0
  38. package/dist/src/xai-types.d.ts +118 -0
  39. package/dist/src/xai-types.js +6 -0
  40. package/package.json +76 -0
  41. package/src/cli.ts +27 -0
  42. package/src/index.ts +120 -0
  43. package/src/xai-budget.ts +165 -0
  44. package/src/xai-capabilities.ts +1046 -0
  45. package/src/xai-conformance.ts +136 -0
  46. package/src/xai-connector.ts +212 -0
  47. package/src/xai-device-auth-css.gen.ts +6 -0
  48. package/src/xai-device-auth-ui.ts +90 -0
  49. package/src/xai-journey.uitest.ts +155 -0
  50. package/src/xai-models.ts +154 -0
  51. package/src/xai-oauth.ts +301 -0
  52. package/src/xai-scenario.ts +148 -0
  53. package/src/xai-server.ts +258 -0
  54. package/src/xai-stub.ts +213 -0
  55. package/src/xai-twin.ts +960 -0
  56. package/src/xai-types.ts +111 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,246 @@
1
+ # @volter/twin-xai
2
+
3
+ A local, faithful **xAI (Grok) API** twin the real `@ai-sdk/xai` provider — or any
4
+ OpenAI-compatible client — talks to unmodified: point it at the twin's `baseURL` and
5
+ `generateText`/`streamText` (with tools), deferred completions, the grok model catalogs,
6
+ Live Search parameters, api-key introspection, and tokenize-text all work. Built on the
7
+ shared `@volter/world-core` kernel; see [the model](../../../docs/concepts/the-model.md) for storage and branching; no parallel side store.
8
+
9
+ The same server also covers the official Grok Build CLI's documented chat-proxy seam.
10
+ Generated Worlds seal both sides independently: `XAI_TWIN_AUTH_BASE_URL=${url}` exposes the
11
+ virtual account's device authorization/token exchange/refresh surface to a consuming credential
12
+ broker, while `GROK_CLI_CHAT_PROXY_BASE_URL=${url}/v1` routes inference. The virtual account issues
13
+ the lease bearer that broker supplies to the CLI through Grok Build's external-auth provider command; the
14
+ Twin honors `X-XAI-Token-Auth` and `x-grok-model-override` (including
15
+ `grok-build`), and successful calls accumulate on that same account's virtual usage ledger.
16
+ Remove either override—and set `TWIN_XAI_AUTH_SEAM=unsealed` when combining real OAuth with
17
+ twinned inference—for an explicit partial-unseal acceptance run. No real renewable credential
18
+ is copied into a sealed World. The official CLI does **not** consume
19
+ `XAI_TWIN_AUTH_BASE_URL`: direct `grok login --device-auth` still uses xAI's fixed device-login
20
+ origin and is an explicit capability todo, not a claimed sealed path.
21
+
22
+ ```ts
23
+ import { createXai } from '@ai-sdk/xai';
24
+ import { generateText } from 'ai';
25
+ import { createXaiTwinServer } from '@volter/twin-xai';
26
+
27
+ const { port } = createXaiTwinServer({});
28
+ const xai = createXai({ apiKey: 'xai-twin', baseURL: `http://127.0.0.1:${port}/v1` });
29
+ const res = await generateText({ model: xai('grok-4-0709'), prompt: 'hello' });
30
+ // res.text starts with "[twin-stub:grok-4-0709]" — a deterministic stub, clearly labeled.
31
+ ```
32
+
33
+ ## The generative-stub design (be honest)
34
+
35
+ The twin **cannot run Grok** — there are no weights here. So `POST /v1/chat/completions`,
36
+ `POST /v1/completions`, and `POST /v1/messages` return a **deterministic STUB completion**
37
+ that is unmistakably a twin stub (it carries a `[twin-stub:<model>]` marker and echoes your
38
+ prompt), and **Live Search** returns deterministic **labeled stub citations** on a
39
+ `twin.invalid` host — they **never** pretend to be real model output or real retrieval.
40
+
41
+ What **is** faithful is the **entire protocol envelope**, including xAI's deltas from plain
42
+ OpenAI compatibility:
43
+
44
+ - chat response shape — `{ id:<uuid>, object:'chat.completion', created, model, choices:[…],
45
+ usage:{prompt_tokens, completion_tokens, total_tokens, prompt_tokens_details,
46
+ completion_tokens_details, num_sources_used}, system_fingerprint }` (xAI ids are
47
+ **UUID-formatted**, not `chatcmpl-…`; usage carries the xAI token-detail objects)
48
+ - **errors** — xAI's gRPC-transcoded **flat `{ code, error }` strings** (e.g. `"Client
49
+ specified an invalid argument"`, `"Some requested entity was not found"`), never OpenAI's
50
+ nested `{ error: {…} }`; unknown models get the vendor's "does not exist or your team has
51
+ no access" 404
52
+ - **streaming** via SSE — `chat.completion.chunk` deltas ending with `data: [DONE]`; each
53
+ streamed **tool call arrives as ONE COMPLETE delta** (id + name + full arguments — xAI does
54
+ not split arguments across chunks; the real `@ai-sdk/xai` chunk schema rejects split deltas)
55
+ - **tool / function calling** — `tool_calls` + `finish_reason:'tool_calls'`, `tool_choice`
56
+ (none/required/named), `parallel_tool_calls`, schema-typed stub arguments
57
+ - **reasoning** — `grok-3-mini` accepts `reasoning_effort` (low/high) and exposes
58
+ `message.reasoning_content` + `usage.completion_tokens_details.reasoning_tokens`; the
59
+ grok-4-family **rejects `reasoning_effort` (400)** and spends reasoning tokens without ever
60
+ exposing the trace — both modeled
61
+ - **deferred completions** — `deferred:true` → `{ request_id }`, then
62
+ `GET /v1/chat/deferred-completion/:id` → `202` pending → `200` result → **consumed
63
+ (404 after)** — stateful, kernel-backed
64
+ - **Live Search** — `search_parameters` (mode auto/on/off, sources web/x/news/rss,
65
+ `return_citations`) validated; `citations[]` + `usage.num_sources_used` served. The twin
66
+ treats `mode:'auto'` as searching so behavior stays deterministic
67
+ - **structured outputs** — `response_format` json_object / json_schema → valid JSON content
68
+ - **Anthropic-compatible `POST /v1/messages`** — content blocks, `tool_use` (from
69
+ `input_schema`), `stop_reason`, `usage`, and the **required `max_tokens`** rule
70
+ - **legacy `POST /v1/completions`** — `text_completion` envelope
71
+
72
+ The genuinely **stateful + static** surface is real, not a stub:
73
+
74
+ - `POST /oauth2/device/code` + `/oauth2/token` — one coherent virtual Grok account with
75
+ pending/approve/deny, one-use device exchange, refresh rotation, expiring access tokens,
76
+ display identity, and shared virtual usage. `GET /oauth2/device` renders the small real
77
+ authorization page; in-process capability setup may make the same decision through the
78
+ Twin-only `/twin/oauth/authorizations` control seam, which is deliberately absent from the
79
+ network surface
80
+ - `GET /v1/models` (+ `/:id`) — the grok catalog (OpenAI-compatible shape), **merged with
81
+ connector-observed real models** (observed models are catalog rows for listing/retrieval;
82
+ they do not gain inference behavior or alias resolution); catalog aliases (`grok-4` →
83
+ `grok-4-0709`) resolve for retrieval AND inference
84
+ - `GET /v1/language-models` (+ `/:id`) — xAI's rich model objects (modalities, per-token
85
+ price fields, aliases). Price fields are deterministic representative constants, not a live
86
+ price sheet
87
+ - `GET /v1/image-generation-models` (+ `/:id`)
88
+ - `POST /v1/images/generations` — faithful shape (url | b64_json + revised_prompt, n 1–10)
89
+ including the xAI compatibility delta that OpenAI's `size`/`quality`/`style` are
90
+ **rejected (400)**
91
+ - `GET /v1/api-key` — key introspection (redacted value, acls, blocked/disabled flags); the
92
+ reserved sentinel `xai-blocked` reports `api_key_blocked:true` and 403s everywhere else
93
+ - `POST /v1/tokenize-text` — deterministic pseudo-tokenizer (faithful
94
+ `token_ids[].token_id/string_token/token_bytes` shape; tokens re-join to the input; NOT the
95
+ real Grok BPE)
96
+
97
+ Auth is modeled on the live wire: missing/`xai-invalid` bearer → 401, `xai-blocked` → 403,
98
+ any other ordinary API key accepted. A sealed Grok CLI request additionally requires a
99
+ current access token issued by this Twin's OAuth state; a foreign/live token fails 401 rather
100
+ than silently crossing Worlds. A deterministic `x-twin-force-rate-limit` trigger returns the
101
+ faithful 429 + `retry-after`.
102
+
103
+ ## Scenario scripting (twin scaffolding)
104
+
105
+ `xai-scenario.ts` (the anthropic-pack convention, adapted to the chat-completions wire):
106
+ a JSON scenario file scripts the exact assistant turns a flow under test needs — matched on
107
+ last user text / tools / tool-result turns / Nth call, answering with text and/or complete
108
+ `tool_calls` — while the envelope (unary + SSE) stays vendor-faithful. Wire up via
109
+ `createXaiTwinServer({ scenarioPath })`, `TWIN_XAI_SCENARIO`, or
110
+ `world-xai serve --scenario <file>`. Scenarios apply **only** to `POST /v1/chat/completions`
111
+ and are **twin scaffolding, not vendor surface** — deliberately absent from the capability
112
+ manifest.
113
+
114
+ ## CLI
115
+
116
+ ```
117
+ world-xai serve [--port N] [--root DIR] [--read-only] [--scenario FILE] # the API twin (SDK target)
118
+ world-xai conformance [--root DIR] # offline envelope checks
119
+ ```
120
+
121
+ ## Connector (pull; push refuses loudly)
122
+
123
+ `syncXaiFromReal` pulls the real model catalogs (`/v1/models` + `/v1/language-models`) into
124
+ the twin over an **injected client** (`liveXaiExecute(apiKey)` live; a fake in tests) — the
125
+ pack holds no key and imports no SDK at runtime. The served catalogs merge observed models
126
+ over the static table. **Push refuses loudly for every operation**: the xAI API has no
127
+ client-writable resources (every endpoint is inference or read-only catalog/introspection),
128
+ so `pushXaiAction` throws rather than silently dropping — or fabricating — a vendor write.
129
+
130
+ ## Rate budget (fail-closed, before every live call)
131
+
132
+ `liveXaiExecute` is this pack's **one construction site** for a client that really reaches
133
+ `api.x.ai`, and every request it issues goes through a **persistent, fail-closed rate budget**: a
134
+ durable spend ledger keyed by **vendor and a hash of the API key** (limits are per key, so it is
135
+ deliberately not cwd-scoped), consulted **before** the request, that **throws instead of calling**
136
+ past a rolling-window ceiling or while a `Retry-After`/429/`x-ratelimit-remaining: 0` cooldown is
137
+ armed. `checkBudget` **reserves** inside a file lock, so a burst is genuinely refused rather than
138
+ raced through; a corrupt ledger counts as a **full** window rather than zero spend; and the ledger is
139
+ on disk, so a fresh process does **not** get a fresh allowance. There is no option to disable it, and
140
+ a `budget` that is not an unmodified `XaiBudget` — a duck-typed stand-in, a subclass overriding
141
+ `checkBudget`, a `Proxy` trapping it — is refused rather than trusted.
142
+
143
+ The mechanism is **shared and vendor-agnostic** (`@volter/world-core` → `packages/world-core/src/rateBudget.ts`);
144
+ what lives here in [`xai-budget.ts`](src/xai-budget.ts) is xAI's **declaration** plus the
145
+ vendor-bound `XaiBudget`. Read the kernel module's header for what the guard does *not* guarantee.
146
+
147
+ **The numbers, honestly.** xAI **publishes no scalar rate limit at all** in its public docs — not in
148
+ the API reference, not on the models page (which carries pricing and capability tables but no
149
+ RPM/RPS/TPM figures), not in the overview or quickstart, and none of them even points at a dashboard
150
+ where one could be read. So this declaration does **not** model a vendor limit and does not pretend
151
+ to: it pins to the kernel's austere fallback — **60 weighted units / 60 s at 2 per call = 30 calls a
152
+ minute** — rather than borrowing OpenAI's tier limits on the strength of xAI's OpenAI-compatible
153
+ protocol. *Protocol compatibility is not quota compatibility.* Pricing is **flat, deliberately**:
154
+ `XaiExecute` is typed GET-only over read-only catalogs and push refuses loudly, so no caller can
155
+ reach a token-billed inference endpoint and no reachable endpoint is credibly dearer than another —
156
+ inventing a ratio would be a made-up number dressed as vendor fact. A caller can tighten further;
157
+ options may only tighten.
158
+
159
+ Proven by [`xai-budget.test.ts`](src/xai-budget.test.ts), which drives the **real** executor over an
160
+ injected `fetch` and an injected clock and asserts refusals **by counting calls**: after the 30th the
161
+ fake has recorded exactly 30, and the 31st attempt throws with that count **unchanged** — "it threw"
162
+ is not proof, "it threw and nothing left the process" is. Cross-process persistence is proven by
163
+ really running a second process. Two source-level teeth also fail the build: no in-pack test may
164
+ construct against the operator's real `$HOME` ledger, and the raw `api.x.ai` host may appear only in
165
+ an allowlisted file.
166
+
167
+ ## Coverage
168
+
169
+ The capability manifest (`xai-capabilities.ts`) enumerates the **real xAI API surface** as
170
+ the honest denominator; `verify()` proves each `done` against the local twin, offline +
171
+ deterministically. Run `bun scripts/twin-capabilities.ts xai` for the live numbers. The
172
+ SDK-parity test (`xai-sdk.integration.test.ts`) drives the twin with the real, unmodified
173
+ `@ai-sdk/xai` provider through its public `baseURL` option — `generateText`/`streamText`
174
+ with tools, the exact call shape of the primary consumer.
175
+
176
+ **Deliberately absent surface:** xAI publishes **no embeddings endpoint** (announced but not
177
+ GA at authoring time), so embeddings appear nowhere in the manifest — the twin 404s
178
+ `/v1/embeddings` exactly like the vendor, and listing it would be denominator padding. If
179
+ xAI ships it, it enters the manifest as honest `todo`s.
180
+
181
+ **Scope boundary (a different host, not an omission):** xAI's **Collections API** and
182
+ **Management API** live on `management-api.x.ai` — a separate console/administration
183
+ product. This pack twins the `api.x.ai` **inference** surface only; the management host is
184
+ out of this pack's scope by that boundary.
185
+
186
+ ### Grok Build device-authorization UI
187
+
188
+ xAI remains API-first, so this pack does **not** fabricate a mirror of the xAI key/billing
189
+ console. Grok Build device authorization is different: its code-entry and permission-consent
190
+ screens are vendor-owned browser steps inside the OAuth protocol itself. The denial and completion
191
+ screens in this pack are explicitly Twin-local terminal states because no official equivalents
192
+ were captured. The Twin serves those states on `/oauth2/device` and `/oauth2/device/consent` using one
193
+ projection-backed React renderer with the exact self-served SpaceXAI symbol, progressive form
194
+ submits, same-origin assets, UI-dimension capabilities, mutation coverage, and real-browser
195
+ approval/denial/invalid-code/sign-out journeys. Blank and invalid entry states match the live
196
+ disabled-button and clear-field redirect behavior. The permission rows
197
+ come from the pending request's stored scopes; the visible decision mutates the same device row
198
+ that `/oauth2/token` later exchanges. `world-xai mirror` is therefore only an alias for
199
+ `world-xai serve`, never a separate or drifting renderer.
200
+
201
+ ### Done (proven, verifiable)
202
+ - **Chat** — create + faithful envelope (UUID ids, usage detail objects), labeled stub,
203
+ validation (flat `{code,error}` 400s), vendor 404 for unknown models, `n`,
204
+ `max_tokens`/`max_completion_tokens`, system/multi-turn, `stop`, deterministic usage,
205
+ structured outputs, `seed`, `reasoning_effort` (grok-3-mini exposes / grok-4 rejects),
206
+ vision content parts (image_tokens counted)
207
+ - **Streaming** — chunk sequence + `[DONE]`, content reconstruction, terminal
208
+ `finish_reason`, complete-delta tool calls, `stream_options.include_usage`
209
+ - **Tools** — tool_calls envelope, `tool_choice`, `parallel_tool_calls`, schema-typed
210
+ arguments, tool-result round-trip
211
+ - **Live Search** — `search_parameters` validation + citations + `num_sources_used`, source
212
+ selection (web/x/news/rss), `return_citations` toggle
213
+ - **Deferred completions** — create (`request_id`), 202→200→consumed lifecycle
214
+ - **Messages (Anthropic-compat)** — envelope, required-`max_tokens` rule, tools → `tool_use`
215
+ - **Legacy completions** — `text_completion` envelope
216
+ - **Models** — flat list/get, alias resolution, rich language-models, image-generation
217
+ models
218
+ - **Images** — generations shape (url/b64_json, n bounds), OpenAI-param rejection delta
219
+ - **api-key** — introspection incl. the blocked sentinel
220
+ - **tokenize-text** — faithful token_ids shape
221
+ - **Errors/protocol** — flat envelope, modeled 401/403/429, read-only 405
222
+ - **Grok OAuth + CLI proxy** — brokered device authorization/exchange/refresh, the documented CLI chat-proxy override, session-token marker, and
223
+ `x-grok-model-override` routing for the built-in `grok-build` coding route
224
+ - **Connector** — read surface, pull+map+merge (offline, injected client, idempotent),
225
+ loud push refusal
226
+ - **Conformance** — offline envelope harness (9 checks)
227
+
228
+ ### Planned (todo — real vendor surface not yet reached)
229
+ - **The Responses API** — `POST /v1/responses` (+ retrieve/delete/compact), xAI's current
230
+ first-class stateful inference surface (docs now file chat completions under "legacy")
231
+ - Chat `logprobs`, presence/frequency penalties, cached prompt tokens
232
+ - Deferred-completion expiry window
233
+ - Live Search date range / max results / per-source filters
234
+ - Anthropic-compat streaming + system/multi-block content
235
+ - Legacy completions streaming + echo/suffix
236
+ - api-key ACL enforcement
237
+ - Direct `grok login --device-auth` redirection to a sealed Twin origin (the official CLI fixes
238
+ that login origin; brokered external auth is the supported one-sign-in seam today)
239
+ - Connector pull of the image-generation catalog (`xai.connector.pull_image_generation_models`,
240
+ also filed in pull-audit.json)
241
+
242
+ - Image URLs that resolve — serve deterministic placeholder image bytes at the URLs
243
+ `/v1/images/generations` returns
244
+
245
+ There are no carve-outs. The labeled stub completion and the deterministic labeled citations are
246
+ this twin's answer, not a shortfall from a "real" one; every capability is done or todo.