@cultured_computer/sight 0.5.0 → 0.6.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/README.md +43 -28
- package/dist/cli.js +10 -4
- package/dist/index.cjs +360 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +37 -1
- package/dist/index.d.ts +37 -1
- package/dist/index.js +360 -2
- package/dist/index.js.map +1 -1
- package/package.json +3 -5
package/README.md
CHANGED
|
@@ -59,29 +59,6 @@ Notes:
|
|
|
59
59
|
stable, pseudonymous user id you supply. Return metrics key on the user id;
|
|
60
60
|
sessions without it still capture, but return behaviour is not computable.
|
|
61
61
|
|
|
62
|
-
## Connect a community you don't serve: the CLI, no account
|
|
63
|
-
|
|
64
|
-
The SDK above captures from *inside* your serving path. The bundled `sight` CLI
|
|
65
|
-
does the other end: it attaches Sight to a world you do **not** serve (a buzz
|
|
66
|
-
relay/community) as a read-only observer, with **no account and no dashboard
|
|
67
|
-
signup**:
|
|
68
|
-
|
|
69
|
-
```bash
|
|
70
|
-
npx @cultured_computer/sight connect https://your-relay.example --invite <code> [--pulse]
|
|
71
|
-
```
|
|
72
|
-
|
|
73
|
-
- `--invite` is a single-use code you mint on your own relay (its admin surface,
|
|
74
|
-
or `POST /api/invites` as the community owner). The invite is the
|
|
75
|
-
authorization; Sight can never enter a community you did not invite it into.
|
|
76
|
-
- `--pulse` opts into the daily readout (counts, times, and links only;
|
|
77
|
-
off by default).
|
|
78
|
-
|
|
79
|
-
It prints a **claim link**: the archive (sessions, measurements, the label
|
|
80
|
-
queue, and any billing later) attaches when and if you claim it, so you can run
|
|
81
|
-
the whole thing before creating an account. Both lanes share one project.
|
|
82
|
-
The full walkthrough lives at
|
|
83
|
-
[Connect your buzz community](https://sight.cultured.computer/docs/connect-your-room).
|
|
84
|
-
|
|
85
62
|
## Pull your own data out: the CLI, from your terminal
|
|
86
63
|
|
|
87
64
|
The `sight` CLI also carries out data from projects you **own**, with no
|
|
@@ -96,6 +73,9 @@ npx @cultured_computer/sight auth login
|
|
|
96
73
|
# then pull a deployment's full record
|
|
97
74
|
npx @cultured_computer/sight export --project <slug> --deployment <slug> --out data.jsonl
|
|
98
75
|
|
|
76
|
+
# or pull the readings: the per-turn judge labels (closure, backward-pass, ...)
|
|
77
|
+
npx @cultured_computer/sight export --project <slug> --deployment <slug> --readings --out readings.jsonl
|
|
78
|
+
|
|
99
79
|
# sign out when you're done
|
|
100
80
|
npx @cultured_computer/sight auth logout
|
|
101
81
|
```
|
|
@@ -109,15 +89,45 @@ npx @cultured_computer/sight auth logout
|
|
|
109
89
|
Tier-2 redacted shape the dashboard produces. It is owner-only: the token is
|
|
110
90
|
your session, so the carry-out gate is exactly the dashboard's. Members read
|
|
111
91
|
in-product; owners carry the dataset out.
|
|
92
|
+
- `--readings` pulls the graded reads instead of the record: one line per
|
|
93
|
+
per-turn judge label (closure, backward-pass, and the rest), with the rubric
|
|
94
|
+
version and judge-model pin. These are the re-computable evidence layer over
|
|
95
|
+
the record, not part of the versioned record schema.
|
|
112
96
|
- `--out <file>` writes to a file; omit it to stream to stdout.
|
|
113
97
|
|
|
98
|
+
One more CLI door, for a different shape: `sight connect` attaches Sight to a
|
|
99
|
+
buzz community you don't serve as a read-only observer (invite-code
|
|
100
|
+
authorization, no account needed up front). A side lane, not the install —
|
|
101
|
+
the walkthrough lives at
|
|
102
|
+
[Connect your buzz community](https://sight.cultured.computer/docs/connect-your-room).
|
|
103
|
+
|
|
114
104
|
## What lands automatically
|
|
115
105
|
|
|
116
|
-
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
106
|
+
- **OpenAI: wrap your client.** This is the reliable autocapture path and
|
|
107
|
+
the one to use in every new integration:
|
|
108
|
+
|
|
109
|
+
```ts
|
|
110
|
+
import OpenAI from 'openai';
|
|
111
|
+
import { Sight, wrapOpenAI } from '@cultured_computer/sight';
|
|
112
|
+
|
|
113
|
+
const openai = wrapOpenAI(new OpenAI());
|
|
114
|
+
// Every chat.completions.create and responses.create call on this
|
|
115
|
+
// client is now captured, streaming included. Wrap before or after
|
|
116
|
+
// Sight.init(); order does not matter.
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
Module-level autocapture (no wrap call) also exists but has hard limits:
|
|
120
|
+
it attaches only under CommonJS, only when `openai` loads after `init`,
|
|
121
|
+
and only for openai v4 (the underlying instrumentation does not support
|
|
122
|
+
v5+). When it cannot attach, the SDK now prints a warning naming
|
|
123
|
+
`wrapOpenAI` instead of failing silently. If you run ESM or openai v5+,
|
|
124
|
+
wrap the client.
|
|
125
|
+
- Module-level autocapture is on from `init` for calls made through the
|
|
126
|
+
Anthropic SDK, Vercel AI SDK, LangChain, and LangGraph in the process,
|
|
127
|
+
with the same CommonJS and load-order caveats. Each adapter no-ops if
|
|
128
|
+
its target library is not installed. Mercury-2 reached through the
|
|
129
|
+
OpenAI SDK with a baseURL override is captured and tagged by provider;
|
|
130
|
+
`wrapOpenAI` applies there too.
|
|
121
131
|
- Plumbing fields populate with no further configuration: model, tokens,
|
|
122
132
|
latency, cost, tool calls, finish reason.
|
|
123
133
|
- Turns are grouped into sessions by the ids you supply; sessions are created
|
|
@@ -226,6 +236,11 @@ consequences. See [Data format](https://sight.cultured.computer/docs/data-format
|
|
|
226
236
|
- [Status](https://sight.cultured.computer/docs/where-it-stands): what
|
|
227
237
|
is available now versus in beta.
|
|
228
238
|
|
|
239
|
+
## Legal
|
|
240
|
+
|
|
241
|
+
[Privacy Policy](https://sight.cultured.computer/privacy) and
|
|
242
|
+
[Terms of Service](https://sight.cultured.computer/terms).
|
|
243
|
+
|
|
229
244
|
## License
|
|
230
245
|
|
|
231
246
|
MIT (c) Cultured Computer
|
package/dist/cli.js
CHANGED
|
@@ -19,7 +19,7 @@ function usage() {
|
|
|
19
19
|
" sight connect <relay-url> --invite <code> [--pulse] [--api <base>]",
|
|
20
20
|
" sight auth login [--base <dashboard-url>]",
|
|
21
21
|
" sight auth logout",
|
|
22
|
-
" sight export --project <slug> --deployment <slug> [--out file.jsonl]",
|
|
22
|
+
" sight export --project <slug> --deployment <slug> [--readings] [--out file.jsonl]",
|
|
23
23
|
"",
|
|
24
24
|
" connect attach Sight to a buzz community as a read-only observer.",
|
|
25
25
|
" --invite one single-use invite code, minted by you on",
|
|
@@ -35,6 +35,9 @@ function usage() {
|
|
|
35
35
|
" token lives at ~/.config/sight/credentials.json (0600).",
|
|
36
36
|
" export pull a deployment\u2019s full record (RLDS JSONL) with that",
|
|
37
37
|
" token. Owner role on the project required.",
|
|
38
|
+
" --readings pull the per-turn judge labels (the graded",
|
|
39
|
+
" reads: closure, backward-pass, and the rest)",
|
|
40
|
+
" instead of the record.",
|
|
38
41
|
"",
|
|
39
42
|
"The SDK half of this package (serving-path capture) is documented at",
|
|
40
43
|
"https://sight.cultured.computer/docs (the two lanes share one project)."
|
|
@@ -204,8 +207,9 @@ async function exportRecord(args) {
|
|
|
204
207
|
const project = flag(args, "--project");
|
|
205
208
|
const deployment = flag(args, "--deployment");
|
|
206
209
|
const out = flag(args, "--out") ?? null;
|
|
210
|
+
const readings = args.includes("--readings");
|
|
207
211
|
if (!project || !deployment) {
|
|
208
|
-
console.error("usage: sight export --project <slug> --deployment <slug> [--out file.jsonl]");
|
|
212
|
+
console.error("usage: sight export --project <slug> --deployment <slug> [--readings] [--out file.jsonl]");
|
|
209
213
|
return 1;
|
|
210
214
|
}
|
|
211
215
|
const creds = readCredentials();
|
|
@@ -213,7 +217,7 @@ async function exportRecord(args) {
|
|
|
213
217
|
console.error("no stored login \u2014 run sight auth login first.");
|
|
214
218
|
return 1;
|
|
215
219
|
}
|
|
216
|
-
const url = `${creds.base}/api/export?project=${encodeURIComponent(project)}&deployment=${encodeURIComponent(deployment)}
|
|
220
|
+
const url = `${creds.base}/api/export?project=${encodeURIComponent(project)}&deployment=${encodeURIComponent(deployment)}` + (readings ? "&kind=readings" : "");
|
|
217
221
|
const res = await fetch(url, {
|
|
218
222
|
headers: { authorization: `Bearer ${creds.token}` }
|
|
219
223
|
}).catch((err) => ({ __err: err }));
|
|
@@ -227,7 +231,9 @@ async function exportRecord(args) {
|
|
|
227
231
|
const text = await res.text();
|
|
228
232
|
if (out) {
|
|
229
233
|
writeFileSync(out, text);
|
|
230
|
-
console.log(
|
|
234
|
+
console.log(
|
|
235
|
+
`exported to ${out} (${text.split("\n").filter(Boolean).length} ${readings ? "readings" : "episodes"}).`
|
|
236
|
+
);
|
|
231
237
|
} else {
|
|
232
238
|
process.stdout.write(text);
|
|
233
239
|
}
|
package/dist/index.cjs
CHANGED
|
@@ -733,8 +733,10 @@ function extractSystemPromptText(attrs) {
|
|
|
733
733
|
return void 0;
|
|
734
734
|
}
|
|
735
735
|
async function maybeAutoStampEnvironmentConfig(session, attrs) {
|
|
736
|
+
await autoStampFromSystemText(session, extractSystemPromptText(attrs));
|
|
737
|
+
}
|
|
738
|
+
async function autoStampFromSystemText(session, systemText) {
|
|
736
739
|
if (session.environmentConfigHash != null) return;
|
|
737
|
-
const systemText = extractSystemPromptText(attrs);
|
|
738
740
|
if (!systemText) return;
|
|
739
741
|
const hash = await hashEnvironmentConfig(systemText);
|
|
740
742
|
if (session.environmentConfigHash != null) return;
|
|
@@ -839,6 +841,342 @@ var ProbeSpanProcessor = class {
|
|
|
839
841
|
}
|
|
840
842
|
};
|
|
841
843
|
|
|
844
|
+
// src/instrumentation/wrap-openai.ts
|
|
845
|
+
var bound = null;
|
|
846
|
+
var warnedUnbound = false;
|
|
847
|
+
function bindWrapOpenAI(state2, captureFn) {
|
|
848
|
+
bound = { state: state2, captureFn };
|
|
849
|
+
}
|
|
850
|
+
function unbindWrapOpenAI() {
|
|
851
|
+
bound = null;
|
|
852
|
+
}
|
|
853
|
+
var WRAPPED = /* @__PURE__ */ Symbol.for("sight.wrapOpenAI");
|
|
854
|
+
function asRecord(v) {
|
|
855
|
+
return v !== null && typeof v === "object" ? v : void 0;
|
|
856
|
+
}
|
|
857
|
+
function asString2(v) {
|
|
858
|
+
return typeof v === "string" ? v : void 0;
|
|
859
|
+
}
|
|
860
|
+
function asNumber2(v) {
|
|
861
|
+
return typeof v === "number" ? v : void 0;
|
|
862
|
+
}
|
|
863
|
+
function messageText2(content) {
|
|
864
|
+
if (typeof content === "string") return content;
|
|
865
|
+
if (Array.isArray(content)) {
|
|
866
|
+
const parts = [];
|
|
867
|
+
for (const part of content) {
|
|
868
|
+
if (typeof part === "string") parts.push(part);
|
|
869
|
+
else {
|
|
870
|
+
const p = asRecord(part);
|
|
871
|
+
const text = p?.["text"] ?? p?.["content"];
|
|
872
|
+
if (typeof text === "string") parts.push(text);
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
return parts.length > 0 ? parts.join("\n") : void 0;
|
|
876
|
+
}
|
|
877
|
+
return void 0;
|
|
878
|
+
}
|
|
879
|
+
function systemTextFromParams(params) {
|
|
880
|
+
if (!params) return void 0;
|
|
881
|
+
const instructions = asString2(params["instructions"]);
|
|
882
|
+
if (instructions && instructions.length > 0) return instructions;
|
|
883
|
+
const messages = params["messages"];
|
|
884
|
+
if (Array.isArray(messages)) {
|
|
885
|
+
for (const raw of messages) {
|
|
886
|
+
const m = asRecord(raw);
|
|
887
|
+
if (m && (m["role"] === "system" || m["role"] === "developer")) {
|
|
888
|
+
const text = messageText2(m["content"]);
|
|
889
|
+
if (text) return text;
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
}
|
|
893
|
+
return void 0;
|
|
894
|
+
}
|
|
895
|
+
function providerFor(model) {
|
|
896
|
+
return model?.toLowerCase().startsWith("mercury") ? "inception" : "openai";
|
|
897
|
+
}
|
|
898
|
+
function payloadFromChatResponse(r, requestModel) {
|
|
899
|
+
const choice = Array.isArray(r["choices"]) ? asRecord(r["choices"][0]) : void 0;
|
|
900
|
+
const message = asRecord(choice?.["message"]);
|
|
901
|
+
const usage = asRecord(r["usage"]);
|
|
902
|
+
const promptDetails = asRecord(usage?.["prompt_tokens_details"]);
|
|
903
|
+
const toolCalls = Array.isArray(message?.["tool_calls"]) ? message["tool_calls"] : void 0;
|
|
904
|
+
const toolNames = toolCalls?.map((t) => asString2(asRecord(asRecord(t)?.["function"])?.["name"])).filter((n) => typeof n === "string");
|
|
905
|
+
return {
|
|
906
|
+
model: asString2(r["model"]) ?? requestModel,
|
|
907
|
+
text: messageText2(message?.["content"]),
|
|
908
|
+
tokensInput: asNumber2(usage?.["prompt_tokens"]),
|
|
909
|
+
tokensOutput: asNumber2(usage?.["completion_tokens"]),
|
|
910
|
+
cachedTokens: asNumber2(promptDetails?.["cached_tokens"]),
|
|
911
|
+
finishReason: asString2(choice?.["finish_reason"]),
|
|
912
|
+
toolNames
|
|
913
|
+
};
|
|
914
|
+
}
|
|
915
|
+
function payloadFromResponsesResponse(r, requestModel) {
|
|
916
|
+
const usage = asRecord(r["usage"]);
|
|
917
|
+
const inputDetails = asRecord(usage?.["input_tokens_details"]);
|
|
918
|
+
let text = asString2(r["output_text"]);
|
|
919
|
+
const toolNames = [];
|
|
920
|
+
if (Array.isArray(r["output"])) {
|
|
921
|
+
const texts = [];
|
|
922
|
+
for (const raw of r["output"]) {
|
|
923
|
+
const item = asRecord(raw);
|
|
924
|
+
if (!item) continue;
|
|
925
|
+
if (item["type"] === "function_call") {
|
|
926
|
+
const name = asString2(item["name"]);
|
|
927
|
+
if (name) toolNames.push(name);
|
|
928
|
+
}
|
|
929
|
+
if (item["type"] === "message" && Array.isArray(item["content"])) {
|
|
930
|
+
for (const c of item["content"]) {
|
|
931
|
+
const cr = asRecord(c);
|
|
932
|
+
if (cr?.["type"] === "output_text") {
|
|
933
|
+
const t = asString2(cr["text"]);
|
|
934
|
+
if (t) texts.push(t);
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
if (!text && texts.length > 0) text = texts.join("\n");
|
|
940
|
+
}
|
|
941
|
+
return {
|
|
942
|
+
model: asString2(r["model"]) ?? requestModel,
|
|
943
|
+
text,
|
|
944
|
+
tokensInput: asNumber2(usage?.["input_tokens"]),
|
|
945
|
+
tokensOutput: asNumber2(usage?.["output_tokens"]),
|
|
946
|
+
cachedTokens: asNumber2(inputDetails?.["cached_tokens"]),
|
|
947
|
+
finishReason: asString2(r["status"]),
|
|
948
|
+
toolNames: toolNames.length > 0 ? toolNames : void 0
|
|
949
|
+
};
|
|
950
|
+
}
|
|
951
|
+
function buildTurnPayload(x, latencyMs, api) {
|
|
952
|
+
return {
|
|
953
|
+
probe_tokens_input: x.tokensInput,
|
|
954
|
+
probe_tokens_output: x.tokensOutput,
|
|
955
|
+
probe_latency_ms: latencyMs,
|
|
956
|
+
probe_model: x.model,
|
|
957
|
+
probe_provider: providerFor(x.model),
|
|
958
|
+
probe_tool_calls: x.toolNames?.length,
|
|
959
|
+
probe_tool_names: x.toolNames,
|
|
960
|
+
probe_error: void 0,
|
|
961
|
+
probe_finish_reason: x.finishReason,
|
|
962
|
+
response: x.text ? { text: x.text } : void 0,
|
|
963
|
+
probe_cache_read_input_tokens: x.cachedTokens,
|
|
964
|
+
_wrap: { api, adapter: "wrapOpenAI" }
|
|
965
|
+
};
|
|
966
|
+
}
|
|
967
|
+
function emit(params, payload) {
|
|
968
|
+
if (!bound) {
|
|
969
|
+
if (!warnedUnbound) {
|
|
970
|
+
warnedUnbound = true;
|
|
971
|
+
console.warn(
|
|
972
|
+
"[sight] wrapOpenAI: call observed before Probe.init(); nothing captured until init runs."
|
|
973
|
+
);
|
|
974
|
+
}
|
|
975
|
+
return;
|
|
976
|
+
}
|
|
977
|
+
const { state: state2, captureFn } = bound;
|
|
978
|
+
const sessionId = getCurrentSessionId();
|
|
979
|
+
if (!sessionId) {
|
|
980
|
+
if (state2.config.debug) {
|
|
981
|
+
console.warn(
|
|
982
|
+
"[sight] wrapOpenAI: call with no session context; skipped (wrap calls in Probe.withSession())."
|
|
983
|
+
);
|
|
984
|
+
}
|
|
985
|
+
return;
|
|
986
|
+
}
|
|
987
|
+
const { session, sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(
|
|
988
|
+
state2,
|
|
989
|
+
sessionId
|
|
990
|
+
);
|
|
991
|
+
const captured = {
|
|
992
|
+
deploymentSlug: state2.config.deployment,
|
|
993
|
+
sessionExternalId,
|
|
994
|
+
turnIndex,
|
|
995
|
+
personaSlug: personaSlug ?? void 0,
|
|
996
|
+
payload
|
|
997
|
+
};
|
|
998
|
+
void (async () => {
|
|
999
|
+
await autoStampFromSystemText(session, systemTextFromParams(params));
|
|
1000
|
+
await captureFn(captured);
|
|
1001
|
+
})().catch((err) => {
|
|
1002
|
+
if (state2.config.debug) {
|
|
1003
|
+
console.error(`[sight] wrapOpenAI capture error: ${err instanceof Error ? err.message : err}`);
|
|
1004
|
+
}
|
|
1005
|
+
});
|
|
1006
|
+
}
|
|
1007
|
+
function teeStream(stream, onChunk, onDone) {
|
|
1008
|
+
let done = false;
|
|
1009
|
+
const finish = () => {
|
|
1010
|
+
if (!done) {
|
|
1011
|
+
done = true;
|
|
1012
|
+
onDone();
|
|
1013
|
+
}
|
|
1014
|
+
};
|
|
1015
|
+
return new Proxy(stream, {
|
|
1016
|
+
get(target, prop, receiver) {
|
|
1017
|
+
if (prop === Symbol.asyncIterator) {
|
|
1018
|
+
return function() {
|
|
1019
|
+
const inner = target[Symbol.asyncIterator]();
|
|
1020
|
+
return {
|
|
1021
|
+
async next() {
|
|
1022
|
+
try {
|
|
1023
|
+
const r = await inner.next();
|
|
1024
|
+
if (r.done) finish();
|
|
1025
|
+
else onChunk(r.value);
|
|
1026
|
+
return r;
|
|
1027
|
+
} catch (err) {
|
|
1028
|
+
finish();
|
|
1029
|
+
throw err;
|
|
1030
|
+
}
|
|
1031
|
+
},
|
|
1032
|
+
async return(value2) {
|
|
1033
|
+
finish();
|
|
1034
|
+
return inner.return ? inner.return(value2) : { done: true, value: value2 };
|
|
1035
|
+
},
|
|
1036
|
+
async throw(err) {
|
|
1037
|
+
finish();
|
|
1038
|
+
if (inner.throw) return inner.throw(err);
|
|
1039
|
+
throw err;
|
|
1040
|
+
}
|
|
1041
|
+
};
|
|
1042
|
+
};
|
|
1043
|
+
}
|
|
1044
|
+
const value = Reflect.get(target, prop, receiver);
|
|
1045
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
1046
|
+
}
|
|
1047
|
+
});
|
|
1048
|
+
}
|
|
1049
|
+
function chatStreamAccumulator(requestModel) {
|
|
1050
|
+
const texts = [];
|
|
1051
|
+
let model = requestModel;
|
|
1052
|
+
let finishReason;
|
|
1053
|
+
let tokensInput;
|
|
1054
|
+
let tokensOutput;
|
|
1055
|
+
let cachedTokens;
|
|
1056
|
+
return {
|
|
1057
|
+
onChunk(chunk) {
|
|
1058
|
+
const c = asRecord(chunk);
|
|
1059
|
+
if (!c) return;
|
|
1060
|
+
model = asString2(c["model"]) ?? model;
|
|
1061
|
+
const choice = Array.isArray(c["choices"]) ? asRecord(c["choices"][0]) : void 0;
|
|
1062
|
+
const delta = asRecord(choice?.["delta"]);
|
|
1063
|
+
const t = asString2(delta?.["content"]);
|
|
1064
|
+
if (t) texts.push(t);
|
|
1065
|
+
finishReason = asString2(choice?.["finish_reason"]) ?? finishReason;
|
|
1066
|
+
const usage = asRecord(c["usage"]);
|
|
1067
|
+
if (usage) {
|
|
1068
|
+
tokensInput = asNumber2(usage["prompt_tokens"]) ?? tokensInput;
|
|
1069
|
+
tokensOutput = asNumber2(usage["completion_tokens"]) ?? tokensOutput;
|
|
1070
|
+
cachedTokens = asNumber2(asRecord(usage["prompt_tokens_details"])?.["cached_tokens"]) ?? cachedTokens;
|
|
1071
|
+
}
|
|
1072
|
+
},
|
|
1073
|
+
result: () => ({
|
|
1074
|
+
model,
|
|
1075
|
+
text: texts.length > 0 ? texts.join("") : void 0,
|
|
1076
|
+
tokensInput,
|
|
1077
|
+
tokensOutput,
|
|
1078
|
+
cachedTokens,
|
|
1079
|
+
finishReason,
|
|
1080
|
+
toolNames: void 0
|
|
1081
|
+
})
|
|
1082
|
+
};
|
|
1083
|
+
}
|
|
1084
|
+
function responsesStreamAccumulator(requestModel) {
|
|
1085
|
+
const texts = [];
|
|
1086
|
+
let final = null;
|
|
1087
|
+
return {
|
|
1088
|
+
onChunk(chunk) {
|
|
1089
|
+
const c = asRecord(chunk);
|
|
1090
|
+
if (!c) return;
|
|
1091
|
+
if (c["type"] === "response.output_text.delta") {
|
|
1092
|
+
const t = asString2(c["delta"]);
|
|
1093
|
+
if (t) texts.push(t);
|
|
1094
|
+
}
|
|
1095
|
+
if (c["type"] === "response.completed") {
|
|
1096
|
+
const response = asRecord(c["response"]);
|
|
1097
|
+
if (response) final = payloadFromResponsesResponse(response, requestModel);
|
|
1098
|
+
}
|
|
1099
|
+
},
|
|
1100
|
+
result: () => {
|
|
1101
|
+
if (final) {
|
|
1102
|
+
return { ...final, text: final.text ?? (texts.length > 0 ? texts.join("") : void 0) };
|
|
1103
|
+
}
|
|
1104
|
+
return {
|
|
1105
|
+
model: requestModel,
|
|
1106
|
+
text: texts.length > 0 ? texts.join("") : void 0,
|
|
1107
|
+
tokensInput: void 0,
|
|
1108
|
+
tokensOutput: void 0,
|
|
1109
|
+
cachedTokens: void 0,
|
|
1110
|
+
finishReason: void 0,
|
|
1111
|
+
toolNames: void 0
|
|
1112
|
+
};
|
|
1113
|
+
}
|
|
1114
|
+
};
|
|
1115
|
+
}
|
|
1116
|
+
function wrapCreate(target, api, makeAccumulator, extractResponse) {
|
|
1117
|
+
const original = target["create"];
|
|
1118
|
+
if (typeof original !== "function") return;
|
|
1119
|
+
target["create"] = function(...args) {
|
|
1120
|
+
const params = asRecord(args[0]);
|
|
1121
|
+
const requestModel = asString2(params?.["model"]);
|
|
1122
|
+
const startedAt = Date.now();
|
|
1123
|
+
const result = original.apply(this, args);
|
|
1124
|
+
if (!result || typeof result.then !== "function") return result;
|
|
1125
|
+
return result.then(
|
|
1126
|
+
(resolved) => {
|
|
1127
|
+
try {
|
|
1128
|
+
const isStream = resolved !== null && typeof resolved === "object" && Symbol.asyncIterator in resolved;
|
|
1129
|
+
if (isStream) {
|
|
1130
|
+
const acc = makeAccumulator(requestModel);
|
|
1131
|
+
return teeStream(resolved, acc.onChunk, () => {
|
|
1132
|
+
emit(params, buildTurnPayload(acc.result(), Date.now() - startedAt, api));
|
|
1133
|
+
});
|
|
1134
|
+
}
|
|
1135
|
+
const r = asRecord(resolved);
|
|
1136
|
+
if (r) {
|
|
1137
|
+
emit(params, buildTurnPayload(extractResponse(r, requestModel), Date.now() - startedAt, api));
|
|
1138
|
+
}
|
|
1139
|
+
return resolved;
|
|
1140
|
+
} catch {
|
|
1141
|
+
return resolved;
|
|
1142
|
+
}
|
|
1143
|
+
},
|
|
1144
|
+
(err) => {
|
|
1145
|
+
try {
|
|
1146
|
+
const x = {
|
|
1147
|
+
model: requestModel,
|
|
1148
|
+
text: void 0,
|
|
1149
|
+
tokensInput: void 0,
|
|
1150
|
+
tokensOutput: void 0,
|
|
1151
|
+
cachedTokens: void 0,
|
|
1152
|
+
finishReason: void 0,
|
|
1153
|
+
toolNames: void 0
|
|
1154
|
+
};
|
|
1155
|
+
const payload = buildTurnPayload(x, Date.now() - startedAt, api);
|
|
1156
|
+
payload.probe_error = err instanceof Error ? err.message : String(err);
|
|
1157
|
+
emit(params, payload);
|
|
1158
|
+
} catch {
|
|
1159
|
+
}
|
|
1160
|
+
throw err;
|
|
1161
|
+
}
|
|
1162
|
+
);
|
|
1163
|
+
};
|
|
1164
|
+
}
|
|
1165
|
+
function wrapOpenAI(client) {
|
|
1166
|
+
const c = client;
|
|
1167
|
+
if (c[WRAPPED]) return client;
|
|
1168
|
+
c[WRAPPED] = true;
|
|
1169
|
+
const completions = asRecord(asRecord(c["chat"])?.["completions"]);
|
|
1170
|
+
if (completions) {
|
|
1171
|
+
wrapCreate(completions, "chat", chatStreamAccumulator, payloadFromChatResponse);
|
|
1172
|
+
}
|
|
1173
|
+
const responses = asRecord(c["responses"]);
|
|
1174
|
+
if (responses) {
|
|
1175
|
+
wrapCreate(responses, "responses", responsesStreamAccumulator, payloadFromResponsesResponse);
|
|
1176
|
+
}
|
|
1177
|
+
return client;
|
|
1178
|
+
}
|
|
1179
|
+
|
|
842
1180
|
// src/instrumentation/setup.ts
|
|
843
1181
|
var installedProcessor = null;
|
|
844
1182
|
function setupOtelProvider(state2, captureFn) {
|
|
@@ -861,6 +1199,7 @@ function setupOtelProvider(state2, captureFn) {
|
|
|
861
1199
|
}
|
|
862
1200
|
function detachOtelState() {
|
|
863
1201
|
installedProcessor?.rebind(null);
|
|
1202
|
+
unbindWrapOpenAI();
|
|
864
1203
|
}
|
|
865
1204
|
|
|
866
1205
|
// src/instrumentation/openai.ts
|
|
@@ -882,6 +1221,7 @@ async function registerOpenAI(state2) {
|
|
|
882
1221
|
});
|
|
883
1222
|
instrumentation.enable();
|
|
884
1223
|
registered = true;
|
|
1224
|
+
void verifyPatchAttached();
|
|
885
1225
|
} catch (err) {
|
|
886
1226
|
if (state2.config.debug) {
|
|
887
1227
|
const msg = err instanceof Error ? err.message : String(err);
|
|
@@ -889,6 +1229,23 @@ async function registerOpenAI(state2) {
|
|
|
889
1229
|
}
|
|
890
1230
|
}
|
|
891
1231
|
}
|
|
1232
|
+
function isPatchDetached(mod) {
|
|
1233
|
+
const OpenAIClass = mod?.default ?? mod?.OpenAI;
|
|
1234
|
+
const create = OpenAIClass?.Chat?.Completions?.prototype?.create;
|
|
1235
|
+
if (typeof create !== "function") return true;
|
|
1236
|
+
return create.__wrapped !== true;
|
|
1237
|
+
}
|
|
1238
|
+
async function verifyPatchAttached() {
|
|
1239
|
+
try {
|
|
1240
|
+
const mod = await import('openai');
|
|
1241
|
+
if (!isPatchDetached(mod)) return;
|
|
1242
|
+
const version = mod?.default?.VERSION ?? mod?.VERSION;
|
|
1243
|
+
console.warn(
|
|
1244
|
+
`[sight] OpenAI autocapture via module patching did not attach` + (version ? ` (openai v${version})` : "") + `. This happens on openai >=5, under ESM, or when 'openai' loads before init. Wrap your client instead: import { wrapOpenAI } from '@cultured_computer/sight'; const client = wrapOpenAI(new OpenAI()). Until then, no turns are captured from this client.`
|
|
1245
|
+
);
|
|
1246
|
+
} catch {
|
|
1247
|
+
}
|
|
1248
|
+
}
|
|
892
1249
|
|
|
893
1250
|
// src/instrumentation/anthropic.ts
|
|
894
1251
|
var registered2 = false;
|
|
@@ -997,6 +1354,7 @@ async function registerMercury(state2) {
|
|
|
997
1354
|
// src/instrumentation/index.ts
|
|
998
1355
|
function registerAllInstrumentations(state2, captureFn) {
|
|
999
1356
|
setupOtelProvider(state2, captureFn);
|
|
1357
|
+
bindWrapOpenAI(state2, captureFn);
|
|
1000
1358
|
const registrations = [
|
|
1001
1359
|
registerOpenAI(state2),
|
|
1002
1360
|
registerAnthropic(state2),
|
|
@@ -2102,5 +2460,6 @@ var Probe = class {
|
|
|
2102
2460
|
|
|
2103
2461
|
exports.Probe = Probe;
|
|
2104
2462
|
exports.Sight = Probe;
|
|
2463
|
+
exports.wrapOpenAI = wrapOpenAI;
|
|
2105
2464
|
//# sourceMappingURL=index.cjs.map
|
|
2106
2465
|
//# sourceMappingURL=index.cjs.map
|