grix-connector 4.3.0 → 4.3.2

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 A}from"node:child_process";import{createHash as R,randomUUID as V}from"node:crypto";import{closeSync as N,copyFileSync as p,cpSync as S,existsSync as d,mkdirSync as y,openSync as O,readFileSync as h,rmSync as f,statSync as m,writeFileSync as b}from"node:fs";import{join as o,resolve as I}from"node:path";import{fileURLToPath as D}from"node:url";import{promisify as G}from"node:util";import{log as C}from"../../core/log/index.js";import{resolveCliPath as B}from"../../core/util/cli-probe.js";import{bridgeDiscoveryDirectory as M,discoverDshBridgeEndpoints as T,resolveDshProfileIdentity as J}from"./profile-resolver.js";const L=G(A),F=2*1024*1024,u="@grix/dsh-bridge",z="deepseek-harness-bridge-installer",w=2,U=1e3;class se{options;command;identity;constructor(e={}){this.options=e,this.command=e.command?.trim()||"dsh",this.identity=J({dshHome:e.dshHome,profileName:e.profileName})}async status(){const e=await B(this.command),r=this.bridgeAsset(),t=this.readInstalledBridgeVersion(),n=r.version,s=T(this.identity),a=s[0]?.bridgeVersion??null,l=s[0]?.dshVersion??null,_=e?await j(e,this.options.dshHome):null;let c;return e?d(this.identity.profileRoot)?t?t!==n||this.installedBridgeContentStale(r)?c="bridge_update_required":s.length===0||a!==t||this.runningBridgePredatesInstalledContent(s[0])?c="profile_restart_required":c="ready":c="bridge_missing":c="profile_missing":c="dsh_missing",{readiness:c,command:this.command,commandPath:e,dshVersion:_,runningDshVersion:l,identity:this.identity,installedBridgeVersion:t,bundledBridgeVersion:n,runningBridgeVersion:a,endpointCount:s.length}}async install(){const e=await B(this.command);if(!e)throw Object.assign(new Error(`${this.command} not found`),{code:"dsh_missing"});const r=this.bridgeAsset();return E(this.identity,async()=>{await g(e,["--profile",this.identity.profileName,"--dump-config"],this.options.dshHome);const t=this.readInstalledBridgeVersion();if(t===r.version&&!this.installedBridgeContentStale(r))return this.status();const n=o(this.identity.dshHome,"assets","grix-dsh-bridge");y(n,{recursive:!0,mode:448});const s=this.captureInstallBackup(n,t),a=o(n,`grix-dsh-bridge-${r.version}.tgz`);p(r.tarball,a);try{if(t===r.version&&d(this.bridgePackageRoot())&&(await g(e,["plugin","--profile",this.identity.profileName,"remove",u],this.options.dshHome),d(this.bridgePackageRoot())))throw Object.assign(new Error(`dsh plugin remove left ${u} in place; refusing to attest an unverified reinstall`),{code:"bridge_install_failed"});await this.runPluginAdd(e,a),await g(e,["--profile",this.identity.profileName,"--dump-config"],this.options.dshHome);const l=this.readInstalledBridgeVersion();if(l!==r.version)throw Object.assign(new Error(`Bridge package did not land on disk (installed ${l??"none"}, expected ${r.version})`),{code:"bridge_install_failed"});this.writeInstalledBridgeIntegrity(r.integrity)}catch(l){await this.rollbackInstall(e,n,s,t);try{f(a,{force:!0})}catch{}throw Object.assign(new Error(`Bridge install failed: ${P(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 E(this.identity,async()=>(this.readInstalledBridgeVersion()&&await g(e,["plugin","--profile",this.identity.profileName,"remove",u],this.options.dshHome),this.status()))}async runPluginAdd(e,r){const t=["plugin","--profile",this.identity.profileName,"add",r];let n;for(let s=1;s<=w;s++)try{await g(e,t,this.options.dshHome);return}catch(a){n=a,C.warn(z,`dsh plugin add attempt ${s}/${w} failed for profile ${this.identity.profileName}
2
- ${X(a)}`),s<w&&await new Promise(l=>setTimeout(l,U))}throw n}bridgePackageRoot(){return o(this.identity.profileRoot,"node_modules","@grix","dsh-bridge")}profilePackageJsonPath(){return o(this.identity.profileRoot,"package.json")}captureInstallBackup(e,r){const t=o(e,"rollback",`${Date.now()}-${V()}`);y(t,{recursive:!0,mode:448});const n=this.bridgePackageRoot(),s=d(n);s&&S(n,o(t,"dsh-bridge"),{recursive:!0});const a=this.profilePackageJsonPath(),l=d(a);l&&p(a,o(t,"package.json"));const _=["pnpm-lock.yaml","package-lock.json","yarn.lock"];for(const c of _){const v=o(this.identity.profileRoot,c);d(v)&&p(v,o(t,c))}return b(o(t,"manifest.json"),`${JSON.stringify({priorVersion:r,hadBridge:s,hadPackageJson:l})}
3
- `,{mode:384}),{root:t,priorVersion:r,hadBridge:s,hadPackageJson:l}}async rollbackInstall(e,r,t,n){const s=n?o(r,`grix-dsh-bridge-${n}.tgz`):null;if(s&&d(s)&&await g(e,["plugin","--profile",this.identity.profileName,"add",s],this.options.dshHome).then(()=>!0).catch(()=>!1)){this.discardInstallBackup(t);return}if(t.hadBridge&&d(o(t.root,"dsh-bridge"))){this.restoreFilesystemBackup(t),this.discardInstallBackup(t);return}n?t.hadPackageJson&&this.restoreFilesystemBackup(t):(await g(e,["plugin","--profile",this.identity.profileName,"remove",u],this.options.dshHome).catch(()=>{}),this.cleanHalfInstalledBridge()),this.discardInstallBackup(t)}restoreFilesystemBackup(e){const r=this.bridgePackageRoot(),t=o(e.root,"dsh-bridge");e.hadBridge&&d(t)&&(f(r,{recursive:!0,force:!0}),y(o(this.identity.profileRoot,"node_modules","@grix"),{recursive:!0,mode:448}),S(t,r,{recursive:!0})),e.hadPackageJson&&d(o(e.root,"package.json"))&&p(o(e.root,"package.json"),this.profilePackageJsonPath());for(const n of["pnpm-lock.yaml","package-lock.json","yarn.lock"]){const s=o(e.root,n);d(s)&&p(s,o(this.identity.profileRoot,n))}}cleanHalfInstalledBridge(){try{f(this.bridgePackageRoot(),{recursive:!0,force:!0})}catch{}const e=this.profilePackageJsonPath();if(d(e))try{const r=JSON.parse(h(e,"utf8"));let t=!1;for(const n of["dependencies","devDependencies","optionalDependencies","peerDependencies"]){const s=r[n];s&&typeof s=="object"&&!Array.isArray(s)&&u in s&&(delete s[u],t=!0)}t&&b(e,`${JSON.stringify(r,null,2)}
1
+ import{execFile as V}from"node:child_process";import{createHash as N,randomUUID as O}from"node:crypto";import{closeSync as G,copyFileSync as p,cpSync as P,existsSync as d,mkdirSync as y,openSync as T,readFileSync as h,rmSync as f,statSync as m,writeFileSync as b}from"node:fs";import{join as o,resolve as I}from"node:path";import{fileURLToPath as D}from"node:url";import{promisify as C}from"node:util";import{log as $}from"../../core/log/index.js";import{resolveShimInvocation as M}from"../../core/runtime/spawn.js";import{resolveCliPath as B}from"../../core/util/cli-probe.js";import{bridgeDiscoveryDirectory as J,discoverDshBridgeEndpoints as L,resolveDshProfileIdentity as F}from"./profile-resolver.js";const z=C(V),U=2*1024*1024,u="@grix/dsh-bridge",x="deepseek-harness-bridge-installer",k=2,q=1e3;class oe{options;command;identity;constructor(e={}){this.options=e,this.command=e.command?.trim()||"dsh",this.identity=F({dshHome:e.dshHome,profileName:e.profileName})}async status(){const e=await B(this.command),r=this.bridgeAsset(),t=this.readInstalledBridgeVersion(),n=r.version,s=L(this.identity),a=s[0]?.bridgeVersion??null,l=s[0]?.dshVersion??null,_=e?await R(e,this.options.dshHome):null;let c;return e?d(this.identity.profileRoot)?t?t!==n||this.installedBridgeContentStale(r)?c="bridge_update_required":s.length===0||a!==t||this.runningBridgePredatesInstalledContent(s[0])?c="profile_restart_required":c="ready":c="bridge_missing":c="profile_missing":c="dsh_missing",{readiness:c,command:this.command,commandPath:e,dshVersion:_,runningDshVersion:l,identity:this.identity,installedBridgeVersion:t,bundledBridgeVersion:n,runningBridgeVersion:a,endpointCount:s.length}}async install(){const e=await B(this.command);if(!e)throw Object.assign(new Error(`${this.command} not found`),{code:"dsh_missing"});const r=this.bridgeAsset();return A(this.identity,async()=>{await g(e,["--profile",this.identity.profileName,"--dump-config"],this.options.dshHome);const t=this.readInstalledBridgeVersion();if(t===r.version&&!this.installedBridgeContentStale(r))return this.status();const n=o(this.identity.dshHome,"assets","grix-dsh-bridge");y(n,{recursive:!0,mode:448});const s=this.captureInstallBackup(n,t),a=o(n,`grix-dsh-bridge-${r.version}.tgz`);p(r.tarball,a);try{if(t===r.version&&d(this.bridgePackageRoot())&&(await g(e,["plugin","--profile",this.identity.profileName,"remove",u],this.options.dshHome),d(this.bridgePackageRoot())))throw Object.assign(new Error(`dsh plugin remove left ${u} in place; refusing to attest an unverified reinstall`),{code:"bridge_install_failed"});await this.runPluginAdd(e,a),await g(e,["--profile",this.identity.profileName,"--dump-config"],this.options.dshHome);const l=this.readInstalledBridgeVersion();if(l!==r.version)throw Object.assign(new Error(`Bridge package did not land on disk (installed ${l??"none"}, expected ${r.version})`),{code:"bridge_install_failed"});this.writeInstalledBridgeIntegrity(r.integrity)}catch(l){await this.rollbackInstall(e,n,s,t);try{f(a,{force:!0})}catch{}throw Object.assign(new Error(`Bridge install failed: ${w(l)}`),{code:"bridge_install_failed"})}return this.discardInstallBackup(s),this.status()})}async uninstall(){const e=await B(this.command);if(!e)throw Object.assign(new Error(`${this.command} not found`),{code:"dsh_missing"});return A(this.identity,async()=>(this.readInstalledBridgeVersion()&&await g(e,["plugin","--profile",this.identity.profileName,"remove",u],this.options.dshHome),this.status()))}async runPluginAdd(e,r){const t=["plugin","--profile",this.identity.profileName,"add",r];let n;for(let s=1;s<=k;s++)try{await g(e,t,this.options.dshHome);return}catch(a){n=a,$.warn(x,`dsh plugin add attempt ${s}/${k} failed for profile ${this.identity.profileName}
2
+ ${Y(a)}`),s<k&&await new Promise(l=>setTimeout(l,q))}throw n}bridgePackageRoot(){return o(this.identity.profileRoot,"node_modules","@grix","dsh-bridge")}profilePackageJsonPath(){return o(this.identity.profileRoot,"package.json")}captureInstallBackup(e,r){const t=o(e,"rollback",`${Date.now()}-${O()}`);y(t,{recursive:!0,mode:448});const n=this.bridgePackageRoot(),s=d(n);s&&P(n,o(t,"dsh-bridge"),{recursive:!0});const a=this.profilePackageJsonPath(),l=d(a);l&&p(a,o(t,"package.json"));const _=["pnpm-lock.yaml","package-lock.json","yarn.lock"];for(const c of _){const S=o(this.identity.profileRoot,c);d(S)&&p(S,o(t,c))}return b(o(t,"manifest.json"),`${JSON.stringify({priorVersion:r,hadBridge:s,hadPackageJson:l})}
3
+ `,{mode:384}),{root:t,priorVersion:r,hadBridge:s,hadPackageJson:l}}async rollbackInstall(e,r,t,n){const s=n?o(r,`grix-dsh-bridge-${n}.tgz`):null;if(s&&d(s)&&await g(e,["plugin","--profile",this.identity.profileName,"add",s],this.options.dshHome).then(()=>!0).catch(()=>!1)){this.discardInstallBackup(t);return}if(t.hadBridge&&d(o(t.root,"dsh-bridge"))){this.restoreFilesystemBackup(t),this.discardInstallBackup(t);return}n?t.hadPackageJson&&this.restoreFilesystemBackup(t):(await g(e,["plugin","--profile",this.identity.profileName,"remove",u],this.options.dshHome).catch(()=>{}),this.cleanHalfInstalledBridge()),this.discardInstallBackup(t)}restoreFilesystemBackup(e){const r=this.bridgePackageRoot(),t=o(e.root,"dsh-bridge");e.hadBridge&&d(t)&&(f(r,{recursive:!0,force:!0}),y(o(this.identity.profileRoot,"node_modules","@grix"),{recursive:!0,mode:448}),P(t,r,{recursive:!0})),e.hadPackageJson&&d(o(e.root,"package.json"))&&p(o(e.root,"package.json"),this.profilePackageJsonPath());for(const n of["pnpm-lock.yaml","package-lock.json","yarn.lock"]){const s=o(e.root,n);d(s)&&p(s,o(this.identity.profileRoot,n))}}cleanHalfInstalledBridge(){try{f(this.bridgePackageRoot(),{recursive:!0,force:!0})}catch{}const e=this.profilePackageJsonPath();if(d(e))try{const r=JSON.parse(h(e,"utf8"));let t=!1;for(const n of["dependencies","devDependencies","optionalDependencies","peerDependencies"]){const s=r[n];s&&typeof s=="object"&&!Array.isArray(s)&&u in s&&(delete s[u],t=!0)}t&&b(e,`${JSON.stringify(r,null,2)}
4
4
  `,{mode:384})}catch{}}discardInstallBackup(e){try{f(e.root,{recursive:!0,force:!0})}catch{}}readInstalledBridgeVersion(){const e=o(this.bridgePackageRoot(),"package.json");try{const r=JSON.parse(h(e,"utf8"));return typeof r.version=="string"?r.version:null}catch{return null}}installedIntegrityPath(){return o(this.bridgePackageRoot(),".grix-bridge-integrity")}readInstalledBridgeIntegrity(){try{const e=h(this.installedIntegrityPath(),"utf8").trim();return e.startsWith("sha512-")?e:null}catch{return null}}writeInstalledBridgeIntegrity(e){b(this.installedIntegrityPath(),`${e}
5
- `,{encoding:"utf8",mode:384})}installedBridgeContentStale(e=this.bridgeAsset()){return d(this.bridgePackageRoot())?this.readInstalledBridgeIntegrity()!==e.integrity:!0}runningBridgePredatesInstalledContent(e){try{const r=m(this.installedIntegrityPath()).mtimeMs,t=Date.parse(e.startedAt);return Number.isFinite(t)?r>t:!0}catch{return!1}}bridgeAsset(){return this.options.tarballPath?x(I(this.options.tarballPath)):$()}}function ne(i){if(i.readiness==="ready")return null;const e=i.identity.profileName,r=`dsh --profile ${e}`,t=i.endpointCount>0&&i.runningBridgeVersion&&i.installedBridgeVersion&&i.runningBridgeVersion!==i.installedBridgeVersion?`Grix Bridge in DSH profile "${e}" is running version ${i.runningBridgeVersion}, but ${i.installedBridgeVersion} is installed on disk. dsh does not hot-load plugin upgrades: stop the running profile process, then start it again with: ${r}`:`Grix Bridge is installed in DSH profile "${e}", but no live Bridge endpoint is available. dsh does not hot-load plugins: stop the running profile process, then start it again with: ${r}`,n={dsh_missing:"dsh is not installed or not on PATH. Install DeepSeek Harness (dsh), then retry.",profile_missing:`DSH profile "${e}" does not exist yet. Create/boot it once with: ${r}`,bridge_missing:`Grix Bridge is not installed in DSH profile "${e}". Install it from the DeepSeek Harness toolbar (or the dsh_install_bridge action), then restart the profile if it is already running.`,bridge_update_required:`Grix Bridge in DSH profile "${e}" needs an update (installed ${i.installedBridgeVersion??"none"}, expected ${i.bundledBridgeVersion}${i.installedBridgeVersion===i.bundledBridgeVersion?", content hash mismatch":""}). Update from the toolbar, then restart the profile \u2014 dsh does not hot-load plugin upgrades.`,profile_restart_required:t};return Object.assign(new Error(n[i.readiness]),{code:i.readiness})}function oe(){return $().tarball}function $(){const i=[D(new URL("../../assets/dsh-bridge/",import.meta.url)),D(new URL("../../../dist/assets/dsh-bridge/",import.meta.url))].find(t=>d(o(t,"manifest.json")));if(!i)throw Object.assign(new Error("Bundled Grix DSH Bridge asset is unavailable; run the Connector build first"),{code:"bridge_asset_missing"});const e=JSON.parse(h(o(i,"manifest.json"),"utf8"));if(typeof e.tarball!="string"||!e.tarball||typeof e.bridgeVersion!="string"||!e.bridgeVersion)throw Object.assign(new Error("Invalid Grix DSH Bridge asset manifest"),{code:"bridge_asset_invalid"});const r=x(o(i,e.tarball),e.bridgeVersion);if(Number(e.size)!==m(r.tarball).size)throw Object.assign(new Error("Grix DSH Bridge asset size mismatch"),{code:"bridge_asset_invalid"});if(typeof e.integrity=="string"&&e.integrity.startsWith("sha512-")&&e.integrity!==r.integrity)throw Object.assign(new Error("Grix DSH Bridge asset integrity mismatch"),{code:"bridge_asset_invalid"});return r}function x(i,e){if(!d(i)||!m(i).isFile())throw Object.assign(new Error(`Grix DSH Bridge asset is missing: ${i}`),{code:"bridge_asset_missing"});if(m(i).size>F)throw Object.assign(new Error("Grix DSH Bridge asset exceeds the 2 MiB safety limit"),{code:"bridge_asset_invalid"});const r=e??/grix-dsh-bridge-([0-9A-Za-z.+-]+)\.tgz$/.exec(i)?.[1];if(!r)throw Object.assign(new Error("Cannot determine Grix DSH Bridge version"),{code:"bridge_asset_invalid"});const t=`sha512-${R("sha512").update(h(i)).digest("base64")}`;return{tarball:i,version:r,integrity:t}}async function E(i,e){const r=M(i);y(r,{recursive:!0,mode:448});const t=o(r,"install.lock");let n=H(t);if(n===null){let s=0;try{s=Number(h(t,"utf8").trim())}catch{}let a=!1;try{a=s===0&&Date.now()-m(t).mtimeMs>5*6e4}catch{}if(a||Number.isSafeInteger(s)&&s>0&&!q(s)){try{f(t,{force:!0})}catch{}n=H(t)}}if(n===null)throw Object.assign(new Error(`Another Grix DSH Bridge install is active for profile ${i.profileName}`),{code:"bridge_install_busy"});try{return b(n,`${process.pid}
6
- `,"utf8"),await e()}finally{N(n);try{f(t,{force:!0})}catch{}}}function H(i){try{return O(i,"wx",384)}catch(e){if(e.code==="EEXIST")return null;throw Object.assign(new Error(`Cannot acquire Grix DSH Bridge install lock: ${P(e)}`),{code:"bridge_install_failed"})}}function q(i){try{return process.kill(i,0),!0}catch(e){return e.code==="EPERM"}}async function ae(i,e){const r=await B(i?.trim()||"dsh");return r?j(r,e):null}async function j(i,e){try{return(await g(i,["--version"],e)).trim().split(/\s+/)[0]||null}catch{return null}}async function g(i,e,r){try{return(await L(i,e,{env:{...process.env,...r?{DSH_HOME:I(r)}:{}},timeout:6e4,maxBuffer:8388608})).stdout}catch(t){const n=t&&typeof t=="object"?t:{};throw Object.assign(new Error(P(t)),{code:"dsh_command_failed",stderr:typeof n.stderr=="string"?k(n.stderr):void 0})}}function k(i){return i.replace(/(api[_-]?key|authorization|bearer)\s*[:=]\s*\S+/gi,"$1=[REDACTED]")}function P(i){const e=i&&typeof i=="object"?i:{};return k(String(e.stderr??e.message??i??"unknown error")).replace(/[\r\n]+/g," ").slice(0,1024)}function X(i){const e=i&&typeof i=="object"?i:{};return k(String(e.stderr??e.message??i??"unknown error")).slice(0,8*1024)}export{se as DshBridgeInstaller,oe as defaultBridgeTarball,ne as errorForDshBridgeReadiness,ae as readDshCliVersion};
5
+ `,{encoding:"utf8",mode:384})}installedBridgeContentStale(e=this.bridgeAsset()){return d(this.bridgePackageRoot())?this.readInstalledBridgeIntegrity()!==e.integrity:!0}runningBridgePredatesInstalledContent(e){try{const r=m(this.installedIntegrityPath()).mtimeMs,t=Date.parse(e.startedAt);return Number.isFinite(t)?r>t:!0}catch{return!1}}bridgeAsset(){return this.options.tarballPath?E(I(this.options.tarballPath)):H()}}function ae(i){if(i.readiness==="ready")return null;const e=i.identity.profileName,r=`dsh --profile ${e}`,t=`dsh does not hot-load plugin changes: stop the running profile process, then start it again with: ${r}`;let n;i.endpointCount===0?n=`Grix Bridge is installed in DSH profile "${e}", but no live Bridge endpoint is available. Start the profile with: ${r}`:i.runningBridgeVersion&&i.installedBridgeVersion&&i.runningBridgeVersion!==i.installedBridgeVersion?n=`Grix Bridge in DSH profile "${e}" is running version ${i.runningBridgeVersion}, but ${i.installedBridgeVersion} is installed on disk. ${t}`:n=`The live Grix Bridge in DSH profile "${e}" predates the Bridge content installed on disk. ${t}`;const s={dsh_missing:"dsh is not installed or not on PATH. Install DeepSeek Harness (dsh), then retry.",profile_missing:`DSH profile "${e}" does not exist yet. Create/boot it once with: ${r}`,bridge_missing:`Grix Bridge is not installed in DSH profile "${e}". Install it from the DeepSeek Harness toolbar (or the dsh_install_bridge action), then restart the profile if it is already running.`,bridge_update_required:`Grix Bridge in DSH profile "${e}" needs an update (installed ${i.installedBridgeVersion??"none"}, expected ${i.bundledBridgeVersion}${i.installedBridgeVersion===i.bundledBridgeVersion?", content hash mismatch":""}). Update from the toolbar, then restart the profile \u2014 dsh does not hot-load plugin upgrades.`,profile_restart_required:n};return Object.assign(new Error(s[i.readiness]),{code:i.readiness})}function de(){return H().tarball}function H(){const i=[D(new URL("../../assets/dsh-bridge/",import.meta.url)),D(new URL("../../../dist/assets/dsh-bridge/",import.meta.url))].find(t=>d(o(t,"manifest.json")));if(!i)throw Object.assign(new Error("Bundled Grix DSH Bridge asset is unavailable; run the Connector build first"),{code:"bridge_asset_missing"});const e=JSON.parse(h(o(i,"manifest.json"),"utf8"));if(typeof e.tarball!="string"||!e.tarball||typeof e.bridgeVersion!="string"||!e.bridgeVersion)throw Object.assign(new Error("Invalid Grix DSH Bridge asset manifest"),{code:"bridge_asset_invalid"});const r=E(o(i,e.tarball),e.bridgeVersion);if(Number(e.size)!==m(r.tarball).size)throw Object.assign(new Error("Grix DSH Bridge asset size mismatch"),{code:"bridge_asset_invalid"});if(typeof e.integrity=="string"&&e.integrity.startsWith("sha512-")&&e.integrity!==r.integrity)throw Object.assign(new Error("Grix DSH Bridge asset integrity mismatch"),{code:"bridge_asset_invalid"});return r}function E(i,e){if(!d(i)||!m(i).isFile())throw Object.assign(new Error(`Grix DSH Bridge asset is missing: ${i}`),{code:"bridge_asset_missing"});if(m(i).size>U)throw Object.assign(new Error("Grix DSH Bridge asset exceeds the 2 MiB safety limit"),{code:"bridge_asset_invalid"});const r=e??/grix-dsh-bridge-([0-9A-Za-z.+-]+)\.tgz$/.exec(i)?.[1];if(!r)throw Object.assign(new Error("Cannot determine Grix DSH Bridge version"),{code:"bridge_asset_invalid"});const t=`sha512-${N("sha512").update(h(i)).digest("base64")}`;return{tarball:i,version:r,integrity:t}}async function A(i,e){const r=J(i);y(r,{recursive:!0,mode:448});const t=o(r,"install.lock");let n=j(t);if(n===null){let s=0;try{s=Number(h(t,"utf8").trim())}catch{}let a=!1;try{a=s===0&&Date.now()-m(t).mtimeMs>5*6e4}catch{}if(a||Number.isSafeInteger(s)&&s>0&&!X(s)){try{f(t,{force:!0})}catch{}n=j(t)}}if(n===null)throw Object.assign(new Error(`Another Grix DSH Bridge install is active for profile ${i.profileName}`),{code:"bridge_install_busy"});try{return b(n,`${process.pid}
6
+ `,"utf8"),await e()}finally{G(n);try{f(t,{force:!0})}catch{}}}function j(i){try{return T(i,"wx",384)}catch(e){if(e.code==="EEXIST")return null;throw Object.assign(new Error(`Cannot acquire Grix DSH Bridge install lock: ${w(e)}`),{code:"bridge_install_failed"})}}function X(i){try{return process.kill(i,0),!0}catch(e){return e.code==="EPERM"}}async function le(i,e){const r=await B(i?.trim()||"dsh");return r?R(r,e):null}async function R(i,e){try{return(await g(i,["--version"],e)).trim().split(/\s+/)[0]||null}catch(r){return $.warn(x,`dsh --version \u63A2\u6D4B\u5931\u8D25\uFF08${i}\uFF09\uFF1A${w(r)}`),null}}async function g(i,e,r){try{const t=M(i,e);return(await z(t.command,t.args,{env:{...process.env,...r?{DSH_HOME:I(r)}:{}},timeout:6e4,maxBuffer:8*1024*1024,windowsVerbatimArguments:t.windowsVerbatimArguments})).stdout}catch(t){const n=t&&typeof t=="object"?t:{};throw Object.assign(new Error(w(t)),{code:"dsh_command_failed",stderr:typeof n.stderr=="string"?v(n.stderr):void 0})}}function v(i){return i.replace(/(api[_-]?key|authorization|bearer)\s*[:=]\s*\S+/gi,"$1=[REDACTED]")}function w(i){const e=i&&typeof i=="object"?i:{};return v(String(e.stderr??e.message??i??"unknown error")).replace(/[\r\n]+/g," ").slice(0,1024)}function Y(i){const e=i&&typeof i=="object"?i:{};return v(String(e.stderr??e.message??i??"unknown error")).slice(0,8*1024)}export{oe as DshBridgeInstaller,de as defaultBridgeTarball,ae as errorForDshBridgeReadiness,le as readDshCliVersion};
@@ -1 +1 @@
1
- import{existsSync as n}from"node:fs";import{execFile as i}from"node:child_process";import{promisify as a}from"node:util";import{resolveCliPath as c}from"../../core/util/cli-probe.js";import{assertSelectableDshProfileName as m,resolveDshHome as d,resolveDshProfileIdentity as l}from"./profile-resolver.js";const f=a(i),h="@deepseek-ai/dsh-web-app";async function g(e){const s=m(e.profileName),r=l({dshHome:e.dshHome,profileName:s});if(n(r.profileRoot))return{identity:r,created:!1};const o=e.run??p,t=e.run?e.command?.trim()||"dsh":await c(e.command?.trim()||"dsh");if(!t)throw Object.assign(new Error("dsh is not installed or not on PATH"),{code:"dsh_missing"});return await o(t,["plugin","--profile",s,"add",h],r.dshHome),{identity:r,created:!0}}async function p(e,s,r){try{return(await f(e,s,{env:{...process.env,...r?{DSH_HOME:d(r)}:{}},timeout:6e4,maxBuffer:8388608})).stdout}catch(o){const t=o&&typeof o=="object"?o:{};throw Object.assign(new Error(String(t.stderr??t.message??o??"unknown error").replace(/[\r\n]+/g," ").slice(0,1024)),{code:"dsh_command_failed"})}}export{g as createDshWebProfile,p as runDshCommand};
1
+ import{existsSync as n}from"node:fs";import{execFile as i}from"node:child_process";import{promisify as m}from"node:util";import{resolveCliPath as a}from"../../core/util/cli-probe.js";import{resolveShimInvocation as c}from"../../core/runtime/spawn.js";import{assertSelectableDshProfileName as d,resolveDshHome as l,resolveDshProfileIdentity as f}from"./profile-resolver.js";const h=m(i),p="@deepseek-ai/dsh-web-app";async function _(r){const s=d(r.profileName),o=f({dshHome:r.dshHome,profileName:s});if(n(o.profileRoot))return{identity:o,created:!1};const e=r.run??u,t=r.run?r.command?.trim()||"dsh":await a(r.command?.trim()||"dsh");if(!t)throw Object.assign(new Error("dsh is not installed or not on PATH"),{code:"dsh_missing"});return await e(t,["plugin","--profile",s,"add",p],o.dshHome),{identity:o,created:!0}}async function u(r,s,o){try{const e=c(r,s);return(await h(e.command,e.args,{env:{...process.env,...o?{DSH_HOME:l(o)}:{}},timeout:6e4,maxBuffer:8*1024*1024,windowsVerbatimArguments:e.windowsVerbatimArguments})).stdout}catch(e){const t=e&&typeof e=="object"?e:{};throw Object.assign(new Error(String(t.stderr??t.message??e??"unknown error").replace(/[\r\n]+/g," ").slice(0,1024)),{code:"dsh_command_failed"})}}export{_ as createDshWebProfile,u as runDshCommand};
@@ -1,2 +1,2 @@
1
- import{createWriteStream as k,existsSync as A,mkdirSync as K,readFileSync as C,renameSync as F,rmSync as H,writeFileSync as j}from"node:fs";import{join as R}from"node:path";import{log as d}from"../../core/log/index.js";import{resolveCliPath as G}from"../../core/util/cli-probe.js";import{killProcessGroup as B,spawnCommand as q}from"../../core/runtime/spawn.js";import{errorForDshBridgeReadiness as I}from"./bridge-installer.js";import{bridgeDiscoveryDirectory as N,discoverDshBridgeEndpoints as y,profileHasWebApp as U}from"./profile-resolver.js";const c="deepseek-harness-profile-supervisor",O=45e3,J=500;function W(e){return{...process.env,DSH_HOME:e}}const m=new Map,p=new Map;function $(e,r,i="coalesce"){const t=m.get(e.profileKey);if(t&&i==="coalesce")return t.promise;const o=(t?t.promise.catch(()=>{}).then(()=>r()):r()).finally(()=>{m.get(e.profileKey)?.promise===o&&m.delete(e.profileKey)});return m.set(e.profileKey,{promise:o}),o}async function ce(e){return $(e.installer.identity,()=>T(e))}async function fe(e){return $(e.installer.identity,()=>Y(e))}async function Y(e){const r=e.autoInstall!==!1;let i=await e.installer.status();return r&&["profile_missing","bridge_missing","bridge_update_required"].includes(i.readiness)&&(i=await e.installer.install()),i.readiness==="ready"&&!e.reloadManaged?i:T(e)}async function T(e){const r=e.installer,i=e.autoStart!==!1,t=e.readyTimeoutMs??O;let n=await r.status();if(e.reloadManaged&&(n=await z(r,n,t),n.readiness==="ready")||n.readiness==="ready")return n;if(!i){const l=I(n);if(l)throw l;return n}if(n.readiness==="profile_restart_required"&&n.endpointCount===0)await P(r,n.identity),n=await S(g,r,t),g(n)||await b(n.identity,"bridge endpoint did not appear");else if(n.readiness==="profile_restart_required"&&n.endpointCount>0&&n.runningBridgeVersion&&n.installedBridgeVersion){const l=y(n.identity),a=u(n.identity),w=a&&l.find(s=>s.pid===a.pid),M=n.runningBridgeVersion!==n.installedBridgeVersion?"bridge upgrade":"bridge content refresh";w&&a&&f(a.pid)?(d.info(c,`restarting connector-managed profile=${n.identity.profileName} pid=${a.pid} for ${M}`),await h(n.identity,a.pid)):d.info(c,`starting connector-managed profile=${n.identity.profileName} for ${M}; external profile processes are left untouched`),await P(r,n.identity),n=await S(g,r,t),g(n)||await b(n.identity,"bridge endpoint did not appear after upgrade restart")}if(n.readiness==="ready")return Q(n),n;const o=I(n);if(o)throw o;return n}async function z(e,r,i){const t=r.identity,n=u(t);if(!n||!f(n.pid))return r;const o=y(t);if(!o.some(w=>w.pid===n.pid)&&o.length>0)return r;d.info(c,`reloading connector-managed profile=${t.profileName} pid=${n.pid} after settings write`),await h(t,n.pid),await P(e,t);const a=await S(g,e,i);return g(a)||await b(t,"bridge endpoint did not appear after settings reload"),a}function Q(e){d.info(c,`bridge ready profile=${e.identity.profileName} endpoints=${e.endpointCount} bridge=${e.runningBridgeVersion}`)}async function P(e,r){const i=u(r);if(i&&f(i.pid)){if(y(r).some(x=>x.pid===i.pid)){d.info(c,`reusing connector-managed profile=${r.profileName} pid=${i.pid}`);return}d.warn(c,`restarting stuck connector-managed profile=${r.profileName} pid=${i.pid} (alive without endpoint)`),await h(r,i.pid)}else i&&D(r);const t=await G(e.command);if(!t)throw Object.assign(new Error("dsh is not installed or not on PATH"),{code:"dsh_missing"});const n=X(r),o=N(r);K(o,{recursive:!0,mode:448});const l=R(o,"managed-profile.log"),a=k(l,{flags:"a",mode:384}),w=W(r.dshHome),s=q(t,n,{cwd:r.profileRoot,env:w,stdio:["ignore","pipe","pipe"],detached:!0}).process;if(!s.pid)throw a.end(),Object.assign(new Error(`Failed to start DSH profile "${r.profileName}"`),{code:"profile_start_failed"});s.stdout?.pipe(a,{end:!1}),s.stderr?.pipe(a,{end:!1}),s.once("exit",(E,v)=>{d.warn(c,`managed profile exited profile=${r.profileName} pid=${s.pid} code=${E} signal=${v}`),p.get(r.profileKey)===s&&p.delete(r.profileKey),u(r)?.pid===s.pid&&D(r);try{a.end()}catch{}}),s.unref(),p.set(r.profileKey,s),Z(r,{schemaVersion:1,profileKey:r.profileKey,profileName:r.profileName,pid:s.pid,startedAt:new Date().toISOString(),command:t,args:n}),d.info(c,`started connector-managed profile=${r.profileName} pid=${s.pid} args=${n.join(" ")}`)}async function b(e,r){const i=u(e);i&&(d.warn(c,`stopping stuck connector-managed profile=${e.profileName} pid=${i.pid} reason=${r}`),await h(e,i.pid))}async function h(e,r){const i=p.get(e.profileKey);if(i?.pid===r){try{B(i,"SIGTERM")}catch{}p.delete(e.profileKey)}else if(f(r))try{process.kill(r,"SIGTERM")}catch{}const t=Date.now()+5e3;for(;Date.now()<t&&f(r);)await V(100);if(f(r))try{process.kill(r,"SIGKILL")}catch{}D(e)}function X(e){return U(e.profileRoot,e.profileName)?["--profile",e.profileName,"--port","0"]:["--profile",e.profileName]}async function S(e,r,i){const t=Date.now()+i;let n=await r.status();for(;Date.now()<t;){if(e(n))return n;const o=u(r.identity);if(o&&!f(o.pid))throw D(r.identity),Object.assign(new Error(`Connector-managed DSH profile "${r.identity.profileName}" exited before Bridge became ready`),{code:"profile_start_failed"});await V(J),n=await r.status()}return n}function _(e){return R(N(e),"managed-profile.json")}function u(e){try{const r=JSON.parse(C(_(e),"utf8"));return r.schemaVersion!==1||typeof r.pid!="number"||r.profileKey!==e.profileKey?null:r}catch{return null}}function Z(e,r){const i=N(e);K(i,{recursive:!0,mode:448});const t=_(e),n=`${t}.${process.pid}.tmp`;j(n,`${JSON.stringify(r,null,2)}
2
- `,{mode:384}),F(n,t)}function D(e){try{H(_(e),{force:!0})}catch{}}function f(e){try{return process.kill(e,0),!0}catch(r){return r.code==="EPERM"}}function V(e){return new Promise(r=>setTimeout(r,e))}function le(){m.clear();for(const e of p.values())try{e.pid&&B(e,"SIGKILL")}catch{}p.clear()}function pe(e){return A(_(e))}async function ue(e){const r=m.get(e.profileKey);r&&await r.promise.catch(()=>{})}async function ge(e,r=O){let i="failed";return await $(e.identity,async()=>(i=await ee(e,r),L(e,i==="restarted"?"ready":"profile_restart_required")),"queue"),i}async function ee(e,r){const i=e.identity,t=u(i);if(!t||!f(t.pid))return"not_managed";const n=y(i);if(n.length>0&&!n.some(o=>o.pid===t.pid))return"not_managed";try{return d.info(c,`restarting connector-managed profile=${i.profileName} pid=${t.pid} for plugin toggle`),await h(i,t.pid),await P(e,i),(await S(g,e,r)).readiness==="ready"?"restarted":"failed"}catch(o){return d.warn(c,`plugin-toggle restart failed profile=${i.profileName}: ${o instanceof Error?o.message:String(o)}`),"failed"}}function g(e){return e.readiness==="ready"}function me(e,r){return $(e.identity,async()=>(await r,L(e,"ready")))}function L(e,r){return{readiness:r,command:e.command,commandPath:null,dshVersion:null,runningDshVersion:null,identity:e.identity,installedBridgeVersion:null,bundledBridgeVersion:"",runningBridgeVersion:null,endpointCount:0}}export{ue as awaitDshProfileIdle,X as buildDshProfileBootArgs,ce as ensureDshBridgeReady,me as holdDshProfileInflightForTests,pe as managedProfileRecordExists,W as managedProfileSpawnEnv,fe as prepareDshProfileBridge,le as resetDshProfileSupervisorForTests,ge as restartManagedProfileIfOwned};
1
+ import{createWriteStream as H,existsSync as j,mkdirSync as v,readFileSync as U,renameSync as q,rmSync as J,writeFileSync as W}from"node:fs";import{join as K}from"node:path";import{log as d}from"../../core/log/index.js";import{resolveCliPath as Y}from"../../core/util/cli-probe.js";import{killProcessGroup as O,spawnCommand as z}from"../../core/runtime/spawn.js";import{errorForDshBridgeReadiness as A}from"./bridge-installer.js";import{bridgeDiscoveryDirectory as M,discoverDshBridgeEndpoints as g,profileHasWebApp as Q}from"./profile-resolver.js";const c="deepseek-harness-profile-supervisor",I=45e3,T=5*6e4,X=500;function Z(e){return{...process.env,DSH_HOME:e}}const w=new Map,m=new Map;function $(e,r,n="coalesce"){const t=w.get(e.profileKey);if(t&&n==="coalesce")return t.promise;const i=(t?t.promise.catch(()=>{}).then(()=>r()):r()).finally(()=>{w.get(e.profileKey)?.promise===i&&w.delete(e.profileKey)});return w.set(e.profileKey,{promise:i}),i}async function $e(e){return $(e.installer.identity,()=>F(e))}async function Pe(e){return $(e.installer.identity,()=>ee(e))}async function ee(e){const r=e.autoInstall!==!1;let n=await e.installer.status();return r&&["profile_missing","bridge_missing","bridge_update_required"].includes(n.readiness)&&(n=await e.installer.install()),n.readiness==="ready"&&!e.reloadManaged?(E(n.identity),n):F(e)}async function F(e){const r=e.installer,n=e.autoStart!==!1,t=e.readyTimeoutMs??I,o=e.bootGraceMs??T;let i=await r.status();if(e.reloadManaged&&(i=await re(r,i,t,o)),i.readiness==="ready")return E(i.identity),i;if(!n){const a=A(i);if(a)throw a;return i}if(i.readiness==="profile_restart_required"&&(i.endpointCount>0&&await ne(i),await _(r,i.identity,o),i=await N(r,t),S(i)||await L(i.identity,o,"bridge endpoint did not appear")),i.readiness==="ready")return te(i),i;const s=A(i);if(s)throw s;return i}async function re(e,r,n,t){const o=r.identity,i=p(o);if(!i||!l(i.pid))return r;const s=g(o);if(!s.some(D=>y(i,D))&&s.length>0)return r;d.info(c,`reloading connector-managed profile=${o.profileName} pid=${i.pid} after settings write`),await h(o,i.pid),await _(e,o,t);const u=await N(e,n);return S(u)||await L(o,t,"bridge endpoint did not appear after settings reload"),u}async function ne(e){const r=e.identity,n=p(r),t=g(r),o=e.runningBridgeVersion&&e.installedBridgeVersion&&e.runningBridgeVersion!==e.installedBridgeVersion?"bridge upgrade":"bridge content refresh";if(n&&l(n.pid)&&t.some(i=>y(n,i))){d.info(c,`restarting connector-managed profile=${r.profileName} pid=${n.pid} for ${o}`),await h(r,n.pid);return}d.info(c,`starting connector-managed profile=${r.profileName} for ${o}; external profile processes are left untouched`)}async function N(e,r){const n=await se(S,e,r);return S(n)&&E(e.identity),n}async function L(e,r,n){const t=de(e,r);if(t)throw d.info(c,`managed profile=${e.profileName} pid=${t.pid} still booting; left running (${n})`),ie(e,t);await oe(e,n)}function ie(e,r){return Object.assign(new Error(`DSH profile "${e.profileName}" is still starting (pid ${r.pid}); a first boot installs the profile dependencies before Grix Bridge can listen. The Connector keeps it running \u2014 send the message again in a moment and it will attach automatically.`),{code:"profile_starting"})}function te(e){d.info(c,`bridge ready profile=${e.identity.profileName} endpoints=${e.endpointCount} bridge=${e.runningBridgeVersion}`)}async function _(e,r,n){const t=p(r);if(t&&l(t.pid)){if(g(r).some(x=>y(t,x))){d.info(c,`reusing connector-managed profile=${r.profileName} pid=${t.pid}`);return}if(k(t,n)){d.info(c,`waiting on booting connector-managed profile=${r.profileName} pid=${t.pid}`);return}d.warn(c,`restarting stuck connector-managed profile=${r.profileName} pid=${t.pid} (alive without endpoint)`),await h(r,t.pid)}else t&&b(r);const o=await Y(e.command);if(!o)throw Object.assign(new Error("dsh is not installed or not on PATH"),{code:"dsh_missing"});const i=ae(r),s=M(r);v(s,{recursive:!0,mode:448});const a=K(s,"managed-profile.log"),u=H(a,{flags:"a",mode:384}),D=Z(r.dshHome),f=z(o,i,{cwd:r.profileRoot,env:D,stdio:["ignore","pipe","pipe"],detached:process.platform!=="win32"}).process;if(!f.pid)throw u.end(),Object.assign(new Error(`Failed to start DSH profile "${r.profileName}"`),{code:"profile_start_failed"});f.stdout?.pipe(u,{end:!1}),f.stderr?.pipe(u,{end:!1}),f.once("exit",(B,R)=>{d.warn(c,`managed profile exited profile=${r.profileName} pid=${f.pid} code=${B} signal=${R}`),m.get(r.profileKey)===f&&m.delete(r.profileKey),p(r)?.pid===f.pid&&b(r);try{u.end()}catch{}}),f.unref(),m.set(r.profileKey,f),V(r,{schemaVersion:1,profileKey:r.profileKey,profileName:r.profileName,pid:f.pid,startedAt:new Date().toISOString(),command:o,args:i}),d.info(c,`started connector-managed profile=${r.profileName} pid=${f.pid} args=${i.join(" ")}`)}async function oe(e,r){const n=p(e);n&&(d.warn(c,`stopping stuck connector-managed profile=${e.profileName} pid=${n.pid} reason=${r}`),await h(e,n.pid))}async function h(e,r){const n=p(e)?.endpointPid,t=n&&n!==r&&g(e).some(a=>a.pid===n)?n:null,o=t?[r,t]:[r],i=m.get(e.profileKey);if(i?.pid===r){try{O(i,"SIGTERM")}catch{}m.delete(e.profileKey)}else for(const a of o)if(l(a))try{process.kill(a,"SIGTERM")}catch{}const s=Date.now()+5e3;for(;Date.now()<s&&o.some(l);)await G(100);for(const a of o)if(l(a))try{process.kill(a,"SIGKILL")}catch{}b(e)}function ae(e){return Q(e.profileRoot,e.profileName)?["--profile",e.profileName,"--port","0"]:["--profile",e.profileName]}async function se(e,r,n){const t=Date.now()+n;let o=await r.status();for(;Date.now()<t;){if(e(o))return o;const i=p(r.identity);if(i&&!l(i.pid))throw b(r.identity),Object.assign(new Error(`Connector-managed DSH profile "${r.identity.profileName}" exited before Bridge became ready`),{code:"profile_start_failed"});await G(X),o=await r.status()}return o}function P(e){return K(M(e),"managed-profile.json")}function p(e){try{const r=JSON.parse(U(P(e),"utf8"));return r.schemaVersion!==1||typeof r.pid!="number"||r.profileKey!==e.profileKey?null:r}catch{return null}}function V(e,r){const n=M(e);v(n,{recursive:!0,mode:448});const t=P(e),o=`${t}.${process.pid}.tmp`;W(o,`${JSON.stringify(r,null,2)}
2
+ `,{mode:384}),q(o,t)}function y(e,r){return r.pid===e.pid||r.pid===e.endpointPid}function k(e,r){const n=Date.parse(e.startedAt);return Number.isFinite(n)?Date.now()-n<r:!1}function de(e,r){const n=p(e);return!n||!l(n.pid)||g(e).some(t=>y(n,t))?null:k(n,r)?n:null}function E(e){const r=p(e);if(!r||typeof r.endpointPid=="number"||!l(r.pid))return;const n=g(e);if(n.some(s=>s.pid===r.pid))return;const t=Date.parse(r.startedAt);if(!Number.isFinite(t))return;const o=n.filter(s=>{const a=Date.parse(s.startedAt);return Number.isFinite(a)&&a>=t});if(o.length!==1)return;const i=o[0];V(e,{...r,endpointPid:i.pid}),d.info(c,`adopted managed bridge endpoint profile=${e.profileName} wrapper=${r.pid} pid=${i.pid}`)}function b(e){try{J(P(e),{force:!0})}catch{}}function l(e){try{return process.kill(e,0),!0}catch(r){return r.code==="EPERM"}}function G(e){return new Promise(r=>setTimeout(r,e))}function be(){w.clear();for(const e of m.values())try{e.pid&&O(e,"SIGKILL")}catch{}m.clear()}function Se(e){return j(P(e))}async function De(e){const r=w.get(e.profileKey);r&&await r.promise.catch(()=>{})}async function Me(e,r=I){let n="failed";return await $(e.identity,async()=>(n=await ce(e,r),C(e,n==="restarted"?"ready":"profile_restart_required")),"queue"),n}async function ce(e,r){const n=e.identity,t=p(n);if(!t||!l(t.pid))return"not_managed";const o=g(n);if(o.length>0&&!o.some(i=>y(t,i)))return"not_managed";try{return d.info(c,`restarting connector-managed profile=${n.profileName} pid=${t.pid} for plugin toggle`),await h(n,t.pid),await _(e,n,T),(await N(e,r)).readiness==="ready"?"restarted":"failed"}catch(i){return d.warn(c,`plugin-toggle restart failed profile=${n.profileName}: ${i instanceof Error?i.message:String(i)}`),"failed"}}function S(e){return e.readiness==="ready"}function Ne(e,r){return $(e.identity,async()=>(await r,C(e,"ready")))}function C(e,r){return{readiness:r,command:e.command,commandPath:null,dshVersion:null,runningDshVersion:null,identity:e.identity,installedBridgeVersion:null,bundledBridgeVersion:"",runningBridgeVersion:null,endpointCount:0}}export{De as awaitDshProfileIdle,ae as buildDshProfileBootArgs,$e as ensureDshBridgeReady,Ne as holdDshProfileInflightForTests,Se as managedProfileRecordExists,Z as managedProfileSpawnEnv,Pe as prepareDshProfileBridge,be as resetDshProfileSupervisorForTests,Me as restartManagedProfileIfOwned};
@@ -1,7 +1,7 @@
1
- import{execFile as b}from"node:child_process";import{promisify as w}from"node:util";import{EventEmitter as I}from"node:events";import{stat as $}from"node:fs/promises";import{mkdirSync as T,writeFileSync as A,unlinkSync as k,statSync as f,readFileSync as R,existsSync as C}from"node:fs";import{join as m,resolve as M}from"node:path";import{fileURLToPath as F}from"node:url";import{tmpdir as B,homedir as g}from"node:os";import{resolveCommandPath as D,spawnCommand as N,killProcessGroup as E,hasChildProcesses as G}from"../../core/runtime/spawn.js";import{InternalApiServer as L}from"../../core/mcp/internal-api-server.js";import{IdentityInjector as O}from"../shared/identity-injector.js";import{compactToolInputForWire as j}from"../shared/tool-wire-payload.js";import{syncDefaultSkillsToDir as q}from"../../default-skills/index.js";import{PiTransport as U}from"./pi-transport.js";import{log as a}from"../../core/log/index.js";import{scanSkills as z}from"../claude/skill-scanner.js";import{SessionBindingStore as H}from"../../core/persistence/session-binding-store.js";import{splitTextForAibotProtocol as W}from"../../core/protocol/index.js";import{InboundMessageIdInjector as Y}from"../shared/inbound-message-id-injector.js";import{buildSimpleProbeReport as K}from"../shared/probe-util.js";import{piGrixProviderId as V,removePiGrixProvider as X,writePiGrixProvider as J}from"./pi-provider-config.js";const y=new Map;function Q(){const d=m(g(),".pi","agent","mcp.json");try{if(!C(d))return{};const e=JSON.parse(R(d,"utf8"))?.mcpServers;return!e||typeof e!="object"||Array.isArray(e)?{}:e}catch(t){return a.warn("pi-adapter",`Failed to read Pi user MCP config ${d}: ${t instanceof Error?t.message:String(t)}`),{}}}async function Z(d){const t=y.get(d);if(t!==void 0)return t;let e=!1;try{const s=w(b),i=process.platform==="win32",n=i&&/\s/.test(d)&&!d.startsWith('"')?`"${d}"`:d,{stdout:r,stderr:c}=await s(n,["--help"],{timeout:5e3,encoding:"utf-8",...i?{shell:!0}:{}});e=/--mcp-config\b/.test(`${r??""}${c??""}`)}catch{e=!1}return y.set(d,e),a.info("pi-adapter",`Pi --mcp-config \u652F\u6301\u63A2\u6D4B: ${e?"\u652F\u6301":"\u4E0D\u652F\u6301"} (${d})`),e}class tt extends I{adapterSessionId;constructor(t){super(),this.adapterSessionId=t}emitDone(t){this.emit("done",t)}emitError(t){if(this.listenerCount("error")===0){a.warn("pi-adapter",`Prompt handle error (no listeners): ${t.message}`);return}this.emit("error",t)}async cancel(){}}const et=12e4,st=90*1e3,x=1800*1e3;function _(d){try{return process.kill(d,0),!0}catch(t){return t.code==="EPERM"}}const it=500,nt=2e3,v=3,rt=500;function at(d){return new Promise(t=>setTimeout(t,d))}function u(d){if(d===void 0)return"undefined";if(d===null)return"null";if(typeof d=="string")return d.length>500?`${d.slice(0,500)}...`:d;try{const t=JSON.stringify(d);return t.length>500?`${t.slice(0,500)}...`:t}catch{return String(d)}}class P extends I{type="pi";config;callbacks;process=null;transport=new U;alive=!1;stopped=!1;internalApi=null;mcpConfigPath=null;identity;inboundMessageIds=new Y;piSessionPath=null;activeEventId=null;activeSessionId=null;activeAuditCapture=null;completedAuditBoundaries=new Map;isStreaming=!1;streamSeq=0;clientMsgSeq=0;activeClientMsgId=null;thinkingSeq=0;textBuffer="";emittedTextByIndex=new Map;textFlushTimer=null;activeRunError=null;runErrorEmitted=!1;idleTimer=null;lastRpcAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;composingSessionId=null;composingInterval=null;doneGuardTimer=null;bindingStore=null;aibotSessionId="";sessionReadyPromise=null;provider;agentName="";constructor(t,e){super(),this.config=t,this.callbacks=e,this.identity=new O("pi-adapter",e.getAgentProfile);const s=t.options??{};this.aibotSessionId=String(s.aibotSessionId??"").trim(),this.agentName=String(s.agentName??"").trim(),this.provider=s.provider,this.bindingStore=s.bindingStore instanceof H?s.bindingStore:null,this.bindingStore&&this.aibotSessionId&&(this.piSessionPath=this.bindingStore.getPiSessionPath(this.aibotSessionId)??null)}async start(){await this.startInternalApi(),await this.spawnPi(),await this.ensureSessionReady(),a.info("pi-adapter",`Ready (pid=${this.process?.pid})`),await this.syncModelBinding()}async syncModelBinding(){if(this.aibotSessionId)for(let t=1;t<=v;t++)try{const[e,s]=await Promise.all([this.transport.send("get_available_models"),this.transport.send("get_state")]),i=e.data?.models;if(!i||i.length===0){if(t<v){await at(rt);continue}a.warn("pi-adapter",`syncModelBinding: empty model list after ${v} attempts, giving up`);return}const n=s.data?.model,r={available_models:i.map(c=>({id:c.id,display_name:c.name??c.id,...c.provider?{provider:c.provider}:{}}))};n?.id&&(r.model_id=n.id),n?.provider&&(r.model_provider=n.provider),this.callbacks.sendUpdateBindingCard(this.aibotSessionId,this.isStreaming?"composing":"ready",this.resolveCwd(),r),a.info("pi-adapter",`synced model binding: ${i.length} models, current=${n?.id??"unknown"} (attempt ${t})`);return}catch(e){a.warn("pi-adapter",`syncModelBinding failed (non-fatal): ${e instanceof Error?e.message:String(e)}`);return}}async stop(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.cancelDoneGuard(),this.transport.close(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.mcpConfigPath){try{k(this.mcpConfigPath)}catch{}this.mcpConfigPath=null}if(this.process){const t=this.process;try{E(t,"SIGTERM")}catch{}const e=setTimeout(()=>{try{E(t,"SIGKILL")}catch{}},5e3);t.on("exit",()=>clearTimeout(e)),this.process=null}}isAlive(){return this.alive}async createSession(t){this.sessionReadyPromise=null,await this.createNewSession();const e=this.piSessionPath||`pi-${Date.now()}`;return a.info("pi-adapter",`Session created: ${e} (path=${this.piSessionPath})`),e}async resumeSession(t,e){await this.switchSession()}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(t){this.identity.forgetSession(t),this.inboundMessageIds.forgetSession(t),this.piSessionPath=null,this.sessionReadyPromise=null,this.persistPiSessionPath(void 0)}sendPrompt(t){const e=new tt(t.adapterSessionId),s=this.buildPromptTextFromRequest(t);return this.ensureSessionReady().then(()=>this.transport.send("prompt",{message:s})).then(i=>{i.success||e.emitDone({status:"failed",error:i.error})}).catch(i=>{e.emitError(i instanceof Error?i:new Error(String(i)))}),e}async cancel(t){try{await this.transport.send("abort")}catch{}}deliverInboundEvent(t){const{event_id:e,session_id:s,content:i}=t,n=this.buildPromptText(t);if(this.isStreaming){if(this.activeEventId&&this.activeEventId!==e){const r=this.activeEventId;a.info("pi-adapter",`steer: cancel ${r} -> ${e}`),this.flushTextBuffer(),this.callbacks.sendEventResult(r,"canceled","steered to new event"),this.activeAuditCapture?.eventId===r&&(this.snapshotAuditBoundary(r),this.emit("eventDone",r))}this.activeEventId=e,this.activeSessionId=s,this.beginAuditCapture(t),this.resetRunStreamState(),this.startComposing(s,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n,streamingBehavior:"steer"}).catch(r=>{a.error("pi-adapter",`steer failed: ${r}`),this.callbacks.sendEventResult(e,"failed",String(r))})}else a.info("pi-adapter",`prompt: event=${e} session=${s}`),this.activeEventId=e,this.activeSessionId=s,this.beginAuditCapture(t),this.isStreaming=!0,this.resetRunStreamState(),this.startComposing(s,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n}).then(r=>{r.success||(a.error("pi-adapter",`prompt rejected: ${r.error}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",r.error),this.clearActive())}).catch(r=>{a.error("pi-adapter",`prompt error: ${r}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",String(r)),this.clearActive()})}deliverStopEvent(t,e){if(this.activeEventId===t){a.info("pi-adapter",`stop: event=${t}, releasing busy immediately`),this.transport.send("abort").catch(()=>{}),this.flushTextBuffer();const s=this.nextStreamSeq(),i=this.activeClientMsgId??void 0;this.callbacks.sendStreamChunk(t,this.activeSessionId??"","",s,!0,i),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(t,"canceled","stopped by user"),this.clearActive()}}async handleLocalAction(t){const e=t.action_id;switch(t.action_type){case"set_model":{const s=t.params??{},i=(s.modelId??s.model_id??"").trim();if(!i)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_model","model_id is required"),{handled:!0,kind:"set_model_error"};try{let n=s.provider?.trim();return n||(n=(await this.transport.send("get_available_models")).data?.models?.find(l=>l.id===i)?.provider?.trim()),n?(await this.transport.send("set_model",{provider:n,modelId:i}),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"model_set",provider:n,modelId:i}),this.syncModelBinding(),{handled:!0,kind:"set_model"}):(this.callbacks.sendLocalActionResult(e,"failed",void 0,"model_not_found",`No provider for model: ${i}`),{handled:!0,kind:"set_model_error"})}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_model_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_model_error"}}}case"get_context":try{const s=await this.transport.send("get_state");return this.callbacks.sendLocalActionResult(e,"ok",{state:s}),{handled:!0,kind:"get_context"}}catch(s){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"get_context_error",s instanceof Error?s.message:String(s)),{handled:!1,kind:""}}case"pi_extension_ui_response":return this.transport.sendNoWait({type:"extension_ui_response",...t.params??{}}),this.callbacks.sendLocalActionResult(e,"ok"),{handled:!0,kind:"extension_ui_response"};default:return{handled:!1,kind:""}}}setPermissionHandler(t){}async ping(t){try{return await this.transport.send("get_state"),!0}catch{return!1}}getStatus(){return{alive:this.alive,busy:this.isStreaming,sessions:this.piSessionPath?1:0}}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}takeAuditBoundary(t){const e=this.completedAuditBoundaries.get(t);return e&&this.completedAuditBoundaries.delete(t),e}clearActiveEventForShutdown(){this.stopIdleTimer(),this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.activeEventId=null}getMcpConfig(){if(!this.internalApi)return null;const t=M(F(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[t,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const t=this.process?.pid;return t?G(t,[t]):!1}async probe(t){const e=this.getStatus();return{...await K(this.config.command||"pi",{alive:e.alive,busy:e.busy,started:!!this.process},t),session:this.probeSessionRecord()}}probeSessionRecord(){const t=this.piSessionPath;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const e=f(t);return{recordPath:t,lastActivityMs:e.mtimeMs,freshMs:Date.now()-e.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}getSupportedCommands(){return[{name:"model",description:"List or set model",args:"[provider:model_id]"},{name:"interrupt",description:"Interrupt current run"},{name:"status",description:"Show session status"},{name:"skills",description:"List available skills"}]}async execCommand(t,e,s){try{if(!this.alive)return{status:"failed",message:"Pi process not running"};switch(t){case"model":{const i=e.trim();if(i){const c=i.indexOf(":");if(c<1)return{status:"failed",message:"Format: provider:model_id"};const l=i.slice(0,c),h=i.slice(c+1);if(!h)return{status:"failed",message:"Format: provider:model_id"};const p=await this.transport.send("set_model",{provider:l,modelId:h});return p?.success?{status:"ok",message:`Model set to ${l}:${h}`}:{status:"failed",message:`Failed to set model: ${p?.error??"unknown error"}`}}const r=(await this.transport.send("get_available_models"))?.data?.models;return r&&r.length>0?{status:"ok",message:`Available models:
1
+ import{execFile as P}from"node:child_process";import{promisify as b}from"node:util";import{EventEmitter as I}from"node:events";import{stat as $}from"node:fs/promises";import{mkdirSync as T,writeFileSync as A,unlinkSync as k,statSync as f,readFileSync as R,existsSync as C}from"node:fs";import{join as m,resolve as M}from"node:path";import{fileURLToPath as F}from"node:url";import{tmpdir as B,homedir as g}from"node:os";import{resolveCommandPath as D,resolveWindowsExecInvocation as N,spawnCommand as G,killProcessGroup as E,hasChildProcesses as L}from"../../core/runtime/spawn.js";import{InternalApiServer as O}from"../../core/mcp/internal-api-server.js";import{IdentityInjector as j}from"../shared/identity-injector.js";import{compactToolInputForWire as q}from"../shared/tool-wire-payload.js";import{syncDefaultSkillsToDir as U}from"../../default-skills/index.js";import{PiTransport as z}from"./pi-transport.js";import{log as o}from"../../core/log/index.js";import{scanSkills as V}from"../claude/skill-scanner.js";import{SessionBindingStore as H}from"../../core/persistence/session-binding-store.js";import{splitTextForAibotProtocol as Y}from"../../core/protocol/index.js";import{InboundMessageIdInjector as K}from"../shared/inbound-message-id-injector.js";import{buildSimpleProbeReport as W}from"../shared/probe-util.js";import{piGrixProviderId as X,removePiGrixProvider as J,writePiGrixProvider as Q}from"./pi-provider-config.js";const y=new Map;function Z(){const c=m(g(),".pi","agent","mcp.json");try{if(!C(c))return{};const e=JSON.parse(R(c,"utf8"))?.mcpServers;return!e||typeof e!="object"||Array.isArray(e)?{}:e}catch(t){return o.warn("pi-adapter",`Failed to read Pi user MCP config ${c}: ${t instanceof Error?t.message:String(t)}`),{}}}async function tt(c){const t=y.get(c);if(t!==void 0)return t;let e=!1;try{const s=b(P),i=N(c,["--help"]),{stdout:n,stderr:r}=await s(i.command,i.args,{timeout:5e3,encoding:"utf-8",windowsVerbatimArguments:i.windowsVerbatimArguments});e=/--mcp-config\b/.test(`${n??""}${r??""}`)}catch{e=!1}return y.set(c,e),o.info("pi-adapter",`Pi --mcp-config \u652F\u6301\u63A2\u6D4B: ${e?"\u652F\u6301":"\u4E0D\u652F\u6301"} (${c})`),e}class et extends I{adapterSessionId;constructor(t){super(),this.adapterSessionId=t}emitDone(t){this.emit("done",t)}emitError(t){if(this.listenerCount("error")===0){o.warn("pi-adapter",`Prompt handle error (no listeners): ${t.message}`);return}this.emit("error",t)}async cancel(){}}const st=12e4,it=90*1e3,x=1800*1e3;function _(c){try{return process.kill(c,0),!0}catch(t){return t.code==="EPERM"}}const nt=500,rt=2e3,v=3,ot=500;function at(c){return new Promise(t=>setTimeout(t,c))}function u(c){if(c===void 0)return"undefined";if(c===null)return"null";if(typeof c=="string")return c.length>500?`${c.slice(0,500)}...`:c;try{const t=JSON.stringify(c);return t.length>500?`${t.slice(0,500)}...`:t}catch{return String(c)}}class w extends I{type="pi";config;callbacks;process=null;transport=new z;alive=!1;stopped=!1;internalApi=null;mcpConfigPath=null;identity;inboundMessageIds=new K;piSessionPath=null;activeEventId=null;activeSessionId=null;activeAuditCapture=null;completedAuditBoundaries=new Map;isStreaming=!1;streamSeq=0;clientMsgSeq=0;activeClientMsgId=null;thinkingSeq=0;textBuffer="";emittedTextByIndex=new Map;textFlushTimer=null;activeRunError=null;runErrorEmitted=!1;idleTimer=null;lastRpcAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;composingSessionId=null;composingInterval=null;doneGuardTimer=null;bindingStore=null;aibotSessionId="";sessionReadyPromise=null;provider;agentName="";constructor(t,e){super(),this.config=t,this.callbacks=e,this.identity=new j("pi-adapter",e.getAgentProfile);const s=t.options??{};this.aibotSessionId=String(s.aibotSessionId??"").trim(),this.agentName=String(s.agentName??"").trim(),this.provider=s.provider,this.bindingStore=s.bindingStore instanceof H?s.bindingStore:null,this.bindingStore&&this.aibotSessionId&&(this.piSessionPath=this.bindingStore.getPiSessionPath(this.aibotSessionId)??null)}async start(){await this.startInternalApi(),await this.spawnPi(),await this.ensureSessionReady(),o.info("pi-adapter",`Ready (pid=${this.process?.pid})`),await this.syncModelBinding()}async syncModelBinding(){if(this.aibotSessionId)for(let t=1;t<=v;t++)try{const[e,s]=await Promise.all([this.transport.send("get_available_models"),this.transport.send("get_state")]),i=e.data?.models;if(!i||i.length===0){if(t<v){await at(ot);continue}o.warn("pi-adapter",`syncModelBinding: empty model list after ${v} attempts, giving up`);return}const n=s.data?.model,r={available_models:i.map(d=>({id:d.id,display_name:d.name??d.id,...d.provider?{provider:d.provider}:{}}))};n?.id&&(r.model_id=n.id),n?.provider&&(r.model_provider=n.provider),this.callbacks.sendUpdateBindingCard(this.aibotSessionId,this.isStreaming?"composing":"ready",this.resolveCwd(),r),o.info("pi-adapter",`synced model binding: ${i.length} models, current=${n?.id??"unknown"} (attempt ${t})`);return}catch(e){o.warn("pi-adapter",`syncModelBinding failed (non-fatal): ${e instanceof Error?e.message:String(e)}`);return}}async stop(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.cancelDoneGuard(),this.transport.close(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.mcpConfigPath){try{k(this.mcpConfigPath)}catch{}this.mcpConfigPath=null}if(this.process){const t=this.process;try{E(t,"SIGTERM")}catch{}const e=setTimeout(()=>{try{E(t,"SIGKILL")}catch{}},5e3);t.on("exit",()=>clearTimeout(e)),this.process=null}}isAlive(){return this.alive}async createSession(t){this.sessionReadyPromise=null,await this.createNewSession();const e=this.piSessionPath||`pi-${Date.now()}`;return o.info("pi-adapter",`Session created: ${e} (path=${this.piSessionPath})`),e}async resumeSession(t,e){await this.switchSession()}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(t){this.identity.forgetSession(t),this.inboundMessageIds.forgetSession(t),this.piSessionPath=null,this.sessionReadyPromise=null,this.persistPiSessionPath(void 0)}sendPrompt(t){const e=new et(t.adapterSessionId),s=this.buildPromptTextFromRequest(t);return this.ensureSessionReady().then(()=>this.transport.send("prompt",{message:s})).then(i=>{i.success||e.emitDone({status:"failed",error:i.error})}).catch(i=>{e.emitError(i instanceof Error?i:new Error(String(i)))}),e}async cancel(t){try{await this.transport.send("abort")}catch{}}deliverInboundEvent(t){const{event_id:e,session_id:s,content:i}=t,n=this.buildPromptText(t);if(this.isStreaming){if(this.activeEventId&&this.activeEventId!==e){const r=this.activeEventId;o.info("pi-adapter",`steer: cancel ${r} -> ${e}`),this.flushTextBuffer(),this.callbacks.sendEventResult(r,"canceled","steered to new event"),this.activeAuditCapture?.eventId===r&&(this.snapshotAuditBoundary(r),this.emit("eventDone",r))}this.activeEventId=e,this.activeSessionId=s,this.beginAuditCapture(t),this.resetRunStreamState(),this.startComposing(s,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n,streamingBehavior:"steer"}).catch(r=>{o.error("pi-adapter",`steer failed: ${r}`),this.callbacks.sendEventResult(e,"failed",String(r))})}else o.info("pi-adapter",`prompt: event=${e} session=${s}`),this.activeEventId=e,this.activeSessionId=s,this.beginAuditCapture(t),this.isStreaming=!0,this.resetRunStreamState(),this.startComposing(s,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n}).then(r=>{r.success||(o.error("pi-adapter",`prompt rejected: ${r.error}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",r.error),this.clearActive())}).catch(r=>{o.error("pi-adapter",`prompt error: ${r}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",String(r)),this.clearActive()})}deliverStopEvent(t,e){if(this.activeEventId===t){o.info("pi-adapter",`stop: event=${t}, releasing busy immediately`),this.transport.send("abort").catch(()=>{}),this.flushTextBuffer();const s=this.nextStreamSeq(),i=this.activeClientMsgId??void 0;this.callbacks.sendStreamChunk(t,this.activeSessionId??"","",s,!0,i),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(t,"canceled","stopped by user"),this.clearActive()}}async handleLocalAction(t){const e=t.action_id;switch(t.action_type){case"set_model":{const s=t.params??{},i=(s.modelId??s.model_id??"").trim();if(!i)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_model","model_id is required"),{handled:!0,kind:"set_model_error"};try{let n=s.provider?.trim();return n||(n=(await this.transport.send("get_available_models")).data?.models?.find(l=>l.id===i)?.provider?.trim()),n?(await this.transport.send("set_model",{provider:n,modelId:i}),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"model_set",provider:n,modelId:i}),this.syncModelBinding(),{handled:!0,kind:"set_model"}):(this.callbacks.sendLocalActionResult(e,"failed",void 0,"model_not_found",`No provider for model: ${i}`),{handled:!0,kind:"set_model_error"})}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_model_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_model_error"}}}case"get_context":try{const s=await this.transport.send("get_state");return this.callbacks.sendLocalActionResult(e,"ok",{state:s}),{handled:!0,kind:"get_context"}}catch(s){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"get_context_error",s instanceof Error?s.message:String(s)),{handled:!1,kind:""}}case"pi_extension_ui_response":return this.transport.sendNoWait({type:"extension_ui_response",...t.params??{}}),this.callbacks.sendLocalActionResult(e,"ok"),{handled:!0,kind:"extension_ui_response"};default:return{handled:!1,kind:""}}}setPermissionHandler(t){}async ping(t){try{return await this.transport.send("get_state"),!0}catch{return!1}}getStatus(){return{alive:this.alive,busy:this.isStreaming,sessions:this.piSessionPath?1:0}}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}takeAuditBoundary(t){const e=this.completedAuditBoundaries.get(t);return e&&this.completedAuditBoundaries.delete(t),e}clearActiveEventForShutdown(){this.stopIdleTimer(),this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.activeEventId=null}getMcpConfig(){if(!this.internalApi)return null;const t=M(F(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[t,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const t=this.process?.pid;return t?L(t,[t]):!1}async probe(t){const e=this.getStatus();return{...await W(this.config.command||"pi",{alive:e.alive,busy:e.busy,started:!!this.process},t),session:this.probeSessionRecord()}}probeSessionRecord(){const t=this.piSessionPath;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const e=f(t);return{recordPath:t,lastActivityMs:e.mtimeMs,freshMs:Date.now()-e.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}getSupportedCommands(){return[{name:"model",description:"List or set model",args:"[provider:model_id]"},{name:"interrupt",description:"Interrupt current run"},{name:"status",description:"Show session status"},{name:"skills",description:"List available skills"}]}async execCommand(t,e,s){try{if(!this.alive)return{status:"failed",message:"Pi process not running"};switch(t){case"model":{const i=e.trim();if(i){const d=i.indexOf(":");if(d<1)return{status:"failed",message:"Format: provider:model_id"};const l=i.slice(0,d),h=i.slice(d+1);if(!h)return{status:"failed",message:"Format: provider:model_id"};const p=await this.transport.send("set_model",{provider:l,modelId:h});return p?.success?{status:"ok",message:`Model set to ${l}:${h}`}:{status:"failed",message:`Failed to set model: ${p?.error??"unknown error"}`}}const r=(await this.transport.send("get_available_models"))?.data?.models;return r&&r.length>0?{status:"ok",message:`Available models:
2
2
  ${r.map(l=>` ${l.provider??"unknown"}:${l.id} (${l.name??l.id})`).join(`
3
- `)}`,data:r}:{status:"ok",message:"No models available",data:[]}}case"interrupt":return this.isStreaming?(await this.transport.send("abort"),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","interrupted"),this.clearActive(),{status:"ok",message:"Run interrupted"}):{status:"failed",message:"No active run to interrupt"};case"status":{const i=this.getStatus();return{status:"ok",message:`Alive: ${i.alive}, Busy: ${i.busy}, Session: ${this.piSessionPath??"none"}`,data:{alive:i.alive,busy:i.busy,sessions:i.sessions,sessionPath:this.piSessionPath}}}case"skills":{const i=z({mode:"pi"}),n=i.map(r=>`- ${r.name}${r.trigger?` (${r.trigger})`:""} [${r.source}]: ${r.description}`);return{status:"ok",message:n.length>0?n.join(`
4
- `):"No skills found",data:i}}default:return{status:"unsupported",message:`Unknown command: ${t}`}}}catch(i){return{status:"failed",message:i instanceof Error?i.message:String(i)}}}resolveCwd(){if(this.bindingStore&&this.aibotSessionId){const e=this.bindingStore.get(this.aibotSessionId);if(e?.cwd)return e.cwd}const t=(this.config.options??{}).cwd;return typeof t=="string"&&t?t:process.cwd()}async startInternalApi(){try{this.internalApi=new L,this.internalApi.setInvokeHandler(async(r,c,l,h)=>this.callbacks.agentInvoke(r,c,h)),await this.internalApi.start(0),a.info("pi-adapter",`Internal API started at ${this.internalApi.url}`);const t=this.getMcpConfig(),e=Q(),s=m(B(),"grix-pi-mcp");T(s,{recursive:!0}),this.mcpConfigPath=m(s,`mcp-${process.pid}-${Date.now()}.json`),A(this.mcpConfigPath,JSON.stringify({mcpServers:{...e,[t.name]:{command:t.command,args:t.args,directTools:!0,lifecycle:"eager"}}}),"utf8"),a.info("pi-adapter",`MCP config written to ${this.mcpConfigPath}`);const i=m(g(),".pi","agent","skills"),n=q(i);n.length>0&&a.info("pi-adapter",`Synced connector skills to ${i}: [${n.join(", ")}]`)}catch(t){a.warn("pi-adapter",`Failed to start MCP tools (non-fatal): ${t instanceof Error?t.message:String(t)}`)}}async spawnPi(){const t=this.config.command||"pi",e=D(t,typeof process.env.PATH=="string"?process.env.PATH:void 0),s=this.config.args??[],n=s.some(o=>o.startsWith("--mode"))?[...s]:["--mode","rpc",...s],r=String(this.config.env?.PI_CODING_AGENT_DIR??"").trim()||m(g(),".pi","agent"),c=V(this.agentName);this.provider?await J(r,c,this.provider)?(n.includes("--provider")||n.push("--provider",c),!n.includes("--model")&&this.provider.model?.trim()&&n.push("--model",this.provider.model.trim())):a.warn("pi-adapter","provider config incomplete (baseUrl/model required); Grix provider not applied"):await X(r,c).then(o=>{o&&a.info("pi-adapter",`Removed stale Grix provider "${c}" from models.json`)}).catch(o=>{a.warn("pi-adapter",`Failed to clean up Grix provider config: ${o instanceof Error?o.message:String(o)}`)}),this.mcpConfigPath&&!n.some(o=>o==="--mcp-config")&&(await Z(e)?n.push("--mcp-config",this.mcpConfigPath):a.warn("pi-adapter","\u5F53\u524D Pi \u4E0D\u652F\u6301 --mcp-config\uFF08\u672A\u68C0\u6D4B\u5230 pi-mcp-adapter \u6269\u5C55\uFF09\uFF0C\u8DF3\u8FC7 MCP \u6CE8\u5165\u4EE5\u907F\u514D\u542F\u52A8\u5931\u8D25"));const l={...process.env,...this.config.env},h=this.provider?.apiKey?.trim();h&&!l.GRIX_PROVIDER_API_KEY?.trim()&&(l.GRIX_PROVIDER_API_KEY=h);const p=this.resolveCwd();a.info("pi-adapter",`Spawning: ${e} ${n.join(" ")}`);try{if(!(await $(p)).isDirectory())throw new Error(`Bound path is not a directory: ${p}`)}catch(o){throw String(o?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${p}. Please rebind with /grix open <valid-directory>.`):o}try{this.process=N(e,n,{env:l,cwd:p}).process}catch(o){throw a.error("pi-adapter",`PI spawn threw: ${o}`),this.alive=!1,o}this.process.on("error",o=>{a.error("pi-adapter",`Spawn error: ${o.message}`),this.alive=!1,this.transport.close(),this.activeEventId&&(this.callbacks.sendEventResult(this.activeEventId,"failed",`Spawn error: ${o.message}`),this.clearActive()),this.stopped||this.emit("exit",1)}),this.process.on("exit",o=>{a.info("pi-adapter",`PI process exited (code=${o})`),this.alive=!1,this.transport.close(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"failed",`PI process exited (code=${o})`),this.isStreaming=!1,this.clearActive(),this.stopped||this.emit("exit",o??1)}),this.process.stderr?.on("data",o=>{const S=o.toString().trim();S&&a.info("pi-adapter",`[pi stderr] ${S}`)}),this.transport.on("event",o=>this.handlePiEvent(o)),this.transport.bind(this.process.stdin,this.process.stdout),this.alive=!0}handlePiEvent(t){if(this.stopped)return;if(this.lastRpcAt=Date.now(),t.type==="tool_execution_start"){const s=t;s.toolCallId&&this.toolCallsInFlight.add(s.toolCallId)}else if(t.type==="tool_execution_end"){const s=t;s.toolCallId&&this.toolCallsInFlight.delete(s.toolCallId)}switch(this.resetIdleTimer(),t.type){case"message_update":{const s=t.assistantMessageEvent;if(!s)break;const i=s.type;if(i==="text_delta"){const n=s.delta;if(n){const r=typeof s.contentIndex=="number"?s.contentIndex:0;this.rememberEmittedText(r,n),this.appendText(n)}}else if(i==="text_end"){const n=s.content,r=typeof s.contentIndex=="number"?s.contentIndex:0;n&&this.appendMissingText(r,n)}else if(i==="thinking_delta"){const n=s.delta;n&&this.activeEventId&&this.activeSessionId&&(this.thinkingSeq++,this.callbacks.sendThinking(this.activeEventId,this.activeSessionId,n))}else if(i==="done"||i==="error"){if(this.flushTextBuffer(),i==="error"){const n=this.piMessageError(s.error,s.reason);a.warn("pi-adapter",`terminal message_update error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${u(s.error)} reason=${u(s.reason)}`),this.recordRunError(n)}this.scheduleDoneGuard()}break}case"message_end":{const s=t.message;s?.role==="assistant"&&s.stopReason==="error"&&(a.warn("pi-adapter",`terminal message_end error event=${this.activeEventId} sessionId=${this.activeSessionId} errorMessage=${u(s.errorMessage)} message=${u(s)}`),this.recordRunError(this.piMessageError(s,s.errorMessage)),this.scheduleDoneGuard());break}case"tool_execution_start":{if(this.cancelDoneGuard(),this.flushTextBuffer(),!this.activeEventId||!this.activeSessionId)break;const s=t;if(s.toolName){const i=j(s.args);this.callbacks.sendToolUse(this.activeEventId,this.activeSessionId,s.toolName,i)}break}case"tool_execution_end":{if(!this.activeEventId||!this.activeSessionId)break;const s=t;s.isError&&this.callbacks.sendToolResult(this.activeEventId,this.activeSessionId,s.toolName,"(failed)");break}case"agent_end":{if(a.info("pi-adapter",`agent_end event=${this.activeEventId} sessionId=${this.activeSessionId}`),this.cancelDoneGuard(),t.willRetry===!0&&this.activeEventId){a.info("pi-adapter",`agent_end willRetry=true \u2014 holding event=${this.activeEventId} for auto-retry`),this.activeRunError=null,this.emittedTextByIndex.clear(),this.resetIdleTimer();break}this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.completeActiveEvent();break}case"agent_start":{this.cancelDoneGuard(),this.activeEventId&&(a.info("pi-adapter",`agent_start event=${this.activeEventId}`),this.isStreaming=!0);break}default:break}}appendText(t){if(this.textBuffer+=t,this.textBuffer.length>=nt){this.flushTextBuffer();return}this.scheduleTextFlush()}scheduleTextFlush(){this.textFlushTimer||(this.textFlushTimer=setTimeout(()=>{this.textFlushTimer=null,this.flushTextBuffer()},it))}flushTextBuffer(){this.stopTextFlush(),!(!this.textBuffer||!this.activeEventId||!this.activeSessionId)&&(this.sendTextChunks(this.textBuffer),this.textBuffer="")}sendTextChunks(t){if(!(!this.activeEventId||!this.activeSessionId))for(const e of W(t))this.callbacks.sendStreamChunk(this.activeEventId,this.activeSessionId,e,this.nextStreamSeq(),!1,this.activeClientMsgId??void 0)}stopTextFlush(){this.textFlushTimer&&(clearTimeout(this.textFlushTimer),this.textFlushTimer=null)}buildPromptText(t){let e=t.content||"";if(t.context_messages_json)try{const i=JSON.parse(t.context_messages_json);if(Array.isArray(i)&&i.length>0){const n=i.map(r=>`[context] ${r.sender_id??"unknown"}: ${r.content}`).join(`
3
+ `)}`,data:r}:{status:"ok",message:"No models available",data:[]}}case"interrupt":return this.isStreaming?(await this.transport.send("abort"),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","interrupted"),this.clearActive(),{status:"ok",message:"Run interrupted"}):{status:"failed",message:"No active run to interrupt"};case"status":{const i=this.getStatus();return{status:"ok",message:`Alive: ${i.alive}, Busy: ${i.busy}, Session: ${this.piSessionPath??"none"}`,data:{alive:i.alive,busy:i.busy,sessions:i.sessions,sessionPath:this.piSessionPath}}}case"skills":{const i=V({mode:"pi"}),n=i.map(r=>`- ${r.name}${r.trigger?` (${r.trigger})`:""} [${r.source}]: ${r.description}`);return{status:"ok",message:n.length>0?n.join(`
4
+ `):"No skills found",data:i}}default:return{status:"unsupported",message:`Unknown command: ${t}`}}}catch(i){return{status:"failed",message:i instanceof Error?i.message:String(i)}}}resolveCwd(){if(this.bindingStore&&this.aibotSessionId){const e=this.bindingStore.get(this.aibotSessionId);if(e?.cwd)return e.cwd}const t=(this.config.options??{}).cwd;return typeof t=="string"&&t?t:process.cwd()}async startInternalApi(){try{this.internalApi=new O,this.internalApi.setInvokeHandler(async(r,d,l,h)=>this.callbacks.agentInvoke(r,d,h)),await this.internalApi.start(0),o.info("pi-adapter",`Internal API started at ${this.internalApi.url}`);const t=this.getMcpConfig(),e=Z(),s=m(B(),"grix-pi-mcp");T(s,{recursive:!0}),this.mcpConfigPath=m(s,`mcp-${process.pid}-${Date.now()}.json`),A(this.mcpConfigPath,JSON.stringify({mcpServers:{...e,[t.name]:{command:t.command,args:t.args,directTools:!0,lifecycle:"eager"}}}),"utf8"),o.info("pi-adapter",`MCP config written to ${this.mcpConfigPath}`);const i=m(g(),".pi","agent","skills"),n=U(i);n.length>0&&o.info("pi-adapter",`Synced connector skills to ${i}: [${n.join(", ")}]`)}catch(t){o.warn("pi-adapter",`Failed to start MCP tools (non-fatal): ${t instanceof Error?t.message:String(t)}`)}}async spawnPi(){const t=this.config.command||"pi",e=D(t,typeof process.env.PATH=="string"?process.env.PATH:void 0),s=this.config.args??[],n=s.some(a=>a.startsWith("--mode"))?[...s]:["--mode","rpc",...s],r=String(this.config.env?.PI_CODING_AGENT_DIR??"").trim()||m(g(),".pi","agent"),d=X(this.agentName);this.provider?await Q(r,d,this.provider)?(n.includes("--provider")||n.push("--provider",d),!n.includes("--model")&&this.provider.model?.trim()&&n.push("--model",this.provider.model.trim())):o.warn("pi-adapter","provider config incomplete (baseUrl/model required); Grix provider not applied"):await J(r,d).then(a=>{a&&o.info("pi-adapter",`Removed stale Grix provider "${d}" from models.json`)}).catch(a=>{o.warn("pi-adapter",`Failed to clean up Grix provider config: ${a instanceof Error?a.message:String(a)}`)}),this.mcpConfigPath&&!n.some(a=>a==="--mcp-config")&&(await tt(e)?n.push("--mcp-config",this.mcpConfigPath):o.warn("pi-adapter","\u5F53\u524D Pi \u4E0D\u652F\u6301 --mcp-config\uFF08\u672A\u68C0\u6D4B\u5230 pi-mcp-adapter \u6269\u5C55\uFF09\uFF0C\u8DF3\u8FC7 MCP \u6CE8\u5165\u4EE5\u907F\u514D\u542F\u52A8\u5931\u8D25"));const l={...process.env,...this.config.env},h=this.provider?.apiKey?.trim();h&&!l.GRIX_PROVIDER_API_KEY?.trim()&&(l.GRIX_PROVIDER_API_KEY=h);const p=this.resolveCwd();o.info("pi-adapter",`Spawning: ${e} ${n.join(" ")}`);try{if(!(await $(p)).isDirectory())throw new Error(`Bound path is not a directory: ${p}`)}catch(a){throw String(a?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${p}. Please rebind with /grix open <valid-directory>.`):a}try{this.process=G(e,n,{env:l,cwd:p}).process}catch(a){throw o.error("pi-adapter",`PI spawn threw: ${a}`),this.alive=!1,a}this.process.on("error",a=>{o.error("pi-adapter",`Spawn error: ${a.message}`),this.alive=!1,this.transport.close(),this.activeEventId&&(this.callbacks.sendEventResult(this.activeEventId,"failed",`Spawn error: ${a.message}`),this.clearActive()),this.stopped||this.emit("exit",1)}),this.process.on("exit",a=>{o.info("pi-adapter",`PI process exited (code=${a})`),this.alive=!1,this.transport.close(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"failed",`PI process exited (code=${a})`),this.isStreaming=!1,this.clearActive(),this.stopped||this.emit("exit",a??1)}),this.process.stderr?.on("data",a=>{const S=a.toString().trim();S&&o.info("pi-adapter",`[pi stderr] ${S}`)}),this.transport.on("event",a=>this.handlePiEvent(a)),this.transport.bind(this.process.stdin,this.process.stdout),this.alive=!0}handlePiEvent(t){if(this.stopped)return;if(this.lastRpcAt=Date.now(),t.type==="tool_execution_start"){const s=t;s.toolCallId&&this.toolCallsInFlight.add(s.toolCallId)}else if(t.type==="tool_execution_end"){const s=t;s.toolCallId&&this.toolCallsInFlight.delete(s.toolCallId)}switch(this.resetIdleTimer(),t.type){case"message_update":{const s=t.assistantMessageEvent;if(!s)break;const i=s.type;if(i==="text_delta"){const n=s.delta;if(n){const r=typeof s.contentIndex=="number"?s.contentIndex:0;this.rememberEmittedText(r,n),this.appendText(n)}}else if(i==="text_end"){const n=s.content,r=typeof s.contentIndex=="number"?s.contentIndex:0;n&&this.appendMissingText(r,n)}else if(i==="thinking_delta"){const n=s.delta;n&&this.activeEventId&&this.activeSessionId&&(this.thinkingSeq++,this.callbacks.sendThinking(this.activeEventId,this.activeSessionId,n))}else if(i==="done"||i==="error"){if(this.flushTextBuffer(),i==="error"){const n=this.piMessageError(s.error,s.reason);o.warn("pi-adapter",`terminal message_update error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${u(s.error)} reason=${u(s.reason)}`),this.recordRunError(n)}this.scheduleDoneGuard()}break}case"message_end":{const s=t.message;s?.role==="assistant"&&s.stopReason==="error"&&(o.warn("pi-adapter",`terminal message_end error event=${this.activeEventId} sessionId=${this.activeSessionId} errorMessage=${u(s.errorMessage)} message=${u(s)}`),this.recordRunError(this.piMessageError(s,s.errorMessage)),this.scheduleDoneGuard());break}case"tool_execution_start":{if(this.cancelDoneGuard(),this.flushTextBuffer(),!this.activeEventId||!this.activeSessionId)break;const s=t;if(s.toolName){const i=q(s.args);this.callbacks.sendToolUse(this.activeEventId,this.activeSessionId,s.toolName,i)}break}case"tool_execution_end":{if(!this.activeEventId||!this.activeSessionId)break;const s=t;s.isError&&this.callbacks.sendToolResult(this.activeEventId,this.activeSessionId,s.toolName,"(failed)");break}case"agent_end":{if(o.info("pi-adapter",`agent_end event=${this.activeEventId} sessionId=${this.activeSessionId}`),this.cancelDoneGuard(),t.willRetry===!0&&this.activeEventId){o.info("pi-adapter",`agent_end willRetry=true \u2014 holding event=${this.activeEventId} for auto-retry`),this.activeRunError=null,this.emittedTextByIndex.clear(),this.resetIdleTimer();break}this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.completeActiveEvent();break}case"agent_start":{this.cancelDoneGuard(),this.activeEventId&&(o.info("pi-adapter",`agent_start event=${this.activeEventId}`),this.isStreaming=!0);break}default:break}}appendText(t){if(this.textBuffer+=t,this.textBuffer.length>=rt){this.flushTextBuffer();return}this.scheduleTextFlush()}scheduleTextFlush(){this.textFlushTimer||(this.textFlushTimer=setTimeout(()=>{this.textFlushTimer=null,this.flushTextBuffer()},nt))}flushTextBuffer(){this.stopTextFlush(),!(!this.textBuffer||!this.activeEventId||!this.activeSessionId)&&(this.sendTextChunks(this.textBuffer),this.textBuffer="")}sendTextChunks(t){if(!(!this.activeEventId||!this.activeSessionId))for(const e of Y(t))this.callbacks.sendStreamChunk(this.activeEventId,this.activeSessionId,e,this.nextStreamSeq(),!1,this.activeClientMsgId??void 0)}stopTextFlush(){this.textFlushTimer&&(clearTimeout(this.textFlushTimer),this.textFlushTimer=null)}buildPromptText(t){let e=t.content||"";if(t.context_messages_json)try{const i=JSON.parse(t.context_messages_json);if(Array.isArray(i)&&i.length>0){const n=i.map(r=>`[context] ${r.sender_id??"unknown"}: ${r.content}`).join(`
5
5
  `);e=`${e}
6
6
 
7
7
  [Conversation context]
@@ -9,4 +9,4 @@ ${n}`}}catch{}const s=this.identity.injectOnce(t.session_id,e);return this.inbou
9
9
  `);e=`${e}
10
10
 
11
11
  [Conversation context]
12
- ${s}`}return this.identity.injectOnce(t.adapterSessionId,e)}clearActive(){const t=this.activeEventId;t&&this.snapshotAuditBoundary(t),this.activeEventId=null,this.activeSessionId=null,this.activeClientMsgId=null,this.activeRunError=null,this.textBuffer="",this.emittedTextByIndex.clear(),this.toolCallsInFlight.clear(),this.livenessExtendStartAt=void 0,this.stopIdleTimer(),t&&this.emit("eventDone",t)}beginAuditCapture(t){if(this.activeAuditCapture?.eventId===t.event_id||(this.activeAuditCapture=null,t.audit?.enabled!==!0))return;const e=this.piSessionPath??void 0;let s;if(e)try{s=f(e).size}catch{s=0}this.activeAuditCapture={eventId:t.event_id,...e?{transcriptPath:e}:{},...s===void 0?{}:{transcriptStartOffset:s}}}snapshotAuditBoundary(t){const e=this.activeAuditCapture;if(!e||e.eventId!==t)return;this.activeAuditCapture=null;const s={adapterType:"pi"};if(e.transcriptPath){let i=e.transcriptStartOffset??0;try{i=f(e.transcriptPath).size}catch{}s.transcriptPath=e.transcriptPath,s.transcriptStartOffset=e.transcriptStartOffset??0,s.transcriptEndOffset=i,s.providerSessionId=this.piSessionPath??e.transcriptPath}this.completedAuditBoundaries.set(t,s)}resetRunStreamState(){this.streamSeq=0,this.thinkingSeq=0,this.textBuffer="",this.activeRunError=null,this.runErrorEmitted=!1,this.emittedTextByIndex.clear(),this.activeClientMsgId=`pi_${++this.clientMsgSeq}_${Date.now()}`}nextStreamSeq(){return this.streamSeq++,this.streamSeq}completeActiveEvent(){if(!this.activeEventId){this.clearActive();return}const t=this.activeEventId,e=this.activeSessionId??"",s=this.activeClientMsgId??void 0,i=this.activeRunError??void 0;i&&this.emitPendingRunError(),this.clearActive(),this.finalizeEvent(t,e,s,i)}finalizeEvent(t,e,s,i){const n=this.nextStreamSeq(),r=i?"failed":"responded";a.info("pi-adapter",`finalize event=${t} sessionId=${e} status=${r} clientMsgId=${s??""} terminalError=${i?u(i):""}`),this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t,e,s).then(()=>{this.callbacks.sendEventResult(t,r,i),a.info("pi-adapter",`event ${r} (reliable) event=${t}`)}).catch(c=>{a.error("pi-adapter",`finalStreamChunk ACK failed event=${t}: ${c}`),this.callbacks.sendEventResult(t,"failed",`final output delivery failed: ${c instanceof Error?c.message:String(c)}`),a.info("pi-adapter",`event failed (final delivery) event=${t}`)}):(this.callbacks.sendStreamChunk(t,e,"",n,!0,s),this.callbacks.sendEventResult(t,r,i),a.info("pi-adapter",`event ${r} event=${t}`))}recordRunError(t){if(this.activeRunError||!this.activeEventId||!this.activeSessionId)return;const e=t.trim()||"Pi request failed";this.activeRunError=e,a.warn("pi-adapter",`recorded terminal error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${u(e)}`),this.flushTextBuffer()}emitPendingRunError(){this.runErrorEmitted||!this.activeRunError||!this.activeEventId||!this.activeSessionId||(this.runErrorEmitted=!0,this.callbacks.sendRunError(this.activeEventId,this.activeSessionId,this.activeRunError,this.nextStreamSeq(),this.activeClientMsgId??void 0))}piMessageError(t,e){if(t&&typeof t=="object"){const s=t.errorMessage;if(typeof s=="string"&&s.trim())return s.trim()}return typeof t=="string"&&t.trim()?t.trim():typeof e=="string"&&e.trim()&&e.trim()!=="error"?e.trim():"Pi request failed"}rememberEmittedText(t,e){this.emittedTextByIndex.set(t,(this.emittedTextByIndex.get(t)??"")+e)}appendMissingText(t,e){const s=this.emittedTextByIndex.get(t)??"";if(e!==s){if(e.startsWith(s)){const i=e.slice(s.length);i&&(this.rememberEmittedText(t,i),this.appendText(i));return}if(!s){this.rememberEmittedText(t,e),this.appendText(e);return}a.info("pi-adapter",`text_end content mismatch at index=${t}, keeping streamed deltas`)}}startComposing(t,e){this.stopComposing(),this.composingSessionId=t,this.callbacks.sendSessionActivitySet(t,"composing",!0,{ref_event_id:e,ttl_ms:12e4}),this.composingInterval=setInterval(()=>{this.composingSessionId&&this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!0,{ttl_ms:12e4})},3e4)}stopComposing(){this.composingInterval&&(clearInterval(this.composingInterval),this.composingInterval=null),this.composingSessionId&&(this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!1),this.composingSessionId=null)}static DONE_GUARD_MS=5e3;scheduleDoneGuard(){this.cancelDoneGuard(),!(!this.activeEventId||!this.activeSessionId)&&(this.doneGuardTimer=setTimeout(()=>{this.doneGuardTimer=null,!(!this.activeEventId||!this.isStreaming)&&(a.info("pi-adapter",`done guard triggered \u2014 no agent_end received, ending event=${this.activeEventId}`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.completeActiveEvent())},P.DONE_GUARD_MS))}cancelDoneGuard(){this.doneGuardTimer&&(clearTimeout(this.doneGuardTimer),this.doneGuardTimer=null)}shouldExtendByLiveness(){if(!this.isStreaming||!this.activeEventId)return!1;const t=this.process?.pid;if(!this.alive||!t||!_(t))return!1;const e=Date.now(),s=this.lastRpcAt>0?e-this.lastRpcAt:Number.POSITIVE_INFINITY;if(s<st)return this.livenessExtendStartAt=e,a.info("pi-adapter",`Liveness check: fresh RPC for ${this.activeEventId} (rpcAge=${s}ms, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const n=this.livenessExtendStartAt??e;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=n),e-n>x?(a.warn("pi-adapter",`Liveness extension budget exhausted for ${this.activeEventId} (no progress for ${Math.round((e-n)/6e4)}min), allowing idle fail`),!1):(a.info("pi-adapter",`Liveness check: turn in progress for ${this.activeEventId} (toolsInFlight=${this.toolCallsInFlight.size}, rpcAge=${Number.isFinite(s)?`${s}ms`:"n/a"}), extending`),!0)}resetIdleTimer(){this.stopIdleTimer(),!(this.stopped||!this.isStreaming)&&(this.idleTimer=setTimeout(()=>{if(this.stopped||!this.isStreaming)return;if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const t=this.process?.pid,s=!!(this.alive&&t&&_(t))?`liveness budget exhausted after ${x/6e4}min`:"process not alive";a.error("pi-adapter",`Idle timeout (${s}, toolsInFlight=${this.toolCallsInFlight.size}) \u2014 emitting exit for respawn`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.activeEventId&&(this.emitPendingRunError(),this.callbacks.sendEventResult(this.activeEventId,"failed",`idle timeout: ${s}`)),this.clearActive(),this.emit("exit",-1)},et))}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}async ensureSessionReady(){return this.sessionReadyPromise?this.sessionReadyPromise:(this.sessionReadyPromise=this.restoreOrCreateSession().finally(()=>{this.sessionReadyPromise=null}),this.sessionReadyPromise)}async restoreOrCreateSession(){try{await this.switchSession();return}catch(t){this.piSessionPath&&a.error("pi-adapter",`switch_session failed, creating new session: ${t}`)}await this.createNewSession()}async switchSession(){if(!this.piSessionPath)throw new Error("no PI session path");const t=await this.transport.send("switch_session",{sessionPath:this.piSessionPath});if(!t.success)throw this.piSessionPath=null,this.persistPiSessionPath(void 0),new Error(`switch_session failed: ${t.error}`)}async createNewSession(){const t=await this.transport.send("new_session");if(!t.success)throw new Error(`new_session failed: ${t.error}`);let e=null;if(e=t.data?.sessionFile??null,!e)try{const i=await this.transport.send("get_state");i.success&&(e=i.data?.sessionFile??null)}catch{}this.piSessionPath=e,this.persistPiSessionPath(this.piSessionPath??void 0)}persistPiSessionPath(t){!this.bindingStore||!this.aibotSessionId||this.bindingStore.setPiSessionPath(this.aibotSessionId,t)}}export{P as PiAdapter};
12
+ ${s}`}return this.identity.injectOnce(t.adapterSessionId,e)}clearActive(){const t=this.activeEventId;t&&this.snapshotAuditBoundary(t),this.activeEventId=null,this.activeSessionId=null,this.activeClientMsgId=null,this.activeRunError=null,this.textBuffer="",this.emittedTextByIndex.clear(),this.toolCallsInFlight.clear(),this.livenessExtendStartAt=void 0,this.stopIdleTimer(),t&&this.emit("eventDone",t)}beginAuditCapture(t){if(this.activeAuditCapture?.eventId===t.event_id||(this.activeAuditCapture=null,t.audit?.enabled!==!0))return;const e=this.piSessionPath??void 0;let s;if(e)try{s=f(e).size}catch{s=0}this.activeAuditCapture={eventId:t.event_id,...e?{transcriptPath:e}:{},...s===void 0?{}:{transcriptStartOffset:s}}}snapshotAuditBoundary(t){const e=this.activeAuditCapture;if(!e||e.eventId!==t)return;this.activeAuditCapture=null;const s={adapterType:"pi"};if(e.transcriptPath){let i=e.transcriptStartOffset??0;try{i=f(e.transcriptPath).size}catch{}s.transcriptPath=e.transcriptPath,s.transcriptStartOffset=e.transcriptStartOffset??0,s.transcriptEndOffset=i,s.providerSessionId=this.piSessionPath??e.transcriptPath}this.completedAuditBoundaries.set(t,s)}resetRunStreamState(){this.streamSeq=0,this.thinkingSeq=0,this.textBuffer="",this.activeRunError=null,this.runErrorEmitted=!1,this.emittedTextByIndex.clear(),this.activeClientMsgId=`pi_${++this.clientMsgSeq}_${Date.now()}`}nextStreamSeq(){return this.streamSeq++,this.streamSeq}completeActiveEvent(){if(!this.activeEventId){this.clearActive();return}const t=this.activeEventId,e=this.activeSessionId??"",s=this.activeClientMsgId??void 0,i=this.activeRunError??void 0;i&&this.emitPendingRunError(),this.clearActive(),this.finalizeEvent(t,e,s,i)}finalizeEvent(t,e,s,i){const n=this.nextStreamSeq(),r=i?"failed":"responded";o.info("pi-adapter",`finalize event=${t} sessionId=${e} status=${r} clientMsgId=${s??""} terminalError=${i?u(i):""}`),this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t,e,s).then(()=>{this.callbacks.sendEventResult(t,r,i),o.info("pi-adapter",`event ${r} (reliable) event=${t}`)}).catch(d=>{o.error("pi-adapter",`finalStreamChunk ACK failed event=${t}: ${d}`),this.callbacks.sendEventResult(t,"failed",`final output delivery failed: ${d instanceof Error?d.message:String(d)}`),o.info("pi-adapter",`event failed (final delivery) event=${t}`)}):(this.callbacks.sendStreamChunk(t,e,"",n,!0,s),this.callbacks.sendEventResult(t,r,i),o.info("pi-adapter",`event ${r} event=${t}`))}recordRunError(t){if(this.activeRunError||!this.activeEventId||!this.activeSessionId)return;const e=t.trim()||"Pi request failed";this.activeRunError=e,o.warn("pi-adapter",`recorded terminal error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${u(e)}`),this.flushTextBuffer()}emitPendingRunError(){this.runErrorEmitted||!this.activeRunError||!this.activeEventId||!this.activeSessionId||(this.runErrorEmitted=!0,this.callbacks.sendRunError(this.activeEventId,this.activeSessionId,this.activeRunError,this.nextStreamSeq(),this.activeClientMsgId??void 0))}piMessageError(t,e){if(t&&typeof t=="object"){const s=t.errorMessage;if(typeof s=="string"&&s.trim())return s.trim()}return typeof t=="string"&&t.trim()?t.trim():typeof e=="string"&&e.trim()&&e.trim()!=="error"?e.trim():"Pi request failed"}rememberEmittedText(t,e){this.emittedTextByIndex.set(t,(this.emittedTextByIndex.get(t)??"")+e)}appendMissingText(t,e){const s=this.emittedTextByIndex.get(t)??"";if(e!==s){if(e.startsWith(s)){const i=e.slice(s.length);i&&(this.rememberEmittedText(t,i),this.appendText(i));return}if(!s){this.rememberEmittedText(t,e),this.appendText(e);return}o.info("pi-adapter",`text_end content mismatch at index=${t}, keeping streamed deltas`)}}startComposing(t,e){this.stopComposing(),this.composingSessionId=t,this.callbacks.sendSessionActivitySet(t,"composing",!0,{ref_event_id:e,ttl_ms:12e4}),this.composingInterval=setInterval(()=>{this.composingSessionId&&this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!0,{ttl_ms:12e4})},3e4)}stopComposing(){this.composingInterval&&(clearInterval(this.composingInterval),this.composingInterval=null),this.composingSessionId&&(this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!1),this.composingSessionId=null)}static DONE_GUARD_MS=5e3;scheduleDoneGuard(){this.cancelDoneGuard(),!(!this.activeEventId||!this.activeSessionId)&&(this.doneGuardTimer=setTimeout(()=>{this.doneGuardTimer=null,!(!this.activeEventId||!this.isStreaming)&&(o.info("pi-adapter",`done guard triggered \u2014 no agent_end received, ending event=${this.activeEventId}`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.completeActiveEvent())},w.DONE_GUARD_MS))}cancelDoneGuard(){this.doneGuardTimer&&(clearTimeout(this.doneGuardTimer),this.doneGuardTimer=null)}shouldExtendByLiveness(){if(!this.isStreaming||!this.activeEventId)return!1;const t=this.process?.pid;if(!this.alive||!t||!_(t))return!1;const e=Date.now(),s=this.lastRpcAt>0?e-this.lastRpcAt:Number.POSITIVE_INFINITY;if(s<it)return this.livenessExtendStartAt=e,o.info("pi-adapter",`Liveness check: fresh RPC for ${this.activeEventId} (rpcAge=${s}ms, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const n=this.livenessExtendStartAt??e;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=n),e-n>x?(o.warn("pi-adapter",`Liveness extension budget exhausted for ${this.activeEventId} (no progress for ${Math.round((e-n)/6e4)}min), allowing idle fail`),!1):(o.info("pi-adapter",`Liveness check: turn in progress for ${this.activeEventId} (toolsInFlight=${this.toolCallsInFlight.size}, rpcAge=${Number.isFinite(s)?`${s}ms`:"n/a"}), extending`),!0)}resetIdleTimer(){this.stopIdleTimer(),!(this.stopped||!this.isStreaming)&&(this.idleTimer=setTimeout(()=>{if(this.stopped||!this.isStreaming)return;if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const t=this.process?.pid,s=!!(this.alive&&t&&_(t))?`liveness budget exhausted after ${x/6e4}min`:"process not alive";o.error("pi-adapter",`Idle timeout (${s}, toolsInFlight=${this.toolCallsInFlight.size}) \u2014 emitting exit for respawn`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.activeEventId&&(this.emitPendingRunError(),this.callbacks.sendEventResult(this.activeEventId,"failed",`idle timeout: ${s}`)),this.clearActive(),this.emit("exit",-1)},st))}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}async ensureSessionReady(){return this.sessionReadyPromise?this.sessionReadyPromise:(this.sessionReadyPromise=this.restoreOrCreateSession().finally(()=>{this.sessionReadyPromise=null}),this.sessionReadyPromise)}async restoreOrCreateSession(){try{await this.switchSession();return}catch(t){this.piSessionPath&&o.error("pi-adapter",`switch_session failed, creating new session: ${t}`)}await this.createNewSession()}async switchSession(){if(!this.piSessionPath)throw new Error("no PI session path");const t=await this.transport.send("switch_session",{sessionPath:this.piSessionPath});if(!t.success)throw this.piSessionPath=null,this.persistPiSessionPath(void 0),new Error(`switch_session failed: ${t.error}`)}async createNewSession(){const t=await this.transport.send("new_session");if(!t.success)throw new Error(`new_session failed: ${t.error}`);let e=null;if(e=t.data?.sessionFile??null,!e)try{const i=await this.transport.send("get_state");i.success&&(e=i.data?.sessionFile??null)}catch{}this.piSessionPath=e,this.persistPiSessionPath(this.piSessionPath??void 0)}persistPiSessionPath(t){!this.bindingStore||!this.aibotSessionId||this.bindingStore.setPiSessionPath(this.aibotSessionId,t)}}export{w as PiAdapter};
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "bridgeVersion": "4.3.0",
4
- "tarball": "grix-dsh-bridge-4.3.0.tgz",
5
- "size": 22489,
3
+ "bridgeVersion": "4.3.2",
4
+ "tarball": "grix-dsh-bridge-4.3.2.tgz",
5
+ "size": 22532,
6
6
  "unpackedSize": 89865,
7
- "shasum": "446787a5a6ace52998f6c190a149aaa3da2f9943",
8
- "integrity": "sha512-2eNtxpcjfeLIiyxYt7cgwohggr5JMDGqD4RJEV1GhwOIUjqOK16mRZ6OwfAHMqNYhg+PwpLDKnN/KHWF14xBWg=="
7
+ "shasum": "14a642d07854f5b6c6fd68aa4f180bbf485cc77e",
8
+ "integrity": "sha512-Zz9BTYdKa95fWjhZP2e6Y8FhA0AI21ql1h9VSYpFMGbL53kiAIGszQBx+HAxn2m8Xr18DxsJ85ePxAIhsRa9dA=="
9
9
  }
@@ -1 +1 @@
1
- import{log as t}from"../core/log/index.js";const n=3e3,o=6e4,r=10,a=300*1e3,p=6e4,u=1e4,m=3;class c{attempts=0;slowRetryTimer=null;respawnTimer=null;healthCheckTimer=null;healthFailures=0;get exhausted(){return this.attempts>=r}resetAttempts(){this.attempts=0}resetHealthFailures(){this.healthFailures=0}stopSlowRetry(){this.slowRetryTimer&&(clearTimeout(this.slowRetryTimer),this.slowRetryTimer=null)}stopHealthCheck(){this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null)}stop(){this.stopSlowRetry(),this.respawnTimer&&(clearTimeout(this.respawnTimer),this.respawnTimer=null)}stopAll(){this.stopHealthCheck(),this.stop()}startHealthCheck(e){if(this.stopHealthCheck(),!e.pingAgent)return;this.healthFailures=0;const s=e.healthCheckIntervalMs??p,i=e.healthCheckTimeoutMs??u,h=e.healthCheckMaxFailures??m;this.healthCheckTimer=setInterval(()=>{if(e.stopped){this.stopHealthCheck();return}if(!e.pingAgent){this.stopHealthCheck();return}e.agentAlive!==!1&&e.pingAgent(i).then(l=>{l?this.healthFailures=0:(this.healthFailures++,t.info(e.name,`Health check failed (${this.healthFailures}/${h})`),this.healthFailures>=h&&(t.error(e.name,"Health check exhausted, triggering respawn"),this.healthFailures=0,e.onAbortActiveRun&&e.onAbortActiveRun("health check exhausted"),this.scheduleRespawn(e)))}).catch(()=>{this.healthFailures++,t.info(e.name,`Health check error (${this.healthFailures}/${h})`),this.healthFailures>=h&&(t.error(e.name,"Health check exhausted (error), triggering respawn"),this.healthFailures=0,e.onAbortActiveRun&&e.onAbortActiveRun("health check exhausted"),this.scheduleRespawn(e))})},s)}scheduleRespawn(e){try{e.onCleanupAgent()}catch{}if(this.respawnTimer&&(clearTimeout(this.respawnTimer),this.respawnTimer=null),this.attempts++,this.attempts>r){t.error(e.name,`Max respawn attempts reached, will retry in ${a/1e3}s`),this.scheduleSlowRetry(e);return}const s=Math.min(n*2**(this.attempts-1),o);t.info(e.name,`Respawn attempt ${this.attempts}/${r} in ${s}ms`),this.respawnTimer=setTimeout(()=>{this.respawnTimer=null,!e.stopped&&e.onRespawnNeeded().catch(i=>{t.error(e.name,`Respawn failed: ${i}`),this.scheduleRespawn(e)})},s)}scheduleSlowRetry(e){this.stopSlowRetry(),this.slowRetryTimer=setTimeout(()=>{e.stopped||(t.info(e.name,"Slow retry: attempting respawn"),this.attempts=0,e.onRespawnNeeded().catch(s=>{t.error(e.name,`Slow retry failed: ${s}`),this.scheduleRespawn(e)}))},a)}}export{c as RespawnManager};
1
+ import{log as t}from"../core/log/index.js";const o=3e3,p=6e4,r=10,l=300*1e3,u=6e4,n=1e4,m=3;class T{attempts=0;slowRetryTimer=null;respawnTimer=null;healthCheckTimer=null;healthFailures=0;get exhausted(){return this.attempts>=r}resetAttempts(){this.attempts=0}resetHealthFailures(){this.healthFailures=0}stopSlowRetry(){this.slowRetryTimer&&(clearTimeout(this.slowRetryTimer),this.slowRetryTimer=null)}stopHealthCheck(){this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null)}stop(){this.stopSlowRetry(),this.respawnTimer&&(clearTimeout(this.respawnTimer),this.respawnTimer=null)}stopAll(){this.stopHealthCheck(),this.stop()}startHealthCheck(e){if(this.stopHealthCheck(),!e.pingAgent)return;this.healthFailures=0;const h=e.healthCheckIntervalMs??u,i=e.healthCheckTimeoutMs??n,s=e.healthCheckMaxFailures??m;this.healthCheckTimer=setInterval(()=>{if(e.stopped){this.stopHealthCheck();return}if(!e.pingAgent){this.stopHealthCheck();return}e.agentAlive!==!1&&e.pingAgent(i).then(a=>{a?this.healthFailures=0:(this.healthFailures++,t.info(e.name,`Health check failed (${this.healthFailures}/${s})`),this.healthFailures>=s&&(t.error(e.name,"Health check exhausted, triggering respawn"),this.healthFailures=0,e.onAbortActiveRun&&e.onAbortActiveRun("health check exhausted"),this.scheduleRespawn(e,{recheckHealth:!0})))}).catch(()=>{this.healthFailures++,t.info(e.name,`Health check error (${this.healthFailures}/${s})`),this.healthFailures>=s&&(t.error(e.name,"Health check exhausted (error), triggering respawn"),this.healthFailures=0,e.onAbortActiveRun&&e.onAbortActiveRun("health check exhausted"),this.scheduleRespawn(e,{recheckHealth:!0}))})},h)}scheduleRespawn(e,h){try{e.onCleanupAgent()}catch{}if(this.respawnTimer&&(clearTimeout(this.respawnTimer),this.respawnTimer=null),this.attempts++,this.attempts>r){t.error(e.name,`Max respawn attempts reached, will retry in ${l/1e3}s`),this.scheduleSlowRetry(e);return}const i=Math.min(o*2**(this.attempts-1),p);t.info(e.name,`Respawn attempt ${this.attempts}/${r} in ${i}ms`),this.respawnTimer=setTimeout(async()=>{if(this.respawnTimer=null,!e.stopped){if(h?.recheckHealth&&e.pingAgent&&e.agentAlive!==!1){const s=e.healthCheckTimeoutMs??n,a=await e.pingAgent(s).catch(()=>!1);if(e.stopped)return;if(a){t.info(e.name,"Agent recovered before respawn fired; skipping respawn"),this.attempts=0,this.healthFailures=0;return}}e.onRespawnNeeded().catch(s=>{t.error(e.name,`Respawn failed: ${s}`),this.scheduleRespawn(e)})}},i)}scheduleSlowRetry(e){this.stopSlowRetry(),this.slowRetryTimer=setTimeout(()=>{e.stopped||(t.info(e.name,"Slow retry: attempting respawn"),this.attempts=0,e.onRespawnNeeded().catch(h=>{t.error(e.name,`Slow retry failed: ${h}`),this.scheduleRespawn(e)}))},l)}}export{T as RespawnManager};
@@ -1,3 +1,3 @@
1
- import{isRequestTimeoutError as E}from"../core/aibot/errors.js";import{log as f}from"../core/log/index.js";import{splitTextForAibotProtocol as p,AIBOT_PROTOCOL_MAX_RUNES as C}from"../core/protocol/protocol-text.js";import{isThinkingEventDropped as k,isToolEventDropped as y,normalizeRuntimeConfigSnapshot as S}from"./runtime-config.js";const q={claude:!1,acp:!1,codex:!0,codewhale:!0,pi:!0,openhuman:!1,cursor:!1,opencode:!0,agy:!0,"deepseek-harness":!1};class _{handle;connectorRuntimeConfig;eventRuntimeConfigs=new Map;eventQuotedMessageIds=new Map;defaultQuoteTrigger=!1;thinkingSeqMap=new Map;thinkingSessionMap=new Map;toolCardSeq=0;bufferedEventTexts=new Map;singleMessageDeliveries=new Map;chunkSeqMap=new Map;rejectedEvents=new Set;terminalEvents=new Set;static MAX_TERMINAL_EVENTS=1e3;stoppedEvents=new Set;streamCoalesce=new Map;streamCoalesceMs=T();static STREAM_COALESCE_MAX_RUNES=2048;recentToolCards=new Map;static TOOL_CARD_DEDUP_MS=100;constructor(e){this.connectorRuntimeConfig={...e}}bind(e){this.handle=e}markEventRejected(e){if(!e)return;this.rejectedEvents.add(e);const t=`${e}:`;for(const s of[...this.streamCoalesce.keys()])if(s.startsWith(t)){const n=this.streamCoalesce.get(s);n.timer&&clearTimeout(n.timer),this.streamCoalesce.delete(s)}f.info("send-ctrl",`event marked as stream-rejected, future chunks will be dropped event=${e}`)}markEventTerminal(e){if(!(!e||this.terminalEvents.has(e))&&(this.terminalEvents.add(e),this.terminalEvents.size>_.MAX_TERMINAL_EVENTS)){const t=this.terminalEvents.values().next().value;t!==void 0&&this.terminalEvents.delete(t)}}isEventClosed(e){return!!e&&(this.rejectedEvents.has(e)||this.terminalEvents.has(e))}markEventStopped(e){e&&(this.stoppedEvents.add(e),f.info("send-ctrl",`[stop-trace] event marked stopped; subsequent outbound will be flagged event=${e}`))}flagOutboundAfterStop(e,t,s,n,r,a){!e||!this.stoppedEvents.has(e)||f.warn("send-ctrl",`[stop-trace] OUTBOUND AFTER STOP ${s} event=${e} session=${t} seq=${n} is_finish=${r} len=${a}`)}getGlobalRuntimeConfig(){return this.connectorRuntimeConfig}setStreamCoalesceMs(e){this.streamCoalesceMs=Number.isFinite(e)&&e>0?Math.floor(e):0}captureEventRuntimeConfig(e){this.terminalEvents.delete(e.event_id);const t=S(e.connector_runtime_config);if(t||!this.eventRuntimeConfigs.has(e.event_id)){const s=t??this.connectorRuntimeConfig;this.eventRuntimeConfigs.set(e.event_id,{responseDelivery:s.responseDelivery,toolEvents:s.toolEvents,thinkingEvents:s.thinkingEvents})}e.msg_id&&!this.eventQuotedMessageIds.has(e.event_id)&&this.eventQuotedMessageIds.set(e.event_id,e.msg_id)}discardEventState(e){e&&(this.markEventTerminal(e),this.clearEventTrackingState(e))}clearEventTrackingState(e){this.eventRuntimeConfigs.delete(e),this.eventQuotedMessageIds.delete(e),this.rejectedEvents.delete(e),this.singleMessageDeliveries.delete(e),this.thinkingSeqMap.delete(e),this.thinkingSessionMap.delete(e),this.bufferedEventTexts.delete(e);for(const t of[...this.streamCoalesce.keys()])if(t.startsWith(`${e}:`)){const s=this.streamCoalesce.get(t);s.timer&&clearTimeout(s.timer),this.streamCoalesce.delete(t)}this.stoppedEvents.delete(e)&&f.info("send-ctrl",`[stop-trace] event tracking cleared stop flag event=${e}`);for(const t of this.chunkSeqMap.keys())t.startsWith(`${e}:`)&&this.chunkSeqMap.delete(t);for(const t of this.recentToolCards.keys())t.startsWith(`${e}:`)&&this.recentToolCards.delete(t)}setDefaultQuoteTrigger(e){this.defaultQuoteTrigger=e}getDefaultQuotedMessageId(e){if(!(!this.defaultQuoteTrigger||!e))return this.eventQuotedMessageIds.get(e)}resolveEventRuntimeConfig(e){if(e){const t=this.eventRuntimeConfigs.get(e);if(t)return t}return this.connectorRuntimeConfig}shouldDropToolDisplayEvent(e){return y(this.resolveEventRuntimeConfig(e))}shouldDropThinkingDisplayEvent(e){return k(this.resolveEventRuntimeConfig(e))}shouldDropCodexDisplayEvent(e,t){return this.shouldDropToolDisplayEvent(e)?t==="item/completed":!1}shouldDropAcpRawDisplayEvent(e,t){return!!(this.shouldDropToolDisplayEvent(e)&&(t==="tool_use"||t==="tool_result")||this.shouldDropThinkingDisplayEvent(e)&&t==="thinking")}sendReply(e,t,s,n,r,a){if(!a?.skipToolFilter&&this.shouldDropToolDisplayEvent(e)&&D(s,r)||this.isEventClosed(e))return;if(this.flagOutboundAfterStop(e,t,"reply",0,!1,(s||"").length),this.resolveEventRuntimeConfig(e).responseDelivery==="stream"&&!r){const i=p(s),l=e?`reply_stream_${e}`:`reply_stream_${Date.now()}`;if(i.length===0){this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:s||" ",quoted_message_id:n||void 0});return}for(let u=0;u<i.length;u++){const c=u===i.length-1;this.sendStreamChunk(e,t,i[u],u+1,c,l,n)}return}this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:s,quoted_message_id:n||void 0,...r?{extra:r}:{}})}sendStreamChunk(e,t,s,n,r,a,o){if(this.isEventClosed(e))return;if(o=o??this.getDefaultQuotedMessageId(e),this.flagOutboundAfterStop(e,t,"stream_chunk",n,r,(s||"").length),this.resolveEventRuntimeConfig(e).responseDelivery==="single_message"&&e){this.bufferStreamChunk(e,t,s,r,o);return}if(this.streamCoalesceMs<=0){this.emitStreamChunkParts(e,t,s,n,r,a,o);return}this.coalesceStreamChunk(e,t,s,r,a,o)}async sendFinalStreamChunkReliable(e,t,s,n,r=!1,a=!1){if(this.isEventClosed(e))throw new Error(`required agent output was already rejected or the event is terminal: event=${e}`);a||this.finalizeThinking(e,t);const o=this.resolveEventRuntimeConfig(e);if(!r&&o.responseDelivery==="single_message"&&e){if(this.flushCoalesceForEvent(e),await this.ensureSingleMessageDelivery(e,n),this.isEventClosed(e))throw new Error(`required agent output was rejected before terminal: event=${e}`);return}const i=`${e}:${s??"default"}`;this.flushCoalesce(i,!1),this.streamCoalesce.delete(i);const l=(this.chunkSeqMap.get(i)??0)+1;this.chunkSeqMap.set(i,l);const u=this.getDefaultQuotedMessageId(e),c={event_id:e,session_id:t,delta_content:"",chunk_seq:l,is_finish:!0,...s?{client_msg_id:s}:{},...u?{quoted_message_id:u}:{}};this.flagOutboundAfterStop(e,t,"stream_chunk_final",l,!0,0);const m=async()=>{const h=await this.handle.sendStreamChunkRequest(c,n);if(h.cmd!=="send_ack"){const g=h.payload;throw new Error(`final chunk rejected: cmd=${h.cmd} code=${g?.code??""} msg=${g?.msg??""}`)}};try{await m()}catch(h){if(E(h))f.warn("send-ctrl",`final chunk ACK timed out, retry request with same chunk_seq=${l} event=${e}`),await m();else throw f.warn("send-ctrl",`final chunk send failed (no resend) event=${e}: ${h}`),h}if(this.isEventClosed(e))throw new Error(`required agent output was rejected before terminal: event=${e}`)}async deliverAuxiliaryLargeText(e,t,s,n){if(!s||this.isEventClosed(e))return!1;if(this.resolveEventRuntimeConfig(e).responseDelivery==="single_message"&&e){const o=this.getDefaultQuotedMessageId(e),i=p(s);for(let l=0;l<i.length;l++)this.flagOutboundAfterStop(e,t,"aux_detail_msg",l+1,!1,i[l].length),this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:i[l],...l===0&&o?{quoted_message_id:o}:{},client_msg_id:i.length>1?`${n}_p${l+1}`:n});return!0}const a=p(s);for(const o of a)this.sendStreamChunk(e,t,o,0,!1,n);return await this.sendFinalStreamChunkReliable(e,t,n,void 0,!1,!0),!0}coalesceStreamChunk(e,t,s,n,r,a){if(!s&&!n)return;const o=`${e}:${r??"default"}`;let i=this.streamCoalesce.get(o);if(i||(i={eventId:e,sessionId:t,clientMsgId:r,quotedMessageId:a,text:"",flushedOnce:!1},this.streamCoalesce.set(o,i)),s&&(i.text+=s),i.sessionId=t,r!==void 0&&(i.clientMsgId=r),!i.quotedMessageId&&a&&(i.quotedMessageId=a),n){this.flushCoalesce(o,!0);return}if(!i.flushedOnce||i.text.length>=_.STREAM_COALESCE_MAX_RUNES){this.flushCoalesce(o,!1);return}i.timer||(i.timer=setTimeout(()=>this.flushCoalesce(o,!1),this.streamCoalesceMs))}flushCoalesce(e,t){const s=this.streamCoalesce.get(e);if(!s)return;s.timer&&(clearTimeout(s.timer),s.timer=void 0);const n=s.text;s.text="",s.flushedOnce=!0,t&&this.streamCoalesce.delete(e),!(!n&&!t)&&this.emitStreamChunkParts(s.eventId,s.sessionId,n,0,t,s.clientMsgId,s.quotedMessageId)}flushCoalesceForEvent(e){const t=`${e}:`;for(const s of[...this.streamCoalesce.keys()])s.startsWith(t)&&(this.flushCoalesce(s,!1),this.streamCoalesce.delete(s))}emitStreamChunkParts(e,t,s,n,r,a,o){const i=s||(r?`
2
- `:"");if(!i&&!r)return;const l=p(i,C);l.length===0&&l.push(i||`
3
- `);const u=`${e}:${a??"default"}`;for(let c=0;c<l.length;c++){const m=c===l.length-1,h=this.chunkSeqMap.get(u)??0,g=c===0&&n>h?n:h+1;this.chunkSeqMap.set(u,g),this.handle.sendStreamChunk({event_id:e,session_id:t,delta_content:l[c],chunk_seq:g,is_finish:m&&r,...a?{client_msg_id:a}:{},...o?{quoted_message_id:o}:{}})}}sendEventResult(e,t,s,n){this.finalizeThinking(e,""),this.flushCoalesceForEvent(e);const r=this.ensureSingleMessageDelivery(e),a=(o,i=s,l=n)=>{o==="responded"&&this.rejectedEvents.has(e)&&(o="failed",l=l||"agent_output_rejected",i=i||"required agent output was rejected by the server"),this.markEventTerminal(e),this.handle.sendEventResult({event_id:e,status:o,...i?{msg:i}:{},...l?{code:l}:{},updated_at:Date.now()}),this.clearEventTrackingState(e)};if(!r){a(t);return}r.then(()=>a(t),o=>{const i=`final output delivery failed: ${o instanceof Error?o.message:String(o)}`;a(t==="responded"?"failed":t,t==="responded"?i:s,t==="responded"?"agent_output_delivery_failed":n)})}sendThinking(e,t,s){if(this.shouldDropThinkingDisplayEvent(e)||this.isEventClosed(e))return;this.flagOutboundAfterStop(e,t,"thinking",this.thinkingSeqMap.get(e)??0,!1,(s||"").length);const n=(this.thinkingSeqMap.get(e)??0)+1;this.thinkingSeqMap.set(e,n),this.thinkingSessionMap.set(e,t),this.handle.sendStreamChunk({event_id:e,session_id:t,delta_content:s,chunk_seq:n,is_finish:!1,client_msg_id:`${e}_thinking`,is_thinking:!0})}sendToolExecutionCard(e,t,s,n){if(this.shouldDropToolDisplayEvent(e)){f.info("send-ctrl",`[tool-card] DROP event=${e} session=${t} summary=${s.summaryText}`);return}const a=Date.now(),o=`${e}:${s.summaryText}:${s.detailText??""}`,i=this.recentToolCards.get(o);if(i!==void 0&&a-i<_.TOOL_CARD_DEDUP_MS){f.info("send-ctrl",`[tool-card] DEDUP event=${e} session=${t} summary=${s.summaryText}`);return}this.recentToolCards.set(o,a);const l={summary_text:s.summaryText};s.detailText&&(l.detail_text=s.detailText),f.info("send-ctrl",`[tool-card] SEND event=${e} session=${t} summary=${s.summaryText}`),this.handle.sendMsg({event_id:e,session_id:t,client_msg_id:n??`tool_${++this.toolCardSeq}_${Date.now()}`,msg_type:1,content:"",extra:{channel_data:{grix:{toolExecution:l}},agent_api_origin:!0}})}finalizeThinking(e,t){const s=this.thinkingSeqMap.get(e);s!==void 0&&(this.thinkingSeqMap.delete(e),t=t||this.thinkingSessionMap.get(e)||"",this.thinkingSessionMap.delete(e),t&&(this.isEventClosed(e)||this.handle.sendStreamChunk({event_id:e,session_id:t,delta_content:"",chunk_seq:s+1,is_finish:!0,client_msg_id:`${e}_thinking`,is_thinking:!0})))}bufferOnly(e,t,s,n,r){r=r??this.getDefaultQuotedMessageId(e),this.bufferStreamChunk(e,t,s,n,r)}bufferStreamChunk(e,t,s,n,r){const a=this.bufferedEventTexts.get(e);a?(s&&(a.text+=s),!a.quotedMessageId&&r&&(a.quotedMessageId=r)):this.bufferedEventTexts.set(e,{sessionId:t,text:s??"",quotedMessageId:r||void 0}),n&&this.ensureSingleMessageDelivery(e)?.catch(i=>{f.warn("send-ctrl",`single-message output delivery failed event=${e}: ${i instanceof Error?i.message:String(i)}`)})}ensureSingleMessageDelivery(e,t){const s=this.singleMessageDeliveries.get(e);if(s)return s;const n=this.bufferedEventTexts.get(e);if(!n||(this.bufferedEventTexts.delete(e),!n.text))return;const r=(async()=>{const a={event_id:e,session_id:n.sessionId,content:n.text,client_msg_id:`agent_single_${e}`,...n.quotedMessageId?{quoted_message_id:n.quotedMessageId}:{}},o=async()=>{const i=t===void 0?await this.handle.sendText(a):await this.handle.sendText(a,t);if(i.cmd!=="send_ack"){const l=i.payload;throw new Error(`single-message output rejected: cmd=${i.cmd} code=${l?.code??""} msg=${l?.msg??""}`)}};try{await o()}catch(i){if(!E(i))throw i;f.warn("send-ctrl",`single-message ACK timed out, retry request with stable client_msg_id=${a.client_msg_id} event=${e}`),await o()}})();return this.singleMessageDeliveries.set(e,r),r}}function T(){const d=process.env.GRIX_STREAM_COALESCE_MS;if(d===void 0||d==="")return 500;const e=Number(d);return Number.isFinite(e)&&e>=0?Math.floor(e):500}function D(d,e){return e&&typeof e=="object"&&e.channel_data?.grix?.toolExecution?!0:/^\[tool\]/.test(d)||/^\[tool result\]/.test(d)}export{q as DEFAULT_QUOTE_TRIGGER_BY_ADAPTER,_ as SendController};
1
+ import{isRequestTimeoutError as E}from"../core/aibot/errors.js";import{log as f}from"../core/log/index.js";import{splitTextForAibotProtocol as p,AIBOT_PROTOCOL_MAX_RUNES as C}from"../core/protocol/protocol-text.js";import{isThinkingEventDropped as k,isToolEventDropped as y,normalizeRuntimeConfigSnapshot as S}from"./runtime-config.js";const v={claude:!1,acp:!1,codex:!0,codewhale:!0,pi:!0,openhuman:!1,cursor:!1,opencode:!0,agy:!0,"deepseek-harness":!1};class _{handle;connectorRuntimeConfig;eventRuntimeConfigs=new Map;eventQuotedMessageIds=new Map;defaultQuoteTrigger=!1;thinkingSeqMap=new Map;thinkingSessionMap=new Map;toolCardSeq=0;bufferedEventTexts=new Map;singleMessageDeliveries=new Map;chunkSeqMap=new Map;rejectedEvents=new Set;terminalEvents=new Set;static MAX_TERMINAL_EVENTS=1e3;stoppedEvents=new Set;streamCoalesce=new Map;streamCoalesceMs=T();static STREAM_COALESCE_MAX_RUNES=2048;recentToolCards=new Map;static TOOL_CARD_DEDUP_MS=100;constructor(e){this.connectorRuntimeConfig={...e}}bind(e){this.handle=e}markEventRejected(e){if(!e)return;this.rejectedEvents.add(e);const t=`${e}:`;for(const s of[...this.streamCoalesce.keys()])if(s.startsWith(t)){const n=this.streamCoalesce.get(s);n.timer&&clearTimeout(n.timer),this.streamCoalesce.delete(s)}f.info("send-ctrl",`event marked as stream-rejected, future chunks will be dropped event=${e}`)}markEventTerminal(e){if(!(!e||this.terminalEvents.has(e))&&(this.terminalEvents.add(e),this.terminalEvents.size>_.MAX_TERMINAL_EVENTS)){const t=this.terminalEvents.values().next().value;t!==void 0&&this.terminalEvents.delete(t)}}isEventClosed(e){return!!e&&(this.rejectedEvents.has(e)||this.terminalEvents.has(e))}markEventStopped(e){e&&(this.stoppedEvents.add(e),f.info("send-ctrl",`[stop-trace] event marked stopped; subsequent outbound will be flagged event=${e}`))}flagOutboundAfterStop(e,t,s,n,o,a){!e||!this.stoppedEvents.has(e)||f.warn("send-ctrl",`[stop-trace] OUTBOUND AFTER STOP ${s} event=${e} session=${t} seq=${n} is_finish=${o} len=${a}`)}getGlobalRuntimeConfig(){return this.connectorRuntimeConfig}setStreamCoalesceMs(e){this.streamCoalesceMs=Number.isFinite(e)&&e>0?Math.floor(e):0}captureEventRuntimeConfig(e){this.terminalEvents.delete(e.event_id);const t=S(e.connector_runtime_config);if(t||!this.eventRuntimeConfigs.has(e.event_id)){const s=t??this.connectorRuntimeConfig;this.eventRuntimeConfigs.set(e.event_id,{responseDelivery:s.responseDelivery,toolEvents:s.toolEvents,thinkingEvents:s.thinkingEvents}),f.info("send-ctrl",`[runtime-config] event=${e.event_id} response_delivery=${s.responseDelivery} tool_events=${s.toolEvents} thinking_events=${s.thinkingEvents} source=${t?"event":"global"}`)}e.msg_id&&!this.eventQuotedMessageIds.has(e.event_id)&&this.eventQuotedMessageIds.set(e.event_id,e.msg_id)}discardEventState(e){e&&(this.markEventTerminal(e),this.clearEventTrackingState(e))}clearEventTrackingState(e){this.eventRuntimeConfigs.delete(e),this.eventQuotedMessageIds.delete(e),this.rejectedEvents.delete(e),this.singleMessageDeliveries.delete(e),this.thinkingSeqMap.delete(e),this.thinkingSessionMap.delete(e),this.bufferedEventTexts.delete(e);for(const t of[...this.streamCoalesce.keys()])if(t.startsWith(`${e}:`)){const s=this.streamCoalesce.get(t);s.timer&&clearTimeout(s.timer),this.streamCoalesce.delete(t)}this.stoppedEvents.delete(e)&&f.info("send-ctrl",`[stop-trace] event tracking cleared stop flag event=${e}`);for(const t of this.chunkSeqMap.keys())t.startsWith(`${e}:`)&&this.chunkSeqMap.delete(t);for(const t of this.recentToolCards.keys())t.startsWith(`${e}:`)&&this.recentToolCards.delete(t)}setDefaultQuoteTrigger(e){this.defaultQuoteTrigger=e}getDefaultQuotedMessageId(e){if(!(!this.defaultQuoteTrigger||!e))return this.eventQuotedMessageIds.get(e)}resolveEventRuntimeConfig(e){if(e){const t=this.eventRuntimeConfigs.get(e);if(t)return t}return this.connectorRuntimeConfig}shouldDropToolDisplayEvent(e){return y(this.resolveEventRuntimeConfig(e))}shouldDropThinkingDisplayEvent(e){return k(this.resolveEventRuntimeConfig(e))}shouldDropCodexDisplayEvent(e,t){return this.shouldDropToolDisplayEvent(e)?t==="item/completed":!1}shouldDropAcpRawDisplayEvent(e,t){return!!(this.shouldDropToolDisplayEvent(e)&&(t==="tool_use"||t==="tool_result")||this.shouldDropThinkingDisplayEvent(e)&&t==="thinking")}sendReply(e,t,s,n,o,a){if(!a?.skipToolFilter&&this.shouldDropToolDisplayEvent(e)&&$(s,o)||this.isEventClosed(e))return;if(this.flagOutboundAfterStop(e,t,"reply",0,!1,(s||"").length),this.resolveEventRuntimeConfig(e).responseDelivery==="stream"&&!o){const i=p(s),l=e?`reply_stream_${e}`:`reply_stream_${Date.now()}`;if(i.length===0){this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:s||" ",quoted_message_id:n||void 0});return}for(let u=0;u<i.length;u++){const c=u===i.length-1;this.sendStreamChunk(e,t,i[u],u+1,c,l,n)}return}this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:s,quoted_message_id:n||void 0,...o?{extra:o}:{}})}sendStreamChunk(e,t,s,n,o,a,r){if(this.isEventClosed(e))return;if(r=r??this.getDefaultQuotedMessageId(e),this.flagOutboundAfterStop(e,t,"stream_chunk",n,o,(s||"").length),this.resolveEventRuntimeConfig(e).responseDelivery==="single_message"&&e){this.bufferStreamChunk(e,t,s,r,a);return}if(this.streamCoalesceMs<=0){this.emitStreamChunkParts(e,t,s,n,o,a,r);return}this.coalesceStreamChunk(e,t,s,o,a,r)}async sendFinalStreamChunkReliable(e,t,s,n,o=!1,a=!1){if(this.isEventClosed(e))throw new Error(`required agent output was already rejected or the event is terminal: event=${e}`);a||this.finalizeThinking(e,t);const r=this.resolveEventRuntimeConfig(e);if(!o&&r.responseDelivery==="single_message"&&e){if(this.flushCoalesceForEvent(e),await this.ensureSingleMessageDelivery(e,n),this.isEventClosed(e))throw new Error(`required agent output was rejected before terminal: event=${e}`);return}const i=`${e}:${s??"default"}`;this.flushCoalesce(i,!1),this.streamCoalesce.delete(i);const l=(this.chunkSeqMap.get(i)??0)+1;this.chunkSeqMap.set(i,l);const u=this.getDefaultQuotedMessageId(e),c={event_id:e,session_id:t,delta_content:"",chunk_seq:l,is_finish:!0,...s?{client_msg_id:s}:{},...u?{quoted_message_id:u}:{}};this.flagOutboundAfterStop(e,t,"stream_chunk_final",l,!0,0);const m=async()=>{const h=await this.handle.sendStreamChunkRequest(c,n);if(h.cmd!=="send_ack"){const g=h.payload;throw new Error(`final chunk rejected: cmd=${h.cmd} code=${g?.code??""} msg=${g?.msg??""}`)}};try{await m()}catch(h){if(E(h))f.warn("send-ctrl",`final chunk ACK timed out, retry request with same chunk_seq=${l} event=${e}`),await m();else throw f.warn("send-ctrl",`final chunk send failed (no resend) event=${e}: ${h}`),h}if(this.isEventClosed(e))throw new Error(`required agent output was rejected before terminal: event=${e}`)}async deliverAuxiliaryLargeText(e,t,s,n){if(!s||this.isEventClosed(e))return!1;if(this.resolveEventRuntimeConfig(e).responseDelivery==="single_message"&&e){const r=this.getDefaultQuotedMessageId(e),i=p(s);for(let l=0;l<i.length;l++)this.flagOutboundAfterStop(e,t,"aux_detail_msg",l+1,!1,i[l].length),this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:i[l],...l===0&&r?{quoted_message_id:r}:{},client_msg_id:i.length>1?`${n}_p${l+1}`:n});return!0}const a=p(s);for(const r of a)this.sendStreamChunk(e,t,r,0,!1,n);return await this.sendFinalStreamChunkReliable(e,t,n,void 0,!1,!0),!0}coalesceStreamChunk(e,t,s,n,o,a){if(!s&&!n)return;const r=`${e}:${o??"default"}`;let i=this.streamCoalesce.get(r);if(i||(i={eventId:e,sessionId:t,clientMsgId:o,quotedMessageId:a,text:"",flushedOnce:!1},this.streamCoalesce.set(r,i)),s&&(i.text+=s),i.sessionId=t,o!==void 0&&(i.clientMsgId=o),!i.quotedMessageId&&a&&(i.quotedMessageId=a),n){this.flushCoalesce(r,!0);return}if(!i.flushedOnce||i.text.length>=_.STREAM_COALESCE_MAX_RUNES){this.flushCoalesce(r,!1);return}i.timer||(i.timer=setTimeout(()=>this.flushCoalesce(r,!1),this.streamCoalesceMs))}flushCoalesce(e,t){const s=this.streamCoalesce.get(e);if(!s)return;s.timer&&(clearTimeout(s.timer),s.timer=void 0);const n=s.text;s.text="",s.flushedOnce=!0,t&&this.streamCoalesce.delete(e),!(!n&&!t)&&this.emitStreamChunkParts(s.eventId,s.sessionId,n,0,t,s.clientMsgId,s.quotedMessageId)}flushCoalesceForEvent(e){const t=`${e}:`;for(const s of[...this.streamCoalesce.keys()])s.startsWith(t)&&(this.flushCoalesce(s,!1),this.streamCoalesce.delete(s))}emitStreamChunkParts(e,t,s,n,o,a,r){const i=s||(o?`
2
+ `:"");if(!i&&!o)return;const l=p(i,C);l.length===0&&l.push(i||`
3
+ `);const u=`${e}:${a??"default"}`;for(let c=0;c<l.length;c++){const m=c===l.length-1,h=this.chunkSeqMap.get(u)??0,g=c===0&&n>h?n:h+1;this.chunkSeqMap.set(u,g),this.handle.sendStreamChunk({event_id:e,session_id:t,delta_content:l[c],chunk_seq:g,is_finish:m&&o,...a?{client_msg_id:a}:{},...r?{quoted_message_id:r}:{}})}}sendEventResult(e,t,s,n){this.finalizeThinking(e,""),this.flushCoalesceForEvent(e);const o=this.ensureSingleMessageDelivery(e),a=(r,i=s,l=n)=>{r==="responded"&&this.rejectedEvents.has(e)&&(r="failed",l=l||"agent_output_rejected",i=i||"required agent output was rejected by the server"),this.markEventTerminal(e),this.handle.sendEventResult({event_id:e,status:r,...i?{msg:i}:{},...l?{code:l}:{},updated_at:Date.now()}),this.clearEventTrackingState(e)};if(!o){a(t);return}o.then(()=>a(t),r=>{const i=`final output delivery failed: ${r instanceof Error?r.message:String(r)}`;a(t==="responded"?"failed":t,t==="responded"?i:s,t==="responded"?"agent_output_delivery_failed":n)})}sendThinking(e,t,s){if(this.shouldDropThinkingDisplayEvent(e)||this.isEventClosed(e))return;this.flagOutboundAfterStop(e,t,"thinking",this.thinkingSeqMap.get(e)??0,!1,(s||"").length);const n=(this.thinkingSeqMap.get(e)??0)+1;this.thinkingSeqMap.set(e,n),this.thinkingSessionMap.set(e,t),this.handle.sendStreamChunk({event_id:e,session_id:t,delta_content:s,chunk_seq:n,is_finish:!1,client_msg_id:`${e}_thinking`,is_thinking:!0})}sendToolExecutionCard(e,t,s,n){if(this.shouldDropToolDisplayEvent(e)){f.info("send-ctrl",`[tool-card] DROP event=${e} session=${t} summary=${s.summaryText}`);return}const a=Date.now(),r=`${e}:${s.summaryText}:${s.detailText??""}`,i=this.recentToolCards.get(r);if(i!==void 0&&a-i<_.TOOL_CARD_DEDUP_MS){f.info("send-ctrl",`[tool-card] DEDUP event=${e} session=${t} summary=${s.summaryText}`);return}this.recentToolCards.set(r,a);const l={summary_text:s.summaryText};s.detailText&&(l.detail_text=s.detailText),f.info("send-ctrl",`[tool-card] SEND event=${e} session=${t} summary=${s.summaryText}`),this.handle.sendMsg({event_id:e,session_id:t,client_msg_id:n??`tool_${++this.toolCardSeq}_${Date.now()}`,msg_type:1,content:"",extra:{channel_data:{grix:{toolExecution:l}},agent_api_origin:!0}})}finalizeThinking(e,t){const s=this.thinkingSeqMap.get(e);s!==void 0&&(this.thinkingSeqMap.delete(e),t=t||this.thinkingSessionMap.get(e)||"",this.thinkingSessionMap.delete(e),t&&(this.isEventClosed(e)||this.handle.sendStreamChunk({event_id:e,session_id:t,delta_content:"",chunk_seq:s+1,is_finish:!0,client_msg_id:`${e}_thinking`,is_thinking:!0})))}bufferOnly(e,t,s,n,o){o=o??this.getDefaultQuotedMessageId(e),this.bufferStreamChunk(e,t,s,o)}bufferStreamChunk(e,t,s,n,o){const a=typeof o=="string"&&o.startsWith("reply_"),r=this.bufferedEventTexts.get(e);if(!r){this.bufferedEventTexts.set(e,{sessionId:t,text:s??"",quotedMessageId:n||void 0,replyReceived:a});return}a?r.replyReceived?s&&(r.text+=s):(r.text=s??"",r.replyReceived=!0):!r.replyReceived&&s&&(r.text+=s),!r.quotedMessageId&&n&&(r.quotedMessageId=n)}ensureSingleMessageDelivery(e,t){const s=this.singleMessageDeliveries.get(e);if(s)return s;const n=this.bufferedEventTexts.get(e);if(!n||(this.bufferedEventTexts.delete(e),!n.text))return;const o=(async()=>{const a={event_id:e,session_id:n.sessionId,content:n.text,client_msg_id:`agent_single_${e}`,...n.quotedMessageId?{quoted_message_id:n.quotedMessageId}:{}},r=async()=>{const i=t===void 0?await this.handle.sendText(a):await this.handle.sendText(a,t);if(i.cmd!=="send_ack"){const l=i.payload;throw new Error(`single-message output rejected: cmd=${i.cmd} code=${l?.code??""} msg=${l?.msg??""}`)}};try{await r()}catch(i){if(!E(i))throw i;f.warn("send-ctrl",`single-message ACK timed out, retry request with stable client_msg_id=${a.client_msg_id} event=${e}`),await r()}})();return this.singleMessageDeliveries.set(e,o),o}}function T(){const d=process.env.GRIX_STREAM_COALESCE_MS;if(d===void 0||d==="")return 500;const e=Number(d);return Number.isFinite(e)&&e>=0?Math.floor(e):500}function $(d,e){return e&&typeof e=="object"&&e.channel_data?.grix?.toolExecution?!0:/^\[tool\]/.test(d)||/^\[tool result\]/.test(d)}export{v as DEFAULT_QUOTE_TRIGGER_BY_ADAPTER,_ as SendController};
@@ -1,2 +1,2 @@
1
- import{mkdir as S}from"node:fs/promises";import{open as d,readFile as g,unlink as s}from"node:fs/promises";import{join as f}from"node:path";import{randomUUID as v}from"node:crypto";import{readJSONFile as k,writeJSONFileAtomic as c}from"../util/json-file.js";import{appendRotatingFileSync as w}from"../log/rotation.js";const l=20,p=3e4,y=5e3;class U{statePath;logPath;lockPath;rotationOptions;constructor(e,a,n=e+".lock",o={}){this.statePath=e,this.logPath=a,this.lockPath=n,this.rotationOptions=o}get filePath(){return this.statePath}async recordHookEvent(e){const a=P(e);await this.withStateLock(async n=>{n.recent_events.push(a),n.recent_events.sort((o,i)=>o.event_at-i.event_at),n.recent_events.length>l&&(n.recent_events=n.recent_events.slice(-l)),n.latest_event=a,n.updated_at=Date.now()}),this.appendEventLog(a)}async readState(){const e=k(this.statePath);return!e||typeof e!="object"?this.emptyState():this.normalizeState(e)}async reset(){await this.withStateLock(async()=>{await c(this.statePath,this.emptyState())})}emptyState(){return{schema_version:1,updated_at:0,latest_event:null,recent_events:[]}}normalizeState(e){const a=Array.isArray(e.recent_events)?e.recent_events:[];return{schema_version:1,updated_at:e.updated_at??0,latest_event:e.latest_event?_(e.latest_event):null,recent_events:a.filter(n=>typeof n=="object"&&n!==null).map(_)}}async withStateLock(e){await S(f(this.statePath,"..").replace(/\/[^/]+$/,""),{recursive:!0}).catch(()=>{});const a=Date.now()+y;let n=!1;for(;!n&&Date.now()<a;)try{await(await d(this.lockPath,"wx")).close(),n=!0}catch(o){if(o.code==="EEXIST"){const m=await g(this.lockPath,"utf8").catch(()=>""),r=Number(m);!isNaN(r)&&Date.now()-r>p?await s(this.lockPath).catch(()=>{}):await new Promise(u=>setTimeout(u,100))}else throw o}if(!n)throw new Error("hook-signal-store: lock acquisition timeout");try{await D(this.lockPath,String(Date.now()));const o=await this.readState(),i=await e(o);return await c(this.statePath,o),i}finally{await s(this.lockPath).catch(()=>{})}}appendEventLog(e){const a=E(e),n=`${new Date(e.event_at).toISOString()} ${a}
2
- `;try{w(this.logPath,n,this.rotationOptions)}catch{}}}function h(t){if(t!=null){if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}}function P(t){return{event_id:v(),hook_event_name:String(t.hook_event_name??""),event_at:Date.now(),detail:T(t),tool_input:h(t.tool_input)}}function _(t){return{event_id:String(t.event_id??""),hook_event_name:String(t.hook_event_name??""),event_at:t.event_at??0,detail:String(t.detail??""),tool_input:h(t.tool_input)}}function E(t){const e=t.hook_event_name,a=t.detail?`:${t.detail}`:"";return`${e}${a}`}function T(t){switch(String(t.hook_event_name??"")){case"SessionStart":return String(t.source??"");case"PreToolUse":case"PermissionRequest":case"PostToolUse":case"PostToolUseFailure":case"PermissionDenied":return String(t.tool_name??t.reason??"");case"Elicitation":return String(t.mode??"");case"ElicitationResult":return String(t.action??t.mode??"");case"Notification":return String(t.matcher??t.notification_type??t.type??"");case"StopFailure":return String(t.stop_reason??t.error??t.detail??"");case"Stop":return String(t.stop_reason??"");case"PreCompact":case"PostCompact":return String(t.trigger??"");case"ConfigChange":return String(t.source??"");default:return""}}async function D(t,e){const{writeFile:a}=await import("node:fs/promises");await a(t,e,"utf8")}export{U as HookSignalStore};
1
+ import{mkdir as S}from"node:fs/promises";import{open as d,readFile as g,unlink as s}from"node:fs/promises";import{join as v}from"node:path";import{randomUUID as f}from"node:crypto";import{readJSONFile as p,writeJSONFileAtomic as c}from"../util/json-file.js";import{appendRotatingFileSync as w}from"../log/rotation.js";const l=20,k=3e4,P=5e3;class b{statePath;logPath;lockPath;rotationOptions;constructor(e,a,n=e+".lock",o={}){this.statePath=e,this.logPath=a,this.lockPath=n,this.rotationOptions=o}get filePath(){return this.statePath}async recordHookEvent(e){const a=y(e);await this.withStateLock(async n=>{n.recent_events.push(a),n.recent_events.sort((o,r)=>o.event_at-r.event_at),n.recent_events.length>l&&(n.recent_events=n.recent_events.slice(-l)),n.latest_event=a,n.updated_at=Date.now()}),this.appendEventLog(a)}async readState(){const e=p(this.statePath);return!e||typeof e!="object"?this.emptyState():this.normalizeState(e)}async reset(){await this.withStateLock(async()=>{await c(this.statePath,this.emptyState())})}emptyState(){return{schema_version:1,updated_at:0,latest_event:null,recent_events:[]}}normalizeState(e){const a=Array.isArray(e.recent_events)?e.recent_events:[];return{schema_version:1,updated_at:e.updated_at??0,latest_event:e.latest_event?_(e.latest_event):null,recent_events:a.filter(n=>typeof n=="object"&&n!==null).map(_)}}async withStateLock(e){await S(v(this.statePath,"..").replace(/\/[^/]+$/,""),{recursive:!0}).catch(()=>{});const a=Date.now()+P;let n=!1;for(;!n&&Date.now()<a;)try{await(await d(this.lockPath,"wx")).close(),n=!0}catch(o){if(o.code==="EEXIST"){const m=await g(this.lockPath,"utf8").catch(()=>""),i=Number(m);!isNaN(i)&&Date.now()-i>k?await s(this.lockPath).catch(()=>{}):await new Promise(u=>setTimeout(u,100))}else throw o}if(!n)throw new Error("hook-signal-store: lock acquisition timeout");try{await O(this.lockPath,String(Date.now()));const o=await this.readState(),r=await e(o);return await c(this.statePath,o),r}finally{await s(this.lockPath).catch(()=>{})}}appendEventLog(e){const a=E(e),n=`${new Date(e.event_at).toISOString()} ${a}
2
+ `;try{w(this.logPath,n,this.rotationOptions)}catch{}}}function h(t){if(t!=null){if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}}function y(t){return{event_id:f(),hook_event_name:String(t.hook_event_name??""),event_at:Date.now(),detail:T(t),tool_input:h(t.tool_input)}}function _(t){return{event_id:String(t.event_id??""),hook_event_name:String(t.hook_event_name??""),event_at:t.event_at??0,detail:String(t.detail??""),tool_input:h(t.tool_input)}}function E(t){const e=t.hook_event_name,a=t.detail?`:${t.detail}`:"";return`${e}${a}`}function T(t){switch(String(t.hook_event_name??"")){case"SessionStart":return String(t.source??"");case"UserPromptSubmit":return D(String(t.prompt??""));case"PreToolUse":case"PermissionRequest":case"PostToolUse":case"PostToolUseFailure":case"PermissionDenied":return String(t.tool_name??t.reason??"");case"Elicitation":return String(t.mode??"");case"ElicitationResult":return String(t.action??t.mode??"");case"Notification":return String(t.matcher??t.notification_type??t.type??"");case"StopFailure":return String(t.stop_reason??t.error??t.detail??"");case"Stop":return String(t.stop_reason??"");case"PreCompact":case"PostCompact":return String(t.trigger??"");case"ConfigChange":return String(t.source??"");default:return""}}async function O(t,e){const{writeFile:a}=await import("node:fs/promises");await a(t,e,"utf8")}function D(t){const e=/<channel\b[^>]*\sevent_id="([^"]*)"/g;let a="",n;for(;(n=e.exec(t))!==null;)a=n[1];if(a)return a;try{const o=JSON.parse(t);return o?.meta?.event_id?String(o.meta.event_id):""}catch{return""}}export{b as HookSignalStore,D as extractGrixEventIdFromPrompt};
@@ -1,2 +1,2 @@
1
- import{accessSync as l,constants as w}from"node:fs";import{spawn as p,execSync as h}from"node:child_process";import{isAbsolute as P,join as m}from"node:path";const S=process.platform==="win32"?";":":";function C(t){try{return l(t,w.X_OK),!0}catch{return!1}}function H(t,e){const n=String(t??"").trim();if(!n||P(n))return n;const i=process.platform==="win32",r=String(e??process.env.PATH??""),s=[],o=new Set;for(const c of r.split(S)){const d=c.trim();if(!d)continue;if(i){const u=m(d,n+".cmd");o.has(u)||(o.add(u),s.push(u))}const a=m(d,n);o.has(a)||(o.add(a),s.push(a))}for(const c of s)if(C(c))return c;return console.warn(`[spawn:resolve] command="${n}" not found in PATH. candidates tried: [${s.join(", ")}] PATH=${r.substring(0,500)}${r.length>500?"...(truncated)":""}`),n}function N(t,e,n={}){const{cwd:i,env:r,...s}=n,o={stdio:s.stdio??["pipe","pipe","pipe"],env:r??{...process.env},cwd:i,windowsHide:!0,...s};if(process.platform==="win32"&&/\.(cmd|bat)$/i.test(t)){const d=process.env.ComSpec||"cmd.exe",a=`""${t}" ${e.join(" ")}"`;return{process:p(d,["/d","/s","/c",a],{...o,windowsVerbatimArguments:!0}),isCmdSpawn:!0}}return{process:p(t,e,{...o,detached:o.detached??process.platform!=="win32"}),isCmdSpawn:!1}}async function $(t){return!t||t<=0?[]:process.platform==="win32"?y(t):new Promise(e=>{const n=p("pgrep",["-g",String(t)],{stdio:"pipe",timeout:3e3}),i=[];n.stdout?.on("data",r=>{r.toString().split(`
2
- `).forEach(s=>{const o=parseInt(s.trim(),10);!isNaN(o)&&o>0&&i.push(o)})}),n.on("close",()=>e(i)),n.on("error",()=>e([]))})}function y(t){return new Promise(e=>{const n=s=>{e(s.split(/\r?\n/).map(o=>parseInt(o.trim(),10)).filter(o=>!isNaN(o)&&o>0))},i=p("wmic",["process","where",`(ParentProcessId=${t})`,"get","ProcessId"],{stdio:"pipe",windowsHide:!0});let r="";i.stdout?.on("data",s=>{r+=s.toString()}),i.on("close",s=>{if(s===0){n(r);return}f(t).then(e)}),i.on("error",()=>{f(t).then(e)})})}function f(t){return new Promise(e=>{const n=`${process.env.SystemRoot||"C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`,i=p(n,["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",`(Get-CimInstance Win32_Process -Filter 'ParentProcessId=${t}').ProcessId`],{stdio:"pipe",windowsHide:!0});let r="";i.stdout?.on("data",s=>{r+=s.toString()}),i.on("close",()=>{e(r.split(/\r?\n/).map(s=>parseInt(s.trim(),10)).filter(s=>!isNaN(s)&&s>0))}),i.on("error",()=>e([]))})}async function v(t,e=[]){return(await $(t)).some(i=>!e.includes(i))}function b(t,e="SIGTERM"){if(t.pid){if(process.platform==="win32"){try{h(`taskkill /pid ${t.pid} /T /F`,{stdio:"pipe",timeout:5e3,windowsHide:!0})}catch{t.kill(e)}return}try{process.kill(-t.pid,e)}catch{t.kill(e)}}}export{v as hasChildProcesses,b as killProcessGroup,$ as listGroupPids,H as resolveCommandPath,N as spawnCommand};
1
+ import{accessSync as w,constants as h}from"node:fs";import{spawn as d,execSync as P}from"node:child_process";import{isAbsolute as S,join as m}from"node:path";const $=process.platform==="win32"?";":":";function x(t){try{return w(t,h.X_OK),!0}catch{return!1}}function H(t,e){const n=String(t??"").trim();if(!n||S(n))return n;const r=process.platform==="win32",i=String(e??process.env.PATH??""),s=[],o=new Set;for(const c of i.split($)){const a=c.trim();if(!a)continue;if(r){const u=m(a,n+".cmd");o.has(u)||(o.add(u),s.push(u))}const p=m(a,n);o.has(p)||(o.add(p),s.push(p))}for(const c of s)if(x(c))return c;return console.warn(`[spawn:resolve] command="${n}" not found in PATH. candidates tried: [${s.join(", ")}] PATH=${i.substring(0,500)}${i.length>500?"...(truncated)":""}`),n}function C(t,e=process.platform){return e==="win32"&&/\.(cmd|bat)$/i.test(t)}function v(t){return t.length>0&&!/[\s"^&|<>()%!]/.test(t)?t:`"${t.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\*)$/,"$1$1")}"`}function f(t,e){const n=e.map(v).join(" ");return n?`""${t}" ${n}"`:`""${t}""`}function b(t,e,n=process.platform){return C(t,n)?{command:process.env.ComSpec||"cmd.exe",args:["/d","/s","/c",f(t,e)],windowsVerbatimArguments:!0}:{command:t,args:e,windowsVerbatimArguments:!1}}function N(t,e,n=process.platform){return n!=="win32"?{command:t,args:e,windowsVerbatimArguments:!1}:{command:process.env.ComSpec||"cmd.exe",args:["/d","/s","/c",f(t,e)],windowsVerbatimArguments:!0}}function V(t,e,n={}){const{cwd:r,env:i,...s}=n,o={stdio:s.stdio??["pipe","pipe","pipe"],env:i??{...process.env},cwd:r,windowsHide:!0,...s},c=b(t,e);return c.windowsVerbatimArguments?{process:d(c.command,c.args,{...o,windowsVerbatimArguments:!0}),isCmdSpawn:!0}:{process:d(t,e,{...o,detached:o.detached??process.platform!=="win32"}),isCmdSpawn:!1}}async function g(t){return!t||t<=0?[]:process.platform==="win32"?I(t):new Promise(e=>{const n=d("pgrep",["-g",String(t)],{stdio:"pipe",timeout:3e3}),r=[];n.stdout?.on("data",i=>{i.toString().split(`
2
+ `).forEach(s=>{const o=parseInt(s.trim(),10);!isNaN(o)&&o>0&&r.push(o)})}),n.on("close",()=>e(r)),n.on("error",()=>e([]))})}function I(t){return new Promise(e=>{const n=s=>{e(s.split(/\r?\n/).map(o=>parseInt(o.trim(),10)).filter(o=>!isNaN(o)&&o>0))},r=d("wmic",["process","where",`(ParentProcessId=${t})`,"get","ProcessId"],{stdio:"pipe",windowsHide:!0});let i="";r.stdout?.on("data",s=>{i+=s.toString()}),r.on("close",s=>{if(s===0){n(i);return}l(t).then(e)}),r.on("error",()=>{l(t).then(e)})})}function l(t){return new Promise(e=>{const n=`${process.env.SystemRoot||"C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`,r=d(n,["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",`(Get-CimInstance Win32_Process -Filter 'ParentProcessId=${t}').ProcessId`],{stdio:"pipe",windowsHide:!0});let i="";r.stdout?.on("data",s=>{i+=s.toString()}),r.on("close",()=>{e(i.split(/\r?\n/).map(s=>parseInt(s.trim(),10)).filter(s=>!isNaN(s)&&s>0))}),r.on("error",()=>e([]))})}async function k(t,e=[]){return(await g(t)).some(r=>!e.includes(r))}function T(t,e="SIGTERM"){if(t.pid){if(process.platform==="win32"){try{P(`taskkill /pid ${t.pid} /T /F`,{stdio:"pipe",timeout:5e3,windowsHide:!0})}catch{t.kill(e)}return}try{process.kill(-t.pid,e)}catch{t.kill(e)}}}export{f as buildWindowsCmdLine,k as hasChildProcesses,C as isWindowsShimPath,T as killProcessGroup,g as listGroupPids,v as quoteWindowsCmdArg,H as resolveCommandPath,b as resolveShimInvocation,N as resolveWindowsExecInvocation,V as spawnCommand};
@@ -1,2 +1,2 @@
1
- import{execFile as c}from"node:child_process";import{accessSync as b,constants as H,existsSync as A,statSync as T}from"node:fs";import{join as h,dirname as g,basename as $,delimiter as p}from"node:path";import{promisify as l}from"node:util";import{log as a}from"../log/logger.js";const I=3e3,C=5e3,d="__GRIX_SHELL_PATH__";function x(t,e){const n=[".cmd",".bat",".exe",""];for(const r of t)if(r)for(const i of n){const s=h(r,`${e}${i}`);if(A(s))return s}return null}const M=1e4,P={cache:null,inflight:null},S={cache:null,inflight:null},_={cache:null,inflight:null};let w=0;function q(){w++;for(const t of[P,S,_])t.cache=null,t.inflight=null}function m(t,e){if(t.cache&&Date.now()-t.cache.at<M)return Promise.resolve(t.cache.value);if(t.inflight)return t.inflight;const n=w,r=e().then(i=>(w===n&&(t.cache={value:i,at:Date.now()}),t.inflight===r&&(t.inflight=null),i),i=>{throw t.inflight===r&&(t.inflight=null),i});return t.inflight=r,r}function D(){return h(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe")}function W(){return m(P,async()=>{const t=l(c),e=async n=>{try{const{stdout:r}=await t(D(),["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",`[Environment]::GetEnvironmentVariable('Path','${n}')`],{timeout:5e3,encoding:"utf-8",windowsHide:!0});return r.split(";").map(i=>i.trim()).filter(Boolean)}catch(r){return a.warn("cli-probe",`\u8BFB\u53D6\u6CE8\u518C\u8868 ${n} PATH \u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),[]}};return[...await e("User"),...await e("Machine")]})}async function F(t){if(process.platform!=="win32")return null;const e=await W(),n=x(e,t)??await v(t);return n&&E(g(n)),n}function O(t){try{return T(t).isFile()?(b(t,H.X_OK),!0):!1}catch{return!1}}function y(t,e){for(const n of t){if(!n)continue;const r=h(n,e);if(O(r))return r}return null}const G=new Set(["sh","bash","zsh","ksh","dash","ash"]);function R(){return m(S,async()=>{const t=process.env.SHELL||"/bin/sh";if(!G.has($(t)))return a.info("cli-probe",`\u767B\u5F55 shell ${t} \u4E0D\u652F\u6301 -lic\uFF0C\u8DF3\u8FC7 shell PATH \u8BFB\u53D6`),[];const e=l(c);try{const n=e(t,["-lic",`printf '\\n${d}%s\\n' "$PATH"`],{timeout:C,killSignal:"SIGKILL",encoding:"utf-8"});n.child?.stdin?.end();const{stdout:r}=await n,i=r.split(/\r?\n/).reverse().find(s=>s.startsWith(d));return i?i.slice(d.length).split(p).map(s=>s.trim()).filter(Boolean):[]}catch(n){return a.warn("cli-probe",`\u8BFB\u53D6\u767B\u5F55 shell PATH \u5931\u8D25: ${n instanceof Error?n.message:String(n)}`),[]}})}function k(){return m(_,async()=>{const t=l(c),e=process.platform==="win32";try{const{stdout:n}=await t(e?"cmd.exe":"npm",e?["/c","npm","prefix","-g"]:["prefix","-g"],{timeout:5e3,killSignal:"SIGKILL",encoding:"utf-8",...e?{windowsHide:!0}:{}});return n.trim()||null}catch{return null}})}async function v(t){const e=await k();return e?process.platform==="win32"?x([e],t):y([h(e,"bin"),e],t):null}async function N(t){if(process.platform==="win32")return null;const e=await R(),n=y(e,t)??await v(t);return a.info("cli-probe",`\u767B\u5F55 shell PATH / npm \u5168\u5C40 bin \u515C\u5E95\u67E5\u627E ${t}: \u7ED3\u679C=${n??"\u672A\u627E\u5230"}`),n&&E(g(n)),n}function E(t){const e=process.env.PATH??"",n=process.platform==="win32"?(r,i)=>r.toLowerCase()===i.toLowerCase():(r,i)=>r===i;e.split(p).some(r=>n(r,t))||(process.env.PATH=e?`${e}${p}${t}`:t,a.info("cli-probe",`\u5DF2\u5C06 ${t} \u8FFD\u52A0\u5230\u5F53\u524D\u8FDB\u7A0B PATH\uFF08\u5B89\u88C5\u540E\u81EA\u6108\uFF09`))}async function B(t){const e=l(c),n=process.platform==="win32",r=n?"where":"which";try{const{stdout:i}=await e(r,[t],{timeout:3e3,encoding:"utf-8"}),s=i.trim().split(/\r?\n/).map(o=>o.trim()).filter(Boolean);if(s.length>0){if(n){const o=s.find(f=>/\.(cmd|bat)$/i.test(f));if(o)return o;const u=s.find(f=>/\.exe$/i.test(f));return u||s[0]}return s[0]}return await L(t)}catch{return await L(t)}}function L(t){return process.platform==="win32"?F(t):N(t)}async function J(t,e=["--version"],n=I){const r=l(c),i=process.platform==="win32";try{const s=i&&/\s/.test(t)&&!t.startsWith('"')?`"${t}"`:t,{stdout:o,stderr:u}=await r(s,e,{timeout:n,encoding:"utf-8",...i?{shell:!0}:{}});return{version:(o||u||"").trim().split(`
2
- `)[0]?.trim()||null||null}}catch(s){const o=s;return o.killed||o.code==="ETIMEDOUT"?{version:null,error:{code:"version_timeout",message:"version check timed out"}}:{version:null,error:{code:"cli_error",message:o.message??String(s)}}}}export{y as findPosixExecutableInDirs,x as findWindowsExecutableInDirs,J as getCliVersion,q as invalidateCliPathCache,B as resolveCliPath,N as resolvePosixInstalledCli,v as resolveViaNpmGlobalBin,F as resolveWindowsInstalledCli};
1
+ import{execFile as c}from"node:child_process";import{accessSync as L,constants as A,existsSync as H,statSync as I}from"node:fs";import{join as f,dirname as g,basename as T,delimiter as d}from"node:path";import{promisify as l}from"node:util";import{resolveWindowsExecInvocation as $}from"../runtime/spawn.js";import{log as a}from"../log/logger.js";const C=3e3,M=5e3,p="__GRIX_SHELL_PATH__";function x(n,e){const t=[".cmd",".bat",".exe",""];for(const r of n)if(r)for(const i of t){const o=f(r,`${e}${i}`);if(H(o))return o}return null}const D=1e4,P={cache:null,inflight:null},S={cache:null,inflight:null},_={cache:null,inflight:null};let w=0;function B(){w++;for(const n of[P,S,_])n.cache=null,n.inflight=null}function m(n,e){if(n.cache&&Date.now()-n.cache.at<D)return Promise.resolve(n.cache.value);if(n.inflight)return n.inflight;const t=w,r=e().then(i=>(w===t&&(n.cache={value:i,at:Date.now()}),n.inflight===r&&(n.inflight=null),i),i=>{throw n.inflight===r&&(n.inflight=null),i});return n.inflight=r,r}function W(){return f(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe")}function F(){return m(P,async()=>{const n=l(c),e=async t=>{try{const{stdout:r}=await n(W(),["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",`[Environment]::GetEnvironmentVariable('Path','${t}')`],{timeout:5e3,encoding:"utf-8",windowsHide:!0});return r.split(";").map(i=>i.trim()).filter(Boolean)}catch(r){return a.warn("cli-probe",`\u8BFB\u53D6\u6CE8\u518C\u8868 ${t} PATH \u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),[]}};return[...await e("User"),...await e("Machine")]})}async function O(n){if(process.platform!=="win32")return null;const e=await F(),t=x(e,n)??await y(n);return t&&E(g(t)),t}function G(n){try{return I(n).isFile()?(L(n,A.X_OK),!0):!1}catch{return!1}}function v(n,e){for(const t of n){if(!t)continue;const r=f(t,e);if(G(r))return r}return null}const R=new Set(["sh","bash","zsh","ksh","dash","ash"]);function k(){return m(S,async()=>{const n=process.env.SHELL||"/bin/sh";if(!R.has(T(n)))return a.info("cli-probe",`\u767B\u5F55 shell ${n} \u4E0D\u652F\u6301 -lic\uFF0C\u8DF3\u8FC7 shell PATH \u8BFB\u53D6`),[];const e=l(c);try{const t=e(n,["-lic",`printf '\\n${p}%s\\n' "$PATH"`],{timeout:M,killSignal:"SIGKILL",encoding:"utf-8"});t.child?.stdin?.end();const{stdout:r}=await t,i=r.split(/\r?\n/).reverse().find(o=>o.startsWith(p));return i?i.slice(p.length).split(d).map(o=>o.trim()).filter(Boolean):[]}catch(t){return a.warn("cli-probe",`\u8BFB\u53D6\u767B\u5F55 shell PATH \u5931\u8D25: ${t instanceof Error?t.message:String(t)}`),[]}})}function N(){return m(_,async()=>{const n=l(c),e=process.platform==="win32";try{const{stdout:t}=await n(e?"cmd.exe":"npm",e?["/c","npm","prefix","-g"]:["prefix","-g"],{timeout:5e3,killSignal:"SIGKILL",encoding:"utf-8",...e?{windowsHide:!0}:{}});return t.trim()||null}catch{return null}})}async function y(n){const e=await N();return e?process.platform==="win32"?x([e],n):v([f(e,"bin"),e],n):null}async function V(n){if(process.platform==="win32")return null;const e=await k(),t=v(e,n)??await y(n);return a.info("cli-probe",`\u767B\u5F55 shell PATH / npm \u5168\u5C40 bin \u515C\u5E95\u67E5\u627E ${n}: \u7ED3\u679C=${t??"\u672A\u627E\u5230"}`),t&&E(g(t)),t}function E(n){const e=process.env.PATH??"",t=process.platform==="win32"?(r,i)=>r.toLowerCase()===i.toLowerCase():(r,i)=>r===i;e.split(d).some(r=>t(r,n))||(process.env.PATH=e?`${e}${d}${n}`:n,a.info("cli-probe",`\u5DF2\u5C06 ${n} \u8FFD\u52A0\u5230\u5F53\u524D\u8FDB\u7A0B PATH\uFF08\u5B89\u88C5\u540E\u81EA\u6108\uFF09`))}async function J(n){const e=l(c),t=process.platform==="win32",r=t?"where":"which";try{const{stdout:i}=await e(r,[n],{timeout:3e3,encoding:"utf-8"}),o=i.trim().split(/\r?\n/).map(s=>s.trim()).filter(Boolean);if(o.length>0){if(t){const s=o.find(u=>/\.(cmd|bat)$/i.test(u));if(s)return s;const h=o.find(u=>/\.exe$/i.test(u));return h||o[0]}return o[0]}return await b(n)}catch{return await b(n)}}function b(n){return process.platform==="win32"?O(n):V(n)}async function Q(n,e=["--version"],t=C){const r=l(c);try{const i=$(n,e),{stdout:o,stderr:s}=await r(i.command,i.args,{timeout:t,encoding:"utf-8",windowsVerbatimArguments:i.windowsVerbatimArguments});return{version:(o||s||"").trim().split(`
2
+ `)[0]?.trim()||null||null}}catch(i){const o=i;return o.killed||o.code==="ETIMEDOUT"?{version:null,error:{code:"version_timeout",message:"version check timed out"}}:{version:null,error:{code:"cli_error",message:o.message??String(i)}}}}export{v as findPosixExecutableInDirs,x as findWindowsExecutableInDirs,Q as getCliVersion,B as invalidateCliPathCache,J as resolveCliPath,V as resolvePosixInstalledCli,y as resolveViaNpmGlobalBin,O as resolveWindowsInstalledCli};
@@ -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.3.0",
3
+ "version": "4.3.2",
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",