grix-connector 4.3.0 → 4.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/dist/adapter/claude/activity-status-manager.js +1 -1
  2. package/dist/adapter/claude/claude-adapter.js +18 -18
  3. package/dist/adapter/claude/claude-bridge-server.js +1 -1
  4. package/dist/adapter/claude/claude-tools.js +1 -1
  5. package/dist/adapter/claude/claude-worker-client.js +1 -1
  6. package/dist/adapter/claude/mcp-http-launcher.js +2 -2
  7. package/dist/adapter/claude/result-timeout.js +1 -1
  8. package/dist/adapter/codewhale/codewhale-adapter.js +3 -3
  9. package/dist/adapter/codex/codex-bridge.js +9 -9
  10. package/dist/adapter/deepseek-harness/bridge-installer.js +4 -4
  11. package/dist/adapter/deepseek-harness/profile-catalog.js +1 -1
  12. package/dist/adapter/pi/pi-adapter.js +4 -4
  13. package/dist/assets/dsh-bridge/grix-dsh-bridge-4.3.1.tgz +0 -0
  14. package/dist/assets/dsh-bridge/manifest.json +5 -5
  15. package/dist/bridge/respawn-manager.js +1 -1
  16. package/dist/bridge/send-controller.js +3 -3
  17. package/dist/core/access/allowlist-store.js +1 -1
  18. package/dist/core/file-ops/list-files.js +1 -1
  19. package/dist/core/hooks/hook-signal-store.js +2 -2
  20. package/dist/core/runtime/spawn.js +2 -2
  21. package/dist/core/util/cli-probe.js +2 -2
  22. package/dist/log.js +2 -2
  23. package/dist/mcp/stream-http/config.js +1 -1
  24. package/dist/mcp/stream-http/connection-binding.js +1 -1
  25. package/dist/mcp/stream-http/security.js +1 -1
  26. package/dist/mcp/stream-http/tool-executor.js +1 -1
  27. package/dist/mcp/stream-http/tool-registry.js +1 -1
  28. package/dist/mcp/stream-http/tool-schemas.js +1 -1
  29. package/package.json +1 -1
  30. package/dist/assets/dsh-bridge/grix-dsh-bridge-4.3.0.tgz +0 -0
@@ -1,7 +1,7 @@
1
- import{execFile as b}from"node:child_process";import{promisify as w}from"node:util";import{EventEmitter as I}from"node:events";import{stat as $}from"node:fs/promises";import{mkdirSync as T,writeFileSync as A,unlinkSync as k,statSync as f,readFileSync as R,existsSync as C}from"node:fs";import{join as m,resolve as M}from"node:path";import{fileURLToPath as F}from"node:url";import{tmpdir as B,homedir as g}from"node:os";import{resolveCommandPath as D,spawnCommand as N,killProcessGroup as E,hasChildProcesses as G}from"../../core/runtime/spawn.js";import{InternalApiServer as L}from"../../core/mcp/internal-api-server.js";import{IdentityInjector as O}from"../shared/identity-injector.js";import{compactToolInputForWire as j}from"../shared/tool-wire-payload.js";import{syncDefaultSkillsToDir as q}from"../../default-skills/index.js";import{PiTransport as U}from"./pi-transport.js";import{log as a}from"../../core/log/index.js";import{scanSkills as z}from"../claude/skill-scanner.js";import{SessionBindingStore as H}from"../../core/persistence/session-binding-store.js";import{splitTextForAibotProtocol as W}from"../../core/protocol/index.js";import{InboundMessageIdInjector as Y}from"../shared/inbound-message-id-injector.js";import{buildSimpleProbeReport as K}from"../shared/probe-util.js";import{piGrixProviderId as V,removePiGrixProvider as X,writePiGrixProvider as J}from"./pi-provider-config.js";const y=new Map;function Q(){const d=m(g(),".pi","agent","mcp.json");try{if(!C(d))return{};const e=JSON.parse(R(d,"utf8"))?.mcpServers;return!e||typeof e!="object"||Array.isArray(e)?{}:e}catch(t){return a.warn("pi-adapter",`Failed to read Pi user MCP config ${d}: ${t instanceof Error?t.message:String(t)}`),{}}}async function Z(d){const t=y.get(d);if(t!==void 0)return t;let e=!1;try{const s=w(b),i=process.platform==="win32",n=i&&/\s/.test(d)&&!d.startsWith('"')?`"${d}"`:d,{stdout:r,stderr:c}=await s(n,["--help"],{timeout:5e3,encoding:"utf-8",...i?{shell:!0}:{}});e=/--mcp-config\b/.test(`${r??""}${c??""}`)}catch{e=!1}return y.set(d,e),a.info("pi-adapter",`Pi --mcp-config \u652F\u6301\u63A2\u6D4B: ${e?"\u652F\u6301":"\u4E0D\u652F\u6301"} (${d})`),e}class tt extends I{adapterSessionId;constructor(t){super(),this.adapterSessionId=t}emitDone(t){this.emit("done",t)}emitError(t){if(this.listenerCount("error")===0){a.warn("pi-adapter",`Prompt handle error (no listeners): ${t.message}`);return}this.emit("error",t)}async cancel(){}}const et=12e4,st=90*1e3,x=1800*1e3;function _(d){try{return process.kill(d,0),!0}catch(t){return t.code==="EPERM"}}const it=500,nt=2e3,v=3,rt=500;function at(d){return new Promise(t=>setTimeout(t,d))}function u(d){if(d===void 0)return"undefined";if(d===null)return"null";if(typeof d=="string")return d.length>500?`${d.slice(0,500)}...`:d;try{const t=JSON.stringify(d);return t.length>500?`${t.slice(0,500)}...`:t}catch{return String(d)}}class P extends I{type="pi";config;callbacks;process=null;transport=new U;alive=!1;stopped=!1;internalApi=null;mcpConfigPath=null;identity;inboundMessageIds=new Y;piSessionPath=null;activeEventId=null;activeSessionId=null;activeAuditCapture=null;completedAuditBoundaries=new Map;isStreaming=!1;streamSeq=0;clientMsgSeq=0;activeClientMsgId=null;thinkingSeq=0;textBuffer="";emittedTextByIndex=new Map;textFlushTimer=null;activeRunError=null;runErrorEmitted=!1;idleTimer=null;lastRpcAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;composingSessionId=null;composingInterval=null;doneGuardTimer=null;bindingStore=null;aibotSessionId="";sessionReadyPromise=null;provider;agentName="";constructor(t,e){super(),this.config=t,this.callbacks=e,this.identity=new O("pi-adapter",e.getAgentProfile);const s=t.options??{};this.aibotSessionId=String(s.aibotSessionId??"").trim(),this.agentName=String(s.agentName??"").trim(),this.provider=s.provider,this.bindingStore=s.bindingStore instanceof H?s.bindingStore:null,this.bindingStore&&this.aibotSessionId&&(this.piSessionPath=this.bindingStore.getPiSessionPath(this.aibotSessionId)??null)}async start(){await this.startInternalApi(),await this.spawnPi(),await this.ensureSessionReady(),a.info("pi-adapter",`Ready (pid=${this.process?.pid})`),await this.syncModelBinding()}async syncModelBinding(){if(this.aibotSessionId)for(let t=1;t<=v;t++)try{const[e,s]=await Promise.all([this.transport.send("get_available_models"),this.transport.send("get_state")]),i=e.data?.models;if(!i||i.length===0){if(t<v){await at(rt);continue}a.warn("pi-adapter",`syncModelBinding: empty model list after ${v} attempts, giving up`);return}const n=s.data?.model,r={available_models:i.map(c=>({id:c.id,display_name:c.name??c.id,...c.provider?{provider:c.provider}:{}}))};n?.id&&(r.model_id=n.id),n?.provider&&(r.model_provider=n.provider),this.callbacks.sendUpdateBindingCard(this.aibotSessionId,this.isStreaming?"composing":"ready",this.resolveCwd(),r),a.info("pi-adapter",`synced model binding: ${i.length} models, current=${n?.id??"unknown"} (attempt ${t})`);return}catch(e){a.warn("pi-adapter",`syncModelBinding failed (non-fatal): ${e instanceof Error?e.message:String(e)}`);return}}async stop(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.cancelDoneGuard(),this.transport.close(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.mcpConfigPath){try{k(this.mcpConfigPath)}catch{}this.mcpConfigPath=null}if(this.process){const t=this.process;try{E(t,"SIGTERM")}catch{}const e=setTimeout(()=>{try{E(t,"SIGKILL")}catch{}},5e3);t.on("exit",()=>clearTimeout(e)),this.process=null}}isAlive(){return this.alive}async createSession(t){this.sessionReadyPromise=null,await this.createNewSession();const e=this.piSessionPath||`pi-${Date.now()}`;return a.info("pi-adapter",`Session created: ${e} (path=${this.piSessionPath})`),e}async resumeSession(t,e){await this.switchSession()}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(t){this.identity.forgetSession(t),this.inboundMessageIds.forgetSession(t),this.piSessionPath=null,this.sessionReadyPromise=null,this.persistPiSessionPath(void 0)}sendPrompt(t){const e=new tt(t.adapterSessionId),s=this.buildPromptTextFromRequest(t);return this.ensureSessionReady().then(()=>this.transport.send("prompt",{message:s})).then(i=>{i.success||e.emitDone({status:"failed",error:i.error})}).catch(i=>{e.emitError(i instanceof Error?i:new Error(String(i)))}),e}async cancel(t){try{await this.transport.send("abort")}catch{}}deliverInboundEvent(t){const{event_id:e,session_id:s,content:i}=t,n=this.buildPromptText(t);if(this.isStreaming){if(this.activeEventId&&this.activeEventId!==e){const r=this.activeEventId;a.info("pi-adapter",`steer: cancel ${r} -> ${e}`),this.flushTextBuffer(),this.callbacks.sendEventResult(r,"canceled","steered to new event"),this.activeAuditCapture?.eventId===r&&(this.snapshotAuditBoundary(r),this.emit("eventDone",r))}this.activeEventId=e,this.activeSessionId=s,this.beginAuditCapture(t),this.resetRunStreamState(),this.startComposing(s,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n,streamingBehavior:"steer"}).catch(r=>{a.error("pi-adapter",`steer failed: ${r}`),this.callbacks.sendEventResult(e,"failed",String(r))})}else a.info("pi-adapter",`prompt: event=${e} session=${s}`),this.activeEventId=e,this.activeSessionId=s,this.beginAuditCapture(t),this.isStreaming=!0,this.resetRunStreamState(),this.startComposing(s,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n}).then(r=>{r.success||(a.error("pi-adapter",`prompt rejected: ${r.error}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",r.error),this.clearActive())}).catch(r=>{a.error("pi-adapter",`prompt error: ${r}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",String(r)),this.clearActive()})}deliverStopEvent(t,e){if(this.activeEventId===t){a.info("pi-adapter",`stop: event=${t}, releasing busy immediately`),this.transport.send("abort").catch(()=>{}),this.flushTextBuffer();const s=this.nextStreamSeq(),i=this.activeClientMsgId??void 0;this.callbacks.sendStreamChunk(t,this.activeSessionId??"","",s,!0,i),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(t,"canceled","stopped by user"),this.clearActive()}}async handleLocalAction(t){const e=t.action_id;switch(t.action_type){case"set_model":{const s=t.params??{},i=(s.modelId??s.model_id??"").trim();if(!i)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_model","model_id is required"),{handled:!0,kind:"set_model_error"};try{let n=s.provider?.trim();return n||(n=(await this.transport.send("get_available_models")).data?.models?.find(l=>l.id===i)?.provider?.trim()),n?(await this.transport.send("set_model",{provider:n,modelId:i}),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"model_set",provider:n,modelId:i}),this.syncModelBinding(),{handled:!0,kind:"set_model"}):(this.callbacks.sendLocalActionResult(e,"failed",void 0,"model_not_found",`No provider for model: ${i}`),{handled:!0,kind:"set_model_error"})}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_model_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_model_error"}}}case"get_context":try{const s=await this.transport.send("get_state");return this.callbacks.sendLocalActionResult(e,"ok",{state:s}),{handled:!0,kind:"get_context"}}catch(s){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"get_context_error",s instanceof Error?s.message:String(s)),{handled:!1,kind:""}}case"pi_extension_ui_response":return this.transport.sendNoWait({type:"extension_ui_response",...t.params??{}}),this.callbacks.sendLocalActionResult(e,"ok"),{handled:!0,kind:"extension_ui_response"};default:return{handled:!1,kind:""}}}setPermissionHandler(t){}async ping(t){try{return await this.transport.send("get_state"),!0}catch{return!1}}getStatus(){return{alive:this.alive,busy:this.isStreaming,sessions:this.piSessionPath?1:0}}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}takeAuditBoundary(t){const e=this.completedAuditBoundaries.get(t);return e&&this.completedAuditBoundaries.delete(t),e}clearActiveEventForShutdown(){this.stopIdleTimer(),this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.activeEventId=null}getMcpConfig(){if(!this.internalApi)return null;const t=M(F(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[t,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const t=this.process?.pid;return t?G(t,[t]):!1}async probe(t){const e=this.getStatus();return{...await K(this.config.command||"pi",{alive:e.alive,busy:e.busy,started:!!this.process},t),session:this.probeSessionRecord()}}probeSessionRecord(){const t=this.piSessionPath;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const e=f(t);return{recordPath:t,lastActivityMs:e.mtimeMs,freshMs:Date.now()-e.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}getSupportedCommands(){return[{name:"model",description:"List or set model",args:"[provider:model_id]"},{name:"interrupt",description:"Interrupt current run"},{name:"status",description:"Show session status"},{name:"skills",description:"List available skills"}]}async execCommand(t,e,s){try{if(!this.alive)return{status:"failed",message:"Pi process not running"};switch(t){case"model":{const i=e.trim();if(i){const c=i.indexOf(":");if(c<1)return{status:"failed",message:"Format: provider:model_id"};const l=i.slice(0,c),h=i.slice(c+1);if(!h)return{status:"failed",message:"Format: provider:model_id"};const p=await this.transport.send("set_model",{provider:l,modelId:h});return p?.success?{status:"ok",message:`Model set to ${l}:${h}`}:{status:"failed",message:`Failed to set model: ${p?.error??"unknown error"}`}}const r=(await this.transport.send("get_available_models"))?.data?.models;return r&&r.length>0?{status:"ok",message:`Available models:
1
+ import{execFile as P}from"node:child_process";import{promisify as b}from"node:util";import{EventEmitter as I}from"node:events";import{stat as $}from"node:fs/promises";import{mkdirSync as T,writeFileSync as A,unlinkSync as k,statSync as f,readFileSync as R,existsSync as C}from"node:fs";import{join as m,resolve as M}from"node:path";import{fileURLToPath as F}from"node:url";import{tmpdir as B,homedir as g}from"node:os";import{resolveCommandPath as D,resolveWindowsExecInvocation as N,spawnCommand as G,killProcessGroup as E,hasChildProcesses as L}from"../../core/runtime/spawn.js";import{InternalApiServer as O}from"../../core/mcp/internal-api-server.js";import{IdentityInjector as j}from"../shared/identity-injector.js";import{compactToolInputForWire as q}from"../shared/tool-wire-payload.js";import{syncDefaultSkillsToDir as U}from"../../default-skills/index.js";import{PiTransport as z}from"./pi-transport.js";import{log as o}from"../../core/log/index.js";import{scanSkills as V}from"../claude/skill-scanner.js";import{SessionBindingStore as H}from"../../core/persistence/session-binding-store.js";import{splitTextForAibotProtocol as Y}from"../../core/protocol/index.js";import{InboundMessageIdInjector as K}from"../shared/inbound-message-id-injector.js";import{buildSimpleProbeReport as W}from"../shared/probe-util.js";import{piGrixProviderId as X,removePiGrixProvider as J,writePiGrixProvider as Q}from"./pi-provider-config.js";const y=new Map;function Z(){const c=m(g(),".pi","agent","mcp.json");try{if(!C(c))return{};const e=JSON.parse(R(c,"utf8"))?.mcpServers;return!e||typeof e!="object"||Array.isArray(e)?{}:e}catch(t){return o.warn("pi-adapter",`Failed to read Pi user MCP config ${c}: ${t instanceof Error?t.message:String(t)}`),{}}}async function tt(c){const t=y.get(c);if(t!==void 0)return t;let e=!1;try{const s=b(P),i=N(c,["--help"]),{stdout:n,stderr:r}=await s(i.command,i.args,{timeout:5e3,encoding:"utf-8",windowsVerbatimArguments:i.windowsVerbatimArguments});e=/--mcp-config\b/.test(`${n??""}${r??""}`)}catch{e=!1}return y.set(c,e),o.info("pi-adapter",`Pi --mcp-config \u652F\u6301\u63A2\u6D4B: ${e?"\u652F\u6301":"\u4E0D\u652F\u6301"} (${c})`),e}class et extends I{adapterSessionId;constructor(t){super(),this.adapterSessionId=t}emitDone(t){this.emit("done",t)}emitError(t){if(this.listenerCount("error")===0){o.warn("pi-adapter",`Prompt handle error (no listeners): ${t.message}`);return}this.emit("error",t)}async cancel(){}}const st=12e4,it=90*1e3,x=1800*1e3;function _(c){try{return process.kill(c,0),!0}catch(t){return t.code==="EPERM"}}const nt=500,rt=2e3,v=3,ot=500;function at(c){return new Promise(t=>setTimeout(t,c))}function u(c){if(c===void 0)return"undefined";if(c===null)return"null";if(typeof c=="string")return c.length>500?`${c.slice(0,500)}...`:c;try{const t=JSON.stringify(c);return t.length>500?`${t.slice(0,500)}...`:t}catch{return String(c)}}class w extends I{type="pi";config;callbacks;process=null;transport=new z;alive=!1;stopped=!1;internalApi=null;mcpConfigPath=null;identity;inboundMessageIds=new K;piSessionPath=null;activeEventId=null;activeSessionId=null;activeAuditCapture=null;completedAuditBoundaries=new Map;isStreaming=!1;streamSeq=0;clientMsgSeq=0;activeClientMsgId=null;thinkingSeq=0;textBuffer="";emittedTextByIndex=new Map;textFlushTimer=null;activeRunError=null;runErrorEmitted=!1;idleTimer=null;lastRpcAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;composingSessionId=null;composingInterval=null;doneGuardTimer=null;bindingStore=null;aibotSessionId="";sessionReadyPromise=null;provider;agentName="";constructor(t,e){super(),this.config=t,this.callbacks=e,this.identity=new j("pi-adapter",e.getAgentProfile);const s=t.options??{};this.aibotSessionId=String(s.aibotSessionId??"").trim(),this.agentName=String(s.agentName??"").trim(),this.provider=s.provider,this.bindingStore=s.bindingStore instanceof H?s.bindingStore:null,this.bindingStore&&this.aibotSessionId&&(this.piSessionPath=this.bindingStore.getPiSessionPath(this.aibotSessionId)??null)}async start(){await this.startInternalApi(),await this.spawnPi(),await this.ensureSessionReady(),o.info("pi-adapter",`Ready (pid=${this.process?.pid})`),await this.syncModelBinding()}async syncModelBinding(){if(this.aibotSessionId)for(let t=1;t<=v;t++)try{const[e,s]=await Promise.all([this.transport.send("get_available_models"),this.transport.send("get_state")]),i=e.data?.models;if(!i||i.length===0){if(t<v){await at(ot);continue}o.warn("pi-adapter",`syncModelBinding: empty model list after ${v} attempts, giving up`);return}const n=s.data?.model,r={available_models:i.map(d=>({id:d.id,display_name:d.name??d.id,...d.provider?{provider:d.provider}:{}}))};n?.id&&(r.model_id=n.id),n?.provider&&(r.model_provider=n.provider),this.callbacks.sendUpdateBindingCard(this.aibotSessionId,this.isStreaming?"composing":"ready",this.resolveCwd(),r),o.info("pi-adapter",`synced model binding: ${i.length} models, current=${n?.id??"unknown"} (attempt ${t})`);return}catch(e){o.warn("pi-adapter",`syncModelBinding failed (non-fatal): ${e instanceof Error?e.message:String(e)}`);return}}async stop(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.cancelDoneGuard(),this.transport.close(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.mcpConfigPath){try{k(this.mcpConfigPath)}catch{}this.mcpConfigPath=null}if(this.process){const t=this.process;try{E(t,"SIGTERM")}catch{}const e=setTimeout(()=>{try{E(t,"SIGKILL")}catch{}},5e3);t.on("exit",()=>clearTimeout(e)),this.process=null}}isAlive(){return this.alive}async createSession(t){this.sessionReadyPromise=null,await this.createNewSession();const e=this.piSessionPath||`pi-${Date.now()}`;return o.info("pi-adapter",`Session created: ${e} (path=${this.piSessionPath})`),e}async resumeSession(t,e){await this.switchSession()}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(t){this.identity.forgetSession(t),this.inboundMessageIds.forgetSession(t),this.piSessionPath=null,this.sessionReadyPromise=null,this.persistPiSessionPath(void 0)}sendPrompt(t){const e=new et(t.adapterSessionId),s=this.buildPromptTextFromRequest(t);return this.ensureSessionReady().then(()=>this.transport.send("prompt",{message:s})).then(i=>{i.success||e.emitDone({status:"failed",error:i.error})}).catch(i=>{e.emitError(i instanceof Error?i:new Error(String(i)))}),e}async cancel(t){try{await this.transport.send("abort")}catch{}}deliverInboundEvent(t){const{event_id:e,session_id:s,content:i}=t,n=this.buildPromptText(t);if(this.isStreaming){if(this.activeEventId&&this.activeEventId!==e){const r=this.activeEventId;o.info("pi-adapter",`steer: cancel ${r} -> ${e}`),this.flushTextBuffer(),this.callbacks.sendEventResult(r,"canceled","steered to new event"),this.activeAuditCapture?.eventId===r&&(this.snapshotAuditBoundary(r),this.emit("eventDone",r))}this.activeEventId=e,this.activeSessionId=s,this.beginAuditCapture(t),this.resetRunStreamState(),this.startComposing(s,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n,streamingBehavior:"steer"}).catch(r=>{o.error("pi-adapter",`steer failed: ${r}`),this.callbacks.sendEventResult(e,"failed",String(r))})}else o.info("pi-adapter",`prompt: event=${e} session=${s}`),this.activeEventId=e,this.activeSessionId=s,this.beginAuditCapture(t),this.isStreaming=!0,this.resetRunStreamState(),this.startComposing(s,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n}).then(r=>{r.success||(o.error("pi-adapter",`prompt rejected: ${r.error}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",r.error),this.clearActive())}).catch(r=>{o.error("pi-adapter",`prompt error: ${r}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",String(r)),this.clearActive()})}deliverStopEvent(t,e){if(this.activeEventId===t){o.info("pi-adapter",`stop: event=${t}, releasing busy immediately`),this.transport.send("abort").catch(()=>{}),this.flushTextBuffer();const s=this.nextStreamSeq(),i=this.activeClientMsgId??void 0;this.callbacks.sendStreamChunk(t,this.activeSessionId??"","",s,!0,i),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(t,"canceled","stopped by user"),this.clearActive()}}async handleLocalAction(t){const e=t.action_id;switch(t.action_type){case"set_model":{const s=t.params??{},i=(s.modelId??s.model_id??"").trim();if(!i)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_model","model_id is required"),{handled:!0,kind:"set_model_error"};try{let n=s.provider?.trim();return n||(n=(await this.transport.send("get_available_models")).data?.models?.find(l=>l.id===i)?.provider?.trim()),n?(await this.transport.send("set_model",{provider:n,modelId:i}),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"model_set",provider:n,modelId:i}),this.syncModelBinding(),{handled:!0,kind:"set_model"}):(this.callbacks.sendLocalActionResult(e,"failed",void 0,"model_not_found",`No provider for model: ${i}`),{handled:!0,kind:"set_model_error"})}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_model_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_model_error"}}}case"get_context":try{const s=await this.transport.send("get_state");return this.callbacks.sendLocalActionResult(e,"ok",{state:s}),{handled:!0,kind:"get_context"}}catch(s){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"get_context_error",s instanceof Error?s.message:String(s)),{handled:!1,kind:""}}case"pi_extension_ui_response":return this.transport.sendNoWait({type:"extension_ui_response",...t.params??{}}),this.callbacks.sendLocalActionResult(e,"ok"),{handled:!0,kind:"extension_ui_response"};default:return{handled:!1,kind:""}}}setPermissionHandler(t){}async ping(t){try{return await this.transport.send("get_state"),!0}catch{return!1}}getStatus(){return{alive:this.alive,busy:this.isStreaming,sessions:this.piSessionPath?1:0}}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}takeAuditBoundary(t){const e=this.completedAuditBoundaries.get(t);return e&&this.completedAuditBoundaries.delete(t),e}clearActiveEventForShutdown(){this.stopIdleTimer(),this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.activeEventId=null}getMcpConfig(){if(!this.internalApi)return null;const t=M(F(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[t,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const t=this.process?.pid;return t?L(t,[t]):!1}async probe(t){const e=this.getStatus();return{...await W(this.config.command||"pi",{alive:e.alive,busy:e.busy,started:!!this.process},t),session:this.probeSessionRecord()}}probeSessionRecord(){const t=this.piSessionPath;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const e=f(t);return{recordPath:t,lastActivityMs:e.mtimeMs,freshMs:Date.now()-e.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}getSupportedCommands(){return[{name:"model",description:"List or set model",args:"[provider:model_id]"},{name:"interrupt",description:"Interrupt current run"},{name:"status",description:"Show session status"},{name:"skills",description:"List available skills"}]}async execCommand(t,e,s){try{if(!this.alive)return{status:"failed",message:"Pi process not running"};switch(t){case"model":{const i=e.trim();if(i){const d=i.indexOf(":");if(d<1)return{status:"failed",message:"Format: provider:model_id"};const l=i.slice(0,d),h=i.slice(d+1);if(!h)return{status:"failed",message:"Format: provider:model_id"};const p=await this.transport.send("set_model",{provider:l,modelId:h});return p?.success?{status:"ok",message:`Model set to ${l}:${h}`}:{status:"failed",message:`Failed to set model: ${p?.error??"unknown error"}`}}const r=(await this.transport.send("get_available_models"))?.data?.models;return r&&r.length>0?{status:"ok",message:`Available models:
2
2
  ${r.map(l=>` ${l.provider??"unknown"}:${l.id} (${l.name??l.id})`).join(`
3
- `)}`,data:r}:{status:"ok",message:"No models available",data:[]}}case"interrupt":return this.isStreaming?(await this.transport.send("abort"),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","interrupted"),this.clearActive(),{status:"ok",message:"Run interrupted"}):{status:"failed",message:"No active run to interrupt"};case"status":{const i=this.getStatus();return{status:"ok",message:`Alive: ${i.alive}, Busy: ${i.busy}, Session: ${this.piSessionPath??"none"}`,data:{alive:i.alive,busy:i.busy,sessions:i.sessions,sessionPath:this.piSessionPath}}}case"skills":{const i=z({mode:"pi"}),n=i.map(r=>`- ${r.name}${r.trigger?` (${r.trigger})`:""} [${r.source}]: ${r.description}`);return{status:"ok",message:n.length>0?n.join(`
4
- `):"No skills found",data:i}}default:return{status:"unsupported",message:`Unknown command: ${t}`}}}catch(i){return{status:"failed",message:i instanceof Error?i.message:String(i)}}}resolveCwd(){if(this.bindingStore&&this.aibotSessionId){const e=this.bindingStore.get(this.aibotSessionId);if(e?.cwd)return e.cwd}const t=(this.config.options??{}).cwd;return typeof t=="string"&&t?t:process.cwd()}async startInternalApi(){try{this.internalApi=new L,this.internalApi.setInvokeHandler(async(r,c,l,h)=>this.callbacks.agentInvoke(r,c,h)),await this.internalApi.start(0),a.info("pi-adapter",`Internal API started at ${this.internalApi.url}`);const t=this.getMcpConfig(),e=Q(),s=m(B(),"grix-pi-mcp");T(s,{recursive:!0}),this.mcpConfigPath=m(s,`mcp-${process.pid}-${Date.now()}.json`),A(this.mcpConfigPath,JSON.stringify({mcpServers:{...e,[t.name]:{command:t.command,args:t.args,directTools:!0,lifecycle:"eager"}}}),"utf8"),a.info("pi-adapter",`MCP config written to ${this.mcpConfigPath}`);const i=m(g(),".pi","agent","skills"),n=q(i);n.length>0&&a.info("pi-adapter",`Synced connector skills to ${i}: [${n.join(", ")}]`)}catch(t){a.warn("pi-adapter",`Failed to start MCP tools (non-fatal): ${t instanceof Error?t.message:String(t)}`)}}async spawnPi(){const t=this.config.command||"pi",e=D(t,typeof process.env.PATH=="string"?process.env.PATH:void 0),s=this.config.args??[],n=s.some(o=>o.startsWith("--mode"))?[...s]:["--mode","rpc",...s],r=String(this.config.env?.PI_CODING_AGENT_DIR??"").trim()||m(g(),".pi","agent"),c=V(this.agentName);this.provider?await J(r,c,this.provider)?(n.includes("--provider")||n.push("--provider",c),!n.includes("--model")&&this.provider.model?.trim()&&n.push("--model",this.provider.model.trim())):a.warn("pi-adapter","provider config incomplete (baseUrl/model required); Grix provider not applied"):await X(r,c).then(o=>{o&&a.info("pi-adapter",`Removed stale Grix provider "${c}" from models.json`)}).catch(o=>{a.warn("pi-adapter",`Failed to clean up Grix provider config: ${o instanceof Error?o.message:String(o)}`)}),this.mcpConfigPath&&!n.some(o=>o==="--mcp-config")&&(await Z(e)?n.push("--mcp-config",this.mcpConfigPath):a.warn("pi-adapter","\u5F53\u524D Pi \u4E0D\u652F\u6301 --mcp-config\uFF08\u672A\u68C0\u6D4B\u5230 pi-mcp-adapter \u6269\u5C55\uFF09\uFF0C\u8DF3\u8FC7 MCP \u6CE8\u5165\u4EE5\u907F\u514D\u542F\u52A8\u5931\u8D25"));const l={...process.env,...this.config.env},h=this.provider?.apiKey?.trim();h&&!l.GRIX_PROVIDER_API_KEY?.trim()&&(l.GRIX_PROVIDER_API_KEY=h);const p=this.resolveCwd();a.info("pi-adapter",`Spawning: ${e} ${n.join(" ")}`);try{if(!(await $(p)).isDirectory())throw new Error(`Bound path is not a directory: ${p}`)}catch(o){throw String(o?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${p}. Please rebind with /grix open <valid-directory>.`):o}try{this.process=N(e,n,{env:l,cwd:p}).process}catch(o){throw a.error("pi-adapter",`PI spawn threw: ${o}`),this.alive=!1,o}this.process.on("error",o=>{a.error("pi-adapter",`Spawn error: ${o.message}`),this.alive=!1,this.transport.close(),this.activeEventId&&(this.callbacks.sendEventResult(this.activeEventId,"failed",`Spawn error: ${o.message}`),this.clearActive()),this.stopped||this.emit("exit",1)}),this.process.on("exit",o=>{a.info("pi-adapter",`PI process exited (code=${o})`),this.alive=!1,this.transport.close(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"failed",`PI process exited (code=${o})`),this.isStreaming=!1,this.clearActive(),this.stopped||this.emit("exit",o??1)}),this.process.stderr?.on("data",o=>{const S=o.toString().trim();S&&a.info("pi-adapter",`[pi stderr] ${S}`)}),this.transport.on("event",o=>this.handlePiEvent(o)),this.transport.bind(this.process.stdin,this.process.stdout),this.alive=!0}handlePiEvent(t){if(this.stopped)return;if(this.lastRpcAt=Date.now(),t.type==="tool_execution_start"){const s=t;s.toolCallId&&this.toolCallsInFlight.add(s.toolCallId)}else if(t.type==="tool_execution_end"){const s=t;s.toolCallId&&this.toolCallsInFlight.delete(s.toolCallId)}switch(this.resetIdleTimer(),t.type){case"message_update":{const s=t.assistantMessageEvent;if(!s)break;const i=s.type;if(i==="text_delta"){const n=s.delta;if(n){const r=typeof s.contentIndex=="number"?s.contentIndex:0;this.rememberEmittedText(r,n),this.appendText(n)}}else if(i==="text_end"){const n=s.content,r=typeof s.contentIndex=="number"?s.contentIndex:0;n&&this.appendMissingText(r,n)}else if(i==="thinking_delta"){const n=s.delta;n&&this.activeEventId&&this.activeSessionId&&(this.thinkingSeq++,this.callbacks.sendThinking(this.activeEventId,this.activeSessionId,n))}else if(i==="done"||i==="error"){if(this.flushTextBuffer(),i==="error"){const n=this.piMessageError(s.error,s.reason);a.warn("pi-adapter",`terminal message_update error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${u(s.error)} reason=${u(s.reason)}`),this.recordRunError(n)}this.scheduleDoneGuard()}break}case"message_end":{const s=t.message;s?.role==="assistant"&&s.stopReason==="error"&&(a.warn("pi-adapter",`terminal message_end error event=${this.activeEventId} sessionId=${this.activeSessionId} errorMessage=${u(s.errorMessage)} message=${u(s)}`),this.recordRunError(this.piMessageError(s,s.errorMessage)),this.scheduleDoneGuard());break}case"tool_execution_start":{if(this.cancelDoneGuard(),this.flushTextBuffer(),!this.activeEventId||!this.activeSessionId)break;const s=t;if(s.toolName){const i=j(s.args);this.callbacks.sendToolUse(this.activeEventId,this.activeSessionId,s.toolName,i)}break}case"tool_execution_end":{if(!this.activeEventId||!this.activeSessionId)break;const s=t;s.isError&&this.callbacks.sendToolResult(this.activeEventId,this.activeSessionId,s.toolName,"(failed)");break}case"agent_end":{if(a.info("pi-adapter",`agent_end event=${this.activeEventId} sessionId=${this.activeSessionId}`),this.cancelDoneGuard(),t.willRetry===!0&&this.activeEventId){a.info("pi-adapter",`agent_end willRetry=true \u2014 holding event=${this.activeEventId} for auto-retry`),this.activeRunError=null,this.emittedTextByIndex.clear(),this.resetIdleTimer();break}this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.completeActiveEvent();break}case"agent_start":{this.cancelDoneGuard(),this.activeEventId&&(a.info("pi-adapter",`agent_start event=${this.activeEventId}`),this.isStreaming=!0);break}default:break}}appendText(t){if(this.textBuffer+=t,this.textBuffer.length>=nt){this.flushTextBuffer();return}this.scheduleTextFlush()}scheduleTextFlush(){this.textFlushTimer||(this.textFlushTimer=setTimeout(()=>{this.textFlushTimer=null,this.flushTextBuffer()},it))}flushTextBuffer(){this.stopTextFlush(),!(!this.textBuffer||!this.activeEventId||!this.activeSessionId)&&(this.sendTextChunks(this.textBuffer),this.textBuffer="")}sendTextChunks(t){if(!(!this.activeEventId||!this.activeSessionId))for(const e of W(t))this.callbacks.sendStreamChunk(this.activeEventId,this.activeSessionId,e,this.nextStreamSeq(),!1,this.activeClientMsgId??void 0)}stopTextFlush(){this.textFlushTimer&&(clearTimeout(this.textFlushTimer),this.textFlushTimer=null)}buildPromptText(t){let e=t.content||"";if(t.context_messages_json)try{const i=JSON.parse(t.context_messages_json);if(Array.isArray(i)&&i.length>0){const n=i.map(r=>`[context] ${r.sender_id??"unknown"}: ${r.content}`).join(`
3
+ `)}`,data:r}:{status:"ok",message:"No models available",data:[]}}case"interrupt":return this.isStreaming?(await this.transport.send("abort"),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","interrupted"),this.clearActive(),{status:"ok",message:"Run interrupted"}):{status:"failed",message:"No active run to interrupt"};case"status":{const i=this.getStatus();return{status:"ok",message:`Alive: ${i.alive}, Busy: ${i.busy}, Session: ${this.piSessionPath??"none"}`,data:{alive:i.alive,busy:i.busy,sessions:i.sessions,sessionPath:this.piSessionPath}}}case"skills":{const i=V({mode:"pi"}),n=i.map(r=>`- ${r.name}${r.trigger?` (${r.trigger})`:""} [${r.source}]: ${r.description}`);return{status:"ok",message:n.length>0?n.join(`
4
+ `):"No skills found",data:i}}default:return{status:"unsupported",message:`Unknown command: ${t}`}}}catch(i){return{status:"failed",message:i instanceof Error?i.message:String(i)}}}resolveCwd(){if(this.bindingStore&&this.aibotSessionId){const e=this.bindingStore.get(this.aibotSessionId);if(e?.cwd)return e.cwd}const t=(this.config.options??{}).cwd;return typeof t=="string"&&t?t:process.cwd()}async startInternalApi(){try{this.internalApi=new O,this.internalApi.setInvokeHandler(async(r,d,l,h)=>this.callbacks.agentInvoke(r,d,h)),await this.internalApi.start(0),o.info("pi-adapter",`Internal API started at ${this.internalApi.url}`);const t=this.getMcpConfig(),e=Z(),s=m(B(),"grix-pi-mcp");T(s,{recursive:!0}),this.mcpConfigPath=m(s,`mcp-${process.pid}-${Date.now()}.json`),A(this.mcpConfigPath,JSON.stringify({mcpServers:{...e,[t.name]:{command:t.command,args:t.args,directTools:!0,lifecycle:"eager"}}}),"utf8"),o.info("pi-adapter",`MCP config written to ${this.mcpConfigPath}`);const i=m(g(),".pi","agent","skills"),n=U(i);n.length>0&&o.info("pi-adapter",`Synced connector skills to ${i}: [${n.join(", ")}]`)}catch(t){o.warn("pi-adapter",`Failed to start MCP tools (non-fatal): ${t instanceof Error?t.message:String(t)}`)}}async spawnPi(){const t=this.config.command||"pi",e=D(t,typeof process.env.PATH=="string"?process.env.PATH:void 0),s=this.config.args??[],n=s.some(a=>a.startsWith("--mode"))?[...s]:["--mode","rpc",...s],r=String(this.config.env?.PI_CODING_AGENT_DIR??"").trim()||m(g(),".pi","agent"),d=X(this.agentName);this.provider?await Q(r,d,this.provider)?(n.includes("--provider")||n.push("--provider",d),!n.includes("--model")&&this.provider.model?.trim()&&n.push("--model",this.provider.model.trim())):o.warn("pi-adapter","provider config incomplete (baseUrl/model required); Grix provider not applied"):await J(r,d).then(a=>{a&&o.info("pi-adapter",`Removed stale Grix provider "${d}" from models.json`)}).catch(a=>{o.warn("pi-adapter",`Failed to clean up Grix provider config: ${a instanceof Error?a.message:String(a)}`)}),this.mcpConfigPath&&!n.some(a=>a==="--mcp-config")&&(await tt(e)?n.push("--mcp-config",this.mcpConfigPath):o.warn("pi-adapter","\u5F53\u524D Pi \u4E0D\u652F\u6301 --mcp-config\uFF08\u672A\u68C0\u6D4B\u5230 pi-mcp-adapter \u6269\u5C55\uFF09\uFF0C\u8DF3\u8FC7 MCP \u6CE8\u5165\u4EE5\u907F\u514D\u542F\u52A8\u5931\u8D25"));const l={...process.env,...this.config.env},h=this.provider?.apiKey?.trim();h&&!l.GRIX_PROVIDER_API_KEY?.trim()&&(l.GRIX_PROVIDER_API_KEY=h);const p=this.resolveCwd();o.info("pi-adapter",`Spawning: ${e} ${n.join(" ")}`);try{if(!(await $(p)).isDirectory())throw new Error(`Bound path is not a directory: ${p}`)}catch(a){throw String(a?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${p}. Please rebind with /grix open <valid-directory>.`):a}try{this.process=G(e,n,{env:l,cwd:p}).process}catch(a){throw o.error("pi-adapter",`PI spawn threw: ${a}`),this.alive=!1,a}this.process.on("error",a=>{o.error("pi-adapter",`Spawn error: ${a.message}`),this.alive=!1,this.transport.close(),this.activeEventId&&(this.callbacks.sendEventResult(this.activeEventId,"failed",`Spawn error: ${a.message}`),this.clearActive()),this.stopped||this.emit("exit",1)}),this.process.on("exit",a=>{o.info("pi-adapter",`PI process exited (code=${a})`),this.alive=!1,this.transport.close(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"failed",`PI process exited (code=${a})`),this.isStreaming=!1,this.clearActive(),this.stopped||this.emit("exit",a??1)}),this.process.stderr?.on("data",a=>{const S=a.toString().trim();S&&o.info("pi-adapter",`[pi stderr] ${S}`)}),this.transport.on("event",a=>this.handlePiEvent(a)),this.transport.bind(this.process.stdin,this.process.stdout),this.alive=!0}handlePiEvent(t){if(this.stopped)return;if(this.lastRpcAt=Date.now(),t.type==="tool_execution_start"){const s=t;s.toolCallId&&this.toolCallsInFlight.add(s.toolCallId)}else if(t.type==="tool_execution_end"){const s=t;s.toolCallId&&this.toolCallsInFlight.delete(s.toolCallId)}switch(this.resetIdleTimer(),t.type){case"message_update":{const s=t.assistantMessageEvent;if(!s)break;const i=s.type;if(i==="text_delta"){const n=s.delta;if(n){const r=typeof s.contentIndex=="number"?s.contentIndex:0;this.rememberEmittedText(r,n),this.appendText(n)}}else if(i==="text_end"){const n=s.content,r=typeof s.contentIndex=="number"?s.contentIndex:0;n&&this.appendMissingText(r,n)}else if(i==="thinking_delta"){const n=s.delta;n&&this.activeEventId&&this.activeSessionId&&(this.thinkingSeq++,this.callbacks.sendThinking(this.activeEventId,this.activeSessionId,n))}else if(i==="done"||i==="error"){if(this.flushTextBuffer(),i==="error"){const n=this.piMessageError(s.error,s.reason);o.warn("pi-adapter",`terminal message_update error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${u(s.error)} reason=${u(s.reason)}`),this.recordRunError(n)}this.scheduleDoneGuard()}break}case"message_end":{const s=t.message;s?.role==="assistant"&&s.stopReason==="error"&&(o.warn("pi-adapter",`terminal message_end error event=${this.activeEventId} sessionId=${this.activeSessionId} errorMessage=${u(s.errorMessage)} message=${u(s)}`),this.recordRunError(this.piMessageError(s,s.errorMessage)),this.scheduleDoneGuard());break}case"tool_execution_start":{if(this.cancelDoneGuard(),this.flushTextBuffer(),!this.activeEventId||!this.activeSessionId)break;const s=t;if(s.toolName){const i=q(s.args);this.callbacks.sendToolUse(this.activeEventId,this.activeSessionId,s.toolName,i)}break}case"tool_execution_end":{if(!this.activeEventId||!this.activeSessionId)break;const s=t;s.isError&&this.callbacks.sendToolResult(this.activeEventId,this.activeSessionId,s.toolName,"(failed)");break}case"agent_end":{if(o.info("pi-adapter",`agent_end event=${this.activeEventId} sessionId=${this.activeSessionId}`),this.cancelDoneGuard(),t.willRetry===!0&&this.activeEventId){o.info("pi-adapter",`agent_end willRetry=true \u2014 holding event=${this.activeEventId} for auto-retry`),this.activeRunError=null,this.emittedTextByIndex.clear(),this.resetIdleTimer();break}this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.completeActiveEvent();break}case"agent_start":{this.cancelDoneGuard(),this.activeEventId&&(o.info("pi-adapter",`agent_start event=${this.activeEventId}`),this.isStreaming=!0);break}default:break}}appendText(t){if(this.textBuffer+=t,this.textBuffer.length>=rt){this.flushTextBuffer();return}this.scheduleTextFlush()}scheduleTextFlush(){this.textFlushTimer||(this.textFlushTimer=setTimeout(()=>{this.textFlushTimer=null,this.flushTextBuffer()},nt))}flushTextBuffer(){this.stopTextFlush(),!(!this.textBuffer||!this.activeEventId||!this.activeSessionId)&&(this.sendTextChunks(this.textBuffer),this.textBuffer="")}sendTextChunks(t){if(!(!this.activeEventId||!this.activeSessionId))for(const e of Y(t))this.callbacks.sendStreamChunk(this.activeEventId,this.activeSessionId,e,this.nextStreamSeq(),!1,this.activeClientMsgId??void 0)}stopTextFlush(){this.textFlushTimer&&(clearTimeout(this.textFlushTimer),this.textFlushTimer=null)}buildPromptText(t){let e=t.content||"";if(t.context_messages_json)try{const i=JSON.parse(t.context_messages_json);if(Array.isArray(i)&&i.length>0){const n=i.map(r=>`[context] ${r.sender_id??"unknown"}: ${r.content}`).join(`
5
5
  `);e=`${e}
6
6
 
7
7
  [Conversation context]
@@ -9,4 +9,4 @@ ${n}`}}catch{}const s=this.identity.injectOnce(t.session_id,e);return this.inbou
9
9
  `);e=`${e}
10
10
 
11
11
  [Conversation context]
12
- ${s}`}return this.identity.injectOnce(t.adapterSessionId,e)}clearActive(){const t=this.activeEventId;t&&this.snapshotAuditBoundary(t),this.activeEventId=null,this.activeSessionId=null,this.activeClientMsgId=null,this.activeRunError=null,this.textBuffer="",this.emittedTextByIndex.clear(),this.toolCallsInFlight.clear(),this.livenessExtendStartAt=void 0,this.stopIdleTimer(),t&&this.emit("eventDone",t)}beginAuditCapture(t){if(this.activeAuditCapture?.eventId===t.event_id||(this.activeAuditCapture=null,t.audit?.enabled!==!0))return;const e=this.piSessionPath??void 0;let s;if(e)try{s=f(e).size}catch{s=0}this.activeAuditCapture={eventId:t.event_id,...e?{transcriptPath:e}:{},...s===void 0?{}:{transcriptStartOffset:s}}}snapshotAuditBoundary(t){const e=this.activeAuditCapture;if(!e||e.eventId!==t)return;this.activeAuditCapture=null;const s={adapterType:"pi"};if(e.transcriptPath){let i=e.transcriptStartOffset??0;try{i=f(e.transcriptPath).size}catch{}s.transcriptPath=e.transcriptPath,s.transcriptStartOffset=e.transcriptStartOffset??0,s.transcriptEndOffset=i,s.providerSessionId=this.piSessionPath??e.transcriptPath}this.completedAuditBoundaries.set(t,s)}resetRunStreamState(){this.streamSeq=0,this.thinkingSeq=0,this.textBuffer="",this.activeRunError=null,this.runErrorEmitted=!1,this.emittedTextByIndex.clear(),this.activeClientMsgId=`pi_${++this.clientMsgSeq}_${Date.now()}`}nextStreamSeq(){return this.streamSeq++,this.streamSeq}completeActiveEvent(){if(!this.activeEventId){this.clearActive();return}const t=this.activeEventId,e=this.activeSessionId??"",s=this.activeClientMsgId??void 0,i=this.activeRunError??void 0;i&&this.emitPendingRunError(),this.clearActive(),this.finalizeEvent(t,e,s,i)}finalizeEvent(t,e,s,i){const n=this.nextStreamSeq(),r=i?"failed":"responded";a.info("pi-adapter",`finalize event=${t} sessionId=${e} status=${r} clientMsgId=${s??""} terminalError=${i?u(i):""}`),this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t,e,s).then(()=>{this.callbacks.sendEventResult(t,r,i),a.info("pi-adapter",`event ${r} (reliable) event=${t}`)}).catch(c=>{a.error("pi-adapter",`finalStreamChunk ACK failed event=${t}: ${c}`),this.callbacks.sendEventResult(t,"failed",`final output delivery failed: ${c instanceof Error?c.message:String(c)}`),a.info("pi-adapter",`event failed (final delivery) event=${t}`)}):(this.callbacks.sendStreamChunk(t,e,"",n,!0,s),this.callbacks.sendEventResult(t,r,i),a.info("pi-adapter",`event ${r} event=${t}`))}recordRunError(t){if(this.activeRunError||!this.activeEventId||!this.activeSessionId)return;const e=t.trim()||"Pi request failed";this.activeRunError=e,a.warn("pi-adapter",`recorded terminal error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${u(e)}`),this.flushTextBuffer()}emitPendingRunError(){this.runErrorEmitted||!this.activeRunError||!this.activeEventId||!this.activeSessionId||(this.runErrorEmitted=!0,this.callbacks.sendRunError(this.activeEventId,this.activeSessionId,this.activeRunError,this.nextStreamSeq(),this.activeClientMsgId??void 0))}piMessageError(t,e){if(t&&typeof t=="object"){const s=t.errorMessage;if(typeof s=="string"&&s.trim())return s.trim()}return typeof t=="string"&&t.trim()?t.trim():typeof e=="string"&&e.trim()&&e.trim()!=="error"?e.trim():"Pi request failed"}rememberEmittedText(t,e){this.emittedTextByIndex.set(t,(this.emittedTextByIndex.get(t)??"")+e)}appendMissingText(t,e){const s=this.emittedTextByIndex.get(t)??"";if(e!==s){if(e.startsWith(s)){const i=e.slice(s.length);i&&(this.rememberEmittedText(t,i),this.appendText(i));return}if(!s){this.rememberEmittedText(t,e),this.appendText(e);return}a.info("pi-adapter",`text_end content mismatch at index=${t}, keeping streamed deltas`)}}startComposing(t,e){this.stopComposing(),this.composingSessionId=t,this.callbacks.sendSessionActivitySet(t,"composing",!0,{ref_event_id:e,ttl_ms:12e4}),this.composingInterval=setInterval(()=>{this.composingSessionId&&this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!0,{ttl_ms:12e4})},3e4)}stopComposing(){this.composingInterval&&(clearInterval(this.composingInterval),this.composingInterval=null),this.composingSessionId&&(this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!1),this.composingSessionId=null)}static DONE_GUARD_MS=5e3;scheduleDoneGuard(){this.cancelDoneGuard(),!(!this.activeEventId||!this.activeSessionId)&&(this.doneGuardTimer=setTimeout(()=>{this.doneGuardTimer=null,!(!this.activeEventId||!this.isStreaming)&&(a.info("pi-adapter",`done guard triggered \u2014 no agent_end received, ending event=${this.activeEventId}`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.completeActiveEvent())},P.DONE_GUARD_MS))}cancelDoneGuard(){this.doneGuardTimer&&(clearTimeout(this.doneGuardTimer),this.doneGuardTimer=null)}shouldExtendByLiveness(){if(!this.isStreaming||!this.activeEventId)return!1;const t=this.process?.pid;if(!this.alive||!t||!_(t))return!1;const e=Date.now(),s=this.lastRpcAt>0?e-this.lastRpcAt:Number.POSITIVE_INFINITY;if(s<st)return this.livenessExtendStartAt=e,a.info("pi-adapter",`Liveness check: fresh RPC for ${this.activeEventId} (rpcAge=${s}ms, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const n=this.livenessExtendStartAt??e;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=n),e-n>x?(a.warn("pi-adapter",`Liveness extension budget exhausted for ${this.activeEventId} (no progress for ${Math.round((e-n)/6e4)}min), allowing idle fail`),!1):(a.info("pi-adapter",`Liveness check: turn in progress for ${this.activeEventId} (toolsInFlight=${this.toolCallsInFlight.size}, rpcAge=${Number.isFinite(s)?`${s}ms`:"n/a"}), extending`),!0)}resetIdleTimer(){this.stopIdleTimer(),!(this.stopped||!this.isStreaming)&&(this.idleTimer=setTimeout(()=>{if(this.stopped||!this.isStreaming)return;if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const t=this.process?.pid,s=!!(this.alive&&t&&_(t))?`liveness budget exhausted after ${x/6e4}min`:"process not alive";a.error("pi-adapter",`Idle timeout (${s}, toolsInFlight=${this.toolCallsInFlight.size}) \u2014 emitting exit for respawn`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.activeEventId&&(this.emitPendingRunError(),this.callbacks.sendEventResult(this.activeEventId,"failed",`idle timeout: ${s}`)),this.clearActive(),this.emit("exit",-1)},et))}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}async ensureSessionReady(){return this.sessionReadyPromise?this.sessionReadyPromise:(this.sessionReadyPromise=this.restoreOrCreateSession().finally(()=>{this.sessionReadyPromise=null}),this.sessionReadyPromise)}async restoreOrCreateSession(){try{await this.switchSession();return}catch(t){this.piSessionPath&&a.error("pi-adapter",`switch_session failed, creating new session: ${t}`)}await this.createNewSession()}async switchSession(){if(!this.piSessionPath)throw new Error("no PI session path");const t=await this.transport.send("switch_session",{sessionPath:this.piSessionPath});if(!t.success)throw this.piSessionPath=null,this.persistPiSessionPath(void 0),new Error(`switch_session failed: ${t.error}`)}async createNewSession(){const t=await this.transport.send("new_session");if(!t.success)throw new Error(`new_session failed: ${t.error}`);let e=null;if(e=t.data?.sessionFile??null,!e)try{const i=await this.transport.send("get_state");i.success&&(e=i.data?.sessionFile??null)}catch{}this.piSessionPath=e,this.persistPiSessionPath(this.piSessionPath??void 0)}persistPiSessionPath(t){!this.bindingStore||!this.aibotSessionId||this.bindingStore.setPiSessionPath(this.aibotSessionId,t)}}export{P as PiAdapter};
12
+ ${s}`}return this.identity.injectOnce(t.adapterSessionId,e)}clearActive(){const t=this.activeEventId;t&&this.snapshotAuditBoundary(t),this.activeEventId=null,this.activeSessionId=null,this.activeClientMsgId=null,this.activeRunError=null,this.textBuffer="",this.emittedTextByIndex.clear(),this.toolCallsInFlight.clear(),this.livenessExtendStartAt=void 0,this.stopIdleTimer(),t&&this.emit("eventDone",t)}beginAuditCapture(t){if(this.activeAuditCapture?.eventId===t.event_id||(this.activeAuditCapture=null,t.audit?.enabled!==!0))return;const e=this.piSessionPath??void 0;let s;if(e)try{s=f(e).size}catch{s=0}this.activeAuditCapture={eventId:t.event_id,...e?{transcriptPath:e}:{},...s===void 0?{}:{transcriptStartOffset:s}}}snapshotAuditBoundary(t){const e=this.activeAuditCapture;if(!e||e.eventId!==t)return;this.activeAuditCapture=null;const s={adapterType:"pi"};if(e.transcriptPath){let i=e.transcriptStartOffset??0;try{i=f(e.transcriptPath).size}catch{}s.transcriptPath=e.transcriptPath,s.transcriptStartOffset=e.transcriptStartOffset??0,s.transcriptEndOffset=i,s.providerSessionId=this.piSessionPath??e.transcriptPath}this.completedAuditBoundaries.set(t,s)}resetRunStreamState(){this.streamSeq=0,this.thinkingSeq=0,this.textBuffer="",this.activeRunError=null,this.runErrorEmitted=!1,this.emittedTextByIndex.clear(),this.activeClientMsgId=`pi_${++this.clientMsgSeq}_${Date.now()}`}nextStreamSeq(){return this.streamSeq++,this.streamSeq}completeActiveEvent(){if(!this.activeEventId){this.clearActive();return}const t=this.activeEventId,e=this.activeSessionId??"",s=this.activeClientMsgId??void 0,i=this.activeRunError??void 0;i&&this.emitPendingRunError(),this.clearActive(),this.finalizeEvent(t,e,s,i)}finalizeEvent(t,e,s,i){const n=this.nextStreamSeq(),r=i?"failed":"responded";o.info("pi-adapter",`finalize event=${t} sessionId=${e} status=${r} clientMsgId=${s??""} terminalError=${i?u(i):""}`),this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t,e,s).then(()=>{this.callbacks.sendEventResult(t,r,i),o.info("pi-adapter",`event ${r} (reliable) event=${t}`)}).catch(d=>{o.error("pi-adapter",`finalStreamChunk ACK failed event=${t}: ${d}`),this.callbacks.sendEventResult(t,"failed",`final output delivery failed: ${d instanceof Error?d.message:String(d)}`),o.info("pi-adapter",`event failed (final delivery) event=${t}`)}):(this.callbacks.sendStreamChunk(t,e,"",n,!0,s),this.callbacks.sendEventResult(t,r,i),o.info("pi-adapter",`event ${r} event=${t}`))}recordRunError(t){if(this.activeRunError||!this.activeEventId||!this.activeSessionId)return;const e=t.trim()||"Pi request failed";this.activeRunError=e,o.warn("pi-adapter",`recorded terminal error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${u(e)}`),this.flushTextBuffer()}emitPendingRunError(){this.runErrorEmitted||!this.activeRunError||!this.activeEventId||!this.activeSessionId||(this.runErrorEmitted=!0,this.callbacks.sendRunError(this.activeEventId,this.activeSessionId,this.activeRunError,this.nextStreamSeq(),this.activeClientMsgId??void 0))}piMessageError(t,e){if(t&&typeof t=="object"){const s=t.errorMessage;if(typeof s=="string"&&s.trim())return s.trim()}return typeof t=="string"&&t.trim()?t.trim():typeof e=="string"&&e.trim()&&e.trim()!=="error"?e.trim():"Pi request failed"}rememberEmittedText(t,e){this.emittedTextByIndex.set(t,(this.emittedTextByIndex.get(t)??"")+e)}appendMissingText(t,e){const s=this.emittedTextByIndex.get(t)??"";if(e!==s){if(e.startsWith(s)){const i=e.slice(s.length);i&&(this.rememberEmittedText(t,i),this.appendText(i));return}if(!s){this.rememberEmittedText(t,e),this.appendText(e);return}o.info("pi-adapter",`text_end content mismatch at index=${t}, keeping streamed deltas`)}}startComposing(t,e){this.stopComposing(),this.composingSessionId=t,this.callbacks.sendSessionActivitySet(t,"composing",!0,{ref_event_id:e,ttl_ms:12e4}),this.composingInterval=setInterval(()=>{this.composingSessionId&&this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!0,{ttl_ms:12e4})},3e4)}stopComposing(){this.composingInterval&&(clearInterval(this.composingInterval),this.composingInterval=null),this.composingSessionId&&(this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!1),this.composingSessionId=null)}static DONE_GUARD_MS=5e3;scheduleDoneGuard(){this.cancelDoneGuard(),!(!this.activeEventId||!this.activeSessionId)&&(this.doneGuardTimer=setTimeout(()=>{this.doneGuardTimer=null,!(!this.activeEventId||!this.isStreaming)&&(o.info("pi-adapter",`done guard triggered \u2014 no agent_end received, ending event=${this.activeEventId}`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.completeActiveEvent())},w.DONE_GUARD_MS))}cancelDoneGuard(){this.doneGuardTimer&&(clearTimeout(this.doneGuardTimer),this.doneGuardTimer=null)}shouldExtendByLiveness(){if(!this.isStreaming||!this.activeEventId)return!1;const t=this.process?.pid;if(!this.alive||!t||!_(t))return!1;const e=Date.now(),s=this.lastRpcAt>0?e-this.lastRpcAt:Number.POSITIVE_INFINITY;if(s<it)return this.livenessExtendStartAt=e,o.info("pi-adapter",`Liveness check: fresh RPC for ${this.activeEventId} (rpcAge=${s}ms, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const n=this.livenessExtendStartAt??e;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=n),e-n>x?(o.warn("pi-adapter",`Liveness extension budget exhausted for ${this.activeEventId} (no progress for ${Math.round((e-n)/6e4)}min), allowing idle fail`),!1):(o.info("pi-adapter",`Liveness check: turn in progress for ${this.activeEventId} (toolsInFlight=${this.toolCallsInFlight.size}, rpcAge=${Number.isFinite(s)?`${s}ms`:"n/a"}), extending`),!0)}resetIdleTimer(){this.stopIdleTimer(),!(this.stopped||!this.isStreaming)&&(this.idleTimer=setTimeout(()=>{if(this.stopped||!this.isStreaming)return;if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const t=this.process?.pid,s=!!(this.alive&&t&&_(t))?`liveness budget exhausted after ${x/6e4}min`:"process not alive";o.error("pi-adapter",`Idle timeout (${s}, toolsInFlight=${this.toolCallsInFlight.size}) \u2014 emitting exit for respawn`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.activeEventId&&(this.emitPendingRunError(),this.callbacks.sendEventResult(this.activeEventId,"failed",`idle timeout: ${s}`)),this.clearActive(),this.emit("exit",-1)},st))}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}async ensureSessionReady(){return this.sessionReadyPromise?this.sessionReadyPromise:(this.sessionReadyPromise=this.restoreOrCreateSession().finally(()=>{this.sessionReadyPromise=null}),this.sessionReadyPromise)}async restoreOrCreateSession(){try{await this.switchSession();return}catch(t){this.piSessionPath&&o.error("pi-adapter",`switch_session failed, creating new session: ${t}`)}await this.createNewSession()}async switchSession(){if(!this.piSessionPath)throw new Error("no PI session path");const t=await this.transport.send("switch_session",{sessionPath:this.piSessionPath});if(!t.success)throw this.piSessionPath=null,this.persistPiSessionPath(void 0),new Error(`switch_session failed: ${t.error}`)}async createNewSession(){const t=await this.transport.send("new_session");if(!t.success)throw new Error(`new_session failed: ${t.error}`);let e=null;if(e=t.data?.sessionFile??null,!e)try{const i=await this.transport.send("get_state");i.success&&(e=i.data?.sessionFile??null)}catch{}this.piSessionPath=e,this.persistPiSessionPath(this.piSessionPath??void 0)}persistPiSessionPath(t){!this.bindingStore||!this.aibotSessionId||this.bindingStore.setPiSessionPath(this.aibotSessionId,t)}}export{w as PiAdapter};
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "bridgeVersion": "4.3.0",
4
- "tarball": "grix-dsh-bridge-4.3.0.tgz",
5
- "size": 22489,
3
+ "bridgeVersion": "4.3.1",
4
+ "tarball": "grix-dsh-bridge-4.3.1.tgz",
5
+ "size": 22531,
6
6
  "unpackedSize": 89865,
7
- "shasum": "446787a5a6ace52998f6c190a149aaa3da2f9943",
8
- "integrity": "sha512-2eNtxpcjfeLIiyxYt7cgwohggr5JMDGqD4RJEV1GhwOIUjqOK16mRZ6OwfAHMqNYhg+PwpLDKnN/KHWF14xBWg=="
7
+ "shasum": "4986c0efcce74e1bf87a5b5ff4fcaf5dd56c8e92",
8
+ "integrity": "sha512-vxviwM7PAw6KMAFY/iZ7yF89rwJfzFiRRURzI4kTs0WWk+50TO9Ulbd5UMCnenE3P3GmKHWARkq0QcpRPtVa7g=="
9
9
  }
@@ -1 +1 @@
1
- import{log as t}from"../core/log/index.js";const n=3e3,o=6e4,r=10,a=300*1e3,p=6e4,u=1e4,m=3;class c{attempts=0;slowRetryTimer=null;respawnTimer=null;healthCheckTimer=null;healthFailures=0;get exhausted(){return this.attempts>=r}resetAttempts(){this.attempts=0}resetHealthFailures(){this.healthFailures=0}stopSlowRetry(){this.slowRetryTimer&&(clearTimeout(this.slowRetryTimer),this.slowRetryTimer=null)}stopHealthCheck(){this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null)}stop(){this.stopSlowRetry(),this.respawnTimer&&(clearTimeout(this.respawnTimer),this.respawnTimer=null)}stopAll(){this.stopHealthCheck(),this.stop()}startHealthCheck(e){if(this.stopHealthCheck(),!e.pingAgent)return;this.healthFailures=0;const s=e.healthCheckIntervalMs??p,i=e.healthCheckTimeoutMs??u,h=e.healthCheckMaxFailures??m;this.healthCheckTimer=setInterval(()=>{if(e.stopped){this.stopHealthCheck();return}if(!e.pingAgent){this.stopHealthCheck();return}e.agentAlive!==!1&&e.pingAgent(i).then(l=>{l?this.healthFailures=0:(this.healthFailures++,t.info(e.name,`Health check failed (${this.healthFailures}/${h})`),this.healthFailures>=h&&(t.error(e.name,"Health check exhausted, triggering respawn"),this.healthFailures=0,e.onAbortActiveRun&&e.onAbortActiveRun("health check exhausted"),this.scheduleRespawn(e)))}).catch(()=>{this.healthFailures++,t.info(e.name,`Health check error (${this.healthFailures}/${h})`),this.healthFailures>=h&&(t.error(e.name,"Health check exhausted (error), triggering respawn"),this.healthFailures=0,e.onAbortActiveRun&&e.onAbortActiveRun("health check exhausted"),this.scheduleRespawn(e))})},s)}scheduleRespawn(e){try{e.onCleanupAgent()}catch{}if(this.respawnTimer&&(clearTimeout(this.respawnTimer),this.respawnTimer=null),this.attempts++,this.attempts>r){t.error(e.name,`Max respawn attempts reached, will retry in ${a/1e3}s`),this.scheduleSlowRetry(e);return}const s=Math.min(n*2**(this.attempts-1),o);t.info(e.name,`Respawn attempt ${this.attempts}/${r} in ${s}ms`),this.respawnTimer=setTimeout(()=>{this.respawnTimer=null,!e.stopped&&e.onRespawnNeeded().catch(i=>{t.error(e.name,`Respawn failed: ${i}`),this.scheduleRespawn(e)})},s)}scheduleSlowRetry(e){this.stopSlowRetry(),this.slowRetryTimer=setTimeout(()=>{e.stopped||(t.info(e.name,"Slow retry: attempting respawn"),this.attempts=0,e.onRespawnNeeded().catch(s=>{t.error(e.name,`Slow retry failed: ${s}`),this.scheduleRespawn(e)}))},a)}}export{c as RespawnManager};
1
+ import{log as t}from"../core/log/index.js";const o=3e3,p=6e4,r=10,l=300*1e3,u=6e4,n=1e4,m=3;class T{attempts=0;slowRetryTimer=null;respawnTimer=null;healthCheckTimer=null;healthFailures=0;get exhausted(){return this.attempts>=r}resetAttempts(){this.attempts=0}resetHealthFailures(){this.healthFailures=0}stopSlowRetry(){this.slowRetryTimer&&(clearTimeout(this.slowRetryTimer),this.slowRetryTimer=null)}stopHealthCheck(){this.healthCheckTimer&&(clearInterval(this.healthCheckTimer),this.healthCheckTimer=null)}stop(){this.stopSlowRetry(),this.respawnTimer&&(clearTimeout(this.respawnTimer),this.respawnTimer=null)}stopAll(){this.stopHealthCheck(),this.stop()}startHealthCheck(e){if(this.stopHealthCheck(),!e.pingAgent)return;this.healthFailures=0;const h=e.healthCheckIntervalMs??u,i=e.healthCheckTimeoutMs??n,s=e.healthCheckMaxFailures??m;this.healthCheckTimer=setInterval(()=>{if(e.stopped){this.stopHealthCheck();return}if(!e.pingAgent){this.stopHealthCheck();return}e.agentAlive!==!1&&e.pingAgent(i).then(a=>{a?this.healthFailures=0:(this.healthFailures++,t.info(e.name,`Health check failed (${this.healthFailures}/${s})`),this.healthFailures>=s&&(t.error(e.name,"Health check exhausted, triggering respawn"),this.healthFailures=0,e.onAbortActiveRun&&e.onAbortActiveRun("health check exhausted"),this.scheduleRespawn(e,{recheckHealth:!0})))}).catch(()=>{this.healthFailures++,t.info(e.name,`Health check error (${this.healthFailures}/${s})`),this.healthFailures>=s&&(t.error(e.name,"Health check exhausted (error), triggering respawn"),this.healthFailures=0,e.onAbortActiveRun&&e.onAbortActiveRun("health check exhausted"),this.scheduleRespawn(e,{recheckHealth:!0}))})},h)}scheduleRespawn(e,h){try{e.onCleanupAgent()}catch{}if(this.respawnTimer&&(clearTimeout(this.respawnTimer),this.respawnTimer=null),this.attempts++,this.attempts>r){t.error(e.name,`Max respawn attempts reached, will retry in ${l/1e3}s`),this.scheduleSlowRetry(e);return}const i=Math.min(o*2**(this.attempts-1),p);t.info(e.name,`Respawn attempt ${this.attempts}/${r} in ${i}ms`),this.respawnTimer=setTimeout(async()=>{if(this.respawnTimer=null,!e.stopped){if(h?.recheckHealth&&e.pingAgent&&e.agentAlive!==!1){const s=e.healthCheckTimeoutMs??n,a=await e.pingAgent(s).catch(()=>!1);if(e.stopped)return;if(a){t.info(e.name,"Agent recovered before respawn fired; skipping respawn"),this.attempts=0,this.healthFailures=0;return}}e.onRespawnNeeded().catch(s=>{t.error(e.name,`Respawn failed: ${s}`),this.scheduleRespawn(e)})}},i)}scheduleSlowRetry(e){this.stopSlowRetry(),this.slowRetryTimer=setTimeout(()=>{e.stopped||(t.info(e.name,"Slow retry: attempting respawn"),this.attempts=0,e.onRespawnNeeded().catch(h=>{t.error(e.name,`Slow retry failed: ${h}`),this.scheduleRespawn(e)}))},l)}}export{T as RespawnManager};
@@ -1,3 +1,3 @@
1
- import{isRequestTimeoutError as E}from"../core/aibot/errors.js";import{log as f}from"../core/log/index.js";import{splitTextForAibotProtocol as p,AIBOT_PROTOCOL_MAX_RUNES as C}from"../core/protocol/protocol-text.js";import{isThinkingEventDropped as k,isToolEventDropped as y,normalizeRuntimeConfigSnapshot as S}from"./runtime-config.js";const q={claude:!1,acp:!1,codex:!0,codewhale:!0,pi:!0,openhuman:!1,cursor:!1,opencode:!0,agy:!0,"deepseek-harness":!1};class _{handle;connectorRuntimeConfig;eventRuntimeConfigs=new Map;eventQuotedMessageIds=new Map;defaultQuoteTrigger=!1;thinkingSeqMap=new Map;thinkingSessionMap=new Map;toolCardSeq=0;bufferedEventTexts=new Map;singleMessageDeliveries=new Map;chunkSeqMap=new Map;rejectedEvents=new Set;terminalEvents=new Set;static MAX_TERMINAL_EVENTS=1e3;stoppedEvents=new Set;streamCoalesce=new Map;streamCoalesceMs=T();static STREAM_COALESCE_MAX_RUNES=2048;recentToolCards=new Map;static TOOL_CARD_DEDUP_MS=100;constructor(e){this.connectorRuntimeConfig={...e}}bind(e){this.handle=e}markEventRejected(e){if(!e)return;this.rejectedEvents.add(e);const t=`${e}:`;for(const s of[...this.streamCoalesce.keys()])if(s.startsWith(t)){const n=this.streamCoalesce.get(s);n.timer&&clearTimeout(n.timer),this.streamCoalesce.delete(s)}f.info("send-ctrl",`event marked as stream-rejected, future chunks will be dropped event=${e}`)}markEventTerminal(e){if(!(!e||this.terminalEvents.has(e))&&(this.terminalEvents.add(e),this.terminalEvents.size>_.MAX_TERMINAL_EVENTS)){const t=this.terminalEvents.values().next().value;t!==void 0&&this.terminalEvents.delete(t)}}isEventClosed(e){return!!e&&(this.rejectedEvents.has(e)||this.terminalEvents.has(e))}markEventStopped(e){e&&(this.stoppedEvents.add(e),f.info("send-ctrl",`[stop-trace] event marked stopped; subsequent outbound will be flagged event=${e}`))}flagOutboundAfterStop(e,t,s,n,r,a){!e||!this.stoppedEvents.has(e)||f.warn("send-ctrl",`[stop-trace] OUTBOUND AFTER STOP ${s} event=${e} session=${t} seq=${n} is_finish=${r} len=${a}`)}getGlobalRuntimeConfig(){return this.connectorRuntimeConfig}setStreamCoalesceMs(e){this.streamCoalesceMs=Number.isFinite(e)&&e>0?Math.floor(e):0}captureEventRuntimeConfig(e){this.terminalEvents.delete(e.event_id);const t=S(e.connector_runtime_config);if(t||!this.eventRuntimeConfigs.has(e.event_id)){const s=t??this.connectorRuntimeConfig;this.eventRuntimeConfigs.set(e.event_id,{responseDelivery:s.responseDelivery,toolEvents:s.toolEvents,thinkingEvents:s.thinkingEvents})}e.msg_id&&!this.eventQuotedMessageIds.has(e.event_id)&&this.eventQuotedMessageIds.set(e.event_id,e.msg_id)}discardEventState(e){e&&(this.markEventTerminal(e),this.clearEventTrackingState(e))}clearEventTrackingState(e){this.eventRuntimeConfigs.delete(e),this.eventQuotedMessageIds.delete(e),this.rejectedEvents.delete(e),this.singleMessageDeliveries.delete(e),this.thinkingSeqMap.delete(e),this.thinkingSessionMap.delete(e),this.bufferedEventTexts.delete(e);for(const t of[...this.streamCoalesce.keys()])if(t.startsWith(`${e}:`)){const s=this.streamCoalesce.get(t);s.timer&&clearTimeout(s.timer),this.streamCoalesce.delete(t)}this.stoppedEvents.delete(e)&&f.info("send-ctrl",`[stop-trace] event tracking cleared stop flag event=${e}`);for(const t of this.chunkSeqMap.keys())t.startsWith(`${e}:`)&&this.chunkSeqMap.delete(t);for(const t of this.recentToolCards.keys())t.startsWith(`${e}:`)&&this.recentToolCards.delete(t)}setDefaultQuoteTrigger(e){this.defaultQuoteTrigger=e}getDefaultQuotedMessageId(e){if(!(!this.defaultQuoteTrigger||!e))return this.eventQuotedMessageIds.get(e)}resolveEventRuntimeConfig(e){if(e){const t=this.eventRuntimeConfigs.get(e);if(t)return t}return this.connectorRuntimeConfig}shouldDropToolDisplayEvent(e){return y(this.resolveEventRuntimeConfig(e))}shouldDropThinkingDisplayEvent(e){return k(this.resolveEventRuntimeConfig(e))}shouldDropCodexDisplayEvent(e,t){return this.shouldDropToolDisplayEvent(e)?t==="item/completed":!1}shouldDropAcpRawDisplayEvent(e,t){return!!(this.shouldDropToolDisplayEvent(e)&&(t==="tool_use"||t==="tool_result")||this.shouldDropThinkingDisplayEvent(e)&&t==="thinking")}sendReply(e,t,s,n,r,a){if(!a?.skipToolFilter&&this.shouldDropToolDisplayEvent(e)&&D(s,r)||this.isEventClosed(e))return;if(this.flagOutboundAfterStop(e,t,"reply",0,!1,(s||"").length),this.resolveEventRuntimeConfig(e).responseDelivery==="stream"&&!r){const i=p(s),l=e?`reply_stream_${e}`:`reply_stream_${Date.now()}`;if(i.length===0){this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:s||" ",quoted_message_id:n||void 0});return}for(let u=0;u<i.length;u++){const c=u===i.length-1;this.sendStreamChunk(e,t,i[u],u+1,c,l,n)}return}this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:s,quoted_message_id:n||void 0,...r?{extra:r}:{}})}sendStreamChunk(e,t,s,n,r,a,o){if(this.isEventClosed(e))return;if(o=o??this.getDefaultQuotedMessageId(e),this.flagOutboundAfterStop(e,t,"stream_chunk",n,r,(s||"").length),this.resolveEventRuntimeConfig(e).responseDelivery==="single_message"&&e){this.bufferStreamChunk(e,t,s,r,o);return}if(this.streamCoalesceMs<=0){this.emitStreamChunkParts(e,t,s,n,r,a,o);return}this.coalesceStreamChunk(e,t,s,r,a,o)}async sendFinalStreamChunkReliable(e,t,s,n,r=!1,a=!1){if(this.isEventClosed(e))throw new Error(`required agent output was already rejected or the event is terminal: event=${e}`);a||this.finalizeThinking(e,t);const o=this.resolveEventRuntimeConfig(e);if(!r&&o.responseDelivery==="single_message"&&e){if(this.flushCoalesceForEvent(e),await this.ensureSingleMessageDelivery(e,n),this.isEventClosed(e))throw new Error(`required agent output was rejected before terminal: event=${e}`);return}const i=`${e}:${s??"default"}`;this.flushCoalesce(i,!1),this.streamCoalesce.delete(i);const l=(this.chunkSeqMap.get(i)??0)+1;this.chunkSeqMap.set(i,l);const u=this.getDefaultQuotedMessageId(e),c={event_id:e,session_id:t,delta_content:"",chunk_seq:l,is_finish:!0,...s?{client_msg_id:s}:{},...u?{quoted_message_id:u}:{}};this.flagOutboundAfterStop(e,t,"stream_chunk_final",l,!0,0);const m=async()=>{const h=await this.handle.sendStreamChunkRequest(c,n);if(h.cmd!=="send_ack"){const g=h.payload;throw new Error(`final chunk rejected: cmd=${h.cmd} code=${g?.code??""} msg=${g?.msg??""}`)}};try{await m()}catch(h){if(E(h))f.warn("send-ctrl",`final chunk ACK timed out, retry request with same chunk_seq=${l} event=${e}`),await m();else throw f.warn("send-ctrl",`final chunk send failed (no resend) event=${e}: ${h}`),h}if(this.isEventClosed(e))throw new Error(`required agent output was rejected before terminal: event=${e}`)}async deliverAuxiliaryLargeText(e,t,s,n){if(!s||this.isEventClosed(e))return!1;if(this.resolveEventRuntimeConfig(e).responseDelivery==="single_message"&&e){const o=this.getDefaultQuotedMessageId(e),i=p(s);for(let l=0;l<i.length;l++)this.flagOutboundAfterStop(e,t,"aux_detail_msg",l+1,!1,i[l].length),this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:i[l],...l===0&&o?{quoted_message_id:o}:{},client_msg_id:i.length>1?`${n}_p${l+1}`:n});return!0}const a=p(s);for(const o of a)this.sendStreamChunk(e,t,o,0,!1,n);return await this.sendFinalStreamChunkReliable(e,t,n,void 0,!1,!0),!0}coalesceStreamChunk(e,t,s,n,r,a){if(!s&&!n)return;const o=`${e}:${r??"default"}`;let i=this.streamCoalesce.get(o);if(i||(i={eventId:e,sessionId:t,clientMsgId:r,quotedMessageId:a,text:"",flushedOnce:!1},this.streamCoalesce.set(o,i)),s&&(i.text+=s),i.sessionId=t,r!==void 0&&(i.clientMsgId=r),!i.quotedMessageId&&a&&(i.quotedMessageId=a),n){this.flushCoalesce(o,!0);return}if(!i.flushedOnce||i.text.length>=_.STREAM_COALESCE_MAX_RUNES){this.flushCoalesce(o,!1);return}i.timer||(i.timer=setTimeout(()=>this.flushCoalesce(o,!1),this.streamCoalesceMs))}flushCoalesce(e,t){const s=this.streamCoalesce.get(e);if(!s)return;s.timer&&(clearTimeout(s.timer),s.timer=void 0);const n=s.text;s.text="",s.flushedOnce=!0,t&&this.streamCoalesce.delete(e),!(!n&&!t)&&this.emitStreamChunkParts(s.eventId,s.sessionId,n,0,t,s.clientMsgId,s.quotedMessageId)}flushCoalesceForEvent(e){const t=`${e}:`;for(const s of[...this.streamCoalesce.keys()])s.startsWith(t)&&(this.flushCoalesce(s,!1),this.streamCoalesce.delete(s))}emitStreamChunkParts(e,t,s,n,r,a,o){const i=s||(r?`
2
- `:"");if(!i&&!r)return;const l=p(i,C);l.length===0&&l.push(i||`
3
- `);const u=`${e}:${a??"default"}`;for(let c=0;c<l.length;c++){const m=c===l.length-1,h=this.chunkSeqMap.get(u)??0,g=c===0&&n>h?n:h+1;this.chunkSeqMap.set(u,g),this.handle.sendStreamChunk({event_id:e,session_id:t,delta_content:l[c],chunk_seq:g,is_finish:m&&r,...a?{client_msg_id:a}:{},...o?{quoted_message_id:o}:{}})}}sendEventResult(e,t,s,n){this.finalizeThinking(e,""),this.flushCoalesceForEvent(e);const r=this.ensureSingleMessageDelivery(e),a=(o,i=s,l=n)=>{o==="responded"&&this.rejectedEvents.has(e)&&(o="failed",l=l||"agent_output_rejected",i=i||"required agent output was rejected by the server"),this.markEventTerminal(e),this.handle.sendEventResult({event_id:e,status:o,...i?{msg:i}:{},...l?{code:l}:{},updated_at:Date.now()}),this.clearEventTrackingState(e)};if(!r){a(t);return}r.then(()=>a(t),o=>{const i=`final output delivery failed: ${o instanceof Error?o.message:String(o)}`;a(t==="responded"?"failed":t,t==="responded"?i:s,t==="responded"?"agent_output_delivery_failed":n)})}sendThinking(e,t,s){if(this.shouldDropThinkingDisplayEvent(e)||this.isEventClosed(e))return;this.flagOutboundAfterStop(e,t,"thinking",this.thinkingSeqMap.get(e)??0,!1,(s||"").length);const n=(this.thinkingSeqMap.get(e)??0)+1;this.thinkingSeqMap.set(e,n),this.thinkingSessionMap.set(e,t),this.handle.sendStreamChunk({event_id:e,session_id:t,delta_content:s,chunk_seq:n,is_finish:!1,client_msg_id:`${e}_thinking`,is_thinking:!0})}sendToolExecutionCard(e,t,s,n){if(this.shouldDropToolDisplayEvent(e)){f.info("send-ctrl",`[tool-card] DROP event=${e} session=${t} summary=${s.summaryText}`);return}const a=Date.now(),o=`${e}:${s.summaryText}:${s.detailText??""}`,i=this.recentToolCards.get(o);if(i!==void 0&&a-i<_.TOOL_CARD_DEDUP_MS){f.info("send-ctrl",`[tool-card] DEDUP event=${e} session=${t} summary=${s.summaryText}`);return}this.recentToolCards.set(o,a);const l={summary_text:s.summaryText};s.detailText&&(l.detail_text=s.detailText),f.info("send-ctrl",`[tool-card] SEND event=${e} session=${t} summary=${s.summaryText}`),this.handle.sendMsg({event_id:e,session_id:t,client_msg_id:n??`tool_${++this.toolCardSeq}_${Date.now()}`,msg_type:1,content:"",extra:{channel_data:{grix:{toolExecution:l}},agent_api_origin:!0}})}finalizeThinking(e,t){const s=this.thinkingSeqMap.get(e);s!==void 0&&(this.thinkingSeqMap.delete(e),t=t||this.thinkingSessionMap.get(e)||"",this.thinkingSessionMap.delete(e),t&&(this.isEventClosed(e)||this.handle.sendStreamChunk({event_id:e,session_id:t,delta_content:"",chunk_seq:s+1,is_finish:!0,client_msg_id:`${e}_thinking`,is_thinking:!0})))}bufferOnly(e,t,s,n,r){r=r??this.getDefaultQuotedMessageId(e),this.bufferStreamChunk(e,t,s,n,r)}bufferStreamChunk(e,t,s,n,r){const a=this.bufferedEventTexts.get(e);a?(s&&(a.text+=s),!a.quotedMessageId&&r&&(a.quotedMessageId=r)):this.bufferedEventTexts.set(e,{sessionId:t,text:s??"",quotedMessageId:r||void 0}),n&&this.ensureSingleMessageDelivery(e)?.catch(i=>{f.warn("send-ctrl",`single-message output delivery failed event=${e}: ${i instanceof Error?i.message:String(i)}`)})}ensureSingleMessageDelivery(e,t){const s=this.singleMessageDeliveries.get(e);if(s)return s;const n=this.bufferedEventTexts.get(e);if(!n||(this.bufferedEventTexts.delete(e),!n.text))return;const r=(async()=>{const a={event_id:e,session_id:n.sessionId,content:n.text,client_msg_id:`agent_single_${e}`,...n.quotedMessageId?{quoted_message_id:n.quotedMessageId}:{}},o=async()=>{const i=t===void 0?await this.handle.sendText(a):await this.handle.sendText(a,t);if(i.cmd!=="send_ack"){const l=i.payload;throw new Error(`single-message output rejected: cmd=${i.cmd} code=${l?.code??""} msg=${l?.msg??""}`)}};try{await o()}catch(i){if(!E(i))throw i;f.warn("send-ctrl",`single-message ACK timed out, retry request with stable client_msg_id=${a.client_msg_id} event=${e}`),await o()}})();return this.singleMessageDeliveries.set(e,r),r}}function T(){const d=process.env.GRIX_STREAM_COALESCE_MS;if(d===void 0||d==="")return 500;const e=Number(d);return Number.isFinite(e)&&e>=0?Math.floor(e):500}function D(d,e){return e&&typeof e=="object"&&e.channel_data?.grix?.toolExecution?!0:/^\[tool\]/.test(d)||/^\[tool result\]/.test(d)}export{q as DEFAULT_QUOTE_TRIGGER_BY_ADAPTER,_ as SendController};
1
+ import{isRequestTimeoutError as E}from"../core/aibot/errors.js";import{log as f}from"../core/log/index.js";import{splitTextForAibotProtocol as p,AIBOT_PROTOCOL_MAX_RUNES as C}from"../core/protocol/protocol-text.js";import{isThinkingEventDropped as k,isToolEventDropped as y,normalizeRuntimeConfigSnapshot as S}from"./runtime-config.js";const v={claude:!1,acp:!1,codex:!0,codewhale:!0,pi:!0,openhuman:!1,cursor:!1,opencode:!0,agy:!0,"deepseek-harness":!1};class _{handle;connectorRuntimeConfig;eventRuntimeConfigs=new Map;eventQuotedMessageIds=new Map;defaultQuoteTrigger=!1;thinkingSeqMap=new Map;thinkingSessionMap=new Map;toolCardSeq=0;bufferedEventTexts=new Map;singleMessageDeliveries=new Map;chunkSeqMap=new Map;rejectedEvents=new Set;terminalEvents=new Set;static MAX_TERMINAL_EVENTS=1e3;stoppedEvents=new Set;streamCoalesce=new Map;streamCoalesceMs=T();static STREAM_COALESCE_MAX_RUNES=2048;recentToolCards=new Map;static TOOL_CARD_DEDUP_MS=100;constructor(e){this.connectorRuntimeConfig={...e}}bind(e){this.handle=e}markEventRejected(e){if(!e)return;this.rejectedEvents.add(e);const t=`${e}:`;for(const s of[...this.streamCoalesce.keys()])if(s.startsWith(t)){const n=this.streamCoalesce.get(s);n.timer&&clearTimeout(n.timer),this.streamCoalesce.delete(s)}f.info("send-ctrl",`event marked as stream-rejected, future chunks will be dropped event=${e}`)}markEventTerminal(e){if(!(!e||this.terminalEvents.has(e))&&(this.terminalEvents.add(e),this.terminalEvents.size>_.MAX_TERMINAL_EVENTS)){const t=this.terminalEvents.values().next().value;t!==void 0&&this.terminalEvents.delete(t)}}isEventClosed(e){return!!e&&(this.rejectedEvents.has(e)||this.terminalEvents.has(e))}markEventStopped(e){e&&(this.stoppedEvents.add(e),f.info("send-ctrl",`[stop-trace] event marked stopped; subsequent outbound will be flagged event=${e}`))}flagOutboundAfterStop(e,t,s,n,o,a){!e||!this.stoppedEvents.has(e)||f.warn("send-ctrl",`[stop-trace] OUTBOUND AFTER STOP ${s} event=${e} session=${t} seq=${n} is_finish=${o} len=${a}`)}getGlobalRuntimeConfig(){return this.connectorRuntimeConfig}setStreamCoalesceMs(e){this.streamCoalesceMs=Number.isFinite(e)&&e>0?Math.floor(e):0}captureEventRuntimeConfig(e){this.terminalEvents.delete(e.event_id);const t=S(e.connector_runtime_config);if(t||!this.eventRuntimeConfigs.has(e.event_id)){const s=t??this.connectorRuntimeConfig;this.eventRuntimeConfigs.set(e.event_id,{responseDelivery:s.responseDelivery,toolEvents:s.toolEvents,thinkingEvents:s.thinkingEvents}),f.info("send-ctrl",`[runtime-config] event=${e.event_id} response_delivery=${s.responseDelivery} tool_events=${s.toolEvents} thinking_events=${s.thinkingEvents} source=${t?"event":"global"}`)}e.msg_id&&!this.eventQuotedMessageIds.has(e.event_id)&&this.eventQuotedMessageIds.set(e.event_id,e.msg_id)}discardEventState(e){e&&(this.markEventTerminal(e),this.clearEventTrackingState(e))}clearEventTrackingState(e){this.eventRuntimeConfigs.delete(e),this.eventQuotedMessageIds.delete(e),this.rejectedEvents.delete(e),this.singleMessageDeliveries.delete(e),this.thinkingSeqMap.delete(e),this.thinkingSessionMap.delete(e),this.bufferedEventTexts.delete(e);for(const t of[...this.streamCoalesce.keys()])if(t.startsWith(`${e}:`)){const s=this.streamCoalesce.get(t);s.timer&&clearTimeout(s.timer),this.streamCoalesce.delete(t)}this.stoppedEvents.delete(e)&&f.info("send-ctrl",`[stop-trace] event tracking cleared stop flag event=${e}`);for(const t of this.chunkSeqMap.keys())t.startsWith(`${e}:`)&&this.chunkSeqMap.delete(t);for(const t of this.recentToolCards.keys())t.startsWith(`${e}:`)&&this.recentToolCards.delete(t)}setDefaultQuoteTrigger(e){this.defaultQuoteTrigger=e}getDefaultQuotedMessageId(e){if(!(!this.defaultQuoteTrigger||!e))return this.eventQuotedMessageIds.get(e)}resolveEventRuntimeConfig(e){if(e){const t=this.eventRuntimeConfigs.get(e);if(t)return t}return this.connectorRuntimeConfig}shouldDropToolDisplayEvent(e){return y(this.resolveEventRuntimeConfig(e))}shouldDropThinkingDisplayEvent(e){return k(this.resolveEventRuntimeConfig(e))}shouldDropCodexDisplayEvent(e,t){return this.shouldDropToolDisplayEvent(e)?t==="item/completed":!1}shouldDropAcpRawDisplayEvent(e,t){return!!(this.shouldDropToolDisplayEvent(e)&&(t==="tool_use"||t==="tool_result")||this.shouldDropThinkingDisplayEvent(e)&&t==="thinking")}sendReply(e,t,s,n,o,a){if(!a?.skipToolFilter&&this.shouldDropToolDisplayEvent(e)&&$(s,o)||this.isEventClosed(e))return;if(this.flagOutboundAfterStop(e,t,"reply",0,!1,(s||"").length),this.resolveEventRuntimeConfig(e).responseDelivery==="stream"&&!o){const i=p(s),l=e?`reply_stream_${e}`:`reply_stream_${Date.now()}`;if(i.length===0){this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:s||" ",quoted_message_id:n||void 0});return}for(let u=0;u<i.length;u++){const c=u===i.length-1;this.sendStreamChunk(e,t,i[u],u+1,c,l,n)}return}this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:s,quoted_message_id:n||void 0,...o?{extra:o}:{}})}sendStreamChunk(e,t,s,n,o,a,r){if(this.isEventClosed(e))return;if(r=r??this.getDefaultQuotedMessageId(e),this.flagOutboundAfterStop(e,t,"stream_chunk",n,o,(s||"").length),this.resolveEventRuntimeConfig(e).responseDelivery==="single_message"&&e){this.bufferStreamChunk(e,t,s,r,a);return}if(this.streamCoalesceMs<=0){this.emitStreamChunkParts(e,t,s,n,o,a,r);return}this.coalesceStreamChunk(e,t,s,o,a,r)}async sendFinalStreamChunkReliable(e,t,s,n,o=!1,a=!1){if(this.isEventClosed(e))throw new Error(`required agent output was already rejected or the event is terminal: event=${e}`);a||this.finalizeThinking(e,t);const r=this.resolveEventRuntimeConfig(e);if(!o&&r.responseDelivery==="single_message"&&e){if(this.flushCoalesceForEvent(e),await this.ensureSingleMessageDelivery(e,n),this.isEventClosed(e))throw new Error(`required agent output was rejected before terminal: event=${e}`);return}const i=`${e}:${s??"default"}`;this.flushCoalesce(i,!1),this.streamCoalesce.delete(i);const l=(this.chunkSeqMap.get(i)??0)+1;this.chunkSeqMap.set(i,l);const u=this.getDefaultQuotedMessageId(e),c={event_id:e,session_id:t,delta_content:"",chunk_seq:l,is_finish:!0,...s?{client_msg_id:s}:{},...u?{quoted_message_id:u}:{}};this.flagOutboundAfterStop(e,t,"stream_chunk_final",l,!0,0);const m=async()=>{const h=await this.handle.sendStreamChunkRequest(c,n);if(h.cmd!=="send_ack"){const g=h.payload;throw new Error(`final chunk rejected: cmd=${h.cmd} code=${g?.code??""} msg=${g?.msg??""}`)}};try{await m()}catch(h){if(E(h))f.warn("send-ctrl",`final chunk ACK timed out, retry request with same chunk_seq=${l} event=${e}`),await m();else throw f.warn("send-ctrl",`final chunk send failed (no resend) event=${e}: ${h}`),h}if(this.isEventClosed(e))throw new Error(`required agent output was rejected before terminal: event=${e}`)}async deliverAuxiliaryLargeText(e,t,s,n){if(!s||this.isEventClosed(e))return!1;if(this.resolveEventRuntimeConfig(e).responseDelivery==="single_message"&&e){const r=this.getDefaultQuotedMessageId(e),i=p(s);for(let l=0;l<i.length;l++)this.flagOutboundAfterStop(e,t,"aux_detail_msg",l+1,!1,i[l].length),this.handle.sendMsg({event_id:e,session_id:t,msg_type:1,content:i[l],...l===0&&r?{quoted_message_id:r}:{},client_msg_id:i.length>1?`${n}_p${l+1}`:n});return!0}const a=p(s);for(const r of a)this.sendStreamChunk(e,t,r,0,!1,n);return await this.sendFinalStreamChunkReliable(e,t,n,void 0,!1,!0),!0}coalesceStreamChunk(e,t,s,n,o,a){if(!s&&!n)return;const r=`${e}:${o??"default"}`;let i=this.streamCoalesce.get(r);if(i||(i={eventId:e,sessionId:t,clientMsgId:o,quotedMessageId:a,text:"",flushedOnce:!1},this.streamCoalesce.set(r,i)),s&&(i.text+=s),i.sessionId=t,o!==void 0&&(i.clientMsgId=o),!i.quotedMessageId&&a&&(i.quotedMessageId=a),n){this.flushCoalesce(r,!0);return}if(!i.flushedOnce||i.text.length>=_.STREAM_COALESCE_MAX_RUNES){this.flushCoalesce(r,!1);return}i.timer||(i.timer=setTimeout(()=>this.flushCoalesce(r,!1),this.streamCoalesceMs))}flushCoalesce(e,t){const s=this.streamCoalesce.get(e);if(!s)return;s.timer&&(clearTimeout(s.timer),s.timer=void 0);const n=s.text;s.text="",s.flushedOnce=!0,t&&this.streamCoalesce.delete(e),!(!n&&!t)&&this.emitStreamChunkParts(s.eventId,s.sessionId,n,0,t,s.clientMsgId,s.quotedMessageId)}flushCoalesceForEvent(e){const t=`${e}:`;for(const s of[...this.streamCoalesce.keys()])s.startsWith(t)&&(this.flushCoalesce(s,!1),this.streamCoalesce.delete(s))}emitStreamChunkParts(e,t,s,n,o,a,r){const i=s||(o?`
2
+ `:"");if(!i&&!o)return;const l=p(i,C);l.length===0&&l.push(i||`
3
+ `);const u=`${e}:${a??"default"}`;for(let c=0;c<l.length;c++){const m=c===l.length-1,h=this.chunkSeqMap.get(u)??0,g=c===0&&n>h?n:h+1;this.chunkSeqMap.set(u,g),this.handle.sendStreamChunk({event_id:e,session_id:t,delta_content:l[c],chunk_seq:g,is_finish:m&&o,...a?{client_msg_id:a}:{},...r?{quoted_message_id:r}:{}})}}sendEventResult(e,t,s,n){this.finalizeThinking(e,""),this.flushCoalesceForEvent(e);const o=this.ensureSingleMessageDelivery(e),a=(r,i=s,l=n)=>{r==="responded"&&this.rejectedEvents.has(e)&&(r="failed",l=l||"agent_output_rejected",i=i||"required agent output was rejected by the server"),this.markEventTerminal(e),this.handle.sendEventResult({event_id:e,status:r,...i?{msg:i}:{},...l?{code:l}:{},updated_at:Date.now()}),this.clearEventTrackingState(e)};if(!o){a(t);return}o.then(()=>a(t),r=>{const i=`final output delivery failed: ${r instanceof Error?r.message:String(r)}`;a(t==="responded"?"failed":t,t==="responded"?i:s,t==="responded"?"agent_output_delivery_failed":n)})}sendThinking(e,t,s){if(this.shouldDropThinkingDisplayEvent(e)||this.isEventClosed(e))return;this.flagOutboundAfterStop(e,t,"thinking",this.thinkingSeqMap.get(e)??0,!1,(s||"").length);const n=(this.thinkingSeqMap.get(e)??0)+1;this.thinkingSeqMap.set(e,n),this.thinkingSessionMap.set(e,t),this.handle.sendStreamChunk({event_id:e,session_id:t,delta_content:s,chunk_seq:n,is_finish:!1,client_msg_id:`${e}_thinking`,is_thinking:!0})}sendToolExecutionCard(e,t,s,n){if(this.shouldDropToolDisplayEvent(e)){f.info("send-ctrl",`[tool-card] DROP event=${e} session=${t} summary=${s.summaryText}`);return}const a=Date.now(),r=`${e}:${s.summaryText}:${s.detailText??""}`,i=this.recentToolCards.get(r);if(i!==void 0&&a-i<_.TOOL_CARD_DEDUP_MS){f.info("send-ctrl",`[tool-card] DEDUP event=${e} session=${t} summary=${s.summaryText}`);return}this.recentToolCards.set(r,a);const l={summary_text:s.summaryText};s.detailText&&(l.detail_text=s.detailText),f.info("send-ctrl",`[tool-card] SEND event=${e} session=${t} summary=${s.summaryText}`),this.handle.sendMsg({event_id:e,session_id:t,client_msg_id:n??`tool_${++this.toolCardSeq}_${Date.now()}`,msg_type:1,content:"",extra:{channel_data:{grix:{toolExecution:l}},agent_api_origin:!0}})}finalizeThinking(e,t){const s=this.thinkingSeqMap.get(e);s!==void 0&&(this.thinkingSeqMap.delete(e),t=t||this.thinkingSessionMap.get(e)||"",this.thinkingSessionMap.delete(e),t&&(this.isEventClosed(e)||this.handle.sendStreamChunk({event_id:e,session_id:t,delta_content:"",chunk_seq:s+1,is_finish:!0,client_msg_id:`${e}_thinking`,is_thinking:!0})))}bufferOnly(e,t,s,n,o){o=o??this.getDefaultQuotedMessageId(e),this.bufferStreamChunk(e,t,s,o)}bufferStreamChunk(e,t,s,n,o){const a=typeof o=="string"&&o.startsWith("reply_"),r=this.bufferedEventTexts.get(e);if(!r){this.bufferedEventTexts.set(e,{sessionId:t,text:s??"",quotedMessageId:n||void 0,replyReceived:a});return}a?r.replyReceived?s&&(r.text+=s):(r.text=s??"",r.replyReceived=!0):!r.replyReceived&&s&&(r.text+=s),!r.quotedMessageId&&n&&(r.quotedMessageId=n)}ensureSingleMessageDelivery(e,t){const s=this.singleMessageDeliveries.get(e);if(s)return s;const n=this.bufferedEventTexts.get(e);if(!n||(this.bufferedEventTexts.delete(e),!n.text))return;const o=(async()=>{const a={event_id:e,session_id:n.sessionId,content:n.text,client_msg_id:`agent_single_${e}`,...n.quotedMessageId?{quoted_message_id:n.quotedMessageId}:{}},r=async()=>{const i=t===void 0?await this.handle.sendText(a):await this.handle.sendText(a,t);if(i.cmd!=="send_ack"){const l=i.payload;throw new Error(`single-message output rejected: cmd=${i.cmd} code=${l?.code??""} msg=${l?.msg??""}`)}};try{await r()}catch(i){if(!E(i))throw i;f.warn("send-ctrl",`single-message ACK timed out, retry request with stable client_msg_id=${a.client_msg_id} event=${e}`),await r()}})();return this.singleMessageDeliveries.set(e,o),o}}function T(){const d=process.env.GRIX_STREAM_COALESCE_MS;if(d===void 0||d==="")return 500;const e=Number(d);return Number.isFinite(e)&&e>=0?Math.floor(e):500}function $(d,e){return e&&typeof e=="object"&&e.channel_data?.grix?.toolExecution?!0:/^\[tool\]/.test(d)||/^\[tool result\]/.test(d)}export{v as DEFAULT_QUOTE_TRIGGER_BY_ADAPTER,_ as SendController};
@@ -1 +1 @@
1
- import{readJSONFile as o,writeJSONFileAtomic as e}from"../util/json-file.js";function n(t){const r=o(t);return r&&typeof r=="object"&&"owners"in r&&Array.isArray(r.owners)?r.owners.filter(i=>typeof i=="string"&&i.trim().length>0):[]}async function s(t,r){await e(t,{owners:r})}export{n as readAllowlist,s as writeAllowlist};
1
+ import{readJSONFile as o,writeJSONFileAtomic as i}from"../util/json-file.js";function n(t){const r=o(t);return r&&typeof r=="object"&&"owners"in r&&Array.isArray(r.owners)?r.owners.filter(e=>typeof e=="string"&&e.trim().length>0):[]}async function s(t,r){await i(t,{owners:r})}export{n as readAllowlist,s as writeAllowlist};
@@ -1 +1 @@
1
- import{readdir as r,stat as m}from"node:fs/promises";import{join as l,extname as d}from"node:path";const x={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",md:"text/markdown",csv:"text/csv",json:"application/json",xml:"application/xml",yaml:"text/yaml",yml:"text/yaml",html:"text/html",css:"text/css",js:"text/javascript",ts:"text/typescript",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",gz:"application/gzip",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",mkv:"video/x-matroska",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac",aac:"audio/aac"};function n(a){const p=d(a).slice(1).toLowerCase();return x[p]}async function f(a,p=!1){const c=await r(a,{withFileTypes:!0}),s=[];for(const t of c){if(!p&&t.name.startsWith("."))continue;const i=l(a,t.name),e={id:i,name:t.name,is_directory:t.isDirectory()};try{if(t.isDirectory()){const o=await m(i);e.modified_at=o.mtime.toISOString()}else{const o=await m(i);e.size=o.size,e.modified_at=o.mtime.toISOString(),e.mime_type=n(t.name)}}catch{}s.push(e)}return s.sort((t,i)=>t.is_directory!==i.is_directory?t.is_directory?-1:1:t.name.localeCompare(i.name)),s}export{f as listFiles,n as resolveMimeType};
1
+ import{readdir as r,stat as m}from"node:fs/promises";import{join as l,extname as d}from"node:path";const x={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",md:"text/markdown",csv:"text/csv",json:"application/json",xml:"application/xml",yaml:"text/yaml",yml:"text/yaml",html:"text/html",css:"text/css",js:"text/javascript",ts:"text/typescript",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",gz:"application/gzip",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",mkv:"video/x-matroska",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac",aac:"audio/aac"};function n(a){const p=d(a).slice(1).toLowerCase();return x[p]}async function f(a,p=!1){const c=await r(a,{withFileTypes:!0}),s=[];for(const i of c){if(!p&&i.name.startsWith("."))continue;const t=l(a,i.name),e={id:t,name:i.name,is_directory:i.isDirectory()};try{if(i.isDirectory()){const o=await m(t);e.modified_at=o.mtime.toISOString()}else{const o=await m(t);e.size=o.size,e.modified_at=o.mtime.toISOString(),e.mime_type=n(i.name)}}catch{}s.push(e)}return s.sort((i,t)=>i.is_directory!==t.is_directory?i.is_directory?-1:1:i.name.localeCompare(t.name)),s}export{f as listFiles,n as resolveMimeType};
@@ -1,2 +1,2 @@
1
- import{mkdir as S}from"node:fs/promises";import{open as d,readFile as g,unlink as s}from"node:fs/promises";import{join as f}from"node:path";import{randomUUID as v}from"node:crypto";import{readJSONFile as k,writeJSONFileAtomic as c}from"../util/json-file.js";import{appendRotatingFileSync as w}from"../log/rotation.js";const l=20,p=3e4,y=5e3;class U{statePath;logPath;lockPath;rotationOptions;constructor(e,a,n=e+".lock",o={}){this.statePath=e,this.logPath=a,this.lockPath=n,this.rotationOptions=o}get filePath(){return this.statePath}async recordHookEvent(e){const a=P(e);await this.withStateLock(async n=>{n.recent_events.push(a),n.recent_events.sort((o,i)=>o.event_at-i.event_at),n.recent_events.length>l&&(n.recent_events=n.recent_events.slice(-l)),n.latest_event=a,n.updated_at=Date.now()}),this.appendEventLog(a)}async readState(){const e=k(this.statePath);return!e||typeof e!="object"?this.emptyState():this.normalizeState(e)}async reset(){await this.withStateLock(async()=>{await c(this.statePath,this.emptyState())})}emptyState(){return{schema_version:1,updated_at:0,latest_event:null,recent_events:[]}}normalizeState(e){const a=Array.isArray(e.recent_events)?e.recent_events:[];return{schema_version:1,updated_at:e.updated_at??0,latest_event:e.latest_event?_(e.latest_event):null,recent_events:a.filter(n=>typeof n=="object"&&n!==null).map(_)}}async withStateLock(e){await S(f(this.statePath,"..").replace(/\/[^/]+$/,""),{recursive:!0}).catch(()=>{});const a=Date.now()+y;let n=!1;for(;!n&&Date.now()<a;)try{await(await d(this.lockPath,"wx")).close(),n=!0}catch(o){if(o.code==="EEXIST"){const m=await g(this.lockPath,"utf8").catch(()=>""),r=Number(m);!isNaN(r)&&Date.now()-r>p?await s(this.lockPath).catch(()=>{}):await new Promise(u=>setTimeout(u,100))}else throw o}if(!n)throw new Error("hook-signal-store: lock acquisition timeout");try{await D(this.lockPath,String(Date.now()));const o=await this.readState(),i=await e(o);return await c(this.statePath,o),i}finally{await s(this.lockPath).catch(()=>{})}}appendEventLog(e){const a=E(e),n=`${new Date(e.event_at).toISOString()} ${a}
2
- `;try{w(this.logPath,n,this.rotationOptions)}catch{}}}function h(t){if(t!=null){if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}}function P(t){return{event_id:v(),hook_event_name:String(t.hook_event_name??""),event_at:Date.now(),detail:T(t),tool_input:h(t.tool_input)}}function _(t){return{event_id:String(t.event_id??""),hook_event_name:String(t.hook_event_name??""),event_at:t.event_at??0,detail:String(t.detail??""),tool_input:h(t.tool_input)}}function E(t){const e=t.hook_event_name,a=t.detail?`:${t.detail}`:"";return`${e}${a}`}function T(t){switch(String(t.hook_event_name??"")){case"SessionStart":return String(t.source??"");case"PreToolUse":case"PermissionRequest":case"PostToolUse":case"PostToolUseFailure":case"PermissionDenied":return String(t.tool_name??t.reason??"");case"Elicitation":return String(t.mode??"");case"ElicitationResult":return String(t.action??t.mode??"");case"Notification":return String(t.matcher??t.notification_type??t.type??"");case"StopFailure":return String(t.stop_reason??t.error??t.detail??"");case"Stop":return String(t.stop_reason??"");case"PreCompact":case"PostCompact":return String(t.trigger??"");case"ConfigChange":return String(t.source??"");default:return""}}async function D(t,e){const{writeFile:a}=await import("node:fs/promises");await a(t,e,"utf8")}export{U as HookSignalStore};
1
+ import{mkdir as S}from"node:fs/promises";import{open as d,readFile as g,unlink as s}from"node:fs/promises";import{join as v}from"node:path";import{randomUUID as f}from"node:crypto";import{readJSONFile as p,writeJSONFileAtomic as c}from"../util/json-file.js";import{appendRotatingFileSync as w}from"../log/rotation.js";const l=20,k=3e4,P=5e3;class b{statePath;logPath;lockPath;rotationOptions;constructor(e,a,n=e+".lock",o={}){this.statePath=e,this.logPath=a,this.lockPath=n,this.rotationOptions=o}get filePath(){return this.statePath}async recordHookEvent(e){const a=y(e);await this.withStateLock(async n=>{n.recent_events.push(a),n.recent_events.sort((o,r)=>o.event_at-r.event_at),n.recent_events.length>l&&(n.recent_events=n.recent_events.slice(-l)),n.latest_event=a,n.updated_at=Date.now()}),this.appendEventLog(a)}async readState(){const e=p(this.statePath);return!e||typeof e!="object"?this.emptyState():this.normalizeState(e)}async reset(){await this.withStateLock(async()=>{await c(this.statePath,this.emptyState())})}emptyState(){return{schema_version:1,updated_at:0,latest_event:null,recent_events:[]}}normalizeState(e){const a=Array.isArray(e.recent_events)?e.recent_events:[];return{schema_version:1,updated_at:e.updated_at??0,latest_event:e.latest_event?_(e.latest_event):null,recent_events:a.filter(n=>typeof n=="object"&&n!==null).map(_)}}async withStateLock(e){await S(v(this.statePath,"..").replace(/\/[^/]+$/,""),{recursive:!0}).catch(()=>{});const a=Date.now()+P;let n=!1;for(;!n&&Date.now()<a;)try{await(await d(this.lockPath,"wx")).close(),n=!0}catch(o){if(o.code==="EEXIST"){const m=await g(this.lockPath,"utf8").catch(()=>""),i=Number(m);!isNaN(i)&&Date.now()-i>k?await s(this.lockPath).catch(()=>{}):await new Promise(u=>setTimeout(u,100))}else throw o}if(!n)throw new Error("hook-signal-store: lock acquisition timeout");try{await O(this.lockPath,String(Date.now()));const o=await this.readState(),r=await e(o);return await c(this.statePath,o),r}finally{await s(this.lockPath).catch(()=>{})}}appendEventLog(e){const a=E(e),n=`${new Date(e.event_at).toISOString()} ${a}
2
+ `;try{w(this.logPath,n,this.rotationOptions)}catch{}}}function h(t){if(t!=null){if(typeof t=="string")return t;try{return JSON.stringify(t)}catch{return String(t)}}}function y(t){return{event_id:f(),hook_event_name:String(t.hook_event_name??""),event_at:Date.now(),detail:T(t),tool_input:h(t.tool_input)}}function _(t){return{event_id:String(t.event_id??""),hook_event_name:String(t.hook_event_name??""),event_at:t.event_at??0,detail:String(t.detail??""),tool_input:h(t.tool_input)}}function E(t){const e=t.hook_event_name,a=t.detail?`:${t.detail}`:"";return`${e}${a}`}function T(t){switch(String(t.hook_event_name??"")){case"SessionStart":return String(t.source??"");case"UserPromptSubmit":return D(String(t.prompt??""));case"PreToolUse":case"PermissionRequest":case"PostToolUse":case"PostToolUseFailure":case"PermissionDenied":return String(t.tool_name??t.reason??"");case"Elicitation":return String(t.mode??"");case"ElicitationResult":return String(t.action??t.mode??"");case"Notification":return String(t.matcher??t.notification_type??t.type??"");case"StopFailure":return String(t.stop_reason??t.error??t.detail??"");case"Stop":return String(t.stop_reason??"");case"PreCompact":case"PostCompact":return String(t.trigger??"");case"ConfigChange":return String(t.source??"");default:return""}}async function O(t,e){const{writeFile:a}=await import("node:fs/promises");await a(t,e,"utf8")}function D(t){const e=/<channel\b[^>]*\sevent_id="([^"]*)"/g;let a="",n;for(;(n=e.exec(t))!==null;)a=n[1];if(a)return a;try{const o=JSON.parse(t);return o?.meta?.event_id?String(o.meta.event_id):""}catch{return""}}export{b as HookSignalStore,D as extractGrixEventIdFromPrompt};
@@ -1,2 +1,2 @@
1
- import{accessSync as l,constants as w}from"node:fs";import{spawn as p,execSync as h}from"node:child_process";import{isAbsolute as P,join as m}from"node:path";const S=process.platform==="win32"?";":":";function C(t){try{return l(t,w.X_OK),!0}catch{return!1}}function H(t,e){const n=String(t??"").trim();if(!n||P(n))return n;const i=process.platform==="win32",r=String(e??process.env.PATH??""),s=[],o=new Set;for(const c of r.split(S)){const d=c.trim();if(!d)continue;if(i){const u=m(d,n+".cmd");o.has(u)||(o.add(u),s.push(u))}const a=m(d,n);o.has(a)||(o.add(a),s.push(a))}for(const c of s)if(C(c))return c;return console.warn(`[spawn:resolve] command="${n}" not found in PATH. candidates tried: [${s.join(", ")}] PATH=${r.substring(0,500)}${r.length>500?"...(truncated)":""}`),n}function N(t,e,n={}){const{cwd:i,env:r,...s}=n,o={stdio:s.stdio??["pipe","pipe","pipe"],env:r??{...process.env},cwd:i,windowsHide:!0,...s};if(process.platform==="win32"&&/\.(cmd|bat)$/i.test(t)){const d=process.env.ComSpec||"cmd.exe",a=`""${t}" ${e.join(" ")}"`;return{process:p(d,["/d","/s","/c",a],{...o,windowsVerbatimArguments:!0}),isCmdSpawn:!0}}return{process:p(t,e,{...o,detached:o.detached??process.platform!=="win32"}),isCmdSpawn:!1}}async function $(t){return!t||t<=0?[]:process.platform==="win32"?y(t):new Promise(e=>{const n=p("pgrep",["-g",String(t)],{stdio:"pipe",timeout:3e3}),i=[];n.stdout?.on("data",r=>{r.toString().split(`
2
- `).forEach(s=>{const o=parseInt(s.trim(),10);!isNaN(o)&&o>0&&i.push(o)})}),n.on("close",()=>e(i)),n.on("error",()=>e([]))})}function y(t){return new Promise(e=>{const n=s=>{e(s.split(/\r?\n/).map(o=>parseInt(o.trim(),10)).filter(o=>!isNaN(o)&&o>0))},i=p("wmic",["process","where",`(ParentProcessId=${t})`,"get","ProcessId"],{stdio:"pipe",windowsHide:!0});let r="";i.stdout?.on("data",s=>{r+=s.toString()}),i.on("close",s=>{if(s===0){n(r);return}f(t).then(e)}),i.on("error",()=>{f(t).then(e)})})}function f(t){return new Promise(e=>{const n=`${process.env.SystemRoot||"C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`,i=p(n,["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",`(Get-CimInstance Win32_Process -Filter 'ParentProcessId=${t}').ProcessId`],{stdio:"pipe",windowsHide:!0});let r="";i.stdout?.on("data",s=>{r+=s.toString()}),i.on("close",()=>{e(r.split(/\r?\n/).map(s=>parseInt(s.trim(),10)).filter(s=>!isNaN(s)&&s>0))}),i.on("error",()=>e([]))})}async function v(t,e=[]){return(await $(t)).some(i=>!e.includes(i))}function b(t,e="SIGTERM"){if(t.pid){if(process.platform==="win32"){try{h(`taskkill /pid ${t.pid} /T /F`,{stdio:"pipe",timeout:5e3,windowsHide:!0})}catch{t.kill(e)}return}try{process.kill(-t.pid,e)}catch{t.kill(e)}}}export{v as hasChildProcesses,b as killProcessGroup,$ as listGroupPids,H as resolveCommandPath,N as spawnCommand};
1
+ import{accessSync as w,constants as h}from"node:fs";import{spawn as d,execSync as P}from"node:child_process";import{isAbsolute as S,join as m}from"node:path";const $=process.platform==="win32"?";":":";function x(t){try{return w(t,h.X_OK),!0}catch{return!1}}function H(t,e){const n=String(t??"").trim();if(!n||S(n))return n;const r=process.platform==="win32",i=String(e??process.env.PATH??""),s=[],o=new Set;for(const c of i.split($)){const a=c.trim();if(!a)continue;if(r){const u=m(a,n+".cmd");o.has(u)||(o.add(u),s.push(u))}const p=m(a,n);o.has(p)||(o.add(p),s.push(p))}for(const c of s)if(x(c))return c;return console.warn(`[spawn:resolve] command="${n}" not found in PATH. candidates tried: [${s.join(", ")}] PATH=${i.substring(0,500)}${i.length>500?"...(truncated)":""}`),n}function C(t,e=process.platform){return e==="win32"&&/\.(cmd|bat)$/i.test(t)}function v(t){return t.length>0&&!/[\s"^&|<>()%!]/.test(t)?t:`"${t.replace(/(\\*)"/g,'$1$1\\"').replace(/(\\*)$/,"$1$1")}"`}function f(t,e){const n=e.map(v).join(" ");return n?`""${t}" ${n}"`:`""${t}""`}function b(t,e,n=process.platform){return C(t,n)?{command:process.env.ComSpec||"cmd.exe",args:["/d","/s","/c",f(t,e)],windowsVerbatimArguments:!0}:{command:t,args:e,windowsVerbatimArguments:!1}}function N(t,e,n=process.platform){return n!=="win32"?{command:t,args:e,windowsVerbatimArguments:!1}:{command:process.env.ComSpec||"cmd.exe",args:["/d","/s","/c",f(t,e)],windowsVerbatimArguments:!0}}function V(t,e,n={}){const{cwd:r,env:i,...s}=n,o={stdio:s.stdio??["pipe","pipe","pipe"],env:i??{...process.env},cwd:r,windowsHide:!0,...s},c=b(t,e);return c.windowsVerbatimArguments?{process:d(c.command,c.args,{...o,windowsVerbatimArguments:!0}),isCmdSpawn:!0}:{process:d(t,e,{...o,detached:o.detached??process.platform!=="win32"}),isCmdSpawn:!1}}async function g(t){return!t||t<=0?[]:process.platform==="win32"?I(t):new Promise(e=>{const n=d("pgrep",["-g",String(t)],{stdio:"pipe",timeout:3e3}),r=[];n.stdout?.on("data",i=>{i.toString().split(`
2
+ `).forEach(s=>{const o=parseInt(s.trim(),10);!isNaN(o)&&o>0&&r.push(o)})}),n.on("close",()=>e(r)),n.on("error",()=>e([]))})}function I(t){return new Promise(e=>{const n=s=>{e(s.split(/\r?\n/).map(o=>parseInt(o.trim(),10)).filter(o=>!isNaN(o)&&o>0))},r=d("wmic",["process","where",`(ParentProcessId=${t})`,"get","ProcessId"],{stdio:"pipe",windowsHide:!0});let i="";r.stdout?.on("data",s=>{i+=s.toString()}),r.on("close",s=>{if(s===0){n(i);return}l(t).then(e)}),r.on("error",()=>{l(t).then(e)})})}function l(t){return new Promise(e=>{const n=`${process.env.SystemRoot||"C:\\Windows"}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe`,r=d(n,["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",`(Get-CimInstance Win32_Process -Filter 'ParentProcessId=${t}').ProcessId`],{stdio:"pipe",windowsHide:!0});let i="";r.stdout?.on("data",s=>{i+=s.toString()}),r.on("close",()=>{e(i.split(/\r?\n/).map(s=>parseInt(s.trim(),10)).filter(s=>!isNaN(s)&&s>0))}),r.on("error",()=>e([]))})}async function k(t,e=[]){return(await g(t)).some(r=>!e.includes(r))}function T(t,e="SIGTERM"){if(t.pid){if(process.platform==="win32"){try{P(`taskkill /pid ${t.pid} /T /F`,{stdio:"pipe",timeout:5e3,windowsHide:!0})}catch{t.kill(e)}return}try{process.kill(-t.pid,e)}catch{t.kill(e)}}}export{f as buildWindowsCmdLine,k as hasChildProcesses,C as isWindowsShimPath,T as killProcessGroup,g as listGroupPids,v as quoteWindowsCmdArg,H as resolveCommandPath,b as resolveShimInvocation,N as resolveWindowsExecInvocation,V as spawnCommand};
@@ -1,2 +1,2 @@
1
- import{execFile as c}from"node:child_process";import{accessSync as b,constants as H,existsSync as A,statSync as T}from"node:fs";import{join as h,dirname as g,basename as $,delimiter as p}from"node:path";import{promisify as l}from"node:util";import{log as a}from"../log/logger.js";const I=3e3,C=5e3,d="__GRIX_SHELL_PATH__";function x(t,e){const n=[".cmd",".bat",".exe",""];for(const r of t)if(r)for(const i of n){const s=h(r,`${e}${i}`);if(A(s))return s}return null}const M=1e4,P={cache:null,inflight:null},S={cache:null,inflight:null},_={cache:null,inflight:null};let w=0;function q(){w++;for(const t of[P,S,_])t.cache=null,t.inflight=null}function m(t,e){if(t.cache&&Date.now()-t.cache.at<M)return Promise.resolve(t.cache.value);if(t.inflight)return t.inflight;const n=w,r=e().then(i=>(w===n&&(t.cache={value:i,at:Date.now()}),t.inflight===r&&(t.inflight=null),i),i=>{throw t.inflight===r&&(t.inflight=null),i});return t.inflight=r,r}function D(){return h(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe")}function W(){return m(P,async()=>{const t=l(c),e=async n=>{try{const{stdout:r}=await t(D(),["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",`[Environment]::GetEnvironmentVariable('Path','${n}')`],{timeout:5e3,encoding:"utf-8",windowsHide:!0});return r.split(";").map(i=>i.trim()).filter(Boolean)}catch(r){return a.warn("cli-probe",`\u8BFB\u53D6\u6CE8\u518C\u8868 ${n} PATH \u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),[]}};return[...await e("User"),...await e("Machine")]})}async function F(t){if(process.platform!=="win32")return null;const e=await W(),n=x(e,t)??await v(t);return n&&E(g(n)),n}function O(t){try{return T(t).isFile()?(b(t,H.X_OK),!0):!1}catch{return!1}}function y(t,e){for(const n of t){if(!n)continue;const r=h(n,e);if(O(r))return r}return null}const G=new Set(["sh","bash","zsh","ksh","dash","ash"]);function R(){return m(S,async()=>{const t=process.env.SHELL||"/bin/sh";if(!G.has($(t)))return a.info("cli-probe",`\u767B\u5F55 shell ${t} \u4E0D\u652F\u6301 -lic\uFF0C\u8DF3\u8FC7 shell PATH \u8BFB\u53D6`),[];const e=l(c);try{const n=e(t,["-lic",`printf '\\n${d}%s\\n' "$PATH"`],{timeout:C,killSignal:"SIGKILL",encoding:"utf-8"});n.child?.stdin?.end();const{stdout:r}=await n,i=r.split(/\r?\n/).reverse().find(s=>s.startsWith(d));return i?i.slice(d.length).split(p).map(s=>s.trim()).filter(Boolean):[]}catch(n){return a.warn("cli-probe",`\u8BFB\u53D6\u767B\u5F55 shell PATH \u5931\u8D25: ${n instanceof Error?n.message:String(n)}`),[]}})}function k(){return m(_,async()=>{const t=l(c),e=process.platform==="win32";try{const{stdout:n}=await t(e?"cmd.exe":"npm",e?["/c","npm","prefix","-g"]:["prefix","-g"],{timeout:5e3,killSignal:"SIGKILL",encoding:"utf-8",...e?{windowsHide:!0}:{}});return n.trim()||null}catch{return null}})}async function v(t){const e=await k();return e?process.platform==="win32"?x([e],t):y([h(e,"bin"),e],t):null}async function N(t){if(process.platform==="win32")return null;const e=await R(),n=y(e,t)??await v(t);return a.info("cli-probe",`\u767B\u5F55 shell PATH / npm \u5168\u5C40 bin \u515C\u5E95\u67E5\u627E ${t}: \u7ED3\u679C=${n??"\u672A\u627E\u5230"}`),n&&E(g(n)),n}function E(t){const e=process.env.PATH??"",n=process.platform==="win32"?(r,i)=>r.toLowerCase()===i.toLowerCase():(r,i)=>r===i;e.split(p).some(r=>n(r,t))||(process.env.PATH=e?`${e}${p}${t}`:t,a.info("cli-probe",`\u5DF2\u5C06 ${t} \u8FFD\u52A0\u5230\u5F53\u524D\u8FDB\u7A0B PATH\uFF08\u5B89\u88C5\u540E\u81EA\u6108\uFF09`))}async function B(t){const e=l(c),n=process.platform==="win32",r=n?"where":"which";try{const{stdout:i}=await e(r,[t],{timeout:3e3,encoding:"utf-8"}),s=i.trim().split(/\r?\n/).map(o=>o.trim()).filter(Boolean);if(s.length>0){if(n){const o=s.find(f=>/\.(cmd|bat)$/i.test(f));if(o)return o;const u=s.find(f=>/\.exe$/i.test(f));return u||s[0]}return s[0]}return await L(t)}catch{return await L(t)}}function L(t){return process.platform==="win32"?F(t):N(t)}async function J(t,e=["--version"],n=I){const r=l(c),i=process.platform==="win32";try{const s=i&&/\s/.test(t)&&!t.startsWith('"')?`"${t}"`:t,{stdout:o,stderr:u}=await r(s,e,{timeout:n,encoding:"utf-8",...i?{shell:!0}:{}});return{version:(o||u||"").trim().split(`
2
- `)[0]?.trim()||null||null}}catch(s){const o=s;return o.killed||o.code==="ETIMEDOUT"?{version:null,error:{code:"version_timeout",message:"version check timed out"}}:{version:null,error:{code:"cli_error",message:o.message??String(s)}}}}export{y as findPosixExecutableInDirs,x as findWindowsExecutableInDirs,J as getCliVersion,q as invalidateCliPathCache,B as resolveCliPath,N as resolvePosixInstalledCli,v as resolveViaNpmGlobalBin,F as resolveWindowsInstalledCli};
1
+ import{execFile as c}from"node:child_process";import{accessSync as L,constants as A,existsSync as H,statSync as I}from"node:fs";import{join as f,dirname as g,basename as T,delimiter as d}from"node:path";import{promisify as l}from"node:util";import{resolveWindowsExecInvocation as $}from"../runtime/spawn.js";import{log as a}from"../log/logger.js";const C=3e3,M=5e3,p="__GRIX_SHELL_PATH__";function x(n,e){const t=[".cmd",".bat",".exe",""];for(const r of n)if(r)for(const i of t){const o=f(r,`${e}${i}`);if(H(o))return o}return null}const D=1e4,P={cache:null,inflight:null},S={cache:null,inflight:null},_={cache:null,inflight:null};let w=0;function B(){w++;for(const n of[P,S,_])n.cache=null,n.inflight=null}function m(n,e){if(n.cache&&Date.now()-n.cache.at<D)return Promise.resolve(n.cache.value);if(n.inflight)return n.inflight;const t=w,r=e().then(i=>(w===t&&(n.cache={value:i,at:Date.now()}),n.inflight===r&&(n.inflight=null),i),i=>{throw n.inflight===r&&(n.inflight=null),i});return n.inflight=r,r}function W(){return f(process.env.SystemRoot||"C:\\Windows","System32","WindowsPowerShell","v1.0","powershell.exe")}function F(){return m(P,async()=>{const n=l(c),e=async t=>{try{const{stdout:r}=await n(W(),["-NoProfile","-NonInteractive","-WindowStyle","Hidden","-Command",`[Environment]::GetEnvironmentVariable('Path','${t}')`],{timeout:5e3,encoding:"utf-8",windowsHide:!0});return r.split(";").map(i=>i.trim()).filter(Boolean)}catch(r){return a.warn("cli-probe",`\u8BFB\u53D6\u6CE8\u518C\u8868 ${t} PATH \u5931\u8D25: ${r instanceof Error?r.message:String(r)}`),[]}};return[...await e("User"),...await e("Machine")]})}async function O(n){if(process.platform!=="win32")return null;const e=await F(),t=x(e,n)??await y(n);return t&&E(g(t)),t}function G(n){try{return I(n).isFile()?(L(n,A.X_OK),!0):!1}catch{return!1}}function v(n,e){for(const t of n){if(!t)continue;const r=f(t,e);if(G(r))return r}return null}const R=new Set(["sh","bash","zsh","ksh","dash","ash"]);function k(){return m(S,async()=>{const n=process.env.SHELL||"/bin/sh";if(!R.has(T(n)))return a.info("cli-probe",`\u767B\u5F55 shell ${n} \u4E0D\u652F\u6301 -lic\uFF0C\u8DF3\u8FC7 shell PATH \u8BFB\u53D6`),[];const e=l(c);try{const t=e(n,["-lic",`printf '\\n${p}%s\\n' "$PATH"`],{timeout:M,killSignal:"SIGKILL",encoding:"utf-8"});t.child?.stdin?.end();const{stdout:r}=await t,i=r.split(/\r?\n/).reverse().find(o=>o.startsWith(p));return i?i.slice(p.length).split(d).map(o=>o.trim()).filter(Boolean):[]}catch(t){return a.warn("cli-probe",`\u8BFB\u53D6\u767B\u5F55 shell PATH \u5931\u8D25: ${t instanceof Error?t.message:String(t)}`),[]}})}function N(){return m(_,async()=>{const n=l(c),e=process.platform==="win32";try{const{stdout:t}=await n(e?"cmd.exe":"npm",e?["/c","npm","prefix","-g"]:["prefix","-g"],{timeout:5e3,killSignal:"SIGKILL",encoding:"utf-8",...e?{windowsHide:!0}:{}});return t.trim()||null}catch{return null}})}async function y(n){const e=await N();return e?process.platform==="win32"?x([e],n):v([f(e,"bin"),e],n):null}async function V(n){if(process.platform==="win32")return null;const e=await k(),t=v(e,n)??await y(n);return a.info("cli-probe",`\u767B\u5F55 shell PATH / npm \u5168\u5C40 bin \u515C\u5E95\u67E5\u627E ${n}: \u7ED3\u679C=${t??"\u672A\u627E\u5230"}`),t&&E(g(t)),t}function E(n){const e=process.env.PATH??"",t=process.platform==="win32"?(r,i)=>r.toLowerCase()===i.toLowerCase():(r,i)=>r===i;e.split(d).some(r=>t(r,n))||(process.env.PATH=e?`${e}${d}${n}`:n,a.info("cli-probe",`\u5DF2\u5C06 ${n} \u8FFD\u52A0\u5230\u5F53\u524D\u8FDB\u7A0B PATH\uFF08\u5B89\u88C5\u540E\u81EA\u6108\uFF09`))}async function J(n){const e=l(c),t=process.platform==="win32",r=t?"where":"which";try{const{stdout:i}=await e(r,[n],{timeout:3e3,encoding:"utf-8"}),o=i.trim().split(/\r?\n/).map(s=>s.trim()).filter(Boolean);if(o.length>0){if(t){const s=o.find(u=>/\.(cmd|bat)$/i.test(u));if(s)return s;const h=o.find(u=>/\.exe$/i.test(u));return h||o[0]}return o[0]}return await b(n)}catch{return await b(n)}}function b(n){return process.platform==="win32"?O(n):V(n)}async function Q(n,e=["--version"],t=C){const r=l(c);try{const i=$(n,e),{stdout:o,stderr:s}=await r(i.command,i.args,{timeout:t,encoding:"utf-8",windowsVerbatimArguments:i.windowsVerbatimArguments});return{version:(o||s||"").trim().split(`
2
+ `)[0]?.trim()||null||null}}catch(i){const o=i;return o.killed||o.code==="ETIMEDOUT"?{version:null,error:{code:"version_timeout",message:"version check timed out"}}:{version:null,error:{code:"cli_error",message:o.message??String(i)}}}}export{v as findPosixExecutableInDirs,x as findWindowsExecutableInDirs,Q as getCliVersion,B as invalidateCliPathCache,J as resolveCliPath,V as resolvePosixInstalledCli,y as resolveViaNpmGlobalBin,O as resolveWindowsInstalledCli};
package/dist/log.js CHANGED
@@ -1,3 +1,3 @@
1
- import{createWriteStream as g,mkdirSync as l,existsSync as f}from"node:fs";import{join as t}from"node:path";import{homedir as m}from"node:os";const i=t(m(),".grix"),s={base:i,config:t(i,"config"),log:t(i,"log"),data:t(i,"data")};function S(){for(const o of Object.values(s))f(o)||l(o,{recursive:!0})}let a=null;function $(){const o=new Date().toISOString().slice(0,10),r=t(s.log,`grix-acp-${o}.log`);a=g(r,{flags:"a"})}function c(){return new Date().toISOString().slice(11,19)}const u={info(o,r,...n){const e=`${c()} [${o}] ${r}${n.length?" "+n.map(String).join(" "):""}`;console.log(e),a?.write(e+`
2
- `)},error(o,r,...n){const e=`${c()} [${o}] ERROR ${r}${n.length?" "+n.map(String).join(" "):""}`;console.error(e),a?.write(e+`
1
+ import{createWriteStream as g,mkdirSync as l,existsSync as f}from"node:fs";import{join as i}from"node:path";import{homedir as m}from"node:os";const n=i(m(),".grix"),s={base:n,config:i(n,"config"),log:i(n,"log"),data:i(n,"data")};function S(){for(const o of Object.values(s))f(o)||l(o,{recursive:!0})}let a=null;function $(){const o=new Date().toISOString().slice(0,10),r=i(s.log,`grix-acp-${o}.log`);a=g(r,{flags:"a"})}function c(){return new Date().toISOString().slice(11,19)}const u={info(o,r,...t){const e=`${c()} [${o}] ${r}${t.length?" "+t.map(String).join(" "):""}`;console.log(e),a?.write(e+`
2
+ `)},error(o,r,...t){const e=`${c()} [${o}] ERROR ${r}${t.length?" "+t.map(String).join(" "):""}`;console.error(e),a?.write(e+`
3
3
  `)}};export{s as GRIX_PATHS,S as ensureGrixDirs,$ as initLogger,u as log};
@@ -1 +1 @@
1
- import*as i from"node:net";const e={bind:"127.0.0.1",port:0,endpoint:"/mcp",sessionTimeoutMs:18e5,invokeTimeoutMs:3e4};function n(o){const u={bind:o?.bind??e.bind,port:o?.port??e.port,endpoint:o?.endpoint??e.endpoint,sessionTimeoutMs:o?.sessionTimeoutMs??e.sessionTimeoutMs,invokeTimeoutMs:o?.invokeTimeoutMs??e.invokeTimeoutMs,allowedOrigins:o?.allowedOrigins,allowedHosts:o?.allowedHosts};return s(u.bind),u.port!==0&&t(u.port),r(u.sessionTimeoutMs),u}function s(o){if(!o||!i.isIPv4(o)&&!i.isIPv6(o))throw new Error(`\u914D\u7F6E\u6821\u9A8C\u5931\u8D25: bind \u5730\u5740 "${o}" \u4E0D\u662F\u5408\u6CD5\u7684 IPv4 \u6216 IPv6 \u5730\u5740`)}function t(o){if(!Number.isInteger(o)||o<1||o>65535)throw new Error(`\u914D\u7F6E\u6821\u9A8C\u5931\u8D25: port \u503C ${o} \u4E0D\u5728\u5408\u6CD5\u8303\u56F4 1-65535 \u5185\u6216\u4E0D\u662F\u6574\u6570`)}function r(o){if(!Number.isInteger(o)||o<1e3||o>864e5)throw new Error(`\u914D\u7F6E\u6821\u9A8C\u5931\u8D25: session_timeout_ms \u503C ${o} \u4E0D\u5728\u5408\u6CD5\u8303\u56F4 1000-86400000 \u5185`)}export{n as createDefaultGatewayConfig};
1
+ import*as n from"node:net";const i={bind:"127.0.0.1",port:0,endpoint:"/mcp",sessionTimeoutMs:18e5,invokeTimeoutMs:3e4};function s(u){const e={bind:u?.bind??i.bind,port:u?.port??i.port,endpoint:u?.endpoint??i.endpoint,sessionTimeoutMs:u?.sessionTimeoutMs??i.sessionTimeoutMs,invokeTimeoutMs:u?.invokeTimeoutMs??i.invokeTimeoutMs,allowedOrigins:u?.allowedOrigins,allowedHosts:u?.allowedHosts};return t(e.bind),e.port!==0&&o(e.port),r(e.sessionTimeoutMs),e}function t(u){if(!u||!n.isIPv4(u)&&!n.isIPv6(u))throw new Error(`\u914D\u7F6E\u6821\u9A8C\u5931\u8D25: bind \u5730\u5740 "${u}" \u4E0D\u662F\u5408\u6CD5\u7684 IPv4 \u6216 IPv6 \u5730\u5740`)}function o(u){if(!Number.isInteger(u)||u<1||u>65535)throw new Error(`\u914D\u7F6E\u6821\u9A8C\u5931\u8D25: port \u503C ${u} \u4E0D\u5728\u5408\u6CD5\u8303\u56F4 1-65535 \u5185\u6216\u4E0D\u662F\u6574\u6570`)}function r(u){if(!Number.isInteger(u)||u<1e3||u>864e5)throw new Error(`\u914D\u7F6E\u6821\u9A8C\u5931\u8D25: session_timeout_ms \u503C ${u} \u4E0D\u5728\u5408\u6CD5\u8303\u56F4 1000-86400000 \u5185`)}export{s as createDefaultGatewayConfig};
@@ -1 +1 @@
1
- const r=3e4;class c{connectionManager;onDisconnected;bindings=new Map;constructor(n,i){this.connectionManager=n,this.onDisconnected=i}async bind(n,i){if(this.bindings.has(n))throw new Error(`Session ${n} is already bound to a connection`);const e=await this.connectWithTimeout(i),t=[],s=e.onDisconnected(()=>{this.removeBinding(n),this.onDisconnected(n)});return t.push(s),this.bindings.set(n,{sessionId:n,handle:e,subscriptions:t}),e}getHandle(n){return this.bindings.get(n)?.handle}unbind(n){const i=this.bindings.get(n);if(i){this.bindings.delete(n);for(const e of i.subscriptions)e();i.handle.disconnect()}}unbindAll(){const n=[...this.bindings.keys()];for(const i of n)this.unbind(i)}connectWithTimeout(n){return new Promise((i,e)=>{let t=!1;const s=setTimeout(()=>{t||(t=!0,e(new Error("Connection bind timeout after 30000ms")))},3e4);this.connectionManager.connect({agentId:n.agentId,apiKey:n.apiKey,url:n.wsUrl,clientType:n.clientType,capabilities:["agent_invoke"],adapterHint:`${n.clientType}/base`},{maxRetries:0}).then(o=>{t?o.disconnect():(t=!0,clearTimeout(s),i(o))}).catch(o=>{t||(t=!0,clearTimeout(s),e(o))})})}removeBinding(n){const i=this.bindings.get(n);if(i){this.bindings.delete(n);for(const e of i.subscriptions)e()}}}export{c as ConnectionBindingImpl};
1
+ const a=3e4;class c{connectionManager;onDisconnected;bindings=new Map;constructor(n,i){this.connectionManager=n,this.onDisconnected=i}async bind(n,i){if(this.bindings.has(n))throw new Error(`Session ${n} is already bound to a connection`);const e=await this.connectWithTimeout(i),t=[],s=e.onDisconnected(()=>{this.removeBinding(n),this.onDisconnected(n)});return t.push(s),this.bindings.set(n,{sessionId:n,handle:e,subscriptions:t}),e}getHandle(n){return this.bindings.get(n)?.handle}unbind(n){const i=this.bindings.get(n);if(i){this.bindings.delete(n);for(const e of i.subscriptions)e();i.handle.disconnect()}}unbindAll(){const n=[...this.bindings.keys()];for(const i of n)this.unbind(i)}connectWithTimeout(n){return new Promise((i,e)=>{let t=!1;const s=setTimeout(()=>{t||(t=!0,e(new Error("Connection bind timeout after 30000ms")))},3e4);this.connectionManager.connect({agentId:n.agentId,apiKey:n.apiKey,url:n.wsUrl,clientType:n.clientType,capabilities:["agent_invoke"],adapterHint:`${n.clientType}/base`},{maxRetries:0}).then(o=>{t?o.disconnect():(t=!0,clearTimeout(s),i(o))}).catch(o=>{t||(t=!0,clearTimeout(s),e(o))})})}removeBinding(n){const i=this.bindings.get(n);if(i){this.bindings.delete(n);for(const e of i.subscriptions)e()}}}export{c as ConnectionBindingImpl};
@@ -1 +1 @@
1
- function a(e){const t=new Set([`http://127.0.0.1:${e.serverPort}`,`http://localhost:${e.serverPort}`,...e.allowedOrigins]),o=new Set([`127.0.0.1:${e.serverPort}`,`localhost:${e.serverPort}`,...e.allowedHosts]);return{validateRequest(s){const r=i(s,t);if(!r.ok)return r;const n=l(s,o);return n.ok?{ok:!0}:n}}}function i(e,t){const o=e.headers.origin;return o?t.has(o)?{ok:!0}:{ok:!1,statusCode:403,message:`Origin not allowed: ${o}`}:{ok:!0}}function l(e,t){const o=e.headers.host;return o?t.has(o)?{ok:!0}:{ok:!1,statusCode:403,message:`Host not allowed: ${o}`}:{ok:!1,statusCode:403,message:"Missing Host header"}}export{a as createSecurityPolicy};
1
+ function a(o){const e=new Set([`http://127.0.0.1:${o.serverPort}`,`http://localhost:${o.serverPort}`,...o.allowedOrigins]),t=new Set([`127.0.0.1:${o.serverPort}`,`localhost:${o.serverPort}`,...o.allowedHosts]);return{validateRequest(s){const r=i(s,e);if(!r.ok)return r;const n=l(s,t);return n.ok?{ok:!0}:n}}}function i(o,e){const t=o.headers.origin;return t?e.has(t)?{ok:!0}:{ok:!1,statusCode:403,message:`Origin not allowed: ${t}`}:{ok:!0}}function l(o,e){const t=o.headers.host;return t?e.has(t)?{ok:!0}:{ok:!1,statusCode:403,message:`Host not allowed: ${t}`}:{ok:!1,statusCode:403,message:"Missing Host header"}}export{a as createSecurityPolicy};
@@ -1 +1 @@
1
- import{toolCallToInvoke as i}from"../../core/mcp/tools.js";import{ToolRegistryImpl as l}from"./tool-registry.js";import{validateToolArgs as a}from"./tool-schemas.js";import{isEventTool as p,executeEventTool as d}from"./event-tool-executor.js";class y{registry;constructor(){this.registry=new l}async execute(t,e,r,n){if(!this.registry.hasTool(e))return this.errorResult(`\u672A\u77E5\u5DE5\u5177: ${e}`);const s=a(e,r);if(!s.valid)return this.errorResult(`\u53C2\u6570\u6821\u9A8C\u5931\u8D25: ${s.error}`);if(t.status!=="ready")return this.errorResult(`\u8FDE\u63A5\u4E0D\u53EF\u7528: \u5F53\u524D\u72B6\u6001\u4E3A ${t.status}`);if(p(e))return this.executeEventTool(t,e,r);const o=i(e,r);try{const u=await t.agentInvoke(o.action,o.params,n);return this.normalizeResult(u)}catch(u){const c=u instanceof Error?u.message:String(u);return c.toLowerCase().includes("timeout")?this.errorResult(`\u8C03\u7528\u8D85\u65F6: ${c}`):this.errorResult(`\u8C03\u7528\u5931\u8D25: ${c}`)}}normalizeResult(t){if(t==null||typeof t!="object")return this.successResult(t??null);const e=t,r=typeof e.code=="number"?e.code:0;if(r===0){const s="data"in e?e.data:null;return this.successResult(s??null)}const n=typeof e.msg=="string"?e.msg:"\u672A\u77E5\u9519\u8BEF";return this.errorResult(`\u4E0A\u6E38\u9519\u8BEF [code=${r}]: ${n}`)}successResult(t){return{content:[{type:"text",text:JSON.stringify(t)}],isError:!1}}errorResult(t){return{content:[{type:"text",text:t}],isError:!0}}async executeEventTool(t,e,r){return e==="grix_access_control"?this.executeAccessControl(t,r):d(t,e,r)}async executeAccessControl(t,e){const r=String(e.action??""),n={pair_approve:"pair_approve",pair_deny:"pair_deny",allow_sender:"sender_allow",remove_sender:"sender_remove",set_policy:"policy_set"}[r];if(!n)return this.errorResult(`\u672A\u77E5 access_control action: ${r}`);const s={};e.code!=null&&(s.code=e.code),e.sender_id!=null&&(s.sender_id=e.sender_id),e.policy!=null&&(s.policy=e.policy);try{const o=await t.agentInvoke("claude_access_control",{verb:n,payload:s},3e4);return this.successResult(o)}catch(o){const u=o instanceof Error?o.message:String(o);return this.errorResult(`access_control \u8C03\u7528\u5931\u8D25: ${u}`)}}}export{y as ToolExecutorImpl};
1
+ import{toolCallToInvoke as i}from"../../core/mcp/tools.js";import{ToolRegistryImpl as l}from"./tool-registry.js";import{validateToolArgs as a}from"./tool-schemas.js";import{isEventTool as p,executeEventTool as d}from"./event-tool-executor.js";class y{registry;constructor(){this.registry=new l}async execute(r,e,t,n){if(!this.registry.hasTool(e))return this.errorResult(`\u672A\u77E5\u5DE5\u5177: ${e}`);const s=a(e,t);if(!s.valid)return this.errorResult(`\u53C2\u6570\u6821\u9A8C\u5931\u8D25: ${s.error}`);if(r.status!=="ready")return this.errorResult(`\u8FDE\u63A5\u4E0D\u53EF\u7528: \u5F53\u524D\u72B6\u6001\u4E3A ${r.status}`);if(p(e))return this.executeEventTool(r,e,t);const o=i(e,t);try{const u=await r.agentInvoke(o.action,o.params,n);return this.normalizeResult(u)}catch(u){const c=u instanceof Error?u.message:String(u);return c.toLowerCase().includes("timeout")?this.errorResult(`\u8C03\u7528\u8D85\u65F6: ${c}`):this.errorResult(`\u8C03\u7528\u5931\u8D25: ${c}`)}}normalizeResult(r){if(r==null||typeof r!="object")return this.successResult(r??null);const e=r,t=typeof e.code=="number"?e.code:0;if(t===0){const s="data"in e?e.data:null;return this.successResult(s??null)}const n=typeof e.msg=="string"?e.msg:"\u672A\u77E5\u9519\u8BEF";return this.errorResult(`\u4E0A\u6E38\u9519\u8BEF [code=${t}]: ${n}`)}successResult(r){return{content:[{type:"text",text:JSON.stringify(r)}],isError:!1}}errorResult(r){return{content:[{type:"text",text:r}],isError:!0}}async executeEventTool(r,e,t){return e==="grix_access_control"?this.executeAccessControl(r,t):d(r,e,t)}async executeAccessControl(r,e){const t=String(e.action??""),n={pair_approve:"pair_approve",pair_deny:"pair_deny",allow_sender:"sender_allow",remove_sender:"sender_remove",set_policy:"policy_set"}[t];if(!n)return this.errorResult(`\u672A\u77E5 access_control action: ${t}`);const s={};e.code!=null&&(s.code=e.code),e.sender_id!=null&&(s.sender_id=e.sender_id),e.policy!=null&&(s.policy=e.policy);try{const o=await r.agentInvoke("claude_access_control",{verb:n,payload:s},3e4);return this.successResult(o)}catch(o){const u=o instanceof Error?o.message:String(o);return this.errorResult(`access_control \u8C03\u7528\u5931\u8D25: ${u}`)}}}export{y as ToolExecutorImpl};
@@ -1 +1 @@
1
- import{TOOLS as s,EVENT_TOOLS as t}from"../../core/mcp/tools.js";const e=new Set(["grix_query","grix_group","grix_message_send","grix_message_unsend","grix_admin"]),r=new Set(["grix_reply","grix_complete","grix_event_ack","grix_composing","grix_access_control","grix_status"]);class a{tools;toolMap;constructor(){this.tools=[...s.filter(o=>e.has(o.name)),...t.filter(o=>r.has(o.name))],this.toolMap=new Map(this.tools.map(o=>[o.name,o]))}getTools(){return this.tools}getTool(o){return this.toolMap.get(o)}hasTool(o){return this.toolMap.has(o)}}export{a as ToolRegistryImpl};
1
+ import{TOOLS as o,EVENT_TOOLS as s}from"../../core/mcp/tools.js";const e=new Set(["grix_query","grix_group","grix_message_send","grix_message_unsend","grix_admin"]),r=new Set(["grix_reply","grix_complete","grix_event_ack","grix_composing","grix_access_control","grix_status"]);class a{tools;toolMap;constructor(){this.tools=[...o.filter(t=>e.has(t.name)),...s.filter(t=>r.has(t.name))],this.toolMap=new Map(this.tools.map(t=>[t.name,t]))}getTools(){return this.tools}getTool(t){return this.toolMap.get(t)}hasTool(t){return this.toolMap.has(t)}}export{a as ToolRegistryImpl};
@@ -1 +1 @@
1
- const o={required:["action"],properties:{action:{type:"string",enum:["contact_search","session_search","message_history","message_search"]},id:{type:"string"},keyword:{type:"string",maxLength:200},limit:{type:"integer",minimum:1,maximum:100},offset:{type:"integer",minimum:0},sessionId:{type:"string"},beforeId:{type:"string"}}},a={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"}}},p={required:["sessionId","content"],properties:{sessionId:{type:"string"},content:{type:"string",maxLength:1e4},msgType:{type:"integer"},quotedMessageId:{type:"string"},threadId:{type:"string"}}},m={required:["sessionId","msgId"],properties:{sessionId:{type:"string"},msgId:{type:"string"}}},g={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"}}},y={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"}}},d={required:["event_id","status"],properties:{event_id:{type:"string"},status:{type:"string",enum:["responded","canceled","failed"]},msg:{type:"string",maxLength:500}}},c={required:["event_id"],properties:{event_id:{type:"string"},session_id:{type:"string"}}},l={required:["session_id","active"],properties:{session_id:{type:"string"},active:{type:"boolean"},event_id:{type:"string"}}},_={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"]}}},f={required:[],properties:{}},C={grix_query:o,grix_group:a,grix_message_send:p,grix_message_unsend:m,grix_admin:g,grix_reply:y,grix_complete:d,grix_event_ack:c,grix_composing:l,grix_access_control:_,grix_status:f};function B(u,t){const e=C[u];if(!e)return{valid:!1,error:`\u672A\u77E5\u5DE5\u5177: ${u}`};for(const i of e.required)if(t[i]===void 0||t[i]===null)return{valid:!1,error:`\u7F3A\u5C11\u5FC5\u586B\u53C2\u6570: ${i}`};for(const[i,r]of Object.entries(t)){if(r==null)continue;const n=e.properties[i];if(!n)continue;const s=$(i,r,n);if(s)return{valid:!1,error:s}}return{valid:!0}}function $(u,t,e){switch(e.type){case"string":if(typeof t!="string")return`\u53C2\u6570 ${u} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B string\uFF0C\u5B9E\u9645 ${typeof t}`;if(e.maxLength!==void 0&&t.length>e.maxLength)return`\u53C2\u6570 ${u} \u8D85\u8FC7\u6700\u5927\u957F\u5EA6 ${e.maxLength}\uFF0C\u5B9E\u9645 ${t.length}`;if(e.enum&&!e.enum.includes(t))return`\u53C2\u6570 ${u} \u503C "${t}" \u4E0D\u5728\u5141\u8BB8\u8303\u56F4 [${e.enum.join(", ")}]`;break;case"integer":if(typeof t!="number"||!Number.isInteger(t))return`\u53C2\u6570 ${u} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B integer\uFF0C\u5B9E\u9645 ${typeof t=="number"?"\u6D6E\u70B9\u6570":typeof t}`;if(e.minimum!==void 0&&t<e.minimum)return`\u53C2\u6570 ${u} \u503C ${t} \u5C0F\u4E8E\u6700\u5C0F\u503C ${e.minimum}`;if(e.maximum!==void 0&&t>e.maximum)return`\u53C2\u6570 ${u} \u503C ${t} \u5927\u4E8E\u6700\u5927\u503C ${e.maximum}`;if(e.enum&&!e.enum.includes(t))return`\u53C2\u6570 ${u} \u503C ${t} \u4E0D\u5728\u5141\u8BB8\u8303\u56F4 [${e.enum.join(", ")}]`;break;case"boolean":if(typeof t!="boolean")return`\u53C2\u6570 ${u} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B boolean\uFF0C\u5B9E\u9645 ${typeof t}`;break;case"array":if(!Array.isArray(t))return`\u53C2\u6570 ${u} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B array\uFF0C\u5B9E\u9645 ${typeof t}`;if(e.maxItems!==void 0&&t.length>e.maxItems)return`\u53C2\u6570 ${u} \u8D85\u8FC7\u6700\u5927\u5143\u7D20\u6570 ${e.maxItems}\uFF0C\u5B9E\u9645 ${t.length}`;if(e.items)for(let i=0;i<t.length;i++){const r=t[i];if(e.items.type==="string"&&typeof r!="string")return`\u53C2\u6570 ${u}[${i}] \u7C7B\u578B\u9519\u8BEF: \u671F\u671B string\uFF0C\u5B9E\u9645 ${typeof r}`;if(e.items.type==="integer"){if(typeof r!="number"||!Number.isInteger(r))return`\u53C2\u6570 ${u}[${i}] \u7C7B\u578B\u9519\u8BEF: \u671F\u671B integer\uFF0C\u5B9E\u9645 ${typeof r}`;if(e.items.enum&&!e.items.enum.includes(r))return`\u53C2\u6570 ${u}[${i}] \u503C ${r} \u4E0D\u5728\u5141\u8BB8\u8303\u56F4 [${e.items.enum.join(", ")}]`}}break}}export{B as validateToolArgs};
1
+ const o={required:["action"],properties:{action:{type:"string",enum:["contact_search","session_search","message_history","message_search"]},id:{type:"string"},keyword:{type:"string",maxLength:200},limit:{type:"integer",minimum:1,maximum:100},offset:{type:"integer",minimum:0},sessionId:{type:"string"},beforeId:{type:"string"}}},a={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"}}},p={required:["sessionId","content"],properties:{sessionId:{type:"string"},content:{type:"string",maxLength:1e4},msgType:{type:"integer"},quotedMessageId:{type:"string"},threadId:{type:"string"}}},m={required:["sessionId","msgId"],properties:{sessionId:{type:"string"},msgId:{type:"string"}}},g={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"}}},y={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"}}},d={required:["event_id","status"],properties:{event_id:{type:"string"},status:{type:"string",enum:["responded","canceled","failed"]},msg:{type:"string",maxLength:500}}},c={required:["event_id"],properties:{event_id:{type:"string"},session_id:{type:"string"}}},l={required:["session_id","active"],properties:{session_id:{type:"string"},active:{type:"boolean"},event_id:{type:"string"}}},_={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"]}}},f={required:[],properties:{}},C={grix_query:o,grix_group:a,grix_message_send:p,grix_message_unsend:m,grix_admin:g,grix_reply:y,grix_complete:d,grix_event_ack:c,grix_composing:l,grix_access_control:_,grix_status:f};function B(r,t){const e=C[r];if(!e)return{valid:!1,error:`\u672A\u77E5\u5DE5\u5177: ${r}`};for(const i of e.required)if(t[i]===void 0||t[i]===null)return{valid:!1,error:`\u7F3A\u5C11\u5FC5\u586B\u53C2\u6570: ${i}`};for(const[i,u]of Object.entries(t)){if(u==null)continue;const n=e.properties[i];if(!n)continue;const s=$(i,u,n);if(s)return{valid:!1,error:s}}return{valid:!0}}function $(r,t,e){switch(e.type){case"string":if(typeof t!="string")return`\u53C2\u6570 ${r} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B string\uFF0C\u5B9E\u9645 ${typeof t}`;if(e.maxLength!==void 0&&t.length>e.maxLength)return`\u53C2\u6570 ${r} \u8D85\u8FC7\u6700\u5927\u957F\u5EA6 ${e.maxLength}\uFF0C\u5B9E\u9645 ${t.length}`;if(e.enum&&!e.enum.includes(t))return`\u53C2\u6570 ${r} \u503C "${t}" \u4E0D\u5728\u5141\u8BB8\u8303\u56F4 [${e.enum.join(", ")}]`;break;case"integer":if(typeof t!="number"||!Number.isInteger(t))return`\u53C2\u6570 ${r} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B integer\uFF0C\u5B9E\u9645 ${typeof t=="number"?"\u6D6E\u70B9\u6570":typeof t}`;if(e.minimum!==void 0&&t<e.minimum)return`\u53C2\u6570 ${r} \u503C ${t} \u5C0F\u4E8E\u6700\u5C0F\u503C ${e.minimum}`;if(e.maximum!==void 0&&t>e.maximum)return`\u53C2\u6570 ${r} \u503C ${t} \u5927\u4E8E\u6700\u5927\u503C ${e.maximum}`;if(e.enum&&!e.enum.includes(t))return`\u53C2\u6570 ${r} \u503C ${t} \u4E0D\u5728\u5141\u8BB8\u8303\u56F4 [${e.enum.join(", ")}]`;break;case"boolean":if(typeof t!="boolean")return`\u53C2\u6570 ${r} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B boolean\uFF0C\u5B9E\u9645 ${typeof t}`;break;case"array":if(!Array.isArray(t))return`\u53C2\u6570 ${r} \u7C7B\u578B\u9519\u8BEF: \u671F\u671B array\uFF0C\u5B9E\u9645 ${typeof t}`;if(e.maxItems!==void 0&&t.length>e.maxItems)return`\u53C2\u6570 ${r} \u8D85\u8FC7\u6700\u5927\u5143\u7D20\u6570 ${e.maxItems}\uFF0C\u5B9E\u9645 ${t.length}`;if(e.items)for(let i=0;i<t.length;i++){const u=t[i];if(e.items.type==="string"&&typeof u!="string")return`\u53C2\u6570 ${r}[${i}] \u7C7B\u578B\u9519\u8BEF: \u671F\u671B string\uFF0C\u5B9E\u9645 ${typeof u}`;if(e.items.type==="integer"){if(typeof u!="number"||!Number.isInteger(u))return`\u53C2\u6570 ${r}[${i}] \u7C7B\u578B\u9519\u8BEF: \u671F\u671B integer\uFF0C\u5B9E\u9645 ${typeof u}`;if(e.items.enum&&!e.items.enum.includes(u))return`\u53C2\u6570 ${r}[${i}] \u503C ${u} \u4E0D\u5728\u5141\u8BB8\u8303\u56F4 [${e.items.enum.join(", ")}]`}}break}}export{B as validateToolArgs};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "grix-connector",
3
- "version": "4.3.0",
3
+ "version": "4.3.1",
4
4
  "description": "Connect local AI coding agents (Claude, Codex, Gemini, Qwen, DeepSeek, Cursor, OpenCode, Pi, OpenHuman, Reasonix) to the Grix scheduling platform. Also serves as an OpenClaw plugin for Grix channel transport.",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",