@quantiya/codevibe-core 2.0.51 → 2.0.52

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.
@@ -15,10 +15,10 @@ export interface ProviderConfig {
15
15
  readonly synthesizedHeaders: Readonly<Record<string, string>>;
16
16
  /**
17
17
  * The EXACT allowlist of `anthropic-beta` (or provider equivalent)
18
- * tokens the broker will pass through. A request carrying a beta token
19
- * outside this set is rejected (400) — header VALUES are agent-
20
- * controlled and can carry data (Codex R2). Empty for OpenAI (no beta
21
- * header is forwarded).
18
+ * tokens the broker will pass through. Non-allowlisted tokens are
19
+ * filtered out (dropped) by the canonical constructor — header VALUES
20
+ * are agent-controlled and cannot ride through unreviewed (Codex R2).
21
+ * Empty for OpenAI (no beta header is forwarded).
22
22
  */
23
23
  readonly betaTokenAllowlist: ReadonlySet<string>;
24
24
  /**
@@ -62,9 +62,9 @@ export declare function requestSha256(body: unknown): string;
62
62
  /**
63
63
  * Build the canonical upstream request (§3.4 step 0). Rejects (throws
64
64
  * `CanonicalRejectError` → 400) anything outside the canonical shape:
65
- * non-JSON content type, a body that isn't a JSON object, or a non-
66
- * allowlisted beta token. DROPS the agent's auth / every other header /
67
- * all query params silently (they simply do not survive into the result).
65
+ * non-JSON content type, a body that isn't a JSON object, or a non-canonical
66
+ * model ID. Non-allowlisted beta tokens are FILTERED (dropped); agent auth /
67
+ * every other header / all query params are DROPPED silently.
68
68
  */
69
69
  export declare function buildCanonicalRequest(input: CanonicalInput): CanonicalRequest;
70
70
  /**
package/dist/index.js CHANGED
@@ -5792,7 +5792,7 @@ ${$.bold}left alone${$.reset} ${$.dim}(needs --force)${$.reset}:`);for(let x of
5792
5792
  ${$.red}\u2717${$.reset} ${g.length} entr${g.length===1?"y":"ies"} may still hold real data and ${g.length===1?"was":"were"} NOT included above. Re-run with ${$.bold}--force${$.reset} as well if you mean to give those bytes up.`)}if(!m.length){if(i&&!a){let x=await pw(e,s,u,l);if(BR(x))return 1}return 1}if(!i)return console.log(`
5793
5793
  Nothing was written. Re-run with ${$.bold}--yes${$.reset} to apply${g.length?" the entries listed first":""}.`),0;let w=Ut.join(s,vs),v=[];try{v=De.readdirSync(w)}catch{v=[]}if(v.length)return console.error(`${$.red}\u2717${$.reset} A CodeVibe session is registering a root right now. Try again once it is idle.`),1;let b=Ut.join(s,Aa),E=De.readFileSync(b,"utf8");if(KD.createHash("sha256").update(E).digest("hex")!==KD.createHash("sha256").update(p.raw).digest("hex"))return console.error(`${$.red}\u2717${$.reset} The registry changed while this ran. Nothing was written; re-run.`),1;let A=new Date().toISOString().replace(/[:.]/g,"-"),k=Ut.join(Ut.dirname(s),"shadow-root-backups",A),R=Ut.join(k,"shadow-roots.json");try{De.mkdirSync(k,{recursive:!0,mode:448}),De.copyFileSync(b,R)}catch(x){return console.error(`${$.red}\u2717${$.reset} Could not write the backup at ${k} (${x.code??"unknown error"}). Nothing was changed \u2014 this command will not clear an entry it cannot restore.`),1}let S=new Set(m.map(x=>x.root.path)),T=p.roots.filter(x=>!S.has(x.path)),P=Ut.join(k,`.registry.next.${process.pid}`);try{De.writeFileSync(P,JSON.stringify({version:2,roots:T}),{mode:384}),De.renameSync(P,b)}catch(x){return console.error(`${$.red}\u2717${$.reset} Could not replace the registry (${x.code??"unknown error"}). Nothing was changed; a copy of it is at ${R}.`),1}finally{try{De.unlinkSync(P)}catch{}}let O=[],_=[];for(let x of m)for(let C of x.markers){let H=Ut.join(k,`marker-${O.length}-${Ut.basename(C)}`);try{De.copyFileSync(C,H),O.push({copy:Ut.basename(H),original:C})}catch(G){if(G.code!=="ENOENT"){_.push(C);continue}}try{De.unlinkSync(C)}catch{}try{De.rmdirSync(Ut.dirname(C))}catch{}}try{De.writeFileSync(Ut.join(k,"manifest.json"),`${JSON.stringify({clearedAtUtc:new Date().toISOString(),registry:b,registryBackup:Ut.basename(R),clearedRoots:m.map(x=>x.root.path),markers:O,unbackedMarkers:_},null,2)}
5794
5794
  `,{mode:384})}catch{}if(console.log(`
5795
- ${$.green}\u2713${$.reset} Cleared ${m.length} entr${m.length===1?"y":"ies"}${O.length?` and ${O.length} task record(s)`:""}. Backup: ${k}`),_.length&&console.error(`${$.red}!${$.reset} ${_.length} task record(s) could not be backed up and were left in place. They name a cleared root and do nothing, but nothing was destroyed either \u2014 remove them by hand once you know why the copy failed.`),g.length&&console.log(`${$.dim} ${g.length} entr${g.length===1?"y was":"ies were"} left alone; re-run with --force if you mean to give those bytes up.${$.reset}`),!a){let x=await pw(e,s,u,l);if(BR(x))return 1}return console.log(" Tasks should start again in any CodeVibe session."),0}var De,Ut,KD,$R,$,Lae,qR=D(()=>{"use strict";De=N(require("fs")),Ut=N(require("path")),KD=N(require("crypto")),$R=require("child_process");mo();om();Wr();Md();uw();Ci();gs();vo();Uf();Pa();$={reset:"\x1B[0m",dim:"\x1B[2m",bold:"\x1B[1m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",cyan:"\x1B[36m"},Lae=[{agent:"CLAUDE",command:"claude",name:"Claude Code"},{agent:"CODEX",command:"codex",name:"Codex CLI"},{agent:"ANTIGRAVITY",command:"agy",name:"Antigravity CLI"}]});var fw,jD=D(()=>{"use strict";fw=[{method:"POST",path:"/v1/messages",auth:"broker_token"},{method:"POST",path:"/v1/responses",auth:"broker_token"},{method:"GET",path:"/healthz",auth:"none"},{method:"GET",path:"/models",auth:"none"},{method:"GET",path:"/v1/models",auth:"none"}]});var Sh,VD=D(()=>{"use strict";Sh=class{constructor(e={}){this.opts=e;this.emitted=[];this.counter=0}async emit(e,r){if(this.emitted.push({kind:e,payload:r}),this.opts.failKinds?.includes(e))throw new Error(`StubStrictAuditSink: simulated IPC failure for ${e}`);return this.opts.nackKinds?.includes(e)?{nack:`StubStrictAuditSink: simulated nack for ${e}`}:(this.counter+=1,{ack:`stub-ack-${this.counter}`})}ofKind(e){return this.emitted.filter(r=>r.kind===e)}}});function Eh(t){return Hae[t]}function KR(t){return t==="/v1/messages"?"anthropic":t==="/v1/responses"?"openai":null}var $ae,Gae,Hae,jR=D(()=>{"use strict";$ae="2023-06-01",Gae=new Set(["oauth-2025-04-20","claude-code-20250219","context-1m-2025-08-07","interleaved-thinking-2025-05-14","context-management-2025-06-27","prompt-caching-scope-2026-01-05","mid-conversation-system-2026-04-07","effort-2025-11-24"]),Hae={anthropic:{upstreamBaseUrl:"https://api.anthropic.com",upstreamPath:"/v1/messages",synthesizedHeaders:{"anthropic-version":$ae,"content-type":"application/json"},betaTokenAllowlist:Gae,betaHeaderName:"anthropic-beta"},openai:{upstreamBaseUrl:"https://api.openai.com",upstreamPath:"/v1/responses",synthesizedHeaders:{"content-type":"application/json"},betaTokenAllowlist:new Set,betaHeaderName:null}}});var zD,Wae,H2,Rh,JD=D(()=>{"use strict";zD=require("node:crypto"),Wae=1800*1e3,H2=32,Rh=class{constructor(e=Wae){this.ttlMs=e;this.current=null;this.graceToken=null;this.generation=0}mint(e=Date.now()){let r=(0,zD.randomBytes)(H2).toString("base64url");return this.current={value:r,expiresAtMs:e+this.ttlMs},this.graceToken=null,this.generation+=1,this.current}rotateWithGrace(e=Date.now()){if(this.current===null||this.graceToken!==null)return null;this.graceToken=this.current;let r=(0,zD.randomBytes)(H2).toString("base64url");return this.current={value:r,expiresAtMs:e+this.ttlMs},this.generation+=1,{token:this.current,generation:this.generation}}commitRotation(e){e!==void 0&&e.generation!==this.generation||(this.graceToken=null)}rollbackRotation(e){e!==void 0&&e.generation!==this.generation||this.graceToken!==null&&(this.current=this.graceToken,this.graceToken=null)}hasPendingGrace(){return this.graceToken!==null}get(){return this.current}acceptedValues(){let e=[];return this.current&&e.push(this.current.value),this.graceToken&&e.push(this.graceToken.value),e}authenticate(e,r=Date.now()){return e?!!(this.current&&r<this.current.expiresAtMs&&e===this.current.value||this.graceToken&&r<this.graceToken.expiresAtMs&&e===this.graceToken.value):!1}clear(){this.current=null,this.graceToken=null}}});function qae(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function YD(t){return(0,VR.createHash)("sha256").update(JSON.stringify(t)).digest("hex")}function Kae(t,e){let r=Eh(t);if(!r.betaHeaderName)return{};let n=e?.[r.betaHeaderName];if(n===void 0||n==="")return{};let i=n.split(",").map(a=>a.trim()).filter(a=>a.length>0),o=i.filter(a=>r.betaTokenAllowlist.has(a)),s=i.filter(a=>!r.betaTokenAllowlist.has(a));return s.length>0&&y.warn("[canonical] dropped non-allowlisted beta tokens",{dropped:s}),o.length===0?{}:{[r.betaHeaderName]:o.join(",")}}function zR(t){let{provider:e,request:r}=t,n=Eh(e);if(t.agentContentType!==void 0&&t.agentContentType.split(";")[0].trim().toLowerCase()!=="application/json")throw new zs("non-JSON content type");let i=r.body;if(i==null||typeof i!="object"||Array.isArray(i))throw new zs("body is not a JSON object");if(qae(i,"model")){let c=i.model;if(typeof c!="string"||!Uae.test(c))throw new zs("model is not a canonical model id")}let o=(0,VR.randomUUID)(),s=YD(i),a={...n.synthesizedHeaders,...Kae(e,t.agentHeaders)};return{provider:e,upstreamUrl:n.upstreamBaseUrl+n.upstreamPath,headers:a,body:i,modelCallId:o,requestSha256:s}}function JR(t,e){let r=e.filter(p=>p.length>0),n=[],i=[],o="[REDACTED-SELF-CRED]",s="[REDACTED-SELF-CRED-KEY]",a="[REDACTED-CP7-KEY]",c=p=>r.some(h=>p.includes(h)),l=(p,h)=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(h)?`${p}.${h}`:`${p}['${h.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}']`,d=(p,h)=>{if(typeof p=="string"){if(r.length===0)return p;let f=p,m=!1;for(let g of r)f.includes(g)&&(f=f.split(g).join(o),m=!0);return m&&n.push(h),f}if(Array.isArray(p))return p.map((f,m)=>d(f,`${h}[${m}]`));if(p!==null&&typeof p=="object"){let f=Object.create(null),m=0,g=0;for(let[w,v]of Object.entries(p))if(r.length>0&&c(w)){m+=1;let b=`${s}-${m}`,E=l(h,b);n.push(E),f[b]=d(v,E)}else if(z_(w)){g+=1;let b=`${a}-${g}`,E=l(h,b);i.push({field:E,patternClass:"secret_object_key"}),f[b]=d(v,E)}else f[w]=d(v,l(h,w));return f}return p};return{body:d(t,"$"),leakedPaths:n,keyScrubs:i}}var VR,zs,Uae,XD=D(()=>{"use strict";VR=require("node:crypto");jR();ue();Ll();zs=class extends Error{constructor(r){super(r);this.reason=r;this.name="CanonicalRejectError"}},Uae=/^[A-Za-z0-9._:/-]{1,200}$/});function YR(){return yd.upstreamBaseUrl+yd.upstreamPath}var jae,yd,XR,QR,ZR,eA=D(()=>{"use strict";jae="0.144.4",yd={upstreamBaseUrl:"https://chatgpt.com/backend-api/codex",upstreamPath:"/responses",synthesizedHeaders:{"content-type":"application/json",originator:"codex_cli_rs","user-agent":`codex_cli_rs/${jae}`},assumeSseOn200:!0};XR="https://auth.openai.com/oauth/token",QR="app_EMoamEEZ73f0CkXaXp7hrann",ZR="application/x-www-form-urlencoded"});function W2(t){try{let e=new URL(t);return`${e.protocol}//${e.host}${e.pathname}`}catch{return"<unparseable-url>"}}async function Jae(t,e){let r=t.body;if(!r||typeof r.getReader!="function"){let s=await t.text();return Buffer.byteLength(s,"utf8")>e?{rawBody:"",oversized:!0}:{rawBody:s,oversized:!1}}let n=r.getReader(),i=[],o=0;try{for(;;){let{done:s,value:a}=await n.read();if(s)break;if(!(!a||a.byteLength===0)){if(o+a.byteLength>e)return await n.cancel().catch(()=>{}),{rawBody:"",oversized:!0};o+=a.byteLength,i.push(a)}}}catch{return await n.cancel().catch(()=>{}),{rawBody:"",oversized:!0}}return{rawBody:Buffer.concat(i.map(s=>Buffer.from(s)),o).toString("utf8"),oversized:!1}}function QD(t){let e=new URLSearchParams;return e.set("grant_type","refresh_token"),e.set("refresh_token",t),e.set("client_id",QR),e.toString()}async function tA(t,e,r={}){let n=(r.now?.()??new Date).toISOString(),i;try{i=await e.post({url:XR,body:QD(t.refresh_token),contentType:ZR,signal:r.signal})}catch{return{kind:"transient",reason:"transport_error"}}if(i.status===200){let a=U2(i,!1);if(a&&typeof a.access_token=="string"&&a.access_token.length>0){let c={access_token:a.access_token,refresh_token:typeof a.refresh_token=="string"&&a.refresh_token.length>0?a.refresh_token:t.refresh_token,account_id:t.account_id,last_refresh:n},l=typeof a.id_token=="string"&&a.id_token.length>0?a.id_token:t.id_token;return l!==void 0&&(c.id_token=l),{kind:"rotated",bundle:c}}return{kind:"transient",reason:"malformed_success"}}let o=U2(i,!0),s=typeof o?.error=="string"?o.error:void 0;return s==="invalid_grant"?(y.warn("[oauth-refresh] permanent refresh failure (invalid_grant)"),{kind:"permanent",reason:"invalid_grant"}):(y.warn(`[oauth-refresh] transient refresh failure (status=${i.status})`),{kind:"transient",reason:s??`status_${i.status}`})}function U2(t,e){if(t.oversized||e&&(!t.contentType||!t.contentType.includes("application/json"))||!t.rawBody||t.rawBody.length===0)return null;try{let r=JSON.parse(t.rawBody);return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}var Vae,zae,Ah,ZD=D(()=>{"use strict";ue();eA();Vae=64*1024,zae=3e4,Ah=class{constructor(e={}){this.opts=e}async post(e){let r=this.opts.fetchFn??fetch,n=this.opts.timeoutMs??zae,i=new AbortController,o=setTimeout(()=>i.abort(),n),s=()=>i.abort();e.signal&&(e.signal.aborted?i.abort():e.signal.addEventListener("abort",s,{once:!0}));try{let a=await r(e.url,{method:"POST",headers:{"content-type":e.contentType},body:e.body,redirect:"error",signal:i.signal}),{rawBody:c,oversized:l}=await Jae(a,Vae);return y.debug(`[oauth-refresh] POST ${W2(e.url)} -> ${a.status}`),{status:a.status,rawBody:c,contentType:(a.headers.get("content-type")??void 0)?.toLowerCase(),oversized:l}}catch(a){throw y.warn(`[oauth-refresh] transport error POSTing ${W2(e.url)}`,{code:a?.code}),new Error("oauth refresh transport error")}finally{clearTimeout(o),e.signal&&e.signal.removeEventListener("abort",s)}}}});function tce(){return{status:200,body:{models:ece.map(t=>({slug:t.slug,display_name:t.displayName,description:"CodeVibe broker compatibility model metadata.",default_reasoning_level:"medium",supported_reasoning_levels:Zae,shell_type:"shell_command",visibility:t.slug==="codex-auto-review"?"hide":"list",supported_in_api:t.supportedInApi,priority:t.priority,additional_speed_tiers:[],service_tiers:[],availability_nux:null,upgrade:null,base_instructions:"You are Codex, a coding agent.",model_messages:null,supports_reasoning_summaries:!1,default_reasoning_summary:"none",reasoning_summary_format:null,support_verbosity:!0,default_verbosity:"low",apply_patch_tool_type:"freeform",web_search_tool_type:"text",truncation_policy:{mode:"tokens",limit:1e4},supports_parallel_tool_calls:!0,supports_image_detail_original:!1,context_window:128e3,max_context_window:128e3,auto_compact_token_limit:null,comp_hash:null,effective_context_window_percent:95,experimental_supported_tools:[],input_modalities:["text"],supports_search_tool:!0,use_responses_lite:!1}))}}}function q2(t,e){return e.class==="oauth_bundle"?{authorization:`Bearer ${e.material.access_token}`,"ChatGPT-Account-Id":e.material.account_id}:t==="anthropic"?e.class==="subscription_token"?{authorization:`Bearer ${e.material}`}:{"x-api-key":e.material,authorization:`Bearer ${e.material}`}:{authorization:`Bearer ${e.material}`}}function rce(t,e){return t==="anthropic"&&e.startsWith("sk-ant-oat")?{class:"subscription_token",material:e}:{class:"api_key",material:e}}function nce(t){return t.class==="oauth_bundle"?[t.material.access_token,t.material.refresh_token]:[t.material]}function ice(t){return t.class==="oauth_bundle"?t.material.refresh_token:t.material}function oce(t,e,r){return`${t}-${e}-${r}`}function sce(t){let e=(o,s)=>Object.prototype.hasOwnProperty.call(o,s)?o[s]:void 0;if(t===void 0)return;if(typeof t=="string")return{kind:"string",bytes:t.length};if(t===null)return{kind:"null"};if(Array.isArray(t))return{kind:"array"};if(typeof t!="object")return{kind:typeof t};let r=e(t,"error");if(typeof r=="string")return{kind:"string-error",bytes:r.length};let n=r!==null&&typeof r=="object"&&!Array.isArray(r)?r:t,i={};for(let o of["message","type","code"]){let s=e(n,o);typeof s=="string"&&(i[o]=s.length)}return{kind:"object",nestedError:n!==t,fields:i}}var K2,j2,V2,z2,Yae,Xae,Qae,eN,Zae,ece,Ih,J2=D(()=>{"use strict";K2=require("node:crypto"),j2=N(require("node:http")),V2=require("node:stream"),z2=require("node:stream/promises");ue();VD();jR();JD();XD();Ll();uw();eA();ZD();Wh();jD();Yae=1500*1e3,Xae=5e3,Qae=12e4,eN=class extends V2.PassThrough{constructor(r,n){super({autoDestroy:!0});this.idleMs=r;this.onIdle=n;this.disarmed=!1}_construct(r){this.arm(),r()}_transform(r,n,i){this.arm(),i(null,r)}_destroy(r,n){this.disarm(),n(r)}arm(){this.disarmed||(this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(this.onIdle,this.idleMs),this.idleTimer.unref?.())}disarm(){this.disarmed=!0,this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=void 0)}},Zae=[{effort:"low",description:"Fast responses with lighter reasoning"},{effort:"medium",description:"Balances speed and reasoning depth for everyday tasks"},{effort:"high",description:"Greater reasoning depth for complex problems"},{effort:"xhigh",description:"Extra high reasoning depth for complex problems"}],ece=[{slug:"gpt-5.5",displayName:"GPT-5.5",priority:7,supportedInApi:!0},{slug:"gpt-5.4",displayName:"GPT-5.4",priority:16,supportedInApi:!0},{slug:"gpt-5.4-mini",displayName:"GPT-5.4-Mini",priority:23,supportedInApi:!0},{slug:"gpt-5.3-codex",displayName:"GPT-5.3-Codex",priority:26,supportedInApi:!0},{slug:"gpt-5.2",displayName:"GPT-5.2",priority:35,supportedInApi:!0},{slug:"codex-auto-review",displayName:"Codex Auto Review",priority:43,supportedInApi:!0}];Ih=class{constructor(e){this.tokenMinter=new Rh;this.server=null;this.boundAddr=null;this.upstreamKeys=new Map;this.issuanceIds=new Map;this.issuanceCounter=0;this.credentialGeneration=new Map;this.inflightRefresh=new Map;this.stopping=!1;this.lifecycleGeneration=0;this.ops=new Set;this.taskId=e.taskId,this.upstreamClient=e.upstreamClient,this.vendorKeyStore=e.vendorKeyStore??new Sn,this.auditSink=e.auditSink??new Sh,this.brokerId=`broker-${process.pid}-${Date.now()}`,this.refreshTransport=e.refreshTransport??new Ah,this.oauthLock=e.oauthLock,this.proactiveThresholdMs=e.proactiveRefreshThresholdMs??Yae,this.stopDrainTimeoutMs=e.stopDrainTimeoutMs??Xae,this.nowFn=e.now??Date.now,this.delayFn=e.delay??(r=>new Promise(n=>setTimeout(n,r)))}getOAuthLock(e){return this.oauthLock||(this.oauthLock=ra({lockDir:ta(`vendor-oauth-${e}`)})),this.oauthLock}async start(){this.tokenMinter.mint();let e=j2.createServer((n,i)=>{this.handleHttp(n,i)});await new Promise((n,i)=>{e.once("error",i),e.listen(0,"127.0.0.1",()=>{e.removeListener("error",i),n()})});let r=e.address();return this.server=e,this.boundAddr=`127.0.0.1:${r.port}`,y.info(`[Broker] Started model gateway on ${this.boundAddr}`,{taskId:this.taskId}),{hostBrokerAddr:this.boundAddr}}async healthz(){return this.server!==null}async stop(){let e=!this.stopping;this.stopping=!0,e&&(this.lifecycleGeneration+=1);let r=[...this.ops];r.length>0&&await Promise.race([Promise.allSettled(r.map(i=>i.done)),this.delayFn(this.stopDrainTimeoutMs)]);let n=[...this.ops];for(let i of n)try{i.controller.abort()}catch{}if(await Promise.allSettled(n.map(i=>i.done)),this.upstreamKeys.clear(),this.credentialGeneration.clear(),this.inflightRefresh.clear(),this.tokenMinter.clear(),this.server){let i=this.server;this.server=null,this.boundAddr=null,await new Promise(o=>i.close(()=>o()))}y.info("[Broker] Stopped + zeroized upstream credentials",{taskId:this.taskId})}registerOp(){let e,r=new Promise(i=>{e=i}),n={controller:new AbortController,done:r,resolveDone:e,lifecycleGen:this.lifecycleGeneration};return this.ops.add(n),n}deregisterOp(e){this.ops.delete(e),e.resolveDone()}isStale(e){return this.lifecycleGeneration!==e.lifecycleGen}currentBrokerToken(){return this.tokenMinter.get()}rotateBrokerToken(){return this.server===null?null:this.tokenMinter.rotateWithGrace()}commitBrokerTokenRotation(e){this.tokenMinter.commitRotation(e)}rollbackBrokerTokenRotation(e){this.tokenMinter.rollbackRotation(e)}getVendorKey(e){return this.vendorKeyStore.getVendorKey(e)}setVendorKey(e,r){return this.vendorKeyStore.setVendorKey(e,r)}clearVendorKey(e){return this.vendorKeyStore.clearVendorKey(e)}getVendorOAuthBundle(e){return this.vendorKeyStore.getVendorOAuthBundle(e)}setVendorOAuthBundle(e,r){return this.vendorKeyStore.setVendorOAuthBundle(e,r)}clearVendorOAuthBundle(e){return this.vendorKeyStore.clearVendorOAuthBundle(e)}async handle(e,r){let n=fw.find(o=>o.method===e.method&&o.path===e.path);if(!n)return{status:403,body:{error:"forbidden"}};if(n.path==="/healthz")return{status:200,body:{ok:!0}};if(n.path==="/models"||n.path==="/v1/models")return tce();if(!this.tokenMinter.authenticate(e.brokerToken))return{status:401,body:{error:"invalid broker token"}};let i=KR(e.path);return i?this.gateway(i,e,r):{status:403,body:{error:"forbidden"}}}async gateway(e,r,n){let i=this.registerOp(),o={signal:i.controller.signal,lifecycleGen:i.lifecycleGen};try{return this.stopping?{status:503,body:{error:"broker stopping"}}:await this.gatewayInner(e,r,o,i,n)}finally{this.deregisterOp(i)}}async gatewayInner(e,r,n,i,o){let s=await this.loadVendorCredential(e,n);if(s===null)return{status:503,body:{error:"no upstream credential"}};if(s.class==="oauth_bundle"&&this.isProactiveDue(s.material)){let v=await this.refreshOAuth(e,n,"proactive");if(v.kind==="rotated"||v.kind==="adopted")s={class:"oauth_bundle",material:v.bundle};else{if(v.kind==="revoked")return{status:503,body:{error:"no upstream credential"}};if(v.kind==="permanent")return this.permanentRefreshResponse()}}let a;try{a=zR({provider:e,request:r,agentHeaders:r.agentHeaders,agentQuery:r.agentQuery,agentContentType:r.agentContentType})}catch(v){if(v instanceof zs)return{status:400,body:{error:v.reason}};throw v}let{modelCallId:c,requestSha256:l}=a,d=[...nce(s),...this.tokenMinter.acceptedValues()],u=JR(a.body,d),p=oS(u.body);for(let v of u.leakedPaths)if(!await this.emitGated("model_context_scrubbed",{model_call_id:c,field:v,pattern_class:"self_credential"}))return{status:503,body:{error:"audit unavailable"}};for(let v of u.keyScrubs)if(!await this.emitGated("model_context_scrubbed",{model_call_id:c,field:v.field,pattern_class:v.patternClass}))return{status:503,body:{error:"audit unavailable"}};for(let v of p.findings)if(!await this.emitGated("model_context_scrubbed",{model_call_id:c,field:v.field,pattern_class:v.patternClass}))return{status:503,body:{error:"audit unavailable"}};if(!await this.emitGated("model_call",{agent:e,model:this.extractModel(p.scrubbed),model_call_id:c,request_sha256:l,credential_issuance_id:this.lastIssuanceId(e)}))return{status:503,body:{error:"audit unavailable"}};let f=this.genOf(e),m=s,g=this.buildUpstreamTarget(e,m,a.headers,a.upstreamUrl),w=!1;try{for(;;){let v=await this.upstreamClient.post({url:g.url,headers:g.headers,body:p.scrubbed,signal:n.signal}),b=(v.headers["content-type"]??"").toLowerCase().trim(),E=b.length===0,A=b.startsWith("text/event-stream"),k=g.assumeSseOn200,R=v.status===200&&!!o&&(A||E&&k);if(y.info("[Broker] forward decision",{taskId:this.taskId,modelCallId:c,status:v.status,ctAbsent:E,isSse:A,assumeSse:k,decision:R?"streamed":"buffered"}),R&&o)return await this.streamForward(v,o,n,i,c);let S=await v.readText(),T;try{T=S.length?JSON.parse(S):void 0}catch{T=void 0}if(!w&&m.class==="oauth_bundle"&&v.status===401){w=!0;let O=await this.refreshOAuth(e,n,"reactive",f);if(O.kind==="rotated"||O.kind==="adopted"){m={class:"oauth_bundle",material:O.bundle},g=this.buildUpstreamTarget(e,m,a.headers,a.upstreamUrl);continue}if(O.kind==="permanent"){let _=this.permanentRefreshResponse();return await this.emitBestEffort("model_call_result",{model_call_id:c,result:"refresh_permanent"}),_}if(O.kind==="revoked"){let _={status:503,body:{error:"no upstream credential"}};return await this.emitBestEffort("model_call_result",{model_call_id:c,result:"revoked"}),_}}let P=this.mapUpstream({status:v.status,body:T});return await this.emitBestEffort("model_call_result",{model_call_id:c,result:P.status===200?"ok":`upstream_${v.status}`,...this.extractUsage(T)}),P}}catch{let v={status:502,body:{error:"upstream forward failed"}};return await this.emitBestEffort("model_call_result",{model_call_id:c,result:"forward_error"}),v}}async streamForward(e,r,n,i,o){let s,a;try{s=e.bodyStream();let c=(e.headers["content-type"]??"").trim();return r.writeHead(200,{"content-type":c.length?e.headers["content-type"]:"text/event-stream"}),a=new eN(Qae,()=>i.controller.abort()),await(0,z2.pipeline)(s,a,r,{signal:n.signal}),await this.emitBestEffort("model_call_result",{model_call_id:o,result:"ok_streamed",usageSource:"unavailable_streamed"}),{kind:"handled"}}catch(c){return a?.destroy(),s&&(s.on("error",()=>{}),s.destroy()),i.controller.abort(),r.headersSent?(r.destroy(),y.warn("[Broker] streaming forward failed after headers sent",{errorShape:c instanceof Error?{name:c.name}:{kind:typeof c}}),await this.emitBestEffort("model_call_result",{model_call_id:o,result:"stream_error",usageSource:"unavailable_streamed"}),{kind:"handled"}):(await this.emitBestEffort("model_call_result",{model_call_id:o,result:"forward_error",usageSource:"unavailable_streamed"}),{status:502,body:{error:"upstream forward failed"}})}}buildUpstreamTarget(e,r,n,i){if(r.class==="oauth_bundle"){let s={...n,...yd.synthesizedHeaders,...q2(e,r)};return{url:YR(),headers:s,assumeSseOn200:yd.assumeSseOn200}}let o={...n,...q2(e,r)};if(e==="anthropic"&&r.class==="subscription_token"){let s=o["anthropic-beta"];o["anthropic-beta"]=s?s.includes("oauth-2025-04-20")?s:`${s},oauth-2025-04-20`:"oauth-2025-04-20"}return{url:i,headers:o,assumeSseOn200:!1}}async loadVendorCredential(e,r){let n=this.upstreamKeys.get(e);if(n!==void 0)return n;let i=await this.vendorKeyStore.getVendorKey(e),o=null;if(i!==null)o=rce(e,i);else if(e==="openai"){let a=await this.vendorKeyStore.getVendorOAuthBundle(e);a&&(o={class:"oauth_bundle",material:a})}if(o===null)return null;if(this.isStale(r)||this.stopping)return o;this.upstreamKeys.set(e,o),o.class==="oauth_bundle"&&!this.credentialGeneration.has(e)&&this.credentialGeneration.set(e,0),this.issuanceCounter+=1;let s=oce(this.brokerId,e,this.issuanceCounter);return this.issuanceIds.set(e,s),await this.emitBestEffort("broker_credential_loaded",{provider:e,key_fingerprint:(0,K2.createHash)("sha256").update(ice(o)).digest("hex").slice(0,16),credential_issuance_id:s}),o}genOf(e){return this.credentialGeneration.get(e)??0}currentBundle(e){let r=this.upstreamKeys.get(e);return r&&r.class==="oauth_bundle"?r.material:null}isProactiveDue(e){let r=Date.parse(e.last_refresh);return Number.isNaN(r)?!1:this.nowFn()-r>=this.proactiveThresholdMs}adoptBundle(e,r,n){this.isStale(n)||this.stopping||(this.upstreamKeys.set(e,{class:"oauth_bundle",material:r}),this.credentialGeneration.set(e,this.genOf(e)+1))}async refreshOAuth(e,r,n,i){if(n==="reactive"&&i!==void 0&&i<this.genOf(e)){let s=this.currentBundle(e);return s?{kind:"adopted",bundle:s}:{kind:"transient",reason:"gen_advanced_but_absent"}}let o=this.inflightRefresh.get(e);return o||(o=this.doRefreshUnderLock(e,r).finally(()=>{this.inflightRefresh.delete(e)}),this.inflightRefresh.set(e,o)),o}async doRefreshUnderLock(e,r){let n=this.getOAuthLock(e),i;try{i=await n.acquire()}catch{return{kind:"transient",reason:"lock_unavailable"}}try{let o=await this.vendorKeyStore.getVendorOAuthBundle(e);if(!o)return{kind:"revoked",reason:"cleared"};let s=this.currentBundle(e);if(s&&o.access_token!==s.access_token)return this.adoptBundle(e,o,r),{kind:"adopted",bundle:o};let a=await tA(o,this.refreshTransport,{signal:r.signal});return a.kind==="permanent"?{kind:"permanent",reason:a.reason}:a.kind==="transient"?{kind:"transient",reason:a.reason}:this.isStale(r)||this.stopping?{kind:"transient",reason:"stopping"}:await i.reassertOwnership()?this.isStale(r)||this.stopping?{kind:"transient",reason:"stopping"}:(await this.vendorKeyStore.setVendorOAuthBundle(e,a.bundle),this.adoptBundle(e,a.bundle,r),{kind:"rotated",bundle:a.bundle}):{kind:"transient",reason:"ownership_lost"}}finally{await i.release()}}lastIssuanceId(e){return this.issuanceIds.get(e)??""}permanentRefreshResponse(){return{status:502,body:{error:"upstream auth failed",remediation:"re-run: codevibe vendor-key import-codex"}}}mapUpstream(e){return e.status!==200&&y.warn("[Broker] upstream non-200",{status:e.status,errorShape:sce(e.body)}),e.status===401||e.status===403?{status:502,body:{error:"upstream auth failed"}}:e.status===200?{status:200,body:e.body}:{status:502,body:{error:`upstream_${e.status}`}}}extractModel(e){if(e!==null&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"model")){let r=e.model;if(typeof r=="string")return r}return"unknown"}extractUsage(e){if(e===null||typeof e!="object")return{};let r=e.usage;if(r===null||typeof r!="object")return{};let n=r,i={};return typeof n.input_tokens=="number"&&(i.prompt_tokens=n.input_tokens),typeof n.output_tokens=="number"&&(i.completion_tokens=n.output_tokens),typeof n.prompt_tokens=="number"&&(i.prompt_tokens=n.prompt_tokens),typeof n.completion_tokens=="number"&&(i.completion_tokens=n.completion_tokens),i}async emitGated(e,r){try{return"ack"in await this.auditSink.emit(e,r)}catch{return!1}}async emitBestEffort(e,r){try{await this.auditSink.emit(e,r)}catch{}}async handleHttp(e,r){try{let n=e.method??"GET",i=new URL(e.url??"/","http://127.0.0.1"),o=i.pathname,s={};for(let[p,h]of Object.entries(e.headers))typeof h=="string"?s[p.toLowerCase()]=h:Array.isArray(h)&&(s[p.toLowerCase()]=h.join(","));let a={};for(let[p,h]of i.searchParams.entries())a[p]=h;let c=this.extractBrokerToken(s),l,d=!1;if(n==="POST"){let p=await this.readBody(e);if(p.length>0)try{l=JSON.parse(p)}catch{d=!0}}if(d&&fw.some(p=>p.method===n&&p.path===o)){this.writeJson(r,400,{error:"malformed JSON body"});return}let u=await this.handle({method:n,path:o,brokerToken:c,body:l,agentHeaders:s,agentQuery:a,agentContentType:s["content-type"]},r);if("kind"in u)return;this.writeJson(r,u.status,u.body)}catch(n){y.error("[Broker] HTTP handler error",{error:n instanceof Error?n.message:String(n)}),r.headersSent?r.destroy():this.writeJson(r,502,{error:"broker internal error"})}}extractBrokerToken(e){if(e["x-api-key"])return e["x-api-key"];let r=e.authorization;if(r&&r.toLowerCase().startsWith("bearer "))return r.slice(7).trim()}readBody(e){return new Promise((r,n)=>{let i=[];e.on("data",o=>i.push(o)),e.on("end",()=>r(Buffer.concat(i).toString("utf8"))),e.on("error",n)})}writeJson(e,r,n){let i=JSON.stringify(n??{});e.writeHead(r,{"content-type":"application/json"}),e.end(i)}}});function Y2(t){try{let e=new URL(t);return`${e.protocol}//${e.host}${e.pathname}`}catch{return"<unparseable-url>"}}var tN,ace,Th,X2=D(()=>{"use strict";tN=require("node:stream");ue();ace=12e4;Th=class{constructor(e={}){this.opts=e}async post(e){let r=this.opts.fetchFn??fetch,n=this.opts.timeoutMs??ace,i=new AbortController,o=setTimeout(()=>i.abort(),n),s=e.signal,a=()=>i.abort();s&&(s.aborted?i.abort():s.addEventListener("abort",a,{once:!0}));let c=!1,l=()=>{c||(c=!0,s&&s.removeEventListener("abort",a))},d;try{d=await r(e.url,{method:"POST",headers:{...e.headers},body:JSON.stringify(e.body),redirect:"error",signal:i.signal})}catch(m){throw clearTimeout(o),l(),y.warn(`[UpstreamClient] transport error POSTing ${Y2(e.url)}`,{code:m?.code}),new Error("upstream transport error")}clearTimeout(o),y.debug(`[UpstreamClient] POST ${Y2(e.url)} -> ${d.status}`);let u={};d.headers.forEach((m,g)=>{u[g.toLowerCase()]=m});let p=d,h=!1,f=()=>{if(h)throw new Error("UpstreamResult body already consumed (bodyStream/readText are one-shot; LOCK #643-1)");h=!0};return{status:p.status,headers:u,bodyStream(){if(f(),p.body===null)return l(),tN.Readable.from([]);let m=tN.Readable.fromWeb(p.body);return m.once("close",l),m},async readText(){f();let m=setTimeout(()=>i.abort(),n);s?.aborted&&i.abort();try{return await p.text()}catch{throw new Error("upstream transport error")}finally{clearTimeout(m),l()}}}}}});var rN={};lr(rN,{BROKER_ROUTES:()=>fw,BrokerTokenMinter:()=>Rh,CHATGPT_OAUTH_CLIENT_ID:()=>QR,CHATGPT_REFRESH_CONTENT_TYPE:()=>ZR,CHATGPT_TOKEN_ENDPOINT:()=>XR,CHATGPT_UPSTREAM_CONFIG:()=>yd,CanonicalRejectError:()=>zs,FetchRefreshTransport:()=>Ah,FetchUpstreamClient:()=>Th,KeychainVendorKeyStore:()=>Sn,LocalModelGatewayBroker:()=>Ih,OAuthAccountLock:()=>Hh,StubStrictAuditSink:()=>Sh,buildCanonicalRequest:()=>zR,buildRefreshBody:()=>QD,chatGptUpstreamUrl:()=>YR,createOAuthAccountLock:()=>ra,defaultOAuthLockDir:()=>ta,getProviderConfig:()=>Eh,providerForPath:()=>KR,refreshOAuthToken:()=>tA,requestSha256:()=>YD,scrubRequestBody:()=>oS,selfCredentialGuard:()=>JR});var rA=D(()=>{"use strict";jD();J2();X2();VD();uw();JD();eA();ZD();Wh();XD();Ll();jR()});function nA(t){let e={},r=process.execPath.slice(0,process.execPath.lastIndexOf("/"));e.PATH=`${t.path??yw}:${r}`,e.HOME=t.sandboxHome;let n=t.safeSource??{};for(let i of gw){let o=n[i];typeof o=="string"&&o.length>0&&(e[i]=o)}return t.provider==="anthropic"?e.ANTHROPIC_BASE_URL=t.sandboxBrokerUrl:e.OPENAI_BASE_URL=`${t.sandboxBrokerUrl.replace(/\/+$/,"")}/v1`,t.provider==="anthropic"?(e.CLAUDE_CONFIG_DIR=t.sandboxBootstrapDir,e.CLAUDE_CODE_TMPDIR=t.claudeScratchDir??t.sandboxBootstrapDir):e.CODEX_HOME=t.sandboxBootstrapDir,e}function ww(t){let e=new Set(["ANTHROPIC_BASE_URL","OPENAI_BASE_URL"]);for(let r of Object.keys(t))if(!e.has(r)){for(let n of cce)if(n.test(r))throw new Error(`sanitizedEnv I1 violation: credential-shaped key "${r}" present in the agent env \u2014 refusing to launch (allow-list bug)`)}}var gw,yw,cce,nN=D(()=>{"use strict";gw=["LANG","LC_ALL","LC_CTYPE","TERM","TZ"],yw="/usr/local/bin:/usr/bin:/bin";cce=[/^ANTHROPIC_API_KEY$/i,/^ANTHROPIC_AUTH_TOKEN$/i,/^OPENAI_API_KEY$/i,/_API_KEY$/i,/_SECRET$/i,/_SECRET_ACCESS_KEY$/i,/^AWS_/i,/^GH_TOKEN$/i,/^GITHUB_TOKEN$/i,/^GOOGLE_/i,/_TOKEN$/i,/^SSH_/i]});function oN(t){return t==="CLAUDE"?"anthropic":t==="CODEX"?"openai":null}function iN(t,e){if(t===e)return!0;let r=Er.relative(e,t);return r.length>0&&!r.startsWith("..")&&!Er.isAbsolute(r)}function pce(t){let e=t.split(Er.sep);for(let i=e.length-2;i>=0;i--)if(e[i]===uce&&e[i+1]===dce){let o=[...e];return o[i+1]=lce,Er.join(o.join(Er.sep),Q2)}let r=Er.dirname(t),n=Er.basename(t);return Er.join(r,".codevibe-audit",n,Q2)}async function hce(t,e){let r;try{r=await wd.promises.realpath(e)}catch{throw new Error(`CP-7 W3: cannot realpath workdir "${e}" \u2014 refusing to launch (audit containment fail-closed)`)}let n=Er.dirname(t);await wd.promises.mkdir(n,{recursive:!0});let i;try{i=await wd.promises.realpath(n)}catch{throw new Error(`CP-7 W3: cannot realpath audit dir "${n}" \u2014 refusing to launch (fail-closed)`)}let o=Er.join(i,Er.basename(t)),s;try{s=await wd.promises.lstat(o)}catch{s=void 0}let a=o;if(s?.isSymbolicLink())try{a=await wd.promises.realpath(o)}catch{throw new Error(`CP-7 W3: audit leaf "${o}" is a symlink that does not resolve (dangling) \u2014 refusing to launch (fail-closed). The audit file must be a regular file in the sibling .codevibe/audit/ tree.`)}if(iN(i,r)||iN(o,r)||iN(a,r))throw new Error(`CP-7 W3: audit path "${o}" (resolved target "${a}") is inside the agent workdir "${r}" \u2014 the agent could truncate/forge the forensic record (Stage-1 r1 HIGH fail-closed). The audit MUST live in the sibling .codevibe/audit/ tree, never under .codevibe/state/<group>/<track>/.`);return o}async function Ph(t){if(t.webBrowsingActive)return{mode:"reduced_trust",reducedTrust:!0,reducedTrustReason:`Agent web browsing active for ${t.agentKind} \u2014 running in reduced-trust mode with shadow-diff capture and guarded web tools`,teardown:async()=>{}};let e=oN(t.agentKind);if(e===null)return t.requireConfined?fce(t):{mode:"reduced_trust",reducedTrust:!0,reducedTrustReason:`${t.agentKind} is a reduced-trust agent (\xA76 Q4) \u2014 no vendor broker; runs on the legacy spawn path with shadow-diff capture`,teardown:async()=>{}};let r=await Jl(t.ladderDeps);if(r.tier==="reduced_trust")return{mode:"reduced_trust",reducedTrust:!0,reducedTrustReason:r.reducedTrustReason,teardown:async()=>{}};let n,i=null;if(t.brokerDeps?.auditSink)n=t.brokerDeps.auditSink;else{let w=t.auditPath??pce(t.workdir),v=await hce(w,t.workdir);i=Er.dirname(v),n=new _l(t.taskId,v)}let o=t.upstreamClient??new Th,s=(t.makeBroker??(w=>new Ih(w)))({taskId:t.taskId,upstreamClient:o,...t.brokerDeps?.vendorKeyStore?{vendorKeyStore:t.brokerDeps.vendorKeyStore}:{},auditSink:n}),a;try{({hostBrokerAddr:a}=await s.start())}catch(w){let v=Object.assign(new Error("CP-7: broker failed to start \u2014 refusing to launch the implementor (fail-closed)"),{cause:w});try{await s.stop()}catch(b){throw Object.assign(new Error("CP-7: broker start failed and cleanup also failed"),{causes:[v,b]})}throw v}let c=s.currentBrokerToken();if(!c){let w=new Error("CP-7: broker minted no token \u2014 refusing to launch (fail-closed)");try{await s.stop()}catch(v){throw Object.assign(new Error("CP-7: broker minted no token and cleanup also failed"),{causes:[w,v]})}throw w}let l=c.value,d=r.tier==="docker"?`http://127.0.0.1:${Hp}`:`http://${a}`,u=r.tier==="docker"?fy:t.workdir,p=r.tier==="docker"?Vv:null,h=r.tier==="docker"?JP:null,f,m,g;try{f=await Hu.create({provider:e,sandboxBrokerUrl:d,initialToken:l,...p!==null?{sandboxDir:p,sandboxConfigDir:h??JP}:{sandboxDirEqualsHostDir:!0,configDirEqualsHostDir:!0},hostRoot:t.bootstrapHostRoot,...r.tier==="sandbox_exec"&&e==="anthropic"?{claudeScratchHostRoot:t.claudeScratchHostRoot??"/tmp"}:{},workdir:t.workdir,...t.workdirAuthority?{workdirAuthority:t.workdirAuthority}:{}});let w=p!==null?{hostDir:f.hostDir,sandboxDir:p}:{hostDir:f.hostDir,sandboxDir:f.hostDir},v=h!==null?{hostDir:f.configHostDir,sandboxDir:h}:{hostDir:f.configHostDir,sandboxDir:f.configHostDir},b=f.claudeScratchSpec,E=nA({provider:e,sandboxBrokerUrl:d,sandboxHome:u,sandboxBootstrapDir:v.sandboxDir,...b!==null?{claudeScratchDir:b.sandboxDir}:{},safeSource:t.localeSource});ww(E);let A=xP(t.role,E,t.processTreeId),k={isolationTech:r.tier==="docker"?"docker":"sandbox_exec",workdir:t.workdir,...t.workdirAuthority?{workdirAuthority:t.workdirAuthority}:{},hostBrokerAddr:a,sandboxBrokerUrl:d,taskId:t.taskId,sanitizedEnv:A,agentBootstrap:w,agentConfig:v,...b!==null?{agentScratch:b}:{},...i!==null?{auditDir:i}:{}};m=await r.substrate.launch(k),y.info(`[CP-7] Substrate engaged (tier=${r.tier}, egress=${m.egressFidelity}) \u2014 agent is creditless, broker holds the key`,{taskId:t.taskId,agent:t.agentKind});let R=f,S=m,T=s,P=null,O,_=()=>O||(O=(async()=>{P&&(clearInterval(P),P=null);let q=[];for(let z of[()=>S.teardown(),()=>T.stop(),()=>R.destroy()])try{await z()}catch(U){q.push(U)}if(q.length>0)throw y.warn("[CP-7] substrate cleanup failed \u2014 task cannot pass",{taskId:t.taskId,failureCount:q.length,..._r(q[0])}),q.length===1?q[0]:Object.assign(new Error("CP-7 substrate cleanup failed"),{causes:q})})(),O);g=_;let x=`launch-${t.taskId}-${Date.now()}`,C=S.egressFidelity==="strict"?"structural_deny_network_none":"coarse_loopback_only",H;try{H=await n.emit("egress_denied",{destination:"*",protocol:"all",denial_reason:C,caller_event_id:x})}catch(q){throw Object.assign(new Error("CP-7 W3: egress-posture audit emit failed \u2014 refusing to launch the creditless agent (audit-before-effect fail-closed)"),{cause:q})}if(!("ack"in H))throw new Error("CP-7 W3: egress-posture audit was rejected \u2014 refusing to launch the creditless agent (no durable egress posture \u2192 no agent)");let G=t.tokenRefreshIntervalMs??600*1e3,F=null,L=async()=>{if(!(typeof T.rotateBrokerToken=="function"&&typeof T.commitBrokerTokenRotation=="function"&&typeof T.rollbackBrokerTokenRotation=="function")){let U=T.currentBrokerToken();U&&await R.refresh(U.value);return}let z=T.rotateBrokerToken();if(z)try{await R.refresh(z.token.value),T.commitBrokerTokenRotation(z)}catch(U){T.rollbackBrokerTokenRotation(z),y.warn("[CP-7] broker-token refresh write FAILED \u2014 rolled back to the prior token and tearing down (fail-closed)",{taskId:t.taskId,..._r(U)});let V=Object.assign(new Error("CP-7 broker-token refresh failed"),{cause:U});try{await _()}catch(ee){throw Object.assign(new Error("CP-7 broker-token refresh failed and cleanup also failed"),{causes:[V,ee]})}throw V}},W=async()=>{let z=(F??Promise.resolve()).catch(()=>{}).then(()=>L());F=z;try{await z}finally{F===z&&(F=null)}};return G>0&&(P=setInterval(()=>{W().catch(()=>{})},G),P.unref?.()),{mode:"substrate",tier:r.tier,reducedTrust:r.reducedTrust,reducedTrustReason:r.tier==="sandbox_exec"?r.reducedTrustReason:void 0,substrateHandle:S,agentConfigDir:v.sandboxDir,finalEnv:A,refreshBrokerToken:W,teardown:_}}catch(w){let v=w instanceof Error?w:new Error("CP-7 substrate launch failed"),b=[];if(g)try{await g()}catch(E){b.push(E)}else for(let E of[...m?[()=>m.teardown()]:[],...f?[()=>f.destroy()]:[],()=>s.stop()])try{await E()}catch(A){b.push(A)}throw b.length>0?(y.warn("[CP-7] failed launch also failed cleanup",{taskId:t.taskId,failureCount:b.length,..._r(b[0])}),Object.assign(new Error("CP-7 substrate launch failed and cleanup also failed"),{causes:[v,...b]})):v}}async function fce(t){let e=t.agentKind;if(e!=="GEMINI"&&e!=="ANTIGRAVITY")throw new Error(`engageWriteConfinedResolverSandbox: unmapped broker-less agent ${e}`);let r=await Jl(t.ladderDeps);if(r.tier==="reduced_trust")return{mode:"reduced_trust",reducedTrust:!0,reducedTrustReason:`${e} resolver confinement unavailable \u2014 no sandbox substrate on this host (${r.reducedTrustReason}); the requireConfined spawn fail-closes to the human gate`,teardown:async()=>{}};if(r.tier==="docker")return{mode:"reduced_trust",reducedTrust:!0,reducedTrustReason:`${e} resolver confinement unavailable on the docker tier \u2014 the A1 image cannot carry the host-installed ${e} binary + its file-based auth; the requireConfined spawn fail-closes to the human gate`,teardown:async()=>{}};let n=Z2.homedir(),i=Er.join(n,...mce[e]);await wd.promises.mkdir(i,{recursive:!0}).catch(()=>{});let o={},s=process.execPath.slice(0,process.execPath.lastIndexOf("/"));o.PATH=`${yw}:${s}`,o.HOME=n;let a=t.localeSource??{};for(let u of gw){let p=a[u];typeof p=="string"&&p.length>0&&(o[u]=p)}ww(o);let c=xP(t.role,o,t.processTreeId),l={isolationTech:"sandbox_exec",workdir:t.workdir,...t.workdirAuthority?{workdirAuthority:t.workdirAuthority}:{},hostBrokerAddr:"",sandboxBrokerUrl:"",taskId:t.taskId,sanitizedEnv:c,agentConfig:{hostDir:i,sandboxDir:i},networkPosture:"open"},d=await r.substrate.launch(l);return y.info(`[A1d] Resolver-confinement row engaged (tier=sandbox_exec, egress=open) \u2014 writes fenced to the disposable workspace; ${e} runs on its own file-based auth (no broker)`,{taskId:t.taskId,agent:e}),{mode:"substrate",tier:"sandbox_exec",reducedTrust:!0,reducedTrustReason:`${e} class-2 resolver: write-confined to the disposable merge workspace (A5 Seatbelt); egress OPEN (broker-less \u2014 the agent dials its vendor directly with its own file-based auth)`,substrateHandle:d,agentConfigDir:i,finalEnv:c,refreshBrokerToken:async()=>{},teardown:async()=>{await d.teardown().catch(()=>{})}}}var wd,Z2,Er,lce,dce,uce,Q2,mce,ez=D(()=>{"use strict";wd=require("node:fs"),Z2=N(require("node:os")),Er=N(require("node:path"));rA();ST();Jk();ue();Lv();jS();qS();zv();VS();nN();lce="audit",dce="state",uce=".codevibe",Q2="audit.jsonl";mce={GEMINI:[".gemini"],ANTIGRAVITY:[".gemini","antigravity-cli"]}});function iA(t){return yce.has(t.toUpperCase())||wce.test(t)?!1:gce.some(e=>e.test(t))}function sN(t){return Object.keys(t).filter(iA)}function aN(t){let e={};for(let[r,n]of Object.entries(t))n!==void 0&&(iA(r)||(e[r]=n));return e[bw]="1",e}function oA(t={}){let e=t.platform??process.platform,r=t.env??process.env,n=t.exit??(u=>process.exit(u));if(e!=="darwin")return!1;let i=sN(r);if(i.length===0)return!1;if(r[bw])throw new Error(`[le-env-scrub] Refusing to launch the Local Executor: the scrub marker (${bw}) is set but credential-shaped env vars are still present (${i.join(", ")}). A genuine re-exec'd child has NO credential-shaped vars; this indicates a spoofed marker or a broken scrub. Fail closed (CP-7 I1, A5 parent-procargs vector) \u2014 never launch the LE with a vendor credential in its exec-time procargs.`);let o=t.spawnSyncFn??tz.spawnSync,s=t.execPath??process.execPath,a=t.argv??process.argv.slice(1),c=t.cwd??process.cwd(),l=aN(r);try{t.onScrub?.(i)}catch{}let d=o(s,a,{env:l,stdio:"inherit",cwd:c});return d.signal?n(1):n(d.status??1),!0}var tz,bw,gce,yce,wce,rz=D(()=>{"use strict";tz=require("node:child_process"),bw="CODEVIBE_LE_ENV_SCRUBBED",gce=[/^ANTHROPIC_/i,/^OPENAI_/i,/^GOOGLE_/i,/^GEMINI_/i,/^GH_TOKEN$/i,/^GITHUB_TOKEN$/i,/_API_KEY$/i,/_ACCESS_KEY_ID$/i,/_SECRET_ACCESS_KEY$/i,/_SECRET$/i,/_TOKEN$/i],yce=new Set(["ANTHROPIC_BASE_URL","OPENAI_BASE_URL","GOOGLE_BASE_URL"]),wce=/_BASE_URL$/i});var cN={};lr(cN,{ApiKeyBootstrap:()=>Hu,CODEX_PROVIDER_ID:()=>Tf,CP7_CANONICAL_FORM_VERSION:()=>L_,Cp7AuditWriter:()=>_l,GENESIS_PREV_HASH:()=>zk,HELPER_SCRIPT_NAME:()=>Kv,IMPLEMENTOR_CREDENTIAL_MISSING:()=>GC,ImplementorCredentialMissingError:()=>jl,LE_ENV_SCRUBBED_MARKER:()=>bw,REVIEWER_CREDENTIAL_MISSING:()=>iy,ReviewerCredentialMissingError:()=>Kl,SAFE_ENV_ALLOWLIST:()=>gw,SANDBOX_BOOTSTRAP_DIR:()=>Vv,SANDBOX_DEFAULT_PATH:()=>yw,TOKEN_FILE_NAME:()=>jv,assertImplementorVendorCredential:()=>cy,assertNoAmbientCreds:()=>ww,assertReviewerVendorCredential:()=>ay,buildSanitizedBaseEnv:()=>nA,buildScrubbedLeEnv:()=>aN,canonicalEntryBytes:()=>wg,canonicalJson:()=>kp,computeEntryHash:()=>Sp,engageSubstrate:()=>Ph,findCredShapedKeys:()=>sN,implementorProviderFor:()=>sy,isCredShapedEnvKey:()=>iA,providerForAgent:()=>oN,reviewerProviderFor:()=>oy,scrubLeEnvOrReexec:()=>oA,selectSubstrate:()=>Jl,verifyChain:()=>B_,withImplementorCredentialPreflight:()=>Vl,withReviewerCredentialPreflight:()=>$p});var sA=D(()=>{"use strict";ez();VS();nN();zv();HC();rz();Jk()});function vw(t,e,r){let n=Xc(e.prompt_template,"AntigravityReviewerProvider"),i=[];e.model_hint!==null&&i.push("--model",e.model_hint);let o=Math.max(1,Math.floor(e.timeout_ms/1e3)-5);i.push("--print-timeout",`${o}s`),i.push("--add-dir",r),i.push("--print",n);let s=we({...process.env,QUORUM_REVIEWER_SUBPROCESS:"1"});return{command:t,args:i,env:s}}async function bce(t,e,r,n){if(!r.exit_success){let a=Yl(r.stderr)??"spawn_failed";throw new Qe({kind:"spawn_failed",agent:t.agent,reason:`agy exited with non-zero status; stderr: ${r.stderr.trim()}`,failureReason:a})}let i=r.stdout,o={verdict_id:(0,nz.v4)(),gate_id:e,seat_id:t.seat_id,role:t.role,reviewer_agent:t.agent,model_used:t.model_hint,tokens_used:null,latency_ms:r.elapsed_ms,submitted_at:new Date().toISOString(),usage:Dt("provider_unsupported",r.elapsed_ms)};if(n!==void 0){let a=await n(i,{seatId:t.seat_id,role:t.role,agent:t.agent}),c=Jp(a,i);return{...o,...c}}let s=Ya(i);if(!s.ok)throw new Qe({kind:"parse_failure",agent:t.agent,raw_output:r.stdout});return{...o,verdict:s.verdict.kind,reasoning:s.verdict.reasoning,suggested_changes:s.verdict.suggested_changes,residual_observations:s.verdict.residual_observations}}var nz,xh,lN=D(()=>{"use strict";nz=require("uuid");Lu();Vp();Ja();jp();by();pa();tE();zp();Qt();xh=class{constructor(e={}){this.executable=e.executable??"agy"}async evaluate(e,r,n){if(e.agent!=="antigravity")throw new Error(`AntigravityReviewerProvider called with non-Antigravity spec (got ${e.agent}); the engine's registry wiring is responsible for dispatch`);if(n?.substrate!==void 0)throw new Qe({kind:"spawn_failed",agent:e.agent,reason:"AntigravityReviewerProvider received a substrate handle \u2014 agy is reduced-trust (never substrate-contained, \xA76 Q4); the loop must pre-route antigravity seats to the legacy path",failureReason:"spawn_failed"});let i=n?.workdir;if(i===void 0||i.length===0)throw new Qe({kind:"spawn_failed",agent:e.agent,reason:"AntigravityReviewerProvider requires opts.workdir (agy is workspace-centric \u2014 without --add-dir it cannot read the repo); the evaluate site must thread the loop workingDir",failureReason:"spawn_failed"});let o;try{o=vw(this.executable,e,i)}catch(a){throw new Qe({kind:"spawn_failed",agent:e.agent,reason:a instanceof Error?a.message:String(a),failureReason:"spawn_failed"})}let s;try{s=await qo({command:o.command,args:o.args,env:o.env,prompt:"",timeout_ms:e.timeout_ms})}catch(a){throw a instanceof Mr?new Qe(Yp(e.agent,a.detail)):a}return bce(e,r,s,n?.classifyVerdict)}}});function kw(t,e,r=!1){let n=[];n.push("--print"),n.push("--output-format","json"),n.push("--allowed-tools",e.tool_allowlist.join(",")),n.push("--tools",e.tool_allowlist.join(",")),n.push("--disallowed-tools","WebFetch,WebSearch,Agent,Task,Workflow,SendMessage,ListAgents"),n.push("--strict-mcp-config"),e.model_hint!==null&&n.push("--model",e.model_hint);let i=r?{}:we({...process.env,QUORUM_REVIEWER_SUBPROCESS:"1"});return{command:t,args:n,env:i}}async function vce(t,e,r,n){if(!r.exit_success){let c=Us(r.stdout)??Yl(r.stderr)??"spawn_failed";throw new Qe({kind:"spawn_failed",agent:t.agent,reason:`claude exited with non-zero status; stderr: ${r.stderr.trim()}`,failureReason:c})}let{text:i}=bo(r.stdout),o=Tc(r.stdout,r.elapsed_ms),s={verdict_id:(0,iz.v4)(),gate_id:e,seat_id:t.seat_id,role:t.role,reviewer_agent:t.agent,model_used:t.model_hint,tokens_used:o.totalTokens,latency_ms:r.elapsed_ms,submitted_at:new Date().toISOString(),usage:o};if(n!==void 0){let c=await n(i,{seatId:t.seat_id,role:t.role,agent:t.agent}),l=Jp(c,i);return{...s,...l}}let a=Ya(i);if(!a.ok)throw new Qe({kind:"parse_failure",agent:t.agent,raw_output:r.stdout});return{...s,verdict:a.verdict.kind,reasoning:a.verdict.reasoning,suggested_changes:a.verdict.suggested_changes,residual_observations:a.verdict.residual_observations}}var iz,_h,dN=D(()=>{"use strict";iz=require("uuid");Vp();Ja();jp();by();tE();zp();pa();Qt();_h=class{constructor(e={}){this.executable=e.executable??"claude"}async evaluate(e,r,n){if(e.agent!=="claude")throw new Error(`ClaudeReviewerProvider called with non-Claude spec (got ${e.agent}); the engine's registry wiring is responsible for dispatch`);let i=n?.substrate!==void 0,o=kw(this.executable,e,i),s;try{s=await qo({command:o.command,args:o.args,env:o.env,prompt:e.prompt_template,timeout_ms:e.timeout_ms,...n?.substrate!==void 0?{substrate:n.substrate}:{}})}catch(a){throw a instanceof Mr?new Qe(Yp(e.agent,a.detail)):a}return vce(e,r,s,n?.classifyVerdict)}}});function aA(){return new Sw().with("claude",new _h).with("codex",new Xp).with("antigravity",new xh)}var Sw,uN=D(()=>{"use strict";Ja();lN();dN();ky();Sw=class{constructor(){this.providers=new Map}with(e,r){return this.providers.set(e,r),this}register(e,r){this.providers.set(e,r)}providerFor(e){return this.providers.get(e)}registeredAgents(){return Array.from(this.providers.keys())}async evaluate(e,r,n){let i=this.providers.get(e.agent);if(i===void 0)throw new Qe({kind:"spawn_failed",agent:e.agent,reason:`no provider registered for ${e.agent} \u2014 registry was built without a ${e.agent} entry but the policy snapshot includes a ${e.agent} reviewer`});return i.evaluate(e,r,n)}}});function az(){return{schemaVersion:1,choice:"not_configured",artifactId:null,ollamaModel:null,updatedAt:new Date(0).toISOString()}}function kce(t=process.env){return t.NODE_ENV==="test"&&t.CODEVIBE_HOME_OVERRIDE?t.CODEVIBE_HOME_OVERRIDE:cA.default.join(sz.default.homedir(),".codevibe")}function Sce(t=process.env){return cA.default.join(kce(t),"local-model-state.json")}function oz(t){if(!t||typeof t!="object")return az();let e=t;return{schemaVersion:1,choice:e.choice==="skipped"||e.choice==="enabled"?e.choice:"not_configured",artifactId:typeof e.artifactId=="string"&&e.artifactId.trim()?e.artifactId:null,ollamaModel:typeof e.ollamaModel=="string"&&e.ollamaModel.trim()?e.ollamaModel:null,updatedAt:typeof e.updatedAt=="string"&&e.updatedAt?e.updatedAt:new Date(0).toISOString()}}async function hN(t=lA){return t.read()}async function mN(t,e=null,r=lA){await r.write({schemaVersion:1,choice:"enabled",artifactId:t,ollamaModel:e,updatedAt:new Date().toISOString()})}var Ew,sz,cA,pN,lA,fN=D(()=>{"use strict";Ew=require("fs"),sz=N(require("os")),cA=N(require("path"));pN=class{constructor(e=Sce()){this.filePath=e}async read(){try{let e=await Ew.promises.readFile(this.filePath,"utf8");return oz(JSON.parse(e))}catch{return az()}}async write(e){await Ew.promises.mkdir(cA.default.dirname(this.filePath),{recursive:!0,mode:448}),await Ew.promises.writeFile(this.filePath,`${JSON.stringify(oz(e),null,2)}
5795
+ ${$.green}\u2713${$.reset} Cleared ${m.length} entr${m.length===1?"y":"ies"}${O.length?` and ${O.length} task record(s)`:""}. Backup: ${k}`),_.length&&console.error(`${$.red}!${$.reset} ${_.length} task record(s) could not be backed up and were left in place. They name a cleared root and do nothing, but nothing was destroyed either \u2014 remove them by hand once you know why the copy failed.`),g.length&&console.log(`${$.dim} ${g.length} entr${g.length===1?"y was":"ies were"} left alone; re-run with --force if you mean to give those bytes up.${$.reset}`),!a){let x=await pw(e,s,u,l);if(BR(x))return 1}return console.log(" Tasks should start again in any CodeVibe session."),0}var De,Ut,KD,$R,$,Lae,qR=D(()=>{"use strict";De=N(require("fs")),Ut=N(require("path")),KD=N(require("crypto")),$R=require("child_process");mo();om();Wr();Md();uw();Ci();gs();vo();Uf();Pa();$={reset:"\x1B[0m",dim:"\x1B[2m",bold:"\x1B[1m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",cyan:"\x1B[36m"},Lae=[{agent:"CLAUDE",command:"claude",name:"Claude Code"},{agent:"CODEX",command:"codex",name:"Codex CLI"},{agent:"ANTIGRAVITY",command:"agy",name:"Antigravity CLI"}]});var fw,jD=D(()=>{"use strict";fw=[{method:"POST",path:"/v1/messages",auth:"broker_token"},{method:"POST",path:"/v1/responses",auth:"broker_token"},{method:"GET",path:"/healthz",auth:"none"},{method:"GET",path:"/models",auth:"none"},{method:"GET",path:"/v1/models",auth:"none"}]});var Sh,VD=D(()=>{"use strict";Sh=class{constructor(e={}){this.opts=e;this.emitted=[];this.counter=0}async emit(e,r){if(this.emitted.push({kind:e,payload:r}),this.opts.failKinds?.includes(e))throw new Error(`StubStrictAuditSink: simulated IPC failure for ${e}`);return this.opts.nackKinds?.includes(e)?{nack:`StubStrictAuditSink: simulated nack for ${e}`}:(this.counter+=1,{ack:`stub-ack-${this.counter}`})}ofKind(e){return this.emitted.filter(r=>r.kind===e)}}});function Eh(t){return Hae[t]}function KR(t){return t==="/v1/messages"?"anthropic":t==="/v1/responses"?"openai":null}var $ae,Gae,Hae,jR=D(()=>{"use strict";$ae="2023-06-01",Gae=new Set(["oauth-2025-04-20","claude-code-20250219","context-1m-2025-08-07","interleaved-thinking-2025-05-14","context-management-2025-06-27","prompt-caching-scope-2026-01-05","mid-conversation-system-2026-04-07","effort-2025-11-24","thinking-token-count-2026-05-13","per-turn-control-2026-07-01","mid-conversation-tool-changes-2026-07-01"]),Hae={anthropic:{upstreamBaseUrl:"https://api.anthropic.com",upstreamPath:"/v1/messages",synthesizedHeaders:{"anthropic-version":$ae,"content-type":"application/json"},betaTokenAllowlist:Gae,betaHeaderName:"anthropic-beta"},openai:{upstreamBaseUrl:"https://api.openai.com",upstreamPath:"/v1/responses",synthesizedHeaders:{"content-type":"application/json"},betaTokenAllowlist:new Set,betaHeaderName:null}}});var zD,Wae,H2,Rh,JD=D(()=>{"use strict";zD=require("node:crypto"),Wae=1800*1e3,H2=32,Rh=class{constructor(e=Wae){this.ttlMs=e;this.current=null;this.graceToken=null;this.generation=0}mint(e=Date.now()){let r=(0,zD.randomBytes)(H2).toString("base64url");return this.current={value:r,expiresAtMs:e+this.ttlMs},this.graceToken=null,this.generation+=1,this.current}rotateWithGrace(e=Date.now()){if(this.current===null||this.graceToken!==null)return null;this.graceToken=this.current;let r=(0,zD.randomBytes)(H2).toString("base64url");return this.current={value:r,expiresAtMs:e+this.ttlMs},this.generation+=1,{token:this.current,generation:this.generation}}commitRotation(e){e!==void 0&&e.generation!==this.generation||(this.graceToken=null)}rollbackRotation(e){e!==void 0&&e.generation!==this.generation||this.graceToken!==null&&(this.current=this.graceToken,this.graceToken=null)}hasPendingGrace(){return this.graceToken!==null}get(){return this.current}acceptedValues(){let e=[];return this.current&&e.push(this.current.value),this.graceToken&&e.push(this.graceToken.value),e}authenticate(e,r=Date.now()){return e?!!(this.current&&r<this.current.expiresAtMs&&e===this.current.value||this.graceToken&&r<this.graceToken.expiresAtMs&&e===this.graceToken.value):!1}clear(){this.current=null,this.graceToken=null}}});function qae(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function YD(t){return(0,VR.createHash)("sha256").update(JSON.stringify(t)).digest("hex")}function Kae(t,e){let r=Eh(t);if(!r.betaHeaderName)return{};let n=e?.[r.betaHeaderName];if(n===void 0||n==="")return{};let i=n.split(",").map(a=>a.trim()).filter(a=>a.length>0),o=i.filter(a=>r.betaTokenAllowlist.has(a)),s=i.filter(a=>!r.betaTokenAllowlist.has(a));return s.length>0&&y.warn("[canonical] dropped non-allowlisted beta tokens",{dropped:s}),o.length===0?{}:{[r.betaHeaderName]:o.join(",")}}function zR(t){let{provider:e,request:r}=t,n=Eh(e);if(t.agentContentType!==void 0&&t.agentContentType.split(";")[0].trim().toLowerCase()!=="application/json")throw new zs("non-JSON content type");let i=r.body;if(i==null||typeof i!="object"||Array.isArray(i))throw new zs("body is not a JSON object");if(qae(i,"model")){let c=i.model;if(typeof c!="string"||!Uae.test(c))throw new zs("model is not a canonical model id")}let o=(0,VR.randomUUID)(),s=YD(i),a={...n.synthesizedHeaders,...Kae(e,t.agentHeaders)};return{provider:e,upstreamUrl:n.upstreamBaseUrl+n.upstreamPath,headers:a,body:i,modelCallId:o,requestSha256:s}}function JR(t,e){let r=e.filter(p=>p.length>0),n=[],i=[],o="[REDACTED-SELF-CRED]",s="[REDACTED-SELF-CRED-KEY]",a="[REDACTED-CP7-KEY]",c=p=>r.some(h=>p.includes(h)),l=(p,h)=>/^[A-Za-z_][A-Za-z0-9_]*$/.test(h)?`${p}.${h}`:`${p}['${h.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}']`,d=(p,h)=>{if(typeof p=="string"){if(r.length===0)return p;let f=p,m=!1;for(let g of r)f.includes(g)&&(f=f.split(g).join(o),m=!0);return m&&n.push(h),f}if(Array.isArray(p))return p.map((f,m)=>d(f,`${h}[${m}]`));if(p!==null&&typeof p=="object"){let f=Object.create(null),m=0,g=0;for(let[w,v]of Object.entries(p))if(r.length>0&&c(w)){m+=1;let b=`${s}-${m}`,E=l(h,b);n.push(E),f[b]=d(v,E)}else if(z_(w)){g+=1;let b=`${a}-${g}`,E=l(h,b);i.push({field:E,patternClass:"secret_object_key"}),f[b]=d(v,E)}else f[w]=d(v,l(h,w));return f}return p};return{body:d(t,"$"),leakedPaths:n,keyScrubs:i}}var VR,zs,Uae,XD=D(()=>{"use strict";VR=require("node:crypto");jR();ue();Ll();zs=class extends Error{constructor(r){super(r);this.reason=r;this.name="CanonicalRejectError"}},Uae=/^[A-Za-z0-9._:/-]{1,200}$/});function YR(){return yd.upstreamBaseUrl+yd.upstreamPath}var jae,yd,XR,QR,ZR,eA=D(()=>{"use strict";jae="0.144.4",yd={upstreamBaseUrl:"https://chatgpt.com/backend-api/codex",upstreamPath:"/responses",synthesizedHeaders:{"content-type":"application/json",originator:"codex_cli_rs","user-agent":`codex_cli_rs/${jae}`},assumeSseOn200:!0};XR="https://auth.openai.com/oauth/token",QR="app_EMoamEEZ73f0CkXaXp7hrann",ZR="application/x-www-form-urlencoded"});function W2(t){try{let e=new URL(t);return`${e.protocol}//${e.host}${e.pathname}`}catch{return"<unparseable-url>"}}async function Jae(t,e){let r=t.body;if(!r||typeof r.getReader!="function"){let s=await t.text();return Buffer.byteLength(s,"utf8")>e?{rawBody:"",oversized:!0}:{rawBody:s,oversized:!1}}let n=r.getReader(),i=[],o=0;try{for(;;){let{done:s,value:a}=await n.read();if(s)break;if(!(!a||a.byteLength===0)){if(o+a.byteLength>e)return await n.cancel().catch(()=>{}),{rawBody:"",oversized:!0};o+=a.byteLength,i.push(a)}}}catch{return await n.cancel().catch(()=>{}),{rawBody:"",oversized:!0}}return{rawBody:Buffer.concat(i.map(s=>Buffer.from(s)),o).toString("utf8"),oversized:!1}}function QD(t){let e=new URLSearchParams;return e.set("grant_type","refresh_token"),e.set("refresh_token",t),e.set("client_id",QR),e.toString()}async function tA(t,e,r={}){let n=(r.now?.()??new Date).toISOString(),i;try{i=await e.post({url:XR,body:QD(t.refresh_token),contentType:ZR,signal:r.signal})}catch{return{kind:"transient",reason:"transport_error"}}if(i.status===200){let a=U2(i,!1);if(a&&typeof a.access_token=="string"&&a.access_token.length>0){let c={access_token:a.access_token,refresh_token:typeof a.refresh_token=="string"&&a.refresh_token.length>0?a.refresh_token:t.refresh_token,account_id:t.account_id,last_refresh:n},l=typeof a.id_token=="string"&&a.id_token.length>0?a.id_token:t.id_token;return l!==void 0&&(c.id_token=l),{kind:"rotated",bundle:c}}return{kind:"transient",reason:"malformed_success"}}let o=U2(i,!0),s=typeof o?.error=="string"?o.error:void 0;return s==="invalid_grant"?(y.warn("[oauth-refresh] permanent refresh failure (invalid_grant)"),{kind:"permanent",reason:"invalid_grant"}):(y.warn(`[oauth-refresh] transient refresh failure (status=${i.status})`),{kind:"transient",reason:s??`status_${i.status}`})}function U2(t,e){if(t.oversized||e&&(!t.contentType||!t.contentType.includes("application/json"))||!t.rawBody||t.rawBody.length===0)return null;try{let r=JSON.parse(t.rawBody);return r!==null&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}var Vae,zae,Ah,ZD=D(()=>{"use strict";ue();eA();Vae=64*1024,zae=3e4,Ah=class{constructor(e={}){this.opts=e}async post(e){let r=this.opts.fetchFn??fetch,n=this.opts.timeoutMs??zae,i=new AbortController,o=setTimeout(()=>i.abort(),n),s=()=>i.abort();e.signal&&(e.signal.aborted?i.abort():e.signal.addEventListener("abort",s,{once:!0}));try{let a=await r(e.url,{method:"POST",headers:{"content-type":e.contentType},body:e.body,redirect:"error",signal:i.signal}),{rawBody:c,oversized:l}=await Jae(a,Vae);return y.debug(`[oauth-refresh] POST ${W2(e.url)} -> ${a.status}`),{status:a.status,rawBody:c,contentType:(a.headers.get("content-type")??void 0)?.toLowerCase(),oversized:l}}catch(a){throw y.warn(`[oauth-refresh] transport error POSTing ${W2(e.url)}`,{code:a?.code}),new Error("oauth refresh transport error")}finally{clearTimeout(o),e.signal&&e.signal.removeEventListener("abort",s)}}}});function tce(){return{status:200,body:{models:ece.map(t=>({slug:t.slug,display_name:t.displayName,description:"CodeVibe broker compatibility model metadata.",default_reasoning_level:"medium",supported_reasoning_levels:Zae,shell_type:"shell_command",visibility:t.slug==="codex-auto-review"?"hide":"list",supported_in_api:t.supportedInApi,priority:t.priority,additional_speed_tiers:[],service_tiers:[],availability_nux:null,upgrade:null,base_instructions:"You are Codex, a coding agent.",model_messages:null,supports_reasoning_summaries:!1,default_reasoning_summary:"none",reasoning_summary_format:null,support_verbosity:!0,default_verbosity:"low",apply_patch_tool_type:"freeform",web_search_tool_type:"text",truncation_policy:{mode:"tokens",limit:1e4},supports_parallel_tool_calls:!0,supports_image_detail_original:!1,context_window:128e3,max_context_window:128e3,auto_compact_token_limit:null,comp_hash:null,effective_context_window_percent:95,experimental_supported_tools:[],input_modalities:["text"],supports_search_tool:!0,use_responses_lite:!1}))}}}function q2(t,e){return e.class==="oauth_bundle"?{authorization:`Bearer ${e.material.access_token}`,"ChatGPT-Account-Id":e.material.account_id}:t==="anthropic"?e.class==="subscription_token"?{authorization:`Bearer ${e.material}`}:{"x-api-key":e.material,authorization:`Bearer ${e.material}`}:{authorization:`Bearer ${e.material}`}}function rce(t,e){return t==="anthropic"&&e.startsWith("sk-ant-oat")?{class:"subscription_token",material:e}:{class:"api_key",material:e}}function nce(t){return t.class==="oauth_bundle"?[t.material.access_token,t.material.refresh_token]:[t.material]}function ice(t){return t.class==="oauth_bundle"?t.material.refresh_token:t.material}function oce(t,e,r){return`${t}-${e}-${r}`}function sce(t){let e=(o,s)=>Object.prototype.hasOwnProperty.call(o,s)?o[s]:void 0;if(t===void 0)return;if(typeof t=="string")return{kind:"string",bytes:t.length};if(t===null)return{kind:"null"};if(Array.isArray(t))return{kind:"array"};if(typeof t!="object")return{kind:typeof t};let r=e(t,"error");if(typeof r=="string")return{kind:"string-error",bytes:r.length};let n=r!==null&&typeof r=="object"&&!Array.isArray(r)?r:t,i={};for(let o of["message","type","code"]){let s=e(n,o);typeof s=="string"&&(i[o]=s.length)}return{kind:"object",nestedError:n!==t,fields:i}}var K2,j2,V2,z2,Yae,Xae,Qae,eN,Zae,ece,Ih,J2=D(()=>{"use strict";K2=require("node:crypto"),j2=N(require("node:http")),V2=require("node:stream"),z2=require("node:stream/promises");ue();VD();jR();JD();XD();Ll();uw();eA();ZD();Wh();jD();Yae=1500*1e3,Xae=5e3,Qae=12e4,eN=class extends V2.PassThrough{constructor(r,n){super({autoDestroy:!0});this.idleMs=r;this.onIdle=n;this.disarmed=!1}_construct(r){this.arm(),r()}_transform(r,n,i){this.arm(),i(null,r)}_destroy(r,n){this.disarm(),n(r)}arm(){this.disarmed||(this.idleTimer&&clearTimeout(this.idleTimer),this.idleTimer=setTimeout(this.onIdle,this.idleMs),this.idleTimer.unref?.())}disarm(){this.disarmed=!0,this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=void 0)}},Zae=[{effort:"low",description:"Fast responses with lighter reasoning"},{effort:"medium",description:"Balances speed and reasoning depth for everyday tasks"},{effort:"high",description:"Greater reasoning depth for complex problems"},{effort:"xhigh",description:"Extra high reasoning depth for complex problems"}],ece=[{slug:"gpt-5.5",displayName:"GPT-5.5",priority:7,supportedInApi:!0},{slug:"gpt-5.4",displayName:"GPT-5.4",priority:16,supportedInApi:!0},{slug:"gpt-5.4-mini",displayName:"GPT-5.4-Mini",priority:23,supportedInApi:!0},{slug:"gpt-5.3-codex",displayName:"GPT-5.3-Codex",priority:26,supportedInApi:!0},{slug:"gpt-5.2",displayName:"GPT-5.2",priority:35,supportedInApi:!0},{slug:"codex-auto-review",displayName:"Codex Auto Review",priority:43,supportedInApi:!0}];Ih=class{constructor(e){this.tokenMinter=new Rh;this.server=null;this.boundAddr=null;this.upstreamKeys=new Map;this.issuanceIds=new Map;this.issuanceCounter=0;this.credentialGeneration=new Map;this.inflightRefresh=new Map;this.stopping=!1;this.lifecycleGeneration=0;this.ops=new Set;this.taskId=e.taskId,this.upstreamClient=e.upstreamClient,this.vendorKeyStore=e.vendorKeyStore??new Sn,this.auditSink=e.auditSink??new Sh,this.brokerId=`broker-${process.pid}-${Date.now()}`,this.refreshTransport=e.refreshTransport??new Ah,this.oauthLock=e.oauthLock,this.proactiveThresholdMs=e.proactiveRefreshThresholdMs??Yae,this.stopDrainTimeoutMs=e.stopDrainTimeoutMs??Xae,this.nowFn=e.now??Date.now,this.delayFn=e.delay??(r=>new Promise(n=>setTimeout(n,r)))}getOAuthLock(e){return this.oauthLock||(this.oauthLock=ra({lockDir:ta(`vendor-oauth-${e}`)})),this.oauthLock}async start(){this.tokenMinter.mint();let e=j2.createServer((n,i)=>{this.handleHttp(n,i)});await new Promise((n,i)=>{e.once("error",i),e.listen(0,"127.0.0.1",()=>{e.removeListener("error",i),n()})});let r=e.address();return this.server=e,this.boundAddr=`127.0.0.1:${r.port}`,y.info(`[Broker] Started model gateway on ${this.boundAddr}`,{taskId:this.taskId}),{hostBrokerAddr:this.boundAddr}}async healthz(){return this.server!==null}async stop(){let e=!this.stopping;this.stopping=!0,e&&(this.lifecycleGeneration+=1);let r=[...this.ops];r.length>0&&await Promise.race([Promise.allSettled(r.map(i=>i.done)),this.delayFn(this.stopDrainTimeoutMs)]);let n=[...this.ops];for(let i of n)try{i.controller.abort()}catch{}if(await Promise.allSettled(n.map(i=>i.done)),this.upstreamKeys.clear(),this.credentialGeneration.clear(),this.inflightRefresh.clear(),this.tokenMinter.clear(),this.server){let i=this.server;this.server=null,this.boundAddr=null,await new Promise(o=>i.close(()=>o()))}y.info("[Broker] Stopped + zeroized upstream credentials",{taskId:this.taskId})}registerOp(){let e,r=new Promise(i=>{e=i}),n={controller:new AbortController,done:r,resolveDone:e,lifecycleGen:this.lifecycleGeneration};return this.ops.add(n),n}deregisterOp(e){this.ops.delete(e),e.resolveDone()}isStale(e){return this.lifecycleGeneration!==e.lifecycleGen}currentBrokerToken(){return this.tokenMinter.get()}rotateBrokerToken(){return this.server===null?null:this.tokenMinter.rotateWithGrace()}commitBrokerTokenRotation(e){this.tokenMinter.commitRotation(e)}rollbackBrokerTokenRotation(e){this.tokenMinter.rollbackRotation(e)}getVendorKey(e){return this.vendorKeyStore.getVendorKey(e)}setVendorKey(e,r){return this.vendorKeyStore.setVendorKey(e,r)}clearVendorKey(e){return this.vendorKeyStore.clearVendorKey(e)}getVendorOAuthBundle(e){return this.vendorKeyStore.getVendorOAuthBundle(e)}setVendorOAuthBundle(e,r){return this.vendorKeyStore.setVendorOAuthBundle(e,r)}clearVendorOAuthBundle(e){return this.vendorKeyStore.clearVendorOAuthBundle(e)}async handle(e,r){let n=fw.find(o=>o.method===e.method&&o.path===e.path);if(!n)return{status:403,body:{error:"forbidden"}};if(n.path==="/healthz")return{status:200,body:{ok:!0}};if(n.path==="/models"||n.path==="/v1/models")return tce();if(!this.tokenMinter.authenticate(e.brokerToken))return{status:401,body:{error:"invalid broker token"}};let i=KR(e.path);return i?this.gateway(i,e,r):{status:403,body:{error:"forbidden"}}}async gateway(e,r,n){let i=this.registerOp(),o={signal:i.controller.signal,lifecycleGen:i.lifecycleGen};try{return this.stopping?{status:503,body:{error:"broker stopping"}}:await this.gatewayInner(e,r,o,i,n)}finally{this.deregisterOp(i)}}async gatewayInner(e,r,n,i,o){let s=await this.loadVendorCredential(e,n);if(s===null)return{status:503,body:{error:"no upstream credential"}};if(s.class==="oauth_bundle"&&this.isProactiveDue(s.material)){let v=await this.refreshOAuth(e,n,"proactive");if(v.kind==="rotated"||v.kind==="adopted")s={class:"oauth_bundle",material:v.bundle};else{if(v.kind==="revoked")return{status:503,body:{error:"no upstream credential"}};if(v.kind==="permanent")return this.permanentRefreshResponse()}}let a;try{a=zR({provider:e,request:r,agentHeaders:r.agentHeaders,agentQuery:r.agentQuery,agentContentType:r.agentContentType})}catch(v){if(v instanceof zs)return{status:400,body:{error:v.reason}};throw v}let{modelCallId:c,requestSha256:l}=a,d=[...nce(s),...this.tokenMinter.acceptedValues()],u=JR(a.body,d),p=oS(u.body);for(let v of u.leakedPaths)if(!await this.emitGated("model_context_scrubbed",{model_call_id:c,field:v,pattern_class:"self_credential"}))return{status:503,body:{error:"audit unavailable"}};for(let v of u.keyScrubs)if(!await this.emitGated("model_context_scrubbed",{model_call_id:c,field:v.field,pattern_class:v.patternClass}))return{status:503,body:{error:"audit unavailable"}};for(let v of p.findings)if(!await this.emitGated("model_context_scrubbed",{model_call_id:c,field:v.field,pattern_class:v.patternClass}))return{status:503,body:{error:"audit unavailable"}};if(!await this.emitGated("model_call",{agent:e,model:this.extractModel(p.scrubbed),model_call_id:c,request_sha256:l,credential_issuance_id:this.lastIssuanceId(e)}))return{status:503,body:{error:"audit unavailable"}};let f=this.genOf(e),m=s,g=this.buildUpstreamTarget(e,m,a.headers,a.upstreamUrl),w=!1;try{for(;;){let v=await this.upstreamClient.post({url:g.url,headers:g.headers,body:p.scrubbed,signal:n.signal}),b=(v.headers["content-type"]??"").toLowerCase().trim(),E=b.length===0,A=b.startsWith("text/event-stream"),k=g.assumeSseOn200,R=v.status===200&&!!o&&(A||E&&k);if(y.info("[Broker] forward decision",{taskId:this.taskId,modelCallId:c,status:v.status,ctAbsent:E,isSse:A,assumeSse:k,decision:R?"streamed":"buffered"}),R&&o)return await this.streamForward(v,o,n,i,c);let S=await v.readText(),T;try{T=S.length?JSON.parse(S):void 0}catch{T=void 0}if(!w&&m.class==="oauth_bundle"&&v.status===401){w=!0;let O=await this.refreshOAuth(e,n,"reactive",f);if(O.kind==="rotated"||O.kind==="adopted"){m={class:"oauth_bundle",material:O.bundle},g=this.buildUpstreamTarget(e,m,a.headers,a.upstreamUrl);continue}if(O.kind==="permanent"){let _=this.permanentRefreshResponse();return await this.emitBestEffort("model_call_result",{model_call_id:c,result:"refresh_permanent"}),_}if(O.kind==="revoked"){let _={status:503,body:{error:"no upstream credential"}};return await this.emitBestEffort("model_call_result",{model_call_id:c,result:"revoked"}),_}}let P=this.mapUpstream({status:v.status,body:T});return await this.emitBestEffort("model_call_result",{model_call_id:c,result:P.status===200?"ok":`upstream_${v.status}`,...this.extractUsage(T)}),P}}catch{let v={status:502,body:{error:"upstream forward failed"}};return await this.emitBestEffort("model_call_result",{model_call_id:c,result:"forward_error"}),v}}async streamForward(e,r,n,i,o){let s,a;try{s=e.bodyStream();let c=(e.headers["content-type"]??"").trim();return r.writeHead(200,{"content-type":c.length?e.headers["content-type"]:"text/event-stream"}),a=new eN(Qae,()=>i.controller.abort()),await(0,z2.pipeline)(s,a,r,{signal:n.signal}),await this.emitBestEffort("model_call_result",{model_call_id:o,result:"ok_streamed",usageSource:"unavailable_streamed"}),{kind:"handled"}}catch(c){return a?.destroy(),s&&(s.on("error",()=>{}),s.destroy()),i.controller.abort(),r.headersSent?(r.destroy(),y.warn("[Broker] streaming forward failed after headers sent",{errorShape:c instanceof Error?{name:c.name}:{kind:typeof c}}),await this.emitBestEffort("model_call_result",{model_call_id:o,result:"stream_error",usageSource:"unavailable_streamed"}),{kind:"handled"}):(await this.emitBestEffort("model_call_result",{model_call_id:o,result:"forward_error",usageSource:"unavailable_streamed"}),{status:502,body:{error:"upstream forward failed"}})}}buildUpstreamTarget(e,r,n,i){if(r.class==="oauth_bundle"){let s={...n,...yd.synthesizedHeaders,...q2(e,r)};return{url:YR(),headers:s,assumeSseOn200:yd.assumeSseOn200}}let o={...n,...q2(e,r)};if(e==="anthropic"&&r.class==="subscription_token"){let s=o["anthropic-beta"];o["anthropic-beta"]=s?s.includes("oauth-2025-04-20")?s:`${s},oauth-2025-04-20`:"oauth-2025-04-20"}return{url:i,headers:o,assumeSseOn200:!1}}async loadVendorCredential(e,r){let n=this.upstreamKeys.get(e);if(n!==void 0)return n;let i=await this.vendorKeyStore.getVendorKey(e),o=null;if(i!==null)o=rce(e,i);else if(e==="openai"){let a=await this.vendorKeyStore.getVendorOAuthBundle(e);a&&(o={class:"oauth_bundle",material:a})}if(o===null)return null;if(this.isStale(r)||this.stopping)return o;this.upstreamKeys.set(e,o),o.class==="oauth_bundle"&&!this.credentialGeneration.has(e)&&this.credentialGeneration.set(e,0),this.issuanceCounter+=1;let s=oce(this.brokerId,e,this.issuanceCounter);return this.issuanceIds.set(e,s),await this.emitBestEffort("broker_credential_loaded",{provider:e,key_fingerprint:(0,K2.createHash)("sha256").update(ice(o)).digest("hex").slice(0,16),credential_issuance_id:s}),o}genOf(e){return this.credentialGeneration.get(e)??0}currentBundle(e){let r=this.upstreamKeys.get(e);return r&&r.class==="oauth_bundle"?r.material:null}isProactiveDue(e){let r=Date.parse(e.last_refresh);return Number.isNaN(r)?!1:this.nowFn()-r>=this.proactiveThresholdMs}adoptBundle(e,r,n){this.isStale(n)||this.stopping||(this.upstreamKeys.set(e,{class:"oauth_bundle",material:r}),this.credentialGeneration.set(e,this.genOf(e)+1))}async refreshOAuth(e,r,n,i){if(n==="reactive"&&i!==void 0&&i<this.genOf(e)){let s=this.currentBundle(e);return s?{kind:"adopted",bundle:s}:{kind:"transient",reason:"gen_advanced_but_absent"}}let o=this.inflightRefresh.get(e);return o||(o=this.doRefreshUnderLock(e,r).finally(()=>{this.inflightRefresh.delete(e)}),this.inflightRefresh.set(e,o)),o}async doRefreshUnderLock(e,r){let n=this.getOAuthLock(e),i;try{i=await n.acquire()}catch{return{kind:"transient",reason:"lock_unavailable"}}try{let o=await this.vendorKeyStore.getVendorOAuthBundle(e);if(!o)return{kind:"revoked",reason:"cleared"};let s=this.currentBundle(e);if(s&&o.access_token!==s.access_token)return this.adoptBundle(e,o,r),{kind:"adopted",bundle:o};let a=await tA(o,this.refreshTransport,{signal:r.signal});return a.kind==="permanent"?{kind:"permanent",reason:a.reason}:a.kind==="transient"?{kind:"transient",reason:a.reason}:this.isStale(r)||this.stopping?{kind:"transient",reason:"stopping"}:await i.reassertOwnership()?this.isStale(r)||this.stopping?{kind:"transient",reason:"stopping"}:(await this.vendorKeyStore.setVendorOAuthBundle(e,a.bundle),this.adoptBundle(e,a.bundle,r),{kind:"rotated",bundle:a.bundle}):{kind:"transient",reason:"ownership_lost"}}finally{await i.release()}}lastIssuanceId(e){return this.issuanceIds.get(e)??""}permanentRefreshResponse(){return{status:502,body:{error:"upstream auth failed",remediation:"re-run: codevibe vendor-key import-codex"}}}mapUpstream(e){return e.status!==200&&y.warn("[Broker] upstream non-200",{status:e.status,errorShape:sce(e.body)}),e.status===401||e.status===403?{status:502,body:{error:"upstream auth failed"}}:e.status===200?{status:200,body:e.body}:{status:502,body:{error:`upstream_${e.status}`}}}extractModel(e){if(e!==null&&typeof e=="object"&&Object.prototype.hasOwnProperty.call(e,"model")){let r=e.model;if(typeof r=="string")return r}return"unknown"}extractUsage(e){if(e===null||typeof e!="object")return{};let r=e.usage;if(r===null||typeof r!="object")return{};let n=r,i={};return typeof n.input_tokens=="number"&&(i.prompt_tokens=n.input_tokens),typeof n.output_tokens=="number"&&(i.completion_tokens=n.output_tokens),typeof n.prompt_tokens=="number"&&(i.prompt_tokens=n.prompt_tokens),typeof n.completion_tokens=="number"&&(i.completion_tokens=n.completion_tokens),i}async emitGated(e,r){try{return"ack"in await this.auditSink.emit(e,r)}catch{return!1}}async emitBestEffort(e,r){try{await this.auditSink.emit(e,r)}catch{}}async handleHttp(e,r){try{let n=e.method??"GET",i=new URL(e.url??"/","http://127.0.0.1"),o=i.pathname,s={};for(let[p,h]of Object.entries(e.headers))typeof h=="string"?s[p.toLowerCase()]=h:Array.isArray(h)&&(s[p.toLowerCase()]=h.join(","));let a={};for(let[p,h]of i.searchParams.entries())a[p]=h;let c=this.extractBrokerToken(s),l,d=!1;if(n==="POST"){let p=await this.readBody(e);if(p.length>0)try{l=JSON.parse(p)}catch{d=!0}}if(d&&fw.some(p=>p.method===n&&p.path===o)){this.writeJson(r,400,{error:"malformed JSON body"});return}let u=await this.handle({method:n,path:o,brokerToken:c,body:l,agentHeaders:s,agentQuery:a,agentContentType:s["content-type"]},r);if("kind"in u)return;this.writeJson(r,u.status,u.body)}catch(n){y.error("[Broker] HTTP handler error",{error:n instanceof Error?n.message:String(n)}),r.headersSent?r.destroy():this.writeJson(r,502,{error:"broker internal error"})}}extractBrokerToken(e){if(e["x-api-key"])return e["x-api-key"];let r=e.authorization;if(r&&r.toLowerCase().startsWith("bearer "))return r.slice(7).trim()}readBody(e){return new Promise((r,n)=>{let i=[];e.on("data",o=>i.push(o)),e.on("end",()=>r(Buffer.concat(i).toString("utf8"))),e.on("error",n)})}writeJson(e,r,n){let i=JSON.stringify(n??{});e.writeHead(r,{"content-type":"application/json"}),e.end(i)}}});function Y2(t){try{let e=new URL(t);return`${e.protocol}//${e.host}${e.pathname}`}catch{return"<unparseable-url>"}}var tN,ace,Th,X2=D(()=>{"use strict";tN=require("node:stream");ue();ace=12e4;Th=class{constructor(e={}){this.opts=e}async post(e){let r=this.opts.fetchFn??fetch,n=this.opts.timeoutMs??ace,i=new AbortController,o=setTimeout(()=>i.abort(),n),s=e.signal,a=()=>i.abort();s&&(s.aborted?i.abort():s.addEventListener("abort",a,{once:!0}));let c=!1,l=()=>{c||(c=!0,s&&s.removeEventListener("abort",a))},d;try{d=await r(e.url,{method:"POST",headers:{...e.headers},body:JSON.stringify(e.body),redirect:"error",signal:i.signal})}catch(m){throw clearTimeout(o),l(),y.warn(`[UpstreamClient] transport error POSTing ${Y2(e.url)}`,{code:m?.code}),new Error("upstream transport error")}clearTimeout(o),y.debug(`[UpstreamClient] POST ${Y2(e.url)} -> ${d.status}`);let u={};d.headers.forEach((m,g)=>{u[g.toLowerCase()]=m});let p=d,h=!1,f=()=>{if(h)throw new Error("UpstreamResult body already consumed (bodyStream/readText are one-shot; LOCK #643-1)");h=!0};return{status:p.status,headers:u,bodyStream(){if(f(),p.body===null)return l(),tN.Readable.from([]);let m=tN.Readable.fromWeb(p.body);return m.once("close",l),m},async readText(){f();let m=setTimeout(()=>i.abort(),n);s?.aborted&&i.abort();try{return await p.text()}catch{throw new Error("upstream transport error")}finally{clearTimeout(m),l()}}}}}});var rN={};lr(rN,{BROKER_ROUTES:()=>fw,BrokerTokenMinter:()=>Rh,CHATGPT_OAUTH_CLIENT_ID:()=>QR,CHATGPT_REFRESH_CONTENT_TYPE:()=>ZR,CHATGPT_TOKEN_ENDPOINT:()=>XR,CHATGPT_UPSTREAM_CONFIG:()=>yd,CanonicalRejectError:()=>zs,FetchRefreshTransport:()=>Ah,FetchUpstreamClient:()=>Th,KeychainVendorKeyStore:()=>Sn,LocalModelGatewayBroker:()=>Ih,OAuthAccountLock:()=>Hh,StubStrictAuditSink:()=>Sh,buildCanonicalRequest:()=>zR,buildRefreshBody:()=>QD,chatGptUpstreamUrl:()=>YR,createOAuthAccountLock:()=>ra,defaultOAuthLockDir:()=>ta,getProviderConfig:()=>Eh,providerForPath:()=>KR,refreshOAuthToken:()=>tA,requestSha256:()=>YD,scrubRequestBody:()=>oS,selfCredentialGuard:()=>JR});var rA=D(()=>{"use strict";jD();J2();X2();VD();uw();JD();eA();ZD();Wh();XD();Ll();jR()});function nA(t){let e={},r=process.execPath.slice(0,process.execPath.lastIndexOf("/"));e.PATH=`${t.path??yw}:${r}`,e.HOME=t.sandboxHome;let n=t.safeSource??{};for(let i of gw){let o=n[i];typeof o=="string"&&o.length>0&&(e[i]=o)}return t.provider==="anthropic"?e.ANTHROPIC_BASE_URL=t.sandboxBrokerUrl:e.OPENAI_BASE_URL=`${t.sandboxBrokerUrl.replace(/\/+$/,"")}/v1`,t.provider==="anthropic"?(e.CLAUDE_CONFIG_DIR=t.sandboxBootstrapDir,e.CLAUDE_CODE_TMPDIR=t.claudeScratchDir??t.sandboxBootstrapDir):e.CODEX_HOME=t.sandboxBootstrapDir,e}function ww(t){let e=new Set(["ANTHROPIC_BASE_URL","OPENAI_BASE_URL"]);for(let r of Object.keys(t))if(!e.has(r)){for(let n of cce)if(n.test(r))throw new Error(`sanitizedEnv I1 violation: credential-shaped key "${r}" present in the agent env \u2014 refusing to launch (allow-list bug)`)}}var gw,yw,cce,nN=D(()=>{"use strict";gw=["LANG","LC_ALL","LC_CTYPE","TERM","TZ"],yw="/usr/local/bin:/usr/bin:/bin";cce=[/^ANTHROPIC_API_KEY$/i,/^ANTHROPIC_AUTH_TOKEN$/i,/^OPENAI_API_KEY$/i,/_API_KEY$/i,/_SECRET$/i,/_SECRET_ACCESS_KEY$/i,/^AWS_/i,/^GH_TOKEN$/i,/^GITHUB_TOKEN$/i,/^GOOGLE_/i,/_TOKEN$/i,/^SSH_/i]});function oN(t){return t==="CLAUDE"?"anthropic":t==="CODEX"?"openai":null}function iN(t,e){if(t===e)return!0;let r=Er.relative(e,t);return r.length>0&&!r.startsWith("..")&&!Er.isAbsolute(r)}function pce(t){let e=t.split(Er.sep);for(let i=e.length-2;i>=0;i--)if(e[i]===uce&&e[i+1]===dce){let o=[...e];return o[i+1]=lce,Er.join(o.join(Er.sep),Q2)}let r=Er.dirname(t),n=Er.basename(t);return Er.join(r,".codevibe-audit",n,Q2)}async function hce(t,e){let r;try{r=await wd.promises.realpath(e)}catch{throw new Error(`CP-7 W3: cannot realpath workdir "${e}" \u2014 refusing to launch (audit containment fail-closed)`)}let n=Er.dirname(t);await wd.promises.mkdir(n,{recursive:!0});let i;try{i=await wd.promises.realpath(n)}catch{throw new Error(`CP-7 W3: cannot realpath audit dir "${n}" \u2014 refusing to launch (fail-closed)`)}let o=Er.join(i,Er.basename(t)),s;try{s=await wd.promises.lstat(o)}catch{s=void 0}let a=o;if(s?.isSymbolicLink())try{a=await wd.promises.realpath(o)}catch{throw new Error(`CP-7 W3: audit leaf "${o}" is a symlink that does not resolve (dangling) \u2014 refusing to launch (fail-closed). The audit file must be a regular file in the sibling .codevibe/audit/ tree.`)}if(iN(i,r)||iN(o,r)||iN(a,r))throw new Error(`CP-7 W3: audit path "${o}" (resolved target "${a}") is inside the agent workdir "${r}" \u2014 the agent could truncate/forge the forensic record (Stage-1 r1 HIGH fail-closed). The audit MUST live in the sibling .codevibe/audit/ tree, never under .codevibe/state/<group>/<track>/.`);return o}async function Ph(t){if(t.webBrowsingActive)return{mode:"reduced_trust",reducedTrust:!0,reducedTrustReason:`Agent web browsing active for ${t.agentKind} \u2014 running in reduced-trust mode with shadow-diff capture and guarded web tools`,teardown:async()=>{}};let e=oN(t.agentKind);if(e===null)return t.requireConfined?fce(t):{mode:"reduced_trust",reducedTrust:!0,reducedTrustReason:`${t.agentKind} is a reduced-trust agent (\xA76 Q4) \u2014 no vendor broker; runs on the legacy spawn path with shadow-diff capture`,teardown:async()=>{}};let r=await Jl(t.ladderDeps);if(r.tier==="reduced_trust")return{mode:"reduced_trust",reducedTrust:!0,reducedTrustReason:r.reducedTrustReason,teardown:async()=>{}};let n,i=null;if(t.brokerDeps?.auditSink)n=t.brokerDeps.auditSink;else{let w=t.auditPath??pce(t.workdir),v=await hce(w,t.workdir);i=Er.dirname(v),n=new _l(t.taskId,v)}let o=t.upstreamClient??new Th,s=(t.makeBroker??(w=>new Ih(w)))({taskId:t.taskId,upstreamClient:o,...t.brokerDeps?.vendorKeyStore?{vendorKeyStore:t.brokerDeps.vendorKeyStore}:{},auditSink:n}),a;try{({hostBrokerAddr:a}=await s.start())}catch(w){let v=Object.assign(new Error("CP-7: broker failed to start \u2014 refusing to launch the implementor (fail-closed)"),{cause:w});try{await s.stop()}catch(b){throw Object.assign(new Error("CP-7: broker start failed and cleanup also failed"),{causes:[v,b]})}throw v}let c=s.currentBrokerToken();if(!c){let w=new Error("CP-7: broker minted no token \u2014 refusing to launch (fail-closed)");try{await s.stop()}catch(v){throw Object.assign(new Error("CP-7: broker minted no token and cleanup also failed"),{causes:[w,v]})}throw w}let l=c.value,d=r.tier==="docker"?`http://127.0.0.1:${Hp}`:`http://${a}`,u=r.tier==="docker"?fy:t.workdir,p=r.tier==="docker"?Vv:null,h=r.tier==="docker"?JP:null,f,m,g;try{f=await Hu.create({provider:e,sandboxBrokerUrl:d,initialToken:l,...p!==null?{sandboxDir:p,sandboxConfigDir:h??JP}:{sandboxDirEqualsHostDir:!0,configDirEqualsHostDir:!0},hostRoot:t.bootstrapHostRoot,...r.tier==="sandbox_exec"&&e==="anthropic"?{claudeScratchHostRoot:t.claudeScratchHostRoot??"/tmp"}:{},workdir:t.workdir,...t.workdirAuthority?{workdirAuthority:t.workdirAuthority}:{}});let w=p!==null?{hostDir:f.hostDir,sandboxDir:p}:{hostDir:f.hostDir,sandboxDir:f.hostDir},v=h!==null?{hostDir:f.configHostDir,sandboxDir:h}:{hostDir:f.configHostDir,sandboxDir:f.configHostDir},b=f.claudeScratchSpec,E=nA({provider:e,sandboxBrokerUrl:d,sandboxHome:u,sandboxBootstrapDir:v.sandboxDir,...b!==null?{claudeScratchDir:b.sandboxDir}:{},safeSource:t.localeSource});ww(E);let A=xP(t.role,E,t.processTreeId),k={isolationTech:r.tier==="docker"?"docker":"sandbox_exec",workdir:t.workdir,...t.workdirAuthority?{workdirAuthority:t.workdirAuthority}:{},hostBrokerAddr:a,sandboxBrokerUrl:d,taskId:t.taskId,sanitizedEnv:A,agentBootstrap:w,agentConfig:v,...b!==null?{agentScratch:b}:{},...i!==null?{auditDir:i}:{}};m=await r.substrate.launch(k),y.info(`[CP-7] Substrate engaged (tier=${r.tier}, egress=${m.egressFidelity}) \u2014 agent is creditless, broker holds the key`,{taskId:t.taskId,agent:t.agentKind});let R=f,S=m,T=s,P=null,O,_=()=>O||(O=(async()=>{P&&(clearInterval(P),P=null);let q=[];for(let z of[()=>S.teardown(),()=>T.stop(),()=>R.destroy()])try{await z()}catch(U){q.push(U)}if(q.length>0)throw y.warn("[CP-7] substrate cleanup failed \u2014 task cannot pass",{taskId:t.taskId,failureCount:q.length,..._r(q[0])}),q.length===1?q[0]:Object.assign(new Error("CP-7 substrate cleanup failed"),{causes:q})})(),O);g=_;let x=`launch-${t.taskId}-${Date.now()}`,C=S.egressFidelity==="strict"?"structural_deny_network_none":"coarse_loopback_only",H;try{H=await n.emit("egress_denied",{destination:"*",protocol:"all",denial_reason:C,caller_event_id:x})}catch(q){throw Object.assign(new Error("CP-7 W3: egress-posture audit emit failed \u2014 refusing to launch the creditless agent (audit-before-effect fail-closed)"),{cause:q})}if(!("ack"in H))throw new Error("CP-7 W3: egress-posture audit was rejected \u2014 refusing to launch the creditless agent (no durable egress posture \u2192 no agent)");let G=t.tokenRefreshIntervalMs??600*1e3,F=null,L=async()=>{if(!(typeof T.rotateBrokerToken=="function"&&typeof T.commitBrokerTokenRotation=="function"&&typeof T.rollbackBrokerTokenRotation=="function")){let U=T.currentBrokerToken();U&&await R.refresh(U.value);return}let z=T.rotateBrokerToken();if(z)try{await R.refresh(z.token.value),T.commitBrokerTokenRotation(z)}catch(U){T.rollbackBrokerTokenRotation(z),y.warn("[CP-7] broker-token refresh write FAILED \u2014 rolled back to the prior token and tearing down (fail-closed)",{taskId:t.taskId,..._r(U)});let V=Object.assign(new Error("CP-7 broker-token refresh failed"),{cause:U});try{await _()}catch(ee){throw Object.assign(new Error("CP-7 broker-token refresh failed and cleanup also failed"),{causes:[V,ee]})}throw V}},W=async()=>{let z=(F??Promise.resolve()).catch(()=>{}).then(()=>L());F=z;try{await z}finally{F===z&&(F=null)}};return G>0&&(P=setInterval(()=>{W().catch(()=>{})},G),P.unref?.()),{mode:"substrate",tier:r.tier,reducedTrust:r.reducedTrust,reducedTrustReason:r.tier==="sandbox_exec"?r.reducedTrustReason:void 0,substrateHandle:S,agentConfigDir:v.sandboxDir,finalEnv:A,refreshBrokerToken:W,teardown:_}}catch(w){let v=w instanceof Error?w:new Error("CP-7 substrate launch failed"),b=[];if(g)try{await g()}catch(E){b.push(E)}else for(let E of[...m?[()=>m.teardown()]:[],...f?[()=>f.destroy()]:[],()=>s.stop()])try{await E()}catch(A){b.push(A)}throw b.length>0?(y.warn("[CP-7] failed launch also failed cleanup",{taskId:t.taskId,failureCount:b.length,..._r(b[0])}),Object.assign(new Error("CP-7 substrate launch failed and cleanup also failed"),{causes:[v,...b]})):v}}async function fce(t){let e=t.agentKind;if(e!=="GEMINI"&&e!=="ANTIGRAVITY")throw new Error(`engageWriteConfinedResolverSandbox: unmapped broker-less agent ${e}`);let r=await Jl(t.ladderDeps);if(r.tier==="reduced_trust")return{mode:"reduced_trust",reducedTrust:!0,reducedTrustReason:`${e} resolver confinement unavailable \u2014 no sandbox substrate on this host (${r.reducedTrustReason}); the requireConfined spawn fail-closes to the human gate`,teardown:async()=>{}};if(r.tier==="docker")return{mode:"reduced_trust",reducedTrust:!0,reducedTrustReason:`${e} resolver confinement unavailable on the docker tier \u2014 the A1 image cannot carry the host-installed ${e} binary + its file-based auth; the requireConfined spawn fail-closes to the human gate`,teardown:async()=>{}};let n=Z2.homedir(),i=Er.join(n,...mce[e]);await wd.promises.mkdir(i,{recursive:!0}).catch(()=>{});let o={},s=process.execPath.slice(0,process.execPath.lastIndexOf("/"));o.PATH=`${yw}:${s}`,o.HOME=n;let a=t.localeSource??{};for(let u of gw){let p=a[u];typeof p=="string"&&p.length>0&&(o[u]=p)}ww(o);let c=xP(t.role,o,t.processTreeId),l={isolationTech:"sandbox_exec",workdir:t.workdir,...t.workdirAuthority?{workdirAuthority:t.workdirAuthority}:{},hostBrokerAddr:"",sandboxBrokerUrl:"",taskId:t.taskId,sanitizedEnv:c,agentConfig:{hostDir:i,sandboxDir:i},networkPosture:"open"},d=await r.substrate.launch(l);return y.info(`[A1d] Resolver-confinement row engaged (tier=sandbox_exec, egress=open) \u2014 writes fenced to the disposable workspace; ${e} runs on its own file-based auth (no broker)`,{taskId:t.taskId,agent:e}),{mode:"substrate",tier:"sandbox_exec",reducedTrust:!0,reducedTrustReason:`${e} class-2 resolver: write-confined to the disposable merge workspace (A5 Seatbelt); egress OPEN (broker-less \u2014 the agent dials its vendor directly with its own file-based auth)`,substrateHandle:d,agentConfigDir:i,finalEnv:c,refreshBrokerToken:async()=>{},teardown:async()=>{await d.teardown().catch(()=>{})}}}var wd,Z2,Er,lce,dce,uce,Q2,mce,ez=D(()=>{"use strict";wd=require("node:fs"),Z2=N(require("node:os")),Er=N(require("node:path"));rA();ST();Jk();ue();Lv();jS();qS();zv();VS();nN();lce="audit",dce="state",uce=".codevibe",Q2="audit.jsonl";mce={GEMINI:[".gemini"],ANTIGRAVITY:[".gemini","antigravity-cli"]}});function iA(t){return yce.has(t.toUpperCase())||wce.test(t)?!1:gce.some(e=>e.test(t))}function sN(t){return Object.keys(t).filter(iA)}function aN(t){let e={};for(let[r,n]of Object.entries(t))n!==void 0&&(iA(r)||(e[r]=n));return e[bw]="1",e}function oA(t={}){let e=t.platform??process.platform,r=t.env??process.env,n=t.exit??(u=>process.exit(u));if(e!=="darwin")return!1;let i=sN(r);if(i.length===0)return!1;if(r[bw])throw new Error(`[le-env-scrub] Refusing to launch the Local Executor: the scrub marker (${bw}) is set but credential-shaped env vars are still present (${i.join(", ")}). A genuine re-exec'd child has NO credential-shaped vars; this indicates a spoofed marker or a broken scrub. Fail closed (CP-7 I1, A5 parent-procargs vector) \u2014 never launch the LE with a vendor credential in its exec-time procargs.`);let o=t.spawnSyncFn??tz.spawnSync,s=t.execPath??process.execPath,a=t.argv??process.argv.slice(1),c=t.cwd??process.cwd(),l=aN(r);try{t.onScrub?.(i)}catch{}let d=o(s,a,{env:l,stdio:"inherit",cwd:c});return d.signal?n(1):n(d.status??1),!0}var tz,bw,gce,yce,wce,rz=D(()=>{"use strict";tz=require("node:child_process"),bw="CODEVIBE_LE_ENV_SCRUBBED",gce=[/^ANTHROPIC_/i,/^OPENAI_/i,/^GOOGLE_/i,/^GEMINI_/i,/^GH_TOKEN$/i,/^GITHUB_TOKEN$/i,/_API_KEY$/i,/_ACCESS_KEY_ID$/i,/_SECRET_ACCESS_KEY$/i,/_SECRET$/i,/_TOKEN$/i],yce=new Set(["ANTHROPIC_BASE_URL","OPENAI_BASE_URL","GOOGLE_BASE_URL"]),wce=/_BASE_URL$/i});var cN={};lr(cN,{ApiKeyBootstrap:()=>Hu,CODEX_PROVIDER_ID:()=>Tf,CP7_CANONICAL_FORM_VERSION:()=>L_,Cp7AuditWriter:()=>_l,GENESIS_PREV_HASH:()=>zk,HELPER_SCRIPT_NAME:()=>Kv,IMPLEMENTOR_CREDENTIAL_MISSING:()=>GC,ImplementorCredentialMissingError:()=>jl,LE_ENV_SCRUBBED_MARKER:()=>bw,REVIEWER_CREDENTIAL_MISSING:()=>iy,ReviewerCredentialMissingError:()=>Kl,SAFE_ENV_ALLOWLIST:()=>gw,SANDBOX_BOOTSTRAP_DIR:()=>Vv,SANDBOX_DEFAULT_PATH:()=>yw,TOKEN_FILE_NAME:()=>jv,assertImplementorVendorCredential:()=>cy,assertNoAmbientCreds:()=>ww,assertReviewerVendorCredential:()=>ay,buildSanitizedBaseEnv:()=>nA,buildScrubbedLeEnv:()=>aN,canonicalEntryBytes:()=>wg,canonicalJson:()=>kp,computeEntryHash:()=>Sp,engageSubstrate:()=>Ph,findCredShapedKeys:()=>sN,implementorProviderFor:()=>sy,isCredShapedEnvKey:()=>iA,providerForAgent:()=>oN,reviewerProviderFor:()=>oy,scrubLeEnvOrReexec:()=>oA,selectSubstrate:()=>Jl,verifyChain:()=>B_,withImplementorCredentialPreflight:()=>Vl,withReviewerCredentialPreflight:()=>$p});var sA=D(()=>{"use strict";ez();VS();nN();zv();HC();rz();Jk()});function vw(t,e,r){let n=Xc(e.prompt_template,"AntigravityReviewerProvider"),i=[];e.model_hint!==null&&i.push("--model",e.model_hint);let o=Math.max(1,Math.floor(e.timeout_ms/1e3)-5);i.push("--print-timeout",`${o}s`),i.push("--add-dir",r),i.push("--print",n);let s=we({...process.env,QUORUM_REVIEWER_SUBPROCESS:"1"});return{command:t,args:i,env:s}}async function bce(t,e,r,n){if(!r.exit_success){let a=Yl(r.stderr)??"spawn_failed";throw new Qe({kind:"spawn_failed",agent:t.agent,reason:`agy exited with non-zero status; stderr: ${r.stderr.trim()}`,failureReason:a})}let i=r.stdout,o={verdict_id:(0,nz.v4)(),gate_id:e,seat_id:t.seat_id,role:t.role,reviewer_agent:t.agent,model_used:t.model_hint,tokens_used:null,latency_ms:r.elapsed_ms,submitted_at:new Date().toISOString(),usage:Dt("provider_unsupported",r.elapsed_ms)};if(n!==void 0){let a=await n(i,{seatId:t.seat_id,role:t.role,agent:t.agent}),c=Jp(a,i);return{...o,...c}}let s=Ya(i);if(!s.ok)throw new Qe({kind:"parse_failure",agent:t.agent,raw_output:r.stdout});return{...o,verdict:s.verdict.kind,reasoning:s.verdict.reasoning,suggested_changes:s.verdict.suggested_changes,residual_observations:s.verdict.residual_observations}}var nz,xh,lN=D(()=>{"use strict";nz=require("uuid");Lu();Vp();Ja();jp();by();pa();tE();zp();Qt();xh=class{constructor(e={}){this.executable=e.executable??"agy"}async evaluate(e,r,n){if(e.agent!=="antigravity")throw new Error(`AntigravityReviewerProvider called with non-Antigravity spec (got ${e.agent}); the engine's registry wiring is responsible for dispatch`);if(n?.substrate!==void 0)throw new Qe({kind:"spawn_failed",agent:e.agent,reason:"AntigravityReviewerProvider received a substrate handle \u2014 agy is reduced-trust (never substrate-contained, \xA76 Q4); the loop must pre-route antigravity seats to the legacy path",failureReason:"spawn_failed"});let i=n?.workdir;if(i===void 0||i.length===0)throw new Qe({kind:"spawn_failed",agent:e.agent,reason:"AntigravityReviewerProvider requires opts.workdir (agy is workspace-centric \u2014 without --add-dir it cannot read the repo); the evaluate site must thread the loop workingDir",failureReason:"spawn_failed"});let o;try{o=vw(this.executable,e,i)}catch(a){throw new Qe({kind:"spawn_failed",agent:e.agent,reason:a instanceof Error?a.message:String(a),failureReason:"spawn_failed"})}let s;try{s=await qo({command:o.command,args:o.args,env:o.env,prompt:"",timeout_ms:e.timeout_ms})}catch(a){throw a instanceof Mr?new Qe(Yp(e.agent,a.detail)):a}return bce(e,r,s,n?.classifyVerdict)}}});function kw(t,e,r=!1){let n=[];n.push("--print"),n.push("--output-format","json"),n.push("--allowed-tools",e.tool_allowlist.join(",")),n.push("--tools",e.tool_allowlist.join(",")),n.push("--disallowed-tools","WebFetch,WebSearch,Agent,Task,Workflow,SendMessage,ListAgents"),n.push("--strict-mcp-config"),e.model_hint!==null&&n.push("--model",e.model_hint);let i=r?{}:we({...process.env,QUORUM_REVIEWER_SUBPROCESS:"1"});return{command:t,args:n,env:i}}async function vce(t,e,r,n){if(!r.exit_success){let c=Us(r.stdout)??Yl(r.stderr)??"spawn_failed";throw new Qe({kind:"spawn_failed",agent:t.agent,reason:`claude exited with non-zero status; stderr: ${r.stderr.trim()}`,failureReason:c})}let{text:i}=bo(r.stdout),o=Tc(r.stdout,r.elapsed_ms),s={verdict_id:(0,iz.v4)(),gate_id:e,seat_id:t.seat_id,role:t.role,reviewer_agent:t.agent,model_used:t.model_hint,tokens_used:o.totalTokens,latency_ms:r.elapsed_ms,submitted_at:new Date().toISOString(),usage:o};if(n!==void 0){let c=await n(i,{seatId:t.seat_id,role:t.role,agent:t.agent}),l=Jp(c,i);return{...s,...l}}let a=Ya(i);if(!a.ok)throw new Qe({kind:"parse_failure",agent:t.agent,raw_output:r.stdout});return{...s,verdict:a.verdict.kind,reasoning:a.verdict.reasoning,suggested_changes:a.verdict.suggested_changes,residual_observations:a.verdict.residual_observations}}var iz,_h,dN=D(()=>{"use strict";iz=require("uuid");Vp();Ja();jp();by();tE();zp();pa();Qt();_h=class{constructor(e={}){this.executable=e.executable??"claude"}async evaluate(e,r,n){if(e.agent!=="claude")throw new Error(`ClaudeReviewerProvider called with non-Claude spec (got ${e.agent}); the engine's registry wiring is responsible for dispatch`);let i=n?.substrate!==void 0,o=kw(this.executable,e,i),s;try{s=await qo({command:o.command,args:o.args,env:o.env,prompt:e.prompt_template,timeout_ms:e.timeout_ms,...n?.substrate!==void 0?{substrate:n.substrate}:{}})}catch(a){throw a instanceof Mr?new Qe(Yp(e.agent,a.detail)):a}return vce(e,r,s,n?.classifyVerdict)}}});function aA(){return new Sw().with("claude",new _h).with("codex",new Xp).with("antigravity",new xh)}var Sw,uN=D(()=>{"use strict";Ja();lN();dN();ky();Sw=class{constructor(){this.providers=new Map}with(e,r){return this.providers.set(e,r),this}register(e,r){this.providers.set(e,r)}providerFor(e){return this.providers.get(e)}registeredAgents(){return Array.from(this.providers.keys())}async evaluate(e,r,n){let i=this.providers.get(e.agent);if(i===void 0)throw new Qe({kind:"spawn_failed",agent:e.agent,reason:`no provider registered for ${e.agent} \u2014 registry was built without a ${e.agent} entry but the policy snapshot includes a ${e.agent} reviewer`});return i.evaluate(e,r,n)}}});function az(){return{schemaVersion:1,choice:"not_configured",artifactId:null,ollamaModel:null,updatedAt:new Date(0).toISOString()}}function kce(t=process.env){return t.NODE_ENV==="test"&&t.CODEVIBE_HOME_OVERRIDE?t.CODEVIBE_HOME_OVERRIDE:cA.default.join(sz.default.homedir(),".codevibe")}function Sce(t=process.env){return cA.default.join(kce(t),"local-model-state.json")}function oz(t){if(!t||typeof t!="object")return az();let e=t;return{schemaVersion:1,choice:e.choice==="skipped"||e.choice==="enabled"?e.choice:"not_configured",artifactId:typeof e.artifactId=="string"&&e.artifactId.trim()?e.artifactId:null,ollamaModel:typeof e.ollamaModel=="string"&&e.ollamaModel.trim()?e.ollamaModel:null,updatedAt:typeof e.updatedAt=="string"&&e.updatedAt?e.updatedAt:new Date(0).toISOString()}}async function hN(t=lA){return t.read()}async function mN(t,e=null,r=lA){await r.write({schemaVersion:1,choice:"enabled",artifactId:t,ollamaModel:e,updatedAt:new Date().toISOString()})}var Ew,sz,cA,pN,lA,fN=D(()=>{"use strict";Ew=require("fs"),sz=N(require("os")),cA=N(require("path"));pN=class{constructor(e=Sce()){this.filePath=e}async read(){try{let e=await Ew.promises.readFile(this.filePath,"utf8");return oz(JSON.parse(e))}catch{return az()}}async write(e){await Ew.promises.mkdir(cA.default.dirname(this.filePath),{recursive:!0,mode:448}),await Ew.promises.writeFile(this.filePath,`${JSON.stringify(oz(e),null,2)}
5796
5796
  `,{mode:384})}async clear(){await Ew.promises.rm(this.filePath,{force:!0})}},lA=new pN});function Pce(t){let e=t?.trim();return e||null}function xce(t){if(!t?.trim())return[];let e;try{e=JSON.parse(t)}catch{return null}return!Array.isArray(e)||e.some(r=>typeof r!="string")?null:e}function _ce(t){if(!t?.trim())return Ece;let e=Number(t);return!Number.isSafeInteger(e)||e<=0||e>Rce?null:e}function gN(t){return t.includes("\0")}function dA(t,e=process.env){let r=Pce(e.CODEVIBE_LOCAL_MODEL_COMMAND);if(!r)return{ok:!1,reason:"CODEVIBE_LOCAL_MODEL_COMMAND is not configured. It must point to the verified local Gemma runner."};if(gN(r)||gN(t))return{ok:!1,reason:"local Gemma runtime command or model path is invalid."};let n=xce(e.CODEVIBE_LOCAL_MODEL_ARGS_JSON);if(!n||n.some(gN))return{ok:!1,reason:"CODEVIBE_LOCAL_MODEL_ARGS_JSON must be a JSON array of string arguments."};let i=_ce(e.CODEVIBE_LOCAL_MODEL_TIMEOUT_MS);return i?{ok:!0,config:{command:r,args:n,modelPath:t,timeoutMs:i,env:e}}:{ok:!1,reason:"CODEVIBE_LOCAL_MODEL_TIMEOUT_MS must be a positive integer no greater than 300000."}}function cz(t,e,r){let n=t+e.toString("utf8");return Buffer.byteLength(n,"utf8")<=r?n:n.slice(0,r)+`
5797
5797
  [truncated]
5798
5798
  `}function Cce(t){let e=t.trim();if(!e.startsWith("{")||!e.endsWith("}"))throw new Error("local Gemma process stdout must be strict JSON only");try{JSON.parse(e)}catch(r){throw new Error(`local Gemma process stdout was not valid JSON: ${r.message}`)}return e}var lz,dz,Ece,Rce,Ace,Ice,Tce,Ch,yN=D(()=>{"use strict";lz=require("child_process"),dz=N(require("path"));Qt();bu();Ece=3e4,Rce=5*6e4,Ace=1e3,Ice=256*1024,Tce=64*1024;Ch=class{constructor(e){this.config=e;this.runtimeLabel=`local-gemma-process:${dz.default.basename(e.command)}`}async classify(e){return this.invoke(e,"classify")}async generateAdvisory(e,r){return this.invoke(e,"advisory",{responseFormat:r?.responseFormat??"json"})}async probe(){let e=Date.now();try{let r=await this.invoke(["You are CodeVibe local Gemma health check.","Return STRICT JSON ONLY:",'{"action":"advisory_response","rationale":"health check","advisory_summary":"ok"}'].join(`
@@ -78040,13 +78040,8 @@ var StubStrictAuditSink = class {
78040
78040
 
78041
78041
  // src/credential-broker/broker-config.ts
78042
78042
  var ANTHROPIC_VERSION = "2023-06-01", ANTHROPIC_BETA_ALLOWLIST = /* @__PURE__ */ new Set([
78043
- // Reviewed 2026-07-03 (host path-A dogfood): the FULL standard flag set the
78044
- // live Claude Code CLI (2.1.x) sends — captured verbatim from the dropped-
78045
- // token diagnostic. All are STATIC vendor-published feature-flag constants
78046
- // (no agent-controlled data can ride in an exact-match token). Several gate
78047
- // BODY fields the CLI always emits (`context_management`, thinking, caching,
78048
- // effort) — dropping a flag while its body field survives makes the upstream
78049
- // 400 the whole request ("Extra inputs are not permitted").
78043
+ // Reviewed 2026-07-03 (host path-A dogfood): the initial flag set the
78044
+ // live Claude Code CLI (2.1.x) sent.
78050
78045
  "oauth-2025-04-20",
78051
78046
  "claude-code-20250219",
78052
78047
  "context-1m-2025-08-07",
@@ -78054,7 +78049,18 @@ var ANTHROPIC_VERSION = "2023-06-01", ANTHROPIC_BETA_ALLOWLIST = /* @__PURE__ */
78054
78049
  "context-management-2025-06-27",
78055
78050
  "prompt-caching-scope-2026-01-05",
78056
78051
  "mid-conversation-system-2026-04-07",
78057
- "effort-2025-11-24"
78052
+ "effort-2025-11-24",
78053
+ // Reviewed 2026-09-24 (BB-D-01 / Stage-2 R3): Empirically captured from live
78054
+ // Claude Code CLI 2.1.282 requests on /v1/messages?beta=true. Baseline broker at
78055
+ // f0369c2 dropped these tokens, causing upstream Anthropic to return HTTP 400.
78056
+ // Documented Anthropic beta features:
78057
+ // - thinking-token-count-2026-05-13: token usage reporting for thinking blocks.
78058
+ // - per-turn-control-2026-07-01: per-turn effort / output_config directives.
78059
+ // - mid-conversation-tool-changes-2026-07-01: dynamic tool updates preserving prompt cache.
78060
+ // Note: advisor-tool-2026-03-01 is deliberately EXCLUDED (unneeded and prevents account-billed advisor tool invocation).
78061
+ "thinking-token-count-2026-05-13",
78062
+ "per-turn-control-2026-07-01",
78063
+ "mid-conversation-tool-changes-2026-07-01"
78058
78064
  ]), PROVIDER_CONFIGS = {
78059
78065
  anthropic: {
78060
78066
  upstreamBaseUrl: "https://api.anthropic.com",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quantiya/codevibe-core",
3
- "version": "2.0.51",
3
+ "version": "2.0.52",
4
4
  "description": "Core library for CodeVibe plugins - shared keychain, crypto, AppSync, and auth functionality",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",