grix-connector 4.3.1 → 4.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- import{execFile as V}from"node:child_process";import{createHash as N,randomUUID as O}from"node:crypto";import{closeSync as G,copyFileSync as p,cpSync as S,existsSync as d,mkdirSync as y,openSync as C,readFileSync as h,rmSync as f,statSync as m,writeFileSync as b}from"node:fs";import{join as o,resolve as I}from"node:path";import{fileURLToPath as D}from"node:url";import{promisify as M}from"node:util";import{log as $}from"../../core/log/index.js";import{resolveShimInvocation as T}from"../../core/runtime/spawn.js";import{resolveCliPath as B}from"../../core/util/cli-probe.js";import{bridgeDiscoveryDirectory as J,discoverDshBridgeEndpoints as L,resolveDshProfileIdentity as F}from"./profile-resolver.js";const z=M(V),U=2*1024*1024,u="@grix/dsh-bridge",x="deepseek-harness-bridge-installer",k=2,q=1e3;class oe{options;command;identity;constructor(e={}){this.options=e,this.command=e.command?.trim()||"dsh",this.identity=F({dshHome:e.dshHome,profileName:e.profileName})}async status(){const e=await B(this.command),r=this.bridgeAsset(),t=this.readInstalledBridgeVersion(),n=r.version,s=L(this.identity),a=s[0]?.bridgeVersion??null,l=s[0]?.dshVersion??null,_=e?await R(e,this.options.dshHome):null;let c;return e?d(this.identity.profileRoot)?t?t!==n||this.installedBridgeContentStale(r)?c="bridge_update_required":s.length===0||a!==t||this.runningBridgePredatesInstalledContent(s[0])?c="profile_restart_required":c="ready":c="bridge_missing":c="profile_missing":c="dsh_missing",{readiness:c,command:this.command,commandPath:e,dshVersion:_,runningDshVersion:l,identity:this.identity,installedBridgeVersion:t,bundledBridgeVersion:n,runningBridgeVersion:a,endpointCount:s.length}}async install(){const e=await B(this.command);if(!e)throw Object.assign(new Error(`${this.command} not found`),{code:"dsh_missing"});const r=this.bridgeAsset();return A(this.identity,async()=>{await g(e,["--profile",this.identity.profileName,"--dump-config"],this.options.dshHome);const t=this.readInstalledBridgeVersion();if(t===r.version&&!this.installedBridgeContentStale(r))return this.status();const n=o(this.identity.dshHome,"assets","grix-dsh-bridge");y(n,{recursive:!0,mode:448});const s=this.captureInstallBackup(n,t),a=o(n,`grix-dsh-bridge-${r.version}.tgz`);p(r.tarball,a);try{if(t===r.version&&d(this.bridgePackageRoot())&&(await g(e,["plugin","--profile",this.identity.profileName,"remove",u],this.options.dshHome),d(this.bridgePackageRoot())))throw Object.assign(new Error(`dsh plugin remove left ${u} in place; refusing to attest an unverified reinstall`),{code:"bridge_install_failed"});await this.runPluginAdd(e,a),await g(e,["--profile",this.identity.profileName,"--dump-config"],this.options.dshHome);const l=this.readInstalledBridgeVersion();if(l!==r.version)throw Object.assign(new Error(`Bridge package did not land on disk (installed ${l??"none"}, expected ${r.version})`),{code:"bridge_install_failed"});this.writeInstalledBridgeIntegrity(r.integrity)}catch(l){await this.rollbackInstall(e,n,s,t);try{f(a,{force:!0})}catch{}throw Object.assign(new Error(`Bridge install failed: ${w(l)}`),{code:"bridge_install_failed"})}return this.discardInstallBackup(s),this.status()})}async uninstall(){const e=await B(this.command);if(!e)throw Object.assign(new Error(`${this.command} not found`),{code:"dsh_missing"});return A(this.identity,async()=>(this.readInstalledBridgeVersion()&&await g(e,["plugin","--profile",this.identity.profileName,"remove",u],this.options.dshHome),this.status()))}async runPluginAdd(e,r){const t=["plugin","--profile",this.identity.profileName,"add",r];let n;for(let s=1;s<=k;s++)try{await g(e,t,this.options.dshHome);return}catch(a){n=a,$.warn(x,`dsh plugin add attempt ${s}/${k} failed for profile ${this.identity.profileName}
2
- ${Y(a)}`),s<k&&await new Promise(l=>setTimeout(l,q))}throw n}bridgePackageRoot(){return o(this.identity.profileRoot,"node_modules","@grix","dsh-bridge")}profilePackageJsonPath(){return o(this.identity.profileRoot,"package.json")}captureInstallBackup(e,r){const t=o(e,"rollback",`${Date.now()}-${O()}`);y(t,{recursive:!0,mode:448});const n=this.bridgePackageRoot(),s=d(n);s&&S(n,o(t,"dsh-bridge"),{recursive:!0});const a=this.profilePackageJsonPath(),l=d(a);l&&p(a,o(t,"package.json"));const _=["pnpm-lock.yaml","package-lock.json","yarn.lock"];for(const c of _){const P=o(this.identity.profileRoot,c);d(P)&&p(P,o(t,c))}return b(o(t,"manifest.json"),`${JSON.stringify({priorVersion:r,hadBridge:s,hadPackageJson:l})}
3
- `,{mode:384}),{root:t,priorVersion:r,hadBridge:s,hadPackageJson:l}}async rollbackInstall(e,r,t,n){const s=n?o(r,`grix-dsh-bridge-${n}.tgz`):null;if(s&&d(s)&&await g(e,["plugin","--profile",this.identity.profileName,"add",s],this.options.dshHome).then(()=>!0).catch(()=>!1)){this.discardInstallBackup(t);return}if(t.hadBridge&&d(o(t.root,"dsh-bridge"))){this.restoreFilesystemBackup(t),this.discardInstallBackup(t);return}n?t.hadPackageJson&&this.restoreFilesystemBackup(t):(await g(e,["plugin","--profile",this.identity.profileName,"remove",u],this.options.dshHome).catch(()=>{}),this.cleanHalfInstalledBridge()),this.discardInstallBackup(t)}restoreFilesystemBackup(e){const r=this.bridgePackageRoot(),t=o(e.root,"dsh-bridge");e.hadBridge&&d(t)&&(f(r,{recursive:!0,force:!0}),y(o(this.identity.profileRoot,"node_modules","@grix"),{recursive:!0,mode:448}),S(t,r,{recursive:!0})),e.hadPackageJson&&d(o(e.root,"package.json"))&&p(o(e.root,"package.json"),this.profilePackageJsonPath());for(const n of["pnpm-lock.yaml","package-lock.json","yarn.lock"]){const s=o(e.root,n);d(s)&&p(s,o(this.identity.profileRoot,n))}}cleanHalfInstalledBridge(){try{f(this.bridgePackageRoot(),{recursive:!0,force:!0})}catch{}const e=this.profilePackageJsonPath();if(d(e))try{const r=JSON.parse(h(e,"utf8"));let t=!1;for(const n of["dependencies","devDependencies","optionalDependencies","peerDependencies"]){const s=r[n];s&&typeof s=="object"&&!Array.isArray(s)&&u in s&&(delete s[u],t=!0)}t&&b(e,`${JSON.stringify(r,null,2)}
1
+ import{execFile as V}from"node:child_process";import{createHash as N,randomUUID as O}from"node:crypto";import{closeSync as G,copyFileSync as p,cpSync as P,existsSync as d,mkdirSync as y,openSync as T,readFileSync as h,rmSync as f,statSync as m,writeFileSync as b}from"node:fs";import{join as o,resolve as I}from"node:path";import{fileURLToPath as D}from"node:url";import{promisify as C}from"node:util";import{log as $}from"../../core/log/index.js";import{resolveShimInvocation as M}from"../../core/runtime/spawn.js";import{resolveCliPath as B}from"../../core/util/cli-probe.js";import{bridgeDiscoveryDirectory as J,discoverDshBridgeEndpoints as L,resolveDshProfileIdentity as F}from"./profile-resolver.js";const z=C(V),U=2*1024*1024,u="@grix/dsh-bridge",x="deepseek-harness-bridge-installer",k=2,q=1e3;class oe{options;command;identity;constructor(e={}){this.options=e,this.command=e.command?.trim()||"dsh",this.identity=F({dshHome:e.dshHome,profileName:e.profileName})}async status(){const e=await B(this.command),r=this.bridgeAsset(),t=this.readInstalledBridgeVersion(),n=r.version,s=L(this.identity),a=s[0]?.bridgeVersion??null,l=s[0]?.dshVersion??null,_=e?await R(e,this.options.dshHome):null;let c;return e?d(this.identity.profileRoot)?t?t!==n||this.installedBridgeContentStale(r)?c="bridge_update_required":s.length===0||a!==t||this.runningBridgePredatesInstalledContent(s[0])?c="profile_restart_required":c="ready":c="bridge_missing":c="profile_missing":c="dsh_missing",{readiness:c,command:this.command,commandPath:e,dshVersion:_,runningDshVersion:l,identity:this.identity,installedBridgeVersion:t,bundledBridgeVersion:n,runningBridgeVersion:a,endpointCount:s.length}}async install(){const e=await B(this.command);if(!e)throw Object.assign(new Error(`${this.command} not found`),{code:"dsh_missing"});const r=this.bridgeAsset();return A(this.identity,async()=>{await g(e,["--profile",this.identity.profileName,"--dump-config"],this.options.dshHome);const t=this.readInstalledBridgeVersion();if(t===r.version&&!this.installedBridgeContentStale(r))return this.status();const n=o(this.identity.dshHome,"assets","grix-dsh-bridge");y(n,{recursive:!0,mode:448});const s=this.captureInstallBackup(n,t),a=o(n,`grix-dsh-bridge-${r.version}.tgz`);p(r.tarball,a);try{if(t===r.version&&d(this.bridgePackageRoot())&&(await g(e,["plugin","--profile",this.identity.profileName,"remove",u],this.options.dshHome),d(this.bridgePackageRoot())))throw Object.assign(new Error(`dsh plugin remove left ${u} in place; refusing to attest an unverified reinstall`),{code:"bridge_install_failed"});await this.runPluginAdd(e,a),await g(e,["--profile",this.identity.profileName,"--dump-config"],this.options.dshHome);const l=this.readInstalledBridgeVersion();if(l!==r.version)throw Object.assign(new Error(`Bridge package did not land on disk (installed ${l??"none"}, expected ${r.version})`),{code:"bridge_install_failed"});this.writeInstalledBridgeIntegrity(r.integrity)}catch(l){await this.rollbackInstall(e,n,s,t);try{f(a,{force:!0})}catch{}throw Object.assign(new Error(`Bridge install failed: ${w(l)}`),{code:"bridge_install_failed"})}return this.discardInstallBackup(s),this.status()})}async uninstall(){const e=await B(this.command);if(!e)throw Object.assign(new Error(`${this.command} not found`),{code:"dsh_missing"});return A(this.identity,async()=>(this.readInstalledBridgeVersion()&&await g(e,["plugin","--profile",this.identity.profileName,"remove",u],this.options.dshHome),this.status()))}async runPluginAdd(e,r){const t=["plugin","--profile",this.identity.profileName,"add",r];let n;for(let s=1;s<=k;s++)try{await g(e,t,this.options.dshHome);return}catch(a){n=a,$.warn(x,`dsh plugin add attempt ${s}/${k} failed for profile ${this.identity.profileName}
2
+ ${Y(a)}`),s<k&&await new Promise(l=>setTimeout(l,q))}throw n}bridgePackageRoot(){return o(this.identity.profileRoot,"node_modules","@grix","dsh-bridge")}profilePackageJsonPath(){return o(this.identity.profileRoot,"package.json")}captureInstallBackup(e,r){const t=o(e,"rollback",`${Date.now()}-${O()}`);y(t,{recursive:!0,mode:448});const n=this.bridgePackageRoot(),s=d(n);s&&P(n,o(t,"dsh-bridge"),{recursive:!0});const a=this.profilePackageJsonPath(),l=d(a);l&&p(a,o(t,"package.json"));const _=["pnpm-lock.yaml","package-lock.json","yarn.lock"];for(const c of _){const S=o(this.identity.profileRoot,c);d(S)&&p(S,o(t,c))}return b(o(t,"manifest.json"),`${JSON.stringify({priorVersion:r,hadBridge:s,hadPackageJson:l})}
3
+ `,{mode:384}),{root:t,priorVersion:r,hadBridge:s,hadPackageJson:l}}async rollbackInstall(e,r,t,n){const s=n?o(r,`grix-dsh-bridge-${n}.tgz`):null;if(s&&d(s)&&await g(e,["plugin","--profile",this.identity.profileName,"add",s],this.options.dshHome).then(()=>!0).catch(()=>!1)){this.discardInstallBackup(t);return}if(t.hadBridge&&d(o(t.root,"dsh-bridge"))){this.restoreFilesystemBackup(t),this.discardInstallBackup(t);return}n?t.hadPackageJson&&this.restoreFilesystemBackup(t):(await g(e,["plugin","--profile",this.identity.profileName,"remove",u],this.options.dshHome).catch(()=>{}),this.cleanHalfInstalledBridge()),this.discardInstallBackup(t)}restoreFilesystemBackup(e){const r=this.bridgePackageRoot(),t=o(e.root,"dsh-bridge");e.hadBridge&&d(t)&&(f(r,{recursive:!0,force:!0}),y(o(this.identity.profileRoot,"node_modules","@grix"),{recursive:!0,mode:448}),P(t,r,{recursive:!0})),e.hadPackageJson&&d(o(e.root,"package.json"))&&p(o(e.root,"package.json"),this.profilePackageJsonPath());for(const n of["pnpm-lock.yaml","package-lock.json","yarn.lock"]){const s=o(e.root,n);d(s)&&p(s,o(this.identity.profileRoot,n))}}cleanHalfInstalledBridge(){try{f(this.bridgePackageRoot(),{recursive:!0,force:!0})}catch{}const e=this.profilePackageJsonPath();if(d(e))try{const r=JSON.parse(h(e,"utf8"));let t=!1;for(const n of["dependencies","devDependencies","optionalDependencies","peerDependencies"]){const s=r[n];s&&typeof s=="object"&&!Array.isArray(s)&&u in s&&(delete s[u],t=!0)}t&&b(e,`${JSON.stringify(r,null,2)}
4
4
  `,{mode:384})}catch{}}discardInstallBackup(e){try{f(e.root,{recursive:!0,force:!0})}catch{}}readInstalledBridgeVersion(){const e=o(this.bridgePackageRoot(),"package.json");try{const r=JSON.parse(h(e,"utf8"));return typeof r.version=="string"?r.version:null}catch{return null}}installedIntegrityPath(){return o(this.bridgePackageRoot(),".grix-bridge-integrity")}readInstalledBridgeIntegrity(){try{const e=h(this.installedIntegrityPath(),"utf8").trim();return e.startsWith("sha512-")?e:null}catch{return null}}writeInstalledBridgeIntegrity(e){b(this.installedIntegrityPath(),`${e}
5
- `,{encoding:"utf8",mode:384})}installedBridgeContentStale(e=this.bridgeAsset()){return d(this.bridgePackageRoot())?this.readInstalledBridgeIntegrity()!==e.integrity:!0}runningBridgePredatesInstalledContent(e){try{const r=m(this.installedIntegrityPath()).mtimeMs,t=Date.parse(e.startedAt);return Number.isFinite(t)?r>t:!0}catch{return!1}}bridgeAsset(){return this.options.tarballPath?H(I(this.options.tarballPath)):E()}}function ae(i){if(i.readiness==="ready")return null;const e=i.identity.profileName,r=`dsh --profile ${e}`,t=i.endpointCount>0&&i.runningBridgeVersion&&i.installedBridgeVersion&&i.runningBridgeVersion!==i.installedBridgeVersion?`Grix Bridge in DSH profile "${e}" is running version ${i.runningBridgeVersion}, but ${i.installedBridgeVersion} is installed on disk. dsh does not hot-load plugin upgrades: stop the running profile process, then start it again with: ${r}`:`Grix Bridge is installed in DSH profile "${e}", but no live Bridge endpoint is available. dsh does not hot-load plugins: stop the running profile process, then start it again with: ${r}`,n={dsh_missing:"dsh is not installed or not on PATH. Install DeepSeek Harness (dsh), then retry.",profile_missing:`DSH profile "${e}" does not exist yet. Create/boot it once with: ${r}`,bridge_missing:`Grix Bridge is not installed in DSH profile "${e}". Install it from the DeepSeek Harness toolbar (or the dsh_install_bridge action), then restart the profile if it is already running.`,bridge_update_required:`Grix Bridge in DSH profile "${e}" needs an update (installed ${i.installedBridgeVersion??"none"}, expected ${i.bundledBridgeVersion}${i.installedBridgeVersion===i.bundledBridgeVersion?", content hash mismatch":""}). Update from the toolbar, then restart the profile \u2014 dsh does not hot-load plugin upgrades.`,profile_restart_required:t};return Object.assign(new Error(n[i.readiness]),{code:i.readiness})}function de(){return E().tarball}function E(){const i=[D(new URL("../../assets/dsh-bridge/",import.meta.url)),D(new URL("../../../dist/assets/dsh-bridge/",import.meta.url))].find(t=>d(o(t,"manifest.json")));if(!i)throw Object.assign(new Error("Bundled Grix DSH Bridge asset is unavailable; run the Connector build first"),{code:"bridge_asset_missing"});const e=JSON.parse(h(o(i,"manifest.json"),"utf8"));if(typeof e.tarball!="string"||!e.tarball||typeof e.bridgeVersion!="string"||!e.bridgeVersion)throw Object.assign(new Error("Invalid Grix DSH Bridge asset manifest"),{code:"bridge_asset_invalid"});const r=H(o(i,e.tarball),e.bridgeVersion);if(Number(e.size)!==m(r.tarball).size)throw Object.assign(new Error("Grix DSH Bridge asset size mismatch"),{code:"bridge_asset_invalid"});if(typeof e.integrity=="string"&&e.integrity.startsWith("sha512-")&&e.integrity!==r.integrity)throw Object.assign(new Error("Grix DSH Bridge asset integrity mismatch"),{code:"bridge_asset_invalid"});return r}function H(i,e){if(!d(i)||!m(i).isFile())throw Object.assign(new Error(`Grix DSH Bridge asset is missing: ${i}`),{code:"bridge_asset_missing"});if(m(i).size>U)throw Object.assign(new Error("Grix DSH Bridge asset exceeds the 2 MiB safety limit"),{code:"bridge_asset_invalid"});const r=e??/grix-dsh-bridge-([0-9A-Za-z.+-]+)\.tgz$/.exec(i)?.[1];if(!r)throw Object.assign(new Error("Cannot determine Grix DSH Bridge version"),{code:"bridge_asset_invalid"});const t=`sha512-${N("sha512").update(h(i)).digest("base64")}`;return{tarball:i,version:r,integrity:t}}async function A(i,e){const r=J(i);y(r,{recursive:!0,mode:448});const t=o(r,"install.lock");let n=j(t);if(n===null){let s=0;try{s=Number(h(t,"utf8").trim())}catch{}let a=!1;try{a=s===0&&Date.now()-m(t).mtimeMs>5*6e4}catch{}if(a||Number.isSafeInteger(s)&&s>0&&!X(s)){try{f(t,{force:!0})}catch{}n=j(t)}}if(n===null)throw Object.assign(new Error(`Another Grix DSH Bridge install is active for profile ${i.profileName}`),{code:"bridge_install_busy"});try{return b(n,`${process.pid}
6
- `,"utf8"),await e()}finally{G(n);try{f(t,{force:!0})}catch{}}}function j(i){try{return C(i,"wx",384)}catch(e){if(e.code==="EEXIST")return null;throw Object.assign(new Error(`Cannot acquire Grix DSH Bridge install lock: ${w(e)}`),{code:"bridge_install_failed"})}}function X(i){try{return process.kill(i,0),!0}catch(e){return e.code==="EPERM"}}async function le(i,e){const r=await B(i?.trim()||"dsh");return r?R(r,e):null}async function R(i,e){try{return(await g(i,["--version"],e)).trim().split(/\s+/)[0]||null}catch(r){return $.warn(x,`dsh --version \u63A2\u6D4B\u5931\u8D25\uFF08${i}\uFF09\uFF1A${w(r)}`),null}}async function g(i,e,r){try{const t=T(i,e);return(await z(t.command,t.args,{env:{...process.env,...r?{DSH_HOME:I(r)}:{}},timeout:6e4,maxBuffer:8*1024*1024,windowsVerbatimArguments:t.windowsVerbatimArguments})).stdout}catch(t){const n=t&&typeof t=="object"?t:{};throw Object.assign(new Error(w(t)),{code:"dsh_command_failed",stderr:typeof n.stderr=="string"?v(n.stderr):void 0})}}function v(i){return i.replace(/(api[_-]?key|authorization|bearer)\s*[:=]\s*\S+/gi,"$1=[REDACTED]")}function w(i){const e=i&&typeof i=="object"?i:{};return v(String(e.stderr??e.message??i??"unknown error")).replace(/[\r\n]+/g," ").slice(0,1024)}function Y(i){const e=i&&typeof i=="object"?i:{};return v(String(e.stderr??e.message??i??"unknown error")).slice(0,8*1024)}export{oe as DshBridgeInstaller,de as defaultBridgeTarball,ae as errorForDshBridgeReadiness,le as readDshCliVersion};
5
+ `,{encoding:"utf8",mode:384})}installedBridgeContentStale(e=this.bridgeAsset()){return d(this.bridgePackageRoot())?this.readInstalledBridgeIntegrity()!==e.integrity:!0}runningBridgePredatesInstalledContent(e){try{const r=m(this.installedIntegrityPath()).mtimeMs,t=Date.parse(e.startedAt);return Number.isFinite(t)?r>t:!0}catch{return!1}}bridgeAsset(){return this.options.tarballPath?E(I(this.options.tarballPath)):H()}}function ae(i){if(i.readiness==="ready")return null;const e=i.identity.profileName,r=`dsh --profile ${e}`,t=`dsh does not hot-load plugin changes: stop the running profile process, then start it again with: ${r}`;let n;i.endpointCount===0?n=`Grix Bridge is installed in DSH profile "${e}", but no live Bridge endpoint is available. Start the profile with: ${r}`:i.runningBridgeVersion&&i.installedBridgeVersion&&i.runningBridgeVersion!==i.installedBridgeVersion?n=`Grix Bridge in DSH profile "${e}" is running version ${i.runningBridgeVersion}, but ${i.installedBridgeVersion} is installed on disk. ${t}`:n=`The live Grix Bridge in DSH profile "${e}" predates the Bridge content installed on disk. ${t}`;const s={dsh_missing:"dsh is not installed or not on PATH. Install DeepSeek Harness (dsh), then retry.",profile_missing:`DSH profile "${e}" does not exist yet. Create/boot it once with: ${r}`,bridge_missing:`Grix Bridge is not installed in DSH profile "${e}". Install it from the DeepSeek Harness toolbar (or the dsh_install_bridge action), then restart the profile if it is already running.`,bridge_update_required:`Grix Bridge in DSH profile "${e}" needs an update (installed ${i.installedBridgeVersion??"none"}, expected ${i.bundledBridgeVersion}${i.installedBridgeVersion===i.bundledBridgeVersion?", content hash mismatch":""}). Update from the toolbar, then restart the profile \u2014 dsh does not hot-load plugin upgrades.`,profile_restart_required:n};return Object.assign(new Error(s[i.readiness]),{code:i.readiness})}function de(){return H().tarball}function H(){const i=[D(new URL("../../assets/dsh-bridge/",import.meta.url)),D(new URL("../../../dist/assets/dsh-bridge/",import.meta.url))].find(t=>d(o(t,"manifest.json")));if(!i)throw Object.assign(new Error("Bundled Grix DSH Bridge asset is unavailable; run the Connector build first"),{code:"bridge_asset_missing"});const e=JSON.parse(h(o(i,"manifest.json"),"utf8"));if(typeof e.tarball!="string"||!e.tarball||typeof e.bridgeVersion!="string"||!e.bridgeVersion)throw Object.assign(new Error("Invalid Grix DSH Bridge asset manifest"),{code:"bridge_asset_invalid"});const r=E(o(i,e.tarball),e.bridgeVersion);if(Number(e.size)!==m(r.tarball).size)throw Object.assign(new Error("Grix DSH Bridge asset size mismatch"),{code:"bridge_asset_invalid"});if(typeof e.integrity=="string"&&e.integrity.startsWith("sha512-")&&e.integrity!==r.integrity)throw Object.assign(new Error("Grix DSH Bridge asset integrity mismatch"),{code:"bridge_asset_invalid"});return r}function E(i,e){if(!d(i)||!m(i).isFile())throw Object.assign(new Error(`Grix DSH Bridge asset is missing: ${i}`),{code:"bridge_asset_missing"});if(m(i).size>U)throw Object.assign(new Error("Grix DSH Bridge asset exceeds the 2 MiB safety limit"),{code:"bridge_asset_invalid"});const r=e??/grix-dsh-bridge-([0-9A-Za-z.+-]+)\.tgz$/.exec(i)?.[1];if(!r)throw Object.assign(new Error("Cannot determine Grix DSH Bridge version"),{code:"bridge_asset_invalid"});const t=`sha512-${N("sha512").update(h(i)).digest("base64")}`;return{tarball:i,version:r,integrity:t}}async function A(i,e){const r=J(i);y(r,{recursive:!0,mode:448});const t=o(r,"install.lock");let n=j(t);if(n===null){let s=0;try{s=Number(h(t,"utf8").trim())}catch{}let a=!1;try{a=s===0&&Date.now()-m(t).mtimeMs>5*6e4}catch{}if(a||Number.isSafeInteger(s)&&s>0&&!X(s)){try{f(t,{force:!0})}catch{}n=j(t)}}if(n===null)throw Object.assign(new Error(`Another Grix DSH Bridge install is active for profile ${i.profileName}`),{code:"bridge_install_busy"});try{return b(n,`${process.pid}
6
+ `,"utf8"),await e()}finally{G(n);try{f(t,{force:!0})}catch{}}}function j(i){try{return T(i,"wx",384)}catch(e){if(e.code==="EEXIST")return null;throw Object.assign(new Error(`Cannot acquire Grix DSH Bridge install lock: ${w(e)}`),{code:"bridge_install_failed"})}}function X(i){try{return process.kill(i,0),!0}catch(e){return e.code==="EPERM"}}async function le(i,e){const r=await B(i?.trim()||"dsh");return r?R(r,e):null}async function R(i,e){try{return(await g(i,["--version"],e)).trim().split(/\s+/)[0]||null}catch(r){return $.warn(x,`dsh --version \u63A2\u6D4B\u5931\u8D25\uFF08${i}\uFF09\uFF1A${w(r)}`),null}}async function g(i,e,r){try{const t=M(i,e);return(await z(t.command,t.args,{env:{...process.env,...r?{DSH_HOME:I(r)}:{}},timeout:6e4,maxBuffer:8*1024*1024,windowsVerbatimArguments:t.windowsVerbatimArguments})).stdout}catch(t){const n=t&&typeof t=="object"?t:{};throw Object.assign(new Error(w(t)),{code:"dsh_command_failed",stderr:typeof n.stderr=="string"?v(n.stderr):void 0})}}function v(i){return i.replace(/(api[_-]?key|authorization|bearer)\s*[:=]\s*\S+/gi,"$1=[REDACTED]")}function w(i){const e=i&&typeof i=="object"?i:{};return v(String(e.stderr??e.message??i??"unknown error")).replace(/[\r\n]+/g," ").slice(0,1024)}function Y(i){const e=i&&typeof i=="object"?i:{};return v(String(e.stderr??e.message??i??"unknown error")).slice(0,8*1024)}export{oe as DshBridgeInstaller,de as defaultBridgeTarball,ae as errorForDshBridgeReadiness,le as readDshCliVersion};
@@ -1,2 +1,2 @@
1
- import{createWriteStream as k,existsSync as A,mkdirSync as K,readFileSync as C,renameSync as F,rmSync as H,writeFileSync as j}from"node:fs";import{join as R}from"node:path";import{log as d}from"../../core/log/index.js";import{resolveCliPath as G}from"../../core/util/cli-probe.js";import{killProcessGroup as B,spawnCommand as q}from"../../core/runtime/spawn.js";import{errorForDshBridgeReadiness as I}from"./bridge-installer.js";import{bridgeDiscoveryDirectory as N,discoverDshBridgeEndpoints as y,profileHasWebApp as U}from"./profile-resolver.js";const c="deepseek-harness-profile-supervisor",O=45e3,J=500;function W(e){return{...process.env,DSH_HOME:e}}const m=new Map,p=new Map;function $(e,r,i="coalesce"){const t=m.get(e.profileKey);if(t&&i==="coalesce")return t.promise;const o=(t?t.promise.catch(()=>{}).then(()=>r()):r()).finally(()=>{m.get(e.profileKey)?.promise===o&&m.delete(e.profileKey)});return m.set(e.profileKey,{promise:o}),o}async function ce(e){return $(e.installer.identity,()=>T(e))}async function fe(e){return $(e.installer.identity,()=>Y(e))}async function Y(e){const r=e.autoInstall!==!1;let i=await e.installer.status();return r&&["profile_missing","bridge_missing","bridge_update_required"].includes(i.readiness)&&(i=await e.installer.install()),i.readiness==="ready"&&!e.reloadManaged?i:T(e)}async function T(e){const r=e.installer,i=e.autoStart!==!1,t=e.readyTimeoutMs??O;let n=await r.status();if(e.reloadManaged&&(n=await z(r,n,t),n.readiness==="ready")||n.readiness==="ready")return n;if(!i){const l=I(n);if(l)throw l;return n}if(n.readiness==="profile_restart_required"&&n.endpointCount===0)await P(r,n.identity),n=await S(g,r,t),g(n)||await b(n.identity,"bridge endpoint did not appear");else if(n.readiness==="profile_restart_required"&&n.endpointCount>0&&n.runningBridgeVersion&&n.installedBridgeVersion){const l=y(n.identity),a=u(n.identity),w=a&&l.find(s=>s.pid===a.pid),M=n.runningBridgeVersion!==n.installedBridgeVersion?"bridge upgrade":"bridge content refresh";w&&a&&f(a.pid)?(d.info(c,`restarting connector-managed profile=${n.identity.profileName} pid=${a.pid} for ${M}`),await h(n.identity,a.pid)):d.info(c,`starting connector-managed profile=${n.identity.profileName} for ${M}; external profile processes are left untouched`),await P(r,n.identity),n=await S(g,r,t),g(n)||await b(n.identity,"bridge endpoint did not appear after upgrade restart")}if(n.readiness==="ready")return Q(n),n;const o=I(n);if(o)throw o;return n}async function z(e,r,i){const t=r.identity,n=u(t);if(!n||!f(n.pid))return r;const o=y(t);if(!o.some(w=>w.pid===n.pid)&&o.length>0)return r;d.info(c,`reloading connector-managed profile=${t.profileName} pid=${n.pid} after settings write`),await h(t,n.pid),await P(e,t);const a=await S(g,e,i);return g(a)||await b(t,"bridge endpoint did not appear after settings reload"),a}function Q(e){d.info(c,`bridge ready profile=${e.identity.profileName} endpoints=${e.endpointCount} bridge=${e.runningBridgeVersion}`)}async function P(e,r){const i=u(r);if(i&&f(i.pid)){if(y(r).some(x=>x.pid===i.pid)){d.info(c,`reusing connector-managed profile=${r.profileName} pid=${i.pid}`);return}d.warn(c,`restarting stuck connector-managed profile=${r.profileName} pid=${i.pid} (alive without endpoint)`),await h(r,i.pid)}else i&&D(r);const t=await G(e.command);if(!t)throw Object.assign(new Error("dsh is not installed or not on PATH"),{code:"dsh_missing"});const n=X(r),o=N(r);K(o,{recursive:!0,mode:448});const l=R(o,"managed-profile.log"),a=k(l,{flags:"a",mode:384}),w=W(r.dshHome),s=q(t,n,{cwd:r.profileRoot,env:w,stdio:["ignore","pipe","pipe"],detached:!0}).process;if(!s.pid)throw a.end(),Object.assign(new Error(`Failed to start DSH profile "${r.profileName}"`),{code:"profile_start_failed"});s.stdout?.pipe(a,{end:!1}),s.stderr?.pipe(a,{end:!1}),s.once("exit",(E,v)=>{d.warn(c,`managed profile exited profile=${r.profileName} pid=${s.pid} code=${E} signal=${v}`),p.get(r.profileKey)===s&&p.delete(r.profileKey),u(r)?.pid===s.pid&&D(r);try{a.end()}catch{}}),s.unref(),p.set(r.profileKey,s),Z(r,{schemaVersion:1,profileKey:r.profileKey,profileName:r.profileName,pid:s.pid,startedAt:new Date().toISOString(),command:t,args:n}),d.info(c,`started connector-managed profile=${r.profileName} pid=${s.pid} args=${n.join(" ")}`)}async function b(e,r){const i=u(e);i&&(d.warn(c,`stopping stuck connector-managed profile=${e.profileName} pid=${i.pid} reason=${r}`),await h(e,i.pid))}async function h(e,r){const i=p.get(e.profileKey);if(i?.pid===r){try{B(i,"SIGTERM")}catch{}p.delete(e.profileKey)}else if(f(r))try{process.kill(r,"SIGTERM")}catch{}const t=Date.now()+5e3;for(;Date.now()<t&&f(r);)await V(100);if(f(r))try{process.kill(r,"SIGKILL")}catch{}D(e)}function X(e){return U(e.profileRoot,e.profileName)?["--profile",e.profileName,"--port","0"]:["--profile",e.profileName]}async function S(e,r,i){const t=Date.now()+i;let n=await r.status();for(;Date.now()<t;){if(e(n))return n;const o=u(r.identity);if(o&&!f(o.pid))throw D(r.identity),Object.assign(new Error(`Connector-managed DSH profile "${r.identity.profileName}" exited before Bridge became ready`),{code:"profile_start_failed"});await V(J),n=await r.status()}return n}function _(e){return R(N(e),"managed-profile.json")}function u(e){try{const r=JSON.parse(C(_(e),"utf8"));return r.schemaVersion!==1||typeof r.pid!="number"||r.profileKey!==e.profileKey?null:r}catch{return null}}function Z(e,r){const i=N(e);K(i,{recursive:!0,mode:448});const t=_(e),n=`${t}.${process.pid}.tmp`;j(n,`${JSON.stringify(r,null,2)}
2
- `,{mode:384}),F(n,t)}function D(e){try{H(_(e),{force:!0})}catch{}}function f(e){try{return process.kill(e,0),!0}catch(r){return r.code==="EPERM"}}function V(e){return new Promise(r=>setTimeout(r,e))}function le(){m.clear();for(const e of p.values())try{e.pid&&B(e,"SIGKILL")}catch{}p.clear()}function pe(e){return A(_(e))}async function ue(e){const r=m.get(e.profileKey);r&&await r.promise.catch(()=>{})}async function ge(e,r=O){let i="failed";return await $(e.identity,async()=>(i=await ee(e,r),L(e,i==="restarted"?"ready":"profile_restart_required")),"queue"),i}async function ee(e,r){const i=e.identity,t=u(i);if(!t||!f(t.pid))return"not_managed";const n=y(i);if(n.length>0&&!n.some(o=>o.pid===t.pid))return"not_managed";try{return d.info(c,`restarting connector-managed profile=${i.profileName} pid=${t.pid} for plugin toggle`),await h(i,t.pid),await P(e,i),(await S(g,e,r)).readiness==="ready"?"restarted":"failed"}catch(o){return d.warn(c,`plugin-toggle restart failed profile=${i.profileName}: ${o instanceof Error?o.message:String(o)}`),"failed"}}function g(e){return e.readiness==="ready"}function me(e,r){return $(e.identity,async()=>(await r,L(e,"ready")))}function L(e,r){return{readiness:r,command:e.command,commandPath:null,dshVersion:null,runningDshVersion:null,identity:e.identity,installedBridgeVersion:null,bundledBridgeVersion:"",runningBridgeVersion:null,endpointCount:0}}export{ue as awaitDshProfileIdle,X as buildDshProfileBootArgs,ce as ensureDshBridgeReady,me as holdDshProfileInflightForTests,pe as managedProfileRecordExists,W as managedProfileSpawnEnv,fe as prepareDshProfileBridge,le as resetDshProfileSupervisorForTests,ge as restartManagedProfileIfOwned};
1
+ import{createWriteStream as H,existsSync as j,mkdirSync as v,readFileSync as U,renameSync as q,rmSync as J,writeFileSync as W}from"node:fs";import{join as K}from"node:path";import{log as d}from"../../core/log/index.js";import{resolveCliPath as Y}from"../../core/util/cli-probe.js";import{killProcessGroup as O,spawnCommand as z}from"../../core/runtime/spawn.js";import{errorForDshBridgeReadiness as A}from"./bridge-installer.js";import{bridgeDiscoveryDirectory as M,discoverDshBridgeEndpoints as g,profileHasWebApp as Q}from"./profile-resolver.js";const c="deepseek-harness-profile-supervisor",I=45e3,T=5*6e4,X=500;function Z(e){return{...process.env,DSH_HOME:e}}const w=new Map,m=new Map;function $(e,r,n="coalesce"){const t=w.get(e.profileKey);if(t&&n==="coalesce")return t.promise;const i=(t?t.promise.catch(()=>{}).then(()=>r()):r()).finally(()=>{w.get(e.profileKey)?.promise===i&&w.delete(e.profileKey)});return w.set(e.profileKey,{promise:i}),i}async function $e(e){return $(e.installer.identity,()=>F(e))}async function Pe(e){return $(e.installer.identity,()=>ee(e))}async function ee(e){const r=e.autoInstall!==!1;let n=await e.installer.status();return r&&["profile_missing","bridge_missing","bridge_update_required"].includes(n.readiness)&&(n=await e.installer.install()),n.readiness==="ready"&&!e.reloadManaged?(E(n.identity),n):F(e)}async function F(e){const r=e.installer,n=e.autoStart!==!1,t=e.readyTimeoutMs??I,o=e.bootGraceMs??T;let i=await r.status();if(e.reloadManaged&&(i=await re(r,i,t,o)),i.readiness==="ready")return E(i.identity),i;if(!n){const a=A(i);if(a)throw a;return i}if(i.readiness==="profile_restart_required"&&(i.endpointCount>0&&await ne(i),await _(r,i.identity,o),i=await N(r,t),S(i)||await L(i.identity,o,"bridge endpoint did not appear")),i.readiness==="ready")return te(i),i;const s=A(i);if(s)throw s;return i}async function re(e,r,n,t){const o=r.identity,i=p(o);if(!i||!l(i.pid))return r;const s=g(o);if(!s.some(D=>y(i,D))&&s.length>0)return r;d.info(c,`reloading connector-managed profile=${o.profileName} pid=${i.pid} after settings write`),await h(o,i.pid),await _(e,o,t);const u=await N(e,n);return S(u)||await L(o,t,"bridge endpoint did not appear after settings reload"),u}async function ne(e){const r=e.identity,n=p(r),t=g(r),o=e.runningBridgeVersion&&e.installedBridgeVersion&&e.runningBridgeVersion!==e.installedBridgeVersion?"bridge upgrade":"bridge content refresh";if(n&&l(n.pid)&&t.some(i=>y(n,i))){d.info(c,`restarting connector-managed profile=${r.profileName} pid=${n.pid} for ${o}`),await h(r,n.pid);return}d.info(c,`starting connector-managed profile=${r.profileName} for ${o}; external profile processes are left untouched`)}async function N(e,r){const n=await se(S,e,r);return S(n)&&E(e.identity),n}async function L(e,r,n){const t=de(e,r);if(t)throw d.info(c,`managed profile=${e.profileName} pid=${t.pid} still booting; left running (${n})`),ie(e,t);await oe(e,n)}function ie(e,r){return Object.assign(new Error(`DSH profile "${e.profileName}" is still starting (pid ${r.pid}); a first boot installs the profile dependencies before Grix Bridge can listen. The Connector keeps it running \u2014 send the message again in a moment and it will attach automatically.`),{code:"profile_starting"})}function te(e){d.info(c,`bridge ready profile=${e.identity.profileName} endpoints=${e.endpointCount} bridge=${e.runningBridgeVersion}`)}async function _(e,r,n){const t=p(r);if(t&&l(t.pid)){if(g(r).some(x=>y(t,x))){d.info(c,`reusing connector-managed profile=${r.profileName} pid=${t.pid}`);return}if(k(t,n)){d.info(c,`waiting on booting connector-managed profile=${r.profileName} pid=${t.pid}`);return}d.warn(c,`restarting stuck connector-managed profile=${r.profileName} pid=${t.pid} (alive without endpoint)`),await h(r,t.pid)}else t&&b(r);const o=await Y(e.command);if(!o)throw Object.assign(new Error("dsh is not installed or not on PATH"),{code:"dsh_missing"});const i=ae(r),s=M(r);v(s,{recursive:!0,mode:448});const a=K(s,"managed-profile.log"),u=H(a,{flags:"a",mode:384}),D=Z(r.dshHome),f=z(o,i,{cwd:r.profileRoot,env:D,stdio:["ignore","pipe","pipe"],detached:process.platform!=="win32"}).process;if(!f.pid)throw u.end(),Object.assign(new Error(`Failed to start DSH profile "${r.profileName}"`),{code:"profile_start_failed"});f.stdout?.pipe(u,{end:!1}),f.stderr?.pipe(u,{end:!1}),f.once("exit",(B,R)=>{d.warn(c,`managed profile exited profile=${r.profileName} pid=${f.pid} code=${B} signal=${R}`),m.get(r.profileKey)===f&&m.delete(r.profileKey),p(r)?.pid===f.pid&&b(r);try{u.end()}catch{}}),f.unref(),m.set(r.profileKey,f),V(r,{schemaVersion:1,profileKey:r.profileKey,profileName:r.profileName,pid:f.pid,startedAt:new Date().toISOString(),command:o,args:i}),d.info(c,`started connector-managed profile=${r.profileName} pid=${f.pid} args=${i.join(" ")}`)}async function oe(e,r){const n=p(e);n&&(d.warn(c,`stopping stuck connector-managed profile=${e.profileName} pid=${n.pid} reason=${r}`),await h(e,n.pid))}async function h(e,r){const n=p(e)?.endpointPid,t=n&&n!==r&&g(e).some(a=>a.pid===n)?n:null,o=t?[r,t]:[r],i=m.get(e.profileKey);if(i?.pid===r){try{O(i,"SIGTERM")}catch{}m.delete(e.profileKey)}else for(const a of o)if(l(a))try{process.kill(a,"SIGTERM")}catch{}const s=Date.now()+5e3;for(;Date.now()<s&&o.some(l);)await G(100);for(const a of o)if(l(a))try{process.kill(a,"SIGKILL")}catch{}b(e)}function ae(e){return Q(e.profileRoot,e.profileName)?["--profile",e.profileName,"--port","0"]:["--profile",e.profileName]}async function se(e,r,n){const t=Date.now()+n;let o=await r.status();for(;Date.now()<t;){if(e(o))return o;const i=p(r.identity);if(i&&!l(i.pid))throw b(r.identity),Object.assign(new Error(`Connector-managed DSH profile "${r.identity.profileName}" exited before Bridge became ready`),{code:"profile_start_failed"});await G(X),o=await r.status()}return o}function P(e){return K(M(e),"managed-profile.json")}function p(e){try{const r=JSON.parse(U(P(e),"utf8"));return r.schemaVersion!==1||typeof r.pid!="number"||r.profileKey!==e.profileKey?null:r}catch{return null}}function V(e,r){const n=M(e);v(n,{recursive:!0,mode:448});const t=P(e),o=`${t}.${process.pid}.tmp`;W(o,`${JSON.stringify(r,null,2)}
2
+ `,{mode:384}),q(o,t)}function y(e,r){return r.pid===e.pid||r.pid===e.endpointPid}function k(e,r){const n=Date.parse(e.startedAt);return Number.isFinite(n)?Date.now()-n<r:!1}function de(e,r){const n=p(e);return!n||!l(n.pid)||g(e).some(t=>y(n,t))?null:k(n,r)?n:null}function E(e){const r=p(e);if(!r||typeof r.endpointPid=="number"||!l(r.pid))return;const n=g(e);if(n.some(s=>s.pid===r.pid))return;const t=Date.parse(r.startedAt);if(!Number.isFinite(t))return;const o=n.filter(s=>{const a=Date.parse(s.startedAt);return Number.isFinite(a)&&a>=t});if(o.length!==1)return;const i=o[0];V(e,{...r,endpointPid:i.pid}),d.info(c,`adopted managed bridge endpoint profile=${e.profileName} wrapper=${r.pid} pid=${i.pid}`)}function b(e){try{J(P(e),{force:!0})}catch{}}function l(e){try{return process.kill(e,0),!0}catch(r){return r.code==="EPERM"}}function G(e){return new Promise(r=>setTimeout(r,e))}function be(){w.clear();for(const e of m.values())try{e.pid&&O(e,"SIGKILL")}catch{}m.clear()}function Se(e){return j(P(e))}async function De(e){const r=w.get(e.profileKey);r&&await r.promise.catch(()=>{})}async function Me(e,r=I){let n="failed";return await $(e.identity,async()=>(n=await ce(e,r),C(e,n==="restarted"?"ready":"profile_restart_required")),"queue"),n}async function ce(e,r){const n=e.identity,t=p(n);if(!t||!l(t.pid))return"not_managed";const o=g(n);if(o.length>0&&!o.some(i=>y(t,i)))return"not_managed";try{return d.info(c,`restarting connector-managed profile=${n.profileName} pid=${t.pid} for plugin toggle`),await h(n,t.pid),await _(e,n,T),(await N(e,r)).readiness==="ready"?"restarted":"failed"}catch(i){return d.warn(c,`plugin-toggle restart failed profile=${n.profileName}: ${i instanceof Error?i.message:String(i)}`),"failed"}}function S(e){return e.readiness==="ready"}function Ne(e,r){return $(e.identity,async()=>(await r,C(e,"ready")))}function C(e,r){return{readiness:r,command:e.command,commandPath:null,dshVersion:null,runningDshVersion:null,identity:e.identity,installedBridgeVersion:null,bundledBridgeVersion:"",runningBridgeVersion:null,endpointCount:0}}export{De as awaitDshProfileIdle,ae as buildDshProfileBootArgs,$e as ensureDshBridgeReady,Ne as holdDshProfileInflightForTests,Se as managedProfileRecordExists,Z as managedProfileSpawnEnv,Pe as prepareDshProfileBridge,be as resetDshProfileSupervisorForTests,Me as restartManagedProfileIfOwned};
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "bridgeVersion": "4.3.1",
4
- "tarball": "grix-dsh-bridge-4.3.1.tgz",
5
- "size": 22531,
3
+ "bridgeVersion": "4.3.3",
4
+ "tarball": "grix-dsh-bridge-4.3.3.tgz",
5
+ "size": 22532,
6
6
  "unpackedSize": 89865,
7
- "shasum": "4986c0efcce74e1bf87a5b5ff4fcaf5dd56c8e92",
8
- "integrity": "sha512-vxviwM7PAw6KMAFY/iZ7yF89rwJfzFiRRURzI4kTs0WWk+50TO9Ulbd5UMCnenE3P3GmKHWARkq0QcpRPtVa7g=="
7
+ "shasum": "134139721d37b4d493f5da3c92c3cc99069fea4e",
8
+ "integrity": "sha512-Xzh4MiY7zJBq/P+N/mpNKCnrLqIggl4voSvV7PNu/Vj//RdkBJH75Wo+7rFBkV7nVyyhJj7nD4z4XWBX28P3Ag=="
9
9
  }
@@ -1,9 +1,9 @@
1
- import T from"node:path";import{realpath as te,stat as Q}from"node:fs/promises";import{tmpdir as ne}from"node:os";import{createHash as O,randomUUID as B}from"node:crypto";import{ConnectionManager as ie}from"../core/aibot/index.js";import{AUDIT_LOCAL_ACTION_TYPES as se}from"../core/aibot/types.js";import{ClaudeAdapter as N}from"../adapter/claude/index.js";import{CodexAdapter as W}from"../adapter/codex/index.js";import"../adapter/claude/session-history.js";import"../adapter/codex/session-history.js";import"../adapter/pi/session-history.js";import"../adapter/opencode/session-history.js";import"../adapter/codewhale/session-history.js";import"../adapter/deepseek-harness/session-history.js";import{PiAdapter as oe}from"../adapter/pi/index.js";import{AcpAdapter as y}from"../adapter/acp/index.js";import{OpenHumanAdapter as re}from"../adapter/openhuman/index.js";import{CursorAdapter as ae}from"../adapter/cursor/index.js";import{CodeWhaleAdapter as de}from"../adapter/codewhale/index.js";import{OpenCodeAdapter as F}from"../adapter/opencode/index.js";import{AgyAdapter as G}from"../adapter/agy/index.js";import{DshJsonRpcAdapter as le,buildDshBindingToolbarMeta as ce,DEFAULT_DSH_PRESETS as he,listDshPlugins as ue,listDshSkills as pe,listDshProfiles as ge,normalizeDshReasoningEffort as fe,normalizeDshThinking as me,resolveDshAgentPreset as ve,resolveDshCatalogForToolbar as _e,resolveDshModeId as j,resolveDshSelectedProfileName as Se}from"../adapter/deepseek-harness/index.js";import{LOCAL_ACTION_TYPES as k,SESSION_CONTROL_ERROR_CODES as E,SESSION_CONTROL_VERBS as S,SESSION_MODE_IDS as be}from"../adapter/claude/protocol-contract.js";import{isAuditLocalActionType as Ce}from"../audit/query/audit-local-actions.js";import{shouldEnableRawApiCapture as K}from"../audit/raw-capture/types.js";import{syncDefaultSkillsToDir as we}from"../default-skills/index.js";import{buildWireSkills as Ae}from"../core/skill-sync/sync-state.js";import{executeEventTool as Ee}from"../core/mcp/event-tool-executor.js";import{fetchAvailableModels as ke}from"../adapter/claude/model-list.js";import{applyProxyEnv as Re,getProxyManager as ye}from"../core/proxy/index.js";import{getKiroRelaySpawnEnv as Pe}from"../core/proxy/kiro-relay.js";import{supportsKiroCwRelay as Te}from"../core/config/provider-env.js";import{buildProviderEnv as xe}from"../core/config/provider-env.js";import{isClaudeDirectEnv as De,stripGrixRelayEnv as Me}from"../core/config/claude-direct-env.js";import{sweepNativeProviderResidue as He}from"./native-provider-sweep.js";import{scanCodexSessions as Le}from"../adapter/codex/session-scanner.js";import{scanClaudeSessions as $e}from"../adapter/claude/session-scanner.js";import{reasonixStampFromSessionId as Ie,resolveAcpAgentTypes as Qe,scanAcpSessions as Oe,scanReasonixSessionTitles as Be}from"../adapter/acp/session-scanner.js";import{scanPiSessions as Fe}from"../adapter/pi/session-scanner.js";import{scanCodeWhaleSessions as qe}from"../adapter/codewhale/session-scanner.js";import{scanCursorSessions as Ue}from"../adapter/cursor/session-scanner.js";import{scanOpenCodeSessions as Ne}from"../adapter/opencode/session-scanner.js";import{scanDshSessions as We}from"../adapter/deepseek-harness/session-scanner.js";import{SessionScanCache as P,resolveCodexLeafDirs as Ge,resolveClaudeLeafDirs as je,resolveAcpLeafDirs as Ke,resolvePiLeafDirs as ze,resolveCodeWhaleLeafDirs as Je,resolveCursorLeafDirs as Ye,resolveOpenCodeLeafDirs as Xe,resolveDshLeafDirs as Ve,resolveReasonixLeafDirs as Ze}from"./session-scan-cache.js";import{log as p,ConversationLog as et,AgentApiPacketLog as tt,BridgeEventLog as nt,GRIX_PATHS as L}from"../core/log/index.js";import{routeSessionControlCommand as it,routeSessionControlLocalAction as st}from"./session-control-router.js";import{maybeOfferCliInstall as ot,handleCliInstallQuestionReply as rt,handleCliInstallInteractionReply as at,runConfirmedCliInstall as dt}from"./cli-install-flow.js";import{handleEventCancel as lt,waitForEventDone as ct,handleAibotStop as ht,killAndResumeStopSlot as ut,handleAibotRevoke as pt}from"./event-stop.js";import{handleConfigureGatewayProvider as gt,getAuditLocalActionHandler as ft,handleAuditLocalAction as mt,handleConnectorRollback as vt,getRelayStateSyncer as _t,relayStateSyncOnConnect as St,reportRelayStateLocalChange as bt,handleApplyRelayState as Ct,fetchRelayCredential as wt,isSharedInstance as At}from"./connector-ops.js";import{unbindSession as Et,handleUnbindTextCommand as kt,handleUnbindLocalAction as Rt,handleListSessionsTextCommand as yt,handleListSessionsLocalAction as Pt,handleSyncHistoryLocalAction as Tt}from"./session-list.js";import{handleCodexSessionControlOpen as xt,handleSessionControlForPool as Dt,handleSessionControlLocalActionForPool as Mt,handleCodexSessionControlLocalActionOpen as Ht,handleCursorSessionControlLocalActionOpen as Lt,handlePiSessionControlOpen as $t,handlePiSessionControlRestart as It,handlePiSessionControlRestartLocalAction as Qt,syncOpenCodeBinding as Ot,isWorkspaceFreeClient as Bt,ensureDefaultBindingForWorkspaceFreeClient as Ft,bindSessionForPool as qt,deferredCallbacks as Ut,handleOpenHumanSessionControlOpen as Nt,handleCodeWhaleSessionControlOpen as Wt,handleCodeWhaleSessionControlLocalActionOpen as Gt,handleDeepSeekSessionControlLocalActionOpen as jt}from"./session-control-open.js";import{handleGetSessionUsage as Kt,handleThreadCompact as zt}from"./session-usage.js";import{handleSkillDeleteLocalAction as Jt,handleSkillUploadLocalAction as Yt,handleSkillEnableLocalAction as Xt,handleSkillRefreshLocalAction as Vt,handleSkillDisableLocalAction as Zt,computeSkillReport as en,reportSessionSkills as tn,skillsSyncGroupKey as nn,forceRefreshSkills as sn,adoptSkillsWireHashFromDisk as on,buildLibrarySkillsReport as rn,skillLookupEnv as an}from"./skill-actions.js";import{normalizeClaudeModeId as dn,handleExecCommandOptions as ln,resolveSessionModelId as cn,resolveSessionModeId as hn,resolveCursorSessionModeId as un,resolveClaudeSessionEffort as pn,resolveClaudeSessionModeId as gn,currentClaudeModeId as fn,resolveCodexSessionModelId as mn,resolveCodexNewSessionGlobalDefault as vn,pinCodexGlobalDefault as _n,buildCursorToolbarMeta as Sn,buildAgyToolbarMeta as bn,buildAgyQuotaMeta as Cn,sendAgyBindingCard as wn,refreshAndPushAgyQuota as An,handleAgySetModel as En,buildClaudeToolbarMeta as kn}from"./toolbar-meta.js";import{resolveProviderQuotaSource as Rn,maybeQueryProviderQuota as yn,startProviderQuotaTimer as Pn,stopProviderQuotaTimer as Tn,refreshAndPushProviderQuota as xn,pushProviderQuotaToBindings as Dn,enrichProviderQuotaMeta as Mn,providerQuotaMetaPayload as Hn,refreshProviderQuotaForSession as Ln,refreshQuotaAfterModelSwitch as $n,doRefreshQuotaAfterModelSwitch as In}from"./provider-quota.js";import{handleGetRateLimits as Qn,resolveRateLimitWakeSessionId as On,wakeRateLimitSlot as Bn}from"./rate-limits.js";import{RevokeHandler as Fn}from"./revoke-handler.js";import{AdapterPool as qn}from"./adapter-pool.js";import{parseSessionControlCommand as Un,handleSessionControlCommand as Nn,handleSessionControlLocalAction as Wn}from"./session-controller.js";import{isOpenSessionDirectiveMessage as Gn,parseExecApprovalResolutionMessage as jn,parseAgentQuestionReplyMessage as Kn}from"../core/protocol/interaction-parser.js";import{isCliMissingError as zn,sessionControlOpenFailure as Jn}from"./cli-install-offer.js";import{handleAcpSetModel as z,handleAcpSetMode as J,resolveAcpInitialDefaults as Yn}from"./acp-toolbar-persist.js";import{SessionBindingStore as Xn}from"../core/persistence/session-binding-store.js";import{handleFileListAction as Vn,handleCreateFolderAction as Zn,serveLocalFile as ei,realHomeDir as Y}from"../core/files/index.js";import{getMachineName as ti}from"../core/util/index.js";import{uploadReplyFileToAgentMedia as ni}from"../core/protocol/agent-api-media.js";import{ActiveEventStore as ii}from"../core/persistence/active-event-store.js";import{PendingEventCoordinator as si}from"./pending-event-coordinator.js";import{LifecycleBarrier as oi}from"./lifecycle-barrier.js";import{QUEUE_COMPOSING_TTL_MS as ri}from"./event-queue.js";import{DEFAULT_CONNECTOR_RUNTIME_CONFIG as ai,applyConnectorRuntimeConfigPatch as di,extractConnectorRuntimeConfigPatch as li}from"./runtime-config.js";import{DEFAULT_QUOTE_TRIGGER_BY_ADAPTER as ci,SendController as hi}from"./send-controller.js";import{providerQuotaToRateLimits as ui,providerQuotaToCodexRateLimits as pi}from"../core/provider-quota/index.js";import{buildToolUseCard as D,buildToolResultCard as M,buildDshOnlineToolCard as gi,buildLocalGrixCardLink as X}from"./tool-card-utils.js";import{planRawEventDelivery as fi,buildAuxiliaryDetailText as mi}from"./raw-event-delivery.js";import{DeferredEventManager as vi}from"./deferred-events.js";import{buildAgentProbeResult as _i,PROBE_CACHE_TTL_STATIC_MS as Si,PROBE_CACHE_TTL_FULL_MS as bi}from"./probe-helper.js";import{BridgeAuditController as Ci}from"../audit/integration/bridge-audit-controller.js";import{isSettlableAuditProducer as wi,NoopAuditProducer as Ai}from"../audit/producer/audit-producer.js";import{buildAuditStatePayload as $,AuditPreparationFailedError as Ei,AuditTurnScopeUnsupportedError as ki}from"../audit/core/audit-state.js";import{extractAuditOptions as V,freezeAuditOptions as Ri,stripAuditOptions as yi}from"../audit/core/audit-options.js";import{AuditSessionOptionsError as Pi}from"../audit/core/audit-session-registry.js";const Ti=600*1e3,Z=1800*1e3,xi=60*1e3,Di=4e3;function Mi(U,e,t){const s=O("sha256").update(U).update("\0").update(e).update("\0").update(t).digest("hex");return T.join(L.data,"audit-source","reasonix",`${s}.jsonl`)}const I=new Set(["claude","acp","agy","cursor","codex","deepseek-harness"]),ee=new Set(["claude","codex","cursor","codewhale","opencode","pi","openhuman","agy","acp","deepseek-harness"]),q=3;class ao{config;name;aibotHandle;aibotConfig;pool;stopped=!1;startupAbortController=new AbortController;stopPromise=null;dropPendingEventsRequested=!1;pendingEventsDropped=!1;revokeHandler=new Fn;sessionBindings=new Map;deferredMgr;sendCtrl=new hi(ai);bindingStore;globalConfigStore;upgradeTrigger=null;daemonShutdownRequester=null;lifecycleBusyChecker=null;lifecycleAdmissionCloser=null;lifecycleAdmissionRestorer=null;installAgentHandler=null;pendingCliInstalls=new Map;agentDeletedHandler=null;shareSetHandler=null;skillSyncHandler=null;providerConfigHandler=null;relayStateApplyPorts=null;relayStateSyncer=null;agentProfile={agentName:"",introduction:""};agentSystemPrompt="";activeEventStore;pendingEvents;pendingStartedEventIds=new Set;lifecycleBarrier=new oi;cachedRateLimits=null;cachedRateLimitsSampledAtMs=null;cachedCodexContextWindow=null;cachedCodexTokenUsage=null;cachedCodexUsageSampledAtMs=null;cachedAcpContextWindow=null;cachedAcpContextWindowSampledAtMs=null;cachedClaudeRateLimitState=null;cachedProviderQuota=null;cachedProviderQuotaSampledAtMs=null;cachedProviderQuotaKey=null;sessionProviderHints=new Map;sessionProviderQuotas=new Map;sessionProviderMeta=new Map;lastModelSwitchQuotaRefresh=null;claudeWorkerStatus=new Map;lastReportedSkillsHash="";lastReportedSkillsWireHash="";conversationLog=null;packetLog=null;providerQuotaTimer=null;eventSessionIndex=new Map;inflightEvents=new Map;restartCount=new Map;selfDrivenSessions=new Set;selfDrivenLabels=new Map;probeCache=new Map;auditController;auditLocalActionHandler=null;sessionScanCache;reasonixTitleScan=null;isRateLimitsCacheFresh(e){if(!Number.isFinite(e))return!1;const t=Number(e);return t>0&&Date.now()-t<=xi}resolveProviderQuotaSource(e){return Rn(this,e)}maybeQueryProviderQuota(e=!1,t){return yn(this,e,t)}startProviderQuotaTimer(){Pn(this)}stopProviderQuotaTimer(){Tn(this)}refreshAndPushProviderQuota(e=!1){return xn(this,e)}pushProviderQuotaToBindings(e,t=!1){Dn(this,e,t)}enrichProviderQuotaMeta(e,t="standard",s=this.cachedProviderQuota,i=this.cachedProviderQuotaSampledAtMs){return Mn(this,e,t,s,i)}providerQuotaMetaPayload(e,t,s){return Hn(this,e,t,s)}refreshProviderQuotaForSession(e,t,s){return Ln(this,e,t,s)}refreshQuotaAfterModelSwitch(e,t,s){$n(this,e,t,s)}doRefreshQuotaAfterModelSwitch(e,t,s){return In(this,e,t,s)}getFreshClaudeRateLimitState(){const e=this.cachedClaudeRateLimitState;return e&&this.isRateLimitsCacheFresh(e.sampledAt)?e:null}getFreshCodexGlobalRateLimitCache(){const e=this.cachedRateLimits,t=this.cachedCodexContextWindow,s=this.cachedCodexTokenUsage;return{sampledAt:Math.max(this.cachedRateLimitsSampledAtMs??0,this.cachedCodexUsageSampledAtMs??0)||null,rateLimits:e,contextWindow:t,tokenUsage:s,hasData:!!(e||t||s)}}getStatus(){const e=this.pool?.getStatus()??{total:0,ready:0,busy:0};return{name:this.name,agentId:this.config.aibot.agentId,alive:!this.stopped,busy:e.busy>0,wsConnected:this.aibotHandle?.status==="ready",exhausted:this.pool?[...this.pool.getAllSlots()].some(t=>t.respawn.exhausted):!1,adapterType:this.config.adapterType??"acp",clientType:this.config.aibot.clientType,pool:e}}hasPendingWork(){return this.pool?.hasPendingWork()??!1}hasPendingOrBackgroundWork(){return this.lifecycleBarrier.hasActiveAdmissions()||(this.pool?.hasPendingOrBackgroundWork()??!1)}async waitUntilLifecycleIdle(e){const t=()=>this.lifecycleBusyChecker?.()??this.hasPendingOrBackgroundWork();if(t()){const s=Math.round(Z/6e4);p.info(this.name,`${e}: active tasks detected, waiting up to ${s}min until idle before restart (admission stays open while waiting)`);const i=Date.now()+Z,n=5e3,o=600*1e3;let r=Date.now();for(;t()&&!this.stopped;){if(Date.now()>=i)return p.warn(this.name,`${e}: idle wait exceeded ${s}min; abandoning this restart. Admission was never closed, so agents kept serving. A busy state that never clears usually means an adapter leaked its busy flag \u2014 check for a turn that never completed.`),!1;await new Promise(a=>setTimeout(a,n)),Date.now()-r>=o&&(r=Date.now(),p.info(this.name,`${e}: still waiting for active tasks to finish before restart`))}}return this.stopped?!1:(this.closeLifecycleAdmissionForRestart(),t()?(p.warn(this.name,`${e}: work arrived while closing admission; reopening and abandoning this restart`),this.reopenLifecycleAdmissionAfterAbort(),!1):(p.info(this.name,`${e}: all tasks completed, proceeding with restart`),!0))}reopenLifecycleAdmissionAfterAbort(){if(this.lifecycleAdmissionRestorer){this.lifecycleAdmissionRestorer();return}this.openLifecycleAdmission()}relayEnvStale=!1;relayEnvSettledHandler;async recycleAdaptersForRelayChange(){if(!this.pool)return this.relayEnvStale=!1,!0;if(this.hasPendingWork())return this.relayEnvStale=!0,p.info(this.name,"relay changed but agent is busy; adapters keep the old env until the next message (marked stale)"),!1;const e=[...this.pool.getAllSlots()];let t=0,s=!1;for(const i of e){if(this.hasPendingWork())return this.relayEnvStale=!0,p.info(this.name,"new work arrived while recycling; remaining adapters stay stale until the next message"),!1;let n=!1;await this.pool.removeSlot(i.sessionId).catch(o=>{s=!0,n=!0,p.warn(this.name,`failed to recycle adapter slot ${i.sessionId} after relay change: ${o}`)}),n||(t+=1)}return t>0&&p.info(this.name,`recycled ${t} adapter slot(s) so the new Grix relay env takes effect`),s?(this.relayEnvStale=!0,!1):(this.relayEnvStale=!1,this.relayEnvSettledHandler?.(),!0)}setRelayEnvSettledHandler(e){this.relayEnvSettledHandler=e}providerResolver;setProviderResolver(e){this.providerResolver=e}hasStaleRelayEnv(){return this.relayEnvStale}markRelayEnvStale(){this.relayEnvStale=!0}async probe(e={}){const t=e.conversation?"full":"static",s=e.conversation?bi:Si;if(!e.fresh){const a=this.probeCache.get(t);if(a&&Date.now()-a.sampledAt<s)return{...a.result,cached:!0}}const i=this.config.adapterType??"acp",n=this.createAdapter(i,"__probe__"),o=e.conversation&&i==="acp"?()=>this.runAcpConversationProbe(n,e.timeoutMs??1e4):void 0;let r;try{r=await _i({adapter:n,agentName:this.name,clientType:this.config.aibot.clientType,adapterType:i,providerBaseUrl:this.config.providerBaseUrl??null,opts:e,launchConversationProbe:o})}finally{n.stop().catch(()=>{})}return this.probeCache.set(t,{result:r,sampledAt:r.probed_at}),r}async runAcpConversationProbe(e,t){const s=Date.now(),i="__probe__",n=`probe-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,o=this.config.agent.cwd||ne(),r=()=>Date.now()-s;try{await e.start()}catch(h){return{attempted:!0,ok:!1,latency_ms:r(),error:{code:"conversation_failed",message:`start failed: ${h instanceof Error?h.message:String(h)}`}}}if(!e.isAlive())return{attempted:!0,ok:!1,latency_ms:r(),error:{code:"process_not_started",message:"agent process not alive"}};if(e instanceof y)try{await e.bindSession(i,o)}catch{}let a=null;const c=new Promise(h=>{a=g=>{g===n&&h()},e.on("eventDone",a)});e.deliverInboundEvent({event_id:n,session_id:i,content:"ping",msg_id:n}),e.deliverStopEvent(n,i);let d=null;const l=await Promise.race([c.then(()=>!1),new Promise(h=>{d=setTimeout(()=>h(!0),t)})]);return d&&clearTimeout(d),a&&e.removeListener("eventDone",a),l?{attempted:!0,ok:!1,latency_ms:r(),error:{code:"conversation_timeout",message:`no eventDone within ${t}ms`}}:{attempted:!0,ok:!0,latency_ms:r()}}constructor(e,t,s=new Ai){this.config=e,this.auditController=new Ci(s,{onAuditState:n=>{try{this.aibotHandle.sendAuditState($(n,Date.now()))}catch{}}}),wi(s)&&s.addJobSettledHandler((n,o)=>{this.auditController.handleJobSettled(n,o)}),this.name=e.name;const i=e.adapterType??"acp";if(this.sendCtrl.setDefaultQuoteTrigger(ci[i]),this.aibotConfig={...e.aibot,...i==="claude"?{localActions:e.aibot.localActions??["session_control","claude_interaction_reply","get_session_usage","get_rate_limits","set_model","set_mode","set_reasoning_effort","thread_compact","get_agent_global_config",...se]}:{}},e.eventQueue&&(this.aibotConfig.concurrency={max_concurrent:e.eventQueue.maxConcurrent,max_queued:e.eventQueue.maxQueued,queue_timeout_ms:e.eventQueue.queueTimeoutMs,cancelable_queued:e.eventQueue.cancelableQueued,cancelable_running:e.eventQueue.cancelableRunning}),this.conversationLog=e.logDir?new et(e.logDir):null,this.packetLog=e.logDir?new tt(e.logDir):null,this.bindingStore=new Xn(e.bindingsPath,e.legacyBindingsPath),this.bindingStore.load(),this.globalConfigStore=t??null,this.deferredMgr=new vi(this.name),this.activeEventStore=e.activeEventStorePath?new ii(e.activeEventStorePath):null,this.pendingEvents=new si(e.pendingEventStorePath),i==="codex")this.sessionScanCache=new P(Le,Ge);else if(i==="claude")this.sessionScanCache=new P($e,je);else if(i==="pi"){const n=e.agent.env?.PI_CODING_AGENT_DIR;this.sessionScanCache=new P(()=>Fe(void 0,n),()=>ze(void 0,n))}else if(i==="codewhale")this.sessionScanCache=new P(qe,Je);else if(i==="cursor")this.sessionScanCache=new P(Ue,Ye);else if(i==="opencode")this.sessionScanCache=new P(Ne,Xe);else if(i==="deepseek-harness"){const n=typeof e.adapterOptions?.dshHome=="string"?e.adapterOptions.dshHome:e.agent.env?.DSH_HOME;this.sessionScanCache=new P(()=>We(n),()=>Ve(n))}else if(i==="agy")this.sessionScanCache=new P(()=>[],()=>[]);else{e.aibot.clientType?.trim().toLowerCase()==="reasonix"&&(this.reasonixTitleScan=new P(Be,Ze));const n=Qe(e.aibot.clientType);this.sessionScanCache=n?new P(()=>Oe(void 0,n),()=>Ke(void 0,n)):new P(()=>[],()=>[])}}async start(){if(this.stopped)throw new Error("agent start aborted");if(await He({agentName:this.name,adapterType:this.config.adapterType??"acp",command:this.config.agent.command,piConfigDir:this.config.agent.env?.PI_CODING_AGENT_DIR,dshHome:typeof this.config.adapterOptions?.dshHome=="string"?this.config.adapterOptions.dshHome:this.config.agent.env?.DSH_HOME,hasProvider:!!this.config.agent.provider,boundCwds:[...this.bindingStore.entries()].map(([,n])=>String(n.cwd??""))}).then(n=>{n.length>0&&p.info(this.name,`restored native provider config after relay disable: ${n.join(", ")}`)}).catch(n=>{p.warn(this.name,`native provider residue sweep failed: ${n instanceof Error?n.message:String(n)}`)}),this.stopped)throw new Error("agent start aborted");if((this.config.adapterType??"acp")==="claude"){if(await ke().catch(()=>{}),this.stopped)throw new Error("agent start aborted");this.maybeQueryProviderQuota().catch(()=>{})}if(this.stopped)throw new Error("agent start aborted");const e=!!(this.config.providerBaseUrl&&this.config.providerApiKey||this.config.agent.provider?.baseUrl&&this.config.agent.provider?.apiKey),t=(this.config.adapterType??"acp")==="pi",s=(this.config.adapterType??"acp")==="opencode";if(this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi"||e?(this.maybeQueryProviderQuota().catch(()=>{}),this.startProviderQuotaTimer()):(t||s)&&this.startProviderQuotaTimer(),(this.config.adapterType??"acp")==="codex"&&this.maybeQueryProviderQuota().catch(()=>{}),(this.config.adapterType??"acp")==="opencode"&&this.maybeQueryProviderQuota().catch(()=>{}),this.stopped)throw new Error("agent start aborted");if(await this.connectAibot(),this.stopped)throw this.aibotHandle?.disconnect(),new Error("agent start aborted");this.sendCtrl.bind(this.aibotHandle);const i=this.config.adapterType??"acp";if(this.pool=new qn({maxPoolSize:this.config.poolMaxSize??20,idleTimeoutMs:this.config.poolIdleTimeoutMs??18e5,eventQueue:this.config.eventQueue},n=>{const o=this.createAdapter(i,n);return o instanceof y&&o.on("acpSessionReady",r=>{this.bindingStore.setAcpSessionId(n,r),this.sessionScanCache.invalidate()}),o},(n,o)=>{this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()})}),this.pool.setEventStateHandler((n,o,r,a)=>{if(p.info(this.name,`[queue-debug] send event_state session=${o} event=${n} state=${r} queue_pos=${a?.queue_position??""} queue_total=${a?.queue_total??""}`),this.aibotHandle.sendEventState({event_id:n,session_id:o,state:r,content_preview:a?.content_preview,content:a?.content,queue_position:a?.queue_position,queue_total:a?.queue_total,actions:a?.actions,reason:a?.reason,held:a?.held,held_reason:a?.held_reason,updated_at:Date.now()}),this.pushQueueSnapshotForSession(o),r==="running"&&(this.pendingStartedEventIds.add(n),this.pendingEvents.remove(n).catch(c=>{p.warn(this.name,`Failed to remove running event from pending store event=${n}: ${c instanceof Error?c.message:String(c)}`)})),r==="canceled"||r==="failed"){const c=r==="canceled"?"canceled":"failed";this.aibotHandle.sendEventResult({event_id:n,status:c,msg:a?.reason,updated_at:Date.now()}),this.auditController.closeWithoutAdapter(n,c,a?.reason,{queueTerminalState:r}),this.discardEventTrackingState(n),this.pendingEvents.remove(n).catch(d=>{p.warn(this.name,`Failed to remove queued terminal event from pending store event=${n}: ${d instanceof Error?d.message:String(d)}`)})}}),this.pool.setQueueComposingHandler((n,o,r)=>{this.aibotHandle.sendSessionActivitySet({session_id:n,kind:"composing",active:o,...o?{ttl_ms:ri,ref_event_id:r}:{}})}),this.pool.setInternalErrorHandler(n=>{this.handleSessionInternalError(n).catch(o=>{p.error(this.name,`[recovery] handleSessionInternalError failed event=${n.eventId} session=${n.sessionId}: ${o instanceof Error?o.message:String(o)}`)})}),this.pool.setEventStartedHandler((n,o)=>{if(this.reportSessionSkills(o),this.config.adapterType!=="claude")return;this.claudeWorkerStatus.set(o,"busy");const r=this.bindingStore.get(o);r?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"busy",cwd:r.cwd,meta:this.buildClaudeToolbarMeta(o)})}),this.pool.setEventDoneHandler((n,o)=>{this.markAuditAdapterClosed(n,o);const r=this.config.adapterType??"acp";if(r==="claude"){this.claudeWorkerStatus.set(o,"ready");const a=this.bindingStore.get(o);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:"ready",cwd:a.cwd,meta:this.buildClaudeToolbarMeta(o)})}else if(r==="agy"){const a=this.bindingStore.get(o);if(a?.cwd){const c=this.buildAgyToolbarMeta(o),d=c?.available_models??[];p.info(this.name,`[agy-toolbar-diag] eventDone push binding card session=${o} model_id=${String(c?.model_id??"")} available_models=${d.length} meta_keys=${c?Object.keys(c).join(","):"<none>"}`),this.sendAgyBindingCard(o,a.cwd,c),this.refreshAndPushAgyQuota(o)}else p.info(this.name,`[agy-toolbar-diag] eventDone skip binding card: no binding cwd session=${o}`)}}),this.pool.setSessionActivityHandler((n,o,r)=>{const a=this.selfDrivenSessions.has(n),c=this.selfDrivenLabels.get(n);o?(this.selfDrivenSessions.add(n),r&&this.selfDrivenLabels.set(n,r),this.aibotHandle.sendSessionActivitySet({session_id:n,kind:"composing",active:!0,ttl_ms:9e4})):(this.selfDrivenSessions.delete(n),this.selfDrivenLabels.delete(n),a&&this.aibotHandle.sendSessionActivitySet({session_id:n,kind:"composing",active:!1})),(a!==o||o&&r!==void 0&&r!==c)&&this.pushQueueSnapshotForSession(n)}),await this.replayPendingEventsOnStartup(),this.stopped)throw new Error("agent start aborted");this.pool.startIdleSweep(),p.info(this.name,`Ready (adapter: ${i}, poolMax: ${this.config.poolMaxSize??20})`)}requestStop(){this.stopped=!0,this.lifecycleBarrier.close(),this.startupAbortController.abort(),this.pool?.stopIdleSweep(),this.stopProviderQuotaTimer(),this.pool?.pauseAllQueues("shutdown")}async stop(e){if(e?.dropPendingEvents&&(this.dropPendingEventsRequested=!0),this.requestStop(),!this.stopPromise){const t=this.stopOnce();this.stopPromise=t,t.catch(()=>{this.stopPromise===t&&(this.stopPromise=null)})}await this.stopPromise,this.dropPendingEventsRequested&&!this.pendingEventsDropped&&await this.dropPendingEventsBestEffort()}async stopOnce(){this.lifecycleBarrier.close(),this.pool?.stopIdleSweep(),this.stopProviderQuotaTimer(),this.pool?.pauseAllQueues("shutdown");const e=this.pool?.collectActiveEventIds()??[],t=new Map(e.map(r=>[r,this.eventSessionIndex.get(r)]));e.length>0&&this.activeEventStore&&await this.activeEventStore.save(e);for(const r of e)p.info(this.name,`Canceling active event on shutdown: ${r}`),this.sendEventResultWithCleanup(r,"canceled","process shutting down");e.length>0&&await new Promise(r=>setTimeout(r,100)),this.pool?.clearActiveEventsForShutdown();for(const r of e){const a=t.get(r),c=a?this.pool?.getSlot(a):void 0;this.auditController.markAdapterClosed(r,c?.adapter.takeAuditBoundary?.(r)??{processTerminated:!0})}const s=this.deferredMgr.getAllDeferredEntries(),i=this.pool?.drainAllQueuedEvents()??[],n=this.pendingEvents.dedupe([...this.pendingEvents.replaySnapshot(),...s.map(r=>({kind:"deferred",channel:r.channel,sessionId:r.sessionId,event:r.event})),...i.map(r=>({kind:"queued",event:r}))]);let o=!1;if(this.dropPendingEventsRequested)try{await this.pendingEvents.clear(),this.pendingEventsDropped=!0}catch(r){p.warn(this.name,`Failed to clear pending event store on removal: ${r instanceof Error?r.message:String(r)}`)}else try{o=await this.pendingEvents.mergeForShutdown(n)}catch(r){p.error(this.name,`Failed to persist pending events on shutdown: ${r instanceof Error?r.message:String(r)}`)}if(!o)for(const r of n){const a=r.event;p.info(this.name,`Failing pending event on shutdown: ${a.event_id}`),this.sendEventResultWithCleanup(a.event_id,"failed","process shutting down"),this.auditController.markAdapterClosed(a.event_id,{adapterNotStarted:!0,processTerminated:!0})}this.deferredMgr.clearAll(),await this.pool?.stop(),this.aibotHandle?.disconnect(),e.length>0&&this.activeEventStore&&await this.activeEventStore.save([]),this.eventSessionIndex.clear(),this.inflightEvents.clear(),this.restartCount.clear(),this.auditController.dispose()}async dropPendingEventsBestEffort(){try{await this.pendingEvents.clear(),this.pendingEventsDropped=!0}catch(e){p.warn(this.name,`Failed to clear pending event store on removal: ${e instanceof Error?e.message:String(e)}`)}}resolveSpawnEnv(){const e=this.providerResolver?this.providerResolver():this.config.agent.provider,t=xe(this.config.agent.clientType,e),s=this.config.agent.env;let i=Object.keys(t).length>0?{...t,...s}:s;if(De(t)){const n=ye()?.getRuntimeInfo(),o={...s??{},...t},r=Me(o,{proxyUrl:n?.proxyUrl,caCertPath:n?.caCertPath,caBundlePath:n?.caBundlePath});return delete r.ANTHROPIC_API_KEY,delete r.CLAUDE_CODE_OAUTH_TOKEN,r}if(Te(this.config.agent.clientType)){const n=Pe(this.name);n&&(i={...i??{},...n})}return Re(i,this.name,this.config.agent.clientType)}createAdapter(e,t){switch(e){case"claude":return this.createClaudeAdapter(t);case"codex":return this.createCodexAdapter(t);case"pi":return this.createPiAdapter(t);case"openhuman":return this.createOpenHumanAdapter(t);case"codewhale":return this.createCodeWhaleAdapter(t);case"cursor":return this.createCursorAdapter(t);case"opencode":return this.createOpenCodeAdapter(t);case"agy":return this.createAgyAdapter(t);case"deepseek-harness":return this.createDshAdapter(t);default:return this.createAcpAdapter(t)}}createDshAdapter(e){const t={sendStreamChunk:(n,o,r,a,c,d,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,r,a,c,d,l)},sendFinalStreamChunkReliable:this.reliableFinalWiring("deepseek-harness",Di),sendThinking:(n,o,r)=>this.sendThinkingByRuntimeConfig(n,o,r),sendEventResult:(n,o,r,a)=>{this.sendEventResultWithCleanup(n,o,r,void 0,a)},sendRawEventEnvelope:(n,o,r,a)=>{const c=gi(r);if(c){this.sendToolExecutionCard(n,o,c);return}this.deliverRawEventEnvelope(n,o,r,"deepseek",a)},sendLocalActionResult:(n,o,r,a,c)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:o,...r!==void 0?{result:r}:{},...a?{error_code:a}:{},...c?{error_msg:c}:{}},e)},sendPermissionCard:n=>{this.sendGrixApprovalCard(n,"deepseek")},sendUpdateBindingCard:(n,o,r,a)=>{this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:o,cwd:r,meta:a})},getAgentProfile:()=>({...this.agentProfile,systemPrompt:this.agentSystemPrompt}),getAgentId:()=>this.config.aibot.agentId,queryProviderQuota:n=>this.maybeQueryProviderQuota(n===!0,{providerId:"deepseek"}),agentInvoke:async(n,o,r)=>this.platformInvoke(n,o,r),eventToolInvoke:async(n,o)=>this.invokeDshEventTool(n,o)},s=O("sha256").update(this.config.aibot.agentId).digest("hex").slice(0,24),i=this.config.adapterOptions??{};return new le({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:i},t,{aibotSessionId:e,bindingStore:this.bindingStore,globalConfigStore:this.globalConfigStore,agentName:this.name,dataRoot:T.join(L.data,"deepseek-harness",s),...typeof i.cordisPath=="string"?{cordisPath:i.cordisPath}:{},...typeof i.defaultModel=="string"?{defaultModel:i.defaultModel}:{},...typeof i.maxTokens=="number"?{maxTokens:i.maxTokens}:{},...typeof i.maxLineBytes=="number"?{maxLineBytes:i.maxLineBytes}:{},...i.integrationMode==="embedded_jsonrpc"||i.integrationMode==="profile_bridge"?{integrationMode:i.integrationMode}:{},...typeof i.dshHome=="string"?{dshHome:i.dshHome}:{},...typeof i.dshProfile=="string"?{dshProfile:i.dshProfile}:{},...typeof i.autoInstallBridge=="boolean"?{autoInstallBridge:i.autoInstallBridge}:{},...typeof i.autoStartProfile=="boolean"?{autoStartProfile:i.autoStartProfile}:{},...this.config.agent.provider?{provider:this.config.agent.provider}:{},promptTimeoutMs:this.config.promptTimeoutMs})}createCursorAdapter(e){const t={...this.config.adapterOptions??{}};t.bindingStore=this.bindingStore,t.aibotSessionId=e;const s=this.bindingStore.get(e),i=this.resolveSessionModelId(e);i&&(t.model=i);const n=this.resolveCursorSessionModeId(e),o=n??"full_auto";n||this.bindingStore.setCursorModeId(e,o),t.mode=o,s?.cwd&&(t.workspace=s.cwd);const r={sendStreamChunk:(a,c,d,l,h,g,u)=>{this.sendStreamChunkByRuntimeConfig(a,c,d,l,h,g,u)},sendEventResult:(a,c,d)=>{this.sendEventResultWithCleanup(a,c,d)},sendEventAck:(a,c)=>{this.aibotHandle.sendEventAck({event_id:a,session_id:c,received_at:Date.now()})},sendRawEventEnvelope:(a,c,d)=>{this.deliverRawEventEnvelope(a,c,d,"cursor",this.buildCursorRawEventFallbackText(d))},sendAgentQuestionCard:(a,c,d)=>{const l=d.questions.map(g=>g.header).join(", "),h=X(`[Agent Question] ${d.request_id}`,"agent_question",d);this.aibotHandle.sendText({event_id:a,session_id:c,content:h,msg_type:1,extra:{card_type:"agent_question",summary_text:l}})},agentInvoke:async(a,c,d)=>this.platformInvoke(a,c,d),sendLocalActionResult:(a,c,d,l,h)=>{this.aibotHandle.sendLocalActionResult({action_id:a,status:c,...d!==void 0?{result:d}:{},...l?{error_code:l}:{},...h?{error_msg:h}:{}},e)},sendUpdateBindingCard:(a,c,d,l)=>{this.aibotHandle.sendUpdateBindingCard({session_id:a,worker_status:c,cwd:d,...l?{meta:l}:{}})},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId};return new ae({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:t},r)}createClaudeAdapter(e){const t={sendReply:(n,o,r,a,c)=>{this.sendReplyByRuntimeConfig(n,o,r,a,c)},sendStreamChunk:(n,o,r,a,c,d,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,r,a,c,d,l)},sendMedia:(n,o,r,a,c,d,l)=>{this.aibotHandle.sendMedia({event_id:n,session_id:o,content:r,msg_type:2,quoted_message_id:c||void 0,client_msg_id:d||void 0,extra:l?{media_caption:a,...l}:{media_caption:a}})},sendEventResult:(n,o,r,a)=>{this.sendEventResultWithCleanup(n,o,r,a)},sendEventAck:(n,o)=>{this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()})},agentInvoke:async(n,o,r)=>this.platformInvoke(n,o,r),sendLocalActionResult:(n,o,r,a,c)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:o,...r!==void 0?{result:r}:{},...a?{error_code:a}:{},...c?{error_msg:c}:{}},e)},sendToolUse:(n,o,r,a)=>{this.sendToolExecutionCard(n,o,D(r,a))},sendToolResult:(n,o,r,a)=>{this.sendToolExecutionCard(n,o,M(r,a))},getWsUrl:()=>this.config.aibot.url,getAgentId:()=>this.config.aibot.agentId,getAgentProfile:()=>this.agentProfile,getApiKey:()=>this.config.aibot.apiKey,getActiveEventCount:()=>0,getPendingPermissionCount:()=>0,getPendingElicitationCount:()=>0,sendAgentQuestionCard:(n,o,r)=>{this.sendGrixAgentQuestionCard(n,o,r)},sendPermissionCard:n=>{this.sendGrixApprovalCard(n,"claude")},sendDirectMessage:n=>{this.aibotHandle.sendMsg({session_id:n.sessionId,msg_type:1,content:n.content,...n.clientMsgId?{client_msg_id:n.clientMsgId}:{},...n.quotedMessageId?{quoted_message_id:n.quotedMessageId}:{}})},onStatusLineUpdated:n=>{(n.rateLimits?.fiveHour||n.rateLimits?.sevenDay)&&(this.cachedClaudeRateLimitState=n);const o=this.bindingStore.get(e);o?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:this.claudeWorkerStatus.get(e)??"ready",cwd:o.cwd,meta:this.buildClaudeToolbarMeta(e)})},sendMcpFrame:n=>{this.aibotHandle.sendMcpFrame(e,n)}},s=this.config.adapterOptions??{},i={...s,sessionRuntimeResolver:()=>{const n=this.bindingStore.get(e),o=this.auditController.getSession(e);return{cwd:n?.cwd,modeId:this.resolveClaudeSessionModeId(e)??be.fullAuto,modelId:this.resolveSessionModelId(e),effort:this.resolveClaudeSessionEffort(e),pluginDir:s.pluginDir,claudeSessionId:n?.claudeSessionId,...o?{audit:{enabled:!0,profile:o.options.profile,capture:o.options.capture}}:{},onSessionIdAssigned:r=>{this.bindingStore.setClaudeSessionId(e,r),this.sessionScanCache.invalidate()}}}};return new N({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:i},t)}createCodexAdapter(e){let t=null;const s={sendEventResult:(r,a,c)=>{if(a!=="responded"){this.sendEventResultWithCleanup(r,a,c);return}this.sendCtrl.sendFinalStreamChunkReliable(r,e,`codex_terminal_fence_${r}`,5e3,!0,!0).then(()=>this.sendEventResultWithCleanup(r,a,c),d=>{const l=`codex output acceptance fence failed: ${d instanceof Error?d.message:String(d)}`;this.sendEventResultWithCleanup(r,a==="responded"?"failed":a,a==="responded"?l:c)})},sendEventAck:(r,a)=>this.aibotHandle.sendEventAck({event_id:r,session_id:a,received_at:Date.now()}),sendCodexEvent:r=>{this.shouldDropCodexDisplayEvent(r.event_id,r.codex_method)||(this.captureCodexAuditOutput(r),this.aibotHandle.sendCodexEvent(this.stampCodexEventQuote(r)),this.logCodexEventToConversation(r))},sendThinking:(r,a,c)=>{this.sendThinkingByRuntimeConfig(r,a,c)},sendRunError:(r,a,c)=>{this.sendRunErrorAsChunk(r,a,c)},sendUpdateBindingCard:(r,a,c,d)=>{const l={...d??{}};if(!l.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const h=this.providerQuotaToCodexRateLimits(this.cachedProviderQuota);h&&(l.rate_limits=h.rateLimits,l.rate_limit_primary_percent=h.primaryPercent,l.rate_limit_secondary_percent=h.secondaryPercent,l.rate_limit_primary_window_min=h.primaryWindowMin,l.rate_limit_secondary_window_min=h.secondaryWindowMin)}!l.provider_quota&&this.cachedProviderQuota?.success&&(l.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:r,worker_status:a,cwd:c,...Object.keys(l).length>0?{meta:l}:{}})},agentInvoke:async(r,a,c)=>this.platformInvoke(r,a,c),sendLocalActionResult:(r,a,c,d,l)=>this.aibotHandle.sendLocalActionResult({action_id:r,status:a,...c!==void 0?{result:c}:{},...d?{error_code:d}:{},...l?{error_msg:l}:{}},e),sendSessionActivitySet:(r,a,c,d)=>{this.aibotHandle.sendSessionActivitySet({session_id:r,kind:a,active:c,...d??{}})},getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId,onRateLimitsUpdated:r=>{this.cachedRateLimits=r,this.cachedRateLimitsSampledAtMs=Date.now(),this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const a=this.bindingStore.get(e);if(a?.cwd){const c=this.cachedRateLimitsSampledAtMs,d={rate_limits:{...r.primary.windowMinutes>0?{primary:r.primary}:{},...r.secondary.windowMinutes>0?{secondary:r.secondary}:{},sampledAt:c},rate_limit_primary_percent:r.primary.usedPercent,rate_limit_secondary_percent:r.secondary.usedPercent,rate_limit_primary_window_min:r.primary.windowMinutes,rate_limit_secondary_window_min:r.secondary.windowMinutes,credits:r.credits,...r.extras&&r.extras.length>0?{extra_limits:r.extras}:{},...t?.getEffortMeta()};this.cachedProviderQuota?.success&&(d.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:a.cwd,meta:d})}},onContextWindowUpdated:r=>{if(!r)return;this.cachedCodexContextWindow=r,this.cachedCodexUsageSampledAtMs=Date.now();const a=this.bindingStore.get(e);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:a.cwd,meta:{context_window:r,...t?.getEffortMeta()}})},onTokenUsageUpdated:r=>{r&&(this.cachedCodexTokenUsage=r,this.cachedCodexUsageSampledAtMs=Date.now())}},i=this.config.adapterOptions??{},n=this.globalConfigStore?.get(this.name),o=this.auditController.getAdapterPreparation(e);return t=new W({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...i,model:this.resolveCodexSessionModelId(e)??i.model,collaborationMode:this.bindingStore.getCodexModeId(e)??this.resolveCodexNewSessionGlobalDefault(e,n?.codexModeId,r=>this.bindingStore.setCodexModeId(e,r))??i.collaborationMode,reasoningEffort:this.bindingStore.getCodexReasoningEffort(e)??this.pinCodexGlobalDefault(n?.codexReasoningEffort,r=>this.bindingStore.setCodexReasoningEffort(e,r))??i.reasoningEffort,serviceTier:this.bindingStore.getCodexServiceTier(e)??this.resolveCodexNewSessionGlobalDefault(e,n?.codexServiceTier,r=>this.bindingStore.setCodexServiceTier(e,r))??i.serviceTier,sandboxMode:this.bindingStore.getCodexSandboxMode(e)??this.pinCodexGlobalDefault(n?.codexSandboxMode,r=>this.bindingStore.setCodexSandboxMode(e,r))??i.sandboxMode,aibotSessionId:e,bindingStore:this.bindingStore,...K(o?.options)?{rawApiCapture:{auditId:o.auditId,sessionId:e,spoolRootDir:T.join(L.data,"audit-replay","raw-spool")}}:{}}},s),t}createCodeWhaleAdapter(e){const t={sendEventResult:(i,n,o)=>{this.sendEventResultWithCleanup(i,n,o)},sendEventAck:(i,n)=>this.aibotHandle.sendEventAck({event_id:i,session_id:n,received_at:Date.now()}),sendStreamChunk:(i,n,o,r,a,c)=>{this.sendStreamChunkByRuntimeConfig(i,n,o,r,a,c)},sendUpdateBindingCard:(i,n,o,r)=>this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:n,cwd:o,...this.providerQuotaMetaPayload(r,i,o)}),sendLocalActionResult:(i,n,o,r,a)=>this.aibotHandle.sendLocalActionResult({action_id:i,status:n,...o!==void 0?{result:o}:{},...r?{error_code:r}:{},...a?{error_msg:a}:{}},e),sendSessionActivitySet:(i,n,o,r)=>{this.aibotHandle.sendSessionActivitySet({session_id:i,kind:n,active:o,...r??{}})},sendToolUse:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,D(o,r))},sendToolResult:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,M(o,r))},agentInvoke:async(i,n,o)=>this.platformInvoke(i,n,o),getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},s=this.config.adapterOptions??{};return new de({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...s,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,model:this.resolveSessionModelId(e)??s.model,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},t)}createPiAdapter(e){const t={sendEventResult:(i,n,o)=>{this.sendEventResultWithCleanup(i,n,o),p.info("bridge",`[pi] sendEventResult event=${i} status=${n}`)},sendEventAck:(i,n)=>this.aibotHandle.sendEventAck({event_id:i,session_id:n,received_at:Date.now()}),sendUpdateBindingCard:(i,n,o,r)=>this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:n,cwd:o,...this.providerQuotaMetaPayload(r,i,o)}),agentInvoke:async(i,n,o)=>this.platformInvoke(i,n,o),sendLocalActionResult:(i,n,o,r,a)=>{this.aibotHandle.sendLocalActionResult({action_id:i,status:n,...o!==void 0?{result:o}:{},...r?{error_code:r}:{},...a?{error_msg:a}:{}},e)},sendSessionActivitySet:(i,n,o,r)=>{this.aibotHandle.sendSessionActivitySet({session_id:i,kind:n,active:o,...r??{}})},sendToolUse:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,D(o,r))},sendToolResult:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,M(o,r))},sendStreamChunk:(i,n,o,r,a,c)=>{this.sendStreamChunkByRuntimeConfig(i,n,o,r,a,c),a&&p.info("bridge",`[pi] sendFinalStreamChunk event=${i} seq=${r}`)},sendFinalStreamChunkReliable:this.reliableFinalWiring("pi"),sendThinking:(i,n,o)=>{this.sendThinkingByRuntimeConfig(i,n,o)},sendRunError:(i,n,o,r,a)=>{this.sendStreamChunkByRuntimeConfig(i,n,`
1
+ import y from"node:path";import{tmpdir as U}from"node:os";import{createHash as M,randomUUID as R}from"node:crypto";import{ConnectionManager as q}from"../core/aibot/index.js";import{AUDIT_LOCAL_ACTION_TYPES as N}from"../core/aibot/types.js";import{ClaudeAdapter as L}from"../adapter/claude/index.js";import{CodexAdapter as D}from"../adapter/codex/index.js";import"../adapter/claude/session-history.js";import"../adapter/codex/session-history.js";import"../adapter/pi/session-history.js";import"../adapter/opencode/session-history.js";import"../adapter/codewhale/session-history.js";import"../adapter/deepseek-harness/session-history.js";import{PiAdapter as W}from"../adapter/pi/index.js";import{AcpAdapter as S}from"../adapter/acp/index.js";import{OpenHumanAdapter as G}from"../adapter/openhuman/index.js";import{CursorAdapter as j}from"../adapter/cursor/index.js";import{CodeWhaleAdapter as K}from"../adapter/codewhale/index.js";import{OpenCodeAdapter as k}from"../adapter/opencode/index.js";import{AgyAdapter as H}from"../adapter/agy/index.js";import{DshJsonRpcAdapter as z}from"../adapter/deepseek-harness/index.js";import{LOCAL_ACTION_TYPES as f,SESSION_CONTROL_ERROR_CODES as $,SESSION_CONTROL_VERBS as E,SESSION_MODE_IDS as J}from"../adapter/claude/protocol-contract.js";import{isAuditLocalActionType as Y}from"../audit/query/audit-local-actions.js";import{shouldEnableRawApiCapture as Q}from"../audit/raw-capture/types.js";import{buildWireSkills as X}from"../core/skill-sync/sync-state.js";import{executeEventTool as V}from"../core/mcp/event-tool-executor.js";import{fetchAvailableModels as Z}from"../adapter/claude/model-list.js";import{applyProxyEnv as ee,getProxyManager as te}from"../core/proxy/index.js";import{getKiroRelaySpawnEnv as ne}from"../core/proxy/kiro-relay.js";import{supportsKiroCwRelay as ie}from"../core/config/provider-env.js";import{buildProviderEnv as se}from"../core/config/provider-env.js";import{isClaudeDirectEnv as oe,stripGrixRelayEnv as re}from"../core/config/claude-direct-env.js";import{sweepNativeProviderResidue as ae}from"./native-provider-sweep.js";import{scanCodexSessions as de}from"../adapter/codex/session-scanner.js";import{scanClaudeSessions as le}from"../adapter/claude/session-scanner.js";import{resolveAcpAgentTypes as ce,scanAcpSessions as he,scanReasonixSessionTitles as ue}from"../adapter/acp/session-scanner.js";import{scanPiSessions as pe}from"../adapter/pi/session-scanner.js";import{scanCodeWhaleSessions as ge}from"../adapter/codewhale/session-scanner.js";import{scanCursorSessions as fe}from"../adapter/cursor/session-scanner.js";import{scanOpenCodeSessions as me}from"../adapter/opencode/session-scanner.js";import{scanDshSessions as ve}from"../adapter/deepseek-harness/session-scanner.js";import{SessionScanCache as v,resolveCodexLeafDirs as _e,resolveClaudeLeafDirs as Se,resolveAcpLeafDirs as Ce,resolvePiLeafDirs as be,resolveCodeWhaleLeafDirs as Ae,resolveCursorLeafDirs as Ee,resolveOpenCodeLeafDirs as we,resolveDshLeafDirs as ye,resolveReasonixLeafDirs as Re}from"./session-scan-cache.js";import{log as h,ConversationLog as ke,AgentApiPacketLog as Te,BridgeEventLog as Pe,GRIX_PATHS as w}from"../core/log/index.js";import{routeSessionControlCommand as xe,routeSessionControlLocalAction as Me}from"./session-control-router.js";import{maybeOfferCliInstall as Le,handleCliInstallQuestionReply as De,handleCliInstallInteractionReply as He,runConfirmedCliInstall as $e}from"./cli-install-flow.js";import{handleEventCancel as Qe,waitForEventDone as Ie,handleAibotStop as Oe,killAndResumeStopSlot as Be,handleAibotRevoke as Fe}from"./event-stop.js";import{handleConfigureGatewayProvider as Ue,getAuditLocalActionHandler as qe,handleAuditLocalAction as Ne,handleConnectorRollback as We,getRelayStateSyncer as Ge,relayStateSyncOnConnect as je,reportRelayStateLocalChange as Ke,handleApplyRelayState as ze,fetchRelayCredential as Je,isSharedInstance as Ye}from"./connector-ops.js";import{unbindSession as Xe,handleUnbindTextCommand as Ve,handleUnbindLocalAction as Ze,handleListSessionsTextCommand as et,handleListSessionsLocalAction as tt,handleSyncHistoryLocalAction as nt}from"./session-list.js";import{handleCodexSessionControlOpen as it,handleSessionControlForPool as st,handleSessionControlLocalActionForPool as ot,handleCodexSessionControlLocalActionOpen as rt,handleCursorSessionControlLocalActionOpen as at,handlePiSessionControlOpen as dt,handlePiSessionControlRestart as lt,handlePiSessionControlRestartLocalAction as ct,syncOpenCodeBinding as ht,isWorkspaceFreeClient as ut,ensureDefaultBindingForWorkspaceFreeClient as pt,bindSessionForPool as gt,deferredCallbacks as ft,handleOpenHumanSessionControlOpen as mt,handleCodeWhaleSessionControlOpen as vt,handleCodeWhaleSessionControlLocalActionOpen as _t,handleDeepSeekSessionControlLocalActionOpen as St}from"./session-control-open.js";import{handleGetSessionUsage as Ct,handleThreadCompact as bt}from"./session-usage.js";import{handleSkillDeleteLocalAction as At,handleSkillUploadLocalAction as Et,handleSkillEnableLocalAction as wt,handleSkillRefreshLocalAction as yt,handleSkillDisableLocalAction as Rt,computeSkillReport as kt,reportSessionSkills as Tt,skillsSyncGroupKey as Pt,forceRefreshSkills as xt,adoptSkillsWireHashFromDisk as Mt,buildLibrarySkillsReport as Lt,skillLookupEnv as Dt}from"./skill-actions.js";import{normalizeClaudeModeId as Ht,handleExecCommandOptions as $t,resolveSessionModelId as Qt,resolveSessionModeId as It,resolveCursorSessionModeId as Ot,resolveClaudeSessionEffort as Bt,resolveClaudeSessionModeId as Ft,currentClaudeModeId as Ut,resolveCodexSessionModelId as qt,resolveCodexNewSessionGlobalDefault as Nt,pinCodexGlobalDefault as Wt,buildCursorToolbarMeta as Gt,buildAgyToolbarMeta as jt,buildAgyQuotaMeta as Kt,sendAgyBindingCard as zt,refreshAndPushAgyQuota as Jt,handleAgySetModel as Yt,buildClaudeToolbarMeta as Xt}from"./toolbar-meta.js";import{resolveProviderQuotaSource as Vt,maybeQueryProviderQuota as Zt,startProviderQuotaTimer as en,stopProviderQuotaTimer as tn,refreshAndPushProviderQuota as nn,pushProviderQuotaToBindings as sn,enrichProviderQuotaMeta as on,providerQuotaMetaPayload as rn,refreshProviderQuotaForSession as an,refreshQuotaAfterModelSwitch as dn,doRefreshQuotaAfterModelSwitch as ln}from"./provider-quota.js";import{handleGetRateLimits as cn,resolveRateLimitWakeSessionId as hn,wakeRateLimitSlot as un}from"./rate-limits.js";import{RevokeHandler as pn}from"./revoke-handler.js";import{AdapterPool as gn}from"./adapter-pool.js";import{parseSessionControlCommand as fn}from"./session-controller.js";import{isOpenSessionDirectiveMessage as mn,parseExecApprovalResolutionMessage as vn,parseAgentQuestionReplyMessage as _n}from"../core/protocol/interaction-parser.js";import{rejectUnusableAuditOptions as Sn}from"./inbound-audit-gate.js";import{interceptUnboundInboundEvent as Cn}from"./inbound-binding-gate.js";import{dispatchSessionControlTextCommand as bn}from"./text-command-session-control.js";import{dispatchSessionControlLocalAction as An}from"./local-action-session-control.js";import{handleCreateFolderLocalAction as En,handleFileListLocalAction as wn}from"./local-action-files.js";import{handleAcpToolbarLocalAction as yn,persistToolbarSelection as Rn}from"./local-action-toolbar.js";import{buildOpenedBindingResult as kn,ensureImportedAgentSession as Tn,hasDiskScanner as Pn,normalizePathForCompare as xn,providerKeyForAdapter as Mn,resolveAgentSessionId as Ln,resolveOrphanTitle as Dn,setResolvedAgentSessionId as Hn}from"./session-identity.js";import{buildDshOpenedToolbarMeta as $n,dshCatalogDataRoot as Qn}from"./dsh-toolbar.js";import{ensureSlotStarted as In,failSessionOpen as On,getClaudeWorkerStatus as Bn,refreshClaudeWorkerStatusCard as Fn,resolveCwdForBinding as Un}from"./session-open-helpers.js";import{handleAcpSetModel as qn,handleAcpSetMode as Nn,resolveAcpInitialDefaults as Wn}from"./acp-toolbar-persist.js";import{SessionBindingStore as Gn}from"../core/persistence/session-binding-store.js";import{serveLocalFile as jn}from"../core/files/index.js";import{uploadReplyFileToAgentMedia as Kn}from"../core/protocol/agent-api-media.js";import{ActiveEventStore as zn}from"../core/persistence/active-event-store.js";import{PendingEventCoordinator as Jn}from"./pending-event-coordinator.js";import{LifecycleBarrier as Yn}from"./lifecycle-barrier.js";import{QUEUE_COMPOSING_TTL_MS as Xn}from"./event-queue.js";import{DEFAULT_CONNECTOR_RUNTIME_CONFIG as Vn,applyConnectorRuntimeConfigPatch as Zn,extractConnectorRuntimeConfigPatch as ei}from"./runtime-config.js";import{DEFAULT_QUOTE_TRIGGER_BY_ADAPTER as ti,SendController as ni}from"./send-controller.js";import{providerQuotaToRateLimits as ii,providerQuotaToCodexRateLimits as si}from"../core/provider-quota/index.js";import{buildToolUseCard as C,buildToolResultCard as b,buildDshOnlineToolCard as oi,buildLocalGrixCardLink as I}from"./tool-card-utils.js";import{planRawEventDelivery as ri,buildAuxiliaryDetailText as ai}from"./raw-event-delivery.js";import{DeferredEventManager as di}from"./deferred-events.js";import{buildAgentProbeResult as li,PROBE_CACHE_TTL_STATIC_MS as ci,PROBE_CACHE_TTL_FULL_MS as hi}from"./probe-helper.js";import{BridgeAuditController as ui}from"../audit/integration/bridge-audit-controller.js";import{isSettlableAuditProducer as pi,NoopAuditProducer as gi}from"../audit/producer/audit-producer.js";import{buildAuditStatePayload as O,AuditPreparationFailedError as fi,AuditTurnScopeUnsupportedError as mi}from"../audit/core/audit-state.js";import{extractAuditOptions as B,freezeAuditOptions as vi,stripAuditOptions as _i}from"../audit/core/audit-options.js";import{AuditSessionOptionsError as Si}from"../audit/core/audit-session-registry.js";const Ci=600*1e3,F=1800*1e3,bi=60*1e3,Ai=4e3;function Ei(x,e,i){const r=M("sha256").update(x).update("\0").update(e).update("\0").update(i).digest("hex");return y.join(w.data,"audit-source","reasonix",`${r}.jsonl`)}const T=new Set(["claude","acp","agy","cursor","codex","deepseek-harness"]),wi=new Set(["claude","codex","cursor","codewhale","opencode","pi","openhuman","agy","acp","deepseek-harness"]),P=3;class oo{config;name;aibotHandle;aibotConfig;pool;stopped=!1;startupAbortController=new AbortController;stopPromise=null;dropPendingEventsRequested=!1;pendingEventsDropped=!1;revokeHandler=new pn;sessionBindings=new Map;deferredMgr;sendCtrl=new ni(Vn);bindingStore;globalConfigStore;upgradeTrigger=null;daemonShutdownRequester=null;lifecycleBusyChecker=null;lifecycleAdmissionCloser=null;lifecycleAdmissionRestorer=null;installAgentHandler=null;pendingCliInstalls=new Map;agentDeletedHandler=null;shareSetHandler=null;skillSyncHandler=null;providerConfigHandler=null;relayStateApplyPorts=null;relayStateSyncer=null;agentProfile={agentName:"",introduction:""};agentSystemPrompt="";activeEventStore;pendingEvents;pendingStartedEventIds=new Set;lifecycleBarrier=new Yn;cachedRateLimits=null;cachedRateLimitsSampledAtMs=null;cachedCodexContextWindow=null;cachedCodexTokenUsage=null;cachedCodexUsageSampledAtMs=null;cachedAcpContextWindow=null;cachedAcpContextWindowSampledAtMs=null;cachedClaudeRateLimitState=null;cachedProviderQuota=null;cachedProviderQuotaSampledAtMs=null;cachedProviderQuotaKey=null;sessionProviderHints=new Map;sessionProviderQuotas=new Map;sessionProviderMeta=new Map;lastModelSwitchQuotaRefresh=null;claudeWorkerStatus=new Map;lastReportedSkillsHash="";lastReportedSkillsWireHash="";conversationLog=null;packetLog=null;providerQuotaTimer=null;eventSessionIndex=new Map;inflightEvents=new Map;restartCount=new Map;selfDrivenSessions=new Set;selfDrivenLabels=new Map;probeCache=new Map;auditController;auditLocalActionHandler=null;sessionScanCache;reasonixTitleScan=null;isRateLimitsCacheFresh(e){if(!Number.isFinite(e))return!1;const i=Number(e);return i>0&&Date.now()-i<=bi}resolveProviderQuotaSource(e){return Vt(this,e)}maybeQueryProviderQuota(e=!1,i){return Zt(this,e,i)}startProviderQuotaTimer(){en(this)}stopProviderQuotaTimer(){tn(this)}refreshAndPushProviderQuota(e=!1){return nn(this,e)}pushProviderQuotaToBindings(e,i=!1){sn(this,e,i)}enrichProviderQuotaMeta(e,i="standard",r=this.cachedProviderQuota,n=this.cachedProviderQuotaSampledAtMs){return on(this,e,i,r,n)}providerQuotaMetaPayload(e,i,r){return rn(this,e,i,r)}refreshProviderQuotaForSession(e,i,r){return an(this,e,i,r)}refreshQuotaAfterModelSwitch(e,i,r){dn(this,e,i,r)}doRefreshQuotaAfterModelSwitch(e,i,r){return ln(this,e,i,r)}getFreshClaudeRateLimitState(){const e=this.cachedClaudeRateLimitState;return e&&this.isRateLimitsCacheFresh(e.sampledAt)?e:null}getFreshCodexGlobalRateLimitCache(){const e=this.cachedRateLimits,i=this.cachedCodexContextWindow,r=this.cachedCodexTokenUsage;return{sampledAt:Math.max(this.cachedRateLimitsSampledAtMs??0,this.cachedCodexUsageSampledAtMs??0)||null,rateLimits:e,contextWindow:i,tokenUsage:r,hasData:!!(e||i||r)}}getStatus(){const e=this.pool?.getStatus()??{total:0,ready:0,busy:0};return{name:this.name,agentId:this.config.aibot.agentId,alive:!this.stopped,busy:e.busy>0,wsConnected:this.aibotHandle?.status==="ready",exhausted:this.pool?[...this.pool.getAllSlots()].some(i=>i.respawn.exhausted):!1,adapterType:this.config.adapterType??"acp",clientType:this.config.aibot.clientType,pool:e}}hasPendingWork(){return this.pool?.hasPendingWork()??!1}hasPendingOrBackgroundWork(){return this.lifecycleBarrier.hasActiveAdmissions()||(this.pool?.hasPendingOrBackgroundWork()??!1)}async waitUntilLifecycleIdle(e){const i=()=>this.lifecycleBusyChecker?.()??this.hasPendingOrBackgroundWork();if(i()){const r=Math.round(F/6e4);h.info(this.name,`${e}: active tasks detected, waiting up to ${r}min until idle before restart (admission stays open while waiting)`);const n=Date.now()+F,t=5e3,s=600*1e3;let o=Date.now();for(;i()&&!this.stopped;){if(Date.now()>=n)return h.warn(this.name,`${e}: idle wait exceeded ${r}min; abandoning this restart. Admission was never closed, so agents kept serving. A busy state that never clears usually means an adapter leaked its busy flag \u2014 check for a turn that never completed.`),!1;await new Promise(a=>setTimeout(a,t)),Date.now()-o>=s&&(o=Date.now(),h.info(this.name,`${e}: still waiting for active tasks to finish before restart`))}}return this.stopped?!1:(this.closeLifecycleAdmissionForRestart(),i()?(h.warn(this.name,`${e}: work arrived while closing admission; reopening and abandoning this restart`),this.reopenLifecycleAdmissionAfterAbort(),!1):(h.info(this.name,`${e}: all tasks completed, proceeding with restart`),!0))}reopenLifecycleAdmissionAfterAbort(){if(this.lifecycleAdmissionRestorer){this.lifecycleAdmissionRestorer();return}this.openLifecycleAdmission()}relayEnvStale=!1;relayEnvSettledHandler;async recycleAdaptersForRelayChange(){if(!this.pool)return this.relayEnvStale=!1,!0;if(this.hasPendingWork())return this.relayEnvStale=!0,h.info(this.name,"relay changed but agent is busy; adapters keep the old env until the next message (marked stale)"),!1;const e=[...this.pool.getAllSlots()];let i=0,r=!1;for(const n of e){if(this.hasPendingWork())return this.relayEnvStale=!0,h.info(this.name,"new work arrived while recycling; remaining adapters stay stale until the next message"),!1;let t=!1;await this.pool.removeSlot(n.sessionId).catch(s=>{r=!0,t=!0,h.warn(this.name,`failed to recycle adapter slot ${n.sessionId} after relay change: ${s}`)}),t||(i+=1)}return i>0&&h.info(this.name,`recycled ${i} adapter slot(s) so the new Grix relay env takes effect`),r?(this.relayEnvStale=!0,!1):(this.relayEnvStale=!1,this.relayEnvSettledHandler?.(),!0)}setRelayEnvSettledHandler(e){this.relayEnvSettledHandler=e}providerResolver;setProviderResolver(e){this.providerResolver=e}hasStaleRelayEnv(){return this.relayEnvStale}markRelayEnvStale(){this.relayEnvStale=!0}async probe(e={}){const i=e.conversation?"full":"static",r=e.conversation?hi:ci;if(!e.fresh){const a=this.probeCache.get(i);if(a&&Date.now()-a.sampledAt<r)return{...a.result,cached:!0}}const n=this.config.adapterType??"acp",t=this.createAdapter(n,"__probe__"),s=e.conversation&&n==="acp"?()=>this.runAcpConversationProbe(t,e.timeoutMs??1e4):void 0;let o;try{o=await li({adapter:t,agentName:this.name,clientType:this.config.aibot.clientType,adapterType:n,providerBaseUrl:this.config.providerBaseUrl??null,opts:e,launchConversationProbe:s})}finally{t.stop().catch(()=>{})}return this.probeCache.set(i,{result:o,sampledAt:o.probed_at}),o}async runAcpConversationProbe(e,i){const r=Date.now(),n="__probe__",t=`probe-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s=this.config.agent.cwd||U(),o=()=>Date.now()-r;try{await e.start()}catch(u){return{attempted:!0,ok:!1,latency_ms:o(),error:{code:"conversation_failed",message:`start failed: ${u instanceof Error?u.message:String(u)}`}}}if(!e.isAlive())return{attempted:!0,ok:!1,latency_ms:o(),error:{code:"process_not_started",message:"agent process not alive"}};if(e instanceof S)try{await e.bindSession(n,s)}catch{}let a=null;const l=new Promise(u=>{a=g=>{g===t&&u()},e.on("eventDone",a)});e.deliverInboundEvent({event_id:t,session_id:n,content:"ping",msg_id:t}),e.deliverStopEvent(t,n);let d=null;const c=await Promise.race([l.then(()=>!1),new Promise(u=>{d=setTimeout(()=>u(!0),i)})]);return d&&clearTimeout(d),a&&e.removeListener("eventDone",a),c?{attempted:!0,ok:!1,latency_ms:o(),error:{code:"conversation_timeout",message:`no eventDone within ${i}ms`}}:{attempted:!0,ok:!0,latency_ms:o()}}constructor(e,i,r=new gi){this.config=e,this.auditController=new ui(r,{onAuditState:t=>{try{this.aibotHandle.sendAuditState(O(t,Date.now()))}catch{}}}),pi(r)&&r.addJobSettledHandler((t,s)=>{this.auditController.handleJobSettled(t,s)}),this.name=e.name;const n=e.adapterType??"acp";if(this.sendCtrl.setDefaultQuoteTrigger(ti[n]),this.aibotConfig={...e.aibot,...n==="claude"?{localActions:e.aibot.localActions??["session_control","claude_interaction_reply","get_session_usage","get_rate_limits","set_model","set_mode","set_reasoning_effort","thread_compact","get_agent_global_config",...N]}:{}},e.eventQueue&&(this.aibotConfig.concurrency={max_concurrent:e.eventQueue.maxConcurrent,max_queued:e.eventQueue.maxQueued,queue_timeout_ms:e.eventQueue.queueTimeoutMs,cancelable_queued:e.eventQueue.cancelableQueued,cancelable_running:e.eventQueue.cancelableRunning}),this.conversationLog=e.logDir?new ke(e.logDir):null,this.packetLog=e.logDir?new Te(e.logDir):null,this.bindingStore=new Gn(e.bindingsPath,e.legacyBindingsPath),this.bindingStore.load(),this.globalConfigStore=i??null,this.deferredMgr=new di(this.name),this.activeEventStore=e.activeEventStorePath?new zn(e.activeEventStorePath):null,this.pendingEvents=new Jn(e.pendingEventStorePath),n==="codex")this.sessionScanCache=new v(de,_e);else if(n==="claude")this.sessionScanCache=new v(le,Se);else if(n==="pi"){const t=e.agent.env?.PI_CODING_AGENT_DIR;this.sessionScanCache=new v(()=>pe(void 0,t),()=>be(void 0,t))}else if(n==="codewhale")this.sessionScanCache=new v(ge,Ae);else if(n==="cursor")this.sessionScanCache=new v(fe,Ee);else if(n==="opencode")this.sessionScanCache=new v(me,we);else if(n==="deepseek-harness"){const t=typeof e.adapterOptions?.dshHome=="string"?e.adapterOptions.dshHome:e.agent.env?.DSH_HOME;this.sessionScanCache=new v(()=>ve(t),()=>ye(t))}else if(n==="agy")this.sessionScanCache=new v(()=>[],()=>[]);else{e.aibot.clientType?.trim().toLowerCase()==="reasonix"&&(this.reasonixTitleScan=new v(ue,Re));const t=ce(e.aibot.clientType);this.sessionScanCache=t?new v(()=>he(void 0,t),()=>Ce(void 0,t)):new v(()=>[],()=>[])}}async start(){if(this.stopped)throw new Error("agent start aborted");if(await ae({agentName:this.name,adapterType:this.config.adapterType??"acp",command:this.config.agent.command,piConfigDir:this.config.agent.env?.PI_CODING_AGENT_DIR,dshHome:typeof this.config.adapterOptions?.dshHome=="string"?this.config.adapterOptions.dshHome:this.config.agent.env?.DSH_HOME,hasProvider:!!this.config.agent.provider,boundCwds:[...this.bindingStore.entries()].map(([,t])=>String(t.cwd??""))}).then(t=>{t.length>0&&h.info(this.name,`restored native provider config after relay disable: ${t.join(", ")}`)}).catch(t=>{h.warn(this.name,`native provider residue sweep failed: ${t instanceof Error?t.message:String(t)}`)}),this.stopped)throw new Error("agent start aborted");if((this.config.adapterType??"acp")==="claude"){if(await Z().catch(()=>{}),this.stopped)throw new Error("agent start aborted");this.maybeQueryProviderQuota().catch(()=>{})}if(this.stopped)throw new Error("agent start aborted");const e=!!(this.config.providerBaseUrl&&this.config.providerApiKey||this.config.agent.provider?.baseUrl&&this.config.agent.provider?.apiKey),i=(this.config.adapterType??"acp")==="pi",r=(this.config.adapterType??"acp")==="opencode";if(this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi"||e?(this.maybeQueryProviderQuota().catch(()=>{}),this.startProviderQuotaTimer()):(i||r)&&this.startProviderQuotaTimer(),(this.config.adapterType??"acp")==="codex"&&this.maybeQueryProviderQuota().catch(()=>{}),(this.config.adapterType??"acp")==="opencode"&&this.maybeQueryProviderQuota().catch(()=>{}),this.stopped)throw new Error("agent start aborted");if(await this.connectAibot(),this.stopped)throw this.aibotHandle?.disconnect(),new Error("agent start aborted");this.sendCtrl.bind(this.aibotHandle);const n=this.config.adapterType??"acp";if(this.pool=new gn({maxPoolSize:this.config.poolMaxSize??20,idleTimeoutMs:this.config.poolIdleTimeoutMs??18e5,eventQueue:this.config.eventQueue},t=>{const s=this.createAdapter(n,t);return s instanceof S&&s.on("acpSessionReady",o=>{this.bindingStore.setAcpSessionId(t,o),this.sessionScanCache.invalidate()}),s},(t,s)=>{this.aibotHandle.sendEventAck({event_id:t,session_id:s,received_at:Date.now()})}),this.pool.setEventStateHandler((t,s,o,a)=>{if(h.info(this.name,`[queue-debug] send event_state session=${s} event=${t} state=${o} queue_pos=${a?.queue_position??""} queue_total=${a?.queue_total??""}`),this.aibotHandle.sendEventState({event_id:t,session_id:s,state:o,content_preview:a?.content_preview,content:a?.content,queue_position:a?.queue_position,queue_total:a?.queue_total,actions:a?.actions,reason:a?.reason,held:a?.held,held_reason:a?.held_reason,updated_at:Date.now()}),this.pushQueueSnapshotForSession(s),o==="running"&&(this.pendingStartedEventIds.add(t),this.pendingEvents.remove(t).catch(l=>{h.warn(this.name,`Failed to remove running event from pending store event=${t}: ${l instanceof Error?l.message:String(l)}`)})),o==="canceled"||o==="failed"){const l=o==="canceled"?"canceled":"failed";this.aibotHandle.sendEventResult({event_id:t,status:l,msg:a?.reason,updated_at:Date.now()}),this.auditController.closeWithoutAdapter(t,l,a?.reason,{queueTerminalState:o}),this.discardEventTrackingState(t),this.pendingEvents.remove(t).catch(d=>{h.warn(this.name,`Failed to remove queued terminal event from pending store event=${t}: ${d instanceof Error?d.message:String(d)}`)})}}),this.pool.setQueueComposingHandler((t,s,o)=>{this.aibotHandle.sendSessionActivitySet({session_id:t,kind:"composing",active:s,...s?{ttl_ms:Xn,ref_event_id:o}:{}})}),this.pool.setInternalErrorHandler(t=>{this.handleSessionInternalError(t).catch(s=>{h.error(this.name,`[recovery] handleSessionInternalError failed event=${t.eventId} session=${t.sessionId}: ${s instanceof Error?s.message:String(s)}`)})}),this.pool.setEventStartedHandler((t,s)=>{if(this.reportSessionSkills(s),this.config.adapterType!=="claude")return;this.claudeWorkerStatus.set(s,"busy");const o=this.bindingStore.get(s);o?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:s,worker_status:"busy",cwd:o.cwd,meta:this.buildClaudeToolbarMeta(s)})}),this.pool.setEventDoneHandler((t,s)=>{this.markAuditAdapterClosed(t,s);const o=this.config.adapterType??"acp";if(o==="claude"){this.claudeWorkerStatus.set(s,"ready");const a=this.bindingStore.get(s);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:s,worker_status:"ready",cwd:a.cwd,meta:this.buildClaudeToolbarMeta(s)})}else if(o==="agy"){const a=this.bindingStore.get(s);if(a?.cwd){const l=this.buildAgyToolbarMeta(s),d=l?.available_models??[];h.info(this.name,`[agy-toolbar-diag] eventDone push binding card session=${s} model_id=${String(l?.model_id??"")} available_models=${d.length} meta_keys=${l?Object.keys(l).join(","):"<none>"}`),this.sendAgyBindingCard(s,a.cwd,l),this.refreshAndPushAgyQuota(s)}else h.info(this.name,`[agy-toolbar-diag] eventDone skip binding card: no binding cwd session=${s}`)}}),this.pool.setSessionActivityHandler((t,s,o)=>{const a=this.selfDrivenSessions.has(t),l=this.selfDrivenLabels.get(t);s?(this.selfDrivenSessions.add(t),o&&this.selfDrivenLabels.set(t,o),this.aibotHandle.sendSessionActivitySet({session_id:t,kind:"composing",active:!0,ttl_ms:9e4})):(this.selfDrivenSessions.delete(t),this.selfDrivenLabels.delete(t),a&&this.aibotHandle.sendSessionActivitySet({session_id:t,kind:"composing",active:!1})),(a!==s||s&&o!==void 0&&o!==l)&&this.pushQueueSnapshotForSession(t)}),await this.replayPendingEventsOnStartup(),this.stopped)throw new Error("agent start aborted");this.pool.startIdleSweep(),h.info(this.name,`Ready (adapter: ${n}, poolMax: ${this.config.poolMaxSize??20})`)}requestStop(){this.stopped=!0,this.lifecycleBarrier.close(),this.startupAbortController.abort(),this.pool?.stopIdleSweep(),this.stopProviderQuotaTimer(),this.pool?.pauseAllQueues("shutdown")}async stop(e){if(e?.dropPendingEvents&&(this.dropPendingEventsRequested=!0),this.requestStop(),!this.stopPromise){const i=this.stopOnce();this.stopPromise=i,i.catch(()=>{this.stopPromise===i&&(this.stopPromise=null)})}await this.stopPromise,this.dropPendingEventsRequested&&!this.pendingEventsDropped&&await this.dropPendingEventsBestEffort()}async stopOnce(){this.lifecycleBarrier.close(),this.pool?.stopIdleSweep(),this.stopProviderQuotaTimer(),this.pool?.pauseAllQueues("shutdown");const e=this.pool?.collectActiveEventIds()??[],i=new Map(e.map(o=>[o,this.eventSessionIndex.get(o)]));e.length>0&&this.activeEventStore&&await this.activeEventStore.save(e);for(const o of e)h.info(this.name,`Canceling active event on shutdown: ${o}`),this.sendEventResultWithCleanup(o,"canceled","process shutting down");e.length>0&&await new Promise(o=>setTimeout(o,100)),this.pool?.clearActiveEventsForShutdown();for(const o of e){const a=i.get(o),l=a?this.pool?.getSlot(a):void 0;this.auditController.markAdapterClosed(o,l?.adapter.takeAuditBoundary?.(o)??{processTerminated:!0})}const r=this.deferredMgr.getAllDeferredEntries(),n=this.pool?.drainAllQueuedEvents()??[],t=this.pendingEvents.dedupe([...this.pendingEvents.replaySnapshot(),...r.map(o=>({kind:"deferred",channel:o.channel,sessionId:o.sessionId,event:o.event})),...n.map(o=>({kind:"queued",event:o}))]);let s=!1;if(this.dropPendingEventsRequested)try{await this.pendingEvents.clear(),this.pendingEventsDropped=!0}catch(o){h.warn(this.name,`Failed to clear pending event store on removal: ${o instanceof Error?o.message:String(o)}`)}else try{s=await this.pendingEvents.mergeForShutdown(t)}catch(o){h.error(this.name,`Failed to persist pending events on shutdown: ${o instanceof Error?o.message:String(o)}`)}if(!s)for(const o of t){const a=o.event;h.info(this.name,`Failing pending event on shutdown: ${a.event_id}`),this.sendEventResultWithCleanup(a.event_id,"failed","process shutting down"),this.auditController.markAdapterClosed(a.event_id,{adapterNotStarted:!0,processTerminated:!0})}this.deferredMgr.clearAll(),await this.pool?.stop(),this.aibotHandle?.disconnect(),e.length>0&&this.activeEventStore&&await this.activeEventStore.save([]),this.eventSessionIndex.clear(),this.inflightEvents.clear(),this.restartCount.clear(),this.auditController.dispose()}async dropPendingEventsBestEffort(){try{await this.pendingEvents.clear(),this.pendingEventsDropped=!0}catch(e){h.warn(this.name,`Failed to clear pending event store on removal: ${e instanceof Error?e.message:String(e)}`)}}resolveSpawnEnv(){const e=this.providerResolver?this.providerResolver():this.config.agent.provider,i=se(this.config.agent.clientType,e),r=this.config.agent.env;let n=Object.keys(i).length>0?{...i,...r}:r;if(oe(i)){const t=te()?.getRuntimeInfo(),s={...r??{},...i},o=re(s,{proxyUrl:t?.proxyUrl,caCertPath:t?.caCertPath,caBundlePath:t?.caBundlePath});return delete o.ANTHROPIC_API_KEY,delete o.CLAUDE_CODE_OAUTH_TOKEN,o}if(ie(this.config.agent.clientType)){const t=ne(this.name);t&&(n={...n??{},...t})}return ee(n,this.name,this.config.agent.clientType)}createAdapter(e,i){switch(e){case"claude":return this.createClaudeAdapter(i);case"codex":return this.createCodexAdapter(i);case"pi":return this.createPiAdapter(i);case"openhuman":return this.createOpenHumanAdapter(i);case"codewhale":return this.createCodeWhaleAdapter(i);case"cursor":return this.createCursorAdapter(i);case"opencode":return this.createOpenCodeAdapter(i);case"agy":return this.createAgyAdapter(i);case"deepseek-harness":return this.createDshAdapter(i);default:return this.createAcpAdapter(i)}}createDshAdapter(e){const i={sendStreamChunk:(t,s,o,a,l,d,c)=>{this.sendStreamChunkByRuntimeConfig(t,s,o,a,l,d,c)},sendFinalStreamChunkReliable:this.reliableFinalWiring("deepseek-harness",Ai),sendThinking:(t,s,o)=>this.sendThinkingByRuntimeConfig(t,s,o),sendEventResult:(t,s,o,a)=>{this.sendEventResultWithCleanup(t,s,o,void 0,a)},sendRawEventEnvelope:(t,s,o,a)=>{const l=oi(o);if(l){this.sendToolExecutionCard(t,s,l);return}this.deliverRawEventEnvelope(t,s,o,"deepseek",a)},sendLocalActionResult:(t,s,o,a,l)=>{this.aibotHandle.sendLocalActionResult({action_id:t,status:s,...o!==void 0?{result:o}:{},...a?{error_code:a}:{},...l?{error_msg:l}:{}},e)},sendPermissionCard:t=>{this.sendGrixApprovalCard(t,"deepseek")},sendUpdateBindingCard:(t,s,o,a)=>{this.aibotHandle.sendUpdateBindingCard({session_id:t,worker_status:s,cwd:o,meta:a})},getAgentProfile:()=>({...this.agentProfile,systemPrompt:this.agentSystemPrompt}),getAgentId:()=>this.config.aibot.agentId,queryProviderQuota:t=>this.maybeQueryProviderQuota(t===!0,{providerId:"deepseek"}),agentInvoke:async(t,s,o)=>this.platformInvoke(t,s,o),eventToolInvoke:async(t,s)=>this.invokeDshEventTool(t,s)},r=M("sha256").update(this.config.aibot.agentId).digest("hex").slice(0,24),n=this.config.adapterOptions??{};return new z({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:n},i,{aibotSessionId:e,bindingStore:this.bindingStore,globalConfigStore:this.globalConfigStore,agentName:this.name,dataRoot:y.join(w.data,"deepseek-harness",r),...typeof n.cordisPath=="string"?{cordisPath:n.cordisPath}:{},...typeof n.defaultModel=="string"?{defaultModel:n.defaultModel}:{},...typeof n.maxTokens=="number"?{maxTokens:n.maxTokens}:{},...typeof n.maxLineBytes=="number"?{maxLineBytes:n.maxLineBytes}:{},...n.integrationMode==="embedded_jsonrpc"||n.integrationMode==="profile_bridge"?{integrationMode:n.integrationMode}:{},...typeof n.dshHome=="string"?{dshHome:n.dshHome}:{},...typeof n.dshProfile=="string"?{dshProfile:n.dshProfile}:{},...typeof n.autoInstallBridge=="boolean"?{autoInstallBridge:n.autoInstallBridge}:{},...typeof n.autoStartProfile=="boolean"?{autoStartProfile:n.autoStartProfile}:{},...this.config.agent.provider?{provider:this.config.agent.provider}:{},promptTimeoutMs:this.config.promptTimeoutMs})}createCursorAdapter(e){const i={...this.config.adapterOptions??{}};i.bindingStore=this.bindingStore,i.aibotSessionId=e;const r=this.bindingStore.get(e),n=this.resolveSessionModelId(e);n&&(i.model=n);const t=this.resolveCursorSessionModeId(e),s=t??"full_auto";t||this.bindingStore.setCursorModeId(e,s),i.mode=s,r?.cwd&&(i.workspace=r.cwd);const o={sendStreamChunk:(a,l,d,c,u,g,p)=>{this.sendStreamChunkByRuntimeConfig(a,l,d,c,u,g,p)},sendEventResult:(a,l,d)=>{this.sendEventResultWithCleanup(a,l,d)},sendEventAck:(a,l)=>{this.aibotHandle.sendEventAck({event_id:a,session_id:l,received_at:Date.now()})},sendRawEventEnvelope:(a,l,d)=>{this.deliverRawEventEnvelope(a,l,d,"cursor",this.buildCursorRawEventFallbackText(d))},sendAgentQuestionCard:(a,l,d)=>{const c=d.questions.map(g=>g.header).join(", "),u=I(`[Agent Question] ${d.request_id}`,"agent_question",d);this.aibotHandle.sendText({event_id:a,session_id:l,content:u,msg_type:1,extra:{card_type:"agent_question",summary_text:c}})},agentInvoke:async(a,l,d)=>this.platformInvoke(a,l,d),sendLocalActionResult:(a,l,d,c,u)=>{this.aibotHandle.sendLocalActionResult({action_id:a,status:l,...d!==void 0?{result:d}:{},...c?{error_code:c}:{},...u?{error_msg:u}:{}},e)},sendUpdateBindingCard:(a,l,d,c)=>{this.aibotHandle.sendUpdateBindingCard({session_id:a,worker_status:l,cwd:d,...c?{meta:c}:{}})},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId};return new j({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:i},o)}createClaudeAdapter(e){const i={sendReply:(t,s,o,a,l)=>{this.sendReplyByRuntimeConfig(t,s,o,a,l)},sendStreamChunk:(t,s,o,a,l,d,c)=>{this.sendStreamChunkByRuntimeConfig(t,s,o,a,l,d,c)},sendMedia:(t,s,o,a,l,d,c)=>{this.aibotHandle.sendMedia({event_id:t,session_id:s,content:o,msg_type:2,quoted_message_id:l||void 0,client_msg_id:d||void 0,extra:c?{media_caption:a,...c}:{media_caption:a}})},sendEventResult:(t,s,o,a)=>{this.sendEventResultWithCleanup(t,s,o,a)},sendEventAck:(t,s)=>{this.aibotHandle.sendEventAck({event_id:t,session_id:s,received_at:Date.now()})},agentInvoke:async(t,s,o)=>this.platformInvoke(t,s,o),sendLocalActionResult:(t,s,o,a,l)=>{this.aibotHandle.sendLocalActionResult({action_id:t,status:s,...o!==void 0?{result:o}:{},...a?{error_code:a}:{},...l?{error_msg:l}:{}},e)},sendToolUse:(t,s,o,a)=>{this.sendToolExecutionCard(t,s,C(o,a))},sendToolResult:(t,s,o,a)=>{this.sendToolExecutionCard(t,s,b(o,a))},getWsUrl:()=>this.config.aibot.url,getAgentId:()=>this.config.aibot.agentId,getAgentProfile:()=>this.agentProfile,getApiKey:()=>this.config.aibot.apiKey,getActiveEventCount:()=>0,getPendingPermissionCount:()=>0,getPendingElicitationCount:()=>0,sendAgentQuestionCard:(t,s,o)=>{this.sendGrixAgentQuestionCard(t,s,o)},sendPermissionCard:t=>{this.sendGrixApprovalCard(t,"claude")},sendDirectMessage:t=>{this.aibotHandle.sendMsg({session_id:t.sessionId,msg_type:1,content:t.content,...t.clientMsgId?{client_msg_id:t.clientMsgId}:{},...t.quotedMessageId?{quoted_message_id:t.quotedMessageId}:{}})},onStatusLineUpdated:t=>{(t.rateLimits?.fiveHour||t.rateLimits?.sevenDay)&&(this.cachedClaudeRateLimitState=t);const s=this.bindingStore.get(e);s?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:this.claudeWorkerStatus.get(e)??"ready",cwd:s.cwd,meta:this.buildClaudeToolbarMeta(e)})},sendMcpFrame:t=>{this.aibotHandle.sendMcpFrame(e,t)}},r=this.config.adapterOptions??{},n={...r,sessionRuntimeResolver:()=>{const t=this.bindingStore.get(e),s=this.auditController.getSession(e);return{cwd:t?.cwd,modeId:this.resolveClaudeSessionModeId(e)??J.fullAuto,modelId:this.resolveSessionModelId(e),effort:this.resolveClaudeSessionEffort(e),pluginDir:r.pluginDir,claudeSessionId:t?.claudeSessionId,...s?{audit:{enabled:!0,profile:s.options.profile,capture:s.options.capture}}:{},onSessionIdAssigned:o=>{this.bindingStore.setClaudeSessionId(e,o),this.sessionScanCache.invalidate()}}}};return new L({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:n},i)}createCodexAdapter(e){let i=null;const r={sendEventResult:(o,a,l)=>{if(a!=="responded"){this.sendEventResultWithCleanup(o,a,l);return}this.sendCtrl.sendFinalStreamChunkReliable(o,e,`codex_terminal_fence_${o}`,5e3,!0,!0).then(()=>this.sendEventResultWithCleanup(o,a,l),d=>{const c=`codex output acceptance fence failed: ${d instanceof Error?d.message:String(d)}`;this.sendEventResultWithCleanup(o,a==="responded"?"failed":a,a==="responded"?c:l)})},sendEventAck:(o,a)=>this.aibotHandle.sendEventAck({event_id:o,session_id:a,received_at:Date.now()}),sendCodexEvent:o=>{this.shouldDropCodexDisplayEvent(o.event_id,o.codex_method)||(this.captureCodexAuditOutput(o),this.aibotHandle.sendCodexEvent(this.stampCodexEventQuote(o)),this.logCodexEventToConversation(o))},sendThinking:(o,a,l)=>{this.sendThinkingByRuntimeConfig(o,a,l)},sendRunError:(o,a,l)=>{this.sendRunErrorAsChunk(o,a,l)},sendUpdateBindingCard:(o,a,l,d)=>{const c={...d??{}};if(!c.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const u=this.providerQuotaToCodexRateLimits(this.cachedProviderQuota);u&&(c.rate_limits=u.rateLimits,c.rate_limit_primary_percent=u.primaryPercent,c.rate_limit_secondary_percent=u.secondaryPercent,c.rate_limit_primary_window_min=u.primaryWindowMin,c.rate_limit_secondary_window_min=u.secondaryWindowMin)}!c.provider_quota&&this.cachedProviderQuota?.success&&(c.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:a,cwd:l,...Object.keys(c).length>0?{meta:c}:{}})},agentInvoke:async(o,a,l)=>this.platformInvoke(o,a,l),sendLocalActionResult:(o,a,l,d,c)=>this.aibotHandle.sendLocalActionResult({action_id:o,status:a,...l!==void 0?{result:l}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}},e),sendSessionActivitySet:(o,a,l,d)=>{this.aibotHandle.sendSessionActivitySet({session_id:o,kind:a,active:l,...d??{}})},getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId,onRateLimitsUpdated:o=>{this.cachedRateLimits=o,this.cachedRateLimitsSampledAtMs=Date.now(),this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const a=this.bindingStore.get(e);if(a?.cwd){const l=this.cachedRateLimitsSampledAtMs,d={rate_limits:{...o.primary.windowMinutes>0?{primary:o.primary}:{},...o.secondary.windowMinutes>0?{secondary:o.secondary}:{},sampledAt:l},rate_limit_primary_percent:o.primary.usedPercent,rate_limit_secondary_percent:o.secondary.usedPercent,rate_limit_primary_window_min:o.primary.windowMinutes,rate_limit_secondary_window_min:o.secondary.windowMinutes,credits:o.credits,...o.extras&&o.extras.length>0?{extra_limits:o.extras}:{},...i?.getEffortMeta()};this.cachedProviderQuota?.success&&(d.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:a.cwd,meta:d})}},onContextWindowUpdated:o=>{if(!o)return;this.cachedCodexContextWindow=o,this.cachedCodexUsageSampledAtMs=Date.now();const a=this.bindingStore.get(e);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:a.cwd,meta:{context_window:o,...i?.getEffortMeta()}})},onTokenUsageUpdated:o=>{o&&(this.cachedCodexTokenUsage=o,this.cachedCodexUsageSampledAtMs=Date.now())}},n=this.config.adapterOptions??{},t=this.globalConfigStore?.get(this.name),s=this.auditController.getAdapterPreparation(e);return i=new D({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...n,model:this.resolveCodexSessionModelId(e)??n.model,collaborationMode:this.bindingStore.getCodexModeId(e)??this.resolveCodexNewSessionGlobalDefault(e,t?.codexModeId,o=>this.bindingStore.setCodexModeId(e,o))??n.collaborationMode,reasoningEffort:this.bindingStore.getCodexReasoningEffort(e)??this.pinCodexGlobalDefault(t?.codexReasoningEffort,o=>this.bindingStore.setCodexReasoningEffort(e,o))??n.reasoningEffort,serviceTier:this.bindingStore.getCodexServiceTier(e)??this.resolveCodexNewSessionGlobalDefault(e,t?.codexServiceTier,o=>this.bindingStore.setCodexServiceTier(e,o))??n.serviceTier,sandboxMode:this.bindingStore.getCodexSandboxMode(e)??this.pinCodexGlobalDefault(t?.codexSandboxMode,o=>this.bindingStore.setCodexSandboxMode(e,o))??n.sandboxMode,aibotSessionId:e,bindingStore:this.bindingStore,...Q(s?.options)?{rawApiCapture:{auditId:s.auditId,sessionId:e,spoolRootDir:y.join(w.data,"audit-replay","raw-spool")}}:{}}},r),i}createCodeWhaleAdapter(e){const i={sendEventResult:(n,t,s)=>{this.sendEventResultWithCleanup(n,t,s)},sendEventAck:(n,t)=>this.aibotHandle.sendEventAck({event_id:n,session_id:t,received_at:Date.now()}),sendStreamChunk:(n,t,s,o,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,t,s,o,a,l)},sendUpdateBindingCard:(n,t,s,o)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:t,cwd:s,...this.providerQuotaMetaPayload(o,n,s)}),sendLocalActionResult:(n,t,s,o,a)=>this.aibotHandle.sendLocalActionResult({action_id:n,status:t,...s!==void 0?{result:s}:{},...o?{error_code:o}:{},...a?{error_msg:a}:{}},e),sendSessionActivitySet:(n,t,s,o)=>{this.aibotHandle.sendSessionActivitySet({session_id:n,kind:t,active:s,...o??{}})},sendToolUse:(n,t,s,o)=>{this.sendToolExecutionCard(n,t,C(s,o))},sendToolResult:(n,t,s,o)=>{this.sendToolExecutionCard(n,t,b(s,o))},agentInvoke:async(n,t,s)=>this.platformInvoke(n,t,s),getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=this.config.adapterOptions??{};return new K({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...r,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,model:this.resolveSessionModelId(e)??r.model,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},i)}createPiAdapter(e){const i={sendEventResult:(n,t,s)=>{this.sendEventResultWithCleanup(n,t,s),h.info("bridge",`[pi] sendEventResult event=${n} status=${t}`)},sendEventAck:(n,t)=>this.aibotHandle.sendEventAck({event_id:n,session_id:t,received_at:Date.now()}),sendUpdateBindingCard:(n,t,s,o)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:t,cwd:s,...this.providerQuotaMetaPayload(o,n,s)}),agentInvoke:async(n,t,s)=>this.platformInvoke(n,t,s),sendLocalActionResult:(n,t,s,o,a)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:t,...s!==void 0?{result:s}:{},...o?{error_code:o}:{},...a?{error_msg:a}:{}},e)},sendSessionActivitySet:(n,t,s,o)=>{this.aibotHandle.sendSessionActivitySet({session_id:n,kind:t,active:s,...o??{}})},sendToolUse:(n,t,s,o)=>{this.sendToolExecutionCard(n,t,C(s,o))},sendToolResult:(n,t,s,o)=>{this.sendToolExecutionCard(n,t,b(s,o))},sendStreamChunk:(n,t,s,o,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,t,s,o,a,l),a&&h.info("bridge",`[pi] sendFinalStreamChunk event=${n} seq=${o}`)},sendFinalStreamChunkReliable:this.reliableFinalWiring("pi"),sendThinking:(n,t,s)=>{this.sendThinkingByRuntimeConfig(n,t,s)},sendRunError:(n,t,s,o,a)=>{this.sendStreamChunkByRuntimeConfig(n,t,`
2
2
 
3
- Error: ${o}`,r,!1,a)},getAgentProfile:()=>this.agentProfile},s=this.config.adapterOptions??{};return new oe({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...s,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},t)}createOpenHumanAdapter(e){const t={sendStreamChunk:(i,n,o,r,a,c)=>{this.sendStreamChunkByRuntimeConfig(i,n,o,r,a,c)},sendFinalStreamChunkReliable:async(i,n,o,r)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(i,n,r)}catch(a){throw p.error("bridge",`[openhuman] sendFinalStreamChunkReliable ACK failed event=${i}: ${a}`),a}},sendEventResult:(i,n,o)=>{this.sendEventResultWithCleanup(i,n,o),p.info("bridge",`[openhuman] sendEventResult event=${i} status=${n}`)},sendEventAck:(i,n)=>this.aibotHandle.sendEventAck({event_id:i,session_id:n,received_at:Date.now()}),sendToolUse:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,D(o,r))},sendToolResult:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,M(o,r))},sendThinking:(i,n,o)=>{this.sendThinkingByRuntimeConfig(i,n,o)},sendRunError:(i,n,o)=>{this.sendStreamChunkByRuntimeConfig(i,n,`
3
+ Error: ${s}`,o,!1,a)},getAgentProfile:()=>this.agentProfile},r=this.config.adapterOptions??{};return new W({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...r,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},i)}createOpenHumanAdapter(e){const i={sendStreamChunk:(n,t,s,o,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,t,s,o,a,l)},sendFinalStreamChunkReliable:async(n,t,s,o)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(n,t,o)}catch(a){throw h.error("bridge",`[openhuman] sendFinalStreamChunkReliable ACK failed event=${n}: ${a}`),a}},sendEventResult:(n,t,s)=>{this.sendEventResultWithCleanup(n,t,s),h.info("bridge",`[openhuman] sendEventResult event=${n} status=${t}`)},sendEventAck:(n,t)=>this.aibotHandle.sendEventAck({event_id:n,session_id:t,received_at:Date.now()}),sendToolUse:(n,t,s,o)=>{this.sendToolExecutionCard(n,t,C(s,o))},sendToolResult:(n,t,s,o)=>{this.sendToolExecutionCard(n,t,b(s,o))},sendThinking:(n,t,s)=>{this.sendThinkingByRuntimeConfig(n,t,s)},sendRunError:(n,t,s)=>{this.sendStreamChunkByRuntimeConfig(n,t,`
4
4
 
5
- Error: ${o}`,0,!1)},sendUpdateBindingCard:(i,n,o,r)=>this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:n,cwd:o,...this.providerQuotaMetaPayload(r,i,o)}),agentInvoke:async(i,n,o)=>this.platformInvoke(i,n,o),sendLocalActionResult:(i,n,o,r,a)=>{this.aibotHandle.sendLocalActionResult({action_id:i,status:n,...o!==void 0?{result:o}:{},...r?{error_code:r}:{},...a?{error_msg:a}:{}},e)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},s=this.config.adapterOptions??{};return new re({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:s},t,{port:s.port,host:s.host,workspaceDir:s.workspace_dir,sessionToken:s.session_token,enableSessionBinding:!0,aibotSessionId:e})}createOpenCodeAdapter(e){const t={sendStreamChunk:(i,n,o,r,a,c)=>{this.sendStreamChunkByRuntimeConfig(i,n,o,r,a,c)},sendFinalStreamChunkReliable:this.reliableFinalWiring("opencode"),sendEventResult:(i,n,o)=>{this.sendEventResultWithCleanup(i,n,o),p.info("bridge",`[opencode] sendEventResult event=${i} status=${n}`)},sendEventAck:(i,n)=>this.aibotHandle.sendEventAck({event_id:i,session_id:n,received_at:Date.now()}),sendToolUse:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,D(o,r))},sendToolResult:(i,n,o,r)=>{this.sendToolExecutionCard(i,n,M(o,r))},sendThinking:(i,n,o)=>{this.sendThinkingByRuntimeConfig(i,n,o)},sendRunError:(i,n,o)=>{this.sendRunErrorAsChunk(i,n,o)},sendUpdateBindingCard:(i,n,o,r)=>this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:n,cwd:o,...this.providerQuotaMetaPayload(r,i,o)}),agentInvoke:async(i,n,o)=>this.platformInvoke(i,n,o),sendLocalActionResult:(i,n,o,r,a)=>{this.aibotHandle.sendLocalActionResult({action_id:i,status:n,...o!==void 0?{result:o}:{},...r?{error_code:r}:{},...a?{error_msg:a}:{}},e)},sendPermissionCard:i=>{this.sendGrixApprovalCard(i,"opencode")},sendAgentQuestionCard:(i,n,o)=>{this.sendGrixAgentQuestionCard(i,n,o)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},s=this.config.adapterOptions??{};return new F({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:s},t,{port:s.port,hostname:s.hostname,model:s.model??this.resolveSessionModelId(e),agent:s.agent,permissionPolicy:s.permission_policy,enableSessionBinding:!0,aibotSessionId:e,bindingStore:this.bindingStore,...this.config.agent.provider?{provider:this.config.agent.provider}:{}})}createAgyAdapter(e){const t={sendStreamChunk:(i,n,o,r,a,c)=>{this.sendStreamChunkByRuntimeConfig(i,n,o,r,a,c)},sendEventResult:(i,n,o)=>{this.sendEventResultWithCleanup(i,n,o)},sendEventAck:(i,n)=>{this.aibotHandle.sendEventAck({event_id:i,session_id:n,received_at:Date.now()})},agentInvoke:async(i,n,o)=>this.platformInvoke(i,n,o),forceCompleteInternalEvent:(i,n)=>{this.pool.eventComplete(i,n),this.pushQueueSnapshotForSession(n)},persistConversationId:(i,n)=>{this.bindingStore.setAgyConversationId(i,n)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},s=i=>{const n=this.bindingStore.get(i);return{cwd:n?.cwd,modelId:this.resolveSessionModelId(i),conversationId:n?.agyConversationId}};return new G({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:this.config.adapterOptions??{}},t,s)}createAcpAdapter(e){const t=this.isAcpRawTransportEnabled(),s={sendStreamChunk:(d,l,h,g,u,f,b)=>{this.sendStreamChunkByRuntimeConfig(d,l,h,g,u,f,b)},sendFinalStreamChunkReliable:this.reliableFinalWiring("acp",4e3),sendEventResult:(d,l,h)=>{this.sendEventResultWithCleanup(d,l,h)},sendEventAck:(d,l)=>{this.aibotHandle.sendEventAck({event_id:d,session_id:l,received_at:Date.now()})},agentInvoke:async(d,l,h)=>this.platformInvoke(d,l,h),sendLocalActionResult:(d,l,h,g,u)=>{this.aibotHandle.sendLocalActionResult({action_id:d,status:l,...h!==void 0?{result:h}:{},...g?{error_code:g}:{},...u?{error_msg:u}:{}},e)},sendRawEventEnvelope:(d,l,h)=>{this.sendAcpRawEventEnvelope(d,l,h)},sendToolUse:(d,l,h,g)=>{if(t){this.sendAcpRawEventEnvelope(d,l,{type:"tool_use",payload:{tool_name:h,tool_input:g??""}});return}this.sendToolExecutionCard(d,l,D(h,g))},sendToolResult:(d,l,h,g)=>{this.sendToolExecutionCard(d,l,M(h,g))},sendThinking:(d,l,h)=>{this.sendThinkingByRuntimeConfig(d,l,h)},sendRunError:(d,l,h)=>{this.sendStreamChunkByRuntimeConfig(d,l,`
5
+ Error: ${s}`,0,!1)},sendUpdateBindingCard:(n,t,s,o)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:t,cwd:s,...this.providerQuotaMetaPayload(o,n,s)}),agentInvoke:async(n,t,s)=>this.platformInvoke(n,t,s),sendLocalActionResult:(n,t,s,o,a)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:t,...s!==void 0?{result:s}:{},...o?{error_code:o}:{},...a?{error_msg:a}:{}},e)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=this.config.adapterOptions??{};return new G({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:r},i,{port:r.port,host:r.host,workspaceDir:r.workspace_dir,sessionToken:r.session_token,enableSessionBinding:!0,aibotSessionId:e})}createOpenCodeAdapter(e){const i={sendStreamChunk:(n,t,s,o,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,t,s,o,a,l)},sendFinalStreamChunkReliable:this.reliableFinalWiring("opencode"),sendEventResult:(n,t,s)=>{this.sendEventResultWithCleanup(n,t,s),h.info("bridge",`[opencode] sendEventResult event=${n} status=${t}`)},sendEventAck:(n,t)=>this.aibotHandle.sendEventAck({event_id:n,session_id:t,received_at:Date.now()}),sendToolUse:(n,t,s,o)=>{this.sendToolExecutionCard(n,t,C(s,o))},sendToolResult:(n,t,s,o)=>{this.sendToolExecutionCard(n,t,b(s,o))},sendThinking:(n,t,s)=>{this.sendThinkingByRuntimeConfig(n,t,s)},sendRunError:(n,t,s)=>{this.sendRunErrorAsChunk(n,t,s)},sendUpdateBindingCard:(n,t,s,o)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:t,cwd:s,...this.providerQuotaMetaPayload(o,n,s)}),agentInvoke:async(n,t,s)=>this.platformInvoke(n,t,s),sendLocalActionResult:(n,t,s,o,a)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:t,...s!==void 0?{result:s}:{},...o?{error_code:o}:{},...a?{error_msg:a}:{}},e)},sendPermissionCard:n=>{this.sendGrixApprovalCard(n,"opencode")},sendAgentQuestionCard:(n,t,s)=>{this.sendGrixAgentQuestionCard(n,t,s)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=this.config.adapterOptions??{};return new k({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:r},i,{port:r.port,hostname:r.hostname,model:r.model??this.resolveSessionModelId(e),agent:r.agent,permissionPolicy:r.permission_policy,enableSessionBinding:!0,aibotSessionId:e,bindingStore:this.bindingStore,...this.config.agent.provider?{provider:this.config.agent.provider}:{}})}createAgyAdapter(e){const i={sendStreamChunk:(n,t,s,o,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,t,s,o,a,l)},sendEventResult:(n,t,s)=>{this.sendEventResultWithCleanup(n,t,s)},sendEventAck:(n,t)=>{this.aibotHandle.sendEventAck({event_id:n,session_id:t,received_at:Date.now()})},agentInvoke:async(n,t,s)=>this.platformInvoke(n,t,s),forceCompleteInternalEvent:(n,t)=>{this.pool.eventComplete(n,t),this.pushQueueSnapshotForSession(t)},persistConversationId:(n,t)=>{this.bindingStore.setAgyConversationId(n,t)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=n=>{const t=this.bindingStore.get(n);return{cwd:t?.cwd,modelId:this.resolveSessionModelId(n),conversationId:t?.agyConversationId}};return new H({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:this.config.adapterOptions??{}},i,r)}createAcpAdapter(e){const i=this.isAcpRawTransportEnabled(),r={sendStreamChunk:(d,c,u,g,p,_,A)=>{this.sendStreamChunkByRuntimeConfig(d,c,u,g,p,_,A)},sendFinalStreamChunkReliable:this.reliableFinalWiring("acp",4e3),sendEventResult:(d,c,u)=>{this.sendEventResultWithCleanup(d,c,u)},sendEventAck:(d,c)=>{this.aibotHandle.sendEventAck({event_id:d,session_id:c,received_at:Date.now()})},agentInvoke:async(d,c,u)=>this.platformInvoke(d,c,u),sendLocalActionResult:(d,c,u,g,p)=>{this.aibotHandle.sendLocalActionResult({action_id:d,status:c,...u!==void 0?{result:u}:{},...g?{error_code:g}:{},...p?{error_msg:p}:{}},e)},sendRawEventEnvelope:(d,c,u)=>{this.sendAcpRawEventEnvelope(d,c,u)},sendToolUse:(d,c,u,g)=>{if(i){this.sendAcpRawEventEnvelope(d,c,{type:"tool_use",payload:{tool_name:u,tool_input:g??""}});return}this.sendToolExecutionCard(d,c,C(u,g))},sendToolResult:(d,c,u,g)=>{this.sendToolExecutionCard(d,c,b(u,g))},sendThinking:(d,c,u)=>{this.sendThinkingByRuntimeConfig(d,c,u)},sendRunError:(d,c,u)=>{this.sendStreamChunkByRuntimeConfig(d,c,`
6
6
 
7
- Error: ${h}`,1,!1)},sendAgentQuestionCard:(d,l,h)=>{this.sendGrixAgentQuestionCard(d,l,h)},sendPermissionCard:d=>{p.info("bridge","sendPermissionCard callback entered",{rawTransport:t,eventId:d.eventId,sessionId:d.sessionId,toolCallId:d.toolCallId,toolName:d.toolName,toolTitle:d.toolTitle});const l=d.toolInput&&d.toolTitle&&d.toolInput!==d.toolTitle?`${d.toolTitle}: ${d.toolInput}`:d.toolTitle||d.toolInput||d.toolName;if(t){this.sendAcpRawEventEnvelope(d.eventId,d.sessionId,{type:"permission_request",payload:{tool_call_id:d.toolCallId,tool_name:d.toolName,tool_title:d.toolTitle,...d.toolInput?{tool_input:d.toolInput}:{},options:d.options}}),p.info("bridge","sendPermissionCard: sent via rawEventEnvelope",{eventId:d.eventId,toolCallId:d.toolCallId});return}const h=`perm_${B()}`,g={event_id:d.eventId,session_id:d.sessionId,client_msg_id:h,msg_type:1,content:d.toolTitle?`Permission required: ${d.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:d.toolCallId,approvalSlug:d.toolName},grix:{execApproval:{approval_command_id:d.toolCallId,approval_type:"permission",command:l,host:"acp"}}},agent_api_origin:!0}};p.info("bridge","sendPermissionCard: about to invoke aibotHandle.sendMsg",{eventId:d.eventId,sessionId:d.sessionId,clientMsgId:h,toolCallId:d.toolCallId,contentLength:g.content.length});try{this.aibotHandle.sendMsg(g),p.info("bridge","sendPermissionCard: aibotHandle.sendMsg returned",{eventId:d.eventId,clientMsgId:h})}catch(u){p.error("bridge","sendPermissionCard: aibotHandle.sendMsg threw",{eventId:d.eventId,clientMsgId:h,error:u instanceof Error?u.message:String(u)})}},sendAuthNotification:(d,l)=>{d&&this.aibotHandle.sendMsg({session_id:d,msg_type:1,content:l,extra:{biz_card:{version:1,type:"agent_error",payload:{error:{name:"AuthRequired",message:l}}}}})},sendAgentMessage:(d,l)=>{d&&l&&this.aibotHandle.sendMsg({session_id:d,msg_type:1,content:l})},sendUpdateBindingCard:(d,l,h,g)=>{const u={...g??{}};if(!u.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const f=this.providerQuotaToRateLimits(this.cachedProviderQuota);f&&(u.rate_limits=f)}!u.provider_quota&&this.cachedProviderQuota?.success&&(u.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:d,worker_status:l,cwd:h,...Object.keys(u).length>0?{meta:u}:{}})},onSkillsUpdate:(d,l)=>{try{this.aibotHandle.sendSkillsUpdate({skills:Ae(d,L.skills),library_skills:this.buildLibrarySkillsReport(l)})}catch(h){}},onContextWindowUpdated:d=>{this.cachedAcpContextWindow=d,this.cachedAcpContextWindowSampledAtMs=Date.now();const l="usedPercentage"in d?d.usedPercentage.toFixed(1):(d.used/d.size*100).toFixed(1);p.info(this.name,`[acp] context_window updated: ${l}%`);const h=this.bindingStore.get(e);if(h?.cwd){const g="usedPercentage"in d?d.usedPercentage:Math.min(100,d.used/d.size*100),u={context_window:{..."usedPercentage"in d?{}:d,usedPercentage:g,remainingPercentage:100-g}};if((this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi")&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{}),u.provider_quota=this.cachedProviderQuota;const f=this.providerQuotaToRateLimits(this.cachedProviderQuota);f&&(u.rate_limits=f)}this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:h.cwd,meta:u})}},sendMcpFrame:d=>{this.aibotHandle.sendMcpFrame(e,d)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},i=e?this.bindingStore.get(e):void 0,n=e?this.auditController.getSession(e):void 0,o=this.config.aibot.clientType==="reasonix"&&n?Mi(this.name,e,n.auditId):void 0,r=this.globalConfigStore?.get(this.name),{initialModel:a,initialMode:c}=Yn({sessionBinding:i,globalDefaults:r,configInitialMode:this.config.acpInitialMode});return e&&a&&!i?.acpModelId&&this.bindingStore.setAcpModelId(e,a),e&&c&&!i?.acpModeId&&this.bindingStore.setAcpModeId(e,c),(a||c)&&p.info(this.name,`[toolbar] hydrate from binding: session=${e} model=${a??"<none>"} mode=${c??"<none>"}`),new y({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv()},s,{acpAuthMethod:this.config.acpAuthMethod,acpInitialMode:c,acpInitialModel:a,acpMcpTools:this.config.acpMcpTools,rawTransport:t,eventResultsPath:this.config.eventResultsPath,approvalMode:this.config.approvalMode,bindingStore:this.config.enableSessionBinding?this.bindingStore:void 0,aibotSessionId:e,autoInjectArgs:this.config.autoInjectArgs,nativeProviderScope:this.name,bridgeLog:this.config.logDir?new nt(this.config.logDir,`${this.name}-${e}`):null,reasonixAuditTranscriptPath:o,agentType:this.config.aibot.clientType})}async connectAibot(){const t=await new ie().connect(this.aibotConfig,{aborted:()=>this.stopped,signal:this.startupAbortController.signal,label:this.name,packetLog:this.packetLog,maxRetries:this.config.connectMaxRetries});if(this.stopped)throw t.disconnect(),new Error("connection aborted");this.aibotHandle=t;const s=this.aibotHandle.authAck;if(this.applyAgentProfile(s?.agent_name,s?.introduction,{source:"auth_ack",respawnOnChange:!1},s?.system_prompt),this.aibotHandle.onEvent(i=>{this.handleAibotEvent(i).catch(n=>{p.error(this.name,`handleAibotEvent failed: ${n}`),this.aibotHandle.sendEventAck({event_id:i.event_id,session_id:i.session_id,received_at:Date.now()});const o=n instanceof Error?n.message:String(n);if(/CWD must be|Bound directory does not exist|Bound path is not a directory/i.test(o)&&i.session_id){this.bindingStore.delete(i.session_id),this.sessionBindings.delete(i.session_id),this.sessionProviderHints.delete(i.session_id),this.sessionProviderQuotas.delete(i.session_id),this.sessionProviderMeta.delete(i.session_id);const a=this.pool.getSlot(i.session_id);a?.adapter instanceof y&&a.adapter.getSessionBindings().delete(i.session_id);const c=this.config.adapterType??"acp",d=this.resolveBindingChannelKey(c);this.aibotHandle.sendMsg({event_id:i.event_id,session_id:i.session_id,msg_type:1,content:o,extra:{channel_data:{[d]:{sessionBinding:{status:"missing",reason:"binding_stale",error_code:E.invalidCwd}}}},quoted_message_id:i.msg_id});return}this.aibotHandle.sendEventResult({event_id:i.event_id,status:"failed",msg:o,updated_at:Date.now()})})}),this.aibotHandle.onStop(i=>{try{this.handleAibotStop(i)}catch(n){p.error(this.name,`handleAibotStop failed: ${n}`)}}),this.aibotHandle.onAgentDeleted(i=>{p.warn(this.name,`agent deleted on platform (source=${i?.source??"unknown"}${i?.reason?` reason=${i.reason}`:""}), notifying manager to clean up`);try{this.agentDeletedHandler?.()}catch(n){p.error(this.name,`agentDeletedHandler failed: ${n}`)}}),this.aibotHandle.onShareSet(i=>{try{this.shareSetHandler?.(Array.isArray(i?.shared_to)?i.shared_to:[])}catch(n){p.error(this.name,`onShareSet failed: ${n}`)}}),this.aibotHandle.onProfilePush(i=>{try{this.applyAgentProfile(i?.agent_name,i?.introduction,{source:"profile_push",respawnOnChange:!0},i?.system_prompt)}catch(n){p.error(this.name,`onProfilePush failed: ${n}`)}}),this.aibotHandle.onSkillSync(i=>{if(!this.stopped)try{p.info(this.name,`skill_sync received owner=${i?.owner_id??""} name=${i?.name??""}`),this.skillSyncHandler?.()}catch(n){p.error(this.name,`onSkillSync failed: ${n}`)}}),this.aibotHandle.onRevoke(i=>{this.handleAibotRevoke(i).catch(n=>{p.error(this.name,`handleAibotRevoke failed: ${n}`)})}),this.aibotHandle.onLocalAction(i=>{this.handleAibotLocalAction(i).catch(n=>{p.error(this.name,`handleAibotLocalAction failed: ${n}`)})}),this.aibotHandle.onEventCancel(i=>{p.info(this.name,`recv event_cancel event_id=${i.event_id} session_id=${i.session_id}`),this.handleEventCancel(i).catch(n=>{p.error(this.name,`handleEventCancel failed: ${n}`)})}),this.aibotHandle.onMcpFrame((i,n)=>{const o=this.pool.getSlot(i)?.adapter;o?.deliverMcpFrameToAgent?o.deliverMcpFrameToAgent(n):p.warn(this.name,`mcp_frame: no adapter for session=${i}`)}),this.aibotHandle.onQueueClear(i=>{const n=this.pool.clearQueue(i.session_id);this.aibotHandle.sendQueueClearResult({session_id:i.session_id,canceled_event_ids:n}),this.pushQueueSnapshotForSession(i.session_id)}),typeof this.aibotHandle.onQueueReorder=="function"&&this.aibotHandle.onQueueReorder(i=>{const n=Array.isArray(i.ordered_event_ids)?i.ordered_event_ids.filter(r=>typeof r=="string"&&r.length>0):[],o=this.pool.reorderQueue(i.session_id,n);this.aibotHandle.sendQueueReorderResult({session_id:i.session_id,applied_event_ids:o}),this.pushQueueSnapshotForSession(i.session_id)}),typeof this.aibotHandle.onEventHold=="function"&&this.aibotHandle.onEventHold(i=>{const n=typeof i.session_id=="string"?i.session_id:"",o=typeof i.event_id=="string"?i.event_id:"",r=i.hold!==!1;if(p.info(this.name,`recv event_hold event_id=${o} session_id=${n} hold=${r} reason=${i.reason??""}`),!n||!o){this.aibotHandle.sendEventHoldResult({session_id:n,event_id:o,ok:!1,held:!1,error:"bad_request"});return}const a=typeof i.reason=="string"?i.reason:"",c=typeof i.ttl_ms=="number"?i.ttl_ms:void 0,d=this.pool.holdEvent(n,o,r,a,c),l=d==="ok";this.aibotHandle.sendEventHoldResult({session_id:n,event_id:o,ok:l,held:l?r:!1,...l?{}:{error:d}}),l&&this.pushQueueSnapshotForSession(n)}),typeof this.aibotHandle.onQueueEdit=="function"&&this.aibotHandle.onQueueEdit(i=>{const n=typeof i.session_id=="string"?i.session_id:"",o=typeof i.event_id=="string"?i.event_id:"";if(p.info(this.name,`recv queue_edit event_id=${o} session_id=${n}`),!n||!o){this.aibotHandle.sendQueueEditResult({session_id:n,event_id:o,ok:!1,error:"bad_request"});return}const r=typeof i.content=="string"?i.content:"",a=this.pool.editQueuedEvent(n,o,r),c=a==="ok";this.aibotHandle.sendQueueEditResult({session_id:n,event_id:o,ok:c,...c?{}:{error:a}}),c&&this.pushQueueSnapshotForSession(n)}),typeof this.aibotHandle.onQueueSnapshotQuery=="function"&&this.aibotHandle.onQueueSnapshotQuery(i=>{this.replyQueueSnapshotForSession(i.session_id)}),p.info(this.name,"Connected to aibot"),this.activeEventStore){const i=await this.activeEventStore.drain();if(i.length>0){p.warn(this.name,`Recovering ${i.length} stale event(s) from previous run`);for(const n of i)p.info(this.name,`Failing stale event on startup: ${n}`),this.aibotHandle.sendEventResult({event_id:n,status:"failed",msg:"process restarted, event lost",updated_at:Date.now()})}}this.pushQueueSnapshots(),this.relayStateSyncOnConnect(),this.aibotHandle.onReconnected(()=>{if(this.stopped)return;this.pushQueueSnapshots();const i=this.aibotHandle.authAck;this.applyAgentProfile(i?.agent_name,i?.introduction,{source:"reconnect",respawnOnChange:!0},i?.system_prompt),this.forceRefreshSkills(void 0,{force:!0}),this.skillSyncHandler?.(),this.relayStateSyncOnConnect()}),this.aibotHandle.onStreamRejected((i,n)=>{this.sendCtrl.markEventRejected(i)})}applyAgentProfile(e,t,s,i){const n=String(e??"").trim(),o=String(t??"").trim(),r=i===void 0?this.agentSystemPrompt:String(i),a=n!==this.agentProfile.agentName||o!==this.agentProfile.introduction||r!==this.agentSystemPrompt;this.agentProfile={agentName:n,introduction:o},this.agentSystemPrompt=r,n||o?p.info(this.name,`agent profile (${s.source}): GOT name="${n}" intro_len=${o.length} system_prompt_len=${r.length} changed=${a}`):p.warn(this.name,`agent profile (${s.source}): EMPTY \u2014 \u670D\u52A1\u7AEF\u672A\u4E0B\u53D1 agent_name/introduction\uFF08auth_ack \u5B57\u6BB5\u7F3A\u5931\u6216\u503C\u4E3A\u7A7A\uFF09`),a&&s.respawnOnChange&&this.applyProfileChangeToAdapters("agent_profile_changed")}applyProfileChangeToAdapters(e){if(!this.pool)return;const t=this.pool.getAllSlots();let s=0;for(const r of t)if(r.adapter.onAgentProfileChanged)try{r.adapter.onAgentProfileChanged(),s++}catch(a){p.warn(this.name,`onAgentProfileChanged failed for session=${r.sessionId}: ${a}`)}const i=t.filter(r=>r.adapter instanceof N),n=i.filter(r=>{if(r.state!=="ready")return!1;const a=r.adapter.getStatus();return!a.busy&&!a.backgroundBusy}),o=i.length-n.length;p.info(this.name,`${e}: notified ${s} adapter(s) via hook; respawning ${n.length} idle Claude slot(s), skipping ${o} busy`);for(const r of n)this.pool.removeSlot(r.sessionId).catch(a=>{p.warn(this.name,`removeSlot failed during ${e}: ${a}`)})}pushQueueSnapshots(){if(!(!this.config.eventQueue||!this.pool))for(const e of this.pool.getAllSlots())this.pushQueueSnapshotForSession(e.sessionId)}buildQueueSnapshotPayload(e){const t=this.pool?.getQueueSnapshot(e)??null,s=t?[...t.running]:[],i=t?t.running_items.map(o=>({event_id:o.event_id,...o.content_preview?{content_preview:o.content_preview}:{},...o.title?{title:o.title}:{},...o.summary?{summary:o.summary}:{},actions:[{type:"stop"}]})):[],n=t?t.queued.map(o=>({event_id:o.event_id,position:o.position,...o.content_preview?{content_preview:o.content_preview}:{},...typeof o.content=="string"?{content:o.content}:{},...o.title?{title:o.title}:{},...o.summary?{summary:o.summary}:{},held:o.held===!0,held_reason:o.held_reason??"",actions:[{type:"cancel"}]})):[];if(s.length===0&&this.selfDrivenSessions.has(e)&&this.pool?.getSlot(e)){const o=`selfdrive_${e}`,r=this.selfDrivenLabels.get(e)??"Background task in progress";s.push(o),i.push({event_id:o,content_preview:r,title:r,summary:r,actions:[]})}return{session_id:e,running:s,running_items:i,queued:n}}pushQueueSnapshotForSession(e){if(!this.config.eventQueue||!this.pool)return;const t=this.buildQueueSnapshotPayload(e);p.info(this.name,`[queue-debug] push snapshot session=${e} running=${t.running.length} queued=${t.queued.length} running_ids=[${t.running.join(",")}]`),this.aibotHandle.sendQueueSnapshot(t)}replyQueueSnapshotForSession(e){!this.config.eventQueue||!this.pool||this.aibotHandle.sendQueueSnapshot(this.buildQueueSnapshotPayload(e))}async platformInvoke(e,t,s){return e==="file_link"?ei(t):e==="file_upload"?this.uploadFileAndSendMedia(t):this.aibotHandle.agentInvoke(e,t,s)}invokeDshEventTool(e,t){const s=Ee(this.aibotHandle,e,t),i=s.content[0]?.text??"";if(s.isError)throw new Error(i||`grix event tool "${e}" failed`);try{return JSON.parse(i)}catch{return i}}async uploadFileAndSendMedia(e){const t=String(e.file_path??"").trim(),s=String(e.session_id??"").trim(),i=String(e.caption??"").trim(),n=String(e.reply_to_message_id??"").trim();if(!t)throw new Error("file_path is required");if(!s)throw new Error("session_id is required");const o=await ni({wsURL:this.config.aibot.url,apiKey:this.config.aibot.apiKey,sessionID:s,filePath:t}),r=await this.aibotHandle.sendMedia({session_id:s,msg_type:2,content:i||`[${o.attachment_type}]`,client_msg_id:`file_upload_${B()}`,...n?{quoted_message_id:n}:{},extra:o.extra});if(r.cmd!=="send_ack"){const c=r.payload??{},d=String(c.msg??r.cmd);throw new Error(`media message send failed: ${d}`)}const a=r.payload??{};return{ok:!0,file_name:o.file_name,attachment_type:o.attachment_type,access_url:o.access_url,message_id:a.msg_id!=null?String(a.msg_id):null}}sendReplyByRuntimeConfig(e,t,s,i,n){const o=this.indexEventSession(e,t)??t;this.auditController.captureReply(e,s),this.sendCtrl.sendReply(e,o,s,i,n),s&&this.conversationLog?.logOutbound?.(o,e,"reply",s)}stampCodexEventQuote(e){if(e.quoted_message_id!=null){if(e.quoted_message_id)return e;const{quoted_message_id:o,...r}=e;return r}const t=e;if(t.codex_method!=="item/agentMessage/delta")return e;const i=t.codex_payload?.params?.phase;if(typeof i=="string"&&i.trim()&&i.trim().toLowerCase()!=="final_answer")return e;const n=this.sendCtrl.getDefaultQuotedMessageId(e.event_id);return n?{...e,quoted_message_id:n}:e}captureCodexAuditOutput(e){if(e.codex_method!=="item/agentMessage/delta")return;const t=e.codex_payload?.params,s=typeof t?.phase=="string"?t.phase.trim().toLowerCase():"";if(s&&s!=="final_answer")return;const i=t?.delta;typeof i!="string"||!i||this.auditController.captureUnsequencedStreamChunk(e.event_id,i)}discardEventTrackingState(e){this.inflightEvents.delete(e),this.restartCount.delete(e),this.eventSessionIndex.delete(e),this.pendingStartedEventIds.delete(e),this.sendCtrl.discardEventState(e)}reliableFinalWiring(e,t){return async(s,i,n)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(s,i,n,t)}catch(o){throw p.error("bridge",`[${e}] sendFinalStreamChunkReliable ACK failed event=${s}: ${o}`),o}p.info("bridge",`[${e}] sendFinalStreamChunkReliable done event=${s}`)}}sendStreamChunkByRuntimeConfig(e,t,s,i,n,o,r){const a=this.indexEventSession(e,t)??t;this.auditController.captureStreamChunk(e,i,s),this.sendCtrl.sendStreamChunk(e,a,s,i,n,o,r),(s||n)&&this.conversationLog?.logOutbound?.(a,e,n?"stream_chunk_finish":"stream_chunk",s)}surfacedRunErrorEvents=new Set;sendRunErrorAsChunk(e,t,s){this.surfacedRunErrorEvents.has(e)||(this.surfacedRunErrorEvents.add(e),this.sendStreamChunkByRuntimeConfig(e,t,`
7
+ Error: ${u}`,1,!1)},sendAgentQuestionCard:(d,c,u)=>{this.sendGrixAgentQuestionCard(d,c,u)},sendPermissionCard:d=>{h.info("bridge","sendPermissionCard callback entered",{rawTransport:i,eventId:d.eventId,sessionId:d.sessionId,toolCallId:d.toolCallId,toolName:d.toolName,toolTitle:d.toolTitle});const c=d.toolInput&&d.toolTitle&&d.toolInput!==d.toolTitle?`${d.toolTitle}: ${d.toolInput}`:d.toolTitle||d.toolInput||d.toolName;if(i){this.sendAcpRawEventEnvelope(d.eventId,d.sessionId,{type:"permission_request",payload:{tool_call_id:d.toolCallId,tool_name:d.toolName,tool_title:d.toolTitle,...d.toolInput?{tool_input:d.toolInput}:{},options:d.options}}),h.info("bridge","sendPermissionCard: sent via rawEventEnvelope",{eventId:d.eventId,toolCallId:d.toolCallId});return}const u=`perm_${R()}`,g={event_id:d.eventId,session_id:d.sessionId,client_msg_id:u,msg_type:1,content:d.toolTitle?`Permission required: ${d.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:d.toolCallId,approvalSlug:d.toolName},grix:{execApproval:{approval_command_id:d.toolCallId,approval_type:"permission",command:c,host:"acp"}}},agent_api_origin:!0}};h.info("bridge","sendPermissionCard: about to invoke aibotHandle.sendMsg",{eventId:d.eventId,sessionId:d.sessionId,clientMsgId:u,toolCallId:d.toolCallId,contentLength:g.content.length});try{this.aibotHandle.sendMsg(g),h.info("bridge","sendPermissionCard: aibotHandle.sendMsg returned",{eventId:d.eventId,clientMsgId:u})}catch(p){h.error("bridge","sendPermissionCard: aibotHandle.sendMsg threw",{eventId:d.eventId,clientMsgId:u,error:p instanceof Error?p.message:String(p)})}},sendAuthNotification:(d,c)=>{d&&this.aibotHandle.sendMsg({session_id:d,msg_type:1,content:c,extra:{biz_card:{version:1,type:"agent_error",payload:{error:{name:"AuthRequired",message:c}}}}})},sendAgentMessage:(d,c)=>{d&&c&&this.aibotHandle.sendMsg({session_id:d,msg_type:1,content:c})},sendUpdateBindingCard:(d,c,u,g)=>{const p={...g??{}};if(!p.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const _=this.providerQuotaToRateLimits(this.cachedProviderQuota);_&&(p.rate_limits=_)}!p.provider_quota&&this.cachedProviderQuota?.success&&(p.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:d,worker_status:c,cwd:u,...Object.keys(p).length>0?{meta:p}:{}})},onSkillsUpdate:(d,c)=>{try{this.aibotHandle.sendSkillsUpdate({skills:X(d,w.skills),library_skills:this.buildLibrarySkillsReport(c)})}catch(u){}},onContextWindowUpdated:d=>{this.cachedAcpContextWindow=d,this.cachedAcpContextWindowSampledAtMs=Date.now();const c="usedPercentage"in d?d.usedPercentage.toFixed(1):(d.used/d.size*100).toFixed(1);h.info(this.name,`[acp] context_window updated: ${c}%`);const u=this.bindingStore.get(e);if(u?.cwd){const g="usedPercentage"in d?d.usedPercentage:Math.min(100,d.used/d.size*100),p={context_window:{..."usedPercentage"in d?{}:d,usedPercentage:g,remainingPercentage:100-g}};if((this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi")&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{}),p.provider_quota=this.cachedProviderQuota;const _=this.providerQuotaToRateLimits(this.cachedProviderQuota);_&&(p.rate_limits=_)}this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:u.cwd,meta:p})}},sendMcpFrame:d=>{this.aibotHandle.sendMcpFrame(e,d)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},n=e?this.bindingStore.get(e):void 0,t=e?this.auditController.getSession(e):void 0,s=this.config.aibot.clientType==="reasonix"&&t?Ei(this.name,e,t.auditId):void 0,o=this.globalConfigStore?.get(this.name),{initialModel:a,initialMode:l}=Wn({sessionBinding:n,globalDefaults:o,configInitialMode:this.config.acpInitialMode});return e&&a&&!n?.acpModelId&&this.bindingStore.setAcpModelId(e,a),e&&l&&!n?.acpModeId&&this.bindingStore.setAcpModeId(e,l),(a||l)&&h.info(this.name,`[toolbar] hydrate from binding: session=${e} model=${a??"<none>"} mode=${l??"<none>"}`),new S({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv()},r,{acpAuthMethod:this.config.acpAuthMethod,acpInitialMode:l,acpInitialModel:a,acpMcpTools:this.config.acpMcpTools,rawTransport:i,eventResultsPath:this.config.eventResultsPath,approvalMode:this.config.approvalMode,bindingStore:this.config.enableSessionBinding?this.bindingStore:void 0,aibotSessionId:e,autoInjectArgs:this.config.autoInjectArgs,nativeProviderScope:this.name,bridgeLog:this.config.logDir?new Pe(this.config.logDir,`${this.name}-${e}`):null,reasonixAuditTranscriptPath:s,agentType:this.config.aibot.clientType})}async connectAibot(){const i=await new q().connect(this.aibotConfig,{aborted:()=>this.stopped,signal:this.startupAbortController.signal,label:this.name,packetLog:this.packetLog,maxRetries:this.config.connectMaxRetries});if(this.stopped)throw i.disconnect(),new Error("connection aborted");this.aibotHandle=i;const r=this.aibotHandle.authAck;if(this.applyAgentProfile(r?.agent_name,r?.introduction,{source:"auth_ack",respawnOnChange:!1},r?.system_prompt),this.aibotHandle.onEvent(n=>{this.handleAibotEvent(n).catch(t=>{h.error(this.name,`handleAibotEvent failed: ${t}`),this.aibotHandle.sendEventAck({event_id:n.event_id,session_id:n.session_id,received_at:Date.now()});const s=t instanceof Error?t.message:String(t);if(/CWD must be|Bound directory does not exist|Bound path is not a directory/i.test(s)&&n.session_id){this.bindingStore.delete(n.session_id),this.sessionBindings.delete(n.session_id),this.sessionProviderHints.delete(n.session_id),this.sessionProviderQuotas.delete(n.session_id),this.sessionProviderMeta.delete(n.session_id);const a=this.pool.getSlot(n.session_id);a?.adapter instanceof S&&a.adapter.getSessionBindings().delete(n.session_id);const l=this.config.adapterType??"acp",d=this.resolveBindingChannelKey(l);this.aibotHandle.sendMsg({event_id:n.event_id,session_id:n.session_id,msg_type:1,content:s,extra:{channel_data:{[d]:{sessionBinding:{status:"missing",reason:"binding_stale",error_code:$.invalidCwd}}}},quoted_message_id:n.msg_id});return}this.aibotHandle.sendEventResult({event_id:n.event_id,status:"failed",msg:s,updated_at:Date.now()})})}),this.aibotHandle.onStop(n=>{try{this.handleAibotStop(n)}catch(t){h.error(this.name,`handleAibotStop failed: ${t}`)}}),this.aibotHandle.onAgentDeleted(n=>{h.warn(this.name,`agent deleted on platform (source=${n?.source??"unknown"}${n?.reason?` reason=${n.reason}`:""}), notifying manager to clean up`);try{this.agentDeletedHandler?.()}catch(t){h.error(this.name,`agentDeletedHandler failed: ${t}`)}}),this.aibotHandle.onShareSet(n=>{try{this.shareSetHandler?.(Array.isArray(n?.shared_to)?n.shared_to:[])}catch(t){h.error(this.name,`onShareSet failed: ${t}`)}}),this.aibotHandle.onProfilePush(n=>{try{this.applyAgentProfile(n?.agent_name,n?.introduction,{source:"profile_push",respawnOnChange:!0},n?.system_prompt)}catch(t){h.error(this.name,`onProfilePush failed: ${t}`)}}),this.aibotHandle.onSkillSync(n=>{if(!this.stopped)try{h.info(this.name,`skill_sync received owner=${n?.owner_id??""} name=${n?.name??""}`),this.skillSyncHandler?.()}catch(t){h.error(this.name,`onSkillSync failed: ${t}`)}}),this.aibotHandle.onRevoke(n=>{this.handleAibotRevoke(n).catch(t=>{h.error(this.name,`handleAibotRevoke failed: ${t}`)})}),this.aibotHandle.onLocalAction(n=>{this.handleAibotLocalAction(n).catch(t=>{h.error(this.name,`handleAibotLocalAction failed: ${t}`)})}),this.aibotHandle.onEventCancel(n=>{h.info(this.name,`recv event_cancel event_id=${n.event_id} session_id=${n.session_id}`),this.handleEventCancel(n).catch(t=>{h.error(this.name,`handleEventCancel failed: ${t}`)})}),this.aibotHandle.onMcpFrame((n,t)=>{const s=this.pool.getSlot(n)?.adapter;s?.deliverMcpFrameToAgent?s.deliverMcpFrameToAgent(t):h.warn(this.name,`mcp_frame: no adapter for session=${n}`)}),this.aibotHandle.onQueueClear(n=>{const t=this.pool.clearQueue(n.session_id);this.aibotHandle.sendQueueClearResult({session_id:n.session_id,canceled_event_ids:t}),this.pushQueueSnapshotForSession(n.session_id)}),typeof this.aibotHandle.onQueueReorder=="function"&&this.aibotHandle.onQueueReorder(n=>{const t=Array.isArray(n.ordered_event_ids)?n.ordered_event_ids.filter(o=>typeof o=="string"&&o.length>0):[],s=this.pool.reorderQueue(n.session_id,t);this.aibotHandle.sendQueueReorderResult({session_id:n.session_id,applied_event_ids:s}),this.pushQueueSnapshotForSession(n.session_id)}),typeof this.aibotHandle.onEventHold=="function"&&this.aibotHandle.onEventHold(n=>{const t=typeof n.session_id=="string"?n.session_id:"",s=typeof n.event_id=="string"?n.event_id:"",o=n.hold!==!1;if(h.info(this.name,`recv event_hold event_id=${s} session_id=${t} hold=${o} reason=${n.reason??""}`),!t||!s){this.aibotHandle.sendEventHoldResult({session_id:t,event_id:s,ok:!1,held:!1,error:"bad_request"});return}const a=typeof n.reason=="string"?n.reason:"",l=typeof n.ttl_ms=="number"?n.ttl_ms:void 0,d=this.pool.holdEvent(t,s,o,a,l),c=d==="ok";this.aibotHandle.sendEventHoldResult({session_id:t,event_id:s,ok:c,held:c?o:!1,...c?{}:{error:d}}),c&&this.pushQueueSnapshotForSession(t)}),typeof this.aibotHandle.onQueueEdit=="function"&&this.aibotHandle.onQueueEdit(n=>{const t=typeof n.session_id=="string"?n.session_id:"",s=typeof n.event_id=="string"?n.event_id:"";if(h.info(this.name,`recv queue_edit event_id=${s} session_id=${t}`),!t||!s){this.aibotHandle.sendQueueEditResult({session_id:t,event_id:s,ok:!1,error:"bad_request"});return}const o=typeof n.content=="string"?n.content:"",a=this.pool.editQueuedEvent(t,s,o),l=a==="ok";this.aibotHandle.sendQueueEditResult({session_id:t,event_id:s,ok:l,...l?{}:{error:a}}),l&&this.pushQueueSnapshotForSession(t)}),typeof this.aibotHandle.onQueueSnapshotQuery=="function"&&this.aibotHandle.onQueueSnapshotQuery(n=>{this.replyQueueSnapshotForSession(n.session_id)}),h.info(this.name,"Connected to aibot"),this.activeEventStore){const n=await this.activeEventStore.drain();if(n.length>0){h.warn(this.name,`Recovering ${n.length} stale event(s) from previous run`);for(const t of n)h.info(this.name,`Failing stale event on startup: ${t}`),this.aibotHandle.sendEventResult({event_id:t,status:"failed",msg:"process restarted, event lost",updated_at:Date.now()})}}this.pushQueueSnapshots(),this.relayStateSyncOnConnect(),this.aibotHandle.onReconnected(()=>{if(this.stopped)return;this.pushQueueSnapshots();const n=this.aibotHandle.authAck;this.applyAgentProfile(n?.agent_name,n?.introduction,{source:"reconnect",respawnOnChange:!0},n?.system_prompt),this.forceRefreshSkills(void 0,{force:!0}),this.skillSyncHandler?.(),this.relayStateSyncOnConnect()}),this.aibotHandle.onStreamRejected((n,t)=>{this.sendCtrl.markEventRejected(n)})}applyAgentProfile(e,i,r,n){const t=String(e??"").trim(),s=String(i??"").trim(),o=n===void 0?this.agentSystemPrompt:String(n),a=t!==this.agentProfile.agentName||s!==this.agentProfile.introduction||o!==this.agentSystemPrompt;this.agentProfile={agentName:t,introduction:s},this.agentSystemPrompt=o,t||s?h.info(this.name,`agent profile (${r.source}): GOT name="${t}" intro_len=${s.length} system_prompt_len=${o.length} changed=${a}`):h.warn(this.name,`agent profile (${r.source}): EMPTY \u2014 \u670D\u52A1\u7AEF\u672A\u4E0B\u53D1 agent_name/introduction\uFF08auth_ack \u5B57\u6BB5\u7F3A\u5931\u6216\u503C\u4E3A\u7A7A\uFF09`),a&&r.respawnOnChange&&this.applyProfileChangeToAdapters("agent_profile_changed")}applyProfileChangeToAdapters(e){if(!this.pool)return;const i=this.pool.getAllSlots();let r=0;for(const o of i)if(o.adapter.onAgentProfileChanged)try{o.adapter.onAgentProfileChanged(),r++}catch(a){h.warn(this.name,`onAgentProfileChanged failed for session=${o.sessionId}: ${a}`)}const n=i.filter(o=>o.adapter instanceof L),t=n.filter(o=>{if(o.state!=="ready")return!1;const a=o.adapter.getStatus();return!a.busy&&!a.backgroundBusy}),s=n.length-t.length;h.info(this.name,`${e}: notified ${r} adapter(s) via hook; respawning ${t.length} idle Claude slot(s), skipping ${s} busy`);for(const o of t)this.pool.removeSlot(o.sessionId).catch(a=>{h.warn(this.name,`removeSlot failed during ${e}: ${a}`)})}pushQueueSnapshots(){if(!(!this.config.eventQueue||!this.pool))for(const e of this.pool.getAllSlots())this.pushQueueSnapshotForSession(e.sessionId)}buildQueueSnapshotPayload(e){const i=this.pool?.getQueueSnapshot(e)??null,r=i?[...i.running]:[],n=i?i.running_items.map(s=>({event_id:s.event_id,...s.content_preview?{content_preview:s.content_preview}:{},...s.title?{title:s.title}:{},...s.summary?{summary:s.summary}:{},actions:[{type:"stop"}]})):[],t=i?i.queued.map(s=>({event_id:s.event_id,position:s.position,...s.content_preview?{content_preview:s.content_preview}:{},...typeof s.content=="string"?{content:s.content}:{},...s.title?{title:s.title}:{},...s.summary?{summary:s.summary}:{},held:s.held===!0,held_reason:s.held_reason??"",actions:[{type:"cancel"}]})):[];if(r.length===0&&this.selfDrivenSessions.has(e)&&this.pool?.getSlot(e)){const s=`selfdrive_${e}`,o=this.selfDrivenLabels.get(e)??"Background task in progress";r.push(s),n.push({event_id:s,content_preview:o,title:o,summary:o,actions:[]})}return{session_id:e,running:r,running_items:n,queued:t}}pushQueueSnapshotForSession(e){if(!this.config.eventQueue||!this.pool)return;const i=this.buildQueueSnapshotPayload(e);h.info(this.name,`[queue-debug] push snapshot session=${e} running=${i.running.length} queued=${i.queued.length} running_ids=[${i.running.join(",")}]`),this.aibotHandle.sendQueueSnapshot(i)}replyQueueSnapshotForSession(e){!this.config.eventQueue||!this.pool||this.aibotHandle.sendQueueSnapshot(this.buildQueueSnapshotPayload(e))}async platformInvoke(e,i,r){return e==="file_link"?jn(i):e==="file_upload"?this.uploadFileAndSendMedia(i):this.aibotHandle.agentInvoke(e,i,r)}invokeDshEventTool(e,i){const r=V(this.aibotHandle,e,i),n=r.content[0]?.text??"";if(r.isError)throw new Error(n||`grix event tool "${e}" failed`);try{return JSON.parse(n)}catch{return n}}async uploadFileAndSendMedia(e){const i=String(e.file_path??"").trim(),r=String(e.session_id??"").trim(),n=String(e.caption??"").trim(),t=String(e.reply_to_message_id??"").trim();if(!i)throw new Error("file_path is required");if(!r)throw new Error("session_id is required");const s=await Kn({wsURL:this.config.aibot.url,apiKey:this.config.aibot.apiKey,sessionID:r,filePath:i}),o=await this.aibotHandle.sendMedia({session_id:r,msg_type:2,content:n||`[${s.attachment_type}]`,client_msg_id:`file_upload_${R()}`,...t?{quoted_message_id:t}:{},extra:s.extra});if(o.cmd!=="send_ack"){const l=o.payload??{},d=String(l.msg??o.cmd);throw new Error(`media message send failed: ${d}`)}const a=o.payload??{};return{ok:!0,file_name:s.file_name,attachment_type:s.attachment_type,access_url:s.access_url,message_id:a.msg_id!=null?String(a.msg_id):null}}sendReplyByRuntimeConfig(e,i,r,n,t){const s=this.indexEventSession(e,i)??i;this.auditController.captureReply(e,r),this.sendCtrl.sendReply(e,s,r,n,t),r&&this.conversationLog?.logOutbound?.(s,e,"reply",r)}stampCodexEventQuote(e){if(e.quoted_message_id!=null){if(e.quoted_message_id)return e;const{quoted_message_id:s,...o}=e;return o}const i=e;if(i.codex_method!=="item/agentMessage/delta")return e;const n=i.codex_payload?.params?.phase;if(typeof n=="string"&&n.trim()&&n.trim().toLowerCase()!=="final_answer")return e;const t=this.sendCtrl.getDefaultQuotedMessageId(e.event_id);return t?{...e,quoted_message_id:t}:e}captureCodexAuditOutput(e){if(e.codex_method!=="item/agentMessage/delta")return;const i=e.codex_payload?.params,r=typeof i?.phase=="string"?i.phase.trim().toLowerCase():"";if(r&&r!=="final_answer")return;const n=i?.delta;typeof n!="string"||!n||this.auditController.captureUnsequencedStreamChunk(e.event_id,n)}discardEventTrackingState(e){this.inflightEvents.delete(e),this.restartCount.delete(e),this.eventSessionIndex.delete(e),this.pendingStartedEventIds.delete(e),this.sendCtrl.discardEventState(e)}reliableFinalWiring(e,i){return async(r,n,t)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(r,n,t,i)}catch(s){throw h.error("bridge",`[${e}] sendFinalStreamChunkReliable ACK failed event=${r}: ${s}`),s}h.info("bridge",`[${e}] sendFinalStreamChunkReliable done event=${r}`)}}sendStreamChunkByRuntimeConfig(e,i,r,n,t,s,o){const a=this.indexEventSession(e,i)??i;this.auditController.captureStreamChunk(e,n,r),this.sendCtrl.sendStreamChunk(e,a,r,n,t,s,o),(r||t)&&this.conversationLog?.logOutbound?.(a,e,t?"stream_chunk_finish":"stream_chunk",r)}surfacedRunErrorEvents=new Set;sendRunErrorAsChunk(e,i,r){this.surfacedRunErrorEvents.has(e)||(this.surfacedRunErrorEvents.add(e),this.sendStreamChunkByRuntimeConfig(e,i,`
8
8
 
9
- Error: ${s}`,1,!1))}sendEventResultWithCleanup(e,t,s,i,n=!1){const o=this.eventSessionIndex.get(e);n&&this.surfacedRunErrorEvents.add(e),t==="failed"&&o&&s?.trim()&&this.sendRunErrorAsChunk(e,o,s),this.auditController.markResponded(e,t,s),this.sendCtrl.sendEventResult(e,t,s,i),o&&(this.pool.eventComplete(e,o)===!1&&p.error(this.name,`Event terminal result could not release queue slot event=${e} session=${o} status=${t}`),this.pushQueueSnapshotForSession(o),this.conversationLog?.logResult?.(o,e,t,s),this.eventSessionIndex.delete(e)),this.inflightEvents.delete(e),this.restartCount.delete(e),this.surfacedRunErrorEvents.delete(e),this.pendingStartedEventIds.delete(e),this.pendingEvents.remove(e).catch(r=>{p.warn(this.name,`Failed to remove terminal event from pending store event=${e}: ${r instanceof Error?r.message:String(r)}`)}),t==="responded"&&(this.config.adapterType??"acp")!=="agy"&&(this.cachedProviderQuotaSampledAtMs=null,this.refreshAndPushProviderQuota(!0).catch(()=>{}))}async handleSessionInternalError(e){const{eventId:t,sessionId:s,errorMsg:i}=e;if(this.stopped)return;const n=this.inflightEvents.get(t);if(!n){p.warn(this.name,`[recovery] no inflight event for internalError event=${t} session=${s}; surface failure directly`),this.sendRunErrorAsChunk(t,s,i),this.sendEventResultWithCleanup(t,"failed",i,"agent_stop_failure");return}const o=(this.restartCount.get(t)??0)+1;this.restartCount.set(t,o);const r=this.config.adapterType??"acp";if(o>q){p.error(this.name,`[recovery] adapter=${r} session=${s} event=${t} restart=${o}/${q} outcome=give-up err=${i}`),this.sendRunErrorAsChunk(t,s,i),this.sendEventResultWithCleanup(t,"failed",i,"agent_stop_failure");return}p.info(this.name,`[recovery] adapter=${r} session=${s} event=${t} restart=${o}/${q} outcome=restarting err=${i}`);const a=this.pool.drainQueuedForSession(s);a.length>0&&p.info(this.name,`[recovery] session=${s} preserved ${a.length} queued sibling event(s) across restart`);try{await this.pool.removeSlot(s)}catch(l){p.warn(this.name,`[recovery] removeSlot failed session=${s}: ${l instanceof Error?l.message:String(l)}`)}if(this.stopped)return;const c=e.replayOriginalContent?n.content:this.resolveRecoveryPrompt(r,n),d={...n,content:c};try{await this.pool.deliverInboundEvent(d)}catch(l){p.error(this.name,`[recovery] redeliver failed event=${t} session=${s}: ${l instanceof Error?l.message:String(l)}`),this.sendEventResultWithCleanup(t,"failed",l instanceof Error?l.message:String(l));return}for(const l of a){if(this.stopped)break;try{await this.pool.deliverInboundEvent(l)}catch(h){p.error(this.name,`[recovery] sibling redeliver failed event=${l.event_id} session=${s}: ${h instanceof Error?h.message:String(h)}`),this.sendEventResultWithCleanup(l.event_id,"failed",h instanceof Error?h.message:String(h))}}}resolveRecoveryPrompt(e,t){return e==="acp"?"continue":t.content}sendThinkingByRuntimeConfig(e,t,s){this.sendCtrl.sendThinking(e,t,s)}bufferStreamChunk(e,t,s,i,n){this.auditController.captureUnsequencedStreamChunk(e,s),this.sendCtrl.bufferOnly(e,t,s,i,n)}flushBufferedStreamText(e){}resolveEventRuntimeConfig(e){return this.sendCtrl.resolveEventRuntimeConfig(e)}captureEventRuntimeConfig(e){this.sendCtrl.captureEventRuntimeConfig(e),this.indexEventSession(e.event_id,e.session_id),this.auditController.markRecording(e.event_id),e.event_id&&!this.inflightEvents.has(e.event_id)&&this.inflightEvents.set(e.event_id,e)}async replayPendingEventsOnStartup(){const e=await this.pendingEvents.loadForReplay();if(e.length===0)return;const t=new Set(e.map(i=>i.event.event_id).filter(Boolean)),s=[];p.warn(this.name,`Replaying ${e.length} pending event(s) from previous run`);for(const i of e){if(this.stopped)break;const n=i.event;this.pendingEvents.startReplay(i);try{if(i.kind==="deferred"){const o=this.bindingStore.get(i.sessionId);o?.cwd?(await this.prepareBoundDeferredReplay(i,o.cwd),await this.deliverPendingReplayEvent(n),this.pendingStartedEventIds.has(n.event_id)||s.push(i)):(this.restorePendingReplayAuditTurn(n),this.deferredMgr.defer(i.channel,i.sessionId,n),s.push(i))}else await this.deliverPendingReplayEvent(n),this.pendingStartedEventIds.has(n.event_id)||s.push(i)}catch(o){const r=o instanceof Error?o.message:String(o);p.error(this.name,`Pending event replay failed event=${n.event_id}: ${r}`),this.sendEventResultWithCleanup(n.event_id,"failed",r),this.pendingEvents.markCanceled(n.event_id),await this.pendingEvents.remove(n.event_id).catch(()=>{})}finally{this.pendingEvents.finishReplay(i),await this.pendingEvents.checkpointReplay(t,[...s,...this.pendingEvents.replaySnapshot()])}if(this.stopped)break}this.stopped||(this.pendingEvents.finishAllReplay(),await this.pendingEvents.checkpointReplay(t,s))}failEventIfLifecycleDraining(e,t="connector is draining for restart; control command was not executed"){return this.lifecycleBarrier.isClosed()?(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"connector_lifecycle_draining",msg:t,updated_at:Date.now()}),!0):!1}sendCanceledPendingEventResult(e,t){this.restorePendingReplayAuditTurn(e),this.captureEventRuntimeConfig(e),this.sendEventResultWithCleanup(e.event_id,"canceled",t),this.auditController.markAdapterClosed(e.event_id,{adapterNotStarted:!0})}async deliverPendingReplayEvent(e){this.restorePendingReplayAuditTurn(e),this.captureEventRuntimeConfig(e),await this.pool.deliverInboundEvent(e)}async prepareBoundDeferredReplay(e,t){this.sessionBindings.set(e.sessionId,t),e.channel==="acp"?await this.bindSessionForPool(e.sessionId,t):e.channel==="opencode"&&await this.syncOpenCodeBinding(e.sessionId,t)}restorePendingReplayAuditTurn(e){const t=e.audit;if(!t?.enabled||!t.auditId||!t.capture||!t.profile||!t.scope)return;const s=Ri({enabled:!0,scope:t.scope,profile:t.profile,capture:t.capture,...t.retentionDays===void 0?{}:{retentionDays:t.retentionDays}});if(!s.enabled)return;const i=Object.freeze({auditId:t.auditId,businessSessionId:e.session_id,provider:this.resolveAuditProvider(),options:s,createdAt:new Date().toISOString()}),n=this.auditController.startTurn({session:i,eventId:e.event_id,userInput:e.content??"",...e.msg_id===void 0?{}:{originMsgId:e.msg_id},...Number.isFinite(Number(e.created_at))&&Number(e.created_at)>0?{startedAt:new Date(Number(e.created_at)).toISOString()}:{},boundary:{adapterType:this.config.adapterType??"acp"}});n&&(e.audit={...t,auditId:n.auditId,turnId:n.turnId,profile:i.options.profile,capture:{...i.options.capture},rawProviderBody:i.options.capture.rawProviderBody})}indexEventSession(e,t){if(!e||!t)return;const s=this.eventSessionIndex.get(e);return s?(s!==t&&p.warn(this.name,`Ignoring event session mismatch event=${e} indexed=${s} supplied=${t}`),s):(this.eventSessionIndex.set(e,t),t)}shouldDropToolDisplayEvent(e){return this.sendCtrl.shouldDropToolDisplayEvent(e)}shouldDropThinkingDisplayEvent(e){return this.sendCtrl.shouldDropThinkingDisplayEvent(e)}shouldDropCodexDisplayEvent(e,t){return this.sendCtrl.shouldDropCodexDisplayEvent(e,t)}logCodexEventToConversation(e){if(!this.conversationLog||e.codex_method!=="item/agentMessage/delta")return;const s=e.codex_payload?.params?.delta;if(!s)return;const i=this.eventSessionIndex.get(e.event_id)??e.session_id;this.conversationLog.append(i,{ts:Date.now(),dir:"outbound",event_id:e.event_id,kind:"codex_delta",text_len:s.length,content:s})}isAcpRawTransportEnabled(){return(this.config.adapterOptions??{}).raw_transport===!0}shouldDropAcpRawDisplayEvent(e,t){return this.sendCtrl.shouldDropAcpRawDisplayEvent(e,t)}sendAcpRawEventEnvelope(e,t,s){this.shouldDropAcpRawDisplayEvent(e,s.type)||this.deliverRawEventEnvelope(e,t,s,"acp",this.buildAcpRawEventFallbackText(s))}buildAcpRawEventFallbackText(e){const t=String(e.type??"").trim();if(!t)return"[acp] event";switch(t){case"permission_request":return`Permission required: ${String(e.payload?.tool_title??e.payload?.tool_name??"permission request")}`;case"tool_use":return`[tool] ${String(e.payload?.tool_name??"tool")}`;case"tool_result":return"[tool result]";case"thinking":return"[thinking]";case"error":return`[error] ${String(e.payload?.message??"agent error")}`;case"result":return"[result]";default:return`[acp] ${t}`}}rawDetailSeq=0;deliverRawEventEnvelope(e,t,s,i,n){const o=fi({envelope:s,fallbackText:n,channelKey:i,allocateRefId:()=>`${e}_rawd_${++this.rawDetailSeq}`}),r=()=>{this.aibotHandle.sendMsg({event_id:e,session_id:t,msg_type:1,content:o.fallbackText,extra:{channel_data:{[i]:{raw_event:o.envelope}},agent_api_origin:!0}})};if(!o.sharded){r();return}p.info("bridge",`${i} raw_event oversized, sharded delivery: event=${e} fields=${o.oversizedFields.map(a=>a.field).join(",")}`),(async()=>{for(const a of o.oversizedFields)await this.sendCtrl.deliverAuxiliaryLargeText(e,t,mi({envelopeType:s.type,field:a.field,fullText:a.fullText}),a.refClientMsgId);r()})().catch(a=>{p.warn("bridge",`${i} raw_event sharded delivery failed event=${e}: ${a}`)})}buildCursorRawEventFallbackText(e){const t=String(e?.type??"").trim(),s=e?.payload&&typeof e.payload=="object"?e.payload:{};switch(t){case"permission_request":return`Permission required: ${String(s.tool_title??s.tool_name??"permission request")}`;case"tool_use":case"tool_call":case"tool_execution_start":return`[tool] ${String(s.tool_name??s.toolName??"tool")}`;case"tool_result":case"tool_execution_end":case"tool_execution_update":return"[tool result]";case"error":return`[error] ${String(s.message??"agent error")}`;default:return t?`[cursor] ${t}`:"[cursor] event"}}sendToolExecutionCard(e,t,s,i){this.sendCtrl.sendToolExecutionCard(e,t,s,i)}sendGrixApprovalCard(e,t){this.aibotHandle.sendMsg({event_id:e.eventId,session_id:e.sessionId,client_msg_id:`perm_${B()}`,msg_type:1,content:e.toolTitle?`Permission required: ${e.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:e.approvalId,approvalSlug:e.toolName},grix:{execApproval:{approval_command_id:e.approvalId,command:e.toolTitle||e.toolName,host:t}}},agent_api_origin:!0}})}sendGrixAgentQuestionCard(e,t,s){const i=s.questions.map(o=>o.header).join(", "),n=X(`[Agent Question] ${s.request_id}`,"agent_question",s);this.aibotHandle.sendText({event_id:e,session_id:t,content:n,msg_type:1,extra:{card_type:"agent_question",summary_text:i}})}async handleAgentQuestionReplyEvent(e){const t=Kn(String(e.content??""));if(!t)return!1;this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const i=this.pool.getSlot(e.session_id)?.adapter,n=i instanceof y?"acp":i instanceof F?"opencode":this.config.adapterType??"unknown",o=i instanceof F?i.handleQuestionReplyEvent(t):i instanceof y?await i.handleQuestionReplyEvent(t):{delivered:!1,errorCode:"interaction_request_not_pending",errorMsg:"The question is no longer pending; the reply was not delivered."};return o.delivered?(p.info(this.name,`[${n}] question reply delivered event=${e.event_id} session=${e.session_id} request=${t.request_id}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()})):(p.warn(this.name,`[${n}] question reply rejected event=${e.event_id} session=${e.session_id} request=${t.request_id} code=${o.errorCode??"interaction_reply_failed"}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:o.errorCode??"interaction_reply_failed",msg:o.errorMsg??"The question reply was not delivered.",updated_at:Date.now()})),!0}async handleExecApprovalResolutionEvent(e){const t=jn(String(e.content??""));if(!t)return!1;this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const i=this.pool.getSlot(e.session_id)?.adapter,n=t.params,o=String(n.tool_call_id??n.approval_command_id??n.approval_id??n.exec_context_id??""),r=i?.handleExecApprovalEvent?await i.handleExecApprovalEvent({...n,event_id:e.event_id,session_id:e.session_id}):{delivered:!1,errorCode:"approval_not_supported",errorMsg:"The current adapter does not support exec approval resolution events."};return r.delivered?(p.info(this.name,`[${this.config.adapterType??"unknown"}] exec approval resolution delivered event=${e.event_id} session=${e.session_id} approval=${o||"-"}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()})):(p.warn(this.name,`[${this.config.adapterType??"unknown"}] exec approval resolution rejected event=${e.event_id} session=${e.session_id} approval=${o||"-"} code=${r.errorCode}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:r.errorCode,msg:r.errorMsg,updated_at:Date.now()})),!0}async handleAibotEvent(e){if(this.relayEnvStale&&!this.hasPendingWork()&&await this.recycleAdaptersForRelayChange(),this.stopped){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:"agent shutting down",updated_at:Date.now()});return}this.logInboundConversation(e);const t=this.config.adapterType??"acp",s=Un(e);let i;if(s&&(i=this.lifecycleBarrier.tryEnter()??void 0,!i)){this.failEventIfLifecycleDraining(e);return}try{if(await this.handleCliInstallQuestionReply(e)||(t==="opencode"||t==="acp")&&await this.handleAgentQuestionReplyEvent(e)||await this.handleExecApprovalResolutionEvent(e))return;const n=li(e.extra);if(n.error){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"connector_config_invalid",msg:n.error,updated_at:Date.now()});return}const o=n.patch,r=V(e.extra);if((r.state!=="absent"||r.error)&&p.info(this.name,`[audit-marker] event=${e.event_id} session=${e.session_id} msg=${e.msg_id??""} state=${r.state??"error"} scope=${r.options?.enabled?r.options.scope:""} error=${r.error??""}`),r.error){if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"audit_config_invalid",msg:r.error,updated_at:Date.now()}),(()=>{try{if(!e.extra||typeof e.extra!="object")return!1;const h=e.extra,g=h.extra,u=h.audit??(g&&typeof g=="object"?g.audit:void 0);return!u||typeof u!="object"?!1:u.scope==="turn"}catch{return!1}})())try{this.aibotHandle.sendAuditState($({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:"audit_config_invalid",errorMessage:r.error},Date.now()))}catch{}return}if(r.state==="enabled"&&t!=="claude"&&t!=="codex"&&t!=="cursor"&&t!=="opencode"&&t!=="pi"&&t!=="codewhale"&&t!=="deepseek-harness"&&t!=="agy"&&t!=="acp"){if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"audit_provider_unsupported",msg:`Audit replay is not supported for adapter: ${t}`,updated_at:Date.now()}),r.options?.enabled&&r.options.scope==="turn")try{this.aibotHandle.sendAuditState($({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:"audit_provider_unsupported",errorMessage:`Audit replay is not supported for adapter: ${t}`},Date.now()))}catch{}return}if(s){if(r.state!=="absent"||s.verb===S.open)try{this.auditController.resolveSession({sessionId:e.session_id,provider:this.resolveAuditProvider(),extra:e.extra})}catch(l){this.sendAuditConfigurationError(e,l);return}if(s.verb===S.exec){await this.handleSessionControlCommand(s,e);return}if(s.verb===S.listSessions){await this.handleListSessionsTextCommand(e);return}if(s.verb===S.unbind){await this.handleUnbindTextCommand(e);return}if(t==="claude"){await this.handleSessionControlCommand(s,e);return}if(t==="codex"&&s.verb===S.open){await this.handleCodexSessionControlOpen(s,e);return}if(t==="pi"&&s.verb===S.open){await this.handlePiSessionControlOpen(s,e);return}if(t==="pi"&&s.verb===S.restart){await this.handlePiSessionControlRestart(e);return}if((t==="openhuman"||t==="opencode")&&s.verb===S.open){await this.handleOpenHumanSessionControlOpen(s,e);return}if(t==="codewhale"&&s.verb===S.open){await this.handleCodeWhaleSessionControlOpen(s,e);return}if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),s.verb===S.open){const l=s.args.trim();if(!l){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:E.cwdRequired,msg:"cwd is required",updated_at:Date.now()});return}try{const h=T.resolve(l);if(!(await Q(h)).isDirectory()){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:E.invalidCwd,msg:`Path is not a directory: ${h}`,updated_at:Date.now()});return}}catch(h){const g=String(h?.code??""),u=g==="ENOENT"?`Directory does not exist: ${T.resolve(l)}`:g==="EACCES"||g==="EPERM"?"Directory is not accessible":`Invalid path: ${l}`;this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:E.invalidCwd,msg:u,updated_at:Date.now()});return}}if(s.verb===S.open){const l=this.bindingStore.get(e.session_id);if(l?.cwd)try{await Q(l.cwd)}catch{p.info("bridge",`Stale binding detected for session ${e.session_id}: ${l.cwd} no longer exists, clearing`),this.bindingStore.delete(e.session_id),this.sessionBindings.delete(e.session_id),this.sessionProviderHints.delete(e.session_id),this.sessionProviderQuotas.delete(e.session_id),this.sessionProviderMeta.delete(e.session_id);const h=this.pool.getSlot(e.session_id);h?.adapter instanceof y&&h.adapter.getSessionBindings().delete(e.session_id)}}if(await this.handleSessionControlForPool(s,e),t==="acp"&&s.verb===S.stop){const h=this.bindingStore.get(e.session_id)?.cwd??"";await this.pool.removeSlot(e.session_id).catch(()=>{}),this.sessionBindings.delete(e.session_id),this.sessionProviderHints.delete(e.session_id),this.sessionProviderQuotas.delete(e.session_id),this.sessionProviderMeta.delete(e.session_id),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:`Session worker stopped for ${h}`,updated_at:Date.now()});return}if(Nn(s,e,this.sessionControlCtx(e.session_id),{...this.sessionControlSenders(e.session_id),sendEventAck:()=>{}}),s.verb===S.open&&(await this.deferredMgr.release(e.session_id,this.deferredCallbacks()),t==="agy")){const l=this.bindingStore.get(e.session_id)?.cwd??"";l&&(this.sendAgyBindingCard(e.session_id,l),this.refreshAndPushAgyQuota(e.session_id,!0))}return}if(e.mirror_mode==="record_only"){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()});return}if(this.isStaleEvent(e)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"event_stale",msg:"event is stale and will not be processed",updated_at:Date.now()});return}let a;try{a=this.auditController.resolveSession({sessionId:e.session_id,provider:this.resolveAuditProvider(),extra:e.extra,eventId:e.event_id}).session}catch(l){this.sendAuditConfigurationError(e,l);return}if(ee.has(t)&&await this.ensureDefaultBindingForWorkspaceFreeClient(e.session_id,t),ee.has(t)&&!this.bindingStore.get(e.session_id)?.cwd){const h=t,g=this.prepareAuditedInboundEvent(e,o,a);p.info(this.name,`[${h}] binding missing session_id=${e.session_id} event_id=${e.event_id}`);try{const f=await this.pendingEvents.append({kind:"deferred",channel:h,sessionId:String(e.session_id??"").trim(),event:g});if(this.lifecycleBarrier.isClosed()&&!f)throw new Error("pending event store unavailable during lifecycle drain")}catch(f){const b=f instanceof Error?f.message:String(f);this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.auditController.closeWithoutAdapter(e.event_id,"failed",b,{deliveryFailed:!0}),this.discardEventTrackingState(e.event_id),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:b,updated_at:Date.now()});return}if(this.pendingEvents.isCanceled(e.event_id)){await this.pendingEvents.remove(e.event_id),this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.sendCanceledPendingEventResult(g,"canceled");return}this.deferredMgr.defer(h,String(e.session_id??"").trim(),g);const u=this.resolveBindingChannelKey(t);this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendMsg({event_id:e.event_id,session_id:e.session_id,msg_type:1,content:"Session binding missing.",extra:{channel_data:{[u]:{sessionBinding:{status:"missing",reason:"binding_missing",error_code:E.bindingMissing}}}},quoted_message_id:e.msg_id});return}if((this.config.adapterType??"acp")==="acp"){const h=String(e.content??"").trim().match(/^\/(\S+)\s*(.*)/);if(h){const[,g,u]=h,b=this.pool.getSlot(e.session_id)?.adapter;if(b?.execCommand&&(b.getSupportedCommands?.()??[]).some(m=>m.name===g||m.name===`/${g}`)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});try{const m=await b.execCommand(g,u.trim(),e.session_id);m.status==="options"&&m.data&&this.handleExecCommandOptions(e.session_id,g,m.data),this.aibotHandle.sendEventResult({event_id:e.event_id,status:m.status==="failed"?"failed":"responded",msg:m.message,updated_at:Date.now()})}catch(m){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:m instanceof Error?m.message:String(m),updated_at:Date.now()})}return}}}if(t==="codex"&&K(a?.options)){const l=this.pool.getSlot(e.session_id);if(l?.adapter instanceof W&&!l.adapter.hasRawApiCaptureRelay()){const h=l.eventQueue.snapshot(e.session_id);h.running.length===0&&h.queued.length===0?(p.info(this.name,`[audit-raw-capture] recreating idle Codex adapter before event=${e.event_id} session=${e.session_id}`),await this.pool.removeSlot(e.session_id)):p.warn(this.name,`[audit-raw-capture] Codex adapter lacks relay but is not idle event=${e.event_id} session=${e.session_id} running=${h.running.length} queued=${h.queued.length}`)}}const d=this.prepareAuditedInboundEvent(e,o,a);try{const l=await this.pendingEvents.append({kind:"queued",event:d});if(this.pendingEvents.isCanceled(e.event_id)){await this.pendingEvents.remove(e.event_id),this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.sendCanceledPendingEventResult(d,"canceled");return}if(this.lifecycleBarrier.isClosed()){if(!l)throw new Error("pending event store unavailable during lifecycle drain");this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),p.info(this.name,`Persisted inbound event during lifecycle drain: ${e.event_id}`);return}this.captureEventRuntimeConfig(d),await this.pool.deliverInboundEvent(d)}catch(l){await this.pendingEvents.remove(e.event_id).catch(h=>{p.warn(this.name,`Failed to remove undelivered pending event=${e.event_id}: ${h instanceof Error?h.message:String(h)}`)}),this.failUndeliveredInboundEvent(e,l)}}finally{i?.()}}failUndeliveredInboundEvent(e,t){const s=t instanceof Error?t.message:String(t);this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.auditController.closeWithoutAdapter(e.event_id,"failed",s,{deliveryFailed:!0}),this.discardEventTrackingState(e.event_id),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:s,updated_at:Date.now()})}handleCodexSessionControlOpen(e,t){return xt(this,e,t)}handleSessionControlForPool(e,t){return Dt(this,e,t)}handleSessionControlLocalActionForPool(e){return Mt(this,e)}handleCodexSessionControlLocalActionOpen(e){return Ht(this,e)}handleCursorSessionControlLocalActionOpen(e){return Lt(this,e)}handlePiSessionControlOpen(e,t){return $t(this,e,t)}handlePiSessionControlRestart(e){return It(this,e)}handlePiSessionControlRestartLocalAction(e){return Qt(this,e)}syncOpenCodeBinding(e,t){return Ot(this,e,t)}isWorkspaceFreeClient(){return Bt(this)}ensureDefaultBindingForWorkspaceFreeClient(e,t){return Ft(this,e,t)}bindSessionForPool(e,t){return qt(this,e,t)}deferredCallbacks(){return Ut(this)}handleOpenHumanSessionControlOpen(e,t){return Nt(this,e,t)}handleCodeWhaleSessionControlOpen(e,t){return Wt(this,e,t)}handleCodeWhaleSessionControlLocalActionOpen(e){return Gt(this,e)}handleDeepSeekSessionControlLocalActionOpen(e){return jt(this,e)}normalizeClaudeModeId(e){return dn(this,e)}handleExecCommandOptions(e,t,s){ln(this,e,t,s)}resolveSessionModelId(e){return cn(this,e)}resolveSessionModeId(e){return hn(this,e)}resolveCursorSessionModeId(e){return un(this,e)}resolveClaudeSessionEffort(e){return pn(this,e)}resolveClaudeSessionModeId(e){return gn(this,e)}currentClaudeModeId(e){return fn(this,e)}resolveCodexSessionModelId(e){return mn(this,e)}resolveCodexNewSessionGlobalDefault(e,t,s){return vn(this,e,t,s)}pinCodexGlobalDefault(e,t){return _n(this,e,t)}buildCursorToolbarMeta(e){return Sn(this,e)}buildAgyToolbarMeta(e,t){return bn(this,e,t)}buildAgyQuotaMeta(e){return Cn(this,e)}sendAgyBindingCard(e,t,s){return wn(this,e,t,s)}refreshAndPushAgyQuota(e,t=!1){return An(this,e,t)}handleAgySetModel(e,t){return En(this,e,t)}buildClaudeToolbarMeta(e){return kn(this,e)}providerQuotaToCodexRateLimits(e){return pi(e,this.cachedProviderQuotaSampledAtMs??Date.now())}providerQuotaToRateLimits(e){return ui(e,this.cachedProviderQuotaSampledAtMs??Date.now())}async resolveCwdForBinding(e){const t=String(e??"").trim();if(process.platform!=="win32"&&(/^[a-zA-Z]:[\\/]/.test(t)||/^\\\\/.test(t))){const n=new Error(`Specified path is not valid on this host: ${t}`);throw n.cwdErrorCode=E.invalidCwd,n}const s=T.resolve(t);let i;try{i=await Q(s)}catch(n){const o=String(n?.code??"");if(o==="ENOENT"){const r=new Error(`Specified path does not exist: ${s}`);throw r.cwdErrorCode=E.invalidCwd,r}if(o==="EACCES"||o==="EPERM"){const r=new Error("Specified path is not accessible.");throw r.cwdErrorCode=E.invalidCwd,r}throw n}if(!i.isDirectory()){const n=new Error("Specified path is not a directory.");throw n.cwdErrorCode=E.invalidCwd,n}try{return await te(s)}catch{return s}}failSessionOpen(e,t){const{code:s,msg:i}=Jn(e);return this.maybeOfferCliInstall({sessionId:t.sessionId,eventId:t.eventId,quotedMessageId:t.quotedMessageId,cwd:t.cwd,err:e}),t.send?.(s,i),{code:s,msg:i}}maybeOfferCliInstall(e){ot(this,e)}handleCliInstallQuestionReply(e){return rt(this,e)}handleCliInstallInteractionReply(e){return at(this,e)}runConfirmedCliInstall(e,t){return dt(this,e,t)}getClaudeWorkerStatus(e){const t=this.pool.getSlot(e);return t?t.state==="starting"?"starting":t.state==="stopped"?"stopped":t.adapter.getStatus().busy?"busy":"ready":"stopped"}refreshClaudeWorkerStatusCard(e,t){const s=this.getClaudeWorkerStatus(e);return this.claudeWorkerStatus.set(e,s),this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:s,cwd:t,meta:this.buildClaudeToolbarMeta(e)}),s}handleSkillDeleteLocalAction(e){return Jt(this,e)}handleSkillUploadLocalAction(e){return Yt(this,e)}handleSkillEnableLocalAction(e){return Xt(this,e)}handleSkillRefreshLocalAction(e){Vt(this,e)}handleSkillDisableLocalAction(e){return Zt(this,e)}computeSkillReport(e){return en(this,e)}reportSessionSkills(e){tn(this,e)}skillsSyncGroupKey(){return nn(this)}forceRefreshSkills(e,t){return sn(this,e,t)}adoptSkillsWireHashFromDisk(){on(this)}buildLibrarySkillsReport(e){return rn(this,e)}skillLookupEnv(){return an(this)}async ensureSlotStarted(e,t=6e4){const s=await this.pool.getOrCreateSlot(e);if(!s)throw new Error("Failed to allocate session slot");s.startPromise&&(p.info(this.name,`ensureSlotStarted: awaiting startPromise for session=${e}`),await Promise.race([s.startPromise,new Promise((i,n)=>setTimeout(()=>n(new Error(`ensureSlotStarted timeout (${t}ms) session=${e}`)),t))]),p.info(this.name,`ensureSlotStarted: startPromise resolved for session=${e}`))}resolveOrphanTitle(e){if(e){if(this.reasonixTitleScan){const t=Ie(e);if(!t)return;const s=this.reasonixTitleScan.get().filter(i=>i.stamp===t);return s.length===1?s[0].title:void 0}if((this.config.adapterType??"acp")==="cursor")return this.sessionScanCache.get().find(s=>s.sessionId===e)?.title}}resolveAgentSessionId(e){switch(this.config.adapterType??"acp"){case"claude":return e.claudeSessionId;case"codex":return e.codexThreadId;case"pi":return e.piSessionPath;case"codewhale":return e.codewhaleThreadId;case"agy":return e.agyConversationId;case"deepseek-harness":return e.dshProfileSessionId??e.acpSessionId;default:return e.acpSessionId}}providerKeyForAdapter(){const e=this.config.adapterType??"acp";switch(e){case"claude":case"codex":case"pi":case"codewhale":case"deepseek-harness":return e;default:return"acp"}}setResolvedAgentSessionId(e,t){const s=String(e??"").trim(),i=String(t??"").trim();if(!s||!i)return;switch(this.config.adapterType??"acp"){case"claude":this.bindingStore.setClaudeSessionId(s,i);break;case"codex":this.bindingStore.setCodexThreadId(s,i);break;case"pi":this.bindingStore.setPiSessionPath(s,i);break;case"codewhale":this.bindingStore.setCodeWhaleThreadId(s,i);break;case"agy":this.bindingStore.setAgyConversationId(s,i);break;default:this.bindingStore.setAcpSessionId(s,i);break}this.sessionScanCache.invalidate()}normalizePathForCompare(e){const t=String(e??"").trim();if(!t)return"";const s=T.resolve(t);return process.platform==="win32"?s.toLowerCase():s}ensureImportedAgentSession(e,t){const s=String(e??"").trim();if(!s)return;const i=this.normalizePathForCompare(t);let n="";const o=this.config.adapterType??"acp";if(o==="codex"?n=this.sessionScanCache.get().find(c=>c.threadId===s)?.cwd??"":o==="claude"?n=this.sessionScanCache.get().find(c=>c.sessionId===s)?.cwd??"":o==="cursor"?n=this.sessionScanCache.get().find(c=>c.sessionId===s)?.cwd??"":o==="acp"?n=this.sessionScanCache.get().find(c=>c.sessionId===s)?.cwd??"":o==="deepseek-harness"&&(n=this.sessionScanCache.get().find(c=>c.sessionId===s)?.cwd??""),!n){for(const[,a]of this.bindingStore.entries())if(this.resolveAgentSessionId(a)===s){n=a.cwd??"";break}}if(!n){const a=new Error(`agent session not found: ${s}`);throw a.sessionControlErrorCode=E.invalidAgentSession,a}const r=this.normalizePathForCompare(n);if(r&&i&&r!==i){const a=new Error(`agent session cwd mismatch: expected ${t}, got ${n}`);throw a.sessionControlErrorCode=E.invalidAgentSession,a}}buildOpenedBindingResult(e,t,s="ready"){const i=this.bindingStore.get(e),n=i?String(this.resolveAgentSessionId(i)??"").trim():"",o={aibotSessionId:e,providerKey:this.providerKeyForAdapter(),cwd:t,workerStatus:s};return n&&(o.bindingId=n,o.agentSessionId=n),(this.config.adapterType??"acp")==="deepseek-harness"&&Object.assign(o,this.buildDshOpenedToolbarMeta(e)),o}buildDshOpenedToolbarMeta(e){const t=this.globalConfigStore?.get(this.name),s=this.bindingStore.get(e),i=this.config.adapterOptions??{},n=typeof i.dshHome=="string"?i.dshHome:void 0;if(!this.bindingStore.getDshAgentPreset(e)){const R=ve(t?.dshAgentPreset,he);this.bindingStore.setDshAgentPreset(e,R)}const o=this.bindingStore.getDshSelectedProfile(e),r=Se({binding:o,global:t?.dshProfile,adapter:typeof i.dshProfile=="string"?i.dshProfile:void 0});o||this.bindingStore.setDshSelectedProfile(e,r);const a=this.dshCatalogDataRoot(),c=this.bindingStore.getDshSettings(e),d=c?.providerId??t?.dshProviderId,l=_e({dataRoot:a,providerId:d}),h=[c?.modelId,t?.dshModelId,l.models[0]?.id].find(R=>!!R&&l.models.some(C=>C.id===R))??l.models[0]?.id,g=j(s?.dshModeId,t?.dshModeId),u={};!s?.dshProviderId&&l.providerId&&(u.providerId=l.providerId),!s?.dshModelId&&h&&(u.modelId=h),s?.dshModeId||(u.modeId=g),s?.dshThinking||(u.thinking=me(t?.dshThinking)??"enabled"),s?.dshReasoningEffort||(u.reasoningEffort=fe(t?.dshReasoningEffort)??"high"),Object.keys(u).length>0&&this.bindingStore.updateDshSettings(e,u);const f=this.bindingStore.getDshSettings(e);let b=[],v=[],m=!1;try{b=ue({dshHome:n,profileName:r,enabledPluginIds:this.bindingStore.getDshEnabledPlugins(e)}),m=!1}catch{}const w=T.join(a,"dsh-session-skills");return we(w),v=pe({skillsDir:w,enabledSkillIds:this.bindingStore.getDshEnabledSkills(e)}),ce({agentPreset:f?.agentPreset,agentPresetLocked:this.bindingStore.isDshAgentPresetLocked(e),profileName:r,profiles:ge({dshHome:n}),profileLocked:this.bindingStore.isDshProfileLocked(e),plugins:b,skills:v,pluginRestartRequired:m,providerId:f?.providerId??l.providerId,modelId:f?.modelId??h,modeId:j(this.bindingStore.get(e)?.dshModeId,t?.dshModeId),thinking:f?.thinking,reasoningEffort:f?.reasoningEffort,providers:l.providers,models:l.models})}dshCatalogDataRoot(){const e=O("sha256").update(this.config.aibot.agentId).digest("hex").slice(0,24);return T.join(L.data,"deepseek-harness",e)}hasDiskScanner(){const e=this.config.adapterType??"acp";return e==="codex"||e==="claude"||e==="acp"||e==="deepseek-harness"}unbindSession(e){return Et(this,e)}handleUnbindTextCommand(e){return kt(this,e)}handleUnbindLocalAction(e){return Rt(this,e)}handleListSessionsTextCommand(e){return yt(this,e)}handleListSessionsLocalAction(e){return Pt(this,e)}handleSyncHistoryLocalAction(e){return Tt(this,e)}handleSessionControlCommand(e,t){return it(this,e,t)}handleSessionControlLocalAction(e){return st(this,e)}handleEventCancel(e){return lt(this,e)}waitForEventDone(e,t,s){return ct(this,e,t,s)}handleAibotStop(e){ht(this,e)}killAndResumeStopSlot(e,t){return ut(this,e,t)}handleAibotRevoke(e){return pt(this,e)}handleConfigureGatewayProvider(e){return gt(this,e)}getAuditLocalActionHandler(){return ft(this)}handleAuditLocalAction(e){return mt(this,e)}handleConnectorRollback(e){return vt(this,e)}getRelayStateSyncer(){return _t(this)}relayStateSyncOnConnect(){St(this)}reportRelayStateLocalChange(){bt(this)}handleApplyRelayState(e){return Ct(this,e)}fetchRelayCredential(e){return wt(this,e)}isSharedInstance(){return At(this)}async handleAibotLocalAction(e){if(this.stopped){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"connector_lifecycle_draining",error_msg:"connector is shutting down; local action was not executed"});return}const t=e.action_type??"",s=String((e.params??{}).session_id??""),i=String((e.params??{}).verb??"").trim().toLowerCase();p.debug(this.name,`local_action received action_type=${t} verb=${i||"-"} action_id=${e.action_id} session_id=${s}`);let n;if(t===k.sessionControl&&(n=this.lifecycleBarrier.tryEnter()??void 0,!n)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"connector_lifecycle_draining",error_msg:"connector is draining for restart; session control was not executed"});return}try{if(t===k.interactionReply&&await this.handleCliInstallInteractionReply(e))return;if(Ce(t)){await this.handleAuditLocalAction(e);return}const o=(this.config.adapterType??"acp")==="claude";if(t===k.sessionControl&&i===S.exec&&await this.handleSessionControlLocalAction(e))return;if(t===k.sessionControl&&i===S.listSessions){await this.handleListSessionsLocalAction(e);return}if(t===k.sessionControl&&i===S.syncHistory){await this.handleSyncHistoryLocalAction(e);return}if(t===k.sessionControl&&i===S.unbind){await this.handleUnbindLocalAction(e);return}if(t==="skill_upload"){await this.handleSkillUploadLocalAction(e);return}if(t==="skill_delete"){await this.handleSkillDeleteLocalAction(e);return}if(t==="skill_enable"){await this.handleSkillEnableLocalAction(e);return}if(t==="skill_disable"){await this.handleSkillDisableLocalAction(e);return}if(t==="skill_refresh"){this.handleSkillRefreshLocalAction(e);return}const r=(this.config.adapterType??"acp")==="opencode";if((o&&(t===k.interactionReply||t==="exec_approve"||t==="exec_reject")||r&&t===k.interactionReply)&&(await this.pool.deliverLocalAction(e)).handled||o&&await this.handleSessionControlLocalAction(e))return;if(t===k.sessionControl){const u=this.config.adapterType??"acp",f=u==="codex",b=u==="pi",v=String((e.params??{}).verb??"").trim().toLowerCase();if(f&&v===S.open){await this.handleCodexSessionControlLocalActionOpen(e);return}if(u==="cursor"&&v===S.open){await this.handleCursorSessionControlLocalActionOpen(e);return}if(f&&v==="restart"){const _=this.bindingStore.get(s)?.cwd??"";await this.pool.removeSlot(s).catch(()=>{}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"restarted",binding:{aibotSessionId:s,cwd:_,workerStatus:"ready"}}});return}if(b&&v===S.open){try{const C=e.params??{},_=String(C.cwd??"").trim();if(!_){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:E.cwdRequired,error_msg:"session cwd is required"});return}const A=await this.resolveCwdForBinding(_),x=String(C.agent_session_id??"").trim();this.ensureImportedAgentSession(x,A),this.bindingStore.set(s,A),this.setResolvedAgentSessionId(s,x),this.sessionBindings.set(s,A),await this.ensureSlotStarted(s).catch(H=>{if(zn(H))throw H;p.warn("bridge",`pi ensureSlotStarted on local-action bind failed (non-fatal): ${H instanceof Error?H.message:String(H)}`)}),await this.deferredMgr.release(s,this.deferredCallbacks()),this.aibotHandle.sendUpdateBindingCard({session_id:s,worker_status:"ready",cwd:A}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(s,A)}})}catch(C){this.failSessionOpen(C,{sessionId:s,eventId:e.action_id,cwd:this.bindingStore.get(s)?.cwd||String((e.params??{}).cwd??"").trim(),send:(_,A)=>this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:_,error_msg:A})})}return}if(b&&v===S.restart){await this.handlePiSessionControlRestartLocalAction(e);return}if((u==="openhuman"||u==="opencode")&&v===S.open){try{const C=e.params??{},_=String(C.cwd??"").trim();if(!_){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:E.cwdRequired,error_msg:"session cwd is required"});return}const A=await this.resolveCwdForBinding(_),x=String(C.agent_session_id??"").trim();this.ensureImportedAgentSession(x,A),this.bindingStore.set(s,A),this.setResolvedAgentSessionId(s,x),this.sessionBindings.set(s,A),await this.syncOpenCodeBinding(s,A),await this.deferredMgr.release(s,this.deferredCallbacks()),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(s,A)}})}catch(C){this.failSessionOpen(C,{sessionId:s,eventId:e.action_id,cwd:this.bindingStore.get(s)?.cwd||String((e.params??{}).cwd??"").trim(),send:(_,A)=>this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:_,error_msg:A})})}return}if(u==="codewhale"&&v===S.open){await this.handleCodeWhaleSessionControlLocalActionOpen(e);return}if(u==="deepseek-harness"&&v===S.open){await this.handleDeepSeekSessionControlLocalActionOpen(e);return}if(u==="acp"&&v===S.stop){const _=this.bindingStore.get(s)?.cwd??"";await this.pool.removeSlot(s).catch(()=>{}),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"stopped",binding:{aibotSessionId:s,cwd:_,workerStatus:"stopped"}}});return}try{if(v===S.open){const C=e.params??{},_=String(C.cwd??"").trim();if(!_){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:E.cwdRequired,error_msg:"session cwd is required"});return}const A=String(C.agent_session_id??"").trim();if(A){const x=await this.resolveCwdForBinding(_);this.ensureImportedAgentSession(A,x)}}await this.handleSessionControlLocalActionForPool(e)}catch(C){this.failSessionOpen(C,{sessionId:s,eventId:e.action_id,cwd:this.bindingStore.get(s)?.cwd||String((e.params??{}).cwd??"").trim(),send:(_,A)=>this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:_,error_msg:A})});return}if(v===S.open){const C=e.params??{},_=await this.resolveCwdForBinding(String(C.cwd??"").trim());this.setResolvedAgentSessionId(s,String(C.agent_session_id??"").trim()),u==="agy"&&(this.bindingStore.set(s,_),this.sessionBindings.set(s,_)),await this.deferredMgr.release(s,this.deferredCallbacks()),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{outcome:"opened",binding:this.buildOpenedBindingResult(s,_)}}),(this.config.adapterType??"acp")==="agy"&&(this.sendAgyBindingCard(s,_),this.refreshAndPushAgyQuota(s,!0))}else Wn(e,this.sessionControlCtx(s),this.sessionControlSenders(s));return}if(t==="file_list"){const u=Date.now(),f=s?this.bindingStore.get(s)?.cwd:void 0,b=e.params??{},v=String(b.parent_id??"").trim(),m=Array.isArray(b.allowed_extensions)?b.allowed_extensions.filter(_=>typeof _=="string").map(_=>_.trim()).filter(_=>_.length>0):[];p.info("file-list-diag",`plugin << recv action_id=${e.action_id} session_id=${s} parent_id=${v||"<root>"} show_hidden=${!!b.show_hidden} ext_count=${m.length} bound_cwd=${f??"<none>"}`);const w=await Vn({parent_id:v||null,session_id:s,show_hidden:!!b.show_hidden,allowed_extensions:m},{resolveCwd:()=>f??this.config.agent.cwd??process.cwd(),fallbackDir:Y()}),R=Date.now()-u,C=w.result?.files?.length??0;p.info("file-list-diag",`plugin -> reply action_id=${e.action_id} status=${w.status} elapsed=${R}ms count=${C} current_path=${w.result?.current_path??""} error_code=${w.error_code??""} error_msg=${w.error_msg??""}`),this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:w.status,...w.result?{result:{...w.result,machine_name:ti()}}:{},...w.error_code?{error_code:w.error_code}:{},...w.error_msg?{error_msg:w.error_msg}:{}});return}if(t==="create_folder"){const u=s?this.bindingStore.get(s)?.cwd:void 0,f=String((e.params??{}).parent_id??"").trim(),b=String((e.params??{}).name??"").trim(),v=await Zn({parent_id:f||null,name:b,session_id:s},{resolveCwd:()=>u??this.config.agent.cwd??process.cwd(),fallbackDir:Y()});this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:v.status,...v.result?{result:v.result}:{},...v.error_code?{error_code:v.error_code}:{},...v.error_msg?{error_msg:v.error_msg}:{}});return}if(t===k.setModel&&(this.config.adapterType??"acp")==="agy"){await this.handleAgySetModel(e,s);return}if(t===k.getSessionUsage){if((this.config.adapterType??"acp")==="deepseek-harness"&&(await this.pool.deliverLocalAction(e,{autoCreateSlot:!!s&&!!this.bindingStore.get(s)?.cwd})).handled)return;await this.handleGetSessionUsage(e,s);return}if(t===k.getRateLimits){if((this.config.adapterType??"acp")==="deepseek-harness"&&(await this.pool.deliverLocalAction(e,{autoCreateSlot:!!s&&!!this.bindingStore.get(s)?.cwd})).handled)return;await this.handleGetRateLimits(e,s);return}const a=(this.config.adapterType??"acp")==="acp",c=(this.config.adapterType??"acp")==="cursor";if((o||a||c)&&t===k.threadCompact){await this.handleThreadCompact(e,s);return}if(t==="connector_rollback"){await this.handleConnectorRollback(e);return}if(t==="connector_upgrade_push"){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{accepted:!0}}),this.upgradeTrigger?.();return}if(t===k.getAgentGlobalConfig){const u=this.globalConfigStore?.get(this.name);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{agentName:this.name,...u?{config:u}:{config:null}}});return}if(t==="configure_gateway_provider"){await this.handleConfigureGatewayProvider(e);return}if(t==="apply_relay_state"){await this.handleApplyRelayState(e);return}const d=this.config.adapterType??"acp",l=(d==="codex"||d==="cursor"||d==="pi"||d==="openhuman"||d==="opencode"||d==="deepseek-harness"||d==="acp")&&!!s&&!!this.bindingStore.get(s)?.cwd,h=await this.pool.deliverLocalAction(e,{autoCreateSlot:l});if(h.handled){if(h.kind==="set_mode"){const u=String((e.params??{}).mode_id??"");u&&(d==="cursor"?(this.bindingStore.setCursorModeId(s,u),this.globalConfigStore?.set(this.name,{cursorModeId:u})):d==="claude"?(this.bindingStore.setModeId(s,u),this.globalConfigStore?.set(this.name,{modeId:u})):d==="opencode"?(this.bindingStore.setModeId(s,u),this.globalConfigStore?.set(this.name,{modeId:u})):I.has(d)?d==="codex"&&this.globalConfigStore?.set(this.name,{codexModeId:u}):this.globalConfigStore?.set(this.name,{acpInitialMode:u}))}else if(h.kind==="set_model"){const u=String((e.params??{}).model_id??"").trim();if(u){d==="cursor"?(this.bindingStore.setModelId(s,u),this.globalConfigStore?.set(this.name,{modelId:u})):d==="opencode"?(this.bindingStore.setModelId(s,u),this.globalConfigStore?.set(this.name,{modelId:u})):d==="codewhale"?(this.bindingStore.setModelId(s,u),this.globalConfigStore?.set(this.name,{modelId:u})):d==="codex"?this.globalConfigStore?.set(this.name,{codexModelId:u,codexReasoningEffort:void 0}):I.has(d)||this.globalConfigStore?.set(this.name,{modelId:u});const f=String((e.params??{}).provider??(e.params??{}).model_provider??"").trim()||void 0;this.refreshQuotaAfterModelSwitch(s,u,f)}}else if(h.kind==="set_reasoning_effort"){const u=String((e.params??{}).reasoning_effort??(e.params??{}).reasoning_eff??(e.params??{}).effort??"");u&&this.globalConfigStore?.set(this.name,{codexReasoningEffort:u})}else if(h.kind==="set_sandbox_mode"){const u=String((e.params??{}).sandbox_mode??(e.params??{}).sandboxMode??"");if(u){const f=u==="default"?void 0:u;this.globalConfigStore?.set(this.name,{codexSandboxMode:f})}}else if(h.kind==="set_service_tier"){const u=String((e.params??{}).service_tier??(e.params??{}).serviceTier??(e.params??{}).value??"").trim();if(u){const f=u.toLowerCase()==="default"?void 0:u;this.globalConfigStore?.set(this.name,{codexServiceTier:f})}}return}if((d==="codex"||d==="cursor"||d==="pi"||d==="openhuman"||d==="opencode"||d==="deepseek-harness")&&s&&!this.bindingStore.get(s)?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:E.bindingMissing,error_msg:"Session binding missing. Open a workspace first."});return}if(d==="acp"&&(t==="set_mode"||t==="set_model")){const u=this.sessionControlSenders(s),f=this.pool.getSlot(s)?.adapter,b={bindingStore:this.bindingStore,acpAdapter:f instanceof y?f:null,globalConfigStore:this.globalConfigStore,agentName:this.name,log:p};if(t==="set_mode"){const v=String((e.params??{}).mode_id??""),m=await J(b,s,v);if(m.status==="failed")u.sendLocalActionResult(e.action_id,"failed",void 0,m.errorCode,m.errorMsg);else{const w=f instanceof y?f.buildToolbarContext(m.result?.outcome==="mode_set"?"mode_set":"mode_set_failed"):null,R=w?{...w,...m.result}:m.result;u.sendLocalActionResult(e.action_id,"ok",R)}}else{const v=String((e.params??{}).model_id??""),m=await z(b,s,v);if(m.status==="failed")u.sendLocalActionResult(e.action_id,"failed",void 0,m.errorCode,m.errorMsg);else{const w=f instanceof y?f.buildToolbarContext(m.result?.outcome==="model_set"?"model_set":"model_set_failed"):null,R=w?{...w,...m.result}:m.result;u.sendLocalActionResult(e.action_id,"ok",R),m.result?.outcome==="model_set"&&this.refreshQuotaAfterModelSwitch(s,v)}}return}const g=!!s&&!!this.pool.getSlot(s);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"unsupported_local_action",error_msg:g?`Action type "${t}" is not supported by the current agent process.`:`No active agent process for this session. The reply to action "${t}" could not be delivered \u2014 please resend it as a new message.`})}finally{n?.()}}handleGetSessionUsage(e,t){return Kt(this,e,t)}handleThreadCompact(e,t){return zt(this,e,t)}handleGetRateLimits(e,t){return Qn(this,e,t)}resolveRateLimitWakeSessionId(e,t){return On(this,e,t)}wakeRateLimitSlot(e,t){return Bn(this,e,t)}sessionControlCtx(e){const t=this.pool.getSlot(e),s=t?.adapter instanceof y?t.adapter:null,i=(this.config.adapterType??"acp")==="acp",n={bindingStore:this.bindingStore,acpAdapter:s,globalConfigStore:this.globalConfigStore,agentName:this.name,log:p};return{getCwd:()=>this.bindingStore.get(e)?.cwd??this.config.agent.cwd??process.cwd(),getSessionBindings:()=>{if(s)return s.getSessionBindings();const o=this.sessionBindings;if(e&&!o.has(e)){const r=this.bindingStore.get(e);r?.cwd&&o.set(e,r.cwd)}return o},getStatus:()=>this.getStatus(),isAcpAlive:!!s?.isAlive(),getAcpSessionOptions:()=>s?.acpSessionOptions??null,setMode:o=>s?s.setMode(o):Promise.resolve(!1),setModel:o=>s?s.setModel(o):Promise.resolve(!1),acpSetMode:i?(o,r)=>J(n,o,r):void 0,acpSetModel:i?(o,r)=>z(n,o,r):void 0,getPendingApproval:o=>{const r=s?.pendingApprovalEntries.get(o);return r?{requestId:r}:void 0},deletePendingApproval:o=>s?.pendingApprovalEntries.delete(o)??!1,respondPermission:(o,r)=>(s&&s.respondToPermission(o,r),Promise.resolve()),onSessionBound:(o,r)=>{this.bindingStore.set(o,r)},onSessionUnbound:o=>{this.unbindSession(o).catch(r=>{p.warn(this.name,`session unbind cleanup failed: ${r instanceof Error?r.message:String(r)}`)})},cancelActiveRun:()=>(this.config.adapterType??"acp")==="agy"&&t?.adapter instanceof G?(t.adapter.cancelCurrentRun(),Promise.resolve()):t?.adapter?.cancel("")??Promise.resolve(),onModeSet:o=>{const r=this.config.adapterType??"acp";r==="codex"?this.globalConfigStore?.set(this.name,{codexModeId:o}):r==="opencode"?this.bindingStore.setModeId(e,o):I.has(r)||this.globalConfigStore?.set(this.name,{acpInitialMode:o})},onModelSet:o=>{const r=this.config.adapterType??"acp";r==="codex"?this.globalConfigStore?.set(this.name,{codexModelId:o}):r==="opencode"?this.bindingStore.setModelId(e,o):I.has(r)||this.globalConfigStore?.set(this.name,{modelId:o}),this.refreshQuotaAfterModelSwitch(e,o)}}}sessionControlSenders(e){return{sendEventAck:(t,s)=>this.aibotHandle.sendEventAck({event_id:t,session_id:s,received_at:Date.now()}),sendEventResult:(t,s,i)=>this.aibotHandle.sendEventResult({event_id:t,status:s,...i?.msg?{msg:i.msg}:{},...i?.code?{code:i.code}:{},updated_at:Date.now()}),sendLocalActionResult:(t,s,i,n,o)=>this.aibotHandle.sendLocalActionResult({action_id:t,status:s,...i?{result:i}:{},...n?{error_code:n}:{},...o?{error_msg:o}:{}},e)}}resolveBindingChannelKey(e){switch(e){case"claude":return"grix-claude";case"codex":return"codex";case"cursor":return"cursor";case"pi":return"pi";case"openhuman":return"openhuman";case"codewhale":return"codewhale";case"opencode":return"opencode";case"agy":return"acp";case"deepseek-harness":return"deepseek";case"acp":return this.config.aibot.clientType==="qwen"?"qwen":"acp";default:return e}}finalizeThinking(e,t){this.sendCtrl.finalizeThinking(e,t)}logInboundConversation(e){const t=String(e.session_id??"").trim();t&&this.conversationLog?.logInbound(t,{event_id:e.event_id,msg_id:e.msg_id,sender_id:e.sender_id,msg_type:e.msg_type,content:e.content??""})}resolveAuditProvider(){const e=this.config.adapterType??"acp";return e==="claude"||e==="codex"||e==="cursor"||e==="opencode"||e==="pi"||e==="codewhale"||e==="deepseek-harness"||e==="agy"?e:"acp"}sendAuditConfigurationError(e,t){const s=t instanceof Error?t.message:String(t),i=(()=>{const a=V(e.extra);return a.options?.enabled===!0&&a.options.scope==="turn"})(),n=t instanceof ki||t instanceof Ei,o=t instanceof Pi&&i,r=o?"audit_config_invalid":n?t.code:"audit_config_conflict";if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:r,msg:s,updated_at:Date.now()}),n||o)try{this.aibotHandle.sendAuditState($({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:r,errorMessage:s},Date.now()))}catch{}}markAuditAdapterClosed(e,t){const i=this.pool.getSlot(t)?.adapter.takeAuditBoundary?.(e);this.auditController.markAdapterClosed(e,i)}prepareAuditedInboundEvent(e,t,s){const i=this.buildInboundEvent(e,t),n=this.bindingStore.get(e.session_id),o=n?this.resolveAgentSessionId(n):void 0,r=Number(e.created_at),a=Number.isFinite(r)&&r>0?new Date(r).toISOString():void 0,c=this.auditController.startTurn({session:s,eventId:e.event_id,userInput:e.content??"",...e.msg_id===void 0?{}:{originMsgId:e.msg_id},...a===void 0?{}:{startedAt:a},boundary:{adapterType:this.config.adapterType??"acp",...o?{providerSessionId:o}:{}}});return c&&(i.audit={enabled:!0,auditId:c.auditId,turnId:c.turnId,...s?{scope:s.options.scope,profile:s.options.profile,...s.options.retentionDays===void 0?{}:{retentionDays:s.options.retentionDays},capture:{...s.options.capture}}:{},rawProviderBody:s?.options.capture.rawProviderBody===!0}),i}buildInboundEvent(e,t){const s=di(this.sendCtrl.getGlobalRuntimeConfig(),t),i=yi(e.extra);return{event_id:e.event_id,session_id:e.session_id,thread_id:e.thread_id,sender_id:e.sender_id,msg_id:e.msg_id,msg_type:e.msg_type,content:e.content??"",quoted_message_id:e.quoted_message_id,context_messages_json:this.buildContextMessagesJson(e.context_messages),extra_json:i===void 0?void 0:JSON.stringify(i),connector_runtime_config:{response_delivery:s.responseDelivery,tool_events:s.toolEvents,thinking_events:s.thinkingEvents},session_type:e.session_type,created_at:e.created_at}}buildContextMessagesJson(e){if(!e)return;const t=e.filter(s=>!Gn(String(s?.content??"")));if(t.length!==0)return JSON.stringify(t)}isStaleEvent(e){const t=Number(e.created_at);return!Number.isFinite(t)||t<=0?!1:Date.now()-t>Ti}setUpgradeTrigger(e){this.upgradeTrigger=e}setDaemonShutdownRequester(e){this.daemonShutdownRequester=e}setLifecycleBusyChecker(e){this.lifecycleBusyChecker=e}setLifecycleAdmissionCloser(e){this.lifecycleAdmissionCloser=e}setLifecycleAdmissionRestorer(e){this.lifecycleAdmissionRestorer=e}closeLifecycleAdmission(){this.lifecycleBarrier.setAutoOpenHandler(e=>{p.warn(this.name,`Lifecycle admission auto-reopened after ${Math.round(e/1e3)}s: a restart was expected but never happened. Admission is open again and events flow; the pending restart or upgrade did not complete.`)}),this.lifecycleBarrier.close()}openLifecycleAdmission(){this.lifecycleBarrier.open()}closeLifecycleAdmissionForRestart(){this.lifecycleAdmissionCloser?this.lifecycleAdmissionCloser():this.closeLifecycleAdmission()}setInstallAgentHandler(e){this.installAgentHandler=e}setAgentDeletedHandler(e){this.agentDeletedHandler=e}setSkillSyncHandler(e){this.skillSyncHandler=e}setShareSetHandler(e){this.shareSetHandler=e}setProviderConfigHandler(e){this.providerConfigHandler=e}setRelayStateApplyPorts(e){this.relayStateApplyPorts=e}}export{ao as AgentInstance};
9
+ Error: ${r}`,1,!1))}sendEventResultWithCleanup(e,i,r,n,t=!1){const s=this.eventSessionIndex.get(e);t&&this.surfacedRunErrorEvents.add(e),i==="failed"&&s&&r?.trim()&&this.sendRunErrorAsChunk(e,s,r),this.auditController.markResponded(e,i,r),this.sendCtrl.sendEventResult(e,i,r,n),s&&(this.pool.eventComplete(e,s)===!1&&h.error(this.name,`Event terminal result could not release queue slot event=${e} session=${s} status=${i}`),this.pushQueueSnapshotForSession(s),this.conversationLog?.logResult?.(s,e,i,r),this.eventSessionIndex.delete(e)),this.inflightEvents.delete(e),this.restartCount.delete(e),this.surfacedRunErrorEvents.delete(e),this.pendingStartedEventIds.delete(e),this.pendingEvents.remove(e).catch(o=>{h.warn(this.name,`Failed to remove terminal event from pending store event=${e}: ${o instanceof Error?o.message:String(o)}`)}),i==="responded"&&(this.config.adapterType??"acp")!=="agy"&&(this.cachedProviderQuotaSampledAtMs=null,this.refreshAndPushProviderQuota(!0).catch(()=>{}))}async handleSessionInternalError(e){const{eventId:i,sessionId:r,errorMsg:n}=e;if(this.stopped)return;const t=this.inflightEvents.get(i);if(!t){h.warn(this.name,`[recovery] no inflight event for internalError event=${i} session=${r}; surface failure directly`),this.sendRunErrorAsChunk(i,r,n),this.sendEventResultWithCleanup(i,"failed",n,"agent_stop_failure");return}const s=(this.restartCount.get(i)??0)+1;this.restartCount.set(i,s);const o=this.config.adapterType??"acp";if(s>P){h.error(this.name,`[recovery] adapter=${o} session=${r} event=${i} restart=${s}/${P} outcome=give-up err=${n}`),this.sendRunErrorAsChunk(i,r,n),this.sendEventResultWithCleanup(i,"failed",n,"agent_stop_failure");return}h.info(this.name,`[recovery] adapter=${o} session=${r} event=${i} restart=${s}/${P} outcome=restarting err=${n}`);const a=this.pool.drainQueuedForSession(r);a.length>0&&h.info(this.name,`[recovery] session=${r} preserved ${a.length} queued sibling event(s) across restart`);try{await this.pool.removeSlot(r)}catch(c){h.warn(this.name,`[recovery] removeSlot failed session=${r}: ${c instanceof Error?c.message:String(c)}`)}if(this.stopped)return;const l=e.replayOriginalContent?t.content:this.resolveRecoveryPrompt(o,t),d={...t,content:l};try{await this.pool.deliverInboundEvent(d)}catch(c){h.error(this.name,`[recovery] redeliver failed event=${i} session=${r}: ${c instanceof Error?c.message:String(c)}`),this.sendEventResultWithCleanup(i,"failed",c instanceof Error?c.message:String(c));return}for(const c of a){if(this.stopped)break;try{await this.pool.deliverInboundEvent(c)}catch(u){h.error(this.name,`[recovery] sibling redeliver failed event=${c.event_id} session=${r}: ${u instanceof Error?u.message:String(u)}`),this.sendEventResultWithCleanup(c.event_id,"failed",u instanceof Error?u.message:String(u))}}}resolveRecoveryPrompt(e,i){return e==="acp"?"continue":i.content}sendThinkingByRuntimeConfig(e,i,r){this.sendCtrl.sendThinking(e,i,r)}bufferStreamChunk(e,i,r,n,t){this.auditController.captureUnsequencedStreamChunk(e,r),this.sendCtrl.bufferOnly(e,i,r,n,t)}flushBufferedStreamText(e){}resolveEventRuntimeConfig(e){return this.sendCtrl.resolveEventRuntimeConfig(e)}captureEventRuntimeConfig(e){this.sendCtrl.captureEventRuntimeConfig(e),this.indexEventSession(e.event_id,e.session_id),this.auditController.markRecording(e.event_id),e.event_id&&!this.inflightEvents.has(e.event_id)&&this.inflightEvents.set(e.event_id,e)}async replayPendingEventsOnStartup(){const e=await this.pendingEvents.loadForReplay();if(e.length===0)return;const i=new Set(e.map(n=>n.event.event_id).filter(Boolean)),r=[];h.warn(this.name,`Replaying ${e.length} pending event(s) from previous run`);for(const n of e){if(this.stopped)break;const t=n.event;this.pendingEvents.startReplay(n);try{if(n.kind==="deferred"){const s=this.bindingStore.get(n.sessionId);s?.cwd?(await this.prepareBoundDeferredReplay(n,s.cwd),await this.deliverPendingReplayEvent(t),this.pendingStartedEventIds.has(t.event_id)||r.push(n)):(this.restorePendingReplayAuditTurn(t),this.deferredMgr.defer(n.channel,n.sessionId,t),r.push(n))}else await this.deliverPendingReplayEvent(t),this.pendingStartedEventIds.has(t.event_id)||r.push(n)}catch(s){const o=s instanceof Error?s.message:String(s);h.error(this.name,`Pending event replay failed event=${t.event_id}: ${o}`),this.sendEventResultWithCleanup(t.event_id,"failed",o),this.pendingEvents.markCanceled(t.event_id),await this.pendingEvents.remove(t.event_id).catch(()=>{})}finally{this.pendingEvents.finishReplay(n),await this.pendingEvents.checkpointReplay(i,[...r,...this.pendingEvents.replaySnapshot()])}if(this.stopped)break}this.stopped||(this.pendingEvents.finishAllReplay(),await this.pendingEvents.checkpointReplay(i,r))}failEventIfLifecycleDraining(e,i="connector is draining for restart; control command was not executed"){return this.lifecycleBarrier.isClosed()?(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"connector_lifecycle_draining",msg:i,updated_at:Date.now()}),!0):!1}sendCanceledPendingEventResult(e,i){this.restorePendingReplayAuditTurn(e),this.captureEventRuntimeConfig(e),this.sendEventResultWithCleanup(e.event_id,"canceled",i),this.auditController.markAdapterClosed(e.event_id,{adapterNotStarted:!0})}async deliverPendingReplayEvent(e){this.restorePendingReplayAuditTurn(e),this.captureEventRuntimeConfig(e),await this.pool.deliverInboundEvent(e)}async prepareBoundDeferredReplay(e,i){this.sessionBindings.set(e.sessionId,i),e.channel==="acp"?await this.bindSessionForPool(e.sessionId,i):e.channel==="opencode"&&await this.syncOpenCodeBinding(e.sessionId,i)}restorePendingReplayAuditTurn(e){const i=e.audit;if(!i?.enabled||!i.auditId||!i.capture||!i.profile||!i.scope)return;const r=vi({enabled:!0,scope:i.scope,profile:i.profile,capture:i.capture,...i.retentionDays===void 0?{}:{retentionDays:i.retentionDays}});if(!r.enabled)return;const n=Object.freeze({auditId:i.auditId,businessSessionId:e.session_id,provider:this.resolveAuditProvider(),options:r,createdAt:new Date().toISOString()}),t=this.auditController.startTurn({session:n,eventId:e.event_id,userInput:e.content??"",...e.msg_id===void 0?{}:{originMsgId:e.msg_id},...Number.isFinite(Number(e.created_at))&&Number(e.created_at)>0?{startedAt:new Date(Number(e.created_at)).toISOString()}:{},boundary:{adapterType:this.config.adapterType??"acp"}});t&&(e.audit={...i,auditId:t.auditId,turnId:t.turnId,profile:n.options.profile,capture:{...n.options.capture},rawProviderBody:n.options.capture.rawProviderBody})}indexEventSession(e,i){if(!e||!i)return;const r=this.eventSessionIndex.get(e);return r?(r!==i&&h.warn(this.name,`Ignoring event session mismatch event=${e} indexed=${r} supplied=${i}`),r):(this.eventSessionIndex.set(e,i),i)}shouldDropToolDisplayEvent(e){return this.sendCtrl.shouldDropToolDisplayEvent(e)}shouldDropThinkingDisplayEvent(e){return this.sendCtrl.shouldDropThinkingDisplayEvent(e)}shouldDropCodexDisplayEvent(e,i){return this.sendCtrl.shouldDropCodexDisplayEvent(e,i)}logCodexEventToConversation(e){if(!this.conversationLog||e.codex_method!=="item/agentMessage/delta")return;const r=e.codex_payload?.params?.delta;if(!r)return;const n=this.eventSessionIndex.get(e.event_id)??e.session_id;this.conversationLog.append(n,{ts:Date.now(),dir:"outbound",event_id:e.event_id,kind:"codex_delta",text_len:r.length,content:r})}isAcpRawTransportEnabled(){return(this.config.adapterOptions??{}).raw_transport===!0}shouldDropAcpRawDisplayEvent(e,i){return this.sendCtrl.shouldDropAcpRawDisplayEvent(e,i)}sendAcpRawEventEnvelope(e,i,r){this.shouldDropAcpRawDisplayEvent(e,r.type)||this.deliverRawEventEnvelope(e,i,r,"acp",this.buildAcpRawEventFallbackText(r))}buildAcpRawEventFallbackText(e){const i=String(e.type??"").trim();if(!i)return"[acp] event";switch(i){case"permission_request":return`Permission required: ${String(e.payload?.tool_title??e.payload?.tool_name??"permission request")}`;case"tool_use":return`[tool] ${String(e.payload?.tool_name??"tool")}`;case"tool_result":return"[tool result]";case"thinking":return"[thinking]";case"error":return`[error] ${String(e.payload?.message??"agent error")}`;case"result":return"[result]";default:return`[acp] ${i}`}}rawDetailSeq=0;deliverRawEventEnvelope(e,i,r,n,t){const s=ri({envelope:r,fallbackText:t,channelKey:n,allocateRefId:()=>`${e}_rawd_${++this.rawDetailSeq}`}),o=()=>{this.aibotHandle.sendMsg({event_id:e,session_id:i,msg_type:1,content:s.fallbackText,extra:{channel_data:{[n]:{raw_event:s.envelope}},agent_api_origin:!0}})};if(!s.sharded){o();return}h.info("bridge",`${n} raw_event oversized, sharded delivery: event=${e} fields=${s.oversizedFields.map(a=>a.field).join(",")}`),(async()=>{for(const a of s.oversizedFields)await this.sendCtrl.deliverAuxiliaryLargeText(e,i,ai({envelopeType:r.type,field:a.field,fullText:a.fullText}),a.refClientMsgId);o()})().catch(a=>{h.warn("bridge",`${n} raw_event sharded delivery failed event=${e}: ${a}`)})}buildCursorRawEventFallbackText(e){const i=String(e?.type??"").trim(),r=e?.payload&&typeof e.payload=="object"?e.payload:{};switch(i){case"permission_request":return`Permission required: ${String(r.tool_title??r.tool_name??"permission request")}`;case"tool_use":case"tool_call":case"tool_execution_start":return`[tool] ${String(r.tool_name??r.toolName??"tool")}`;case"tool_result":case"tool_execution_end":case"tool_execution_update":return"[tool result]";case"error":return`[error] ${String(r.message??"agent error")}`;default:return i?`[cursor] ${i}`:"[cursor] event"}}sendToolExecutionCard(e,i,r,n){this.sendCtrl.sendToolExecutionCard(e,i,r,n)}sendGrixApprovalCard(e,i){this.aibotHandle.sendMsg({event_id:e.eventId,session_id:e.sessionId,client_msg_id:`perm_${R()}`,msg_type:1,content:e.toolTitle?`Permission required: ${e.toolTitle}`:"Permission request",extra:{channel_data:{execApproval:{approvalId:e.approvalId,approvalSlug:e.toolName},grix:{execApproval:{approval_command_id:e.approvalId,command:e.toolTitle||e.toolName,host:i}}},agent_api_origin:!0}})}sendGrixAgentQuestionCard(e,i,r){const n=r.questions.map(s=>s.header).join(", "),t=I(`[Agent Question] ${r.request_id}`,"agent_question",r);this.aibotHandle.sendText({event_id:e,session_id:i,content:t,msg_type:1,extra:{card_type:"agent_question",summary_text:n}})}async handleAgentQuestionReplyEvent(e){const i=_n(String(e.content??""));if(!i)return!1;this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const n=this.pool.getSlot(e.session_id)?.adapter,t=n instanceof S?"acp":n instanceof k?"opencode":this.config.adapterType??"unknown",s=n instanceof k?n.handleQuestionReplyEvent(i):n instanceof S?await n.handleQuestionReplyEvent(i):{delivered:!1,errorCode:"interaction_request_not_pending",errorMsg:"The question is no longer pending; the reply was not delivered."};return s.delivered?(h.info(this.name,`[${t}] question reply delivered event=${e.event_id} session=${e.session_id} request=${i.request_id}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()})):(h.warn(this.name,`[${t}] question reply rejected event=${e.event_id} session=${e.session_id} request=${i.request_id} code=${s.errorCode??"interaction_reply_failed"}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:s.errorCode??"interaction_reply_failed",msg:s.errorMsg??"The question reply was not delivered.",updated_at:Date.now()})),!0}async handleExecApprovalResolutionEvent(e){const i=vn(String(e.content??""));if(!i)return!1;this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});const n=this.pool.getSlot(e.session_id)?.adapter,t=i.params,s=String(t.tool_call_id??t.approval_command_id??t.approval_id??t.exec_context_id??""),o=n?.handleExecApprovalEvent?await n.handleExecApprovalEvent({...t,event_id:e.event_id,session_id:e.session_id}):{delivered:!1,errorCode:"approval_not_supported",errorMsg:"The current adapter does not support exec approval resolution events."};return o.delivered?(h.info(this.name,`[${this.config.adapterType??"unknown"}] exec approval resolution delivered event=${e.event_id} session=${e.session_id} approval=${s||"-"}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()})):(h.warn(this.name,`[${this.config.adapterType??"unknown"}] exec approval resolution rejected event=${e.event_id} session=${e.session_id} approval=${s||"-"} code=${o.errorCode}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:o.errorCode,msg:o.errorMsg,updated_at:Date.now()})),!0}async handleAibotEvent(e){if(this.relayEnvStale&&!this.hasPendingWork()&&await this.recycleAdaptersForRelayChange(),this.stopped){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:"agent shutting down",updated_at:Date.now()});return}this.logInboundConversation(e);const i=this.config.adapterType??"acp",r=fn(e);let n;if(r&&(n=this.lifecycleBarrier.tryEnter()??void 0,!n)){this.failEventIfLifecycleDraining(e);return}try{if(await this.handleCliInstallQuestionReply(e)||(i==="opencode"||i==="acp")&&await this.handleAgentQuestionReplyEvent(e)||await this.handleExecApprovalResolutionEvent(e))return;const t=ei(e.extra);if(t.error){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"connector_config_invalid",msg:t.error,updated_at:Date.now()});return}const s=t.patch,o=B(e.extra);if(Sn(this,e,i,o))return;if(r){await bn(this,r,e,i,o);return}if(e.mirror_mode==="record_only"){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",updated_at:Date.now()});return}if(this.isStaleEvent(e)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"event_stale",msg:"event is stale and will not be processed",updated_at:Date.now()});return}let a;try{a=this.auditController.resolveSession({sessionId:e.session_id,provider:this.resolveAuditProvider(),extra:e.extra,eventId:e.event_id}).session}catch(c){this.sendAuditConfigurationError(e,c);return}if(await Cn(this,e,i,wi.has(i),s,a))return;if((this.config.adapterType??"acp")==="acp"){const u=String(e.content??"").trim().match(/^\/(\S+)\s*(.*)/);if(u){const[,g,p]=u,A=this.pool.getSlot(e.session_id)?.adapter;if(A?.execCommand&&(A.getSupportedCommands?.()??[]).some(m=>m.name===g||m.name===`/${g}`)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});try{const m=await A.execCommand(g,p.trim(),e.session_id);m.status==="options"&&m.data&&this.handleExecCommandOptions(e.session_id,g,m.data),this.aibotHandle.sendEventResult({event_id:e.event_id,status:m.status==="failed"?"failed":"responded",msg:m.message,updated_at:Date.now()})}catch(m){this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:m instanceof Error?m.message:String(m),updated_at:Date.now()})}return}}}if(i==="codex"&&Q(a?.options)){const c=this.pool.getSlot(e.session_id);if(c?.adapter instanceof D&&!c.adapter.hasRawApiCaptureRelay()){const u=c.eventQueue.snapshot(e.session_id);u.running.length===0&&u.queued.length===0?(h.info(this.name,`[audit-raw-capture] recreating idle Codex adapter before event=${e.event_id} session=${e.session_id}`),await this.pool.removeSlot(e.session_id)):h.warn(this.name,`[audit-raw-capture] Codex adapter lacks relay but is not idle event=${e.event_id} session=${e.session_id} running=${u.running.length} queued=${u.queued.length}`)}}const d=this.prepareAuditedInboundEvent(e,s,a);try{const c=await this.pendingEvents.append({kind:"queued",event:d});if(this.pendingEvents.isCanceled(e.event_id)){await this.pendingEvents.remove(e.event_id),this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.sendCanceledPendingEventResult(d,"canceled");return}if(this.lifecycleBarrier.isClosed()){if(!c)throw new Error("pending event store unavailable during lifecycle drain");this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),h.info(this.name,`Persisted inbound event during lifecycle drain: ${e.event_id}`);return}this.captureEventRuntimeConfig(d),await this.pool.deliverInboundEvent(d)}catch(c){await this.pendingEvents.remove(e.event_id).catch(u=>{h.warn(this.name,`Failed to remove undelivered pending event=${e.event_id}: ${u instanceof Error?u.message:String(u)}`)}),this.failUndeliveredInboundEvent(e,c)}}finally{n?.()}}failUndeliveredInboundEvent(e,i){const r=i instanceof Error?i.message:String(i);this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.auditController.closeWithoutAdapter(e.event_id,"failed",r,{deliveryFailed:!0}),this.discardEventTrackingState(e.event_id),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:r,updated_at:Date.now()})}handleCodexSessionControlOpen(e,i){return it(this,e,i)}handleSessionControlForPool(e,i){return st(this,e,i)}handleSessionControlLocalActionForPool(e){return ot(this,e)}handleCodexSessionControlLocalActionOpen(e){return rt(this,e)}handleCursorSessionControlLocalActionOpen(e){return at(this,e)}handlePiSessionControlOpen(e,i){return dt(this,e,i)}handlePiSessionControlRestart(e){return lt(this,e)}handlePiSessionControlRestartLocalAction(e){return ct(this,e)}syncOpenCodeBinding(e,i){return ht(this,e,i)}isWorkspaceFreeClient(){return ut(this)}ensureDefaultBindingForWorkspaceFreeClient(e,i){return pt(this,e,i)}bindSessionForPool(e,i){return gt(this,e,i)}deferredCallbacks(){return ft(this)}handleOpenHumanSessionControlOpen(e,i){return mt(this,e,i)}handleCodeWhaleSessionControlOpen(e,i){return vt(this,e,i)}handleCodeWhaleSessionControlLocalActionOpen(e){return _t(this,e)}handleDeepSeekSessionControlLocalActionOpen(e){return St(this,e)}normalizeClaudeModeId(e){return Ht(this,e)}handleExecCommandOptions(e,i,r){$t(this,e,i,r)}resolveSessionModelId(e){return Qt(this,e)}resolveSessionModeId(e){return It(this,e)}resolveCursorSessionModeId(e){return Ot(this,e)}resolveClaudeSessionEffort(e){return Bt(this,e)}resolveClaudeSessionModeId(e){return Ft(this,e)}currentClaudeModeId(e){return Ut(this,e)}resolveCodexSessionModelId(e){return qt(this,e)}resolveCodexNewSessionGlobalDefault(e,i,r){return Nt(this,e,i,r)}pinCodexGlobalDefault(e,i){return Wt(this,e,i)}buildCursorToolbarMeta(e){return Gt(this,e)}buildAgyToolbarMeta(e,i){return jt(this,e,i)}buildAgyQuotaMeta(e){return Kt(this,e)}sendAgyBindingCard(e,i,r){return zt(this,e,i,r)}refreshAndPushAgyQuota(e,i=!1){return Jt(this,e,i)}handleAgySetModel(e,i){return Yt(this,e,i)}buildClaudeToolbarMeta(e){return Xt(this,e)}providerQuotaToCodexRateLimits(e){return si(e,this.cachedProviderQuotaSampledAtMs??Date.now())}providerQuotaToRateLimits(e){return ii(e,this.cachedProviderQuotaSampledAtMs??Date.now())}async resolveCwdForBinding(e){return Un(e)}failSessionOpen(e,i){return On(this,e,i)}getClaudeWorkerStatus(e){return Bn(this,e)}refreshClaudeWorkerStatusCard(e,i){return Fn(this,e,i)}async ensureSlotStarted(e,i=6e4){return In(this,e,i)}maybeOfferCliInstall(e){Le(this,e)}handleCliInstallQuestionReply(e){return De(this,e)}handleCliInstallInteractionReply(e){return He(this,e)}runConfirmedCliInstall(e,i){return $e(this,e,i)}handleSkillDeleteLocalAction(e){return At(this,e)}handleSkillUploadLocalAction(e){return Et(this,e)}handleSkillEnableLocalAction(e){return wt(this,e)}handleSkillRefreshLocalAction(e){yt(this,e)}handleSkillDisableLocalAction(e){return Rt(this,e)}computeSkillReport(e){return kt(this,e)}reportSessionSkills(e){Tt(this,e)}skillsSyncGroupKey(){return Pt(this)}forceRefreshSkills(e,i){return xt(this,e,i)}adoptSkillsWireHashFromDisk(){Mt(this)}buildLibrarySkillsReport(e){return Lt(this,e)}skillLookupEnv(){return Dt(this)}resolveOrphanTitle(e){return Dn(this,e)}resolveAgentSessionId(e){return Ln(this,e)}providerKeyForAdapter(){return Mn(this)}setResolvedAgentSessionId(e,i){Hn(this,e,i)}normalizePathForCompare(e){return xn(e)}ensureImportedAgentSession(e,i){Tn(this,e,i)}buildOpenedBindingResult(e,i,r="ready"){return kn(this,e,i,r)}buildDshOpenedToolbarMeta(e){return $n(this,e)}dshCatalogDataRoot(){return Qn(this)}hasDiskScanner(){return Pn(this)}unbindSession(e){return Xe(this,e)}handleUnbindTextCommand(e){return Ve(this,e)}handleUnbindLocalAction(e){return Ze(this,e)}handleListSessionsTextCommand(e){return et(this,e)}handleListSessionsLocalAction(e){return tt(this,e)}handleSyncHistoryLocalAction(e){return nt(this,e)}handleSessionControlCommand(e,i){return xe(this,e,i)}handleSessionControlLocalAction(e){return Me(this,e)}handleEventCancel(e){return Qe(this,e)}waitForEventDone(e,i,r){return Ie(this,e,i,r)}handleAibotStop(e){Oe(this,e)}killAndResumeStopSlot(e,i){return Be(this,e,i)}handleAibotRevoke(e){return Fe(this,e)}handleConfigureGatewayProvider(e){return Ue(this,e)}getAuditLocalActionHandler(){return qe(this)}handleAuditLocalAction(e){return Ne(this,e)}handleConnectorRollback(e){return We(this,e)}getRelayStateSyncer(){return Ge(this)}relayStateSyncOnConnect(){je(this)}reportRelayStateLocalChange(){Ke(this)}handleApplyRelayState(e){return ze(this,e)}fetchRelayCredential(e){return Je(this,e)}isSharedInstance(){return Ye(this)}async handleAibotLocalAction(e){if(this.stopped){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"connector_lifecycle_draining",error_msg:"connector is shutting down; local action was not executed"});return}const i=e.action_type??"",r=String((e.params??{}).session_id??""),n=String((e.params??{}).verb??"").trim().toLowerCase();h.debug(this.name,`local_action received action_type=${i} verb=${n||"-"} action_id=${e.action_id} session_id=${r}`);let t;if(i===f.sessionControl&&(t=this.lifecycleBarrier.tryEnter()??void 0,!t)){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"connector_lifecycle_draining",error_msg:"connector is draining for restart; session control was not executed"});return}try{if(i===f.interactionReply&&await this.handleCliInstallInteractionReply(e))return;if(Y(i)){await this.handleAuditLocalAction(e);return}const s=(this.config.adapterType??"acp")==="claude";if(i===f.sessionControl&&n===E.exec&&await this.handleSessionControlLocalAction(e))return;if(i===f.sessionControl&&n===E.listSessions){await this.handleListSessionsLocalAction(e);return}if(i===f.sessionControl&&n===E.syncHistory){await this.handleSyncHistoryLocalAction(e);return}if(i===f.sessionControl&&n===E.unbind){await this.handleUnbindLocalAction(e);return}if(i==="skill_upload"){await this.handleSkillUploadLocalAction(e);return}if(i==="skill_delete"){await this.handleSkillDeleteLocalAction(e);return}if(i==="skill_enable"){await this.handleSkillEnableLocalAction(e);return}if(i==="skill_disable"){await this.handleSkillDisableLocalAction(e);return}if(i==="skill_refresh"){this.handleSkillRefreshLocalAction(e);return}const o=(this.config.adapterType??"acp")==="opencode";if((s&&(i===f.interactionReply||i==="exec_approve"||i==="exec_reject")||o&&i===f.interactionReply)&&(await this.pool.deliverLocalAction(e)).handled||s&&await this.handleSessionControlLocalAction(e))return;if(i===f.sessionControl){await An(this,e,r);return}if(i==="file_list"){await wn(this,e,r);return}if(i==="create_folder"){await En(this,e,r);return}if(i===f.setModel&&(this.config.adapterType??"acp")==="agy"){await this.handleAgySetModel(e,r);return}if(i===f.getSessionUsage){if((this.config.adapterType??"acp")==="deepseek-harness"&&(await this.pool.deliverLocalAction(e,{autoCreateSlot:!!r&&!!this.bindingStore.get(r)?.cwd})).handled)return;await this.handleGetSessionUsage(e,r);return}if(i===f.getRateLimits){if((this.config.adapterType??"acp")==="deepseek-harness"&&(await this.pool.deliverLocalAction(e,{autoCreateSlot:!!r&&!!this.bindingStore.get(r)?.cwd})).handled)return;await this.handleGetRateLimits(e,r);return}const a=(this.config.adapterType??"acp")==="acp",l=(this.config.adapterType??"acp")==="cursor";if((s||a||l)&&i===f.threadCompact){await this.handleThreadCompact(e,r);return}if(i==="connector_rollback"){await this.handleConnectorRollback(e);return}if(i==="connector_upgrade_push"){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{accepted:!0}}),this.upgradeTrigger?.();return}if(i===f.getAgentGlobalConfig){const p=this.globalConfigStore?.get(this.name);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{agentName:this.name,...p?{config:p}:{config:null}}});return}if(i==="configure_gateway_provider"){await this.handleConfigureGatewayProvider(e);return}if(i==="apply_relay_state"){await this.handleApplyRelayState(e);return}const d=this.config.adapterType??"acp",c=(d==="codex"||d==="cursor"||d==="pi"||d==="openhuman"||d==="opencode"||d==="deepseek-harness"||d==="acp")&&!!r&&!!this.bindingStore.get(r)?.cwd,u=await this.pool.deliverLocalAction(e,{autoCreateSlot:c});if(u.handled){Rn(this,e,r,d,u,p=>T.has(p));return}if((d==="codex"||d==="cursor"||d==="pi"||d==="openhuman"||d==="opencode"||d==="deepseek-harness")&&r&&!this.bindingStore.get(r)?.cwd){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:$.bindingMissing,error_msg:"Session binding missing. Open a workspace first."});return}if(d==="acp"&&(i==="set_mode"||i==="set_model")){await yn(this,e,r,i);return}const g=!!r&&!!this.pool.getSlot(r);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"unsupported_local_action",error_msg:g?`Action type "${i}" is not supported by the current agent process.`:`No active agent process for this session. The reply to action "${i}" could not be delivered \u2014 please resend it as a new message.`})}finally{t?.()}}handleGetSessionUsage(e,i){return Ct(this,e,i)}handleThreadCompact(e,i){return bt(this,e,i)}handleGetRateLimits(e,i){return cn(this,e,i)}resolveRateLimitWakeSessionId(e,i){return hn(this,e,i)}wakeRateLimitSlot(e,i){return un(this,e,i)}sessionControlCtx(e){const i=this.pool.getSlot(e),r=i?.adapter instanceof S?i.adapter:null,n=(this.config.adapterType??"acp")==="acp",t={bindingStore:this.bindingStore,acpAdapter:r,globalConfigStore:this.globalConfigStore,agentName:this.name,log:h};return{getCwd:()=>this.bindingStore.get(e)?.cwd??this.config.agent.cwd??process.cwd(),getSessionBindings:()=>{if(r)return r.getSessionBindings();const s=this.sessionBindings;if(e&&!s.has(e)){const o=this.bindingStore.get(e);o?.cwd&&s.set(e,o.cwd)}return s},getStatus:()=>this.getStatus(),isAcpAlive:!!r?.isAlive(),getAcpSessionOptions:()=>r?.acpSessionOptions??null,setMode:s=>r?r.setMode(s):Promise.resolve(!1),setModel:s=>r?r.setModel(s):Promise.resolve(!1),acpSetMode:n?(s,o)=>Nn(t,s,o):void 0,acpSetModel:n?(s,o)=>qn(t,s,o):void 0,getPendingApproval:s=>{const o=r?.pendingApprovalEntries.get(s);return o?{requestId:o}:void 0},deletePendingApproval:s=>r?.pendingApprovalEntries.delete(s)??!1,respondPermission:(s,o)=>(r&&r.respondToPermission(s,o),Promise.resolve()),onSessionBound:(s,o)=>{this.bindingStore.set(s,o)},onSessionUnbound:s=>{this.unbindSession(s).catch(o=>{h.warn(this.name,`session unbind cleanup failed: ${o instanceof Error?o.message:String(o)}`)})},cancelActiveRun:()=>(this.config.adapterType??"acp")==="agy"&&i?.adapter instanceof H?(i.adapter.cancelCurrentRun(),Promise.resolve()):i?.adapter?.cancel("")??Promise.resolve(),onModeSet:s=>{const o=this.config.adapterType??"acp";o==="codex"?this.globalConfigStore?.set(this.name,{codexModeId:s}):o==="opencode"?this.bindingStore.setModeId(e,s):T.has(o)||this.globalConfigStore?.set(this.name,{acpInitialMode:s})},onModelSet:s=>{const o=this.config.adapterType??"acp";o==="codex"?this.globalConfigStore?.set(this.name,{codexModelId:s}):o==="opencode"?this.bindingStore.setModelId(e,s):T.has(o)||this.globalConfigStore?.set(this.name,{modelId:s}),this.refreshQuotaAfterModelSwitch(e,s)}}}sessionControlSenders(e){return{sendEventAck:(i,r)=>this.aibotHandle.sendEventAck({event_id:i,session_id:r,received_at:Date.now()}),sendEventResult:(i,r,n)=>this.aibotHandle.sendEventResult({event_id:i,status:r,...n?.msg?{msg:n.msg}:{},...n?.code?{code:n.code}:{},updated_at:Date.now()}),sendLocalActionResult:(i,r,n,t,s)=>this.aibotHandle.sendLocalActionResult({action_id:i,status:r,...n?{result:n}:{},...t?{error_code:t}:{},...s?{error_msg:s}:{}},e)}}resolveBindingChannelKey(e){switch(e){case"claude":return"grix-claude";case"codex":return"codex";case"cursor":return"cursor";case"pi":return"pi";case"openhuman":return"openhuman";case"codewhale":return"codewhale";case"opencode":return"opencode";case"agy":return"acp";case"deepseek-harness":return"deepseek";case"acp":return this.config.aibot.clientType==="qwen"?"qwen":"acp";default:return e}}finalizeThinking(e,i){this.sendCtrl.finalizeThinking(e,i)}logInboundConversation(e){const i=String(e.session_id??"").trim();i&&this.conversationLog?.logInbound(i,{event_id:e.event_id,msg_id:e.msg_id,sender_id:e.sender_id,msg_type:e.msg_type,content:e.content??""})}resolveAuditProvider(){const e=this.config.adapterType??"acp";return e==="claude"||e==="codex"||e==="cursor"||e==="opencode"||e==="pi"||e==="codewhale"||e==="deepseek-harness"||e==="agy"?e:"acp"}sendAuditConfigurationError(e,i){const r=i instanceof Error?i.message:String(i),n=(()=>{const a=B(e.extra);return a.options?.enabled===!0&&a.options.scope==="turn"})(),t=i instanceof mi||i instanceof fi,s=i instanceof Si&&n,o=s?"audit_config_invalid":t?i.code:"audit_config_conflict";if(this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:o,msg:r,updated_at:Date.now()}),t||s)try{this.aibotHandle.sendAuditState(O({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:o,errorMessage:r},Date.now()))}catch{}}markAuditAdapterClosed(e,i){const n=this.pool.getSlot(i)?.adapter.takeAuditBoundary?.(e);this.auditController.markAdapterClosed(e,n)}prepareAuditedInboundEvent(e,i,r){const n=this.buildInboundEvent(e,i),t=this.bindingStore.get(e.session_id),s=t?this.resolveAgentSessionId(t):void 0,o=Number(e.created_at),a=Number.isFinite(o)&&o>0?new Date(o).toISOString():void 0,l=this.auditController.startTurn({session:r,eventId:e.event_id,userInput:e.content??"",...e.msg_id===void 0?{}:{originMsgId:e.msg_id},...a===void 0?{}:{startedAt:a},boundary:{adapterType:this.config.adapterType??"acp",...s?{providerSessionId:s}:{}}});return l&&(n.audit={enabled:!0,auditId:l.auditId,turnId:l.turnId,...r?{scope:r.options.scope,profile:r.options.profile,...r.options.retentionDays===void 0?{}:{retentionDays:r.options.retentionDays},capture:{...r.options.capture}}:{},rawProviderBody:r?.options.capture.rawProviderBody===!0}),n}buildInboundEvent(e,i){const r=Zn(this.sendCtrl.getGlobalRuntimeConfig(),i),n=_i(e.extra);return{event_id:e.event_id,session_id:e.session_id,thread_id:e.thread_id,sender_id:e.sender_id,msg_id:e.msg_id,msg_type:e.msg_type,content:e.content??"",quoted_message_id:e.quoted_message_id,context_messages_json:this.buildContextMessagesJson(e.context_messages),extra_json:n===void 0?void 0:JSON.stringify(n),connector_runtime_config:{response_delivery:r.responseDelivery,tool_events:r.toolEvents,thinking_events:r.thinkingEvents},session_type:e.session_type,created_at:e.created_at}}buildContextMessagesJson(e){if(!e)return;const i=e.filter(r=>!mn(String(r?.content??"")));if(i.length!==0)return JSON.stringify(i)}isStaleEvent(e){const i=Number(e.created_at);return!Number.isFinite(i)||i<=0?!1:Date.now()-i>Ci}setUpgradeTrigger(e){this.upgradeTrigger=e}setDaemonShutdownRequester(e){this.daemonShutdownRequester=e}setLifecycleBusyChecker(e){this.lifecycleBusyChecker=e}setLifecycleAdmissionCloser(e){this.lifecycleAdmissionCloser=e}setLifecycleAdmissionRestorer(e){this.lifecycleAdmissionRestorer=e}closeLifecycleAdmission(){this.lifecycleBarrier.setAutoOpenHandler(e=>{h.warn(this.name,`Lifecycle admission auto-reopened after ${Math.round(e/1e3)}s: a restart was expected but never happened. Admission is open again and events flow; the pending restart or upgrade did not complete.`)}),this.lifecycleBarrier.close()}openLifecycleAdmission(){this.lifecycleBarrier.open()}closeLifecycleAdmissionForRestart(){this.lifecycleAdmissionCloser?this.lifecycleAdmissionCloser():this.closeLifecycleAdmission()}setInstallAgentHandler(e){this.installAgentHandler=e}setAgentDeletedHandler(e){this.agentDeletedHandler=e}setSkillSyncHandler(e){this.skillSyncHandler=e}setShareSetHandler(e){this.shareSetHandler=e}setProviderConfigHandler(e){this.providerConfigHandler=e}setRelayStateApplyPorts(e){this.relayStateApplyPorts=e}}export{oo as AgentInstance,T as PER_SESSION_ADAPTERS};
@@ -0,0 +1 @@
1
+ import P from"node:path";import{createHash as T}from"node:crypto";import{buildDshBindingToolbarMeta as E,DEFAULT_DSH_PRESETS as H,listDshPlugins as M,listDshSkills as O,listDshProfiles as R,normalizeDshReasoningEffort as A,normalizeDshThinking as _,resolveDshAgentPreset as L,resolveDshCatalogForToolbar as y,resolveDshModeId as k,resolveDshSelectedProfileName as x}from"../adapter/deepseek-harness/index.js";import{syncDefaultSkillsToDir as B}from"../default-skills/index.js";import{GRIX_PATHS as C}from"../core/log/index.js";const G=[],K=["name","config","bindingStore","globalConfigStore"];function j(e){const o=T("sha256").update(e.config.aibot.agentId).digest("hex").slice(0,24);return P.join(C.data,"deepseek-harness",o)}function U(e,o){const i=e.globalConfigStore?.get(e.name),n=e.bindingStore.get(o),s=e.config.adapterOptions??{},f=typeof s.dshHome=="string"?s.dshHome:void 0;if(!e.bindingStore.getDshAgentPreset(o)){const l=L(i?.dshAgentPreset,H);e.bindingStore.setDshAgentPreset(o,l)}const h=e.bindingStore.getDshSelectedProfile(o),g=x({binding:h,global:i?.dshProfile,adapter:typeof s.dshProfile=="string"?s.dshProfile:void 0});h||e.bindingStore.setDshSelectedProfile(o,g);const c=j(e),p=e.bindingStore.getDshSettings(o),u=p?.providerId??i?.dshProviderId,d=y({dataRoot:c,providerId:u}),a=[p?.modelId,i?.dshModelId,d.models[0]?.id].find(l=>!!l&&d.models.some(v=>v.id===l))??d.models[0]?.id,I=k(n?.dshModeId,i?.dshModeId),t={};!n?.dshProviderId&&d.providerId&&(t.providerId=d.providerId),!n?.dshModelId&&a&&(t.modelId=a),n?.dshModeId||(t.modeId=I),n?.dshThinking||(t.thinking=_(i?.dshThinking)??"enabled"),n?.dshReasoningEffort||(t.reasoningEffort=A(i?.dshReasoningEffort)??"high"),Object.keys(t).length>0&&e.bindingStore.updateDshSettings(o,t);const r=e.bindingStore.getDshSettings(o);let S=[],m=[],b=!1;try{S=M({dshHome:f,profileName:g,enabledPluginIds:e.bindingStore.getDshEnabledPlugins(o)}),b=!1}catch{}const D=P.join(c,"dsh-session-skills");return B(D),m=O({skillsDir:D,enabledSkillIds:e.bindingStore.getDshEnabledSkills(o)}),E({agentPreset:r?.agentPreset,agentPresetLocked:e.bindingStore.isDshAgentPresetLocked(o),profileName:g,profiles:R({dshHome:f}),profileLocked:e.bindingStore.isDshProfileLocked(o),plugins:S,skills:m,pluginRestartRequired:b,providerId:r?.providerId??d.providerId,modelId:r?.modelId??a,modeId:k(e.bindingStore.get(o)?.dshModeId,i?.dshModeId),thinking:r?.thinking,reasoningEffort:r?.reasoningEffort,providers:d.providers,models:d.models})}export{K as DSH_TOOLBAR_HOST_FIELDS,G as DSH_TOOLBAR_HOST_METHODS,U as buildDshOpenedToolbarMeta,j as dshCatalogDataRoot};
@@ -0,0 +1 @@
1
+ import{log as _}from"../core/log/index.js";import{buildAuditStatePayload as d}from"../audit/core/audit-state.js";const v=[],a=["name","aibotHandle"];function m(i,e,n,t){if((t.state!=="absent"||t.error)&&_.info(i.name,`[audit-marker] event=${e.event_id} session=${e.session_id} msg=${e.msg_id??""} state=${t.state??"error"} scope=${t.options?.enabled?t.options.scope:""} error=${t.error??""}`),t.error){if(i.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),i.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"audit_config_invalid",msg:t.error,updated_at:Date.now()}),(()=>{try{if(!e.extra||typeof e.extra!="object")return!1;const o=e.extra,s=o.extra,r=o.audit??(s&&typeof s=="object"?s.audit:void 0);return!r||typeof r!="object"?!1:r.scope==="turn"}catch{return!1}})())try{i.aibotHandle.sendAuditState(d({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:"audit_config_invalid",errorMessage:t.error},Date.now()))}catch{}return!0}if(t.state==="enabled"&&n!=="claude"&&n!=="codex"&&n!=="cursor"&&n!=="opencode"&&n!=="pi"&&n!=="codewhale"&&n!=="deepseek-harness"&&n!=="agy"&&n!=="acp"){if(i.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),i.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:"audit_provider_unsupported",msg:`Audit replay is not supported for adapter: ${n}`,updated_at:Date.now()}),t.options?.enabled&&t.options.scope==="turn")try{i.aibotHandle.sendAuditState(d({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:"audit_provider_unsupported",errorMessage:`Audit replay is not supported for adapter: ${n}`},Date.now()))}catch{}return!0}return!1}export{a as INBOUND_AUDIT_GATE_HOST_FIELDS,v as INBOUND_AUDIT_GATE_HOST_METHODS,m as rejectUnusableAuditOptions};
@@ -0,0 +1 @@
1
+ import{SESSION_CONTROL_ERROR_CODES as o}from"../adapter/claude/protocol-contract.js";import{log as a}from"../core/log/index.js";const l=["discardEventTrackingState","ensureDefaultBindingForWorkspaceFreeClient","prepareAuditedInboundEvent","resolveBindingChannelKey","sendCanceledPendingEventResult"],b=["name","aibotHandle","bindingStore","deferredMgr","pendingEvents","lifecycleBarrier","auditController"];async function m(n,e,t,r,c,v){if(r&&await n.ensureDefaultBindingForWorkspaceFreeClient(e.session_id,t),r&&!n.bindingStore.get(e.session_id)?.cwd){const s=t,d=n.prepareAuditedInboundEvent(e,c,v);a.info(n.name,`[${s}] binding missing session_id=${e.session_id} event_id=${e.event_id}`);try{const i=await n.pendingEvents.append({kind:"deferred",channel:s,sessionId:String(e.session_id??"").trim(),event:d});if(n.lifecycleBarrier.isClosed()&&!i)throw new Error("pending event store unavailable during lifecycle drain")}catch(i){const _=i instanceof Error?i.message:String(i);return n.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),n.auditController.closeWithoutAdapter(e.event_id,"failed",_,{deliveryFailed:!0}),n.discardEventTrackingState(e.event_id),n.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:_,updated_at:Date.now()}),!0}if(n.pendingEvents.isCanceled(e.event_id))return await n.pendingEvents.remove(e.event_id),n.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),n.sendCanceledPendingEventResult(d,"canceled"),!0;n.deferredMgr.defer(s,String(e.session_id??"").trim(),d);const g=n.resolveBindingChannelKey(t);return n.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),n.aibotHandle.sendMsg({event_id:e.event_id,session_id:e.session_id,msg_type:1,content:"Session binding missing.",extra:{channel_data:{[g]:{sessionBinding:{status:"missing",reason:"binding_missing",error_code:o.bindingMissing}}}},quoted_message_id:e.msg_id}),!0}return!1}export{b as INBOUND_BINDING_GATE_HOST_FIELDS,l as INBOUND_BINDING_GATE_HOST_METHODS,m as interceptUnboundInboundEvent};
@@ -0,0 +1 @@
1
+ import{handleFileListAction as m,handleCreateFolderAction as p,realHomeDir as l}from"../core/files/index.js";import{getMachineName as w}from"../core/util/index.js";import{log as _}from"../core/log/index.js";const L=[],$=["config","aibotHandle","bindingStore"];async function S(o,t,n){const c=Date.now(),a=n?o.bindingStore.get(n)?.cwd:void 0,i=t.params??{},r=String(i.parent_id??"").trim(),d=Array.isArray(i.allowed_extensions)?i.allowed_extensions.filter(s=>typeof s=="string").map(s=>s.trim()).filter(s=>s.length>0):[];_.info("file-list-diag",`plugin << recv action_id=${t.action_id} session_id=${n} parent_id=${r||"<root>"} show_hidden=${!!i.show_hidden} ext_count=${d.length} bound_cwd=${a??"<none>"}`);const e=await m({parent_id:r||null,session_id:n,show_hidden:!!i.show_hidden,allowed_extensions:d},{resolveCwd:()=>a??o.config.agent.cwd??process.cwd(),fallbackDir:l()}),u=Date.now()-c,g=e.result?.files?.length??0;_.info("file-list-diag",`plugin -> reply action_id=${t.action_id} status=${e.status} elapsed=${u}ms count=${g} current_path=${e.result?.current_path??""} error_code=${e.error_code??""} error_msg=${e.error_msg??""}`),o.aibotHandle.sendLocalActionResult({action_id:t.action_id,status:e.status,...e.result?{result:{...e.result,machine_name:w()}}:{},...e.error_code?{error_code:e.error_code}:{},...e.error_msg?{error_msg:e.error_msg}:{}})}async function b(o,t,n){const c=n?o.bindingStore.get(n)?.cwd:void 0,a=String((t.params??{}).parent_id??"").trim(),i=String((t.params??{}).name??"").trim(),r=await p({parent_id:a||null,name:i,session_id:n},{resolveCwd:()=>c??o.config.agent.cwd??process.cwd(),fallbackDir:l()});o.aibotHandle.sendLocalActionResult({action_id:t.action_id,status:r.status,...r.result?{result:r.result}:{},...r.error_code?{error_code:r.error_code}:{},...r.error_msg?{error_msg:r.error_msg}:{}})}export{$ as LOCAL_ACTION_FILES_HOST_FIELDS,L as LOCAL_ACTION_FILES_HOST_METHODS,b as handleCreateFolderLocalAction,S as handleFileListLocalAction};
@@ -0,0 +1 @@
1
+ import{SESSION_CONTROL_ERROR_CODES as g,SESSION_CONTROL_VERBS as a}from"../adapter/claude/protocol-contract.js";import{log as w}from"../core/log/index.js";import{handleSessionControlLocalAction as C}from"./session-controller.js";import{isCliMissingError as _}from"./cli-install-offer.js";const R=["buildOpenedBindingResult","deferredCallbacks","ensureImportedAgentSession","ensureSlotStarted","failSessionOpen","handleCodeWhaleSessionControlLocalActionOpen","handleCodexSessionControlLocalActionOpen","handleCursorSessionControlLocalActionOpen","handleDeepSeekSessionControlLocalActionOpen","handlePiSessionControlRestartLocalAction","handleSessionControlLocalActionForPool","refreshAndPushAgyQuota","resolveCwdForBinding","sendAgyBindingCard","sessionControlCtx","sessionControlSenders","setResolvedAgentSessionId","syncOpenCodeBinding"],v=["config","aibotHandle","pool","bindingStore","sessionBindings","deferredMgr"];async function B(e,i,n){const c=e.config.adapterType??"acp",S=c==="codex",u=c==="pi",d=String((i.params??{}).verb??"").trim().toLowerCase();if(S&&d===a.open){await e.handleCodexSessionControlLocalActionOpen(i);return}if(c==="cursor"&&d===a.open){await e.handleCursorSessionControlLocalActionOpen(i);return}if(S&&d==="restart"){const t=e.bindingStore.get(n)?.cwd??"";await e.pool.removeSlot(n).catch(()=>{}),e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"ok",result:{outcome:"restarted",binding:{aibotSessionId:n,cwd:t,workerStatus:"ready"}}});return}if(u&&d===a.open){try{const o=i.params??{},t=String(o.cwd??"").trim();if(!t){e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"failed",error_code:g.cwdRequired,error_msg:"session cwd is required"});return}const r=await e.resolveCwdForBinding(t),s=String(o.agent_session_id??"").trim();e.ensureImportedAgentSession(s,r),e.bindingStore.set(n,r),e.setResolvedAgentSessionId(n,s),e.sessionBindings.set(n,r),await e.ensureSlotStarted(n).catch(l=>{if(_(l))throw l;w.warn("bridge",`pi ensureSlotStarted on local-action bind failed (non-fatal): ${l instanceof Error?l.message:String(l)}`)}),await e.deferredMgr.release(n,e.deferredCallbacks()),e.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:"ready",cwd:r}),e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"ok",result:{outcome:"opened",binding:e.buildOpenedBindingResult(n,r)}})}catch(o){e.failSessionOpen(o,{sessionId:n,eventId:i.action_id,cwd:e.bindingStore.get(n)?.cwd||String((i.params??{}).cwd??"").trim(),send:(t,r)=>e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"failed",error_code:t,error_msg:r})})}return}if(u&&d===a.restart){await e.handlePiSessionControlRestartLocalAction(i);return}if((c==="openhuman"||c==="opencode")&&d===a.open){try{const o=i.params??{},t=String(o.cwd??"").trim();if(!t){e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"failed",error_code:g.cwdRequired,error_msg:"session cwd is required"});return}const r=await e.resolveCwdForBinding(t),s=String(o.agent_session_id??"").trim();e.ensureImportedAgentSession(s,r),e.bindingStore.set(n,r),e.setResolvedAgentSessionId(n,s),e.sessionBindings.set(n,r),await e.syncOpenCodeBinding(n,r),await e.deferredMgr.release(n,e.deferredCallbacks()),e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"ok",result:{outcome:"opened",binding:e.buildOpenedBindingResult(n,r)}})}catch(o){e.failSessionOpen(o,{sessionId:n,eventId:i.action_id,cwd:e.bindingStore.get(n)?.cwd||String((i.params??{}).cwd??"").trim(),send:(t,r)=>e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"failed",error_code:t,error_msg:r})})}return}if(c==="codewhale"&&d===a.open){await e.handleCodeWhaleSessionControlLocalActionOpen(i);return}if(c==="deepseek-harness"&&d===a.open){await e.handleDeepSeekSessionControlLocalActionOpen(i);return}if(c==="acp"&&d===a.stop){const t=e.bindingStore.get(n)?.cwd??"";await e.pool.removeSlot(n).catch(()=>{}),e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"ok",result:{outcome:"stopped",binding:{aibotSessionId:n,cwd:t,workerStatus:"stopped"}}});return}try{if(d===a.open){const o=i.params??{},t=String(o.cwd??"").trim();if(!t){e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"failed",error_code:g.cwdRequired,error_msg:"session cwd is required"});return}const r=String(o.agent_session_id??"").trim();if(r){const s=await e.resolveCwdForBinding(t);e.ensureImportedAgentSession(r,s)}}await e.handleSessionControlLocalActionForPool(i)}catch(o){e.failSessionOpen(o,{sessionId:n,eventId:i.action_id,cwd:e.bindingStore.get(n)?.cwd||String((i.params??{}).cwd??"").trim(),send:(t,r)=>e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"failed",error_code:t,error_msg:r})});return}if(d===a.open){const o=i.params??{},t=await e.resolveCwdForBinding(String(o.cwd??"").trim());e.setResolvedAgentSessionId(n,String(o.agent_session_id??"").trim()),c==="agy"&&(e.bindingStore.set(n,t),e.sessionBindings.set(n,t)),await e.deferredMgr.release(n,e.deferredCallbacks()),e.aibotHandle.sendLocalActionResult({action_id:i.action_id,status:"ok",result:{outcome:"opened",binding:e.buildOpenedBindingResult(n,t)}}),(e.config.adapterType??"acp")==="agy"&&(e.sendAgyBindingCard(n,t),e.refreshAndPushAgyQuota(n,!0))}else C(i,e.sessionControlCtx(n),e.sessionControlSenders(n))}export{v as LOCAL_ACTION_SESSION_CONTROL_HOST_FIELDS,R as LOCAL_ACTION_SESSION_CONTROL_HOST_METHODS,B as dispatchSessionControlLocalAction};
@@ -0,0 +1 @@
1
+ import{AcpAdapter as s}from"../adapter/acp/index.js";import{log as m}from"../core/log/index.js";import{handleAcpSetModel as g,handleAcpSetMode as S}from"./acp-toolbar-persist.js";const C=["refreshQuotaAfterModelSwitch","sessionControlSenders"],x=["name","pool","bindingStore","globalConfigStore"];function M(e,n,r,t,l,f){if(l.kind==="set_mode"){const o=String((n.params??{}).mode_id??"");o&&(t==="cursor"?(e.bindingStore.setCursorModeId(r,o),e.globalConfigStore?.set(e.name,{cursorModeId:o})):t==="claude"?(e.bindingStore.setModeId(r,o),e.globalConfigStore?.set(e.name,{modeId:o})):t==="opencode"?(e.bindingStore.setModeId(r,o),e.globalConfigStore?.set(e.name,{modeId:o})):f(t)?t==="codex"&&e.globalConfigStore?.set(e.name,{codexModeId:o}):e.globalConfigStore?.set(e.name,{acpInitialMode:o}))}else if(l.kind==="set_model"){const o=String((n.params??{}).model_id??"").trim();if(o){t==="cursor"?(e.bindingStore.setModelId(r,o),e.globalConfigStore?.set(e.name,{modelId:o})):t==="opencode"?(e.bindingStore.setModelId(r,o),e.globalConfigStore?.set(e.name,{modelId:o})):t==="codewhale"?(e.bindingStore.setModelId(r,o),e.globalConfigStore?.set(e.name,{modelId:o})):t==="codex"?e.globalConfigStore?.set(e.name,{codexModelId:o,codexReasoningEffort:void 0}):f(t)||e.globalConfigStore?.set(e.name,{modelId:o});const d=String((n.params??{}).provider??(n.params??{}).model_provider??"").trim()||void 0;e.refreshQuotaAfterModelSwitch(r,o,d)}}else if(l.kind==="set_reasoning_effort"){const o=String((n.params??{}).reasoning_effort??(n.params??{}).reasoning_eff??(n.params??{}).effort??"");o&&e.globalConfigStore?.set(e.name,{codexReasoningEffort:o})}else if(l.kind==="set_sandbox_mode"){const o=String((n.params??{}).sandbox_mode??(n.params??{}).sandboxMode??"");if(o){const d=o==="default"?void 0:o;e.globalConfigStore?.set(e.name,{codexSandboxMode:d})}}else if(l.kind==="set_service_tier"){const o=String((n.params??{}).service_tier??(n.params??{}).serviceTier??(n.params??{}).value??"").trim();if(o){const d=o.toLowerCase()==="default"?void 0:o;e.globalConfigStore?.set(e.name,{codexServiceTier:d})}}}async function A(e,n,r,t){const l=e.sessionControlSenders(r),f=e.pool.getSlot(r)?.adapter,o={bindingStore:e.bindingStore,acpAdapter:f instanceof s?f:null,globalConfigStore:e.globalConfigStore,agentName:e.name,log:m};if(t==="set_mode"){const d=String((n.params??{}).mode_id??""),i=await S(o,r,d);if(i.status==="failed")l.sendLocalActionResult(n.action_id,"failed",void 0,i.errorCode,i.errorMsg);else{const a=f instanceof s?f.buildToolbarContext(i.result?.outcome==="mode_set"?"mode_set":"mode_set_failed"):null,c=a?{...a,...i.result}:i.result;l.sendLocalActionResult(n.action_id,"ok",c)}}else{const d=String((n.params??{}).model_id??""),i=await g(o,r,d);if(i.status==="failed")l.sendLocalActionResult(n.action_id,"failed",void 0,i.errorCode,i.errorMsg);else{const a=f instanceof s?f.buildToolbarContext(i.result?.outcome==="model_set"?"model_set":"model_set_failed"):null,c=a?{...a,...i.result}:i.result;l.sendLocalActionResult(n.action_id,"ok",c),i.result?.outcome==="model_set"&&e.refreshQuotaAfterModelSwitch(r,d)}}}export{x as LOCAL_ACTION_TOOLBAR_HOST_FIELDS,C as LOCAL_ACTION_TOOLBAR_HOST_METHODS,A as handleAcpToolbarLocalAction,M as persistToolbarSelection};
@@ -0,0 +1 @@
1
+ import u from"node:path";import{SESSION_CONTROL_ERROR_CODES as p}from"../adapter/claude/protocol-contract.js";import{reasonixStampFromSessionId as l}from"../adapter/acp/session-scanner.js";const T=["buildDshOpenedToolbarMeta"],x=["config","bindingStore","sessionScanCache","reasonixTitleScan"];function C(e,n){if(n){if(e.reasonixTitleScan){const a=l(n);if(!a)return;const t=e.reasonixTitleScan.get().filter(s=>s.stamp===a);return t.length===1?t[0].title:void 0}if((e.config.adapterType??"acp")==="cursor")return e.sessionScanCache.get().find(t=>t.sessionId===n)?.title}}function S(e,n){switch(e.config.adapterType??"acp"){case"claude":return n.claudeSessionId;case"codex":return n.codexThreadId;case"pi":return n.piSessionPath;case"codewhale":return n.codewhaleThreadId;case"agy":return n.agyConversationId;case"deepseek-harness":return n.dshProfileSessionId??n.acpSessionId;default:return n.acpSessionId}}function g(e){const n=e.config.adapterType??"acp";switch(n){case"claude":case"codex":case"pi":case"codewhale":case"deepseek-harness":return n;default:return"acp"}}function w(e,n,a){const t=String(n??"").trim(),s=String(a??"").trim();if(!t||!s)return;switch(e.config.adapterType??"acp"){case"claude":e.bindingStore.setClaudeSessionId(t,s);break;case"codex":e.bindingStore.setCodexThreadId(t,s);break;case"pi":e.bindingStore.setPiSessionPath(t,s);break;case"codewhale":e.bindingStore.setCodeWhaleThreadId(t,s);break;case"agy":e.bindingStore.setAgyConversationId(t,s);break;default:e.bindingStore.setAcpSessionId(t,s);break}e.sessionScanCache.invalidate()}function f(e){const n=String(e??"").trim();if(!n)return"";const a=u.resolve(n);return process.platform==="win32"?a.toLowerCase():a}function b(e,n,a){const t=String(n??"").trim();if(!t)return;const s=f(a);let r="";const o=e.config.adapterType??"acp";if(o==="codex"?r=e.sessionScanCache.get().find(c=>c.threadId===t)?.cwd??"":o==="claude"?r=e.sessionScanCache.get().find(c=>c.sessionId===t)?.cwd??"":o==="cursor"?r=e.sessionScanCache.get().find(c=>c.sessionId===t)?.cwd??"":o==="acp"?r=e.sessionScanCache.get().find(c=>c.sessionId===t)?.cwd??"":o==="deepseek-harness"&&(r=e.sessionScanCache.get().find(c=>c.sessionId===t)?.cwd??""),!r){for(const[,i]of e.bindingStore.entries())if(S(e,i)===t){r=i.cwd??"";break}}if(!r){const i=new Error(`agent session not found: ${t}`);throw i.sessionControlErrorCode=p.invalidAgentSession,i}const d=f(r);if(d&&s&&d!==s){const i=new Error(`agent session cwd mismatch: expected ${a}, got ${r}`);throw i.sessionControlErrorCode=p.invalidAgentSession,i}}function y(e,n,a,t="ready"){const s=e.bindingStore.get(n),r=s?String(S(e,s)??"").trim():"",o={aibotSessionId:n,providerKey:g(e),cwd:a,workerStatus:t};return r&&(o.bindingId=r,o.agentSessionId=r),(e.config.adapterType??"acp")==="deepseek-harness"&&Object.assign(o,e.buildDshOpenedToolbarMeta(n)),o}function O(e){const n=e.config.adapterType??"acp";return n==="codex"||n==="claude"||n==="acp"||n==="deepseek-harness"}export{x as SESSION_IDENTITY_HOST_FIELDS,T as SESSION_IDENTITY_HOST_METHODS,y as buildOpenedBindingResult,b as ensureImportedAgentSession,O as hasDiskScanner,f as normalizePathForCompare,g as providerKeyForAdapter,S as resolveAgentSessionId,C as resolveOrphanTitle,w as setResolvedAgentSessionId};
@@ -0,0 +1 @@
1
+ import l from"node:path";import{realpath as c,stat as S}from"node:fs/promises";import{SESSION_CONTROL_ERROR_CODES as s}from"../adapter/claude/protocol-contract.js";import{log as d}from"../core/log/index.js";import{sessionControlOpenFailure as u}from"./cli-install-offer.js";const O=["maybeOfferCliInstall","buildClaudeToolbarMeta"],g=["name","aibotHandle","pool","claudeWorkerStatus"];async function _(r){const e=String(r??"").trim();if(process.platform!=="win32"&&(/^[a-zA-Z]:[\\/]/.test(e)||/^\\\\/.test(e))){const a=new Error(`Specified path is not valid on this host: ${e}`);throw a.cwdErrorCode=s.invalidCwd,a}const t=l.resolve(e);let o;try{o=await S(t)}catch(a){const i=String(a?.code??"");if(i==="ENOENT"){const n=new Error(`Specified path does not exist: ${t}`);throw n.cwdErrorCode=s.invalidCwd,n}if(i==="EACCES"||i==="EPERM"){const n=new Error("Specified path is not accessible.");throw n.cwdErrorCode=s.invalidCwd,n}throw a}if(!o.isDirectory()){const a=new Error("Specified path is not a directory.");throw a.cwdErrorCode=s.invalidCwd,a}try{return await c(t)}catch{return t}}function h(r,e,t){const{code:o,msg:a}=u(e);return r.maybeOfferCliInstall({sessionId:t.sessionId,eventId:t.eventId,quotedMessageId:t.quotedMessageId,cwd:t.cwd,err:e}),t.send?.(o,a),{code:o,msg:a}}function p(r,e){const t=r.pool.getSlot(e);return t?t.state==="starting"?"starting":t.state==="stopped"?"stopped":t.adapter.getStatus().busy?"busy":"ready":"stopped"}function P(r,e,t){const o=p(r,e);return r.claudeWorkerStatus.set(e,o),r.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:o,cwd:t,meta:r.buildClaudeToolbarMeta(e)}),o}async function b(r,e,t=6e4){const o=await r.pool.getOrCreateSlot(e);if(!o)throw new Error("Failed to allocate session slot");o.startPromise&&(d.info(r.name,`ensureSlotStarted: awaiting startPromise for session=${e}`),await Promise.race([o.startPromise,new Promise((a,i)=>setTimeout(()=>i(new Error(`ensureSlotStarted timeout (${t}ms) session=${e}`)),t))]),d.info(r.name,`ensureSlotStarted: startPromise resolved for session=${e}`))}export{g as SESSION_OPEN_HELPERS_HOST_FIELDS,O as SESSION_OPEN_HELPERS_HOST_METHODS,b as ensureSlotStarted,h as failSessionOpen,p as getClaudeWorkerStatus,P as refreshClaudeWorkerStatusCard,_ as resolveCwdForBinding};
@@ -0,0 +1 @@
1
+ import _ from"node:path";import{stat as v}from"node:fs/promises";import{SESSION_CONTROL_ERROR_CODES as u,SESSION_CONTROL_VERBS as r}from"../adapter/claude/protocol-contract.js";import{AcpAdapter as g}from"../adapter/acp/index.js";import{log as l}from"../core/log/index.js";import{handleSessionControlCommand as c}from"./session-controller.js";const P=["deferredCallbacks","handleCodeWhaleSessionControlOpen","handleCodexSessionControlOpen","handleListSessionsTextCommand","handleOpenHumanSessionControlOpen","handlePiSessionControlOpen","handlePiSessionControlRestart","handleSessionControlCommand","handleSessionControlForPool","handleUnbindTextCommand","refreshAndPushAgyQuota","resolveAuditProvider","sendAgyBindingCard","sendAuditConfigurationError","sessionControlCtx","sessionControlSenders"],x=["aibotHandle","pool","bindingStore","sessionBindings","sessionProviderHints","sessionProviderQuotas","sessionProviderMeta","deferredMgr","auditController"];async function A(i,s,e,t,S){if(S.state!=="absent"||s.verb===r.open)try{i.auditController.resolveSession({sessionId:e.session_id,provider:i.resolveAuditProvider(),extra:e.extra})}catch(n){return i.sendAuditConfigurationError(e,n),!0}if(s.verb===r.exec)return await i.handleSessionControlCommand(s,e),!0;if(s.verb===r.listSessions)return await i.handleListSessionsTextCommand(e),!0;if(s.verb===r.unbind)return await i.handleUnbindTextCommand(e),!0;if(t==="claude")return await i.handleSessionControlCommand(s,e),!0;if(t==="codex"&&s.verb===r.open)return await i.handleCodexSessionControlOpen(s,e),!0;if(t==="pi"&&s.verb===r.open)return await i.handlePiSessionControlOpen(s,e),!0;if(t==="pi"&&s.verb===r.restart)return await i.handlePiSessionControlRestart(e),!0;if((t==="openhuman"||t==="opencode")&&s.verb===r.open)return await i.handleOpenHumanSessionControlOpen(s,e),!0;if(t==="codewhale"&&s.verb===r.open)return await i.handleCodeWhaleSessionControlOpen(s,e),!0;if(i.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()}),s.verb===r.open){const n=s.args.trim();if(!n)return i.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:u.cwdRequired,msg:"cwd is required",updated_at:Date.now()}),!0;try{const d=_.resolve(n);if(!(await v(d)).isDirectory())return i.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:u.invalidCwd,msg:`Path is not a directory: ${d}`,updated_at:Date.now()}),!0}catch(d){const o=String(d?.code??""),f=o==="ENOENT"?`Directory does not exist: ${_.resolve(n)}`:o==="EACCES"||o==="EPERM"?"Directory is not accessible":`Invalid path: ${n}`;return i.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:u.invalidCwd,msg:f,updated_at:Date.now()}),!0}}if(s.verb===r.open){const n=i.bindingStore.get(e.session_id);if(n?.cwd)try{await v(n.cwd)}catch{l.info("bridge",`Stale binding detected for session ${e.session_id}: ${n.cwd} no longer exists, clearing`),i.bindingStore.delete(e.session_id),i.sessionBindings.delete(e.session_id),i.sessionProviderHints.delete(e.session_id),i.sessionProviderQuotas.delete(e.session_id),i.sessionProviderMeta.delete(e.session_id);const d=i.pool.getSlot(e.session_id);d?.adapter instanceof g&&d.adapter.getSessionBindings().delete(e.session_id)}}if(await i.handleSessionControlForPool(s,e),t==="acp"&&s.verb===r.stop){const d=i.bindingStore.get(e.session_id)?.cwd??"";return await i.pool.removeSlot(e.session_id).catch(()=>{}),i.sessionBindings.delete(e.session_id),i.sessionProviderHints.delete(e.session_id),i.sessionProviderQuotas.delete(e.session_id),i.sessionProviderMeta.delete(e.session_id),i.aibotHandle.sendEventResult({event_id:e.event_id,status:"responded",msg:`Session worker stopped for ${d}`,updated_at:Date.now()}),!0}if(c(s,e,i.sessionControlCtx(e.session_id),{...i.sessionControlSenders(e.session_id),sendEventAck:()=>{}}),s.verb===r.open&&(await i.deferredMgr.release(e.session_id,i.deferredCallbacks()),t==="agy")){const n=i.bindingStore.get(e.session_id)?.cwd??"";n&&(i.sendAgyBindingCard(e.session_id,n),i.refreshAndPushAgyQuota(e.session_id,!0))}return!0}export{x as TEXT_COMMAND_SESSION_CONTROL_HOST_FIELDS,P as TEXT_COMMAND_SESSION_CONTROL_HOST_METHODS,A as dispatchSessionControlTextCommand};
@@ -1 +1 @@
1
- function a(o){const e=new Set([`http://127.0.0.1:${o.serverPort}`,`http://localhost:${o.serverPort}`,...o.allowedOrigins]),t=new Set([`127.0.0.1:${o.serverPort}`,`localhost:${o.serverPort}`,...o.allowedHosts]);return{validateRequest(s){const r=i(s,e);if(!r.ok)return r;const n=l(s,t);return n.ok?{ok:!0}:n}}}function i(o,e){const t=o.headers.origin;return t?e.has(t)?{ok:!0}:{ok:!1,statusCode:403,message:`Origin not allowed: ${t}`}:{ok:!0}}function l(o,e){const t=o.headers.host;return t?e.has(t)?{ok:!0}:{ok:!1,statusCode:403,message:`Host not allowed: ${t}`}:{ok:!1,statusCode:403,message:"Missing Host header"}}export{a as createSecurityPolicy};
1
+ function a(e){const t=new Set([`http://127.0.0.1:${e.serverPort}`,`http://localhost:${e.serverPort}`,...e.allowedOrigins]),o=new Set([`127.0.0.1:${e.serverPort}`,`localhost:${e.serverPort}`,...e.allowedHosts]);return{validateRequest(s){const r=i(s,t);if(!r.ok)return r;const n=l(s,o);return n.ok?{ok:!0}:n}}}function i(e,t){const o=e.headers.origin;return o?t.has(o)?{ok:!0}:{ok:!1,statusCode:403,message:`Origin not allowed: ${o}`}:{ok:!0}}function l(e,t){const o=e.headers.host;return o?t.has(o)?{ok:!0}:{ok:!1,statusCode:403,message:`Host not allowed: ${o}`}:{ok:!1,statusCode:403,message:"Missing Host header"}}export{a as createSecurityPolicy};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "grix-connector",
3
- "version": "4.3.1",
3
+ "version": "4.3.3",
4
4
  "description": "Connect local AI coding agents (Claude, Codex, Gemini, Qwen, DeepSeek, Cursor, OpenCode, Pi, OpenHuman, Reasonix) to the Grix scheduling platform. Also serves as an OpenClaw plugin for Grix channel transport.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",