orchid-sdk 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.
package/LICENSE ADDED
@@ -0,0 +1,176 @@
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
53
+ of 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 LICENSE 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
package/README.md ADDED
@@ -0,0 +1,150 @@
1
+ # Orchid TypeScript SDK
2
+
3
+ The Orchid TypeScript SDK is a lightweight, thin SDK designed to work seamlessly with Orchid - [the Orchestration Interactive Debugger](https://orchidtrace.xyz).
4
+
5
+ It automatically intercepts outgoing LLM and external API requests (e.g., OpenAI, Anthropic, Gemini, Vertex AI, SerpAPI, etc.) and routes them through the local Orchid Proxy. This enables full request capturing, visualization, interactive debugging, and mock replay capabilities in unit tests or local development environments.
6
+
7
+ **Requires Node.js 18+** (native `fetch` and `AsyncLocalStorage`).
8
+
9
+ ---
10
+
11
+ ## Installation
12
+
13
+ ```bash
14
+ npm install orchid-sdk
15
+ ```
16
+
17
+ ---
18
+
19
+ ## Quickstart
20
+
21
+ ### 1. Initialization
22
+
23
+ Call `await init()` at the entry point of your application (before instantiating any LLM clients).
24
+
25
+ ```ts
26
+ import { init } from "orchid-sdk";
27
+
28
+ // Initialize the Orchid environment and patch the global fetch
29
+ await init();
30
+
31
+ // Now, standard client libraries will automatically route through the Orchid proxy!
32
+ import OpenAI from "openai";
33
+ const client = new OpenAI();
34
+ ```
35
+
36
+ ### 2. Session Contexts
37
+
38
+ Use `session()` to group API exchanges under a specific session ID and mode. Context propagates safely across async boundaries via `AsyncLocalStorage`.
39
+
40
+ ```ts
41
+ import { init, session } from "orchid-sdk";
42
+
43
+ await init();
44
+
45
+ // Intercept and capture requests in this block under a custom session name
46
+ await session("user-onboarding-flow", "capture", async () => {
47
+ // Outgoing LLM calls here will be captured under session ID 'user-onboarding-flow'
48
+ const response = await client.chat.completions.create({
49
+ model: "gpt-5.2",
50
+ messages: [{ role: "user", content: "Hello!" }],
51
+ });
52
+ });
53
+ ```
54
+
55
+ Supported modes are:
56
+ * `"capture"`: Intercepts and records all outgoing requests.
57
+ * `"replay"`: Intercepts requests and serves mocked responses from previously recorded exchanges.
58
+ * `"passthrough"`: Bypasses the proxy database logging (requests still pass through but are not recorded/mocked).
59
+
60
+ ### Explicit fetch wrapper (no global patching)
61
+
62
+ If you prefer not to patch `globalThis.fetch`, pass `orchidFetch` directly to clients that accept a custom fetch implementation:
63
+
64
+ ```ts
65
+ import { orchidFetch } from "orchid-sdk";
66
+ import OpenAI from "openai";
67
+
68
+ const client = new OpenAI({ fetch: orchidFetch });
69
+ ```
70
+
71
+ ---
72
+
73
+ ## Capture & Replay Test Helper (`withReplay`)
74
+
75
+ `withReplay()` automates capturing and replaying HTTP exchanges. It is framework-agnostic and works in vitest, jest, or `node:test`, ensuring test suites are deterministic and do not make expensive, slow, or volatile external network calls.
76
+
77
+ ```ts
78
+ import { withReplay } from "orchid-sdk";
79
+
80
+ test("user greeting", () =>
81
+ withReplay("tests/fixtures/test_user_greeting.json", async () => {
82
+ // If ORCHID_RECORD=1: executes the API call and saves results to the JSON fixture file.
83
+ // If ORCHID_RECORD=0 or unset: mocks the API call using the contents of the fixture file.
84
+ const response = await client.chat.completions.create({
85
+ model: "gpt-5.2",
86
+ messages: [{ role: "user", content: "Say hello!" }],
87
+ });
88
+ expect(response.choices[0].message.content.toLowerCase()).toContain("hello");
89
+ }));
90
+ ```
91
+
92
+ ---
93
+
94
+ ## Orchid Control Client
95
+
96
+ For programmatic control over recorded fixtures, use `OrchidControlClient` to check health, export, or import fixtures.
97
+
98
+ ```ts
99
+ import { OrchidControlClient } from "orchid-sdk";
100
+
101
+ // Create the client pointing to the control port (default: 4321)
102
+ const controlClient = new OrchidControlClient();
103
+
104
+ // Check if the query service is active
105
+ if (await controlClient.checkHealth()) {
106
+ // Export a recorded session to a local JSON file
107
+ await controlClient.exportFixture("my-session-123", "fixtures/session_data.json");
108
+
109
+ // Import a local JSON fixture database back into the proxy
110
+ await controlClient.importFixture("fixtures/session_data.json");
111
+ }
112
+ ```
113
+
114
+ ---
115
+
116
+ ## Configuration (Environment Variables)
117
+
118
+ | Variable | Default | Description |
119
+ | :--- | :--- | :--- |
120
+ | `ORCHID_PROXY_URL` | `http://127.0.0.1:4320/v1` | The Orchid Proxy intercept endpoint. |
121
+ | `ORCHID_QUERY_URL` | derived (`:4321`) | The Query & Control API endpoint. |
122
+ | `ORCHID_PROXY_KEY` | — | Auth key sent as `X-Orchid-Proxy-Key`. |
123
+ | `ORCHID_API_KEY` | — | Control plane API key (`X-Orchid-Api-Key`). |
124
+ | `ORCHID_SESSION_ID` / `ORCHID_MODE` | — | Global session/mode fallback when no `session()` scope is active. |
125
+ | `ORCHID_CAPTURE_DOMAINS` | — | Comma-separated extra domains to intercept, or `*` for all. |
126
+ | `ORCHID_IGNORE_DOMAINS` | — | Comma-separated domains to never intercept. |
127
+ | `ORCHID_RECORD` | — | Set to `1` to run `withReplay` blocks in record mode. |
128
+ | `ORCHID_BYPASS_HEALTHCHECK` | — | Set to `True` to skip the init health check. |
129
+
130
+ ---
131
+
132
+ ## How It Works (Auto-Instrumentation)
133
+
134
+ When you call `init()`, the SDK patches `globalThis.fetch` (Node's native undici-backed fetch). This automatically intercepts libraries like `openai` and `@anthropic-ai/sdk`, which use the global fetch as their underlying HTTP transport. Requests to core LLM providers (and any `ORCHID_CAPTURE_DOMAINS`) are rewritten to the proxy with `X-Orchid-*` control headers attached; localhost traffic is never intercepted.
135
+
136
+ ### Fail-Soft Fallback
137
+
138
+ The SDK is built to be resilient. During initialization, the SDK performs a fast health check on the Orchid Query service.
139
+ * If the proxy or control service is **offline**, the SDK silently falls back to direct routing. The global fetch is not patched, and environment base URLs are not modified.
140
+ * If the patch is active but the proxy goes offline mid-session, the wrapper catches connection failures, logs a warning, case-insensitively purges internal Orchid headers (preventing key leakage), and seamlessly retries the request directly to the upstream public API.
141
+
142
+ ---
143
+
144
+ ## Development
145
+
146
+ ```bash
147
+ npm install
148
+ npm test # vitest
149
+ npm run build # tsup -> dist/ (esm + cjs + d.ts)
150
+ ```
package/dist/index.cjs ADDED
@@ -0,0 +1,346 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ OrchidControlClient: () => OrchidControlClient,
24
+ currentMode: () => currentMode,
25
+ currentSessionId: () => currentSessionId,
26
+ init: () => init,
27
+ orchidFetch: () => orchidFetch,
28
+ session: () => session,
29
+ uninstall: () => uninstall,
30
+ withReplay: () => withReplay
31
+ });
32
+ module.exports = __toCommonJS(index_exports);
33
+
34
+ // src/context.ts
35
+ var import_node_async_hooks = require("async_hooks");
36
+ var storage = new import_node_async_hooks.AsyncLocalStorage();
37
+ function currentSessionId() {
38
+ return storage.getStore()?.sessionId ?? process.env.ORCHID_SESSION_ID ?? void 0;
39
+ }
40
+ function currentMode() {
41
+ return storage.getStore()?.mode ?? process.env.ORCHID_MODE ?? void 0;
42
+ }
43
+ function session(sessionId, mode, fn) {
44
+ return storage.run({ sessionId, mode }, fn);
45
+ }
46
+
47
+ // src/core.ts
48
+ var CORE_PROVIDERS = [
49
+ "api.openai.com",
50
+ "api.anthropic.com",
51
+ "generativelanguage.googleapis.com",
52
+ "aiplatform.googleapis.com"
53
+ ];
54
+ var LOCAL_HOSTS = ["localhost", "127.0.0.1", "::1", "[::1]"];
55
+ var patched = false;
56
+ var offlineFallback = false;
57
+ var originalFetch;
58
+ function proxyUrl() {
59
+ return process.env.ORCHID_PROXY_URL ?? "http://127.0.0.1:4320/v1";
60
+ }
61
+ function envList(name) {
62
+ return (process.env[name] ?? "").split(",").map((s) => s.trim()).filter((s) => s.length > 0);
63
+ }
64
+ function isCoreProvider(host) {
65
+ return CORE_PROVIDERS.some((c) => host.includes(c));
66
+ }
67
+ function shouldIntercept(url) {
68
+ if (offlineFallback) return false;
69
+ const host = url.hostname;
70
+ if (LOCAL_HOSTS.some((h) => host === h)) return false;
71
+ if (envList("ORCHID_IGNORE_DOMAINS").some((d) => host.includes(d))) {
72
+ return false;
73
+ }
74
+ if (isCoreProvider(host)) return true;
75
+ const capture = envList("ORCHID_CAPTURE_DOMAINS");
76
+ if (capture.includes("*")) return true;
77
+ if (capture.some((d) => host.includes(d))) return true;
78
+ return false;
79
+ }
80
+ function rewriteUrl(originalUrl) {
81
+ const proxy = new URL(proxyUrl());
82
+ const rewritten = new URL(originalUrl.toString());
83
+ rewritten.protocol = proxy.protocol;
84
+ rewritten.host = proxy.host;
85
+ if (isCoreProvider(originalUrl.hostname)) {
86
+ const proxyBasePath = proxy.pathname.replace(/\/+$/, "");
87
+ if (proxyBasePath && !originalUrl.pathname.startsWith(proxyBasePath)) {
88
+ rewritten.pathname = proxyBasePath + originalUrl.pathname;
89
+ }
90
+ }
91
+ return rewritten;
92
+ }
93
+ function injectHeaders(headers, targetUrl, originalUrl) {
94
+ const proxy = new URL(proxyUrl());
95
+ if (targetUrl.host !== proxy.host) return;
96
+ const proxyKey = process.env.ORCHID_PROXY_KEY;
97
+ if (proxyKey) headers.set("X-Orchid-Proxy-Key", proxyKey);
98
+ const sessionId = currentSessionId();
99
+ let mode = currentMode();
100
+ if (sessionId) {
101
+ headers.set("X-Orchid-Session-Id", sessionId);
102
+ if (!mode) mode = "capture";
103
+ }
104
+ if (mode) headers.set("X-Orchid-Mode", mode);
105
+ if (originalUrl && originalUrl.host !== proxy.host) {
106
+ headers.set(
107
+ "X-Orchid-Target-Url",
108
+ `${originalUrl.protocol}//${originalUrl.host}`
109
+ );
110
+ }
111
+ }
112
+ function purgeOrchidHeaders(headers) {
113
+ const toDelete = [];
114
+ headers.forEach((_value, key) => {
115
+ if (key.toLowerCase().startsWith("x-orchid-")) toDelete.push(key);
116
+ });
117
+ for (const key of toDelete) headers.delete(key);
118
+ }
119
+ function isConnectionError(err) {
120
+ if (!(err instanceof Error)) return false;
121
+ const cause = err.cause;
122
+ const code = cause?.code ?? err.code;
123
+ return code === "ECONNREFUSED" || code === "ECONNRESET" || code === "EHOSTUNREACH" || code === "ENOTFOUND" || code === "ETIMEDOUT" || code === "UND_ERR_CONNECT_TIMEOUT" || code === "UND_ERR_SOCKET";
124
+ }
125
+ var orchidFetch = async (input, init2) => {
126
+ const baseFetch = originalFetch ?? globalThis.fetch;
127
+ const request = new Request(input, init2);
128
+ const original = new URL(request.url);
129
+ if (!shouldIntercept(original)) {
130
+ const headers2 = new Headers(request.headers);
131
+ injectHeaders(headers2, original);
132
+ return baseFetch(new Request(request, { headers: headers2 }));
133
+ }
134
+ const rewritten = rewriteUrl(original);
135
+ const headers = new Headers(request.headers);
136
+ injectHeaders(headers, rewritten, original);
137
+ const proxied = new Request(rewritten, {
138
+ method: request.method,
139
+ headers,
140
+ body: request.body,
141
+ // Required by undici when streaming a body
142
+ ...request.body ? { duplex: "half" } : {},
143
+ redirect: request.redirect,
144
+ signal: request.signal
145
+ });
146
+ try {
147
+ return await baseFetch(proxied);
148
+ } catch (err) {
149
+ if (!isConnectionError(err)) throw err;
150
+ console.warn(
151
+ `[orchid] Proxy connection failed (${String(err)}). Falling back to direct routing: ${original}`
152
+ );
153
+ const fallbackHeaders = new Headers(request.headers);
154
+ purgeOrchidHeaders(fallbackHeaders);
155
+ return baseFetch(
156
+ new Request(original, {
157
+ method: request.method,
158
+ headers: fallbackHeaders,
159
+ body: request.body,
160
+ ...request.body ? { duplex: "half" } : {},
161
+ redirect: request.redirect,
162
+ signal: request.signal
163
+ })
164
+ );
165
+ }
166
+ };
167
+ function deriveQueryUrl() {
168
+ const explicit = process.env.ORCHID_QUERY_URL;
169
+ if (explicit) return explicit;
170
+ const proxy = new URL(proxyUrl());
171
+ if (proxy.port === "4320") proxy.port = "4321";
172
+ proxy.pathname = "";
173
+ return proxy.toString().replace(/\/+$/, "");
174
+ }
175
+ async function proxyIsHealthy() {
176
+ const baseFetch = originalFetch ?? globalThis.fetch;
177
+ try {
178
+ const resp = await baseFetch(`${deriveQueryUrl()}/health`, {
179
+ signal: AbortSignal.timeout(1e3)
180
+ });
181
+ return resp.status === 200;
182
+ } catch {
183
+ return false;
184
+ }
185
+ }
186
+ async function init(options = {}) {
187
+ offlineFallback = false;
188
+ const proxy = proxyUrl();
189
+ let parsed;
190
+ try {
191
+ parsed = new URL(proxy);
192
+ } catch {
193
+ throw new Error(`Malformed ORCHID_PROXY_URL: ${proxy}`);
194
+ }
195
+ if (!parsed.protocol || !parsed.host) {
196
+ throw new Error(`Malformed ORCHID_PROXY_URL: ${proxy}`);
197
+ }
198
+ const bypass = options.bypassHealthCheck === true || process.env.ORCHID_BYPASS_HEALTHCHECK === "True" || process.env.VITEST !== void 0;
199
+ if (!bypass) {
200
+ offlineFallback = !await proxyIsHealthy();
201
+ }
202
+ if (!offlineFallback) {
203
+ process.env.OPENAI_BASE_URL = proxy;
204
+ }
205
+ if (!patched && !offlineFallback) {
206
+ originalFetch = globalThis.fetch;
207
+ globalThis.fetch = orchidFetch;
208
+ patched = true;
209
+ }
210
+ }
211
+ function uninstall() {
212
+ if (patched && originalFetch) {
213
+ globalThis.fetch = originalFetch;
214
+ originalFetch = void 0;
215
+ patched = false;
216
+ }
217
+ offlineFallback = false;
218
+ }
219
+
220
+ // src/client.ts
221
+ var import_promises = require("fs/promises");
222
+ var import_node_path = require("path");
223
+ var OrchidControlClient = class {
224
+ queryUrl;
225
+ apiKey;
226
+ /**
227
+ * @param queryUrl URL of the Orchid Query service (default: http://127.0.0.1:4321).
228
+ * @param apiKey API key for authenticating with the control plane.
229
+ */
230
+ constructor(queryUrl, apiKey) {
231
+ this.queryUrl = queryUrl ?? process.env.ORCHID_QUERY_URL ?? "http://127.0.0.1:4321";
232
+ this.apiKey = apiKey ?? process.env.ORCHID_API_KEY ?? void 0;
233
+ }
234
+ headers() {
235
+ return this.apiKey ? { "X-Orchid-Api-Key": this.apiKey } : {};
236
+ }
237
+ /** Checks the health of the Orchid Query service. */
238
+ async checkHealth() {
239
+ try {
240
+ const resp = await fetch(`${this.queryUrl}/health`, {
241
+ headers: this.headers(),
242
+ signal: AbortSignal.timeout(5e3)
243
+ });
244
+ return resp.status === 200;
245
+ } catch (err) {
246
+ console.warn(`[orchid] Query service health check failed: ${String(err)}`);
247
+ return false;
248
+ }
249
+ }
250
+ /**
251
+ * Exports all captured exchanges for a session from the proxy and saves
252
+ * them to a local JSON fixture file.
253
+ */
254
+ async exportFixture(sessionId, path) {
255
+ try {
256
+ const resp = await fetch(
257
+ `${this.queryUrl}/v1/sessions/${encodeURIComponent(sessionId)}/export`,
258
+ { headers: this.headers() }
259
+ );
260
+ if (resp.status === 404) {
261
+ console.warn(`[orchid] Session ${sessionId} not found to export.`);
262
+ return false;
263
+ }
264
+ if (!resp.ok) {
265
+ throw new Error(`Export failed with status ${resp.status}`);
266
+ }
267
+ const fixture = await resp.json();
268
+ await (0, import_promises.mkdir)((0, import_node_path.dirname)(path), { recursive: true });
269
+ await (0, import_promises.writeFile)(path, JSON.stringify(fixture, null, 2));
270
+ return true;
271
+ } catch (err) {
272
+ console.warn(
273
+ `[orchid] Failed to export fixture for session ${sessionId} to ${path}: ${String(err)}`
274
+ );
275
+ return false;
276
+ }
277
+ }
278
+ /**
279
+ * Reads a local JSON fixture file and imports its exchanges into the
280
+ * Orchid Proxy database.
281
+ *
282
+ * @throws If the fixture file does not exist or the import request fails.
283
+ */
284
+ async importFixture(path) {
285
+ const raw = await (0, import_promises.readFile)(path, "utf-8");
286
+ const fixture = JSON.parse(raw);
287
+ const resp = await fetch(`${this.queryUrl}/v1/sessions/import`, {
288
+ method: "POST",
289
+ headers: { "Content-Type": "application/json", ...this.headers() },
290
+ body: JSON.stringify(fixture)
291
+ });
292
+ if (!resp.ok) {
293
+ throw new Error(`Import failed with status ${resp.status}`);
294
+ }
295
+ return resp.status === 201;
296
+ }
297
+ };
298
+
299
+ // src/replay.ts
300
+ var import_promises2 = require("fs/promises");
301
+ var import_node_fs = require("fs");
302
+ var import_node_path2 = require("path");
303
+ function recordMode() {
304
+ return ["1", "true", "yes"].includes(
305
+ (process.env.ORCHID_RECORD ?? "").toLowerCase()
306
+ );
307
+ }
308
+ async function fixtureSessionId(path) {
309
+ if (!(0, import_node_fs.existsSync)(path)) return void 0;
310
+ try {
311
+ const data = JSON.parse(await (0, import_promises2.readFile)(path, "utf-8"));
312
+ return data?.session?.id ?? void 0;
313
+ } catch {
314
+ return void 0;
315
+ }
316
+ }
317
+ function sleep(ms) {
318
+ return new Promise((resolve) => setTimeout(resolve, ms));
319
+ }
320
+ async function withReplay(fixturePath, fn, options = {}) {
321
+ const client = new OrchidControlClient();
322
+ const sessionId = options.sessionId ?? await fixtureSessionId(fixturePath) ?? (0, import_node_path2.basename)(fixturePath, (0, import_node_path2.extname)(fixturePath));
323
+ if (recordMode()) {
324
+ const result = await session(sessionId, "capture", fn);
325
+ const flushSleep = Number(process.env.ORCHID_FLUSH_SLEEP ?? "0.2");
326
+ if (flushSleep > 0) await sleep(flushSleep * 1e3);
327
+ await client.exportFixture(sessionId, fixturePath);
328
+ return result;
329
+ }
330
+ if (!(0, import_node_fs.existsSync)(fixturePath)) {
331
+ throw new Error(`Fixture file not found: ${fixturePath}`);
332
+ }
333
+ await client.importFixture(fixturePath);
334
+ return session(sessionId, "replay", fn);
335
+ }
336
+ // Annotate the CommonJS export names for ESM import in node:
337
+ 0 && (module.exports = {
338
+ OrchidControlClient,
339
+ currentMode,
340
+ currentSessionId,
341
+ init,
342
+ orchidFetch,
343
+ session,
344
+ uninstall,
345
+ withReplay
346
+ });
@@ -0,0 +1,103 @@
1
+ /**
2
+ * An explicit fetch wrapper implementing Orchid interception. Use this
3
+ * directly (e.g. pass it as a custom `fetch` to an LLM client) if you prefer
4
+ * not to patch the global fetch.
5
+ */
6
+ declare const orchidFetch: typeof globalThis.fetch;
7
+ interface InitOptions {
8
+ /** Skip the proxy health check (also enabled by ORCHID_BYPASS_HEALTHCHECK=True or under vitest). */
9
+ bypassHealthCheck?: boolean;
10
+ }
11
+ /**
12
+ * Initializes the Orchid Thin SDK environment.
13
+ *
14
+ * Checks if the Orchid Proxy is online via health check. If online, patches
15
+ * `globalThis.fetch` to route LLM requests through the Orchid Proxy and
16
+ * overrides `OPENAI_BASE_URL`. If the proxy is offline, fail-soft (direct
17
+ * routing) is maintained and no patch is applied.
18
+ *
19
+ * Call this at the entry point of your application, before instantiating any
20
+ * LLM clients.
21
+ */
22
+ declare function init(options?: InitOptions): Promise<void>;
23
+ /** Restores the original global fetch. Intended for tests. */
24
+ declare function uninstall(): void;
25
+
26
+ type OrchidMode = "capture" | "replay" | "passthrough" | "log";
27
+ interface OrchidContext {
28
+ sessionId: string;
29
+ mode: OrchidMode;
30
+ }
31
+ /** Returns the active session ID, falling back to ORCHID_SESSION_ID. */
32
+ declare function currentSessionId(): string | undefined;
33
+ /** Returns the active mode, falling back to ORCHID_MODE. */
34
+ declare function currentMode(): string | undefined;
35
+ /**
36
+ * Runs `fn` with the given Orchid session context. All requests dispatched
37
+ * (transitively) inside `fn` are grouped under `sessionId` with the given mode.
38
+ *
39
+ * ```ts
40
+ * await session("user-onboarding-flow", "capture", async () => {
41
+ * await client.chat.completions.create({ ... });
42
+ * });
43
+ * ```
44
+ */
45
+ declare function session<T>(sessionId: string, mode: OrchidMode, fn: () => T): T;
46
+
47
+ /**
48
+ * Control client for managing the Orchid capture/replay database.
49
+ * Provides methods to perform health checks, export captured sessions,
50
+ * and import fixtures into the Orchid Proxy.
51
+ */
52
+ declare class OrchidControlClient {
53
+ readonly queryUrl: string;
54
+ readonly apiKey?: string;
55
+ /**
56
+ * @param queryUrl URL of the Orchid Query service (default: http://127.0.0.1:4321).
57
+ * @param apiKey API key for authenticating with the control plane.
58
+ */
59
+ constructor(queryUrl?: string, apiKey?: string);
60
+ private headers;
61
+ /** Checks the health of the Orchid Query service. */
62
+ checkHealth(): Promise<boolean>;
63
+ /**
64
+ * Exports all captured exchanges for a session from the proxy and saves
65
+ * them to a local JSON fixture file.
66
+ */
67
+ exportFixture(sessionId: string, path: string): Promise<boolean>;
68
+ /**
69
+ * Reads a local JSON fixture file and imports its exchanges into the
70
+ * Orchid Proxy database.
71
+ *
72
+ * @throws If the fixture file does not exist or the import request fails.
73
+ */
74
+ importFixture(path: string): Promise<boolean>;
75
+ }
76
+
77
+ /**
78
+ * Runs `fn` with capture/replay backed by a JSON fixture file. Framework
79
+ * agnostic — works as a plain wrapper in vitest, jest, or node:test.
80
+ *
81
+ * - If `ORCHID_RECORD=1`: runs `fn` in capture mode and exports the session's
82
+ * HTTP traffic to the fixture path afterwards.
83
+ * - Otherwise: imports the fixture into the proxy and runs `fn` in replay
84
+ * mode, serving mocked responses with no external network calls.
85
+ *
86
+ * ```ts
87
+ * test("user greeting", () =>
88
+ * withReplay("tests/fixtures/test_user_greeting.json", async () => {
89
+ * const response = await client.chat.completions.create({ ... });
90
+ * expect(response.choices[0].message.content).toMatch(/hello/i);
91
+ * }));
92
+ * ```
93
+ *
94
+ * @param fixturePath Local JSON file path where traffic is saved/replayed.
95
+ * @param fn The function to run under the fixture's session.
96
+ * @param options.sessionId Session ID override; defaults to the fixture's
97
+ * recorded session ID, then the fixture file's base name.
98
+ */
99
+ declare function withReplay<T>(fixturePath: string, fn: () => Promise<T>, options?: {
100
+ sessionId?: string;
101
+ }): Promise<T>;
102
+
103
+ export { type InitOptions, type OrchidContext, OrchidControlClient, type OrchidMode, currentMode, currentSessionId, init, orchidFetch, session, uninstall, withReplay };
@@ -0,0 +1,103 @@
1
+ /**
2
+ * An explicit fetch wrapper implementing Orchid interception. Use this
3
+ * directly (e.g. pass it as a custom `fetch` to an LLM client) if you prefer
4
+ * not to patch the global fetch.
5
+ */
6
+ declare const orchidFetch: typeof globalThis.fetch;
7
+ interface InitOptions {
8
+ /** Skip the proxy health check (also enabled by ORCHID_BYPASS_HEALTHCHECK=True or under vitest). */
9
+ bypassHealthCheck?: boolean;
10
+ }
11
+ /**
12
+ * Initializes the Orchid Thin SDK environment.
13
+ *
14
+ * Checks if the Orchid Proxy is online via health check. If online, patches
15
+ * `globalThis.fetch` to route LLM requests through the Orchid Proxy and
16
+ * overrides `OPENAI_BASE_URL`. If the proxy is offline, fail-soft (direct
17
+ * routing) is maintained and no patch is applied.
18
+ *
19
+ * Call this at the entry point of your application, before instantiating any
20
+ * LLM clients.
21
+ */
22
+ declare function init(options?: InitOptions): Promise<void>;
23
+ /** Restores the original global fetch. Intended for tests. */
24
+ declare function uninstall(): void;
25
+
26
+ type OrchidMode = "capture" | "replay" | "passthrough" | "log";
27
+ interface OrchidContext {
28
+ sessionId: string;
29
+ mode: OrchidMode;
30
+ }
31
+ /** Returns the active session ID, falling back to ORCHID_SESSION_ID. */
32
+ declare function currentSessionId(): string | undefined;
33
+ /** Returns the active mode, falling back to ORCHID_MODE. */
34
+ declare function currentMode(): string | undefined;
35
+ /**
36
+ * Runs `fn` with the given Orchid session context. All requests dispatched
37
+ * (transitively) inside `fn` are grouped under `sessionId` with the given mode.
38
+ *
39
+ * ```ts
40
+ * await session("user-onboarding-flow", "capture", async () => {
41
+ * await client.chat.completions.create({ ... });
42
+ * });
43
+ * ```
44
+ */
45
+ declare function session<T>(sessionId: string, mode: OrchidMode, fn: () => T): T;
46
+
47
+ /**
48
+ * Control client for managing the Orchid capture/replay database.
49
+ * Provides methods to perform health checks, export captured sessions,
50
+ * and import fixtures into the Orchid Proxy.
51
+ */
52
+ declare class OrchidControlClient {
53
+ readonly queryUrl: string;
54
+ readonly apiKey?: string;
55
+ /**
56
+ * @param queryUrl URL of the Orchid Query service (default: http://127.0.0.1:4321).
57
+ * @param apiKey API key for authenticating with the control plane.
58
+ */
59
+ constructor(queryUrl?: string, apiKey?: string);
60
+ private headers;
61
+ /** Checks the health of the Orchid Query service. */
62
+ checkHealth(): Promise<boolean>;
63
+ /**
64
+ * Exports all captured exchanges for a session from the proxy and saves
65
+ * them to a local JSON fixture file.
66
+ */
67
+ exportFixture(sessionId: string, path: string): Promise<boolean>;
68
+ /**
69
+ * Reads a local JSON fixture file and imports its exchanges into the
70
+ * Orchid Proxy database.
71
+ *
72
+ * @throws If the fixture file does not exist or the import request fails.
73
+ */
74
+ importFixture(path: string): Promise<boolean>;
75
+ }
76
+
77
+ /**
78
+ * Runs `fn` with capture/replay backed by a JSON fixture file. Framework
79
+ * agnostic — works as a plain wrapper in vitest, jest, or node:test.
80
+ *
81
+ * - If `ORCHID_RECORD=1`: runs `fn` in capture mode and exports the session's
82
+ * HTTP traffic to the fixture path afterwards.
83
+ * - Otherwise: imports the fixture into the proxy and runs `fn` in replay
84
+ * mode, serving mocked responses with no external network calls.
85
+ *
86
+ * ```ts
87
+ * test("user greeting", () =>
88
+ * withReplay("tests/fixtures/test_user_greeting.json", async () => {
89
+ * const response = await client.chat.completions.create({ ... });
90
+ * expect(response.choices[0].message.content).toMatch(/hello/i);
91
+ * }));
92
+ * ```
93
+ *
94
+ * @param fixturePath Local JSON file path where traffic is saved/replayed.
95
+ * @param fn The function to run under the fixture's session.
96
+ * @param options.sessionId Session ID override; defaults to the fixture's
97
+ * recorded session ID, then the fixture file's base name.
98
+ */
99
+ declare function withReplay<T>(fixturePath: string, fn: () => Promise<T>, options?: {
100
+ sessionId?: string;
101
+ }): Promise<T>;
102
+
103
+ export { type InitOptions, type OrchidContext, OrchidControlClient, type OrchidMode, currentMode, currentSessionId, init, orchidFetch, session, uninstall, withReplay };
package/dist/index.js ADDED
@@ -0,0 +1,312 @@
1
+ // src/context.ts
2
+ import { AsyncLocalStorage } from "async_hooks";
3
+ var storage = new AsyncLocalStorage();
4
+ function currentSessionId() {
5
+ return storage.getStore()?.sessionId ?? process.env.ORCHID_SESSION_ID ?? void 0;
6
+ }
7
+ function currentMode() {
8
+ return storage.getStore()?.mode ?? process.env.ORCHID_MODE ?? void 0;
9
+ }
10
+ function session(sessionId, mode, fn) {
11
+ return storage.run({ sessionId, mode }, fn);
12
+ }
13
+
14
+ // src/core.ts
15
+ var CORE_PROVIDERS = [
16
+ "api.openai.com",
17
+ "api.anthropic.com",
18
+ "generativelanguage.googleapis.com",
19
+ "aiplatform.googleapis.com"
20
+ ];
21
+ var LOCAL_HOSTS = ["localhost", "127.0.0.1", "::1", "[::1]"];
22
+ var patched = false;
23
+ var offlineFallback = false;
24
+ var originalFetch;
25
+ function proxyUrl() {
26
+ return process.env.ORCHID_PROXY_URL ?? "http://127.0.0.1:4320/v1";
27
+ }
28
+ function envList(name) {
29
+ return (process.env[name] ?? "").split(",").map((s) => s.trim()).filter((s) => s.length > 0);
30
+ }
31
+ function isCoreProvider(host) {
32
+ return CORE_PROVIDERS.some((c) => host.includes(c));
33
+ }
34
+ function shouldIntercept(url) {
35
+ if (offlineFallback) return false;
36
+ const host = url.hostname;
37
+ if (LOCAL_HOSTS.some((h) => host === h)) return false;
38
+ if (envList("ORCHID_IGNORE_DOMAINS").some((d) => host.includes(d))) {
39
+ return false;
40
+ }
41
+ if (isCoreProvider(host)) return true;
42
+ const capture = envList("ORCHID_CAPTURE_DOMAINS");
43
+ if (capture.includes("*")) return true;
44
+ if (capture.some((d) => host.includes(d))) return true;
45
+ return false;
46
+ }
47
+ function rewriteUrl(originalUrl) {
48
+ const proxy = new URL(proxyUrl());
49
+ const rewritten = new URL(originalUrl.toString());
50
+ rewritten.protocol = proxy.protocol;
51
+ rewritten.host = proxy.host;
52
+ if (isCoreProvider(originalUrl.hostname)) {
53
+ const proxyBasePath = proxy.pathname.replace(/\/+$/, "");
54
+ if (proxyBasePath && !originalUrl.pathname.startsWith(proxyBasePath)) {
55
+ rewritten.pathname = proxyBasePath + originalUrl.pathname;
56
+ }
57
+ }
58
+ return rewritten;
59
+ }
60
+ function injectHeaders(headers, targetUrl, originalUrl) {
61
+ const proxy = new URL(proxyUrl());
62
+ if (targetUrl.host !== proxy.host) return;
63
+ const proxyKey = process.env.ORCHID_PROXY_KEY;
64
+ if (proxyKey) headers.set("X-Orchid-Proxy-Key", proxyKey);
65
+ const sessionId = currentSessionId();
66
+ let mode = currentMode();
67
+ if (sessionId) {
68
+ headers.set("X-Orchid-Session-Id", sessionId);
69
+ if (!mode) mode = "capture";
70
+ }
71
+ if (mode) headers.set("X-Orchid-Mode", mode);
72
+ if (originalUrl && originalUrl.host !== proxy.host) {
73
+ headers.set(
74
+ "X-Orchid-Target-Url",
75
+ `${originalUrl.protocol}//${originalUrl.host}`
76
+ );
77
+ }
78
+ }
79
+ function purgeOrchidHeaders(headers) {
80
+ const toDelete = [];
81
+ headers.forEach((_value, key) => {
82
+ if (key.toLowerCase().startsWith("x-orchid-")) toDelete.push(key);
83
+ });
84
+ for (const key of toDelete) headers.delete(key);
85
+ }
86
+ function isConnectionError(err) {
87
+ if (!(err instanceof Error)) return false;
88
+ const cause = err.cause;
89
+ const code = cause?.code ?? err.code;
90
+ return code === "ECONNREFUSED" || code === "ECONNRESET" || code === "EHOSTUNREACH" || code === "ENOTFOUND" || code === "ETIMEDOUT" || code === "UND_ERR_CONNECT_TIMEOUT" || code === "UND_ERR_SOCKET";
91
+ }
92
+ var orchidFetch = async (input, init2) => {
93
+ const baseFetch = originalFetch ?? globalThis.fetch;
94
+ const request = new Request(input, init2);
95
+ const original = new URL(request.url);
96
+ if (!shouldIntercept(original)) {
97
+ const headers2 = new Headers(request.headers);
98
+ injectHeaders(headers2, original);
99
+ return baseFetch(new Request(request, { headers: headers2 }));
100
+ }
101
+ const rewritten = rewriteUrl(original);
102
+ const headers = new Headers(request.headers);
103
+ injectHeaders(headers, rewritten, original);
104
+ const proxied = new Request(rewritten, {
105
+ method: request.method,
106
+ headers,
107
+ body: request.body,
108
+ // Required by undici when streaming a body
109
+ ...request.body ? { duplex: "half" } : {},
110
+ redirect: request.redirect,
111
+ signal: request.signal
112
+ });
113
+ try {
114
+ return await baseFetch(proxied);
115
+ } catch (err) {
116
+ if (!isConnectionError(err)) throw err;
117
+ console.warn(
118
+ `[orchid] Proxy connection failed (${String(err)}). Falling back to direct routing: ${original}`
119
+ );
120
+ const fallbackHeaders = new Headers(request.headers);
121
+ purgeOrchidHeaders(fallbackHeaders);
122
+ return baseFetch(
123
+ new Request(original, {
124
+ method: request.method,
125
+ headers: fallbackHeaders,
126
+ body: request.body,
127
+ ...request.body ? { duplex: "half" } : {},
128
+ redirect: request.redirect,
129
+ signal: request.signal
130
+ })
131
+ );
132
+ }
133
+ };
134
+ function deriveQueryUrl() {
135
+ const explicit = process.env.ORCHID_QUERY_URL;
136
+ if (explicit) return explicit;
137
+ const proxy = new URL(proxyUrl());
138
+ if (proxy.port === "4320") proxy.port = "4321";
139
+ proxy.pathname = "";
140
+ return proxy.toString().replace(/\/+$/, "");
141
+ }
142
+ async function proxyIsHealthy() {
143
+ const baseFetch = originalFetch ?? globalThis.fetch;
144
+ try {
145
+ const resp = await baseFetch(`${deriveQueryUrl()}/health`, {
146
+ signal: AbortSignal.timeout(1e3)
147
+ });
148
+ return resp.status === 200;
149
+ } catch {
150
+ return false;
151
+ }
152
+ }
153
+ async function init(options = {}) {
154
+ offlineFallback = false;
155
+ const proxy = proxyUrl();
156
+ let parsed;
157
+ try {
158
+ parsed = new URL(proxy);
159
+ } catch {
160
+ throw new Error(`Malformed ORCHID_PROXY_URL: ${proxy}`);
161
+ }
162
+ if (!parsed.protocol || !parsed.host) {
163
+ throw new Error(`Malformed ORCHID_PROXY_URL: ${proxy}`);
164
+ }
165
+ const bypass = options.bypassHealthCheck === true || process.env.ORCHID_BYPASS_HEALTHCHECK === "True" || process.env.VITEST !== void 0;
166
+ if (!bypass) {
167
+ offlineFallback = !await proxyIsHealthy();
168
+ }
169
+ if (!offlineFallback) {
170
+ process.env.OPENAI_BASE_URL = proxy;
171
+ }
172
+ if (!patched && !offlineFallback) {
173
+ originalFetch = globalThis.fetch;
174
+ globalThis.fetch = orchidFetch;
175
+ patched = true;
176
+ }
177
+ }
178
+ function uninstall() {
179
+ if (patched && originalFetch) {
180
+ globalThis.fetch = originalFetch;
181
+ originalFetch = void 0;
182
+ patched = false;
183
+ }
184
+ offlineFallback = false;
185
+ }
186
+
187
+ // src/client.ts
188
+ import { mkdir, readFile, writeFile } from "fs/promises";
189
+ import { dirname } from "path";
190
+ var OrchidControlClient = class {
191
+ queryUrl;
192
+ apiKey;
193
+ /**
194
+ * @param queryUrl URL of the Orchid Query service (default: http://127.0.0.1:4321).
195
+ * @param apiKey API key for authenticating with the control plane.
196
+ */
197
+ constructor(queryUrl, apiKey) {
198
+ this.queryUrl = queryUrl ?? process.env.ORCHID_QUERY_URL ?? "http://127.0.0.1:4321";
199
+ this.apiKey = apiKey ?? process.env.ORCHID_API_KEY ?? void 0;
200
+ }
201
+ headers() {
202
+ return this.apiKey ? { "X-Orchid-Api-Key": this.apiKey } : {};
203
+ }
204
+ /** Checks the health of the Orchid Query service. */
205
+ async checkHealth() {
206
+ try {
207
+ const resp = await fetch(`${this.queryUrl}/health`, {
208
+ headers: this.headers(),
209
+ signal: AbortSignal.timeout(5e3)
210
+ });
211
+ return resp.status === 200;
212
+ } catch (err) {
213
+ console.warn(`[orchid] Query service health check failed: ${String(err)}`);
214
+ return false;
215
+ }
216
+ }
217
+ /**
218
+ * Exports all captured exchanges for a session from the proxy and saves
219
+ * them to a local JSON fixture file.
220
+ */
221
+ async exportFixture(sessionId, path) {
222
+ try {
223
+ const resp = await fetch(
224
+ `${this.queryUrl}/v1/sessions/${encodeURIComponent(sessionId)}/export`,
225
+ { headers: this.headers() }
226
+ );
227
+ if (resp.status === 404) {
228
+ console.warn(`[orchid] Session ${sessionId} not found to export.`);
229
+ return false;
230
+ }
231
+ if (!resp.ok) {
232
+ throw new Error(`Export failed with status ${resp.status}`);
233
+ }
234
+ const fixture = await resp.json();
235
+ await mkdir(dirname(path), { recursive: true });
236
+ await writeFile(path, JSON.stringify(fixture, null, 2));
237
+ return true;
238
+ } catch (err) {
239
+ console.warn(
240
+ `[orchid] Failed to export fixture for session ${sessionId} to ${path}: ${String(err)}`
241
+ );
242
+ return false;
243
+ }
244
+ }
245
+ /**
246
+ * Reads a local JSON fixture file and imports its exchanges into the
247
+ * Orchid Proxy database.
248
+ *
249
+ * @throws If the fixture file does not exist or the import request fails.
250
+ */
251
+ async importFixture(path) {
252
+ const raw = await readFile(path, "utf-8");
253
+ const fixture = JSON.parse(raw);
254
+ const resp = await fetch(`${this.queryUrl}/v1/sessions/import`, {
255
+ method: "POST",
256
+ headers: { "Content-Type": "application/json", ...this.headers() },
257
+ body: JSON.stringify(fixture)
258
+ });
259
+ if (!resp.ok) {
260
+ throw new Error(`Import failed with status ${resp.status}`);
261
+ }
262
+ return resp.status === 201;
263
+ }
264
+ };
265
+
266
+ // src/replay.ts
267
+ import { readFile as readFile2 } from "fs/promises";
268
+ import { existsSync } from "fs";
269
+ import { basename, extname } from "path";
270
+ function recordMode() {
271
+ return ["1", "true", "yes"].includes(
272
+ (process.env.ORCHID_RECORD ?? "").toLowerCase()
273
+ );
274
+ }
275
+ async function fixtureSessionId(path) {
276
+ if (!existsSync(path)) return void 0;
277
+ try {
278
+ const data = JSON.parse(await readFile2(path, "utf-8"));
279
+ return data?.session?.id ?? void 0;
280
+ } catch {
281
+ return void 0;
282
+ }
283
+ }
284
+ function sleep(ms) {
285
+ return new Promise((resolve) => setTimeout(resolve, ms));
286
+ }
287
+ async function withReplay(fixturePath, fn, options = {}) {
288
+ const client = new OrchidControlClient();
289
+ const sessionId = options.sessionId ?? await fixtureSessionId(fixturePath) ?? basename(fixturePath, extname(fixturePath));
290
+ if (recordMode()) {
291
+ const result = await session(sessionId, "capture", fn);
292
+ const flushSleep = Number(process.env.ORCHID_FLUSH_SLEEP ?? "0.2");
293
+ if (flushSleep > 0) await sleep(flushSleep * 1e3);
294
+ await client.exportFixture(sessionId, fixturePath);
295
+ return result;
296
+ }
297
+ if (!existsSync(fixturePath)) {
298
+ throw new Error(`Fixture file not found: ${fixturePath}`);
299
+ }
300
+ await client.importFixture(fixturePath);
301
+ return session(sessionId, "replay", fn);
302
+ }
303
+ export {
304
+ OrchidControlClient,
305
+ currentMode,
306
+ currentSessionId,
307
+ init,
308
+ orchidFetch,
309
+ session,
310
+ uninstall,
311
+ withReplay
312
+ };
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "orchid-sdk",
3
+ "version": "0.1.0",
4
+ "description": "Thin TypeScript SDK for Orchid — the Orchestration Interactive Debugger. Routes outbound LLM requests through the local Orchid Proxy for capture, replay, and interactive debugging.",
5
+ "author": "Orchid Team <team@orchid.dev>",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/mario-guerra/orchid.git"
9
+ },
10
+ "bugs": {
11
+ "url": "https://github.com/mario-guerra/orchid/issues"
12
+ },
13
+ "license": "Apache-2.0",
14
+ "type": "module",
15
+ "engines": {
16
+ "node": ">=18"
17
+ },
18
+ "main": "./dist/index.cjs",
19
+ "module": "./dist/index.js",
20
+ "types": "./dist/index.d.ts",
21
+ "exports": {
22
+ ".": {
23
+ "types": "./dist/index.d.ts",
24
+ "import": "./dist/index.js",
25
+ "require": "./dist/index.cjs"
26
+ }
27
+ },
28
+ "files": [
29
+ "dist"
30
+ ],
31
+ "scripts": {
32
+ "build": "tsup src/index.ts --format esm,cjs --dts --clean",
33
+ "test": "vitest run",
34
+ "typecheck": "tsc --noEmit"
35
+ },
36
+ "keywords": [
37
+ "orchid",
38
+ "llm",
39
+ "proxy",
40
+ "capture",
41
+ "replay",
42
+ "debugging",
43
+ "observability"
44
+ ],
45
+ "devDependencies": {
46
+ "@types/node": "^20.14.0",
47
+ "tsup": "^8.0.0",
48
+ "typescript": "^5.4.0",
49
+ "vitest": "^2.0.0"
50
+ }
51
+ }