@302ai/media-studio-core 0.1.0-beta.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/LICENSE +190 -0
- package/README.md +213 -0
- package/dist/client/auth.d.ts +13 -0
- package/dist/client/auth.js +34 -0
- package/dist/client/chat.d.ts +14 -0
- package/dist/client/chat.js +89 -0
- package/dist/client/client.d.ts +20 -0
- package/dist/client/client.js +34 -0
- package/dist/client/session.d.ts +33 -0
- package/dist/client/session.js +91 -0
- package/dist/client/sessions.d.ts +54 -0
- package/dist/client/sessions.js +213 -0
- package/dist/client/types.d.ts +45 -0
- package/dist/client/types.js +9 -0
- package/dist/events.d.ts +90 -0
- package/dist/format/tool-formatter.d.ts +31 -0
- package/dist/format/tool-formatter.js +395 -0
- package/dist/index.d.ts +18 -0
- package/dist/index.js +24 -0
- package/dist/media/media-result.d.ts +21 -0
- package/dist/media/media-result.js +134 -0
- package/dist/media.d.ts +16 -0
- package/dist/sessions/types.d.ts +375 -0
- package/dist/sessions/types.js +129 -0
- package/dist/stream/events.d.ts +90 -0
- package/dist/stream/events.js +54 -0
- package/dist/stream/stream.d.ts +58 -0
- package/dist/stream/stream.js +325 -0
- package/dist/transport/errors.d.ts +30 -0
- package/dist/transport/errors.js +47 -0
- package/dist/transport/types.d.ts +44 -0
- package/dist/transport/types.js +1 -0
- package/dist/transport/upstream.d.ts +8 -0
- package/dist/transport/upstream.js +63 -0
- package/package.json +52 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
Copyright 2026 302.AI
|
|
179
|
+
|
|
180
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
181
|
+
you may not use this file except in compliance with the License.
|
|
182
|
+
You may obtain a copy of the License at
|
|
183
|
+
|
|
184
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
185
|
+
|
|
186
|
+
Unless required by applicable law or agreed to in writing, software
|
|
187
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
188
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
189
|
+
See the License for the specific language governing permissions and
|
|
190
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
# @302ai/media-studio-core
|
|
2
|
+
|
|
3
|
+
Outbound client and isomorphic core SDK for 302.AI Media Studio services. Provides high-level client management (`MediaStudioClient`), session lifecycle and prewarming (`client.sessions`), and low-level streaming chat completions transport (`sendChatUpstream`).
|
|
4
|
+
|
|
5
|
+
## Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
bun add @302ai/media-studio-core
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Usage
|
|
12
|
+
|
|
13
|
+
### High-level client & sessions
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { createMediaStudioClient } from "@302ai/media-studio-core";
|
|
17
|
+
|
|
18
|
+
const client = createMediaStudioClient({
|
|
19
|
+
baseUrl: "https://media.302.ai",
|
|
20
|
+
apiKey: process.env.API_302_KEY,
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
// List sessions from server
|
|
24
|
+
const { sessions } = await client.sessions.list({ limit: 20 });
|
|
25
|
+
|
|
26
|
+
// Provision a new session via prewarm
|
|
27
|
+
const outcome = await client.sessions.prewarm({
|
|
28
|
+
sessionId: crypto.randomUUID(),
|
|
29
|
+
source: "cli", // "web" | "cli"
|
|
30
|
+
note: "CLI Session",
|
|
31
|
+
onStageChange: (stage) => console.log(`Stage: ${stage}`),
|
|
32
|
+
onSessionReady: (session) => {
|
|
33
|
+
// Upstream commit point: safe to save pointer
|
|
34
|
+
saveSessionId(session.id);
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
// Delete a session
|
|
39
|
+
await client.sessions.remove(sessionId);
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
### Low-level raw stream transport
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
import { sendChatUpstream, ChatUpstreamError } from "@302ai/media-studio-core";
|
|
46
|
+
|
|
47
|
+
try {
|
|
48
|
+
const response = await sendChatUpstream({
|
|
49
|
+
apiBaseUrl: "https://api.302.ai",
|
|
50
|
+
apiKey: process.env.API_302_KEY,
|
|
51
|
+
sessionId: "your-stable-session-id",
|
|
52
|
+
messages: [{ role: "user", content: "Draw me a cat" }],
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
for await (const chunk of response.body) {
|
|
56
|
+
// Your own SSE handling. No pipeline is applied for you.
|
|
57
|
+
}
|
|
58
|
+
} catch (error) {
|
|
59
|
+
if (error instanceof ChatUpstreamError) {
|
|
60
|
+
console.error(error.status, error.message);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
## API
|
|
66
|
+
|
|
67
|
+
### `client.sessions`
|
|
68
|
+
|
|
69
|
+
Session management against the Media Studio gateway (`MediaStudioClient.prototype.sessions`).
|
|
70
|
+
|
|
71
|
+
#### `client.sessions.list(query?): Promise<ListSessionsResponse>`
|
|
72
|
+
|
|
73
|
+
Lists sessions stored upstream on the server (the single source of truth).
|
|
74
|
+
|
|
75
|
+
| Query Field | Type | Notes |
|
|
76
|
+
| --- | --- | --- |
|
|
77
|
+
| `limit` | `number` | Optional maximum count of sessions to return. |
|
|
78
|
+
| `offset` | `number` | Optional offset for pagination. |
|
|
79
|
+
| `note` | `string` | Optional substring filter on session notes. |
|
|
80
|
+
|
|
81
|
+
Returns `{ sessions: SessionItem[], total?: number }`. Each `SessionItem` contains `id`, `note`, `source` (`"web"` | `"cli"`), `createdAt`, and `updatedAt`.
|
|
82
|
+
|
|
83
|
+
#### `client.sessions.remove(sessionId): Promise<void>`
|
|
84
|
+
|
|
85
|
+
Deletes a session server-side. Destroys upstream conversation memory irreversibly. Throws `ChatUpstreamError` on HTTP failure.
|
|
86
|
+
|
|
87
|
+
#### `client.sessions.prewarm(options): Promise<SessionPrewarmOutcome>`
|
|
88
|
+
|
|
89
|
+
Provisions a session via the prewarm SSE endpoint (`/api/sessions/prewarm`) — the same preparation flow used by the web app.
|
|
90
|
+
|
|
91
|
+
**Options**:
|
|
92
|
+
|
|
93
|
+
| Field | Type | Notes |
|
|
94
|
+
| --- | --- | --- |
|
|
95
|
+
| `sessionId` | `string` | Client-generated UUID for the session. |
|
|
96
|
+
| `source` | `"web" \| "cli"` | Session creation provenance (`SessionSource`). |
|
|
97
|
+
| `note` | `string` | Optional human-readable note/title. |
|
|
98
|
+
| `installUserSkills` | `boolean` | Whether to install user library skills during prewarm. |
|
|
99
|
+
| `signal` | `AbortSignal` | Request abort signal. |
|
|
100
|
+
| `onStageChange` | `(stage) => void` | Stage progress callback: `"creating"` → `"sandbox"` → `"skills"` → `"finishing"`. |
|
|
101
|
+
| `onSessionReady` | `(session) => void` | Fired once when `session_ready` arrives (upstream commit point). |
|
|
102
|
+
|
|
103
|
+
**Outcome**:
|
|
104
|
+
Returns a discriminated union `SessionPrewarmOutcome`:
|
|
105
|
+
- `{ status: "ready", session: PrewarmSessionReady }` — Full provisioning completed (sandbox + skills ready).
|
|
106
|
+
- `{ status: "fallback", session: PrewarmSessionReady }` — Session persisted upstream, but sandbox/skills provisioning failed or stream ended early; plain-text chat remains usable.
|
|
107
|
+
- `{ status: "failed" }` — Failed before session creation; no session exists upstream.
|
|
108
|
+
|
|
109
|
+
#### Prewarm Commit-Point Invariant (`session_ready`)
|
|
110
|
+
|
|
111
|
+
The `session_ready` event is the upstream commit point:
|
|
112
|
+
- **Before `session_ready`**: The session has not been committed to server storage. If the request fails or is aborted before this event, no session exists upstream; callers must NOT persist or store this `sessionId`.
|
|
113
|
+
- **After `session_ready`**: The session is durably committed upstream. `onSessionReady` fires exactly once. Even if subsequent sandbox or skill stages fail (`status === "fallback"`), callers must KEEP this session ID and continue to chat with plain-text fallback. Calling `prewarm` again with a new ID after `onSessionReady` fired would abandon the previous session and leak orphan sessions on the server.
|
|
114
|
+
|
|
115
|
+
### `sendChatUpstream(request): Promise<Response>`
|
|
116
|
+
|
|
117
|
+
Resolves with the upstream streaming response. Throws `ChatUpstreamError` when the upstream status is not ok.
|
|
118
|
+
|
|
119
|
+
**Required**
|
|
120
|
+
|
|
121
|
+
| Field | Type | Notes |
|
|
122
|
+
| --- | --- | --- |
|
|
123
|
+
| `apiBaseUrl` | `string` | API origin. Trailing slash tolerated. |
|
|
124
|
+
| `apiKey` | `string` | Sent as a bearer token. |
|
|
125
|
+
| `sessionId` | `string` | Stable client session id. |
|
|
126
|
+
| `messages` | `ChatUpstreamMessage[]` | OpenAI-format messages. |
|
|
127
|
+
|
|
128
|
+
**Optional**
|
|
129
|
+
|
|
130
|
+
| Field | Type | Notes |
|
|
131
|
+
| --- | --- | --- |
|
|
132
|
+
| `locale` | `string` | Forwarded so upstream can localize error text. |
|
|
133
|
+
| `modelParams` | `string \| Record<string, unknown>` | Objects are JSON-serialized. |
|
|
134
|
+
| `skillUrls` | `string[]` | Skill packages to load for this turn. |
|
|
135
|
+
| `chatTaskId` | `string` | Switches upstream into poll/resume mode. |
|
|
136
|
+
| `sinceSeq` | `number` | Incremental cursor; only meaningful with `chatTaskId`. |
|
|
137
|
+
| `structuredOutput` | `boolean` | Defaults to `false` (AI SDK event stream). Set `true` for raw claude-code stream-json. |
|
|
138
|
+
| `signal` | `AbortSignal` | Ties upstream request lifetime to your connection. |
|
|
139
|
+
|
|
140
|
+
Streaming is always on and the endpoint path is fixed, so neither is caller-controllable.
|
|
141
|
+
|
|
142
|
+
### `ChatUpstreamError`
|
|
143
|
+
|
|
144
|
+
Extends `Error` with `status` (the upstream HTTP status) and `body` (the raw response text). Its `message` is the human-readable upstream text.
|
|
145
|
+
|
|
146
|
+
### `extractUpstreamErrorMessage(body): string | null`
|
|
147
|
+
|
|
148
|
+
Pulls a readable message out of an upstream error body, checking in order: `error.message_cn`, `error.message`, `message_cn`, `message`, `error`.
|
|
149
|
+
|
|
150
|
+
## Development & Testing
|
|
151
|
+
|
|
152
|
+
### In-repo iteration
|
|
153
|
+
|
|
154
|
+
The app and vitest alias `@302ai/media-studio-core` to `src/index.ts`
|
|
155
|
+
(tsconfig `paths` + `vitest.config.ts`), so **no build step is needed** while
|
|
156
|
+
developing — edits are picked up directly. Unit tests are co-located
|
|
157
|
+
(`*.test.ts` next to source) and run from the repo root:
|
|
158
|
+
|
|
159
|
+
```bash
|
|
160
|
+
bun run test # full suite (vitest resolves core to src)
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
### Build
|
|
164
|
+
|
|
165
|
+
```bash
|
|
166
|
+
bun run package:build # tsc -> dist/ + fix-dist.ts (.js specifier repair)
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
`exports` points at `dist/` unconditionally — the published artifact and the
|
|
170
|
+
in-repo source are two different files.
|
|
171
|
+
|
|
172
|
+
### Publishing gates (required before every publish)
|
|
173
|
+
|
|
174
|
+
```bash
|
|
175
|
+
bun run package:check # = build + publint + attw + smoke, chained
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
| Script | What it catches |
|
|
179
|
+
| --- | --- |
|
|
180
|
+
| `package:build` | Compile errors; emits ESM + `.d.ts` |
|
|
181
|
+
| `package:lint` | `publint` manifest/packaging defects |
|
|
182
|
+
| `package:types` | `attw --profile esm-only` type-resolution defects |
|
|
183
|
+
| `package:smoke` | The only check that runs the **published artifact** |
|
|
184
|
+
|
|
185
|
+
**Why the smoke test matters:** because local tooling aliases to `src`, the
|
|
186
|
+
app NEVER executes `dist` — every in-repo gate can pass while `dist` is
|
|
187
|
+
broken. `package:smoke` packs the real tarball, installs it outside the repo,
|
|
188
|
+
imports it under real Node ESM, and type-checks the shipped `.d.ts` under
|
|
189
|
+
`nodenext`. It has already caught two real defects (extensionless relative
|
|
190
|
+
specifiers; a `publishConfig.exports` map only pnpm honours). See
|
|
191
|
+
`docs/adr/0004-chat-upstream-client-package.md`.
|
|
192
|
+
|
|
193
|
+
Run `package:check` whenever you touch `packages/**`, `bunfig.toml`,
|
|
194
|
+
`bun.lock`, `tsconfig.json`, or the root manifest — and always before a
|
|
195
|
+
publish.
|
|
196
|
+
|
|
197
|
+
### Notes learned the hard way
|
|
198
|
+
|
|
199
|
+
- `bun pm pack` does NOT run publish lifecycle scripts; the smoke script
|
|
200
|
+
builds explicitly first. Don't assume pack produces a fresh dist.
|
|
201
|
+
- Publishing is manual by design (`bun publish --dry-run` first; version
|
|
202
|
+
numbers are burned by hand and never reused).
|
|
203
|
+
- `attw` node10-resolution failure and the CJS warning are intrinsic to an
|
|
204
|
+
ESM-only package — the `esm-only` profile records that intent, don't
|
|
205
|
+
"fix" them with a CJS build.
|
|
206
|
+
|
|
207
|
+
## Notes
|
|
208
|
+
|
|
209
|
+
No logging, no retries, no AI SDK dependency. Observability and retry policy are the caller's to own.
|
|
210
|
+
|
|
211
|
+
## License
|
|
212
|
+
|
|
213
|
+
Apache-2.0. Copyright 2026 302.AI. See [LICENSE](./LICENSE).
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type MeResponse } from "./types.js";
|
|
2
|
+
export declare class ClientAuth {
|
|
3
|
+
private readonly baseUrl;
|
|
4
|
+
private readonly apiKey;
|
|
5
|
+
private readonly customFetch;
|
|
6
|
+
constructor(baseUrl: string, apiKey: string, customFetch?: typeof fetch);
|
|
7
|
+
/**
|
|
8
|
+
* Fetches current authentication status and user details from /api/auth/me.
|
|
9
|
+
*
|
|
10
|
+
* @throws {ChatUpstreamError} on HTTP failure or invalid token (401).
|
|
11
|
+
*/
|
|
12
|
+
getMe(): Promise<MeResponse>;
|
|
13
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { ChatUpstreamError, extractUpstreamErrorMessage, } from "../transport/errors.js";
|
|
2
|
+
import { MeResponseSchema } from "./types.js";
|
|
3
|
+
export class ClientAuth {
|
|
4
|
+
baseUrl;
|
|
5
|
+
apiKey;
|
|
6
|
+
customFetch;
|
|
7
|
+
constructor(baseUrl, apiKey, customFetch) {
|
|
8
|
+
this.baseUrl = baseUrl;
|
|
9
|
+
this.apiKey = apiKey;
|
|
10
|
+
this.customFetch = customFetch ?? fetch;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Fetches current authentication status and user details from /api/auth/me.
|
|
14
|
+
*
|
|
15
|
+
* @throws {ChatUpstreamError} on HTTP failure or invalid token (401).
|
|
16
|
+
*/
|
|
17
|
+
async getMe() {
|
|
18
|
+
const url = `${this.baseUrl}/api/auth/me`;
|
|
19
|
+
const response = await this.customFetch(url, {
|
|
20
|
+
method: "GET",
|
|
21
|
+
headers: {
|
|
22
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
23
|
+
},
|
|
24
|
+
});
|
|
25
|
+
if (!response.ok) {
|
|
26
|
+
const rawBody = await response.text();
|
|
27
|
+
const message = extractUpstreamErrorMessage(rawBody) ||
|
|
28
|
+
`Authentication verification failed with status ${response.status}`;
|
|
29
|
+
throw new ChatUpstreamError(message, response.status, rawBody);
|
|
30
|
+
}
|
|
31
|
+
const rawJson = await response.json();
|
|
32
|
+
return MeResponseSchema.parse(rawJson);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { ChatStream } from "../stream/stream.js";
|
|
2
|
+
import type { ChatTurnOptions, QuickPromptOptions } from "./types.js";
|
|
3
|
+
export declare class ClientChat {
|
|
4
|
+
private readonly baseUrl;
|
|
5
|
+
private readonly apiKey;
|
|
6
|
+
private readonly defaultLocale?;
|
|
7
|
+
private readonly customFetch;
|
|
8
|
+
constructor(baseUrl: string, apiKey: string, defaultLocale?: string, customFetch?: typeof fetch);
|
|
9
|
+
private executeTurn;
|
|
10
|
+
raw(prompt: string, options: QuickPromptOptions): Promise<Response>;
|
|
11
|
+
raw(options: ChatTurnOptions): Promise<Response>;
|
|
12
|
+
stream(prompt: string, options: QuickPromptOptions): Promise<ChatStream>;
|
|
13
|
+
stream(options: ChatTurnOptions): Promise<ChatStream>;
|
|
14
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
import { isNotNil, isString } from "es-toolkit/predicate";
|
|
2
|
+
import { ChatStream } from "../stream/stream.js";
|
|
3
|
+
export class ClientChat {
|
|
4
|
+
baseUrl;
|
|
5
|
+
apiKey;
|
|
6
|
+
defaultLocale;
|
|
7
|
+
customFetch;
|
|
8
|
+
constructor(baseUrl, apiKey, defaultLocale, customFetch) {
|
|
9
|
+
this.baseUrl = baseUrl;
|
|
10
|
+
this.apiKey = apiKey;
|
|
11
|
+
this.defaultLocale = defaultLocale;
|
|
12
|
+
this.customFetch = customFetch ?? fetch;
|
|
13
|
+
}
|
|
14
|
+
executeTurn(options) {
|
|
15
|
+
const base = this.baseUrl;
|
|
16
|
+
const url = `${base}/api/chat/claude-sse`;
|
|
17
|
+
const headers = {
|
|
18
|
+
"Content-Type": "application/json",
|
|
19
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
20
|
+
"X-User-Session-Id": options.sessionId,
|
|
21
|
+
};
|
|
22
|
+
if (this.defaultLocale) {
|
|
23
|
+
headers["X-UI-Locale"] = this.defaultLocale;
|
|
24
|
+
}
|
|
25
|
+
const body = {
|
|
26
|
+
session_id: options.sessionId,
|
|
27
|
+
messages: options.messages,
|
|
28
|
+
...(options.chatTaskId ? { chat_task_id: options.chatTaskId } : {}),
|
|
29
|
+
...(isNotNil(options.sinceSeq) ? { since_seq: options.sinceSeq } : {}),
|
|
30
|
+
...(isNotNil(options.modelParams)
|
|
31
|
+
? { model_params: options.modelParams }
|
|
32
|
+
: {}),
|
|
33
|
+
...(isNotNil(options.skillUrls) ? { skill_urls: options.skillUrls } : {}),
|
|
34
|
+
...(isNotNil(options.structuredOutput)
|
|
35
|
+
? { structured_output: options.structuredOutput }
|
|
36
|
+
: {}),
|
|
37
|
+
};
|
|
38
|
+
// If single user turn with string content, also set prompt for gateway convenience
|
|
39
|
+
if (options.messages.length === 1 &&
|
|
40
|
+
options.messages[0].role === "user" &&
|
|
41
|
+
isString(options.messages[0].content)) {
|
|
42
|
+
body.prompt = options.messages[0].content;
|
|
43
|
+
}
|
|
44
|
+
return this.customFetch(url, {
|
|
45
|
+
method: "POST",
|
|
46
|
+
headers,
|
|
47
|
+
body: JSON.stringify(body),
|
|
48
|
+
signal: options.signal,
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
async raw(promptOrOptions, maybeOptions) {
|
|
52
|
+
if (isString(promptOrOptions)) {
|
|
53
|
+
if (!maybeOptions) {
|
|
54
|
+
throw new Error("QuickPromptOptions including sessionId is required");
|
|
55
|
+
}
|
|
56
|
+
return this.executeTurn({
|
|
57
|
+
sessionId: maybeOptions.sessionId,
|
|
58
|
+
messages: [{ role: "user", content: promptOrOptions }],
|
|
59
|
+
chatTaskId: maybeOptions.chatTaskId,
|
|
60
|
+
signal: maybeOptions.signal,
|
|
61
|
+
maxRetries: maybeOptions.maxRetries,
|
|
62
|
+
initialRetryDelayMs: maybeOptions.initialRetryDelayMs,
|
|
63
|
+
onFinalResponse: maybeOptions.onFinalResponse,
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
return this.executeTurn(promptOrOptions);
|
|
67
|
+
}
|
|
68
|
+
async stream(promptOrOptions, maybeOptions) {
|
|
69
|
+
if (isString(promptOrOptions)) {
|
|
70
|
+
if (!maybeOptions) {
|
|
71
|
+
throw new Error("QuickPromptOptions including sessionId is required");
|
|
72
|
+
}
|
|
73
|
+
return new ChatStream(() => this.raw(promptOrOptions, maybeOptions), {
|
|
74
|
+
maxRetries: maybeOptions.maxRetries,
|
|
75
|
+
initialRetryDelayMs: maybeOptions.initialRetryDelayMs,
|
|
76
|
+
signal: maybeOptions.signal,
|
|
77
|
+
onFinalResponse: maybeOptions.onFinalResponse,
|
|
78
|
+
onError: maybeOptions.onError,
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
return new ChatStream(() => this.raw(promptOrOptions), {
|
|
82
|
+
maxRetries: promptOrOptions.maxRetries,
|
|
83
|
+
initialRetryDelayMs: promptOrOptions.initialRetryDelayMs,
|
|
84
|
+
signal: promptOrOptions.signal,
|
|
85
|
+
onFinalResponse: promptOrOptions.onFinalResponse,
|
|
86
|
+
onError: promptOrOptions.onError,
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { ClientAuth } from "./auth.js";
|
|
2
|
+
import { ClientChat } from "./chat.js";
|
|
3
|
+
import { ChatSession } from "./session.js";
|
|
4
|
+
import { ClientSessions } from "./sessions.js";
|
|
5
|
+
import type { ChatSessionOptions, MediaStudioClientOptions } from "./types.js";
|
|
6
|
+
export declare class MediaStudioClient {
|
|
7
|
+
readonly baseUrl: string;
|
|
8
|
+
readonly apiKey: string;
|
|
9
|
+
readonly locale?: string;
|
|
10
|
+
readonly auth: ClientAuth;
|
|
11
|
+
readonly chat: ClientChat;
|
|
12
|
+
readonly sessions: ClientSessions;
|
|
13
|
+
constructor(options: MediaStudioClientOptions);
|
|
14
|
+
/**
|
|
15
|
+
* Creates a multi-turn conversation session that maintains `sessionId`
|
|
16
|
+
* and conversation history across turns.
|
|
17
|
+
*/
|
|
18
|
+
createSession(options?: ChatSessionOptions): ChatSession;
|
|
19
|
+
}
|
|
20
|
+
export declare function createMediaStudioClient(options: MediaStudioClientOptions): MediaStudioClient;
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { ClientAuth } from "./auth.js";
|
|
2
|
+
import { ClientChat } from "./chat.js";
|
|
3
|
+
import { ChatSession } from "./session.js";
|
|
4
|
+
import { ClientSessions } from "./sessions.js";
|
|
5
|
+
export class MediaStudioClient {
|
|
6
|
+
baseUrl;
|
|
7
|
+
apiKey;
|
|
8
|
+
locale;
|
|
9
|
+
auth;
|
|
10
|
+
chat;
|
|
11
|
+
sessions;
|
|
12
|
+
constructor(options) {
|
|
13
|
+
const trimmedKey = options.apiKey.trim();
|
|
14
|
+
if (!trimmedKey) {
|
|
15
|
+
throw new Error("apiKey is required and cannot be empty");
|
|
16
|
+
}
|
|
17
|
+
this.apiKey = trimmedKey;
|
|
18
|
+
this.baseUrl = (options.baseUrl ?? "https://media.302.ai").replace(/\/+$/, "");
|
|
19
|
+
this.locale = options.locale;
|
|
20
|
+
this.auth = new ClientAuth(this.baseUrl, this.apiKey, options.fetch);
|
|
21
|
+
this.chat = new ClientChat(this.baseUrl, this.apiKey, this.locale, options.fetch);
|
|
22
|
+
this.sessions = new ClientSessions(this.baseUrl, this.apiKey, options.fetch);
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Creates a multi-turn conversation session that maintains `sessionId`
|
|
26
|
+
* and conversation history across turns.
|
|
27
|
+
*/
|
|
28
|
+
createSession(options) {
|
|
29
|
+
return new ChatSession(this.chat, options);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
export function createMediaStudioClient(options) {
|
|
33
|
+
return new MediaStudioClient(options);
|
|
34
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { ChatStream } from "../stream/stream.js";
|
|
2
|
+
import type { ChatUpstreamMessage } from "../transport/types.js";
|
|
3
|
+
import type { ClientChat } from "./chat.js";
|
|
4
|
+
import type { ChatSessionOptions, QuickPromptOptions } from "./types.js";
|
|
5
|
+
export declare class ChatSession {
|
|
6
|
+
readonly sessionId: string;
|
|
7
|
+
private readonly chat;
|
|
8
|
+
private messages;
|
|
9
|
+
private isTurnActive;
|
|
10
|
+
constructor(chat: ClientChat, options?: ChatSessionOptions);
|
|
11
|
+
/**
|
|
12
|
+
* Whether a message turn is currently in-flight.
|
|
13
|
+
*/
|
|
14
|
+
get isBusy(): boolean;
|
|
15
|
+
/**
|
|
16
|
+
* Returns a copy of the current in-memory conversation history.
|
|
17
|
+
*/
|
|
18
|
+
getMessages(): ChatUpstreamMessage[];
|
|
19
|
+
/**
|
|
20
|
+
* Clears accumulated turn history while preserving the session ID.
|
|
21
|
+
*/
|
|
22
|
+
clearHistory(): void;
|
|
23
|
+
/**
|
|
24
|
+
* Sends a user turn within this session.
|
|
25
|
+
*
|
|
26
|
+
* Automatically appends the user message to history, dispatches the full
|
|
27
|
+
* history to the model, and asynchronously appends the assistant's reply
|
|
28
|
+
* to history once the stream completes.
|
|
29
|
+
*
|
|
30
|
+
* Throws an error if another turn is already active on this session.
|
|
31
|
+
*/
|
|
32
|
+
sendMessage(prompt: string, options?: Omit<QuickPromptOptions, "sessionId">): Promise<ChatStream>;
|
|
33
|
+
}
|