@contractspec/example.agent-console 3.8.16 → 3.8.18

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.
@@ -1,5 +1,5 @@
1
- import{defineVisualization as d0,VisualizationRegistry as W1}from"@contractspec/lib.contracts-spec/visualizations";var G0={key:"agent.run.list",version:"1.0.0"},O0={version:"1.0.0",domain:"ai-ops",stability:"experimental",owners:["@example.agent-console"],tags:["agent-console","visualization","operations"]},J0=d0({meta:{...O0,key:"agent-console.visualization.run-status",title:"Run Status Breakdown",description:"Distribution of run outcomes across the current sample.",goal:"Make operational success and failure mix visible at a glance.",context:"Agent operations overview."},source:{primary:G0,resultPath:"data"},visualization:{kind:"pie",nameDimension:"status",valueMeasure:"runs",dimensions:[{key:"status",label:"Status",dataPath:"status",type:"category"}],measures:[{key:"runs",label:"Runs",dataPath:"runs",format:"number"}],table:{caption:"Run counts by status."}}}),W0=d0({meta:{...O0,key:"agent-console.visualization.run-activity",title:"Recent Run Activity",description:"Daily run volume across the current sample.",goal:"Show whether agent activity is rising or slowing down.",context:"Operations trend monitoring."},source:{primary:G0,resultPath:"data"},visualization:{kind:"cartesian",variant:"line",xDimension:"day",yMeasures:["runs"],dimensions:[{key:"day",label:"Day",dataPath:"day",type:"time"}],measures:[{key:"runs",label:"Runs",dataPath:"runs",format:"number",color:"#0f766e"}],table:{caption:"Daily run counts."}}}),F0=d0({meta:{...O0,key:"agent-console.visualization.run-efficiency",title:"Duration vs Tokens",description:"Scatter chart comparing token consumption and runtime.",goal:"Reveal outlier runs that are slow relative to their token usage.",context:"Operational performance diagnostics."},source:{primary:G0,resultPath:"data"},visualization:{kind:"cartesian",variant:"scatter",xDimension:"totalTokens",yMeasures:["durationMs"],dimensions:[{key:"totalTokens",label:"Total Tokens",dataPath:"totalTokens",type:"number"}],measures:[{key:"durationMs",label:"Duration",dataPath:"durationMs",format:"duration",color:"#7c3aed"},{key:"estimatedCostUsd",label:"Cost",dataPath:"estimatedCostUsd",format:"currency"}],series:[{key:"runs",label:"Runs",measure:"durationMs",type:"scatter",color:"#7c3aed"}],table:{caption:"Run duration versus token usage."}}}),g0=[J0,W0,F0],Nf=new W1([...g0]),yf=g0.map((f)=>({key:f.meta.key,version:f.meta.version}));function l0(f){if(!f)return"unknown";return f.toISOString().slice(0,10)}function c(f){let p=new Map,q=new Map;for(let m of f)p.set(m.status,(p.get(m.status)??0)+1),q.set(l0(m.startedAt??m.queuedAt),(q.get(l0(m.startedAt??m.queuedAt))??0)+1);return[{key:"run-status",spec:J0,data:{data:Array.from(p.entries()).map(([m,Z])=>({status:m,runs:Z}))},title:"Run Status Breakdown",description:"Completed, failed, running, and cancelled runs in the sample.",height:260},{key:"run-activity",spec:W0,data:{data:Array.from(q.entries()).sort(([m],[Z])=>m.localeCompare(Z)).map(([m,Z])=>({day:m,runs:Z}))},title:"Recent Run Activity",description:"Daily run volume derived from run start times."},{key:"run-efficiency",spec:F0,data:{data:f.filter((m)=>typeof m.durationMs==="number").map((m)=>({totalTokens:m.totalTokens,durationMs:m.durationMs??0,estimatedCostUsd:m.estimatedCostUsd}))},title:"Duration vs Tokens",description:"Operational scatter plot for spotting inefficient runs."}]}var s=[{id:"agent-1",organizationId:"demo-org",name:"Customer Support Bot",slug:"customer-support-bot",description:"Handles tier-1 customer inquiries and routes complex issues.",status:"ACTIVE",modelProvider:"OPENAI",modelName:"gpt-4o-mini",modelConfig:{temperature:0.7},systemPrompt:"You are a helpful customer support assistant.",toolChoice:"auto",maxIterations:10,timeoutMs:120000,version:"1.0.0",tags:["support","tier-1"],createdAt:new Date("2024-01-15T10:00:00Z"),updatedAt:new Date("2024-03-20T14:30:00Z")},{id:"agent-2",organizationId:"demo-org",name:"Code Review Assistant",slug:"code-review-assistant",description:"Reviews pull requests and provides actionable feedback.",status:"ACTIVE",modelProvider:"ANTHROPIC",modelName:"claude-sonnet-4-20250514",modelConfig:{temperature:0.3},systemPrompt:"You are a code review expert.",toolChoice:"auto",maxIterations:15,timeoutMs:180000,version:"2.1.0",tags:["code","review","dev"],createdAt:new Date("2024-02-10T09:00:00Z"),updatedAt:new Date("2024-04-05T11:15:00Z")},{id:"agent-3",organizationId:"demo-org",name:"Data Analyst",slug:"data-analyst",description:"Queries databases and generates insights from data.",status:"PAUSED",modelProvider:"OPENAI",modelName:"gpt-4o",modelConfig:{temperature:0.5},systemPrompt:"You are a data analyst expert in SQL and analytics.",toolChoice:"required",maxIterations:20,timeoutMs:300000,version:"1.2.0",tags:["data","analytics","sql"],createdAt:new Date("2024-03-01T08:00:00Z"),updatedAt:new Date("2024-04-10T16:45:00Z")},{id:"agent-4",organizationId:"demo-org",name:"Meeting Scheduler",slug:"meeting-scheduler",description:"Schedules meetings and manages calendar conflicts.",status:"DRAFT",modelProvider:"GOOGLE",modelName:"gemini-2.0-flash",modelConfig:{temperature:0.2},systemPrompt:"You help schedule and organize meetings efficiently.",toolChoice:"auto",maxIterations:5,timeoutMs:60000,version:"0.1.0",tags:["calendar","scheduling"],createdAt:new Date("2024-04-01T12:00:00Z"),updatedAt:new Date("2024-04-01T12:00:00Z")}];var f0=[{id:"tool-1",organizationId:"demo-org",name:"Web Search",slug:"web-search",description:"Search the web for real-time information using Brave API.",category:"RETRIEVAL",status:"ACTIVE",parametersSchema:{type:"object",properties:{query:{type:"string",description:"Search query"},numResults:{type:"number",default:10}},required:["query"]},outputSchema:{type:"array",items:{type:"object"}},implementationType:"http",implementationConfig:{url:"https://api.brave.com/search",method:"GET"},maxInvocationsPerMinute:60,timeoutMs:30000,version:"1.0.0",tags:["search","web"],createdAt:new Date("2024-01-01T00:00:00Z"),updatedAt:new Date("2024-02-15T10:00:00Z")},{id:"tool-2",organizationId:"demo-org",name:"SQL Query",slug:"sql-query",description:"Execute read-only SQL queries against the data warehouse.",category:"RETRIEVAL",status:"ACTIVE",parametersSchema:{type:"object",properties:{query:{type:"string",description:"SQL query"},maxRows:{type:"number",default:100}},required:["query"]},outputSchema:{type:"object"},implementationType:"function",implementationConfig:{handler:"executeSqlQuery"},maxInvocationsPerMinute:30,timeoutMs:60000,version:"1.1.0",tags:["sql","database"],createdAt:new Date("2024-01-05T00:00:00Z"),updatedAt:new Date("2024-03-10T14:00:00Z")},{id:"tool-3",organizationId:"demo-org",name:"Email Sender",slug:"email-sender",description:"Send emails via SMTP or API.",category:"COMMUNICATION",status:"ACTIVE",parametersSchema:{type:"object",properties:{to:{type:"string"},subject:{type:"string"},body:{type:"string"}},required:["to","subject","body"]},implementationType:"http",implementationConfig:{url:"/api/send-email",method:"POST"},maxInvocationsPerMinute:10,timeoutMs:30000,version:"1.0.0",tags:["email","communication"],createdAt:new Date("2024-02-01T00:00:00Z"),updatedAt:new Date("2024-02-01T00:00:00Z")},{id:"tool-4",organizationId:"demo-org",name:"GitHub Integration",slug:"github-integration",description:"Interact with GitHub repositories, PRs, and issues.",category:"INTEGRATION",status:"ACTIVE",parametersSchema:{type:"object",properties:{action:{type:"string",enum:["list_prs","get_pr","create_comment"]},repo:{type:"string"},params:{type:"object"}},required:["action","repo"]},implementationType:"http",implementationConfig:{url:"https://api.github.com",auth:"token"},maxInvocationsPerMinute:100,timeoutMs:15000,version:"2.0.0",tags:["github","integration","code"],createdAt:new Date("2024-02-20T00:00:00Z"),updatedAt:new Date("2024-04-01T09:00:00Z")},{id:"tool-5",organizationId:"demo-org",name:"Calculator",slug:"calculator",description:"Perform mathematical calculations.",category:"COMPUTATION",status:"ACTIVE",parametersSchema:{type:"object",properties:{expression:{type:"string",description:"Math expression to evaluate"}},required:["expression"]},outputSchema:{type:"object",properties:{result:{type:"number"}}},implementationType:"function",implementationConfig:{handler:"evaluateMath"},timeoutMs:5000,version:"1.0.0",tags:["math","utility"],createdAt:new Date("2024-01-10T00:00:00Z"),updatedAt:new Date("2024-01-10T00:00:00Z")}];var p0=[{id:"run-1",organizationId:"demo-org",projectId:"demo-project",agentId:"agent-1",agentName:"Customer Support Bot",userId:"user-1",sessionId:"session-1",input:{message:"How do I reset my password?",context:{}},output:{response:"You can reset your password by clicking..."},status:"COMPLETED",totalTokens:1250,promptTokens:800,completionTokens:450,totalIterations:3,durationMs:4500,estimatedCostUsd:0.0025,queuedAt:new Date("2024-04-15T10:00:00Z"),startedAt:new Date("2024-04-15T10:00:01Z"),completedAt:new Date("2024-04-15T10:00:05Z"),steps:[],logs:[]},{id:"run-2",organizationId:"demo-org",projectId:"demo-project",agentId:"agent-2",agentName:"Code Review Assistant",userId:"user-2",input:{message:"Review PR #123",context:{prNumber:123}},status:"IN_PROGRESS",totalTokens:3500,promptTokens:3000,completionTokens:500,totalIterations:5,queuedAt:new Date("2024-04-15T10:30:00Z"),startedAt:new Date("2024-04-15T10:30:02Z"),steps:[],logs:[]},{id:"run-3",organizationId:"demo-org",projectId:"demo-project",agentId:"agent-1",agentName:"Customer Support Bot",userId:"user-1",input:{message:"What are your business hours?"},output:{response:"Our business hours are 9 AM to 5 PM EST..."},status:"COMPLETED",totalTokens:800,promptTokens:500,completionTokens:300,totalIterations:2,durationMs:2100,estimatedCostUsd:0.0012,queuedAt:new Date("2024-04-15T09:00:00Z"),startedAt:new Date("2024-04-15T09:00:01Z"),completedAt:new Date("2024-04-15T09:00:03Z"),steps:[],logs:[]},{id:"run-4",organizationId:"demo-org",projectId:"demo-project",agentId:"agent-3",agentName:"Data Analyst",userId:"user-3",input:{message:"Generate sales report for Q1"},status:"FAILED",errorMessage:"Database connection timeout",errorCode:"DB_TIMEOUT",totalTokens:2000,promptTokens:1500,completionTokens:500,totalIterations:8,durationMs:45000,queuedAt:new Date("2024-04-14T15:00:00Z"),startedAt:new Date("2024-04-14T15:00:05Z"),completedAt:new Date("2024-04-14T15:00:50Z"),steps:[],logs:[]},{id:"run-5",organizationId:"demo-org",projectId:"demo-project",agentId:"agent-2",agentName:"Code Review Assistant",userId:"user-2",input:{message:"Review PR #120"},output:{response:"Code review complete. 3 suggestions..."},status:"COMPLETED",totalTokens:5200,promptTokens:4000,completionTokens:1200,totalIterations:7,durationMs:15000,estimatedCostUsd:0.0156,queuedAt:new Date("2024-04-14T11:00:00Z"),startedAt:new Date("2024-04-14T11:00:03Z"),completedAt:new Date("2024-04-14T11:00:18Z"),steps:[],logs:[]}];var n0=[{id:"runs",label:"Runs",icon:"▶"},{id:"agents",label:"Agents",icon:"\uD83E\uDD16"},{id:"tools",label:"Tools",icon:"\uD83D\uDD27"},{id:"metrics",label:"Metrics",icon:"\uD83D\uDCCA"}];function j0(f){let p=f.filter((M)=>M.status==="COMPLETED").length,q=f.reduce((M,w)=>M+w.totalTokens,0),m=f.reduce((M,w)=>M+(w.estimatedCostUsd??0),0),Z=f.map((M)=>M.durationMs).filter((M)=>typeof M==="number");return{averageDurationMs:Z.length>0?Z.reduce((M,w)=>M+w,0)/Z.length:0,completedRuns:p,successRate:f.length>0?p/f.length:0,totalCostUsd:m,totalRuns:f.length,totalTokens:q}}function m0(f){if(f<1000)return f.toString();if(f<1e6)return`${(f/1000).toFixed(1)}K`;return`${(f/1e6).toFixed(2)}M`}function e0(f){if(!f)return"-";if(f<1000)return`${f}ms`;if(f<60000)return`${(f/1000).toFixed(1)}s`;return`${(f/60000).toFixed(1)}m`}function x0(f){return new Intl.DateTimeFormat("en-US",{dateStyle:"medium",timeStyle:"short"}).format(f)}function X0(f){if(typeof document>"u")return{onPress:f};return{onClick:f}}import{Badge as F1}from"@contractspec/lib.ui-kit-web/ui/badge";import{Card as w0,CardContent as Z0,CardHeader as X1,CardTitle as h1}from"@contractspec/lib.ui-kit-web/ui/card";import{HStack as h0,VStack as j}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as _}from"@contractspec/lib.ui-kit-web/ui/text";import{jsx as J,jsxs as h}from"react/jsx-runtime";function a0({metrics:f}){let p=[{label:"Total Runs",value:String(f.totalRuns),hint:`${Math.round(f.successRate*100)}% success`},{label:"Success Rate",value:`${Math.round(f.successRate*100)}%`,hint:"of all runs"},{label:"Total Tokens",value:m0(f.totalTokens),hint:"This period"},{label:"Total Cost",value:`$${f.totalCostUsd.toFixed(2)}`,hint:"This period"}];return J(h0,{gap:"md",className:"flex-wrap",children:p.map((q)=>J(w0,{className:"min-w-52 flex-1",children:h(Z0,{className:"flex flex-col gap-1 pt-6",children:[J(_,{className:"text-muted-foreground text-sm",children:q.label}),J(_,{className:"font-bold text-2xl",children:q.value}),J(_,{className:"text-muted-foreground text-sm",children:q.hint})]})},q.label))})}function t0({agents:f}){return J(j,{gap:"md",children:f.map((p)=>J(w0,{children:h(Z0,{className:"flex flex-col gap-2 pt-6",children:[h(h0,{justify:"between",align:"start",children:[h(j,{gap:"xs",className:"flex-1",children:[J(_,{className:"font-semibold text-lg",children:p.name}),h(_,{className:"text-muted-foreground text-sm",children:[p.modelProvider," / ",p.modelName]})]}),J(q0,{status:p.status})]}),J(_,{className:"text-muted-foreground text-sm",children:p.description})]})},p.id))})}function s0({tools:f}){return J(j,{gap:"md",children:f.map((p)=>J(w0,{children:h(Z0,{className:"flex flex-col gap-2 pt-6",children:[h(h0,{justify:"between",align:"start",children:[h(j,{gap:"xs",className:"flex-1",children:[J(_,{className:"font-semibold text-lg",children:p.name}),h(_,{className:"text-muted-foreground text-sm",children:[p.category," / ",p.implementationType]})]}),J(q0,{status:p.status})]}),J(_,{className:"text-muted-foreground text-sm",children:p.description})]})},p.id))})}function f1({metrics:f}){return h(j,{gap:"md",children:[J(_,{className:"font-semibold text-lg",children:"Usage Analytics"}),h(w0,{children:[J(X1,{children:J(h1,{children:"Run Outcomes"})}),h(Z0,{className:"flex flex-col gap-3",children:[h(_,{children:["Completed: ",f.completedRuns]}),h(_,{children:["Failed: ",f.totalRuns-f.completedRuns]}),h(_,{children:["Average duration: ",(f.averageDurationMs/1000).toFixed(1),"s"]})]})]})]})}function q0({status:f}){return J(F1,{variant:f==="FAILED"||f==="CANCELLED"?"destructive":f==="ACTIVE"||f==="COMPLETED"?"secondary":"outline",children:J(_,{className:"font-semibold text-xs",children:f})})}import{useContractTable as _1}from"@contractspec/lib.presentation-runtime-react";import{Card as H1,CardContent as V1}from"@contractspec/lib.ui-kit-web/ui/card";import{DataTable as E1}from"@contractspec/lib.ui-kit-web/ui/data-table";import{VStack as k1}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as M0}from"@contractspec/lib.ui-kit-web/ui/text";import{useMemo as B1}from"react";import{jsx as C,jsxs as v1}from"react/jsx-runtime";function p1({runs:f}){let p=B1(()=>[{id:"queuedAt",header:"Run",label:"Run",accessor:(m)=>m.queuedAt.getTime(),cell:({item:m})=>v1(k1,{gap:"xs",children:[C(M0,{className:"font-mono text-sm",children:m.id}),C(M0,{className:"text-muted-foreground text-xs",children:x0(m.queuedAt)})]}),size:180,canSort:!0,canHide:!0},{id:"agentName",header:"Agent",label:"Agent",accessorKey:"agentName",size:220,canSort:!0},{id:"status",header:"Status",label:"Status",accessorKey:"status",cell:({value:m})=>C(q0,{status:String(m)}),size:140,canSort:!0},{id:"totalTokens",header:"Tokens",label:"Tokens",accessorKey:"totalTokens",cell:({value:m})=>m0(Number(m??0)),align:"right",size:120,canSort:!0},{id:"durationMs",header:"Duration",label:"Duration",accessorKey:"durationMs",cell:({value:m})=>e0(typeof m==="number"?m:void 0),align:"right",size:130,canHide:!0}],[]),q=_1({data:f,columns:p,initialState:{pagination:{pageIndex:0,pageSize:5}},getRowId:(m)=>m.id});return C(E1,{controller:q,toolbar:C(M0,{className:"text-muted-foreground text-sm",children:"Run History"}),emptyState:C(H1,{children:C(V1,{className:"pt-6",children:C(M0,{className:"text-muted-foreground",children:"No runs yet"})})})})}import{createVisualizationModel as b1}from"@contractspec/lib.presentation-runtime-core";import{Button as m1}from"@contractspec/lib.ui-kit-web/ui/button";import{Card as L1,CardContent as u1,CardDescription as C1,CardHeader as r1,CardTitle as S1}from"@contractspec/lib.ui-kit-web/ui/card";import{HStack as w1,VStack as N0}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as e}from"@contractspec/lib.ui-kit-web/ui/text";import{Visualization as i1}from"@contractspec/lib.ui-kit-web/ui/visualization";import{useMemo as Z1,useState as c1}from"react";import{jsx as F,jsxs as S}from"react/jsx-runtime";function q1({agents:f=s,runs:p=p0,showHeaderAction:q=!0,tools:m=f0}){let[Z,M]=c1("runs"),w=Z1(()=>j0(p),[p]),y=Z1(()=>c(p),[p]);return S(N0,{gap:"xl",align:"stretch",children:[S(w1,{justify:"between",align:"center",className:"gap-3",children:[F(e,{className:"font-bold text-2xl",children:"AI Agent Console"}),q?F(m1,{...X0(()=>{return}),children:F(e,{children:"+ New Agent"})}):null]}),F(a0,{metrics:w}),S(N0,{gap:"md",children:[S(N0,{gap:"xs",children:[F(e,{className:"font-semibold text-lg",children:"Operational Visualizations"}),F(e,{className:"text-muted-foreground text-sm",children:"Contract-backed charts derived from recent run activity."})]}),F(N0,{gap:"md",children:y.map((U)=>S(L1,{children:[S(r1,{children:[F(S1,{children:U.title}),F(C1,{children:U.description})]}),F(u1,{children:F(i1,{height:U.height,model:b1(U.spec,U.data)})})]},U.key))})]}),F(w1,{className:"rounded-lg bg-muted p-1",gap:"xs",children:n0.map((U)=>F(m1,{size:"sm",variant:Z===U.id?"secondary":"ghost",className:"flex-1",...X0(()=>M(U.id)),children:S(e,{children:[U.icon," ",U.label]})},U.id))}),Z==="runs"?F(p1,{runs:p}):null,Z==="agents"?F(t0,{agents:f}):null,Z==="tools"?F(s0,{tools:m}):null,Z==="metrics"?F(f1,{metrics:w}):null]})}import{VisualizationCard as o1,VisualizationGrid as g1}from"@contractspec/lib.design-system";import{jsx as y0,jsxs as M1}from"react/jsx-runtime";function N1({runs:f}){let p=c(f);return M1("section",{className:"space-y-3",children:[M1("div",{children:[y0("h3",{className:"font-semibold text-lg",children:"Operational Visualizations"}),y0("p",{className:"text-muted-foreground text-sm",children:"Contract-backed charts derived from recent run activity."})]}),y0(g1,{children:p.map((q)=>y0(o1,{data:q.data,description:q.description,height:q.height,spec:q.spec,title:q.title},q.key))})]})}import{useTemplateRuntime as l1}from"@contractspec/lib.example-shared-ui";import{useCallback as n1,useEffect as j1,useMemo as e1,useState as D0}from"react";function o(f={}){let{handlers:p,projectId:q}=l1(),{agent:m}=p,[Z,M]=D0(null),[w,y]=D0(!0),[U,I]=D0(null),[N,T]=D0(1),D=n1(async()=>{y(!0),I(null);try{let z=await m.listAgents({projectId:q,search:f.search,status:f.status==="all"?void 0:f.status,limit:f.limit??20,offset:(N-1)*(f.limit??20)});M(z)}catch(z){I(z instanceof Error?z:Error("Unknown error"))}finally{y(!1)}},[m,q,f.search,f.status,f.limit,N]);j1(()=>{D()},[D]);let Y=e1(()=>{if(!Z)return null;return{total:Z.total,active:Z.items.filter((z)=>z.status==="ACTIVE").length,paused:Z.items.filter((z)=>z.status==="PAUSED").length,draft:Z.items.filter((z)=>z.status==="DRAFT").length}},[Z]);return{data:Z,loading:w,error:U,stats:Y,page:N,refetch:D,nextPage:()=>T((z)=>z+1),prevPage:()=>N>1&&T((z)=>z-1)}}import{useTemplateRuntime as t1}from"@contractspec/lib.example-shared-ui";import{useCallback as g,useState as H0}from"react";var _0="demo-org",Dp="agent-console-demo";function Up(f){return f.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function Tp(f){return{...f}}function Kp(f){return{...f}}function Ap(f){return{...f}}function zp(){let f=0,p=Date.parse("2026-03-20T09:00:00.000Z");return()=>new Date(p+f++*60000)}function x1(f){return f.toLowerCase()}function a1(f){return f==="IN_PROGRESS"?"RUNNING":f}function Qp(f,p){let q=s.map((w)=>({id:w.id,projectId:f,organizationId:p,name:w.name,slug:w.slug,description:w.description,modelProvider:x1(w.modelProvider),modelName:w.modelName,systemPrompt:w.systemPrompt,temperature:typeof w.modelConfig?.temperature==="number"?w.modelConfig.temperature:0.4,maxTokens:8192,status:w.status,createdAt:w.createdAt,updatedAt:w.updatedAt})),m=f0.map((w)=>({id:w.id,projectId:f,organizationId:p,name:w.name,description:w.description,version:w.version,category:w.category,status:w.status,inputSchema:JSON.stringify(w.parametersSchema),outputSchema:w.outputSchema?JSON.stringify(w.outputSchema):void 0,endpoint:typeof w.implementationConfig?.url==="string"?w.implementationConfig.url:void 0,createdAt:w.createdAt,updatedAt:w.updatedAt})),Z=new Map(q.map((w)=>[w.id,w.name])),M=p0.map((w)=>({id:w.id,projectId:f,agentId:w.agentId,agentName:Z.get(w.agentId)??w.agentName??"Unknown agent",status:a1(w.status),input:JSON.stringify(w.input),output:w.output?JSON.stringify(w.output):void 0,totalTokens:w.totalTokens,promptTokens:w.promptTokens,completionTokens:w.completionTokens,estimatedCostUsd:w.estimatedCostUsd??0,durationMs:w.durationMs,errorMessage:w.errorMessage,queuedAt:w.queuedAt,startedAt:w.startedAt,completedAt:w.completedAt}));return{agents:q,tools:m,runs:M}}function Pp(f){let p=f.length,q=f.filter((Z)=>Z.status==="COMPLETED").length,m=f.map((Z)=>Z.durationMs).filter((Z)=>typeof Z==="number");return{totalRuns:p,successRate:p===0?0:q/p,averageDurationMs:m.length===0?0:Math.round(m.reduce((Z,M)=>Z+M,0)/m.length),totalTokens:f.reduce((Z,M)=>Z+M.totalTokens,0),totalCostUsd:f.reduce((Z,M)=>Z+M.estimatedCostUsd,0)}}function V0(f,p){return f instanceof Error?f:Error(p)}function E0(f={}){let{handlers:p,projectId:q}=t1(),{agent:m}=p,[Z,M]=H0({loading:!1,error:null,data:null}),[w,y]=H0({loading:!1,error:null,data:null}),[U,I]=H0({loading:!1,error:null,data:null}),N=g(async($)=>{M({loading:!0,error:null,data:null});try{let R=await m.createAgent($,{projectId:q,organizationId:_0});return M({loading:!1,error:null,data:R}),f.onSuccess?.(),R}catch(R){let A=V0(R,"Failed to create agent");throw M({loading:!1,error:A,data:null}),f.onError?.(A),A}},[m,q,f]),T=g(async($)=>{y({loading:!0,error:null,data:null});try{let R=await m.updateAgent($);return y({loading:!1,error:null,data:R}),f.onSuccess?.(),R}catch(R){let A=V0(R,"Failed to update agent");throw y({loading:!1,error:A,data:null}),f.onError?.(A),A}},[m,f]),D=g(async($)=>{return T({id:$,status:"ACTIVE"})},[T]),Y=g(async($)=>{return T({id:$,status:"PAUSED"})},[T]),z=g(async($)=>{return T({id:$,status:"ARCHIVED"})},[T]),d=g(async($)=>{I({loading:!0,error:null,data:null});try{let R=await m.executeAgent({agentId:$.agentId,message:$.message,context:{projectId:q,organizationId:_0}});return I({loading:!1,error:null,data:R}),f.onSuccess?.(),R}catch(R){let A=V0(R,"Failed to execute agent");throw I({loading:!1,error:A,data:null}),f.onError?.(A),A}},[m,q,f]);return{createAgent:N,updateAgent:T,activateAgent:D,pauseAgent:Y,archiveAgent:z,executeAgent:d,createState:Z,updateState:w,executeState:U,isLoading:Z.loading||w.loading||U.loading}}import{useTemplateRuntime as s1}from"@contractspec/lib.example-shared-ui";import{useCallback as f2,useEffect as p2,useState as x}from"react";function a(f={}){let{handlers:p,projectId:q}=s1(),{agent:m}=p,[Z,M]=x(null),[w,y]=x(null),[U,I]=x(!0),[N,T]=x(null),[D,Y]=x(0),z=f.pageSize??f.limit??20,d=f.pageIndex??D,[$]=f.sorting??[],R=f2(async()=>{I(!0),T(null);try{let[K,G]=await Promise.all([m.listRuns({projectId:q,agentId:f.agentId,status:f.status==="all"?void 0:f.status,sortBy:$?.id,sortDirection:$?$.desc?"desc":"asc":void 0,limit:z,offset:d*z}),m.getRunMetrics({projectId:q,agentId:f.agentId})]);M(K),y(G)}catch(K){T(K instanceof Error?K:Error("Unknown error"))}finally{I(!1)}},[m,d,z,q,f.agentId,f.status,$?.desc,$?.id]);p2(()=>{R()},[R]);let A=f.pageIndex!==void 0;return{data:Z,metrics:w,loading:U,error:N,page:d+1,pageIndex:d,pageSize:z,refetch:R,nextPage:A?void 0:()=>Y((K)=>K+1),prevPage:A?void 0:()=>Y((K)=>Math.max(0,K-1))}}import{Button as B}from"@contractspec/lib.design-system";import{useState as U0}from"react";import{jsx as O,jsxs as X}from"react/jsx-runtime";function m2(f){switch(f){case"ACTIVE":return"text-green-600 bg-green-100 dark:text-green-400 dark:bg-green-900/30";case"DRAFT":return"text-blue-600 bg-blue-100 dark:text-blue-400 dark:bg-blue-900/30";case"PAUSED":return"text-yellow-600 bg-yellow-100 dark:text-yellow-400 dark:bg-yellow-900/30";case"ARCHIVED":return"text-gray-600 bg-gray-100 dark:text-gray-400 dark:bg-gray-700";default:return"text-gray-600 bg-gray-100"}}function k0({isOpen:f,agent:p,onClose:q,onActivate:m,onPause:Z,onArchive:M,onExecute:w,isLoading:y=!1}){let[U,I]=U0("menu"),[N,T]=U0(""),[D,Y]=U0(null),[z,d]=U0(null),$=()=>{I("menu"),T(""),Y(null),d(null)},R=()=>{$(),q()},A=async()=>{if(!p)return;if(d(null),!N.trim()){d("Please enter a message");return}try{await w(p.id,N.trim()),R()}catch(G){d(G instanceof Error?G.message:"Failed to execute agent")}},K=async(G)=>{if(!p)return;d(null);try{switch(G){case"activate":await m(p.id);break;case"pause":await Z(p.id);break;case"archive":await M(p.id);break}R()}catch(u){d(u instanceof Error?u.message:`Failed to ${G} agent`)}};if(!f||!p)return null;return X("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[O("div",{className:"absolute inset-0 bg-background/80 backdrop-blur-sm",onClick:R,role:"button",tabIndex:0,onKeyDown:(G)=>{if(G.key==="Enter"||G.key===" ")R()},"aria-label":"Close modal"}),X("div",{className:"relative z-10 w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-xl",children:[X("div",{className:"mb-4 border-border border-b pb-4",children:[O("h2",{className:"font-semibold text-xl",children:p.name}),X("div",{className:"mt-1 flex items-center gap-2",children:[X("span",{className:"text-muted-foreground text-sm",children:[p.modelProvider," / ",p.modelName]}),O("span",{className:`rounded-full px-2 py-0.5 font-medium text-xs ${m2(p.status)}`,children:p.status})]}),p.description&&O("p",{className:"mt-2 text-muted-foreground text-sm",children:p.description})]}),U==="menu"&&X("div",{className:"space-y-3",children:[p.status==="ACTIVE"&&X(B,{className:"w-full justify-start",variant:"ghost",onPress:()=>I("execute"),children:[O("span",{className:"mr-2",children:"▶️"})," Execute Agent"]}),(p.status==="DRAFT"||p.status==="PAUSED")&&X(B,{className:"w-full justify-start",variant:"ghost",onPress:()=>K("activate"),disabled:y,children:[O("span",{className:"mr-2",children:"\uD83D\uDFE2"})," Activate Agent"]}),p.status==="ACTIVE"&&X(B,{className:"w-full justify-start",variant:"ghost",onPress:()=>K("pause"),disabled:y,children:[O("span",{className:"mr-2",children:"⏸️"})," Pause Agent"]}),p.status!=="ARCHIVED"&&X(B,{className:"w-full justify-start text-yellow-600 hover:text-yellow-700",variant:"ghost",onPress:()=>{Y("archive"),I("confirm")},children:[O("span",{className:"mr-2",children:"\uD83D\uDCE6"})," Archive Agent"]}),p.status==="ARCHIVED"&&X(B,{className:"w-full justify-start",variant:"ghost",onPress:()=>K("activate"),disabled:y,children:[O("span",{className:"mr-2",children:"\uD83D\uDD04"})," Restore Agent"]}),z&&O("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:z}),O("div",{className:"border-border border-t pt-3",children:O(B,{className:"w-full",variant:"outline",onPress:R,children:"Close"})})]}),U==="execute"&&X("div",{className:"space-y-4",children:[X("div",{children:[O("label",{htmlFor:"execute-message",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Message *"}),O("textarea",{id:"execute-message",value:N,onChange:(G)=>T(G.target.value),placeholder:"Enter your message to the agent...",rows:4,disabled:y,className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50"})]}),z&&O("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:z}),X("div",{className:"flex justify-end gap-3 pt-2",children:[O(B,{variant:"ghost",onPress:()=>I("menu"),disabled:y,children:"Back"}),O(B,{onPress:A,disabled:y,children:y?"Executing...":"▶️ Execute"})]})]}),U==="confirm"&&D==="archive"&&X("div",{className:"space-y-4",children:[X("p",{className:"text-muted-foreground",children:["Are you sure you want to archive"," ",O("span",{className:"font-medium text-foreground",children:p.name}),"?"]}),O("p",{className:"text-muted-foreground text-sm",children:"Archived agents cannot be executed but can be restored later."}),z&&O("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:z}),X("div",{className:"flex justify-end gap-3 pt-2",children:[O(B,{variant:"ghost",onPress:()=>I("menu"),disabled:y,children:"Cancel"}),O(B,{onPress:()=>K("archive"),disabled:y,children:y?"Archiving...":"\uD83D\uDCE6 Archive"})]})]})]})]})}import{Button as y1,Input as w2}from"@contractspec/lib.design-system";import{useState as l}from"react";import{jsx as W,jsxs as v}from"react/jsx-runtime";var B0=[{value:"openai",label:"OpenAI",models:["gpt-5.4","gpt-5-mini","gpt-4o","gpt-4-turbo","gpt-3.5-turbo"]},{value:"anthropic",label:"Anthropic",models:["claude-sonnet-4-6","claude-opus-4-6","claude-haiku-4-5"]},{value:"google",label:"Google",models:["gemini-2.5-flash","gemini-2.5-pro","gemini-pro","gemini-ultra"]},{value:"mistral",label:"Mistral",models:["mistral-large-2512","mistral-large-latest","mistral-medium-latest","mistral-small-latest"]}];function v0({isOpen:f,onClose:p,onSubmit:q,isLoading:m=!1}){let[Z,M]=l(""),[w,y]=l(""),[U,I]=l("openai"),[N,T]=l("gpt-5.4"),[D,Y]=l(""),[z,d]=l(null),$=B0.find((K)=>K.value===U),R=async(K)=>{if(K.preventDefault(),d(null),!Z.trim()){d("Agent name is required");return}try{await q({name:Z.trim(),description:w.trim()||void 0,modelProvider:U,modelName:N,systemPrompt:D.trim()||void 0}),M(""),y(""),I("openai"),T("gpt-5.4"),Y(""),p()}catch(G){d(G instanceof Error?G.message:"Failed to create agent")}},A=(K)=>{I(K);let G=B0.find((u)=>u.value===K);if(G)T(G.models[0])};if(!f)return null;return v("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[W("div",{className:"absolute inset-0 bg-background/80 backdrop-blur-sm",onClick:p,role:"button",tabIndex:0,onKeyDown:(K)=>{if(K.key==="Enter"||K.key===" ")p()},"aria-label":"Close modal"}),v("div",{className:"relative z-10 max-h-[90vh] w-full max-w-lg overflow-y-auto rounded-xl border border-border bg-card p-6 shadow-xl",children:[W("h2",{className:"mb-4 font-semibold text-xl",children:"Create New Agent"}),v("form",{onSubmit:R,className:"space-y-4",children:[v("div",{children:[W("label",{htmlFor:"agent-name",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Agent Name *"}),W(w2,{id:"agent-name",value:Z,onChange:(K)=>M(K.target.value),placeholder:"e.g., Customer Support Bot",disabled:m})]}),v("div",{children:[W("label",{htmlFor:"agent-description",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Description"}),W("textarea",{id:"agent-description",value:w,onChange:(K)=>y(K.target.value),placeholder:"Describe what this agent does...",rows:2,disabled:m,className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50"})]}),v("div",{className:"flex gap-3",children:[v("div",{className:"flex-1",children:[W("label",{htmlFor:"model-provider",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Provider *"}),W("select",{id:"model-provider",value:U,onChange:(K)=>A(K.target.value),disabled:m,className:"h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50",children:B0.map((K)=>W("option",{value:K.value,children:K.label},K.value))})]}),v("div",{className:"flex-1",children:[W("label",{htmlFor:"model-name",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Model *"}),W("select",{id:"model-name",value:N,onChange:(K)=>T(K.target.value),disabled:m,className:"h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50",children:$?.models.map((K)=>W("option",{value:K,children:K},K))})]})]}),v("div",{children:[W("label",{htmlFor:"system-prompt",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"System Prompt"}),W("textarea",{id:"system-prompt",value:D,onChange:(K)=>Y(K.target.value),placeholder:"You are a helpful assistant that...",rows:4,disabled:m,className:"w-full rounded-md border border-input bg-background px-3 py-2 font-mono text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50"}),W("p",{className:"mt-1 text-muted-foreground text-xs",children:"Instructions that define the agent's behavior"})]}),z&&W("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:z}),v("div",{className:"flex justify-end gap-3 pt-2",children:[W(y1,{type:"button",variant:"ghost",onPress:p,disabled:m,children:"Cancel"}),W(y1,{type:"submit",disabled:m,children:m?"Creating...":"Create Agent"})]})]})]})]})}import{Button as T0,StatusChip as Z2}from"@contractspec/lib.design-system";import{HStack as L0,VStack as b0}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as i}from"@contractspec/lib.ui-kit-web/ui/text";import{jsx as L,jsxs as k}from"react/jsx-runtime";function u0(f){switch(f){case"COMPLETED":return"success";case"RUNNING":return"warning";case"QUEUED":return"neutral";case"FAILED":case"CANCELLED":return"danger";default:return"neutral"}}function C0(f){if(!f)return"-";if(f<1000)return`${f}ms`;if(f<60000)return`${(f/1000).toFixed(1)}s`;return`${(f/60000).toFixed(1)}m`}function n(f){if(f<1000)return f.toString();if(f<1e6)return`${(f/1000).toFixed(1)}K`;return`${(f/1e6).toFixed(2)}M`}function U1(f){if(!f)return"-";return`$${f.toFixed(4)}`}function D1(f){return JSON.stringify(f??null,null,2)}function T1({run:f}){return k(b0,{gap:"sm",className:"py-2",children:[k(L0,{justify:"between",className:"flex-wrap",children:[L(Z2,{tone:u0(f.status),label:f.status}),k(i,{className:"text-muted-foreground text-sm",children:["Queued ",f.queuedAt.toLocaleString()]})]}),k(L0,{gap:"lg",className:"flex-wrap",children:[k(i,{className:"text-muted-foreground text-sm",children:["Prompt ",n(f.promptTokens)]}),k(i,{className:"text-muted-foreground text-sm",children:["Completion ",n(f.completionTokens)]}),k(i,{className:"text-muted-foreground text-sm",children:["Duration ",C0(f.durationMs)]})]}),k(b0,{gap:"xs",children:[L(i,{className:"font-medium text-sm",children:"Input"}),L("pre",{className:"overflow-auto rounded-md bg-muted/40 p-3 text-xs",children:D1(f.input)})]}),k(b0,{gap:"xs",children:[L(i,{className:"font-medium text-sm",children:"Output"}),L("pre",{className:"overflow-auto rounded-md bg-muted/40 p-3 text-xs",children:D1(f.output??f.errorMessage??"Pending")})]})]})}function K1({controller:f,totalRuns:p}){let q=f.rows[0],m=f.columns.find((w)=>w.id==="queuedAt"),Z=f.columns.find((w)=>w.id==="durationMs"),M=f.columns.find((w)=>w.id==="estimatedCostUsd");return k(L0,{gap:"sm",className:"flex-wrap",children:[k(i,{className:"text-muted-foreground text-sm",children:[p," runs"]}),L(T0,{variant:"outline",size:"sm",onPress:()=>q?.toggleExpanded?.(!q?.isExpanded),children:"Expand Latest Run"}),L(T0,{variant:"outline",size:"sm",onPress:()=>m?.toggleVisibility?.(!m?.visible),children:m?.visible?"Hide Time":"Show Time"}),L(T0,{variant:"outline",size:"sm",onPress:()=>Z?.toggleVisibility?.(!Z?.visible),children:Z?.visible?"Hide Duration":"Show Duration"}),L(T0,{variant:"outline",size:"sm",onPress:()=>M?.toggleVisibility?.(!M?.visible),children:M?.visible?"Hide Cost":"Show Cost"})]})}import{StatusChip as q2}from"@contractspec/lib.design-system";import{VStack as M2}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as r0}from"@contractspec/lib.ui-kit-web/ui/text";import{jsx as K0,jsxs as N2}from"react/jsx-runtime";function A1(){return[{id:"queuedAt",header:"Run",label:"Run",accessor:(f)=>f.queuedAt.getTime(),cell:({item:f})=>N2(M2,{gap:"xs",children:[K0(r0,{className:"font-mono text-sm",children:f.id.slice(-8)}),K0(r0,{className:"text-muted-foreground text-xs",children:f.queuedAt.toLocaleString()})]}),size:220,minSize:180,canSort:!0,canHide:!0,canResize:!0},{id:"agentName",header:"Agent",label:"Agent",accessor:(f)=>f.agentName??"Unknown Agent",cell:({value:f})=>K0(r0,{className:"font-medium",children:typeof f==="string"?f:"Unknown Agent"}),size:220,canSort:!0,canResize:!0},{id:"status",header:"Status",label:"Status",accessorKey:"status",cell:({value:f})=>{let p=typeof f==="string"?f:"QUEUED";return K0(q2,{tone:u0(p),label:p})},size:150,canSort:!0,canResize:!0},{id:"totalTokens",header:"Tokens",label:"Tokens",accessorKey:"totalTokens",cell:({value:f})=>n(Number(f??0)),align:"right",size:140,canSort:!0,canResize:!0},{id:"durationMs",header:"Duration",label:"Duration",accessorKey:"durationMs",cell:({value:f})=>C0(typeof f==="number"?f:void 0),align:"right",size:140,canSort:!0,canHide:!0,canResize:!0},{id:"estimatedCostUsd",header:"Cost",label:"Cost",accessorKey:"estimatedCostUsd",cell:({value:f})=>U1(typeof f==="number"?f:void 0),align:"right",size:140,canSort:!0,canHide:!0,canResize:!0}]}import{DataTable as y2}from"@contractspec/lib.design-system";import{useContractTable as D2}from"@contractspec/lib.presentation-runtime-react";import*as z1 from"react";import{jsx as A0}from"react/jsx-runtime";function Q1({runs:f,totalItems:p,pageIndex:q,pageSize:m,sorting:Z,loading:M,onSortingChange:w,onPaginationChange:y,onRunClick:U}){let I=z1.useMemo(()=>A1(),[]),N=D2({data:f,columns:I,executionMode:"server",totalItems:p,state:{sorting:Z,pagination:{pageIndex:q,pageSize:m}},onSortingChange:w,onPaginationChange:y,initialState:{columnVisibility:{estimatedCostUsd:!1}},getRowId:(T)=>T.id,renderExpandedContent:(T)=>A0(T1,{run:T}),getCanExpand:()=>!0});return A0(y2,{controller:N,title:"Run History",description:"Server-mode ContractSpec table with shared pagination, sorting, visibility, and expansion.",loading:M,onRowPress:(T)=>U?.(T.id),toolbar:A0(K1,{controller:N,totalRuns:p}),emptyState:A0("div",{className:"rounded-md border border-dashed p-8 text-center text-muted-foreground text-sm",children:"No runs yet"})})}import{EmptyState as U2,ErrorState as T2,LoaderBlock as K2,StatCard as z0,StatCardGroup as A2}from"@contractspec/lib.design-system";import{useState as P1}from"react";import{jsx as r,jsxs as $1}from"react/jsx-runtime";function Q0({agentId:f,onRunClick:p}){let[q,m]=P1([{id:"queuedAt",desc:!0}]),[Z,M]=P1({pageIndex:0,pageSize:3}),{data:w,metrics:y,loading:U,error:I,refetch:N}=a({agentId:f,pageIndex:Z.pageIndex,pageSize:Z.pageSize,sorting:q});if(U&&!w)return r(K2,{label:"Loading runs..."});if(I)return r(T2,{title:"Failed to load runs",description:I.message,onRetry:N,retryLabel:"Retry"});if(!w?.items.length)return r(U2,{title:"No runs yet",description:"Execute an agent to see run history here."});return $1("div",{className:"space-y-6",children:[y?$1(A2,{children:[r(z0,{label:"Total Runs",value:y.totalRuns}),r(z0,{label:"Success Rate",value:`${(y.successRate*100).toFixed(1)}%`}),r(z0,{label:"Total Tokens",value:n(y.totalTokens)}),r(z0,{label:"Total Cost",value:`$${y.totalCostUsd.toFixed(2)}`})]}):null,r(Q1,{runs:w.items,totalItems:w.total,pageIndex:Z.pageIndex,pageSize:Z.pageSize,sorting:q,loading:U,onSortingChange:(T)=>{m(T),M((D)=>({...D,pageIndex:0}))},onPaginationChange:M,onRunClick:p})]})}import{useTemplateRuntime as z2}from"@contractspec/lib.example-shared-ui";import{useCallback as Q2,useEffect as P2,useMemo as $2,useState as P0}from"react";function S0(f={}){let{handlers:p,projectId:q}=z2(),{agent:m}=p,[Z,M]=P0(null),[w,y]=P0(!0),[U,I]=P0(null),[N,T]=P0(1),D=Q2(async()=>{y(!0),I(null);try{let $=await m.listTools({projectId:q,search:f.search,category:f.category,status:f.status==="all"?void 0:f.status,limit:f.limit??50,offset:(N-1)*(f.limit??50)});M($)}catch($){I($ instanceof Error?$:Error("Unknown error"))}finally{y(!1)}},[m,q,f.search,f.category,f.status,f.limit,N]);P2(()=>{D()},[D]);let{stats:Y,groupedByCategory:z,categoryStats:d}=$2(()=>{if(!Z)return{stats:null,groupedByCategory:{},categoryStats:[]};let $=Z.items,R=$.filter((E)=>E.status==="ACTIVE").length,A=$.filter((E)=>E.status==="DEPRECATED").length,K=$.filter((E)=>E.status==="DISABLED").length,G={},u={};$.forEach((E)=>{let b=E.category;if(!G[b])G[b]=[];G[b].push(E),u[b]=(u[b]||0)+1});let o0=Object.entries(u).map(([E,b])=>({category:E,count:b})).sort((E,b)=>b.count-E.count);return{stats:{total:Z.total,active:R,deprecated:A,disabled:K,topCategories:o0.slice(0,5)},groupedByCategory:G,categoryStats:o0}},[Z]);return{data:Z,loading:w,error:U,stats:Y,groupedByCategory:z,categoryStats:d,page:N,refetch:D,nextPage:()=>T(($)=>$+1),prevPage:()=>N>1&&T(($)=>$-1)}}import{Button as I2,EmptyState as R2,EntityCard as Y2,ErrorState as d2,LoaderBlock as G2,StatCard as I1,StatCardGroup as O2,StatusChip as J2}from"@contractspec/lib.design-system";import{jsx as H,jsxs as $0}from"react/jsx-runtime";var R1={RETRIEVAL:"\uD83D\uDD0D",COMPUTATION:"\uD83E\uDDEE",COMMUNICATION:"\uD83D\uDCE7",INTEGRATION:"\uD83D\uDD17",UTILITY:"\uD83D\uDEE0️",CUSTOM:"⚙️"};function W2(f){switch(f){case"ACTIVE":return"success";case"DRAFT":return"neutral";case"DEPRECATED":return"warning";case"DISABLED":return"danger";default:return"neutral"}}function I0({onToolClick:f,onCreateTool:p}){let{data:q,loading:m,error:Z,groupedByCategory:M,categoryStats:w,refetch:y}=S0();if(m&&!q)return H(G2,{label:"Loading tools..."});if(Z)return H(d2,{title:"Failed to load tools",description:Z.message,onRetry:y,retryLabel:"Retry"});if(!q?.items.length)return H(R2,{title:"No tools registered",description:"Create your first tool to extend agent capabilities.",primaryAction:p?H(I2,{onPress:p,children:"Create Tool"}):void 0});return $0("div",{className:"space-y-8",children:[$0(O2,{children:[H(I1,{label:"Total Tools",value:q.total}),w.slice(0,3).map(({category:U,count:I})=>H(I1,{label:`${R1[U]??""} ${U}`,value:I},U))]}),Object.entries(M).map(([U,I])=>$0("section",{className:"space-y-4",children:[$0("div",{className:"flex items-center gap-2",children:[H("span",{className:"text-2xl",children:R1[U]}),H("h3",{className:"font-semibold text-lg",children:U}),H("span",{className:"rounded-full bg-muted px-2 py-0.5 text-muted-foreground text-xs",children:I.length})]}),H("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:I.map((N)=>H(Y2,{cardTitle:N.name,cardSubtitle:`v${N.version}`,meta:H("p",{className:"text-muted-foreground text-sm",children:N.description}),chips:H(J2,{tone:W2(N.status),label:N.status}),footer:H("code",{className:"text-muted-foreground text-xs",children:N.name}),onClick:f?()=>f(N.id):void 0},N.id))})]},U))]})}import{Button as i0,StatCard as F2,StatCardGroup as X2}from"@contractspec/lib.design-system";import{useCallback as h2,useMemo as _2,useState as t}from"react";import{jsx as Q,jsxs as P}from"react/jsx-runtime";function Y4(){let[f,p]=t("runs"),[q,m]=t(!1),[Z,M]=t(null),[w,y]=t(!1),[U,I]=t(0),{data:N,metrics:T,refetch:D}=a(),{refetch:Y}=o(),z=E0({onSuccess:()=>{Y(),D(),I((A)=>A+1)}}),d=h2((A)=>{M(A),y(!0)},[]),$=[{id:"runs",label:"Runs",icon:"▶"},{id:"agents",label:"Agents",icon:"\uD83E\uDD16"},{id:"tools",label:"Tools",icon:"\uD83D\uDD27"},{id:"metrics",label:"Metrics",icon:"\uD83D\uDCCA"}],R=_2(()=>{if(!T)return[{label:"Total Runs",value:"-",hint:"Loading..."},{label:"Success Rate",value:"-",hint:""},{label:"Total Tokens",value:"-",hint:""},{label:"Total Cost",value:"-",hint:""}];return[{label:"Total Runs",value:T.totalRuns.toLocaleString(),hint:`${(T.successRate*100).toFixed(0)}% success`},{label:"Success Rate",value:`${(T.successRate*100).toFixed(0)}%`,hint:"of all runs"},{label:"Total Tokens",value:T.totalTokens>=1e6?`${(T.totalTokens/1e6).toFixed(1)}M`:`${(T.totalTokens/1000).toFixed(0)}K`,hint:"This period"},{label:"Total Cost",value:`$${T.totalCostUsd.toFixed(2)}`,hint:"This period"}]},[T]);return P("div",{className:"space-y-6",children:[P("div",{className:"flex items-center justify-between",children:[Q("h2",{className:"font-bold text-2xl",children:"AI Agent Console"}),P(i0,{onPress:()=>m(!0),children:[Q("span",{className:"mr-2",children:"+"})," New Agent"]})]}),Q(X2,{children:R.map((A,K)=>Q(F2,{label:A.label,value:A.value,hint:A.hint},K))}),Q(N1,{runs:N?.items??[]}),Q("nav",{className:"flex gap-1 rounded-lg bg-muted p-1",role:"tablist",children:$.map((A)=>P("button",{type:"button",role:"tab","aria-selected":f===A.id,onClick:()=>p(A.id),className:`flex flex-1 items-center justify-center gap-2 rounded-md px-4 py-2 font-medium text-sm transition-colors ${f===A.id?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[Q("span",{children:A.icon}),A.label]},A.id))}),P("div",{className:"min-h-[400px]",role:"tabpanel",children:[f==="runs"&&Q(Q0,{},U),f==="agents"&&Q(H2,{onAgentClick:d},U),f==="tools"&&Q(I0,{}),f==="metrics"&&Q(E2,{metrics:T})]}),Q(v0,{isOpen:q,onClose:()=>m(!1),onSubmit:async(A)=>{await z.createAgent(A)},isLoading:z.createState.loading}),Q(k0,{isOpen:w,agent:Z,onClose:()=>{y(!1),M(null)},onActivate:async(A)=>{await z.activateAgent(A)},onPause:async(A)=>{await z.pauseAgent(A)},onArchive:async(A)=>{await z.archiveAgent(A)},onExecute:async(A,K)=>{await z.executeAgent({agentId:A,message:K})},isLoading:z.isLoading})]})}function H2({onAgentClick:f}){let{data:p,loading:q,error:m,stats:Z,refetch:M}=o();if(q&&!p)return Q("div",{className:"flex h-64 items-center justify-center text-muted-foreground",children:"Loading agents..."});if(m)return P("div",{className:"flex h-64 flex-col items-center justify-center text-destructive",children:[P("p",{children:["Failed to load agents: ",m.message]}),Q(i0,{variant:"outline",onPress:M,className:"mt-2",children:"Retry"})]});if(!p?.items.length)return P("div",{className:"flex h-64 flex-col items-center justify-center text-muted-foreground",children:[Q("p",{className:"font-medium text-lg",children:"No agents yet"}),Q("p",{className:"text-sm",children:"Create your first AI agent to get started."})]});return P("div",{className:"space-y-4",children:[Z&&P("div",{className:"flex gap-4 text-sm",children:[P("span",{children:["Total: ",Z.total]}),P("span",{className:"text-green-600",children:["Active: ",Z.active]}),P("span",{className:"text-yellow-600",children:["Paused: ",Z.paused]}),P("span",{className:"text-blue-600",children:["Draft: ",Z.draft]})]}),Q("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:p.items.map((w)=>Q(V2,{agent:w,onClick:()=>f(w)},w.id))})]})}function V2({agent:f,onClick:p}){let q={ACTIVE:"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",DRAFT:"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400",PAUSED:"bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400",ARCHIVED:"bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400"};return P("div",{onClick:p,className:"cursor-pointer rounded-xl border border-border bg-card p-4 transition-all hover:shadow-md",role:"button",tabIndex:0,onKeyDown:(m)=>{if(m.key==="Enter"||m.key===" ")p()},children:[P("div",{className:"flex items-start justify-between",children:[P("div",{className:"min-w-0 flex-1",children:[Q("h3",{className:"truncate font-semibold",children:f.name}),P("p",{className:"text-muted-foreground text-sm",children:[f.modelProvider," / ",f.modelName]})]}),Q("span",{className:`rounded-full px-2 py-0.5 font-medium text-xs ${q[f.status]}`,children:f.status})]}),f.description&&Q("p",{className:"mt-2 line-clamp-2 text-muted-foreground text-sm",children:f.description}),P("div",{className:"mt-3 flex items-center justify-between",children:[Q("span",{className:"text-muted-foreground text-xs",children:f.modelName}),Q(i0,{variant:"ghost",size:"sm",onPress:p,children:"Actions"})]})]})}function E2({metrics:f}){if(!f)return Q("div",{className:"flex h-64 items-center justify-center text-muted-foreground",children:"Loading metrics..."});let p=Math.round(f.totalRuns*f.successRate),q=f.totalRuns-p;return P("div",{className:"space-y-6",children:[Q("h3",{className:"font-semibold text-lg",children:"Usage Analytics"}),P("div",{className:"grid gap-6 md:grid-cols-2",children:[P("div",{className:"rounded-xl border border-border bg-card p-4",children:[Q("h4",{className:"font-medium",children:"Run Outcomes"}),P("div",{className:"mt-4 space-y-3",children:[Q(Y1,{label:"Completed",value:p,total:f.totalRuns,color:"bg-green-500"}),Q(Y1,{label:"Failed",value:q,total:f.totalRuns,color:"bg-red-500"})]})]}),P("div",{className:"rounded-xl border border-border bg-card p-4",children:[Q("h4",{className:"font-medium",children:"Performance"}),P("dl",{className:"mt-4 grid grid-cols-2 gap-4",children:[P("div",{children:[Q("dt",{className:"text-muted-foreground text-sm",children:"Avg Duration"}),P("dd",{className:"font-semibold text-xl",children:[(f.averageDurationMs/1000).toFixed(1),"s"]})]}),P("div",{children:[Q("dt",{className:"text-muted-foreground text-sm",children:"Success Rate"}),P("dd",{className:"font-semibold text-xl",children:[(f.successRate*100).toFixed(0),"%"]})]})]})]})]}),P("div",{className:"rounded-xl border border-border bg-card p-4",children:[Q("h4",{className:"font-medium",children:"Key Metrics"}),P("dl",{className:"mt-4 grid gap-4 sm:grid-cols-3",children:[P("div",{children:[Q("dt",{className:"text-muted-foreground text-sm",children:"Total Runs"}),Q("dd",{className:"font-semibold text-2xl",children:f.totalRuns.toLocaleString()})]}),P("div",{children:[Q("dt",{className:"text-muted-foreground text-sm",children:"Total Tokens"}),P("dd",{className:"font-semibold text-2xl",children:[(f.totalTokens/1000).toFixed(0),"K"]})]}),P("div",{children:[Q("dt",{className:"text-muted-foreground text-sm",children:"Cost per Run"}),P("dd",{className:"font-semibold text-2xl",children:["$",f.totalRuns>0?(f.totalCostUsd/f.totalRuns).toFixed(4):"0"]})]})]})]})]})}function Y1({label:f,value:p,total:q,color:m}){let Z=q>0?p/q*100:0;return P("div",{children:[P("div",{className:"flex justify-between text-sm",children:[Q("span",{children:f}),P("span",{className:"text-muted-foreground",children:[p," (",Z.toFixed(0),"%)"]})]}),Q("div",{className:"mt-1 h-2 overflow-hidden rounded-full bg-muted",children:Q("div",{className:`h-full ${m}`,style:{width:`${Z}%`}})})]})}import{VStack as k2}from"@contractspec/lib.ui-kit-web/ui/stack";import{ExecutionLaneConsoleDemo as B2}from"@contractspec/module.execution-console";import{jsx as d1,jsxs as v2}from"react/jsx-runtime";function H4(){return v2(k2,{gap:"xl",align:"stretch",children:[d1(q1,{}),d1(B2,{})]})}var b2={overlayId:"agent-console.demo-user",version:"1.0.0",description:"Simplifies agent console for demo users",appliesTo:{feature:"agent-console",role:"demo"},modifications:[{type:"hideField",field:"modelConfig",reason:"Advanced config not relevant for demo"},{type:"hideField",field:"webhookConfig",reason:"Integration not available in demo"},{type:"renameLabel",field:"systemPrompt",newLabel:"Agent Instructions"},{type:"addBadge",position:"header",label:"Demo Mode",variant:"warning"}]},L2={overlayId:"agent-console.read-only",version:"1.0.0",description:"Read-only view for non-admin users",appliesTo:{feature:"agent-console",role:"viewer"},modifications:[{type:"hideField",field:"deleteButton",reason:"No delete permission"},{type:"hideField",field:"editButton",reason:"No edit permission"},{type:"hideField",field:"createButton",reason:"No create permission"}]},S4=[b2,L2];import{AGENT_CONSOLE_DEMO_ORGANIZATION_ID as u2,AGENT_CONSOLE_DEMO_PROJECT_ID as G1,createAgentConsoleDemoHandlers as C2}from"@contractspec/example.agent-console/shared";var r2={target:"markdown",render:async(f,p)=>{if(f.source.type!=="component"||f.source.componentKey!=="AgentListView")throw Error("agentListMarkdownRenderer: not AgentListView");let q=Array.isArray(p?.data)?{items:p.data,total:p.data.length,hasMore:!1}:await C2({projectId:G1}).listAgents({projectId:G1,organizationId:u2,limit:50,offset:0}),m=[`# ${f.meta.description??"Agent List"}`,"",`> ${f.meta.key} v${f.meta.version}`,"",`**Total Agents:** ${q.total}`,"","## Agents",""],Z={};for(let M of q.items){let w=M.status;if(Z[w])Z[w].push(M);else Z[w]=[M]}for(let[M,w]of Object.entries(Z)){m.push(`### ${M} (${w.length})`),m.push("");for(let y of w)if(m.push(`- **${y.name}** (${y.modelProvider}/${y.modelName})`),y.description)m.push(` > ${y.description}`);m.push("")}return{mimeType:"text/markdown",body:m.join(`
2
- `)}}};import{Button as S2,EmptyState as i2,EntityCard as c2,ErrorState as o2,LoaderBlock as g2,StatCard as R0,StatCardGroup as l2,StatusChip as n2}from"@contractspec/lib.design-system";import{jsx as V,jsxs as Y0}from"react/jsx-runtime";function j2(f){switch(f){case"ACTIVE":return"success";case"PAUSED":case"DRAFT":return"warning";case"ARCHIVED":return"neutral";default:return"neutral"}}function c0(){let{data:f,loading:p,error:q,stats:m,refetch:Z}=o();if(p&&!f)return V(g2,{label:"Loading agents..."});if(q)return V(o2,{title:"Failed to load agents",description:q.message,onRetry:Z,retryLabel:"Retry"});if(!f?.items.length)return V(i2,{title:"No agents yet",description:"Create your first AI agent to get started."});return Y0("div",{className:"space-y-6",children:[m&&Y0(l2,{children:[V(R0,{label:"Total Agents",value:m.total}),V(R0,{label:"Active",value:m.active}),V(R0,{label:"Paused",value:m.paused}),V(R0,{label:"Draft",value:m.draft})]}),Y0("div",{className:"flex items-center justify-between",children:[V("h3",{className:"font-semibold text-lg",children:"Agents"}),V(S2,{onPress:()=>alert("Create Agent clicked!"),children:"Create Agent"})]}),V("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:f.items.map((M)=>V(c2,{cardTitle:M.name,cardSubtitle:M.modelName,meta:V("p",{className:"text-muted-foreground text-sm",children:M.description}),chips:V(n2,{tone:j2(M.status),label:M.status}),footer:Y0("span",{className:"text-muted-foreground text-xs",children:["Created ",M.createdAt.toLocaleDateString()]}),onClick:()=>alert(`View agent: ${M.name}`)},M.id))})]})}import{jsx as x2}from"react/jsx-runtime";var e2={target:"react",render:async(f)=>{if(f.source.type!=="component")throw Error("AgentListRenderer: expected component source");if(f.source.componentKey!=="AgentListView")throw Error(`AgentListRenderer: unknown component ${f.source.componentKey}`);return x2(c0,{})}};import{getFallbackAgentConsoleDashboardData as a2}from"@contractspec/example.agent-console/shared";function t2(f){if(f<1000)return`${f}ms`;if(f<60000)return`${(f/1000).toFixed(1)}s`;return`${(f/60000).toFixed(1)}m`}var s2={target:"markdown",render:async(f,p)=>{if(f.source.type!=="component"||f.source.componentKey!=="AgentConsoleDashboard")throw Error("agentDashboardMarkdownRenderer: not AgentConsoleDashboard");let q=p?.data??await a2(),m=q.agents.filter((D)=>D.status==="ACTIVE").length,Z=q.runs.filter((D)=>D.status==="COMPLETED").length,M=q.runs.filter((D)=>D.status==="FAILED").length,w=q.runs.reduce((D,Y)=>D+(Y.totalTokens??0),0),y=q.runs.reduce((D,Y)=>D+(Y.estimatedCostUsd??0),0),U=q.tools.filter((D)=>D.status==="ACTIVE").length,I=c(q.runs),N=["# Agent Console Dashboard","","> AI agent operations overview","","## Summary","","| Metric | Value |","|--------|-------|",`| Total Agents | ${q.summary.totalAgents} |`,`| Active Agents | ${m} |`,`| Total Runs | ${q.summary.totalRuns} |`,`| Completed Runs | ${Z} |`,`| Failed Runs | ${M} |`,`| Total Tokens | ${w.toLocaleString()} |`,`| Total Cost | $${y.toFixed(4)} |`,`| Total Tools | ${q.summary.totalTools} |`,`| Active Tools | ${U} |`,"","## Agents",""];if(q.agents.length===0)N.push("_No agents configured._");else{N.push("| Agent | Model | Status | Description |"),N.push("|-------|-------|--------|-------------|");for(let D of q.agents.slice(0,5))N.push(`| ${D.name} | ${D.modelProvider}/${D.modelName} | ${D.status} | ${D.description??"-"} |`);if(q.agents.length>5)N.push(`| ... | ... | ... | _${q.summary.totalAgents-5} more_ |`)}if(N.push(""),N.push("## Recent Runs"),N.push(""),q.runs.length===0)N.push("_No runs yet._");else{N.push("| Run ID | Agent | Status | Duration | Tokens | Cost |"),N.push("|--------|-------|--------|----------|--------|------|");for(let D of q.runs.slice(0,5))N.push(`| ${D.id.slice(-8)} | ${D.agentName} | ${D.status} | ${D.durationMs?t2(D.durationMs):"-"} | ${D.totalTokens??0} | $${(D.estimatedCostUsd??0).toFixed(4)} |`);if(q.runs.length>5)N.push(`| ... | ... | ... | ... | ... | _${q.summary.totalRuns-5} more_ |`)}N.push(""),N.push("## Visualization Overview"),N.push("");for(let D of I)N.push(`- **${D.title}** via \`${D.spec.meta.key}\``);N.push(""),N.push("## Tools"),N.push("");let T={};for(let D of q.tools){let Y=D.category;if(!T[Y])T[Y]=[];T[Y].push(D)}if(Object.keys(T).length===0)N.push("_No tools registered._");else{N.push("| Category | Tools | Active |"),N.push("|----------|-------|--------|");for(let[D,Y]of Object.entries(T).sort()){let z=Y.filter((d)=>d.status==="ACTIVE").length;N.push(`| ${D} | ${Y.length} | ${z} |`)}}return{mimeType:"text/markdown",body:N.join(`
3
- `)}}};import{AGENT_CONSOLE_DEMO_PROJECT_ID as O1,createAgentConsoleDemoHandlers as ff}from"@contractspec/example.agent-console/shared";function pf(f){if(f<1000)return`${f}ms`;if(f<60000)return`${(f/1000).toFixed(1)}s`;return`${(f/60000).toFixed(1)}m`}var mf={target:"markdown",render:async(f,p)=>{if(f.source.type!=="component"||f.source.componentKey!=="RunListView")throw Error("runListMarkdownRenderer: not RunListView");let q=Array.isArray(p?.data)?{items:p.data,total:p.data.length,hasMore:!1}:await ff({projectId:O1}).listRuns({projectId:O1,limit:20,offset:0}),m=[`# ${f.meta.description??"Agent Runs"}`,"",`> ${f.meta.key} v${f.meta.version}`,"",`**Total Runs:** ${q.total}`,"","## Recent Runs","","| ID | Agent | Status | Duration | Tokens | Cost |","| --- | --- | --- | --- | --- | --- |"];for(let Z of q.items.slice(0,10))m.push(`| ${Z.id.slice(-8)} | ${Z.agentName} | ${Z.status} | ${Z.durationMs?pf(Z.durationMs):"-"} | ${Z.totalTokens} | $${Z.estimatedCostUsd?.toFixed(4)??"-"} |`);return{mimeType:"text/markdown",body:m.join(`
4
- `)}}};import{AGENT_CONSOLE_DEMO_ORGANIZATION_ID as wf,AGENT_CONSOLE_DEMO_PROJECT_ID as J1,createAgentConsoleDemoHandlers as Zf}from"@contractspec/example.agent-console/shared";var qf={target:"markdown",render:async(f,p)=>{if(f.source.type!=="component"||f.source.componentKey!=="ToolRegistryView")throw Error("toolRegistryMarkdownRenderer: not ToolRegistryView");let q=Array.isArray(p?.data)?{items:p.data,total:p.data.length,hasMore:!1}:await Zf({projectId:J1}).listTools({projectId:J1,organizationId:wf,limit:50,offset:0}),m=[`# ${f.meta.description??"Tool Registry"}`,"",`> ${f.meta.key} v${f.meta.version}`,"",`**Total Tools:** ${q.total}`,""],Z={};for(let M of q.items){let w=M.category;if(!Z[w])Z[w]=[];Z[w].push(M)}for(let[M,w]of Object.entries(Z).sort()){m.push(`## ${M} (${w.length})`),m.push("");for(let y of w){let U=y.status==="ACTIVE"?"✅":y.status==="DEPRECATED"?"⚠️":"❌";if(m.push(`### ${U} ${y.name} v${y.version}`),m.push(""),m.push(`> \`${y.id}\``),m.push(""),y.description)m.push(y.description),m.push("")}}return{mimeType:"text/markdown",body:m.join(`
5
- `)}}};export{S0 as useToolList,a as useRunList,E0 as useAgentMutations,o as useAgentList,qf as toolRegistryMarkdownRenderer,mf as runListMarkdownRenderer,e2 as agentListReactRenderer,r2 as agentListMarkdownRenderer,s2 as agentDashboardMarkdownRenderer,L2 as agentConsoleReadOnlyOverlay,S4 as agentConsoleOverlays,b2 as agentConsoleDemoOverlay,I0 as ToolRegistryView,Q0 as RunListView,H4 as ExecutionConsoleHost,v0 as CreateAgentModal,I0 as AgentToolRegistry,Q0 as AgentRunList,c0 as AgentListView,Y4 as AgentDashboard,q1 as AgentConsolePreview,k0 as AgentActionsModal};
1
+ import{defineVisualization as R0,VisualizationRegistry as _1}from"@contractspec/lib.contracts-spec/visualizations";var J0={key:"agent.run.list",version:"1.0.0"},W0={version:"1.0.0",domain:"ai-ops",stability:"experimental",owners:["@example.agent-console"],tags:["agent-console","visualization","operations"]},F0=R0({meta:{...W0,key:"agent-console.visualization.run-status",title:"Run Status Breakdown",description:"Distribution of run outcomes across the current sample.",goal:"Make operational success and failure mix visible at a glance.",context:"Agent operations overview."},source:{primary:J0,resultPath:"data"},visualization:{kind:"pie",nameDimension:"status",valueMeasure:"runs",dimensions:[{key:"status",label:"Status",dataPath:"status",type:"category"}],measures:[{key:"runs",label:"Runs",dataPath:"runs",format:"number"}],table:{caption:"Run counts by status."}}}),X0=R0({meta:{...W0,key:"agent-console.visualization.run-activity",title:"Recent Run Activity",description:"Daily run volume across the current sample.",goal:"Show whether agent activity is rising or slowing down.",context:"Operations trend monitoring."},source:{primary:J0,resultPath:"data"},visualization:{kind:"cartesian",variant:"line",xDimension:"day",yMeasures:["runs"],dimensions:[{key:"day",label:"Day",dataPath:"day",type:"time"}],measures:[{key:"runs",label:"Runs",dataPath:"runs",format:"number",color:"#0f766e"}],table:{caption:"Daily run counts."}}}),h0=R0({meta:{...W0,key:"agent-console.visualization.run-efficiency",title:"Duration vs Tokens",description:"Scatter chart comparing token consumption and runtime.",goal:"Reveal outlier runs that are slow relative to their token usage.",context:"Operational performance diagnostics."},source:{primary:J0,resultPath:"data"},visualization:{kind:"cartesian",variant:"scatter",xDimension:"totalTokens",yMeasures:["durationMs"],dimensions:[{key:"totalTokens",label:"Total Tokens",dataPath:"totalTokens",type:"number"}],measures:[{key:"durationMs",label:"Duration",dataPath:"durationMs",format:"duration",color:"#7c3aed"},{key:"estimatedCostUsd",label:"Cost",dataPath:"estimatedCostUsd",format:"currency"}],series:[{key:"runs",label:"Runs",measure:"durationMs",type:"scatter",color:"#7c3aed"}],table:{caption:"Run duration versus token usage."}}}),o0=[F0,X0,h0],Of=new _1([...o0]),Pf=o0.map((f)=>({key:f.meta.key,version:f.meta.version}));function n0(f){if(!f)return"unknown";return f.toISOString().slice(0,10)}function g(f){let p=new Map,w=new Map;for(let m of f)p.set(m.status,(p.get(m.status)??0)+1),w.set(n0(m.startedAt??m.queuedAt),(w.get(n0(m.startedAt??m.queuedAt))??0)+1);return[{key:"run-status",spec:F0,data:{data:Array.from(p.entries()).map(([m,q])=>({status:m,runs:q}))},title:"Run Status Breakdown",description:"Completed, failed, running, and cancelled runs in the sample.",height:260},{key:"run-activity",spec:X0,data:{data:Array.from(w.entries()).sort(([m],[q])=>m.localeCompare(q)).map(([m,q])=>({day:m,runs:q}))},title:"Recent Run Activity",description:"Daily run volume derived from run start times."},{key:"run-efficiency",spec:h0,data:{data:f.filter((m)=>typeof m.durationMs==="number").map((m)=>({totalTokens:m.totalTokens,durationMs:m.durationMs??0,estimatedCostUsd:m.estimatedCostUsd}))},title:"Duration vs Tokens",description:"Operational scatter plot for spotting inefficient runs."}]}var s=[{id:"agent-1",organizationId:"demo-org",name:"Customer Support Bot",slug:"customer-support-bot",description:"Handles tier-1 customer inquiries and routes complex issues.",status:"ACTIVE",modelProvider:"OPENAI",modelName:"gpt-4o-mini",modelConfig:{temperature:0.7},systemPrompt:"You are a helpful customer support assistant.",toolChoice:"auto",maxIterations:10,timeoutMs:120000,version:"1.0.0",tags:["support","tier-1"],createdAt:new Date("2024-01-15T10:00:00Z"),updatedAt:new Date("2024-03-20T14:30:00Z")},{id:"agent-2",organizationId:"demo-org",name:"Code Review Assistant",slug:"code-review-assistant",description:"Reviews pull requests and provides actionable feedback.",status:"ACTIVE",modelProvider:"ANTHROPIC",modelName:"claude-sonnet-4-20250514",modelConfig:{temperature:0.3},systemPrompt:"You are a code review expert.",toolChoice:"auto",maxIterations:15,timeoutMs:180000,version:"2.1.0",tags:["code","review","dev"],createdAt:new Date("2024-02-10T09:00:00Z"),updatedAt:new Date("2024-04-05T11:15:00Z")},{id:"agent-3",organizationId:"demo-org",name:"Data Analyst",slug:"data-analyst",description:"Queries databases and generates insights from data.",status:"PAUSED",modelProvider:"OPENAI",modelName:"gpt-4o",modelConfig:{temperature:0.5},systemPrompt:"You are a data analyst expert in SQL and analytics.",toolChoice:"required",maxIterations:20,timeoutMs:300000,version:"1.2.0",tags:["data","analytics","sql"],createdAt:new Date("2024-03-01T08:00:00Z"),updatedAt:new Date("2024-04-10T16:45:00Z")},{id:"agent-4",organizationId:"demo-org",name:"Meeting Scheduler",slug:"meeting-scheduler",description:"Schedules meetings and manages calendar conflicts.",status:"DRAFT",modelProvider:"GOOGLE",modelName:"gemini-2.0-flash",modelConfig:{temperature:0.2},systemPrompt:"You help schedule and organize meetings efficiently.",toolChoice:"auto",maxIterations:5,timeoutMs:60000,version:"0.1.0",tags:["calendar","scheduling"],createdAt:new Date("2024-04-01T12:00:00Z"),updatedAt:new Date("2024-04-01T12:00:00Z")}];var f0=[{id:"tool-1",organizationId:"demo-org",name:"Web Search",slug:"web-search",description:"Search the web for real-time information using Brave API.",category:"RETRIEVAL",status:"ACTIVE",parametersSchema:{type:"object",properties:{query:{type:"string",description:"Search query"},numResults:{type:"number",default:10}},required:["query"]},outputSchema:{type:"array",items:{type:"object"}},implementationType:"http",implementationConfig:{url:"https://api.brave.com/search",method:"GET"},maxInvocationsPerMinute:60,timeoutMs:30000,version:"1.0.0",tags:["search","web"],createdAt:new Date("2024-01-01T00:00:00Z"),updatedAt:new Date("2024-02-15T10:00:00Z")},{id:"tool-2",organizationId:"demo-org",name:"SQL Query",slug:"sql-query",description:"Execute read-only SQL queries against the data warehouse.",category:"RETRIEVAL",status:"ACTIVE",parametersSchema:{type:"object",properties:{query:{type:"string",description:"SQL query"},maxRows:{type:"number",default:100}},required:["query"]},outputSchema:{type:"object"},implementationType:"function",implementationConfig:{handler:"executeSqlQuery"},maxInvocationsPerMinute:30,timeoutMs:60000,version:"1.1.0",tags:["sql","database"],createdAt:new Date("2024-01-05T00:00:00Z"),updatedAt:new Date("2024-03-10T14:00:00Z")},{id:"tool-3",organizationId:"demo-org",name:"Email Sender",slug:"email-sender",description:"Send emails via SMTP or API.",category:"COMMUNICATION",status:"ACTIVE",parametersSchema:{type:"object",properties:{to:{type:"string"},subject:{type:"string"},body:{type:"string"}},required:["to","subject","body"]},implementationType:"http",implementationConfig:{url:"/api/send-email",method:"POST"},maxInvocationsPerMinute:10,timeoutMs:30000,version:"1.0.0",tags:["email","communication"],createdAt:new Date("2024-02-01T00:00:00Z"),updatedAt:new Date("2024-02-01T00:00:00Z")},{id:"tool-4",organizationId:"demo-org",name:"GitHub Integration",slug:"github-integration",description:"Interact with GitHub repositories, PRs, and issues.",category:"INTEGRATION",status:"ACTIVE",parametersSchema:{type:"object",properties:{action:{type:"string",enum:["list_prs","get_pr","create_comment"]},repo:{type:"string"},params:{type:"object"}},required:["action","repo"]},implementationType:"http",implementationConfig:{url:"https://api.github.com",auth:"token"},maxInvocationsPerMinute:100,timeoutMs:15000,version:"2.0.0",tags:["github","integration","code"],createdAt:new Date("2024-02-20T00:00:00Z"),updatedAt:new Date("2024-04-01T09:00:00Z")},{id:"tool-5",organizationId:"demo-org",name:"Calculator",slug:"calculator",description:"Perform mathematical calculations.",category:"COMPUTATION",status:"ACTIVE",parametersSchema:{type:"object",properties:{expression:{type:"string",description:"Math expression to evaluate"}},required:["expression"]},outputSchema:{type:"object",properties:{result:{type:"number"}}},implementationType:"function",implementationConfig:{handler:"evaluateMath"},timeoutMs:5000,version:"1.0.0",tags:["math","utility"],createdAt:new Date("2024-01-10T00:00:00Z"),updatedAt:new Date("2024-01-10T00:00:00Z")}];var p0=[{id:"run-1",organizationId:"demo-org",projectId:"demo-project",agentId:"agent-1",agentName:"Customer Support Bot",userId:"user-1",sessionId:"session-1",input:{message:"How do I reset my password?",context:{}},output:{response:"You can reset your password by clicking..."},status:"COMPLETED",totalTokens:1250,promptTokens:800,completionTokens:450,totalIterations:3,durationMs:4500,estimatedCostUsd:0.0025,queuedAt:new Date("2024-04-15T10:00:00Z"),startedAt:new Date("2024-04-15T10:00:01Z"),completedAt:new Date("2024-04-15T10:00:05Z"),steps:[],logs:[]},{id:"run-2",organizationId:"demo-org",projectId:"demo-project",agentId:"agent-2",agentName:"Code Review Assistant",userId:"user-2",input:{message:"Review PR #123",context:{prNumber:123}},status:"IN_PROGRESS",totalTokens:3500,promptTokens:3000,completionTokens:500,totalIterations:5,queuedAt:new Date("2024-04-15T10:30:00Z"),startedAt:new Date("2024-04-15T10:30:02Z"),steps:[],logs:[]},{id:"run-3",organizationId:"demo-org",projectId:"demo-project",agentId:"agent-1",agentName:"Customer Support Bot",userId:"user-1",input:{message:"What are your business hours?"},output:{response:"Our business hours are 9 AM to 5 PM EST..."},status:"COMPLETED",totalTokens:800,promptTokens:500,completionTokens:300,totalIterations:2,durationMs:2100,estimatedCostUsd:0.0012,queuedAt:new Date("2024-04-15T09:00:00Z"),startedAt:new Date("2024-04-15T09:00:01Z"),completedAt:new Date("2024-04-15T09:00:03Z"),steps:[],logs:[]},{id:"run-4",organizationId:"demo-org",projectId:"demo-project",agentId:"agent-3",agentName:"Data Analyst",userId:"user-3",input:{message:"Generate sales report for Q1"},status:"FAILED",errorMessage:"Database connection timeout",errorCode:"DB_TIMEOUT",totalTokens:2000,promptTokens:1500,completionTokens:500,totalIterations:8,durationMs:45000,queuedAt:new Date("2024-04-14T15:00:00Z"),startedAt:new Date("2024-04-14T15:00:05Z"),completedAt:new Date("2024-04-14T15:00:50Z"),steps:[],logs:[]},{id:"run-5",organizationId:"demo-org",projectId:"demo-project",agentId:"agent-2",agentName:"Code Review Assistant",userId:"user-2",input:{message:"Review PR #120"},output:{response:"Code review complete. 3 suggestions..."},status:"COMPLETED",totalTokens:5200,promptTokens:4000,completionTokens:1200,totalIterations:7,durationMs:15000,estimatedCostUsd:0.0156,queuedAt:new Date("2024-04-14T11:00:00Z"),startedAt:new Date("2024-04-14T11:00:03Z"),completedAt:new Date("2024-04-14T11:00:18Z"),steps:[],logs:[]}];var j0=[{id:"runs",label:"Runs",icon:"▶"},{id:"agents",label:"Agents",icon:"\uD83E\uDD16"},{id:"tools",label:"Tools",icon:"\uD83D\uDD27"},{id:"metrics",label:"Metrics",icon:"\uD83D\uDCCA"}];function x0(f){let p=f.filter((M)=>M.status==="COMPLETED").length,w=f.reduce((M,Z)=>M+Z.totalTokens,0),m=f.reduce((M,Z)=>M+(Z.estimatedCostUsd??0),0),q=f.map((M)=>M.durationMs).filter((M)=>typeof M==="number");return{averageDurationMs:q.length>0?q.reduce((M,Z)=>M+Z,0)/q.length:0,completedRuns:p,successRate:f.length>0?p/f.length:0,totalCostUsd:m,totalRuns:f.length,totalTokens:w}}function m0(f){if(f<1000)return f.toString();if(f<1e6)return`${(f/1000).toFixed(1)}K`;return`${(f/1e6).toFixed(2)}M`}function e0(f){if(!f)return"-";if(f<1000)return`${f}ms`;if(f<60000)return`${(f/1000).toFixed(1)}s`;return`${(f/60000).toFixed(1)}m`}function a0(f){return new Intl.DateTimeFormat("en-US",{dateStyle:"medium",timeStyle:"short"}).format(f)}function t0(f){if(typeof document>"u")return{onPress:f};return{onClick:f}}import{Badge as d1}from"@contractspec/lib.ui-kit-web/ui/badge";import{Card as H1,CardContent as V1}from"@contractspec/lib.ui-kit-web/ui/card";import{Box as k1,HStack as s0,VStack as E1}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as Z0}from"@contractspec/lib.ui-kit-web/ui/text";import{jsx as v,jsxs as _0}from"react/jsx-runtime";function w0({getKey:f,items:p,renderItem:w}){return v(s0,{gap:"none",align:"stretch",className:"flex-wrap",children:p.map((m)=>v(k1,{gap:"none",className:"flex w-full min-w-0 p-1.5 sm:w-1/2 lg:w-1/4",children:w(m)},f(m)))})}function d0({description:f,name:p,status:w,subtitle:m}){return v(H1,{className:"h-full w-full",children:_0(V1,{className:"flex flex-col gap-2 pt-6",children:[_0(s0,{justify:"between",align:"start",children:[_0(E1,{gap:"xs",className:"flex-1",children:[v(Z0,{className:"font-semibold text-lg",children:p}),v(Z0,{className:"text-muted-foreground text-sm",children:m})]}),v(q0,{status:w})]}),v(Z0,{className:"text-muted-foreground text-sm",children:f})]})})}function q0({status:f}){return v(d1,{variant:f==="FAILED"||f==="CANCELLED"?"destructive":f==="ACTIVE"||f==="COMPLETED"?"secondary":"outline",children:v(Z0,{className:"font-semibold text-xs",children:f})})}import{Card as f1,CardContent as p1,CardHeader as B1,CardTitle as v1}from"@contractspec/lib.ui-kit-web/ui/card";import{VStack as b1}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as u}from"@contractspec/lib.ui-kit-web/ui/text";import{jsx as _,jsxs as i}from"react/jsx-runtime";function m1({metrics:f}){let p=[{label:"Total Runs",value:String(f.totalRuns),hint:`${Math.round(f.successRate*100)}% success`},{label:"Success Rate",value:`${Math.round(f.successRate*100)}%`,hint:"of all runs"},{label:"Total Tokens",value:m0(f.totalTokens),hint:"This period"},{label:"Total Cost",value:`$${f.totalCostUsd.toFixed(2)}`,hint:"This period"}];return _(w0,{items:p,getKey:(w)=>w.label,renderItem:(w)=>_(f1,{className:"h-full w-full",children:i(p1,{className:"flex flex-col gap-1 pt-6",children:[_(u,{className:"text-muted-foreground text-sm",children:w.label}),_(u,{className:"font-bold text-2xl",children:w.value}),_(u,{className:"text-muted-foreground text-sm",children:w.hint})]})})})}function Z1({agents:f}){return _(w0,{items:f,getKey:(p)=>p.id,renderItem:(p)=>_(d0,{description:p.description,name:p.name,status:p.status,subtitle:`${p.modelProvider} / ${p.modelName}`})})}function w1({tools:f}){return _(w0,{items:f,getKey:(p)=>p.id,renderItem:(p)=>_(d0,{description:p.description,name:p.name,status:p.status,subtitle:`${p.category} / ${p.implementationType}`})})}function q1({metrics:f}){return i(b1,{gap:"md",children:[_(u,{className:"font-semibold text-lg",children:"Usage Analytics"}),i(f1,{children:[_(B1,{children:_(v1,{children:_(u,{children:"Run Outcomes"})})}),i(p1,{className:"flex flex-col gap-3",children:[i(u,{children:["Completed: ",f.completedRuns]}),i(u,{children:["Failed: ",f.totalRuns-f.completedRuns]}),i(u,{children:["Average duration: ",(f.averageDurationMs/1000).toFixed(1),"s"]})]})]})]})}import{useContractTable as L1}from"@contractspec/lib.presentation-runtime-react";import{Card as u1,CardContent as S1}from"@contractspec/lib.ui-kit-web/ui/card";import{DataTable as C1}from"@contractspec/lib.ui-kit-web/ui/data-table";import{VStack as r1}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as M0}from"@contractspec/lib.ui-kit-web/ui/text";import{useMemo as i1}from"react";import{jsx as S,jsxs as c1}from"react/jsx-runtime";function M1({runs:f}){let p=i1(()=>[{id:"queuedAt",header:"Run",label:"Run",accessor:(m)=>m.queuedAt.getTime(),cell:({item:m})=>c1(r1,{gap:"xs",children:[S(M0,{className:"font-mono text-sm",children:m.id}),S(M0,{className:"text-muted-foreground text-xs",children:a0(m.queuedAt)})]}),size:180,canSort:!0,canHide:!0},{id:"agentName",header:"Agent",label:"Agent",accessorKey:"agentName",size:220,canSort:!0},{id:"status",header:"Status",label:"Status",accessorKey:"status",cell:({value:m})=>S(q0,{status:String(m)}),size:140,canSort:!0},{id:"totalTokens",header:"Tokens",label:"Tokens",accessorKey:"totalTokens",cell:({value:m})=>m0(Number(m??0)),align:"right",size:120,canSort:!0},{id:"durationMs",header:"Duration",label:"Duration",accessorKey:"durationMs",cell:({value:m})=>e0(typeof m==="number"?m:void 0),align:"right",size:130,canHide:!0}],[]),w=L1({data:f,columns:p,initialState:{pagination:{pageIndex:0,pageSize:5}},getRowId:(m)=>m.id});return S(C1,{controller:w,toolbar:S(M0,{className:"text-muted-foreground text-sm",children:"Run History"}),emptyState:S(u1,{children:S(S1,{className:"pt-6",children:S(M0,{className:"text-muted-foreground",children:"No runs yet"})})})})}import{Tabs as g1,TabsContent as N0,TabsList as l1,TabsTrigger as o1}from"@contractspec/lib.design-system";import{createVisualizationModel as n1}from"@contractspec/lib.presentation-runtime-core";import{Button as j1}from"@contractspec/lib.ui-kit-web/ui/button";import{Card as x1,CardContent as e1,CardDescription as a1,CardHeader as t1,CardTitle as s1}from"@contractspec/lib.ui-kit-web/ui/card";import{HStack as f2,VStack as D0}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as x}from"@contractspec/lib.ui-kit-web/ui/text";import{Visualization as p2}from"@contractspec/lib.ui-kit-web/ui/visualization";import{useMemo as N1}from"react";import{jsx as W,jsxs as C}from"react/jsx-runtime";function D1({agents:f=s,runs:p=p0,showHeaderAction:w=!0,tools:m=f0}){let q=N1(()=>x0(p),[p]),M=N1(()=>g(p),[p]);return C(D0,{gap:"xl",align:"stretch",children:[C(f2,{justify:"between",align:"center",className:"gap-3",children:[W(x,{className:"font-bold text-2xl",children:"AI Agent Console"}),w?W(j1,{...t0(()=>{return}),children:W(x,{children:"+ New Agent"})}):null]}),W(m1,{metrics:q}),C(D0,{gap:"md",children:[C(D0,{gap:"xs",children:[W(x,{className:"font-semibold text-lg",children:"Operational Visualizations"}),W(x,{className:"text-muted-foreground text-sm",children:"Contract-backed charts derived from recent run activity."})]}),W(D0,{gap:"md",children:M.map((Z)=>C(x1,{children:[C(t1,{children:[W(s1,{children:Z.title}),W(a1,{children:Z.description})]}),W(e1,{children:W(p2,{height:Z.height,model:n1(Z.spec,Z.data)})})]},Z.key))})]}),C(g1,{defaultValue:"runs",className:"w-full gap-4",children:[W(l1,{className:"h-auto w-full flex-wrap",children:j0.map((Z)=>W(o1,{value:Z.id,className:"min-h-8 min-w-24 flex-1",children:C(x,{children:[Z.icon," ",Z.label]})},Z.id))}),W(N0,{value:"runs",children:W(M1,{runs:p})}),W(N0,{value:"agents",children:W(Z1,{agents:f})}),W(N0,{value:"tools",children:W(w1,{tools:m})}),W(N0,{value:"metrics",children:W(q1,{metrics:q})})]})]})}import{VisualizationCard as m2,VisualizationGrid as Z2}from"@contractspec/lib.design-system";import{jsx as T0,jsxs as T1}from"react/jsx-runtime";function U1({runs:f}){let p=g(f);return T1("section",{className:"space-y-3",children:[T1("div",{children:[T0("h3",{className:"font-semibold text-lg",children:"Operational Visualizations"}),T0("p",{className:"text-muted-foreground text-sm",children:"Contract-backed charts derived from recent run activity."})]}),T0(Z2,{children:p.map((w)=>T0(m2,{data:w.data,description:w.description,height:w.height,spec:w.spec,title:w.title},w.key))})]})}import{useTemplateRuntime as w2}from"@contractspec/lib.example-shared-ui";import{useCallback as q2,useEffect as M2,useMemo as N2,useState as U0}from"react";function l(f={}){let{handlers:p,projectId:w}=w2(),{agent:m}=p,[q,M]=U0(null),[Z,D]=U0(!0),[A,G]=U0(null),[N,U]=U0(1),T=q2(async()=>{D(!0),G(null);try{let K=await m.listAgents({projectId:w,search:f.search,status:f.status==="all"?void 0:f.status,limit:f.limit??20,offset:(N-1)*(f.limit??20)});M(K)}catch(K){G(K instanceof Error?K:Error("Unknown error"))}finally{D(!1)}},[m,w,f.search,f.status,f.limit,N]);M2(()=>{T()},[T]);let P=N2(()=>{if(!q)return null;return{total:q.total,active:q.items.filter((K)=>K.status==="ACTIVE").length,paused:q.items.filter((K)=>K.status==="PAUSED").length,draft:q.items.filter((K)=>K.status==="DRAFT").length}},[q]);return{data:q,loading:Z,error:A,stats:P,page:N,refetch:T,nextPage:()=>U((K)=>K+1),prevPage:()=>N>1&&U((K)=>K-1)}}import{useTemplateRuntime as U2}from"@contractspec/lib.example-shared-ui";import{useCallback as o,useState as V0}from"react";var H0="demo-org",d4="agent-console-demo";function H4(f){return f.toLowerCase().trim().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}function V4(f){return{...f}}function k4(f){return{...f}}function E4(f){return{...f}}function B4(){let f=0,p=Date.parse("2026-03-20T09:00:00.000Z");return()=>new Date(p+f++*60000)}function D2(f){return f.toLowerCase()}function T2(f){return f==="IN_PROGRESS"?"RUNNING":f}function v4(f,p){let w=s.map((Z)=>({id:Z.id,projectId:f,organizationId:p,name:Z.name,slug:Z.slug,description:Z.description,modelProvider:D2(Z.modelProvider),modelName:Z.modelName,systemPrompt:Z.systemPrompt,temperature:typeof Z.modelConfig?.temperature==="number"?Z.modelConfig.temperature:0.4,maxTokens:8192,status:Z.status,createdAt:Z.createdAt,updatedAt:Z.updatedAt})),m=f0.map((Z)=>({id:Z.id,projectId:f,organizationId:p,name:Z.name,description:Z.description,version:Z.version,category:Z.category,status:Z.status,inputSchema:JSON.stringify(Z.parametersSchema),outputSchema:Z.outputSchema?JSON.stringify(Z.outputSchema):void 0,endpoint:typeof Z.implementationConfig?.url==="string"?Z.implementationConfig.url:void 0,createdAt:Z.createdAt,updatedAt:Z.updatedAt})),q=new Map(w.map((Z)=>[Z.id,Z.name])),M=p0.map((Z)=>({id:Z.id,projectId:f,agentId:Z.agentId,agentName:q.get(Z.agentId)??Z.agentName??"Unknown agent",status:T2(Z.status),input:JSON.stringify(Z.input),output:Z.output?JSON.stringify(Z.output):void 0,totalTokens:Z.totalTokens,promptTokens:Z.promptTokens,completionTokens:Z.completionTokens,estimatedCostUsd:Z.estimatedCostUsd??0,durationMs:Z.durationMs,errorMessage:Z.errorMessage,queuedAt:Z.queuedAt,startedAt:Z.startedAt,completedAt:Z.completedAt}));return{agents:w,tools:m,runs:M}}function b4(f){let p=f.length,w=f.filter((q)=>q.status==="COMPLETED").length,m=f.map((q)=>q.durationMs).filter((q)=>typeof q==="number");return{totalRuns:p,successRate:p===0?0:w/p,averageDurationMs:m.length===0?0:Math.round(m.reduce((q,M)=>q+M,0)/m.length),totalTokens:f.reduce((q,M)=>q+M.totalTokens,0),totalCostUsd:f.reduce((q,M)=>q+M.estimatedCostUsd,0)}}function k0(f,p){return f instanceof Error?f:Error(p)}function E0(f={}){let{handlers:p,projectId:w}=U2(),{agent:m}=p,[q,M]=V0({loading:!1,error:null,data:null}),[Z,D]=V0({loading:!1,error:null,data:null}),[A,G]=V0({loading:!1,error:null,data:null}),N=o(async(Y)=>{M({loading:!0,error:null,data:null});try{let O=await m.createAgent(Y,{projectId:w,organizationId:H0});return M({loading:!1,error:null,data:O}),f.onSuccess?.(),O}catch(O){let z=k0(O,"Failed to create agent");throw M({loading:!1,error:z,data:null}),f.onError?.(z),z}},[m,w,f]),U=o(async(Y)=>{D({loading:!0,error:null,data:null});try{let O=await m.updateAgent(Y);return D({loading:!1,error:null,data:O}),f.onSuccess?.(),O}catch(O){let z=k0(O,"Failed to update agent");throw D({loading:!1,error:z,data:null}),f.onError?.(z),z}},[m,f]),T=o(async(Y)=>{return U({id:Y,status:"ACTIVE"})},[U]),P=o(async(Y)=>{return U({id:Y,status:"PAUSED"})},[U]),K=o(async(Y)=>{return U({id:Y,status:"ARCHIVED"})},[U]),I=o(async(Y)=>{G({loading:!0,error:null,data:null});try{let O=await m.executeAgent({agentId:Y.agentId,message:Y.message,context:{projectId:w,organizationId:H0}});return G({loading:!1,error:null,data:O}),f.onSuccess?.(),O}catch(O){let z=k0(O,"Failed to execute agent");throw G({loading:!1,error:z,data:null}),f.onError?.(z),z}},[m,w,f]);return{createAgent:N,updateAgent:U,activateAgent:T,pauseAgent:P,archiveAgent:K,executeAgent:I,createState:q,updateState:Z,executeState:A,isLoading:q.loading||Z.loading||A.loading}}import{useTemplateRuntime as y2}from"@contractspec/lib.example-shared-ui";import{useCallback as z2,useEffect as K2,useState as e}from"react";function a(f={}){let{handlers:p,projectId:w}=y2(),{agent:m}=p,[q,M]=e(null),[Z,D]=e(null),[A,G]=e(!0),[N,U]=e(null),[T,P]=e(0),K=f.pageSize??f.limit??20,I=f.pageIndex??T,[Y]=f.sorting??[],O=z2(async()=>{G(!0),U(null);try{let[y,R]=await Promise.all([m.listRuns({projectId:w,agentId:f.agentId,status:f.status==="all"?void 0:f.status,sortBy:Y?.id,sortDirection:Y?Y.desc?"desc":"asc":void 0,limit:K,offset:I*K}),m.getRunMetrics({projectId:w,agentId:f.agentId})]);M(y),D(R)}catch(y){U(y instanceof Error?y:Error("Unknown error"))}finally{G(!1)}},[m,I,K,w,f.agentId,f.status,Y?.desc,Y?.id]);K2(()=>{O()},[O]);let z=f.pageIndex!==void 0;return{data:q,metrics:Z,loading:A,error:N,page:I+1,pageIndex:I,pageSize:K,refetch:O,nextPage:z?void 0:()=>P((y)=>y+1),prevPage:z?void 0:()=>P((y)=>Math.max(0,y-1))}}import{Button as k}from"@contractspec/lib.design-system";import{useState as y0}from"react";import{jsx as J,jsxs as X}from"react/jsx-runtime";function Q2(f){switch(f){case"ACTIVE":return"text-green-600 bg-green-100 dark:text-green-400 dark:bg-green-900/30";case"DRAFT":return"text-blue-600 bg-blue-100 dark:text-blue-400 dark:bg-blue-900/30";case"PAUSED":return"text-yellow-600 bg-yellow-100 dark:text-yellow-400 dark:bg-yellow-900/30";case"ARCHIVED":return"text-gray-600 bg-gray-100 dark:text-gray-400 dark:bg-gray-700";default:return"text-gray-600 bg-gray-100"}}function B0({isOpen:f,agent:p,onClose:w,onActivate:m,onPause:q,onArchive:M,onExecute:Z,isLoading:D=!1}){let[A,G]=y0("menu"),[N,U]=y0(""),[T,P]=y0(null),[K,I]=y0(null),Y=()=>{G("menu"),U(""),P(null),I(null)},O=()=>{Y(),w()},z=async()=>{if(!p)return;if(I(null),!N.trim()){I("Please enter a message");return}try{await Z(p.id,N.trim()),O()}catch(R){I(R instanceof Error?R.message:"Failed to execute agent")}},y=async(R)=>{if(!p)return;I(null);try{switch(R){case"activate":await m(p.id);break;case"pause":await q(p.id);break;case"archive":await M(p.id);break}O()}catch(L){I(L instanceof Error?L.message:`Failed to ${R} agent`)}};if(!f||!p)return null;return X("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[J("div",{className:"absolute inset-0 bg-background/80 backdrop-blur-sm",onClick:O,role:"button",tabIndex:0,onKeyDown:(R)=>{if(R.key==="Enter"||R.key===" ")O()},"aria-label":"Close modal"}),X("div",{className:"relative z-10 w-full max-w-md rounded-xl border border-border bg-card p-6 shadow-xl",children:[X("div",{className:"mb-4 border-border border-b pb-4",children:[J("h2",{className:"font-semibold text-xl",children:p.name}),X("div",{className:"mt-1 flex items-center gap-2",children:[X("span",{className:"text-muted-foreground text-sm",children:[p.modelProvider," / ",p.modelName]}),J("span",{className:`rounded-full px-2 py-0.5 font-medium text-xs ${Q2(p.status)}`,children:p.status})]}),p.description&&J("p",{className:"mt-2 text-muted-foreground text-sm",children:p.description})]}),A==="menu"&&X("div",{className:"space-y-3",children:[p.status==="ACTIVE"&&X(k,{className:"w-full justify-start",variant:"ghost",onPress:()=>G("execute"),children:[J("span",{className:"mr-2",children:"▶️"})," Execute Agent"]}),(p.status==="DRAFT"||p.status==="PAUSED")&&X(k,{className:"w-full justify-start",variant:"ghost",onPress:()=>y("activate"),disabled:D,children:[J("span",{className:"mr-2",children:"\uD83D\uDFE2"})," Activate Agent"]}),p.status==="ACTIVE"&&X(k,{className:"w-full justify-start",variant:"ghost",onPress:()=>y("pause"),disabled:D,children:[J("span",{className:"mr-2",children:"⏸️"})," Pause Agent"]}),p.status!=="ARCHIVED"&&X(k,{className:"w-full justify-start text-yellow-600 hover:text-yellow-700",variant:"ghost",onPress:()=>{P("archive"),G("confirm")},children:[J("span",{className:"mr-2",children:"\uD83D\uDCE6"})," Archive Agent"]}),p.status==="ARCHIVED"&&X(k,{className:"w-full justify-start",variant:"ghost",onPress:()=>y("activate"),disabled:D,children:[J("span",{className:"mr-2",children:"\uD83D\uDD04"})," Restore Agent"]}),K&&J("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:K}),J("div",{className:"border-border border-t pt-3",children:J(k,{className:"w-full",variant:"outline",onPress:O,children:"Close"})})]}),A==="execute"&&X("div",{className:"space-y-4",children:[X("div",{children:[J("label",{htmlFor:"execute-message",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Message *"}),J("textarea",{id:"execute-message",value:N,onChange:(R)=>U(R.target.value),placeholder:"Enter your message to the agent...",rows:4,disabled:D,className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50"})]}),K&&J("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:K}),X("div",{className:"flex justify-end gap-3 pt-2",children:[J(k,{variant:"ghost",onPress:()=>G("menu"),disabled:D,children:"Back"}),J(k,{onPress:z,disabled:D,children:D?"Executing...":"▶️ Execute"})]})]}),A==="confirm"&&T==="archive"&&X("div",{className:"space-y-4",children:[X("p",{className:"text-muted-foreground",children:["Are you sure you want to archive"," ",J("span",{className:"font-medium text-foreground",children:p.name}),"?"]}),J("p",{className:"text-muted-foreground text-sm",children:"Archived agents cannot be executed but can be restored later."}),K&&J("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:K}),X("div",{className:"flex justify-end gap-3 pt-2",children:[J(k,{variant:"ghost",onPress:()=>G("menu"),disabled:D,children:"Cancel"}),J(k,{onPress:()=>y("archive"),disabled:D,children:D?"Archiving...":"\uD83D\uDCE6 Archive"})]})]})]})]})}import{Button as y1,Input as $2}from"@contractspec/lib.design-system";import{useState as n}from"react";import{jsx as F,jsxs as E}from"react/jsx-runtime";var v0=[{value:"openai",label:"OpenAI",models:["gpt-5.4","gpt-5-mini","gpt-4o","gpt-4-turbo","gpt-3.5-turbo"]},{value:"anthropic",label:"Anthropic",models:["claude-sonnet-4-6","claude-opus-4-6","claude-haiku-4-5"]},{value:"google",label:"Google",models:["gemini-2.5-flash","gemini-2.5-pro","gemini-pro","gemini-ultra"]},{value:"mistral",label:"Mistral",models:["mistral-large-2512","mistral-large-latest","mistral-medium-latest","mistral-small-latest"]}];function b0({isOpen:f,onClose:p,onSubmit:w,isLoading:m=!1}){let[q,M]=n(""),[Z,D]=n(""),[A,G]=n("openai"),[N,U]=n("gpt-5.4"),[T,P]=n(""),[K,I]=n(null),Y=v0.find((y)=>y.value===A),O=async(y)=>{if(y.preventDefault(),I(null),!q.trim()){I("Agent name is required");return}try{await w({name:q.trim(),description:Z.trim()||void 0,modelProvider:A,modelName:N,systemPrompt:T.trim()||void 0}),M(""),D(""),G("openai"),U("gpt-5.4"),P(""),p()}catch(R){I(R instanceof Error?R.message:"Failed to create agent")}},z=(y)=>{G(y);let R=v0.find((L)=>L.value===y);if(R)U(R.models[0])};if(!f)return null;return E("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[F("div",{className:"absolute inset-0 bg-background/80 backdrop-blur-sm",onClick:p,role:"button",tabIndex:0,onKeyDown:(y)=>{if(y.key==="Enter"||y.key===" ")p()},"aria-label":"Close modal"}),E("div",{className:"relative z-10 max-h-[90vh] w-full max-w-lg overflow-y-auto rounded-xl border border-border bg-card p-6 shadow-xl",children:[F("h2",{className:"mb-4 font-semibold text-xl",children:"Create New Agent"}),E("form",{onSubmit:O,className:"space-y-4",children:[E("div",{children:[F("label",{htmlFor:"agent-name",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Agent Name *"}),F($2,{id:"agent-name",value:q,onChange:(y)=>M(y.target.value),placeholder:"e.g., Customer Support Bot",disabled:m})]}),E("div",{children:[F("label",{htmlFor:"agent-description",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Description"}),F("textarea",{id:"agent-description",value:Z,onChange:(y)=>D(y.target.value),placeholder:"Describe what this agent does...",rows:2,disabled:m,className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50"})]}),E("div",{className:"flex gap-3",children:[E("div",{className:"flex-1",children:[F("label",{htmlFor:"model-provider",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Provider *"}),F("select",{id:"model-provider",value:A,onChange:(y)=>z(y.target.value),disabled:m,className:"h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50",children:v0.map((y)=>F("option",{value:y.value,children:y.label},y.value))})]}),E("div",{className:"flex-1",children:[F("label",{htmlFor:"model-name",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"Model *"}),F("select",{id:"model-name",value:N,onChange:(y)=>U(y.target.value),disabled:m,className:"h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50",children:Y?.models.map((y)=>F("option",{value:y,children:y},y))})]})]}),E("div",{children:[F("label",{htmlFor:"system-prompt",className:"mb-1 block font-medium text-muted-foreground text-sm",children:"System Prompt"}),F("textarea",{id:"system-prompt",value:T,onChange:(y)=>P(y.target.value),placeholder:"You are a helpful assistant that...",rows:4,disabled:m,className:"w-full rounded-md border border-input bg-background px-3 py-2 font-mono text-sm focus:outline-none focus:ring-2 focus:ring-ring disabled:opacity-50"}),F("p",{className:"mt-1 text-muted-foreground text-xs",children:"Instructions that define the agent's behavior"})]}),K&&F("div",{className:"rounded-md bg-destructive/10 p-3 text-destructive text-sm",children:K}),E("div",{className:"flex justify-end gap-3 pt-2",children:[F(y1,{type:"button",variant:"ghost",onPress:p,disabled:m,children:"Cancel"}),F(y1,{type:"submit",disabled:m,children:m?"Creating...":"Create Agent"})]})]})]})]})}import{Button as z0,StatusChip as Y2}from"@contractspec/lib.design-system";import{HStack as u0,VStack as L0}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as c}from"@contractspec/lib.ui-kit-web/ui/text";import{jsx as b,jsxs as V}from"react/jsx-runtime";function S0(f){switch(f){case"COMPLETED":return"success";case"RUNNING":return"warning";case"QUEUED":return"neutral";case"FAILED":case"CANCELLED":return"danger";default:return"neutral"}}function C0(f){if(!f)return"-";if(f<1000)return`${f}ms`;if(f<60000)return`${(f/1000).toFixed(1)}s`;return`${(f/60000).toFixed(1)}m`}function j(f){if(f<1000)return f.toString();if(f<1e6)return`${(f/1000).toFixed(1)}K`;return`${(f/1e6).toFixed(2)}M`}function K1(f){if(!f)return"-";return`$${f.toFixed(4)}`}function z1(f){return JSON.stringify(f??null,null,2)}function Q1({run:f}){return V(L0,{gap:"sm",className:"py-2",children:[V(u0,{justify:"between",className:"flex-wrap",children:[b(Y2,{tone:S0(f.status),label:f.status}),V(c,{className:"text-muted-foreground text-sm",children:["Queued ",f.queuedAt.toLocaleString()]})]}),V(u0,{gap:"lg",className:"flex-wrap",children:[V(c,{className:"text-muted-foreground text-sm",children:["Prompt ",j(f.promptTokens)]}),V(c,{className:"text-muted-foreground text-sm",children:["Completion ",j(f.completionTokens)]}),V(c,{className:"text-muted-foreground text-sm",children:["Duration ",C0(f.durationMs)]})]}),V(L0,{gap:"xs",children:[b(c,{className:"font-medium text-sm",children:"Input"}),b("pre",{className:"overflow-auto rounded-md bg-muted/40 p-3 text-xs",children:z1(f.input)})]}),V(L0,{gap:"xs",children:[b(c,{className:"font-medium text-sm",children:"Output"}),b("pre",{className:"overflow-auto rounded-md bg-muted/40 p-3 text-xs",children:z1(f.output??f.errorMessage??"Pending")})]})]})}function $1({controller:f,totalRuns:p}){let w=f.rows[0],m=f.columns.find((Z)=>Z.id==="queuedAt"),q=f.columns.find((Z)=>Z.id==="durationMs"),M=f.columns.find((Z)=>Z.id==="estimatedCostUsd");return V(u0,{gap:"sm",className:"flex-wrap",children:[V(c,{className:"text-muted-foreground text-sm",children:[p," runs"]}),b(z0,{variant:"outline",size:"sm",onPress:()=>w?.toggleExpanded?.(!w?.isExpanded),children:"Expand Latest Run"}),b(z0,{variant:"outline",size:"sm",onPress:()=>m?.toggleVisibility?.(!m?.visible),children:m?.visible?"Hide Time":"Show Time"}),b(z0,{variant:"outline",size:"sm",onPress:()=>q?.toggleVisibility?.(!q?.visible),children:q?.visible?"Hide Duration":"Show Duration"}),b(z0,{variant:"outline",size:"sm",onPress:()=>M?.toggleVisibility?.(!M?.visible),children:M?.visible?"Hide Cost":"Show Cost"})]})}import{StatusChip as A2}from"@contractspec/lib.design-system";import{VStack as G2}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as r0}from"@contractspec/lib.ui-kit-web/ui/text";import{jsx as K0,jsxs as O2}from"react/jsx-runtime";function Y1(){return[{id:"queuedAt",header:"Run",label:"Run",accessor:(f)=>f.queuedAt.getTime(),cell:({item:f})=>O2(G2,{gap:"xs",children:[K0(r0,{className:"font-mono text-sm",children:f.id.slice(-8)}),K0(r0,{className:"text-muted-foreground text-xs",children:f.queuedAt.toLocaleString()})]}),size:220,minSize:180,canSort:!0,canHide:!0,canResize:!0},{id:"agentName",header:"Agent",label:"Agent",accessor:(f)=>f.agentName??"Unknown Agent",cell:({value:f})=>K0(r0,{className:"font-medium",children:typeof f==="string"?f:"Unknown Agent"}),size:220,canSort:!0,canResize:!0},{id:"status",header:"Status",label:"Status",accessorKey:"status",cell:({value:f})=>{let p=typeof f==="string"?f:"QUEUED";return K0(A2,{tone:S0(p),label:p})},size:150,canSort:!0,canResize:!0},{id:"totalTokens",header:"Tokens",label:"Tokens",accessorKey:"totalTokens",cell:({value:f})=>j(Number(f??0)),align:"right",size:140,canSort:!0,canResize:!0},{id:"durationMs",header:"Duration",label:"Duration",accessorKey:"durationMs",cell:({value:f})=>C0(typeof f==="number"?f:void 0),align:"right",size:140,canSort:!0,canHide:!0,canResize:!0},{id:"estimatedCostUsd",header:"Cost",label:"Cost",accessorKey:"estimatedCostUsd",cell:({value:f})=>K1(typeof f==="number"?f:void 0),align:"right",size:140,canSort:!0,canHide:!0,canResize:!0}]}import{DataTable as P2}from"@contractspec/lib.design-system";import{useContractTable as I2}from"@contractspec/lib.presentation-runtime-react";import*as A1 from"react";import{jsx as Q0}from"react/jsx-runtime";function G1({runs:f,totalItems:p,pageIndex:w,pageSize:m,sorting:q,loading:M,onSortingChange:Z,onPaginationChange:D,onRunClick:A}){let G=A1.useMemo(()=>Y1(),[]),N=I2({data:f,columns:G,executionMode:"server",totalItems:p,state:{sorting:q,pagination:{pageIndex:w,pageSize:m}},onSortingChange:Z,onPaginationChange:D,initialState:{columnVisibility:{estimatedCostUsd:!1}},getRowId:(U)=>U.id,renderExpandedContent:(U)=>Q0(Q1,{run:U}),getCanExpand:()=>!0});return Q0(P2,{controller:N,title:"Run History",description:"Server-mode ContractSpec table with shared pagination, sorting, visibility, and expansion.",loading:M,onRowPress:(U)=>A?.(U.id),toolbar:Q0($1,{controller:N,totalRuns:p}),emptyState:Q0("div",{className:"rounded-md border border-dashed p-8 text-center text-muted-foreground text-sm",children:"No runs yet"})})}import{EmptyState as R2,ErrorState as J2,LoaderBlock as W2,StatCard as $0,StatCardGroup as F2}from"@contractspec/lib.design-system";import{useState as O1}from"react";import{jsx as r,jsxs as P1}from"react/jsx-runtime";function Y0({agentId:f,onRunClick:p}){let[w,m]=O1([{id:"queuedAt",desc:!0}]),[q,M]=O1({pageIndex:0,pageSize:3}),{data:Z,metrics:D,loading:A,error:G,refetch:N}=a({agentId:f,pageIndex:q.pageIndex,pageSize:q.pageSize,sorting:w});if(A&&!Z)return r(W2,{label:"Loading runs..."});if(G)return r(J2,{title:"Failed to load runs",description:G.message,onRetry:N,retryLabel:"Retry"});if(!Z?.items.length)return r(R2,{title:"No runs yet",description:"Execute an agent to see run history here."});return P1("div",{className:"space-y-6",children:[D?P1(F2,{children:[r($0,{label:"Total Runs",value:D.totalRuns}),r($0,{label:"Success Rate",value:`${(D.successRate*100).toFixed(1)}%`}),r($0,{label:"Total Tokens",value:j(D.totalTokens)}),r($0,{label:"Total Cost",value:`$${D.totalCostUsd.toFixed(2)}`})]}):null,r(G1,{runs:Z.items,totalItems:Z.total,pageIndex:q.pageIndex,pageSize:q.pageSize,sorting:w,loading:A,onSortingChange:(U)=>{m(U),M((T)=>({...T,pageIndex:0}))},onPaginationChange:M,onRunClick:p})]})}import{useTemplateRuntime as X2}from"@contractspec/lib.example-shared-ui";import{useCallback as h2,useEffect as _2,useMemo as d2,useState as A0}from"react";function i0(f={}){let{handlers:p,projectId:w}=X2(),{agent:m}=p,[q,M]=A0(null),[Z,D]=A0(!0),[A,G]=A0(null),[N,U]=A0(1),T=h2(async()=>{D(!0),G(null);try{let Y=await m.listTools({projectId:w,search:f.search,category:f.category,status:f.status==="all"?void 0:f.status,limit:f.limit??50,offset:(N-1)*(f.limit??50)});M(Y)}catch(Y){G(Y instanceof Error?Y:Error("Unknown error"))}finally{D(!1)}},[m,w,f.search,f.category,f.status,f.limit,N]);_2(()=>{T()},[T]);let{stats:P,groupedByCategory:K,categoryStats:I}=d2(()=>{if(!q)return{stats:null,groupedByCategory:{},categoryStats:[]};let Y=q.items,O=Y.filter((H)=>H.status==="ACTIVE").length,z=Y.filter((H)=>H.status==="DEPRECATED").length,y=Y.filter((H)=>H.status==="DISABLED").length,R={},L={};Y.forEach((H)=>{let B=H.category;if(!R[B])R[B]=[];R[B].push(H),L[B]=(L[B]||0)+1});let l0=Object.entries(L).map(([H,B])=>({category:H,count:B})).sort((H,B)=>B.count-H.count);return{stats:{total:q.total,active:O,deprecated:z,disabled:y,topCategories:l0.slice(0,5)},groupedByCategory:R,categoryStats:l0}},[q]);return{data:q,loading:Z,error:A,stats:P,groupedByCategory:K,categoryStats:I,page:N,refetch:T,nextPage:()=>U((Y)=>Y+1),prevPage:()=>N>1&&U((Y)=>Y-1)}}import{Button as H2,EmptyState as V2,EntityCard as k2,ErrorState as E2,LoaderBlock as B2,StatCard as I1,StatCardGroup as v2,StatusChip as b2}from"@contractspec/lib.design-system";import{jsx as h,jsxs as G0}from"react/jsx-runtime";var R1={RETRIEVAL:"\uD83D\uDD0D",COMPUTATION:"\uD83E\uDDEE",COMMUNICATION:"\uD83D\uDCE7",INTEGRATION:"\uD83D\uDD17",UTILITY:"\uD83D\uDEE0️",CUSTOM:"⚙️"};function L2(f){switch(f){case"ACTIVE":return"success";case"DRAFT":return"neutral";case"DEPRECATED":return"warning";case"DISABLED":return"danger";default:return"neutral"}}function O0({onToolClick:f,onCreateTool:p}){let{data:w,loading:m,error:q,groupedByCategory:M,categoryStats:Z,refetch:D}=i0();if(m&&!w)return h(B2,{label:"Loading tools..."});if(q)return h(E2,{title:"Failed to load tools",description:q.message,onRetry:D,retryLabel:"Retry"});if(!w?.items.length)return h(V2,{title:"No tools registered",description:"Create your first tool to extend agent capabilities.",primaryAction:p?h(H2,{onPress:p,children:"Create Tool"}):void 0});return G0("div",{className:"space-y-8",children:[G0(v2,{children:[h(I1,{label:"Total Tools",value:w.total}),Z.slice(0,3).map(({category:A,count:G})=>h(I1,{label:`${R1[A]??""} ${A}`,value:G},A))]}),Object.entries(M).map(([A,G])=>G0("section",{className:"space-y-4",children:[G0("div",{className:"flex items-center gap-2",children:[h("span",{className:"text-2xl",children:R1[A]}),h("h3",{className:"font-semibold text-lg",children:A}),h("span",{className:"rounded-full bg-muted px-2 py-0.5 text-muted-foreground text-xs",children:G.length})]}),h("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:G.map((N)=>h(k2,{cardTitle:N.name,cardSubtitle:`v${N.version}`,meta:h("p",{className:"text-muted-foreground text-sm",children:N.description}),chips:h(b2,{tone:L2(N.status),label:N.status}),footer:h("code",{className:"text-muted-foreground text-xs",children:N.name}),onClick:f?()=>f(N.id):void 0},N.id))})]},A))]})}import{Button as c0,StatCard as u2,StatCardGroup as S2}from"@contractspec/lib.design-system";import{useCallback as C2,useMemo as r2,useState as t}from"react";import{jsx as Q,jsxs as $}from"react/jsx-runtime";function Cp(){let[f,p]=t("runs"),[w,m]=t(!1),[q,M]=t(null),[Z,D]=t(!1),[A,G]=t(0),{data:N,metrics:U,refetch:T}=a(),{refetch:P}=l(),K=E0({onSuccess:()=>{P(),T(),G((z)=>z+1)}}),I=C2((z)=>{M(z),D(!0)},[]),Y=[{id:"runs",label:"Runs",icon:"▶"},{id:"agents",label:"Agents",icon:"\uD83E\uDD16"},{id:"tools",label:"Tools",icon:"\uD83D\uDD27"},{id:"metrics",label:"Metrics",icon:"\uD83D\uDCCA"}],O=r2(()=>{if(!U)return[{label:"Total Runs",value:"-",hint:"Loading..."},{label:"Success Rate",value:"-",hint:""},{label:"Total Tokens",value:"-",hint:""},{label:"Total Cost",value:"-",hint:""}];return[{label:"Total Runs",value:U.totalRuns.toLocaleString(),hint:`${(U.successRate*100).toFixed(0)}% success`},{label:"Success Rate",value:`${(U.successRate*100).toFixed(0)}%`,hint:"of all runs"},{label:"Total Tokens",value:U.totalTokens>=1e6?`${(U.totalTokens/1e6).toFixed(1)}M`:`${(U.totalTokens/1000).toFixed(0)}K`,hint:"This period"},{label:"Total Cost",value:`$${U.totalCostUsd.toFixed(2)}`,hint:"This period"}]},[U]);return $("div",{className:"space-y-6",children:[$("div",{className:"flex items-center justify-between",children:[Q("h2",{className:"font-bold text-2xl",children:"AI Agent Console"}),$(c0,{onPress:()=>m(!0),children:[Q("span",{className:"mr-2",children:"+"})," New Agent"]})]}),Q(S2,{children:O.map((z,y)=>Q(u2,{label:z.label,value:z.value,hint:z.hint},y))}),Q(U1,{runs:N?.items??[]}),Q("nav",{className:"flex gap-1 rounded-lg bg-muted p-1",role:"tablist",children:Y.map((z)=>$("button",{type:"button",role:"tab","aria-selected":f===z.id,onClick:()=>p(z.id),className:`flex flex-1 items-center justify-center gap-2 rounded-md px-4 py-2 font-medium text-sm transition-colors ${f===z.id?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[Q("span",{children:z.icon}),z.label]},z.id))}),$("div",{className:"min-h-[400px]",role:"tabpanel",children:[f==="runs"&&Q(Y0,{},A),f==="agents"&&Q(i2,{onAgentClick:I},A),f==="tools"&&Q(O0,{}),f==="metrics"&&Q(g2,{metrics:U})]}),Q(b0,{isOpen:w,onClose:()=>m(!1),onSubmit:async(z)=>{await K.createAgent(z)},isLoading:K.createState.loading}),Q(B0,{isOpen:Z,agent:q,onClose:()=>{D(!1),M(null)},onActivate:async(z)=>{await K.activateAgent(z)},onPause:async(z)=>{await K.pauseAgent(z)},onArchive:async(z)=>{await K.archiveAgent(z)},onExecute:async(z,y)=>{await K.executeAgent({agentId:z,message:y})},isLoading:K.isLoading})]})}function i2({onAgentClick:f}){let{data:p,loading:w,error:m,stats:q,refetch:M}=l();if(w&&!p)return Q("div",{className:"flex h-64 items-center justify-center text-muted-foreground",children:"Loading agents..."});if(m)return $("div",{className:"flex h-64 flex-col items-center justify-center text-destructive",children:[$("p",{children:["Failed to load agents: ",m.message]}),Q(c0,{variant:"outline",onPress:M,className:"mt-2",children:"Retry"})]});if(!p?.items.length)return $("div",{className:"flex h-64 flex-col items-center justify-center text-muted-foreground",children:[Q("p",{className:"font-medium text-lg",children:"No agents yet"}),Q("p",{className:"text-sm",children:"Create your first AI agent to get started."})]});return $("div",{className:"space-y-4",children:[q&&$("div",{className:"flex gap-4 text-sm",children:[$("span",{children:["Total: ",q.total]}),$("span",{className:"text-green-600",children:["Active: ",q.active]}),$("span",{className:"text-yellow-600",children:["Paused: ",q.paused]}),$("span",{className:"text-blue-600",children:["Draft: ",q.draft]})]}),Q("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:p.items.map((Z)=>Q(c2,{agent:Z,onClick:()=>f(Z)},Z.id))})]})}function c2({agent:f,onClick:p}){let w={ACTIVE:"bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",DRAFT:"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400",PAUSED:"bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400",ARCHIVED:"bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-400"};return $("div",{onClick:p,className:"cursor-pointer rounded-xl border border-border bg-card p-4 transition-all hover:shadow-md",role:"button",tabIndex:0,onKeyDown:(m)=>{if(m.key==="Enter"||m.key===" ")p()},children:[$("div",{className:"flex items-start justify-between",children:[$("div",{className:"min-w-0 flex-1",children:[Q("h3",{className:"truncate font-semibold",children:f.name}),$("p",{className:"text-muted-foreground text-sm",children:[f.modelProvider," / ",f.modelName]})]}),Q("span",{className:`rounded-full px-2 py-0.5 font-medium text-xs ${w[f.status]}`,children:f.status})]}),f.description&&Q("p",{className:"mt-2 line-clamp-2 text-muted-foreground text-sm",children:f.description}),$("div",{className:"mt-3 flex items-center justify-between",children:[Q("span",{className:"text-muted-foreground text-xs",children:f.modelName}),Q(c0,{variant:"ghost",size:"sm",onPress:p,children:"Actions"})]})]})}function g2({metrics:f}){if(!f)return Q("div",{className:"flex h-64 items-center justify-center text-muted-foreground",children:"Loading metrics..."});let p=Math.round(f.totalRuns*f.successRate),w=f.totalRuns-p;return $("div",{className:"space-y-6",children:[Q("h3",{className:"font-semibold text-lg",children:"Usage Analytics"}),$("div",{className:"grid gap-6 md:grid-cols-2",children:[$("div",{className:"rounded-xl border border-border bg-card p-4",children:[Q("h4",{className:"font-medium",children:"Run Outcomes"}),$("div",{className:"mt-4 space-y-3",children:[Q(J1,{label:"Completed",value:p,total:f.totalRuns,color:"bg-green-500"}),Q(J1,{label:"Failed",value:w,total:f.totalRuns,color:"bg-red-500"})]})]}),$("div",{className:"rounded-xl border border-border bg-card p-4",children:[Q("h4",{className:"font-medium",children:"Performance"}),$("dl",{className:"mt-4 grid grid-cols-2 gap-4",children:[$("div",{children:[Q("dt",{className:"text-muted-foreground text-sm",children:"Avg Duration"}),$("dd",{className:"font-semibold text-xl",children:[(f.averageDurationMs/1000).toFixed(1),"s"]})]}),$("div",{children:[Q("dt",{className:"text-muted-foreground text-sm",children:"Success Rate"}),$("dd",{className:"font-semibold text-xl",children:[(f.successRate*100).toFixed(0),"%"]})]})]})]})]}),$("div",{className:"rounded-xl border border-border bg-card p-4",children:[Q("h4",{className:"font-medium",children:"Key Metrics"}),$("dl",{className:"mt-4 grid gap-4 sm:grid-cols-3",children:[$("div",{children:[Q("dt",{className:"text-muted-foreground text-sm",children:"Total Runs"}),Q("dd",{className:"font-semibold text-2xl",children:f.totalRuns.toLocaleString()})]}),$("div",{children:[Q("dt",{className:"text-muted-foreground text-sm",children:"Total Tokens"}),$("dd",{className:"font-semibold text-2xl",children:[(f.totalTokens/1000).toFixed(0),"K"]})]}),$("div",{children:[Q("dt",{className:"text-muted-foreground text-sm",children:"Cost per Run"}),$("dd",{className:"font-semibold text-2xl",children:["$",f.totalRuns>0?(f.totalCostUsd/f.totalRuns).toFixed(4):"0"]})]})]})]})]})}function J1({label:f,value:p,total:w,color:m}){let q=w>0?p/w*100:0;return $("div",{children:[$("div",{className:"flex justify-between text-sm",children:[Q("span",{children:f}),$("span",{className:"text-muted-foreground",children:[p," (",q.toFixed(0),"%)"]})]}),Q("div",{className:"mt-1 h-2 overflow-hidden rounded-full bg-muted",children:Q("div",{className:`h-full ${m}`,style:{width:`${q}%`}})})]})}import{VStack as l2}from"@contractspec/lib.ui-kit-web/ui/stack";import{ExecutionLaneConsoleDemo as o2}from"@contractspec/module.execution-console";import{jsx as W1,jsxs as n2}from"react/jsx-runtime";function ep(){return n2(l2,{gap:"xl",align:"stretch",children:[W1(D1,{}),W1(o2,{})]})}var j2={overlayId:"agent-console.demo-user",version:"1.0.0",description:"Simplifies agent console for demo users",appliesTo:{feature:"agent-console",role:"demo"},modifications:[{type:"hideField",field:"modelConfig",reason:"Advanced config not relevant for demo"},{type:"hideField",field:"webhookConfig",reason:"Integration not available in demo"},{type:"renameLabel",field:"systemPrompt",newLabel:"Agent Instructions"},{type:"addBadge",position:"header",label:"Demo Mode",variant:"warning"}]},x2={overlayId:"agent-console.read-only",version:"1.0.0",description:"Read-only view for non-admin users",appliesTo:{feature:"agent-console",role:"viewer"},modifications:[{type:"hideField",field:"deleteButton",reason:"No delete permission"},{type:"hideField",field:"editButton",reason:"No edit permission"},{type:"hideField",field:"createButton",reason:"No create permission"}]},Nm=[j2,x2];import{AGENT_CONSOLE_DEMO_ORGANIZATION_ID as e2,AGENT_CONSOLE_DEMO_PROJECT_ID as F1,createAgentConsoleDemoHandlers as a2}from"@contractspec/example.agent-console/shared";var t2={target:"markdown",render:async(f,p)=>{if(f.source.type!=="component"||f.source.componentKey!=="AgentListView")throw Error("agentListMarkdownRenderer: not AgentListView");let w=Array.isArray(p?.data)?{items:p.data,total:p.data.length,hasMore:!1}:await a2({projectId:F1}).listAgents({projectId:F1,organizationId:e2,limit:50,offset:0}),m=[`# ${f.meta.description??"Agent List"}`,"",`> ${f.meta.key} v${f.meta.version}`,"",`**Total Agents:** ${w.total}`,"","## Agents",""],q={};for(let M of w.items){let Z=M.status;if(q[Z])q[Z].push(M);else q[Z]=[M]}for(let[M,Z]of Object.entries(q)){m.push(`### ${M} (${Z.length})`),m.push("");for(let D of Z)if(m.push(`- **${D.name}** (${D.modelProvider}/${D.modelName})`),D.description)m.push(` > ${D.description}`);m.push("")}return{mimeType:"text/markdown",body:m.join(`
2
+ `)}}};import{Button as s2,EmptyState as ff,EntityCard as pf,ErrorState as mf,LoaderBlock as Zf,StatCard as P0,StatCardGroup as wf,StatusChip as qf}from"@contractspec/lib.design-system";import{jsx as d,jsxs as I0}from"react/jsx-runtime";function Mf(f){switch(f){case"ACTIVE":return"success";case"PAUSED":case"DRAFT":return"warning";case"ARCHIVED":return"neutral";default:return"neutral"}}function g0(){let{data:f,loading:p,error:w,stats:m,refetch:q}=l();if(p&&!f)return d(Zf,{label:"Loading agents..."});if(w)return d(mf,{title:"Failed to load agents",description:w.message,onRetry:q,retryLabel:"Retry"});if(!f?.items.length)return d(ff,{title:"No agents yet",description:"Create your first AI agent to get started."});return I0("div",{className:"space-y-6",children:[m&&I0(wf,{children:[d(P0,{label:"Total Agents",value:m.total}),d(P0,{label:"Active",value:m.active}),d(P0,{label:"Paused",value:m.paused}),d(P0,{label:"Draft",value:m.draft})]}),I0("div",{className:"flex items-center justify-between",children:[d("h3",{className:"font-semibold text-lg",children:"Agents"}),d(s2,{onPress:()=>alert("Create Agent clicked!"),children:"Create Agent"})]}),d("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:f.items.map((M)=>d(pf,{cardTitle:M.name,cardSubtitle:M.modelName,meta:d("p",{className:"text-muted-foreground text-sm",children:M.description}),chips:d(qf,{tone:Mf(M.status),label:M.status}),footer:I0("span",{className:"text-muted-foreground text-xs",children:["Created ",M.createdAt.toLocaleDateString()]}),onClick:()=>alert(`View agent: ${M.name}`)},M.id))})]})}import{jsx as Df}from"react/jsx-runtime";var Nf={target:"react",render:async(f)=>{if(f.source.type!=="component")throw Error("AgentListRenderer: expected component source");if(f.source.componentKey!=="AgentListView")throw Error(`AgentListRenderer: unknown component ${f.source.componentKey}`);return Df(g0,{})}};import{getFallbackAgentConsoleDashboardData as Tf}from"@contractspec/example.agent-console/shared";function Uf(f){if(f<1000)return`${f}ms`;if(f<60000)return`${(f/1000).toFixed(1)}s`;return`${(f/60000).toFixed(1)}m`}var yf={target:"markdown",render:async(f,p)=>{if(f.source.type!=="component"||f.source.componentKey!=="AgentConsoleDashboard")throw Error("agentDashboardMarkdownRenderer: not AgentConsoleDashboard");let w=p?.data??await Tf(),m=w.agents.filter((T)=>T.status==="ACTIVE").length,q=w.runs.filter((T)=>T.status==="COMPLETED").length,M=w.runs.filter((T)=>T.status==="FAILED").length,Z=w.runs.reduce((T,P)=>T+(P.totalTokens??0),0),D=w.runs.reduce((T,P)=>T+(P.estimatedCostUsd??0),0),A=w.tools.filter((T)=>T.status==="ACTIVE").length,G=g(w.runs),N=["# Agent Console Dashboard","","> AI agent operations overview","","## Summary","","| Metric | Value |","|--------|-------|",`| Total Agents | ${w.summary.totalAgents} |`,`| Active Agents | ${m} |`,`| Total Runs | ${w.summary.totalRuns} |`,`| Completed Runs | ${q} |`,`| Failed Runs | ${M} |`,`| Total Tokens | ${Z.toLocaleString()} |`,`| Total Cost | $${D.toFixed(4)} |`,`| Total Tools | ${w.summary.totalTools} |`,`| Active Tools | ${A} |`,"","## Agents",""];if(w.agents.length===0)N.push("_No agents configured._");else{N.push("| Agent | Model | Status | Description |"),N.push("|-------|-------|--------|-------------|");for(let T of w.agents.slice(0,5))N.push(`| ${T.name} | ${T.modelProvider}/${T.modelName} | ${T.status} | ${T.description??"-"} |`);if(w.agents.length>5)N.push(`| ... | ... | ... | _${w.summary.totalAgents-5} more_ |`)}if(N.push(""),N.push("## Recent Runs"),N.push(""),w.runs.length===0)N.push("_No runs yet._");else{N.push("| Run ID | Agent | Status | Duration | Tokens | Cost |"),N.push("|--------|-------|--------|----------|--------|------|");for(let T of w.runs.slice(0,5))N.push(`| ${T.id.slice(-8)} | ${T.agentName} | ${T.status} | ${T.durationMs?Uf(T.durationMs):"-"} | ${T.totalTokens??0} | $${(T.estimatedCostUsd??0).toFixed(4)} |`);if(w.runs.length>5)N.push(`| ... | ... | ... | ... | ... | _${w.summary.totalRuns-5} more_ |`)}N.push(""),N.push("## Visualization Overview"),N.push("");for(let T of G)N.push(`- **${T.title}** via \`${T.spec.meta.key}\``);N.push(""),N.push("## Tools"),N.push("");let U={};for(let T of w.tools){let P=T.category;if(!U[P])U[P]=[];U[P].push(T)}if(Object.keys(U).length===0)N.push("_No tools registered._");else{N.push("| Category | Tools | Active |"),N.push("|----------|-------|--------|");for(let[T,P]of Object.entries(U).sort()){let K=P.filter((I)=>I.status==="ACTIVE").length;N.push(`| ${T} | ${P.length} | ${K} |`)}}return{mimeType:"text/markdown",body:N.join(`
3
+ `)}}};import{AGENT_CONSOLE_DEMO_PROJECT_ID as X1,createAgentConsoleDemoHandlers as zf}from"@contractspec/example.agent-console/shared";function Kf(f){if(f<1000)return`${f}ms`;if(f<60000)return`${(f/1000).toFixed(1)}s`;return`${(f/60000).toFixed(1)}m`}var Qf={target:"markdown",render:async(f,p)=>{if(f.source.type!=="component"||f.source.componentKey!=="RunListView")throw Error("runListMarkdownRenderer: not RunListView");let w=Array.isArray(p?.data)?{items:p.data,total:p.data.length,hasMore:!1}:await zf({projectId:X1}).listRuns({projectId:X1,limit:20,offset:0}),m=[`# ${f.meta.description??"Agent Runs"}`,"",`> ${f.meta.key} v${f.meta.version}`,"",`**Total Runs:** ${w.total}`,"","## Recent Runs","","| ID | Agent | Status | Duration | Tokens | Cost |","| --- | --- | --- | --- | --- | --- |"];for(let q of w.items.slice(0,10))m.push(`| ${q.id.slice(-8)} | ${q.agentName} | ${q.status} | ${q.durationMs?Kf(q.durationMs):"-"} | ${q.totalTokens} | $${q.estimatedCostUsd?.toFixed(4)??"-"} |`);return{mimeType:"text/markdown",body:m.join(`
4
+ `)}}};import{AGENT_CONSOLE_DEMO_ORGANIZATION_ID as $f,AGENT_CONSOLE_DEMO_PROJECT_ID as h1,createAgentConsoleDemoHandlers as Yf}from"@contractspec/example.agent-console/shared";var Af={target:"markdown",render:async(f,p)=>{if(f.source.type!=="component"||f.source.componentKey!=="ToolRegistryView")throw Error("toolRegistryMarkdownRenderer: not ToolRegistryView");let w=Array.isArray(p?.data)?{items:p.data,total:p.data.length,hasMore:!1}:await Yf({projectId:h1}).listTools({projectId:h1,organizationId:$f,limit:50,offset:0}),m=[`# ${f.meta.description??"Tool Registry"}`,"",`> ${f.meta.key} v${f.meta.version}`,"",`**Total Tools:** ${w.total}`,""],q={};for(let M of w.items){let Z=M.category;if(!q[Z])q[Z]=[];q[Z].push(M)}for(let[M,Z]of Object.entries(q).sort()){m.push(`## ${M} (${Z.length})`),m.push("");for(let D of Z){let A=D.status==="ACTIVE"?"✅":D.status==="DEPRECATED"?"⚠️":"❌";if(m.push(`### ${A} ${D.name} v${D.version}`),m.push(""),m.push(`> \`${D.id}\``),m.push(""),D.description)m.push(D.description),m.push("")}}return{mimeType:"text/markdown",body:m.join(`
5
+ `)}}};export{i0 as useToolList,a as useRunList,E0 as useAgentMutations,l as useAgentList,Af as toolRegistryMarkdownRenderer,Qf as runListMarkdownRenderer,Nf as agentListReactRenderer,t2 as agentListMarkdownRenderer,yf as agentDashboardMarkdownRenderer,x2 as agentConsoleReadOnlyOverlay,Nm as agentConsoleOverlays,j2 as agentConsoleDemoOverlay,O0 as ToolRegistryView,Y0 as RunListView,ep as ExecutionConsoleHost,b0 as CreateAgentModal,O0 as AgentToolRegistry,Y0 as AgentRunList,g0 as AgentListView,Cp as AgentDashboard,D1 as AgentConsolePreview,B0 as AgentActionsModal};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{defineVisualization as D,VisualizationRegistry as V}from"@contractspec/lib.contracts-spec/visualizations";var M={key:"agent.run.list",version:"1.0.0"},P={version:"1.0.0",domain:"ai-ops",stability:"experimental",owners:["@example.agent-console"],tags:["agent-console","visualization","operations"]},b=D({meta:{...P,key:"agent-console.visualization.run-status",title:"Run Status Breakdown",description:"Distribution of run outcomes across the current sample.",goal:"Make operational success and failure mix visible at a glance.",context:"Agent operations overview."},source:{primary:M,resultPath:"data"},visualization:{kind:"pie",nameDimension:"status",valueMeasure:"runs",dimensions:[{key:"status",label:"Status",dataPath:"status",type:"category"}],measures:[{key:"runs",label:"Runs",dataPath:"runs",format:"number"}],table:{caption:"Run counts by status."}}}),Z=D({meta:{...P,key:"agent-console.visualization.run-activity",title:"Recent Run Activity",description:"Daily run volume across the current sample.",goal:"Show whether agent activity is rising or slowing down.",context:"Operations trend monitoring."},source:{primary:M,resultPath:"data"},visualization:{kind:"cartesian",variant:"line",xDimension:"day",yMeasures:["runs"],dimensions:[{key:"day",label:"Day",dataPath:"day",type:"time"}],measures:[{key:"runs",label:"Runs",dataPath:"runs",format:"number",color:"#0f766e"}],table:{caption:"Daily run counts."}}}),C=D({meta:{...P,key:"agent-console.visualization.run-efficiency",title:"Duration vs Tokens",description:"Scatter chart comparing token consumption and runtime.",goal:"Reveal outlier runs that are slow relative to their token usage.",context:"Operational performance diagnostics."},source:{primary:M,resultPath:"data"},visualization:{kind:"cartesian",variant:"scatter",xDimension:"totalTokens",yMeasures:["durationMs"],dimensions:[{key:"totalTokens",label:"Total Tokens",dataPath:"totalTokens",type:"number"}],measures:[{key:"durationMs",label:"Duration",dataPath:"durationMs",format:"duration",color:"#7c3aed"},{key:"estimatedCostUsd",label:"Cost",dataPath:"estimatedCostUsd",format:"currency"}],series:[{key:"runs",label:"Runs",measure:"durationMs",type:"scatter",color:"#7c3aed"}],table:{caption:"Run duration versus token usage."}}}),v=[b,Z,C],ye=new V([...v]),fe=v.map((e)=>({key:e.meta.key,version:e.meta.version}));function E(e){if(!e)return"unknown";return e.toISOString().slice(0,10)}function R(e){let o=new Map,s=new Map;for(let t of e)o.set(t.status,(o.get(t.status)??0)+1),s.set(E(t.startedAt??t.queuedAt),(s.get(E(t.startedAt??t.queuedAt))??0)+1);return[{key:"run-status",spec:b,data:{data:Array.from(o.entries()).map(([t,a])=>({status:t,runs:a}))},title:"Run Status Breakdown",description:"Completed, failed, running, and cancelled runs in the sample.",height:260},{key:"run-activity",spec:Z,data:{data:Array.from(s.entries()).sort(([t],[a])=>t.localeCompare(a)).map(([t,a])=>({day:t,runs:a}))},title:"Recent Run Activity",description:"Daily run volume derived from run start times."},{key:"run-efficiency",spec:C,data:{data:e.filter((t)=>typeof t.durationMs==="number").map((t)=>({totalTokens:t.totalTokens,durationMs:t.durationMs??0,estimatedCostUsd:t.estimatedCostUsd}))},title:"Duration vs Tokens",description:"Operational scatter plot for spotting inefficient runs."}]}var S=[{id:"agent-1",organizationId:"demo-org",name:"Customer Support Bot",slug:"customer-support-bot",description:"Handles tier-1 customer inquiries and routes complex issues.",status:"ACTIVE",modelProvider:"OPENAI",modelName:"gpt-4o-mini",modelConfig:{temperature:0.7},systemPrompt:"You are a helpful customer support assistant.",toolChoice:"auto",maxIterations:10,timeoutMs:120000,version:"1.0.0",tags:["support","tier-1"],createdAt:new Date("2024-01-15T10:00:00Z"),updatedAt:new Date("2024-03-20T14:30:00Z")},{id:"agent-2",organizationId:"demo-org",name:"Code Review Assistant",slug:"code-review-assistant",description:"Reviews pull requests and provides actionable feedback.",status:"ACTIVE",modelProvider:"ANTHROPIC",modelName:"claude-sonnet-4-20250514",modelConfig:{temperature:0.3},systemPrompt:"You are a code review expert.",toolChoice:"auto",maxIterations:15,timeoutMs:180000,version:"2.1.0",tags:["code","review","dev"],createdAt:new Date("2024-02-10T09:00:00Z"),updatedAt:new Date("2024-04-05T11:15:00Z")},{id:"agent-3",organizationId:"demo-org",name:"Data Analyst",slug:"data-analyst",description:"Queries databases and generates insights from data.",status:"PAUSED",modelProvider:"OPENAI",modelName:"gpt-4o",modelConfig:{temperature:0.5},systemPrompt:"You are a data analyst expert in SQL and analytics.",toolChoice:"required",maxIterations:20,timeoutMs:300000,version:"1.2.0",tags:["data","analytics","sql"],createdAt:new Date("2024-03-01T08:00:00Z"),updatedAt:new Date("2024-04-10T16:45:00Z")},{id:"agent-4",organizationId:"demo-org",name:"Meeting Scheduler",slug:"meeting-scheduler",description:"Schedules meetings and manages calendar conflicts.",status:"DRAFT",modelProvider:"GOOGLE",modelName:"gemini-2.0-flash",modelConfig:{temperature:0.2},systemPrompt:"You help schedule and organize meetings efficiently.",toolChoice:"auto",maxIterations:5,timeoutMs:60000,version:"0.1.0",tags:["calendar","scheduling"],createdAt:new Date("2024-04-01T12:00:00Z"),updatedAt:new Date("2024-04-01T12:00:00Z")}];var N=[{id:"tool-1",organizationId:"demo-org",name:"Web Search",slug:"web-search",description:"Search the web for real-time information using Brave API.",category:"RETRIEVAL",status:"ACTIVE",parametersSchema:{type:"object",properties:{query:{type:"string",description:"Search query"},numResults:{type:"number",default:10}},required:["query"]},outputSchema:{type:"array",items:{type:"object"}},implementationType:"http",implementationConfig:{url:"https://api.brave.com/search",method:"GET"},maxInvocationsPerMinute:60,timeoutMs:30000,version:"1.0.0",tags:["search","web"],createdAt:new Date("2024-01-01T00:00:00Z"),updatedAt:new Date("2024-02-15T10:00:00Z")},{id:"tool-2",organizationId:"demo-org",name:"SQL Query",slug:"sql-query",description:"Execute read-only SQL queries against the data warehouse.",category:"RETRIEVAL",status:"ACTIVE",parametersSchema:{type:"object",properties:{query:{type:"string",description:"SQL query"},maxRows:{type:"number",default:100}},required:["query"]},outputSchema:{type:"object"},implementationType:"function",implementationConfig:{handler:"executeSqlQuery"},maxInvocationsPerMinute:30,timeoutMs:60000,version:"1.1.0",tags:["sql","database"],createdAt:new Date("2024-01-05T00:00:00Z"),updatedAt:new Date("2024-03-10T14:00:00Z")},{id:"tool-3",organizationId:"demo-org",name:"Email Sender",slug:"email-sender",description:"Send emails via SMTP or API.",category:"COMMUNICATION",status:"ACTIVE",parametersSchema:{type:"object",properties:{to:{type:"string"},subject:{type:"string"},body:{type:"string"}},required:["to","subject","body"]},implementationType:"http",implementationConfig:{url:"/api/send-email",method:"POST"},maxInvocationsPerMinute:10,timeoutMs:30000,version:"1.0.0",tags:["email","communication"],createdAt:new Date("2024-02-01T00:00:00Z"),updatedAt:new Date("2024-02-01T00:00:00Z")},{id:"tool-4",organizationId:"demo-org",name:"GitHub Integration",slug:"github-integration",description:"Interact with GitHub repositories, PRs, and issues.",category:"INTEGRATION",status:"ACTIVE",parametersSchema:{type:"object",properties:{action:{type:"string",enum:["list_prs","get_pr","create_comment"]},repo:{type:"string"},params:{type:"object"}},required:["action","repo"]},implementationType:"http",implementationConfig:{url:"https://api.github.com",auth:"token"},maxInvocationsPerMinute:100,timeoutMs:15000,version:"2.0.0",tags:["github","integration","code"],createdAt:new Date("2024-02-20T00:00:00Z"),updatedAt:new Date("2024-04-01T09:00:00Z")},{id:"tool-5",organizationId:"demo-org",name:"Calculator",slug:"calculator",description:"Perform mathematical calculations.",category:"COMPUTATION",status:"ACTIVE",parametersSchema:{type:"object",properties:{expression:{type:"string",description:"Math expression to evaluate"}},required:["expression"]},outputSchema:{type:"object",properties:{result:{type:"number"}}},implementationType:"function",implementationConfig:{handler:"evaluateMath"},timeoutMs:5000,version:"1.0.0",tags:["math","utility"],createdAt:new Date("2024-01-10T00:00:00Z"),updatedAt:new Date("2024-01-10T00:00:00Z")}];var k=[{id:"run-1",organizationId:"demo-org",projectId:"demo-project",agentId:"agent-1",agentName:"Customer Support Bot",userId:"user-1",sessionId:"session-1",input:{message:"How do I reset my password?",context:{}},output:{response:"You can reset your password by clicking..."},status:"COMPLETED",totalTokens:1250,promptTokens:800,completionTokens:450,totalIterations:3,durationMs:4500,estimatedCostUsd:0.0025,queuedAt:new Date("2024-04-15T10:00:00Z"),startedAt:new Date("2024-04-15T10:00:01Z"),completedAt:new Date("2024-04-15T10:00:05Z"),steps:[],logs:[]},{id:"run-2",organizationId:"demo-org",projectId:"demo-project",agentId:"agent-2",agentName:"Code Review Assistant",userId:"user-2",input:{message:"Review PR #123",context:{prNumber:123}},status:"IN_PROGRESS",totalTokens:3500,promptTokens:3000,completionTokens:500,totalIterations:5,queuedAt:new Date("2024-04-15T10:30:00Z"),startedAt:new Date("2024-04-15T10:30:02Z"),steps:[],logs:[]},{id:"run-3",organizationId:"demo-org",projectId:"demo-project",agentId:"agent-1",agentName:"Customer Support Bot",userId:"user-1",input:{message:"What are your business hours?"},output:{response:"Our business hours are 9 AM to 5 PM EST..."},status:"COMPLETED",totalTokens:800,promptTokens:500,completionTokens:300,totalIterations:2,durationMs:2100,estimatedCostUsd:0.0012,queuedAt:new Date("2024-04-15T09:00:00Z"),startedAt:new Date("2024-04-15T09:00:01Z"),completedAt:new Date("2024-04-15T09:00:03Z"),steps:[],logs:[]},{id:"run-4",organizationId:"demo-org",projectId:"demo-project",agentId:"agent-3",agentName:"Data Analyst",userId:"user-3",input:{message:"Generate sales report for Q1"},status:"FAILED",errorMessage:"Database connection timeout",errorCode:"DB_TIMEOUT",totalTokens:2000,promptTokens:1500,completionTokens:500,totalIterations:8,durationMs:45000,queuedAt:new Date("2024-04-14T15:00:00Z"),startedAt:new Date("2024-04-14T15:00:05Z"),completedAt:new Date("2024-04-14T15:00:50Z"),steps:[],logs:[]},{id:"run-5",organizationId:"demo-org",projectId:"demo-project",agentId:"agent-2",agentName:"Code Review Assistant",userId:"user-2",input:{message:"Review PR #120"},output:{response:"Code review complete. 3 suggestions..."},status:"COMPLETED",totalTokens:5200,promptTokens:4000,completionTokens:1200,totalIterations:7,durationMs:15000,estimatedCostUsd:0.0156,queuedAt:new Date("2024-04-14T11:00:00Z"),startedAt:new Date("2024-04-14T11:00:03Z"),completedAt:new Date("2024-04-14T11:00:18Z"),steps:[],logs:[]}];var U=[{id:"runs",label:"Runs",icon:"\u25B6"},{id:"agents",label:"Agents",icon:"\uD83E\uDD16"},{id:"tools",label:"Tools",icon:"\uD83D\uDD27"},{id:"metrics",label:"Metrics",icon:"\uD83D\uDCCA"}];function _(e){let o=e.filter((u)=>u.status==="COMPLETED").length,s=e.reduce((u,m)=>u+m.totalTokens,0),t=e.reduce((u,m)=>u+(m.estimatedCostUsd??0),0),a=e.map((u)=>u.durationMs).filter((u)=>typeof u==="number");return{averageDurationMs:a.length>0?a.reduce((u,m)=>u+m,0)/a.length:0,completedRuns:o,successRate:e.length>0?o/e.length:0,totalCostUsd:t,totalRuns:e.length,totalTokens:s}}function f(e){if(e<1000)return e.toString();if(e<1e6)return`${(e/1000).toFixed(1)}K`;return`${(e/1e6).toFixed(2)}M`}function L(e){if(!e)return"-";if(e<1000)return`${e}ms`;if(e<60000)return`${(e/1000).toFixed(1)}s`;return`${(e/60000).toFixed(1)}m`}function z(e){return new Intl.DateTimeFormat("en-US",{dateStyle:"medium",timeStyle:"short"}).format(e)}function O(e){if(typeof document>"u")return{onPress:e};return{onClick:e}}import{Badge as X}from"@contractspec/lib.ui-kit-web/ui/badge";import{Card as I,CardContent as A,CardHeader as H,CardTitle as j}from"@contractspec/lib.ui-kit-web/ui/card";import{HStack as q,VStack as l}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as d}from"@contractspec/lib.ui-kit-web/ui/text";import{jsx as n,jsxs as i}from"react/jsx-runtime";function G({metrics:e}){let o=[{label:"Total Runs",value:String(e.totalRuns),hint:`${Math.round(e.successRate*100)}% success`},{label:"Success Rate",value:`${Math.round(e.successRate*100)}%`,hint:"of all runs"},{label:"Total Tokens",value:f(e.totalTokens),hint:"This period"},{label:"Total Cost",value:`$${e.totalCostUsd.toFixed(2)}`,hint:"This period"}];return n(q,{gap:"md",className:"flex-wrap",children:o.map((s)=>n(I,{className:"min-w-52 flex-1",children:i(A,{className:"flex flex-col gap-1 pt-6",children:[n(d,{className:"text-muted-foreground text-sm",children:s.label}),n(d,{className:"font-bold text-2xl",children:s.value}),n(d,{className:"text-muted-foreground text-sm",children:s.hint})]})},s.label))})}function K({agents:e}){return n(l,{gap:"md",children:e.map((o)=>n(I,{children:i(A,{className:"flex flex-col gap-2 pt-6",children:[i(q,{justify:"between",align:"start",children:[i(l,{gap:"xs",className:"flex-1",children:[n(d,{className:"font-semibold text-lg",children:o.name}),i(d,{className:"text-muted-foreground text-sm",children:[o.modelProvider," / ",o.modelName]})]}),n(h,{status:o.status})]}),n(d,{className:"text-muted-foreground text-sm",children:o.description})]})},o.id))})}function Q({tools:e}){return n(l,{gap:"md",children:e.map((o)=>n(I,{children:i(A,{className:"flex flex-col gap-2 pt-6",children:[i(q,{justify:"between",align:"start",children:[i(l,{gap:"xs",className:"flex-1",children:[n(d,{className:"font-semibold text-lg",children:o.name}),i(d,{className:"text-muted-foreground text-sm",children:[o.category," / ",o.implementationType]})]}),n(h,{status:o.status})]}),n(d,{className:"text-muted-foreground text-sm",children:o.description})]})},o.id))})}function Y({metrics:e}){return i(l,{gap:"md",children:[n(d,{className:"font-semibold text-lg",children:"Usage Analytics"}),i(I,{children:[n(H,{children:n(j,{children:"Run Outcomes"})}),i(A,{className:"flex flex-col gap-3",children:[i(d,{children:["Completed: ",e.completedRuns]}),i(d,{children:["Failed: ",e.totalRuns-e.completedRuns]}),i(d,{children:["Average duration: ",(e.averageDurationMs/1000).toFixed(1),"s"]})]})]})]})}function h({status:e}){return n(X,{variant:e==="FAILED"||e==="CANCELLED"?"destructive":e==="ACTIVE"||e==="COMPLETED"?"secondary":"outline",children:n(d,{className:"font-semibold text-xs",children:e})})}import{useContractTable as x}from"@contractspec/lib.presentation-runtime-react";import{Card as ee,CardContent as te}from"@contractspec/lib.ui-kit-web/ui/card";import{DataTable as oe}from"@contractspec/lib.ui-kit-web/ui/data-table";import{VStack as ne}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as T}from"@contractspec/lib.ui-kit-web/ui/text";import{useMemo as re}from"react";import{jsx as c,jsxs as ae}from"react/jsx-runtime";function $({runs:e}){let o=re(()=>[{id:"queuedAt",header:"Run",label:"Run",accessor:(t)=>t.queuedAt.getTime(),cell:({item:t})=>ae(ne,{gap:"xs",children:[c(T,{className:"font-mono text-sm",children:t.id}),c(T,{className:"text-muted-foreground text-xs",children:z(t.queuedAt)})]}),size:180,canSort:!0,canHide:!0},{id:"agentName",header:"Agent",label:"Agent",accessorKey:"agentName",size:220,canSort:!0},{id:"status",header:"Status",label:"Status",accessorKey:"status",cell:({value:t})=>c(h,{status:String(t)}),size:140,canSort:!0},{id:"totalTokens",header:"Tokens",label:"Tokens",accessorKey:"totalTokens",cell:({value:t})=>f(Number(t??0)),align:"right",size:120,canSort:!0},{id:"durationMs",header:"Duration",label:"Duration",accessorKey:"durationMs",cell:({value:t})=>L(typeof t==="number"?t:void 0),align:"right",size:130,canHide:!0}],[]),s=x({data:e,columns:o,initialState:{pagination:{pageIndex:0,pageSize:5}},getRowId:(t)=>t.id});return c(oe,{controller:s,toolbar:c(T,{className:"text-muted-foreground text-sm",children:"Run History"}),emptyState:c(ee,{children:c(te,{className:"pt-6",children:c(T,{className:"text-muted-foreground",children:"No runs yet"})})})})}import{createVisualizationModel as ie}from"@contractspec/lib.presentation-runtime-core";import{Button as F}from"@contractspec/lib.ui-kit-web/ui/button";import{Card as se,CardContent as de,CardDescription as ue,CardHeader as pe,CardTitle as me}from"@contractspec/lib.ui-kit-web/ui/card";import{HStack as B,VStack as w}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as y}from"@contractspec/lib.ui-kit-web/ui/text";import{Visualization as ce}from"@contractspec/lib.ui-kit-web/ui/visualization";import{useMemo as W,useState as ge}from"react";import{jsx as r,jsxs as g}from"react/jsx-runtime";function rt({agents:e=S,runs:o=k,showHeaderAction:s=!0,tools:t=N}){let[a,u]=ge("runs"),m=W(()=>_(o),[o]),J=W(()=>R(o),[o]);return g(w,{gap:"xl",align:"stretch",children:[g(B,{justify:"between",align:"center",className:"gap-3",children:[r(y,{className:"font-bold text-2xl",children:"AI Agent Console"}),s?r(F,{...O(()=>{return}),children:r(y,{children:"+ New Agent"})}):null]}),r(G,{metrics:m}),g(w,{gap:"md",children:[g(w,{gap:"xs",children:[r(y,{className:"font-semibold text-lg",children:"Operational Visualizations"}),r(y,{className:"text-muted-foreground text-sm",children:"Contract-backed charts derived from recent run activity."})]}),r(w,{gap:"md",children:J.map((p)=>g(se,{children:[g(pe,{children:[r(me,{children:p.title}),r(ue,{children:p.description})]}),r(de,{children:r(ce,{height:p.height,model:ie(p.spec,p.data)})})]},p.key))})]}),r(B,{className:"rounded-lg bg-muted p-1",gap:"xs",children:U.map((p)=>r(F,{size:"sm",variant:a===p.id?"secondary":"ghost",className:"flex-1",...O(()=>u(p.id)),children:g(y,{children:[p.icon," ",p.label]})},p.id))}),a==="runs"?r($,{runs:o}):null,a==="agents"?r(K,{agents:e}):null,a==="tools"?r(Q,{tools:t}):null,a==="metrics"?r(Y,{metrics:m}):null]})}export{rt as AgentConsolePreview};
2
+ import{defineVisualization as D,VisualizationRegistry as X}from"@contractspec/lib.contracts-spec/visualizations";var M={key:"agent.run.list",version:"1.0.0"},P={version:"1.0.0",domain:"ai-ops",stability:"experimental",owners:["@example.agent-console"],tags:["agent-console","visualization","operations"]},b=D({meta:{...P,key:"agent-console.visualization.run-status",title:"Run Status Breakdown",description:"Distribution of run outcomes across the current sample.",goal:"Make operational success and failure mix visible at a glance.",context:"Agent operations overview."},source:{primary:M,resultPath:"data"},visualization:{kind:"pie",nameDimension:"status",valueMeasure:"runs",dimensions:[{key:"status",label:"Status",dataPath:"status",type:"category"}],measures:[{key:"runs",label:"Runs",dataPath:"runs",format:"number"}],table:{caption:"Run counts by status."}}}),S=D({meta:{...P,key:"agent-console.visualization.run-activity",title:"Recent Run Activity",description:"Daily run volume across the current sample.",goal:"Show whether agent activity is rising or slowing down.",context:"Operations trend monitoring."},source:{primary:M,resultPath:"data"},visualization:{kind:"cartesian",variant:"line",xDimension:"day",yMeasures:["runs"],dimensions:[{key:"day",label:"Day",dataPath:"day",type:"time"}],measures:[{key:"runs",label:"Runs",dataPath:"runs",format:"number",color:"#0f766e"}],table:{caption:"Daily run counts."}}}),Z=D({meta:{...P,key:"agent-console.visualization.run-efficiency",title:"Duration vs Tokens",description:"Scatter chart comparing token consumption and runtime.",goal:"Reveal outlier runs that are slow relative to their token usage.",context:"Operational performance diagnostics."},source:{primary:M,resultPath:"data"},visualization:{kind:"cartesian",variant:"scatter",xDimension:"totalTokens",yMeasures:["durationMs"],dimensions:[{key:"totalTokens",label:"Total Tokens",dataPath:"totalTokens",type:"number"}],measures:[{key:"durationMs",label:"Duration",dataPath:"durationMs",format:"duration",color:"#7c3aed"},{key:"estimatedCostUsd",label:"Cost",dataPath:"estimatedCostUsd",format:"currency"}],series:[{key:"runs",label:"Runs",measure:"durationMs",type:"scatter",color:"#7c3aed"}],table:{caption:"Run duration versus token usage."}}}),q=[b,S,Z],be=new X([...q]),Se=q.map((e)=>({key:e.meta.key,version:e.meta.version}));function E(e){if(!e)return"unknown";return e.toISOString().slice(0,10)}function R(e){let o=new Map,a=new Map;for(let t of e)o.set(t.status,(o.get(t.status)??0)+1),a.set(E(t.startedAt??t.queuedAt),(a.get(E(t.startedAt??t.queuedAt))??0)+1);return[{key:"run-status",spec:b,data:{data:Array.from(o.entries()).map(([t,d])=>({status:t,runs:d}))},title:"Run Status Breakdown",description:"Completed, failed, running, and cancelled runs in the sample.",height:260},{key:"run-activity",spec:S,data:{data:Array.from(a.entries()).sort(([t],[d])=>t.localeCompare(d)).map(([t,d])=>({day:t,runs:d}))},title:"Recent Run Activity",description:"Daily run volume derived from run start times."},{key:"run-efficiency",spec:Z,data:{data:e.filter((t)=>typeof t.durationMs==="number").map((t)=>({totalTokens:t.totalTokens,durationMs:t.durationMs??0,estimatedCostUsd:t.estimatedCostUsd}))},title:"Duration vs Tokens",description:"Operational scatter plot for spotting inefficient runs."}]}var N=[{id:"agent-1",organizationId:"demo-org",name:"Customer Support Bot",slug:"customer-support-bot",description:"Handles tier-1 customer inquiries and routes complex issues.",status:"ACTIVE",modelProvider:"OPENAI",modelName:"gpt-4o-mini",modelConfig:{temperature:0.7},systemPrompt:"You are a helpful customer support assistant.",toolChoice:"auto",maxIterations:10,timeoutMs:120000,version:"1.0.0",tags:["support","tier-1"],createdAt:new Date("2024-01-15T10:00:00Z"),updatedAt:new Date("2024-03-20T14:30:00Z")},{id:"agent-2",organizationId:"demo-org",name:"Code Review Assistant",slug:"code-review-assistant",description:"Reviews pull requests and provides actionable feedback.",status:"ACTIVE",modelProvider:"ANTHROPIC",modelName:"claude-sonnet-4-20250514",modelConfig:{temperature:0.3},systemPrompt:"You are a code review expert.",toolChoice:"auto",maxIterations:15,timeoutMs:180000,version:"2.1.0",tags:["code","review","dev"],createdAt:new Date("2024-02-10T09:00:00Z"),updatedAt:new Date("2024-04-05T11:15:00Z")},{id:"agent-3",organizationId:"demo-org",name:"Data Analyst",slug:"data-analyst",description:"Queries databases and generates insights from data.",status:"PAUSED",modelProvider:"OPENAI",modelName:"gpt-4o",modelConfig:{temperature:0.5},systemPrompt:"You are a data analyst expert in SQL and analytics.",toolChoice:"required",maxIterations:20,timeoutMs:300000,version:"1.2.0",tags:["data","analytics","sql"],createdAt:new Date("2024-03-01T08:00:00Z"),updatedAt:new Date("2024-04-10T16:45:00Z")},{id:"agent-4",organizationId:"demo-org",name:"Meeting Scheduler",slug:"meeting-scheduler",description:"Schedules meetings and manages calendar conflicts.",status:"DRAFT",modelProvider:"GOOGLE",modelName:"gemini-2.0-flash",modelConfig:{temperature:0.2},systemPrompt:"You help schedule and organize meetings efficiently.",toolChoice:"auto",maxIterations:5,timeoutMs:60000,version:"0.1.0",tags:["calendar","scheduling"],createdAt:new Date("2024-04-01T12:00:00Z"),updatedAt:new Date("2024-04-01T12:00:00Z")}];var k=[{id:"tool-1",organizationId:"demo-org",name:"Web Search",slug:"web-search",description:"Search the web for real-time information using Brave API.",category:"RETRIEVAL",status:"ACTIVE",parametersSchema:{type:"object",properties:{query:{type:"string",description:"Search query"},numResults:{type:"number",default:10}},required:["query"]},outputSchema:{type:"array",items:{type:"object"}},implementationType:"http",implementationConfig:{url:"https://api.brave.com/search",method:"GET"},maxInvocationsPerMinute:60,timeoutMs:30000,version:"1.0.0",tags:["search","web"],createdAt:new Date("2024-01-01T00:00:00Z"),updatedAt:new Date("2024-02-15T10:00:00Z")},{id:"tool-2",organizationId:"demo-org",name:"SQL Query",slug:"sql-query",description:"Execute read-only SQL queries against the data warehouse.",category:"RETRIEVAL",status:"ACTIVE",parametersSchema:{type:"object",properties:{query:{type:"string",description:"SQL query"},maxRows:{type:"number",default:100}},required:["query"]},outputSchema:{type:"object"},implementationType:"function",implementationConfig:{handler:"executeSqlQuery"},maxInvocationsPerMinute:30,timeoutMs:60000,version:"1.1.0",tags:["sql","database"],createdAt:new Date("2024-01-05T00:00:00Z"),updatedAt:new Date("2024-03-10T14:00:00Z")},{id:"tool-3",organizationId:"demo-org",name:"Email Sender",slug:"email-sender",description:"Send emails via SMTP or API.",category:"COMMUNICATION",status:"ACTIVE",parametersSchema:{type:"object",properties:{to:{type:"string"},subject:{type:"string"},body:{type:"string"}},required:["to","subject","body"]},implementationType:"http",implementationConfig:{url:"/api/send-email",method:"POST"},maxInvocationsPerMinute:10,timeoutMs:30000,version:"1.0.0",tags:["email","communication"],createdAt:new Date("2024-02-01T00:00:00Z"),updatedAt:new Date("2024-02-01T00:00:00Z")},{id:"tool-4",organizationId:"demo-org",name:"GitHub Integration",slug:"github-integration",description:"Interact with GitHub repositories, PRs, and issues.",category:"INTEGRATION",status:"ACTIVE",parametersSchema:{type:"object",properties:{action:{type:"string",enum:["list_prs","get_pr","create_comment"]},repo:{type:"string"},params:{type:"object"}},required:["action","repo"]},implementationType:"http",implementationConfig:{url:"https://api.github.com",auth:"token"},maxInvocationsPerMinute:100,timeoutMs:15000,version:"2.0.0",tags:["github","integration","code"],createdAt:new Date("2024-02-20T00:00:00Z"),updatedAt:new Date("2024-04-01T09:00:00Z")},{id:"tool-5",organizationId:"demo-org",name:"Calculator",slug:"calculator",description:"Perform mathematical calculations.",category:"COMPUTATION",status:"ACTIVE",parametersSchema:{type:"object",properties:{expression:{type:"string",description:"Math expression to evaluate"}},required:["expression"]},outputSchema:{type:"object",properties:{result:{type:"number"}}},implementationType:"function",implementationConfig:{handler:"evaluateMath"},timeoutMs:5000,version:"1.0.0",tags:["math","utility"],createdAt:new Date("2024-01-10T00:00:00Z"),updatedAt:new Date("2024-01-10T00:00:00Z")}];var C=[{id:"run-1",organizationId:"demo-org",projectId:"demo-project",agentId:"agent-1",agentName:"Customer Support Bot",userId:"user-1",sessionId:"session-1",input:{message:"How do I reset my password?",context:{}},output:{response:"You can reset your password by clicking..."},status:"COMPLETED",totalTokens:1250,promptTokens:800,completionTokens:450,totalIterations:3,durationMs:4500,estimatedCostUsd:0.0025,queuedAt:new Date("2024-04-15T10:00:00Z"),startedAt:new Date("2024-04-15T10:00:01Z"),completedAt:new Date("2024-04-15T10:00:05Z"),steps:[],logs:[]},{id:"run-2",organizationId:"demo-org",projectId:"demo-project",agentId:"agent-2",agentName:"Code Review Assistant",userId:"user-2",input:{message:"Review PR #123",context:{prNumber:123}},status:"IN_PROGRESS",totalTokens:3500,promptTokens:3000,completionTokens:500,totalIterations:5,queuedAt:new Date("2024-04-15T10:30:00Z"),startedAt:new Date("2024-04-15T10:30:02Z"),steps:[],logs:[]},{id:"run-3",organizationId:"demo-org",projectId:"demo-project",agentId:"agent-1",agentName:"Customer Support Bot",userId:"user-1",input:{message:"What are your business hours?"},output:{response:"Our business hours are 9 AM to 5 PM EST..."},status:"COMPLETED",totalTokens:800,promptTokens:500,completionTokens:300,totalIterations:2,durationMs:2100,estimatedCostUsd:0.0012,queuedAt:new Date("2024-04-15T09:00:00Z"),startedAt:new Date("2024-04-15T09:00:01Z"),completedAt:new Date("2024-04-15T09:00:03Z"),steps:[],logs:[]},{id:"run-4",organizationId:"demo-org",projectId:"demo-project",agentId:"agent-3",agentName:"Data Analyst",userId:"user-3",input:{message:"Generate sales report for Q1"},status:"FAILED",errorMessage:"Database connection timeout",errorCode:"DB_TIMEOUT",totalTokens:2000,promptTokens:1500,completionTokens:500,totalIterations:8,durationMs:45000,queuedAt:new Date("2024-04-14T15:00:00Z"),startedAt:new Date("2024-04-14T15:00:05Z"),completedAt:new Date("2024-04-14T15:00:50Z"),steps:[],logs:[]},{id:"run-5",organizationId:"demo-org",projectId:"demo-project",agentId:"agent-2",agentName:"Code Review Assistant",userId:"user-2",input:{message:"Review PR #120"},output:{response:"Code review complete. 3 suggestions..."},status:"COMPLETED",totalTokens:5200,promptTokens:4000,completionTokens:1200,totalIterations:7,durationMs:15000,estimatedCostUsd:0.0156,queuedAt:new Date("2024-04-14T11:00:00Z"),startedAt:new Date("2024-04-14T11:00:03Z"),completedAt:new Date("2024-04-14T11:00:18Z"),steps:[],logs:[]}];var U=[{id:"runs",label:"Runs",icon:"\u25B6"},{id:"agents",label:"Agents",icon:"\uD83E\uDD16"},{id:"tools",label:"Tools",icon:"\uD83D\uDD27"},{id:"metrics",label:"Metrics",icon:"\uD83D\uDCCA"}];function _(e){let o=e.filter((i)=>i.status==="COMPLETED").length,a=e.reduce((i,r)=>i+r.totalTokens,0),t=e.reduce((i,r)=>i+(r.estimatedCostUsd??0),0),d=e.map((i)=>i.durationMs).filter((i)=>typeof i==="number");return{averageDurationMs:d.length>0?d.reduce((i,r)=>i+r,0)/d.length:0,completedRuns:o,successRate:e.length>0?o/e.length:0,totalCostUsd:t,totalRuns:e.length,totalTokens:a}}function y(e){if(e<1000)return e.toString();if(e<1e6)return`${(e/1000).toFixed(1)}K`;return`${(e/1e6).toFixed(2)}M`}function L(e){if(!e)return"-";if(e<1000)return`${e}ms`;if(e<60000)return`${(e/1000).toFixed(1)}s`;return`${(e/60000).toFixed(1)}m`}function z(e){return new Intl.DateTimeFormat("en-US",{dateStyle:"medium",timeStyle:"short"}).format(e)}function G(e){if(typeof document>"u")return{onPress:e};return{onClick:e}}import{Badge as H}from"@contractspec/lib.ui-kit-web/ui/badge";import{Card as j,CardContent as x}from"@contractspec/lib.ui-kit-web/ui/card";import{Box as ee,HStack as Q,VStack as te}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as f}from"@contractspec/lib.ui-kit-web/ui/text";import{jsx as u,jsxs as O}from"react/jsx-runtime";function I({getKey:e,items:o,renderItem:a}){return u(Q,{gap:"none",align:"stretch",className:"flex-wrap",children:o.map((t)=>u(ee,{gap:"none",className:"flex w-full min-w-0 p-1.5 sm:w-1/2 lg:w-1/4",children:a(t)},e(t)))})}function v({description:e,name:o,status:a,subtitle:t}){return u(j,{className:"h-full w-full",children:O(x,{className:"flex flex-col gap-2 pt-6",children:[O(Q,{justify:"between",align:"start",children:[O(te,{gap:"xs",className:"flex-1",children:[u(f,{className:"font-semibold text-lg",children:o}),u(f,{className:"text-muted-foreground text-sm",children:t})]}),u(T,{status:a})]}),u(f,{className:"text-muted-foreground text-sm",children:e})]})})}function T({status:e}){return u(H,{variant:e==="FAILED"||e==="CANCELLED"?"destructive":e==="ACTIVE"||e==="COMPLETED"?"secondary":"outline",children:u(f,{className:"font-semibold text-xs",children:e})})}import{Card as K,CardContent as Y,CardHeader as oe,CardTitle as ne}from"@contractspec/lib.ui-kit-web/ui/card";import{VStack as ae}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as p}from"@contractspec/lib.ui-kit-web/ui/text";import{jsx as s,jsxs as g}from"react/jsx-runtime";function $({metrics:e}){let o=[{label:"Total Runs",value:String(e.totalRuns),hint:`${Math.round(e.successRate*100)}% success`},{label:"Success Rate",value:`${Math.round(e.successRate*100)}%`,hint:"of all runs"},{label:"Total Tokens",value:y(e.totalTokens),hint:"This period"},{label:"Total Cost",value:`$${e.totalCostUsd.toFixed(2)}`,hint:"This period"}];return s(I,{items:o,getKey:(a)=>a.label,renderItem:(a)=>s(K,{className:"h-full w-full",children:g(Y,{className:"flex flex-col gap-1 pt-6",children:[s(p,{className:"text-muted-foreground text-sm",children:a.label}),s(p,{className:"font-bold text-2xl",children:a.value}),s(p,{className:"text-muted-foreground text-sm",children:a.hint})]})})})}function F({agents:e}){return s(I,{items:e,getKey:(o)=>o.id,renderItem:(o)=>s(v,{description:o.description,name:o.name,status:o.status,subtitle:`${o.modelProvider} / ${o.modelName}`})})}function V({tools:e}){return s(I,{items:e,getKey:(o)=>o.id,renderItem:(o)=>s(v,{description:o.description,name:o.name,status:o.status,subtitle:`${o.category} / ${o.implementationType}`})})}function B({metrics:e}){return g(ae,{gap:"md",children:[s(p,{className:"font-semibold text-lg",children:"Usage Analytics"}),g(K,{children:[s(oe,{children:s(ne,{children:s(p,{children:"Run Outcomes"})})}),g(Y,{className:"flex flex-col gap-3",children:[g(p,{children:["Completed: ",e.completedRuns]}),g(p,{children:["Failed: ",e.totalRuns-e.completedRuns]}),g(p,{children:["Average duration: ",(e.averageDurationMs/1000).toFixed(1),"s"]})]})]})]})}import{useContractTable as re}from"@contractspec/lib.presentation-runtime-react";import{Card as ie,CardContent as se}from"@contractspec/lib.ui-kit-web/ui/card";import{DataTable as de}from"@contractspec/lib.ui-kit-web/ui/data-table";import{VStack as ue}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as h}from"@contractspec/lib.ui-kit-web/ui/text";import{useMemo as pe}from"react";import{jsx as m,jsxs as me}from"react/jsx-runtime";function W({runs:e}){let o=pe(()=>[{id:"queuedAt",header:"Run",label:"Run",accessor:(t)=>t.queuedAt.getTime(),cell:({item:t})=>me(ue,{gap:"xs",children:[m(h,{className:"font-mono text-sm",children:t.id}),m(h,{className:"text-muted-foreground text-xs",children:z(t.queuedAt)})]}),size:180,canSort:!0,canHide:!0},{id:"agentName",header:"Agent",label:"Agent",accessorKey:"agentName",size:220,canSort:!0},{id:"status",header:"Status",label:"Status",accessorKey:"status",cell:({value:t})=>m(T,{status:String(t)}),size:140,canSort:!0},{id:"totalTokens",header:"Tokens",label:"Tokens",accessorKey:"totalTokens",cell:({value:t})=>y(Number(t??0)),align:"right",size:120,canSort:!0},{id:"durationMs",header:"Duration",label:"Duration",accessorKey:"durationMs",cell:({value:t})=>L(typeof t==="number"?t:void 0),align:"right",size:130,canHide:!0}],[]),a=re({data:e,columns:o,initialState:{pagination:{pageIndex:0,pageSize:5}},getRowId:(t)=>t.id});return m(de,{controller:a,toolbar:m(h,{className:"text-muted-foreground text-sm",children:"Run History"}),emptyState:m(ie,{children:m(se,{className:"pt-6",children:m(h,{className:"text-muted-foreground",children:"No runs yet"})})})})}import{Tabs as ce,TabsContent as A,TabsList as ge,TabsTrigger as le}from"@contractspec/lib.design-system";import{createVisualizationModel as ye}from"@contractspec/lib.presentation-runtime-core";import{Button as fe}from"@contractspec/lib.ui-kit-web/ui/button";import{Card as Ie,CardContent as Te,CardDescription as he,CardHeader as Ae,CardTitle as we}from"@contractspec/lib.ui-kit-web/ui/card";import{HStack as De,VStack as w}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as l}from"@contractspec/lib.ui-kit-web/ui/text";import{Visualization as Me}from"@contractspec/lib.ui-kit-web/ui/visualization";import{useMemo as J}from"react";import{jsx as n,jsxs as c}from"react/jsx-runtime";function Dt({agents:e=N,runs:o=C,showHeaderAction:a=!0,tools:t=k}){let d=J(()=>_(o),[o]),i=J(()=>R(o),[o]);return c(w,{gap:"xl",align:"stretch",children:[c(De,{justify:"between",align:"center",className:"gap-3",children:[n(l,{className:"font-bold text-2xl",children:"AI Agent Console"}),a?n(fe,{...G(()=>{return}),children:n(l,{children:"+ New Agent"})}):null]}),n($,{metrics:d}),c(w,{gap:"md",children:[c(w,{gap:"xs",children:[n(l,{className:"font-semibold text-lg",children:"Operational Visualizations"}),n(l,{className:"text-muted-foreground text-sm",children:"Contract-backed charts derived from recent run activity."})]}),n(w,{gap:"md",children:i.map((r)=>c(Ie,{children:[c(Ae,{children:[n(we,{children:r.title}),n(he,{children:r.description})]}),n(Te,{children:n(Me,{height:r.height,model:ye(r.spec,r.data)})})]},r.key))})]}),c(ce,{defaultValue:"runs",className:"w-full gap-4",children:[n(ge,{className:"h-auto w-full flex-wrap",children:U.map((r)=>n(le,{value:r.id,className:"min-h-8 min-w-24 flex-1",children:c(l,{children:[r.icon," ",r.label]})},r.id))}),n(A,{value:"runs",children:n(W,{runs:o})}),n(A,{value:"agents",children:n(F,{agents:e})}),n(A,{value:"tools",children:n(V,{tools:t})}),n(A,{value:"metrics",children:n(B,{metrics:d})})]})]})}export{Dt as AgentConsolePreview};
@@ -0,0 +1,17 @@
1
+ import type { ReactNode } from 'react';
2
+ interface AgentConsoleResponsiveCardsProps<TItem> {
3
+ getKey: (item: TItem) => string;
4
+ items: readonly TItem[];
5
+ renderItem: (item: TItem) => ReactNode;
6
+ }
7
+ export declare function AgentConsoleResponsiveCards<TItem>({ getKey, items, renderItem, }: AgentConsoleResponsiveCardsProps<TItem>): import("react/jsx-runtime").JSX.Element;
8
+ export declare function AgentConsoleEntityCard({ description, name, status, subtitle, }: {
9
+ description: string;
10
+ name: string;
11
+ status: string;
12
+ subtitle: string;
13
+ }): import("react/jsx-runtime").JSX.Element;
14
+ export declare function AgentConsoleStatusBadge({ status }: {
15
+ status: string;
16
+ }): import("react/jsx-runtime").JSX.Element;
17
+ export {};
@@ -0,0 +1,2 @@
1
+ // @bun
2
+ import{Badge as G}from"@contractspec/lib.ui-kit-web/ui/badge";import{Card as J,CardContent as L}from"@contractspec/lib.ui-kit-web/ui/card";import{Box as M,HStack as F,VStack as N}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as z}from"@contractspec/lib.ui-kit-web/ui/text";import{jsx as h,jsxs as E}from"react/jsx-runtime";function W({getKey:f,items:q,renderItem:D}){return h(F,{gap:"none",align:"stretch",className:"flex-wrap",children:q.map((v)=>h(M,{gap:"none",className:"flex w-full min-w-0 p-1.5 sm:w-1/2 lg:w-1/4",children:D(v)},f(v)))})}function X({description:f,name:q,status:D,subtitle:v}){return h(J,{className:"h-full w-full",children:E(L,{className:"flex flex-col gap-2 pt-6",children:[E(F,{justify:"between",align:"start",children:[E(N,{gap:"xs",className:"flex-1",children:[h(z,{className:"font-semibold text-lg",children:q}),h(z,{className:"text-muted-foreground text-sm",children:v})]}),h(O,{status:D})]}),h(z,{className:"text-muted-foreground text-sm",children:f})]})})}function O({status:f}){return h(G,{variant:f==="FAILED"||f==="CANCELLED"?"destructive":f==="ACTIVE"||f==="COMPLETED"?"secondary":"outline",children:h(z,{className:"font-semibold text-xs",children:f})})}export{O as AgentConsoleStatusBadge,W as AgentConsoleResponsiveCards,X as AgentConsoleEntityCard};
@@ -1,4 +1,5 @@
1
1
  import type { AgentConsolePreviewAgent, AgentConsolePreviewTool, createAgentConsolePreviewMetrics } from './AgentConsolePreview.data';
2
+ export { AgentConsoleStatusBadge } from './AgentConsolePreviewCards';
2
3
  type PreviewMetrics = ReturnType<typeof createAgentConsolePreviewMetrics>;
3
4
  export declare function AgentConsoleMetricCards({ metrics, }: {
4
5
  metrics: PreviewMetrics;
@@ -12,7 +13,3 @@ export declare function AgentConsoleToolCards({ tools, }: {
12
13
  export declare function AgentConsoleMetricsPanel({ metrics, }: {
13
14
  metrics: PreviewMetrics;
14
15
  }): import("react/jsx-runtime").JSX.Element;
15
- export declare function AgentConsoleStatusBadge({ status }: {
16
- status: string;
17
- }): import("react/jsx-runtime").JSX.Element;
18
- export {};
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- var v=[{id:"runs",label:"Runs",icon:"\u25B6"},{id:"agents",label:"Agents",icon:"\uD83E\uDD16"},{id:"tools",label:"Tools",icon:"\uD83D\uDD27"},{id:"metrics",label:"Metrics",icon:"\uD83D\uDCCA"}];function E(e){let o=e.filter((f)=>f.status==="COMPLETED").length,p=e.reduce((f,l)=>f+l.totalTokens,0),d=e.reduce((f,l)=>f+(l.estimatedCostUsd??0),0),A=e.map((f)=>f.durationMs).filter((f)=>typeof f==="number");return{averageDurationMs:A.length>0?A.reduce((f,l)=>f+l,0)/A.length:0,completedRuns:o,successRate:e.length>0?o/e.length:0,totalCostUsd:d,totalRuns:e.length,totalTokens:p}}function b(e){if(e<1000)return e.toString();if(e<1e6)return`${(e/1000).toFixed(1)}K`;return`${(e/1e6).toFixed(2)}M`}function K(e){if(!e)return"-";if(e<1000)return`${e}ms`;if(e<60000)return`${(e/1000).toFixed(1)}s`;return`${(e/60000).toFixed(1)}m`}function h(e){return new Intl.DateTimeFormat("en-US",{dateStyle:"medium",timeStyle:"short"}).format(e)}function w(e){if(typeof document>"u")return{onPress:e};return{onClick:e}}import{Badge as P}from"@contractspec/lib.ui-kit-web/ui/badge";import{Card as _,CardContent as y,CardHeader as R,CardTitle as g}from"@contractspec/lib.ui-kit-web/ui/card";import{HStack as O,VStack as u}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as i}from"@contractspec/lib.ui-kit-web/ui/text";import{jsx as n,jsxs as r}from"react/jsx-runtime";function C({metrics:e}){let o=[{label:"Total Runs",value:String(e.totalRuns),hint:`${Math.round(e.successRate*100)}% success`},{label:"Success Rate",value:`${Math.round(e.successRate*100)}%`,hint:"of all runs"},{label:"Total Tokens",value:b(e.totalTokens),hint:"This period"},{label:"Total Cost",value:`$${e.totalCostUsd.toFixed(2)}`,hint:"This period"}];return n(O,{gap:"md",className:"flex-wrap",children:o.map((p)=>n(_,{className:"min-w-52 flex-1",children:r(y,{className:"flex flex-col gap-1 pt-6",children:[n(i,{className:"text-muted-foreground text-sm",children:p.label}),n(i,{className:"font-bold text-2xl",children:p.value}),n(i,{className:"text-muted-foreground text-sm",children:p.hint})]})},p.label))})}function L({agents:e}){return n(u,{gap:"md",children:e.map((o)=>n(_,{children:r(y,{className:"flex flex-col gap-2 pt-6",children:[r(O,{justify:"between",align:"start",children:[r(u,{gap:"xs",className:"flex-1",children:[n(i,{className:"font-semibold text-lg",children:o.name}),r(i,{className:"text-muted-foreground text-sm",children:[o.modelProvider," / ",o.modelName]})]}),n(M,{status:o.status})]}),n(i,{className:"text-muted-foreground text-sm",children:o.description})]})},o.id))})}function G({tools:e}){return n(u,{gap:"md",children:e.map((o)=>n(_,{children:r(y,{className:"flex flex-col gap-2 pt-6",children:[r(O,{justify:"between",align:"start",children:[r(u,{gap:"xs",className:"flex-1",children:[n(i,{className:"font-semibold text-lg",children:o.name}),r(i,{className:"text-muted-foreground text-sm",children:[o.category," / ",o.implementationType]})]}),n(M,{status:o.status})]}),n(i,{className:"text-muted-foreground text-sm",children:o.description})]})},o.id))})}function I({metrics:e}){return r(u,{gap:"md",children:[n(i,{className:"font-semibold text-lg",children:"Usage Analytics"}),r(_,{children:[n(R,{children:n(g,{children:"Run Outcomes"})}),r(y,{className:"flex flex-col gap-3",children:[r(i,{children:["Completed: ",e.completedRuns]}),r(i,{children:["Failed: ",e.totalRuns-e.completedRuns]}),r(i,{children:["Average duration: ",(e.averageDurationMs/1000).toFixed(1),"s"]})]})]})]})}function M({status:e}){return n(P,{variant:e==="FAILED"||e==="CANCELLED"?"destructive":e==="ACTIVE"||e==="COMPLETED"?"secondary":"outline",children:n(i,{className:"font-semibold text-xs",children:e})})}export{G as AgentConsoleToolCards,M as AgentConsoleStatusBadge,I as AgentConsoleMetricsPanel,C as AgentConsoleMetricCards,L as AgentConsoleAgentCards};
2
+ var v=[{id:"runs",label:"Runs",icon:"\u25B6"},{id:"agents",label:"Agents",icon:"\uD83E\uDD16"},{id:"tools",label:"Tools",icon:"\uD83D\uDD27"},{id:"metrics",label:"Metrics",icon:"\uD83D\uDCCA"}];function w(n){let o=n.filter((p)=>p.status==="COMPLETED").length,f=n.reduce((p,O)=>p+O.totalTokens,0),l=n.reduce((p,O)=>p+(O.estimatedCostUsd??0),0),y=n.map((p)=>p.durationMs).filter((p)=>typeof p==="number");return{averageDurationMs:y.length>0?y.reduce((p,O)=>p+O,0)/y.length:0,completedRuns:o,successRate:n.length>0?o/n.length:0,totalCostUsd:l,totalRuns:n.length,totalTokens:f}}function A(n){if(n<1000)return n.toString();if(n<1e6)return`${(n/1000).toFixed(1)}K`;return`${(n/1e6).toFixed(2)}M`}function G(n){if(!n)return"-";if(n<1000)return`${n}ms`;if(n<60000)return`${(n/1000).toFixed(1)}s`;return`${(n/60000).toFixed(1)}m`}function g(n){return new Intl.DateTimeFormat("en-US",{dateStyle:"medium",timeStyle:"short"}).format(n)}function T(n){if(typeof document>"u")return{onPress:n};return{onClick:n}}import{Badge as N}from"@contractspec/lib.ui-kit-web/ui/badge";import{Card as R,CardContent as F}from"@contractspec/lib.ui-kit-web/ui/card";import{Box as K,HStack as S,VStack as U}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as M}from"@contractspec/lib.ui-kit-web/ui/text";import{jsx as u,jsxs as P}from"react/jsx-runtime";function i({getKey:n,items:o,renderItem:f}){return u(S,{gap:"none",align:"stretch",className:"flex-wrap",children:o.map((l)=>u(K,{gap:"none",className:"flex w-full min-w-0 p-1.5 sm:w-1/2 lg:w-1/4",children:f(l)},n(l)))})}function b({description:n,name:o,status:f,subtitle:l}){return u(R,{className:"h-full w-full",children:P(F,{className:"flex flex-col gap-2 pt-6",children:[P(S,{justify:"between",align:"start",children:[P(U,{gap:"xs",className:"flex-1",children:[u(M,{className:"font-semibold text-lg",children:o}),u(M,{className:"text-muted-foreground text-sm",children:l})]}),u(h,{status:f})]}),u(M,{className:"text-muted-foreground text-sm",children:n})]})})}function h({status:n}){return u(N,{variant:n==="FAILED"||n==="CANCELLED"?"destructive":n==="ACTIVE"||n==="COMPLETED"?"secondary":"outline",children:u(M,{className:"font-semibold text-xs",children:n})})}import{Card as D,CardContent as E,CardHeader as $,CardTitle as L}from"@contractspec/lib.ui-kit-web/ui/card";import{VStack as d}from"@contractspec/lib.ui-kit-web/ui/stack";import{Text as _}from"@contractspec/lib.ui-kit-web/ui/text";import{jsx as r,jsxs as e}from"react/jsx-runtime";function c({metrics:n}){let o=[{label:"Total Runs",value:String(n.totalRuns),hint:`${Math.round(n.successRate*100)}% success`},{label:"Success Rate",value:`${Math.round(n.successRate*100)}%`,hint:"of all runs"},{label:"Total Tokens",value:A(n.totalTokens),hint:"This period"},{label:"Total Cost",value:`$${n.totalCostUsd.toFixed(2)}`,hint:"This period"}];return r(i,{items:o,getKey:(f)=>f.label,renderItem:(f)=>r(D,{className:"h-full w-full",children:e(E,{className:"flex flex-col gap-1 pt-6",children:[r(_,{className:"text-muted-foreground text-sm",children:f.label}),r(_,{className:"font-bold text-2xl",children:f.value}),r(_,{className:"text-muted-foreground text-sm",children:f.hint})]})})})}function m({agents:n}){return r(i,{items:n,getKey:(o)=>o.id,renderItem:(o)=>r(b,{description:o.description,name:o.name,status:o.status,subtitle:`${o.modelProvider} / ${o.modelName}`})})}function C({tools:n}){return r(i,{items:n,getKey:(o)=>o.id,renderItem:(o)=>r(b,{description:o.description,name:o.name,status:o.status,subtitle:`${o.category} / ${o.implementationType}`})})}function k({metrics:n}){return e(d,{gap:"md",children:[r(_,{className:"font-semibold text-lg",children:"Usage Analytics"}),e(D,{children:[r($,{children:r(L,{children:r(_,{children:"Run Outcomes"})})}),e(E,{className:"flex flex-col gap-3",children:[e(_,{children:["Completed: ",n.completedRuns]}),e(_,{children:["Failed: ",n.totalRuns-n.completedRuns]}),e(_,{children:["Average duration: ",(n.averageDurationMs/1000).toFixed(1),"s"]})]})]})]})}export{C as AgentConsoleToolCards,h as AgentConsoleStatusBadge,k as AgentConsoleMetricsPanel,c as AgentConsoleMetricCards,m as AgentConsoleAgentCards};