@linzumi/cli 1.0.177 → 1.0.179

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.
@@ -575,7 +575,7 @@ ${e.body}`).digest("hex").slice(0,16),Zj=e=>{switch(e){case"stale_epoch":case"po
575
575
 
576
576
  `);return{body:i===""?"Plan":i,structured:{kind:"agent_plan",item_id:e,transcript_unit_id:`agent_plan:${e}`,stream_state:t,provider:n.provider,provider_turn_id:n.providerTurnId,explanation:n.explanation,steps:n.steps}}}case"commandOutput":{let r=n.chunks[n.chunks.length-1],o=Fy(e,{command:n.command,output:Rpe(n.chunks),processId:n.processId,stream:r?.stream??""},t);return{body:Epe(o),structured:o}}case"fileChange":{let r=iC(n.patchText);return{body:r,structured:mj(e,r,t,t==="completed"?"completed":n.status)}}case"terminalInput":return{body:n.inputText,structured:{kind:"codex_terminal_input",item_id:e,transcript_unit_id:`codex_terminal_input:${e}`,stream_state:t,process_id:n.processId??"",input_text:n.inputText}};case"webSearch":return{body:qk(n.queries),structured:gj(e,n.queries,t)};case"agentStatus":{let r=Ak(e,{...n,body:kc(n.body)},t);return{body:cf(n.title,kc(n.body)),structured:r}}case"agentTaskUpdate":{let r=kc(n.body),o=Ok(e,{...n,body:r},t);return{body:cf(n.title,r??n.progressLabel),structured:o}}}}function Epe(e){let n=h(e.command)??"",t=typeof e.output=="string"?e.output:"";return[`$ ${n}`,t].filter(r=>r.trim()!=="").join(`
577
577
 
578
- `)}function Cq(e){switch(h(e.type)){case"reasoning":return"reasoning";case"agentMessage":return"assistant";case"message":return h(e.role)==="assistant"?"assistant":void 0;case"exitedReviewMode":return"assistant";case"commandExecution":return"commandOutput";case"terminalInput":return"terminalInput";case"fileChange":case"file_change":return"fileChange";case"web_search_call":case"webSearchCall":case"webSearch":return"webSearch";case"agentStatus":return"agentStatus";case"agentTaskUpdate":return"agentTaskUpdate";default:return}}function Tq(e){return e.flatMap((n,t)=>{if(!ne(n))return[];let r=Cq(n);return r===void 0||r==="webSearch"?[]:Cc(n,t).filter(o=>o.body.trim()!=="").map(o=>({snapshotIndex:t,itemId:h(n.id),streamKind:r,body:o.body,structured:o.structured}))})}function sC(e,n){let t=h(e.kind)??"codex_output";return{...e,item_id:n,transcript_unit_id:`${t}:${n}`}}function aC(e,n,t,r){if(t==="webSearch")return`local-codex-search-${xq("sha256").update(`${e}:${n}:web-search`).digest("hex").slice(0,32)}`;let o={assistant:"",reasoning:"reasoning:",agentPlan:"agent-plan:",commandOutput:"command:",fileChange:"file-change:",terminalInput:"terminal:",agentStatus:"agent-status:",agentTaskUpdate:"agent-task:"};return`local-codex-stream-${xq("sha256").update(`${e}:${n}:${o[t]}${r}`).digest("hex").slice(0,32)}`}function xf(e){let n=$(e.turn),t=$(e.item),r=$(t?.turn);return h(n?.id)??h(e.turnId)??h(e.turn_id)??h(t?.turnId)??h(t?.turn_id)??h(r?.id)}var Ppe,dC=q(()=>{"use strict";xs();Wn();jn();Ppe={pending:"PENDING",inProgress:"IN_PROGRESS",completed:"COMPLETED"}});function Iq(e){let n=e.toLowerCase(),t=n.includes("<html")||n.includes("<!doctype html"),r=n.includes("cloudflare");return!!(n.includes("sorry, you have been blocked")||n.includes("attention required")&&r||n.includes("cf_chl_")||n.includes("challenge-platform")||n.includes("just a moment")&&(r||n.includes("cf-"))||t&&(n.includes("cloudflare ray id")||n.includes("cf-ray")||r&&n.includes("blocked")))}var Pq,Rq=q(()=>{"use strict";Pq="edge_blocked"});function uC(e){return Ope.test(e)}function Hy(e){let n=$pe.test(e),t=n?e.match(Lpe)?.[1]:void 0,r=t===void 0?void 0:Number.parseInt(t,10);return{status:qpe(e),requestId:Npe(e),edgeBlocked:Iq(e),oauthExpired:uC(e),providerOutage:n,holdCeilingMinutes:r!==void 0&&r>0?r:void 0,providerOutageRoute:n?{provider:e.match(Fpe)?.[1],model:e.match(jpe)?.[1]}:void 0,message:zpe(e)}}function Gy(e){let n=e.provenance;if(n?.providerOutage===!0)return"route_outage";if(e.stalled)return"transient_upstream";if(n===void 0||n.oauthExpired)return;if(n.edgeBlocked)return"transient_upstream";let t=n.status;if(t!==void 0){if(t===429)return"rate_limited";if(t!==402){if(t===408||t===425||t>=500)return"transient_upstream";if(t>=400&&t<500)return"deterministic"}}}function Dq(e){return e.status!==void 0||e.requestId!==void 0||e.edgeBlocked||e.oauthExpired||e.providerOutage}function Mq(e,n){let t=[];return n.status!==void 0&&t.push(`HTTP ${n.status}`),n.requestId!==void 0&&t.push(`request ${n.requestId}`),n.edgeBlocked&&t.push(`blocked at the network edge by Cloudflare before reaching Linzumi - our infrastructure, not your usage; retrying usually succeeds [failure_class=${Pq}]`),n.oauthExpired&&t.push(`Claude login expired on this computer - run \`claude\` in a terminal there and sign in again, then retry [failure_class=${Mc}]`),t.length===0?e:`${e} (${t.join(", ")})`}function qpe(e){for(let n of Dpe){let t=e.match(n)?.[1];if(t!==void 0)return Number.parseInt(t,10)}}function Npe(e){for(let n of Mpe){let t=e.match(n)?.[1];if(t!==void 0)return t}}function zpe(e){let n=e.match(Ape)?.[1],r=(n===void 0?e:Upe(n)).trim();return r.length<=Eq?r:`${$r(r,Eq-1)}\u2026`}function Upe(e){try{return JSON.parse(`"${e}"`)}catch{return e}}var Eq,Mc,Dpe,Mpe,Ape,Ope,$pe,Lpe,Fpe,jpe,bf=q(()=>{"use strict";Rq();xs();Eq=200,Mc="claude_oauth_expired",Dpe=[/\bAPI Error:?\s*([1-5]\d{2})\b/i,/\b(?:HTTP|status(?:\s+code)?)[\s:]+([1-5]\d{2})\b/i],Mpe=[/"request[_-]id"\s*:\s*"([^"]{1,128})"/i,/\brequest[_ -]id[:=]\s*"?([A-Za-z0-9_-]{6,128})/i,/\b(req_[A-Za-z0-9]{6,})\b/],Ape=/"error"\s*:\s*\{[^{}]*?"message"\s*:\s*"((?:[^"\\]|\\.){1,500})"/,Ope=/\boauth\b[\s\S]{0,120}?\b(?:expired|revoked|could not be refreshed)\b/i;$pe=/"code"\s*:\s*"provider_outage"/,Lpe=/"hold_ceiling_minutes"\s*:\s*(\d{1,4})\b/,Fpe=/"provider"\s*:\s*"([^"]{1,100})"/,jpe=/"model"\s*:\s*"([^"]{1,100})"/});function wf(e){return e!==void 0&&Bpe.has(e)}function Hpe(e){if(e===void 0)return;let n=h(e.type);if(n!=="mcpToolCall"&&n!=="dynamicToolCall"&&n!=="collabAgentToolCall"||h(e.status)!=="completed"||e.error!==void 0&&e.error!==null||e.success===!1)return;let t=h(e.tool)??"";return(t.split("__").pop()??t)===Kpe?"reply":"action"}function qq(e,n){let t=Hpe(n);t==="reply"?e.agentReplyToolCallSeen=!0:t==="action"&&(e.agentActionToolCallSeen=!0)}function Zpe(e){return`The model appears stuck in a loop - stopped after ${e} reasoning steps with no output or tool call (retry to try again).`}function Qpe(e){return e!=="reasoning"}function Xpe(e){return e!==void 0&&e.startsWith(Nq)}function Ype(e){for(let n of e){let t=zq($(n));if(t!==void 0)return t}}function zq(e){if(e===void 0)return;let n=h(e.codex_protocol_failure_reason)??h(e.protocolFailureReason);if(n!==void 0)return n;let t=h(e.type);if(t!=="function_call_output"&&t!=="custom_tool_call_output")return;let r=h(e.output)??h(e.result)??h(e.text)??h(e.content),o=efe(r);return o===void 0?void 0:`${Nq}: ${o}`}function efe(e){let n="unsupported call:";if(e===void 0)return;let t=e.trim();if(!t.toLowerCase().startsWith(n))return;let r=t.slice(n.length).trim();return r===""?"unknown":r}function Uq(){return{phase:"running",turns:new Map,terminalTurnIds:new Set,bufferedTurns:new Map,consecutiveEmptyTurns:0,lastEmptyTurnCause:void 0,lastUpstreamErrorSummary:void 0,consecutiveIsolatedRejections:0,costCap402Seen:!1}}function Bq(e,n,t){let r=[];return e.phase==="running"&&vfe(e,t,r),Jq(e,n,t,r),r}function Jq(e,n,t,r){if(n.source==="lifecycle"){sfe(e,n.kind,n.reason,t,r);return}if(e.phase==="dead"){r.push(yn("pipeline.loop.event_after_death",{source:n.source}));return}if(e.phase==="closing"){r.push(yn("pipeline.loop.event_after_close",{source:n.source}));return}if(n.source==="snapshot"){let o=e.bufferedTurns.get(n.turnId);if(o!==void 0){o.push(n);return}bfe(e,n.turnId,n.snapshot,t,r);return}ife(e,n,t,r)}function ofe(e){return rfe.has(e)}function ife(e,n,t,r){let o=n.notification.method,i=n.notification.params??{};if(o===Sf)return;if(o===Oc){gfe(e,i,t,r);return}if(!tfe.has(o))return;let a=xf(i)??Yy(e);if(a===void 0){r.push(yn("pipeline.loop.notification_without_turn",{method:o}));return}if(e.terminalTurnIds.has(a)){r.push(yn("pipeline.loop.notification_for_terminal_turn",{method:o,turn_id:a}));return}let d=e.turns.get(a);if(d===void 0){let l=t.sourceSeqForTurn(a);if(l===void 0){wfe(e,a,n,r);return}d=afe(e,a,l)}if(d.notificationCount+=1,ofe(o)&&(d.modelInteractionSeen=!0,d.unresolvedUpstreamErrorHttpStatus=void 0),o==="turn/started")return;if(o==="turn/completed"){dfe(d,r);return}let u=nfe.get(o);if(u!==void 0){let l=hfe(o,i,d,{costCap402Seen:e.costCap402Seen,midStreamResumeAttemptAtMs:t.midStreamResumeAttemptAtMsForSeq?.(d.sourceSeq),freshSessionResumeAttemptAtMs:t.freshSessionResumeAttemptAtMsForSeq?.(d.sourceSeq)});l.autoResumeMidStreamStall?r.push(yn("codex.mid_stream_stall_auto_resume_flagged",{thread_key:t.threadKey,turn_id:d.turnId,source_seq:d.sourceSeq,reason:vd(i)})):l.midStreamResumeRateLimitSuppressed?r.push(yn("codex.mid_stream_stall_resume_suppressed_rate_limit",{thread_key:t.threadKey,turn_id:d.turnId,source_seq:d.sourceSeq,reason:vd(i)})):l.midStreamResumeAttemptBurnedAtMs!==void 0&&(r.push(yn("codex.mid_stream_stall_second_stall_after_resume",{thread_key:t.threadKey,turn_id:d.turnId,source_seq:d.sourceSeq,resume_attempt_at_ms:l.midStreamResumeAttemptBurnedAtMs,reason:vd(i),fresh_session_resume_granted:l.freshSessionResumeMidStreamStall===!0})),l.freshSessionResumeMidStreamStall===!0&&r.push(yn("codex.mid_stream_stall_fresh_session_resume_flagged",{thread_key:t.threadKey,turn_id:d.turnId,source_seq:d.sourceSeq,resume_attempt_at_ms:l.midStreamResumeAttemptBurnedAtMs,reason:vd(i)}))),l.autoRetryPreFirstByteStall?r.push(yn("codex.pre_first_byte_stall_auto_retry_flagged",{thread_key:t.threadKey,turn_id:d.turnId,source_seq:d.sourceSeq,reason:vd(i),evidence_class:cC(d)})):l.costCapAutoRetrySuppressed&&r.push(yn("codex.pre_first_byte_stall_retry_suppressed_cost_cap",{thread_key:t.threadKey,turn_id:d.turnId,source_seq:d.sourceSeq,reason:vd(i),flavor:i.midStreamResumableStall===!0?"mid_stream_resume":"pre_first_byte_retry"})),Zy(e,d,u,vd(i),r,t,u,l);return}if(o==="error"){d.errorNotificationCount+=1;let l=Zfe(i);l!==void 0&&(d.toolFatalSeen=!0,d.toolFatalDetail===void 0&&l!==""&&(d.toolFatalDetail=l),r.push(yn("codex.tool_fatal_captured",{turn_id:d.turnId,detail:l===""?null:l})));let p=jfe(i);p!==void 0&&(d.upstreamRejectedSeen=!0,d.upstreamRejectedDetail===void 0&&p!==""&&(d.upstreamRejectedDetail=p),r.push(yn("codex.upstream_rejection_captured",{turn_id:d.turnId,detail:p===""?null:p})));let m=Ufe(i);if(m!==void 0){d.providerOutageFlaggedSeen=!0,d.providerOutageDetail===void 0&&m!==""&&(d.providerOutageDetail=m);let S=Bfe(i);d.providerOutageRoute===void 0&&(d.providerOutageRoute=S),r.push(yn("codex.provider_outage_flagged_captured",{turn_id:d.turnId,detail:m===""?null:m,provider:S?.provider??null,model:S?.model??null,hold_ceiling_ms:S?.holdCeilingMs??null}))}let f=e_(i),y=Tfe(i);y!==void 0&&(d.edgeBlockEvidence=y),f!==void 0&&(d.lastUpstreamErrorHttpStatus===void 0||f>d.lastUpstreamErrorHttpStatus)&&(d.lastUpstreamErrorHttpStatus=f),f===402&&!e.costCap402Seen&&(e.costCap402Seen=!0,r.push(yn("codex.cost_cap_402_seen",{turn_id:d.turnId})));let _=Sfe(i),b=!1;if(_!==void 0)d.lastUpstreamErrorReason=_,r.push(yn("codex.upstream_error_captured",{turn_id:d.turnId,reason:_}));else{let S=kf(i);S!==void 0&&(d.lastErrorDiagnosticText=S,b=!0,r.push(yn("codex.error_without_http_status_captured",{turn_id:d.turnId,diagnostic_text:S})))}l===void 0&&p===void 0&&m===void 0&&f===void 0&&_===void 0&&!b&&(d.unattributedErrorNotificationCount+=1);let v=Lfe(i);v!==void 0&&(d.lastUpstreamErrorSummary=v,e.lastUpstreamErrorSummary=v,r.push(yn("codex.upstream_turn_error_captured",{turn_id:d.turnId,upstream_error:v})));let w=[_,v,d.lastErrorDiagnosticText].some(S=>S!==void 0&&fC.test(S))?429:void 0,k=f??w;k!==void 0&&(d.unresolvedUpstreamErrorHttpStatus=k);return}if((o.startsWith("item/")||o==="command/exec/outputDelta")&&_fe(d,o,i,t,r),o==="item/completed"||o==="response_item"){yfe(d,i,t,r);return}let c=wq(o,i);if(c===void 0){if(o==="turn/plan/updated"){let l=h(i.threadId);r.push(yn("harness.plan_snapshot_rejected",{turn_id:a,...l===void 0?{}:{thread_id:l}}))}return}if(d.phase==="active"){if(Qpe(c.streamKind))d.reasoningStepsWithoutProgress=0;else if(d.reasoningStepsWithoutProgress+=1,d.reasoningStepsWithoutProgress>Lq){let l=Zpe(d.reasoningStepsWithoutProgress);r.push(yn("codex.reasoning_loop_breaker_tripped",{thread_key:t.threadKey,turn_id:d.turnId,source_seq:d.sourceSeq,reasoning_steps_without_progress:d.reasoningStepsWithoutProgress,max_reasoning_steps_without_progress:Lq})),Zy(e,d,"failed",l,r,t,"interrupted");return}}Gq(d,c,t,r)}function sfe(e,n,t,r,o){if(n==="codexDied"){if(e.phase==="dead")return;for(let i of[...e.turns.values()])Zy(e,i,"failed",t,o,r,"interrupted");for(let[i,s]of e.bufferedTurns)o.push(yn("pipeline.loop.buffered_turn_dropped",{turn_id:i,buffered_event_count:s.length,reason:t})),o.push({type:"turnTerminal",turnId:i,outcome:"failed",reason:t}),Xy(e,i);e.bufferedTurns.clear(),e.phase="dead",o.push(yn("pipeline.loop.codex_died",{reason:t}));return}e.phase==="running"&&(e.phase="closing",o.push(yn("pipeline.loop.closing",{kind:n,reason:t})))}function afe(e,n,t){let r={turnId:n,sourceSeq:t,phase:"active",protocolFailureReason:void 0,lastUpstreamErrorReason:void 0,edgeBlockEvidence:void 0,lastErrorDiagnosticText:void 0,toolFatalSeen:!1,toolFatalDetail:void 0,upstreamRejectedSeen:!1,upstreamRejectedDetail:void 0,providerOutageFlaggedSeen:!1,providerOutageDetail:void 0,providerOutageRoute:void 0,lastUpstreamErrorHttpStatus:void 0,unresolvedUpstreamErrorHttpStatus:void 0,lastUpstreamErrorSummary:void 0,errorNotificationCount:0,unattributedErrorNotificationCount:0,notificationCount:0,modelInteractionSeen:!1,reasoningStepsWithoutProgress:0,agentReplyToolCallSeen:!1,agentActionToolCallSeen:!1,items:[]};return e.turns.set(n,r),r}function dfe(e,n){if(e.phase==="completing"){n.push(yn("pipeline.loop.duplicate_turn_completed",{turn_id:e.turnId}));return}e.phase="completing",n.push({type:"requestSnapshot",turnId:e.turnId})}function Kq(e){return e===429||e>=500&&e<=599?"transient":"deterministic"}function mC(){return process.env.LINZUMI_DISABLE_UPSTREAM_ERROR_TURN_FATE_FIX==="1"}function cfe(e){let n=Vq.exec(e);return n!==null?Kq(Number(n[1])):!mC()&&fC.test(e)||ufe.test(e)?"transient":"deterministic"}function cC(e){let n=!1,t=e.upstreamRejectedSeen||e.providerOutageFlaggedSeen||e.toolFatalSeen||e.modelInteractionSeen||e.unattributedErrorNotificationCount>0,r=0;e.lastUpstreamErrorHttpStatus!==void 0&&(r+=1,Kq(e.lastUpstreamErrorHttpStatus)==="transient"?n=!0:t=!0);for(let o of[e.lastUpstreamErrorReason,e.lastErrorDiagnosticText])o!==void 0&&(r+=1,cfe(o)==="transient"?n=!0:t=!0);return e.errorNotificationCount>r+e.unattributedErrorNotificationCount&&!e.upstreamRejectedSeen&&!e.providerOutageFlaggedSeen&&!e.toolFatalSeen&&(t=!0),t?"deterministic":n?"transient":"none"}function lC(e){if(e.lastUpstreamErrorHttpStatus===429)return!0;for(let n of[e.lastUpstreamErrorReason,e.lastErrorDiagnosticText]){if(n===void 0)continue;let t=Vq.exec(n);if(t!==null&&Number(t[1])===429||!mC()&&fC.test(n))return!0}return!1}function pfe(e){return` (An automatic resume was attempted at ${new Date(e).toISOString()} and the stream stalled again, so it will not be retried automatically.)`}function ffe(e){return` (An automatic resume was attempted at ${new Date(e).toISOString()} and the stream stalled again - reconnecting on a fresh model session automatically.)`}function mfe(e){return` (An automatic resume was attempted at ${new Date(e).toISOString()} after the stream stalled; it did not complete.)`}function hfe(e,n,t,r={costCap402Seen:!1}){let o=e==="turn/failed"&&h($(n.error)?.code)==="idle_stream_timeout",i=e==="turn/failed"&&n.retryable===!0,s=(e==="turn/failed"||e==="turn/aborted")&&Do(n.fate)?n.fate:void 0,a=(()=>{if(e!=="turn/failed")return;let M=$(n.route_outage_hold);if(M===void 0)return;let P=Q(M.hold_ceiling_ms);return{provider:h(M.provider),model:h(M.model),holdCeilingMs:P!==void 0&&P>0?P:void 0}})(),d=e==="turn/failed"&&n.failure_class===Mc?Mc:void 0;if(!o)return{autoRetryPreFirstByteStall:!1,messageStateRetryable:i,costCapAutoRetrySuppressed:!1,messageStateFate:s,messageStateFailureClass:d,autoResumeMidStreamStall:!1,midStreamResumeRateLimitSuppressed:!1,...a===void 0?{}:{messageStateRouteOutageHold:a}};let u=r.midStreamResumeAttemptAtMs,c=u!==void 0,l=cC(t)!=="deterministic",p=n.preFirstByteStall===!0&&l,m=n.midStreamResumableStall===!0,f=m&&lC(t),y=cC({...t,modelInteractionSeen:!1})!=="deterministic",_=m&&!c&&!f&&y,b=r.freshSessionResumeAttemptAtMs!==void 0,v=m&&c&&!b&&!f&&y,w=(p&&!c||_||v)&&r.costCap402Seen,k=p&&!c&&!w,S=_&&!w,R=v&&!w,T=m&&!c&&f;return{autoRetryPreFirstByteStall:k,messageStateRetryable:p||i,costCapAutoRetrySuppressed:w,messageStateFate:s??(lC(t)?"rate_limited":"transient_upstream"),messageStateFailureClass:d,autoResumeMidStreamStall:S,midStreamResumeRateLimitSuppressed:T,...c?{midStreamResumeAttemptBurnedAtMs:u}:{},...R?{freshSessionResumeMidStreamStall:!0}:{}}}function Hq(e){return e>0?` (${e} automatic ${e===1?"retry":"retries"} did not help.)`:""}function Zy(e,n,t,r,o,i,s=t,a={autoRetryPreFirstByteStall:!1,messageStateRetryable:!1,costCapAutoRetrySuppressed:!1,messageStateFate:void 0,messageStateFailureClass:void 0,autoResumeMidStreamStall:!1,midStreamResumeRateLimitSuppressed:!1}){let d=Qq(a.messageStateFate,i,{sourceSeq:n.sourceSeq,upstreamHttpStatus:n.lastUpstreamErrorHttpStatus}),u=a.autoRetryPreFirstByteStall||a.costCapAutoRetrySuppressed?`${r}${Hq(i.autoRetryAttemptsForSeq?.(n.sourceSeq)??0)}${a.costCapAutoRetrySuppressed?Wq:""}`:r;if(a.midStreamResumeRateLimitSuppressed&&(u+=lfe),t==="failed")if(a.midStreamResumeAttemptBurnedAtMs!==void 0)u+=a.freshSessionResumeMidStreamStall===!0?ffe(a.midStreamResumeAttemptBurnedAtMs):pfe(a.midStreamResumeAttemptBurnedAtMs);else{let l=i.midStreamResumeAttemptAtMsForSeq?.(n.sourceSeq);l!==void 0&&(u+=mfe(l))}for(let l of n.items){if(!l.posted||wf(l.emittedStreamState))continue;let p=Dc(l.wireItemKey,l.content,s);o.push({type:"enqueue",kind:Tt.finalizeRow,data:{...Qy(i,n,l,p),stream_snapshot_index:vf(l),terminal_outcome:t,reason:r},resolution:"must_ack"}),l.emittedStreamState=s,l.lastEmittedBody=p.body}let c=i.sessionExecutesRecoveryGrants===!0&&t==="failed"&&(a.autoRetryPreFirstByteStall||a.autoResumeMidStreamStall||a.freshSessionResumeMidStreamStall===!0);o.push({type:"enqueue",kind:Tt.messageState,data:{thread_key:i.threadKey,turn_id:n.turnId,seq:n.sourceSeq,status:c?"recovering":"failed",reason:u,...a.messageStateRetryable&&!c?{retryable:!0}:{},...d===void 0?{}:{fate:d},...a.messageStateFailureClass===void 0?{}:{failure_class:a.messageStateFailureClass},...(()=>{let l=d===void 0?void 0:i.ladderHistoryForSeq?.(n.sourceSeq,d);return l===void 0?{}:{ladder:l}})(),...(()=>{let l=n.lastUpstreamErrorSummary??e.lastUpstreamErrorSummary;return l===void 0?{}:{upstream_error:l}})()},resolution:"must_ack"}),o.push({type:"turnTerminal",turnId:n.turnId,outcome:t,reason:u,...a.autoRetryPreFirstByteStall?{retryableEmptyTurn:!0}:{},...a.autoResumeMidStreamStall?{autoResumeMidStreamStall:!0}:{},...a.freshSessionResumeMidStreamStall?{freshSessionResumeMidStreamStall:!0}:{},...d===void 0?{}:{fate:d},...d==="route_outage"?{routeOutageHold:{provider:a.messageStateRouteOutageHold?.provider,model:a.messageStateRouteOutageHold?.model,holdCeilingMs:a.messageStateRouteOutageHold?.holdCeilingMs}}:{}}),e.turns.delete(n.turnId),Xy(e,n.turnId)}function gfe(e,n,t,r){let o=h(n.turnId),i=h(n.reason)??"turn source-seq mapping failed";if(o===void 0||e.terminalTurnIds.has(o))return;let s=e.turns.get(o);if(s!==void 0){Zy(e,s,"failed",i,r,t);return}let a=e.bufferedTurns.get(o);e.bufferedTurns.delete(o),r.push(yn("pipeline.loop.buffered_turn_failed",{level:"warn",turn_id:o,buffered_event_count:a?.length??0,reason:i})),r.push({type:"turnTerminal",turnId:o,outcome:"failed",reason:i}),Xy(e,o)}function Gq(e,n,t,r){if(e.phase!=="active"){r.push(yn("pipeline.loop.delta_for_completing_turn",{turn_id:e.turnId,stream_kind:n.streamKind}));return}let o=Zq(e,n.streamKind,n.itemId,t);if(o.completed){r.push(yn("pipeline.loop.delta_for_completed_item",{turn_id:e.turnId,item_key:o.itemKey}));return}o.content=Sq(o.content,n);let i=o.nextDeltaIndex;o.nextDeltaIndex+=1;let s=n.streamKind==="terminalInput"?"completed":"streaming";hC(e,o,i,s,t,r)}function yfe(e,n,t,r){let o=$(n.item);o!==void 0&&(e.protocolFailureReason??=zq(o)),qq(e,o??n);let i=kq(n);if(i===void 0)return;if(i.streamKind==="webSearch"){Gq(e,{streamKind:"webSearch",itemId:i.itemId,queries:i.content.streamKind==="webSearch"?i.content.queries:[]},t,r);return}if(e.phase!=="active"){r.push(yn("pipeline.loop.item_completed_for_completing_turn",{turn_id:e.turnId,stream_kind:i.streamKind}));return}let s=Zq(e,i.streamKind,i.itemId,t,{adoptOpenIdLess:!0});if(s.completed&&!xfe(s,i))return;s.content=i.content,s.completed=!0;let a=i.streamKind==="assistant"?"streaming":"completed",d=Dc(s.wireItemKey,s.content,a);s.posted&&d.body===s.lastEmittedBody&&(a==="streaming"||wf(s.emittedStreamState))||hC(e,s,Math.max(s.nextDeltaIndex-1,0),a,t,r)}function _fe(e,n,t,r,o){if(e.phase!=="active")return;let i=h(($(t.item)??t).type);if(i==="agentStatus")return;let s=Ec(t),a=n==="item/agentMessage/delta"||i==="agentMessage";for(let d of e.items)d.identity.streamKind!=="assistant"||!d.completed||!d.posted||wf(d.emittedStreamState)||!(s!==void 0?d.identity.itemId!==s:!a)||hC(e,d,Math.max(d.nextDeltaIndex-1,0),"completed",r,o)}function xfe(e,n){return e.identity.streamKind!==n.streamKind?!1:n.streamKind==="agentStatus"||n.streamKind==="agentTaskUpdate"}function hC(e,n,t,r,o,i){let s=Dc(n.wireItemKey,n.content,r);if(!n.posted){if(s.body.trim()==="")return;i.push({type:"enqueue",kind:Tt.postStreamedRow,data:{...Qy(o,e,n,s),delta_index:t,stream_snapshot_index:vf(n)},resolution:"must_ack"}),n.posted=!0,n.emittedStreamState=r,n.lastEmittedBody=s.body,r==="completed"&&(n.completed=!0);return}i.push({type:"enqueue",kind:Tt.streamSnapshot,data:{...Qy(o,e,n,s),delta_index:t,stream_snapshot_index:vf(n)},coalesceKey:n.itemKey,resolution:"must_ack"}),n.emittedStreamState=r,n.lastEmittedBody=s.body}function Zq(e,n,t,r,o={adoptOpenIdLess:!1}){if(n==="webSearch")return e.items.find(s=>s.identity.streamKind==="webSearch")??Fq(e,"webSearch",`web-search:${e.turnId}`,r);if(t!==void 0){let s=e.items.find(a=>a.identity.streamKind===n&&a.identity.itemId===t);if(s!==void 0)return s}let i=e.items.find(s=>s.identity.streamKind===n&&s.identity.itemId===void 0&&!s.completed);return t===void 0&&i!==void 0||t!==void 0&&o.adoptOpenIdLess&&i!==void 0?i:Fq(e,n,t,r)}function Fq(e,n,t,r){let o={turnId:e.turnId,itemId:t,itemIndex:e.items.length,streamKind:n},i=Jj(o),s=t??i,a={identity:o,itemKey:i,wireItemKey:s,clientMessageId:aC(r.instanceId,e.turnId,n,s),content:vq(n),posted:!1,completed:!1,emittedStreamState:void 0,lastEmittedBody:void 0,nextDeltaIndex:0,nextStreamSnapshotIndex:1};return e.items.push(a),a}function bfe(e,n,t,r,o){if(e.terminalTurnIds.has(n)){o.push(yn("pipeline.loop.duplicate_snapshot",{turn_id:n}));return}let i=e.turns.get(n);if(i===void 0){o.push(yn("pipeline.loop.snapshot_for_unknown_turn",{turn_id:n}));return}if(i.phase!=="completing"){o.push(yn("pipeline.loop.snapshot_for_active_turn",{turn_id:n}));return}let s=Array.isArray(t.items)?t.items:[];i.protocolFailureReason??=Ype(s);for(let B of s)qq(i,$(B));let a=Tq(s),d=new Set,u=new Map;a.forEach((B,Ke)=>{if(B.itemId===void 0)return;let He=i.items.find(Ze=>Ze.posted&&!d.has(Ze.itemKey)&&Ze.identity.streamKind===B.streamKind&&Ze.identity.itemId===B.itemId);He!==void 0&&(d.add(He.itemKey),u.set(Ke,He))});let c=new Map;for(let B of i.items)B.posted&&!d.has(B.itemKey)&&B.identity.itemId===void 0&&c.set(B.identity.streamKind,(c.get(B.identity.streamKind)??0)+1);let l=new Map;a.forEach((B,Ke)=>{u.has(Ke)||l.set(B.streamKind,(l.get(B.streamKind)??0)+1)});let p=(B,Ke)=>{let He=Dc(B.wireItemKey,B.content,"completed").body.trim(),Ze=Ke.body.trim();return Ze.startsWith(He)||He.startsWith(Ze)};a.forEach((B,Ke)=>{if(u.has(Ke))return;let He=l.get(B.streamKind)===c.get(B.streamKind);if(B.itemId!==void 0&&!He)return;let Ze=i.items.find(X=>X.posted&&!d.has(X.itemKey)&&X.identity.streamKind===B.streamKind&&X.identity.itemId===void 0);Ze!==void 0&&(B.itemId!==void 0&&!p(Ze,B)||(d.add(Ze.itemKey),u.set(Ke,Ze)))});for(let B of i.items){let Ke=[...u.entries()].find(([,Ze])=>Ze.itemKey===B.itemKey);if(Ke!==void 0){let Ze=a[Ke[0]];if(Ze===void 0||B.identity.streamKind==="assistant"&&wf(B.emittedStreamState)&&B.lastEmittedBody===Ze.body)continue;o.push({type:"enqueue",kind:Tt.finalizeRow,data:{thread_key:r.threadKey,turn_id:i.turnId,item_key:B.itemKey,item_id:B.wireItemKey,stream_kind:B.identity.streamKind,item_index:B.identity.itemIndex,source_seq:i.sourceSeq,client_message_id:B.clientMessageId,body:Ze.body,structured:sC(Ze.structured,B.wireItemKey),stream_snapshot_index:vf(B),terminal_outcome:"completed"},resolution:"must_ack"}),B.emittedStreamState="completed",B.lastEmittedBody=Ze.body;continue}if(!B.posted||wf(B.emittedStreamState))continue;let He=Dc(B.wireItemKey,B.content,"completed");o.push({type:"enqueue",kind:Tt.finalizeRow,data:{...Qy(r,i,B,He),stream_snapshot_index:vf(B),terminal_outcome:"completed"},resolution:"must_ack"}),B.emittedStreamState="completed",B.lastEmittedBody=He.body}a.forEach((B,Ke)=>{if(u.has(Ke))return;let He=B.itemId??`${i.turnId}:${B.streamKind}:snapshot:${B.snapshotIndex}`;o.push({type:"enqueue",kind:Tt.postCompletedRow,data:{thread_key:r.threadKey,turn_id:i.turnId,item_key:`${i.turnId}:${B.streamKind}:${B.itemId??`snapshot:${B.snapshotIndex}`}`,item_id:He,stream_kind:B.streamKind,snapshot_index:B.snapshotIndex,source_seq:i.sourceSeq,client_message_id:aC(r.instanceId,i.turnId,B.streamKind,He),body:B.body,structured:sC(B.structured,He),stream_snapshot_index:1},resolution:"must_ack"})});let m=i.items.some(B=>B.identity.streamKind==="assistant"&&B.posted)||a.some(B=>B.streamKind==="assistant"),f=i.agentActionToolCallSeen||i.items.some(B=>B.posted&&Oq.has(B.identity.streamKind))||a.some(B=>Oq.has(B.streamKind)),y=r.linzumiAgentSession===!0&&m&&!i.agentReplyToolCallSeen&&!f,_=m&&!y,b=_&&!mC()?i.unresolvedUpstreamErrorHttpStatus:void 0,v=b!==void 0,w=i.protocolFailureReason,k=w!==void 0&&Xpe(w)&&_,S=k?void 0:w,R=!_&&w===void 0&&i.lastUpstreamErrorReason===void 0?y?{cause:Wpe}:Qfe(i,a.length,i.lastUpstreamErrorSummary??e.lastUpstreamErrorSummary):void 0,T=!_&&S===void 0&&i.upstreamRejectedSeen,M=!_&&S===void 0&&i.providerOutageFlaggedSeen,P=Ife(i.lastUpstreamErrorHttpStatus),D=!_&&S===void 0&&i.edgeBlockEvidence!==void 0,F=T&&!M&&!P,E=M||F?Vfe({providerOutageFlagged:M,priorConsecutiveIsolatedRejections:e.consecutiveIsolatedRejections,stormDetail:i.providerOutageDetail,rejectionDetail:i.upstreamRejectedDetail}):void 0,N=E?.kind==="isolated_retry";F?e.consecutiveIsolatedRejections+=1:e.consecutiveIsolatedRejections=0;let V=!_&&S===void 0&&i.lastUpstreamErrorReason===void 0&&i.lastErrorDiagnosticText===void 0&&!T&&Pfe(i.lastUpstreamErrorHttpStatus),G=!_&&S===void 0&&i.lastUpstreamErrorReason===void 0&&P,Z=!_&&S===void 0&&i.lastUpstreamErrorReason===void 0&&!T&&!V&&!G&&i.toolFatalSeen,H=E!==void 0?E.reason:G?Rfe(i.lastUpstreamErrorHttpStatus,i.upstreamRejectedDetail??i.lastErrorDiagnosticText):V?Efe(i.lastUpstreamErrorHttpStatus):Z?Mfe(i.toolFatalDetail):i.lastUpstreamErrorReason??(y?Vpe:R===void 0?Aq:`${Aq} [${R.cause}]`),le=R!==void 0&&S===void 0&&i.modelInteractionSeen&&i.lastErrorDiagnosticText===void 0&&!T&&!V&&!G&&!Z;le?(e.consecutiveEmptyTurns+=1,e.lastEmptyTurnCause=R?.cause):(e.consecutiveEmptyTurns=0,e.lastEmptyTurnCause=void 0);let De=le&&e.consecutiveEmptyTurns>$q,we=le&&!De||N,Re=r.autoRetryAttemptsForSeq?.(i.sourceSeq)??0,me=we&&e.costCap402Seen&&Re<po,O=we&&!me;D&&o.push(yn("codex.edge_blocked_captured",{thread_key:r.threadKey,turn_id:i.turnId,source_seq:i.sourceSeq,http_status:i.edgeBlockEvidence?.status,signature:i.edgeBlockEvidence?.signature}));let K=De?`${Gpe} (${e.consecutiveEmptyTurns} in a row${R===void 0?"":`: ${R.cause}`}).`:void 0,ee=S??(b!==void 0?Dfe(b,i.lastUpstreamErrorSummary??e.lastUpstreamErrorSummary):_?void 0:K??H),Ae=ee===void 0?void 0:`${ee}${Hq(le&&!De?Re:0)}${me?Wq:""}`,ve=R!==void 0&&!De&&!T&&!V&&!G&&!Z||N||D||v,xe=M?"route_outage":b!==void 0?Uk(b):ve?"transient_upstream":V?i.lastUpstreamErrorHttpStatus===void 0?"transient_upstream":Uk(i.lastUpstreamErrorHttpStatus):T||Z||G||De||S!==void 0?"deterministic":lC(i)?"rate_limited":"deterministic",se=Qq(xe,r,{sourceSeq:i.sourceSeq,upstreamHttpStatus:b??i.lastUpstreamErrorHttpStatus})??xe;me&&o.push(yn("codex.empty_turn_auto_retry_suppressed_cost_cap",{thread_key:r.threadKey,turn_id:i.turnId,source_seq:i.sourceSeq,reason:ee??null,isolated_rejection_retry_suppressed:N})),De&&o.push(yn("codex.empty_turn_loop_guard_tripped",{thread_key:r.threadKey,turn_id:i.turnId,source_seq:i.sourceSeq,consecutive_empty_turns:e.consecutiveEmptyTurns,max_consecutive_empty_turns:$q,cause:R?.cause??null,last_upstream_error:i.lastUpstreamErrorSummary??e.lastUpstreamErrorSummary??null})),k?o.push(yn("codex.turn_completed_with_unsupported_tool_call_ignored",{thread_key:r.threadKey,turn_id:i.turnId,source_seq:i.sourceSeq,reason:w})):w!==void 0&&o.push(yn("codex.turn_completed_with_protocol_failure",{thread_key:r.threadKey,turn_id:i.turnId,source_seq:i.sourceSeq,reason:w})),y&&o.push(yn("codex.agent_turn_narration_only_no_reply",{thread_key:r.threadKey,turn_id:i.turnId,source_seq:i.sourceSeq,streamed_item_count:i.items.length,snapshot_item_count:a.length,agent_reply_tool_call_seen:i.agentReplyToolCallSeen,agent_action_tool_call_seen:i.agentActionToolCallSeen,retryable_empty_turn:ve,empty_turn_loop_guard_tripped:De})),v&&o.push(yn("codex.turn_demoted_late_upstream_error",{thread_key:r.threadKey,turn_id:i.turnId,source_seq:i.sourceSeq,http_status:b??null,fate:se,streamed_item_count:i.items.length,last_upstream_error:i.lastUpstreamErrorSummary??e.lastUpstreamErrorSummary??null})),m||o.push(yn("codex.turn_completed_without_assistant_output",{thread_key:r.threadKey,turn_id:i.turnId,source_seq:i.sourceSeq,streamed_item_count:i.items.length,snapshot_item_count:a.length,notification_count:i.notificationCount,error_notification_count:i.errorNotificationCount,model_interaction_seen:i.modelInteractionSeen,last_error_diagnostic_text:i.lastErrorDiagnosticText??null,last_upstream_error_reason:i.lastUpstreamErrorReason??null,last_upstream_error_summary:i.lastUpstreamErrorSummary??null,empty_turn_cause:R?.cause??null,tool_fatal_seen:Z,tool_fatal_detail:i.toolFatalDetail??null,upstream_rejected_seen:T,upstream_rejected_detail:i.upstreamRejectedDetail??null,upstream_terminal_4xx:G,last_upstream_error_http_status:i.lastUpstreamErrorHttpStatus??null,provider_outage_flagged:M,isolated_rejection_retry_granted:N,rejection_disposition:E?.kind??null,consecutive_isolated_rejections:e.consecutiveIsolatedRejections,retryable_empty_turn:ve,empty_turn_loop_guard_tripped:De,cost_cap_auto_retry_suppressed:me}));let ie=r.sessionExecutesRecoveryGrants===!0&&O;o.push({type:"enqueue",kind:Tt.messageState,data:{thread_key:r.threadKey,turn_id:i.turnId,seq:i.sourceSeq,...Ae===void 0?{status:"processed"}:{status:ie?"recovering":"failed",reason:Ae,...ve&&!ie?{retryable:!0}:{},fate:se,...(()=>{let B=r.ladderHistoryForSeq?.(i.sourceSeq,se);return B===void 0?{}:{ladder:B}})(),...D?{failure_class:"edge_blocked"}:{},...(()=>{let B=i.lastUpstreamErrorSummary??e.lastUpstreamErrorSummary;return B===void 0?{}:{upstream_error:B}})()}},resolution:"must_ack"}),Ae===void 0&&(e.lastUpstreamErrorSummary=void 0),o.push(Ae===void 0?{type:"turnTerminal",turnId:i.turnId,outcome:"completed"}:{type:"turnTerminal",turnId:i.turnId,outcome:"failed",reason:Ae,...O?{retryableEmptyTurn:!0}:{},fate:se,...se==="route_outage"?{routeOutageHold:{provider:i.providerOutageRoute?.provider,model:i.providerOutageRoute?.model,holdCeilingMs:i.providerOutageRoute?.holdCeilingMs}}:{}}),e.turns.delete(i.turnId),Xy(e,i.turnId)}function wfe(e,n,t,r){let o=e.bufferedTurns.get(n);if(o===void 0){e.bufferedTurns.set(n,[t]),r.push(yn("pipeline.loop.turn_events_buffered",{turn_id:n}));return}o.push(t)}function vfe(e,n,t){for(let r of[...e.bufferedTurns.keys()]){if(n.sourceSeqForTurn(r)===void 0)continue;let o=e.bufferedTurns.get(r)??[];e.bufferedTurns.delete(r),t.push(yn("pipeline.loop.buffered_turn_drained",{turn_id:r,buffered_event_count:o.length}));for(let i of o)Jq(e,i,n,t)}}function Xy(e,n){for(e.terminalTurnIds.delete(n),e.terminalTurnIds.add(n);e.terminalTurnIds.size>Jpe;){let t=e.terminalTurnIds.values().next().value;if(t===void 0)return;e.terminalTurnIds.delete(t)}}function Yy(e){let n=[...e.turns.values()].filter(t=>t.phase==="active");return n.length===1?n[0]?.turnId:void 0}function Qy(e,n,t,r){return{thread_key:e.threadKey,turn_id:n.turnId,item_key:t.itemKey,item_id:t.wireItemKey,stream_kind:t.identity.streamKind,item_index:t.identity.itemIndex,source_seq:n.sourceSeq,client_message_id:t.clientMessageId,body:r.body,structured:r.structured}}function vf(e){let n=e.nextStreamSnapshotIndex;return e.nextStreamSnapshotIndex+=1,n}function vd(e){return h(e.reason)??h(e.message)??h($(e.error)?.message)??h(e.error)??"codex_turn_aborted"}function Sfe(e){let n=h(e.diagnostic_summary)??h($($(e.diagnostic_payload)?.error)?.message);if(n===void 0)return;let t=n.replace(/<[^>]*>/g," ").replace(/data:[^"' )]+/g,"").replace(/\s+/g," ").trim().slice(0,180);if(t.length===0)return;let r=e_(e);return r===void 0?`Model gateway error: ${t}`:`Model gateway error (HTTP ${r}): ${t}`}function e_(e){let n=$($(e.diagnostic_payload)?.error),t=$(n?.codexErrorInfo),o=[$(t?.responseStreamDisconnected)?.httpStatusCode,t?.httpStatusCode,t?.statusCode,t?.status,n?.httpStatusCode,n?.statusCode,n?.status];for(let i of o)if(typeof i=="number"&&Number.isFinite(i))return i}function kfe(e){for(let n of e){if(n===void 0)continue;let t=/unexpected status (401|403)\b/i.exec(n)??/\b(401|403)\s+(?:unauthorized|forbidden)\b/i.exec(n);if(t?.[1]!==void 0)return t[1]==="401"?401:403}}function Cfe(e){return/(?:<!doctype\s+html|<html(?:\s|>))/i.test(e)||/@font-face/i.test(e)&&/cloudflare|cf-ray/i.test(e)}function Tfe(e){let n=$($(e.diagnostic_payload)?.error),t=[h(e.diagnostic_summary),h(n?.message),h(e.message)],r=e_(e)??kfe(t);if(r!==401&&r!==403)return;let o=t.find(s=>s!==void 0&&Cfe(s)&&/cloudflare|cf-ray|\bblocked\b|access denied|\bchallenge\b|attention required/i.test(s));if(o===void 0)return;let i=/cloudflare|cf-ray/i.test(o)?"cloudflare":/\bblocked\b|access denied/i.test(o)?"blocked":/attention required/i.test(o)?"attention_required":"challenge";return{status:r,signature:i}}function Pfe(e){return e===void 0?!1:e===402||e===408||e===425||e===429||e>=500&&e<=599}function Ife(e){return e===void 0||e<400||e>499?!1:e!==402&&e!==408&&e!==425&&e!==429}function Rfe(e,n){let t="the model provider rejected this request as invalid (a retry sends the same request and fails the same way, so it was not retried; check the selected model / request and send again).",r=e===void 0?`Model provider rejected this request: ${t}`:`Model provider rejected this request (HTTP ${e}): ${t}`,o=typeof n=="string"?n.trim():"";return o===""?r:`${r} Upstream said: ${o}`}function Efe(e){let n="the model provider returned no usable response this turn (retrying will not help until it recovers).";return e===void 0?`Model upstream unavailable: ${n}`:`Model upstream unavailable (HTTP ${e}): ${n}`}function Dfe(e,n){let t=n===void 0?"":` Upstream error: ${n}.`,r=e===429?"The upstream reported a rate limit - retry once it clears to run the turn to completion.":"Please retry to run the turn to completion.";return`The turn was cut off by an upstream error (HTTP ${e}) after partial output had already streamed - it did not complete.${t} `+r}function Mfe(e){let n="The agent run was cut off by a tool failure and produced no response (retrying will hit the same failure until the underlying tool call is fixed).",t=typeof e=="string"?e.trim():"";return t===""?`Tool execution failed: ${n}`:`Tool execution failed (${t}): ${n}`}function kf(e){let n=$($(e.diagnostic_payload)?.error),t=h(e.message)??h(e.reason)??h($(e.error)?.message)??h(e.error)??h(e.diagnostic)??h(n?.message)??h($(n?.error)?.message);if(t===void 0)return;let r=t.replace(/<[^>]*>/g," ").replace(/data:[^"' )]+/g,"").replace(/\s+/g," ").trim().slice(0,180);return r.length===0?void 0:r}function Ac(e){if(e===void 0)return;let n=e.replace(/<[^>]*>/g," ").replace(/data:[^"' )]+/g,"").replace(/\s+/g," ").trim().slice(0,180);return n.length===0?void 0:n}function Lfe(e){let n=$(e.error),t=$($(e.diagnostic_payload)?.error),r=$(t?.error),o=e_(e),i=h(n?.type)??h(n?.code)??h(t?.type)??h(t?.code)??h(r?.type)??h(r?.code)??jq(n?.codexErrorInfo)??jq(t?.codexErrorInfo),s=Ac(h(n?.message))??Ac(h(r?.message))??Ac(h(t?.message))??kf(e);if(o===void 0&&i===void 0){let u=oa(h(n?.message))??oa(h(r?.message))??oa(h(t?.message))??oa(h(e.message))??oa(h(e.reason))??oa(h(e.error))??oa(h(e.diagnostic))??oa(h(e.diagnostic_summary));u!==void 0&&(o=u.status,i=u.errorType,s=Ac(u.message)??s)}let a=[o===void 0?void 0:String(o),i?.trim()===""?void 0:i?.trim()].filter(u=>u!==void 0).join(" "),d=a===""?s:s===void 0?a:`${a}: ${s}`;if(!(d===void 0||d===""))return d.slice(0,$fe)}function jq(e){if(typeof e=="string"&&e.trim()!=="")return e;let n=$(e);if(n===void 0)return;let t=Object.keys(n);return t.length===1?t[0]:void 0}function oa(e){if(e===void 0)return;let n=e.indexOf("{");if(n===-1)return;let t=md(e.slice(n))??md(e.slice(n,e.lastIndexOf("}")+1));if(t===void 0||h(t.type)!=="error")return;let r=$(t.error);if(r===void 0)return;let o=t.status;return{status:typeof o=="number"&&Number.isFinite(o)?o:void 0,errorType:h(r.type)??h(r.code),message:h(r.message)}}function Ffe(e){let n=$($(e.diagnostic_payload)?.error),t=$(n?.error),r=$(e.error),o=[{code:h(n?.code),message:h(n?.message)},{code:h(n?.type),message:h(n?.message)},{code:h(t?.code),message:h(t?.message)},{code:h(t?.type),message:h(t?.message)},{code:h(r?.code),message:h(r?.message)},{code:h(r?.type),message:h(r?.message)},{code:h(e.code),message:h(e.message)},{code:h(e.type),message:h(e.message)}];for(let i of o){let s=i.code?.trim();if(s!==void 0&&s!==""&&Afe.test(s))return{codeOrType:s,message:i.message}}}function jfe(e){let n=Ffe(e),t=kf(e),r=t!==void 0&&Ofe.test(t);return n===void 0&&!r?void 0:Ac(n?.message)??t??""}function qfe(e){let n="the model provider rejected this request and produced no response (retrying will hit the same rejection until the request is changed).",t=typeof e=="string"?e.trim():"";return t===""?`The model request was rejected: ${n}`:`The model request was rejected (${t}): ${n}`}function Ufe(e){let n=$($(e.diagnostic_payload)?.error),t=$(n?.error),r=$(e.error),o=[h(n?.code),h(n?.type),h(t?.code),h(t?.type),h(r?.code),h(r?.type),h(e.code),h(e.type)],i=[h(n?.message),h(t?.message),h(r?.message),h(e.message),h(e.reason)];if(o.some(a=>{let d=a?.trim();return d!==void 0&&d!==""&&pC.test(d)})){for(let a of i){let d=Ac(a);if(d!==void 0&&zfe.test(d))return d}return kf(e)??""}}function Qq(e,n,t){return t?.upstreamHttpStatus===402?e:e==="transient_upstream"&&n.routeOutageActive?.(t?.sourceSeq)===!0?"route_outage":e}function Bfe(e){let n=$($(e.diagnostic_payload)?.error),t=$(n?.error),r=$(e.error);for(let o of[t,n,r,e]){if(o===void 0)continue;let i=h(o.code)?.trim(),s=h(o.type)?.trim();if(!(i!==void 0&&i!==""&&pC.test(i)||s!==void 0&&s!==""&&pC.test(s)))continue;let d=o.hold_ceiling_minutes,u=typeof d=="number"&&Number.isFinite(d)&&d>0?Math.floor(d)*6e4:void 0;return{provider:h(o.provider),model:h(o.model),holdCeilingMs:u}}}function Jfe(e){let n=typeof e=="string"?e.trim():"";return n===""?"The model provider is currently rejecting requests / experiencing an outage. Your message was NOT processed. Please retry later, or switch to a different model.":n}function Kfe(e){let n="the model provider rejected this request and produced no response (a one-off retry did not help).",t=typeof e=="string"?e.trim():"";return t===""?`The model request was rejected: ${n}`:`The model request was rejected (${t}): ${n}`}function Vfe(e){return e.providerOutageFlagged?{kind:"storm",retryable:!1,reason:Jfe(e.stormDetail)}:e.priorConsecutiveIsolatedRejections<Nfe?{kind:"isolated_retry",retryable:!0,reason:qfe(e.rejectionDetail)}:{kind:"isolated_terminal",retryable:!1,reason:Kfe(e.rejectionDetail)}}function Gfe(e){return Wfe.test(e)||Hfe.test(e)}function Zfe(e){let n=h(e.kind)??h(e.type)??h($(e.error)?.kind)??h($(e.error)?.type),t=typeof n=="string"&&/(tool.*fatal|fatal.*tool|response[._]failed|tool_failure)/i.test(n),r=kf(e),o=r!==void 0&&Gfe(r);if(!(!t&&!o))return r??""}function Qfe(e,n,t){let r=t===void 0?"":` (last upstream error: ${t})`;return e.lastErrorDiagnosticText!==void 0?{cause:`codex error without HTTP status: ${e.lastErrorDiagnosticText}`}:e.modelInteractionSeen?{cause:`model returned no assistant output: ${e.items.length} streamed items, ${n} snapshot items${r}`}:{cause:`codex never called the model: 0 model interactions, ${e.notificationCount} notifications, ${e.errorNotificationCount} errors${r}`}}function yn(e,n){return{type:"log",event:e,fields:n}}var Bpe,Sf,Oc,Jpe,po,Aq,Kpe,Vpe,Wpe,Oq,$q,Gpe,Lq,Nq,nfe,tfe,rfe,ufe,Vq,fC,lfe,Wq,Afe,Ofe,$fe,Nfe,pC,zfe,Wfe,Hfe,n_=q(()=>{"use strict";bf();Wn();Pc();Ky();dC();Bpe=new Set(["completed","failed","interrupted"]);Sf="pipeline/turnMappingReady",Oc="pipeline/turnMappingFailed",Jpe=512,po=2,Aq="Codex completed without producing a response.",Kpe="linzumi_agent_reply",Vpe="The agent ended its turn after narrating an intent without posting a reply or taking any action.",Wpe="agent narrated intent but posted no reply and took no action",Oq=new Set(["commandOutput","fileChange","terminalInput","agentStatus","agentTaskUpdate"]);$q=3,Gpe="Stopped after repeated empty responses in a row",Lq=64;Nq="Codex emitted unsupported tool call";nfe=new Map([["turn/failed","failed"],["turn/aborted","interrupted"],["turn/canceled","interrupted"],["turn/cancelled","interrupted"]]),tfe=new Set(["turn/started","turn/completed","turn/failed","turn/aborted","turn/canceled","turn/cancelled","error","turn/plan/updated","item/agentMessage/delta","item/reasoning/textDelta","item/commandExecution/outputDelta","command/exec/outputDelta","item/fileChange/outputDelta","item/commandExecution/terminalInteraction","item/started","item/completed","response_item"]),rfe=new Set(["turn/plan/updated","item/agentMessage/delta","item/reasoning/textDelta","item/commandExecution/outputDelta","command/exec/outputDelta","item/fileChange/outputDelta","item/commandExecution/terminalInteraction","item/started","item/completed","response_item"]);ufe=/upstream model stream stalled/i,Vq=/\(HTTP (\d{3})\)/,fC=/\(HTTP 429\)|\bstatus:?\s+429\b|\b429\s+Too\s+Many\s+Requests\b|\bHTTP\s+429\b/i;lfe=" (An automatic resume was not attempted: the upstream reported a rate limit (HTTP 429) during this turn, and an automatic resume would burn straight into it. Retry once the rate limit clears.)";Wq=" (Automatic retries are paused: this session hit your Linzumi cost cap (HTTP 402), and an automatic retry must never spend past it. Retry manually when your budget allows.)";Afe=/^(?:model_request_rejected|invalid_request_error|invalid_request|request_rejected|content_policy_violation|content_filter|input_validation_error)$/i,Ofe=/\bmodel request was rejected\b|\bmodel_request_rejected\b/i;$fe=300;Nfe=1,pC=/^provider_outage$/i,zfe=/rejecting requests|experiencing an outage|provider outage/i;Wfe=/\bapply_patch\b[^]*\bincompatible\b|\bin-flight tool future\b[^]*\bfail/i,Hfe=/\btools::router\b[^]*\bfatal\b|\bresponse\.failed\b/i});function Xq(e){return e===void 0?[]:[...e.values()].map(n=>({...n}))}function Yq(e){let n=Uq(),t={threadKey:e.threadKey,instanceId:e.instanceId,sourceSeqForTurn:e.sourceSeqForTurn,autoRetryAttemptsForSeq:e.autoRetryAttemptsForSeq,midStreamResumeAttemptAtMsForSeq:e.midStreamResumeAttemptAtMsForSeq,freshSessionResumeAttemptAtMsForSeq:e.freshSessionResumeAttemptAtMsForSeq,routeOutageActive:e.routeOutageActive,ladderHistoryForSeq:e.ladderHistoryForSeq,sessionExecutesRecoveryGrants:e.sessionExecutesRecoveryGrants===!0,linzumiAgentSession:e.linzumiAgentSession===!0},r=[],o=e.now??(()=>Date.now()),i=new Map,s=new Map,a=new Map,d=new Map,u=new Set,c=e.bufferedTurnMaxAgeMs??Xfe,l=e.bufferedTurnMaxEvents??Yfe,p=e.bufferedTurnSweepIntervalMs??eme,m=!1,f=!0,y,_=(P,D)=>{try{e.log(P,D)}catch{}},b=P=>{switch(P.type){case"enqueue":e.outbox.enqueue({kind:P.kind,data:P.data,...P.coalesceKey===void 0?{}:{coalesceKey:P.coalesceKey},resolution:P.resolution});return;case"requestSnapshot":e.requestSnapshot(P.turnId);return;case"turnTerminal":e.onTurnTerminal(P.turnId,P.outcome,P.reason,P.retryableEmptyTurn,P.autoResumeMidStreamStall,P.fate,P.freshSessionResumeMidStreamStall,P.routeOutageHold);return;case"log":_(P.event,P.fields);return}},v=()=>{for(let P of n.turns.keys())i.has(P)||i.set(P,o());for(let P of[...i.keys()])n.turns.has(P)||i.delete(P);for(let P of n.bufferedTurns.keys())s.has(P)||s.set(P,o());for(let P of[...s.keys()])n.bufferedTurns.has(P)||(s.delete(P),u.delete(P));for(let P of[...a.keys()])!n.turns.has(P)&&!n.bufferedTurns.has(P)&&a.delete(P);for(let P of[...d.keys()])!n.turns.has(P)&&!n.bufferedTurns.has(P)&&d.delete(P)},w=(P,D)=>{!n.turns.has(P)&&!n.bufferedTurns.has(P)||a.set(P,{atMs:o(),kind:D})},k=P=>{if(P.source!=="codex")return;let D=P.notification.method;if(D===Sf||D===Oc)return;let F=xf(P.notification.params??{})??Yy(n);F!==void 0&&w(F,D)},S=P=>{if(P.source!=="codex")return;let D=P.notification.method;if(D!=="item/started"&&D!=="item/completed"&&D!=="response_item")return;let F=P.notification.params??{},E=xf(F)??Yy(n);if(E===void 0||!n.turns.has(E)&&!n.bufferedTurns.has(E))return;let N=Ec(F);if(N===void 0||N==="")return;if(D!=="item/started"){d.get(E)?.delete(N);return}let V=h($(F.item)?.type);if(V===void 0||!nme.has(V))return;let G=d.get(E);G===void 0&&(G=new Map,d.set(E,G)),G.set(N,{kind:V,startedAtMs:o()})},R=()=>{if(!f||n.phase!=="running")return!1;let P=o(),D=!1;for(let[F,E]of n.bufferedTurns){if(u.has(F))continue;let N=P-(s.get(F)??P),V=N>c,G=E.length>l;!V&&!G||(u.add(F),_("pipeline.loop.buffered_turn_overdue",{level:"warn",thread_key:e.threadKey,turn_id:F,buffered_event_count:E.length,age_ms:N,max_age_ms:c,max_events:l}),r.push({source:"codex",notification:{method:Oc,params:{turnId:F,reason:G?`turn source mapping never arrived (${E.length} buffered events exceeded the ${l} cap)`:`turn source mapping never arrived within ${c}ms`}}}),D=!0)}return D},T=()=>{if(!m){m=!0;try{for(;r.length>0;){let P=r.shift();if(P===void 0)continue;let D;try{D=Bq(n,P,t)}catch(F){_("pipeline.loop.event_processing_failed",{thread_key:e.threadKey,source:P.source,message:F instanceof Error?F.message:String(F)});continue}v(),k(P),S(P);for(let F of D)try{b(F)}catch(E){_("pipeline.loop.effect_failed",{thread_key:e.threadKey,effect:F.type,message:E instanceof Error?E.message:String(E)})}R()}}finally{m=!1}}},M=p>0?setInterval(()=>{R()&&T()},p):void 0;return M?.unref?.(),{submit:P=>{try{if(!f){_("pipeline.loop.event_after_drain",{thread_key:e.threadKey,source:P.source});return}r.push(P),T()}catch(D){_("pipeline.loop.submit_failed",{thread_key:e.threadKey,message:D instanceof Error?D.message:String(D)})}},metrics:()=>({queueDepth:r.length,phase:n.phase,activeTurns:[...n.turns.values()].map(P=>({turnId:P.turnId,sourceSeq:P.sourceSeq,startedAtMs:i.get(P.turnId)??o(),lastActivityAtMs:a.get(P.turnId)?.atMs,lastActivityKind:a.get(P.turnId)?.kind,openItems:Xq(d.get(P.turnId))})),bufferedTurns:[...n.bufferedTurns.entries()].map(([P,D])=>({turnId:P,bufferedEventCount:D.length,firstBufferedAtMs:s.get(P)??o(),lastActivityAtMs:a.get(P)?.atMs,lastActivityKind:a.get(P)?.kind,openItems:Xq(d.get(P))}))}),noteTurnActivity:(P,D)=>{try{w(P,D)}catch(F){_("pipeline.loop.note_activity_failed",{thread_key:e.threadKey,message:F instanceof Error?F.message:String(F)})}},drainAndClose:P=>(y===void 0&&(y=(async()=>{f=!1,M!==void 0&&clearInterval(M),await Promise.resolve(),T();try{await e.outbox.flush(P)}catch(D){_("pipeline.loop.drain_flush_failed",{thread_key:e.threadKey,message:D instanceof Error?D.message:String(D)})}})()),y)}}var Xfe,Yfe,eme,nme,eN=q(()=>{"use strict";Wn();dC();n_();Xfe=10*6e4,Yfe=1e4,eme=3e4,nme=new Set(["commandExecution","terminalInput","mcpToolCall","dynamicToolCall","collabAgentToolCall","contextCompaction"])});function r_(e){let n=ame(e),t=gq({threadKey:e.threadKey,push:e.push,builders:n,...e.persistDir===void 0?{}:{persistDir:e.persistDir},...e.outboxRetryDelaysMs===void 0?{}:{retryDelaysMs:[...e.outboxRetryDelaysMs]},maxInFlightPushes:e.outboxMaxInFlightPushes??rme,...e.journalRecoveryMaxAgeMs===void 0?{}:{journalRecoveryMaxAgeMs:e.journalRecoveryMaxAgeMs},isRetryBudgetExempt:yC,onPermanentFailure:(u,c)=>{e.log("pipeline.outbox_entry_failed",{thread_key:e.threadKey,entry_seq:u.entrySeq,kind:u.kind,attempts:u.attempts,item_key:h(u.data.item_key)??null,turn_id:h(u.data.turn_id)??null,message:c.message})},log:e.log}),r,o=u=>{let c=u.data;if(u.kind===Tt.messageState){let l=h(c.turn_id);l!==void 0&&e.isRecoveredTurn?.(l)===!0&&(c={...c,suppress_terminal_for_recovered_turn:!0});let p=h(c.status);if(p==="failed"||p==="recovering"){let m=e.runtimeMetadataForSourceSeq?.(Q(c.seq)),f=h(m?.model),y=h(m?.model_provider);c={...c,...h(c.model)===void 0&&f!==void 0?{model:f}:{},...h(c.provider)===void 0&&y!==void 0?{provider:y}:{}}}}if(sme(u.kind)){let l=Q(c.source_seq),p=$(c.local_runner_runtime_metadata)??e.runtimeMetadataForSourceSeq?.(l);p!==void 0&&(c={...c,local_runner_runtime_metadata:p})}return c!==u.data?t.enqueue({...u,data:c}):t.enqueue(u)},i={...t,enqueue:u=>{let c=e.wire().kandanThreadId,l=c===void 0?void 0:Xk(c);if(l===void 0)return o(u);let p=nq(l,u.kind,u.data,Date.now(),Tt),m=()=>{for(let y of p)t.enqueue({kind:Qk,data:eq(y),resolution:"must_ack"})};if(u.kind===Tt.messageState){m();let y=o(u);return l.done&&c!==void 0&&oq(c,l),y}let f=o(u);return m(),f}},s=async u=>{let c=e.snapshotRetryDelaysMs??tme;for(let l=0;;l+=1)try{let p=await e.resolveSnapshot(u);r.submit({source:"snapshot",turnId:u,snapshot:{items:[...p.items]}});return}catch(p){let m=p instanceof Error?p.message:String(p),f=c[l];if(e.log("pipeline.snapshot_resolution_failed",{thread_key:e.threadKey,turn_id:u,attempt:l+1,retry_in_ms:f??null,message:m}),f===void 0){r.submit({source:"codex",notification:{method:"turn/failed",params:{turnId:u,reason:`completion snapshot resolution failed: ${m}`}}});return}await pme(f)}};r=Yq({threadKey:e.threadKey,outbox:i,sourceSeqForTurn:e.sourceSeqForTurn,autoRetryAttemptsForSeq:e.autoRetryAttemptsForSeq,midStreamResumeAttemptAtMsForSeq:e.midStreamResumeAttemptAtMsForSeq,freshSessionResumeAttemptAtMsForSeq:e.freshSessionResumeAttemptAtMsForSeq,routeOutageActive:e.routeOutageActive,ladderHistoryForSeq:e.ladderHistoryForSeq,sessionExecutesRecoveryGrants:e.sessionExecutesRecoveryGrants,onTurnTerminal:e.onTurnTerminal,requestSnapshot:u=>{s(u).catch(c=>{e.log("pipeline.snapshot_request_failed",{thread_key:e.threadKey,turn_id:u,message:c instanceof Error?c.message:String(c)})})},instanceId:e.instanceId,log:e.log,linzumiAgentSession:e.linzumiAgentSession===!0});let a=yq({threadKey:e.threadKey,outboxMetrics:()=>t.metrics(),loopMetrics:()=>r.metrics(),log:e.log,intervalMs:e.statsIntervalMs,turnStalledThresholdMs:e.turnStalledThresholdMs,turnWaitStates:e.turnWaitStates}),d;return{submitNotification:(u,c)=>{r.submit({source:"codex",notification:{method:u,params:c}})},notifyTurnMappingReady:u=>{r.submit({source:"codex",notification:{method:Sf,params:{turnId:u}}})},notifyTurnMappingFailed:(u,c)=>{r.submit({source:"codex",notification:{method:Oc,params:{turnId:u,reason:c}}})},noteTurnActivity:(u,c)=>{r.noteTurnActivity(u,c)},submitLifecycle:(u,c)=>{r.submit({source:"lifecycle",kind:u,reason:c})},pause:()=>{t.pause()},resume:()=>{t.resume()},rebindThreadKey:u=>{t.rekeyJournal(u)},flushOutbox:u=>t.flush(u),metrics:()=>t.metrics(),close:u=>(d===void 0&&(d=(async()=>{a.stop(),r.submit({source:"lifecycle",kind:"shutdown",reason:"session closed"}),await r.drainAndClose(u),await t.close(u)})()),d)}}function nN(e){let n=cy(e);return n===void 0?{}:{traceparent:n}}function ome(e){return{...h(e.turn_id)===void 0?{}:{turn_id:h(e.turn_id)},...h(e.item_key)===void 0?{}:{item_key:h(e.item_key)},...Q(e.delta_index)===void 0?{}:{delta_index:Q(e.delta_index)},...Q(e.stream_snapshot_index)===void 0?{}:{stream_snapshot_index:Q(e.stream_snapshot_index)}}}function ime(e){return typeof e.body=="string"?e.body:""}function tN(e){return $(e.structured)??{}}function sme(e){return e===Tt.postStreamedRow||e===Tt.streamSnapshot||e===Tt.finalizeRow||e===Tt.postCompletedRow}function ame(e){let n={build:o=>{let i=e.wire();if(i.kandanThreadId===void 0||i.codexThreadId===void 0)return{skip:!0,reason:"session_thread_unbound"};let s=h(o.client_message_id);if(s===void 0)return{skip:!0,reason:"missing_client_message_id"};let a=h(o.turn_id),d=Q(o.source_seq),u={...a===void 0?{}:{turn_id:a},stream_key:s},c=$(o.local_runner_runtime_metadata),l={...u,...c??{}},p=e.sandboxNetworkDenialSurfacing===!0?pj(tN(o),c):tN(o);return{event:"session:stream_thread_message",payload:{workspace:i.workspaceSlug,channel:i.channelSlug,thread_id:i.kandanThreadId,stream_key:s,...i.leaseEpoch===void 0?{}:{lease_epoch:i.leaseEpoch},body:ime(o),payload:{...e.runnerPayload("codex_output",i.codexThreadId,d,l),...i.rootSeq===void 0?{}:{reply_to_seq:i.rootSeq},...d===void 0?{}:{source_message_seq:d},...u,structured:{...p,stream_key:s}},client_message_id:s,...ome(o),...nN(i.kandanThreadId)}}}},t={build:o=>{let i=e.wire();if(i.kandanThreadId===void 0)return{skip:!0,reason:"session_thread_unbound"};let s=Q(o.seq),a=h(o.status);if(s===void 0||a===void 0)return{skip:!0,reason:"malformed_message_state_entry"};let d=h(o.turn_id);return o.suppress_terminal_for_recovered_turn===!0||d!==void 0&&e.isRecoveredTurn?.(d)===!0?{skip:!0,reason:"terminal_for_recovered_turn"}:{event:"message_state",payload:{workspace:i.workspaceSlug,channel:i.channelSlug,thread_id:i.kandanThreadId,instance_id:e.instanceId,...i.codexThreadId===void 0?{}:{codex_thread_id:i.codexThreadId},seq:s,status:a,...h(o.reason)===void 0?{}:{reason:h(o.reason)},...o.retryable===!0?{retryable:!0}:{},...Do(o.fate)?{fate:o.fate}:{},...$(o.ladder)===void 0?{}:{ladder:$(o.ladder)},...o.failure_class==="edge_blocked"||o.failure_class==="claude_oauth_expired"?{failure_class:o.failure_class}:{},...h(o.upstream_error)===void 0?{}:{upstream_error:h(o.upstream_error)},...h(o.model)===void 0?{}:{model:h(o.model)},...h(o.provider)===void 0?{}:{provider:h(o.provider)},...h(o.turn_id)===void 0?{}:{turn_id:h(o.turn_id)},...i.leaseEpoch===void 0?{}:{lease_epoch:i.leaseEpoch},...nN(i.kandanThreadId)}}}},r={build:o=>{let i=Q(o.session_id);return i!==void 0&&Yk(i)&&h(o.frame_kind)!=="terminal"?{skip:!0,reason:"adt_generation_fenced"}:{event:Vj,payload:{session_id:o.session_id??null,lease_epoch:o.lease_epoch??null,frame_index:o.frame_index??null,frame_kind:o.frame_kind??null,body:o.body??null,byte_len:o.byte_len??null}}},onReply:(o,i)=>{let s=$($(i)?.adt);if(s===void 0)return;let a=Q(o.session_id);if(s.accepted===!1){let d=Zj(s.reason);if(e.log?.("adt.append_rejected",{session_id:a??null,presented_epoch:Q(o.lease_epoch)??null,frame_index:Q(o.frame_index)??null,reason:d}),a!==void 0){iq(a);let u=e.wire().kandanThreadId,c=u===void 0?void 0:Xk(u);c!==void 0&&c.binding.sessionId===a&&Xj(c.emitter),e.log?.("adt.generation_fenced",{session_id:a,reason:d})}return}s.duplicate===!0&&e.log?.("adt.frame_resend_accepted",{session_id:a??null,frame_index:Q(o.frame_index)??null})}};return{[Tt.postStreamedRow]:n,[Tt.streamSnapshot]:n,[Tt.finalizeRow]:n,[Tt.postCompletedRow]:n,[Tt.messageState]:t,[Qk]:r}}function iN(e,n){if("error"in e)return[];let t=$($(e.result)?.thread),o=(Fe(t?.turns)??[]).filter(ne).find(i=>i.id===n);return(Fe(o?.items)??[]).filter(ne)}function gC(e){if(!e.some(t=>dme.has(h(t.type)??"")))return[...e];let n=new Set;return e.forEach(t=>{let r=t_.get(h(t.type)??"");if(r===void 0)return;let o=h(t.call_id);if(o===void 0)return;let i=e.findIndex((s,a)=>!n.has(a)&&h(s.type)===r&&h(s.call_id)===o);i>=0&&n.add(i)}),e.flatMap((t,r)=>{let o=h(t.type)??"",i=t_.get(o);if(i!==void 0){let s=h(t.call_id),a=s===void 0?void 0:e.find(d=>h(d.type)===i&&h(d.call_id)===s);return $k(a===void 0?[t]:[t,a]).flatMap(d=>{let u=rN(d);return u===void 0?[]:[u]})}return o==="function_call_output"||o==="custom_tool_call_output"?n.has(r)?[]:$k([t]).flatMap(s=>{let a=rN(s);return a===void 0?[]:[a]}):[t]})}function rN(e){let n=e.structured,t=/^item-\d+$/.test(e.itemKey)?void 0:e.itemKey,r=t===void 0?{}:{id:t},o=typeof n.output=="string"?n.output:"";switch(h(n.kind)){case"codex_command_execution":{let i=ume(o);return{type:"commandExecution",...r,...i===void 0?{}:{codex_protocol_failure_reason:i},command:h(n.command)??"command",...h(n.tool_name)===void 0?{}:{toolName:h(n.tool_name)},cwd:h(n.cwd)??"",status:h(n.status)??"",...h(n.process_id)===void 0||h(n.process_id)===""?{}:{processId:h(n.process_id)},aggregatedOutput:o}}case"codex_file_change":return{type:"fileChange",...r,status:h(n.status)??"",patchText:h(n.patch_text)??e.body,changes:Fe(n.changes)??[]};default:return}}function ume(e){let n="unsupported call:",t=e.trim();if(!t.toLowerCase().startsWith(n))return;let r=t.slice(n.length).trim();return`Codex emitted unsupported tool call: ${r===""?"unknown":r}`}function sN(e,n){if(n.length===0)return[...e];let t=oN(e),r=oN(n),o=new Set,i=r.map(d=>{let u=d.exactKey===void 0?-1:t.findIndex((l,p)=>!o.has(p)&&l.exactKey===d.exactKey);if(u>=0)return o.add(u),{kind:"read",readIndex:u};let c=d.semanticKey===void 0?-1:t.findIndex((l,p)=>!o.has(p)&&l.semanticKey===d.semanticKey);return c>=0?(o.add(c),{kind:"read",readIndex:c}):{kind:"session",raw:d.raw}}),s=[],a=0;for(let d of i)switch(d.kind){case"read":{for(;a<d.readIndex;){if(!o.has(a)){let c=t[a];c!==void 0&&s.push(c.raw)}a+=1}let u=t[d.readIndex];u!==void 0&&s.push(u.raw),a=Math.max(a,d.readIndex+1);break}case"session":s.push(d.raw);break}for(;a<t.length;){if(!o.has(a)){let d=t[a];d!==void 0&&s.push(d.raw)}a+=1}return s}function oN(e){return e.map((n,t)=>{let r=Cc(n,t).find(o=>o.body.trim()!=="");return r===void 0?{raw:n,exactKey:void 0,semanticKey:void 0}:{raw:n,exactKey:cme(r),semanticKey:lme(r)}})}function cme(e){return`${h(e.structured.kind)??""}:${e.itemKey}`}function lme(e){let n=h(e.structured.kind)??"";switch(n){case"codex_command_execution":return JSON.stringify([n,h(e.structured.command)??"",h(e.structured.cwd)??"",h(e.structured.output)??e.body]);case"codex_file_change":return JSON.stringify([n,h(e.structured.patch_text)??e.body]);case"codex_reasoning":return JSON.stringify([n,h(e.structured.content)??e.body]);case"codex_terminal_input":return JSON.stringify([n,h(e.structured.input_text)??e.body]);default:return JSON.stringify([n,e.body])}}function o_(e){return qj(e)}function yC(e){return Nj(e)}function pme(e){return new Promise(n=>{setTimeout(n,e)})}var tme,rme,t_,dme,_C=q(()=>{"use strict";xs();Wn();Pc();rk();Jy();jn();Ky();oC();_q();eN();n_();tme=[1e3,5e3],rme=16;t_=new Map([["function_call","function_call_output"],["custom_tool_call","custom_tool_call_output"]]),dme=new Set([...t_.keys(),...t_.values()])});import{execFile as fme}from"node:child_process";import{copyFileSync as cN,existsSync as xC,mkdirSync as Tf,readFileSync as lN,readdirSync as Pf,rmSync as aN,statSync as pN,writeFileSync as fN}from"node:fs";import{homedir as mme}from"node:os";import{dirname as bC,join as Ao,resolve as wC}from"node:path";import{promisify as hme}from"node:util";function bme(e=process.env){let n=e[gme];if(n===void 0)return!0;let t=n.trim().toLowerCase();return!(t==="0"||t==="false"||t==="off")}function If(e=process.env){let n=e.LINZUMI_GIT_SAFETY_SNAPSHOTS_DIR;return n!==void 0&&n.trim()!==""?wC(n):wC(mme(),".linzumi","safety-snapshots")}async function Sd(e,n){try{let{stdout:t,stderr:r}=await mN("git",[...n],{cwd:e,encoding:"utf8",timeout:hN,maxBuffer:67108864});return{ok:!0,stdout:t,stderr:r}}catch(t){let r=t;return{ok:!1,stdout:typeof r.stdout=="string"?r.stdout:"",stderr:typeof r.stderr=="string"?r.stderr:t instanceof Error?t.message:String(t)}}}function wme(e){let n=e.split("\0"),t=[];for(let r=0;r<n.length;r+=1){let o=n[r];if(o===void 0||o.length<4)continue;let i=o.slice(0,2),s=o.slice(3);t.push({status:i,path:s}),(i.includes("R")||i.includes("C"))&&(r+=1)}return t}function i_(e){let n=e.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"");return n===""?"x":n}function vme(e){let n=new Date(e.nowMs).toISOString().replace(/-|:|\..*$/g,"").replace("T","-"),t=i_(e.threadId).slice(-12),r=i_(e.turnRef).slice(-12);return`${n}-${t}-${r}`}function Sme(e){return`refs/linzumi/safety/${e}`}async function kme(e){let n=e.env??process.env;if(!bme(n))return{kind:"disabled"};let t=Date.now(),r=()=>Date.now()-t,o=await Sd(e.cwd,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!o.ok)return o.stderr.toLowerCase().includes("not a git repository")?{kind:"not_git",durationMs:r()}:{kind:"error",message:`git status failed: ${o.stderr.trim()}`,durationMs:r()};let i=wme(o.stdout);if(i.length===0)return{kind:"clean",durationMs:r()};try{let s=e.nowMs??t,a=vme({threadId:e.threadId,turnRef:e.turnRef,nowMs:s}),d=e.snapshotsRoot??If(n),u=Ao(d,i_(e.threadId),`${i_(e.turnRef)}-${s}`),c=e.maxTotalBytes??yme,l=i.filter(F=>F.status==="??").map(F=>F.path),p=i.filter(F=>F.status!=="??"&&F.status!=="!!").map(F=>F.path),m=await Sd(e.cwd,["rev-parse","--show-toplevel"]),f=m.ok?m.stdout.trim():e.cwd,y=await Sd(e.cwd,["branch","--show-current"]),_=y.ok&&y.stdout.trim()!==""?y.stdout.trim():void 0,b=await Sd(e.cwd,["rev-parse","HEAD"]),v=b.ok?b.stdout.trim():void 0,w,k;if(p.length>0){let F=await Sd(e.cwd,["stash","create",`linzumi safety snapshot ${a}`]),E=F.ok?F.stdout.trim():"";if(E!==""){w=E;let N=Sme(a);k=(await Sd(e.cwd,["update-ref",N,E])).ok?N:void 0}}Tf(u,{recursive:!0});let S=[],R=0,T=(F,E)=>{let N=Ao(f,F),V=0;try{let G=pN(N);if(!G.isFile())return!1;if(V=G.size,R+V>c)return S.push({path:F,bytes:V,reason:"size_cap"}),!1;let Z=Ao(u,E,F);return Tf(bC(Z),{recursive:!0}),cN(N,Z),R+=V,!0}catch{return S.push({path:F,bytes:V,reason:"copy_error"}),!1}},M=l.filter(F=>T(F,"untracked")),P=w===void 0&&p.length>0?p.filter(F=>T(F,"tracked")):[],D={version:1,id:a,createdAtMs:s,threadId:e.threadId,turnRef:e.turnRef,cwd:e.cwd,repoRoot:f,branch:_,headCommit:v,stashCommit:w,safetyRef:k,trackedPaths:p,untrackedPaths:M,trackedFallbackPaths:P,skippedFiles:S,copiedBytes:R,durationMs:r()};return fN(Ao(u,"manifest.json"),`${JSON.stringify(D,null,2)}
578
+ `)}function Cq(e){switch(h(e.type)){case"reasoning":return"reasoning";case"agentMessage":return"assistant";case"message":return h(e.role)==="assistant"?"assistant":void 0;case"exitedReviewMode":return"assistant";case"commandExecution":return"commandOutput";case"terminalInput":return"terminalInput";case"fileChange":case"file_change":return"fileChange";case"web_search_call":case"webSearchCall":case"webSearch":return"webSearch";case"agentStatus":return"agentStatus";case"agentTaskUpdate":return"agentTaskUpdate";default:return}}function Tq(e){return e.flatMap((n,t)=>{if(!ne(n))return[];let r=Cq(n);return r===void 0||r==="webSearch"?[]:Cc(n,t).filter(o=>o.body.trim()!=="").map(o=>({snapshotIndex:t,itemId:h(n.id),streamKind:r,body:o.body,structured:o.structured}))})}function sC(e,n){let t=h(e.kind)??"codex_output";return{...e,item_id:n,transcript_unit_id:`${t}:${n}`}}function aC(e,n,t,r){if(t==="webSearch")return`local-codex-search-${xq("sha256").update(`${e}:${n}:web-search`).digest("hex").slice(0,32)}`;let o={assistant:"",reasoning:"reasoning:",agentPlan:"agent-plan:",commandOutput:"command:",fileChange:"file-change:",terminalInput:"terminal:",agentStatus:"agent-status:",agentTaskUpdate:"agent-task:"};return`local-codex-stream-${xq("sha256").update(`${e}:${n}:${o[t]}${r}`).digest("hex").slice(0,32)}`}function xf(e){let n=$(e.turn),t=$(e.item),r=$(t?.turn);return h(n?.id)??h(e.turnId)??h(e.turn_id)??h(t?.turnId)??h(t?.turn_id)??h(r?.id)}var Ppe,dC=q(()=>{"use strict";xs();Wn();jn();Ppe={pending:"PENDING",inProgress:"IN_PROGRESS",completed:"COMPLETED"}});function Iq(e){let n=e.toLowerCase(),t=n.includes("<html")||n.includes("<!doctype html"),r=n.includes("cloudflare");return!!(n.includes("sorry, you have been blocked")||n.includes("attention required")&&r||n.includes("cf_chl_")||n.includes("challenge-platform")||n.includes("just a moment")&&(r||n.includes("cf-"))||t&&(n.includes("cloudflare ray id")||n.includes("cf-ray")||r&&n.includes("blocked")))}var Pq,Rq=q(()=>{"use strict";Pq="edge_blocked"});function uC(e){return Ope.test(e)}function Hy(e){let n=$pe.test(e),t=n?e.match(Lpe)?.[1]:void 0,r=t===void 0?void 0:Number.parseInt(t,10);return{status:qpe(e),requestId:Npe(e),edgeBlocked:Iq(e),oauthExpired:uC(e),providerOutage:n,holdCeilingMinutes:r!==void 0&&r>0?r:void 0,providerOutageRoute:n?{provider:e.match(Fpe)?.[1],model:e.match(jpe)?.[1]}:void 0,message:zpe(e)}}function Gy(e){let n=e.provenance;if(n?.providerOutage===!0)return"route_outage";if(e.stalled)return"transient_upstream";if(n===void 0||n.oauthExpired)return;if(n.edgeBlocked)return"transient_upstream";let t=n.status;if(t!==void 0){if(t===429)return"rate_limited";if(t!==402){if(t===408||t===425||t>=500)return"transient_upstream";if(t>=400&&t<500)return"deterministic"}}}function Dq(e){return e.status!==void 0||e.requestId!==void 0||e.edgeBlocked||e.oauthExpired||e.providerOutage}function Mq(e,n){let t=[];return n.status!==void 0&&t.push(`HTTP ${n.status}`),n.requestId!==void 0&&t.push(`request ${n.requestId}`),n.edgeBlocked&&t.push(`blocked at the network edge by Cloudflare before reaching Linzumi - our infrastructure, not your usage; retrying usually succeeds [failure_class=${Pq}]`),n.oauthExpired&&t.push(`Claude login expired on this computer - run \`claude\` in a terminal there and sign in again, then retry [failure_class=${Mc}]`),t.length===0?e:`${e} (${t.join(", ")})`}function qpe(e){for(let n of Dpe){let t=e.match(n)?.[1];if(t!==void 0)return Number.parseInt(t,10)}}function Npe(e){for(let n of Mpe){let t=e.match(n)?.[1];if(t!==void 0)return t}}function zpe(e){let n=e.match(Ape)?.[1],r=(n===void 0?e:Upe(n)).trim();return r.length<=Eq?r:`${$r(r,Eq-1)}\u2026`}function Upe(e){try{return JSON.parse(`"${e}"`)}catch{return e}}var Eq,Mc,Dpe,Mpe,Ape,Ope,$pe,Lpe,Fpe,jpe,bf=q(()=>{"use strict";Rq();xs();Eq=200,Mc="claude_oauth_expired",Dpe=[/\bAPI Error:?\s*([1-5]\d{2})\b/i,/\b(?:HTTP|status(?:\s+code)?)[\s:]+([1-5]\d{2})\b/i],Mpe=[/"request[_-]id"\s*:\s*"([^"]{1,128})"/i,/\brequest[_ -]id[:=]\s*"?([A-Za-z0-9_-]{6,128})/i,/\b(req_[A-Za-z0-9]{6,})\b/],Ape=/"error"\s*:\s*\{[^{}]*?"message"\s*:\s*"((?:[^"\\]|\\.){1,500})"/,Ope=/\boauth\b[\s\S]{0,120}?\b(?:expired|revoked|could not be refreshed)\b/i;$pe=/"code"\s*:\s*"provider_outage"/,Lpe=/"hold_ceiling_minutes"\s*:\s*(\d{1,4})\b/,Fpe=/"provider"\s*:\s*"([^"]{1,100})"/,jpe=/"model"\s*:\s*"([^"]{1,100})"/});function wf(e){return e!==void 0&&Bpe.has(e)}function Hpe(e){if(e===void 0)return;let n=h(e.type);if(n!=="mcpToolCall"&&n!=="dynamicToolCall"&&n!=="collabAgentToolCall"||h(e.status)!=="completed"||e.error!==void 0&&e.error!==null||e.success===!1)return;let t=h(e.tool)??"";return(t.split("__").pop()??t)===Kpe?"reply":"action"}function qq(e,n){let t=Hpe(n);t==="reply"?e.agentReplyToolCallSeen=!0:t==="action"&&(e.agentActionToolCallSeen=!0)}function Zpe(e){return`The model appears stuck in a loop - stopped after ${e} reasoning steps with no output or tool call (retry to try again).`}function Qpe(e){return e!=="reasoning"}function Xpe(e){return e!==void 0&&e.startsWith(Nq)}function Ype(e){for(let n of e){let t=zq($(n));if(t!==void 0)return t}}function zq(e){if(e===void 0)return;let n=h(e.codex_protocol_failure_reason)??h(e.protocolFailureReason);if(n!==void 0)return n;let t=h(e.type);if(t!=="function_call_output"&&t!=="custom_tool_call_output")return;let r=h(e.output)??h(e.result)??h(e.text)??h(e.content),o=efe(r);return o===void 0?void 0:`${Nq}: ${o}`}function efe(e){let n="unsupported call:";if(e===void 0)return;let t=e.trim();if(!t.toLowerCase().startsWith(n))return;let r=t.slice(n.length).trim();return r===""?"unknown":r}function Uq(){return{phase:"running",turns:new Map,terminalTurnIds:new Set,bufferedTurns:new Map,consecutiveEmptyTurns:0,lastEmptyTurnCause:void 0,lastUpstreamErrorSummary:void 0,consecutiveIsolatedRejections:0,costCap402Seen:!1}}function Bq(e,n,t){let r=[];return e.phase==="running"&&vfe(e,t,r),Jq(e,n,t,r),r}function Jq(e,n,t,r){if(n.source==="lifecycle"){sfe(e,n.kind,n.reason,t,r);return}if(e.phase==="dead"){r.push(yn("pipeline.loop.event_after_death",{source:n.source}));return}if(e.phase==="closing"){r.push(yn("pipeline.loop.event_after_close",{source:n.source}));return}if(n.source==="snapshot"){let o=e.bufferedTurns.get(n.turnId);if(o!==void 0){o.push(n);return}bfe(e,n.turnId,n.snapshot,t,r);return}ife(e,n,t,r)}function ofe(e){return rfe.has(e)}function ife(e,n,t,r){let o=n.notification.method,i=n.notification.params??{};if(o===Sf)return;if(o===Oc){gfe(e,i,t,r);return}if(!tfe.has(o))return;let a=xf(i)??Yy(e);if(a===void 0){r.push(yn("pipeline.loop.notification_without_turn",{method:o}));return}if(e.terminalTurnIds.has(a)){r.push(yn("pipeline.loop.notification_for_terminal_turn",{method:o,turn_id:a}));return}let d=e.turns.get(a);if(d===void 0){let l=t.sourceSeqForTurn(a);if(l===void 0){wfe(e,a,n,r);return}d=afe(e,a,l)}if(d.notificationCount+=1,ofe(o)&&(d.modelInteractionSeen=!0,d.unresolvedUpstreamErrorHttpStatus=void 0),o==="turn/started")return;if(o==="turn/completed"){dfe(d,r);return}let u=nfe.get(o);if(u!==void 0){let l=hfe(o,i,d,{costCap402Seen:e.costCap402Seen,midStreamResumeAttemptAtMs:t.midStreamResumeAttemptAtMsForSeq?.(d.sourceSeq),freshSessionResumeAttemptAtMs:t.freshSessionResumeAttemptAtMsForSeq?.(d.sourceSeq)});l.autoResumeMidStreamStall?r.push(yn("codex.mid_stream_stall_auto_resume_flagged",{thread_key:t.threadKey,turn_id:d.turnId,source_seq:d.sourceSeq,reason:vd(i)})):l.midStreamResumeRateLimitSuppressed?r.push(yn("codex.mid_stream_stall_resume_suppressed_rate_limit",{thread_key:t.threadKey,turn_id:d.turnId,source_seq:d.sourceSeq,reason:vd(i)})):l.midStreamResumeAttemptBurnedAtMs!==void 0&&(r.push(yn("codex.mid_stream_stall_second_stall_after_resume",{thread_key:t.threadKey,turn_id:d.turnId,source_seq:d.sourceSeq,resume_attempt_at_ms:l.midStreamResumeAttemptBurnedAtMs,reason:vd(i),fresh_session_resume_granted:l.freshSessionResumeMidStreamStall===!0})),l.freshSessionResumeMidStreamStall===!0&&r.push(yn("codex.mid_stream_stall_fresh_session_resume_flagged",{thread_key:t.threadKey,turn_id:d.turnId,source_seq:d.sourceSeq,resume_attempt_at_ms:l.midStreamResumeAttemptBurnedAtMs,reason:vd(i)}))),l.autoRetryPreFirstByteStall?r.push(yn("codex.pre_first_byte_stall_auto_retry_flagged",{thread_key:t.threadKey,turn_id:d.turnId,source_seq:d.sourceSeq,reason:vd(i),evidence_class:cC(d)})):l.costCapAutoRetrySuppressed&&r.push(yn("codex.pre_first_byte_stall_retry_suppressed_cost_cap",{thread_key:t.threadKey,turn_id:d.turnId,source_seq:d.sourceSeq,reason:vd(i),flavor:i.midStreamResumableStall===!0?"mid_stream_resume":"pre_first_byte_retry"})),Zy(e,d,u,vd(i),r,t,u,l);return}if(o==="error"){d.errorNotificationCount+=1;let l=Zfe(i);l!==void 0&&(d.toolFatalSeen=!0,d.toolFatalDetail===void 0&&l!==""&&(d.toolFatalDetail=l),r.push(yn("codex.tool_fatal_captured",{turn_id:d.turnId,detail:l===""?null:l})));let p=jfe(i);p!==void 0&&(d.upstreamRejectedSeen=!0,d.upstreamRejectedDetail===void 0&&p!==""&&(d.upstreamRejectedDetail=p),r.push(yn("codex.upstream_rejection_captured",{turn_id:d.turnId,detail:p===""?null:p})));let m=Ufe(i);if(m!==void 0){d.providerOutageFlaggedSeen=!0,d.providerOutageDetail===void 0&&m!==""&&(d.providerOutageDetail=m);let S=Bfe(i);d.providerOutageRoute===void 0&&(d.providerOutageRoute=S),r.push(yn("codex.provider_outage_flagged_captured",{turn_id:d.turnId,detail:m===""?null:m,provider:S?.provider??null,model:S?.model??null,hold_ceiling_ms:S?.holdCeilingMs??null}))}let f=e_(i),y=Tfe(i);y!==void 0&&(d.edgeBlockEvidence=y),f!==void 0&&(d.lastUpstreamErrorHttpStatus===void 0||f>d.lastUpstreamErrorHttpStatus)&&(d.lastUpstreamErrorHttpStatus=f),f===402&&!e.costCap402Seen&&(e.costCap402Seen=!0,r.push(yn("codex.cost_cap_402_seen",{turn_id:d.turnId})));let _=Sfe(i),b=!1;if(_!==void 0)d.lastUpstreamErrorReason=_,r.push(yn("codex.upstream_error_captured",{turn_id:d.turnId,reason:_}));else{let S=kf(i);S!==void 0&&(d.lastErrorDiagnosticText=S,b=!0,r.push(yn("codex.error_without_http_status_captured",{turn_id:d.turnId,diagnostic_text:S})))}l===void 0&&p===void 0&&m===void 0&&f===void 0&&_===void 0&&!b&&(d.unattributedErrorNotificationCount+=1);let v=Lfe(i);v!==void 0&&(d.lastUpstreamErrorSummary=v,e.lastUpstreamErrorSummary=v,r.push(yn("codex.upstream_turn_error_captured",{turn_id:d.turnId,upstream_error:v})));let w=[_,v,d.lastErrorDiagnosticText].some(S=>S!==void 0&&fC.test(S))?429:void 0,k=f??w;k!==void 0&&(d.unresolvedUpstreamErrorHttpStatus=k);return}if((o.startsWith("item/")||o==="command/exec/outputDelta")&&_fe(d,o,i,t,r),o==="item/completed"||o==="response_item"){yfe(d,i,t,r);return}let c=wq(o,i);if(c===void 0){if(o==="turn/plan/updated"){let l=h(i.threadId);r.push(yn("harness.plan_snapshot_rejected",{turn_id:a,...l===void 0?{}:{thread_id:l}}))}return}if(d.phase==="active"){if(Qpe(c.streamKind))d.reasoningStepsWithoutProgress=0;else if(d.reasoningStepsWithoutProgress+=1,d.reasoningStepsWithoutProgress>Lq){let l=Zpe(d.reasoningStepsWithoutProgress);r.push(yn("codex.reasoning_loop_breaker_tripped",{thread_key:t.threadKey,turn_id:d.turnId,source_seq:d.sourceSeq,reasoning_steps_without_progress:d.reasoningStepsWithoutProgress,max_reasoning_steps_without_progress:Lq})),Zy(e,d,"failed",l,r,t,"interrupted");return}}Gq(d,c,t,r)}function sfe(e,n,t,r,o){if(n==="codexDied"){if(e.phase==="dead")return;for(let i of[...e.turns.values()])Zy(e,i,"failed",t,o,r,"interrupted");for(let[i,s]of e.bufferedTurns)o.push(yn("pipeline.loop.buffered_turn_dropped",{turn_id:i,buffered_event_count:s.length,reason:t})),o.push({type:"turnTerminal",turnId:i,outcome:"failed",reason:t}),Xy(e,i);e.bufferedTurns.clear(),e.phase="dead",o.push(yn("pipeline.loop.codex_died",{reason:t}));return}e.phase==="running"&&(e.phase="closing",o.push(yn("pipeline.loop.closing",{kind:n,reason:t})))}function afe(e,n,t){let r={turnId:n,sourceSeq:t,phase:"active",protocolFailureReason:void 0,lastUpstreamErrorReason:void 0,edgeBlockEvidence:void 0,lastErrorDiagnosticText:void 0,toolFatalSeen:!1,toolFatalDetail:void 0,upstreamRejectedSeen:!1,upstreamRejectedDetail:void 0,providerOutageFlaggedSeen:!1,providerOutageDetail:void 0,providerOutageRoute:void 0,lastUpstreamErrorHttpStatus:void 0,unresolvedUpstreamErrorHttpStatus:void 0,lastUpstreamErrorSummary:void 0,errorNotificationCount:0,unattributedErrorNotificationCount:0,notificationCount:0,modelInteractionSeen:!1,reasoningStepsWithoutProgress:0,agentReplyToolCallSeen:!1,agentActionToolCallSeen:!1,items:[]};return e.turns.set(n,r),r}function dfe(e,n){if(e.phase==="completing"){n.push(yn("pipeline.loop.duplicate_turn_completed",{turn_id:e.turnId}));return}e.phase="completing",n.push({type:"requestSnapshot",turnId:e.turnId})}function Kq(e){return e===429||e>=500&&e<=599?"transient":"deterministic"}function mC(){return process.env.LINZUMI_DISABLE_UPSTREAM_ERROR_TURN_FATE_FIX==="1"}function cfe(e){let n=Vq.exec(e);return n!==null?Kq(Number(n[1])):!mC()&&fC.test(e)||ufe.test(e)?"transient":"deterministic"}function cC(e){let n=!1,t=e.upstreamRejectedSeen||e.providerOutageFlaggedSeen||e.toolFatalSeen||e.modelInteractionSeen||e.unattributedErrorNotificationCount>0,r=0;e.lastUpstreamErrorHttpStatus!==void 0&&(r+=1,Kq(e.lastUpstreamErrorHttpStatus)==="transient"?n=!0:t=!0);for(let o of[e.lastUpstreamErrorReason,e.lastErrorDiagnosticText])o!==void 0&&(r+=1,cfe(o)==="transient"?n=!0:t=!0);return e.errorNotificationCount>r+e.unattributedErrorNotificationCount&&!e.upstreamRejectedSeen&&!e.providerOutageFlaggedSeen&&!e.toolFatalSeen&&(t=!0),t?"deterministic":n?"transient":"none"}function lC(e){if(e.lastUpstreamErrorHttpStatus===429)return!0;for(let n of[e.lastUpstreamErrorReason,e.lastErrorDiagnosticText]){if(n===void 0)continue;let t=Vq.exec(n);if(t!==null&&Number(t[1])===429||!mC()&&fC.test(n))return!0}return!1}function pfe(e){return` (An automatic resume was attempted at ${new Date(e).toISOString()} and the stream stalled again, so it will not be retried automatically.)`}function ffe(e){return` (An automatic resume was attempted at ${new Date(e).toISOString()} and the stream stalled again - reconnecting on a fresh model session automatically.)`}function mfe(e){return` (An automatic resume was attempted at ${new Date(e).toISOString()} after the stream stalled; it did not complete.)`}function hfe(e,n,t,r={costCap402Seen:!1}){let o=e==="turn/failed"&&h($(n.error)?.code)==="idle_stream_timeout",i=e==="turn/failed"&&n.retryable===!0,s=(e==="turn/failed"||e==="turn/aborted")&&Do(n.fate)?n.fate:void 0,a=(()=>{if(e!=="turn/failed")return;let M=$(n.route_outage_hold);if(M===void 0)return;let P=Q(M.hold_ceiling_ms);return{provider:h(M.provider),model:h(M.model),holdCeilingMs:P!==void 0&&P>0?P:void 0}})(),d=e==="turn/failed"&&n.failure_class===Mc?Mc:void 0;if(!o)return{autoRetryPreFirstByteStall:!1,messageStateRetryable:i,costCapAutoRetrySuppressed:!1,messageStateFate:s,messageStateFailureClass:d,autoResumeMidStreamStall:!1,midStreamResumeRateLimitSuppressed:!1,...a===void 0?{}:{messageStateRouteOutageHold:a}};let u=r.midStreamResumeAttemptAtMs,c=u!==void 0,l=cC(t)!=="deterministic",p=n.preFirstByteStall===!0&&l,m=n.midStreamResumableStall===!0,f=m&&lC(t),y=cC({...t,modelInteractionSeen:!1})!=="deterministic",_=m&&!c&&!f&&y,b=r.freshSessionResumeAttemptAtMs!==void 0,v=m&&c&&!b&&!f&&y,w=(p&&!c||_||v)&&r.costCap402Seen,k=p&&!c&&!w,S=_&&!w,R=v&&!w,T=m&&!c&&f;return{autoRetryPreFirstByteStall:k,messageStateRetryable:p||i,costCapAutoRetrySuppressed:w,messageStateFate:s??(lC(t)?"rate_limited":"transient_upstream"),messageStateFailureClass:d,autoResumeMidStreamStall:S,midStreamResumeRateLimitSuppressed:T,...c?{midStreamResumeAttemptBurnedAtMs:u}:{},...R?{freshSessionResumeMidStreamStall:!0}:{}}}function Hq(e){return e>0?` (${e} automatic ${e===1?"retry":"retries"} did not help.)`:""}function Zy(e,n,t,r,o,i,s=t,a={autoRetryPreFirstByteStall:!1,messageStateRetryable:!1,costCapAutoRetrySuppressed:!1,messageStateFate:void 0,messageStateFailureClass:void 0,autoResumeMidStreamStall:!1,midStreamResumeRateLimitSuppressed:!1}){let d=Qq(a.messageStateFate,i,{sourceSeq:n.sourceSeq,upstreamHttpStatus:n.lastUpstreamErrorHttpStatus}),u=a.autoRetryPreFirstByteStall||a.costCapAutoRetrySuppressed?`${r}${Hq(i.autoRetryAttemptsForSeq?.(n.sourceSeq)??0)}${a.costCapAutoRetrySuppressed?Wq:""}`:r;if(a.midStreamResumeRateLimitSuppressed&&(u+=lfe),t==="failed")if(a.midStreamResumeAttemptBurnedAtMs!==void 0)u+=a.freshSessionResumeMidStreamStall===!0?ffe(a.midStreamResumeAttemptBurnedAtMs):pfe(a.midStreamResumeAttemptBurnedAtMs);else{let l=i.midStreamResumeAttemptAtMsForSeq?.(n.sourceSeq);l!==void 0&&(u+=mfe(l))}for(let l of n.items){if(!l.posted||wf(l.emittedStreamState))continue;let p=Dc(l.wireItemKey,l.content,s);o.push({type:"enqueue",kind:Tt.finalizeRow,data:{...Qy(i,n,l,p),stream_snapshot_index:vf(l),terminal_outcome:t,reason:r},resolution:"must_ack"}),l.emittedStreamState=s,l.lastEmittedBody=p.body}let c=i.sessionExecutesRecoveryGrants===!0&&t==="failed"&&(a.autoRetryPreFirstByteStall||a.autoResumeMidStreamStall||a.freshSessionResumeMidStreamStall===!0);o.push({type:"enqueue",kind:Tt.messageState,data:{thread_key:i.threadKey,turn_id:n.turnId,seq:n.sourceSeq,status:c?"recovering":"failed",reason:u,...a.messageStateRetryable&&!c?{retryable:!0}:{},...d===void 0?{}:{fate:d},...a.messageStateFailureClass===void 0?{}:{failure_class:a.messageStateFailureClass},...(()=>{let l=d===void 0?void 0:i.ladderHistoryForSeq?.(n.sourceSeq,d);return l===void 0?{}:{ladder:l}})(),...(()=>{let l=n.lastUpstreamErrorSummary??e.lastUpstreamErrorSummary;return l===void 0?{}:{upstream_error:l}})()},resolution:"must_ack"}),o.push({type:"turnTerminal",turnId:n.turnId,outcome:t,reason:u,...a.autoRetryPreFirstByteStall?{retryableEmptyTurn:!0}:{},...a.autoResumeMidStreamStall?{autoResumeMidStreamStall:!0}:{},...a.freshSessionResumeMidStreamStall?{freshSessionResumeMidStreamStall:!0}:{},...d===void 0?{}:{fate:d},...d==="route_outage"?{routeOutageHold:{provider:a.messageStateRouteOutageHold?.provider,model:a.messageStateRouteOutageHold?.model,holdCeilingMs:a.messageStateRouteOutageHold?.holdCeilingMs}}:{}}),e.turns.delete(n.turnId),Xy(e,n.turnId)}function gfe(e,n,t,r){let o=h(n.turnId),i=h(n.reason)??"turn source-seq mapping failed";if(o===void 0||e.terminalTurnIds.has(o))return;let s=e.turns.get(o);if(s!==void 0){Zy(e,s,"failed",i,r,t);return}let a=e.bufferedTurns.get(o);e.bufferedTurns.delete(o),r.push(yn("pipeline.loop.buffered_turn_failed",{level:"warn",turn_id:o,buffered_event_count:a?.length??0,reason:i})),r.push({type:"turnTerminal",turnId:o,outcome:"failed",reason:i}),Xy(e,o)}function Gq(e,n,t,r){if(e.phase!=="active"){r.push(yn("pipeline.loop.delta_for_completing_turn",{turn_id:e.turnId,stream_kind:n.streamKind}));return}let o=Zq(e,n.streamKind,n.itemId,t);if(o.completed){r.push(yn("pipeline.loop.delta_for_completed_item",{turn_id:e.turnId,item_key:o.itemKey}));return}o.content=Sq(o.content,n);let i=o.nextDeltaIndex;o.nextDeltaIndex+=1;let s=n.streamKind==="terminalInput"?"completed":"streaming";hC(e,o,i,s,t,r)}function yfe(e,n,t,r){let o=$(n.item);o!==void 0&&(e.protocolFailureReason??=zq(o)),qq(e,o??n);let i=kq(n);if(i===void 0)return;if(i.streamKind==="webSearch"){Gq(e,{streamKind:"webSearch",itemId:i.itemId,queries:i.content.streamKind==="webSearch"?i.content.queries:[]},t,r);return}if(e.phase!=="active"){r.push(yn("pipeline.loop.item_completed_for_completing_turn",{turn_id:e.turnId,stream_kind:i.streamKind}));return}let s=Zq(e,i.streamKind,i.itemId,t,{adoptOpenIdLess:!0});if(s.completed&&!xfe(s,i))return;s.content=i.content,s.completed=!0;let a=i.streamKind==="assistant"?"streaming":"completed",d=Dc(s.wireItemKey,s.content,a);s.posted&&d.body===s.lastEmittedBody&&(a==="streaming"||wf(s.emittedStreamState))||hC(e,s,Math.max(s.nextDeltaIndex-1,0),a,t,r)}function _fe(e,n,t,r,o){if(e.phase!=="active")return;let i=h(($(t.item)??t).type);if(i==="agentStatus")return;let s=Ec(t),a=n==="item/agentMessage/delta"||i==="agentMessage";for(let d of e.items)d.identity.streamKind!=="assistant"||!d.completed||!d.posted||wf(d.emittedStreamState)||!(s!==void 0?d.identity.itemId!==s:!a)||hC(e,d,Math.max(d.nextDeltaIndex-1,0),"completed",r,o)}function xfe(e,n){return e.identity.streamKind!==n.streamKind?!1:n.streamKind==="agentStatus"||n.streamKind==="agentTaskUpdate"}function hC(e,n,t,r,o,i){let s=Dc(n.wireItemKey,n.content,r);if(!n.posted){if(s.body.trim()==="")return;i.push({type:"enqueue",kind:Tt.postStreamedRow,data:{...Qy(o,e,n,s),delta_index:t,stream_snapshot_index:vf(n)},resolution:"must_ack"}),n.posted=!0,n.emittedStreamState=r,n.lastEmittedBody=s.body,r==="completed"&&(n.completed=!0);return}i.push({type:"enqueue",kind:Tt.streamSnapshot,data:{...Qy(o,e,n,s),delta_index:t,stream_snapshot_index:vf(n)},coalesceKey:n.itemKey,resolution:"must_ack"}),n.emittedStreamState=r,n.lastEmittedBody=s.body}function Zq(e,n,t,r,o={adoptOpenIdLess:!1}){if(n==="webSearch")return e.items.find(s=>s.identity.streamKind==="webSearch")??Fq(e,"webSearch",`web-search:${e.turnId}`,r);if(t!==void 0){let s=e.items.find(a=>a.identity.streamKind===n&&a.identity.itemId===t);if(s!==void 0)return s}let i=e.items.find(s=>s.identity.streamKind===n&&s.identity.itemId===void 0&&!s.completed);return t===void 0&&i!==void 0||t!==void 0&&o.adoptOpenIdLess&&i!==void 0?i:Fq(e,n,t,r)}function Fq(e,n,t,r){let o={turnId:e.turnId,itemId:t,itemIndex:e.items.length,streamKind:n},i=Jj(o),s=t??i,a={identity:o,itemKey:i,wireItemKey:s,clientMessageId:aC(r.instanceId,e.turnId,n,s),content:vq(n),posted:!1,completed:!1,emittedStreamState:void 0,lastEmittedBody:void 0,nextDeltaIndex:0,nextStreamSnapshotIndex:1};return e.items.push(a),a}function bfe(e,n,t,r,o){if(e.terminalTurnIds.has(n)){o.push(yn("pipeline.loop.duplicate_snapshot",{turn_id:n}));return}let i=e.turns.get(n);if(i===void 0){o.push(yn("pipeline.loop.snapshot_for_unknown_turn",{turn_id:n}));return}if(i.phase!=="completing"){o.push(yn("pipeline.loop.snapshot_for_active_turn",{turn_id:n}));return}let s=Array.isArray(t.items)?t.items:[];i.protocolFailureReason??=Ype(s);for(let B of s)qq(i,$(B));let a=Tq(s),d=new Set,u=new Map;a.forEach((B,Ke)=>{if(B.itemId===void 0)return;let He=i.items.find(Ze=>Ze.posted&&!d.has(Ze.itemKey)&&Ze.identity.streamKind===B.streamKind&&Ze.identity.itemId===B.itemId);He!==void 0&&(d.add(He.itemKey),u.set(Ke,He))});let c=new Map;for(let B of i.items)B.posted&&!d.has(B.itemKey)&&B.identity.itemId===void 0&&c.set(B.identity.streamKind,(c.get(B.identity.streamKind)??0)+1);let l=new Map;a.forEach((B,Ke)=>{u.has(Ke)||l.set(B.streamKind,(l.get(B.streamKind)??0)+1)});let p=(B,Ke)=>{let He=Dc(B.wireItemKey,B.content,"completed").body.trim(),Ze=Ke.body.trim();return Ze.startsWith(He)||He.startsWith(Ze)};a.forEach((B,Ke)=>{if(u.has(Ke))return;let He=l.get(B.streamKind)===c.get(B.streamKind);if(B.itemId!==void 0&&!He)return;let Ze=i.items.find(X=>X.posted&&!d.has(X.itemKey)&&X.identity.streamKind===B.streamKind&&X.identity.itemId===void 0);Ze!==void 0&&(B.itemId!==void 0&&!p(Ze,B)||(d.add(Ze.itemKey),u.set(Ke,Ze)))});for(let B of i.items){let Ke=[...u.entries()].find(([,Ze])=>Ze.itemKey===B.itemKey);if(Ke!==void 0){let Ze=a[Ke[0]];if(Ze===void 0||B.identity.streamKind==="assistant"&&wf(B.emittedStreamState)&&B.lastEmittedBody===Ze.body)continue;o.push({type:"enqueue",kind:Tt.finalizeRow,data:{thread_key:r.threadKey,turn_id:i.turnId,item_key:B.itemKey,item_id:B.wireItemKey,stream_kind:B.identity.streamKind,item_index:B.identity.itemIndex,source_seq:i.sourceSeq,client_message_id:B.clientMessageId,body:Ze.body,structured:sC(Ze.structured,B.wireItemKey),stream_snapshot_index:vf(B),terminal_outcome:"completed"},resolution:"must_ack"}),B.emittedStreamState="completed",B.lastEmittedBody=Ze.body;continue}if(!B.posted||wf(B.emittedStreamState))continue;let He=Dc(B.wireItemKey,B.content,"completed");o.push({type:"enqueue",kind:Tt.finalizeRow,data:{...Qy(r,i,B,He),stream_snapshot_index:vf(B),terminal_outcome:"completed"},resolution:"must_ack"}),B.emittedStreamState="completed",B.lastEmittedBody=He.body}a.forEach((B,Ke)=>{if(u.has(Ke))return;let He=B.itemId??`${i.turnId}:${B.streamKind}:snapshot:${B.snapshotIndex}`;o.push({type:"enqueue",kind:Tt.postCompletedRow,data:{thread_key:r.threadKey,turn_id:i.turnId,item_key:`${i.turnId}:${B.streamKind}:${B.itemId??`snapshot:${B.snapshotIndex}`}`,item_id:He,stream_kind:B.streamKind,snapshot_index:B.snapshotIndex,source_seq:i.sourceSeq,client_message_id:aC(r.instanceId,i.turnId,B.streamKind,He),body:B.body,structured:sC(B.structured,He),stream_snapshot_index:1},resolution:"must_ack"})});let m=i.items.some(B=>B.identity.streamKind==="assistant"&&B.posted)||a.some(B=>B.streamKind==="assistant"),f=i.agentActionToolCallSeen||i.items.some(B=>B.posted&&Oq.has(B.identity.streamKind))||a.some(B=>Oq.has(B.streamKind)),y=r.linzumiAgentSession===!0&&m&&!i.agentReplyToolCallSeen&&!f,_=m&&!y,b=_&&!mC()?i.unresolvedUpstreamErrorHttpStatus:void 0,v=b!==void 0,w=i.protocolFailureReason,k=w!==void 0&&Xpe(w)&&_,S=k?void 0:w,R=!_&&w===void 0&&i.lastUpstreamErrorReason===void 0?y?{cause:Wpe}:Qfe(i,a.length,i.lastUpstreamErrorSummary??e.lastUpstreamErrorSummary):void 0,T=!_&&S===void 0&&i.upstreamRejectedSeen,M=!_&&S===void 0&&i.providerOutageFlaggedSeen,P=Ife(i.lastUpstreamErrorHttpStatus),D=!_&&S===void 0&&i.edgeBlockEvidence!==void 0,F=T&&!M&&!P,E=M||F?Vfe({providerOutageFlagged:M,priorConsecutiveIsolatedRejections:e.consecutiveIsolatedRejections,stormDetail:i.providerOutageDetail,rejectionDetail:i.upstreamRejectedDetail}):void 0,N=E?.kind==="isolated_retry";F?e.consecutiveIsolatedRejections+=1:e.consecutiveIsolatedRejections=0;let V=!_&&S===void 0&&i.lastUpstreamErrorReason===void 0&&i.lastErrorDiagnosticText===void 0&&!T&&Pfe(i.lastUpstreamErrorHttpStatus),G=!_&&S===void 0&&i.lastUpstreamErrorReason===void 0&&P,Z=!_&&S===void 0&&i.lastUpstreamErrorReason===void 0&&!T&&!V&&!G&&i.toolFatalSeen,H=E!==void 0?E.reason:G?Rfe(i.lastUpstreamErrorHttpStatus,i.upstreamRejectedDetail??i.lastErrorDiagnosticText):V?Efe(i.lastUpstreamErrorHttpStatus):Z?Mfe(i.toolFatalDetail):i.lastUpstreamErrorReason??(y?Vpe:R===void 0?Aq:`${Aq} [${R.cause}]`),le=R!==void 0&&S===void 0&&i.modelInteractionSeen&&i.lastErrorDiagnosticText===void 0&&!T&&!V&&!G&&!Z;le?(e.consecutiveEmptyTurns+=1,e.lastEmptyTurnCause=R?.cause):(e.consecutiveEmptyTurns=0,e.lastEmptyTurnCause=void 0);let De=le&&e.consecutiveEmptyTurns>$q,we=le&&!De||N,Re=r.autoRetryAttemptsForSeq?.(i.sourceSeq)??0,me=we&&e.costCap402Seen&&Re<po,O=we&&!me;D&&o.push(yn("codex.edge_blocked_captured",{thread_key:r.threadKey,turn_id:i.turnId,source_seq:i.sourceSeq,http_status:i.edgeBlockEvidence?.status,signature:i.edgeBlockEvidence?.signature}));let K=De?`${Gpe} (${e.consecutiveEmptyTurns} in a row${R===void 0?"":`: ${R.cause}`}).`:void 0,ee=S??(b!==void 0?Dfe(b,i.lastUpstreamErrorSummary??e.lastUpstreamErrorSummary):_?void 0:K??H),Ae=ee===void 0?void 0:`${ee}${Hq(le&&!De?Re:0)}${me?Wq:""}`,ve=R!==void 0&&!De&&!T&&!V&&!G&&!Z||N||D||v,xe=M?"route_outage":b!==void 0?Uk(b):ve?"transient_upstream":V?i.lastUpstreamErrorHttpStatus===void 0?"transient_upstream":Uk(i.lastUpstreamErrorHttpStatus):T||Z||G||De||S!==void 0?"deterministic":lC(i)?"rate_limited":"deterministic",se=Qq(xe,r,{sourceSeq:i.sourceSeq,upstreamHttpStatus:b??i.lastUpstreamErrorHttpStatus})??xe;me&&o.push(yn("codex.empty_turn_auto_retry_suppressed_cost_cap",{thread_key:r.threadKey,turn_id:i.turnId,source_seq:i.sourceSeq,reason:ee??null,isolated_rejection_retry_suppressed:N})),De&&o.push(yn("codex.empty_turn_loop_guard_tripped",{thread_key:r.threadKey,turn_id:i.turnId,source_seq:i.sourceSeq,consecutive_empty_turns:e.consecutiveEmptyTurns,max_consecutive_empty_turns:$q,cause:R?.cause??null,last_upstream_error:i.lastUpstreamErrorSummary??e.lastUpstreamErrorSummary??null})),k?o.push(yn("codex.turn_completed_with_unsupported_tool_call_ignored",{thread_key:r.threadKey,turn_id:i.turnId,source_seq:i.sourceSeq,reason:w})):w!==void 0&&o.push(yn("codex.turn_completed_with_protocol_failure",{thread_key:r.threadKey,turn_id:i.turnId,source_seq:i.sourceSeq,reason:w})),y&&o.push(yn("codex.agent_turn_narration_only_no_reply",{thread_key:r.threadKey,turn_id:i.turnId,source_seq:i.sourceSeq,streamed_item_count:i.items.length,snapshot_item_count:a.length,agent_reply_tool_call_seen:i.agentReplyToolCallSeen,agent_action_tool_call_seen:i.agentActionToolCallSeen,retryable_empty_turn:ve,empty_turn_loop_guard_tripped:De})),v&&o.push(yn("codex.turn_demoted_late_upstream_error",{thread_key:r.threadKey,turn_id:i.turnId,source_seq:i.sourceSeq,http_status:b??null,fate:se,streamed_item_count:i.items.length,last_upstream_error:i.lastUpstreamErrorSummary??e.lastUpstreamErrorSummary??null})),m||o.push(yn("codex.turn_completed_without_assistant_output",{thread_key:r.threadKey,turn_id:i.turnId,source_seq:i.sourceSeq,streamed_item_count:i.items.length,snapshot_item_count:a.length,notification_count:i.notificationCount,error_notification_count:i.errorNotificationCount,model_interaction_seen:i.modelInteractionSeen,last_error_diagnostic_text:i.lastErrorDiagnosticText??null,last_upstream_error_reason:i.lastUpstreamErrorReason??null,last_upstream_error_summary:i.lastUpstreamErrorSummary??null,empty_turn_cause:R?.cause??null,tool_fatal_seen:Z,tool_fatal_detail:i.toolFatalDetail??null,upstream_rejected_seen:T,upstream_rejected_detail:i.upstreamRejectedDetail??null,upstream_terminal_4xx:G,last_upstream_error_http_status:i.lastUpstreamErrorHttpStatus??null,provider_outage_flagged:M,isolated_rejection_retry_granted:N,rejection_disposition:E?.kind??null,consecutive_isolated_rejections:e.consecutiveIsolatedRejections,retryable_empty_turn:ve,empty_turn_loop_guard_tripped:De,cost_cap_auto_retry_suppressed:me}));let ie=r.sessionExecutesRecoveryGrants===!0&&O;o.push({type:"enqueue",kind:Tt.messageState,data:{thread_key:r.threadKey,turn_id:i.turnId,seq:i.sourceSeq,...Ae===void 0?{status:"processed"}:{status:ie?"recovering":"failed",reason:Ae,...ve&&!ie?{retryable:!0}:{},fate:se,...(()=>{let B=r.ladderHistoryForSeq?.(i.sourceSeq,se);return B===void 0?{}:{ladder:B}})(),...D?{failure_class:"edge_blocked"}:{},...(()=>{let B=i.lastUpstreamErrorSummary??e.lastUpstreamErrorSummary;return B===void 0?{}:{upstream_error:B}})()}},resolution:"must_ack"}),Ae===void 0&&(e.lastUpstreamErrorSummary=void 0),o.push(Ae===void 0?{type:"turnTerminal",turnId:i.turnId,outcome:"completed"}:{type:"turnTerminal",turnId:i.turnId,outcome:"failed",reason:Ae,...O?{retryableEmptyTurn:!0}:{},fate:se,...se==="route_outage"?{routeOutageHold:{provider:i.providerOutageRoute?.provider,model:i.providerOutageRoute?.model,holdCeilingMs:i.providerOutageRoute?.holdCeilingMs}}:{}}),e.turns.delete(i.turnId),Xy(e,i.turnId)}function wfe(e,n,t,r){let o=e.bufferedTurns.get(n);if(o===void 0){e.bufferedTurns.set(n,[t]),r.push(yn("pipeline.loop.turn_events_buffered",{turn_id:n}));return}o.push(t)}function vfe(e,n,t){for(let r of[...e.bufferedTurns.keys()]){if(n.sourceSeqForTurn(r)===void 0)continue;let o=e.bufferedTurns.get(r)??[];e.bufferedTurns.delete(r),t.push(yn("pipeline.loop.buffered_turn_drained",{turn_id:r,buffered_event_count:o.length}));for(let i of o)Jq(e,i,n,t)}}function Xy(e,n){for(e.terminalTurnIds.delete(n),e.terminalTurnIds.add(n);e.terminalTurnIds.size>Jpe;){let t=e.terminalTurnIds.values().next().value;if(t===void 0)return;e.terminalTurnIds.delete(t)}}function Yy(e){let n=[...e.turns.values()].filter(t=>t.phase==="active");return n.length===1?n[0]?.turnId:void 0}function Qy(e,n,t,r){return{thread_key:e.threadKey,turn_id:n.turnId,item_key:t.itemKey,item_id:t.wireItemKey,stream_kind:t.identity.streamKind,item_index:t.identity.itemIndex,source_seq:n.sourceSeq,client_message_id:t.clientMessageId,body:r.body,structured:r.structured}}function vf(e){let n=e.nextStreamSnapshotIndex;return e.nextStreamSnapshotIndex+=1,n}function vd(e){return h(e.reason)??h(e.message)??h($(e.error)?.message)??h(e.error)??"codex_turn_aborted"}function Sfe(e){let n=h(e.diagnostic_summary)??h($($(e.diagnostic_payload)?.error)?.message);if(n===void 0)return;let t=n.replace(/<[^>]*>/g," ").replace(/data:[^"' )]+/g,"").replace(/\s+/g," ").trim().slice(0,180);if(t.length===0)return;let r=e_(e);return r===void 0?`Model gateway error: ${t}`:`Model gateway error (HTTP ${r}): ${t}`}function e_(e){let n=$($(e.diagnostic_payload)?.error),t=$(n?.codexErrorInfo),o=[$(t?.responseStreamDisconnected)?.httpStatusCode,t?.httpStatusCode,t?.statusCode,t?.status,n?.httpStatusCode,n?.statusCode,n?.status];for(let i of o)if(typeof i=="number"&&Number.isFinite(i))return i}function kfe(e){for(let n of e){if(n===void 0)continue;let t=/unexpected status (401|403)\b/i.exec(n)??/\b(401|403)\s+(?:unauthorized|forbidden)\b/i.exec(n);if(t?.[1]!==void 0)return t[1]==="401"?401:403}}function Cfe(e){return/(?:<!doctype\s+html|<html(?:\s|>))/i.test(e)||/@font-face/i.test(e)&&/cloudflare|cf-ray/i.test(e)}function Tfe(e){let n=$($(e.diagnostic_payload)?.error),t=[h(e.diagnostic_summary),h(n?.message),h(e.message)],r=e_(e)??kfe(t);if(r!==401&&r!==403)return;let o=t.find(s=>s!==void 0&&Cfe(s)&&/cloudflare|cf-ray|\bblocked\b|access denied|\bchallenge\b|attention required/i.test(s));if(o===void 0)return;let i=/cloudflare|cf-ray/i.test(o)?"cloudflare":/\bblocked\b|access denied/i.test(o)?"blocked":/attention required/i.test(o)?"attention_required":"challenge";return{status:r,signature:i}}function Pfe(e){return e===void 0?!1:e===402||e===408||e===425||e===429||e>=500&&e<=599}function Ife(e){return e===void 0||e<400||e>499?!1:e!==402&&e!==408&&e!==425&&e!==429}function Rfe(e,n){let t="the model provider rejected this request as invalid (a retry sends the same request and fails the same way, so it was not retried; check the selected model / request and send again).",r=e===void 0?`Model provider rejected this request: ${t}`:`Model provider rejected this request (HTTP ${e}): ${t}`,o=typeof n=="string"?n.trim():"";return o===""?r:`${r} Upstream said: ${o}`}function Efe(e){let n="the model provider returned no usable response this turn (retrying will not help until it recovers).";return e===void 0?`Model upstream unavailable: ${n}`:`Model upstream unavailable (HTTP ${e}): ${n}`}function Dfe(e,n){let t=n===void 0?"":` Upstream error: ${n}.`,r=e===429?"The upstream reported a rate limit - retry once it clears to run the turn to completion.":"Please retry to run the turn to completion.";return`The turn was cut off by an upstream error (HTTP ${e}) after partial output had already streamed - it did not complete.${t} `+r}function Mfe(e){let n="The agent run was cut off by a tool failure and produced no response (retrying will hit the same failure until the underlying tool call is fixed).",t=typeof e=="string"?e.trim():"";return t===""?`Tool execution failed: ${n}`:`Tool execution failed (${t}): ${n}`}function kf(e){let n=$($(e.diagnostic_payload)?.error),t=h(e.message)??h(e.reason)??h($(e.error)?.message)??h(e.error)??h(e.diagnostic)??h(n?.message)??h($(n?.error)?.message);if(t===void 0)return;let r=t.replace(/<[^>]*>/g," ").replace(/data:[^"' )]+/g,"").replace(/\s+/g," ").trim().slice(0,180);return r.length===0?void 0:r}function Ac(e){if(e===void 0)return;let n=e.replace(/<[^>]*>/g," ").replace(/data:[^"' )]+/g,"").replace(/\s+/g," ").trim().slice(0,180);return n.length===0?void 0:n}function Lfe(e){let n=$(e.error),t=$($(e.diagnostic_payload)?.error),r=$(t?.error),o=e_(e),i=h(n?.type)??h(n?.code)??h(t?.type)??h(t?.code)??h(r?.type)??h(r?.code)??jq(n?.codexErrorInfo)??jq(t?.codexErrorInfo),s=Ac(h(n?.message))??Ac(h(r?.message))??Ac(h(t?.message))??kf(e);if(o===void 0&&i===void 0){let u=oa(h(n?.message))??oa(h(r?.message))??oa(h(t?.message))??oa(h(e.message))??oa(h(e.reason))??oa(h(e.error))??oa(h(e.diagnostic))??oa(h(e.diagnostic_summary));u!==void 0&&(o=u.status,i=u.errorType,s=Ac(u.message)??s)}let a=[o===void 0?void 0:String(o),i?.trim()===""?void 0:i?.trim()].filter(u=>u!==void 0).join(" "),d=a===""?s:s===void 0?a:`${a}: ${s}`;if(!(d===void 0||d===""))return d.slice(0,$fe)}function jq(e){if(typeof e=="string"&&e.trim()!=="")return e;let n=$(e);if(n===void 0)return;let t=Object.keys(n);return t.length===1?t[0]:void 0}function oa(e){if(e===void 0)return;let n=e.indexOf("{");if(n===-1)return;let t=md(e.slice(n))??md(e.slice(n,e.lastIndexOf("}")+1));if(t===void 0||h(t.type)!=="error")return;let r=$(t.error);if(r===void 0)return;let o=t.status;return{status:typeof o=="number"&&Number.isFinite(o)?o:void 0,errorType:h(r.type)??h(r.code),message:h(r.message)}}function Ffe(e){let n=$($(e.diagnostic_payload)?.error),t=$(n?.error),r=$(e.error),o=[{code:h(n?.code),message:h(n?.message)},{code:h(n?.type),message:h(n?.message)},{code:h(t?.code),message:h(t?.message)},{code:h(t?.type),message:h(t?.message)},{code:h(r?.code),message:h(r?.message)},{code:h(r?.type),message:h(r?.message)},{code:h(e.code),message:h(e.message)},{code:h(e.type),message:h(e.message)}];for(let i of o){let s=i.code?.trim();if(s!==void 0&&s!==""&&Afe.test(s))return{codeOrType:s,message:i.message}}}function jfe(e){let n=Ffe(e),t=kf(e),r=t!==void 0&&Ofe.test(t);return n===void 0&&!r?void 0:Ac(n?.message)??t??""}function qfe(e){let n="the model provider rejected this request and produced no response (retrying will hit the same rejection until the request is changed).",t=typeof e=="string"?e.trim():"";return t===""?`The model request was rejected: ${n}`:`The model request was rejected (${t}): ${n}`}function Ufe(e){let n=$($(e.diagnostic_payload)?.error),t=$(n?.error),r=$(e.error),o=[h(n?.code),h(n?.type),h(t?.code),h(t?.type),h(r?.code),h(r?.type),h(e.code),h(e.type)],i=[h(n?.message),h(t?.message),h(r?.message),h(e.message),h(e.reason)];if(o.some(a=>{let d=a?.trim();return d!==void 0&&d!==""&&pC.test(d)})){for(let a of i){let d=Ac(a);if(d!==void 0&&zfe.test(d))return d}return kf(e)??""}}function Qq(e,n,t){return t?.upstreamHttpStatus===402?e:e==="transient_upstream"&&n.routeOutageActive?.(t?.sourceSeq)===!0?"route_outage":e}function Bfe(e){let n=$($(e.diagnostic_payload)?.error),t=$(n?.error),r=$(e.error);for(let o of[t,n,r,e]){if(o===void 0)continue;let i=h(o.code)?.trim(),s=h(o.type)?.trim();if(!(i!==void 0&&i!==""&&pC.test(i)||s!==void 0&&s!==""&&pC.test(s)))continue;let d=o.hold_ceiling_minutes,u=typeof d=="number"&&Number.isFinite(d)&&d>0?Math.floor(d)*6e4:void 0;return{provider:h(o.provider),model:h(o.model),holdCeilingMs:u}}}function Jfe(e){let n=typeof e=="string"?e.trim():"";return n===""?"The model provider is currently rejecting requests / experiencing an outage. Your message was NOT processed. Please retry later, or switch to a different model.":n}function Kfe(e){let n="the model provider rejected this request and produced no response (a one-off retry did not help).",t=typeof e=="string"?e.trim():"";return t===""?`The model request was rejected: ${n}`:`The model request was rejected (${t}): ${n}`}function Vfe(e){return e.providerOutageFlagged?{kind:"storm",retryable:!1,reason:Jfe(e.stormDetail)}:e.priorConsecutiveIsolatedRejections<Nfe?{kind:"isolated_retry",retryable:!0,reason:qfe(e.rejectionDetail)}:{kind:"isolated_terminal",retryable:!1,reason:Kfe(e.rejectionDetail)}}function Gfe(e){return Wfe.test(e)||Hfe.test(e)}function Zfe(e){let n=h(e.kind)??h(e.type)??h($(e.error)?.kind)??h($(e.error)?.type),t=typeof n=="string"&&/(tool.*fatal|fatal.*tool|response[._]failed|tool_failure)/i.test(n),r=kf(e),o=r!==void 0&&Gfe(r);if(!(!t&&!o))return r??""}function Qfe(e,n,t){let r=t===void 0?"":` (last upstream error: ${t})`;return e.lastErrorDiagnosticText!==void 0?{cause:`codex error without HTTP status: ${e.lastErrorDiagnosticText}`}:e.modelInteractionSeen?{cause:`model returned no assistant output: ${e.items.length} streamed items, ${n} snapshot items${r}`}:{cause:`codex never called the model: 0 model interactions, ${e.notificationCount} notifications, ${e.errorNotificationCount} errors${r}`}}function yn(e,n){return{type:"log",event:e,fields:n}}var Bpe,Sf,Oc,Jpe,po,Aq,Kpe,Vpe,Wpe,Oq,$q,Gpe,Lq,Nq,nfe,tfe,rfe,ufe,Vq,fC,lfe,Wq,Afe,Ofe,$fe,Nfe,pC,zfe,Wfe,Hfe,n_=q(()=>{"use strict";bf();Wn();Pc();Ky();dC();Bpe=new Set(["completed","failed","interrupted"]);Sf="pipeline/turnMappingReady",Oc="pipeline/turnMappingFailed",Jpe=512,po=2,Aq="Codex completed without producing a response.",Kpe="linzumi_agent_reply",Vpe="The agent ended its turn after narrating an intent without posting a reply or taking any action.",Wpe="agent narrated intent but posted no reply and took no action",Oq=new Set(["commandOutput","fileChange","terminalInput","agentStatus","agentTaskUpdate"]);$q=3,Gpe="Stopped after repeated empty responses in a row",Lq=64;Nq="Codex emitted unsupported tool call";nfe=new Map([["turn/failed","failed"],["turn/aborted","interrupted"],["turn/canceled","interrupted"],["turn/cancelled","interrupted"]]),tfe=new Set(["turn/started","turn/completed","turn/failed","turn/aborted","turn/canceled","turn/cancelled","error","turn/plan/updated","item/agentMessage/delta","item/reasoning/textDelta","item/commandExecution/outputDelta","command/exec/outputDelta","item/fileChange/outputDelta","item/commandExecution/terminalInteraction","item/started","item/completed","response_item"]),rfe=new Set(["turn/plan/updated","item/agentMessage/delta","item/reasoning/textDelta","item/commandExecution/outputDelta","command/exec/outputDelta","item/fileChange/outputDelta","item/commandExecution/terminalInteraction","item/started","item/completed","response_item"]);ufe=/upstream model stream stalled/i,Vq=/\(HTTP (\d{3})\)/,fC=/\(HTTP 429\)|\bstatus:?\s+429\b|\b429\s+Too\s+Many\s+Requests\b|\bHTTP\s+429\b/i;lfe=" (An automatic resume was not attempted: the upstream reported a rate limit (HTTP 429) during this turn, and an automatic resume would burn straight into it. Retry once the rate limit clears.)";Wq=" (Automatic retries are paused: this session hit your Linzumi cost cap (HTTP 402), and an automatic retry must never spend past it. Retry manually when your budget allows.)";Afe=/^(?:model_request_rejected|invalid_request_error|invalid_request|request_rejected|content_policy_violation|content_filter|input_validation_error)$/i,Ofe=/\bmodel request was rejected\b|\bmodel_request_rejected\b/i;$fe=300;Nfe=1,pC=/^provider_outage$/i,zfe=/rejecting requests|experiencing an outage|provider outage/i;Wfe=/\bapply_patch\b[^]*\bincompatible\b|\bin-flight tool future\b[^]*\bfail/i,Hfe=/\btools::router\b[^]*\bfatal\b|\bresponse\.failed\b/i});function Xq(e){return e===void 0?[]:[...e.values()].map(n=>({...n}))}function Yq(e){let n=Uq(),t={threadKey:e.threadKey,instanceId:e.instanceId,sourceSeqForTurn:e.sourceSeqForTurn,autoRetryAttemptsForSeq:e.autoRetryAttemptsForSeq,midStreamResumeAttemptAtMsForSeq:e.midStreamResumeAttemptAtMsForSeq,freshSessionResumeAttemptAtMsForSeq:e.freshSessionResumeAttemptAtMsForSeq,routeOutageActive:e.routeOutageActive,ladderHistoryForSeq:e.ladderHistoryForSeq,sessionExecutesRecoveryGrants:e.sessionExecutesRecoveryGrants===!0,linzumiAgentSession:e.linzumiAgentSession===!0},r=[],o=e.now??(()=>Date.now()),i=new Map,s=new Map,a=new Map,d=new Map,u=new Set,c=e.bufferedTurnMaxAgeMs??Xfe,l=e.bufferedTurnMaxEvents??Yfe,p=e.bufferedTurnSweepIntervalMs??eme,m=!1,f=!0,y,_=(P,D)=>{try{e.log(P,D)}catch{}},b=P=>{switch(P.type){case"enqueue":e.outbox.enqueue({kind:P.kind,data:P.data,...P.coalesceKey===void 0?{}:{coalesceKey:P.coalesceKey},resolution:P.resolution});return;case"requestSnapshot":e.requestSnapshot(P.turnId);return;case"turnTerminal":e.onTurnTerminal(P.turnId,P.outcome,P.reason,P.retryableEmptyTurn,P.autoResumeMidStreamStall,P.fate,P.freshSessionResumeMidStreamStall,P.routeOutageHold);return;case"log":_(P.event,P.fields);return}},v=()=>{for(let P of n.turns.keys())i.has(P)||i.set(P,o());for(let P of[...i.keys()])n.turns.has(P)||i.delete(P);for(let P of n.bufferedTurns.keys())s.has(P)||s.set(P,o());for(let P of[...s.keys()])n.bufferedTurns.has(P)||(s.delete(P),u.delete(P));for(let P of[...a.keys()])!n.turns.has(P)&&!n.bufferedTurns.has(P)&&a.delete(P);for(let P of[...d.keys()])!n.turns.has(P)&&!n.bufferedTurns.has(P)&&d.delete(P)},w=(P,D)=>{!n.turns.has(P)&&!n.bufferedTurns.has(P)||a.set(P,{atMs:o(),kind:D})},k=P=>{if(P.source!=="codex")return;let D=P.notification.method;if(D===Sf||D===Oc)return;let F=xf(P.notification.params??{})??Yy(n);F!==void 0&&w(F,D)},S=P=>{if(P.source!=="codex")return;let D=P.notification.method;if(D!=="item/started"&&D!=="item/completed"&&D!=="response_item")return;let F=P.notification.params??{},E=xf(F)??Yy(n);if(E===void 0||!n.turns.has(E)&&!n.bufferedTurns.has(E))return;let N=Ec(F);if(N===void 0||N==="")return;if(D!=="item/started"){d.get(E)?.delete(N);return}let V=h($(F.item)?.type);if(V===void 0||!nme.has(V))return;let G=d.get(E);G===void 0&&(G=new Map,d.set(E,G)),G.set(N,{kind:V,startedAtMs:o()})},R=()=>{if(!f||n.phase!=="running")return!1;let P=o(),D=!1;for(let[F,E]of n.bufferedTurns){if(u.has(F))continue;let N=P-(s.get(F)??P),V=N>c,G=E.length>l;!V&&!G||(u.add(F),_("pipeline.loop.buffered_turn_overdue",{level:"warn",thread_key:e.threadKey,turn_id:F,buffered_event_count:E.length,age_ms:N,max_age_ms:c,max_events:l}),r.push({source:"codex",notification:{method:Oc,params:{turnId:F,reason:G?`turn source mapping never arrived (${E.length} buffered events exceeded the ${l} cap)`:`turn source mapping never arrived within ${c}ms`}}}),D=!0)}return D},T=()=>{if(!m){m=!0;try{for(;r.length>0;){let P=r.shift();if(P===void 0)continue;let D;try{D=Bq(n,P,t)}catch(F){_("pipeline.loop.event_processing_failed",{thread_key:e.threadKey,source:P.source,message:F instanceof Error?F.message:String(F)});continue}v(),k(P),S(P);for(let F of D)try{b(F)}catch(E){_("pipeline.loop.effect_failed",{thread_key:e.threadKey,effect:F.type,message:E instanceof Error?E.message:String(E)})}R()}}finally{m=!1}}},M=p>0?setInterval(()=>{R()&&T()},p):void 0;return M?.unref?.(),{submit:P=>{try{if(!f){_("pipeline.loop.event_after_drain",{thread_key:e.threadKey,source:P.source});return}r.push(P),T()}catch(D){_("pipeline.loop.submit_failed",{thread_key:e.threadKey,message:D instanceof Error?D.message:String(D)})}},metrics:()=>({queueDepth:r.length,phase:n.phase,activeTurns:[...n.turns.values()].map(P=>({turnId:P.turnId,sourceSeq:P.sourceSeq,startedAtMs:i.get(P.turnId)??o(),lastActivityAtMs:a.get(P.turnId)?.atMs,lastActivityKind:a.get(P.turnId)?.kind,openItems:Xq(d.get(P.turnId))})),bufferedTurns:[...n.bufferedTurns.entries()].map(([P,D])=>({turnId:P,bufferedEventCount:D.length,firstBufferedAtMs:s.get(P)??o(),lastActivityAtMs:a.get(P)?.atMs,lastActivityKind:a.get(P)?.kind,openItems:Xq(d.get(P))}))}),noteTurnActivity:(P,D)=>{try{w(P,D)}catch(F){_("pipeline.loop.note_activity_failed",{thread_key:e.threadKey,message:F instanceof Error?F.message:String(F)})}},drainAndClose:P=>(y===void 0&&(y=(async()=>{f=!1,M!==void 0&&clearInterval(M),await Promise.resolve(),T();try{await e.outbox.flush(P)}catch(D){_("pipeline.loop.drain_flush_failed",{thread_key:e.threadKey,message:D instanceof Error?D.message:String(D)})}})()),y)}}var Xfe,Yfe,eme,nme,eN=q(()=>{"use strict";Wn();dC();n_();Xfe=10*6e4,Yfe=1e4,eme=3e4,nme=new Set(["commandExecution","terminalInput","mcpToolCall","dynamicToolCall","collabAgentToolCall","contextCompaction"])});function r_(e){let n=ame(e),t=gq({threadKey:e.threadKey,push:e.push,builders:n,...e.persistDir===void 0?{}:{persistDir:e.persistDir},...e.outboxRetryDelaysMs===void 0?{}:{retryDelaysMs:[...e.outboxRetryDelaysMs]},maxInFlightPushes:e.outboxMaxInFlightPushes??rme,...e.journalRecoveryMaxAgeMs===void 0?{}:{journalRecoveryMaxAgeMs:e.journalRecoveryMaxAgeMs},isRetryBudgetExempt:yC,onPermanentFailure:(u,c)=>{e.log("pipeline.outbox_entry_failed",{thread_key:e.threadKey,entry_seq:u.entrySeq,kind:u.kind,attempts:u.attempts,item_key:h(u.data.item_key)??null,turn_id:h(u.data.turn_id)??null,message:c.message})},log:e.log}),r,o=u=>{let c=u.data;if(u.kind===Tt.messageState){let l=h(c.turn_id);l!==void 0&&e.isRecoveredTurn?.(l)===!0&&(c={...c,suppress_terminal_for_recovered_turn:!0});let p=h(c.status);if(p==="failed"||p==="recovering"){let m=e.runtimeMetadataForSourceSeq?.(Q(c.seq)),f=h(m?.model),y=h(m?.model_provider);c={...c,...h(c.model)===void 0&&f!==void 0?{model:f}:{},...h(c.provider)===void 0&&y!==void 0?{provider:y}:{}}}}if(sme(u.kind)){let l=Q(c.source_seq),p=$(c.local_runner_runtime_metadata)??e.runtimeMetadataForSourceSeq?.(l);p!==void 0&&(c={...c,local_runner_runtime_metadata:p})}return c!==u.data?t.enqueue({...u,data:c}):t.enqueue(u)},i={...t,enqueue:u=>{let c=e.wire().kandanThreadId,l=c===void 0?void 0:Xk(c);if(l===void 0)return o(u);let p=nq(l,u.kind,u.data,Date.now(),Tt),m=()=>{for(let y of p)t.enqueue({kind:Qk,data:eq(y),resolution:"must_ack"})};if(u.kind===Tt.messageState){m();let y=o(u);return l.done&&c!==void 0&&oq(c,l),y}let f=o(u);return m(),f}},s=async u=>{let c=e.snapshotRetryDelaysMs??tme;for(let l=0;;l+=1)try{let p=await e.resolveSnapshot(u);r.submit({source:"snapshot",turnId:u,snapshot:{items:[...p.items]}});return}catch(p){let m=p instanceof Error?p.message:String(p),f=c[l];if(e.log("pipeline.snapshot_resolution_failed",{thread_key:e.threadKey,turn_id:u,attempt:l+1,retry_in_ms:f??null,message:m}),f===void 0){r.submit({source:"codex",notification:{method:"turn/failed",params:{turnId:u,reason:`completion snapshot resolution failed: ${m}`}}});return}await pme(f)}};r=Yq({threadKey:e.threadKey,outbox:i,sourceSeqForTurn:e.sourceSeqForTurn,autoRetryAttemptsForSeq:e.autoRetryAttemptsForSeq,midStreamResumeAttemptAtMsForSeq:e.midStreamResumeAttemptAtMsForSeq,freshSessionResumeAttemptAtMsForSeq:e.freshSessionResumeAttemptAtMsForSeq,routeOutageActive:e.routeOutageActive,ladderHistoryForSeq:e.ladderHistoryForSeq,sessionExecutesRecoveryGrants:e.sessionExecutesRecoveryGrants,onTurnTerminal:e.onTurnTerminal,requestSnapshot:u=>{s(u).catch(c=>{e.log("pipeline.snapshot_request_failed",{thread_key:e.threadKey,turn_id:u,message:c instanceof Error?c.message:String(c)})})},instanceId:e.instanceId,log:e.log,linzumiAgentSession:e.linzumiAgentSession===!0});let a=yq({threadKey:e.threadKey,outboxMetrics:()=>t.metrics(),loopMetrics:()=>r.metrics(),log:e.log,intervalMs:e.statsIntervalMs,turnStalledThresholdMs:e.turnStalledThresholdMs,turnWaitStates:e.turnWaitStates}),d;return{submitNotification:(u,c)=>{r.submit({source:"codex",notification:{method:u,params:c}})},notifyTurnMappingReady:u=>{r.submit({source:"codex",notification:{method:Sf,params:{turnId:u}}})},notifyTurnMappingFailed:(u,c)=>{r.submit({source:"codex",notification:{method:Oc,params:{turnId:u,reason:c}}})},noteTurnActivity:(u,c)=>{r.noteTurnActivity(u,c)},submitLifecycle:(u,c)=>{r.submit({source:"lifecycle",kind:u,reason:c})},pause:()=>{t.pause()},resume:()=>{t.resume()},rebindThreadKey:u=>{t.rekeyJournal(u)},flushOutbox:u=>t.flush(u),metrics:()=>t.metrics(),close:u=>(d===void 0&&(d=(async()=>{a.stop(),r.submit({source:"lifecycle",kind:"shutdown",reason:"session closed"}),await r.drainAndClose(u),await t.close(u)})()),d)}}function nN(e){let n=cy(e);return n===void 0?{}:{traceparent:n}}function ome(e){return{...h(e.turn_id)===void 0?{}:{turn_id:h(e.turn_id)},...h(e.item_key)===void 0?{}:{item_key:h(e.item_key)},...Q(e.delta_index)===void 0?{}:{delta_index:Q(e.delta_index)},...Q(e.stream_snapshot_index)===void 0?{}:{stream_snapshot_index:Q(e.stream_snapshot_index)}}}function ime(e){return typeof e.body=="string"?e.body:""}function tN(e){return $(e.structured)??{}}function sme(e){return e===Tt.postStreamedRow||e===Tt.streamSnapshot||e===Tt.finalizeRow||e===Tt.postCompletedRow}function ame(e){let n={build:o=>{let i=e.wire();if(i.kandanThreadId===void 0||i.codexThreadId===void 0)return{skip:!0,reason:"session_thread_unbound"};let s=h(o.client_message_id);if(s===void 0)return{skip:!0,reason:"missing_client_message_id"};let a=h(o.turn_id),d=Q(o.source_seq),u={...a===void 0?{}:{turn_id:a},stream_key:s},c=$(o.local_runner_runtime_metadata),l={...u,...c??{}},p=e.sandboxNetworkDenialSurfacing===!0?pj(tN(o),c):tN(o);return{event:"session:stream_thread_message",payload:{workspace:i.workspaceSlug,channel:i.channelSlug,thread_id:i.kandanThreadId,stream_key:s,...i.leaseEpoch===void 0?{}:{lease_epoch:i.leaseEpoch},body:ime(o),payload:{...e.runnerPayload("codex_output",i.codexThreadId,d,l),...i.rootSeq===void 0?{}:{reply_to_seq:i.rootSeq},...d===void 0?{}:{source_message_seq:d},...u,structured:{...p,stream_key:s}},client_message_id:s,...ome(o),...nN(i.kandanThreadId)}}}},t={build:o=>{let i=e.wire();if(i.kandanThreadId===void 0)return{skip:!0,reason:"session_thread_unbound"};let s=Q(o.seq),a=h(o.status);if(s===void 0||a===void 0)return{skip:!0,reason:"malformed_message_state_entry"};let d=h(o.turn_id);return o.suppress_terminal_for_recovered_turn===!0||d!==void 0&&e.isRecoveredTurn?.(d)===!0?{skip:!0,reason:"terminal_for_recovered_turn"}:{event:"message_state",payload:{workspace:i.workspaceSlug,channel:i.channelSlug,thread_id:i.kandanThreadId,instance_id:e.instanceId,...i.codexThreadId===void 0?{}:{codex_thread_id:i.codexThreadId},seq:s,status:a,...h(o.reason)===void 0?{}:{reason:h(o.reason)},...o.retryable===!0?{retryable:!0}:{},...Do(o.fate)?{fate:o.fate}:{},...$(o.ladder)===void 0?{}:{ladder:$(o.ladder)},...o.failure_class==="edge_blocked"||o.failure_class==="claude_oauth_expired"?{failure_class:o.failure_class}:{},...h(o.upstream_error)===void 0?{}:{upstream_error:h(o.upstream_error)},...h(o.model)===void 0?{}:{model:h(o.model)},...h(o.provider)===void 0?{}:{provider:h(o.provider)},...h(o.turn_id)===void 0?{}:{turn_id:h(o.turn_id)},...i.leaseEpoch===void 0?{}:{lease_epoch:i.leaseEpoch},...nN(i.kandanThreadId)}}}},r={build:o=>{let i=Q(o.session_id);return i!==void 0&&Yk(i)?{skip:!0,reason:"adt_generation_fenced"}:{event:Vj,payload:{session_id:o.session_id??null,lease_epoch:o.lease_epoch??null,frame_index:o.frame_index??null,frame_kind:o.frame_kind??null,body:o.body??null,byte_len:o.byte_len??null}}},onReply:(o,i)=>{let s=$($(i)?.adt);if(s===void 0)return;let a=Q(o.session_id);if(s.accepted===!1){let d=Zj(s.reason);if(e.log?.("adt.append_rejected",{session_id:a??null,presented_epoch:Q(o.lease_epoch)??null,frame_index:Q(o.frame_index)??null,reason:d}),a!==void 0){iq(a);let u=e.wire().kandanThreadId,c=u===void 0?void 0:Xk(u);c!==void 0&&c.binding.sessionId===a&&Xj(c.emitter),e.log?.("adt.generation_fenced",{session_id:a,reason:d})}return}s.duplicate===!0&&e.log?.("adt.frame_resend_accepted",{session_id:a??null,frame_index:Q(o.frame_index)??null})}};return{[Tt.postStreamedRow]:n,[Tt.streamSnapshot]:n,[Tt.finalizeRow]:n,[Tt.postCompletedRow]:n,[Tt.messageState]:t,[Qk]:r}}function iN(e,n){if("error"in e)return[];let t=$($(e.result)?.thread),o=(Fe(t?.turns)??[]).filter(ne).find(i=>i.id===n);return(Fe(o?.items)??[]).filter(ne)}function gC(e){if(!e.some(t=>dme.has(h(t.type)??"")))return[...e];let n=new Set;return e.forEach(t=>{let r=t_.get(h(t.type)??"");if(r===void 0)return;let o=h(t.call_id);if(o===void 0)return;let i=e.findIndex((s,a)=>!n.has(a)&&h(s.type)===r&&h(s.call_id)===o);i>=0&&n.add(i)}),e.flatMap((t,r)=>{let o=h(t.type)??"",i=t_.get(o);if(i!==void 0){let s=h(t.call_id),a=s===void 0?void 0:e.find(d=>h(d.type)===i&&h(d.call_id)===s);return $k(a===void 0?[t]:[t,a]).flatMap(d=>{let u=rN(d);return u===void 0?[]:[u]})}return o==="function_call_output"||o==="custom_tool_call_output"?n.has(r)?[]:$k([t]).flatMap(s=>{let a=rN(s);return a===void 0?[]:[a]}):[t]})}function rN(e){let n=e.structured,t=/^item-\d+$/.test(e.itemKey)?void 0:e.itemKey,r=t===void 0?{}:{id:t},o=typeof n.output=="string"?n.output:"";switch(h(n.kind)){case"codex_command_execution":{let i=ume(o);return{type:"commandExecution",...r,...i===void 0?{}:{codex_protocol_failure_reason:i},command:h(n.command)??"command",...h(n.tool_name)===void 0?{}:{toolName:h(n.tool_name)},cwd:h(n.cwd)??"",status:h(n.status)??"",...h(n.process_id)===void 0||h(n.process_id)===""?{}:{processId:h(n.process_id)},aggregatedOutput:o}}case"codex_file_change":return{type:"fileChange",...r,status:h(n.status)??"",patchText:h(n.patch_text)??e.body,changes:Fe(n.changes)??[]};default:return}}function ume(e){let n="unsupported call:",t=e.trim();if(!t.toLowerCase().startsWith(n))return;let r=t.slice(n.length).trim();return`Codex emitted unsupported tool call: ${r===""?"unknown":r}`}function sN(e,n){if(n.length===0)return[...e];let t=oN(e),r=oN(n),o=new Set,i=r.map(d=>{let u=d.exactKey===void 0?-1:t.findIndex((l,p)=>!o.has(p)&&l.exactKey===d.exactKey);if(u>=0)return o.add(u),{kind:"read",readIndex:u};let c=d.semanticKey===void 0?-1:t.findIndex((l,p)=>!o.has(p)&&l.semanticKey===d.semanticKey);return c>=0?(o.add(c),{kind:"read",readIndex:c}):{kind:"session",raw:d.raw}}),s=[],a=0;for(let d of i)switch(d.kind){case"read":{for(;a<d.readIndex;){if(!o.has(a)){let c=t[a];c!==void 0&&s.push(c.raw)}a+=1}let u=t[d.readIndex];u!==void 0&&s.push(u.raw),a=Math.max(a,d.readIndex+1);break}case"session":s.push(d.raw);break}for(;a<t.length;){if(!o.has(a)){let d=t[a];d!==void 0&&s.push(d.raw)}a+=1}return s}function oN(e){return e.map((n,t)=>{let r=Cc(n,t).find(o=>o.body.trim()!=="");return r===void 0?{raw:n,exactKey:void 0,semanticKey:void 0}:{raw:n,exactKey:cme(r),semanticKey:lme(r)}})}function cme(e){return`${h(e.structured.kind)??""}:${e.itemKey}`}function lme(e){let n=h(e.structured.kind)??"";switch(n){case"codex_command_execution":return JSON.stringify([n,h(e.structured.command)??"",h(e.structured.cwd)??"",h(e.structured.output)??e.body]);case"codex_file_change":return JSON.stringify([n,h(e.structured.patch_text)??e.body]);case"codex_reasoning":return JSON.stringify([n,h(e.structured.content)??e.body]);case"codex_terminal_input":return JSON.stringify([n,h(e.structured.input_text)??e.body]);default:return JSON.stringify([n,e.body])}}function o_(e){return qj(e)}function yC(e){return Nj(e)}function pme(e){return new Promise(n=>{setTimeout(n,e)})}var tme,rme,t_,dme,_C=q(()=>{"use strict";xs();Wn();Pc();rk();Jy();jn();Ky();oC();_q();eN();n_();tme=[1e3,5e3],rme=16;t_=new Map([["function_call","function_call_output"],["custom_tool_call","custom_tool_call_output"]]),dme=new Set([...t_.keys(),...t_.values()])});import{execFile as fme}from"node:child_process";import{copyFileSync as cN,existsSync as xC,mkdirSync as Tf,readFileSync as lN,readdirSync as Pf,rmSync as aN,statSync as pN,writeFileSync as fN}from"node:fs";import{homedir as mme}from"node:os";import{dirname as bC,join as Ao,resolve as wC}from"node:path";import{promisify as hme}from"node:util";function bme(e=process.env){let n=e[gme];if(n===void 0)return!0;let t=n.trim().toLowerCase();return!(t==="0"||t==="false"||t==="off")}function If(e=process.env){let n=e.LINZUMI_GIT_SAFETY_SNAPSHOTS_DIR;return n!==void 0&&n.trim()!==""?wC(n):wC(mme(),".linzumi","safety-snapshots")}async function Sd(e,n){try{let{stdout:t,stderr:r}=await mN("git",[...n],{cwd:e,encoding:"utf8",timeout:hN,maxBuffer:67108864});return{ok:!0,stdout:t,stderr:r}}catch(t){let r=t;return{ok:!1,stdout:typeof r.stdout=="string"?r.stdout:"",stderr:typeof r.stderr=="string"?r.stderr:t instanceof Error?t.message:String(t)}}}function wme(e){let n=e.split("\0"),t=[];for(let r=0;r<n.length;r+=1){let o=n[r];if(o===void 0||o.length<4)continue;let i=o.slice(0,2),s=o.slice(3);t.push({status:i,path:s}),(i.includes("R")||i.includes("C"))&&(r+=1)}return t}function i_(e){let n=e.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"");return n===""?"x":n}function vme(e){let n=new Date(e.nowMs).toISOString().replace(/-|:|\..*$/g,"").replace("T","-"),t=i_(e.threadId).slice(-12),r=i_(e.turnRef).slice(-12);return`${n}-${t}-${r}`}function Sme(e){return`refs/linzumi/safety/${e}`}async function kme(e){let n=e.env??process.env;if(!bme(n))return{kind:"disabled"};let t=Date.now(),r=()=>Date.now()-t,o=await Sd(e.cwd,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!o.ok)return o.stderr.toLowerCase().includes("not a git repository")?{kind:"not_git",durationMs:r()}:{kind:"error",message:`git status failed: ${o.stderr.trim()}`,durationMs:r()};let i=wme(o.stdout);if(i.length===0)return{kind:"clean",durationMs:r()};try{let s=e.nowMs??t,a=vme({threadId:e.threadId,turnRef:e.turnRef,nowMs:s}),d=e.snapshotsRoot??If(n),u=Ao(d,i_(e.threadId),`${i_(e.turnRef)}-${s}`),c=e.maxTotalBytes??yme,l=i.filter(F=>F.status==="??").map(F=>F.path),p=i.filter(F=>F.status!=="??"&&F.status!=="!!").map(F=>F.path),m=await Sd(e.cwd,["rev-parse","--show-toplevel"]),f=m.ok?m.stdout.trim():e.cwd,y=await Sd(e.cwd,["branch","--show-current"]),_=y.ok&&y.stdout.trim()!==""?y.stdout.trim():void 0,b=await Sd(e.cwd,["rev-parse","HEAD"]),v=b.ok?b.stdout.trim():void 0,w,k;if(p.length>0){let F=await Sd(e.cwd,["stash","create",`linzumi safety snapshot ${a}`]),E=F.ok?F.stdout.trim():"";if(E!==""){w=E;let N=Sme(a);k=(await Sd(e.cwd,["update-ref",N,E])).ok?N:void 0}}Tf(u,{recursive:!0});let S=[],R=0,T=(F,E)=>{let N=Ao(f,F),V=0;try{let G=pN(N);if(!G.isFile())return!1;if(V=G.size,R+V>c)return S.push({path:F,bytes:V,reason:"size_cap"}),!1;let Z=Ao(u,E,F);return Tf(bC(Z),{recursive:!0}),cN(N,Z),R+=V,!0}catch{return S.push({path:F,bytes:V,reason:"copy_error"}),!1}},M=l.filter(F=>T(F,"untracked")),P=w===void 0&&p.length>0?p.filter(F=>T(F,"tracked")):[],D={version:1,id:a,createdAtMs:s,threadId:e.threadId,turnRef:e.turnRef,cwd:e.cwd,repoRoot:f,branch:_,headCommit:v,stashCommit:w,safetyRef:k,trackedPaths:p,untrackedPaths:M,trackedFallbackPaths:P,skippedFiles:S,copiedBytes:R,durationMs:r()};return fN(Ao(u,"manifest.json"),`${JSON.stringify(D,null,2)}
579
579
  `),{kind:"snapshot",manifest:D,snapshotDir:u}}catch(s){return{kind:"error",message:s instanceof Error?s.message:String(s),durationMs:r()}}}function s_(e){let n=[],t;try{t=Pf(e)}catch{return[]}for(let r of t){let o=Ao(e,r),i;try{i=Pf(o)}catch{continue}for(let s of i){let a=Ao(o,s);try{let d=JSON.parse(lN(Ao(a,"manifest.json"),"utf8"));d.version===1&&typeof d.id=="string"&&n.push({manifest:d,snapshotDir:a})}catch{}}}return n.sort((r,o)=>o.manifest.createdAtMs-r.manifest.createdAtMs)}async function gN(e){let{manifest:n,snapshotDir:t}=e.snapshot,r=wC(e.toDir);if(xC(r)&&Pf(r).length>0)throw new Error(`refusing to restore into non-empty directory: ${r} (recovery never clobbers existing state)`);Tf(r,{recursive:!0});let o=[];for(let a of n.untrackedPaths){let d=Ao(t,"untracked",a);if(!xC(d))continue;let u=Ao(r,a);Tf(bC(u),{recursive:!0}),cN(d,u),o.push(a)}let i=[],s=[];for(let a of n.trackedPaths){let d;if(n.stashCommit!==void 0)try{let{stdout:c}=await mN("git",["show",`${n.stashCommit}:${a}`],{cwd:n.repoRoot,encoding:"buffer",timeout:hN,maxBuffer:536870912});d=c}catch{d=void 0}if(d===void 0){let c=Ao(t,"tracked",a);xC(c)&&(d=lN(c))}if(d===void 0){s.push(a);continue}let u=Ao(r,a);Tf(bC(u),{recursive:!0}),fN(u,d),i.push(a)}return{restoredDir:r,restoredTracked:i,restoredUntracked:o,missingTracked:s,stashCommit:n.stashCommit,safetyRef:n.safetyRef}}async function yN(e){let n=e.nowMs??Date.now(),t=e.maxAgeMs??_me,r=e.maxCount??xme,o=s_(e.snapshotsRoot),i=o.filter(l=>n-l.manifest.createdAtMs>t),a=o.filter(l=>n-l.manifest.createdAtMs<=t).slice(r),d=[...i,...a],u=[],c=[];for(let l of d){let{manifest:p,snapshotDir:m}=l;p.safetyRef!==void 0&&p.stashCommit!==void 0&&(await Sd(p.repoRoot,["update-ref","-d",p.safetyRef,p.stashCommit])).ok&&c.push(p.safetyRef);try{aN(m,{recursive:!0,force:!0}),u.push(m)}catch{}}try{for(let l of Pf(e.snapshotsRoot)){let p=Ao(e.snapshotsRoot,l);try{pN(p).isDirectory()&&Pf(p).length===0&&aN(p,{recursive:!0,force:!0})}catch{}}}catch{}return{removedSnapshotDirs:u,removedRefs:c}}function Tme(e){return Cme.some(n=>n.test(e))}function _N(e){let n=[],t=[],r="",o,i=()=>{r!==""&&(t.push(r),r="")},s=()=>{i(),t.length>0&&(n.push(t),t=[])};for(let a=0;a<e.length;a+=1){let d=e[a];if(o!==void 0){d===o?o=void 0:r+=d;continue}if(d==="'"||d==='"'){o=d;continue}if(d==="\\"){a+=1;let u=e[a];u!==void 0&&(r+=u);continue}if(d===";"||d===`
580
580
  `){s();continue}if(d==="&"||d==="|"){s(),e[a+1]===d&&(a+=1);continue}if(/\s/.test(d)){i();continue}r+=d}return s(),n}function dN(e){let n=e.lastIndexOf("/");return n===-1?e:e.slice(n+1)}function Rme(e){let n=1,t;for(;n<e.length;){let y=e[n];if(!y.startsWith("-"))break;if(y==="-C"){t=e[n+1],n+=2;continue}n+=y==="-c"?2:1}let r=e[n];if(r===void 0)return;let o=e.slice(n+1),i={restore:["--source","-s"],commit:["-m","--message","-F","--file","-C","-c","--reuse-message","--reedit-message","--fixup","--squash","-t","--template","--author","--date"],clean:["-e","--exclude"]},s=new Set(i[r]??[]),a=[],d=[],u=[],c=!1,l=!1;for(let y=0;y<o.length;y+=1){let _=o[y];if(!c&&_==="--"){c=!0;continue}if(!c&&_.startsWith("-")){a.push(_),(s.has(_)||r==="commit"&&/^-[A-Za-z]+$/.test(_)&&_.endsWith("m"))&&(y+=1);continue}if(_==="."||_==="./"||_===":/"){l=!0,(c?u:d).push(_);continue}(c?u:d).push(_)}let p=(c?u:d).filter(y=>y!=="."&&y!=="./"&&y!==":/"),f=Eme({subcommand:r,rest:o,flags:a,afterDashDash:u,sawDashDash:c,treeWide:l,pathTokens:p,hasShortFlagLetter:y=>a.some(_=>/^-[A-Za-z]+$/.test(_)&&_.slice(1).includes(y))});return f===void 0||t===void 0?f:{...f,workdir:t}}function Eme(e){let{subcommand:n,rest:t,flags:r,afterDashDash:o,sawDashDash:i,treeWide:s,pathTokens:a,hasShortFlagLetter:d}=e;switch(n){case"restore":{let u=r.includes("--staged")||d("S"),c=r.includes("--worktree")||d("W");return u&&!c?void 0:s?{operation:"restored",paths:[],scope:"tracked"}:a.length===0?void 0:{operation:"restored",paths:a,scope:"named"}}case"checkout":{if(r.includes("-b")||r.includes("-B")||r.includes("--orphan"))return;if(i){if(o.some(c=>c==="."||c==="./"))return{operation:"restored",paths:[],scope:"tracked"};let u=o.filter(c=>c!=="."&&c!=="./");return u.length===0?void 0:{operation:"restored",paths:u,scope:"named"}}return s?{operation:"restored",paths:[],scope:"tracked"}:r.includes("-f")||r.includes("--force")?{operation:"restored",paths:[],scope:"tracked"}:void 0}case"reset":return r.includes("--hard")||r.includes("--merge")||r.includes("--keep")?{operation:"reset",paths:[],scope:"tracked"}:void 0;case"clean":return r.includes("--dry-run")||d("n")||!r.includes("--force")&&!d("f")?void 0:a.length===0?{operation:"deleted",paths:[],scope:"untracked"}:{operation:"deleted",paths:a,scope:"named"};case"stash":{let u=t[0];return u==="drop"||u==="clear"||u==="pop"?{operation:"reset",paths:[],scope:"none"}:void 0}case"commit":return r.includes("--all")||d("a")?{operation:"committed",paths:[],scope:"tracked"}:a.length===0?void 0:{operation:"committed",paths:a,scope:"named"};default:return}}function Dme(e){let n=[],t=!1;for(let r of e.slice(1)){if(!t&&r==="--"){t=!0;continue}if(!t&&r.startsWith("-")){if(r==="--help"||r==="--version")return;continue}n.push(r)}return n.length===0?void 0:{operation:"deleted",paths:n,scope:"named"}}function xN(e,n,t,r){let o=0;for(;o<e.length;){let d=e[o];if(/^[A-Za-z_][A-Za-z0-9_]*=/.test(d)){o+=1;continue}if(Ime.has(dN(d))){o+=1;continue}break}let i=e[o];if(i===void 0)return;let s=dN(i);if(s==="cd"||s==="pushd"){r.dir=e[o+1];return}if(Pme.has(s)&&t<3&&e.slice(o+1).some(u=>/^-[A-Za-z]*c/.test(u))){let u=e.slice(o+1).find(c=>!c.startsWith("-"));if(u!==void 0){let c={dir:r.dir};for(let l of _N(u))xN(l,n,t+1,c)}return}let a=d=>d===void 0||d.workdir!==void 0||r.dir===void 0?d:{...d,workdir:r.dir};if(s==="git"){let d=a(Rme(e.slice(o)));d!==void 0&&n.push(d);return}if(s==="rm"){let d=a(Dme(e.slice(o)));d!==void 0&&n.push(d)}}function Mme(e){let n=[],t={dir:void 0};for(let r of _N(e))xN(r,n,0,t);return n}function Ame(e,n){let t=e;for(n!==void 0&&t.startsWith(`${n}/`)&&(t=t.slice(n.length+1));t.startsWith("./");)t=t.slice(2);if(t=t.replace(/\/+$/,""),!(t===""||t==="."||t.startsWith("-")))return t}function uN(e,n){return e===n||n.startsWith(`${e}/`)?!0:e.includes("/")&&n.endsWith(`/${e}`)}function Ome(e){let n=new Map,t=(i,s,a)=>{n.delete(i),n.set(i,{path:i,operation:s,wasUntracked:a})},r=e.repoRoot?.replace(/\/+$/,""),o=i=>i.workdir!==void 0&&i.workdir.startsWith("/")&&r!==void 0&&r!==""&&i.workdir!==r&&!i.workdir.startsWith(`${r}/`);for(let i of e.invocations)if(!o(i))switch(i.scope){case"none":break;case"tracked":for(let s of e.trackedPaths)t(s,i.operation,!1);break;case"untracked":for(let s of e.untrackedPaths)t(s,i.operation,!0);break;case"named":{for(let s of i.paths){let a=Ame(s,e.repoRoot);if(a!==void 0){for(let d of e.trackedPaths)uN(a,d)&&t(d,i.operation,!1);if(i.operation==="deleted")for(let d of e.untrackedPaths)uN(a,d)&&t(d,i.operation,!0)}}break}}return[...n.values()]}function Fme(e,n){if(Mo.delete(e),Mo.size>=Lme){let t=Mo.keys().next().value;t!==void 0&&Mo.delete(t)}Mo.set(e,n)}async function Rf(e){try{let n=await kme({cwd:e.cwd,threadId:e.threadKey,turnRef:e.turnRef,snapshotsRoot:e.snapshotsRoot,env:e.env});switch(n.kind){case"snapshot":{Fme(e.threadKey,{manifest:n.manifest,destructiveCommand:void 0,workingTreeChanges:new Map,droppedWorkingTreeChangeCount:0}),e.log("git_safety.snapshot_captured",{thread_key:e.threadKey,turn_ref:e.turnRef,snapshot_id:n.manifest.id,stash_commit:n.manifest.stashCommit??null,safety_ref:n.manifest.safetyRef??null,tracked_paths:n.manifest.trackedPaths.length,untracked_paths:n.manifest.untrackedPaths.length,copied_bytes:n.manifest.copiedBytes,skipped_files:n.manifest.skippedFiles.length,duration_ms:n.manifest.durationMs});for(let t of n.manifest.skippedFiles)e.log("git_safety.snapshot_file_skipped",{thread_key:e.threadKey,snapshot_id:n.manifest.id,path:t.path,bytes:t.bytes,reason:t.reason});break}case"error":Mo.delete(e.threadKey),e.log("git_safety.snapshot_failed",{thread_key:e.threadKey,turn_ref:e.turnRef,cwd:e.cwd,message:n.message,duration_ms:n.durationMs});break;case"clean":case"not_git":case"disabled":Mo.delete(e.threadKey);break}return n}catch(n){e.log("git_safety.snapshot_failed",{thread_key:e.threadKey,turn_ref:e.turnRef,cwd:e.cwd,message:n instanceof Error?n.message:String(n)});return}}function a_(e,n){let t=Mo.get(e);if(t!==void 0){t.destructiveCommand===void 0&&Tme(n)&&(t.destructiveCommand=n);try{let r=Mme(n);if(r.length===0)return;let o=Ome({invocations:r,trackedPaths:t.manifest.trackedPaths,untrackedPaths:t.manifest.untrackedPaths,repoRoot:t.manifest.repoRoot});for(let i of o)t.workingTreeChanges.has(i.path)||t.workingTreeChanges.size<$me?t.workingTreeChanges.set(i.path,i):t.droppedWorkingTreeChangeCount+=1}catch{}}}function zme(e){switch(e.operation){case"deleted":return e.wasUntracked?"was untracked - no git recovery of its own":"had your uncommitted changes";case"committed":return"included your uncommitted changes";case"restored":case"reset":return"discarded your uncommitted changes"}}function Ume(e,n,t){let r=n.slice(0,Nme),o=n.length-r.length+Math.max(0,t),i=r.map(a=>`- ${a.operation} \`${a.path}\` (${zme(a)})`);o>0&&i.push(`- ...and ${o} more`);let s=e.stashCommit===void 0?"":` Tracked changes are also directly recoverable with \`git stash apply ${e.stashCommit}\`.`;return`Changed your working tree:
581
581
  ${i.join(`
@@ -1510,7 +1510,7 @@ To kick the agent off:
1510
1510
  `,M=Buffer.byteLength(T,"utf8");if(M>s)return l("runner_diagnostics.spool_entry_dropped",{reason:"entry_too_large",entry_bytes:M,max_entry_bytes:s}),!1;gEe(n,{recursive:!0}),m(u)+M>i&&f(),_(M);let P=b()?`
1511
1511
  `:"";return fEe(u,`${P}${T}`,"utf8"),!0}catch(R){return l("runner_diagnostics.spool_failed",{error:R instanceof Error?R.message:String(R)}),!1}},w=S=>{let R=[],T=_Ee(S,"utf8");for(let M of T.split(`
1512
1512
  `))if(M.trim()!=="")try{let P=JSON.parse(M);P!==null&&typeof P=="object"&&R.push({parsed:P,raw:M})}catch{}return R};return{append:v,drain:async S=>{if(c)return{uploadedBatches:0,uploadedEntries:0,remainingBatches:p().length,skipped:!0};c=!0;let R=0,T=0;try{f(),_(0);let M=a()-o;for(let P of p()){let D;try{D=w(P)}catch(Z){l("runner_diagnostics.spool_batch_unreadable",{file:P,error:Z instanceof Error?Z.message:String(Z)}),y(P,"unreadable");continue}let F=D.filter(Z=>{let H=$Ee(Z.parsed);return H===void 0||H>=M});if(F.length===0){y(P,"empty_or_expired");continue}let E=gR(P,".jsonl"),N=F.map(Z=>Z.raw).join(`
1513
- `),V=F.map(Z=>Z.parsed.spooled_at).filter(Z=>typeof Z=="string"),G={bundle_name:"runner-diagnostics-spool",exported_at:new Date(a()).toISOString(),idempotency_key:E,diagnostics:{kind:"runner_diagnostic_log",spool_batch:!0,idempotency_key:E,entry_count:F.length,...V.length===0?{}:{first_spooled_at:V[0],last_spooled_at:V[V.length-1]}},telemetry_ndjson:N};try{await S(G)}catch(Z){l("runner_diagnostics.spool_upload_failed",{file:P,remaining_batches:p().length,error:Z instanceof Error?Z.message:String(Z)});break}R+=1,T+=F.length;try{vJ(P)}catch(Z){l("runner_diagnostics.spool_delete_failed",{file:P,error:Z instanceof Error?Z.message:String(Z)})}}}catch(M){l("runner_diagnostics.spool_drain_failed",{error:M instanceof Error?M.message:String(M)})}finally{c=!1}return{uploadedBatches:R,uploadedEntries:T,remainingBatches:p().length,skipped:!1}},pendingBatchFiles:p}}var kEe,CEe,TEe,PEe,IEe,SJ,EEe,DEe,CJ=q(()=>{"use strict";Cx();kEe=32*1024*1024,CEe=10080*60*1e3,TEe=4*1024*1024,PEe=1024*1024,IEe="spool.jsonl",SJ=/^batch-(\d{1,16})-[0-9a-f-]+\.jsonl$/;EEe=/\b([A-Z][A-Z0-9_]{1,})=("[^"\n]*"|'[^'\n]*'|[^\s"'`;,)\]}]+)/g,DEe=/(?:\/(?:[A-Za-z0-9._@~+-]|%[0-9A-Fa-f]{2})+){2,}/g});var Vt,_R,wa=q(()=>{"use strict";Vt="1.0.177",_R=`linzumi ${Vt}`});import{closeSync as PJ,existsSync as bR,mkdirSync as LEe,openSync as IJ,readFileSync as RJ,renameSync as FEe,unlinkSync as Xd,writeFileSync as jEe,writeSync as EJ}from"node:fs";import{dirname as DJ,join as qEe}from"node:path";function wR(e){return e instanceof Ds||e instanceof Error&&e.name===AJ&&"lockPath"in e&&"heldBy"in e}function vR(e,n=et(),t){let r=t===void 0?encodeURIComponent(e):Jd(t);return qEe(DJ(n),"runners",`${r}.lock`)}function Nb(e){let n=vR(e.machineId,e.configPath,e.linzumiUrl),t=e.isPidAlive??NJ,r=e.now??(()=>new Date),o=e.killPid??XEe,i=r().toISOString(),s={version:1,machineId:e.machineId,runnerId:e.runnerId,pid:e.pid??process.pid,cwd:e.cwd,workspace:e.workspace,...e.linzumiUrl===void 0?{}:{linzumiUrl:zn(e.linzumiUrl)},...e.launchSource===void 0?{}:{launchSource:e.launchSource},startedAt:i,heartbeatAt:i,cliVersion:e.cliVersion??Vt,...e.gracefulUpdateDrain===!0?{gracefulUpdateDrain:!0}:{}};BEe(e.machineId,e.configPath,e.linzumiUrl,t,r,o,e.onTakeover),JEe(n,s,t,r,o,e.onTakeover,e.beforeReadExistingLock,e.beforeReplaceStaleLock);let a=()=>OJ(n,s,r),d=setInterval(a,MJ);return d.unref(),{path:n,record:s,heartbeat:a,release:()=>{clearInterval(d),jJ(n,s)}}}function OJ(e,n,t){try{let r=Ub(e);if(r===void 0||r.machineId!==n.machineId||r.runnerId!==n.runnerId||r.pid!==n.pid||r.startedAt!==n.startedAt)return;let o={...r,heartbeatAt:t().toISOString()},i=`${e}.tmp`;jEe(i,`${JSON.stringify(o,null,2)}
1513
+ `),V=F.map(Z=>Z.parsed.spooled_at).filter(Z=>typeof Z=="string"),G={bundle_name:"runner-diagnostics-spool",exported_at:new Date(a()).toISOString(),idempotency_key:E,diagnostics:{kind:"runner_diagnostic_log",spool_batch:!0,idempotency_key:E,entry_count:F.length,...V.length===0?{}:{first_spooled_at:V[0],last_spooled_at:V[V.length-1]}},telemetry_ndjson:N};try{await S(G)}catch(Z){l("runner_diagnostics.spool_upload_failed",{file:P,remaining_batches:p().length,error:Z instanceof Error?Z.message:String(Z)});break}R+=1,T+=F.length;try{vJ(P)}catch(Z){l("runner_diagnostics.spool_delete_failed",{file:P,error:Z instanceof Error?Z.message:String(Z)})}}}catch(M){l("runner_diagnostics.spool_drain_failed",{error:M instanceof Error?M.message:String(M)})}finally{c=!1}return{uploadedBatches:R,uploadedEntries:T,remainingBatches:p().length,skipped:!1}},pendingBatchFiles:p}}var kEe,CEe,TEe,PEe,IEe,SJ,EEe,DEe,CJ=q(()=>{"use strict";Cx();kEe=32*1024*1024,CEe=10080*60*1e3,TEe=4*1024*1024,PEe=1024*1024,IEe="spool.jsonl",SJ=/^batch-(\d{1,16})-[0-9a-f-]+\.jsonl$/;EEe=/\b([A-Z][A-Z0-9_]{1,})=("[^"\n]*"|'[^'\n]*'|[^\s"'`;,)\]}]+)/g,DEe=/(?:\/(?:[A-Za-z0-9._@~+-]|%[0-9A-Fa-f]{2})+){2,}/g});var Vt,_R,wa=q(()=>{"use strict";Vt="1.0.179",_R=`linzumi ${Vt}`});import{closeSync as PJ,existsSync as bR,mkdirSync as LEe,openSync as IJ,readFileSync as RJ,renameSync as FEe,unlinkSync as Xd,writeFileSync as jEe,writeSync as EJ}from"node:fs";import{dirname as DJ,join as qEe}from"node:path";function wR(e){return e instanceof Ds||e instanceof Error&&e.name===AJ&&"lockPath"in e&&"heldBy"in e}function vR(e,n=et(),t){let r=t===void 0?encodeURIComponent(e):Jd(t);return qEe(DJ(n),"runners",`${r}.lock`)}function Nb(e){let n=vR(e.machineId,e.configPath,e.linzumiUrl),t=e.isPidAlive??NJ,r=e.now??(()=>new Date),o=e.killPid??XEe,i=r().toISOString(),s={version:1,machineId:e.machineId,runnerId:e.runnerId,pid:e.pid??process.pid,cwd:e.cwd,workspace:e.workspace,...e.linzumiUrl===void 0?{}:{linzumiUrl:zn(e.linzumiUrl)},...e.launchSource===void 0?{}:{launchSource:e.launchSource},startedAt:i,heartbeatAt:i,cliVersion:e.cliVersion??Vt,...e.gracefulUpdateDrain===!0?{gracefulUpdateDrain:!0}:{}};BEe(e.machineId,e.configPath,e.linzumiUrl,t,r,o,e.onTakeover),JEe(n,s,t,r,o,e.onTakeover,e.beforeReadExistingLock,e.beforeReplaceStaleLock);let a=()=>OJ(n,s,r),d=setInterval(a,MJ);return d.unref(),{path:n,record:s,heartbeat:a,release:()=>{clearInterval(d),jJ(n,s)}}}function OJ(e,n,t){try{let r=Ub(e);if(r===void 0||r.machineId!==n.machineId||r.runnerId!==n.runnerId||r.pid!==n.pid||r.startedAt!==n.startedAt)return;let o={...r,heartbeatAt:t().toISOString()},i=`${e}.tmp`;jEe(i,`${JSON.stringify(o,null,2)}
1514
1514
  `,"utf8"),FEe(i,e)}catch{}}function Yd(e,n,t){if(!n(e.pid))return{state:"dead"};let r=e.heartbeatAt??e.startedAt,o=Date.parse(r);return Number.isNaN(o)||t().getTime()-o>NEe?{state:"wedged",reason:e.heartbeatAt===void 0?"missing_heartbeat":"stale_heartbeat"}:{state:"live"}}function $J(e,n,t,r){return t!==zb||e.launchSource!==zb?!1:r.state!=="live"?!0:zEe(n,e.cliVersion)>0}function zEe(e,n){let t=TJ(e),r=TJ(n);for(let o=0;o<3;o++){let i=t.core[o],s=r.core[o];if(i===void 0||s===void 0)throw new Error(`compareCliVersions: unexpected undefined at core index ${o}`);if(i!==s)return i>s?1:-1}return t.prerelease.length===0&&r.prerelease.length===0?0:t.prerelease.length===0?1:r.prerelease.length===0?-1:UEe(t.prerelease,r.prerelease)}function TJ(e){let n=e.trim().replace(/^v/i,"").split("+",1)[0]??"",t=n.indexOf("-"),r=t===-1?n:n.slice(0,t),o=t===-1?"":n.slice(t+1),i=r.split("."),s=[xR(i[0]),xR(i[1]),xR(i[2])],a=o===""?[]:o.split(".").filter(d=>d!=="");return{core:s,prerelease:a}}function xR(e){let n=Number.parseInt(e??"",10);return Number.isInteger(n)&&n>=0?n:0}function UEe(e,n){let t=Math.max(e.length,n.length);for(let r=0;r<t;r++){let o=e[r],i=n[r];if(o===void 0)return-1;if(i===void 0)return 1;let s=Number.parseInt(o,10),a=Number.parseInt(i,10),d=s.toString()===o,u=a.toString()===i;if(d&&u){if(s!==a)return s>a?1:-1}else{if(d!==u)return d?-1:1;if(o!==i)return o>i?1:-1}}return 0}function LJ(e,n,t,r,o){try{r(n.pid)}catch(i){let s=i!==null&&typeof i=="object"&&"code"in i?i.code:void 0;if(s!=="ESRCH")throw s==="EPERM"||s==="EACCES"?new Error(`Cannot take over the runner lock at ${e}: its holder process (pid ${n.pid}) is owned by another user and cannot be stopped. Stop that process, or remove the lock file, then retry.`):i}o?.({lockPath:e,holderPid:n.pid,holderRunnerId:n.runnerId,reason:t})}function BEe(e,n,t,r,o,i,s){if(t===void 0||kr(t)!==kr(Xt))return;let a=vR(e,n),d=Ub(a);if(d!==void 0){if(Yd(d,r,o).state==="live")throw new Ds(a,d);FJ(a,r,()=>{let u=bR(a)?SR(a):void 0;if(u===void 0)return;let c=Yd(u,r,o);if(c.state==="live")throw new Ds(a,u);c.state==="wedged"&&LJ(a,u,c.reason,i,s),Xd(a)})}}function JEe(e,n,t,r,o,i,s,a){if(qb(e,n))return;s?.();let d=Ub(e);if(d===void 0){if(qb(e,n))return;throw new Error(`another Linzumi runner lock appeared while starting: ${e}`)}if(Yd(d,t,r).state==="live")throw new Ds(e,d);a?.(),FJ(e,t,()=>{let u=bR(e)?SR(e):void 0;if(u!==void 0){let c=Yd(u,t,r);if(c.state==="live")throw new Ds(e,u);c.state==="wedged"&&LJ(e,u,c.reason,o,i),Xd(e)}if(!qb(e,n))throw new Error(`another Linzumi runner lock appeared while starting: ${e}`)})}function qb(e,n){LEe(DJ(e),{recursive:!0});try{let t=IJ(e,"wx");try{EJ(t,`${JSON.stringify(n,null,2)}
1515
1515
  `)}finally{PJ(t)}return!0}catch(t){if(Il(t,"EEXIST"))return!1;throw t}}function FJ(e,n,t){let r=`${e}.replace`;for(;;)try{let o=IJ(r,"wx");try{EJ(o,`${process.pid}
1516
1516
  `),t()}finally{PJ(o),Xd(r)}return}catch(o){if(Il(o,"EEXIST")){let i=KEe(r);if(i===void 0)continue;if(n(i))throw new Error(["another Linzumi runner is already replacing a stale runner lock",`lock: ${e}`,"Wait for that startup to finish, then retry."].join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@linzumi/cli",
3
- "version": "1.0.177",
3
+ "version": "1.0.179",
4
4
  "description": "Linzumi CLI \u2014 point a Codex agent at the real code on your laptop, with your team watching and steering from shared threads.",
5
5
  "type": "module",
6
6
  "bin": {