@linzumi/cli 1.0.267 → 1.0.268
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/impl-res/cloud-supervisor.mjs +2 -2
- package/dist/impl-res/index.js +260 -257
- package/dist/impl-res/mcp-server.mjs +1 -1
- package/dist/impl-ts/cloud-supervisor.mjs +2 -2
- package/dist/impl-ts/index.js +5 -5
- package/dist/impl-ts/mcp-server.mjs +1 -1
- package/dist/mcp-server.mjs +1 -1
- package/package.json +1 -1
package/dist/impl-ts/index.js
CHANGED
|
@@ -607,7 +607,7 @@ ${n}
|
|
|
607
607
|
`}function f2(e,n){let t=Object.fromEntries([["t",e],["seq",n.entrySeq],["kind",n.kind],["data",n.data]]),r=n.coalesceKey;return r!==void 0&&(t.coalesceKey=r),t.resolution=vQ(n.resolution),t.atMs=n.enqueuedAtMs,lg(t)}function pv(e,n){return lg(Object.fromEntries([["t",e],["seq",n]]))}function XC(e){if(typeof e=="string")return e}function ug(e,n){return e!==void 0&&typeof e=="number"&&St(e)?e:n}function xDe(e){let n=e.seq,t=n!==void 0&&typeof n=="number"&&St(n)?n:void 0,r=XC(e.kind),o=e.data,i=typeof o=="object"&&o!==null&&!Array.isArray(o)?o:void 0,a=e.resolution,s=typeof a=="string"?vDe(a):void 0,d=e.atMs,u=d!==void 0&&typeof d=="number"&&isFinite(d)?d:0;if(t!==void 0&&r!==void 0&&i!==void 0&&s!==void 0)return{entrySeq:t,kind:r,data:i,coalesceKey:XC(e.coalesceKey),resolution:s,attempts:0,enqueuedAtMs:u}}function wDe(e,n,t,r,o,i){let a=t.counters,s=l=>{let f=Dn(XC(e.t),"missing"),p=ro({path:o,recordType:f,reason:l});if(p!==void 0){let h=qu(p);if(h.TAG==="Ok")return r("outbox_journal_line_discarded",h._0);console.warn("outbox_journal_diagnostic_encoding_failed path="+o+" reason="+h._0);return}r("outbox_journal_line_discarded",{}),console.warn("outbox_journal_diagnostic_encoding_failed path="+o)},d=l=>{if(l>a.lastEntrySeq){a.lastEntrySeq=l;return}},u=e.t,c=0;if(typeof u=="string")switch(u){case"coalesce":a.totalEnqueued=a.totalEnqueued+1|0;let l=e.seq,f=l!==void 0&&typeof l=="number"&&St(l)?l:void 0,p=e.data,h=typeof p=="object"&&p!==null&&!Array.isArray(p)?p:void 0;if(f===void 0||h===void 0)return s("coalesce requires integer seq and object data");let y=n.get(f);return y!==void 0?y.data=h:s("coalesce entry missing"),d(f);case"context":let m=e.kv;if(m===void 0||typeof m!="object"||m===null||Array.isArray(m))return s("context requires object kv");t.kv=new Map,Object.entries(m).forEach(S=>{t.kv.set(S[0],S[1])});return;case"counters":let _=e.nonterminalFailed;return _!==void 0&&(typeof _=="number"&&St(_)&&_>=0?a.knownNonterminalFailures=_|0:s("counters requires nonnegative integer nonterminalFailed")),["enqueued","acked","dropped","failed","expired","lastSeq"].forEach(S=>{let C=e[S];if(typeof C=="number")return St(C)&&C>=0?void 0:s("counters requires nonnegative integer "+S);s("counters requires nonnegative integer "+S)}),a.totalEnqueued=ug(e.enqueued,0)|0,a.totalAcked=ug(e.acked,0)|0,a.totalDroppedBestEffort=ug(e.dropped,0)|0,a.totalPermanentFailures=ug(e.failed,0)|0,a.totalExpiredOnRecovery=ug(e.expired,0)|0,d(ug(e.lastSeq,0));case"item_seq":return;case"kv":let w=XC(e.key),v=e.value;if(w!==void 0&&v!==void 0){t.kv.set(w,v);return}else return s("kv requires string key and present value");case"enqueue":case"pending":c=2;break;case"ack":case"drop":case"expired":case"fail":case"skip":c=3;break;default:c=1}else c=1;switch(c){case 1:return r("outbox_journal_unknown_record",Object.fromEntries([["path",o],["recordType",Dn(e.t,null)]]));case 2:let l=xDe(e);if(l===void 0)return r("outbox_journal_line_discarded",Object.fromEntries([["path",o],["recordType",Dn(e.t,null)]]));if(n.set(l.entrySeq,l),d(l.entrySeq),e.t==="enqueue"){a.totalEnqueued=a.totalEnqueued+1|0;return}else return;case 3:let p=e.seq;if(p===void 0||typeof p!="number"||!St(p))return s("terminal disposition requires integer seq");let h=e.t,y=n.get(p);h==="fail"&&y!==void 0&&(y.kind==="adt.terminal_attempt"?(i.contents=i.contents+1|0,t.failedTerminalEntries.push(y)):a.knownNonterminalFailures=Dn(a.knownNonterminalFailures,0)+1|0),n.delete(p),d(p);let m=e.t;if(m===void 0||typeof m!="string")return;switch(m){case"ack":a.totalAcked=a.totalAcked+1|0;return;case"drop":a.totalDroppedBestEffort=a.totalDroppedBestEffort+1|0;return;case"expired":a.totalExpiredOnRecovery=a.totalExpiredOnRecovery+1|0;return;case"fail":a.totalPermanentFailures=a.totalPermanentFailures+1|0;return;default:return}}}function cc(e,n,t){let r={pendingEntries:[],failedTerminalEntries:[],kv:new Map,counters:{totalEnqueued:0,totalAcked:0,totalDroppedBestEffort:0,totalPermanentFailures:0,knownNonterminalFailures:0,totalExpiredOnRecovery:0,lastEntrySeq:0}},o=t!==void 0?{TAG:"Ok",_0:t}:Ks(e);if(o.TAG==="Ok"){let a=new Map,s={contents:0},d={contents:0},u=o._0.split(`
|
|
608
608
|
`),c={contents:-1};u.forEach((f,p)=>{if(f.trim()!==""){c.contents=p;return}}),u.forEach((f,p)=>{if(!(p<=c.contents&&f.trim()!==""))return;let h;try{h=JSON.parse(f)}catch{h=void 0}if(typeof h=="object"&&h!==null&&!Array.isArray(h)){if(h.t==="counters"){let m=h.failed;typeof m=="number"&&St(m)&&m>d.contents&&(d.contents=m|0)}return wDe(h,a,r,n,e,s)}n("outbox_journal_line_discarded",Object.fromEntries([["path",e],["line",p+1|0],["trailing",p===c.contents]]))}),r.counters.totalPermanentFailures<d.contents&&(r.counters.totalPermanentFailures=d.contents);let l=s.contents+Dn(r.counters.knownNonterminalFailures,0)|0;if(l!==r.counters.totalPermanentFailures){let f=ro({path:e,recordedFailures:r.counters.totalPermanentFailures,accountedFailures:l});if(f!==void 0){let p=qu(f);p.TAG==="Ok"?n("outbox_journal_failure_inventory_incomplete",p._0):console.warn("outbox_journal_failure_inventory_encoding_failed path="+e+" reason="+p._0)}else n("outbox_journal_failure_inventory_incomplete",{}),console.warn("outbox_journal_failure_inventory_encoding_failed path="+e)}return r.pendingEntries=a.values().toArray(),r}let i=o._0;return Js(i,"ENOENT")||n("outbox_journal_read_failed",Object.fromEntries([["path",e],["error",i.message]])),r}function SDe(e){return rr(e,0,(n,t)=>(n+t.split(`
|
|
609
609
|
`).length|0)-1|0)}function xQ(e,n,t,r,o,i){let a=r!==void 0?r:256,s=o!==void 0?o:3,d=i!==void 0?i:RW,u={contents:e},c=Hl(mv.dirname(e));c.TAG!=="Ok"&&ta(t,"outbox_journal_directory_creation_failed",{path:e,reason:c._0.message});let l={contents:[]},f={contents:Promise.resolve()},p={contents:void 0},h={contents:0},y={contents:0},m={contents:!1},_={contents:!1},w={contents:!1},v={contents:0},S={contents:0},C={contents:!1},A={contents:0},T={contents:!1},M={contents:!1},I=K=>{if(T.contents=!0,S.contents=S.contents+1|0,v.contents=v.contents+1|0,t("outbox_journal_write_failed",Object.fromEntries([["path",u.contents],["error",K]])),!C.contents&&v.contents>=s&&(C.contents=!0,t("outbox_journal_degraded",Object.fromEntries([["level","error"],["path",u.contents],["consecutiveWriteFailures",v.contents],["totalWriteFailures",S.contents]]))),!(C.contents&&l.contents.length!==0))return;M.contents=!0;let Z=SDe(l.contents);l.contents=[],t("outbox_journal_buffered_records_dropped",Object.fromEntries([["level","error"],["path",u.contents],["droppedRecords",Z],["consecutiveWriteFailures",v.contents],["totalWriteFailures",S.contents]]))},P=()=>{if(v.contents=0,C.contents)return C.contents=!1,t("outbox_journal_recovered",Object.fromEntries([["level","warn"],["path",u.contents],["totalWriteFailures",S.contents]]))},z=async()=>{h.contents=0,y.contents=0,m.contents=!1;let K=n(),Z;try{let re=JSON.stringify({t:"counters",enqueued:K.counters.totalEnqueued,acked:K.counters.totalAcked,dropped:K.counters.totalDroppedBestEffort,failed:K.counters.totalPermanentFailures,expired:K.counters.totalExpiredOnRecovery,lastSeq:K.counters.lastEntrySeq,nonterminalFailed:K.counters.knownNonterminalFailures});Z=re!==void 0?{TAG:"Ok",_0:re+`
|
|
610
|
-
`}:{TAG:"Error",_0:"journal counters could not be serialized"}}catch(re){let _e=Tn(re);Z={TAG:"Error",_0:tr(_e).message}}if(Z.TAG!=="Ok")return Z;let N=Z._0,W=l.contents;l.contents=[];let ee={};K.kv.forEach((re,_e)=>{ee[_e]=re});let ne=[N,lg(Object.fromEntries([["t","context"],["kv",ee]]))].concat(K.pendingEntries.map(re=>f2("pending",re))),ye=K.failedTerminalEntries;ye.length!==0&&(ye.forEach(re=>{ne.push(f2("pending",re)),ne.push(pv("fail",re.entrySeq))}),ne.push(N));let L=u.contents+".tmp",ce=await EW(L,ne.join("")),pe;return pe=ce.TAG==="Ok"?await lD(L,u.contents):{TAG:"Error",_0:ce._0},pe.TAG==="Ok"?(T.contents=!1,_.contents=K.pendingEntries.length===0,t("outbox_journal_compacted",Object.fromEntries([["path",u.contents],["pendingEntries",K.pendingEntries.length]])),{TAG:"Ok",_0:void 0}):(l.contents=W.concat(l.contents),h.contents=a,y.contents=1048576,{TAG:"Error",_0:pe._0.message})},$=async()=>{let K;if(l.contents.length!==0){let N=l.contents.join("");l.contents=[];let W=await d(u.contents,N);W.TAG==="Ok"?K={TAG:"Ok",_0:void 0}:(l.contents=[N].concat(l.contents),K={TAG:"Error",_0:W._0.message})}else K={TAG:"Ok",_0:void 0};if(K.TAG!=="Ok")return{TAG:"Error",_0:K._0};let Z=h.contents>0&&!_.contents&&!m.contents?n().pendingEntries.length===0:!1;return T.contents||h.contents>=a||y.contents>=1048576||Z?await z():{TAG:"Ok",_0:void 0}},J=()=>{let K=p.contents;if(K!==void 0)return K;A.contents=A.contents+1|0;let Z=f.contents.then(()=>(p.contents=void 0,$().then(N=>(N.TAG==="Ok"?P():I(N._0),A.contents=A.contents-1|0,N))));return p.contents=Z,f.contents=Z.then(N=>{}),Z},Q=(K,Z)=>w.contents?(M.contents=!0,t("outbox_journal_append_after_close",Object.fromEntries([["path",u.contents]])),Promise.resolve({TAG:"Error",_0:"outbox journal is closed"})):(l.contents.push(K),y.contents=y.contents+Buffer.byteLength(K,"utf8")|0,Z&&(h.contents=h.contents+1|0),J());return{durability:()=>M.contents?"Lost":A.contents>0||l.contents.length!==0||T.contents?"Pending":"Durable",writeInProgress:()=>!M.contents&&!T.contents?A.contents>0?!0:l.contents.length!==0:!1,appendEnqueue:K=>Q(f2("enqueue",K),!1),appendCoalesce:(K,Z)=>Q(lg(Object.fromEntries([["t","coalesce"],["seq",K],["data",Z]])),!1),appendAck:(K,Z)=>{Z!==void 0&&Z&&(m.contents=!0),Q(pv("ack",K),!0)},appendSkip:(K,Z)=>{Q(lg(Object.fromEntries([["t","skip"],["seq",K],["reason",Z]])),!0)},appendDrop:K=>{Q(pv("drop",K),!0)},appendFail:K=>{Q(pv("fail",K),!0)},appendExpired:K=>{Q(pv("expired",K),!0)},appendKv:(K,Z)=>{Q(lg(Object.fromEntries([["t","kv"],["key",K],["value",Z]])),!1)},settled:()=>f.contents.then(()=>{}),status:()=>({totalWriteFailures:S.contents,degraded:C.contents}),rekey:K=>{if(w.contents)return t("outbox_journal_rekey_after_close",Object.fromEntries([["path",K]]));A.contents=A.contents+1|0,f.contents=f.contents.then(async()=>{if(K!==u.contents){let Z=u.contents,N=Hl(mv.dirname(K)),W;if(W=N.TAG==="Ok"?await lD(Z,K):{TAG:"Error",_0:N._0},W.TAG==="Ok")u.contents=K,t("outbox_journal_rekeyed",Object.fromEntries([["from",Z],["to",K]]));else{let ee=W._0;Js(ee,"ENOENT")?(u.contents=K,t("outbox_journal_rekeyed",Object.fromEntries([["from",Z],["to",K]]))):(M.contents=!0,t("outbox_journal_rekey_failed",Object.fromEntries([["level","error"],["from",Z],["to",K],["error",ee.message]])))}}A.contents=A.contents-1|0})},close:async()=>{if(w.contents=!0,A.contents=A.contents+1|0,await f.contents,l.contents.length!==0||T.contents||h.contents>=a||y.contents>=1048576){let K=await $();K.TAG==="Ok"?P():I(K._0)}A.contents=A.contents-1|0}}}var cg=B(()=>{kr();Wr();vt();Cr();yo();dg();$u()});function YC(e,n,t,r,o,i){if(!e)return{kind:"unavailable",reason:"terminal journal durability unavailable"};let a=n.filter(s=>s.kind==="adt.terminal_attempt").length;return a>0?{kind:"pending",count:a}:rr(t,"clear",(s,d)=>{if(typeof s=="object"&&s.kind==="unavailable")return s;let u=r(Xl(d.entrySeq));if(u!==void 0){let l=ro(d.data),f=ro(u);return(l!==void 0&&f!==void 0?Yl(d.entrySeq,l,f):!1)?s:(ta(i,"adt.terminal_repair_receipt_mismatch",{threadKey:o,entrySeq:d.entrySeq}),{kind:"unavailable",reason:"terminal correction receipt mismatch"})}let c;return c=typeof s!="object"||s.kind!=="repair_needed"?0:s.count,{kind:"repair_needed",count:c+1|0}})}var p2=B(()=>{kr();$u()});function TDe(e,n){switch(e){case"MustReachConsensus":return{TAG:"RetryAfterExhaustion",_0:Dn(n[n.length-1|0],1e3)};case"MustAck":case"BestEffort":return"FailAfterExhaustion"}}function PDe(e,n){switch(e){case"MustReachConsensus":return!1;case"MustAck":case"BestEffort":return n}}function eT(e,n){return e+"\0"+n}function SQ(e,n){let t=Math.max(1,Math.ceil(n*e.length)|0);return Dn(e[t-1|0],0)}function ADe(e){if(e.length===0)return;let n=e.toSorted((t,r)=>t-r);return{p50Ms:SQ(n,.5),p95Ms:SQ(n,.95),maxMs:Dn(n[n.length-1|0],0),ackedInWindow:n.length}}function IDe(e){return new Promise((n,t)=>{setTimeout(()=>n(),e)})}function gv(e,n){if(n.kind!=="adt.terminal_attempt")return!1;let t=n.resolution,r=n.data;switch(t){case"MustAck":let o=r.thread_key;if(typeof o!="string")return!1;let i=r.seq;if(typeof i!="number")return!1;let a=r.turn_id;if(typeof a!="string")return!1;let s=r.status;if(typeof s!="string"||s!=="processed")return!1;let d=r.terminal_frame;if(typeof d!="object"||d===null||Array.isArray(d))return!1;let u=d.session_id;if(typeof u!="number")return!1;let c=d.lease_epoch;if(typeof c!="number")return!1;let l=d.frame_index;if(typeof l!="number")return!1;let f=d.frame_kind;if(typeof f!="string"||f!=="terminal")return!1;let p=d.assistant_phase;if(typeof p!="string"||p!=="final_answer")return!1;let h=d.source_stream_key;return typeof h!="string"?!1:typeof d.body=="string"&&o===e&&a!==""&&h!==""?[i,u,c,l].every(m=>St(m)&&m>0?m<=9007199254740991:!1):!1;case"MustReachConsensus":case"BestEffort":return!1}}function m2(e){let n=Dn(e.recoveryMode,"OrdinaryRecovery"),t=e.log,r=e.onPermanentFailure,o=e.builders,i=e.threadKey,a={contents:i},s=ue=>{throw ta(t,"outbox_journal_generation_refused",{thread_key:i,reason:ue}),new Error(ue)},d=e.journalGeneration;if(d!==void 0){let ue=cv(d),Pe=e.persistDir;ue&&Pe!==void 0||s("journal generation requires a valid session and durable directory")}let u=ue=>{let Pe=e.journalGeneration;return Pe!==void 0?lc(ue,Pe):ue},c=Dn(e.now,()=>Date.now()),l=Dn(e.retryDelaysMs,kDe.slice()),f={contents:[]},p={contents:0},h=[],y=[],m=[],_=new Map,w={contents:new Map},v={contents:0},S=[],C={contents:1},A={contents:0},T={contents:0},M={contents:0},I={contents:0},P={contents:0},z={contents:0},$={contents:0},J=[],Q={contents:0},K={contents:n==="TerminalRepairRecovery"},Z={contents:!0},N={contents:!1},W={contents:void 0},ee={contents:void 0},ne={contents:!1},ye=new Map,L=new Map,ce=(ue,Pe)=>{let be=Pe.then(en=>(ye.delete(ue),en));ye.set(ue,be)},pe=Math.max(1,Dn(e.maxInFlightPushes,1)),re={contents:0},_e={contents:0},le={contents:[]},Oe={contents:Promise.resolve()},F=()=>f.contents[p.contents],H=()=>({totalEnqueued:A.contents,totalAcked:T.contents,totalDroppedBestEffort:I.contents,totalPermanentFailures:P.contents,knownNonterminalFailures:z.contents,totalExpiredOnRecovery:$.contents,lastEntrySeq:C.contents-1}),V=e.persistDir;if(V!==void 0){let ue=ap(V,u(a.contents)),Pe=e.journalGeneration,be;if(Pe!==void 0){let yn=Dk(sg(Pe));be=yn.TAG==="Ok"?yn._0:s(yn._0)}else be=void 0;let en=e.journalGeneration,pn;if(en!==void 0){let yn=vi(ue);if(yn.TAG==="Ok")switch(yn._0){case"LstatMissing":pn=!1;break;case"LstatFile":pn=!0;break;case"LstatSymlink":case"LstatOther":pn=s("journal location is not a regular file");break}else pn=s(yn._0.message)}else pn=!1;let rn=cc(ue,(yn,Wn)=>{ne.contents=!0,t(yn,Wn)},void 0);rn.pendingEntries.forEach(yn=>{m.push(yn)});let mn=e.journalGeneration;if(mn!==void 0)if(be!==void 0){if(pn){let yn=rn.kv.get(is);if(yn!==void 0){let Wn=QC(yn);Wn.TAG==="Ok"?Jn(Wn._0,mn)&&!ne.contents||s("journal generation identity mismatch or unavailable contents"):s(Wn._0)}else s("existing generation journal lacks identity metadata")}}else s("journal generation metadata construction mismatch");else be!==void 0?s("journal generation metadata construction mismatch"):rn.kv.has(is)&&s("generation journal opened without required identity");let nt=Dn(e.journalRecoveryMaxAgeMs,CDe),Qn=c(),ft=[];rn.pendingEntries.forEach(yn=>{let Wn=!1;if(n==="TerminalRepairRecovery"&&gv(a.contents,yn)){let Fi=yn.data.terminal_repair,Lt;if(Fi!==void 0)if(typeof Fi=="object"&&Fi!==null&&!Array.isArray(Fi)){let ji=Fi.failed_entry_seq;if(typeof ji=="number"){let Xi=Fi.original_lease_epoch;if(typeof Xi=="number"){let Pd=rn.failedTerminalEntries.find(Fe=>Fe.entrySeq===ji&&!("terminal_repair"in Fe.data)?gv(a.contents,Fe):!1),zs=rn.kv.get("terminal_repair_prepared:"+ji.toString()),Y=ro(yn.data);if(Pd!==void 0&&zs!==void 0&&typeof zs=="string"&&Y!==void 0&&["thread_key","seq","turn_id","status"].every(Fe=>Jn(Pd.data[Fe],yn.data[Fe]))){let Fe=Pd.data.terminal_frame,Le=yn.data.terminal_frame,ve;ve=typeof Fe=="object"&&Fe!==null&&!Array.isArray(Fe)&&typeof Le=="object"&&Le!==null&&!Array.isArray(Le)?Jn(Fe.lease_epoch,Xi)&&["session_id","body"].every(ze=>Jn(Fe[ze],Le[ze]))&&Jf(zs,Y):!1,Lt=ve}else Lt=!1}else Lt=!1}else Lt=!1}else Lt=!1;else Lt=!0;Wn=Lt}if(PDe(yn.resolution,Qn-yn.enqueuedAtMs>nt)&&!Wn){ft.push(yn);return}let er={entry:yn,state:"EntryQueued",outcome:void 0,retryTimer:void 0};f.contents.push(er);let ho=yn.coalesceKey;if(ho!==void 0){_.set(eT(yn.kind,ho),er);return}}),w.contents=rn.kv,be!==void 0&&w.contents.set(is,be),rn.failedTerminalEntries.forEach(yn=>{y.push(yn)}),A.contents=rn.counters.totalEnqueued,T.contents=rn.counters.totalAcked,I.contents=rn.counters.totalDroppedBestEffort,P.contents=rn.counters.totalPermanentFailures,z.contents=Dn(rn.counters.knownNonterminalFailures,0),$.contents=rn.counters.totalExpiredOnRecovery+ft.length|0,C.contents=rn.counters.lastEntrySeq+1;let Mt=xQ(ue,()=>({pendingEntries:h.concat(f.contents.slice(p.contents).map(yn=>yn.entry)),failedTerminalEntries:y,kv:w.contents,counters:H()}),t,e.journalCompactionThreshold,void 0,e.journalAppendFile);if(ee.contents=Mt,be!==void 0&&!pn&&Mt.appendKv(is,be),ft.length!==0){ft.forEach(er=>Mt.appendExpired(er.entrySeq));let yn=ft.map(er=>Math.max(0,Qn-er.enqueuedAtMs)),Wn=new Set(ft.map(er=>er.kind));t("outbox_recovery_expired",Object.fromEntries([["level","warn"],["threadKey",a.contents],["expiredEntries",ft.length],["survivingEntries",f.contents.length-p.contents|0],["maxAgeMs",nt],["oldestAgeMs",rr(yn,0,(er,ho)=>Math.max(er,ho))],["newestAgeMs",rr(yn,Number.POSITIVE_INFINITY,(er,ho)=>Math.min(er,ho))],["kinds",Wn.values().toArray().map(er=>er)]]))}(f.contents.length-p.contents|0)>0&&t("outbox_recovered",Object.fromEntries([["threadKey",a.contents],["pendingEntries",f.contents.length-p.contents|0],["nextEntrySeq",C.contents]]))}let te=(ue,Pe)=>{ue===is&&s("journal generation metadata is immutable"),w.contents.set(ue,Pe);let be=ee.contents;if(be!==void 0){be.appendKv(ue,Pe),v.contents=v.contents+1|0,Bu(be.settled().then(()=>{v.contents=v.contents-1|0}),en=>(ta(t,"outbox_durable_fact_settlement_failed",{threadKey:a.contents,key:ue,reason:tr(en).message}),Promise.resolve()));return}},he=ue=>w.contents.get(ue),me={remember:te,recall:he},Se=()=>{if(p.contents=p.contents+1|0,p.contents>=64&&p.contents<<1>=f.contents.length){f.contents=f.contents.slice(p.contents),p.contents=0;return}},Ie=()=>{let ue=F(),Pe=S.length-1|0;for(;Pe>=0;){let be=S[Pe];if(be!==void 0&&(ue!==void 0?ue.entry.entrySeq>be.upToSeq:!0)){S.splice(Pe,1);let pn=be.timer;pn!==void 0&&clearTimeout(bt(pn)),be.resolve({TAG:"Ok",_0:void 0})}Pe=Pe-1|0}},xe=(ue,Pe)=>{let be=L.get(ue);if(be!==void 0){L.delete(ue),be.forEach(en=>en(Pe));return}},Je=ue=>{let Pe=ue.entry.coalesceKey;if(Pe===void 0)return;let be=eT(ue.entry.kind,Pe),en=_.get(be);if(en!==void 0&&en===ue){_.delete(be);return}},Nn=(ue,Pe)=>{let be=ue.entry;switch(Pe.TAG){case"OutcomeAck":xe(be.entrySeq,{TAG:"Ok",_0:void 0});let en=o[be.kind];if(en!==void 0){let Mt=en.onReply;if(Mt!==void 0){let yn;try{Mt(be.data,Pe._0,me),yn={TAG:"Ok",_0:void 0}}catch(Wn){let er=Tn(Wn);yn={TAG:"Error",_0:tr(er)}}yn.TAG!=="Ok"&&t("outbox_on_reply_failed",Object.fromEntries([["threadKey",a.contents],["entrySeq",be.entrySeq],["kind",be.kind],["error",yn._0.message]]))}}let pn=ee.contents;pn!==void 0&&pn.appendAck(be.entrySeq,be.resolution==="MustReachConsensus");break;case"OutcomeSkip":let rn=Pe._0;xe(be.entrySeq,{TAG:"Error",_0:"outbox entry skipped: "+rn}),t("outbox_entry_skipped",Object.fromEntries([["threadKey",a.contents],["entrySeq",be.entrySeq],["kind",be.kind],["reason",rn]]));let mn=ee.contents;mn!==void 0&&mn.appendSkip(be.entrySeq,rn);break;case"OutcomeFail":let nt=Pe._0;xe(be.entrySeq,{TAG:"Error",_0:nt});let Qn=be.resolution,ft=0;switch(Qn){case"MustAck":case"MustReachConsensus":ft=1;break;case"BestEffort":let Mt=ee.contents;Mt!==void 0&&Mt.appendDrop(be.entrySeq);break}if(ft===1){be.kind==="adt.terminal_attempt"&&y.push(be);let yn=ee.contents;yn!==void 0&&yn.appendFail(be.entrySeq);let Wn;try{r(be,nt),Wn={TAG:"Ok",_0:void 0}}catch(er){let ho=Tn(er);Wn={TAG:"Error",_0:tr(ho)}}Wn.TAG!=="Ok"&&t("outbox_permanent_failure_callback_failed",Object.fromEntries([["threadKey",a.contents],["entrySeq",be.entrySeq],["error",Wn._0.message]]))}break;case"OutcomePreserveForRestart":h.push(be),t("outbox_entry_preserved_for_restart",Object.fromEntries([["threadKey",a.contents],["entrySeq",be.entrySeq],["kind",be.kind],["reason",Pe._0]]));break}Je(ue),Se(),Ie()},Ke=()=>{let ue=!0;for(;ue;){let Pe=F();if(Pe!==void 0){let be=Pe.outcome;be!==void 0?Nn(Pe,be):ue=!1}else ue=!1}},qe=(ue,Pe)=>{let be=ue.entry;if(Pe.TAG==="OutcomeFail"){let en=Pe._0,pn=be.resolution,rn=0;switch(pn){case"MustAck":case"MustReachConsensus":rn=1;break;case"BestEffort":I.contents=I.contents+1|0,t("outbox_dropped_best_effort",Object.fromEntries([["threadKey",a.contents],["entrySeq",be.entrySeq],["kind",be.kind],["attempts",be.attempts],["error",en]]));break}rn===1&&(P.contents=P.contents+1|0,be.kind!=="adt.terminal_attempt"&&(z.contents=z.contents+1|0),t("outbox_permanent_failure",Object.fromEntries([["threadKey",a.contents],["entrySeq",be.entrySeq],["kind",be.kind],["attempts",be.attempts],["error",en]])))}ue.outcome=Pe,ue.state="EntryQueued"},dn=ue=>{let Pe=ue.retryTimer;if(Pe!==void 0){clearTimeout(bt(Pe)),ue.retryTimer=void 0;return}},Ln=ue=>{let Pe=e.supersedesQueuedEntry;if(Pe===void 0)return;let be=ue.kind,en=ue.resolution,pn=ue.data,rn={entryKind:be,resolution:en,data:pn};for(let mn=p.contents,nt=f.contents.length;mn<nt;++mn){let Qn=f.contents[mn];if(Qn!==void 0){let ft=Qn.entry;Qn.state==="EntryQueued"&&(Qn.outcome!==void 0||!Pe(rn,{entryKind:ft.kind,resolution:ft.resolution,data:ft.data})||(dn(Qn),qe(Qn,{TAG:"OutcomeSkip",_0:"superseded_by_terminal"})))}}},In=ue=>{J.length<256?J.push(ue):J[Q.contents]=ue;let Pe=Q.contents+1|0;Q.contents=Pe>=256?0:Pe},cn=()=>{if(re.contents>0)return;let ue=le.contents;le.contents=[],ue.forEach(Pe=>Pe())},ct=()=>{let ue=F();return ue===void 0||ue.state!=="EntryQueued"||ue.outcome!==void 0?!1:ue.retryTimer!==void 0},Un={contents:()=>{}},Rn=(ue,Pe)=>{dn(ue);let be=setTimeout(()=>{if(ue.retryTimer=void 0,!(N.contents||K.contents||ue.outcome!==void 0))return Un.contents()},Pe|0);be.unref(),ue.retryTimer=br(be)},Ye=(ue,Pe,be)=>{if(ue.state="EntryQueued",M.contents=M.contents+1|0,t("outbox_consensus_retry",Object.fromEntries([["threadKey",a.contents],["entrySeq",ue.entry.entrySeq],["kind",ue.entry.kind],["attempt",ue.entry.attempts],["delayMs",be],["error",Pe]])),!N.contents&&!K.contents)return Rn(ue,be)},fn=(ue,Pe)=>{let be=TDe(ue.entry.resolution,l);return typeof be!="object"?qe(ue,{TAG:"OutcomeFail",_0:Pe}):Ye(ue,Pe,be._0)},ht=async(ue,Pe,be)=>{let en=ue.entry,pn=c(),rn;try{rn=await e.push(Pe[0],Pe[1],Pe[2],be,{entryKind:en.kind,resolution:en.resolution,data:en.data})}catch(mn){let nt=Tn(mn);rn={TAG:"PushFailed",_0:{message:tr(nt).message,budgetExempt:!1}}}switch(rn.TAG){case"Acked":let mn=rn._0;be(),In(Math.max(0,c()-pn));let nt=o[en.kind],Qn;if(nt!==void 0){let Fi=nt.adjudicateReply;if(Fi!==void 0)try{Qn=Fi(en.data,mn,me)}catch(Lt){let ji=Tn(Lt);Qn={TAG:"RetryReply",_0:tr(ji).message}}else Qn="AcceptReply"}else Qn="AcceptReply";if(typeof Qn!="object")return T.contents=T.contents+1|0,qe(ue,{TAG:"OutcomeAck",_0:mn});let ft=Qn._0,Mt=l[en.attempts-1|0];return Mt!==void 0?Ye(ue,ft,Mt):fn(ue,ft);case"PushFailed":let yn=rn._0,Wn=yn.message;if(be(),ue.state="EntryQueued",Dn(yn.nonRetryable,!1))return qe(ue,{TAG:"OutcomeSkip",_0:"authenticated_terminal_attempt_superseded"});if(yn.budgetExempt)return en.attempts=en.attempts-1|0,M.contents=M.contents+1|0,t("outbox_push_connection_wait",Object.fromEntries([["threadKey",a.contents],["entrySeq",en.entrySeq],["kind",en.kind],["error",Wn]])),!N.contents&&!K.contents?Rn(ue,1e3):void 0;let ho=l[en.attempts-1|0];return ho!==void 0?(M.contents=M.contents+1|0,t("outbox_push_retry",Object.fromEntries([["threadKey",a.contents],["entrySeq",en.entrySeq],["kind",en.kind],["attempt",en.attempts],["delayMs",ho],["error",Wn]])),!N.contents&&!K.contents?Rn(ue,ho):void 0):fn(ue,Wn);case"PreserveForRestart":return be(),ue.state="EntryQueued",en.attempts=en.attempts-1|0,qe(ue,{TAG:"OutcomePreserveForRestart",_0:rn._0})}},q=async(ue,Pe)=>{let be=Pe!==void 0?Pe:!1,en=ue.entry,pn=be?Promise.resolve():Oe.contents,rn={contents:()=>{}};be||(Oe.contents=new Promise((Mt,yn)=>{rn.contents=Mt}));let mn={contents:!1},nt=()=>{if(!mn.contents)return mn.contents=!0,rn.contents()};ue.state="EntryPushing",re.contents=re.contents+1|0;let Qn=()=>{if(re.contents=re.contents-1|0,be){_e.contents=_e.contents-1|0;return}};if(await pn,N.contents||K.contents||ue.outcome!==void 0)return ue.state="EntryQueued",nt(),Qn();let ft=o[en.kind];if(ft!==void 0){let Mt;try{Mt=ft.build(en.data,me)}catch(yn){let Wn=Tn(yn);Mt={TAG:"BuildFailed",_0:tr(Wn).message}}switch(Mt.TAG){case"BuildPush":return en.attempts=en.attempts+1|0,await ht(ue,[Mt.event,Mt.payload,Mt.timeoutMs],nt),Qn();case"BuildSkip":let yn=Mt._0;switch(nt(),en.resolution){case"MustReachConsensus":fn(ue,"must_reach_consensus builder skipped without consensus: "+yn);break;case"MustAck":case"BestEffort":qe(ue,{TAG:"OutcomeSkip",_0:yn});break}return Qn();case"BuildFailed":return nt(),fn(ue,Mt._0),Qn()}}else return nt(),fn(ue,"no outbox builder registered for kind "+en.kind),Qn()},X=()=>{let ue=e.isPriorityEntry;if(ue===void 0)return;let Pe,be=!1,en=!1;for(let pn=p.contents,rn=f.contents.length;pn<rn;++pn){let mn=Pe,nt=en,Qn=f.contents[pn];if(mn===void 0&&!nt&&Qn!==void 0){let ft=Qn.entry;if(Qn.outcome===void 0)if(ue({entryKind:ft.kind,resolution:ft.resolution,data:ft.data})){let Wn=Qn.state,er=Qn.retryTimer;Wn==="EntryQueued"&&er===void 0&&be?Pe=Qn:en=!0}else{let Wn=Qn.state,er=Qn.retryTimer;(Wn!=="EntryQueued"||er!==void 0)&&(be=!0)}}}return Pe},ae=()=>{if(_e.contents!==0)return;let Pe=X();if(Pe!==void 0){_e.contents=_e.contents+1|0,Bu(q(Pe,!0).then(()=>Un.contents()),be=>(t("outbox_priority_overflow_error",Object.fromEntries([["threadKey",a.contents]])),Un.contents(),Promise.resolve()));return}},j=()=>{if(Ke(),N.contents||K.contents)return cn();if(ct())return ae(),cn();let ue=p.contents;for(;ue<f.contents.length&&re.contents<pe;){let Pe=f.contents[ue];Pe!==void 0&&Pe.state==="EntryQueued"&&Pe.outcome===void 0&&(Pe.retryTimer!==void 0||Bu(q(Pe,void 0).then(()=>j()),rn=>(t("outbox_drain_loop_error",Object.fromEntries([["threadKey",a.contents]])),j(),Promise.resolve()))),ue=ue+1|0}re.contents>=pe&&ae(),cn()};Un.contents=j;let de=()=>{if(K.contents||N.contents)return;if(F()!==void 0){Promise.resolve().then(()=>{if(!N.contents&&!K.contents)return j()});return}},ge=ue=>{let Pe=C.contents-1,be=F();return(be!==void 0?be.entry.entrySeq>Pe:!0)?Promise.resolve({TAG:"Ok",_0:void 0}):new Promise((pn,rn)=>{let mn={upToSeq:Pe,resolve:pn,timer:void 0};ue!==void 0&&(mn.timer=br(setTimeout(()=>{let nt=S.indexOf(mn);nt===-1||S.splice(nt,1),pn({TAG:"Error",_0:"outbox flush for "+a.contents+" timed out after "+ue.toString()+"ms with "+(f.contents.length-p.contents|0).toString()+" entries pending"})},ue|0))),S.push(mn)})},Te=async ue=>{Z.contents=!1;let Pe=await ge(ue);Pe.TAG!=="Ok"&&t("outbox_close_flush_timeout",Object.fromEntries([["threadKey",a.contents],["depth",f.contents.length-p.contents|0],["error",Pe._0]])),N.contents=!0;let be=p.contents;for(;be<f.contents.length;){let rn=f.contents[be];rn!==void 0&&dn(rn),be=be+1|0}re.contents>0&&await Promise.race([new Promise((rn,mn)=>{le.contents.push(()=>rn())}),IDe(1e3)]);let en=S.slice();S.splice(0,S.length),en.forEach(rn=>{let mn=rn.timer;mn!==void 0&&clearTimeout(bt(mn)),rn.resolve({TAG:"Error",_0:"outbox for "+a.contents+" closed"})}),L.forEach((rn,mn)=>{rn.forEach(nt=>nt({TAG:"Error",_0:"outbox entry "+mn.toString()+" for "+a.contents+" closed before acknowledgement"}))}),L.clear();let pn=ee.contents;if(pn!==void 0)return await pn.close()},Ae=(ue,Pe,be)=>{if(ue===void 0)return be;let en=ue.coalesce;if(en===void 0)return be;let pn;try{pn={TAG:"Ok",_0:en(Pe.data,be)}}catch(rn){let mn=Tn(rn);pn={TAG:"Error",_0:tr(mn)}}return pn.TAG==="Ok"?pn._0:(t("outbox_coalesce_failed",Object.fromEntries([["threadKey",a.contents],["entrySeq",Pe.entrySeq],["kind",Pe.kind],["error",pn._0.message]])),be)},Aa={failedTerminalEntries:()=>y.slice(),terminalPublicationDebt:()=>{let ue=ee.contents,Pe=ue!==void 0?ue.durability()==="Durable"&&!ne.contents&&v.contents===0:!1;return YC(Pe,h.concat(f.contents.slice(p.contents).map(be=>be.entry)),y,he,a.contents,t)},restartWriteInProgress:()=>{let ue=ee.contents;return ue!==void 0&&!ne.contents?ue.writeInProgress():!1},pendingTerminalEntries:()=>h.concat(f.contents.slice(p.contents).map(ue=>ue.entry)).filter(ue=>ue.kind==="adt.terminal_attempt"),retainPendingTerminalForRepair:async()=>{let ue=mn=>(ta(t,"outbox_cold_publication_retention_refused",{thread_key:a.contents,reason:mn}),{TAG:"Error",_0:mn}),Pe=f.contents.slice(p.contents),be=Pe.filter(mn=>mn.entry.kind==="adt.terminal_attempt"?!("terminal_repair"in mn.entry.data):!1);if(!(K.contents&&!N.contents&&re.contents===0&&h.length===0&&Pe.every(mn=>mn.state==="EntryQueued"&&Md(mn.outcome)?Md(mn.retryTimer):!1)))return ue("cold publication retention requires paused, live, no-inflight ownership");if(be.length===0)return Pe.every(mn=>mn.entry.kind==="adt.terminal_attempt")?{TAG:"Ok",_0:void 0}:ue("mixed ordinary pending publication work");if(!(Pe.length===be.length&&be.every(mn=>m.some(nt=>nt===mn.entry)?gv(a.contents,mn.entry):!1)))return ue("mixed, malformed or non-recovered pending publication work");let pn=ee.contents;if(pn===void 0)return ue("cold publication journal is unavailable");switch(pn.durability()){case"Durable":switch(be.forEach(nt=>{pn.appendFail(nt.entry.entrySeq),y.push(nt.entry),Je(nt)}),p.contents=f.contents.length,be.forEach(nt=>ta(t,"outbox_cold_publication_retained_for_repair",{thread_key:a.contents,entry_seq:nt.entry.entrySeq})),await pn.settled(),pn.durability()){case"Durable":return{TAG:"Ok",_0:void 0};case"Pending":case"Lost":return ue("cold publication retention did not become durable")}case"Pending":case"Lost":return ue("cold publication journal is not durable")}},rememberDurableFact:te,recallDurableFact:he,enqueue:ue=>{if(!Z.contents)return{TAG:"Error",_0:"outbox for "+a.contents+" is closed"};A.contents=A.contents+1|0,Ln(ue);let Pe=ue.coalesceKey,be;if(Pe!==void 0){let Qn=eT(ue.kind,Pe),ft=_.get(Qn);if(ft!==void 0)if(ft.state==="EntryQueued")if(ft.outcome!==void 0)be=void 0;else{ft.entry.data=Ae(o[ue.kind],ft.entry,ue.data);let Wn=ee.contents;Wn!==void 0?ce(ft.entry.entrySeq,Wn.appendCoalesce(ft.entry.entrySeq,ft.entry.data)):ce(ft.entry.entrySeq,Promise.resolve({TAG:"Error",_0:"outbox journal is unavailable"})),be=ft.entry.entrySeq}else be=void 0;else be=void 0}else be=void 0;if(be!==void 0)return{TAG:"Ok",_0:be};let en=C.contents;C.contents=C.contents+1;let pn={entrySeq:en,kind:ue.kind,data:ue.data,coalesceKey:ue.coalesceKey,resolution:ue.resolution,attempts:0,enqueuedAtMs:c()},rn={entry:pn,state:"EntryQueued",outcome:void 0,retryTimer:void 0};f.contents.push(rn);let mn=ue.coalesceKey;mn!==void 0&&_.set(eT(ue.kind,mn),rn);let nt=ee.contents;return nt!==void 0?ce(en,nt.appendEnqueue(pn)):ce(en,Promise.resolve({TAG:"Error",_0:"outbox journal is unavailable"})),de(),{TAG:"Ok",_0:en}},awaitEnqueuePersistence:ue=>{let Pe=ye.get(ue);return Pe!==void 0?Pe:Promise.resolve({TAG:"Error",_0:"outbox enqueue "+ue.toString()+" has no pending persistence acknowledgement"})},awaitEntryAcknowledgement:ue=>new Promise((Pe,be)=>{let en=L.get(ue);en!==void 0?en.push(Pe):L.set(ue,[Pe])}),flush:ge,pause:()=>{K.contents=!0},resume:()=>{if(!K.contents)return;K.contents=!1;let ue=p.contents;for(;ue<f.contents.length;){let Pe=f.contents[ue];Pe!==void 0&&(Pe.entry.attempts=0,dn(Pe)),ue=ue+1|0}de()},metrics:()=>{let ue=F(),Pe=$t(ee.contents,be=>be.status());return{depth:f.contents.length-p.contents|0,oldestEntryAgeMs:$t(ue,be=>Math.max(0,c()-be.entry.enqueuedAtMs)),totalEnqueued:A.contents,totalAcked:T.contents,totalRetried:M.contents,totalDroppedBestEffort:I.contents,totalPermanentFailures:P.contents,totalExpiredOnRecovery:$.contents,totalJournalWriteFailures:Dn($t(Pe,be=>be.totalWriteFailures),0),journalDegraded:Dn($t(Pe,be=>be.degraded),!1),paused:K.contents,pushLatency:ADe(J)}},close:ue=>{let Pe=W.contents;if(Pe!==void 0)return Pe;let be=Te(Dn(ue,3e4));return W.contents=be,be},journalSettled:()=>{let ue=ee.contents;return ue!==void 0?ue.settled():Promise.resolve()},rekeyJournal:ue=>{if(ue===a.contents)return;a.contents=ue;let Pe=e.persistDir,be=ee.contents;if(Pe!==void 0&&be!==void 0)return be.rekey(ap(Pe,u(ue)))}};return de(),Aa}var kDe,CDe,nT=B(()=>{kr();Wr();vt();ig();Dr();ir();Cr();yo();cg();dg();$u();p2();kDe=[500,1e3,2500,5e3,1e4,3e4],CDe=1440*60*1e3});var RDe,OAn,tT=B(()=>{Uu();RDe=["deterministic","transient_upstream","transient_local","rate_limited","needs_approval","needs_decision","route_outage"],OAn=oV(RDe)});var kQ=B(()=>{});var GAn,CQ=B(()=>{kr();vt();ti();Dr();ir();kQ();GAn=Object.fromEntries([["granular",Object.fromEntries([["sandbox_approval",!1],["rules",!1],["skill_approval",!1],["request_permissions",!1],["mcp_elicitations",!0]])]])});var fg=B(()=>{vt();tT();cg()});var VAn,HAn,ZAn,_v=B(()=>{kr();vt();Dr();Cr();CQ();fg();VAn=new RegExp("^https?:\\/\\/","i"),HAn=new RegExp("^data:","i"),ZAn=new RegExp("^file:\\/\\/","i")});var y2=B(()=>{kr();Wr();vt();ir();Cr();_v()});var IQ=B(()=>{});var zIn,GIn,UIn,BIn,JIn,KIn,WIn,VIn,HIn,ZIn,QIn,XIn,YIn,eRn,nRn,tRn,rRn,oRn,iRn,aRn,_2=B(()=>{kr();xq();vt();fD();Dr();ir();tT();Cr();IQ();_v();fg();y2();zIn=new RegExp("<[^>]*>","g"),GIn=new RegExp(`data:[^"' )]+`,"g"),UIn=new RegExp("\\s+","g"),BIn=new RegExp("(?:<!doctype\\s+html|<html(?:\\s|>))","i"),JIn=new RegExp("cloudflare|cf-ray|\\bblocked\\b|access denied|\\bchallenge\\b|attention required","i"),KIn=new RegExp("cloudflare|cf-ray","i"),WIn=new RegExp("\\bblocked\\b|access denied","i"),VIn=new RegExp("attention required","i"),HIn=new RegExp("@font-face","i"),ZIn=new RegExp("unexpected status (401|403)\\b","i"),QIn=new RegExp("\\b(401|403)\\s+(?:unauthorized|forbidden)\\b","i"),XIn=new RegExp("^(?:model_request_rejected|invalid_request_error|invalid_request|request_rejected|content_policy_violation|content_filter|input_validation_error)$","i"),YIn=new RegExp("\\bmodel request was rejected\\b|\\bmodel_request_rejected\\b","i"),eRn=new RegExp("^provider_outage$","i"),nRn=new RegExp("rejecting requests|experiencing an outage|provider outage","i"),tRn=new RegExp("\\bapply_patch\\b[^]*\\bincompatible\\b|\\bin-flight tool future\\b[^]*\\bfail","i"),rRn=new RegExp("\\btools::router\\b[^]*\\bfatal\\b|\\bresponse\\.failed\\b","i"),oRn=new RegExp("(tool.*fatal|fatal.*tool|response[._]failed|tool_failure)","i"),iRn=new RegExp("upstream model stream stalled","i"),aRn=new RegExp("\\(HTTP (\\d{3})\\)")});var lRn,b2=B(()=>{Eu();vt();ir();yo();_v();fg();y2();_2();lRn=10*6e4});var pRn,MQ=B(()=>{kr();vt();ir();Lf();yo();b2();fg();pRn=10*6e4});function v2(e,n){return{message:n,budgetExempt:!1,preserveForRestart:e!==void 0?e:!1}}function $Q(e,n){let t=n-e.maxLivePressureAgeMs;return e.activeAckStartedAtMs.some(r=>r<=t)}function oT(e){return e.replace(eqe,"?").slice(0,128)}function FQ(e,n){return rr(e.activeAckStartedAtMs,0,(t,r)=>Math.max(t,n-r))}function nqe(e,n,t,r,o){e.pressureShedCount.contents=e.pressureShedCount.contents+1|0;let i=o!==void 0?o.TAG==="ItemStream"?["item",oT(o.itemKey),$t(o.turnId,oT)]:["turn",void 0,oT(o._0)]:["none",void 0,void 0],a;return a=n==="AckPressure"?"ack_pressure":"queue_age",{event:"commander_push.pressure_shed",branch:a,shedCount:e.pressureShedCount.contents,ageMs:t,budgetMs:e.maxLivePressureAgeMs,threadKey:oT(r),streamKind:i[0],itemKey:i[1],turnId:i[2]}}function jQ(e,n,t,r,o,i){let a=i(),s=nqe(e,n,t,r,o);try{e.onPressureShed(s)}catch{let u=s.branch,c=s.shedCount,l=s.ageMs,f=s.budgetMs,p=s.threadKey,h=s.streamKind,y=s.itemKey,m=s.turnId,_={event:"commander_push.pressure_shed_fallback",branch:u,shedCount:c,ageMs:l,budgetMs:f,threadKey:p,streamKind:h,itemKey:y,turnId:m};try{e.onPressureShedFallback(_)}catch{}}return a}function qQ(e){let n=e.now(),t=n-e.maxLivePressureAgeMs,r=$Q(e,n),o=[];e.live.activeThreads.forEach(i=>{let a=e.live.pendingByThread.get(i);if(a===void 0)return;let s=a.filter(u=>{let c=u.enqueuedAtMs<=t;if(!r&&!c)return!0;let l=r?"AckPressure":"QueueAge",f;return f=l==="AckPressure"?FQ(e,n):n-u.enqueuedAtMs,jQ(e,l,f,u.threadKey,u.streamIdentity,()=>xh(u.supersede,p=>p())),!1});s.length!==0?(e.live.pendingByThread.set(i,s),o.push(i)):e.live.pendingByThread.delete(i)}),e.live.activeThreads.splice(0,e.live.activeThreads.length,...o)}function NQ(e){let n=e.activeThreads.shift();if(n===void 0)return{TAG:"Ok",_0:void 0};let t=e.pendingByThread.get(n);if(t===void 0)return{TAG:"Error",_0:"Commander push admission lost an active thread"};let r=t.shift();return r!==void 0?(t.length!==0?e.activeThreads.push(n):e.pendingByThread.delete(n),{TAG:"Ok",_0:r}):(e.pendingByThread.delete(n),{TAG:"Error",_0:"Commander push admission thread queue was empty"})}function tqe(e){for(;;){let n=NQ(e.live);if(n.TAG!=="Ok")return{TAG:"Error",_0:n._0};let t=n._0;if(t===void 0)return{TAG:"Ok",_0:void 0};let r=e.now(),o=$Q(e,r),i=t.enqueuedAtMs+e.maxLivePressureAgeMs<=r;if(!o&&!i)return{TAG:"Ok",_0:t};let a=o?"AckPressure":"QueueAge",s;s=a==="AckPressure"?FQ(e,r):r-t.enqueuedAtMs,jQ(e,a,s,t.threadKey,t.streamIdentity,()=>xh(t.supersede,d=>d()))}}function rqe(e){for(;;){let n=e.priority.activeThreads.length!==0,t=e.live.activeThreads.length!==0,r=e.maxInFlight===1?!0:e.liveInFlight.contents<(e.maxInFlight-1|0),o=t&&r,i=e.consecutivePriority.contents<8,a=0;if(n)a=o&&!i?1:2;else if(o)a=1;else return e.consecutivePriority.contents=0,{TAG:"Ok",_0:void 0};switch(a){case 1:e.consecutivePriority.contents=0;let s=tqe(e);if(s.TAG!=="Ok")return{TAG:"Error",_0:s._0};let d=s._0;if(d!==void 0)return{TAG:"Ok",_0:d};continue;case 2:return e.consecutivePriority.contents=e.consecutivePriority.contents+1|0,NQ(e.priority)}}}function oqe(e,n,t,r,o,i){let a=n!==void 0?n:2e3,s=t!==void 0?t:w=>performance.now(),d=r!==void 0?r:(w,v)=>{let S=setTimeout(v,w);return S.unref(),()=>{clearTimeout(S)}},u=o!==void 0?o:w=>{console.warn("commander_push.pressure_shed",w)},c=i!==void 0?i:w=>{console.warn("commander_push.pressure_shed_fallback",w)},l=e>0,f=a>0&&isFinite(a)&&Number.isSafeInteger(a);if(!l)return{TAG:"Error",_0:"Commander push admission maxInFlight must be a positive integer"};if(!f)return{TAG:"Error",_0:"Commander push admission maxLivePressureAgeMs must be positive and finite"};let p={maxInFlight:e,priority:{pendingByThread:new Map,activeThreads:[]},live:{pendingByThread:new Map,activeThreads:[]},inFlight:{contents:0},liveInFlight:{contents:0},consecutivePriority:{contents:0},pumpScheduled:{contents:!1},schedulePump:()=>{},armPressureCheck:w=>{},recomputePressureCheck:()=>{},maxLivePressureAgeMs:a,now:s,schedulePressureCheck:d,activeAckStartedAtMs:[],cancelPressureCheck:{contents:void 0},pressureCheckDeadlineMs:{contents:void 0},onPressureShed:u,onPressureShedFallback:c,pressureShedCount:{contents:0}},h=w=>{let v=p.pressureCheckDeadlineMs.contents;if(v!==void 0){if(v<=w)return;xh(p.cancelPressureCheck.contents,A=>A()),p.pressureCheckDeadlineMs.contents=w;let C=p.schedulePressureCheck(Math.max(1,w-p.now()),()=>{p.cancelPressureCheck.contents=void 0,p.pressureCheckDeadlineMs.contents=void 0,qQ(p),p.schedulePump(),p.recomputePressureCheck()});p.cancelPressureCheck.contents=C;return}xh(p.cancelPressureCheck.contents,C=>C()),p.pressureCheckDeadlineMs.contents=w;let S=p.schedulePressureCheck(Math.max(1,w-p.now()),()=>{p.cancelPressureCheck.contents=void 0,p.pressureCheckDeadlineMs.contents=void 0,qQ(p),p.schedulePump(),p.recomputePressureCheck()});p.cancelPressureCheck.contents=S},y=()=>{let w={contents:void 0};p.live.pendingByThread.forEach(S=>{S.forEach(C=>{let A=C.enqueuedAtMs+p.maxLivePressureAgeMs,T=w.contents;w.contents=T!==void 0?Math.min(T,A):A})});let v=w.contents;if(v!==void 0)return h(rr(p.activeAckStartedAtMs,v,(S,C)=>Math.min(S,C+p.maxLivePressureAgeMs)))},m=()=>{for(;;){if(p.pumpScheduled.contents=!1,p.inFlight.contents>=p.maxInFlight)return;let w=rqe(p);if(w.TAG==="Ok"){let S=w._0;if(S===void 0)return;let C=p.now();p.inFlight.contents=p.inFlight.contents+1|0,p.activeAckStartedAtMs.push(C),p.live.activeThreads.length!==0&&h(C+p.maxLivePressureAgeMs),S.replaceableLive&&(p.liveInFlight.contents=p.liveInFlight.contents+1|0),Bu(S.task(),A=>{let T=Rd(A),M=T!==void 0?Dn(Bs(bt(T)),"unknown admission task error"):"unknown admission task error";return S.fail(v2(void 0,M)),Promise.resolve()}).finally(()=>{p.inFlight.contents=p.inFlight.contents-1|0;let A=p.activeAckStartedAtMs.indexOf(C);A!==-1&&p.activeAckStartedAtMs.splice(A,1),S.replaceableLive&&(p.liveInFlight.contents=p.liveInFlight.contents-1|0),p.schedulePump()});continue}let v=w._0;p.priority.pendingByThread.forEach(S=>{S.forEach(C=>C.fail(v2(void 0,v)))}),p.live.pendingByThread.forEach(S=>{S.forEach(C=>C.fail(v2(void 0,v)))}),p.priority.pendingByThread.clear(),p.live.pendingByThread.clear(),p.priority.activeThreads.splice(0,p.priority.activeThreads.length),p.live.activeThreads.splice(0,p.live.activeThreads.length);return}},_=()=>{if(!p.pumpScheduled.contents){p.pumpScheduled.contents=!0,queueMicrotask(m);return}};return p.schedulePump=_,p.armPressureCheck=h,p.recomputePressureCheck=y,{TAG:"Ok",_0:p}}function iqe(e){let n=$t(e[OQ],r=>r.trim());if(n===void 0)return{TAG:"Ok",_0:8};if(n==="")return{TAG:"Ok",_0:8};let t=Number(n);return Number.isSafeInteger(t)&&t>=2?{TAG:"Ok",_0:t|0}:{TAG:"Error",_0:OQ+" must be an integer of at least 2"}}function aqe(e){let n=$t(e[DQ],r=>r.trim());if(n===void 0)return{TAG:"Ok",_0:2e3};if(n==="")return{TAG:"Ok",_0:2e3};let t=Number(n);return Number.isSafeInteger(t)&&t>0?{TAG:"Ok",_0:t|0}:{TAG:"Error",_0:DQ+" must be a positive integer"}}var OQ,DQ,eqe,mRn,LQ=B(()=>{kr();Eu();vt();ti();ig();ir();OQ="LINZUMI_COMMANDER_PUSH_MAX_INFLIGHT",DQ="LINZUMI_COMMANDER_PUSH_PRESSURE_BUDGET_MS";eqe=new RegExp("[^\\x20-\\x7E]","g");mRn=xi(iqe(process.env),e=>xi(aqe(process.env),n=>oqe(e,n,void 0,void 0,void 0,void 0)))});var zQ=B(()=>{});var hRn,GQ=B(()=>{Uu();Kh();hRn=sV(e=>({joinRef:e.item(0,Wb(st)),ref:e.item(1,Wb(st)),topic:e.item(2,st),event:e.item(3,st),payload:e.item(4,Jh)}))});var SRn,UQ,kRn,CRn,TRn,PRn,iT=B(()=>{Ql();kr();Eu();Wr();vt();ti();ig();Dr();ir();Cr();zQ();yo();yD();GQ();hD();SRn=new RegExp("/$"),UQ="[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]",kRn=new RegExp(UQ),CRn=new RegExp(UQ,"g"),TRn=new RegExp("^npm install -g @linzumi\\/cli(@[0-9A-Za-z^~.-]{1,32})?$"),PRn=new RegExp("^\\d+\\.\\d+\\.\\d+(?:[-+][0-9A-Za-z.-]{1,32})?$")});var BQ=B(()=>{kr();vt()});var pqe,ARn,IRn,mqe,hqe,RRn,ERn,JQ=B(()=>{Uu();vt();Kh();pqe=Ma(e=>({decision:e.m(st),label:e.m(st),description:e.m(hr(st))})),ARn=Ma(e=>({decision:e.m(st)})),IRn=Ma(e=>({status:e.m(st),response:e.m(Jh)})),mqe=Pr("terminal"),hqe=ns([Pr("interrupted"),Pr("processed"),Pr("failed"),Pr("ignored"),Pr("stop_failed")]),RRn=Ma(e=>({disposition:e.m(mqe),thread_id:e.m(st),seq:e.m(es),status:e.m(hqe),reason:e.m(rV(st))})),ERn=Ma(e=>({approval_request_id:e.m(st),approval_kind:e.m(st),approval_summary:e.m(st),approval_reason:e.m(hr(st)),approval_port:e.m(hr(es)),approval_pid:e.m(hr(es)),approval_command:e.m(hr(st)),approval_cwd:e.m(hr(st)),approval_process_name:e.m(hr(st)),approval_process_icon_key:e.m(hr(st)),approval_process_icon_path:e.m(hr(st)),approval_choices:e.m(hr(Qk(pqe))),approval_allowed_actor_slug:e.m(hr(st)),approval_allowed_actor_user_id:e.m(hr(es))}))});function _qe(e){if(typeof e!="object"||e===null||Array.isArray(e))return{TAG:"Error",_0:"fused terminal acknowledgement envelope was not an object"};let n=e.status,t=e.response;if(n===void 0)return{TAG:"Error",_0:"fused terminal acknowledgement omitted status"};if(typeof n!="string")return{TAG:"Error",_0:"fused terminal acknowledgement status was not a string"};if(n==="ok"&&typeof t=="object"&&t!==null&&!Array.isArray(t)){let r=t.terminal_attempt;return r!==void 0?typeof r=="object"&&r!==null&&!Array.isArray(r)?{TAG:"Ok",_0:r}:{TAG:"Error",_0:"fused terminal acknowledgement was not an object"}:{TAG:"Error",_0:"fused terminal acknowledgement omitted terminal_attempt"}}return{TAG:"Error",_0:"fused terminal acknowledgement status was not ok: "+n}}function bqe(e,n,t){let r=_qe(t);if(r.TAG!=="Ok")return{TAG:"Error",_0:r._0};let o=r._0,i=o.frame;if(i===void 0)return{TAG:"Error",_0:"fused terminal acknowledgement omitted frame"};if(typeof i!="object"||i===null||Array.isArray(i))return{TAG:"Error",_0:"fused terminal frame acknowledgement was not an object"};let a=i.accepted;if(a===void 0)return{TAG:"Error",_0:"fused terminal frame omitted accepted disposition"};if(typeof a!="boolean")return{TAG:"Error",_0:"fused terminal frame accepted disposition was not boolean"};if(a){let s=o.message_state;if(s===void 0)return{TAG:"Error",_0:"fused terminal acknowledgement omitted message_state"};if(typeof s!="object"||s===null||Array.isArray(s))return{TAG:"Error",_0:"fused terminal message_state was not an object"};let d=s.disposition;if(d===void 0)return{TAG:"Error",_0:"fused terminal message_state omitted disposition"};if(typeof d!="string")return{TAG:"Error",_0:"fused terminal message_state disposition was not a string"};switch(d){case"applied":return{TAG:"Ok",_0:"AppliedTerminalMessageState"};case"terminal":let u=s.thread_id,c=s.seq,l=s.status,f=s.reason;if(u===void 0)return{TAG:"Error",_0:"fused terminal message_state consensus omitted required fields"};if(typeof u!="string")return{TAG:"Error",_0:"fused terminal message_state consensus omitted required fields"};if(c===void 0)return{TAG:"Error",_0:"fused terminal message_state consensus omitted required fields"};if(typeof c!="number")return{TAG:"Error",_0:"fused terminal message_state consensus omitted required fields"};if(l===void 0)return{TAG:"Error",_0:"fused terminal message_state consensus omitted required fields"};if(typeof l!="string")return{TAG:"Error",_0:"fused terminal message_state consensus omitted required fields"};if(f===void 0)return{TAG:"Error",_0:"fused terminal message_state consensus omitted required fields"};let p=u===e,h=c===n;if(!p)return{TAG:"Error",_0:"fused terminal message_state consensus identity mismatch"};if(!h)return{TAG:"Error",_0:"fused terminal message_state consensus identity mismatch"};switch(l){case"failed":case"ignored":case"interrupted":case"processed":case"stop_failed":break;default:return{TAG:"Error",_0:"fused terminal message_state consensus carried invalid status or reason"}}return f===null?{TAG:"Ok",_0:{TAG:"StoredTerminalMessageState",_0:{threadId:u,sourceSeq:c,status:l,reason:void 0}}}:typeof f=="string"?{TAG:"Ok",_0:{TAG:"StoredTerminalMessageState",_0:{threadId:u,sourceSeq:c,status:l,reason:f}}}:{TAG:"Error",_0:"fused terminal message_state consensus carried invalid status or reason"};default:return{TAG:"Error",_0:"unknown fused terminal message_state disposition: "+d}}}else{let s=YW(i.reason),d=XW(s);switch(s){case"FrameIndexReuse":case"UnknownRejection":return{TAG:"Ok",_0:{TAG:"RejectedTerminalFrame",_0:{TAG:"RetryableTerminalFrameRejection",_0:d}}};default:return{TAG:"Ok",_0:{TAG:"RejectedTerminalFrame",_0:{TAG:"GenerationTerminalFrameRejection",_0:d}}}}}}function KQ(e,n,t){let r;try{r=JSON.parse(t)}catch{r=void 0}if(r===void 0)return{kind:"retry",message:"fused terminal reply was not valid JSON"};let o=bqe(e,n,r);if(o.TAG!=="Ok")return{kind:"retry",message:o._0};let i=o._0;if(typeof i!="object"||i.TAG==="StoredTerminalMessageState")return"accepted";let a=i._0;return a.TAG==="RetryableTerminalFrameRejection"?{kind:"retry",message:a._0}:"generation_rejected"}var sEn,w2=B(()=>{kr();Eu();Wr();vt();ti();ig();nT();eq();Dr();ir();tT();Cr();Rh();yo();b2();MQ();LQ();_v();iT();fg();_2();BQ();$u();JQ();sEn=new RegExp("^item-\\d+$")});var pg,S2=B(()=>{w2();pg=KQ});function as(e){return typeof e=="string"&&xqe.has(e)}function k2(e){return wqe.has(e)}function Sqe(e){return VQ[e]}function mg(e){if(e===void 0)return{};let n=Sqe(e);return k2(n)?{fate:n,retryable:!0}:{fate:n}}function C2(e){return e===429?"rate_limited":e===402||e===408||e===425||e>=500&&e<=599?"transient_upstream":"deterministic"}var vqe,xqe,wqe,VQ,uEn,hg=B(()=>{"use strict";vqe=["deterministic","transient_upstream","transient_local","rate_limited","needs_approval","needs_decision","route_outage"],xqe=new Set(vqe);wqe=new Set(["transient_upstream","transient_local","route_outage"]);VQ={runner_updating:"transient_local",stillborn_worker:"transient_local",infra_turn_kill:"transient_local",resume_transient:"transient_local",start_stage_transient:"transient_local",resume_torn_tail:"transient_local",resurrection_interrupted:"transient_local",dead_letter_exhausted:"transient_local",dead_letter_withheld:"needs_decision",dead_letter_permanent:"deterministic",resume_cwd_not_allowed:"deterministic",cwd_stillbirth_circuit_open:"deterministic",engine_unavailable:"deterministic",provider_binding_rejected:"deterministic",project_untrusted:"deterministic",attachment_download_failed:"transient_local",claude_input_queue_closed:"transient_local",claude_dispatch_wedged:"transient_local"};uEn=Object.keys(VQ)});import{readFile as kqe}from"node:fs/promises";async function HQ(e){let n;try{n=await kqe(e,"utf8")}catch(t){return{type:"error",error:{type:"file_read_failed",path:e,message:t instanceof Error?t.message:String(t)}}}return Iqe(e,n)}function Iqe(e,n){let t=[],r=n.split(/\r?\n/u);for(let o=0;o<r.length;o+=1){let i=r[o],a=o+1;if(i===void 0||i.trim()==="")continue;let s;try{s=JSON.parse(i)}catch(c){return{type:"error",error:{type:"invalid_json",path:e,line:a,message:c instanceof Error?c.message:String(c)}}}let d=Rqe(e,a,s);if(d.type==="error")return d;let u=T2(d.record);if(u!==void 0)return{type:"error",error:{type:"credential_not_redacted",path:e,line:a,keyPath:u}};t.push(d.record)}return{type:"ok",fixture:{path:e,records:t}}}function ZQ(e){return JSON.stringify(e)}function Rqe(e,n,t){let r=O(t);if(r===void 0)return gg(e,n,"record must be a JSON object");let o=ie(r.schemaVersion);if(o!==1)return gg(e,n,"schemaVersion must be 1");let i=b(r.provider);if(i===void 0||!Cqe.has(i))return gg(e,n,"provider is not supported");let a=b(r.captureKind);if(a===void 0||!Tqe.has(a))return gg(e,n,"captureKind is not supported");let s=ie(r.ordinal);if(s===void 0||s<0)return gg(e,n,"ordinal must be a non-negative integer");let d=ie(r.offsetMs);if(d===void 0||d<0)return gg(e,n,"offsetMs must be a non-negative integer");let u=b(r.rawText),c=O(r.captureMetadata),l=Array.isArray(r.transforms)?r.transforms.filter(se):void 0;return{type:"ok",record:{schemaVersion:o,provider:i,captureKind:a,ordinal:s,offsetMs:d,...u===void 0?{}:{rawText:u},...r.rawValue===void 0?{}:{rawValue:r.rawValue},...c===void 0?{}:{captureMetadata:c},...l===void 0?{}:{transforms:l}}}}function gg(e,n,t){return{type:"error",error:{type:"invalid_record",path:e,line:n,message:t}}}function T2(e,n="$"){if(Array.isArray(e)){for(let t=0;t<e.length;t+=1){let r=T2(e[t]??null,`${n}[${t}]`);if(r!==void 0)return r}return}if(se(e))for(let[t,r]of Object.entries(e)){let o=`${n}.${t}`;if(Pqe.test(t)&&!P2(r))return o;if(r!==void 0){let i=T2(r,o);if(i!==void 0)return i}}}function P2(e){return e==null?!0:typeof e=="string"?Aqe.has(e):Array.isArray(e)?e.every(n=>P2(n)):se(e)?Object.values(e).every(n=>P2(n)):!1}var Cqe,Tqe,Pqe,Aqe,A2=B(()=>{"use strict";qt();Zt();Cqe=new Set(["codex-app-server","claude-code-sdk"]),Tqe=new Set(["incoming","outgoing","notification","request","response","sdk-message","commander-push","session-marker"]),Pqe=/(^|[_-])(token|secret|api[_-]?key|authorization|cookie|private[_-]?key|login[_-]?url)([_-]|$)/iu,Aqe=new Set(["[REDACTED]","<REDACTED>","$REDACTED"])});import{mkdirSync as Eqe,appendFileSync as Mqe}from"node:fs";import{dirname as Oqe}from"node:path";function I2(){return QQ()!==void 0}function sp(e){let n=QQ();if(n===void 0)return;let t=qqe(n),r=$qe(e),o={schemaVersion:1,provider:e.provider,captureKind:e.captureKind,ordinal:t.nextOrdinal,offsetMs:Math.max(0,Date.now()-t.startedAtMs),...r.rawText===void 0?{}:{rawText:r.rawText},...r.rawValue===void 0?{}:{rawValue:r.rawValue},...e.captureMetadata===void 0?{}:{captureMetadata:vv(e.captureMetadata)},...r.transforms.length===0?e.transforms===void 0?{}:{transforms:e.transforms}:{transforms:[...e.transforms??[],...r.transforms]}};t.nextOrdinal+=1,Mqe(n,`${ZQ(o)}
|
|
610
|
+
`}:{TAG:"Error",_0:"journal counters could not be serialized"}}catch(re){let _e=Tn(re);Z={TAG:"Error",_0:tr(_e).message}}if(Z.TAG!=="Ok")return Z;let N=Z._0,W=l.contents;l.contents=[];let ee={};K.kv.forEach((re,_e)=>{ee[_e]=re});let ne=[N,lg(Object.fromEntries([["t","context"],["kv",ee]]))].concat(K.pendingEntries.map(re=>f2("pending",re))),ye=K.failedTerminalEntries;ye.length!==0&&(ye.forEach(re=>{ne.push(f2("pending",re)),ne.push(pv("fail",re.entrySeq))}),ne.push(N));let L=u.contents+".tmp",ce=await EW(L,ne.join("")),pe;return pe=ce.TAG==="Ok"?await lD(L,u.contents):{TAG:"Error",_0:ce._0},pe.TAG==="Ok"?(T.contents=!1,_.contents=K.pendingEntries.length===0,t("outbox_journal_compacted",Object.fromEntries([["path",u.contents],["pendingEntries",K.pendingEntries.length]])),{TAG:"Ok",_0:void 0}):(l.contents=W.concat(l.contents),h.contents=a,y.contents=1048576,{TAG:"Error",_0:pe._0.message})},$=async()=>{let K;if(l.contents.length!==0){let N=l.contents.join("");l.contents=[];let W=await d(u.contents,N);W.TAG==="Ok"?K={TAG:"Ok",_0:void 0}:(l.contents=[N].concat(l.contents),K={TAG:"Error",_0:W._0.message})}else K={TAG:"Ok",_0:void 0};if(K.TAG!=="Ok")return{TAG:"Error",_0:K._0};let Z=h.contents>0&&!_.contents&&!m.contents?n().pendingEntries.length===0:!1;return T.contents||h.contents>=a||y.contents>=1048576||Z?await z():{TAG:"Ok",_0:void 0}},J=()=>{let K=p.contents;if(K!==void 0)return K;A.contents=A.contents+1|0;let Z=f.contents.then(()=>(p.contents=void 0,$().then(N=>(N.TAG==="Ok"?P():I(N._0),A.contents=A.contents-1|0,N))));return p.contents=Z,f.contents=Z.then(N=>{}),Z},Q=(K,Z)=>w.contents?(M.contents=!0,t("outbox_journal_append_after_close",Object.fromEntries([["path",u.contents]])),Promise.resolve({TAG:"Error",_0:"outbox journal is closed"})):(l.contents.push(K),y.contents=y.contents+Buffer.byteLength(K,"utf8")|0,Z&&(h.contents=h.contents+1|0),J());return{durability:()=>M.contents?"Lost":A.contents>0||l.contents.length!==0||T.contents?"Pending":"Durable",writeInProgress:()=>!M.contents&&!T.contents?A.contents>0?!0:l.contents.length!==0:!1,appendEnqueue:K=>Q(f2("enqueue",K),!1),appendCoalesce:(K,Z)=>Q(lg(Object.fromEntries([["t","coalesce"],["seq",K],["data",Z]])),!1),appendAck:(K,Z)=>{Z!==void 0&&Z&&(m.contents=!0),Q(pv("ack",K),!0)},appendSkip:(K,Z)=>{Q(lg(Object.fromEntries([["t","skip"],["seq",K],["reason",Z]])),!0)},appendDrop:K=>{Q(pv("drop",K),!0)},appendFail:K=>{Q(pv("fail",K),!0)},appendExpired:K=>{Q(pv("expired",K),!0)},appendKv:(K,Z)=>{Q(lg(Object.fromEntries([["t","kv"],["key",K],["value",Z]])),!1)},settled:()=>f.contents.then(()=>{}),status:()=>({totalWriteFailures:S.contents,degraded:C.contents}),rekey:K=>{if(w.contents)return t("outbox_journal_rekey_after_close",Object.fromEntries([["path",K]]));A.contents=A.contents+1|0,f.contents=f.contents.then(async()=>{if(K!==u.contents){let Z=u.contents,N=Hl(mv.dirname(K)),W;if(W=N.TAG==="Ok"?await lD(Z,K):{TAG:"Error",_0:N._0},W.TAG==="Ok")u.contents=K,t("outbox_journal_rekeyed",Object.fromEntries([["from",Z],["to",K]]));else{let ee=W._0;Js(ee,"ENOENT")?(u.contents=K,t("outbox_journal_rekeyed",Object.fromEntries([["from",Z],["to",K]]))):(M.contents=!0,t("outbox_journal_rekey_failed",Object.fromEntries([["level","error"],["from",Z],["to",K],["error",ee.message]])))}}A.contents=A.contents-1|0})},close:async()=>{if(w.contents=!0,A.contents=A.contents+1|0,await f.contents,l.contents.length!==0||T.contents||h.contents>=a||y.contents>=1048576){let K=await $();K.TAG==="Ok"?P():I(K._0)}A.contents=A.contents-1|0}}}var cg=B(()=>{kr();Wr();vt();Cr();yo();dg();$u()});function YC(e,n,t,r,o,i){if(!e)return{kind:"unavailable",reason:"terminal journal durability unavailable"};let a=n.filter(s=>s.kind==="adt.terminal_attempt").length;return a>0?{kind:"pending",count:a}:rr(t,"clear",(s,d)=>{if(typeof s=="object"&&s.kind==="unavailable")return s;let u=r(Xl(d.entrySeq));if(u!==void 0){let l=ro(d.data),f=ro(u);return(l!==void 0&&f!==void 0?Yl(d.entrySeq,l,f):!1)?s:(ta(i,"adt.terminal_repair_receipt_mismatch",{threadKey:o,entrySeq:d.entrySeq}),{kind:"unavailable",reason:"terminal correction receipt mismatch"})}let c;return c=typeof s!="object"||s.kind!=="repair_needed"?0:s.count,{kind:"repair_needed",count:c+1|0}})}var p2=B(()=>{kr();$u()});function TDe(e,n){switch(e){case"MustReachConsensus":return{TAG:"RetryAfterExhaustion",_0:Dn(n[n.length-1|0],1e3)};case"MustAck":case"BestEffort":return"FailAfterExhaustion"}}function PDe(e,n){switch(e){case"MustReachConsensus":return!1;case"MustAck":case"BestEffort":return n}}function eT(e,n){return e+"\0"+n}function SQ(e,n){let t=Math.max(1,Math.ceil(n*e.length)|0);return Dn(e[t-1|0],0)}function ADe(e){if(e.length===0)return;let n=e.toSorted((t,r)=>t-r);return{p50Ms:SQ(n,.5),p95Ms:SQ(n,.95),maxMs:Dn(n[n.length-1|0],0),ackedInWindow:n.length}}function IDe(e){return new Promise((n,t)=>{setTimeout(()=>n(),e)})}function gv(e,n){if(n.kind!=="adt.terminal_attempt")return!1;let t=n.resolution,r=n.data;switch(t){case"MustAck":let o=r.thread_key;if(typeof o!="string")return!1;let i=r.seq;if(typeof i!="number")return!1;let a=r.turn_id;if(typeof a!="string")return!1;let s=r.status;if(typeof s!="string"||s!=="processed")return!1;let d=r.terminal_frame;if(typeof d!="object"||d===null||Array.isArray(d))return!1;let u=d.session_id;if(typeof u!="number")return!1;let c=d.lease_epoch;if(typeof c!="number")return!1;let l=d.frame_index;if(typeof l!="number")return!1;let f=d.frame_kind;if(typeof f!="string"||f!=="terminal")return!1;let p=d.assistant_phase;if(typeof p!="string"||p!=="final_answer")return!1;let h=d.source_stream_key;return typeof h!="string"?!1:typeof d.body=="string"&&o===e&&a!==""&&h!==""?[i,u,c,l].every(m=>St(m)&&m>0?m<=9007199254740991:!1):!1;case"MustReachConsensus":case"BestEffort":return!1}}function m2(e){let n=Dn(e.recoveryMode,"OrdinaryRecovery"),t=e.log,r=e.onPermanentFailure,o=e.builders,i=e.threadKey,a={contents:i},s=ue=>{throw ta(t,"outbox_journal_generation_refused",{thread_key:i,reason:ue}),new Error(ue)},d=e.journalGeneration;if(d!==void 0){let ue=cv(d),Pe=e.persistDir;ue&&Pe!==void 0||s("journal generation requires a valid session and durable directory")}let u=ue=>{let Pe=e.journalGeneration;return Pe!==void 0?lc(ue,Pe):ue},c=Dn(e.now,()=>Date.now()),l=Dn(e.retryDelaysMs,kDe.slice()),f={contents:[]},p={contents:0},h=[],y=[],m=[],_=new Map,w={contents:new Map},v={contents:0},S=[],C={contents:1},A={contents:0},T={contents:0},M={contents:0},I={contents:0},P={contents:0},z={contents:0},$={contents:0},J=[],Q={contents:0},K={contents:n==="TerminalRepairRecovery"},Z={contents:!0},N={contents:!1},W={contents:void 0},ee={contents:void 0},ne={contents:!1},ye=new Map,L=new Map,ce=(ue,Pe)=>{let be=Pe.then(en=>(ye.delete(ue),en));ye.set(ue,be)},pe=Math.max(1,Dn(e.maxInFlightPushes,1)),re={contents:0},_e={contents:0},le={contents:[]},Oe={contents:Promise.resolve()},F=()=>f.contents[p.contents],H=()=>({totalEnqueued:A.contents,totalAcked:T.contents,totalDroppedBestEffort:I.contents,totalPermanentFailures:P.contents,knownNonterminalFailures:z.contents,totalExpiredOnRecovery:$.contents,lastEntrySeq:C.contents-1}),V=e.persistDir;if(V!==void 0){let ue=ap(V,u(a.contents)),Pe=e.journalGeneration,be;if(Pe!==void 0){let yn=Dk(sg(Pe));be=yn.TAG==="Ok"?yn._0:s(yn._0)}else be=void 0;let en=e.journalGeneration,pn;if(en!==void 0){let yn=vi(ue);if(yn.TAG==="Ok")switch(yn._0){case"LstatMissing":pn=!1;break;case"LstatFile":pn=!0;break;case"LstatSymlink":case"LstatOther":pn=s("journal location is not a regular file");break}else pn=s(yn._0.message)}else pn=!1;let rn=cc(ue,(yn,Wn)=>{ne.contents=!0,t(yn,Wn)},void 0);rn.pendingEntries.forEach(yn=>{m.push(yn)});let mn=e.journalGeneration;if(mn!==void 0)if(be!==void 0){if(pn){let yn=rn.kv.get(is);if(yn!==void 0){let Wn=QC(yn);Wn.TAG==="Ok"?Jn(Wn._0,mn)&&!ne.contents||s("journal generation identity mismatch or unavailable contents"):s(Wn._0)}else s("existing generation journal lacks identity metadata")}}else s("journal generation metadata construction mismatch");else be!==void 0?s("journal generation metadata construction mismatch"):rn.kv.has(is)&&s("generation journal opened without required identity");let nt=Dn(e.journalRecoveryMaxAgeMs,CDe),Qn=c(),ft=[];rn.pendingEntries.forEach(yn=>{let Wn=!1;if(n==="TerminalRepairRecovery"&&gv(a.contents,yn)){let Fi=yn.data.terminal_repair,Lt;if(Fi!==void 0)if(typeof Fi=="object"&&Fi!==null&&!Array.isArray(Fi)){let ji=Fi.failed_entry_seq;if(typeof ji=="number"){let Xi=Fi.original_lease_epoch;if(typeof Xi=="number"){let Pd=rn.failedTerminalEntries.find(Fe=>Fe.entrySeq===ji&&!("terminal_repair"in Fe.data)?gv(a.contents,Fe):!1),zs=rn.kv.get("terminal_repair_prepared:"+ji.toString()),Y=ro(yn.data);if(Pd!==void 0&&zs!==void 0&&typeof zs=="string"&&Y!==void 0&&["thread_key","seq","turn_id","status"].every(Fe=>Jn(Pd.data[Fe],yn.data[Fe]))){let Fe=Pd.data.terminal_frame,Le=yn.data.terminal_frame,ve;ve=typeof Fe=="object"&&Fe!==null&&!Array.isArray(Fe)&&typeof Le=="object"&&Le!==null&&!Array.isArray(Le)?Jn(Fe.lease_epoch,Xi)&&["session_id","body"].every(ze=>Jn(Fe[ze],Le[ze]))&&Jf(zs,Y):!1,Lt=ve}else Lt=!1}else Lt=!1}else Lt=!1}else Lt=!1;else Lt=!0;Wn=Lt}if(PDe(yn.resolution,Qn-yn.enqueuedAtMs>nt)&&!Wn){ft.push(yn);return}let er={entry:yn,state:"EntryQueued",outcome:void 0,retryTimer:void 0};f.contents.push(er);let ho=yn.coalesceKey;if(ho!==void 0){_.set(eT(yn.kind,ho),er);return}}),w.contents=rn.kv,be!==void 0&&w.contents.set(is,be),rn.failedTerminalEntries.forEach(yn=>{y.push(yn)}),A.contents=rn.counters.totalEnqueued,T.contents=rn.counters.totalAcked,I.contents=rn.counters.totalDroppedBestEffort,P.contents=rn.counters.totalPermanentFailures,z.contents=Dn(rn.counters.knownNonterminalFailures,0),$.contents=rn.counters.totalExpiredOnRecovery+ft.length|0,C.contents=rn.counters.lastEntrySeq+1;let Mt=xQ(ue,()=>({pendingEntries:h.concat(f.contents.slice(p.contents).map(yn=>yn.entry)),failedTerminalEntries:y,kv:w.contents,counters:H()}),t,e.journalCompactionThreshold,void 0,e.journalAppendFile);if(ee.contents=Mt,be!==void 0&&!pn&&Mt.appendKv(is,be),ft.length!==0){ft.forEach(er=>Mt.appendExpired(er.entrySeq));let yn=ft.map(er=>Math.max(0,Qn-er.enqueuedAtMs)),Wn=new Set(ft.map(er=>er.kind));t("outbox_recovery_expired",Object.fromEntries([["level","warn"],["threadKey",a.contents],["expiredEntries",ft.length],["survivingEntries",f.contents.length-p.contents|0],["maxAgeMs",nt],["oldestAgeMs",rr(yn,0,(er,ho)=>Math.max(er,ho))],["newestAgeMs",rr(yn,Number.POSITIVE_INFINITY,(er,ho)=>Math.min(er,ho))],["kinds",Wn.values().toArray().map(er=>er)]]))}(f.contents.length-p.contents|0)>0&&t("outbox_recovered",Object.fromEntries([["threadKey",a.contents],["pendingEntries",f.contents.length-p.contents|0],["nextEntrySeq",C.contents]]))}let te=(ue,Pe)=>{ue===is&&s("journal generation metadata is immutable"),w.contents.set(ue,Pe);let be=ee.contents;if(be!==void 0){be.appendKv(ue,Pe),v.contents=v.contents+1|0,Bu(be.settled().then(()=>{v.contents=v.contents-1|0}),en=>(ta(t,"outbox_durable_fact_settlement_failed",{threadKey:a.contents,key:ue,reason:tr(en).message}),Promise.resolve()));return}},he=ue=>w.contents.get(ue),me={remember:te,recall:he},Se=()=>{if(p.contents=p.contents+1|0,p.contents>=64&&p.contents<<1>=f.contents.length){f.contents=f.contents.slice(p.contents),p.contents=0;return}},Ie=()=>{let ue=F(),Pe=S.length-1|0;for(;Pe>=0;){let be=S[Pe];if(be!==void 0&&(ue!==void 0?ue.entry.entrySeq>be.upToSeq:!0)){S.splice(Pe,1);let pn=be.timer;pn!==void 0&&clearTimeout(bt(pn)),be.resolve({TAG:"Ok",_0:void 0})}Pe=Pe-1|0}},xe=(ue,Pe)=>{let be=L.get(ue);if(be!==void 0){L.delete(ue),be.forEach(en=>en(Pe));return}},Je=ue=>{let Pe=ue.entry.coalesceKey;if(Pe===void 0)return;let be=eT(ue.entry.kind,Pe),en=_.get(be);if(en!==void 0&&en===ue){_.delete(be);return}},Nn=(ue,Pe)=>{let be=ue.entry;switch(Pe.TAG){case"OutcomeAck":xe(be.entrySeq,{TAG:"Ok",_0:void 0});let en=o[be.kind];if(en!==void 0){let Mt=en.onReply;if(Mt!==void 0){let yn;try{Mt(be.data,Pe._0,me),yn={TAG:"Ok",_0:void 0}}catch(Wn){let er=Tn(Wn);yn={TAG:"Error",_0:tr(er)}}yn.TAG!=="Ok"&&t("outbox_on_reply_failed",Object.fromEntries([["threadKey",a.contents],["entrySeq",be.entrySeq],["kind",be.kind],["error",yn._0.message]]))}}let pn=ee.contents;pn!==void 0&&pn.appendAck(be.entrySeq,be.resolution==="MustReachConsensus");break;case"OutcomeSkip":let rn=Pe._0;xe(be.entrySeq,{TAG:"Error",_0:"outbox entry skipped: "+rn}),t("outbox_entry_skipped",Object.fromEntries([["threadKey",a.contents],["entrySeq",be.entrySeq],["kind",be.kind],["reason",rn]]));let mn=ee.contents;mn!==void 0&&mn.appendSkip(be.entrySeq,rn);break;case"OutcomeFail":let nt=Pe._0;xe(be.entrySeq,{TAG:"Error",_0:nt});let Qn=be.resolution,ft=0;switch(Qn){case"MustAck":case"MustReachConsensus":ft=1;break;case"BestEffort":let Mt=ee.contents;Mt!==void 0&&Mt.appendDrop(be.entrySeq);break}if(ft===1){be.kind==="adt.terminal_attempt"&&y.push(be);let yn=ee.contents;yn!==void 0&&yn.appendFail(be.entrySeq);let Wn;try{r(be,nt),Wn={TAG:"Ok",_0:void 0}}catch(er){let ho=Tn(er);Wn={TAG:"Error",_0:tr(ho)}}Wn.TAG!=="Ok"&&t("outbox_permanent_failure_callback_failed",Object.fromEntries([["threadKey",a.contents],["entrySeq",be.entrySeq],["error",Wn._0.message]]))}break;case"OutcomePreserveForRestart":h.push(be),t("outbox_entry_preserved_for_restart",Object.fromEntries([["threadKey",a.contents],["entrySeq",be.entrySeq],["kind",be.kind],["reason",Pe._0]]));break}Je(ue),Se(),Ie()},Ke=()=>{let ue=!0;for(;ue;){let Pe=F();if(Pe!==void 0){let be=Pe.outcome;be!==void 0?Nn(Pe,be):ue=!1}else ue=!1}},qe=(ue,Pe)=>{let be=ue.entry;if(Pe.TAG==="OutcomeFail"){let en=Pe._0,pn=be.resolution,rn=0;switch(pn){case"MustAck":case"MustReachConsensus":rn=1;break;case"BestEffort":I.contents=I.contents+1|0,t("outbox_dropped_best_effort",Object.fromEntries([["threadKey",a.contents],["entrySeq",be.entrySeq],["kind",be.kind],["attempts",be.attempts],["error",en]]));break}rn===1&&(P.contents=P.contents+1|0,be.kind!=="adt.terminal_attempt"&&(z.contents=z.contents+1|0),t("outbox_permanent_failure",Object.fromEntries([["threadKey",a.contents],["entrySeq",be.entrySeq],["kind",be.kind],["attempts",be.attempts],["error",en]])))}ue.outcome=Pe,ue.state="EntryQueued"},dn=ue=>{let Pe=ue.retryTimer;if(Pe!==void 0){clearTimeout(bt(Pe)),ue.retryTimer=void 0;return}},Ln=ue=>{let Pe=e.supersedesQueuedEntry;if(Pe===void 0)return;let be=ue.kind,en=ue.resolution,pn=ue.data,rn={entryKind:be,resolution:en,data:pn};for(let mn=p.contents,nt=f.contents.length;mn<nt;++mn){let Qn=f.contents[mn];if(Qn!==void 0){let ft=Qn.entry;Qn.state==="EntryQueued"&&(Qn.outcome!==void 0||!Pe(rn,{entryKind:ft.kind,resolution:ft.resolution,data:ft.data})||(dn(Qn),qe(Qn,{TAG:"OutcomeSkip",_0:"superseded_by_terminal"})))}}},In=ue=>{J.length<256?J.push(ue):J[Q.contents]=ue;let Pe=Q.contents+1|0;Q.contents=Pe>=256?0:Pe},cn=()=>{if(re.contents>0)return;let ue=le.contents;le.contents=[],ue.forEach(Pe=>Pe())},ct=()=>{let ue=F();return ue===void 0||ue.state!=="EntryQueued"||ue.outcome!==void 0?!1:ue.retryTimer!==void 0},Un={contents:()=>{}},Rn=(ue,Pe)=>{dn(ue);let be=setTimeout(()=>{if(ue.retryTimer=void 0,!(N.contents||K.contents||ue.outcome!==void 0))return Un.contents()},Pe|0);be.unref(),ue.retryTimer=br(be)},Ye=(ue,Pe,be)=>{if(ue.state="EntryQueued",M.contents=M.contents+1|0,t("outbox_consensus_retry",Object.fromEntries([["threadKey",a.contents],["entrySeq",ue.entry.entrySeq],["kind",ue.entry.kind],["attempt",ue.entry.attempts],["delayMs",be],["error",Pe]])),!N.contents&&!K.contents)return Rn(ue,be)},fn=(ue,Pe)=>{let be=TDe(ue.entry.resolution,l);return typeof be!="object"?qe(ue,{TAG:"OutcomeFail",_0:Pe}):Ye(ue,Pe,be._0)},ht=async(ue,Pe,be)=>{let en=ue.entry,pn=c(),rn;try{rn=await e.push(Pe[0],Pe[1],Pe[2],be,{entryKind:en.kind,resolution:en.resolution,data:en.data})}catch(mn){let nt=Tn(mn);rn={TAG:"PushFailed",_0:{message:tr(nt).message,budgetExempt:!1}}}switch(rn.TAG){case"Acked":let mn=rn._0;be(),In(Math.max(0,c()-pn));let nt=o[en.kind],Qn;if(nt!==void 0){let Fi=nt.adjudicateReply;if(Fi!==void 0)try{Qn=Fi(en.data,mn,me)}catch(Lt){let ji=Tn(Lt);Qn={TAG:"RetryReply",_0:tr(ji).message}}else Qn="AcceptReply"}else Qn="AcceptReply";if(typeof Qn!="object")return T.contents=T.contents+1|0,qe(ue,{TAG:"OutcomeAck",_0:mn});let ft=Qn._0,Mt=l[en.attempts-1|0];return Mt!==void 0?Ye(ue,ft,Mt):fn(ue,ft);case"PushFailed":let yn=rn._0,Wn=yn.message;if(be(),ue.state="EntryQueued",Dn(yn.nonRetryable,!1))return qe(ue,{TAG:"OutcomeSkip",_0:"authenticated_terminal_attempt_superseded"});if(yn.budgetExempt)return en.attempts=en.attempts-1|0,M.contents=M.contents+1|0,t("outbox_push_connection_wait",Object.fromEntries([["threadKey",a.contents],["entrySeq",en.entrySeq],["kind",en.kind],["error",Wn]])),!N.contents&&!K.contents?Rn(ue,1e3):void 0;let ho=l[en.attempts-1|0];return ho!==void 0?(M.contents=M.contents+1|0,t("outbox_push_retry",Object.fromEntries([["threadKey",a.contents],["entrySeq",en.entrySeq],["kind",en.kind],["attempt",en.attempts],["delayMs",ho],["error",Wn]])),!N.contents&&!K.contents?Rn(ue,ho):void 0):fn(ue,Wn);case"PreserveForRestart":return be(),ue.state="EntryQueued",en.attempts=en.attempts-1|0,qe(ue,{TAG:"OutcomePreserveForRestart",_0:rn._0})}},q=async(ue,Pe)=>{let be=Pe!==void 0?Pe:!1,en=ue.entry,pn=be?Promise.resolve():Oe.contents,rn={contents:()=>{}};be||(Oe.contents=new Promise((Mt,yn)=>{rn.contents=Mt}));let mn={contents:!1},nt=()=>{if(!mn.contents)return mn.contents=!0,rn.contents()};ue.state="EntryPushing",re.contents=re.contents+1|0;let Qn=()=>{if(re.contents=re.contents-1|0,be){_e.contents=_e.contents-1|0;return}};if(await pn,N.contents||K.contents||ue.outcome!==void 0)return ue.state="EntryQueued",nt(),Qn();let ft=o[en.kind];if(ft!==void 0){let Mt;try{Mt=ft.build(en.data,me)}catch(yn){let Wn=Tn(yn);Mt={TAG:"BuildFailed",_0:tr(Wn).message}}switch(Mt.TAG){case"BuildPush":return en.attempts=en.attempts+1|0,await ht(ue,[Mt.event,Mt.payload,Mt.timeoutMs],nt),Qn();case"BuildSkip":let yn=Mt._0;switch(nt(),en.resolution){case"MustReachConsensus":fn(ue,"must_reach_consensus builder skipped without consensus: "+yn);break;case"MustAck":case"BestEffort":qe(ue,{TAG:"OutcomeSkip",_0:yn});break}return Qn();case"BuildFailed":return nt(),fn(ue,Mt._0),Qn()}}else return nt(),fn(ue,"no outbox builder registered for kind "+en.kind),Qn()},X=()=>{let ue=e.isPriorityEntry;if(ue===void 0)return;let Pe,be=!1,en=!1;for(let pn=p.contents,rn=f.contents.length;pn<rn;++pn){let mn=Pe,nt=en,Qn=f.contents[pn];if(mn===void 0&&!nt&&Qn!==void 0){let ft=Qn.entry;if(Qn.outcome===void 0)if(ue({entryKind:ft.kind,resolution:ft.resolution,data:ft.data})){let Wn=Qn.state,er=Qn.retryTimer;Wn==="EntryQueued"&&er===void 0&&be?Pe=Qn:en=!0}else{let Wn=Qn.state,er=Qn.retryTimer;(Wn!=="EntryQueued"||er!==void 0)&&(be=!0)}}}return Pe},ae=()=>{if(_e.contents!==0)return;let Pe=X();if(Pe!==void 0){_e.contents=_e.contents+1|0,Bu(q(Pe,!0).then(()=>Un.contents()),be=>(t("outbox_priority_overflow_error",Object.fromEntries([["threadKey",a.contents]])),Un.contents(),Promise.resolve()));return}},j=()=>{if(Ke(),N.contents||K.contents)return cn();if(ct())return ae(),cn();let ue=p.contents;for(;ue<f.contents.length&&re.contents<pe;){let Pe=f.contents[ue];Pe!==void 0&&Pe.state==="EntryQueued"&&Pe.outcome===void 0&&(Pe.retryTimer!==void 0||Bu(q(Pe,void 0).then(()=>j()),rn=>(t("outbox_drain_loop_error",Object.fromEntries([["threadKey",a.contents]])),j(),Promise.resolve()))),ue=ue+1|0}re.contents>=pe&&ae(),cn()};Un.contents=j;let de=()=>{if(K.contents||N.contents)return;if(F()!==void 0){Promise.resolve().then(()=>{if(!N.contents&&!K.contents)return j()});return}},ge=ue=>{let Pe=C.contents-1,be=F();return(be!==void 0?be.entry.entrySeq>Pe:!0)?Promise.resolve({TAG:"Ok",_0:void 0}):new Promise((pn,rn)=>{let mn={upToSeq:Pe,resolve:pn,timer:void 0};ue!==void 0&&(mn.timer=br(setTimeout(()=>{let nt=S.indexOf(mn);nt===-1||S.splice(nt,1),pn({TAG:"Error",_0:"outbox flush for "+a.contents+" timed out after "+ue.toString()+"ms with "+(f.contents.length-p.contents|0).toString()+" entries pending"})},ue|0))),S.push(mn)})},Te=async ue=>{Z.contents=!1;let Pe=await ge(ue);Pe.TAG!=="Ok"&&t("outbox_close_flush_timeout",Object.fromEntries([["threadKey",a.contents],["depth",f.contents.length-p.contents|0],["error",Pe._0]])),N.contents=!0;let be=p.contents;for(;be<f.contents.length;){let rn=f.contents[be];rn!==void 0&&dn(rn),be=be+1|0}re.contents>0&&await Promise.race([new Promise((rn,mn)=>{le.contents.push(()=>rn())}),IDe(1e3)]);let en=S.slice();S.splice(0,S.length),en.forEach(rn=>{let mn=rn.timer;mn!==void 0&&clearTimeout(bt(mn)),rn.resolve({TAG:"Error",_0:"outbox for "+a.contents+" closed"})}),L.forEach((rn,mn)=>{rn.forEach(nt=>nt({TAG:"Error",_0:"outbox entry "+mn.toString()+" for "+a.contents+" closed before acknowledgement"}))}),L.clear();let pn=ee.contents;if(pn!==void 0)return await pn.close()},Ae=(ue,Pe,be)=>{if(ue===void 0)return be;let en=ue.coalesce;if(en===void 0)return be;let pn;try{pn={TAG:"Ok",_0:en(Pe.data,be)}}catch(rn){let mn=Tn(rn);pn={TAG:"Error",_0:tr(mn)}}return pn.TAG==="Ok"?pn._0:(t("outbox_coalesce_failed",Object.fromEntries([["threadKey",a.contents],["entrySeq",Pe.entrySeq],["kind",Pe.kind],["error",pn._0.message]])),be)},Aa={failedTerminalEntries:()=>y.slice(),terminalPublicationDebt:()=>{let ue=ee.contents,Pe=ue!==void 0?ue.durability()==="Durable"&&!ne.contents&&v.contents===0:!1;return YC(Pe,h.concat(f.contents.slice(p.contents).map(be=>be.entry)),y,he,a.contents,t)},restartWriteInProgress:()=>{let ue=ee.contents;return ue!==void 0&&!ne.contents?ue.writeInProgress():!1},pendingTerminalEntries:()=>h.concat(f.contents.slice(p.contents).map(ue=>ue.entry)).filter(ue=>ue.kind==="adt.terminal_attempt"),retainPendingTerminalForRepair:async()=>{let ue=mn=>(ta(t,"outbox_cold_publication_retention_refused",{thread_key:a.contents,reason:mn}),{TAG:"Error",_0:mn}),Pe=f.contents.slice(p.contents),be=Pe.filter(mn=>mn.entry.kind==="adt.terminal_attempt"?!("terminal_repair"in mn.entry.data):!1);if(!(K.contents&&!N.contents&&re.contents===0&&h.length===0&&Pe.every(mn=>mn.state==="EntryQueued"&&Md(mn.outcome)?Md(mn.retryTimer):!1)))return ue("cold publication retention requires paused, live, no-inflight ownership");if(be.length===0)return Pe.every(mn=>mn.entry.kind==="adt.terminal_attempt")?{TAG:"Ok",_0:void 0}:ue("mixed ordinary pending publication work");if(!(Pe.length===be.length&&be.every(mn=>m.some(nt=>nt===mn.entry)?gv(a.contents,mn.entry):!1)))return ue("mixed, malformed or non-recovered pending publication work");let pn=ee.contents;if(pn===void 0)return ue("cold publication journal is unavailable");switch(pn.durability()){case"Durable":switch(be.forEach(nt=>{pn.appendFail(nt.entry.entrySeq),y.push(nt.entry),Je(nt)}),p.contents=f.contents.length,be.forEach(nt=>ta(t,"outbox_cold_publication_retained_for_repair",{thread_key:a.contents,entry_seq:nt.entry.entrySeq})),await pn.settled(),pn.durability()){case"Durable":return{TAG:"Ok",_0:void 0};case"Pending":case"Lost":return ue("cold publication retention did not become durable")}case"Pending":case"Lost":return ue("cold publication journal is not durable")}},rememberDurableFact:te,recallDurableFact:he,enqueue:ue=>{if(!Z.contents)return{TAG:"Error",_0:"outbox for "+a.contents+" is closed"};A.contents=A.contents+1|0,Ln(ue);let Pe=ue.coalesceKey,be;if(Pe!==void 0){let Qn=eT(ue.kind,Pe),ft=_.get(Qn);if(ft!==void 0)if(ft.state==="EntryQueued")if(ft.outcome!==void 0)be=void 0;else{ft.entry.data=Ae(o[ue.kind],ft.entry,ue.data);let Wn=ee.contents;Wn!==void 0?ce(ft.entry.entrySeq,Wn.appendCoalesce(ft.entry.entrySeq,ft.entry.data)):ce(ft.entry.entrySeq,Promise.resolve({TAG:"Error",_0:"outbox journal is unavailable"})),be=ft.entry.entrySeq}else be=void 0;else be=void 0}else be=void 0;if(be!==void 0)return{TAG:"Ok",_0:be};let en=C.contents;C.contents=C.contents+1;let pn={entrySeq:en,kind:ue.kind,data:ue.data,coalesceKey:ue.coalesceKey,resolution:ue.resolution,attempts:0,enqueuedAtMs:c()},rn={entry:pn,state:"EntryQueued",outcome:void 0,retryTimer:void 0};f.contents.push(rn);let mn=ue.coalesceKey;mn!==void 0&&_.set(eT(ue.kind,mn),rn);let nt=ee.contents;return nt!==void 0?ce(en,nt.appendEnqueue(pn)):ce(en,Promise.resolve({TAG:"Error",_0:"outbox journal is unavailable"})),de(),{TAG:"Ok",_0:en}},awaitEnqueuePersistence:ue=>{let Pe=ye.get(ue);return Pe!==void 0?Pe:Promise.resolve({TAG:"Error",_0:"outbox enqueue "+ue.toString()+" has no pending persistence acknowledgement"})},awaitEntryAcknowledgement:ue=>new Promise((Pe,be)=>{let en=L.get(ue);en!==void 0?en.push(Pe):L.set(ue,[Pe])}),flush:ge,pause:()=>{K.contents=!0},resume:()=>{if(!K.contents)return;K.contents=!1;let ue=p.contents;for(;ue<f.contents.length;){let Pe=f.contents[ue];Pe!==void 0&&(Pe.entry.attempts=0,dn(Pe)),ue=ue+1|0}de()},metrics:()=>{let ue=F(),Pe=$t(ee.contents,be=>be.status());return{depth:f.contents.length-p.contents|0,oldestEntryAgeMs:$t(ue,be=>Math.max(0,c()-be.entry.enqueuedAtMs)),totalEnqueued:A.contents,totalAcked:T.contents,totalRetried:M.contents,totalDroppedBestEffort:I.contents,totalPermanentFailures:P.contents,totalExpiredOnRecovery:$.contents,totalJournalWriteFailures:Dn($t(Pe,be=>be.totalWriteFailures),0),journalDegraded:Dn($t(Pe,be=>be.degraded),!1),paused:K.contents,pushLatency:ADe(J)}},close:ue=>{let Pe=W.contents;if(Pe!==void 0)return Pe;let be=Te(Dn(ue,3e4));return W.contents=be,be},journalSettled:()=>{let ue=ee.contents;return ue!==void 0?ue.settled():Promise.resolve()},rekeyJournal:ue=>{if(ue===a.contents)return;a.contents=ue;let Pe=e.persistDir,be=ee.contents;if(Pe!==void 0&&be!==void 0)return be.rekey(ap(Pe,u(ue)))}};return de(),Aa}var kDe,CDe,nT=B(()=>{kr();Wr();vt();ig();Dr();ir();Cr();yo();cg();dg();$u();p2();kDe=[500,1e3,2500,5e3,1e4,3e4],CDe=1440*60*1e3});var RDe,OAn,tT=B(()=>{Uu();RDe=["deterministic","transient_upstream","transient_local","rate_limited","needs_approval","needs_decision","route_outage"],OAn=oV(RDe)});var kQ=B(()=>{});var GAn,CQ=B(()=>{kr();vt();ti();Dr();ir();kQ();GAn=Object.fromEntries([["granular",Object.fromEntries([["sandbox_approval",!1],["rules",!1],["skill_approval",!1],["request_permissions",!1],["mcp_elicitations",!0]])]])});var fg=B(()=>{vt();tT();cg()});var VAn,HAn,ZAn,_v=B(()=>{kr();vt();Dr();Cr();CQ();fg();VAn=new RegExp("^https?:\\/\\/","i"),HAn=new RegExp("^data:","i"),ZAn=new RegExp("^file:\\/\\/","i")});var y2=B(()=>{kr();Wr();vt();ir();Cr();_v()});var IQ=B(()=>{});var zIn,GIn,UIn,BIn,JIn,KIn,WIn,VIn,HIn,ZIn,QIn,XIn,YIn,eRn,nRn,tRn,rRn,oRn,iRn,aRn,_2=B(()=>{kr();xq();vt();fD();Dr();ir();tT();Cr();IQ();_v();fg();y2();zIn=new RegExp("<[^>]*>","g"),GIn=new RegExp(`data:[^"' )]+`,"g"),UIn=new RegExp("\\s+","g"),BIn=new RegExp("(?:<!doctype\\s+html|<html(?:\\s|>))","i"),JIn=new RegExp("cloudflare|cf-ray|\\bblocked\\b|access denied|\\bchallenge\\b|attention required","i"),KIn=new RegExp("cloudflare|cf-ray","i"),WIn=new RegExp("\\bblocked\\b|access denied","i"),VIn=new RegExp("attention required","i"),HIn=new RegExp("@font-face","i"),ZIn=new RegExp("unexpected status (401|403)\\b","i"),QIn=new RegExp("\\b(401|403)\\s+(?:unauthorized|forbidden)\\b","i"),XIn=new RegExp("^(?:model_request_rejected|invalid_request_error|invalid_request|request_rejected|content_policy_violation|content_filter|input_validation_error)$","i"),YIn=new RegExp("\\bmodel request was rejected\\b|\\bmodel_request_rejected\\b","i"),eRn=new RegExp("^provider_outage$","i"),nRn=new RegExp("rejecting requests|experiencing an outage|provider outage","i"),tRn=new RegExp("\\bapply_patch\\b[^]*\\bincompatible\\b|\\bin-flight tool future\\b[^]*\\bfail","i"),rRn=new RegExp("\\btools::router\\b[^]*\\bfatal\\b|\\bresponse\\.failed\\b","i"),oRn=new RegExp("(tool.*fatal|fatal.*tool|response[._]failed|tool_failure)","i"),iRn=new RegExp("upstream model stream stalled","i"),aRn=new RegExp("\\(HTTP (\\d{3})\\)")});var lRn,b2=B(()=>{Eu();vt();ir();yo();_v();fg();y2();_2();lRn=10*6e4});var pRn,MQ=B(()=>{kr();vt();ir();Lf();yo();b2();fg();pRn=10*6e4});function v2(e,n){return{message:n,budgetExempt:!1,preserveForRestart:e!==void 0?e:!1}}function $Q(e,n){let t=n-e.maxLivePressureAgeMs;return e.activeAckStartedAtMs.some(r=>r<=t)}function oT(e){return e.replace(eqe,"?").slice(0,128)}function FQ(e,n){return rr(e.activeAckStartedAtMs,0,(t,r)=>Math.max(t,n-r))}function nqe(e,n,t,r,o){e.pressureShedCount.contents=e.pressureShedCount.contents+1|0;let i=o!==void 0?o.TAG==="ItemStream"?["item",oT(o.itemKey),$t(o.turnId,oT)]:["turn",void 0,oT(o._0)]:["none",void 0,void 0],a;return a=n==="AckPressure"?"ack_pressure":"queue_age",{event:"commander_push.pressure_shed",branch:a,shedCount:e.pressureShedCount.contents,ageMs:t,budgetMs:e.maxLivePressureAgeMs,threadKey:oT(r),streamKind:i[0],itemKey:i[1],turnId:i[2]}}function jQ(e,n,t,r,o,i){let a=i(),s=nqe(e,n,t,r,o);try{e.onPressureShed(s)}catch{let u=s.branch,c=s.shedCount,l=s.ageMs,f=s.budgetMs,p=s.threadKey,h=s.streamKind,y=s.itemKey,m=s.turnId,_={event:"commander_push.pressure_shed_fallback",branch:u,shedCount:c,ageMs:l,budgetMs:f,threadKey:p,streamKind:h,itemKey:y,turnId:m};try{e.onPressureShedFallback(_)}catch{}}return a}function qQ(e){let n=e.now(),t=n-e.maxLivePressureAgeMs,r=$Q(e,n),o=[];e.live.activeThreads.forEach(i=>{let a=e.live.pendingByThread.get(i);if(a===void 0)return;let s=a.filter(u=>{let c=u.enqueuedAtMs<=t;if(!r&&!c)return!0;let l=r?"AckPressure":"QueueAge",f;return f=l==="AckPressure"?FQ(e,n):n-u.enqueuedAtMs,jQ(e,l,f,u.threadKey,u.streamIdentity,()=>xh(u.supersede,p=>p())),!1});s.length!==0?(e.live.pendingByThread.set(i,s),o.push(i)):e.live.pendingByThread.delete(i)}),e.live.activeThreads.splice(0,e.live.activeThreads.length,...o)}function NQ(e){let n=e.activeThreads.shift();if(n===void 0)return{TAG:"Ok",_0:void 0};let t=e.pendingByThread.get(n);if(t===void 0)return{TAG:"Error",_0:"Commander push admission lost an active thread"};let r=t.shift();return r!==void 0?(t.length!==0?e.activeThreads.push(n):e.pendingByThread.delete(n),{TAG:"Ok",_0:r}):(e.pendingByThread.delete(n),{TAG:"Error",_0:"Commander push admission thread queue was empty"})}function tqe(e){for(;;){let n=NQ(e.live);if(n.TAG!=="Ok")return{TAG:"Error",_0:n._0};let t=n._0;if(t===void 0)return{TAG:"Ok",_0:void 0};let r=e.now(),o=$Q(e,r),i=t.enqueuedAtMs+e.maxLivePressureAgeMs<=r;if(!o&&!i)return{TAG:"Ok",_0:t};let a=o?"AckPressure":"QueueAge",s;s=a==="AckPressure"?FQ(e,r):r-t.enqueuedAtMs,jQ(e,a,s,t.threadKey,t.streamIdentity,()=>xh(t.supersede,d=>d()))}}function rqe(e){for(;;){let n=e.priority.activeThreads.length!==0,t=e.live.activeThreads.length!==0,r=e.maxInFlight===1?!0:e.liveInFlight.contents<(e.maxInFlight-1|0),o=t&&r,i=e.consecutivePriority.contents<8,a=0;if(n)a=o&&!i?1:2;else if(o)a=1;else return e.consecutivePriority.contents=0,{TAG:"Ok",_0:void 0};switch(a){case 1:e.consecutivePriority.contents=0;let s=tqe(e);if(s.TAG!=="Ok")return{TAG:"Error",_0:s._0};let d=s._0;if(d!==void 0)return{TAG:"Ok",_0:d};continue;case 2:return e.consecutivePriority.contents=e.consecutivePriority.contents+1|0,NQ(e.priority)}}}function oqe(e,n,t,r,o,i){let a=n!==void 0?n:2e3,s=t!==void 0?t:w=>performance.now(),d=r!==void 0?r:(w,v)=>{let S=setTimeout(v,w);return S.unref(),()=>{clearTimeout(S)}},u=o!==void 0?o:w=>{console.warn("commander_push.pressure_shed",w)},c=i!==void 0?i:w=>{console.warn("commander_push.pressure_shed_fallback",w)},l=e>0,f=a>0&&isFinite(a)&&Number.isSafeInteger(a);if(!l)return{TAG:"Error",_0:"Commander push admission maxInFlight must be a positive integer"};if(!f)return{TAG:"Error",_0:"Commander push admission maxLivePressureAgeMs must be positive and finite"};let p={maxInFlight:e,priority:{pendingByThread:new Map,activeThreads:[]},live:{pendingByThread:new Map,activeThreads:[]},inFlight:{contents:0},liveInFlight:{contents:0},consecutivePriority:{contents:0},pumpScheduled:{contents:!1},schedulePump:()=>{},armPressureCheck:w=>{},recomputePressureCheck:()=>{},maxLivePressureAgeMs:a,now:s,schedulePressureCheck:d,activeAckStartedAtMs:[],cancelPressureCheck:{contents:void 0},pressureCheckDeadlineMs:{contents:void 0},onPressureShed:u,onPressureShedFallback:c,pressureShedCount:{contents:0}},h=w=>{let v=p.pressureCheckDeadlineMs.contents;if(v!==void 0){if(v<=w)return;xh(p.cancelPressureCheck.contents,A=>A()),p.pressureCheckDeadlineMs.contents=w;let C=p.schedulePressureCheck(Math.max(1,w-p.now()),()=>{p.cancelPressureCheck.contents=void 0,p.pressureCheckDeadlineMs.contents=void 0,qQ(p),p.schedulePump(),p.recomputePressureCheck()});p.cancelPressureCheck.contents=C;return}xh(p.cancelPressureCheck.contents,C=>C()),p.pressureCheckDeadlineMs.contents=w;let S=p.schedulePressureCheck(Math.max(1,w-p.now()),()=>{p.cancelPressureCheck.contents=void 0,p.pressureCheckDeadlineMs.contents=void 0,qQ(p),p.schedulePump(),p.recomputePressureCheck()});p.cancelPressureCheck.contents=S},y=()=>{let w={contents:void 0};p.live.pendingByThread.forEach(S=>{S.forEach(C=>{let A=C.enqueuedAtMs+p.maxLivePressureAgeMs,T=w.contents;w.contents=T!==void 0?Math.min(T,A):A})});let v=w.contents;if(v!==void 0)return h(rr(p.activeAckStartedAtMs,v,(S,C)=>Math.min(S,C+p.maxLivePressureAgeMs)))},m=()=>{for(;;){if(p.pumpScheduled.contents=!1,p.inFlight.contents>=p.maxInFlight)return;let w=rqe(p);if(w.TAG==="Ok"){let S=w._0;if(S===void 0)return;let C=p.now();p.inFlight.contents=p.inFlight.contents+1|0,p.activeAckStartedAtMs.push(C),p.live.activeThreads.length!==0&&h(C+p.maxLivePressureAgeMs),S.replaceableLive&&(p.liveInFlight.contents=p.liveInFlight.contents+1|0),Bu(S.task(),A=>{let T=Rd(A),M=T!==void 0?Dn(Bs(bt(T)),"unknown admission task error"):"unknown admission task error";return S.fail(v2(void 0,M)),Promise.resolve()}).finally(()=>{p.inFlight.contents=p.inFlight.contents-1|0;let A=p.activeAckStartedAtMs.indexOf(C);A!==-1&&p.activeAckStartedAtMs.splice(A,1),S.replaceableLive&&(p.liveInFlight.contents=p.liveInFlight.contents-1|0),p.schedulePump()});continue}let v=w._0;p.priority.pendingByThread.forEach(S=>{S.forEach(C=>C.fail(v2(void 0,v)))}),p.live.pendingByThread.forEach(S=>{S.forEach(C=>C.fail(v2(void 0,v)))}),p.priority.pendingByThread.clear(),p.live.pendingByThread.clear(),p.priority.activeThreads.splice(0,p.priority.activeThreads.length),p.live.activeThreads.splice(0,p.live.activeThreads.length);return}},_=()=>{if(!p.pumpScheduled.contents){p.pumpScheduled.contents=!0,queueMicrotask(m);return}};return p.schedulePump=_,p.armPressureCheck=h,p.recomputePressureCheck=y,{TAG:"Ok",_0:p}}function iqe(e){let n=$t(e[OQ],r=>r.trim());if(n===void 0)return{TAG:"Ok",_0:16};if(n==="")return{TAG:"Ok",_0:16};let t=Number(n);return Number.isSafeInteger(t)&&t>=2?{TAG:"Ok",_0:t|0}:{TAG:"Error",_0:OQ+" must be an integer of at least 2"}}function aqe(e){let n=$t(e[DQ],r=>r.trim());if(n===void 0)return{TAG:"Ok",_0:2e3};if(n==="")return{TAG:"Ok",_0:2e3};let t=Number(n);return Number.isSafeInteger(t)&&t>0?{TAG:"Ok",_0:t|0}:{TAG:"Error",_0:DQ+" must be a positive integer"}}var OQ,DQ,eqe,mRn,LQ=B(()=>{kr();Eu();vt();ti();ig();ir();OQ="LINZUMI_COMMANDER_PUSH_MAX_INFLIGHT",DQ="LINZUMI_COMMANDER_PUSH_PRESSURE_BUDGET_MS";eqe=new RegExp("[^\\x20-\\x7E]","g");mRn=xi(iqe(process.env),e=>xi(aqe(process.env),n=>oqe(e,n,void 0,void 0,void 0,void 0)))});var zQ=B(()=>{});var hRn,GQ=B(()=>{Uu();Kh();hRn=sV(e=>({joinRef:e.item(0,Wb(st)),ref:e.item(1,Wb(st)),topic:e.item(2,st),event:e.item(3,st),payload:e.item(4,Jh)}))});var SRn,UQ,kRn,CRn,TRn,PRn,iT=B(()=>{Ql();kr();Eu();Wr();vt();ti();ig();Dr();ir();Cr();zQ();yo();yD();GQ();hD();SRn=new RegExp("/$"),UQ="[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?<![\\uD800-\\uDBFF])[\\uDC00-\\uDFFF]",kRn=new RegExp(UQ),CRn=new RegExp(UQ,"g"),TRn=new RegExp("^npm install -g @linzumi\\/cli(@[0-9A-Za-z^~.-]{1,32})?$"),PRn=new RegExp("^\\d+\\.\\d+\\.\\d+(?:[-+][0-9A-Za-z.-]{1,32})?$")});var BQ=B(()=>{kr();vt()});var pqe,ARn,IRn,mqe,hqe,RRn,ERn,JQ=B(()=>{Uu();vt();Kh();pqe=Ma(e=>({decision:e.m(st),label:e.m(st),description:e.m(hr(st))})),ARn=Ma(e=>({decision:e.m(st)})),IRn=Ma(e=>({status:e.m(st),response:e.m(Jh)})),mqe=Pr("terminal"),hqe=ns([Pr("interrupted"),Pr("processed"),Pr("failed"),Pr("ignored"),Pr("stop_failed")]),RRn=Ma(e=>({disposition:e.m(mqe),thread_id:e.m(st),seq:e.m(es),status:e.m(hqe),reason:e.m(rV(st))})),ERn=Ma(e=>({approval_request_id:e.m(st),approval_kind:e.m(st),approval_summary:e.m(st),approval_reason:e.m(hr(st)),approval_port:e.m(hr(es)),approval_pid:e.m(hr(es)),approval_command:e.m(hr(st)),approval_cwd:e.m(hr(st)),approval_process_name:e.m(hr(st)),approval_process_icon_key:e.m(hr(st)),approval_process_icon_path:e.m(hr(st)),approval_choices:e.m(hr(Qk(pqe))),approval_allowed_actor_slug:e.m(hr(st)),approval_allowed_actor_user_id:e.m(hr(es))}))});function _qe(e){if(typeof e!="object"||e===null||Array.isArray(e))return{TAG:"Error",_0:"fused terminal acknowledgement envelope was not an object"};let n=e.status,t=e.response;if(n===void 0)return{TAG:"Error",_0:"fused terminal acknowledgement omitted status"};if(typeof n!="string")return{TAG:"Error",_0:"fused terminal acknowledgement status was not a string"};if(n==="ok"&&typeof t=="object"&&t!==null&&!Array.isArray(t)){let r=t.terminal_attempt;return r!==void 0?typeof r=="object"&&r!==null&&!Array.isArray(r)?{TAG:"Ok",_0:r}:{TAG:"Error",_0:"fused terminal acknowledgement was not an object"}:{TAG:"Error",_0:"fused terminal acknowledgement omitted terminal_attempt"}}return{TAG:"Error",_0:"fused terminal acknowledgement status was not ok: "+n}}function bqe(e,n,t){let r=_qe(t);if(r.TAG!=="Ok")return{TAG:"Error",_0:r._0};let o=r._0,i=o.frame;if(i===void 0)return{TAG:"Error",_0:"fused terminal acknowledgement omitted frame"};if(typeof i!="object"||i===null||Array.isArray(i))return{TAG:"Error",_0:"fused terminal frame acknowledgement was not an object"};let a=i.accepted;if(a===void 0)return{TAG:"Error",_0:"fused terminal frame omitted accepted disposition"};if(typeof a!="boolean")return{TAG:"Error",_0:"fused terminal frame accepted disposition was not boolean"};if(a){let s=o.message_state;if(s===void 0)return{TAG:"Error",_0:"fused terminal acknowledgement omitted message_state"};if(typeof s!="object"||s===null||Array.isArray(s))return{TAG:"Error",_0:"fused terminal message_state was not an object"};let d=s.disposition;if(d===void 0)return{TAG:"Error",_0:"fused terminal message_state omitted disposition"};if(typeof d!="string")return{TAG:"Error",_0:"fused terminal message_state disposition was not a string"};switch(d){case"applied":return{TAG:"Ok",_0:"AppliedTerminalMessageState"};case"terminal":let u=s.thread_id,c=s.seq,l=s.status,f=s.reason;if(u===void 0)return{TAG:"Error",_0:"fused terminal message_state consensus omitted required fields"};if(typeof u!="string")return{TAG:"Error",_0:"fused terminal message_state consensus omitted required fields"};if(c===void 0)return{TAG:"Error",_0:"fused terminal message_state consensus omitted required fields"};if(typeof c!="number")return{TAG:"Error",_0:"fused terminal message_state consensus omitted required fields"};if(l===void 0)return{TAG:"Error",_0:"fused terminal message_state consensus omitted required fields"};if(typeof l!="string")return{TAG:"Error",_0:"fused terminal message_state consensus omitted required fields"};if(f===void 0)return{TAG:"Error",_0:"fused terminal message_state consensus omitted required fields"};let p=u===e,h=c===n;if(!p)return{TAG:"Error",_0:"fused terminal message_state consensus identity mismatch"};if(!h)return{TAG:"Error",_0:"fused terminal message_state consensus identity mismatch"};switch(l){case"failed":case"ignored":case"interrupted":case"processed":case"stop_failed":break;default:return{TAG:"Error",_0:"fused terminal message_state consensus carried invalid status or reason"}}return f===null?{TAG:"Ok",_0:{TAG:"StoredTerminalMessageState",_0:{threadId:u,sourceSeq:c,status:l,reason:void 0}}}:typeof f=="string"?{TAG:"Ok",_0:{TAG:"StoredTerminalMessageState",_0:{threadId:u,sourceSeq:c,status:l,reason:f}}}:{TAG:"Error",_0:"fused terminal message_state consensus carried invalid status or reason"};default:return{TAG:"Error",_0:"unknown fused terminal message_state disposition: "+d}}}else{let s=YW(i.reason),d=XW(s);switch(s){case"FrameIndexReuse":case"UnknownRejection":return{TAG:"Ok",_0:{TAG:"RejectedTerminalFrame",_0:{TAG:"RetryableTerminalFrameRejection",_0:d}}};default:return{TAG:"Ok",_0:{TAG:"RejectedTerminalFrame",_0:{TAG:"GenerationTerminalFrameRejection",_0:d}}}}}}function KQ(e,n,t){let r;try{r=JSON.parse(t)}catch{r=void 0}if(r===void 0)return{kind:"retry",message:"fused terminal reply was not valid JSON"};let o=bqe(e,n,r);if(o.TAG!=="Ok")return{kind:"retry",message:o._0};let i=o._0;if(typeof i!="object"||i.TAG==="StoredTerminalMessageState")return"accepted";let a=i._0;return a.TAG==="RetryableTerminalFrameRejection"?{kind:"retry",message:a._0}:"generation_rejected"}var sEn,w2=B(()=>{kr();Eu();Wr();vt();ti();ig();nT();eq();Dr();ir();tT();Cr();Rh();yo();b2();MQ();LQ();_v();iT();fg();_2();BQ();$u();JQ();sEn=new RegExp("^item-\\d+$")});var pg,S2=B(()=>{w2();pg=KQ});function as(e){return typeof e=="string"&&xqe.has(e)}function k2(e){return wqe.has(e)}function Sqe(e){return VQ[e]}function mg(e){if(e===void 0)return{};let n=Sqe(e);return k2(n)?{fate:n,retryable:!0}:{fate:n}}function C2(e){return e===429?"rate_limited":e===402||e===408||e===425||e>=500&&e<=599?"transient_upstream":"deterministic"}var vqe,xqe,wqe,VQ,uEn,hg=B(()=>{"use strict";vqe=["deterministic","transient_upstream","transient_local","rate_limited","needs_approval","needs_decision","route_outage"],xqe=new Set(vqe);wqe=new Set(["transient_upstream","transient_local","route_outage"]);VQ={runner_updating:"transient_local",stillborn_worker:"transient_local",infra_turn_kill:"transient_local",resume_transient:"transient_local",start_stage_transient:"transient_local",resume_torn_tail:"transient_local",resurrection_interrupted:"transient_local",dead_letter_exhausted:"transient_local",dead_letter_withheld:"needs_decision",dead_letter_permanent:"deterministic",resume_cwd_not_allowed:"deterministic",cwd_stillbirth_circuit_open:"deterministic",engine_unavailable:"deterministic",provider_binding_rejected:"deterministic",project_untrusted:"deterministic",attachment_download_failed:"transient_local",claude_input_queue_closed:"transient_local",claude_dispatch_wedged:"transient_local"};uEn=Object.keys(VQ)});import{readFile as kqe}from"node:fs/promises";async function HQ(e){let n;try{n=await kqe(e,"utf8")}catch(t){return{type:"error",error:{type:"file_read_failed",path:e,message:t instanceof Error?t.message:String(t)}}}return Iqe(e,n)}function Iqe(e,n){let t=[],r=n.split(/\r?\n/u);for(let o=0;o<r.length;o+=1){let i=r[o],a=o+1;if(i===void 0||i.trim()==="")continue;let s;try{s=JSON.parse(i)}catch(c){return{type:"error",error:{type:"invalid_json",path:e,line:a,message:c instanceof Error?c.message:String(c)}}}let d=Rqe(e,a,s);if(d.type==="error")return d;let u=T2(d.record);if(u!==void 0)return{type:"error",error:{type:"credential_not_redacted",path:e,line:a,keyPath:u}};t.push(d.record)}return{type:"ok",fixture:{path:e,records:t}}}function ZQ(e){return JSON.stringify(e)}function Rqe(e,n,t){let r=O(t);if(r===void 0)return gg(e,n,"record must be a JSON object");let o=ie(r.schemaVersion);if(o!==1)return gg(e,n,"schemaVersion must be 1");let i=b(r.provider);if(i===void 0||!Cqe.has(i))return gg(e,n,"provider is not supported");let a=b(r.captureKind);if(a===void 0||!Tqe.has(a))return gg(e,n,"captureKind is not supported");let s=ie(r.ordinal);if(s===void 0||s<0)return gg(e,n,"ordinal must be a non-negative integer");let d=ie(r.offsetMs);if(d===void 0||d<0)return gg(e,n,"offsetMs must be a non-negative integer");let u=b(r.rawText),c=O(r.captureMetadata),l=Array.isArray(r.transforms)?r.transforms.filter(se):void 0;return{type:"ok",record:{schemaVersion:o,provider:i,captureKind:a,ordinal:s,offsetMs:d,...u===void 0?{}:{rawText:u},...r.rawValue===void 0?{}:{rawValue:r.rawValue},...c===void 0?{}:{captureMetadata:c},...l===void 0?{}:{transforms:l}}}}function gg(e,n,t){return{type:"error",error:{type:"invalid_record",path:e,line:n,message:t}}}function T2(e,n="$"){if(Array.isArray(e)){for(let t=0;t<e.length;t+=1){let r=T2(e[t]??null,`${n}[${t}]`);if(r!==void 0)return r}return}if(se(e))for(let[t,r]of Object.entries(e)){let o=`${n}.${t}`;if(Pqe.test(t)&&!P2(r))return o;if(r!==void 0){let i=T2(r,o);if(i!==void 0)return i}}}function P2(e){return e==null?!0:typeof e=="string"?Aqe.has(e):Array.isArray(e)?e.every(n=>P2(n)):se(e)?Object.values(e).every(n=>P2(n)):!1}var Cqe,Tqe,Pqe,Aqe,A2=B(()=>{"use strict";qt();Zt();Cqe=new Set(["codex-app-server","claude-code-sdk"]),Tqe=new Set(["incoming","outgoing","notification","request","response","sdk-message","commander-push","session-marker"]),Pqe=/(^|[_-])(token|secret|api[_-]?key|authorization|cookie|private[_-]?key|login[_-]?url)([_-]|$)/iu,Aqe=new Set(["[REDACTED]","<REDACTED>","$REDACTED"])});import{mkdirSync as Eqe,appendFileSync as Mqe}from"node:fs";import{dirname as Oqe}from"node:path";function I2(){return QQ()!==void 0}function sp(e){let n=QQ();if(n===void 0)return;let t=qqe(n),r=$qe(e),o={schemaVersion:1,provider:e.provider,captureKind:e.captureKind,ordinal:t.nextOrdinal,offsetMs:Math.max(0,Date.now()-t.startedAtMs),...r.rawText===void 0?{}:{rawText:r.rawText},...r.rawValue===void 0?{}:{rawValue:r.rawValue},...e.captureMetadata===void 0?{}:{captureMetadata:vv(e.captureMetadata)},...r.transforms.length===0?e.transforms===void 0?{}:{transforms:e.transforms}:{transforms:[...e.transforms??[],...r.transforms]}};t.nextOrdinal+=1,Mqe(n,`${ZQ(o)}
|
|
611
611
|
`,"utf8")}function QQ(){let e=process.env.LINZUMI_AGENT_REPLAY_RECORD_FILE?.trim();return e===void 0||e===""?void 0:e}function qqe(e){return bv!==void 0&&bv.path===e||(Eqe(Oqe(e),{recursive:!0}),bv={path:e,startedAtMs:Date.now(),nextOrdinal:0}),bv}function $qe(e){if(process.env.LINZUMI_AGENT_REPLAY_EXACT_RAW==="1")return{rawText:e.rawText,rawValue:e.rawValue,transforms:[]};let n=[],t=e.rawValue===void 0?void 0:vv(e.rawValue,"$.rawValue",n);return{rawText:Fqe(e.rawText,n),rawValue:t,transforms:n}}function Fqe(e,n){if(e!==void 0)try{let t=JSON.parse(e);return JSON.stringify(vv(t,"$.rawText",n))}catch{return e}}function vv(e,n="$",t=[]){if(Array.isArray(e))return e.map((o,i)=>vv(o,`${n}[${i}]`,t));if(!se(e))return e;let r=Object.entries(e).map(([o,i])=>{let a=`${n}.${o}`;return Dqe.test(o)?(t.push({type:"credential_redaction",path:a}),[o,"[REDACTED]"]):[o,i===void 0?void 0:vv(i,a,t)]});return Object.fromEntries(r)}var bv,Dqe,aT=B(()=>{"use strict";A2();qt();Dqe=/(^|[_-])(token|secret|api[_-]?key|authorization|cookie|private[_-]?key|login[_-]?url)([_-]|$)/iu});import{Buffer as jqe}from"node:buffer";function uT(e){return e instanceof sT||e instanceof Error&&e.name===aX&&"reply"in e}function yg(e){return e instanceof Xs||e instanceof Error&&e.name===iX&&"phase"in e&&"reason"in e}function sX(e){return yg(e)?e.phase==="wait_for_connection"?!0:e.reason!=="timeout":!1}function dX(e){return yg(e)&&(e.phase==="wait_for_connection"||e.reason==="topic_lost")}function XQ(e,n,t){return e==="phx_join"?t:n}function Kqe(e){let n;try{n=JSON.stringify(se(e)?rs(e):e)??"undefined"}catch{return"<unserializable payload>"}return n.length<=YQ?n:`${n.slice(0,YQ)}\u2026`}function Wqe(e){let n=new URL(e);switch(n.protocol){case"http:":n.protocol="ws:";break;case"https:":n.protocol="wss:";break}return n.pathname=n.pathname.replace(/\/$/,"")+"/socket/websocket",n.searchParams.set("vsn","2.0.0"),n.toString()}function Vqe(e){return[`${Jqe}${jqe.from(e,"utf8").toString("base64url")}`,"phoenix"]}async function lT(e,n,t=(o,i)=>new WebSocket(o,i===void 0?void 0:[...i]),r={}){let o=typeof n=="string"?n:void 0,i=()=>{if(typeof n=="string")return n;try{let j=n();if(typeof j=="string"&&j.trim()!=="")return o=j,j}catch{}if(o!==void 0)return o;throw new Error("phoenix token provider returned no usable token")},a=r.onOperatorNotice??(j=>{console.error(j)}),s=(j,de)=>{try{r.auditEvent?.(j,de)}catch(ge){let Te=(ge instanceof Error?ge.message:String(ge)).slice(0,240),Ae=`linzumi: phoenix.audit_sink_failed event=${j.slice(0,120)} message=${Te}`;try{a(Ae)}catch{try{console.error(Ae)}catch{}}}},d=new Map,u=new Map,c=new Map,l=new Map,f=new Map,p=new Map,h=new Map,y=new Map,m=new Set,_=1,w=new Set,v=new Set,S=new Set,C=new Set,A=new Set,T=(j,de)=>{for(let ge of A)try{ge(j,de)}catch(Te){s("phoenix.join_reply_observer_failed",{topic:j,message:(Te instanceof Error?Te.message:String(Te)).slice(0,240)})}},M=new Set,I=new Set,P={nextRef:1,websocket:void 0,closed:!1,connected:!1,hasEverConnected:!1,connectionGeneration:0,ready:Promise.resolve(),resolveReady:void 0,rejectReady:void 0,reconnectTimer:void 0,reconnectAttempts:0,backoffResetTimer:void 0,heartbeatTimer:void 0,connectedAt:void 0,pendingHeartbeats:[],lastHeartbeatAckAt:void 0,lastHeartbeatLatencyMs:void 0},z=r.pushTimeoutMs??Nqe,$=r.joinTimeoutMs??(r.pushTimeoutMs===void 0?Lqe:z),J=r.controlCursorStore,Q=r.controlEpochStore,K=j=>{d.forEach(de=>{clearTimeout(de.timer),de.reject(j)}),d.clear()},Z=()=>{P.resolveReady===void 0&&(P.ready=new Promise((j,de)=>{P.resolveReady=j,P.rejectReady=de}),P.ready.catch(()=>{}))},N=()=>{P.resolveReady?.(),P.resolveReady=void 0,P.rejectReady=void 0},W=j=>{P.rejectReady?.(j),P.resolveReady=void 0,P.rejectReady=void 0},ee=j=>{P.closed=!0,P.reconnectTimer!==void 0&&(clearTimeout(P.reconnectTimer),P.reconnectTimer=void 0),Rn(),Ye(),P.websocket?.close(),W(j),K(ia.clientClosed("reply"))},ne=(j,de)=>{let ge=oX(de);if(ge===void 0)return!0;let Te=l.get(j);if(Te!==void 0&&ge<=Te)return!1;let Ae=f.get(j);return Ae!==void 0&&Ae.has(ge)?!1:(ye(j,ge),!0)},ye=(j,de)=>{let ge=l.get(j);if(ge===void 0){l.set(j,de);return}if(de===ge+1){ge+=1;let Ae=f.get(j);if(Ae!==void 0)for(;Ae.has(ge+1);)ge+=1,Ae.delete(ge);l.set(j,ge);return}let Te=f.get(j);Te===void 0&&(Te=new Set,f.set(j,Te)),Te.add(de)},L=j=>l.get(j),ce=(j,de)=>{if(!j.startsWith("local_runner:"))return;let ge=de.control_high_water;if(typeof ge!="number"||!Number.isInteger(ge))return;let Te=l.get(j);if(!(Te===void 0||ge>=Te)&&(re(j),J?.reset!==void 0))try{J.reset(j,0)}catch{}},pe=j=>y.get(j)??0,re=j=>{l.delete(j),f.delete(j),p.delete(j),h.delete(j),y.set(j,pe(j)+1)},_e=(j,de)=>{if(Q===void 0||!j.startsWith("local_runner:"))return!1;let ge=de.control_epoch;if(typeof ge!="string"||ge==="")return!1;let Te=!1;try{Te=Q.adopt(j,ge)}catch{return!1}return Te&&re(j),Te},le=(j,de)=>{if(J!==void 0)try{J.onAdvance(j,de)}catch{}},Oe=(j,de,ge)=>{if(ge!==pe(j))return;let Te=p.get(j);Te?.delete(de);let Ae=h.get(j);(Ae===void 0||de>Ae)&&h.set(j,de);let $e=Te===void 0||Te.size===0?h.get(j):Math.min(...Te)-1;if($e===void 0)return;let Ze=L(j),Qe=Ze===void 0?$e:Math.min($e,Ze);le(j,Qe)},F=j=>{let de=l.get(j);if(de!==void 0)return de;if(J===void 0)return;let ge=r2e(J,j);return ge===void 0?0:(l.set(j,ge),ge)},H=new Set,V=(j,de,ge,Te)=>{try{te(j,de,ge,Te)}catch(Ae){let $e=Ae instanceof Error?Ae.message:String(Ae);try{Ee("phoenix.pushed_frame_dispatch_failed",{topic:j,frame:de,message:$e,stack:Ae instanceof Error?Ae.stack??null:null,payloadSnippet:Kqe(Te),dropped:!0})}catch{}if(!H.has(de)){H.add(de);try{a(`linzumi: dropped a pushed "${de}" frame on ${j} whose dispatch failed (${$e}); see the CLI audit log for the payload snippet.`)}catch{}}}},te=(j,de,ge,Te)=>{if(j.startsWith("local_runner:")&&de==="control"&&t2e(Te)){if(!ne(j,Te))return;let Ae=oX(Te);if(Ae!==void 0){let Qe=p.get(j);Qe===void 0&&(Qe=new Set,p.set(j,Qe)),Qe.add(Ae)}let $e=pe(j),Ze=Ae===void 0?()=>{}:()=>Oe(j,Ae,$e);w.forEach(Qe=>Qe(Te,Ze))}ge===null&&de!=="phx_reply"&&de!=="phx_error"&&v.forEach(Ae=>Ae(j,de,Te))},he=(j,de)=>{let ge=l.get(j),Te=ge===void 0?de:Math.max(ge,de),Ae=f.get(j);if(Ae!==void 0){for(let $e of Ae)$e<=Te&&Ae.delete($e);for(;Ae.has(Te+1);)Te+=1,Ae.delete(Te)}l.set(j,Te)},me=j=>{let de=L(j);if(de===void 0)return;let ge=p.get(j),Te=ge!==void 0&&ge.size>0?Math.min(...ge)-1:void 0;le(j,Te===void 0?de:Math.min(Te,de))},Se=(j,de)=>{if(j.startsWith("chat:")){let ge=de.events;if(ge==null)return;if(!Array.isArray(ge))throw new Error(`phoenix rejoin returned invalid events for ${j}`);ge.forEach(Te=>{v.forEach(Ae=>Ae(j,"event",Te))});return}if(j.startsWith("local_runner:")){let ge=de.controls;if(ge==null)return;if(!Array.isArray(ge))throw new Error(`phoenix rejoin returned invalid controls for ${j}`);ge.forEach($e=>{if(!a2e($e))return;let Ze={...$e.payload,replayed:!0,...$e.control_seq===void 0?{}:{control_seq:$e.control_seq}};V(j,$e.event,null,Ze)});let Te=de.controls_advance_to,Ae=de.control_high_water;typeof Te=="number"&&Number.isInteger(Te)&&(typeof Ae!="number"||Te<=Ae)&&he(j,Te),me(j)}},Ie=async(j,de)=>{let ge=eX(String(j.data)),[,Te,Ae,$e,Ze]=ge;if(Te!==null&&Ae==="phoenix"&&$e==="phx_reply"){let Qe=P.pendingHeartbeats.find(xn=>xn.ref===Te&&xn.generation===P.connectionGeneration);if(Qe!==void 0){let xn=Date.now(),nn=Math.max(0,xn-Qe.sentAt);P.pendingHeartbeats=P.pendingHeartbeats.filter(Sr=>Sr.ref!==Te||Sr.generation!==Qe.generation),P.lastHeartbeatAckAt=xn,P.lastHeartbeatLatencyMs=nn,s("phoenix.heartbeat_acknowledged",{connection_generation:Qe.generation,ref:Te,latency_ms:nn})}}if(Te!==null&&($e==="phx_reply"||$e==="phx_error")){let Qe=d.get(Te);if(Qe!==void 0)if(d.delete(Te),clearTimeout(Qe.timer),$e==="phx_error")Qe.reject(new Error("phoenix push failed"));else if(n2e(Ze)){let xn=ia.topicLost();Qe.reject(xn),de()}else if(e2e(Ze)&&Qe.event!=="phx_join")Qe.reject(new sT(Ze));else{if(Qe.event==="phx_join"&&u.has(Ae)&&xv(Ze)){let xn=_e(Ae,Ze.response);ce(Ae,Ze.response);try{if(T(Ae,Ze.response),Ae.startsWith("local_runner:"))for(let nn of C)await nn(Ae,Ze.response);xn||Se(Ae,Ze.response)}catch(nn){Qe.reject(nn instanceof Error?nn:new Error(String(nn)));return}Ae.startsWith("local_runner:")&&(Ze.response.controls_truncated===!0||xn)&&Ke(Ae)}Qe.resolve(Ze)}}V(Ae,$e,Te,Ze)},xe=(j,de,ge,Te=XQ(de,z,$),Ae)=>{let $e=P.websocket;if($e===void 0||$e.readyState!==WebSocket.OPEN)return Promise.reject(ia.socketNotOpen());let Ze=String(P.nextRef);P.nextRef+=1,de==="phx_join"&&c.set(j,Ze);let Qe=de==="phx_join"?Ze:c.get(j)??null,xn=Hqe(j,de,PC(ge)),nn=xn.payload,Sr=[Qe,Ze,xn.topic,xn.event,nn],et=Math.max(0,Math.ceil(Te));return new Promise((Fo,jo)=>{let jl=setTimeout(()=>{d.delete(Ze)&&jo(ia.replyTimeout(et,de))},et);d.set(Ze,{event:de,timer:jl,resolve:Fo,reject:jo}),sp({provider:i2e(nn),captureKind:"commander-push",rawText:JSON.stringify(Sr),rawValue:{topic:j,event:de,payload:nn}}),$e.send(JSON.stringify(Sr)),Ae?.()})},Je=(j,de)=>{let ge={};for(let Te of de)for(let[Ae,$e]of Object.entries(Te)){if($e===void 0)continue;let Ze=ge[Ae];Ae==="last_seq"&&typeof $e=="number"&&typeof Ze=="number"?ge[Ae]=Math.min(Ze,$e):Ze===void 0&&(ge[Ae]=$e)}if(j.startsWith("local_runner:")){let Te=F(j);Te!==void 0&&(ge.last_control_seq=Te);let Ae=o2e(Q,j);Ae!==void 0&&(ge.last_control_epoch=Ae)}return ge},Nn=async j=>{let de=0,ge=0;for(;;){let Te=u.get(j);if(Te===void 0)return;let Ae=F(j),$e=await xe(j,"phx_join",Je(j,[...Te.values()].map(et=>et.payload())));if(de+=1,!xv($e))return;let Ze=Array.isArray($e.response.controls)?$e.response.controls.length:0;ge+=Ze;let Qe=$e.response.controls_truncated===!0,xn=F(j),nn=$e.response.control_high_water,Sr=Qe?typeof nn=="number"&&Number.isInteger(nn)&&xn!==void 0?Math.max(0,nn-xn):null:0;if(Ee("phoenix.control_backlog_fetch_progress",{topic:j,fetches:de,fetched:ge,remaining_estimate:Sr,truncated:Qe}),!Qe)return;if(xn===Ae){a(`phoenix.control_backlog_fetch_stalled topic=${j} fetches=${de} fetched=${ge} cursor=${String(xn)}; a truncated reply made no cursor progress - stopping this fetch loop (a server paging bug; the next reconnect resumes from the watermark)`);return}de%Bqe===0&&a(`phoenix.control_backlog_cap_exceeded topic=${j} fetches=${de} fetched=${ge} remaining_estimate=${Sr??"unknown"}; continuing the paginated backlog fetch (a healthy connection never reconnects, so nothing is deferred)`),await new Promise(et=>{setImmediate(et)})}},Ke=j=>{m.has(j)||(m.add(j),Nn(j).catch(()=>{}).finally(()=>m.delete(j)))},qe=new Map,dn=async()=>{qe.clear();for(let[j,de]of u){let ge=await xe(j,"phx_join",Je(j,[...de.values()].map(Te=>Te.payload())));if(!xv(ge)){let Te=nX(ge);throw Te!==void 0?new Ju(Te):new Error(`phoenix rejoin failed for ${j}`)}se(ge.response)&&qe.set(j,ge.response)}},Ln=()=>{if(P.closed||P.reconnectTimer!==void 0)return;Z();let j=Math.min(Gqe,zqe*2**P.reconnectAttempts);P.reconnectAttempts+=1,P.reconnectTimer=setTimeout(()=>{P.reconnectTimer=void 0,q()},Math.random()*j)},In=(j,de)=>{let ge=P.connected,Te=P.connectedAt;P.connectedAt=void 0,P.connected=!1;let Ae=P.websocket;if(P.websocket=void 0,Rn(),Ye(),Ae!==void 0&&(Ae.readyState===WebSocket.CONNECTING||Ae.readyState===WebSocket.OPEN))try{Ae.close()}catch{}if(K(j),Ln(),ge||P.hasEverConnected&&(de.trigger==="reconnect_failure"||de.trigger==="hard_reset")){let Ze={closeCode:de.code,closeReason:typeof de.reason=="string"&&de.reason!==""?de.reason:void 0,previousSessionDurationMs:Te===void 0?void 0:Math.max(0,Date.now()-Te),reconnectCount:P.reconnectAttempts,connectionGeneration:P.connectionGeneration,trigger:de.trigger},Qe=P.pendingHeartbeats.at(-1);s("phoenix.transport_disconnected",{trigger:de.trigger,connection_generation:P.connectionGeneration,close_code:Ze.closeCode??null,close_reason:Ze.closeReason??null,session_duration_ms:Ze.previousSessionDurationMs??null,reconnect_count:Ze.reconnectCount,last_heartbeat_ack_at_ms:P.lastHeartbeatAckAt??null,last_heartbeat_latency_ms:P.lastHeartbeatLatencyMs??null,last_heartbeat_ref:Qe?.ref??null,last_heartbeat_generation:Qe?.generation??null,heartbeat_unacknowledged_ms:Qe===void 0?null:Math.max(0,Date.now()-Qe.sentAt)}),ge&&M.forEach(xn=>{try{xn(Ze)}catch{}}),P.pendingHeartbeats=[],P.lastHeartbeatAckAt=void 0,P.lastHeartbeatLatencyMs=void 0}},cn=()=>{In(ia.topicLost(),{trigger:"topic_authority_lost",reason:"unmatched_topic"}),P.reconnectTimer!==void 0&&(clearTimeout(P.reconnectTimer),P.reconnectTimer=void 0),q()},ct=3e4,Un=8,Rn=()=>{P.heartbeatTimer!==void 0&&(clearInterval(P.heartbeatTimer),P.heartbeatTimer=void 0)},Ye=()=>{P.backoffResetTimer!==void 0&&(clearTimeout(P.backoffResetTimer),P.backoffResetTimer=void 0)},fn=()=>{Ye(),P.backoffResetTimer=setTimeout(()=>{P.backoffResetTimer=void 0,P.connected&&(P.reconnectAttempts=0)},Uqe),P.backoffResetTimer?.unref?.()},ht=()=>{Rn(),P.heartbeatTimer=setInterval(()=>{let j=P.websocket;if(j===void 0||j.readyState!==WebSocket.OPEN)return;let de=P.pendingHeartbeats.at(-1);de!==void 0&&!de.overdueReported&&(s("phoenix.heartbeat_overdue",{connection_generation:de.generation,ref:de.ref,elapsed_ms:Math.max(0,Date.now()-de.sentAt)}),de.overdueReported=!0);let ge=String(P.nextRef);P.nextRef+=1;try{j.send(JSON.stringify([null,ge,"phoenix","heartbeat",{}]));let Te=P.pendingHeartbeats.slice(-(Un-1));P.pendingHeartbeats=[...Te,{ref:ge,sentAt:Date.now(),generation:P.connectionGeneration,overdueReported:!1}],s("phoenix.heartbeat_sent",{connection_generation:P.connectionGeneration,ref:ge})}catch{}},ct)},q=async()=>{if(P.closed)return;let j;try{j=t(Wqe(e),Vqe(i()));let de=j,ge;if(P.websocket=j,j.addEventListener("message",Te=>{if(P.websocket===de){let Ae=xn=>{let nn=xn instanceof Error?xn:new Error(String(xn));a(`phoenix.message_dispatch_failed message=${nn.message}; reconnecting so the frame is replayed from durable state`),P.websocket===de&&In(ia.reconnectFailed(),{trigger:"message_dispatch_failure"})},$e=(()=>{try{let[,xn,nn,Sr,et]=eX(String(Te.data)),Fo=xn===null?void 0:d.get(xn);return Sr==="phx_reply"&&Fo?.event==="phx_join"&&u.has(nn)&&xv(et)&&nn.startsWith("local_runner:")&&C.size>0}catch{return!1}})(),Ze=()=>Ie(Te,cn).then(()=>!0,xn=>(Ae(xn),!1)),Qe=ge;if(Qe!==void 0){let xn=Qe.then(nn=>nn&&P.websocket===de?Ze():!1).finally(()=>{ge===xn&&(ge=void 0)});ge=xn}else if($e){let xn=Ze().finally(()=>{ge===xn&&(ge=void 0)});ge=xn}else Ze()}}),j.addEventListener("close",Te=>{P.websocket===j&&In(ia.socketClosed(),{trigger:"socket_close",code:typeof Te.code=="number"?Te.code:void 0,reason:typeof Te.reason=="string"?Te.reason:void 0})},{once:!0}),j.addEventListener("error",()=>{P.websocket===j&&In(ia.socketClosed(),{trigger:"socket_error"})},{once:!0}),await s2e(j,z),P.closed||P.websocket!==j||(P.connectionGeneration+=1,await dn(),P.closed||P.websocket!==j))return;if(P.connected=!0,P.connectedAt=Date.now(),P.hasEverConnected=!0,fn(),ht(),N(),P.connectionGeneration>1){let Te=new Map(qe);S.forEach(Ae=>{Promise.resolve(Ae(Te)).catch(()=>{})})}}catch(de){if(P.closed||j!==void 0&&P.websocket!==void 0&&P.websocket!==j)return;if(!P.hasEverConnected){ee(de instanceof Error?de:new Error(String(de)));return}if(de instanceof Ju){ee(de),I.forEach(ge=>ge(de));return}In(ia.reconnectFailed(),{trigger:"reconnect_failure"})}};Z(),q(),await P.ready;let X=(j,de)=>new Promise((ge,Te)=>{let Ae=setTimeout(()=>{Te(ia.connectionWaitTimeout(z,j))},Math.max(0,de-Date.now()));P.ready.then(()=>{clearTimeout(Ae),ge()},$e=>{clearTimeout(Ae),Te($e instanceof Error?$e:new Error(String($e)))})}),ae=async(j,de,ge,Te,Ae)=>{let $e=XQ(de,z,$),Ze=Date.now()+$e;if(await X(de,Ze),Ae!==void 0&&!Ae())throw console.warn("phoenix.publication_owner_superseded",{topic:j,event:de}),new Error("publication owner superseded before socket write");return xe(j,de,ge,Ze-Date.now(),Te)};return{join:async(j,de,ge)=>{let Te=ge?.registrationId??`join-registration-${_++}`,Ae=[...u.get(j)?.values()??[]].map(Qe=>Qe.payload()),$e=await ae(j,"phx_join",Je(j,[...Ae,de]));if(xv($e)){let Qe=u.get(j)??new Map,xn=Qe.size===0;if(xn&&T(j,$e.response),Qe.set(Te,{payload:ge?.rejoinPayload??(()=>de)}),u.set(j,Qe),xn&&j.startsWith("local_runner:")){let nn=_e(j,$e.response);ce(j,$e.response),nn||Se(j,$e.response),($e.response.controls_truncated===!0||nn)&&Ke(j)}return $e.response}let Ze=nX($e);throw Ze!==void 0?new Ju(Ze):new Error(`phoenix join failed: ${Yqe($e)}`)},unregisterJoin:(j,de)=>{let ge=u.get(j);ge!==void 0&&(ge.delete(de),ge.size===0&&(u.delete(j),c.delete(j)))},push:ae,pushIfConnected:async(j,de,ge)=>{if(!P.connected)throw ia.notConnected();return await xe(j,de,ge)},onControl:j=>{w.add(j)},onEvent:j=>{v.add(j)},onBeforeControlReplay:j=>{C.add(j)},onJoinReply:j=>{A.add(j)},onReconnect:j=>{S.add(j)},onDisconnect:j=>{M.add(j)},onFatal:j=>{I.add(j)},forceReconnect:j=>P.closed||!P.connected?!1:(In(ia.socketClosed(),{trigger:"forced_reconnect",reason:j??"forced_stale_reconnect"}),!0),hardReset:j=>P.closed?!1:(In(ia.socketClosed(),{trigger:"hard_reset",reason:j??"hard_reset"}),P.reconnectTimer!==void 0&&(clearTimeout(P.reconnectTimer),P.reconnectTimer=void 0),q(),!0),close:()=>{ee(ia.clientClosed("wait_for_connection"))}}}function R2(e){return typeof e=="string"?wv.test(e):Array.isArray(e)?e.some(R2):se(e)?Object.entries(e).some(([n,t])=>wv.test(n)||t!==void 0&&R2(t)):!1}function E2(e){return typeof e=="string"?e.replace(dT,"\uFFFD"):Array.isArray(e)?e.map(E2):se(e)?Object.fromEntries(Object.entries(e).map(([n,t])=>[n.replace(dT,"\uFFFD"),t===void 0?t:E2(t)])):e}function Hqe(e,n,t){if(!wv.test(e)&&!wv.test(n)&&!R2(t))return{topic:e,event:n,payload:t};let r=e.replace(dT,"\uFFFD"),o=n.replace(dT,"\uFFFD");return Ee("phoenix.outbound_frame_lone_surrogate_sanitized",{purpose:"phoenix.send_totality",topic:r,frame_event:o}),{topic:r,event:o,payload:E2(t)}}function eX(e){let n=JSON.parse(e);if(Array.isArray(n)&&n.length===5&&(n[0]===null||typeof n[0]=="string")&&(n[1]===null||typeof n[1]=="string")&&typeof n[2]=="string"&&typeof n[3]=="string")return n;throw new Error("invalid Phoenix frame")}function xv(e){return se(e)&&e.status==="ok"&&se(e.response)}function Zqe(e){switch(e.kind){case"commander_version_too_old":return`phoenix join failed: commander_version_too_old: this Linzumi server requires @linzumi/cli ${e.minVersion} or newer. Update with: ${e.upgradeCommand}`;case"adt_stream_v1_required":return`phoenix join failed: adt_stream_v1_required: this Linzumi server requires @linzumi/cli with native ADT streaming. Update with: ${e.upgradeCommand}`}}function Qqe(e){return typeof e=="string"&&e.length<=100&&lX.test(e)?e:uX}function nX(e){if(!se(e)||!se(e.response))return;let n=e.response;if(n.error==="adt_stream_v1_required")return{kind:"adt_stream_v1_required",upgradeCommand:uX};if(n.error==="commander_version_too_old"&&!(typeof n.min_version!="string"||n.min_version.length>64||!cX.test(n.min_version)||typeof n.upgrade_command!="string"||n.upgrade_command.length>100||!lX.test(n.upgrade_command)))return{kind:"commander_version_too_old",minVersion:n.min_version,upgradeCommand:n.upgrade_command}}function Xqe(e){return typeof e=="string"&&e.length<=64&&cX.test(e)?`@linzumi/cli ${e} or newer`:"a newer @linzumi/cli"}function Yqe(e){if(se(e)){let n=e.response;if(se(n)&&n.error==="commander_version_too_old"){let t=Xqe(n.min_version),r=Qqe(n.upgrade_command);return`commander_version_too_old: this Linzumi server requires ${t}. Update with: ${r}`}}return fX(e)}function fX(e){if(!se(e))return"invalid reply";let n=e.response;return se(n)&&typeof n.error=="string"?n.error:se(n)&&typeof n.reason=="string"?n.reason:se(n)&&typeof n.message=="string"?n.message:typeof e.error=="string"?e.error:"unknown"}function e2e(e){return se(e)&&e.status!=="ok"}function n2e(e){if(!se(e)||e.status!=="error")return!1;let n=e.response;return se(n)&&n.reason==="unmatched topic"}function t2e(e){return se(e)&&typeof e.type=="string"}function r2e(e,n){try{let t=e.initial(n);return typeof t=="number"&&Number.isInteger(t)&&t>=0?t:void 0}catch{return}}function o2e(e,n){if(e!==void 0)try{let t=e.current(n);return typeof t=="string"&&t!==""?t:void 0}catch{return}}function i2e(e){if(rX(e,"agent_provider")==="claude-code")return"claude-code-sdk";let t=tX(e,"metadata"),r=tX(t,"local_codex_runner");return rX(r,"agent_provider")==="claude-code"?"claude-code-sdk":"codex-app-server"}function tX(e,n){let t=e?.[n];return se(t)?t:void 0}function rX(e,n){let t=e?.[n];return typeof t=="string"?t:void 0}function oX(e){if(!se(e))return;let n=e.control_seq;return typeof n=="number"&&Number.isInteger(n)?n:void 0}function a2e(e){return se(e)&&typeof e.event=="string"&&se(e.payload)&&(e.control_seq===void 0||typeof e.control_seq=="number"&&Number.isInteger(e.control_seq))}function s2e(e,n){return new Promise((t,r)=>{let o,i=a=>{o!==void 0&&(clearTimeout(o),o=void 0),a()};e.addEventListener("open",()=>i(t),{once:!0}),e.addEventListener("error",()=>i(()=>r(new Error("websocket open failed"))),{once:!0}),e.addEventListener("close",()=>i(()=>r(new Error("websocket closed before open"))),{once:!0}),n!==void 0&&(o=setTimeout(()=>{o=void 0,i(()=>r(new Error(`websocket open timed out after ${n}ms`)))},n))})}var iX,Xs,aX,sT,ia,Nqe,Lqe,zqe,Gqe,Uqe,Bqe,Jqe,YQ,wv,dT,Ju,uX,lX,cX,Sv=B(()=>{"use strict";aT();AC();io();qt();iX="PhoenixPushError",Xs=class extends Error{phase;reason;constructor(n,t,r){super(r),this.name=iX,this.phase=n,this.reason=t}},aX="PhoenixReplyRejectedError",sT=class extends Error{reply;constructor(n){super(`phoenix push failed: ${fX(n)}`),this.name=aX,this.reply=n}};ia={socketClosed:()=>new Xs("reply","socket_closed","phoenix websocket closed"),reconnectFailed:()=>new Xs("reply","socket_closed","phoenix websocket reconnect failed"),topicLost:()=>new Xs("reply","topic_lost","phoenix topic authority lost"),socketNotOpen:()=>new Xs("wait_for_connection","socket_not_open","phoenix websocket is not open"),clientClosed:e=>new Xs(e,"client_closed","phoenix client closed"),notConnected:()=>new Xs("wait_for_connection","not_connected","phoenix client is not connected"),connectionWaitTimeout:(e,n)=>new Xs("wait_for_connection","timeout",`phoenix push timed out after ${e}ms waiting for connection: ${n}`),replyTimeout:(e,n)=>new Xs("reply","timeout",`phoenix push timed out after ${e}ms: ${n}`)};Nqe=3e4,Lqe=125e3;zqe=250,Gqe=1e4,Uqe=3e4,Bqe=20,Jqe="base64url.bearer.phx.",YQ=400;wv=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/,dT=new RegExp(wv.source,"g");Ju=class extends Error{refusal;constructor(n){super(Zqe(n)),this.name="PhoenixCommanderVersionTooOldError",this.refusal=n}};uX="npm install -g @linzumi/cli@latest",lX=/^npm install -g @linzumi\/cli(@[0-9A-Za-z^~.-]{1,32})?$/,cX=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]{1,32})?$/});function M2(e){let n=e.sessionId===e.freshSessionId,t=e.freshLeaseEpoch>=e.leaseEpoch,r=e.fenced,o=(e.providerStarted||e.emittedFrameCount>0)&&e.freshNextFrameIndex>e.nextFrameIndex;return n?t?r?{kind:"refused",message:"cannot reconcile fenced ADT publication authority"}:o?{kind:"refused",message:"reconciled ADT frontier exceeds owned emitted history"}:{kind:"accepted",nextFrameIndex:e.nextFrameIndex>=e.freshNextFrameIndex?e.nextFrameIndex:e.freshNextFrameIndex}:{kind:"refused",message:"reconciled ADT lease epoch regressed"}:{kind:"refused",message:"reconciled ADT session identity changed"}}function O2(e,n,t,r,o){return e===r?o===n?!0:t.includes(o):!1}var D2=B(()=>{});var mX,hX,gX=B(()=>{D2();mX=M2,hX=O2});import{createHash as d2e}from"node:crypto";function bX(e){let n=e.itemId??`index:${e.itemIndex}`;return`${e.turnId}:${e.streamKind}:${n}`}function pT(e,n,t=!1){let r=mX({sessionId:e.binding.sessionId,leaseEpoch:e.binding.leaseEpoch,nextFrameIndex:e.emitter.nextFrameIndex,emittedFrameCount:e.emitter.emittedFrameCount,providerStarted:t,fenced:e.emitter.fenced,freshSessionId:n.sessionId,freshLeaseEpoch:n.leaseEpoch,freshNextFrameIndex:n.nextFrameIndex});return r.kind==="refused"?r:(e.reconciledLeaseEpochs=[...new Set([...e.reconciledLeaseEpochs??[],e.binding.leaseEpoch])],e.binding=n,e.emitter={...e.emitter,binding:n,nextFrameIndex:r.nextFrameIndex},{kind:"accepted"})}function TX(e,n,t){let r=O(n==="adt_frame"?t:t.terminal_frame);if(r===void 0||typeof r.session_id!="number"||typeof r.lease_epoch!="number")return{kind:"refused",message:"ADT publication session or lease missing"};if(e.emitter.fenced||!hX(e.binding.sessionId,e.binding.leaseEpoch,e.reconciledLeaseEpochs??[],r.session_id,r.lease_epoch))return{kind:"refused",message:"ADT publication does not own the reconciled session and lease"};let o={...r,lease_epoch:e.binding.leaseEpoch};return{kind:"accepted",payload:n==="adt_frame"?o:{...t,terminal_frame:o}}}var Qt,vX,xX,cT,wX,dp,$2,u2e,l2e,c2e,SX,f2e,fT,p2e,Cv,F2,kX,m2e,CX,h2e,j2,q2,N2,yX,g2e,y2e,Ku,Tv,mT,_g,_2e,b2e,_X,PX,v2e,kv,AX,hT,gT,Pv=B(()=>{"use strict";Zt();gX();Qt={postStreamedRow:"pipeline.post_streamed_row",streamSnapshot:"pipeline.stream_snapshot",finalizeRow:"pipeline.finalize_row",postCompletedRow:"pipeline.post_completed_row",messageState:"pipeline.message_state",unmappedTurnFailure:"pipeline.unmapped_turn_failure"},vX="adt_stream_v1",xX="adt_frame",cT="terminal_attempt",wX="adt_stall_heartbeat",dp=e=>typeof e=="number"&&Number.isInteger(e)&&e>=1?e:null,$2=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null,u2e=e=>{let n=$2(e);if(n===null)return{ok:!1,reason:"binding_not_object"};let t=dp(n.session_id);if(t===null)return{ok:!1,reason:"session_id_invalid"};let r=dp(n.lease_epoch);if(r===null)return{ok:!1,reason:"lease_epoch_invalid"};let o=dp(n.next_frame_index);if(o===null)return{ok:!1,reason:"next_frame_index_invalid"};if(!("checkpoint_config"in n))return{ok:!1,reason:"checkpoint_config_missing"};let i=l2e(n.checkpoint_config);return i===null?{ok:!1,reason:"checkpoint_config_invalid"}:{ok:!0,binding:{sessionId:t,leaseEpoch:r,nextFrameIndex:o,checkpointConfig:i}}},l2e=e=>{let n=$2(e);if(n===null)return null;let t=dp(n.version);if(t===null)return null;let r=$2(n.thresholds);if(r===null)return null;let o=dp(r.max_bytes),i=dp(r.max_deltas),a=dp(r.max_interval_ms);return o===null||i===null||a===null?null:{version:t,thresholds:{maxBytes:o,maxDeltas:i,maxIntervalMs:a}}},c2e=e=>({session_id:e.sessionId,lease_epoch:e.leaseEpoch,frame_index:e.frameIndex,frame_kind:e.frameKind,body:e.body,byte_len:e.byteLen,...e.assistantIdentity===void 0?{}:{assistant_phase:e.assistantIdentity.phase,source_stream_key:e.assistantIdentity.sourceStreamKey}}),SX=e=>Buffer.byteLength(e,"utf8"),f2e=e=>d2e("sha256").update(`${e.frameKind}
|
|
612
612
|
${e.body}`).digest("hex").slice(0,16),fT=e=>{switch(e){case"stale_epoch":case"post_settle":case"post_terminal":case"frame_index_reuse":return e;default:return"unknown"}},p2e=(e,n)=>({binding:e,cumulative:"",pendingBody:"",pendingBytes:0,pendingDeltas:0,lastFrameAtMs:n,nextFrameIndex:e.nextFrameIndex,emittedFrameCount:0,checkpointPending:!1,terminalEmitted:!1,fenced:!1}),Cv=(e,n,t)=>{let r=n==="delta"?e.pendingBody:e.cumulative,o={sessionId:e.binding.sessionId,leaseEpoch:e.binding.leaseEpoch,frameIndex:e.nextFrameIndex,frameKind:n,body:r,byteLen:SX(r),assistantIdentity:e.assistantIdentity};return e.nextFrameIndex+=1,e.emittedFrameCount+=1,e.pendingBody="",e.pendingBytes=0,e.pendingDeltas=0,e.lastFrameAtMs=t,n!=="delta"&&(e.checkpointPending=!1),o},F2=e=>e.emittedFrameCount===0||e.checkpointPending?"checkpoint":"delta",kX=(e,n)=>{let{thresholds:t}=e.binding.checkpointConfig;return e.pendingDeltas===0?!1:e.pendingBytes>=t.maxBytes||e.pendingDeltas>=t.maxDeltas||n-e.lastFrameAtMs>=t.maxIntervalMs},m2e=(e,n,t)=>e.fenced||e.terminalEmitted||n.length===0||(e.cumulative+=n,e.pendingBody+=n,e.pendingBytes+=SX(n),e.pendingDeltas+=1,!kX(e,t))?null:Cv(e,F2(e),t),CX=(e,n)=>e.fenced||e.terminalEmitted||!kX(e,n)?null:Cv(e,F2(e),n),h2e=(e,n)=>e.fenced||e.terminalEmitted||e.pendingBody.length===0?null:Cv(e,F2(e),n),j2=(e,n)=>e.fenced||e.terminalEmitted?null:(e.terminalEmitted=!0,Cv(e,"terminal",n)),q2=e=>{e.fenced||e.terminalEmitted||(e.cumulative="",e.pendingBody="",e.pendingBytes=0,e.pendingDeltas=0,e.checkpointPending=!0)},N2=e=>{e.fenced=!0},yX=e=>`adt_stream_v1 dispatch refused: ${e}; the commander refuses to stream unconfigured (no baked fallback thresholds exist by law - plan doc 2.4/MF9)`,g2e=new Set(["processed","failed","interrupted","ignored"]),y2e=e=>g2e.has(e);Ku=(e,n,t)=>{if(e==null)return{kind:"absent"};let r=u2e(e);if(!r.ok)return{kind:"refused",reason:r.reason,message:yX(r.reason)};if(n===void 0||!Number.isInteger(n)||n<1)return{kind:"refused",reason:"source_seq_invalid",message:yX("source_seq_invalid")};let{binding:o}=r;return{kind:"accepted",session:{binding:o,sourceSeq:n,emitter:p2e(o,t),trackedItemKey:void 0,trackedItemRank:0,itemFirstSeenOrdinals:new Map,lastBody:"",done:!1},ackPayload:{session_id:o.sessionId,lease_epoch:o.leaseEpoch,checkpoint_config_version:o.checkpointConfig.version}}},Tv="adt.frame",mT="adt.terminal_attempt",_g=e=>({...c2e(e),digest:f2e(e)}),_2e=e=>typeof e.stream_kind=="string"?e.stream_kind:void 0,b2e=e=>{let n=e.structured;return typeof n!="object"||n===null||Array.isArray(n)?0:n.phase==="final_answer"?1:0},_X=(e,n)=>typeof e[n]=="number"&&Number.isInteger(e[n])?e[n]:void 0,PX=(e,n,t,r,o)=>{if(e.done||e.emitter.fenced)return[];if(n===o.messageState){let v=_X(t,"seq"),S=typeof t.status=="string"?t.status:void 0;if(v!==e.sourceSeq||S===void 0||!y2e(S))return[];let C=h2e(e.emitter,r),A=j2(e.emitter,r);e.done=!0;let T=[];return C!==null&&T.push(C),A!==null&&T.push(A),T}if(!(n===o.postStreamedRow||n===o.streamSnapshot||n===o.finalizeRow||n===o.postCompletedRow))return[];if(_2e(t)!=="assistant")return[];if(_X(t,"source_seq")!==e.sourceSeq)return[];let a=typeof t.item_key=="string"?t.item_key:void 0;if(a===void 0)return[];let s=b2e(t),d=e.itemFirstSeenOrdinals.get(a);if(d===void 0&&(d=e.itemFirstSeenOrdinals.size,e.itemFirstSeenOrdinals.set(a,d)),e.trackedItemKey===void 0)e.trackedItemKey=a,e.trackedItemRank=s;else if(e.trackedItemKey===a)e.trackedItemRank=s;else{let v=e.itemFirstSeenOrdinals.get(e.trackedItemKey)??-1;if(!(s>e.trackedItemRank||s===e.trackedItemRank&&d>v))return[];e.trackedItemKey=a,e.trackedItemRank=s,e.lastBody="",q2(e.emitter)}let u=typeof t.body=="string"?t.body:"",c=t.structured,l=c!==null&&typeof c=="object"&&"phase"in c?c.phase:void 0,f=typeof t.client_message_id=="string"?t.client_message_id:void 0;if(l!=null&&l!=="commentary"&&l!=="final_answer"||(l==="commentary"||l==="final_answer")&&!f)return N2(e.emitter),console.error("adt.assistant_identity_refused",{session_id:e.binding.sessionId,lease_epoch:e.binding.leaseEpoch,reason:l!=="commentary"&&l!=="final_answer"?"invalid_assistant_phase":f===void 0?"missing_source_stream_key":"empty_source_stream_key"}),[];let p=(l==="commentary"||l==="final_answer")&&f?{phase:l,sourceStreamKey:f}:void 0,h=p?.phase!==e.emitter.assistantIdentity?.phase||p?.sourceStreamKey!==e.emitter.assistantIdentity?.sourceStreamKey,y=h&&(p?.phase==="final_answer"||e.emitter.emittedFrameCount>0);h&&(q2(e.emitter),e.emitter.assistantIdentity=p,e.lastBody="");let m=!u.startsWith(e.lastBody);m&&(q2(e.emitter),e.lastBody="");let _=u.slice(e.lastBody.length);e.lastBody=u;let w=m2e(e.emitter,_,r);return w===null?y||m?[Cv(e.emitter,"checkpoint",r)]:[]:[w]},v2e=256,kv=new Set,AX=(e,n)=>`${e}:${n}`,hT=(e,n)=>{for(kv.add(AX(e,n));kv.size>v2e;){let t=kv.values().next();if(t.done===!0)break;kv.delete(t.value)}},gT=(e,n)=>kv.has(AX(e,n))});var up,bg,yT,L2,IX,z2=B(()=>{dg();up=is,bg=cv,yT=lc,L2=ag,IX=sg});import{mkdirSync as RX,readFileSync as x2e,renameSync as w2e,writeFileSync as S2e}from"node:fs";import{appendFile as k2e,rename as EX,writeFile as C2e}from"node:fs/promises";import{createHash as T2e}from"node:crypto";import{dirname as MX,join as P2e}from"node:path";function fc(e,n){let t=n.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[-.]+|[-.]+$/g,"").slice(0,80),r=T2e("sha256").update(n).digest("hex").slice(0,8);return P2e(e,`${t===""?"thread":t}.${r}.outbox.jsonl`)}function vg(e,n,t){let r={pendingEntries:[],failedTerminalEntries:[],kv:new Map,counters:{totalEnqueued:0,totalAcked:0,totalDroppedBestEffort:0,totalPermanentFailures:0,knownNonterminalFailures:0,totalExpiredOnRecovery:0,lastEntrySeq:0},recovery:{type:"healthy",presence:"missing"}},o;try{o=t?.contents??x2e(e,"utf8")}catch(l){return qX(l,"ENOENT")||(n("outbox_journal_read_failed",{path:e,error:bT(l)}),r.recovery={type:"unavailable",reason:"read_failed"}),r}r.recovery={type:"healthy",presence:"loaded"};let i=new Map,a=0,s=0,d=o.split(`
|
|
613
613
|
`),u=-1;for(let l=0;l<d.length;l+=1){let f=d[l];f!==void 0&&f.trim()!==""&&(u=l)}for(let l=0;l<=u;l+=1){let f=d[l];if(f===void 0||f.trim()==="")continue;let p=q2e(f);if(p===void 0){let _=M2e({raw:o,line:f,index:l,lastIndex:u,physicalLastIndex:d.length-1,recovery:r.recovery});if(_!==void 0){if(t?.mode==="read_only"){n("outbox_journal_inspection_refused",{path:e,line:l+1,reason:"truncated_ordinary_tail",recordType:_}),r.recovery={type:"unavailable",reason:"inspection_requires_repair"};continue}let w=OX(e,o.slice(0,o.lastIndexOf(`
|
|
@@ -621,7 +621,7 @@ ${e.body}`).digest("hex").slice(0,16),fT=e=>{switch(e){case"stale_epoch":case"po
|
|
|
621
621
|
|
|
622
622
|
`);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=KC(e,{command:n.command,output:n$e(n.chunks),processId:n.processId,stream:r?.stream??""},t);return{body:t$e(o),structured:o}}case"fileChange":{let r=J2(n.patchText);return{body:r,structured:iQ(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:d2(n.queries),structured:sQ(e,n.queries,t)};case"toolCall":return{body:n.previewText,structured:{kind:"codex_tool_call",item_id:e,transcript_unit_id:`codex_tool_call:${e}`,stream_state:t,tool_name:n.toolName??"",input_summary:n.inputSummary??"",output_summary:n.outputSummary??""}};case"agentStatus":{let r=GC(e,{...n,body:rg(n.body)},t);return{body:sv(n.title,rg(n.body)),structured:r}}case"agentTaskUpdate":{let r=rg(n.body),o=n2(e,{...n,body:r},t);return{body:sv(n.title,r??n.progressLabel),structured:o}}}}function t$e(e){let n=b(e.command)??"",t=typeof e.output=="string"?e.output:"";return[`$ ${n}`,t].filter(r=>r.trim()!=="").join(`
|
|
623
623
|
|
|
624
|
-
`)}function QX(e){switch(b(e.type)){case"reasoning":return"reasoning";case"agentMessage":return"assistant";case"message":return b(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"mcpToolCall":case"dynamicToolCall":case"collabAgentToolCall":return"toolCall";case"sleep":case"imageGeneration":return"agentStatus";case"agentStatus":return"agentStatus";case"agentTaskUpdate":return"agentTaskUpdate";default:return}}function XX(e){return e.flatMap((n,t)=>{if(!se(n))return[];let r=QX(n);return r===void 0||r==="webSearch"?[]:og(n,t).filter(o=>o.body.trim()!=="").map(o=>({snapshotIndex:t,providerItemType:b(n.type),itemId:b(n.id),streamKind:r,body:o.body,structured:o.structured}))})}function K2(e,n){let t=b(e.kind)??"codex_output";return{...e,item_id:n,transcript_unit_id:b(e.divider_identity)??`${t}:${n}`}}function W2(e,n,t,r){if(t==="webSearch")return`local-codex-search-${BX("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:",toolCall:"tool-call:",agentStatus:"agent-status:",agentTaskUpdate:"agent-task:"};return`local-codex-stream-${BX("sha256").update(`${e}:${n}:${o[t]}${r}`).digest("hex").slice(0,32)}`}function Rv(e){let n=O(e.turn),t=O(e.item),r=O(t?.turn);return b(n?.id)??b(e.turnId)??b(e.turn_id)??b(t?.turnId)??b(t?.turn_id)??b(r?.id)}var X2e,V2=B(()=>{"use strict";os();Zt();qt();X2e={pending:"PENDING",inProgress:"IN_PROGRESS",completed:"COMPLETED"}});function eY(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 YX,nY=B(()=>{"use strict";YX="edge_blocked"});function H2(e){return a$e.test(e)}function wT(e){let n=s$e.test(e),t=n?e.match(d$e)?.[1]:void 0,r=t===void 0?void 0:Number.parseInt(t,10);return{status:c$e(e),requestId:f$e(e),edgeBlocked:eY(e),oauthExpired:H2(e),providerOutage:n,holdCeilingMinutes:r!==void 0&&r>0?r:void 0,providerOutageRoute:n?{provider:e.match(u$e)?.[1],model:e.match(l$e)?.[1]}:void 0,message:p$e(e)}}function ST(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 rY(e){return e.status!==void 0||e.requestId!==void 0||e.edgeBlocked||e.oauthExpired||e.providerOutage}function oY(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=${YX}]`),n.oauthExpired&&t.push(`Claude login expired on this computer - run \`claude\` in a terminal there and sign in again, then retry [failure_class=${Sg}]`),t.length===0?e:`${e} (${t.join(", ")})`}function c$e(e){for(let n of r$e){let t=e.match(n)?.[1];if(t!==void 0)return Number.parseInt(t,10)}}function f$e(e){for(let n of o$e){let t=e.match(n)?.[1];if(t!==void 0)return t}}function p$e(e){let n=e.match(i$e)?.[1],r=(n===void 0?e:m$e(n)).trim();return r.length<=tY?r:`${Ui(r,tY-1)}\u2026`}function m$e(e){try{return JSON.parse(`"${e}"`)}catch{return e}}var tY,Sg,r$e,o$e,i$e,a$e,s$e,d$e,u$e,l$e,Ev=B(()=>{"use strict";nY();os();tY=200,Sg="claude_oauth_expired",r$e=[/\bAPI Error:?\s*([1-5]\d{2})\b/i,/\b(?:HTTP|status(?:\s+code)?)[\s:]+([1-5]\d{2})\b/i],o$e=[/"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/],i$e=/"error"\s*:\s*\{[^{}]*?"message"\s*:\s*"((?:[^"\\]|\\.){1,500})"/,a$e=/\boauth\b[\s\S]{0,120}?\b(?:expired|revoked|could not be refreshed)\b/i;s$e=/"code"\s*:\s*"provider_outage"/,d$e=/"hold_ceiling_minutes"\s*:\s*(\d{1,4})\b/,u$e=/"provider"\s*:\s*"([^"]{1,100})"/,l$e=/"model"\s*:\s*"([^"]{1,100})"/});function CT(e){return e!==void 0&&h$e.has(e)}function v$e(e){if(e===void 0)return;let n=b(e.type);if(n!=="mcpToolCall"&&n!=="dynamicToolCall"&&n!=="collabAgentToolCall"||b(e.status)!=="completed"||e.error!==void 0&&e.error!==null||e.success===!1)return;let t=b(e.tool)??"";return(t.split("__").pop()??t)===y$e?"reply":"action"}function fY(e,n){let t=v$e(n);t==="reply"?e.agentReplyToolCallSeen=!0:t==="action"&&(e.agentActionToolCallSeen=!0)}function w$e(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 S$e(e){return e!=="reasoning"}function k$e(e){return e!==void 0&&e.startsWith(pY)}function C$e(e){for(let n of e){let t=mY(O(n));if(t!==void 0)return t}}function mY(e){if(e===void 0)return;let n=b(e.codex_protocol_failure_reason)??b(e.protocolFailureReason);if(n!==void 0)return n;let t=b(e.type);if(t!=="function_call_output"&&t!=="custom_tool_call_output")return;let r=b(e.output)??b(e.result)??b(e.text)??b(e.content),o=T$e(r);return o===void 0?void 0:`${pY}: ${o}`}function T$e(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 hY(){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 gY(e,n,t){let r=[];return e.phase==="running"&&H$e(e,t,r),yY(e,n,t,r),r}function yY(e,n,t,r){if(n.source==="lifecycle"){q$e(e,n.kind,n.reason,t,r);return}if(e.phase==="dead"){r.push(dt("pipeline.loop.event_after_death",{source:n.source}));return}if(e.phase==="closing"){r.push(dt("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}W$e(e,n.turnId,n.snapshot,t,r);return}E$e(e,n,t,r)}function R$e(e){return I$e.has(e)}function E$e(e,n,t,r){let o=n.notification.method,i=n.notification.params??{};if(o===Ov)return;if(o===Cg){J$e(e,i,t,r);return}if(!A$e.has(o))return;let s=Rv(i)??AT(e);if(s===void 0){r.push(dt("pipeline.loop.notification_without_turn",{method:o}));return}if(e.terminalTurnIds.has(s)){r.push(dt("pipeline.loop.notification_for_terminal_turn",{method:o,turn_id:s}));return}let d=e.turns.get(s);if(d===void 0){let p=t.sourceSeqForTurn(s);if(p===void 0){V$e(e,s,n,r);return}d=$$e(e,s,p)}if(d.notificationCount+=1,R$e(o)&&(d.modelInteractionSeen=!0,d.unresolvedUpstreamErrorHttpStatus=void 0),o==="turn/started")return;if(o==="turn/completed"){F$e(d,r);return}let u=P$e.get(o);if(u!==void 0){let p=B$e(o,i,d,{costCap402Seen:e.costCap402Seen,midStreamResumeAttemptAtMs:t.midStreamResumeAttemptAtMsForSeq?.(d.sourceSeq),freshSessionResumeAttemptAtMs:t.freshSessionResumeAttemptAtMsForSeq?.(d.sourceSeq)});p.autoResumeMidStreamStall?r.push(dt("codex.mid_stream_stall_auto_resume_flagged",{thread_key:t.threadKey,turn_id:d.turnId,source_seq:d.sourceSeq,reason:cp(i)})):p.midStreamResumeRateLimitSuppressed?r.push(dt("codex.mid_stream_stall_resume_suppressed_rate_limit",{thread_key:t.threadKey,turn_id:d.turnId,source_seq:d.sourceSeq,reason:cp(i)})):p.midStreamResumeAttemptBurnedAtMs!==void 0&&(r.push(dt("codex.mid_stream_stall_second_stall_after_resume",{thread_key:t.threadKey,turn_id:d.turnId,source_seq:d.sourceSeq,resume_attempt_at_ms:p.midStreamResumeAttemptBurnedAtMs,reason:cp(i),fresh_session_resume_granted:p.freshSessionResumeMidStreamStall===!0})),p.freshSessionResumeMidStreamStall===!0&&r.push(dt("codex.mid_stream_stall_fresh_session_resume_flagged",{thread_key:t.threadKey,turn_id:d.turnId,source_seq:d.sourceSeq,resume_attempt_at_ms:p.midStreamResumeAttemptBurnedAtMs,reason:cp(i)}))),p.autoRetryPreFirstByteStall?r.push(dt("codex.pre_first_byte_stall_auto_retry_flagged",{thread_key:t.threadKey,turn_id:d.turnId,source_seq:d.sourceSeq,reason:cp(i),phase:b(i.idleStreamPhase)??"pre_first_byte",idle_threshold_ms:ie(i.idleStreamThresholdMs)??null,evidence_class:Z2(d)})):p.costCapAutoRetrySuppressed&&r.push(dt("codex.pre_first_byte_stall_retry_suppressed_cost_cap",{thread_key:t.threadKey,turn_id:d.turnId,source_seq:d.sourceSeq,reason:cp(i),flavor:i.midStreamResumableStall===!0?"mid_stream_resume":"pre_first_byte_retry"})),TT(e,d,u,cp(i),r,t,u,p,o===Dv?"interrupted":"failed");return}if(o==="error"){d.errorNotificationCount+=1;let p=SFe(i);p!==void 0&&(d.toolFatalSeen=!0,d.toolFatalDetail===void 0&&p!==""&&(d.toolFatalDetail=p),r.push(dt("codex.tool_fatal_captured",{turn_id:d.turnId,detail:p===""?null:p})));let h=cFe(i);h!==void 0&&(d.upstreamRejectedSeen=!0,d.upstreamRejectedDetail===void 0&&h!==""&&(d.upstreamRejectedDetail=h),r.push(dt("codex.upstream_rejection_captured",{turn_id:d.turnId,detail:h===""?null:h})));let y=hFe(i);if(y!==void 0){d.providerOutageFlaggedSeen=!0,d.providerOutageDetail===void 0&&y!==""&&(d.providerOutageDetail=y);let T=gFe(i);d.providerOutageRoute===void 0&&(d.providerOutageRoute=T),r.push(dt("codex.provider_outage_flagged_captured",{turn_id:d.turnId,detail:y===""?null:y,provider:T?.provider??null,model:T?.model??null,hold_ceiling_ms:T?.holdCeilingMs??null}))}let m=IT(i),_=Y$e(i);_!==void 0&&(d.edgeBlockEvidence=_),m!==void 0&&(d.lastUpstreamErrorHttpStatus===void 0||m>d.lastUpstreamErrorHttpStatus)&&(d.lastUpstreamErrorHttpStatus=m),m===402&&!e.costCap402Seen&&(e.costCap402Seen=!0,r.push(dt("codex.cost_cap_402_seen",{turn_id:d.turnId})));let w=Z$e(i),v=!1;if(w!==void 0)d.lastUpstreamErrorReason=w,r.push(dt("codex.upstream_error_captured",{turn_id:d.turnId,reason:w}));else{let T=qv(i);T!==void 0&&(d.lastErrorDiagnosticText=T,v=!0,r.push(dt("codex.error_without_http_status_captured",{turn_id:d.turnId,diagnostic_text:T})))}p===void 0&&h===void 0&&y===void 0&&m===void 0&&w===void 0&&!v&&(d.unattributedErrorNotificationCount+=1);let S=uFe(i);S!==void 0&&(d.lastUpstreamErrorSummary=S,e.lastUpstreamErrorSummary=S,r.push(dt("codex.upstream_turn_error_captured",{turn_id:d.turnId,upstream_error:S})));let C=[w,S,d.lastErrorDiagnosticText].some(T=>T!==void 0&&Y2.test(T))?429:void 0,A=m??C;A!==void 0&&(d.unresolvedUpstreamErrorHttpStatus=A);return}if(o==="item/started"){let p=O(i.item),h=b(p?.id),y=p?.phase,m=b(y);p!==void 0&&b(p.type)==="agentMessage"&&(h!==void 0&&p.delivery==="async"&&(d.asyncAssistantItemIds.add(h),d.assistantPhasesByItemId.set(h,"commentary")),m==="commentary"||m==="final_answer"?h!==void 0&&d.assistantPhasesByItemId.set(h,u2(p)):y!==void 0&&r.push(dt("harness.assistant_phase_rejected",{turn_id:s,...h===void 0?{}:{item_id:h},phase:y})))}let c=M$e(o,i,d);if(c!==void 0){uY(d,{...i,item:c},t,r);return}if(o==="item/completed"||o==="response_item"){uY(d,i,t,r);return}let l=i;if(o==="item/agentMessage/delta"){let p=xg(i);p!==void 0&&(i.delivery==="async"||O(i.item)?.delivery==="async")&&(d.asyncAssistantItemIds.add(p),d.assistantPhasesByItemId.set(p,"commentary"));let h=i.phase??O(i.item)?.phase,y=b(h);if(y==="commentary"||y==="final_answer"){if(p!==void 0){let _=d.asyncAssistantItemIds.has(p)?"commentary":y;d.assistantPhasesByItemId.set(p,_),l={...i,phase:_}}}else if(h!==void 0)r.push(dt("harness.assistant_phase_rejected",{turn_id:s,...p===void 0?{}:{item_id:p},phase:h}));else if(p!==void 0){let m=d.assistantPhasesByItemId.get(p);m!==void 0&&(l={...i,phase:m})}}let f=WX(o,l);if(f===void 0){if(o==="turn/plan/updated"){let p=b(i.threadId);r.push(dt("harness.plan_snapshot_rejected",{turn_id:s,...p===void 0?{}:{thread_id:p}}))}return}if(d.phase==="active"){if(S$e(f.streamKind))d.reasoningStepsWithoutProgress=0;else if(d.reasoningStepsWithoutProgress+=1,d.reasoningStepsWithoutProgress>dY){let p=w$e(d.reasoningStepsWithoutProgress);r.push(dt("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:dY})),TT(e,d,"failed",p,r,t,"interrupted");return}}SY(d,f,t,r)}function M$e(e,n,t){let r=O(n.item),o=b(r?.id),i=b(n.turnId),a=ie(n.completedAtMs)??ie(n.startedAtMs);if((e==="item/started"||e==="item/completed")&&b(r?.type)==="contextCompaction"&&o!==void 0){let s=e==="item/started",d=s?"START":"END",u=O$e(t,o);return{type:"agentStatus",id:`${o}:${s?"start":"complete"}`,title:s?"Context compaction started":"Context compaction completed",severity:"info",provider:"codex",eventKind:"compaction_boundary",dividerKind:"context_compaction",dividerIdentity:u,...a===void 0?{}:{occurredAtMs:a},rawProviderMetadata:{phase:d,lifecycle:e,harness:"codex",compactionItemId:o,...i===void 0?{}:{turnId:i}}}}if(e==="thread/compacted"&&i!==void 0){let s=t.compactionThreadEventIndex;return t.compactionThreadEventIndex+=1,{type:"agentStatus",id:s===0?`thread-compacted:${i}`:`thread-compacted:${i}:${s}`,title:"Thread compacted",severity:"info",provider:"codex",eventKind:"compaction_boundary",dividerKind:"context_compaction",dividerIdentity:D$e(t),rawProviderMetadata:{phase:"END",lifecycle:e,harness:"codex",turnId:i}}}}function O$e(e,n){let t=e.compactionDividerIdentities.get(n);if(t!==void 0)return e.lastCompactionItemId=n,t;let r=e.lastCompactionItemId===void 0&&e.compactionFallbackIdentity!==void 0?e.compactionFallbackIdentity:`agent_status_event:context_compaction:${e.turnId}:${n}`;return e.compactionDividerIdentities.set(n,r),e.lastCompactionItemId=n,r}function D$e(e){let n=e.lastCompactionItemId===void 0?void 0:e.compactionDividerIdentities.get(e.lastCompactionItemId);if(e.lastCompactionItemId=void 0,n!==void 0)return e.compactionFallbackIdentity=void 0,n;e.compactionFallbackIndex+=1;let t=`agent_status_event:context_compaction:${e.turnId}:fallback:${e.compactionFallbackIndex}`;return e.compactionFallbackIdentity=t,t}function q$e(e,n,t,r,o){if(n==="codexDied"){if(e.phase==="dead")return;for(let i of[...e.turns.values()])TT(e,i,"failed",t,o,r,"interrupted");for(let i of[...e.bufferedTurns.keys()])wY(e,i,t,o);e.phase="dead",o.push(dt("pipeline.loop.codex_died",{reason:t}));return}e.phase==="running"&&(e.phase="closing",o.push(dt("pipeline.loop.closing",{kind:n,reason:t})))}function $$e(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,compactionDividerIdentities:new Map,lastCompactionItemId:void 0,compactionFallbackIdentity:void 0,compactionFallbackIndex:0,compactionThreadEventIndex:0,assistantPhasesByItemId:new Map,asyncAssistantItemIds:new Set,items:[]};return e.turns.set(n,r),r}function F$e(e,n){if(e.phase==="completing"){n.push(dt("pipeline.loop.duplicate_turn_completed",{turn_id:e.turnId}));return}e.phase="completing",n.push({type:"requestSnapshot",turnId:e.turnId})}function _Y(e){return e===429||e>=500&&e<=599?"transient":"deterministic"}function e$(){return process.env.LINZUMI_DISABLE_UPSTREAM_ERROR_TURN_FATE_FIX==="1"}function N$e(e){let n=bY.exec(e);return n!==null?_Y(Number(n[1])):!e$()&&Y2.test(e)||j$e.test(e)?"transient":"deterministic"}function Z2(e){let n=!1,t=e.upstreamRejectedSeen||e.providerOutageFlaggedSeen||e.toolFatalSeen||e.modelInteractionSeen||e.unattributedErrorNotificationCount>0,r=0;e.lastUpstreamErrorHttpStatus!==void 0&&(r+=1,_Y(e.lastUpstreamErrorHttpStatus)==="transient"?n=!0:t=!0);for(let o of[e.lastUpstreamErrorReason,e.lastErrorDiagnosticText])o!==void 0&&(r+=1,N$e(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 Q2(e){if(e.lastUpstreamErrorHttpStatus===429)return!0;for(let n of[e.lastUpstreamErrorReason,e.lastErrorDiagnosticText]){if(n===void 0)continue;let t=bY.exec(n);if(t!==null&&Number(t[1])===429||!e$()&&Y2.test(n))return!0}return!1}function z$e(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 G$e(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 U$e(e){return` (An automatic resume was attempted at ${new Date(e).toISOString()} after the stream stalled; it did not complete.)`}function B$e(e,n,t,r={costCap402Seen:!1}){let o=e==="turn/failed"&&b(O(n.error)?.code)==="idle_stream_timeout",i=e==="turn/failed"&&n.retryable===!0,a=(e==="turn/failed"||e==="turn/aborted")&&as(n.fate)?n.fate:void 0,s=(()=>{if(e!=="turn/failed")return;let M=O(n.route_outage_hold);if(M===void 0)return;let I=ie(M.hold_ceiling_ms);return{provider:b(M.provider),model:b(M.model),holdCeilingMs:I!==void 0&&I>0?I:void 0}})(),d=e==="turn/failed"&&n.failure_class===Sg?Sg:void 0;if(!o)return{autoRetryPreFirstByteStall:!1,messageStateRetryable:i,costCapAutoRetrySuppressed:!1,messageStateFate:a,messageStateFailureClass:d,autoResumeMidStreamStall:!1,midStreamResumeRateLimitSuppressed:!1,...s===void 0?{}:{messageStateRouteOutageHold:s}};let u=r.midStreamResumeAttemptAtMs,c=u!==void 0,l=Z2(t)!=="deterministic",f=n.preFirstByteStall===!0&&l,p=n.midStreamResumableStall===!0,h=p&&Q2(t),y=Z2({...t,modelInteractionSeen:!1})!=="deterministic",m=p&&!c&&!h&&y,_=r.freshSessionResumeAttemptAtMs!==void 0,w=p&&c&&!_&&!h&&y,v=(f&&!c||m||w)&&r.costCap402Seen,S=f&&!c&&!v,C=m&&!v,A=w&&!v,T=p&&!c&&h;return{autoRetryPreFirstByteStall:S,messageStateRetryable:f||i,costCapAutoRetrySuppressed:v,messageStateFate:a??(Q2(t)?"rate_limited":"transient_upstream"),messageStateFailureClass:d,autoResumeMidStreamStall:C,midStreamResumeRateLimitSuppressed:T,...c?{midStreamResumeAttemptBurnedAtMs:u}:{},...A?{freshSessionResumeMidStreamStall:!0}:{}}}function xY(e){return e>0?` (${e} automatic ${e===1?"retry":"retries"} did not help.)`:""}function TT(e,n,t,r,o,i,a=t,s={autoRetryPreFirstByteStall:!1,messageStateRetryable:!1,costCapAutoRetrySuppressed:!1,messageStateFate:void 0,messageStateFailureClass:void 0,autoResumeMidStreamStall:!1,midStreamResumeRateLimitSuppressed:!1},d="failed"){let u=TY(s.messageStateFate,i,{sourceSeq:n.sourceSeq,upstreamHttpStatus:n.lastUpstreamErrorHttpStatus}),c=s.autoRetryPreFirstByteStall||s.costCapAutoRetrySuppressed?`${r}${xY(i.autoRetryAttemptsForSeq?.(n.sourceSeq)??0)}${s.costCapAutoRetrySuppressed?vY:""}`:r;if(s.midStreamResumeRateLimitSuppressed&&(c+=L$e),t==="failed")if(s.midStreamResumeAttemptBurnedAtMs!==void 0)c+=s.freshSessionResumeMidStreamStall===!0?G$e(s.midStreamResumeAttemptBurnedAtMs):z$e(s.midStreamResumeAttemptBurnedAtMs);else{let f=i.midStreamResumeAttemptAtMsForSeq?.(n.sourceSeq);f!==void 0&&(c+=U$e(f))}for(let f of n.items){if(!f.posted||CT(f.emittedStreamState))continue;let p=wg(f.wireItemKey,f.content,a);o.push({type:"enqueue",kind:Qt.finalizeRow,data:{...PT(i,n,f,p),stream_snapshot_index:Mv(f),terminal_outcome:t,reason:r},resolution:"must_ack"}),f.emittedStreamState=a,f.lastEmittedBody=p.body}let l=i.sessionExecutesRecoveryGrants===!0&&t==="failed"&&(s.autoRetryPreFirstByteStall||s.autoResumeMidStreamStall||s.freshSessionResumeMidStreamStall===!0);o.push({type:"enqueue",kind:Qt.messageState,data:{thread_key:i.threadKey,turn_id:n.turnId,seq:n.sourceSeq,status:l?"recovering":d,reason:c,...s.messageStateRetryable&&!l?{retryable:!0}:{},...u===void 0?{}:{fate:u},...s.messageStateFailureClass===void 0?{}:{failure_class:s.messageStateFailureClass},...(()=>{let f=u===void 0?void 0:i.ladderHistoryForSeq?.(n.sourceSeq,u);return f===void 0?{}:{ladder:f}})(),...(()=>{let f=n.lastUpstreamErrorSummary??e.lastUpstreamErrorSummary;return f===void 0?{}:{upstream_error:f}})()},resolution:d==="interrupted"?"must_reach_consensus":"must_ack"}),o.push({type:"turnTerminal",turnId:n.turnId,outcome:t,reason:c,...s.autoRetryPreFirstByteStall?{retryableEmptyTurn:!0}:{},...s.autoResumeMidStreamStall?{autoResumeMidStreamStall:!0}:{},...s.freshSessionResumeMidStreamStall?{freshSessionResumeMidStreamStall:!0}:{},...u===void 0?{}:{fate:u},...u==="route_outage"?{routeOutageHold:{provider:s.messageStateRouteOutageHold?.provider,model:s.messageStateRouteOutageHold?.model,holdCeilingMs:s.messageStateRouteOutageHold?.holdCeilingMs}}:{}}),e.turns.delete(n.turnId),n$(e,n.turnId)}function J$e(e,n,t,r){let o=b(n.turnId),i=b(n.reason)??"turn source-seq mapping failed";if(o===void 0||e.terminalTurnIds.has(o))return;let a=e.turns.get(o);if(a!==void 0){TT(e,a,"failed",i,r,t);return}wY(e,o,i,r)}function wY(e,n,t,r){let o=e.bufferedTurns.get(n),i=o?.length??0,a=o?.[0],s=o?.[i-1];r.push({type:"enqueue",kind:Qt.unmappedTurnFailure,data:{turn_id:n,buffered_event_count:i,first_event:kT(a),last_event:kT(s),reason:"A response was produced but could not be delivered because its turn source mapping never arrived. Please retry."},coalesceKey:`unmapped-turn-failure:${n}`,resolution:"must_ack"}),r.push(dt("pipeline.loop.buffered_turn_failed",{level:"error",turn_id:n,buffered_event_count:i,first_event:kT(a),last_event:kT(s),reason:t})),e.bufferedTurns.delete(n),r.push({type:"turnTerminal",turnId:n,outcome:"failed",reason:t}),n$(e,n)}function kT(e){return e===void 0?"none":e.source==="codex"?e.notification.method:e.source==="snapshot"?"snapshot":`lifecycle/${e.kind}`}function SY(e,n,t,r){if(e.phase!=="active"){r.push(dt("pipeline.loop.delta_for_completing_turn",{turn_id:e.turnId,stream_kind:n.streamKind}));return}let o=CY(e,n.streamKind,n.itemId,t);if(o.completed){r.push(dt("pipeline.loop.delta_for_completed_item",{turn_id:e.turnId,item_key:o.itemKey}));return}o.content=HX(o.content,n);let i=o.nextDeltaIndex;o.nextDeltaIndex+=1;let a=n.streamKind==="terminalInput"?"completed":"streaming";kY(e,o,i,a,t,r)}function uY(e,n,t,r){let o=O(n.item);o!==void 0&&(e.protocolFailureReason??=mY(o)),fY(e,o??n);let i=ZX(n);if(i===void 0)return;if(i.streamKind==="webSearch"){SY(e,{streamKind:"webSearch",itemId:i.itemId,queries:i.content.streamKind==="webSearch"?i.content.queries:[]},t,r);return}if(e.phase!=="active"){r.push(dt("pipeline.loop.item_completed_for_completing_turn",{turn_id:e.turnId,stream_kind:i.streamKind}));return}let a=CY(e,i.streamKind,i.itemId,t,{adoptOpenIdLess:!0});if(a.completed&&!K$e(a,i))return;a.content=i.content,a.completed=!0;let s="completed",d=wg(a.wireItemKey,a.content,s);a.posted&&d.body===a.lastEmittedBody&&CT(a.emittedStreamState)||kY(e,a,Math.max(a.nextDeltaIndex-1,0),s,t,r)}function K$e(e,n){return e.identity.streamKind!==n.streamKind?!1:n.streamKind==="agentStatus"||n.streamKind==="agentTaskUpdate"}function kY(e,n,t,r,o,i){let a=wg(n.wireItemKey,n.content,r);if(!n.posted){if(a.body.trim()==="")return;i.push({type:"enqueue",kind:Qt.postStreamedRow,data:{...PT(o,e,n,a),delta_index:t,stream_snapshot_index:Mv(n)},resolution:"must_ack"}),n.posted=!0,n.emittedStreamState=r,n.lastEmittedBody=a.body,r==="completed"&&(n.completed=!0);return}i.push({type:"enqueue",kind:Qt.streamSnapshot,data:{...PT(o,e,n,a),delta_index:t,stream_snapshot_index:Mv(n)},coalesceKey:n.itemKey,resolution:"must_ack"}),n.emittedStreamState=r,n.lastEmittedBody=a.body}function CY(e,n,t,r,o={adoptOpenIdLess:!1}){if(n==="webSearch")return e.items.find(a=>a.identity.streamKind==="webSearch")??lY(e,"webSearch",`web-search:${e.turnId}`,r);if(t!==void 0){let a=e.items.find(s=>s.identity.streamKind===n&&s.identity.itemId===t);if(a!==void 0)return a}let i=e.items.find(a=>a.identity.streamKind===n&&a.identity.itemId===void 0&&!a.completed);return t===void 0&&i!==void 0||t!==void 0&&o.adoptOpenIdLess&&i!==void 0?i:lY(e,n,t,r)}function lY(e,n,t,r){let o={turnId:e.turnId,itemId:t,itemIndex:e.items.length,streamKind:n},i=bX(o),a=t??i,s={identity:o,itemKey:i,wireItemKey:a,clientMessageId:W2(r.instanceId,e.turnId,n,a),content:VX(n),posted:!1,completed:!1,emittedStreamState:void 0,lastEmittedBody:void 0,nextDeltaIndex:0,nextStreamSnapshotIndex:1};return e.items.push(s),s}function W$e(e,n,t,r,o){if(e.terminalTurnIds.has(n)){o.push(dt("pipeline.loop.duplicate_snapshot",{turn_id:n}));return}let i=e.turns.get(n);if(i===void 0){o.push(dt("pipeline.loop.snapshot_for_unknown_turn",{turn_id:n}));return}if(i.phase!=="completing"){o.push(dt("pipeline.loop.snapshot_for_active_turn",{turn_id:n}));return}let a=Array.isArray(t.items)?t.items:[];i.protocolFailureReason??=C$e(a);for(let te of a)fY(i,O(te));let s=XX(a),d=new Set,u=new Map;s.forEach((te,he)=>{if(te.itemId===void 0)return;let me=i.items.find(Se=>Se.posted&&!d.has(Se.itemKey)&&Se.identity.streamKind===te.streamKind&&Se.identity.itemId===te.itemId);me!==void 0&&(d.add(me.itemKey),u.set(he,me))});let c=new Map;for(let te of i.items)te.posted&&!d.has(te.itemKey)&&te.identity.itemId===void 0&&c.set(te.identity.streamKind,(c.get(te.identity.streamKind)??0)+1);let l=new Map;s.forEach((te,he)=>{u.has(he)||l.set(te.streamKind,(l.get(te.streamKind)??0)+1)});let f=(te,he)=>{let me=wg(te.wireItemKey,te.content,"completed").body.trim(),Se=he.body.trim();return Se.startsWith(me)||me.startsWith(Se)};s.forEach((te,he)=>{if(u.has(he))return;let me=l.get(te.streamKind)===c.get(te.streamKind);if(te.itemId!==void 0&&!me)return;let Se=i.items.find(Ie=>Ie.posted&&!d.has(Ie.itemKey)&&Ie.identity.streamKind===te.streamKind&&Ie.identity.itemId===void 0);Se!==void 0&&(te.itemId!==void 0&&!f(Se,te)||(d.add(Se.itemKey),u.set(he,Se)))});for(let te of i.items){let he=[...u.entries()].find(([,Se])=>Se.itemKey===te.itemKey);if(he!==void 0){let Se=s[he[0]];if(Se===void 0||te.identity.streamKind==="assistant"&&CT(te.emittedStreamState)&&te.lastEmittedBody===Se.body)continue;o.push({type:"enqueue",kind:Qt.finalizeRow,data:{thread_key:r.threadKey,turn_id:i.turnId,item_key:te.itemKey,item_id:te.wireItemKey,stream_kind:te.identity.streamKind,item_index:te.identity.itemIndex,source_seq:i.sourceSeq,client_message_id:te.clientMessageId,body:Se.body,structured:{...K2(Se.structured,te.wireItemKey),...te.completed?{}:{completion_provenance:"end_of_turn_finalize"}},stream_snapshot_index:Mv(te),terminal_outcome:"completed"},resolution:"must_ack"}),te.emittedStreamState="completed",te.lastEmittedBody=Se.body;continue}if(!te.posted||CT(te.emittedStreamState))continue;let me=wg(te.wireItemKey,te.content,"completed");o.push({type:"enqueue",kind:Qt.finalizeRow,data:{...PT(r,i,te,{...me,structured:{...me.structured,completion_provenance:"end_of_turn_finalize"}}),stream_snapshot_index:Mv(te),terminal_outcome:"completed"},resolution:"must_ack"}),te.emittedStreamState="completed",te.lastEmittedBody=me.body}s.forEach((te,he)=>{if(u.has(he))return;let me=te.itemId??`${i.turnId}:${te.streamKind}:snapshot:${te.snapshotIndex}`;o.push({type:"enqueue",kind:Qt.postCompletedRow,data:{thread_key:r.threadKey,turn_id:i.turnId,item_key:`${i.turnId}:${te.streamKind}:${te.itemId??`snapshot:${te.snapshotIndex}`}`,item_id:me,stream_kind:te.streamKind,snapshot_index:te.snapshotIndex,source_seq:i.sourceSeq,client_message_id:W2(r.instanceId,i.turnId,te.streamKind,me),body:te.body,structured:K2(te.structured,me),stream_snapshot_index:1},resolution:"must_ack"})});let p=i.items.some(te=>te.identity.streamKind==="assistant"&&te.posted)||s.some(te=>te.streamKind==="assistant"),h=i.agentActionToolCallSeen||i.items.some(te=>te.posted&&aY.has(te.identity.streamKind)&&!(te.content.streamKind==="agentStatus"&&(te.content.severity==="error"||te.content.providerItemType==="sleep")))||s.some(te=>te.providerItemType!=="sleep"&&aY.has(te.streamKind)&&!(te.streamKind==="agentStatus"&&te.structured.severity==="error")),y=r.linzumiAgentSession===!0&&p&&!i.agentReplyToolCallSeen&&!h,m=p&&!y,_=m&&!e$()?i.unresolvedUpstreamErrorHttpStatus:void 0,w=_!==void 0,v=i.protocolFailureReason,S=v!==void 0&&k$e(v)&&m,C=S?void 0:v,A=!m&&v===void 0&&i.lastUpstreamErrorReason===void 0?y?{cause:b$e}:kFe(i,s.length,i.lastUpstreamErrorSummary??e.lastUpstreamErrorSummary):void 0,T=!m&&C===void 0&&i.upstreamRejectedSeen,M=!m&&C===void 0&&i.providerOutageFlaggedSeen,I=nFe(i.lastUpstreamErrorHttpStatus),P=!m&&C===void 0&&i.edgeBlockEvidence!==void 0,z=T&&!M&&!I,$=M||z?bFe({providerOutageFlagged:M,priorConsecutiveIsolatedRejections:e.consecutiveIsolatedRejections,stormDetail:i.providerOutageDetail,rejectionDetail:i.upstreamRejectedDetail}):void 0,J=$?.kind==="isolated_retry";z?e.consecutiveIsolatedRejections+=1:e.consecutiveIsolatedRejections=0;let Q=!m&&C===void 0&&i.lastUpstreamErrorReason===void 0&&i.lastErrorDiagnosticText===void 0&&!T&&eFe(i.lastUpstreamErrorHttpStatus),K=!m&&C===void 0&&i.lastUpstreamErrorReason===void 0&&I,Z=!m&&C===void 0&&i.lastUpstreamErrorReason===void 0&&!T&&!Q&&!K&&i.toolFatalSeen,N=$!==void 0?$.reason:K?tFe(i.lastUpstreamErrorHttpStatus,i.upstreamRejectedDetail??i.lastErrorDiagnosticText):Q?rFe(i.lastUpstreamErrorHttpStatus):Z?iFe(i.toolFatalDetail):i.lastUpstreamErrorReason??(y?_$e:A===void 0?iY:`${iY} [${A.cause}]`),W=A!==void 0&&C===void 0&&i.modelInteractionSeen&&i.lastErrorDiagnosticText===void 0&&!T&&!Q&&!K&&!Z;W?(e.consecutiveEmptyTurns+=1,e.lastEmptyTurnCause=A?.cause):(e.consecutiveEmptyTurns=0,e.lastEmptyTurnCause=void 0);let ee=W&&e.consecutiveEmptyTurns>sY,ne=W&&!ee||J,ye=r.autoRetryAttemptsForSeq?.(i.sourceSeq)??0,L=ne&&e.costCap402Seen&&ye<Da,ce=ne&&!L;P&&o.push(dt("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 pe=ee?`${x$e} (${e.consecutiveEmptyTurns} in a row${A===void 0?"":`: ${A.cause}`}).`:void 0,re=C??(_!==void 0?oFe(_,i.lastUpstreamErrorSummary??e.lastUpstreamErrorSummary):m?void 0:pe??N),le=re===void 0?void 0:`${re}${xY(W&&!ee?ye:0)}${L?vY:""}`,Oe=A!==void 0&&!ee&&!T&&!Q&&!K&&!Z||J||P||w,F=M?"route_outage":_!==void 0?C2(_):Oe?"transient_upstream":Q?i.lastUpstreamErrorHttpStatus===void 0?"transient_upstream":C2(i.lastUpstreamErrorHttpStatus):T||Z||K||ee||C!==void 0?"deterministic":Q2(i)?"rate_limited":"deterministic",H=TY(F,r,{sourceSeq:i.sourceSeq,upstreamHttpStatus:_??i.lastUpstreamErrorHttpStatus})??F;L&&o.push(dt("codex.empty_turn_auto_retry_suppressed_cost_cap",{thread_key:r.threadKey,turn_id:i.turnId,source_seq:i.sourceSeq,reason:re??null,isolated_rejection_retry_suppressed:J})),ee&&o.push(dt("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:sY,cause:A?.cause??null,last_upstream_error:i.lastUpstreamErrorSummary??e.lastUpstreamErrorSummary??null})),S?o.push(dt("codex.turn_completed_with_unsupported_tool_call_ignored",{thread_key:r.threadKey,turn_id:i.turnId,source_seq:i.sourceSeq,reason:v})):v!==void 0&&o.push(dt("codex.turn_completed_with_protocol_failure",{thread_key:r.threadKey,turn_id:i.turnId,source_seq:i.sourceSeq,reason:v})),y&&o.push(dt("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:s.length,agent_reply_tool_call_seen:i.agentReplyToolCallSeen,agent_action_tool_call_seen:i.agentActionToolCallSeen,retryable_empty_turn:Oe,empty_turn_loop_guard_tripped:ee})),w&&o.push(dt("codex.turn_demoted_late_upstream_error",{thread_key:r.threadKey,turn_id:i.turnId,source_seq:i.sourceSeq,http_status:_??null,fate:H,streamed_item_count:i.items.length,last_upstream_error:i.lastUpstreamErrorSummary??e.lastUpstreamErrorSummary??null})),p||o.push(dt("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:s.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:A?.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:K,last_upstream_error_http_status:i.lastUpstreamErrorHttpStatus??null,provider_outage_flagged:M,isolated_rejection_retry_granted:J,rejection_disposition:$?.kind??null,consecutive_isolated_rejections:e.consecutiveIsolatedRejections,retryable_empty_turn:Oe,empty_turn_loop_guard_tripped:ee,cost_cap_auto_retry_suppressed:L}));let V=r.sessionExecutesRecoveryGrants===!0&&ce;o.push({type:"enqueue",kind:Qt.messageState,data:{thread_key:r.threadKey,turn_id:i.turnId,seq:i.sourceSeq,...le===void 0?{status:"processed"}:{status:V?"recovering":"failed",reason:le,...Oe&&!V?{retryable:!0}:{},fate:H,...(()=>{let te=r.ladderHistoryForSeq?.(i.sourceSeq,H);return te===void 0?{}:{ladder:te}})(),...P?{failure_class:"edge_blocked"}:{},...(()=>{let te=i.lastUpstreamErrorSummary??e.lastUpstreamErrorSummary;return te===void 0?{}:{upstream_error:te}})()}},resolution:"must_ack"}),le===void 0&&(e.lastUpstreamErrorSummary=void 0),o.push(le===void 0?{type:"turnTerminal",turnId:i.turnId,outcome:"completed"}:{type:"turnTerminal",turnId:i.turnId,outcome:"failed",reason:le,...ce?{retryableEmptyTurn:!0}:{},fate:H,...H==="route_outage"?{routeOutageHold:{provider:i.providerOutageRoute?.provider,model:i.providerOutageRoute?.model,holdCeilingMs:i.providerOutageRoute?.holdCeilingMs}}:{}}),e.turns.delete(i.turnId),n$(e,i.turnId)}function V$e(e,n,t,r){let o=e.bufferedTurns.get(n);if(o===void 0){e.bufferedTurns.set(n,[t]),r.push(dt("pipeline.loop.turn_events_buffered",{turn_id:n}));return}o.push(t)}function H$e(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(dt("pipeline.loop.buffered_turn_drained",{turn_id:r,buffered_event_count:o.length}));for(let i of o)yY(e,i,n,t)}}function n$(e,n){for(e.terminalTurnIds.delete(n),e.terminalTurnIds.add(n);e.terminalTurnIds.size>g$e;){let t=e.terminalTurnIds.values().next().value;if(t===void 0)return;e.terminalTurnIds.delete(t)}}function AT(e){let n=[...e.turns.values()].filter(t=>t.phase==="active");return n.length===1?n[0]?.turnId:void 0}function PT(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 Mv(e){let n=e.nextStreamSnapshotIndex;return e.nextStreamSnapshotIndex+=1,n}function cp(e){return b(e.reason)??b(e.message)??b(O(e.error)?.message)??b(e.error)??"codex_turn_aborted"}function Z$e(e){let n=b(e.diagnostic_summary)??b(O(O(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=IT(e);return r===void 0?`Model gateway error: ${t}`:`Model gateway error (HTTP ${r}): ${t}`}function IT(e){let n=O(O(e.diagnostic_payload)?.error),t=O(n?.codexErrorInfo),o=[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 Q$e(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 X$e(e){return/(?:<!doctype\s+html|<html(?:\s|>))/i.test(e)||/@font-face/i.test(e)&&/cloudflare|cf-ray/i.test(e)}function Y$e(e){let n=O(O(e.diagnostic_payload)?.error),t=[b(e.diagnostic_summary),b(n?.message),b(e.message)],r=IT(e)??Q$e(t);if(r!==401&&r!==403)return;let o=t.find(a=>a!==void 0&&X$e(a)&&/cloudflare|cf-ray|\bblocked\b|access denied|\bchallenge\b|attention required/i.test(a));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 eFe(e){return e===void 0?!1:e===402||e===408||e===425||e===429||e>=500&&e<=599}function nFe(e){return e===void 0||e<400||e>499?!1:e!==402&&e!==408&&e!==425&&e!==429}function tFe(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 rFe(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 oFe(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 iFe(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 qv(e){let n=O(O(e.diagnostic_payload)?.error),t=b(e.message)??b(e.reason)??b(O(e.error)?.message)??b(e.error)??b(e.diagnostic)??b(n?.message)??b(O(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 kg(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 uFe(e){let n=O(e.error),t=O(O(e.diagnostic_payload)?.error),r=O(t?.error),o=IT(e),i=b(n?.type)??b(n?.code)??b(t?.type)??b(t?.code)??b(r?.type)??b(r?.code)??cY(n?.codexErrorInfo)??cY(t?.codexErrorInfo),a=kg(b(n?.message))??kg(b(r?.message))??kg(b(t?.message))??qv(e);if(o===void 0&&i===void 0){let u=hc(b(n?.message))??hc(b(r?.message))??hc(b(t?.message))??hc(b(e.message))??hc(b(e.reason))??hc(b(e.error))??hc(b(e.diagnostic))??hc(b(e.diagnostic_summary));u!==void 0&&(o=u.status,i=u.errorType,a=kg(u.message)??a)}let s=[o===void 0?void 0:String(o),i?.trim()===""?void 0:i?.trim()].filter(u=>u!==void 0).join(" "),d=s===""?a:a===void 0?s:`${s}: ${a}`;if(!(d===void 0||d===""))return d.slice(0,dFe)}function cY(e){if(typeof e=="string"&&e.trim()!=="")return e;let n=O(e);if(n===void 0)return;let t=Object.keys(n);return t.length===1?t[0]:void 0}function hc(e){if(e===void 0)return;let n=e.indexOf("{");if(n===-1)return;let t=qf(e.slice(n))??qf(e.slice(n,e.lastIndexOf("}")+1));if(t===void 0||b(t.type)!=="error")return;let r=O(t.error);if(r===void 0)return;let o=t.status;return{status:typeof o=="number"&&Number.isFinite(o)?o:void 0,errorType:b(r.type)??b(r.code),message:b(r.message)}}function lFe(e){let n=O(O(e.diagnostic_payload)?.error),t=O(n?.error),r=O(e.error),o=[{code:b(n?.code),message:b(n?.message)},{code:b(n?.type),message:b(n?.message)},{code:b(t?.code),message:b(t?.message)},{code:b(t?.type),message:b(t?.message)},{code:b(r?.code),message:b(r?.message)},{code:b(r?.type),message:b(r?.message)},{code:b(e.code),message:b(e.message)},{code:b(e.type),message:b(e.message)}];for(let i of o){let a=i.code?.trim();if(a!==void 0&&a!==""&&aFe.test(a))return{codeOrType:a,message:i.message}}}function cFe(e){let n=lFe(e),t=qv(e),r=t!==void 0&&sFe.test(t);return n===void 0&&!r?void 0:kg(n?.message)??t??""}function fFe(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 hFe(e){let n=O(O(e.diagnostic_payload)?.error),t=O(n?.error),r=O(e.error),o=[b(n?.code),b(n?.type),b(t?.code),b(t?.type),b(r?.code),b(r?.type),b(e.code),b(e.type)],i=[b(n?.message),b(t?.message),b(r?.message),b(e.message),b(e.reason)];if(o.some(s=>{let d=s?.trim();return d!==void 0&&d!==""&&X2.test(d)})){for(let s of i){let d=kg(s);if(d!==void 0&&mFe.test(d))return d}return qv(e)??""}}function TY(e,n,t){return t?.upstreamHttpStatus===402?e:e==="transient_upstream"&&n.routeOutageActive?.(t?.sourceSeq)===!0?"route_outage":e}function gFe(e){let n=O(O(e.diagnostic_payload)?.error),t=O(n?.error),r=O(e.error);for(let o of[t,n,r,e]){if(o===void 0)continue;let i=b(o.code)?.trim(),a=b(o.type)?.trim();if(!(i!==void 0&&i!==""&&X2.test(i)||a!==void 0&&a!==""&&X2.test(a)))continue;let d=o.hold_ceiling_minutes,u=typeof d=="number"&&Number.isFinite(d)&&d>0?Math.floor(d)*6e4:void 0;return{provider:b(o.provider),model:b(o.model),holdCeilingMs:u}}}function yFe(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 _Fe(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 bFe(e){return e.providerOutageFlagged?{kind:"storm",retryable:!1,reason:yFe(e.stormDetail)}:e.priorConsecutiveIsolatedRejections<pFe?{kind:"isolated_retry",retryable:!0,reason:fFe(e.rejectionDetail)}:{kind:"isolated_terminal",retryable:!1,reason:_Fe(e.rejectionDetail)}}function wFe(e){return vFe.test(e)||xFe.test(e)}function SFe(e){let n=b(e.kind)??b(e.type)??b(O(e.error)?.kind)??b(O(e.error)?.type),t=typeof n=="string"&&/(tool.*fatal|fatal.*tool|response[._]failed|tool_failure)/i.test(n),r=qv(e),o=r!==void 0&&wFe(r);if(!(!t&&!o))return r??""}function kFe(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 dt(e,n){return{type:"log",event:e,fields:n}}var h$e,Ov,Cg,g$e,Da,iY,y$e,_$e,b$e,aY,sY,x$e,dY,pY,Dv,P$e,A$e,I$e,j$e,bY,Y2,L$e,vY,aFe,sFe,dFe,pFe,X2,mFe,vFe,xFe,RT=B(()=>{"use strict";Ev();os();Zt();hg();Pv();V2();h$e=new Set(["completed","failed","interrupted"]);Ov="pipeline/turnMappingReady",Cg="pipeline/turnMappingFailed",g$e=512,Da=2,iY="Codex completed without producing a response.",y$e="linzumi_agent_reply",_$e="The agent ended its turn after narrating an intent without posting a reply or taking any action.",b$e="agent narrated intent but posted no reply and took no action",aY=new Set(["commandOutput","fileChange","terminalInput","agentStatus","agentTaskUpdate"]);sY=3,x$e="Stopped after repeated empty responses in a row",dY=64;pY="Codex emitted unsupported tool call";Dv="pipeline/stopInterrupted",P$e=new Map([["turn/failed","failed"],["turn/aborted","interrupted"],["turn/canceled","interrupted"],["turn/cancelled","interrupted"],[Dv,"interrupted"]]),A$e=new Set(["turn/started","turn/completed","turn/failed","turn/aborted","turn/canceled","turn/cancelled",Dv,"error","turn/plan/updated","item/agentMessage/delta","item/reasoning/textDelta","item/commandExecution/outputDelta","command/exec/outputDelta","item/fileChange/outputDelta","item/fileChange/patchUpdated","item/mcpToolCall/progress","item/commandExecution/terminalInteraction","item/started","item/completed","response_item","thread/compacted"]),I$e=new Set(["turn/plan/updated","item/agentMessage/delta","item/reasoning/textDelta","item/commandExecution/outputDelta","command/exec/outputDelta","item/fileChange/outputDelta","item/fileChange/patchUpdated","item/mcpToolCall/progress","item/commandExecution/terminalInteraction","item/started","item/completed","response_item"]);j$e=/upstream model stream stalled/i,bY=/\(HTTP (\d{3})\)/,Y2=/\(HTTP 429\)|\bstatus:?\s+429\b|\b429\s+Too\s+Many\s+Requests\b|\bHTTP\s+429\b/i;L$e=" (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.)";vY=" (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,sFe=/\bmodel request was rejected\b|\bmodel_request_rejected\b/i;dFe=300;pFe=1,X2=/^provider_outage$/i,mFe=/rejecting requests|experiencing an outage|provider outage/i;vFe=/\bapply_patch\b[^]*\bincompatible\b|\bin-flight tool future\b[^]*\bfail/i,xFe=/\btools::router\b[^]*\bfatal\b|\bresponse\.failed\b/i});function PY(e){return e===void 0?[]:[...e.values()].map(n=>({...n}))}function AY(e){let n=hY(),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,a=new Map,s=new Map,d=new Map,u=new Set,c=e.bufferedTurnMaxAgeMs??CFe,l=e.bufferedTurnMaxEvents??TFe,f=e.bufferedTurnSweepIntervalMs??PFe,p=!1,h=!0,y,m=(I,P)=>{try{e.log(I,P)}catch{}},_=I=>{switch(I.type){case"enqueue":e.outbox.enqueue({kind:I.kind,data:I.data,...I.coalesceKey===void 0?{}:{coalesceKey:I.coalesceKey},resolution:I.resolution});return;case"requestSnapshot":e.requestSnapshot(I.turnId);return;case"turnTerminal":e.onTurnTerminal(I.turnId,I.outcome,I.reason,I.retryableEmptyTurn,I.autoResumeMidStreamStall,I.fate,I.freshSessionResumeMidStreamStall,I.routeOutageHold);return;case"log":m(I.event,I.fields);return}},w=()=>{for(let I of n.turns.keys())i.has(I)||i.set(I,o());for(let I of[...i.keys()])n.turns.has(I)||i.delete(I);for(let I of n.bufferedTurns.keys())a.has(I)||a.set(I,o());for(let I of[...a.keys()])n.bufferedTurns.has(I)||(a.delete(I),u.delete(I));for(let I of[...s.keys()])!n.turns.has(I)&&!n.bufferedTurns.has(I)&&s.delete(I);for(let I of[...d.keys()])!n.turns.has(I)&&!n.bufferedTurns.has(I)&&d.delete(I)},v=(I,P)=>{!n.turns.has(I)&&!n.bufferedTurns.has(I)||s.set(I,{atMs:o(),kind:P})},S=I=>{if(I.source!=="codex")return;let P=I.notification.method;if(P===Ov||P===Cg)return;let z=Rv(I.notification.params??{})??AT(n);z!==void 0&&v(z,P)},C=I=>{if(I.source!=="codex")return;let P=I.notification.method;if(P!=="item/started"&&P!=="item/completed"&&P!=="response_item")return;let z=I.notification.params??{},$=Rv(z)??AT(n);if($===void 0||!n.turns.has($)&&!n.bufferedTurns.has($))return;let J=xg(z);if(J===void 0||J==="")return;if(P!=="item/started"){d.get($)?.delete(J);return}let Q=b(O(z.item)?.type);if(Q===void 0||!AFe.has(Q))return;let K=d.get($);K===void 0&&(K=new Map,d.set($,K)),K.set(J,{kind:Q,startedAtMs:o()})},A=()=>{if(!h||n.phase!=="running")return!1;let I=o(),P=!1;for(let[z,$]of n.bufferedTurns){if(u.has(z))continue;let J=I-(a.get(z)??I),Q=J>c,K=$.length>l;!Q&&!K||(u.add(z),m("pipeline.loop.buffered_turn_overdue",{level:"error",thread_key:e.threadKey,turn_id:z,buffered_event_count:$.length,age_ms:J,max_age_ms:c,max_events:l}),r.push({source:"codex",notification:{method:Cg,params:{turnId:z,reason:K?`turn source mapping never arrived (${$.length} buffered events exceeded the ${l} cap)`:`turn source mapping never arrived within ${c}ms`}}}),P=!0)}return P},T=()=>{if(!p){p=!0;try{for(;r.length>0;){let I=r.shift();if(I===void 0)continue;let P;try{P=gY(n,I,t)}catch(z){m("pipeline.loop.event_processing_failed",{thread_key:e.threadKey,source:I.source,message:z instanceof Error?z.message:String(z)});continue}w(),S(I),C(I);for(let z of P)try{_(z)}catch($){m("pipeline.loop.effect_failed",{thread_key:e.threadKey,effect:z.type,message:$ instanceof Error?$.message:String($)})}A()}}finally{p=!1}}},M=f>0?setInterval(()=>{A()&&T()},f):void 0;return M?.unref?.(),{submit:I=>{try{if(!h){m("pipeline.loop.event_after_drain",{thread_key:e.threadKey,source:I.source});return}r.push(I),T()}catch(P){m("pipeline.loop.submit_failed",{thread_key:e.threadKey,message:P instanceof Error?P.message:String(P)})}},metrics:()=>({queueDepth:r.length,phase:n.phase,activeTurns:[...n.turns.values()].map(I=>({turnId:I.turnId,sourceSeq:I.sourceSeq,startedAtMs:i.get(I.turnId)??o(),lastActivityAtMs:s.get(I.turnId)?.atMs,lastActivityKind:s.get(I.turnId)?.kind,openItems:PY(d.get(I.turnId))})),bufferedTurns:[...n.bufferedTurns.entries()].map(([I,P])=>({turnId:I,bufferedEventCount:P.length,firstBufferedAtMs:a.get(I)??o(),lastActivityAtMs:s.get(I)?.atMs,lastActivityKind:s.get(I)?.kind,openItems:PY(d.get(I))}))}),noteTurnActivity:(I,P)=>{try{v(I,P)}catch(z){m("pipeline.loop.note_activity_failed",{thread_key:e.threadKey,message:z instanceof Error?z.message:String(z)})}},drainAndClose:I=>(y===void 0&&(y=(async()=>{h=!1,M!==void 0&&clearInterval(M),await Promise.resolve(),T();try{await e.outbox.flush(I)}catch(P){m("pipeline.loop.drain_flush_failed",{thread_key:e.threadKey,message:P instanceof Error?P.message:String(P)})}})()),y)}}var CFe,TFe,PFe,AFe,IY=B(()=>{"use strict";Zt();V2();RT();CFe=10*6e4,TFe=1e4,PFe=3e4,AFe=new Set(["commandExecution","terminalInput","mcpToolCall","dynamicToolCall","collabAgentToolCall"])});async function RFe(e,n,t){let r=c=>(t("adt.terminal_repair_refused",{thread_id:n.threadId,source_seq:n.sourceSeq,session_id:n.sessionId,reason:c}),{kind:"refused",message:c});await e.journalSettled();let o=e.terminalPublicationDebt();if(typeof o=="object"&&o.kind==="unavailable")return r(o.reason);let i=e.failedTerminalEntries().filter(c=>{let l=O(c.data.terminal_frame);return c.data.terminal_repair===void 0&&ie(c.data.seq)===n.sourceSeq&&ie(l?.session_id)===n.sessionId&&ie(l?.lease_epoch)===n.originalLeaseEpoch}),a=i[0];if(i.length!==1||a===void 0)return r("terminal failure evidence is missing or ambiguous");let s=JSON.stringify(a.data),d=e.recallDurableFact(Kf(a.entrySeq));if(d!==void 0&&Eh(a.entrySeq,s,JSON.stringify(d)))return t("adt.terminal_repair_already_resolved",{thread_id:n.threadId,source_seq:n.sourceSeq,failed_entry_seq:a.entrySeq}),{kind:"ready",id:Kf(a.entrySeq),serializedData:s};let u=await r7(n.threadId,n.sourceSeq,n.sessionId,n.originalLeaseEpoch,a.entrySeq,s,JSON.stringify(n.binding),n.authoritativeTerminal,{readPrepared:c=>{let l=e.recallDurableFact(c);return l===void 0?void 0:typeof l=="string"?l:"invalid prepared fact"},writePrepared:async(c,l)=>(e.rememberDurableFact(c,l),await e.journalSettled(),e.metrics().totalJournalWriteFailures===0?"IoOk":{kind:"IoError",message:"terminal repair preparation was not durable"}),authorize:c=>{let l=O(JSON.parse(c));return l!==void 0&&n.authorize(l)?"IoOk":{kind:"IoError",message:"terminal repair publication authority refused"}},enqueue:async c=>{let l=O(JSON.parse(c));if(l===void 0)return{kind:"IoError",message:"terminal repair entry is not an object"};let f=O(l.terminal_repair)?.id,p=e.pendingTerminalEntries().filter(h=>O(h.data.terminal_repair)?.id===f);return p.length>0?(t("adt.terminal_repair_pending_retained",{thread_id:n.threadId,source_seq:n.sourceSeq,count:p.length}),p.length===1&&JSON.stringify(p[0]?.data)===c?"IoOk":{kind:"IoError",message:"pending correction identity differs"}):(e.enqueue({kind:"adt.terminal_attempt",data:l,resolution:"must_reach_consensus"}),await e.journalSettled(),e.metrics().totalJournalWriteFailures===0?"IoOk":{kind:"IoError",message:"terminal correction enqueue was not durable"})}});return u.kind==="refused"?r(u.message):u}function Fv(e){let n=LFe(e),t=KFe(),r=zX({threadKey:e.threadKey,...e.journalGeneration===void 0?{}:{journalGeneration:e.journalGeneration},push:(_,w,v,S,C)=>{if(C===void 0)throw new Error("Session pipeline push requires outbox metadata");let A=DFe(_,w,C),T=()=>e.push(_,A,v,S),M=ET(C),I=qFe(C);return e.commanderPushAdmission===void 0?T():e.commanderPushAdmission.run({threadKey:e.threadKey,pushClass:M,owner:t,...I===void 0?{}:{streamIdentity:I}},T,M==="replaceable_live"?()=>null:void 0)},...e.commanderPushAdmission===void 0?{}:{isPriorityEntry:_=>ET(_)!=="replaceable_live",supersedesQueuedEntry:$Fe},builders:n,...e.persistDir===void 0?{}:{persistDir:e.persistDir},...e.outboxRetryDelaysMs===void 0?{}:{retryDelaysMs:[...e.outboxRetryDelaysMs]},maxInFlightPushes:e.outboxMaxInFlightPushes??(e.commanderPushAdmission===void 0?MFe:1),...e.journalRecoveryMaxAgeMs===void 0?{}:{journalRecoveryMaxAgeMs:e.journalRecoveryMaxAgeMs},...e.outboxRecoveryMode===void 0?{}:{recoveryMode:e.outboxRecoveryMode},isRetryBudgetExempt:a$,shouldPreserveForRestart:EFe,onPermanentFailure:(_,w)=>{if(e.log("pipeline.outbox_entry_failed",{thread_key:e.threadKey,entry_seq:_.entrySeq,kind:_.kind,attempts:_.attempts,item_key:b(_.data.item_key)??null,turn_id:b(_.data.turn_id)??null,message:w.message}),_.kind===r$){let v=b(_.data.event),S=O(_.data.payload);if(v===void 0||S===void 0){e.log("pipeline.durable_session_push_failure_invalid_data",{thread_key:e.threadKey,entry_seq:_.entrySeq,event:_.data.event??null});return}e.onDurablePushPermanentFailure?.(v,S,w)}},log:e.log}),o,i=_=>{let w=_.data;if(_.kind===Qt.messageState){let v=b(w.turn_id);v!==void 0&&e.isRecoveredTurn?.(v)===!0&&(w={...w,suppress_terminal_for_recovered_turn:!0});let S=b(w.status);if(S==="failed"||S==="recovering"){let C=e.runtimeMetadataForSourceSeq?.(ie(w.seq)),A=b(C?.model),T=b(C?.model_provider);w={...w,...b(w.model)===void 0&&A!==void 0?{model:A}:{},...b(w.provider)===void 0&&T!==void 0?{provider:T}:{}}}}if(NFe(_.kind)){let v=ie(w.source_seq),S=O(w.local_runner_runtime_metadata)??e.runtimeMetadataForSourceSeq?.(v);S!==void 0&&(w={...w,local_runner_runtime_metadata:S});let C=v===void 0?void 0:e.executionLegRecoveryAttemptIdForSourceSeq?.(v);C!==void 0&&(w={...w,executionLegRecoveryAttemptId:C})}return w!==_.data?r.enqueue({..._,data:w}):r.enqueue(_)},a=e.adtIntervalNowMs??(()=>Date.now()),s=e.scheduleAdtInterval??((_,w)=>{let v=setTimeout(w,_);return v.unref?.(),()=>clearTimeout(v)}),d=new Map,u=!1,c=_=>{let w=CX(_.emitter,a());w!==null&&r.enqueue({kind:Tv,data:_g(w),resolution:"must_ack"})},l=_=>{if(d.get(_.sourceSeq)?.(),d.delete(_.sourceSeq),u||_.done||_.emitter.fenced||_.emitter.terminalEmitted||_.emitter.pendingDeltas===0)return;let w=a(),v=Math.max(0,_.emitter.lastFrameAtMs+_.binding.checkpointConfig.thresholds.maxIntervalMs-w),S=s(v,()=>{if(d.delete(_.sourceSeq),u)return;let C=e.adtAuthorityForSourceSeq?.(_.sourceSeq);if(C===void 0||C.sourceSeq!==_.sourceSeq||C.binding.sessionId!==_.binding.sessionId||C.binding.leaseEpoch!==_.binding.leaseEpoch){e.log("adt.interval_authority_stale",{thread_key:e.threadKey,source_seq:_.sourceSeq,scheduled_session_id:_.binding.sessionId,scheduled_lease_epoch:_.binding.leaseEpoch,current_session_id:C?.binding.sessionId??null,current_lease_epoch:C?.binding.leaseEpoch??null});return}c(C),l(C)});d.set(_.sourceSeq,S)},f=()=>{u=!0;for(let _ of d.values())_();d.clear()},p={...r,enqueue:_=>{let w=_.kind===Qt.messageState?ie(_.data.seq):ie(_.data.source_seq),v=w===void 0?void 0:e.adtAuthorityForSourceSeq?.(w);if(v===void 0)return i(_);let S=PX(v,_.kind,_.data,a(),Qt),C=(T=S)=>{for(let M of T)r.enqueue({kind:Tv,data:_g(M),resolution:"must_ack"})};if(_.kind===Qt.messageState){let T=S.find(M=>M.frameKind==="terminal");return C(S.filter(M=>M.frameKind!=="terminal")),l(v),i(T!==void 0?{kind:mT,data:{..._.data,terminal_frame:_g(T)},resolution:_.resolution,..._.coalesceKey===void 0?{}:{coalesceKey:_.coalesceKey}}:_)}let A=i(_);return C(),l(v),A}},h=async _=>{let w=e.snapshotRetryDelaysMs??IFe;for(let v=0;;v+=1)try{let S=await e.resolveSnapshot(_);o.submit({source:"snapshot",turnId:_,snapshot:{items:[...S.items]}});return}catch(S){let C=S instanceof Error?S.message:String(S),A=w[v];if(e.log("pipeline.snapshot_resolution_failed",{thread_key:e.threadKey,turn_id:_,attempt:v+1,retry_in_ms:A??null,message:C}),A===void 0){o.submit({source:"codex",notification:{method:"turn/failed",params:{turnId:_,reason:`completion snapshot resolution failed: ${C}`}}});return}await JFe(A)}};o=AY({threadKey:e.threadKey,outbox:p,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:_=>{h(_).catch(w=>{e.log("pipeline.snapshot_request_failed",{thread_key:e.threadKey,turn_id:_,message:w instanceof Error?w.message:String(w)})})},instanceId:e.instanceId,log:e.log,linzumiAgentSession:e.linzumiAgentSession===!0});let y=GX({threadKey:e.threadKey,outboxMetrics:()=>r.metrics(),loopMetrics:()=>o.metrics(),log:e.log,intervalMs:e.statsIntervalMs,turnStalledThresholdMs:e.turnStalledThresholdMs,turnWaitStates:e.turnWaitStates}),m;return{submitNotification:(_,w)=>{o.submit({source:"codex",notification:{method:_,params:w}})},notifyTurnMappingReady:_=>{o.submit({source:"codex",notification:{method:Ov,params:{turnId:_}}})},notifyTurnMappingFailed:(_,w)=>{o.submit({source:"codex",notification:{method:Cg,params:{turnId:_,reason:w}}})},noteTurnActivity:(_,w)=>{o.noteTurnActivity(_,w)},submitLifecycle:(_,w)=>{o.submit({source:"lifecycle",kind:_,reason:w})},pause:()=>{r.pause()},resume:()=>{r.resume()},rebindThreadKey:_=>{r.rekeyJournal(_)},enqueueDurablePush:(_,w,v)=>r.enqueue({kind:r$,data:{event:_,payload:w},...v===void 0?{}:{coalesceKey:v},resolution:"must_ack"}),readDurableFact:_=>r.recallDurableFact(_),durableFactRecovery:()=>r.durableFactRecovery(),retainPendingTerminalForRepair:()=>r.retainPendingTerminalForRepair(),terminalPublicationDebt:()=>r.terminalPublicationDebt(),settleJournalForRestart:()=>r.journalSettled(),restartWriteInProgress:()=>r.restartWriteInProgress(),flushForRestart:async()=>{let _=o.metrics();if(_.queueDepth!==0||_.activeTurns.length!==0||_.bufferedTurns.length!==0)throw e.log("commander_restart_publication_flush_refused",{threadKey:e.threadKey,reason:"restart_pipeline_not_quiescent"}),new Error("restart_pipeline_not_quiescent");await r.flush(),await r.journalSettled();let w=o.metrics();if(w.queueDepth!==0||w.activeTurns.length!==0||w.bufferedTurns.length!==0||r.metrics().depth!==0||r.terminalPublicationDebt()!=="clear")throw e.log("commander_restart_publication_flush_refused",{threadKey:e.threadKey,reason:"restart_publication_evidence_not_clear"}),new Error("restart_publication_evidence_not_clear")},failedTerminalEntries:()=>r.failedTerminalEntries(),repairTerminalDebt:async _=>{let w=await RFe(r,_,e.log);return w.kind==="ready"&&r.flush().then(async()=>{await r.journalSettled(),r.terminalPublicationDebt()==="clear"?e.onTerminalDebtResolved?.(_.threadId,_.sourceSeq,_.sessionId):e.log("adt.terminal_repair_still_pending",{thread_id:_.threadId,source_seq:_.sourceSeq})}).catch(v=>e.log("adt.terminal_repair_settlement_failed",{thread_id:_.threadId,reason:v instanceof Error?v.message:"unknown settlement failure"})),w},writeDurableFact:async(_,w)=>{let v=r.metrics().totalJournalWriteFailures;r.rememberDurableFact(_,w),await r.journalSettled();let S=r.metrics();if(e.persistDir!==void 0&&(S.totalJournalWriteFailures>v||S.journalDegraded))throw new Error(`Failed to persist durable session fact ${_} for ${e.threadKey}`)},flushOutbox:_=>r.flush(_),metrics:()=>r.metrics(),close:_=>(m===void 0&&(e.commanderPushAdmission?.cancelQueued(t),m=(async()=>{f(),y.stop(),o.submit({source:"lifecycle",kind:"shutdown",reason:"session closed"}),await o.drainAndClose(_),await r.close(_)})()),m)}}function o$(e){if(e.checkpoint_due===!0)return!0;let n=ie(e.stream_snapshot_index);return n===void 0?!1:n%OFe===0}function NY(e){switch(e.entryKind){case Qt.postStreamedRow:switch(t$(e.data)){case void 0:return"started";case"completed":return"completed";case"failed":return"failed";case"cancelled":return"cancelled"}case Qt.streamSnapshot:{let n=t$(e.data);return n===void 0?o$(e.data)?"checkpoint":"delta":n}case Qt.finalizeRow:case Qt.postCompletedRow:switch(t$(e.data)){case void 0:case"completed":return"completed";case"failed":return"failed";case"cancelled":return"cancelled"}case Qt.messageState:switch(b(e.data.status)){case"failed":return"failed";case"interrupted":return"cancelled";case"processed":return"completed";default:return}case Tv:switch(b(e.data.frame_kind)){case"delta":return"checkpoint";case"checkpoint":return"checkpoint";case"terminal":return"completed";default:return}case mT:return"completed";default:return}}function DFe(e,n,t){switch(e){case"session:stream_thread_message":{let r=NY(t);if(r===void 0)throw new Error("Stream pipeline push requires a lifecycle");return{...n,stream_lifecycle:r}}default:return n}}function ET(e){switch(NY(e)){case"delta":return"replaceable_live";case"completed":case"failed":case"cancelled":return"terminal";case"started":case"checkpoint":case void 0:return"durable"}}function RY(e){let n=bC(e);return n===void 0?{}:{traceparent:n}}function FFe(e){return{...b(e.turn_id)===void 0?{}:{turn_id:b(e.turn_id)},...b(e.item_key)===void 0?{}:{item_key:b(e.item_key)},...ie(e.delta_index)===void 0?{}:{delta_index:ie(e.delta_index)},...ie(e.stream_snapshot_index)===void 0?{}:{stream_snapshot_index:ie(e.stream_snapshot_index)}}}function jFe(e){return typeof e.body=="string"?e.body:""}function EY(e){return O(e.structured)??{}}function NFe(e){return e===Qt.postStreamedRow||e===Qt.streamSnapshot||e===Qt.finalizeRow||e===Qt.postCompletedRow}function LFe(e){let n={build:l=>{let f=e.wire();if(f.kandanThreadId===void 0||f.codexThreadId===void 0)return{skip:!0,reason:"session_thread_unbound"};let p=b(l.client_message_id);if(p===void 0)return{skip:!0,reason:"missing_client_message_id"};let h=b(l.turn_id),y=ie(l.source_seq),m=b(l.executionLegRecoveryAttemptId),_={...h===void 0?{}:{turn_id:h},stream_key:p},w=O(l.local_runner_runtime_metadata),v={..._,...w??{}},S=e.sandboxNetworkDenialSurfacing===!0?nQ(EY(l),w):EY(l);return{event:"session:stream_thread_message",payload:{workspace:f.workspaceSlug,channel:f.channelSlug,thread_id:f.kandanThreadId,stream_key:p,...f.leaseEpoch===void 0?{}:{lease_epoch:f.leaseEpoch},...m===void 0?{}:{executionLegRecoveryAttemptId:m},body:jFe(l),payload:{...e.runnerPayload("codex_output",f.codexThreadId,y,v),...f.rootSeq===void 0?{}:{reply_to_seq:f.rootSeq},...m===void 0?{}:{executionLegRecoveryAttemptId:m},...y===void 0?{}:{source_message_seq:y},..._,structured:{...S,stream_key:p}},client_message_id:p,...FFe(l),...RY(f.kandanThreadId)}}},replyPolicy:{kind:"transport_ack"},coalesce:(l,f)=>o$(l)||o$(f)?{...f,checkpoint_due:!0}:f},t={build:l=>{let f=e.wire();if(f.kandanThreadId===void 0)return{skip:!0,reason:"session_thread_unbound"};let p=ie(l.seq),h=b(l.status);if(p===void 0||h===void 0)return{skip:!0,reason:"malformed_message_state_entry"};let y=b(l.turn_id);return l.suppress_terminal_for_recovered_turn===!0||y!==void 0&&e.isRecoveredTurn?.(y)===!0?{skip:!0,reason:"terminal_for_recovered_turn"}:{event:"message_state",payload:{workspace:f.workspaceSlug,channel:f.channelSlug,thread_id:f.kandanThreadId,instance_id:e.instanceId,...f.codexThreadId===void 0?{}:{codex_thread_id:f.codexThreadId},seq:p,status:h,...b(l.reason)===void 0?{}:{reason:b(l.reason)},...l.retryable===!0?{retryable:!0}:{},...as(l.fate)?{fate:l.fate}:{},...O(l.ladder)===void 0?{}:{ladder:O(l.ladder)},...l.failure_class==="edge_blocked"||l.failure_class==="claude_oauth_expired"?{failure_class:l.failure_class}:{},...b(l.upstream_error)===void 0?{}:{upstream_error:b(l.upstream_error)},...b(l.model)===void 0?{}:{model:b(l.model)},...b(l.provider)===void 0?{}:{provider:b(l.provider)},...b(l.turn_id)===void 0?{}:{turn_id:b(l.turn_id)},...f.leaseEpoch===void 0?{}:{lease_epoch:f.leaseEpoch},...RY(f.kandanThreadId)}}},replyPolicy:{kind:"adjudicate",adjudicateReply:(l,f)=>{if(l.approval_failure_consensus!==!0)return{kind:"accept"};let p=e.wire().kandanThreadId,h=ie(l.seq);if(p===void 0||h===void 0)return{kind:"retry",failure:new Error("approval failure consensus entry omitted its expected identity")};let y=(()=>{switch(e.messageStateReplyShape.kind){case"inner_response":return Zs(f);case"full_reply":return Zs(f,"full")}})();switch(y.kind){case"applied":return{kind:"accept"};case"terminal":return y.threadId===p&&y.sourceSeq===h?{kind:"accept"}:{kind:"retry",failure:new Error(`terminal message_state consensus identity mismatch: expected ${p}:${h}, received ${y.threadId}:${y.sourceSeq}`)};case"invalid":return{kind:"retry",failure:new Error(y.error)};case"unconfirmed":return{kind:"retry",failure:new Error("approval failure message_state consensus was unconfirmed")}}}}},r={build:l=>{let f=e.wire(),p=b(l.turn_id),h=b(l.reason),y=ie(l.buffered_event_count),m=b(l.first_event),_=b(l.last_event);if(f.kandanThreadId===void 0||f.codexThreadId===void 0)return e.log?.("pipeline.unmapped_turn_failure_build_failed",{level:"error",turn_id:p??null,missing_kandan_thread_id:f.kandanThreadId===void 0,missing_codex_thread_id:f.codexThreadId===void 0}),{skip:!0,reason:"session_thread_unbound"};if(p===void 0||h===void 0||y===void 0||y<0||m===void 0||_===void 0)return e.log?.("pipeline.unmapped_turn_failure_build_failed",{level:"error",turn_id:p??null,missing_reason:h===void 0,buffered_event_count:y??null,first_event:m??null,last_event:_??null}),{skip:!0,reason:"malformed_unmapped_turn_failure"};let w=`unmapped-turn-failure:${p}`;return{event:"session:post_thread_message",payload:{workspace:f.workspaceSlug,channel:f.channelSlug,thread_id:f.kandanThreadId,body:h,payload:{...e.runnerPayload("unmapped_turn_failure",f.codexThreadId,void 0,{turn_id:p}),structured:{kind:"agent_status_event",item_id:w,transcript_unit_id:`agent_status_event:${w}`,stream_state:"completed",event_kind:"status",title:"Response delivery failed",body:h,severity:"error",agent_provider:"codex",occurred_at_ms:null,raw_provider_metadata:{turn_id:p,buffered_event_count:y,first_event:m,last_event:_}}},client_message_id:w,turn_id:p}}},replyPolicy:{kind:"transport_ack"}},o=l=>{let f=O(l);return O(f?.adt)??O(O(f?.terminal_attempt)?.frame)??O(O(O(f?.response)?.terminal_attempt)?.frame)},i={build:l=>{let f=ie(l.session_id),p=ie(l.lease_epoch);return f!==void 0&&p!==void 0&&gT(f,p)?{skip:!0,reason:"adt_generation_fenced"}:{event:xX,payload:{session_id:l.session_id??null,lease_epoch:l.lease_epoch??null,frame_index:l.frame_index??null,frame_kind:l.frame_kind??null,body:l.body??null,byte_len:l.byte_len??null,...l.assistant_phase===void 0?{}:{assistant_phase:l.assistant_phase},...l.source_stream_key===void 0?{}:{source_stream_key:l.source_stream_key}}}},replyPolicy:{kind:"transport_ack"},onReply:(l,f)=>{let p=O(l.terminal_frame)??l,h=o(f);if(h===void 0)return;let y=ie(p.session_id),m=ie(p.lease_epoch);if(h.accepted===!1){let _=fT(h.reason),w=e.wire().kandanThreadId;if(e.log?.("adt.append_rejected",{session_id:y??null,presented_epoch:ie(p.lease_epoch)??null,frame_index:ie(p.frame_index)??null,reason:_}),y===void 0||m===void 0||w===void 0){let v=[...y===void 0?["session_id"]:[],...m===void 0?["lease_epoch"]:[],...w===void 0?["thread_id"]:[]].join(",");e.log?.("adt.authority_release_identity_missing",{thread_id:w??null,session_id:y??null,lease_epoch:m??null,missing_identity:v})}else{hT(y,m);let v=e.fenceAdtAuthority?.(y,m);v?.kind==="skipped"&&e.log?.("adt.authority_release_skipped",{thread_id:e.wire().kandanThreadId??null,source_seq:v.sourceSeq??null,session_id:y,lease_epoch:m,release_reason:v.reason}),e.log?.("adt.generation_fenced",{session_id:y,reason:_})}return}h.duplicate===!0&&e.log?.("adt.frame_resend_accepted",{session_id:y??null,frame_index:ie(p.frame_index)??null})}},a="terminal_attempt_frame_correction",s=l=>{let f=O(l.terminal_frame),p=ie(f?.session_id),h=ie(f?.lease_epoch);if(p!==void 0)return h===void 0?void 0:[p,h]},d=(l,f)=>{let p=s(l),h=O(f.recall(a));if(p!==void 0){let[y,m]=p;return ie(h?.session_id)===y&&ie(h?.lease_epoch)===m?ie(h?.next_frame_index):void 0}},u={build:(l,f)=>{let p=t.build(l,f);if("skip"in p)return p;let h=O(l.terminal_frame);if(h===void 0)return{skip:!0,reason:"terminal_attempt_frame_missing"};let y=l.terminal_repair===void 0?d(l,f):void 0;return{event:cT,payload:{...p.payload,...l.terminal_repair===void 0?{}:{terminal_repair:l.terminal_repair},terminal_frame:{session_id:h.session_id??null,lease_epoch:h.lease_epoch??null,frame_index:y??h.frame_index??null,frame_kind:h.frame_kind??null,body:h.body??null,byte_len:h.byte_len??null,...h.assistant_phase===void 0?{}:{assistant_phase:h.assistant_phase},...h.source_stream_key===void 0?{}:{source_stream_key:h.source_stream_key}}}}},replyPolicy:{kind:"adjudicate",adjudicateReply:(l,f,p)=>{if(l.terminal_repair!==void 0){let m=e.wire().kandanThreadId,_=ie(l.seq);if(m===void 0||_===void 0)return{kind:"retry",failure:new Error("terminal repair identity unavailable")};let w=e.messageStateReplyShape.kind==="inner_response"?{status:"ok",response:f}:f,v=pg(m,_,JSON.stringify(w)),S=PD(m,JSON.stringify(l));return v==="accepted"&&S.kind==="ready"?{kind:"accept"}:{kind:"retry",failure:new Error("terminal repair requires accepted exact consensus")}}let h=o(f);switch(h?.accepted===!1?fT(h.reason):void 0){case"frame_index_reuse":{let m=s(l),_=ie(h?.next_frame_index),w=d(l,p)??ie(O(l.terminal_frame)?.frame_index);if(m===void 0||_===void 0||w===void 0||_<=w)return{kind:"retry",failure:new Error("fused terminal frame correction index was unavailable")};let[v,S]=m;return p.remember(a,{session_id:v,lease_epoch:S,next_frame_index:_}),{kind:"retry",failure:new Error("fused terminal frame index was corrected by the server")}}case"unknown":return{kind:"retry",failure:new Error("retryable fused terminal frame rejection")};case"stale_epoch":case"post_settle":case"post_terminal":case void 0:{let m=e.wire().kandanThreadId,_=ie(l.seq);if(m===void 0||_===void 0||s(l)===void 0)return{kind:"retry",failure:new Error("fused terminal expected identity missing")};let w=e.messageStateReplyShape.kind==="inner_response"?{status:"ok",response:f}:f,v=pg(m,_,JSON.stringify(w));return typeof v=="object"?{kind:"retry",failure:new Error(v.message)}:{kind:"accept"}}}}},onReply:(l,f,p)=>{if(l.terminal_repair!==void 0){let m=e.wire().kandanThreadId,_=PD(m??"",JSON.stringify(l));if(_.kind!=="ready"){let w={thread_id:m??null,source_seq:l.seq??null,reason:_.message};e.log?e.log("adt.terminal_repair_receipt_refused",w):console.warn("adt.terminal_repair_receipt_refused",w);return}p.remember(_.id,JSON.parse(_.serializedData))}let h=o(f);switch(h?.accepted===!1?fT(h.reason):void 0){case"frame_index_reuse":case"unknown":return;case"stale_epoch":case"post_settle":case"post_terminal":case void 0:{let m=e.wire().kandanThreadId,_=ie(l.seq),w=s(l),v=e.messageStateReplyShape.kind==="inner_response"?{status:"ok",response:f}:f,S=m===void 0||_===void 0?{kind:"retry",message:"fused terminal expected identity missing"}:pg(m,_,JSON.stringify(v));if(w===void 0||_===void 0||typeof S=="object"){let C={source_seq:_??null,message:typeof S=="object"?S.message:"session identity missing"};e.log!==void 0?e.log("adt.terminal_retirement_refused",C):console.warn("adt.terminal_retirement_refused",C);return}i.onReply?.(l,f,p),e.onAdtAuthorityRetired?.(w[0],_);return}}}},c={build:l=>{let f=b(l.event),p=O(l.payload);return f===void 0||p===void 0?{skip:!0,reason:"invalid_durable_session_push"}:{event:f,payload:p}},replyPolicy:{kind:"transport_ack"}};return{[Qt.postStreamedRow]:n,[Qt.streamSnapshot]:n,[Qt.finalizeRow]:n,[Qt.postCompletedRow]:n,[Qt.messageState]:t,[Qt.unmappedTurnFailure]:r,[Tv]:i,[mT]:u,[r$]:c}}function LY(e,n){if("error"in e)return[];let t=O(O(e.result)?.thread),o=(Xe(t?.turns)??[]).filter(se).find(i=>i.id===n);return(Xe(o?.items)??[]).filter(se)}function i$(e){if(!e.some(t=>zFe.has(b(t.type)??"")))return[...e];let n=new Set;return e.forEach(t=>{let r=MT.get(b(t.type)??"");if(r===void 0)return;let o=b(t.call_id);if(o===void 0)return;let i=e.findIndex((a,s)=>!n.has(s)&&b(a.type)===r&&b(a.call_id)===o);i>=0&&n.add(i)}),e.flatMap((t,r)=>{let o=b(t.type)??"",i=MT.get(o);if(i!==void 0){let a=b(t.call_id),s=a===void 0?void 0:e.find(d=>b(d.type)===i&&b(d.call_id)===a);return t2(s===void 0?[t]:[t,s]).flatMap(d=>{let u=MY(d);return u===void 0?[]:[u]})}return o==="function_call_output"||o==="custom_tool_call_output"?n.has(r)?[]:t2([t]).flatMap(a=>{let s=MY(a);return s===void 0?[]:[s]}):[t]})}function MY(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(b(n.kind)){case"codex_command_execution":{let i=GFe(o);return{type:"commandExecution",...r,...i===void 0?{}:{codex_protocol_failure_reason:i},command:b(n.command)??"command",...b(n.tool_name)===void 0?{}:{toolName:b(n.tool_name)},cwd:b(n.cwd)??"",status:b(n.status)??"",...b(n.process_id)===void 0||b(n.process_id)===""?{}:{processId:b(n.process_id)},aggregatedOutput:o}}case"codex_file_change":return{type:"fileChange",...r,status:b(n.status)??"",patchText:b(n.patch_text)??e.body,changes:Xe(n.changes)??[]};default:return}}function GFe(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 zY(e,n){if(n.length===0)return[...e];let t=OY(e),r=OY(n),o=new Set,i=r.map(d=>{let u=d.exactKey===void 0?-1:t.findIndex((l,f)=>!o.has(f)&&l.exactKey===d.exactKey);if(u>=0)return o.add(u),{kind:"read",readIndex:u,sourceItemId:void 0};let c=d.semanticKey===void 0?-1:t.findIndex((l,f)=>!o.has(f)&&l.semanticKey===d.semanticKey);if(c>=0){o.add(c);let l=b(d.raw.type),f=l==="agentMessage"||l==="message"&&d.raw.role==="assistant"?b(d.raw.id):void 0;return{kind:"read",readIndex:c,sourceItemId:f}}return{kind:"session",raw:d.raw}}),a=[],s=0;for(let d of i)switch(d.kind){case"read":{for(;s<d.readIndex;){if(!o.has(s)){let c=t[s];c!==void 0&&a.push(c.raw)}s+=1}let u=t[d.readIndex];u!==void 0&&a.push(d.sourceItemId===void 0?u.raw:{...u.raw,id:d.sourceItemId}),s=Math.max(s,d.readIndex+1);break}case"session":a.push(d.raw);break}for(;s<t.length;){if(!o.has(s)){let d=t[s];d!==void 0&&a.push(d.raw)}s+=1}return a}function OY(e){return e.map((n,t)=>{let r=og(n,t).find(o=>o.body.trim()!=="");return r===void 0?{raw:n,exactKey:void 0,semanticKey:void 0}:{raw:n,exactKey:UFe(r),semanticKey:BFe(r)}})}function UFe(e){return`${b(e.structured.kind)??""}:${e.itemKey}`}function BFe(e){let n=b(e.structured.kind)??"";switch(n){case"codex_assistant_message":return JSON.stringify([n,e.body,b(e.structured.phase)??""]);case"codex_command_execution":return JSON.stringify([n,b(e.structured.command)??"",b(e.structured.cwd)??"",b(e.structured.output)??e.body]);case"codex_file_change":return JSON.stringify([n,b(e.structured.patch_text)??e.body]);case"codex_reasoning":return JSON.stringify([n,b(e.structured.content)??e.body]);case"codex_terminal_input":return JSON.stringify([n,b(e.structured.input_text)??e.body]);default:return JSON.stringify([n,e.body])}}function OT(e){return sX(e)}function a$(e){return dX(e)}function JFe(e){return new Promise(n=>{setTimeout(n,e)})}function UY(e=process.env){let n=e.LINZUMI_COMMANDER_PUSH_MAX_INFLIGHT?.trim();switch(n){case void 0:case"":return WFe;default:{let t=Number(n);switch(Number.isSafeInteger(t)&&t>=2){case!0:return t;case!1:throw new Error("LINZUMI_COMMANDER_PUSH_MAX_INFLIGHT must be an integer of at least 2")}}}}function BY(e=process.env){let n=e[DY]?.trim();switch(n){case void 0:case"":return GY;default:{let t=Number(n);switch(Number.isSafeInteger(t)&&t>0){case!0:return t;case!1:throw new Error(`${DY} must be a positive integer`)}}}}var IFe,r$,$v,EFe,MFe,OFe,t$,qFe,$Fe,MT,zFe,KFe,WFe,GY,DY,VFe,qY,HFe,$Y,FY,ZFe,QFe,jY,JY,DT=B(()=>{"use strict";os();dc();S2();Db();Zt();hg();Sq();Sv();qt();Pv();Iv();UX();IY();RT();IFe=[1e3,5e3];r$="pipeline.durable_session_push",$v=class extends Error{constructor(){super("Commander push admission owner closed before admission"),this.name="CommanderPushAdmissionOwnerClosedError"}},EFe=e=>e instanceof $v,MFe=16;OFe=32,t$=e=>{switch(b(O(e.structured)?.stream_state)){case"completed":return"completed";case"failed":return"failed";case"removed":case"interrupted":return"cancelled";default:return}};qFe=e=>{let n=b(e.data.item_key),t=b(e.data.turn_id);return n===void 0?e.entryKind===Qt.messageState?t===void 0?void 0:{kind:"turn",turnId:t}:void 0:{kind:"item",itemKey:n,...t===void 0?{}:{turnId:t}}},$Fe=(e,n)=>{switch(ET(e)==="terminal"&&ET(n)==="replaceable_live"){case!0:break;case!1:return!1}let t=b(e.data.item_key),r=b(n.data.item_key);switch(t){case void 0:{if(e.entryKind!==Qt.messageState)return!1;let o=b(e.data.turn_id),i=b(n.data.turn_id);return o!==void 0&&o===i}default:switch(t===r){case!1:return!1;case!0:{let o=b(e.data.turn_id),i=b(n.data.turn_id);return o===void 0?i===void 0:o===i}}}};MT=new Map([["function_call","function_call_output"],["custom_tool_call","custom_tool_call_output"]]),zFe=new Set([...MT.keys(),...MT.values()]);KFe=()=>({}),WFe=8,GY=2e3,DY="LINZUMI_COMMANDER_PUSH_PRESSURE_BUDGET_MS";VFe=8,qY=()=>({pendingByThread:new Map,activeThreads:[]}),HFe=e=>{switch(e){case"replaceable_live":return"replaceable_live";case"durable":case"terminal":case"control":return"priority"}},$Y=(e,n,t)=>{let r=e.pendingByThread.get(n);if(r===void 0){e.pendingByThread.set(n,[t]),e.activeThreads.push(n);return}else r.push(t)},FY=e=>{let n=e.activeThreads.shift();switch(n){case void 0:return;default:{let t=e.pendingByThread.get(n);switch(t){case void 0:throw new Error("Commander push admission lane lost an active thread");default:{let r=t.shift();if(r===void 0)throw new Error("Commander push admission thread queue was empty");return t.length===0?e.pendingByThread.delete(n):e.activeThreads.push(n),r}}}}},ZFe=(e,n)=>{switch(n?.kind){case"item":switch(e?.kind){case"turn":case void 0:return!1;case"item":switch(e.itemKey===n.itemKey){case!1:return!1;case!0:return e.turnId===void 0?n.turnId===void 0:e.turnId===n.turnId}}case"turn":switch(e?.kind){case"item":case"turn":return e.turnId===n.turnId;case void 0:return!1}case void 0:return!1}},QFe=(e,n,t)=>{let r=e.pendingByThread.get(n);switch(r){case void 0:return;default:{let o=r.filter(i=>{switch(i.supersede){case void 0:return!0;default:switch(ZFe(i.streamIdentity,t)){case!1:return!0;case!0:return i.supersede(),!1}}});if(o.length===0){e.pendingByThread.delete(n);let i=e.activeThreads.indexOf(n);i===-1||e.activeThreads.splice(i,1);return}else e.pendingByThread.set(n,o)}}},jY=(e,n)=>{for(let[t,r]of e.pendingByThread){let o=r.filter(i=>{switch(i.owner===n){case!1:return!0;case!0:return i.reject(new $v),!1}});o.length===0?(e.pendingByThread.delete(t),e.activeThreads.splice(0,e.activeThreads.length,...e.activeThreads.filter(i=>i!==t))):e.pendingByThread.set(t,o)}},JY=e=>{switch(Number.isSafeInteger(e.maxInFlight)&&e.maxInFlight>0){case!1:throw new Error("Commander push admission maxInFlight must be a positive integer");case!0:break}let n=qY(),t=qY(),r=new WeakSet,o=e.now??(()=>performance.now()),i=e.maxLivePressureAgeMs??GY;switch(Number.isSafeInteger(i)&&i>0){case!1:throw new Error("Commander push admission maxLivePressureAgeMs must be a positive integer");case!0:break}let a=e.schedulePressureCheck??((N,W)=>{let ee=setTimeout(W,N);return ee.unref?.(),()=>clearTimeout(ee)}),s=e.maxInFlight===1?1:e.maxInFlight-1,d=0,u=0,c=!1,l=0,f=new Set,p,h,y=0,m=e.onPressureShed??(N=>{console.warn("commander_push.pressure_shed",N)}),_=e.onPressureShedFallback??(N=>{console.warn("commander_push.pressure_shed_fallback",N)}),w=N=>N.replace(/[^\x20-\x7e]/g,"?").slice(0,128),v=(N,W,ee,ne)=>{y+=1;let ye={event:"commander_push.pressure_shed",branch:N,shedCount:y,ageMs:W,budgetMs:i,threadKey:w(ee)};switch(ne?.kind){case"item":return{...ye,streamKind:"item",itemKey:w(ne.itemKey),...ne.turnId===void 0?{}:{turnId:w(ne.turnId)}};case"turn":return{...ye,streamKind:"turn",turnId:w(ne.turnId)};case void 0:return{...ye,streamKind:"none"}}},S=(N,W,ee,ne,ye)=>{let L=ye(),ce=v(N,W,ee,ne);try{m(ce)}catch{try{_({...ce,event:"commander_push.pressure_shed_fallback"})}catch{}}return L},C=N=>{let W=0;for(let ee of f)W=Math.max(W,N-ee.startedAtMs);return W},A=N=>{let W=N-i;for(let ee of f)if(ee.startedAtMs<=W)return!0;return!1},T=()=>{let N=o(),W=N-i,ee=A(N),ne=[];for(let ye of t.activeThreads){let L=t.pendingByThread.get(ye);if(L!==void 0){let ce=L.filter(pe=>{let re=ee?"ack_pressure":pe.enqueuedAtMs<=W?"queue_age":void 0;return re===void 0?!0:(S(re,re==="ack_pressure"?C(N):N-pe.enqueuedAtMs,pe.threadKey,pe.streamIdentity,()=>pe.supersede?.()),!1)});ce.length===0?t.pendingByThread.delete(ye):(t.pendingByThread.set(ye,ce),ne.push(ye))}}t.activeThreads.splice(0,t.activeThreads.length);for(let ye of ne)t.activeThreads.push(ye)},M=N=>{switch(h!==void 0&&h<=N){case!0:return;case!1:break}p?.(),h=N,p=a(Math.max(1,N-o()),()=>{p=void 0,h=void 0,T(),$(),I()})},I=()=>{let N;for(let W of t.pendingByThread.values())for(let ee of W){let ne=ee.enqueuedAtMs+i;N=N===void 0?ne:Math.min(N,ne)}switch(N){case void 0:return;default:for(let W of f)N=Math.min(N,W.startedAtMs+i);M(N)}},P=()=>{for(;;){let N=FY(t);switch(N){case void 0:return;default:let W=o(),ee=A(W)?"ack_pressure":N.enqueuedAtMs+i<=W?"queue_age":void 0;if(ee===void 0)return N;S(ee,ee==="ack_pressure"?C(W):W-N.enqueuedAtMs,N.threadKey,N.streamIdentity,()=>N.supersede?.())}}},z=()=>{let N=n.activeThreads.length>0,W=t.activeThreads.length>0&&u<s;switch(N&&(!W||l<VFe)){case!0:{let ee=FY(n);if(ee===void 0)throw new Error("Commander push priority lane lost its pending task");return l+=1,{priority:"priority",pending:ee,startedAtMs:o()}}case!1:switch(W){case!0:{let ee=P();return ee===void 0?z():(l=0,{priority:"replaceable_live",pending:ee,startedAtMs:o()})}case!1:l=0;return}}},$=()=>{switch(c){case!0:return;case!1:c=!0,queueMicrotask(Q)}},J=async N=>{try{await N.pending.task()}catch(W){N.pending.reject(W)}finally{switch(d-=1,N.priority){case"replaceable_live":u-=1;break;case"priority":break}f.delete(N),$()}};function Q(){for(c=!1;d<e.maxInFlight;){let N=z();switch(N){case void 0:return;default:switch(d+=1,f.add(N),t.activeThreads.length>0){case!0:M(N.startedAtMs+i);break;case!1:break}switch(N.priority){case"replaceable_live":u+=1;break;case"priority":break}J(N)}}}return{run:(N,W,ee)=>{if(N.threadKey.trim()==="")throw new Error("Commander push admission threadKey must not be empty");switch(N.owner===void 0||!r.has(N.owner)){case!1:return Promise.reject(new $v);case!0:break}switch(N.pushClass){case"terminal":QFe(t,N.threadKey,N.streamIdentity);break;case"replaceable_live":if(ee===void 0)throw new Error("Commander replaceable live admission requires onSuperseded");let L=o();switch(A(L)){case!0:return Promise.resolve(S("ack_pressure",C(L),N.threadKey,N.streamIdentity,ee));case!1:break}break;case"durable":case"control":break}let ne=o(),ye=new Promise((L,ce)=>{let pe={threadKey:N.threadKey,task:async()=>{let re=await W();L(re)},reject:ce,...ee===void 0?{}:{supersede:()=>L(ee())},...N.streamIdentity===void 0?{}:{streamIdentity:N.streamIdentity},...N.owner===void 0?{}:{owner:N.owner},enqueuedAtMs:ne};switch(HFe(N.pushClass)){case"priority":$Y(n,N.threadKey,pe);break;case"replaceable_live":$Y(t,N.threadKey,pe)}});switch($(),N.pushClass){case"replaceable_live":{let L=ne+i;for(let ce of f)L=Math.min(L,ce.startedAtMs+i);M(L);break}case"durable":case"terminal":case"control":break}return ye},cancelQueued:N=>{r.add(N),jY(n,N),jY(t,N),t.pendingByThread.size===0&&(p?.(),p=void 0,h=void 0)}}}});import{execFile as XFe}from"node:child_process";import{createHash as YFe,randomUUID as eje}from"node:crypto";import{constants as nje,copyFileSync as tje,createReadStream as rje,existsSync as s$,mkdirSync as d$,readFileSync as ZY,readdirSync as Nv,rmSync as KY,statSync as oje,writeFileSync as ije}from"node:fs";import{copyFile as aje,mkdir as WY,stat as sje,writeFile as dje}from"node:fs/promises";import{homedir as uje}from"node:os";import{dirname as u$,join as qa,resolve as l$}from"node:path";import{promisify as lje}from"node:util";function hje(e=process.env){let n=e[cje];if(n===void 0)return!0;let t=n.trim().toLowerCase();return!(t==="0"||t==="false"||t==="off")}function Lv(e=process.env){let n=e.LINZUMI_GIT_SAFETY_SNAPSHOTS_DIR;return n!==void 0&&n.trim()!==""?l$(n):l$(uje(),".linzumi","safety-snapshots")}async function aa(e,n){try{let{stdout:t,stderr:r}=await QY("git",[...n],{cwd:e,encoding:"utf8",timeout:XY,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 YY(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),a=o.slice(3);t.push({status:i,path:a}),(i.includes("R")||i.includes("C"))&&(r+=1)}return t}function qT(e){let n=e.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"");return n===""?"x":n}function gje(e){let n=new Date(e.nowMs).toISOString().replace(/-|:|\..*$/g,"").replace("T","-"),t=qT(e.threadId).slice(-12),r=qT(e.turnRef).slice(-12),o=e.captureNonce===void 0?"":`-${qT(e.captureNonce)}`;return`${n}-${t}-${r}${o}`}function yje(e){return`refs/linzumi/safety/${e}`}async function _je(e,n,t=aje){try{await t(e,n,nje.COPYFILE_FICLONE_FORCE)}catch{await t(e,n,0)}}async function eee(e){let n=YFe("sha256");for await(let t of rje(e)){if(!Buffer.isBuffer(t))throw new Error(`Expected a byte buffer while hashing ${e}`);n.update(t)}return n.digest("hex")}async function bje(e){let n=e.env??process.env;if(!hje(n))return{kind:"disabled"};let t=Date.now(),r=()=>Date.now()-t,o=await aa(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=YY(o.stdout);if(i.length===0){let a={kind:"clean",durationMs:r()};return c$.set(a,{cwd:e.cwd,repoRoot:e.cwd,statusRaw:o.stdout,trackedTree:void 0,trackedIndexTree:void 0,copiedFileDigests:new Map}),a}try{let a=e.nowMs??t,s=eje(),d=gje({threadId:e.threadId,turnRef:e.turnRef,nowMs:a,captureNonce:s}),u=e.snapshotsRoot??Lv(n),c=qa(u,qT(e.threadId),d),l=e.maxTotalBytes??fje,f=i.filter(N=>N.status==="??").map(N=>N.path),p=i.filter(N=>N.status!=="??"&&N.status!=="!!").map(N=>N.path),h=await aa(e.cwd,["rev-parse","--show-toplevel"]),y=h.ok?h.stdout.trim():e.cwd,m=await aa(e.cwd,["branch","--show-current"]),_=m.ok&&m.stdout.trim()!==""?m.stdout.trim():void 0,w=await aa(e.cwd,["rev-parse","HEAD"]),v=w.ok?w.stdout.trim():void 0,S,C,A,T;if(p.length>0){let N=await aa(e.cwd,["stash","create",`linzumi safety snapshot ${d}`]),W=N.ok?N.stdout.trim():"";if(W!==""){S=W;let[ee,ne]=await Promise.all([aa(e.cwd,["rev-parse",`${W}^{tree}`]),aa(e.cwd,["rev-parse",`${W}^2^{tree}`])]);A=ee.ok?ee.stdout.trim():void 0,T=ne.ok?ne.stdout.trim():void 0;let ye=yje(d);C=(await aa(e.cwd,["update-ref",ye,W])).ok?ye:void 0}}await WY(c,{recursive:!0});let M=[],I=new Map,P=0,z=async(N,W)=>{let ee=qa(y,N),ne=0;try{let ye=await sje(ee);if(!ye.isFile())return!1;if(ne=ye.size,P+ne>l)return M.push({path:N,bytes:ne,reason:"size_cap"}),!1;let L=qa(c,W,N);return await WY(u$(L),{recursive:!0}),await _je(ee,L),I.set(N,await eee(L)),P+=ne,!0}catch{return M.push({path:N,bytes:ne,reason:"copy_error"}),!1}},$=(N,W)=>N.reduce(async(ee,ne)=>{let ye=await ee;return await z(ne,W)&&ye.push(ne),ye},Promise.resolve([])),J=await $(f,"untracked"),Q=S===void 0&&p.length>0?await $(p,"tracked"):[],K={version:1,id:d,createdAtMs:a,threadId:e.threadId,turnRef:e.turnRef,cwd:e.cwd,repoRoot:y,branch:_,headCommit:v,stashCommit:S,safetyRef:C,trackedPaths:p,untrackedPaths:J,trackedFallbackPaths:Q,skippedFiles:M,copiedBytes:P,durationMs:r()};await dje(qa(c,"manifest.json"),`${JSON.stringify(K,null,2)}
|
|
624
|
+
`)}function QX(e){switch(b(e.type)){case"reasoning":return"reasoning";case"agentMessage":return"assistant";case"message":return b(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"mcpToolCall":case"dynamicToolCall":case"collabAgentToolCall":return"toolCall";case"sleep":case"imageGeneration":return"agentStatus";case"agentStatus":return"agentStatus";case"agentTaskUpdate":return"agentTaskUpdate";default:return}}function XX(e){return e.flatMap((n,t)=>{if(!se(n))return[];let r=QX(n);return r===void 0||r==="webSearch"?[]:og(n,t).filter(o=>o.body.trim()!=="").map(o=>({snapshotIndex:t,providerItemType:b(n.type),itemId:b(n.id),streamKind:r,body:o.body,structured:o.structured}))})}function K2(e,n){let t=b(e.kind)??"codex_output";return{...e,item_id:n,transcript_unit_id:b(e.divider_identity)??`${t}:${n}`}}function W2(e,n,t,r){if(t==="webSearch")return`local-codex-search-${BX("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:",toolCall:"tool-call:",agentStatus:"agent-status:",agentTaskUpdate:"agent-task:"};return`local-codex-stream-${BX("sha256").update(`${e}:${n}:${o[t]}${r}`).digest("hex").slice(0,32)}`}function Rv(e){let n=O(e.turn),t=O(e.item),r=O(t?.turn);return b(n?.id)??b(e.turnId)??b(e.turn_id)??b(t?.turnId)??b(t?.turn_id)??b(r?.id)}var X2e,V2=B(()=>{"use strict";os();Zt();qt();X2e={pending:"PENDING",inProgress:"IN_PROGRESS",completed:"COMPLETED"}});function eY(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 YX,nY=B(()=>{"use strict";YX="edge_blocked"});function H2(e){return a$e.test(e)}function wT(e){let n=s$e.test(e),t=n?e.match(d$e)?.[1]:void 0,r=t===void 0?void 0:Number.parseInt(t,10);return{status:c$e(e),requestId:f$e(e),edgeBlocked:eY(e),oauthExpired:H2(e),providerOutage:n,holdCeilingMinutes:r!==void 0&&r>0?r:void 0,providerOutageRoute:n?{provider:e.match(u$e)?.[1],model:e.match(l$e)?.[1]}:void 0,message:p$e(e)}}function ST(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 rY(e){return e.status!==void 0||e.requestId!==void 0||e.edgeBlocked||e.oauthExpired||e.providerOutage}function oY(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=${YX}]`),n.oauthExpired&&t.push(`Claude login expired on this computer - run \`claude\` in a terminal there and sign in again, then retry [failure_class=${Sg}]`),t.length===0?e:`${e} (${t.join(", ")})`}function c$e(e){for(let n of r$e){let t=e.match(n)?.[1];if(t!==void 0)return Number.parseInt(t,10)}}function f$e(e){for(let n of o$e){let t=e.match(n)?.[1];if(t!==void 0)return t}}function p$e(e){let n=e.match(i$e)?.[1],r=(n===void 0?e:m$e(n)).trim();return r.length<=tY?r:`${Ui(r,tY-1)}\u2026`}function m$e(e){try{return JSON.parse(`"${e}"`)}catch{return e}}var tY,Sg,r$e,o$e,i$e,a$e,s$e,d$e,u$e,l$e,Ev=B(()=>{"use strict";nY();os();tY=200,Sg="claude_oauth_expired",r$e=[/\bAPI Error:?\s*([1-5]\d{2})\b/i,/\b(?:HTTP|status(?:\s+code)?)[\s:]+([1-5]\d{2})\b/i],o$e=[/"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/],i$e=/"error"\s*:\s*\{[^{}]*?"message"\s*:\s*"((?:[^"\\]|\\.){1,500})"/,a$e=/\boauth\b[\s\S]{0,120}?\b(?:expired|revoked|could not be refreshed)\b/i;s$e=/"code"\s*:\s*"provider_outage"/,d$e=/"hold_ceiling_minutes"\s*:\s*(\d{1,4})\b/,u$e=/"provider"\s*:\s*"([^"]{1,100})"/,l$e=/"model"\s*:\s*"([^"]{1,100})"/});function CT(e){return e!==void 0&&h$e.has(e)}function v$e(e){if(e===void 0)return;let n=b(e.type);if(n!=="mcpToolCall"&&n!=="dynamicToolCall"&&n!=="collabAgentToolCall"||b(e.status)!=="completed"||e.error!==void 0&&e.error!==null||e.success===!1)return;let t=b(e.tool)??"";return(t.split("__").pop()??t)===y$e?"reply":"action"}function fY(e,n){let t=v$e(n);t==="reply"?e.agentReplyToolCallSeen=!0:t==="action"&&(e.agentActionToolCallSeen=!0)}function w$e(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 S$e(e){return e!=="reasoning"}function k$e(e){return e!==void 0&&e.startsWith(pY)}function C$e(e){for(let n of e){let t=mY(O(n));if(t!==void 0)return t}}function mY(e){if(e===void 0)return;let n=b(e.codex_protocol_failure_reason)??b(e.protocolFailureReason);if(n!==void 0)return n;let t=b(e.type);if(t!=="function_call_output"&&t!=="custom_tool_call_output")return;let r=b(e.output)??b(e.result)??b(e.text)??b(e.content),o=T$e(r);return o===void 0?void 0:`${pY}: ${o}`}function T$e(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 hY(){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 gY(e,n,t){let r=[];return e.phase==="running"&&H$e(e,t,r),yY(e,n,t,r),r}function yY(e,n,t,r){if(n.source==="lifecycle"){q$e(e,n.kind,n.reason,t,r);return}if(e.phase==="dead"){r.push(dt("pipeline.loop.event_after_death",{source:n.source}));return}if(e.phase==="closing"){r.push(dt("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}W$e(e,n.turnId,n.snapshot,t,r);return}E$e(e,n,t,r)}function R$e(e){return I$e.has(e)}function E$e(e,n,t,r){let o=n.notification.method,i=n.notification.params??{};if(o===Ov)return;if(o===Cg){J$e(e,i,t,r);return}if(!A$e.has(o))return;let s=Rv(i)??AT(e);if(s===void 0){r.push(dt("pipeline.loop.notification_without_turn",{method:o}));return}if(e.terminalTurnIds.has(s)){r.push(dt("pipeline.loop.notification_for_terminal_turn",{method:o,turn_id:s}));return}let d=e.turns.get(s);if(d===void 0){let p=t.sourceSeqForTurn(s);if(p===void 0){V$e(e,s,n,r);return}d=$$e(e,s,p)}if(d.notificationCount+=1,R$e(o)&&(d.modelInteractionSeen=!0,d.unresolvedUpstreamErrorHttpStatus=void 0),o==="turn/started")return;if(o==="turn/completed"){F$e(d,r);return}let u=P$e.get(o);if(u!==void 0){let p=B$e(o,i,d,{costCap402Seen:e.costCap402Seen,midStreamResumeAttemptAtMs:t.midStreamResumeAttemptAtMsForSeq?.(d.sourceSeq),freshSessionResumeAttemptAtMs:t.freshSessionResumeAttemptAtMsForSeq?.(d.sourceSeq)});p.autoResumeMidStreamStall?r.push(dt("codex.mid_stream_stall_auto_resume_flagged",{thread_key:t.threadKey,turn_id:d.turnId,source_seq:d.sourceSeq,reason:cp(i)})):p.midStreamResumeRateLimitSuppressed?r.push(dt("codex.mid_stream_stall_resume_suppressed_rate_limit",{thread_key:t.threadKey,turn_id:d.turnId,source_seq:d.sourceSeq,reason:cp(i)})):p.midStreamResumeAttemptBurnedAtMs!==void 0&&(r.push(dt("codex.mid_stream_stall_second_stall_after_resume",{thread_key:t.threadKey,turn_id:d.turnId,source_seq:d.sourceSeq,resume_attempt_at_ms:p.midStreamResumeAttemptBurnedAtMs,reason:cp(i),fresh_session_resume_granted:p.freshSessionResumeMidStreamStall===!0})),p.freshSessionResumeMidStreamStall===!0&&r.push(dt("codex.mid_stream_stall_fresh_session_resume_flagged",{thread_key:t.threadKey,turn_id:d.turnId,source_seq:d.sourceSeq,resume_attempt_at_ms:p.midStreamResumeAttemptBurnedAtMs,reason:cp(i)}))),p.autoRetryPreFirstByteStall?r.push(dt("codex.pre_first_byte_stall_auto_retry_flagged",{thread_key:t.threadKey,turn_id:d.turnId,source_seq:d.sourceSeq,reason:cp(i),phase:b(i.idleStreamPhase)??"pre_first_byte",idle_threshold_ms:ie(i.idleStreamThresholdMs)??null,evidence_class:Z2(d)})):p.costCapAutoRetrySuppressed&&r.push(dt("codex.pre_first_byte_stall_retry_suppressed_cost_cap",{thread_key:t.threadKey,turn_id:d.turnId,source_seq:d.sourceSeq,reason:cp(i),flavor:i.midStreamResumableStall===!0?"mid_stream_resume":"pre_first_byte_retry"})),TT(e,d,u,cp(i),r,t,u,p,o===Dv?"interrupted":"failed");return}if(o==="error"){d.errorNotificationCount+=1;let p=SFe(i);p!==void 0&&(d.toolFatalSeen=!0,d.toolFatalDetail===void 0&&p!==""&&(d.toolFatalDetail=p),r.push(dt("codex.tool_fatal_captured",{turn_id:d.turnId,detail:p===""?null:p})));let h=cFe(i);h!==void 0&&(d.upstreamRejectedSeen=!0,d.upstreamRejectedDetail===void 0&&h!==""&&(d.upstreamRejectedDetail=h),r.push(dt("codex.upstream_rejection_captured",{turn_id:d.turnId,detail:h===""?null:h})));let y=hFe(i);if(y!==void 0){d.providerOutageFlaggedSeen=!0,d.providerOutageDetail===void 0&&y!==""&&(d.providerOutageDetail=y);let T=gFe(i);d.providerOutageRoute===void 0&&(d.providerOutageRoute=T),r.push(dt("codex.provider_outage_flagged_captured",{turn_id:d.turnId,detail:y===""?null:y,provider:T?.provider??null,model:T?.model??null,hold_ceiling_ms:T?.holdCeilingMs??null}))}let m=IT(i),_=Y$e(i);_!==void 0&&(d.edgeBlockEvidence=_),m!==void 0&&(d.lastUpstreamErrorHttpStatus===void 0||m>d.lastUpstreamErrorHttpStatus)&&(d.lastUpstreamErrorHttpStatus=m),m===402&&!e.costCap402Seen&&(e.costCap402Seen=!0,r.push(dt("codex.cost_cap_402_seen",{turn_id:d.turnId})));let w=Z$e(i),v=!1;if(w!==void 0)d.lastUpstreamErrorReason=w,r.push(dt("codex.upstream_error_captured",{turn_id:d.turnId,reason:w}));else{let T=qv(i);T!==void 0&&(d.lastErrorDiagnosticText=T,v=!0,r.push(dt("codex.error_without_http_status_captured",{turn_id:d.turnId,diagnostic_text:T})))}p===void 0&&h===void 0&&y===void 0&&m===void 0&&w===void 0&&!v&&(d.unattributedErrorNotificationCount+=1);let S=uFe(i);S!==void 0&&(d.lastUpstreamErrorSummary=S,e.lastUpstreamErrorSummary=S,r.push(dt("codex.upstream_turn_error_captured",{turn_id:d.turnId,upstream_error:S})));let C=[w,S,d.lastErrorDiagnosticText].some(T=>T!==void 0&&Y2.test(T))?429:void 0,A=m??C;A!==void 0&&(d.unresolvedUpstreamErrorHttpStatus=A);return}if(o==="item/started"){let p=O(i.item),h=b(p?.id),y=p?.phase,m=b(y);p!==void 0&&b(p.type)==="agentMessage"&&(h!==void 0&&p.delivery==="async"&&(d.asyncAssistantItemIds.add(h),d.assistantPhasesByItemId.set(h,"commentary")),m==="commentary"||m==="final_answer"?h!==void 0&&d.assistantPhasesByItemId.set(h,u2(p)):y!==void 0&&r.push(dt("harness.assistant_phase_rejected",{turn_id:s,...h===void 0?{}:{item_id:h},phase:y})))}let c=M$e(o,i,d);if(c!==void 0){uY(d,{...i,item:c},t,r);return}if(o==="item/completed"||o==="response_item"){uY(d,i,t,r);return}let l=i;if(o==="item/agentMessage/delta"){let p=xg(i);p!==void 0&&(i.delivery==="async"||O(i.item)?.delivery==="async")&&(d.asyncAssistantItemIds.add(p),d.assistantPhasesByItemId.set(p,"commentary"));let h=i.phase??O(i.item)?.phase,y=b(h);if(y==="commentary"||y==="final_answer"){if(p!==void 0){let _=d.asyncAssistantItemIds.has(p)?"commentary":y;d.assistantPhasesByItemId.set(p,_),l={...i,phase:_}}}else if(h!==void 0)r.push(dt("harness.assistant_phase_rejected",{turn_id:s,...p===void 0?{}:{item_id:p},phase:h}));else if(p!==void 0){let m=d.assistantPhasesByItemId.get(p);m!==void 0&&(l={...i,phase:m})}}let f=WX(o,l);if(f===void 0){if(o==="turn/plan/updated"){let p=b(i.threadId);r.push(dt("harness.plan_snapshot_rejected",{turn_id:s,...p===void 0?{}:{thread_id:p}}))}return}if(d.phase==="active"){if(S$e(f.streamKind))d.reasoningStepsWithoutProgress=0;else if(d.reasoningStepsWithoutProgress+=1,d.reasoningStepsWithoutProgress>dY){let p=w$e(d.reasoningStepsWithoutProgress);r.push(dt("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:dY})),TT(e,d,"failed",p,r,t,"interrupted");return}}SY(d,f,t,r)}function M$e(e,n,t){let r=O(n.item),o=b(r?.id),i=b(n.turnId),a=ie(n.completedAtMs)??ie(n.startedAtMs);if((e==="item/started"||e==="item/completed")&&b(r?.type)==="contextCompaction"&&o!==void 0){let s=e==="item/started",d=s?"START":"END",u=O$e(t,o);return{type:"agentStatus",id:`${o}:${s?"start":"complete"}`,title:s?"Context compaction started":"Context compaction completed",severity:"info",provider:"codex",eventKind:"compaction_boundary",dividerKind:"context_compaction",dividerIdentity:u,...a===void 0?{}:{occurredAtMs:a},rawProviderMetadata:{phase:d,lifecycle:e,harness:"codex",compactionItemId:o,...i===void 0?{}:{turnId:i}}}}if(e==="thread/compacted"&&i!==void 0){let s=t.compactionThreadEventIndex;return t.compactionThreadEventIndex+=1,{type:"agentStatus",id:s===0?`thread-compacted:${i}`:`thread-compacted:${i}:${s}`,title:"Thread compacted",severity:"info",provider:"codex",eventKind:"compaction_boundary",dividerKind:"context_compaction",dividerIdentity:D$e(t),rawProviderMetadata:{phase:"END",lifecycle:e,harness:"codex",turnId:i}}}}function O$e(e,n){let t=e.compactionDividerIdentities.get(n);if(t!==void 0)return e.lastCompactionItemId=n,t;let r=e.lastCompactionItemId===void 0&&e.compactionFallbackIdentity!==void 0?e.compactionFallbackIdentity:`agent_status_event:context_compaction:${e.turnId}:${n}`;return e.compactionDividerIdentities.set(n,r),e.lastCompactionItemId=n,r}function D$e(e){let n=e.lastCompactionItemId===void 0?void 0:e.compactionDividerIdentities.get(e.lastCompactionItemId);if(e.lastCompactionItemId=void 0,n!==void 0)return e.compactionFallbackIdentity=void 0,n;e.compactionFallbackIndex+=1;let t=`agent_status_event:context_compaction:${e.turnId}:fallback:${e.compactionFallbackIndex}`;return e.compactionFallbackIdentity=t,t}function q$e(e,n,t,r,o){if(n==="codexDied"){if(e.phase==="dead")return;for(let i of[...e.turns.values()])TT(e,i,"failed",t,o,r,"interrupted");for(let i of[...e.bufferedTurns.keys()])wY(e,i,t,o);e.phase="dead",o.push(dt("pipeline.loop.codex_died",{reason:t}));return}e.phase==="running"&&(e.phase="closing",o.push(dt("pipeline.loop.closing",{kind:n,reason:t})))}function $$e(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,compactionDividerIdentities:new Map,lastCompactionItemId:void 0,compactionFallbackIdentity:void 0,compactionFallbackIndex:0,compactionThreadEventIndex:0,assistantPhasesByItemId:new Map,asyncAssistantItemIds:new Set,items:[]};return e.turns.set(n,r),r}function F$e(e,n){if(e.phase==="completing"){n.push(dt("pipeline.loop.duplicate_turn_completed",{turn_id:e.turnId}));return}e.phase="completing",n.push({type:"requestSnapshot",turnId:e.turnId})}function _Y(e){return e===429||e>=500&&e<=599?"transient":"deterministic"}function e$(){return process.env.LINZUMI_DISABLE_UPSTREAM_ERROR_TURN_FATE_FIX==="1"}function N$e(e){let n=bY.exec(e);return n!==null?_Y(Number(n[1])):!e$()&&Y2.test(e)||j$e.test(e)?"transient":"deterministic"}function Z2(e){let n=!1,t=e.upstreamRejectedSeen||e.providerOutageFlaggedSeen||e.toolFatalSeen||e.modelInteractionSeen||e.unattributedErrorNotificationCount>0,r=0;e.lastUpstreamErrorHttpStatus!==void 0&&(r+=1,_Y(e.lastUpstreamErrorHttpStatus)==="transient"?n=!0:t=!0);for(let o of[e.lastUpstreamErrorReason,e.lastErrorDiagnosticText])o!==void 0&&(r+=1,N$e(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 Q2(e){if(e.lastUpstreamErrorHttpStatus===429)return!0;for(let n of[e.lastUpstreamErrorReason,e.lastErrorDiagnosticText]){if(n===void 0)continue;let t=bY.exec(n);if(t!==null&&Number(t[1])===429||!e$()&&Y2.test(n))return!0}return!1}function z$e(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 G$e(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 U$e(e){return` (An automatic resume was attempted at ${new Date(e).toISOString()} after the stream stalled; it did not complete.)`}function B$e(e,n,t,r={costCap402Seen:!1}){let o=e==="turn/failed"&&b(O(n.error)?.code)==="idle_stream_timeout",i=e==="turn/failed"&&n.retryable===!0,a=(e==="turn/failed"||e==="turn/aborted")&&as(n.fate)?n.fate:void 0,s=(()=>{if(e!=="turn/failed")return;let M=O(n.route_outage_hold);if(M===void 0)return;let I=ie(M.hold_ceiling_ms);return{provider:b(M.provider),model:b(M.model),holdCeilingMs:I!==void 0&&I>0?I:void 0}})(),d=e==="turn/failed"&&n.failure_class===Sg?Sg:void 0;if(!o)return{autoRetryPreFirstByteStall:!1,messageStateRetryable:i,costCapAutoRetrySuppressed:!1,messageStateFate:a,messageStateFailureClass:d,autoResumeMidStreamStall:!1,midStreamResumeRateLimitSuppressed:!1,...s===void 0?{}:{messageStateRouteOutageHold:s}};let u=r.midStreamResumeAttemptAtMs,c=u!==void 0,l=Z2(t)!=="deterministic",f=n.preFirstByteStall===!0&&l,p=n.midStreamResumableStall===!0,h=p&&Q2(t),y=Z2({...t,modelInteractionSeen:!1})!=="deterministic",m=p&&!c&&!h&&y,_=r.freshSessionResumeAttemptAtMs!==void 0,w=p&&c&&!_&&!h&&y,v=(f&&!c||m||w)&&r.costCap402Seen,S=f&&!c&&!v,C=m&&!v,A=w&&!v,T=p&&!c&&h;return{autoRetryPreFirstByteStall:S,messageStateRetryable:f||i,costCapAutoRetrySuppressed:v,messageStateFate:a??(Q2(t)?"rate_limited":"transient_upstream"),messageStateFailureClass:d,autoResumeMidStreamStall:C,midStreamResumeRateLimitSuppressed:T,...c?{midStreamResumeAttemptBurnedAtMs:u}:{},...A?{freshSessionResumeMidStreamStall:!0}:{}}}function xY(e){return e>0?` (${e} automatic ${e===1?"retry":"retries"} did not help.)`:""}function TT(e,n,t,r,o,i,a=t,s={autoRetryPreFirstByteStall:!1,messageStateRetryable:!1,costCapAutoRetrySuppressed:!1,messageStateFate:void 0,messageStateFailureClass:void 0,autoResumeMidStreamStall:!1,midStreamResumeRateLimitSuppressed:!1},d="failed"){let u=TY(s.messageStateFate,i,{sourceSeq:n.sourceSeq,upstreamHttpStatus:n.lastUpstreamErrorHttpStatus}),c=s.autoRetryPreFirstByteStall||s.costCapAutoRetrySuppressed?`${r}${xY(i.autoRetryAttemptsForSeq?.(n.sourceSeq)??0)}${s.costCapAutoRetrySuppressed?vY:""}`:r;if(s.midStreamResumeRateLimitSuppressed&&(c+=L$e),t==="failed")if(s.midStreamResumeAttemptBurnedAtMs!==void 0)c+=s.freshSessionResumeMidStreamStall===!0?G$e(s.midStreamResumeAttemptBurnedAtMs):z$e(s.midStreamResumeAttemptBurnedAtMs);else{let f=i.midStreamResumeAttemptAtMsForSeq?.(n.sourceSeq);f!==void 0&&(c+=U$e(f))}for(let f of n.items){if(!f.posted||CT(f.emittedStreamState))continue;let p=wg(f.wireItemKey,f.content,a);o.push({type:"enqueue",kind:Qt.finalizeRow,data:{...PT(i,n,f,p),stream_snapshot_index:Mv(f),terminal_outcome:t,reason:r},resolution:"must_ack"}),f.emittedStreamState=a,f.lastEmittedBody=p.body}let l=i.sessionExecutesRecoveryGrants===!0&&t==="failed"&&(s.autoRetryPreFirstByteStall||s.autoResumeMidStreamStall||s.freshSessionResumeMidStreamStall===!0);o.push({type:"enqueue",kind:Qt.messageState,data:{thread_key:i.threadKey,turn_id:n.turnId,seq:n.sourceSeq,status:l?"recovering":d,reason:c,...s.messageStateRetryable&&!l?{retryable:!0}:{},...u===void 0?{}:{fate:u},...s.messageStateFailureClass===void 0?{}:{failure_class:s.messageStateFailureClass},...(()=>{let f=u===void 0?void 0:i.ladderHistoryForSeq?.(n.sourceSeq,u);return f===void 0?{}:{ladder:f}})(),...(()=>{let f=n.lastUpstreamErrorSummary??e.lastUpstreamErrorSummary;return f===void 0?{}:{upstream_error:f}})()},resolution:d==="interrupted"?"must_reach_consensus":"must_ack"}),o.push({type:"turnTerminal",turnId:n.turnId,outcome:t,reason:c,...s.autoRetryPreFirstByteStall?{retryableEmptyTurn:!0}:{},...s.autoResumeMidStreamStall?{autoResumeMidStreamStall:!0}:{},...s.freshSessionResumeMidStreamStall?{freshSessionResumeMidStreamStall:!0}:{},...u===void 0?{}:{fate:u},...u==="route_outage"?{routeOutageHold:{provider:s.messageStateRouteOutageHold?.provider,model:s.messageStateRouteOutageHold?.model,holdCeilingMs:s.messageStateRouteOutageHold?.holdCeilingMs}}:{}}),e.turns.delete(n.turnId),n$(e,n.turnId)}function J$e(e,n,t,r){let o=b(n.turnId),i=b(n.reason)??"turn source-seq mapping failed";if(o===void 0||e.terminalTurnIds.has(o))return;let a=e.turns.get(o);if(a!==void 0){TT(e,a,"failed",i,r,t);return}wY(e,o,i,r)}function wY(e,n,t,r){let o=e.bufferedTurns.get(n),i=o?.length??0,a=o?.[0],s=o?.[i-1];r.push({type:"enqueue",kind:Qt.unmappedTurnFailure,data:{turn_id:n,buffered_event_count:i,first_event:kT(a),last_event:kT(s),reason:"A response was produced but could not be delivered because its turn source mapping never arrived. Please retry."},coalesceKey:`unmapped-turn-failure:${n}`,resolution:"must_ack"}),r.push(dt("pipeline.loop.buffered_turn_failed",{level:"error",turn_id:n,buffered_event_count:i,first_event:kT(a),last_event:kT(s),reason:t})),e.bufferedTurns.delete(n),r.push({type:"turnTerminal",turnId:n,outcome:"failed",reason:t}),n$(e,n)}function kT(e){return e===void 0?"none":e.source==="codex"?e.notification.method:e.source==="snapshot"?"snapshot":`lifecycle/${e.kind}`}function SY(e,n,t,r){if(e.phase!=="active"){r.push(dt("pipeline.loop.delta_for_completing_turn",{turn_id:e.turnId,stream_kind:n.streamKind}));return}let o=CY(e,n.streamKind,n.itemId,t);if(o.completed){r.push(dt("pipeline.loop.delta_for_completed_item",{turn_id:e.turnId,item_key:o.itemKey}));return}o.content=HX(o.content,n);let i=o.nextDeltaIndex;o.nextDeltaIndex+=1;let a=n.streamKind==="terminalInput"?"completed":"streaming";kY(e,o,i,a,t,r)}function uY(e,n,t,r){let o=O(n.item);o!==void 0&&(e.protocolFailureReason??=mY(o)),fY(e,o??n);let i=ZX(n);if(i===void 0)return;if(i.streamKind==="webSearch"){SY(e,{streamKind:"webSearch",itemId:i.itemId,queries:i.content.streamKind==="webSearch"?i.content.queries:[]},t,r);return}if(e.phase!=="active"){r.push(dt("pipeline.loop.item_completed_for_completing_turn",{turn_id:e.turnId,stream_kind:i.streamKind}));return}let a=CY(e,i.streamKind,i.itemId,t,{adoptOpenIdLess:!0});if(a.completed&&!K$e(a,i))return;a.content=i.content,a.completed=!0;let s="completed",d=wg(a.wireItemKey,a.content,s);a.posted&&d.body===a.lastEmittedBody&&CT(a.emittedStreamState)||kY(e,a,Math.max(a.nextDeltaIndex-1,0),s,t,r)}function K$e(e,n){return e.identity.streamKind!==n.streamKind?!1:n.streamKind==="agentStatus"||n.streamKind==="agentTaskUpdate"}function kY(e,n,t,r,o,i){let a=wg(n.wireItemKey,n.content,r);if(!n.posted){if(a.body.trim()==="")return;i.push({type:"enqueue",kind:Qt.postStreamedRow,data:{...PT(o,e,n,a),delta_index:t,stream_snapshot_index:Mv(n)},resolution:"must_ack"}),n.posted=!0,n.emittedStreamState=r,n.lastEmittedBody=a.body,r==="completed"&&(n.completed=!0);return}i.push({type:"enqueue",kind:Qt.streamSnapshot,data:{...PT(o,e,n,a),delta_index:t,stream_snapshot_index:Mv(n)},coalesceKey:n.itemKey,resolution:"must_ack"}),n.emittedStreamState=r,n.lastEmittedBody=a.body}function CY(e,n,t,r,o={adoptOpenIdLess:!1}){if(n==="webSearch")return e.items.find(a=>a.identity.streamKind==="webSearch")??lY(e,"webSearch",`web-search:${e.turnId}`,r);if(t!==void 0){let a=e.items.find(s=>s.identity.streamKind===n&&s.identity.itemId===t);if(a!==void 0)return a}let i=e.items.find(a=>a.identity.streamKind===n&&a.identity.itemId===void 0&&!a.completed);return t===void 0&&i!==void 0||t!==void 0&&o.adoptOpenIdLess&&i!==void 0?i:lY(e,n,t,r)}function lY(e,n,t,r){let o={turnId:e.turnId,itemId:t,itemIndex:e.items.length,streamKind:n},i=bX(o),a=t??i,s={identity:o,itemKey:i,wireItemKey:a,clientMessageId:W2(r.instanceId,e.turnId,n,a),content:VX(n),posted:!1,completed:!1,emittedStreamState:void 0,lastEmittedBody:void 0,nextDeltaIndex:0,nextStreamSnapshotIndex:1};return e.items.push(s),s}function W$e(e,n,t,r,o){if(e.terminalTurnIds.has(n)){o.push(dt("pipeline.loop.duplicate_snapshot",{turn_id:n}));return}let i=e.turns.get(n);if(i===void 0){o.push(dt("pipeline.loop.snapshot_for_unknown_turn",{turn_id:n}));return}if(i.phase!=="completing"){o.push(dt("pipeline.loop.snapshot_for_active_turn",{turn_id:n}));return}let a=Array.isArray(t.items)?t.items:[];i.protocolFailureReason??=C$e(a);for(let te of a)fY(i,O(te));let s=XX(a),d=new Set,u=new Map;s.forEach((te,he)=>{if(te.itemId===void 0)return;let me=i.items.find(Se=>Se.posted&&!d.has(Se.itemKey)&&Se.identity.streamKind===te.streamKind&&Se.identity.itemId===te.itemId);me!==void 0&&(d.add(me.itemKey),u.set(he,me))});let c=new Map;for(let te of i.items)te.posted&&!d.has(te.itemKey)&&te.identity.itemId===void 0&&c.set(te.identity.streamKind,(c.get(te.identity.streamKind)??0)+1);let l=new Map;s.forEach((te,he)=>{u.has(he)||l.set(te.streamKind,(l.get(te.streamKind)??0)+1)});let f=(te,he)=>{let me=wg(te.wireItemKey,te.content,"completed").body.trim(),Se=he.body.trim();return Se.startsWith(me)||me.startsWith(Se)};s.forEach((te,he)=>{if(u.has(he))return;let me=l.get(te.streamKind)===c.get(te.streamKind);if(te.itemId!==void 0&&!me)return;let Se=i.items.find(Ie=>Ie.posted&&!d.has(Ie.itemKey)&&Ie.identity.streamKind===te.streamKind&&Ie.identity.itemId===void 0);Se!==void 0&&(te.itemId!==void 0&&!f(Se,te)||(d.add(Se.itemKey),u.set(he,Se)))});for(let te of i.items){let he=[...u.entries()].find(([,Se])=>Se.itemKey===te.itemKey);if(he!==void 0){let Se=s[he[0]];if(Se===void 0||te.identity.streamKind==="assistant"&&CT(te.emittedStreamState)&&te.lastEmittedBody===Se.body)continue;o.push({type:"enqueue",kind:Qt.finalizeRow,data:{thread_key:r.threadKey,turn_id:i.turnId,item_key:te.itemKey,item_id:te.wireItemKey,stream_kind:te.identity.streamKind,item_index:te.identity.itemIndex,source_seq:i.sourceSeq,client_message_id:te.clientMessageId,body:Se.body,structured:{...K2(Se.structured,te.wireItemKey),...te.completed?{}:{completion_provenance:"end_of_turn_finalize"}},stream_snapshot_index:Mv(te),terminal_outcome:"completed"},resolution:"must_ack"}),te.emittedStreamState="completed",te.lastEmittedBody=Se.body;continue}if(!te.posted||CT(te.emittedStreamState))continue;let me=wg(te.wireItemKey,te.content,"completed");o.push({type:"enqueue",kind:Qt.finalizeRow,data:{...PT(r,i,te,{...me,structured:{...me.structured,completion_provenance:"end_of_turn_finalize"}}),stream_snapshot_index:Mv(te),terminal_outcome:"completed"},resolution:"must_ack"}),te.emittedStreamState="completed",te.lastEmittedBody=me.body}s.forEach((te,he)=>{if(u.has(he))return;let me=te.itemId??`${i.turnId}:${te.streamKind}:snapshot:${te.snapshotIndex}`;o.push({type:"enqueue",kind:Qt.postCompletedRow,data:{thread_key:r.threadKey,turn_id:i.turnId,item_key:`${i.turnId}:${te.streamKind}:${te.itemId??`snapshot:${te.snapshotIndex}`}`,item_id:me,stream_kind:te.streamKind,snapshot_index:te.snapshotIndex,source_seq:i.sourceSeq,client_message_id:W2(r.instanceId,i.turnId,te.streamKind,me),body:te.body,structured:K2(te.structured,me),stream_snapshot_index:1},resolution:"must_ack"})});let p=i.items.some(te=>te.identity.streamKind==="assistant"&&te.posted)||s.some(te=>te.streamKind==="assistant"),h=i.agentActionToolCallSeen||i.items.some(te=>te.posted&&aY.has(te.identity.streamKind)&&!(te.content.streamKind==="agentStatus"&&(te.content.severity==="error"||te.content.providerItemType==="sleep")))||s.some(te=>te.providerItemType!=="sleep"&&aY.has(te.streamKind)&&!(te.streamKind==="agentStatus"&&te.structured.severity==="error")),y=r.linzumiAgentSession===!0&&p&&!i.agentReplyToolCallSeen&&!h,m=p&&!y,_=m&&!e$()?i.unresolvedUpstreamErrorHttpStatus:void 0,w=_!==void 0,v=i.protocolFailureReason,S=v!==void 0&&k$e(v)&&m,C=S?void 0:v,A=!m&&v===void 0&&i.lastUpstreamErrorReason===void 0?y?{cause:b$e}:kFe(i,s.length,i.lastUpstreamErrorSummary??e.lastUpstreamErrorSummary):void 0,T=!m&&C===void 0&&i.upstreamRejectedSeen,M=!m&&C===void 0&&i.providerOutageFlaggedSeen,I=nFe(i.lastUpstreamErrorHttpStatus),P=!m&&C===void 0&&i.edgeBlockEvidence!==void 0,z=T&&!M&&!I,$=M||z?bFe({providerOutageFlagged:M,priorConsecutiveIsolatedRejections:e.consecutiveIsolatedRejections,stormDetail:i.providerOutageDetail,rejectionDetail:i.upstreamRejectedDetail}):void 0,J=$?.kind==="isolated_retry";z?e.consecutiveIsolatedRejections+=1:e.consecutiveIsolatedRejections=0;let Q=!m&&C===void 0&&i.lastUpstreamErrorReason===void 0&&i.lastErrorDiagnosticText===void 0&&!T&&eFe(i.lastUpstreamErrorHttpStatus),K=!m&&C===void 0&&i.lastUpstreamErrorReason===void 0&&I,Z=!m&&C===void 0&&i.lastUpstreamErrorReason===void 0&&!T&&!Q&&!K&&i.toolFatalSeen,N=$!==void 0?$.reason:K?tFe(i.lastUpstreamErrorHttpStatus,i.upstreamRejectedDetail??i.lastErrorDiagnosticText):Q?rFe(i.lastUpstreamErrorHttpStatus):Z?iFe(i.toolFatalDetail):i.lastUpstreamErrorReason??(y?_$e:A===void 0?iY:`${iY} [${A.cause}]`),W=A!==void 0&&C===void 0&&i.modelInteractionSeen&&i.lastErrorDiagnosticText===void 0&&!T&&!Q&&!K&&!Z;W?(e.consecutiveEmptyTurns+=1,e.lastEmptyTurnCause=A?.cause):(e.consecutiveEmptyTurns=0,e.lastEmptyTurnCause=void 0);let ee=W&&e.consecutiveEmptyTurns>sY,ne=W&&!ee||J,ye=r.autoRetryAttemptsForSeq?.(i.sourceSeq)??0,L=ne&&e.costCap402Seen&&ye<Da,ce=ne&&!L;P&&o.push(dt("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 pe=ee?`${x$e} (${e.consecutiveEmptyTurns} in a row${A===void 0?"":`: ${A.cause}`}).`:void 0,re=C??(_!==void 0?oFe(_,i.lastUpstreamErrorSummary??e.lastUpstreamErrorSummary):m?void 0:pe??N),le=re===void 0?void 0:`${re}${xY(W&&!ee?ye:0)}${L?vY:""}`,Oe=A!==void 0&&!ee&&!T&&!Q&&!K&&!Z||J||P||w,F=M?"route_outage":_!==void 0?C2(_):Oe?"transient_upstream":Q?i.lastUpstreamErrorHttpStatus===void 0?"transient_upstream":C2(i.lastUpstreamErrorHttpStatus):T||Z||K||ee||C!==void 0?"deterministic":Q2(i)?"rate_limited":"deterministic",H=TY(F,r,{sourceSeq:i.sourceSeq,upstreamHttpStatus:_??i.lastUpstreamErrorHttpStatus})??F;L&&o.push(dt("codex.empty_turn_auto_retry_suppressed_cost_cap",{thread_key:r.threadKey,turn_id:i.turnId,source_seq:i.sourceSeq,reason:re??null,isolated_rejection_retry_suppressed:J})),ee&&o.push(dt("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:sY,cause:A?.cause??null,last_upstream_error:i.lastUpstreamErrorSummary??e.lastUpstreamErrorSummary??null})),S?o.push(dt("codex.turn_completed_with_unsupported_tool_call_ignored",{thread_key:r.threadKey,turn_id:i.turnId,source_seq:i.sourceSeq,reason:v})):v!==void 0&&o.push(dt("codex.turn_completed_with_protocol_failure",{thread_key:r.threadKey,turn_id:i.turnId,source_seq:i.sourceSeq,reason:v})),y&&o.push(dt("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:s.length,agent_reply_tool_call_seen:i.agentReplyToolCallSeen,agent_action_tool_call_seen:i.agentActionToolCallSeen,retryable_empty_turn:Oe,empty_turn_loop_guard_tripped:ee})),w&&o.push(dt("codex.turn_demoted_late_upstream_error",{thread_key:r.threadKey,turn_id:i.turnId,source_seq:i.sourceSeq,http_status:_??null,fate:H,streamed_item_count:i.items.length,last_upstream_error:i.lastUpstreamErrorSummary??e.lastUpstreamErrorSummary??null})),p||o.push(dt("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:s.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:A?.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:K,last_upstream_error_http_status:i.lastUpstreamErrorHttpStatus??null,provider_outage_flagged:M,isolated_rejection_retry_granted:J,rejection_disposition:$?.kind??null,consecutive_isolated_rejections:e.consecutiveIsolatedRejections,retryable_empty_turn:Oe,empty_turn_loop_guard_tripped:ee,cost_cap_auto_retry_suppressed:L}));let V=r.sessionExecutesRecoveryGrants===!0&&ce;o.push({type:"enqueue",kind:Qt.messageState,data:{thread_key:r.threadKey,turn_id:i.turnId,seq:i.sourceSeq,...le===void 0?{status:"processed"}:{status:V?"recovering":"failed",reason:le,...Oe&&!V?{retryable:!0}:{},fate:H,...(()=>{let te=r.ladderHistoryForSeq?.(i.sourceSeq,H);return te===void 0?{}:{ladder:te}})(),...P?{failure_class:"edge_blocked"}:{},...(()=>{let te=i.lastUpstreamErrorSummary??e.lastUpstreamErrorSummary;return te===void 0?{}:{upstream_error:te}})()}},resolution:"must_ack"}),le===void 0&&(e.lastUpstreamErrorSummary=void 0),o.push(le===void 0?{type:"turnTerminal",turnId:i.turnId,outcome:"completed"}:{type:"turnTerminal",turnId:i.turnId,outcome:"failed",reason:le,...ce?{retryableEmptyTurn:!0}:{},fate:H,...H==="route_outage"?{routeOutageHold:{provider:i.providerOutageRoute?.provider,model:i.providerOutageRoute?.model,holdCeilingMs:i.providerOutageRoute?.holdCeilingMs}}:{}}),e.turns.delete(i.turnId),n$(e,i.turnId)}function V$e(e,n,t,r){let o=e.bufferedTurns.get(n);if(o===void 0){e.bufferedTurns.set(n,[t]),r.push(dt("pipeline.loop.turn_events_buffered",{turn_id:n}));return}o.push(t)}function H$e(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(dt("pipeline.loop.buffered_turn_drained",{turn_id:r,buffered_event_count:o.length}));for(let i of o)yY(e,i,n,t)}}function n$(e,n){for(e.terminalTurnIds.delete(n),e.terminalTurnIds.add(n);e.terminalTurnIds.size>g$e;){let t=e.terminalTurnIds.values().next().value;if(t===void 0)return;e.terminalTurnIds.delete(t)}}function AT(e){let n=[...e.turns.values()].filter(t=>t.phase==="active");return n.length===1?n[0]?.turnId:void 0}function PT(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 Mv(e){let n=e.nextStreamSnapshotIndex;return e.nextStreamSnapshotIndex+=1,n}function cp(e){return b(e.reason)??b(e.message)??b(O(e.error)?.message)??b(e.error)??"codex_turn_aborted"}function Z$e(e){let n=b(e.diagnostic_summary)??b(O(O(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=IT(e);return r===void 0?`Model gateway error: ${t}`:`Model gateway error (HTTP ${r}): ${t}`}function IT(e){let n=O(O(e.diagnostic_payload)?.error),t=O(n?.codexErrorInfo),o=[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 Q$e(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 X$e(e){return/(?:<!doctype\s+html|<html(?:\s|>))/i.test(e)||/@font-face/i.test(e)&&/cloudflare|cf-ray/i.test(e)}function Y$e(e){let n=O(O(e.diagnostic_payload)?.error),t=[b(e.diagnostic_summary),b(n?.message),b(e.message)],r=IT(e)??Q$e(t);if(r!==401&&r!==403)return;let o=t.find(a=>a!==void 0&&X$e(a)&&/cloudflare|cf-ray|\bblocked\b|access denied|\bchallenge\b|attention required/i.test(a));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 eFe(e){return e===void 0?!1:e===402||e===408||e===425||e===429||e>=500&&e<=599}function nFe(e){return e===void 0||e<400||e>499?!1:e!==402&&e!==408&&e!==425&&e!==429}function tFe(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 rFe(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 oFe(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 iFe(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 qv(e){let n=O(O(e.diagnostic_payload)?.error),t=b(e.message)??b(e.reason)??b(O(e.error)?.message)??b(e.error)??b(e.diagnostic)??b(n?.message)??b(O(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 kg(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 uFe(e){let n=O(e.error),t=O(O(e.diagnostic_payload)?.error),r=O(t?.error),o=IT(e),i=b(n?.type)??b(n?.code)??b(t?.type)??b(t?.code)??b(r?.type)??b(r?.code)??cY(n?.codexErrorInfo)??cY(t?.codexErrorInfo),a=kg(b(n?.message))??kg(b(r?.message))??kg(b(t?.message))??qv(e);if(o===void 0&&i===void 0){let u=hc(b(n?.message))??hc(b(r?.message))??hc(b(t?.message))??hc(b(e.message))??hc(b(e.reason))??hc(b(e.error))??hc(b(e.diagnostic))??hc(b(e.diagnostic_summary));u!==void 0&&(o=u.status,i=u.errorType,a=kg(u.message)??a)}let s=[o===void 0?void 0:String(o),i?.trim()===""?void 0:i?.trim()].filter(u=>u!==void 0).join(" "),d=s===""?a:a===void 0?s:`${s}: ${a}`;if(!(d===void 0||d===""))return d.slice(0,dFe)}function cY(e){if(typeof e=="string"&&e.trim()!=="")return e;let n=O(e);if(n===void 0)return;let t=Object.keys(n);return t.length===1?t[0]:void 0}function hc(e){if(e===void 0)return;let n=e.indexOf("{");if(n===-1)return;let t=qf(e.slice(n))??qf(e.slice(n,e.lastIndexOf("}")+1));if(t===void 0||b(t.type)!=="error")return;let r=O(t.error);if(r===void 0)return;let o=t.status;return{status:typeof o=="number"&&Number.isFinite(o)?o:void 0,errorType:b(r.type)??b(r.code),message:b(r.message)}}function lFe(e){let n=O(O(e.diagnostic_payload)?.error),t=O(n?.error),r=O(e.error),o=[{code:b(n?.code),message:b(n?.message)},{code:b(n?.type),message:b(n?.message)},{code:b(t?.code),message:b(t?.message)},{code:b(t?.type),message:b(t?.message)},{code:b(r?.code),message:b(r?.message)},{code:b(r?.type),message:b(r?.message)},{code:b(e.code),message:b(e.message)},{code:b(e.type),message:b(e.message)}];for(let i of o){let a=i.code?.trim();if(a!==void 0&&a!==""&&aFe.test(a))return{codeOrType:a,message:i.message}}}function cFe(e){let n=lFe(e),t=qv(e),r=t!==void 0&&sFe.test(t);return n===void 0&&!r?void 0:kg(n?.message)??t??""}function fFe(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 hFe(e){let n=O(O(e.diagnostic_payload)?.error),t=O(n?.error),r=O(e.error),o=[b(n?.code),b(n?.type),b(t?.code),b(t?.type),b(r?.code),b(r?.type),b(e.code),b(e.type)],i=[b(n?.message),b(t?.message),b(r?.message),b(e.message),b(e.reason)];if(o.some(s=>{let d=s?.trim();return d!==void 0&&d!==""&&X2.test(d)})){for(let s of i){let d=kg(s);if(d!==void 0&&mFe.test(d))return d}return qv(e)??""}}function TY(e,n,t){return t?.upstreamHttpStatus===402?e:e==="transient_upstream"&&n.routeOutageActive?.(t?.sourceSeq)===!0?"route_outage":e}function gFe(e){let n=O(O(e.diagnostic_payload)?.error),t=O(n?.error),r=O(e.error);for(let o of[t,n,r,e]){if(o===void 0)continue;let i=b(o.code)?.trim(),a=b(o.type)?.trim();if(!(i!==void 0&&i!==""&&X2.test(i)||a!==void 0&&a!==""&&X2.test(a)))continue;let d=o.hold_ceiling_minutes,u=typeof d=="number"&&Number.isFinite(d)&&d>0?Math.floor(d)*6e4:void 0;return{provider:b(o.provider),model:b(o.model),holdCeilingMs:u}}}function yFe(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 _Fe(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 bFe(e){return e.providerOutageFlagged?{kind:"storm",retryable:!1,reason:yFe(e.stormDetail)}:e.priorConsecutiveIsolatedRejections<pFe?{kind:"isolated_retry",retryable:!0,reason:fFe(e.rejectionDetail)}:{kind:"isolated_terminal",retryable:!1,reason:_Fe(e.rejectionDetail)}}function wFe(e){return vFe.test(e)||xFe.test(e)}function SFe(e){let n=b(e.kind)??b(e.type)??b(O(e.error)?.kind)??b(O(e.error)?.type),t=typeof n=="string"&&/(tool.*fatal|fatal.*tool|response[._]failed|tool_failure)/i.test(n),r=qv(e),o=r!==void 0&&wFe(r);if(!(!t&&!o))return r??""}function kFe(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 dt(e,n){return{type:"log",event:e,fields:n}}var h$e,Ov,Cg,g$e,Da,iY,y$e,_$e,b$e,aY,sY,x$e,dY,pY,Dv,P$e,A$e,I$e,j$e,bY,Y2,L$e,vY,aFe,sFe,dFe,pFe,X2,mFe,vFe,xFe,RT=B(()=>{"use strict";Ev();os();Zt();hg();Pv();V2();h$e=new Set(["completed","failed","interrupted"]);Ov="pipeline/turnMappingReady",Cg="pipeline/turnMappingFailed",g$e=512,Da=2,iY="Codex completed without producing a response.",y$e="linzumi_agent_reply",_$e="The agent ended its turn after narrating an intent without posting a reply or taking any action.",b$e="agent narrated intent but posted no reply and took no action",aY=new Set(["commandOutput","fileChange","terminalInput","agentStatus","agentTaskUpdate"]);sY=3,x$e="Stopped after repeated empty responses in a row",dY=64;pY="Codex emitted unsupported tool call";Dv="pipeline/stopInterrupted",P$e=new Map([["turn/failed","failed"],["turn/aborted","interrupted"],["turn/canceled","interrupted"],["turn/cancelled","interrupted"],[Dv,"interrupted"]]),A$e=new Set(["turn/started","turn/completed","turn/failed","turn/aborted","turn/canceled","turn/cancelled",Dv,"error","turn/plan/updated","item/agentMessage/delta","item/reasoning/textDelta","item/commandExecution/outputDelta","command/exec/outputDelta","item/fileChange/outputDelta","item/fileChange/patchUpdated","item/mcpToolCall/progress","item/commandExecution/terminalInteraction","item/started","item/completed","response_item","thread/compacted"]),I$e=new Set(["turn/plan/updated","item/agentMessage/delta","item/reasoning/textDelta","item/commandExecution/outputDelta","command/exec/outputDelta","item/fileChange/outputDelta","item/fileChange/patchUpdated","item/mcpToolCall/progress","item/commandExecution/terminalInteraction","item/started","item/completed","response_item"]);j$e=/upstream model stream stalled/i,bY=/\(HTTP (\d{3})\)/,Y2=/\(HTTP 429\)|\bstatus:?\s+429\b|\b429\s+Too\s+Many\s+Requests\b|\bHTTP\s+429\b/i;L$e=" (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.)";vY=" (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,sFe=/\bmodel request was rejected\b|\bmodel_request_rejected\b/i;dFe=300;pFe=1,X2=/^provider_outage$/i,mFe=/rejecting requests|experiencing an outage|provider outage/i;vFe=/\bapply_patch\b[^]*\bincompatible\b|\bin-flight tool future\b[^]*\bfail/i,xFe=/\btools::router\b[^]*\bfatal\b|\bresponse\.failed\b/i});function PY(e){return e===void 0?[]:[...e.values()].map(n=>({...n}))}function AY(e){let n=hY(),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,a=new Map,s=new Map,d=new Map,u=new Set,c=e.bufferedTurnMaxAgeMs??CFe,l=e.bufferedTurnMaxEvents??TFe,f=e.bufferedTurnSweepIntervalMs??PFe,p=!1,h=!0,y,m=(I,P)=>{try{e.log(I,P)}catch{}},_=I=>{switch(I.type){case"enqueue":e.outbox.enqueue({kind:I.kind,data:I.data,...I.coalesceKey===void 0?{}:{coalesceKey:I.coalesceKey},resolution:I.resolution});return;case"requestSnapshot":e.requestSnapshot(I.turnId);return;case"turnTerminal":e.onTurnTerminal(I.turnId,I.outcome,I.reason,I.retryableEmptyTurn,I.autoResumeMidStreamStall,I.fate,I.freshSessionResumeMidStreamStall,I.routeOutageHold);return;case"log":m(I.event,I.fields);return}},w=()=>{for(let I of n.turns.keys())i.has(I)||i.set(I,o());for(let I of[...i.keys()])n.turns.has(I)||i.delete(I);for(let I of n.bufferedTurns.keys())a.has(I)||a.set(I,o());for(let I of[...a.keys()])n.bufferedTurns.has(I)||(a.delete(I),u.delete(I));for(let I of[...s.keys()])!n.turns.has(I)&&!n.bufferedTurns.has(I)&&s.delete(I);for(let I of[...d.keys()])!n.turns.has(I)&&!n.bufferedTurns.has(I)&&d.delete(I)},v=(I,P)=>{!n.turns.has(I)&&!n.bufferedTurns.has(I)||s.set(I,{atMs:o(),kind:P})},S=I=>{if(I.source!=="codex")return;let P=I.notification.method;if(P===Ov||P===Cg)return;let z=Rv(I.notification.params??{})??AT(n);z!==void 0&&v(z,P)},C=I=>{if(I.source!=="codex")return;let P=I.notification.method;if(P!=="item/started"&&P!=="item/completed"&&P!=="response_item")return;let z=I.notification.params??{},$=Rv(z)??AT(n);if($===void 0||!n.turns.has($)&&!n.bufferedTurns.has($))return;let J=xg(z);if(J===void 0||J==="")return;if(P!=="item/started"){d.get($)?.delete(J);return}let Q=b(O(z.item)?.type);if(Q===void 0||!AFe.has(Q))return;let K=d.get($);K===void 0&&(K=new Map,d.set($,K)),K.set(J,{kind:Q,startedAtMs:o()})},A=()=>{if(!h||n.phase!=="running")return!1;let I=o(),P=!1;for(let[z,$]of n.bufferedTurns){if(u.has(z))continue;let J=I-(a.get(z)??I),Q=J>c,K=$.length>l;!Q&&!K||(u.add(z),m("pipeline.loop.buffered_turn_overdue",{level:"error",thread_key:e.threadKey,turn_id:z,buffered_event_count:$.length,age_ms:J,max_age_ms:c,max_events:l}),r.push({source:"codex",notification:{method:Cg,params:{turnId:z,reason:K?`turn source mapping never arrived (${$.length} buffered events exceeded the ${l} cap)`:`turn source mapping never arrived within ${c}ms`}}}),P=!0)}return P},T=()=>{if(!p){p=!0;try{for(;r.length>0;){let I=r.shift();if(I===void 0)continue;let P;try{P=gY(n,I,t)}catch(z){m("pipeline.loop.event_processing_failed",{thread_key:e.threadKey,source:I.source,message:z instanceof Error?z.message:String(z)});continue}w(),S(I),C(I);for(let z of P)try{_(z)}catch($){m("pipeline.loop.effect_failed",{thread_key:e.threadKey,effect:z.type,message:$ instanceof Error?$.message:String($)})}A()}}finally{p=!1}}},M=f>0?setInterval(()=>{A()&&T()},f):void 0;return M?.unref?.(),{submit:I=>{try{if(!h){m("pipeline.loop.event_after_drain",{thread_key:e.threadKey,source:I.source});return}r.push(I),T()}catch(P){m("pipeline.loop.submit_failed",{thread_key:e.threadKey,message:P instanceof Error?P.message:String(P)})}},metrics:()=>({queueDepth:r.length,phase:n.phase,activeTurns:[...n.turns.values()].map(I=>({turnId:I.turnId,sourceSeq:I.sourceSeq,startedAtMs:i.get(I.turnId)??o(),lastActivityAtMs:s.get(I.turnId)?.atMs,lastActivityKind:s.get(I.turnId)?.kind,openItems:PY(d.get(I.turnId))})),bufferedTurns:[...n.bufferedTurns.entries()].map(([I,P])=>({turnId:I,bufferedEventCount:P.length,firstBufferedAtMs:a.get(I)??o(),lastActivityAtMs:s.get(I)?.atMs,lastActivityKind:s.get(I)?.kind,openItems:PY(d.get(I))}))}),noteTurnActivity:(I,P)=>{try{v(I,P)}catch(z){m("pipeline.loop.note_activity_failed",{thread_key:e.threadKey,message:z instanceof Error?z.message:String(z)})}},drainAndClose:I=>(y===void 0&&(y=(async()=>{h=!1,M!==void 0&&clearInterval(M),await Promise.resolve(),T();try{await e.outbox.flush(I)}catch(P){m("pipeline.loop.drain_flush_failed",{thread_key:e.threadKey,message:P instanceof Error?P.message:String(P)})}})()),y)}}var CFe,TFe,PFe,AFe,IY=B(()=>{"use strict";Zt();V2();RT();CFe=10*6e4,TFe=1e4,PFe=3e4,AFe=new Set(["commandExecution","terminalInput","mcpToolCall","dynamicToolCall","collabAgentToolCall"])});async function RFe(e,n,t){let r=c=>(t("adt.terminal_repair_refused",{thread_id:n.threadId,source_seq:n.sourceSeq,session_id:n.sessionId,reason:c}),{kind:"refused",message:c});await e.journalSettled();let o=e.terminalPublicationDebt();if(typeof o=="object"&&o.kind==="unavailable")return r(o.reason);let i=e.failedTerminalEntries().filter(c=>{let l=O(c.data.terminal_frame);return c.data.terminal_repair===void 0&&ie(c.data.seq)===n.sourceSeq&&ie(l?.session_id)===n.sessionId&&ie(l?.lease_epoch)===n.originalLeaseEpoch}),a=i[0];if(i.length!==1||a===void 0)return r("terminal failure evidence is missing or ambiguous");let s=JSON.stringify(a.data),d=e.recallDurableFact(Kf(a.entrySeq));if(d!==void 0&&Eh(a.entrySeq,s,JSON.stringify(d)))return t("adt.terminal_repair_already_resolved",{thread_id:n.threadId,source_seq:n.sourceSeq,failed_entry_seq:a.entrySeq}),{kind:"ready",id:Kf(a.entrySeq),serializedData:s};let u=await r7(n.threadId,n.sourceSeq,n.sessionId,n.originalLeaseEpoch,a.entrySeq,s,JSON.stringify(n.binding),n.authoritativeTerminal,{readPrepared:c=>{let l=e.recallDurableFact(c);return l===void 0?void 0:typeof l=="string"?l:"invalid prepared fact"},writePrepared:async(c,l)=>(e.rememberDurableFact(c,l),await e.journalSettled(),e.metrics().totalJournalWriteFailures===0?"IoOk":{kind:"IoError",message:"terminal repair preparation was not durable"}),authorize:c=>{let l=O(JSON.parse(c));return l!==void 0&&n.authorize(l)?"IoOk":{kind:"IoError",message:"terminal repair publication authority refused"}},enqueue:async c=>{let l=O(JSON.parse(c));if(l===void 0)return{kind:"IoError",message:"terminal repair entry is not an object"};let f=O(l.terminal_repair)?.id,p=e.pendingTerminalEntries().filter(h=>O(h.data.terminal_repair)?.id===f);return p.length>0?(t("adt.terminal_repair_pending_retained",{thread_id:n.threadId,source_seq:n.sourceSeq,count:p.length}),p.length===1&&JSON.stringify(p[0]?.data)===c?"IoOk":{kind:"IoError",message:"pending correction identity differs"}):(e.enqueue({kind:"adt.terminal_attempt",data:l,resolution:"must_reach_consensus"}),await e.journalSettled(),e.metrics().totalJournalWriteFailures===0?"IoOk":{kind:"IoError",message:"terminal correction enqueue was not durable"})}});return u.kind==="refused"?r(u.message):u}function Fv(e){let n=LFe(e),t=KFe(),r=zX({threadKey:e.threadKey,...e.journalGeneration===void 0?{}:{journalGeneration:e.journalGeneration},push:(_,w,v,S,C)=>{if(C===void 0)throw new Error("Session pipeline push requires outbox metadata");let A=DFe(_,w,C),T=()=>e.push(_,A,v,S),M=ET(C),I=qFe(C);return e.commanderPushAdmission===void 0?T():e.commanderPushAdmission.run({threadKey:e.threadKey,pushClass:M,owner:t,...I===void 0?{}:{streamIdentity:I}},T,M==="replaceable_live"?()=>null:void 0)},...e.commanderPushAdmission===void 0?{}:{isPriorityEntry:_=>ET(_)!=="replaceable_live",supersedesQueuedEntry:$Fe},builders:n,...e.persistDir===void 0?{}:{persistDir:e.persistDir},...e.outboxRetryDelaysMs===void 0?{}:{retryDelaysMs:[...e.outboxRetryDelaysMs]},maxInFlightPushes:e.outboxMaxInFlightPushes??(e.commanderPushAdmission===void 0?MFe:1),...e.journalRecoveryMaxAgeMs===void 0?{}:{journalRecoveryMaxAgeMs:e.journalRecoveryMaxAgeMs},...e.outboxRecoveryMode===void 0?{}:{recoveryMode:e.outboxRecoveryMode},isRetryBudgetExempt:a$,shouldPreserveForRestart:EFe,onPermanentFailure:(_,w)=>{if(e.log("pipeline.outbox_entry_failed",{thread_key:e.threadKey,entry_seq:_.entrySeq,kind:_.kind,attempts:_.attempts,item_key:b(_.data.item_key)??null,turn_id:b(_.data.turn_id)??null,message:w.message}),_.kind===r$){let v=b(_.data.event),S=O(_.data.payload);if(v===void 0||S===void 0){e.log("pipeline.durable_session_push_failure_invalid_data",{thread_key:e.threadKey,entry_seq:_.entrySeq,event:_.data.event??null});return}e.onDurablePushPermanentFailure?.(v,S,w)}},log:e.log}),o,i=_=>{let w=_.data;if(_.kind===Qt.messageState){let v=b(w.turn_id);v!==void 0&&e.isRecoveredTurn?.(v)===!0&&(w={...w,suppress_terminal_for_recovered_turn:!0});let S=b(w.status);if(S==="failed"||S==="recovering"){let C=e.runtimeMetadataForSourceSeq?.(ie(w.seq)),A=b(C?.model),T=b(C?.model_provider);w={...w,...b(w.model)===void 0&&A!==void 0?{model:A}:{},...b(w.provider)===void 0&&T!==void 0?{provider:T}:{}}}}if(NFe(_.kind)){let v=ie(w.source_seq),S=O(w.local_runner_runtime_metadata)??e.runtimeMetadataForSourceSeq?.(v);S!==void 0&&(w={...w,local_runner_runtime_metadata:S});let C=v===void 0?void 0:e.executionLegRecoveryAttemptIdForSourceSeq?.(v);C!==void 0&&(w={...w,executionLegRecoveryAttemptId:C})}return w!==_.data?r.enqueue({..._,data:w}):r.enqueue(_)},a=e.adtIntervalNowMs??(()=>Date.now()),s=e.scheduleAdtInterval??((_,w)=>{let v=setTimeout(w,_);return v.unref?.(),()=>clearTimeout(v)}),d=new Map,u=!1,c=_=>{let w=CX(_.emitter,a());w!==null&&r.enqueue({kind:Tv,data:_g(w),resolution:"must_ack"})},l=_=>{if(d.get(_.sourceSeq)?.(),d.delete(_.sourceSeq),u||_.done||_.emitter.fenced||_.emitter.terminalEmitted||_.emitter.pendingDeltas===0)return;let w=a(),v=Math.max(0,_.emitter.lastFrameAtMs+_.binding.checkpointConfig.thresholds.maxIntervalMs-w),S=s(v,()=>{if(d.delete(_.sourceSeq),u)return;let C=e.adtAuthorityForSourceSeq?.(_.sourceSeq);if(C===void 0||C.sourceSeq!==_.sourceSeq||C.binding.sessionId!==_.binding.sessionId||C.binding.leaseEpoch!==_.binding.leaseEpoch){e.log("adt.interval_authority_stale",{thread_key:e.threadKey,source_seq:_.sourceSeq,scheduled_session_id:_.binding.sessionId,scheduled_lease_epoch:_.binding.leaseEpoch,current_session_id:C?.binding.sessionId??null,current_lease_epoch:C?.binding.leaseEpoch??null});return}c(C),l(C)});d.set(_.sourceSeq,S)},f=()=>{u=!0;for(let _ of d.values())_();d.clear()},p={...r,enqueue:_=>{let w=_.kind===Qt.messageState?ie(_.data.seq):ie(_.data.source_seq),v=w===void 0?void 0:e.adtAuthorityForSourceSeq?.(w);if(v===void 0)return i(_);let S=PX(v,_.kind,_.data,a(),Qt),C=(T=S)=>{for(let M of T)r.enqueue({kind:Tv,data:_g(M),resolution:"must_ack"})};if(_.kind===Qt.messageState){let T=S.find(M=>M.frameKind==="terminal");return C(S.filter(M=>M.frameKind!=="terminal")),l(v),i(T!==void 0?{kind:mT,data:{..._.data,terminal_frame:_g(T)},resolution:_.resolution,..._.coalesceKey===void 0?{}:{coalesceKey:_.coalesceKey}}:_)}let A=i(_);return C(),l(v),A}},h=async _=>{let w=e.snapshotRetryDelaysMs??IFe;for(let v=0;;v+=1)try{let S=await e.resolveSnapshot(_);o.submit({source:"snapshot",turnId:_,snapshot:{items:[...S.items]}});return}catch(S){let C=S instanceof Error?S.message:String(S),A=w[v];if(e.log("pipeline.snapshot_resolution_failed",{thread_key:e.threadKey,turn_id:_,attempt:v+1,retry_in_ms:A??null,message:C}),A===void 0){o.submit({source:"codex",notification:{method:"turn/failed",params:{turnId:_,reason:`completion snapshot resolution failed: ${C}`}}});return}await JFe(A)}};o=AY({threadKey:e.threadKey,outbox:p,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:_=>{h(_).catch(w=>{e.log("pipeline.snapshot_request_failed",{thread_key:e.threadKey,turn_id:_,message:w instanceof Error?w.message:String(w)})})},instanceId:e.instanceId,log:e.log,linzumiAgentSession:e.linzumiAgentSession===!0});let y=GX({threadKey:e.threadKey,outboxMetrics:()=>r.metrics(),loopMetrics:()=>o.metrics(),log:e.log,intervalMs:e.statsIntervalMs,turnStalledThresholdMs:e.turnStalledThresholdMs,turnWaitStates:e.turnWaitStates}),m;return{submitNotification:(_,w)=>{o.submit({source:"codex",notification:{method:_,params:w}})},notifyTurnMappingReady:_=>{o.submit({source:"codex",notification:{method:Ov,params:{turnId:_}}})},notifyTurnMappingFailed:(_,w)=>{o.submit({source:"codex",notification:{method:Cg,params:{turnId:_,reason:w}}})},noteTurnActivity:(_,w)=>{o.noteTurnActivity(_,w)},submitLifecycle:(_,w)=>{o.submit({source:"lifecycle",kind:_,reason:w})},pause:()=>{r.pause()},resume:()=>{r.resume()},rebindThreadKey:_=>{r.rekeyJournal(_)},enqueueDurablePush:(_,w,v)=>r.enqueue({kind:r$,data:{event:_,payload:w},...v===void 0?{}:{coalesceKey:v},resolution:"must_ack"}),readDurableFact:_=>r.recallDurableFact(_),durableFactRecovery:()=>r.durableFactRecovery(),retainPendingTerminalForRepair:()=>r.retainPendingTerminalForRepair(),terminalPublicationDebt:()=>r.terminalPublicationDebt(),settleJournalForRestart:()=>r.journalSettled(),restartWriteInProgress:()=>r.restartWriteInProgress(),flushForRestart:async()=>{let _=o.metrics();if(_.queueDepth!==0||_.activeTurns.length!==0||_.bufferedTurns.length!==0)throw e.log("commander_restart_publication_flush_refused",{threadKey:e.threadKey,reason:"restart_pipeline_not_quiescent"}),new Error("restart_pipeline_not_quiescent");await r.flush(),await r.journalSettled();let w=o.metrics();if(w.queueDepth!==0||w.activeTurns.length!==0||w.bufferedTurns.length!==0||r.metrics().depth!==0||r.terminalPublicationDebt()!=="clear")throw e.log("commander_restart_publication_flush_refused",{threadKey:e.threadKey,reason:"restart_publication_evidence_not_clear"}),new Error("restart_publication_evidence_not_clear")},failedTerminalEntries:()=>r.failedTerminalEntries(),repairTerminalDebt:async _=>{let w=await RFe(r,_,e.log);return w.kind==="ready"&&r.flush().then(async()=>{await r.journalSettled(),r.terminalPublicationDebt()==="clear"?e.onTerminalDebtResolved?.(_.threadId,_.sourceSeq,_.sessionId):e.log("adt.terminal_repair_still_pending",{thread_id:_.threadId,source_seq:_.sourceSeq})}).catch(v=>e.log("adt.terminal_repair_settlement_failed",{thread_id:_.threadId,reason:v instanceof Error?v.message:"unknown settlement failure"})),w},writeDurableFact:async(_,w)=>{let v=r.metrics().totalJournalWriteFailures;r.rememberDurableFact(_,w),await r.journalSettled();let S=r.metrics();if(e.persistDir!==void 0&&(S.totalJournalWriteFailures>v||S.journalDegraded))throw new Error(`Failed to persist durable session fact ${_} for ${e.threadKey}`)},flushOutbox:_=>r.flush(_),metrics:()=>r.metrics(),close:_=>(m===void 0&&(e.commanderPushAdmission?.cancelQueued(t),m=(async()=>{f(),y.stop(),o.submit({source:"lifecycle",kind:"shutdown",reason:"session closed"}),await o.drainAndClose(_),await r.close(_)})()),m)}}function o$(e){if(e.checkpoint_due===!0)return!0;let n=ie(e.stream_snapshot_index);return n===void 0?!1:n%OFe===0}function NY(e){switch(e.entryKind){case Qt.postStreamedRow:switch(t$(e.data)){case void 0:return"started";case"completed":return"completed";case"failed":return"failed";case"cancelled":return"cancelled"}case Qt.streamSnapshot:{let n=t$(e.data);return n===void 0?o$(e.data)?"checkpoint":"delta":n}case Qt.finalizeRow:case Qt.postCompletedRow:switch(t$(e.data)){case void 0:case"completed":return"completed";case"failed":return"failed";case"cancelled":return"cancelled"}case Qt.messageState:switch(b(e.data.status)){case"failed":return"failed";case"interrupted":return"cancelled";case"processed":return"completed";default:return}case Tv:switch(b(e.data.frame_kind)){case"delta":return"checkpoint";case"checkpoint":return"checkpoint";case"terminal":return"completed";default:return}case mT:return"completed";default:return}}function DFe(e,n,t){switch(e){case"session:stream_thread_message":{let r=NY(t);if(r===void 0)throw new Error("Stream pipeline push requires a lifecycle");return{...n,stream_lifecycle:r}}default:return n}}function ET(e){switch(NY(e)){case"delta":return"replaceable_live";case"completed":case"failed":case"cancelled":return"terminal";case"started":case"checkpoint":case void 0:return"durable"}}function RY(e){let n=bC(e);return n===void 0?{}:{traceparent:n}}function FFe(e){return{...b(e.turn_id)===void 0?{}:{turn_id:b(e.turn_id)},...b(e.item_key)===void 0?{}:{item_key:b(e.item_key)},...ie(e.delta_index)===void 0?{}:{delta_index:ie(e.delta_index)},...ie(e.stream_snapshot_index)===void 0?{}:{stream_snapshot_index:ie(e.stream_snapshot_index)}}}function jFe(e){return typeof e.body=="string"?e.body:""}function EY(e){return O(e.structured)??{}}function NFe(e){return e===Qt.postStreamedRow||e===Qt.streamSnapshot||e===Qt.finalizeRow||e===Qt.postCompletedRow}function LFe(e){let n={build:l=>{let f=e.wire();if(f.kandanThreadId===void 0||f.codexThreadId===void 0)return{skip:!0,reason:"session_thread_unbound"};let p=b(l.client_message_id);if(p===void 0)return{skip:!0,reason:"missing_client_message_id"};let h=b(l.turn_id),y=ie(l.source_seq),m=b(l.executionLegRecoveryAttemptId),_={...h===void 0?{}:{turn_id:h},stream_key:p},w=O(l.local_runner_runtime_metadata),v={..._,...w??{}},S=e.sandboxNetworkDenialSurfacing===!0?nQ(EY(l),w):EY(l);return{event:"session:stream_thread_message",payload:{workspace:f.workspaceSlug,channel:f.channelSlug,thread_id:f.kandanThreadId,stream_key:p,...f.leaseEpoch===void 0?{}:{lease_epoch:f.leaseEpoch},...m===void 0?{}:{executionLegRecoveryAttemptId:m},body:jFe(l),payload:{...e.runnerPayload("codex_output",f.codexThreadId,y,v),...f.rootSeq===void 0?{}:{reply_to_seq:f.rootSeq},...m===void 0?{}:{executionLegRecoveryAttemptId:m},...y===void 0?{}:{source_message_seq:y},..._,structured:{...S,stream_key:p}},client_message_id:p,...FFe(l),...RY(f.kandanThreadId)}}},replyPolicy:{kind:"transport_ack"},coalesce:(l,f)=>o$(l)||o$(f)?{...f,checkpoint_due:!0}:f},t={build:l=>{let f=e.wire();if(f.kandanThreadId===void 0)return{skip:!0,reason:"session_thread_unbound"};let p=ie(l.seq),h=b(l.status);if(p===void 0||h===void 0)return{skip:!0,reason:"malformed_message_state_entry"};let y=b(l.turn_id);return l.suppress_terminal_for_recovered_turn===!0||y!==void 0&&e.isRecoveredTurn?.(y)===!0?{skip:!0,reason:"terminal_for_recovered_turn"}:{event:"message_state",payload:{workspace:f.workspaceSlug,channel:f.channelSlug,thread_id:f.kandanThreadId,instance_id:e.instanceId,...f.codexThreadId===void 0?{}:{codex_thread_id:f.codexThreadId},seq:p,status:h,...b(l.reason)===void 0?{}:{reason:b(l.reason)},...l.retryable===!0?{retryable:!0}:{},...as(l.fate)?{fate:l.fate}:{},...O(l.ladder)===void 0?{}:{ladder:O(l.ladder)},...l.failure_class==="edge_blocked"||l.failure_class==="claude_oauth_expired"?{failure_class:l.failure_class}:{},...b(l.upstream_error)===void 0?{}:{upstream_error:b(l.upstream_error)},...b(l.model)===void 0?{}:{model:b(l.model)},...b(l.provider)===void 0?{}:{provider:b(l.provider)},...b(l.turn_id)===void 0?{}:{turn_id:b(l.turn_id)},...f.leaseEpoch===void 0?{}:{lease_epoch:f.leaseEpoch},...RY(f.kandanThreadId)}}},replyPolicy:{kind:"adjudicate",adjudicateReply:(l,f)=>{if(l.approval_failure_consensus!==!0)return{kind:"accept"};let p=e.wire().kandanThreadId,h=ie(l.seq);if(p===void 0||h===void 0)return{kind:"retry",failure:new Error("approval failure consensus entry omitted its expected identity")};let y=(()=>{switch(e.messageStateReplyShape.kind){case"inner_response":return Zs(f);case"full_reply":return Zs(f,"full")}})();switch(y.kind){case"applied":return{kind:"accept"};case"terminal":return y.threadId===p&&y.sourceSeq===h?{kind:"accept"}:{kind:"retry",failure:new Error(`terminal message_state consensus identity mismatch: expected ${p}:${h}, received ${y.threadId}:${y.sourceSeq}`)};case"invalid":return{kind:"retry",failure:new Error(y.error)};case"unconfirmed":return{kind:"retry",failure:new Error("approval failure message_state consensus was unconfirmed")}}}}},r={build:l=>{let f=e.wire(),p=b(l.turn_id),h=b(l.reason),y=ie(l.buffered_event_count),m=b(l.first_event),_=b(l.last_event);if(f.kandanThreadId===void 0||f.codexThreadId===void 0)return e.log?.("pipeline.unmapped_turn_failure_build_failed",{level:"error",turn_id:p??null,missing_kandan_thread_id:f.kandanThreadId===void 0,missing_codex_thread_id:f.codexThreadId===void 0}),{skip:!0,reason:"session_thread_unbound"};if(p===void 0||h===void 0||y===void 0||y<0||m===void 0||_===void 0)return e.log?.("pipeline.unmapped_turn_failure_build_failed",{level:"error",turn_id:p??null,missing_reason:h===void 0,buffered_event_count:y??null,first_event:m??null,last_event:_??null}),{skip:!0,reason:"malformed_unmapped_turn_failure"};let w=`unmapped-turn-failure:${p}`;return{event:"session:post_thread_message",payload:{workspace:f.workspaceSlug,channel:f.channelSlug,thread_id:f.kandanThreadId,body:h,payload:{...e.runnerPayload("unmapped_turn_failure",f.codexThreadId,void 0,{turn_id:p}),structured:{kind:"agent_status_event",item_id:w,transcript_unit_id:`agent_status_event:${w}`,stream_state:"completed",event_kind:"status",title:"Response delivery failed",body:h,severity:"error",agent_provider:"codex",occurred_at_ms:null,raw_provider_metadata:{turn_id:p,buffered_event_count:y,first_event:m,last_event:_}}},client_message_id:w,turn_id:p}}},replyPolicy:{kind:"transport_ack"}},o=l=>{let f=O(l);return O(f?.adt)??O(O(f?.terminal_attempt)?.frame)??O(O(O(f?.response)?.terminal_attempt)?.frame)},i={build:l=>{let f=ie(l.session_id),p=ie(l.lease_epoch);return f!==void 0&&p!==void 0&&gT(f,p)?{skip:!0,reason:"adt_generation_fenced"}:{event:xX,payload:{session_id:l.session_id??null,lease_epoch:l.lease_epoch??null,frame_index:l.frame_index??null,frame_kind:l.frame_kind??null,body:l.body??null,byte_len:l.byte_len??null,...l.assistant_phase===void 0?{}:{assistant_phase:l.assistant_phase},...l.source_stream_key===void 0?{}:{source_stream_key:l.source_stream_key}}}},replyPolicy:{kind:"transport_ack"},onReply:(l,f)=>{let p=O(l.terminal_frame)??l,h=o(f);if(h===void 0)return;let y=ie(p.session_id),m=ie(p.lease_epoch);if(h.accepted===!1){let _=fT(h.reason),w=e.wire().kandanThreadId;if(e.log?.("adt.append_rejected",{session_id:y??null,presented_epoch:ie(p.lease_epoch)??null,frame_index:ie(p.frame_index)??null,reason:_}),y===void 0||m===void 0||w===void 0){let v=[...y===void 0?["session_id"]:[],...m===void 0?["lease_epoch"]:[],...w===void 0?["thread_id"]:[]].join(",");e.log?.("adt.authority_release_identity_missing",{thread_id:w??null,session_id:y??null,lease_epoch:m??null,missing_identity:v})}else{hT(y,m);let v=e.fenceAdtAuthority?.(y,m);v?.kind==="skipped"&&e.log?.("adt.authority_release_skipped",{thread_id:e.wire().kandanThreadId??null,source_seq:v.sourceSeq??null,session_id:y,lease_epoch:m,release_reason:v.reason}),e.log?.("adt.generation_fenced",{session_id:y,reason:_})}return}h.duplicate===!0&&e.log?.("adt.frame_resend_accepted",{session_id:y??null,frame_index:ie(p.frame_index)??null})}},a="terminal_attempt_frame_correction",s=l=>{let f=O(l.terminal_frame),p=ie(f?.session_id),h=ie(f?.lease_epoch);if(p!==void 0)return h===void 0?void 0:[p,h]},d=(l,f)=>{let p=s(l),h=O(f.recall(a));if(p!==void 0){let[y,m]=p;return ie(h?.session_id)===y&&ie(h?.lease_epoch)===m?ie(h?.next_frame_index):void 0}},u={build:(l,f)=>{let p=t.build(l,f);if("skip"in p)return p;let h=O(l.terminal_frame);if(h===void 0)return{skip:!0,reason:"terminal_attempt_frame_missing"};let y=l.terminal_repair===void 0?d(l,f):void 0;return{event:cT,payload:{...p.payload,...l.terminal_repair===void 0?{}:{terminal_repair:l.terminal_repair},terminal_frame:{session_id:h.session_id??null,lease_epoch:h.lease_epoch??null,frame_index:y??h.frame_index??null,frame_kind:h.frame_kind??null,body:h.body??null,byte_len:h.byte_len??null,...h.assistant_phase===void 0?{}:{assistant_phase:h.assistant_phase},...h.source_stream_key===void 0?{}:{source_stream_key:h.source_stream_key}}}}},replyPolicy:{kind:"adjudicate",adjudicateReply:(l,f,p)=>{if(l.terminal_repair!==void 0){let m=e.wire().kandanThreadId,_=ie(l.seq);if(m===void 0||_===void 0)return{kind:"retry",failure:new Error("terminal repair identity unavailable")};let w=e.messageStateReplyShape.kind==="inner_response"?{status:"ok",response:f}:f,v=pg(m,_,JSON.stringify(w)),S=PD(m,JSON.stringify(l));return v==="accepted"&&S.kind==="ready"?{kind:"accept"}:{kind:"retry",failure:new Error("terminal repair requires accepted exact consensus")}}let h=o(f);switch(h?.accepted===!1?fT(h.reason):void 0){case"frame_index_reuse":{let m=s(l),_=ie(h?.next_frame_index),w=d(l,p)??ie(O(l.terminal_frame)?.frame_index);if(m===void 0||_===void 0||w===void 0||_<=w)return{kind:"retry",failure:new Error("fused terminal frame correction index was unavailable")};let[v,S]=m;return p.remember(a,{session_id:v,lease_epoch:S,next_frame_index:_}),{kind:"retry",failure:new Error("fused terminal frame index was corrected by the server")}}case"unknown":return{kind:"retry",failure:new Error("retryable fused terminal frame rejection")};case"stale_epoch":case"post_settle":case"post_terminal":case void 0:{let m=e.wire().kandanThreadId,_=ie(l.seq);if(m===void 0||_===void 0||s(l)===void 0)return{kind:"retry",failure:new Error("fused terminal expected identity missing")};let w=e.messageStateReplyShape.kind==="inner_response"?{status:"ok",response:f}:f,v=pg(m,_,JSON.stringify(w));return typeof v=="object"?{kind:"retry",failure:new Error(v.message)}:{kind:"accept"}}}}},onReply:(l,f,p)=>{if(l.terminal_repair!==void 0){let m=e.wire().kandanThreadId,_=PD(m??"",JSON.stringify(l));if(_.kind!=="ready"){let w={thread_id:m??null,source_seq:l.seq??null,reason:_.message};e.log?e.log("adt.terminal_repair_receipt_refused",w):console.warn("adt.terminal_repair_receipt_refused",w);return}p.remember(_.id,JSON.parse(_.serializedData))}let h=o(f);switch(h?.accepted===!1?fT(h.reason):void 0){case"frame_index_reuse":case"unknown":return;case"stale_epoch":case"post_settle":case"post_terminal":case void 0:{let m=e.wire().kandanThreadId,_=ie(l.seq),w=s(l),v=e.messageStateReplyShape.kind==="inner_response"?{status:"ok",response:f}:f,S=m===void 0||_===void 0?{kind:"retry",message:"fused terminal expected identity missing"}:pg(m,_,JSON.stringify(v));if(w===void 0||_===void 0||typeof S=="object"){let C={source_seq:_??null,message:typeof S=="object"?S.message:"session identity missing"};e.log!==void 0?e.log("adt.terminal_retirement_refused",C):console.warn("adt.terminal_retirement_refused",C);return}i.onReply?.(l,f,p),e.onAdtAuthorityRetired?.(w[0],_);return}}}},c={build:l=>{let f=b(l.event),p=O(l.payload);return f===void 0||p===void 0?{skip:!0,reason:"invalid_durable_session_push"}:{event:f,payload:p}},replyPolicy:{kind:"transport_ack"}};return{[Qt.postStreamedRow]:n,[Qt.streamSnapshot]:n,[Qt.finalizeRow]:n,[Qt.postCompletedRow]:n,[Qt.messageState]:t,[Qt.unmappedTurnFailure]:r,[Tv]:i,[mT]:u,[r$]:c}}function LY(e,n){if("error"in e)return[];let t=O(O(e.result)?.thread),o=(Xe(t?.turns)??[]).filter(se).find(i=>i.id===n);return(Xe(o?.items)??[]).filter(se)}function i$(e){if(!e.some(t=>zFe.has(b(t.type)??"")))return[...e];let n=new Set;return e.forEach(t=>{let r=MT.get(b(t.type)??"");if(r===void 0)return;let o=b(t.call_id);if(o===void 0)return;let i=e.findIndex((a,s)=>!n.has(s)&&b(a.type)===r&&b(a.call_id)===o);i>=0&&n.add(i)}),e.flatMap((t,r)=>{let o=b(t.type)??"",i=MT.get(o);if(i!==void 0){let a=b(t.call_id),s=a===void 0?void 0:e.find(d=>b(d.type)===i&&b(d.call_id)===a);return t2(s===void 0?[t]:[t,s]).flatMap(d=>{let u=MY(d);return u===void 0?[]:[u]})}return o==="function_call_output"||o==="custom_tool_call_output"?n.has(r)?[]:t2([t]).flatMap(a=>{let s=MY(a);return s===void 0?[]:[s]}):[t]})}function MY(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(b(n.kind)){case"codex_command_execution":{let i=GFe(o);return{type:"commandExecution",...r,...i===void 0?{}:{codex_protocol_failure_reason:i},command:b(n.command)??"command",...b(n.tool_name)===void 0?{}:{toolName:b(n.tool_name)},cwd:b(n.cwd)??"",status:b(n.status)??"",...b(n.process_id)===void 0||b(n.process_id)===""?{}:{processId:b(n.process_id)},aggregatedOutput:o}}case"codex_file_change":return{type:"fileChange",...r,status:b(n.status)??"",patchText:b(n.patch_text)??e.body,changes:Xe(n.changes)??[]};default:return}}function GFe(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 zY(e,n){if(n.length===0)return[...e];let t=OY(e),r=OY(n),o=new Set,i=r.map(d=>{let u=d.exactKey===void 0?-1:t.findIndex((l,f)=>!o.has(f)&&l.exactKey===d.exactKey);if(u>=0)return o.add(u),{kind:"read",readIndex:u,sourceItemId:void 0};let c=d.semanticKey===void 0?-1:t.findIndex((l,f)=>!o.has(f)&&l.semanticKey===d.semanticKey);if(c>=0){o.add(c);let l=b(d.raw.type),f=l==="agentMessage"||l==="message"&&d.raw.role==="assistant"?b(d.raw.id):void 0;return{kind:"read",readIndex:c,sourceItemId:f}}return{kind:"session",raw:d.raw}}),a=[],s=0;for(let d of i)switch(d.kind){case"read":{for(;s<d.readIndex;){if(!o.has(s)){let c=t[s];c!==void 0&&a.push(c.raw)}s+=1}let u=t[d.readIndex];u!==void 0&&a.push(d.sourceItemId===void 0?u.raw:{...u.raw,id:d.sourceItemId}),s=Math.max(s,d.readIndex+1);break}case"session":a.push(d.raw);break}for(;s<t.length;){if(!o.has(s)){let d=t[s];d!==void 0&&a.push(d.raw)}s+=1}return a}function OY(e){return e.map((n,t)=>{let r=og(n,t).find(o=>o.body.trim()!=="");return r===void 0?{raw:n,exactKey:void 0,semanticKey:void 0}:{raw:n,exactKey:UFe(r),semanticKey:BFe(r)}})}function UFe(e){return`${b(e.structured.kind)??""}:${e.itemKey}`}function BFe(e){let n=b(e.structured.kind)??"";switch(n){case"codex_assistant_message":return JSON.stringify([n,e.body,b(e.structured.phase)??""]);case"codex_command_execution":return JSON.stringify([n,b(e.structured.command)??"",b(e.structured.cwd)??"",b(e.structured.output)??e.body]);case"codex_file_change":return JSON.stringify([n,b(e.structured.patch_text)??e.body]);case"codex_reasoning":return JSON.stringify([n,b(e.structured.content)??e.body]);case"codex_terminal_input":return JSON.stringify([n,b(e.structured.input_text)??e.body]);default:return JSON.stringify([n,e.body])}}function OT(e){return sX(e)}function a$(e){return dX(e)}function JFe(e){return new Promise(n=>{setTimeout(n,e)})}function UY(e=process.env){let n=e.LINZUMI_COMMANDER_PUSH_MAX_INFLIGHT?.trim();switch(n){case void 0:case"":return WFe;default:{let t=Number(n);switch(Number.isSafeInteger(t)&&t>=2){case!0:return t;case!1:throw new Error("LINZUMI_COMMANDER_PUSH_MAX_INFLIGHT must be an integer of at least 2")}}}}function BY(e=process.env){let n=e[DY]?.trim();switch(n){case void 0:case"":return GY;default:{let t=Number(n);switch(Number.isSafeInteger(t)&&t>0){case!0:return t;case!1:throw new Error(`${DY} must be a positive integer`)}}}}var IFe,r$,$v,EFe,MFe,OFe,t$,qFe,$Fe,MT,zFe,KFe,WFe,GY,DY,VFe,qY,HFe,$Y,FY,ZFe,QFe,jY,JY,DT=B(()=>{"use strict";os();dc();S2();Db();Zt();hg();Sq();Sv();qt();Pv();Iv();UX();IY();RT();IFe=[1e3,5e3];r$="pipeline.durable_session_push",$v=class extends Error{constructor(){super("Commander push admission owner closed before admission"),this.name="CommanderPushAdmissionOwnerClosedError"}},EFe=e=>e instanceof $v,MFe=16;OFe=32,t$=e=>{switch(b(O(e.structured)?.stream_state)){case"completed":return"completed";case"failed":return"failed";case"removed":case"interrupted":return"cancelled";default:return}};qFe=e=>{let n=b(e.data.item_key),t=b(e.data.turn_id);return n===void 0?e.entryKind===Qt.messageState?t===void 0?void 0:{kind:"turn",turnId:t}:void 0:{kind:"item",itemKey:n,...t===void 0?{}:{turnId:t}}},$Fe=(e,n)=>{switch(ET(e)==="terminal"&&ET(n)==="replaceable_live"){case!0:break;case!1:return!1}let t=b(e.data.item_key),r=b(n.data.item_key);switch(t){case void 0:{if(e.entryKind!==Qt.messageState)return!1;let o=b(e.data.turn_id),i=b(n.data.turn_id);return o!==void 0&&o===i}default:switch(t===r){case!1:return!1;case!0:{let o=b(e.data.turn_id),i=b(n.data.turn_id);return o===void 0?i===void 0:o===i}}}};MT=new Map([["function_call","function_call_output"],["custom_tool_call","custom_tool_call_output"]]),zFe=new Set([...MT.keys(),...MT.values()]);KFe=()=>({}),WFe=16,GY=2e3,DY="LINZUMI_COMMANDER_PUSH_PRESSURE_BUDGET_MS";VFe=8,qY=()=>({pendingByThread:new Map,activeThreads:[]}),HFe=e=>{switch(e){case"replaceable_live":return"replaceable_live";case"durable":case"terminal":case"control":return"priority"}},$Y=(e,n,t)=>{let r=e.pendingByThread.get(n);if(r===void 0){e.pendingByThread.set(n,[t]),e.activeThreads.push(n);return}else r.push(t)},FY=e=>{let n=e.activeThreads.shift();switch(n){case void 0:return;default:{let t=e.pendingByThread.get(n);switch(t){case void 0:throw new Error("Commander push admission lane lost an active thread");default:{let r=t.shift();if(r===void 0)throw new Error("Commander push admission thread queue was empty");return t.length===0?e.pendingByThread.delete(n):e.activeThreads.push(n),r}}}}},ZFe=(e,n)=>{switch(n?.kind){case"item":switch(e?.kind){case"turn":case void 0:return!1;case"item":switch(e.itemKey===n.itemKey){case!1:return!1;case!0:return e.turnId===void 0?n.turnId===void 0:e.turnId===n.turnId}}case"turn":switch(e?.kind){case"item":case"turn":return e.turnId===n.turnId;case void 0:return!1}case void 0:return!1}},QFe=(e,n,t)=>{let r=e.pendingByThread.get(n);switch(r){case void 0:return;default:{let o=r.filter(i=>{switch(i.supersede){case void 0:return!0;default:switch(ZFe(i.streamIdentity,t)){case!1:return!0;case!0:return i.supersede(),!1}}});if(o.length===0){e.pendingByThread.delete(n);let i=e.activeThreads.indexOf(n);i===-1||e.activeThreads.splice(i,1);return}else e.pendingByThread.set(n,o)}}},jY=(e,n)=>{for(let[t,r]of e.pendingByThread){let o=r.filter(i=>{switch(i.owner===n){case!1:return!0;case!0:return i.reject(new $v),!1}});o.length===0?(e.pendingByThread.delete(t),e.activeThreads.splice(0,e.activeThreads.length,...e.activeThreads.filter(i=>i!==t))):e.pendingByThread.set(t,o)}},JY=e=>{switch(Number.isSafeInteger(e.maxInFlight)&&e.maxInFlight>0){case!1:throw new Error("Commander push admission maxInFlight must be a positive integer");case!0:break}let n=qY(),t=qY(),r=new WeakSet,o=e.now??(()=>performance.now()),i=e.maxLivePressureAgeMs??GY;switch(Number.isSafeInteger(i)&&i>0){case!1:throw new Error("Commander push admission maxLivePressureAgeMs must be a positive integer");case!0:break}let a=e.schedulePressureCheck??((N,W)=>{let ee=setTimeout(W,N);return ee.unref?.(),()=>clearTimeout(ee)}),s=e.maxInFlight===1?1:e.maxInFlight-1,d=0,u=0,c=!1,l=0,f=new Set,p,h,y=0,m=e.onPressureShed??(N=>{console.warn("commander_push.pressure_shed",N)}),_=e.onPressureShedFallback??(N=>{console.warn("commander_push.pressure_shed_fallback",N)}),w=N=>N.replace(/[^\x20-\x7e]/g,"?").slice(0,128),v=(N,W,ee,ne)=>{y+=1;let ye={event:"commander_push.pressure_shed",branch:N,shedCount:y,ageMs:W,budgetMs:i,threadKey:w(ee)};switch(ne?.kind){case"item":return{...ye,streamKind:"item",itemKey:w(ne.itemKey),...ne.turnId===void 0?{}:{turnId:w(ne.turnId)}};case"turn":return{...ye,streamKind:"turn",turnId:w(ne.turnId)};case void 0:return{...ye,streamKind:"none"}}},S=(N,W,ee,ne,ye)=>{let L=ye(),ce=v(N,W,ee,ne);try{m(ce)}catch{try{_({...ce,event:"commander_push.pressure_shed_fallback"})}catch{}}return L},C=N=>{let W=0;for(let ee of f)W=Math.max(W,N-ee.startedAtMs);return W},A=N=>{let W=N-i;for(let ee of f)if(ee.startedAtMs<=W)return!0;return!1},T=()=>{let N=o(),W=N-i,ee=A(N),ne=[];for(let ye of t.activeThreads){let L=t.pendingByThread.get(ye);if(L!==void 0){let ce=L.filter(pe=>{let re=ee?"ack_pressure":pe.enqueuedAtMs<=W?"queue_age":void 0;return re===void 0?!0:(S(re,re==="ack_pressure"?C(N):N-pe.enqueuedAtMs,pe.threadKey,pe.streamIdentity,()=>pe.supersede?.()),!1)});ce.length===0?t.pendingByThread.delete(ye):(t.pendingByThread.set(ye,ce),ne.push(ye))}}t.activeThreads.splice(0,t.activeThreads.length);for(let ye of ne)t.activeThreads.push(ye)},M=N=>{switch(h!==void 0&&h<=N){case!0:return;case!1:break}p?.(),h=N,p=a(Math.max(1,N-o()),()=>{p=void 0,h=void 0,T(),$(),I()})},I=()=>{let N;for(let W of t.pendingByThread.values())for(let ee of W){let ne=ee.enqueuedAtMs+i;N=N===void 0?ne:Math.min(N,ne)}switch(N){case void 0:return;default:for(let W of f)N=Math.min(N,W.startedAtMs+i);M(N)}},P=()=>{for(;;){let N=FY(t);switch(N){case void 0:return;default:let W=o(),ee=A(W)?"ack_pressure":N.enqueuedAtMs+i<=W?"queue_age":void 0;if(ee===void 0)return N;S(ee,ee==="ack_pressure"?C(W):W-N.enqueuedAtMs,N.threadKey,N.streamIdentity,()=>N.supersede?.())}}},z=()=>{let N=n.activeThreads.length>0,W=t.activeThreads.length>0&&u<s;switch(N&&(!W||l<VFe)){case!0:{let ee=FY(n);if(ee===void 0)throw new Error("Commander push priority lane lost its pending task");return l+=1,{priority:"priority",pending:ee,startedAtMs:o()}}case!1:switch(W){case!0:{let ee=P();return ee===void 0?z():(l=0,{priority:"replaceable_live",pending:ee,startedAtMs:o()})}case!1:l=0;return}}},$=()=>{switch(c){case!0:return;case!1:c=!0,queueMicrotask(Q)}},J=async N=>{try{await N.pending.task()}catch(W){N.pending.reject(W)}finally{switch(d-=1,N.priority){case"replaceable_live":u-=1;break;case"priority":break}f.delete(N),$()}};function Q(){for(c=!1;d<e.maxInFlight;){let N=z();switch(N){case void 0:return;default:switch(d+=1,f.add(N),t.activeThreads.length>0){case!0:M(N.startedAtMs+i);break;case!1:break}switch(N.priority){case"replaceable_live":u+=1;break;case"priority":break}J(N)}}}return{run:(N,W,ee)=>{if(N.threadKey.trim()==="")throw new Error("Commander push admission threadKey must not be empty");switch(N.owner===void 0||!r.has(N.owner)){case!1:return Promise.reject(new $v);case!0:break}switch(N.pushClass){case"terminal":QFe(t,N.threadKey,N.streamIdentity);break;case"replaceable_live":if(ee===void 0)throw new Error("Commander replaceable live admission requires onSuperseded");let L=o();switch(A(L)){case!0:return Promise.resolve(S("ack_pressure",C(L),N.threadKey,N.streamIdentity,ee));case!1:break}break;case"durable":case"control":break}let ne=o(),ye=new Promise((L,ce)=>{let pe={threadKey:N.threadKey,task:async()=>{let re=await W();L(re)},reject:ce,...ee===void 0?{}:{supersede:()=>L(ee())},...N.streamIdentity===void 0?{}:{streamIdentity:N.streamIdentity},...N.owner===void 0?{}:{owner:N.owner},enqueuedAtMs:ne};switch(HFe(N.pushClass)){case"priority":$Y(n,N.threadKey,pe);break;case"replaceable_live":$Y(t,N.threadKey,pe)}});switch($(),N.pushClass){case"replaceable_live":{let L=ne+i;for(let ce of f)L=Math.min(L,ce.startedAtMs+i);M(L);break}case"durable":case"terminal":case"control":break}return ye},cancelQueued:N=>{r.add(N),jY(n,N),jY(t,N),t.pendingByThread.size===0&&(p?.(),p=void 0,h=void 0)}}}});import{execFile as XFe}from"node:child_process";import{createHash as YFe,randomUUID as eje}from"node:crypto";import{constants as nje,copyFileSync as tje,createReadStream as rje,existsSync as s$,mkdirSync as d$,readFileSync as ZY,readdirSync as Nv,rmSync as KY,statSync as oje,writeFileSync as ije}from"node:fs";import{copyFile as aje,mkdir as WY,stat as sje,writeFile as dje}from"node:fs/promises";import{homedir as uje}from"node:os";import{dirname as u$,join as qa,resolve as l$}from"node:path";import{promisify as lje}from"node:util";function hje(e=process.env){let n=e[cje];if(n===void 0)return!0;let t=n.trim().toLowerCase();return!(t==="0"||t==="false"||t==="off")}function Lv(e=process.env){let n=e.LINZUMI_GIT_SAFETY_SNAPSHOTS_DIR;return n!==void 0&&n.trim()!==""?l$(n):l$(uje(),".linzumi","safety-snapshots")}async function aa(e,n){try{let{stdout:t,stderr:r}=await QY("git",[...n],{cwd:e,encoding:"utf8",timeout:XY,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 YY(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),a=o.slice(3);t.push({status:i,path:a}),(i.includes("R")||i.includes("C"))&&(r+=1)}return t}function qT(e){let n=e.replace(/[^A-Za-z0-9._-]+/g,"-").replace(/^[.-]+|[.-]+$/g,"");return n===""?"x":n}function gje(e){let n=new Date(e.nowMs).toISOString().replace(/-|:|\..*$/g,"").replace("T","-"),t=qT(e.threadId).slice(-12),r=qT(e.turnRef).slice(-12),o=e.captureNonce===void 0?"":`-${qT(e.captureNonce)}`;return`${n}-${t}-${r}${o}`}function yje(e){return`refs/linzumi/safety/${e}`}async function _je(e,n,t=aje){try{await t(e,n,nje.COPYFILE_FICLONE_FORCE)}catch{await t(e,n,0)}}async function eee(e){let n=YFe("sha256");for await(let t of rje(e)){if(!Buffer.isBuffer(t))throw new Error(`Expected a byte buffer while hashing ${e}`);n.update(t)}return n.digest("hex")}async function bje(e){let n=e.env??process.env;if(!hje(n))return{kind:"disabled"};let t=Date.now(),r=()=>Date.now()-t,o=await aa(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=YY(o.stdout);if(i.length===0){let a={kind:"clean",durationMs:r()};return c$.set(a,{cwd:e.cwd,repoRoot:e.cwd,statusRaw:o.stdout,trackedTree:void 0,trackedIndexTree:void 0,copiedFileDigests:new Map}),a}try{let a=e.nowMs??t,s=eje(),d=gje({threadId:e.threadId,turnRef:e.turnRef,nowMs:a,captureNonce:s}),u=e.snapshotsRoot??Lv(n),c=qa(u,qT(e.threadId),d),l=e.maxTotalBytes??fje,f=i.filter(N=>N.status==="??").map(N=>N.path),p=i.filter(N=>N.status!=="??"&&N.status!=="!!").map(N=>N.path),h=await aa(e.cwd,["rev-parse","--show-toplevel"]),y=h.ok?h.stdout.trim():e.cwd,m=await aa(e.cwd,["branch","--show-current"]),_=m.ok&&m.stdout.trim()!==""?m.stdout.trim():void 0,w=await aa(e.cwd,["rev-parse","HEAD"]),v=w.ok?w.stdout.trim():void 0,S,C,A,T;if(p.length>0){let N=await aa(e.cwd,["stash","create",`linzumi safety snapshot ${d}`]),W=N.ok?N.stdout.trim():"";if(W!==""){S=W;let[ee,ne]=await Promise.all([aa(e.cwd,["rev-parse",`${W}^{tree}`]),aa(e.cwd,["rev-parse",`${W}^2^{tree}`])]);A=ee.ok?ee.stdout.trim():void 0,T=ne.ok?ne.stdout.trim():void 0;let ye=yje(d);C=(await aa(e.cwd,["update-ref",ye,W])).ok?ye:void 0}}await WY(c,{recursive:!0});let M=[],I=new Map,P=0,z=async(N,W)=>{let ee=qa(y,N),ne=0;try{let ye=await sje(ee);if(!ye.isFile())return!1;if(ne=ye.size,P+ne>l)return M.push({path:N,bytes:ne,reason:"size_cap"}),!1;let L=qa(c,W,N);return await WY(u$(L),{recursive:!0}),await _je(ee,L),I.set(N,await eee(L)),P+=ne,!0}catch{return M.push({path:N,bytes:ne,reason:"copy_error"}),!1}},$=(N,W)=>N.reduce(async(ee,ne)=>{let ye=await ee;return await z(ne,W)&&ye.push(ne),ye},Promise.resolve([])),J=await $(f,"untracked"),Q=S===void 0&&p.length>0?await $(p,"tracked"):[],K={version:1,id:d,createdAtMs:a,threadId:e.threadId,turnRef:e.turnRef,cwd:e.cwd,repoRoot:y,branch:_,headCommit:v,stashCommit:S,safetyRef:C,trackedPaths:p,untrackedPaths:J,trackedFallbackPaths:Q,skippedFiles:M,copiedBytes:P,durationMs:r()};await dje(qa(c,"manifest.json"),`${JSON.stringify(K,null,2)}
|
|
625
625
|
`);let Z={kind:"snapshot",manifest:K,snapshotDir:c};return c$.set(Z,{cwd:e.cwd,repoRoot:y,statusRaw:o.stdout,trackedTree:A,trackedIndexTree:T,copiedFileDigests:I}),Z}catch(a){return{kind:"error",message:a instanceof Error?a.message:String(a),durationMs:r()}}}function $T(e){let n=[],t;try{t=Nv(e)}catch{return[]}for(let r of t){let o=qa(e,r),i;try{i=Nv(o)}catch{continue}for(let a of i){let s=qa(o,a);try{let d=JSON.parse(ZY(qa(s,"manifest.json"),"utf8"));d.version===1&&typeof d.id=="string"&&n.push({manifest:d,snapshotDir:s})}catch{}}}return n.sort((r,o)=>o.manifest.createdAtMs-r.manifest.createdAtMs)}async function nee(e){let{manifest:n,snapshotDir:t}=e.snapshot,r=l$(e.toDir);if(s$(r)&&Nv(r).length>0)throw new Error(`refusing to restore into non-empty directory: ${r} (recovery never clobbers existing state)`);d$(r,{recursive:!0});let o=[];for(let s of n.untrackedPaths){let d=qa(t,"untracked",s);if(!s$(d))continue;let u=qa(r,s);d$(u$(u),{recursive:!0}),tje(d,u),o.push(s)}let i=[],a=[];for(let s of n.trackedPaths){let d;if(n.stashCommit!==void 0)try{let{stdout:c}=await QY("git",["show",`${n.stashCommit}:${s}`],{cwd:n.repoRoot,encoding:"buffer",timeout:XY,maxBuffer:536870912});d=c}catch{d=void 0}if(d===void 0){let c=qa(t,"tracked",s);s$(c)&&(d=ZY(c))}if(d===void 0){a.push(s);continue}let u=qa(r,s);d$(u$(u),{recursive:!0}),ije(u,d),i.push(s)}return{restoredDir:r,restoredTracked:i,restoredUntracked:o,missingTracked:a,stashCommit:n.stashCommit,safetyRef:n.safetyRef}}async function tee(e){let n=e.nowMs??Date.now(),t=e.maxAgeMs??pje,r=e.maxCount??mje,o=$T(e.snapshotsRoot),i=o.filter(l=>n-l.manifest.createdAtMs>t),s=o.filter(l=>n-l.manifest.createdAtMs<=t).slice(r),d=[...i,...s],u=[],c=[];for(let l of d){let{manifest:f,snapshotDir:p}=l;f.safetyRef!==void 0&&f.stashCommit!==void 0&&(await aa(f.repoRoot,["update-ref","-d",f.safetyRef,f.stashCommit])).ok&&c.push(f.safetyRef);try{KY(p,{recursive:!0,force:!0}),u.push(p)}catch{}}try{for(let l of Nv(e.snapshotsRoot)){let f=qa(e.snapshotsRoot,l);try{oje(f).isDirectory()&&Nv(f).length===0&&KY(f,{recursive:!0,force:!0})}catch{}}}catch{}return{removedSnapshotDirs:u,removedRefs:c}}function xje(e){return vje.some(n=>n.test(e))}function ree(e){let n=[],t=[],r="",o,i=()=>{r!==""&&(t.push(r),r="")},a=()=>{i(),t.length>0&&(n.push(t),t=[])};for(let s=0;s<e.length;s+=1){let d=e[s];if(o!==void 0){d===o?o=void 0:r+=d;continue}if(d==="'"||d==='"'){o=d;continue}if(d==="\\"){s+=1;let u=e[s];u!==void 0&&(r+=u);continue}if(d===";"||d===`
|
|
626
626
|
`){a();continue}if(d==="&"||d==="|"){a(),e[s+1]===d&&(s+=1);continue}if(/\s/.test(d)){i();continue}r+=d}return a(),n}function VY(e){let n=e.lastIndexOf("/");return n===-1?e:e.slice(n+1)}function kje(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"]},a=new Set(i[r]??[]),s=[],d=[],u=[],c=!1,l=!1;for(let y=0;y<o.length;y+=1){let m=o[y];if(!c&&m==="--"){c=!0;continue}if(!c&&m.startsWith("-")){s.push(m),(a.has(m)||r==="commit"&&/^-[A-Za-z]+$/.test(m)&&m.endsWith("m"))&&(y+=1);continue}if(m==="."||m==="./"||m===":/"){l=!0,(c?u:d).push(m);continue}(c?u:d).push(m)}let f=(c?u:d).filter(y=>y!=="."&&y!=="./"&&y!==":/"),h=Cje({subcommand:r,rest:o,flags:s,afterDashDash:u,sawDashDash:c,treeWide:l,pathTokens:f,hasShortFlagLetter:y=>s.some(m=>/^-[A-Za-z]+$/.test(m)&&m.slice(1).includes(y))});return h===void 0||t===void 0?h:{...h,workdir:t}}function Cje(e){let{subcommand:n,rest:t,flags:r,afterDashDash:o,sawDashDash:i,treeWide:a,pathTokens:s,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:a?{operation:"restored",paths:[],scope:"tracked"}:s.length===0?void 0:{operation:"restored",paths:s,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 a?{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:s.length===0?{operation:"deleted",paths:[],scope:"untracked"}:{operation:"deleted",paths:s,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"}:s.length===0?void 0:{operation:"committed",paths:s,scope:"named"};default:return}}function Tje(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 oee(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(Sje.has(VY(d))){o+=1;continue}break}let i=e[o];if(i===void 0)return;let a=VY(i);if(a==="cd"||a==="pushd"){r.dir=e[o+1];return}if(wje.has(a)&&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 ree(u))oee(l,n,t+1,c)}return}let s=d=>d===void 0||d.workdir!==void 0||r.dir===void 0?d:{...d,workdir:r.dir};if(a==="git"){let d=s(kje(e.slice(o)));d!==void 0&&n.push(d);return}if(a==="rm"){let d=s(Tje(e.slice(o)));d!==void 0&&n.push(d)}}function Pje(e){let n=[],t={dir:void 0};for(let r of ree(e))oee(r,n,0,t);return n}function Aje(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 HY(e,n){return e===n||n.startsWith(`${e}/`)?!0:e.includes("/")&&n.endsWith(`/${e}`)}function Ije(e){let n=new Map,t=(i,a,s)=>{n.delete(i),n.set(i,{path:i,operation:a,wasUntracked:s})},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 a of e.trackedPaths)t(a,i.operation,!1);break;case"untracked":for(let a of e.untrackedPaths)t(a,i.operation,!0);break;case"named":{for(let a of i.paths){let s=Aje(a,e.repoRoot);if(s!==void 0){for(let d of e.trackedPaths)HY(s,d)&&t(d,i.operation,!1);if(i.operation==="deleted")for(let d of e.untrackedPaths)HY(s,d)&&t(d,i.operation,!0)}}break}}return[...n.values()]}function Mje(e,n){if(ss.delete(e),ss.size>=Eje){let t=ss.keys().next().value;t!==void 0&&ss.delete(t)}ss.set(e,n)}async function Tg(e){try{let n=await bje({cwd:e.cwd,threadId:e.threadKey,turnRef:e.turnRef,snapshotsRoot:e.snapshotsRoot,env:e.env});if(e.isCurrentAttempt?.()===!1)return e.log("git_safety.snapshot_discarded_stale_attempt",{thread_key:e.threadKey,turn_ref:e.turnRef,cwd:e.cwd,outcome_kind:n.kind,snapshot_id:n.kind==="snapshot"?n.manifest.id:null}),n;switch(n.kind){case"snapshot":{Mje(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":ss.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":ss.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}}async function Dje(e,n){let t=[...n.entries()],r=64;for(let o=0;o<t.length;o+=r){let i=t.slice(o,o+r);if((await Promise.all(i.map(async([s,d])=>{try{return await eee(qa(e,s))===d}catch{return!1}}))).some(s=>!s))return!0}return!1}async function qje(e,n){if(!n)return{worktree:void 0,index:void 0};let t=await aa(e,["stash","create","linzumi safety provider-boundary validation"]),r=t.ok?t.stdout.trim():"";if(r==="")return{worktree:void 0,index:void 0};let[o,i]=await Promise.all([aa(e,["rev-parse",`${r}^{tree}`]),aa(e,["rev-parse",`${r}^2^{tree}`])]);return{worktree:o.ok?o.stdout.trim():void 0,index:i.ok?i.stdout.trim():void 0}}async function $je(e,n){if(n?.kind==="disabled")return{kind:"current"};if(n?.kind==="not_git"){let a=await aa(e,["status","--porcelain=v1","-z","--untracked-files=all"]);return!a.ok&&a.stderr.toLowerCase().includes("not a git repository")?{kind:"current"}:{kind:"changed"}}if(n===void 0)return{kind:"current"};if(n.kind==="error")return{kind:"changed"};let t=c$.get(n);if(t===void 0)return{kind:"changed"};let r=await aa(e,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!r.ok||r.stdout!==t.statusRaw)return{kind:"changed"};let o=YY(r.stdout),i=await qje(e,o.some(a=>a.status!=="??"&&a.status!=="!!"));return i.worktree!==t.trackedTree||i.index!==t.trackedIndexTree?{kind:"changed"}:await Dje(t.repoRoot,t.copiedFileDigests)?{kind:"changed"}:{kind:"current"}}async function iee(e,n,t){if(t===0&&n?.kind==="error")return e.log("git_safety.snapshot_provider_boundary_initial_error_fail_open",{thread_key:e.threadKey,turn_ref:e.turnRef,cwd:e.cwd,message:n.message,duration_ms:n.durationMs}),{kind:"unchanged"};if((await $je(e.cwd,n)).kind==="current")return e.log("git_safety.snapshot_provider_boundary_unchanged",{thread_key:e.threadKey,turn_ref:e.turnRef,cwd:e.cwd}),t===0?{kind:"unchanged"}:{kind:"recaptured",outcome:n};if(t>=Oje)return e.log("git_safety.snapshot_provider_boundary_unstable",{thread_key:e.threadKey,turn_ref:e.turnRef,cwd:e.cwd,replacement_captures:t}),{kind:"unstable",outcome:n,replacementCaptures:t};e.log("git_safety.snapshot_provider_boundary_changed",{thread_key:e.threadKey,turn_ref:e.turnRef,cwd:e.cwd,replacement_capture:t+1});let o=await Tg(e);return await iee(e,o,t+1)}async function aee(e){return await iee(e,e.initialOutcome,0)}function FT(e,n){let t=ss.get(e);if(t!==void 0){t.destructiveCommand===void 0&&xje(n)&&(t.destructiveCommand=n);try{let r=Pje(n);if(r.length===0)return;let o=Ije({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<Rje?t.workingTreeChanges.set(i.path,i):t.droppedWorkingTreeChangeCount+=1}catch{}}}function Lje(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 zje(e,n,t){let r=n.slice(0,Nje),o=n.length-r.length+Math.max(0,t),i=r.map(s=>`- ${s.operation} \`${s.path}\` (${Lje(s)})`);o>0&&i.push(`- ...and ${o} more`);let a=e.stashCommit===void 0?"":` Tracked changes are also directly recoverable with \`git stash apply ${e.stashCommit}\`.`;return`Changed your working tree:
|
|
627
627
|
${i.join(`
|
|
@@ -929,7 +929,7 @@ const watchdog = setInterval(() => {
|
|
|
929
929
|
trust_level = "trusted"
|
|
930
930
|
`}let o=e.slice(r.start,r.end),i=/^(\s*trust_level\s*=\s*).*(\r?)$/m,a=i.test(o)?o.replace(i,'$1"trusted"$2'):`${tde(o)}
|
|
931
931
|
trust_level = "trusted"
|
|
932
|
-
`;return`${e.slice(0,r.start)}${a}${e.slice(r.end)}`}function _Ke(e,n){let t=/^\s*\[[^\]]+\]\s*$/gm,r;for(;(r=t.exec(e))!==null;){if(r[0].trim()!==n)continue;let o=t.exec(e);return{start:r.index,end:o?.index??e.length}}}function bKe(e){return JSON.stringify(e)}function tde(e){return e.replace(/\r?\n+$/,"")}var CN=B(()=>{"use strict"});var ode,rde=B(()=>{ode={name:"@linzumi/cli",version:"1.0.
|
|
932
|
+
`;return`${e.slice(0,r.start)}${a}${e.slice(r.end)}`}function _Ke(e,n){let t=/^\s*\[[^\]]+\]\s*$/gm,r;for(;(r=t.exec(e))!==null;){if(r[0].trim()!==n)continue;let o=t.exec(e);return{start:r.index,end:o?.index??e.length}}}function bKe(e){return JSON.stringify(e)}function tde(e){return e.replace(/\r?\n+$/,"")}var CN=B(()=>{"use strict"});var ode,rde=B(()=>{ode={name:"@linzumi/cli",version:"1.0.268",description:"Linzumi CLI \u2014 point a Codex agent at the real code on your laptop, with your team watching and steering from shared threads.",type:"module",bin:{linzumi:"bin/linzumi.js"},files:["README.md","bin","dist","scripts"],scripts:{"test:agent-source":"LINZUMI_CI_QUARANTINE=0 pnpm exec vitest run --config vitest.config.mjs test/channelSession.test.ts test/kandanQueue.test.ts test/llmProxySessionCredential.test.ts test/runnerBridge.test.ts test/threadCodexWorkerIpc.test.ts -t '(?:^| )(retains three busy accepted source snapshots without fusing or interrupting|keeps different accepted agent sources distinct through interrupt pickup|does not install an old mint after its credential is (replaced|stopped)|worker agent capability requires an exact true ready flag|starts an explicitly server-keyed OpenAI agent worker without local OpenAI credentials|applies the accepted OpenAI follow-up model on an existing worker|refuses explicit OpenAI worker creation with (passthrough|missing-token|blank-origin) binding|refuses a private agent turn without an owned relay before Codex|explicitly capable worker receives a private request through ordinary IPC|old worker receives no private agent source descriptor)$'",build:"rescript build ../linzumi-cli-rescript && node scripts/build.mjs","test:actual-commander-parity":"pnpm --dir ../linzumi-cli-rescript build && node --test --test-concurrency=1 ../linzumi-cli-rescript/src/parity/ActualCommanderParityConformance.res.mjs","bump-version":"node scripts/bump-cli-version.mjs","codex:history-table":"node scripts/codex_history_table.mjs",test:"npm run test:startup && node --import tsx --test ../linzumi-cli-rescript/src/parity/McpToolCallBoundaryTest.res.mjs && rescript build ../../kandan/server_v2/web/replay_harness && vitest run --config vitest.config.mjs",typecheck:"rescript build ../linzumi-cli-rescript && tsgo --noEmit -p tsconfig.source.json","typecheck:all":"rescript build ../linzumi-cli-rescript && tsgo --noEmit -p tsconfig.json","typecheck:watch":"rescript build ../linzumi-cli-rescript && tsgo --noEmit -w -p tsconfig.source.json",prepack:"rescript build -q ../linzumi-cli-rescript && node scripts/build.mjs","pack:dry-run":"npm pack --dry-run","record:agent-fixtures":"tsx scripts/record-agent-replay-fixtures.ts","normalize:agent-fixture":"tsx scripts/normalize-agent-replay-fixture.ts","vendor:codex-app-server-protocol":"tsx scripts/vendor-codex-app-server-protocol.ts","replay:agent-fixture":"tsx scripts/replay-agent-fixture.ts","replay:agent-backend":"tsx scripts/replay-agent-backend.ts","vendor:codex-app-server-protocol:check":"tsx scripts/vendor-codex-app-server-protocol.ts --check","replay:agent-backend-browser":"tsx scripts/replay-agent-backend-browser.ts","promote:gstack-claude-smoke-fixture":"tsx scripts/promote-gstack-claude-smoke-fixture.ts","diagnose:claude-probe":"tsx scripts/diagnose-claude-probe.ts","test:startup":"npm run build && node --test --test-concurrency=1 ../linzumi-cli-rescript/src/parity/CommanderStartupRefusalConformance.res.mjs"},keywords:["linzumi","kandan","codex","local-runner"],license:"MIT",publishConfig:{access:"public"},dependencies:{"@anthropic-ai/claude-agent-sdk":"0.3.199","@inquirer/prompts":"^7.8.6","@modelcontextprotocol/sdk":"^1.29.0","@openai/codex":"0.153.2",blessed:"^0.1.81","proper-lockfile":"3.2.0",undici:"^6.25.0",ws:"^8.18.0",zod:"^3.25.76"},engines:{node:">=20"},readmeFilename:"README.md",devDependencies:{"@types/blessed":"^0.1.27","@types/node":"^22.18.6","@types/proper-lockfile":"4.1.4","@typescript/native-preview":"7.0.0-dev.20260703.1",esbuild:"^0.27.2","fast-check":"^3.23.2",rescript:"12.3.0",tsx:"^4.21.0",typescript:"^5.9.3",vitest:"^1.6.1"}}});import{createHash as xKe}from"node:crypto";import{existsSync as TN,mkdirSync as PN,readFileSync as wKe,readdirSync as ide,renameSync as SKe,rmSync as ade,statSync as kKe,writeFileSync as AN}from"node:fs";import{homedir as sde}from"node:os";import{dirname as IN,join as ll}from"node:path";function wo(e=process.env){let n=e.LINZUMI_VM_CONFIG_FILE;return n!==void 0&&n.trim()!==""?n:ll(sde(),".linzumi","vm.json")}function RN(e=wo()){return ll(IN(e),"vm-machines")}function Eo(e=process.env){let n=e.LINZUMI_VM_RUNTIME_DIR;return n!==void 0&&n.trim()!==""?n:ll(sde(),".linzumi","vm-runtime")}function uy(e=wo()){if(!TN(e))return CKe;let n=JSON.parse(wKe(e,"utf8"));if(typeof n!="object"||n===null||n.version!==1)throw new Error(`invalid Linzumi VM state file: ${e}`);let t=n,r=TKe(t.cloud,e);return{version:1,enabled:t.enabled===!0,...r===void 0?{}:{cloud:r}}}function TKe(e,n){if(e==null)return;if(typeof e!="object")throw new Error(`invalid "cloud" section in Linzumi VM state file: ${n}`);let t=e;if(t.baseUrl!==void 0&&typeof t.baseUrl!="string"||t.apiKeyFile!==void 0&&typeof t.apiKeyFile!="string")throw new Error(`invalid "cloud" section in Linzumi VM state file: ${n}`);let r=PKe(t.agent,n);return{enabled:t.enabled===!0,...t.baseUrl===void 0?{}:{baseUrl:t.baseUrl},...t.apiKeyFile===void 0?{}:{apiKeyFile:t.apiKeyFile},...r===void 0?{}:{agent:r}}}function PKe(e,n){if(e==null)return;let t=()=>{throw new Error(`invalid "cloud.agent" section in Linzumi VM state file: ${n}`)};typeof e!="object"&&t();let r=e;return(r.image!==void 0&&typeof r.image!="string"||r.maxConcurrentTurns!==void 0&&typeof r.maxConcurrentTurns!="number"||r.autoStopSeconds!==void 0&&typeof r.autoStopSeconds!="number"||r.allowCidrs!==void 0&&!(Array.isArray(r.allowCidrs)&&r.allowCidrs.every(o=>typeof o=="string")))&&t(),{enabled:r.enabled===!0,...r.image===void 0?{}:{image:r.image},...r.allowCidrs===void 0?{}:{allowCidrs:r.allowCidrs},...r.maxConcurrentTurns===void 0?{}:{maxConcurrentTurns:r.maxConcurrentTurns},...r.autoStopSeconds===void 0?{}:{autoStopSeconds:r.autoStopSeconds}}}function AKe(e,n=wo()){PN(IN(n),{recursive:!0});let t=`${n}.tmp`;AN(t,`${JSON.stringify(e,null,2)}
|
|
933
933
|
`,{mode:384}),SKe(t,n)}function EN(e,n=wo()){let t={...uy(n),enabled:e};return AKe(t,n),t}function MN(e=wo()){let n=RN(e);return TN(n)?ide(n).sort():[]}function BA(e,n=wo()){JA(e);let t=RN(n);PN(t,{recursive:!0}),AN(ll(t,e),"",{mode:384})}function fw(e,n=wo()){let t=RN(n);for(let r of e)JA(r),ade(ll(t,r),{force:!0})}function ON(e=wo()){return ll(IN(e),"vm-goldens")}function lde(e,n=wo()){JA(e);let t=ON(n);PN(t,{recursive:!0}),AN(ll(t,e),"",{mode:384})}function cde(e=wo()){let n=ON(e);return TN(n)?ide(n).sort().flatMap(t=>{try{return[{name:t,registeredAtMs:kKe(ll(n,t)).mtimeMs}]}catch{return[]}}):[]}function fde(e,n=wo()){let t=ON(n);for(let r of e)JA(r),ade(ll(t,r),{force:!0})}function RKe(e){return e.startsWith(IKe)}function pde(e,n){let t=new Set(n);return[...new Set(e)].filter(RKe).filter(r=>!t.has(r)).sort()}function JA(e){if(e===""||e.includes("/")||e.includes("\\")||e==="."||e==="..")throw new Error(`unsafe VM machine name: ${e}`)}function KA(e=process.env,n=wo(e)){switch(e.LINZUMI_VM_EXECUTION?.trim().toLowerCase()){case"1":case"true":return!0;case"0":case"false":return!1;default:break}try{return uy(n).enabled}catch(r){return console.warn(`linzumi vm: VM execution preview staying OFF - could not read the VM state file at ${n} (${r instanceof Error?r.message:String(r)}); run \`linzumi vm enable\` to rewrite it.`),!1}}function ly(e=process.env){let n=e.LINZUMI_VM_CODEX_VERSION?.trim();return n===void 0||n===""?qp:n}function WA(e){return`linzumi-codex-${xKe("sha256").update(`${e.cwd}\0${e.kandanThreadId??"main"}`).digest("hex").slice(0,12)}`}var pa,qp,dde,ude,CKe,IKe,Ji=B(()=>{"use strict";rde();pa="1.3.2",qp=ode.dependencies["@openai/codex"],dde=2,ude=4096,CKe={version:1,enabled:!1};IKe="linzumi-golden-"});function HA(e){return e==="open"||e==="hardened"?e:VA}function ZA(e){if(typeof e!="string")return!1;let n=e.trim();if(n==="")return!1;let t=n.indexOf("/");if(t===-1)return!1;let r=n.slice(0,t),o=n.slice(t+1),i=Number.parseInt(o,10);if(!Number.isInteger(i)||String(i)!==o)return!1;if(r.includes(":"))return i>=0&&i<=128&&OKe(r);let a=r.split(".");if(a.length!==4)return!1;for(let s of a){let d=Number.parseInt(s,10);if(!Number.isInteger(d)||String(d)!==s||d<0||d>255)return!1}return i>=0&&i<=32}function OKe(e){if(e.includes(":::")||e.split("::").length-1>1)return!1;let t=e.split(":").filter(r=>r!=="");return t.length===0||t.length>8?!1:t.every(r=>/^[0-9a-fA-F]{1,4}$/.test(r))}function QA(e){if(typeof e!="string")return!1;let n=e.trim();if(n===EKe||n===MKe)return!0;let t=n.indexOf("/");return t===-1?!1:n.slice(t+1).trim()==="0"}function DKe(e=process.env){let n=e.LINZUMI_VM_EGRESS_CIDRS;return n===void 0?[...DN]:n.split(",").map(t=>t.trim()).filter(t=>t!=="")}function qKe(e=process.env){let n=DKe(e);if(n.length===0)throw new Error("VM egress allowlist is empty; the default-deny egress gate refuses to create a VM with no reachable gateway (set LINZUMI_VM_EGRESS_CIDRS)");for(let t of n){if(QA(t))throw new Error(`VM egress allowlist contains a wide-open CIDR (${t}); the default-deny egress ship-gate forbids open egress from a job VM`);if(!ZA(t))throw new Error(`VM egress allowlist contains a malformed CIDR (${t}); refusing to create a VM with an unparseable egress policy`)}return{allowedCidrs:n,mode:"allowlist"}}function $Ke(e){return e.LINZUMI_VM_EGRESS_CIDRS!==void 0}function FKe(e=process.env){return $Ke(e)?!1:DN.length===1&&DN[0]===qN}function jKe(){return{mode:"open",allowedCidrs:[]}}function XA(e=process.env,n=VA,t=r=>console.warn(r)){if(n==="open")return t("VM egress: FULL INTERNET (open mode) - this job VM has unrestricted network egress. Filesystem/process isolation is unchanged; only the network knob is open. Use Hardened mode (deny-all + LINZUMI_VM_EGRESS_CIDRS allowlist) to lock egress down."),jKe();if(FKe(e))throw new Error(`VM egress Hardened mode is selected but the egress allowlist is still the placeholder gateway range (${qN}) and no LINZUMI_VM_EGRESS_CIDRS override is set. Refusing to start a hardened job VM with an unconfirmed egress policy - set LINZUMI_VM_EGRESS_CIDRS to the real gateway CIDR(s) (or replace the placeholder default), or use the default Full-internet (open) egress mode.`);return qKe(e)}function mde(e){if(e===null||typeof e!="object"||e.mode!=="allowlist"&&e.mode!=="open")throw new Error("VM egress policy is not in a known mode (allowlist|open) (gate violated)");if(e.mode==="open"){if(!Array.isArray(e.allowedCidrs)||e.allowedCidrs.length!==0)throw new Error("VM egress policy is open mode but carries a non-empty allowlist (open mode is unrestricted; the allowlist must be empty)");return e}if(!Array.isArray(e.allowedCidrs)||e.allowedCidrs.length===0)throw new Error("VM egress policy has an empty allowlist (gate violated)");for(let n of e.allowedCidrs)if(QA(n)||!ZA(n))throw new Error(`VM egress policy allowlist entry is invalid or wide-open (${n})`);return e}var EKe,MKe,qN,DN,VA,$N=B(()=>{"use strict";EKe="0.0.0.0/0",MKe="::/0",qN="34.120.0.0/16",DN=Object.freeze([qN]),VA="open"});function yde(e){return`/etc/linzumi/provisioned-v2-${e.replace(/[^A-Za-z0-9._-]/g,"_")}`}function eI(e){return["/bin/sh","-c",["set -e","apk add --no-cache ca-certificates nodejs npm git ripgrep bash curl >/dev/null","update-ca-certificates >/dev/null 2>&1 || true",`npm install -g --no-fund --no-audit @openai/codex@${Pi(e)} >/dev/null`,"mkdir -p /etc/linzumi /opt/linzumi","rm -f /etc/linzumi/provisioned-v2-* 2>/dev/null || true",`touch ${yde(e)}`].join(" && ")]}function _de(e){return["/bin/sh","-c",`test -f ${yde(e)} && command -v codex >/dev/null && command -v node >/dev/null && test -s ${NKe}`]}function bde(){return["/bin/sh","-c",`grep -q '^nameserver' /etc/resolv.conf 2>/dev/null || { ${LKe.map(n=>`echo ${Pi(`nameserver ${n}`)} >>/etc/resolv.conf`).join("; ")}; } 2>/dev/null; true`]}function vde(e){return Object.entries(e).map(([n,t])=>`export ${n}=${Pi(t)}
|
|
934
934
|
`).join("")}function xde(e){let n=["codex",...e.codexArgs].map(t=>Pi(t)).join(" ");return["/bin/sh","-c",`cd ${Pi(e.cwd)} && export CODEX_HOME=${Pi(pw)} && . ${LN} && nohup ${n} >${hde} 2>&1 &`]}function zN(){return["/bin/sh","-c",`rm -rf ${YA} 2>/dev/null; true`]}function wde(e){return["/bin/sh","-c",`curl -sf http://127.0.0.1:${e}/readyz >/dev/null`]}function Sde(){return["/bin/sh","-c",`nohup node ${FN} >${gde} 2>&1 &`]}function kde(){return["/bin/sh","-c",'pkill -INT -f "codex app-server" 2>/dev/null; pkill -f "node /opt/linzumi/relay.js" 2>/dev/null; true']}function Cde(){return["/bin/sh","-c",['pkill -KILL -f "codex app-server" 2>/dev/null','pkill -KILL -f "node /opt/linzumi/relay.js" 2>/dev/null','i=0; while pgrep -f "codex app-server" >/dev/null 2>&1; do i=$((i+1)); [ "$i" -ge 200 ] && break; done',"true"].join("; ")]}function Tde(){return["/bin/sh","-c",`tail -n 40 ${hde} 2>/dev/null; tail -n 10 ${gde} 2>/dev/null`]}function Pi(e){return`'${e.replaceAll("'",String.raw`'\''`)}'`}var FN,hde,gde,jN,YA,pw,NN,NKe,LKe,LN,nI=B(()=>{"use strict";FN="/opt/linzumi/relay.js",hde="/tmp/linzumi-codex-app-server.log",gde="/tmp/linzumi-relay.log",jN="/opt/linzumi/mcp-server.mjs";YA="/dev/shm/linzumi",pw=`${YA}/codex`,NN=`${YA}/mcp-auth.json`;NKe="/etc/ssl/certs/ca-certificates.crt";LKe=["1.1.1.1","8.8.8.8"];LN=`${YA}/codex.env`});import{randomBytes as zKe}from"node:crypto";import{createServer as Pde}from"node:net";async function Rde(){let e=zKe(16).toString("hex"),n=new Map,t=new Set,r={nextId:1,control:void 0,controlEverConnected:!1,closed:!1,pingTimer:void 0,relayWaiters:[]},o=l=>{let f=n.get(l);f!==void 0&&(n.delete(l),clearTimeout(f.timer),f.socket.destroy())},i=()=>{for(let l of t)try{l()}catch{}t.clear()},a=l=>{r.control?.destroy(),r.control=l,r.controlEverConnected=!0,l.setNoDelay(!0),l.on("data",()=>{}),l.on("error",()=>{}),l.on("close",()=>{r.control===l&&(r.control=void 0,r.closed||i())}),r.relayWaiters.splice(0).forEach(f=>f())},s=(l,f)=>{let p=n.get(f);if(p===void 0){l.destroy();return}n.delete(f),clearTimeout(p.timer),l.setNoDelay(!0),p.socket.setNoDelay(!0),l.on("error",()=>p.socket.destroy()),p.socket.on("error",()=>l.destroy()),l.pipe(p.socket),p.socket.pipe(l),l.on("close",()=>p.socket.destroy()),p.socket.on("close",()=>l.destroy()),p.socket.resume()},d=Pde(l=>{l.on("error",()=>{}),BKe(l,f=>{let p=f.split(" ");if(p[0]==="CTRL"&&p[1]===e&&p.length===2){a(l);return}if(p[0]==="DATA"&&p[1]===e&&p[2]!==void 0&&p.length===3){s(l,p[2]);return}l.destroy()})}),u=Pde(l=>{l.on("error",()=>{});let f=r.control;if(f===void 0){l.destroy();return}let p=String(r.nextId);r.nextId+=1,l.pause();let h=setTimeout(()=>o(p),UKe);n.set(p,{socket:l,timer:h}),f.write(`OPEN ${p}
|
|
935
935
|
`)});await Promise.all([Ade(d),Ade(u)]),r.pingTimer=setInterval(()=>{r.control?.write(`PING
|
|
@@ -1607,7 +1607,7 @@ To kick the agent off:
|
|
|
1607
1607
|
`,M=Buffer.byteLength(T,"utf8");if(M>a)return l("runner_diagnostics.spool_entry_dropped",{reason:"entry_too_large",entry_bytes:M,max_entry_bytes:a}),!1;iZe(n,{recursive:!0}),p(u)+M>i&&h(),m(M);let I=_()?`
|
|
1608
1608
|
`:"";return tZe(u,`${I}${T}`,"utf8"),!0}catch(A){return l("runner_diagnostics.spool_failed",{error:A instanceof Error?A.message:String(A)}),!1}},v=C=>{let A=[],T=sZe(C,"utf8");for(let M of T.split(`
|
|
1609
1609
|
`))if(M.trim()!=="")try{let I=JSON.parse(M);I!==null&&typeof I=="object"&&A.push({parsed:I,raw:M})}catch{}return A};return{append:w,drain:async C=>{if(c)return{uploadedBatches:0,uploadedEntries:0,remainingBatches:f().length,skipped:!0};c=!0;let A=0,T=0;try{h(),m(0);let M=s()-o;for(let I of f()){let P;try{P=v(I)}catch(Z){l("runner_diagnostics.spool_batch_unreadable",{file:I,error:Z instanceof Error?Z.message:String(Z)}),y(I,"unreadable");continue}let z=P.filter(Z=>{let N=kZe(Z.parsed);return N===void 0||N>=M});if(z.length===0){y(I,"empty_or_expired");continue}let $=C6(I,".jsonl"),J=z.map(Z=>Z.raw).join(`
|
|
1610
|
-
`),Q=z.map(Z=>Z.parsed.spooled_at).filter(Z=>typeof Z=="string"),K={bundle_name:"runner-diagnostics-spool",exported_at:new Date(s()).toISOString(),idempotency_key:$,diagnostics:{kind:"runner_diagnostic_log",spool_batch:!0,idempotency_key:$,entry_count:z.length,...Q.length===0?{}:{first_spooled_at:Q[0],last_spooled_at:Q[Q.length-1]}},telemetry_ndjson:J};try{await C(K)}catch(Z){l("runner_diagnostics.spool_upload_failed",{file:I,remaining_batches:f().length,error:Z instanceof Error?Z.message:String(Z)});break}A+=1,T+=z.length;try{hpe(I)}catch(Z){l("runner_diagnostics.spool_delete_failed",{file:I,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:A,uploadedEntries:T,remainingBatches:f().length,skipped:!1}},pendingBatchFiles:f}}var pZe,mZe,hZe,gZe,yZe,gpe,bZe,vZe,_pe=B(()=>{"use strict";IA();pZe=32*1024*1024,mZe=10080*60*1e3,hZe=4*1024*1024,gZe=1024*1024,yZe="spool.jsonl",gpe=/^batch-(\d{1,16})-[0-9a-f-]+\.jsonl$/;bZe=/\b([A-Z][A-Z0-9_]{1,})=("[^"\n]*"|'[^'\n]*'|[^\s"'`;,)\]}]+)/g,vZe=/(?:\/(?:[A-Za-z0-9._@~+-]|%[0-9A-Fa-f]{2})+){2,}/g});var no,P6,Nc=B(()=>{"use strict";no="1.0.
|
|
1610
|
+
`),Q=z.map(Z=>Z.parsed.spooled_at).filter(Z=>typeof Z=="string"),K={bundle_name:"runner-diagnostics-spool",exported_at:new Date(s()).toISOString(),idempotency_key:$,diagnostics:{kind:"runner_diagnostic_log",spool_batch:!0,idempotency_key:$,entry_count:z.length,...Q.length===0?{}:{first_spooled_at:Q[0],last_spooled_at:Q[Q.length-1]}},telemetry_ndjson:J};try{await C(K)}catch(Z){l("runner_diagnostics.spool_upload_failed",{file:I,remaining_batches:f().length,error:Z instanceof Error?Z.message:String(Z)});break}A+=1,T+=z.length;try{hpe(I)}catch(Z){l("runner_diagnostics.spool_delete_failed",{file:I,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:A,uploadedEntries:T,remainingBatches:f().length,skipped:!1}},pendingBatchFiles:f}}var pZe,mZe,hZe,gZe,yZe,gpe,bZe,vZe,_pe=B(()=>{"use strict";IA();pZe=32*1024*1024,mZe=10080*60*1e3,hZe=4*1024*1024,gZe=1024*1024,yZe="spool.jsonl",gpe=/^batch-(\d{1,16})-[0-9a-f-]+\.jsonl$/;bZe=/\b([A-Z][A-Z0-9_]{1,})=("[^"\n]*"|'[^'\n]*'|[^\s"'`;,)\]}]+)/g,vZe=/(?:\/(?:[A-Za-z0-9._@~+-]|%[0-9A-Fa-f]{2})+){2,}/g});var no,P6,Nc=B(()=>{"use strict";no="1.0.268",P6=`linzumi ${no}`});import{closeSync as vpe,existsSync as I6,mkdirSync as CZe,openSync as xpe,readFileSync as wpe,renameSync as TZe,unlinkSync as Hp,writeFileSync as PZe,writeSync as Spe}from"node:fs";import{dirname as kpe,join as AZe}from"node:path";function R6(e){return e instanceof ml||e instanceof Error&&e.name===Tpe&&"lockPath"in e&&"heldBy"in e}function E6(e,n=gr(),t){let r=t===void 0?encodeURIComponent(e):Fp(t);return AZe(kpe(n),"runners",`${r}.lock`)}function dR(e){let n=E6(e.machineId,e.configPath,e.linzumiUrl),t=e.isPidAlive??Ope,r=e.now??(()=>new Date),o=e.killPid??zZe,i=r().toISOString(),a={version:1,machineId:e.machineId,runnerId:e.runnerId,pid:e.pid??process.pid,cwd:e.cwd,workspace:e.workspace,...e.linzumiUrl===void 0?{}:{linzumiUrl:Yt(e.linzumiUrl)},...e.launchSource===void 0?{}:{launchSource:e.launchSource},...e.processGroupLeader===!0?{processGroupLeader:!0}:{},startedAt:i,heartbeatAt:i,cliVersion:e.cliVersion??no,...e.gracefulUpdateDrain===!0?{gracefulUpdateDrain:!0}:{}};MZe(e.machineId,e.configPath,e.linzumiUrl,t,r,o,e.onTakeover),OZe(n,a,t,r,o,e.onTakeover,e.beforeReadExistingLock,e.beforeReplaceStaleLock);let s=()=>Ppe(n,a,r),d=setInterval(s,Cpe);return d.unref(),{path:n,record:a,heartbeat:s,release:()=>{clearInterval(d),Epe(n,a)}}}function Ppe(e,n,t){try{let r=lR(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`;PZe(i,`${JSON.stringify(o,null,2)}
|
|
1611
1611
|
`,"utf8"),TZe(i,e)}catch{}}function Zp(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>IZe?{state:"wedged",reason:e.heartbeatAt===void 0?"missing_heartbeat":"stale_heartbeat"}:{state:"live"}}function Ape(e,n,t,r){return t!==uR||e.launchSource!==uR?!1:r.state!=="live"?!0:RZe(n,e.cliVersion)>0}function RZe(e,n){let t=bpe(e),r=bpe(n);for(let o=0;o<3;o++){let i=t.core[o],a=r.core[o];if(i===void 0||a===void 0)throw new Error(`compareCliVersions: unexpected undefined at core index ${o}`);if(i!==a)return i>a?1:-1}return t.prerelease.length===0&&r.prerelease.length===0?0:t.prerelease.length===0?1:r.prerelease.length===0?-1:EZe(t.prerelease,r.prerelease)}function bpe(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("."),a=[A6(i[0]),A6(i[1]),A6(i[2])],s=o===""?[]:o.split(".").filter(d=>d!=="");return{core:a,prerelease:s}}function A6(e){let n=Number.parseInt(e??"",10);return Number.isInteger(n)&&n>=0?n:0}function EZe(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 a=Number.parseInt(o,10),s=Number.parseInt(i,10),d=a.toString()===o,u=s.toString()===i;if(d&&u){if(a!==s)return a>s?1:-1}else{if(d!==u)return d?-1:1;if(o!==i)return o>i?1:-1}}return 0}function Ipe(e,n,t,r,o){try{r(n.pid)}catch(i){let a=i!==null&&typeof i=="object"&&"code"in i?i.code:void 0;if(a!=="ESRCH")throw a==="EPERM"||a==="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 MZe(e,n,t,r,o,i,a){if(t===void 0||Ai(t)!==Ai(Ko))return;let s=E6(e,n),d=lR(s);if(d!==void 0){if(Zp(d,r,o).state==="live")throw new ml(s,d);Rpe(s,r,()=>{let u=I6(s)?M6(s):void 0;if(u===void 0)return;let c=Zp(u,r,o);if(c.state==="live")throw new ml(s,u);c.state==="wedged"&&Ipe(s,u,c.reason,i,a),Hp(s)})}}function OZe(e,n,t,r,o,i,a,s){if(sR(e,n))return;a?.();let d=lR(e);if(d===void 0){if(sR(e,n))return;throw new Error(`another Linzumi runner lock appeared while starting: ${e}`)}if(Zp(d,t,r).state==="live")throw new ml(e,d);s?.(),Rpe(e,t,()=>{let u=I6(e)?M6(e):void 0;if(u!==void 0){let c=Zp(u,t,r);if(c.state==="live")throw new ml(e,u);c.state==="wedged"&&Ipe(e,u,c.reason,o,i),Hp(e)}if(!sR(e,n))throw new Error(`another Linzumi runner lock appeared while starting: ${e}`)})}function sR(e,n){CZe(kpe(e),{recursive:!0});try{let t=xpe(e,"wx");try{Spe(t,`${JSON.stringify(n,null,2)}
|
|
1612
1612
|
`)}finally{vpe(t)}return!0}catch(t){if(qy(t,"EEXIST"))return!1;throw t}}function Rpe(e,n,t){let r=`${e}.replace`;for(;;)try{let o=xpe(r,"wx");try{Spe(o,`${process.pid}
|
|
1613
1613
|
`),t()}finally{vpe(o),Hp(r)}return}catch(o){if(qy(o,"EEXIST")){let i=DZe(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(`
|
|
@@ -2233,7 +2233,7 @@ Tools:
|
|
|
2233
2233
|
Auth:
|
|
2234
2234
|
Uses --token, LINZUMI_MCP_ACCESS_TOKEN, or cached local runner OAuth from linzumi auth.
|
|
2235
2235
|
Hosted personal agents use --delegation-auth-file with a signed delegation grant.
|
|
2236
|
-
`}async function s_n(e){let n=p5(e);if(n.get("help")===!0){process.stdout.write(xke());return}let t=h5(n,"api-url"),r=await f5({kandanUrl:t,explicitToken:Jt(n,"token")??process.env.LINZUMI_MCP_ACCESS_TOKEN,authFilePath:Jt(n,"auth-file"),delegationAuthFilePath:Jt(n,"delegation-auth-file"),workspaceSlug:Jt(n,"workspace"),channelSlug:Jt(n,"channel")}),o=Jt(n,"owner-username")??process.env.LINZUMI_MCP_OWNER_USERNAME,i=m5(Jt(n,"mode")),a=wke(Jt(n,"tool-scope")),s=Jt(n,"cwd")??process.cwd(),d=Jt(n,"thread-id")??process.env.LINZUMI_THREAD_RUNNER_KANDAN_THREAD_ID,u=n.get("agent-session")===!0?Jle(Jt(n,"auth-file")):void 0,c=Qd({kandanUrl:t,accessToken:r.accessToken,authMode:r.mode,operatingMode:i,topicWakeTurnCapability:u}),l=new ZM({name:"linzumi",version:"0.1.0"});__n(l),c_n(l,{client:c,toolScope:a,operatingMode:i,cwd:s,kandanUrl:t,defaultThreadId:d,ownerUsername:o,agentSession:n.get("agent-session")===!0,topicQuietAuthFilePath:u===void 0?void 0:Jt(n,"auth-file"),documentSurfaces:kb(r.accessToken),askUserQuestionTool:n.get("ask-user-question-tool")===!0,devServices:u_n(process.env),multiAgentJobs:n.get("multi-agent-jobs")===!0});let f=new XM;await l.connect(u===void 0?f:l_n(f,()=>c.recordTopicWakeToolAttempt(),Jt(n,"auth-file")))}var pke="One or two sentences a teammate skimming the board would want: what changed, and what happens next. Standup register, present tense, name agents and lanes plainly. No thread ids or UUIDs unless needed for lookup; proofs and evidence belong in the thread, not here. Good: 'Retired the silent watchdog and spawned Thorne to replace it \u2014 running lean at three children.' Bad: 'Broken 67f1d639 archived abandoned; board claim preceded spawn; children verified at exactly 3.'",d_n=new Intl.Segmenter("en",{granularity:"grapheme"}),mke=D.string().min(1).refine(e=>Array.from(d_n.segment(e)).length<=240,{message:"status_note over 240 chars \u2014 trim to what a reader needs; put evidence in the thread."});function u_n(e){let n=e.LINZUMI_DEV_SERVICES_SCOPE?.trim(),t=Number.parseInt(e.LINZUMI_DEV_SERVICES_OWNER_PID??"",10);if(!(n===void 0||n===""||!Number.isInteger(t)||t<=0))return{scopeDir:xc(n),ownerPid:t}}function l_n(e,n,t){let r=Promise.resolve(),o="accepting",i=new Map,a=()=>{if(o="closed_after_failure",console.warn("topic_quiet_tool_admission_refused"),t!==void 0)try{kw(t,"attempt_failed")}catch{console.warn("topic_quiet_fault_custody_unresolved")}},s={start:async()=>{e.onclose=()=>s.onclose?.(),e.onerror=d=>s.onerror?.(d),e.onmessage=(d,u)=>{if(o!=="accepting"){console.warn("topic_quiet_transport_closed_request_refused");return}if(!("method"in d)||d.method!=="tools/call"||!("id"in d)){s.onmessage?.(d,u);return}let c=qH(d.params??null);r=r.then(async()=>{if(o!=="accepting"){console.warn("topic_quiet_transport_queued_request_refused");return}try{if(c||(t!==void 0&&kw(t,"attempt_pending"),await n(),t!==void 0&&kw(t,"attempt_acknowledged")),s.onmessage===void 0)throw new Error("topic_quiet_transport_unbound");let l=new Promise((f,p)=>{i.set(d.id,{quietRequest:c,resolve:f,reject:p})});s.onmessage(d,u),await l}catch{i.delete(d.id),a();try{await e.send({jsonrpc:"2.0",id:d.id,result:{isError:!0,content:[{type:"text",text:"topic_quiet_tool_admission_refused"}]}})}finally{await e.close()}}}).catch(()=>{console.warn("topic_quiet_transport_response_failed"),s.onerror?.(new Error("topic_quiet_transport_response_failed"))})},await e.start()},send:async(d,u)=>{let c="id"in d&&d.id!==void 0&&("result"in d||"error"in d)?i.get(d.id):void 0,l=c!==void 0&&("error"in d||"result"in d&&O(d.result)?.isError===!0);c!==void 0&&(o=$H(c.quietRequest,l,yq("result"in d?O(d.result)?.structuredContent??null:null)),o==="closed_after_failure"&&a());try{await e.send(d,u),c?.resolve(),o!=="accepting"&&await e.close()}catch(f){throw c?.reject(f),f}finally{c!==void 0&&"id"in d&&d.id!==void 0&&i.delete(d.id)}},close:()=>e.close(),setProtocolVersion:d=>e.setProtocolVersion?.(d)};return s}function c_n(e,n){let{client:t,toolScope:r,operatingMode:o,cwd:i,kandanUrl:a,defaultThreadId:s,ownerUsername:d,agentSession:u,devServices:c}=n;u&&e.tool("linzumi_complete_topic_wake_no_action","Complete an authenticated conditional topic wake when its condition requires no action. Supply a clear reason. This posts no message, proposes no edit, and cannot conceal failed tools or attempted effects. Ordinary mentions and component batches are not eligible.",{reason:D.string().refine(MH,{message:"A nonblank reason of at most 2000 UTF-8 bytes is required."})},async f=>{let p=await t.completeTopicWakeNoAction({reason:f.reason});if(!yq(p))throw new Error("topic_quiet_server_receipt_invalid");return n.topicQuietAuthFilePath!==void 0&&kw(n.topicQuietAuthFilePath,"quiet_acknowledged"),He(p)});let l=r==="all"||r==="coding";if(n.askUserQuestionTool===!0&&e.tool(pee,`Ask the user up to ${Bv} structured multiple-choice questions and BLOCK until they answer in the Linzumi thread. Use this whenever you need a decision or clarification mid-task. Each question needs a short header (max ${Jv} chars) and ${Kv}-${Wv} options {label, description}; a built-in "${Hv}" free-text choice is always shown in addition to your options, so never add one yourself. Set multiSelect true to allow choosing several options. Returns {answers} keyed by question text: a single label string, an array of labels for multiSelect, and {"other": "<typed text>"} for a free-text reply.`,{questions:D.array(D.object({question:D.string().describe("The question to ask the user."),header:D.string().describe(`Short category header shown above the question (max ${Jv} chars, e.g. "Auth", "Scope").`),options:D.array(D.object({label:D.string().describe("Option label the user taps."),description:D.string().optional().describe("One-line explanation of the option.")})).describe(`${Kv}-${Wv} options for this question.`),multiSelect:D.boolean().optional().describe("True lets the user select several options; the answer becomes an array.")})).describe(`1-${Bv} questions to ask atomically.`)},async f=>w_n((p,h)=>e.server.elicitInput(p,h),f)),n.documentSurfaces===!0){let f=D.number().int().positive().optional().describe("Immutable admitted entry_id from the component wake batch. Required when the batch has multiple authorized contexts; never selects newer authority."),p=async(h,y)=>He(await t.agentDocumentTool({...y,tool:h}));e.tool("linzumi_lookup_documents","Search document titles and content within the controlling human's visibility ceiling. Returns authorized results in canonical search order; zero, one, and multiple matches carry the rule-03 ambiguity meaning.",{query:D.string().min(1).describe("Document title or content search query."),component_entry_id:f},async h=>p("lookup_documents",h)),e.tool("linzumi_read_document","Read one in-scope document as full AST and metadata, including pending proposals and required-agent-context comments. Both controlling-human visibility and agent delegation are required.",{document_id:D.string().uuid().describe("Document UUID."),component_entry_id:f},async h=>p("read_document",h)),u?(e.tool("linzumi_invoke_command","Invoke a registered command authorized by the current component wake context. Use the embedding document UUID, exact command name and typed inputs from that context, a stable idempotency key, and its admitted component_entry_id. Current permissions and the frozen per-entry authority are rechecked by the server; this tool grants no new authority.",{document_id:D.string().uuid().describe("Embedding document UUID."),command_name:D.string().min(1).describe("Exact registered command name authorized by this component context."),inputs:D.record(D.unknown()).describe("Typed inputs for the registered command."),idempotency_key:D.string().min(1).describe("Stable key for this logical command invocation; preserve it on replay."),component_entry_id:f},async h=>p("invoke_command",h)),e.tool("linzumi_append_document_section","Use this tool for append-shaped document requests: add or append a new section, or add or update a tracker row as new section content, including parent-delegated work. After resolving exactly one patch target document and reading it, call this tool in the same turn; do not merely reply with suggested prose. Other authorized context documents do not make the patch target ambiguous. Supply only the heading and body Markdown: the server composes the closed structural operations. Every change is proposal-always.",{document_id:D.string().uuid().describe("Document UUID."),heading:D.string().trim().min(1).describe("Section heading."),body_markdown:D.string().trim().min(1).describe("Section body as Markdown authored by the model."),component_entry_id:f},async h=>p("append_document_section",h)),e.tool("linzumi_replace_section","Use this tool for targeted section rewrites, fixes, and tightening. After resolving exactly one patch target document and reading it, identify the section by exact heading text or its heading block UUID and supply the replacement body Markdown. The server rejects missing and ambiguous headings with actionable typed errors and composes the closed structural operations. Every change is proposal-always.",{document_id:D.string().uuid().describe("Document UUID."),heading_or_section_ref:D.string().trim().min(1).describe("Exact heading text or heading block UUID from read_document."),body_markdown:D.string().trim().min(1).describe("Replacement section body as Markdown."),component_entry_id:f},async h=>p("replace_section",h)),e.tool("linzumi_annotate_document_section","Use this tool to add a durable note to one existing heading-delimited document section without rewriting its content. After resolving exactly one patch target document and reading it, identify the section by exact heading text or its heading block UUID and supply only the note Markdown. The server rejects missing and ambiguous headings, composes the anchored comment, and persists a proposal before any authorized auto-apply.",{document_id:D.string().uuid().describe("Document UUID."),heading_or_section_ref:D.string().trim().min(1).describe("Exact heading text or heading block UUID from read_document."),note_markdown:D.string().trim().min(1).describe("Durable section note as Markdown."),component_entry_id:f},async h=>p("annotate_document_section",h)),e.tool("linzumi_decline_document_action","Decline the current document action when no advertised document intent can express it. Give a clear reason; the server relays it verbatim with an honest decline prefix and satisfies the action binding.",{reason:D.string().refine(h=>h.trim().length>0,{message:"Reason must contain non-whitespace text."}).describe("Clear reason the available document intents cannot express the request.")},async h=>He(await t.declineDocumentAction({reason:h.reason})))):e.tool("linzumi_propose_document_patch","Submit a raw revisioned structural document patch. This power/API surface requires the caller to compose the closed operation vocabulary. Create a native data-bound table with the atomic create_bound_table operation containing bindingId, block, and binding; rows remain source data and must not be copied into the block. Every change is proposal-always.",{document_id:D.string().uuid().describe("Document UUID."),patch:D.object({baseRevision:D.number().int().nonnegative(),operations:D.array(D.record(D.unknown())),title:D.string().min(1).optional()}).describe("Revisioned structural document patch."),rationale:D.string().min(1).describe("Why this change is proposed."),component_entry_id:f},async h=>p("propose_document_patch",h)),u||e.tool("linzumi_create_document","Create an agent-attributed document through an atomic bootstrap proposal and apply transaction in the named folder or workspace default folder.",{title:D.string().min(1).describe("Document title."),initial_patch:D.record(D.unknown()).describe("Bootstrap structural patch."),folder_id:D.string().uuid().optional().describe("Destination folder UUID."),component_entry_id:f},async h=>p("create_document",h))}if(u){e.tool("linzumi_agent_reply","Post your single @linzumi reply for the current turn into the surface where you were mentioned. Call EXACTLY ONCE per turn with your final answer; the reply links to this working session automatically. Fails with already_replied on a second call and no_active_asker_binding when no turn is active.",{body:D.string().min(1).describe("Plain-text reply body to post."),tokens:Um.optional()},async p=>He(await t.agentReply({body:p.body,...p.tokens===void 0?{}:{tokens:p.tokens}})));let f=async(p,h)=>He(await t.agentTopicTool({...h,tool:p}));e.tool("linzumi_create_topic_wake_subscription","Create or update a standing subscription that wakes @linzumi when new entries land on an existing workspace topic. Use this when the user asks you to watch a topic and perform an ongoing job. The server stores the instruction, derives the creator from the current asker, and targets this conversation; do not claim success without calling this tool.",{topic_slug:D.string().min(1).describe("Existing workspace topic slug to watch."),instruction:D.string().min(1).max(4e3).describe("Standing job to execute whenever a matching topic entry wakes the agent.")},async p=>f("create_topic_wake_subscription",p)),e.tool("linzumi_disable_topic_wake_subscription","Disable the current asker's standing @linzumi wake subscription for a topic. The durable row and cursor are retained so reactivation can drain the disabled-period backlog.",{topic_slug:D.string().min(1).describe("Workspace topic slug whose standing wake should stop.")},async p=>f("disable_topic_wake_subscription",p)),e.tool("linzumi_list_coding_jobs","List the coding jobs the current asker can see in this workspace: runner connections (online and recent) with their bound job threads. Live state - never answered from search.",{},async()=>He(await t.agentListCodingJobs({}))),e.tool("linzumi_start_coding_job","Start a coding job exactly as if the asking user clicked start: same runner/channel authorization, same pipeline. Returns status 'unavailable' with a reason when the runner cannot take the job (relay that honestly).",{channel:D.string().describe("Channel slug to host the job thread."),runner_key:D.string().describe("Runner (computer) to run the job on."),cwd:D.string().describe("Working directory on the runner."),work_description:D.string().min(1).describe("What the job should do - the initial instruction."),model:D.string().optional().describe("Model override (optional)."),model_provider:D.string().optional().describe("Model provider override, e.g. 'wafer' (optional)."),execution_mode:D.enum(["raw","local_vm"]).optional().describe("Execution placement override (optional)."),project_task_id:D.string().optional().describe("Project task item to bind the job to (task_id from linzumi_get_project_tasks). The task flips todo -> active and links to the new job."),visibility:D.enum(["project","private"]).optional().describe("Job visibility. Defaults to 'project'; private jobs are limited to directly authorized participants.")},async p=>He(await t.agentStartCodingJob(p))),e.tool("linzumi_interrupt_coding_job","Interrupt a coding job: mode 'steer' (default) discards its queued follow-ups so your next message lands first; mode 'stop' terminates the current turn.",{channel:D.string().describe("Channel slug hosting the job thread."),thread_id:D.string().uuid().describe("The job thread UUID."),mode:D.enum(["steer","stop"]).optional().describe("Interrupt mode; defaults to 'steer'.")},async p=>He(await t.agentInterruptCodingJob(p))),e.tool("linzumi_send_coding_job_message","Message a coding job or a person. Queue is the encouraged default: it lands in the colleague's inbox for their own cadence. Steer only for urgent, potentially-clashing work because it interrupts the running turn. Would this be worthless or harmful after their turn finishes? If no, queue. Delivery urgency is not access control. To message a person, pass to_user and omit channel and thread_id: delivery lands in their personal inbox.",{channel:D.string().optional().describe("Channel slug hosting the job thread. Required unless to_user is set."),thread_id:D.string().uuid().optional().describe("The job thread UUID. Required unless to_user is set."),to_user:D.string().min(1).optional().describe("Username of a workspace member to message instead of a job. Delivery lands in their personal inbox."),body:D.string().min(1).describe("Message body to send."),tokens:Um.optional(),delivery:D.enum(["queue","steer"]).optional().describe("Delivery urgency. Defaults to 'queue'.")},async p=>He(await t.agentSendCodingJobMessage(p))),e.tool("linzumi_read_coding_job_thread","Read a coding job's thread (asker-visible history) plus its workflow status metadata.",{channel:D.string().describe("Channel slug hosting the job thread."),thread_id:D.string().uuid().describe("The job thread UUID."),limit:D.number().int().min(1).max(100).optional().describe("Maximum replies to return."),before_seq:D.number().int().positive().optional().describe("Return replies before this channel seq.")},async p=>He(await t.agentReadCodingJobThread(p))),e.tool("linzumi_resolve_job_approval","Resolve a coding job's pending approval request with the asking user's decision ('approve' or 'deny'). Only relays the asker's authority - never approve without their explicit instruction.",{channel:D.string().describe("Channel slug hosting the job thread."),thread_id:D.string().uuid().describe("The job thread UUID."),source_seq:D.number().int().positive().describe("Channel seq of the message the approval request rides on."),request_id:D.string().describe("The approval request id."),decision:D.enum(["approve","deny"]).describe("The asker's decision.")},async p=>He(await t.agentResolveJobApproval(p))),e.tool("linzumi_archive_coding_job","Archive a coding job's thread (or any thread the asking user owns) so it leaves the active list; history is preserved. Do this when the asker says to archive a job or thread - never just promise it.",{channel:D.string().describe("Channel slug hosting the thread."),thread_id:D.string().uuid().describe("The thread UUID to archive.")},async p=>He(await t.agentArchiveCodingJob(p))),e.tool("linzumi_unarchive_coding_job","Unarchive a previously archived coding job thread the asking user owns, returning it to the active list.",{channel:D.string().describe("Channel slug hosting the thread."),thread_id:D.string().uuid().describe("The thread UUID to unarchive.")},async p=>He(await t.agentUnarchiveCodingJob(p))),e.tool("linzumi_set_thread_status","Set a thread's lifecycle status as the asking user: 'closed' marks it done, 'open' reopens it. Works on threads the asker owns.",{channel:D.string().describe("Channel slug hosting the thread."),thread_id:D.string().uuid().describe("The thread UUID."),status:D.enum(["open","closed"]).describe("Replacement lifecycle status ('closed' = done).")},async p=>He(await t.agentSetThreadStatus(p))),e.tool("linzumi_create_channel","Create a new public channel in this workspace as the asking user. The slug is derived from the name.",{name:D.string().min(1).describe("Channel name to create.")},async p=>He(await t.agentCreateChannel(p))),e.tool("linzumi_rename_channel","Rename a channel's display name as the asking user. The channel's URL slug stays stable.",{channel:D.string().describe("Current channel slug to rename."),name:D.string().min(1).describe("New display name.")},async p=>He(await t.agentRenameChannel(p))),e.tool("linzumi_archive_channel","Archive a channel in this workspace as the asking user. History is preserved; the channel leaves the active sidebar.",{channel:D.string().describe("Channel slug to archive.")},async p=>He(await t.agentArchiveChannel(p))),e.tool("linzumi_unarchive_channel","Unarchive a previously archived channel as the asking user.",{channel:D.string().describe("Channel slug to unarchive.")},async p=>He(await t.agentUnarchiveChannel(p))),e.tool("linzumi_add_reaction","Add an emoji reaction to a channel message as the asking user. Accepts unicode emoji or a workspace :shortcode:.",{channel:D.string().describe("Channel slug containing the message."),message_seq:D.number().int().positive().describe("Channel seq of the message to react to."),emoji:D.string().min(1).describe("Emoji to add (unicode or :shortcode:).")},async p=>He(await t.agentAddReaction(p))),e.tool("linzumi_remove_reaction","Remove the asking user's emoji reaction from a channel message.",{channel:D.string().describe("Channel slug containing the message."),message_seq:D.number().int().positive().describe("Channel seq of the reacted message."),emoji:D.string().min(1).describe("Emoji to remove (unicode or :shortcode:).")},async p=>He(await t.agentRemoveReaction(p))),e.tool("linzumi_pin_message","Pin a channel message as the asking user. Thread replies re-point to their root message.",{channel:D.string().describe("Channel slug containing the message."),message_seq:D.number().int().positive().describe("Channel seq of the message to pin.")},async p=>He(await t.agentPinMessage(p))),e.tool("linzumi_unpin_message","Remove a pin from a channel message as the asking user.",{channel:D.string().describe("Channel slug containing the message."),message_seq:D.number().int().positive().describe("Channel seq of the pinned message.")},async p=>He(await t.agentUnpinMessage(p)))}r==="all"&&(e.tool("linzumi_get_message","Read one Linzumi message by scoped message_seq/message_id or a Linzumi message URL, with optional bounded before/after context.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),message_id:D.union([D.string(),D.number()]).optional().describe("Message seq inside the scoped channel."),message_seq:D.union([D.string(),D.number()]).optional().describe("Alias for message_id."),message_url:D.string().optional().describe("Full Linzumi message URL with #message-<seq>."),before:D.number().int().min(0).max(100).optional().describe("Number of visible messages before the target."),after:D.number().int().min(0).max(100).optional().describe("Number of visible messages after the target.")},async f=>He(await t.getMessage(f))),e.tool("linzumi_get_thread","Read one Linzumi thread by thread_id in the scoped channel, including the parent message and bounded replies.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:D.string().uuid().describe("Linzumi thread UUID."),limit:D.number().int().min(1).max(100).optional().describe("Maximum replies to return."),before_seq:D.number().int().positive().optional().describe("Return replies before this channel seq.")},async f=>He(await t.getThread(f))),e.tool("linzumi_get_thread_transcript","Read a Linzumi thread's full transcript as canonical IR nodes (user/assistant messages, command executions, file changes, tool calls, statuses), cursor-paginated over the complete history. Use the returned cursor with has_more to walk older pages.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:D.string().uuid().describe("Linzumi thread UUID."),limit:D.number().int().min(1).max(500).optional().describe("Maximum transcript nodes per page (default 200)."),cursor:D.number().int().positive().optional().describe("Return nodes below this seq (the previous page reply cursor).")},async f=>He(await t.getThreadTranscript(f))),e.tool("linzumi_get_channel","Read scoped Linzumi channel metadata and bounded recent channel messages.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),limit:D.number().int().min(1).max(100).optional().describe("Maximum messages to return."),before_seq:D.number().int().positive().optional().describe("Return messages before this channel seq.")},async f=>He(await t.getChannel(f))),e.tool("linzumi_search_workspace","Search the Linzumi workspace with hybrid lexical+semantic retrieval, scoped to what the authorizing user can access. Returns scored content chunks with provenance (channel, thread, authored time) and a permalink to cite.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),query:D.string().min(1).describe("Natural-language or keyword query to retrieve against."),limit:D.number().int().min(1).max(25).optional().describe("Maximum results to return (default 10, server-capped)."),source_types:D.array(D.enum(["message","coding_job","github_pr","github_pr_review","github_check_run","github_workflow_run","github_diff","dictation","file"])).optional().describe("Restrict results to these corpora; omit for all."),authored_after:D.string().optional().describe("ISO8601 instant; only content authored at or after this time."),authored_before:D.string().optional().describe("ISO8601 instant; only content authored at or before this time."),repo:D.string().optional().describe("Restrict GitHub-sourced results to one repository by full name (owner/name)."),check_status:D.enum(["pending","success","failed"]).optional().describe("Restrict check and workflow results to one conclusion bucket.")},async f=>He(await t.searchWorkspace(f))),e.tool("linzumi_ask_workspace",'Ask the Linzumi workspace a natural-language question and get a synthesized, citation-backed answer over what the authorizing user can access. Costs an LLM call on cache misses, so prefer linzumi_search_workspace for simple lookups. A "refused" status means there was not enough accessible evidence - treat it as "the workspace does not know", never retry verbatim.',{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),question:D.string().min(1).max(2e3).describe("Natural-language question to answer with citations."),channel:D.string().optional().describe("Optional channel slug providing conversational context; never widens access."),allow_cached:D.boolean().optional().describe("Allow serving a cached synthesis when the evidence set is unchanged (default true). Set false to force fresh synthesis.")},async f=>He(await t.askWorkspace(f))),e.tool("linzumi_about_me","Read what the authorizing user has told Linzumi about themselves: their profile facts (homes, unit preferences, and other self-maintained attributes) plus their derived current timezone. Use it to personalize answers (e.g. pick the right city for weather, use their preferred units). Predicates may have multiple active values; prefer the one consistent with the derived timezone.",{},async f=>He(await t.aboutMe(f)))),l&&(e.tool("linzumi_web_search","Search the public web for live or external information: news, current events, weather, prices, third-party API docs, research. Returns result titles, URLs, and snippets. Use this whenever the answer lives outside the Linzumi workspace; follow up with linzumi_fetch_url to read a result page.",{query:D.string().min(1).describe("Web search query (natural language or keywords)."),limit:D.number().int().min(1).max(10).optional().describe("Maximum results to return (default 8, server-capped).")},async f=>He(await t.webSearch(f))),e.tool("linzumi_fetch_url","Fetch one public http(s) URL and return its readable text content (HTML is reduced to plain text; large pages are truncated). Use it to read pages found via linzumi_web_search or any public docs/API reference. Only public addresses are reachable - private/internal hosts are rejected with url_not_allowed.",{url:D.string().min(1).describe("Absolute public http(s) URL to fetch.")},async f=>He(await t.fetchUrl(f)))),r==="all"&&(e.tool("linzumi_list_ui_targets","List every UI surface you can ask the user to open in their own Linzumi window (channels, DMs, threads, projects, coding jobs, computers, catch-up, activity, settings tabs, pane layouts) with the structured args each kind takes. Use UI control only when the user asks for help or asks to be shown something.",{},async()=>await bke(t.listUiTargets({}))),e.tool("linzumi_open_ui","Ask the user to open one whitelisted UI surface in their own already-open Linzumi window. A consent toast appears in THEIR session; navigation happens only if they tap Open. The call blocks until they decide and returns status opened/dismissed/expired - or error no_active_ui_session when they have no Linzumi window open (tell them to open Linzumi), or invalid_target with a detail. Use it only when the user asks for help or asks to be shown something; kinds and per-kind args come from linzumi_list_ui_targets.",{kind:D.string().min(1).describe("Target kind from linzumi_list_ui_targets (e.g. settings_workspace, channel, pane_layout)."),args:D.record(D.unknown()).optional().describe("Structured per-kind args from linzumi_list_ui_targets (never a URL - the server computes every path)."),workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async f=>await bke(t.openUi(Cd(f,s))))),l&&(e.registerTool("linzumi_schedule_wake",{description:'Schedule this coding job to wake itself once and start an ordinary visible turn with the supplied prompt. Provide exactly one of fire_at or delay_minutes. Good: delay_minutes=20, prompt="Check CI, address any failures, then update the plan." Bad: prompt="wake up" (it gives the future turn no actionable context).',inputSchema:D.object({fire_at:D.string().datetime({offset:!0}).optional().describe("Future ISO8601 timestamp with timezone."),delay_minutes:D.number().int().min(1).max(525600).optional().describe("Minutes from now before the one-time wake fires."),prompt:D.string().min(1).max(4e3).describe("Actionable human-register description of exactly what to do when this job wakes.")}).refine(f=>f.fire_at===void 0!=(f.delay_minutes===void 0),{message:"provide exactly one of fire_at or delay_minutes"})},async f=>He(await t.scheduleWake(f))),e.tool("linzumi_cancel_wake","Cancel one still-scheduled wake owned by this coding job. Fired, already-canceled, missing, or another job's wake fails loudly.",{wake_id:D.string().uuid().describe("Wake id returned by linzumi_schedule_wake.")},async f=>He(await t.cancelWake(f))),e.tool("linzumi_get_coding_job_metadata","Read the active coding job workflow metadata for a thread, including the agent-owned goal, ordered plan steps, step lock versions, and workflow status.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:D.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread.")},async f=>He(await t.getCodingJobMetadata(Cd(f,s)))),e.tool("linzumi_rename_coding_job","Update the current coding job thread title and workflow-facing title. Use this when the job scope changes materially so the Linzumi thread list and metadata overview stay accurate.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:D.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),title:D.string().min(1).max(100).describe("Concise user-visible title for this coding job.")},async f=>He(await t.renameCodingJob(Cd(f,s)))),e.tool("linzumi_upsert_coding_job_plan","Set or update the current coding job goal. Use this at job start and whenever the goal changes materially.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:D.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),goal:D.string().min(1).max(1e4).describe("Concrete user-visible goal for this coding job."),snooze_reason:D.string().min(1).max(500).optional().describe('Declare a legitimate wait to pause liveness nudges: what you are waiting on, in plain words a teammate would understand. Good: "waiting on CI for PR #4633". Must be sent together with snooze_minutes.'),snooze_minutes:D.number().int().min(1).max(1440).optional().describe("How many minutes until the wait should be rechecked (1-1440). The deadline is mandatory - open-ended waits are refused. Must be sent together with snooze_reason.")},async f=>He(await t.upsertCodingJobPlan(Cd(f,s)))),e.tool("linzumi_replace_coding_job_plan_steps","Replace the ordered coding job plan steps. Use this for the initial plan and for substantial rewrites when the old plan no longer fits the work.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:D.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),goal:D.string().min(1).max(1e4).optional().describe("Required when no plan exists yet; updates the current coding job goal."),steps:D.array(D.object({title:D.string().min(1).max(255),description:D.string().min(1).max(1e4),status:D.enum(["pending","active","completed","blocked","canceled"]),status_note:mke.optional().describe(pke),completed_debrief:D.string().min(1).max(2e4).optional().describe("Required for completed steps. A short paragraph of plain prose for a teammate: what was done, and how we know it worked. Same voice as the note, just more room. Never a compliance recital. Put evidence and verification here.")})).min(1).max(50).describe("Ordered user-visible plan steps. Completed steps must include completed_debrief.")},async f=>He(await t.replaceCodingJobPlanSteps(Cd(f,s)))),e.tool("linzumi_update_coding_job_plan_step","Update one coding job plan step status or note. Read metadata first and pass the current step lock_version.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:D.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),step_id:D.string().uuid().describe("Step id returned by linzumi_get_coding_job_metadata."),lock_version:D.number().int().positive().describe("Current step lock_version from metadata."),status:D.enum(["pending","active","completed","blocked","canceled"]),status_note:mke.optional().describe(pke),completed_debrief:D.string().min(1).max(2e4).optional().describe("Required when marking a step completed. A short paragraph of plain prose for a teammate: what was done, and how we know it worked. Same voice as the note, just more room. Never a compliance recital. Put evidence and verification here.")},async f=>He(await t.updateCodingJobPlanStep(Cd(f,s)))),e.tool("linzumi_link_coding_job_pull_request","Link the active coding job to its primary GitHub pull request so PR comments, files, commits, checks, deployments, and reviews can flow into the metadata view.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:D.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),github_repo_owner:D.string().min(1).max(255),github_repo_name:D.string().min(1).max(255),github_pr_number:D.number().int().positive(),github_pr_url:D.string().url(),title:D.string().min(1).max(255),body:D.string().min(1).max(1e5).optional(),head_branch:D.string().min(1).max(255),head_sha:D.string().min(7).max(64),base_branch:D.string().min(1).max(255),base_sha:D.string().min(7).max(64),state:D.enum(["draft","open","closed","merged"]).optional(),is_draft:D.boolean().optional(),review_status:D.enum(["unknown","review_required","approved","changes_requested"]).optional(),source_remote_url:D.string().min(1).max(1e3).describe("Git remote URL for the local job worktree; required when this job has no repo workspace yet."),runtime_worktree_root:D.string().min(1).max(1e3).describe("Absolute local worktree path for the coding job; required when this job has no repo workspace yet."),dirty_status:D.enum(["unknown","clean","dirty"]).optional(),dirty_summary:D.string().min(1).max(2e3).optional()},async f=>He(await t.linkCodingJobPullRequest(Cd(f,s)))),e.tool("linzumi_upload_files",["Upload local files to Linzumi and attach them to a new, exact, or latest assistant message. Use silently; do not mention this tool in the visible reply.","The JSON result includes message.attachments[].url as an absolute URL. Use those returned URLs when writing rich media directives such as ::audio, ::video, ::image, or Markdown images. Do not guess attachment URLs before upload.","For a message that should both attach files and show inline rich media, use a two-step flow: first upload/attach the files to create or target the message, then edit the same target message with body text that references the returned absolute URLs. When the result has target_seq, use target.kind=message_seq and message_seq=target_seq for that follow-up edit; result.message is the edit event that carries the new attachments, and target_message is the original target."].join(" "),{target:D.object({kind:D.enum(["new_message","message_seq","latest_assistant_message"]).describe("new_message creates a message; message_seq edits an exact message; latest_assistant_message edits the latest assistant message in the scoped thread/channel."),message_seq:D.union([D.string(),D.number()]).optional().describe("Required when kind is message_seq."),thread_id:D.string().optional().describe("Thread UUID. Defaults to the active Linzumi thread when the MCP server was launched with one.")}).describe("Attachment target. Prefer latest_assistant_message to attach files to the reply you already posted; use new_message ONLY when no assistant message exists yet in the scoped thread. Never re-use your visible reply text as a new_message body - that posts the reply twice. To reference uploaded files in the message body, upload first, then edit message_seq/latest_assistant_message with the returned absolute attachment URLs. If the upload result includes target_seq, use message_seq=target_seq for that follow-up edit."),files:D.array(D.string().min(1)).min(1).max(16).describe("Local file paths to upload. Paths must be non-hidden files inside the approved workspace or Downloads; source/text files of any language are supported, plus common document, image, patch, archive, and video types."),body:D.string().min(1).max(2e4).optional().describe("Required for new_message: a SHORT file-share caption (for example: Attached the generated report), never a copy of your visible reply - that would post the reply twice. Optional replacement body for message_seq/latest_assistant_message; when omitted, the existing message body is preserved. Rich media directives in body must use Linzumi attachment download URLs returned by this tool."),workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug. Omit to use the target thread's channel (when the thread is known) or the authenticated token scope.")},async f=>{let p=gke(f.target,s);try{let h=await m_n({client:t,cwd:i,kandanUrl:a,target:p,files:f.files,workspace:f.workspace,channel:f.channel,body:f.body});return He(yke(a,h))}catch(h){throw p_n(h)}}),e.tool("linzumi_edit_message","Edit an exact scoped Linzumi message by message_seq. Use after linzumi_upload_files when you need a body-only follow-up edit that embeds returned attachment URLs. Requires channel.write, and thread.write when target.thread_id is set. Rich media src/poster values must be Linzumi attachment download URLs.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),target:D.object({message_seq:D.union([D.string(),D.number()]).describe("Exact message seq to edit. After linzumi_upload_files returns target_seq, pass that value here."),thread_id:D.string().optional().describe("Thread UUID when editing a thread message. Use the upload result target_message.thread_id when present.")}).describe("Exact message target for the body edit."),body:D.string().min(1).max(2e4).describe("Replacement Markdown body. Rich media src/poster values must be Linzumi attachment download URLs returned by linzumi_upload_files.")},async f=>He(yke(a,await t.editMessage({...f,target:gke(f.target,s)}))))),r==="all"&&(e.tool("linzumi_list_vault_secrets","List vault secret names, descriptions, and whether each secret is personal or workspace-owned. Does not return secret values.",{},async f=>He(await t.listVaultSecrets(f))),e.tool("linzumi_list_projects","List the projects in the current workspace with their project_id (needed by the other project task tools), slug, title, description, and state.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async f=>He(await t.listProjects(f))),e.tool("linzumi_get_project_tasks",`Read a project's full task graph: task GROUPS (kind "group", organizational containers, exactly one level deep) and ISSUES (kind "issue", the executable work items), each with status (todo/active/blocked/review/done/canceled), DERIVED work_state readiness (ready = todo with every dependency satisfied; blocked = todo with unsatisfied dependencies; running/stalled = active with/without a connected job), parent group, assignee, lock_version, and dependency edges (depends_on_task_ids / unblocks_task_ids). Always read this before reorganizing. Inside a project-bound coding job the project is inferred automatically; otherwise pass project_id from linzumi_list_projects.`,{project_id:D.string().optional().describe("Project id from linzumi_list_projects. Omit inside a coding job started from a project to use that project.")},async f=>He(await t.getProjectTasks(Cd(f,s)))),e.tool("linzumi_create_project_task",'Create a task group (kind "group") or issue (kind "issue", the default) in a project. Groups organize issues and are exactly one level deep: a parent_id must name a GROUP, and groups themselves can never have a parent. New tasks default to status "todo" and append to the end unless position is given. Inside a project-bound coding job the project is inferred; otherwise pass project_id.',{project_id:D.string().optional().describe("Project id from linzumi_list_projects. Omit inside a coding job started from a project to use that project."),title:D.string().min(1).describe("Task title."),kind:D.enum(["issue","group"]).optional().describe('What to create: "issue" (executable work item, default) or "group" (organizational container).'),description:D.string().optional().describe("Detailed description of the work - written so an engineer (or coding agent) could execute the task from it."),status:D.enum(["todo","active","blocked","review","done","canceled"]).optional().describe('Initial status. Defaults to "todo".'),parent_id:D.string().optional().describe("task_id of the GROUP to place an issue in. Only issues can have a parent."),assignee:D.string().optional().describe("Username of a workspace member to assign."),position:D.number().int().min(0).optional().describe("Sort position. Defaults to appending at the end.")},async f=>He(await t.createProjectTask(Cd(f,s)))),e.tool("linzumi_update_project_task",'Update a task group or issue: retitle, edit description/status_note, transition status (todo/active/blocked/review/done/canceled), reassign, reorder (position), or reorganize (parent_id moves an issue into a group; clear_parent moves it to top level). Only the fields you pass change; description and status_note accept null to clear. Prefer updating existing tasks over delete-and-recreate. Pass the lock_version from your last read to fail loudly ("stale") instead of overwriting a concurrent edit.',{task_id:D.string().describe("task_id of the group or issue to update."),title:D.string().min(1).optional().describe("New title."),description:D.string().nullable().optional().describe("New description. Pass null to clear it."),status:D.enum(["todo","active","blocked","review","done","canceled"]).optional().describe('New status. "done"/"canceled" satisfy dependent tasks; "blocked" is a manual hold.'),status_note:D.string().nullable().optional().describe("Short human-readable note about the current status. Pass null to clear it."),position:D.number().int().min(0).optional().describe("New sort position among siblings."),parent_id:D.string().optional().describe("task_id of the GROUP to move this issue into. Do not combine with clear_parent."),clear_parent:D.boolean().optional().describe("true moves the issue to the top level (no group). Do not combine with parent_id."),assignee:D.string().optional().describe("Username of a workspace member to assign. Do not combine with clear_assignee."),clear_assignee:D.boolean().optional().describe("true removes the assignee. Do not combine with assignee."),lock_version:D.number().int().positive().optional().describe("The task's lock_version from your last read, for compare-and-swap safety.")},async f=>He(await t.updateProjectTask(f))),e.tool("linzumi_delete_project_task",`Permanently delete a task group or issue. Dependency edges on the task are removed with it (dependents may become ready). Deletion is normally the USER's call - prefer status "canceled" or an update unless you are certain the entry is obsolete.`,{task_id:D.string().describe("task_id of the group or issue to delete.")},async f=>He(await t.deleteProjectTask(f))),e.tool("linzumi_add_project_task_dependency",'Add the dependency edge "task_id is blocked by depends_on_task_id" between two ISSUES in the same project (groups cannot have dependencies). The dependent stays blocked until the prerequisite reaches done or canceled. The graph must stay acyclic: an edge that would create a cycle is refused with reason "would_create_cycle" and the offending cycle_path so you can restructure. Duplicate and self edges are rejected.',{task_id:D.string().describe("task_id of the DEPENDENT issue (the one that must wait)."),depends_on_task_id:D.string().describe("task_id of the PREREQUISITE issue (the one that must finish first).")},async f=>He(await t.addProjectTaskDependency(f))),e.tool("linzumi_remove_project_task_dependency",'Remove the dependency edge "task_id is blocked by depends_on_task_id". The dependent issue may become ready if that was its last unsatisfied dependency.',{task_id:D.string().describe("task_id of the DEPENDENT issue."),depends_on_task_id:D.string().describe("task_id of the PREREQUISITE issue the edge points at.")},async f=>He(await t.removeProjectTaskDependency(f))),e.tool("linzumi_get_call_transcript","Read the full transcript of a completed Linzumi notetaker call: call metadata (title, platform, started/ended/transcribed times), participants, and every spoken segment in order with speaker names and millisecond offsets. Pass the call_id embedded in the request (or copied from the call card). Errors: call_not_found (missing or not visible to you), call_transcript_not_ready (call still connecting, in progress, or transcribing - retry later).",{call_id:D.string().describe("The call id from the call card or the launching message (a CallRecording id - the opaque GraphQL id and the bare uuid both work).")},async f=>He(await t.getCallTranscript(f))),u||(e.tool("linzumi_start_coding_job","Start a coding job as the invoking user (same authorization and pipeline as clicking start). To start a project task item, pass project_task_id so the task flips todo -> active and links to the new job. Only start tasks whose work_state is ready. Proceed when the user has already explicitly authorized this launch within the agreed scope; DAG bookkeeping does not require renewed approval. Otherwise, offer and wait for explicit acceptance. Do not duplicate existing active work or treat task readiness as launch authorization. Omit channel, runner_key, and cwd to reuse this job's own channel, computer, and folder. Returns status 'unavailable' with a reason when the runner cannot take the job (relay that honestly).",{work_description:D.string().min(1).describe("What the job should do - the initial instruction. For a task item, write it from the task title and description."),project_task_id:D.string().optional().describe("Project task item to bind the job to (task_id from linzumi_get_project_tasks). The task flips todo -> active and links to the new job."),visibility:D.enum(["project","private"]).optional().describe("Child-job visibility. Defaults to 'project'; private jobs are limited to directly authorized participants."),channel:D.string().optional().describe("Channel slug to host the job thread. Omit to use this job's own channel."),runner_key:D.string().optional().describe("Runner (computer) to run the job on. Omit to use this job's own computer."),cwd:D.string().optional().describe("Working directory on the runner. Omit to use this job's own folder."),model:D.string().optional().describe("Model override (optional)."),model_provider:D.string().optional().describe("Model provider override, e.g. 'wafer' (optional)."),agent_provider:D.string().optional().describe("Agent provider override, e.g. 'codex' (optional)."),reasoning_effort:D.enum(["default","low","medium","high","xhigh","ultra"]).optional().describe("Reasoning effort override (optional)."),approval_policy:D.enum(["default","on-request","on-failure","never"]).optional().describe("Approval policy override (optional)."),sandbox:D.enum(["default","workspace-write","read-only","danger-full-access"]).optional().describe("Sandbox override (optional)."),fast:D.boolean().optional().describe("Fast-mode override (optional)."),allow_port_forwarding_by_default:D.boolean().optional().describe("Default port-forwarding override (optional)."),execution_mode:D.enum(["raw","local_vm"]).optional().describe("Execution placement override (optional)."),egress_mode:D.enum(["open","hardened"]).optional().describe("Local-VM egress override (optional).")},async f=>He(await t.agentStartCodingJob(Cd(f,s)))),n.multiAgentJobs===!0&&(e.tool("linzumi_spawn_child_job","Spawn a durable child coding job under YOUR OWN job, on any harness or model - plan a DAG and delegate its legs to workers you then coordinate through discovery and messaging. The child lands on this job's channel, computer, and folder; it inherits this job's project and visibility (a private parent's children stay private), human roles cascade to it, and a human manages its lifecycle. Returns status 'unavailable' with a reason when the runner cannot take the job (relay that honestly).",{work_description:D.string().min(1).describe("What the child job should do - the initial instruction, written to stand alone."),agent_provider:D.string().optional().describe("Harness for the child, e.g. 'codex' or 'claude-code'. Omit to reuse this job's own harness. A different harness is fine: a cross-harness child is always a child job."),model:D.string().optional().describe("Model override for the child (optional)."),model_provider:D.string().optional().describe("Model provider override, e.g. 'wafer' (optional)."),reasoning_effort:D.enum(["default","low","medium","high","xhigh","ultra"]).optional().describe("Reasoning effort override (optional)."),project_task_id:D.string().optional().describe("Project task item to bind the child to (task_id from linzumi_get_project_tasks). The task flips todo -> active and links to the new job."),visibility:D.enum(["project","private"]).optional().describe("Child visibility. Defaults to this job's own visibility; a private parent's children must stay private.")},async f=>He(await t.agentSpawnChildJob(Cd(f,s)))),e.tool("linzumi_archive_child_job","Archive a coding job that is YOUR OWN job or one beneath it in your job tree, retiring it from the active lists, the org map and the needs-you deck; history is preserved and it can be unarchived. Use this to clean up child jobs you spawned that are finished or dead - do it in the current turn, never just promise it. Refused for sibling, parent or unrelated jobs, and for jobs that do not belong to the human you are working for. When the job still has live descendants the call returns confirmation_required with their exact count and ids; call again with descendant_action 'keep' (archive only this job, re-parenting its children) or 'cascade' (archive the whole subtree) plus those expected values.",{job_id:D.string().describe("The coding job id to archive: your own job, or any job beneath it in your tree."),outcome:D.enum(["completed","abandoned","superseded"]).describe("Why the job is being archived."),descendant_action:D.enum(["keep","cascade"]).optional().describe("Phase-2 choice when the job has live descendants. 'keep' archives only this job and re-parents its children; 'cascade' archives the whole subtree."),expected_descendant_count:D.number().int().optional().describe("The descendant_count returned by the phase-1 call."),expected_descendant_job_ids:D.array(D.string()).optional().describe("The descendant_job_ids returned by the phase-1 call; the call is refused if the subtree changed."),expected_descendant_fingerprint:D.string().optional().describe("The descendant_fingerprint returned by the phase-1 call.")},async f=>He(await t.agentArchiveChildJob(f))),e.tool("linzumi_unarchive_child_job","Unarchive a previously archived coding job that is YOUR OWN job or one beneath it in your job tree. It returns as hibernating and wakes when messaged. Same ownership scope as linzumi_archive_child_job. Refused when the job is not archived, or when its home thread already holds a live job.",{job_id:D.string().describe("The archived coding job id to bring back: your own job, or any job beneath it in your tree.")},async f=>He(await t.agentUnarchiveChildJob(f))),e.tool("linzumi_discover_coding_jobs","Search current sitreps inside this coding job project for overlapping files, modules, objectives, or blockers. Results include durable job addresses for coordination. Private jobs outside your visible set never appear.",{query:D.string().min(1).describe("Free-text clash-surface query, such as a file path, module, migration, or objective.")},async f=>He(await t.agentDiscoverCodingJobs({...f,source_thread_id:s}))),e.tool("linzumi_send_coding_job_message","Message a visible coding job in this project, or a person. Queue is the encouraged default: it lands in the colleague's inbox for their own cadence. Steer only for urgent, potentially-clashing work because it interrupts the running turn. Would this be worthless or harmful after their turn finishes? If no, queue. Delivery urgency is not access control. To message a person, pass to_user and omit channel and thread_id: delivery lands in their personal inbox.",{channel:D.string().optional().describe("Channel slug hosting the target job. Required unless to_user is set."),thread_id:D.string().uuid().optional().describe("Target job thread UUID. Required unless to_user is set."),to_user:D.string().min(1).optional().describe("Username of a workspace member to message instead of a job. Delivery lands in their personal inbox."),body:D.string().min(1).describe("Coordination message to send."),tokens:Um.optional(),delivery:D.enum(["queue","steer"]).optional().describe("Delivery urgency. Defaults to 'queue'.")},async f=>He(await t.agentSendCodingJobMessage({...f,source_thread_id:s})))))),r_n(r)&&(e.tool("linzumi_upload_custom_emoji","Upload a local image as a workspace custom emoji. For generated emoji art, create a transparent PNG with a simple centered subject, crisp edges, strong contrast, minimal tiny details, and enough outline/highlight separation to read at 16-24px on both dark and light backgrounds. Use lowercase shortcode names without colons unless preserving a user-provided :name:.",{name:fke.describe("Custom emoji shortcode name, with or without surrounding colons."),file:D.string().min(1).describe("Local PNG/WebP/GIF/JPEG file path to upload. Prefer transparent PNG for generated emoji."),workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async f=>He(await h_n({client:t,cwd:i,kandanUrl:a,name:f.name,file:f.file,workspace:f.workspace}))),e.tool("linzumi_rename_custom_emoji","Rename an existing workspace custom emoji. The new name may include surrounding colons; Linzumi stores the normalized shortcode without colons.",{emoji_id:D.union([D.string(),D.number().int().positive()]).describe("Workspace custom emoji id returned by linzumi_upload_custom_emoji or workspace emoji listings."),name:fke.describe("New shortcode name, with or without surrounding colons."),workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async f=>He(await t.renameCustomEmoji(f)))),e.tool("linzumi_media_guide","Return the full Linzumi rich-media authoring guide (audio/video/image directives, URL rules, upload-then-embed flow, examples). Call once BEFORE writing any ::audio/::video/::image directive or Markdown image into a Linzumi message.",{},async()=>({content:[{type:"text",text:NC}]})),e.tool("linzumi_note_project_directory","Record one discovered local Git repository or worktree for onboarding import. Call once per project as soon as it is found.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),runner_id:D.string().min(1).describe("Local runner/computer id provided in the discovery prompt."),path:D.string().min(1).describe("Absolute local path to the repository worktree root."),display_name:D.string().optional().describe("Short project label. Defaults to the path basename."),activity_at:D.string().optional().describe("Best-known recent activity time as an ISO-8601 timestamp."),import_key:D.string().optional().describe("Stable dedupe key. Defaults to path."),metadata:D.record(D.unknown()).optional().describe("Small structured metadata such as branch or remote origin.")},async f=>He(await t.noteProjectDirectory(f))),e.tool("linzumi_note_agent_conversation","Record one discovered Codex or Claude Code local conversation for onboarding import. Call once per conversation as soon as it is found.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),runner_id:D.string().min(1).describe("Local runner/computer id provided in the discovery prompt."),source:D.enum(["codex","claude_code"]).describe("Conversation source."),import_key:D.string().min(1).describe("Stable dedupe key, such as a session id or file path."),path:D.string().optional().describe("Absolute local path to the conversation file or directory."),display_name:D.string().optional().describe("Short label for the discovered conversation."),activity_at:D.string().optional().describe("Best-known recent activity time as an ISO-8601 timestamp."),metadata:D.record(D.unknown()).optional().describe("Small structured metadata such as session id or project path.")},async f=>He(await t.noteAgentConversation(f))),e.tool("linzumi_note_onboarding_discovery_status","Record onboarding discovery progress. Call when a search phase starts, checks another place, completes, or fails.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),runner_id:D.string().min(1).describe("Local runner/computer id provided in the discovery prompt."),phase:D.enum(["projects","conversations"]).describe("Discovery phase being reported."),status:D.enum(["starting","running","completed","failed"]).describe("Current phase status."),places_searched:D.number().int().nonnegative().optional().describe("Count of concrete folders/files/known locations checked so far."),message:D.string().optional().describe("Short user-facing status note."),current_place:D.string().optional().describe("Current folder, file, Git command target, or known location being checked."),current_source:D.string().optional().describe("Short machine-readable source label such as git, codex, or claude_code."),last_error:D.string().optional().describe("Short failure detail when status is failed."),metadata:D.record(D.unknown()).optional().describe("Small structured status metadata.")},async f=>He(await t.noteOnboardingDiscoveryStatus(f))),r==="all"&&o_n(o)&&(e.tool("linzumi_dm_owner","Send a plain-text DM to the configured Commander owner. Requires dm.write and a visible owner username.",{owner_username:D.string().optional().describe("Owner username. Defaults to LINZUMI_MCP_OWNER_USERNAME or --owner-username."),workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Source channel slug used to verify owner visibility."),body:D.string().min(1).max(2e4).describe("Plain-text message body to DM."),tokens:Um.optional()},async f=>{let p=f.owner_username??d;if(p===void 0)throw new Error("owner_username is required for linzumi_dm_owner");return He(await t.dmOwner({...f,owner_username:p}))}),e.tool("linzumi_send_channel_message","Post a NEW standalone Markdown message into the scoped Linzumi channel as the authenticated local-runner user. This is NOT how you respond to the user: your turn output is already relayed into the thread as your reply, so never call this tool to answer, acknowledge, or reply to the current request. Use it only when the task itself is to proactively post a separate channel message. Requires channel.write. Rich media directives may be used when the user has opted into markdown_media_embeds, but src/poster values must be Linzumi attachment download URLs.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),body:D.string().min(1).max(2e4).describe("Markdown message body to post. Rich media src/poster values must be Linzumi attachment download URLs, not third-party URLs, /relative paths, or local filesystem paths."),tokens:Um.optional()},async f=>He(await t.sendChannelMessage(f))),e.tool("linzumi_send_thread_reply","Post a Markdown reply into some OTHER existing Linzumi thread as the authenticated local-runner user. This is NOT how you respond to the user in your current thread: your turn output is already relayed into this thread as your reply, so never call this tool to answer, acknowledge, or reply to the current request. Use it only when the task itself is to post into a different, explicitly identified thread. Requires thread.write. Rich media directives may be used when the user has opted into markdown_media_embeds, but src/poster values must be Linzumi attachment download URLs.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:D.string().uuid().describe("Existing Linzumi thread UUID."),body:D.string().min(1).max(2e4).describe("Markdown reply body to post. Rich media src/poster values must be Linzumi attachment download URLs, not third-party URLs, /relative paths, or local filesystem paths."),tokens:Um.optional()},async f=>He(await t.sendThreadReply(f))),e.tool("linzumi_send_dm","Send a plain-text DM as the authenticated local-runner user to a visible user in the scoped workspace/channel. Requires dm.write.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Source channel slug used to verify target visibility."),username:D.string().describe("Visible Linzumi username to DM."),body:D.string().min(1).max(2e4).describe("Plain-text message body to DM."),tokens:Um.optional()},async f=>He(await t.sendDm(f)))),r==="all"&&e.tool("linzumi_get_vault_values","Request values for explicit vault env var names after a thread-scoped human approval. Requires vault.read; thread_id resolves the approval thread.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug used to disambiguate the approval thread when needed."),thread_id:D.string().uuid().describe("Existing Linzumi thread UUID for the inline approval."),env_var_names:D.array(D.string().regex(/^[A-Z][A-Z0-9_]{0,127}$/)).min(1).max(20).describe("Explicit vault env var names to request. This tool cannot list all vault keys."),description:D.string().min(1).max(500).describe("Human-readable reason shown in the approval request."),justification:D.string().min(10).max(1e3).describe("Agent justification shown to the approver.")},async f=>He(await t.getVaultValues(f))),r==="all"&&!u&&c!==void 0&&f_n(e,i,c)}function hke(e){return{name:e.record.name,command:e.record.command,cwd:e.record.cwd,ports:[...e.record.ports],restart_on_branch_change:e.record.restartOnBranchChange,desired_state:e.record.desiredState,liveness:e.liveness,port_health:e.portProbes.map(n=>({port:n.port,listening:n.listening})),started_at_ms:e.record.startedAtMs??null,last_exit:e.lastExit===void 0?null:{code:e.lastExit.code,signal:e.lastExit.signal,at_ms:e.lastExit.atMs},log_path:e.record.logPath,failure:e.failure===void 0?null:{reason:e.failure.reason,at_ms:e.failure.atMs}}}function f_n(e,n,t){e.tool("linzumi_dev_service_start","Start a long-running local dev server (npm run dev, storybook, docker compose up, ...) as a MANAGED SERVICE owned by the Linzumi runner. Use this instead of running dev servers in your own shell: a managed service survives the end of your turn and branch switches, is auto-restarted if it crashes, and its declared ports are health-probed and surfaced in the product. Calling start for an existing name declaratively RESTARTS it (e.g. after a checkout). Declare EVERY port the app serves from (primary plus HMR/asset/bundle sibling ports).",{name:D.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/).describe("Stable service name (slug), e.g. 'web' or 'storybook'. Reusing a name restarts that service."),command:D.string().min(1).describe("Shell command that runs the server in the foreground (never daemonize/screen/nohup it yourself), e.g. 'npm run dev'. Runs via the user's login shell."),cwd:D.string().optional().describe("Working directory for the service. Defaults to the session cwd."),ports:D.array(D.number().int().min(1).max(65535)).max(16).default([]).describe("Every TCP port this service listens on (primary AND related ports such as the Vite/HMR bundle port). Used for health probes and product visibility."),restart_on_branch_change:D.boolean().optional().describe("Restart the service automatically when the git branch of its cwd changes (for servers that go stale across checkouts)."),wait_for_ports_ms:D.number().int().min(0).max(6e4).optional().describe("How long to wait for the declared ports to accept connections before returning (default 15000).")},async r=>{let o=await uP({scopeDir:t.scopeDir,definition:{name:r.name,command:r.command,cwd:r.cwd??n,ports:r.ports,restartOnBranchChange:r.restart_on_branch_change===!0},ownerPid:t.ownerPid});if(!o.ok)return He({ok:!1,error:o.error});let i=Date.now()+(r.wait_for_ports_ms??15e3),a=o.record.ports.length===0;for(;!a&&Date.now()<i;)a=(await Promise.all(o.record.ports.map(c=>Z$(c)))).every(c=>c),a||await new Promise(c=>setTimeout(c,250));let d=(await cx(t.scopeDir)).find(u=>u.record.name===o.record.name);return He({ok:!0,service:d===void 0?{name:o.record.name}:hke(d),...d!==void 0&&d.liveness!=="running"?{hint:"The service is not (fully) serving its declared ports yet. Check linzumi_dev_service_logs before assuming it works."}:{}})}),e.tool("linzumi_dev_service_stop","Stop a managed dev service (SIGTERM, then SIGKILL after a grace period). The registration is kept so linzumi_dev_service_start can bring it back.",{name:D.string().min(1).describe("Service name to stop.")},async r=>{let o=await fx({scopeDir:t.scopeDir,name:r.name});return He(o.ok?{ok:!0,name:o.record.name,desired_state:"stopped"}:{ok:!1,error:o.error})}),e.tool("linzumi_dev_service_status","List every managed dev service with liveness (running / unhealthy / exited / failed / stopped), per-port health probes, last exit, and any terminal failure reason. Live state - always check this before concluding a dev server is up or down.",{},async()=>{let r=await cx(t.scopeDir);return He({services:r.map(o=>hke(o))})}),e.tool("linzumi_dev_service_logs","Read the tail of a managed dev service's combined stdout/stderr log.",{name:D.string().min(1).describe("Service name."),max_bytes:D.number().int().min(256).max(65536).optional().describe("Tail size in bytes (default 16384).")},async r=>{let o=cP(t.scopeDir,r.name,r.max_bytes??16384);return He(o===void 0?{ok:!1,error:`no log for service: ${r.name}`}:{ok:!0,name:r.name,log_tail:o})}),e.tool("linzumi_dev_service_remove","Stop a managed dev service AND delete its registration (it will not be resurrected on runner restart). Use stop instead when the user may want it back.",{name:D.string().min(1).describe("Service name to remove.")},async r=>{let o=await lP({scopeDir:t.scopeDir,name:r.name});return He(o.ok?{ok:!0,name:o.record.name,removed:!0}:{ok:!1,error:o.error})})}function p_n(e){return!(e instanceof Error)||!e.message.includes("channel_required")?e:new Error(`${e.message}. Remediation: pass the channel slug in the \`channel\` parameter, or set target.thread_id to a Linzumi thread you can access (the server resolves the thread's channel). The files were NOT attached; retry with a channel or thread instead of leaving them on disk.`,{cause:e})}async function m_n(e){let n=await Promise.all(e.files.map(a=>Jq(e.cwd,a))),t=b(e.target.thread_id),r=await e.client.prepareMessageUploads({...e.workspace===void 0?{}:{workspace:e.workspace},...e.channel===void 0?{}:{channel:e.channel},...t===void 0?{}:{thread_id:t},files:n.map(a=>({file_name:a.fileName,content_type:a.contentType,size_bytes:a.sizeBytes}))}),o=Xe(r.uploads)??[];if(o.length!==n.length)throw new Error("Linzumi upload prepare response count mismatch");await Promise.all(n.map(async(a,s)=>{let d=O(o[s]),u=b(d?.upload_url),c=b(d?.upload_method)??"PUT";if(u===void 0)throw new Error("Linzumi upload prepare response missing upload_url");let l=a.bytes,f=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength),p=await fetch(v0(e.kandanUrl,u),{method:c,headers:{"content-type":a.contentType},body:f});if(!p.ok)throw new Error(`Linzumi upload failed for ${a.fileName}: ${p.status} ${p.statusText}`)}));let i=o.map(a=>{let s=b(O(a)?.file_id);if(s===void 0)throw new Error("Linzumi upload prepare response missing file_id");return s});return await e.client.attachMessageFiles({...e.workspace===void 0?{}:{workspace:e.workspace},...e.channel===void 0?{}:{channel:e.channel},...t===void 0?{}:{thread_id:t},target:e.target,...e.body===void 0?{}:{body:e.body},uploaded_file_ids:i})}async function h_n(e){let n=await Jq(e.cwd,e.file),t=await e.client.prepareCustomEmoji({...e.workspace===void 0?{}:{workspace:e.workspace},name:e.name,file_name:n.fileName,content_type:n.contentType,size_bytes:n.sizeBytes}),r=O(t.upload),o=b(r?.upload_url),i=b(r?.upload_method)??"PUT";if(o===void 0)throw new Error("Linzumi custom emoji prepare response missing upload_url");let a=n.bytes,s=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength),d=await fetch(v0(e.kandanUrl,o),{method:i,headers:{"content-type":n.contentType},body:s});if(!d.ok){let l=`${d.status} ${d.statusText}`,p=(await d.text()).trim(),h=p===""?l:(()=>{try{let y=JSON.parse(p);return se(y)&&typeof y.error=="string"?y.error:p}catch{return p}})();throw new Error(`Linzumi custom emoji upload failed: ${h}`)}let u=await d.json();if(!se(u))throw new Error("Linzumi custom emoji upload returned non-object JSON");let c=O(u.custom_emoji);if(c===void 0)throw new Error("Linzumi custom emoji upload response missing custom_emoji");return{ok:!0,workspace:t.workspace,emoji:c,asset_id:b(u.asset_id),id:ie(c?.id),name:b(c?.name),shortcode:b(c?.shortcode),image_url:b(c?.image_url)}}function gke(e,n){if(b(e.thread_id)!==void 0||n===void 0)return e;switch(e.message_seq===void 0){case!1:return{...e,thread_id:n};case!0:switch(b(e.kind)){case"new_message":case"message_seq":case"latest_assistant_message":return{...e,thread_id:n};default:return e}}}function Cd(e,n){return b(e.thread_id)!==void 0||n===void 0?e:{...e,thread_id:n}}function v0(e,n){try{return new URL(n).toString()}catch{let r=e.replace(/^wss:\/\//,"https://").replace(/^ws:\/\//,"http://");return new URL(n,r).toString()}}function yke(e,n){let t=O(n.message),r=O(n.target_message);return t===void 0&&r===void 0?n:{...n,...t===void 0?{}:{message:_ke(e,t)},...r===void 0?{}:{target_message:_ke(e,r)}}}function _ke(e,n){let t=Xe(n.attachments);return t===void 0?n:{...n,attachments:t.map(r=>g_n(e,r))}}function g_n(e,n){let t=O(n);if(t===void 0)return n;let r=b(t.url),o=O(t.image_variants);return{...t,...r===void 0?{}:{url:v0(e,r)},...o===void 0?{}:{image_variants:y_n(e,o)}}}function y_n(e,n){let t=b(n.inline_url),r=b(n.carousel_url);return{...n,...t===void 0?{}:{inline_url:v0(e,t)},...r===void 0?{}:{carousel_url:v0(e,r)}}}function __n(e){e.server.registerCapabilities({resources:{listChanged:!1}}),e.server.setRequestHandler(h_,()=>({resources:[]})),e.server.setRequestHandler(g_,()=>({resourceTemplates:[]}))}async function b_n(e){let n=p5(e),t=h5(n,"api-url"),r=Jt(n,"format")??"codex",o=m5(Jt(n,"mode")),i=n.get("include-token")===!0?(await f5({kandanUrl:t,explicitToken:Jt(n,"token")??process.env.LINZUMI_MCP_ACCESS_TOKEN,authFilePath:Jt(n,"auth-file"),delegationAuthFilePath:Jt(n,"delegation-auth-file"),workspaceSlug:Jt(n,"workspace"),channelSlug:Jt(n,"channel")})).accessToken:void 0,a=Ld({command:Jt(n,"command"),kandanUrl:t,accessToken:i,delegationAuthFilePath:Jt(n,"delegation-auth-file"),ownerUsername:Jt(n,"owner-username")??process.env.LINZUMI_MCP_OWNER_USERNAME,operatingMode:o,toolScope:wke(Jt(n,"tool-scope")),multiAgentJobs:n.get("multi-agent-jobs")===!0});switch(r){case"codex":process.stdout.write(cee(a));return;case"claude-code":process.stdout.write(lee(a));return;default:throw new Error("--format must be codex or claude-code")}}async function v_n(e){let n=p5(e),t=h5(n,"api-url"),r=await f5({kandanUrl:t,explicitToken:Jt(n,"token")??process.env.LINZUMI_MCP_ACCESS_TOKEN,authFilePath:Jt(n,"auth-file"),delegationAuthFilePath:Jt(n,"delegation-auth-file"),workspaceSlug:Jt(n,"workspace"),channelSlug:Jt(n,"channel")});switch(r.mode){case"local-runner":{if(!await sI({kandanUrl:t,accessToken:r.accessToken,workspaceSlug:Jt(n,"workspace"),channelSlug:Jt(n,"channel")}))throw new Error("Linzumi MCP auth validation failed");break}case"personal-agent-delegation":{await Qd({kandanUrl:t,accessToken:r.accessToken,authMode:r.mode,operatingMode:m5(Jt(n,"mode"))}).validateAuth();break}}process.stdout.write(`Linzumi MCP auth OK
|
|
2236
|
+
`}async function s_n(e){let n=p5(e);if(n.get("help")===!0){process.stdout.write(xke());return}let t=h5(n,"api-url"),r=await f5({kandanUrl:t,explicitToken:Jt(n,"token")??process.env.LINZUMI_MCP_ACCESS_TOKEN,authFilePath:Jt(n,"auth-file"),delegationAuthFilePath:Jt(n,"delegation-auth-file"),workspaceSlug:Jt(n,"workspace"),channelSlug:Jt(n,"channel")}),o=Jt(n,"owner-username")??process.env.LINZUMI_MCP_OWNER_USERNAME,i=m5(Jt(n,"mode")),a=wke(Jt(n,"tool-scope")),s=Jt(n,"cwd")??process.cwd(),d=Jt(n,"thread-id")??process.env.LINZUMI_THREAD_RUNNER_KANDAN_THREAD_ID,u=n.get("agent-session")===!0?Jle(Jt(n,"auth-file")):void 0,c=Qd({kandanUrl:t,accessToken:r.accessToken,authMode:r.mode,operatingMode:i,topicWakeTurnCapability:u}),l=new ZM({name:"linzumi",version:"0.1.0"});__n(l),c_n(l,{client:c,toolScope:a,operatingMode:i,cwd:s,kandanUrl:t,defaultThreadId:d,ownerUsername:o,agentSession:n.get("agent-session")===!0,topicQuietAuthFilePath:u===void 0?void 0:Jt(n,"auth-file"),documentSurfaces:kb(r.accessToken),askUserQuestionTool:n.get("ask-user-question-tool")===!0,devServices:u_n(process.env),multiAgentJobs:n.get("multi-agent-jobs")===!0});let f=new XM;await l.connect(u===void 0?f:l_n(f,()=>c.recordTopicWakeToolAttempt(),Jt(n,"auth-file")))}var pke="One or two sentences a teammate skimming the board would want: what changed, and what happens next. Standup register, present tense, name agents and lanes plainly. No thread ids or UUIDs unless needed for lookup; proofs and evidence belong in the thread, not here. Good: 'Retired the silent watchdog and spawned Thorne to replace it \u2014 running lean at three children.' Bad: 'Broken 67f1d639 archived abandoned; board claim preceded spawn; children verified at exactly 3.'",d_n=new Intl.Segmenter("en",{granularity:"grapheme"}),mke=D.string().min(1).refine(e=>Array.from(d_n.segment(e)).length<=240,{message:"status_note over 240 chars \u2014 trim to what a reader needs; put evidence in the thread."});function u_n(e){let n=e.LINZUMI_DEV_SERVICES_SCOPE?.trim(),t=Number.parseInt(e.LINZUMI_DEV_SERVICES_OWNER_PID??"",10);if(!(n===void 0||n===""||!Number.isInteger(t)||t<=0))return{scopeDir:xc(n),ownerPid:t}}function l_n(e,n,t){let r=Promise.resolve(),o="accepting",i=new Map,a=()=>{if(o="closed_after_failure",console.warn("topic_quiet_tool_admission_refused"),t!==void 0)try{kw(t,"attempt_failed")}catch{console.warn("topic_quiet_fault_custody_unresolved")}},s={start:async()=>{e.onclose=()=>s.onclose?.(),e.onerror=d=>s.onerror?.(d),e.onmessage=(d,u)=>{if(o!=="accepting"){console.warn("topic_quiet_transport_closed_request_refused");return}if(!("method"in d)||d.method!=="tools/call"||!("id"in d)){s.onmessage?.(d,u);return}let c=qH(d.params??null);r=r.then(async()=>{if(o!=="accepting"){console.warn("topic_quiet_transport_queued_request_refused");return}try{if(c||(t!==void 0&&kw(t,"attempt_pending"),await n(),t!==void 0&&kw(t,"attempt_acknowledged")),s.onmessage===void 0)throw new Error("topic_quiet_transport_unbound");let l=new Promise((f,p)=>{i.set(d.id,{quietRequest:c,resolve:f,reject:p})});s.onmessage(d,u),await l}catch{i.delete(d.id),a();try{await e.send({jsonrpc:"2.0",id:d.id,result:{isError:!0,content:[{type:"text",text:"topic_quiet_tool_admission_refused"}]}})}finally{await e.close()}}}).catch(()=>{console.warn("topic_quiet_transport_response_failed"),s.onerror?.(new Error("topic_quiet_transport_response_failed"))})},await e.start()},send:async(d,u)=>{let c="id"in d&&d.id!==void 0&&("result"in d||"error"in d)?i.get(d.id):void 0,l=c!==void 0&&("error"in d||"result"in d&&O(d.result)?.isError===!0);c!==void 0&&(o=$H(c.quietRequest,l,yq("result"in d?O(d.result)?.structuredContent??null:null)),o==="closed_after_failure"&&a());try{await e.send(d,u),c?.resolve(),o!=="accepting"&&await e.close()}catch(f){throw c?.reject(f),f}finally{c!==void 0&&"id"in d&&d.id!==void 0&&i.delete(d.id)}},close:()=>e.close(),setProtocolVersion:d=>e.setProtocolVersion?.(d)};return s}function c_n(e,n){let{client:t,toolScope:r,operatingMode:o,cwd:i,kandanUrl:a,defaultThreadId:s,ownerUsername:d,agentSession:u,devServices:c}=n;u&&e.tool("linzumi_complete_topic_wake_no_action","Complete an authenticated conditional topic wake when its condition requires no action. Supply a clear reason. This posts no message, proposes no edit, and cannot conceal failed tools or attempted effects. Ordinary mentions and component batches are not eligible.",{reason:D.string().refine(MH,{message:"A nonblank reason of at most 2000 UTF-8 bytes is required."})},async f=>{let p=await t.completeTopicWakeNoAction({reason:f.reason});if(!yq(p))throw new Error("topic_quiet_server_receipt_invalid");return n.topicQuietAuthFilePath!==void 0&&kw(n.topicQuietAuthFilePath,"quiet_acknowledged"),He(p)});let l=r==="all"||r==="coding";if(n.askUserQuestionTool===!0&&e.tool(pee,`Ask the user up to ${Bv} structured multiple-choice questions and BLOCK until they answer in the Linzumi thread. Use this whenever you need a decision or clarification mid-task. Each question needs a short header (max ${Jv} chars) and ${Kv}-${Wv} options {label, description}; a built-in "${Hv}" free-text choice is always shown in addition to your options, so never add one yourself. Set multiSelect true to allow choosing several options. Returns {answers} keyed by question text: a single label string, an array of labels for multiSelect, and {"other": "<typed text>"} for a free-text reply.`,{questions:D.array(D.object({question:D.string().describe("The question to ask the user."),header:D.string().describe(`Short category header shown above the question (max ${Jv} chars, e.g. "Auth", "Scope").`),options:D.array(D.object({label:D.string().describe("Option label the user taps."),description:D.string().optional().describe("One-line explanation of the option.")})).describe(`${Kv}-${Wv} options for this question.`),multiSelect:D.boolean().optional().describe("True lets the user select several options; the answer becomes an array.")})).describe(`1-${Bv} questions to ask atomically.`)},async f=>w_n((p,h)=>e.server.elicitInput(p,h),f)),n.documentSurfaces===!0){let f=D.number().int().positive().optional().describe("Immutable admitted entry_id from the component wake batch. Required when the batch has multiple authorized contexts; never selects newer authority."),p=async(h,y)=>He(await t.agentDocumentTool({...y,tool:h}));e.tool("linzumi_lookup_documents","Search document titles and content within the controlling human's visibility ceiling. Returns authorized results in canonical search order; zero, one, and multiple matches carry the rule-03 ambiguity meaning.",{query:D.string().min(1).describe("Document title or content search query."),component_entry_id:f},async h=>p("lookup_documents",h)),e.tool("linzumi_read_document","Read one in-scope document as full AST and metadata, including pending proposals and required-agent-context comments. Both controlling-human visibility and agent delegation are required.",{document_id:D.string().uuid().describe("Document UUID."),component_entry_id:f},async h=>p("read_document",h)),u?(e.tool("linzumi_invoke_command","Invoke a registered command authorized by the current component wake context. Use the embedding document UUID, exact command name and typed inputs from that context, a stable idempotency key, and its admitted component_entry_id. Current permissions and the frozen per-entry authority are rechecked by the server; this tool grants no new authority.",{document_id:D.string().uuid().describe("Embedding document UUID."),command_name:D.string().min(1).describe("Exact registered command name authorized by this component context."),inputs:D.record(D.unknown()).describe("Typed inputs for the registered command."),idempotency_key:D.string().min(1).describe("Stable key for this logical command invocation; preserve it on replay."),component_entry_id:f},async h=>p("invoke_command",h)),e.tool("linzumi_append_document_section","Use this tool for append-shaped document requests: add or append a new section, or add or update a tracker row as new section content, including parent-delegated work. After resolving exactly one patch target document and reading it, call this tool in the same turn; do not merely reply with suggested prose. Other authorized context documents do not make the patch target ambiguous. Supply only the heading and body Markdown: the server composes the closed structural operations. Every change is proposal-always.",{document_id:D.string().uuid().describe("Document UUID."),heading:D.string().trim().min(1).describe("Section heading."),body_markdown:D.string().trim().min(1).describe("Section body as Markdown authored by the model."),component_entry_id:f},async h=>p("append_document_section",h)),e.tool("linzumi_replace_section","Use this tool for targeted section rewrites, fixes, and tightening. After resolving exactly one patch target document and reading it, identify the section by exact heading text or its heading block UUID and supply the replacement body Markdown. The server rejects missing and ambiguous headings with actionable typed errors and composes the closed structural operations. Every change is proposal-always.",{document_id:D.string().uuid().describe("Document UUID."),heading_or_section_ref:D.string().trim().min(1).describe("Exact heading text or heading block UUID from read_document."),body_markdown:D.string().trim().min(1).describe("Replacement section body as Markdown."),component_entry_id:f},async h=>p("replace_section",h)),e.tool("linzumi_annotate_document_section","Use this tool to add a durable note to one existing heading-delimited document section without rewriting its content. After resolving exactly one patch target document and reading it, identify the section by exact heading text or its heading block UUID and supply only the note Markdown. The server rejects missing and ambiguous headings, composes the anchored comment, and persists a proposal before any authorized auto-apply.",{document_id:D.string().uuid().describe("Document UUID."),heading_or_section_ref:D.string().trim().min(1).describe("Exact heading text or heading block UUID from read_document."),note_markdown:D.string().trim().min(1).describe("Durable section note as Markdown."),component_entry_id:f},async h=>p("annotate_document_section",h)),e.tool("linzumi_decline_document_action","Decline the current document action when no advertised document intent can express it. Give a clear reason; the server relays it verbatim with an honest decline prefix and satisfies the action binding.",{reason:D.string().refine(h=>h.trim().length>0,{message:"Reason must contain non-whitespace text."}).describe("Clear reason the available document intents cannot express the request.")},async h=>He(await t.declineDocumentAction({reason:h.reason})))):e.tool("linzumi_propose_document_patch","Submit a raw revisioned structural document patch. This power/API surface requires the caller to compose the closed operation vocabulary. Create a native data-bound table with the atomic create_bound_table operation containing bindingId, block, and binding; rows remain source data and must not be copied into the block. Every change is proposal-always.",{document_id:D.string().uuid().describe("Document UUID."),patch:D.object({baseRevision:D.number().int().nonnegative(),operations:D.array(D.record(D.unknown())),title:D.string().min(1).optional()}).describe("Revisioned structural document patch."),rationale:D.string().min(1).describe("Why this change is proposed."),component_entry_id:f},async h=>p("propose_document_patch",h)),u||e.tool("linzumi_create_document","Create an agent-attributed document through an atomic bootstrap proposal and apply transaction in the named folder or workspace default folder.",{title:D.string().min(1).describe("Document title."),initial_patch:D.record(D.unknown()).describe("Bootstrap structural patch."),folder_id:D.string().uuid().optional().describe("Destination folder UUID."),component_entry_id:f},async h=>p("create_document",h))}if(u){e.tool("linzumi_agent_reply","Post your single @linzumi reply for the current turn into the surface where you were mentioned. Call EXACTLY ONCE per turn with your final answer; the reply links to this working session automatically. Fails with already_replied on a second call and no_active_asker_binding when no turn is active.",{body:D.string().min(1).describe("Plain-text reply body to post."),tokens:Um.optional()},async p=>He(await t.agentReply({body:p.body,...p.tokens===void 0?{}:{tokens:p.tokens}})));let f=async(p,h)=>He(await t.agentTopicTool({...h,tool:p}));e.tool("linzumi_create_topic_wake_subscription","Create or update a standing subscription that wakes @linzumi when new entries land on an existing workspace topic. Use this when the user asks you to watch a topic and perform an ongoing job. The server stores the instruction, derives the creator from the current asker, and targets this conversation; do not claim success without calling this tool.",{topic_slug:D.string().min(1).describe("Existing workspace topic slug to watch."),instruction:D.string().min(1).max(4e3).describe("Standing job to execute whenever a matching topic entry wakes the agent.")},async p=>f("create_topic_wake_subscription",p)),e.tool("linzumi_disable_topic_wake_subscription","Disable the current asker's standing @linzumi wake subscription for a topic. The durable row and cursor are retained so reactivation can drain the disabled-period backlog.",{topic_slug:D.string().min(1).describe("Workspace topic slug whose standing wake should stop.")},async p=>f("disable_topic_wake_subscription",p)),e.tool("linzumi_list_coding_jobs","List the coding jobs the current asker can see in this workspace: runner connections (online and recent) with their bound job threads. Live state - never answered from search.",{},async()=>He(await t.agentListCodingJobs({}))),e.tool("linzumi_start_coding_job","Start a coding job exactly as if the asking user clicked start: same runner/channel authorization, same pipeline. Returns status 'unavailable' with a reason when the runner cannot take the job (relay that honestly).",{channel:D.string().describe("Channel slug to host the job thread."),runner_key:D.string().describe("Runner (computer) to run the job on."),cwd:D.string().describe("Working directory on the runner."),work_description:D.string().min(1).describe("What the job should do - the initial instruction."),model:D.string().optional().describe("Model override (optional)."),model_provider:D.string().optional().describe("Model provider override, e.g. 'wafer' (optional)."),execution_mode:D.enum(["raw","local_vm"]).optional().describe("Execution placement override (optional)."),project_task_id:D.string().optional().describe("Project task item to bind the job to (task_id from linzumi_get_project_tasks). The task flips todo -> active and links to the new job."),visibility:D.enum(["project","private"]).optional().describe("Job visibility. Defaults to 'project'; private jobs are limited to directly authorized participants.")},async p=>He(await t.agentStartCodingJob(p))),e.tool("linzumi_interrupt_coding_job","Interrupt a coding job: mode 'steer' (default) discards its queued follow-ups so your next message lands first; mode 'stop' terminates the current turn.",{channel:D.string().describe("Channel slug hosting the job thread."),thread_id:D.string().uuid().describe("The job thread UUID."),mode:D.enum(["steer","stop"]).optional().describe("Interrupt mode; defaults to 'steer'.")},async p=>He(await t.agentInterruptCodingJob(p))),e.tool("linzumi_send_coding_job_message","Message a coding job or a person. Queue is the encouraged default: it lands in the colleague's inbox for their own cadence. Steer only for urgent, potentially-clashing work because it interrupts the running turn. Would this be worthless or harmful after their turn finishes? If no, queue. Delivery urgency is not access control. To message a person, pass to_user and omit channel and thread_id: delivery lands in their personal inbox.",{channel:D.string().optional().describe("Channel slug hosting the job thread. Required unless to_user is set."),thread_id:D.string().uuid().optional().describe("The job thread UUID. Required unless to_user is set."),to_user:D.string().min(1).optional().describe("Username of a workspace member to message instead of a job. Delivery lands in their personal inbox."),body:D.string().min(1).describe("Message body to send."),tokens:Um.optional(),delivery:D.enum(["queue","steer"]).optional().describe("Delivery urgency. Defaults to 'queue'.")},async p=>He(await t.agentSendCodingJobMessage(p))),e.tool("linzumi_read_coding_job_thread","Read a coding job's thread (asker-visible history) plus its workflow status metadata.",{channel:D.string().describe("Channel slug hosting the job thread."),thread_id:D.string().uuid().describe("The job thread UUID."),limit:D.number().int().min(1).max(100).optional().describe("Maximum replies to return."),before_seq:D.number().int().positive().optional().describe("Return replies before this channel seq.")},async p=>He(await t.agentReadCodingJobThread(p))),e.tool("linzumi_resolve_job_approval","Resolve a coding job's pending approval request with the asking user's decision ('approve' or 'deny'). Only relays the asker's authority - never approve without their explicit instruction.",{channel:D.string().describe("Channel slug hosting the job thread."),thread_id:D.string().uuid().describe("The job thread UUID."),source_seq:D.number().int().positive().describe("Channel seq of the message the approval request rides on."),request_id:D.string().describe("The approval request id."),decision:D.enum(["approve","deny"]).describe("The asker's decision.")},async p=>He(await t.agentResolveJobApproval(p))),e.tool("linzumi_archive_coding_job","Archive a coding job's thread (or any thread the asking user owns) so it leaves the active list; history is preserved. Do this when the asker says to archive a job or thread - never just promise it.",{channel:D.string().describe("Channel slug hosting the thread."),thread_id:D.string().uuid().describe("The thread UUID to archive.")},async p=>He(await t.agentArchiveCodingJob(p))),e.tool("linzumi_unarchive_coding_job","Unarchive a previously archived coding job thread the asking user owns, returning it to the active list.",{channel:D.string().describe("Channel slug hosting the thread."),thread_id:D.string().uuid().describe("The thread UUID to unarchive.")},async p=>He(await t.agentUnarchiveCodingJob(p))),e.tool("linzumi_set_thread_status","Set a thread's lifecycle status as the asking user: 'closed' marks it done, 'open' reopens it. Works on threads the asker owns.",{channel:D.string().describe("Channel slug hosting the thread."),thread_id:D.string().uuid().describe("The thread UUID."),status:D.enum(["open","closed"]).describe("Replacement lifecycle status ('closed' = done).")},async p=>He(await t.agentSetThreadStatus(p))),e.tool("linzumi_create_channel","Create a new public channel in this workspace as the asking user. The slug is derived from the name.",{name:D.string().min(1).describe("Channel name to create.")},async p=>He(await t.agentCreateChannel(p))),e.tool("linzumi_rename_channel","Rename a channel's display name as the asking user. The channel's URL slug stays stable.",{channel:D.string().describe("Current channel slug to rename."),name:D.string().min(1).describe("New display name.")},async p=>He(await t.agentRenameChannel(p))),e.tool("linzumi_archive_channel","Archive a channel in this workspace as the asking user. History is preserved; the channel leaves the active sidebar.",{channel:D.string().describe("Channel slug to archive.")},async p=>He(await t.agentArchiveChannel(p))),e.tool("linzumi_unarchive_channel","Unarchive a previously archived channel as the asking user.",{channel:D.string().describe("Channel slug to unarchive.")},async p=>He(await t.agentUnarchiveChannel(p))),e.tool("linzumi_add_reaction","Add an emoji reaction to a channel message as the asking user. Accepts unicode emoji or a workspace :shortcode:.",{channel:D.string().describe("Channel slug containing the message."),message_seq:D.number().int().positive().describe("Channel seq of the message to react to."),emoji:D.string().min(1).describe("Emoji to add (unicode or :shortcode:).")},async p=>He(await t.agentAddReaction(p))),e.tool("linzumi_remove_reaction","Remove the asking user's emoji reaction from a channel message.",{channel:D.string().describe("Channel slug containing the message."),message_seq:D.number().int().positive().describe("Channel seq of the reacted message."),emoji:D.string().min(1).describe("Emoji to remove (unicode or :shortcode:).")},async p=>He(await t.agentRemoveReaction(p))),e.tool("linzumi_pin_message","Pin a channel message as the asking user. Thread replies re-point to their root message.",{channel:D.string().describe("Channel slug containing the message."),message_seq:D.number().int().positive().describe("Channel seq of the message to pin.")},async p=>He(await t.agentPinMessage(p))),e.tool("linzumi_unpin_message","Remove a pin from a channel message as the asking user.",{channel:D.string().describe("Channel slug containing the message."),message_seq:D.number().int().positive().describe("Channel seq of the pinned message.")},async p=>He(await t.agentUnpinMessage(p)))}r==="all"&&(e.tool("linzumi_get_message","Read one Linzumi message by scoped message_seq/message_id or a Linzumi message URL, with optional bounded before/after context.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),message_id:D.union([D.string(),D.number()]).optional().describe("Message seq inside the scoped channel."),message_seq:D.union([D.string(),D.number()]).optional().describe("Alias for message_id."),message_url:D.string().optional().describe("Full Linzumi message URL with #message-<seq>."),before:D.number().int().min(0).max(100).optional().describe("Number of visible messages before the target."),after:D.number().int().min(0).max(100).optional().describe("Number of visible messages after the target.")},async f=>He(await t.getMessage(f))),e.tool("linzumi_get_thread","Read one Linzumi thread by thread_id in the scoped channel, including the parent message and bounded replies.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:D.string().uuid().describe("Linzumi thread UUID."),limit:D.number().int().min(1).max(100).optional().describe("Maximum replies to return."),before_seq:D.number().int().positive().optional().describe("Return replies before this channel seq.")},async f=>He(await t.getThread(f))),e.tool("linzumi_get_thread_transcript","Read a Linzumi thread's full transcript as canonical IR nodes (user/assistant messages, command executions, file changes, tool calls, statuses), cursor-paginated over the complete history. Use the returned cursor with has_more to walk older pages.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:D.string().uuid().describe("Linzumi thread UUID."),limit:D.number().int().min(1).max(500).optional().describe("Maximum transcript nodes per page (default 200)."),cursor:D.number().int().positive().optional().describe("Return nodes below this seq (the previous page reply cursor).")},async f=>He(await t.getThreadTranscript(f))),e.tool("linzumi_get_channel","Read scoped Linzumi channel metadata and bounded recent channel messages.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),limit:D.number().int().min(1).max(100).optional().describe("Maximum messages to return."),before_seq:D.number().int().positive().optional().describe("Return messages before this channel seq.")},async f=>He(await t.getChannel(f))),e.tool("linzumi_search_workspace","Search the Linzumi workspace with hybrid lexical+semantic retrieval, scoped to what the authorizing user can access. Returns scored content chunks with provenance (channel, thread, authored time) and a permalink to cite.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),query:D.string().min(1).describe("Natural-language or keyword query to retrieve against."),limit:D.number().int().min(1).max(25).optional().describe("Maximum results to return (default 10, server-capped)."),source_types:D.array(D.enum(["message","coding_job","github_pr","github_pr_review","github_check_run","github_workflow_run","github_diff","dictation","file"])).optional().describe("Restrict results to these corpora; omit for all."),authored_after:D.string().optional().describe("ISO8601 instant; only content authored at or after this time."),authored_before:D.string().optional().describe("ISO8601 instant; only content authored at or before this time."),repo:D.string().optional().describe("Restrict GitHub-sourced results to one repository by full name (owner/name)."),check_status:D.enum(["pending","success","failed"]).optional().describe("Restrict check and workflow results to one conclusion bucket.")},async f=>He(await t.searchWorkspace(f))),e.tool("linzumi_ask_workspace",'Ask the Linzumi workspace a natural-language question and get a synthesized, citation-backed answer over what the authorizing user can access. Costs an LLM call on cache misses, so prefer linzumi_search_workspace for simple lookups. A "refused" status means there was not enough accessible evidence - treat it as "the workspace does not know", never retry verbatim.',{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),question:D.string().min(1).max(2e3).describe("Natural-language question to answer with citations."),channel:D.string().optional().describe("Optional channel slug providing conversational context; never widens access."),allow_cached:D.boolean().optional().describe("Allow serving a cached synthesis when the evidence set is unchanged (default true). Set false to force fresh synthesis.")},async f=>He(await t.askWorkspace(f))),e.tool("linzumi_about_me","Read what the authorizing user has told Linzumi about themselves: their profile facts (homes, unit preferences, and other self-maintained attributes) plus their derived current timezone. Use it to personalize answers (e.g. pick the right city for weather, use their preferred units). Predicates may have multiple active values; prefer the one consistent with the derived timezone.",{},async f=>He(await t.aboutMe(f)))),l&&(e.tool("linzumi_web_search","Search the public web for live or external information: news, current events, weather, prices, third-party API docs, research. Returns result titles, URLs, and snippets. Use this whenever the answer lives outside the Linzumi workspace; follow up with linzumi_fetch_url to read a result page.",{query:D.string().min(1).describe("Web search query (natural language or keywords)."),limit:D.number().int().min(1).max(10).optional().describe("Maximum results to return (default 8, server-capped).")},async f=>He(await t.webSearch(f))),e.tool("linzumi_fetch_url","Fetch one public http(s) URL and return its readable text content (HTML is reduced to plain text; large pages are truncated). Use it to read pages found via linzumi_web_search or any public docs/API reference. Only public addresses are reachable - private/internal hosts are rejected with url_not_allowed.",{url:D.string().min(1).describe("Absolute public http(s) URL to fetch.")},async f=>He(await t.fetchUrl(f)))),r==="all"&&(e.tool("linzumi_list_ui_targets","List every UI surface you can ask the user to open in their own Linzumi window (channels, DMs, threads, projects, coding jobs, computers, catch-up, activity, settings tabs, pane layouts) with the structured args each kind takes. Use UI control only when the user asks for help or asks to be shown something.",{},async()=>await bke(t.listUiTargets({}))),e.tool("linzumi_open_ui","Ask the user to open one whitelisted UI surface in their own already-open Linzumi window. A consent toast appears in THEIR session; navigation happens only if they tap Open. The call blocks until they decide and returns status opened/dismissed/expired - or error no_active_ui_session when they have no Linzumi window open (tell them to open Linzumi), or invalid_target with a detail. Use it only when the user asks for help or asks to be shown something; kinds and per-kind args come from linzumi_list_ui_targets.",{kind:D.string().min(1).describe("Target kind from linzumi_list_ui_targets (e.g. settings_workspace, channel, pane_layout)."),args:D.record(D.unknown()).optional().describe("Structured per-kind args from linzumi_list_ui_targets (never a URL - the server computes every path)."),workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async f=>await bke(t.openUi(Cd(f,s))))),l&&(e.registerTool("linzumi_schedule_wake",{description:'Schedule this coding job to wake itself once and start an ordinary visible turn with the supplied prompt. Provide exactly one of fire_at or delay_minutes. Good: delay_minutes=20, prompt="Check CI, address any failures, then update the plan." Bad: prompt="wake up" (it gives the future turn no actionable context).',inputSchema:D.object({fire_at:D.string().datetime({offset:!0}).optional().describe("Future ISO8601 timestamp with timezone."),delay_minutes:D.number().int().min(1).max(525600).optional().describe("Minutes from now before the one-time wake fires."),prompt:D.string().min(1).max(4e3).describe("Actionable human-register description of exactly what to do when this job wakes.")}).refine(f=>f.fire_at===void 0!=(f.delay_minutes===void 0),{message:"provide exactly one of fire_at or delay_minutes"})},async f=>He(await t.scheduleWake(f))),e.tool("linzumi_cancel_wake","Cancel one still-scheduled wake owned by this coding job. Fired, already-canceled, missing, or another job's wake fails loudly.",{wake_id:D.string().uuid().describe("Wake id returned by linzumi_schedule_wake.")},async f=>He(await t.cancelWake(f))),e.tool("linzumi_get_coding_job_metadata","Read the active coding job workflow metadata for a thread, including the agent-owned goal, ordered plan steps, step lock versions, and workflow status.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:D.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread.")},async f=>He(await t.getCodingJobMetadata(Cd(f,s)))),e.tool("linzumi_rename_coding_job","Update the current coding job thread title and workflow-facing title. Use this when the job scope changes materially so the Linzumi thread list and metadata overview stay accurate.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:D.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),title:D.string().min(1).max(100).describe("Concise user-visible title for this coding job.")},async f=>He(await t.renameCodingJob(Cd(f,s)))),e.tool("linzumi_upsert_coding_job_plan","Set or update the current coding job goal. Use this at job start and whenever the goal changes materially.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:D.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),goal:D.string().min(1).max(1e4).describe("Concrete user-visible goal for this coding job."),snooze_reason:D.string().min(1).max(500).optional().describe('Declare a legitimate wait to pause liveness nudges: what you are waiting on, in plain words a teammate would understand. Good: "waiting on CI for PR #4633". Must be sent together with snooze_minutes.'),snooze_minutes:D.number().int().min(1).max(1440).optional().describe("How many minutes until the wait should be rechecked (1-1440). The deadline is mandatory - open-ended waits are refused. Must be sent together with snooze_reason.")},async f=>He(await t.upsertCodingJobPlan(Cd(f,s)))),e.tool("linzumi_replace_coding_job_plan_steps","Replace the ordered coding job plan steps. Use this for the initial plan and for substantial rewrites when the old plan no longer fits the work.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:D.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),goal:D.string().min(1).max(1e4).optional().describe("Required when no plan exists yet; updates the current coding job goal."),steps:D.array(D.object({title:D.string().min(1).max(255),description:D.string().min(1).max(1e4),status:D.enum(["pending","active","completed","blocked","canceled"]),status_note:mke.optional().describe(pke),completed_debrief:D.string().min(1).max(2e4).optional().describe("Required for completed steps. A short paragraph of plain prose for a teammate: what was done, and how we know it worked. Same voice as the note, just more room. Never a compliance recital. Put evidence and verification here.")})).min(1).max(50).describe("Ordered user-visible plan steps. Completed steps must include completed_debrief.")},async f=>He(await t.replaceCodingJobPlanSteps(Cd(f,s)))),e.tool("linzumi_update_coding_job_plan_step","Update one coding job plan step status or note. Read metadata first and pass the current step lock_version.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:D.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),step_id:D.string().uuid().describe("Step id returned by linzumi_get_coding_job_metadata."),lock_version:D.number().int().positive().describe("Current step lock_version from metadata."),status:D.enum(["pending","active","completed","blocked","canceled"]),status_note:mke.optional().describe(pke),completed_debrief:D.string().min(1).max(2e4).optional().describe("Required when marking a step completed. A short paragraph of plain prose for a teammate: what was done, and how we know it worked. Same voice as the note, just more room. Never a compliance recital. Put evidence and verification here.")},async f=>He(await t.updateCodingJobPlanStep(Cd(f,s)))),e.tool("linzumi_link_coding_job_pull_request","Link the active coding job to its primary GitHub pull request so PR comments, files, commits, checks, deployments, and reviews can flow into the metadata view.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:D.string().uuid().optional().describe("Linzumi thread UUID. Defaults to the active coding job thread."),github_repo_owner:D.string().min(1).max(255),github_repo_name:D.string().min(1).max(255),github_pr_number:D.number().int().positive(),github_pr_url:D.string().url(),title:D.string().min(1).max(255),body:D.string().min(1).max(1e5).optional(),head_branch:D.string().min(1).max(255),head_sha:D.string().min(7).max(64),base_branch:D.string().min(1).max(255),base_sha:D.string().min(7).max(64),state:D.enum(["draft","open","closed","merged"]).optional(),merge_commit_sha:D.string().min(7).max(64).optional().describe("Actual GitHub merge commit SHA. Required when state is merged; omit for other states. This is not the PR head SHA."),is_draft:D.boolean().optional(),review_status:D.enum(["unknown","review_required","approved","changes_requested"]).optional(),source_remote_url:D.string().min(1).max(1e3).describe("Git remote URL for the local job worktree; required when this job has no repo workspace yet."),runtime_worktree_root:D.string().min(1).max(1e3).describe("Absolute local worktree path for the coding job; required when this job has no repo workspace yet."),dirty_status:D.enum(["unknown","clean","dirty"]).optional(),dirty_summary:D.string().min(1).max(2e3).optional()},async f=>He(await t.linkCodingJobPullRequest(Cd(f,s)))),e.tool("linzumi_upload_files",["Upload local files to Linzumi and attach them to a new, exact, or latest assistant message. Use silently; do not mention this tool in the visible reply.","The JSON result includes message.attachments[].url as an absolute URL. Use those returned URLs when writing rich media directives such as ::audio, ::video, ::image, or Markdown images. Do not guess attachment URLs before upload.","For a message that should both attach files and show inline rich media, use a two-step flow: first upload/attach the files to create or target the message, then edit the same target message with body text that references the returned absolute URLs. When the result has target_seq, use target.kind=message_seq and message_seq=target_seq for that follow-up edit; result.message is the edit event that carries the new attachments, and target_message is the original target."].join(" "),{target:D.object({kind:D.enum(["new_message","message_seq","latest_assistant_message"]).describe("new_message creates a message; message_seq edits an exact message; latest_assistant_message edits the latest assistant message in the scoped thread/channel."),message_seq:D.union([D.string(),D.number()]).optional().describe("Required when kind is message_seq."),thread_id:D.string().optional().describe("Thread UUID. Defaults to the active Linzumi thread when the MCP server was launched with one.")}).describe("Attachment target. Prefer latest_assistant_message to attach files to the reply you already posted; use new_message ONLY when no assistant message exists yet in the scoped thread. Never re-use your visible reply text as a new_message body - that posts the reply twice. To reference uploaded files in the message body, upload first, then edit message_seq/latest_assistant_message with the returned absolute attachment URLs. If the upload result includes target_seq, use message_seq=target_seq for that follow-up edit."),files:D.array(D.string().min(1)).min(1).max(16).describe("Local file paths to upload. Paths must be non-hidden files inside the approved workspace or Downloads; source/text files of any language are supported, plus common document, image, patch, archive, and video types."),body:D.string().min(1).max(2e4).optional().describe("Required for new_message: a SHORT file-share caption (for example: Attached the generated report), never a copy of your visible reply - that would post the reply twice. Optional replacement body for message_seq/latest_assistant_message; when omitted, the existing message body is preserved. Rich media directives in body must use Linzumi attachment download URLs returned by this tool."),workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug. Omit to use the target thread's channel (when the thread is known) or the authenticated token scope.")},async f=>{let p=gke(f.target,s);try{let h=await m_n({client:t,cwd:i,kandanUrl:a,target:p,files:f.files,workspace:f.workspace,channel:f.channel,body:f.body});return He(yke(a,h))}catch(h){throw p_n(h)}}),e.tool("linzumi_edit_message","Edit an exact scoped Linzumi message by message_seq. Use after linzumi_upload_files when you need a body-only follow-up edit that embeds returned attachment URLs. Requires channel.write, and thread.write when target.thread_id is set. Rich media src/poster values must be Linzumi attachment download URLs.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),target:D.object({message_seq:D.union([D.string(),D.number()]).describe("Exact message seq to edit. After linzumi_upload_files returns target_seq, pass that value here."),thread_id:D.string().optional().describe("Thread UUID when editing a thread message. Use the upload result target_message.thread_id when present.")}).describe("Exact message target for the body edit."),body:D.string().min(1).max(2e4).describe("Replacement Markdown body. Rich media src/poster values must be Linzumi attachment download URLs returned by linzumi_upload_files.")},async f=>He(yke(a,await t.editMessage({...f,target:gke(f.target,s)}))))),r==="all"&&(e.tool("linzumi_list_vault_secrets","List vault secret names, descriptions, and whether each secret is personal or workspace-owned. Does not return secret values.",{},async f=>He(await t.listVaultSecrets(f))),e.tool("linzumi_list_projects","List the projects in the current workspace with their project_id (needed by the other project task tools), slug, title, description, and state.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async f=>He(await t.listProjects(f))),e.tool("linzumi_get_project_tasks",`Read a project's full task graph: task GROUPS (kind "group", organizational containers, exactly one level deep) and ISSUES (kind "issue", the executable work items), each with status (todo/active/blocked/review/done/canceled), DERIVED work_state readiness (ready = todo with every dependency satisfied; blocked = todo with unsatisfied dependencies; running/stalled = active with/without a connected job), parent group, assignee, lock_version, and dependency edges (depends_on_task_ids / unblocks_task_ids). Always read this before reorganizing. Inside a project-bound coding job the project is inferred automatically; otherwise pass project_id from linzumi_list_projects.`,{project_id:D.string().optional().describe("Project id from linzumi_list_projects. Omit inside a coding job started from a project to use that project.")},async f=>He(await t.getProjectTasks(Cd(f,s)))),e.tool("linzumi_create_project_task",'Create a task group (kind "group") or issue (kind "issue", the default) in a project. Groups organize issues and are exactly one level deep: a parent_id must name a GROUP, and groups themselves can never have a parent. New tasks default to status "todo" and append to the end unless position is given. Inside a project-bound coding job the project is inferred; otherwise pass project_id.',{project_id:D.string().optional().describe("Project id from linzumi_list_projects. Omit inside a coding job started from a project to use that project."),title:D.string().min(1).describe("Task title."),kind:D.enum(["issue","group"]).optional().describe('What to create: "issue" (executable work item, default) or "group" (organizational container).'),description:D.string().optional().describe("Detailed description of the work - written so an engineer (or coding agent) could execute the task from it."),status:D.enum(["todo","active","blocked","review","done","canceled"]).optional().describe('Initial status. Defaults to "todo".'),parent_id:D.string().optional().describe("task_id of the GROUP to place an issue in. Only issues can have a parent."),assignee:D.string().optional().describe("Username of a workspace member to assign."),position:D.number().int().min(0).optional().describe("Sort position. Defaults to appending at the end.")},async f=>He(await t.createProjectTask(Cd(f,s)))),e.tool("linzumi_update_project_task",'Update a task group or issue: retitle, edit description/status_note, transition status (todo/active/blocked/review/done/canceled), reassign, reorder (position), or reorganize (parent_id moves an issue into a group; clear_parent moves it to top level). Only the fields you pass change; description and status_note accept null to clear. Prefer updating existing tasks over delete-and-recreate. Pass the lock_version from your last read to fail loudly ("stale") instead of overwriting a concurrent edit.',{task_id:D.string().describe("task_id of the group or issue to update."),title:D.string().min(1).optional().describe("New title."),description:D.string().nullable().optional().describe("New description. Pass null to clear it."),status:D.enum(["todo","active","blocked","review","done","canceled"]).optional().describe('New status. "done"/"canceled" satisfy dependent tasks; "blocked" is a manual hold.'),status_note:D.string().nullable().optional().describe("Short human-readable note about the current status. Pass null to clear it."),position:D.number().int().min(0).optional().describe("New sort position among siblings."),parent_id:D.string().optional().describe("task_id of the GROUP to move this issue into. Do not combine with clear_parent."),clear_parent:D.boolean().optional().describe("true moves the issue to the top level (no group). Do not combine with parent_id."),assignee:D.string().optional().describe("Username of a workspace member to assign. Do not combine with clear_assignee."),clear_assignee:D.boolean().optional().describe("true removes the assignee. Do not combine with assignee."),lock_version:D.number().int().positive().optional().describe("The task's lock_version from your last read, for compare-and-swap safety.")},async f=>He(await t.updateProjectTask(f))),e.tool("linzumi_delete_project_task",`Permanently delete a task group or issue. Dependency edges on the task are removed with it (dependents may become ready). Deletion is normally the USER's call - prefer status "canceled" or an update unless you are certain the entry is obsolete.`,{task_id:D.string().describe("task_id of the group or issue to delete.")},async f=>He(await t.deleteProjectTask(f))),e.tool("linzumi_add_project_task_dependency",'Add the dependency edge "task_id is blocked by depends_on_task_id" between two ISSUES in the same project (groups cannot have dependencies). The dependent stays blocked until the prerequisite reaches done or canceled. The graph must stay acyclic: an edge that would create a cycle is refused with reason "would_create_cycle" and the offending cycle_path so you can restructure. Duplicate and self edges are rejected.',{task_id:D.string().describe("task_id of the DEPENDENT issue (the one that must wait)."),depends_on_task_id:D.string().describe("task_id of the PREREQUISITE issue (the one that must finish first).")},async f=>He(await t.addProjectTaskDependency(f))),e.tool("linzumi_remove_project_task_dependency",'Remove the dependency edge "task_id is blocked by depends_on_task_id". The dependent issue may become ready if that was its last unsatisfied dependency.',{task_id:D.string().describe("task_id of the DEPENDENT issue."),depends_on_task_id:D.string().describe("task_id of the PREREQUISITE issue the edge points at.")},async f=>He(await t.removeProjectTaskDependency(f))),e.tool("linzumi_get_call_transcript","Read the full transcript of a completed Linzumi notetaker call: call metadata (title, platform, started/ended/transcribed times), participants, and every spoken segment in order with speaker names and millisecond offsets. Pass the call_id embedded in the request (or copied from the call card). Errors: call_not_found (missing or not visible to you), call_transcript_not_ready (call still connecting, in progress, or transcribing - retry later).",{call_id:D.string().describe("The call id from the call card or the launching message (a CallRecording id - the opaque GraphQL id and the bare uuid both work).")},async f=>He(await t.getCallTranscript(f))),u||(e.tool("linzumi_start_coding_job","Start a coding job as the invoking user (same authorization and pipeline as clicking start). To start a project task item, pass project_task_id so the task flips todo -> active and links to the new job. Only start tasks whose work_state is ready. Proceed when the user has already explicitly authorized this launch within the agreed scope; DAG bookkeeping does not require renewed approval. Otherwise, offer and wait for explicit acceptance. Do not duplicate existing active work or treat task readiness as launch authorization. Omit channel, runner_key, and cwd to reuse this job's own channel, computer, and folder. Returns status 'unavailable' with a reason when the runner cannot take the job (relay that honestly).",{work_description:D.string().min(1).describe("What the job should do - the initial instruction. For a task item, write it from the task title and description."),project_task_id:D.string().optional().describe("Project task item to bind the job to (task_id from linzumi_get_project_tasks). The task flips todo -> active and links to the new job."),visibility:D.enum(["project","private"]).optional().describe("Child-job visibility. Defaults to 'project'; private jobs are limited to directly authorized participants."),channel:D.string().optional().describe("Channel slug to host the job thread. Omit to use this job's own channel."),runner_key:D.string().optional().describe("Runner (computer) to run the job on. Omit to use this job's own computer."),cwd:D.string().optional().describe("Working directory on the runner. Omit to use this job's own folder."),model:D.string().optional().describe("Model override (optional)."),model_provider:D.string().optional().describe("Model provider override, e.g. 'wafer' (optional)."),agent_provider:D.string().optional().describe("Agent provider override, e.g. 'codex' (optional)."),reasoning_effort:D.enum(["default","low","medium","high","xhigh","ultra"]).optional().describe("Reasoning effort override (optional)."),approval_policy:D.enum(["default","on-request","on-failure","never"]).optional().describe("Approval policy override (optional)."),sandbox:D.enum(["default","workspace-write","read-only","danger-full-access"]).optional().describe("Sandbox override (optional)."),fast:D.boolean().optional().describe("Fast-mode override (optional)."),allow_port_forwarding_by_default:D.boolean().optional().describe("Default port-forwarding override (optional)."),execution_mode:D.enum(["raw","local_vm"]).optional().describe("Execution placement override (optional)."),egress_mode:D.enum(["open","hardened"]).optional().describe("Local-VM egress override (optional).")},async f=>He(await t.agentStartCodingJob(Cd(f,s)))),n.multiAgentJobs===!0&&(e.tool("linzumi_spawn_child_job","Spawn a durable child coding job under YOUR OWN job, on any harness or model - plan a DAG and delegate its legs to workers you then coordinate through discovery and messaging. The child lands on this job's channel, computer, and folder; it inherits this job's project and visibility (a private parent's children stay private), human roles cascade to it, and a human manages its lifecycle. Returns status 'unavailable' with a reason when the runner cannot take the job (relay that honestly).",{work_description:D.string().min(1).describe("What the child job should do - the initial instruction, written to stand alone."),agent_provider:D.string().optional().describe("Harness for the child, e.g. 'codex' or 'claude-code'. Omit to reuse this job's own harness. A different harness is fine: a cross-harness child is always a child job."),model:D.string().optional().describe("Model override for the child (optional)."),model_provider:D.string().optional().describe("Model provider override, e.g. 'wafer' (optional)."),reasoning_effort:D.enum(["default","low","medium","high","xhigh","ultra"]).optional().describe("Reasoning effort override (optional)."),project_task_id:D.string().optional().describe("Project task item to bind the child to (task_id from linzumi_get_project_tasks). The task flips todo -> active and links to the new job."),visibility:D.enum(["project","private"]).optional().describe("Child visibility. Defaults to this job's own visibility; a private parent's children must stay private.")},async f=>He(await t.agentSpawnChildJob(Cd(f,s)))),e.tool("linzumi_archive_child_job","Archive a coding job that is YOUR OWN job or one beneath it in your job tree, retiring it from the active lists, the org map and the needs-you deck; history is preserved and it can be unarchived. Use this to clean up child jobs you spawned that are finished or dead - do it in the current turn, never just promise it. Refused for sibling, parent or unrelated jobs, and for jobs that do not belong to the human you are working for. When the job still has live descendants the call returns confirmation_required with their exact count and ids; call again with descendant_action 'keep' (archive only this job, re-parenting its children) or 'cascade' (archive the whole subtree) plus those expected values.",{job_id:D.string().describe("The coding job id to archive: your own job, or any job beneath it in your tree."),outcome:D.enum(["completed","abandoned","superseded"]).describe("Why the job is being archived."),descendant_action:D.enum(["keep","cascade"]).optional().describe("Phase-2 choice when the job has live descendants. 'keep' archives only this job and re-parents its children; 'cascade' archives the whole subtree."),expected_descendant_count:D.number().int().optional().describe("The descendant_count returned by the phase-1 call."),expected_descendant_job_ids:D.array(D.string()).optional().describe("The descendant_job_ids returned by the phase-1 call; the call is refused if the subtree changed."),expected_descendant_fingerprint:D.string().optional().describe("The descendant_fingerprint returned by the phase-1 call.")},async f=>He(await t.agentArchiveChildJob(f))),e.tool("linzumi_unarchive_child_job","Unarchive a previously archived coding job that is YOUR OWN job or one beneath it in your job tree. It returns as hibernating and wakes when messaged. Same ownership scope as linzumi_archive_child_job. Refused when the job is not archived, or when its home thread already holds a live job.",{job_id:D.string().describe("The archived coding job id to bring back: your own job, or any job beneath it in your tree.")},async f=>He(await t.agentUnarchiveChildJob(f))),e.tool("linzumi_discover_coding_jobs","Search current sitreps inside this coding job project for overlapping files, modules, objectives, or blockers. Results include durable job addresses for coordination. Private jobs outside your visible set never appear.",{query:D.string().min(1).describe("Free-text clash-surface query, such as a file path, module, migration, or objective.")},async f=>He(await t.agentDiscoverCodingJobs({...f,source_thread_id:s}))),e.tool("linzumi_send_coding_job_message","Message a visible coding job in this project, or a person. Queue is the encouraged default: it lands in the colleague's inbox for their own cadence. Steer only for urgent, potentially-clashing work because it interrupts the running turn. Would this be worthless or harmful after their turn finishes? If no, queue. Delivery urgency is not access control. To message a person, pass to_user and omit channel and thread_id: delivery lands in their personal inbox.",{channel:D.string().optional().describe("Channel slug hosting the target job. Required unless to_user is set."),thread_id:D.string().uuid().optional().describe("Target job thread UUID. Required unless to_user is set."),to_user:D.string().min(1).optional().describe("Username of a workspace member to message instead of a job. Delivery lands in their personal inbox."),body:D.string().min(1).describe("Coordination message to send."),tokens:Um.optional(),delivery:D.enum(["queue","steer"]).optional().describe("Delivery urgency. Defaults to 'queue'.")},async f=>He(await t.agentSendCodingJobMessage({...f,source_thread_id:s})))))),r_n(r)&&(e.tool("linzumi_upload_custom_emoji","Upload a local image as a workspace custom emoji. For generated emoji art, create a transparent PNG with a simple centered subject, crisp edges, strong contrast, minimal tiny details, and enough outline/highlight separation to read at 16-24px on both dark and light backgrounds. Use lowercase shortcode names without colons unless preserving a user-provided :name:.",{name:fke.describe("Custom emoji shortcode name, with or without surrounding colons."),file:D.string().min(1).describe("Local PNG/WebP/GIF/JPEG file path to upload. Prefer transparent PNG for generated emoji."),workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async f=>He(await h_n({client:t,cwd:i,kandanUrl:a,name:f.name,file:f.file,workspace:f.workspace}))),e.tool("linzumi_rename_custom_emoji","Rename an existing workspace custom emoji. The new name may include surrounding colons; Linzumi stores the normalized shortcode without colons.",{emoji_id:D.union([D.string(),D.number().int().positive()]).describe("Workspace custom emoji id returned by linzumi_upload_custom_emoji or workspace emoji listings."),name:fke.describe("New shortcode name, with or without surrounding colons."),workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope.")},async f=>He(await t.renameCustomEmoji(f)))),e.tool("linzumi_media_guide","Return the full Linzumi rich-media authoring guide (audio/video/image directives, URL rules, upload-then-embed flow, examples). Call once BEFORE writing any ::audio/::video/::image directive or Markdown image into a Linzumi message.",{},async()=>({content:[{type:"text",text:NC}]})),e.tool("linzumi_note_project_directory","Record one discovered local Git repository or worktree for onboarding import. Call once per project as soon as it is found.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),runner_id:D.string().min(1).describe("Local runner/computer id provided in the discovery prompt."),path:D.string().min(1).describe("Absolute local path to the repository worktree root."),display_name:D.string().optional().describe("Short project label. Defaults to the path basename."),activity_at:D.string().optional().describe("Best-known recent activity time as an ISO-8601 timestamp."),import_key:D.string().optional().describe("Stable dedupe key. Defaults to path."),metadata:D.record(D.unknown()).optional().describe("Small structured metadata such as branch or remote origin.")},async f=>He(await t.noteProjectDirectory(f))),e.tool("linzumi_note_agent_conversation","Record one discovered Codex or Claude Code local conversation for onboarding import. Call once per conversation as soon as it is found.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),runner_id:D.string().min(1).describe("Local runner/computer id provided in the discovery prompt."),source:D.enum(["codex","claude_code"]).describe("Conversation source."),import_key:D.string().min(1).describe("Stable dedupe key, such as a session id or file path."),path:D.string().optional().describe("Absolute local path to the conversation file or directory."),display_name:D.string().optional().describe("Short label for the discovered conversation."),activity_at:D.string().optional().describe("Best-known recent activity time as an ISO-8601 timestamp."),metadata:D.record(D.unknown()).optional().describe("Small structured metadata such as session id or project path.")},async f=>He(await t.noteAgentConversation(f))),e.tool("linzumi_note_onboarding_discovery_status","Record onboarding discovery progress. Call when a search phase starts, checks another place, completes, or fails.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),runner_id:D.string().min(1).describe("Local runner/computer id provided in the discovery prompt."),phase:D.enum(["projects","conversations"]).describe("Discovery phase being reported."),status:D.enum(["starting","running","completed","failed"]).describe("Current phase status."),places_searched:D.number().int().nonnegative().optional().describe("Count of concrete folders/files/known locations checked so far."),message:D.string().optional().describe("Short user-facing status note."),current_place:D.string().optional().describe("Current folder, file, Git command target, or known location being checked."),current_source:D.string().optional().describe("Short machine-readable source label such as git, codex, or claude_code."),last_error:D.string().optional().describe("Short failure detail when status is failed."),metadata:D.record(D.unknown()).optional().describe("Small structured status metadata.")},async f=>He(await t.noteOnboardingDiscoveryStatus(f))),r==="all"&&o_n(o)&&(e.tool("linzumi_dm_owner","Send a plain-text DM to the configured Commander owner. Requires dm.write and a visible owner username.",{owner_username:D.string().optional().describe("Owner username. Defaults to LINZUMI_MCP_OWNER_USERNAME or --owner-username."),workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Source channel slug used to verify owner visibility."),body:D.string().min(1).max(2e4).describe("Plain-text message body to DM."),tokens:Um.optional()},async f=>{let p=f.owner_username??d;if(p===void 0)throw new Error("owner_username is required for linzumi_dm_owner");return He(await t.dmOwner({...f,owner_username:p}))}),e.tool("linzumi_send_channel_message","Post a NEW standalone Markdown message into the scoped Linzumi channel as the authenticated local-runner user. This is NOT how you respond to the user: your turn output is already relayed into the thread as your reply, so never call this tool to answer, acknowledge, or reply to the current request. Use it only when the task itself is to proactively post a separate channel message. Requires channel.write. Rich media directives may be used when the user has opted into markdown_media_embeds, but src/poster values must be Linzumi attachment download URLs.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),body:D.string().min(1).max(2e4).describe("Markdown message body to post. Rich media src/poster values must be Linzumi attachment download URLs, not third-party URLs, /relative paths, or local filesystem paths."),tokens:Um.optional()},async f=>He(await t.sendChannelMessage(f))),e.tool("linzumi_send_thread_reply","Post a Markdown reply into some OTHER existing Linzumi thread as the authenticated local-runner user. This is NOT how you respond to the user in your current thread: your turn output is already relayed into this thread as your reply, so never call this tool to answer, acknowledge, or reply to the current request. Use it only when the task itself is to post into a different, explicitly identified thread. Requires thread.write. Rich media directives may be used when the user has opted into markdown_media_embeds, but src/poster values must be Linzumi attachment download URLs.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug. Omit to use the authenticated token scope."),thread_id:D.string().uuid().describe("Existing Linzumi thread UUID."),body:D.string().min(1).max(2e4).describe("Markdown reply body to post. Rich media src/poster values must be Linzumi attachment download URLs, not third-party URLs, /relative paths, or local filesystem paths."),tokens:Um.optional()},async f=>He(await t.sendThreadReply(f))),e.tool("linzumi_send_dm","Send a plain-text DM as the authenticated local-runner user to a visible user in the scoped workspace/channel. Requires dm.write.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Source channel slug used to verify target visibility."),username:D.string().describe("Visible Linzumi username to DM."),body:D.string().min(1).max(2e4).describe("Plain-text message body to DM."),tokens:Um.optional()},async f=>He(await t.sendDm(f)))),r==="all"&&e.tool("linzumi_get_vault_values","Request values for explicit vault env var names after a thread-scoped human approval. Requires vault.read; thread_id resolves the approval thread.",{workspace:D.string().optional().describe("Workspace slug. Omit to use the authenticated token scope."),channel:D.string().optional().describe("Channel slug used to disambiguate the approval thread when needed."),thread_id:D.string().uuid().describe("Existing Linzumi thread UUID for the inline approval."),env_var_names:D.array(D.string().regex(/^[A-Z][A-Z0-9_]{0,127}$/)).min(1).max(20).describe("Explicit vault env var names to request. This tool cannot list all vault keys."),description:D.string().min(1).max(500).describe("Human-readable reason shown in the approval request."),justification:D.string().min(10).max(1e3).describe("Agent justification shown to the approver.")},async f=>He(await t.getVaultValues(f))),r==="all"&&!u&&c!==void 0&&f_n(e,i,c)}function hke(e){return{name:e.record.name,command:e.record.command,cwd:e.record.cwd,ports:[...e.record.ports],restart_on_branch_change:e.record.restartOnBranchChange,desired_state:e.record.desiredState,liveness:e.liveness,port_health:e.portProbes.map(n=>({port:n.port,listening:n.listening})),started_at_ms:e.record.startedAtMs??null,last_exit:e.lastExit===void 0?null:{code:e.lastExit.code,signal:e.lastExit.signal,at_ms:e.lastExit.atMs},log_path:e.record.logPath,failure:e.failure===void 0?null:{reason:e.failure.reason,at_ms:e.failure.atMs}}}function f_n(e,n,t){e.tool("linzumi_dev_service_start","Start a long-running local dev server (npm run dev, storybook, docker compose up, ...) as a MANAGED SERVICE owned by the Linzumi runner. Use this instead of running dev servers in your own shell: a managed service survives the end of your turn and branch switches, is auto-restarted if it crashes, and its declared ports are health-probed and surfaced in the product. Calling start for an existing name declaratively RESTARTS it (e.g. after a checkout). Declare EVERY port the app serves from (primary plus HMR/asset/bundle sibling ports).",{name:D.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/).describe("Stable service name (slug), e.g. 'web' or 'storybook'. Reusing a name restarts that service."),command:D.string().min(1).describe("Shell command that runs the server in the foreground (never daemonize/screen/nohup it yourself), e.g. 'npm run dev'. Runs via the user's login shell."),cwd:D.string().optional().describe("Working directory for the service. Defaults to the session cwd."),ports:D.array(D.number().int().min(1).max(65535)).max(16).default([]).describe("Every TCP port this service listens on (primary AND related ports such as the Vite/HMR bundle port). Used for health probes and product visibility."),restart_on_branch_change:D.boolean().optional().describe("Restart the service automatically when the git branch of its cwd changes (for servers that go stale across checkouts)."),wait_for_ports_ms:D.number().int().min(0).max(6e4).optional().describe("How long to wait for the declared ports to accept connections before returning (default 15000).")},async r=>{let o=await uP({scopeDir:t.scopeDir,definition:{name:r.name,command:r.command,cwd:r.cwd??n,ports:r.ports,restartOnBranchChange:r.restart_on_branch_change===!0},ownerPid:t.ownerPid});if(!o.ok)return He({ok:!1,error:o.error});let i=Date.now()+(r.wait_for_ports_ms??15e3),a=o.record.ports.length===0;for(;!a&&Date.now()<i;)a=(await Promise.all(o.record.ports.map(c=>Z$(c)))).every(c=>c),a||await new Promise(c=>setTimeout(c,250));let d=(await cx(t.scopeDir)).find(u=>u.record.name===o.record.name);return He({ok:!0,service:d===void 0?{name:o.record.name}:hke(d),...d!==void 0&&d.liveness!=="running"?{hint:"The service is not (fully) serving its declared ports yet. Check linzumi_dev_service_logs before assuming it works."}:{}})}),e.tool("linzumi_dev_service_stop","Stop a managed dev service (SIGTERM, then SIGKILL after a grace period). The registration is kept so linzumi_dev_service_start can bring it back.",{name:D.string().min(1).describe("Service name to stop.")},async r=>{let o=await fx({scopeDir:t.scopeDir,name:r.name});return He(o.ok?{ok:!0,name:o.record.name,desired_state:"stopped"}:{ok:!1,error:o.error})}),e.tool("linzumi_dev_service_status","List every managed dev service with liveness (running / unhealthy / exited / failed / stopped), per-port health probes, last exit, and any terminal failure reason. Live state - always check this before concluding a dev server is up or down.",{},async()=>{let r=await cx(t.scopeDir);return He({services:r.map(o=>hke(o))})}),e.tool("linzumi_dev_service_logs","Read the tail of a managed dev service's combined stdout/stderr log.",{name:D.string().min(1).describe("Service name."),max_bytes:D.number().int().min(256).max(65536).optional().describe("Tail size in bytes (default 16384).")},async r=>{let o=cP(t.scopeDir,r.name,r.max_bytes??16384);return He(o===void 0?{ok:!1,error:`no log for service: ${r.name}`}:{ok:!0,name:r.name,log_tail:o})}),e.tool("linzumi_dev_service_remove","Stop a managed dev service AND delete its registration (it will not be resurrected on runner restart). Use stop instead when the user may want it back.",{name:D.string().min(1).describe("Service name to remove.")},async r=>{let o=await lP({scopeDir:t.scopeDir,name:r.name});return He(o.ok?{ok:!0,name:o.record.name,removed:!0}:{ok:!1,error:o.error})})}function p_n(e){return!(e instanceof Error)||!e.message.includes("channel_required")?e:new Error(`${e.message}. Remediation: pass the channel slug in the \`channel\` parameter, or set target.thread_id to a Linzumi thread you can access (the server resolves the thread's channel). The files were NOT attached; retry with a channel or thread instead of leaving them on disk.`,{cause:e})}async function m_n(e){let n=await Promise.all(e.files.map(a=>Jq(e.cwd,a))),t=b(e.target.thread_id),r=await e.client.prepareMessageUploads({...e.workspace===void 0?{}:{workspace:e.workspace},...e.channel===void 0?{}:{channel:e.channel},...t===void 0?{}:{thread_id:t},files:n.map(a=>({file_name:a.fileName,content_type:a.contentType,size_bytes:a.sizeBytes}))}),o=Xe(r.uploads)??[];if(o.length!==n.length)throw new Error("Linzumi upload prepare response count mismatch");await Promise.all(n.map(async(a,s)=>{let d=O(o[s]),u=b(d?.upload_url),c=b(d?.upload_method)??"PUT";if(u===void 0)throw new Error("Linzumi upload prepare response missing upload_url");let l=a.bytes,f=l.buffer.slice(l.byteOffset,l.byteOffset+l.byteLength),p=await fetch(v0(e.kandanUrl,u),{method:c,headers:{"content-type":a.contentType},body:f});if(!p.ok)throw new Error(`Linzumi upload failed for ${a.fileName}: ${p.status} ${p.statusText}`)}));let i=o.map(a=>{let s=b(O(a)?.file_id);if(s===void 0)throw new Error("Linzumi upload prepare response missing file_id");return s});return await e.client.attachMessageFiles({...e.workspace===void 0?{}:{workspace:e.workspace},...e.channel===void 0?{}:{channel:e.channel},...t===void 0?{}:{thread_id:t},target:e.target,...e.body===void 0?{}:{body:e.body},uploaded_file_ids:i})}async function h_n(e){let n=await Jq(e.cwd,e.file),t=await e.client.prepareCustomEmoji({...e.workspace===void 0?{}:{workspace:e.workspace},name:e.name,file_name:n.fileName,content_type:n.contentType,size_bytes:n.sizeBytes}),r=O(t.upload),o=b(r?.upload_url),i=b(r?.upload_method)??"PUT";if(o===void 0)throw new Error("Linzumi custom emoji prepare response missing upload_url");let a=n.bytes,s=a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength),d=await fetch(v0(e.kandanUrl,o),{method:i,headers:{"content-type":n.contentType},body:s});if(!d.ok){let l=`${d.status} ${d.statusText}`,p=(await d.text()).trim(),h=p===""?l:(()=>{try{let y=JSON.parse(p);return se(y)&&typeof y.error=="string"?y.error:p}catch{return p}})();throw new Error(`Linzumi custom emoji upload failed: ${h}`)}let u=await d.json();if(!se(u))throw new Error("Linzumi custom emoji upload returned non-object JSON");let c=O(u.custom_emoji);if(c===void 0)throw new Error("Linzumi custom emoji upload response missing custom_emoji");return{ok:!0,workspace:t.workspace,emoji:c,asset_id:b(u.asset_id),id:ie(c?.id),name:b(c?.name),shortcode:b(c?.shortcode),image_url:b(c?.image_url)}}function gke(e,n){if(b(e.thread_id)!==void 0||n===void 0)return e;switch(e.message_seq===void 0){case!1:return{...e,thread_id:n};case!0:switch(b(e.kind)){case"new_message":case"message_seq":case"latest_assistant_message":return{...e,thread_id:n};default:return e}}}function Cd(e,n){return b(e.thread_id)!==void 0||n===void 0?e:{...e,thread_id:n}}function v0(e,n){try{return new URL(n).toString()}catch{let r=e.replace(/^wss:\/\//,"https://").replace(/^ws:\/\//,"http://");return new URL(n,r).toString()}}function yke(e,n){let t=O(n.message),r=O(n.target_message);return t===void 0&&r===void 0?n:{...n,...t===void 0?{}:{message:_ke(e,t)},...r===void 0?{}:{target_message:_ke(e,r)}}}function _ke(e,n){let t=Xe(n.attachments);return t===void 0?n:{...n,attachments:t.map(r=>g_n(e,r))}}function g_n(e,n){let t=O(n);if(t===void 0)return n;let r=b(t.url),o=O(t.image_variants);return{...t,...r===void 0?{}:{url:v0(e,r)},...o===void 0?{}:{image_variants:y_n(e,o)}}}function y_n(e,n){let t=b(n.inline_url),r=b(n.carousel_url);return{...n,...t===void 0?{}:{inline_url:v0(e,t)},...r===void 0?{}:{carousel_url:v0(e,r)}}}function __n(e){e.server.registerCapabilities({resources:{listChanged:!1}}),e.server.setRequestHandler(h_,()=>({resources:[]})),e.server.setRequestHandler(g_,()=>({resourceTemplates:[]}))}async function b_n(e){let n=p5(e),t=h5(n,"api-url"),r=Jt(n,"format")??"codex",o=m5(Jt(n,"mode")),i=n.get("include-token")===!0?(await f5({kandanUrl:t,explicitToken:Jt(n,"token")??process.env.LINZUMI_MCP_ACCESS_TOKEN,authFilePath:Jt(n,"auth-file"),delegationAuthFilePath:Jt(n,"delegation-auth-file"),workspaceSlug:Jt(n,"workspace"),channelSlug:Jt(n,"channel")})).accessToken:void 0,a=Ld({command:Jt(n,"command"),kandanUrl:t,accessToken:i,delegationAuthFilePath:Jt(n,"delegation-auth-file"),ownerUsername:Jt(n,"owner-username")??process.env.LINZUMI_MCP_OWNER_USERNAME,operatingMode:o,toolScope:wke(Jt(n,"tool-scope")),multiAgentJobs:n.get("multi-agent-jobs")===!0});switch(r){case"codex":process.stdout.write(cee(a));return;case"claude-code":process.stdout.write(lee(a));return;default:throw new Error("--format must be codex or claude-code")}}async function v_n(e){let n=p5(e),t=h5(n,"api-url"),r=await f5({kandanUrl:t,explicitToken:Jt(n,"token")??process.env.LINZUMI_MCP_ACCESS_TOKEN,authFilePath:Jt(n,"auth-file"),delegationAuthFilePath:Jt(n,"delegation-auth-file"),workspaceSlug:Jt(n,"workspace"),channelSlug:Jt(n,"channel")});switch(r.mode){case"local-runner":{if(!await sI({kandanUrl:t,accessToken:r.accessToken,workspaceSlug:Jt(n,"workspace"),channelSlug:Jt(n,"channel")}))throw new Error("Linzumi MCP auth validation failed");break}case"personal-agent-delegation":{await Qd({kandanUrl:t,accessToken:r.accessToken,authMode:r.mode,operatingMode:m5(Jt(n,"mode"))}).validateAuth();break}}process.stdout.write(`Linzumi MCP auth OK
|
|
2237
2237
|
`)}async function f5(e){if(e.delegationAuthFilePath!==void 0){if(e.explicitToken!==void 0||e.authFilePath!==void 0)throw new Error("--delegation-auth-file cannot be combined with --token or --auth-file");return{accessToken:Vle(e.delegationAuthFilePath).accessToken,mode:"personal-agent-delegation"}}return{accessToken:await x_n({kandanUrl:e.kandanUrl,explicitToken:e.explicitToken,authFilePath:e.authFilePath,workspaceSlug:e.workspaceSlug,channelSlug:e.channelSlug}),mode:"local-runner"}}async function x_n(e,n={readCachedToken:zp,validateTokenOutcome:_w,resolveToken:Hc}){let t=e.explicitToken??n.readCachedToken(e.kandanUrl,e.authFilePath)?.accessToken;if(t===void 0)throw new Error("missing Linzumi MCP token; run linzumi auth or pass --token");let r=await n.validateTokenOutcome({kandanUrl:e.kandanUrl,accessToken:t,workspaceSlug:e.workspaceSlug,channelSlug:e.channelSlug});if(r==="usable")return t;let o=r;try{return await n.resolveToken({kandanUrl:e.kandanUrl,workspaceSlug:e.workspaceSlug,channelSlug:e.channelSlug,authFilePath:e.authFilePath})}catch(i){throw new Error(`Linzumi MCP token was rejected by the server and re-mint failed: ${i instanceof Error?i.message:String(i)}`)}}function Ol(e){return{content:[{type:"text",text:e}],isError:!0}}async function w_n(e,n){let t=h$(n);if(t.type==="invalid")return Ol(t.message);let r;try{r=await e(_ee(t.request),{timeout:hee})}catch(o){return Ol(`the interview could not be delivered to the user: ${o instanceof Error?o.message:String(o)}`)}switch(r.action){case"accept":{let o=xee(t.request,r.content??void 0);switch(o.type){case"ok":return He({answers:o.answers});case"invalid":return Ol(o.message)}break}case"decline":{let o=See(r._meta);switch(o){case Zv:return Ol("linzumi_ask_user_question is unavailable during a Plan-mode turn: use the native request_user_input interview tool instead");case Qv:return Ol("the interview was declined: no active turn is bound to this session");default:let i="publish_failed: ";return o?.startsWith(i)?Ol(`the interview could not be published to the user: ${o.slice(i.length)}`):Ol("the interview request was declined by the runner")}}case"cancel":return Ol("the user dismissed the question without answering");default:return Ol(`the interview returned an unknown action: ${String(r.action)}`)}}function He(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}async function bke(e){try{return He(await e)}catch(n){let t=n instanceof Error?n.message:String(n),r=t.match(/failed: ([a-z0-9_]+)(?: detail=(.+))?$/);if(r===null)return He({error:t});let[,o,i]=r;return He(i===void 0?{error:o??t}:{error:o??t,detail:i})}}function p5(e){let n=new Map;for(let t=0;t<e.length;t+=1){let r=e[t];if(r===void 0)continue;if(!r.startsWith("--"))throw new Error(`unexpected argument ${r}`);let o=r.slice(2),i=a_n.get(o);if(i===void 0)throw new Error(`unsupported option --${o}`);if(i.kind==="boolean"){n.set(o,!0);continue}let a=e[t+1];if(a===void 0||a.startsWith("--"))throw new Error(`--${o} requires a value`);n.set(o,a),t+=1}return n}function Jt(e,n){let t=e.get(n);return typeof t=="string"&&t.trim()!==""?t:void 0}function m5(e){switch(e){case void 0:return"text";case"voice":case"text":return e;default:throw new Error("--mode must be voice or text")}}function wke(e){switch(e){case void 0:return"all";case"all":case"coding":case"onboarding-discovery":return e;default:throw new Error("--tool-scope must be all, coding, or onboarding-discovery")}}function h5(e,n){let t=Jt(e,n);if(t===void 0)throw new Error(`--${n} is required`);return t}import{execFile as S_n}from"node:child_process";import{promisify as k_n}from"node:util";var C_n=k_n(S_n),gf="Codex MCP Credentials",q_="2DC432GLL2",$_="2CWCP5BR45",T_n=async e=>{let n=await C_n("/usr/bin/security",[...e],{encoding:"utf8"});return{stdout:n.stdout,stderr:n.stderr}};function P_n(e=[q_,$_]){return[...e.map(t=>t.trim()).filter(t=>t.length>0).map(t=>`teamid:${t}`),"apple:"].join(",")}function A_n(e){return["set-generic-password-partition-list","-S",e.partitionList,"-s",gf,"-a",e.account,"-k",e.keychainPassword]}function I_n(){return["find-generic-password","-s",gf]}function R_n(){return["dump-keychain"]}function E_n(e){let n=[],t=new Set;for(let r of e.split(`
|
|
2238
2238
|
`)){let o=r.trim();if(!o.startsWith('"acct"'))continue;let i=o.indexOf("=");if(i===-1)continue;let a=o.slice(i+1).trim(),s;a==="<NULL>"?s="":a.startsWith('"')&&a.endsWith('"')&&a.length>=2?s=a.slice(1,-1):s=a,t.has(s)||(t.add(s),n.push(s))}return n}function Ske(e){let n=e.trim();return n==="<NULL>"?"":n.startsWith('"')&&n.endsWith('"')&&n.length>=2?n.slice(1,-1):n}function M_n(e){let n=[],t=new Set,r,o,i=!1,a=()=>{if(r===gf){let s=o??"";t.has(s)||(t.add(s),n.push(s))}r=void 0,o=void 0,i=!1};for(let s of e.split(`
|
|
2239
2239
|
`)){let d=s.trim();if(d.startsWith("keychain:")){a();continue}if(d.startsWith('"svce"')){let u=d.indexOf("=");u!==-1&&(r=Ske(d.slice(u+1)));continue}if(d.startsWith('"acct"')){let u=d.indexOf("=");u!==-1&&!i&&(o=Ske(d.slice(u+1)),i=!0)}}return a(),n}async function O_n(e){try{let{stdout:n}=await e(R_n());return M_n(n)}catch(n){if(kke(n))return[];try{let{stdout:t}=await e(I_n());return E_n(t)}catch(t){if(kke(t))return[];throw t}}}function kke(e){if(typeof e!="object"||e===null)return!1;let n=e;if(n.code===44)return!0;let t=`${n.stderr??""}${n.message??""}`;return t.includes("could not be found")||t.includes("SecKeychainSearchCopyNext")||t.includes("errSecItemNotFound")}function D_n(e){if(typeof e=="object"&&e!==null){let n=e,t=typeof n.stderr=="string"?n.stderr.trim():"";if(t.length>0)return t;if(typeof n.message=="string")return n.message}return String(e)}async function Cke(e){let n=e.platform??process.platform,t=e.write??(l=>{process.stdout.write(l)}),r=e.writeError??(l=>{process.stderr.write(l)}),o=e.exec??T_n,i=e.teamIds??[q_,$_],a=P_n(i);if(n!=="darwin")return t(`fix-codex-keychain only applies on macOS (darwin). Nothing to do on ${n}.
|