agentic-coding-harness 0.28.0__tar.gz → 0.28.1__tar.gz

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,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: agentic-coding-harness
3
- Version: 0.28.0
3
+ Version: 0.28.1
4
4
  Summary: Run, watch, and meter Claude Code, Codex CLI, Gemini CLI, OpenCode, and Kiro from one CLI — verified cost tracking, token usage, budget caps, OTel gen_ai spans, Langfuse traces, and a live dashboard + MCP server.
5
5
  Project-URL: Homepage, https://github.com/sblattj/agentic-coding-harness
6
6
  Project-URL: Repository, https://github.com/sblattj/agentic-coding-harness
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "agentic-coding-harness"
7
- version = "0.28.0"
7
+ version = "0.28.1"
8
8
  description = "Run, watch, and meter Claude Code, Codex CLI, Gemini CLI, OpenCode, and Kiro from one CLI — verified cost tracking, token usage, budget caps, OTel gen_ai spans, Langfuse traces, and a live dashboard + MCP server."
9
9
  keywords = ["claude-code", "codex-cli", "gemini-cli", "opencode", "kiro", "coding-agent", "agent-observability", "cost-tracking", "token-usage", "opentelemetry", "langfuse", "mcp-server", "llm", "ai-agents", "cli"]
10
10
  authors = [{ name = "Stephen Blatt" }]
@@ -5,6 +5,6 @@ Node.js >= 22) and execs the vendored ach.mjs CLI bundle with full
5
5
  argument passthrough.
6
6
  """
7
7
 
8
- __version__ = "0.28.0"
8
+ __version__ = "0.28.1"
9
9
 
10
10
  __all__ = ["__version__"]
@@ -99,7 +99,7 @@ ${i.join(`
99
99
  FROM session
100
100
  ORDER BY time_created DESC
101
101
  LIMIT ?
102
- `;var Ya=G(()=>{Ne();Ft();Q_={headless:!0,streaming:!0,resume:!0,acp:!0,tmuxFallback:!0},c6=D({type:k(),sessionID:k().nullish(),part:Re()}),u6=D({read:C().nullish(),write:C().nullish()}),l6=D({total:C().nullish(),input:C().nullish(),output:C().nullish(),reasoning:C().nullish(),cache:u6.nullish()}),d6=D({type:ae("step-start")}).passthrough(),p6=D({type:ae("text"),text:k()}).passthrough(),h6=D({type:ae("step-finish"),reason:k().nullish(),tokens:l6,cost:C().nullish()}).passthrough()});function w6(e){if(!pt(e))return;let t;for(let s of Object.values(e)){if(!pt(s))continue;let{tokens:o,percent:i}=s;if(typeof o!=="number"||typeof i!=="number")continue;if(!Number.isFinite(o)||!Number.isFinite(i)||o<1000||i<=0)continue;if(t===void 0||o>t.tokens)t={tokens:o,percent:i}}if(t===void 0)return;let n=t.tokens/(t.percent/100),r;for(let s of y6)if(Math.abs(n-s)/s<=0.15&&(r===void 0||Math.abs(n-s)<Math.abs(n-r)))r=s;return r??Math.round(n)}function pt(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function pr(e,t){for(let n of t){let r=e[n];if(typeof r==="string"&&r!=="")return r}return}function Ll(e){return e!==void 0&&e!==null}function r1(e){return!Ll(e)||e===""||pt(e)&&Object.keys(e).length===0}function R6(e,t){if(!Ll(t))return e;if(!Ll(e)||r1(e))return t;if(r1(t))return e;let n=(r)=>{try{return JSON.stringify(r)?.length??0}catch{return 0}};return n(t)>=n(e)?t:e}function ni(e){if(typeof e==="number"&&Number.isFinite(e))return e;if(typeof e==="string"&&e.trim()!==""&&Number.isFinite(Number(e)))return Number(e);return 0}function A6(e){if(!Array.isArray(e))return null;let t=0;for(let n of e)if(pt(n))t+=ni(n.value);return t}function I6(e){let t=e.tokenUsage??e.usage??e;return{inputTokens:ni(t.inputTokens??t.uncachedInputTokens),cacheReadTokens:ni(t.cacheReadTokens??t.cacheReadInputTokens),cacheWriteTokens:ni(t.cacheWriteTokens??t.cacheWriteInputTokens),outputTokens:ni(t.outputTokens),reasoningTokens:null,totalTokens:ni(t.totalTokens??t.total)||null,durationMs:null,raw:e}}function s1(e){let t=/^\s*\[warn\]\s+failed to set model\s+'([^']*)'\s*:/.exec(e);if(!t)return null;return{kind:"modelAckUnsupported",model:t[1]??""}}function o1(e){if(!/^\s*Dynamic registration failed:/.test(e))return null;return{notice:"mcpRegistrationFailed",warning:"kiro: MCP dynamic client registration failed (a server in ~/.kiro/settings/mcp.json or the agent's mcpServers rejected registration): "+e}}function Pl(e={}){let t=e.transport??"headless",n=new Map,r=new Map,s,o=!1,i,a,c=null,u=0,l,d=!1,p,h=0,f="",_=null,m="",g=null,v=0;function y(P,F,V={}){return{type:"step",payload:{kind:P,transport:t,countsAsTurn:!1,...V,raw:F}}}function w(P,F){if(typeof P!=="string"||P==="")return;if(s===void 0)s=P;if(!o)o=!0,F.push({type:"session",sessionId:P})}function b(P){let F=_,V=m;if(_=null,m="",F===null||V.trim()==="")return;P.push({type:"message",role:"assistant",text:V,...F==="reasoning"?{reasoning:!0}:{}})}function R(P){if(t!=="acp"||g!==null)return;v+=1,g=`kiro-acp-est-${v}`,P.push({type:"model_call",phase:"start",callId:g,provenance:"estimated"})}function S(P){if(g===null)return;P.push({type:"model_call",phase:"end",callId:g,provenance:"estimated"}),g=null}function T(P){b(P),S(P)}function I(P){if(p===void 0&&Number.isFinite(P)&&P>0)p=P}function A(P,F){if(w(P.sessionId,F),typeof P.contextUsagePercentage==="number")l=P.contextUsagePercentage,I(l);let V=A6(P.meteringUsage);if(V===null){F.push(y("metadata",P));return}T(F);let q=c??0;if(c!==null&&V===c){F.push(y("metadata",P,{duplicateSnapshot:!0}));return}c=V,u+=1;let he={credits:V-q,creditsCumulative:V,source:"native",tokensAvailable:!1,...l!==void 0?{contextUsagePercentage:l}:{},...p!==void 0?{contextStartPercentage:p}:{},meteringUsage:P.meteringUsage,...typeof P.turnDurationMs==="number"?{turnDurationMs:P.turnDurationMs}:{}},fe={inputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,outputTokens:0,reasoningTokens:null,totalTokens:null,durationMs:typeof P.turnDurationMs==="number"?P.turnDurationMs:null,raw:P,extra:he};F.push({type:"usage",tokens:fe})}function E(P,F){let V=typeof P.sessionUpdate==="string"?P.sessionUpdate:"";switch(V){case"agent_message_chunk":case"agent_thought_chunk":{let q=pt(P.content)?P.content:void 0,he=q&&typeof q.text==="string"?q.text:"";if(K(F),he!==""){R(F);let fe=V==="agent_thought_chunk"?"reasoning":"message";if(_!==null&&_!==fe)b(F);_=fe,m+=he}if(V==="agent_message_chunk")f+=he;F.push(y("chunk",P,{text:he,chunkKind:V}));return}case"tool_call":case"tool_call_chunk":{T(F);let q=typeof P.toolCallId==="string"?P.toolCallId:"";if(q===""){let ve=z("");J(ve,P),F.push(W(ve));return}let he=n.get(q);if(he&&he.startedSeen){let ve=N(P);if(ve!=="unknown")he.name=ve;F.push(y("toolCallDuplicate",P,{toolCallId:q}));return}let fe=r.get(q),ee=fe??z(q);if(J(ee,P),he)he.name=ee.name;else n.set(q,{name:ee.name,status:"started",startedSeen:!1,resultSeen:!1});if(Ll(ee.input)){if(L(ee,F),fe)F.push(y("toolCallDuplicate",P,{toolCallId:q}));return}r.set(q,ee),F.push(y(fe?"toolCallDuplicate":"toolCallPending",P,{toolCallId:q}));return}case"tool_call_update":{let q=typeof P.toolCallId==="string"?P.toolCallId:"",he=typeof P.status==="string"?P.status:"",fe=q!==""?r.get(q):void 0;if(fe){J(fe,P);let ve=n.get(q);if(ve)ve.name=fe.name;L(fe,F)}let ee=q!==""?n.get(q):void 0;if(he!=="completed"&&he!=="failed"){if(ee)ee.status=he==="in_progress"?"in_progress":ee.status;F.push(y("toolCallUpdate",P,{toolCallId:q,status:he}));return}if(ee)ee.status=he,ee.resultSeen=!0;F.push({type:"tool",toolName:ee?ee.name:"unknown",phase:"result",...q!==""?{toolCallId:q}:{},output:P.rawOutput??null,status:he==="completed"?"success":"error"});return}case"session_info_update":F.push(y("vendor",P,{sessionUpdate:V})),O(P,F);return;default:F.push(y("vendor",P,{sessionUpdate:V}))}}function O(P,F){let V=pt(P._meta)?P._meta:void 0,q=V&&pt(V.kiro)?V.kiro:void 0;if(!q||q.kind!=="context_usage")return;let he=pt(q.contextUsage)?q.contextUsage:void 0,fe=typeof q.usagePercentage==="number"?q.usagePercentage:he?.usagePercentage;if(typeof fe!=="number"||!Number.isFinite(fe))return;l=fe,I(fe);let ee=w6(q.breakdown),ve;if(!d&&pt(q.breakdown)){let me={};for(let[rn,st]of Object.entries(q.breakdown))if(pt(st)&&typeof st.tokens==="number"&&Number.isFinite(st.tokens))me[rn]=st.tokens;if(Object.keys(me).length>0)ve=me,d=!0}let Ze={source:"native",tokensAvailable:!1,contextUsagePercentage:fe,...p!==void 0?{contextStartPercentage:p}:{},...ee!==void 0?{contextWindowDerived:ee}:{},...ve!==void 0?{contextBreakdown:ve}:{}};F.push({type:"usage",tokens:{inputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,outputTokens:0,reasoningTokens:null,totalTokens:null,durationMs:null,raw:P,extra:Ze}})}function M(P){let F=pt(P._meta)?P._meta:void 0,V=F&&pt(F.kiro)?F.kiro:void 0;if(V&&typeof V.toolName==="string"&&V.toolName!=="")return V.toolName;return}function N(P){return M(P)??pr(P,["kind","title"])??"unknown"}function z(P){return{id:P,name:"unknown",nameFromMeta:!1,input:void 0}}function J(P,F){let V=M(F);if(V!==void 0)P.name=V,P.nameFromMeta=!0;else if(!P.nameFromMeta){let q=pr(F,["kind","title"]);if(q!==void 0)P.name=q}if(P.input=R6(P.input,F.rawInput),typeof F.title==="string"&&F.title!=="")P.title=F.title;if(Array.isArray(F.locations)&&F.locations.length>0)P.locations=F.locations}function W(P){return{type:"tool",toolName:P.name,phase:"start",...P.id!==""?{toolCallId:P.id}:{},input:P.input??null,...P.title!==void 0?{title:P.title}:{},...P.locations!==void 0?{locations:P.locations}:{}}}function L(P,F){r.delete(P.id);let V=n.get(P.id);if(V)V.startedSeen=!0;F.push(W(P))}function K(P){for(let F of[...r.values()])L(F,P)}function Q(P,F){if(w(P.sessionId,F),K(F),T(F),typeof P.status==="string")a=P.status;if(typeof P.stopReason==="string")i=P.stopReason;h+=1,F.push(y("runFinished",P,{...typeof P.status==="string"?{status:P.status}:{},...typeof P.stopReason==="string"?{stopReason:P.stopReason}:{},turn:h}))}function ye(P,F,V){let q=pr(P,["sessionId","session_id","sessionID"]);if(k6.has(F)){if(q)w(q,V);else V.push(y("vendor",P));return!0}if(x6.has(F)){let he=pr(P,["role"]);return V.push({type:"message",role:he==="user"||he==="system"?he:"assistant",text:pr(P,["text","content","message"])??""}),!0}if(S6.has(F)){let he=pr(P,["toolCallId","tool_call_id","id"]);return V.push({type:"tool",toolName:pr(P,["name","tool_name","toolName"])??"unknown",phase:"start",...he?{toolCallId:he}:{},input:P.input??P.arguments??P.args??null}),!0}if(C6.has(F)){let he=pr(P,["toolCallId","tool_call_id","id"]);return V.push({type:"tool",toolName:pr(P,["name","tool_name","toolName"])??"unknown",phase:"result",...he?{toolCallId:he}:{},output:P.output??P.result??P.content??null,...typeof P.isError==="boolean"?{status:P.isError?"error":"success"}:{}}),!0}if(E6.has(F))return V.push({type:"usage",tokens:I6(P)}),!0;if(T6.has(F))return V.push({type:"error",message:pr(P,["message","error","reason"])??"unknown error"}),!0;return!1}function H(P){let F=[];if(typeof P!=="string"||P.trim()==="")return F;let V;try{V=JSON.parse(P.trim())}catch{return F}if(!pt(V))return F;let q=V,he=typeof q.type==="string"?q.type:"",fe=pt(q.data)?q.data:{};switch(he){case"runStarted":return F.push(y("runStarted",fe)),F;case"metadata":return A(fe,F),F;case"sessionUpdate":{if(w(fe.sessionId,F),pt(fe.update))E(fe.update,F);else F.push(y("vendor",q));return F}case"runFinished":return Q(fe,F),F;default:if(ye(q,he,F))return F;return F.push(y("vendor",q)),F}}function Z(P){let F=[];if(!pt(P))return F;if(P.kind==="promptResult")return Q(pt(P.result)?P.result:{},F),F;let V=typeof P.method==="string"?P.method:"",q=pt(P.params)?P.params:{};if(V==="session/update"||V==="_kiro.dev/session/update"){if(w(q.sessionId,F),pt(q.update))E(q.update,F);else F.push(y("vendor",P));return F}if(V==="_kiro.dev/metadata")return A(q,F),F;if(V!=="")return w(q.sessionId,F),F.push(y("vendor",P,{method:V})),F;if(pt(P.result))w(P.result.sessionId,F);return F.push(y("vendor",P)),F}function le(){let P=[];return K(P),T(P),P}function Ee(){return{...s!==void 0?{nativeSessionId:s}:{},...i!==void 0?{stopReason:i}:{},...a!==void 0?{status:a}:{},credits:{latest:c,snapshots:u},...l!==void 0?{contextUsagePercentage:l}:{},toolCalls:n,turns:h,messageText:f}}return{pushHeadlessLine:H,pushAcpMessage:Z,flush:le,state:Ee}}var y6,k6,x6,S6,C6,E6,T6;var tm=G(()=>{y6=[128000,200000,256000,400000,1e6,2000000];k6=new Set(["session","session_start"]),x6=new Set(["assistant","assistant_message","assistantResponse","message"]),S6=new Set(["tool_use","toolUse","toolInvocation"]),C6=new Set(["tool_result","toolResult"]),E6=new Set(["usage","metering","token_usage"]),T6=new Set(["error","systemError"])});import{readFileSync as O6}from"node:fs";function M6(){try{let e=O6(new URL("../package.json",import.meta.url),"utf8"),t=JSON.parse(e).version;if(typeof t==="string"&&t!=="")return t}catch{}return"0.28.0"}var mt;var hr=G(()=>{mt=M6()});function Nl(e={}){let t=["acp"];if(e.engine==="v3")return t.push("--agent-engine","v3"),t;if(e.agent)t.push("--agent",e.agent);if(e.model)t.push("--model",e.model);if(e.effort)t.push("--effort",e.effort);if(e.tools==="all")t.push("--trust-all-tools");else if(e.tools==="none")t.push("--trust-tools=");else if(Array.isArray(e.tools))t.push(`--trust-tools=${e.tools.join(",")}`);if(e.engine)t.push("--agent-engine",e.engine);return t}function i1(e){if(e===void 0)return;let t={outcome:{outcome:"cancelled"}};if(e==="none")return async()=>t;let n=e==="all"?null:new Set(e);return async(r)=>{let s=r??{};if(n!==null){let a=s.toolCall??{};if(![a._meta?.kiro?.toolId,a._meta?.kiro?.toolName,a.toolName,a.name,a.kind].filter((u)=>typeof u==="string"&&u!=="").some((u)=>n.has(u)))return t}let o=Array.isArray(s.options)?s.options:[],i=o.find((a)=>a.kind==="allow_once")??o.find((a)=>typeof a.kind==="string"&&a.kind.startsWith("allow"));if(!i||typeof i.optionId!=="string")return t;return{outcome:{outcome:"selected",optionId:i.optionId}}}}class Xa{#e;#t;#n;#r;#s;#o;#i;#a;#u;#l;#d;#c;#h=null;#w=0;#f=new Map;#m=[];#p=!1;#v=null;#k=[];#b=null;#y=0;pid;exitCode=null;notifications=new tn;constructor(e){this.#e=e.command??"kiro-cli",this.#t=e.args,this.#n=e.cwd,this.#r=e.env,this.#s=e.scrubEnv,this.#o=e.spawnFn??Pn,this.#i=e.startupMs??60000,this.#a=e.clientInfo??{name:"agentic-coding-harness",version:mt},this.#u=e.onPermission??D6,this.#l=e.termGraceMs??2000,this.#d=e.killGraceMs??3000,this.#c=e.stderrLines??200}stderrTail(e=20){return this.#m.slice(-e).join(`
102
+ `;var Ya=G(()=>{Ne();Ft();Q_={headless:!0,streaming:!0,resume:!0,acp:!0,tmuxFallback:!0},c6=D({type:k(),sessionID:k().nullish(),part:Re()}),u6=D({read:C().nullish(),write:C().nullish()}),l6=D({total:C().nullish(),input:C().nullish(),output:C().nullish(),reasoning:C().nullish(),cache:u6.nullish()}),d6=D({type:ae("step-start")}).passthrough(),p6=D({type:ae("text"),text:k()}).passthrough(),h6=D({type:ae("step-finish"),reason:k().nullish(),tokens:l6,cost:C().nullish()}).passthrough()});function w6(e){if(!pt(e))return;let t;for(let s of Object.values(e)){if(!pt(s))continue;let{tokens:o,percent:i}=s;if(typeof o!=="number"||typeof i!=="number")continue;if(!Number.isFinite(o)||!Number.isFinite(i)||o<1000||i<=0)continue;if(t===void 0||o>t.tokens)t={tokens:o,percent:i}}if(t===void 0)return;let n=t.tokens/(t.percent/100),r;for(let s of y6)if(Math.abs(n-s)/s<=0.15&&(r===void 0||Math.abs(n-s)<Math.abs(n-r)))r=s;return r??Math.round(n)}function pt(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function pr(e,t){for(let n of t){let r=e[n];if(typeof r==="string"&&r!=="")return r}return}function Ll(e){return e!==void 0&&e!==null}function r1(e){return!Ll(e)||e===""||pt(e)&&Object.keys(e).length===0}function R6(e,t){if(!Ll(t))return e;if(!Ll(e)||r1(e))return t;if(r1(t))return e;let n=(r)=>{try{return JSON.stringify(r)?.length??0}catch{return 0}};return n(t)>=n(e)?t:e}function ni(e){if(typeof e==="number"&&Number.isFinite(e))return e;if(typeof e==="string"&&e.trim()!==""&&Number.isFinite(Number(e)))return Number(e);return 0}function A6(e){if(!Array.isArray(e))return null;let t=0;for(let n of e)if(pt(n))t+=ni(n.value);return t}function I6(e){let t=e.tokenUsage??e.usage??e;return{inputTokens:ni(t.inputTokens??t.uncachedInputTokens),cacheReadTokens:ni(t.cacheReadTokens??t.cacheReadInputTokens),cacheWriteTokens:ni(t.cacheWriteTokens??t.cacheWriteInputTokens),outputTokens:ni(t.outputTokens),reasoningTokens:null,totalTokens:ni(t.totalTokens??t.total)||null,durationMs:null,raw:e}}function s1(e){let t=/^\s*\[warn\]\s+failed to set model\s+'([^']*)'\s*:/.exec(e);if(!t)return null;return{kind:"modelAckUnsupported",model:t[1]??""}}function o1(e){if(!/^\s*Dynamic registration failed:/.test(e))return null;return{notice:"mcpRegistrationFailed",warning:"kiro: MCP dynamic client registration failed (a server in ~/.kiro/settings/mcp.json or the agent's mcpServers rejected registration): "+e}}function Pl(e={}){let t=e.transport??"headless",n=new Map,r=new Map,s,o=!1,i,a,c=null,u=0,l,d=!1,p,h=0,f="",_=null,m="",g=null,v=0;function y(P,F,V={}){return{type:"step",payload:{kind:P,transport:t,countsAsTurn:!1,...V,raw:F}}}function w(P,F){if(typeof P!=="string"||P==="")return;if(s===void 0)s=P;if(!o)o=!0,F.push({type:"session",sessionId:P})}function b(P){let F=_,V=m;if(_=null,m="",F===null||V.trim()==="")return;P.push({type:"message",role:"assistant",text:V,...F==="reasoning"?{reasoning:!0}:{}})}function R(P){if(t!=="acp"||g!==null)return;v+=1,g=`kiro-acp-est-${v}`,P.push({type:"model_call",phase:"start",callId:g,provenance:"estimated"})}function S(P){if(g===null)return;P.push({type:"model_call",phase:"end",callId:g,provenance:"estimated"}),g=null}function T(P){b(P),S(P)}function I(P){if(p===void 0&&Number.isFinite(P)&&P>0)p=P}function A(P,F){if(w(P.sessionId,F),typeof P.contextUsagePercentage==="number")l=P.contextUsagePercentage,I(l);let V=A6(P.meteringUsage);if(V===null){F.push(y("metadata",P));return}T(F);let q=c??0;if(c!==null&&V===c){F.push(y("metadata",P,{duplicateSnapshot:!0}));return}c=V,u+=1;let he={credits:V-q,creditsCumulative:V,source:"native",tokensAvailable:!1,...l!==void 0?{contextUsagePercentage:l}:{},...p!==void 0?{contextStartPercentage:p}:{},meteringUsage:P.meteringUsage,...typeof P.turnDurationMs==="number"?{turnDurationMs:P.turnDurationMs}:{}},fe={inputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,outputTokens:0,reasoningTokens:null,totalTokens:null,durationMs:typeof P.turnDurationMs==="number"?P.turnDurationMs:null,raw:P,extra:he};F.push({type:"usage",tokens:fe})}function E(P,F){let V=typeof P.sessionUpdate==="string"?P.sessionUpdate:"";switch(V){case"agent_message_chunk":case"agent_thought_chunk":{let q=pt(P.content)?P.content:void 0,he=q&&typeof q.text==="string"?q.text:"";if(K(F),he!==""){R(F);let fe=V==="agent_thought_chunk"?"reasoning":"message";if(_!==null&&_!==fe)b(F);_=fe,m+=he}if(V==="agent_message_chunk")f+=he;F.push(y("chunk",P,{text:he,chunkKind:V}));return}case"tool_call":case"tool_call_chunk":{T(F);let q=typeof P.toolCallId==="string"?P.toolCallId:"";if(q===""){let ve=z("");J(ve,P),F.push(W(ve));return}let he=n.get(q);if(he&&he.startedSeen){let ve=N(P);if(ve!=="unknown")he.name=ve;F.push(y("toolCallDuplicate",P,{toolCallId:q}));return}let fe=r.get(q),ee=fe??z(q);if(J(ee,P),he)he.name=ee.name;else n.set(q,{name:ee.name,status:"started",startedSeen:!1,resultSeen:!1});if(Ll(ee.input)){if(L(ee,F),fe)F.push(y("toolCallDuplicate",P,{toolCallId:q}));return}r.set(q,ee),F.push(y(fe?"toolCallDuplicate":"toolCallPending",P,{toolCallId:q}));return}case"tool_call_update":{let q=typeof P.toolCallId==="string"?P.toolCallId:"",he=typeof P.status==="string"?P.status:"",fe=q!==""?r.get(q):void 0;if(fe){J(fe,P);let ve=n.get(q);if(ve)ve.name=fe.name;L(fe,F)}let ee=q!==""?n.get(q):void 0;if(he!=="completed"&&he!=="failed"){if(ee)ee.status=he==="in_progress"?"in_progress":ee.status;F.push(y("toolCallUpdate",P,{toolCallId:q,status:he}));return}if(ee)ee.status=he,ee.resultSeen=!0;F.push({type:"tool",toolName:ee?ee.name:"unknown",phase:"result",...q!==""?{toolCallId:q}:{},output:P.rawOutput??null,status:he==="completed"?"success":"error"});return}case"session_info_update":F.push(y("vendor",P,{sessionUpdate:V})),O(P,F);return;default:F.push(y("vendor",P,{sessionUpdate:V}))}}function O(P,F){let V=pt(P._meta)?P._meta:void 0,q=V&&pt(V.kiro)?V.kiro:void 0;if(!q||q.kind!=="context_usage")return;let he=pt(q.contextUsage)?q.contextUsage:void 0,fe=typeof q.usagePercentage==="number"?q.usagePercentage:he?.usagePercentage;if(typeof fe!=="number"||!Number.isFinite(fe))return;l=fe,I(fe);let ee=w6(q.breakdown),ve;if(!d&&pt(q.breakdown)){let me={};for(let[rn,st]of Object.entries(q.breakdown))if(pt(st)&&typeof st.tokens==="number"&&Number.isFinite(st.tokens))me[rn]=st.tokens;if(Object.keys(me).length>0)ve=me,d=!0}let Ze={source:"native",tokensAvailable:!1,contextUsagePercentage:fe,...p!==void 0?{contextStartPercentage:p}:{},...ee!==void 0?{contextWindowDerived:ee}:{},...ve!==void 0?{contextBreakdown:ve}:{}};F.push({type:"usage",tokens:{inputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,outputTokens:0,reasoningTokens:null,totalTokens:null,durationMs:null,raw:P,extra:Ze}})}function M(P){let F=pt(P._meta)?P._meta:void 0,V=F&&pt(F.kiro)?F.kiro:void 0;if(V&&typeof V.toolName==="string"&&V.toolName!=="")return V.toolName;return}function N(P){return M(P)??pr(P,["kind","title"])??"unknown"}function z(P){return{id:P,name:"unknown",nameFromMeta:!1,input:void 0}}function J(P,F){let V=M(F);if(V!==void 0)P.name=V,P.nameFromMeta=!0;else if(!P.nameFromMeta){let q=pr(F,["kind","title"]);if(q!==void 0)P.name=q}if(P.input=R6(P.input,F.rawInput),typeof F.title==="string"&&F.title!=="")P.title=F.title;if(Array.isArray(F.locations)&&F.locations.length>0)P.locations=F.locations}function W(P){return{type:"tool",toolName:P.name,phase:"start",...P.id!==""?{toolCallId:P.id}:{},input:P.input??null,...P.title!==void 0?{title:P.title}:{},...P.locations!==void 0?{locations:P.locations}:{}}}function L(P,F){r.delete(P.id);let V=n.get(P.id);if(V)V.startedSeen=!0;F.push(W(P))}function K(P){for(let F of[...r.values()])L(F,P)}function Q(P,F){if(w(P.sessionId,F),K(F),T(F),typeof P.status==="string")a=P.status;if(typeof P.stopReason==="string")i=P.stopReason;h+=1,F.push(y("runFinished",P,{...typeof P.status==="string"?{status:P.status}:{},...typeof P.stopReason==="string"?{stopReason:P.stopReason}:{},turn:h}))}function ye(P,F,V){let q=pr(P,["sessionId","session_id","sessionID"]);if(k6.has(F)){if(q)w(q,V);else V.push(y("vendor",P));return!0}if(x6.has(F)){let he=pr(P,["role"]);return V.push({type:"message",role:he==="user"||he==="system"?he:"assistant",text:pr(P,["text","content","message"])??""}),!0}if(S6.has(F)){let he=pr(P,["toolCallId","tool_call_id","id"]);return V.push({type:"tool",toolName:pr(P,["name","tool_name","toolName"])??"unknown",phase:"start",...he?{toolCallId:he}:{},input:P.input??P.arguments??P.args??null}),!0}if(C6.has(F)){let he=pr(P,["toolCallId","tool_call_id","id"]);return V.push({type:"tool",toolName:pr(P,["name","tool_name","toolName"])??"unknown",phase:"result",...he?{toolCallId:he}:{},output:P.output??P.result??P.content??null,...typeof P.isError==="boolean"?{status:P.isError?"error":"success"}:{}}),!0}if(E6.has(F))return V.push({type:"usage",tokens:I6(P)}),!0;if(T6.has(F))return V.push({type:"error",message:pr(P,["message","error","reason"])??"unknown error"}),!0;return!1}function H(P){let F=[];if(typeof P!=="string"||P.trim()==="")return F;let V;try{V=JSON.parse(P.trim())}catch{return F}if(!pt(V))return F;let q=V,he=typeof q.type==="string"?q.type:"",fe=pt(q.data)?q.data:{};switch(he){case"runStarted":return F.push(y("runStarted",fe)),F;case"metadata":return A(fe,F),F;case"sessionUpdate":{if(w(fe.sessionId,F),pt(fe.update))E(fe.update,F);else F.push(y("vendor",q));return F}case"runFinished":return Q(fe,F),F;default:if(ye(q,he,F))return F;return F.push(y("vendor",q)),F}}function Z(P){let F=[];if(!pt(P))return F;if(P.kind==="promptResult")return Q(pt(P.result)?P.result:{},F),F;let V=typeof P.method==="string"?P.method:"",q=pt(P.params)?P.params:{};if(V==="session/update"||V==="_kiro.dev/session/update"){if(w(q.sessionId,F),pt(q.update))E(q.update,F);else F.push(y("vendor",P));return F}if(V==="_kiro.dev/metadata")return A(q,F),F;if(V!=="")return w(q.sessionId,F),F.push(y("vendor",P,{method:V})),F;if(pt(P.result))w(P.result.sessionId,F);return F.push(y("vendor",P)),F}function le(){let P=[];return K(P),T(P),P}function Ee(){return{...s!==void 0?{nativeSessionId:s}:{},...i!==void 0?{stopReason:i}:{},...a!==void 0?{status:a}:{},credits:{latest:c,snapshots:u},...l!==void 0?{contextUsagePercentage:l}:{},toolCalls:n,turns:h,messageText:f}}return{pushHeadlessLine:H,pushAcpMessage:Z,flush:le,state:Ee}}var y6,k6,x6,S6,C6,E6,T6;var tm=G(()=>{y6=[128000,200000,256000,400000,1e6,2000000];k6=new Set(["session","session_start"]),x6=new Set(["assistant","assistant_message","assistantResponse","message"]),S6=new Set(["tool_use","toolUse","toolInvocation"]),C6=new Set(["tool_result","toolResult"]),E6=new Set(["usage","metering","token_usage"]),T6=new Set(["error","systemError"])});import{readFileSync as O6}from"node:fs";function M6(){try{let e=O6(new URL("../package.json",import.meta.url),"utf8"),t=JSON.parse(e).version;if(typeof t==="string"&&t!=="")return t}catch{}return"0.28.1"}var mt;var hr=G(()=>{mt=M6()});function Nl(e={}){let t=["acp"];if(e.engine==="v3")return t.push("--agent-engine","v3"),t;if(e.agent)t.push("--agent",e.agent);if(e.model)t.push("--model",e.model);if(e.effort)t.push("--effort",e.effort);if(e.tools==="all")t.push("--trust-all-tools");else if(e.tools==="none")t.push("--trust-tools=");else if(Array.isArray(e.tools))t.push(`--trust-tools=${e.tools.join(",")}`);if(e.engine)t.push("--agent-engine",e.engine);return t}function i1(e){if(e===void 0)return;let t={outcome:{outcome:"cancelled"}};if(e==="none")return async()=>t;let n=e==="all"?null:new Set(e);return async(r)=>{let s=r??{};if(n!==null){let a=s.toolCall??{};if(![a._meta?.kiro?.toolId,a._meta?.kiro?.toolName,a.toolName,a.name,a.kind].filter((u)=>typeof u==="string"&&u!=="").some((u)=>n.has(u)))return t}let o=Array.isArray(s.options)?s.options:[],i=o.find((a)=>a.kind==="allow_once")??o.find((a)=>typeof a.kind==="string"&&a.kind.startsWith("allow"));if(!i||typeof i.optionId!=="string")return t;return{outcome:{outcome:"selected",optionId:i.optionId}}}}class Xa{#e;#t;#n;#r;#s;#o;#i;#a;#u;#l;#d;#c;#h=null;#w=0;#f=new Map;#m=[];#p=!1;#v=null;#k=[];#b=null;#y=0;pid;exitCode=null;notifications=new tn;constructor(e){this.#e=e.command??"kiro-cli",this.#t=e.args,this.#n=e.cwd,this.#r=e.env,this.#s=e.scrubEnv,this.#o=e.spawnFn??Pn,this.#i=e.startupMs??60000,this.#a=e.clientInfo??{name:"agentic-coding-harness",version:mt},this.#u=e.onPermission??D6,this.#l=e.termGraceMs??2000,this.#d=e.killGraceMs??3000,this.#c=e.stderrLines??200}stderrTail(e=20){return this.#m.slice(-e).join(`
103
103
  `)}get exited(){return this.#p}start(){if(this.#h)return;let e;try{e=this.#o(this.#e,this.#t,{cwd:this.#n,env:Nn(this.#r?{...process.env,...this.#r}:process.env,this.#s),stdio:["pipe","pipe","pipe"]})}catch(r){throw new Qe("spawn",`failed to spawn ${this.#e}`,"",r)}this.#h=e,this.pid=e.pid;let t=new dr;e.stdout?.setEncoding("utf8"),e.stdout?.on("data",(r)=>{for(let s of t.push(r))this.#T(s)}),e.stdout?.on("end",()=>{for(let r of t.flush())this.#T(r)});let n=new dr;e.stderr?.setEncoding("utf8"),e.stderr?.on("data",(r)=>{for(let s of n.push(r))this.#x(s)}),e.once("error",(r)=>{this.#x(`spawn error: ${r.message}`),this.#S(null)}),e.once("close",(r)=>{this.#S(r)})}#x(e){if(this.#m.push(e),this.#m.length>this.#c)this.#m.splice(0,this.#m.length-this.#c)}#S(e){if(this.#p)return;this.#p=!0,this.exitCode=e;for(let[,n]of this.#f){if(n.timer)clearTimeout(n.timer);n.reject(new Qe(n.phase,`child exited (code ${e??"null"}) with ${n.method} in flight`,this.stderrTail()))}this.#f.clear(),this.notifications.close();let t=this.#k;this.#k=[];for(let n of t)n(e)}#C(){if(this.#p)return Promise.resolve(this.exitCode);return new Promise((e)=>this.#k.push(e))}close(){if(this.#v)return this.#v;return this.#v=this.#R(),this.#v}async#R(){let e=this.#h;if(!e)return this.exitCode;if(this.#p)return this.exitCode;try{e.stdin?.end()}catch{}if(await this.#E(this.#l))return this.exitCode;try{e.kill("SIGTERM")}catch{}if(await this.#E(this.#d))return this.exitCode;try{e.kill("SIGKILL")}catch{}return await this.#C()}#E(e){if(this.#p)return Promise.resolve(!0);return new Promise((t)=>{let n=setTimeout(()=>t(this.#p),e);n.unref?.(),this.#C().then(()=>{clearTimeout(n),t(!0)})})}#g(e){let t=this.#h;if(!t||this.#p)return;t.stdin?.write(`${JSON.stringify(e)}
104
104
  `)}#T(e){let t=e.trim();if(!t)return;let n;try{n=JSON.parse(t)}catch{this.#x(`non-json stdout: ${t.slice(0,400)}`);return}let r=n.id!==void 0&&n.id!==null;if(r&&typeof n.method==="string"){this.#I(n.id,n.method,n.params);return}if(r){this.#A(n);return}if(typeof n.method==="string"){if(this.#b!==null&&n.method==="session/update"&&n.params?.sessionId===this.#b){this.#y++;return}this.notifications.push({method:n.method,params:n.params})}}#A(e){let t=Number(e.id),n=this.#f.get(t);if(!n)return;if(this.#f.delete(t),n.timer)clearTimeout(n.timer);let r=e.error;if(r){let s=typeof r.data==="string"&&r.data!==""?`: ${r.data}`:"";n.reject(new Qe(n.phase,`${n.method} failed: ${r.message??"unknown error"}${s} (code ${r.code??"?"})`,this.stderrTail(),r));return}n.resolve(e.result)}async#I(e,t,n){let r;if(t==="session/request_permission"){let s;try{s=await this.#u(n)}catch{s={outcome:{outcome:"cancelled"}}}r=s,this.#g({jsonrpc:"2.0",id:e,result:s})}else if(L6.test(t)){let s={code:-32601,message:`Method not found: ${t} (client advertises fs:false, terminal:false)`};r={error:s},this.#g({jsonrpc:"2.0",id:e,error:s})}else{let s={code:-32601,message:`Method not found: ${t}`};r={error:s},this.#g({jsonrpc:"2.0",id:e,error:s})}this.notifications.push({method:"__client_request",params:{method:t,params:n,answered:r}})}#_(e,t,n,r){if(!this.#h)this.start();if(this.#p)return Promise.reject(new Qe(n,`child already exited (code ${this.exitCode??"null"})`,this.stderrTail()));let s=this.#w++;return new Promise((o,i)=>{let a={phase:n,method:e,resolve:o,reject:i,timer:null};if(r!==null){let c=setTimeout(()=>{this.#f.delete(s),this.close().then(()=>{i(new Qe(n,`${e} did not respond within ${r}ms`,this.stderrTail()))})},r);c.unref?.(),a.timer=c}this.#f.set(s,a),this.#g({jsonrpc:"2.0",id:s,method:e,params:t})})}initialize(){return this.#_("initialize",{protocolVersion:1,clientCapabilities:{fs:{readTextFile:!1,writeTextFile:!1},terminal:!1},clientInfo:this.#a},"initialize",this.#i)}newSession(e){return this.#_("session/new",{cwd:e.cwd,mcpServers:e.mcpServers??[]},"session/new",this.#i)}async loadSession(e,t={}){this.#b=e;try{return await this.#_("session/load",{sessionId:e,cwd:t.cwd??this.#n??process.cwd(),mcpServers:t.mcpServers??[]},"session/load",this.#i)??{}}finally{this.#b=null}}get replayedCount(){return this.#y}async setConfigOption(e,t,n){let r=await this.#_("session/set_config_option",{sessionId:e,configId:t,value:n},"session/set_config_option",this.#i);return Array.isArray(r?.configOptions)?r.configOptions:[]}setModel(e,t){return this.#_("session/set_model",{sessionId:e,modelId:t},"session/set_model",this.#i)}prompt(e,t){return this.#_("session/prompt",{sessionId:e,prompt:[{type:"text",text:t}]},"session/prompt",null)}cancel(e){this.#g({jsonrpc:"2.0",method:"session/cancel",params:{sessionId:e}})}async handshake(e){let t=[],n=null,r=(c)=>{if(P6.test(c.method))t.push(c.method);if(c.method==="session/update"){let u=c.params?.update;if(u?.sessionUpdate==="config_option_update"&&Array.isArray(u.configOptions))n={options:u.configOptions,seq:(n?.seq??0)+1}}},s=this.#M(r),o=Date.now(),i=e.resume!==void 0&&e.resume!==""?e.resume:void 0,a=i!==void 0?"session/load":"session/new";try{let c=Date.now(),u=await this.initialize(),l=Date.now()-c,d=0,p=0,h;if(i!==void 0){if(u.agentCapabilities?.loadSession===!1)throw new Qe("session/load",`cannot resume '${i}': the agent advertises agentCapabilities.loadSession:false`,this.stderrTail());let b=Date.now(),R=await this.loadSession(i,{cwd:e.cwd,mcpServers:e.mcpServers});p=Date.now()-b,h={...R,sessionId:i}}else{let b=Date.now();h=await this.newSession({cwd:e.cwd,mcpServers:e.mcpServers}),d=Date.now()-b}if(this.#p)throw new Qe(a,`child exited (code ${this.exitCode??"null"}) right after ${a}`,this.stderrTail());if(e.engine==="v3")return await this.#O({opts:e,init:u,session:h,sessionPhase:a,pushed:()=>n,mcpNotices:t,resumed:i!==void 0,t0:o,initializeMs:l,newSessionMs:d,loadSessionMs:p});let f=h.modes?.currentModeId??null,_=h.modes?.availableModes??[],m=h.models?.currentModelId??null,g=h.models?.availableModels??[];if(e.agent&&f!==e.agent)throw new Qe(a,`requested agent '${e.agent}' is not the session mode (current '${f??"none"}'); available: ${_.map((b)=>b.id).join(", ")||"none"}`,this.stderrTail());let v=e.model?g.some((b)=>b.modelId===e.model):!1,y="not-requested",w=0;if(e.model){if(e.requireModelAck&&!v)throw new Qe("session/set_model",`model '${e.model}' is not offered by this session; available: ${g.map((R)=>R.modelId).join(", ")||"none"}`,this.stderrTail());let b=Date.now();try{await this.setModel(h.sessionId,e.model),y="acknowledged"}catch(R){if(e.requireModelAck)throw R;y="rejected"}w=Date.now()-b}return{cliVersion:u.agentInfo?.version??null,sessionId:h.sessionId,currentModeId:f,availableModes:_,currentModelId:m,availableModels:g,modelAck:y,agentVerified:e.agent!==void 0&&f===e.agent,modelVerified:v,effortAck:"not-requested",currentEffort:null,mcpNotices:t,resumed:i!==void 0,replayedUpdates:this.#y,durationsMs:{initialize:l,newSession:d,loadSession:p,setModel:w,setConfig:0,total:Date.now()-o}}}finally{s()}}async#O(e){let{opts:t,session:n}=e,r=n.sessionId,s="session/set_config_option",o=n.modes?.availableModes??[],i=e.pushed()?.options??n.configOptions??[],a=(S)=>i.find((T)=>T.id===S),c=(S)=>(S?.options??[]).map((T)=>T.value).filter((T)=>typeof T==="string"),u=(S)=>{let T=a(S)?.currentValue;return typeof T==="string"?T:null},l=(S)=>{if(S.length>0)i=S},d=async(S,T,I)=>{let A=Date.now()+I;for(;;){let E=e.pushed();if(E&&E.seq>T&&E.options.some((O)=>O.id===S)){i=E.options;return}if(Date.now()>=A||this.#p)return;await new Promise((O)=>setTimeout(O,25))}},p=()=>e.pushed()?.seq??0,h=Math.min(this.#i,15000),f=Math.min(this.#i,2000),_=0,m=0,g=!1;if(t.agent){let S=new Set([...o.map((A)=>A.id),...c(a("mode"))]),T="; use --kiro-transport headless to run a custom agent on engine v3 without ACP";if(!S.has(t.agent))throw new Qe(e.sessionPhase,`requested agent '${t.agent}' is not offered by this engine v3 session; available: ${[...S].join(", ")||"none"}; use --kiro-transport headless to run a custom agent on engine v3 without ACP`,this.stderrTail());if(u("mode")!==t.agent&&(n.modes?.currentModeId??null)!==t.agent){let A=Date.now();l(await this.setConfigOption(r,"mode",t.agent)),_+=Date.now()-A}let I=u("mode")??n.modes?.currentModeId??null;if(I!==t.agent)throw new Qe("session/set_config_option",`engine v3 did not switch to agent '${t.agent}' (current '${I??"none"}'); use --kiro-transport headless to run a custom agent on engine v3 without ACP`,this.stderrTail());g=!0}let v="not-requested",y=!1;if(t.model){if(!a("model"))await d("model",0,h);let S=c(a("model"));if(S.length>0&&!S.includes(t.model)){if(t.requireModelAck)throw new Qe("session/set_config_option",`model '${t.model}' is not offered by this session; available: ${S.join(", ")}`,this.stderrTail());v="rejected"}else{let T=Date.now(),I=p();try{l(await this.setConfigOption(r,"model",t.model))}catch(A){if(t.requireModelAck)throw A}if(u("model")!==t.model)await d("model",I,h);if(u("model")!==t.model&&c(a("model")).includes(t.model))l(await this.setConfigOption(r,"model",t.model));if(m=Date.now()-T,y=c(a("model")).includes(t.model),v=y&&u("model")===t.model?"acknowledged":"rejected",v==="rejected"&&t.requireModelAck)throw new Qe("session/set_config_option",`model '${t.model}' was not acknowledged (current '${u("model")??"none"}'); available: ${c(a("model")).join(", ")||"none"}`,this.stderrTail())}}let w="not-requested";if(t.effort){if(!a("effortLevel"))await d("effortLevel",0,f);let S=c(a("effortLevel"));if(!S.includes(t.effort))throw new Qe("session/set_config_option",`effort '${t.effort}' is not available for model '${u("model")??"unknown"}' on engine v3; available: ${S.join(", ")||"none"}`,this.stderrTail());if(u("effortLevel")!==t.effort){let T=Date.now();l(await this.setConfigOption(r,"effortLevel",t.effort)),_+=Date.now()-T}if(u("effortLevel")!==t.effort)throw new Qe("session/set_config_option",`engine v3 did not apply effort '${t.effort}' (current '${u("effortLevel")??"none"}')`,this.stderrTail());w="acknowledged"}let R=(a("model")?.options??[]).filter((S)=>typeof S.value==="string").map((S)=>({modelId:S.value,...typeof S.name==="string"?{name:S.name}:{}}));return{cliVersion:e.init.agentInfo?.version??null,sessionId:r,currentModeId:u("mode")??n.modes?.currentModeId??null,availableModes:o,currentModelId:u("model"),availableModels:R,modelAck:v,agentVerified:g,modelVerified:y,effortAck:w,currentEffort:u("effortLevel"),mcpNotices:e.mcpNotices,resumed:e.resumed,replayedUpdates:this.#y,durationsMs:{initialize:e.initializeMs,newSession:e.newSessionMs,loadSession:e.loadSessionMs,setModel:m,setConfig:_,total:Date.now()-e.t0}}}#M(e){let t=this.notifications,n=t.push.bind(t);return t.push=(...r)=>{for(let s of r)e(s);n(...r)},()=>{t.push=n}}}var Qe,D6=async()=>({outcome:{outcome:"cancelled"}}),L6,P6;var nm=G(()=>{hr();Ft();Qe=class Qe extends Error{phase;stderrTail;cause;constructor(e,t,n="",r){super(`kiro acp [${e}]: ${t}`);this.name="KiroAcpError",this.phase=e,this.stderrTail=n,this.cause=r}};L6=/^(fs\/|terminal\/)/,P6=/^_kiro\.dev\/(mcp|webTools)\//});import{createHash as N6}from"node:crypto";function F6(e){return N6("sha256").update(JSON.stringify(e)).digest("hex")}function B6(e){if(e instanceof Qe){let t=e.stderrTail.trim();return t===""?e.message:`${e.message}
105
105
  stderr: ${t}`}return e instanceof Error?e.message:String(e)}function j6(e){return e instanceof Qe?e.phase:"unknown"}async function c1(e,t){let n=e.kiro??{},r=[...Nl({...n.agent!==void 0?{agent:n.agent}:{},...e.model!==void 0?{model:e.model}:{},...n.effort!==void 0?{effort:n.effort}:{},...n.tools!==void 0?{tools:n.tools}:{},...n.engine!==void 0?{engine:n.engine}:{}}),...e.extraArgs??[]],s=n.engine==="v3",o=t.onPermission??(s?i1(n.tools):void 0),i=new Xa({...t.command!==void 0?{command:t.command}:{},args:r,...e.cwd!==void 0?{cwd:e.cwd}:{},...e.env!==void 0?{env:e.env}:{},...e.sandbox?.scrubEnv!==void 0?{scrubEnv:e.sandbox.scrubEnv}:{},...t.spawnFn!==void 0?{spawnFn:t.spawnFn}:{},...n.startupMs!==void 0?{startupMs:n.startupMs}:{},...o!==void 0?{onPermission:o}:{}}),a=Pl({transport:"acp"}),c=new tn,u=[],l=[],d=()=>{},p=new Promise((R)=>{d=R}),h=!1,f,_,m,g=(R)=>{for(let S of R)c.push(S)},v=(R)=>{let S=at("kiro",R);if(S)c.push(S)},y=(R)=>{let S=[];for(let T of a.pushAcpMessage(R)){let I=at("kiro",T);if(!I)continue;if(T.type==="usage"&&I.type==="usage"){let A=T.tokens?.extra;if(A){let E=I.usage;E.extra={...E.extra??{},...A}}}S.push(I)}g(S)},w=(async()=>{for await(let R of i.notifications){if(R.method==="__client_request"){let S=R.params??{};v({type:"step",payload:{kind:"clientRequest",transport:"acp",countsAsTurn:!1,...S}});continue}if(l.push(R.method),a1.test(R.method))u.push(R.method);y(R)}})();(async()=>{let R=1;try{if(i.start(),_=await i.handshake({cwd:e.cwd??process.cwd(),mcpServers:n.mcpServers??[],...n.agent!==void 0?{agent:n.agent}:{},...e.model!==void 0?{model:e.model}:{},requireModelAck:n.requireModelAck??e.model!==void 0,...n.engine!==void 0?{engine:n.engine}:{},...s&&n.effort!==void 0?{effort:n.effort}:{},...e.resume!==void 0&&e.resume!==""?{resume:e.resume}:{}}),f=_.sessionId,y({jsonrpc:"2.0",result:{sessionId:_.sessionId}}),n.requireMcpStartup===!0){if(u.length===0)await U6(50);let I=[...new Set([...u,..._.mcpNotices.filter((A)=>a1.test(A))])];if(I.length>0)throw new Qe("mcp",`requireMcpStartup: MCP failed to start (${I.join(", ")}); no prompt was sent`,i.stderrTail())}if(i.exited)throw new Qe(_.resumed?"session/load":"session/new",`child exited (code ${i.exitCode??"null"}) before session/prompt`,i.stderrTail());let S=await i.prompt(f,e.prompt);y({kind:"promptResult",result:S});let T=typeof S.stopReason==="string"?S.stopReason:"";if(R=T===""||$6.has(T)?0:1,T==="cancelled")h=!0}catch(S){v({type:"error",message:`kiro acp failed in phase '${j6(S)}': ${B6(S)}`}),R=1}finally{m=W6({kiro:n,spec:e,receipt:_,args:r,notices:l,sessionId:f}),await i.close(),await w;for(let S of a.flush())v(S);c.close(),d(R)}})();let b=await rt({agent:"kiro",events:c,mapEvent:(R)=>R,exit:p,abort:()=>{if(h=!0,f!==void 0)i.cancel(f);i.close()},isAborted:()=>h,...e.resume!==void 0?{fallbackSessionId:e.resume}:{},sessionIdWaitMs:0});return b.kiro=()=>m,b}function W6(e){let{kiro:t,spec:n,receipt:r,args:s}=e,o={...t,transport:"acp"},i={argv:s,sessionId:e.sessionId??null,currentModeId:r?.currentModeId??null,currentModelId:r?.currentModelId??null,modelVerified:r?.modelVerified??!1,agentVerified:r?.agentVerified??!1,mcpNotices:[...new Set([...r?.mcpNotices??[],...e.notices])],...n.model!==void 0?{requestedModel:n.model}:{},...t.engine!==void 0?{engine:t.engine}:{},...t.effort!==void 0?{requestedEffort:t.effort,effortAck:r?.effortAck??"not-requested",currentEffort:r?.currentEffort??null}:{},...t.tools!==void 0?{toolTrust:t.engine==="v3"?"acp-permission-policy":"argv"}:{}};return{cliVersion:r?.cliVersion??"unknown",transport:"acp",requested:o,effective:i,...e.sessionId!==void 0?{nativeSessionId:e.sessionId}:{},modelAck:r?.modelAck??(n.model===void 0?"not-requested":"rejected"),configHash:F6({requested:o,effective:i})}}var $6,a1,U6=(e)=>new Promise((t)=>{setTimeout(t,e).unref?.()});var u1=G(()=>{nm();tm();Ft();$6=new Set(["end_turn","max_tokens","max_turn_requests","refusal"]),a1=/^_kiro\.dev\/mcp\//});import{spawn as H6,spawnSync as z6}from"node:child_process";import{EventEmitter as K6}from"node:events";import{existsSync as sm,readFileSync as l1,unlinkSync as G6,writeFileSync as h1}from"node:fs";import Qa from"node:os";import om from"node:path";import{createInterface as d1}from"node:readline";import q6 from"node:tls";function ri(e,t=0){if(typeof e==="number"&&Number.isFinite(e))return e;if(typeof e==="string"&&e.trim()!==""&&Number.isFinite(Number(e)))return Number(e);return t}function p1(e){if(e===null||e===void 0||e==="")return null;let t=ri(e,Number.NaN);return Number.isFinite(t)?t:null}function J6(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)&&V6.some((t)=>(t in e))}function Z6(e,t=Date.now()){let n=e.trim();if(!n.startsWith("{"))return null;let r;try{r=JSON.parse(n)}catch{return null}if(typeof r!=="object"||r===null||Array.isArray(r))return null;let s=r;if(typeof s.event!=="string"||s.event.length===0)return null;let o=J6(s.tokenUsage),i=o?s.tokenUsage:{};if(!o&&(s.credits===void 0||s.credits===null)&&(s.contextUsagePercentage===void 0||s.contextUsagePercentage===null))return null;let a=typeof s.ts==="number"&&Number.isFinite(s.ts)?Math.round(s.ts*1000):t,c={event:s.event,totalTokens:ri(i.totalTokens??i.total),credits:p1(s.credits??s.units),contextUsagePercentage:p1(s.contextUsagePercentage??s.contextUsage),raw:s};if(!o)c.tokensAvailable=!1;if(typeof s.url==="string")c.url=s.url;return{agent:"kiro",...typeof s.model==="string"&&s.model!==""?{model:s.model}:{},inputTokens:ri(i.uncachedInputTokens),outputTokens:ri(i.outputTokens),cacheReadTokens:ri(i.cacheReadInputTokens),cacheWriteTokens:ri(i.cacheWriteInputTokens),timestamp:a,extra:c}}function X6(e=Qa.tmpdir()){let t=om.join(e,`kiro-mitm-addon-${process.pid}.py`);return h1(t,Y6,{mode:493}),t}function am(e=process.env.MITMDUMP_BIN??"mitmdump"){if(rm?.bin===e)return rm.available;let t=e.includes("/")?sm(e):z6("/bin/sh",["-c",`command -v ${e}`],{stdio:"ignore"}).status===0;return rm={bin:e,available:t},t}function t4(e=process.env){let t=(e[e4]??"").split(",").map((n)=>n.trim()).filter(Boolean);return`^(?:${[...Q6,...t].join("|")})(?::\\d+)?$`}function n4(e,t,n=process.env){return["-p",String(e),"--listen-host","127.0.0.1","--allow-hosts",t4(n),"-s",t]}function f1(e,t=Qa.tmpdir()){return om.join(t,`kiro-mitm-ca-bundle-${process.pid}-${e}.pem`)}function s4(e,t=Qa.tmpdir()){try{G6(f1(e,t))}catch{}}function o4(e,t=im,n=Qa.tmpdir()){try{if(!sm(e))return e;let r=l1(e,"utf8"),s=[process.env.SSL_CERT_FILE,...r4].find((a)=>!!a&&a!==e&&sm(a)),o=s?l1(s,"utf8"):q6.rootCertificates.join(`
@@ -3212,13 +3212,18 @@ main { flex: 1; min-height: 0; display: grid; grid-template-columns: 1.04fr 1.3f
3212
3212
  .v.c-cr, .v.c-cw { color: var(--teal); }
3213
3213
  .v.c-cost { color: var(--amber); } .v.c-el { color: var(--fg); }
3214
3214
  .v.c-lat { color: var(--cyan); }
3215
- .toollat { padding: 6px 10px 0; flex: none; font: 10.5px var(--mono); color: var(--dim); max-height: 7.5em; overflow-y: auto; }
3215
+ .stat .sub { font: 10px var(--mono); color: var(--dim); margin-top: 1px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
3216
+ .toollat { padding: 6px 10px 0; flex: none; font: 10.5px var(--mono); color: var(--dim); }
3217
+ .toollat.open { max-height: 40%; overflow-y: auto; }
3218
+ .toollat .more { font: inherit; color: var(--cyan); background: none; border: 0; padding: 1px 0; cursor: pointer; }
3219
+ .toollat .more:hover { text-decoration: underline; }
3220
+ .provlegend { font: 9.5px var(--mono); color: var(--faint); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
3216
3221
  .toollat:empty { display: none; }
3217
3222
  .toollat .tl { display: grid; grid-template-columns: minmax(0, 1fr) auto auto auto auto; gap: 10px; padding: 1px 0; }
3218
3223
  .toollat .tl b { color: var(--fg); font-weight: 500; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
3219
3224
  .toollat .tl.hd { color: var(--faint); text-transform: uppercase; letter-spacing: .1em; font-size: 9px; }
3220
3225
  .toollat .err { color: var(--red); }
3221
- .chartwrap { flex: 1; min-height: 0; display: grid; grid-template-rows: 1fr auto auto; padding: 8px 10px 10px; gap: 4px; }
3226
+ .chartwrap { flex: 1; min-height: 0; display: grid; grid-template-rows: 1fr auto auto auto; padding: 8px 10px 10px; gap: 4px; }
3222
3227
  .chartbox { position: relative; min-height: 0; }
3223
3228
  #chart { width: 100%; height: 100%; display: block; }
3224
3229
  #chart .grid { stroke: var(--line); stroke-width: 1; vector-effect: non-scaling-stroke; }
@@ -3440,6 +3445,7 @@ footer.min .tbody { display: none; }
3440
3445
  </div>
3441
3446
  <div class="axt" id="axT"></div>
3442
3447
  <div class="legend"><span><i class="sw sw-t"></i>tokens</span><span><i class="sw sw-u"></i>cost</span></div>
3448
+ <div class="provlegend" title="provenance markers (docs/PROVENANCE.md)">* computed by ach (tokens x bundled price) ≈ estimated (heuristic) unmarked = reported by the agent CLI n/a = not reported</div>
3443
3449
  </div>
3444
3450
  </section>
3445
3451
  <section class="panel logs" aria-label="logs">
@@ -3484,15 +3490,89 @@ function K(n) {
3484
3490
  if (n >= 1e3) return (n / 1e3).toFixed(1) + "k";
3485
3491
  return String(Math.round(n));
3486
3492
  }
3487
- function costUnavailable() {
3488
- return rec && (rec.metering === "none" || (rec.usage && rec.usage.usd && rec.usage.usd.available === false));
3493
+ /* ===== provenance markers (#186; byte-identical to index.html's block, pinned by tests/web-trio-cost.test.ts) ===== */
3494
+ /* provenance:begin */
3495
+ var PROV_MARK = { reported: "", computed: "*", estimated: "\\u2248" };
3496
+ /* Stored totals.provenance wins; a local record written before it existed is
3497
+ derived (the driver always priced costUsd itself); an external record
3498
+ without a map is never guessed at. */
3499
+ function provOf(r) {
3500
+ var t = (r && r.totals) || null;
3501
+ if (!t) return {};
3502
+ if (t.provenance) return t.provenance;
3503
+ if (r.source === "external") return {};
3504
+ var out = {};
3505
+ var usdKnown = !(r.usage && r.usage.usd && r.usage.usd.available === false);
3506
+ if (usdKnown) {
3507
+ if (t.costSource) out.costUsd = t.costSource;
3508
+ else if (t.costUsd > 0) out.costUsd = "computed";
3509
+ }
3510
+ if (t.contextTokens != null) out.contextTokens = "estimated";
3511
+ return out;
3512
+ }
3513
+ function provMark(r, field) {
3514
+ var p = provOf(r)[field];
3515
+ return p ? PROV_MARK[p] || "" : "";
3489
3516
  }
3490
- function observedCost() {
3491
- if (costUnavailable()) return null;
3492
- if (rec && rec.usage && rec.usage.usd && rec.usage.usd.available === true && rec.totals) return rec.totals.costUsd;
3493
- return obs && obs.totalCostUsd;
3517
+ /* Context occupancy is DERIVED: always rendered with the estimated marker.
3518
+ #141: a turn-total reading is cumulative usage, never occupancy (records
3519
+ written before #141 still set totals.contextTokens from it). */
3520
+ function fmtCtx(r) {
3521
+ var c = r && r.usage && r.usage.context;
3522
+ if (c && c.basis === "turn-total") {
3523
+ var cum = c.cumulativeTokens != null ? c.cumulativeTokens : c.tokens;
3524
+ return cum == null ? "n/a" : "n/a (cumulative " + Number(cum).toLocaleString("en-US") + " tok, not occupancy)";
3525
+ }
3526
+ var t = r && r.totals;
3527
+ if (!t || t.contextTokens == null) return "";
3528
+ return PROV_MARK.estimated + Number(t.contextTokens).toLocaleString("en-US") + " tok";
3494
3529
  }
3530
+ /* provenance:end */
3531
+
3532
+ /* trio-cost:begin */
3533
+ var PROV_TITLE = { reported: "reported by the agent CLI", computed: "computed by ach (tokens x bundled price)", estimated: "estimated (heuristic)" };
3495
3534
  function USD(n) { return n == null || !isFinite(n) ? "n/a" : "$" + Number(n).toFixed(3); }
3535
+ function costUnavailableFor(r) {
3536
+ return !!r && (r.metering === "none" || !!(r.usage && r.usage.usd && r.usage.usd.available === false));
3537
+ }
3538
+ /* The run's headline cost (#186). The record's total wins, so trio agrees
3539
+ with the grid and \`ach stats\`, and it carries the same provenance marker
3540
+ the grid shows. When the run's own usage events total a different amount
3541
+ (an older record priced by ach while the agent CLI stated its own cost),
3542
+ that figure is surfaced as \`alt\` instead of being silently dropped. */
3543
+ function costView(r, o) {
3544
+ if (!o) return { value: null, text: "–", mark: "", title: "", alt: null };
3545
+ if (costUnavailableFor(r)) return { value: null, text: "n/a", mark: "", title: "cost not reported", alt: null };
3546
+ var fromRec = !!(r && r.usage && r.usage.usd && r.usage.usd.available === true && r.totals);
3547
+ var v = fromRec ? r.totals.costUsd : o.totalCostUsd;
3548
+ if (v == null || !isFinite(v)) return { value: null, text: "n/a", mark: "", title: "cost not reported", alt: null };
3549
+ var p = fromRec ? provOf(r).costUsd : undefined;
3550
+ var mark = p ? PROV_MARK[p] || "" : "";
3551
+ var title = fromRec ? (p ? PROV_TITLE[p] : "run record total") : "sum of the run's usage events";
3552
+ var alt = null;
3553
+ var s = o.totalCostUsd;
3554
+ if (fromRec && s != null && isFinite(s) && Math.abs(s - v) > Math.max(0.0005, 0.005 * Math.max(Math.abs(s), Math.abs(v)))) {
3555
+ alt = s;
3556
+ title += " · the run's usage events total " + USD(s);
3557
+ }
3558
+ return { value: v, text: USD(v) + mark, mark: mark, title: title, alt: alt };
3559
+ }
3560
+ /* trio-cost:end */
3561
+
3562
+ /* tool-rows:begin */
3563
+ /* Per-tool table (#187): a hidden-scrollbar overflow box cut its last row in
3564
+ half under the chart, with no sign more rows existed. Show the first \`cap\`
3565
+ rows plus an explicit "+K more" toggle instead; expanded shows them all. */
3566
+ var TOOL_ROWS_CAP = 4;
3567
+ function toolRowsView(rows, open, cap) {
3568
+ rows = rows || [];
3569
+ if (rows.length <= cap) return { shown: rows, hidden: 0, toggle: "" };
3570
+ if (open) return { shown: rows, hidden: 0, toggle: "show fewer ▴" };
3571
+ return { shown: rows.slice(0, cap), hidden: rows.length - cap, toggle: "+" + (rows.length - cap) + " more ▾" };
3572
+ }
3573
+ /* tool-rows:end */
3574
+ var toolsOpen = false; // per-tool table expanded (#187)
3575
+ function costUnavailable() { return costUnavailableFor(rec); }
3496
3576
  function S(ms) { return ((ms || 0) / 1000).toFixed(1) + "s"; }
3497
3577
  function fmtDurMs(ms) {
3498
3578
  ms = Number(ms) || 0;
@@ -3553,7 +3633,9 @@ function renderHeader() {
3553
3633
  } else {
3554
3634
  $("pulseTxt").textContent = status.toUpperCase();
3555
3635
  }
3556
- $("totalCost").textContent = obs ? USD(observedCost()) : "\\u2013";
3636
+ var cv = costView(rec, obs);
3637
+ $("totalCost").textContent = cv.text;
3638
+ $("totalCost").title = cv.title;
3557
3639
  }
3558
3640
 
3559
3641
  /* ===== fatal states ===== */
@@ -3713,7 +3795,10 @@ function renderMetrics() {
3713
3795
  ["cache read", last ? K(last.cacheRead) : "\\u2013", "c-cr"],
3714
3796
  ["cache write", last ? K(last.cacheWrite) : "\\u2013", "c-cw"],
3715
3797
  ["cache hit", obs && obs.cacheHitRatio != null ? (obs.cacheHitRatio * 100).toFixed(1) + "%" : (last ? "n/a" : "\\u2013"), "c-cr"],
3716
- ["cost", obs ? USD(observedCost()) : "\\u2013", "c-cost"],
3798
+ (function () {
3799
+ var cv = costView(rec, obs);
3800
+ return ["cost", cv.text, "c-cost", cv.title, cv.alt != null ? "usage events " + USD(cv.alt) : ""];
3801
+ })(),
3717
3802
  ["duration", obs ? S(obs.durationMs) : "\\u2013", "c-el"],
3718
3803
  ];
3719
3804
  // latency (#32): n/a when the log cannot support the metric (no model_call_*
@@ -3734,6 +3819,7 @@ function renderMetrics() {
3734
3819
  if (c[3]) d.title = c[3];
3735
3820
  d.appendChild(el("div", "k", c[0]));
3736
3821
  d.appendChild(el("div", "v " + c[2], c[1]));
3822
+ if (c[4]) d.appendChild(el("div", "sub", c[4]));
3737
3823
  box.appendChild(d);
3738
3824
  });
3739
3825
  // per-model cache-hit (#69): one compact card per model from obs.byModel
@@ -3752,7 +3838,9 @@ function renderMetrics() {
3752
3838
  var hd = el("div", "tl hd");
3753
3839
  ["tool", "calls", "avg", "p95", "total"].forEach(function (h) { hd.appendChild(el("span", null, h)); });
3754
3840
  tl.appendChild(hd);
3755
- toolRows.forEach(function (r) {
3841
+ var view = toolRowsView(toolRows, toolsOpen, TOOL_ROWS_CAP);
3842
+ tl.classList.toggle("open", toolsOpen);
3843
+ view.shown.forEach(function (r) {
3756
3844
  var row = el("div", "tl");
3757
3845
  row.title = r.name + " \\u00b7 max " + fmtDurMs(r.maxMs) + (r.errors ? " \\u00b7 " + r.errors + " error(s)" : "");
3758
3846
  row.appendChild(el("b", null, r.name));
@@ -3762,6 +3850,13 @@ function renderMetrics() {
3762
3850
  row.appendChild(el("span", null, "\\u03a3 " + fmtDurMs(r.totalMs)));
3763
3851
  tl.appendChild(row);
3764
3852
  });
3853
+ if (view.toggle) {
3854
+ var more = el("button", "more", view.toggle);
3855
+ more.type = "button";
3856
+ more.setAttribute("aria-expanded", toolsOpen ? "true" : "false");
3857
+ more.addEventListener("click", function () { toolsOpen = !toolsOpen; renderMetrics(); });
3858
+ tl.appendChild(more);
3859
+ }
3765
3860
  }
3766
3861
  var nPts = obs && obs.metrics ? obs.metrics.length : 0;
3767
3862
  $("chartMeta").textContent = nPts ? nPts + " usage points" : "";