@tangle-network/agent-app 0.60.231 → 0.60.233
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/dist/assistant/index.js +8 -8
- package/dist/chat-react/index.js +4 -4
- package/dist/chat-routes/index.js +6 -8
- package/dist/chat-routes/index.js.map +1 -1
- package/dist/{chunk-5IS3GCMR.js → chunk-232KA6MR.js} +3 -3
- package/dist/{chunk-KMIDRUUH.js → chunk-35APKGPB.js} +2 -2
- package/dist/{chunk-GNBBY3KN.js → chunk-3K45OQ5X.js} +3 -3
- package/dist/{chunk-A3CUVYRZ.js → chunk-4JAXSEYW.js} +3 -3
- package/dist/{chunk-BKVDPMFD.js → chunk-BBYUWYEL.js} +2 -2
- package/dist/{chunk-DA5XLDZR.js → chunk-BNFUJNPS.js} +4 -4
- package/dist/{chunk-7QZNHBQT.js → chunk-DUGIVKNA.js} +215 -2
- package/dist/chunk-DUGIVKNA.js.map +1 -0
- package/dist/{chunk-J63KUZBE.js → chunk-F5FFOIS5.js} +6 -3
- package/dist/chunk-F5FFOIS5.js.map +1 -0
- package/dist/{chunk-BQILMP73.js → chunk-FJEGGUOQ.js} +2 -2
- package/dist/{chunk-TEIKC276.js → chunk-GMC5DO2O.js} +3 -3
- package/dist/{chunk-HEPEGY6Q.js → chunk-JYVUFRRV.js} +2 -2
- package/dist/{chunk-JILHXHJE.js → chunk-K7SKQ7GY.js} +2 -2
- package/dist/{chunk-RMPPWNW7.js → chunk-MX3RI3MO.js} +6 -10
- package/dist/{chunk-RMPPWNW7.js.map → chunk-MX3RI3MO.js.map} +1 -1
- package/dist/{chunk-XG6FODYO.js → chunk-XIN7DOAB.js} +108 -100
- package/dist/chunk-XIN7DOAB.js.map +1 -0
- package/dist/{mention-editor-NOS5R3AU.js → mention-editor-6FJ6HRSN.js} +2 -2
- package/dist/public-consultation/index.d.ts +1 -1
- package/dist/public-consultation/index.js +2 -4
- package/dist/public-consultation/index.js.map +1 -1
- package/dist/runtime/index.js +4 -5
- package/dist/runtime/index.js.map +1 -1
- package/dist/runtime/router-turn.js +3 -4
- package/dist/sandbox/index.js +3 -3
- package/dist/settings-react/index.js +1 -1
- package/dist/studio-react/index.js +2 -2
- package/dist/turn-trace/index.js +8 -12
- package/dist/web-react/agent-profile-editor.js +4 -4
- package/dist/web-react/control-glyphs.d.ts +20 -0
- package/dist/web-react/controls.d.ts +6 -358
- package/dist/web-react/effort-picker.d.ts +98 -0
- package/dist/web-react/index.js +8 -8
- package/dist/web-react/model-picker.d.ts +67 -0
- package/dist/web-react/picker-presentation.d.ts +89 -0
- package/dist/web-react/popover-surface.d.ts +89 -0
- package/dist/web-react/use-pending.d.ts +11 -0
- package/dist/workspace-react/index.js +3 -3
- package/package.json +1 -1
- package/dist/chunk-7QZNHBQT.js.map +0 -1
- package/dist/chunk-J63KUZBE.js.map +0 -1
- package/dist/chunk-LHGYK5I3.js +0 -160
- package/dist/chunk-LHGYK5I3.js.map +0 -1
- package/dist/chunk-PIUYJTTK.js +0 -63
- package/dist/chunk-PIUYJTTK.js.map +0 -1
- package/dist/chunk-XG6FODYO.js.map +0 -1
- /package/dist/{chunk-5IS3GCMR.js.map → chunk-232KA6MR.js.map} +0 -0
- /package/dist/{chunk-KMIDRUUH.js.map → chunk-35APKGPB.js.map} +0 -0
- /package/dist/{chunk-GNBBY3KN.js.map → chunk-3K45OQ5X.js.map} +0 -0
- /package/dist/{chunk-A3CUVYRZ.js.map → chunk-4JAXSEYW.js.map} +0 -0
- /package/dist/{chunk-BKVDPMFD.js.map → chunk-BBYUWYEL.js.map} +0 -0
- /package/dist/{chunk-DA5XLDZR.js.map → chunk-BNFUJNPS.js.map} +0 -0
- /package/dist/{chunk-BQILMP73.js.map → chunk-FJEGGUOQ.js.map} +0 -0
- /package/dist/{chunk-TEIKC276.js.map → chunk-GMC5DO2O.js.map} +0 -0
- /package/dist/{chunk-HEPEGY6Q.js.map → chunk-JYVUFRRV.js.map} +0 -0
- /package/dist/{chunk-JILHXHJE.js.map → chunk-K7SKQ7GY.js.map} +0 -0
- /package/dist/{mention-editor-NOS5R3AU.js.map → mention-editor-6FJ6HRSN.js.map} +0 -0
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Focus treatment for a row inside a popover panel.
|
|
3
|
+
*
|
|
4
|
+
* The ring itself now comes from the `:focus-visible` floor in tokens.css, so
|
|
5
|
+
* this no longer restates a width or a colour. What it still has to say is
|
|
6
|
+
* WHERE the ring is drawn: a popover option is a full-width row inside a panel
|
|
7
|
+
* that clips its own corners (`overflow-hidden rounded-xl`), and an outward
|
|
8
|
+
* ring on the first or last row is clipped away by that panel. Pulling the
|
|
9
|
+
* offset negative draws the same ring just inside the row instead.
|
|
10
|
+
*/
|
|
11
|
+
export declare const POPOVER_OPTION_FOCUS = "focus-visible:[outline-offset:-2px]";
|
|
12
|
+
/**
|
|
13
|
+
* The one overlay elevation for floating surfaces — picker menus, popovers,
|
|
14
|
+
* drawers, modals. Reads the theme's `--shadow-overlay` token, so every overlay
|
|
15
|
+
* lifts with the same shadow and re-themes from one source. The floating
|
|
16
|
+
* composer uses the quieter `shadow-raised` rung instead.
|
|
17
|
+
*
|
|
18
|
+
* Written as an arbitrary value rather than the preset's `shadow-overlay`
|
|
19
|
+
* utility, because that utility only exists where the preset is part of the
|
|
20
|
+
* Tailwind build. A host that gets its tokens through a precompiled bundle —
|
|
21
|
+
* `@tangle-network/sandbox-ui` ships brand's tokens inlined, with no `@theme`
|
|
22
|
+
* block surviving the compile — receives `--shadow-overlay` as a plain custom
|
|
23
|
+
* property, from which no `shadow-overlay` utility can be generated, and these
|
|
24
|
+
* surfaces render flat. The arbitrary form emits from the class alone and works
|
|
25
|
+
* either way.
|
|
26
|
+
*/
|
|
27
|
+
export declare const OVERLAY_SHADOW = "shadow-[var(--shadow-overlay)]";
|
|
28
|
+
/**
|
|
29
|
+
* Root geometry for a picker — the box that holds the trigger — in one place
|
|
30
|
+
* because every picker in this family has to agree on it.
|
|
31
|
+
*
|
|
32
|
+
* Shrink-wrapping (`inline-flex`) is the default: these controls dock on a
|
|
33
|
+
* composer row where an expanding pill shoves its neighbours around. A STACKED
|
|
34
|
+
* panel wants the opposite — the compact `AgentSessionControls` gear popover
|
|
35
|
+
* lays its controls out in a column, and a shrink-wrapped root there makes a
|
|
36
|
+
* trigger's own `w-full` a no-op, since it fills a box the trigger itself
|
|
37
|
+
* sized. That is what left Agent backend short of the panel edge and Thinking
|
|
38
|
+
* narrower still.
|
|
39
|
+
*
|
|
40
|
+
* The panel is portaled ({@link PopoverSurface}), so widening the root widens
|
|
41
|
+
* the TRIGGER only. A menu that should follow it declares `matchTriggerWidth`.
|
|
42
|
+
*/
|
|
43
|
+
export declare function pickerRootClass(fullWidth: boolean): string;
|
|
44
|
+
/**
|
|
45
|
+
* How a picker's TRIGGER is drawn. The menu it opens is the same either way.
|
|
46
|
+
*
|
|
47
|
+
* - `chip` (default): the 32px bordered pill — `rounded-full border
|
|
48
|
+
* border-border bg-card font-medium`, on the composer row's height.
|
|
49
|
+
* - `quiet`: a 32px borderless text button (the control scale's sm, the
|
|
50
|
+
* composer row's one height) — muted label, small glyph, a
|
|
51
|
+
* surface fill on hover and while the menu is open, nothing else. For a
|
|
52
|
+
* composer whose card already draws the border: three pills docked under
|
|
53
|
+
* the input there read as three more cards, not as the input's controls.
|
|
54
|
+
* - `field`: a full-width form field — the same height, radius, border,
|
|
55
|
+
* well, and focus treatment as a text input at `--control-height`. For a
|
|
56
|
+
* settings form, where a pill among inputs reads as a different control.
|
|
57
|
+
*/
|
|
58
|
+
export type PickerVariant = 'chip' | 'quiet' | 'field';
|
|
59
|
+
/**
|
|
60
|
+
* Trigger classes for a `field` picker: `@tangle-network/ui`'s own field
|
|
61
|
+
* presentation and `md` field size, the classes its `Input` and `SelectTrigger`
|
|
62
|
+
* draw, so a model, harness or timezone selector sits in a form as one more
|
|
63
|
+
* field — the same well on every plane, the same border, hover and focus halo.
|
|
64
|
+
*/
|
|
65
|
+
export declare function fieldPickerTriggerClass({ interactive }?: {
|
|
66
|
+
interactive?: boolean;
|
|
67
|
+
}): string;
|
|
68
|
+
/** The chip trigger: a fixed 32px height (no vertical padding, so the 20px
|
|
69
|
+
* line and the border cannot push it to 34px). A full-width EffortPicker in a
|
|
70
|
+
* settings panel keeps the 36px field row instead. */
|
|
71
|
+
export declare const CHIP_PICKER_TRIGGER = "inline-flex h-[var(--control-height-sm,2rem)] items-center gap-1.5 whitespace-nowrap rounded-full border border-border bg-card px-3 text-sm font-medium text-foreground transition";
|
|
72
|
+
/**
|
|
73
|
+
* Trigger classes for a `quiet` picker. Height, padding, radius, and type are
|
|
74
|
+
* fixed here so the triggers on one composer row agree; a caller adds only
|
|
75
|
+
* width (`w-full`) and alignment (`justify-between`).
|
|
76
|
+
*
|
|
77
|
+
* The focus ring is drawn on the element rather than left to the tokens.css
|
|
78
|
+
* `:focus-visible` floor: a quiet trigger sits beside the composer's own action
|
|
79
|
+
* buttons (attach, dictate, send), which draw `focus-visible:ring-2
|
|
80
|
+
* focus-visible:ring-ring`, and a row whose controls answer keyboard focus two
|
|
81
|
+
* different ways reads as two families.
|
|
82
|
+
*
|
|
83
|
+
* `interactive: false` is for a PINNED control (see `HarnessPicker`'s
|
|
84
|
+
* `lockReason`): it keeps the resting treatment and draws no hover or open
|
|
85
|
+
* fill, because a fill promises a menu the control will not open.
|
|
86
|
+
*/
|
|
87
|
+
export declare function quietPickerTriggerClass({ interactive }?: {
|
|
88
|
+
interactive?: boolean;
|
|
89
|
+
}): string;
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/** Portaled popover placement, nested focus, and outside-click ownership. */
|
|
2
|
+
import { useLayoutEffect, type ReactNode, type RefObject } from 'react';
|
|
3
|
+
/**
|
|
4
|
+
* Keyboard + pointer model for a trigger-and-popover pair, dependency-free.
|
|
5
|
+
* Outside-mousedown and Escape both close; Escape also returns focus to the
|
|
6
|
+
* trigger so keyboard users aren't dropped at the top of the document. The
|
|
7
|
+
* returned `triggerProps` carry the ARIA contract (`aria-haspopup`/
|
|
8
|
+
* `aria-expanded`); spread them onto the trigger button.
|
|
9
|
+
*
|
|
10
|
+
* `panelRef` belongs to the popover panel and MUST be wired when the panel is
|
|
11
|
+
* rendered through {@link PopoverSurface}: a portaled panel is not inside
|
|
12
|
+
* `containerRef`, so a container-only outside test reads every click on the
|
|
13
|
+
* menu's own rows as an outside click and closes before the row's handler runs.
|
|
14
|
+
*/
|
|
15
|
+
export declare function usePopover(open: boolean, setOpen: (open: boolean) => void): {
|
|
16
|
+
containerRef: RefObject<HTMLDivElement | null>;
|
|
17
|
+
triggerRef: RefObject<HTMLButtonElement | null>;
|
|
18
|
+
panelRef: RefObject<HTMLDivElement | null>;
|
|
19
|
+
triggerProps: {
|
|
20
|
+
ref: RefObject<HTMLButtonElement | null>;
|
|
21
|
+
'aria-haspopup': true;
|
|
22
|
+
'aria-expanded': boolean;
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Marks the portaled panel in the DOM. Products and audits (see
|
|
27
|
+
* `playground/scripts/popover-hit-test.mjs`) select on this rather than on a
|
|
28
|
+
* Tailwind class, which is presentation and free to change.
|
|
29
|
+
*
|
|
30
|
+
* Its VALUE is the surface's ancestor path (`outer/inner`), which is what
|
|
31
|
+
* restores "is this click inside my popover" after the portal flattens two
|
|
32
|
+
* nested panels into two siblings of `<body>`.
|
|
33
|
+
*/
|
|
34
|
+
export declare const POPOVER_SURFACE_ATTR = "data-agent-app-popover";
|
|
35
|
+
/**
|
|
36
|
+
* `PopoverSurface` is now mounted (closed) inside every server-rendered
|
|
37
|
+
* composer, so its hooks run on the server once per composer per request.
|
|
38
|
+
* React 18 logs "useLayoutEffect does nothing on the server" for that; React 19
|
|
39
|
+
* does not (measured silent on react-dom 19.2.8). The peer floor is `react >=18`,
|
|
40
|
+
* so bind the synchronous hook only where there is a DOM and the effect hook
|
|
41
|
+
* elsewhere — placement never runs on the server either way.
|
|
42
|
+
*/
|
|
43
|
+
export declare const useBrowserLayoutEffect: typeof useLayoutEffect;
|
|
44
|
+
export interface PopoverSurfaceProps {
|
|
45
|
+
open: boolean;
|
|
46
|
+
/** The trigger the panel anchors to — `usePopover`'s `triggerRef`. */
|
|
47
|
+
triggerRef: RefObject<HTMLElement | null>;
|
|
48
|
+
/** `usePopover`'s `panelRef`; also what the outside-click test consults. */
|
|
49
|
+
panelRef: RefObject<HTMLDivElement | null>;
|
|
50
|
+
/** Presentation classes. Placement and elevation are owned here — a caller
|
|
51
|
+
* must not pass `absolute`/`fixed`/`top-*`/`bottom-*`/`z-*`. */
|
|
52
|
+
className?: string;
|
|
53
|
+
role?: string;
|
|
54
|
+
id?: string;
|
|
55
|
+
'aria-label'?: string;
|
|
56
|
+
/** Make the panel at least as wide as its trigger. A portaled panel has no
|
|
57
|
+
* `w-full` to inherit — the trigger is no longer its offset parent — so a
|
|
58
|
+
* menu that used to stretch to a full-width trigger declares it here. */
|
|
59
|
+
matchTriggerWidth?: boolean;
|
|
60
|
+
/** Preferred side. `above` suits controls docked at the bottom of a composer;
|
|
61
|
+
* `below` suits headers, rows, and rails. Either flips when the other side has more room. */
|
|
62
|
+
side?: 'above' | 'below';
|
|
63
|
+
/** Which trigger edge the panel lines up with. `end` keeps a row's trailing menu over the row. */
|
|
64
|
+
align?: 'start' | 'end';
|
|
65
|
+
/** Opt in to remeasurement when asynchronous or filtered content changes. */
|
|
66
|
+
contentKey?: unknown;
|
|
67
|
+
children: ReactNode;
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* The floating panel every canonical picker opens.
|
|
71
|
+
*
|
|
72
|
+
* It renders through a PORTAL to `document.body` and anchors itself to the
|
|
73
|
+
* trigger in viewport coordinates, because an in-place `absolute` panel's
|
|
74
|
+
* visibility is decided by markup this package does not own. Measured in
|
|
75
|
+
* production: the shipped chat composer docks these controls inside a
|
|
76
|
+
* horizontally scrolling rail (`overflow-x-auto`), and a scroll container
|
|
77
|
+
* clips every positioned descendant whose containing block sits inside it —
|
|
78
|
+
* so a correct 420x457 menu with correct coordinates painted zero pixels and
|
|
79
|
+
* could not be clicked. An ancestor `transform`/`filter`/`contain` would trap
|
|
80
|
+
* it the same way through the stacking context instead of the clip. Leaving
|
|
81
|
+
* the DOM subtree is the only placement a host cannot re-break.
|
|
82
|
+
*
|
|
83
|
+
* Placement prefers ABOVE the trigger (these controls dock at the bottom of a
|
|
84
|
+
* composer), flips below when there is more room there, clamps horizontally
|
|
85
|
+
* into the viewport, and caps its own height to the space on the chosen side.
|
|
86
|
+
* The panel is `visibility: hidden` for the measure pass so it never paints at
|
|
87
|
+
* the pre-placement origin.
|
|
88
|
+
*/
|
|
89
|
+
export declare function PopoverSurface({ open, triggerRef, panelRef, className, role, id, 'aria-label': ariaLabel, matchTriggerWidth, side, align, contentKey, children, }: PopoverSurfaceProps): import("react").ReactPortal | null;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Guard an async action against double-submit. `run` ignores re-entrant calls
|
|
3
|
+
* while a promise is in flight and flips `pending` so the caller can disable
|
|
4
|
+
* the control — the fix for double-charge / double-approve on a slow network.
|
|
5
|
+
* Settles (success or throw) before clearing, and no-ops state updates after
|
|
6
|
+
* unmount.
|
|
7
|
+
*/
|
|
8
|
+
export declare function usePending(): {
|
|
9
|
+
pending: boolean;
|
|
10
|
+
run: (action: () => void | Promise<void>) => void;
|
|
11
|
+
};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
WorkspaceInitial,
|
|
3
3
|
WorkspaceSwitcher
|
|
4
|
-
} from "../chunk-
|
|
4
|
+
} from "../chunk-3K45OQ5X.js";
|
|
5
5
|
import {
|
|
6
6
|
ActionDialog,
|
|
7
7
|
ActionDialogButton
|
|
@@ -17,13 +17,13 @@ import {
|
|
|
17
17
|
} from "../chunk-SJWIZT7B.js";
|
|
18
18
|
import {
|
|
19
19
|
usePopoverDialog
|
|
20
|
-
} from "../chunk-
|
|
20
|
+
} from "../chunk-JYVUFRRV.js";
|
|
21
21
|
import {
|
|
22
22
|
CheckGlyph,
|
|
23
23
|
OVERLAY_SHADOW,
|
|
24
24
|
PopoverSurface,
|
|
25
25
|
usePopover
|
|
26
|
-
} from "../chunk-
|
|
26
|
+
} from "../chunk-XIN7DOAB.js";
|
|
27
27
|
import "../chunk-RASGKEAL.js";
|
|
28
28
|
import "../chunk-AMUXRAUO.js";
|
|
29
29
|
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/turn-trace/recorder.ts"],"sourcesContent":["/**\n * One trace per agent turn: a root span for the turn's wall time and named\n * child spans for where that time went (admission, each model call, each tool\n * call, the box claim and prompt, persistence).\n *\n * This module only records. It has no imports, so the Router engine, the\n * sandbox helpers and the chat route share it from any runtime, a Worker\n * included. `./otel` turns a finished trace into OTLP spans for Tangle\n * Intelligence.\n *\n * The turn's trace id is its execution id in the charset every hop accepts\n * ({@link turnTraceId}), sent as `x-tangle-trace-id` on every Router and\n * Sandbox call, so a Router dispatch row and a sandbox record join the turn's\n * spans by one id.\n */\n\n/** What a span's time is spent on. Each instant of the turn is credited to the deepest open span's kind. */\nexport type TurnSpanKind =\n | 'admission'\n | 'router'\n | 'model'\n | 'network'\n | 'tool'\n | 'sandbox'\n | 'persist'\n | 'other'\n\nexport const TURN_SPAN_KINDS: readonly TurnSpanKind[] = ['admission', 'router', 'model', 'network', 'tool', 'sandbox', 'persist', 'other']\n\n/** Bounded primitive metadata. Never prompts, answers, tool arguments or credentials. */\nexport type TurnSpanAttrs = Record<string, string | number | boolean>\n\nexport interface TurnSpanRecord {\n spanId: string\n /** The root span's id for a top-level child. */\n parentSpanId: string\n name: string\n kind: TurnSpanKind\n startMs: number\n endMs: number\n attrs: TurnSpanAttrs\n /** Set when the span ended in failure; a short code or message, never content. */\n error?: string\n /** True when the turn finished while the span was still open. */\n unfinished?: boolean\n}\n\nexport interface TurnSpan {\n readonly id: string\n /** Merge attributes. A later value replaces an earlier one. */\n set(attrs: TurnSpanAttrs): TurnSpan\n /** End now. A second call changes nothing. `error` marks the span failed. */\n end(attrs?: TurnSpanAttrs, error?: unknown): void\n /** A child that starts now. */\n child(name: string, kind: TurnSpanKind, attrs?: TurnSpanAttrs): TurnSpan\n /** A child whose times are already known. */\n record(name: string, kind: TurnSpanKind, startMs: number, endMs: number, attrs?: TurnSpanAttrs): TurnSpan\n}\n\n/** How much of the turn's wall time is inside named spans, and what the time was spent on. */\nexport interface TurnTraceSummary {\n traceId: string\n wallMs: number\n /** Wall time inside at least one child span. */\n coveredMs: number\n /** `coveredMs / wallMs` as a percentage, one decimal. */\n coveragePct: number\n uncoveredMs: number\n /** The longest stretch with no span open: where an unnamed wait hides. */\n largestGapMs: number\n /** Wall time credited to the deepest open span's kind. Sums to `coveredMs`. */\n byKind: Record<TurnSpanKind, number>\n spans: number\n modelCalls: number\n toolCalls: number\n /** Spans refused after the per-turn cap. */\n dropped: number\n /** From the request to the first visible text the member could read (see {@link TurnTrace.markFirstText}); absent when none streamed. */\n firstTextMs?: number\n /** Headline latency: request to first reasoning, tool activity or answer output. */\n firstVisibleMs?: number\n /** D1 round trips in the turn scope, when its binding is instrumented. */\n d1Queries?: number\n}\n\nexport interface TurnTraceSnapshot {\n traceId: string\n /** The id the root span is exported under. */\n rootSpanId: string\n executionId: string\n startedAt: number\n endedAt: number\n spans: TurnSpanRecord[]\n summary: TurnTraceSummary\n /** `ok`, or the failure the turn ended with. */\n status: 'ok' | 'error'\n error?: string\n}\n\n/** Where a finished turn's trace goes. `labels` are the host's metadata for the root span (session, user, workspace). */\nexport type TurnTraceSink = (snapshot: TurnTraceSnapshot, labels: TurnSpanAttrs) => void | Promise<void>\n\nexport interface TurnTrace {\n /** The turn's execution id in the charset the Router and Sandbox accept. Send it as `x-tangle-trace-id`. */\n readonly traceId: string\n readonly executionId: string\n readonly startedAt: number\n /** The span a top-level child hangs from. */\n readonly root: TurnSpan\n /** Name the turn's execution id once it is known. Spans recorded earlier keep their times. */\n bind(executionId: string): void\n start(name: string, kind: TurnSpanKind, attrs?: TurnSpanAttrs, parent?: TurnSpan): TurnSpan\n record(name: string, kind: TurnSpanKind, startMs: number, endMs: number, attrs?: TurnSpanAttrs, parent?: TurnSpan): TurnSpan\n /** Run `work` inside a span; the span ends when it settles, failed if it throws. */\n measure<T>(name: string, kind: TurnSpanKind, work: (span: TurnSpan) => Promise<T> | T, attrs?: TurnSpanAttrs, parent?: TurnSpan): Promise<T>\n /**\n * Note that the turn's first visible text reached the member. The chat route calls it on the first text event of\n * either lane; a product that owns its turn calls it itself. Only the first call counts. The summary's\n * `firstTextMs` then reads from the request, so it holds admission, the box or the Router, and the model.\n */\n markFirstText(at?: number): void\n /** Mark the first reasoning, tool activity or answer output. Only the first call counts. */\n markFirstVisible(at?: number): void\n /** Read the current numbers without ending the trace. */\n summary(now?: number): TurnTraceSummary\n /** Read the spans recorded so far without ending the trace; an open span reads as ending at `now`. */\n spans(now?: number): TurnSpanRecord[]\n /** End the trace: open spans close at `endedAt`, and later spans are refused. A second call returns the first result. */\n finish(outcome?: { error?: unknown; endedAt?: number }): TurnTraceSnapshot\n}\n\nexport interface CreateTurnTraceOptions {\n /** Epoch ms the turn began (default now). A route passes its request time so admission is inside the trace. */\n startedAt?: number\n executionId?: string\n now?: () => number\n /** Most spans one turn keeps (default 1000); the rest are counted as dropped. */\n maxSpans?: number\n /** Live counter captured by the server turn owner; no Node dependency in the recorder. */\n d1QueryCounter?: { readonly queries: number }\n}\n\nconst TRACE_ID_PATTERN = /^[\\w-]{8,200}$/\nconst MAX_ATTRS = 48\nconst MAX_ATTR_STRING = 200\n\n/** True when the Router and the Sandbox API keep this id as a `x-tangle-trace-id`. */\nexport function isTraceId(value: string): boolean {\n return TRACE_ID_PATTERN.test(value)\n}\n\n/**\n * The turn's execution id as a trace id. Execution ids carry `:` (`app:session:turn`),\n * which the Router drops from `x-tangle-trace-id`, so every character outside\n * `[A-Za-z0-9_-]` becomes `_`. An id already in the charset is returned as it is.\n */\nexport function turnTraceId(executionId: string): string {\n // An id in the charset is the caller's own, whatever its length (the Router drops one under 8 characters; it is not rewritten here).\n if (/^[\\w-]{1,200}$/.test(executionId)) return executionId\n const id = executionId.replace(/[^\\w-]/g, '_').slice(0, 200)\n return id.length >= 8 ? id : id.padEnd(8, '_')\n}\n\nfunction randomHex(bytes: number): string {\n const out = new Uint8Array(bytes)\n if (typeof globalThis.crypto?.getRandomValues === 'function') globalThis.crypto.getRandomValues(out)\n else for (let i = 0; i < bytes; i++) out[i] = Math.floor(Math.random() * 256)\n return Array.from(out, (b) => b.toString(16).padStart(2, '0')).join('')\n}\n\nfunction boundedAttrs(attrs: TurnSpanAttrs): TurnSpanAttrs {\n const out: TurnSpanAttrs = {}\n let count = 0\n for (const [key, value] of Object.entries(attrs)) {\n if (count >= MAX_ATTRS) break\n if (typeof value === 'number' && !Number.isFinite(value)) continue\n out[key.slice(0, 80)] = typeof value === 'string' ? value.slice(0, MAX_ATTR_STRING) : value\n count++\n }\n return out\n}\n\nfunction errorText(error: unknown): string {\n if (error instanceof Error) return (error.name === 'Error' ? error.message : `${error.name}: ${error.message}`).slice(0, MAX_ATTR_STRING)\n return String(error).slice(0, MAX_ATTR_STRING)\n}\n\nconst zeroKinds = (): Record<TurnSpanKind, number> => ({\n admission: 0, router: 0, model: 0, network: 0, tool: 0, sandbox: 0, persist: 0, other: 0,\n})\n\nconst round1 = (value: number) => Math.round(value * 10) / 10\n\n/**\n * Coverage and the per-kind split for a set of spans over `[startMs, endMs]`.\n * Exported for a reader that holds the spans of a finished trace.\n */\nexport function summarizeTurnSpans(\n spans: readonly Pick<TurnSpanRecord, 'spanId' | 'parentSpanId' | 'kind' | 'name' | 'startMs' | 'endMs'>[],\n rootSpanId: string,\n startMs: number,\n endMs: number,\n traceId: string,\n dropped = 0,\n): TurnTraceSummary {\n const wallMs = Math.max(0, endMs - startMs)\n const parent = new Map(spans.map((span) => [span.spanId, span.parentSpanId]))\n const depthOf = (id: string): number => {\n let depth = 0\n for (let at = parent.get(id); at !== undefined && at !== rootSpanId; at = parent.get(at)) {\n depth++\n if (depth > 64) break\n }\n return depth\n }\n const clipped = spans\n .map((span) => ({ span, start: Math.max(startMs, span.startMs), end: Math.min(endMs, span.endMs), depth: depthOf(span.spanId) }))\n .filter((entry) => entry.end > entry.start)\n const points = [...new Set([startMs, endMs, ...clipped.flatMap((entry) => [entry.start, entry.end])])].sort((a, b) => a - b)\n const byKind = zeroKinds()\n let coveredMs = 0\n let largestGapMs = 0\n let gap = 0\n for (let i = 0; i + 1 < points.length; i++) {\n const from = points[i]!\n const to = points[i + 1]!\n let deepest: (typeof clipped)[number] | undefined\n for (const entry of clipped) {\n if (entry.start <= from && entry.end >= to && (!deepest || entry.depth > deepest.depth || (entry.depth === deepest.depth && entry.start > deepest.start))) deepest = entry\n }\n if (deepest) {\n byKind[deepest.span.kind] += to - from\n coveredMs += to - from\n gap = 0\n } else {\n gap += to - from\n largestGapMs = Math.max(largestGapMs, gap)\n }\n }\n for (const kind of TURN_SPAN_KINDS) byKind[kind] = round1(byKind[kind])\n return {\n traceId,\n wallMs: round1(wallMs),\n coveredMs: round1(coveredMs),\n coveragePct: wallMs > 0 ? round1((coveredMs / wallMs) * 100) : 0,\n uncoveredMs: round1(wallMs - coveredMs),\n largestGapMs: round1(largestGapMs),\n byKind,\n spans: spans.length,\n modelCalls: spans.filter((span) => span.name === 'model.call').length,\n toolCalls: spans.filter((span) => span.name === 'tool.call').length,\n dropped,\n }\n}\n\nexport function createTurnTrace(options: CreateTurnTraceOptions = {}): TurnTrace {\n const now = options.now ?? Date.now\n const startedAt = options.startedAt ?? now()\n const maxSpans = options.maxSpans ?? 1000\n const rootId = randomHex(8)\n let executionId = options.executionId ?? `pending_${randomHex(6)}`\n let traceId = turnTraceId(executionId)\n const records = new Map<string, TurnSpanRecord>()\n const open = new Set<string>()\n let dropped = 0\n let finished: TurnTraceSnapshot | undefined\n let firstVisibleAt: number | undefined\n let firstTextAt: number | undefined\n\n // A refused or late span still returns a handle, so instrumentation never branches on the trace's state.\n const inert = (id: string): TurnSpan => {\n const handle: TurnSpan = {\n id,\n set: () => handle,\n end: () => {},\n child: () => inert(rootId),\n record: () => inert(rootId),\n }\n return handle\n }\n\n const handleFor = (id: string): TurnSpan => {\n const handle: TurnSpan = {\n id,\n set(attrs) {\n const record = records.get(id)\n if (record && !finished) record.attrs = boundedAttrs({ ...record.attrs, ...attrs })\n return handle\n },\n end(attrs, error) {\n const record = records.get(id)\n if (!record || !open.has(id) || finished) return\n open.delete(id)\n record.endMs = Math.max(record.startMs, now())\n if (attrs) record.attrs = boundedAttrs({ ...record.attrs, ...attrs })\n if (error !== undefined) record.error = errorText(error)\n },\n child: (name, kind, attrs) => trace.start(name, kind, attrs, handle),\n record: (name, kind, start, end, attrs) => trace.record(name, kind, start, end, attrs, handle),\n }\n return handle\n }\n\n const add = (name: string, kind: TurnSpanKind, startMs: number, endMs: number | undefined, attrs: TurnSpanAttrs | undefined, parent: TurnSpan | undefined): TurnSpan => {\n if (finished) return inert(rootId)\n if (records.size >= maxSpans) {\n dropped++\n return inert(rootId)\n }\n const spanId = randomHex(8)\n records.set(spanId, {\n spanId,\n parentSpanId: parent && parent.id !== spanId ? parent.id : rootId,\n name: name.slice(0, 80),\n kind,\n startMs,\n endMs: endMs ?? startMs,\n attrs: attrs ? boundedAttrs(attrs) : {},\n })\n if (endMs === undefined) open.add(spanId)\n return handleFor(spanId)\n }\n\n const rootHandle: TurnSpan = {\n id: rootId,\n set: () => rootHandle,\n end: () => {},\n child: (name, kind, attrs) => trace.start(name, kind, attrs),\n record: (name, kind, start, end, attrs) => trace.record(name, kind, start, end, attrs),\n }\n\n const withMeasurements = (summary: TurnTraceSummary): TurnTraceSummary => ({\n ...summary,\n ...(firstVisibleAt === undefined ? {} : { firstVisibleMs: round1(firstVisibleAt - startedAt) }),\n ...(firstTextAt === undefined ? {} : { firstTextMs: round1(firstTextAt - startedAt) }),\n ...(options.d1QueryCounter === undefined ? {} : { d1Queries: options.d1QueryCounter.queries }),\n })\n\n const trace: TurnTrace = {\n get traceId() { return traceId },\n get executionId() { return executionId },\n startedAt,\n root: rootHandle,\n bind(id) {\n executionId = id\n traceId = turnTraceId(id)\n },\n start: (name, kind, attrs, parent) => add(name, kind, now(), undefined, attrs, parent),\n record: (name, kind, startMs, endMs, attrs, parent) => add(name, kind, startMs, Math.max(startMs, endMs), attrs, parent),\n async measure(name, kind, work, attrs, parent) {\n const span = trace.start(name, kind, attrs, parent)\n try {\n const result = await work(span)\n span.end()\n return result\n } catch (error) {\n span.end(undefined, error)\n throw error\n }\n },\n markFirstVisible(at) {\n if (finished || firstVisibleAt !== undefined) return\n firstVisibleAt = Math.max(startedAt, at ?? now())\n },\n markFirstText(at) {\n if (finished || firstTextAt !== undefined) return\n firstTextAt = Math.max(startedAt, at ?? now())\n firstVisibleAt ??= firstTextAt\n },\n summary(at) {\n if (finished) return finished.summary\n const end = at ?? now()\n return withMeasurements(summarizeTurnSpans(trace.spans(end), rootId, startedAt, end, traceId, dropped))\n },\n spans(at) {\n const end = at ?? finished?.endedAt ?? now()\n return [...records.values()].map((record) => open.has(record.spanId) ? { ...record, endMs: end } : { ...record })\n },\n finish(outcome) {\n if (finished) return finished\n const endedAt = Math.max(startedAt, outcome?.endedAt ?? now())\n for (const id of open) {\n const record = records.get(id)!\n record.endMs = Math.max(record.startMs, endedAt)\n record.unfinished = true\n }\n open.clear()\n const spans = [...records.values()].sort((a, b) => a.startMs - b.startMs)\n finished = {\n traceId,\n rootSpanId: rootId,\n executionId,\n startedAt,\n endedAt,\n spans,\n summary: withMeasurements(summarizeTurnSpans(spans, rootId, startedAt, endedAt, traceId, dropped)),\n status: outcome?.error === undefined ? 'ok' : 'error',\n ...(outcome?.error === undefined ? {} : { error: errorText(outcome.error) }),\n }\n return finished\n },\n }\n return trace\n}\n"],"mappings":";AA2BO,IAAM,kBAA2C,CAAC,aAAa,UAAU,SAAS,WAAW,QAAQ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AAI,WAAW,SAAS,WAAW,IAAI,CAAC;AAC7D,iBAAW,MAAM,MAAM;AACrB,cAAM,SAAS,QAAQ,IAAI,EAAE;AAC7B,eAAO,QAAQ,KAAK,IAAI,OAAO,SAAS,OAAO;AAC/C,eAAO,aAAa;AAAA,MACtB;AACA,WAAK,MAAM;AACX,YAAM,QAAQ,CAAC,GAAG,QAAQ,OAAO,CAAC,EAAE,KAAK,CAAC,GAAG,MAAM,EAAE,UAAU,EAAE,OAAO;AACxE,iBAAW;AAAA,QACT;AAAA,QACA,YAAY;AAAA,QACZ;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA,SAAS,iBAAiB,mBAAmB,OAAO,QAAQ,WAAW,SAAS,SAAS,OAAO,CAAC;AAAA,QACjG,QAAQ,SAAS,UAAU,SAAY,OAAO;AAAA,QAC9C,GAAI,SAAS,UAAU,SAAY,CAAC,IAAI,EAAE,OAAO,UAAU,QAAQ,KAAK,EAAE;AAAA,MAC5E;AACA,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/turn-trace/traced-fetch.ts"],"sourcesContent":["import type { TurnSpan, TurnTrace } from './recorder'\nimport { parseServerTiming, serverTimingAttrs } from './server-timing'\n\nconst counters = new WeakMap<TurnTrace, Map<string, number>>()\n\n/** 1-based count of `name` spans started through {@link nextCallIndex} on this trace. */\nexport function nextCallIndex(trace: TurnTrace, name: string): number {\n const byName = counters.get(trace) ?? new Map<string, number>()\n counters.set(trace, byName)\n const next = (byName.get(name) ?? 0) + 1\n byName.set(name, next)\n return next\n}\n\n/**\n * The Router's own steps before its provider fetch, as children of `router.pre_upstream` (`origin` is the Router's\n * handler start on this clock, `end` its `upstream_start`). `t_authed` and `t_admitted` are offsets from the handler\n * start: `router.auth` runs to the first, `router.admission` (budgets, credits, routing) to the second, and\n * `router.dispatch` (body, pricing, the dispatch row, the spend hold) to the provider fetch. `dispatch_row` and\n * `spend_authorize` are durations that run back to back and end just before the fetch, so they are placed backwards\n * from `end`. A step the header does not carry is left out, and nothing is placed outside `[origin, end]`.\n */\nfunction recordRouterSteps(parent: TurnSpan, origin: number, end: number, stamp: (name: string) => number | undefined): void {\n const offset = (name: string) => {\n const ms = stamp(name)\n return ms === undefined ? undefined : Math.min(end, origin + ms)\n }\n let at = origin\n for (const [step, name] of [['t_authed', 'router.auth'], ['t_admitted', 'router.admission']] as const) {\n const until = offset(step)\n if (until === undefined || until <= at) continue\n parent.record(name, 'router', at, until)\n at = until\n }\n if (end <= at) return\n const dispatch = parent.record('router.dispatch', 'router', at, end)\n let stepEnd = end\n for (const step of ['spend_authorize', 'dispatch_row']) {\n const ms = stamp(step)\n if (ms === undefined) continue\n const start = Math.max(at, stepEnd - ms)\n dispatch.record(`router.${step}`, 'router', start, stepEnd)\n stepEnd = start\n }\n}\n\nexport interface TracedModelFetchOptions {\n /** The span a model call hangs from. Default: the trace's root. */\n parent?: TurnSpan\n /** The model the request asks for. */\n model?: string\n /** Receives each model call's span as it starts, so the engine can add the token counts when usage arrives. */\n onSpan?: (span: TurnSpan) => void\n}\n\n/**\n * `fetch` for a model request, recording one `model.call` span per send: the\n * wall time from the request to the end of its body, the time to the first\n * byte, and the Router's own `Server-Timing` so the wait before the first byte\n * splits into network and server time.\n *\n * Children partition the call:\n * - `network`: the wait for headers, less the Router's server time;\n * - `router.pre_upstream`: the Router's work before its provider fetch\n * (`upstream_start`), split by its own steps (see {@link recordRouterSteps});\n * - `router.upstream_wait`: the provider's time to response headers\n * (`upstream_headers`);\n * - `model.stream`: headers to the end of the body.\n * Without a `Server-Timing` header the first byte's wait is one `model.wait`\n * span, because the split is not known.\n *\n * The response body is passed through unchanged; the span ends when the body\n * ends, errors or is cancelled.\n */\nexport function tracedModelFetch(trace: TurnTrace, inner: typeof fetch, options: TracedModelFetchOptions = {}): typeof fetch {\n return async (input, init) => {\n const sentAt = Date.now()\n const span = trace.start('model.call', 'model', {\n 'gen_ai.operation.name': 'chat',\n 'call.index': nextCallIndex(trace, 'model.call'),\n ...(options.model ? { 'gen_ai.request.model': options.model } : {}),\n }, options.parent)\n options.onSpan?.(span)\n let response: Response\n try {\n response = await inner(input, init)\n } catch (error) {\n span.end({ 'http.failed': true }, error)\n throw error\n }\n const headersAt = Date.now()\n const timing = parseServerTiming(response.headers.get('server-timing'))\n // The last entry: a fallback chain repeats a step, and the response is the last provider's.\n const stamp = (name: string) => {\n for (let i = timing.length - 1; i >= 0; i--) if (timing[i]!.name === name && timing[i]!.durMs !== undefined) return timing[i]!.durMs\n return undefined\n }\n const preUpstreamMs = stamp('upstream_start')\n const upstreamWaitMs = stamp('upstream_headers')\n const waitMs = headersAt - sentAt\n span.set({ 'http.status_code': response.status, ttfb_ms: waitMs, ...serverTimingAttrs(timing) })\n\n let firstByteAt: number | undefined\n const finish = (endedAt: number, error?: unknown, cancelled?: boolean) => {\n const known = preUpstreamMs !== undefined || upstreamWaitMs !== undefined\n if (known) {\n const serverMs = Math.min(waitMs, (preUpstreamMs ?? 0) + (upstreamWaitMs ?? 0))\n const networkMs = waitMs - serverMs\n let at = sentAt\n span.record('network', 'network', at, at + networkMs, { 'network.ms': Math.round(networkMs) })\n at += networkMs\n if (preUpstreamMs !== undefined) {\n const end = Math.min(headersAt, at + preUpstreamMs)\n recordRouterSteps(span.record('router.pre_upstream', 'router', at, end), at, end, stamp)\n at = end\n }\n if (upstreamWaitMs !== undefined) span.record('router.upstream_wait', 'model', at, headersAt)\n span.set({ network_ms: Math.round(networkMs), router_server_ms: Math.round(serverMs) })\n } else {\n span.record('model.wait', 'model', sentAt, headersAt, { split: 'unknown' })\n }\n span.record('model.stream', 'model', headersAt, Math.max(headersAt, endedAt))\n const failure = error ?? (response.status >= 400 ? `http_${response.status}` : undefined)\n span.end({\n ...(firstByteAt !== undefined ? { ttft_ms: firstByteAt - sentAt } : {}),\n ...(cancelled ? { cancelled: true } : {}),\n }, failure)\n }\n\n if (!response.body) {\n finish(headersAt)\n return response\n }\n const reader = response.body.getReader()\n let settled = false\n const settle = (error?: unknown, cancelled?: boolean) => {\n if (settled) return\n settled = true\n finish(Date.now(), error, cancelled)\n }\n const body = new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n const { done, value } = await reader.read()\n if (done) {\n settle()\n controller.close()\n return\n }\n firstByteAt ??= Date.now()\n controller.enqueue(value)\n } catch (error) {\n settle(error)\n controller.error(error)\n }\n },\n async cancel(reason) {\n settle(undefined, true)\n await reader.cancel(reason)\n },\n })\n return new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers })\n }\n}\n"],"mappings":";;;;;;AAGA,IAAM,WAAW,oBAAI,QAAwC;AAGtD,SAAS,cAAc,OAAkB,MAAsB;AACpE,QAAM,SAAS,SAAS,IAAI,KAAK,KAAK,oBAAI,IAAoB;AAC9D,WAAS,IAAI,OAAO,MAAM;AAC1B,QAAM,QAAQ,OAAO,IAAI,IAAI,KAAK,KAAK;AACvC,SAAO,IAAI,MAAM,IAAI;AACrB,SAAO;AACT;AAUA,SAAS,kBAAkB,QAAkB,QAAgB,KAAa,OAAmD;AAC3H,QAAM,SAAS,CAAC,SAAiB;AAC/B,UAAM,KAAK,MAAM,IAAI;AACrB,WAAO,OAAO,SAAY,SAAY,KAAK,IAAI,KAAK,SAAS,EAAE;AAAA,EACjE;AACA,MAAI,KAAK;AACT,aAAW,CAAC,MAAM,IAAI,KAAK,CAAC,CAAC,YAAY,aAAa,GAAG,CAAC,cAAc,kBAAkB,CAAC,GAAY;AACrG,UAAM,QAAQ,OAAO,IAAI;AACzB,QAAI,UAAU,UAAa,SAAS,GAAI;AACxC,WAAO,OAAO,MAAM,UAAU,IAAI,KAAK;AACvC,SAAK;AAAA,EACP;AACA,MAAI,OAAO,GAAI;AACf,QAAM,WAAW,OAAO,OAAO,mBAAmB,UAAU,IAAI,GAAG;AACnE,MAAI,UAAU;AACd,aAAW,QAAQ,CAAC,mBAAmB,cAAc,GAAG;AACtD,UAAM,KAAK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A,IACrC;AACA,UAAM,OAAO,IAAI,eAA2B;AAAA,MAC1C,MAAM,KAAK,YAAY;AACrB,YAAI;AACF,gBAAM,EAAE,MAAM,MAAM,IAAI,MAAM,OAAO,KAAK;AAC1C,cAAI,MAAM;AACR,mBAAO;AACP,uBAAW,MAAM;AACjB;AAAA,UACF;AACA,0BAAgB,KAAK,IAAI;AACzB,qBAAW,QAAQ,KAAK;AAAA,QAC1B,SAAS,OAAO;AACd,iBAAO,KAAK;AACZ,qBAAW,MAAM,KAAK;AAAA,QACxB;AAAA,MACF;AAAA,MACA,MAAM,OAAO,QAAQ;AACnB,eAAO,QAAW,IAAI;AACtB,cAAM,OAAO,OAAO,MAAM;AAAA,MAC5B;AAAA,IACF,CAAC;AACD,WAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,SAAS,QAAQ,YAAY,SAAS,YAAY,SAAS,SAAS,QAAQ,CAAC;AAAA,EACnH;AACF;","names":[]}
|
package/dist/chunk-LHGYK5I3.js
DELETED
|
@@ -1,160 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
TURN_SPAN_KINDS
|
|
3
|
-
} from "./chunk-7QZNHBQT.js";
|
|
4
|
-
|
|
5
|
-
// src/turn-trace/otel.ts
|
|
6
|
-
function attributes(record, doubles = /* @__PURE__ */ new Set()) {
|
|
7
|
-
return Object.entries(record).flatMap(([key, value]) => {
|
|
8
|
-
if (typeof value === "number" && !Number.isFinite(value)) return [];
|
|
9
|
-
return [{
|
|
10
|
-
key,
|
|
11
|
-
value: typeof value === "number" ? Number.isInteger(value) && !doubles.has(key) ? { intValue: value.toString() } : { doubleValue: value } : typeof value === "boolean" ? { boolValue: value } : { stringValue: value }
|
|
12
|
-
}];
|
|
13
|
-
});
|
|
14
|
-
}
|
|
15
|
-
var ROOT_MEASUREMENTS = /* @__PURE__ */ new Set([
|
|
16
|
-
"tangle.duration_ms",
|
|
17
|
-
"tangle.turn.wall_ms",
|
|
18
|
-
"tangle.turn.covered_ms",
|
|
19
|
-
"tangle.turn.coverage_pct",
|
|
20
|
-
"tangle.turn.uncovered_ms",
|
|
21
|
-
"tangle.turn.largest_gap_ms",
|
|
22
|
-
"tangle.turn.first_visible_ms",
|
|
23
|
-
"tangle.turn.first_text_ms",
|
|
24
|
-
...TURN_SPAN_KINDS.map((kind) => `tangle.turn.${kind}_ms`)
|
|
25
|
-
]);
|
|
26
|
-
function otlpTraceId(traceId) {
|
|
27
|
-
if (/^[0-9a-f]{32}$/.test(traceId)) return traceId;
|
|
28
|
-
const dashless = traceId.replace(/-/g, "");
|
|
29
|
-
if (/^[0-9a-f]{32}$/.test(dashless)) return dashless;
|
|
30
|
-
return hexId(traceId, 32);
|
|
31
|
-
}
|
|
32
|
-
function hexId(input, length) {
|
|
33
|
-
const hashes = [2166136261, 2654435769, 2246822507, 3266489909];
|
|
34
|
-
for (const byte of new TextEncoder().encode(input)) {
|
|
35
|
-
for (let lane = 0; lane < hashes.length; lane += 1) hashes[lane] = Math.imul(hashes[lane] ^ byte + lane, 16777619);
|
|
36
|
-
}
|
|
37
|
-
let out = hashes.map((hash) => (hash >>> 0).toString(16).padStart(8, "0")).join("");
|
|
38
|
-
while (out.length < length) out += hexId(`${input}:${out.length}`, 32);
|
|
39
|
-
return out.slice(0, length);
|
|
40
|
-
}
|
|
41
|
-
var msToNs = (ms) => (BigInt(Math.floor(ms)) * 1000000n).toString();
|
|
42
|
-
var SPAN_KIND = { "model.call": "LLM", "tool.call": "TOOL" };
|
|
43
|
-
function buildTurnTraceOtelSpans(snapshot, labels = {}) {
|
|
44
|
-
const traceId = otlpTraceId(snapshot.traceId);
|
|
45
|
-
const root = snapshot.rootSpanId;
|
|
46
|
-
const { summary } = snapshot;
|
|
47
|
-
const rootAttrs = {
|
|
48
|
-
...labels,
|
|
49
|
-
"openinference.span.kind": "CHAIN",
|
|
50
|
-
"tangle.execution_id": snapshot.executionId,
|
|
51
|
-
"tangle.trace_id": snapshot.traceId,
|
|
52
|
-
"tangle.started_at_ms": snapshot.startedAt,
|
|
53
|
-
"tangle.completed_at_ms": snapshot.endedAt,
|
|
54
|
-
"tangle.duration_ms": summary.wallMs,
|
|
55
|
-
"tangle.turn.wall_ms": summary.wallMs,
|
|
56
|
-
"tangle.turn.covered_ms": summary.coveredMs,
|
|
57
|
-
"tangle.turn.coverage_pct": summary.coveragePct,
|
|
58
|
-
"tangle.turn.uncovered_ms": summary.uncoveredMs,
|
|
59
|
-
"tangle.turn.largest_gap_ms": summary.largestGapMs,
|
|
60
|
-
"tangle.turn.spans": summary.spans,
|
|
61
|
-
"tangle.turn.model_calls": summary.modelCalls,
|
|
62
|
-
"tangle.turn.tool_calls": summary.toolCalls,
|
|
63
|
-
...summary.firstVisibleMs === void 0 ? {} : { "tangle.turn.first_visible_ms": summary.firstVisibleMs },
|
|
64
|
-
...summary.firstTextMs === void 0 ? {} : { "tangle.turn.first_text_ms": summary.firstTextMs },
|
|
65
|
-
...summary.d1Queries === void 0 ? {} : { "tangle.turn.d1_queries": summary.d1Queries },
|
|
66
|
-
...summary.dropped ? { "tangle.turn.spans_dropped": summary.dropped } : {},
|
|
67
|
-
...Object.fromEntries(TURN_SPAN_KINDS.map((kind) => [`tangle.turn.${kind}_ms`, summary.byKind[kind]]))
|
|
68
|
-
};
|
|
69
|
-
const spans = [{
|
|
70
|
-
traceId,
|
|
71
|
-
spanId: root,
|
|
72
|
-
name: "agent_app.turn",
|
|
73
|
-
kind: 1,
|
|
74
|
-
startTimeUnixNano: msToNs(snapshot.startedAt),
|
|
75
|
-
endTimeUnixNano: msToNs(snapshot.endedAt),
|
|
76
|
-
attributes: attributes(rootAttrs, ROOT_MEASUREMENTS),
|
|
77
|
-
status: snapshot.status === "ok" ? { code: 1 } : { code: 2, ...snapshot.error ? { message: snapshot.error } : {} }
|
|
78
|
-
}];
|
|
79
|
-
for (const span of snapshot.spans) {
|
|
80
|
-
const attrs = {
|
|
81
|
-
...span.attrs,
|
|
82
|
-
"openinference.span.kind": SPAN_KIND[span.name] ?? "CHAIN",
|
|
83
|
-
"tangle.turn.span_kind": span.kind,
|
|
84
|
-
"agent.parent.confidence": "explicit",
|
|
85
|
-
...span.name === "tool.call" ? { "gen_ai.operation.name": "execute_tool" } : {},
|
|
86
|
-
...span.unfinished ? { "tangle.turn.unfinished": true } : {},
|
|
87
|
-
...span.error ? { "error.message": span.error } : {}
|
|
88
|
-
};
|
|
89
|
-
spans.push({
|
|
90
|
-
traceId,
|
|
91
|
-
spanId: span.spanId,
|
|
92
|
-
parentSpanId: span.parentSpanId,
|
|
93
|
-
name: span.name,
|
|
94
|
-
kind: 1,
|
|
95
|
-
startTimeUnixNano: msToNs(span.startMs),
|
|
96
|
-
endTimeUnixNano: msToNs(span.endMs),
|
|
97
|
-
attributes: attributes(attrs),
|
|
98
|
-
status: span.error ? { code: 2, message: span.error } : { code: 1 }
|
|
99
|
-
});
|
|
100
|
-
}
|
|
101
|
-
return spans;
|
|
102
|
-
}
|
|
103
|
-
var DEFAULT_INTELLIGENCE_BASE_URL = "https://intelligence.tangle.tools";
|
|
104
|
-
var INGEST_KEY_ENV = ["SANDBOX_PRODUCTION_API_KEY", "TCLOUD_SANDBOX_API_KEY", "SANDBOX_API_KEY"];
|
|
105
|
-
function resolveIngestKey() {
|
|
106
|
-
if (typeof process === "undefined") return void 0;
|
|
107
|
-
for (const name of INGEST_KEY_ENV) {
|
|
108
|
-
const value = process.env?.[name]?.trim();
|
|
109
|
-
if (value) return value;
|
|
110
|
-
}
|
|
111
|
-
return void 0;
|
|
112
|
-
}
|
|
113
|
-
var SCOPE = { name: "@tangle-network/agent-app", version: "turn-trace" };
|
|
114
|
-
function createIntelligenceTurnTraceSink(options) {
|
|
115
|
-
const url = `${(options.baseUrl ?? DEFAULT_INTELLIGENCE_BASE_URL).replace(/\/+$/, "")}/v1/otlp/v1/traces`;
|
|
116
|
-
const report = options.onError ?? ((reason) => console.warn(`[turn-trace] export failed: ${reason}`));
|
|
117
|
-
const fail = (reason) => {
|
|
118
|
-
try {
|
|
119
|
-
report(reason.slice(0, 200));
|
|
120
|
-
} catch {
|
|
121
|
-
}
|
|
122
|
-
};
|
|
123
|
-
let missingKeyReported = false;
|
|
124
|
-
return async (snapshot, labels) => {
|
|
125
|
-
const apiKey = options.apiKey?.trim() || resolveIngestKey();
|
|
126
|
-
if (!apiKey) {
|
|
127
|
-
if (!missingKeyReported) fail(`no ingest key: set ${INGEST_KEY_ENV.join(", ")} or pass apiKey`);
|
|
128
|
-
missingKeyReported = true;
|
|
129
|
-
return;
|
|
130
|
-
}
|
|
131
|
-
try {
|
|
132
|
-
const body = {
|
|
133
|
-
resourceSpans: [{
|
|
134
|
-
resource: { attributes: attributes({ "service.name": options.project, "tangle.project": options.project }) },
|
|
135
|
-
scopeSpans: [{ scope: SCOPE, spans: buildTurnTraceOtelSpans(snapshot, { project: options.project, ...labels }) }]
|
|
136
|
-
}]
|
|
137
|
-
};
|
|
138
|
-
const response = await fetch(url, {
|
|
139
|
-
method: "POST",
|
|
140
|
-
headers: { "content-type": "application/json", authorization: `Bearer ${apiKey}` },
|
|
141
|
-
body: JSON.stringify(body),
|
|
142
|
-
signal: AbortSignal.timeout(options.timeoutMs ?? 5e3)
|
|
143
|
-
});
|
|
144
|
-
const text = await response.text();
|
|
145
|
-
if (!response.ok) return fail(`HTTP ${response.status} from the OTLP ingest`);
|
|
146
|
-
const rejected = Number(JSON.parse(text || "{}").partialSuccess?.rejectedSpans ?? 0);
|
|
147
|
-
if (rejected > 0) fail(`the OTLP ingest rejected ${rejected} spans`);
|
|
148
|
-
} catch (error) {
|
|
149
|
-
fail(error instanceof Error ? error.message : "turn trace export failed");
|
|
150
|
-
}
|
|
151
|
-
};
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
export {
|
|
155
|
-
otlpTraceId,
|
|
156
|
-
buildTurnTraceOtelSpans,
|
|
157
|
-
resolveIngestKey,
|
|
158
|
-
createIntelligenceTurnTraceSink
|
|
159
|
-
};
|
|
160
|
-
//# sourceMappingURL=chunk-LHGYK5I3.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/turn-trace/otel.ts"],"sourcesContent":["/**\n * A finished turn trace as OTLP spans, sent to Tangle Intelligence.\n *\n * The attribute vocabulary is the one agent-runtime's span builders write\n * (`gen_ai.operation.name`, `gen_ai.request.model`, `gen_ai.usage.*`,\n * `gen_ai.tool.name`, OpenInference's span kind, `agent.parent.confidence`), and\n * the wire shape is the one its `createOtelExporter` posts to\n * `<base>/v1/otlp/v1/traces`.\n *\n * It does not import agent-runtime. The runtime root pulls the whole sandbox\n * SDK into a Worker bundle, and the SDK's chain client imports `viem`, which a\n * Worker build cannot resolve (Hospitality's release failed on exactly that);\n * and its exporter keeps a timer a Worker refuses at module scope. One OTLP\n * POST per finished turn needs neither.\n */\nimport { TURN_SPAN_KINDS, type TurnSpanAttrs, type TurnSpanKind, type TurnTraceSink, type TurnTraceSnapshot } from './recorder'\n\n/** One OTLP/JSON span, as Intelligence's ingest reads it. */\nexport interface OtlpSpan {\n traceId: string\n spanId: string\n parentSpanId?: string\n name: string\n kind: number\n startTimeUnixNano: string\n endTimeUnixNano: string\n attributes: Array<{ key: string; value: { stringValue?: string; intValue?: string; doubleValue?: number; boolValue?: boolean } }>\n status: { code: number; message?: string }\n}\n\n/** `doubles` names measurements that stay `doubleValue` when they land on a whole number, so a reader sees one type per key. */\nfunction attributes(record: Record<string, string | number | boolean>, doubles: ReadonlySet<string> = new Set()): OtlpSpan['attributes'] {\n return Object.entries(record).flatMap(([key, value]) => {\n if (typeof value === 'number' && !Number.isFinite(value)) return []\n return [{\n key,\n value: typeof value === 'number' ? (Number.isInteger(value) && !doubles.has(key) ? { intValue: value.toString() } : { doubleValue: value })\n : typeof value === 'boolean' ? { boolValue: value } : { stringValue: value },\n }]\n })\n}\n\n/** The root span's measured numbers: one decimal, so each is always a `doubleValue`. */\nconst ROOT_MEASUREMENTS: ReadonlySet<string> = new Set([\n 'tangle.duration_ms',\n 'tangle.turn.wall_ms',\n 'tangle.turn.covered_ms',\n 'tangle.turn.coverage_pct',\n 'tangle.turn.uncovered_ms',\n 'tangle.turn.largest_gap_ms',\n 'tangle.turn.first_visible_ms',\n 'tangle.turn.first_text_ms',\n ...TURN_SPAN_KINDS.map((kind) => `tangle.turn.${kind}_ms`),\n])\n\n/**\n * A Tangle trace id as the 32-hex OTLP trace id. The mapping is the Sandbox SDK's `otelTraceIdForTangleTrace`, so a\n * Sandbox trace export of the same turn lands in the same OTLP trace. An id that is already 32 hex, or a UUID, is used as it is.\n */\nexport function otlpTraceId(traceId: string): string {\n if (/^[0-9a-f]{32}$/.test(traceId)) return traceId\n const dashless = traceId.replace(/-/g, '')\n if (/^[0-9a-f]{32}$/.test(dashless)) return dashless\n return hexId(traceId, 32)\n}\n\nfunction hexId(input: string, length: number): string {\n const hashes = [2166136261, 2654435769, 2246822507, 3266489909]\n for (const byte of new TextEncoder().encode(input)) {\n for (let lane = 0; lane < hashes.length; lane += 1) hashes[lane] = Math.imul((hashes[lane] as number) ^ (byte + lane), 16777619)\n }\n let out = hashes.map((hash) => (hash >>> 0).toString(16).padStart(8, '0')).join('')\n while (out.length < length) out += hexId(`${input}:${out.length}`, 32)\n return out.slice(0, length)\n}\n\nconst msToNs = (ms: number) => (BigInt(Math.floor(ms)) * 1_000_000n).toString()\n\n/** OpenInference span kind per turn span: model calls read as LLM, tool calls as TOOL. */\nconst SPAN_KIND: Partial<Record<string, 'LLM' | 'TOOL'>> = { 'model.call': 'LLM', 'tool.call': 'TOOL' }\n\n/**\n * The root span (`agent_app.turn`) carries the host's labels and the turn's\n * numbers: wall time, the share inside child spans, and the time credited to\n * each kind of span. Children follow under it.\n */\nexport function buildTurnTraceOtelSpans(snapshot: TurnTraceSnapshot, labels: TurnSpanAttrs = {}): OtlpSpan[] {\n const traceId = otlpTraceId(snapshot.traceId)\n const root = snapshot.rootSpanId\n const { summary } = snapshot\n const rootAttrs: Record<string, string | number | boolean> = {\n ...labels,\n 'openinference.span.kind': 'CHAIN',\n 'tangle.execution_id': snapshot.executionId,\n 'tangle.trace_id': snapshot.traceId,\n 'tangle.started_at_ms': snapshot.startedAt,\n 'tangle.completed_at_ms': snapshot.endedAt,\n 'tangle.duration_ms': summary.wallMs,\n 'tangle.turn.wall_ms': summary.wallMs,\n 'tangle.turn.covered_ms': summary.coveredMs,\n 'tangle.turn.coverage_pct': summary.coveragePct,\n 'tangle.turn.uncovered_ms': summary.uncoveredMs,\n 'tangle.turn.largest_gap_ms': summary.largestGapMs,\n 'tangle.turn.spans': summary.spans,\n 'tangle.turn.model_calls': summary.modelCalls,\n 'tangle.turn.tool_calls': summary.toolCalls,\n ...(summary.firstVisibleMs === undefined ? {} : { 'tangle.turn.first_visible_ms': summary.firstVisibleMs }),\n ...(summary.firstTextMs === undefined ? {} : { 'tangle.turn.first_text_ms': summary.firstTextMs }),\n ...(summary.d1Queries === undefined ? {} : { 'tangle.turn.d1_queries': summary.d1Queries }),\n ...(summary.dropped ? { 'tangle.turn.spans_dropped': summary.dropped } : {}),\n ...Object.fromEntries(TURN_SPAN_KINDS.map((kind: TurnSpanKind) => [`tangle.turn.${kind}_ms`, summary.byKind[kind]])),\n }\n const spans: OtlpSpan[] = [{\n traceId,\n spanId: root,\n name: 'agent_app.turn',\n kind: 1,\n startTimeUnixNano: msToNs(snapshot.startedAt),\n endTimeUnixNano: msToNs(snapshot.endedAt),\n attributes: attributes(rootAttrs, ROOT_MEASUREMENTS),\n status: snapshot.status === 'ok' ? { code: 1 } : { code: 2, ...(snapshot.error ? { message: snapshot.error } : {}) },\n }]\n for (const span of snapshot.spans) {\n const attrs: Record<string, string | number | boolean> = {\n ...span.attrs,\n 'openinference.span.kind': SPAN_KIND[span.name] ?? 'CHAIN',\n 'tangle.turn.span_kind': span.kind,\n 'agent.parent.confidence': 'explicit',\n ...(span.name === 'tool.call' ? { 'gen_ai.operation.name': 'execute_tool' } : {}),\n ...(span.unfinished ? { 'tangle.turn.unfinished': true } : {}),\n ...(span.error ? { 'error.message': span.error } : {}),\n }\n spans.push({\n traceId,\n spanId: span.spanId,\n parentSpanId: span.parentSpanId,\n name: span.name,\n kind: 1,\n startTimeUnixNano: msToNs(span.startMs),\n endTimeUnixNano: msToNs(span.endMs),\n attributes: attributes(attrs),\n status: span.error ? { code: 2, message: span.error } : { code: 1 },\n })\n }\n return spans\n}\n\nexport interface IntelligenceTurnTraceSinkOptions {\n /** The Intelligence project the spans belong to, e.g. `legal-agent`. */\n project: string\n /**\n * The tenant key the ingest requires. Omit it: the sink reads the Sandbox product key from the first of\n * `SANDBOX_PRODUCTION_API_KEY`, `TCLOUD_SANDBOX_API_KEY` and `SANDBOX_API_KEY` that is set, the platform key the\n * ingest verifies. Legal's Worker `TANGLE_API_KEY` got 401 on every export (#468, 2026-10-19), so a key is never assumed: a refusal is a console warning.\n */\n apiKey?: string\n /** Default `https://intelligence.tangle.tools`; spans go to `<base>/v1/otlp/v1/traces`. */\n baseUrl?: string\n /** Called with a short reason when a delivery fails. Never receives span content. Default: a console warning. */\n onError?: (reason: string) => void\n /** Milliseconds one POST may take (default 5000). */\n timeoutMs?: number\n}\n\nconst DEFAULT_INTELLIGENCE_BASE_URL = 'https://intelligence.tangle.tools'\n/** The Sandbox product key names, in the order the apps' sandbox lanes prefer them. Read per delivery: a Worker's env is not populated at module scope. */\nconst INGEST_KEY_ENV = ['SANDBOX_PRODUCTION_API_KEY', 'TCLOUD_SANDBOX_API_KEY', 'SANDBOX_API_KEY'] as const\n\n/** The key the ingest verifies, from the host's environment: what the sink uses when it is given none, and what an app's other Intelligence client should use too. */\nexport function resolveIngestKey(): string | undefined {\n if (typeof process === 'undefined') return undefined\n for (const name of INGEST_KEY_ENV) {\n const value = process.env?.[name]?.trim()\n if (value) return value\n }\n return undefined\n}\nconst SCOPE = { name: '@tangle-network/agent-app', version: 'turn-trace' }\n\n/**\n * The sink a chat route or a Worker turn hands each finished trace to: one OTLP POST per turn, awaited, so a host that\n * runs it under `waitUntil` keeps the isolate alive until delivery. It never throws; every failure, including a missing\n * key and a non-2xx answer, goes to `onError` (a console warning by default), because a silent sink hid Legal's 401s.\n */\nexport function createIntelligenceTurnTraceSink(options: IntelligenceTurnTraceSinkOptions): TurnTraceSink {\n const url = `${(options.baseUrl ?? DEFAULT_INTELLIGENCE_BASE_URL).replace(/\\/+$/, '')}/v1/otlp/v1/traces`\n const report = options.onError ?? ((reason: string) => console.warn(`[turn-trace] export failed: ${reason}`))\n const fail = (reason: string) => { try { report(reason.slice(0, 200)) } catch { /* telemetry only */ } }\n let missingKeyReported = false\n return async (snapshot, labels) => {\n const apiKey = options.apiKey?.trim() || resolveIngestKey()\n if (!apiKey) {\n if (!missingKeyReported) fail(`no ingest key: set ${INGEST_KEY_ENV.join(', ')} or pass apiKey`)\n missingKeyReported = true\n return\n }\n try {\n const body = {\n resourceSpans: [{\n resource: { attributes: attributes({ 'service.name': options.project, 'tangle.project': options.project }) },\n scopeSpans: [{ scope: SCOPE, spans: buildTurnTraceOtelSpans(snapshot, { project: options.project, ...labels }) }],\n }],\n }\n const response = await fetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json', authorization: `Bearer ${apiKey}` },\n body: JSON.stringify(body),\n signal: AbortSignal.timeout(options.timeoutMs ?? 5_000),\n })\n const text = await response.text()\n if (!response.ok) return fail(`HTTP ${response.status} from the OTLP ingest`)\n // A 2xx can still refuse part of a batch (`partialSuccess.rejectedSpans`).\n const rejected = Number((JSON.parse(text || '{}') as { partialSuccess?: { rejectedSpans?: unknown } }).partialSuccess?.rejectedSpans ?? 0)\n if (rejected > 0) fail(`the OTLP ingest rejected ${rejected} spans`)\n } catch (error) {\n fail(error instanceof Error ? error.message : 'turn trace export failed')\n }\n }\n}\n"],"mappings":";;;;;AA+BA,SAAS,WAAW,QAAmD,UAA+B,oBAAI,IAAI,GAA2B;AACvI,SAAO,OAAO,QAAQ,MAAM,EAAE,QAAQ,CAAC,CAAC,KAAK,KAAK,MAAM;AACtD,QAAI,OAAO,UAAU,YAAY,CAAC,OAAO,SAA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BAAuB;AAE5E,YAAM,WAAW,OAAQ,KAAK,MAAM,QAAQ,IAAI,EAAuD,gBAAgB,iBAAiB,CAAC;AACzI,UAAI,WAAW,EAAG,MAAK,4BAA4B,QAAQ,QAAQ;AAAA,IACrE,SAAS,OAAO;AACd,WAAK,iBAAiB,QAAQ,MAAM,UAAU,0BAA0B;AAAA,IAC1E;AAAA,EACF;AACF;","names":[]}
|
package/dist/chunk-PIUYJTTK.js
DELETED
|
@@ -1,63 +0,0 @@
|
|
|
1
|
-
// src/turn-trace/server-timing.ts
|
|
2
|
-
function splitEntries(header) {
|
|
3
|
-
const out = [];
|
|
4
|
-
let current = "";
|
|
5
|
-
let quoted = false;
|
|
6
|
-
for (const char of header) {
|
|
7
|
-
if (char === '"') quoted = !quoted;
|
|
8
|
-
if (char === "," && !quoted) {
|
|
9
|
-
out.push(current);
|
|
10
|
-
current = "";
|
|
11
|
-
} else {
|
|
12
|
-
current += char;
|
|
13
|
-
}
|
|
14
|
-
}
|
|
15
|
-
out.push(current);
|
|
16
|
-
return out;
|
|
17
|
-
}
|
|
18
|
-
function parseServerTiming(header) {
|
|
19
|
-
if (!header) return [];
|
|
20
|
-
const entries = [];
|
|
21
|
-
for (const raw of splitEntries(header.slice(0, 4096))) {
|
|
22
|
-
const [name, ...params] = raw.split(";").map((part) => part.trim());
|
|
23
|
-
if (!name || !/^[\w.!#$%&'*+^`|~-]+$/.test(name)) continue;
|
|
24
|
-
const entry = { name };
|
|
25
|
-
for (const param of params) {
|
|
26
|
-
const eq = param.indexOf("=");
|
|
27
|
-
if (eq < 0) continue;
|
|
28
|
-
const key = param.slice(0, eq).trim().toLowerCase();
|
|
29
|
-
const value = param.slice(eq + 1).trim();
|
|
30
|
-
if (key === "dur") {
|
|
31
|
-
const dur = Number(value);
|
|
32
|
-
if (Number.isFinite(dur) && dur >= 0) entry.durMs = dur;
|
|
33
|
-
} else if (key === "desc") {
|
|
34
|
-
entry.desc = value.replace(/^"|"$/g, "").slice(0, 120);
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
entries.push(entry);
|
|
38
|
-
}
|
|
39
|
-
return entries;
|
|
40
|
-
}
|
|
41
|
-
function serverTimingAttrs(entries) {
|
|
42
|
-
const out = {};
|
|
43
|
-
for (const entry of entries.slice(0, 32)) {
|
|
44
|
-
const key = entry.name.replace(/[^\w]/g, "_");
|
|
45
|
-
if (entry.durMs !== void 0) out[`server_timing.${key}_ms`] = Math.round(entry.durMs * 10) / 10;
|
|
46
|
-
else if (entry.desc !== void 0) out[`server_timing.${key}`] = entry.desc;
|
|
47
|
-
}
|
|
48
|
-
return out;
|
|
49
|
-
}
|
|
50
|
-
function formatServerTiming(entries) {
|
|
51
|
-
return entries.filter((entry) => /^[\w.!#$%&'*+^`|~-]+$/.test(entry.name)).slice(0, 32).map((entry) => [
|
|
52
|
-
entry.name,
|
|
53
|
-
...entry.durMs === void 0 ? [] : [`dur=${Math.round(entry.durMs * 10) / 10}`],
|
|
54
|
-
...entry.desc === void 0 ? [] : [`desc="${entry.desc.replace(/["\\]/g, "").slice(0, 120)}"`]
|
|
55
|
-
].join(";")).join(", ");
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
export {
|
|
59
|
-
parseServerTiming,
|
|
60
|
-
serverTimingAttrs,
|
|
61
|
-
formatServerTiming
|
|
62
|
-
};
|
|
63
|
-
//# sourceMappingURL=chunk-PIUYJTTK.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/turn-trace/server-timing.ts"],"sourcesContent":["/** One entry of a `Server-Timing` response header. */\nexport interface ServerTimingEntry {\n name: string\n /** Milliseconds, when the entry carries `dur`. */\n durMs?: number\n /** `desc`, unquoted: a count or a label, never a duration. */\n desc?: string\n}\n\n/** Split on commas that sit outside a quoted `desc`. */\nfunction splitEntries(header: string): string[] {\n const out: string[] = []\n let current = ''\n let quoted = false\n for (const char of header) {\n if (char === '\"') quoted = !quoted\n if (char === ',' && !quoted) {\n out.push(current)\n current = ''\n } else {\n current += char\n }\n }\n out.push(current)\n return out\n}\n\n/**\n * Parse a `Server-Timing` header, as the Router and the Sandbox orchestrator\n * send it. A malformed entry is skipped; the result never throws.\n */\nexport function parseServerTiming(header: string | null | undefined): ServerTimingEntry[] {\n if (!header) return []\n const entries: ServerTimingEntry[] = []\n for (const raw of splitEntries(header.slice(0, 4096))) {\n const [name, ...params] = raw.split(';').map((part) => part.trim())\n if (!name || !/^[\\w.!#$%&'*+^`|~-]+$/.test(name)) continue\n const entry: ServerTimingEntry = { name }\n for (const param of params) {\n const eq = param.indexOf('=')\n if (eq < 0) continue\n const key = param.slice(0, eq).trim().toLowerCase()\n const value = param.slice(eq + 1).trim()\n if (key === 'dur') {\n const dur = Number(value)\n if (Number.isFinite(dur) && dur >= 0) entry.durMs = dur\n } else if (key === 'desc') {\n entry.desc = value.replace(/^\"|\"$/g, '').slice(0, 120)\n }\n }\n entries.push(entry)\n }\n return entries\n}\n\n/** Flat span attributes for the entries: `server_timing.<name>_ms` for a duration, `server_timing.<name>` for a `desc`. */\nexport function serverTimingAttrs(entries: readonly ServerTimingEntry[]): Record<string, string | number> {\n const out: Record<string, string | number> = {}\n for (const entry of entries.slice(0, 32)) {\n const key = entry.name.replace(/[^\\w]/g, '_')\n if (entry.durMs !== undefined) out[`server_timing.${key}_ms`] = Math.round(entry.durMs * 10) / 10\n else if (entry.desc !== undefined) out[`server_timing.${key}`] = entry.desc\n }\n return out\n}\n\n/** Format entries as a `Server-Timing` header value, the inverse of {@link parseServerTiming}. Invalid names are skipped. */\nexport function formatServerTiming(entries: readonly ServerTimingEntry[]): string {\n return entries\n .filter((entry) => /^[\\w.!#$%&'*+^`|~-]+$/.test(entry.name))\n .slice(0, 32)\n .map((entry) => [\n entry.name,\n ...(entry.durMs === undefined ? [] : [`dur=${Math.round(entry.durMs * 10) / 10}`]),\n ...(entry.desc === undefined ? [] : [`desc=\"${entry.desc.replace(/[\"\\\\]/g, '').slice(0, 120)}\"`]),\n ].join(';'))\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