grix-connector 5.0.0 → 5.1.0
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.
- package/dist/adapter/pi/pi-adapter.js +8 -7
- package/dist/assets/dsh-bridge/{grix-dsh-bridge-5.0.0.tgz → grix-dsh-bridge-5.1.0.tgz} +0 -0
- package/dist/assets/dsh-bridge/manifest.json +5 -5
- package/dist/bridge/bridge.js +3 -2
- package/dist/bridge/send-controller.js +3 -3
- package/dist/core/aibot/client.js +2 -2
- package/dist/core/protocol/protocol-text.js +1 -1
- package/dist/manager.js +1 -1
- package/openclaw-plugin/index.js +10 -4
- package/package.json +1 -1
|
@@ -1,13 +1,14 @@
|
|
|
1
|
-
import{EventEmitter as y}from"node:events";import{stat as C}from"node:fs/promises";import{mkdirSync as B,writeFileSync as G,unlinkSync as D,statSync as v,existsSync as S}from"node:fs";import{join as u,resolve as F,delimiter as w}from"node:path";import{fileURLToPath as I}from"node:url";import{tmpdir as O,homedir as b}from"node:os";import{resolveCommandPath as N,spawnCommand as L,killProcessGroup as _,hasChildProcesses as j}from"../../core/runtime/spawn.js";import{InternalApiServer as z}from"../../core/mcp/internal-api-server.js";import{TOOLS as E}from"../../core/mcp/tools.js";import{IdentityInjector as q}from"../shared/identity-injector.js";import{compactToolInputForWire as J}from"../shared/tool-wire-payload.js";import{syncDefaultSkillsToDir as K}from"../../default-skills/index.js";import{PiTransport as U}from"./pi-transport.js";import{log as o}from"../../core/log/index.js";import{scanSkills as H}from"../claude/skill-scanner.js";import{listLivingDescendants as X,countLivingDescendantsOutsideBaseline as Y}from"../cursor/living-descendants.js";import{SessionBindingStore as V}from"../../core/persistence/session-binding-store.js";import{AgentGlobalConfigStore as W}from"../../core/persistence/agent-global-config-store.js";import{splitTextForAibotProtocol as Q}from"../../core/protocol/index.js";import{InboundMessageIdInjector as Z}from"../shared/inbound-message-id-injector.js";import{buildSimpleProbeReport as tt}from"../shared/probe-util.js";import{piGrixProviderId as et,removePiGrixProvider as it,writePiGrixProvider as st}from"./pi-provider-config.js";import{agentIdOf as nt}from"../shared/native-provider-config.js";import{writeOmpMcpEntry as rt,recordOmpMcpEntryPid as ot,removeOmpMcpEntry as at}from"./omp-mcp-config.js";import{PI_GRIX_TOOLS_READY_PREFIX as P}from"./pi-grix-tools-extension.js";function dt(c){return nt(c)==="omp"}function lt(c){return process.platform!=="win32"?"PATH":Object.keys(c).find(t=>t.toLowerCase()==="path")??"PATH"}function ct(c){const t=lt(c),e=String(c[t]??""),i=process.platform==="win32"?"bun.exe":"bun";if(e.split(w).some(r=>r.trim()&&S(u(r.trim(),i))))return c;const n=u(b(),".bun","bin");return S(u(n,i))?(o.info("pi-adapter",`bun \u4E0D\u5728\u5F53\u524D PATH\uFF0C\u8865\u4E0A\u9ED8\u8BA4\u5B89\u88C5\u76EE\u5F55: ${n}`),{...c,[t]:e?`${n}${w}${e}`:n}):c}class ht extends y{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 pt=12e4,T=90*1e3,$=1800*1e3;function A(c){try{return process.kill(c,0),!0}catch(t){return t.code==="EPERM"}}const ut=500,mt=2e3,x=3,ft=500,gt=1e4;function R(c){return new Promise(t=>setTimeout(t,c))}function vt(c){const t=new Set,e=[];for(const i of c){const s=i.provider?.trim();!s||t.has(s)||(t.add(s),e.push({id:s,display_name:s}))}return e}function m(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 M extends y{type="pi";config;callbacks;process=null;transport=new U;alive=!1;stopped=!1;internalApi=null;mcpConfigPath=null;piGrixToolsExtensionPath=null;piGrixToolsReady=!1;piGrixToolsReadyError=null;piGrixToolsStderrBuffer="";cwdMcpJsonDir=null;cwdMcpJsonKey=null;identity;inboundMessageIds=new Z;piSessionPath=null;activeEventId=null;activeSessionId=null;activeAuditCapture=null;completedAuditBoundaries=new Map;isStreaming=!1;abortBarrier=null;promptGeneration=0;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;descendantBaseline;composingSessionId=null;composingInterval=null;doneGuardTimer=null;bindingStore=null;globalConfigStore=null;modelSelectionRevision=0;initializationPromise=null;aibotSessionId="";sessionReadyPromise=null;provider;agentName="";clientType="";constructor(t,e){super(),this.config=t,this.callbacks=e,this.identity=new q("pi-adapter",e.getAgentProfile);const i=t.options??{};this.aibotSessionId=String(i.aibotSessionId??"").trim(),this.agentName=String(i.agentName??"").trim(),this.clientType=String(i.clientType??"").trim().toLowerCase(),this.provider=i.provider,this.bindingStore=i.bindingStore instanceof V?i.bindingStore:null,this.globalConfigStore=i.globalConfigStore instanceof W?i.globalConfigStore:null,this.bindingStore&&this.aibotSessionId&&(this.piSessionPath=this.bindingStore.getPiSessionPath(this.aibotSessionId)??null)}isOmp(t=this.config.command||"pi"){return this.clientType?this.clientType==="omp":dt(t)}resolvePiConfigDir(){return String(this.config.env?.PI_CODING_AGENT_DIR??"").trim()||u(b(),".pi","agent")}start(){return this.initializationPromise=this.initializeSession(),this.initializationPromise}async initializeSession(){const t=this.resolveInitialModel();if(await this.startInternalApi(),await this.spawnPi(),await this.ensureSessionReady(),t)try{await this.setModelSelection(t.provider,t.modelId,!1)}catch(e){o.warn("pi-adapter",`Failed to restore model selection: ${e instanceof Error?e.message:String(e)}`)}o.info("pi-adapter",`Ready (pid=${this.process?.pid})`),await this.syncModelBinding()}async syncModelBinding(){if(!this.aibotSessionId)return;const t=this.modelSelectionRevision;for(let e=1;e<=x;e++)try{const[i,s]=await Promise.all([this.transport.send("get_available_models"),this.transport.send("get_state")]);if(t!==this.modelSelectionRevision)return;const n=i.data?.models;if(!n||n.length===0){if(e<x){await R(ft);continue}o.warn("pi-adapter",`syncModelBinding: empty model list after ${x} attempts, giving up`);return}const r=s.data?.model,a=this.bindingStore?.get(this.aibotSessionId);s.success&&r?.provider&&r.id&&!(a?.piProviderId&&a.piModelId)&&this.bindingStore?.setPiModel(this.aibotSessionId,r.provider,r.id);const d={available_models:n.map(p=>({id:p.id,display_name:p.name??p.id,...p.provider?{provider:p.provider}:{}}))},h=vt(n);h.length>0&&(d.available_providers=h),r?.id&&(d.model_id=r.id),r?.provider&&(d.provider_id=r.provider,d.model_provider=r.provider),this.callbacks.sendUpdateBindingCard(this.aibotSessionId,this.isStreaming?"composing":"ready",this.resolveCwd(),d),o.info("pi-adapter",`synced model binding: ${n.length} models, current=${r?.id??"unknown"} (attempt ${e})`);return}catch(i){o.warn("pi-adapter",`syncModelBinding failed (non-fatal): ${i instanceof Error?i.message:String(i)}`);return}}resolveInitialModel(){const t=this.bindingStore?.get(this.aibotSessionId);if(t?.piProviderId&&t.piModelId)return{provider:t.piProviderId,modelId:t.piModelId};if(this.piSessionPath)return;const e=this.globalConfigStore?.get(this.agentName);if(e?.piProviderId&&e.piModelId)return{provider:e.piProviderId,modelId:e.piModelId}}async setModelSelection(t,e,i){const s=await this.transport.send("set_model",{provider:t,modelId:e});if(!s.success)throw new Error(s.error||"set_model failed");this.modelSelectionRevision++,this.aibotSessionId&&this.bindingStore?.setPiModel(this.aibotSessionId,t,e),i&&this.agentName&&this.globalConfigStore?.set(this.agentName,{piProviderId:t,piModelId:e})}async currentModel(){try{return(await this.transport.send("get_state")).data?.model??null}catch{return null}}async stop(){if(this.stopped=!0,this.promptGeneration++,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{D(this.mcpConfigPath)}catch{}this.mcpConfigPath=null}if(this.cwdMcpJsonDir&&this.cwdMcpJsonKey){const t=this.cwdMcpJsonDir,e=this.cwdMcpJsonKey;this.cwdMcpJsonDir=null,this.cwdMcpJsonKey=null;try{await at(t,e)}catch(i){o.warn("pi-adapter",`\u6E05\u7406 omp cwd .mcp.json \u6761\u76EE\u5931\u8D25 key=${e}: ${i instanceof Error?i.message:String(i)}`)}}if(this.process){const t=this.process;try{_(t,"SIGTERM")}catch{}const e=setTimeout(()=>{try{_(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 ht(t.adapterSessionId),i=this.buildPromptTextFromRequest(t);return this.ensureSessionReady().then(()=>this.transport.send("prompt",{message:i})).then(s=>{s.success||e.emitDone({status:"failed",error:s.error})}).catch(s=>{e.emitError(s instanceof Error?s:new Error(String(s)))}),e}async cancel(t){try{await this.transport.send("abort")}catch{}}deliverInboundEvent(t){const{event_id:e,session_id:i,content:s}=t,n=++this.promptGeneration,r=this.buildPromptText(t);if(this.isStreaming){if(this.activeEventId&&this.activeEventId!==e){const a=this.activeEventId;o.info("pi-adapter",`steer: cancel ${a} -> ${e}`),this.flushTextBuffer(),this.callbacks.sendEventResult(a,"canceled","steered to new event"),this.activeAuditCapture?.eventId===a&&(this.snapshotAuditBoundary(a),this.emit("eventDone",a))}this.activeEventId=e,this.activeSessionId=i,this.resetRunStreamState(),this.startComposing(i,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.sendInboundPrompt(t,n,{message:r,streamingBehavior:"steer"})}else o.info("pi-adapter",`prompt: event=${e} session=${i}`),this.activeEventId=e,this.activeSessionId=i,this.isStreaming=!0,this.resetRunStreamState(),this.startComposing(i,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.sendInboundPrompt(t,n,{message:r})}sendInboundPrompt(t,e,i){const s=t.event_id,n=()=>!this.stopped&&this.promptGeneration===e&&this.activeEventId===s;(async()=>{if(this.abortBarrier&&await this.abortBarrier,!n())return;this.beginAuditCapture(t);const a=await this.transport.send("prompt",i);if(!a.success)throw new Error(a.error||"prompt rejected")})().catch(a=>{if(!n())return;const d=a instanceof Error?a.message:String(a);o.error("pi-adapter",`prompt error event=${s}: ${d}`),this.isStreaming=!1,this.cancelDoneGuard(),this.stopComposing(),this.stopIdleTimer(),this.clearActive(),this.callbacks.sendEventResult(s,"failed",d)})}beginAbortBarrier(){if(this.abortBarrier)return;const t=Promise.resolve().then(()=>this.transport.send("abort")).then(e=>{if(!e.success)throw new Error(e.error||"abort rejected")});this.abortBarrier=t,t.then(()=>{this.abortBarrier===t&&(this.abortBarrier=null)},e=>{o.error("pi-adapter",`abort failed: ${e}`)})}deliverStopEvent(t,e){if(this.activeEventId===t){o.info("pi-adapter",`stop: event=${t}, releasing busy immediately`),this.promptGeneration++,this.beginAbortBarrier(),this.cancelDoneGuard(),this.flushTextBuffer();const i=this.nextStreamSeq(),s=this.activeClientMsgId??void 0;this.callbacks.sendStreamChunk(t,this.activeSessionId??"","",i,!0,s),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.clearActive(),this.callbacks.sendEventResult(t,"canceled","stopped by user")}}async handleLocalAction(t){const e=t.action_id;switch(t.action_type){case"set_model":{const i=t.params??{},s=(i.modelId??i.model_id??"").trim();if(!s)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_model","model_id is required"),{handled:!0,kind:"set_model_error"};try{await this.initializationPromise;let n=(i.provider_id??i.provider??i.model_provider)?.trim();if(!n){const d=((await this.transport.send("get_available_models")).data?.models??[]).filter(h=>h.id===s&&h.provider?.trim());if(d.length>1){const h=(await this.currentModel())?.provider?.trim();n=d.find(p=>p.provider?.trim()===h)?.provider?.trim()}n=n??d[0]?.provider?.trim()}return n?(await this.setModelSelection(n,s,!0),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"model_set",provider:n,modelId:s}),this.syncModelBinding(),{handled:!0,kind:"set_model"}):(this.callbacks.sendLocalActionResult(e,"failed",void 0,"model_not_found",`No provider for model: ${s}`),{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"set_provider":{const i=t.params??{},s=(i.provider_id??i.provider??"").trim();if(!s)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_provider","provider_id is required"),{handled:!0,kind:"set_provider_error"};try{await this.initializationPromise;const a=((await this.transport.send("get_available_models")).data?.models??[]).filter(p=>p.provider?.trim()===s);if(a.length===0)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"provider_not_found",`No models for provider: ${s}`),{handled:!0,kind:"set_provider_error"};const d=(await this.currentModel())?.id,h=a.find(p=>p.id===d)?.id??a[0].id;return await this.setModelSelection(s,h,!0),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"provider_set",provider:s,modelId:h}),this.syncModelBinding(),{handled:!0,kind:"set_provider"}}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_provider_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_provider_error"}}}case"get_context":try{const i=await this.transport.send("get_state");return this.callbacks.sendLocalActionResult(e,"ok",{state:i}),{handled:!0,kind:"get_context"}}catch(i){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"get_context_error",i instanceof Error?i.message:String(i)),{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||!this.isOmp())return null;const t=F(I(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?j(t,[t]):!1}async probe(t){const e=this.getStatus();return{...await tt(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=v(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,i){try{if(t==="model"&&e.trim()&&await this.initializationPromise,!this.alive)return{status:"failed",message:"Pi process not running"};switch(t){case"model":{const s=e.trim();if(s){const a=s.indexOf(":");if(a<1)return{status:"failed",message:"Format: provider:model_id"};const d=s.slice(0,a),h=s.slice(a+1);return h?(await this.setModelSelection(d,h,!0),this.syncModelBinding(),{status:"ok",message:`Model set to ${d}:${h}`}):{status:"failed",message:"Format: provider:model_id"}}const r=(await this.transport.send("get_available_models"))?.data?.models;return r&&r.length>0?{status:"ok",message:`Available models:
|
|
2
|
-
${r.map(d=>` ${d.provider??"unknown"}:${d.id} (${d.name??d.id})`).join(`
|
|
3
|
-
|
|
4
|
-
`)
|
|
5
|
-
|
|
1
|
+
import{EventEmitter as w}from"node:events";import{stat as D}from"node:fs/promises";import{mkdirSync as F,writeFileSync as O,unlinkSync as N,statSync as S,existsSync as I}from"node:fs";import{join as m,resolve as L,delimiter as _}from"node:path";import{fileURLToPath as y}from"node:url";import{tmpdir as j,homedir as b}from"node:os";import{resolveCommandPath as z,spawnCommand as K,killProcessGroup as P,hasChildProcesses as q}from"../../core/runtime/spawn.js";import{InternalApiServer as J}from"../../core/mcp/internal-api-server.js";import{TOOLS as E}from"../../core/mcp/tools.js";import{IdentityInjector as U}from"../shared/identity-injector.js";import{compactToolInputForWire as Y}from"../shared/tool-wire-payload.js";import{syncDefaultSkillsToDir as H}from"../../default-skills/index.js";import{PiTransport as X}from"./pi-transport.js";import{log as a}from"../../core/log/index.js";import{scanSkills as V}from"../claude/skill-scanner.js";import{listLivingDescendants as W,countLivingDescendantsOutsideBaseline as Q}from"../cursor/living-descendants.js";import{SessionBindingStore as Z}from"../../core/persistence/session-binding-store.js";import{AgentGlobalConfigStore as tt}from"../../core/persistence/agent-global-config-store.js";import{splitTextForAibotProtocol as et}from"../../core/protocol/index.js";import{InboundMessageIdInjector as it}from"../shared/inbound-message-id-injector.js";import{buildSimpleProbeReport as st}from"../shared/probe-util.js";import{piGrixProviderId as rt,removePiGrixProvider as nt,writePiGrixProvider as ot}from"./pi-provider-config.js";import{agentIdOf as at}from"../shared/native-provider-config.js";import{writeOmpMcpEntry as dt,recordOmpMcpEntryPid as lt,removeOmpMcpEntry as ct}from"./omp-mcp-config.js";import{PI_GRIX_TOOLS_READY_PREFIX as T}from"./pi-grix-tools-extension.js";function ht(c){return at(c)==="omp"}function pt(c){return process.platform!=="win32"?"PATH":Object.keys(c).find(t=>t.toLowerCase()==="path")??"PATH"}function ut(c){const t=pt(c),e=String(c[t]??""),i=process.platform==="win32"?"bun.exe":"bun";if(e.split(_).some(n=>n.trim()&&I(m(n.trim(),i))))return c;const r=m(b(),".bun","bin");return I(m(r,i))?(a.info("pi-adapter",`bun \u4E0D\u5728\u5F53\u524D PATH\uFF0C\u8865\u4E0A\u9ED8\u8BA4\u5B89\u88C5\u76EE\u5F55: ${r}`),{...c,[t]:e?`${r}${_}${e}`:r}):c}class mt extends w{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 ft=12e4,$=90*1e3,R=1800*1e3;function A(c){try{return process.kill(c,0),!0}catch(t){return t.code==="EPERM"}}const gt=500,vt=2e3,x=3,St=500,It=1e4,yt=[6e3,15e3,3e4];function M(c){return new Promise(t=>setTimeout(t,c))}function Et(c){const t=new Set,e=[];for(const i of c){const s=i.provider?.trim();!s||t.has(s)||(t.add(s),e.push({id:s,display_name:s}))}return e}function C(c){if(!c)return{mode:"none"};const t=c.baseUrl?.trim(),e=c.apiKey?.trim(),i=c.providerId?.trim(),s=c.model?.trim();return t&&s&&(!i||e)?{mode:"relay"}:i&&s?{mode:"native",providerId:i,modelId:s}:{mode:"none"}}function k(c){return c.trim().toLowerCase().replace(/_/g,"-")}function f(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 B extends w{type="pi";config;callbacks;process=null;transport=new X;alive=!1;stopped=!1;internalApi=null;mcpConfigPath=null;piGrixToolsExtensionPath=null;piGrixToolsReady=!1;piGrixToolsReadyError=null;piGrixToolsStderrBuffer="";cwdMcpJsonDir=null;cwdMcpJsonKey=null;identity;inboundMessageIds=new it;piSessionPath=null;activeEventId=null;activeSessionId=null;activeAuditCapture=null;completedAuditBoundaries=new Map;isStreaming=!1;abortBarrier=null;promptGeneration=0;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;descendantBaseline;composingSessionId=null;composingInterval=null;doneGuardTimer=null;bindingStore=null;globalConfigStore=null;modelSelectionRevision=0;catalogResyncTimers=[];catalogSignature="";initializationPromise=null;aibotSessionId="";sessionReadyPromise=null;provider;agentName="";clientType="";constructor(t,e){super(),this.config=t,this.callbacks=e,this.identity=new U("pi-adapter",e.getAgentProfile);const i=t.options??{};this.aibotSessionId=String(i.aibotSessionId??"").trim(),this.agentName=String(i.agentName??"").trim(),this.clientType=String(i.clientType??"").trim().toLowerCase(),this.provider=i.provider,this.bindingStore=i.bindingStore instanceof Z?i.bindingStore:null,this.globalConfigStore=i.globalConfigStore instanceof tt?i.globalConfigStore:null,this.bindingStore&&this.aibotSessionId&&(this.piSessionPath=this.bindingStore.getPiSessionPath(this.aibotSessionId)??null)}isOmp(t=this.config.command||"pi"){return this.clientType?this.clientType==="omp":ht(t)}resolvePiConfigDir(){return String(this.config.env?.PI_CODING_AGENT_DIR??"").trim()||m(b(),".pi","agent")}start(){return this.initializationPromise=this.initializeSession(),this.initializationPromise}async initializeSession(){const t=this.resolveInitialModel();await this.startInternalApi(),await this.spawnPi(),await this.ensureSessionReady();let e;if(t)try{await this.tryRestoreModelSelection(t)}catch(i){e=t,a.warn("pi-adapter",`Failed to restore model selection: ${i instanceof Error?i.message:String(i)}; retrying after catalog refresh`)}a.info("pi-adapter",`Ready (pid=${this.process?.pid})`),await this.syncModelBinding(!!e),this.scheduleCatalogResync(e)}scheduleCatalogResync(t){if(this.catalogResyncTimers.length>0)return;let e=this.modelSelectionRevision,i=this.catalogSignature;for(const s of yt){const r=setTimeout(()=>{(async()=>{if(!(this.stopped||e!==this.modelSelectionRevision)){if(t){const n=t;try{await this.tryRestoreModelSelection(n),t=void 0,e=this.modelSelectionRevision,a.info("pi-adapter",`Applied configured model after catalog refresh: ${n.provider}:${n.modelId}`)}catch(o){a.warn("pi-adapter",`Model selection retry after catalog refresh failed: ${o instanceof Error?o.message:String(o)}`)}}if(await this.syncModelBinding(),!t&&this.catalogSignature===i){this.clearCatalogResyncTimers();return}i=this.catalogSignature}})()},s);this.catalogResyncTimers.push(r)}}clearCatalogResyncTimers(){for(const t of this.catalogResyncTimers)clearTimeout(t);this.catalogResyncTimers=[]}async tryRestoreModelSelection(t){try{await this.setModelSelection(t.provider,t.modelId,!1);return}catch(e){const i=await this.resolveProviderIdForModel(t.modelId,t.provider);if(!i)throw e;a.info("pi-adapter",`Provider "${t.provider}" unmatched for model ${t.modelId}; using "${i}"`),await this.setModelSelection(i,t.modelId,!1)}}async resolveProviderIdForModel(t,e){try{const s=(await this.transport.send("get_available_models")).data?.models??[];if(new Set(s.map(d=>d.provider?.trim()).filter(d=>!!d)).has(e))return;const n=k(e);return s.find(d=>d.id===t&&d.provider&&k(d.provider)===n)?.provider?.trim()||void 0}catch{return}}async syncModelBinding(t=!1){if(!this.aibotSessionId)return;const e=this.modelSelectionRevision;for(let i=1;i<=x;i++)try{const[s,r]=await Promise.all([this.transport.send("get_available_models"),this.transport.send("get_state")]);if(e!==this.modelSelectionRevision)return;const n=s.data?.models;if(!n||n.length===0){if(i<x){await M(St);continue}a.warn("pi-adapter",`syncModelBinding: empty model list after ${x} attempts, giving up`);return}const o=r.data?.model,d=this.bindingStore?.get(this.aibotSessionId);!t&&r.success&&o?.provider&&o.id&&!(d?.piProviderId&&d.piModelId)&&this.bindingStore?.setPiModel(this.aibotSessionId,o.provider,o.id);const h={available_models:n.map(u=>({id:u.id,display_name:u.name??u.id,...u.provider?{provider:u.provider}:{}}))},p=Et(n);p.length>0&&(h.available_providers=p),o?.id&&(h.model_id=o.id),o?.provider&&(h.provider_id=o.provider,h.model_provider=o.provider),this.callbacks.sendUpdateBindingCard(this.aibotSessionId,this.isStreaming?"composing":"ready",this.resolveCwd(),h),this.catalogSignature=n.map(u=>`${u.provider??""}\0${u.id}`).sort().join(`
|
|
2
|
+
`),a.info("pi-adapter",`synced model binding: ${n.length} models, current=${o?.id??"unknown"} (attempt ${i})`);return}catch(s){a.warn("pi-adapter",`syncModelBinding failed (non-fatal): ${s instanceof Error?s.message:String(s)}`);return}}resolveInitialModel(){const t=this.bindingStore?.get(this.aibotSessionId);if(t?.piProviderId&&t.piModelId)return{provider:t.piProviderId,modelId:t.piModelId};if(this.piSessionPath)return;const e=C(this.provider);if(e.mode==="native")return{provider:e.providerId,modelId:e.modelId};const i=this.globalConfigStore?.get(this.agentName);if(i?.piProviderId&&i.piModelId)return{provider:i.piProviderId,modelId:i.piModelId}}async setModelSelection(t,e,i){const s=await this.transport.send("set_model",{provider:t,modelId:e});if(!s.success)throw new Error(s.error||"set_model failed");this.modelSelectionRevision++,this.aibotSessionId&&this.bindingStore?.setPiModel(this.aibotSessionId,t,e),i&&this.agentName&&this.globalConfigStore?.set(this.agentName,{piProviderId:t,piModelId:e})}async currentModel(){try{return(await this.transport.send("get_state")).data?.model??null}catch{return null}}async stop(){if(this.stopped=!0,this.promptGeneration++,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.cancelDoneGuard(),this.clearCatalogResyncTimers(),this.transport.close(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.mcpConfigPath){try{N(this.mcpConfigPath)}catch{}this.mcpConfigPath=null}if(this.cwdMcpJsonDir&&this.cwdMcpJsonKey){const t=this.cwdMcpJsonDir,e=this.cwdMcpJsonKey;this.cwdMcpJsonDir=null,this.cwdMcpJsonKey=null;try{await ct(t,e)}catch(i){a.warn("pi-adapter",`\u6E05\u7406 omp cwd .mcp.json \u6761\u76EE\u5931\u8D25 key=${e}: ${i instanceof Error?i.message:String(i)}`)}}if(this.process){const t=this.process;try{P(t,"SIGTERM")}catch{}const e=setTimeout(()=>{try{P(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 mt(t.adapterSessionId),i=this.buildPromptTextFromRequest(t);return this.ensureSessionReady().then(()=>this.transport.send("prompt",{message:i})).then(s=>{s.success||e.emitDone({status:"failed",error:s.error})}).catch(s=>{e.emitError(s instanceof Error?s:new Error(String(s)))}),e}async cancel(t){try{await this.transport.send("abort")}catch{}}deliverInboundEvent(t){const{event_id:e,session_id:i,content:s}=t,r=++this.promptGeneration,n=this.buildPromptText(t);if(this.isStreaming){if(this.activeEventId&&this.activeEventId!==e){const o=this.activeEventId;a.info("pi-adapter",`steer: cancel ${o} -> ${e}`),this.flushTextBuffer(),this.callbacks.sendEventResult(o,"canceled","steered to new event"),this.activeAuditCapture?.eventId===o&&(this.snapshotAuditBoundary(o),this.emit("eventDone",o))}this.activeEventId=e,this.activeSessionId=i,this.resetRunStreamState(),this.startComposing(i,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.sendInboundPrompt(t,r,{message:n,streamingBehavior:"steer"})}else a.info("pi-adapter",`prompt: event=${e} session=${i}`),this.activeEventId=e,this.activeSessionId=i,this.isStreaming=!0,this.resetRunStreamState(),this.startComposing(i,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.sendInboundPrompt(t,r,{message:n})}sendInboundPrompt(t,e,i){const s=t.event_id,r=()=>!this.stopped&&this.promptGeneration===e&&this.activeEventId===s;(async()=>{if(this.abortBarrier&&await this.abortBarrier,!r())return;this.beginAuditCapture(t);const o=await this.transport.send("prompt",i);if(!o.success)throw new Error(o.error||"prompt rejected")})().catch(o=>{if(!r())return;const d=o instanceof Error?o.message:String(o);a.error("pi-adapter",`prompt error event=${s}: ${d}`),this.isStreaming=!1,this.cancelDoneGuard(),this.stopComposing(),this.stopIdleTimer(),this.clearActive(),this.callbacks.sendEventResult(s,"failed",d)})}beginAbortBarrier(){if(this.abortBarrier)return;const t=Promise.resolve().then(()=>this.transport.send("abort")).then(e=>{if(!e.success)throw new Error(e.error||"abort rejected")});this.abortBarrier=t,t.then(()=>{this.abortBarrier===t&&(this.abortBarrier=null)},e=>{a.error("pi-adapter",`abort failed: ${e}`)})}deliverStopEvent(t,e){if(this.activeEventId===t){a.info("pi-adapter",`stop: event=${t}, releasing busy immediately`),this.promptGeneration++,this.beginAbortBarrier(),this.cancelDoneGuard(),this.flushTextBuffer();const i=this.nextStreamSeq(),s=this.activeClientMsgId??void 0;this.callbacks.sendStreamChunk(t,this.activeSessionId??"","",i,!0,s),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.clearActive(),this.callbacks.sendEventResult(t,"canceled","stopped by user")}}async handleLocalAction(t){const e=t.action_id;switch(t.action_type){case"set_model":{const i=t.params??{},s=(i.modelId??i.model_id??"").trim();if(!s)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_model","model_id is required"),{handled:!0,kind:"set_model_error"};try{await this.initializationPromise;let r=(i.provider_id??i.provider??i.model_provider)?.trim();if(!r){const d=((await this.transport.send("get_available_models")).data?.models??[]).filter(h=>h.id===s&&h.provider?.trim());if(d.length>1){const h=(await this.currentModel())?.provider?.trim();r=d.find(p=>p.provider?.trim()===h)?.provider?.trim()}r=r??d[0]?.provider?.trim()}return r?(await this.setModelSelection(r,s,!0),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"model_set",provider:r,modelId:s}),this.syncModelBinding(),{handled:!0,kind:"set_model"}):(this.callbacks.sendLocalActionResult(e,"failed",void 0,"model_not_found",`No provider for model: ${s}`),{handled:!0,kind:"set_model_error"})}catch(r){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_model_error",r instanceof Error?r.message:String(r)),{handled:!0,kind:"set_model_error"}}}case"set_provider":{const i=t.params??{},s=(i.provider_id??i.provider??"").trim();if(!s)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_provider","provider_id is required"),{handled:!0,kind:"set_provider_error"};try{await this.initializationPromise;const o=((await this.transport.send("get_available_models")).data?.models??[]).filter(p=>p.provider?.trim()===s);if(o.length===0)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"provider_not_found",`No models for provider: ${s}`),{handled:!0,kind:"set_provider_error"};const d=(await this.currentModel())?.id,h=o.find(p=>p.id===d)?.id??o[0].id;return await this.setModelSelection(s,h,!0),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"provider_set",provider:s,modelId:h}),this.syncModelBinding(),{handled:!0,kind:"set_provider"}}catch(r){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_provider_error",r instanceof Error?r.message:String(r)),{handled:!0,kind:"set_provider_error"}}}case"get_context":try{const i=await this.transport.send("get_state");return this.callbacks.sendLocalActionResult(e,"ok",{state:i}),{handled:!0,kind:"get_context"}}catch(i){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"get_context_error",i instanceof Error?i.message:String(i)),{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||!this.isOmp())return null;const t=L(y(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?q(t,[t]):!1}async probe(t){const e=this.getStatus();return{...await st(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=S(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,i){try{if(t==="model"&&e.trim()&&await this.initializationPromise,!this.alive)return{status:"failed",message:"Pi process not running"};switch(t){case"model":{const s=e.trim();if(s){const o=s.indexOf(":");if(o<1)return{status:"failed",message:"Format: provider:model_id"};const d=s.slice(0,o),h=s.slice(o+1);return h?(await this.setModelSelection(d,h,!0),this.syncModelBinding(),{status:"ok",message:`Model set to ${d}:${h}`}):{status:"failed",message:"Format: provider:model_id"}}const n=(await this.transport.send("get_available_models"))?.data?.models;return n&&n.length>0?{status:"ok",message:`Available models:
|
|
3
|
+
${n.map(d=>` ${d.provider??"unknown"}:${d.id} (${d.name??d.id})`).join(`
|
|
4
|
+
`)}`,data:n}:{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 s=this.getStatus();return{status:"ok",message:`Alive: ${s.alive}, Busy: ${s.busy}, Session: ${this.piSessionPath??"none"}`,data:{alive:s.alive,busy:s.busy,sessions:s.sessions,sessionPath:this.piSessionPath}}}case"skills":{const s=V({mode:"pi"}),r=s.map(n=>`- ${n.name}${n.trigger?` (${n.trigger})`:""} [${n.source}]: ${n.description}`);return{status:"ok",message:r.length>0?r.join(`
|
|
5
|
+
`):"No skills found",data:s}}default:return{status:"unsupported",message:`Unknown command: ${t}`}}}catch(s){return{status:"failed",message:s instanceof Error?s.message:String(s)}}}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(){const t=this.isOmp();try{this.internalApi=new J,this.internalApi.setInvokeHandler(async(r,n,o,d)=>this.callbacks.agentInvoke(r,n,d)),await this.internalApi.start(0),a.info("pi-adapter",`Internal API started at ${this.internalApi.url}`);const e=this.resolvePiConfigDir();if(t){const r=this.getMcpConfig(),n=m(j(),"grix-pi-mcp");F(n,{recursive:!0}),this.mcpConfigPath=m(n,`mcp-${process.pid}-${Date.now()}.json`),O(this.mcpConfigPath,JSON.stringify({mcpServers:{[r.name]:{command:r.command,args:r.args,directTools:!0,lifecycle:"eager"}}}),"utf8"),a.info("pi-adapter",`MCP config written to ${this.mcpConfigPath}`)}else{const r=y(new URL("./pi-grix-tools-extension.js",import.meta.url)),n=y(new URL("./pi-grix-tools-extension.ts",import.meta.url));if(this.piGrixToolsExtensionPath=I(r)?r:n,!I(this.piGrixToolsExtensionPath))throw new Error(`Pi Grix tools extension not found: ${this.piGrixToolsExtensionPath}`);a.info("pi-adapter",`Pi Grix direct tools extension: ${this.piGrixToolsExtensionPath}`)}const i=m(e,"skills"),s=H(i);s.length>0&&a.info("pi-adapter",`Synced connector skills to ${i}: [${s.join(", ")}]`)}catch(e){if(this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),t){a.warn("pi-adapter",`Failed to start MCP tools (non-fatal): ${e instanceof Error?e.message:String(e)}`);return}throw a.error("pi-adapter",`Failed to start Pi Grix tools: ${e instanceof Error?e.message:String(e)}`),e}}async writeOmpCwdMcpConfig(t){if(!this.mcpConfigPath)return;const e=this.getMcpConfig();if(e)try{const i=await dt(t,{name:e.name,command:e.command,args:e.args});this.cwdMcpJsonDir=t,this.cwdMcpJsonKey=i}catch(i){a.warn("pi-adapter",`\u5199\u5165 omp <cwd>/.omp/mcp.json \u5931\u8D25: ${i instanceof Error?i.message:String(i)}`)}}async spawnPi(){const t=this.config.command||"pi",e=z(t,typeof process.env.PATH=="string"?process.env.PATH:void 0),i=this.config.args??[],r=i.some(l=>l.startsWith("--mode"))?[...i]:["--mode","rpc",...i],n=this.resolvePiConfigDir(),o=rt(this.agentName),d=C(this.provider);if(d.mode==="relay"){const l=this.isOmp(e)?"bare":"dollar";await ot(n,o,this.provider,l)?(r.includes("--provider")||r.push("--provider",o),!r.includes("--model")&&this.provider.model?.trim()&&r.push("--model",this.provider.model.trim())):a.warn("pi-adapter","provider config incomplete (baseUrl/model required); Grix provider not applied")}else d.mode==="native"&&a.info("pi-adapter",`Native provider ${d.providerId}:${d.modelId}; applying model via RPC (no models.json injection)`),await nt(n,o).then(l=>{l&&a.info("pi-adapter",`Removed stale Grix provider "${o}" from models.json`)}).catch(l=>{a.warn("pi-adapter",`Failed to clean up Grix provider config: ${l instanceof Error?l.message:String(l)}`)});const h=this.isOmp(e);if(!h){if(!this.internalApi||!this.piGrixToolsExtensionPath)throw new Error("Pi Grix tools are not initialized");r.some((v,G)=>(v==="--extension"||v==="-e")&&r[G+1]===this.piGrixToolsExtensionPath)||r.push("--extension",this.piGrixToolsExtensionPath),this.piGrixToolsReady=!1,this.piGrixToolsReadyError=null,this.piGrixToolsStderrBuffer=""}let p={...process.env,...this.config.env};h?p=ut(p):p.GRIX_CONNECTOR_INTERNAL_API=this.internalApi.url;const u=this.provider?.apiKey?.trim();u&&!p.GRIX_PROVIDER_API_KEY?.trim()&&(p.GRIX_PROVIDER_API_KEY=u);const g=this.resolveCwd();a.info("pi-adapter",`Spawning: ${e} ${r.join(" ")}`);try{if(!(await D(g)).isDirectory())throw new Error(`Bound path is not a directory: ${g}`)}catch(l){throw String(l?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${g}. Please rebind with /grix open <valid-directory>.`):l}h&&await this.writeOmpCwdMcpConfig(g);try{this.process=K(e,r,{env:p,cwd:g}).process}catch(l){throw a.error("pi-adapter",`PI spawn threw: ${l}`),this.alive=!1,l}if(h&&this.cwdMcpJsonDir&&this.cwdMcpJsonKey&&this.process.pid&<(this.cwdMcpJsonDir,this.cwdMcpJsonKey,this.process.pid).catch(l=>{a.warn("pi-adapter",`\u8BB0\u5F55 omp \u5B50\u8FDB\u7A0B pid \u5230 mcp \u72B6\u6001\u6587\u4EF6\u5931\u8D25: ${l instanceof Error?l.message:String(l)}`)}),this.process.on("error",l=>{a.error("pi-adapter",`Spawn error: ${l.message}`),this.alive=!1,this.clearCatalogResyncTimers(),this.transport.close(),this.activeEventId&&(this.callbacks.sendEventResult(this.activeEventId,"failed",`Spawn error: ${l.message}`),this.clearActive()),this.stopped||this.emit("exit",1)}),this.process.on("exit",l=>{a.info("pi-adapter",`PI process exited (code=${l})`),this.alive=!1,this.clearCatalogResyncTimers(),this.transport.close(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"failed",`PI process exited (code=${l})`),this.isStreaming=!1,this.clearActive(),this.stopped||this.emit("exit",l??1)}),this.process.stderr?.on("data",l=>{h||this.observePiGrixToolsStderr(l.toString());const v=l.toString().trim();v&&a.info("pi-adapter",`[pi stderr] ${v}`)}),this.transport.on("event",l=>this.handlePiEvent(l)),this.transport.bind(this.process.stdin,this.process.stdout),this.alive=!0,!h)try{await this.waitForPiGrixToolsReady()}catch(l){throw await this.stop(),l}}observePiGrixToolsStderr(t){const e=this.piGrixToolsStderrBuffer+t;this.piGrixToolsStderrBuffer=e.slice(-4096);const i=e.indexOf(T);if(i<0)return;const s=e.indexOf(`
|
|
6
|
+
`,i);if(s<0)return;const r=e.slice(i+T.length,s).trim();if(this.piGrixToolsStderrBuffer="",!/^\d+$/.test(r)||Number(r)!==E.length){this.piGrixToolsReadyError=`Pi Grix tools count mismatch: expected ${E.length}, got ${r||"invalid"}`;return}this.piGrixToolsReady=!0,a.info("pi-adapter",`Pi Grix direct tools ready: ${r} tools`)}async waitForPiGrixToolsReady(t=It){const e=Date.now()+t;for(;!this.piGrixToolsReady;){if(this.piGrixToolsReadyError)throw new Error(this.piGrixToolsReadyError);if(!this.process||!this.alive)throw new Error("Pi exited before Grix tools were ready");if(Date.now()>=e)throw new Error(`Timed out waiting for ${E.length} Pi Grix tools to become ready`);await M(25)}}handlePiEvent(t){if(this.stopped||this.abortBarrier)return;if(this.lastRpcAt=Date.now(),t.type==="tool_execution_start"){const i=t;this.descendantBaseline===void 0&&this.captureDescendantBaseline(),i.toolCallId&&this.toolCallsInFlight.add(i.toolCallId)}else if(t.type==="tool_execution_end"){const i=t;i.toolCallId&&this.toolCallsInFlight.delete(i.toolCallId)}switch(this.resetIdleTimer(),t.type){case"message_update":{const i=t.assistantMessageEvent;if(!i)break;const s=i.type;if(s==="text_delta"){const r=i.delta;if(r){const n=typeof i.contentIndex=="number"?i.contentIndex:0;this.rememberEmittedText(n,r),this.appendText(r)}}else if(s==="text_end"){const r=i.content,n=typeof i.contentIndex=="number"?i.contentIndex:0;r&&this.appendMissingText(n,r)}else if(s==="thinking_delta"){const r=i.delta;r&&this.activeEventId&&this.activeSessionId&&(this.thinkingSeq++,this.callbacks.sendThinking(this.activeEventId,this.activeSessionId,r))}else if(s==="done"||s==="error"){if(this.flushTextBuffer(),s==="error"){const r=this.piMessageError(i.error,i.reason);a.warn("pi-adapter",`terminal message_update error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${f(i.error)} reason=${f(i.reason)}`),this.recordRunError(r)}this.scheduleDoneGuard()}break}case"message_end":{const i=t.message;i?.role==="assistant"&&i.stopReason==="error"&&(a.warn("pi-adapter",`terminal message_end error event=${this.activeEventId} sessionId=${this.activeSessionId} errorMessage=${f(i.errorMessage)} message=${f(i)}`),this.recordRunError(this.piMessageError(i,i.errorMessage)),this.scheduleDoneGuard());break}case"tool_execution_start":{if(this.cancelDoneGuard(),this.flushTextBuffer(),!this.activeEventId||!this.activeSessionId)break;const i=t;if(i.toolName){const s=Y(i.args);this.callbacks.sendToolUse(this.activeEventId,this.activeSessionId,i.toolName,s)}break}case"tool_execution_end":{if(!this.activeEventId||!this.activeSessionId)break;const i=t;i.isError&&this.callbacks.sendToolResult(this.activeEventId,this.activeSessionId,i.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.captureOmpAuditMessages(t.messages),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>=vt){this.flushTextBuffer();return}this.scheduleTextFlush()}scheduleTextFlush(){this.textFlushTimer||(this.textFlushTimer=setTimeout(()=>{this.textFlushTimer=null,this.flushTextBuffer()},gt))}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 et(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 s=JSON.parse(t.context_messages_json);if(Array.isArray(s)&&s.length>0){const r=s.map(n=>`[context] ${n.sender_id??"unknown"}: ${n.content}`).join(`
|
|
6
7
|
`);e=`${e}
|
|
7
8
|
|
|
8
9
|
[Conversation context]
|
|
9
|
-
${
|
|
10
|
+
${r}`}}catch{}const i=this.identity.injectOnce(t.session_id,e);return this.inboundMessageIds.inject(t.session_id,i,t.msg_id)}buildPromptTextFromRequest(t){let e=t.text;if(t.contextMessages&&t.contextMessages.length>0){const i=t.contextMessages.map(s=>`[context] ${s.senderId}: ${s.content}`).join(`
|
|
10
11
|
`);e=`${e}
|
|
11
12
|
|
|
12
13
|
[Conversation context]
|
|
13
|
-
${i}`}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.descendantBaseline=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 i;if(e)try{i=
|
|
14
|
+
${i}`}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.descendantBaseline=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 i;if(e)try{i=S(e).size}catch{i=0}this.activeAuditCapture={eventId:t.event_id,...e?{transcriptPath:e}:{},...i===void 0?{}:{transcriptStartOffset:i},...this.isOmp(this.config.command??"")?{eventRecords:[]}:{}}}captureOmpAuditMessages(t){const e=this.activeAuditCapture;if(!(!e?.eventRecords||e.eventId!==this.activeEventId)&&Array.isArray(t))for(const i of t){if(!i||typeof i!="object"||Array.isArray(i))continue;const s=i,r=s.timestamp;e.eventRecords.push({type:"message",message:s,timestamp:typeof r=="number"&&Number.isFinite(r)?new Date(r).toISOString():new Date().toISOString()})}}snapshotAuditBoundary(t){const e=this.activeAuditCapture;if(!e||e.eventId!==t)return;this.activeAuditCapture=null;const i={adapterType:"pi"};if(e.transcriptPath){let s=e.transcriptStartOffset??0;try{s=S(e.transcriptPath).size}catch{}i.transcriptPath=e.transcriptPath,i.transcriptStartOffset=e.transcriptStartOffset??0,i.transcriptEndOffset=s,i.providerSessionId=this.piSessionPath??e.transcriptPath}else e.eventRecords&&e.eventRecords.length>0&&(i.eventRecords=e.eventRecords);this.completedAuditBoundaries.set(t,i)}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()}`,this.descendantBaseline=void 0}nextStreamSeq(){return this.streamSeq++,this.streamSeq}completeActiveEvent(){if(!this.activeEventId){this.clearActive();return}const t=this.activeEventId,e=this.activeSessionId??"",i=this.activeClientMsgId??void 0,s=this.activeRunError??void 0;s&&this.emitPendingRunError();const r=this.runErrorEmitted;this.clearActive(),this.finalizeEvent(t,e,i,s,r)}finalizeEvent(t,e,i,s,r=!1){const n=this.nextStreamSeq(),o=s?"failed":"responded";a.info("pi-adapter",`finalize event=${t} sessionId=${e} status=${o} clientMsgId=${i??""} terminalError=${s?f(s):""}`),this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t,e,i).then(()=>{this.callbacks.sendEventResult(t,o,s,void 0,r),a.info("pi-adapter",`event ${o} (reliable) event=${t}`)}).catch(d=>{a.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)}`),a.info("pi-adapter",`event failed (final delivery) event=${t}`)}):(this.callbacks.sendStreamChunk(t,e,"",n,!0,i),this.callbacks.sendEventResult(t,o,s,void 0,r),a.info("pi-adapter",`event ${o} 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=${f(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 i=t.errorMessage;if(typeof i=="string"&&i.trim())return i.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 i=this.emittedTextByIndex.get(t)??"";if(e!==i){if(e.startsWith(i)){const s=e.slice(i.length);s&&(this.rememberEmittedText(t,s),this.appendText(s));return}if(!i){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())},B.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||!A(t))return!1;if(this.toolCallsInFlight.size>0&&this.descendantBaseline instanceof Set){let o=0;try{o=Q(t,this.descendantBaseline)}catch{o=0}if(o>0)return this.livenessExtendStartAt=void 0,a.info("pi-adapter",`Liveness check: tool descendants for ${this.activeEventId} (descendants=${o}, toolsInFlight=${this.toolCallsInFlight.size}), extending without budget`),!0}const e=Date.now(),i=this.lastRpcAt>0?e-this.lastRpcAt:Number.POSITIVE_INFINITY,s=this.transcriptFreshMs();if(i<$||s!==null&&s<$)return this.livenessExtendStartAt=e,a.info("pi-adapter",`Liveness check: fresh progress for ${this.activeEventId} (rpcAge=${Number.isFinite(i)?`${i}ms`:"n/a"}, transcriptAge=${s!==null?`${s}ms`:"n/a"}, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const n=this.livenessExtendStartAt??e;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=n),e-n>R?(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(i)?`${i}ms`:"n/a"}, transcriptAge=${s!==null?`${s}ms`:"n/a"}), extending`),!0)}captureDescendantBaseline(){const t=this.process?.pid;if(!t){this.descendantBaseline=null;return}try{this.descendantBaseline=new Set(W(t)),a.info("pi-adapter",`Liveness baseline captured for ${this.activeEventId}: ${this.descendantBaseline.size} resident descendant(s)`)}catch{this.descendantBaseline=null}}transcriptFreshMs(){const t=this.piSessionPath;if(!t)return null;try{return Date.now()-S(t).mtimeMs}catch{return null}}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,i=!!(this.alive&&t&&A(t))?`liveness budget exhausted after ${R/6e4}min`:"process not alive";a.error("pi-adapter",`Idle timeout (${i}, 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: ${i}`,void 0,this.runErrorEmitted)),this.clearActive(),this.emit("exit",-1)},ft))}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 s=await this.transport.send("get_state");s.success&&(e=s.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{B as PiAdapter,C as planPiProvider};
|
|
Binary file
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schemaVersion": 1,
|
|
3
|
-
"bridgeVersion": "5.
|
|
4
|
-
"tarball": "grix-dsh-bridge-5.
|
|
5
|
-
"size":
|
|
3
|
+
"bridgeVersion": "5.1.0",
|
|
4
|
+
"tarball": "grix-dsh-bridge-5.1.0.tgz",
|
|
5
|
+
"size": 24833,
|
|
6
6
|
"unpackedSize": 99264,
|
|
7
|
-
"shasum": "
|
|
8
|
-
"integrity": "sha512-
|
|
7
|
+
"shasum": "691fad119747cc050ff25f397dd092ca22f8343f",
|
|
8
|
+
"integrity": "sha512-1iDE+i5alDCJ82gwiSQ3o8jvqUMVgqxNQ3a9PRbk8frN9izSaAMbkkX65Qg7qQ/eqcUY7L8FH/9j+GII0Odtgg=="
|
|
9
9
|
}
|