grix-connector 4.16.0 → 4.16.1

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 I,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 $}from"node:path";import{fileURLToPath as x}from"node:url";import{promisify as C}from"node:util";import{log as w}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";import{unshadowInstalledDshPackages as z}from"./profile-package-shadow.js";const U=C(V),q=2*1024*1024,u="@grix/dsh-bridge",_="deepseek-harness-bridge-installer",v=2,X=1e3;class de{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),t=this.bridgeAsset(),i=this.readInstalledBridgeVersion(),n=t.version,s=L(this.identity),a=s[0]?.bridgeVersion??null,l=s[0]?.dshVersion??null,P=e?await R(e,this.options.dshHome):null;let c;return e?d(this.identity.profileRoot)?i?i!==n||this.installedBridgeContentStale(t)?c="bridge_update_required":s.length===0||a!==i||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:P,runningDshVersion:l,identity:this.identity,installedBridgeVersion:i,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 t=this.bridgeAsset();return j(this.identity,async()=>{await g(e,["--profile",this.identity.profileName,"--dump-config"],this.options.dshHome);const i=this.readInstalledBridgeVersion();if(i===t.version&&!this.installedBridgeContentStale(t))return this.status();const n=o(this.identity.dshHome,"assets","grix-dsh-bridge");y(n,{recursive:!0,mode:448});const s=this.captureInstallBackup(n,i),a=o(n,`grix-dsh-bridge-${t.version}.tgz`);p(t.tarball,a);try{if(i===t.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!==t.version)throw Object.assign(new Error(`Bridge package did not land on disk (installed ${l??"none"}, expected ${t.version})`),{code:"bridge_install_failed"});this.writeInstalledBridgeIntegrity(t.integrity),this.unshadowProfileDshPackages(e)}catch(l){try{await this.rollbackInstall(e,n,s,i)}finally{this.unshadowProfileDshPackages(e);try{f(a,{force:!0})}catch{}}throw Object.assign(new Error(`Bridge install failed: ${k(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 j(this.identity,async()=>(this.readInstalledBridgeVersion()&&await g(e,["plugin","--profile",this.identity.profileName,"remove",u],this.options.dshHome),this.status()))}async runPluginAdd(e,t){const i=["plugin","--profile",this.identity.profileName,"add",t];let n;for(let s=1;s<=v;s++)try{await g(e,i,this.options.dshHome);return}catch(a){n=a,w.warn(_,`dsh plugin add attempt ${s}/${v} failed for profile ${this.identity.profileName}
2
- ${W(a)}`),s<v&&await new Promise(l=>setTimeout(l,X))}throw n}unshadowProfileDshPackages(e){try{const t=z(this.identity.profileRoot,e);t.length>0&&w.info(_,`unshadowed profile DSH packages after bridge install: ${t.join(", ")}`)}catch(t){w.warn(_,`profile DSH package unshadow after install failed: ${t instanceof Error?t.message:t}`)}}bridgePackageRoot(){return o(this.identity.profileRoot,"node_modules","@grix","dsh-bridge")}profilePackageJsonPath(){return o(this.identity.profileRoot,"package.json")}captureInstallBackup(e,t){const i=o(e,"rollback",`${Date.now()}-${O()}`);y(i,{recursive:!0,mode:448});const n=this.bridgePackageRoot(),s=d(n);s&&I(n,o(i,"dsh-bridge"),{recursive:!0});const a=this.profilePackageJsonPath(),l=d(a);l&&p(a,o(i,"package.json"));const P=["pnpm-lock.yaml","package-lock.json","yarn.lock"];for(const c of P){const S=o(this.identity.profileRoot,c);d(S)&&p(S,o(i,c))}return b(o(i,"manifest.json"),`${JSON.stringify({priorVersion:t,hadBridge:s,hadPackageJson:l})}
3
- `,{mode:384}),{root:i,priorVersion:t,hadBridge:s,hadPackageJson:l}}async rollbackInstall(e,t,i,n){const s=n?o(t,`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(i);return}if(i.hadBridge&&d(o(i.root,"dsh-bridge"))){this.restoreFilesystemBackup(i),this.discardInstallBackup(i);return}n?i.hadPackageJson&&this.restoreFilesystemBackup(i):(await g(e,["plugin","--profile",this.identity.profileName,"remove",u],this.options.dshHome).catch(()=>{}),this.cleanHalfInstalledBridge()),this.discardInstallBackup(i)}restoreFilesystemBackup(e){const t=this.bridgePackageRoot(),i=o(e.root,"dsh-bridge");e.hadBridge&&d(i)&&(f(t,{recursive:!0,force:!0}),y(o(this.identity.profileRoot,"node_modules","@grix"),{recursive:!0,mode:448}),I(i,t,{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 t=JSON.parse(h(e,"utf8"));let i=!1;for(const n of["dependencies","devDependencies","optionalDependencies","peerDependencies"]){const s=t[n];s&&typeof s=="object"&&!Array.isArray(s)&&u in s&&(delete s[u],i=!0)}i&&b(e,`${JSON.stringify(t,null,2)}
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 t=JSON.parse(h(e,"utf8"));return typeof t.version=="string"?t.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 t=m(this.installedIntegrityPath()).mtimeMs,i=Date.parse(e.startedAt);return Number.isFinite(i)?t>i:!0}catch{return!1}}bridgeAsset(){return this.options.tarballPath?E($(this.options.tarballPath)):H()}}function le(r){if(r.readiness==="ready")return null;const e=r.identity.profileName,t=`dsh --profile ${e}`,i=`dsh does not hot-load plugin changes: stop the running profile process, then start it again with: ${t}`;let n;r.endpointCount===0?n=`Grix Bridge is installed in DSH profile "${e}", but no live Bridge endpoint is available. Start the profile with: ${t}`:r.runningBridgeVersion&&r.installedBridgeVersion&&r.runningBridgeVersion!==r.installedBridgeVersion?n=`Grix Bridge in DSH profile "${e}" is running version ${r.runningBridgeVersion}, but ${r.installedBridgeVersion} is installed on disk. ${i}`:n=`The live Grix Bridge in DSH profile "${e}" predates the Bridge content installed on disk. ${i}`;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: ${t}`,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 ${r.installedBridgeVersion??"none"}, expected ${r.bundledBridgeVersion}${r.installedBridgeVersion===r.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[r.readiness]),{code:r.readiness})}function ce(){return H().tarball}function H(){const r=[x(new URL("../../assets/dsh-bridge/",import.meta.url)),x(new URL("../../../dist/assets/dsh-bridge/",import.meta.url))].find(i=>d(o(i,"manifest.json")));if(!r)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(r,"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 t=E(o(r,e.tarball),e.bridgeVersion);if(Number(e.size)!==m(t.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!==t.integrity)throw Object.assign(new Error("Grix DSH Bridge asset integrity mismatch"),{code:"bridge_asset_invalid"});return t}function E(r,e){if(!d(r)||!m(r).isFile())throw Object.assign(new Error(`Grix DSH Bridge asset is missing: ${r}`),{code:"bridge_asset_missing"});if(m(r).size>q)throw Object.assign(new Error("Grix DSH Bridge asset exceeds the 2 MiB safety limit"),{code:"bridge_asset_invalid"});const t=e??/grix-dsh-bridge-([0-9A-Za-z.+-]+)\.tgz$/.exec(r)?.[1];if(!t)throw Object.assign(new Error("Cannot determine Grix DSH Bridge version"),{code:"bridge_asset_invalid"});const i=`sha512-${N("sha512").update(h(r)).digest("base64")}`;return{tarball:r,version:t,integrity:i}}async function j(r,e){const t=J(r);y(t,{recursive:!0,mode:448});const i=o(t,"install.lock");let n=A(i);if(n===null){let s=0;try{s=Number(h(i,"utf8").trim())}catch{}let a=!1;try{a=s===0&&Date.now()-m(i).mtimeMs>5*6e4}catch{}if(a||Number.isSafeInteger(s)&&s>0&&!Y(s)){try{f(i,{force:!0})}catch{}n=A(i)}}if(n===null)throw Object.assign(new Error(`Another Grix DSH Bridge install is active for profile ${r.profileName}`),{code:"bridge_install_busy"});try{return b(n,`${process.pid}
6
- `,"utf8"),await e()}finally{G(n);try{f(i,{force:!0})}catch{}}}function A(r){try{return T(r,"wx",384)}catch(e){if(e.code==="EEXIST")return null;throw Object.assign(new Error(`Cannot acquire Grix DSH Bridge install lock: ${k(e)}`),{code:"bridge_install_failed"})}}function Y(r){try{return process.kill(r,0),!0}catch(e){return e.code==="EPERM"}}async function ge(r,e){const t=await B(r?.trim()||"dsh");return t?R(t,e):null}async function R(r,e){try{return(await g(r,["--version"],e)).trim().split(/\s+/)[0]||null}catch(t){return w.warn(_,`dsh --version \u63A2\u6D4B\u5931\u8D25\uFF08${r}\uFF09\uFF1A${k(t)}`),null}}async function g(r,e,t){try{const i=M(r,e);return(await U(i.command,i.args,{env:{...process.env,...t?{DSH_HOME:$(t)}:{}},timeout:6e4,maxBuffer:8*1024*1024,windowsVerbatimArguments:i.windowsVerbatimArguments})).stdout}catch(i){const n=i&&typeof i=="object"?i:{};throw Object.assign(new Error(k(i)),{code:"dsh_command_failed",stderr:typeof n.stderr=="string"?D(n.stderr):void 0})}}function D(r){return r.replace(/(api[_-]?key|authorization|bearer)\s*[:=]\s*\S+/gi,"$1=[REDACTED]")}function k(r){const e=r&&typeof r=="object"?r:{};return D(String(e.stderr??e.message??r??"unknown error")).replace(/[\r\n]+/g," ").slice(0,1024)}function W(r){const e=r&&typeof r=="object"?r:{};return D(String(e.stderr??e.message??r??"unknown error")).slice(0,8*1024)}export{de as DshBridgeInstaller,ce as defaultBridgeTarball,le as errorForDshBridgeReadiness,ge as readDshCliVersion};
1
+ import{execFile as N}from"node:child_process";import{createHash as G,randomUUID as T}from"node:crypto";import{closeSync as C,copyFileSync as m,cpSync as x,existsSync as d,mkdirSync as b,openSync as M,readFileSync as f,rmSync as u,statSync as y,writeFileSync as w}from"node:fs";import{join as o,resolve as E}from"node:path";import{fileURLToPath as V}from"node:url";import{promisify as q}from"node:util";import{log as _}from"../../core/log/index.js";import{resolveShimInvocation as J}from"../../core/runtime/spawn.js";import{resolveCliPath as B}from"../../core/util/cli-probe.js";import{bridgeDiscoveryDirectory as L,discoverDshBridgeEndpoints as F,resolveDshProfileIdentity as U}from"./profile-resolver.js";import{compareDshVersions as z}from"./dsh-version.js";import{unshadowInstalledDshPackages as X}from"./profile-package-shadow.js";const Y=q(N),W=2*1024*1024,p="@grix/dsh-bridge",k="deepseek-harness-bridge-installer",P="0.2.0-rc.2";function D(t){const e=z(t,P);return e===null||e<0}const S=2,K=1e3;class ge{options;command;identity;constructor(e={}){this.options=e,this.command=e.command?.trim()||"dsh",this.identity=U({dshHome:e.dshHome,profileName:e.profileName})}async status(){const e=await B(this.command),r=this.bridgeAsset(),i=this.readInstalledBridgeVersion(),n=r.version,s=F(this.identity),a=s[0]?.bridgeVersion??null,c=s[0]?.dshVersion??null,h=e?await $(e,this.options.dshHome):null;let l;return e?D(h)?l="dsh_update_required":d(this.identity.profileRoot)?i?i!==n||this.installedBridgeContentStale(r)?l="bridge_update_required":s.length===0||D(c)||a!==i||this.runningBridgePredatesInstalledContent(s[0])?l="profile_restart_required":l="ready":l="bridge_missing":l="profile_missing":l="dsh_missing",{readiness:l,command:this.command,commandPath:e,dshVersion:h,runningDshVersion:c,identity:this.identity,installedBridgeVersion:i,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=await $(e,this.options.dshHome);if(D(r))throw Object.assign(new Error(`dsh ${r??"unknown"} at ${e} is too old: Grix requires dsh >= ${P}`),{code:"dsh_update_required"});const i=this.bridgeAsset();return A(this.identity,async()=>{await g(e,["--profile",this.identity.profileName,"--dump-config"],this.options.dshHome);const n=this.readInstalledBridgeVersion();if(n===i.version&&!this.installedBridgeContentStale(i))return this.status();const s=o(this.identity.dshHome,"assets","grix-dsh-bridge");b(s,{recursive:!0,mode:448});const a=this.captureInstallBackup(s,n),c=o(s,`grix-dsh-bridge-${i.version}.tgz`);m(i.tarball,c);try{if(n===i.version&&d(this.bridgePackageRoot())&&(await g(e,["plugin","--profile",this.identity.profileName,"remove",p],this.options.dshHome),d(this.bridgePackageRoot())))throw Object.assign(new Error(`dsh plugin remove left ${p} in place; refusing to attest an unverified reinstall`),{code:"bridge_install_failed"});await this.runPluginAdd(e,c),await g(e,["--profile",this.identity.profileName,"--dump-config"],this.options.dshHome);const h=this.readInstalledBridgeVersion();if(h!==i.version)throw Object.assign(new Error(`Bridge package did not land on disk (installed ${h??"none"}, expected ${i.version})`),{code:"bridge_install_failed"});this.writeInstalledBridgeIntegrity(i.integrity),this.unshadowProfileDshPackages(e)}catch(h){try{await this.rollbackInstall(e,s,a,n)}finally{this.unshadowProfileDshPackages(e);try{u(c,{force:!0})}catch{}}throw Object.assign(new Error(`Bridge install failed: ${v(h)}`),{code:"bridge_install_failed"})}return this.discardInstallBackup(a),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",p],this.options.dshHome),this.status()))}async runPluginAdd(e,r){const i=["plugin","--profile",this.identity.profileName,"add",r];let n;for(let s=1;s<=S;s++)try{await g(e,i,this.options.dshHome);return}catch(a){n=a,_.warn(k,`dsh plugin add attempt ${s}/${S} failed for profile ${this.identity.profileName}
2
+ ${Q(a)}`),s<S&&await new Promise(c=>setTimeout(c,K))}throw n}unshadowProfileDshPackages(e){try{const r=X(this.identity.profileRoot,e);r.length>0&&_.info(k,`unshadowed profile DSH packages after bridge install: ${r.join(", ")}`)}catch(r){_.warn(k,`profile DSH package unshadow after install failed: ${r instanceof Error?r.message:r}`)}}bridgePackageRoot(){return o(this.identity.profileRoot,"node_modules","@grix","dsh-bridge")}profilePackageJsonPath(){return o(this.identity.profileRoot,"package.json")}captureInstallBackup(e,r){const i=o(e,"rollback",`${Date.now()}-${T()}`);b(i,{recursive:!0,mode:448});const n=this.bridgePackageRoot(),s=d(n);s&&x(n,o(i,"dsh-bridge"),{recursive:!0});const a=this.profilePackageJsonPath(),c=d(a);c&&m(a,o(i,"package.json"));const h=["pnpm-lock.yaml","package-lock.json","yarn.lock"];for(const l of h){const H=o(this.identity.profileRoot,l);d(H)&&m(H,o(i,l))}return w(o(i,"manifest.json"),`${JSON.stringify({priorVersion:r,hadBridge:s,hadPackageJson:c})}
3
+ `,{mode:384}),{root:i,priorVersion:r,hadBridge:s,hadPackageJson:c}}async rollbackInstall(e,r,i,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(i);return}if(i.hadBridge&&d(o(i.root,"dsh-bridge"))){this.restoreFilesystemBackup(i),this.discardInstallBackup(i);return}n?i.hadPackageJson&&this.restoreFilesystemBackup(i):(await g(e,["plugin","--profile",this.identity.profileName,"remove",p],this.options.dshHome).catch(()=>{}),this.cleanHalfInstalledBridge()),this.discardInstallBackup(i)}restoreFilesystemBackup(e){const r=this.bridgePackageRoot(),i=o(e.root,"dsh-bridge");e.hadBridge&&d(i)&&(u(r,{recursive:!0,force:!0}),b(o(this.identity.profileRoot,"node_modules","@grix"),{recursive:!0,mode:448}),x(i,r,{recursive:!0})),e.hadPackageJson&&d(o(e.root,"package.json"))&&m(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)&&m(s,o(this.identity.profileRoot,n))}}cleanHalfInstalledBridge(){try{u(this.bridgePackageRoot(),{recursive:!0,force:!0})}catch{}const e=this.profilePackageJsonPath();if(d(e))try{const r=JSON.parse(f(e,"utf8"));let i=!1;for(const n of["dependencies","devDependencies","optionalDependencies","peerDependencies"]){const s=r[n];s&&typeof s=="object"&&!Array.isArray(s)&&p in s&&(delete s[p],i=!0)}i&&w(e,`${JSON.stringify(r,null,2)}
4
+ `,{mode:384})}catch{}}discardInstallBackup(e){try{u(e.root,{recursive:!0,force:!0})}catch{}}readInstalledBridgeVersion(){const e=o(this.bridgePackageRoot(),"package.json");try{const r=JSON.parse(f(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=f(this.installedIntegrityPath(),"utf8").trim();return e.startsWith("sha512-")?e:null}catch{return null}}writeInstalledBridgeIntegrity(e){w(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=y(this.installedIntegrityPath()).mtimeMs,i=Date.parse(e.startedAt);return Number.isFinite(i)?r>i:!0}catch{return!1}}bridgeAsset(){return this.options.tarballPath?j(E(this.options.tarballPath)):R()}}function fe(t){if(t.readiness==="ready")return null;const e=t.identity.profileName,r=`dsh --profile ${e}`,i=`dsh does not hot-load plugin changes: stop the running profile process, then start it again with: ${r}`;let n;t.endpointCount===0?n=`Grix Bridge is installed in DSH profile "${e}", but no live Bridge endpoint is available. Start the profile with: ${r}`:D(t.runningDshVersion)?n=`DSH profile "${e}" is running dsh ${t.runningDshVersion??"unknown"}, older than the required ${P} (older dsh cannot serve the opencode-go session routing header). Restart the profile on the upgraded dsh: ${i}`:t.runningBridgeVersion&&t.installedBridgeVersion&&t.runningBridgeVersion!==t.installedBridgeVersion?n=`Grix Bridge in DSH profile "${e}" is running version ${t.runningBridgeVersion}, but ${t.installedBridgeVersion} is installed on disk. ${i}`:n=`The live Grix Bridge in DSH profile "${e}" predates the Bridge content installed on disk. ${i}`;const s={dsh_missing:"dsh is not installed or not on PATH. Install DeepSeek Harness (dsh), then retry.",dsh_update_required:`dsh ${t.dshVersion??"unknown"} at ${t.commandPath??t.command} is too old: Grix requires dsh >= ${P} (earlier versions cannot send the opencode-go session routing header). Upgrade dsh and retry; if multiple dsh copies are installed (e.g. nvm and Homebrew), check PATH order so the new one wins.`,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 ${t.installedBridgeVersion??"none"}, expected ${t.bundledBridgeVersion}${t.installedBridgeVersion===t.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[t.readiness]),{code:t.readiness})}function ue(){return R().tarball}function R(){const t=[V(new URL("../../assets/dsh-bridge/",import.meta.url)),V(new URL("../../../dist/assets/dsh-bridge/",import.meta.url))].find(i=>d(o(i,"manifest.json")));if(!t)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(f(o(t,"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=j(o(t,e.tarball),e.bridgeVersion);if(Number(e.size)!==y(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 j(t,e){if(!d(t)||!y(t).isFile())throw Object.assign(new Error(`Grix DSH Bridge asset is missing: ${t}`),{code:"bridge_asset_missing"});if(y(t).size>W)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(t)?.[1];if(!r)throw Object.assign(new Error("Cannot determine Grix DSH Bridge version"),{code:"bridge_asset_invalid"});const i=`sha512-${G("sha512").update(f(t)).digest("base64")}`;return{tarball:t,version:r,integrity:i}}async function A(t,e){const r=L(t);b(r,{recursive:!0,mode:448});const i=o(r,"install.lock");let n=O(i);if(n===null){let s=0;try{s=Number(f(i,"utf8").trim())}catch{}let a=!1;try{a=s===0&&Date.now()-y(i).mtimeMs>5*6e4}catch{}if(a||Number.isSafeInteger(s)&&s>0&&!Z(s)){try{u(i,{force:!0})}catch{}n=O(i)}}if(n===null)throw Object.assign(new Error(`Another Grix DSH Bridge install is active for profile ${t.profileName}`),{code:"bridge_install_busy"});try{return w(n,`${process.pid}
6
+ `,"utf8"),await e()}finally{C(n);try{u(i,{force:!0})}catch{}}}function O(t){try{return M(t,"wx",384)}catch(e){if(e.code==="EEXIST")return null;throw Object.assign(new Error(`Cannot acquire Grix DSH Bridge install lock: ${v(e)}`),{code:"bridge_install_failed"})}}function Z(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}async function pe(t,e){const r=await B(t?.trim()||"dsh");return r?$(r,e):null}async function $(t,e){try{return(await g(t,["--version"],e)).trim().split(/\s+/)[0]||null}catch(r){return _.warn(k,`dsh --version \u63A2\u6D4B\u5931\u8D25\uFF08${t}\uFF09\uFF1A${v(r)}`),null}}async function g(t,e,r){try{const i=J(t,e);return(await Y(i.command,i.args,{env:{...process.env,...r?{DSH_HOME:E(r)}:{}},timeout:6e4,maxBuffer:8*1024*1024,windowsVerbatimArguments:i.windowsVerbatimArguments})).stdout}catch(i){const n=i&&typeof i=="object"?i:{};throw Object.assign(new Error(v(i)),{code:"dsh_command_failed",stderr:typeof n.stderr=="string"?I(n.stderr):void 0})}}function I(t){return t.replace(/(api[_-]?key|authorization|bearer)\s*[:=]\s*\S+/gi,"$1=[REDACTED]")}function v(t){const e=t&&typeof t=="object"?t:{};return I(String(e.stderr??e.message??t??"unknown error")).replace(/[\r\n]+/g," ").slice(0,1024)}function Q(t){const e=t&&typeof t=="object"?t:{};return I(String(e.stderr??e.message??t??"unknown error")).slice(0,8*1024)}export{P as DSH_MIN_SUPPORTED_VERSION,ge as DshBridgeInstaller,ue as defaultBridgeTarball,D as dshVersionTooOld,fe as errorForDshBridgeReadiness,pe as readDshCliVersion};
@@ -1,3 +1,7 @@
1
- import{createHash as E,randomUUID as x}from"node:crypto";import{EventEmitter as U}from"node:events";import{copyFileSync as ce,existsSync as W,mkdirSync as ue}from"node:fs";import{dirname as pe,join as T,resolve as G}from"node:path";import{fileURLToPath as z}from"node:url";import{log as f}from"../../core/log/index.js";import{syncDefaultSkillsToDir as ge}from"../../default-skills/index.js";import{resolveCliPath as fe}from"../../core/util/cli-probe.js";import{DshWireCapture as me}from"./audit-boundary.js";import{dsmlToolCallKey as ve,projectVisibleDsmlText as be}from"./dsml-text-filter.js";import{mapDshSessionEvent as _e,unwrapDshSessionEvent as Se}from"./event-mapper.js";import{buildDshUserPrompt as Q,extractQuotedMessageMarker as K}from"./prompt-builder.js";import{DshProcessRuntime as ke}from"./process-runtime.js";import{DshProfileRuntime as Ie}from"./profile-runtime.js";import{compareDshVersions as X}from"./dsh-version.js";import{createDshWebProfile as we}from"./profile-catalog.js";import{listDshPlugins as M,resolveDshPlugin as Te,updateDshPluginIds as Pe}from"./plugin-manager.js";import{listDshSkills as R,resolveDshSkill as ye,updateDshSkillIds as De}from"./skill-manager.js";import{prepareDshSessionPluginOverlay as Ce}from"./session-plugin-overlay.js";import{assertSelectableDshProfileName as Ee,discoverDshBridgeEndpoints as xe,listDshProfiles as Me,resolveDshConnectorProfileDataDir as Re,resolveDshHome as Ae,resolveDshSelectedProfileName as He}from"./profile-resolver.js";import{DshBridgeInstaller as A,errorForDshBridgeReadiness as H,readDshCliVersion as $e}from"./bridge-installer.js";import{ensureDshBridgeReady as Be,prepareDshProfileBridge as qe}from"./profile-supervisor.js";import{DSH_RUNTIME_ENSURE_MAX_ATTEMPTS as J,dshRuntimeEnsureBackoffMs as Fe,isRetryableDshRuntimeError as Ne}from"./runtime-ensure.js";import{runDshProtocolProbe as Le}from"./probe.js";import{buildDshSystemPrompt as je,describeDshSystemPrompt as Ve}from"./system-prompt.js";import{DshActionCoordinator as Oe}from"./toolbar-actions.js";import{adoptDshProfileModels as Ue,adoptLiveDshProviderSelection as We,buildDshToolbarMeta as Ge,DEFAULT_DSH_MAX_TOKENS as ze,DEFAULT_DSH_MODELS as Qe,DEFAULT_DSH_PRESETS as Ke,DEFAULT_DSH_PROVIDER_ID as $,DEFAULT_DSH_REASONING_EFFORT as Xe,DEFAULT_DSH_THINKING as Je,normalizeDshPresets as Ye,normalizeDshProviders as Ze,normalizeDshReasoningEffort as B,normalizeDshThinking as q,permissionModeFor as Y,resolveDshAgentPreset as Z,resolveDshModeId as et,resolveDshProviderId as tt,retainRequestedDshProvider as it}from"./toolbar-state.js";import{modelsForDshProvider as st,resolveDshCatalogForToolbar as nt,writeDshCatalogCache as ot}from"./catalog-cache.js";import{TurnCorrelator as rt}from"./turn-correlator.js";import{effectiveDshReasoningEffort as at}from"./types.js";import{getDshSessionUsageStore as dt,normalizeDshUsage as ee}from"./usage.js";import{toolCallToInvoke as lt}from"../../core/mcp/tools.js";import{isEventTool as ht}from"../../core/mcp/event-tool-executor.js";import{isDshBridgedGrixTool as ct}from"./grix-tool-bridge.js";import{DSH_GRIX_PROVIDER_ID as v,dshCredentialsLayoutFor as ut,isDshGrixProviderConfigured as te,removeDshGrixProvider as pt,writeDshGrixProvider as gt}from"./dsh-provider-config.js";const m="deepseek-harness-adapter",ie=20*6e4,se=6e4,ne=9e4,oe=180*6e4,re="0.1.0-rc.8",ae="0.1.0-rc.8";class ft extends U{adapterSessionId;cancelFn;constructor(e,t){super(),this.adapterSessionId=e,this.cancelFn=t}cancel(){return this.cancelFn()}}class ai extends U{config;callbacks;type="deepseek-harness";alive=!1;stopped=!1;runtime=null;capture=null;runtimeGeneration=0;runtimeSessionId="";applied;active=null;correlator=null;timeoutTimer=null;hardTimeoutTimer=null;activeTimeoutMs=ie;intentionalRuntimeStop=!1;personaDirty=!1;profileRevision=0;appliedProfileRevision=-1;rebuildPromise=null;runtimeStartPromise=null;contextWindow=null;reportedContextCapacity=null;providerQuota=null;settingsState="applied";settingsErrorCode=null;injectedMessageIds=new Set;auditBoundaries=new Map;actionCoordinator=new Oe;activeWireStart=0;activeUsage=de();activeUsageSeq=-1;activeCommittedUsageSeqs=new Set;permissionHandler=null;quotedMessageId;cancelRequested=!1;runtimeReadiness="unknown";bridgeCapabilities=null;profileDshVersion=null;bridgeAckCursor=0;pendingFinalBridgeAck=null;finishingTurn=!1;pendingApprovals=new Map;options;models=Qe;providers=[];presets=[...Ke];catalogProviderId;constructor(e,t,i){super(),this.config=e,this.callbacks=t,this.options=i,this.hydrateCatalogFromCache()}async start(){this.alive=!0,this.stopped=!1,this.settingsState="applied",this.settingsErrorCode=null,this.hydrateCatalogFromCache();const e=this.options.bindingStore.get(this.options.aibotSessionId);if(e?.cwd&&this.seedSessionToolbarFromGlobal(),this.syncGrixProvider(),e&&await this.options.bindingStore.flush(),this.resolveIntegrationMode()==="profile_bridge")try{const t=await this.attachSelectedProfile();await this.healBridgeUpdate(t)}catch(t){this.runtimeReadiness=String(t?.code??"bridge_probe_failed"),this.settingsErrorCode=this.runtimeReadiness}else this.runtimeReadiness="ready";this.pushToolbarMeta(),this.refreshProviderQuota(!1)}async stop(){this.stopped=!0,this.clearPendingApprovals("cancelled"),this.clearTimeout(),this.active&&this.finishActive("canceled","connector shutdown"),this.applied=void 0,this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState==="pending"&&(this.settingsState="applied"),this.settingsErrorCode=null,this.pushToolbarMeta(),await this.rebuildPromise?.catch(()=>{}),await this.stopRuntime(!0),await this.usageStore().flush(),this.alive=!1}isAlive(){return this.alive&&!this.stopped}async createSession(e){return this.options.aibotSessionId}async resumeSession(e,t){}async destroySession(e){e===this.options.aibotSessionId&&(this.usageStore().delete(e),await this.usageStore().flush(),await this.stopRuntime(!0))}sendPrompt(e){const t=new ft(e.adapterSessionId,()=>this.cancel(e.adapterSessionId));return queueMicrotask(()=>t.emit("done",{status:"failed",error:"Use deliverInboundEvent for platform prompts"})),t}async cancel(e){await this.cancelActive("user canceled")}deliverInboundEvent(e){if(!this.isAlive()){this.failEvent(e,"adapter is not alive");return}if(e.attachments_json&&e.attachments_json!=="[]"){this.failEvent(e,"DeepSeek Harness first version supports text only; attachments must be materialized in the bound workspace");return}if(this.active){this.failEvent(e,"concurrent prompt rejected");return}this.runInboundEvent(e)}deliverStopEvent(e,t){this.active&&e===this.active.inbound.event_id&&(t&&t!==this.active.inbound.session_id||this.cancelActive("user canceled"))}async handleLocalAction(e){if(!["set_model","set_mode","set_provider","set_thinking","set_reasoning_effort","set_preset","set_profile","create_profile","get_session_usage","get_rate_limits","dsh_bridge_status","dsh_install_bridge","dsh_list_plugins","dsh_enable_plugin","dsh_disable_plugin","dsh_refresh_plugins","dsh_list_skills","dsh_enable_skill","dsh_disable_skill","dsh_list_mcp","dsh_list_tools","dsh_list_jobs","dsh_list_goals","exec_approve","exec_reject","permission_approve","permission_reject"].includes(e.action_type))return{handled:!1,kind:""};const t=await this.actionCoordinator.run(e.action_id,()=>this.executeLocalAction(e));return this.callbacks.sendLocalActionResult(e.action_id,t.status,t.result,t.errorCode,t.errorMsg),{handled:!0,kind:e.action_type}}async handleExecApprovalEvent(e){const t=String(e.approval_command_id??e.approval_id??e.tool_call_id??"").trim(),i=this.pendingApprovals.get(t);return i?(clearTimeout(i.timer),this.pendingApprovals.delete(t),i.resolve(e.decision==="deny"?"rejected":"allowed-once"),{delivered:!0}):{delivered:!1,errorCode:"approval_not_found",errorMsg:"That DSH approval request is no longer pending"}}setPermissionHandler(e){this.permissionHandler=e}async ping(e){return this.isAlive()&&(!this.runtime||this.runtime.isConnected())}getStatus(){return{alive:this.isAlive()&&!!this.runtime,busy:!!this.active||this.intentionalRuntimeStop||!!this.rebuildPromise||!!this.runtimeStartPromise,backgroundBusy:!1,sessions:this.runtime?1:0,details:{runtimeGeneration:this.runtimeGeneration,runtimeSessionId:this.runtimeSessionId||void 0}}}getActiveEventIds(){return this.active?[this.active.inbound.event_id]:[]}takeAuditBoundary(e){const t=this.auditBoundaries.get(e);return this.auditBoundaries.delete(e),t}clearActiveEventForShutdown(){this.active=null,this.correlator=null,this.clearTimeout()}getMcpConfig(){return null}async hasBackgroundWork(){return this.runtime?.hasBackgroundWork()??!1}onAgentProfileChanged(){this.profileRevision+=1,this.personaDirty=!0,!this.active&&this.runtime&&this.rebuildRuntime("persona_changed")}updateProviderQuotaSnapshot(e){this.providerQuota=e??null;const t=this.options.bindingStore.get(this.options.aibotSessionId);this.callbacks.sendUpdateBindingCard(this.options.aibotSessionId,this.stopped?"stopped":this.active?"busy":"ready",t?.cwd,{provider_quota:this.providerQuota})}async probe(e={}){const t=this.resolveIntegrationMode(),i=t==="embedded_jsonrpc"?this.config.command||"dsh-jsonrpc-agent":"dsh",s=await fe(i),n=!!s;let a={ok:e.conversation!==!0,latency:null};if(n&&e.conversation===!0&&s)if(t==="embedded_jsonrpc")try{const d=await Le({command:s,args:this.config.args,cordisPath:G(this.options.cordisPath??z(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),settings:this.resolveDesiredSettings(),timeoutMs:e.timeoutMs});a={ok:!0,latency:d.latencyMs,serverName:d.serverName,serverVersion:d.serverVersion}}catch(d){a={ok:!1,latency:null,error:this.redactError(d)}}else{const d=Date.now();try{const r=new A({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),p=await Be({installer:r,autoStart:!1}),u=H(p);if(u)throw u;const o=xe(p.identity);if(o.length===0)throw Object.assign(new Error(`No live Grix Bridge endpoint in DSH profile "${p.identity.profileName}"`),{code:"bridge_missing"});a={ok:!0,latency:Date.now()-d,serverName:"grix-dsh-profile-bridge",serverVersion:o[0].bridgeVersion}}catch(r){a={ok:!1,latency:null,error:this.redactError(r)}}}return{cli:{command:i,installed:n,path:s,version:null,...n?{}:{error:{code:"cli_not_found",message:`${i} not found`}}},conversation:{attempted:e.conversation===!0,ok:a.ok,latency_ms:a.latency,...a.ok?{}:{error:{code:"conversation_failed",message:a.error??"initialize/shutdown probe failed"}}},config:{model:this.resolveDesiredSettings().modelId,base_url:this.config.env?.DEEPSEEK_BASE_URL??null,source:{model:"config",base_url:this.config.env?.DEEPSEEK_BASE_URL?"env":"unknown"},extras:{protocol:t==="profile_bridge"?"grix-dsh/1":"jsonrpc-v1",profile:this.resolveSelectedProfile(),serverName:a.serverName,serverVersion:a.serverVersion}},process:{started:!!this.runtime,alive:this.runtime?.isConnected()??!1,busy:!!this.active}}}async runInboundEvent(e){const t={inbound:e,admitted:!1,claimed:!1,turnEnded:!1,rootIdle:!1,text:"",sentText:"",seq:0,startedAt:Date.now()};this.active=t,this.correlator=new rt(t),this.activeUsage=de(),this.activeUsageSeq=-1,this.activeCommittedUsageSeqs.clear(),this.quotedMessageId=void 0,this.cancelRequested=!1,this.emit("eventStarted",e.event_id,e.session_id);try{if(await this.ensureRuntimeWithRetry(),this.cancelRequested||this.active!==t)return;this.activeWireStart=this.capture?.offset??0;const i=Q(e,this.injectedMessageIds);this.startTimeout(e.timeoutMs);const s=await this.runtime.client.prompt({sessionId:this.runtimeSessionId,contentBlocks:[{type:"text",text:i.text}]});if(!s?.messageId)throw Object.assign(new Error("session/prompt response missing messageId"),{code:"protocol_invalid_prompt_result"});this.correlator.setPromptMessageId(s.messageId)}catch(i){const s=this.redactError(i,e.content);this.finishActive(this.cancelRequested?"canceled":"failed",this.cancelRequested?"user canceled":s)}}async ensureRuntime(){if(this.stopped)throw new Error("adapter stopped");if(this.runtime)return;this.syncGrixProvider(),await this.writeGrixProviderFile();const t=this.options.bindingStore.get(this.options.aibotSessionId)?.cwd;if(!t)throw Object.assign(new Error("Session binding missing. Open a workspace first."),{code:"binding_missing"});const i=this.projectConnectorSkills();let s=this.resolveDesiredSettings();const n=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),a={};n?.modelId||(a.modelId=s.modelId),!n?.providerId&&s.providerId&&(a.providerId=s.providerId),n?.thinking||(a.thinking=s.thinking),n?.reasoningEffort||(a.reasoningEffort=s.reasoningEffort),Object.keys(a).length>0&&(this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,a),await this.options.bindingStore.flush(),s=this.resolveDesiredSettings());const d=this.callbacks.getAgentProfile(),r=this.profileRevision,p=je({...d,grixSessionId:this.options.aibotSessionId,agentId:this.callbacks.getAgentId()}),u=Ve(p);this.runtimeGeneration+=1;const o=this.resolveIntegrationMode(),l=this.resolveSelectedProfile();if(o==="profile_bridge")try{await this.ensureProfileReadyForChat(),this.pushToolbarMeta()}catch(g){throw this.settingsState="failed",this.settingsErrorCode=String(g?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.pushToolbarMeta(),g}let c=o==="profile_bridge"?this.options.bindingStore.getDshProfileBinding(this.options.aibotSessionId,l):void 0;o==="profile_bridge"&&!c&&(c={profileName:l,sessionId:_t(this.options.aibotSessionId),sessionCreated:!1,eventCursor:0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,c),await this.options.bindingStore.flush()),this.runtimeSessionId=c?.sessionId??bt(this.options.aibotSessionId,this.runtimeGeneration);const b=this.profileDataDir(l),F=G(this.options.cordisPath??z(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),N=Ce({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:l,pluginIds:s.pluginIds??[],overlayId:E("sha256").update(this.options.aibotSessionId).digest("hex").slice(0,24),baseCordisPath:F}),he=T(b,"audit-source",`${this.runtimeSessionId}.jsonl`);this.capture=new me(he);const _=o==="embedded_jsonrpc"?new ke({command:this.config.command||"dsh-jsonrpc-agent",args:this.config.args,cwd:t,cordisPath:N.embeddedCordisPath??F,home:b,sessionRoot:T(b,"sessions"),skillsDir:i,env:this.config.env,systemPrompt:p,settings:s,capture:this.capture,maxLineBytes:this.options.maxLineBytes}):new Ie({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:l,cwd:t,ownerId:`${this.callbacks.getAgentId()}:${this.options.aibotSessionId}`,sessionId:this.runtimeSessionId,resumeSession:c?.sessionCreated===!0,lastAckCursor:c?.eventCursor??0,systemPrompt:p,settings:s,skillsDir:i,pluginOverlayPath:N.bridgeOverlayPath,capture:this.capture,maxFrameBytes:this.options.maxLineBytes,onApproval:g=>this.handleBridgeApproval(g),onToolInvoke:(g,P,I)=>this.invokeGrixTool(g,P,I),onCursorAck:g=>{!c||g<=c.eventCursor||(c={...c,eventCursor:g},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,c))}});this.runtime=_,this.bridgeAckCursor=c?.eventCursor??0,this.pendingFinalBridgeAck=null,this.finishingTurn=!1,this.intentionalRuntimeStop=!1;try{const g=await _.start();if(!_.isConnected())throw Object.assign(new Error("Harness runtime disconnected immediately after initialize"),{code:"runtime_exited"});_.client?.on("notification",(S,k)=>this.onNotification(S,k)),_.client?.on("protocolError",S=>this.onProtocolError(S)),_.onExit(()=>this.onRuntimeExit()),_.client?.activateNotifications?.();let P=!1;if(o==="profile_bridge"){const S=Ze(g.providers),k=We({requestedProviderId:s.providerId,liveProviders:S,liveSelectedProvider:String(g.selectedProvider??"")});this.providers=it(S,k.providerId,this.providers),s={...s,providerId:k.providerId},P=k.persistFallback;const D=k.providerId,j=Object.prototype.hasOwnProperty.call(g,"models")?g.models:void 0,V=!!this.catalogProviderId&&!!D&&D!==this.catalogProviderId;this.models=Ue({current:this.models,fetched:j,providerChanged:V}),(j!==void 0||V)&&(this.catalogProviderId=D||this.catalogProviderId);const C=String(g.selectedModel??"");C&&C!==s.modelId&&(s={...s,modelId:C});const O=Ye(g.presets);O.length>0&&(this.presets=O);const y=String(g.selectedPreset??"");y&&y!==s.agentPreset&&(s={...s,agentPreset:y},this.options.bindingStore.getDshAgentPreset(this.options.aibotSessionId)||this.options.bindingStore.setDshAgentPreset(this.options.aibotSessionId,y))}const I=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),L=(I?.revision??0)!==s.revision,w={};!L&&P&&(I?.providerId??"")!==(s.providerId??"")&&(w.providerId=s.providerId),!L&&(I?.modelId??"")!==s.modelId&&(w.modelId=s.modelId),(w.providerId||w.modelId)&&(s.revision=this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,w)??s.revision,await this.options.bindingStore.flush(),f.warn(m,`replaced unavailable persisted DSH catalog selection provider=${s.providerId} model=${s.modelId}`)),this.applied={runtimeGeneration:this.runtimeGeneration,appliedRevision:s.revision,providerId:s.providerId??$,modelId:s.modelId,modeId:s.modeId,thinking:s.thinking,reasoningEffort:at(s)},this.runtimeReadiness="ready",this.bridgeCapabilities=g.capabilities??null,o==="profile_bridge"&&c&&!c.sessionCreated&&(c={...c,sessionCreated:!0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,c),await this.options.bindingStore.flush()),this.settingsState=this.resolveDesiredSettings().revision===s.revision?"applied":"pending",this.settingsErrorCode=null,this.appliedProfileRevision=r,this.personaDirty=this.appliedProfileRevision!==this.profileRevision,f.info(m,`runtime initialized generation=${this.runtimeGeneration} prompt_schema=${u.schemaVersion} prompt_sha256=${u.sha256} prompt_length=${u.length}`),await this.persistCatalogCache(s.providerId??$),this.pushToolbarMeta(),this.settingsState==="pending"&&!this.active&&!this.stopped&&this.rebuildRuntime("settings_changed_during_start")}catch(g){throw this.settingsState="failed",this.settingsErrorCode=String(g?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.applied=void 0,this.pushToolbarMeta(),await this.stopRuntime(!0),g}}ensureRuntimeWithRetry(){if(this.runtimeStartPromise)return this.runtimeStartPromise;const e=this.ensureRuntimeWithRetryLoop();this.runtimeStartPromise=e;const t=()=>{this.runtimeStartPromise===e&&(this.runtimeStartPromise=null)};return e.then(t,t),e}async ensureRuntimeWithRetryLoop(){let e;for(let t=1;t<=J;t++)try{await this.ensureRuntime();return}catch(i){e=i;const s=String(i?.code??"");if(this.cancelRequested||!Ne(s)||t===J)throw i;f.warn(m,`runtime ensure retry attempt=${t} code=${s||"unknown"}`),this.settingsState="pending",this.settingsErrorCode=s||"runtime_initialize_failed",this.runtimeReadiness=this.settingsErrorCode,this.pushToolbarMeta(),await this.stopRuntime(!0),await vt(Fe(t))}throw e}onNotification(e,t){const i=mt(t);if(e==="session.event"){const s=Se(t);if(!s){this.onProtocolError(new Error("malformed session.event"));return}const n=this.onSessionEvent(s);this.advanceBridgeAck(i,n);return}if(e==="session.status"){const s=t&&typeof t=="object"?t:{};if(String(s.sessionId??"")===this.runtimeSessionId){this.touchActivity(),this.correlator?.markRootStatus(String(s.status??"")),s.status==="idle"&&this.active&&this.correlator&&f.debug(m,`turn correlation idle admitted=${this.active.admitted} claimed=${this.active.claimed} ended=${this.active.turnEnded} complete=${this.correlator.complete}`);const a=!!this.correlator?.complete;a&&this.finishFromTurnOutcome(),this.advanceBridgeAck(i,a)}else i>0&&this.advanceBridgeAck(i,!1);return}if(e==="subagent.started"||e==="subagent.finished"){this.touchActivity(3);const s=t&&typeof t=="object"?t:{},n=String(s.childSessionId??s.sessionId??"");n&&this.capture?.addChild(n),this.active&&this.callbacks.sendRawEventEnvelope(this.active.inbound.event_id,this.active.inbound.session_id,{type:e,payload:s},e==="subagent.started"?"[subagent started]":"[subagent finished]"),this.advanceBridgeAck(i,!1);return}this.onProtocolError(new Error(`unknown required JSON-RPC notification: ${e}`))}onSessionEvent(e){if(!this.active||!this.correlator)return!1;this.touchActivity(e.type==="tool/call"||e.type==="tool/result"?3:1);const t=_e(e);if(t.kind==="unknown"&&!Pt(e)&&e.ignorable!==!0)return this.onProtocolError(new Error(`unknown required SessionEvent: ${e.type}`)),!1;if(e.sessionId&&e.sessionId!==this.runtimeSessionId)return!1;const i=this.correlator.accept(e);if((e.type==="agent/inbox/spliced"||e.type==="user/message"||e.type==="turn/end")&&f.debug(m,`turn correlation event=${e.type} belongs=${i} admitted=${this.active.admitted} claimed=${this.active.claimed} ended=${this.active.turnEnded}`),e.type==="agent/inbox/spliced"&&this.active.admitted){const s=Q(this.active.inbound,this.injectedMessageIds);for(const n of s.contextIds)this.injectedMessageIds.add(n);s.currentMessageId&&this.injectedMessageIds.add(s.currentMessageId)}return i?It(e)?(this.flushPendingTextAsThinking(),!1):t.kind==="text"?(t.payload?.committed===!0?(t.payload?.hasToolCall===!0?this.applyCommittedToolStepText(t.text??""):this.applyCommittedText(t.text??""),t.usage&&this.collectCommittedUsage(t.usage,Number(e.seq??e.step??Date.now()))):this.applyTextDelta(t.text??""),!1):t.kind==="thinking"?(this.thinkingEnabled()&&this.callbacks.sendThinking(this.active.inbound.event_id,this.active.inbound.session_id,t.text??""),!1):t.kind==="tool_call"?(this.flushPendingTextAsThinking(),this.toolEventsEnabled()&&this.sendRaw("tool_call",{call_id:t.callId,tool_name:t.name,tool_input:t.input},`[tool] ${t.name}`),!1):t.kind==="tool_result"?(this.toolEventsEnabled()&&this.sendRaw("tool_result",{call_id:t.callId,result:t.output},`[tool result] ${t.callId??""}`),!1):t.kind==="todo"||t.kind==="compaction"?!1:t.kind==="context"?(this.updateContextCapacity(t.payload),!1):t.kind==="usage"?(this.updateContextWindow(t.usage),!1):t.kind==="turn_end"&&this.correlator.complete?(this.finishFromTurnOutcome(),!0):!1:!1}applyTextDelta(e){this.active.pendingText=`${this.active.pendingText??""}${e}`}applyCommittedText(e){const t=this.active;if(t.pendingText=void 0,e.startsWith(t.text))t.text=e;else if(!t.text.startsWith(e)){f.warn(m,`committed assistant text diverged event=${t.inbound.event_id}`);const i=K(e).quotedMessageId;i&&(this.quotedMessageId=i),t.text=t.sentText}this.flushVisibleText(!1)}flushPendingTextAsThinking(){const e=this.active,t=e?.pendingText;!e||!t||(e.pendingText=void 0,this.thinkingEnabled()&&t.trim()&&this.callbacks.sendThinking(e.inbound.event_id,e.inbound.session_id,t),e.lastThinkingText=t)}applyCommittedToolStepText(e){const t=this.active;t&&(t.pendingText=void 0,e.trim()&&t.lastThinkingText!==e&&this.thinkingEnabled()&&(this.callbacks.sendThinking(t.inbound.event_id,t.inbound.session_id,e),t.lastThinkingText=e))}promotePendingTextToVisible(){const e=this.active,t=e?.pendingText;!e||!t||(e.pendingText=void 0,e.text+=t)}flushVisibleText(e,t={}){const i=this.active;if(!i)return;const s=K(i.text);s.quotedMessageId&&(this.quotedMessageId=s.quotedMessageId);const n=s.text.replace(/\[\[quoted_message_id:[^\]]*$/g,""),a=be(n,{finalize:t.finalizeDsml===!0||e});this.surfaceSuppressedDsmlToolCalls(a.suppressedToolCalls);const d=a.visible;this.observeVisibleTextAfterToolCall(d);let r="";d.startsWith(i.sentText)?r=d.slice(i.sentText.length):(e||t.finalizeDsml)&&(r=d),!(!r&&!e)&&(i.repliedViaTool||(i.seq+=1,this.callbacks.sendStreamChunk(i.inbound.event_id,i.inbound.session_id,r,i.seq,e,`${i.inbound.event_id}-dsh`,this.quotedMessageId)),i.sentText=d)}surfaceSuppressedDsmlToolCalls(e){if(!this.active||e.length===0)return;const t=this.active.dsmlSuppressedKeys??new Set;this.active.dsmlSuppressedKeys=t;for(const i of e){const s=ve(i);if(t.has(s)||(t.add(s),this.markToolCallAwaitingFinalText(),f.warn(m,`suppressed leaked DSML tool markup name=${i.name} event=${this.active.inbound.event_id}`),!this.toolEventsEnabled()))continue;let n=i.arguments;try{n=JSON.parse(i.arguments)}catch{}this.sendRaw("tool_call",{call_id:`dsml-${t.size}`,tool_name:i.name,tool_input:n,source:"dsml_text_leak",executed:!1},`[tool] ${i.name}`)}}markToolCallAwaitingFinalText(){const e=this.active;e&&(e.toolCallAwaitingFinalText=!0,e.toolCallVisibleTextLength=e.sentText.length)}observeVisibleTextAfterToolCall(e){const t=this.active;if(!t?.toolCallAwaitingFinalText)return;const i=t.toolCallVisibleTextLength??t.sentText.length;e.slice(i).trim().length!==0&&(t.toolCallAwaitingFinalText=!1,t.toolCallVisibleTextLength=void 0)}collectCommittedUsage(e,t){if(this.activeCommittedUsageSeqs.has(t))return;this.activeCommittedUsageSeqs.add(t);const i=ee(e);this.activeUsage.inputTokens+=i.inputTokens,this.activeUsage.outputTokens+=i.outputTokens,this.activeUsage.cacheReadInputTokens+=i.cacheReadInputTokens,this.activeUsage.cacheCreationInputTokens+=i.cacheCreationInputTokens,this.activeUsage.reasoningTokens+=i.reasoningTokens,this.activeUsageSeq=Math.max(this.activeUsageSeq,t),this.updateContextWindow(i)}updateContextWindow(e){const t=ee(e),i=this.resolveDesiredSettings(),s=this.models.find(a=>a.id===i.modelId),n=this.reportedContextCapacity??s?.contextWindow;if(n&&n>0){const a=t.inputTokens+t.cacheReadInputTokens+t.cacheCreationInputTokens;this.contextWindow={usedTokens:a,totalTokens:n,remainingTokens:Math.max(0,n-a),usedPercentage:a/n*100,remainingPercentage:Math.max(0,100-a/n*100)},this.pushToolbarMeta()}}updateContextCapacity(e){const t=Number(e?.contextWindow);if(!Number.isFinite(t)||t<=0)return;this.reportedContextCapacity=t;const i=this.contextWindow&&typeof this.contextWindow=="object"?this.contextWindow:{},s=Math.max(0,Number(i.usedTokens)||0);this.contextWindow={usedTokens:s,totalTokens:t,remainingTokens:Math.max(0,t-s),usedPercentage:s/t*100,remainingPercentage:Math.max(0,100-s/t*100)},this.pushToolbarMeta()}finishFromTurnOutcome(){if(!this.active)return;this.finishingTurn=!0;const e=this.active.outcome??"completed",t=this.active.outcomeDetail?.trim();e==="completed"?this.finishActive("responded"):e==="aborted"?this.finishActive("canceled"):e==="max-tokens"&&this.active.sentText?this.finishActive("responded","Response truncated at model token limit"):this.finishActive("failed",t?t.toLowerCase().includes(e.toLowerCase())?`Harness turn ended: ${t}`:`Harness turn ended: ${e}: ${t}`:`Harness turn ended: ${e}`)}finishActive(e,t){const i=this.active;if(!i)return;let s=this.cancelRequested?"canceled":e,n=this.cancelRequested?"user canceled":t;this.finishingTurn=!0,this.clearTimeout(),this.promotePendingTextToVisible(),this.flushVisibleText(!1,{finalizeDsml:!0}),s==="responded"&&i.toolCallAwaitingFinalText&&!i.repliedViaTool&&(s="failed",n="DeepSeek Harness ended after a tool call without returning final assistant text",f.warn(m,`${n} event=${i.inbound.event_id}`)),i.text=i.sentText;const a=s==="failed"&&!!n?.trim();a&&(i.text+=`
1
+ import{createHash as x,randomUUID as D}from"node:crypto";import{EventEmitter as V}from"node:events";import{copyFileSync as ue,existsSync as W,mkdirSync as pe}from"node:fs";import{dirname as ge,join as T,resolve as G}from"node:path";import{fileURLToPath as Q}from"node:url";import{log as p}from"../../core/log/index.js";import{syncDefaultSkillsToDir as fe}from"../../default-skills/index.js";import{resolveCliPath as me}from"../../core/util/cli-probe.js";import{DshWireCapture as ve}from"./audit-boundary.js";import{dsmlToolCallKey as be,projectVisibleDsmlText as _e}from"./dsml-text-filter.js";import{mapDshSessionEvent as Se,unwrapDshSessionEvent as ke}from"./event-mapper.js";import{buildDshUserPrompt as z,extractQuotedMessageMarker as K}from"./prompt-builder.js";import{DshProcessRuntime as Ie}from"./process-runtime.js";import{DshProfileRuntime as we}from"./profile-runtime.js";import{compareDshVersions as X}from"./dsh-version.js";import{createDshWebProfile as Te}from"./profile-catalog.js";import{listDshPlugins as R,resolveDshPlugin as ye,updateDshPluginIds as Pe}from"./plugin-manager.js";import{listDshSkills as M,resolveDshSkill as Ee,updateDshSkillIds as Ce}from"./skill-manager.js";import{prepareDshSessionPluginOverlay as xe}from"./session-plugin-overlay.js";import{assertSelectableDshProfileName as De,discoverDshBridgeEndpoints as Re,listDshProfiles as Me,resolveDshConnectorProfileDataDir as Ae,resolveDshHome as He,resolveDshSelectedProfileName as $e}from"./profile-resolver.js";import{DshBridgeInstaller as A,errorForDshBridgeReadiness as H,readDshCliVersion as Be}from"./bridge-installer.js";import{ensureDshBridgeReady as qe,prepareDshProfileBridge as Fe}from"./profile-supervisor.js";import{DSH_RUNTIME_ENSURE_MAX_ATTEMPTS as J,dshRuntimeEnsureBackoffMs as Ne,isRetryableDshRuntimeError as Ue}from"./runtime-ensure.js";import{runDshProtocolProbe as je}from"./probe.js";import{buildDshSystemPrompt as Le,describeDshSystemPrompt as Oe}from"./system-prompt.js";import{DshActionCoordinator as Ve}from"./toolbar-actions.js";import{adoptDshProfileModels as We,adoptLiveDshProviderSelection as Ge,buildDshToolbarMeta as Qe,DEFAULT_DSH_MAX_TOKENS as ze,DEFAULT_DSH_MODELS as Ke,DEFAULT_DSH_PRESETS as Xe,DEFAULT_DSH_PROVIDER_ID as $,DEFAULT_DSH_REASONING_EFFORT as Je,DEFAULT_DSH_THINKING as Ye,normalizeDshPresets as Ze,normalizeDshProviders as et,normalizeDshReasoningEffort as B,normalizeDshThinking as q,permissionModeFor as Y,resolveDshAgentPreset as Z,resolveDshModeId as tt,resolveDshProviderId as it,retainRequestedDshProvider as st}from"./toolbar-state.js";import{modelsForDshProvider as nt,resolveDshCatalogForToolbar as ot,writeDshCatalogCache as rt}from"./catalog-cache.js";import{TurnCorrelator as ee}from"./turn-correlator.js";import{effectiveDshReasoningEffort as at}from"./types.js";import{getDshSessionUsageStore as dt,normalizeDshUsage as te}from"./usage.js";import{toolCallToInvoke as lt}from"../../core/mcp/tools.js";import{isEventTool as ht}from"../../core/mcp/event-tool-executor.js";import{isDshBridgedGrixTool as ct}from"./grix-tool-bridge.js";import{DSH_GRIX_PROVIDER_ID as v,dshCredentialsLayoutFor as ut,isDshGrixProviderConfigured as ie,removeDshGrixProvider as pt,writeDshGrixProvider as gt}from"./dsh-provider-config.js";const g="deepseek-harness-adapter",se=20*6e4,ne=6e4,oe=9e4,re=180*6e4,ae="0.1.0-rc.8",de="0.1.0-rc.8";class ft extends V{adapterSessionId;cancelFn;constructor(e,t){super(),this.adapterSessionId=e,this.cancelFn=t}cancel(){return this.cancelFn()}}class ai extends V{config;callbacks;type="deepseek-harness";alive=!1;stopped=!1;runtime=null;replaySupersededRuntimes=new WeakSet;capture=null;runtimeGeneration=0;runtimeSessionId="";applied;active=null;correlator=null;warnedUnknownNonSurfaceEvents=new Set;noticedUnknownSurfaceTypes=new Set;timeoutTimer=null;hardTimeoutTimer=null;activeTimeoutMs=se;intentionalRuntimeStop=!1;personaDirty=!1;profileRevision=0;appliedProfileRevision=-1;rebuildPromise=null;runtimeStartPromise=null;contextWindow=null;reportedContextCapacity=null;providerQuota=null;settingsState="applied";settingsErrorCode=null;injectedMessageIds=new Set;auditBoundaries=new Map;actionCoordinator=new Ve;activeWireStart=0;activeUsage=le();activeUsageSeq=-1;activeCommittedUsageSeqs=new Set;permissionHandler=null;quotedMessageId;cancelRequested=!1;runtimeReadiness="unknown";bridgeCapabilities=null;profileDshVersion=null;bridgeAckCursor=0;pendingFinalBridgeAck=null;finishingTurn=!1;pendingApprovals=new Map;options;models=Ke;providers=[];presets=[...Xe];catalogProviderId;constructor(e,t,i){super(),this.config=e,this.callbacks=t,this.options=i,this.hydrateCatalogFromCache()}async start(){this.alive=!0,this.stopped=!1,this.settingsState="applied",this.settingsErrorCode=null,this.hydrateCatalogFromCache();const e=this.options.bindingStore.get(this.options.aibotSessionId);if(e?.cwd&&this.seedSessionToolbarFromGlobal(),this.syncGrixProvider(),e&&await this.options.bindingStore.flush(),this.resolveIntegrationMode()==="profile_bridge")try{const t=await this.attachSelectedProfile();await this.healBridgeUpdate(t)}catch(t){this.runtimeReadiness=String(t?.code??"bridge_probe_failed"),this.settingsErrorCode=this.runtimeReadiness}else this.runtimeReadiness="ready";this.pushToolbarMeta(),this.refreshProviderQuota(!1)}async stop(){this.stopped=!0,this.clearPendingApprovals("cancelled"),this.clearTimeout(),this.active&&this.finishActive("canceled","connector shutdown"),this.applied=void 0,this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState==="pending"&&(this.settingsState="applied"),this.settingsErrorCode=null,this.pushToolbarMeta(),await this.rebuildPromise?.catch(()=>{}),await this.stopRuntime(!0),await this.usageStore().flush(),this.alive=!1}isAlive(){return this.alive&&!this.stopped}async createSession(e){return this.options.aibotSessionId}async resumeSession(e,t){}async destroySession(e){e===this.options.aibotSessionId&&(this.usageStore().delete(e),await this.usageStore().flush(),await this.stopRuntime(!0))}sendPrompt(e){const t=new ft(e.adapterSessionId,()=>this.cancel(e.adapterSessionId));return queueMicrotask(()=>t.emit("done",{status:"failed",error:"Use deliverInboundEvent for platform prompts"})),t}async cancel(e){await this.cancelActive("user canceled")}deliverInboundEvent(e){if(!this.isAlive()){this.failEvent(e,"adapter is not alive");return}if(e.attachments_json&&e.attachments_json!=="[]"){this.failEvent(e,"DeepSeek Harness first version supports text only; attachments must be materialized in the bound workspace");return}if(this.active){this.failEvent(e,"concurrent prompt rejected");return}this.runInboundEvent(e)}deliverStopEvent(e,t){this.active&&e===this.active.inbound.event_id&&(t&&t!==this.active.inbound.session_id||this.cancelActive("user canceled"))}async handleLocalAction(e){if(!["set_model","set_mode","set_provider","set_thinking","set_reasoning_effort","set_preset","set_profile","create_profile","get_session_usage","get_rate_limits","dsh_bridge_status","dsh_install_bridge","dsh_list_plugins","dsh_enable_plugin","dsh_disable_plugin","dsh_refresh_plugins","dsh_list_skills","dsh_enable_skill","dsh_disable_skill","dsh_list_mcp","dsh_list_tools","dsh_list_jobs","dsh_list_goals","exec_approve","exec_reject","permission_approve","permission_reject"].includes(e.action_type))return{handled:!1,kind:""};const t=await this.actionCoordinator.run(e.action_id,()=>this.executeLocalAction(e));return this.callbacks.sendLocalActionResult(e.action_id,t.status,t.result,t.errorCode,t.errorMsg),{handled:!0,kind:e.action_type}}async handleExecApprovalEvent(e){const t=String(e.approval_command_id??e.approval_id??e.tool_call_id??"").trim(),i=this.pendingApprovals.get(t);return i?(clearTimeout(i.timer),this.pendingApprovals.delete(t),i.resolve(e.decision==="deny"?"rejected":"allowed-once"),{delivered:!0}):{delivered:!1,errorCode:"approval_not_found",errorMsg:"That DSH approval request is no longer pending"}}setPermissionHandler(e){this.permissionHandler=e}async ping(e){return this.isAlive()&&(!this.runtime||this.runtime.isConnected())}getStatus(){return{alive:this.isAlive()&&!!this.runtime,busy:!!this.active||this.intentionalRuntimeStop||!!this.rebuildPromise||!!this.runtimeStartPromise,backgroundBusy:!1,sessions:this.runtime?1:0,details:{runtimeGeneration:this.runtimeGeneration,runtimeSessionId:this.runtimeSessionId||void 0}}}getActiveEventIds(){return this.active?[this.active.inbound.event_id]:[]}takeAuditBoundary(e){const t=this.auditBoundaries.get(e);return this.auditBoundaries.delete(e),t}clearActiveEventForShutdown(){this.active=null,this.correlator=null,this.clearTimeout()}getMcpConfig(){return null}async hasBackgroundWork(){return this.runtime?.hasBackgroundWork()??!1}onAgentProfileChanged(){this.profileRevision+=1,this.personaDirty=!0,!this.active&&this.runtime&&this.rebuildRuntime("persona_changed")}updateProviderQuotaSnapshot(e){this.providerQuota=e??null;const t=this.options.bindingStore.get(this.options.aibotSessionId);this.callbacks.sendUpdateBindingCard(this.options.aibotSessionId,this.stopped?"stopped":this.active?"busy":"ready",t?.cwd,{provider_quota:this.providerQuota})}async probe(e={}){const t=this.resolveIntegrationMode(),i=t==="embedded_jsonrpc"?this.config.command||"dsh-jsonrpc-agent":"dsh",s=await me(i),n=!!s;let a={ok:e.conversation!==!0,latency:null};if(n&&e.conversation===!0&&s)if(t==="embedded_jsonrpc")try{const d=await je({command:s,args:this.config.args,cordisPath:G(this.options.cordisPath??Q(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),settings:this.resolveDesiredSettings(),timeoutMs:e.timeoutMs});a={ok:!0,latency:d.latencyMs,serverName:d.serverName,serverVersion:d.serverVersion}}catch(d){a={ok:!1,latency:null,error:this.redactError(d)}}else{const d=Date.now();try{const r=new A({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),f=await qe({installer:r,autoStart:!1}),u=H(f);if(u)throw u;const o=Re(f.identity);if(o.length===0)throw Object.assign(new Error(`No live Grix Bridge endpoint in DSH profile "${f.identity.profileName}"`),{code:"bridge_missing"});a={ok:!0,latency:Date.now()-d,serverName:"grix-dsh-profile-bridge",serverVersion:o[0].bridgeVersion}}catch(r){a={ok:!1,latency:null,error:this.redactError(r)}}}return{cli:{command:i,installed:n,path:s,version:null,...n?{}:{error:{code:"cli_not_found",message:`${i} not found`}}},conversation:{attempted:e.conversation===!0,ok:a.ok,latency_ms:a.latency,...a.ok?{}:{error:{code:"conversation_failed",message:a.error??"initialize/shutdown probe failed"}}},config:{model:this.resolveDesiredSettings().modelId,base_url:this.config.env?.DEEPSEEK_BASE_URL??null,source:{model:"config",base_url:this.config.env?.DEEPSEEK_BASE_URL?"env":"unknown"},extras:{protocol:t==="profile_bridge"?"grix-dsh/1":"jsonrpc-v1",profile:this.resolveSelectedProfile(),serverName:a.serverName,serverVersion:a.serverVersion}},process:{started:!!this.runtime,alive:this.runtime?.isConnected()??!1,busy:!!this.active}}}async runInboundEvent(e){const t={inbound:e,admitted:!1,claimed:!1,turnEnded:!1,rootIdle:!1,text:"",sentText:"",seq:0,startedAt:Date.now()};this.active=t,this.correlator=new ee(t),this.activeUsage=le(),this.activeUsageSeq=-1,this.activeCommittedUsageSeqs.clear(),this.noticedUnknownSurfaceTypes.clear(),this.quotedMessageId=void 0,this.cancelRequested=!1,this.emit("eventStarted",e.event_id,e.session_id);try{await this.submitActivePrompt(t)}catch(i){await this.handlePromptSubmissionFailure(t,i)}}async submitActivePrompt(e){const t=e.inbound;if(await this.ensureRuntimeWithRetry(),this.cancelRequested||this.active!==e)return;this.activeWireStart=this.capture?.offset??0;const i=z(t,this.injectedMessageIds);this.startTimeout(t.timeoutMs);const s=await this.runtime.client.prompt({sessionId:this.runtimeSessionId,contentBlocks:[{type:"text",text:i.text}]});if(!s?.messageId)throw Object.assign(new Error("session/prompt response missing messageId"),{code:"protocol_invalid_prompt_result"});this.correlator.setPromptMessageId(s.messageId)}isPromptUnaccepted(e){return!e.messageId&&!e.admitted&&!e.claimed&&!e.turnEnded&&!e.text&&!e.sentText}canReplayAfterRuntimeExit(e){return!(e.runtimeExitReplayed||!this.isPromptUnaccepted(e)||this.runtime?.isConnected())}async handlePromptSubmissionFailure(e,t){const i=e.inbound;if(!this.cancelRequested&&!this.stopped&&this.active===e&&this.canReplayAfterRuntimeExit(e)){e.runtimeExitReplayed=!0,p.warn(g,`Harness runtime exited before accepting prompt ${i.event_id}; replaying the prompt once on a fresh runtime`);const n=this.runtime;n&&this.replaySupersededRuntimes.add(n),await this.stopRuntime(!0),this.correlator=new ee(e);try{await this.submitActivePrompt(e);return}catch(a){const d=this.runtime;if(d&&this.replaySupersededRuntimes.add(d),await this.stopRuntime(!0),this.active!==e||this.stopped)return;const r=this.redactError(a,i.content);this.finishActive(this.cancelRequested?"canceled":"failed",this.cancelRequested?"user canceled":`Harness runtime exited; prompt replay failed: ${r}`),this.cancelRequested||this.emit("exit",1);return}}const s=this.redactError(t,i.content);this.finishActive(this.cancelRequested?"canceled":"failed",this.cancelRequested?"user canceled":s)}async ensureRuntime(){if(this.stopped)throw new Error("adapter stopped");if(this.runtime)return;this.syncGrixProvider(),await this.writeGrixProviderFile();const t=this.options.bindingStore.get(this.options.aibotSessionId)?.cwd;if(!t)throw Object.assign(new Error("Session binding missing. Open a workspace first."),{code:"binding_missing"});const i=this.projectConnectorSkills();let s=this.resolveDesiredSettings();const n=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),a={};n?.modelId||(a.modelId=s.modelId),!n?.providerId&&s.providerId&&(a.providerId=s.providerId),n?.thinking||(a.thinking=s.thinking),n?.reasoningEffort||(a.reasoningEffort=s.reasoningEffort),Object.keys(a).length>0&&(this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,a),await this.options.bindingStore.flush(),s=this.resolveDesiredSettings());const d=this.callbacks.getAgentProfile(),r=this.profileRevision,f=Le({...d,grixSessionId:this.options.aibotSessionId,agentId:this.callbacks.getAgentId()}),u=Oe(f);this.runtimeGeneration+=1;const o=this.resolveIntegrationMode(),l=this.resolveSelectedProfile();if(o==="profile_bridge")try{await this.ensureProfileReadyForChat(),this.pushToolbarMeta()}catch(m){throw this.settingsState="failed",this.settingsErrorCode=String(m?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.pushToolbarMeta(),m}let c=o==="profile_bridge"?this.options.bindingStore.getDshProfileBinding(this.options.aibotSessionId,l):void 0;o==="profile_bridge"&&!c&&(c={profileName:l,sessionId:_t(this.options.aibotSessionId),sessionCreated:!1,eventCursor:0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,c),await this.options.bindingStore.flush()),this.runtimeSessionId=c?.sessionId??bt(this.options.aibotSessionId,this.runtimeGeneration);const b=this.profileDataDir(l),F=G(this.options.cordisPath??Q(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),N=xe({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:l,pluginIds:s.pluginIds??[],overlayId:x("sha256").update(this.options.aibotSessionId).digest("hex").slice(0,24),baseCordisPath:F}),ce=T(b,"audit-source",`${this.runtimeSessionId}.jsonl`);this.capture=new ve(ce);const _=o==="embedded_jsonrpc"?new Ie({command:this.config.command||"dsh-jsonrpc-agent",args:this.config.args,cwd:t,cordisPath:N.embeddedCordisPath??F,home:b,sessionRoot:T(b,"sessions"),skillsDir:i,env:this.config.env,systemPrompt:f,settings:s,capture:this.capture,maxLineBytes:this.options.maxLineBytes}):new we({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:l,cwd:t,ownerId:`${this.callbacks.getAgentId()}:${this.options.aibotSessionId}`,sessionId:this.runtimeSessionId,resumeSession:c?.sessionCreated===!0,lastAckCursor:c?.eventCursor??0,systemPrompt:f,settings:s,skillsDir:i,pluginOverlayPath:N.bridgeOverlayPath,capture:this.capture,maxFrameBytes:this.options.maxLineBytes,onApproval:m=>this.handleBridgeApproval(m),onToolInvoke:(m,y,I)=>this.invokeGrixTool(m,y,I),onCursorAck:m=>{!c||m<=c.eventCursor||(c={...c,eventCursor:m},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,c))}});this.runtime=_,this.bridgeAckCursor=c?.eventCursor??0,this.pendingFinalBridgeAck=null,this.finishingTurn=!1,this.intentionalRuntimeStop=!1;try{const m=await _.start();if(!_.isConnected())throw Object.assign(new Error("Harness runtime disconnected immediately after initialize"),{code:"runtime_exited"});_.client?.on("notification",(S,k)=>this.onNotification(S,k)),_.client?.on("protocolError",S=>this.onProtocolError(S)),_.onExit(()=>this.onRuntimeExit(_)),_.client?.activateNotifications?.();let y=!1;if(o==="profile_bridge"){const S=et(m.providers),k=Ge({requestedProviderId:s.providerId,liveProviders:S,liveSelectedProvider:String(m.selectedProvider??"")});this.providers=st(S,k.providerId,this.providers),s={...s,providerId:k.providerId},y=k.persistFallback;const E=k.providerId,j=Object.prototype.hasOwnProperty.call(m,"models")?m.models:void 0,L=!!this.catalogProviderId&&!!E&&E!==this.catalogProviderId;this.models=We({current:this.models,fetched:j,providerChanged:L}),(j!==void 0||L)&&(this.catalogProviderId=E||this.catalogProviderId);const C=String(m.selectedModel??"");C&&C!==s.modelId&&(s={...s,modelId:C});const O=Ze(m.presets);O.length>0&&(this.presets=O);const P=String(m.selectedPreset??"");P&&P!==s.agentPreset&&(s={...s,agentPreset:P},this.options.bindingStore.getDshAgentPreset(this.options.aibotSessionId)||this.options.bindingStore.setDshAgentPreset(this.options.aibotSessionId,P))}const I=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),U=(I?.revision??0)!==s.revision,w={};!U&&y&&(I?.providerId??"")!==(s.providerId??"")&&(w.providerId=s.providerId),!U&&(I?.modelId??"")!==s.modelId&&(w.modelId=s.modelId),(w.providerId||w.modelId)&&(s.revision=this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,w)??s.revision,await this.options.bindingStore.flush(),p.warn(g,`replaced unavailable persisted DSH catalog selection provider=${s.providerId} model=${s.modelId}`)),this.applied={runtimeGeneration:this.runtimeGeneration,appliedRevision:s.revision,providerId:s.providerId??$,modelId:s.modelId,modeId:s.modeId,thinking:s.thinking,reasoningEffort:at(s)},this.runtimeReadiness="ready",this.bridgeCapabilities=m.capabilities??null,o==="profile_bridge"&&c&&!c.sessionCreated&&(c={...c,sessionCreated:!0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,c),await this.options.bindingStore.flush()),this.settingsState=this.resolveDesiredSettings().revision===s.revision?"applied":"pending",this.settingsErrorCode=null,this.appliedProfileRevision=r,this.personaDirty=this.appliedProfileRevision!==this.profileRevision,p.info(g,`runtime initialized generation=${this.runtimeGeneration} prompt_schema=${u.schemaVersion} prompt_sha256=${u.sha256} prompt_length=${u.length}`),await this.persistCatalogCache(s.providerId??$),this.pushToolbarMeta(),this.settingsState==="pending"&&!this.active&&!this.stopped&&this.rebuildRuntime("settings_changed_during_start")}catch(m){throw this.settingsState="failed",this.settingsErrorCode=String(m?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.applied=void 0,this.pushToolbarMeta(),await this.stopRuntime(!0),m}}ensureRuntimeWithRetry(){if(this.runtimeStartPromise)return this.runtimeStartPromise;const e=this.ensureRuntimeWithRetryLoop();this.runtimeStartPromise=e;const t=()=>{this.runtimeStartPromise===e&&(this.runtimeStartPromise=null)};return e.then(t,t),e}async ensureRuntimeWithRetryLoop(){let e;for(let t=1;t<=J;t++)try{await this.ensureRuntime();return}catch(i){e=i;const s=String(i?.code??"");if(this.cancelRequested||!Ue(s)||t===J)throw i;p.warn(g,`runtime ensure retry attempt=${t} code=${s||"unknown"}`),this.settingsState="pending",this.settingsErrorCode=s||"runtime_initialize_failed",this.runtimeReadiness=this.settingsErrorCode,this.pushToolbarMeta(),await this.stopRuntime(!0),await vt(Ne(t))}throw e}onNotification(e,t){const i=mt(t);if(e==="session.event"){const s=ke(t);if(!s){this.onProtocolError(new Error("malformed session.event"));return}const n=this.onSessionEvent(s);this.advanceBridgeAck(i,n);return}if(e==="session.status"){const s=t&&typeof t=="object"?t:{};if(String(s.sessionId??"")===this.runtimeSessionId){this.touchActivity(),this.correlator?.markRootStatus(String(s.status??"")),s.status==="idle"&&this.active&&this.correlator&&p.debug(g,`turn correlation idle admitted=${this.active.admitted} claimed=${this.active.claimed} ended=${this.active.turnEnded} complete=${this.correlator.complete}`);const a=!!this.correlator?.complete;a&&this.finishFromTurnOutcome(),this.advanceBridgeAck(i,a)}else i>0&&this.advanceBridgeAck(i,!1);return}if(e==="subagent.started"||e==="subagent.finished"){this.touchActivity(3);const s=t&&typeof t=="object"?t:{},n=String(s.childSessionId??s.sessionId??"");n&&this.capture?.addChild(n),this.active&&this.callbacks.sendRawEventEnvelope(this.active.inbound.event_id,this.active.inbound.session_id,{type:e,payload:s},e==="subagent.started"?"[subagent started]":"[subagent finished]"),this.advanceBridgeAck(i,!1);return}this.onProtocolError(new Error(`unknown required JSON-RPC notification: ${e}`))}onSessionEvent(e){if(!this.active||!this.correlator)return!1;this.touchActivity(e.type==="tool/call"||e.type==="tool/result"?3:1);const t=Se(e);if(t.kind==="unknown"&&!yt(e)&&e.ignorable!==!0)return e.surfaceOp===void 0?(this.warnedUnknownNonSurfaceEvents.has(e.type)||(this.warnedUnknownNonSurfaceEvents.add(e.type),p.warn(g,`ignoring unknown non-surface SessionEvent: ${e.type}`)),!1):(this.surfaceUnknownEventNotice(e.type),!1);if(e.sessionId&&e.sessionId!==this.runtimeSessionId)return!1;const i=this.correlator.accept(e);if((e.type==="agent/inbox/spliced"||e.type==="user/message"||e.type==="turn/end")&&p.debug(g,`turn correlation event=${e.type} belongs=${i} admitted=${this.active.admitted} claimed=${this.active.claimed} ended=${this.active.turnEnded}`),e.type==="agent/inbox/spliced"&&this.active.admitted){const s=z(this.active.inbound,this.injectedMessageIds);for(const n of s.contextIds)this.injectedMessageIds.add(n);s.currentMessageId&&this.injectedMessageIds.add(s.currentMessageId)}return i?It(e)?(this.flushPendingTextAsThinking(),!1):t.kind==="text"?(t.payload?.committed===!0?(t.payload?.hasToolCall===!0?this.applyCommittedToolStepText(t.text??""):this.applyCommittedText(t.text??""),t.usage&&this.collectCommittedUsage(t.usage,Number(e.seq??e.step??Date.now()))):this.applyTextDelta(t.text??""),!1):t.kind==="thinking"?(this.thinkingEnabled()&&this.callbacks.sendThinking(this.active.inbound.event_id,this.active.inbound.session_id,t.text??""),!1):t.kind==="tool_call"?(this.flushPendingTextAsThinking(),this.toolEventsEnabled()&&this.sendRaw("tool_call",{call_id:t.callId,tool_name:t.name,tool_input:t.input},`[tool] ${t.name}`),!1):t.kind==="tool_result"?(this.toolEventsEnabled()&&this.sendRaw("tool_result",{call_id:t.callId,result:t.output},`[tool result] ${t.callId??""}`),!1):t.kind==="todo"||t.kind==="compaction"?!1:t.kind==="context"?(this.updateContextCapacity(t.payload),!1):t.kind==="usage"?(this.updateContextWindow(t.usage),!1):t.kind==="turn_end"&&this.correlator.complete?(this.finishFromTurnOutcome(),!0):!1:!1}applyTextDelta(e){this.active.pendingText=`${this.active.pendingText??""}${e}`}applyCommittedText(e){const t=this.active;if(t.pendingText=void 0,e.startsWith(t.text))t.text=e;else if(!t.text.startsWith(e)){p.warn(g,`committed assistant text diverged event=${t.inbound.event_id}`);const i=K(e).quotedMessageId;i&&(this.quotedMessageId=i),t.text=t.sentText}this.flushVisibleText(!1)}flushPendingTextAsThinking(){const e=this.active,t=e?.pendingText;!e||!t||(e.pendingText=void 0,this.thinkingEnabled()&&t.trim()&&this.callbacks.sendThinking(e.inbound.event_id,e.inbound.session_id,t),e.lastThinkingText=t)}applyCommittedToolStepText(e){const t=this.active;t&&(t.pendingText=void 0,e.trim()&&t.lastThinkingText!==e&&this.thinkingEnabled()&&(this.callbacks.sendThinking(t.inbound.event_id,t.inbound.session_id,e),t.lastThinkingText=e))}promotePendingTextToVisible(){const e=this.active,t=e?.pendingText;!e||!t||(e.pendingText=void 0,e.text+=t)}surfaceUnknownEventNotice(e){const t=this.active;!t||this.noticedUnknownSurfaceTypes.has(e)||(this.noticedUnknownSurfaceTypes.add(e),p.warn(g,`unknown surface SessionEvent surfaced as chat notice: ${e}`),!t.repliedViaTool&&(t.seq+=1,this.callbacks.sendStreamChunk(t.inbound.event_id,t.inbound.session_id,`
2
2
 
3
- Error: ${n}`,this.flushVisibleText(!1,{finalizeDsml:!0})),s==="responded"&&this.activeUsageSeq>=0&&(this.usageStore().commit(i.inbound.session_id,this.runtimeSessionId,this.activeUsageSeq,this.applied?.modelId??this.resolveDesiredSettings().modelId,this.activeUsage),this.usageStore().flush()),i.inbound.audit?.enabled&&this.capture&&this.auditBoundaries.set(i.inbound.event_id,this.capture.boundary({runtimeSessionId:this.runtimeSessionId,rootSessionId:this.runtimeSessionId,startOffset:this.activeWireStart,turn:i.turn,messageId:i.messageId}));const d=this.personaDirty&&!!this.runtime,r=!!this.runtime&&!!this.applied&&this.applied.appliedRevision!==this.resolveDesiredSettings().revision;d&&this.emit("pauseIntake","barrier"),this.active=null,this.correlator=null;const p=`${i.inbound.event_id}-dsh`,u=(o,l,c=!1)=>{this.callbacks.sendEventResult(i.inbound.event_id,o,l,c),this.emit("eventDone",i.inbound.event_id),d?this.rebuildRuntime("persona_changed"):r&&this.rebuildRuntime("settings_changed")};if(i.repliedViaTool&&i.seq===0){this.flushPendingFinalBridgeAck(!0).then(()=>u(s,n,a),()=>u(s,n,a));return}this.callbacks.sendFinalStreamChunkReliable(i.inbound.event_id,i.inbound.session_id,p).then(async()=>{await this.flushPendingFinalBridgeAck(!0),u(s,n,a)},async o=>{await this.flushPendingFinalBridgeAck(!1),u(s==="responded"?"failed":s,s==="responded"?`Final output delivery failed: ${this.redactError(o,i.inbound.content)}`:n)})}advanceBridgeAck(e,t){if(!(e<=0)){if(t||this.finishingTurn||this.pendingFinalBridgeAck!==null){this.pendingFinalBridgeAck=Math.max(this.pendingFinalBridgeAck??0,e);return}this.ackBridgeCursor(e)}}async flushPendingFinalBridgeAck(e){const t=this.pendingFinalBridgeAck;this.pendingFinalBridgeAck=null,this.finishingTurn=!1,!(!e||t===null)&&await this.ackBridgeCursor(t)}async ackBridgeCursor(e){if(e<=this.bridgeAckCursor)return;const t=this.runtime?.client?.ack;if(!t){this.bridgeAckCursor=Math.max(this.bridgeAckCursor,e);return}try{await t.call(this.runtime.client,e),this.bridgeAckCursor=Math.max(this.bridgeAckCursor,e)}catch(i){this.onProtocolError(i instanceof Error?i:new Error(String(i)))}}async cancelActive(e){this.active&&(this.cancelRequested=!0,this.clearPendingApprovals("cancelled"),this.resolveIntegrationMode()==="embedded_jsonrpc"?(this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="applied",this.pushToolbarMeta(),this.runtimeStartPromise&&this.runtime&&await this.runtime.terminate().catch(()=>{}),await this.runtimeStartPromise?.catch(()=>{}),await this.stopRuntime(!0)):(await this.runtimeStartPromise?.catch(()=>{}),await this.runtime?.cancel(this.runtimeSessionId).catch(()=>{}),this.runtime&&!this.runtime.isConnected()&&await this.stopRuntime(!0)),this.finishActive("canceled",e))}async handleBridgeApproval(e){const t=this.permissionHandler,i=String(e.interactionId??e.callId??x());if(t)try{return await t({adapterSessionId:this.options.aibotSessionId,requestId:i,description:String(e.reason??`Allow ${String(e.toolName??"operation")}?`),options:[{id:"allow_once",label:"Allow once",isAllow:!0},{id:"reject",label:"Reject",isAllow:!1}]})==="allow_once"?"allowed-once":"rejected"}catch{return"cancelled"}const s=this.active;return s?(this.callbacks.sendPermissionCard({eventId:s.inbound.event_id,sessionId:s.inbound.session_id,approvalId:i,toolName:String(e.toolName??"operation"),toolTitle:String(e.reason??`Allow ${String(e.toolName??"operation")}?`)}),new Promise(n=>{const a=setTimeout(()=>{this.pendingApprovals.delete(i),n("unavailable")},3e5);a.unref?.(),this.pendingApprovals.set(i,{resolve:n,timer:a})})):"unavailable"}async invokeGrixTool(e,t,i){if(!ct(e))throw Object.assign(new Error(`grix tool "${e}" is not exposed to DSH`),{code:"capability_unavailable"});if(ht(e)){if(!this.callbacks.eventToolInvoke)throw Object.assign(new Error(`grix event tool "${e}" has no connector-side runner`),{code:"capability_unavailable"});const n=this.active,a=await this.callbacks.eventToolInvoke(e,t);if(e==="grix_reply"&&n){const d=String(t.session_id??"").trim();(!d||d===n.inbound.session_id)&&(n.repliedViaTool=!0)}return a}if(!this.callbacks.agentInvoke)throw Object.assign(new Error(`grix tool "${e}" has no connector-side action runner`),{code:"capability_unavailable"});const s=lt(e,t);return this.callbacks.agentInvoke(s.action,s.params,i??s.timeoutMs)}projectConnectorSkills(){const e=T(this.options.dataRoot,"dsh-session-skills"),t=ge(e);return t.length>0&&f.info(m,`Synced connector skills to ${e}: [${t.join(", ")}]`),e}rebuildRuntime(e){if(this.stopped||this.active)return Promise.resolve();if(this.rebuildPromise)return this.rebuildPromise;const t=(async()=>{this.emit("pauseIntake","barrier"),this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="pending",this.pushToolbarMeta();try{await this.stopRuntime(!0),await this.ensureRuntime()}catch(i){f.warn(m,`${e} rebuild failed: ${this.redactError(i)}`)}finally{this.emit("resumeIntake","barrier")}})();return this.rebuildPromise=t.finally(()=>{this.rebuildPromise=null;const i=this.resolveDesiredSettings().revision;!this.stopped&&!this.active&&(this.personaDirty||this.applied&&this.applied.appliedRevision!==i)&&this.rebuildRuntime("coalesced_state_changed")}),this.rebuildPromise}async stopRuntime(e){const t=this.runtime;t&&(this.intentionalRuntimeStop=e,this.runtime=null,await t.shutdown().catch(()=>t.terminate()),this.capture?.close(),this.capture=null,this.intentionalRuntimeStop=!1)}onRuntimeExit(){this.intentionalRuntimeStop||this.stopped||(this.runtime=null,this.capture?.close(),this.capture=null,this.applied=void 0,this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState="failed",this.settingsErrorCode="runtime_exited",this.pushToolbarMeta(),this.active&&this.finishActive("failed","Harness runtime exited; prompt was not replayed"),this.emit("exit",1))}onProtocolError(e){if(this.stopped||!this.runtime&&!this.active)return;const t=this.redactError(e,this.active?.inbound.content);this.clearPendingApprovals("unavailable"),this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState="failed",this.settingsErrorCode="protocol_error",this.pushToolbarMeta();const i=this.runtime;this.runtime=null,this.intentionalRuntimeStop=!0,i?.client?.close(e),this.active&&this.finishActive("failed",`Harness protocol error: ${t}`),i?.terminate().finally(()=>{this.intentionalRuntimeStop=!1}),this.emit("exit",1)}async executeLocalAction(e){const t=e.params??{},i=String(t.session_id??"");if(!i||i!==this.options.aibotSessionId)return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing"};if(["exec_approve","exec_reject","permission_approve","permission_reject"].includes(e.action_type)){const o=String(t.approval_command_id??t.approval_id??t.request_id??"").trim(),l=this.pendingApprovals.get(o);if(!l)return{status:"failed",errorCode:"unknown_or_expired_approval_id",errorMsg:"That DSH approval request is no longer pending"};clearTimeout(l.timer),this.pendingApprovals.delete(o);const c=e.action_type==="exec_approve"||e.action_type==="permission_approve";return l.resolve(c?"allowed-once":"rejected"),{status:"ok",result:{approval_id:o,decision:c?"allow-once":"deny"}}}if(e.action_type==="get_session_usage")return{status:"ok",result:{adapterType:"deepseek-harness",available:!0,dsh_profile:this.resolveSelectedProfile(),...this.usageStore().get(i)}};if(e.action_type==="get_rate_limits"){this.providerQuota=null,this.pushToolbarMeta();try{this.providerQuota=await this.callbacks.queryProviderQuota(!0)??{provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:"unavailable"}}catch(o){this.providerQuota={provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:this.redactError(o)}}return this.pushToolbarMeta(),{status:"ok",result:{sampledAt:new Date().toISOString(),contextWindow:this.contextWindow,providerQuota:this.providerQuota}}}if(e.action_type==="dsh_bridge_status"||e.action_type==="dsh_install_bridge"){if(this.resolveIntegrationMode()!=="profile_bridge")return{status:"unsupported",errorCode:"capability_unavailable",errorMsg:"Bridge management requires Profile Bridge mode"};if(this.active||this.runtime)return{status:"failed",errorCode:"worker_busy",errorMsg:"Stop the active DSH session before changing its Profile plugin"};try{const o=new A({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),l=e.action_type==="dsh_install_bridge"?await o.install():await o.status();return this.runtimeReadiness=l.readiness,this.settingsErrorCode=l.readiness==="ready"?null:l.readiness,this.pushToolbarMeta(),{status:"ok",result:wt(l)}}catch(o){const l=String(o?.code??"bridge_install_failed");return this.runtimeReadiness=l,this.settingsErrorCode=l,this.pushToolbarMeta(),{status:"failed",errorCode:l,errorMsg:this.redactError(o)}}}if(e.action_type==="dsh_list_plugins"||e.action_type==="dsh_refresh_plugins"||e.action_type==="dsh_enable_plugin"||e.action_type==="dsh_disable_plugin")return this.executePluginAction(e.action_type,t,i);if(e.action_type==="dsh_list_skills"||e.action_type==="dsh_enable_skill"||e.action_type==="dsh_disable_skill")return this.executeSkillAction(e.action_type,t,i);const n={dsh_list_mcp:"mcp/list",dsh_list_tools:"tools/list",dsh_list_jobs:"jobs/list",dsh_list_goals:"goals/list"}[e.action_type];if(n){if(this.resolveIntegrationMode()!=="profile_bridge")return{status:"unsupported",errorCode:"capability_unavailable",errorMsg:"DSH resources require Profile Bridge mode"};if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot query DSH resources during an active turn"};try{return await this.ensureRuntimeWithRetry(),{status:"ok",result:await this.runtime?.client?.call(n,{cwd:this.options.bindingStore.get(i)?.cwd})}}catch(o){const l=String(o?.code??"resource_query_failed");return{status:l==="capability_unavailable"?"unsupported":"failed",errorCode:l,errorMsg:this.redactError(o)}}}if(e.action_type==="set_profile"||e.action_type==="create_profile"){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek Harness Profile during an active turn"};if(!this.options.bindingStore.get(i))return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};let o;try{o=Ee(String(t.profile_id??t.dsh_profile??t.profile_name??t.name??""))}catch(c){return{status:"failed",errorCode:"profile_invalid",errorMsg:this.redactError(c)}}if(this.options.bindingStore.isDshProfileLocked(i)){const c=this.resolveSelectedProfile();return e.action_type==="create_profile"||c!==o?{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}:this.finishProfileSelection(o,!1)}if(e.action_type==="create_profile")try{const c=this.options.createDshProfile?await this.options.createDshProfile(o):await we({profileName:o,dshHome:this.options.dshHome??this.config.env?.DSH_HOME}),b=c.identity?.profileName??o;return this.persistSelectedProfile(b)?(await this.flushSelectedProfile(),this.finishProfileSelection(b,c.created)):{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}}catch(c){return{status:"failed",errorCode:String(c?.code??"profile_create_failed"),errorMsg:this.redactError(c)}}return this.listProfiles().some(c=>c.id===o)?this.persistSelectedProfile(o)?(await this.flushSelectedProfile(),this.finishProfileSelection(o,!1)):{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}:{status:"failed",errorCode:"profile_not_found",errorMsg:"Requested DSH profile is not in the local catalog"}}if(e.action_type==="set_preset"){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek Harness settings during an active turn"};if(!this.options.bindingStore.get(i)?.cwd)return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const l=String(t.agent_preset_id??t.preset_id??"").trim();if(!this.presets.some(b=>b.id===l))return{status:"failed",errorCode:"preset_not_found",errorMsg:"Requested agent preset is not in the Harness catalog"};const c=Z(this.resolveDesiredSettings().agentPreset,this.presets);return this.options.bindingStore.isDshAgentPresetLocked(i)?c===l?{status:"ok",result:this.presetActionResult(l,!0)}:{status:"failed",errorCode:"agent_preset_locked",errorMsg:"This conversation scene is locked after the session is created"}:c===l?(this.options.bindingStore.setDshAgentPreset(i,l),await this.persistGlobalToolbarDefaults({dshAgentPreset:l}),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(l,!1)}):this.options.bindingStore.setDshAgentPreset(i,l)?(await this.persistGlobalToolbarDefaults({dshAgentPreset:l}),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(l,!1)}):{status:"failed",errorCode:"agent_preset_locked",errorMsg:"This conversation scene is locked after the session is created"}}if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek Harness settings during an active turn"};if(!this.options.bindingStore.get(i)?.cwd)return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const d=this.resolveDesiredSettings();let r;if(e.action_type==="set_provider"){const o=String(t.provider_id??"").trim();if(!this.providers.some(l=>l.id===o))return{status:"failed",errorCode:"provider_not_found",errorMsg:"Requested provider is not in the Harness catalog"};r={providerId:o},o!==d.providerId&&(this.models=st(this.options.dataRoot,o),this.catalogProviderId=o,this.models.some(l=>l.id===d.modelId)||(r.modelId=this.models[0]?.id))}else if(e.action_type==="set_model"){const o=String(t.model_id??"").trim();if(!this.models.some(l=>l.id===o))return{status:"failed",errorCode:"model_not_found",errorMsg:"Requested model is not in the Harness catalog"};r={modelId:o}}else if(e.action_type==="set_thinking"){const o=q(t.thinking_mode??t.thinking);if(!o)return{status:"failed",errorCode:"thinking_invalid",errorMsg:"thinking_mode must be enabled or disabled"};r={thinking:o}}else if(e.action_type==="set_reasoning_effort"){const o=B(t.reasoning_effort??t.reasoningEffort);if(!o)return{status:"failed",errorCode:"reasoning_effort_invalid",errorMsg:"reasoning_effort must be high or max"};r={reasoningEffort:o}}else{const o=String(t.mode_id??"").trim();if(o!=="approval"&&o!=="full_auto")return{status:"failed",errorCode:"mode_invalid",errorMsg:"mode_id must be approval or full_auto"};r={modeId:o}}if((r.providerId===void 0||r.providerId===d.providerId)&&(r.modelId===void 0||r.modelId===d.modelId)&&(r.modeId===void 0||r.modeId===d.modeId)&&(r.thinking===void 0||r.thinking===d.thinking)&&(r.reasoningEffort===void 0||r.reasoningEffort===d.reasoningEffort)&&this.applied?.appliedRevision===d.revision)return{status:"ok",result:this.settingsActionResult(e.action_type,r,d.revision,"already_applied",!0)};const u=this.options.bindingStore.updateDshSettings(i,r)??d.revision;if(await this.options.bindingStore.flush(),(r.providerId||r.modelId||r.modeId||r.thinking||r.reasoningEffort)&&await this.persistGlobalToolbarDefaults({...r.providerId?{dshProviderId:r.providerId}:{},...r.modelId?{dshModelId:r.modelId}:{},...r.modeId?{dshModeId:r.modeId}:{},...r.thinking?{dshThinking:r.thinking}:{},...r.reasoningEffort?{dshReasoningEffort:r.reasoningEffort}:{}}),this.contextWindow=null,this.reportedContextCapacity=null,this.settingsErrorCode=null,this.runtimeStartPromise&&await this.runtimeStartPromise.catch(()=>{}),!this.runtime)return this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,r,u,"applied",!1)};if(this.active)return this.applied&&this.applied.appliedRevision>=u?(this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,r,u,"applied",!0)}):(this.settingsState="pending",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,r,u,"pending",!0)});this.settingsState="pending",this.pushToolbarMeta();try{if(await this.rebuildRuntime("settings_changed"),!this.applied||this.applied.appliedRevision<u)throw new Error("new runtime did not apply requested revision");return this.refreshProviderQuota(!0),{status:"ok",result:this.settingsActionResult(e.action_type,r,u,"applied",!0)}}catch(o){return{status:"failed",result:this.settingsActionResult(e.action_type,r,u,"failed",!1,this.redactError(o)),errorCode:"settings_apply_failed",errorMsg:this.redactError(o)}}}async finishProfileSelection(e,t){if(this.resolveIntegrationMode()==="profile_bridge")try{await this.prepareSelectedProfile()}catch(i){const s=String(i?.code??"profile_start_failed");return this.runtimeReadiness=s,this.settingsErrorCode=s,this.pushToolbarMeta(),{status:"failed",errorCode:s,errorMsg:this.redactError(i)}}return this.pushToolbarMeta(),{status:"ok",result:this.profileActionResult(e,t)}}createBridgeInstaller(){const e=this.options.bridgeInstallerOptions??{};return new A({command:e.command??"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile(),...e.tarballPath?{tarballPath:e.tarballPath}:{}})}async healBridgeUpdate(e){return e.readiness!=="bridge_update_required"||this.options.autoInstallBridge===!1?e:(f.info(m,`auto-updating stale Bridge profile=${e.identity.profileName} installed=${e.installedBridgeVersion??"none"} bundled=${e.bundledBridgeVersion}`),await this.prepareSelectedProfile(),this.attachSelectedProfile())}async ensureProfileReadyForChat(){if(!(this.options.autoInstallBridge!==!1||this.options.autoStartProfile!==!1)){const s=await this.attachSelectedProfile(),n=H(s);if(n)throw n;return}this.settingsState="pending",this.pushToolbarMeta(),await this.prepareSelectedProfile();let t=await this.attachSelectedProfile();t.readiness==="bridge_update_required"&&(t=await this.healBridgeUpdate(t));const i=H(t);if(i)throw i}async attachSelectedProfile(){const t=await this.createBridgeInstaller().status();return this.runtimeReadiness=t.readiness,this.profileDshVersion=t.runningDshVersion??t.dshVersion??null,this.settingsErrorCode=t.readiness==="ready"?null:t.readiness,t}async prepareSelectedProfile(){const e=this.createBridgeInstaller(),t=await qe({installer:e,autoInstall:this.options.autoInstallBridge!==!1,autoStart:this.options.autoStartProfile!==!1});this.runtimeReadiness=t.readiness,this.profileDshVersion=t.runningDshVersion??t.dshVersion??null,this.settingsErrorCode=t.readiness==="ready"?null:t.readiness}profileActionResult(e,t){return{outcome:t?"profile_created":"profile_set",profile_id:e,dsh_profile:e,created:t,dsh_profile_locked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),dsh_profile_create:!this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),available_profiles:this.listProfiles(),session_context:{dsh_profile:e,dsh_profile_locked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),dsh_profile_create:!this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId)}}}persistSelectedProfile(e){return this.options.bindingStore.setDshSelectedProfile(this.options.aibotSessionId,e)?(this.options.globalConfigStore?.set(this.options.agentName,{dshProfile:e}),!0):!1}async persistGlobalToolbarDefaults(e){this.options.globalConfigStore&&Object.values(e).some(t=>t!==void 0)&&(this.options.globalConfigStore.set(this.options.agentName,e),await this.options.globalConfigStore.flush())}seedSessionToolbarFromGlobal(){const e=this.options.aibotSessionId,t=this.options.bindingStore.get(e);if(!t?.cwd)return;const i=this.resolveDesiredSettings(),s={};t.dshProviderId||(s.providerId=i.providerId),t.dshModelId||(s.modelId=i.modelId),t.dshModeId||(s.modeId=i.modeId),t.dshThinking||(s.thinking=i.thinking),t.dshReasoningEffort||(s.reasoningEffort=i.reasoningEffort),Object.keys(s).length>0&&this.options.bindingStore.updateDshSettings(e,s),!this.options.bindingStore.getDshAgentPreset(e)&&i.agentPreset&&this.options.bindingStore.setDshAgentPreset(e,i.agentPreset),this.options.bindingStore.getDshSelectedProfile(e)||this.options.bindingStore.setDshSelectedProfile(e,this.resolveSelectedProfile())}async flushSelectedProfile(){await this.options.bindingStore.flush(),await this.options.globalConfigStore?.flush()}listProfiles(){return Me({dshHome:this.options.dshHome??this.config.env?.DSH_HOME})}pluginCommandContext(){return{dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile(),enabledPluginIds:this.options.bindingStore.getDshEnabledPlugins(this.options.aibotSessionId)}}skillCommandContext(){return{skillsDir:this.projectConnectorSkills(),enabledSkillIds:this.options.bindingStore.getDshEnabledSkills(this.options.aibotSessionId)}}currentPlugins(){try{return M(this.pluginCommandContext())}catch{return[]}}currentSkills(){return this.sessionSkillControlUnavailable()?[]:R(this.skillCommandContext())}pluginRestartRequired(){return!1}async executePluginAction(e,t,i){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek plugins during an active turn"};if(!this.options.bindingStore.get(i))return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const s=this.pluginCommandContext();try{if(e==="dsh_list_plugins"||e==="dsh_refresh_plugins"){const o=M(s);return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(o,!1)}}const n=String(t.name??t.plugin_name??"").trim(),a=this.options.bindingStore.getDshEnabledPlugins(i);let d=n;try{const{plugin:o}=Te({...s,name:n});d=o.name}catch(o){const l=String(o?.code??"");if(e!=="dsh_disable_plugin"||l!=="plugin_not_found"||!a.includes(n))throw o}const r=Pe(a,d,e==="dsh_enable_plugin"),p=this.options.bindingStore.setDshEnabledPlugins(i,r.pluginIds)??this.resolveDesiredSettings().revision;await this.options.bindingStore.flush();const u=M({...s,enabledPluginIds:r.pluginIds});if(!r.changed)return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(u,!1,"skipped")};if(this.runtimeStartPromise&&await this.runtimeStartPromise.catch(()=>{}),!this.runtime)return this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(u,!0,"skipped")};if(this.active)return this.settingsState="pending",this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(u,!0,"pending")};if(this.settingsState="pending",this.pushToolbarMeta(),await this.rebuildRuntime("plugin_changed"),!this.applied||this.applied.appliedRevision<p)throw new Error("new runtime did not apply requested plugin revision");return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(u,!0,"restarted")}}catch(n){return{status:"failed",errorCode:String(n?.code??"plugin_action_failed"),errorMsg:this.redactError(n)}}}async executeSkillAction(e,t,i){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek skills during an active turn"};if(!this.options.bindingStore.get(i))return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};if(this.sessionSkillControlUnavailable())return this.pushToolbarMeta(),{status:"unsupported",errorCode:"capability_unavailable",errorMsg:`DSH session skills require @deepseek-ai/dsh ${re} or newer`};const s=this.skillCommandContext();try{if(e==="dsh_list_skills"){const o=R(s);return this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(o,!1)}}const n=String(t.name??t.skill_name??"").trim(),a=this.options.bindingStore.getDshEnabledSkills(i);let d=n;try{d=ye({...s,name:n}).name}catch(o){const l=String(o?.code??"");if(e!=="dsh_disable_skill"||l!=="skill_not_found"||!a.includes(n))throw o}const r=De(a,d,e==="dsh_enable_skill"),p=this.options.bindingStore.setDshEnabledSkills(i,r.skillIds)??this.resolveDesiredSettings().revision;await this.options.bindingStore.flush();const u=R({...s,enabledSkillIds:r.skillIds});if(!r.changed)return this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(u,!1,"skipped")};if(this.runtimeStartPromise&&await this.runtimeStartPromise.catch(()=>{}),!this.runtime)return this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(u,!0,"skipped")};if(this.active)return this.settingsState="pending",this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(u,!0,"pending")};if(this.settingsState="pending",this.pushToolbarMeta(),await this.rebuildRuntime("skill_changed"),!this.applied||this.applied.appliedRevision<p)throw new Error("new runtime did not apply requested skill revision");return this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(u,!0,"restarted")}}catch(n){return{status:"failed",errorCode:String(n?.code??"skill_action_failed"),errorMsg:this.redactError(n)}}}pluginActionResult(e,t,i="skipped"){const s=this.resolveSelectedProfile(),n=this.pluginRestartRequired();return{outcome:t?i==="restarted"?"plugin_applied":"plugin_updated":"plugin_unchanged",dsh_profile:s,dsh_plugins:e,dsh_plugin_restart_required:n,restart:i,session_context:{dsh_profile:s,dsh_plugins:e,dsh_plugin_restart_required:n}}}skillActionResult(e,t,i="skipped"){return{outcome:t?i==="restarted"?"skill_applied":"skill_updated":"skill_unchanged",dsh_skills:e,restart:i,session_context:{dsh_skills:e}}}resolveSelectedProfile(){const e=this.options.bindingStore.getDshSelectedProfile(this.options.aibotSessionId),t=He({binding:e,global:this.options.globalConfigStore?.get(this.options.agentName)?.dshProfile,adapter:this.options.dshProfile});return this.options.bindingStore.get(this.options.aibotSessionId)&&e!==t&&this.options.bindingStore.setDshSelectedProfile(this.options.aibotSessionId,t),t}profileDataDir(e=this.resolveSelectedProfile()){return Re(this.options.dataRoot,e)}usageStore(){const e=this.resolveSelectedProfile(),t=T(this.profileDataDir(e),"session-usage.json"),i=T(this.options.dataRoot,"session-usage.json");return!W(t)&&W(i)&&(ue(pe(t),{recursive:!0,mode:448}),ce(i,t)),dt(t)}presetActionResult(e,t){const i=this.resolveDesiredSettings();return{outcome:"preset_set",agentPreset:e,agent_preset_id:e,agent_preset_locked:t,available_presets:[...this.presets],session_context:{agent_preset_id:i.agentPreset??e,agent_preset_locked:t}}}settingsActionResult(e,t,i,s,n,a){const d=this.resolveDesiredSettings(),r=d.revision||i,p={provider_id:d.providerId,model_id:d.modelId,mode_id:d.modeId,thinking_mode:d.thinking,reasoning_effort:d.reasoningEffort,applied_provider_id:this.applied?.providerId??null,applied_model_id:this.applied?.modelId??null,applied_mode_id:this.applied?.modeId??null,applied_thinking_mode:this.applied?.thinking??null,applied_reasoning_effort:this.applied?.reasoningEffort??null,applied_settings_revision:this.applied?.appliedRevision??null,settings_state:this.settingsState,settings_revision:r};return e==="set_mode"&&(p.sandbox_mode=Y(d.modeId),p.approval_policy=d.modeId==="full_auto"?"never":"ask"),{outcome:`${e==="set_provider"?"provider":e==="set_model"?"model":e==="set_thinking"?"thinking":e==="set_reasoning_effort"?"reasoning_effort":"mode"}_set${s==="pending"||s==="failed"?"_pending":""}`,...t.providerId?{providerId:t.providerId,provider_id:t.providerId}:{},...t.modelId?{modelId:t.modelId,model_id:t.modelId}:{},...t.modeId?{modeId:t.modeId,mode_id:t.modeId,sandbox_mode:Y(t.modeId),approval_policy:t.modeId==="full_auto"?"never":"ask"}:{},...t.thinking?{thinking:t.thinking,thinking_mode:t.thinking}:{},...t.reasoningEffort?{reasoningEffort:t.reasoningEffort,reasoning_effort:t.reasoningEffort}:{},settingsRevision:r,settings_revision:r,sessionAlive:n,available_providers:[...this.providers],available_models:[...this.models],session_context:p,...a?{error:a}:{}}}hydrateCatalogFromCache(){const e=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),t=this.options.globalConfigStore?.get(this.options.agentName),i=nt({dataRoot:this.options.dataRoot,providerId:e?.providerId??t?.dshProviderId});this.providers=i.providers,this.models=this.options.models?.length?this.options.models:i.models,this.catalogProviderId=i.providerId}async persistCatalogCache(e){try{await ot({dataRoot:this.options.dataRoot,providers:this.providers,providerId:e,models:this.models})}catch(t){f.warn(m,`failed to persist DSH catalog cache: ${t instanceof Error?t.message:String(t)}`)}}async writeGrixProviderFile(){const e=Ae(this.options.dshHome??this.config.env?.DSH_HOME),t=await this.resolveCredentialsLayout(e);try{if(te(this.options.provider)){await gt(e,v,this.options.provider??{},t)==="skipped"&&f.warn(m,`Grix provider not written to DSH settings (user-owned "${v}" route or unreadable YAML); relay will not take effect`);return}await pt(e,v)}catch(i){f.warn(m,`Failed to sync Grix provider into DSH settings: ${this.redactError(i)}`)}}async resolveCredentialsLayout(e){let t=this.profileDshVersion;if(!t)try{t=await $e(this.options.bridgeInstallerOptions?.command??"dsh",e)}catch(s){f.warn(m,`could not read dsh version, assuming the current credentials layout: ${this.redactError(s)}`)}const i=ut(t);return St(t)&&f.warn(m,`dsh ${t} predates ${ae}: it drops the supportsDeveloperRole / maxTokensField switches, so relayed requests keep the OpenAI-style wire format and the gateway rejects them. Upgrade dsh to use the Grix relay.`),i}syncGrixProvider(){if(te(this.options.provider)){this.providers.some(s=>s.id===v)||(this.providers=[{id:v,displayName:"Grix"},...this.providers]);const e=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),t=this.options.globalConfigStore?.get(this.options.agentName),i=e?.providerId??t?.dshProviderId;(!i||i===$||i===v)&&this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,{providerId:v});return}this.providers=this.providers.filter(e=>e.id!==v)}resolveDesiredSettings(){const e=this.options.bindingStore.get(this.options.aibotSessionId),t=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),i=this.options.globalConfigStore?.get(this.options.agentName),s=t?.providerId??i?.dshProviderId,n=this.providers.some(p=>p.id===v)?v:void 0,a=tt(s||n,this.providers),d=[t?.modelId,i?.dshModelId,this.options.defaultModel,this.models[0]?.id].find(p=>!!p&&this.models.some(u=>u.id===p))??"deepseek-chat",r=Z(t?.agentPreset??i?.dshAgentPreset,this.presets);return{providerId:a,modelId:d,modeId:et(e?.dshModeId,i?.dshModeId),thinking:q(t?.thinking)??q(i?.dshThinking)??Je,reasoningEffort:B(t?.reasoningEffort)??B(i?.dshReasoningEffort)??Xe,agentPreset:r,pluginIds:this.options.bindingStore.getDshEnabledPlugins(this.options.aibotSessionId),skillIds:this.options.bindingStore.getDshEnabledSkills(this.options.aibotSessionId),skillIdsExplicit:Array.isArray(e?.dshSkillIds),maxTokens:t?.maxTokens??this.options.maxTokens??ze,revision:t?.revision??0}}resolveIntegrationMode(){return this.options.integrationMode?this.options.integrationMode:(this.config.command||"").includes("dsh-jsonrpc-agent")?"embedded_jsonrpc":"profile_bridge"}sessionSkillControlUnavailable(){return this.resolveIntegrationMode()!=="profile_bridge"?!1:this.bridgeCapabilities&&typeof this.bridgeCapabilities=="object"?this.bridgeCapabilities.sessionSkillAllowlist!==!0:kt(this.profileDshVersion)}pushToolbarMeta(){const e=this.options.bindingStore.get(this.options.aibotSessionId);this.callbacks.sendUpdateBindingCard(this.options.aibotSessionId,this.stopped?"stopped":this.active?"busy":"ready",e?.cwd,Ge({desired:this.resolveDesiredSettings(),applied:this.applied,models:this.models,providers:this.providers,presets:this.presets,agentPresetLocked:this.options.bindingStore.isDshAgentPresetLocked(this.options.aibotSessionId),state:this.settingsState,errorCode:this.settingsErrorCode,contextWindow:this.contextWindow,providerQuota:this.providerQuota,integrationMode:this.resolveIntegrationMode(),profileName:this.resolveSelectedProfile(),profiles:this.listProfiles(),profileLocked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),plugins:this.currentPlugins(),skills:this.currentSkills(),pluginRestartRequired:this.pluginRestartRequired(),runtimeReadiness:this.runtimeReadiness,bridgeCapabilities:this.bridgeCapabilities}))}async refreshProviderQuota(e){this.providerQuota=null,this.pushToolbarMeta();try{this.providerQuota=await this.callbacks.queryProviderQuota(e)??{provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:"unavailable"}}catch{this.providerQuota={provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:"unavailable"}}this.pushToolbarMeta()}clearPendingApprovals(e){for(const t of this.pendingApprovals.values())clearTimeout(t.timer),t.resolve(e);this.pendingApprovals.clear()}thinkingEnabled(){const e=this.active?.inbound.connector_runtime_config?.thinking_events??this.active?.inbound.connector_runtime_config?.thinkingEvents;return e!=="off"&&e!=="hidden"&&e!=="none"}toolEventsEnabled(){const e=this.active?.inbound.connector_runtime_config?.tool_events;return e!=="off"&&e!=="hidden"&&e!=="none"}sendRaw(e,t,i){this.active&&this.callbacks.sendRawEventEnvelope(this.active.inbound.event_id,this.active.inbound.session_id,{type:e,payload:t},i)}failEvent(e,t){this.callbacks.sendEventResult(e.event_id,"failed",t),this.emit("eventDone",e.event_id)}startTimeout(e){this.activeTimeoutMs=e??this.options.promptTimeoutMs??ie,this.noteRuntimeActivity(),this.armTimeout(this.activeIdleTimeoutMs()),this.armHardTimeout(this.activeTimeoutMs)}touchActivity(e=1){!this.active||!this.timeoutTimer||(this.noteRuntimeActivity(),this.armTimeout(this.activeIdleTimeoutMs()))}noteRuntimeActivity(){this.active&&(this.active.lastRuntimeActivityAt=Date.now(),this.active.livenessExtendStartAt=void 0)}activeIdleTimeoutMs(){const e=this.options.activeIdleTimeoutMs??se,t=Number.isFinite(e)&&e>0?e:se;return Math.min(t,this.activeTimeoutMs)}livenessFreshMs(){const e=this.options.livenessFreshMs??ne;return Number.isFinite(e)&&e>0?e:ne}livenessMaxExtendMs(){const e=this.options.livenessMaxExtendMs??oe;return Number.isFinite(e)&&e>0?e:oe}armTimeout(e){this.clearIdleTimeout(),this.timeoutTimer=setTimeout(()=>{this.handlePromptTimeout()},e),this.timeoutTimer.unref?.()}armHardTimeout(e){this.clearHardTimeout(),this.hardTimeoutTimer=setTimeout(()=>{this.handlePromptHardTimeout()},e),this.hardTimeoutTimer.unref?.()}async handlePromptTimeout(){const e=this.active;if(e){if(this.pendingApprovals.size>0){f.info(m,`Idle timeout skipped: pendingApprovals=${this.pendingApprovals.size} event=${e.inbound.event_id}`),this.armTimeout(this.activeIdleTimeoutMs());return}if(this.shouldExtendByLiveness(e.inbound.event_id)){this.armTimeout(this.activeIdleTimeoutMs());return}await this.failActiveTimeout("idle","Harness prompt idle timeout and the runtime was terminated")}}async handlePromptHardTimeout(){const e=this.active;if(e&&this.shouldExtendByLiveness(e.inbound.event_id)){this.armHardTimeout(this.activeTimeoutMs);return}await this.failActiveTimeout("hard","Harness prompt exceeded max duration and the runtime was terminated")}shouldExtendByLiveness(e){const t=this.active;if(!t||t.inbound.event_id!==e||!this.runtime?.isConnected()||!(!t.turnEnded&&(!!t.messageId||t.admitted||t.claimed)))return!1;const s=Date.now(),n=t.lastRuntimeActivityAt??t.startedAt,a=Math.max(0,s-n);if(a<this.livenessFreshMs())return t.livenessExtendStartAt=s,f.info(m,`Liveness check: recent DSH activity for ${e} (quietMs=${a}), extending`),!0;const d=t.livenessExtendStartAt??n;t.livenessExtendStartAt=d;const r=s-d;return r>this.livenessMaxExtendMs()?(f.warn(m,`Liveness extension budget exhausted for ${e} (quietMs=${a}, extendMs=${r}), allowing close`),!1):(f.info(m,`Liveness check: DSH turn still open for ${e} (claimed=${t.claimed}, turnEnded=${t.turnEnded}, quietMs=${a}), extending`),!0)}async failActiveTimeout(e,t){if(!this.active)return;const i=this.active;this.clearTimeout();const s=this.runtime;this.runtime=null,this.intentionalRuntimeStop=!0,this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="applied",this.settingsErrorCode=null,this.pushToolbarMeta(),await s?.cancel(this.runtimeSessionId).catch(()=>{}),s&&await s.shutdown().catch(()=>s.terminate()),this.intentionalRuntimeStop=!1,!(this.active!==i||this.stopped)&&(f.error(m,`Active DSH turn ${e} timeout: ${i.inbound.event_id}`),this.finishActive("failed",t),this.emit("exit",1))}clearTimeout(){this.clearIdleTimeout(),this.clearHardTimeout()}clearIdleTimeout(){this.timeoutTimer&&clearTimeout(this.timeoutTimer),this.timeoutTimer=null}clearHardTimeout(){this.hardTimeoutTimer&&clearTimeout(this.hardTimeoutTimer),this.hardTimeoutTimer=null}redactError(e,t){let i=e instanceof Error?e.message:String(e);const s=this.config.env?.DEEPSEEK_API_KEY;return s&&(i=i.split(s).join("[REDACTED]")),i=i.replace(/(api[_-]?key|authorization|bearer)\s*[:=]\s*\S+/gi,"$1=[REDACTED]"),t&&t.length>=16&&i.includes(t)&&(i="Harness request failed (prompt echo redacted)"),(i.includes("[aibot-system-prompt]")||i.includes("[base-behavior]"))&&(i="Harness runtime failed (system prompt echo redacted)"),i.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g,"").slice(0,2e3)}}function mt(h){const e=Number(h&&typeof h=="object"?h.cursor:0);return Number.isSafeInteger(e)&&e>0?e:0}function vt(h){return new Promise(e=>setTimeout(e,h))}function bt(h,e){return`grix-${E("sha256").update(h).digest("hex").slice(0,12)}-${e}-${x().slice(0,8)}`}function _t(h){return`grix-${E("sha256").update(h).digest("hex").slice(0,16)}-${x().slice(0,8)}`}function de(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,reasoningTokens:0}}function St(h){const e=X(h,ae);return e!==null&&e<0}function kt(h){const e=X(h,re);return e!==null&&e<0}function le(h){const e=h.data?.chunk&&typeof h.data.chunk=="object"?h.data.chunk:h.data;return String(e?.type??"")}function It(h){return h.type==="assistant/chunk:tool-call-delta"||h.type==="assistant/chunk"&&le(h)==="tool-call-delta"}function wt(h){return{readiness:h.readiness,profile:h.identity.profileName,dshVersion:h.dshVersion,runningDshVersion:h.runningDshVersion,installedBridgeVersion:h.installedBridgeVersion,bundledBridgeVersion:h.bundledBridgeVersion,runningBridgeVersion:h.runningBridgeVersion,endpointCount:h.endpointCount,requiresProfileRestart:h.readiness==="profile_restart_required"}}const Tt=new Set(["turn/start","step/start","step/end","agent/inbox/spliced","user/message","request/header","system/message","assistant/attempt","session-log-deepseek/delivery-accepted","job/registered","job/settled","session/title","session/title-llm-request","session/end-seed","web/deepseek-search-llm-request","assistant/chunk:tool-call-delta","permission/preset","sandbox/mode","approval/policy","approval/asked","approval/decided","plan/mode","agent-preset/selected","llm/retry","llm/retry-started","goal/change","schedule/change","feedback/record","hook/invoked","hook/result","command/run","command/done","subagent/descriptor","tool-workflow/agent-start","tool-workflow/agent-end","tool-workflow/run-start","tool-workflow/run-end","tool/code-dispatch","tool/code-dispatch-start"]);function Pt(h){const e=le(h);return Tt.has(h.type)||h.type==="assistant/chunk"&&["block-start","block-end","tool-call-delta","finish"].includes(e)}export{ai as DshJsonRpcAdapter};
3
+ [\u8FDE\u63A5\u5668\u63D0\u793A] \u672A\u8BC6\u522B\u7684 dsh \u4E8B\u4EF6 ${e}\uFF0C\u6B64\u6BB5\u5185\u5BB9\u53EF\u80FD\u663E\u793A\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u622A\u56FE\u53CD\u9988\u7ED9\u5F00\u53D1\u8005\u3002
4
+
5
+ `,t.seq,!1,`${t.inbound.event_id}-dsh`,this.quotedMessageId)))}flushVisibleText(e,t={}){const i=this.active;if(!i)return;const s=K(i.text);s.quotedMessageId&&(this.quotedMessageId=s.quotedMessageId);const n=s.text.replace(/\[\[quoted_message_id:[^\]]*$/g,""),a=_e(n,{finalize:t.finalizeDsml===!0||e});this.surfaceSuppressedDsmlToolCalls(a.suppressedToolCalls);const d=a.visible;this.observeVisibleTextAfterToolCall(d);let r="";d.startsWith(i.sentText)?r=d.slice(i.sentText.length):(e||t.finalizeDsml)&&(r=d),!(!r&&!e)&&(i.repliedViaTool||(i.seq+=1,this.callbacks.sendStreamChunk(i.inbound.event_id,i.inbound.session_id,r,i.seq,e,`${i.inbound.event_id}-dsh`,this.quotedMessageId)),i.sentText=d)}surfaceSuppressedDsmlToolCalls(e){if(!this.active||e.length===0)return;const t=this.active.dsmlSuppressedKeys??new Set;this.active.dsmlSuppressedKeys=t;for(const i of e){const s=be(i);if(t.has(s)||(t.add(s),this.markToolCallAwaitingFinalText(),p.warn(g,`suppressed leaked DSML tool markup name=${i.name} event=${this.active.inbound.event_id}`),!this.toolEventsEnabled()))continue;let n=i.arguments;try{n=JSON.parse(i.arguments)}catch{}this.sendRaw("tool_call",{call_id:`dsml-${t.size}`,tool_name:i.name,tool_input:n,source:"dsml_text_leak",executed:!1},`[tool] ${i.name}`)}}markToolCallAwaitingFinalText(){const e=this.active;e&&(e.toolCallAwaitingFinalText=!0,e.toolCallVisibleTextLength=e.sentText.length)}observeVisibleTextAfterToolCall(e){const t=this.active;if(!t?.toolCallAwaitingFinalText)return;const i=t.toolCallVisibleTextLength??t.sentText.length;e.slice(i).trim().length!==0&&(t.toolCallAwaitingFinalText=!1,t.toolCallVisibleTextLength=void 0)}collectCommittedUsage(e,t){if(this.activeCommittedUsageSeqs.has(t))return;this.activeCommittedUsageSeqs.add(t);const i=te(e);this.activeUsage.inputTokens+=i.inputTokens,this.activeUsage.outputTokens+=i.outputTokens,this.activeUsage.cacheReadInputTokens+=i.cacheReadInputTokens,this.activeUsage.cacheCreationInputTokens+=i.cacheCreationInputTokens,this.activeUsage.reasoningTokens+=i.reasoningTokens,this.activeUsageSeq=Math.max(this.activeUsageSeq,t),this.updateContextWindow(i)}updateContextWindow(e){const t=te(e),i=this.resolveDesiredSettings(),s=this.models.find(a=>a.id===i.modelId),n=this.reportedContextCapacity??s?.contextWindow;if(n&&n>0){const a=t.inputTokens+t.cacheReadInputTokens+t.cacheCreationInputTokens;this.contextWindow={usedTokens:a,totalTokens:n,remainingTokens:Math.max(0,n-a),usedPercentage:a/n*100,remainingPercentage:Math.max(0,100-a/n*100)},this.pushToolbarMeta()}}updateContextCapacity(e){const t=Number(e?.contextWindow);if(!Number.isFinite(t)||t<=0)return;this.reportedContextCapacity=t;const i=this.contextWindow&&typeof this.contextWindow=="object"?this.contextWindow:{},s=Math.max(0,Number(i.usedTokens)||0);this.contextWindow={usedTokens:s,totalTokens:t,remainingTokens:Math.max(0,t-s),usedPercentage:s/t*100,remainingPercentage:Math.max(0,100-s/t*100)},this.pushToolbarMeta()}finishFromTurnOutcome(){if(!this.active)return;this.finishingTurn=!0;const e=this.active.outcome??"completed",t=this.active.outcomeDetail?.trim();e==="completed"?this.finishActive("responded"):e==="aborted"?this.finishActive("canceled"):e==="max-tokens"&&this.active.sentText?this.finishActive("responded","Response truncated at model token limit"):this.finishActive("failed",t?t.toLowerCase().includes(e.toLowerCase())?`Harness turn ended: ${t}`:`Harness turn ended: ${e}: ${t}`:`Harness turn ended: ${e}`)}finishActive(e,t){const i=this.active;if(!i)return;let s=this.cancelRequested?"canceled":e,n=this.cancelRequested?"user canceled":t;this.finishingTurn=!0,this.clearTimeout(),this.promotePendingTextToVisible(),this.flushVisibleText(!1,{finalizeDsml:!0}),s==="responded"&&i.toolCallAwaitingFinalText&&!i.repliedViaTool&&(s="failed",n="DeepSeek Harness ended after a tool call without returning final assistant text",p.warn(g,`${n} event=${i.inbound.event_id}`)),i.text=i.sentText;const a=s==="failed"&&!!n?.trim();a&&(i.text+=`
6
+
7
+ Error: ${n}`,this.flushVisibleText(!1,{finalizeDsml:!0})),s==="responded"&&this.activeUsageSeq>=0&&(this.usageStore().commit(i.inbound.session_id,this.runtimeSessionId,this.activeUsageSeq,this.applied?.modelId??this.resolveDesiredSettings().modelId,this.activeUsage),this.usageStore().flush()),i.inbound.audit?.enabled&&this.capture&&this.auditBoundaries.set(i.inbound.event_id,this.capture.boundary({runtimeSessionId:this.runtimeSessionId,rootSessionId:this.runtimeSessionId,startOffset:this.activeWireStart,turn:i.turn,messageId:i.messageId}));const d=this.personaDirty&&!!this.runtime,r=!!this.runtime&&!!this.applied&&this.applied.appliedRevision!==this.resolveDesiredSettings().revision;d&&this.emit("pauseIntake","barrier"),this.active=null,this.correlator=null;const f=`${i.inbound.event_id}-dsh`,u=(o,l,c=!1)=>{this.callbacks.sendEventResult(i.inbound.event_id,o,l,c),this.emit("eventDone",i.inbound.event_id),d?this.rebuildRuntime("persona_changed"):r&&this.rebuildRuntime("settings_changed")};if(i.repliedViaTool&&i.seq===0){this.flushPendingFinalBridgeAck(!0).then(()=>u(s,n,a),()=>u(s,n,a));return}this.callbacks.sendFinalStreamChunkReliable(i.inbound.event_id,i.inbound.session_id,f).then(async()=>{await this.flushPendingFinalBridgeAck(!0),u(s,n,a)},async o=>{await this.flushPendingFinalBridgeAck(!1),u(s==="responded"?"failed":s,s==="responded"?`Final output delivery failed: ${this.redactError(o,i.inbound.content)}`:n)})}advanceBridgeAck(e,t){if(!(e<=0)){if(t||this.finishingTurn||this.pendingFinalBridgeAck!==null){this.pendingFinalBridgeAck=Math.max(this.pendingFinalBridgeAck??0,e);return}this.ackBridgeCursor(e)}}async flushPendingFinalBridgeAck(e){const t=this.pendingFinalBridgeAck;this.pendingFinalBridgeAck=null,this.finishingTurn=!1,!(!e||t===null)&&await this.ackBridgeCursor(t)}async ackBridgeCursor(e){if(e<=this.bridgeAckCursor)return;const t=this.runtime?.client?.ack;if(!t){this.bridgeAckCursor=Math.max(this.bridgeAckCursor,e);return}try{await t.call(this.runtime.client,e),this.bridgeAckCursor=Math.max(this.bridgeAckCursor,e)}catch(i){this.onProtocolError(i instanceof Error?i:new Error(String(i)))}}async cancelActive(e){this.active&&(this.cancelRequested=!0,this.clearPendingApprovals("cancelled"),this.resolveIntegrationMode()==="embedded_jsonrpc"?(this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="applied",this.pushToolbarMeta(),this.runtimeStartPromise&&this.runtime&&await this.runtime.terminate().catch(()=>{}),await this.runtimeStartPromise?.catch(()=>{}),await this.stopRuntime(!0)):(await this.runtimeStartPromise?.catch(()=>{}),await this.runtime?.cancel(this.runtimeSessionId).catch(()=>{}),this.runtime&&!this.runtime.isConnected()&&await this.stopRuntime(!0)),this.finishActive("canceled",e))}async handleBridgeApproval(e){const t=this.permissionHandler,i=String(e.interactionId??e.callId??D());if(t)try{return await t({adapterSessionId:this.options.aibotSessionId,requestId:i,description:String(e.reason??`Allow ${String(e.toolName??"operation")}?`),options:[{id:"allow_once",label:"Allow once",isAllow:!0},{id:"reject",label:"Reject",isAllow:!1}]})==="allow_once"?"allowed-once":"rejected"}catch{return"cancelled"}const s=this.active;return s?(this.callbacks.sendPermissionCard({eventId:s.inbound.event_id,sessionId:s.inbound.session_id,approvalId:i,toolName:String(e.toolName??"operation"),toolTitle:String(e.reason??`Allow ${String(e.toolName??"operation")}?`)}),new Promise(n=>{const a=setTimeout(()=>{this.pendingApprovals.delete(i),n("unavailable")},3e5);a.unref?.(),this.pendingApprovals.set(i,{resolve:n,timer:a})})):"unavailable"}async invokeGrixTool(e,t,i){if(!ct(e))throw Object.assign(new Error(`grix tool "${e}" is not exposed to DSH`),{code:"capability_unavailable"});if(ht(e)){if(!this.callbacks.eventToolInvoke)throw Object.assign(new Error(`grix event tool "${e}" has no connector-side runner`),{code:"capability_unavailable"});const n=this.active,a=await this.callbacks.eventToolInvoke(e,t);if(e==="grix_reply"&&n){const d=String(t.session_id??"").trim();(!d||d===n.inbound.session_id)&&(n.repliedViaTool=!0)}return a}if(!this.callbacks.agentInvoke)throw Object.assign(new Error(`grix tool "${e}" has no connector-side action runner`),{code:"capability_unavailable"});const s=lt(e,t);return this.callbacks.agentInvoke(s.action,s.params,i??s.timeoutMs)}projectConnectorSkills(){const e=T(this.options.dataRoot,"dsh-session-skills"),t=fe(e);return t.length>0&&p.info(g,`Synced connector skills to ${e}: [${t.join(", ")}]`),e}rebuildRuntime(e){if(this.stopped||this.active)return Promise.resolve();if(this.rebuildPromise)return this.rebuildPromise;const t=(async()=>{this.emit("pauseIntake","barrier"),this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="pending",this.pushToolbarMeta();try{await this.stopRuntime(!0),await this.ensureRuntime()}catch(i){p.warn(g,`${e} rebuild failed: ${this.redactError(i)}`)}finally{this.emit("resumeIntake","barrier")}})();return this.rebuildPromise=t.finally(()=>{this.rebuildPromise=null;const i=this.resolveDesiredSettings().revision;!this.stopped&&!this.active&&(this.personaDirty||this.applied&&this.applied.appliedRevision!==i)&&this.rebuildRuntime("coalesced_state_changed")}),this.rebuildPromise}async stopRuntime(e){const t=this.runtime;t&&(this.intentionalRuntimeStop=e,this.runtime=null,await t.shutdown().catch(()=>t.terminate()),this.capture?.close(),this.capture=null,this.intentionalRuntimeStop=!1)}onRuntimeExit(e){if(!(this.intentionalRuntimeStop||this.stopped)&&!(e&&this.replaySupersededRuntimes.has(e))){if(this.runtime=null,this.capture?.close(),this.capture=null,this.applied=void 0,this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState="failed",this.settingsErrorCode="runtime_exited",this.pushToolbarMeta(),this.active){if(this.isPromptUnaccepted(this.active)){p.warn(g,`Harness runtime exited before accepting prompt ${this.active.inbound.event_id}; awaiting in-flight prompt failure`);return}this.finishActive("failed","Harness runtime exited; prompt was not replayed")}this.emit("exit",1)}}onProtocolError(e){if(this.stopped||!this.runtime&&!this.active)return;const t=this.redactError(e,this.active?.inbound.content);this.clearPendingApprovals("unavailable"),this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState="failed",this.settingsErrorCode="protocol_error",this.pushToolbarMeta();const i=this.runtime;this.runtime=null,this.intentionalRuntimeStop=!0,i?.client?.close(e),this.active&&this.finishActive("failed",`Harness protocol error: ${t}`),i?.terminate().finally(()=>{this.intentionalRuntimeStop=!1}),this.emit("exit",1)}async executeLocalAction(e){const t=e.params??{},i=String(t.session_id??"");if(!i||i!==this.options.aibotSessionId)return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing"};if(["exec_approve","exec_reject","permission_approve","permission_reject"].includes(e.action_type)){const o=String(t.approval_command_id??t.approval_id??t.request_id??"").trim(),l=this.pendingApprovals.get(o);if(!l)return{status:"failed",errorCode:"unknown_or_expired_approval_id",errorMsg:"That DSH approval request is no longer pending"};clearTimeout(l.timer),this.pendingApprovals.delete(o);const c=e.action_type==="exec_approve"||e.action_type==="permission_approve";return l.resolve(c?"allowed-once":"rejected"),{status:"ok",result:{approval_id:o,decision:c?"allow-once":"deny"}}}if(e.action_type==="get_session_usage")return{status:"ok",result:{adapterType:"deepseek-harness",available:!0,dsh_profile:this.resolveSelectedProfile(),...this.usageStore().get(i)}};if(e.action_type==="get_rate_limits"){this.providerQuota=null,this.pushToolbarMeta();try{this.providerQuota=await this.callbacks.queryProviderQuota(!0,this.providerQuotaHint())??this.providerQuotaFallback()}catch(o){this.providerQuota={...this.providerQuotaFallback(),error:this.redactError(o)}}return this.pushToolbarMeta(),{status:"ok",result:{sampledAt:new Date().toISOString(),contextWindow:this.contextWindow,providerQuota:this.providerQuota}}}if(e.action_type==="dsh_bridge_status"||e.action_type==="dsh_install_bridge"){if(this.resolveIntegrationMode()!=="profile_bridge")return{status:"unsupported",errorCode:"capability_unavailable",errorMsg:"Bridge management requires Profile Bridge mode"};if(this.active||this.runtime)return{status:"failed",errorCode:"worker_busy",errorMsg:"Stop the active DSH session before changing its Profile plugin"};try{const o=new A({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),l=e.action_type==="dsh_install_bridge"?await o.install():await o.status();return this.runtimeReadiness=l.readiness,this.settingsErrorCode=l.readiness==="ready"?null:l.readiness,this.pushToolbarMeta(),{status:"ok",result:wt(l)}}catch(o){const l=String(o?.code??"bridge_install_failed");return this.runtimeReadiness=l,this.settingsErrorCode=l,this.pushToolbarMeta(),{status:"failed",errorCode:l,errorMsg:this.redactError(o)}}}if(e.action_type==="dsh_list_plugins"||e.action_type==="dsh_refresh_plugins"||e.action_type==="dsh_enable_plugin"||e.action_type==="dsh_disable_plugin")return this.executePluginAction(e.action_type,t,i);if(e.action_type==="dsh_list_skills"||e.action_type==="dsh_enable_skill"||e.action_type==="dsh_disable_skill")return this.executeSkillAction(e.action_type,t,i);const n={dsh_list_mcp:"mcp/list",dsh_list_tools:"tools/list",dsh_list_jobs:"jobs/list",dsh_list_goals:"goals/list"}[e.action_type];if(n){if(this.resolveIntegrationMode()!=="profile_bridge")return{status:"unsupported",errorCode:"capability_unavailable",errorMsg:"DSH resources require Profile Bridge mode"};if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot query DSH resources during an active turn"};try{return await this.ensureRuntimeWithRetry(),{status:"ok",result:await this.runtime?.client?.call(n,{cwd:this.options.bindingStore.get(i)?.cwd})}}catch(o){const l=String(o?.code??"resource_query_failed");return{status:l==="capability_unavailable"?"unsupported":"failed",errorCode:l,errorMsg:this.redactError(o)}}}if(e.action_type==="set_profile"||e.action_type==="create_profile"){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek Harness Profile during an active turn"};if(!this.options.bindingStore.get(i))return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};let o;try{o=De(String(t.profile_id??t.dsh_profile??t.profile_name??t.name??""))}catch(c){return{status:"failed",errorCode:"profile_invalid",errorMsg:this.redactError(c)}}if(this.options.bindingStore.isDshProfileLocked(i)){const c=this.resolveSelectedProfile();return e.action_type==="create_profile"||c!==o?{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}:this.finishProfileSelection(o,!1)}if(e.action_type==="create_profile")try{const c=this.options.createDshProfile?await this.options.createDshProfile(o):await Te({profileName:o,dshHome:this.options.dshHome??this.config.env?.DSH_HOME}),b=c.identity?.profileName??o;return this.persistSelectedProfile(b)?(await this.flushSelectedProfile(),this.finishProfileSelection(b,c.created)):{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}}catch(c){return{status:"failed",errorCode:String(c?.code??"profile_create_failed"),errorMsg:this.redactError(c)}}return this.listProfiles().some(c=>c.id===o)?this.persistSelectedProfile(o)?(await this.flushSelectedProfile(),this.finishProfileSelection(o,!1)):{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}:{status:"failed",errorCode:"profile_not_found",errorMsg:"Requested DSH profile is not in the local catalog"}}if(e.action_type==="set_preset"){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek Harness settings during an active turn"};if(!this.options.bindingStore.get(i)?.cwd)return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const l=String(t.agent_preset_id??t.preset_id??"").trim();if(!this.presets.some(b=>b.id===l))return{status:"failed",errorCode:"preset_not_found",errorMsg:"Requested agent preset is not in the Harness catalog"};const c=Z(this.resolveDesiredSettings().agentPreset,this.presets);return this.options.bindingStore.isDshAgentPresetLocked(i)?c===l?{status:"ok",result:this.presetActionResult(l,!0)}:{status:"failed",errorCode:"agent_preset_locked",errorMsg:"This conversation scene is locked after the session is created"}:c===l?(this.options.bindingStore.setDshAgentPreset(i,l),await this.persistGlobalToolbarDefaults({dshAgentPreset:l}),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(l,!1)}):this.options.bindingStore.setDshAgentPreset(i,l)?(await this.persistGlobalToolbarDefaults({dshAgentPreset:l}),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(l,!1)}):{status:"failed",errorCode:"agent_preset_locked",errorMsg:"This conversation scene is locked after the session is created"}}if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek Harness settings during an active turn"};if(!this.options.bindingStore.get(i)?.cwd)return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const d=this.resolveDesiredSettings();let r;if(e.action_type==="set_provider"){const o=String(t.provider_id??"").trim();if(!this.providers.some(l=>l.id===o))return{status:"failed",errorCode:"provider_not_found",errorMsg:"Requested provider is not in the Harness catalog"};r={providerId:o},o!==d.providerId&&(this.models=nt(this.options.dataRoot,o),this.catalogProviderId=o,this.models.some(l=>l.id===d.modelId)||(r.modelId=this.models[0]?.id))}else if(e.action_type==="set_model"){const o=String(t.model_id??"").trim();if(!this.models.some(l=>l.id===o))return{status:"failed",errorCode:"model_not_found",errorMsg:"Requested model is not in the Harness catalog"};r={modelId:o}}else if(e.action_type==="set_thinking"){const o=q(t.thinking_mode??t.thinking);if(!o)return{status:"failed",errorCode:"thinking_invalid",errorMsg:"thinking_mode must be enabled or disabled"};r={thinking:o}}else if(e.action_type==="set_reasoning_effort"){const o=B(t.reasoning_effort??t.reasoningEffort);if(!o)return{status:"failed",errorCode:"reasoning_effort_invalid",errorMsg:"reasoning_effort must be high or max"};r={reasoningEffort:o}}else{const o=String(t.mode_id??"").trim();if(o!=="approval"&&o!=="full_auto")return{status:"failed",errorCode:"mode_invalid",errorMsg:"mode_id must be approval or full_auto"};r={modeId:o}}if((r.providerId===void 0||r.providerId===d.providerId)&&(r.modelId===void 0||r.modelId===d.modelId)&&(r.modeId===void 0||r.modeId===d.modeId)&&(r.thinking===void 0||r.thinking===d.thinking)&&(r.reasoningEffort===void 0||r.reasoningEffort===d.reasoningEffort)&&this.applied?.appliedRevision===d.revision)return{status:"ok",result:this.settingsActionResult(e.action_type,r,d.revision,"already_applied",!0)};const u=this.options.bindingStore.updateDshSettings(i,r)??d.revision;if(await this.options.bindingStore.flush(),(r.providerId||r.modelId||r.modeId||r.thinking||r.reasoningEffort)&&await this.persistGlobalToolbarDefaults({...r.providerId?{dshProviderId:r.providerId}:{},...r.modelId?{dshModelId:r.modelId}:{},...r.modeId?{dshModeId:r.modeId}:{},...r.thinking?{dshThinking:r.thinking}:{},...r.reasoningEffort?{dshReasoningEffort:r.reasoningEffort}:{}}),this.contextWindow=null,this.reportedContextCapacity=null,this.settingsErrorCode=null,this.runtimeStartPromise&&await this.runtimeStartPromise.catch(()=>{}),!this.runtime)return this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,r,u,"applied",!1)};if(this.active)return this.applied&&this.applied.appliedRevision>=u?(this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,r,u,"applied",!0)}):(this.settingsState="pending",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,r,u,"pending",!0)});this.settingsState="pending",this.pushToolbarMeta();try{if(await this.rebuildRuntime("settings_changed"),!this.applied||this.applied.appliedRevision<u)throw new Error("new runtime did not apply requested revision");return this.refreshProviderQuota(!0),{status:"ok",result:this.settingsActionResult(e.action_type,r,u,"applied",!0)}}catch(o){return{status:"failed",result:this.settingsActionResult(e.action_type,r,u,"failed",!1,this.redactError(o)),errorCode:"settings_apply_failed",errorMsg:this.redactError(o)}}}async finishProfileSelection(e,t){if(this.resolveIntegrationMode()==="profile_bridge")try{await this.prepareSelectedProfile()}catch(i){const s=String(i?.code??"profile_start_failed");return this.runtimeReadiness=s,this.settingsErrorCode=s,this.pushToolbarMeta(),{status:"failed",errorCode:s,errorMsg:this.redactError(i)}}return this.pushToolbarMeta(),{status:"ok",result:this.profileActionResult(e,t)}}createBridgeInstaller(){const e=this.options.bridgeInstallerOptions??{};return new A({command:e.command??"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile(),...e.tarballPath?{tarballPath:e.tarballPath}:{}})}async healBridgeUpdate(e){return e.readiness!=="bridge_update_required"||this.options.autoInstallBridge===!1?e:(p.info(g,`auto-updating stale Bridge profile=${e.identity.profileName} installed=${e.installedBridgeVersion??"none"} bundled=${e.bundledBridgeVersion}`),await this.prepareSelectedProfile(),this.attachSelectedProfile())}async ensureProfileReadyForChat(){if(!(this.options.autoInstallBridge!==!1||this.options.autoStartProfile!==!1)){const s=await this.attachSelectedProfile(),n=H(s);if(n)throw n;return}this.settingsState="pending",this.pushToolbarMeta(),await this.prepareSelectedProfile();let t=await this.attachSelectedProfile();t.readiness==="bridge_update_required"&&(t=await this.healBridgeUpdate(t));const i=H(t);if(i)throw i}async attachSelectedProfile(){const t=await this.createBridgeInstaller().status();return this.runtimeReadiness=t.readiness,this.profileDshVersion=t.runningDshVersion??t.dshVersion??null,this.settingsErrorCode=t.readiness==="ready"?null:t.readiness,t}async prepareSelectedProfile(){const e=this.createBridgeInstaller(),t=await Fe({installer:e,autoInstall:this.options.autoInstallBridge!==!1,autoStart:this.options.autoStartProfile!==!1});this.runtimeReadiness=t.readiness,this.profileDshVersion=t.runningDshVersion??t.dshVersion??null,this.settingsErrorCode=t.readiness==="ready"?null:t.readiness}profileActionResult(e,t){return{outcome:t?"profile_created":"profile_set",profile_id:e,dsh_profile:e,created:t,dsh_profile_locked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),dsh_profile_create:!this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),available_profiles:this.listProfiles(),session_context:{dsh_profile:e,dsh_profile_locked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),dsh_profile_create:!this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId)}}}persistSelectedProfile(e){return this.options.bindingStore.setDshSelectedProfile(this.options.aibotSessionId,e)?(this.options.globalConfigStore?.set(this.options.agentName,{dshProfile:e}),!0):!1}async persistGlobalToolbarDefaults(e){this.options.globalConfigStore&&Object.values(e).some(t=>t!==void 0)&&(this.options.globalConfigStore.set(this.options.agentName,e),await this.options.globalConfigStore.flush())}seedSessionToolbarFromGlobal(){const e=this.options.aibotSessionId,t=this.options.bindingStore.get(e);if(!t?.cwd)return;const i=this.resolveDesiredSettings(),s={};t.dshProviderId||(s.providerId=i.providerId),t.dshModelId||(s.modelId=i.modelId),t.dshModeId||(s.modeId=i.modeId),t.dshThinking||(s.thinking=i.thinking),t.dshReasoningEffort||(s.reasoningEffort=i.reasoningEffort),Object.keys(s).length>0&&this.options.bindingStore.updateDshSettings(e,s),!this.options.bindingStore.getDshAgentPreset(e)&&i.agentPreset&&this.options.bindingStore.setDshAgentPreset(e,i.agentPreset),this.options.bindingStore.getDshSelectedProfile(e)||this.options.bindingStore.setDshSelectedProfile(e,this.resolveSelectedProfile())}async flushSelectedProfile(){await this.options.bindingStore.flush(),await this.options.globalConfigStore?.flush()}listProfiles(){return Me({dshHome:this.options.dshHome??this.config.env?.DSH_HOME})}pluginCommandContext(){return{dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile(),enabledPluginIds:this.options.bindingStore.getDshEnabledPlugins(this.options.aibotSessionId)}}skillCommandContext(){return{skillsDir:this.projectConnectorSkills(),enabledSkillIds:this.options.bindingStore.getDshEnabledSkills(this.options.aibotSessionId)}}currentPlugins(){try{return R(this.pluginCommandContext())}catch{return[]}}currentSkills(){return this.sessionSkillControlUnavailable()?[]:M(this.skillCommandContext())}pluginRestartRequired(){return!1}async executePluginAction(e,t,i){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek plugins during an active turn"};if(!this.options.bindingStore.get(i))return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const s=this.pluginCommandContext();try{if(e==="dsh_list_plugins"||e==="dsh_refresh_plugins"){const o=R(s);return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(o,!1)}}const n=String(t.name??t.plugin_name??"").trim(),a=this.options.bindingStore.getDshEnabledPlugins(i);let d=n;try{const{plugin:o}=ye({...s,name:n});d=o.name}catch(o){const l=String(o?.code??"");if(e!=="dsh_disable_plugin"||l!=="plugin_not_found"||!a.includes(n))throw o}const r=Pe(a,d,e==="dsh_enable_plugin"),f=this.options.bindingStore.setDshEnabledPlugins(i,r.pluginIds)??this.resolveDesiredSettings().revision;await this.options.bindingStore.flush();const u=R({...s,enabledPluginIds:r.pluginIds});if(!r.changed)return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(u,!1,"skipped")};if(this.runtimeStartPromise&&await this.runtimeStartPromise.catch(()=>{}),!this.runtime)return this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(u,!0,"skipped")};if(this.active)return this.settingsState="pending",this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(u,!0,"pending")};if(this.settingsState="pending",this.pushToolbarMeta(),await this.rebuildRuntime("plugin_changed"),!this.applied||this.applied.appliedRevision<f)throw new Error("new runtime did not apply requested plugin revision");return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(u,!0,"restarted")}}catch(n){return{status:"failed",errorCode:String(n?.code??"plugin_action_failed"),errorMsg:this.redactError(n)}}}async executeSkillAction(e,t,i){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek skills during an active turn"};if(!this.options.bindingStore.get(i))return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};if(this.sessionSkillControlUnavailable())return this.pushToolbarMeta(),{status:"unsupported",errorCode:"capability_unavailable",errorMsg:`DSH session skills require @deepseek-ai/dsh ${ae} or newer`};const s=this.skillCommandContext();try{if(e==="dsh_list_skills"){const o=M(s);return this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(o,!1)}}const n=String(t.name??t.skill_name??"").trim(),a=this.options.bindingStore.getDshEnabledSkills(i);let d=n;try{d=Ee({...s,name:n}).name}catch(o){const l=String(o?.code??"");if(e!=="dsh_disable_skill"||l!=="skill_not_found"||!a.includes(n))throw o}const r=Ce(a,d,e==="dsh_enable_skill"),f=this.options.bindingStore.setDshEnabledSkills(i,r.skillIds)??this.resolveDesiredSettings().revision;await this.options.bindingStore.flush();const u=M({...s,enabledSkillIds:r.skillIds});if(!r.changed)return this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(u,!1,"skipped")};if(this.runtimeStartPromise&&await this.runtimeStartPromise.catch(()=>{}),!this.runtime)return this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(u,!0,"skipped")};if(this.active)return this.settingsState="pending",this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(u,!0,"pending")};if(this.settingsState="pending",this.pushToolbarMeta(),await this.rebuildRuntime("skill_changed"),!this.applied||this.applied.appliedRevision<f)throw new Error("new runtime did not apply requested skill revision");return this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(u,!0,"restarted")}}catch(n){return{status:"failed",errorCode:String(n?.code??"skill_action_failed"),errorMsg:this.redactError(n)}}}pluginActionResult(e,t,i="skipped"){const s=this.resolveSelectedProfile(),n=this.pluginRestartRequired();return{outcome:t?i==="restarted"?"plugin_applied":"plugin_updated":"plugin_unchanged",dsh_profile:s,dsh_plugins:e,dsh_plugin_restart_required:n,restart:i,session_context:{dsh_profile:s,dsh_plugins:e,dsh_plugin_restart_required:n}}}skillActionResult(e,t,i="skipped"){return{outcome:t?i==="restarted"?"skill_applied":"skill_updated":"skill_unchanged",dsh_skills:e,restart:i,session_context:{dsh_skills:e}}}resolveSelectedProfile(){const e=this.options.bindingStore.getDshSelectedProfile(this.options.aibotSessionId),t=$e({binding:e,global:this.options.globalConfigStore?.get(this.options.agentName)?.dshProfile,adapter:this.options.dshProfile});return this.options.bindingStore.get(this.options.aibotSessionId)&&e!==t&&this.options.bindingStore.setDshSelectedProfile(this.options.aibotSessionId,t),t}profileDataDir(e=this.resolveSelectedProfile()){return Ae(this.options.dataRoot,e)}usageStore(){const e=this.resolveSelectedProfile(),t=T(this.profileDataDir(e),"session-usage.json"),i=T(this.options.dataRoot,"session-usage.json");return!W(t)&&W(i)&&(pe(ge(t),{recursive:!0,mode:448}),ue(i,t)),dt(t)}presetActionResult(e,t){const i=this.resolveDesiredSettings();return{outcome:"preset_set",agentPreset:e,agent_preset_id:e,agent_preset_locked:t,available_presets:[...this.presets],session_context:{agent_preset_id:i.agentPreset??e,agent_preset_locked:t}}}settingsActionResult(e,t,i,s,n,a){const d=this.resolveDesiredSettings(),r=d.revision||i,f={provider_id:d.providerId,model_id:d.modelId,mode_id:d.modeId,thinking_mode:d.thinking,reasoning_effort:d.reasoningEffort,applied_provider_id:this.applied?.providerId??null,applied_model_id:this.applied?.modelId??null,applied_mode_id:this.applied?.modeId??null,applied_thinking_mode:this.applied?.thinking??null,applied_reasoning_effort:this.applied?.reasoningEffort??null,applied_settings_revision:this.applied?.appliedRevision??null,settings_state:this.settingsState,settings_revision:r};return e==="set_mode"&&(f.sandbox_mode=Y(d.modeId),f.approval_policy=d.modeId==="full_auto"?"never":"ask"),{outcome:`${e==="set_provider"?"provider":e==="set_model"?"model":e==="set_thinking"?"thinking":e==="set_reasoning_effort"?"reasoning_effort":"mode"}_set${s==="pending"||s==="failed"?"_pending":""}`,...t.providerId?{providerId:t.providerId,provider_id:t.providerId}:{},...t.modelId?{modelId:t.modelId,model_id:t.modelId}:{},...t.modeId?{modeId:t.modeId,mode_id:t.modeId,sandbox_mode:Y(t.modeId),approval_policy:t.modeId==="full_auto"?"never":"ask"}:{},...t.thinking?{thinking:t.thinking,thinking_mode:t.thinking}:{},...t.reasoningEffort?{reasoningEffort:t.reasoningEffort,reasoning_effort:t.reasoningEffort}:{},settingsRevision:r,settings_revision:r,sessionAlive:n,available_providers:[...this.providers],available_models:[...this.models],session_context:f,...a?{error:a}:{}}}hydrateCatalogFromCache(){const e=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),t=this.options.globalConfigStore?.get(this.options.agentName),i=ot({dataRoot:this.options.dataRoot,providerId:e?.providerId??t?.dshProviderId});this.providers=i.providers,this.models=this.options.models?.length?this.options.models:i.models,this.catalogProviderId=i.providerId}async persistCatalogCache(e){try{await rt({dataRoot:this.options.dataRoot,providers:this.providers,providerId:e,models:this.models})}catch(t){p.warn(g,`failed to persist DSH catalog cache: ${t instanceof Error?t.message:String(t)}`)}}async writeGrixProviderFile(){const e=He(this.options.dshHome??this.config.env?.DSH_HOME),t=await this.resolveCredentialsLayout(e);try{if(ie(this.options.provider)){await gt(e,v,this.options.provider??{},t)==="skipped"&&p.warn(g,`Grix provider not written to DSH settings (user-owned "${v}" route or unreadable YAML); relay will not take effect`);return}await pt(e,v)}catch(i){p.warn(g,`Failed to sync Grix provider into DSH settings: ${this.redactError(i)}`)}}async resolveCredentialsLayout(e){let t=this.profileDshVersion;if(!t)try{t=await Be(this.options.bridgeInstallerOptions?.command??"dsh",e)}catch(s){p.warn(g,`could not read dsh version, assuming the current credentials layout: ${this.redactError(s)}`)}const i=ut(t);return St(t)&&p.warn(g,`dsh ${t} predates ${de}: it drops the supportsDeveloperRole / maxTokensField switches, so relayed requests keep the OpenAI-style wire format and the gateway rejects them. Upgrade dsh to use the Grix relay.`),i}syncGrixProvider(){if(ie(this.options.provider)){this.providers.some(s=>s.id===v)||(this.providers=[{id:v,displayName:"Grix"},...this.providers]);const e=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),t=this.options.globalConfigStore?.get(this.options.agentName),i=e?.providerId??t?.dshProviderId;(!i||i===$||i===v)&&this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,{providerId:v});return}this.providers=this.providers.filter(e=>e.id!==v)}resolveDesiredSettings(){const e=this.options.bindingStore.get(this.options.aibotSessionId),t=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),i=this.options.globalConfigStore?.get(this.options.agentName),s=t?.providerId??i?.dshProviderId,n=this.providers.some(f=>f.id===v)?v:void 0,a=it(s||n,this.providers),d=[t?.modelId,i?.dshModelId,this.options.defaultModel,this.models[0]?.id].find(f=>!!f&&this.models.some(u=>u.id===f))??"deepseek-chat",r=Z(t?.agentPreset??i?.dshAgentPreset,this.presets);return{providerId:a,modelId:d,modeId:tt(e?.dshModeId,i?.dshModeId),thinking:q(t?.thinking)??q(i?.dshThinking)??Ye,reasoningEffort:B(t?.reasoningEffort)??B(i?.dshReasoningEffort)??Je,agentPreset:r,pluginIds:this.options.bindingStore.getDshEnabledPlugins(this.options.aibotSessionId),skillIds:this.options.bindingStore.getDshEnabledSkills(this.options.aibotSessionId),skillIdsExplicit:Array.isArray(e?.dshSkillIds),maxTokens:t?.maxTokens??this.options.maxTokens??ze,revision:t?.revision??0}}resolveIntegrationMode(){return this.options.integrationMode?this.options.integrationMode:(this.config.command||"").includes("dsh-jsonrpc-agent")?"embedded_jsonrpc":"profile_bridge"}sessionSkillControlUnavailable(){return this.resolveIntegrationMode()!=="profile_bridge"?!1:this.bridgeCapabilities&&typeof this.bridgeCapabilities=="object"?this.bridgeCapabilities.sessionSkillAllowlist!==!0:kt(this.profileDshVersion)}pushToolbarMeta(){const e=this.options.bindingStore.get(this.options.aibotSessionId);this.callbacks.sendUpdateBindingCard(this.options.aibotSessionId,this.stopped?"stopped":this.active?"busy":"ready",e?.cwd,Qe({desired:this.resolveDesiredSettings(),applied:this.applied,models:this.models,providers:this.providers,presets:this.presets,agentPresetLocked:this.options.bindingStore.isDshAgentPresetLocked(this.options.aibotSessionId),state:this.settingsState,errorCode:this.settingsErrorCode,contextWindow:this.contextWindow,providerQuota:this.providerQuota,integrationMode:this.resolveIntegrationMode(),profileName:this.resolveSelectedProfile(),profiles:this.listProfiles(),profileLocked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),plugins:this.currentPlugins(),skills:this.currentSkills(),pluginRestartRequired:this.pluginRestartRequired(),runtimeReadiness:this.runtimeReadiness,bridgeCapabilities:this.bridgeCapabilities}))}providerQuotaHint(){const e=this.resolveDesiredSettings(),t=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),i=this.options.globalConfigStore?.get(this.options.agentName);return{providerId:t?.providerId??i?.dshProviderId??e.providerId,model:e.modelId}}providerQuotaFallback(){const e=this.providerQuotaHint().providerId;return e==="opencode-go"||e==="opencode_go"?{provider:"opencode_go",providerLabel:"OpenCode Go",success:!1,error:"unavailable"}:{provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:"unavailable"}}async refreshProviderQuota(e){this.providerQuota=null,this.pushToolbarMeta();try{this.providerQuota=await this.callbacks.queryProviderQuota(e,this.providerQuotaHint())??this.providerQuotaFallback()}catch{this.providerQuota=this.providerQuotaFallback()}this.pushToolbarMeta()}clearPendingApprovals(e){for(const t of this.pendingApprovals.values())clearTimeout(t.timer),t.resolve(e);this.pendingApprovals.clear()}thinkingEnabled(){const e=this.active?.inbound.connector_runtime_config?.thinking_events??this.active?.inbound.connector_runtime_config?.thinkingEvents;return e!=="off"&&e!=="hidden"&&e!=="none"}toolEventsEnabled(){const e=this.active?.inbound.connector_runtime_config?.tool_events;return e!=="off"&&e!=="hidden"&&e!=="none"}sendRaw(e,t,i){this.active&&this.callbacks.sendRawEventEnvelope(this.active.inbound.event_id,this.active.inbound.session_id,{type:e,payload:t},i)}failEvent(e,t){this.callbacks.sendEventResult(e.event_id,"failed",t),this.emit("eventDone",e.event_id)}startTimeout(e){this.activeTimeoutMs=e??this.options.promptTimeoutMs??se,this.noteRuntimeActivity(),this.armTimeout(this.activeIdleTimeoutMs()),this.armHardTimeout(this.activeTimeoutMs)}touchActivity(e=1){!this.active||!this.timeoutTimer||(this.noteRuntimeActivity(),this.armTimeout(this.activeIdleTimeoutMs()))}noteRuntimeActivity(){this.active&&(this.active.lastRuntimeActivityAt=Date.now(),this.active.livenessExtendStartAt=void 0)}activeIdleTimeoutMs(){const e=this.options.activeIdleTimeoutMs??ne,t=Number.isFinite(e)&&e>0?e:ne;return Math.min(t,this.activeTimeoutMs)}livenessFreshMs(){const e=this.options.livenessFreshMs??oe;return Number.isFinite(e)&&e>0?e:oe}livenessMaxExtendMs(){const e=this.options.livenessMaxExtendMs??re;return Number.isFinite(e)&&e>0?e:re}armTimeout(e){this.clearIdleTimeout(),this.timeoutTimer=setTimeout(()=>{this.handlePromptTimeout()},e),this.timeoutTimer.unref?.()}armHardTimeout(e){this.clearHardTimeout(),this.hardTimeoutTimer=setTimeout(()=>{this.handlePromptHardTimeout()},e),this.hardTimeoutTimer.unref?.()}async handlePromptTimeout(){const e=this.active;if(e){if(this.pendingApprovals.size>0){p.info(g,`Idle timeout skipped: pendingApprovals=${this.pendingApprovals.size} event=${e.inbound.event_id}`),this.armTimeout(this.activeIdleTimeoutMs());return}if(this.shouldExtendByLiveness(e.inbound.event_id)){this.armTimeout(this.activeIdleTimeoutMs());return}await this.failActiveTimeout("idle","Harness prompt idle timeout and the runtime was terminated")}}async handlePromptHardTimeout(){const e=this.active;if(e&&this.shouldExtendByLiveness(e.inbound.event_id)){this.armHardTimeout(this.activeTimeoutMs);return}await this.failActiveTimeout("hard","Harness prompt exceeded max duration and the runtime was terminated")}shouldExtendByLiveness(e){const t=this.active;if(!t||t.inbound.event_id!==e||!this.runtime?.isConnected()||!(!t.turnEnded&&(!!t.messageId||t.admitted||t.claimed)))return!1;const s=Date.now(),n=t.lastRuntimeActivityAt??t.startedAt,a=Math.max(0,s-n);if(a<this.livenessFreshMs())return t.livenessExtendStartAt=s,p.info(g,`Liveness check: recent DSH activity for ${e} (quietMs=${a}), extending`),!0;const d=t.livenessExtendStartAt??n;t.livenessExtendStartAt=d;const r=s-d;return r>this.livenessMaxExtendMs()?(p.warn(g,`Liveness extension budget exhausted for ${e} (quietMs=${a}, extendMs=${r}), allowing close`),!1):(p.info(g,`Liveness check: DSH turn still open for ${e} (claimed=${t.claimed}, turnEnded=${t.turnEnded}, quietMs=${a}), extending`),!0)}async failActiveTimeout(e,t){if(!this.active)return;const i=this.active;this.clearTimeout();const s=this.runtime;this.runtime=null,this.intentionalRuntimeStop=!0,this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="applied",this.settingsErrorCode=null,this.pushToolbarMeta(),await s?.cancel(this.runtimeSessionId).catch(()=>{}),s&&await s.shutdown().catch(()=>s.terminate()),this.intentionalRuntimeStop=!1,!(this.active!==i||this.stopped)&&(p.error(g,`Active DSH turn ${e} timeout: ${i.inbound.event_id}`),this.finishActive("failed",t),this.emit("exit",1))}clearTimeout(){this.clearIdleTimeout(),this.clearHardTimeout()}clearIdleTimeout(){this.timeoutTimer&&clearTimeout(this.timeoutTimer),this.timeoutTimer=null}clearHardTimeout(){this.hardTimeoutTimer&&clearTimeout(this.hardTimeoutTimer),this.hardTimeoutTimer=null}redactError(e,t){let i=e instanceof Error?e.message:String(e);const s=this.config.env?.DEEPSEEK_API_KEY;return s&&(i=i.split(s).join("[REDACTED]")),i=i.replace(/(api[_-]?key|authorization|bearer)\s*[:=]\s*\S+/gi,"$1=[REDACTED]"),t&&t.length>=16&&i.includes(t)&&(i="Harness request failed (prompt echo redacted)"),(i.includes("[aibot-system-prompt]")||i.includes("[base-behavior]"))&&(i="Harness runtime failed (system prompt echo redacted)"),i.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g,"").slice(0,2e3)}}function mt(h){const e=Number(h&&typeof h=="object"?h.cursor:0);return Number.isSafeInteger(e)&&e>0?e:0}function vt(h){return new Promise(e=>setTimeout(e,h))}function bt(h,e){return`grix-${x("sha256").update(h).digest("hex").slice(0,12)}-${e}-${D().slice(0,8)}`}function _t(h){return`grix-${x("sha256").update(h).digest("hex").slice(0,16)}-${D().slice(0,8)}`}function le(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,reasoningTokens:0}}function St(h){const e=X(h,de);return e!==null&&e<0}function kt(h){const e=X(h,ae);return e!==null&&e<0}function he(h){const e=h.data?.chunk&&typeof h.data.chunk=="object"?h.data.chunk:h.data;return String(e?.type??"")}function It(h){return h.type==="assistant/chunk:tool-call-delta"||h.type==="assistant/chunk"&&he(h)==="tool-call-delta"}function wt(h){return{readiness:h.readiness,profile:h.identity.profileName,dshVersion:h.dshVersion,runningDshVersion:h.runningDshVersion,installedBridgeVersion:h.installedBridgeVersion,bundledBridgeVersion:h.bundledBridgeVersion,runningBridgeVersion:h.runningBridgeVersion,endpointCount:h.endpointCount,requiresProfileRestart:h.readiness==="profile_restart_required"}}const Tt=new Set(["turn/start","step/start","step/end","agent/inbox/spliced","user/message","request/header","system/message","assistant/attempt","session-log-deepseek/delivery-accepted","job/registered","job/settled","developer/message","session/title","session/title-llm-request","session/end-seed","web/deepseek-search-llm-request","assistant/chunk:tool-call-delta","permission/preset","sandbox/mode","approval/policy","approval/asked","approval/decided","plan/mode","agent-preset/selected","llm/retry","llm/retry-started","goal/change","schedule/change","feedback/record","hook/invoked","hook/result","command/run","command/done","subagent/descriptor","tool-workflow/agent-start","tool-workflow/agent-end","tool-workflow/run-start","tool-workflow/run-end","tool/code-dispatch","tool/code-dispatch-start"]);function yt(h){const e=he(h);return Tt.has(h.type)||h.type==="assistant/chunk"&&["block-start","block-end","tool-call-delta","finish"].includes(e)}export{ai as DshJsonRpcAdapter};
@@ -1,4 +1,4 @@
1
- import{EventEmitter as a}from"node:events";class u extends a{readable;writable;options;nextId=1;pending=new Map;completedIds=new Set;buffer="";closed=!1;writeChain=Promise.resolve();maxLineBytes;constructor(t,e,r={}){super(),this.readable=t,this.writable=e,this.options=r,this.maxLineBytes=r.maxLineBytes??4*1024*1024,t.setEncoding("utf8"),t.on("data",i=>this.onData(i)),t.on("end",()=>this.close(new Error("JSON-RPC stdout ended"))),t.on("error",i=>this.protocolError(i)),e.on("error",i=>this.protocolError(i))}initialize(t,e){return this.call("initialize",t,e)}prompt(t,e){return this.call("session/prompt",t,e)}async shutdown(t){await this.call("shutdown",{},t)}async call(t,e,r){if(this.closed)throw new Error("JSON-RPC client closed");const i=this.nextId++,o=String(i),n={jsonrpc:"2.0",id:i,method:t,params:e??null};return new Promise((l,c)=>{const d={resolve:l,reject:c};if(r){const s=()=>{this.pending.delete(o),c(Object.assign(new Error("JSON-RPC call aborted"),{code:"aborted"}))};if(d.abort=()=>r.removeEventListener("abort",s),r.aborted){s();return}r.addEventListener("abort",s,{once:!0})}this.pending.set(o,d),this.write(n).catch(s=>{this.pending.delete(o),d.abort?.(),c(s)})})}close(t=new Error("JSON-RPC client closed")){if(!this.closed){this.closed=!0;for(const e of this.pending.values())e.abort?.(),e.reject(t);this.pending.clear(),this.emit("close",t)}}onData(t){if(this.closed)return;if(this.buffer+=t,Buffer.byteLength(this.buffer,"utf8")>this.maxLineBytes&&!this.buffer.includes(`
1
+ import{EventEmitter as h}from"node:events";class u extends h{readable;writable;options;nextId=1;pending=new Map;completedIds=new Set;buffer="";closed=!1;writeChain=Promise.resolve();maxLineBytes;get isClosed(){return this.closed}constructor(t,e,r={}){super(),this.readable=t,this.writable=e,this.options=r,this.maxLineBytes=r.maxLineBytes??4*1024*1024,t.setEncoding("utf8"),t.on("data",i=>this.onData(i)),t.on("end",()=>this.close(new Error("JSON-RPC stdout ended"))),t.on("error",i=>this.protocolError(i)),e.on("error",i=>this.protocolError(i))}initialize(t,e){return this.call("initialize",t,e)}prompt(t,e){return this.call("session/prompt",t,e)}async shutdown(t){await this.call("shutdown",{},t)}async call(t,e,r){if(this.closed)throw new Error("JSON-RPC client closed");const i=this.nextId++,o=String(i),n={jsonrpc:"2.0",id:i,method:t,params:e??null};return new Promise((l,c)=>{const d={resolve:l,reject:c};if(r){const s=()=>{this.pending.delete(o),c(Object.assign(new Error("JSON-RPC call aborted"),{code:"aborted"}))};if(d.abort=()=>r.removeEventListener("abort",s),r.aborted){s();return}r.addEventListener("abort",s,{once:!0})}this.pending.set(o,d),this.write(n).catch(s=>{this.pending.delete(o),d.abort?.(),c(s)})})}close(t=new Error("JSON-RPC client closed")){if(!this.closed){this.closed=!0;for(const e of this.pending.values())e.abort?.(),e.reject(t);this.pending.clear(),this.emit("close",t)}}onData(t){if(this.closed)return;if(this.buffer+=t,Buffer.byteLength(this.buffer,"utf8")>this.maxLineBytes&&!this.buffer.includes(`
2
2
  `)){this.protocolError(Object.assign(new Error("JSON-RPC line exceeds byte limit"),{code:"line_too_large"}));return}const e=this.buffer.split(`
3
3
  `);if(this.buffer=e.pop()??"",Buffer.byteLength(this.buffer,"utf8")>this.maxLineBytes){this.protocolError(Object.assign(new Error("JSON-RPC line exceeds byte limit"),{code:"line_too_large"}));return}for(const r of e)if(r.trim()){if(Buffer.byteLength(r,"utf8")>this.maxLineBytes){this.protocolError(Object.assign(new Error("JSON-RPC line exceeds byte limit"),{code:"line_too_large"}));return}if(this.dispatch(r),this.closed)return}}dispatch(t){let e;try{e=JSON.parse(t)}catch{this.protocolError(Object.assign(new Error("stdout contains invalid JSON-RPC"),{code:"invalid_json"}));return}if(this.options.capture?.append("in",e),e.jsonrpc!=="2.0"){this.protocolError(new Error("unsupported JSON-RPC version"));return}if(e.id!==void 0&&typeof e.method!="string"){const r=String(e.id);if(this.completedIds.has(r)){this.protocolError(new Error(`duplicate JSON-RPC response id=${r}`));return}const i=this.pending.get(r);if(!i){this.protocolError(new Error(`unexpected JSON-RPC response id=${r}`));return}if(this.pending.delete(r),this.completedIds.add(r),this.completedIds.size>1024&&this.completedIds.delete(this.completedIds.values().next().value),i.abort?.(),e.error&&typeof e.error=="object"){const o=e.error;i.reject(Object.assign(new Error(String(o.message??"JSON-RPC error")),{code:o.code,data:o.data}))}else i.resolve(e.result);return}if(typeof e.method=="string"&&e.id===void 0){const r=e.method,i=e.params;setImmediate(()=>{this.closed||this.emit("notification",r,i)});return}this.protocolError(new Error("unsupported JSON-RPC server request/envelope"))}write(t){const e=`${JSON.stringify(t)}
4
4
  `;if(Buffer.byteLength(e,"utf8")>this.maxLineBytes)return Promise.reject(new Error("outbound JSON-RPC line exceeds byte limit"));this.options.capture?.append("out",t);const r=this.writeChain.then(()=>new Promise((i,o)=>{this.writable.write(e,"utf8",n=>n?o(n):i())}));return this.writeChain=r.catch(()=>{}),r}protocolError(t){this.emit("protocolError",t),this.close(t)}}export{u as DshJsonRpcClient};
@@ -1 +1 @@
1
- import{chmodSync as u,existsSync as m,mkdirSync as E,realpathSync as f,statSync as l}from"node:fs";import{isAbsolute as h,relative as _,resolve as d}from"node:path";import{log as S}from"../../core/log/index.js";import{hasChildProcesses as y,killProcessGroup as w,resolveCommandPath as O,spawnCommand as v}from"../../core/runtime/spawn.js";import{DshJsonRpcClient as L}from"./jsonrpc-client.js";import{effectiveDshReasoningEffort as k}from"./types.js";import{permissionModeFor as x}from"./toolbar-state.js";const T="deepseek-harness-runtime",C="deepseek-harness-sdk-runtime",g=new Set(["0.0.1"]),b=15e3,A=["PATH","SystemRoot","COMSPEC","PATHEXT","WINDIR","LANG","LC_ALL","LC_CTYPE","TZ","TMPDIR","TMP","TEMP","HTTPS_PROXY","HTTP_PROXY","ALL_PROXY","NO_PROXY","https_proxy","http_proxy","all_proxy","no_proxy","SSL_CERT_FILE","SSL_CERT_DIR","NODE_EXTRA_CA_CERTS"],H=["DEEPSEEK_API_KEY","DEEPSEEK_BASE_URL"];function M(n,s){const t={};for(const i of A){const e=s?.[i]??n[i];e!==void 0&&(t[i]=e)}for(const i of H){const e=s?.[i];e!==void 0&&(t[i]=e)}return t}class ${options;process=null;client=null;stderrTail="";constructor(s){this.options=s}async start(){this.validatePaths(),E(this.options.home,{recursive:!0,mode:448}),E(this.options.sessionRoot,{recursive:!0,mode:448});try{u(this.options.home,448),u(this.options.sessionRoot,448)}catch{}const s={...M(process.env,this.options.env),HOME:this.options.home,DSH_CORDIS_CONFIG:this.options.cordisPath,DSH_HOME:this.options.home,DSH_CWD:this.options.cwd,DSH_SESSION_ROOT:this.options.sessionRoot,DSH_SYSTEM_PROMPT:this.options.systemPrompt,DSH_PERMISSION_MODE:x(this.options.settings.modeId),DSH_TELEMETRY_DISABLED:"1",GRIX_SESSION_SKILL_IDS:JSON.stringify(this.options.settings.skillIds??[]),...this.options.skillsDir?{GRIX_SKILLS_DIR:this.options.skillsDir}:{}},t=O(this.options.command,s.PATH),i=v(t,[this.options.cordisPath,...this.options.args??[]],{cwd:this.options.cwd,env:s,stdio:["pipe","pipe","pipe"],detached:!0});if(this.process=i.process,!this.process.stdout||!this.process.stdin)throw new Error("Harness stdio unavailable");this.client=new L(this.process.stdout,this.process.stdin,{maxLineBytes:this.options.maxLineBytes,capture:this.options.capture}),this.process.stderr?.setEncoding("utf8"),this.process.stderr?.on("data",p=>{this.stderrTail=N(`${this.stderrTail}${String(p)}`,s.DEEPSEEK_API_KEY).slice(-8192)});const e=new Promise((p,D)=>this.process?.once("error",D)),c=new AbortController,r=this.client.initialize({cwd:this.options.cwd,provider:"deepseek-official",model:this.options.settings.modelId,reasoningEffort:k(this.options.settings),maxTokens:this.options.settings.maxTokens},c.signal),a=P(this.options.initializeTimeoutMs??b,"Harness initialize timed out",()=>c.abort()),o=await Promise.race([r,e,a.promise]).finally(a.cancel);if(o.serverInfo?.name!==C||!g.has(o.serverInfo?.version))throw await this.terminate(),Object.assign(new Error(`incompatible Harness server ${R(o.serverInfo?.name)}@${R(o.serverInfo?.version)}`),{code:"protocol_incompatible"});const I=o.capabilities&&typeof o.capabilities=="object"?o.capabilities:{};return(this.options.settings.skillIds?.length??0)>0&&I.sessionSkillAllowlist!==!0&&S.warn(T,"Harness runtime does not guarantee the session skill allowlist; continuing without treating session skills as applied"),S.info(T,`initialized server=${o.serverInfo.name}@${o.serverInfo.version} env_keys=${Object.keys(s).filter(p=>p.startsWith("DSH_")||p.startsWith("DEEPSEEK_")).join(",")}`),o}async shutdown(){if(!this.process)return;const t=this.waitForExit(1e3).then(()=>!0,()=>!1),i=P(2e3,"Harness shutdown timed out");try{await Promise.race([this.client?.shutdown(),i.promise])}catch{}finally{i.cancel()}await t||await this.terminate(),this.client?.close(),this.client=null,this.process=null}async terminate(){const s=this.process;if(!s)return;const t=this.waitForExit(3e3).then(()=>!0,()=>!1);w(s,"SIGTERM"),await t||w(s,"SIGKILL"),this.client?.close(new Error("Harness runtime terminated")),this.client=null,this.process=null}async cancel(s){await this.terminate()}isConnected(){return!!this.process&&this.process.exitCode===null&&!!this.client}onExit(s){const t=this.process;return t?(t.once("exit",s),()=>t.removeListener("exit",s)):()=>{}}async hasBackgroundWork(){return this.process?.pid?y(this.process.pid,[this.process.pid]):!1}validatePaths(){const s=f(d(this.options.cwd));if(!m(s)||!l(s).isDirectory())throw new Error("bound workspace does not exist or is not a directory");if(!h(this.options.cordisPath)||!m(this.options.cordisPath)||!l(this.options.cordisPath).isFile())throw new Error("Cordis path must be an existing absolute file");const t=_(s,f(d(this.options.cordisPath)));if(t===""||!t.startsWith("..")&&!h(t))throw new Error("Cordis deployment file must be outside the user workspace");if((l(this.options.cordisPath).mode&18)!==0)throw new Error("Cordis deployment file must not be group/world writable");const i=_(s,d(this.options.sessionRoot));if(i===""||!i.startsWith("..")&&!h(i))throw new Error("DSH_SESSION_ROOT must be outside the workspace")}waitForExit(s){const t=this.process;return!t||t.exitCode!==null?Promise.resolve():new Promise((i,e)=>{const c=setTimeout(()=>{a(),e(new Error("process exit timeout"))},s),r=()=>{a(),i()},a=()=>{clearTimeout(c),t.removeListener("exit",r)};t.once("exit",r)})}}function P(n,s,t){let i;return{promise:new Promise((c,r)=>{i=setTimeout(()=>{t?.(),r(Object.assign(new Error(s),{code:"runtime_timeout"}))},n),i.unref?.()}),cancel:()=>{i&&clearTimeout(i)}}}function N(n,s){let t=n.replace(/(api[_-]?key|authorization|bearer)\s*[:=]\s*\S+/gi,"$1=[REDACTED]");return s&&(t=t.split(s).join("[REDACTED]")),t}function R(n){return String(n??"unknown").replace(/[\u0000-\u001f\u007f]/g,"").slice(0,128)||"unknown"}export{$ as DshProcessRuntime,M as sanitizeDshRuntimeEnv};
1
+ import{chmodSync as u,existsSync as m,mkdirSync as E,realpathSync as f,statSync as p}from"node:fs";import{isAbsolute as h,relative as _,resolve as d}from"node:path";import{log as S}from"../../core/log/index.js";import{hasChildProcesses as y,killProcessGroup as w,resolveCommandPath as O,spawnCommand as v}from"../../core/runtime/spawn.js";import{DshJsonRpcClient as C}from"./jsonrpc-client.js";import{effectiveDshReasoningEffort as L}from"./types.js";import{permissionModeFor as k}from"./toolbar-state.js";const T="deepseek-harness-runtime",x="deepseek-harness-sdk-runtime",g=new Set(["0.0.1"]),b=15e3,A=["PATH","SystemRoot","COMSPEC","PATHEXT","WINDIR","LANG","LC_ALL","LC_CTYPE","TZ","TMPDIR","TMP","TEMP","HTTPS_PROXY","HTTP_PROXY","ALL_PROXY","NO_PROXY","https_proxy","http_proxy","all_proxy","no_proxy","SSL_CERT_FILE","SSL_CERT_DIR","NODE_EXTRA_CA_CERTS"],H=["DEEPSEEK_API_KEY","DEEPSEEK_BASE_URL"];function M(n,s){const t={};for(const i of A){const e=s?.[i]??n[i];e!==void 0&&(t[i]=e)}for(const i of H){const e=s?.[i];e!==void 0&&(t[i]=e)}return t}class ${options;process=null;client=null;stderrTail="";constructor(s){this.options=s}async start(){this.validatePaths(),E(this.options.home,{recursive:!0,mode:448}),E(this.options.sessionRoot,{recursive:!0,mode:448});try{u(this.options.home,448),u(this.options.sessionRoot,448)}catch{}const s={...M(process.env,this.options.env),HOME:this.options.home,DSH_CORDIS_CONFIG:this.options.cordisPath,DSH_HOME:this.options.home,DSH_CWD:this.options.cwd,DSH_SESSION_ROOT:this.options.sessionRoot,DSH_SYSTEM_PROMPT:this.options.systemPrompt,DSH_PERMISSION_MODE:k(this.options.settings.modeId),DSH_TELEMETRY_DISABLED:"1",GRIX_SESSION_SKILL_IDS:JSON.stringify(this.options.settings.skillIds??[]),...this.options.skillsDir?{GRIX_SKILLS_DIR:this.options.skillsDir}:{}},t=O(this.options.command,s.PATH),i=v(t,[this.options.cordisPath,...this.options.args??[]],{cwd:this.options.cwd,env:s,stdio:["pipe","pipe","pipe"],detached:!0});if(this.process=i.process,!this.process.stdout||!this.process.stdin)throw new Error("Harness stdio unavailable");this.client=new C(this.process.stdout,this.process.stdin,{maxLineBytes:this.options.maxLineBytes,capture:this.options.capture}),this.process.stderr?.setEncoding("utf8"),this.process.stderr?.on("data",l=>{this.stderrTail=N(`${this.stderrTail}${String(l)}`,s.DEEPSEEK_API_KEY).slice(-8192)});const e=new Promise((l,D)=>this.process?.once("error",D)),c=new AbortController,r=this.client.initialize({cwd:this.options.cwd,provider:"deepseek-official",model:this.options.settings.modelId,reasoningEffort:L(this.options.settings),maxTokens:this.options.settings.maxTokens},c.signal),a=P(this.options.initializeTimeoutMs??b,"Harness initialize timed out",()=>c.abort()),o=await Promise.race([r,e,a.promise]).finally(a.cancel);if(o.serverInfo?.name!==x||!g.has(o.serverInfo?.version))throw await this.terminate(),Object.assign(new Error(`incompatible Harness server ${R(o.serverInfo?.name)}@${R(o.serverInfo?.version)}`),{code:"protocol_incompatible"});const I=o.capabilities&&typeof o.capabilities=="object"?o.capabilities:{};return(this.options.settings.skillIds?.length??0)>0&&I.sessionSkillAllowlist!==!0&&S.warn(T,"Harness runtime does not guarantee the session skill allowlist; continuing without treating session skills as applied"),S.info(T,`initialized server=${o.serverInfo.name}@${o.serverInfo.version} env_keys=${Object.keys(s).filter(l=>l.startsWith("DSH_")||l.startsWith("DEEPSEEK_")).join(",")}`),o}async shutdown(){if(!this.process)return;const t=this.waitForExit(1e3).then(()=>!0,()=>!1),i=P(2e3,"Harness shutdown timed out");try{await Promise.race([this.client?.shutdown(),i.promise])}catch{}finally{i.cancel()}await t||await this.terminate(),this.client?.close(),this.client=null,this.process=null}async terminate(){const s=this.process;if(!s)return;const t=this.waitForExit(3e3).then(()=>!0,()=>!1);w(s,"SIGTERM"),await t||w(s,"SIGKILL"),this.client?.close(new Error("Harness runtime terminated")),this.client=null,this.process=null}async cancel(s){await this.terminate()}isConnected(){return!!this.process&&this.process.exitCode===null&&!!this.client&&!this.client.isClosed}onExit(s){const t=this.process;return t?(t.once("exit",s),()=>t.removeListener("exit",s)):()=>{}}async hasBackgroundWork(){return this.process?.pid?y(this.process.pid,[this.process.pid]):!1}validatePaths(){const s=f(d(this.options.cwd));if(!m(s)||!p(s).isDirectory())throw new Error("bound workspace does not exist or is not a directory");if(!h(this.options.cordisPath)||!m(this.options.cordisPath)||!p(this.options.cordisPath).isFile())throw new Error("Cordis path must be an existing absolute file");const t=_(s,f(d(this.options.cordisPath)));if(t===""||!t.startsWith("..")&&!h(t))throw new Error("Cordis deployment file must be outside the user workspace");if((p(this.options.cordisPath).mode&18)!==0)throw new Error("Cordis deployment file must not be group/world writable");const i=_(s,d(this.options.sessionRoot));if(i===""||!i.startsWith("..")&&!h(i))throw new Error("DSH_SESSION_ROOT must be outside the workspace")}waitForExit(s){const t=this.process;return!t||t.exitCode!==null?Promise.resolve():new Promise((i,e)=>{const c=setTimeout(()=>{a(),e(new Error("process exit timeout"))},s),r=()=>{a(),i()},a=()=>{clearTimeout(c),t.removeListener("exit",r)};t.once("exit",r)})}}function P(n,s,t){let i;return{promise:new Promise((c,r)=>{i=setTimeout(()=>{t?.(),r(Object.assign(new Error(s),{code:"runtime_timeout"}))},n),i.unref?.()}),cancel:()=>{i&&clearTimeout(i)}}}function N(n,s){let t=n.replace(/(api[_-]?key|authorization|bearer)\s*[:=]\s*\S+/gi,"$1=[REDACTED]");return s&&(t=t.split(s).join("[REDACTED]")),t}function R(n){return String(n??"unknown").replace(/[\u0000-\u001f\u007f]/g,"").slice(0,128)||"unknown"}export{$ as DshProcessRuntime,M as sanitizeDshRuntimeEnv};
@@ -1 +1 @@
1
- import{createHash as H}from"node:crypto";import{existsSync as p,readFileSync as a,readdirSync as y,realpathSync as g,statSync as d}from"node:fs";import{homedir as P}from"node:os";import{basename as h,dirname as c,join as i,resolve as l}from"node:path";import{fileURLToPath as E}from"node:url";function u(e,r=process.env){const t=e?.trim()||r.DSH_HOME?.trim()||i(P(),".dsh");return l(t)}const s="web",D="headless";function m(e){return O(String(e??"").trim())}function A(e){const r=m(e);if(r===D)throw Object.assign(new Error("headless is a one-shot DSH profile and cannot be used as a Grix Profile"),{code:"profile_invalid"});return r}function J(e,r){return i(l(e),"profiles",m(r))}function C(e={}){for(const r of[e.binding,e.global,e.adapter]){const t=String(r??"").trim();if(t)try{return A(t)}catch{continue}}return s}function S(e){return e===s?"Web":e}function R(e,r){if(r===s)return!0;try{const n=JSON.parse(a(i(e,"package.json"),"utf8")).dsh?.profile?.bundles;return Array.isArray(n)&&n.some(o=>String(o).includes("dsh-web-app"))}catch{return!1}}function V(e={}){const r=u(e.dshHome,e.env),t=new Map;t.set(s,{id:s,displayName:S(s),webApp:!0});const n=i(r,"profiles");if(!p(n)||!d(n).isDirectory())return[...t.values()];for(const o of y(n).sort()){if(o===D||o===s||o==="node_modules")continue;try{m(o)}catch{continue}const f=i(n,o);try{if(!d(f).isDirectory()||!JSON.parse(a(i(f,"package.json"),"utf8")).dsh?.profile)continue}catch{continue}t.set(o,{id:o,displayName:S(o),webApp:R(f,o)})}return[...t.values()]}function w(e){const r=u(e.dshHome,e.env),t=m(e.profileName?.trim()||s),n=l(r,"profiles",t),o=p(n)?g(n):n;return{dshHome:r,profileName:t,profileRoot:o,profileKey:N(o)}}function N(e){return H("sha256").update(l(e)).digest("hex")}function I(e){return i(e.dshHome,"run","grix-dsh-bridge",e.profileKey)}function _(e){const r=I(e);if(!p(r)||!d(r).isDirectory())return[];const t=[];for(const n of y(r).filter(o=>o.endsWith(".json")).sort())try{const o=JSON.parse(a(i(r,n),"utf8"));if(!F(o)||o.profileKey!==e.profileKey||!M(o.pid)||!p(o.tokenPath)||!d(o.tokenPath).isFile())continue;t.push(o)}catch{}return t.sort((n,o)=>b(o)-b(n)||o.instanceId.localeCompare(n.instanceId))}function W(e){const r=_(e);if(r.length===0)throw Object.assign(new Error(`No live Grix Bridge endpoint in DSH profile "${e.profileName}". If Bridge is already installed, restart the profile (stop it, then: dsh --profile ${e.profileName}); otherwise install the Grix Bridge plugin first.`),{code:"bridge_missing"});return r[0]}function b(e){const r=Date.parse(e.startedAt);return Number.isFinite(r)?r:0}function T(e){let r=c(E(e)),t;for(;c(r)!==r;){const o=i(r,"package.json");if(p(o))try{if(JSON.parse(a(o,"utf8")).dsh?.profile)return x(r)}catch{}h(r)==="node_modules"&&(t=c(r)),r=c(r)}if(t)return x(t);const n=u();return w({dshHome:n,profileName:process.env.GRIX_DSH_PROFILE||s})}function x(e){const r=g(e),t=h(r),n=c(r);return{dshHome:h(n)==="profiles"?c(n):u(),profileName:t,profileRoot:r,profileKey:N(r)}}function O(e){if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\")||e.includes("\0"))throw Object.assign(new Error("Invalid DSH profile name"),{code:"profile_invalid"});return e}function F(e){return e.schemaVersion===1&&(e.transport==="unix"||e.transport==="pipe")&&typeof e.address=="string"&&e.address.length>0&&Number.isSafeInteger(e.pid)&&Number(e.pid)>0&&typeof e.startedAt=="string"&&typeof e.profileKey=="string"&&typeof e.profileName=="string"&&typeof e.dshVersion=="string"&&typeof e.bridgeVersion=="string"&&Number.isSafeInteger(e.protocolMin)&&Number.isSafeInteger(e.protocolMax)&&typeof e.instanceId=="string"&&typeof e.tokenPath=="string"}function M(e){try{return process.kill(e,0),!0}catch(r){return r.code==="EPERM"}}export{s as DEFAULT_DSH_PROFILE_NAME,D as DSH_HEADLESS_PROFILE_NAME,A as assertSelectableDshProfileName,I as bridgeDiscoveryDirectory,_ as discoverDshBridgeEndpoints,S as dshProfileDisplayName,T as inferProfileIdentityFromModule,V as listDshProfiles,m as parseDshProfileName,R as profileHasWebApp,N as profileKeyFor,J as resolveDshConnectorProfileDataDir,u as resolveDshHome,w as resolveDshProfileIdentity,C as resolveDshSelectedProfileName,W as selectDshBridgeEndpoint};
1
+ import{createHash as H}from"node:crypto";import{existsSync as c,readFileSync as a,readdirSync as y,realpathSync as g,statSync as d}from"node:fs";import{homedir as P}from"node:os";import{basename as h,dirname as f,join as i,resolve as l}from"node:path";import{fileURLToPath as E}from"node:url";function u(e,r=process.env){const t=e?.trim()||r.DSH_HOME?.trim()||i(P(),".dsh");return l(t)}const s="web",D="headless";function m(e){return O(String(e??"").trim())}function A(e){const r=m(e);if(r===D)throw Object.assign(new Error("headless is a one-shot DSH profile and cannot be used as a Grix Profile"),{code:"profile_invalid"});return r}function J(e,r){return i(l(e),"profiles",m(r))}function C(e={}){for(const r of[e.binding,e.global,e.adapter]){const t=String(r??"").trim();if(t)try{return A(t)}catch{continue}}return s}function S(e){return e===s?"Web":e}function R(e,r){if(r===s)return!0;try{const n=JSON.parse(a(i(e,"package.json"),"utf8")).dsh?.profile?.bundles;return Array.isArray(n)&&n.some(o=>String(o).includes("dsh-web-app"))}catch{return!1}}function V(e={}){const r=u(e.dshHome,e.env),t=new Map;t.set(s,{id:s,displayName:S(s),webApp:!0});const n=i(r,"profiles");if(!c(n)||!d(n).isDirectory())return[...t.values()];for(const o of y(n).sort()){if(o===D||o===s||o==="node_modules")continue;try{m(o)}catch{continue}const p=i(n,o);try{if(!d(p).isDirectory()||!JSON.parse(a(i(p,"package.json"),"utf8")).dsh?.profile)continue}catch{continue}t.set(o,{id:o,displayName:S(o),webApp:R(p,o)})}return[...t.values()]}function w(e){const r=u(e.dshHome,e.env),t=m(e.profileName?.trim()||s),n=l(r,"profiles",t),o=c(n)?g(n):n;return{dshHome:r,profileName:t,profileRoot:o,profileKey:N(o)}}function N(e){return H("sha256").update(l(e)).digest("hex")}function I(e){return i(e.dshHome,"run","grix-dsh-bridge",e.profileKey)}function _(e){const r=I(e);if(!c(r)||!d(r).isDirectory())return[];const t=[];for(const n of y(r).filter(o=>o.endsWith(".json")).sort())try{const o=JSON.parse(a(i(r,n),"utf8"));if(!F(o)||o.profileKey!==e.profileKey||!M(o.pid)||!c(o.tokenPath)||!d(o.tokenPath).isFile()||o.transport==="unix"&&!c(o.address))continue;t.push(o)}catch{}return t.sort((n,o)=>b(o)-b(n)||o.instanceId.localeCompare(n.instanceId))}function W(e){const r=_(e);if(r.length===0)throw Object.assign(new Error(`No live Grix Bridge endpoint in DSH profile "${e.profileName}". If Bridge is already installed, restart the profile (stop it, then: dsh --profile ${e.profileName}); otherwise install the Grix Bridge plugin first.`),{code:"bridge_missing"});return r[0]}function b(e){const r=Date.parse(e.startedAt);return Number.isFinite(r)?r:0}function T(e){let r=f(E(e)),t;for(;f(r)!==r;){const o=i(r,"package.json");if(c(o))try{if(JSON.parse(a(o,"utf8")).dsh?.profile)return x(r)}catch{}h(r)==="node_modules"&&(t=f(r)),r=f(r)}if(t)return x(t);const n=u();return w({dshHome:n,profileName:process.env.GRIX_DSH_PROFILE||s})}function x(e){const r=g(e),t=h(r),n=f(r);return{dshHome:h(n)==="profiles"?f(n):u(),profileName:t,profileRoot:r,profileKey:N(r)}}function O(e){if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\")||e.includes("\0"))throw Object.assign(new Error("Invalid DSH profile name"),{code:"profile_invalid"});return e}function F(e){return e.schemaVersion===1&&(e.transport==="unix"||e.transport==="pipe")&&typeof e.address=="string"&&e.address.length>0&&Number.isSafeInteger(e.pid)&&Number(e.pid)>0&&typeof e.startedAt=="string"&&typeof e.profileKey=="string"&&typeof e.profileName=="string"&&typeof e.dshVersion=="string"&&typeof e.bridgeVersion=="string"&&Number.isSafeInteger(e.protocolMin)&&Number.isSafeInteger(e.protocolMax)&&typeof e.instanceId=="string"&&typeof e.tokenPath=="string"}function M(e){try{return process.kill(e,0),!0}catch(r){return r.code==="EPERM"}}export{s as DEFAULT_DSH_PROFILE_NAME,D as DSH_HEADLESS_PROFILE_NAME,A as assertSelectableDshProfileName,I as bridgeDiscoveryDirectory,_ as discoverDshBridgeEndpoints,S as dshProfileDisplayName,T as inferProfileIdentityFromModule,V as listDshProfiles,m as parseDshProfileName,R as profileHasWebApp,N as profileKeyFor,J as resolveDshConnectorProfileDataDir,u as resolveDshHome,w as resolveDshProfileIdentity,C as resolveDshSelectedProfileName,W as selectDshBridgeEndpoint};
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "bridgeVersion": "4.16.0",
4
- "tarball": "grix-dsh-bridge-4.16.0.tgz",
5
- "size": 24210,
3
+ "bridgeVersion": "4.16.1",
4
+ "tarball": "grix-dsh-bridge-4.16.1.tgz",
5
+ "size": 24211,
6
6
  "unpackedSize": 96662,
7
- "shasum": "8a33e845783a1fd5810e15d72cfa00975d6dfe0d",
8
- "integrity": "sha512-jeyck/gCIUgkdb3/Wwr0oWQvK4MYqmzwO8IpgHFt+4+FqCoAGheXfqYW0nMChrF0D1MfruPDexGVU++KmG1ZmA=="
7
+ "shasum": "fc04db27b9554184f780a3f046814d43ca26b534",
8
+ "integrity": "sha512-8FoG6eL5UPFo8RMhQD7sDDB3/DmswSWfpuBPeWZ3sxTiTSPKa9f69+ND6Vtnstx7qAVYZ33/uC9MnxcdEoCXvw=="
9
9
  }
@@ -1,3 +1,3 @@
1
- import k from"node:path";import{tmpdir as F}from"node:os";import{createHash as M,randomUUID as T}from"node:crypto";import{ConnectionManager as U}from"../core/aibot/index.js";import{AUDIT_LOCAL_ACTION_TYPES as q}from"../core/aibot/types.js";import{ClaudeAdapter as $}from"../adapter/claude/index.js";import{CodexAdapter as H}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 N}from"../adapter/openhuman/index.js";import{CursorAdapter as j}from"../adapter/cursor/index.js";import{CodeWhaleAdapter as G}from"../adapter/codewhale/index.js";import{OpenCodeAdapter as P}from"../adapter/opencode/index.js";import{AgyAdapter as D}from"../adapter/agy/index.js";import{DshJsonRpcAdapter as K}from"../adapter/deepseek-harness/index.js";import{LOCAL_ACTION_TYPES as f,SESSION_CONTROL_ERROR_CODES as E,SESSION_CONTROL_VERBS as w,SESSION_MODE_IDS as z}from"../adapter/claude/protocol-contract.js";import{isAuditLocalActionType as J}from"../audit/query/audit-local-actions.js";import{shouldEnableRawApiCapture as Q}from"../audit/raw-capture/types.js";import{buildWireSkills as Y}from"../core/skill-sync/sync-state.js";import{executeEventTool as V}from"../core/mcp/event-tool-executor.js";import{fetchAvailableModels as X}from"../adapter/claude/model-list.js";import{primeAgyModels as Z}from"../adapter/agy/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{agentIdOf as ve}from"../adapter/shared/native-provider-config.js";import{scanDshSessions as _e}from"../adapter/deepseek-harness/session-scanner.js";import{SessionScanCache as v,resolveCodexLeafDirs as Se,resolveClaudeLeafDirs as Ce,resolveAcpLeafDirs as be,resolvePiLeafDirs as Ae,resolveCodeWhaleLeafDirs as Ee,resolveCursorLeafDirs as we,resolveOpenCodeLeafDirs as ye,resolveDshLeafDirs as Re,resolveReasonixLeafDirs as ke}from"./session-scan-cache.js";import{log as h,ConversationLog as Te,AgentApiPacketLog as Pe,BridgeEventLog as xe,GRIX_PATHS as y}from"../core/log/index.js";import{routeSessionControlCommand as Le,routeSessionControlLocalAction as Me}from"./session-control-router.js";import{maybeOfferCliInstall as $e,handleCliInstallQuestionReply as He,handleCliInstallInteractionReply as De,runConfirmedCliInstall as Qe}from"./cli-install-flow.js";import{handleEventCancel as Oe,waitForEventDone as Ie,handleAibotStop as Be,killAndResumeStopSlot as Fe,handleAibotRevoke as Ue}from"./event-stop.js";import{handleConfigureGatewayProvider as qe,getAuditLocalActionHandler as We,handleAuditLocalAction as Ne,handleConnectorRollback as je,getRelayStateSyncer as Ge,relayStateSyncOnConnect as Ke,reportRelayStateLocalChange as ze,handleApplyRelayState as Je,fetchRelayCredential as Ye,isSharedInstance as Ve}from"./connector-ops.js";import{CONNECTOR_ADMIN_ACTION_TYPE as Xe,handleConnectorAdminLocalAction as Ze}from"./remote-admin.js";import{unbindSession as et,handleUnbindTextCommand as tt,handleUnbindLocalAction as nt,handleListSessionsTextCommand as it,handleListSessionsLocalAction as st,handleSyncHistoryLocalAction as ot}from"./session-list.js";import{handleCodexSessionControlOpen as rt,handleSessionControlForPool as at,handleSessionControlLocalActionForPool as dt,handleCodexSessionControlLocalActionOpen as lt,handleCursorSessionControlLocalActionOpen as ct,handlePiSessionControlOpen as ht,handlePiSessionControlRestart as ut,handlePiSessionControlRestartLocalAction as pt,syncOpenCodeBinding as gt,isWorkspaceFreeClient as ft,isCwdLockedClient as mt,ensureDefaultBindingForWorkspaceFreeClient as vt,bindSessionForPool as _t,deferredCallbacks as St,handleOpenHumanSessionControlOpen as Ct,handleCodeWhaleSessionControlOpen as bt,handleCodeWhaleSessionControlLocalActionOpen as At,handleDeepSeekSessionControlLocalActionOpen as Et}from"./session-control-open.js";import{CWD_LOCKED_REJECT_MSG as wt}from"./cwd-policy.js";import{normalizeCustomToolbarItems as yt}from"./acp-custom-toolbar.js";import{handleGetSessionUsage as Rt,handleThreadCompact as kt}from"./session-usage.js";import{handleSkillDeleteLocalAction as Tt,handleSkillUploadLocalAction as Pt,handleSkillEnableLocalAction as xt,handleSkillRefreshLocalAction as Lt,handleSkillDisableLocalAction as Mt,computeSkillReport as $t,reportSessionSkills as Ht,skillsSyncGroupKey as Dt,forceRefreshSkills as Qt,adoptSkillsWireHashFromDisk as Ot,buildLibrarySkillsReport as It,skillLookupEnv as Bt}from"./skill-actions.js";import{resolveToolbarSelection as Ft,persistToolbarSelection as O}from"./toolbar-selection.js";import{normalizeClaudeModeId as Ut,handleExecCommandOptions as qt,resolveSessionModelId as Wt,resolveSessionModeId as Nt,resolveCursorSessionModeId as jt,resolveClaudeSessionEffort as Gt,resolveClaudeSessionModeId as Kt,currentClaudeModeId as zt,buildCursorToolbarMeta as Jt,buildAgyToolbarMeta as Yt,buildAgyQuotaMeta as Vt,sendAgyBindingCard as Xt,refreshAndPushAgyQuota as Zt,handleAgySetModel as en,buildClaudeToolbarMeta as tn}from"./toolbar-meta.js";import{resolveProviderQuotaSource as nn,maybeQueryProviderQuota as sn,startProviderQuotaTimer as on,stopProviderQuotaTimer as rn,refreshAndPushProviderQuota as an,pushProviderQuotaToBindings as dn,enrichProviderQuotaMeta as ln,providerQuotaMetaPayload as cn,refreshProviderQuotaForSession as hn,refreshQuotaAfterModelSwitch as un,doRefreshQuotaAfterModelSwitch as pn}from"./provider-quota.js";import{handleGetRateLimits as gn,resolveRateLimitWakeSessionId as fn,wakeRateLimitSlot as mn}from"./rate-limits.js";import{RevokeHandler as vn}from"./revoke-handler.js";import{AdapterPool as _n}from"./adapter-pool.js";import{parseSessionControlCommand as Sn}from"./session-controller.js";import{isOpenSessionDirectiveMessage as Cn,parseExecApprovalResolutionMessage as bn,parseAgentQuestionReplyMessage as An}from"../core/protocol/interaction-parser.js";import{rejectUnusableAuditOptions as En}from"./inbound-audit-gate.js";import{interceptUnboundInboundEvent as wn}from"./inbound-binding-gate.js";import{dispatchSessionControlTextCommand as yn}from"./text-command-session-control.js";import{dispatchSessionControlLocalAction as Rn}from"./local-action-session-control.js";import{handleCreateFolderLocalAction as kn,handleFileListLocalAction as Tn}from"./local-action-files.js";import{handleAcpToolbarLocalAction as Pn,persistToolbarSelection as xn}from"./local-action-toolbar.js";import{buildOpenedBindingResult as Ln,ensureImportedAgentSession as Mn,hasDiskScanner as $n,normalizePathForCompare as Hn,providerKeyForAdapter as Dn,resolveAgentSessionId as Qn,resolveOrphanTitle as On,setResolvedAgentSessionId as In}from"./session-identity.js";import{buildDshOpenedToolbarMeta as Bn,dshCatalogDataRoot as Fn}from"./dsh-toolbar.js";import{ensureSlotStarted as Un,failSessionOpen as qn,getClaudeWorkerStatus as Wn,refreshClaudeWorkerStatusCard as Nn,resolveCwdForBinding as jn}from"./session-open-helpers.js";import{handleAcpSetModel as Gn,handleAcpSetMode as Kn,resolveAcpInitialDefaults as zn}from"./acp-toolbar-persist.js";import{SessionBindingStore as Jn}from"../core/persistence/session-binding-store.js";import{serveLocalFile as Yn}from"../core/files/index.js";import{uploadReplyFileToAgentMedia as Vn}from"../core/protocol/agent-api-media.js";import{attachmentHostFromWsUrl as Xn,buildInboundAttachmentsJson as Zn,materializeInboundAttachments as ei}from"../core/protocol/inbound-attachments.js";import{ActiveEventStore as ti}from"../core/persistence/active-event-store.js";import{PendingEventCoordinator as ni}from"./pending-event-coordinator.js";import{LifecycleBarrier as ii}from"./lifecycle-barrier.js";import{QUEUE_COMPOSING_TTL_MS as si}from"./event-queue.js";import{DEFAULT_CONNECTOR_RUNTIME_CONFIG as oi,applyConnectorRuntimeConfigPatch as ri,extractConnectorRuntimeConfigPatch as ai}from"./runtime-config.js";import{DEFAULT_QUOTE_TRIGGER_BY_ADAPTER as di,SendController as li}from"./send-controller.js";import{providerQuotaToRateLimits as ci,providerQuotaToCodexRateLimits as hi}from"../core/provider-quota/index.js";import{buildToolUseCard as C,buildToolResultCard as b,buildDshOnlineToolCard as ui,buildLocalGrixCardLink as x}from"./tool-card-utils.js";import{planRawEventDelivery as pi,buildAuxiliaryDetailText as gi}from"./raw-event-delivery.js";import{DeferredEventManager as fi}from"./deferred-events.js";import{buildAgentProbeResult as mi,PROBE_CACHE_TTL_STATIC_MS as vi,PROBE_CACHE_TTL_FULL_MS as _i}from"./probe-helper.js";import{BridgeAuditController as Si}from"../audit/integration/bridge-audit-controller.js";import{isSettlableAuditProducer as Ci,NoopAuditProducer as bi}from"../audit/producer/audit-producer.js";import{buildAuditStatePayload as I,AuditPreparationFailedError as Ai,AuditTurnScopeUnsupportedError as Ei}from"../audit/core/audit-state.js";import{extractAuditOptions as B,freezeAuditOptions as wi,stripAuditOptions as yi}from"../audit/core/audit-options.js";import{AuditSessionOptionsError as Ri}from"../audit/core/audit-session-registry.js";import{waitForIdle as ki,formatWaitDuration as Ti}from"../core/upgrade/idle-wait.js";const Pi=600*1e3,xi=1800*1e3,Li=5*6e4,Mi=60*1e3,$i=4e3;function Hi(L,e,t){const r=M("sha256").update(L).update("\0").update(e).update("\0").update(t).digest("hex");return k.join(y.data,"audit-source","reasonix",`${r}.jsonl`)}const Di=new Set(["claude","codex","cursor","codewhale","opencode","pi","openhuman","agy","acp","deepseek-harness"]),R=3;class yo{config;name;aibotHandle;aibotConfig;pool;stopped=!1;startupAbortController=new AbortController;stopPromise=null;dropPendingEventsRequested=!1;pendingEventsDropped=!1;revokeHandler=new vn;sessionBindings=new Map;customToolbars=new Map;deferredMgr;sendCtrl=new li(oi);bindingStore;globalConfigStore;upgradeTrigger=null;daemonShutdownRequester=null;lifecycleBusyChecker=null;lifecycleAdmissionCloser=null;lifecycleAdmissionRestorer=null;installAgentHandler=null;remoteAdminPorts=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 ii;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;rejectedOutputEvents=new Set;blockedDispatchEvents=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<=Mi}isGrixRelayActive(){const e=this.relayStateApplyPorts?.getAppliedMode?.();return e==="direct"||e==="mitm"}resolveProviderQuotaSource(e){return nn(this,e)}maybeQueryProviderQuota(e=!1,t){return sn(this,e,t)}startProviderQuotaTimer(){on(this)}stopProviderQuotaTimer(){rn(this)}refreshAndPushProviderQuota(e=!1){return an(this,e)}pushProviderQuotaToBindings(e,t=!1){dn(this,e,t)}enrichProviderQuotaMeta(e,t="standard",r=this.cachedProviderQuota,n=this.cachedProviderQuotaSampledAtMs){return ln(this,e,t,r,n)}providerQuotaMetaPayload(e,t,r){return cn(this,e,t,r)}refreshProviderQuotaForSession(e,t,r){return hn(this,e,t,r)}refreshQuotaAfterModelSwitch(e,t,r){un(this,e,t,r)}doRefreshQuotaAfterModelSwitch(e,t,r){return pn(this,e,t,r)}getFreshClaudeRateLimitState(){const e=this.cachedClaudeRateLimitState;return e&&this.isRateLimitsCacheFresh(e.sampledAt)?e:null}getFreshCodexGlobalRateLimitCache(){const e=this.cachedRateLimits,t=this.cachedCodexContextWindow,r=this.cachedCodexTokenUsage;return{sampledAt:Math.max(this.cachedRateLimitsSampledAtMs??0,this.cachedCodexUsageSampledAtMs??0)||null,rateLimits:e,contextWindow:t,tokenUsage:r,hasData:!!(e||t||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(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)}describePendingOrBackgroundWork(){const e=this.lifecycleBarrier.describeActiveAdmissions().map(({label:r,heldMs:n})=>({source:"admission",agent:this.name,label:r,...n>Li?{suspect:`admission held for ${Ti(n)}`}:{}})),t=(this.pool?.describePendingOrBackgroundWork()??[]).map(r=>({...r,agent:this.name}));return[...e,...t]}async waitUntilLifecycleIdle(e){return ki({describeBusy:()=>this.lifecycleBusyChecker?.()??this.describePendingOrBackgroundWork(),isStopped:()=>this.stopped,closeAdmission:()=>this.closeLifecycleAdmissionForRestart(),reopenAdmission:()=>this.reopenLifecycleAdmissionAfterAbort(),budgetMs:xi,log:(t,r)=>{t==="warn"?h.warn(this.name,`${e}: ${r}`):h.info(this.name,`${e}: ${r}`)}})}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 t=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 o=!1;await this.pool.removeSlot(n.sessionId).catch(s=>{r=!0,o=!0,h.warn(this.name,`failed to recycle adapter slot ${n.sessionId} after relay change: ${s}`)}),o||(t+=1)}return t>0&&h.info(this.name,`recycled ${t} 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 t=e.conversation?"full":"static",r=e.conversation?_i:vi;if(!e.fresh){const a=this.probeCache.get(t);if(a&&Date.now()-a.sampledAt<r)return{...a.result,cached:!0}}const n=this.config.adapterType??"acp",o=this.createAdapter(n,"__probe__"),s=e.conversation&&n==="acp"?()=>this.runAcpConversationProbe(o,e.timeoutMs??1e4):void 0;let i;try{i=await mi({adapter:o,agentName:this.name,clientType:this.config.aibot.clientType,adapterType:n,providerBaseUrl:this.config.providerBaseUrl??null,opts:e,launchConversationProbe:s})}finally{o.stop().catch(()=>{})}return this.probeCache.set(t,{result:i,sampledAt:i.probed_at}),i}async runAcpConversationProbe(e,t){const r=Date.now(),n="__probe__",o=`probe-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s=this.config.agent.cwd||F(),i=()=>Date.now()-r;try{await e.start()}catch(u){return{attempted:!0,ok:!1,latency_ms:i(),error:{code:"conversation_failed",message:`start failed: ${u instanceof Error?u.message:String(u)}`}}}if(!e.isAlive())return{attempted:!0,ok:!1,latency_ms:i(),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=p=>{p===o&&u()},e.on("eventDone",a)});e.deliverInboundEvent({event_id:o,session_id:n,content:"ping",msg_id:o}),e.deliverStopEvent(o,n);let d=null;const c=await Promise.race([l.then(()=>!1),new Promise(u=>{d=setTimeout(()=>u(!0),t)})]);return d&&clearTimeout(d),a&&e.removeListener("eventDone",a),c?{attempted:!0,ok:!1,latency_ms:i(),error:{code:"conversation_timeout",message:`no eventDone within ${t}ms`}}:{attempted:!0,ok:!0,latency_ms:i()}}constructor(e,t,r=new bi){this.config=e,this.auditController=new Si(r,{onAuditState:o=>{try{this.aibotHandle.sendAuditState(I(o,Date.now()))}catch{}}}),Ci(r)&&r.addJobSettledHandler((o,s)=>{this.auditController.handleJobSettled(o,s)}),this.name=e.name;const n=e.adapterType??"acp";if(this.sendCtrl.setDefaultQuoteTrigger(di[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",...q]}:{}},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 Te(e.logDir):null,this.packetLog=e.logDir?new Pe(e.logDir):null,this.bindingStore=new Jn(e.bindingsPath,e.legacyBindingsPath),this.bindingStore.load(),this.globalConfigStore=t??null,this.deferredMgr=new fi(this.name),this.activeEventStore=e.activeEventStorePath?new ti(e.activeEventStorePath):null,this.pendingEvents=new ni(e.pendingEventStorePath),n==="codex")this.sessionScanCache=new v(de,Se);else if(n==="claude")this.sessionScanCache=new v(le,Ce);else if(n==="pi"){const o=e.agent.env?.PI_CODING_AGENT_DIR;this.sessionScanCache=new v(()=>pe(void 0,o),()=>Ae(void 0,o))}else if(n==="codewhale")this.sessionScanCache=new v(ge,Ee);else if(n==="cursor")this.sessionScanCache=new v(fe,we);else if(n==="opencode"){const o=ve(e.agent.command||"opencode")||"opencode";this.sessionScanCache=new v(()=>me(void 0,o),()=>ye(void 0,o))}else if(n==="deepseek-harness"){const o=typeof e.adapterOptions?.dshHome=="string"?e.adapterOptions.dshHome:e.agent.env?.DSH_HOME;this.sessionScanCache=new v(()=>_e(o),()=>Re(o))}else if(n==="agy")this.sessionScanCache=new v(()=>[],()=>[]);else{e.aibot.clientType?.trim().toLowerCase()==="reasonix"&&(this.reasonixTitleScan=new v(ue,ke));const o=ce(e.aibot.clientType);this.sessionScanCache=o?new v(()=>he(void 0,o),()=>be(void 0,o)):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(([,s])=>String(s.cwd??""))}).then(s=>{s.length>0&&h.info(this.name,`restored native provider config after relay disable: ${s.join(", ")}`)}).catch(s=>{h.warn(this.name,`native provider residue sweep failed: ${s instanceof Error?s.message:String(s)}`)}),this.stopped)throw new Error("agent start aborted");if((this.config.adapterType??"acp")==="claude"){if(await X().catch(()=>{}),this.stopped)throw new Error("agent start aborted");this.maybeQueryProviderQuota().catch(()=>{})}else(this.config.adapterType??"acp")==="agy"&&Z(this.config.agent.command).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",r=(this.config.adapterType??"acp")==="opencode",n=(this.config.adapterType??"acp")==="claude"&&this.isGrixRelayActive();if(this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi"||e||n?(this.maybeQueryProviderQuota().catch(()=>{}),this.startProviderQuotaTimer()):(t||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 o=this.config.adapterType??"acp";if(this.pool=new _n({maxPoolSize:this.config.poolMaxSize??20,idleTimeoutMs:this.config.poolIdleTimeoutMs??18e5,eventQueue:this.config.eventQueue},s=>{const i=this.createAdapter(o,s);return i instanceof S&&i.on("acpSessionReady",a=>{this.bindingStore.setAcpSessionId(s,a),this.sessionScanCache.invalidate()}),i},(s,i)=>{this.aibotHandle.sendEventAck({event_id:s,session_id:i,received_at:Date.now()})}),this.pool.setEventStateHandler((s,i,a,l)=>{if(h.info(this.name,`[queue-debug] send event_state session=${i} event=${s} state=${a} queue_pos=${l?.queue_position??""} queue_total=${l?.queue_total??""}`),this.aibotHandle.sendEventState({event_id:s,session_id:i,state:a,content_preview:l?.content_preview,content:l?.content,queue_position:l?.queue_position,queue_total:l?.queue_total,actions:l?.actions,reason:l?.reason,held:l?.held,held_reason:l?.held_reason,updated_at:Date.now()}),this.pushQueueSnapshotForSession(i),a==="running"&&(this.pendingStartedEventIds.add(s),this.pendingEvents.remove(s).catch(d=>{h.warn(this.name,`Failed to remove running event from pending store event=${s}: ${d instanceof Error?d.message:String(d)}`)})),a==="canceled"||a==="failed"){const d=a==="canceled"?"canceled":"failed";this.aibotHandle.sendEventResult({event_id:s,status:d,msg:l?.reason,updated_at:Date.now()}),this.auditController.closeWithoutAdapter(s,d,l?.reason,{queueTerminalState:a}),this.discardEventTrackingState(s),this.pendingEvents.remove(s).catch(c=>{h.warn(this.name,`Failed to remove queued terminal event from pending store event=${s}: ${c instanceof Error?c.message:String(c)}`)})}}),this.pool.setQueueComposingHandler((s,i,a)=>{this.aibotHandle.sendSessionActivitySet({session_id:s,kind:"composing",active:i,...i?{ttl_ms:si,ref_event_id:a}:{}})}),this.pool.setInternalErrorHandler(s=>{this.handleSessionInternalError(s).catch(i=>{h.error(this.name,`[recovery] handleSessionInternalError failed event=${s.eventId} session=${s.sessionId}: ${i instanceof Error?i.message:String(i)}`)})}),this.pool.setEventStartedHandler((s,i)=>{if(this.reportSessionSkills(i),this.config.adapterType!=="claude")return;this.claudeWorkerStatus.set(i,"busy");const a=this.bindingStore.get(i);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:"busy",cwd:a.cwd,meta:this.buildClaudeToolbarMeta(i)})}),this.pool.setEventDoneHandler((s,i)=>{this.markAuditAdapterClosed(s,i);const a=this.config.adapterType??"acp";if(a==="claude"){this.claudeWorkerStatus.set(i,"ready");const l=this.bindingStore.get(i);l?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:"ready",cwd:l.cwd,meta:this.buildClaudeToolbarMeta(i)})}else if(a==="agy"){const l=this.bindingStore.get(i);if(l?.cwd){const d=this.buildAgyToolbarMeta(i),c=d?.available_models??[];h.info(this.name,`[agy-toolbar-diag] eventDone push binding card session=${i} model_id=${String(d?.model_id??"")} available_models=${c.length} meta_keys=${d?Object.keys(d).join(","):"<none>"}`),this.sendAgyBindingCard(i,l.cwd,d),this.refreshAndPushAgyQuota(i)}else h.info(this.name,`[agy-toolbar-diag] eventDone skip binding card: no binding cwd session=${i}`)}}),this.pool.setSessionActivityHandler((s,i,a)=>{const l=this.selfDrivenSessions.has(s),d=this.selfDrivenLabels.get(s);i?(this.selfDrivenSessions.add(s),a&&this.selfDrivenLabels.set(s,a),this.aibotHandle.sendSessionActivitySet({session_id:s,kind:"composing",active:!0,ttl_ms:9e4})):(this.selfDrivenSessions.delete(s),this.selfDrivenLabels.delete(s),l&&this.aibotHandle.sendSessionActivitySet({session_id:s,kind:"composing",active:!1})),(l!==i||i&&a!==void 0&&a!==d)&&this.pushQueueSnapshotForSession(s)}),await this.replayPendingEventsOnStartup(),this.stopped)throw new Error("agent start aborted");this.pool.startIdleSweep(),h.info(this.name,`Ready (adapter: ${o}, 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(i=>[i,this.eventSessionIndex.get(i)]));e.length>0&&this.activeEventStore&&await this.activeEventStore.save(e);for(const i of e)h.info(this.name,`Canceling active event on shutdown: ${i}`),this.sendEventResultWithCleanup(i,"canceled","process shutting down");e.length>0&&await new Promise(i=>setTimeout(i,100)),this.pool?.clearActiveEventsForShutdown();for(const i of e){const a=t.get(i),l=a?this.pool?.getSlot(a):void 0;this.auditController.markAdapterClosed(i,l?.adapter.takeAuditBoundary?.(i)??{processTerminated:!0})}const r=this.deferredMgr.getAllDeferredEntries(),n=this.pool?.drainAllQueuedEvents()??[],o=this.pendingEvents.dedupe([...this.pendingEvents.replaySnapshot(),...r.map(i=>({kind:"deferred",channel:i.channel,sessionId:i.sessionId,event:i.event})),...n.map(i=>({kind:"queued",event:i}))]);let s=!1;if(this.dropPendingEventsRequested)try{await this.pendingEvents.clear(),this.pendingEventsDropped=!0}catch(i){h.warn(this.name,`Failed to clear pending event store on removal: ${i instanceof Error?i.message:String(i)}`)}else try{s=await this.pendingEvents.mergeForShutdown(o)}catch(i){h.error(this.name,`Failed to persist pending events on shutdown: ${i instanceof Error?i.message:String(i)}`)}if(!s)for(const i of o){const a=i.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,t=se(this.config.agent.clientType,e),r=this.config.agent.env;let n=Object.keys(t).length>0?{...t,...r}:r;if(oe(t)){const o=te()?.getRuntimeInfo(),s={...r??{},...t},i=re(s,{proxyUrl:o?.proxyUrl,caCertPath:o?.caCertPath,caBundlePath:o?.caBundlePath});return delete i.ANTHROPIC_API_KEY,delete i.CLAUDE_CODE_OAUTH_TOKEN,i}if(ie(this.config.agent.clientType)){const o=ne(this.name);o&&(n={...n??{},...o})}return ee(n,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:(o,s,i,a,l,d,c)=>{this.sendStreamChunkByRuntimeConfig(o,s,i,a,l,d,c)},sendFinalStreamChunkReliable:this.reliableFinalWiring("deepseek-harness",$i),sendThinking:(o,s,i)=>this.sendThinkingByRuntimeConfig(o,s,i),sendEventResult:(o,s,i,a)=>{this.sendEventResultWithCleanup(o,s,i,void 0,a)},sendRawEventEnvelope:(o,s,i,a)=>{const l=ui(i);if(l){this.sendToolExecutionCard(o,s,l);return}this.deliverRawEventEnvelope(o,s,i,"deepseek",a)},sendLocalActionResult:(o,s,i,a,l)=>{this.aibotHandle.sendLocalActionResult({action_id:o,status:s,...i!==void 0?{result:i}:{},...a?{error_code:a}:{},...l?{error_msg:l}:{}},e)},sendPermissionCard:o=>{this.sendGrixApprovalCard(o,"deepseek")},sendUpdateBindingCard:(o,s,i,a)=>{this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:s,cwd:i,meta:a})},getAgentProfile:()=>({...this.agentProfile,systemPrompt:this.agentSystemPrompt}),getAgentId:()=>this.config.aibot.agentId,queryProviderQuota:o=>this.maybeQueryProviderQuota(o===!0,{providerId:"deepseek"}),agentInvoke:async(o,s,i)=>this.platformInvoke(o,s,i),eventToolInvoke:async(o,s)=>this.invokeDshEventTool(o,s)},r=M("sha256").update(this.config.aibot.agentId).digest("hex").slice(0,24),n=this.config.adapterOptions??{};return new K({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:n},t,{aibotSessionId:e,bindingStore:this.bindingStore,globalConfigStore:this.globalConfigStore,agentName:this.name,dataRoot:k.join(y.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 t={...this.config.adapterOptions??{}};t.bindingStore=this.bindingStore,t.aibotSessionId=e;const r=this.bindingStore.get(e),n=this.resolveSessionModelId(e);n&&(t.model=n);const o=this.resolveCursorSessionModeId(e),s=o??"full_auto";o||this.bindingStore.setCursorModeId(e,s),t.mode=s,r?.cwd&&(t.workspace=r.cwd);const i={sendStreamChunk:(a,l,d,c,u,p,g)=>{this.sendStreamChunkByRuntimeConfig(a,l,d,c,u,p,g)},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(p=>p.header).join(", "),u=x(`[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:t},i)}createClaudeAdapter(e){let t;const r=()=>{const i=this.pool.getSlot(e);return i?.adapter===t&&!i.stopping},n={onSessionHistoryUnavailable:(i,a)=>{if(!r())return;if(this.bindingStore.get(e)?.claudeSessionId!==i.nativeSessionId){a&&this.sendEventResultWithCleanup(a.event_id,"canceled","session binding changed"),this.pool.removeSlot(e).catch(()=>{});return}this.bindingStore.delete(e),this.sessionBindings.delete(e),this.sessionProviderHints.delete(e),this.sessionProviderQuotas.delete(e),this.sessionProviderMeta.delete(e),this.sessionScanCache.invalidate(),a&&this.sendEventResultWithCleanup(a.event_id,"failed",i.message,E.bindingMissing,!0),this.pool.removeSlot(e).catch(d=>{h.warn(this.name,`Failed to dispose obsolete Claude slot: ${d instanceof Error?d.message:String(d)}`)});const l=this.resolveBindingChannelKey("claude");this.aibotHandle.sendMsg({...a?{event_id:a.event_id,quoted_message_id:a.msg_id}:{},session_id:e,client_msg_id:`claude_history_unavailable_${e}_${i.nativeSessionId}`,msg_type:1,content:x(i.message,"agent_open_session",{summary_text:i.message,detail_text:"\u7ED1\u5B9A\u540E\u5C06\u5F00\u59CB\u65B0\u4F1A\u8BDD\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u521A\u624D\u7684\u8BF7\u6C42\u3002\u5E73\u53F0\u804A\u5929\u6D88\u606F\u4ECD\u4FDD\u7559\uFF0C\u65E7\u5DE5\u5177\u72B6\u6001\u4E0D\u4F1A\u6062\u590D\u3002"}),extra:{channel_data:{[l]:{sessionBinding:{status:"missing",reason:"binding_missing",error_code:E.bindingMissing}}}}})},sendReply:(i,a,l,d,c)=>{this.sendReplyByRuntimeConfig(i,a,l,d,c)},sendStreamChunk:(i,a,l,d,c,u,p)=>{this.sendStreamChunkByRuntimeConfig(i,a,l,d,c,u,p)},sendMedia:(i,a,l,d,c,u,p)=>{this.aibotHandle.sendMedia({event_id:i,session_id:a,content:l,msg_type:2,quoted_message_id:c||void 0,client_msg_id:u||void 0,extra:p?{media_caption:d,...p}:{media_caption:d}})},sendEventResult:(i,a,l,d,c)=>{this.sendEventResultWithCleanup(i,a,l,d,c)},sendEventAck:(i,a)=>{this.aibotHandle.sendEventAck({event_id:i,session_id:a,received_at:Date.now()})},agentInvoke:async(i,a,l)=>this.platformInvoke(i,a,l),sendLocalActionResult:(i,a,l,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:i,status:a,...l!==void 0?{result:l}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}},e)},sendToolUse:(i,a,l,d)=>{this.sendToolExecutionCard(i,a,C(l,d))},sendToolResult:(i,a,l,d)=>{this.sendToolExecutionCard(i,a,b(l,d))},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:(i,a,l)=>{this.sendGrixAgentQuestionCard(i,a,l)},sendPermissionCard:i=>{this.sendGrixApprovalCard(i,"claude")},sendDirectMessage:i=>{this.aibotHandle.sendMsg({session_id:i.sessionId,msg_type:1,content:i.content,...i.clientMsgId?{client_msg_id:i.clientMsgId}:{},...i.quotedMessageId?{quoted_message_id:i.quotedMessageId}:{}})},onStatusLineUpdated:i=>{if(!r())return;(i.rateLimits?.fiveHour||i.rateLimits?.sevenDay)&&(this.cachedClaudeRateLimitState=i);const a=this.bindingStore.get(e);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:this.claudeWorkerStatus.get(e)??"ready",cwd:a.cwd,meta:this.buildClaudeToolbarMeta(e)})},sendMcpFrame:i=>{this.aibotHandle.sendMcpFrame(e,i)}},o=this.config.adapterOptions??{},s={...o,sessionRuntimeResolver:()=>{if(!r())throw new Error("Claude adapter no longer owns session binding");const i=this.bindingStore.get(e),a=this.auditController.getSession(e);return{cwd:i?.cwd,modeId:this.resolveClaudeSessionModeId(e)??z.fullAuto,modelId:this.resolveSessionModelId(e),effort:this.resolveClaudeSessionEffort(e),pluginDir:o.pluginDir,claudeSessionId:i?.claudeSessionId,...a?{audit:{enabled:!0,profile:a.options.profile,capture:a.options.capture}}:{},onSessionIdAssigned:l=>{const d=this.bindingStore.get(e);!r()||!d?.cwd||d.cwd!==i?.cwd||d.claudeSessionId!==i?.claudeSessionId||(this.bindingStore.setClaudeSessionId(e,l),this.sessionScanCache.invalidate())}}}};return t=new $({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:s},n),t}createCodexAdapter(e){let t=null;const r={sendEventResult:(i,a,l)=>{if(a!=="responded"){this.sendEventResultWithCleanup(i,a,l);return}this.sendCtrl.sendFinalStreamChunkReliable(i,e,`codex_terminal_fence_${i}`,5e3,!0,!0).then(()=>this.sendEventResultWithCleanup(i,a,l),d=>{const c=`codex output acceptance fence failed: ${d instanceof Error?d.message:String(d)}`;this.sendEventResultWithCleanup(i,a==="responded"?"failed":a,a==="responded"?c:l)})},sendEventAck:(i,a)=>this.aibotHandle.sendEventAck({event_id:i,session_id:a,received_at:Date.now()}),sendCodexEvent:i=>{this.shouldDropCodexDisplayEvent(i.event_id,i.codex_method)||(this.captureCodexAuditOutput(i),this.aibotHandle.sendCodexEvent(this.stampCodexEventQuote(i)),this.logCodexEventToConversation(i))},sendThinking:(i,a,l)=>{this.sendThinkingByRuntimeConfig(i,a,l)},sendRunError:(i,a,l)=>{this.sendRunErrorAsChunk(i,a,l)},sendUpdateBindingCard:(i,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:i,worker_status:a,cwd:l,...Object.keys(c).length>0?{meta:c}:{}})},agentInvoke:async(i,a,l)=>this.platformInvoke(i,a,l),sendLocalActionResult:(i,a,l,d,c)=>this.aibotHandle.sendLocalActionResult({action_id:i,status:a,...l!==void 0?{result:l}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}},e),sendSessionActivitySet:(i,a,l,d)=>{this.aibotHandle.sendSessionActivitySet({session_id:i,kind:a,active:l,...d??{}})},getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId,onRateLimitsUpdated:i=>{this.cachedRateLimits=i,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:{...i.primary.windowMinutes>0?{primary:i.primary}:{},...i.secondary.windowMinutes>0?{secondary:i.secondary}:{},sampledAt:l},rate_limit_primary_percent:i.primary.usedPercent,rate_limit_secondary_percent:i.secondary.usedPercent,rate_limit_primary_window_min:i.primary.windowMinutes,rate_limit_secondary_window_min:i.secondary.windowMinutes,credits:i.credits,...i.extras&&i.extras.length>0?{extra_limits:i.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:i=>{if(!i)return;this.cachedCodexContextWindow=i,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:i,...t?.getEffortMeta()}})},onTokenUsageUpdated:i=>{i&&(this.cachedCodexTokenUsage=i,this.cachedCodexUsageSampledAtMs=Date.now())}},n=this.config.adapterOptions??{},o=this.auditController.getAdapterPreparation(e),s=i=>Ft(this,"codex",e,i);return t=new H({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...n,model:s("model")??n.model,collaborationMode:s("mode")??n.collaborationMode,reasoningEffort:s("reasoningEffort")??n.reasoningEffort,serviceTier:s("serviceTier")??n.serviceTier,sandboxMode:s("sandboxMode")??n.sandboxMode,aibotSessionId:e,bindingStore:this.bindingStore,...Q(o?.options)?{rawApiCapture:{auditId:o.auditId,sessionId:e,spoolRootDir:k.join(y.data,"audit-replay","raw-spool")}}:{}}},r),t}createCodeWhaleAdapter(e){const t={sendEventResult:(n,o,s)=>{this.sendEventResultWithCleanup(n,o,s)},sendEventAck:(n,o)=>this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()}),sendStreamChunk:(n,o,s,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,s,i,a,l)},sendUpdateBindingCard:(n,o,s,i)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:o,cwd:s,...this.providerQuotaMetaPayload(i,n,s)}),sendLocalActionResult:(n,o,s,i,a)=>this.aibotHandle.sendLocalActionResult({action_id:n,status:o,...s!==void 0?{result:s}:{},...i?{error_code:i}:{},...a?{error_msg:a}:{}},e),sendSessionActivitySet:(n,o,s,i)=>{this.aibotHandle.sendSessionActivitySet({session_id:n,kind:o,active:s,...i??{}})},sendToolUse:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,C(s,i))},sendToolResult:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,b(s,i))},agentInvoke:async(n,o,s)=>this.platformInvoke(n,o,s),getConversationLog:()=>this.conversationLog,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,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,model:this.resolveSessionModelId(e)??r.model,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},t)}createPiAdapter(e){const t={sendEventResult:(n,o,s,i,a)=>{this.sendEventResultWithCleanup(n,o,s,i,a),h.info("bridge",`[pi] sendEventResult event=${n} status=${o}`)},sendEventAck:(n,o)=>this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()}),sendUpdateBindingCard:(n,o,s,i)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:o,cwd:s,...this.providerQuotaMetaPayload(i,n,s)}),agentInvoke:async(n,o,s)=>this.platformInvoke(n,o,s),sendLocalActionResult:(n,o,s,i,a)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:o,...s!==void 0?{result:s}:{},...i?{error_code:i}:{},...a?{error_msg:a}:{}},e)},sendSessionActivitySet:(n,o,s,i)=>{this.aibotHandle.sendSessionActivitySet({session_id:n,kind:o,active:s,...i??{}})},sendToolUse:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,C(s,i))},sendToolResult:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,b(s,i))},sendStreamChunk:(n,o,s,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,s,i,a,l),a&&h.info("bridge",`[pi] sendFinalStreamChunk event=${n} seq=${i}`)},sendFinalStreamChunkReliable:this.reliableFinalWiring("pi"),sendThinking:(n,o,s)=>{this.sendThinkingByRuntimeConfig(n,o,s)},sendRunError:(n,o,s,i,a)=>{this.sendRunErrorAsChunk(n,o,s,i,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,clientType:this.config.agent.clientType,globalConfigStore:this.globalConfigStore,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},t)}createOpenHumanAdapter(e){const t={sendStreamChunk:(n,o,s,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,s,i,a,l)},sendFinalStreamChunkReliable:async(n,o,s,i)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(n,o,i)}catch(a){throw h.error("bridge",`[openhuman] sendFinalStreamChunkReliable ACK failed event=${n}: ${a}`),a}},sendEventResult:(n,o,s)=>{this.sendEventResultWithCleanup(n,o,s),h.info("bridge",`[openhuman] sendEventResult event=${n} status=${o}`)},sendEventAck:(n,o)=>this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()}),sendToolUse:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,C(s,i))},sendToolResult:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,b(s,i))},sendThinking:(n,o,s)=>{this.sendThinkingByRuntimeConfig(n,o,s)},sendRunError:(n,o,s)=>{this.sendRunErrorAsChunk(n,o,s,0)},sendUpdateBindingCard:(n,o,s,i)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:o,cwd:s,...this.providerQuotaMetaPayload(i,n,s)}),agentInvoke:async(n,o,s)=>this.platformInvoke(n,o,s),sendLocalActionResult:(n,o,s,i,a)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:o,...s!==void 0?{result:s}:{},...i?{error_code:i}:{},...a?{error_msg:a}:{}},e)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=this.config.adapterOptions??{};return new N({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:r},t,{port:r.port,host:r.host,workspaceDir:r.workspace_dir,sessionToken:r.session_token,enableSessionBinding:!0,aibotSessionId:e})}createOpenCodeAdapter(e){const t={sendStreamChunk:(n,o,s,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,s,i,a,l)},sendFinalStreamChunkReliable:this.reliableFinalWiring("opencode"),sendEventResult:(n,o,s,i,a)=>{this.sendEventResultWithCleanup(n,o,s,i,a),h.info("bridge",`[opencode] sendEventResult event=${n} status=${o}`)},sendEventAck:(n,o)=>this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()}),sendToolUse:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,C(s,i))},sendToolResult:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,b(s,i))},sendThinking:(n,o,s)=>{this.sendThinkingByRuntimeConfig(n,o,s)},sendRunError:(n,o,s)=>{this.sendRunErrorAsChunk(n,o,s)},sendUpdateBindingCard:(n,o,s,i)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:o,cwd:s,...this.providerQuotaMetaPayload(i,n,s)}),agentInvoke:async(n,o,s)=>this.platformInvoke(n,o,s),sendLocalActionResult:(n,o,s,i,a)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:o,...s!==void 0?{result:s}:{},...i?{error_code:i}:{},...a?{error_msg:a}:{}},e)},sendPermissionCard:n=>{this.sendGrixApprovalCard(n,"opencode")},sendAgentQuestionCard:(n,o,s)=>{this.sendGrixAgentQuestionCard(n,o,s)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=this.config.adapterOptions??{};return new P({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:r},t,{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 t={sendStreamChunk:(n,o,s,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,s,i,a,l)},sendEventResult:(n,o,s)=>{this.sendEventResultWithCleanup(n,o,s)},sendEventAck:(n,o)=>{this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()})},agentInvoke:async(n,o,s)=>this.platformInvoke(n,o,s),forceCompleteInternalEvent:(n,o)=>{this.pool.eventComplete(n,o),this.pushQueueSnapshotForSession(o)},persistConversationId:(n,o)=>{this.bindingStore.setAgyConversationId(n,o)},sendToolUse:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,C(s,i))},sendToolResult:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,b(s,i))},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=n=>{const o=this.bindingStore.get(n);return{cwd:o?.cwd,modelId:this.resolveSessionModelId(n),conversationId:o?.agyConversationId}};return new D({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:this.config.adapterOptions??{}},t,r)}createAcpAdapter(e){const t=this.isAcpRawTransportEnabled(),r={sendStreamChunk:(d,c,u,p,g,_,A)=>{this.sendStreamChunkByRuntimeConfig(d,c,u,p,g,_,A)},sendFinalStreamChunkReliable:this.reliableFinalWiring("acp",4e3),sendEventResult:(d,c,u,p,g)=>{this.sendEventResultWithCleanup(d,c,u,p,g)},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,p,g)=>{this.aibotHandle.sendLocalActionResult({action_id:d,status:c,...u!==void 0?{result:u}:{},...p?{error_code:p}:{},...g?{error_msg:g}:{}},e)},sendRawEventEnvelope:(d,c,u)=>{this.sendAcpRawEventEnvelope(d,c,u)},sendToolUse:(d,c,u,p)=>{if(t){this.sendAcpRawEventEnvelope(d,c,{type:"tool_use",payload:{tool_name:u,tool_input:p??""}});return}this.sendToolExecutionCard(d,c,C(u,p))},sendToolResult:(d,c,u,p)=>{this.sendToolExecutionCard(d,c,b(u,p))},sendThinking:(d,c,u)=>{this.sendThinkingByRuntimeConfig(d,c,u)},sendRunError:(d,c,u)=>{this.sendRunErrorAsChunk(d,c,u)},sendAgentQuestionCard:(d,c,u)=>{this.sendGrixAgentQuestionCard(d,c,u)},sendPermissionCard:d=>{h.info("bridge","sendPermissionCard callback entered",{rawTransport:t,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(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}}),h.info("bridge","sendPermissionCard: sent via rawEventEnvelope",{eventId:d.eventId,toolCallId:d.toolCallId});return}const u=`perm_${T()}`,p={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:p.content.length});try{this.aibotHandle.sendMsg(p),h.info("bridge","sendPermissionCard: aibotHandle.sendMsg returned",{eventId:d.eventId,clientMsgId:u})}catch(g){h.error("bridge","sendPermissionCard: aibotHandle.sendMsg threw",{eventId:d.eventId,clientMsgId:u,error:g instanceof Error?g.message:String(g)})}},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,p)=>{const g={...p??{}};if(!g.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const _=this.providerQuotaToRateLimits(this.cachedProviderQuota);_&&(g.rate_limits=_)}!g.provider_quota&&this.cachedProviderQuota?.success&&(g.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:d,worker_status:c,cwd:u,...Object.keys(g).length>0?{meta:g}:{}})},onSkillsUpdate:(d,c)=>{try{this.aibotHandle.sendSkillsUpdate({skills:Y(d,y.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 p="usedPercentage"in d?d.usedPercentage:Math.min(100,d.used/d.size*100),g={context_window:{..."usedPercentage"in d?{}:d,usedPercentage:p,remainingPercentage:100-p}};if((this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi")&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{}),g.provider_quota=this.cachedProviderQuota;const _=this.providerQuotaToRateLimits(this.cachedProviderQuota);_&&(g.rate_limits=_)}this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:u.cwd,meta:g})}},sendMcpFrame:d=>{this.aibotHandle.sendMcpFrame(e,d)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},n=e?this.bindingStore.get(e):void 0,o=e?this.auditController.getSession(e):void 0,s=this.config.aibot.clientType==="reasonix"&&o?Hi(this.name,e,o.auditId):void 0,i=this.globalConfigStore?.get(this.name),{initialModel:a,initialMode:l}=zn({sessionBinding:n,globalDefaults:i,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: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 xe(this.config.logDir,`${this.name}-${e}`):null,reasonixAuditTranscriptPath:s,agentType:this.config.aibot.clientType,newSessionParams:this.config.adapterOptions?.newSessionParams&&typeof this.config.adapterOptions.newSessionParams=="object"&&!Array.isArray(this.config.adapterOptions.newSessionParams)?this.config.adapterOptions.newSessionParams:void 0})}async connectAibot(){const t=await new U().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 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(o=>{h.error(this.name,`handleAibotEvent failed: ${o}`),this.aibotHandle.sendEventAck({event_id:n.event_id,session_id:n.session_id,received_at:Date.now()});const s=o instanceof Error?o.message:String(o);this.handleStaleCwdError(n,s)||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(o){h.error(this.name,`handleAibotStop failed: ${o}`)}}),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(o){h.error(this.name,`agentDeletedHandler failed: ${o}`)}}),this.aibotHandle.onShareSet(n=>{try{this.shareSetHandler?.(Array.isArray(n?.shared_to)?n.shared_to:[])}catch(o){h.error(this.name,`onShareSet failed: ${o}`)}}),this.aibotHandle.onProfilePush(n=>{try{this.applyAgentProfile(n?.agent_name,n?.introduction,{source:"profile_push",respawnOnChange:!0},n?.system_prompt)}catch(o){h.error(this.name,`onProfilePush failed: ${o}`)}}),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(o){h.error(this.name,`onSkillSync failed: ${o}`)}}),this.aibotHandle.onRevoke(n=>{this.handleAibotRevoke(n).catch(o=>{h.error(this.name,`handleAibotRevoke failed: ${o}`)})}),this.aibotHandle.onLocalAction(n=>{this.handleAibotLocalAction(n).catch(o=>{h.error(this.name,`handleAibotLocalAction failed: ${o}`)})}),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(o=>{h.error(this.name,`handleEventCancel failed: ${o}`)})}),this.aibotHandle.onMcpFrame((n,o)=>{const s=this.pool.getSlot(n)?.adapter;s?.deliverMcpFrameToAgent?s.deliverMcpFrameToAgent(o):h.warn(this.name,`mcp_frame: no adapter for session=${n}`)}),this.aibotHandle.onQueueClear(n=>{const o=this.pool.clearQueue(n.session_id);this.aibotHandle.sendQueueClearResult({session_id:n.session_id,canceled_event_ids:o}),this.pushQueueSnapshotForSession(n.session_id)}),typeof this.aibotHandle.onQueueReorder=="function"&&this.aibotHandle.onQueueReorder(n=>{const o=Array.isArray(n.ordered_event_ids)?n.ordered_event_ids.filter(i=>typeof i=="string"&&i.length>0):[],s=this.pool.reorderQueue(n.session_id,o);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 o=typeof n.session_id=="string"?n.session_id:"",s=typeof n.event_id=="string"?n.event_id:"",i=n.hold!==!1;if(h.info(this.name,`recv event_hold event_id=${s} session_id=${o} hold=${i} reason=${n.reason??""}`),!o||!s){this.aibotHandle.sendEventHoldResult({session_id:o,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(o,s,i,a,l),c=d==="ok";this.aibotHandle.sendEventHoldResult({session_id:o,event_id:s,ok:c,held:c?i:!1,...c?{}:{error:d}}),c&&this.pushQueueSnapshotForSession(o)}),typeof this.aibotHandle.onQueueEdit=="function"&&this.aibotHandle.onQueueEdit(n=>{const o=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=${o}`),!o||!s){this.aibotHandle.sendQueueEditResult({session_id:o,event_id:s,ok:!1,error:"bad_request"});return}const i=typeof n.content=="string"?n.content:"",a=this.pool.editQueuedEvent(o,s,i),l=a==="ok";this.aibotHandle.sendQueueEditResult({session_id:o,event_id:s,ok:l,...l?{}:{error:a}}),l&&this.pushQueueSnapshotForSession(o)}),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 o of n)h.info(this.name,`Failing stale event on startup: ${o}`),this.aibotHandle.sendEventResult({event_id:o,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,o)=>{this.handleStreamRejected(n,o)})}handleStreamRejected(e,t){if(!e||this.rejectedOutputEvents.has(e))return;this.rejectedOutputEvents.add(e),this.rejectedOutputEvents.size>1e3&&this.rejectedOutputEvents.delete(this.rejectedOutputEvents.values().next().value);const r=this.pool?.getEventSessionId(e)??this.eventSessionIndex.get(e),n=`required agent output rejected (code=${t})`;this.sendCtrl.markEventRejected(e),this.sendCtrl.sendEventResult(e,"failed",n,t===0?"agent_output_integrity_failed":"agent_output_rejected"),this.auditController.markResponded(e,"failed",n),this.deferredMgr.removeEvent(e),this.discardEventTrackingState(e),this.blockedDispatchEvents.delete(e),this.surfacedRunErrorTexts.delete(e),this.pendingEvents.remove(e).catch(o=>{h.warn(this.name,`Rejected event pending cleanup failed event=${e}: ${o}`)});try{this.pool?.rejectEventOutput(e,r)}catch(o){h.warn(this.name,`Rejected event cancellation failed event=${e}: ${o}`)}finally{this.pool?.cleanupEvent(e,r),r&&this.pushQueueSnapshotForSession(r)}}applyAgentProfile(e,t,r,n){const o=String(e??"").trim(),s=String(t??"").trim(),i=n===void 0?this.agentSystemPrompt:String(n),a=o!==this.agentProfile.agentName||s!==this.agentProfile.introduction||i!==this.agentSystemPrompt;this.agentProfile={agentName:o,introduction:s},this.agentSystemPrompt=i,o||s?h.info(this.name,`agent profile (${r.source}): GOT name="${o}" intro_len=${s.length} system_prompt_len=${i.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 t=this.pool.getAllSlots();let r=0;for(const i of t)if(i.adapter.onAgentProfileChanged)try{i.adapter.onAgentProfileChanged(),r++}catch(a){h.warn(this.name,`onAgentProfileChanged failed for session=${i.sessionId}: ${a}`)}const n=t.filter(i=>i.adapter instanceof $),o=n.filter(i=>{if(i.state!=="ready")return!1;const a=i.adapter.getStatus();return!a.busy&&!a.backgroundBusy}),s=n.length-o.length;h.info(this.name,`${e}: notified ${r} adapter(s) via hook; respawning ${o.length} idle Claude slot(s), skipping ${s} busy`);for(const i of o)this.pool.removeSlot(i.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 t=this.pool?.getQueueSnapshot(e)??null,r=t?[...t.running]:[],n=t?t.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"}]})):[],o=t?t.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}`,i=this.selfDrivenLabels.get(e)??"Background task in progress";r.push(s),n.push({event_id:s,content_preview:i,title:i,summary:i,actions:[]})}return{session_id:e,running:r,running_items:n,queued:o}}pushQueueSnapshotForSession(e){if(!this.config.eventQueue||!this.pool)return;const t=this.buildQueueSnapshotPayload(e);h.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,r){if(e==="file_link")return Yn(t);if(e==="file_upload")return this.uploadFileAndSendMedia(t);if(e==="toolbar_set")return this.setCustomToolbar(t);const n=e==="chat_state_update"&&typeof t.reason=="string"&&t.reason.startsWith("dispatch_blocked:")&&(t.state==="waiting_question"||t.state==="waiting_approval")?this.pool?.getSlot(String(t.session_id??""))?.adapter.getActiveEventIds()??[]:[];for(const o of n)this.rejectedOutputEvents.has(o)||this.blockedDispatchEvents.set(o,String(t.state));return this.aibotHandle.agentInvoke(e,t,r)}async setCustomToolbar(e){const t=String(this.config.agent.clientType??this.config.aibot.clientType??"").trim().toLowerCase();if(t!=="acp")throw new Error(`grix_toolbar_set is only supported for client_type "acp" (this agent is "${t||"unknown"}")`);const r=String(e.session_id??"").trim();if(!r)throw new Error("grix_toolbar_set requires a session_id");const n=yt(e.items);return this.customToolbars.set(r,n),this.aibotHandle.sendUpdateBindingCard({session_id:r,metadata_only:!0,meta:{custom_toolbar:n}}),h.info(this.name,`[toolbar] custom toolbar published session=${r} items=${n.length}`),{ok:!0,items:n.length}}invokeDshEventTool(e,t){const r=V(this.aibotHandle,e,t),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 t=String(e.file_path??"").trim(),r=String(e.session_id??"").trim(),n=String(e.caption??"").trim(),o=String(e.reply_to_message_id??"").trim();if(!t)throw new Error("file_path is required");if(!r)throw new Error("session_id is required");const s=await Vn({wsURL:this.config.aibot.url,apiKey:this.config.aibot.apiKey,sessionID:r,filePath:t}),i=await this.aibotHandle.sendMedia({session_id:r,msg_type:2,content:n||`[${s.attachment_type}]`,client_msg_id:`file_upload_${T()}`,...o?{quoted_message_id:o}:{},extra:s.extra});if(i.cmd!=="send_ack"){const l=i.payload??{},d=String(l.msg??i.cmd);throw new Error(`media message send failed: ${d}`)}const a=i.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,t,r,n,o){const s=this.indexEventSession(e,t)??t;this.auditController.captureReply(e,r),this.sendCtrl.sendReply(e,s,r,n,o),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,...i}=e;return i}const t=e;if(t.codex_method!=="item/agentMessage/delta")return e;const n=t.codex_payload?.params?.phase;if(typeof n=="string"&&n.trim()&&n.trim().toLowerCase()!=="final_answer")return e;const o=this.sendCtrl.getDefaultQuotedMessageId(e.event_id);return o?{...e,quoted_message_id:o}:e}captureCodexAuditOutput(e){if(e.codex_method!=="item/agentMessage/delta")return;const t=e.codex_payload?.params,r=typeof t?.phase=="string"?t.phase.trim().toLowerCase():"";if(r&&r!=="final_answer")return;const n=t?.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,t){return async(r,n,o,s)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(r,n,o,t,!1,!1,s)}catch(i){throw h.error("bridge",`[${e}] sendFinalStreamChunkReliable ACK failed event=${r}: ${i}`),i}h.info("bridge",`[${e}] sendFinalStreamChunkReliable done event=${r}`)}}sendStreamChunkByRuntimeConfig(e,t,r,n,o,s,i){const a=this.indexEventSession(e,t)??t;this.auditController.captureStreamChunk(e,n,r),this.sendCtrl.sendStreamChunk(e,a,r,n,o,s,i),(r||o)&&this.conversationLog?.logOutbound?.(a,e,o?"stream_chunk_finish":"stream_chunk",r)}surfacedRunErrorTexts=new Map;markRunErrorSurfaced(e,t){const r=t.trim();if(!r)return;const n=this.surfacedRunErrorTexts.get(e);n?n.add(r):this.surfacedRunErrorTexts.set(e,new Set([r]))}sendRunErrorAsChunk(e,t,r,n=1,o){this.surfacedRunErrorTexts.get(e)?.has(r.trim())||(this.markRunErrorSurfaced(e,r),this.sendStreamChunkByRuntimeConfig(e,t,`
1
+ import k from"node:path";import{tmpdir as F}from"node:os";import{createHash as M,randomUUID as T}from"node:crypto";import{ConnectionManager as U}from"../core/aibot/index.js";import{AUDIT_LOCAL_ACTION_TYPES as q}from"../core/aibot/types.js";import{ClaudeAdapter as $}from"../adapter/claude/index.js";import{CodexAdapter as H}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 N}from"../adapter/openhuman/index.js";import{CursorAdapter as j}from"../adapter/cursor/index.js";import{CodeWhaleAdapter as G}from"../adapter/codewhale/index.js";import{OpenCodeAdapter as P}from"../adapter/opencode/index.js";import{AgyAdapter as D}from"../adapter/agy/index.js";import{DshJsonRpcAdapter as K}from"../adapter/deepseek-harness/index.js";import{LOCAL_ACTION_TYPES as f,SESSION_CONTROL_ERROR_CODES as E,SESSION_CONTROL_VERBS as w,SESSION_MODE_IDS as z}from"../adapter/claude/protocol-contract.js";import{isAuditLocalActionType as J}from"../audit/query/audit-local-actions.js";import{shouldEnableRawApiCapture as Q}from"../audit/raw-capture/types.js";import{buildWireSkills as Y}from"../core/skill-sync/sync-state.js";import{executeEventTool as V}from"../core/mcp/event-tool-executor.js";import{fetchAvailableModels as X}from"../adapter/claude/model-list.js";import{primeAgyModels as Z}from"../adapter/agy/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{agentIdOf as ve}from"../adapter/shared/native-provider-config.js";import{scanDshSessions as _e}from"../adapter/deepseek-harness/session-scanner.js";import{SessionScanCache as v,resolveCodexLeafDirs as Se,resolveClaudeLeafDirs as Ce,resolveAcpLeafDirs as be,resolvePiLeafDirs as Ae,resolveCodeWhaleLeafDirs as Ee,resolveCursorLeafDirs as we,resolveOpenCodeLeafDirs as ye,resolveDshLeafDirs as Re,resolveReasonixLeafDirs as ke}from"./session-scan-cache.js";import{log as h,ConversationLog as Te,AgentApiPacketLog as Pe,BridgeEventLog as xe,GRIX_PATHS as y}from"../core/log/index.js";import{routeSessionControlCommand as Le,routeSessionControlLocalAction as Me}from"./session-control-router.js";import{maybeOfferCliInstall as $e,handleCliInstallQuestionReply as He,handleCliInstallInteractionReply as De,runConfirmedCliInstall as Qe}from"./cli-install-flow.js";import{handleEventCancel as Oe,waitForEventDone as Ie,handleAibotStop as Be,killAndResumeStopSlot as Fe,handleAibotRevoke as Ue}from"./event-stop.js";import{handleConfigureGatewayProvider as qe,getAuditLocalActionHandler as We,handleAuditLocalAction as Ne,handleConnectorRollback as je,getRelayStateSyncer as Ge,relayStateSyncOnConnect as Ke,reportRelayStateLocalChange as ze,handleApplyRelayState as Je,fetchRelayCredential as Ye,isSharedInstance as Ve}from"./connector-ops.js";import{CONNECTOR_ADMIN_ACTION_TYPE as Xe,handleConnectorAdminLocalAction as Ze}from"./remote-admin.js";import{unbindSession as et,handleUnbindTextCommand as tt,handleUnbindLocalAction as nt,handleListSessionsTextCommand as it,handleListSessionsLocalAction as st,handleSyncHistoryLocalAction as ot}from"./session-list.js";import{handleCodexSessionControlOpen as rt,handleSessionControlForPool as at,handleSessionControlLocalActionForPool as dt,handleCodexSessionControlLocalActionOpen as lt,handleCursorSessionControlLocalActionOpen as ct,handlePiSessionControlOpen as ht,handlePiSessionControlRestart as ut,handlePiSessionControlRestartLocalAction as pt,syncOpenCodeBinding as gt,isWorkspaceFreeClient as ft,isCwdLockedClient as mt,ensureDefaultBindingForWorkspaceFreeClient as vt,bindSessionForPool as _t,deferredCallbacks as St,handleOpenHumanSessionControlOpen as Ct,handleCodeWhaleSessionControlOpen as bt,handleCodeWhaleSessionControlLocalActionOpen as At,handleDeepSeekSessionControlLocalActionOpen as Et}from"./session-control-open.js";import{CWD_LOCKED_REJECT_MSG as wt}from"./cwd-policy.js";import{normalizeCustomToolbarItems as yt}from"./acp-custom-toolbar.js";import{handleGetSessionUsage as Rt,handleThreadCompact as kt}from"./session-usage.js";import{handleSkillDeleteLocalAction as Tt,handleSkillUploadLocalAction as Pt,handleSkillEnableLocalAction as xt,handleSkillRefreshLocalAction as Lt,handleSkillDisableLocalAction as Mt,computeSkillReport as $t,reportSessionSkills as Ht,skillsSyncGroupKey as Dt,forceRefreshSkills as Qt,adoptSkillsWireHashFromDisk as Ot,buildLibrarySkillsReport as It,skillLookupEnv as Bt}from"./skill-actions.js";import{resolveToolbarSelection as Ft,persistToolbarSelection as O}from"./toolbar-selection.js";import{normalizeClaudeModeId as Ut,handleExecCommandOptions as qt,resolveSessionModelId as Wt,resolveSessionModeId as Nt,resolveCursorSessionModeId as jt,resolveClaudeSessionEffort as Gt,resolveClaudeSessionModeId as Kt,currentClaudeModeId as zt,buildCursorToolbarMeta as Jt,buildAgyToolbarMeta as Yt,buildAgyQuotaMeta as Vt,sendAgyBindingCard as Xt,refreshAndPushAgyQuota as Zt,handleAgySetModel as en,buildClaudeToolbarMeta as tn}from"./toolbar-meta.js";import{resolveProviderQuotaSource as nn,maybeQueryProviderQuota as sn,startProviderQuotaTimer as on,stopProviderQuotaTimer as rn,refreshAndPushProviderQuota as an,pushProviderQuotaToBindings as dn,enrichProviderQuotaMeta as ln,providerQuotaMetaPayload as cn,refreshProviderQuotaForSession as hn,refreshQuotaAfterModelSwitch as un,doRefreshQuotaAfterModelSwitch as pn}from"./provider-quota.js";import{handleGetRateLimits as gn,resolveRateLimitWakeSessionId as fn,wakeRateLimitSlot as mn}from"./rate-limits.js";import{RevokeHandler as vn}from"./revoke-handler.js";import{AdapterPool as _n}from"./adapter-pool.js";import{parseSessionControlCommand as Sn}from"./session-controller.js";import{isOpenSessionDirectiveMessage as Cn,parseExecApprovalResolutionMessage as bn,parseAgentQuestionReplyMessage as An}from"../core/protocol/interaction-parser.js";import{rejectUnusableAuditOptions as En}from"./inbound-audit-gate.js";import{interceptUnboundInboundEvent as wn}from"./inbound-binding-gate.js";import{dispatchSessionControlTextCommand as yn}from"./text-command-session-control.js";import{dispatchSessionControlLocalAction as Rn}from"./local-action-session-control.js";import{handleCreateFolderLocalAction as kn,handleFileListLocalAction as Tn}from"./local-action-files.js";import{handleAcpToolbarLocalAction as Pn,persistToolbarSelection as xn}from"./local-action-toolbar.js";import{buildOpenedBindingResult as Ln,ensureImportedAgentSession as Mn,hasDiskScanner as $n,normalizePathForCompare as Hn,providerKeyForAdapter as Dn,resolveAgentSessionId as Qn,resolveOrphanTitle as On,setResolvedAgentSessionId as In}from"./session-identity.js";import{buildDshOpenedToolbarMeta as Bn,dshCatalogDataRoot as Fn}from"./dsh-toolbar.js";import{ensureSlotStarted as Un,failSessionOpen as qn,getClaudeWorkerStatus as Wn,refreshClaudeWorkerStatusCard as Nn,resolveCwdForBinding as jn}from"./session-open-helpers.js";import{handleAcpSetModel as Gn,handleAcpSetMode as Kn,resolveAcpInitialDefaults as zn}from"./acp-toolbar-persist.js";import{SessionBindingStore as Jn}from"../core/persistence/session-binding-store.js";import{serveLocalFile as Yn}from"../core/files/index.js";import{uploadReplyFileToAgentMedia as Vn}from"../core/protocol/agent-api-media.js";import{attachmentHostFromWsUrl as Xn,buildInboundAttachmentsJson as Zn,materializeInboundAttachments as ei}from"../core/protocol/inbound-attachments.js";import{ActiveEventStore as ti}from"../core/persistence/active-event-store.js";import{PendingEventCoordinator as ni}from"./pending-event-coordinator.js";import{LifecycleBarrier as ii}from"./lifecycle-barrier.js";import{QUEUE_COMPOSING_TTL_MS as si}from"./event-queue.js";import{DEFAULT_CONNECTOR_RUNTIME_CONFIG as oi,applyConnectorRuntimeConfigPatch as ri,extractConnectorRuntimeConfigPatch as ai}from"./runtime-config.js";import{DEFAULT_QUOTE_TRIGGER_BY_ADAPTER as di,SendController as li}from"./send-controller.js";import{providerQuotaToRateLimits as ci,providerQuotaToCodexRateLimits as hi}from"../core/provider-quota/index.js";import{buildToolUseCard as C,buildToolResultCard as b,buildDshOnlineToolCard as ui,buildLocalGrixCardLink as x}from"./tool-card-utils.js";import{planRawEventDelivery as pi,buildAuxiliaryDetailText as gi}from"./raw-event-delivery.js";import{DeferredEventManager as fi}from"./deferred-events.js";import{buildAgentProbeResult as mi,PROBE_CACHE_TTL_STATIC_MS as vi,PROBE_CACHE_TTL_FULL_MS as _i}from"./probe-helper.js";import{BridgeAuditController as Si}from"../audit/integration/bridge-audit-controller.js";import{isSettlableAuditProducer as Ci,NoopAuditProducer as bi}from"../audit/producer/audit-producer.js";import{buildAuditStatePayload as I,AuditPreparationFailedError as Ai,AuditTurnScopeUnsupportedError as Ei}from"../audit/core/audit-state.js";import{extractAuditOptions as B,freezeAuditOptions as wi,stripAuditOptions as yi}from"../audit/core/audit-options.js";import{AuditSessionOptionsError as Ri}from"../audit/core/audit-session-registry.js";import{waitForIdle as ki,formatWaitDuration as Ti}from"../core/upgrade/idle-wait.js";const Pi=600*1e3,xi=1800*1e3,Li=5*6e4,Mi=60*1e3,$i=4e3;function Hi(L,e,t){const r=M("sha256").update(L).update("\0").update(e).update("\0").update(t).digest("hex");return k.join(y.data,"audit-source","reasonix",`${r}.jsonl`)}const Di=new Set(["claude","codex","cursor","codewhale","opencode","pi","openhuman","agy","acp","deepseek-harness"]),R=3;class yo{config;name;aibotHandle;aibotConfig;pool;stopped=!1;startupAbortController=new AbortController;stopPromise=null;dropPendingEventsRequested=!1;pendingEventsDropped=!1;revokeHandler=new vn;sessionBindings=new Map;customToolbars=new Map;deferredMgr;sendCtrl=new li(oi);bindingStore;globalConfigStore;upgradeTrigger=null;daemonShutdownRequester=null;lifecycleBusyChecker=null;lifecycleAdmissionCloser=null;lifecycleAdmissionRestorer=null;installAgentHandler=null;remoteAdminPorts=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 ii;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;rejectedOutputEvents=new Set;blockedDispatchEvents=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<=Mi}isGrixRelayActive(){const e=this.relayStateApplyPorts?.getAppliedMode?.();return e==="direct"||e==="mitm"}resolveProviderQuotaSource(e){return nn(this,e)}maybeQueryProviderQuota(e=!1,t){return sn(this,e,t)}startProviderQuotaTimer(){on(this)}stopProviderQuotaTimer(){rn(this)}refreshAndPushProviderQuota(e=!1){return an(this,e)}pushProviderQuotaToBindings(e,t=!1){dn(this,e,t)}enrichProviderQuotaMeta(e,t="standard",r=this.cachedProviderQuota,n=this.cachedProviderQuotaSampledAtMs){return ln(this,e,t,r,n)}providerQuotaMetaPayload(e,t,r){return cn(this,e,t,r)}refreshProviderQuotaForSession(e,t,r){return hn(this,e,t,r)}refreshQuotaAfterModelSwitch(e,t,r){un(this,e,t,r)}doRefreshQuotaAfterModelSwitch(e,t,r){return pn(this,e,t,r)}getFreshClaudeRateLimitState(){const e=this.cachedClaudeRateLimitState;return e&&this.isRateLimitsCacheFresh(e.sampledAt)?e:null}getFreshCodexGlobalRateLimitCache(){const e=this.cachedRateLimits,t=this.cachedCodexContextWindow,r=this.cachedCodexTokenUsage;return{sampledAt:Math.max(this.cachedRateLimitsSampledAtMs??0,this.cachedCodexUsageSampledAtMs??0)||null,rateLimits:e,contextWindow:t,tokenUsage:r,hasData:!!(e||t||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(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)}describePendingOrBackgroundWork(){const e=this.lifecycleBarrier.describeActiveAdmissions().map(({label:r,heldMs:n})=>({source:"admission",agent:this.name,label:r,...n>Li?{suspect:`admission held for ${Ti(n)}`}:{}})),t=(this.pool?.describePendingOrBackgroundWork()??[]).map(r=>({...r,agent:this.name}));return[...e,...t]}async waitUntilLifecycleIdle(e){return ki({describeBusy:()=>this.lifecycleBusyChecker?.()??this.describePendingOrBackgroundWork(),isStopped:()=>this.stopped,closeAdmission:()=>this.closeLifecycleAdmissionForRestart(),reopenAdmission:()=>this.reopenLifecycleAdmissionAfterAbort(),budgetMs:xi,log:(t,r)=>{t==="warn"?h.warn(this.name,`${e}: ${r}`):h.info(this.name,`${e}: ${r}`)}})}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 t=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 o=!1;await this.pool.removeSlot(n.sessionId).catch(s=>{r=!0,o=!0,h.warn(this.name,`failed to recycle adapter slot ${n.sessionId} after relay change: ${s}`)}),o||(t+=1)}return t>0&&h.info(this.name,`recycled ${t} 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 t=e.conversation?"full":"static",r=e.conversation?_i:vi;if(!e.fresh){const a=this.probeCache.get(t);if(a&&Date.now()-a.sampledAt<r)return{...a.result,cached:!0}}const n=this.config.adapterType??"acp",o=this.createAdapter(n,"__probe__"),s=e.conversation&&n==="acp"?()=>this.runAcpConversationProbe(o,e.timeoutMs??1e4):void 0;let i;try{i=await mi({adapter:o,agentName:this.name,clientType:this.config.aibot.clientType,adapterType:n,providerBaseUrl:this.config.providerBaseUrl??null,opts:e,launchConversationProbe:s})}finally{o.stop().catch(()=>{})}return this.probeCache.set(t,{result:i,sampledAt:i.probed_at}),i}async runAcpConversationProbe(e,t){const r=Date.now(),n="__probe__",o=`probe-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,s=this.config.agent.cwd||F(),i=()=>Date.now()-r;try{await e.start()}catch(u){return{attempted:!0,ok:!1,latency_ms:i(),error:{code:"conversation_failed",message:`start failed: ${u instanceof Error?u.message:String(u)}`}}}if(!e.isAlive())return{attempted:!0,ok:!1,latency_ms:i(),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=p=>{p===o&&u()},e.on("eventDone",a)});e.deliverInboundEvent({event_id:o,session_id:n,content:"ping",msg_id:o}),e.deliverStopEvent(o,n);let d=null;const c=await Promise.race([l.then(()=>!1),new Promise(u=>{d=setTimeout(()=>u(!0),t)})]);return d&&clearTimeout(d),a&&e.removeListener("eventDone",a),c?{attempted:!0,ok:!1,latency_ms:i(),error:{code:"conversation_timeout",message:`no eventDone within ${t}ms`}}:{attempted:!0,ok:!0,latency_ms:i()}}constructor(e,t,r=new bi){this.config=e,this.auditController=new Si(r,{onAuditState:o=>{try{this.aibotHandle.sendAuditState(I(o,Date.now()))}catch{}}}),Ci(r)&&r.addJobSettledHandler((o,s)=>{this.auditController.handleJobSettled(o,s)}),this.name=e.name;const n=e.adapterType??"acp";if(this.sendCtrl.setDefaultQuoteTrigger(di[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",...q]}:{}},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 Te(e.logDir):null,this.packetLog=e.logDir?new Pe(e.logDir):null,this.bindingStore=new Jn(e.bindingsPath,e.legacyBindingsPath),this.bindingStore.load(),this.globalConfigStore=t??null,this.deferredMgr=new fi(this.name),this.activeEventStore=e.activeEventStorePath?new ti(e.activeEventStorePath):null,this.pendingEvents=new ni(e.pendingEventStorePath),n==="codex")this.sessionScanCache=new v(de,Se);else if(n==="claude")this.sessionScanCache=new v(le,Ce);else if(n==="pi"){const o=e.agent.env?.PI_CODING_AGENT_DIR;this.sessionScanCache=new v(()=>pe(void 0,o),()=>Ae(void 0,o))}else if(n==="codewhale")this.sessionScanCache=new v(ge,Ee);else if(n==="cursor")this.sessionScanCache=new v(fe,we);else if(n==="opencode"){const o=ve(e.agent.command||"opencode")||"opencode";this.sessionScanCache=new v(()=>me(void 0,o),()=>ye(void 0,o))}else if(n==="deepseek-harness"){const o=typeof e.adapterOptions?.dshHome=="string"?e.adapterOptions.dshHome:e.agent.env?.DSH_HOME;this.sessionScanCache=new v(()=>_e(o),()=>Re(o))}else if(n==="agy")this.sessionScanCache=new v(()=>[],()=>[]);else{e.aibot.clientType?.trim().toLowerCase()==="reasonix"&&(this.reasonixTitleScan=new v(ue,ke));const o=ce(e.aibot.clientType);this.sessionScanCache=o?new v(()=>he(void 0,o),()=>be(void 0,o)):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(([,s])=>String(s.cwd??""))}).then(s=>{s.length>0&&h.info(this.name,`restored native provider config after relay disable: ${s.join(", ")}`)}).catch(s=>{h.warn(this.name,`native provider residue sweep failed: ${s instanceof Error?s.message:String(s)}`)}),this.stopped)throw new Error("agent start aborted");if((this.config.adapterType??"acp")==="claude"){if(await X().catch(()=>{}),this.stopped)throw new Error("agent start aborted");this.maybeQueryProviderQuota().catch(()=>{})}else(this.config.adapterType??"acp")==="agy"&&Z(this.config.agent.command).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",r=(this.config.adapterType??"acp")==="opencode",n=(this.config.adapterType??"acp")==="claude"&&this.isGrixRelayActive();if(this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi"||e||n?(this.maybeQueryProviderQuota().catch(()=>{}),this.startProviderQuotaTimer()):(t||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 o=this.config.adapterType??"acp";if(this.pool=new _n({maxPoolSize:this.config.poolMaxSize??20,idleTimeoutMs:this.config.poolIdleTimeoutMs??18e5,eventQueue:this.config.eventQueue},s=>{const i=this.createAdapter(o,s);return i instanceof S&&i.on("acpSessionReady",a=>{this.bindingStore.setAcpSessionId(s,a),this.sessionScanCache.invalidate()}),i},(s,i)=>{this.aibotHandle.sendEventAck({event_id:s,session_id:i,received_at:Date.now()})}),this.pool.setEventStateHandler((s,i,a,l)=>{if(h.info(this.name,`[queue-debug] send event_state session=${i} event=${s} state=${a} queue_pos=${l?.queue_position??""} queue_total=${l?.queue_total??""}`),this.aibotHandle.sendEventState({event_id:s,session_id:i,state:a,content_preview:l?.content_preview,content:l?.content,queue_position:l?.queue_position,queue_total:l?.queue_total,actions:l?.actions,reason:l?.reason,held:l?.held,held_reason:l?.held_reason,updated_at:Date.now()}),this.pushQueueSnapshotForSession(i),a==="running"&&(this.pendingStartedEventIds.add(s),this.pendingEvents.remove(s).catch(d=>{h.warn(this.name,`Failed to remove running event from pending store event=${s}: ${d instanceof Error?d.message:String(d)}`)})),a==="canceled"||a==="failed"){const d=a==="canceled"?"canceled":"failed";this.aibotHandle.sendEventResult({event_id:s,status:d,msg:l?.reason,updated_at:Date.now()}),this.auditController.closeWithoutAdapter(s,d,l?.reason,{queueTerminalState:a}),this.discardEventTrackingState(s),this.pendingEvents.remove(s).catch(c=>{h.warn(this.name,`Failed to remove queued terminal event from pending store event=${s}: ${c instanceof Error?c.message:String(c)}`)})}}),this.pool.setQueueComposingHandler((s,i,a)=>{this.aibotHandle.sendSessionActivitySet({session_id:s,kind:"composing",active:i,...i?{ttl_ms:si,ref_event_id:a}:{}})}),this.pool.setInternalErrorHandler(s=>{this.handleSessionInternalError(s).catch(i=>{h.error(this.name,`[recovery] handleSessionInternalError failed event=${s.eventId} session=${s.sessionId}: ${i instanceof Error?i.message:String(i)}`)})}),this.pool.setEventStartedHandler((s,i)=>{if(this.reportSessionSkills(i),this.config.adapterType!=="claude")return;this.claudeWorkerStatus.set(i,"busy");const a=this.bindingStore.get(i);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:"busy",cwd:a.cwd,meta:this.buildClaudeToolbarMeta(i)})}),this.pool.setEventDoneHandler((s,i)=>{this.markAuditAdapterClosed(s,i);const a=this.config.adapterType??"acp";if(a==="claude"){this.claudeWorkerStatus.set(i,"ready");const l=this.bindingStore.get(i);l?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:"ready",cwd:l.cwd,meta:this.buildClaudeToolbarMeta(i)})}else if(a==="agy"){const l=this.bindingStore.get(i);if(l?.cwd){const d=this.buildAgyToolbarMeta(i),c=d?.available_models??[];h.info(this.name,`[agy-toolbar-diag] eventDone push binding card session=${i} model_id=${String(d?.model_id??"")} available_models=${c.length} meta_keys=${d?Object.keys(d).join(","):"<none>"}`),this.sendAgyBindingCard(i,l.cwd,d),this.refreshAndPushAgyQuota(i)}else h.info(this.name,`[agy-toolbar-diag] eventDone skip binding card: no binding cwd session=${i}`)}}),this.pool.setSessionActivityHandler((s,i,a)=>{const l=this.selfDrivenSessions.has(s),d=this.selfDrivenLabels.get(s);i?(this.selfDrivenSessions.add(s),a&&this.selfDrivenLabels.set(s,a),this.aibotHandle.sendSessionActivitySet({session_id:s,kind:"composing",active:!0,ttl_ms:9e4})):(this.selfDrivenSessions.delete(s),this.selfDrivenLabels.delete(s),l&&this.aibotHandle.sendSessionActivitySet({session_id:s,kind:"composing",active:!1})),(l!==i||i&&a!==void 0&&a!==d)&&this.pushQueueSnapshotForSession(s)}),await this.replayPendingEventsOnStartup(),this.stopped)throw new Error("agent start aborted");this.pool.startIdleSweep(),h.info(this.name,`Ready (adapter: ${o}, 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(i=>[i,this.eventSessionIndex.get(i)]));e.length>0&&this.activeEventStore&&await this.activeEventStore.save(e);for(const i of e)h.info(this.name,`Canceling active event on shutdown: ${i}`),this.sendEventResultWithCleanup(i,"canceled","process shutting down");e.length>0&&await new Promise(i=>setTimeout(i,100)),this.pool?.clearActiveEventsForShutdown();for(const i of e){const a=t.get(i),l=a?this.pool?.getSlot(a):void 0;this.auditController.markAdapterClosed(i,l?.adapter.takeAuditBoundary?.(i)??{processTerminated:!0})}const r=this.deferredMgr.getAllDeferredEntries(),n=this.pool?.drainAllQueuedEvents()??[],o=this.pendingEvents.dedupe([...this.pendingEvents.replaySnapshot(),...r.map(i=>({kind:"deferred",channel:i.channel,sessionId:i.sessionId,event:i.event})),...n.map(i=>({kind:"queued",event:i}))]);let s=!1;if(this.dropPendingEventsRequested)try{await this.pendingEvents.clear(),this.pendingEventsDropped=!0}catch(i){h.warn(this.name,`Failed to clear pending event store on removal: ${i instanceof Error?i.message:String(i)}`)}else try{s=await this.pendingEvents.mergeForShutdown(o)}catch(i){h.error(this.name,`Failed to persist pending events on shutdown: ${i instanceof Error?i.message:String(i)}`)}if(!s)for(const i of o){const a=i.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,t=se(this.config.agent.clientType,e),r=this.config.agent.env;let n=Object.keys(t).length>0?{...t,...r}:r;if(oe(t)){const o=te()?.getRuntimeInfo(),s={...r??{},...t},i=re(s,{proxyUrl:o?.proxyUrl,caCertPath:o?.caCertPath,caBundlePath:o?.caBundlePath});return delete i.ANTHROPIC_API_KEY,delete i.CLAUDE_CODE_OAUTH_TOKEN,i}if(ie(this.config.agent.clientType)){const o=ne(this.name);o&&(n={...n??{},...o})}return ee(n,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:(o,s,i,a,l,d,c)=>{this.sendStreamChunkByRuntimeConfig(o,s,i,a,l,d,c)},sendFinalStreamChunkReliable:this.reliableFinalWiring("deepseek-harness",$i),sendThinking:(o,s,i)=>this.sendThinkingByRuntimeConfig(o,s,i),sendEventResult:(o,s,i,a)=>{this.sendEventResultWithCleanup(o,s,i,void 0,a)},sendRawEventEnvelope:(o,s,i,a)=>{const l=ui(i);if(l){this.sendToolExecutionCard(o,s,l);return}this.deliverRawEventEnvelope(o,s,i,"deepseek",a)},sendLocalActionResult:(o,s,i,a,l)=>{this.aibotHandle.sendLocalActionResult({action_id:o,status:s,...i!==void 0?{result:i}:{},...a?{error_code:a}:{},...l?{error_msg:l}:{}},e)},sendPermissionCard:o=>{this.sendGrixApprovalCard(o,"deepseek")},sendUpdateBindingCard:(o,s,i,a)=>{this.aibotHandle.sendUpdateBindingCard({session_id:o,worker_status:s,cwd:i,...this.providerQuotaMetaPayload(a,o,i)})},getAgentProfile:()=>({...this.agentProfile,systemPrompt:this.agentSystemPrompt}),getAgentId:()=>this.config.aibot.agentId,queryProviderQuota:(o,s)=>this.maybeQueryProviderQuota(o===!0,s??{providerId:"deepseek"}),agentInvoke:async(o,s,i)=>this.platformInvoke(o,s,i),eventToolInvoke:async(o,s)=>this.invokeDshEventTool(o,s)},r=M("sha256").update(this.config.aibot.agentId).digest("hex").slice(0,24),n=this.config.adapterOptions??{};return new K({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:n},t,{aibotSessionId:e,bindingStore:this.bindingStore,globalConfigStore:this.globalConfigStore,agentName:this.name,dataRoot:k.join(y.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 t={...this.config.adapterOptions??{}};t.bindingStore=this.bindingStore,t.aibotSessionId=e;const r=this.bindingStore.get(e),n=this.resolveSessionModelId(e);n&&(t.model=n);const o=this.resolveCursorSessionModeId(e),s=o??"full_auto";o||this.bindingStore.setCursorModeId(e,s),t.mode=s,r?.cwd&&(t.workspace=r.cwd);const i={sendStreamChunk:(a,l,d,c,u,p,g)=>{this.sendStreamChunkByRuntimeConfig(a,l,d,c,u,p,g)},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(p=>p.header).join(", "),u=x(`[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:t},i)}createClaudeAdapter(e){let t;const r=()=>{const i=this.pool.getSlot(e);return i?.adapter===t&&!i.stopping},n={onSessionHistoryUnavailable:(i,a)=>{if(!r())return;if(this.bindingStore.get(e)?.claudeSessionId!==i.nativeSessionId){a&&this.sendEventResultWithCleanup(a.event_id,"canceled","session binding changed"),this.pool.removeSlot(e).catch(()=>{});return}this.bindingStore.delete(e),this.sessionBindings.delete(e),this.sessionProviderHints.delete(e),this.sessionProviderQuotas.delete(e),this.sessionProviderMeta.delete(e),this.sessionScanCache.invalidate(),a&&this.sendEventResultWithCleanup(a.event_id,"failed",i.message,E.bindingMissing,!0),this.pool.removeSlot(e).catch(d=>{h.warn(this.name,`Failed to dispose obsolete Claude slot: ${d instanceof Error?d.message:String(d)}`)});const l=this.resolveBindingChannelKey("claude");this.aibotHandle.sendMsg({...a?{event_id:a.event_id,quoted_message_id:a.msg_id}:{},session_id:e,client_msg_id:`claude_history_unavailable_${e}_${i.nativeSessionId}`,msg_type:1,content:x(i.message,"agent_open_session",{summary_text:i.message,detail_text:"\u7ED1\u5B9A\u540E\u5C06\u5F00\u59CB\u65B0\u4F1A\u8BDD\uFF0C\u8BF7\u91CD\u65B0\u53D1\u9001\u521A\u624D\u7684\u8BF7\u6C42\u3002\u5E73\u53F0\u804A\u5929\u6D88\u606F\u4ECD\u4FDD\u7559\uFF0C\u65E7\u5DE5\u5177\u72B6\u6001\u4E0D\u4F1A\u6062\u590D\u3002"}),extra:{channel_data:{[l]:{sessionBinding:{status:"missing",reason:"binding_missing",error_code:E.bindingMissing}}}}})},sendReply:(i,a,l,d,c)=>{this.sendReplyByRuntimeConfig(i,a,l,d,c)},sendStreamChunk:(i,a,l,d,c,u,p)=>{this.sendStreamChunkByRuntimeConfig(i,a,l,d,c,u,p)},sendMedia:(i,a,l,d,c,u,p)=>{this.aibotHandle.sendMedia({event_id:i,session_id:a,content:l,msg_type:2,quoted_message_id:c||void 0,client_msg_id:u||void 0,extra:p?{media_caption:d,...p}:{media_caption:d}})},sendEventResult:(i,a,l,d,c)=>{this.sendEventResultWithCleanup(i,a,l,d,c)},sendEventAck:(i,a)=>{this.aibotHandle.sendEventAck({event_id:i,session_id:a,received_at:Date.now()})},agentInvoke:async(i,a,l)=>this.platformInvoke(i,a,l),sendLocalActionResult:(i,a,l,d,c)=>{this.aibotHandle.sendLocalActionResult({action_id:i,status:a,...l!==void 0?{result:l}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}},e)},sendToolUse:(i,a,l,d)=>{this.sendToolExecutionCard(i,a,C(l,d))},sendToolResult:(i,a,l,d)=>{this.sendToolExecutionCard(i,a,b(l,d))},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:(i,a,l)=>{this.sendGrixAgentQuestionCard(i,a,l)},sendPermissionCard:i=>{this.sendGrixApprovalCard(i,"claude")},sendDirectMessage:i=>{this.aibotHandle.sendMsg({session_id:i.sessionId,msg_type:1,content:i.content,...i.clientMsgId?{client_msg_id:i.clientMsgId}:{},...i.quotedMessageId?{quoted_message_id:i.quotedMessageId}:{}})},onStatusLineUpdated:i=>{if(!r())return;(i.rateLimits?.fiveHour||i.rateLimits?.sevenDay)&&(this.cachedClaudeRateLimitState=i);const a=this.bindingStore.get(e);a?.cwd&&this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:this.claudeWorkerStatus.get(e)??"ready",cwd:a.cwd,meta:this.buildClaudeToolbarMeta(e)})},sendMcpFrame:i=>{this.aibotHandle.sendMcpFrame(e,i)}},o=this.config.adapterOptions??{},s={...o,sessionRuntimeResolver:()=>{if(!r())throw new Error("Claude adapter no longer owns session binding");const i=this.bindingStore.get(e),a=this.auditController.getSession(e);return{cwd:i?.cwd,modeId:this.resolveClaudeSessionModeId(e)??z.fullAuto,modelId:this.resolveSessionModelId(e),effort:this.resolveClaudeSessionEffort(e),pluginDir:o.pluginDir,claudeSessionId:i?.claudeSessionId,...a?{audit:{enabled:!0,profile:a.options.profile,capture:a.options.capture}}:{},onSessionIdAssigned:l=>{const d=this.bindingStore.get(e);!r()||!d?.cwd||d.cwd!==i?.cwd||d.claudeSessionId!==i?.claudeSessionId||(this.bindingStore.setClaudeSessionId(e,l),this.sessionScanCache.invalidate())}}}};return t=new $({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:s},n),t}createCodexAdapter(e){let t=null;const r={sendEventResult:(i,a,l)=>{if(a!=="responded"){this.sendEventResultWithCleanup(i,a,l);return}this.sendCtrl.sendFinalStreamChunkReliable(i,e,`codex_terminal_fence_${i}`,5e3,!0,!0).then(()=>this.sendEventResultWithCleanup(i,a,l),d=>{const c=`codex output acceptance fence failed: ${d instanceof Error?d.message:String(d)}`;this.sendEventResultWithCleanup(i,a==="responded"?"failed":a,a==="responded"?c:l)})},sendEventAck:(i,a)=>this.aibotHandle.sendEventAck({event_id:i,session_id:a,received_at:Date.now()}),sendCodexEvent:i=>{this.shouldDropCodexDisplayEvent(i.event_id,i.codex_method)||(this.captureCodexAuditOutput(i),this.aibotHandle.sendCodexEvent(this.stampCodexEventQuote(i)),this.logCodexEventToConversation(i))},sendThinking:(i,a,l)=>{this.sendThinkingByRuntimeConfig(i,a,l)},sendRunError:(i,a,l)=>{this.sendRunErrorAsChunk(i,a,l)},sendUpdateBindingCard:(i,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:i,worker_status:a,cwd:l,...Object.keys(c).length>0?{meta:c}:{}})},agentInvoke:async(i,a,l)=>this.platformInvoke(i,a,l),sendLocalActionResult:(i,a,l,d,c)=>this.aibotHandle.sendLocalActionResult({action_id:i,status:a,...l!==void 0?{result:l}:{},...d?{error_code:d}:{},...c?{error_msg:c}:{}},e),sendSessionActivitySet:(i,a,l,d)=>{this.aibotHandle.sendSessionActivitySet({session_id:i,kind:a,active:l,...d??{}})},getConversationLog:()=>this.conversationLog,getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId,onRateLimitsUpdated:i=>{this.cachedRateLimits=i,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:{...i.primary.windowMinutes>0?{primary:i.primary}:{},...i.secondary.windowMinutes>0?{secondary:i.secondary}:{},sampledAt:l},rate_limit_primary_percent:i.primary.usedPercent,rate_limit_secondary_percent:i.secondary.usedPercent,rate_limit_primary_window_min:i.primary.windowMinutes,rate_limit_secondary_window_min:i.secondary.windowMinutes,credits:i.credits,...i.extras&&i.extras.length>0?{extra_limits:i.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:i=>{if(!i)return;this.cachedCodexContextWindow=i,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:i,...t?.getEffortMeta()}})},onTokenUsageUpdated:i=>{i&&(this.cachedCodexTokenUsage=i,this.cachedCodexUsageSampledAtMs=Date.now())}},n=this.config.adapterOptions??{},o=this.auditController.getAdapterPreparation(e),s=i=>Ft(this,"codex",e,i);return t=new H({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:{...n,model:s("model")??n.model,collaborationMode:s("mode")??n.collaborationMode,reasoningEffort:s("reasoningEffort")??n.reasoningEffort,serviceTier:s("serviceTier")??n.serviceTier,sandboxMode:s("sandboxMode")??n.sandboxMode,aibotSessionId:e,bindingStore:this.bindingStore,...Q(o?.options)?{rawApiCapture:{auditId:o.auditId,sessionId:e,spoolRootDir:k.join(y.data,"audit-replay","raw-spool")}}:{}}},r),t}createCodeWhaleAdapter(e){const t={sendEventResult:(n,o,s)=>{this.sendEventResultWithCleanup(n,o,s)},sendEventAck:(n,o)=>this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()}),sendStreamChunk:(n,o,s,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,s,i,a,l)},sendUpdateBindingCard:(n,o,s,i)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:o,cwd:s,...this.providerQuotaMetaPayload(i,n,s)}),sendLocalActionResult:(n,o,s,i,a)=>this.aibotHandle.sendLocalActionResult({action_id:n,status:o,...s!==void 0?{result:s}:{},...i?{error_code:i}:{},...a?{error_msg:a}:{}},e),sendSessionActivitySet:(n,o,s,i)=>{this.aibotHandle.sendSessionActivitySet({session_id:n,kind:o,active:s,...i??{}})},sendToolUse:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,C(s,i))},sendToolResult:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,b(s,i))},agentInvoke:async(n,o,s)=>this.platformInvoke(n,o,s),getConversationLog:()=>this.conversationLog,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,aibotSessionId:e,bindingStore:this.bindingStore,agentName:this.name,model:this.resolveSessionModelId(e)??r.model,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},t)}createPiAdapter(e){const t={sendEventResult:(n,o,s,i,a)=>{this.sendEventResultWithCleanup(n,o,s,i,a),h.info("bridge",`[pi] sendEventResult event=${n} status=${o}`)},sendEventAck:(n,o)=>this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()}),sendUpdateBindingCard:(n,o,s,i)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:o,cwd:s,...this.providerQuotaMetaPayload(i,n,s)}),agentInvoke:async(n,o,s)=>this.platformInvoke(n,o,s),sendLocalActionResult:(n,o,s,i,a)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:o,...s!==void 0?{result:s}:{},...i?{error_code:i}:{},...a?{error_msg:a}:{}},e)},sendSessionActivitySet:(n,o,s,i)=>{this.aibotHandle.sendSessionActivitySet({session_id:n,kind:o,active:s,...i??{}})},sendToolUse:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,C(s,i))},sendToolResult:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,b(s,i))},sendStreamChunk:(n,o,s,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,s,i,a,l),a&&h.info("bridge",`[pi] sendFinalStreamChunk event=${n} seq=${i}`)},sendFinalStreamChunkReliable:this.reliableFinalWiring("pi"),sendThinking:(n,o,s)=>{this.sendThinkingByRuntimeConfig(n,o,s)},sendRunError:(n,o,s,i,a)=>{this.sendRunErrorAsChunk(n,o,s,i,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,clientType:this.config.agent.clientType,globalConfigStore:this.globalConfigStore,...this.config.agent.provider?{provider:this.config.agent.provider}:{}}},t)}createOpenHumanAdapter(e){const t={sendStreamChunk:(n,o,s,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,s,i,a,l)},sendFinalStreamChunkReliable:async(n,o,s,i)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(n,o,i)}catch(a){throw h.error("bridge",`[openhuman] sendFinalStreamChunkReliable ACK failed event=${n}: ${a}`),a}},sendEventResult:(n,o,s)=>{this.sendEventResultWithCleanup(n,o,s),h.info("bridge",`[openhuman] sendEventResult event=${n} status=${o}`)},sendEventAck:(n,o)=>this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()}),sendToolUse:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,C(s,i))},sendToolResult:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,b(s,i))},sendThinking:(n,o,s)=>{this.sendThinkingByRuntimeConfig(n,o,s)},sendRunError:(n,o,s)=>{this.sendRunErrorAsChunk(n,o,s,0)},sendUpdateBindingCard:(n,o,s,i)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:o,cwd:s,...this.providerQuotaMetaPayload(i,n,s)}),agentInvoke:async(n,o,s)=>this.platformInvoke(n,o,s),sendLocalActionResult:(n,o,s,i,a)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:o,...s!==void 0?{result:s}:{},...i?{error_code:i}:{},...a?{error_msg:a}:{}},e)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=this.config.adapterOptions??{};return new N({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:r},t,{port:r.port,host:r.host,workspaceDir:r.workspace_dir,sessionToken:r.session_token,enableSessionBinding:!0,aibotSessionId:e})}createOpenCodeAdapter(e){const t={sendStreamChunk:(n,o,s,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,s,i,a,l)},sendFinalStreamChunkReliable:this.reliableFinalWiring("opencode"),sendEventResult:(n,o,s,i,a)=>{this.sendEventResultWithCleanup(n,o,s,i,a),h.info("bridge",`[opencode] sendEventResult event=${n} status=${o}`)},sendEventAck:(n,o)=>this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()}),sendToolUse:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,C(s,i))},sendToolResult:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,b(s,i))},sendThinking:(n,o,s)=>{this.sendThinkingByRuntimeConfig(n,o,s)},sendRunError:(n,o,s)=>{this.sendRunErrorAsChunk(n,o,s)},sendUpdateBindingCard:(n,o,s,i)=>this.aibotHandle.sendUpdateBindingCard({session_id:n,worker_status:o,cwd:s,...this.providerQuotaMetaPayload(i,n,s)}),agentInvoke:async(n,o,s)=>this.platformInvoke(n,o,s),sendLocalActionResult:(n,o,s,i,a)=>{this.aibotHandle.sendLocalActionResult({action_id:n,status:o,...s!==void 0?{result:s}:{},...i?{error_code:i}:{},...a?{error_msg:a}:{}},e)},sendPermissionCard:n=>{this.sendGrixApprovalCard(n,"opencode")},sendAgentQuestionCard:(n,o,s)=>{this.sendGrixAgentQuestionCard(n,o,s)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=this.config.adapterOptions??{};return new P({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:r},t,{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 t={sendStreamChunk:(n,o,s,i,a,l)=>{this.sendStreamChunkByRuntimeConfig(n,o,s,i,a,l)},sendEventResult:(n,o,s)=>{this.sendEventResultWithCleanup(n,o,s)},sendEventAck:(n,o)=>{this.aibotHandle.sendEventAck({event_id:n,session_id:o,received_at:Date.now()})},agentInvoke:async(n,o,s)=>this.platformInvoke(n,o,s),forceCompleteInternalEvent:(n,o)=>{this.pool.eventComplete(n,o),this.pushQueueSnapshotForSession(o)},persistConversationId:(n,o)=>{this.bindingStore.setAgyConversationId(n,o)},sendToolUse:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,C(s,i))},sendToolResult:(n,o,s,i)=>{this.sendToolExecutionCard(n,o,b(s,i))},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},r=n=>{const o=this.bindingStore.get(n);return{cwd:o?.cwd,modelId:this.resolveSessionModelId(n),conversationId:o?.agyConversationId}};return new D({command:this.config.agent.command,args:this.config.agent.args,env:this.resolveSpawnEnv(),options:this.config.adapterOptions??{}},t,r)}createAcpAdapter(e){const t=this.isAcpRawTransportEnabled(),r={sendStreamChunk:(d,c,u,p,g,_,A)=>{this.sendStreamChunkByRuntimeConfig(d,c,u,p,g,_,A)},sendFinalStreamChunkReliable:this.reliableFinalWiring("acp",4e3),sendEventResult:(d,c,u,p,g)=>{this.sendEventResultWithCleanup(d,c,u,p,g)},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,p,g)=>{this.aibotHandle.sendLocalActionResult({action_id:d,status:c,...u!==void 0?{result:u}:{},...p?{error_code:p}:{},...g?{error_msg:g}:{}},e)},sendRawEventEnvelope:(d,c,u)=>{this.sendAcpRawEventEnvelope(d,c,u)},sendToolUse:(d,c,u,p)=>{if(t){this.sendAcpRawEventEnvelope(d,c,{type:"tool_use",payload:{tool_name:u,tool_input:p??""}});return}this.sendToolExecutionCard(d,c,C(u,p))},sendToolResult:(d,c,u,p)=>{this.sendToolExecutionCard(d,c,b(u,p))},sendThinking:(d,c,u)=>{this.sendThinkingByRuntimeConfig(d,c,u)},sendRunError:(d,c,u)=>{this.sendRunErrorAsChunk(d,c,u)},sendAgentQuestionCard:(d,c,u)=>{this.sendGrixAgentQuestionCard(d,c,u)},sendPermissionCard:d=>{h.info("bridge","sendPermissionCard callback entered",{rawTransport:t,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(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}}),h.info("bridge","sendPermissionCard: sent via rawEventEnvelope",{eventId:d.eventId,toolCallId:d.toolCallId});return}const u=`perm_${T()}`,p={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:p.content.length});try{this.aibotHandle.sendMsg(p),h.info("bridge","sendPermissionCard: aibotHandle.sendMsg returned",{eventId:d.eventId,clientMsgId:u})}catch(g){h.error("bridge","sendPermissionCard: aibotHandle.sendMsg threw",{eventId:d.eventId,clientMsgId:u,error:g instanceof Error?g.message:String(g)})}},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,p)=>{const g={...p??{}};if(!g.rate_limits&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{});const _=this.providerQuotaToRateLimits(this.cachedProviderQuota);_&&(g.rate_limits=_)}!g.provider_quota&&this.cachedProviderQuota?.success&&(g.provider_quota=this.cachedProviderQuota),this.aibotHandle.sendUpdateBindingCard({session_id:d,worker_status:c,cwd:u,...Object.keys(g).length>0?{meta:g}:{}})},onSkillsUpdate:(d,c)=>{try{this.aibotHandle.sendSkillsUpdate({skills:Y(d,y.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 p="usedPercentage"in d?d.usedPercentage:Math.min(100,d.used/d.size*100),g={context_window:{..."usedPercentage"in d?{}:d,usedPercentage:p,remainingPercentage:100-p}};if((this.config.aibot.clientType==="kiro"||this.config.aibot.clientType==="kimi")&&this.cachedProviderQuota?.success){this.isRateLimitsCacheFresh(this.cachedProviderQuotaSampledAtMs)||this.maybeQueryProviderQuota().catch(()=>{}),g.provider_quota=this.cachedProviderQuota;const _=this.providerQuotaToRateLimits(this.cachedProviderQuota);_&&(g.rate_limits=_)}this.aibotHandle.sendUpdateBindingCard({session_id:e,worker_status:"ready",cwd:u.cwd,meta:g})}},sendMcpFrame:d=>{this.aibotHandle.sendMcpFrame(e,d)},getAgentProfile:()=>this.agentProfile,getAgentId:()=>this.config.aibot.agentId},n=e?this.bindingStore.get(e):void 0,o=e?this.auditController.getSession(e):void 0,s=this.config.aibot.clientType==="reasonix"&&o?Hi(this.name,e,o.auditId):void 0,i=this.globalConfigStore?.get(this.name),{initialModel:a,initialMode:l}=zn({sessionBinding:n,globalDefaults:i,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: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 xe(this.config.logDir,`${this.name}-${e}`):null,reasonixAuditTranscriptPath:s,agentType:this.config.aibot.clientType,newSessionParams:this.config.adapterOptions?.newSessionParams&&typeof this.config.adapterOptions.newSessionParams=="object"&&!Array.isArray(this.config.adapterOptions.newSessionParams)?this.config.adapterOptions.newSessionParams:void 0})}async connectAibot(){const t=await new U().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 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(o=>{h.error(this.name,`handleAibotEvent failed: ${o}`),this.aibotHandle.sendEventAck({event_id:n.event_id,session_id:n.session_id,received_at:Date.now()});const s=o instanceof Error?o.message:String(o);this.handleStaleCwdError(n,s)||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(o){h.error(this.name,`handleAibotStop failed: ${o}`)}}),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(o){h.error(this.name,`agentDeletedHandler failed: ${o}`)}}),this.aibotHandle.onShareSet(n=>{try{this.shareSetHandler?.(Array.isArray(n?.shared_to)?n.shared_to:[])}catch(o){h.error(this.name,`onShareSet failed: ${o}`)}}),this.aibotHandle.onProfilePush(n=>{try{this.applyAgentProfile(n?.agent_name,n?.introduction,{source:"profile_push",respawnOnChange:!0},n?.system_prompt)}catch(o){h.error(this.name,`onProfilePush failed: ${o}`)}}),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(o){h.error(this.name,`onSkillSync failed: ${o}`)}}),this.aibotHandle.onRevoke(n=>{this.handleAibotRevoke(n).catch(o=>{h.error(this.name,`handleAibotRevoke failed: ${o}`)})}),this.aibotHandle.onLocalAction(n=>{this.handleAibotLocalAction(n).catch(o=>{h.error(this.name,`handleAibotLocalAction failed: ${o}`)})}),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(o=>{h.error(this.name,`handleEventCancel failed: ${o}`)})}),this.aibotHandle.onMcpFrame((n,o)=>{const s=this.pool.getSlot(n)?.adapter;s?.deliverMcpFrameToAgent?s.deliverMcpFrameToAgent(o):h.warn(this.name,`mcp_frame: no adapter for session=${n}`)}),this.aibotHandle.onQueueClear(n=>{const o=this.pool.clearQueue(n.session_id);this.aibotHandle.sendQueueClearResult({session_id:n.session_id,canceled_event_ids:o}),this.pushQueueSnapshotForSession(n.session_id)}),typeof this.aibotHandle.onQueueReorder=="function"&&this.aibotHandle.onQueueReorder(n=>{const o=Array.isArray(n.ordered_event_ids)?n.ordered_event_ids.filter(i=>typeof i=="string"&&i.length>0):[],s=this.pool.reorderQueue(n.session_id,o);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 o=typeof n.session_id=="string"?n.session_id:"",s=typeof n.event_id=="string"?n.event_id:"",i=n.hold!==!1;if(h.info(this.name,`recv event_hold event_id=${s} session_id=${o} hold=${i} reason=${n.reason??""}`),!o||!s){this.aibotHandle.sendEventHoldResult({session_id:o,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(o,s,i,a,l),c=d==="ok";this.aibotHandle.sendEventHoldResult({session_id:o,event_id:s,ok:c,held:c?i:!1,...c?{}:{error:d}}),c&&this.pushQueueSnapshotForSession(o)}),typeof this.aibotHandle.onQueueEdit=="function"&&this.aibotHandle.onQueueEdit(n=>{const o=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=${o}`),!o||!s){this.aibotHandle.sendQueueEditResult({session_id:o,event_id:s,ok:!1,error:"bad_request"});return}const i=typeof n.content=="string"?n.content:"",a=this.pool.editQueuedEvent(o,s,i),l=a==="ok";this.aibotHandle.sendQueueEditResult({session_id:o,event_id:s,ok:l,...l?{}:{error:a}}),l&&this.pushQueueSnapshotForSession(o)}),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 o of n)h.info(this.name,`Failing stale event on startup: ${o}`),this.aibotHandle.sendEventResult({event_id:o,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,o)=>{this.handleStreamRejected(n,o)})}handleStreamRejected(e,t){if(!e||this.rejectedOutputEvents.has(e))return;this.rejectedOutputEvents.add(e),this.rejectedOutputEvents.size>1e3&&this.rejectedOutputEvents.delete(this.rejectedOutputEvents.values().next().value);const r=this.pool?.getEventSessionId(e)??this.eventSessionIndex.get(e),n=`required agent output rejected (code=${t})`;this.sendCtrl.markEventRejected(e),this.sendCtrl.sendEventResult(e,"failed",n,t===0?"agent_output_integrity_failed":"agent_output_rejected"),this.auditController.markResponded(e,"failed",n),this.deferredMgr.removeEvent(e),this.discardEventTrackingState(e),this.blockedDispatchEvents.delete(e),this.surfacedRunErrorTexts.delete(e),this.pendingEvents.remove(e).catch(o=>{h.warn(this.name,`Rejected event pending cleanup failed event=${e}: ${o}`)});try{this.pool?.rejectEventOutput(e,r)}catch(o){h.warn(this.name,`Rejected event cancellation failed event=${e}: ${o}`)}finally{this.pool?.cleanupEvent(e,r),r&&this.pushQueueSnapshotForSession(r)}}applyAgentProfile(e,t,r,n){const o=String(e??"").trim(),s=String(t??"").trim(),i=n===void 0?this.agentSystemPrompt:String(n),a=o!==this.agentProfile.agentName||s!==this.agentProfile.introduction||i!==this.agentSystemPrompt;this.agentProfile={agentName:o,introduction:s},this.agentSystemPrompt=i,o||s?h.info(this.name,`agent profile (${r.source}): GOT name="${o}" intro_len=${s.length} system_prompt_len=${i.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 t=this.pool.getAllSlots();let r=0;for(const i of t)if(i.adapter.onAgentProfileChanged)try{i.adapter.onAgentProfileChanged(),r++}catch(a){h.warn(this.name,`onAgentProfileChanged failed for session=${i.sessionId}: ${a}`)}const n=t.filter(i=>i.adapter instanceof $),o=n.filter(i=>{if(i.state!=="ready")return!1;const a=i.adapter.getStatus();return!a.busy&&!a.backgroundBusy}),s=n.length-o.length;h.info(this.name,`${e}: notified ${r} adapter(s) via hook; respawning ${o.length} idle Claude slot(s), skipping ${s} busy`);for(const i of o)this.pool.removeSlot(i.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 t=this.pool?.getQueueSnapshot(e)??null,r=t?[...t.running]:[],n=t?t.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"}]})):[],o=t?t.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}`,i=this.selfDrivenLabels.get(e)??"Background task in progress";r.push(s),n.push({event_id:s,content_preview:i,title:i,summary:i,actions:[]})}return{session_id:e,running:r,running_items:n,queued:o}}pushQueueSnapshotForSession(e){if(!this.config.eventQueue||!this.pool)return;const t=this.buildQueueSnapshotPayload(e);h.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,r){if(e==="file_link")return Yn(t);if(e==="file_upload")return this.uploadFileAndSendMedia(t);if(e==="toolbar_set")return this.setCustomToolbar(t);const n=e==="chat_state_update"&&typeof t.reason=="string"&&t.reason.startsWith("dispatch_blocked:")&&(t.state==="waiting_question"||t.state==="waiting_approval")?this.pool?.getSlot(String(t.session_id??""))?.adapter.getActiveEventIds()??[]:[];for(const o of n)this.rejectedOutputEvents.has(o)||this.blockedDispatchEvents.set(o,String(t.state));return this.aibotHandle.agentInvoke(e,t,r)}async setCustomToolbar(e){const t=String(this.config.agent.clientType??this.config.aibot.clientType??"").trim().toLowerCase();if(t!=="acp")throw new Error(`grix_toolbar_set is only supported for client_type "acp" (this agent is "${t||"unknown"}")`);const r=String(e.session_id??"").trim();if(!r)throw new Error("grix_toolbar_set requires a session_id");const n=yt(e.items);return this.customToolbars.set(r,n),this.aibotHandle.sendUpdateBindingCard({session_id:r,metadata_only:!0,meta:{custom_toolbar:n}}),h.info(this.name,`[toolbar] custom toolbar published session=${r} items=${n.length}`),{ok:!0,items:n.length}}invokeDshEventTool(e,t){const r=V(this.aibotHandle,e,t),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 t=String(e.file_path??"").trim(),r=String(e.session_id??"").trim(),n=String(e.caption??"").trim(),o=String(e.reply_to_message_id??"").trim();if(!t)throw new Error("file_path is required");if(!r)throw new Error("session_id is required");const s=await Vn({wsURL:this.config.aibot.url,apiKey:this.config.aibot.apiKey,sessionID:r,filePath:t}),i=await this.aibotHandle.sendMedia({session_id:r,msg_type:2,content:n||`[${s.attachment_type}]`,client_msg_id:`file_upload_${T()}`,...o?{quoted_message_id:o}:{},extra:s.extra});if(i.cmd!=="send_ack"){const l=i.payload??{},d=String(l.msg??i.cmd);throw new Error(`media message send failed: ${d}`)}const a=i.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,t,r,n,o){const s=this.indexEventSession(e,t)??t;this.auditController.captureReply(e,r),this.sendCtrl.sendReply(e,s,r,n,o),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,...i}=e;return i}const t=e;if(t.codex_method!=="item/agentMessage/delta")return e;const n=t.codex_payload?.params?.phase;if(typeof n=="string"&&n.trim()&&n.trim().toLowerCase()!=="final_answer")return e;const o=this.sendCtrl.getDefaultQuotedMessageId(e.event_id);return o?{...e,quoted_message_id:o}:e}captureCodexAuditOutput(e){if(e.codex_method!=="item/agentMessage/delta")return;const t=e.codex_payload?.params,r=typeof t?.phase=="string"?t.phase.trim().toLowerCase():"";if(r&&r!=="final_answer")return;const n=t?.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,t){return async(r,n,o,s)=>{try{await this.sendCtrl.sendFinalStreamChunkReliable(r,n,o,t,!1,!1,s)}catch(i){throw h.error("bridge",`[${e}] sendFinalStreamChunkReliable ACK failed event=${r}: ${i}`),i}h.info("bridge",`[${e}] sendFinalStreamChunkReliable done event=${r}`)}}sendStreamChunkByRuntimeConfig(e,t,r,n,o,s,i){const a=this.indexEventSession(e,t)??t;this.auditController.captureStreamChunk(e,n,r),this.sendCtrl.sendStreamChunk(e,a,r,n,o,s,i),(r||o)&&this.conversationLog?.logOutbound?.(a,e,o?"stream_chunk_finish":"stream_chunk",r)}surfacedRunErrorTexts=new Map;markRunErrorSurfaced(e,t){const r=t.trim();if(!r)return;const n=this.surfacedRunErrorTexts.get(e);n?n.add(r):this.surfacedRunErrorTexts.set(e,new Set([r]))}sendRunErrorAsChunk(e,t,r,n=1,o){this.surfacedRunErrorTexts.get(e)?.has(r.trim())||(this.markRunErrorSurfaced(e,r),this.sendStreamChunkByRuntimeConfig(e,t,`
2
2
 
3
3
  Error: ${r}`,n,!1,o))}sendEventResultWithCleanup(e,t,r,n,o=!1){if(this.rejectedOutputEvents?.has(e))return;const s=this.blockedDispatchEvents?.get(e);this.blockedDispatchEvents?.delete(e),s&&t==="responded"&&(t="canceled",n=`agent_blocked_${s}`,r=`${s}: dispatch checkpoint saved; awaiting owner input`);const i=this.pool.getEventSessionId(e)??this.eventSessionIndex.get(e),a=r?.trim()??"";o&&this.markRunErrorSurfaced(e,a),t==="failed"&&i&&a&&this.sendRunErrorAsChunk(e,i,a);const l=t==="failed"&&a!==""&&(this.surfacedRunErrorTexts.get(e)?.has(a)??!1);if(this.auditController.markResponded(e,t,r),this.sendCtrl.finalizeOpenStreams(e),this.sendCtrl.sendEventResult(e,t,r,n,l),this.rejectedOutputEvents?.has(e))return;this.pool.cleanupEvent(e,i)===!1&&h.error(this.name,`Event terminal result could not release queue slot event=${e} session=${i??"-"} status=${t}`),i&&(this.pushQueueSnapshotForSession(i),this.conversationLog?.logResult?.(i,e,t,r)),this.eventSessionIndex.delete(e),this.inflightEvents.delete(e),this.restartCount.delete(e),this.surfacedRunErrorTexts.delete(e),this.pendingStartedEventIds.delete(e),this.pendingEvents.remove(e).catch(c=>{h.warn(this.name,`Failed to remove terminal event from pending store event=${e}: ${c instanceof Error?c.message:String(c)}`)}),t==="responded"&&(this.config.adapterType??"acp")!=="agy"&&(this.cachedProviderQuotaSampledAtMs=null,this.refreshAndPushProviderQuota(!0).catch(()=>{}))}async handleSessionInternalError(e){const{eventId:t,sessionId:r,errorMsg:n}=e;if(this.stopped||this.rejectedOutputEvents?.has(t))return;const o=this.inflightEvents.get(t);if(!o){h.warn(this.name,`[recovery] no inflight event for internalError event=${t} session=${r}; surface failure directly`),this.sendRunErrorAsChunk(t,r,n),this.sendEventResultWithCleanup(t,"failed",n,"agent_stop_failure");return}const s=(this.restartCount.get(t)??0)+1;this.restartCount.set(t,s);const i=this.config.adapterType??"acp";if(s>R){h.error(this.name,`[recovery] adapter=${i} session=${r} event=${t} restart=${s}/${R} outcome=give-up err=${n}`);const c=`${i} agent kept failing after ${R} automatic restarts: ${n}`;this.sendRunErrorAsChunk(t,r,c),this.sendEventResultWithCleanup(t,"failed",c,"agent_stop_failure");return}h.info(this.name,`[recovery] adapter=${i} session=${r} event=${t} restart=${s}/${R} 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||this.rejectedOutputEvents?.has(t)){for(const c of a)this.stopped||await this.pool.deliverInboundEvent(c);return}const l=e.replayOriginalContent?o.content:this.resolveRecoveryPrompt(i,o),d={...o,content:l};try{await this.pool.deliverInboundEvent(d)}catch(c){h.error(this.name,`[recovery] redeliver failed event=${t} session=${r}: ${c instanceof Error?c.message:String(c)}`),this.sendEventResultWithCleanup(t,"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,t){return e==="acp"?"continue":t.content}sendThinkingByRuntimeConfig(e,t,r){this.sendCtrl.sendThinking(e,t,r)}bufferStreamChunk(e,t,r,n,o){this.auditController.captureUnsequencedStreamChunk(e,r),this.sendCtrl.bufferOnly(e,t,r,n,o)}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(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 o=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(o),this.pendingStartedEventIds.has(o.event_id)||r.push(n)):(this.restorePendingReplayAuditTurn(o),this.deferredMgr.defer(n.channel,n.sessionId,o),r.push(n))}else await this.deliverPendingReplayEvent(o),this.pendingStartedEventIds.has(o.event_id)||r.push(n)}catch(s){const i=s instanceof Error?s.message:String(s);h.error(this.name,`Pending event replay failed event=${o.event_id}: ${i}`),this.sendEventResultWithCleanup(o.event_id,"failed",i),this.pendingEvents.markCanceled(o.event_id),await this.pendingEvents.remove(o.event_id).catch(()=>{})}finally{this.pendingEvents.finishReplay(n),await this.pendingEvents.checkpointReplay(t,[...r,...this.pendingEvents.replaySnapshot()])}if(this.stopped)break}this.stopped||(this.pendingEvents.finishAllReplay(),await this.pendingEvents.checkpointReplay(t,r))}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 r=wi({enabled:!0,scope:t.scope,profile:t.profile,capture:t.capture,...t.retentionDays===void 0?{}:{retentionDays:t.retentionDays}});if(!r.enabled)return;const n=Object.freeze({auditId:t.auditId,businessSessionId:e.session_id,provider:this.resolveAuditProvider(),options:r,createdAt:new Date().toISOString()}),o=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"}});o&&(e.audit={...t,auditId:o.auditId,turnId:o.turnId,profile:n.options.profile,capture:{...n.options.capture},rawProviderBody:n.options.capture.rawProviderBody})}indexEventSession(e,t){if(!e||!t)return;const r=this.eventSessionIndex.get(e);return r?(r!==t&&h.warn(this.name,`Ignoring event session mismatch event=${e} indexed=${r} supplied=${t}`),r):(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 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,t){return this.sendCtrl.shouldDropAcpRawDisplayEvent(e,t)}sendAcpRawEventEnvelope(e,t,r){this.shouldDropAcpRawDisplayEvent(e,r.type)||this.deliverRawEventEnvelope(e,t,r,"acp",this.buildAcpRawEventFallbackText(r))}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,r,n,o){const s=pi({envelope:r,fallbackText:o,channelKey:n,allocateRefId:()=>`${e}_rawd_${++this.rawDetailSeq}`}),i=()=>{this.aibotHandle.sendMsg({event_id:e,session_id:t,msg_type:1,content:s.fallbackText,extra:{channel_data:{[n]:{raw_event:s.envelope}},agent_api_origin:!0}})};if(!s.sharded){i();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,t,gi({envelopeType:r.type,field:a.field,fullText:a.fullText}),a.refClientMsgId);i()})().catch(a=>{h.warn("bridge",`${n} raw_event sharded delivery failed event=${e}: ${a}`)})}buildCursorRawEventFallbackText(e){const t=String(e?.type??"").trim(),r=e?.payload&&typeof e.payload=="object"?e.payload:{};switch(t){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 t?`[cursor] ${t}`:"[cursor] event"}}sendToolExecutionCard(e,t,r,n){this.sendCtrl.sendToolExecutionCard(e,t,r,n)}sendGrixApprovalCard(e,t){this.aibotHandle.sendMsg({event_id:e.eventId,session_id:e.sessionId,client_msg_id:`perm_${T()}`,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,r){const n=r.questions.map(s=>s.header).join(", "),o=x(`[Agent Question] ${r.request_id}`,"agent_question",r);this.aibotHandle.sendText({event_id:e,session_id:t,content:o,msg_type:1,extra:{card_type:"agent_question",summary_text:n}})}async handleAgentQuestionReplyEvent(e){const t=An(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 n=this.pool.getSlot(e.session_id)?.adapter,o=n instanceof S?"acp":n instanceof P?"opencode":this.config.adapterType??"unknown",s=n instanceof P?n.handleQuestionReplyEvent(t):n instanceof S?await n.handleQuestionReplyEvent(t):{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,`[${o}] 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()})):(h.warn(this.name,`[${o}] question reply rejected event=${e.event_id} session=${e.session_id} request=${t.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 t=bn(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 n=this.pool.getSlot(e.session_id)?.adapter,o=t.params,s=String(o.tool_call_id??o.approval_command_id??o.approval_id??o.exec_context_id??""),i=n?.handleExecApprovalEvent?await n.handleExecApprovalEvent({...o,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 i.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=${i.errorCode}`),this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",code:i.errorCode,msg:i.errorMsg,updated_at:Date.now()})),!0}async handleAibotEvent(e){if(this.rejectedOutputEvents?.has(e.event_id)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});return}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",r=Sn(e);if(t==="claude"&&this.sendCtrl.hasTerminalResult(e.event_id)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});return}let n;if(r&&(n=this.lifecycleBarrier.tryEnter(`session-control:${r.verb}`)??void 0,!n)){this.failEventIfLifecycleDraining(e);return}try{if(await this.handleCliInstallQuestionReply(e)||(t==="opencode"||t==="acp")&&await this.handleAgentQuestionReplyEvent(e)||await this.handleExecApprovalResolutionEvent(e))return;const o=ai(e.extra);if(o.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:o.error,updated_at:Date.now()});return}const s=o.patch,i=B(e.extra);if(En(this,e,t,i))return;if(r){await yn(this,r,e,t,i,this.config.agent.clientType??this.config.aibot.clientType);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 wn(this,e,t,Di.has(t),s,a))return;if((this.config.adapterType??"acp")==="acp"){const u=String(e.content??"").trim().match(/^\/(\S+)\s*(.*)/);if(u){const[,p,g]=u,A=this.pool.getSlot(e.session_id)?.adapter;if(A?.execCommand&&(A.getSupportedCommands?.()??[]).some(m=>m.name===p||m.name===`/${p}`)){this.aibotHandle.sendEventAck({event_id:e.event_id,session_id:e.session_id,received_at:Date.now()});try{const m=await A.execCommand(p,g.trim(),e.session_id);m.status==="options"&&m.data&&this.handleExecCommandOptions(e.session_id,p,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"&&Q(a?.options)){const c=this.pool.getSlot(e.session_id);if(c?.adapter instanceof H&&!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);d.attachments_json=await ei(d.attachments_json,{extraAllowedHosts:Xn(this.aibotConfig.url),logTag:this.name});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?.()}}handleStaleCwdError(e,t){if(!/CWD must be|Bound directory does not exist|Bound path is not a directory/i.test(t)||!e.session_id)return!1;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 n=this.pool.getSlot(e.session_id);n?.adapter instanceof S&&n.adapter.getSessionBindings().delete(e.session_id);const o=this.config.adapterType??"acp",s=this.resolveBindingChannelKey(o);return this.aibotHandle.sendMsg({event_id:e.event_id,session_id:e.session_id,msg_type:1,content:t,extra:{channel_data:{[s]:{sessionBinding:{status:"missing",reason:"binding_stale",error_code:E.invalidCwd}}}},quoted_message_id:e.msg_id}),!0}failUndeliveredInboundEvent(e,t){const r=t instanceof Error?t.message:String(t);h.warn(this.name,`Inbound event undelivered event=${e.event_id} session=${e.session_id}: ${r}`),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.handleStaleCwdError(e,r)&&this.aibotHandle.sendEventResult({event_id:e.event_id,status:"failed",msg:r,updated_at:Date.now()})}handleCodexSessionControlOpen(e,t){return rt(this,e,t)}handleSessionControlForPool(e,t){return at(this,e,t)}handleSessionControlLocalActionForPool(e){return dt(this,e)}handleCodexSessionControlLocalActionOpen(e){return lt(this,e)}handleCursorSessionControlLocalActionOpen(e){return ct(this,e)}handlePiSessionControlOpen(e,t){return ht(this,e,t)}handlePiSessionControlRestart(e){return ut(this,e)}handlePiSessionControlRestartLocalAction(e){return pt(this,e)}syncOpenCodeBinding(e,t){return gt(this,e,t)}isWorkspaceFreeClient(){return ft(this)}isCwdLockedClient(){return mt(this)}ensureDefaultBindingForWorkspaceFreeClient(e,t){return vt(this,e,t)}bindSessionForPool(e,t){return _t(this,e,t)}deferredCallbacks(){return St(this)}handleOpenHumanSessionControlOpen(e,t){return Ct(this,e,t)}handleCodeWhaleSessionControlOpen(e,t){return bt(this,e,t)}handleCodeWhaleSessionControlLocalActionOpen(e){return At(this,e)}handleDeepSeekSessionControlLocalActionOpen(e){return Et(this,e)}normalizeClaudeModeId(e){return Ut(this,e)}handleExecCommandOptions(e,t,r){qt(this,e,t,r)}resolveSessionModelId(e){return Wt(this,e)}resolveSessionModeId(e){return Nt(this,e)}resolveCursorSessionModeId(e){return jt(this,e)}resolveClaudeSessionEffort(e){return Gt(this,e)}resolveClaudeSessionModeId(e){return Kt(this,e)}currentClaudeModeId(e){return zt(this,e)}buildCursorToolbarMeta(e){return Jt(this,e)}buildAgyToolbarMeta(e,t){return Yt(this,e,t)}buildAgyQuotaMeta(e){return Vt(this,e)}sendAgyBindingCard(e,t,r){return Xt(this,e,t,r)}refreshAndPushAgyQuota(e,t=!1){return Zt(this,e,t)}handleAgySetModel(e,t){return en(this,e,t)}buildClaudeToolbarMeta(e){return tn(this,e)}providerQuotaToCodexRateLimits(e){return hi(e,this.cachedProviderQuotaSampledAtMs??Date.now())}providerQuotaToRateLimits(e){return ci(e,this.cachedProviderQuotaSampledAtMs??Date.now())}async resolveCwdForBinding(e){return jn(e)}failSessionOpen(e,t){return qn(this,e,t)}getClaudeWorkerStatus(e){return Wn(this,e)}refreshClaudeWorkerStatusCard(e,t){return Nn(this,e,t)}async ensureSlotStarted(e,t=6e4){return Un(this,e,t)}maybeOfferCliInstall(e){$e(this,e)}handleCliInstallQuestionReply(e){return He(this,e)}handleCliInstallInteractionReply(e){return De(this,e)}runConfirmedCliInstall(e,t){return Qe(this,e,t)}handleSkillDeleteLocalAction(e){return Tt(this,e)}handleSkillUploadLocalAction(e){return Pt(this,e)}handleSkillEnableLocalAction(e){return xt(this,e)}handleSkillRefreshLocalAction(e){Lt(this,e)}handleSkillDisableLocalAction(e){return Mt(this,e)}computeSkillReport(e){return $t(this,e)}reportSessionSkills(e){Ht(this,e)}skillsSyncGroupKey(){return Dt(this)}forceRefreshSkills(e,t){return Qt(this,e,t)}adoptSkillsWireHashFromDisk(){Ot(this)}buildLibrarySkillsReport(e){return It(this,e)}skillLookupEnv(){return Bt(this)}resolveOrphanTitle(e){return On(this,e)}resolveAgentSessionId(e){return Qn(this,e)}providerKeyForAdapter(){return Dn(this)}setResolvedAgentSessionId(e,t){In(this,e,t)}normalizePathForCompare(e){return Hn(e)}ensureImportedAgentSession(e,t){Mn(this,e,t)}buildOpenedBindingResult(e,t,r="ready"){return Ln(this,e,t,r)}buildDshOpenedToolbarMeta(e){return Bn(this,e)}dshCatalogDataRoot(){return Fn(this)}hasDiskScanner(){return $n(this)}unbindSession(e){return et(this,e)}handleUnbindTextCommand(e){return tt(this,e)}handleUnbindLocalAction(e){return nt(this,e)}handleListSessionsTextCommand(e){return it(this,e)}handleListSessionsLocalAction(e){return st(this,e)}handleSyncHistoryLocalAction(e){return ot(this,e)}handleSessionControlCommand(e,t){return Le(this,e,t)}handleSessionControlLocalAction(e){return Me(this,e)}handleEventCancel(e){return Oe(this,e)}waitForEventDone(e,t,r){return Ie(this,e,t,r)}handleAibotStop(e){Be(this,e)}killAndResumeStopSlot(e,t){return Fe(this,e,t)}handleAibotRevoke(e){return Ue(this,e)}handleConfigureGatewayProvider(e){return qe(this,e)}getAuditLocalActionHandler(){return We(this)}handleAuditLocalAction(e){return Ne(this,e)}handleConnectorRollback(e){return je(this,e)}getRelayStateSyncer(){return Ge(this)}relayStateSyncOnConnect(){Ke(this)}reportRelayStateLocalChange(){ze(this)}handleApplyRelayState(e){return Je(this,e)}fetchRelayCredential(e){return Ye(this,e)}handleConnectorAdminLocalAction(e){return Ze(this,e)}isSharedInstance(){return Ve(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??"",r=String((e.params??{}).session_id??""),n=String((e.params??{}).verb??"").trim().toLowerCase();h.debug(this.name,`local_action received action_type=${t} verb=${n||"-"} action_id=${e.action_id} session_id=${r}`);let o;if(t===f.sessionControl&&(o=this.lifecycleBarrier.tryEnter(`local-action:${n||t}`)??void 0,!o)){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===f.interactionReply&&await this.handleCliInstallInteractionReply(e))return;if(J(t)){await this.handleAuditLocalAction(e);return}const s=(this.config.adapterType??"acp")==="claude";if(t===f.sessionControl&&n===w.exec&&await this.handleSessionControlLocalAction(e))return;if(t===f.sessionControl&&n===w.listSessions){await this.handleListSessionsLocalAction(e);return}if(t===f.sessionControl&&n===w.syncHistory){await this.handleSyncHistoryLocalAction(e);return}if(t===f.sessionControl&&n===w.unbind){if(this.isCwdLockedClient()){this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:E.verbInvalid,error_msg:wt});return}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 i=(this.config.adapterType??"acp")==="opencode";if((s&&(t===f.interactionReply||t==="exec_approve"||t==="exec_reject")||i&&t===f.interactionReply)&&(await this.pool.deliverLocalAction(e)).handled||s&&await this.handleSessionControlLocalAction(e))return;if(t===f.sessionControl){await Rn(this,e,r);return}if(t==="file_list"){await Tn(this,e,r);return}if(t==="create_folder"){await kn(this,e,r);return}if(t===f.setModel&&(this.config.adapterType??"acp")==="agy"){await this.handleAgySetModel(e,r);return}if(t===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(t===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)&&t===f.threadCompact){await this.handleThreadCompact(e,r);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===f.getAgentGlobalConfig){const g=this.globalConfigStore?.get(this.name);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"ok",result:{agentName:this.name,...g?{config:g}:{config:null}}});return}if(t===Xe){await this.handleConnectorAdminLocalAction(e);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",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){xn(this,e,r,d,u);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:E.bindingMissing,error_msg:"Session binding missing. Open a workspace first."});return}if(d==="acp"&&(t==="set_mode"||t==="set_model")){await Pn(this,e,r,t);return}const p=!!r&&!!this.pool.getSlot(r);this.aibotHandle.sendLocalActionResult({action_id:e.action_id,status:"failed",error_code:"unsupported_local_action",error_msg:p?`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{o?.()}}handleGetSessionUsage(e,t){return Rt(this,e,t)}handleThreadCompact(e,t){return kt(this,e,t)}handleGetRateLimits(e,t){return gn(this,e,t)}resolveRateLimitWakeSessionId(e,t){return fn(this,e,t)}wakeRateLimitSlot(e,t){return mn(this,e,t)}sessionControlCtx(e){const t=this.pool.getSlot(e),r=t?.adapter instanceof S?t.adapter:null,n=(this.config.adapterType??"acp")==="acp",o={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 i=this.bindingStore.get(e);i?.cwd&&s.set(e,i.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,i)=>Kn(o,s,i):void 0,acpSetModel:n?(s,i)=>Gn(o,s,i):void 0,getPendingApproval:s=>{const i=r?.pendingApprovalEntries.get(s);return i?{requestId:i}:void 0},deletePendingApproval:s=>r?.pendingApprovalEntries.delete(s)??!1,respondPermission:(s,i)=>(r&&r.respondToPermission(s,i),Promise.resolve()),onSessionBound:(s,i)=>{this.bindingStore.set(s,i)},onSessionUnbound:s=>{this.unbindSession(s).catch(i=>{h.warn(this.name,`session unbind cleanup failed: ${i instanceof Error?i.message:String(i)}`)})},cancelActiveRun:()=>(this.config.adapterType??"acp")==="agy"&&t?.adapter instanceof D?(t.adapter.cancelCurrentRun(),Promise.resolve()):t?.adapter?.cancel("")??Promise.resolve(),onModeSet:s=>{O(this,this.config.adapterType??"acp",e,"mode",s)},onModelSet:s=>{O(this,this.config.adapterType??"acp",e,"model",s),this.refreshQuotaAfterModelSwitch(e,s)}}}sessionControlSenders(e){return{sendEventAck:(t,r)=>this.aibotHandle.sendEventAck({event_id:t,session_id:r,received_at:Date.now()}),sendEventResult:(t,r,n)=>this.aibotHandle.sendEventResult({event_id:t,status:r,...n?.msg?{msg:n.msg}:{},...n?.code?{code:n.code}:{},updated_at:Date.now()}),sendLocalActionResult:(t,r,n,o,s)=>this.aibotHandle.sendLocalActionResult({action_id:t,status:r,...n?{result:n}:{},...o?{error_code:o}:{},...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,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 r=t instanceof Error?t.message:String(t),n=(()=>{const a=B(e.extra);return a.options?.enabled===!0&&a.options.scope==="turn"})(),o=t instanceof Ei||t instanceof Ai,s=t instanceof Ri&&n,i=s?"audit_config_invalid":o?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:i,msg:r,updated_at:Date.now()}),o||s)try{this.aibotHandle.sendAuditState(I({state:"failed",eventId:e.event_id,sessionId:e.session_id,...e.msg_id===void 0?{}:{msgId:e.msg_id},errorCode:i,errorMessage:r},Date.now()))}catch{}}markAuditAdapterClosed(e,t){const n=this.pool.getSlot(t)?.adapter.takeAuditBoundary?.(e);this.auditController.markAdapterClosed(e,n)}prepareAuditedInboundEvent(e,t,r){const n=this.buildInboundEvent(e,t),o=this.bindingStore.get(e.session_id),s=o?this.resolveAgentSessionId(o):void 0,i=Number(e.created_at),a=Number.isFinite(i)&&i>0?new Date(i).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,t){const r=ri(this.sendCtrl.getGlobalRuntimeConfig(),t),n=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:n===void 0?void 0:JSON.stringify(n),attachments_json:Zn(e.attachments),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 t=e.filter(r=>!Cn(String(r?.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>Pi}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}setRemoteAdminPorts(e){this.remoteAdminPorts=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{yo as AgentInstance};
@@ -1 +1 @@
1
- import{sharedProviderQuotaService as Q,detectProviderFromModel as m,normalizeProviderId as P,readPiProviderSettings as x,readOpenCodeProviderSettings as A,isOpenaiCodexProviderName as T,queryOpenaiCodexQuota as S,openaiCodexQuotaCacheKey as $,resolveKimiProviderSettings as q,providerQuotaToRateLimits as R,providerQuotaToCodexRateLimits as H,providerQuotaToolbarExtras as E,resolveOpenCodeConsoleQuotaKey as O,OPENCODE_CONSOLE_ORIGIN as D}from"../core/provider-quota/index.js";import{queryKiroQuota as b}from"../core/provider-quota/kiro.js";import{queryGrixRelayWalletBalance as M}from"../core/provider-quota/grix-relay.js";import{DshJsonRpcAdapter as C,resolveDshHome as U,readDshCredentials as k}from"../adapter/deepseek-harness/index.js";import{readSettingsEnv as I}from"../adapter/claude/model-list.js";import{readCodexProviderSettings as L}from"../adapter/codex/codex-trust.js";import{agentIdOf as w}from"../adapter/shared/native-provider-config.js";import{log as u}from"../core/log/index.js";const K=30*1e3,B=10*1e3,J=["isRateLimitsCacheFresh","isGrixRelayActive","providerQuotaToRateLimits","resolveProviderQuotaSource","maybeQueryProviderQuota","stopProviderQuotaTimer","refreshAndPushProviderQuota","pushProviderQuotaToBindings","enrichProviderQuotaMeta","refreshProviderQuotaForSession","doRefreshQuotaAfterModelSwitch"],X=["name","config","stopped","aibotHandle","pool","bindingStore","sessionBindings","sessionProviderHints","sessionProviderQuotas","sessionProviderMeta","cachedAcpContextWindow","cachedProviderQuota","cachedProviderQuotaKey","cachedProviderQuotaSampledAtMs","providerQuotaTimer","lastModelSwitchQuotaRefresh"];async function Z(e,a){if(a?.disabled||a?.providerId==="openai_codex")return null;let o=e.config.providerBaseUrl??e.config.agent.provider?.baseUrl,n=e.config.providerApiKey??e.config.agent.provider?.apiKey;if((e.config.adapterType??"acp")==="deepseek-harness"){if(n??=e.config.agent.env?.DEEPSEEK_API_KEY,o??=e.config.agent.env?.DEEPSEEK_BASE_URL,!n){const r=U(typeof e.config.adapterOptions?.dshHome=="string"?e.config.adapterOptions.dshHome:void 0,e.config.agent.env);try{const i=await k(r),d=typeof i.DEEPSEEK_API_KEY=="string"?i.DEEPSEEK_API_KEY.trim():"";d&&(n=d,o??=typeof i.DEEPSEEK_BASE_URL=="string"&&i.DEEPSEEK_BASE_URL.trim()?i.DEEPSEEK_BASE_URL.trim():"https://api.deepseek.com",u.debug(e.name,"[provider-quota] deepseek-harness: resolved official DeepSeek API key from DSH credential store ($DSH_HOME)"))}catch(i){u.warn(e.name,`[provider-quota] deepseek-harness: could not read DSH credential store: ${i instanceof Error?i.message:String(i)}`)}}o??=n?"https://api.deepseek.com":void 0}if((!o||!n)&&(e.config.adapterType??"acp")==="claude"){const r=I();o||(o=(r.ANTHROPIC_BASE_URL??"").trim()||void 0),n||(n=(r.ANTHROPIC_API_KEY??"").trim()||(r.ANTHROPIC_AUTH_TOKEN??"").trim()||void 0)}if((!o||!n)&&(e.config.adapterType??"acp")==="codex"){const r=L();!o&&r.baseUrl&&(o=r.baseUrl),!n&&r.apiKey&&(n=r.apiKey)}if((!o||!n)&&(e.config.adapterType??"acp")==="acp"&&e.config.aibot.clientType==="kimi"){const r=await q();!o&&r.baseUrl&&(o=r.baseUrl),!n&&r.apiKey&&(n=r.apiKey)}if((!o||!n)&&(e.config.adapterType??"acp")==="pi"){const r=x(a,e.config.agent.env?.PI_CODING_AGENT_DIR);!o&&r.baseUrl&&(o=r.baseUrl),!n&&r.apiKey&&(n=r.apiKey)}if((!o||!n)&&(e.config.adapterType??"acp")==="opencode"){const r=A(a,void 0,w(e.config.agent.command||"opencode")||"opencode");!o&&r.baseUrl&&(o=r.baseUrl),!n&&r.apiKey&&(n=r.apiKey)}if((e.config.adapterType??"acp")==="opencode"){const r=P(a?.providerId);if(!r||r==="opencode_go"){const i=O({quotaApiKey:e.config.agent.provider?.quotaApiKey,envToken:e.config.agent.env?.OPENCODE_CONSOLE_TOKEN,providerApiKey:n,vendor:w(e.config.agent.command||"opencode")||"opencode"});if(i)return{baseUrl:D,apiKey:i,providerId:"opencode_go"}}}if(!o||!n)return null;const t=P(a?.providerId)??m(a?.model)?.id??P(e.config.agent.provider?.providerId)??m(e.config.agent.provider?.model)?.id;return{baseUrl:o,...e.config.agent.provider?.quotaBaseUrl?{quotaBaseUrl:e.config.agent.provider.quotaBaseUrl}:{},apiKey:n,...t?{providerId:t}:{}}}async function ee(e,a=!1,o){if(e.config.aibot.clientType==="kiro"){if(!a&&e.isRateLimitsCacheFresh(e.cachedProviderQuotaSampledAtMs)&&e.cachedProviderQuota)return e.cachedProviderQuota;try{const r=await b();return e.cachedProviderQuota=r,e.cachedProviderQuotaSampledAtMs=Date.now(),e.cachedProviderQuotaKey="kiro",u.info(e.name,`[provider-quota] kiro queried: success=${r.success}`+(r.balance?` balance=${r.balance.remaining} ${r.balance.unit}`:"")+(r.planName?` plan=${r.planName}`:"")+(r.error?` error=${r.error}`:"")),r}catch(r){return u.warn(e.name,`[provider-quota] kiro query failed: ${r instanceof Error?r.message:String(r)}`),null}}if((e.config.adapterType??"acp")==="claude"&&e.isGrixRelayActive()){if(!a&&e.cachedProviderQuotaKey==="grix-relay"&&e.isRateLimitsCacheFresh(e.cachedProviderQuotaSampledAtMs)&&e.cachedProviderQuota)return e.cachedProviderQuota;try{const r=await M({wsUrl:e.config.aibot.url,apiKey:e.config.aibot.apiKey});return r.success&&(e.cachedProviderQuota=r,e.cachedProviderQuotaSampledAtMs=Date.now(),e.cachedProviderQuotaKey="grix-relay"),u.info(e.name,`[provider-quota] grix-relay queried: success=${r.success}`+(r.balance?` balance=${r.balance.remaining} ${r.balance.unit}`:"")+(r.error?` error=${r.error}`:"")),r.success?r:null}catch(r){return u.warn(e.name,`[provider-quota] grix-relay query failed: ${r instanceof Error?r.message:String(r)}`),null}}if(o?.providerId==="openai_codex")try{const r=await S(e.config.agent.env?.PI_CODING_AGENT_DIR);return r.quota.success?r.quota:null}catch(r){return u.warn(e.name,`[provider-quota] openai_codex query failed: ${r instanceof Error?r.message:String(r)}`),null}const n=await e.resolveProviderQuotaSource(o);if(!n)return null;const t=Q.cacheKey(n);if(!a&&e.isRateLimitsCacheFresh(e.cachedProviderQuotaSampledAtMs)&&e.cachedProviderQuota&&e.cachedProviderQuotaKey===t)return e.cachedProviderQuota;try{const r=await Q.query(n,{fresh:a}),i=r.quota;return e.cachedProviderQuota=i,e.cachedProviderQuotaSampledAtMs=r.sampledAt,e.cachedProviderQuotaKey=r.cacheKey,u.info(e.name,`[provider-quota] queried: provider=${i.provider} success=${i.success}`+(i.tiers.length>0?` tiers=${i.tiers.map(d=>`${d.name}=${d.usedPercent}%`).join(",")}`:"")+(i.balance?` balance=${i.balance.remaining} ${i.balance.unit}`:"")+(i.error?` error=${i.error}`:"")),i}catch(r){return u.warn(e.name,`[provider-quota] query failed: ${r instanceof Error?r.message:String(r)}`),null}}function re(e){e.stopped||e.providerQuotaTimer||(e.providerQuotaTimer=setInterval(()=>{if(e.stopped){e.stopProviderQuotaTimer();return}e.refreshAndPushProviderQuota().catch(()=>{})},K),u.info(e.name,`[provider-quota-timer] started (interval=${K}ms)`))}function ie(e){e.providerQuotaTimer&&(clearInterval(e.providerQuotaTimer),e.providerQuotaTimer=null,u.info(e.name,"[provider-quota-timer] stopped"))}async function ae(e,a=!1){try{let o;if(e.config.aibot.clientType==="kiro")o=await b(),e.cachedProviderQuota=o,e.cachedProviderQuotaSampledAtMs=Date.now(),e.cachedProviderQuotaKey="kiro";else{const n=[...e.sessionBindings.entries()].filter(([t,r])=>!!r&&e.sessionProviderHints.has(t));if(n.length>0&&await Promise.all(n.map(([t,r])=>e.refreshProviderQuotaForSession(t,r,a))),n.length===e.sessionBindings.size&&n.length>0)return;o=await e.maybeQueryProviderQuota(a)}o?.success&&e.pushProviderQuotaToBindings(o,e.sessionProviderHints.size>0)}catch{}}function oe(e,a,o=!1){const n=(e.config.adapterType??"acp")==="claude"&&a.provider==="grix",t=e.providerQuotaToRateLimits(a);for(const[r,i]of e.sessionBindings.entries()){if(!i||o&&e.sessionProviderHints.has(r))continue;if((e.config.adapterType??"acp")==="deepseek-harness"){const p=e.pool.getSlot(r)?.adapter;if(p instanceof C){p.updateProviderQuotaSnapshot(a);continue}}const d={provider_quota:a};n?d.rate_limits=null:t&&(d.rate_limits=t),Object.assign(d,E(a));const c=e.cachedAcpContextWindow;c&&("usedPercentage"in c?d.context_window={usedPercentage:c.usedPercentage,remainingPercentage:100-c.usedPercentage}:d.context_window=c),e.aibotHandle.sendUpdateBindingCard({session_id:r,worker_status:"ready",cwd:i,meta:d})}}function ne(e,a,o="standard",n=e.cachedProviderQuota,t=e.cachedProviderQuotaSampledAtMs){const r={...a??{}};if(!n?.success||(r.provider_quota||(r.provider_quota=n),r.rate_limits))return r;if(o==="codex"){const c=H(n,t??Date.now());return c&&(r.rate_limits=c.rateLimits,r.rate_limit_primary_percent=c.primaryPercent,r.rate_limit_secondary_percent=c.secondaryPercent,r.rate_limit_primary_window_min=c.primaryWindowMin,r.rate_limit_secondary_window_min=c.secondaryWindowMin),r}const i=R(n,t??Date.now());i&&(r.rate_limits=i);const d=E(n);return d.credits&&r.credits===void 0&&(r.credits=d.credits),d.extra_limits&&r.extra_limits===void 0&&(r.extra_limits=d.extra_limits),r}function te(e,a,o,n){let t=e.cachedProviderQuota,r=e.cachedProviderQuotaSampledAtMs,i=!1;if(o){const c=typeof a?.model_provider=="string"?a.model_provider:void 0,p=typeof a?.model_id=="string"?a.model_id:void 0,v=P(c)??m(c)?.id??m(p)?.id??(T(c)?"openai_codex":null);if(v||p){const s=c?.trim().toLowerCase()??"",l=s==="grix"||s.startsWith("grix-"),g={...v?{providerId:v}:{},...p?{model:p}:{},...!!c&&!l&&!v?{disabled:!0}:{}},y=e.sessionProviderHints.get(o),_=y?.providerId!==g.providerId||y?.model!==g.model||y?.disabled!==g.disabled;e.sessionProviderHints.set(o,g),e.sessionProviderMeta.set(o,{...a??{}}),_&&e.sessionProviderQuotas.delete(o),(_||!e.sessionProviderQuotas.has(o))&&n&&e.refreshProviderQuotaForSession(o,n,!1)}const f=e.sessionProviderQuotas.get(o);i=e.sessionProviderHints.has(o),i&&(t=null,r=null),f&&(t=f.quota,r=f.sampledAt)}const d=e.enrichProviderQuotaMeta(a,"standard",t,r);return i&&(d.provider_quota||(d.provider_quota=null),d.rate_limits||(d.rate_limits=null)),Object.keys(d).length>0?{meta:d}:{}}async function de(e,a,o,n){const t=e.sessionProviderHints.get(a);if(!t)return;if(t.disabled){u.debug(e.name,`[provider-quota] session skip: session=${a} reason=hint_disabled providerId=${t.providerId??""} model=${t.model??""}`);return}const r=`${t.providerId??""}|${t.model??""}|false`;try{let i,d,c;if(t.providerId==="openai_codex"){const s=e.sessionProviderQuotas.get(a);if(!n&&s&&s.quota.success&&s.cacheKey.startsWith("openai_codex|")&&e.isRateLimitsCacheFresh(s.sampledAt))i=s.quota,d=s.sampledAt,c=s.cacheKey;else{const l=await S(e.config.agent.env?.PI_CODING_AGENT_DIR);i=l.quota,d=Date.now(),c=$(l.accountKey)}}else{const s=await e.resolveProviderQuotaSource(t);if(!s){u.debug(e.name,`[provider-quota] session skip: session=${a} reason=no_source providerId=${t.providerId??""} model=${t.model??""}`);return}const l=await Q.query(s,{fresh:n});i=l.quota,d=l.sampledAt,c=l.cacheKey}const p=e.sessionProviderHints.get(a);if(`${p?.providerId??""}|${p?.model??""}|${p?.disabled===!0}`!==r)return;if(u.info(e.name,`[provider-quota] queried: provider=${i.provider} success=${i.success}`+(i.tiers.length>0?` tiers=${i.tiers.map(s=>`${s.name}=${s.usedPercent}%`).join(",")}`:"")+(i.balance?` balance=${i.balance.remaining} ${i.balance.unit}`:"")+(i.error?` error=${i.error}`:"")+` session=${a}`),!i.success){const s=e.sessionProviderQuotas.get(a);(!s?.quota.success||s.cacheKey!==c)&&e.sessionProviderQuotas.delete(a);return}e.sessionProviderQuotas.set(a,{quota:i,sampledAt:d,cacheKey:c});const f=e.enrichProviderQuotaMeta(e.sessionProviderMeta.get(a),"standard",i,d);e.aibotHandle.sendUpdateBindingCard({session_id:a,worker_status:"ready",cwd:o,meta:f})}catch(i){u.warn(e.name,`[provider-quota] session query failed: session=${a} ${i instanceof Error?i.message:String(i)}`)}}function ce(e,a,o,n){const t=o.trim();if(!a||!t)return;const r=n?.trim()||void 0,i=`${a}|${r??""}|${t}`,d=Date.now();e.lastModelSwitchQuotaRefresh&&e.lastModelSwitchQuotaRefresh.key===i&&d-e.lastModelSwitchQuotaRefresh.at<B||(e.lastModelSwitchQuotaRefresh={key:i,at:d},e.doRefreshQuotaAfterModelSwitch(a,t,r).catch(c=>{u.warn(e.name,`[provider-quota] model-switch refresh failed: session=${a} model=${t} ${c instanceof Error?c.message:String(c)}`)}))}async function se(e,a,o,n){const t=e.sessionProviderHints.get(a);if(t||n){const i=n??m(o)?.id??t?.providerId,d={...i?{providerId:i}:{},model:o,...t?.disabled?{disabled:!0}:{}},c=t?.providerId!==d.providerId||t?.model!==d.model||t?.disabled!==d.disabled;e.sessionProviderHints.set(a,d),c&&e.sessionProviderQuotas.delete(a);const p=e.sessionBindings.get(a)??e.bindingStore.get(a)?.cwd??"";(c||!e.sessionProviderQuotas.has(a))&&p&&await e.refreshProviderQuotaForSession(a,p,!0);return}const r=await e.maybeQueryProviderQuota(!0,{model:o});r?.success&&e.pushProviderQuotaToBindings(r,e.sessionProviderHints.size>0)}export{X as PROVIDER_QUOTA_HOST_FIELDS,J as PROVIDER_QUOTA_HOST_METHODS,se as doRefreshQuotaAfterModelSwitch,ne as enrichProviderQuotaMeta,ee as maybeQueryProviderQuota,te as providerQuotaMetaPayload,oe as pushProviderQuotaToBindings,ae as refreshAndPushProviderQuota,de as refreshProviderQuotaForSession,ce as refreshQuotaAfterModelSwitch,Z as resolveProviderQuotaSource,re as startProviderQuotaTimer,ie as stopProviderQuotaTimer};
1
+ import{sharedProviderQuotaService as _,detectProviderFromModel as m,normalizeProviderId as g,readPiProviderSettings as x,readOpenCodeProviderSettings as q,isOpenaiCodexProviderName as O,queryOpenaiCodexQuota as S,openaiCodexQuotaCacheKey as $,resolveKimiProviderSettings as R,providerQuotaToRateLimits as H,providerQuotaToCodexRateLimits as C,providerQuotaToolbarExtras as E,resolveOpenCodeConsoleQuotaKey as b,OPENCODE_CONSOLE_ORIGIN as K}from"../core/provider-quota/index.js";import{queryKiroQuota as w}from"../core/provider-quota/kiro.js";import{queryGrixRelayWalletBalance as D}from"../core/provider-quota/grix-relay.js";import{DshJsonRpcAdapter as M,resolveDshHome as U,readDshCredentials as I}from"../adapter/deepseek-harness/index.js";import{readSettingsEnv as N}from"../adapter/claude/model-list.js";import{readCodexProviderSettings as k}from"../adapter/codex/codex-trust.js";import{agentIdOf as A}from"../adapter/shared/native-provider-config.js";import{log as p}from"../core/log/index.js";const T=30*1e3,L=10*1e3,X=["isRateLimitsCacheFresh","isGrixRelayActive","providerQuotaToRateLimits","resolveProviderQuotaSource","maybeQueryProviderQuota","stopProviderQuotaTimer","refreshAndPushProviderQuota","pushProviderQuotaToBindings","enrichProviderQuotaMeta","refreshProviderQuotaForSession","doRefreshQuotaAfterModelSwitch"],Z=["name","config","stopped","aibotHandle","pool","bindingStore","sessionBindings","sessionProviderHints","sessionProviderQuotas","sessionProviderMeta","cachedAcpContextWindow","cachedProviderQuota","cachedProviderQuotaKey","cachedProviderQuotaSampledAtMs","providerQuotaTimer","lastModelSwitchQuotaRefresh"];async function h(e,i){if(i?.disabled||i?.providerId==="openai_codex")return null;let o=e.config.providerBaseUrl??e.config.agent.provider?.baseUrl,n=e.config.providerApiKey??e.config.agent.provider?.apiKey;if((e.config.adapterType??"acp")==="deepseek-harness"){const r=U(typeof e.config.adapterOptions?.dshHome=="string"?e.config.adapterOptions.dshHome:void 0,e.config.agent.env);let a={};try{a=await I(r)}catch(t){p.warn(e.name,`[provider-quota] deepseek-harness: could not read DSH credential store: ${t instanceof Error?t.message:String(t)}`)}const c=t=>{const u=a[t];return typeof u=="string"?u.trim():""};if(g(i?.providerId)==="opencode_go"){const t=b({quotaApiKey:e.config.agent.provider?.quotaApiKey,envToken:e.config.agent.env?.OPENCODE_CONSOLE_TOKEN??e.config.agent.env?.OPENCODE_GO_API_KEY,providerApiKey:c("OPENCODE_GO_API_KEY")||c("OPENCODE_API_KEY")||n});return t?{baseUrl:K,apiKey:t,providerId:"opencode_go"}:null}if(n??=e.config.agent.env?.DEEPSEEK_API_KEY,o??=e.config.agent.env?.DEEPSEEK_BASE_URL,!n){const t=c("DEEPSEEK_API_KEY");t&&(n=t,o??=c("DEEPSEEK_BASE_URL")||"https://api.deepseek.com",p.debug(e.name,"[provider-quota] deepseek-harness: resolved official DeepSeek API key from DSH credential store ($DSH_HOME)"))}o??=n?"https://api.deepseek.com":void 0}if((!o||!n)&&(e.config.adapterType??"acp")==="claude"){const r=N();o||(o=(r.ANTHROPIC_BASE_URL??"").trim()||void 0),n||(n=(r.ANTHROPIC_API_KEY??"").trim()||(r.ANTHROPIC_AUTH_TOKEN??"").trim()||void 0)}if((!o||!n)&&(e.config.adapterType??"acp")==="codex"){const r=k();!o&&r.baseUrl&&(o=r.baseUrl),!n&&r.apiKey&&(n=r.apiKey)}if((!o||!n)&&(e.config.adapterType??"acp")==="acp"&&e.config.aibot.clientType==="kimi"){const r=await R();!o&&r.baseUrl&&(o=r.baseUrl),!n&&r.apiKey&&(n=r.apiKey)}if((!o||!n)&&(e.config.adapterType??"acp")==="pi"){const r=x(i,e.config.agent.env?.PI_CODING_AGENT_DIR);!o&&r.baseUrl&&(o=r.baseUrl),!n&&r.apiKey&&(n=r.apiKey)}if((!o||!n)&&(e.config.adapterType??"acp")==="opencode"){const r=q(i,void 0,A(e.config.agent.command||"opencode")||"opencode");!o&&r.baseUrl&&(o=r.baseUrl),!n&&r.apiKey&&(n=r.apiKey)}if((e.config.adapterType??"acp")==="opencode"){const r=g(i?.providerId);if(!r||r==="opencode_go"){const a=b({quotaApiKey:e.config.agent.provider?.quotaApiKey,envToken:e.config.agent.env?.OPENCODE_CONSOLE_TOKEN,providerApiKey:n,vendor:A(e.config.agent.command||"opencode")||"opencode"});if(a)return{baseUrl:K,apiKey:a,providerId:"opencode_go"}}}if(!o||!n)return null;const d=g(i?.providerId)??m(i?.model)?.id??g(e.config.agent.provider?.providerId)??m(e.config.agent.provider?.model)?.id;return{baseUrl:o,...e.config.agent.provider?.quotaBaseUrl?{quotaBaseUrl:e.config.agent.provider.quotaBaseUrl}:{},apiKey:n,...d?{providerId:d}:{}}}async function ee(e,i=!1,o){if(e.config.aibot.clientType==="kiro"){if(!i&&e.isRateLimitsCacheFresh(e.cachedProviderQuotaSampledAtMs)&&e.cachedProviderQuota)return e.cachedProviderQuota;try{const r=await w();return e.cachedProviderQuota=r,e.cachedProviderQuotaSampledAtMs=Date.now(),e.cachedProviderQuotaKey="kiro",p.info(e.name,`[provider-quota] kiro queried: success=${r.success}`+(r.balance?` balance=${r.balance.remaining} ${r.balance.unit}`:"")+(r.planName?` plan=${r.planName}`:"")+(r.error?` error=${r.error}`:"")),r}catch(r){return p.warn(e.name,`[provider-quota] kiro query failed: ${r instanceof Error?r.message:String(r)}`),null}}if((e.config.adapterType??"acp")==="claude"&&e.isGrixRelayActive()){if(!i&&e.cachedProviderQuotaKey==="grix-relay"&&e.isRateLimitsCacheFresh(e.cachedProviderQuotaSampledAtMs)&&e.cachedProviderQuota)return e.cachedProviderQuota;try{const r=await D({wsUrl:e.config.aibot.url,apiKey:e.config.aibot.apiKey});return r.success&&(e.cachedProviderQuota=r,e.cachedProviderQuotaSampledAtMs=Date.now(),e.cachedProviderQuotaKey="grix-relay"),p.info(e.name,`[provider-quota] grix-relay queried: success=${r.success}`+(r.balance?` balance=${r.balance.remaining} ${r.balance.unit}`:"")+(r.error?` error=${r.error}`:"")),r.success?r:null}catch(r){return p.warn(e.name,`[provider-quota] grix-relay query failed: ${r instanceof Error?r.message:String(r)}`),null}}if(o?.providerId==="openai_codex")try{const r=await S(e.config.agent.env?.PI_CODING_AGENT_DIR);return r.quota.success?r.quota:null}catch(r){return p.warn(e.name,`[provider-quota] openai_codex query failed: ${r instanceof Error?r.message:String(r)}`),null}const n=await e.resolveProviderQuotaSource(o);if(!n)return null;const d=_.cacheKey(n);if(!i&&e.isRateLimitsCacheFresh(e.cachedProviderQuotaSampledAtMs)&&e.cachedProviderQuota&&e.cachedProviderQuotaKey===d)return e.cachedProviderQuota;try{const r=await _.query(n,{fresh:i}),a=r.quota;return e.cachedProviderQuota=a,e.cachedProviderQuotaSampledAtMs=r.sampledAt,e.cachedProviderQuotaKey=r.cacheKey,p.info(e.name,`[provider-quota] queried: provider=${a.provider} success=${a.success}`+(a.tiers.length>0?` tiers=${a.tiers.map(c=>`${c.name}=${c.usedPercent}%`).join(",")}`:"")+(a.balance?` balance=${a.balance.remaining} ${a.balance.unit}`:"")+(a.error?` error=${a.error}`:"")),a}catch(r){return p.warn(e.name,`[provider-quota] query failed: ${r instanceof Error?r.message:String(r)}`),null}}function re(e){e.stopped||e.providerQuotaTimer||(e.providerQuotaTimer=setInterval(()=>{if(e.stopped){e.stopProviderQuotaTimer();return}e.refreshAndPushProviderQuota().catch(()=>{})},T),p.info(e.name,`[provider-quota-timer] started (interval=${T}ms)`))}function ie(e){e.providerQuotaTimer&&(clearInterval(e.providerQuotaTimer),e.providerQuotaTimer=null,p.info(e.name,"[provider-quota-timer] stopped"))}async function ae(e,i=!1){try{let o;if(e.config.aibot.clientType==="kiro")o=await w(),e.cachedProviderQuota=o,e.cachedProviderQuotaSampledAtMs=Date.now(),e.cachedProviderQuotaKey="kiro";else{const n=[...e.sessionBindings.entries()].filter(([d,r])=>!!r&&e.sessionProviderHints.has(d));if(n.length>0&&await Promise.all(n.map(([d,r])=>e.refreshProviderQuotaForSession(d,r,i))),n.length===e.sessionBindings.size&&n.length>0)return;o=await e.maybeQueryProviderQuota(i)}o?.success&&e.pushProviderQuotaToBindings(o,e.sessionProviderHints.size>0)}catch{}}function oe(e,i,o=!1){const n=(e.config.adapterType??"acp")==="claude"&&i.provider==="grix",d=e.providerQuotaToRateLimits(i);for(const[r,a]of e.sessionBindings.entries()){if(!a||o&&e.sessionProviderHints.has(r))continue;if((e.config.adapterType??"acp")==="deepseek-harness"){const u=e.pool.getSlot(r)?.adapter;if(u instanceof M){u.updateProviderQuotaSnapshot(i);continue}}const c={provider_quota:i};n?c.rate_limits=null:d&&(c.rate_limits=d),Object.assign(c,E(i));const t=e.cachedAcpContextWindow;t&&("usedPercentage"in t?c.context_window={usedPercentage:t.usedPercentage,remainingPercentage:100-t.usedPercentage}:c.context_window=t),e.aibotHandle.sendUpdateBindingCard({session_id:r,worker_status:"ready",cwd:a,meta:c})}}function ne(e,i,o="standard",n=e.cachedProviderQuota,d=e.cachedProviderQuotaSampledAtMs){const r={...i??{}};if(!n?.success||(r.provider_quota||(r.provider_quota=n),r.rate_limits))return r;if(o==="codex"){const t=C(n,d??Date.now());return t&&(r.rate_limits=t.rateLimits,r.rate_limit_primary_percent=t.primaryPercent,r.rate_limit_secondary_percent=t.secondaryPercent,r.rate_limit_primary_window_min=t.primaryWindowMin,r.rate_limit_secondary_window_min=t.secondaryWindowMin),r}const a=H(n,d??Date.now());a&&(r.rate_limits=a);const c=E(n);return c.credits&&r.credits===void 0&&(r.credits=c.credits),c.extra_limits&&r.extra_limits===void 0&&(r.extra_limits=c.extra_limits),r}function te(e,i,o,n){let d=e.cachedProviderQuota,r=e.cachedProviderQuotaSampledAtMs,a=!1;if(o){const t=typeof i?.model_provider=="string"?i.model_provider:typeof i?.provider_id=="string"?i.provider_id:void 0,u=typeof i?.model_id=="string"?i.model_id:void 0,v=g(t)??m(t)?.id??m(u)?.id??(O(t)?"openai_codex":null);if(v||u){const s=t?.trim().toLowerCase()??"",l=s==="grix"||s.startsWith("grix-"),P={...v?{providerId:v}:{},...u?{model:u}:{},...!!t&&!l&&!v?{disabled:!0}:{}},y=e.sessionProviderHints.get(o),Q=y?.providerId!==P.providerId||y?.model!==P.model||y?.disabled!==P.disabled;e.sessionProviderHints.set(o,P),e.sessionProviderMeta.set(o,{...i??{}}),Q&&e.sessionProviderQuotas.delete(o),(Q||!e.sessionProviderQuotas.has(o))&&n&&e.refreshProviderQuotaForSession(o,n,!1)}const f=e.sessionProviderQuotas.get(o);a=e.sessionProviderHints.has(o),a&&(d=null,r=null),f&&(d=f.quota,r=f.sampledAt)}const c=e.enrichProviderQuotaMeta(i,"standard",d,r);return a&&(c.provider_quota||(c.provider_quota=null),c.rate_limits||(c.rate_limits=null)),Object.keys(c).length>0?{meta:c}:{}}async function de(e,i,o,n){const d=e.sessionProviderHints.get(i);if(!d)return;if(d.disabled){p.debug(e.name,`[provider-quota] session skip: session=${i} reason=hint_disabled providerId=${d.providerId??""} model=${d.model??""}`);return}const r=`${d.providerId??""}|${d.model??""}|false`;try{let a,c,t;if(d.providerId==="openai_codex"){const s=e.sessionProviderQuotas.get(i);if(!n&&s&&s.quota.success&&s.cacheKey.startsWith("openai_codex|")&&e.isRateLimitsCacheFresh(s.sampledAt))a=s.quota,c=s.sampledAt,t=s.cacheKey;else{const l=await S(e.config.agent.env?.PI_CODING_AGENT_DIR);a=l.quota,c=Date.now(),t=$(l.accountKey)}}else{const s=await e.resolveProviderQuotaSource(d);if(!s){p.debug(e.name,`[provider-quota] session skip: session=${i} reason=no_source providerId=${d.providerId??""} model=${d.model??""}`);return}const l=await _.query(s,{fresh:n});a=l.quota,c=l.sampledAt,t=l.cacheKey}const u=e.sessionProviderHints.get(i);if(`${u?.providerId??""}|${u?.model??""}|${u?.disabled===!0}`!==r)return;if(p.info(e.name,`[provider-quota] queried: provider=${a.provider} success=${a.success}`+(a.tiers.length>0?` tiers=${a.tiers.map(s=>`${s.name}=${s.usedPercent}%`).join(",")}`:"")+(a.balance?` balance=${a.balance.remaining} ${a.balance.unit}`:"")+(a.error?` error=${a.error}`:"")+` session=${i}`),!a.success){const s=e.sessionProviderQuotas.get(i);(!s?.quota.success||s.cacheKey!==t)&&e.sessionProviderQuotas.delete(i);return}e.sessionProviderQuotas.set(i,{quota:a,sampledAt:c,cacheKey:t});const f=e.enrichProviderQuotaMeta(e.sessionProviderMeta.get(i),"standard",a,c);e.aibotHandle.sendUpdateBindingCard({session_id:i,worker_status:"ready",cwd:o,meta:f})}catch(a){p.warn(e.name,`[provider-quota] session query failed: session=${i} ${a instanceof Error?a.message:String(a)}`)}}function ce(e,i,o,n){const d=o.trim();if(!i||!d)return;const r=n?.trim()||void 0,a=`${i}|${r??""}|${d}`,c=Date.now();e.lastModelSwitchQuotaRefresh&&e.lastModelSwitchQuotaRefresh.key===a&&c-e.lastModelSwitchQuotaRefresh.at<L||(e.lastModelSwitchQuotaRefresh={key:a,at:c},e.doRefreshQuotaAfterModelSwitch(i,d,r).catch(t=>{p.warn(e.name,`[provider-quota] model-switch refresh failed: session=${i} model=${d} ${t instanceof Error?t.message:String(t)}`)}))}async function se(e,i,o,n){const d=e.sessionProviderHints.get(i);if(d||n){const a=n??m(o)?.id??d?.providerId,c={...a?{providerId:a}:{},model:o,...d?.disabled?{disabled:!0}:{}},t=d?.providerId!==c.providerId||d?.model!==c.model||d?.disabled!==c.disabled;e.sessionProviderHints.set(i,c),t&&e.sessionProviderQuotas.delete(i);const u=e.sessionBindings.get(i)??e.bindingStore.get(i)?.cwd??"";(t||!e.sessionProviderQuotas.has(i))&&u&&await e.refreshProviderQuotaForSession(i,u,!0);return}const r=await e.maybeQueryProviderQuota(!0,{model:o});r?.success&&e.pushProviderQuotaToBindings(r,e.sessionProviderHints.size>0)}export{Z as PROVIDER_QUOTA_HOST_FIELDS,X as PROVIDER_QUOTA_HOST_METHODS,se as doRefreshQuotaAfterModelSwitch,ne as enrichProviderQuotaMeta,ee as maybeQueryProviderQuota,te as providerQuotaMetaPayload,oe as pushProviderQuotaToBindings,ae as refreshAndPushProviderQuota,de as refreshProviderQuotaForSession,ce as refreshQuotaAfterModelSwitch,h as resolveProviderQuotaSource,re as startProviderQuotaTimer,ie as stopProviderQuotaTimer};
@@ -1 +1 @@
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};
1
+ function a(t){const o=new Set([`http://127.0.0.1:${t.serverPort}`,`http://localhost:${t.serverPort}`,...t.allowedOrigins]),e=new Set([`127.0.0.1:${t.serverPort}`,`localhost:${t.serverPort}`,...t.allowedHosts]);return{validateRequest(s){const r=i(s,o);if(!r.ok)return r;const n=l(s,e);return n.ok?{ok:!0}:n}}}function i(t,o){const e=t.headers.origin;return e?o.has(e)?{ok:!0}:{ok:!1,statusCode:403,message:`Origin not allowed: ${e}`}:{ok:!0}}function l(t,o){const e=t.headers.host;return e?o.has(e)?{ok:!0}:{ok:!1,statusCode:403,message:`Host not allowed: ${e}`}:{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.16.0",
3
+ "version": "4.16.1",
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",