@volter/twin-togetherai 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 (39) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +147 -0
  3. package/dist/src/cli.d.ts +2 -0
  4. package/dist/src/cli.js +28 -0
  5. package/dist/src/index.d.ts +14 -0
  6. package/dist/src/index.js +79 -0
  7. package/dist/src/togetherai-budget.d.ts +52 -0
  8. package/dist/src/togetherai-budget.js +130 -0
  9. package/dist/src/togetherai-capabilities.d.ts +4 -0
  10. package/dist/src/togetherai-capabilities.js +1428 -0
  11. package/dist/src/togetherai-conformance.d.ts +14 -0
  12. package/dist/src/togetherai-conformance.js +452 -0
  13. package/dist/src/togetherai-connector.d.ts +164 -0
  14. package/dist/src/togetherai-connector.js +457 -0
  15. package/dist/src/togetherai-models.d.ts +19 -0
  16. package/dist/src/togetherai-models.js +49 -0
  17. package/dist/src/togetherai-scenario.d.ts +52 -0
  18. package/dist/src/togetherai-scenario.js +168 -0
  19. package/dist/src/togetherai-server.d.ts +16 -0
  20. package/dist/src/togetherai-server.js +187 -0
  21. package/dist/src/togetherai-stub.d.ts +59 -0
  22. package/dist/src/togetherai-stub.js +195 -0
  23. package/dist/src/togetherai-twin.d.ts +83 -0
  24. package/dist/src/togetherai-twin.js +1419 -0
  25. package/dist/src/togetherai-types.d.ts +207 -0
  26. package/dist/src/togetherai-types.js +26 -0
  27. package/package.json +52 -0
  28. package/src/cli.ts +27 -0
  29. package/src/index.ts +118 -0
  30. package/src/togetherai-budget.ts +156 -0
  31. package/src/togetherai-capabilities.ts +1315 -0
  32. package/src/togetherai-conformance.ts +459 -0
  33. package/src/togetherai-connector.ts +496 -0
  34. package/src/togetherai-models.ts +74 -0
  35. package/src/togetherai-scenario.ts +185 -0
  36. package/src/togetherai-server.ts +199 -0
  37. package/src/togetherai-stub.ts +197 -0
  38. package/src/togetherai-twin.ts +1448 -0
  39. package/src/togetherai-types.ts +222 -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,147 @@
1
+ # @volter/twin-togetherai
2
+
3
+ A local, faithful **Together AI API** twin your real `together-ai` SDK talks to unmodified — point
4
+ the client at the twin's `baseURL` and `chat.completions.create`, streaming, `models`, `files`,
5
+ `batches`, `fine-tunes`, `embeddings`, `rerank`, the image endpoints and the audio endpoints all
6
+ work. Built on the shared `@volter/world-core` kernel; see
7
+ [the model](../../../docs/concepts/the-model.md) for storage and branching; no parallel side store.
8
+
9
+ ```ts
10
+ import Together from 'together-ai';
11
+ import { createTogetheraiTwinServer } from '@volter/twin-togetherai';
12
+
13
+ const { port } = createTogetheraiTwinServer({});
14
+ // together-ai's baseURL is the API ROOT; it appends `/v1/…` (or `/v2/…` for videos) itself.
15
+ const client = new Together({ apiKey: 'twin-key', baseURL: `http://127.0.0.1:${port}/v1` });
16
+ const res = await client.chat.completions.create({
17
+ model: 'meta-llama/Llama-3.3-70B-Instruct-Turbo',
18
+ messages: [{ role: 'user', content: 'hello' }],
19
+ });
20
+ // res.choices[0].message.content starts with "[twin-stub:…]" — a deterministic stub, clearly labeled.
21
+ // res.usage carries the three token counts; res.prompt is Together's REQUIRED prompt array.
22
+ ```
23
+
24
+ ## `files.upload()` needs `TOGETHER_API_BASE_URL` — the one documented exception
25
+
26
+ The SDK's custom upload (`client.files.upload(path, purpose)`) is NOT an ordinary SDK call:
27
+ `together-ai` reads **`TOGETHER_API_BASE_URL` at module load and ignores the client's
28
+ `baseURL`** (`lib/upload.js:12`, together-ai@0.53.0 — it then POSTs
29
+ `${baseURL}/files?…` itself to drive its 302-redirect flow). Unset, that var defaults to
30
+ `https://api.together.xyz/v1`, so `files.upload()` **egresses to the real Together API with the
31
+ caller's key** even when the client points at the twin. Before the first `import 'together-ai'`
32
+ (the read happens at module load):
33
+
34
+ ```sh
35
+ TOGETHER_API_BASE_URL=http://127.0.0.1:<port>/v1
36
+ ```
37
+
38
+ Every other SDK call rides `baseURL` (or the injector's `api.together.ai` interception — a world
39
+ wired through `TOGETHER_TWIN_URL` gets `TOGETHER_API_BASE_URL=<twin>/v1` injected from this pack's
40
+ descriptor automatically) and needs nothing else. The integration suite pins the same var for the
41
+ same reason (`togetherai-sdk.integration.test.ts`).
42
+
43
+ ## Together is not OpenAI — the differences this twin models
44
+
45
+ Together exposes an *OpenAI-compatible* inference surface, and treating "compatible" as "identical"
46
+ is how a Together twin gets built wrong. The load-bearing differences, each grounded in
47
+ [`together-ai@0.53.0`](https://www.npmjs.com/package/together-ai) (Stainless-generated from
48
+ Together's own OpenAPI), Together's published spec (141 paths / 156 operations) and Together's
49
+ docs, read 2026-09-16:
50
+
51
+ | | Together | OpenAI |
52
+ |---|---|---|
53
+ | base URL | **`https://api.together.ai/v1/…`** (`TOGETHER_BASE_URL`) | `https://api.openai.com/v1/…` |
54
+ | error envelope | `{ error: { message, type, param, code } }` — `message`+`type` required, `param`/`code` nullable | same shape |
55
+ | `n` | **1..128** — an OpenAI-compatible freedom | no 128 cap |
56
+ | `logprobs` | an **integer 0..20** (not a boolean) | boolean |
57
+ | context overflow | **403** ("context length exceeded"), with `context_length_exceeded_behavior: truncate\|error` | 400 |
58
+ | spending limit | **402** — monthly spending limit reached | — |
59
+ | overload | **503** `engine_overloaded` | — |
60
+ | rate limit | 429 with types `dynamic_request_limited`/`dynamic_token_limited` + `x-ratelimit-reset`; success responses carry NO rate-limit headers | `x-ratelimit-*` on every response |
61
+ | finish reasons | adds **`eos`** | `stop`/`length`/`tool_calls`/`function_call` |
62
+ | chat response | **`prompt: []` REQUIRED** on the schema; usage is **nullable** | no `prompt` array |
63
+ | streaming | **every chunk carries `usage` + `warnings`** | usage only in an opt-in tail chunk |
64
+ | assistant message | has **`reasoning`** / `reasoning_content`; has **no `refusal`** | has `refusal` |
65
+ | files | purposes **`fine-tune`/`eval`/`batch-api`**, capital-F `Processed`/`FileType`, `processing_status` pipeline; upload is a **302-redirect flow** in the SDK or multipart `/files/upload` | `batch`/`fine-tune`/`assistants` purposes |
66
+ | batches | **201 `BatchJobWithWarning {job}`**, list answers a **bare array**, errors are a bare string, UPPER-CASE statuses, endpoints `chat/completions` + audio | 200 batch object, `{object:'list',data}`, `cancelling` statuses |
67
+ | fine-tunes | `/v1/fine-tunes` (NOT OpenAI's `/v1/fine_tuning/jobs`), 9-state lowercase enum, delete answers `{message}` (not `{id, deleted}`) | different path + shape |
68
+ | model ids | slash-namespaced (`meta-llama/Llama-3.3-70B-Instruct-Turbo`) | flat |
69
+
70
+ The twin serves **only** `/v1/…` (the inference half). The v2 management half (endpoints,
71
+ deployments, compute, rl, videos, evaluation, queue, tci) is real Together surface this pack does
72
+ not serve — it 404s like any other unmodeled path, never a fake success. Assistants/Threads,
73
+ `moderations`, OpenAI's `responses` API and OpenAI's batch/file/fine-tuning shapes do not exist at
74
+ Together, so the twin refuses them too.
75
+
76
+ ## The generative-stub design (be honest)
77
+
78
+ The twin **cannot run the model** — there are no weights here. So `POST /v1/chat/completions`
79
+ returns a **deterministic STUB completion** that is unmistakably a twin stub (it carries a
80
+ `[twin-stub:<model>]` marker and echoes your prompt), `POST /v1/embeddings` returns **deterministic
81
+ pseudo-vectors** (L2-normalized, seeded from the input hash, at each model's documented
82
+ dimensionality), `POST /v1/rerank` returns **deterministic pseudo-scores**, and the audio/image
83
+ endpoints return **deterministic labeled stubs**. They **never** pretend to be real model output.
84
+
85
+ What **is** faithful is the **entire protocol envelope**:
86
+
87
+ - chat response shape — `{ id, object:'chat.completion', created, model, choices:[{index, message, finish_reason}], prompt:[], usage }`
88
+ - **streaming** via SSE — real `data: {…chat.completion.chunk with choices[].delta…}` chunks ending with `data: [DONE]` (role chunk → reasoning/content/tool_call deltas → finish_reason chunk → the empty-choices usage tail; **every chunk carries Together's `usage` + `warnings`**; driven through an injected sink — no real sockets in the handler)
89
+ - **tool / function calling** — `tool_calls` + `finish_reason:'tool_calls'`, `tool_choice` (`none`/`auto`/`required`/named), `parallel_tool_calls`, and the deprecated `functions` array answering the deprecated `function_call` shape
90
+ - **reasoning** — `reasoning_effort` `low`/`medium`/`high` surfaces the `reasoning` field on the assistant message
91
+ - **structured outputs** — `response_format` `json_object` / `json_schema` (Together REQUIRES `json_schema.name`, ≤64 chars `[a-zA-Z0-9_-]` — enforced)
92
+ - `n` (1..128), `max_tokens`, `stop`, `seed`, `echo` (the REQUIRED `prompt` array), integer `logprobs` (0..20), `compliance:'hipaa'`; the OpenAI fields Together accepts-but-ignores (`service_tier`, `store`, `metadata`, `prediction`) change nothing; **deterministic usage**
93
+ - Stub honesty: the deterministic completion is ONE continuation regardless of `n` (every choice repeats it); `stop` sequences are honored deterministically — the text is cut at the earliest occurrence of any stop string (the envelope validates and echoes them).
94
+
95
+ The genuinely **stateful + static** surface is real, not a stub:
96
+
97
+ - `GET /v1/models` (+ `/models/:id`) — static catalog answering a **bare array** of `ModelInfo` with Together's `type`/`display_name`/`context_length`
98
+ - `GET /v1/whoami` — static identity for the presented key
99
+ - **Files** — `POST /v1/files/upload` (the spec's create) + `GET/DELETE /v1/files{,/:id,/content}` (+ the SDK's **302-redirect flow** with `x-together-file-id`), kernel-backed, Together's closed purpose/type sets, `processing_status` on fine-tune files
100
+ - **Batches** — `POST/GET /v1/batches` (+ cancel → `CANCELLED`), 201 `BatchJobWithWarning`, bare-array list, closed 3-endpoint set. The asynchronous `VALIDATING→IN_PROGRESS→COMPLETED` progression is a filed `todo`, not modeled: doing it on a read made a GET write to the log (breaking the read-only contract) and minted an action with no vendor endpoint to push it to.
101
+ - **Fine-tunes** — `POST/GET/DELETE /v1/fine-tunes` (+ cancel, events, checkpoints, estimate-price, preview, models/limits), purpose-checked training files; delete answers `{message}` and estimate-price the SDK's `estimation_available` union
102
+
103
+ Vendor-shaped errors throughout: `400` / `401` / `402` / `403` / `404` / `405` (read-only guard) /
104
+ `429` / `503`. Every envelope carries the required `message` + `type` and only keys Together's
105
+ `ErrorData` declares.
106
+
107
+ ## Rate budget (live calls)
108
+
109
+ `liveTogetheraiExecute` — the ONE place this pack issues a real `api.together.xyz` request — routes
110
+ every call through the kernel's fail-closed `RateBudget`. Together publishes NO fixed request limit
111
+ (dynamic, per organization per model), so the declaration pins the kernel's fallback ceiling
112
+ (60 units / 60s, defaultWeight 2 = 30 calls/min) and buys resolution DOWNWARD: inference endpoints
113
+ cost 6, so at most 10 land in a window. A 429's `x-ratelimit-reset` becomes a persisted cooldown.
114
+ There is no option to disable the guard.
115
+
116
+ ## Scenario scripting (twin-only)
117
+
118
+ Chat completions can be scripted by MSW-shaped handlers in a world dir's `handlers/togetherai.json`,
119
+ run by the ONE kernel scenario engine with this pack's adapter:
120
+
121
+ ```json
122
+ { "handlers": [
123
+ { "on": { "userTextIncludes": "refund", "hasTool": "create_job" },
124
+ "respond": { "toolCalls": { "name": "create_job", "arguments": { "title": "Refund order" } } }, "once": true },
125
+ { "on": { "reasoningEffortEquals": "high" }, "respond": { "error": { "type": "engine_overloaded" } } }
126
+ ] }
127
+ ```
128
+
129
+ Load it with `--scenario FILE` / `createTogetheraiTwinServer({ scenarioPath })` /
130
+ `TWIN_TOGETHERAI_SCENARIO`. The read doors `GET /twin` and `GET /twin/scenario` explain and inspect
131
+ it. A malformed file throws **at load**, never a silent fall-back. Scenario support is twin-only
132
+ scaffolding for eval worlds, not vendor surface, so it is deliberately **not** in the capability
133
+ manifest.
134
+
135
+ ## CLI
136
+
137
+ ```sh
138
+ world-togetherai serve [--port N] [--root DIR] [--read-only] [--scenario FILE]
139
+ world-togetherai conformance [--root DIR]
140
+ ```
141
+
142
+ ## Coverage
143
+
144
+ The capability manifest (`togetherai-capabilities.ts`) is authored against Together's published
145
+ OpenAPI spec — 141 paths / 156 operations — with every entry `done` (with a runnable verify) or
146
+ `todo`. The v2 management half is filed honestly as `todo` at `niche` tier. Run
147
+ `world-togetherai conformance` for the offline protocol checks.
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,28 @@
1
+ #!/usr/bin/env node
2
+ import { keepProcessAlive } from '@volter/world-core/lifecycle';
3
+ // world-togetherai CLI: serve the Together API twin or run conformance. Together is an API-first
4
+ // vendor — app.together.ai is a console, not where the work happens
5
+ // (docs/contributing/architecture.md C1b) — so this pack ships no mirror.
6
+ import { hasFlag, optionValue } from '@volter/world-core/args';
7
+ import { createTogetheraiTwinServer } from "./togetherai-server.js";
8
+ const [cmd, ...rest] = process.argv.slice(2);
9
+ const port = Number(optionValue(rest, '--port', '0')) || undefined;
10
+ const root = optionValue(rest, '--root') || undefined;
11
+ const readOnly = hasFlag(rest, '--read-only'); // a twin accepts writes unless started read-only
12
+ const scenario = optionValue(rest, '--scenario') || undefined; // scripted completions (JSON file)
13
+ if (cmd === 'serve') {
14
+ const s = await createTogetheraiTwinServer({ readOnly, ...(root ? { root } : {}), ...(port ? { port } : {}), ...(scenario ? { scenarioPath: scenario } : {}) });
15
+ process.stdout.write(`togetherai twin (Together API at /v1; model output is a deterministic stub)${readOnly ? ' [read-only]' : ''}${scenario ? ` [scenario: ${scenario}]` : ''} at http://127.0.0.1:${s.port}\n`);
16
+ await keepProcessAlive();
17
+ }
18
+ else if (cmd === 'conformance') {
19
+ // dev-only; lazy so the bin runs without @volter/world-tooling
20
+ const { checkTogetheraiConformance } = await import("./togetherai-conformance.js");
21
+ const report = await checkTogetheraiConformance({ ...(root ? { root } : {}) });
22
+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);
23
+ if (!report.ok)
24
+ process.exitCode = 1;
25
+ }
26
+ else {
27
+ process.stdout.write('Usage: world-togetherai serve|conformance [--port N] [--root DIR] [--read-only] [--scenario FILE]\n');
28
+ }
@@ -0,0 +1,14 @@
1
+ export { handleTogetheraiTwinRequest, streamChat, buildChatCompletion, TOGETHERAI_API_PREFIX, TOGETHERAI_UPLOAD_DOOR, handleTogetheraiUploadDoor } from './togetherai-twin.js';
2
+ export type { TogetheraiRequest, TogetheraiResponseEnvelope } from './togetherai-twin.js';
3
+ export { createTogetheraiTwinFetch, createTogetheraiTwinServer, type TogetheraiTwinFetchOptions } from './togetherai-server.js';
4
+ export { TOGETHERAI_MODELS, findModel, SPEECH_MODELS, EMBEDDING_MODELS, EMBEDDING_DIMENSIONS, RERANK_MODELS } from './togetherai-models.js';
5
+ export { buildUsage, contentToText, countPromptTokens, estimateTokens, fnv1a, lastUserText, pseudoEmbedding, stubAssistantText, stubAudioSeconds, stubJsonObject, stubReasoningText, stubToolArguments, stubToolCall, stubTranscript, } from './togetherai-stub.js';
6
+ export type { TogetheraiAssistantMessage, TogetheraiBatch, TogetheraiBatchEndpoint, TogetheraiBatchStatus, TogetheraiChatCompletion, TogetheraiChoice, TogetheraiEmbedding, TogetheraiEmbeddingResponse, TogetheraiError, TogetheraiFile, TogetheraiFilePurpose, TogetheraiFileType, TogetheraiFinishReason, TogetheraiMessageParam, TogetheraiModel, TogetheraiRerankResponse, TogetheraiToolCall, TogetheraiUsage, SseEvent, SseSink, } from './togetherai-types.js';
7
+ export { createTogetheraiScenarioEngine, togetheraiScenarioAdapter, loadTogetheraiScenarioDocument, realizeTogetheraiRespond } from './togetherai-scenario.js';
8
+ export type { TogetheraiScenarioEngine, TogetheraiScenarioRequest, TogetheraiScenarioRespond, ScenarioToolCall, ScriptedResult } from './togetherai-scenario.js';
9
+ export { fullSyncTogetherai, externalIdFor, togetheraiRequestForAction, liveTogetheraiExecute, mapBatch, mapFile, mapModel, pullTogetheraiState, pushTogetheraiAction, pushPendingTogetheraiActions, syncTogetheraiFromReal, unpushableReason, } from './togetherai-connector.js';
10
+ export type { TogetheraiExecute, LiveTogetheraiOptions } from './togetherai-connector.js';
11
+ export { TOGETHERAI_BUDGET_CEILING, TOGETHERAI_BUDGET_MAX_RETRY_AFTER_S, TOGETHERAI_BUDGET_WINDOW_MS, TOGETHERAI_CALL_WEIGHTS, TOGETHERAI_RATE_BUDGET, TogetheraiBudget, TogetheraiBudgetError, togetheraiBudgetPath, togetheraiCallWeight, } from './togetherai-budget.js';
12
+ export type { TogetheraiBudgetErrorKind, TogetheraiBudgetOptions, TogetheraiBudgetReservation, TogetheraiBudgetSnapshot } from './togetherai-budget.js';
13
+ import { type TwinPack } from '@volter/world-core';
14
+ export declare const pack: TwinPack;
@@ -0,0 +1,79 @@
1
+ // @volter/twin-togetherai — the Together AI twin (one vendor, one package), built on the shared
2
+ // @volter/world-core kernel. The Together API: a vendor-faithful protocol envelope (chat
3
+ // completions/streaming/tool_calls with Together's REQUIRED `prompt` array and per-chunk
4
+ // usage/warnings, `eos` finish reasons, Together's OWN status table — 402 spending limit, 403
5
+ // context length, 503 engine overloaded), a static models catalog, deterministic embeddings/
6
+ // rerank/image/audio stubs, and STATEFUL files + batches + fine-tunes — over an event/action log.
7
+ // (Together is an API-first vendor: app.together.ai is a console, not where the work happens, so
8
+ // this pack ships no mirror.)
9
+ //
10
+ // THE DETERMINISTIC STUB IS THE ANSWER: the twin runs no model, so POST /v1/chat/completions
11
+ // returns a DETERMINISTIC STUB completion (clearly labeled), /v1/embeddings returns DETERMINISTIC
12
+ // pseudo-vectors, and the audio endpoints return DETERMINISTIC labeled stubs — never pretending to
13
+ // be real inference. Everything around them — the wire protocol — is faithful. (Conformance +
14
+ // capability tooling live in @volter/world-tooling, a dev dependency — NOT re-exported here, per
15
+ // E2.)
16
+ export { handleTogetheraiTwinRequest, streamChat, buildChatCompletion, TOGETHERAI_API_PREFIX, TOGETHERAI_UPLOAD_DOOR, handleTogetheraiUploadDoor } from "./togetherai-twin.js";
17
+ export { createTogetheraiTwinFetch, createTogetheraiTwinServer } from "./togetherai-server.js";
18
+ export { TOGETHERAI_MODELS, findModel, SPEECH_MODELS, EMBEDDING_MODELS, EMBEDDING_DIMENSIONS, RERANK_MODELS } from "./togetherai-models.js";
19
+ export { buildUsage, contentToText, countPromptTokens, estimateTokens, fnv1a, lastUserText, pseudoEmbedding, stubAssistantText, stubAudioSeconds, stubJsonObject, stubReasoningText, stubToolArguments, stubToolCall, stubTranscript, } from "./togetherai-stub.js";
20
+ export { createTogetheraiScenarioEngine, togetheraiScenarioAdapter, loadTogetheraiScenarioDocument, realizeTogetheraiRespond } from "./togetherai-scenario.js";
21
+ export { fullSyncTogetherai, externalIdFor, togetheraiRequestForAction, liveTogetheraiExecute, mapBatch, mapFile, mapModel, pullTogetheraiState, pushTogetheraiAction, pushPendingTogetheraiActions, syncTogetheraiFromReal, unpushableReason, } from "./togetherai-connector.js";
22
+ // The client-side rate budget — the fail-closed backstop `liveTogetheraiExecute` routes every live
23
+ // request through. The MECHANISM is the kernel's shared, vendor-agnostic `RateBudget`; what lives
24
+ // here is Together's DECLARATION (window/ceiling/per-endpoint weights) plus the vendor-bound
25
+ // bindings. Exported so an operator can inspect spend (`snapshot`) and so a caller can catch
26
+ // `TogetheraiBudgetError` by type; there is deliberately no export that disables the guard.
27
+ export { TOGETHERAI_BUDGET_CEILING, TOGETHERAI_BUDGET_MAX_RETRY_AFTER_S, TOGETHERAI_BUDGET_WINDOW_MS, TOGETHERAI_CALL_WEIGHTS, TOGETHERAI_RATE_BUDGET, TogetheraiBudget, TogetheraiBudgetError, togetheraiBudgetPath, togetheraiCallWeight, } from "./togetherai-budget.js";
28
+ // Registry descriptor: the pack self-describes so tooling can discover it.
29
+ import { registerPack } from '@volter/world-core';
30
+ import { TOGETHERAI_RATE_BUDGET as RATE_BUDGET } from "./togetherai-budget.js";
31
+ import { performTogetheraiAction, syncTogetheraiFromRemote } from "./togetherai-connector.js";
32
+ export const pack = {
33
+ vendor: 'togetherai',
34
+ // PROTOCOL 2 (docs/contributing/architecture.md#protocol-2-the-pack-is-a-plugin): the pack is a plugin — its wire, its tree, and its half of
35
+ // the real state system: perform one entry against Together, refresh the root from it.
36
+ protocol: '2',
37
+ stateSystem: { perform: performTogetheraiAction, refresh: syncTogetheraiFromRemote },
38
+ // the round trip: a file create — the one thing this API mints an id for and keeps, a fresh id
39
+ // each time, so it repeats cleanly on a branch (the spec's own create door, POST
40
+ // /v1/files/upload; Together's purposes are a CLOSED set: fine-tune | eval | batch-api)
41
+ roundTrip: { method: 'POST', path: '/v1/files/upload', body: { purpose: 'batch-api', file_name: 'round-trip.jsonl', content: '' }, headers: { authorization: 'Bearer rt' } },
42
+ // The SAME object togetherai-budget.ts declares at module load — one source of truth, so
43
+ // registering the pack and importing the connector can never arm two different ceilings.
44
+ rateBudget: RATE_BUDGET,
45
+ transport: 'rest',
46
+ archetype: 'generative',
47
+ bin: 'world-togetherai',
48
+ // R2 adopted-as-debt, legibly: declared types no replay can create, each with its reason.
49
+ resourcesUnreachable: {
50
+ 'model': 'the vendor catalog',
51
+ },
52
+ resources: ['file', 'batch', 'finetune', 'model'],
53
+ specSource: 'Together API — enumerated from Together\'s own published OpenAPI spec (api.together.xyz/openapi.json, captured to test-fixtures/togetherai-openapi.yaml: 141 paths / 156 operations — the /v1 inference half AND the v2 management half, of which this pack models the inference half) + together-ai@0.53.0 (Stainless-generated from Together\'s spec: the model unions, the SDK-only 302-redirect upload flow, whoami, the TOGETHER_BASE_URL/TOGETHER_API_KEY/TOGETHER_PROJECT_ID env contract) + docs.together.ai/{error-codes,serverless/rate-limits,inference/openai-compatibility} (all read 2026-09-16). Envelope-faithful; model output, embedding values, rerank scores, images and audio are labeled deterministic stubs.',
54
+ description: 'Together AI API twin — faithful protocol envelope (chat completions/streaming/tool_calls, Together\'s prompt array and eos finish reasons, Together\'s own 402/403/503 status table), models, stateful files/batches/fine-tunes (both upload flows, incl. the SDK\'s 302 redirect), embeddings/rerank/images/audio; generative output is a labeled stub.',
55
+ // ADOPTION (adding-a-twin.md §3): how an app repo betrays that it talks to Together. Declared
56
+ // HERE, not in world-runtime's central SDK_TWINS/ENV_STEM_VENDORS maps — declaring in both
57
+ // throws. `together-ai` is Together's own official client (npm).
58
+ adoption: {
59
+ sdks: ['together-ai'], envStems: ['TOGETHER'],
60
+ },
61
+ // INTERCEPTION: the host the official client addresses by default
62
+ // (together-ai@0.53.0 client.js: TOGETHER_BASE_URL defaults to https://api.together.ai/v1).
63
+ hosts: [{ host: 'api.together.ai' }],
64
+ // App-read endpoint templates RIDE ALONGSIDE the injector (the PLANETSCALE_DATABASE_URL
65
+ // precedent, init.ts wiringFor): `together-ai`'s custom `files.upload()` reads
66
+ // `TOGETHER_API_BASE_URL` at MODULE LOAD and IGNORES the client's `baseURL`
67
+ // (lib/upload.js:12 — it then POSTs `${baseURL}/files?…` itself), so interception of
68
+ // api.together.ai does NOT cover it: unset, `files.upload()` egresses to the real
69
+ // https://api.together.xyz with the caller's key. The template points that var at the twin's
70
+ // `/v1` (the SDK POSTs `/files?…` onto it directly), so the one flow the injector cannot reach
71
+ // is wired too, while ordinary SDK traffic still rides the injector.
72
+ endpointEnv: {
73
+ name: 'TOGETHER_TWIN_URL',
74
+ templates: { TOGETHER_API_BASE_URL: '${url}/v1' },
75
+ note: 'the injector covers api.together.ai, but together-ai\'s files.upload() reads TOGETHER_API_BASE_URL at module load and ignores client.baseURL (lib/upload.js:12) — the template points it at the twin\'s /v1 so the SDK upload flow does not egress to the real vendor.',
76
+ },
77
+ };
78
+ // registered at import: the kernel learns the pack's state system (protocol 2)
79
+ registerPack(pack);
@@ -0,0 +1,52 @@
1
+ import { RateBudget, type RateBudgetDeclaration, type RateBudgetOptions, type RateBudgetReservation, type RateBudgetSnapshot } from '@volter/world-core';
2
+ /** Rolling window, in ms. Spend older than this is pruned. */
3
+ export declare const TOGETHERAI_BUDGET_WINDOW_MS = 60000;
4
+ /**
5
+ * Weighted units allowed inside one window. 60/60s at `defaultWeight` 2 = 30 calls a minute —
6
+ * EXACTLY the kernel's undeclared fallback, because Together publishes no scalar that would
7
+ * justify more. See the header.
8
+ */
9
+ export declare const TOGETHERAI_BUDGET_CEILING = 60;
10
+ /** Seconds. A `x-ratelimit-reset` above this means the key is throttled hard — fail loudly, don't sleep. */
11
+ export declare const TOGETHERAI_BUDGET_MAX_RETRY_AFTER_S = 300;
12
+ /** Per-call cost, keyed by `"<METHOD> <path>"`. See the header for what is documented vs. judged. */
13
+ export declare const TOGETHERAI_CALL_WEIGHTS: {
14
+ /** `/v1/chat/completions`, `/v1/completions`, `/v1/embeddings`, `/v1/rerank`,
15
+ * `/v1/images/generations`, `/v1/audio/*` — token-metered, where Together's DYNAMIC token
16
+ * budget (`dynamic_token_limited`) rather than its request budget is usually what binds. */
17
+ readonly inference: 6;
18
+ /** Everything else: files, batches, models, whoami, fine-tunes, endpoints. */
19
+ readonly other: 2;
20
+ };
21
+ /** THE PACK'S DECLARATION — pure data, the only Together-specific thing in the whole budget. */
22
+ export declare const TOGETHERAI_RATE_BUDGET: RateBudgetDeclaration;
23
+ /**
24
+ * Price one call. The key is `"<METHOD> <path>"` with the query string split off, so a rule can
25
+ * price by method (a write is not a read) without the kernel knowing anything about Together. An
26
+ * unclassified endpoint still costs `defaultWeight` — nothing is ever free.
27
+ */
28
+ export declare function togetheraiCallWeight(method: string, path: string): number;
29
+ /** Where Together's ledger lives. Token-keyed and cwd-independent by default (Together's limits
30
+ * are per ORGANIZATION, i.e. per key, so a cwd-scoped ledger would hand the same key a fresh
31
+ * allowance in every checkout, worktree and CI matrix leg); pass `root` for world-scoped
32
+ * accounting. */
33
+ export declare function togetheraiBudgetPath(opts?: {
34
+ root?: string;
35
+ token?: string;
36
+ } | string): string;
37
+ /** Construction options for Together's budget. The vendor is fixed; everything else may only TIGHTEN. */
38
+ export type TogetheraiBudgetOptions = Omit<RateBudgetOptions, 'vendor'>;
39
+ /**
40
+ * Together's budget — the shared kernel guard bound to this vendor's declaration. A real
41
+ * subclass, not an alias, so `budget instanceof TogetheraiBudget` in `liveTogetheraiExecute`
42
+ * means "a budget that accounts against TOGETHER's ledger under TOGETHER's ceiling".
43
+ */
44
+ export declare class TogetheraiBudget extends RateBudget {
45
+ constructor(opts?: TogetheraiBudgetOptions);
46
+ }
47
+ /** The typed refusal. One error class shared with every other vendor's budget; `err.vendor` says
48
+ * which one refused, and `err.kind` says why. */
49
+ export { RateBudgetError as TogetheraiBudgetError } from '@volter/world-core';
50
+ export type { RateBudgetErrorKind as TogetheraiBudgetErrorKind } from '@volter/world-core';
51
+ export type TogetheraiBudgetReservation = RateBudgetReservation;
52
+ export type TogetheraiBudgetSnapshot = RateBudgetSnapshot;