generalcontext 0.0.0-stage → 0.2.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,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/NOTICE ADDED
@@ -0,0 +1,5 @@
1
+ General Context SDK
2
+ Copyright 2026 General Context Labs, Inc.
3
+
4
+ This product includes software developed at General Context Labs, Inc.
5
+ (https://generalcontextlabs.com).
package/README.md CHANGED
@@ -1,3 +1,120 @@
1
- # Temporary Holding Version
1
+ # generalcontext
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Record your agent's model calls for General Context. Your agent never waits on us, and a failure on our side is logged and dropped, never thrown. No runtime dependencies. Supports OpenAI (`chat.completions`, `responses`) and Anthropic (`messages`), streamed or not.
4
+
5
+ ## Install
6
+
7
+ ```sh
8
+ npm install generalcontext
9
+ ```
10
+
11
+ Set `GENERALCONTEXT_API_KEY` to the key from your workspace's Connect page.
12
+
13
+ ## Initialize
14
+
15
+ Call once per process, before your agent makes model calls. Every OpenAI and Anthropic client is recorded, including ones created earlier.
16
+
17
+ ```ts
18
+ import OpenAI from 'openai';
19
+ import Anthropic from '@anthropic-ai/sdk';
20
+ import { initialize } from 'generalcontext';
21
+
22
+ initialize({ appName: 'support-agent', instrumentModules: { openAI: OpenAI, anthropic: Anthropic } });
23
+ ```
24
+
25
+ ## Configuration
26
+
27
+ | Option | Default | |
28
+ | - | - | - |
29
+ | `apiKey` | `GENERALCONTEXT_API_KEY` | |
30
+ | `baseUrl` | `GENERALCONTEXT_BASE_URL`, else `https://generalcontextlabs.com` | The option wins over the env var. Must be `https://`, except `http://localhost`, `127.0.0.1` or `[::1]`. Other URLs are refused and nothing is sent. |
31
+ | `appName` | none | Sent with every batch. |
32
+ | `redact` | `false` | See [Redaction](#redaction). |
33
+ | `beforeSend` | none | `(call) => call \| null`. Runs at send time on each call, before redaction. Return the call (edited or not) to send it, or `null` to drop it. A throw drops the call. |
34
+ | `instrumentModules` | installed `openai` and `@anthropic-ai/sdk` | Pass these whenever a bundler is involved. |
35
+ | `instrumentFetch` | `false` | SDK clients are always recorded. Set `true` to also record raw `fetch` POSTs to any `/chat/completions` URL. |
36
+ | `disableBatch` | `false` | Send each call right away. |
37
+
38
+ | Env var | |
39
+ | - | - |
40
+ | `GENERALCONTEXT_API_KEY` | API key, if `apiKey` is not passed. |
41
+ | `GENERALCONTEXT_BASE_URL` | Collector URL, if `baseUrl` is not passed. |
42
+ | `GENERALCONTEXT_REDACT_SALT` | Secret that keeps redaction placeholders stable across processes. |
43
+ | `GENERALCONTEXT_DISABLED` | `1`, `true` or `yes` makes `initialize()` do nothing. |
44
+
45
+ Requests never follow redirects. A call over 4 MB is dropped, and the queue holds at most 5000 calls or 64 MB. Pending calls are flushed when the process is about to exit, for at most 2 seconds.
46
+
47
+ ## Proxies
48
+
49
+ Node's built-in `fetch` ignores `HTTPS_PROXY` by default. On Node 24+, set `NODE_USE_ENV_PROXY=1`. On older versions, install a global dispatcher (for example undici's `setGlobalDispatcher(new EnvHttpProxyAgent())`). If your proxy inspects TLS, point `NODE_EXTRA_CA_CERTS` at its CA certificate.
50
+
51
+ ## Next.js
52
+
53
+ Initialize in `instrumentation.ts` at the project root, not in a route file:
54
+
55
+ ```ts
56
+ export async function register() {
57
+ if (process.env.NEXT_RUNTIME === 'nodejs') {
58
+ const { initialize } = await import('generalcontext');
59
+ const { OpenAI } = await import('openai');
60
+ const anthropic = await import('@anthropic-ai/sdk');
61
+ initialize({ appName: 'my-agent', instrumentModules: { openAI: OpenAI, anthropic } });
62
+ }
63
+ }
64
+ ```
65
+
66
+ Keep the SDKs out of the bundle so routes use the instance we patched:
67
+
68
+ ```ts
69
+ // next.config.ts
70
+ export default { serverExternalPackages: ['openai', '@anthropic-ai/sdk'] };
71
+ ```
72
+
73
+ Use the Node.js runtime. The Edge runtime is not supported.
74
+
75
+ ## Sessions and tasks
76
+
77
+ Tag calls with your own ids. Tags carry across `await`.
78
+
79
+ ```ts
80
+ import { withSession, task } from 'generalcontext';
81
+
82
+ await withSession({ sessionId: conversationId, userId: 'u_42', channel: 'chat' }, async () => {
83
+ await task('triage', () => client.chat.completions.create({ ... }));
84
+ });
85
+ ```
86
+
87
+ `withSession(conversationId, fn)` also works. `conversation({ id, ... }, fn)` is the older name.
88
+
89
+ ## Serverless and scripts
90
+
91
+ Calls send in the background. Before a function or script exits:
92
+
93
+ ```ts
94
+ await flush(); // never throws
95
+ ```
96
+
97
+ ## Outcomes and events
98
+
99
+ Both flush pending calls first, so the session exists before the outcome or event arrives. Both return `true` when accepted and never throw.
100
+
101
+ ```ts
102
+ await reportOutcome(conversationId, 'fail', 'customer reopened the ticket');
103
+
104
+ await logEvent({ sessionId: conversationId, eventType: 'order.refunded', eventId: `refund-${refundId}`, properties: { amount: 42.5 } });
105
+ await logEvent({ sessionId: conversationId, eventType: 'handoff.to_human', eventId: `handoff-${ticketId}` });
106
+ ```
107
+
108
+ Pass a stable `eventId` so retries dedupe. `properties` are flat strings, numbers and booleans. `timestamp` defaults to now.
109
+
110
+ ## Redaction
111
+
112
+ `initialize({ redact: true })` replaces emails, phone numbers and card or SSN-like numbers with placeholders such as `<email:3f9a1c>` before anything leaves your process. Set `GENERALCONTEXT_REDACT_SALT` to one secret in every process so the same value gets the same placeholder. Or pass your own `(text) => text`. Redaction also applies to `reportOutcome` and `logEvent`, so a redacted session id still matches its calls.
113
+
114
+ ## One client only
115
+
116
+ `wrap(client, { redact })` records a single client instance without patching the SDK. Its `redact` applies to that client only. If `initialize()` already patched the SDK, the client is recorded with the `initialize()` settings.
117
+
118
+ ## License
119
+
120
+ Apache License 2.0. See [LICENSE](LICENSE) and [NOTICE](NOTICE).
@@ -0,0 +1,82 @@
1
+ export declare const VERSION = "0.2.0";
2
+ type Metadata = Record<string, string | number | boolean>;
3
+ export type Session = {
4
+ sessionId: string;
5
+ userId?: string;
6
+ channel?: string;
7
+ product?: string;
8
+ metadata?: Metadata;
9
+ };
10
+ type Tags = {
11
+ id: string;
12
+ user_id?: string;
13
+ channel?: string;
14
+ product?: string;
15
+ metadata?: Metadata;
16
+ };
17
+ type Api = 'openai-chat' | 'openai-responses' | 'anthropic';
18
+ export type Call = {
19
+ api: Api;
20
+ conversation: Tags | null;
21
+ task: string | null;
22
+ request: unknown;
23
+ response: unknown;
24
+ started_at: string;
25
+ ended_at: string;
26
+ error: string | null;
27
+ };
28
+ type Scrub = (text: string) => string;
29
+ type BeforeSend = (call: Call) => Call | null | undefined;
30
+ export type InitializeOptions = {
31
+ apiKey?: string;
32
+ /** Collector URL. Must be https://, except http://localhost, 127.0.0.1 or [::1]. */
33
+ baseUrl?: string;
34
+ appName?: string;
35
+ /** true for built-in email/phone/card/SSN placeholders, or your own (text) => text. */
36
+ redact?: boolean | Scrub;
37
+ /** Runs at send time on each call, before redaction. Return the call to send, or null to drop it. */
38
+ beforeSend?: BeforeSend;
39
+ /** SDK classes or modules to patch, e.g. { openAI: OpenAI, anthropic: Anthropic }. */
40
+ instrumentModules?: {
41
+ openAI?: unknown;
42
+ anthropic?: unknown;
43
+ };
44
+ /** Also record raw fetch POSTs to any URL ending /chat/completions. Default false. */
45
+ instrumentFetch?: boolean;
46
+ /** Send each call right away instead of batching. */
47
+ disableBatch?: boolean;
48
+ };
49
+ /** Configure recording once per process, before your agent makes model calls. */
50
+ export declare function initialize(options?: InitializeOptions): void;
51
+ /** Tag every call made inside `run` with one session. `conversation` is the same function. */
52
+ export declare function withSession<T>(session: Session | string, run: () => T): T;
53
+ /** Older name for withSession. Accepts { id } as well as { sessionId }. */
54
+ export declare function conversation<T>(tags: Session | {
55
+ id: string;
56
+ channel?: string;
57
+ product?: string;
58
+ metadata?: Metadata;
59
+ } | string, run: () => T): T;
60
+ /** Tag every call made inside `run` with a task name, such as one step of your agent loop. */
61
+ export declare function task<T>(name: string, run: () => T): T;
62
+ /** Wait until recorded calls are sent. Call before a serverless function or script exits. Never throws. */
63
+ export declare function flush(): Promise<void>;
64
+ /** Mark how a session ended. Returns true when the platform accepted it. Never throws. */
65
+ export declare function reportOutcome(sessionId: string, outcome: 'success' | 'fail', note?: string): Promise<boolean>;
66
+ export type AppEvent = {
67
+ sessionId: string;
68
+ eventType: string;
69
+ properties?: Metadata;
70
+ eventId?: string;
71
+ timestamp?: string | Date;
72
+ };
73
+ /** Record something that happened in your systems, such as 'order.refunded'. Pass a stable eventId so retries dedupe. Never throws. */
74
+ export declare function logEvent(event: AppEvent): Promise<boolean>;
75
+ /**
76
+ * Record one client instance only, without initialize(). Returns the same client.
77
+ * `redact` applies to this client only. If initialize() already patched the SDK, its settings apply instead.
78
+ */
79
+ export declare function wrap<C extends object>(client: C, options?: {
80
+ redact?: boolean | Scrub;
81
+ }): C;
82
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,591 @@
1
+ // Copyright 2026 General Context Labs, Inc.
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ // Record your agent's model calls for General Context, without changing how it runs.
4
+ //
5
+ // import OpenAI from 'openai';
6
+ // import { initialize, withSession } from 'generalcontext';
7
+ //
8
+ // initialize({ instrumentModules: { openAI: OpenAI } });
9
+ // await withSession(conversationId, async () => { ... });
10
+ //
11
+ // Every SDK model call (history sent, tools offered, reply and tool calls) is queued and sent in
12
+ // the background. Raw fetch capture is opt-in with instrumentFetch: true. Your agent never waits on General Context, and a failure on our side is
13
+ // logged and dropped, never thrown. No runtime dependencies.
14
+ import { AsyncLocalStorage } from 'node:async_hooks';
15
+ import { createHmac, randomBytes, randomUUID } from 'node:crypto';
16
+ import { createRequire } from 'node:module';
17
+ export const VERSION = '0.2.0';
18
+ const BATCH = 20;
19
+ const MAX_QUEUE = 5000;
20
+ const MAX_CALL_BYTES = 4_000_000; // the server rejects larger calls
21
+ const MAX_QUEUE_BYTES = 64_000_000;
22
+ const MAX_BATCH_BYTES = 4_000_000;
23
+ const SEND_TIMEOUT_MS = 15_000;
24
+ const DIRECT_TIMEOUT_MS = 10_000; // reportOutcome and logEvent
25
+ const EXIT_FLUSH_MS = 2_000;
26
+ const DEFAULT_BASE_URL = 'https://generalcontextlabs.com';
27
+ const config = {
28
+ apiKey: undefined,
29
+ baseUrl: undefined,
30
+ appName: undefined,
31
+ scrub: null,
32
+ beforeSend: null,
33
+ disableBatch: false,
34
+ };
35
+ const scope = new AsyncLocalStorage();
36
+ const queue = [];
37
+ let queuedBytes = 0;
38
+ let initialized = false;
39
+ let sending = null;
40
+ let timer = null;
41
+ let originalFetch = globalThis.fetch;
42
+ let exitHooked = false;
43
+ let stopped = false; // set when the exit flush runs out of time
44
+ const inflight = new Set();
45
+ const apiKey = () => config.apiKey ?? process.env.GENERALCONTEXT_API_KEY;
46
+ // Explicit option, then env var, then default. Trailing slashes are trimmed without a regex.
47
+ const trimSlashes = (url) => { let end = url.length; while (end > 0 && url[end - 1] === '/')
48
+ end--; return url.slice(0, end); };
49
+ const baseUrl = () => trimSlashes(config.baseUrl ?? process.env.GENERALCONTEXT_BASE_URL ?? DEFAULT_BASE_URL);
50
+ const warn = (message) => console.warn(`[generalcontext] ${message}`);
51
+ // Warn at most once per minute for each key, so a broken collector cannot flood logs.
52
+ const lastWarned = new Map();
53
+ function warnLimited(key, message) {
54
+ const now = Date.now();
55
+ if (now - (lastWarned.get(key) ?? -Infinity) < 60_000)
56
+ return;
57
+ lastWarned.set(key, now);
58
+ warn(message);
59
+ }
60
+ // Only send the API key over https, or plain http to this machine for local development.
61
+ function secureUrl(url) {
62
+ try {
63
+ const u = new URL(url);
64
+ return u.protocol === 'https:' || (u.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(u.hostname));
65
+ }
66
+ catch {
67
+ return false;
68
+ }
69
+ }
70
+ const disabledByEnv = () => /^(1|true|yes)$/i.test((process.env.GENERALCONTEXT_DISABLED ?? '').trim());
71
+ /** Configure recording once per process, before your agent makes model calls. */
72
+ export function initialize(options = {}) {
73
+ if (initialized) {
74
+ warn('initialize was already called; ignoring the second call');
75
+ return;
76
+ }
77
+ initialized = true;
78
+ if (disabledByEnv()) {
79
+ warn('GENERALCONTEXT_DISABLED is set; recording is off');
80
+ return;
81
+ }
82
+ config.apiKey = options.apiKey ?? process.env.GENERALCONTEXT_API_KEY;
83
+ config.baseUrl = options.baseUrl;
84
+ config.appName = options.appName;
85
+ config.scrub = redactor(options.redact);
86
+ config.beforeSend = options.beforeSend ?? null;
87
+ config.disableBatch = options.disableBatch ?? false;
88
+ if (!config.apiKey)
89
+ warn('no API key; set GENERALCONTEXT_API_KEY or pass apiKey');
90
+ if (!secureUrl(baseUrl()))
91
+ warn(`baseUrl ${baseUrl()} is not https; nothing will be sent`);
92
+ const modules = options.instrumentModules ?? autoload();
93
+ if (modules.openAI)
94
+ patchOpenAI(modules.openAI);
95
+ if (modules.anthropic)
96
+ patchAnthropic(modules.anthropic);
97
+ if (options.instrumentFetch ?? false)
98
+ patchFetch();
99
+ }
100
+ // Load installed SDKs when the caller did not pass them. Bundlers can hide these; pass instrumentModules there.
101
+ function autoload() {
102
+ const require = createRequire(import.meta.url);
103
+ const load = (name) => { try {
104
+ return require(name);
105
+ }
106
+ catch {
107
+ return undefined;
108
+ } };
109
+ return { openAI: load('openai'), anthropic: load('@anthropic-ai/sdk') };
110
+ }
111
+ // Accept a module namespace, its default export, or the client class itself.
112
+ function clientClass(value, name) {
113
+ const v = value;
114
+ if (typeof v === 'function' && (v.Messages || v.Chat))
115
+ return v;
116
+ return v?.[name] ?? v?.default?.[name] ?? (typeof v === 'function' ? v : typeof v?.default === 'function' ? v.default : undefined);
117
+ }
118
+ function patchOpenAI(value) {
119
+ const OpenAI = clientClass(value, 'OpenAI');
120
+ patchMethod(OpenAI?.Chat?.Completions?.prototype, 'create', 'openai-chat');
121
+ patchMethod(OpenAI?.Responses?.prototype, 'create', 'openai-responses');
122
+ }
123
+ function patchAnthropic(value) {
124
+ const Anthropic = clientClass(value, 'Anthropic');
125
+ // messages.stream() calls messages.create({ stream: true }) internally, so it is covered too.
126
+ patchMethod(Anthropic?.Messages?.prototype, 'create', 'anthropic');
127
+ }
128
+ const MARK = Symbol.for('generalcontext.recorded');
129
+ function patchMethod(owner, name, api) {
130
+ const original = owner?.[name];
131
+ if (typeof original !== 'function' || original[MARK])
132
+ return;
133
+ owner[name] = recording(original, api);
134
+ }
135
+ /** Tag every call made inside `run` with one session. `conversation` is the same function. */
136
+ export function withSession(session, run) {
137
+ const s = typeof session === 'string' ? { sessionId: session } : session;
138
+ const tags = { id: String(s.sessionId) };
139
+ if (s.userId)
140
+ tags.user_id = s.userId;
141
+ if (s.channel)
142
+ tags.channel = s.channel;
143
+ if (s.product)
144
+ tags.product = s.product;
145
+ if (s.metadata)
146
+ tags.metadata = s.metadata;
147
+ return scope.run({ ...scope.getStore(), tags }, run);
148
+ }
149
+ /** Older name for withSession. Accepts { id } as well as { sessionId }. */
150
+ export function conversation(tags, run) {
151
+ if (typeof tags === 'object' && 'id' in tags) {
152
+ const { id, ...rest } = tags;
153
+ return withSession({ ...rest, sessionId: id }, run);
154
+ }
155
+ return withSession(tags, run);
156
+ }
157
+ /** Tag every call made inside `run` with a task name, such as one step of your agent loop. */
158
+ export function task(name, run) {
159
+ return scope.run({ ...scope.getStore(), task: name }, run);
160
+ }
161
+ // Runs before the caller's await continues, so only take the snapshot here. Redaction and beforeSend run at send time.
162
+ function record(call, at, scrub) {
163
+ try {
164
+ if (!apiKey()) {
165
+ warnLimited('no-key', 'GENERALCONTEXT_API_KEY is not set; a model call was not recorded');
166
+ return;
167
+ }
168
+ const json = JSON.stringify({ ...call, conversation: at?.tags ?? null, task: at?.task ?? null });
169
+ const bytes = Buffer.byteLength(json);
170
+ if (bytes > MAX_CALL_BYTES) {
171
+ warnLimited('oversized', `a model call of ${bytes} bytes is over the ${MAX_CALL_BYTES} byte limit and was dropped`);
172
+ return;
173
+ }
174
+ if (queue.length >= MAX_QUEUE || queuedBytes + bytes > MAX_QUEUE_BYTES) {
175
+ warnLimited('queue-full', 'queue is full; a model call was dropped');
176
+ return;
177
+ }
178
+ queue.push({ json, bytes, scrub });
179
+ queuedBytes += bytes;
180
+ hookExit();
181
+ if (config.disableBatch || queue.length >= BATCH)
182
+ void send();
183
+ else if (!timer) {
184
+ timer = setTimeout(() => { timer = null; void send(); }, 500);
185
+ timer.unref?.();
186
+ }
187
+ }
188
+ catch (error) {
189
+ warnLimited('record', `could not record a model call: ${error.message}`);
190
+ }
191
+ }
192
+ // Flush once when the event loop empties, capped at EXIT_FLUSH_MS. Pending requests are aborted at the cap.
193
+ function hookExit() {
194
+ if (exitHooked)
195
+ return;
196
+ exitHooked = true;
197
+ process.once('beforeExit', () => {
198
+ const cap = setTimeout(() => { stopped = true; for (const c of inflight)
199
+ c.abort(); }, EXIT_FLUSH_MS);
200
+ cap.unref?.();
201
+ void flush().finally(() => clearTimeout(cap));
202
+ });
203
+ }
204
+ // Apply beforeSend and redaction. Returns the JSON to send, or null to drop.
205
+ function prepare(entry) {
206
+ let call = JSON.parse(entry.json);
207
+ if (config.beforeSend) {
208
+ try {
209
+ call = config.beforeSend(call);
210
+ }
211
+ catch (error) {
212
+ warnLimited('before-send', `beforeSend threw; a model call was dropped: ${error.message}`);
213
+ return null;
214
+ }
215
+ if (call == null)
216
+ return null;
217
+ }
218
+ return JSON.stringify(scrubbed(call, entry.scrub === undefined ? config.scrub : entry.scrub));
219
+ }
220
+ async function post(path, body, timeoutMs) {
221
+ const url = `${baseUrl()}${path}`;
222
+ if (!secureUrl(url)) {
223
+ warnLimited('insecure', `refusing to send to ${baseUrl()}: baseUrl must be https`);
224
+ return null;
225
+ }
226
+ if (stopped)
227
+ return null;
228
+ const controller = new AbortController();
229
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
230
+ timeout.unref?.();
231
+ inflight.add(controller);
232
+ try {
233
+ return await originalFetch(url, {
234
+ method: 'POST',
235
+ headers: { Authorization: `Bearer ${apiKey()}`, 'Content-Type': 'application/json' },
236
+ body,
237
+ redirect: 'error', // never forward the API key to another host
238
+ signal: controller.signal,
239
+ });
240
+ }
241
+ catch (error) {
242
+ warnLimited(`send:${path}`, `could not reach ${path}: ${error.message}`);
243
+ return null;
244
+ }
245
+ finally {
246
+ clearTimeout(timeout);
247
+ inflight.delete(controller);
248
+ }
249
+ }
250
+ function send() {
251
+ if (sending)
252
+ return sending;
253
+ sending = (async () => {
254
+ const envelope = JSON.stringify({ sdk: `node/${VERSION}`, app: config.appName });
255
+ while (queue.length && !stopped) {
256
+ // Up to BATCH calls and MAX_BATCH_BYTES per request.
257
+ const parts = [];
258
+ let size = envelope.length + 16;
259
+ while (queue.length && parts.length < BATCH) {
260
+ const entry = queue[0];
261
+ let json;
262
+ try {
263
+ json = prepare(entry);
264
+ }
265
+ catch (error) {
266
+ warnLimited('prepare', `could not prepare a model call: ${error.message}`);
267
+ json = null;
268
+ }
269
+ const bytes = json === null ? 0 : Buffer.byteLength(json);
270
+ if (json !== null && bytes > MAX_CALL_BYTES) {
271
+ warnLimited('oversized', `a model call of ${bytes} bytes is over the ${MAX_CALL_BYTES} byte limit and was dropped`);
272
+ json = null;
273
+ }
274
+ if (json !== null && parts.length && size + bytes + 1 > MAX_BATCH_BYTES)
275
+ break; // send what we have; retry this one next
276
+ queue.shift();
277
+ queuedBytes -= entry.bytes;
278
+ if (json === null)
279
+ continue;
280
+ parts.push(json);
281
+ size += bytes + 1;
282
+ }
283
+ if (!parts.length)
284
+ continue;
285
+ const body = `{"calls":[${parts.join(',')}],${envelope.slice(1)}`;
286
+ const response = await post('/api/platform-collect/sdk', body, SEND_TIMEOUT_MS);
287
+ if (response && !response.ok)
288
+ warnLimited('rejected', `${parts.length} calls not accepted: ${response.status}`);
289
+ }
290
+ })().catch(() => { }).finally(() => { sending = null; });
291
+ return sending;
292
+ }
293
+ /** Wait until recorded calls are sent. Call before a serverless function or script exits. Never throws. */
294
+ export async function flush() {
295
+ if (timer) {
296
+ clearTimeout(timer);
297
+ timer = null;
298
+ }
299
+ try {
300
+ await send();
301
+ }
302
+ catch { /* send already logs */ }
303
+ }
304
+ const scrubText = (value) => (config.scrub ? config.scrub(value) : value);
305
+ /** Mark how a session ended. Returns true when the platform accepted it. Never throws. */
306
+ export async function reportOutcome(sessionId, outcome, note) {
307
+ try {
308
+ if (!apiKey()) {
309
+ warnLimited('no-key', 'GENERALCONTEXT_API_KEY is not set; outcome not reported');
310
+ return false;
311
+ }
312
+ await flush();
313
+ const body = { session_id: scrubText(String(sessionId)), outcome, note: note == null ? null : scrubText(note) };
314
+ const response = await post('/api/platform-collect/outcomes', JSON.stringify(body), DIRECT_TIMEOUT_MS);
315
+ return Boolean(response?.ok);
316
+ }
317
+ catch {
318
+ return false;
319
+ }
320
+ }
321
+ /** Record something that happened in your systems, such as 'order.refunded'. Pass a stable eventId so retries dedupe. Never throws. */
322
+ export async function logEvent(event) {
323
+ try {
324
+ if (!apiKey()) {
325
+ warnLimited('no-key', 'GENERALCONTEXT_API_KEY is not set; event not logged');
326
+ return false;
327
+ }
328
+ await flush();
329
+ const timestamp = event.timestamp instanceof Date ? event.timestamp.toISOString() : event.timestamp ?? new Date().toISOString();
330
+ const properties = Object.fromEntries(Object.entries(event.properties ?? {}).map(([k, v]) => [k, typeof v === 'string' ? scrubText(v) : v]));
331
+ const body = { events: [{
332
+ event_id: event.eventId ?? randomUUID(), event_type: scrubText(event.eventType), timestamp,
333
+ session_id: scrubText(String(event.sessionId)), properties,
334
+ }] };
335
+ const response = await post('/api/platform-collect/events', JSON.stringify(body), DIRECT_TIMEOUT_MS);
336
+ return Boolean(response?.ok);
337
+ }
338
+ catch {
339
+ return false;
340
+ }
341
+ }
342
+ // Wrap an SDK create method. The SDK's own promise is returned untouched; recording happens on a side branch.
343
+ function recording(create, api, scrub) {
344
+ const wrapped = function (...args) {
345
+ const started = new Date().toISOString();
346
+ const at = scope.getStore();
347
+ const request = args[0];
348
+ // Mark the call so the fetch patch does not record it a second time.
349
+ const reply = scope.run({ ...at, inSdkCall: true }, () => create.apply(this, args));
350
+ if (!reply || typeof reply.then !== 'function')
351
+ return reply;
352
+ reply.then(response => {
353
+ const done = (result) => record({ api, request, response: result, started_at: started, ended_at: new Date().toISOString(), error: null }, at, scrub);
354
+ if (request?.stream && isStream(response))
355
+ observeStream(response, api, done);
356
+ else
357
+ done(response);
358
+ }, error => {
359
+ record({ api, request, response: null, started_at: started, ended_at: new Date().toISOString(), error: String(error?.message ?? error) }, at, scrub);
360
+ });
361
+ return reply;
362
+ };
363
+ wrapped[MARK] = true;
364
+ return wrapped;
365
+ }
366
+ const isStream = (value) => typeof value?.iterator === 'function';
367
+ // Both SDKs' Stream classes read chunks through `this.iterator`, including tee() and toReadableStream().
368
+ // Replacing it keeps the object, its type and its methods, and lets us see each chunk once.
369
+ function observeStream(stream, api, done) {
370
+ const source = stream.iterator.bind(stream);
371
+ stream.iterator = async function* () {
372
+ const assemble = api === 'anthropic' ? anthropicAssembler() : openAIAssembler();
373
+ let finished = false;
374
+ try {
375
+ for await (const chunk of { [Symbol.asyncIterator]: source }) {
376
+ try {
377
+ assemble.add(chunk);
378
+ }
379
+ catch { /* never break the caller's stream */ }
380
+ yield chunk;
381
+ }
382
+ finished = true;
383
+ }
384
+ finally {
385
+ if (finished)
386
+ done(assemble.result());
387
+ }
388
+ };
389
+ }
390
+ function openAIAssembler() {
391
+ let model, id, usage = null, final = null;
392
+ const choices = [];
393
+ return {
394
+ add(chunk) {
395
+ // Responses API events: the final response arrives whole.
396
+ if (chunk.type) {
397
+ if (chunk.type === 'response.completed')
398
+ final = chunk.response;
399
+ return;
400
+ }
401
+ model ??= chunk.model;
402
+ id ??= chunk.id;
403
+ if (chunk.usage)
404
+ usage = chunk.usage;
405
+ for (const c of chunk.choices ?? []) {
406
+ const choice = choices[c.index] ??= { index: c.index, message: { role: 'assistant', content: null }, finish_reason: null };
407
+ const d = c.delta ?? {};
408
+ if (d.role)
409
+ choice.message.role = d.role;
410
+ if (d.content)
411
+ choice.message.content = (choice.message.content ?? '') + d.content;
412
+ for (const t of d.tool_calls ?? []) {
413
+ const calls = choice.message.tool_calls ??= [];
414
+ const call = calls[t.index] ??= { id: t.id, type: 'function', function: { name: '', arguments: '' } };
415
+ if (t.id)
416
+ call.id = t.id;
417
+ if (t.function?.name)
418
+ call.function.name += t.function.name;
419
+ if (t.function?.arguments)
420
+ call.function.arguments += t.function.arguments;
421
+ }
422
+ if (c.finish_reason)
423
+ choice.finish_reason = c.finish_reason;
424
+ }
425
+ },
426
+ result: () => final ?? ({ id, object: 'chat.completion', model, choices: choices.filter(Boolean), usage }),
427
+ };
428
+ }
429
+ function anthropicAssembler() {
430
+ let message = null;
431
+ const json = [];
432
+ return {
433
+ add(event) {
434
+ if (event.type === 'message_start')
435
+ message = { ...event.message, content: [] };
436
+ else if (!message)
437
+ return;
438
+ else if (event.type === 'content_block_start') {
439
+ message.content[event.index] = { ...event.content_block };
440
+ json[event.index] = '';
441
+ }
442
+ else if (event.type === 'content_block_delta') {
443
+ const block = message.content[event.index], d = event.delta;
444
+ if (d.type === 'text_delta')
445
+ block.text = (block.text ?? '') + d.text;
446
+ else if (d.type === 'input_json_delta')
447
+ json[event.index] += d.partial_json;
448
+ else if (d.type === 'thinking_delta')
449
+ block.thinking = (block.thinking ?? '') + d.thinking;
450
+ }
451
+ else if (event.type === 'content_block_stop') {
452
+ const block = message.content[event.index];
453
+ if (json[event.index]) {
454
+ try {
455
+ block.input = JSON.parse(json[event.index]);
456
+ }
457
+ catch {
458
+ block.input = json[event.index];
459
+ }
460
+ }
461
+ }
462
+ else if (event.type === 'message_delta') {
463
+ Object.assign(message, event.delta);
464
+ message.usage = { ...message.usage, ...event.usage };
465
+ }
466
+ },
467
+ result: () => message,
468
+ };
469
+ }
470
+ // Record raw fetch POSTs to chat-completions endpoints made without a patched SDK.
471
+ function patchFetch() {
472
+ const current = globalThis.fetch;
473
+ if (typeof current !== 'function' || current[MARK])
474
+ return;
475
+ originalFetch = current;
476
+ const patched = async function (input, init) {
477
+ const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
478
+ const method = (init?.method ?? (input instanceof Request ? input.method : 'GET')).toUpperCase();
479
+ const at = scope.getStore();
480
+ const watch = method === 'POST' && /\/chat\/completions\/?(\?.*)?$/.test(url) && !at?.inSdkCall && !url.startsWith(`${baseUrl()}/api/platform-collect/`);
481
+ if (!watch)
482
+ return current(input, init);
483
+ const started = new Date().toISOString();
484
+ let request = null;
485
+ try {
486
+ request = typeof init?.body === 'string' ? JSON.parse(init.body) : input instanceof Request ? await input.clone().json() : null;
487
+ }
488
+ catch { /* not JSON */ }
489
+ const base = { api: 'openai-chat', request, started_at: started };
490
+ let response;
491
+ try {
492
+ response = await current(input, init);
493
+ }
494
+ catch (error) {
495
+ record({ ...base, response: null, ended_at: new Date().toISOString(), error: String(error?.message ?? error) }, at);
496
+ throw error;
497
+ }
498
+ try {
499
+ const copy = response.clone();
500
+ void (async () => {
501
+ try {
502
+ const text = await copy.text();
503
+ const ended = new Date().toISOString();
504
+ if (!response.ok)
505
+ return record({ ...base, response: null, ended_at: ended, error: `HTTP ${response.status}: ${text.slice(0, 500)}` }, at);
506
+ const sse = (response.headers.get('content-type') ?? '').includes('text/event-stream');
507
+ record({ ...base, response: sse ? assembleSSE(text) : JSON.parse(text), ended_at: ended, error: null }, at);
508
+ }
509
+ catch (error) {
510
+ warn(`could not record a fetch call: ${error.message}`);
511
+ }
512
+ })();
513
+ }
514
+ catch { /* body already used */ }
515
+ return response;
516
+ };
517
+ patched[MARK] = true;
518
+ globalThis.fetch = patched;
519
+ }
520
+ function assembleSSE(text) {
521
+ const assemble = openAIAssembler();
522
+ for (const line of text.split('\n')) {
523
+ const data = line.startsWith('data:') ? line.slice(5).trim() : '';
524
+ if (data && data !== '[DONE]') {
525
+ try {
526
+ assemble.add(JSON.parse(data));
527
+ }
528
+ catch { /* skip bad event */ }
529
+ }
530
+ }
531
+ return assemble.result();
532
+ }
533
+ const PATTERNS = [
534
+ // Bounded repeats and a token-start lookbehind keep this linear on adversarial input.
535
+ ['email', /(?<![A-Za-z0-9._%+-])[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9-]{1,63}(?:\.[A-Za-z0-9-]{1,63}){0,8}\.[A-Za-z]{2,24}/g],
536
+ ['card', /\b(?:\d[ -]?){13,16}\b/g],
537
+ ['ssn', /\b\d{3}-\d{2}-\d{4}\b/g],
538
+ ['phone', /(?<![\w])\+?1?[\s.-]?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}(?![\w])/g],
539
+ ];
540
+ function redactor(redact) {
541
+ if (typeof redact === 'function')
542
+ return redact;
543
+ if (!redact)
544
+ return null;
545
+ let salt = process.env.GENERALCONTEXT_REDACT_SALT;
546
+ if (!salt) {
547
+ warn('GENERALCONTEXT_REDACT_SALT is not set; placeholders will differ between processes');
548
+ salt = randomBytes(16).toString('hex');
549
+ }
550
+ const placeholder = (kind, value) => {
551
+ const digits = value.replace(/\D/g, '');
552
+ const normal = kind === 'email' ? value.toLowerCase() : kind === 'phone' ? digits.slice(-10) : digits;
553
+ return `<${kind}:${createHmac('sha256', salt).update(normal).digest('hex').slice(0, 6)}>`;
554
+ };
555
+ return text => PATTERNS.reduce((result, [kind, pattern]) => result.replace(pattern, match => placeholder(kind, match)), text);
556
+ }
557
+ function scrubbed(value, scrub) {
558
+ if (!scrub)
559
+ return value;
560
+ if (typeof value === 'string')
561
+ return scrub(value);
562
+ if (Array.isArray(value))
563
+ return value.map(item => scrubbed(item, scrub));
564
+ if (value && typeof value === 'object')
565
+ return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, scrubbed(item, scrub)]));
566
+ return value;
567
+ }
568
+ /**
569
+ * Record one client instance only, without initialize(). Returns the same client.
570
+ * `redact` applies to this client only. If initialize() already patched the SDK, its settings apply instead.
571
+ */
572
+ export function wrap(client, options = {}) {
573
+ if (disabledByEnv())
574
+ return client;
575
+ const scrub = options.redact === undefined ? undefined : redactor(options.redact);
576
+ const target = client;
577
+ const owners = [];
578
+ if (target.chat?.completions?.create)
579
+ owners.push([target.chat.completions, 'openai-chat']);
580
+ if (target.responses?.create)
581
+ owners.push([target.responses, 'openai-responses']);
582
+ if (!target.chat && target.messages?.create)
583
+ owners.push([target.messages, 'anthropic']);
584
+ if (!owners.length)
585
+ throw new TypeError('wrap expects an OpenAI or Anthropic client');
586
+ for (const [owner, api] of owners) {
587
+ if (!owner.create[MARK])
588
+ owner.create = recording(owner.create.bind(owner), api, scrub);
589
+ }
590
+ return client;
591
+ }
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "generalcontext",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Record your agent's OpenAI and Anthropic calls for General Context review and testing.",
5
+ "license": "Apache-2.0",
6
+ "author": "General Context Labs <research@generalcontextlabs.com>",
7
+ "homepage": "https://generalcontextlabs.com/platform/docs/sdk",
8
+ "bugs": "https://github.com/GeneralContext/sdk/issues",
9
+ "keywords": ["llm", "agents", "observability", "evaluation", "openai", "anthropic", "opentelemetry"],
10
+ "type": "module",
11
+ "main": "dist/index.js",
12
+ "types": "dist/index.d.ts",
13
+ "files": [
14
+ "dist",
15
+ "LICENSE",
16
+ "NOTICE"
17
+ ],
18
+ "engines": {
19
+ "node": ">=18"
20
+ },
21
+ "scripts": {
22
+ "build": "tsc -p .",
23
+ "test": "tsc -p . && node --test test/*.test.mjs",
24
+ "prepublishOnly": "npm test"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "devDependencies": {
30
+ "@anthropic-ai/sdk": "^1.6.0",
31
+ "@types/node": "^22.20.5",
32
+ "openai": "^7.53.0",
33
+ "typescript": "^5.9.3"
34
+ },
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/GeneralContext/sdk.git",
38
+ "directory": "node"
39
+ }
40
+ }