@theoremjs/studio 0.3.4-next.570.gfda95a3 → 0.3.4-next.586.ga59d695

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.
Files changed (42) hide show
  1. package/package.json +4 -4
  2. package/page/assets/{Banner-CrKy_Hwv.js → Banner-CFm9bIyB.js} +3 -3
  3. package/page/assets/{ConsoleFrame-mZpOKfZP.js → ConsoleFrame-7aueQpBk.js} +1 -1
  4. package/page/assets/{ContextMenu-BAMCFPeG.js → ContextMenu-CR_aIpOa.js} +2 -2
  5. package/page/assets/{MenuBottomSheet-COMdKPyt.js → MenuBottomSheet-DR-P3IOp.js} +1 -1
  6. package/page/assets/{SchemaFields-i5CGKHZw.js → SchemaFields-BSSShndR.js} +1 -1
  7. package/page/assets/{ToolResultCharts-CM0D9rIN.js → ToolResultCharts-XNTR-rKf.js} +1 -1
  8. package/page/assets/{TraceInspector-BZ6XsVv6.js → TraceInspector-BhTdCmvR.js} +1 -1
  9. package/page/assets/{TraceOverview-B3KOSNYV.js → TraceOverview-CI_c-DiT.js} +2 -2
  10. package/page/assets/{browser-connection-D9jsfxnA.js → browser-connection-Dcl-x1Ce.js} +1 -1
  11. package/page/assets/{browser-engine-CG3geEGu.js → browser-engine-DMSIXnYu.js} +1 -1
  12. package/page/assets/{browser-transport-Bh1HRv_X.js → browser-transport-BH6B6Zkz.js} +3 -3
  13. package/page/assets/{export-agent-BXoo4WkX.js → export-agent-CmYyW5-4.js} +1 -1
  14. package/page/assets/{guardrail-tester-BiFjW2iT.js → guardrail-tester-CdrwUkyC.js} +1 -1
  15. package/page/assets/{index-Cy5Fau-l.js → index-BEKLh-Ub.js} +12 -12
  16. package/page/assets/{labels-provider-DkA22zkP.js → labels-provider-C_KY4x6D.js} +1 -1
  17. package/page/assets/{live-messages-Chl3Ye0D.js → live-messages-45H0QP4b.js} +1 -1
  18. package/page/assets/{reader-Cn4QuGp2.js → reader-BdNad_CC.js} +1 -1
  19. package/page/assets/{stub-BMUhx6B5.js → stub-DNTcOSDT.js} +1 -1
  20. package/page/assets/{studio-code-pane-BXowjDUi.js → studio-code-pane-BIK0vzg3.js} +1 -1
  21. package/page/assets/{studio-console-By2ZHfS3.js → studio-console-BsNXj5SF.js} +1 -1
  22. package/page/assets/{studio-decision-CZJiH4yV.js → studio-decision-DGiyQnOB.js} +1 -1
  23. package/page/assets/{studio-embedding-DJ4PyagP.js → studio-embedding-BPgMrZVL.js} +1 -1
  24. package/page/assets/{studio-host-console-Cq_V7aux.js → studio-host-console-Dfy1bPU3.js} +2 -2
  25. package/page/assets/{studio-labels-DFzGkFod.js → studio-labels-DApd4Kwg.js} +1 -1
  26. package/page/assets/{studio-live-DkMUAP67.js → studio-live-DkibEnBn.js} +1 -1
  27. package/page/assets/{studio-map-CWw5Sd6l.js → studio-map-BnfAR2-q.js} +1 -1
  28. package/page/assets/studio-trace-replay-BIxga7Hn.js +2 -0
  29. package/page/assets/{tool-schema-DCF2M0n_.js → tool-schema-Dj__kSmM.js} +7 -7
  30. package/page/assets/{tree-BxJ7bZId.js → tree-Bn3Vp-te.js} +1 -1
  31. package/page/assets/{turn-client-CFuTLOCL.js → turn-client-BuzAnIRe.js} +1 -1
  32. package/page/assets/{use-one-call-BibUH5we.js → use-one-call-z-clj_Ar.js} +1 -1
  33. package/page/assets/{use-second-ticker-DQqJ4pIV.js → use-second-ticker-DDXBXbWC.js} +1 -1
  34. package/page/assets/{workspace-D9otnmy3.js → workspace-DXzbTu-L.js} +1 -1
  35. package/page/index.html +14 -14
  36. package/ui/lib/panel-motion.d.ts +8 -4
  37. package/ui/lib/panel-motion.js +58 -33
  38. package/ui/studio-screen.js +26 -27
  39. package/ui/studio-settings.js +3 -3
  40. package/ui/studio-trace-replay.d.ts +5 -0
  41. package/ui/studio-trace-replay.js +20 -13
  42. package/page/assets/studio-trace-replay-DqWHUnOl.js +0 -2
@@ -262,7 +262,7 @@ function SectionBody({ section, ...props }) {
262
262
  const isSection = (value) => SETTINGS_SECTIONS.includes(value);
263
263
  /** The nav's head, as the studio's tree and the docs head theirs: the name, what is open, then the search. */
264
264
  function SettingsNavHead({ project, version }) {
265
- return (_jsxs(VStack, { gap: 4, children: [_jsxs(VStack, { gap: 1, children: [_jsx(Heading, { level: 3, children: "theorem studio" }), _jsx(Text, { type: "supporting", color: "secondary", children: `${project.name} · @theoremjs/agents ${version}` })] }), _jsx(Typeahead, { label: "Search", isLabelHidden: true, placeholder: "Search settings...", searchSource: settingsSource, value: null, onChange: (item) => {
265
+ return (_jsxs(VStack, { gap: 4, children: [_jsxs(VStack, { gap: 1, className: "studio-nav-head", children: [_jsx(Heading, { level: 3, children: "theorem studio" }), _jsx(Text, { type: "supporting", color: "secondary", children: `${project.name} · @theoremjs/agents ${version}` })] }), _jsx(Typeahead, { label: "Search", isLabelHidden: true, placeholder: "Search settings...", searchSource: settingsSource, value: null, onChange: (item) => {
266
266
  const found = SETTINGS.find((setting) => setting.id === item?.id);
267
267
  if (found)
268
268
  showSettingsSection(found.section);
@@ -274,14 +274,14 @@ const SETTINGS_WIDTH = '72rem';
274
274
  export function StudioSettings(props) {
275
275
  const isNarrow = useMediaQuery('(max-width: 768px)');
276
276
  const { section } = useSettingsDoor();
277
- return (_jsx(Section, { variant: "transparent", height: "100%", padding: 0, children: _jsx(Layout, { height: "fill", start: isNarrow ? undefined : (_jsx(Section, { variant: "transparent", width: NAV_WIDTH, height: "100%", padding: 4, dividers: ['end'], children: _jsxs(VStack, { gap: 4, height: "100%", children: [_jsx(SettingsNavHead, { project: props.project, version: props.version }), _jsx(TreeList, { className: "studio-settings-tree", density: "compact", "aria-label": "Settings", items: SETTINGS_SECTIONS.map((each) => ({
277
+ return (_jsx(Section, { variant: "transparent", height: "100%", padding: 0, className: "studio-settings", children: _jsx(Layout, { height: "fill", start: isNarrow ? undefined : (_jsx(Section, { variant: "transparent", width: NAV_WIDTH, height: "100%", padding: 4, dividers: ['end'], children: _jsxs(VStack, { gap: 4, height: "100%", children: [_jsx(SettingsNavHead, { project: props.project, version: props.version }), _jsx(TreeList, { className: "studio-settings-tree", density: "compact", "aria-label": "Settings", items: SETTINGS_SECTIONS.map((each) => ({
278
278
  id: each,
279
279
  label: SECTION_LABELS[each],
280
280
  isSelected: section === each,
281
281
  onClick: () => {
282
282
  showSettingsSection(each);
283
283
  },
284
- })) })] }) })), content: _jsxs(LayoutContent, { padding: 0, children: [_jsx(Section, { variant: "transparent", padding: 3, dividers: ['bottom'], children: _jsxs(HStack, { gap: 2, vAlign: "center", children: [_jsx(StackItem, { size: "fill", children: _jsx(Heading, { level: 4, maxLines: 1, children: SECTION_LABELS[section] }) }), _jsx(IconButton, { label: "Close settings", variant: "ghost", icon: _jsx(Icon, { icon: IconX, size: "sm" }), tooltip: "Back to the studio", onClick: closeSettings })] }) }), _jsx(Section, { variant: "transparent", padding: 3, maxWidth: SETTINGS_WIDTH, className: "studio-settings-body", children: _jsxs(VStack, { gap: 4, children: [isNarrow && _jsx(SettingsNavHead, { project: props.project, version: props.version }), isNarrow && (_jsx(VStack, { hAlign: "center", children: _jsx(TabList, { value: section, onChange: (next) => {
284
+ })) })] }) })), content: _jsxs(LayoutContent, { padding: 0, className: "studio-settings-main", children: [_jsx(Section, { variant: "transparent", padding: 3, dividers: ['bottom'], children: _jsxs(HStack, { gap: 2, vAlign: "center", children: [_jsx(StackItem, { size: "fill", children: _jsx(Heading, { level: 4, maxLines: 1, children: SECTION_LABELS[section] }) }), _jsx(IconButton, { label: "Close settings", variant: "ghost", icon: _jsx(Icon, { icon: IconX, size: "sm" }), tooltip: "Back to the studio", onClick: closeSettings })] }) }), _jsx(Section, { variant: "transparent", padding: 3, maxWidth: SETTINGS_WIDTH, className: "studio-settings-body", children: _jsxs(VStack, { gap: 4, children: [isNarrow && _jsx(SettingsNavHead, { project: props.project, version: props.version }), isNarrow && (_jsx(VStack, { hAlign: "center", children: _jsx(TabList, { value: section, onChange: (next) => {
285
285
  if (isSection(next))
286
286
  showSettingsSection(next);
287
287
  }, children: SETTINGS_SECTIONS.map((each) => (_jsx(Tab, { value: each, label: SECTION_LABELS[each] }, each))) }) })), _jsx(SectionBody, { section: section, ...props })] }) })] }) }) }));
@@ -18,6 +18,11 @@ export type TraceReplayProps = {
18
18
  trace: boolean | undefined;
19
19
  runtime: StudioBrowserRuntime | null;
20
20
  onLive: (start: LiveStart) => void;
21
+ /** The imported file, held by the page so closing the console does not lose it. */
22
+ opened: OpenedTrace | undefined;
23
+ onOpened: (trace: OpenedTrace) => void;
24
+ /** Lets go of the imported file. */
25
+ onClear: () => void;
21
26
  };
22
27
  /**
23
28
  * The trace console, in the frame a decision and a host use: the trace card, then the
@@ -10,10 +10,15 @@ import { jsxs as _jsxs, jsx as _jsx, Fragment as _Fragment } from "react/jsx-run
10
10
  import { Banner } from '@astryxdesign/core/Banner';
11
11
  import { Button } from '@astryxdesign/core/Button';
12
12
  import { FileInput } from '@astryxdesign/core/FileInput';
13
+ import { HStack } from '@astryxdesign/core/HStack';
14
+ import { Icon } from '@astryxdesign/core/Icon';
15
+ import { IconButton } from '@astryxdesign/core/IconButton';
13
16
  import { SegmentedControl, SegmentedControlItem } from '@astryxdesign/core/SegmentedControl';
17
+ import { StackItem } from '@astryxdesign/core/Stack';
14
18
  import { Switch } from '@astryxdesign/core/Switch';
15
19
  import { Text } from '@astryxdesign/core/Text';
16
20
  import { VStack } from '@astryxdesign/core/VStack';
21
+ import { IconX } from '@tabler/icons-react';
17
22
  import { useTheoremChat } from '@theoremjs/react';
18
23
  import { ChatTranscript, ConsoleFrame, RequestCard, ResponseColumn, RunBar, TheoremLabelsProvider, TheoremThemeProvider, useLabels, useTraceInspector, } from '@theoremjs/react/ui';
19
24
  import { createTraceFeed, recordedFeed, } from '@theoremjs/web/client';
@@ -91,7 +96,7 @@ function TraceFacts({ controls }) {
91
96
  `${String(turns)} ${turns === 1 ? 'turn' : 'turns'}`,
92
97
  recordedAt(script),
93
98
  ];
94
- return (_jsxs(_Fragment, { children: [_jsxs(VStack, { gap: 0, children: [_jsx(Text, { type: "label", maxLines: 1, children: controls.opened.name }), _jsx(Text, { type: "supporting", color: "secondary", maxLines: 1, children: facts.filter(Boolean).join(' · ') })] }), script.agent && script.agent !== payload.profile.id ? (_jsx(Banner, { status: "info", title: `Recorded with ${script.agent}; a replay runs through ${payload.profile.id}.` })) : null, turns === 0 ? (_jsx(Banner, { status: "info", title: "This trace holds no conversation to replay." })) : null, _jsx(Switch, { label: "Live tools", description: "Run the profile's tools instead of answering them from the recording.", value: controls.liveTools, onChange: controls.onLiveTools })] }));
99
+ return (_jsxs(_Fragment, { children: [_jsxs(HStack, { gap: 2, vAlign: "center", children: [_jsx(StackItem, { size: "fill", children: _jsxs(VStack, { gap: 0, children: [_jsx(Text, { type: "label", maxLines: 1, children: controls.opened.name }), _jsx(Text, { type: "supporting", color: "secondary", maxLines: 1, children: facts.filter(Boolean).join(' · ') })] }) }), _jsx(IconButton, { label: "Clear trace", variant: "ghost", size: "sm", icon: _jsx(Icon, { icon: IconX, size: "sm" }), isDisabled: controls.isRunning, onClick: controls.onClear })] }), script.agent && script.agent !== payload.profile.id ? (_jsx(Banner, { status: "info", title: `Recorded with ${script.agent}; a replay runs through ${payload.profile.id}.` })) : null, turns === 0 ? (_jsx(Banner, { status: "info", title: "This trace holds no conversation to replay." })) : null, _jsx(Switch, { label: "Live tools", description: "Run the profile's tools instead of answering them from the recording.", value: controls.liveTools, onChange: controls.onLiveTools })] }));
95
100
  }
96
101
  const idle = () => undefined;
97
102
  /** The trace card: the file, what it recorded, and Replay. */
@@ -221,29 +226,30 @@ function ReplayConsole({ payload, iface, trace, card, opened, script, shown, liv
221
226
  export function TraceReplay(props) {
222
227
  return (_jsx(TheoremThemeProvider, { children: _jsx(TheoremLabelsProvider, { labels: STUDIO_LABELS, children: _jsx(TraceConsole, { ...props }) }) }));
223
228
  }
224
- function TraceConsole({ payload, trace, runtime, onLive }) {
229
+ function TraceConsole({ payload, trace, runtime, onLive, opened, onOpened, onClear, }) {
225
230
  const iface = useMemo(() => studioInterface(payload), [payload]);
226
- const [opened, setOpened] = useState();
227
231
  const script = useMemo(() => opened && replayScript(opened.records), [opened]);
228
232
  const recorded = useMemo(() => recordedFeed(opened?.records ?? []), [opened]);
229
- const [attempt, setAttempt] = useState(0);
230
- const [shown, setShown] = useState('recorded');
233
+ const [ran, setRan] = useState();
231
234
  const [liveTools, setLiveTools] = useState(false);
232
- const imported = (next) => {
233
- setOpened(next);
234
- setAttempt(0);
235
- setShown('recorded');
235
+ // invariant: a replay belongs to the file and the agent it ran; another of either shows the recording.
236
+ const run = ran?.of === opened && ran?.agent === payload.profile.id ? ran : undefined;
237
+ const attempt = run?.attempt ?? 0;
238
+ const shown = run?.shown ?? 'recorded';
239
+ const setShown = (next) => {
240
+ if (run)
241
+ setRan({ ...run, shown: next });
236
242
  };
237
243
  const replayOnce = () => {
238
- setAttempt((count) => count + 1);
239
- setShown('replayed');
244
+ if (opened)
245
+ setRan({ of: opened, agent: payload.profile.id, attempt: attempt + 1, shown: 'replayed' });
240
246
  };
241
247
  // invariant: the header offers an import only for a type whose conversation a trace holds.
242
248
  if (iface.type === 'live')
243
249
  return null;
244
250
  if (!opened || !script)
245
- return (_jsx(TraceFrame, { iface: iface, feed: recorded, trace: trace, card: _jsx(TraceCard, { onImport: imported }), conversation: null }));
246
- const card = ({ isRunning, onStop }) => (_jsx(TraceCard, { onImport: imported, controls: {
251
+ return (_jsx(TraceFrame, { iface: iface, feed: recorded, trace: trace, card: _jsx(TraceCard, { onImport: onOpened }), conversation: null }));
252
+ const card = ({ isRunning, onStop }) => (_jsx(TraceCard, { onImport: onOpened, controls: {
247
253
  opened,
248
254
  script,
249
255
  payload,
@@ -258,6 +264,7 @@ function TraceConsole({ payload, trace, runtime, onLive }) {
258
264
  isRunning,
259
265
  onReplay: replayOnce,
260
266
  onStop,
267
+ onClear,
261
268
  } }));
262
269
  if (attempt === 0)
263
270
  return (_jsx(TraceFrame, { iface: iface, feed: recorded, trace: trace, card: card({ isRunning: false, onStop: () => undefined }), conversation: _jsx(Conversation, { iface: iface, blocks: recordedTranscript(script) }) }));
@@ -1,2 +0,0 @@
1
- import{r as e}from"./rolldown-runtime-hePW80VL.js";import{c as t,u as n}from"./themeProps-3IqahpCr.js";import{n as r,t as i}from"./SegmentedControlItem-BBGRPrxp.js";import{t as a}from"./VStack-CkVMcNiK.js";import{D as o,E as s,a as c,b as l,o as u,s as d,y as f}from"./browser-transport-Bh1HRv_X.js";import{t as p}from"./Text-BOqCfzZC.js";import{n as m,t as h}from"./labels-provider-DkA22zkP.js";import{n as g}from"./IconButton-DVUFx-8p.js";import{a as _,t as v}from"./Banner-CrKy_Hwv.js";import{t as y,v as ee}from"./studio-labels-DFzGkFod.js";import{c as b}from"./host-patterns-F-KZIzkF.js";import{w as x}from"./shaped-data-AVV4e7rW.js";import{n as S}from"./trace-record-Dtrz7WQ7.js";import{n as C}from"./trace-schema-9CdEyG6Q.js";import{_ as w}from"./turn-client-CFuTLOCL.js";import{a as T,i as E,o as D,t as O}from"./ConsoleFrame-mZpOKfZP.js";import{S as te,a as k,b as ne,h as re,y as ie}from"./index-Cy5Fau-l.js";var A=e=>typeof e==`object`&&!!e&&!Array.isArray(e),j=(e,t)=>e.attributes[t],M=(e,t)=>{let n=j(e,t);return typeof n==`string`?n:void 0};function N(e,t,n){let r=j(t,n);return r===void 0?void 0:S(e,r)}function P(e,t,n){let r=N(e,t,n);return r===void 0?``:typeof r==`string`?r:JSON.stringify(r)}function F(e,t,n){let r=N(e,t,n);return Array.isArray(r)?r.filter(A):[]}var I=e=>Array.isArray(e.parts)?e.parts.filter(A):[],L=e=>BigInt(String(e.startTimeUnixNano)),R=(e,t)=>{let n=L(e)-L(t);return n===0n?0:n<0n?-1:1};function z(e){let t=e.endTimeUnixNano;if(!t)return;let n=L(e),r=BigInt(String(t));if(r<=n)return;let i=Number(n/1000000n),a=Number(r/1000000n);if(!(!Number.isFinite(i)||!Number.isFinite(a)||a<=i))return{startedAt:i,endedAt:a}}function ae(e){let t=z(e);if(t)return{workedMs:t.endedAt-t.startedAt,endedAt:t.endedAt}}function oe(e,t){let n=ae(t);if(!n)return e;let r=e.findLastIndex(e=>e.kind===`turn-done`);return r<0?e:e.map((e,t)=>t===r?{...e,...n}:e)}var se=e=>`content_sha256`in e||`json_sha256`in e;function B(e){let t=e.arguments;if(A(t))return t;if(typeof t!=`string`)return{};try{let e=JSON.parse(t);return A(e)?e:{}}catch{return{}}}function V(e){if(typeof e.content==`string`){if(e.type===`reasoning`)return{type:`thought`,text:e.content};if(e.type===`text`)return{type:`text`,text:e.content}}}function ce(e){let t=[],n=[],r=!1;for(let i of e){let e=I(i),a=e.some(e=>e.type===`text`);for(let i of e){let e=V(i);se(i)?r=!0:e?t.push(e):i.type===`structured`&&!a?t.push({type:`text`,text:JSON.stringify(i.content)}):i.type===`tool_call`&&typeof i.name==`string`?(n.push(i.name),t.push({type:`tool`,tool:{name:i.name,callId:typeof i.id==`string`?i.id:`replay-${String(n.length)}`,arguments:B(i)}})):(i.type===`blob`||i.type===`uri`)&&(r=!0)}}return{events:t,calls:n,missing:r}}function le(e,t){for(let n=e;n;n=t.get(n.parentSpanId??``)){let e=M(n,`gen_ai.agent.name`);if(M(n,`gen_ai.operation.name`)===`invoke_agent`&&e)return e}return``}var H=e=>M(e,`gen_ai.operation.name`);function ue(e){let t=new Map(e.spans.map(e=>[e.spanId,e]));return e.spans.filter(e=>H(e)===`chat`).toSorted(R).map(n=>{let r=ce(F(e,n,`gen_ai.output.messages`)),i=M(n,`theorem.stop.kind`)??`completed`;return{agent:le(n,t),...r,events:[...r.events,{type:`done`,stop:{kind:i}}]}})}function de(e){return e.spans.filter(e=>H(e)===`execute_tool`).toSorted(R).map(t=>({name:M(t,`gen_ai.tool.name`)??``,result:P(e,t,`gen_ai.tool.call.result`),failed:M(t,`theorem.tool.outcome`)===`error`}))}function fe(e,t){let n=F(e,t,`gen_ai.input.messages`).findLast(e=>e.role===`user`),r=n?I(n):[];return{text:r.flatMap(e=>e.type===`text`&&typeof e.content==`string`?[e.content]:[]).join(`
2
- `),attachments:r.filter(e=>e.type===`blob`||e.type===`uri`).length}}function pe(e,t){let n=[];for(let r of t.events??[]){if(r.name!==`theorem.grounding`)continue;let i=r.attributes.sources;if(i===void 0)continue;let a=S(e,i);if(!Array.isArray(a))continue;let o=[];for(let e of a)A(e)&&typeof e.title==`string`&&typeof e.uri==`string`&&o.push({title:e.title,uri:e.uri,type:e.type===`maps`?`maps`:`web`,...typeof e.placeId==`string`?{placeId:e.placeId}:{}});if(o.length){let e=M(t,`gen_ai.tool.call.id`);n.push({type:`citation`,sources:o,...e?{callId:e}:{}})}}return n}function me(e,t){let n=e.spans.filter(e=>H(e)===`execute_tool`).toSorted(R),r=new Set,i=(e,t)=>{let i=n.find(t=>M(t,`gen_ai.tool.call.id`)===e)??n.find(e=>!r.has(e)&&M(e,`gen_ai.tool.name`)===t);return i&&r.add(i),i},a=[];for(let n of F(e,t,`gen_ai.output.messages`))for(let t of I(n)){let n=V(t);if(n)a.push(n);else if(t.type===`structured`&&t.content!==void 0)a.push({type:`structured`,structured:t.content});else if(t.type===`tool_call`&&typeof t.name==`string`){let n=typeof t.id==`string`?t.id:`call-${String(a.length)}`;a.push(...U(e,t.name,n,B(t),i))}}let o=P(e,t,`theorem.error.public`);t.status.code===`ERROR`&&a.push({type:`error`,errorKind:`internal`,error:o||t.status.message});let s=M(t,`theorem.stop.kind`)??`completed`;return a.push({type:`done`,stop:{kind:s}}),a}function U(e,t,n,r,i){let a=i(n,t),o={type:`tool`,tool:{name:t,callId:n,arguments:r}};if(!a)return[o];let s=z(a),c=s?.startedAt??Number(L(a)/1000000n),l=s?.endedAt??c,u=P(e,a,`gen_ai.tool.call.result`),d=M(a,`theorem.tool.outcome`)===`error`?{phase:`error`,failure:{code:M(a,`theorem.tool.failure.code`)??`failed`,kind:`internal`,message:u},readBack:u}:{phase:`complete`,output:W(u),readBack:u};return[o,{type:`tool`,tool:{name:t,callId:n,phase:`running`,at:c}},{type:`tool`,tool:{name:t,callId:n,at:l,...d}},...pe(e,a)]}function W(e){try{return JSON.parse(e)}catch{return e}}function he(e){let t=``,n,r=[];return e.forEach((e,i)=>{let a=x(e);if(!a||H(a)!==`invoke_agent`)return;let o=M(a,`gen_ai.agent.name`)??``;t||=o;let s=ue(e),c=de(e),l=r.at(-1);if(o!==t&&l){l.calls.push(...s),l.results.push(...c);return}n??=Number(L(a)/1000000n);let u=fe(e,a);r.push({...u,calls:s,results:c,blocks:oe(w({text:u.text},me(e,a),{idPrefix:`recorded-${String(i)}`}),a)})}),{agent:t,turns:r,...n===void 0?{}:{recordedAt:n}}}function ge(e){if(e.failed)throw Error(e.result);let t=W(e.result);return A(t)?t:{result:t}}var _e=e=>{let t=e%100,n=t>=11&&t<=13?`th`:{1:`st`,2:`nd`,3:`rd`}[e%10]??`th`;return`${String(e)}${n}`};function ve(e,t,n){if(!e)return`The profile asked the model a ${_e(t+1)} time this turn; the recording answered ${String(t)}.`;if(e.missing)return`The recording does not hold all of this reply.`;let r=new Set((n.wireTools??[]).map(e=>e.name)),i=e.calls.find(e=>!r.has(e));return i&&`The recording calls ${i}, which the profile no longer offers.`}function ye(e,t,n){let r=0,i=new Map,a=new Map,o=t=>{let n=a.get(t);if(!n){n=new Map;for(let r of e.turns[t]?.results??[])n.set(r.name,[...n.get(r.name)??[],r]);a.set(t,n)}return n},s=t=>({async*complete(a){let o=e.turns[r]?.calls.filter(e=>e.agent===t)??[],s=`${String(r)} ${t}`,c=i.get(s)??0;i.set(s,c+1);let l=ve(o[c],o.length,a);if(l)throw n({turn:r,call:c+1,reason:l}),new b(`request`,`Replay stopped: ${l}`);yield*o[c]?.events??[]}}),c=e=>()=>{let t=o(r).get(e)?.shift();if(!t)throw Error(`The recording has no further result for ${e}.`);return ge(t)},l=new Set(e.turns.flatMap(e=>e.results.map(e=>e.name)));return{provider:n=>s(n.id===t?e.agent:n.id),toolHandlers:Object.fromEntries([...l].map(e=>[e,c(e)])),startTurn:e=>{r=e}}}function G(e){return e.map(e=>{if(e.type===`agent`)return e;let{name:t,description:n,category:r,access:i,permission:a,loadTier:o,paths:s}=e;return{type:`function`,name:t,description:n,category:r,access:i,permission:a,loadTier:o,paths:s,inputSchema:e.inputSchema,outputSchema:e.outputSchema,...e.labels?{labels:e.labels}:{}}})}function be(e){return{...e,customTools:G(e.customTools),...e.dependencies?{dependencies:e.dependencies.map(e=>({...e,customTools:G(e.customTools)}))}:{}}}function K(e){return e.turns.flatMap(e=>e.blocks)}function xe(e){let t=Array.isArray(e)?e:[e];return t.map((e,n)=>{let r=C.safeParse(e);if(r.success)return r.data;let i=t.length>1?` (record ${String(n+1)})`:``;throw new b(`request`,`This file is not a Theorem trace${i}.`)})}function Se(e){let t;try{t=JSON.parse(e)}catch{throw new b(`request`,`This file is not JSON.`)}return xe(t)}var q=e(n(),1),J=t();function Ce(e,t,n){return t?u(e,t,{conversationKey:k(),blocks:n}):f(e,n)}var Y=e=>`turn ${String(e+1)}`;function X({iface:e,feed:t,trace:n,card:r,conversation:i}){let a=_(e,t,n);return(0,J.jsxs)(O,{inspector:a,maxWidth:`960px`,requestLabel:`Trace`,children:[r,i]})}function Z({iface:e,blocks:t,banner:n,chat:r}){let i=m();return(0,J.jsxs)(T,{label:`Conversation`,children:[n,(0,J.jsx)(te,{blocks:t,handle:i(`@theorem.agent.handle`,{handle:e.identity.handle}),labels:e.labels,streaming:r?.streaming,delivery:r?.delivery,answering:r?.answering,onToolDecision:r&&((e,t)=>{r.handleToolDecision(e,t)}),onAuthenticated:r&&((e,t)=>{r.handleAuthenticated(e,t)})})]})}function we({onImport:e}){let[t,n]=(0,q.useState)(),[r,i]=(0,q.useState)(!1);return(0,J.jsxs)(a,{gap:2,children:[(0,J.jsx)(ne,{label:`Trace file`,isLabelHidden:!0,mode:`dropzone`,accept:`application/json,.json`,isLoading:r,placeholder:`Drop a trace (.json) or choose a file`,value:null,changeAction:async t=>{let r=Array.isArray(t)?t[0]:t;if(r){i(!0);try{e({name:r.name,records:Se(await r.text())}),n(void 0)}catch(e){n(e instanceof Error?e.message:String(e))}finally{i(!1)}}},onChange:()=>void 0}),t?(0,J.jsx)(v,{status:`error`,title:t}):null]})}var Te=e=>e.recordedAt===void 0?void 0:new Intl.DateTimeFormat(void 0,{dateStyle:`medium`,timeStyle:`short`}).format(e.recordedAt);function Ee({shown:e,onShown:t}){return(0,J.jsxs)(r,{label:`Show`,size:`sm`,value:e,onChange:e=>{t(e===`replayed`?`replayed`:`recorded`)},children:[(0,J.jsx)(i,{value:`recorded`,label:`Recorded`}),(0,J.jsx)(i,{value:`replayed`,label:`Replayed`})]})}function De({controls:e}){let{script:t,payload:n}=e,r=t.turns.length,i=[t.agent||`No agent`,`${String(r)} ${r===1?`turn`:`turns`}`,Te(t)];return(0,J.jsxs)(J.Fragment,{children:[(0,J.jsxs)(a,{gap:0,children:[(0,J.jsx)(p,{type:`label`,maxLines:1,children:e.opened.name}),(0,J.jsx)(p,{type:`supporting`,color:`secondary`,maxLines:1,children:i.filter(Boolean).join(` · `)})]}),t.agent&&t.agent!==n.profile.id?(0,J.jsx)(v,{status:`info`,title:`Recorded with ${t.agent}; a replay runs through ${n.profile.id}.`}):null,r===0?(0,J.jsx)(v,{status:`info`,title:`This trace holds no conversation to replay.`}):null,(0,J.jsx)(ie,{label:`Live tools`,description:`Run the profile's tools instead of answering them from the recording.`,value:e.liveTools,onChange:e.onLiveTools})]})}var Q=()=>void 0;function $({onImport:e,controls:t}){let n=t?.onReplay??Q;return(0,J.jsxs)(E,{title:`Trace`,onRun:n,actions:t?.shown?(0,J.jsx)(Ee,{shown:t.shown,onShown:t.onShown}):null,children:[(0,J.jsx)(we,{onImport:e}),t?(0,J.jsx)(De,{controls:t}):null,(0,J.jsx)(D,{note:t?`Answers each model call from the recording, so it needs no keys.`:null,isReady:(t?.script.turns.length??0)>0,isRunning:t?.isRunning??!1,runLabel:t?.shown?`Replay again`:`Replay`,runningLabel:`Replaying`,stopLabel:`Stop`,onRun:n,onStop:t?.onStop??Q})]})}function Oe({status:e,turns:t,onContinue:n,onLive:r}){let[i,o]=(0,q.useState)(!1),[s,c]=(0,q.useState)(),l=e=>(0,J.jsx)(g,{label:`Continue live`,variant:`secondary`,size:`sm`,isLoading:i,onClick:async()=>{o(!0),c(void 0);try{await r(e)}catch(e){c(e instanceof Error?e.message:String(e)),o(!1)}}}),u=(()=>{switch(e.kind){case`running`:return(0,J.jsx)(v,{status:`info`,title:`Replaying ${Y(e.turn)} of ${String(t)}`});case`waiting`:return(0,J.jsx)(v,{status:`info`,title:`${Y(e.turn-1)} waits on you`,description:`Answer it in the conversation, then continue the replay.`,endContent:(0,J.jsx)(g,{label:`Continue replay`,variant:`secondary`,size:`sm`,onClick:()=>{n(e.turn)}})});case`missing`:return(0,J.jsx)(v,{status:`warning`,title:`Replay stopped before ${Y(e.turn)}`,description:`It was sent with files, and a trace never holds a file's bytes. Continue live to send it again with yours.`,endContent:l(e.turn)});case`diverged`:{let{turn:t,call:n,reason:r}=e.divergence;return(0,J.jsx)(v,{status:`warning`,title:`Replay stopped at ${Y(t)}, model call ${String(n)}`,description:r,endContent:l(t)})}case`failed`:return(0,J.jsx)(v,{status:`error`,title:`Replay stopped at ${Y(e.turn)}`,description:e.message,endContent:l(e.turn)});case`done`:return(0,J.jsx)(v,{status:`success`,title:`Replayed ${String(t)} ${t===1?`turn`:`turns`}`,description:`Every model call this profile made was one the recording answered.`})}})();return(0,J.jsxs)(a,{gap:1,children:[u,s?(0,J.jsx)(v,{status:`error`,title:s}):null]})}function ke({payload:e,iface:t,trace:n,card:r,opened:i,script:a,shown:l,liveTools:u,runtime:d,onLive:f}){let p=(0,q.useRef)(void 0),[m,h]=(0,q.useState)({kind:`running`,turn:0}),[g]=(0,q.useState)(s),_=(0,q.useMemo)(()=>o(i.records),[i.records]),v=(0,q.useMemo)(()=>ye(a,e.profile.id,e=>{p.current??=e}),[a,e.profile.id]),y=(0,q.useMemo)(()=>c(u?e:be(e),{mode:`byok`,provider:v.provider,...u?{}:{toolHandlers:v.toolHandlers}},{conversationKey:k(),traces:g}),[e,v,u,g]),b=(0,q.useMemo)(()=>u?ee(e):void 0,[u,e]),x=re({transport:y,iface:t,pageTools:b}),{sendText:S,handleStop:C}=x,w=(0,q.useRef)(x.phase);w.current=x.phase;let[T,E]=(0,q.useState)(0);(0,q.useEffect)(()=>{let e=!1,t=async()=>{for(;!e&&w.current===`streaming`;)await new Promise(e=>requestAnimationFrame(e))};return(async()=>{for(let n=T;n<a.turns.length;n+=1){if(await t(),e)return;if(w.current===`gated`)return v.startTurn(n-1),h({kind:`waiting`,turn:n});let{text:r,attachments:i}=a.turns[n];if(i>0)return h({kind:`missing`,turn:n});v.startTurn(n),h({kind:`running`,turn:n});try{let t=await S(r);if(e)return;if(p.current)return h({kind:`diverged`,divergence:p.current});t||--n}catch(e){let t=e instanceof Error?e.message:String(e);return h({kind:`failed`,turn:n,message:t})}}h({kind:`done`})})(),()=>{e=!0,C()}},[T,v,a,S,C]);let D=async t=>{f({...await Ce(e,d,a.turns.slice(0,t).flatMap(e=>e.blocks)),text:a.turns[t]?.text??``})},O=l===`replayed`;return(0,J.jsx)(X,{iface:t,feed:O?g:_,trace:n,card:r({isRunning:m.kind===`running`,onStop:()=>{C(),h({kind:`done`})}}),conversation:(0,J.jsx)(Z,{iface:t,blocks:O?[...x.blocks,...x.streamBlocks]:K(a),chat:O?x:void 0,banner:O?(0,J.jsx)(Oe,{status:m,turns:a.turns.length,onContinue:E,onLive:D}):void 0})})}function Ae(e){return(0,J.jsx)(d,{children:(0,J.jsx)(h,{labels:y,children:(0,J.jsx)(je,{...e})})})}function je({payload:e,trace:t,runtime:n,onLive:r}){let i=(0,q.useMemo)(()=>l(e),[e]),[a,s]=(0,q.useState)(),c=(0,q.useMemo)(()=>a&&he(a.records),[a]),u=(0,q.useMemo)(()=>o(a?.records??[]),[a]),[d,f]=(0,q.useState)(0),[p,m]=(0,q.useState)(`recorded`),[h,g]=(0,q.useState)(!1),_=e=>{s(e),f(0),m(`recorded`)},v=()=>{f(e=>e+1),m(`replayed`)};if(i.type===`live`)return null;if(!a||!c)return(0,J.jsx)(X,{iface:i,feed:u,trace:t,card:(0,J.jsx)($,{onImport:_}),conversation:null});let y=({isRunning:t,onStop:n})=>(0,J.jsx)($,{onImport:_,controls:{opened:a,script:c,payload:e,shown:d>0?p:null,onShown:m,liveTools:h,onLiveTools:e=>{g(e),d>0&&v()},isRunning:t,onReplay:v,onStop:n}});return d===0?(0,J.jsx)(X,{iface:i,feed:u,trace:t,card:y({isRunning:!1,onStop:()=>void 0}),conversation:(0,J.jsx)(Z,{iface:i,blocks:K(c)})}):(0,J.jsx)(ke,{payload:e,iface:i,trace:t,card:y,opened:a,script:c,shown:p,liveTools:h,runtime:n,onLive:r},d)}export{Ae as TraceReplay};