@jini-ai/agent-runtime 0.6.12 → 0.6.15-rc.2
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 +33 -0
- package/dist/agent-protocol/acp/json.d.ts +1 -1
- package/dist/agent-protocol/acp/json.js +6 -3
- package/dist/agent-protocol/acp/models.js +53 -15
- package/dist/agent-protocol/acp/rpc.js +1 -1
- package/dist/agent-protocol/acp/session.d.ts +1 -1
- package/dist/agent-protocol/acp/session.js +30 -18
- package/dist/agent-protocol/acp/text-suppression.js +2 -1
- package/dist/ai-trace/capture.d.ts +17 -0
- package/dist/ai-trace/capture.js +43 -0
- package/dist/ai-trace/classify.d.ts +12 -0
- package/dist/ai-trace/classify.js +13 -0
- package/dist/ai-trace/index.d.ts +13 -0
- package/dist/ai-trace/index.js +6 -0
- package/dist/ai-trace/recorder.d.ts +65 -0
- package/dist/ai-trace/recorder.js +259 -0
- package/dist/ai-trace/sinks.d.ts +51 -0
- package/dist/ai-trace/sinks.js +137 -0
- package/dist/ai-trace/types.d.ts +123 -0
- package/dist/ai-trace/types.js +17 -0
- package/dist/ai-trace/usage.d.ts +13 -0
- package/dist/ai-trace/usage.js +43 -0
- package/dist/claude-filesystem-policy.d.ts +25 -3
- package/dist/claude-filesystem-policy.js +104 -14
- package/dist/core/model-discovery-shared.d.ts +28 -0
- package/dist/core/model-discovery-shared.js +88 -0
- package/dist/defs/antigravity.js +10 -2
- package/dist/defs/claude.js +2 -1
- package/dist/defs/codex.js +13 -2
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/model-discovery-adapters.js +1 -1
- package/dist/model-discovery-shared.d.ts +2 -27
- package/dist/model-discovery-shared.js +2 -87
- package/dist/model-discovery.d.ts +1 -1
- package/dist/model-discovery.js +2 -2
- package/dist/models.js +1 -1
- package/dist/providers/anthropic-messages.d.ts +1 -1
- package/dist/providers/anthropic-messages.js +10 -4
- package/dist/providers/tool-turn.js +12 -43
- package/dist/types.d.ts +4 -0
- package/package.json +16 -10
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module ai-trace/recorder
|
|
3
|
+
*
|
|
4
|
+
* Turns the normalized agent-event stream into {@link AiTraceEvent}s. Every provider path in the
|
|
5
|
+
* runtime already converges on one vocabulary before the daemon sees it — `status` (model),
|
|
6
|
+
* `text_delta`, `thinking_delta`, `tool_use`, `tool_result`, `usage`, `turn_end`, `error`, `end`
|
|
7
|
+
* — emitted by `claude-stream`, `copilot-stream`, `qoder-stream`, `json-event-stream` (Codex,
|
|
8
|
+
* OpenCode, Cursor, Kimi), the ACP session (Gemini/Codex/Hermes over ACP) and
|
|
9
|
+
* `runProviderToolTurn` (OpenAI/Anthropic/Azure/Google HTTP). Tapping that one vocabulary is
|
|
10
|
+
* what makes tracing provider-agnostic: no per-vendor code lives here.
|
|
11
|
+
*
|
|
12
|
+
* A model turn follows explicit request boundaries (`status: requesting`, `end`) when the stream has them;
|
|
13
|
+
* otherwise each usage report closes one turn (CLI per-step or per-run usage).
|
|
14
|
+
* Within a request, usage reports are snapshots, not boundaries: a final frame can contain usage AND more text.
|
|
15
|
+
* HTTP tool-turn produces one turn per call; CLIs that report once per run (Claude Code `result`,
|
|
16
|
+
* Copilot) produce one turn per run with all its tool calls — the granularity the provider gave,
|
|
17
|
+
* not a guess.
|
|
18
|
+
*/
|
|
19
|
+
import { captureText, stringifyForCapture } from './capture.js';
|
|
20
|
+
import { classifyToolError } from './classify.js';
|
|
21
|
+
import { addNullable, normalizeAiUsage } from './usage.js';
|
|
22
|
+
import { reportError } from './sinks.js';
|
|
23
|
+
function str(value) {
|
|
24
|
+
return typeof value === 'string' && value ? value : null;
|
|
25
|
+
}
|
|
26
|
+
function num(value) {
|
|
27
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : null;
|
|
28
|
+
}
|
|
29
|
+
export function createAiTraceRecorder({ sink, runId, agentId }, options = {}) {
|
|
30
|
+
const now = options.now ?? Date.now;
|
|
31
|
+
const traceId = options.traceId ?? runId;
|
|
32
|
+
const captureOptions = { mode: options.capture ?? sink.capture ?? 'metadata', maxChars: options.maxCapturedChars, exactSecrets: options.exactSecrets };
|
|
33
|
+
const capture = (text) => captureText({ text }, captureOptions);
|
|
34
|
+
const keepText = captureOptions.mode === 'full';
|
|
35
|
+
/** Streamed text: `full` redacts the kept text; other modes report the count without having kept it. */
|
|
36
|
+
const captureStreamed = (text, chars) => {
|
|
37
|
+
if (chars === 0 || captureOptions.mode === 'off')
|
|
38
|
+
return null;
|
|
39
|
+
return keepText ? capture(text) : { chars };
|
|
40
|
+
};
|
|
41
|
+
const pending = new Map();
|
|
42
|
+
const seenTools = new Set();
|
|
43
|
+
const totals = { turns: 0, toolCalls: 0, toolErrors: 0, inputTokens: null, outputTokens: null, costUsd: null };
|
|
44
|
+
let model = options.model ?? null;
|
|
45
|
+
let turn = null;
|
|
46
|
+
let lastBoundary = now();
|
|
47
|
+
let runInput = null;
|
|
48
|
+
let lastError = null;
|
|
49
|
+
let lastErrorCode = null;
|
|
50
|
+
// Set by the first `status: requesting`; streams without request boundaries keep usage-closes-turn.
|
|
51
|
+
let requestBounded = false;
|
|
52
|
+
let started = false;
|
|
53
|
+
let finished = false;
|
|
54
|
+
function record(event) {
|
|
55
|
+
try {
|
|
56
|
+
sink.record(event);
|
|
57
|
+
}
|
|
58
|
+
catch (error) {
|
|
59
|
+
reportError({ error, onError: options.onSinkError });
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
function start({ input = null }) {
|
|
63
|
+
if (started)
|
|
64
|
+
return;
|
|
65
|
+
started = true;
|
|
66
|
+
runInput = input;
|
|
67
|
+
lastBoundary = now();
|
|
68
|
+
record({ kind: 'run_started', traceId, runId, at: lastBoundary, agentId, provider: options.provider ?? null, model, sessionId: options.sessionId ?? null, input: capture(input), tags: options.tags ?? [] });
|
|
69
|
+
}
|
|
70
|
+
function noteInput({ input }) {
|
|
71
|
+
if (totals.turns === 0)
|
|
72
|
+
runInput = input;
|
|
73
|
+
}
|
|
74
|
+
function ensureTurn() {
|
|
75
|
+
if (!started)
|
|
76
|
+
start({});
|
|
77
|
+
turn ??= { toolCallCount: 0, id: `${traceId}:turn:${totals.turns}`, index: totals.turns, startedAt: lastBoundary, output: '', outputChars: 0, reasoning: '', reasoningChars: 0, firstTokenAt: null, ttftMs: null, stopReason: null, error: null, errorCode: null, usage: null, reportedCost: null };
|
|
78
|
+
return turn;
|
|
79
|
+
}
|
|
80
|
+
function resolveCost({ usage, reported }) {
|
|
81
|
+
const provided = num(reported);
|
|
82
|
+
if (provided !== null)
|
|
83
|
+
return { costUsd: provided, costSource: 'provider' };
|
|
84
|
+
let estimated = null;
|
|
85
|
+
try {
|
|
86
|
+
estimated = usage && options.priceUsage ? num(options.priceUsage({ model, usage })) : null;
|
|
87
|
+
}
|
|
88
|
+
catch (error) {
|
|
89
|
+
reportError({ error, onError: options.onSinkError });
|
|
90
|
+
}
|
|
91
|
+
return estimated === null ? { costUsd: null, costSource: null } : { costUsd: estimated, costSource: 'estimated' };
|
|
92
|
+
}
|
|
93
|
+
function addToTotals(usage, costUsd) {
|
|
94
|
+
totals.turns += 1;
|
|
95
|
+
totals.inputTokens = addNullable(totals.inputTokens, usage?.inputTokens ?? null);
|
|
96
|
+
totals.outputTokens = addNullable(totals.outputTokens, usage?.outputTokens ?? null);
|
|
97
|
+
totals.costUsd = addNullable(totals.costUsd, costUsd);
|
|
98
|
+
}
|
|
99
|
+
function ttftOf(open) {
|
|
100
|
+
if (open.ttftMs !== null)
|
|
101
|
+
return open.ttftMs;
|
|
102
|
+
return open.firstTokenAt === null ? null : open.firstTokenAt - open.startedAt;
|
|
103
|
+
}
|
|
104
|
+
/** Snapshots replace reported fields and retain omitted counters; they are never summed within a request. */
|
|
105
|
+
function updateUsage({ event }) {
|
|
106
|
+
const open = ensureTurn();
|
|
107
|
+
const usage = normalizeAiUsage({ usage: event.usage });
|
|
108
|
+
if (usage) {
|
|
109
|
+
const merged = { ...usage };
|
|
110
|
+
for (const key of Object.keys(merged))
|
|
111
|
+
merged[key] ??= open.usage?.[key] ?? null;
|
|
112
|
+
open.usage = merged;
|
|
113
|
+
}
|
|
114
|
+
open.reportedCost = num(event.costUsd) ?? open.reportedCost;
|
|
115
|
+
open.stopReason = str(event.stopReason) ?? open.stopReason;
|
|
116
|
+
}
|
|
117
|
+
/** Codes are bounded labels, never arbitrary error prose or a redacted credential. */
|
|
118
|
+
function safeCode({ code }) {
|
|
119
|
+
if (!code)
|
|
120
|
+
return null;
|
|
121
|
+
const captured = captureText({ text: code }, { ...captureOptions, mode: 'full', maxChars: 64 });
|
|
122
|
+
if (captured?.redactions || captured?.truncated)
|
|
123
|
+
return null;
|
|
124
|
+
return /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/.test(code) ? code : null;
|
|
125
|
+
}
|
|
126
|
+
function closeTurn() {
|
|
127
|
+
if (!turn)
|
|
128
|
+
return;
|
|
129
|
+
const open = turn;
|
|
130
|
+
const endedAt = now();
|
|
131
|
+
const usage = open.usage;
|
|
132
|
+
const { costUsd, costSource } = resolveCost({ usage, reported: open.reportedCost });
|
|
133
|
+
const errorContent = capture(open.error);
|
|
134
|
+
record({ kind: 'model_turn', traceId, turnId: open.id, toolCallCount: open.toolCallCount, index: open.index, startedAt: open.startedAt, endedAt, model, input: open.index === 0 ? capture(runInput) : null, output: captureStreamed(open.output, open.outputChars), reasoning: captureStreamed(open.reasoning, open.reasoningChars), usage, costUsd, costSource, ttftMs: ttftOf(open), stopReason: open.stopReason, error: open.error === null ? null : errorContent?.text ?? 'model_error', errorContent, errorCode: safeCode({ code: open.errorCode }) });
|
|
135
|
+
addToTotals(usage, costUsd);
|
|
136
|
+
turn = null;
|
|
137
|
+
lastBoundary = endedAt;
|
|
138
|
+
}
|
|
139
|
+
function emitTool({ tool, result }) {
|
|
140
|
+
const errorClass = result.isError ? classifyToolError({ content: result.content ?? '' }) : null;
|
|
141
|
+
totals.toolCalls += 1;
|
|
142
|
+
if (result.isError)
|
|
143
|
+
totals.toolErrors += 1;
|
|
144
|
+
record({ kind: 'tool_call', traceId, toolCallId: tool.id, turnId: tool.turnId, name: tool.name, input: capture(stringifyForCapture({ value: tool.input })), output: capture(result.content), isError: result.isError, errorClass, startedAt: tool.startedAt, endedAt: result.endedAt });
|
|
145
|
+
}
|
|
146
|
+
const handlers = {
|
|
147
|
+
status(event) {
|
|
148
|
+
if (event.label === 'requesting') {
|
|
149
|
+
requestBounded = true;
|
|
150
|
+
closeTurn();
|
|
151
|
+
// Every HTTP request already emits this status, including tool-only follow-up requests.
|
|
152
|
+
// Its turn (opened lazily by the first event) stays open through usage and delayed
|
|
153
|
+
// tool_use emission until the next boundary.
|
|
154
|
+
lastBoundary = now();
|
|
155
|
+
}
|
|
156
|
+
model = str(event.model) ?? model;
|
|
157
|
+
const ttft = num(event.ttftMs);
|
|
158
|
+
if (ttft !== null)
|
|
159
|
+
ensureTurn().ttftMs = ttft;
|
|
160
|
+
},
|
|
161
|
+
text_delta(event) {
|
|
162
|
+
const open = ensureTurn();
|
|
163
|
+
const delta = typeof event.delta === 'string' ? event.delta : '';
|
|
164
|
+
open.outputChars += delta.length;
|
|
165
|
+
if (keepText)
|
|
166
|
+
open.output += delta;
|
|
167
|
+
open.firstTokenAt ??= now();
|
|
168
|
+
},
|
|
169
|
+
thinking_delta(event) {
|
|
170
|
+
const open = ensureTurn();
|
|
171
|
+
const delta = typeof event.delta === 'string' ? event.delta : '';
|
|
172
|
+
open.reasoningChars += delta.length;
|
|
173
|
+
if (keepText)
|
|
174
|
+
open.reasoning += delta;
|
|
175
|
+
},
|
|
176
|
+
tool_use(event) {
|
|
177
|
+
const id = str(event.id);
|
|
178
|
+
if (!id)
|
|
179
|
+
return;
|
|
180
|
+
const turnId = ensureTurn().id;
|
|
181
|
+
const scopedId = `${turnId}:tool:${id}`;
|
|
182
|
+
if (seenTools.has(scopedId))
|
|
183
|
+
return;
|
|
184
|
+
seenTools.add(scopedId);
|
|
185
|
+
ensureTurn().toolCallCount += 1;
|
|
186
|
+
// HTTP adapters report usage while streaming and emit tool_use only after the stream ends,
|
|
187
|
+
// so usage leaves this request open until its delayed calls have been attributed.
|
|
188
|
+
const tools = pending.get(id) ?? [];
|
|
189
|
+
tools.push({ id: scopedId, name: str(event.name) ?? 'unknown', input: event.input, startedAt: now(), turnId });
|
|
190
|
+
pending.set(id, tools);
|
|
191
|
+
},
|
|
192
|
+
tool_result(event) {
|
|
193
|
+
const id = str(event.toolUseId) ?? 'unknown';
|
|
194
|
+
const tools = pending.get(id);
|
|
195
|
+
const tool = tools?.shift() ?? { id: `${ensureTurn().id}:tool:${id}`, name: 'unknown', input: null, startedAt: now(), turnId: ensureTurn().id };
|
|
196
|
+
if (!tools?.length)
|
|
197
|
+
pending.delete(id);
|
|
198
|
+
emitTool({ tool, result: { content: typeof event.content === 'string' ? event.content : null, isError: event.isError === true, endedAt: now() } });
|
|
199
|
+
},
|
|
200
|
+
// CLI streams (OpenCode step_finish, pi-rpc turn_end, ...) report per-step usage with no request
|
|
201
|
+
// boundary: each report still closes its own turn so totals sum steps instead of keeping the last.
|
|
202
|
+
usage(event) {
|
|
203
|
+
updateUsage({ event });
|
|
204
|
+
if (!requestBounded)
|
|
205
|
+
closeTurn();
|
|
206
|
+
},
|
|
207
|
+
// Boundaries close only existing work: opening a turn for a final stop signal would record
|
|
208
|
+
// an empty phantom model call. CLI turn_end is a control signal; usage may follow it.
|
|
209
|
+
turn_end(event) {
|
|
210
|
+
if (turn)
|
|
211
|
+
turn.stopReason = str(event.stopReason);
|
|
212
|
+
},
|
|
213
|
+
end(event) {
|
|
214
|
+
if (turn)
|
|
215
|
+
turn.stopReason ??= str(event.reason);
|
|
216
|
+
closeTurn();
|
|
217
|
+
},
|
|
218
|
+
error(event) {
|
|
219
|
+
lastError = str(event.message) ?? 'error';
|
|
220
|
+
lastErrorCode = str(event.code);
|
|
221
|
+
const open = ensureTurn();
|
|
222
|
+
open.error = lastError;
|
|
223
|
+
open.errorCode = lastErrorCode;
|
|
224
|
+
},
|
|
225
|
+
};
|
|
226
|
+
function observe(event) {
|
|
227
|
+
if (finished)
|
|
228
|
+
return;
|
|
229
|
+
handlers[String(event.type)]?.(event);
|
|
230
|
+
}
|
|
231
|
+
/** Tools still pending when the run ends are reported with `endedAt: null`, never dropped. */
|
|
232
|
+
function flushOpenWork() {
|
|
233
|
+
if (turn)
|
|
234
|
+
closeTurn();
|
|
235
|
+
for (const tools of pending.values()) {
|
|
236
|
+
for (const tool of tools)
|
|
237
|
+
emitTool({ tool, result: { content: null, isError: false, endedAt: null } });
|
|
238
|
+
}
|
|
239
|
+
pending.clear();
|
|
240
|
+
}
|
|
241
|
+
function runError({ outcome, error }) {
|
|
242
|
+
const message = error?.message ?? (outcome === 'failed' ? lastError : null);
|
|
243
|
+
if (!message)
|
|
244
|
+
return null;
|
|
245
|
+
const content = capture(message);
|
|
246
|
+
return { message: content?.text ?? 'run_error', code: safeCode({ code: error?.code ?? lastErrorCode }), content };
|
|
247
|
+
}
|
|
248
|
+
function finish({ outcome }, { error = null } = {}) {
|
|
249
|
+
if (finished)
|
|
250
|
+
return;
|
|
251
|
+
if (!started)
|
|
252
|
+
start({});
|
|
253
|
+
flushOpenWork();
|
|
254
|
+
finished = true;
|
|
255
|
+
record({ kind: 'run_finished', traceId, at: now(), outcome, error: runError({ outcome, error }), totals: { ...totals } });
|
|
256
|
+
}
|
|
257
|
+
return { traceId, start, noteInput, observe, finish };
|
|
258
|
+
}
|
|
259
|
+
//# sourceMappingURL=recorder.js.map
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module ai-trace/sinks
|
|
3
|
+
* The two backend-free sinks: `noop` (tracing off costs one no-op call per event) and
|
|
4
|
+
* `recording` (in-memory; tests, local debugging, and the swap-proof reference).
|
|
5
|
+
*/
|
|
6
|
+
import type { AiTraceEvent, AiTraceSink } from './types.js';
|
|
7
|
+
export declare const noopAiTraceSink: AiTraceSink;
|
|
8
|
+
export interface RecordingAiTraceSink extends AiTraceSink {
|
|
9
|
+
readonly events: readonly AiTraceEvent[];
|
|
10
|
+
}
|
|
11
|
+
export declare function createRecordingAiTraceSink(_required?: Record<string, never>): RecordingAiTraceSink;
|
|
12
|
+
/**
|
|
13
|
+
* Fans one trace out to several backends (e.g. Langfuse + a local recorder) without either knowing.
|
|
14
|
+
* @param required - Independent backend ports; each is attempted even when an earlier one fails.
|
|
15
|
+
* @param options - Optional failure reporter, itself guarded so logging cannot break a run.
|
|
16
|
+
* @returns A port that contains record, flush, and shutdown failures per sink.
|
|
17
|
+
* Full content is requested only by explicit sink opt-in; other destinations receive their own policy.
|
|
18
|
+
* @complexity O(s) delivery and cleanup for s sinks; cleanup runs concurrently.
|
|
19
|
+
*/
|
|
20
|
+
export declare function createFanOutAiTraceSink({ sinks }: {
|
|
21
|
+
sinks: readonly AiTraceSink[];
|
|
22
|
+
}, { onSinkError }?: {
|
|
23
|
+
onSinkError?: (error: unknown) => void;
|
|
24
|
+
}): AiTraceSink;
|
|
25
|
+
export declare const DEFAULT_LAZY_SINK_QUEUE = 1000;
|
|
26
|
+
/** Reporting is best effort too: a host logger must never turn a tracing failure into a run failure. */
|
|
27
|
+
export declare function reportError({ error, onError }: {
|
|
28
|
+
error: unknown;
|
|
29
|
+
onError: ((error: unknown) => void) | undefined;
|
|
30
|
+
}, _options?: Record<string, never>): void;
|
|
31
|
+
/**
|
|
32
|
+
* A sink usable synchronously while its backend loads asynchronously (hosts build their run
|
|
33
|
+
* lifecycle at module load; a vendor SDK is a dynamic import). Events queue until `load` settles,
|
|
34
|
+
* bounded so a backend that never loads cannot grow memory; overflow drops the oldest event and
|
|
35
|
+
* is counted in `dropped`. A rejected load degrades to noop and is reported once.
|
|
36
|
+
* @param required - Backend factory; synchronous throws and rejected initialization are contained.
|
|
37
|
+
* @param options - Queue bound, load-error reporter, and delivery/cleanup error reporter.
|
|
38
|
+
* @returns A guarded sink whose `ready` fulfills after initialization and isolated queued replay.
|
|
39
|
+
* @complexity O(q) replay and overflow eviction for a queue bounded to q events; O(1) live delivery.
|
|
40
|
+
*/
|
|
41
|
+
export declare function createLazyAiTraceSink({ load }: {
|
|
42
|
+
load: () => Promise<AiTraceSink>;
|
|
43
|
+
}, { maxQueued, onLoadError, onSinkError }?: {
|
|
44
|
+
maxQueued?: number;
|
|
45
|
+
onLoadError?: (error: unknown) => void;
|
|
46
|
+
onSinkError?: (error: unknown) => void;
|
|
47
|
+
}): AiTraceSink & {
|
|
48
|
+
readonly ready: Promise<void>;
|
|
49
|
+
readonly dropped: () => number;
|
|
50
|
+
};
|
|
51
|
+
//# sourceMappingURL=sinks.d.ts.map
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
/** Preserve each destination's content policy when another sink opts into full capture.
|
|
2
|
+
* No prompt, response, reasoning, tool text or error prose crosses a metadata-only boundary.
|
|
3
|
+
* @complexity O(1); captured text is never copied. */
|
|
4
|
+
function eventForCapture({ event, mode }) {
|
|
5
|
+
if (mode === 'full')
|
|
6
|
+
return event;
|
|
7
|
+
const text = (value) => mode === 'off' || !value ? null : { chars: value.chars };
|
|
8
|
+
switch (event.kind) {
|
|
9
|
+
case 'run_started': return { ...event, input: text(event.input) };
|
|
10
|
+
case 'model_turn': return { ...event, input: text(event.input), output: text(event.output), reasoning: text(event.reasoning), errorContent: text(event.errorContent), error: event.error === null ? null : 'model_error' };
|
|
11
|
+
case 'tool_call': return { ...event, input: text(event.input), output: text(event.output) };
|
|
12
|
+
case 'run_finished': return { ...event, error: event.error === null ? null : { ...event.error, message: 'run_error', content: text(event.error.content) } };
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
export const noopAiTraceSink = { record: () => { } };
|
|
16
|
+
export function createRecordingAiTraceSink(_required = {}) {
|
|
17
|
+
const events = [];
|
|
18
|
+
return { events, record: (event) => void events.push(event) };
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Fans one trace out to several backends (e.g. Langfuse + a local recorder) without either knowing.
|
|
22
|
+
* @param required - Independent backend ports; each is attempted even when an earlier one fails.
|
|
23
|
+
* @param options - Optional failure reporter, itself guarded so logging cannot break a run.
|
|
24
|
+
* @returns A port that contains record, flush, and shutdown failures per sink.
|
|
25
|
+
* Full content is requested only by explicit sink opt-in; other destinations receive their own policy.
|
|
26
|
+
* @complexity O(s) delivery and cleanup for s sinks; cleanup runs concurrently.
|
|
27
|
+
*/
|
|
28
|
+
export function createFanOutAiTraceSink({ sinks }, { onSinkError } = {}) {
|
|
29
|
+
return {
|
|
30
|
+
capture: sinks.some((sink) => sink.capture === 'full') ? 'full' : 'metadata',
|
|
31
|
+
record: (event) => {
|
|
32
|
+
for (const sink of sinks) {
|
|
33
|
+
try {
|
|
34
|
+
sink.record(eventForCapture({ event, mode: sink.capture ?? 'metadata' }));
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
reportError({ error, onError: onSinkError });
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
flush: async () => {
|
|
42
|
+
await Promise.all(sinks.map(async (sink) => {
|
|
43
|
+
try {
|
|
44
|
+
await sink.flush?.();
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
reportError({ error, onError: onSinkError });
|
|
48
|
+
}
|
|
49
|
+
}));
|
|
50
|
+
},
|
|
51
|
+
shutdown: async () => {
|
|
52
|
+
await Promise.all(sinks.map(async (sink) => {
|
|
53
|
+
try {
|
|
54
|
+
await sink.shutdown?.();
|
|
55
|
+
}
|
|
56
|
+
catch (error) {
|
|
57
|
+
reportError({ error, onError: onSinkError });
|
|
58
|
+
}
|
|
59
|
+
}));
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
export const DEFAULT_LAZY_SINK_QUEUE = 1_000;
|
|
64
|
+
/** Reporting is best effort too: a host logger must never turn a tracing failure into a run failure. */
|
|
65
|
+
export function reportError({ error, onError }, _options = {}) {
|
|
66
|
+
try {
|
|
67
|
+
onError?.(error);
|
|
68
|
+
}
|
|
69
|
+
catch { /* Tracing error reporting has no effect on application work. */ }
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* A sink usable synchronously while its backend loads asynchronously (hosts build their run
|
|
73
|
+
* lifecycle at module load; a vendor SDK is a dynamic import). Events queue until `load` settles,
|
|
74
|
+
* bounded so a backend that never loads cannot grow memory; overflow drops the oldest event and
|
|
75
|
+
* is counted in `dropped`. A rejected load degrades to noop and is reported once.
|
|
76
|
+
* @param required - Backend factory; synchronous throws and rejected initialization are contained.
|
|
77
|
+
* @param options - Queue bound, load-error reporter, and delivery/cleanup error reporter.
|
|
78
|
+
* @returns A guarded sink whose `ready` fulfills after initialization and isolated queued replay.
|
|
79
|
+
* @complexity O(q) replay and overflow eviction for a queue bounded to q events; O(1) live delivery.
|
|
80
|
+
*/
|
|
81
|
+
export function createLazyAiTraceSink({ load }, { maxQueued = DEFAULT_LAZY_SINK_QUEUE, onLoadError, onSinkError } = {}) {
|
|
82
|
+
let target = null;
|
|
83
|
+
let queue = [];
|
|
84
|
+
let dropped = 0;
|
|
85
|
+
function deliver(event) {
|
|
86
|
+
try {
|
|
87
|
+
target?.record(event);
|
|
88
|
+
}
|
|
89
|
+
catch (error) {
|
|
90
|
+
reportError({ error, onError: onSinkError });
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
// Invoke load synchronously for existing hosts, but contain a synchronous throw as well as rejection.
|
|
94
|
+
const loading = new Promise((resolve) => resolve(load()));
|
|
95
|
+
const ready = loading.then((sink) => {
|
|
96
|
+
target = sink;
|
|
97
|
+
for (const event of queue)
|
|
98
|
+
deliver(event);
|
|
99
|
+
}, (error) => {
|
|
100
|
+
target = noopAiTraceSink;
|
|
101
|
+
reportError({ error, onError: onLoadError });
|
|
102
|
+
}).finally(() => {
|
|
103
|
+
queue = [];
|
|
104
|
+
});
|
|
105
|
+
return {
|
|
106
|
+
ready,
|
|
107
|
+
dropped: () => dropped,
|
|
108
|
+
record(event) {
|
|
109
|
+
if (target)
|
|
110
|
+
return deliver(event);
|
|
111
|
+
if (queue.length >= maxQueued) {
|
|
112
|
+
queue.shift();
|
|
113
|
+
dropped += 1;
|
|
114
|
+
}
|
|
115
|
+
queue.push(event);
|
|
116
|
+
},
|
|
117
|
+
flush: async () => {
|
|
118
|
+
await ready;
|
|
119
|
+
try {
|
|
120
|
+
await target?.flush?.();
|
|
121
|
+
}
|
|
122
|
+
catch (error) {
|
|
123
|
+
reportError({ error, onError: onSinkError });
|
|
124
|
+
}
|
|
125
|
+
},
|
|
126
|
+
shutdown: async () => {
|
|
127
|
+
await ready;
|
|
128
|
+
try {
|
|
129
|
+
await target?.shutdown?.();
|
|
130
|
+
}
|
|
131
|
+
catch (error) {
|
|
132
|
+
reportError({ error, onError: onSinkError });
|
|
133
|
+
}
|
|
134
|
+
},
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
//# sourceMappingURL=sinks.js.map
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module ai-trace/types
|
|
3
|
+
*
|
|
4
|
+
* Vendor-neutral AI-run trace contract: run → model turns → tool calls → outcome.
|
|
5
|
+
*
|
|
6
|
+
* Why a sibling port and not more `RunLifecycleEvent` variants: `TelemetrySink` is the
|
|
7
|
+
* product-analytics port and its `data` is deliberately opaque so the engine never installs a
|
|
8
|
+
* product's event schema. A trace is the opposite — a typed, hierarchical span tree that every
|
|
9
|
+
* backend (Langfuse, Phoenix, Helicone, OTel GenAI) maps field-for-field. Widening the analytics
|
|
10
|
+
* union would force every existing analytics sink to understand spans; a sibling port keeps both
|
|
11
|
+
* contracts small and lets a host install either, both, or neither.
|
|
12
|
+
*
|
|
13
|
+
* Honesty rule: a field a provider stream cannot supply is `null`, never estimated in place.
|
|
14
|
+
* Cost a host prices itself is marked `costSource: 'estimated'`.
|
|
15
|
+
*/
|
|
16
|
+
/** How much prompt/response/tool text leaves the process. `off`: none; `metadata`: char counts only; `full`: redacted text. */
|
|
17
|
+
export type AiContentCapture = 'off' | 'metadata' | 'full';
|
|
18
|
+
/** Why a tool call failed — the split that tells "the model called it wrong" apart from "the tool broke". */
|
|
19
|
+
export type AiToolErrorClass = 'input_validation' | 'execution' | 'denied' | 'timeout';
|
|
20
|
+
export type AiRunOutcome = 'succeeded' | 'failed' | 'cancelled';
|
|
21
|
+
/** Captured text after the capture mode and redaction ran. `text` is present only in `full` mode. */
|
|
22
|
+
export interface AiCapturedText {
|
|
23
|
+
readonly chars: number;
|
|
24
|
+
readonly text?: string;
|
|
25
|
+
readonly truncated?: boolean;
|
|
26
|
+
/** Per-category redaction counts (`{ email: 1 }`), so a reviewer sees what was stripped. */
|
|
27
|
+
readonly redactions?: Readonly<Record<string, number>>;
|
|
28
|
+
}
|
|
29
|
+
/** Token counters; `null` means the provider did not report that counter, not zero. */
|
|
30
|
+
export interface AiTokenUsage {
|
|
31
|
+
readonly inputTokens: number | null;
|
|
32
|
+
readonly outputTokens: number | null;
|
|
33
|
+
readonly cacheReadTokens: number | null;
|
|
34
|
+
readonly cacheWriteTokens: number | null;
|
|
35
|
+
readonly reasoningTokens: number | null;
|
|
36
|
+
}
|
|
37
|
+
export type AiCostSource = 'provider' | 'estimated';
|
|
38
|
+
export interface AiTraceRunStarted {
|
|
39
|
+
readonly kind: 'run_started';
|
|
40
|
+
readonly traceId: string;
|
|
41
|
+
readonly runId: string;
|
|
42
|
+
readonly at: number;
|
|
43
|
+
readonly agentId: string;
|
|
44
|
+
readonly provider: string | null;
|
|
45
|
+
readonly model: string | null;
|
|
46
|
+
/** Host conversation/chat id, so a backend can group runs into sessions. */
|
|
47
|
+
readonly sessionId: string | null;
|
|
48
|
+
readonly input: AiCapturedText | null;
|
|
49
|
+
readonly tags: readonly string[];
|
|
50
|
+
}
|
|
51
|
+
/** One explicit provider request, or a run-level window when the stream supplies no request boundaries. */
|
|
52
|
+
export interface AiTraceModelTurn {
|
|
53
|
+
readonly kind: 'model_turn';
|
|
54
|
+
readonly traceId: string;
|
|
55
|
+
readonly turnId: string;
|
|
56
|
+
readonly index: number;
|
|
57
|
+
readonly startedAt: number;
|
|
58
|
+
readonly endedAt: number;
|
|
59
|
+
readonly model: string | null;
|
|
60
|
+
readonly input: AiCapturedText | null;
|
|
61
|
+
readonly output: AiCapturedText | null;
|
|
62
|
+
readonly reasoning: AiCapturedText | null;
|
|
63
|
+
readonly usage: AiTokenUsage | null;
|
|
64
|
+
readonly costUsd: number | null;
|
|
65
|
+
readonly costSource: AiCostSource | null;
|
|
66
|
+
readonly ttftMs: number | null;
|
|
67
|
+
readonly stopReason: string | null;
|
|
68
|
+
readonly error: string | null;
|
|
69
|
+
/** Error text follows the same capture policy as prompts; `error` is a safe label outside full mode. */
|
|
70
|
+
readonly errorContent?: AiCapturedText | null;
|
|
71
|
+
readonly errorCode?: string | null;
|
|
72
|
+
/** Calls requested by this generation, including tools still pending when the turn closes. */
|
|
73
|
+
readonly toolCallCount?: number;
|
|
74
|
+
}
|
|
75
|
+
export interface AiTraceToolCall {
|
|
76
|
+
readonly kind: 'tool_call';
|
|
77
|
+
readonly traceId: string;
|
|
78
|
+
/** Request-scoped trace identity; provider ids may repeat on the next request. */
|
|
79
|
+
readonly toolCallId: string;
|
|
80
|
+
/** The model turn that requested the call. */
|
|
81
|
+
readonly turnId: string;
|
|
82
|
+
readonly name: string;
|
|
83
|
+
readonly input: AiCapturedText | null;
|
|
84
|
+
readonly output: AiCapturedText | null;
|
|
85
|
+
readonly isError: boolean;
|
|
86
|
+
readonly errorClass: AiToolErrorClass | null;
|
|
87
|
+
readonly startedAt: number;
|
|
88
|
+
/** `null` when the run ended before the tool reported a result. */
|
|
89
|
+
readonly endedAt: number | null;
|
|
90
|
+
}
|
|
91
|
+
export interface AiTraceTotals {
|
|
92
|
+
readonly turns: number;
|
|
93
|
+
readonly toolCalls: number;
|
|
94
|
+
readonly toolErrors: number;
|
|
95
|
+
readonly inputTokens: number | null;
|
|
96
|
+
readonly outputTokens: number | null;
|
|
97
|
+
readonly costUsd: number | null;
|
|
98
|
+
}
|
|
99
|
+
export interface AiTraceRunFinished {
|
|
100
|
+
readonly kind: 'run_finished';
|
|
101
|
+
readonly traceId: string;
|
|
102
|
+
readonly at: number;
|
|
103
|
+
readonly outcome: AiRunOutcome;
|
|
104
|
+
readonly error: {
|
|
105
|
+
readonly message: string;
|
|
106
|
+
readonly code: string | null;
|
|
107
|
+
readonly content?: AiCapturedText | null;
|
|
108
|
+
} | null;
|
|
109
|
+
readonly totals: AiTraceTotals;
|
|
110
|
+
}
|
|
111
|
+
export type AiTraceEvent = AiTraceRunStarted | AiTraceModelTurn | AiTraceToolCall | AiTraceRunFinished;
|
|
112
|
+
/**
|
|
113
|
+
* Backend port. `record` must not throw into the run (the recorder guards it anyway) and must not
|
|
114
|
+
* block: adapters buffer and send in `flush`. Hosts call `shutdown` once on process exit.
|
|
115
|
+
*/
|
|
116
|
+
export interface AiTraceSink {
|
|
117
|
+
/** Requested content policy. Absent means metadata; fan-out preserves each sink's policy. */
|
|
118
|
+
readonly capture?: AiContentCapture;
|
|
119
|
+
record(event: AiTraceEvent): void;
|
|
120
|
+
flush?(): Promise<void>;
|
|
121
|
+
shutdown?(): Promise<void>;
|
|
122
|
+
}
|
|
123
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module ai-trace/types
|
|
3
|
+
*
|
|
4
|
+
* Vendor-neutral AI-run trace contract: run → model turns → tool calls → outcome.
|
|
5
|
+
*
|
|
6
|
+
* Why a sibling port and not more `RunLifecycleEvent` variants: `TelemetrySink` is the
|
|
7
|
+
* product-analytics port and its `data` is deliberately opaque so the engine never installs a
|
|
8
|
+
* product's event schema. A trace is the opposite — a typed, hierarchical span tree that every
|
|
9
|
+
* backend (Langfuse, Phoenix, Helicone, OTel GenAI) maps field-for-field. Widening the analytics
|
|
10
|
+
* union would force every existing analytics sink to understand spans; a sibling port keeps both
|
|
11
|
+
* contracts small and lets a host install either, both, or neither.
|
|
12
|
+
*
|
|
13
|
+
* Honesty rule: a field a provider stream cannot supply is `null`, never estimated in place.
|
|
14
|
+
* Cost a host prices itself is marked `costSource: 'estimated'`.
|
|
15
|
+
*/
|
|
16
|
+
export {};
|
|
17
|
+
//# sourceMappingURL=types.js.map
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module ai-trace/usage
|
|
3
|
+
* Folds every provider's usage spelling into {@link AiTokenUsage}. Each counter takes the first
|
|
4
|
+
* alias the provider actually reported; a counter no alias matched stays `null` (never `0`).
|
|
5
|
+
*/
|
|
6
|
+
import type { AiTokenUsage } from './types.js';
|
|
7
|
+
/** Returns `null` when the input is not a usage object or carries no recognised counter. */
|
|
8
|
+
export declare function normalizeAiUsage({ usage }: {
|
|
9
|
+
usage: unknown;
|
|
10
|
+
}, _options?: Record<string, never>): AiTokenUsage | null;
|
|
11
|
+
/** Adds two nullable counters; `null + null` stays `null` so "never reported" survives totals. */
|
|
12
|
+
export declare function addNullable(a: number | null, b: number | null): number | null;
|
|
13
|
+
//# sourceMappingURL=usage.d.ts.map
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// Dotted paths reach OpenAI's nested `*_details` objects. Order matters only when a provider
|
|
2
|
+
// reports two spellings of the same counter, which none of the normalizers do today.
|
|
3
|
+
const USAGE_ALIASES = {
|
|
4
|
+
inputTokens: ['input_tokens', 'inputTokens', 'prompt_tokens', 'promptTokenCount'],
|
|
5
|
+
outputTokens: ['output_tokens', 'outputTokens', 'completion_tokens', 'candidatesTokenCount'],
|
|
6
|
+
cacheReadTokens: ['cache_read_input_tokens', 'cached_read_tokens', 'cachedReadTokens', 'cacheReadTokens', 'prompt_tokens_details.cached_tokens', 'cachedContentTokenCount'],
|
|
7
|
+
cacheWriteTokens: ['cache_creation_input_tokens', 'cached_write_tokens', 'cacheWriteTokens'],
|
|
8
|
+
reasoningTokens: ['thought_tokens', 'thoughtTokens', 'reasoningTokens', 'completion_tokens_details.reasoning_tokens', 'thoughtsTokenCount', 'reasoning_tokens'],
|
|
9
|
+
};
|
|
10
|
+
function isRecord(value) {
|
|
11
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
12
|
+
}
|
|
13
|
+
function readPath(source, path) {
|
|
14
|
+
let current = source;
|
|
15
|
+
for (const part of path.split('.'))
|
|
16
|
+
current = isRecord(current) ? current[part] : undefined;
|
|
17
|
+
return current;
|
|
18
|
+
}
|
|
19
|
+
function firstNumber(source, aliases) {
|
|
20
|
+
for (const alias of aliases) {
|
|
21
|
+
const value = readPath(source, alias);
|
|
22
|
+
if (typeof value === 'number' && Number.isFinite(value))
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
/** Returns `null` when the input is not a usage object or carries no recognised counter. */
|
|
28
|
+
export function normalizeAiUsage({ usage }, _options = {}) {
|
|
29
|
+
if (!isRecord(usage))
|
|
30
|
+
return null;
|
|
31
|
+
const out = {};
|
|
32
|
+
let found = false;
|
|
33
|
+
for (const key of Object.keys(USAGE_ALIASES)) {
|
|
34
|
+
out[key] = firstNumber(usage, USAGE_ALIASES[key]);
|
|
35
|
+
found ||= out[key] !== null;
|
|
36
|
+
}
|
|
37
|
+
return found ? out : null;
|
|
38
|
+
}
|
|
39
|
+
/** Adds two nullable counters; `null + null` stays `null` so "never reported" survives totals. */
|
|
40
|
+
export function addNullable(a, b) {
|
|
41
|
+
return a === null && b === null ? null : (a ?? 0) + (b ?? 0);
|
|
42
|
+
}
|
|
43
|
+
//# sourceMappingURL=usage.js.map
|