@cultured_computer/sight 0.7.1 → 0.8.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/CHANGELOG.md +257 -0
- package/README.md +380 -78
- package/dist/cli.js +57 -33
- package/dist/index.cjs +1148 -194
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +210 -86
- package/dist/index.d.ts +210 -86
- package/dist/index.js +1148 -196
- package/dist/index.js.map +1 -1
- package/package.json +6 -4
package/dist/index.cjs
CHANGED
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
var zod = require('zod');
|
|
4
4
|
var api = require('@opentelemetry/api');
|
|
5
|
+
var module$1 = require('module');
|
|
6
|
+
|
|
7
|
+
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
|
|
8
|
+
// src/probe.ts
|
|
5
9
|
|
|
6
10
|
// src/client.ts
|
|
7
11
|
var DEFAULT_DASHBOARD_URL = "https://sight.cultured.computer/dashboard";
|
|
@@ -37,8 +41,8 @@ var IngestClient = class {
|
|
|
37
41
|
shedAnnounced = false;
|
|
38
42
|
/**
|
|
39
43
|
* Every network send goes through here: adds the per-send timeout and
|
|
40
|
-
* the in-flight cap
|
|
41
|
-
*
|
|
44
|
+
* the in-flight cap. At the cap, the send is SHED (thrown into the
|
|
45
|
+
* caller's existing fire-and-log catch) rather than queued;
|
|
42
46
|
* the first shed per process warns on stderr, the rest debug-log.
|
|
43
47
|
*/
|
|
44
48
|
async guardedFetch(url, init) {
|
|
@@ -59,7 +63,7 @@ var IngestClient = class {
|
|
|
59
63
|
}
|
|
60
64
|
}
|
|
61
65
|
/**
|
|
62
|
-
* Await all in-flight sends (bounded). Called by
|
|
66
|
+
* Await all in-flight sends (bounded). Called by Sight.shutdown() so
|
|
63
67
|
* short-lived processes (serverless, CLI scripts) can actually exit after
|
|
64
68
|
* it — the documented "in-flight sends finish within 15s" only holds while
|
|
65
69
|
* the process lives. Polling is coarse on purpose: sends report through
|
|
@@ -80,7 +84,7 @@ var IngestClient = class {
|
|
|
80
84
|
}
|
|
81
85
|
/**
|
|
82
86
|
* Send a turn to the ingest API. Fire-and-log: errors are logged but never
|
|
83
|
-
* thrown. The customer's LLM path never blocks on
|
|
87
|
+
* thrown. The customer's LLM path never blocks on capture.
|
|
84
88
|
*/
|
|
85
89
|
async sendTurn(turn) {
|
|
86
90
|
try {
|
|
@@ -157,7 +161,7 @@ var IngestClient = class {
|
|
|
157
161
|
}
|
|
158
162
|
/**
|
|
159
163
|
* Send a session-end event to the ingest API. Records why a session ended
|
|
160
|
-
* on the
|
|
164
|
+
* on the session. Fire-and-log.
|
|
161
165
|
*/
|
|
162
166
|
async sendSessionEnd(deploymentSlug, end) {
|
|
163
167
|
try {
|
|
@@ -360,7 +364,7 @@ var OutcomeHookSchema = zod.z.object({
|
|
|
360
364
|
type: zod.z.enum(["numeric", "categorical", "boolean", "duration"]),
|
|
361
365
|
/**
|
|
362
366
|
* Callback that resolves the outcome for a completed session. Invoked by
|
|
363
|
-
*
|
|
367
|
+
* Sight.endSession() with the session's externalId; a non-null result
|
|
364
368
|
* lands as an outcome event on the session. Not invoked for sessions
|
|
365
369
|
* swept server-side (no explicit endSession) — use emitOutcomeEvent()
|
|
366
370
|
* for outcomes that become known out of band.
|
|
@@ -368,11 +372,12 @@ var OutcomeHookSchema = zod.z.object({
|
|
|
368
372
|
resolve: zod.z.custom()
|
|
369
373
|
});
|
|
370
374
|
var ProbeConfigSchema = zod.z.object({
|
|
371
|
-
/**
|
|
375
|
+
/** The project's API key (an ingest key from the dashboard). Required. */
|
|
372
376
|
apiKey: zod.z.string().min(1),
|
|
373
|
-
/** Deployment slug
|
|
377
|
+
/** Deployment slug: the configuration this traffic belongs to. Required. */
|
|
374
378
|
deployment: zod.z.string().min(1),
|
|
375
|
-
/** Ingest endpoint. Defaults to the production ingest service
|
|
379
|
+
/** Ingest endpoint. Defaults to the production ingest service,
|
|
380
|
+
`https://fieldwork-ingest.fly.dev`. */
|
|
376
381
|
endpoint: zod.z.string().url().default("https://fieldwork-ingest.fly.dev"),
|
|
377
382
|
/**
|
|
378
383
|
* Dashboard base URL used by the one-time first-capture announcement
|
|
@@ -421,14 +426,14 @@ var SessionStartSchema = zod.z.object({
|
|
|
421
426
|
*/
|
|
422
427
|
openedVia: zod.z.enum(["link", "notification", "resume", "direct", "share"]).optional(),
|
|
423
428
|
/**
|
|
424
|
-
* Environmental context
|
|
425
|
-
*
|
|
429
|
+
* Environmental context: browser / device / locale / tz. You choose
|
|
430
|
+
* which fields to include. See the collectClientContext helper.
|
|
426
431
|
*/
|
|
427
432
|
clientContext: zod.z.record(zod.z.string(), zod.z.unknown()).optional(),
|
|
428
433
|
/**
|
|
429
434
|
* Optional customer metadata attached to the session. Forwarded with the
|
|
430
435
|
* first captured turn merged into `clientContext` under the `metadata`
|
|
431
|
-
* key, so it
|
|
436
|
+
* key, so it is stored with the session.
|
|
432
437
|
*/
|
|
433
438
|
metadata: zod.z.record(zod.z.string(), zod.z.unknown()).optional(),
|
|
434
439
|
/**
|
|
@@ -444,7 +449,7 @@ var SessionStartSchema = zod.z.object({
|
|
|
444
449
|
environmentConfigHash: zod.z.string().optional(),
|
|
445
450
|
environmentConfigLabel: zod.z.string().optional()
|
|
446
451
|
});
|
|
447
|
-
zod.z.object({
|
|
452
|
+
var SessionEndSchema = zod.z.object({
|
|
448
453
|
externalId: zod.z.string().min(1),
|
|
449
454
|
endedReason: zod.z.enum([
|
|
450
455
|
"natural",
|
|
@@ -573,8 +578,53 @@ function getCurrentSessionId() {
|
|
|
573
578
|
return baggage?.getEntry(SESSION_BAGGAGE_KEY)?.value;
|
|
574
579
|
}
|
|
575
580
|
|
|
581
|
+
// src/instrumentation/no-session.ts
|
|
582
|
+
var warned = false;
|
|
583
|
+
function noSessionWarning(source) {
|
|
584
|
+
return `[sight] call not captured (${source}): no session scope. Wrap LLM calls in Sight.withSession(id, fn) so they are recorded as turns. This warning prints once per process; later skips log only with debug: true.`;
|
|
585
|
+
}
|
|
586
|
+
function reportNoSessionSkip(source, debug) {
|
|
587
|
+
if (!warned) {
|
|
588
|
+
warned = true;
|
|
589
|
+
console.warn(noSessionWarning(source));
|
|
590
|
+
return;
|
|
591
|
+
}
|
|
592
|
+
if (debug) {
|
|
593
|
+
console.warn(
|
|
594
|
+
`[sight] call not captured (${source}): no session scope; wrap it in Sight.withSession(id, fn).`
|
|
595
|
+
);
|
|
596
|
+
}
|
|
597
|
+
}
|
|
598
|
+
var AI_MODEL_CALL_KEY = api.createContextKey("sight.ai_model_call");
|
|
599
|
+
function runInsideAiModelCall(fn) {
|
|
600
|
+
return api.context.with(api.context.active().setValue(AI_MODEL_CALL_KEY, true), fn);
|
|
601
|
+
}
|
|
602
|
+
function isInsideAiModelCall(ctx = api.context.active()) {
|
|
603
|
+
return ctx.getValue(AI_MODEL_CALL_KEY) === true;
|
|
604
|
+
}
|
|
605
|
+
var MAX_CLAIMS = 1e3;
|
|
606
|
+
var claims = /* @__PURE__ */ new Set();
|
|
607
|
+
var openCalls = 0;
|
|
608
|
+
function noteAiModelCallOpened() {
|
|
609
|
+
openCalls += 1;
|
|
610
|
+
}
|
|
611
|
+
function noteAiModelCallClosed() {
|
|
612
|
+
if (openCalls > 0) openCalls -= 1;
|
|
613
|
+
}
|
|
614
|
+
function aiModelCallsOpen() {
|
|
615
|
+
return openCalls > 0;
|
|
616
|
+
}
|
|
617
|
+
function claimAiResponse(responseId) {
|
|
618
|
+
claims.add(responseId);
|
|
619
|
+
if (claims.size > MAX_CLAIMS) claims.delete(claims.values().next().value);
|
|
620
|
+
}
|
|
621
|
+
function takeAiResponseClaim(responseId) {
|
|
622
|
+
return claims.delete(responseId);
|
|
623
|
+
}
|
|
624
|
+
|
|
576
625
|
// src/instrumentation/otel-processor.ts
|
|
577
626
|
var MAX_DEDUP_SPANS = 1e4;
|
|
627
|
+
var MAX_TOOL_PARENTS = 1e3;
|
|
578
628
|
function attr(attrs, key) {
|
|
579
629
|
return attrs[key];
|
|
580
630
|
}
|
|
@@ -587,64 +637,261 @@ function asNumber(v) {
|
|
|
587
637
|
function asStringArray(v) {
|
|
588
638
|
return Array.isArray(v) && v.every((x) => typeof x === "string") ? v : void 0;
|
|
589
639
|
}
|
|
640
|
+
function firstNumber(attrs, ...keys) {
|
|
641
|
+
for (const key of keys) {
|
|
642
|
+
const n = asNumber(attrs[key]);
|
|
643
|
+
if (n !== void 0) return n;
|
|
644
|
+
}
|
|
645
|
+
return void 0;
|
|
646
|
+
}
|
|
647
|
+
function firstString(attrs, ...keys) {
|
|
648
|
+
for (const key of keys) {
|
|
649
|
+
const s = asString(attrs[key]);
|
|
650
|
+
if (s !== void 0 && s.length > 0) return s;
|
|
651
|
+
}
|
|
652
|
+
return void 0;
|
|
653
|
+
}
|
|
654
|
+
var CAPTURED_OPERATIONS = /* @__PURE__ */ new Set(["chat", "generate_content", "text_completion"]);
|
|
655
|
+
var AI_SDK_MODEL_CALL_OPERATIONS = /* @__PURE__ */ new Set([
|
|
656
|
+
"ai.generateText.doGenerate",
|
|
657
|
+
"ai.streamText.doStream",
|
|
658
|
+
"ai.generateObject.doGenerate",
|
|
659
|
+
"ai.streamObject.doStream"
|
|
660
|
+
]);
|
|
661
|
+
function isAiSdkModelCall(attrs) {
|
|
662
|
+
const op = asString(attrs["ai.operationId"]);
|
|
663
|
+
return op !== void 0 && AI_SDK_MODEL_CALL_OPERATIONS.has(op);
|
|
664
|
+
}
|
|
590
665
|
function isLLMCall(attrs) {
|
|
591
666
|
const op = asString(attrs["gen_ai.operation.name"]);
|
|
592
|
-
if (op
|
|
593
|
-
return
|
|
667
|
+
if (op !== void 0) {
|
|
668
|
+
return CAPTURED_OPERATIONS.has(op);
|
|
594
669
|
}
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
return false;
|
|
670
|
+
if (isAiSdkModelCall(attrs)) return true;
|
|
671
|
+
return asString(attrs["traceloop.span.kind"]) === "agent";
|
|
598
672
|
}
|
|
599
673
|
function isVercelAgentRollup(spanName, attrs) {
|
|
600
674
|
return spanName.startsWith("invoke_agent ") && attrs["ai.telemetry.functionId"] !== void 0;
|
|
601
675
|
}
|
|
602
676
|
function taggedProvider(attrs) {
|
|
603
|
-
const rawProvider =
|
|
677
|
+
const rawProvider = firstString(attrs, "gen_ai.provider.name", "gen_ai.system", "gen_ai.provider");
|
|
604
678
|
const model = asString(attrs["gen_ai.request.model"]);
|
|
605
679
|
if (model?.toLowerCase().startsWith("mercury")) {
|
|
606
680
|
return "inception";
|
|
607
681
|
}
|
|
608
682
|
return rawProvider;
|
|
609
683
|
}
|
|
610
|
-
function
|
|
684
|
+
function isRecord(v) {
|
|
685
|
+
return v !== null && typeof v === "object" && !Array.isArray(v);
|
|
686
|
+
}
|
|
687
|
+
function isMessageLike(v) {
|
|
688
|
+
return isRecord(v) && ("parts" in v || "content" in v || "role" in v);
|
|
689
|
+
}
|
|
690
|
+
function parseStructured(raw) {
|
|
691
|
+
if (typeof raw === "string") {
|
|
692
|
+
const t = raw.trimStart();
|
|
693
|
+
if (!t.startsWith("[") && !t.startsWith("{")) return void 0;
|
|
694
|
+
try {
|
|
695
|
+
return JSON.parse(raw);
|
|
696
|
+
} catch {
|
|
697
|
+
return void 0;
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
if (Array.isArray(raw)) {
|
|
701
|
+
return raw.map((el) => {
|
|
702
|
+
if (typeof el !== "string") return el;
|
|
703
|
+
try {
|
|
704
|
+
return JSON.parse(el);
|
|
705
|
+
} catch {
|
|
706
|
+
return el;
|
|
707
|
+
}
|
|
708
|
+
});
|
|
709
|
+
}
|
|
710
|
+
return raw;
|
|
711
|
+
}
|
|
712
|
+
function asMessageList(parsed) {
|
|
713
|
+
const list = Array.isArray(parsed) ? parsed : isMessageLike(parsed) ? [parsed] : void 0;
|
|
714
|
+
if (!list) return void 0;
|
|
715
|
+
const records = list.filter(isRecord);
|
|
716
|
+
return records.some(isMessageLike) ? records : void 0;
|
|
717
|
+
}
|
|
718
|
+
function partsOf(message) {
|
|
719
|
+
const p = message["parts"] ?? message["content"];
|
|
720
|
+
if (typeof p === "string") return [{ type: "text", content: p }];
|
|
721
|
+
return Array.isArray(p) ? p : [];
|
|
722
|
+
}
|
|
723
|
+
function textOfPart(part, types) {
|
|
724
|
+
if (typeof part === "string") return part;
|
|
725
|
+
if (!isRecord(part)) return void 0;
|
|
726
|
+
const type = part["type"];
|
|
727
|
+
if (type !== void 0 && !(typeof type === "string" && types.has(type))) return void 0;
|
|
728
|
+
const text = part["content"] ?? part["text"];
|
|
729
|
+
return typeof text === "string" ? text : void 0;
|
|
730
|
+
}
|
|
731
|
+
var TEXT_PART = /* @__PURE__ */ new Set(["text"]);
|
|
732
|
+
var INPUT_TEXT_PART = /* @__PURE__ */ new Set(["text", "input_text"]);
|
|
733
|
+
var REFUSAL_PART = /* @__PURE__ */ new Set(["refusal"]);
|
|
734
|
+
function joinText(parts, types, sep) {
|
|
735
|
+
const texts = [];
|
|
736
|
+
for (const part of parts) {
|
|
737
|
+
const t = textOfPart(part, types);
|
|
738
|
+
if (t !== void 0 && t.length > 0) texts.push(t);
|
|
739
|
+
}
|
|
740
|
+
return texts.length > 0 ? texts.join(sep) : void 0;
|
|
741
|
+
}
|
|
742
|
+
function parseOutputMessages(raw) {
|
|
743
|
+
const messages = asMessageList(parseStructured(raw));
|
|
744
|
+
if (!messages) return { structured: false, text: void 0, toolNames: [] };
|
|
745
|
+
const reply = messages.find((m) => {
|
|
746
|
+
const role = m["role"];
|
|
747
|
+
return role !== "user" && role !== "system" && role !== "developer" && role !== "tool";
|
|
748
|
+
});
|
|
749
|
+
if (!reply) return { structured: true, text: void 0, toolNames: [] };
|
|
750
|
+
const parts = partsOf(reply);
|
|
751
|
+
const toolNames = [];
|
|
752
|
+
for (const part of parts) {
|
|
753
|
+
if (!isRecord(part)) continue;
|
|
754
|
+
if (part["type"] === "tool_call" || part["type"] === "server_tool_call") {
|
|
755
|
+
const name = part["name"];
|
|
756
|
+
if (typeof name === "string" && name.length > 0) toolNames.push(name);
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
return {
|
|
760
|
+
structured: true,
|
|
761
|
+
text: joinText(parts, TEXT_PART, "") ?? joinText(parts, REFUSAL_PART, ""),
|
|
762
|
+
toolNames
|
|
763
|
+
};
|
|
764
|
+
}
|
|
765
|
+
function userTextFromMessages(raw, nested = false) {
|
|
766
|
+
const messages = asMessageList(parseStructured(raw));
|
|
767
|
+
if (!messages) return void 0;
|
|
768
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
769
|
+
const message = messages[i];
|
|
770
|
+
const role = message["role"];
|
|
771
|
+
if (role === "system" || role === "developer") continue;
|
|
772
|
+
if (role !== "user") return void 0;
|
|
773
|
+
const text = joinText(partsOf(message), nested ? INPUT_TEXT_PART : TEXT_PART, "\n");
|
|
774
|
+
if (text === void 0) return void 0;
|
|
775
|
+
return nested ? text : unwrapSerializedRequest(text);
|
|
776
|
+
}
|
|
777
|
+
return void 0;
|
|
778
|
+
}
|
|
779
|
+
function unwrapSerializedRequest(text) {
|
|
780
|
+
const parsed = parseStructured(text);
|
|
781
|
+
if (!Array.isArray(parsed) || !parsed.some(isRecord)) return text;
|
|
782
|
+
if (parsed.some(isMessageLike)) return userTextFromMessages(parsed, true);
|
|
783
|
+
return joinText(parsed, INPUT_TEXT_PART, "\n");
|
|
784
|
+
}
|
|
785
|
+
function extractUserText(attrs) {
|
|
786
|
+
return userTextFromMessages(attrs["gen_ai.input.messages"]) ?? (attrs["gen_ai.input.messages"] === void 0 ? userTextFromMessages(attrs["ai.prompt.messages"]) : void 0);
|
|
787
|
+
}
|
|
788
|
+
function aiSdkToolNames(raw) {
|
|
789
|
+
if (typeof raw !== "string") return [];
|
|
790
|
+
try {
|
|
791
|
+
const parsed = JSON.parse(raw);
|
|
792
|
+
if (!Array.isArray(parsed)) return [];
|
|
793
|
+
const names = [];
|
|
794
|
+
for (const call of parsed) {
|
|
795
|
+
const name = isRecord(call) ? call["toolName"] : void 0;
|
|
796
|
+
if (typeof name === "string" && name.length > 0) names.push(name);
|
|
797
|
+
}
|
|
798
|
+
return names;
|
|
799
|
+
} catch {
|
|
800
|
+
return [];
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
function toolNameOfSpan(spanName, attrs) {
|
|
804
|
+
const named = firstString(attrs, "gen_ai.tool.name", "traceloop.entity.name");
|
|
805
|
+
if (named) return named;
|
|
806
|
+
const prefix = "execute_tool ";
|
|
807
|
+
return spanName.startsWith(prefix) && spanName.length > prefix.length ? spanName.slice(prefix.length) : void 0;
|
|
808
|
+
}
|
|
809
|
+
function cacheTokensInInput(span) {
|
|
810
|
+
const scope = span.instrumentationScope?.name;
|
|
811
|
+
if (scope === "@traceloop/instrumentation-openai") return true;
|
|
812
|
+
if (scope === "@traceloop/instrumentation-anthropic") return false;
|
|
813
|
+
return void 0;
|
|
814
|
+
}
|
|
815
|
+
function reportedCost(attrs) {
|
|
816
|
+
const cost = asNumber(attrs["gen_ai.usage.cost"]);
|
|
817
|
+
return cost !== void 0 && Number.isFinite(cost) && cost >= 0 ? cost : void 0;
|
|
818
|
+
}
|
|
819
|
+
function buildPayload(span, childToolNames = []) {
|
|
611
820
|
const a = span.attributes;
|
|
612
821
|
const start = span.startTime[0] * 1e3 + span.startTime[1] / 1e6;
|
|
613
822
|
const end = span.endTime[0] * 1e3 + span.endTime[1] / 1e6;
|
|
614
823
|
const latencyMs = Math.max(0, Math.round(end - start));
|
|
615
|
-
const
|
|
616
|
-
const
|
|
617
|
-
const
|
|
824
|
+
const rawOutput = a["gen_ai.output.messages"];
|
|
825
|
+
const output = parseOutputMessages(rawOutput);
|
|
826
|
+
const responseText = asString(attr(a, "ai.response.text")) ?? (output.structured ? output.text : typeof rawOutput === "string" ? rawOutput : void 0) ?? asString(attr(a, "ai.response.object"));
|
|
827
|
+
const aiToolNames = aiSdkToolNames(attr(a, "ai.response.toolCalls"));
|
|
828
|
+
const toolCallNames = output.toolNames.length > 0 ? output.toolNames : aiToolNames.length > 0 ? aiToolNames : childToolNames.length > 0 ? childToolNames : asStringArray(attr(a, "gen_ai.response.tool_names"));
|
|
829
|
+
const toolCallsCount = toolCallNames?.length ?? asNumber(attr(a, "gen_ai.response.tool_calls_count"));
|
|
618
830
|
const finishReasons = asStringArray(attr(a, "gen_ai.response.finish_reasons"));
|
|
619
|
-
const finishReason = finishReasons?.[0];
|
|
831
|
+
const finishReason = finishReasons?.[0] ?? asString(attr(a, "ai.response.finishReason"));
|
|
832
|
+
const firstChunkMs = firstNumber(a, "ai.response.msToFirstChunk", "ai.stream.msToFirstChunk");
|
|
620
833
|
const error = span.status.code === 2 ? span.status.message ?? "error" : void 0;
|
|
621
834
|
return {
|
|
622
|
-
//
|
|
623
|
-
|
|
624
|
-
|
|
835
|
+
// Operational fields (the probe_* keys land on the turn's own columns).
|
|
836
|
+
// The `ai.*` names are the Vercel AI SDK 6 ones, read last.
|
|
837
|
+
probe_tokens_input: firstNumber(
|
|
838
|
+
a,
|
|
839
|
+
"gen_ai.usage.input_tokens",
|
|
840
|
+
"gen_ai.usage.prompt_tokens",
|
|
841
|
+
"ai.usage.inputTokens",
|
|
842
|
+
"ai.usage.promptTokens"
|
|
843
|
+
),
|
|
844
|
+
probe_tokens_output: firstNumber(
|
|
845
|
+
a,
|
|
846
|
+
"gen_ai.usage.output_tokens",
|
|
847
|
+
"gen_ai.usage.completion_tokens",
|
|
848
|
+
"ai.usage.outputTokens",
|
|
849
|
+
"ai.usage.completionTokens"
|
|
850
|
+
),
|
|
625
851
|
probe_latency_ms: latencyMs,
|
|
626
|
-
|
|
627
|
-
|
|
852
|
+
// First-token time: only ai streams put a first-chunk time on the span;
|
|
853
|
+
// the OpenAI, Anthropic and LangChain instrumentations do not.
|
|
854
|
+
...firstChunkMs === void 0 ? {} : { probe_first_token_ms: Math.max(0, Math.round(firstChunkMs)) },
|
|
855
|
+
probe_model: firstString(
|
|
856
|
+
a,
|
|
857
|
+
"gen_ai.response.model",
|
|
858
|
+
"ai.response.model",
|
|
859
|
+
"gen_ai.request.model",
|
|
860
|
+
"ai.model.id"
|
|
861
|
+
),
|
|
862
|
+
// The model as requested; the response names a dated snapshot.
|
|
863
|
+
probe_request_model: firstString(a, "gen_ai.request.model", "ai.model.id"),
|
|
864
|
+
probe_cost_usd: reportedCost(a),
|
|
865
|
+
probe_provider: taggedProvider(a) ?? asString(attr(a, "ai.model.provider")),
|
|
628
866
|
probe_tool_calls: toolCallsCount,
|
|
629
867
|
probe_tool_names: toolCallNames,
|
|
630
868
|
probe_error: error,
|
|
631
869
|
probe_finish_reason: finishReason,
|
|
632
870
|
// Response text so the SDK edge signature-phrase matcher has something to
|
|
633
|
-
// match against;
|
|
634
|
-
// Tier 2 boundary.
|
|
871
|
+
// match against; personal data is scrubbed server-side before storage.
|
|
635
872
|
response: responseText ? { text: responseText } : void 0,
|
|
636
|
-
//
|
|
637
|
-
//
|
|
638
|
-
probe_cache_read_input_tokens:
|
|
639
|
-
|
|
640
|
-
|
|
873
|
+
// Cache tokens. Current names are dotted (`cache_read.input_tokens`);
|
|
874
|
+
// the underscore names are the earlier Traceloop ones, kept as fallback.
|
|
875
|
+
probe_cache_read_input_tokens: firstNumber(
|
|
876
|
+
a,
|
|
877
|
+
"gen_ai.usage.cache_read.input_tokens",
|
|
878
|
+
"gen_ai.usage.cache_read_input_tokens",
|
|
879
|
+
"ai.usage.inputTokenDetails.cacheReadTokens",
|
|
880
|
+
"ai.usage.cachedInputTokens"
|
|
881
|
+
),
|
|
882
|
+
probe_cache_creation_input_tokens: firstNumber(
|
|
883
|
+
a,
|
|
884
|
+
"gen_ai.usage.cache_creation.input_tokens",
|
|
885
|
+
"gen_ai.usage.cache_creation_input_tokens",
|
|
886
|
+
"ai.usage.inputTokenDetails.cacheWriteTokens"
|
|
641
887
|
),
|
|
888
|
+
probe_cache_tokens_in_input: cacheTokensInInput(span),
|
|
642
889
|
// Debug metadata (kept in payload, not projected to canonical columns).
|
|
643
890
|
_otel: {
|
|
644
891
|
spanName: span.name,
|
|
645
892
|
traceId: span.spanContext().traceId,
|
|
646
893
|
spanId: span.spanContext().spanId,
|
|
647
|
-
operationName:
|
|
894
|
+
operationName: firstString(a, "gen_ai.operation.name", "ai.operationId"),
|
|
648
895
|
traceloopKind: asString(attr(a, "traceloop.span.kind"))
|
|
649
896
|
}
|
|
650
897
|
};
|
|
@@ -767,6 +1014,38 @@ var ProbeSpanProcessor = class {
|
|
|
767
1014
|
state;
|
|
768
1015
|
captureFn;
|
|
769
1016
|
seenSpans = /* @__PURE__ */ new Set();
|
|
1017
|
+
/**
|
|
1018
|
+
* Tool names from execute_tool spans, keyed by "traceId:parentSpanId".
|
|
1019
|
+
* A child span ends before its parent, so when the model-call span that
|
|
1020
|
+
* owns these tools ends, its tool names are already here.
|
|
1021
|
+
*/
|
|
1022
|
+
toolChildren = /* @__PURE__ */ new Map();
|
|
1023
|
+
/** Remember an execute_tool span's tool name under its parent span. */
|
|
1024
|
+
noteToolSpan(span, a) {
|
|
1025
|
+
const name = toolNameOfSpan(span.name, a);
|
|
1026
|
+
if (!name) return;
|
|
1027
|
+
const parent = span;
|
|
1028
|
+
const parentSpanId = parent.parentSpanContext?.spanId ?? parent.parentSpanId;
|
|
1029
|
+
if (!parentSpanId) return;
|
|
1030
|
+
const key = `${span.spanContext().traceId}:${parentSpanId}`;
|
|
1031
|
+
const names = this.toolChildren.get(key);
|
|
1032
|
+
if (names) {
|
|
1033
|
+
names.push(name);
|
|
1034
|
+
return;
|
|
1035
|
+
}
|
|
1036
|
+
if (this.toolChildren.size >= MAX_TOOL_PARENTS) {
|
|
1037
|
+
this.toolChildren.delete(this.toolChildren.keys().next().value);
|
|
1038
|
+
}
|
|
1039
|
+
this.toolChildren.set(key, [name]);
|
|
1040
|
+
}
|
|
1041
|
+
takeToolChildren(span) {
|
|
1042
|
+
const { traceId, spanId } = span.spanContext();
|
|
1043
|
+
const key = `${traceId}:${spanId}`;
|
|
1044
|
+
const names = this.toolChildren.get(key);
|
|
1045
|
+
if (!names) return [];
|
|
1046
|
+
this.toolChildren.delete(key);
|
|
1047
|
+
return names;
|
|
1048
|
+
}
|
|
770
1049
|
/**
|
|
771
1050
|
* Re-point the processor at a new Probe state (or null after shutdown).
|
|
772
1051
|
* A registered span processor cannot be removed from a provider, so
|
|
@@ -775,11 +1054,23 @@ var ProbeSpanProcessor = class {
|
|
|
775
1054
|
* stamping the old deployment slug (production-safety audit R1).
|
|
776
1055
|
*/
|
|
777
1056
|
rebind(state2, captureFn) {
|
|
778
|
-
if (this.state !== state2)
|
|
1057
|
+
if (this.state !== state2) {
|
|
1058
|
+
this.seenSpans.clear();
|
|
1059
|
+
this.toolChildren.clear();
|
|
1060
|
+
}
|
|
779
1061
|
this.state = state2;
|
|
780
1062
|
if (captureFn) this.captureFn = captureFn;
|
|
781
1063
|
}
|
|
782
|
-
|
|
1064
|
+
/**
|
|
1065
|
+
* Spans started inside an `ai` model call that the Sight `ai` integration
|
|
1066
|
+
* captures (a provider that calls an instrumented client). Never turns.
|
|
1067
|
+
*/
|
|
1068
|
+
insideAiCall = /* @__PURE__ */ new WeakSet();
|
|
1069
|
+
onStart(span, parentContext) {
|
|
1070
|
+
try {
|
|
1071
|
+
if (isInsideAiModelCall(parentContext)) this.insideAiCall.add(span);
|
|
1072
|
+
} catch {
|
|
1073
|
+
}
|
|
783
1074
|
}
|
|
784
1075
|
onEnd(span) {
|
|
785
1076
|
try {
|
|
@@ -787,54 +1078,96 @@ var ProbeSpanProcessor = class {
|
|
|
787
1078
|
const state2 = this.state;
|
|
788
1079
|
const a = span.attributes;
|
|
789
1080
|
if (isVercelAgentRollup(span.name, a)) return;
|
|
790
|
-
if (
|
|
791
|
-
|
|
792
|
-
if (!sessionId) {
|
|
793
|
-
if (state2.config.debug) {
|
|
794
|
-
console.warn(
|
|
795
|
-
`[probe/otel] span with no session context; skipped (wrap LLM calls in Probe.withSession()). span=${span.name}`
|
|
796
|
-
);
|
|
797
|
-
}
|
|
1081
|
+
if (asString(a["gen_ai.operation.name"]) === "execute_tool") {
|
|
1082
|
+
this.noteToolSpan(span, a);
|
|
798
1083
|
return;
|
|
799
1084
|
}
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
if (this.seenSpans.size > MAX_DEDUP_SPANS) {
|
|
805
|
-
this.seenSpans.delete(this.seenSpans.values().next().value);
|
|
1085
|
+
if (!isLLMCall(a)) return;
|
|
1086
|
+
if (this.insideAiCall.has(span)) {
|
|
1087
|
+
this.takeToolChildren(span);
|
|
1088
|
+
return;
|
|
806
1089
|
}
|
|
807
|
-
const
|
|
808
|
-
|
|
809
|
-
|
|
1090
|
+
const sessionId = getCurrentSessionId() || firstString(
|
|
1091
|
+
a,
|
|
1092
|
+
"gen_ai.conversation.id",
|
|
1093
|
+
"ai.telemetry.metadata.sightSessionId",
|
|
1094
|
+
"ai.telemetry.metadata.sessionId"
|
|
810
1095
|
);
|
|
811
|
-
const
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
payload: buildPayload(span)
|
|
817
|
-
};
|
|
818
|
-
(async () => {
|
|
819
|
-
await maybeAutoStampEnvironmentConfig(session, a);
|
|
820
|
-
await this.captureFn(captured);
|
|
821
|
-
})().catch((err) => {
|
|
822
|
-
if (state2.config.debug) {
|
|
823
|
-
console.error(
|
|
824
|
-
`[probe/otel] capture error: ${err instanceof Error ? err.message : err}`
|
|
825
|
-
);
|
|
1096
|
+
const responseId = firstString(a, "gen_ai.response.id", "ai.response.id");
|
|
1097
|
+
if (responseId !== void 0) {
|
|
1098
|
+
if (takeAiResponseClaim(responseId)) {
|
|
1099
|
+
this.takeToolChildren(span);
|
|
1100
|
+
return;
|
|
826
1101
|
}
|
|
827
|
-
|
|
1102
|
+
if (aiModelCallsOpen()) {
|
|
1103
|
+
void Promise.resolve().then(() => {
|
|
1104
|
+
try {
|
|
1105
|
+
if (this.state !== state2) return;
|
|
1106
|
+
if (takeAiResponseClaim(responseId)) {
|
|
1107
|
+
this.takeToolChildren(span);
|
|
1108
|
+
return;
|
|
1109
|
+
}
|
|
1110
|
+
this.captureSpan(state2, span, a, sessionId);
|
|
1111
|
+
} catch (err) {
|
|
1112
|
+
if (state2.config.debug) {
|
|
1113
|
+
console.error(
|
|
1114
|
+
`[sight] span processor error: ${err instanceof Error ? err.message : err}`
|
|
1115
|
+
);
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
});
|
|
1119
|
+
return;
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
this.captureSpan(state2, span, a, sessionId);
|
|
828
1123
|
} catch (err) {
|
|
829
1124
|
if (this.state?.config.debug) {
|
|
830
1125
|
console.error(
|
|
831
|
-
`[
|
|
1126
|
+
`[sight] span processor error: ${err instanceof Error ? err.message : err}`
|
|
832
1127
|
);
|
|
833
1128
|
}
|
|
834
1129
|
}
|
|
835
1130
|
}
|
|
1131
|
+
/** The capture itself, once the span is known to be this call's only turn. */
|
|
1132
|
+
captureSpan(state2, span, a, sessionId) {
|
|
1133
|
+
if (!sessionId) {
|
|
1134
|
+
this.takeToolChildren(span);
|
|
1135
|
+
reportNoSessionSkip(`span "${span.name}"`, state2.config.debug);
|
|
1136
|
+
return;
|
|
1137
|
+
}
|
|
1138
|
+
const { traceId, spanId } = span.spanContext();
|
|
1139
|
+
const identity = JSON.stringify([state2.config.deployment, sessionId, traceId, spanId]);
|
|
1140
|
+
if (this.seenSpans.has(identity)) return;
|
|
1141
|
+
this.seenSpans.add(identity);
|
|
1142
|
+
if (this.seenSpans.size > MAX_DEDUP_SPANS) {
|
|
1143
|
+
this.seenSpans.delete(this.seenSpans.values().next().value);
|
|
1144
|
+
}
|
|
1145
|
+
const { session, sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(
|
|
1146
|
+
state2,
|
|
1147
|
+
sessionId
|
|
1148
|
+
);
|
|
1149
|
+
const captured = {
|
|
1150
|
+
deploymentSlug: state2.config.deployment,
|
|
1151
|
+
sessionExternalId,
|
|
1152
|
+
turnIndex,
|
|
1153
|
+
personaSlug: personaSlug ?? void 0,
|
|
1154
|
+
payload: buildPayload(span, this.takeToolChildren(span))
|
|
1155
|
+
};
|
|
1156
|
+
const hints = { observedUserText: extractUserText(a) };
|
|
1157
|
+
(async () => {
|
|
1158
|
+
await maybeAutoStampEnvironmentConfig(session, a);
|
|
1159
|
+
await this.captureFn(captured, hints);
|
|
1160
|
+
})().catch((err) => {
|
|
1161
|
+
if (state2.config.debug) {
|
|
1162
|
+
console.error(
|
|
1163
|
+
`[sight] span capture error: ${err instanceof Error ? err.message : err}`
|
|
1164
|
+
);
|
|
1165
|
+
}
|
|
1166
|
+
});
|
|
1167
|
+
}
|
|
836
1168
|
shutdown() {
|
|
837
1169
|
this.seenSpans.clear();
|
|
1170
|
+
this.toolChildren.clear();
|
|
838
1171
|
return Promise.resolve();
|
|
839
1172
|
}
|
|
840
1173
|
forceFlush() {
|
|
@@ -845,6 +1178,10 @@ var ProbeSpanProcessor = class {
|
|
|
845
1178
|
// src/instrumentation/wrap-openai.ts
|
|
846
1179
|
var bound = null;
|
|
847
1180
|
var warnedUnbound = false;
|
|
1181
|
+
var wrappedClientSeen = false;
|
|
1182
|
+
function hasWrappedClient() {
|
|
1183
|
+
return wrappedClientSeen;
|
|
1184
|
+
}
|
|
848
1185
|
function bindWrapOpenAI(state2, captureFn) {
|
|
849
1186
|
bound = { state: state2, captureFn };
|
|
850
1187
|
}
|
|
@@ -893,8 +1230,33 @@ function systemTextFromParams(params) {
|
|
|
893
1230
|
}
|
|
894
1231
|
return void 0;
|
|
895
1232
|
}
|
|
896
|
-
|
|
897
|
-
|
|
1233
|
+
var now = Date.now;
|
|
1234
|
+
function hostOf(baseURL) {
|
|
1235
|
+
if (!baseURL) return void 0;
|
|
1236
|
+
try {
|
|
1237
|
+
return new URL(baseURL).hostname.toLowerCase();
|
|
1238
|
+
} catch {
|
|
1239
|
+
return void 0;
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
function providerFor(model, baseURL) {
|
|
1243
|
+
if (model?.toLowerCase().startsWith("mercury")) return "inception";
|
|
1244
|
+
const host = hostOf(baseURL);
|
|
1245
|
+
if (!host || host === "api.openai.com") return "openai";
|
|
1246
|
+
if (host === "openrouter.ai" || host.endsWith(".openrouter.ai")) return "openrouter";
|
|
1247
|
+
if (host.endsWith(".openai.azure.com")) return "azure";
|
|
1248
|
+
if (host === "inceptionlabs.ai" || host.endsWith(".inceptionlabs.ai")) return "inception";
|
|
1249
|
+
return void 0;
|
|
1250
|
+
}
|
|
1251
|
+
function costFromUsage(usage) {
|
|
1252
|
+
const cost = asNumber2(usage?.["cost"]);
|
|
1253
|
+
if (cost === void 0 || !Number.isFinite(cost) || cost < 0) return void 0;
|
|
1254
|
+
if (usage?.["is_byok"] === true) {
|
|
1255
|
+
const upstream = asNumber2(asRecord(usage["cost_details"])?.["upstream_inference_cost"]);
|
|
1256
|
+
if (upstream === void 0 || !Number.isFinite(upstream) || upstream < 0) return void 0;
|
|
1257
|
+
return cost + upstream;
|
|
1258
|
+
}
|
|
1259
|
+
return cost;
|
|
898
1260
|
}
|
|
899
1261
|
function payloadFromChatResponse(r, requestModel) {
|
|
900
1262
|
const choice = Array.isArray(r["choices"]) ? asRecord(r["choices"][0]) : void 0;
|
|
@@ -910,7 +1272,8 @@ function payloadFromChatResponse(r, requestModel) {
|
|
|
910
1272
|
tokensOutput: asNumber2(usage?.["completion_tokens"]),
|
|
911
1273
|
cachedTokens: asNumber2(promptDetails?.["cached_tokens"]),
|
|
912
1274
|
finishReason: asString2(choice?.["finish_reason"]),
|
|
913
|
-
toolNames
|
|
1275
|
+
toolNames,
|
|
1276
|
+
costUsd: costFromUsage(usage)
|
|
914
1277
|
};
|
|
915
1278
|
}
|
|
916
1279
|
function payloadFromResponsesResponse(r, requestModel) {
|
|
@@ -946,23 +1309,31 @@ function payloadFromResponsesResponse(r, requestModel) {
|
|
|
946
1309
|
tokensOutput: asNumber2(usage?.["output_tokens"]),
|
|
947
1310
|
cachedTokens: asNumber2(inputDetails?.["cached_tokens"]),
|
|
948
1311
|
finishReason: asString2(r["status"]),
|
|
949
|
-
toolNames: toolNames.length > 0 ? toolNames : void 0
|
|
1312
|
+
toolNames: toolNames.length > 0 ? toolNames : void 0,
|
|
1313
|
+
costUsd: costFromUsage(usage)
|
|
950
1314
|
};
|
|
951
1315
|
}
|
|
952
|
-
function buildTurnPayload(x,
|
|
1316
|
+
function buildTurnPayload(x, call) {
|
|
953
1317
|
return {
|
|
954
1318
|
probe_tokens_input: x.tokensInput,
|
|
955
1319
|
probe_tokens_output: x.tokensOutput,
|
|
956
|
-
probe_latency_ms: latencyMs,
|
|
1320
|
+
probe_latency_ms: call.latencyMs,
|
|
1321
|
+
probe_first_token_ms: call.firstTokenMs,
|
|
1322
|
+
probe_cost_usd: x.costUsd,
|
|
957
1323
|
probe_model: x.model,
|
|
958
|
-
|
|
1324
|
+
// The model as requested. The response names a dated snapshot; the
|
|
1325
|
+
// server prices a turn by whichever of the two the catalogue lists.
|
|
1326
|
+
probe_request_model: call.requestModel,
|
|
1327
|
+
probe_provider: providerFor(x.model ?? call.requestModel, call.baseURL),
|
|
959
1328
|
probe_tool_calls: x.toolNames?.length,
|
|
960
1329
|
probe_tool_names: x.toolNames,
|
|
961
1330
|
probe_error: void 0,
|
|
962
1331
|
probe_finish_reason: x.finishReason,
|
|
963
1332
|
response: x.text ? { text: x.text } : void 0,
|
|
964
1333
|
probe_cache_read_input_tokens: x.cachedTokens,
|
|
965
|
-
|
|
1334
|
+
// OpenAI usage counts cached tokens inside the input count.
|
|
1335
|
+
probe_cache_tokens_in_input: x.cachedTokens !== void 0 ? true : void 0,
|
|
1336
|
+
_wrap: { api: call.api, adapter: "wrapOpenAI" }
|
|
966
1337
|
};
|
|
967
1338
|
}
|
|
968
1339
|
function emit(params, payload) {
|
|
@@ -970,7 +1341,7 @@ function emit(params, payload) {
|
|
|
970
1341
|
if (!warnedUnbound) {
|
|
971
1342
|
warnedUnbound = true;
|
|
972
1343
|
console.warn(
|
|
973
|
-
"[sight] wrapOpenAI: call observed before
|
|
1344
|
+
"[sight] wrapOpenAI: call observed before Sight.init(); nothing captured until init runs."
|
|
974
1345
|
);
|
|
975
1346
|
}
|
|
976
1347
|
return;
|
|
@@ -978,11 +1349,7 @@ function emit(params, payload) {
|
|
|
978
1349
|
const { state: state2, captureFn } = bound;
|
|
979
1350
|
const sessionId = getCurrentSessionId();
|
|
980
1351
|
if (!sessionId) {
|
|
981
|
-
|
|
982
|
-
console.warn(
|
|
983
|
-
"[sight] wrapOpenAI: call with no session context; skipped (wrap calls in Probe.withSession())."
|
|
984
|
-
);
|
|
985
|
-
}
|
|
1352
|
+
reportNoSessionSkip("wrapOpenAI", state2.config.debug);
|
|
986
1353
|
return;
|
|
987
1354
|
}
|
|
988
1355
|
const { session, sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(
|
|
@@ -1047,80 +1414,143 @@ function teeStream(stream, onChunk, onDone) {
|
|
|
1047
1414
|
}
|
|
1048
1415
|
});
|
|
1049
1416
|
}
|
|
1417
|
+
function nonEmpty(v) {
|
|
1418
|
+
return typeof v === "string" && v.length > 0;
|
|
1419
|
+
}
|
|
1050
1420
|
function chatStreamAccumulator(requestModel) {
|
|
1051
1421
|
const texts = [];
|
|
1422
|
+
const toolNameParts = /* @__PURE__ */ new Map();
|
|
1052
1423
|
let model = requestModel;
|
|
1053
1424
|
let finishReason;
|
|
1054
1425
|
let tokensInput;
|
|
1055
1426
|
let tokensOutput;
|
|
1056
1427
|
let cachedTokens;
|
|
1428
|
+
let costUsd;
|
|
1057
1429
|
return {
|
|
1058
1430
|
onChunk(chunk) {
|
|
1059
1431
|
const c = asRecord(chunk);
|
|
1060
|
-
if (!c) return;
|
|
1432
|
+
if (!c) return false;
|
|
1061
1433
|
model = asString2(c["model"]) ?? model;
|
|
1062
1434
|
const choice = Array.isArray(c["choices"]) ? asRecord(c["choices"][0]) : void 0;
|
|
1063
1435
|
const delta = asRecord(choice?.["delta"]);
|
|
1436
|
+
let content = false;
|
|
1064
1437
|
const t = asString2(delta?.["content"]);
|
|
1065
|
-
if (t)
|
|
1438
|
+
if (t) {
|
|
1439
|
+
texts.push(t);
|
|
1440
|
+
content = true;
|
|
1441
|
+
}
|
|
1442
|
+
if (nonEmpty(delta?.["refusal"])) content = true;
|
|
1443
|
+
const toolCalls = delta?.["tool_calls"];
|
|
1444
|
+
if (Array.isArray(toolCalls) && toolCalls.length > 0) {
|
|
1445
|
+
content = true;
|
|
1446
|
+
toolCalls.forEach((raw, position) => {
|
|
1447
|
+
const call = asRecord(raw);
|
|
1448
|
+
const name = asString2(asRecord(call?.["function"])?.["name"]);
|
|
1449
|
+
if (!name) return;
|
|
1450
|
+
const index = asNumber2(call?.["index"]) ?? position;
|
|
1451
|
+
toolNameParts.set(index, (toolNameParts.get(index) ?? "") + name);
|
|
1452
|
+
});
|
|
1453
|
+
}
|
|
1066
1454
|
finishReason = asString2(choice?.["finish_reason"]) ?? finishReason;
|
|
1067
1455
|
const usage = asRecord(c["usage"]);
|
|
1068
1456
|
if (usage) {
|
|
1069
1457
|
tokensInput = asNumber2(usage["prompt_tokens"]) ?? tokensInput;
|
|
1070
1458
|
tokensOutput = asNumber2(usage["completion_tokens"]) ?? tokensOutput;
|
|
1071
1459
|
cachedTokens = asNumber2(asRecord(usage["prompt_tokens_details"])?.["cached_tokens"]) ?? cachedTokens;
|
|
1460
|
+
costUsd = costFromUsage(usage) ?? costUsd;
|
|
1072
1461
|
}
|
|
1462
|
+
return content;
|
|
1073
1463
|
},
|
|
1074
|
-
result: () =>
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1464
|
+
result: () => {
|
|
1465
|
+
const toolNames = [...toolNameParts.entries()].sort((x, y) => x[0] - y[0]).map((e) => e[1]);
|
|
1466
|
+
return {
|
|
1467
|
+
model,
|
|
1468
|
+
text: texts.length > 0 ? texts.join("") : void 0,
|
|
1469
|
+
tokensInput,
|
|
1470
|
+
tokensOutput,
|
|
1471
|
+
cachedTokens,
|
|
1472
|
+
finishReason,
|
|
1473
|
+
toolNames: toolNames.length > 0 ? toolNames : void 0,
|
|
1474
|
+
costUsd
|
|
1475
|
+
};
|
|
1476
|
+
}
|
|
1083
1477
|
};
|
|
1084
1478
|
}
|
|
1479
|
+
var RESPONSES_OUTPUT_DELTAS = /* @__PURE__ */ new Set([
|
|
1480
|
+
"response.output_text.delta",
|
|
1481
|
+
"response.refusal.delta",
|
|
1482
|
+
"response.function_call_arguments.delta"
|
|
1483
|
+
]);
|
|
1085
1484
|
function responsesStreamAccumulator(requestModel) {
|
|
1086
1485
|
const texts = [];
|
|
1486
|
+
const toolNameByIndex = /* @__PURE__ */ new Map();
|
|
1087
1487
|
let final = null;
|
|
1088
1488
|
return {
|
|
1089
1489
|
onChunk(chunk) {
|
|
1090
1490
|
const c = asRecord(chunk);
|
|
1091
|
-
if (!c) return;
|
|
1092
|
-
|
|
1491
|
+
if (!c) return false;
|
|
1492
|
+
const type = asString2(c["type"]);
|
|
1493
|
+
let content = false;
|
|
1494
|
+
if (type === "response.output_text.delta") {
|
|
1093
1495
|
const t = asString2(c["delta"]);
|
|
1094
1496
|
if (t) texts.push(t);
|
|
1095
1497
|
}
|
|
1096
|
-
if (c["
|
|
1498
|
+
if (type !== void 0 && RESPONSES_OUTPUT_DELTAS.has(type) && nonEmpty(c["delta"])) {
|
|
1499
|
+
content = true;
|
|
1500
|
+
}
|
|
1501
|
+
if (type === "response.output_item.added" || type === "response.output_item.done") {
|
|
1502
|
+
const item = asRecord(c["item"]);
|
|
1503
|
+
if (item?.["type"] === "function_call") {
|
|
1504
|
+
content = true;
|
|
1505
|
+
const name = asString2(item["name"]);
|
|
1506
|
+
if (name) toolNameByIndex.set(asNumber2(c["output_index"]) ?? toolNameByIndex.size, name);
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
if (type === "response.completed") {
|
|
1097
1510
|
const response = asRecord(c["response"]);
|
|
1098
1511
|
if (response) final = payloadFromResponsesResponse(response, requestModel);
|
|
1099
1512
|
}
|
|
1513
|
+
return content;
|
|
1100
1514
|
},
|
|
1101
1515
|
result: () => {
|
|
1516
|
+
const streamedNames = [...toolNameByIndex.entries()].sort((x, y) => x[0] - y[0]).map((e) => e[1]);
|
|
1517
|
+
const streamedText = texts.length > 0 ? texts.join("") : void 0;
|
|
1102
1518
|
if (final) {
|
|
1103
|
-
return {
|
|
1519
|
+
return {
|
|
1520
|
+
...final,
|
|
1521
|
+
text: final.text ?? streamedText,
|
|
1522
|
+
toolNames: final.toolNames ?? (streamedNames.length > 0 ? streamedNames : void 0)
|
|
1523
|
+
};
|
|
1104
1524
|
}
|
|
1105
1525
|
return {
|
|
1106
1526
|
model: requestModel,
|
|
1107
|
-
text:
|
|
1527
|
+
text: streamedText,
|
|
1108
1528
|
tokensInput: void 0,
|
|
1109
1529
|
tokensOutput: void 0,
|
|
1110
1530
|
cachedTokens: void 0,
|
|
1111
1531
|
finishReason: void 0,
|
|
1112
|
-
toolNames: void 0
|
|
1532
|
+
toolNames: streamedNames.length > 0 ? streamedNames : void 0,
|
|
1533
|
+
costUsd: void 0
|
|
1113
1534
|
};
|
|
1114
1535
|
}
|
|
1115
1536
|
};
|
|
1116
1537
|
}
|
|
1117
|
-
function wrapCreate(target, api, makeAccumulator, extractResponse) {
|
|
1538
|
+
function wrapCreate(client, target, api, makeAccumulator, extractResponse) {
|
|
1118
1539
|
const original = target["create"];
|
|
1119
1540
|
if (typeof original !== "function") return;
|
|
1120
1541
|
target["create"] = function(...args) {
|
|
1542
|
+
if (isInsideAiModelCall()) return original.apply(this, args);
|
|
1121
1543
|
const params = asRecord(args[0]);
|
|
1122
1544
|
const requestModel = asString2(params?.["model"]);
|
|
1123
|
-
const startedAt =
|
|
1545
|
+
const startedAt = now();
|
|
1546
|
+
const baseURL = asString2(client["baseURL"]);
|
|
1547
|
+
const facts = (firstTokenMs) => ({
|
|
1548
|
+
api,
|
|
1549
|
+
latencyMs: now() - startedAt,
|
|
1550
|
+
firstTokenMs,
|
|
1551
|
+
requestModel,
|
|
1552
|
+
baseURL
|
|
1553
|
+
});
|
|
1124
1554
|
const result = original.apply(this, args);
|
|
1125
1555
|
if (!result || typeof result.then !== "function") return result;
|
|
1126
1556
|
return result.then(
|
|
@@ -1129,13 +1559,23 @@ function wrapCreate(target, api, makeAccumulator, extractResponse) {
|
|
|
1129
1559
|
const isStream = resolved !== null && typeof resolved === "object" && Symbol.asyncIterator in resolved;
|
|
1130
1560
|
if (isStream) {
|
|
1131
1561
|
const acc = makeAccumulator(requestModel);
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
|
|
1562
|
+
let firstTokenMs;
|
|
1563
|
+
return teeStream(
|
|
1564
|
+
resolved,
|
|
1565
|
+
(chunk) => {
|
|
1566
|
+
const arrivedAt = now();
|
|
1567
|
+
if (acc.onChunk(chunk) && firstTokenMs === void 0) {
|
|
1568
|
+
firstTokenMs = Math.max(0, Math.round(arrivedAt - startedAt));
|
|
1569
|
+
}
|
|
1570
|
+
},
|
|
1571
|
+
() => {
|
|
1572
|
+
emit(params, buildTurnPayload(acc.result(), facts(firstTokenMs)));
|
|
1573
|
+
}
|
|
1574
|
+
);
|
|
1135
1575
|
}
|
|
1136
1576
|
const r = asRecord(resolved);
|
|
1137
1577
|
if (r) {
|
|
1138
|
-
emit(params, buildTurnPayload(extractResponse(r, requestModel),
|
|
1578
|
+
emit(params, buildTurnPayload(extractResponse(r, requestModel), facts()));
|
|
1139
1579
|
}
|
|
1140
1580
|
return resolved;
|
|
1141
1581
|
} catch {
|
|
@@ -1151,9 +1591,10 @@ function wrapCreate(target, api, makeAccumulator, extractResponse) {
|
|
|
1151
1591
|
tokensOutput: void 0,
|
|
1152
1592
|
cachedTokens: void 0,
|
|
1153
1593
|
finishReason: void 0,
|
|
1154
|
-
toolNames: void 0
|
|
1594
|
+
toolNames: void 0,
|
|
1595
|
+
costUsd: void 0
|
|
1155
1596
|
};
|
|
1156
|
-
const payload = buildTurnPayload(x,
|
|
1597
|
+
const payload = buildTurnPayload(x, facts());
|
|
1157
1598
|
payload.probe_error = err instanceof Error ? err.message : String(err);
|
|
1158
1599
|
emit(params, payload);
|
|
1159
1600
|
} catch {
|
|
@@ -1164,19 +1605,465 @@ function wrapCreate(target, api, makeAccumulator, extractResponse) {
|
|
|
1164
1605
|
};
|
|
1165
1606
|
}
|
|
1166
1607
|
function wrapOpenAI(client) {
|
|
1608
|
+
wrappedClientSeen = true;
|
|
1167
1609
|
const c = client;
|
|
1168
1610
|
if (c[WRAPPED]) return client;
|
|
1169
1611
|
c[WRAPPED] = true;
|
|
1170
1612
|
const completions = asRecord(asRecord(c["chat"])?.["completions"]);
|
|
1171
1613
|
if (completions) {
|
|
1172
|
-
wrapCreate(completions, "chat", chatStreamAccumulator, payloadFromChatResponse);
|
|
1614
|
+
wrapCreate(c, completions, "chat", chatStreamAccumulator, payloadFromChatResponse);
|
|
1173
1615
|
}
|
|
1174
1616
|
const responses = asRecord(c["responses"]);
|
|
1175
1617
|
if (responses) {
|
|
1176
|
-
wrapCreate(responses, "responses", responsesStreamAccumulator, payloadFromResponsesResponse);
|
|
1618
|
+
wrapCreate(c, responses, "responses", responsesStreamAccumulator, payloadFromResponsesResponse);
|
|
1177
1619
|
}
|
|
1178
1620
|
return client;
|
|
1179
1621
|
}
|
|
1622
|
+
var AI_SESSION_KEYS = ["sightSessionId", "sessionId"];
|
|
1623
|
+
var bound2 = null;
|
|
1624
|
+
var everBound = false;
|
|
1625
|
+
var warnedUnbound2 = false;
|
|
1626
|
+
function bindVercelAI(state2, captureFn) {
|
|
1627
|
+
bound2 = { state: state2, captureFn };
|
|
1628
|
+
everBound = true;
|
|
1629
|
+
}
|
|
1630
|
+
function unbindVercelAI() {
|
|
1631
|
+
bound2 = null;
|
|
1632
|
+
for (const call of calls.values()) closeModelCall(call);
|
|
1633
|
+
calls.clear();
|
|
1634
|
+
}
|
|
1635
|
+
function rec(v) {
|
|
1636
|
+
return v !== null && typeof v === "object" && !Array.isArray(v) ? v : void 0;
|
|
1637
|
+
}
|
|
1638
|
+
function str(v) {
|
|
1639
|
+
return typeof v === "string" && v.length > 0 ? v : void 0;
|
|
1640
|
+
}
|
|
1641
|
+
function num(v) {
|
|
1642
|
+
return typeof v === "number" && Number.isFinite(v) ? v : void 0;
|
|
1643
|
+
}
|
|
1644
|
+
function ms(v) {
|
|
1645
|
+
const n = num(v);
|
|
1646
|
+
return n === void 0 ? void 0 : Math.max(0, Math.round(n));
|
|
1647
|
+
}
|
|
1648
|
+
function textOfContent(content, sep) {
|
|
1649
|
+
if (typeof content === "string") return content.length > 0 ? content : void 0;
|
|
1650
|
+
if (!Array.isArray(content)) return void 0;
|
|
1651
|
+
const texts = [];
|
|
1652
|
+
for (const part of content) {
|
|
1653
|
+
const p = rec(part);
|
|
1654
|
+
if (p?.["type"] === "text" && typeof p["text"] === "string" && p["text"].length > 0) {
|
|
1655
|
+
texts.push(p["text"]);
|
|
1656
|
+
}
|
|
1657
|
+
}
|
|
1658
|
+
return texts.length > 0 ? texts.join(sep) : void 0;
|
|
1659
|
+
}
|
|
1660
|
+
function userTextOf(messages) {
|
|
1661
|
+
if (!Array.isArray(messages)) return void 0;
|
|
1662
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
1663
|
+
const m = rec(messages[i]);
|
|
1664
|
+
if (!m) return void 0;
|
|
1665
|
+
if (m["role"] === "system") continue;
|
|
1666
|
+
if (m["role"] !== "user") return void 0;
|
|
1667
|
+
return textOfContent(m["content"], "\n");
|
|
1668
|
+
}
|
|
1669
|
+
return void 0;
|
|
1670
|
+
}
|
|
1671
|
+
function systemTextOf(instructions, messages) {
|
|
1672
|
+
if (typeof instructions === "string") return str(instructions);
|
|
1673
|
+
const list = Array.isArray(instructions) ? instructions : instructions ? [instructions] : [];
|
|
1674
|
+
const texts = [];
|
|
1675
|
+
for (const item of list) {
|
|
1676
|
+
const t = textOfContent(rec(item)?.["content"], "\n");
|
|
1677
|
+
if (t) texts.push(t);
|
|
1678
|
+
}
|
|
1679
|
+
if (texts.length > 0) return texts.join("\n");
|
|
1680
|
+
if (Array.isArray(messages)) {
|
|
1681
|
+
for (const raw of messages) {
|
|
1682
|
+
const m = rec(raw);
|
|
1683
|
+
if (m?.["role"] === "system") {
|
|
1684
|
+
const t = textOfContent(m["content"], "\n");
|
|
1685
|
+
if (t) return t;
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
}
|
|
1689
|
+
return void 0;
|
|
1690
|
+
}
|
|
1691
|
+
function sessionFromContext(runtimeContext) {
|
|
1692
|
+
const ctx = rec(runtimeContext);
|
|
1693
|
+
if (!ctx) return void 0;
|
|
1694
|
+
for (const key of AI_SESSION_KEYS) {
|
|
1695
|
+
const v = str(ctx[key]);
|
|
1696
|
+
if (v) return v;
|
|
1697
|
+
}
|
|
1698
|
+
return void 0;
|
|
1699
|
+
}
|
|
1700
|
+
function errorMessage(err) {
|
|
1701
|
+
if (err instanceof Error) return err.message || err.name;
|
|
1702
|
+
return typeof err === "string" && err.length > 0 ? err : "error";
|
|
1703
|
+
}
|
|
1704
|
+
var MAX_CALLS = 1e3;
|
|
1705
|
+
var calls = /* @__PURE__ */ new Map();
|
|
1706
|
+
function stateFor(callId) {
|
|
1707
|
+
let call = calls.get(callId);
|
|
1708
|
+
if (!call) {
|
|
1709
|
+
call = {
|
|
1710
|
+
scopeSession: void 0,
|
|
1711
|
+
contextSession: void 0,
|
|
1712
|
+
operationId: void 0,
|
|
1713
|
+
system: void 0,
|
|
1714
|
+
open: null
|
|
1715
|
+
};
|
|
1716
|
+
if (calls.size >= MAX_CALLS) {
|
|
1717
|
+
const oldest = calls.keys().next().value;
|
|
1718
|
+
closeModelCall(calls.get(oldest));
|
|
1719
|
+
calls.delete(oldest);
|
|
1720
|
+
}
|
|
1721
|
+
calls.set(callId, call);
|
|
1722
|
+
}
|
|
1723
|
+
return call;
|
|
1724
|
+
}
|
|
1725
|
+
function openModelCall(call, modelCall) {
|
|
1726
|
+
if (call.open === null) noteAiModelCallOpened();
|
|
1727
|
+
call.open = modelCall;
|
|
1728
|
+
}
|
|
1729
|
+
function closeModelCall(call) {
|
|
1730
|
+
if (call.open !== null) noteAiModelCallClosed();
|
|
1731
|
+
call.open = null;
|
|
1732
|
+
}
|
|
1733
|
+
function buildPayload2(call, f) {
|
|
1734
|
+
const usage = rec(f.usage);
|
|
1735
|
+
const inputDetails = rec(usage?.["inputTokenDetails"]);
|
|
1736
|
+
const outputDetails = rec(usage?.["outputTokenDetails"]);
|
|
1737
|
+
const toolNames = f.toolNames && f.toolNames.length > 0 ? f.toolNames : void 0;
|
|
1738
|
+
return {
|
|
1739
|
+
probe_tokens_input: num(usage?.["inputTokens"]),
|
|
1740
|
+
probe_tokens_output: num(usage?.["outputTokens"]),
|
|
1741
|
+
probe_latency_ms: f.latencyMs,
|
|
1742
|
+
probe_first_token_ms: f.firstTokenMs,
|
|
1743
|
+
probe_model: f.model,
|
|
1744
|
+
probe_provider: f.provider,
|
|
1745
|
+
probe_tool_calls: toolNames?.length,
|
|
1746
|
+
probe_tool_names: toolNames,
|
|
1747
|
+
probe_error: f.error,
|
|
1748
|
+
probe_finish_reason: f.finishReason,
|
|
1749
|
+
response: f.text ? { text: f.text } : void 0,
|
|
1750
|
+
probe_cache_read_input_tokens: num(inputDetails?.["cacheReadTokens"]),
|
|
1751
|
+
probe_cache_creation_input_tokens: num(inputDetails?.["cacheWriteTokens"]),
|
|
1752
|
+
// Debug metadata (kept in payload, not projected to canonical columns).
|
|
1753
|
+
_ai: {
|
|
1754
|
+
adapter: "ai-telemetry",
|
|
1755
|
+
operationId: call.operationId,
|
|
1756
|
+
callId: f.callId,
|
|
1757
|
+
stepNumber: f.stepNumber,
|
|
1758
|
+
functionId: f.functionId,
|
|
1759
|
+
responseId: f.responseId,
|
|
1760
|
+
rawFinishReason: f.rawFinishReason,
|
|
1761
|
+
reasoningTokens: num(outputDetails?.["reasoningTokens"])
|
|
1762
|
+
}
|
|
1763
|
+
};
|
|
1764
|
+
}
|
|
1765
|
+
function emit2(options, call, request, fields) {
|
|
1766
|
+
if (!bound2) {
|
|
1767
|
+
if (!everBound && !warnedUnbound2) {
|
|
1768
|
+
warnedUnbound2 = true;
|
|
1769
|
+
console.warn(
|
|
1770
|
+
"[sight] ai telemetry: call observed before Sight.init(); nothing captured until init runs."
|
|
1771
|
+
);
|
|
1772
|
+
}
|
|
1773
|
+
return;
|
|
1774
|
+
}
|
|
1775
|
+
const { state: state2, captureFn } = bound2;
|
|
1776
|
+
const sessionId = call.scopeSession ?? (getCurrentSessionId() || options.sessionId || call.contextSession);
|
|
1777
|
+
if (!sessionId) {
|
|
1778
|
+
reportNoSessionSkip(`ai ${call.operationId ?? "model call"}`, state2.config.debug);
|
|
1779
|
+
return;
|
|
1780
|
+
}
|
|
1781
|
+
const { session, sessionExternalId, turnIndex, personaSlug } = resolveSessionAndTurn(
|
|
1782
|
+
state2,
|
|
1783
|
+
sessionId
|
|
1784
|
+
);
|
|
1785
|
+
const captured = {
|
|
1786
|
+
deploymentSlug: state2.config.deployment,
|
|
1787
|
+
sessionExternalId,
|
|
1788
|
+
turnIndex,
|
|
1789
|
+
personaSlug: personaSlug ?? void 0,
|
|
1790
|
+
payload: buildPayload2(call, fields)
|
|
1791
|
+
};
|
|
1792
|
+
const hints = { observedUserText: userTextOf(request.messages) };
|
|
1793
|
+
const systemText = systemTextOf(request.instructions, request.messages);
|
|
1794
|
+
void (async () => {
|
|
1795
|
+
await autoStampFromSystemText(session, systemText);
|
|
1796
|
+
await captureFn(captured, hints);
|
|
1797
|
+
})().catch((err) => {
|
|
1798
|
+
if (state2.config.debug) {
|
|
1799
|
+
console.error(
|
|
1800
|
+
`[sight] ai telemetry capture error: ${err instanceof Error ? err.message : err}`
|
|
1801
|
+
);
|
|
1802
|
+
}
|
|
1803
|
+
});
|
|
1804
|
+
}
|
|
1805
|
+
var BRAND = /* @__PURE__ */ Symbol.for("sight.aiTelemetry");
|
|
1806
|
+
function isSightIntegration(v) {
|
|
1807
|
+
return v !== null && typeof v === "object" && v[BRAND] === true;
|
|
1808
|
+
}
|
|
1809
|
+
function guarded(fn) {
|
|
1810
|
+
return (event) => {
|
|
1811
|
+
try {
|
|
1812
|
+
const e = rec(event);
|
|
1813
|
+
if (e) fn(e);
|
|
1814
|
+
} catch (err) {
|
|
1815
|
+
if (bound2?.state.config.debug) {
|
|
1816
|
+
console.error(
|
|
1817
|
+
`[sight] ai telemetry hook error: ${err instanceof Error ? err.message : err}`
|
|
1818
|
+
);
|
|
1819
|
+
}
|
|
1820
|
+
}
|
|
1821
|
+
};
|
|
1822
|
+
}
|
|
1823
|
+
function createIntegration(options) {
|
|
1824
|
+
const failed = (callId, error, functionId) => {
|
|
1825
|
+
if (!callId) return;
|
|
1826
|
+
const call = calls.get(callId);
|
|
1827
|
+
if (!call) return;
|
|
1828
|
+
const open = call.open;
|
|
1829
|
+
closeModelCall(call);
|
|
1830
|
+
calls.delete(callId);
|
|
1831
|
+
if (!open) return;
|
|
1832
|
+
emit2(
|
|
1833
|
+
options,
|
|
1834
|
+
call,
|
|
1835
|
+
{ instructions: open.instructions, messages: open.messages },
|
|
1836
|
+
{
|
|
1837
|
+
callId,
|
|
1838
|
+
model: open.modelId,
|
|
1839
|
+
provider: open.provider,
|
|
1840
|
+
latencyMs: Math.max(0, Date.now() - open.startedAt),
|
|
1841
|
+
error,
|
|
1842
|
+
functionId: str(functionId)
|
|
1843
|
+
}
|
|
1844
|
+
);
|
|
1845
|
+
};
|
|
1846
|
+
const begin = (e, instructions, messages) => {
|
|
1847
|
+
const callId = str(e["callId"]);
|
|
1848
|
+
if (!callId) return;
|
|
1849
|
+
const call = stateFor(callId);
|
|
1850
|
+
call.scopeSession ??= getCurrentSessionId() || void 0;
|
|
1851
|
+
const record = e["recordInputs"] !== false;
|
|
1852
|
+
openModelCall(call, {
|
|
1853
|
+
startedAt: Date.now(),
|
|
1854
|
+
instructions: record ? instructions : void 0,
|
|
1855
|
+
messages: record ? messages : void 0,
|
|
1856
|
+
provider: str(e["provider"]),
|
|
1857
|
+
modelId: str(e["modelId"])
|
|
1858
|
+
});
|
|
1859
|
+
};
|
|
1860
|
+
const integration = {
|
|
1861
|
+
name: "sight",
|
|
1862
|
+
onStart: guarded((e) => {
|
|
1863
|
+
const callId = str(e["callId"]);
|
|
1864
|
+
if (!callId) return;
|
|
1865
|
+
const call = stateFor(callId);
|
|
1866
|
+
call.scopeSession = getCurrentSessionId() || void 0;
|
|
1867
|
+
call.contextSession = sessionFromContext(e["runtimeContext"]);
|
|
1868
|
+
call.operationId = str(e["operationId"]);
|
|
1869
|
+
call.system = e["system"] ?? e["instructions"];
|
|
1870
|
+
}),
|
|
1871
|
+
onStepStart: guarded((e) => {
|
|
1872
|
+
const callId = str(e["callId"]);
|
|
1873
|
+
if (!callId) return;
|
|
1874
|
+
const call = stateFor(callId);
|
|
1875
|
+
call.contextSession = sessionFromContext(e["runtimeContext"]) ?? call.contextSession;
|
|
1876
|
+
}),
|
|
1877
|
+
onLanguageModelCallStart: guarded((e) => {
|
|
1878
|
+
begin(e, e["instructions"], e["messages"]);
|
|
1879
|
+
}),
|
|
1880
|
+
onLanguageModelCallEnd: guarded((e) => {
|
|
1881
|
+
const responseId = str(e["responseId"]);
|
|
1882
|
+
if (bound2 && responseId) claimAiResponse(responseId);
|
|
1883
|
+
}),
|
|
1884
|
+
onStepEnd: guarded((e) => {
|
|
1885
|
+
const callId = str(e["callId"]);
|
|
1886
|
+
if (!callId) return;
|
|
1887
|
+
const call = calls.get(callId);
|
|
1888
|
+
if (!call) return;
|
|
1889
|
+
const open = call.open;
|
|
1890
|
+
closeModelCall(call);
|
|
1891
|
+
call.contextSession = sessionFromContext(e["runtimeContext"]) ?? call.contextSession;
|
|
1892
|
+
const model = rec(e["model"]);
|
|
1893
|
+
const response = rec(e["response"]);
|
|
1894
|
+
const performance = rec(e["performance"]);
|
|
1895
|
+
const content = Array.isArray(e["content"]) ? e["content"] : [];
|
|
1896
|
+
const toolNames = [];
|
|
1897
|
+
for (const part of content) {
|
|
1898
|
+
const p = rec(part);
|
|
1899
|
+
if (p?.["type"] === "tool-call") {
|
|
1900
|
+
const name = str(p["toolName"]);
|
|
1901
|
+
if (name) toolNames.push(name);
|
|
1902
|
+
}
|
|
1903
|
+
}
|
|
1904
|
+
const finishReason = str(e["finishReason"]);
|
|
1905
|
+
emit2(
|
|
1906
|
+
options,
|
|
1907
|
+
call,
|
|
1908
|
+
{ instructions: open?.instructions, messages: open?.messages },
|
|
1909
|
+
{
|
|
1910
|
+
callId,
|
|
1911
|
+
// Text parts only: never reasoning, tool input or tool output.
|
|
1912
|
+
text: e["recordOutputs"] === false ? void 0 : textOfContent(content, ""),
|
|
1913
|
+
// The id the provider returned; the requested id when it returned none.
|
|
1914
|
+
model: str(response?.["modelId"]) ?? str(model?.["modelId"]) ?? open?.modelId,
|
|
1915
|
+
provider: str(model?.["provider"]) ?? open?.provider,
|
|
1916
|
+
usage: e["usage"],
|
|
1917
|
+
finishReason,
|
|
1918
|
+
rawFinishReason: str(e["rawFinishReason"]),
|
|
1919
|
+
toolNames,
|
|
1920
|
+
latencyMs: ms(performance?.["responseTimeMs"]) ?? (open ? Math.max(0, Date.now() - open.startedAt) : void 0),
|
|
1921
|
+
firstTokenMs: ms(performance?.["timeToFirstOutputMs"]),
|
|
1922
|
+
// A stream that failed part way ends its step with this finish
|
|
1923
|
+
// reason; the events carry no error message for it.
|
|
1924
|
+
error: finishReason === "error" ? 'model call ended with finish reason "error"' : void 0,
|
|
1925
|
+
responseId: str(response?.["id"]),
|
|
1926
|
+
stepNumber: num(e["stepNumber"]),
|
|
1927
|
+
functionId: str(e["functionId"])
|
|
1928
|
+
}
|
|
1929
|
+
);
|
|
1930
|
+
}),
|
|
1931
|
+
onObjectStepStart: guarded((e) => {
|
|
1932
|
+
const callId = str(e["callId"]);
|
|
1933
|
+
begin(e, callId ? calls.get(callId)?.system : void 0, e["promptMessages"]);
|
|
1934
|
+
}),
|
|
1935
|
+
onObjectStepEnd: guarded((e) => {
|
|
1936
|
+
const callId = str(e["callId"]);
|
|
1937
|
+
if (!callId) return;
|
|
1938
|
+
const call = calls.get(callId);
|
|
1939
|
+
if (!call) return;
|
|
1940
|
+
const open = call.open;
|
|
1941
|
+
closeModelCall(call);
|
|
1942
|
+
const response = rec(e["response"]);
|
|
1943
|
+
const responseId = str(response?.["id"]);
|
|
1944
|
+
if (bound2 && responseId) claimAiResponse(responseId);
|
|
1945
|
+
emit2(
|
|
1946
|
+
options,
|
|
1947
|
+
call,
|
|
1948
|
+
{ instructions: open?.instructions, messages: open?.messages },
|
|
1949
|
+
{
|
|
1950
|
+
callId,
|
|
1951
|
+
// The reply of an object call is the JSON text the model produced.
|
|
1952
|
+
text: e["recordOutputs"] === false ? void 0 : str(e["objectText"]),
|
|
1953
|
+
model: str(response?.["modelId"]) ?? str(e["modelId"]) ?? open?.modelId,
|
|
1954
|
+
provider: str(e["provider"]) ?? open?.provider,
|
|
1955
|
+
usage: e["usage"],
|
|
1956
|
+
finishReason: str(e["finishReason"]),
|
|
1957
|
+
latencyMs: open ? Math.max(0, Date.now() - open.startedAt) : void 0,
|
|
1958
|
+
firstTokenMs: ms(e["msToFirstChunk"]),
|
|
1959
|
+
responseId,
|
|
1960
|
+
stepNumber: num(e["stepNumber"]),
|
|
1961
|
+
functionId: str(e["functionId"])
|
|
1962
|
+
}
|
|
1963
|
+
);
|
|
1964
|
+
}),
|
|
1965
|
+
onError: guarded((e) => {
|
|
1966
|
+
failed(str(e["callId"]), errorMessage(e["error"]), e["functionId"]);
|
|
1967
|
+
}),
|
|
1968
|
+
onAbort: guarded((e) => {
|
|
1969
|
+
failed(str(e["callId"]), "aborted", e["functionId"]);
|
|
1970
|
+
}),
|
|
1971
|
+
onEnd: guarded((e) => {
|
|
1972
|
+
const callId = str(e["callId"]);
|
|
1973
|
+
if (!callId) return;
|
|
1974
|
+
const call = calls.get(callId);
|
|
1975
|
+
if (!call) return;
|
|
1976
|
+
closeModelCall(call);
|
|
1977
|
+
calls.delete(callId);
|
|
1978
|
+
}),
|
|
1979
|
+
executeLanguageModelCall(callOptions) {
|
|
1980
|
+
if (!bound2) return callOptions.execute();
|
|
1981
|
+
return runInsideAiModelCall(() => callOptions.execute());
|
|
1982
|
+
}
|
|
1983
|
+
};
|
|
1984
|
+
Object.defineProperty(integration, BRAND, { value: true });
|
|
1985
|
+
return integration;
|
|
1986
|
+
}
|
|
1987
|
+
var shared = null;
|
|
1988
|
+
function sightTelemetry(options) {
|
|
1989
|
+
if (options && options.sessionId !== void 0) return createIntegration(options);
|
|
1990
|
+
shared ??= createIntegration({});
|
|
1991
|
+
return shared;
|
|
1992
|
+
}
|
|
1993
|
+
function canRequireEsModule() {
|
|
1994
|
+
const [major = 0, minor = 0] = process.versions.node.split(".").map(Number);
|
|
1995
|
+
return major >= 24 || major === 23 && minor >= 5 || major === 22 && minor >= 13;
|
|
1996
|
+
}
|
|
1997
|
+
var defaultLoaders = {
|
|
1998
|
+
// `ai` reads its integration list when a call starts, so a registration
|
|
1999
|
+
// that lands a tick after init would miss a call made right after init.
|
|
2000
|
+
// `ai` 7 is ES module only; where require() can load it this registers
|
|
2001
|
+
// before init returns, and anywhere else the asynchronous import is used.
|
|
2002
|
+
// createRequire, never a bare `require`: the bundler replaces a bare one
|
|
2003
|
+
// in the ES module build with a stub that always throws.
|
|
2004
|
+
sync: () => canRequireEsModule() ? module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)))("ai") : null,
|
|
2005
|
+
async: () => import('ai')
|
|
2006
|
+
};
|
|
2007
|
+
function globalIntegrations() {
|
|
2008
|
+
const list = globalThis.AI_SDK_TELEMETRY_INTEGRATIONS;
|
|
2009
|
+
return Array.isArray(list) ? list : [];
|
|
2010
|
+
}
|
|
2011
|
+
var registered = false;
|
|
2012
|
+
function register(mod, debug) {
|
|
2013
|
+
if (registered) return;
|
|
2014
|
+
const registerTelemetry = rec(mod)?.["registerTelemetry"];
|
|
2015
|
+
if (typeof registerTelemetry !== "function") {
|
|
2016
|
+
if (debug) {
|
|
2017
|
+
console.log(
|
|
2018
|
+
"[sight/vercel-ai] ai <7 found: no integration to register; calls made with experimental_telemetry: { isEnabled: true } are captured from their OpenTelemetry spans"
|
|
2019
|
+
);
|
|
2020
|
+
}
|
|
2021
|
+
return;
|
|
2022
|
+
}
|
|
2023
|
+
registered = true;
|
|
2024
|
+
if (globalIntegrations().some(isSightIntegration)) {
|
|
2025
|
+
if (debug) console.log("[sight/vercel-ai] telemetry integration already registered");
|
|
2026
|
+
return;
|
|
2027
|
+
}
|
|
2028
|
+
registerTelemetry(sightTelemetry());
|
|
2029
|
+
if (debug) {
|
|
2030
|
+
console.log(
|
|
2031
|
+
"[sight/vercel-ai] telemetry integration registered; generateText, streamText, generateObject and streamObject calls are captured, one turn per model call"
|
|
2032
|
+
);
|
|
2033
|
+
}
|
|
2034
|
+
}
|
|
2035
|
+
async function registerVercelAI(state2, captureFn, loaders = defaultLoaders) {
|
|
2036
|
+
if (captureFn) bindVercelAI(state2, captureFn);
|
|
2037
|
+
if (registered) return;
|
|
2038
|
+
const debug = state2.config.debug;
|
|
2039
|
+
let mod = null;
|
|
2040
|
+
try {
|
|
2041
|
+
mod = loaders.sync();
|
|
2042
|
+
} catch {
|
|
2043
|
+
mod = null;
|
|
2044
|
+
}
|
|
2045
|
+
if (mod === null || mod === void 0) {
|
|
2046
|
+
try {
|
|
2047
|
+
mod = await loaders.async();
|
|
2048
|
+
} catch {
|
|
2049
|
+
if (debug) {
|
|
2050
|
+
console.log(
|
|
2051
|
+
"[sight/vercel-ai] ai is not installed; nothing registered. If ai is bundled where the SDK cannot resolve it, call registerTelemetry(sightTelemetry())."
|
|
2052
|
+
);
|
|
2053
|
+
}
|
|
2054
|
+
return;
|
|
2055
|
+
}
|
|
2056
|
+
}
|
|
2057
|
+
try {
|
|
2058
|
+
register(mod, debug);
|
|
2059
|
+
} catch (err) {
|
|
2060
|
+
if (debug) {
|
|
2061
|
+
console.warn(
|
|
2062
|
+
`[sight/vercel-ai] telemetry integration not registered (${err instanceof Error ? err.message : err})`
|
|
2063
|
+
);
|
|
2064
|
+
}
|
|
2065
|
+
}
|
|
2066
|
+
}
|
|
1180
2067
|
|
|
1181
2068
|
// src/instrumentation/setup.ts
|
|
1182
2069
|
var installedProcessor = null;
|
|
@@ -1201,13 +2088,14 @@ function setupOtelProvider(state2, captureFn) {
|
|
|
1201
2088
|
function detachOtelState() {
|
|
1202
2089
|
installedProcessor?.rebind(null);
|
|
1203
2090
|
unbindWrapOpenAI();
|
|
2091
|
+
unbindVercelAI();
|
|
1204
2092
|
}
|
|
1205
2093
|
|
|
1206
2094
|
// src/instrumentation/openai.ts
|
|
1207
|
-
var
|
|
2095
|
+
var registered2 = false;
|
|
1208
2096
|
var instrumentation = null;
|
|
1209
2097
|
async function registerOpenAI(state2) {
|
|
1210
|
-
if (
|
|
2098
|
+
if (registered2) return;
|
|
1211
2099
|
try {
|
|
1212
2100
|
const mod = await import('@traceloop/instrumentation-openai');
|
|
1213
2101
|
instrumentation = new mod.OpenAIInstrumentation({
|
|
@@ -1215,18 +2103,18 @@ async function registerOpenAI(state2) {
|
|
|
1215
2103
|
exceptionLogger: (err) => {
|
|
1216
2104
|
if (state2.config.debug) {
|
|
1217
2105
|
console.error(
|
|
1218
|
-
`[
|
|
2106
|
+
`[sight/openai] instrumentation exception: ${err instanceof Error ? err.message : err}`
|
|
1219
2107
|
);
|
|
1220
2108
|
}
|
|
1221
2109
|
}
|
|
1222
2110
|
});
|
|
1223
2111
|
instrumentation.enable();
|
|
1224
|
-
|
|
2112
|
+
registered2 = true;
|
|
1225
2113
|
void verifyPatchAttached();
|
|
1226
2114
|
} catch (err) {
|
|
1227
2115
|
if (state2.config.debug) {
|
|
1228
2116
|
const msg = err instanceof Error ? err.message : String(err);
|
|
1229
|
-
console.warn(`[
|
|
2117
|
+
console.warn(`[sight/openai] instrumentation not enabled (${msg}); library not installed?`);
|
|
1230
2118
|
}
|
|
1231
2119
|
}
|
|
1232
2120
|
}
|
|
@@ -1236,94 +2124,85 @@ function isPatchDetached(mod) {
|
|
|
1236
2124
|
if (typeof create !== "function") return true;
|
|
1237
2125
|
return create.__wrapped !== true;
|
|
1238
2126
|
}
|
|
2127
|
+
function patchWarning(mod, wrappedClientInUse) {
|
|
2128
|
+
if (!isPatchDetached(mod)) return null;
|
|
2129
|
+
if (wrappedClientInUse) return null;
|
|
2130
|
+
const version = mod?.default?.VERSION ?? mod?.VERSION;
|
|
2131
|
+
return `[sight] OpenAI module patching did not attach` + (version ? ` (openai v${version})` : "") + `. This happens on openai >=5, under ESM, or when 'openai' loads before init. Calls through a client passed to wrapOpenAI() are captured; calls through an unwrapped OpenAI client are not. import { wrapOpenAI } from '@cultured_computer/sight'; const client = wrapOpenAI(new OpenAI()).`;
|
|
2132
|
+
}
|
|
1239
2133
|
async function verifyPatchAttached() {
|
|
1240
2134
|
try {
|
|
1241
2135
|
const mod = await import('openai');
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
console.warn(
|
|
1245
|
-
`[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.`
|
|
1246
|
-
);
|
|
2136
|
+
const line = patchWarning(mod, hasWrappedClient());
|
|
2137
|
+
if (line !== null) console.warn(line);
|
|
1247
2138
|
} catch {
|
|
1248
2139
|
}
|
|
1249
2140
|
}
|
|
1250
2141
|
|
|
1251
2142
|
// src/instrumentation/anthropic.ts
|
|
1252
|
-
var
|
|
2143
|
+
var registered3 = false;
|
|
1253
2144
|
var instrumentation2 = null;
|
|
1254
2145
|
async function registerAnthropic(state2) {
|
|
1255
|
-
if (
|
|
2146
|
+
if (registered3) return;
|
|
1256
2147
|
try {
|
|
1257
2148
|
const mod = await import('@traceloop/instrumentation-anthropic');
|
|
1258
2149
|
instrumentation2 = new mod.AnthropicInstrumentation({
|
|
1259
2150
|
exceptionLogger: (err) => {
|
|
1260
2151
|
if (state2.config.debug) {
|
|
1261
2152
|
console.error(
|
|
1262
|
-
`[
|
|
2153
|
+
`[sight/anthropic] instrumentation exception: ${err instanceof Error ? err.message : err}`
|
|
1263
2154
|
);
|
|
1264
2155
|
}
|
|
1265
2156
|
}
|
|
1266
2157
|
});
|
|
1267
2158
|
instrumentation2.enable();
|
|
1268
|
-
|
|
2159
|
+
registered3 = true;
|
|
1269
2160
|
} catch (err) {
|
|
1270
2161
|
if (state2.config.debug) {
|
|
1271
2162
|
const msg = err instanceof Error ? err.message : String(err);
|
|
1272
2163
|
console.warn(
|
|
1273
|
-
`[
|
|
2164
|
+
`[sight/anthropic] instrumentation not enabled (${msg}); library not installed?`
|
|
1274
2165
|
);
|
|
1275
2166
|
}
|
|
1276
2167
|
}
|
|
1277
2168
|
}
|
|
1278
2169
|
|
|
1279
2170
|
// src/instrumentation/langchain.ts
|
|
1280
|
-
var
|
|
2171
|
+
var registered4 = false;
|
|
1281
2172
|
var instrumentation3 = null;
|
|
1282
2173
|
async function registerLangChain(state2) {
|
|
1283
|
-
if (
|
|
2174
|
+
if (registered4) return;
|
|
1284
2175
|
try {
|
|
1285
2176
|
const mod = await import('@traceloop/instrumentation-langchain');
|
|
1286
2177
|
instrumentation3 = new mod.LangChainInstrumentation({
|
|
1287
2178
|
exceptionLogger: (err) => {
|
|
1288
2179
|
if (state2.config.debug) {
|
|
1289
2180
|
console.error(
|
|
1290
|
-
`[
|
|
2181
|
+
`[sight/langchain] instrumentation exception: ${err instanceof Error ? err.message : err}`
|
|
1291
2182
|
);
|
|
1292
2183
|
}
|
|
1293
2184
|
}
|
|
1294
2185
|
});
|
|
1295
2186
|
instrumentation3.enable();
|
|
1296
|
-
|
|
2187
|
+
registered4 = true;
|
|
1297
2188
|
} catch (err) {
|
|
1298
2189
|
if (state2.config.debug) {
|
|
1299
2190
|
const msg = err instanceof Error ? err.message : String(err);
|
|
1300
2191
|
console.warn(
|
|
1301
|
-
`[
|
|
2192
|
+
`[sight/langchain] instrumentation not enabled (${msg}); library not installed?`
|
|
1302
2193
|
);
|
|
1303
2194
|
}
|
|
1304
2195
|
}
|
|
1305
2196
|
}
|
|
1306
2197
|
|
|
1307
2198
|
// src/instrumentation/langgraph.ts
|
|
1308
|
-
var registered4 = false;
|
|
1309
|
-
async function registerLangGraph(state2) {
|
|
1310
|
-
if (registered4) return;
|
|
1311
|
-
registered4 = true;
|
|
1312
|
-
if (state2.config.debug) {
|
|
1313
|
-
console.log(
|
|
1314
|
-
"[probe/langgraph] active via LangChain instrumentation; pass thread_id in RunnableConfig for topology"
|
|
1315
|
-
);
|
|
1316
|
-
}
|
|
1317
|
-
}
|
|
1318
|
-
|
|
1319
|
-
// src/instrumentation/vercel-ai.ts
|
|
1320
2199
|
var registered5 = false;
|
|
1321
|
-
async function
|
|
2200
|
+
async function registerLangGraph(state2) {
|
|
1322
2201
|
if (registered5) return;
|
|
1323
2202
|
registered5 = true;
|
|
1324
2203
|
if (state2.config.debug) {
|
|
1325
2204
|
console.log(
|
|
1326
|
-
"[
|
|
2205
|
+
"[sight/langgraph] active via LangChain instrumentation; pass thread_id in RunnableConfig for topology"
|
|
1327
2206
|
);
|
|
1328
2207
|
}
|
|
1329
2208
|
}
|
|
@@ -1335,7 +2214,7 @@ async function registerLiteLLM(state2) {
|
|
|
1335
2214
|
registered6 = true;
|
|
1336
2215
|
if (state2.config.debug) {
|
|
1337
2216
|
console.log(
|
|
1338
|
-
"[
|
|
2217
|
+
"[sight/litellm] LiteLLM (Python) traffic is not captured by this SDK"
|
|
1339
2218
|
);
|
|
1340
2219
|
}
|
|
1341
2220
|
}
|
|
@@ -1347,7 +2226,7 @@ async function registerMercury(state2) {
|
|
|
1347
2226
|
registered7 = true;
|
|
1348
2227
|
if (state2.config.debug) {
|
|
1349
2228
|
console.log(
|
|
1350
|
-
"[
|
|
2229
|
+
"[sight/mercury] active; OpenAI-SDK path via baseURL override is the primary capture route"
|
|
1351
2230
|
);
|
|
1352
2231
|
}
|
|
1353
2232
|
}
|
|
@@ -1361,7 +2240,7 @@ function registerAllInstrumentations(state2, captureFn) {
|
|
|
1361
2240
|
registerAnthropic(state2),
|
|
1362
2241
|
registerLangChain(state2),
|
|
1363
2242
|
registerLangGraph(state2),
|
|
1364
|
-
registerVercelAI(state2),
|
|
2243
|
+
registerVercelAI(state2, captureFn),
|
|
1365
2244
|
registerLiteLLM(state2),
|
|
1366
2245
|
registerMercury(state2)
|
|
1367
2246
|
];
|
|
@@ -1532,7 +2411,7 @@ var UserOutcomeSchema = zod.z.object({
|
|
|
1532
2411
|
/** Thumbs-up / thumbs-down widget value. */
|
|
1533
2412
|
thumbs: zod.z.enum(["up", "down"]).optional()
|
|
1534
2413
|
});
|
|
1535
|
-
zod.z.object({
|
|
2414
|
+
var TurnInputSchema = zod.z.object({
|
|
1536
2415
|
deploymentSlug: zod.z.string().min(1),
|
|
1537
2416
|
sessionExternalId: zod.z.string().min(1),
|
|
1538
2417
|
/**
|
|
@@ -1551,6 +2430,8 @@ zod.z.object({
|
|
|
1551
2430
|
*/
|
|
1552
2431
|
externalUserId: zod.z.string().min(1).optional(),
|
|
1553
2432
|
turnIndex: zod.z.number().int().nonnegative(),
|
|
2433
|
+
// the SDK's identity for one logical turn; with it, an index collision takes the next index instead of dropping
|
|
2434
|
+
turnId: zod.z.string().uuid().optional(),
|
|
1554
2435
|
/**
|
|
1555
2436
|
* Caller-asserted turn timestamp (ISO). OPTIONAL and honored by the
|
|
1556
2437
|
* worker: when present it becomes turns.started_at; when absent the
|
|
@@ -1615,7 +2496,8 @@ zod.z.object({
|
|
|
1615
2496
|
* All optional. Powers Chapter 8e′ Card 3 version behavioral diff.
|
|
1616
2497
|
*/
|
|
1617
2498
|
agentId: zod.z.string().optional(),
|
|
1618
|
-
|
|
2499
|
+
// Endpoint capture explicitly records no experiment; older SDKs omit it.
|
|
2500
|
+
experimentId: zod.z.string().nullish().transform((value) => value ?? void 0),
|
|
1619
2501
|
environmentConfigHash: zod.z.string().optional(),
|
|
1620
2502
|
environmentConfigLabel: zod.z.string().optional(),
|
|
1621
2503
|
/** Internal Studio runner provenance. Customer SDKs never set this. */
|
|
@@ -1638,7 +2520,7 @@ zod.z.object({
|
|
|
1638
2520
|
clientContext: zod.z.record(zod.z.string(), zod.z.unknown()).optional(),
|
|
1639
2521
|
payload: zod.z.record(zod.z.string(), zod.z.unknown())
|
|
1640
2522
|
});
|
|
1641
|
-
zod.z.object({
|
|
2523
|
+
var SessionEndSchema2 = zod.z.object({
|
|
1642
2524
|
deploymentSlug: zod.z.string().min(1),
|
|
1643
2525
|
sessionExternalId: zod.z.string().min(1),
|
|
1644
2526
|
/** Why the session ended. */
|
|
@@ -1653,6 +2535,13 @@ zod.z.object({
|
|
|
1653
2535
|
/** ISO timestamp of session end. */
|
|
1654
2536
|
endedAt: zod.z.string().optional()
|
|
1655
2537
|
});
|
|
2538
|
+
var ENGINE_ENDED_REASONS = ["floor", "turn_cap"];
|
|
2539
|
+
SessionEndSchema2.extend({
|
|
2540
|
+
endedReason: zod.z.enum([
|
|
2541
|
+
...SessionEndSchema2.shape.endedReason.unwrap().options,
|
|
2542
|
+
...ENGINE_ENDED_REASONS
|
|
2543
|
+
]).optional()
|
|
2544
|
+
});
|
|
1656
2545
|
zod.z.object({
|
|
1657
2546
|
deploymentSlug: zod.z.string().min(1),
|
|
1658
2547
|
sessionExternalId: zod.z.string().min(1),
|
|
@@ -2076,9 +2965,25 @@ function validateOrDrop(schema, input, method) {
|
|
|
2076
2965
|
}
|
|
2077
2966
|
return result.data;
|
|
2078
2967
|
}
|
|
2968
|
+
var SessionRefSchema = zod.z.object({ externalId: zod.z.string().min(1) });
|
|
2969
|
+
var UserInputSubmitSchema = SessionRefSchema.extend({ text: zod.z.string() });
|
|
2970
|
+
var UserThumbsSchema = SessionRefSchema.extend({
|
|
2971
|
+
thumbs: zod.z.enum(["up", "down"])
|
|
2972
|
+
});
|
|
2973
|
+
var UserRatingSchema = SessionRefSchema.extend({
|
|
2974
|
+
rating: zod.z.number().int().min(1).max(5)
|
|
2975
|
+
});
|
|
2976
|
+
function newTurnId() {
|
|
2977
|
+
const c = globalThis.crypto;
|
|
2978
|
+
if (c && typeof c.randomUUID === "function") return c.randomUUID();
|
|
2979
|
+
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (ch) => {
|
|
2980
|
+
const r = Math.floor(Math.random() * 16);
|
|
2981
|
+
return (ch === "x" ? r : r & 3 | 8).toString(16);
|
|
2982
|
+
});
|
|
2983
|
+
}
|
|
2079
2984
|
var Probe = class {
|
|
2080
2985
|
/**
|
|
2081
|
-
* Initialize the
|
|
2986
|
+
* Initialize the SDK. Call once at process start. Subsequent calls are
|
|
2082
2987
|
* no-ops with a warning; re-init requires a shutdown() first.
|
|
2083
2988
|
*/
|
|
2084
2989
|
static init(config) {
|
|
@@ -2110,16 +3015,23 @@ var Probe = class {
|
|
|
2110
3015
|
)
|
|
2111
3016
|
);
|
|
2112
3017
|
}
|
|
2113
|
-
registerAllInstrumentations(
|
|
3018
|
+
registerAllInstrumentations(
|
|
3019
|
+
state,
|
|
3020
|
+
(turn, hints) => this.captureWithHints(turn, hints)
|
|
3021
|
+
);
|
|
2114
3022
|
}
|
|
2115
3023
|
/**
|
|
2116
|
-
* Run a callback inside a session
|
|
2117
|
-
*
|
|
2118
|
-
*
|
|
2119
|
-
*
|
|
3024
|
+
* Run a callback inside a session scope. Every LLM call made inside `fn`
|
|
3025
|
+
* through a wrapped OpenAI client or an instrumented library is captured
|
|
3026
|
+
* as a turn on the session `sessionId`.
|
|
3027
|
+
*
|
|
3028
|
+
* Autocapture needs this scope: a call made outside any session scope is
|
|
3029
|
+
* not captured. The first such call in a process prints one warning;
|
|
3030
|
+
* later ones log only with `debug: true`. (Spans that carry
|
|
3031
|
+
* `gen_ai.conversation.id` are the one exception: with no scope, that id
|
|
3032
|
+
* is used as the session id. An explicit scope always wins.)
|
|
2120
3033
|
*
|
|
2121
|
-
*
|
|
2122
|
-
* processor reads the session ID from baggage when each LLM span ends.
|
|
3034
|
+
* The scope is carried in OpenTelemetry baggage across awaits.
|
|
2123
3035
|
*/
|
|
2124
3036
|
static async withSession(sessionId, fn) {
|
|
2125
3037
|
if (state === null) {
|
|
@@ -2164,12 +3076,12 @@ var Probe = class {
|
|
|
2164
3076
|
const validated = validateOrDrop(SessionStartSchema, input, "startSession");
|
|
2165
3077
|
if (validated === null) return;
|
|
2166
3078
|
const existing = state.sessions.get(validated.externalId);
|
|
2167
|
-
const
|
|
3079
|
+
const now2 = Date.now();
|
|
2168
3080
|
const session = {
|
|
2169
3081
|
externalId: validated.externalId,
|
|
2170
3082
|
externalUserId: validated.externalUserId ?? existing?.externalUserId ?? null,
|
|
2171
3083
|
turnIndex: existing?.turnIndex ?? 0,
|
|
2172
|
-
startedAt: existing?.startedAt ??
|
|
3084
|
+
startedAt: existing?.startedAt ?? now2,
|
|
2173
3085
|
personaSlug: validated.persona ?? existing?.personaSlug ?? state.persona?.slug ?? null,
|
|
2174
3086
|
metadata: validated.metadata ?? existing?.metadata ?? null,
|
|
2175
3087
|
openedVia: validated.openedVia ?? existing?.openedVia ?? null,
|
|
@@ -2225,7 +3137,7 @@ var Probe = class {
|
|
|
2225
3137
|
}
|
|
2226
3138
|
/**
|
|
2227
3139
|
* Compute a stable SHA-256 hex hash of prompt/config text for use as
|
|
2228
|
-
* `environmentConfigHash` on
|
|
3140
|
+
* `environmentConfigHash` on Sight.startSession(). Hash is *identity*:
|
|
2229
3141
|
* pass the human-readable version alongside as `environmentConfigLabel`
|
|
2230
3142
|
* for the diff table axis (a card keyed by a3f9c2… is unreadable).
|
|
2231
3143
|
*
|
|
@@ -2260,8 +3172,10 @@ var Probe = class {
|
|
|
2260
3172
|
*/
|
|
2261
3173
|
static async endSession(externalId) {
|
|
2262
3174
|
if (state === null) return;
|
|
3175
|
+
const validEnd = typeof externalId === "string" ? validateOrDrop(SessionRefSchema, { externalId }, "endSession") : validateOrDrop(SessionEndSchema, externalId, "endSession");
|
|
3176
|
+
if (validEnd === null) return;
|
|
2263
3177
|
const externalIdStr = typeof externalId === "string" ? externalId : externalId.externalId;
|
|
2264
|
-
const endedReason = typeof externalId === "string" ?
|
|
3178
|
+
const endedReason = typeof externalId === "string" ? "natural" : externalId.endedReason ?? "natural";
|
|
2265
3179
|
const declared = typeof externalId === "string" ? void 0 : externalId.outcome;
|
|
2266
3180
|
if (declared) {
|
|
2267
3181
|
await this.emitOutcomeEvent({
|
|
@@ -2315,28 +3229,30 @@ var Probe = class {
|
|
|
2315
3229
|
// before startSession or the first LLM call) buffer per externalId and
|
|
2316
3230
|
// flush into the session when it is created.
|
|
2317
3231
|
/**
|
|
2318
|
-
*
|
|
2319
|
-
*
|
|
3232
|
+
* The person started typing. Records the first-keystroke time, sent as
|
|
3233
|
+
* `userInput.firstKeystrokeMs` with the next captured turn. Derivable
|
|
2320
3234
|
* only once a previous agent turn exists; a pre-session typing start
|
|
2321
3235
|
* buffers the pending-input entry without a firstKeystrokeMs value.
|
|
2322
3236
|
*/
|
|
2323
3237
|
static userInputStart(externalId) {
|
|
2324
3238
|
if (state === null) return;
|
|
3239
|
+
if (validateOrDrop(SessionRefSchema, { externalId }, "userInputStart") === null) return;
|
|
2325
3240
|
const session = state.sessions.get(externalId);
|
|
2326
3241
|
const target = session ?? this.preSessionEntry(externalId);
|
|
2327
|
-
const
|
|
2328
|
-
const firstKeystrokeMs = session?.lastAgentTurnAt != null ? Math.max(0,
|
|
3242
|
+
const now2 = Date.now();
|
|
3243
|
+
const firstKeystrokeMs = session?.lastAgentTurnAt != null ? Math.max(0, now2 - session.lastAgentTurnAt) : void 0;
|
|
2329
3244
|
target.pendingUserInput = {
|
|
2330
3245
|
...target.pendingUserInput ?? { editCount: 0 },
|
|
2331
3246
|
firstKeystrokeMs: target.pendingUserInput?.firstKeystrokeMs ?? firstKeystrokeMs
|
|
2332
3247
|
};
|
|
2333
3248
|
}
|
|
2334
3249
|
/**
|
|
2335
|
-
*
|
|
2336
|
-
*
|
|
3250
|
+
* The person pressed backspace or edited. Increments the edit count,
|
|
3251
|
+
* sent as `userInput.editCount` with the next captured turn.
|
|
2337
3252
|
*/
|
|
2338
3253
|
static userInputEdit(externalId) {
|
|
2339
3254
|
if (state === null) return;
|
|
3255
|
+
if (validateOrDrop(SessionRefSchema, { externalId }, "userInputEdit") === null) return;
|
|
2340
3256
|
const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);
|
|
2341
3257
|
target.pendingUserInput = {
|
|
2342
3258
|
...target.pendingUserInput ?? { editCount: 0 },
|
|
@@ -2344,36 +3260,41 @@ var Probe = class {
|
|
|
2344
3260
|
};
|
|
2345
3261
|
}
|
|
2346
3262
|
/**
|
|
2347
|
-
*
|
|
2348
|
-
* server-side before
|
|
2349
|
-
* timestamp
|
|
2350
|
-
*
|
|
2351
|
-
* agent turn → submit).
|
|
3263
|
+
* The person submitted their message. Records the text (scrubbed of
|
|
3264
|
+
* personal data server-side before it is stored) plus the submit
|
|
3265
|
+
* timestamp. The text and timings are sent with the NEXT captured turn:
|
|
3266
|
+
* a turn's person text is the message that prompted its reply.
|
|
2352
3267
|
*/
|
|
2353
3268
|
static userInputSubmit(externalId, text) {
|
|
2354
3269
|
if (state === null) return;
|
|
3270
|
+
if (validateOrDrop(UserInputSubmitSchema, { externalId, text }, "userInputSubmit") === null)
|
|
3271
|
+
return;
|
|
2355
3272
|
const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);
|
|
2356
|
-
const
|
|
3273
|
+
const now2 = Date.now();
|
|
2357
3274
|
target.pendingUserInput = {
|
|
2358
3275
|
...target.pendingUserInput ?? { editCount: 0 },
|
|
2359
3276
|
text,
|
|
2360
|
-
submittedAt:
|
|
3277
|
+
submittedAt: now2
|
|
2361
3278
|
};
|
|
2362
|
-
target.lastUserSubmitAt =
|
|
3279
|
+
target.lastUserSubmitAt = now2;
|
|
2363
3280
|
}
|
|
2364
3281
|
/** Attach a thumbs-up/down to the current turn. */
|
|
2365
3282
|
static userThumbs(externalId, thumbs) {
|
|
2366
3283
|
if (state === null) return;
|
|
3284
|
+
if (validateOrDrop(UserThumbsSchema, { externalId, thumbs }, "userThumbs") === null) return;
|
|
2367
3285
|
const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);
|
|
2368
3286
|
target.pendingUserOutcome = {
|
|
2369
3287
|
...target.pendingUserOutcome ?? {},
|
|
2370
3288
|
thumbs
|
|
2371
3289
|
};
|
|
2372
3290
|
}
|
|
2373
|
-
/**
|
|
3291
|
+
/**
|
|
3292
|
+
* Attach an explicit rating to the current turn: an integer from 1 to 5.
|
|
3293
|
+
* Any other value logs one warning line and is dropped.
|
|
3294
|
+
*/
|
|
2374
3295
|
static userRating(externalId, rating) {
|
|
2375
3296
|
if (state === null) return;
|
|
2376
|
-
if (
|
|
3297
|
+
if (validateOrDrop(UserRatingSchema, { externalId, rating }, "userRating") === null) return;
|
|
2377
3298
|
const target = state.sessions.get(externalId) ?? this.preSessionEntry(externalId);
|
|
2378
3299
|
target.pendingUserOutcome = {
|
|
2379
3300
|
...target.pendingUserOutcome ?? {},
|
|
@@ -2407,27 +3328,56 @@ var Probe = class {
|
|
|
2407
3328
|
state.outcomeHook = hook;
|
|
2408
3329
|
}
|
|
2409
3330
|
/**
|
|
2410
|
-
* Manually capture a turn.
|
|
2411
|
-
*
|
|
3331
|
+
* Manually capture a turn. For callers that do not use autocapture.
|
|
3332
|
+
*
|
|
3333
|
+
* - `deploymentSlug` may be omitted: the `deployment` given to `init` is
|
|
3334
|
+
* used. An explicit value wins.
|
|
3335
|
+
* - Every turn is sent with a `turnId` (a fresh UUID unless you supply
|
|
3336
|
+
* one). A retried send carries the same `turnId`.
|
|
3337
|
+
* - The turn is validated before it is sent. An invalid turn logs one
|
|
3338
|
+
* warning line naming the first invalid field and is dropped; nothing
|
|
3339
|
+
* is sent.
|
|
2412
3340
|
*
|
|
2413
3341
|
* Persona resolution order for the outgoing turn payload:
|
|
2414
3342
|
* 1. turn.personaSlug (turn-level override)
|
|
2415
|
-
* 2.
|
|
2416
|
-
* 3.
|
|
3343
|
+
* 2. the session's persona (from startSession)
|
|
3344
|
+
* 3. the init-level default
|
|
2417
3345
|
*
|
|
2418
|
-
* Signature-phrase matching runs
|
|
3346
|
+
* Signature-phrase matching runs in the SDK when the resolved persona
|
|
2419
3347
|
* has signature phrases registered. The matched slug list is attached to
|
|
2420
3348
|
* `turn.signaturePhraseMatches` before send.
|
|
2421
3349
|
*/
|
|
2422
3350
|
static async captureTurn(turn) {
|
|
3351
|
+
return this.captureWithHints(turn);
|
|
3352
|
+
}
|
|
3353
|
+
/**
|
|
3354
|
+
* The one capture path. Manual captureTurn calls and autocapture both
|
|
3355
|
+
* land here; autocapture also passes what it observed on the request
|
|
3356
|
+
* (`hints`), applied below under the explicit-input-wins rule.
|
|
3357
|
+
*/
|
|
3358
|
+
static async captureWithHints(input, hints) {
|
|
2423
3359
|
if (state === null) {
|
|
2424
3360
|
return;
|
|
2425
3361
|
}
|
|
2426
|
-
if (
|
|
3362
|
+
if (input === null || typeof input !== "object") {
|
|
3363
|
+
validateOrDrop(TurnInputSchema, input, "captureTurn");
|
|
2427
3364
|
return;
|
|
2428
3365
|
}
|
|
2429
|
-
|
|
2430
|
-
|
|
3366
|
+
const turn = {
|
|
3367
|
+
...input,
|
|
3368
|
+
deploymentSlug: input.deploymentSlug ?? state.config.deployment,
|
|
3369
|
+
turnId: input.turnId ?? newTurnId(),
|
|
3370
|
+
payload: input.payload === void 0 || input.payload === null ? {} : input.payload
|
|
3371
|
+
};
|
|
3372
|
+
const payloadPropensity = typeof turn.payload === "object" ? turn.payload.propensity : void 0;
|
|
3373
|
+
const checked = validateOrDrop(
|
|
3374
|
+
TurnInputSchema,
|
|
3375
|
+
{ ...turn, propensity: turn.propensity ?? payloadPropensity },
|
|
3376
|
+
"captureTurn"
|
|
3377
|
+
);
|
|
3378
|
+
if (checked === null) return;
|
|
3379
|
+
if (!this.shouldSample(turn.sessionExternalId, turn.turnIndex)) {
|
|
3380
|
+
return;
|
|
2431
3381
|
}
|
|
2432
3382
|
const propensity = turn.propensity ?? turn.payload.propensity;
|
|
2433
3383
|
let validPropensity = propensity;
|
|
@@ -2495,6 +3445,9 @@ var Probe = class {
|
|
|
2495
3445
|
if (session.pendingUserOutcome && !userOutcome) {
|
|
2496
3446
|
userOutcome = session.pendingUserOutcome;
|
|
2497
3447
|
}
|
|
3448
|
+
if (hints?.observedUserText && !userInput?.text) {
|
|
3449
|
+
userInput = { ...userInput ?? {}, text: hints.observedUserText };
|
|
3450
|
+
}
|
|
2498
3451
|
if (!interactivity && session.lastUserSubmitAt) {
|
|
2499
3452
|
interactivity = {
|
|
2500
3453
|
agentReflectMs: Math.max(0, Date.now() - session.lastUserSubmitAt)
|
|
@@ -2522,7 +3475,7 @@ var Probe = class {
|
|
|
2522
3475
|
envelopeVersion: SDK_ENVELOPE_VERSION,
|
|
2523
3476
|
personaSlug: resolvedPersona,
|
|
2524
3477
|
signaturePhraseMatches: signatureMatches,
|
|
2525
|
-
// User identity from the local session entry (
|
|
3478
|
+
// User identity from the local session entry (Sight.startSession).
|
|
2526
3479
|
// The worker persists it on sessions.external_user_id; never the
|
|
2527
3480
|
// session key. Turn-level override wins for advanced callers.
|
|
2528
3481
|
externalUserId: turn.externalUserId ?? session.externalUserId ?? void 0,
|
|
@@ -2538,7 +3491,7 @@ var Probe = class {
|
|
|
2538
3491
|
// columns (e2e audit 2026-07-13).
|
|
2539
3492
|
propensity: validPropensity,
|
|
2540
3493
|
// Forward RLDS provenance from the local session entry (populated
|
|
2541
|
-
// by
|
|
3494
|
+
// by Sight.startSession). Worker persists at first-turn session
|
|
2542
3495
|
// create; nulls stay null.
|
|
2543
3496
|
agentId: session.agentId ?? void 0,
|
|
2544
3497
|
experimentId: session.experimentId ?? void 0,
|
|
@@ -2547,8 +3500,8 @@ var Probe = class {
|
|
|
2547
3500
|
});
|
|
2548
3501
|
}
|
|
2549
3502
|
/**
|
|
2550
|
-
* Emit a custom outcome event on a session
|
|
2551
|
-
*
|
|
3503
|
+
* Emit a custom outcome event on a session, stored with the `kind`
|
|
3504
|
+
* string you supply. Use for
|
|
2552
3505
|
* customer-defined kinds like "purchase_complete", "handoff_to_human",
|
|
2553
3506
|
* "character_break_severe". Universal seed kinds (break, escalation,
|
|
2554
3507
|
* resolution, thumbs_*, rating_*) are also emitted by worker-side
|
|
@@ -2752,6 +3705,7 @@ exports.SpanInputV2Schema = SpanInputV2Schema;
|
|
|
2752
3705
|
exports.SpanIntervalSchema = SpanIntervalSchema;
|
|
2753
3706
|
exports.SpanPayloadSchema = SpanPayloadSchema;
|
|
2754
3707
|
exports.SpansBatchSchema = SpansBatchSchema;
|
|
3708
|
+
exports.sightTelemetry = sightTelemetry;
|
|
2755
3709
|
exports.wrapOpenAI = wrapOpenAI;
|
|
2756
3710
|
//# sourceMappingURL=index.cjs.map
|
|
2757
3711
|
//# sourceMappingURL=index.cjs.map
|