grix-connector 3.29.1 → 3.29.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- import{execFile as R}from"node:child_process";import{createHash as O,randomUUID as N}from"node:crypto";import{closeSync as G,copyFileSync as m,cpSync as P,existsSync as d,mkdirSync as b,openSync as C,readFileSync as f,rmSync as u,statSync as y,writeFileSync as B}from"node:fs";import{join as o,resolve as I}from"node:path";import{fileURLToPath as $}from"node:url";import{promisify as M}from"node:util";import{log as T}from"../../core/log/index.js";import{resolveCliPath as _}from"../../core/util/cli-probe.js";import{COMPATIBLE_DSH_VERSIONS as H,isCompatibleDshVersion as w}from"./bridge-session-reliability.js";import{bridgeDiscoveryDirectory as J,discoverDshBridgeEndpoints as L,resolveDshProfileIdentity as F}from"./profile-resolver.js";const z=M(R),U=2*1024*1024,p="@grix/dsh-bridge",q="deepseek-harness-bridge-installer",k=2,X=1e3;class ae{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 _(this.command),r=this.bridgeAsset(),i=this.readInstalledBridgeVersion(),s=r.version,n=L(this.identity),a=n.length===1?n[0].bridgeVersion:null,c=n.length===1?n[0].dshVersion:null,g=e?await A(e,this.options.dshHome):null;let l;return e?!w(g)||c!==null&&!w(c)?l="bridge_incompatible":d(this.identity.profileRoot)?i?i!==s||this.installedBridgeContentStale(r)?l="bridge_update_required":n.length===0?l="profile_restart_required":n.length!==1?l="bridge_incompatible":a!==i||this.runningBridgePredatesInstalledContent(n[0])?l="profile_restart_required":l="ready":l="bridge_missing":l="profile_missing":l="dsh_missing",{readiness:l,command:this.command,commandPath:e,dshVersion:g,runningDshVersion:c,identity:this.identity,installedBridgeVersion:i,bundledBridgeVersion:s,runningBridgeVersion:a,endpointCount:n.length,compatibleDshVersions:H}}async install(){const e=await _(this.command);if(!e)throw Object.assign(new Error(`${this.command} not found`),{code:"dsh_missing"});const r=await A(e,this.options.dshHome);if(!w(r))throw Object.assign(new Error(`DSH ${r??"unknown"} is outside the verified Bridge compatibility matrix (${H.join(", ")})`),{code:"bridge_incompatible"});const i=this.bridgeAsset();return j(this.identity,async()=>{await h(e,["--profile",this.identity.profileName,"--dump-config"],this.options.dshHome);const s=this.readInstalledBridgeVersion();if(s===i.version&&!this.installedBridgeContentStale(i))return this.status();const n=o(this.identity.dshHome,"assets","grix-dsh-bridge");b(n,{recursive:!0,mode:448});const a=this.captureInstallBackup(n,s),c=o(n,`grix-dsh-bridge-${i.version}.tgz`);m(i.tarball,c);try{if(s===i.version&&d(this.bridgePackageRoot())&&(await h(e,["plugin","--profile",this.identity.profileName,"remove",p],this.options.dshHome),d(this.bridgePackageRoot())))throw Object.assign(new Error(`dsh plugin remove left ${p} in place; refusing to attest an unverified reinstall`),{code:"bridge_install_failed"});await this.runPluginAdd(e,c),await h(e,["--profile",this.identity.profileName,"--dump-config"],this.options.dshHome);const g=this.readInstalledBridgeVersion();if(g!==i.version)throw Object.assign(new Error(`Bridge package did not land on disk (installed ${g??"none"}, expected ${i.version})`),{code:"bridge_install_failed"});this.writeInstalledBridgeIntegrity(i.integrity)}catch(g){await this.rollbackInstall(e,n,a,s);try{u(c,{force:!0})}catch{}throw Object.assign(new Error(`Bridge install failed: ${D(g)}`),{code:"bridge_install_failed"})}return this.discardInstallBackup(a),this.status()})}async uninstall(){const e=await _(this.command);if(!e)throw Object.assign(new Error(`${this.command} not found`),{code:"dsh_missing"});return j(this.identity,async()=>(this.readInstalledBridgeVersion()&&await h(e,["plugin","--profile",this.identity.profileName,"remove",p],this.options.dshHome),this.status()))}async runPluginAdd(e,r){const i=["plugin","--profile",this.identity.profileName,"add",r];let s;for(let n=1;n<=k;n++)try{await h(e,i,this.options.dshHome);return}catch(a){s=a,T.warn(q,`dsh plugin add attempt ${n}/${k} failed for profile ${this.identity.profileName}
2
- ${W(a)}`),n<k&&await new Promise(c=>setTimeout(c,X))}throw s}bridgePackageRoot(){return o(this.identity.profileRoot,"node_modules","@grix","dsh-bridge")}profilePackageJsonPath(){return o(this.identity.profileRoot,"package.json")}captureInstallBackup(e,r){const i=o(e,"rollback",`${Date.now()}-${N()}`);b(i,{recursive:!0,mode:448});const s=this.bridgePackageRoot(),n=d(s);n&&P(s,o(i,"dsh-bridge"),{recursive:!0});const a=this.profilePackageJsonPath(),c=d(a);c&&m(a,o(i,"package.json"));const g=["pnpm-lock.yaml","package-lock.json","yarn.lock"];for(const l of g){const v=o(this.identity.profileRoot,l);d(v)&&m(v,o(i,l))}return B(o(i,"manifest.json"),`${JSON.stringify({priorVersion:r,hadBridge:n,hadPackageJson:c})}
3
- `,{mode:384}),{root:i,priorVersion:r,hadBridge:n,hadPackageJson:c}}async rollbackInstall(e,r,i,s){const n=s?o(r,`grix-dsh-bridge-${s}.tgz`):null;if(n&&d(n)&&await h(e,["plugin","--profile",this.identity.profileName,"add",n],this.options.dshHome).then(()=>!0).catch(()=>!1)){this.discardInstallBackup(i);return}if(i.hadBridge&&d(o(i.root,"dsh-bridge"))){this.restoreFilesystemBackup(i),this.discardInstallBackup(i);return}s?i.hadPackageJson&&this.restoreFilesystemBackup(i):(await h(e,["plugin","--profile",this.identity.profileName,"remove",p],this.options.dshHome).catch(()=>{}),this.cleanHalfInstalledBridge()),this.discardInstallBackup(i)}restoreFilesystemBackup(e){const r=this.bridgePackageRoot(),i=o(e.root,"dsh-bridge");e.hadBridge&&d(i)&&(u(r,{recursive:!0,force:!0}),b(o(this.identity.profileRoot,"node_modules","@grix"),{recursive:!0,mode:448}),P(i,r,{recursive:!0})),e.hadPackageJson&&d(o(e.root,"package.json"))&&m(o(e.root,"package.json"),this.profilePackageJsonPath());for(const s of["pnpm-lock.yaml","package-lock.json","yarn.lock"]){const n=o(e.root,s);d(n)&&m(n,o(this.identity.profileRoot,s))}}cleanHalfInstalledBridge(){try{u(this.bridgePackageRoot(),{recursive:!0,force:!0})}catch{}const e=this.profilePackageJsonPath();if(d(e))try{const r=JSON.parse(f(e,"utf8"));let i=!1;for(const s of["dependencies","devDependencies","optionalDependencies","peerDependencies"]){const n=r[s];n&&typeof n=="object"&&!Array.isArray(n)&&p in n&&(delete n[p],i=!0)}i&&B(e,`${JSON.stringify(r,null,2)}
1
+ import{execFile as R}from"node:child_process";import{createHash as O,randomUUID as N}from"node:crypto";import{closeSync as G,copyFileSync as m,cpSync as P,existsSync as d,mkdirSync as b,openSync as C,readFileSync as f,rmSync as u,statSync as y,writeFileSync as B}from"node:fs";import{join as o,resolve as I}from"node:path";import{fileURLToPath as $}from"node:url";import{promisify as M}from"node:util";import{log as T}from"../../core/log/index.js";import{resolveCliPath as _}from"../../core/util/cli-probe.js";import{COMPATIBLE_DSH_VERSIONS as H,isCompatibleDshVersion as w}from"./bridge-session-reliability.js";import{bridgeDiscoveryDirectory as J,discoverDshBridgeEndpoints as L,resolveDshProfileIdentity as F}from"./profile-resolver.js";const z=M(R),U=2*1024*1024,p="@grix/dsh-bridge",q="deepseek-harness-bridge-installer",k=2,X=1e3;class ae{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 _(this.command),r=this.bridgeAsset(),i=this.readInstalledBridgeVersion(),s=r.version,n=L(this.identity),a=n[0]?.bridgeVersion??null,l=n[0]?.dshVersion??null,g=e?await A(e,this.options.dshHome):null;let c;return e?!w(g)||l!==null&&!w(l)?c="bridge_incompatible":d(this.identity.profileRoot)?i?i!==s||this.installedBridgeContentStale(r)?c="bridge_update_required":n.length===0||a!==i||this.runningBridgePredatesInstalledContent(n[0])?c="profile_restart_required":c="ready":c="bridge_missing":c="profile_missing":c="dsh_missing",{readiness:c,command:this.command,commandPath:e,dshVersion:g,runningDshVersion:l,identity:this.identity,installedBridgeVersion:i,bundledBridgeVersion:s,runningBridgeVersion:a,endpointCount:n.length,compatibleDshVersions:H}}async install(){const e=await _(this.command);if(!e)throw Object.assign(new Error(`${this.command} not found`),{code:"dsh_missing"});const r=await A(e,this.options.dshHome);if(!w(r))throw Object.assign(new Error(`DSH ${r??"unknown"} is outside the verified Bridge compatibility matrix (${H.join(", ")})`),{code:"bridge_incompatible"});const i=this.bridgeAsset();return j(this.identity,async()=>{await h(e,["--profile",this.identity.profileName,"--dump-config"],this.options.dshHome);const s=this.readInstalledBridgeVersion();if(s===i.version&&!this.installedBridgeContentStale(i))return this.status();const n=o(this.identity.dshHome,"assets","grix-dsh-bridge");b(n,{recursive:!0,mode:448});const a=this.captureInstallBackup(n,s),l=o(n,`grix-dsh-bridge-${i.version}.tgz`);m(i.tarball,l);try{if(s===i.version&&d(this.bridgePackageRoot())&&(await h(e,["plugin","--profile",this.identity.profileName,"remove",p],this.options.dshHome),d(this.bridgePackageRoot())))throw Object.assign(new Error(`dsh plugin remove left ${p} in place; refusing to attest an unverified reinstall`),{code:"bridge_install_failed"});await this.runPluginAdd(e,l),await h(e,["--profile",this.identity.profileName,"--dump-config"],this.options.dshHome);const g=this.readInstalledBridgeVersion();if(g!==i.version)throw Object.assign(new Error(`Bridge package did not land on disk (installed ${g??"none"}, expected ${i.version})`),{code:"bridge_install_failed"});this.writeInstalledBridgeIntegrity(i.integrity)}catch(g){await this.rollbackInstall(e,n,a,s);try{u(l,{force:!0})}catch{}throw Object.assign(new Error(`Bridge install failed: ${D(g)}`),{code:"bridge_install_failed"})}return this.discardInstallBackup(a),this.status()})}async uninstall(){const e=await _(this.command);if(!e)throw Object.assign(new Error(`${this.command} not found`),{code:"dsh_missing"});return j(this.identity,async()=>(this.readInstalledBridgeVersion()&&await h(e,["plugin","--profile",this.identity.profileName,"remove",p],this.options.dshHome),this.status()))}async runPluginAdd(e,r){const i=["plugin","--profile",this.identity.profileName,"add",r];let s;for(let n=1;n<=k;n++)try{await h(e,i,this.options.dshHome);return}catch(a){s=a,T.warn(q,`dsh plugin add attempt ${n}/${k} failed for profile ${this.identity.profileName}
2
+ ${W(a)}`),n<k&&await new Promise(l=>setTimeout(l,X))}throw s}bridgePackageRoot(){return o(this.identity.profileRoot,"node_modules","@grix","dsh-bridge")}profilePackageJsonPath(){return o(this.identity.profileRoot,"package.json")}captureInstallBackup(e,r){const i=o(e,"rollback",`${Date.now()}-${N()}`);b(i,{recursive:!0,mode:448});const s=this.bridgePackageRoot(),n=d(s);n&&P(s,o(i,"dsh-bridge"),{recursive:!0});const a=this.profilePackageJsonPath(),l=d(a);l&&m(a,o(i,"package.json"));const g=["pnpm-lock.yaml","package-lock.json","yarn.lock"];for(const c of g){const v=o(this.identity.profileRoot,c);d(v)&&m(v,o(i,c))}return B(o(i,"manifest.json"),`${JSON.stringify({priorVersion:r,hadBridge:n,hadPackageJson:l})}
3
+ `,{mode:384}),{root:i,priorVersion:r,hadBridge:n,hadPackageJson:l}}async rollbackInstall(e,r,i,s){const n=s?o(r,`grix-dsh-bridge-${s}.tgz`):null;if(n&&d(n)&&await h(e,["plugin","--profile",this.identity.profileName,"add",n],this.options.dshHome).then(()=>!0).catch(()=>!1)){this.discardInstallBackup(i);return}if(i.hadBridge&&d(o(i.root,"dsh-bridge"))){this.restoreFilesystemBackup(i),this.discardInstallBackup(i);return}s?i.hadPackageJson&&this.restoreFilesystemBackup(i):(await h(e,["plugin","--profile",this.identity.profileName,"remove",p],this.options.dshHome).catch(()=>{}),this.cleanHalfInstalledBridge()),this.discardInstallBackup(i)}restoreFilesystemBackup(e){const r=this.bridgePackageRoot(),i=o(e.root,"dsh-bridge");e.hadBridge&&d(i)&&(u(r,{recursive:!0,force:!0}),b(o(this.identity.profileRoot,"node_modules","@grix"),{recursive:!0,mode:448}),P(i,r,{recursive:!0})),e.hadPackageJson&&d(o(e.root,"package.json"))&&m(o(e.root,"package.json"),this.profilePackageJsonPath());for(const s of["pnpm-lock.yaml","package-lock.json","yarn.lock"]){const n=o(e.root,s);d(n)&&m(n,o(this.identity.profileRoot,s))}}cleanHalfInstalledBridge(){try{u(this.bridgePackageRoot(),{recursive:!0,force:!0})}catch{}const e=this.profilePackageJsonPath();if(d(e))try{const r=JSON.parse(f(e,"utf8"));let i=!1;for(const s of["dependencies","devDependencies","optionalDependencies","peerDependencies"]){const n=r[s];n&&typeof n=="object"&&!Array.isArray(n)&&p in n&&(delete n[p],i=!0)}i&&B(e,`${JSON.stringify(r,null,2)}
4
4
  `,{mode:384})}catch{}}discardInstallBackup(e){try{u(e.root,{recursive:!0,force:!0})}catch{}}readInstalledBridgeVersion(){const e=o(this.bridgePackageRoot(),"package.json");try{const r=JSON.parse(f(e,"utf8"));return typeof r.version=="string"?r.version:null}catch{return null}}installedIntegrityPath(){return o(this.bridgePackageRoot(),".grix-bridge-integrity")}readInstalledBridgeIntegrity(){try{const e=f(this.installedIntegrityPath(),"utf8").trim();return e.startsWith("sha512-")?e:null}catch{return null}}writeInstalledBridgeIntegrity(e){B(this.installedIntegrityPath(),`${e}
5
5
  `,{encoding:"utf8",mode:384})}installedBridgeContentStale(e=this.bridgeAsset()){return d(this.bridgePackageRoot())?this.readInstalledBridgeIntegrity()!==e.integrity:!0}runningBridgePredatesInstalledContent(e){try{const r=y(this.installedIntegrityPath()).mtimeMs,i=Date.parse(e.startedAt);return Number.isFinite(i)?r>i:!0}catch{return!1}}bridgeAsset(){return this.options.tarballPath?E(I(this.options.tarballPath)):x()}}function de(t){if(t.readiness==="ready")return null;const e=t.identity.profileName,r=`dsh --profile ${e}`,i=t.endpointCount>0&&t.runningBridgeVersion&&t.installedBridgeVersion&&t.runningBridgeVersion!==t.installedBridgeVersion?`Grix Bridge in DSH profile "${e}" is running version ${t.runningBridgeVersion}, but ${t.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}`,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 ${t.installedBridgeVersion??"none"}, expected ${t.bundledBridgeVersion}${t.installedBridgeVersion===t.bundledBridgeVersion?", content hash mismatch":""}). Update from the toolbar, then restart the profile \u2014 dsh does not hot-load plugin upgrades.`,profile_restart_required:i,bridge_incompatible:`DSH / Grix Bridge versions are incompatible for profile "${e}" (dsh=${t.dshVersion??"unknown"}, running=${t.runningDshVersion??"none"}, bridge=${t.runningBridgeVersion??t.installedBridgeVersion??"none"}). Supported DSH: ${t.compatibleDshVersions.join(", ")}.`};return Object.assign(new Error(s[t.readiness]),{code:t.readiness})}function le(){return x().tarball}function x(){const t=[$(new URL("../../assets/dsh-bridge/",import.meta.url)),$(new URL("../../../dist/assets/dsh-bridge/",import.meta.url))].find(i=>d(o(i,"manifest.json")));if(!t)throw Object.assign(new Error("Bundled Grix DSH Bridge asset is unavailable; run the Connector build first"),{code:"bridge_asset_missing"});const e=JSON.parse(f(o(t,"manifest.json"),"utf8"));if(typeof e.tarball!="string"||!e.tarball||typeof e.bridgeVersion!="string"||!e.bridgeVersion)throw Object.assign(new Error("Invalid Grix DSH Bridge asset manifest"),{code:"bridge_asset_invalid"});const r=E(o(t,e.tarball),e.bridgeVersion);if(Number(e.size)!==y(r.tarball).size)throw Object.assign(new Error("Grix DSH Bridge asset size mismatch"),{code:"bridge_asset_invalid"});if(typeof e.integrity=="string"&&e.integrity.startsWith("sha512-")&&e.integrity!==r.integrity)throw Object.assign(new Error("Grix DSH Bridge asset integrity mismatch"),{code:"bridge_asset_invalid"});return r}function E(t,e){if(!d(t)||!y(t).isFile())throw Object.assign(new Error(`Grix DSH Bridge asset is missing: ${t}`),{code:"bridge_asset_missing"});if(y(t).size>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(t)?.[1];if(!r)throw Object.assign(new Error("Cannot determine Grix DSH Bridge version"),{code:"bridge_asset_invalid"});const i=`sha512-${O("sha512").update(f(t)).digest("base64")}`;return{tarball:t,version:r,integrity:i}}async function j(t,e){const r=J(t);b(r,{recursive:!0,mode:448});const i=o(r,"install.lock");let s=V(i);if(s===null){let n=0;try{n=Number(f(i,"utf8").trim())}catch{}let a=!1;try{a=n===0&&Date.now()-y(i).mtimeMs>5*6e4}catch{}if(a||Number.isSafeInteger(n)&&n>0&&!Y(n)){try{u(i,{force:!0})}catch{}s=V(i)}}if(s===null)throw Object.assign(new Error(`Another Grix DSH Bridge install is active for profile ${t.profileName}`),{code:"bridge_install_busy"});try{return B(s,`${process.pid}
6
6
  `,"utf8"),await e()}finally{G(s);try{u(i,{force:!0})}catch{}}}function V(t){try{return C(t,"wx",384)}catch(e){if(e.code==="EEXIST")return null;throw Object.assign(new Error(`Cannot acquire Grix DSH Bridge install lock: ${D(e)}`),{code:"bridge_install_failed"})}}function Y(t){try{return process.kill(t,0),!0}catch(e){return e.code==="EPERM"}}async function A(t,e){try{return(await h(t,["--version"],e)).trim().split(/\s+/)[0]||null}catch{return null}}async function h(t,e,r){try{return(await z(t,e,{env:{...process.env,...r?{DSH_HOME:I(r)}:{}},timeout:6e4,maxBuffer:8388608})).stdout}catch(i){const s=i&&typeof i=="object"?i:{};throw Object.assign(new Error(D(i)),{code:"dsh_command_failed",stderr:typeof s.stderr=="string"?S(s.stderr):void 0})}}function S(t){return t.replace(/(api[_-]?key|authorization|bearer)\s*[:=]\s*\S+/gi,"$1=[REDACTED]")}function D(t){const e=t&&typeof t=="object"?t:{};return S(String(e.stderr??e.message??t??"unknown error")).replace(/[\r\n]+/g," ").slice(0,1024)}function W(t){const e=t&&typeof t=="object"?t:{};return S(String(e.stderr??e.message??t??"unknown error")).slice(0,8*1024)}export{ae as DshBridgeInstaller,le as defaultBridgeTarball,de as errorForDshBridgeReadiness};
@@ -1,3 +1,3 @@
1
- import{createHash as D,randomUUID as M}from"node:crypto";import{EventEmitter as j}from"node:events";import{copyFileSync as oe,existsSync as L,mkdirSync as ne}from"node:fs";import{dirname as re,join as T,resolve as U}from"node:path";import{fileURLToPath as O}from"node:url";import{log as m}from"../../core/log/index.js";import{syncDefaultSkillsToDir as ae}from"../../default-skills/index.js";import{resolveCliPath as de}from"../../core/util/cli-probe.js";import{DshWireCapture as le}from"./audit-boundary.js";import{dsmlToolCallKey as he,projectVisibleDsmlText as ce}from"./dsml-text-filter.js";import{mapDshSessionEvent as ue,unwrapDshSessionEvent as pe}from"./event-mapper.js";import{buildDshUserPrompt as V,extractQuotedMessageMarker as W}from"./prompt-builder.js";import{DshProcessRuntime as ge}from"./process-runtime.js";import{DshProfileRuntime as me}from"./profile-runtime.js";import{createDshWebProfile as fe}from"./profile-catalog.js";import{listDshPlugins as E,resolveDshPlugin as ve,updateDshPluginIds as be}from"./plugin-manager.js";import{prepareDshSessionPluginOverlay as _e}from"./session-plugin-overlay.js";import{assertSelectableDshProfileName as Se,discoverDshBridgeEndpoints as Ie,listDshProfiles as ke,resolveDshConnectorProfileDataDir as Pe,resolveDshHome as Te,resolveDshSelectedProfileName as we}from"./profile-resolver.js";import{DshBridgeInstaller as R,errorForDshBridgeReadiness as A}from"./bridge-installer.js";import{ensureDshBridgeReady as ye,prepareDshProfileBridge as xe}from"./profile-supervisor.js";import{DSH_RUNTIME_ENSURE_MAX_ATTEMPTS as G,dshRuntimeEnsureBackoffMs as Ce,isRetryableDshRuntimeError as De}from"./runtime-ensure.js";import{runDshProtocolProbe as Me}from"./probe.js";import{buildDshSystemPrompt as Ee,describeDshSystemPrompt as Re}from"./system-prompt.js";import{DshActionCoordinator as Ae}from"./toolbar-actions.js";import{adoptDshProfileModels as He,adoptLiveDshProviderSelection as $e,buildDshToolbarMeta as Be,DEFAULT_DSH_MAX_TOKENS as qe,DEFAULT_DSH_MODELS as Fe,DEFAULT_DSH_PRESETS as Ne,DEFAULT_DSH_PROVIDER_ID as H,normalizeDshPresets as je,normalizeDshProviders as Le,permissionModeFor as z,resolveDshAgentPreset as Q,resolveDshModeId as Ue,resolveDshProviderId as Oe,retainRequestedDshProvider as Ve}from"./toolbar-state.js";import{modelsForDshProvider as We,resolveDshCatalogForToolbar as Ge,writeDshCatalogCache as ze}from"./catalog-cache.js";import{TurnCorrelator as Qe}from"./turn-correlator.js";import{getDshSessionUsageStore as Ke,normalizeDshUsage as K}from"./usage.js";import{toolCallToInvoke as Xe}from"../../core/mcp/tools.js";import{isDshBridgedGrixTool as Je}from"./grix-tool-bridge.js";import{DSH_GRIX_PROVIDER_ID as b,buildDshManagedProvider as X}from"./dsh-provider-config.js";const f="deepseek-harness-adapter",J=20*6e4,Y=6e4,Z=9e4,ee=30*6e4;class Ye extends j{adapterSessionId;cancelFn;constructor(e,t){super(),this.adapterSessionId=e,this.cancelFn=t}cancel(){return this.cancelFn()}}class Ft extends j{config;callbacks;type="deepseek-harness";alive=!1;stopped=!1;runtime=null;capture=null;runtimeGeneration=0;runtimeSessionId="";applied;active=null;correlator=null;timeoutTimer=null;hardTimeoutTimer=null;activeTimeoutMs=J;intentionalRuntimeStop=!1;personaDirty=!1;profileRevision=0;appliedProfileRevision=-1;rebuildPromise=null;runtimeStartPromise=null;contextWindow=null;reportedContextCapacity=null;providerQuota=null;settingsState="applied";settingsErrorCode=null;injectedMessageIds=new Set;auditBoundaries=new Map;actionCoordinator=new Ae;activeWireStart=0;activeUsage=te();activeUsageSeq=-1;activeCommittedUsageSeqs=new Set;permissionHandler=null;quotedMessageId;cancelRequested=!1;runtimeReadiness="unknown";bridgeCapabilities=null;bridgeAckCursor=0;pendingFinalBridgeAck=null;finishingTurn=!1;pendingApprovals=new Map;options;models=Fe;providers=[];presets=[...Ne];catalogProviderId;constructor(e,t,i){super(),this.config=e,this.callbacks=t,this.options=i,this.hydrateCatalogFromCache()}async start(){this.alive=!0,this.stopped=!1,this.settingsState="applied",this.settingsErrorCode=null,this.hydrateCatalogFromCache();const e=this.options.bindingStore.get(this.options.aibotSessionId);if(e?.cwd&&this.seedSessionToolbarFromGlobal(),this.syncGrixProvider(),e&&await this.options.bindingStore.flush(),this.resolveIntegrationMode()==="profile_bridge")try{const t=await this.attachSelectedProfile();await this.healBridgeUpdate(t)}catch(t){this.runtimeReadiness=String(t?.code??"bridge_probe_failed"),this.settingsErrorCode=this.runtimeReadiness}else this.runtimeReadiness="ready";this.pushToolbarMeta(),this.refreshProviderQuota(!1)}async stop(){this.stopped=!0,this.clearPendingApprovals("cancelled"),this.clearTimeout(),this.active&&this.finishActive("canceled","connector shutdown"),this.applied=void 0,this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState="pending",this.settingsErrorCode=null,this.pushToolbarMeta(),await this.rebuildPromise?.catch(()=>{}),await this.stopRuntime(!0),await this.usageStore().flush(),this.alive=!1}isAlive(){return this.alive&&!this.stopped}async createSession(e){return this.options.aibotSessionId}async resumeSession(e,t){}async destroySession(e){e===this.options.aibotSessionId&&(this.usageStore().delete(e),await this.usageStore().flush(),await this.stopRuntime(!0))}sendPrompt(e){const t=new Ye(e.adapterSessionId,()=>this.cancel(e.adapterSessionId));return queueMicrotask(()=>t.emit("done",{status:"failed",error:"Use deliverInboundEvent for platform prompts"})),t}async cancel(e){await this.cancelActive("user canceled")}deliverInboundEvent(e){if(!this.isAlive()){this.failEvent(e,"adapter is not alive");return}if(e.attachments_json&&e.attachments_json!=="[]"){this.failEvent(e,"DeepSeek Harness first version supports text only; attachments must be materialized in the bound workspace");return}if(this.active){this.failEvent(e,"concurrent prompt rejected");return}this.runInboundEvent(e)}deliverStopEvent(e,t){this.active&&e===this.active.inbound.event_id&&(t&&t!==this.active.inbound.session_id||this.cancelActive("user canceled"))}async handleLocalAction(e){if(!["set_model","set_mode","set_provider","set_preset","set_profile","create_profile","get_session_usage","get_rate_limits","dsh_bridge_status","dsh_install_bridge","dsh_list_plugins","dsh_enable_plugin","dsh_disable_plugin","dsh_refresh_plugins","dsh_list_skills","dsh_list_mcp","dsh_list_tools","dsh_list_jobs","dsh_list_goals","exec_approve","exec_reject","permission_approve","permission_reject"].includes(e.action_type))return{handled:!1,kind:""};const t=await this.actionCoordinator.run(e.action_id,()=>this.executeLocalAction(e));return this.callbacks.sendLocalActionResult(e.action_id,t.status,t.result,t.errorCode,t.errorMsg),{handled:!0,kind:e.action_type}}setPermissionHandler(e){this.permissionHandler=e}async ping(e){return this.isAlive()&&(!this.runtime||this.runtime.isConnected())}getStatus(){return{alive:this.isAlive()&&!!this.runtime,busy:!!this.active||this.intentionalRuntimeStop||!!this.rebuildPromise||!!this.runtimeStartPromise,backgroundBusy:!1,sessions:this.runtime?1:0,details:{runtimeGeneration:this.runtimeGeneration,runtimeSessionId:this.runtimeSessionId||void 0}}}getActiveEventIds(){return this.active?[this.active.inbound.event_id]:[]}takeAuditBoundary(e){const t=this.auditBoundaries.get(e);return this.auditBoundaries.delete(e),t}clearActiveEventForShutdown(){this.active=null,this.correlator=null,this.clearTimeout()}getMcpConfig(){return null}async hasBackgroundWork(){return this.runtime?.hasBackgroundWork()??!1}onAgentProfileChanged(){this.profileRevision+=1,this.personaDirty=!0,!this.active&&this.runtime&&this.rebuildRuntime("persona_changed")}updateProviderQuotaSnapshot(e){this.providerQuota=e??null,this.pushToolbarMeta()}async probe(e={}){const t=this.resolveIntegrationMode(),i=t==="embedded_jsonrpc"?this.config.command||"dsh-jsonrpc-agent":"dsh",s=await de(i),o=!!s;let d={ok:e.conversation!==!0,latency:null};if(o&&e.conversation===!0&&s)if(t==="embedded_jsonrpc")try{const l=await Me({command:s,args:this.config.args,cordisPath:U(this.options.cordisPath??O(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),settings:this.resolveDesiredSettings(),timeoutMs:e.timeoutMs});d={ok:!0,latency:l.latencyMs,serverName:l.serverName,serverVersion:l.serverVersion}}catch(l){d={ok:!1,latency:null,error:this.redactError(l)}}else{const l=Date.now();try{const a=new R({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),p=await ye({installer:a,autoStart:!1}),c=A(p);if(c)throw c;const n=Ie(p.identity);if(n.length!==1)throw Object.assign(new Error(n.length===0?`No live Grix Bridge endpoint in DSH profile "${p.identity.profileName}"`:`Multiple live Grix Bridge endpoints for DSH profile "${p.identity.profileName}"`),{code:n.length===0?"bridge_missing":"profile_instance_ambiguous"});d={ok:!0,latency:Date.now()-l,serverName:"grix-dsh-profile-bridge",serverVersion:n[0].bridgeVersion}}catch(a){d={ok:!1,latency:null,error:this.redactError(a)}}}return{cli:{command:i,installed:o,path:s,version:null,...o?{}:{error:{code:"cli_not_found",message:`${i} not found`}}},conversation:{attempted:e.conversation===!0,ok:d.ok,latency_ms:d.latency,...d.ok?{}:{error:{code:"conversation_failed",message:d.error??"initialize/shutdown probe failed"}}},config:{model:this.resolveDesiredSettings().modelId,base_url:this.config.env?.DEEPSEEK_BASE_URL??null,source:{model:"config",base_url:this.config.env?.DEEPSEEK_BASE_URL?"env":"unknown"},extras:{protocol:t==="profile_bridge"?"grix-dsh/1":"jsonrpc-v1",profile:this.resolveSelectedProfile(),serverName:d.serverName,serverVersion:d.serverVersion}},process:{started:!!this.runtime,alive:this.runtime?.isConnected()??!1,busy:!!this.active}}}async runInboundEvent(e){const t={inbound:e,admitted:!1,claimed:!1,turnEnded:!1,rootIdle:!1,text:"",sentText:"",seq:0,startedAt:Date.now()};this.active=t,this.correlator=new Qe(t),this.activeUsage=te(),this.activeUsageSeq=-1,this.activeCommittedUsageSeqs.clear(),this.quotedMessageId=void 0,this.cancelRequested=!1,this.emit("eventStarted",e.event_id,e.session_id);try{if(await this.ensureRuntimeWithRetry(),this.cancelRequested||this.active!==t)return;this.activeWireStart=this.capture?.offset??0;const i=V(e,this.injectedMessageIds);this.startTimeout(e.timeoutMs);const s=await this.runtime.client.prompt({sessionId:this.runtimeSessionId,contentBlocks:[{type:"text",text:i.text}]});if(!s?.messageId)throw Object.assign(new Error("session/prompt response missing messageId"),{code:"protocol_invalid_prompt_result"});this.correlator.setPromptMessageId(s.messageId)}catch(i){const s=this.redactError(i,e.content);this.finishActive(this.cancelRequested?"canceled":"failed",this.cancelRequested?"user canceled":s)}}async ensureRuntime(){if(this.stopped)throw new Error("adapter stopped");if(this.runtime)return;this.syncGrixProvider();const t=this.options.bindingStore.get(this.options.aibotSessionId)?.cwd;if(!t)throw Object.assign(new Error("Session binding missing. Open a workspace first."),{code:"binding_missing"});this.projectConnectorSkills();let i=this.resolveDesiredSettings();const s=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),o={};s?.modelId||(o.modelId=i.modelId),!s?.providerId&&i.providerId&&(o.providerId=i.providerId),(o.modelId||o.providerId)&&(this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,o),await this.options.bindingStore.flush(),i=this.resolveDesiredSettings());const d=this.callbacks.getAgentProfile(),l=this.profileRevision,a=Ee({...d,grixSessionId:this.options.aibotSessionId,agentId:this.callbacks.getAgentId()}),p=Re(a);this.runtimeGeneration+=1;const c=this.resolveIntegrationMode(),n=this.resolveSelectedProfile();if(c==="profile_bridge")try{await this.ensureProfileReadyForChat(),this.pushToolbarMeta()}catch(g){throw this.settingsState="failed",this.settingsErrorCode=String(g?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.pushToolbarMeta(),g}let r=c==="profile_bridge"?this.options.bindingStore.getDshProfileBinding(this.options.aibotSessionId,n):void 0;c==="profile_bridge"&&!r&&(r={profileName:n,sessionId:it(this.options.aibotSessionId),sessionCreated:!1,eventCursor:0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,r),await this.options.bindingStore.flush()),this.runtimeSessionId=r?.sessionId??tt(this.options.aibotSessionId,this.runtimeGeneration);const u=this.profileDataDir(n),v=U(this.options.cordisPath??O(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),$=_e({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:n,pluginIds:i.pluginIds??[],overlayId:D("sha256").update(this.options.aibotSessionId).digest("hex").slice(0,24),baseCordisPath:v}),se=T(u,"audit-source",`${this.runtimeSessionId}.jsonl`);this.capture=new le(se);const _=c==="embedded_jsonrpc"?new ge({command:this.config.command||"dsh-jsonrpc-agent",args:this.config.args,cwd:t,cordisPath:$.embeddedCordisPath??v,home:u,sessionRoot:T(u,"sessions"),env:this.config.env,systemPrompt:a,settings:i,capture:this.capture,maxLineBytes:this.options.maxLineBytes}):new me({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:n,cwd:t,ownerId:`${this.callbacks.getAgentId()}:${this.options.aibotSessionId}`,sessionId:this.runtimeSessionId,resumeSession:r?.sessionCreated===!0,lastAckCursor:r?.eventCursor??0,systemPrompt:a,settings:i,pluginOverlayPath:$.bridgeOverlayPath,managedProvider:i.providerId===b?X(this.options.provider??{}):void 0,capture:this.capture,maxFrameBytes:this.options.maxLineBytes,onApproval:g=>this.handleBridgeApproval(g),onToolInvoke:(g,w,k)=>this.invokeGrixTool(g,w,k),onCursorAck:g=>{!r||g<=r.eventCursor||(r={...r,eventCursor:g},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,r))}});this.runtime=_,this.bridgeAckCursor=r?.eventCursor??0,this.pendingFinalBridgeAck=null,this.finishingTurn=!1,this.intentionalRuntimeStop=!1;try{const g=await _.start();if(!_.isConnected())throw Object.assign(new Error("Harness runtime disconnected immediately after initialize"),{code:"runtime_exited"});_.client?.on("notification",(S,I)=>this.onNotification(S,I)),_.client?.on("protocolError",S=>this.onProtocolError(S)),_.onExit(()=>this.onRuntimeExit()),_.client?.activateNotifications?.();let w=!1;if(c==="profile_bridge"){const S=Le(g.providers),I=$e({requestedProviderId:i.providerId,liveProviders:S,liveSelectedProvider:String(g.selectedProvider??"")});this.providers=Ve(S,I.providerId,this.providers),i={...i,providerId:I.providerId},w=I.persistFallback;const x=I.providerId,q=Object.prototype.hasOwnProperty.call(g,"models")?g.models:void 0,F=!!this.catalogProviderId&&!!x&&x!==this.catalogProviderId;this.models=He({current:this.models,fetched:q,providerChanged:F}),(q!==void 0||F)&&(this.catalogProviderId=x||this.catalogProviderId);const C=String(g.selectedModel??"");C&&C!==i.modelId&&(i={...i,modelId:C});const N=je(g.presets);N.length>0&&(this.presets=N);const y=String(g.selectedPreset??"");y&&y!==i.agentPreset&&(i={...i,agentPreset:y},this.options.bindingStore.getDshAgentPreset(this.options.aibotSessionId)||this.options.bindingStore.setDshAgentPreset(this.options.aibotSessionId,y))}const k=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),B=(k?.revision??0)!==i.revision,P={};!B&&w&&(k?.providerId??"")!==(i.providerId??"")&&(P.providerId=i.providerId),!B&&(k?.modelId??"")!==i.modelId&&(P.modelId=i.modelId),(P.providerId||P.modelId)&&(i.revision=this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,P)??i.revision,await this.options.bindingStore.flush(),m.warn(f,`replaced unavailable persisted DSH catalog selection provider=${i.providerId} model=${i.modelId}`)),this.applied={runtimeGeneration:this.runtimeGeneration,appliedRevision:i.revision,providerId:i.providerId??H,modelId:i.modelId,modeId:i.modeId},this.runtimeReadiness="ready",this.bridgeCapabilities=g.capabilities??null,c==="profile_bridge"&&r&&!r.sessionCreated&&(r={...r,sessionCreated:!0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,r),await this.options.bindingStore.flush()),this.settingsState=this.resolveDesiredSettings().revision===i.revision?"applied":"pending",this.settingsErrorCode=null,this.appliedProfileRevision=l,this.personaDirty=this.appliedProfileRevision!==this.profileRevision,m.info(f,`runtime initialized generation=${this.runtimeGeneration} prompt_schema=${p.schemaVersion} prompt_sha256=${p.sha256} prompt_length=${p.length}`),await this.persistCatalogCache(i.providerId??H),this.pushToolbarMeta(),this.settingsState==="pending"&&!this.active&&!this.stopped&&this.rebuildRuntime("settings_changed_during_start")}catch(g){throw this.settingsState="failed",this.settingsErrorCode=String(g?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.applied=void 0,this.pushToolbarMeta(),await this.stopRuntime(!0),g}}ensureRuntimeWithRetry(){if(this.runtimeStartPromise)return this.runtimeStartPromise;const e=this.ensureRuntimeWithRetryLoop();this.runtimeStartPromise=e;const t=()=>{this.runtimeStartPromise===e&&(this.runtimeStartPromise=null)};return e.then(t,t),e}async ensureRuntimeWithRetryLoop(){let e;for(let t=1;t<=G;t++)try{await this.ensureRuntime();return}catch(i){e=i;const s=String(i?.code??"");if(this.cancelRequested||!De(s)||t===G)throw i;m.warn(f,`runtime ensure retry attempt=${t} code=${s||"unknown"}`),this.settingsState="pending",this.settingsErrorCode=s||"runtime_initialize_failed",this.runtimeReadiness=this.settingsErrorCode,this.pushToolbarMeta(),await this.stopRuntime(!0),await et(Ce(t))}throw e}onNotification(e,t){const i=Ze(t);if(e==="session.event"){const s=pe(t);if(!s){this.onProtocolError(new Error("malformed session.event"));return}const o=this.onSessionEvent(s);this.advanceBridgeAck(i,o);return}if(e==="session.status"){const s=t&&typeof t=="object"?t:{};if(String(s.sessionId??"")===this.runtimeSessionId){this.touchActivity(),this.correlator?.markRootStatus(String(s.status??"")),s.status==="idle"&&this.active&&this.correlator&&m.debug(f,`turn correlation idle admitted=${this.active.admitted} claimed=${this.active.claimed} ended=${this.active.turnEnded} complete=${this.correlator.complete}`);const d=!!this.correlator?.complete;d&&this.finishFromTurnOutcome(),this.advanceBridgeAck(i,d)}else i>0&&this.advanceBridgeAck(i,!1);return}if(e==="subagent.started"||e==="subagent.finished"){this.touchActivity(3);const s=t&&typeof t=="object"?t:{},o=String(s.childSessionId??s.sessionId??"");o&&this.capture?.addChild(o),this.active&&this.callbacks.sendRawEventEnvelope(this.active.inbound.event_id,this.active.inbound.session_id,{type:e,payload:s},e==="subagent.started"?"[subagent started]":"[subagent finished]"),this.advanceBridgeAck(i,!1);return}this.onProtocolError(new Error(`unknown required JSON-RPC notification: ${e}`))}onSessionEvent(e){if(!this.active||!this.correlator)return!1;this.touchActivity(e.type==="tool/call"||e.type==="tool/result"?3:1);const t=ue(e);if(t.kind==="unknown"&&!rt(e)&&e.ignorable!==!0)return this.onProtocolError(new Error(`unknown required SessionEvent: ${e.type}`)),!1;if(e.sessionId&&e.sessionId!==this.runtimeSessionId)return!1;const i=this.correlator.accept(e);if((e.type==="agent/inbox/spliced"||e.type==="user/message"||e.type==="turn/end")&&m.debug(f,`turn correlation event=${e.type} belongs=${i} admitted=${this.active.admitted} claimed=${this.active.claimed} ended=${this.active.turnEnded}`),e.type==="agent/inbox/spliced"&&this.active.admitted){const s=V(this.active.inbound,this.injectedMessageIds);for(const o of s.contextIds)this.injectedMessageIds.add(o);s.currentMessageId&&this.injectedMessageIds.add(s.currentMessageId)}return i?st(e)?(this.flushPendingTextAsThinking(),!1):t.kind==="text"?(t.payload?.committed===!0?(t.payload?.hasToolCall===!0?this.applyCommittedToolStepText(t.text??""):this.applyCommittedText(t.text??""),t.usage&&this.collectCommittedUsage(t.usage,Number(e.seq??e.step??Date.now()))):this.applyTextDelta(t.text??""),!1):t.kind==="thinking"?(this.thinkingEnabled()&&this.callbacks.sendThinking(this.active.inbound.event_id,this.active.inbound.session_id,t.text??""),!1):t.kind==="tool_call"?(this.flushPendingTextAsThinking(),this.toolEventsEnabled()&&this.sendRaw("tool_call",{call_id:t.callId,tool_name:t.name,tool_input:t.input},`[tool] ${t.name}`),!1):t.kind==="tool_result"?(this.toolEventsEnabled()&&this.sendRaw("tool_result",{call_id:t.callId,result:t.output},`[tool result] ${t.callId??""}`),!1):t.kind==="todo"||t.kind==="compaction"?!1:t.kind==="context"?(this.updateContextCapacity(t.payload),!1):t.kind==="usage"?(this.updateContextWindow(t.usage),!1):t.kind==="turn_end"&&this.correlator.complete?(this.finishFromTurnOutcome(),!0):!1:!1}applyTextDelta(e){this.active.pendingText=`${this.active.pendingText??""}${e}`}applyCommittedText(e){const t=this.active;if(t.pendingText=void 0,e.startsWith(t.text))t.text=e;else if(!t.text.startsWith(e)){m.warn(f,`committed assistant text diverged event=${t.inbound.event_id}`);const i=W(e).quotedMessageId;i&&(this.quotedMessageId=i),t.text=t.sentText}this.flushVisibleText(!1)}flushPendingTextAsThinking(){const e=this.active,t=e?.pendingText;!e||!t||(e.pendingText=void 0,this.thinkingEnabled()&&t.trim()&&this.callbacks.sendThinking(e.inbound.event_id,e.inbound.session_id,t),e.lastThinkingText=t)}applyCommittedToolStepText(e){const t=this.active;t&&(t.pendingText=void 0,e.trim()&&t.lastThinkingText!==e&&this.thinkingEnabled()&&(this.callbacks.sendThinking(t.inbound.event_id,t.inbound.session_id,e),t.lastThinkingText=e))}promotePendingTextToVisible(){const e=this.active,t=e?.pendingText;!e||!t||(e.pendingText=void 0,e.text+=t)}flushVisibleText(e,t={}){const i=this.active;if(!i)return;const s=W(i.text);s.quotedMessageId&&(this.quotedMessageId=s.quotedMessageId);const o=s.text.replace(/\[\[quoted_message_id:[^\]]*$/g,""),d=ce(o,{finalize:t.finalizeDsml===!0||e});this.surfaceSuppressedDsmlToolCalls(d.suppressedToolCalls);const l=d.visible;this.observeVisibleTextAfterToolCall(l);let a="";l.startsWith(i.sentText)?a=l.slice(i.sentText.length):(e||t.finalizeDsml)&&(a=l),!(!a&&!e)&&(i.seq+=1,this.callbacks.sendStreamChunk(i.inbound.event_id,i.inbound.session_id,a,i.seq,e,`${i.inbound.event_id}-dsh`,this.quotedMessageId),i.sentText=l)}surfaceSuppressedDsmlToolCalls(e){if(!this.active||e.length===0)return;const t=this.active.dsmlSuppressedKeys??new Set;this.active.dsmlSuppressedKeys=t;for(const i of e){const s=he(i);if(t.has(s)||(t.add(s),this.markToolCallAwaitingFinalText(),m.warn(f,`suppressed leaked DSML tool markup name=${i.name} event=${this.active.inbound.event_id}`),!this.toolEventsEnabled()))continue;let o=i.arguments;try{o=JSON.parse(i.arguments)}catch{}this.sendRaw("tool_call",{call_id:`dsml-${t.size}`,tool_name:i.name,tool_input:o,source:"dsml_text_leak",executed:!1},`[tool] ${i.name}`)}}markToolCallAwaitingFinalText(){const e=this.active;e&&(e.toolCallAwaitingFinalText=!0,e.toolCallVisibleTextLength=e.sentText.length)}observeVisibleTextAfterToolCall(e){const t=this.active;if(!t?.toolCallAwaitingFinalText)return;const i=t.toolCallVisibleTextLength??t.sentText.length;e.slice(i).trim().length!==0&&(t.toolCallAwaitingFinalText=!1,t.toolCallVisibleTextLength=void 0)}collectCommittedUsage(e,t){if(this.activeCommittedUsageSeqs.has(t))return;this.activeCommittedUsageSeqs.add(t);const i=K(e);this.activeUsage.inputTokens+=i.inputTokens,this.activeUsage.outputTokens+=i.outputTokens,this.activeUsage.cacheReadInputTokens+=i.cacheReadInputTokens,this.activeUsage.cacheCreationInputTokens+=i.cacheCreationInputTokens,this.activeUsage.reasoningTokens+=i.reasoningTokens,this.activeUsageSeq=Math.max(this.activeUsageSeq,t),this.updateContextWindow(i)}updateContextWindow(e){const t=K(e),i=this.resolveDesiredSettings(),s=this.models.find(d=>d.id===i.modelId),o=this.reportedContextCapacity??s?.contextWindow;if(o&&o>0){const d=t.inputTokens+t.cacheReadInputTokens+t.cacheCreationInputTokens;this.contextWindow={usedTokens:d,totalTokens:o,remainingTokens:Math.max(0,o-d),usedPercentage:d/o*100,remainingPercentage:Math.max(0,100-d/o*100)},this.pushToolbarMeta()}}updateContextCapacity(e){const t=Number(e?.contextWindow);if(!Number.isFinite(t)||t<=0)return;this.reportedContextCapacity=t;const i=this.contextWindow&&typeof this.contextWindow=="object"?this.contextWindow:{},s=Math.max(0,Number(i.usedTokens)||0);this.contextWindow={usedTokens:s,totalTokens:t,remainingTokens:Math.max(0,t-s),usedPercentage:s/t*100,remainingPercentage:Math.max(0,100-s/t*100)},this.pushToolbarMeta()}finishFromTurnOutcome(){if(!this.active)return;this.finishingTurn=!0;const e=this.active.outcome??"completed",t=this.active.outcomeDetail?.trim();e==="completed"?this.finishActive("responded"):e==="aborted"?this.finishActive("canceled"):e==="max-tokens"&&this.active.sentText?this.finishActive("responded","Response truncated at model token limit"):this.finishActive("failed",t?t.toLowerCase().includes(e.toLowerCase())?`Harness turn ended: ${t}`:`Harness turn ended: ${e}: ${t}`:`Harness turn ended: ${e}`)}finishActive(e,t){const i=this.active;if(!i)return;let s=e,o=t;this.finishingTurn=!0,this.clearTimeout(),this.promotePendingTextToVisible(),this.flushVisibleText(!1,{finalizeDsml:!0}),s==="responded"&&i.toolCallAwaitingFinalText&&(s="failed",o="DeepSeek Harness ended after a tool call without returning final assistant text",m.warn(f,`${o} event=${i.inbound.event_id}`)),i.text=i.sentText;const d=s==="failed"&&!!o?.trim();d&&(i.text+=`
1
+ import{createHash as D,randomUUID as M}from"node:crypto";import{EventEmitter as j}from"node:events";import{copyFileSync as oe,existsSync as L,mkdirSync as ne}from"node:fs";import{dirname as re,join as T,resolve as U}from"node:path";import{fileURLToPath as O}from"node:url";import{log as m}from"../../core/log/index.js";import{syncDefaultSkillsToDir as ae}from"../../default-skills/index.js";import{resolveCliPath as de}from"../../core/util/cli-probe.js";import{DshWireCapture as le}from"./audit-boundary.js";import{dsmlToolCallKey as he,projectVisibleDsmlText as ce}from"./dsml-text-filter.js";import{mapDshSessionEvent as ue,unwrapDshSessionEvent as pe}from"./event-mapper.js";import{buildDshUserPrompt as V,extractQuotedMessageMarker as W}from"./prompt-builder.js";import{DshProcessRuntime as ge}from"./process-runtime.js";import{DshProfileRuntime as me}from"./profile-runtime.js";import{createDshWebProfile as fe}from"./profile-catalog.js";import{listDshPlugins as E,resolveDshPlugin as ve,updateDshPluginIds as be}from"./plugin-manager.js";import{prepareDshSessionPluginOverlay as _e}from"./session-plugin-overlay.js";import{assertSelectableDshProfileName as Se,discoverDshBridgeEndpoints as Ie,listDshProfiles as ke,resolveDshConnectorProfileDataDir as Pe,resolveDshHome as Te,resolveDshSelectedProfileName as we}from"./profile-resolver.js";import{DshBridgeInstaller as R,errorForDshBridgeReadiness as A}from"./bridge-installer.js";import{ensureDshBridgeReady as ye,prepareDshProfileBridge as xe}from"./profile-supervisor.js";import{DSH_RUNTIME_ENSURE_MAX_ATTEMPTS as G,dshRuntimeEnsureBackoffMs as Ce,isRetryableDshRuntimeError as De}from"./runtime-ensure.js";import{runDshProtocolProbe as Me}from"./probe.js";import{buildDshSystemPrompt as Ee,describeDshSystemPrompt as Re}from"./system-prompt.js";import{DshActionCoordinator as Ae}from"./toolbar-actions.js";import{adoptDshProfileModels as He,adoptLiveDshProviderSelection as $e,buildDshToolbarMeta as Be,DEFAULT_DSH_MAX_TOKENS as qe,DEFAULT_DSH_MODELS as Fe,DEFAULT_DSH_PRESETS as Ne,DEFAULT_DSH_PROVIDER_ID as H,normalizeDshPresets as je,normalizeDshProviders as Le,permissionModeFor as z,resolveDshAgentPreset as Q,resolveDshModeId as Ue,resolveDshProviderId as Oe,retainRequestedDshProvider as Ve}from"./toolbar-state.js";import{modelsForDshProvider as We,resolveDshCatalogForToolbar as Ge,writeDshCatalogCache as ze}from"./catalog-cache.js";import{TurnCorrelator as Qe}from"./turn-correlator.js";import{getDshSessionUsageStore as Ke,normalizeDshUsage as K}from"./usage.js";import{toolCallToInvoke as Xe}from"../../core/mcp/tools.js";import{isDshBridgedGrixTool as Je}from"./grix-tool-bridge.js";import{DSH_GRIX_PROVIDER_ID as b,buildDshManagedProvider as X}from"./dsh-provider-config.js";const f="deepseek-harness-adapter",J=20*6e4,Y=6e4,Z=9e4,ee=30*6e4;class Ye extends j{adapterSessionId;cancelFn;constructor(e,t){super(),this.adapterSessionId=e,this.cancelFn=t}cancel(){return this.cancelFn()}}class Ft extends j{config;callbacks;type="deepseek-harness";alive=!1;stopped=!1;runtime=null;capture=null;runtimeGeneration=0;runtimeSessionId="";applied;active=null;correlator=null;timeoutTimer=null;hardTimeoutTimer=null;activeTimeoutMs=J;intentionalRuntimeStop=!1;personaDirty=!1;profileRevision=0;appliedProfileRevision=-1;rebuildPromise=null;runtimeStartPromise=null;contextWindow=null;reportedContextCapacity=null;providerQuota=null;settingsState="applied";settingsErrorCode=null;injectedMessageIds=new Set;auditBoundaries=new Map;actionCoordinator=new Ae;activeWireStart=0;activeUsage=te();activeUsageSeq=-1;activeCommittedUsageSeqs=new Set;permissionHandler=null;quotedMessageId;cancelRequested=!1;runtimeReadiness="unknown";bridgeCapabilities=null;bridgeAckCursor=0;pendingFinalBridgeAck=null;finishingTurn=!1;pendingApprovals=new Map;options;models=Fe;providers=[];presets=[...Ne];catalogProviderId;constructor(e,t,i){super(),this.config=e,this.callbacks=t,this.options=i,this.hydrateCatalogFromCache()}async start(){this.alive=!0,this.stopped=!1,this.settingsState="applied",this.settingsErrorCode=null,this.hydrateCatalogFromCache();const e=this.options.bindingStore.get(this.options.aibotSessionId);if(e?.cwd&&this.seedSessionToolbarFromGlobal(),this.syncGrixProvider(),e&&await this.options.bindingStore.flush(),this.resolveIntegrationMode()==="profile_bridge")try{const t=await this.attachSelectedProfile();await this.healBridgeUpdate(t)}catch(t){this.runtimeReadiness=String(t?.code??"bridge_probe_failed"),this.settingsErrorCode=this.runtimeReadiness}else this.runtimeReadiness="ready";this.pushToolbarMeta(),this.refreshProviderQuota(!1)}async stop(){this.stopped=!0,this.clearPendingApprovals("cancelled"),this.clearTimeout(),this.active&&this.finishActive("canceled","connector shutdown"),this.applied=void 0,this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState="pending",this.settingsErrorCode=null,this.pushToolbarMeta(),await this.rebuildPromise?.catch(()=>{}),await this.stopRuntime(!0),await this.usageStore().flush(),this.alive=!1}isAlive(){return this.alive&&!this.stopped}async createSession(e){return this.options.aibotSessionId}async resumeSession(e,t){}async destroySession(e){e===this.options.aibotSessionId&&(this.usageStore().delete(e),await this.usageStore().flush(),await this.stopRuntime(!0))}sendPrompt(e){const t=new Ye(e.adapterSessionId,()=>this.cancel(e.adapterSessionId));return queueMicrotask(()=>t.emit("done",{status:"failed",error:"Use deliverInboundEvent for platform prompts"})),t}async cancel(e){await this.cancelActive("user canceled")}deliverInboundEvent(e){if(!this.isAlive()){this.failEvent(e,"adapter is not alive");return}if(e.attachments_json&&e.attachments_json!=="[]"){this.failEvent(e,"DeepSeek Harness first version supports text only; attachments must be materialized in the bound workspace");return}if(this.active){this.failEvent(e,"concurrent prompt rejected");return}this.runInboundEvent(e)}deliverStopEvent(e,t){this.active&&e===this.active.inbound.event_id&&(t&&t!==this.active.inbound.session_id||this.cancelActive("user canceled"))}async handleLocalAction(e){if(!["set_model","set_mode","set_provider","set_preset","set_profile","create_profile","get_session_usage","get_rate_limits","dsh_bridge_status","dsh_install_bridge","dsh_list_plugins","dsh_enable_plugin","dsh_disable_plugin","dsh_refresh_plugins","dsh_list_skills","dsh_list_mcp","dsh_list_tools","dsh_list_jobs","dsh_list_goals","exec_approve","exec_reject","permission_approve","permission_reject"].includes(e.action_type))return{handled:!1,kind:""};const t=await this.actionCoordinator.run(e.action_id,()=>this.executeLocalAction(e));return this.callbacks.sendLocalActionResult(e.action_id,t.status,t.result,t.errorCode,t.errorMsg),{handled:!0,kind:e.action_type}}setPermissionHandler(e){this.permissionHandler=e}async ping(e){return this.isAlive()&&(!this.runtime||this.runtime.isConnected())}getStatus(){return{alive:this.isAlive()&&!!this.runtime,busy:!!this.active||this.intentionalRuntimeStop||!!this.rebuildPromise||!!this.runtimeStartPromise,backgroundBusy:!1,sessions:this.runtime?1:0,details:{runtimeGeneration:this.runtimeGeneration,runtimeSessionId:this.runtimeSessionId||void 0}}}getActiveEventIds(){return this.active?[this.active.inbound.event_id]:[]}takeAuditBoundary(e){const t=this.auditBoundaries.get(e);return this.auditBoundaries.delete(e),t}clearActiveEventForShutdown(){this.active=null,this.correlator=null,this.clearTimeout()}getMcpConfig(){return null}async hasBackgroundWork(){return this.runtime?.hasBackgroundWork()??!1}onAgentProfileChanged(){this.profileRevision+=1,this.personaDirty=!0,!this.active&&this.runtime&&this.rebuildRuntime("persona_changed")}updateProviderQuotaSnapshot(e){this.providerQuota=e??null,this.pushToolbarMeta()}async probe(e={}){const t=this.resolveIntegrationMode(),i=t==="embedded_jsonrpc"?this.config.command||"dsh-jsonrpc-agent":"dsh",s=await de(i),o=!!s;let d={ok:e.conversation!==!0,latency:null};if(o&&e.conversation===!0&&s)if(t==="embedded_jsonrpc")try{const l=await Me({command:s,args:this.config.args,cordisPath:U(this.options.cordisPath??O(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),settings:this.resolveDesiredSettings(),timeoutMs:e.timeoutMs});d={ok:!0,latency:l.latencyMs,serverName:l.serverName,serverVersion:l.serverVersion}}catch(l){d={ok:!1,latency:null,error:this.redactError(l)}}else{const l=Date.now();try{const a=new R({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),p=await ye({installer:a,autoStart:!1}),c=A(p);if(c)throw c;const n=Ie(p.identity);if(n.length===0)throw Object.assign(new Error(`No live Grix Bridge endpoint in DSH profile "${p.identity.profileName}"`),{code:"bridge_missing"});d={ok:!0,latency:Date.now()-l,serverName:"grix-dsh-profile-bridge",serverVersion:n[0].bridgeVersion}}catch(a){d={ok:!1,latency:null,error:this.redactError(a)}}}return{cli:{command:i,installed:o,path:s,version:null,...o?{}:{error:{code:"cli_not_found",message:`${i} not found`}}},conversation:{attempted:e.conversation===!0,ok:d.ok,latency_ms:d.latency,...d.ok?{}:{error:{code:"conversation_failed",message:d.error??"initialize/shutdown probe failed"}}},config:{model:this.resolveDesiredSettings().modelId,base_url:this.config.env?.DEEPSEEK_BASE_URL??null,source:{model:"config",base_url:this.config.env?.DEEPSEEK_BASE_URL?"env":"unknown"},extras:{protocol:t==="profile_bridge"?"grix-dsh/1":"jsonrpc-v1",profile:this.resolveSelectedProfile(),serverName:d.serverName,serverVersion:d.serverVersion}},process:{started:!!this.runtime,alive:this.runtime?.isConnected()??!1,busy:!!this.active}}}async runInboundEvent(e){const t={inbound:e,admitted:!1,claimed:!1,turnEnded:!1,rootIdle:!1,text:"",sentText:"",seq:0,startedAt:Date.now()};this.active=t,this.correlator=new Qe(t),this.activeUsage=te(),this.activeUsageSeq=-1,this.activeCommittedUsageSeqs.clear(),this.quotedMessageId=void 0,this.cancelRequested=!1,this.emit("eventStarted",e.event_id,e.session_id);try{if(await this.ensureRuntimeWithRetry(),this.cancelRequested||this.active!==t)return;this.activeWireStart=this.capture?.offset??0;const i=V(e,this.injectedMessageIds);this.startTimeout(e.timeoutMs);const s=await this.runtime.client.prompt({sessionId:this.runtimeSessionId,contentBlocks:[{type:"text",text:i.text}]});if(!s?.messageId)throw Object.assign(new Error("session/prompt response missing messageId"),{code:"protocol_invalid_prompt_result"});this.correlator.setPromptMessageId(s.messageId)}catch(i){const s=this.redactError(i,e.content);this.finishActive(this.cancelRequested?"canceled":"failed",this.cancelRequested?"user canceled":s)}}async ensureRuntime(){if(this.stopped)throw new Error("adapter stopped");if(this.runtime)return;this.syncGrixProvider();const t=this.options.bindingStore.get(this.options.aibotSessionId)?.cwd;if(!t)throw Object.assign(new Error("Session binding missing. Open a workspace first."),{code:"binding_missing"});this.projectConnectorSkills();let i=this.resolveDesiredSettings();const s=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),o={};s?.modelId||(o.modelId=i.modelId),!s?.providerId&&i.providerId&&(o.providerId=i.providerId),(o.modelId||o.providerId)&&(this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,o),await this.options.bindingStore.flush(),i=this.resolveDesiredSettings());const d=this.callbacks.getAgentProfile(),l=this.profileRevision,a=Ee({...d,grixSessionId:this.options.aibotSessionId,agentId:this.callbacks.getAgentId()}),p=Re(a);this.runtimeGeneration+=1;const c=this.resolveIntegrationMode(),n=this.resolveSelectedProfile();if(c==="profile_bridge")try{await this.ensureProfileReadyForChat(),this.pushToolbarMeta()}catch(g){throw this.settingsState="failed",this.settingsErrorCode=String(g?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.pushToolbarMeta(),g}let r=c==="profile_bridge"?this.options.bindingStore.getDshProfileBinding(this.options.aibotSessionId,n):void 0;c==="profile_bridge"&&!r&&(r={profileName:n,sessionId:it(this.options.aibotSessionId),sessionCreated:!1,eventCursor:0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,r),await this.options.bindingStore.flush()),this.runtimeSessionId=r?.sessionId??tt(this.options.aibotSessionId,this.runtimeGeneration);const u=this.profileDataDir(n),v=U(this.options.cordisPath??O(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),$=_e({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:n,pluginIds:i.pluginIds??[],overlayId:D("sha256").update(this.options.aibotSessionId).digest("hex").slice(0,24),baseCordisPath:v}),se=T(u,"audit-source",`${this.runtimeSessionId}.jsonl`);this.capture=new le(se);const _=c==="embedded_jsonrpc"?new ge({command:this.config.command||"dsh-jsonrpc-agent",args:this.config.args,cwd:t,cordisPath:$.embeddedCordisPath??v,home:u,sessionRoot:T(u,"sessions"),env:this.config.env,systemPrompt:a,settings:i,capture:this.capture,maxLineBytes:this.options.maxLineBytes}):new me({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:n,cwd:t,ownerId:`${this.callbacks.getAgentId()}:${this.options.aibotSessionId}`,sessionId:this.runtimeSessionId,resumeSession:r?.sessionCreated===!0,lastAckCursor:r?.eventCursor??0,systemPrompt:a,settings:i,pluginOverlayPath:$.bridgeOverlayPath,managedProvider:i.providerId===b?X(this.options.provider??{}):void 0,capture:this.capture,maxFrameBytes:this.options.maxLineBytes,onApproval:g=>this.handleBridgeApproval(g),onToolInvoke:(g,w,k)=>this.invokeGrixTool(g,w,k),onCursorAck:g=>{!r||g<=r.eventCursor||(r={...r,eventCursor:g},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,r))}});this.runtime=_,this.bridgeAckCursor=r?.eventCursor??0,this.pendingFinalBridgeAck=null,this.finishingTurn=!1,this.intentionalRuntimeStop=!1;try{const g=await _.start();if(!_.isConnected())throw Object.assign(new Error("Harness runtime disconnected immediately after initialize"),{code:"runtime_exited"});_.client?.on("notification",(S,I)=>this.onNotification(S,I)),_.client?.on("protocolError",S=>this.onProtocolError(S)),_.onExit(()=>this.onRuntimeExit()),_.client?.activateNotifications?.();let w=!1;if(c==="profile_bridge"){const S=Le(g.providers),I=$e({requestedProviderId:i.providerId,liveProviders:S,liveSelectedProvider:String(g.selectedProvider??"")});this.providers=Ve(S,I.providerId,this.providers),i={...i,providerId:I.providerId},w=I.persistFallback;const x=I.providerId,q=Object.prototype.hasOwnProperty.call(g,"models")?g.models:void 0,F=!!this.catalogProviderId&&!!x&&x!==this.catalogProviderId;this.models=He({current:this.models,fetched:q,providerChanged:F}),(q!==void 0||F)&&(this.catalogProviderId=x||this.catalogProviderId);const C=String(g.selectedModel??"");C&&C!==i.modelId&&(i={...i,modelId:C});const N=je(g.presets);N.length>0&&(this.presets=N);const y=String(g.selectedPreset??"");y&&y!==i.agentPreset&&(i={...i,agentPreset:y},this.options.bindingStore.getDshAgentPreset(this.options.aibotSessionId)||this.options.bindingStore.setDshAgentPreset(this.options.aibotSessionId,y))}const k=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),B=(k?.revision??0)!==i.revision,P={};!B&&w&&(k?.providerId??"")!==(i.providerId??"")&&(P.providerId=i.providerId),!B&&(k?.modelId??"")!==i.modelId&&(P.modelId=i.modelId),(P.providerId||P.modelId)&&(i.revision=this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,P)??i.revision,await this.options.bindingStore.flush(),m.warn(f,`replaced unavailable persisted DSH catalog selection provider=${i.providerId} model=${i.modelId}`)),this.applied={runtimeGeneration:this.runtimeGeneration,appliedRevision:i.revision,providerId:i.providerId??H,modelId:i.modelId,modeId:i.modeId},this.runtimeReadiness="ready",this.bridgeCapabilities=g.capabilities??null,c==="profile_bridge"&&r&&!r.sessionCreated&&(r={...r,sessionCreated:!0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,r),await this.options.bindingStore.flush()),this.settingsState=this.resolveDesiredSettings().revision===i.revision?"applied":"pending",this.settingsErrorCode=null,this.appliedProfileRevision=l,this.personaDirty=this.appliedProfileRevision!==this.profileRevision,m.info(f,`runtime initialized generation=${this.runtimeGeneration} prompt_schema=${p.schemaVersion} prompt_sha256=${p.sha256} prompt_length=${p.length}`),await this.persistCatalogCache(i.providerId??H),this.pushToolbarMeta(),this.settingsState==="pending"&&!this.active&&!this.stopped&&this.rebuildRuntime("settings_changed_during_start")}catch(g){throw this.settingsState="failed",this.settingsErrorCode=String(g?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.applied=void 0,this.pushToolbarMeta(),await this.stopRuntime(!0),g}}ensureRuntimeWithRetry(){if(this.runtimeStartPromise)return this.runtimeStartPromise;const e=this.ensureRuntimeWithRetryLoop();this.runtimeStartPromise=e;const t=()=>{this.runtimeStartPromise===e&&(this.runtimeStartPromise=null)};return e.then(t,t),e}async ensureRuntimeWithRetryLoop(){let e;for(let t=1;t<=G;t++)try{await this.ensureRuntime();return}catch(i){e=i;const s=String(i?.code??"");if(this.cancelRequested||!De(s)||t===G)throw i;m.warn(f,`runtime ensure retry attempt=${t} code=${s||"unknown"}`),this.settingsState="pending",this.settingsErrorCode=s||"runtime_initialize_failed",this.runtimeReadiness=this.settingsErrorCode,this.pushToolbarMeta(),await this.stopRuntime(!0),await et(Ce(t))}throw e}onNotification(e,t){const i=Ze(t);if(e==="session.event"){const s=pe(t);if(!s){this.onProtocolError(new Error("malformed session.event"));return}const o=this.onSessionEvent(s);this.advanceBridgeAck(i,o);return}if(e==="session.status"){const s=t&&typeof t=="object"?t:{};if(String(s.sessionId??"")===this.runtimeSessionId){this.touchActivity(),this.correlator?.markRootStatus(String(s.status??"")),s.status==="idle"&&this.active&&this.correlator&&m.debug(f,`turn correlation idle admitted=${this.active.admitted} claimed=${this.active.claimed} ended=${this.active.turnEnded} complete=${this.correlator.complete}`);const d=!!this.correlator?.complete;d&&this.finishFromTurnOutcome(),this.advanceBridgeAck(i,d)}else i>0&&this.advanceBridgeAck(i,!1);return}if(e==="subagent.started"||e==="subagent.finished"){this.touchActivity(3);const s=t&&typeof t=="object"?t:{},o=String(s.childSessionId??s.sessionId??"");o&&this.capture?.addChild(o),this.active&&this.callbacks.sendRawEventEnvelope(this.active.inbound.event_id,this.active.inbound.session_id,{type:e,payload:s},e==="subagent.started"?"[subagent started]":"[subagent finished]"),this.advanceBridgeAck(i,!1);return}this.onProtocolError(new Error(`unknown required JSON-RPC notification: ${e}`))}onSessionEvent(e){if(!this.active||!this.correlator)return!1;this.touchActivity(e.type==="tool/call"||e.type==="tool/result"?3:1);const t=ue(e);if(t.kind==="unknown"&&!rt(e)&&e.ignorable!==!0)return this.onProtocolError(new Error(`unknown required SessionEvent: ${e.type}`)),!1;if(e.sessionId&&e.sessionId!==this.runtimeSessionId)return!1;const i=this.correlator.accept(e);if((e.type==="agent/inbox/spliced"||e.type==="user/message"||e.type==="turn/end")&&m.debug(f,`turn correlation event=${e.type} belongs=${i} admitted=${this.active.admitted} claimed=${this.active.claimed} ended=${this.active.turnEnded}`),e.type==="agent/inbox/spliced"&&this.active.admitted){const s=V(this.active.inbound,this.injectedMessageIds);for(const o of s.contextIds)this.injectedMessageIds.add(o);s.currentMessageId&&this.injectedMessageIds.add(s.currentMessageId)}return i?st(e)?(this.flushPendingTextAsThinking(),!1):t.kind==="text"?(t.payload?.committed===!0?(t.payload?.hasToolCall===!0?this.applyCommittedToolStepText(t.text??""):this.applyCommittedText(t.text??""),t.usage&&this.collectCommittedUsage(t.usage,Number(e.seq??e.step??Date.now()))):this.applyTextDelta(t.text??""),!1):t.kind==="thinking"?(this.thinkingEnabled()&&this.callbacks.sendThinking(this.active.inbound.event_id,this.active.inbound.session_id,t.text??""),!1):t.kind==="tool_call"?(this.flushPendingTextAsThinking(),this.toolEventsEnabled()&&this.sendRaw("tool_call",{call_id:t.callId,tool_name:t.name,tool_input:t.input},`[tool] ${t.name}`),!1):t.kind==="tool_result"?(this.toolEventsEnabled()&&this.sendRaw("tool_result",{call_id:t.callId,result:t.output},`[tool result] ${t.callId??""}`),!1):t.kind==="todo"||t.kind==="compaction"?!1:t.kind==="context"?(this.updateContextCapacity(t.payload),!1):t.kind==="usage"?(this.updateContextWindow(t.usage),!1):t.kind==="turn_end"&&this.correlator.complete?(this.finishFromTurnOutcome(),!0):!1:!1}applyTextDelta(e){this.active.pendingText=`${this.active.pendingText??""}${e}`}applyCommittedText(e){const t=this.active;if(t.pendingText=void 0,e.startsWith(t.text))t.text=e;else if(!t.text.startsWith(e)){m.warn(f,`committed assistant text diverged event=${t.inbound.event_id}`);const i=W(e).quotedMessageId;i&&(this.quotedMessageId=i),t.text=t.sentText}this.flushVisibleText(!1)}flushPendingTextAsThinking(){const e=this.active,t=e?.pendingText;!e||!t||(e.pendingText=void 0,this.thinkingEnabled()&&t.trim()&&this.callbacks.sendThinking(e.inbound.event_id,e.inbound.session_id,t),e.lastThinkingText=t)}applyCommittedToolStepText(e){const t=this.active;t&&(t.pendingText=void 0,e.trim()&&t.lastThinkingText!==e&&this.thinkingEnabled()&&(this.callbacks.sendThinking(t.inbound.event_id,t.inbound.session_id,e),t.lastThinkingText=e))}promotePendingTextToVisible(){const e=this.active,t=e?.pendingText;!e||!t||(e.pendingText=void 0,e.text+=t)}flushVisibleText(e,t={}){const i=this.active;if(!i)return;const s=W(i.text);s.quotedMessageId&&(this.quotedMessageId=s.quotedMessageId);const o=s.text.replace(/\[\[quoted_message_id:[^\]]*$/g,""),d=ce(o,{finalize:t.finalizeDsml===!0||e});this.surfaceSuppressedDsmlToolCalls(d.suppressedToolCalls);const l=d.visible;this.observeVisibleTextAfterToolCall(l);let a="";l.startsWith(i.sentText)?a=l.slice(i.sentText.length):(e||t.finalizeDsml)&&(a=l),!(!a&&!e)&&(i.seq+=1,this.callbacks.sendStreamChunk(i.inbound.event_id,i.inbound.session_id,a,i.seq,e,`${i.inbound.event_id}-dsh`,this.quotedMessageId),i.sentText=l)}surfaceSuppressedDsmlToolCalls(e){if(!this.active||e.length===0)return;const t=this.active.dsmlSuppressedKeys??new Set;this.active.dsmlSuppressedKeys=t;for(const i of e){const s=he(i);if(t.has(s)||(t.add(s),this.markToolCallAwaitingFinalText(),m.warn(f,`suppressed leaked DSML tool markup name=${i.name} event=${this.active.inbound.event_id}`),!this.toolEventsEnabled()))continue;let o=i.arguments;try{o=JSON.parse(i.arguments)}catch{}this.sendRaw("tool_call",{call_id:`dsml-${t.size}`,tool_name:i.name,tool_input:o,source:"dsml_text_leak",executed:!1},`[tool] ${i.name}`)}}markToolCallAwaitingFinalText(){const e=this.active;e&&(e.toolCallAwaitingFinalText=!0,e.toolCallVisibleTextLength=e.sentText.length)}observeVisibleTextAfterToolCall(e){const t=this.active;if(!t?.toolCallAwaitingFinalText)return;const i=t.toolCallVisibleTextLength??t.sentText.length;e.slice(i).trim().length!==0&&(t.toolCallAwaitingFinalText=!1,t.toolCallVisibleTextLength=void 0)}collectCommittedUsage(e,t){if(this.activeCommittedUsageSeqs.has(t))return;this.activeCommittedUsageSeqs.add(t);const i=K(e);this.activeUsage.inputTokens+=i.inputTokens,this.activeUsage.outputTokens+=i.outputTokens,this.activeUsage.cacheReadInputTokens+=i.cacheReadInputTokens,this.activeUsage.cacheCreationInputTokens+=i.cacheCreationInputTokens,this.activeUsage.reasoningTokens+=i.reasoningTokens,this.activeUsageSeq=Math.max(this.activeUsageSeq,t),this.updateContextWindow(i)}updateContextWindow(e){const t=K(e),i=this.resolveDesiredSettings(),s=this.models.find(d=>d.id===i.modelId),o=this.reportedContextCapacity??s?.contextWindow;if(o&&o>0){const d=t.inputTokens+t.cacheReadInputTokens+t.cacheCreationInputTokens;this.contextWindow={usedTokens:d,totalTokens:o,remainingTokens:Math.max(0,o-d),usedPercentage:d/o*100,remainingPercentage:Math.max(0,100-d/o*100)},this.pushToolbarMeta()}}updateContextCapacity(e){const t=Number(e?.contextWindow);if(!Number.isFinite(t)||t<=0)return;this.reportedContextCapacity=t;const i=this.contextWindow&&typeof this.contextWindow=="object"?this.contextWindow:{},s=Math.max(0,Number(i.usedTokens)||0);this.contextWindow={usedTokens:s,totalTokens:t,remainingTokens:Math.max(0,t-s),usedPercentage:s/t*100,remainingPercentage:Math.max(0,100-s/t*100)},this.pushToolbarMeta()}finishFromTurnOutcome(){if(!this.active)return;this.finishingTurn=!0;const e=this.active.outcome??"completed",t=this.active.outcomeDetail?.trim();e==="completed"?this.finishActive("responded"):e==="aborted"?this.finishActive("canceled"):e==="max-tokens"&&this.active.sentText?this.finishActive("responded","Response truncated at model token limit"):this.finishActive("failed",t?t.toLowerCase().includes(e.toLowerCase())?`Harness turn ended: ${t}`:`Harness turn ended: ${e}: ${t}`:`Harness turn ended: ${e}`)}finishActive(e,t){const i=this.active;if(!i)return;let s=e,o=t;this.finishingTurn=!0,this.clearTimeout(),this.promotePendingTextToVisible(),this.flushVisibleText(!1,{finalizeDsml:!0}),s==="responded"&&i.toolCallAwaitingFinalText&&(s="failed",o="DeepSeek Harness ended after a tool call without returning final assistant text",m.warn(f,`${o} event=${i.inbound.event_id}`)),i.text=i.sentText;const d=s==="failed"&&!!o?.trim();d&&(i.text+=`
2
2
 
3
3
  Error: ${o}`,this.flushVisibleText(!1,{finalizeDsml:!0})),s==="responded"&&this.activeUsageSeq>=0&&(this.usageStore().commit(i.inbound.session_id,this.runtimeSessionId,this.activeUsageSeq,this.applied?.modelId??this.resolveDesiredSettings().modelId,this.activeUsage),this.usageStore().flush()),i.inbound.audit?.enabled&&this.capture&&this.auditBoundaries.set(i.inbound.event_id,this.capture.boundary({runtimeSessionId:this.runtimeSessionId,rootSessionId:this.runtimeSessionId,startOffset:this.activeWireStart,turn:i.turn,messageId:i.messageId}));const l=this.personaDirty&&!!this.runtime,a=!!this.runtime&&!!this.applied&&this.applied.appliedRevision!==this.resolveDesiredSettings().revision;l&&this.emit("pauseIntake","barrier"),this.active=null,this.correlator=null;const p=`${i.inbound.event_id}-dsh`,c=(n,r,u=!1)=>{this.callbacks.sendEventResult(i.inbound.event_id,n,r,u),this.emit("eventDone",i.inbound.event_id),l?this.rebuildRuntime("persona_changed"):a&&this.rebuildRuntime("settings_changed")};this.callbacks.sendFinalStreamChunkReliable(i.inbound.event_id,i.inbound.session_id,p).then(async()=>{await this.flushPendingFinalBridgeAck(!0),c(s,o,d)},async n=>{await this.flushPendingFinalBridgeAck(!1),c(s==="responded"?"failed":s,s==="responded"?`Final output delivery failed: ${this.redactError(n,i.inbound.content)}`:o)})}advanceBridgeAck(e,t){if(!(e<=0)){if(t||this.finishingTurn||this.pendingFinalBridgeAck!==null){this.pendingFinalBridgeAck=Math.max(this.pendingFinalBridgeAck??0,e);return}this.ackBridgeCursor(e)}}async flushPendingFinalBridgeAck(e){const t=this.pendingFinalBridgeAck;this.pendingFinalBridgeAck=null,this.finishingTurn=!1,!(!e||t===null)&&await this.ackBridgeCursor(t)}async ackBridgeCursor(e){if(e<=this.bridgeAckCursor)return;const t=this.runtime?.client?.ack;if(!t){this.bridgeAckCursor=Math.max(this.bridgeAckCursor,e);return}try{await t.call(this.runtime.client,e),this.bridgeAckCursor=Math.max(this.bridgeAckCursor,e)}catch(i){this.onProtocolError(i instanceof Error?i:new Error(String(i)))}}async cancelActive(e){this.active&&(this.cancelRequested=!0,this.clearPendingApprovals("cancelled"),this.resolveIntegrationMode()==="embedded_jsonrpc"?(this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="applied",this.pushToolbarMeta(),this.runtimeStartPromise&&this.runtime&&await this.runtime.terminate().catch(()=>{}),await this.runtimeStartPromise?.catch(()=>{}),await this.stopRuntime(!0)):(await this.runtimeStartPromise?.catch(()=>{}),await this.runtime?.cancel(this.runtimeSessionId).catch(()=>{}),this.runtime&&!this.runtime.isConnected()&&await this.stopRuntime(!0)),this.finishActive("canceled",e))}async handleBridgeApproval(e){const t=this.permissionHandler,i=String(e.interactionId??e.callId??M());if(t)try{return await t({adapterSessionId:this.options.aibotSessionId,requestId:i,description:String(e.reason??`Allow ${String(e.toolName??"operation")}?`),options:[{id:"allow_once",label:"Allow once",isAllow:!0},{id:"reject",label:"Reject",isAllow:!1}]})==="allow_once"?"allowed-once":"rejected"}catch{return"cancelled"}const s=this.active;return s?(this.callbacks.sendPermissionCard({eventId:s.inbound.event_id,sessionId:s.inbound.session_id,approvalId:i,toolName:String(e.toolName??"operation"),toolTitle:String(e.reason??`Allow ${String(e.toolName??"operation")}?`)}),new Promise(o=>{const d=setTimeout(()=>{this.pendingApprovals.delete(i),o("unavailable")},3e5);d.unref?.(),this.pendingApprovals.set(i,{resolve:o,timer:d})})):"unavailable"}async invokeGrixTool(e,t,i){if(!Je(e))throw Object.assign(new Error(`grix tool "${e}" is not exposed to DSH`),{code:"capability_unavailable"});if(!this.callbacks.agentInvoke)throw Object.assign(new Error(`grix tool "${e}" has no connector-side action runner`),{code:"capability_unavailable"});const s=Xe(e,t);return this.callbacks.agentInvoke(s.action,s.params,i??s.timeoutMs)}projectConnectorSkills(){const e=Te(this.options.dshHome??this.config.env?.DSH_HOME,{...process.env,...this.config.env}),t=T(e,"skills"),i=ae(t);i.length>0&&m.info(f,`Synced connector skills to ${t}: [${i.join(", ")}]`)}rebuildRuntime(e){if(this.stopped||this.active)return Promise.resolve();if(this.rebuildPromise)return this.rebuildPromise;const t=(async()=>{this.emit("pauseIntake","barrier"),this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="pending",this.pushToolbarMeta();try{await this.stopRuntime(!0),await this.ensureRuntime()}catch(i){m.warn(f,`${e} rebuild failed: ${this.redactError(i)}`)}finally{this.emit("resumeIntake","barrier")}})();return this.rebuildPromise=t.finally(()=>{this.rebuildPromise=null;const i=this.resolveDesiredSettings().revision;!this.stopped&&!this.active&&(this.personaDirty||this.applied&&this.applied.appliedRevision!==i)&&this.rebuildRuntime("coalesced_state_changed")}),this.rebuildPromise}async stopRuntime(e){const t=this.runtime;t&&(this.intentionalRuntimeStop=e,this.runtime=null,await t.shutdown().catch(()=>t.terminate()),this.capture?.close(),this.capture=null,this.intentionalRuntimeStop=!1)}onRuntimeExit(){this.intentionalRuntimeStop||this.stopped||(this.runtime=null,this.capture?.close(),this.capture=null,this.applied=void 0,this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState="failed",this.settingsErrorCode="runtime_exited",this.pushToolbarMeta(),this.active&&this.finishActive("failed","Harness runtime exited; prompt was not replayed"),this.emit("exit",1))}onProtocolError(e){if(this.stopped||!this.runtime&&!this.active)return;const t=this.redactError(e,this.active?.inbound.content);this.clearPendingApprovals("unavailable"),this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState="failed",this.settingsErrorCode="protocol_error",this.pushToolbarMeta();const i=this.runtime;this.runtime=null,this.intentionalRuntimeStop=!0,i?.client?.close(e),this.active&&this.finishActive("failed",`Harness protocol error: ${t}`),i?.terminate().finally(()=>{this.intentionalRuntimeStop=!1}),this.emit("exit",1)}async executeLocalAction(e){const t=e.params??{},i=String(t.session_id??"");if(!i||i!==this.options.aibotSessionId)return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing"};if(["exec_approve","exec_reject","permission_approve","permission_reject"].includes(e.action_type)){const n=String(t.approval_command_id??t.approval_id??t.request_id??"").trim(),r=this.pendingApprovals.get(n);if(!r)return{status:"failed",errorCode:"unknown_or_expired_approval_id",errorMsg:"That DSH approval request is no longer pending"};clearTimeout(r.timer),this.pendingApprovals.delete(n);const u=e.action_type==="exec_approve"||e.action_type==="permission_approve";return r.resolve(u?"allowed-once":"rejected"),{status:"ok",result:{approval_id:n,decision:u?"allow-once":"deny"}}}if(e.action_type==="get_session_usage")return{status:"ok",result:{adapterType:"deepseek-harness",available:!0,dsh_profile:this.resolveSelectedProfile(),...this.usageStore().get(i)}};if(e.action_type==="get_rate_limits"){this.providerQuota=null,this.pushToolbarMeta();try{this.providerQuota=await this.callbacks.queryProviderQuota(!0)??{provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:"unavailable"}}catch(n){this.providerQuota={provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:this.redactError(n)}}return this.pushToolbarMeta(),{status:"ok",result:{sampledAt:new Date().toISOString(),contextWindow:this.contextWindow,providerQuota:this.providerQuota}}}if(e.action_type==="dsh_bridge_status"||e.action_type==="dsh_install_bridge"){if(this.resolveIntegrationMode()!=="profile_bridge")return{status:"unsupported",errorCode:"capability_unavailable",errorMsg:"Bridge management requires Profile Bridge mode"};if(this.active||this.runtime)return{status:"failed",errorCode:"worker_busy",errorMsg:"Stop the active DSH session before changing its Profile plugin"};try{const n=new R({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),r=e.action_type==="dsh_install_bridge"?await n.install():await n.status();return this.runtimeReadiness=r.readiness,this.settingsErrorCode=r.readiness==="ready"?null:r.readiness,this.pushToolbarMeta(),{status:"ok",result:ot(r)}}catch(n){const r=String(n?.code??"bridge_install_failed");return this.runtimeReadiness=r,this.settingsErrorCode=r,this.pushToolbarMeta(),{status:"failed",errorCode:r,errorMsg:this.redactError(n)}}}if(e.action_type==="dsh_list_plugins"||e.action_type==="dsh_refresh_plugins"||e.action_type==="dsh_enable_plugin"||e.action_type==="dsh_disable_plugin")return this.executePluginAction(e.action_type,t,i);const o={dsh_list_skills:"skills/list",dsh_list_mcp:"mcp/list",dsh_list_tools:"tools/list",dsh_list_jobs:"jobs/list",dsh_list_goals:"goals/list"}[e.action_type];if(o){if(this.resolveIntegrationMode()!=="profile_bridge")return{status:"unsupported",errorCode:"capability_unavailable",errorMsg:"DSH resources require Profile Bridge mode"};if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot query DSH resources during an active turn"};try{return await this.ensureRuntimeWithRetry(),{status:"ok",result:await this.runtime?.client?.call(o,{cwd:this.options.bindingStore.get(i)?.cwd})}}catch(n){const r=String(n?.code??"resource_query_failed");return{status:r==="capability_unavailable"?"unsupported":"failed",errorCode:r,errorMsg:this.redactError(n)}}}if(e.action_type==="set_profile"||e.action_type==="create_profile"){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek Harness Profile during an active turn"};if(!this.options.bindingStore.get(i))return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};let n;try{n=Se(String(t.profile_id??t.dsh_profile??t.profile_name??t.name??""))}catch(u){return{status:"failed",errorCode:"profile_invalid",errorMsg:this.redactError(u)}}if(this.options.bindingStore.isDshProfileLocked(i)){const u=this.resolveSelectedProfile();return e.action_type==="create_profile"||u!==n?{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}:this.finishProfileSelection(n,!1)}if(e.action_type==="create_profile")try{const u=this.options.createDshProfile?await this.options.createDshProfile(n):await fe({profileName:n,dshHome:this.options.dshHome??this.config.env?.DSH_HOME}),v=u.identity?.profileName??n;return this.persistSelectedProfile(v)?(await this.flushSelectedProfile(),this.finishProfileSelection(v,u.created)):{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}}catch(u){return{status:"failed",errorCode:String(u?.code??"profile_create_failed"),errorMsg:this.redactError(u)}}return this.listProfiles().some(u=>u.id===n)?this.persistSelectedProfile(n)?(await this.flushSelectedProfile(),this.finishProfileSelection(n,!1)):{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}:{status:"failed",errorCode:"profile_not_found",errorMsg:"Requested DSH profile is not in the local catalog"}}if(e.action_type==="set_preset"){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek Harness settings during an active turn"};if(!this.options.bindingStore.get(i)?.cwd)return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const r=String(t.agent_preset_id??t.preset_id??"").trim();if(!this.presets.some(v=>v.id===r))return{status:"failed",errorCode:"preset_not_found",errorMsg:"Requested agent preset is not in the Harness catalog"};const u=Q(this.resolveDesiredSettings().agentPreset,this.presets);return this.options.bindingStore.isDshAgentPresetLocked(i)?u===r?{status:"ok",result:this.presetActionResult(r,!0)}:{status:"failed",errorCode:"agent_preset_locked",errorMsg:"This conversation scene is locked after the session is created"}:u===r?(this.options.bindingStore.setDshAgentPreset(i,r),await this.persistGlobalToolbarDefaults({dshAgentPreset:r}),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(r,!1)}):this.options.bindingStore.setDshAgentPreset(i,r)?(await this.persistGlobalToolbarDefaults({dshAgentPreset:r}),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(r,!1)}):{status:"failed",errorCode:"agent_preset_locked",errorMsg:"This conversation scene is locked after the session is created"}}if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek Harness settings during an active turn"};if(!this.options.bindingStore.get(i)?.cwd)return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const l=this.resolveDesiredSettings();let a;if(e.action_type==="set_provider"){const n=String(t.provider_id??"").trim();if(!this.providers.some(r=>r.id===n))return{status:"failed",errorCode:"provider_not_found",errorMsg:"Requested provider is not in the Harness catalog"};a={providerId:n},n!==l.providerId&&(this.models=We(this.options.dataRoot,n),this.catalogProviderId=n,this.models.some(r=>r.id===l.modelId)||(a.modelId=this.models[0]?.id))}else if(e.action_type==="set_model"){const n=String(t.model_id??"").trim();if(!this.models.some(r=>r.id===n))return{status:"failed",errorCode:"model_not_found",errorMsg:"Requested model is not in the Harness catalog"};a={modelId:n}}else{const n=String(t.mode_id??"").trim();if(n!=="approval"&&n!=="full_auto")return{status:"failed",errorCode:"mode_invalid",errorMsg:"mode_id must be approval or full_auto"};a={modeId:n}}if((a.providerId===void 0||a.providerId===l.providerId)&&(a.modelId===void 0||a.modelId===l.modelId)&&(a.modeId===void 0||a.modeId===l.modeId)&&this.applied?.appliedRevision===l.revision)return{status:"ok",result:this.settingsActionResult(e.action_type,a,l.revision,"already_applied",!0)};const c=this.options.bindingStore.updateDshSettings(i,a)??l.revision;if(await this.options.bindingStore.flush(),(a.providerId||a.modelId||a.modeId)&&await this.persistGlobalToolbarDefaults({...a.providerId?{dshProviderId:a.providerId}:{},...a.modelId?{dshModelId:a.modelId}:{},...a.modeId?{dshModeId:a.modeId}:{}}),this.contextWindow=null,this.reportedContextCapacity=null,this.settingsErrorCode=null,this.runtimeStartPromise&&await this.runtimeStartPromise.catch(()=>{}),!this.runtime)return this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,a,c,"applied",!1)};if(this.active)return this.applied&&this.applied.appliedRevision>=c?(this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,a,c,"applied",!0)}):(this.settingsState="pending",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,a,c,"pending",!0)});this.settingsState="pending",this.pushToolbarMeta();try{if(await this.rebuildRuntime("settings_changed"),!this.applied||this.applied.appliedRevision<c)throw new Error("new runtime did not apply requested revision");return this.refreshProviderQuota(!0),{status:"ok",result:this.settingsActionResult(e.action_type,a,c,"applied",!0)}}catch(n){return{status:"failed",result:this.settingsActionResult(e.action_type,a,c,"failed",!1,this.redactError(n)),errorCode:"settings_apply_failed",errorMsg:this.redactError(n)}}}async finishProfileSelection(e,t){if(this.resolveIntegrationMode()==="profile_bridge")try{await this.prepareSelectedProfile()}catch(i){const s=String(i?.code??"profile_start_failed");return this.runtimeReadiness=s,this.settingsErrorCode=s,this.pushToolbarMeta(),{status:"failed",errorCode:s,errorMsg:this.redactError(i)}}return this.pushToolbarMeta(),{status:"ok",result:this.profileActionResult(e,t)}}createBridgeInstaller(){const e=this.options.bridgeInstallerOptions??{};return new R({command:e.command??"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile(),...e.tarballPath?{tarballPath:e.tarballPath}:{}})}async healBridgeUpdate(e){return e.readiness!=="bridge_update_required"||this.options.autoInstallBridge===!1?e:(m.info(f,`auto-updating stale Bridge profile=${e.identity.profileName} installed=${e.installedBridgeVersion??"none"} bundled=${e.bundledBridgeVersion}`),await this.prepareSelectedProfile(),this.attachSelectedProfile())}async ensureProfileReadyForChat(){if(!(this.options.autoInstallBridge!==!1||this.options.autoStartProfile!==!1)){const s=await this.attachSelectedProfile(),o=A(s);if(o)throw o;return}this.settingsState="pending",this.pushToolbarMeta(),await this.prepareSelectedProfile();let t=await this.attachSelectedProfile();t.readiness==="bridge_update_required"&&(t=await this.healBridgeUpdate(t));const i=A(t);if(i)throw i}async attachSelectedProfile(){const t=await this.createBridgeInstaller().status();return this.runtimeReadiness=t.readiness,this.settingsErrorCode=t.readiness==="ready"?null:t.readiness,t}async prepareSelectedProfile(){const e=this.createBridgeInstaller(),t=await xe({installer:e,autoInstall:this.options.autoInstallBridge!==!1,autoStart:this.options.autoStartProfile!==!1});this.runtimeReadiness=t.readiness,this.settingsErrorCode=t.readiness==="ready"?null:t.readiness}profileActionResult(e,t){return{outcome:t?"profile_created":"profile_set",profile_id:e,dsh_profile:e,created:t,dsh_profile_locked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),dsh_profile_create:!this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),available_profiles:this.listProfiles(),session_context:{dsh_profile:e,dsh_profile_locked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),dsh_profile_create:!this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId)}}}persistSelectedProfile(e){return this.options.bindingStore.setDshSelectedProfile(this.options.aibotSessionId,e)?(this.options.globalConfigStore?.set(this.options.agentName,{dshProfile:e}),!0):!1}async persistGlobalToolbarDefaults(e){this.options.globalConfigStore&&Object.values(e).some(t=>t!==void 0)&&(this.options.globalConfigStore.set(this.options.agentName,e),await this.options.globalConfigStore.flush())}seedSessionToolbarFromGlobal(){const e=this.options.aibotSessionId,t=this.options.bindingStore.get(e);if(!t?.cwd)return;const i=this.resolveDesiredSettings(),s={};t.dshProviderId||(s.providerId=i.providerId),t.dshModelId||(s.modelId=i.modelId),t.dshModeId||(s.modeId=i.modeId),Object.keys(s).length>0&&this.options.bindingStore.updateDshSettings(e,s),!this.options.bindingStore.getDshAgentPreset(e)&&i.agentPreset&&this.options.bindingStore.setDshAgentPreset(e,i.agentPreset),this.options.bindingStore.getDshSelectedProfile(e)||this.options.bindingStore.setDshSelectedProfile(e,this.resolveSelectedProfile())}async flushSelectedProfile(){await this.options.bindingStore.flush(),await this.options.globalConfigStore?.flush()}listProfiles(){return ke({dshHome:this.options.dshHome??this.config.env?.DSH_HOME})}pluginCommandContext(){return{dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile(),enabledPluginIds:this.options.bindingStore.getDshEnabledPlugins(this.options.aibotSessionId)}}currentPlugins(){try{return E(this.pluginCommandContext())}catch{return[]}}pluginRestartRequired(){return!1}async executePluginAction(e,t,i){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek plugins during an active turn"};if(!this.options.bindingStore.get(i))return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const s=this.pluginCommandContext();try{if(e==="dsh_list_plugins"||e==="dsh_refresh_plugins"){const n=E(s);return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(n,!1)}}const o=String(t.name??t.plugin_name??"").trim(),d=this.options.bindingStore.getDshEnabledPlugins(i);let l=o;try{const{plugin:n}=ve({...s,name:o});l=n.name}catch(n){const r=String(n?.code??"");if(e!=="dsh_disable_plugin"||r!=="plugin_not_found"||!d.includes(o))throw n}const a=be(d,l,e==="dsh_enable_plugin"),p=this.options.bindingStore.setDshEnabledPlugins(i,a.pluginIds)??this.resolveDesiredSettings().revision;await this.options.bindingStore.flush();const c=E({...s,enabledPluginIds:a.pluginIds});if(!a.changed)return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(c,!1,"skipped")};if(this.runtimeStartPromise&&await this.runtimeStartPromise.catch(()=>{}),!this.runtime)return this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(c,!0,"skipped")};if(this.settingsState="pending",this.pushToolbarMeta(),await this.rebuildRuntime("plugin_changed"),!this.applied||this.applied.appliedRevision<p)throw new Error("new runtime did not apply requested plugin revision");return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(c,!0,"restarted")}}catch(o){return{status:"failed",errorCode:String(o?.code??"plugin_action_failed"),errorMsg:this.redactError(o)}}}pluginActionResult(e,t,i="skipped"){const s=this.resolveSelectedProfile(),o=this.pluginRestartRequired();return{outcome:t?i==="restarted"?"plugin_applied":"plugin_updated":"plugin_unchanged",dsh_profile:s,dsh_plugins:e,dsh_plugin_restart_required:o,restart:i,session_context:{dsh_profile:s,dsh_plugins:e,dsh_plugin_restart_required:o}}}resolveSelectedProfile(){const e=this.options.bindingStore.getDshSelectedProfile(this.options.aibotSessionId),t=we({binding:e,global:this.options.globalConfigStore?.get(this.options.agentName)?.dshProfile,adapter:this.options.dshProfile});return this.options.bindingStore.get(this.options.aibotSessionId)&&e!==t&&this.options.bindingStore.setDshSelectedProfile(this.options.aibotSessionId,t),t}profileDataDir(e=this.resolveSelectedProfile()){return Pe(this.options.dataRoot,e)}usageStore(){const e=this.resolveSelectedProfile(),t=T(this.profileDataDir(e),"session-usage.json"),i=T(this.options.dataRoot,"session-usage.json");return!L(t)&&L(i)&&(ne(re(t),{recursive:!0,mode:448}),oe(i,t)),Ke(t)}presetActionResult(e,t){const i=this.resolveDesiredSettings();return{outcome:"preset_set",agentPreset:e,agent_preset_id:e,agent_preset_locked:t,available_presets:[...this.presets],session_context:{agent_preset_id:i.agentPreset??e,agent_preset_locked:t}}}settingsActionResult(e,t,i,s,o,d){const l=this.resolveDesiredSettings(),a=l.revision||i,p={provider_id:l.providerId,model_id:l.modelId,mode_id:l.modeId,applied_provider_id:this.applied?.providerId??null,applied_model_id:this.applied?.modelId??null,applied_mode_id:this.applied?.modeId??null,applied_settings_revision:this.applied?.appliedRevision??null,settings_state:this.settingsState,settings_revision:a};return e==="set_mode"&&(p.sandbox_mode=z(l.modeId),p.approval_policy=l.modeId==="full_auto"?"never":"ask"),{outcome:`${e==="set_provider"?"provider":e==="set_model"?"model":"mode"}_set${s==="pending"||s==="failed"?"_pending":""}`,...t.providerId?{providerId:t.providerId,provider_id:t.providerId}:{},...t.modelId?{modelId:t.modelId,model_id:t.modelId}:{},...t.modeId?{modeId:t.modeId,mode_id:t.modeId,sandbox_mode:z(t.modeId),approval_policy:t.modeId==="full_auto"?"never":"ask"}:{},settingsRevision:a,settings_revision:a,sessionAlive:o,available_providers:[...this.providers],available_models:[...this.models],session_context:p,...d?{error:d}:{}}}hydrateCatalogFromCache(){const e=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),t=this.options.globalConfigStore?.get(this.options.agentName),i=Ge({dataRoot:this.options.dataRoot,providerId:e?.providerId??t?.dshProviderId});this.providers=i.providers,this.models=this.options.models?.length?this.options.models:i.models,this.catalogProviderId=i.providerId}async persistCatalogCache(e){try{await ze({dataRoot:this.options.dataRoot,providers:this.providers,providerId:e,models:this.models})}catch(t){m.warn(f,`failed to persist DSH catalog cache: ${t instanceof Error?t.message:String(t)}`)}}syncGrixProvider(){const e=X(this.options.provider??{});if(e){this.providers.some(o=>o.id===b)||(this.providers=[{id:b,displayName:e.displayName},...this.providers]);const t=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),i=this.options.globalConfigStore?.get(this.options.agentName),s=t?.providerId??i?.dshProviderId;(!s||s===H||s===b)&&this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,{providerId:b});return}this.providers=this.providers.filter(t=>t.id!==b)}resolveDesiredSettings(){const e=this.options.bindingStore.get(this.options.aibotSessionId),t=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),i=this.options.globalConfigStore?.get(this.options.agentName),s=t?.providerId??i?.dshProviderId,o=this.providers.some(p=>p.id===b)?b:void 0,d=Oe(s||o,this.providers),l=[t?.modelId,i?.dshModelId,this.options.defaultModel,this.models[0]?.id].find(p=>!!p&&this.models.some(c=>c.id===p))??"deepseek-chat",a=Q(t?.agentPreset??i?.dshAgentPreset,this.presets);return{providerId:d,modelId:l,modeId:Ue(e?.dshModeId,i?.dshModeId),agentPreset:a,pluginIds:this.options.bindingStore.getDshEnabledPlugins(this.options.aibotSessionId),maxTokens:t?.maxTokens??this.options.maxTokens??qe,revision:t?.revision??0}}resolveIntegrationMode(){return this.options.integrationMode?this.options.integrationMode:(this.config.command||"").includes("dsh-jsonrpc-agent")?"embedded_jsonrpc":"profile_bridge"}pushToolbarMeta(){const e=this.options.bindingStore.get(this.options.aibotSessionId);this.callbacks.sendUpdateBindingCard(this.options.aibotSessionId,this.stopped?"stopped":this.active?"busy":"ready",e?.cwd,Be({desired:this.resolveDesiredSettings(),applied:this.applied,models:this.models,providers:this.providers,presets:this.presets,agentPresetLocked:this.options.bindingStore.isDshAgentPresetLocked(this.options.aibotSessionId),state:this.settingsState,errorCode:this.settingsErrorCode,contextWindow:this.contextWindow,providerQuota:this.providerQuota,integrationMode:this.resolveIntegrationMode(),profileName:this.resolveSelectedProfile(),profiles:this.listProfiles(),profileLocked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),plugins:this.currentPlugins(),pluginRestartRequired:this.pluginRestartRequired(),runtimeReadiness:this.runtimeReadiness,bridgeCapabilities:this.bridgeCapabilities}))}async refreshProviderQuota(e){this.providerQuota=null,this.pushToolbarMeta();try{this.providerQuota=await this.callbacks.queryProviderQuota(e)??{provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:"unavailable"}}catch{this.providerQuota={provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:"unavailable"}}this.pushToolbarMeta()}clearPendingApprovals(e){for(const t of this.pendingApprovals.values())clearTimeout(t.timer),t.resolve(e);this.pendingApprovals.clear()}thinkingEnabled(){const e=this.active?.inbound.connector_runtime_config?.thinking_events??this.active?.inbound.connector_runtime_config?.thinkingEvents;return e!=="off"&&e!=="hidden"&&e!=="none"}toolEventsEnabled(){const e=this.active?.inbound.connector_runtime_config?.tool_events;return e!=="off"&&e!=="hidden"&&e!=="none"}sendRaw(e,t,i){this.active&&this.callbacks.sendRawEventEnvelope(this.active.inbound.event_id,this.active.inbound.session_id,{type:e,payload:t},i)}failEvent(e,t){this.callbacks.sendEventResult(e.event_id,"failed",t),this.emit("eventDone",e.event_id)}startTimeout(e){this.activeTimeoutMs=e??this.options.promptTimeoutMs??J,this.noteRuntimeActivity(),this.armTimeout(this.activeIdleTimeoutMs()),this.armHardTimeout(this.activeTimeoutMs)}touchActivity(e=1){!this.active||!this.timeoutTimer||(this.noteRuntimeActivity(),this.armTimeout(this.activeIdleTimeoutMs()))}noteRuntimeActivity(){this.active&&(this.active.lastRuntimeActivityAt=Date.now(),this.active.livenessExtendStartAt=void 0)}activeIdleTimeoutMs(){const e=this.options.activeIdleTimeoutMs??Y,t=Number.isFinite(e)&&e>0?e:Y;return Math.min(t,this.activeTimeoutMs)}livenessFreshMs(){const e=this.options.livenessFreshMs??Z;return Number.isFinite(e)&&e>0?e:Z}livenessMaxExtendMs(){const e=this.options.livenessMaxExtendMs??ee;return Number.isFinite(e)&&e>0?e:ee}armTimeout(e){this.clearIdleTimeout(),this.timeoutTimer=setTimeout(()=>{this.handlePromptTimeout()},e),this.timeoutTimer.unref?.()}armHardTimeout(e){this.clearHardTimeout(),this.hardTimeoutTimer=setTimeout(()=>{this.handlePromptHardTimeout()},e),this.hardTimeoutTimer.unref?.()}async handlePromptTimeout(){const e=this.active;if(e){if(this.pendingApprovals.size>0){m.info(f,`Idle timeout skipped: pendingApprovals=${this.pendingApprovals.size} event=${e.inbound.event_id}`),this.armTimeout(this.activeIdleTimeoutMs());return}if(this.shouldExtendByLiveness(e.inbound.event_id)){this.armTimeout(this.activeIdleTimeoutMs());return}await this.failActiveTimeout("idle","Harness prompt idle timeout and the runtime was terminated")}}async handlePromptHardTimeout(){const e=this.active;if(e&&this.shouldExtendByLiveness(e.inbound.event_id)){this.armHardTimeout(this.activeTimeoutMs);return}await this.failActiveTimeout("hard","Harness prompt exceeded max duration and the runtime was terminated")}shouldExtendByLiveness(e){const t=this.active;if(!t||t.inbound.event_id!==e||!this.runtime?.isConnected()||!(!t.turnEnded&&(!!t.messageId||t.admitted||t.claimed)))return!1;const s=Date.now(),o=t.lastRuntimeActivityAt??t.startedAt,d=Math.max(0,s-o);if(d<this.livenessFreshMs())return t.livenessExtendStartAt=s,m.info(f,`Liveness check: recent DSH activity for ${e} (quietMs=${d}), extending`),!0;const l=t.livenessExtendStartAt??o;t.livenessExtendStartAt=l;const a=s-l;return a>this.livenessMaxExtendMs()?(m.warn(f,`Liveness extension budget exhausted for ${e} (quietMs=${d}, extendMs=${a}), allowing close`),!1):(m.info(f,`Liveness check: DSH turn still open for ${e} (claimed=${t.claimed}, turnEnded=${t.turnEnded}, quietMs=${d}), extending`),!0)}async failActiveTimeout(e,t){if(!this.active)return;const i=this.active;this.clearTimeout();const s=this.runtime;this.runtime=null,this.intentionalRuntimeStop=!0,this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="applied",this.settingsErrorCode=null,this.pushToolbarMeta(),await s?.cancel(this.runtimeSessionId).catch(()=>{}),s&&!s.isConnected()&&await s.terminate().catch(()=>{}),this.intentionalRuntimeStop=!1,!(this.active!==i||this.stopped)&&(m.error(f,`Active DSH turn ${e} timeout: ${i.inbound.event_id}`),this.finishActive("failed",t),this.emit("exit",1))}clearTimeout(){this.clearIdleTimeout(),this.clearHardTimeout()}clearIdleTimeout(){this.timeoutTimer&&clearTimeout(this.timeoutTimer),this.timeoutTimer=null}clearHardTimeout(){this.hardTimeoutTimer&&clearTimeout(this.hardTimeoutTimer),this.hardTimeoutTimer=null}redactError(e,t){let i=e instanceof Error?e.message:String(e);const s=this.config.env?.DEEPSEEK_API_KEY;return s&&(i=i.split(s).join("[REDACTED]")),i=i.replace(/(api[_-]?key|authorization|bearer)\s*[:=]\s*\S+/gi,"$1=[REDACTED]"),t&&t.length>=16&&i.includes(t)&&(i="Harness request failed (prompt echo redacted)"),(i.includes("[aibot-system-prompt]")||i.includes("[base-behavior]"))&&(i="Harness runtime failed (system prompt echo redacted)"),i.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g,"").slice(0,2e3)}}function Ze(h){const e=Number(h&&typeof h=="object"?h.cursor:0);return Number.isSafeInteger(e)&&e>0?e:0}function et(h){return new Promise(e=>setTimeout(e,h))}function tt(h,e){return`grix-${D("sha256").update(h).digest("hex").slice(0,12)}-${e}-${M().slice(0,8)}`}function it(h){return`grix-${D("sha256").update(h).digest("hex").slice(0,16)}-${M().slice(0,8)}`}function te(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,reasoningTokens:0}}function ie(h){const e=h.data?.chunk&&typeof h.data.chunk=="object"?h.data.chunk:h.data;return String(e?.type??"")}function st(h){return h.type==="assistant/chunk:tool-call-delta"||h.type==="assistant/chunk"&&ie(h)==="tool-call-delta"}function ot(h){return{readiness:h.readiness,profile:h.identity.profileName,dshVersion:h.dshVersion,runningDshVersion:h.runningDshVersion,installedBridgeVersion:h.installedBridgeVersion,bundledBridgeVersion:h.bundledBridgeVersion,runningBridgeVersion:h.runningBridgeVersion,endpointCount:h.endpointCount,requiresProfileRestart:h.readiness==="profile_restart_required",compatibleDshVersions:h.compatibleDshVersions}}const nt=new Set(["turn/start","step/start","step/end","agent/inbox/spliced","user/message","request/header","session/title","session/title-llm-request","session/end-seed","web/deepseek-search-llm-request","assistant/chunk:tool-call-delta","permission/preset","sandbox/mode","approval/policy","approval/asked","approval/decided","plan/mode","agent-preset/selected","llm/retry","llm/retry-started","goal/change","schedule/change","feedback/record","hook/invoked","hook/result","command/run","command/done","subagent/descriptor","tool-workflow/agent-start","tool-workflow/agent-end","tool-workflow/run-start","tool-workflow/run-end","tool/code-dispatch","tool/code-dispatch-start"]);function rt(h){const e=ie(h);return nt.has(h.type)||h.type==="assistant/chunk"&&["block-start","block-end","tool-call-delta","finish"].includes(e)}export{Ft as DshJsonRpcAdapter};
@@ -1 +1 @@
1
- import{createHash as N}from"node:crypto";import{existsSync as f,readFileSync as a,readdirSync as g,realpathSync as y,statSync as d}from"node:fs";import{homedir as H}from"node:os";import{basename as m,dirname as c,join as i,resolve as l}from"node:path";import{fileURLToPath as P}from"node:url";function u(e,r=process.env){const t=e?.trim()||r.DSH_HOME?.trim()||i(H(),".dsh");return l(t)}const s="web",S="headless";function h(e){return O(String(e??"").trim())}function E(e){const r=h(e);if(r===S)throw Object.assign(new Error("headless is a one-shot DSH profile and cannot be used as a Grix Profile"),{code:"profile_invalid"});return r}function G(e,r){return i(l(e),"profiles",h(r))}function J(e={}){for(const r of[e.binding,e.global,e.adapter]){const t=String(r??"").trim();if(t)try{return E(t)}catch{continue}}return s}function D(e){return e===s?"Web":e}function w(e,r){if(r===s)return!0;try{const n=JSON.parse(a(i(e,"package.json"),"utf8")).dsh?.profile?.bundles;return Array.isArray(n)&&n.some(o=>String(o).includes("dsh-web-app"))}catch{return!1}}function V(e={}){const r=u(e.dshHome,e.env),t=new Map;t.set(s,{id:s,displayName:D(s),webApp:!0});const n=i(r,"profiles");if(!f(n)||!d(n).isDirectory())return[...t.values()];for(const o of g(n).sort()){if(o===S||o===s||o==="node_modules")continue;try{h(o)}catch{continue}const p=i(n,o);try{if(!d(p).isDirectory()||!JSON.parse(a(i(p,"package.json"),"utf8")).dsh?.profile)continue}catch{continue}t.set(o,{id:o,displayName:D(o),webApp:w(p,o)})}return[...t.values()]}function _(e){const r=u(e.dshHome,e.env),t=h(e.profileName?.trim()||s),n=l(r,"profiles",t),o=f(n)?y(n):n;return{dshHome:r,profileName:t,profileRoot:o,profileKey:b(o)}}function b(e){return N("sha256").update(l(e)).digest("hex")}function R(e){return i(e.dshHome,"run","grix-dsh-bridge",e.profileKey)}function I(e){const r=R(e);if(!f(r)||!d(r).isDirectory())return[];const t=[];for(const n of g(r).filter(o=>o.endsWith(".json")).sort())try{const o=JSON.parse(a(i(r,n),"utf8"));if(!A(o)||o.profileKey!==e.profileKey||!M(o.pid)||!f(o.tokenPath)||!d(o.tokenPath).isFile())continue;t.push(o)}catch{}return t}function W(e){const r=I(e);if(r.length===0)throw Object.assign(new Error(`No live Grix Bridge endpoint in DSH profile "${e.profileName}". If Bridge is already installed, restart the profile (stop it, then: dsh --profile ${e.profileName}); otherwise install the Grix Bridge plugin first.`),{code:"bridge_missing"});if(r.length>1)throw Object.assign(new Error(`Multiple live Grix Bridge endpoints found for DSH profile "${e.profileName}". Stop extra profile processes so only one instance remains.`),{code:"profile_instance_ambiguous"});return r[0]}function $(e){let r=c(P(e)),t;for(;c(r)!==r;){const o=i(r,"package.json");if(f(o))try{if(JSON.parse(a(o,"utf8")).dsh?.profile)return x(r)}catch{}m(r)==="node_modules"&&(t=c(r)),r=c(r)}if(t)return x(t);const n=u();return _({dshHome:n,profileName:process.env.GRIX_DSH_PROFILE||s})}function x(e){const r=y(e),t=m(r),n=c(r);return{dshHome:m(n)==="profiles"?c(n):u(),profileName:t,profileRoot:r,profileKey:b(r)}}function O(e){if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\")||e.includes("\0"))throw Object.assign(new Error("Invalid DSH profile name"),{code:"profile_invalid"});return e}function A(e){return e.schemaVersion===1&&(e.transport==="unix"||e.transport==="pipe")&&typeof e.address=="string"&&e.address.length>0&&Number.isSafeInteger(e.pid)&&Number(e.pid)>0&&typeof e.startedAt=="string"&&typeof e.profileKey=="string"&&typeof e.profileName=="string"&&typeof e.dshVersion=="string"&&typeof e.bridgeVersion=="string"&&Number.isSafeInteger(e.protocolMin)&&Number.isSafeInteger(e.protocolMax)&&typeof e.instanceId=="string"&&typeof e.tokenPath=="string"}function M(e){try{return process.kill(e,0),!0}catch(r){return r.code==="EPERM"}}export{s as DEFAULT_DSH_PROFILE_NAME,S as DSH_HEADLESS_PROFILE_NAME,E as assertSelectableDshProfileName,R as bridgeDiscoveryDirectory,I as discoverDshBridgeEndpoints,D as dshProfileDisplayName,$ as inferProfileIdentityFromModule,V as listDshProfiles,h as parseDshProfileName,w as profileHasWebApp,b as profileKeyFor,G as resolveDshConnectorProfileDataDir,u as resolveDshHome,_ as resolveDshProfileIdentity,J as resolveDshSelectedProfileName,W as selectDshBridgeEndpoint};
1
+ import{createHash as H}from"node:crypto";import{existsSync as p,readFileSync as a,readdirSync as y,realpathSync as g,statSync as d}from"node:fs";import{homedir as P}from"node:os";import{basename as h,dirname as c,join as i,resolve as l}from"node:path";import{fileURLToPath as E}from"node:url";function u(e,r=process.env){const t=e?.trim()||r.DSH_HOME?.trim()||i(P(),".dsh");return l(t)}const s="web",D="headless";function m(e){return O(String(e??"").trim())}function A(e){const r=m(e);if(r===D)throw Object.assign(new Error("headless is a one-shot DSH profile and cannot be used as a Grix Profile"),{code:"profile_invalid"});return r}function J(e,r){return i(l(e),"profiles",m(r))}function C(e={}){for(const r of[e.binding,e.global,e.adapter]){const t=String(r??"").trim();if(t)try{return A(t)}catch{continue}}return s}function S(e){return e===s?"Web":e}function R(e,r){if(r===s)return!0;try{const n=JSON.parse(a(i(e,"package.json"),"utf8")).dsh?.profile?.bundles;return Array.isArray(n)&&n.some(o=>String(o).includes("dsh-web-app"))}catch{return!1}}function V(e={}){const r=u(e.dshHome,e.env),t=new Map;t.set(s,{id:s,displayName:S(s),webApp:!0});const n=i(r,"profiles");if(!p(n)||!d(n).isDirectory())return[...t.values()];for(const o of y(n).sort()){if(o===D||o===s||o==="node_modules")continue;try{m(o)}catch{continue}const f=i(n,o);try{if(!d(f).isDirectory()||!JSON.parse(a(i(f,"package.json"),"utf8")).dsh?.profile)continue}catch{continue}t.set(o,{id:o,displayName:S(o),webApp:R(f,o)})}return[...t.values()]}function w(e){const r=u(e.dshHome,e.env),t=m(e.profileName?.trim()||s),n=l(r,"profiles",t),o=p(n)?g(n):n;return{dshHome:r,profileName:t,profileRoot:o,profileKey:N(o)}}function N(e){return H("sha256").update(l(e)).digest("hex")}function I(e){return i(e.dshHome,"run","grix-dsh-bridge",e.profileKey)}function _(e){const r=I(e);if(!p(r)||!d(r).isDirectory())return[];const t=[];for(const n of y(r).filter(o=>o.endsWith(".json")).sort())try{const o=JSON.parse(a(i(r,n),"utf8"));if(!F(o)||o.profileKey!==e.profileKey||!M(o.pid)||!p(o.tokenPath)||!d(o.tokenPath).isFile())continue;t.push(o)}catch{}return t.sort((n,o)=>b(o)-b(n)||o.instanceId.localeCompare(n.instanceId))}function W(e){const r=_(e);if(r.length===0)throw Object.assign(new Error(`No live Grix Bridge endpoint in DSH profile "${e.profileName}". If Bridge is already installed, restart the profile (stop it, then: dsh --profile ${e.profileName}); otherwise install the Grix Bridge plugin first.`),{code:"bridge_missing"});return r[0]}function b(e){const r=Date.parse(e.startedAt);return Number.isFinite(r)?r:0}function T(e){let r=c(E(e)),t;for(;c(r)!==r;){const o=i(r,"package.json");if(p(o))try{if(JSON.parse(a(o,"utf8")).dsh?.profile)return x(r)}catch{}h(r)==="node_modules"&&(t=c(r)),r=c(r)}if(t)return x(t);const n=u();return w({dshHome:n,profileName:process.env.GRIX_DSH_PROFILE||s})}function x(e){const r=g(e),t=h(r),n=c(r);return{dshHome:h(n)==="profiles"?c(n):u(),profileName:t,profileRoot:r,profileKey:N(r)}}function O(e){if(!e||e==="."||e===".."||e.includes("/")||e.includes("\\")||e.includes("\0"))throw Object.assign(new Error("Invalid DSH profile name"),{code:"profile_invalid"});return e}function F(e){return e.schemaVersion===1&&(e.transport==="unix"||e.transport==="pipe")&&typeof e.address=="string"&&e.address.length>0&&Number.isSafeInteger(e.pid)&&Number(e.pid)>0&&typeof e.startedAt=="string"&&typeof e.profileKey=="string"&&typeof e.profileName=="string"&&typeof e.dshVersion=="string"&&typeof e.bridgeVersion=="string"&&Number.isSafeInteger(e.protocolMin)&&Number.isSafeInteger(e.protocolMax)&&typeof e.instanceId=="string"&&typeof e.tokenPath=="string"}function M(e){try{return process.kill(e,0),!0}catch(r){return r.code==="EPERM"}}export{s as DEFAULT_DSH_PROFILE_NAME,D as DSH_HEADLESS_PROFILE_NAME,A as assertSelectableDshProfileName,I as bridgeDiscoveryDirectory,_ as discoverDshBridgeEndpoints,S as dshProfileDisplayName,T as inferProfileIdentityFromModule,V as listDshProfiles,m as parseDshProfileName,R as profileHasWebApp,N as profileKeyFor,J as resolveDshConnectorProfileDataDir,u as resolveDshHome,w as resolveDshProfileIdentity,C as resolveDshSelectedProfileName,W as selectDshBridgeEndpoint};
@@ -1,2 +1,2 @@
1
- import{createWriteStream as T,existsSync as k,mkdirSync as K,readFileSync as A,renameSync as C,rmSync as F,writeFileSync as H}from"node:fs";import{join as x}from"node:path";import{log as c}from"../../core/log/index.js";import{resolveCliPath as j}from"../../core/util/cli-probe.js";import{killProcessGroup as B,spawnCommand as G}from"../../core/runtime/spawn.js";import{errorForDshBridgeReadiness as R}from"./bridge-installer.js";import{bridgeDiscoveryDirectory as D,discoverDshBridgeEndpoints as y,profileHasWebApp as q}from"./profile-resolver.js";const f="deepseek-harness-profile-supervisor",I=45e3,U=500;function J(e){return{...process.env,DSH_HOME:e}}const m=new Map,u=new Map;function h(e,r,n="coalesce"){const t=m.get(e.profileKey);if(t&&n==="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 de(e){return h(e.installer.identity,()=>O(e))}async function ce(e){return h(e.installer.identity,()=>W(e))}async function W(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?n:O(e)}async function O(e){const r=e.installer,n=e.autoStart!==!1,t=e.readyTimeoutMs??I;let i=await r.status();if(e.reloadManaged&&(i=await Y(r,i,t),i.readiness==="ready")||i.readiness==="ready")return i;if(!n){const a=R(i);if(a)throw a;return i}if(i.readiness==="profile_restart_required"&&i.endpointCount===0)await b(r,i.identity),i=await _(a=>a.readiness==="ready"||a.readiness==="bridge_incompatible",r,t),i.readiness!=="ready"&&i.readiness!=="bridge_incompatible"&&await M(i.identity,"bridge endpoint did not appear");else if(i.readiness==="profile_restart_required"&&i.endpointCount===1&&i.runningBridgeVersion&&i.installedBridgeVersion){const a=y(i.identity)[0],s=g(i.identity);if(a&&s&&s.pid===a.pid&&l(s.pid)){const p=i.runningBridgeVersion!==i.installedBridgeVersion?"bridge upgrade":"bridge content refresh";c.info(f,`restarting connector-managed profile=${i.identity.profileName} pid=${s.pid} for ${p}`),await w(i.identity,s.pid),await b(r,i.identity),i=await _(S=>S.readiness==="ready"||S.readiness==="bridge_incompatible",r,t),i.readiness!=="ready"&&i.readiness!=="bridge_incompatible"&&await M(i.identity,"bridge endpoint did not appear after upgrade restart")}}if(i.readiness==="ready")return z(i),i;const o=R(i);if(o)throw o;return i}async function Y(e,r,n){const t=r.identity,i=g(t);if(!i||!l(i.pid))return r;const o=y(t);if(!o.some(p=>p.pid===i.pid)&&o.length>0)return r;c.info(f,`reloading connector-managed profile=${t.profileName} pid=${i.pid} after settings write`),await w(t,i.pid),await b(e,t);const s=await _(p=>p.readiness==="ready"||p.readiness==="bridge_incompatible",e,n);return s.readiness!=="ready"&&s.readiness!=="bridge_incompatible"&&await M(t,"bridge endpoint did not appear after settings reload"),s}function z(e){c.info(f,`bridge ready profile=${e.identity.profileName} endpoints=${e.endpointCount} bridge=${e.runningBridgeVersion}`)}async function b(e,r){const n=g(r);if(n&&l(n.pid)){if(y(r).some(E=>E.pid===n.pid)){c.info(f,`reusing connector-managed profile=${r.profileName} pid=${n.pid}`);return}c.warn(f,`restarting stuck connector-managed profile=${r.profileName} pid=${n.pid} (alive without endpoint)`),await w(r,n.pid)}else n&&P(r);const t=await j(e.command);if(!t)throw Object.assign(new Error("dsh is not installed or not on PATH"),{code:"dsh_missing"});const i=Q(r),o=D(r);K(o,{recursive:!0,mode:448});const a=x(o,"managed-profile.log"),s=T(a,{flags:"a",mode:384}),p=J(r.dshHome),d=G(t,i,{cwd:r.profileRoot,env:p,stdio:["ignore","pipe","pipe"],detached:!0}).process;if(!d.pid)throw s.end(),Object.assign(new Error(`Failed to start DSH profile "${r.profileName}"`),{code:"profile_start_failed"});d.stdout?.pipe(s,{end:!1}),d.stderr?.pipe(s,{end:!1}),d.once("exit",(N,v)=>{c.warn(f,`managed profile exited profile=${r.profileName} pid=${d.pid} code=${N} signal=${v}`),u.get(r.profileKey)===d&&u.delete(r.profileKey),g(r)?.pid===d.pid&&P(r);try{s.end()}catch{}}),d.unref(),u.set(r.profileKey,d),X(r,{schemaVersion:1,profileKey:r.profileKey,profileName:r.profileName,pid:d.pid,startedAt:new Date().toISOString(),command:t,args:i}),c.info(f,`started connector-managed profile=${r.profileName} pid=${d.pid} args=${i.join(" ")}`)}async function M(e,r){const n=g(e);n&&(c.warn(f,`stopping stuck connector-managed profile=${e.profileName} pid=${n.pid} reason=${r}`),await w(e,n.pid))}async function w(e,r){const n=u.get(e.profileKey);if(n?.pid===r){try{B(n,"SIGTERM")}catch{}u.delete(e.profileKey)}else if(l(r))try{process.kill(r,"SIGTERM")}catch{}const t=Date.now()+5e3;for(;Date.now()<t&&l(r);)await V(100);if(l(r))try{process.kill(r,"SIGKILL")}catch{}P(e)}function Q(e){return q(e.profileRoot,e.profileName)?["--profile",e.profileName,"--port","0"]:["--profile",e.profileName]}async function _(e,r,n){const t=Date.now()+n;let i=await r.status();for(;Date.now()<t;){if(e(i))return i;const o=g(r.identity);if(o&&!l(o.pid))throw P(r.identity),Object.assign(new Error(`Connector-managed DSH profile "${r.identity.profileName}" exited before Bridge became ready`),{code:"profile_start_failed"});await V(U),i=await r.status()}return i}function $(e){return x(D(e),"managed-profile.json")}function g(e){try{const r=JSON.parse(A($(e),"utf8"));return r.schemaVersion!==1||typeof r.pid!="number"||r.profileKey!==e.profileKey?null:r}catch{return null}}function X(e,r){const n=D(e);K(n,{recursive:!0,mode:448});const t=$(e),i=`${t}.${process.pid}.tmp`;H(i,`${JSON.stringify(r,null,2)}
2
- `,{mode:384}),C(i,t)}function P(e){try{F($(e),{force:!0})}catch{}}function l(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 fe(){m.clear();for(const e of u.values())try{e.pid&&B(e,"SIGKILL")}catch{}u.clear()}function pe(e){return k($(e))}async function le(e){const r=m.get(e.profileKey);r&&await r.promise.catch(()=>{})}async function ue(e,r=I){let n="failed";return await h(e.identity,async()=>(n=await Z(e,r),L(e,n==="restarted"?"ready":"profile_restart_required")),"queue"),n}async function Z(e,r){const n=e.identity,t=g(n);if(!t||!l(t.pid))return"not_managed";const i=y(n);if(i.length>0&&!i.some(o=>o.pid===t.pid))return"not_managed";try{return c.info(f,`restarting connector-managed profile=${n.profileName} pid=${t.pid} for plugin toggle`),await w(n,t.pid),await b(e,n),(await _(a=>a.readiness==="ready"||a.readiness==="bridge_incompatible",e,r)).readiness==="ready"?"restarted":"failed"}catch(o){return c.warn(f,`plugin-toggle restart failed profile=${n.profileName}: ${o instanceof Error?o.message:String(o)}`),"failed"}}function ge(e,r){return h(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,compatibleDshVersions:[]}}export{le as awaitDshProfileIdle,Q as buildDshProfileBootArgs,de as ensureDshBridgeReady,ge as holdDshProfileInflightForTests,pe as managedProfileRecordExists,J as managedProfileSpawnEnv,ce as prepareDshProfileBridge,fe as resetDshProfileSupervisorForTests,ue as restartManagedProfileIfOwned};
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 M,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,()=>V(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:V(e)}async function V(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 N(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),b=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 ${b}`),await h(n.identity,a.pid)):d.info(c,`starting connector-managed profile=${n.identity.profileName} for ${b}; external profile processes are left untouched`),await P(r,n.identity),n=await S(g,r,t),g(n)||await N(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 N(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=M(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 N(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 T(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 T(J),n=await r.status()}return n}function _(e){return R(M(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=M(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 T(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"||e.readiness==="bridge_incompatible"}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,compatibleDshVersions:[]}}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,9 +1,9 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "bridgeVersion": "3.29.1",
4
- "tarball": "grix-dsh-bridge-3.29.1.tgz",
3
+ "bridgeVersion": "3.29.3",
4
+ "tarball": "grix-dsh-bridge-3.29.3.tgz",
5
5
  "size": 13786,
6
6
  "unpackedSize": 52666,
7
- "shasum": "7e778926af8452993f1b9f28bcc8e3e3888158e4",
8
- "integrity": "sha512-+FV5HLTtREOg+G7DJq6YhIAhkmujMj8zyei4oKHWgtMfbWbUj5dfVwlEwi6k5b+SjFrwnF61EJxO0SgtHSJ4Fw=="
7
+ "shasum": "7029b8b50ae0b7bf9030177e7f8db880b3e07491",
8
+ "integrity": "sha512-yuTQbvf3JBmmf4N+NNg8MmDlqt7R93q5T1duHXwtI5GyIEtaniGcj29Zvj5RmhoECGwXXvI6CbmN0MUsLrwIGQ=="
9
9
  }
@@ -1,2 +1,2 @@
1
1
  import{EventEmitter as A}from"node:events";import{randomUUID as T}from"node:crypto";import $ from"node:os";import y from"ws";import{log as m}from"../log/index.js";import{getMachineName as S}from"../util/index.js";import{detectTailnetIPv4 as I,ensureServerAndGetPort as P,getFileServerHttpsPort as F}from"../files/file-serve.js";import{TerminalOutbox as M}from"../persistence/terminal-outbox.js";import{TerminalCommitTokenStore as q}from"../persistence/terminal-commit-token-store.js";import{StopResultOutbox as B}from"../persistence/stop-result-outbox.js";import{AUTH_CODE_AGENT_DELETED as w,KICKED_REASON_AGENT_DELETED as R,AgentDeletedError as C,RequestTimeoutError as N}from"./errors.js";function D(E){let e="",t=0,n=!1,s=!1;for(;t<E.length;){const i=E[t];if(n){e+=i,s?s=!1:i==="\\"?s=!0:i==='"'&&(n=!1),t++;continue}if(i==='"'){n=!0,e+=i,t++;continue}if(i==="-"||i>="0"&&i<="9"){const r=t;i==="-"&&t++;const u=t;for(;t<E.length&&E[t]>="0"&&E[t]<="9";)t++;let o=!1;if(E[t]===".")for(o=!0,t++;t<E.length&&E[t]>="0"&&E[t]<="9";)t++;if(E[t]==="e"||E[t]==="E")for(o=!0,t++,(E[t]==="+"||E[t]==="-")&&t++;t<E.length&&E[t]>="0"&&E[t]<="9";)t++;const f=E.slice(r,t),l=t-u;e+=!o&&l>=16?`"${f}"`:f;continue}e+=i,t++}return e}function x(E){const e=[...E??["stream_chunk","local_action_v1","agent_invoke"]];return e.includes("agent_invoke")||e.push("agent_invoke"),e.includes("event_result_ack")||e.push("event_result_ack"),e.includes("terminal_commit_v1")||e.push("terminal_commit_v1"),e.includes("audit_replay_v2")||e.push("audit_replay_v2"),e.includes("session_send_quote_v1")||e.push("session_send_quote_v1"),e}function W(E){const e=[...E??["exec_approve","exec_reject"]];return e.includes("apply_relay_state")||e.push("apply_relay_state"),e}const U="aibot-agent-api-v1",L=1;class p extends A{static DROPPABLE_COMMANDS=new Set(["update_binding_card"]);static BUFFER_OVERFLOW_RETAIN_COMMANDS=new Set(["event_result","codex_event","client_stream_chunk","send_msg","audit_state"]);static MAX_OUTBOUND_BUFFER_SIZE=1e3;static MAX_OUTBOUND_BUFFER_HARD_SIZE=1200;static BACKPRESSURE_THRESHOLD=64*1024;static TERMINAL_RETRY_DELAY_MS=15e3;static MAX_TOKENIZED_TERMINAL_REJECTIONS=5;static EVENT_CORRELATION_TTL_MS=5*6e4;static MAX_EVENT_CORRELATIONS=1024;static MAX_BLOCKED_OUTPUT_EVENTS=4096;static MAX_COMMITTED_TERMINAL_EVENTS=4096;static OUTBOUND_WRITE_CALLBACK_TIMEOUT_MS=1e4;static MIN_REQUIRED_OUTPUT_ACK_TIMEOUT_MS=2e4;static ORDERED_OUTPUT_COMMANDS=new Set(["client_stream_chunk","send_msg","codex_event"]);ws=null;seq=0;heartbeatTimer=null;heartbeatSec=30;heartbeatFailures=0;static HEARTBEAT_MAX_FAILURES=2;connected=!1;reconnecting=!1;reconnectAttempts=0;reconnectRunGeneration=0;everConnected=!1;agentDeleted=!1;config;packetLog;pendingInvokes=new Map;eventCorrelations=new Map;clientMsgEventMap=new Map;eventCorrelationCleanupTimer=null;lastCorrelationPruneAt=0;pendingRequests=new Map;outboundBuffer=[];outboundEntryOrders=new WeakMap;nextOutboundEntryOrder=0;connectionGeneration=0;nextOutboundFlushGeneration=0;outboundFlushInFlight=null;pendingOutputWrites=new Map;pendingOutputSeqsByEvent=new Map;pendingAcceptedOutputs=new Map;pendingAcceptedOutputSeqsByEvent=new Map;pendingAcceptedSeqsByClientMsgId=new Map;nonReplayableOutputEventsBySocket=new Map;provisionalRespondedTerminals=new Map;outputIntegrityFailed=new Map;blockedOutputEvents=new Map;committedTerminalEvents=new Set;ackPolicy=null;negotiatedCapabilities=new Set;terminalOutbox;terminalCommitTokens;stopResultOutbox;terminalInFlight=new Set;terminalRetryTimers=new Map;terminalReplayAfterFlight=new Set;tokenizedTerminalRejections=new Map;stopResultInFlight=new Set;stopResultRetryTimers=new Map;constructor(e,t){super(),this.packetLog=t?.packetLog??null,this.config={url:e.url,agentId:e.agentId,apiKey:e.apiKey,clientType:e.clientType,clientVersion:e.clientVersion??"",adapterHint:e.adapterHint??"",capabilities:x(e.capabilities),localActions:W(e.localActions),skills:e.skills,librarySkills:e.librarySkills,sharedOwnerId:e.sharedOwnerId,concurrency:e.concurrency,terminalOutboxPath:e.terminalOutboxPath,terminalCommitTokenStorePath:e.terminalCommitTokenStorePath,stopResultOutboxPath:e.stopResultOutboxPath},this.terminalOutbox=new M(this.config.terminalOutboxPath),this.terminalCommitTokens=new q(this.config.terminalCommitTokenStorePath??(this.config.terminalOutboxPath?`${this.config.terminalOutboxPath}.tokens`:void 0)),this.stopResultOutbox=new B(this.config.stopResultOutboxPath??(this.config.terminalOutboxPath?`${this.config.terminalOutboxPath}.stops`:void 0));for(const n of this.terminalOutbox.listPending())n.payload.code==="agent_output_integrity_failed"&&this.blockEventOutput(n.payload.event_id)}get isConnected(){return this.connected}async connect(){this.negotiatedCapabilities.clear();const e=this.ws,t=this.connectionGeneration;if(this.pendingRequests.size>0&&this.rejectAllPendingRequests("connection generation replaced"),e){this.connected=!1,this.stopHeartbeat(),this.clearTerminalRetryTimers(),this.clearStopResultRetryTimers();const o=this.outboundFlushInFlight;o&&o.socket===e&&o.connectionGeneration===t&&this.cancelOutboundFlush(o,"connection_lost","connection generation replaced"),this.failNonReplayableOutputsForSocket(e,"connection generation replaced"),this.abortPendingOutputWrites(!0,e,t,"connection generation replaced"),this.abortPendingAcceptedOutputs(!0,e,t),this.clearAllEventCorrelations(),this.connectionGeneration++;try{e.close(1012,"connection generation replaced")}catch{}this.ws===e&&(this.ws=null)}else this.outboundFlushInFlight&&this.cancelOutboundFlush(this.outboundFlushInFlight,"discard","detached connection generation replaced");const n=++this.connectionGeneration;let s,i,r;const u=(async()=>{try{if(s=await I(),s!==void 0)try{i=await P(s);const o=F();o>0&&(r=o)}catch(o){m.warn("aibot",`file server pre-start failed: ${o}`)}}catch(o){m.warn("aibot",`tailnet detect failed: ${o}`)}})();return new Promise((o,f)=>{const l=new y(this.config.url);this.ws=l;const d=setTimeout(()=>{if(!this.isConnectionCurrent(l,n))return;const c=this.pendingRequests.get(_);c&&(this.pendingRequests.delete(_),clearTimeout(c.timer),c.reject(new Error("Auth timeout: no auth_ack received within 15s"))),this.cleanupSocket(l,n)},15e3),_=++this.seq,b=setTimeout(()=>{if(!this.isConnectionCurrent(l,n))return;const c=this.pendingRequests.get(_);c&&(this.pendingRequests.delete(_),c.reject(new Error("Auth request timeout"))),this.cleanupSocket(l,n)},15e3);this.pendingRequests.set(_,{expected:["auth_ack"],resolve:c=>{clearTimeout(d);const a=c.payload;if(a.code===0){this.negotiatedCapabilities=new Set(Array.isArray(a.supported_capabilities)?a.supported_capabilities:[]),this.connected=!0,this.everConnected=!0,this.reconnectAttempts=0,a.heartbeat_sec&&(this.heartbeatSec=a.heartbeat_sec),a.ack_policy&&(this.ackPolicy=a.ack_policy,m.info("aibot",`ack_policy received: push_ack_timeout_ms=${a.ack_policy.push_ack_timeout_ms??"default"} max_retries=${a.ack_policy.max_retries??"default"} timeout_action=${a.ack_policy.timeout_action??"default"}`)),this.startHeartbeat();const h=this.flushOutboundBuffer(l,n);this.emit("auth",a),o(a),h.then(g=>{this.isConnectionCurrent(l,n)&&(g?(this.replayTerminalOutbox(),this.replayStopResultOutbox()):this.reconnectAfterOutboundFlushFailure(l,n))})}else a.code===w?(this.agentDeleted=!0,f(new C(`Agent deleted: code=${a.code} msg=${a.msg}`))):f(new Error(`Auth failed: code=${a.code} msg=${a.msg}`))},reject:c=>{clearTimeout(d),f(c)},timer:b}),l.on("open",async()=>{if(await u,!this.isConnectionCurrent(l,n))return;const c={agent_id:this.config.agentId,api_key:this.config.apiKey,client_type:this.config.clientType,protocol_version:U,contract_version:L,capabilities:this.config.capabilities??[],local_actions:this.config.localActions,skills:this.config.skills,library_skills:this.config.librarySkills};this.config.sharedOwnerId&&(c.shared_owner_id=this.config.sharedOwnerId),this.config.clientVersion&&(c.client="grix-connector",c.client_version=this.config.clientVersion,c.host_type=this.config.clientType,c.host_version=this.config.clientVersion),this.config.adapterHint&&(c.adapter_hint=this.config.adapterHint),c.host_meta={hostname:S(),platform:$.platform(),arch:$.arch(),os_release:$.release(),...s!==void 0&&{tailnet_ip:s},...i!==void 0&&i>0&&{file_server_port:i},...r!==void 0&&r>0&&{file_server_https_port:r}},this.config.concurrency&&(c.concurrency=this.config.concurrency),this.sendPacket("auth",c,_)}),l.on("message",c=>{if(!this.isConnectionCurrent(l,n))return;let a;try{a=JSON.parse(D(c.toString()))}catch{return}try{this.handlePacket(a)}catch(h){this.emitClientError(new Error(`handlePacket error: ${h}`))}}),l.on("close",(c,a)=>{if(!this.isConnectionCurrent(l,n))return;const h=this.everConnected&&!this.agentDeleted;this.connected=!1,this.negotiatedCapabilities.clear(),this.stopHeartbeat(),this.clearTerminalRetryTimers(),this.clearStopResultRetryTimers(),this.rejectAllPendingRequests("websocket closed");const g=`websocket closed code=${c} reason=${a.toString()||"<none>"}`,O=this.outboundFlushInFlight;O&&O.socket===l&&O.connectionGeneration===n&&this.cancelOutboundFlush(O,h?"connection_lost":"discard",g),h?this.failNonReplayableOutputsForSocket(l,g):this.nonReplayableOutputEventsBySocket.delete(l),this.abortPendingOutputWrites(h,l,n,h?g:void 0),this.abortPendingAcceptedOutputs(h,l,n),this.clearAllEventCorrelations(),this.ws===l&&(this.ws=null),this.connectionGeneration++,this.emit("close",c,a.toString());const k=h;m.info("aibot",`ws closed agent=${this.config.clientType}:${this.config.agentId} code=${c} reason=${a.toString()||"<none>"} everConnected=${this.everConnected} reconnecting=${this.reconnecting} agentDeleted=${this.agentDeleted} willReconnect=${k}`),k&&this.attemptReconnect()}),l.on("error",c=>{if(this.isConnectionCurrent(l,n)&&(this.emitClientError(c instanceof Error?c:new Error(String(c))),!this.connected)){const a=this.pendingRequests.get(_);a&&(this.pendingRequests.delete(_),clearTimeout(a.timer),a.reject(c instanceof Error?c:new Error(String(c))))}})})}handlePacket(e){if(this.packetLog?.logInboundPacket(e.cmd,e.seq,e.payload),this.handleCorrelatedSendResponse(e),e.seq>0&&this.pendingRequests.has(e.seq)){const t=this.pendingRequests.get(e.seq);this.pendingRequests.delete(e.seq),clearTimeout(t.timer),t.expected.includes(e.cmd)?t.resolve(e):t.reject(new Error(`unexpected response: got ${e.cmd}, expected ${t.expected.join("/")}`));return}switch(e.cmd){case"auth_ack":break;case"ping":{this.sendPacket("pong",e.payload??{});break}case"event_msg":{const t=e.payload;if(!this.captureInboundTerminalCommitToken(t.event_id,t.terminal_commit_token))break;this.emit("event",t);break}case"local_action":{this.emit("localAction",e.payload);break}case"event_stop":{const t=e.payload;if(!this.captureInboundTerminalCommitToken(t.event_id,t.terminal_commit_token))break;this.emit("stop",t);break}case"event_revoke":{this.emit("revoke",e.payload);break}case"event_edit":{this.emit("edit",e.payload);break}case"event_cancel":{this.emit("eventCancel",e.payload);break}case"queue_clear":{this.emit("queueClear",e.payload);break}case"queue_reorder":{this.emit("queueReorder",e.payload);break}case"queue_snapshot_query":{this.emit("queueSnapshotQuery",e.payload);break}case"event_hold":{this.emit("eventHold",e.payload);break}case"queue_edit":{this.emit("queueEdit",e.payload);break}case"control_share_set":{this.emit("shareSet",e.payload);break}case"agent_profile_push":{this.emit("profilePush",e.payload);break}case"skill_sync":{this.emit("skillSync",e.payload);break}case"kicked":{const t=e.payload;this.emit("kicked",t),this.connected=!1,this.negotiatedCapabilities.clear(),this.stopHeartbeat(),this.clearTerminalRetryTimers(),this.clearStopResultRetryTimers(),this.rejectAllPendingRequests("kicked");const n=this.ws,s=this.connectionGeneration,i=this.outboundFlushInFlight;if(i&&n&&i.socket===n&&i.connectionGeneration===this.connectionGeneration&&this.cancelOutboundFlush(i,t?.reason===R?"discard":"connection_lost",`kicked reason=${t?.reason??"<none>"}`),t?.reason!==R&&n&&this.failNonReplayableOutputsForSocket(n,`kicked reason=${t?.reason??"<none>"}`),this.abortPendingOutputWrites(t?.reason!==R,n??void 0,s,t?.reason!==R?`kicked reason=${t?.reason??"<none>"}`:void 0),this.abortPendingAcceptedOutputs(t?.reason!==R,n??void 0,s),this.clearAllEventCorrelations(),this.connectionGeneration++,t?.reason===R){if(this.agentDeleted=!0,this.reconnecting=!1,this.outboundBuffer.length=0,this.outputIntegrityFailed.clear(),this.nonReplayableOutputEventsBySocket.clear(),this.ws){try{this.ws.close(4001,"kicked")}catch{}this.ws=null}m.error("aibot",`kicked: agent deleted on platform agent=${this.config.clientType}:${this.config.agentId}, reconnect disabled`),this.emit("agentDeleted",{source:"kicked",reason:t.reason});break}if(this.reconnectAttempts=Math.max(this.reconnectAttempts,3),this.ws){try{this.ws.close(4001,"kicked")}catch{}this.ws===n&&(this.ws=null)}this.attemptReconnect();break}case"error":{const t=e.payload,n=[t.ref_cmd?`ref_cmd=${t.ref_cmd}`:"",t.ref_id?`ref_id=${t.ref_id}`:""].filter(Boolean).join(" ");this.emitClientError(new Error(`Server error: code=${t.code} msg=${t.msg}${n?` ${n}`:""}`));break}case"agent_invoke_result":{this.handleInvokeResult(e.payload);break}case"mcp_frame":{const t=e.payload;this.emit("mcpFrame",t.session_id??"",t.frame??null);break}case"send_ack":break;case"send_nack":break;case"local_action_ack":break;default:break}}captureInboundTerminalCommitToken(e,t){const n=t?.trim();if(!n)return!0;if(!e?.trim())return this.rejectInboundTerminalCommitToken("tokenized event is missing event_id"),!1;if(!this.negotiatedCapabilities.has("terminal_commit_v1"))return this.rejectInboundTerminalCommitToken(`tokenized event received without terminal_commit_v1 negotiation event=${e}`),!1;try{return this.terminalCommitTokens.register(e,n),!0}catch(s){return this.rejectInboundTerminalCommitToken(`terminal commit token persist failed event=${e}: ${s instanceof Error?s.message:s}`),!1}}rejectInboundTerminalCommitToken(e){this.emitClientError(new Error(e));const t=this.ws;if(t)try{t.close(1011,"terminal commit token persistence failed")}catch{}}withTerminalCommitToken(e){const t=e.event_id.trim();if(!t)throw new Error("terminal event_result is missing event_id");const n=e.terminal_commit_token?.trim(),s=this.terminalCommitTokens.get(t);if(n&&s&&n!==s)throw new Error(`terminal commit token mismatch for event=${t}`);n&&!s&&this.terminalCommitTokens.register(t,n);const i=s??n;return i?{...e,event_id:t,terminal_commit_token:i}:{...e,event_id:t}}sendEventAck(e){this.sendPacket("event_ack",e)||m.warn("aibot",`event_ack NOT sent (ws not open) event=${e.event_id} ws=${this.ws?`state=${this.ws.readyState}`:"null"}`)}sendStreamChunk(e){!e.delta_content&&!e.is_finish&&(m.warn("aibot",`stream_chunk delta_content empty, patched to newline event=${e.event_id??""} session=${e.session_id} chunk_seq=${e.chunk_seq} is_finish=${e.is_finish}`),e={...e,delta_content:`
2
- `}),this.sendPacket("client_stream_chunk",e)}sendMsg(e){const t={...e,client_msg_id:e.client_msg_id?.trim()||T()};this.sendPacket("send_msg",t)||m.warn("aibot",`send_msg NOT sent (ws not open) event=${t.event_id??""} session=${t.session_id??""} ws=${this.ws?`state=${this.ws.readyState}`:"null"}`)}editMsg(e){this.sendPacket("edit_msg",e)}sendEventResult(e){try{e=this.withTerminalCommitToken(e)}catch(o){this.emitClientError(new Error(`event_result token validation failed: event=${e.event_id}: ${o instanceof Error?o.message:o}`));return}const t=this.terminalOutbox.get(e.event_id);let n,s=this.outputIntegrityFailed.get(e.event_id);const i=t;if(!s&&i?.payload.code==="agent_output_integrity_failed"&&(s={reason:i.payload.msg??"required agent output was discarded before delivery",terminalObserved:!1,terminalSettled:!1},this.outputIntegrityFailed.set(e.event_id,s)),s){if(s.terminalObserved=!0,this.provisionalRespondedTerminals.delete(e.event_id),i&&i.payload.code!=="agent_output_integrity_failed"&&!this.canReplaceUnsentOutputGuard(i)){this.scheduleTerminalDelivery(e.event_id,{ignoreNotBefore:!0});return}if(i?.payload.code==="agent_output_integrity_failed"){this.scheduleTerminalDelivery(e.event_id,{ignoreNotBefore:!0});return}if(s.terminalSettled||this.committedTerminalEvents.has(e.event_id)&&!i){this.outputIntegrityFailed.delete(e.event_id);return}try{n=this.terminalOutbox.enqueue(this.makeOutputIntegrityFailurePayload(e.event_id,s.reason))}catch(o){this.emitClientError(new Error(`output-integrity terminal persist failed: event=${e.event_id}: ${o instanceof Error?o.message:o}`));return}this.scheduleTerminalDelivery(n.payload.event_id,{ignoreNotBefore:!0});return}if(this.committedTerminalEvents.has(e.event_id)&&!t){m.info("aibot",`ignored duplicate terminal after committed ACK event=${e.event_id} status=${e.status}`);return}if(t){if(!(this.canReplaceUnsentOutputGuard(t)&&(e.status==="canceled"||e.status==="failed"))){m.info("aibot",`preserving first durable terminal event=${e.event_id} existing_status=${t.payload.status} ignored_status=${e.status}`),this.scheduleTerminalDelivery(e.event_id,{ignoreNotBefore:!0});return}this.provisionalRespondedTerminals.delete(e.event_id)}if(e.status==="responded"&&this.hasNonReplayableOutput(e.event_id)&&!this.hasPendingOutputAcceptanceFence(e.event_id)){this.markOutputIntegrityFailed(e.event_id,"terminal requested before a complete output acceptance fence");const o=this.outputIntegrityFailed.get(e.event_id);o&&(o.terminalObserved=!0);return}const r=e.status==="responded"&&this.hasUnconfirmedEventOutput(e.event_id),u=r?{...e,status:"failed",code:"agent_output_unconfirmed",msg:"required agent output was not durably confirmed before connector restart",updated_at:Date.now()}:e;r?this.provisionalRespondedTerminals.set(e.event_id,{...e}):this.provisionalRespondedTerminals.delete(e.event_id);try{n=this.terminalOutbox.enqueue(u)}catch(o){this.provisionalRespondedTerminals.delete(e.event_id),this.emitClientError(new Error(`event_result outbox persist failed: event=${e.event_id} status=${e.status}: ${o instanceof Error?o.message:o}`));return}this.scheduleTerminalDelivery(n.payload.event_id,{ignoreNotBefore:!0})}sendLocalActionResult(e){this.sendPacket("local_action_result",e)}sendEventStopAck(e){this.sendPacket("event_stop_ack",e)}sendEventStopResult(e){const t=e.event_id?.trim(),n=e.terminal_commit_token?.trim(),s=t?this.terminalCommitTokens.get(t):void 0;if(n&&s&&n!==s){this.emitClientError(new Error(`event_stop_result token mismatch event=${t??""}`));return}const i=s??n;if(t&&i&&(e.status==="stopped"||e.status==="already_finished")){try{const r=this.stopResultOutbox.enqueue({...e,event_id:t,terminal_commit_token:i});this.scheduleStopResultDelivery(r,{ignoreNotBefore:!0})}catch(r){this.emitClientError(new Error(`event_stop_result outbox persist failed: event=${t} stop=${e.stop_id}: ${r instanceof Error?r.message:r}`))}return}this.sendPacket("event_stop_result",e)}sendSessionActivitySet(e){this.sendPacket("session_activity_set",e)}sendCodexEvent(e){this.sendPacket("codex_event",e)}sendUpdateBindingCard(e){this.sendPacket("update_binding_card",e)}sendAuditState(e){this.sendPacket("audit_state",e)}sendSkillsUpdate(e){this.sendPacket("agent_skills_update",e)}sendPing(){this.sendPacket("ping",{})}sendEventState(e){this.sendPacket("event_state",e)}sendEventCancelResult(e){this.sendPacket("event_cancel_result",e)}sendQueueClearResult(e){this.sendPacket("queue_clear_result",e)}sendQueueReorderResult(e){this.sendPacket("queue_reorder_result",e)}sendEventHoldResult(e){this.sendPacket("event_hold_result",e)}sendQueueEditResult(e){this.sendPacket("queue_edit_result",e)}sendQueueSnapshot(e){this.sendPacket("queue_snapshot",e)}agentInvoke(e,t,n=15e3){return new Promise((s,i)=>{const r=T(),u=Math.max(1e3,Math.min(n,6e4)),o=setTimeout(()=>{this.pendingInvokes.delete(r),i(new Error(`agent_invoke timeout: ${e}`))},u);this.pendingInvokes.set(r,{resolve:s,reject:i,timer:o}),this.sendPacket("agent_invoke",{invoke_id:r,action:e,params:t,timeout_ms:u})})}sendMcpFrame(e,t){this.sendPacket("mcp_frame",{session_id:e,frame:t})}async request(e,t,n){const s=this.outboundFlushInFlight;if(s){if(!await s.promise)throw new Error(`outbound flush failed before request: ${e}`);if(!this.isConnectionCurrent(s.socket,s.connectionGeneration))throw new Error(`connection changed while waiting for outbound flush: ${e}`)}if(!this.connected||!this.ws||this.ws.readyState!==y.OPEN)throw new Error(`send failed: ${e} (websocket not connected)`);return new Promise((i,r)=>{const u=++this.seq,o=setTimeout(()=>{this.pendingRequests.delete(u),r(new N(`request timeout: ${e} (expected ${n.expected.join("/")})`))},n.timeoutMs);this.pendingRequests.set(u,{expected:n.expected,resolve:i,reject:r,timer:o}),this.sendPacket(e,t,u)||(this.pendingRequests.delete(u),clearTimeout(o),r(new Error(`send failed: ${e}`)))})}async sendStreamChunkRequest(e,t=2e4){return this.request("client_stream_chunk",e,{expected:["send_ack","send_nack","error"],timeoutMs:t})}async relayCredentialRequest(e,t=15e3){return this.request("relay_credential_request",e,{expected:["relay_credential_result","error"],timeoutMs:t})}async relayStateSyncRequest(e,t=15e3){return this.request("relay_state_sync_request",e,{expected:["relay_state_sync_result","error"],timeoutMs:t})}sendRelayStateReport(e){this.sendPacket("relay_state_report",e)}async sendText(e,t=2e4){return this.request("send_msg",{msg_type:1,...e,client_msg_id:e.client_msg_id?.trim()||T()},{expected:["send_ack","send_nack","error"],timeoutMs:t})}async sendMedia(e,t=2e4){return this.request("send_msg",{...e,msg_type:2,client_msg_id:e.client_msg_id?.trim()||T()},{expected:["send_ack","send_nack","error"],timeoutMs:t})}async editMessage(e,t=2e4){return this.request("edit_msg",e,{expected:["send_ack","send_nack","error"],timeoutMs:t})}async deleteMessage(e,t,n=2e4){return this.request("delete_msg",{session_id:e,msg_id:t},{expected:["send_ack","send_nack","error"],timeoutMs:n})}async sendEventResultRequest(e,t=5e3){return this.request("event_result",e,{expected:["send_ack","send_nack","error"],timeoutMs:t})}disconnect(){m.info("aibot",`disconnect() agent=${this.config.clientType}:${this.config.agentId} wasConnected=${this.connected} reconnecting=${this.reconnecting} reconnectAttempts=${this.reconnectAttempts}`),this.connected=!1,this.negotiatedCapabilities.clear(),this.everConnected=!1,this.reconnecting=!1,this.reconnectRunGeneration++,this.reconnectAttempts=0,this.stopHeartbeat(),this.clearTerminalRetryTimers(),this.clearStopResultRetryTimers();const e=this.ws,t=this.connectionGeneration,n=this.outboundFlushInFlight;n&&this.cancelOutboundFlush(n,"discard","explicit disconnect"),this.connectionGeneration++,this.rejectAllPendingInvokes("disconnect"),this.rejectAllPendingRequests("disconnect"),this.abortPendingOutputWrites(!1,e??void 0,t),this.abortPendingAcceptedOutputs(!1,e??void 0,t),this.clearAllEventCorrelations(),this.outboundBuffer.length=0,this.provisionalRespondedTerminals.clear(),this.outputIntegrityFailed.clear(),this.nonReplayableOutputEventsBySocket.clear(),this.ws&&(this.ws.close(1e3,"client disconnect"),this.ws=null)}static MAX_CONSECUTIVE_AUTH_FAILURES=5;async attemptReconnect(){if(this.reconnecting||this.agentDeleted)return;this.reconnecting=!0;const e=++this.reconnectRunGeneration;m.info("aibot",`attemptReconnect start agent=${this.config.clientType}:${this.config.agentId} fromAttempts=${this.reconnectAttempts}`),this.emit("disconnected");let t=0;for(;this.reconnecting&&this.reconnectRunGeneration===e;){const n=Math.min(1e3*2**this.reconnectAttempts,3e4),s=Math.floor(n*.2*Math.random());if(this.reconnectAttempts++,await new Promise(u=>setTimeout(u,n+s)),!this.reconnecting||this.reconnectRunGeneration!==e)return;let i=null,r=this.connectionGeneration;try{const u=this.connect();if(i=this.ws,r=this.connectionGeneration,await u,this.reconnectRunGeneration!==e)return;if(!i||!this.isConnectionCurrent(i,r)){if(this.connected&&this.ws){this.reconnecting=!1;return}continue}const o=this.reconnectAttempts;this.reconnectAttempts=0,this.reconnecting=!1,m.info("aibot",`reconnect succeeded agent=${this.config.clientType}:${this.config.agentId} attempt=${o}`);return}catch(u){if(this.reconnectRunGeneration!==e)return;if(i&&!this.isConnectionCurrent(i,r)&&this.connected&&this.ws){this.reconnecting=!1;return}if(i&&this.isConnectionCurrent(i,r)){this.connectionGeneration++;try{i.close()}catch{}this.ws===i&&(this.ws=null)}const o=u instanceof Error?u.message:String(u);if(m.warn("aibot",`reconnect failed agent=${this.config.clientType}:${this.config.agentId} attempt=${this.reconnectAttempts} err=${o}`),u instanceof C){this.agentDeleted=!0,this.reconnecting=!1,m.error("aibot",`reconnect aborted: agent deleted on platform agent=${this.config.clientType}:${this.config.agentId}`),this.emit("agentDeleted",{source:"auth_ack",code:w});return}if(/Auth failed/i.test(o)){if(t++,t>=p.MAX_CONSECUTIVE_AUTH_FAILURES){this.reconnecting=!1,m.error("aibot",`reconnect giving up after ${t} consecutive auth failures agent=${this.config.clientType}:${this.config.agentId}`);return}}else t=0}}}sendPacket(e,t,n){const s=this.outboundEventId(e,t);if(s&&this.blockedOutputEvents.has(s))return this.packetLog?.logOutboundPacket(e,n??0,t,"dropped"),m.warn("aibot",`blocked late output after irreversible event failure event=${s} cmd=${e}`),!1;const i=n===void 0?this.createOutboundEntry(e,t):void 0;if(i&&this.outboundFlushInFlight&&!this.outboundFlushInFlight.finalized&&this.isConnectionCurrent(this.outboundFlushInFlight.socket,this.outboundFlushInFlight.connectionGeneration)&&!p.DROPPABLE_COMMANDS.has(e))return this.bufferOutboundEntry(i),!1;if(this.ws&&this.ws.readyState===y.OPEN&&(e==="auth"||this.connected)){const u=this.ws.bufferedAmount>p.BACKPRESSURE_THRESHOLD;if(!u||!p.DROPPABLE_COMMANDS.has(e)){if(u&&p.DROPPABLE_COMMANDS.has(e))return!1;const o=n??++this.seq,f={cmd:e,seq:o,payload:t};this.packetLog?.logOutboundPacket(e,o,t,"sent");const l=this.ws,d=this.connectionGeneration,_=s;_&&this.trackOutboundEventCorrelation(e,o,t),i&&_&&(this.registerPendingOutputWrite(o,_,i,l,d),this.isAckRequiredOutput(e,t)&&this.registerPendingAcceptedOutput(o,_,i,l,d));let b=!1;try{const c=l.readyState,a=l.bufferedAmount;let h=!1;return l.send(JSON.stringify(f),g=>{if(g&&!h&&(b=!0),e==="event_result"){const v=t;g?m.warn("aibot",`event_result ws send callback failed event=${v.event_id??""} status=${v.status??""} seq=${o} readyState=${c} bufferedAmount=${a} err=${g.message}`):m.info("aibot",`event_result ws send callback ok event=${v.event_id??""} status=${v.status??""} seq=${o} readyState=${c} bufferedAmount=${a}`)}else if(e==="client_stream_chunk"){const v=t;g?m.warn("aibot",`stream_chunk ws send failed event=${v.event_id??""} session=${v.session_id??""} seq=${o} chunk_seq=${v.chunk_seq??""} is_finish=${v.is_finish??""} readyState=${c} bufferedAmount=${a} err=${g.message}`):m.info("aibot",`stream_chunk ws send ok event=${v.event_id??""} session=${v.session_id??""} seq=${o} chunk_seq=${v.chunk_seq??""} is_finish=${v.is_finish??""} client_msg_id=${v.client_msg_id??""} quoted_message_id=${v.quoted_message_id??""} readyState=${c} bufferedAmount=${a}`)}else if(e==="event_ack"){const v=t;g?m.warn("aibot",`event_ack ws send failed event=${v.event_id??""} seq=${o} readyState=${c} bufferedAmount=${a} err=${g.message}`):m.info("aibot",`event_ack ws send ok event=${v.event_id??""} seq=${o} readyState=${c} bufferedAmount=${a}`)}else if(e==="send_msg"){const v=t;g?m.warn("aibot",`send_msg ws send failed event=${v.event_id??""} session=${v.session_id??""} seq=${o} readyState=${c} bufferedAmount=${a} err=${g.message}`):m.info("aibot",`send_msg ws send ok event=${v.event_id??""} session=${v.session_id??""} seq=${o} readyState=${c} bufferedAmount=${a}`)}else if(g){const v=t;m.warn("aibot",`${e} ws send failed seq=${o} session=${v.session_id??""} event=${v.event_id??""} client_msg_id=${v.client_msg_id??""} readyState=${c} bufferedAmount=${a} err=${g.message}`)}const O=this.pendingOutputWrites.get(o),k=!!(O&&O.socket===l&&O.connectionGeneration===d);if(!this.isConnectionCurrent(l,d)){k&&(this.settlePendingOutputWrite(o,!1,!1,l,d),this.settlePendingAcceptedOutput(o,"retry",!1,l,d));return}if(!(i&&_&&!k)){if(g)this.removeSeqFromEventCorrelation(o),_?(this.settlePendingOutputWrite(o,!1,!0,l,d),this.settlePendingAcceptedOutput(o,"retry",!1,l,d)):i&&this.bufferOutboundEntry(i),n!==void 0?this.rejectPendingRequestAfterWriteFailure(o,e,g):i&&this.reconnectAfterOutboundWriteFailure(l,`${e} callback failed`);else if(_){const v=k;this.settlePendingOutputWrite(o,!0,!1,l,d),v&&this.trackNonReplayableOutput(l,e,t,o)}}}),h=!0,!b}catch(c){return this.isConnectionCurrent(l,d)?(this.removeSeqFromEventCorrelation(o),_?(this.settlePendingOutputWrite(o,!1,!0,l,d),this.settlePendingAcceptedOutput(o,"retry",!1,l,d)):i&&this.bufferOutboundEntry(i),this.emitClientError(new Error(`sendPacket failed: ${c}`)),i&&this.reconnectAfterOutboundWriteFailure(l,`${e} send threw`),!1):(this.settlePendingOutputWrite(o,!1,!1,l,d),this.settlePendingAcceptedOutput(o,"retry",!1,l,d),!1)}}}if(p.DROPPABLE_COMMANDS.has(e))return this.packetLog?.logOutboundPacket(e,n??0,t,"dropped"),!1;if(n!==void 0)return this.packetLog?.logOutboundPacket(e,n,t,"dropped"),!1;const r=this.bufferOutboundEntry(i??this.createOutboundEntry(e,t));if(this.packetLog?.logOutboundPacket(e,n??0,t,r?"buffered":"dropped"),r&&e==="client_stream_chunk"){const u=t;m.info("aibot",`stream_chunk buffered (ws not open) event=${u.event_id??""} session=${u.session_id??""} chunk_seq=${u.chunk_seq??""} is_finish=${u.is_finish??""} ws=${this.ws?`state=${this.ws.readyState}`:"null"}`)}return!1}replayTerminalOutbox(){for(const e of this.terminalOutbox.listPending())this.scheduleTerminalDelivery(e.payload.event_id,{ignoreNotBefore:!0})}outboundEventId(e,t){if(!p.ORDERED_OUTPUT_COMMANDS.has(e)||!t||typeof t!="object")return"";const n=t.event_id;return typeof n=="string"?n.trim():""}blockEventOutput(e){const t=e.trim();if(t)for(this.blockedOutputEvents.delete(t),this.blockedOutputEvents.set(t,Date.now()),this.outboundBuffer=this.outboundBuffer.filter(n=>this.outboundEventId(n.cmd,n.payload)!==t);this.blockedOutputEvents.size>p.MAX_BLOCKED_OUTPUT_EVENTS;){const n=this.blockedOutputEvents.keys().next().value;if(!n)break;this.blockedOutputEvents.delete(n)}}isAckRequiredOutput(e,t){return e==="send_msg"?!0:e==="client_stream_chunk"&&!!t&&typeof t=="object"&&t.is_finish===!0}isNonReplayableOutput(e,t){return e==="codex_event"?!0:e==="client_stream_chunk"&&!!t&&typeof t=="object"&&t.is_finish!==!0}trackNonReplayableOutput(e,t,n,s){if(!this.isNonReplayableOutput(t,n))return;const i=this.outboundEventId(t,n);if(!i||this.outputIntegrityFailed.has(i)||this.blockedOutputEvents.has(i))return;let r=this.nonReplayableOutputEventsBySocket.get(e);r||(r=new Map,this.nonReplayableOutputEventsBySocket.set(e,r)),r.set(i,Math.max(r.get(i)??0,s))}clearNonReplayableOutputThrough(e,t,n){if(!e||n<=0)return;const s=this.nonReplayableOutputEventsBySocket.get(e);if(!s)return;const i=s.get(t);i===void 0||i>n||(s.delete(t),s.size===0&&this.nonReplayableOutputEventsBySocket.delete(e))}clearNonReplayableOutputEvent(e){for(const[t,n]of this.nonReplayableOutputEventsBySocket)n.delete(e),n.size===0&&this.nonReplayableOutputEventsBySocket.delete(t)}failNonReplayableOutputsForSocket(e,t){const n=this.nonReplayableOutputEventsBySocket.get(e);if(n){this.nonReplayableOutputEventsBySocket.delete(e);for(const s of n.keys())this.markOutputIntegrityFailed(s,`connection lost before a complete output acceptance fence: ${t}`)}}hasNonReplayableOutput(e){for(const t of this.nonReplayableOutputEventsBySocket.values())if(t.has(e))return!0;return!1}hasPendingOutputAcceptanceFence(e){return!!(this.pendingAcceptedOutputSeqsByEvent.get(e)?.size||this.outboundBuffer.some(t=>this.outboundEventId(t.cmd,t.payload)===e&&this.isAckRequiredOutput(t.cmd,t.payload)))}hasUnconfirmedEventOutput(e){return!!(this.pendingOutputSeqsByEvent.get(e)?.size||this.pendingAcceptedOutputSeqsByEvent.get(e)?.size||this.outboundBuffer.some(t=>this.outboundEventId(t.cmd,t.payload)===e))}trackOutboundEventCorrelation(e,t,n){const s=this.outboundEventId(e,n);if(!s)return;const i=n,r=typeof i.client_msg_id=="string"?i.client_msg_id.trim():"";this.pruneExpiredEventCorrelations();const u=Date.now();let o=this.eventCorrelations.get(s);if(!o){if(this.eventCorrelations.size>=p.MAX_EVENT_CORRELATIONS){let l;for(const d of this.eventCorrelations.values())this.eventHasCriticalDeliveryState(d.eventId)||(!l||d.touchedAt<l.touchedAt)&&(l=d);l&&this.releaseEventCorrelations(l.eventId)}o={eventId:s,clientMsgIds:new Set,seqRanges:[],touchedAt:u,expiresAt:u+p.EVENT_CORRELATION_TTL_MS},this.eventCorrelations.set(s,o)}o.touchedAt=u,o.expiresAt=u+p.EVENT_CORRELATION_TTL_MS;const f=o.seqRanges[o.seqRanges.length-1];if(f&&t===f.end+1?f.end=t:(!f||t<f.start||t>f.end)&&o.seqRanges.push({start:t,end:t}),r){o.clientMsgIds.add(r);let l=this.clientMsgEventMap.get(r);l||(l=new Set,this.clientMsgEventMap.set(r,l)),l.add(s)}this.scheduleEventCorrelationCleanup()}uniqueEventIdForClientMsgId(e){const t=this.clientMsgEventMap.get(e);if(t?.size===1)return t.values().next().value}eventHasCriticalDeliveryState(e){return!!(this.terminalOutbox.get(e)||this.pendingAcceptedOutputSeqsByEvent.get(e)?.size)}eventIdForSeq(e){if(!(e<=0)){for(const t of this.eventCorrelations.values())if(t.seqRanges.some(n=>e>=n.start&&e<=n.end))return t.eventId}}removeSeqFromEventCorrelation(e){if(!(e<=0))for(const t of this.eventCorrelations.values()){const n=t.seqRanges.findIndex(i=>e>=i.start&&e<=i.end);if(n<0)continue;const s=t.seqRanges[n];s.start===s.end?t.seqRanges.splice(n,1):e===s.start?s.start++:e===s.end?s.end--:t.seqRanges.splice(n,1,{start:s.start,end:e-1},{start:e+1,end:s.end});return}}releaseEventCorrelations(e){const t=e.trim();if(!t)return;const n=this.eventCorrelations.get(t);if(n){for(const s of n.clientMsgIds){const i=this.clientMsgEventMap.get(s);i?.delete(t),i?.size===0&&this.clientMsgEventMap.delete(s)}this.eventCorrelations.delete(t)}this.cancelEventCorrelationCleanupIfEmpty()}clearAllEventCorrelations(){this.eventCorrelationCleanupTimer&&(clearTimeout(this.eventCorrelationCleanupTimer),this.eventCorrelationCleanupTimer=null),this.eventCorrelations.clear(),this.clientMsgEventMap.clear(),this.lastCorrelationPruneAt=0}pruneExpiredEventCorrelations(e=Date.now(),t=!1){if(!(!t&&e-this.lastCorrelationPruneAt<1e3)){this.lastCorrelationPruneAt=e;for(const n of[...this.eventCorrelations.values()])n.expiresAt<=e&&!this.eventHasCriticalDeliveryState(n.eventId)&&this.releaseEventCorrelations(n.eventId);this.cancelEventCorrelationCleanupIfEmpty()}}scheduleEventCorrelationCleanup(){if(this.eventCorrelationCleanupTimer||this.eventCorrelations.size===0)return;let e=Number.POSITIVE_INFINITY;for(const t of this.eventCorrelations.values())this.eventHasCriticalDeliveryState(t.eventId)||(e=Math.min(e,t.expiresAt));Number.isFinite(e)&&(this.eventCorrelationCleanupTimer=setTimeout(()=>{this.eventCorrelationCleanupTimer=null,this.pruneExpiredEventCorrelations(Date.now(),!0),this.scheduleEventCorrelationCleanup()},Math.max(1,e-Date.now())),this.eventCorrelationCleanupTimer.unref?.())}cancelEventCorrelationCleanupIfEmpty(){!this.eventCorrelationCleanupTimer||this.eventCorrelations.size>0||(clearTimeout(this.eventCorrelationCleanupTimer),this.eventCorrelationCleanupTimer=null)}handleCorrelatedSendResponse(e){if(e.cmd==="send_ack"){const f=e.payload,l=typeof f.client_msg_id=="string"?f.client_msg_id.trim():"";let d=e.seq>0&&this.pendingAcceptedOutputs.has(e.seq)?e.seq:void 0,_;if(d===void 0&&l){const a=this.pendingAcceptedSeqsByClientMsgId.get(l);if(a?.size===1){const h=a.values().next().value,g=this.pendingAcceptedOutputs.get(h),O=this.uniqueEventIdForClientMsgId(l);g&&O&&g.eventId===O&&(d=h,_=O)}}const b=(d!==void 0?this.pendingAcceptedOutputs.get(d)?.eventId:void 0)??_??this.eventIdForSeq(e.seq),c=d??e.seq;if(d!==void 0){const a=this.pendingOutputWrites.get(d);a&&this.settlePendingOutputWrite(d,!0,!1,a.socket,a.connectionGeneration),this.settlePendingAcceptedOutput(d,"accepted",!1)}else if(e.seq>0){const a=this.pendingOutputWrites.get(e.seq);a&&this.settlePendingOutputWrite(e.seq,!0,!1,a.socket,a.connectionGeneration)}b&&this.clearNonReplayableOutputThrough(this.ws,b,c);return}if(e.cmd!=="send_nack"&&e.cmd!=="error")return;this.pruneExpiredEventCorrelations();const t=e.payload,n=typeof t.client_msg_id=="string"?t.client_msg_id.trim():"",s=e.cmd==="error"&&typeof t.ref_id=="string"?t.ref_id.trim():"",i=e.cmd==="error"&&typeof t.ref_cmd=="string"?t.ref_cmd.trim():"",r=this.eventIdForSeq(e.seq),u=s&&(!i||p.ORDERED_OUTPUT_COMMANDS.has(i))?this.uniqueEventIdForClientMsgId(s)??(this.eventCorrelations.has(s)?s:void 0):void 0,o=r??(n?this.uniqueEventIdForClientMsgId(n):void 0)??u;o&&(this.blockEventOutput(o),this.settlePendingOutputWritesForEvent(o,!0),this.clearNonReplayableOutputEvent(o),e.seq>0&&this.pendingAcceptedOutputs.get(e.seq)?.eventId===o?this.settlePendingAcceptedOutput(e.seq,"rejected",!1):this.settlePendingAcceptedOutputsForEvent(o,"rejected",!1),t.code===4003&&(this.purgeBufferedStreamChunks(o),m.warn("aibot",`event payload rejected (4003), purging buffered chunks for event=${o}`)),this.promotePendingTerminalAfterOutputRejection(o,Number(t.code??0),t.msg),this.emit("streamRejected",o,Number(t.code??0)))}promotePendingTerminalAfterOutputRejection(e,t,n){this.provisionalRespondedTerminals.delete(e);const s=this.terminalOutbox.get(e);if(!(!s||s.payload.status!=="responded"&&s.payload.code!=="agent_output_unconfirmed"||s.deliveryStartedAt))try{const i=this.terminalOutbox.enqueue({...s.payload,status:"failed",code:"agent_output_rejected",msg:n?`required agent output was rejected: ${n}`:`required agent output was rejected by the server (code=${t})`,updated_at:Date.now()});this.scheduleTerminalDelivery(i.payload.event_id,{ignoreNotBefore:!0})}catch(i){this.emitClientError(new Error(`failed to persist output-rejection terminal promotion: event=${e} code=${t}: ${i instanceof Error?i.message:i}`))}}scheduleTerminalDelivery(e,t){if(!this.connected||!this.ws||this.ws.readyState!==y.OPEN)return;if(this.terminalInFlight.has(e)){t?.ignoreNotBefore&&this.terminalReplayAfterFlight.add(e);return}const n=this.terminalOutbox.get(e);if(!n)return;const s=this.terminalRetryTimers.get(e);s&&(clearTimeout(s),this.terminalRetryTimers.delete(e));const i=t?.ignoreNotBefore?0:Math.max(0,n.nextAttemptAt-Date.now()),r=Math.max(i,t?.minimumDelayMs??0);if(r>0){const u=setTimeout(()=>{this.terminalRetryTimers.delete(e),this.scheduleTerminalDelivery(e,{ignoreNotBefore:!0})},r);this.terminalRetryTimers.set(e,u);return}this.deliverTerminalEntry(n)}async deliverTerminalEntry(e){const t=e.payload.event_id;if(this.terminalInFlight.has(t)||!this.terminalOutbox.isCurrent(e))return;this.terminalInFlight.add(t);let n=0;try{n=await this.sendEventResultReliable(e)}finally{this.terminalInFlight.delete(t);const s=this.terminalReplayAfterFlight.delete(t);this.terminalOutbox.get(t)&&this.scheduleTerminalDelivery(t,s?{ignoreNotBefore:!0}:{minimumDelayMs:n})}}clearTerminalRetryTimers(){for(const e of this.terminalRetryTimers.values())clearTimeout(e);this.terminalRetryTimers.clear()}async sendEventResultReliable(e){const t=e.payload.event_id,n=e.payload.terminal_commit_token?.trim();if(n&&!this.negotiatedCapabilities.has("terminal_commit_v1")){const d=this.ws;return this.emitClientError(new Error(`refusing tokenized event_result on an unnegotiated connection: event=${t}`)),d&&this.reconnectAfterOutboundWriteFailure(d,"terminal_commit_v1 not negotiated"),p.TERMINAL_RETRY_DELAY_MS}if(!await this.awaitOutputDeliveryBarrier(t))return p.TERMINAL_RETRY_DELAY_MS;const s=this.provisionalRespondedTerminals.get(t);if(s&&this.terminalOutbox.isCurrent(e))if(!this.canReplaceUnsentOutputGuard(e))this.provisionalRespondedTerminals.delete(t);else try{return this.terminalOutbox.enqueue(s),this.provisionalRespondedTerminals.delete(t),0}catch(d){return this.emitClientError(new Error(`failed to promote confirmed output terminal to responded: event=${t}: ${d instanceof Error?d.message:d}`)),p.TERMINAL_RETRY_DELAY_MS}const i=e.payload;try{if(!this.terminalOutbox.markDeliveryStarted(e))return 0}catch(d){return this.emitClientError(new Error(`event_result delivery-start persist failed: event=${t}: ${d instanceof Error?d.message:d}`)),p.TERMINAL_RETRY_DELAY_MS}const r=Math.max(1,this.ackPolicy?.max_retries??3),u=this.ackPolicy?.push_ack_timeout_ms??5e3,o=750;let f="unknown delivery failure";for(let d=1;d<=r;d++){if(!this.terminalOutbox.isCurrent(e))return 0;const _=this.ws?.readyState??-1,b=this.ws?.bufferedAmount??0;m.info("aibot",`event_result send attempt event=${i.event_id} status=${i.status} attempt=${d}/${r} readyState=${_} bufferedAmount=${b}`);try{const c=await this.sendEventResultRequest(i,u);if(!this.terminalOutbox.isCurrent(e))return 0;if(c.cmd==="send_ack"){const h=c.payload;if(m.info("aibot",`event_result ack event=${i.event_id} status=${i.status} attempt=${d}/${r} ack_event=${h.event_id??""} ack_status=${h.status??""}`),h.event_id!==i.event_id||h.status!==i.status)throw new Error(`event_result ACK mismatch: expected event=${i.event_id} status=${i.status}, got event=${h.event_id??""} status=${h.status??""}`);if(n&&(h.terminal_commit_token?.trim()!==n||h.terminal_committed!==!0))throw new Error(`event_result terminal commit ACK mismatch: event=${i.event_id}`);if(n)try{this.terminalCommitTokens.remove(i.event_id,n)}catch(g){throw new Error(`terminal commit token cleanup failed: event=${i.event_id}: ${g instanceof Error?g.message:g}`)}return this.terminalOutbox.acknowledge(e,h.event_id,h.status,h.terminal_commit_token,h.terminal_committed)&&(this.rememberCommittedTerminalEvent(i.event_id),this.tokenizedTerminalRejections.delete(i.event_id),this.blockEventOutput(i.event_id),this.releaseEventCorrelations(i.event_id),this.clearNonReplayableOutputEvent(i.event_id),this.settleOutputIntegrityTerminal(i.event_id),this.scheduleStopResultsForEvent(i.event_id)),0}const a=c.payload;if(m.warn("aibot",`event_result rejected event=${i.event_id} status=${i.status} attempt=${d}/${r} cmd=${c.cmd} code=${a.code??""} msg=${a.msg??""}${a.ref_cmd?` ref_cmd=${a.ref_cmd}`:""}${a.ref_id?` ref_id=${a.ref_id}`:""}`),n){f=`tokenized terminal rejected: cmd=${c.cmd} code=${a.code??""} msg=${a.msg??""}`;const h=(this.tokenizedTerminalRejections.get(i.event_id)??0)+1;if(this.tokenizedTerminalRejections.set(i.event_id,h),h<p.MAX_TOKENIZED_TERMINAL_REJECTIONS)break;this.tokenizedTerminalRejections.delete(i.event_id);try{this.terminalCommitTokens.remove(i.event_id,n),this.terminalOutbox.moveToDeadLetter(e,{responseCmd:c.cmd,code:a.code,message:a.msg})&&(this.blockEventOutput(i.event_id),this.releaseEventCorrelations(i.event_id),this.clearNonReplayableOutputEvent(i.event_id),this.settleOutputIntegrityTerminal(i.event_id),this.emitClientError(new Error(`tokenized event_result permanently rejected after ${h} rejections, moved to dead-letter: event=${i.event_id} status=${i.status} cmd=${c.cmd} code=${a.code??""} msg=${a.msg??""}`)))}catch(g){f=`dead-letter persist failed: ${g instanceof Error?g.message:g}`,this.emitClientError(new Error(`tokenized event_result dead-letter persist failed: event=${i.event_id} status=${i.status}: ${f}`));break}return 0}try{return this.terminalOutbox.moveToDeadLetter(e,{responseCmd:c.cmd,code:a.code,message:a.msg})&&(this.tokenizedTerminalRejections.delete(i.event_id),this.blockEventOutput(i.event_id),this.releaseEventCorrelations(i.event_id),this.clearNonReplayableOutputEvent(i.event_id),this.settleOutputIntegrityTerminal(i.event_id),this.emitClientError(new Error(`event_result rejected and moved to dead-letter: event=${i.event_id} status=${i.status} cmd=${c.cmd} code=${a.code??""} msg=${a.msg??""}`))),0}catch(h){f=`dead-letter persist failed: ${h instanceof Error?h.message:h}`,this.emitClientError(new Error(`event_result dead-letter persist failed: event=${i.event_id} status=${i.status}: ${f}`));break}}catch(c){const a=c instanceof Error?c.message:String(c);if(f=a,m.warn("aibot",`event_result attempt failed event=${i.event_id} status=${i.status} attempt=${d}/${r} err=${a}`),d===r)break;await new Promise(h=>setTimeout(h,o*d))}}const l=Date.now()+p.TERMINAL_RETRY_DELAY_MS;try{this.terminalOutbox.recordRetry(e,l,f)}catch(d){this.emitClientError(new Error(`event_result retry state persist failed: event=${i.event_id} status=${i.status}: ${d instanceof Error?d.message:d}`))}return this.emitClientError(new Error(`event_result ack failed after ${r} attempts; retained for retry: event=${i.event_id} status=${i.status} err=${f}`)),p.TERMINAL_RETRY_DELAY_MS}purgeBufferedStreamChunks(e){const t=this.outboundBuffer.length;this.outboundBuffer=this.outboundBuffer.filter(n=>n.cmd!=="client_stream_chunk"?!0:n.payload?.event_id!==e),this.outboundBuffer.length<t&&m.info("aibot",`purged ${t-this.outboundBuffer.length} buffered stream chunks for event=${e}`)}emitClientError(e){if(this.listenerCount("error")===0){m.warn("aibot",`Client error (no listeners): ${e.message}`);return}this.emit("error",e)}createOutboundEntry(e,t){const n={cmd:e,payload:t};return this.outboundEntryOrders.set(n,++this.nextOutboundEntryOrder),n}makeOutputIntegrityFailurePayload(e,t){return this.withTerminalCommitToken({event_id:e,status:"failed",code:"agent_output_integrity_failed",msg:`required agent output was discarded before delivery: ${t}`,updated_at:Date.now()})}canReplaceUnsentOutputGuard(e){return e.payload.code==="agent_output_unconfirmed"&&!e.deliveryStartedAt}rememberCommittedTerminalEvent(e){for(this.committedTerminalEvents.delete(e),this.committedTerminalEvents.add(e);this.committedTerminalEvents.size>p.MAX_COMMITTED_TERMINAL_EVENTS;){const t=this.committedTerminalEvents.values().next().value;if(!t)break;this.committedTerminalEvents.delete(t)}}replayStopResultOutbox(){for(const e of this.stopResultOutbox.listPending())this.scheduleStopResultDelivery(e,{ignoreNotBefore:!0})}scheduleStopResultsForEvent(e){for(const t of this.stopResultOutbox.listPending())t.payload.event_id===e&&this.scheduleStopResultDelivery(t,{ignoreNotBefore:!0})}scheduleStopResultDelivery(e,t){if(!this.connected||!this.ws||this.ws.readyState!==y.OPEN||!this.stopResultOutbox.isCurrent(e))return;const n=e.payload.event_id;if(this.terminalOutbox.get(n)||this.terminalCommitTokens.get(n))return;const s=this.stopResultRetryTimers.get(e.key);s&&(clearTimeout(s),this.stopResultRetryTimers.delete(e.key));const i=t?.ignoreNotBefore?0:Math.max(0,e.nextAttemptAt-Date.now());if(i>0){const r=setTimeout(()=>{this.stopResultRetryTimers.delete(e.key),this.scheduleStopResultDelivery(e,{ignoreNotBefore:!0})},i);this.stopResultRetryTimers.set(e.key,r);return}this.deliverStopResultEntry(e)}async deliverStopResultEntry(e){if(this.stopResultInFlight.has(e.key)||!this.stopResultOutbox.isCurrent(e))return;this.stopResultInFlight.add(e.key);let t=p.TERMINAL_RETRY_DELAY_MS;try{t=await this.sendStopResultReliable(e)}finally{if(this.stopResultInFlight.delete(e.key),this.stopResultOutbox.isCurrent(e)){const n=setTimeout(()=>{this.stopResultRetryTimers.delete(e.key),this.scheduleStopResultDelivery(e,{ignoreNotBefore:!0})},t);this.stopResultRetryTimers.set(e.key,n)}}}async sendStopResultReliable(e){const t=this.ackPolicy?.push_ack_timeout_ms??5e3;let n="unknown delivery failure";try{const i=await this.request("event_stop_result",e.payload,{expected:["send_ack","send_nack","error"],timeoutMs:t});if(!this.stopResultOutbox.isCurrent(e))return 0;if(i.cmd==="send_ack"){const r=i.payload;if(this.stopResultOutbox.acknowledge(e,r.event_id,r.terminal_commit_token,r.terminal_committed))return 0;n=`event_stop_result ACK mismatch event=${e.payload.event_id}`}else{const r=i.payload;if(n=`event_stop_result rejected: cmd=${i.cmd} code=${r.code??""} msg=${r.msg??""}`,r.code===4001||r.code===4003){try{this.stopResultOutbox.discard(e)&&this.emitClientError(new Error(`event_stop_result permanently rejected and discarded: event=${e.payload.event_id} stop=${e.payload.stop_id} code=${r.code} msg=${r.msg??""}`))}catch(u){this.emitClientError(new Error(`event_stop_result discard persist failed: event=${e.payload.event_id} stop=${e.payload.stop_id}: ${u instanceof Error?u.message:u}`))}return 0}}}catch(i){n=i instanceof Error?i.message:String(i)}const s=Date.now()+p.TERMINAL_RETRY_DELAY_MS;try{this.stopResultOutbox.recordRetry(e,s,n)}catch(i){this.emitClientError(new Error(`event_stop_result retry state persist failed: event=${e.payload.event_id} stop=${e.payload.stop_id}: ${i instanceof Error?i.message:i}`))}return this.emitClientError(new Error(`event_stop_result retained for retry: event=${e.payload.event_id} stop=${e.payload.stop_id} err=${n}`)),p.TERMINAL_RETRY_DELAY_MS}clearStopResultRetryTimers(){for(const e of this.stopResultRetryTimers.values())clearTimeout(e);this.stopResultRetryTimers.clear()}markOutputIntegrityFailed(e,t){if(this.blockEventOutput(e),this.outputIntegrityFailed.has(e))return;const n={reason:t,terminalObserved:!!(this.provisionalRespondedTerminals.has(e)||this.terminalOutbox.get(e)),terminalSettled:!1};this.outputIntegrityFailed.set(e,n),this.provisionalRespondedTerminals.delete(e),this.clearNonReplayableOutputEvent(e);const s=this.outboundBuffer.length;this.outboundBuffer=this.outboundBuffer.filter(u=>this.outboundEventId(u.cmd,u.payload)!==e);const i=this.terminalOutbox.get(e),r=i?this.canReplaceUnsentOutputGuard(i):!1;if(i&&!r)n.terminalObserved=!0,this.scheduleTerminalDelivery(e,{ignoreNotBefore:!0});else if(!this.committedTerminalEvents.has(e))try{const u=this.terminalOutbox.enqueue(this.makeOutputIntegrityFailurePayload(e,t));this.scheduleTerminalDelivery(u.payload.event_id,{ignoreNotBefore:!0})}catch(u){this.emitClientError(new Error(`output-integrity terminal persist failed: event=${e}: ${u instanceof Error?u.message:u}`))}for(const u of[...this.pendingOutputSeqsByEvent.get(e)??[]])this.settlePendingOutputWrite(u,!1,!1);this.settlePendingAcceptedOutputsForEvent(e,"rejected",!1),this.emit("streamRejected",e,0),this.emitClientError(new Error(`required output integrity failed: event=${e} removed=${s-this.outboundBuffer.length} reason=${t}`))}settleOutputIntegrityTerminal(e){const t=this.outputIntegrityFailed.get(e);t&&(t.terminalSettled=!0,t.terminalObserved&&this.outputIntegrityFailed.delete(e))}bufferOutboundEntry(e){if(this.outboundEntryOrders.has(e)||this.outboundEntryOrders.set(e,++this.nextOutboundEntryOrder),this.outboundBuffer.includes(e))return!0;const t=this.outboundEventId(e.cmd,e.payload);return t&&(this.outputIntegrityFailed.has(t)||this.blockedOutputEvents.has(t))?!1:(this.outboundBuffer.length>=p.MAX_OUTBOUND_BUFFER_SIZE&&(this.outboundBuffer=this.outboundBuffer.filter(n=>p.BUFFER_OVERFLOW_RETAIN_COMMANDS.has(n.cmd)),this.outboundBuffer.length>=p.MAX_OUTBOUND_BUFFER_SIZE&&m.warn("aibot",`outbound buffer soft limit exceeded by ${this.outboundBuffer.length} retained packet(s); preserving required output`)),this.outboundBuffer.length>=p.MAX_OUTBOUND_BUFFER_HARD_SIZE?(t?this.markOutputIntegrityFailed(t,`outbound buffer hard limit ${p.MAX_OUTBOUND_BUFFER_HARD_SIZE} reached`):this.emitClientError(new Error(`outbound buffer hard limit ${p.MAX_OUTBOUND_BUFFER_HARD_SIZE} reached; rejected non-event packet cmd=${e.cmd}`)),!1):(this.outboundBuffer.push(e),this.outboundBuffer.sort((n,s)=>(this.outboundEntryOrders.get(n)??Number.MAX_SAFE_INTEGER)-(this.outboundEntryOrders.get(s)??Number.MAX_SAFE_INTEGER)),!0))}registerPendingOutputWrite(e,t,n,s,i){let r;const u=new Promise(l=>{r=l}),o=setTimeout(()=>{const l=this.pendingOutputWrites.get(e);if(!l||l.socket!==s||l.connectionGeneration!==i)return;if(!this.isConnectionCurrent(s,i)){this.settlePendingOutputWrite(e,!1,!1,s,i);return}this.removeSeqFromEventCorrelation(e);const d=this.isNonReplayableOutput(n.cmd,n.payload);this.settlePendingOutputWrite(e,!1,!d,s,i),d&&this.markOutputIntegrityFailed(t,`websocket write callback timed out for non-replayable ${n.cmd} seq=${e}`),this.emitClientError(new Error(`outbound websocket write callback timeout: cmd=${n.cmd} event=${t} seq=${e} delivery_unknown=${d}`)),this.reconnectAfterOutboundWriteFailure(s,`${n.cmd} callback timeout`)},p.OUTBOUND_WRITE_CALLBACK_TIMEOUT_MS);o.unref?.(),this.pendingOutputWrites.set(e,{eventId:t,entry:n,socket:s,connectionGeneration:i,promise:u,resolve:r,timer:o});let f=this.pendingOutputSeqsByEvent.get(t);f||(f=new Set,this.pendingOutputSeqsByEvent.set(t,f)),f.add(e)}settlePendingOutputWrite(e,t,n,s,i){const r=this.pendingOutputWrites.get(e);if(!r||s&&(r.socket!==s||r.connectionGeneration!==i))return;this.pendingOutputWrites.delete(e),clearTimeout(r.timer);const u=this.pendingOutputSeqsByEvent.get(r.eventId);u?.delete(e),u?.size===0&&this.pendingOutputSeqsByEvent.delete(r.eventId),n&&this.bufferOutboundEntry(r.entry),r.resolve(t)}settlePendingOutputWritesForEvent(e,t){const n=this.pendingOutputSeqsByEvent.get(e);if(n)for(const s of[...n]){const i=this.pendingOutputWrites.get(s);i&&this.settlePendingOutputWrite(s,t,!1,i.socket,i.connectionGeneration)}}abortPendingOutputWrites(e,t,n,s){for(const[i,r]of[...this.pendingOutputWrites.entries()])if(!(t&&(r.socket!==t||r.connectionGeneration!==n))){if(this.removeSeqFromEventCorrelation(i),s&&this.isNonReplayableOutput(r.entry.cmd,r.entry.payload)){this.settlePendingOutputWrite(i,!1,!1,t,n),this.markOutputIntegrityFailed(r.eventId,`connection lost while websocket write completion was unknown: ${s}`);continue}this.settlePendingOutputWrite(i,!1,e,t,n)}}registerPendingAcceptedOutput(e,t,n,s,i){let r;const u=new Promise(h=>{r=h}),o=Math.max(1,this.ackPolicy?.push_ack_timeout_ms??5e3),f=Math.max(1,this.ackPolicy?.max_retries??3),l=Math.max(1e3,Math.ceil(o*.25)),d=Math.max(p.MIN_REQUIRED_OUTPUT_ACK_TIMEOUT_MS,o*f+l),_=setTimeout(()=>{const h=this.pendingAcceptedOutputs.get(e);if(!(!h||h.socket!==s||h.connectionGeneration!==i)){if(!this.isConnectionCurrent(s,i)){this.settlePendingAcceptedOutput(e,"retry",!1,s,i);return}this.settlePendingAcceptedOutput(e,"retry",!0,s,i),this.emitClientError(new Error(`required output ACK timeout; retained for reconnect retry: event=${t} seq=${e}`)),this.reconnectAfterOutboundWriteFailure(s,"required output ACK timeout")}},d);_.unref?.(),this.pendingAcceptedOutputs.set(e,{eventId:t,entry:n,socket:s,connectionGeneration:i,promise:u,resolve:r,timer:_});const b=n.payload,c=typeof b.client_msg_id=="string"?b.client_msg_id.trim():"";if(c){let h=this.pendingAcceptedSeqsByClientMsgId.get(c);h||(h=new Set,this.pendingAcceptedSeqsByClientMsgId.set(c,h)),h.add(e)}let a=this.pendingAcceptedOutputSeqsByEvent.get(t);a||(a=new Set,this.pendingAcceptedOutputSeqsByEvent.set(t,a)),a.add(e)}settlePendingAcceptedOutput(e,t,n,s,i){const r=this.pendingAcceptedOutputs.get(e);if(!r||s&&(r.socket!==s||r.connectionGeneration!==i))return;this.pendingAcceptedOutputs.delete(e),clearTimeout(r.timer);const u=this.pendingAcceptedOutputSeqsByEvent.get(r.eventId);u?.delete(e),u?.size===0&&this.pendingAcceptedOutputSeqsByEvent.delete(r.eventId);const o=r.entry.payload,f=typeof o.client_msg_id=="string"?o.client_msg_id.trim():"";if(f){const l=this.pendingAcceptedSeqsByClientMsgId.get(f);l?.delete(e),l?.size===0&&this.pendingAcceptedSeqsByClientMsgId.delete(f)}n&&this.bufferOutboundEntry(r.entry),r.resolve(t)}settlePendingAcceptedOutputsForEvent(e,t,n){const s=this.pendingAcceptedOutputSeqsByEvent.get(e);if(s)for(const i of[...s])this.settlePendingAcceptedOutput(i,t,n)}abortPendingAcceptedOutputs(e,t,n){for(const[s,i]of[...this.pendingAcceptedOutputs.entries()])t&&(i.socket!==t||i.connectionGeneration!==n)||this.settlePendingAcceptedOutput(s,"retry",e,t,n)}rejectPendingRequestAfterWriteFailure(e,t,n){const s=this.pendingRequests.get(e);s&&(this.pendingRequests.delete(e),clearTimeout(s.timer),s.reject(new Error(`websocket write failed: ${t}: ${n.message}`)))}async awaitOutputDeliveryBarrier(e){const t=this.outboundFlushInFlight;if(t&&!await t.promise)return!1;for(;;){const n=this.pendingOutputSeqsByEvent.get(e);if(!n||n.size===0)break;const s=[...n].map(r=>this.pendingOutputWrites.get(r)?.promise).filter(r=>!!r);if(s.length===0)break;if((await Promise.all(s)).some(r=>!r))return!1}for(;;){const n=this.pendingAcceptedOutputSeqsByEvent.get(e);if(!n||n.size===0)break;const s=[...n].map(r=>this.pendingAcceptedOutputs.get(r)?.promise).filter(r=>!!r);if(s.length===0)break;const i=await Promise.all(s);if(i.includes("retry"))return!1;if(i.includes("rejected")){const r=this.terminalOutbox.get(e);if(!r||r.payload.status==="responded")return!1}}return this.outboundBuffer.some(n=>this.outboundEventId(n.cmd,n.payload)===e)?!1:this.hasNonReplayableOutput(e)?(this.markOutputIntegrityFailed(e,"output flush completed without a complete acceptance fence"),!1):!!(this.connected&&this.ws&&this.ws.readyState===y.OPEN)}isConnectionCurrent(e,t){return this.ws===e&&this.connectionGeneration===t}isOutboundFlushCurrent(e){return!e.finalized&&this.outboundFlushInFlight===e&&this.isConnectionCurrent(e.socket,e.connectionGeneration)}flushOutboundBuffer(e=this.ws,t=this.connectionGeneration){if(!e||!this.isConnectionCurrent(e,t))return Promise.resolve(!1);const n=this.outboundFlushInFlight;if(n){if(!n.finalized&&n.socket===e&&n.connectionGeneration===t)return n.promise;this.cancelOutboundFlush(n,"discard","superseded stale flush")}if(this.outboundBuffer.length===0)return Promise.resolve(!0);const s={connectionGeneration:t,flushGeneration:++this.nextOutboundFlushGeneration,socket:e,promise:Promise.resolve(!1),finalized:!1,activeBatch:null,nextIndex:0,currentWritePending:!1,currentWriteOutcome:null,cancelCurrentWrite:null,remainderHandled:!1};return this.outboundFlushInFlight=s,s.promise=this.performOutboundBufferFlush(s),s.promise.finally(()=>{s.finalized=!0,s.cancelCurrentWrite?.(),s.cancelCurrentWrite=null,this.outboundFlushInFlight===s&&(this.outboundFlushInFlight=null)}),s.promise}async performOutboundBufferFlush(e){for(;this.isOutboundFlushCurrent(e)&&this.outboundBuffer.length>0;){const{socket:t}=e;if(t.readyState!==y.OPEN)return!1;const n=this.outboundBuffer;this.outboundBuffer=[],e.activeBatch=n,e.nextIndex=0,e.remainderHandled=!1;for(let s=0;s<n.length;s++){if(!this.isOutboundFlushCurrent(e))return!1;const i=n[s],{cmd:r,payload:u}=i,o=this.outboundEventId(r,u);if(o&&this.blockedOutputEvents.has(o)){this.packetLog?.logOutboundPacket(r,0,u,"dropped"),e.nextIndex=s+1,e.currentWritePending=!1,e.currentWriteOutcome=null;continue}const f=++this.seq,l={cmd:r,seq:f,payload:u};e.nextIndex=s,e.currentWritePending=!0,e.currentWriteOutcome=null,o&&this.isAckRequiredOutput(r,u)&&this.registerPendingAcceptedOutput(f,o,i,t,e.connectionGeneration);const d=await new Promise(_=>{let b=!1;const c=h=>{b||(b=!0,clearTimeout(a),e.currentWriteOutcome=h,_(h))},a=setTimeout(()=>c("uncertain"),p.OUTBOUND_WRITE_CALLBACK_TIMEOUT_MS);a.unref?.(),e.cancelCurrentWrite=()=>c("canceled");try{this.trackOutboundEventCorrelation(r,f,u),t.send(JSON.stringify(l),h=>{c(h?"retry":"written")})}catch{c("retry")}});if(e.cancelCurrentWrite=null,!this.isOutboundFlushCurrent(e))return!1;if(d!=="written"||t.readyState!==y.OPEN){d==="retry"&&this.removeSeqFromEventCorrelation(f),this.settlePendingAcceptedOutput(f,"retry",!1);const _=this.retainOutboundFlushRemainder(e,d,`auth flush write failed for ${r} seq=${f} outcome=${d}`);return this.emitClientError(new Error(`outbound buffer flush failed at cmd=${r} seq=${f} outcome=${d}; ${_} packet(s) retained`)),!1}this.trackNonReplayableOutput(t,r,u,f),e.currentWritePending=!1,e.currentWriteOutcome="written",e.nextIndex=s+1}e.activeBatch=null,e.currentWritePending=!1,e.currentWriteOutcome=null,e.remainderHandled=!0}return this.isOutboundFlushCurrent(e)}retainOutboundFlushRemainder(e,t,n){if(e.remainderHandled||!e.activeBatch)return 0;e.remainderHandled=!0;const s=e.activeBatch,i=Math.min(e.nextIndex,s.length);let r=i;if(e.currentWritePending&&i<s.length){const o=s[i],f=this.outboundEventId(o.cmd,o.payload);t!=="retry"&&this.isNonReplayableOutput(o.cmd,o.payload)&&f&&(this.markOutputIntegrityFailed(f,n),r=i+1)}let u=0;for(const o of s.slice(r))this.bufferOutboundEntry(o)&&u++;return e.activeBatch=null,e.nextIndex=s.length,e.currentWritePending=!1,u}cancelOutboundFlush(e,t,n){if(e.finalized){this.outboundFlushInFlight===e&&(this.outboundFlushInFlight=null);return}e.finalized=!0,this.outboundFlushInFlight===e&&(this.outboundFlushInFlight=null),t==="connection_lost"?this.retainOutboundFlushRemainder(e,e.currentWriteOutcome,`connection lost during auth flush: ${n}`):(e.remainderHandled=!0,e.activeBatch=null,e.currentWritePending=!1);const s=e.cancelCurrentWrite;e.cancelCurrentWrite=null,s?.()}reconnectAfterOutboundFlushFailure(e,t){this.agentDeleted||!this.isConnectionCurrent(e,t)||this.reconnectAfterOutboundWriteFailure(e,"outbound flush failed")}reconnectAfterOutboundWriteFailure(e,t){if(this.agentDeleted||this.ws!==e)return;const n=this.connectionGeneration;this.connected=!1,this.negotiatedCapabilities.clear(),this.stopHeartbeat(),this.clearTerminalRetryTimers(),this.clearStopResultRetryTimers(),this.rejectAllPendingRequests(t);const s=this.outboundFlushInFlight;s&&s.socket===e&&s.connectionGeneration===n&&this.cancelOutboundFlush(s,"connection_lost",t),this.failNonReplayableOutputsForSocket(e,t),this.abortPendingOutputWrites(!0,e,n,t),this.abortPendingAcceptedOutputs(!0,e,n),this.clearAllEventCorrelations(),this.connectionGeneration++;try{e.close(1011,t)}catch{}this.ws===e&&(this.ws=null),this.attemptReconnect()}handleInvokeResult(e){const t=this.pendingInvokes.get(e.invoke_id);t&&(this.pendingInvokes.delete(e.invoke_id),clearTimeout(t.timer),e.code===0?t.resolve(e.data??null):t.reject(new Error(`agent_invoke error code=${e.code}: ${e.msg??""}`)))}rejectAllPendingInvokes(e){for(const[,t]of this.pendingInvokes)clearTimeout(t.timer),t.reject(new Error(`agent_invoke canceled: ${e}`));this.pendingInvokes.clear()}rejectAllPendingRequests(e){for(const[,t]of this.pendingRequests)clearTimeout(t.timer),t.reject(new Error(`request canceled: ${e}`));this.pendingRequests.clear()}cleanupSocket(e=this.ws,t=this.connectionGeneration){if(!(!e||!this.isConnectionCurrent(e,t)))try{e.close()}catch{}}startHeartbeat(){this.stopHeartbeat(),this.heartbeatFailures=0,this.heartbeatTimer=setInterval(()=>{const e=this.ws,t=this.connectionGeneration;!this.connected||!e||this.request("ping",{ts:Date.now()},{expected:["pong"],timeoutMs:5e3}).then(()=>{this.isConnectionCurrent(e,t)&&(this.heartbeatFailures=0)}).catch(()=>{!this.connected||!this.isConnectionCurrent(e,t)||(this.heartbeatFailures++,!(this.heartbeatFailures<p.HEARTBEAT_MAX_FAILURES)&&(this.cleanupSocket(e,t),this.attemptReconnect()))})},this.heartbeatSec*1e3)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}}export{p as AibotClient,D as preprocessLargeIntegers,x as withRequiredCapabilities};
2
+ `}),this.sendPacket("client_stream_chunk",e)}sendMsg(e){const t={...e,client_msg_id:e.client_msg_id?.trim()||T()};this.sendPacket("send_msg",t)||m.warn("aibot",`send_msg NOT sent (ws not open) event=${t.event_id??""} session=${t.session_id??""} ws=${this.ws?`state=${this.ws.readyState}`:"null"}`)}editMsg(e){this.sendPacket("edit_msg",e)}sendEventResult(e){try{e=this.withTerminalCommitToken(e)}catch(o){this.emitClientError(new Error(`event_result token validation failed: event=${e.event_id}: ${o instanceof Error?o.message:o}`));return}const t=this.terminalOutbox.get(e.event_id);let n,s=this.outputIntegrityFailed.get(e.event_id);const i=t;if(!s&&i?.payload.code==="agent_output_integrity_failed"&&(s={reason:i.payload.msg??"required agent output was discarded before delivery",terminalObserved:!1,terminalSettled:!1},this.outputIntegrityFailed.set(e.event_id,s)),s){if(s.terminalObserved=!0,this.provisionalRespondedTerminals.delete(e.event_id),i&&i.payload.code!=="agent_output_integrity_failed"&&!this.canReplaceUnsentOutputGuard(i)){this.scheduleTerminalDelivery(e.event_id,{ignoreNotBefore:!0});return}if(i?.payload.code==="agent_output_integrity_failed"){this.scheduleTerminalDelivery(e.event_id,{ignoreNotBefore:!0});return}if(s.terminalSettled||this.committedTerminalEvents.has(e.event_id)&&!i){this.outputIntegrityFailed.delete(e.event_id);return}try{n=this.terminalOutbox.enqueue(this.makeOutputIntegrityFailurePayload(e.event_id,s.reason))}catch(o){this.emitClientError(new Error(`output-integrity terminal persist failed: event=${e.event_id}: ${o instanceof Error?o.message:o}`));return}this.scheduleTerminalDelivery(n.payload.event_id,{ignoreNotBefore:!0});return}if(this.committedTerminalEvents.has(e.event_id)&&!t){m.info("aibot",`ignored duplicate terminal after committed ACK event=${e.event_id} status=${e.status}`);return}if(t){if(!(this.canReplaceUnsentOutputGuard(t)&&(e.status==="canceled"||e.status==="failed"))){m.info("aibot",`preserving first durable terminal event=${e.event_id} existing_status=${t.payload.status} ignored_status=${e.status}`),this.scheduleTerminalDelivery(e.event_id,{ignoreNotBefore:!0});return}this.provisionalRespondedTerminals.delete(e.event_id)}if(e.status==="responded"&&this.hasNonReplayableOutput(e.event_id)&&!this.hasPendingOutputAcceptanceFence(e.event_id)){this.markOutputIntegrityFailed(e.event_id,"terminal requested before a complete output acceptance fence");const o=this.outputIntegrityFailed.get(e.event_id);o&&(o.terminalObserved=!0);return}const r=e.status==="responded"&&this.hasUnconfirmedEventOutput(e.event_id),u=r?{...e,status:"failed",code:"agent_output_unconfirmed",msg:"required agent output was not durably confirmed before connector restart",updated_at:Date.now()}:e;r?this.provisionalRespondedTerminals.set(e.event_id,{...e}):this.provisionalRespondedTerminals.delete(e.event_id);try{n=this.terminalOutbox.enqueue(u)}catch(o){this.provisionalRespondedTerminals.delete(e.event_id),this.emitClientError(new Error(`event_result outbox persist failed: event=${e.event_id} status=${e.status}: ${o instanceof Error?o.message:o}`));return}this.scheduleTerminalDelivery(n.payload.event_id,{ignoreNotBefore:!0})}sendLocalActionResult(e){this.sendPacket("local_action_result",e)}sendEventStopAck(e){this.sendPacket("event_stop_ack",e)}sendEventStopResult(e){const t=e.event_id?.trim(),n=e.terminal_commit_token?.trim(),s=t?this.terminalCommitTokens.get(t):void 0;if(n&&s&&n!==s){this.emitClientError(new Error(`event_stop_result token mismatch event=${t??""}`));return}const i=s??n;if(t&&i&&(e.status==="stopped"||e.status==="already_finished")){try{const r=this.stopResultOutbox.enqueue({...e,event_id:t,terminal_commit_token:i});this.scheduleStopResultDelivery(r,{ignoreNotBefore:!0})}catch(r){this.emitClientError(new Error(`event_stop_result outbox persist failed: event=${t} stop=${e.stop_id}: ${r instanceof Error?r.message:r}`))}return}this.sendPacket("event_stop_result",e)}sendSessionActivitySet(e){this.sendPacket("session_activity_set",e)}sendCodexEvent(e){this.sendPacket("codex_event",e)}sendUpdateBindingCard(e){this.sendPacket("update_binding_card",e)}sendAuditState(e){this.sendPacket("audit_state",e)}sendSkillsUpdate(e){this.sendPacket("agent_skills_update",e)}sendPing(){this.sendPacket("ping",{})}sendEventState(e){this.sendPacket("event_state",e)}sendEventCancelResult(e){this.sendPacket("event_cancel_result",e)}sendQueueClearResult(e){this.sendPacket("queue_clear_result",e)}sendQueueReorderResult(e){this.sendPacket("queue_reorder_result",e)}sendEventHoldResult(e){this.sendPacket("event_hold_result",e)}sendQueueEditResult(e){this.sendPacket("queue_edit_result",e)}sendQueueSnapshot(e){this.sendPacket("queue_snapshot",e)}agentInvoke(e,t,n=15e3){return new Promise((s,i)=>{const r=T(),u=Math.max(1e3,Math.min(n,75e3)),o=setTimeout(()=>{this.pendingInvokes.delete(r),i(new Error(`agent_invoke timeout: ${e}`))},u);this.pendingInvokes.set(r,{resolve:s,reject:i,timer:o}),this.sendPacket("agent_invoke",{invoke_id:r,action:e,params:t,timeout_ms:u})})}sendMcpFrame(e,t){this.sendPacket("mcp_frame",{session_id:e,frame:t})}async request(e,t,n){const s=this.outboundFlushInFlight;if(s){if(!await s.promise)throw new Error(`outbound flush failed before request: ${e}`);if(!this.isConnectionCurrent(s.socket,s.connectionGeneration))throw new Error(`connection changed while waiting for outbound flush: ${e}`)}if(!this.connected||!this.ws||this.ws.readyState!==y.OPEN)throw new Error(`send failed: ${e} (websocket not connected)`);return new Promise((i,r)=>{const u=++this.seq,o=setTimeout(()=>{this.pendingRequests.delete(u),r(new N(`request timeout: ${e} (expected ${n.expected.join("/")})`))},n.timeoutMs);this.pendingRequests.set(u,{expected:n.expected,resolve:i,reject:r,timer:o}),this.sendPacket(e,t,u)||(this.pendingRequests.delete(u),clearTimeout(o),r(new Error(`send failed: ${e}`)))})}async sendStreamChunkRequest(e,t=2e4){return this.request("client_stream_chunk",e,{expected:["send_ack","send_nack","error"],timeoutMs:t})}async relayCredentialRequest(e,t=15e3){return this.request("relay_credential_request",e,{expected:["relay_credential_result","error"],timeoutMs:t})}async relayStateSyncRequest(e,t=15e3){return this.request("relay_state_sync_request",e,{expected:["relay_state_sync_result","error"],timeoutMs:t})}sendRelayStateReport(e){this.sendPacket("relay_state_report",e)}async sendText(e,t=2e4){return this.request("send_msg",{msg_type:1,...e,client_msg_id:e.client_msg_id?.trim()||T()},{expected:["send_ack","send_nack","error"],timeoutMs:t})}async sendMedia(e,t=2e4){return this.request("send_msg",{...e,msg_type:2,client_msg_id:e.client_msg_id?.trim()||T()},{expected:["send_ack","send_nack","error"],timeoutMs:t})}async editMessage(e,t=2e4){return this.request("edit_msg",e,{expected:["send_ack","send_nack","error"],timeoutMs:t})}async deleteMessage(e,t,n=2e4){return this.request("delete_msg",{session_id:e,msg_id:t},{expected:["send_ack","send_nack","error"],timeoutMs:n})}async sendEventResultRequest(e,t=5e3){return this.request("event_result",e,{expected:["send_ack","send_nack","error"],timeoutMs:t})}disconnect(){m.info("aibot",`disconnect() agent=${this.config.clientType}:${this.config.agentId} wasConnected=${this.connected} reconnecting=${this.reconnecting} reconnectAttempts=${this.reconnectAttempts}`),this.connected=!1,this.negotiatedCapabilities.clear(),this.everConnected=!1,this.reconnecting=!1,this.reconnectRunGeneration++,this.reconnectAttempts=0,this.stopHeartbeat(),this.clearTerminalRetryTimers(),this.clearStopResultRetryTimers();const e=this.ws,t=this.connectionGeneration,n=this.outboundFlushInFlight;n&&this.cancelOutboundFlush(n,"discard","explicit disconnect"),this.connectionGeneration++,this.rejectAllPendingInvokes("disconnect"),this.rejectAllPendingRequests("disconnect"),this.abortPendingOutputWrites(!1,e??void 0,t),this.abortPendingAcceptedOutputs(!1,e??void 0,t),this.clearAllEventCorrelations(),this.outboundBuffer.length=0,this.provisionalRespondedTerminals.clear(),this.outputIntegrityFailed.clear(),this.nonReplayableOutputEventsBySocket.clear(),this.ws&&(this.ws.close(1e3,"client disconnect"),this.ws=null)}static MAX_CONSECUTIVE_AUTH_FAILURES=5;async attemptReconnect(){if(this.reconnecting||this.agentDeleted)return;this.reconnecting=!0;const e=++this.reconnectRunGeneration;m.info("aibot",`attemptReconnect start agent=${this.config.clientType}:${this.config.agentId} fromAttempts=${this.reconnectAttempts}`),this.emit("disconnected");let t=0;for(;this.reconnecting&&this.reconnectRunGeneration===e;){const n=Math.min(1e3*2**this.reconnectAttempts,3e4),s=Math.floor(n*.2*Math.random());if(this.reconnectAttempts++,await new Promise(u=>setTimeout(u,n+s)),!this.reconnecting||this.reconnectRunGeneration!==e)return;let i=null,r=this.connectionGeneration;try{const u=this.connect();if(i=this.ws,r=this.connectionGeneration,await u,this.reconnectRunGeneration!==e)return;if(!i||!this.isConnectionCurrent(i,r)){if(this.connected&&this.ws){this.reconnecting=!1;return}continue}const o=this.reconnectAttempts;this.reconnectAttempts=0,this.reconnecting=!1,m.info("aibot",`reconnect succeeded agent=${this.config.clientType}:${this.config.agentId} attempt=${o}`);return}catch(u){if(this.reconnectRunGeneration!==e)return;if(i&&!this.isConnectionCurrent(i,r)&&this.connected&&this.ws){this.reconnecting=!1;return}if(i&&this.isConnectionCurrent(i,r)){this.connectionGeneration++;try{i.close()}catch{}this.ws===i&&(this.ws=null)}const o=u instanceof Error?u.message:String(u);if(m.warn("aibot",`reconnect failed agent=${this.config.clientType}:${this.config.agentId} attempt=${this.reconnectAttempts} err=${o}`),u instanceof C){this.agentDeleted=!0,this.reconnecting=!1,m.error("aibot",`reconnect aborted: agent deleted on platform agent=${this.config.clientType}:${this.config.agentId}`),this.emit("agentDeleted",{source:"auth_ack",code:w});return}if(/Auth failed/i.test(o)){if(t++,t>=p.MAX_CONSECUTIVE_AUTH_FAILURES){this.reconnecting=!1,m.error("aibot",`reconnect giving up after ${t} consecutive auth failures agent=${this.config.clientType}:${this.config.agentId}`);return}}else t=0}}}sendPacket(e,t,n){const s=this.outboundEventId(e,t);if(s&&this.blockedOutputEvents.has(s))return this.packetLog?.logOutboundPacket(e,n??0,t,"dropped"),m.warn("aibot",`blocked late output after irreversible event failure event=${s} cmd=${e}`),!1;const i=n===void 0?this.createOutboundEntry(e,t):void 0;if(i&&this.outboundFlushInFlight&&!this.outboundFlushInFlight.finalized&&this.isConnectionCurrent(this.outboundFlushInFlight.socket,this.outboundFlushInFlight.connectionGeneration)&&!p.DROPPABLE_COMMANDS.has(e))return this.bufferOutboundEntry(i),!1;if(this.ws&&this.ws.readyState===y.OPEN&&(e==="auth"||this.connected)){const u=this.ws.bufferedAmount>p.BACKPRESSURE_THRESHOLD;if(!u||!p.DROPPABLE_COMMANDS.has(e)){if(u&&p.DROPPABLE_COMMANDS.has(e))return!1;const o=n??++this.seq,f={cmd:e,seq:o,payload:t};this.packetLog?.logOutboundPacket(e,o,t,"sent");const l=this.ws,d=this.connectionGeneration,_=s;_&&this.trackOutboundEventCorrelation(e,o,t),i&&_&&(this.registerPendingOutputWrite(o,_,i,l,d),this.isAckRequiredOutput(e,t)&&this.registerPendingAcceptedOutput(o,_,i,l,d));let b=!1;try{const c=l.readyState,a=l.bufferedAmount;let h=!1;return l.send(JSON.stringify(f),g=>{if(g&&!h&&(b=!0),e==="event_result"){const v=t;g?m.warn("aibot",`event_result ws send callback failed event=${v.event_id??""} status=${v.status??""} seq=${o} readyState=${c} bufferedAmount=${a} err=${g.message}`):m.info("aibot",`event_result ws send callback ok event=${v.event_id??""} status=${v.status??""} seq=${o} readyState=${c} bufferedAmount=${a}`)}else if(e==="client_stream_chunk"){const v=t;g?m.warn("aibot",`stream_chunk ws send failed event=${v.event_id??""} session=${v.session_id??""} seq=${o} chunk_seq=${v.chunk_seq??""} is_finish=${v.is_finish??""} readyState=${c} bufferedAmount=${a} err=${g.message}`):m.info("aibot",`stream_chunk ws send ok event=${v.event_id??""} session=${v.session_id??""} seq=${o} chunk_seq=${v.chunk_seq??""} is_finish=${v.is_finish??""} client_msg_id=${v.client_msg_id??""} quoted_message_id=${v.quoted_message_id??""} readyState=${c} bufferedAmount=${a}`)}else if(e==="event_ack"){const v=t;g?m.warn("aibot",`event_ack ws send failed event=${v.event_id??""} seq=${o} readyState=${c} bufferedAmount=${a} err=${g.message}`):m.info("aibot",`event_ack ws send ok event=${v.event_id??""} seq=${o} readyState=${c} bufferedAmount=${a}`)}else if(e==="send_msg"){const v=t;g?m.warn("aibot",`send_msg ws send failed event=${v.event_id??""} session=${v.session_id??""} seq=${o} readyState=${c} bufferedAmount=${a} err=${g.message}`):m.info("aibot",`send_msg ws send ok event=${v.event_id??""} session=${v.session_id??""} seq=${o} readyState=${c} bufferedAmount=${a}`)}else if(g){const v=t;m.warn("aibot",`${e} ws send failed seq=${o} session=${v.session_id??""} event=${v.event_id??""} client_msg_id=${v.client_msg_id??""} readyState=${c} bufferedAmount=${a} err=${g.message}`)}const O=this.pendingOutputWrites.get(o),k=!!(O&&O.socket===l&&O.connectionGeneration===d);if(!this.isConnectionCurrent(l,d)){k&&(this.settlePendingOutputWrite(o,!1,!1,l,d),this.settlePendingAcceptedOutput(o,"retry",!1,l,d));return}if(!(i&&_&&!k)){if(g)this.removeSeqFromEventCorrelation(o),_?(this.settlePendingOutputWrite(o,!1,!0,l,d),this.settlePendingAcceptedOutput(o,"retry",!1,l,d)):i&&this.bufferOutboundEntry(i),n!==void 0?this.rejectPendingRequestAfterWriteFailure(o,e,g):i&&this.reconnectAfterOutboundWriteFailure(l,`${e} callback failed`);else if(_){const v=k;this.settlePendingOutputWrite(o,!0,!1,l,d),v&&this.trackNonReplayableOutput(l,e,t,o)}}}),h=!0,!b}catch(c){return this.isConnectionCurrent(l,d)?(this.removeSeqFromEventCorrelation(o),_?(this.settlePendingOutputWrite(o,!1,!0,l,d),this.settlePendingAcceptedOutput(o,"retry",!1,l,d)):i&&this.bufferOutboundEntry(i),this.emitClientError(new Error(`sendPacket failed: ${c}`)),i&&this.reconnectAfterOutboundWriteFailure(l,`${e} send threw`),!1):(this.settlePendingOutputWrite(o,!1,!1,l,d),this.settlePendingAcceptedOutput(o,"retry",!1,l,d),!1)}}}if(p.DROPPABLE_COMMANDS.has(e))return this.packetLog?.logOutboundPacket(e,n??0,t,"dropped"),!1;if(n!==void 0)return this.packetLog?.logOutboundPacket(e,n,t,"dropped"),!1;const r=this.bufferOutboundEntry(i??this.createOutboundEntry(e,t));if(this.packetLog?.logOutboundPacket(e,n??0,t,r?"buffered":"dropped"),r&&e==="client_stream_chunk"){const u=t;m.info("aibot",`stream_chunk buffered (ws not open) event=${u.event_id??""} session=${u.session_id??""} chunk_seq=${u.chunk_seq??""} is_finish=${u.is_finish??""} ws=${this.ws?`state=${this.ws.readyState}`:"null"}`)}return!1}replayTerminalOutbox(){for(const e of this.terminalOutbox.listPending())this.scheduleTerminalDelivery(e.payload.event_id,{ignoreNotBefore:!0})}outboundEventId(e,t){if(!p.ORDERED_OUTPUT_COMMANDS.has(e)||!t||typeof t!="object")return"";const n=t.event_id;return typeof n=="string"?n.trim():""}blockEventOutput(e){const t=e.trim();if(t)for(this.blockedOutputEvents.delete(t),this.blockedOutputEvents.set(t,Date.now()),this.outboundBuffer=this.outboundBuffer.filter(n=>this.outboundEventId(n.cmd,n.payload)!==t);this.blockedOutputEvents.size>p.MAX_BLOCKED_OUTPUT_EVENTS;){const n=this.blockedOutputEvents.keys().next().value;if(!n)break;this.blockedOutputEvents.delete(n)}}isAckRequiredOutput(e,t){return e==="send_msg"?!0:e==="client_stream_chunk"&&!!t&&typeof t=="object"&&t.is_finish===!0}isNonReplayableOutput(e,t){return e==="codex_event"?!0:e==="client_stream_chunk"&&!!t&&typeof t=="object"&&t.is_finish!==!0}trackNonReplayableOutput(e,t,n,s){if(!this.isNonReplayableOutput(t,n))return;const i=this.outboundEventId(t,n);if(!i||this.outputIntegrityFailed.has(i)||this.blockedOutputEvents.has(i))return;let r=this.nonReplayableOutputEventsBySocket.get(e);r||(r=new Map,this.nonReplayableOutputEventsBySocket.set(e,r)),r.set(i,Math.max(r.get(i)??0,s))}clearNonReplayableOutputThrough(e,t,n){if(!e||n<=0)return;const s=this.nonReplayableOutputEventsBySocket.get(e);if(!s)return;const i=s.get(t);i===void 0||i>n||(s.delete(t),s.size===0&&this.nonReplayableOutputEventsBySocket.delete(e))}clearNonReplayableOutputEvent(e){for(const[t,n]of this.nonReplayableOutputEventsBySocket)n.delete(e),n.size===0&&this.nonReplayableOutputEventsBySocket.delete(t)}failNonReplayableOutputsForSocket(e,t){const n=this.nonReplayableOutputEventsBySocket.get(e);if(n){this.nonReplayableOutputEventsBySocket.delete(e);for(const s of n.keys())this.markOutputIntegrityFailed(s,`connection lost before a complete output acceptance fence: ${t}`)}}hasNonReplayableOutput(e){for(const t of this.nonReplayableOutputEventsBySocket.values())if(t.has(e))return!0;return!1}hasPendingOutputAcceptanceFence(e){return!!(this.pendingAcceptedOutputSeqsByEvent.get(e)?.size||this.outboundBuffer.some(t=>this.outboundEventId(t.cmd,t.payload)===e&&this.isAckRequiredOutput(t.cmd,t.payload)))}hasUnconfirmedEventOutput(e){return!!(this.pendingOutputSeqsByEvent.get(e)?.size||this.pendingAcceptedOutputSeqsByEvent.get(e)?.size||this.outboundBuffer.some(t=>this.outboundEventId(t.cmd,t.payload)===e))}trackOutboundEventCorrelation(e,t,n){const s=this.outboundEventId(e,n);if(!s)return;const i=n,r=typeof i.client_msg_id=="string"?i.client_msg_id.trim():"";this.pruneExpiredEventCorrelations();const u=Date.now();let o=this.eventCorrelations.get(s);if(!o){if(this.eventCorrelations.size>=p.MAX_EVENT_CORRELATIONS){let l;for(const d of this.eventCorrelations.values())this.eventHasCriticalDeliveryState(d.eventId)||(!l||d.touchedAt<l.touchedAt)&&(l=d);l&&this.releaseEventCorrelations(l.eventId)}o={eventId:s,clientMsgIds:new Set,seqRanges:[],touchedAt:u,expiresAt:u+p.EVENT_CORRELATION_TTL_MS},this.eventCorrelations.set(s,o)}o.touchedAt=u,o.expiresAt=u+p.EVENT_CORRELATION_TTL_MS;const f=o.seqRanges[o.seqRanges.length-1];if(f&&t===f.end+1?f.end=t:(!f||t<f.start||t>f.end)&&o.seqRanges.push({start:t,end:t}),r){o.clientMsgIds.add(r);let l=this.clientMsgEventMap.get(r);l||(l=new Set,this.clientMsgEventMap.set(r,l)),l.add(s)}this.scheduleEventCorrelationCleanup()}uniqueEventIdForClientMsgId(e){const t=this.clientMsgEventMap.get(e);if(t?.size===1)return t.values().next().value}eventHasCriticalDeliveryState(e){return!!(this.terminalOutbox.get(e)||this.pendingAcceptedOutputSeqsByEvent.get(e)?.size)}eventIdForSeq(e){if(!(e<=0)){for(const t of this.eventCorrelations.values())if(t.seqRanges.some(n=>e>=n.start&&e<=n.end))return t.eventId}}removeSeqFromEventCorrelation(e){if(!(e<=0))for(const t of this.eventCorrelations.values()){const n=t.seqRanges.findIndex(i=>e>=i.start&&e<=i.end);if(n<0)continue;const s=t.seqRanges[n];s.start===s.end?t.seqRanges.splice(n,1):e===s.start?s.start++:e===s.end?s.end--:t.seqRanges.splice(n,1,{start:s.start,end:e-1},{start:e+1,end:s.end});return}}releaseEventCorrelations(e){const t=e.trim();if(!t)return;const n=this.eventCorrelations.get(t);if(n){for(const s of n.clientMsgIds){const i=this.clientMsgEventMap.get(s);i?.delete(t),i?.size===0&&this.clientMsgEventMap.delete(s)}this.eventCorrelations.delete(t)}this.cancelEventCorrelationCleanupIfEmpty()}clearAllEventCorrelations(){this.eventCorrelationCleanupTimer&&(clearTimeout(this.eventCorrelationCleanupTimer),this.eventCorrelationCleanupTimer=null),this.eventCorrelations.clear(),this.clientMsgEventMap.clear(),this.lastCorrelationPruneAt=0}pruneExpiredEventCorrelations(e=Date.now(),t=!1){if(!(!t&&e-this.lastCorrelationPruneAt<1e3)){this.lastCorrelationPruneAt=e;for(const n of[...this.eventCorrelations.values()])n.expiresAt<=e&&!this.eventHasCriticalDeliveryState(n.eventId)&&this.releaseEventCorrelations(n.eventId);this.cancelEventCorrelationCleanupIfEmpty()}}scheduleEventCorrelationCleanup(){if(this.eventCorrelationCleanupTimer||this.eventCorrelations.size===0)return;let e=Number.POSITIVE_INFINITY;for(const t of this.eventCorrelations.values())this.eventHasCriticalDeliveryState(t.eventId)||(e=Math.min(e,t.expiresAt));Number.isFinite(e)&&(this.eventCorrelationCleanupTimer=setTimeout(()=>{this.eventCorrelationCleanupTimer=null,this.pruneExpiredEventCorrelations(Date.now(),!0),this.scheduleEventCorrelationCleanup()},Math.max(1,e-Date.now())),this.eventCorrelationCleanupTimer.unref?.())}cancelEventCorrelationCleanupIfEmpty(){!this.eventCorrelationCleanupTimer||this.eventCorrelations.size>0||(clearTimeout(this.eventCorrelationCleanupTimer),this.eventCorrelationCleanupTimer=null)}handleCorrelatedSendResponse(e){if(e.cmd==="send_ack"){const f=e.payload,l=typeof f.client_msg_id=="string"?f.client_msg_id.trim():"";let d=e.seq>0&&this.pendingAcceptedOutputs.has(e.seq)?e.seq:void 0,_;if(d===void 0&&l){const a=this.pendingAcceptedSeqsByClientMsgId.get(l);if(a?.size===1){const h=a.values().next().value,g=this.pendingAcceptedOutputs.get(h),O=this.uniqueEventIdForClientMsgId(l);g&&O&&g.eventId===O&&(d=h,_=O)}}const b=(d!==void 0?this.pendingAcceptedOutputs.get(d)?.eventId:void 0)??_??this.eventIdForSeq(e.seq),c=d??e.seq;if(d!==void 0){const a=this.pendingOutputWrites.get(d);a&&this.settlePendingOutputWrite(d,!0,!1,a.socket,a.connectionGeneration),this.settlePendingAcceptedOutput(d,"accepted",!1)}else if(e.seq>0){const a=this.pendingOutputWrites.get(e.seq);a&&this.settlePendingOutputWrite(e.seq,!0,!1,a.socket,a.connectionGeneration)}b&&this.clearNonReplayableOutputThrough(this.ws,b,c);return}if(e.cmd!=="send_nack"&&e.cmd!=="error")return;this.pruneExpiredEventCorrelations();const t=e.payload,n=typeof t.client_msg_id=="string"?t.client_msg_id.trim():"",s=e.cmd==="error"&&typeof t.ref_id=="string"?t.ref_id.trim():"",i=e.cmd==="error"&&typeof t.ref_cmd=="string"?t.ref_cmd.trim():"",r=this.eventIdForSeq(e.seq),u=s&&(!i||p.ORDERED_OUTPUT_COMMANDS.has(i))?this.uniqueEventIdForClientMsgId(s)??(this.eventCorrelations.has(s)?s:void 0):void 0,o=r??(n?this.uniqueEventIdForClientMsgId(n):void 0)??u;o&&(this.blockEventOutput(o),this.settlePendingOutputWritesForEvent(o,!0),this.clearNonReplayableOutputEvent(o),e.seq>0&&this.pendingAcceptedOutputs.get(e.seq)?.eventId===o?this.settlePendingAcceptedOutput(e.seq,"rejected",!1):this.settlePendingAcceptedOutputsForEvent(o,"rejected",!1),t.code===4003&&(this.purgeBufferedStreamChunks(o),m.warn("aibot",`event payload rejected (4003), purging buffered chunks for event=${o}`)),this.promotePendingTerminalAfterOutputRejection(o,Number(t.code??0),t.msg),this.emit("streamRejected",o,Number(t.code??0)))}promotePendingTerminalAfterOutputRejection(e,t,n){this.provisionalRespondedTerminals.delete(e);const s=this.terminalOutbox.get(e);if(!(!s||s.payload.status!=="responded"&&s.payload.code!=="agent_output_unconfirmed"||s.deliveryStartedAt))try{const i=this.terminalOutbox.enqueue({...s.payload,status:"failed",code:"agent_output_rejected",msg:n?`required agent output was rejected: ${n}`:`required agent output was rejected by the server (code=${t})`,updated_at:Date.now()});this.scheduleTerminalDelivery(i.payload.event_id,{ignoreNotBefore:!0})}catch(i){this.emitClientError(new Error(`failed to persist output-rejection terminal promotion: event=${e} code=${t}: ${i instanceof Error?i.message:i}`))}}scheduleTerminalDelivery(e,t){if(!this.connected||!this.ws||this.ws.readyState!==y.OPEN)return;if(this.terminalInFlight.has(e)){t?.ignoreNotBefore&&this.terminalReplayAfterFlight.add(e);return}const n=this.terminalOutbox.get(e);if(!n)return;const s=this.terminalRetryTimers.get(e);s&&(clearTimeout(s),this.terminalRetryTimers.delete(e));const i=t?.ignoreNotBefore?0:Math.max(0,n.nextAttemptAt-Date.now()),r=Math.max(i,t?.minimumDelayMs??0);if(r>0){const u=setTimeout(()=>{this.terminalRetryTimers.delete(e),this.scheduleTerminalDelivery(e,{ignoreNotBefore:!0})},r);this.terminalRetryTimers.set(e,u);return}this.deliverTerminalEntry(n)}async deliverTerminalEntry(e){const t=e.payload.event_id;if(this.terminalInFlight.has(t)||!this.terminalOutbox.isCurrent(e))return;this.terminalInFlight.add(t);let n=0;try{n=await this.sendEventResultReliable(e)}finally{this.terminalInFlight.delete(t);const s=this.terminalReplayAfterFlight.delete(t);this.terminalOutbox.get(t)&&this.scheduleTerminalDelivery(t,s?{ignoreNotBefore:!0}:{minimumDelayMs:n})}}clearTerminalRetryTimers(){for(const e of this.terminalRetryTimers.values())clearTimeout(e);this.terminalRetryTimers.clear()}async sendEventResultReliable(e){const t=e.payload.event_id,n=e.payload.terminal_commit_token?.trim();if(n&&!this.negotiatedCapabilities.has("terminal_commit_v1")){const d=this.ws;return this.emitClientError(new Error(`refusing tokenized event_result on an unnegotiated connection: event=${t}`)),d&&this.reconnectAfterOutboundWriteFailure(d,"terminal_commit_v1 not negotiated"),p.TERMINAL_RETRY_DELAY_MS}if(!await this.awaitOutputDeliveryBarrier(t))return p.TERMINAL_RETRY_DELAY_MS;const s=this.provisionalRespondedTerminals.get(t);if(s&&this.terminalOutbox.isCurrent(e))if(!this.canReplaceUnsentOutputGuard(e))this.provisionalRespondedTerminals.delete(t);else try{return this.terminalOutbox.enqueue(s),this.provisionalRespondedTerminals.delete(t),0}catch(d){return this.emitClientError(new Error(`failed to promote confirmed output terminal to responded: event=${t}: ${d instanceof Error?d.message:d}`)),p.TERMINAL_RETRY_DELAY_MS}const i=e.payload;try{if(!this.terminalOutbox.markDeliveryStarted(e))return 0}catch(d){return this.emitClientError(new Error(`event_result delivery-start persist failed: event=${t}: ${d instanceof Error?d.message:d}`)),p.TERMINAL_RETRY_DELAY_MS}const r=Math.max(1,this.ackPolicy?.max_retries??3),u=this.ackPolicy?.push_ack_timeout_ms??5e3,o=750;let f="unknown delivery failure";for(let d=1;d<=r;d++){if(!this.terminalOutbox.isCurrent(e))return 0;const _=this.ws?.readyState??-1,b=this.ws?.bufferedAmount??0;m.info("aibot",`event_result send attempt event=${i.event_id} status=${i.status} attempt=${d}/${r} readyState=${_} bufferedAmount=${b}`);try{const c=await this.sendEventResultRequest(i,u);if(!this.terminalOutbox.isCurrent(e))return 0;if(c.cmd==="send_ack"){const h=c.payload;if(m.info("aibot",`event_result ack event=${i.event_id} status=${i.status} attempt=${d}/${r} ack_event=${h.event_id??""} ack_status=${h.status??""}`),h.event_id!==i.event_id||h.status!==i.status)throw new Error(`event_result ACK mismatch: expected event=${i.event_id} status=${i.status}, got event=${h.event_id??""} status=${h.status??""}`);if(n&&(h.terminal_commit_token?.trim()!==n||h.terminal_committed!==!0))throw new Error(`event_result terminal commit ACK mismatch: event=${i.event_id}`);if(n)try{this.terminalCommitTokens.remove(i.event_id,n)}catch(g){throw new Error(`terminal commit token cleanup failed: event=${i.event_id}: ${g instanceof Error?g.message:g}`)}return this.terminalOutbox.acknowledge(e,h.event_id,h.status,h.terminal_commit_token,h.terminal_committed)&&(this.rememberCommittedTerminalEvent(i.event_id),this.tokenizedTerminalRejections.delete(i.event_id),this.blockEventOutput(i.event_id),this.releaseEventCorrelations(i.event_id),this.clearNonReplayableOutputEvent(i.event_id),this.settleOutputIntegrityTerminal(i.event_id),this.scheduleStopResultsForEvent(i.event_id)),0}const a=c.payload;if(m.warn("aibot",`event_result rejected event=${i.event_id} status=${i.status} attempt=${d}/${r} cmd=${c.cmd} code=${a.code??""} msg=${a.msg??""}${a.ref_cmd?` ref_cmd=${a.ref_cmd}`:""}${a.ref_id?` ref_id=${a.ref_id}`:""}`),n){f=`tokenized terminal rejected: cmd=${c.cmd} code=${a.code??""} msg=${a.msg??""}`;const h=(this.tokenizedTerminalRejections.get(i.event_id)??0)+1;if(this.tokenizedTerminalRejections.set(i.event_id,h),h<p.MAX_TOKENIZED_TERMINAL_REJECTIONS)break;this.tokenizedTerminalRejections.delete(i.event_id);try{this.terminalCommitTokens.remove(i.event_id,n),this.terminalOutbox.moveToDeadLetter(e,{responseCmd:c.cmd,code:a.code,message:a.msg})&&(this.blockEventOutput(i.event_id),this.releaseEventCorrelations(i.event_id),this.clearNonReplayableOutputEvent(i.event_id),this.settleOutputIntegrityTerminal(i.event_id),this.emitClientError(new Error(`tokenized event_result permanently rejected after ${h} rejections, moved to dead-letter: event=${i.event_id} status=${i.status} cmd=${c.cmd} code=${a.code??""} msg=${a.msg??""}`)))}catch(g){f=`dead-letter persist failed: ${g instanceof Error?g.message:g}`,this.emitClientError(new Error(`tokenized event_result dead-letter persist failed: event=${i.event_id} status=${i.status}: ${f}`));break}return 0}try{return this.terminalOutbox.moveToDeadLetter(e,{responseCmd:c.cmd,code:a.code,message:a.msg})&&(this.tokenizedTerminalRejections.delete(i.event_id),this.blockEventOutput(i.event_id),this.releaseEventCorrelations(i.event_id),this.clearNonReplayableOutputEvent(i.event_id),this.settleOutputIntegrityTerminal(i.event_id),this.emitClientError(new Error(`event_result rejected and moved to dead-letter: event=${i.event_id} status=${i.status} cmd=${c.cmd} code=${a.code??""} msg=${a.msg??""}`))),0}catch(h){f=`dead-letter persist failed: ${h instanceof Error?h.message:h}`,this.emitClientError(new Error(`event_result dead-letter persist failed: event=${i.event_id} status=${i.status}: ${f}`));break}}catch(c){const a=c instanceof Error?c.message:String(c);if(f=a,m.warn("aibot",`event_result attempt failed event=${i.event_id} status=${i.status} attempt=${d}/${r} err=${a}`),d===r)break;await new Promise(h=>setTimeout(h,o*d))}}const l=Date.now()+p.TERMINAL_RETRY_DELAY_MS;try{this.terminalOutbox.recordRetry(e,l,f)}catch(d){this.emitClientError(new Error(`event_result retry state persist failed: event=${i.event_id} status=${i.status}: ${d instanceof Error?d.message:d}`))}return this.emitClientError(new Error(`event_result ack failed after ${r} attempts; retained for retry: event=${i.event_id} status=${i.status} err=${f}`)),p.TERMINAL_RETRY_DELAY_MS}purgeBufferedStreamChunks(e){const t=this.outboundBuffer.length;this.outboundBuffer=this.outboundBuffer.filter(n=>n.cmd!=="client_stream_chunk"?!0:n.payload?.event_id!==e),this.outboundBuffer.length<t&&m.info("aibot",`purged ${t-this.outboundBuffer.length} buffered stream chunks for event=${e}`)}emitClientError(e){if(this.listenerCount("error")===0){m.warn("aibot",`Client error (no listeners): ${e.message}`);return}this.emit("error",e)}createOutboundEntry(e,t){const n={cmd:e,payload:t};return this.outboundEntryOrders.set(n,++this.nextOutboundEntryOrder),n}makeOutputIntegrityFailurePayload(e,t){return this.withTerminalCommitToken({event_id:e,status:"failed",code:"agent_output_integrity_failed",msg:`required agent output was discarded before delivery: ${t}`,updated_at:Date.now()})}canReplaceUnsentOutputGuard(e){return e.payload.code==="agent_output_unconfirmed"&&!e.deliveryStartedAt}rememberCommittedTerminalEvent(e){for(this.committedTerminalEvents.delete(e),this.committedTerminalEvents.add(e);this.committedTerminalEvents.size>p.MAX_COMMITTED_TERMINAL_EVENTS;){const t=this.committedTerminalEvents.values().next().value;if(!t)break;this.committedTerminalEvents.delete(t)}}replayStopResultOutbox(){for(const e of this.stopResultOutbox.listPending())this.scheduleStopResultDelivery(e,{ignoreNotBefore:!0})}scheduleStopResultsForEvent(e){for(const t of this.stopResultOutbox.listPending())t.payload.event_id===e&&this.scheduleStopResultDelivery(t,{ignoreNotBefore:!0})}scheduleStopResultDelivery(e,t){if(!this.connected||!this.ws||this.ws.readyState!==y.OPEN||!this.stopResultOutbox.isCurrent(e))return;const n=e.payload.event_id;if(this.terminalOutbox.get(n)||this.terminalCommitTokens.get(n))return;const s=this.stopResultRetryTimers.get(e.key);s&&(clearTimeout(s),this.stopResultRetryTimers.delete(e.key));const i=t?.ignoreNotBefore?0:Math.max(0,e.nextAttemptAt-Date.now());if(i>0){const r=setTimeout(()=>{this.stopResultRetryTimers.delete(e.key),this.scheduleStopResultDelivery(e,{ignoreNotBefore:!0})},i);this.stopResultRetryTimers.set(e.key,r);return}this.deliverStopResultEntry(e)}async deliverStopResultEntry(e){if(this.stopResultInFlight.has(e.key)||!this.stopResultOutbox.isCurrent(e))return;this.stopResultInFlight.add(e.key);let t=p.TERMINAL_RETRY_DELAY_MS;try{t=await this.sendStopResultReliable(e)}finally{if(this.stopResultInFlight.delete(e.key),this.stopResultOutbox.isCurrent(e)){const n=setTimeout(()=>{this.stopResultRetryTimers.delete(e.key),this.scheduleStopResultDelivery(e,{ignoreNotBefore:!0})},t);this.stopResultRetryTimers.set(e.key,n)}}}async sendStopResultReliable(e){const t=this.ackPolicy?.push_ack_timeout_ms??5e3;let n="unknown delivery failure";try{const i=await this.request("event_stop_result",e.payload,{expected:["send_ack","send_nack","error"],timeoutMs:t});if(!this.stopResultOutbox.isCurrent(e))return 0;if(i.cmd==="send_ack"){const r=i.payload;if(this.stopResultOutbox.acknowledge(e,r.event_id,r.terminal_commit_token,r.terminal_committed))return 0;n=`event_stop_result ACK mismatch event=${e.payload.event_id}`}else{const r=i.payload;if(n=`event_stop_result rejected: cmd=${i.cmd} code=${r.code??""} msg=${r.msg??""}`,r.code===4001||r.code===4003){try{this.stopResultOutbox.discard(e)&&this.emitClientError(new Error(`event_stop_result permanently rejected and discarded: event=${e.payload.event_id} stop=${e.payload.stop_id} code=${r.code} msg=${r.msg??""}`))}catch(u){this.emitClientError(new Error(`event_stop_result discard persist failed: event=${e.payload.event_id} stop=${e.payload.stop_id}: ${u instanceof Error?u.message:u}`))}return 0}}}catch(i){n=i instanceof Error?i.message:String(i)}const s=Date.now()+p.TERMINAL_RETRY_DELAY_MS;try{this.stopResultOutbox.recordRetry(e,s,n)}catch(i){this.emitClientError(new Error(`event_stop_result retry state persist failed: event=${e.payload.event_id} stop=${e.payload.stop_id}: ${i instanceof Error?i.message:i}`))}return this.emitClientError(new Error(`event_stop_result retained for retry: event=${e.payload.event_id} stop=${e.payload.stop_id} err=${n}`)),p.TERMINAL_RETRY_DELAY_MS}clearStopResultRetryTimers(){for(const e of this.stopResultRetryTimers.values())clearTimeout(e);this.stopResultRetryTimers.clear()}markOutputIntegrityFailed(e,t){if(this.blockEventOutput(e),this.outputIntegrityFailed.has(e))return;const n={reason:t,terminalObserved:!!(this.provisionalRespondedTerminals.has(e)||this.terminalOutbox.get(e)),terminalSettled:!1};this.outputIntegrityFailed.set(e,n),this.provisionalRespondedTerminals.delete(e),this.clearNonReplayableOutputEvent(e);const s=this.outboundBuffer.length;this.outboundBuffer=this.outboundBuffer.filter(u=>this.outboundEventId(u.cmd,u.payload)!==e);const i=this.terminalOutbox.get(e),r=i?this.canReplaceUnsentOutputGuard(i):!1;if(i&&!r)n.terminalObserved=!0,this.scheduleTerminalDelivery(e,{ignoreNotBefore:!0});else if(!this.committedTerminalEvents.has(e))try{const u=this.terminalOutbox.enqueue(this.makeOutputIntegrityFailurePayload(e,t));this.scheduleTerminalDelivery(u.payload.event_id,{ignoreNotBefore:!0})}catch(u){this.emitClientError(new Error(`output-integrity terminal persist failed: event=${e}: ${u instanceof Error?u.message:u}`))}for(const u of[...this.pendingOutputSeqsByEvent.get(e)??[]])this.settlePendingOutputWrite(u,!1,!1);this.settlePendingAcceptedOutputsForEvent(e,"rejected",!1),this.emit("streamRejected",e,0),this.emitClientError(new Error(`required output integrity failed: event=${e} removed=${s-this.outboundBuffer.length} reason=${t}`))}settleOutputIntegrityTerminal(e){const t=this.outputIntegrityFailed.get(e);t&&(t.terminalSettled=!0,t.terminalObserved&&this.outputIntegrityFailed.delete(e))}bufferOutboundEntry(e){if(this.outboundEntryOrders.has(e)||this.outboundEntryOrders.set(e,++this.nextOutboundEntryOrder),this.outboundBuffer.includes(e))return!0;const t=this.outboundEventId(e.cmd,e.payload);return t&&(this.outputIntegrityFailed.has(t)||this.blockedOutputEvents.has(t))?!1:(this.outboundBuffer.length>=p.MAX_OUTBOUND_BUFFER_SIZE&&(this.outboundBuffer=this.outboundBuffer.filter(n=>p.BUFFER_OVERFLOW_RETAIN_COMMANDS.has(n.cmd)),this.outboundBuffer.length>=p.MAX_OUTBOUND_BUFFER_SIZE&&m.warn("aibot",`outbound buffer soft limit exceeded by ${this.outboundBuffer.length} retained packet(s); preserving required output`)),this.outboundBuffer.length>=p.MAX_OUTBOUND_BUFFER_HARD_SIZE?(t?this.markOutputIntegrityFailed(t,`outbound buffer hard limit ${p.MAX_OUTBOUND_BUFFER_HARD_SIZE} reached`):this.emitClientError(new Error(`outbound buffer hard limit ${p.MAX_OUTBOUND_BUFFER_HARD_SIZE} reached; rejected non-event packet cmd=${e.cmd}`)),!1):(this.outboundBuffer.push(e),this.outboundBuffer.sort((n,s)=>(this.outboundEntryOrders.get(n)??Number.MAX_SAFE_INTEGER)-(this.outboundEntryOrders.get(s)??Number.MAX_SAFE_INTEGER)),!0))}registerPendingOutputWrite(e,t,n,s,i){let r;const u=new Promise(l=>{r=l}),o=setTimeout(()=>{const l=this.pendingOutputWrites.get(e);if(!l||l.socket!==s||l.connectionGeneration!==i)return;if(!this.isConnectionCurrent(s,i)){this.settlePendingOutputWrite(e,!1,!1,s,i);return}this.removeSeqFromEventCorrelation(e);const d=this.isNonReplayableOutput(n.cmd,n.payload);this.settlePendingOutputWrite(e,!1,!d,s,i),d&&this.markOutputIntegrityFailed(t,`websocket write callback timed out for non-replayable ${n.cmd} seq=${e}`),this.emitClientError(new Error(`outbound websocket write callback timeout: cmd=${n.cmd} event=${t} seq=${e} delivery_unknown=${d}`)),this.reconnectAfterOutboundWriteFailure(s,`${n.cmd} callback timeout`)},p.OUTBOUND_WRITE_CALLBACK_TIMEOUT_MS);o.unref?.(),this.pendingOutputWrites.set(e,{eventId:t,entry:n,socket:s,connectionGeneration:i,promise:u,resolve:r,timer:o});let f=this.pendingOutputSeqsByEvent.get(t);f||(f=new Set,this.pendingOutputSeqsByEvent.set(t,f)),f.add(e)}settlePendingOutputWrite(e,t,n,s,i){const r=this.pendingOutputWrites.get(e);if(!r||s&&(r.socket!==s||r.connectionGeneration!==i))return;this.pendingOutputWrites.delete(e),clearTimeout(r.timer);const u=this.pendingOutputSeqsByEvent.get(r.eventId);u?.delete(e),u?.size===0&&this.pendingOutputSeqsByEvent.delete(r.eventId),n&&this.bufferOutboundEntry(r.entry),r.resolve(t)}settlePendingOutputWritesForEvent(e,t){const n=this.pendingOutputSeqsByEvent.get(e);if(n)for(const s of[...n]){const i=this.pendingOutputWrites.get(s);i&&this.settlePendingOutputWrite(s,t,!1,i.socket,i.connectionGeneration)}}abortPendingOutputWrites(e,t,n,s){for(const[i,r]of[...this.pendingOutputWrites.entries()])if(!(t&&(r.socket!==t||r.connectionGeneration!==n))){if(this.removeSeqFromEventCorrelation(i),s&&this.isNonReplayableOutput(r.entry.cmd,r.entry.payload)){this.settlePendingOutputWrite(i,!1,!1,t,n),this.markOutputIntegrityFailed(r.eventId,`connection lost while websocket write completion was unknown: ${s}`);continue}this.settlePendingOutputWrite(i,!1,e,t,n)}}registerPendingAcceptedOutput(e,t,n,s,i){let r;const u=new Promise(h=>{r=h}),o=Math.max(1,this.ackPolicy?.push_ack_timeout_ms??5e3),f=Math.max(1,this.ackPolicy?.max_retries??3),l=Math.max(1e3,Math.ceil(o*.25)),d=Math.max(p.MIN_REQUIRED_OUTPUT_ACK_TIMEOUT_MS,o*f+l),_=setTimeout(()=>{const h=this.pendingAcceptedOutputs.get(e);if(!(!h||h.socket!==s||h.connectionGeneration!==i)){if(!this.isConnectionCurrent(s,i)){this.settlePendingAcceptedOutput(e,"retry",!1,s,i);return}this.settlePendingAcceptedOutput(e,"retry",!0,s,i),this.emitClientError(new Error(`required output ACK timeout; retained for reconnect retry: event=${t} seq=${e}`)),this.reconnectAfterOutboundWriteFailure(s,"required output ACK timeout")}},d);_.unref?.(),this.pendingAcceptedOutputs.set(e,{eventId:t,entry:n,socket:s,connectionGeneration:i,promise:u,resolve:r,timer:_});const b=n.payload,c=typeof b.client_msg_id=="string"?b.client_msg_id.trim():"";if(c){let h=this.pendingAcceptedSeqsByClientMsgId.get(c);h||(h=new Set,this.pendingAcceptedSeqsByClientMsgId.set(c,h)),h.add(e)}let a=this.pendingAcceptedOutputSeqsByEvent.get(t);a||(a=new Set,this.pendingAcceptedOutputSeqsByEvent.set(t,a)),a.add(e)}settlePendingAcceptedOutput(e,t,n,s,i){const r=this.pendingAcceptedOutputs.get(e);if(!r||s&&(r.socket!==s||r.connectionGeneration!==i))return;this.pendingAcceptedOutputs.delete(e),clearTimeout(r.timer);const u=this.pendingAcceptedOutputSeqsByEvent.get(r.eventId);u?.delete(e),u?.size===0&&this.pendingAcceptedOutputSeqsByEvent.delete(r.eventId);const o=r.entry.payload,f=typeof o.client_msg_id=="string"?o.client_msg_id.trim():"";if(f){const l=this.pendingAcceptedSeqsByClientMsgId.get(f);l?.delete(e),l?.size===0&&this.pendingAcceptedSeqsByClientMsgId.delete(f)}n&&this.bufferOutboundEntry(r.entry),r.resolve(t)}settlePendingAcceptedOutputsForEvent(e,t,n){const s=this.pendingAcceptedOutputSeqsByEvent.get(e);if(s)for(const i of[...s])this.settlePendingAcceptedOutput(i,t,n)}abortPendingAcceptedOutputs(e,t,n){for(const[s,i]of[...this.pendingAcceptedOutputs.entries()])t&&(i.socket!==t||i.connectionGeneration!==n)||this.settlePendingAcceptedOutput(s,"retry",e,t,n)}rejectPendingRequestAfterWriteFailure(e,t,n){const s=this.pendingRequests.get(e);s&&(this.pendingRequests.delete(e),clearTimeout(s.timer),s.reject(new Error(`websocket write failed: ${t}: ${n.message}`)))}async awaitOutputDeliveryBarrier(e){const t=this.outboundFlushInFlight;if(t&&!await t.promise)return!1;for(;;){const n=this.pendingOutputSeqsByEvent.get(e);if(!n||n.size===0)break;const s=[...n].map(r=>this.pendingOutputWrites.get(r)?.promise).filter(r=>!!r);if(s.length===0)break;if((await Promise.all(s)).some(r=>!r))return!1}for(;;){const n=this.pendingAcceptedOutputSeqsByEvent.get(e);if(!n||n.size===0)break;const s=[...n].map(r=>this.pendingAcceptedOutputs.get(r)?.promise).filter(r=>!!r);if(s.length===0)break;const i=await Promise.all(s);if(i.includes("retry"))return!1;if(i.includes("rejected")){const r=this.terminalOutbox.get(e);if(!r||r.payload.status==="responded")return!1}}return this.outboundBuffer.some(n=>this.outboundEventId(n.cmd,n.payload)===e)?!1:this.hasNonReplayableOutput(e)?(this.markOutputIntegrityFailed(e,"output flush completed without a complete acceptance fence"),!1):!!(this.connected&&this.ws&&this.ws.readyState===y.OPEN)}isConnectionCurrent(e,t){return this.ws===e&&this.connectionGeneration===t}isOutboundFlushCurrent(e){return!e.finalized&&this.outboundFlushInFlight===e&&this.isConnectionCurrent(e.socket,e.connectionGeneration)}flushOutboundBuffer(e=this.ws,t=this.connectionGeneration){if(!e||!this.isConnectionCurrent(e,t))return Promise.resolve(!1);const n=this.outboundFlushInFlight;if(n){if(!n.finalized&&n.socket===e&&n.connectionGeneration===t)return n.promise;this.cancelOutboundFlush(n,"discard","superseded stale flush")}if(this.outboundBuffer.length===0)return Promise.resolve(!0);const s={connectionGeneration:t,flushGeneration:++this.nextOutboundFlushGeneration,socket:e,promise:Promise.resolve(!1),finalized:!1,activeBatch:null,nextIndex:0,currentWritePending:!1,currentWriteOutcome:null,cancelCurrentWrite:null,remainderHandled:!1};return this.outboundFlushInFlight=s,s.promise=this.performOutboundBufferFlush(s),s.promise.finally(()=>{s.finalized=!0,s.cancelCurrentWrite?.(),s.cancelCurrentWrite=null,this.outboundFlushInFlight===s&&(this.outboundFlushInFlight=null)}),s.promise}async performOutboundBufferFlush(e){for(;this.isOutboundFlushCurrent(e)&&this.outboundBuffer.length>0;){const{socket:t}=e;if(t.readyState!==y.OPEN)return!1;const n=this.outboundBuffer;this.outboundBuffer=[],e.activeBatch=n,e.nextIndex=0,e.remainderHandled=!1;for(let s=0;s<n.length;s++){if(!this.isOutboundFlushCurrent(e))return!1;const i=n[s],{cmd:r,payload:u}=i,o=this.outboundEventId(r,u);if(o&&this.blockedOutputEvents.has(o)){this.packetLog?.logOutboundPacket(r,0,u,"dropped"),e.nextIndex=s+1,e.currentWritePending=!1,e.currentWriteOutcome=null;continue}const f=++this.seq,l={cmd:r,seq:f,payload:u};e.nextIndex=s,e.currentWritePending=!0,e.currentWriteOutcome=null,o&&this.isAckRequiredOutput(r,u)&&this.registerPendingAcceptedOutput(f,o,i,t,e.connectionGeneration);const d=await new Promise(_=>{let b=!1;const c=h=>{b||(b=!0,clearTimeout(a),e.currentWriteOutcome=h,_(h))},a=setTimeout(()=>c("uncertain"),p.OUTBOUND_WRITE_CALLBACK_TIMEOUT_MS);a.unref?.(),e.cancelCurrentWrite=()=>c("canceled");try{this.trackOutboundEventCorrelation(r,f,u),t.send(JSON.stringify(l),h=>{c(h?"retry":"written")})}catch{c("retry")}});if(e.cancelCurrentWrite=null,!this.isOutboundFlushCurrent(e))return!1;if(d!=="written"||t.readyState!==y.OPEN){d==="retry"&&this.removeSeqFromEventCorrelation(f),this.settlePendingAcceptedOutput(f,"retry",!1);const _=this.retainOutboundFlushRemainder(e,d,`auth flush write failed for ${r} seq=${f} outcome=${d}`);return this.emitClientError(new Error(`outbound buffer flush failed at cmd=${r} seq=${f} outcome=${d}; ${_} packet(s) retained`)),!1}this.trackNonReplayableOutput(t,r,u,f),e.currentWritePending=!1,e.currentWriteOutcome="written",e.nextIndex=s+1}e.activeBatch=null,e.currentWritePending=!1,e.currentWriteOutcome=null,e.remainderHandled=!0}return this.isOutboundFlushCurrent(e)}retainOutboundFlushRemainder(e,t,n){if(e.remainderHandled||!e.activeBatch)return 0;e.remainderHandled=!0;const s=e.activeBatch,i=Math.min(e.nextIndex,s.length);let r=i;if(e.currentWritePending&&i<s.length){const o=s[i],f=this.outboundEventId(o.cmd,o.payload);t!=="retry"&&this.isNonReplayableOutput(o.cmd,o.payload)&&f&&(this.markOutputIntegrityFailed(f,n),r=i+1)}let u=0;for(const o of s.slice(r))this.bufferOutboundEntry(o)&&u++;return e.activeBatch=null,e.nextIndex=s.length,e.currentWritePending=!1,u}cancelOutboundFlush(e,t,n){if(e.finalized){this.outboundFlushInFlight===e&&(this.outboundFlushInFlight=null);return}e.finalized=!0,this.outboundFlushInFlight===e&&(this.outboundFlushInFlight=null),t==="connection_lost"?this.retainOutboundFlushRemainder(e,e.currentWriteOutcome,`connection lost during auth flush: ${n}`):(e.remainderHandled=!0,e.activeBatch=null,e.currentWritePending=!1);const s=e.cancelCurrentWrite;e.cancelCurrentWrite=null,s?.()}reconnectAfterOutboundFlushFailure(e,t){this.agentDeleted||!this.isConnectionCurrent(e,t)||this.reconnectAfterOutboundWriteFailure(e,"outbound flush failed")}reconnectAfterOutboundWriteFailure(e,t){if(this.agentDeleted||this.ws!==e)return;const n=this.connectionGeneration;this.connected=!1,this.negotiatedCapabilities.clear(),this.stopHeartbeat(),this.clearTerminalRetryTimers(),this.clearStopResultRetryTimers(),this.rejectAllPendingRequests(t);const s=this.outboundFlushInFlight;s&&s.socket===e&&s.connectionGeneration===n&&this.cancelOutboundFlush(s,"connection_lost",t),this.failNonReplayableOutputsForSocket(e,t),this.abortPendingOutputWrites(!0,e,n,t),this.abortPendingAcceptedOutputs(!0,e,n),this.clearAllEventCorrelations(),this.connectionGeneration++;try{e.close(1011,t)}catch{}this.ws===e&&(this.ws=null),this.attemptReconnect()}handleInvokeResult(e){const t=this.pendingInvokes.get(e.invoke_id);t&&(this.pendingInvokes.delete(e.invoke_id),clearTimeout(t.timer),e.code===0?t.resolve(e.data??null):t.reject(new Error(`agent_invoke error code=${e.code}: ${e.msg??""}`)))}rejectAllPendingInvokes(e){for(const[,t]of this.pendingInvokes)clearTimeout(t.timer),t.reject(new Error(`agent_invoke canceled: ${e}`));this.pendingInvokes.clear()}rejectAllPendingRequests(e){for(const[,t]of this.pendingRequests)clearTimeout(t.timer),t.reject(new Error(`request canceled: ${e}`));this.pendingRequests.clear()}cleanupSocket(e=this.ws,t=this.connectionGeneration){if(!(!e||!this.isConnectionCurrent(e,t)))try{e.close()}catch{}}startHeartbeat(){this.stopHeartbeat(),this.heartbeatFailures=0,this.heartbeatTimer=setInterval(()=>{const e=this.ws,t=this.connectionGeneration;!this.connected||!e||this.request("ping",{ts:Date.now()},{expected:["pong"],timeoutMs:5e3}).then(()=>{this.isConnectionCurrent(e,t)&&(this.heartbeatFailures=0)}).catch(()=>{!this.connected||!this.isConnectionCurrent(e,t)||(this.heartbeatFailures++,!(this.heartbeatFailures<p.HEARTBEAT_MAX_FAILURES)&&(this.cleanupSocket(e,t),this.attemptReconnect()))})},this.heartbeatSec*1e3)}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}}export{p as AibotClient,D as preprocessLargeIntegers,x as withRequiredCapabilities};
@@ -1 +1 @@
1
- import y from"node:http";import{randomBytes as O}from"node:crypto";import{log as c}from"../log/index.js";import{PHASE1_INVOKE_ACTIONS as S}from"./tools.js";import{WebSocketServer as w,WebSocket as k}from"ws";const f=1024*1024,v=32*1024*1024,H=50,b=1e3,g=6e4,N=256,J=new Set([...S,"event_tool_call"]);class E{server=null;port=0;authToken;invokeHandler=null;statusLineHandler=null;otelHandler=null;activeInvokes=0;wss=null;bridgeWs=null;mcpBridgeUpHandler=null;downstreamOutbox=[];constructor(){this.authToken=O(32).toString("hex")}setInvokeHandler(e){this.invokeHandler=e}setStatusLineHandler(e){this.statusLineHandler=e}setOtelHandler(e){this.otelHandler=e}async start(e=0){return new Promise((t,r)=>{this.server=y.createServer((o,i)=>this.handleRequest(o,i)),this.wss=new w({noServer:!0}),this.server.on("upgrade",(o,i,n)=>{const s=new URL(o.url??"/",`http://127.0.0.1:${this.port}`);if(s.pathname!=="/mcp-bridge"||s.searchParams.get("token")!==this.authToken){i.destroy();return}this.wss.handleUpgrade(o,i,n,d=>{if(this.bridgeWs=d,c.info("internal-api","mcp bridge connected"),this.downstreamOutbox.length>0){const a=this.downstreamOutbox;this.downstreamOutbox=[];for(const l of a)d.send(l);c.info("internal-api",`mcp bridge flushed ${a.length} buffered downstream frame(s)`)}d.on("message",a=>{let l;try{l=JSON.parse(a.toString("utf8"))}catch{return}this.mcpBridgeUpHandler?.(l)}),d.on("close",()=>{this.bridgeWs===d&&(this.bridgeWs=null),c.info("internal-api","mcp bridge disconnected")}),d.on("error",()=>{})})}),this.server.on("error",r),this.server.listen(e,"127.0.0.1",()=>{const o=this.server.address();typeof o=="object"&&o&&(this.port=o.port),this.server.removeListener("error",r),t(this.port)})})}get url(){return`http://127.0.0.1:${this.port}?token=${this.authToken}`}get baseUrl(){return`http://127.0.0.1:${this.port}`}get mcpBridgeWsUrl(){return`ws://127.0.0.1:${this.port}/mcp-bridge?token=${this.authToken}`}setMcpBridgeUpHandler(e){this.mcpBridgeUpHandler=e}sendMcpFrameToBridge(e){const t=JSON.stringify(e);if(this.bridgeWs&&this.bridgeWs.readyState===k.OPEN){this.bridgeWs.send(t);return}this.downstreamOutbox.length>=N&&(this.downstreamOutbox.shift(),c.warn("internal-api","mcp downstream outbox full, dropping oldest frame")),this.downstreamOutbox.push(t)}get token(){return this.authToken}async stop(){if(this.server)return new Promise(e=>{this.server.close(()=>{this.server=null,e()})})}checkAuth(e){return e.headers.authorization===`Bearer ${this.authToken}`||new URL(e.url??"/",`http://127.0.0.1:${this.port}`).searchParams.get("token")===this.authToken}handleRequest(e,t){if(e.method!=="POST"){t.writeHead(405),t.end(JSON.stringify({error:"method not allowed"}));return}if(!this.checkAuth(e)){t.writeHead(401),t.end(JSON.stringify({ok:!1,error:"unauthorized"}));return}const r=new URL(e.url??"/",`http://127.0.0.1:${this.port}`);if(r.pathname==="/api/status-line"){this.handleStatusLine(e,t);return}if(r.pathname==="/v1/logs"||r.pathname==="/v1/traces"){this.handleOtel(r.pathname==="/v1/logs"?"logs":"traces",e,t);return}if(!r.pathname.startsWith("/api/invoke")){t.writeHead(404),t.end(JSON.stringify({error:"not found"}));return}const o=[];let i=0;e.on("data",n=>{if(i+=n.length,i>f){t.writeHead(413),t.end(JSON.stringify({ok:!1,error:"request body too large"})),e.destroy();return}o.push(n)}),e.on("end",async()=>{let n;try{n=JSON.parse(Buffer.concat(o).toString("utf8"))}catch{t.writeHead(400),t.end(JSON.stringify({ok:!1,error:"invalid JSON"}));return}const s=n.action,d=n.params??{};if(!s||!this.invokeHandler){t.writeHead(400),t.end(JSON.stringify({ok:!1,error:"missing action or no handler"}));return}if(!J.has(s)){t.writeHead(400),t.end(JSON.stringify({ok:!1,error:`action '${s}' is not allowed`}));return}if(this.activeInvokes>=H){t.writeHead(429),t.end(JSON.stringify({ok:!1,error:"too many concurrent invokes"}));return}const a=n.timeout_ms!=null?Math.max(b,Math.min(n.timeout_ms,g)):g,l=Date.now();this.activeInvokes++;const u=new AbortController;try{const h=await Promise.race([this.invokeHandler(s,d,u.signal,a),new Promise((p,m)=>setTimeout(()=>{u.abort(),m(new Error("invoke timeout"))},a))]);t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0,data:h})),c.info("internal-api",`invoke ok action=${s} tool=${d.tool_name??"-"} ms=${Date.now()-l}`)}catch(h){u.abort();const p=h instanceof Error?h.message:String(h);t.writeHead(500),t.end(JSON.stringify({ok:!1,error:p})),c.error("internal-api",`invoke error action=${s} tool=${d.tool_name??"-"} ms=${Date.now()-l} err=${p}`)}finally{this.activeInvokes--}})}handleStatusLine(e,t){const r=[];let o=0;e.on("data",i=>{if(o+=i.length,o>f){t.writeHead(413),t.end(JSON.stringify({ok:!1,error:"request body too large"})),e.destroy();return}r.push(i)}),e.on("end",async()=>{let i;try{i=JSON.parse(Buffer.concat(r).toString("utf8"))}catch{t.writeHead(400),t.end(JSON.stringify({ok:!1,error:"invalid JSON"}));return}if(!this.statusLineHandler){t.writeHead(200),t.end(JSON.stringify({ok:!0}));return}try{await this.statusLineHandler(i),t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0}))}catch(n){console.error("[internal-api] statusLine handler error:",n instanceof Error?n.message:n),t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0}))}})}handleOtel(e,t,r){const o=[];let i=0,n=!1;t.on("data",s=>{if(!n){if(i+=s.length,i>v){n=!0,r.writeHead(413,{"content-type":"application/json"}),r.end(JSON.stringify({error:"OTLP request body too large"}));return}o.push(s)}}),t.on("end",async()=>{if(n)return;const s=Buffer.concat(o).toString("utf8");let d;try{const a=JSON.parse(s);if(!a||typeof a!="object"||Array.isArray(a))throw new Error("OTLP body is not an object");d=a}catch{r.writeHead(400,{"content-type":"application/json"}),r.end(JSON.stringify({error:"invalid OTLP JSON"}));return}try{await this.otelHandler?.(e,d,s)}catch(a){c.warn("internal-api",`OTLP ${e} evidence persistence failed: ${a instanceof Error?a.message:String(a)}`)}r.writeHead(200,{"content-type":"application/json"}),r.end("{}")})}}export{E as InternalApiServer};
1
+ import y from"node:http";import{randomBytes as O}from"node:crypto";import{log as c}from"../log/index.js";import{PHASE1_INVOKE_ACTIONS as S}from"./tools.js";import{WebSocketServer as w,WebSocket as k}from"ws";const f=1024*1024,v=32*1024*1024,H=50,b=1e3,g=75e3,N=256,J=new Set([...S,"event_tool_call"]);class E{server=null;port=0;authToken;invokeHandler=null;statusLineHandler=null;otelHandler=null;activeInvokes=0;wss=null;bridgeWs=null;mcpBridgeUpHandler=null;downstreamOutbox=[];constructor(){this.authToken=O(32).toString("hex")}setInvokeHandler(e){this.invokeHandler=e}setStatusLineHandler(e){this.statusLineHandler=e}setOtelHandler(e){this.otelHandler=e}async start(e=0){return new Promise((t,r)=>{this.server=y.createServer((o,i)=>this.handleRequest(o,i)),this.wss=new w({noServer:!0}),this.server.on("upgrade",(o,i,n)=>{const s=new URL(o.url??"/",`http://127.0.0.1:${this.port}`);if(s.pathname!=="/mcp-bridge"||s.searchParams.get("token")!==this.authToken){i.destroy();return}this.wss.handleUpgrade(o,i,n,d=>{if(this.bridgeWs=d,c.info("internal-api","mcp bridge connected"),this.downstreamOutbox.length>0){const a=this.downstreamOutbox;this.downstreamOutbox=[];for(const l of a)d.send(l);c.info("internal-api",`mcp bridge flushed ${a.length} buffered downstream frame(s)`)}d.on("message",a=>{let l;try{l=JSON.parse(a.toString("utf8"))}catch{return}this.mcpBridgeUpHandler?.(l)}),d.on("close",()=>{this.bridgeWs===d&&(this.bridgeWs=null),c.info("internal-api","mcp bridge disconnected")}),d.on("error",()=>{})})}),this.server.on("error",r),this.server.listen(e,"127.0.0.1",()=>{const o=this.server.address();typeof o=="object"&&o&&(this.port=o.port),this.server.removeListener("error",r),t(this.port)})})}get url(){return`http://127.0.0.1:${this.port}?token=${this.authToken}`}get baseUrl(){return`http://127.0.0.1:${this.port}`}get mcpBridgeWsUrl(){return`ws://127.0.0.1:${this.port}/mcp-bridge?token=${this.authToken}`}setMcpBridgeUpHandler(e){this.mcpBridgeUpHandler=e}sendMcpFrameToBridge(e){const t=JSON.stringify(e);if(this.bridgeWs&&this.bridgeWs.readyState===k.OPEN){this.bridgeWs.send(t);return}this.downstreamOutbox.length>=N&&(this.downstreamOutbox.shift(),c.warn("internal-api","mcp downstream outbox full, dropping oldest frame")),this.downstreamOutbox.push(t)}get token(){return this.authToken}async stop(){if(this.server)return new Promise(e=>{this.server.close(()=>{this.server=null,e()})})}checkAuth(e){return e.headers.authorization===`Bearer ${this.authToken}`||new URL(e.url??"/",`http://127.0.0.1:${this.port}`).searchParams.get("token")===this.authToken}handleRequest(e,t){if(e.method!=="POST"){t.writeHead(405),t.end(JSON.stringify({error:"method not allowed"}));return}if(!this.checkAuth(e)){t.writeHead(401),t.end(JSON.stringify({ok:!1,error:"unauthorized"}));return}const r=new URL(e.url??"/",`http://127.0.0.1:${this.port}`);if(r.pathname==="/api/status-line"){this.handleStatusLine(e,t);return}if(r.pathname==="/v1/logs"||r.pathname==="/v1/traces"){this.handleOtel(r.pathname==="/v1/logs"?"logs":"traces",e,t);return}if(!r.pathname.startsWith("/api/invoke")){t.writeHead(404),t.end(JSON.stringify({error:"not found"}));return}const o=[];let i=0;e.on("data",n=>{if(i+=n.length,i>f){t.writeHead(413),t.end(JSON.stringify({ok:!1,error:"request body too large"})),e.destroy();return}o.push(n)}),e.on("end",async()=>{let n;try{n=JSON.parse(Buffer.concat(o).toString("utf8"))}catch{t.writeHead(400),t.end(JSON.stringify({ok:!1,error:"invalid JSON"}));return}const s=n.action,d=n.params??{};if(!s||!this.invokeHandler){t.writeHead(400),t.end(JSON.stringify({ok:!1,error:"missing action or no handler"}));return}if(!J.has(s)){t.writeHead(400),t.end(JSON.stringify({ok:!1,error:`action '${s}' is not allowed`}));return}if(this.activeInvokes>=H){t.writeHead(429),t.end(JSON.stringify({ok:!1,error:"too many concurrent invokes"}));return}const a=n.timeout_ms!=null?Math.max(b,Math.min(n.timeout_ms,g)):g,l=Date.now();this.activeInvokes++;const u=new AbortController;try{const h=await Promise.race([this.invokeHandler(s,d,u.signal,a),new Promise((p,m)=>setTimeout(()=>{u.abort(),m(new Error("invoke timeout"))},a))]);t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0,data:h})),c.info("internal-api",`invoke ok action=${s} tool=${d.tool_name??"-"} ms=${Date.now()-l}`)}catch(h){u.abort();const p=h instanceof Error?h.message:String(h);t.writeHead(500),t.end(JSON.stringify({ok:!1,error:p})),c.error("internal-api",`invoke error action=${s} tool=${d.tool_name??"-"} ms=${Date.now()-l} err=${p}`)}finally{this.activeInvokes--}})}handleStatusLine(e,t){const r=[];let o=0;e.on("data",i=>{if(o+=i.length,o>f){t.writeHead(413),t.end(JSON.stringify({ok:!1,error:"request body too large"})),e.destroy();return}r.push(i)}),e.on("end",async()=>{let i;try{i=JSON.parse(Buffer.concat(r).toString("utf8"))}catch{t.writeHead(400),t.end(JSON.stringify({ok:!1,error:"invalid JSON"}));return}if(!this.statusLineHandler){t.writeHead(200),t.end(JSON.stringify({ok:!0}));return}try{await this.statusLineHandler(i),t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0}))}catch(n){console.error("[internal-api] statusLine handler error:",n instanceof Error?n.message:n),t.writeHead(200,{"content-type":"application/json"}),t.end(JSON.stringify({ok:!0}))}})}handleOtel(e,t,r){const o=[];let i=0,n=!1;t.on("data",s=>{if(!n){if(i+=s.length,i>v){n=!0,r.writeHead(413,{"content-type":"application/json"}),r.end(JSON.stringify({error:"OTLP request body too large"}));return}o.push(s)}}),t.on("end",async()=>{if(n)return;const s=Buffer.concat(o).toString("utf8");let d;try{const a=JSON.parse(s);if(!a||typeof a!="object"||Array.isArray(a))throw new Error("OTLP body is not an object");d=a}catch{r.writeHead(400,{"content-type":"application/json"}),r.end(JSON.stringify({error:"invalid OTLP JSON"}));return}try{await this.otelHandler?.(e,d,s)}catch(a){c.warn("internal-api",`OTLP ${e} evidence persistence failed: ${a instanceof Error?a.message:String(a)}`)}r.writeHead(200,{"content-type":"application/json"}),r.end("{}")})}}export{E as InternalApiServer};
@@ -1 +1 @@
1
- const r=[{name:"grix_query",description:"Search contacts, sessions, message history, messages, or favorited sessions in the Grix/AIBot platform. message_history defaults to the newest one clean text/approval-card message and excludes process/tool cards.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["contact_search","session_search","message_history","message_search","search_favorite_sessions"],description:"Query action type. search_favorite_sessions returns the owner's favorited sessions (supports keyword filter)."},id:{type:"string",description:"Contact ID (contact_search) or Session ID (session_search)."},keyword:{type:"string",description:"Search keyword."},sessionType:{type:"integer",enum:[1,2],description:"Filter by session type (session_search only): 1=private chat, 2=group chat. Omit to return all."},limit:{type:"integer",description:"Max results. message_history defaults to 1 when omitted."},offset:{type:"integer",description:"Result offset."},sessionId:{type:"string",description:"Session ID (message_history, message_search)."},beforeId:{type:"string",description:"Pagination cursor (message_history, message_search)."}},required:["action"]},validation:{required:["action"],properties:{action:{type:"string",enum:["contact_search","session_search","message_history","message_search","search_favorite_sessions"]},id:{type:"string"},keyword:{type:"string",maxLength:200},sessionType:{type:"integer",enum:[1,2]},limit:{type:"integer",minimum:1,maximum:100},offset:{type:"integer",minimum:0},sessionId:{type:"string"},beforeId:{type:"string"}}}},{name:"grix_audit_data",description:"Read connector-backed conversation audit replay data from Grix/AIBot: manifest, span pages, and content chunks.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["get_manifest","list_spans","get_content_chunk"],description:"Audit read action. Start with get_manifest, then call list_spans and/or get_content_chunk based on the manifest."},auditId:{type:"string",description:"Audit ID returned by the audited turn metadata."},revision:{type:"integer",description:"Optional manifest revision to read. Usually use the revision returned by get_manifest."},cursor:{type:"string",description:"Opaque pagination cursor returned by list_spans or get_content_chunk."},limit:{type:"integer",description:"Max span items for list_spans."},contentId:{type:"string",description:"Content reference ID from manifest.content_refs (get_content_chunk only)."},maxBytes:{type:"integer",description:"Max UTF-8 bytes to return for get_content_chunk."}},required:["action","auditId"]},validation:{required:["action","auditId"],properties:{action:{type:"string",enum:["get_manifest","list_spans","get_content_chunk"]},auditId:{type:"string"},revision:{type:"integer",minimum:1},cursor:{type:"string",maxLength:4096},limit:{type:"integer",minimum:1,maximum:200},contentId:{type:"string"},maxBytes:{type:"integer",minimum:1,maximum:131072}}}},{name:"grix_group",description:"Manage groups in the Grix/AIBot platform: create, get details, leave, dissolve, manage members and permissions.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create","detail","leave","add_members","remove_members","update_member_role","update_all_members_muted","update_member_speaking","dissolve"],description:"Group action type."},sessionId:{type:"string",description:"Group session ID."},name:{type:"string",description:"Group name (create)."},memberIds:{type:"array",items:{type:"string"},description:"Member IDs to add/remove."},memberTypes:{type:"array",items:{type:"integer",enum:[1,2]},description:"Member types (1=user, 2=agent)."},memberId:{type:"string",description:"Target member ID."},role:{type:"integer",enum:[1,2],description:"New role (1=admin, 2=member)."},memberType:{type:"integer",description:"Member type."},allMembersMuted:{type:"boolean",description:"Whether to mute all members."},isSpeakMuted:{type:"boolean",description:"Whether member is muted."},canSpeakWhenAllMuted:{type:"boolean",description:"Allow speaking when all muted."}},required:["action"]},validation:{required:["action"],properties:{action:{type:"string",enum:["create","detail","leave","add_members","remove_members","update_member_role","update_all_members_muted","update_member_speaking","dissolve"]},sessionId:{type:"string"},name:{type:"string",maxLength:128},memberIds:{type:"array",items:{type:"string"},maxItems:100},memberTypes:{type:"array",items:{type:"integer",enum:[1,2]}},memberId:{type:"string"},role:{type:"integer",enum:[1,2]},memberType:{type:"integer"},allMembersMuted:{type:"boolean"},isSpeakMuted:{type:"boolean"},canSpeakWhenAllMuted:{type:"boolean"}}}},{name:"grix_message_send",description:"Send a message to a session in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string",description:"Target session ID"},content:{type:"string",description:"Message content"},msgType:{type:"integer",description:"Message type (1=text, default 1)"},quotedMessageId:{type:"string",description:"Message ID to reply to"},threadId:{type:"string",description:"Thread ID for threaded reply"}},required:["sessionId","content"]},validation:{required:["sessionId","content"],properties:{sessionId:{type:"string"},content:{type:"string",maxLength:1e4},msgType:{type:"integer"},quotedMessageId:{type:"string"},threadId:{type:"string"}}}},{name:"grix_message_unsend",description:"Recall/unsend a message in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string",description:"Session ID"},msgId:{type:"string",description:"Message ID to unsend"}},required:["sessionId","msgId"]},validation:{required:["sessionId","msgId"],properties:{sessionId:{type:"string"},msgId:{type:"string"}}}},{name:"grix_file_link",description:"Create a direct, tailnet-only download link for a local file on this host. Use this whenever the user asks you to send, share, give, or deliver a file that exists on the machine where you run (a report, log, build artifact, export, or any local path). It returns a ready-to-use Markdown link in the `markdown` field \u2014 include that exact Markdown link in your reply so the user can click and download the file directly over the shared Tailscale network. The link is reachable only inside the tailnet, so just send it as-is \u2014 no need to worry about or mention any link lifetime. The download link is HTTPS, served by a built-in self-signed CA. The result also returns `ca_install_url`: the first time you share a link with a user (or whenever their browser warns the cert is untrusted), also give them this CA install link so they can install and trust it once \u2014 after that all download links work without warnings. Requires this host to be on a tailnet (Tailscale running).",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to a local file on this host to share with the user."},ttl_ms:{type:"integer",description:"Optional link lifetime in milliseconds. Leave unset to use the long default; set only if you deliberately want a short-lived link."}},required:["file_path"]},validation:{required:["file_path"],properties:{file_path:{type:"string",maxLength:4096},ttl_ms:{type:"integer",minimum:1e4,maximum:864e5}}}},{name:"grix_file_upload",description:"Upload a local file to the Grix platform and send it as a media message in the target session. Supports images (jpg/png/webp/gif/bmp/heic/heif), videos (mp4/mov/m4v/webm/mkv/avi), documents (pdf/doc/docx/xls/xlsx/ppt/pptx/txt/md/csv/json/xml), and archives (zip/rar/7z/tar/gz). Max 50 MB. Use this instead of grix_file_link when the file should appear as a native attachment in the chat (visible inline for images/videos), rather than a tailnet download link.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to a local file to upload."},session_id:{type:"string",description:"Target session ID to send the file to."},caption:{type:"string",description:"Optional text caption for the media message."},reply_to_message_id:{type:"string",description:"Optional message ID to quote/reply to."}},required:["file_path","session_id"]},validation:{required:["file_path","session_id"],properties:{file_path:{type:"string",maxLength:4096},session_id:{type:"string"},caption:{type:"string",maxLength:2e3},reply_to_message_id:{type:"string"}}}},{name:"grix_admin",description:"Agent and category management in the Grix/AIBot platform: create agents, manage categories, rotate API keys.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create_agent","list_categories","create_category","update_category","assign_category","rotate_api_key"],description:"Admin action type."},agentName:{type:"string",description:"Agent name (create_agent)."},introduction:{type:"string",description:"Professional behavioral introduction describing the Agent purpose, responsibilities, operating expectations, and boundaries (create_agent)."},isMain:{type:"boolean",description:"Set as main agent (create_agent)."},agentId:{type:"string",description:"Agent ID (assign_category, rotate_api_key)."},categoryId:{type:"string",description:"Category ID (create_agent, update_category, assign_category)."},name:{type:"string",description:"Category name (create_category, update_category)."},parentId:{type:"string",description:"Parent category ID (create_category, update_category)."},sortOrder:{type:"integer",description:"Sort order (create_category, update_category)."}},required:["action"]},validation:{required:["action"],properties:{action:{type:"string",enum:["create_agent","list_categories","create_category","update_category","assign_category","rotate_api_key"]},agentName:{type:"string"},introduction:{type:"string"},isMain:{type:"boolean"},agentId:{type:"string"},categoryId:{type:"string"},name:{type:"string"},parentId:{type:"string"},sortOrder:{type:"integer"}}}},{name:"grix_call_owner",description:"Call your owner into this session to talk by voice. Use this when, during your work, you need to reach your owner \u2014 to discuss something or to get an approval/review. It sends the owner an offline notification; when they tap it they land directly in this conversation and a voice-brain call is started automatically. Requires the owner to have configured a voice brain. Rate-limited per session.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"The session ID to call the owner into."}},required:["session_id"]},validation:{required:["session_id"],properties:{session_id:{type:"string"}}}},{name:"grix_agent_update",description:"Update the display name and/or text introduction of one of your owner's agents, identified by its numeric agent ID. Provide agent_name, introduction, or both \u2014 at least one is required.",inputSchema:{type:"object",properties:{agent_id:{type:"string",description:"Target agent's numeric ID, passed as a string."},agent_name:{type:"string",description:"New display name (max 100 characters, must be unique among the owner's agents)."},introduction:{type:"string",description:"New text introduction (max 300 characters)."}},required:["agent_id"]},validation:{required:["agent_id"],properties:{agent_id:{type:"string"},agent_name:{type:"string",maxLength:100},introduction:{type:"string",maxLength:300}}}},{name:"grix_dispatch_agent",description:`Dispatch one of your owner's agents to do work in a given working directory. Provide the target agent numeric ID, the working directory, and a text description of the task. The backend creates a NEW private session between the owner and that agent for each dispatch (it does not reuse past sessions), binds the working directory when the agent type requires it (claude/codex/etc.), and sends the task into the session AS THE OWNER so the agent starts working. Because the task is delivered as the owner, write it in the owner's first-person voice and tone \u2014 phrase it the way the owner would speak directly to the agent (e.g. "\u5E2E\u6211\u2026", "\u4F60\u53BB\u2026"), NOT as a third-person relay or as yourself narrating on the owner's behalf. Provide a short title summarizing the core of the task \u2014 it becomes the new session's title; if omitted the backend derives one from the task text.`,inputSchema:{type:"object",properties:{agent_id:{type:"string",description:"Target agent's numeric ID, passed as a string."},cwd:{type:"string",description:"Absolute working directory where the agent should do the work."},task:{type:"string",description:"Text description of the task to perform, written in the owner's first-person voice and tone \u2014 it is delivered into the session as the owner, so phrase it as the owner speaking directly to the agent, not as a third-person relay."},title:{type:"string",description:"Optional short title (a few words) summarizing the core of the task; used as the new session's title. If omitted, the backend derives a title from the task text."}},required:["agent_id","cwd","task"]},validation:{required:["agent_id","cwd","task"],properties:{agent_id:{type:"string"},cwd:{type:"string",maxLength:4096},task:{type:"string",maxLength:1e4},title:{type:"string",maxLength:255}}}},{name:"grix_session_send",description:"Send a message into a session AS THE OWNER \u2014 it appears as if the owner sent it, NOT as you (the agent). Dispatch callbacks (report_dispatch_result) MUST use this tool, even when you are a member of the callback session: a message sent as yourself cannot quote-wake the dispatcher agent, and your membership is not checked. NEVER use this for your own ordinary replies in a conversation \u2014 that would make your words show up as the owner's message; reply normally (or use grix_message_send to send as yourself) for those. The owner must be a member of the target session. Requires the Send as Owner permission scope \u2014 if rejected for missing permission, surface the error as-is so the owner can grant it; do not fall back to grix_message_send. Optional quoted_message_id quotes a message in the same session (used by dispatch callbacks to wake the dispatcher agent).",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Target session ID."},content:{type:"string",description:"Message content to send as the owner."},quoted_message_id:{type:"string",description:"Optional message ID in the target session to quote/reply to.",pattern:"^[1-9]\\d*$"}},required:["session_id","content"]},validation:{required:["session_id","content"],properties:{session_id:{type:"string"},content:{type:"string",maxLength:1e4},quoted_message_id:{type:"string",pattern:"^[1-9]\\d*$"}}}},{name:"grix_chat_state_query",description:"Query the chat-level task states across all of your owner's sessions (including direct and group chats). Returns one entry per session with a single mutually-exclusive state: running (working), waiting_approval (blocked on your owner to approve/deny), waiting_question (asked the owner a question, awaiting their reply), completed, failed, or idle (no task / stopped). When session_id identifies one completed session, the entry also includes exactly one clean final_result; non-completed and list queries never include message content. Also returns the session title (task_title) for easy identification. Supports pagination (page/page_size) and optional state filtering. Use this to see at a glance which chats are done, still running, or waiting on the owner.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"(Optional) Query a single session by its ID. Omit to return all sessions."},page:{type:"number",description:"(Optional) Page number, starting from 1. Defaults to 1 if omitted."},page_size:{type:"number",description:"(Optional) Number of items per page, max 100. Defaults to 10 if omitted."},state:{type:"string",description:"(Optional) Filter by a specific state: running, waiting_approval, waiting_question, completed, failed, or idle. Omit to return all states."}}},validation:{required:[],properties:{}}},{name:"grix_chat_state_update",description:"Manually update the task state of a specific chat session. Use this to mark a chat as completed, failed, idle, or any other state when you need to override it manually. The reason is written to stop_reason and is optional.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"The session ID whose state to update."},state:{type:"string",enum:["running","waiting_approval","waiting_question","completed","failed","idle"],description:"The new state to set. Must be one of: running, waiting_approval, waiting_question, completed, failed, idle."},reason:{type:"string",description:"(Optional) Reason for the state change, written to stop_reason."}}},validation:{required:["session_id","state"],properties:{}}},{name:"grix_access_control",description:"Manage sender access control: pair approval, allow/remove senders, set policy.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["pair_approve","pair_deny","allow_sender","remove_sender","set_policy"],description:"Access control action type."},code:{type:"string",description:"Pairing code (required for pair_approve/pair_deny)."},sender_id:{type:"string",description:"Sender ID (required for allow_sender/remove_sender)."},policy:{type:"string",enum:["allowlist","open","disabled"],description:"Access policy (required for set_policy)."}},required:["action"]},validation:{required:["action"],properties:{action:{type:"string",enum:["pair_approve","pair_deny","allow_sender","remove_sender","set_policy"]},code:{type:"string"},sender_id:{type:"string"},policy:{type:"string",enum:["allowlist","open","disabled"]}}}},{name:"grix_widget_visitor_ban",description:"Ban a widget visitor session: blocks the session and adds its most recent init IP to the owner's global IP ban list (7-day expiry).",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Widget visitor session ID (required)."}},required:["session_id"]},validation:{required:["session_id"],properties:{session_id:{type:"string"}}}},{name:"grix_skill_set",description:"Create, update, or delete one of your owner's custom skills in the platform skill library. The skill library auto-syncs to every machine the owner runs an agent on (a per-machine `grix/skills` directory), so defining a skill here makes it available on all of them. A skill is a plain SKILL.md package (frontmatter + body), same standard as other Grix skills. Provide `name` and the full `content` (the SKILL.md text) to create or overwrite by name. To delete a skill, pass its `name` with an empty `content` string. How and when any agent actually loads/uses a synced skill is arranged by the owner (in a system prompt or in conversation); this tool only manages the library.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Skill name (max 100 characters); unique within the owner. Used as the identifier and the synced directory name."},content:{type:"string",description:"Full SKILL.md text. Pass an empty string to delete the skill by name."}},required:["name","content"]},validation:{required:["name","content"],properties:{name:{type:"string",maxLength:100},content:{type:"string",maxLength:262144}}}},{name:"grix_skill_get",description:"Read one of your owner's custom skills by name (returns its full SKILL.md content), or list the owner's skill library when no name is given. Use this before editing to fetch current content, then call grix_skill_set with the revised text.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Skill name to fetch. Omit to list all skills (names + versions) instead."}}},validation:{required:[],properties:{name:{type:"string",maxLength:100}}}}],a=[{name:"grix_reply",description:"Send your final reply \u2014 the conclusion the user is waiting for \u2014 to the specified session. This is the message the user treats as your answer; deliver your final result here, and use plain text only for brief progress notes while you work. Supports streaming in chunks; the frontend automatically aggregates them into one complete message. The connector quotes the message being answered automatically, so quoted_message_id is optional (set it only to quote a different earlier message).",inputSchema:{type:"object",properties:{event_id:{type:"string",description:"Associated event ID from the inbound event."},session_id:{type:"string",description:"Target session ID."},text:{type:"string",description:"Reply text content."},quoted_message_id:{type:"string",description:"Quoted message ID (optional)."},is_final:{type:"boolean",description:"Whether this is a stage-final reply. Advisory only \u2014 does not trigger event completion; completion is handled by the complete tool or Stop hook."}},required:["session_id","text"]},validation:{required:["session_id","text"],properties:{event_id:{type:"string"},session_id:{type:"string"},text:{type:"string",maxLength:5e4},quoted_message_id:{type:"string"},is_final:{type:"boolean"}}}},{name:"grix_complete",description:"Mark event processing as complete, notifying the backend that no more replies are expected.",inputSchema:{type:"object",properties:{event_id:{type:"string",description:"The event ID to complete."},status:{type:"string",enum:["responded","canceled","failed"],description:"Completion status."},msg:{type:"string",description:"Additional note (optional)."}},required:["event_id","status"]},validation:{required:["event_id","status"],properties:{event_id:{type:"string"},status:{type:"string",enum:["responded","canceled","failed"]},msg:{type:"string",maxLength:500}}}},{name:"grix_event_ack",description:"Acknowledge event receipt (usually done automatically by the Dispatcher; agents typically do not need to call this manually).",inputSchema:{type:"object",properties:{event_id:{type:"string",description:"The event ID to acknowledge."},session_id:{type:"string",description:"Session ID."}},required:["event_id"]},validation:{required:["event_id"],properties:{event_id:{type:"string"},session_id:{type:"string"}}}},{name:"grix_composing",description:'Set the "typing" indicator status for a session.',inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID."},active:{type:"boolean",description:"true = typing, false = stopped."},event_id:{type:"string",description:"Associated event ID (optional)."}},required:["session_id","active"]},validation:{required:["session_id","active"],properties:{session_id:{type:"string"},active:{type:"boolean"},event_id:{type:"string"}}}},{name:"grix_status",description:"Query the Grix connection status of the current MCP session.",inputSchema:{type:"object",properties:{}},validation:{required:[],properties:{}}}],v={grix_dispatch_agent:"grix-agent-dispatch",grix_agent_update:"grix-agent-dispatch",grix_query:"grix-query",grix_audit_data:"grix-audit-data",grix_group:"grix-group",grix_message_send:"message-send",grix_message_unsend:"message-unsend",grix_admin:"grix-admin",grix_call_owner:"grix-owner-relay",grix_session_send:"grix-owner-relay",grix_chat_state_query:"grix-chat-state",grix_chat_state_update:"grix-chat-state",grix_status:"grix-chat-state",grix_access_control:"grix-access-control",grix_widget_visitor_ban:"grix-widget-visitor-ban",grix_file_link:"tailnet-file-share"};function w(e){return` Before calling this tool, follow the \`${e}\` skill's procedure first; do not invoke this tool directly without going through that skill's guidance.`}for(const e of[...r,...a]){const t=v[e.name];t&&(e.description+=w(t))}const p=[{name:"reply",description:"Send a visible message back to the chat for this grix-claude event.",inputSchema:{type:"object",properties:{text:{type:"string",description:"The visible reply text to send."},chat_id:{type:"string",description:"The target chat/session id from the <channel> tag."},event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},reply_to:{type:"string",description:"Optional message_id to quote instead of the inbound trigger message."},final:{type:"boolean",description:"Advisory flag only. It does not complete the event; completion is handled by complete tool or Stop hook."}},required:["chat_id","event_id","text"]}},{name:"complete",description:"Finish an event without sending a visible reply so the backend does not time out.",inputSchema:{type:"object",properties:{event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},status:{type:"string",enum:["responded","canceled","failed"]},msg:{type:"string"},code:{type:"string"}},required:["event_id","status"]}}],c=new Set(p.map(e=>e.name)),x=new Set(r.map(e=>e.name)),k=new Set(a.map(e=>e.name)),I=/([A-Za-z0-9._-]+:[A-Za-z0-9._-]+:[A-Za-z0-9._-]+:[A-Za-z0-9._-]+)/,S=/[A-Za-z0-9._-]+/;function H(e){return!!(x.has(e)||k.has(e)||c.has(e)||e.startsWith("mcp__grix"))}const q=[...r,...a],A=[...q,...p],Z=new Map(A.map(e=>[e.name,e]));function K(e,t){return e==="reply"?{name:"grix_reply",args:m("grix_reply",{event_id:t.event_id,session_id:t.chat_id,text:t.text,quoted_message_id:t.reply_to,is_final:t.final})}:e==="complete"?{name:"grix_complete",args:m("grix_complete",{event_id:t.event_id,status:t.status,msg:t.msg,code:t.code})}:{name:e,args:t}}function l(e){const t=String(e??"").trim();return t?t.match(I)?.[1]:void 0}function u(e){const t=String(e??"").trim();if(!t)return;const n=l(t);if(n)return _(n);const i=t.match(/(?:chat_id|session_id)\s*=\s*"([A-Za-z0-9._-]+)"/)?.[1];if(i)return i;const o=t.match(/[A-Za-z0-9._-]+/g)??[];for(const s of o)if(!(s==="event_id"||s==="chat_id"||s==="session_id")&&s.length>0)return s;return t.match(S)?.[0]}function _(e){if(!e)return;const t=e.split(":",1)[0]?.trim();if(t)return u(t)}function m(e,t){if(e!=="grix_reply"&&e!=="grix_complete")return t;const n={...t},i=l(n.event_id);if(i&&(n.event_id=i),e==="grix_reply"){const o=_(i),d=String(n.session_id??""),s=u(n.session_id),b=/\bevent_id\b|["'<>\s]/.test(d);s&&!(b&&o)?n.session_id=s:o&&(n.session_id=o)}return n}function V(e){return c.has(e)}function X(e,t){switch(e){case"grix_query":return T(t);case"grix_audit_data":return M(t);case"grix_group":return O(t);case"grix_message_send":return D(t);case"grix_message_unsend":return L(t);case"grix_file_link":return E(t);case"grix_file_upload":return j(t);case"grix_admin":return $(t);case"grix_call_owner":return N(t);case"grix_agent_update":return P(t);case"grix_dispatch_agent":return C(t);case"grix_session_send":return U(t);case"grix_chat_state_query":return z(t);case"grix_chat_state_update":return B(t);case"grix_access_control":return R(t);case"grix_widget_visitor_ban":return G(t);case"grix_skill_set":return W(t);case"grix_skill_get":return F(t);default:throw new Error(`Unknown tool: ${e}`)}}const g={contact_search:"contact_search",session_search:"session_search",message_history:"message_history",message_search:"message_search",search_favorite_sessions:"search_favorite_sessions"};function T(e){const t=String(e.action??""),n=g[t];if(!n)throw new Error(`Unknown grix_query action: ${t}`);const i={};return e.id!=null&&(i.id=e.id),e.keyword!=null&&(i.keyword=e.keyword),e.sessionType!=null&&(i.session_type=e.sessionType),e.limit!=null?i.limit=e.limit:t==="message_history"&&(i.limit=1),e.offset!=null&&(i.offset=e.offset),e.sessionId!=null&&(i.session_id=e.sessionId),e.beforeId!=null&&(i.before_id=e.beforeId),{action:n,params:i}}const y={get_manifest:"audit_get_manifest",list_spans:"audit_list_spans",get_content_chunk:"audit_get_content_chunk"};function M(e){const t=String(e.action??""),n=y[t];if(!n)throw new Error(`Unknown grix_audit_data action: ${t}`);const i={audit_id:e.auditId};return e.revision!=null&&(i.revision=e.revision),e.cursor!=null&&(i.cursor=e.cursor),e.limit!=null&&(i.limit=e.limit),e.contentId!=null&&(i.content_id=e.contentId),e.maxBytes!=null&&(i.max_bytes=e.maxBytes),{action:n,params:i}}const h={create:"group_create",detail:"group_detail_read",leave:"group_leave_self",add_members:"group_member_add",remove_members:"group_member_remove",update_member_role:"group_member_role_update",update_all_members_muted:"group_all_members_muted_update",update_member_speaking:"group_member_speaking_update",dissolve:"group_dissolve"};function O(e){const t=String(e.action??""),n=h[t];if(!n)throw new Error(`Unknown grix_group action: ${t}`);const i={};return e.sessionId!=null&&(i.session_id=e.sessionId),e.name!=null&&(i.name=e.name),e.memberIds!=null&&(i.member_ids=e.memberIds),e.memberTypes!=null&&(i.member_types=e.memberTypes),e.memberId!=null&&(i.member_id=e.memberId),e.role!=null&&(i.role=e.role),e.memberType!=null&&(i.member_type=e.memberType),e.allMembersMuted!=null&&(i.all_members_muted=e.allMembersMuted),e.isSpeakMuted!=null&&(i.is_speak_muted=e.isSpeakMuted),e.canSpeakWhenAllMuted!=null&&(i.can_speak_when_all_muted=e.canSpeakWhenAllMuted),{action:n,params:i}}function D(e){const t={session_id:e.sessionId,msg_type:e.msgType??1,content:e.content};return e.quotedMessageId!=null&&(t.quoted_message_id=e.quotedMessageId),e.threadId!=null&&(t.thread_id=e.threadId),{action:"send_msg",params:t}}function L(e){return{action:"delete_msg",params:{session_id:e.sessionId,msg_id:e.msgId}}}function E(e){const t={file_path:e.file_path};return e.ttl_ms!=null&&(t.ttl_ms=e.ttl_ms),{action:"file_link",params:t}}function j(e){const t={file_path:e.file_path,session_id:e.session_id};return e.caption!=null&&(t.caption=e.caption),e.reply_to_message_id!=null&&(t.reply_to_message_id=e.reply_to_message_id),{action:"file_upload",params:t,timeoutMs:6e4}}const f={create_agent:"agent_api_create",list_categories:"agent_category_list",create_category:"agent_category_create",update_category:"agent_category_update",assign_category:"agent_category_assign",rotate_api_key:"agent_api_key_rotate"};function N(e){return{action:"call_owner",params:{session_id:e.session_id}}}function P(e){if(e.agent_name==null&&e.introduction==null)throw new Error("grix_agent_update requires agent_name or introduction");const t={agent_id:e.agent_id};return e.agent_name!=null&&(t.agent_name=e.agent_name),e.introduction!=null&&(t.introduction=e.introduction),{action:"agent_introduction_update",params:t}}function C(e){return{action:"dispatch_agent",params:{agent_id:e.agent_id,cwd:e.cwd,task:e.task,title:e.title}}}function U(e){const t={session_id:e.session_id,content:e.content};return e.quoted_message_id!=null&&String(e.quoted_message_id).trim()!==""&&(t.quoted_message_id=e.quoted_message_id),{action:"session_send",params:t}}function z(e){const t={};return e.session_id!=null&&(t.session_id=e.session_id),e.page!=null&&(t.page=e.page),e.page_size!=null&&(t.page_size=e.page_size),e.state!=null&&(t.state=e.state),{action:"chat_state_query",params:t}}function R(e){const t=String(e.action??""),n=Q[t];if(!n)throw new Error(`Unknown grix_access_control action: ${t}`);const i={};return e.code!=null&&(i.code=e.code),e.sender_id!=null&&(i.sender_id=e.sender_id),e.policy!=null&&(i.policy=e.policy),{action:"claude_access_control",params:{verb:n,payload:i},timeoutMs:3e4}}function G(e){return{action:"widget_visitor_ban",params:{session_id:e.session_id}}}function B(e){const t={session_id:e.session_id,state:e.state};return e.reason!=null&&(t.reason=e.reason),{action:"chat_state_update",params:t}}function W(e){return{action:"skill_set",params:{name:e.name,content:e.content},timeoutMs:3e4}}function F(e){const t={};return e.name!=null&&(t.name=e.name),{action:"skill_get",params:t}}function $(e){const t=String(e.action??""),n=f[t];if(!n)throw new Error(`Unknown grix_admin action: ${t}`);const i={};return e.agentName!=null&&(i.agent_name=e.agentName),e.introduction!=null&&(i.introduction=e.introduction),e.isMain!=null&&(i.is_main=e.isMain),e.agentId!=null&&(i.agent_id=e.agentId),e.categoryId!=null&&(i.category_id=e.categoryId),e.name!=null&&(i.name=e.name),e.parentId!=null&&(i.parent_id=e.parentId),e.sortOrder!=null&&(i.sort_order=e.sortOrder),{action:n,params:i}}const Y=new Set([...Object.values(g),...Object.values(y),...Object.values(h),...Object.values(f),"send_msg","delete_msg","file_link","file_upload","call_owner","agent_introduction_update","dispatch_agent","session_send","chat_state_query","chat_state_update","claude_access_control","widget_visitor_ban","skill_set","skill_get"]),Q={pair_approve:"pair_approve",pair_deny:"pair_deny",allow_sender:"sender_allow",remove_sender:"sender_remove",set_policy:"policy_set"};export{Q as ACCESS_CONTROL_ACTION_MAP,q as ALL_TOOLS,a as EVENT_TOOLS,A as EXPOSED_TOOLS,Y as PHASE1_INVOKE_ACTIONS,x as PHASE1_TOOL_NAMES,k as PHASE2_TOOL_NAMES,r as TOOLS,p as TOOL_ALIASES,Z as TOOL_MAP,V as isAlias,H as isGrixInternalToolName,K as mapToolAlias,m as normalizeEventToolArgs,X as toolCallToInvoke};
1
+ const r=[{name:"grix_query",description:"Search contacts, sessions, message history, messages, or favorited sessions in the Grix/AIBot platform. message_history defaults to the newest one clean text/approval-card message and excludes process/tool cards.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["contact_search","session_search","message_history","message_search","search_favorite_sessions"],description:"Query action type. search_favorite_sessions returns the owner's favorited sessions (supports keyword filter)."},id:{type:"string",description:"Contact ID (contact_search) or Session ID (session_search)."},keyword:{type:"string",description:"Search keyword."},sessionType:{type:"integer",enum:[1,2],description:"Filter by session type (session_search only): 1=private chat, 2=group chat. Omit to return all."},limit:{type:"integer",description:"Max results. message_history defaults to 1 when omitted."},offset:{type:"integer",description:"Result offset."},sessionId:{type:"string",description:"Session ID (message_history, message_search)."},beforeId:{type:"string",description:"Pagination cursor (message_history, message_search)."}},required:["action"]},validation:{required:["action"],properties:{action:{type:"string",enum:["contact_search","session_search","message_history","message_search","search_favorite_sessions"]},id:{type:"string"},keyword:{type:"string",maxLength:200},sessionType:{type:"integer",enum:[1,2]},limit:{type:"integer",minimum:1,maximum:100},offset:{type:"integer",minimum:0},sessionId:{type:"string"},beforeId:{type:"string"}}}},{name:"grix_audit_data",description:"Read connector-backed conversation audit replay data from Grix/AIBot: manifest, span pages, and content chunks.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["get_manifest","list_spans","get_content_chunk"],description:"Audit read action. Start with get_manifest, then call list_spans and/or get_content_chunk based on the manifest."},auditId:{type:"string",description:"Audit ID returned by the audited turn metadata."},revision:{type:"integer",description:"Optional manifest revision to read. Usually use the revision returned by get_manifest."},cursor:{type:"string",description:"Opaque pagination cursor returned by list_spans or get_content_chunk."},limit:{type:"integer",description:"Max span items for list_spans."},contentId:{type:"string",description:"Content reference ID from manifest.content_refs (get_content_chunk only)."},maxBytes:{type:"integer",description:"Max UTF-8 bytes to return for get_content_chunk."}},required:["action","auditId"]},validation:{required:["action","auditId"],properties:{action:{type:"string",enum:["get_manifest","list_spans","get_content_chunk"]},auditId:{type:"string"},revision:{type:"integer",minimum:1},cursor:{type:"string",maxLength:4096},limit:{type:"integer",minimum:1,maximum:200},contentId:{type:"string"},maxBytes:{type:"integer",minimum:1,maximum:131072}}}},{name:"grix_group",description:"Manage groups in the Grix/AIBot platform: create, get details, leave, dissolve, manage members and permissions.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create","detail","leave","add_members","remove_members","update_member_role","update_all_members_muted","update_member_speaking","dissolve"],description:"Group action type."},sessionId:{type:"string",description:"Group session ID."},name:{type:"string",description:"Group name (create)."},memberIds:{type:"array",items:{type:"string"},description:"Member IDs to add/remove."},memberTypes:{type:"array",items:{type:"integer",enum:[1,2]},description:"Member types (1=user, 2=agent)."},memberId:{type:"string",description:"Target member ID."},role:{type:"integer",enum:[1,2],description:"New role (1=admin, 2=member)."},memberType:{type:"integer",description:"Member type."},allMembersMuted:{type:"boolean",description:"Whether to mute all members."},isSpeakMuted:{type:"boolean",description:"Whether member is muted."},canSpeakWhenAllMuted:{type:"boolean",description:"Allow speaking when all muted."}},required:["action"]},validation:{required:["action"],properties:{action:{type:"string",enum:["create","detail","leave","add_members","remove_members","update_member_role","update_all_members_muted","update_member_speaking","dissolve"]},sessionId:{type:"string"},name:{type:"string",maxLength:128},memberIds:{type:"array",items:{type:"string"},maxItems:100},memberTypes:{type:"array",items:{type:"integer",enum:[1,2]}},memberId:{type:"string"},role:{type:"integer",enum:[1,2]},memberType:{type:"integer"},allMembersMuted:{type:"boolean"},isSpeakMuted:{type:"boolean"},canSpeakWhenAllMuted:{type:"boolean"}}}},{name:"grix_message_send",description:"Send a message to a session in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string",description:"Target session ID"},content:{type:"string",description:"Message content"},msgType:{type:"integer",description:"Message type (1=text, default 1)"},quotedMessageId:{type:"string",description:"Message ID to reply to"},threadId:{type:"string",description:"Thread ID for threaded reply"}},required:["sessionId","content"]},validation:{required:["sessionId","content"],properties:{sessionId:{type:"string"},content:{type:"string",maxLength:1e4},msgType:{type:"integer"},quotedMessageId:{type:"string"},threadId:{type:"string"}}}},{name:"grix_message_unsend",description:"Recall/unsend a message in the Grix/AIBot platform.",inputSchema:{type:"object",properties:{sessionId:{type:"string",description:"Session ID"},msgId:{type:"string",description:"Message ID to unsend"}},required:["sessionId","msgId"]},validation:{required:["sessionId","msgId"],properties:{sessionId:{type:"string"},msgId:{type:"string"}}}},{name:"grix_file_link",description:"Create a direct, tailnet-only download link for a local file on this host. Use this whenever the user asks you to send, share, give, or deliver a file that exists on the machine where you run (a report, log, build artifact, export, or any local path). It returns a ready-to-use Markdown link in the `markdown` field \u2014 include that exact Markdown link in your reply so the user can click and download the file directly over the shared Tailscale network. The link is reachable only inside the tailnet, so just send it as-is \u2014 no need to worry about or mention any link lifetime. The download link is HTTPS, served by a built-in self-signed CA. The result also returns `ca_install_url`: the first time you share a link with a user (or whenever their browser warns the cert is untrusted), also give them this CA install link so they can install and trust it once \u2014 after that all download links work without warnings. Requires this host to be on a tailnet (Tailscale running).",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to a local file on this host to share with the user."},ttl_ms:{type:"integer",description:"Optional link lifetime in milliseconds. Leave unset to use the long default; set only if you deliberately want a short-lived link."}},required:["file_path"]},validation:{required:["file_path"],properties:{file_path:{type:"string",maxLength:4096},ttl_ms:{type:"integer",minimum:1e4,maximum:864e5}}}},{name:"grix_file_upload",description:"Upload a local file to the Grix platform and send it as a media message in the target session. Supports images (jpg/png/webp/gif/bmp/heic/heif), videos (mp4/mov/m4v/webm/mkv/avi), documents (pdf/doc/docx/xls/xlsx/ppt/pptx/txt/md/csv/json/xml), and archives (zip/rar/7z/tar/gz). Max 50 MB. Use this instead of grix_file_link when the file should appear as a native attachment in the chat (visible inline for images/videos), rather than a tailnet download link.",inputSchema:{type:"object",properties:{file_path:{type:"string",description:"Absolute path to a local file to upload."},session_id:{type:"string",description:"Target session ID to send the file to."},caption:{type:"string",description:"Optional text caption for the media message."},reply_to_message_id:{type:"string",description:"Optional message ID to quote/reply to."}},required:["file_path","session_id"]},validation:{required:["file_path","session_id"],properties:{file_path:{type:"string",maxLength:4096},session_id:{type:"string"},caption:{type:"string",maxLength:2e3},reply_to_message_id:{type:"string"}}}},{name:"grix_admin",description:"Agent and category management in the Grix/AIBot platform: create agents, manage categories, rotate API keys.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["create_agent","list_categories","create_category","update_category","assign_category","rotate_api_key"],description:"Admin action type."},agentName:{type:"string",description:"Agent name (create_agent)."},introduction:{type:"string",description:"Professional behavioral introduction describing the Agent purpose, responsibilities, operating expectations, and boundaries (create_agent)."},isMain:{type:"boolean",description:"Set as main agent (create_agent)."},agentId:{type:"string",description:"Agent ID (assign_category, rotate_api_key)."},categoryId:{type:"string",description:"Category ID (create_agent, update_category, assign_category)."},name:{type:"string",description:"Category name (create_category, update_category)."},parentId:{type:"string",description:"Parent category ID (create_category, update_category)."},sortOrder:{type:"integer",description:"Sort order (create_category, update_category)."}},required:["action"]},validation:{required:["action"],properties:{action:{type:"string",enum:["create_agent","list_categories","create_category","update_category","assign_category","rotate_api_key"]},agentName:{type:"string"},introduction:{type:"string"},isMain:{type:"boolean"},agentId:{type:"string"},categoryId:{type:"string"},name:{type:"string"},parentId:{type:"string"},sortOrder:{type:"integer"}}}},{name:"grix_call_owner",description:"Call your owner into this session to talk by voice. Use this when, during your work, you need to reach your owner \u2014 to discuss something or to get an approval/review. It sends the owner an offline notification; when they tap it they land directly in this conversation and a voice-brain call is started automatically. Requires the owner to have configured a voice brain. Rate-limited per session.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"The session ID to call the owner into."}},required:["session_id"]},validation:{required:["session_id"],properties:{session_id:{type:"string"}}}},{name:"grix_agent_update",description:"Update the display name and/or text introduction of one of your owner's agents, identified by its numeric agent ID. Provide agent_name, introduction, or both \u2014 at least one is required.",inputSchema:{type:"object",properties:{agent_id:{type:"string",description:"Target agent's numeric ID, passed as a string."},agent_name:{type:"string",description:"New display name (max 100 characters, must be unique among the owner's agents)."},introduction:{type:"string",description:"New text introduction (max 300 characters)."}},required:["agent_id"]},validation:{required:["agent_id"],properties:{agent_id:{type:"string"},agent_name:{type:"string",maxLength:100},introduction:{type:"string",maxLength:300}}}},{name:"grix_dispatch_agent",description:`Dispatch one of your owner's agents to do work in a given working directory. Provide the target agent numeric ID, the working directory, and a text description of the task. The backend creates a NEW private session between the owner and that agent for each dispatch (it does not reuse past sessions), binds the working directory when the agent type requires it (claude/codex/etc.), and sends the task into the session AS THE OWNER so the agent starts working. Because the task is delivered as the owner, write it in the owner's first-person voice and tone \u2014 phrase it the way the owner would speak directly to the agent (e.g. "\u5E2E\u6211\u2026", "\u4F60\u53BB\u2026"), NOT as a third-person relay or as yourself narrating on the owner's behalf. Provide a short title summarizing the core of the task \u2014 it becomes the new session's title; if omitted the backend derives one from the task text.`,inputSchema:{type:"object",properties:{agent_id:{type:"string",description:"Target agent's numeric ID, passed as a string."},cwd:{type:"string",description:"Absolute working directory where the agent should do the work."},task:{type:"string",description:"Text description of the task to perform, written in the owner's first-person voice and tone \u2014 it is delivered into the session as the owner, so phrase it as the owner speaking directly to the agent, not as a third-person relay."},title:{type:"string",description:"Optional short title (a few words) summarizing the core of the task; used as the new session's title. If omitted, the backend derives a title from the task text."}},required:["agent_id","cwd","task"]},validation:{required:["agent_id","cwd","task"],properties:{agent_id:{type:"string"},cwd:{type:"string",maxLength:4096},task:{type:"string",maxLength:1e4},title:{type:"string",maxLength:255}}}},{name:"grix_session_send",description:"Send a message into a session AS THE OWNER \u2014 it appears as if the owner sent it, NOT as you (the agent). Dispatch callbacks (report_dispatch_result) MUST use this tool, even when you are a member of the callback session: a message sent as yourself cannot quote-wake the dispatcher agent, and your membership is not checked. NEVER use this for your own ordinary replies in a conversation \u2014 that would make your words show up as the owner's message; reply normally (or use grix_message_send to send as yourself) for those. The owner must be a member of the target session. Requires the Send as Owner permission scope \u2014 if rejected for missing permission, surface the error as-is so the owner can grant it; do not fall back to grix_message_send. Optional quoted_message_id quotes a message in the same session (used by dispatch callbacks to wake the dispatcher agent).",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Target session ID."},content:{type:"string",description:"Message content to send as the owner."},quoted_message_id:{type:"string",description:"Optional message ID in the target session to quote/reply to.",pattern:"^[1-9]\\d*$"}},required:["session_id","content"]},validation:{required:["session_id","content"],properties:{session_id:{type:"string"},content:{type:"string",maxLength:1e4},quoted_message_id:{type:"string",pattern:"^[1-9]\\d*$"}}}},{name:"grix_chat_state_query",description:"Query the chat-level task states across all of your owner's sessions (including direct and group chats). Returns one entry per session with a single mutually-exclusive state: running (working), waiting_approval (blocked on your owner to approve/deny), waiting_question (asked the owner a question, awaiting their reply), completed, failed, or idle (no task / stopped). When session_id identifies one completed session, the entry also includes exactly one clean final_result; non-completed and list queries never include message content. Also returns the session title (task_title) for easy identification. Supports pagination (page/page_size) and optional state filtering. Use this to see at a glance which chats are done, still running, or waiting on the owner.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"(Optional) Query a single session by its ID. Omit to return all sessions."},page:{type:"number",description:"(Optional) Page number, starting from 1. Defaults to 1 if omitted."},page_size:{type:"number",description:"(Optional) Number of items per page, max 100. Defaults to 10 if omitted."},state:{type:"string",description:"(Optional) Filter by a specific state: running, waiting_approval, waiting_question, completed, failed, or idle. Omit to return all states."}}},validation:{required:[],properties:{}}},{name:"grix_chat_state_update",description:"Manually update the task state of a specific chat session. Use this to mark a chat as completed, failed, idle, or any other state when you need to override it manually. The reason is written to stop_reason and is optional.",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"The session ID whose state to update."},state:{type:"string",enum:["running","waiting_approval","waiting_question","completed","failed","idle"],description:"The new state to set. Must be one of: running, waiting_approval, waiting_question, completed, failed, idle."},reason:{type:"string",description:"(Optional) Reason for the state change, written to stop_reason."}}},validation:{required:["session_id","state"],properties:{}}},{name:"grix_access_control",description:"Manage sender access control: pair approval, allow/remove senders, set policy.",inputSchema:{type:"object",properties:{action:{type:"string",enum:["pair_approve","pair_deny","allow_sender","remove_sender","set_policy"],description:"Access control action type."},code:{type:"string",description:"Pairing code (required for pair_approve/pair_deny)."},sender_id:{type:"string",description:"Sender ID (required for allow_sender/remove_sender)."},policy:{type:"string",enum:["allowlist","open","disabled"],description:"Access policy (required for set_policy)."}},required:["action"]},validation:{required:["action"],properties:{action:{type:"string",enum:["pair_approve","pair_deny","allow_sender","remove_sender","set_policy"]},code:{type:"string"},sender_id:{type:"string"},policy:{type:"string",enum:["allowlist","open","disabled"]}}}},{name:"grix_widget_visitor_ban",description:"Ban a widget visitor session: blocks the session and adds its most recent init IP to the owner's global IP ban list (7-day expiry).",inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Widget visitor session ID (required)."}},required:["session_id"]},validation:{required:["session_id"],properties:{session_id:{type:"string"}}}},{name:"grix_skill_set",description:"Create, update, or delete one of your owner's custom skills in the platform skill library. The skill library auto-syncs to every machine the owner runs an agent on (a per-machine `grix/skills` directory), so defining a skill here makes it available on all of them. A skill is a plain SKILL.md package (frontmatter + body), same standard as other Grix skills. Provide `name` and the full `content` (the SKILL.md text) to create or overwrite by name. To delete a skill, pass its `name` with an empty `content` string. How and when any agent actually loads/uses a synced skill is arranged by the owner (in a system prompt or in conversation); this tool only manages the library.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Skill name (max 100 characters); unique within the owner. Used as the identifier and the synced directory name."},content:{type:"string",description:"Full SKILL.md text. Pass an empty string to delete the skill by name."}},required:["name","content"]},validation:{required:["name","content"],properties:{name:{type:"string",maxLength:100},content:{type:"string",maxLength:262144}}}},{name:"grix_skill_get",description:"Read one of your owner's custom skills by name (returns its full SKILL.md content), or list the owner's skill library when no name is given. Use this before editing to fetch current content, then call grix_skill_set with the revised text.",inputSchema:{type:"object",properties:{name:{type:"string",description:"Skill name to fetch. Omit to list all skills (names + versions) instead."}}},validation:{required:[],properties:{name:{type:"string",maxLength:100}}}}],a=[{name:"grix_reply",description:"Send your final reply \u2014 the conclusion the user is waiting for \u2014 to the specified session. This is the message the user treats as your answer; deliver your final result here, and use plain text only for brief progress notes while you work. Supports streaming in chunks; the frontend automatically aggregates them into one complete message. The connector quotes the message being answered automatically, so quoted_message_id is optional (set it only to quote a different earlier message).",inputSchema:{type:"object",properties:{event_id:{type:"string",description:"Associated event ID from the inbound event."},session_id:{type:"string",description:"Target session ID."},text:{type:"string",description:"Reply text content."},quoted_message_id:{type:"string",description:"Quoted message ID (optional)."},is_final:{type:"boolean",description:"Whether this is a stage-final reply. Advisory only \u2014 does not trigger event completion; completion is handled by the complete tool or Stop hook."}},required:["session_id","text"]},validation:{required:["session_id","text"],properties:{event_id:{type:"string"},session_id:{type:"string"},text:{type:"string",maxLength:5e4},quoted_message_id:{type:"string"},is_final:{type:"boolean"}}}},{name:"grix_complete",description:"Mark event processing as complete, notifying the backend that no more replies are expected.",inputSchema:{type:"object",properties:{event_id:{type:"string",description:"The event ID to complete."},status:{type:"string",enum:["responded","canceled","failed"],description:"Completion status."},msg:{type:"string",description:"Additional note (optional)."}},required:["event_id","status"]},validation:{required:["event_id","status"],properties:{event_id:{type:"string"},status:{type:"string",enum:["responded","canceled","failed"]},msg:{type:"string",maxLength:500}}}},{name:"grix_event_ack",description:"Acknowledge event receipt (usually done automatically by the Dispatcher; agents typically do not need to call this manually).",inputSchema:{type:"object",properties:{event_id:{type:"string",description:"The event ID to acknowledge."},session_id:{type:"string",description:"Session ID."}},required:["event_id"]},validation:{required:["event_id"],properties:{event_id:{type:"string"},session_id:{type:"string"}}}},{name:"grix_composing",description:'Set the "typing" indicator status for a session.',inputSchema:{type:"object",properties:{session_id:{type:"string",description:"Session ID."},active:{type:"boolean",description:"true = typing, false = stopped."},event_id:{type:"string",description:"Associated event ID (optional)."}},required:["session_id","active"]},validation:{required:["session_id","active"],properties:{session_id:{type:"string"},active:{type:"boolean"},event_id:{type:"string"}}}},{name:"grix_status",description:"Query the Grix connection status of the current MCP session.",inputSchema:{type:"object",properties:{}},validation:{required:[],properties:{}}}],v={grix_dispatch_agent:"grix-agent-dispatch",grix_agent_update:"grix-agent-dispatch",grix_query:"grix-query",grix_audit_data:"grix-audit-data",grix_group:"grix-group",grix_message_send:"message-send",grix_message_unsend:"message-unsend",grix_admin:"grix-admin",grix_call_owner:"grix-owner-relay",grix_session_send:"grix-owner-relay",grix_chat_state_query:"grix-chat-state",grix_chat_state_update:"grix-chat-state",grix_status:"grix-chat-state",grix_access_control:"grix-access-control",grix_widget_visitor_ban:"grix-widget-visitor-ban",grix_file_link:"tailnet-file-share"};function w(e){return` Before calling this tool, follow the \`${e}\` skill's procedure first; do not invoke this tool directly without going through that skill's guidance.`}for(const e of[...r,...a]){const t=v[e.name];t&&(e.description+=w(t))}const p=[{name:"reply",description:"Send a visible message back to the chat for this grix-claude event.",inputSchema:{type:"object",properties:{text:{type:"string",description:"The visible reply text to send."},chat_id:{type:"string",description:"The target chat/session id from the <channel> tag."},event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},reply_to:{type:"string",description:"Optional message_id to quote instead of the inbound trigger message."},final:{type:"boolean",description:"Advisory flag only. It does not complete the event; completion is handled by complete tool or Stop hook."}},required:["chat_id","event_id","text"]}},{name:"complete",description:"Finish an event without sending a visible reply so the backend does not time out.",inputSchema:{type:"object",properties:{event_id:{type:"string",description:"The Aibot event_id from the <channel> tag."},status:{type:"string",enum:["responded","canceled","failed"]},msg:{type:"string"},code:{type:"string"}},required:["event_id","status"]}}],c=new Set(p.map(e=>e.name)),x=new Set(r.map(e=>e.name)),k=new Set(a.map(e=>e.name)),I=/([A-Za-z0-9._-]+:[A-Za-z0-9._-]+:[A-Za-z0-9._-]+:[A-Za-z0-9._-]+)/,S=/[A-Za-z0-9._-]+/;function H(e){return!!(x.has(e)||k.has(e)||c.has(e)||e.startsWith("mcp__grix"))}const q=[...r,...a],A=[...q,...p],Z=new Map(A.map(e=>[e.name,e]));function K(e,t){return e==="reply"?{name:"grix_reply",args:m("grix_reply",{event_id:t.event_id,session_id:t.chat_id,text:t.text,quoted_message_id:t.reply_to,is_final:t.final})}:e==="complete"?{name:"grix_complete",args:m("grix_complete",{event_id:t.event_id,status:t.status,msg:t.msg,code:t.code})}:{name:e,args:t}}function l(e){const t=String(e??"").trim();return t?t.match(I)?.[1]:void 0}function u(e){const t=String(e??"").trim();if(!t)return;const n=l(t);if(n)return _(n);const i=t.match(/(?:chat_id|session_id)\s*=\s*"([A-Za-z0-9._-]+)"/)?.[1];if(i)return i;const o=t.match(/[A-Za-z0-9._-]+/g)??[];for(const s of o)if(!(s==="event_id"||s==="chat_id"||s==="session_id")&&s.length>0)return s;return t.match(S)?.[0]}function _(e){if(!e)return;const t=e.split(":",1)[0]?.trim();if(t)return u(t)}function m(e,t){if(e!=="grix_reply"&&e!=="grix_complete")return t;const n={...t},i=l(n.event_id);if(i&&(n.event_id=i),e==="grix_reply"){const o=_(i),d=String(n.session_id??""),s=u(n.session_id),b=/\bevent_id\b|["'<>\s]/.test(d);s&&!(b&&o)?n.session_id=s:o&&(n.session_id=o)}return n}function V(e){return c.has(e)}function X(e,t){switch(e){case"grix_query":return T(t);case"grix_audit_data":return M(t);case"grix_group":return O(t);case"grix_message_send":return D(t);case"grix_message_unsend":return L(t);case"grix_file_link":return E(t);case"grix_file_upload":return j(t);case"grix_admin":return $(t);case"grix_call_owner":return N(t);case"grix_agent_update":return P(t);case"grix_dispatch_agent":return C(t);case"grix_session_send":return U(t);case"grix_chat_state_query":return z(t);case"grix_chat_state_update":return B(t);case"grix_access_control":return R(t);case"grix_widget_visitor_ban":return G(t);case"grix_skill_set":return W(t);case"grix_skill_get":return F(t);default:throw new Error(`Unknown tool: ${e}`)}}const g={contact_search:"contact_search",session_search:"session_search",message_history:"message_history",message_search:"message_search",search_favorite_sessions:"search_favorite_sessions"};function T(e){const t=String(e.action??""),n=g[t];if(!n)throw new Error(`Unknown grix_query action: ${t}`);const i={};return e.id!=null&&(i.id=e.id),e.keyword!=null&&(i.keyword=e.keyword),e.sessionType!=null&&(i.session_type=e.sessionType),e.limit!=null?i.limit=e.limit:t==="message_history"&&(i.limit=1),e.offset!=null&&(i.offset=e.offset),e.sessionId!=null&&(i.session_id=e.sessionId),e.beforeId!=null&&(i.before_id=e.beforeId),{action:n,params:i}}const y={get_manifest:"audit_get_manifest",list_spans:"audit_list_spans",get_content_chunk:"audit_get_content_chunk"};function M(e){const t=String(e.action??""),n=y[t];if(!n)throw new Error(`Unknown grix_audit_data action: ${t}`);const i={audit_id:e.auditId};return e.revision!=null&&(i.revision=e.revision),e.cursor!=null&&(i.cursor=e.cursor),e.limit!=null&&(i.limit=e.limit),e.contentId!=null&&(i.content_id=e.contentId),e.maxBytes!=null&&(i.max_bytes=e.maxBytes),{action:n,params:i}}const h={create:"group_create",detail:"group_detail_read",leave:"group_leave_self",add_members:"group_member_add",remove_members:"group_member_remove",update_member_role:"group_member_role_update",update_all_members_muted:"group_all_members_muted_update",update_member_speaking:"group_member_speaking_update",dissolve:"group_dissolve"};function O(e){const t=String(e.action??""),n=h[t];if(!n)throw new Error(`Unknown grix_group action: ${t}`);const i={};return e.sessionId!=null&&(i.session_id=e.sessionId),e.name!=null&&(i.name=e.name),e.memberIds!=null&&(i.member_ids=e.memberIds),e.memberTypes!=null&&(i.member_types=e.memberTypes),e.memberId!=null&&(i.member_id=e.memberId),e.role!=null&&(i.role=e.role),e.memberType!=null&&(i.member_type=e.memberType),e.allMembersMuted!=null&&(i.all_members_muted=e.allMembersMuted),e.isSpeakMuted!=null&&(i.is_speak_muted=e.isSpeakMuted),e.canSpeakWhenAllMuted!=null&&(i.can_speak_when_all_muted=e.canSpeakWhenAllMuted),{action:n,params:i}}function D(e){const t={session_id:e.sessionId,msg_type:e.msgType??1,content:e.content};return e.quotedMessageId!=null&&(t.quoted_message_id=e.quotedMessageId),e.threadId!=null&&(t.thread_id=e.threadId),{action:"send_msg",params:t}}function L(e){return{action:"delete_msg",params:{session_id:e.sessionId,msg_id:e.msgId}}}function E(e){const t={file_path:e.file_path};return e.ttl_ms!=null&&(t.ttl_ms=e.ttl_ms),{action:"file_link",params:t}}function j(e){const t={file_path:e.file_path,session_id:e.session_id};return e.caption!=null&&(t.caption=e.caption),e.reply_to_message_id!=null&&(t.reply_to_message_id=e.reply_to_message_id),{action:"file_upload",params:t,timeoutMs:6e4}}const f={create_agent:"agent_api_create",list_categories:"agent_category_list",create_category:"agent_category_create",update_category:"agent_category_update",assign_category:"agent_category_assign",rotate_api_key:"agent_api_key_rotate"};function N(e){return{action:"call_owner",params:{session_id:e.session_id}}}function P(e){if(e.agent_name==null&&e.introduction==null)throw new Error("grix_agent_update requires agent_name or introduction");const t={agent_id:e.agent_id};return e.agent_name!=null&&(t.agent_name=e.agent_name),e.introduction!=null&&(t.introduction=e.introduction),{action:"agent_introduction_update",params:t}}function C(e){return{action:"dispatch_agent",params:{agent_id:e.agent_id,cwd:e.cwd,task:e.task,title:e.title},timeoutMs:75e3}}function U(e){const t={session_id:e.session_id,content:e.content};return e.quoted_message_id!=null&&String(e.quoted_message_id).trim()!==""&&(t.quoted_message_id=e.quoted_message_id),{action:"session_send",params:t}}function z(e){const t={};return e.session_id!=null&&(t.session_id=e.session_id),e.page!=null&&(t.page=e.page),e.page_size!=null&&(t.page_size=e.page_size),e.state!=null&&(t.state=e.state),{action:"chat_state_query",params:t}}function R(e){const t=String(e.action??""),n=Q[t];if(!n)throw new Error(`Unknown grix_access_control action: ${t}`);const i={};return e.code!=null&&(i.code=e.code),e.sender_id!=null&&(i.sender_id=e.sender_id),e.policy!=null&&(i.policy=e.policy),{action:"claude_access_control",params:{verb:n,payload:i},timeoutMs:3e4}}function G(e){return{action:"widget_visitor_ban",params:{session_id:e.session_id}}}function B(e){const t={session_id:e.session_id,state:e.state};return e.reason!=null&&(t.reason=e.reason),{action:"chat_state_update",params:t}}function W(e){return{action:"skill_set",params:{name:e.name,content:e.content},timeoutMs:3e4}}function F(e){const t={};return e.name!=null&&(t.name=e.name),{action:"skill_get",params:t}}function $(e){const t=String(e.action??""),n=f[t];if(!n)throw new Error(`Unknown grix_admin action: ${t}`);const i={};return e.agentName!=null&&(i.agent_name=e.agentName),e.introduction!=null&&(i.introduction=e.introduction),e.isMain!=null&&(i.is_main=e.isMain),e.agentId!=null&&(i.agent_id=e.agentId),e.categoryId!=null&&(i.category_id=e.categoryId),e.name!=null&&(i.name=e.name),e.parentId!=null&&(i.parent_id=e.parentId),e.sortOrder!=null&&(i.sort_order=e.sortOrder),{action:n,params:i}}const Y=new Set([...Object.values(g),...Object.values(y),...Object.values(h),...Object.values(f),"send_msg","delete_msg","file_link","file_upload","call_owner","agent_introduction_update","dispatch_agent","session_send","chat_state_query","chat_state_update","claude_access_control","widget_visitor_ban","skill_set","skill_get"]),Q={pair_approve:"pair_approve",pair_deny:"pair_deny",allow_sender:"sender_allow",remove_sender:"sender_remove",set_policy:"policy_set"};export{Q as ACCESS_CONTROL_ACTION_MAP,q as ALL_TOOLS,a as EVENT_TOOLS,A as EXPOSED_TOOLS,Y as PHASE1_INVOKE_ACTIONS,x as PHASE1_TOOL_NAMES,k as PHASE2_TOOL_NAMES,r as TOOLS,p as TOOL_ALIASES,Z as TOOL_MAP,V as isAlias,H as isGrixInternalToolName,K as mapToolAlias,m as normalizeEventToolArgs,X as toolCallToInvoke};
@@ -1 +1 @@
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};
1
+ function a(o){const e=new Set([`http://127.0.0.1:${o.serverPort}`,`http://localhost:${o.serverPort}`,...o.allowedOrigins]),t=new Set([`127.0.0.1:${o.serverPort}`,`localhost:${o.serverPort}`,...o.allowedHosts]);return{validateRequest(s){const r=i(s,e);if(!r.ok)return r;const n=l(s,t);return n.ok?{ok:!0}:n}}}function i(o,e){const t=o.headers.origin;return t?e.has(t)?{ok:!0}:{ok:!1,statusCode:403,message:`Origin not allowed: ${t}`}:{ok:!0}}function l(o,e){const t=o.headers.host;return t?e.has(t)?{ok:!0}:{ok:!1,statusCode:403,message:`Host not allowed: ${t}`}:{ok:!1,statusCode:403,message:"Missing Host header"}}export{a as createSecurityPolicy};
@@ -10058,7 +10058,10 @@ function buildAgentUpdateInvoke(args) {
10058
10058
  function buildDispatchAgentInvoke(args) {
10059
10059
  return {
10060
10060
  action: "dispatch_agent",
10061
- params: { agent_id: args.agent_id, cwd: args.cwd, task: args.task, title: args.title }
10061
+ params: { agent_id: args.agent_id, cwd: args.cwd, task: args.task, title: args.title },
10062
+ // Backend session_bind waits 60s (cold slot start). Leave headroom for
10063
+ // session create + send-as-owner after bind succeeds.
10064
+ timeoutMs: 75e3
10062
10065
  };
10063
10066
  }
10064
10067
  function buildSessionSendInvoke(args) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "grix-connector",
3
- "version": "3.29.1",
3
+ "version": "3.29.3",
4
4
  "description": "Connect local AI coding agents (Claude, Codex, Gemini, Qwen, DeepSeek, Cursor, OpenCode, Pi, OpenHuman, Reasonix) to the Grix scheduling platform. Also serves as an OpenClaw plugin for Grix channel transport.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",