grix-connector 4.11.1 → 4.11.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,12 @@
1
- import{EventEmitter as T}from"node:events";import{stat as M}from"node:fs/promises";import{existsSync as $,mkdirSync as O,readFileSync as F,writeFileSync as D}from"node:fs";import{join as S,resolve as B,dirname as L}from"node:path";import{homedir as N}from"node:os";import{fileURLToPath as j}from"node:url";import{resolveCommandPath as Q,spawnCommand as U,killProcessGroup as y,hasChildProcesses as q}from"../../core/runtime/spawn.js";import{InternalApiServer as H}from"../../core/mcp/internal-api-server.js";import{resolveMcpServerName as J,pruneLegacyMcpServerEntries as V}from"../../core/mcp/server-name.js";import{InboundMessageIdInjector as W}from"../shared/inbound-message-id-injector.js";import{IdentityInjector as z}from"../shared/identity-injector.js";import{syncDefaultSkillsToDir as G}from"../../default-skills/index.js";import{buildSimpleProbeReport as X}from"../shared/probe-util.js";import{compactToolInputForWire as Y}from"../shared/tool-wire-payload.js";import{normalizeOCProviderModels as K}from"./opencode-types.js";import{buildOpencodeConfigContent as Z}from"./opencode-config.js";import{agentIdOf as A}from"../shared/native-provider-config.js";import{formatOpenCodeErrorMessage as k}from"./format-error.js";import{OpenCodeTransport as ee}from"./opencode-transport.js";import{log as r}from"../../core/log/index.js";import{splitTextForAibotProtocol as x}from"../../core/protocol/index.js";class te extends T{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitError(e){if(this.listenerCount("error")===0){r.warn("opencode-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}const se=200,ie=2e3,ne=12e4,oe=90*1e3,b=1800*1e3,P=3e4,R=600*1e3,re="claude_interaction_reply",ae="set_mode",de="set_model",ce="127.0.0.1",le=0,he=1e3,m={fullAuto:"full_auto",approval:"approval"},C=[{id:m.fullAuto,displayName:"Full Auto"},{id:m.approval,displayName:"Approval"}],pe=[{permission:"*",pattern:"*",action:"allow"}],ue=[{permission:"doom_loop",pattern:"*",action:"ask"},{permission:"external_directory",pattern:"*",action:"ask"},{permission:"question",pattern:"*",action:"deny"},{permission:"plan_enter",pattern:"*",action:"deny"},{permission:"plan_exit",pattern:"*",action:"deny"},{permission:"repo_clone",pattern:"*",action:"deny"},{permission:"repo_overview",pattern:"*",action:"deny"},{permission:"read",pattern:"*.env",action:"ask"},{permission:"read",pattern:"*.env.*",action:"ask"},{permission:"read",pattern:"*.env.example",action:"allow"}];function w(g){const e=String(g??"").trim().toLowerCase();if(e==="full_auto"||e==="fullauto")return m.fullAuto;if(e==="approval"||e==="ask"||e==="autoedit"||e==="auto_edit")return m.approval}function E(g){try{return process.kill(g,0),!0}catch(e){return e.code==="EPERM"}}class Fe extends T{type="opencode";config;callbacks;options;identity;inboundMessageIds=new W;process=null;transport=new ee;alive=!1;stopped=!1;internalApi=null;sessions=new Map;sessionModes=new Map;sessionModels=new Map;availableModels=[];modelContextLimits=new Map;contextTokensBySession=new Map;activeRun=null;completedEvents=new Set;clientMsgSeq=0;auditCaptures=new Map;completedAuditBoundaries=new Map;idleTimer=null;lastSseAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;toolCardsSent=new Set;messageRoles=new Map;pendingPartChunks=new Map;pendingPermissions=new Map;pendingQuestions=new Map;permissionHandler=null;constructor(e,s,t){super(),this.config=e,this.callbacks=s,this.options=t??{},this.identity=new z("opencode-adapter",s.getAgentProfile)}onAgentProfileChanged(){this.identity.onProfileChanged()}async start(){await this.startInternalApiAndInjectMcp();const e=this.options.hostname??ce,s=this.options.port??le,t=await this.spawnAndWait(e,s),i=this.resolveCwd();await this.transport.connect(t,i),this.transport.on("event",n=>this.handleSseEvent(n));try{await this.refreshModels()}catch(n){r.warn("opencode-adapter",`Failed to fetch providers for toolbar models: ${n instanceof Error?n.message:String(n)}`)}r.info("opencode-adapter",`Ready (pid=${this.process?.pid}, url=${t})`)}async refreshModels(e){const s=await this.transport.listProviders(e),t=[],i=new Map;for(const n of s)for(const o of K(n.models)){t.push({id:`${n.id}/${o.id}`,displayName:o.name||o.id});const a=o.limit?.context;typeof a=="number"&&a>0&&i.set(`${n.id}/${o.id}`,a)}t.sort((n,o)=>{const a=n.displayName.toLowerCase().localeCompare(o.displayName.toLowerCase());return a!==0?a:n.id.localeCompare(o.id)}),this.availableModels=t,this.modelContextLimits=i,r.info("opencode-adapter",`Fetched ${t.length} models from ${s.length} providers (directory=${e??"current"})`)}resolveContextLimit(e,s){const t=this.modelContextLimits.get(`${e}/${s}`);if(t)return t;let i;for(const[n,o]of this.modelContextLimits)n.startsWith(`${e}/`)&&(i=i===void 0?o:Math.max(i,o));return i}buildContextWindowMeta(e,s,t,i){if(!i||i<=0)return;const n=this.resolveContextLimit(s,t);if(!n)return;const o=Math.min(100,i/n*100);return{context_window:{used:i,size:n,usedPercentage:o,remainingPercentage:100-o}}}async stop(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.transport.disconnect(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.process){const e=this.process;try{y(e,"SIGTERM")}catch{}const s=setTimeout(()=>{try{y(e,"SIGKILL")}catch{}},5e3);e.on("exit",()=>clearTimeout(s)),this.process=null}}isAlive(){return this.alive}async createSession(e){const s=e.cwd??this.resolveCwd();await this.transport.useDirectory(s);const t=await this.transport.createSession({title:`grix-${Date.now()}`},s);return this.sessions.set(t.id,{ocSessionId:t.id,cwd:s}),r.info("opencode-adapter",`Created OC session ${t.id} for cwd=${s}`),await this.applySessionPermission(t.id,t.id,s),t.id}async resumeSession(e,s){const t=this.sessions.get(e);if(t?.ocSessionId)try{await this.transport.useDirectory(t.cwd),await this.transport.getSession(t.ocSessionId,t.cwd),await this.applySessionPermission(e,t.ocSessionId,t.cwd)}catch{r.warn("opencode-adapter",`OC session ${t.ocSessionId} gone, will create new on next prompt`),t.ocSessionId=""}}async destroySession(e){const s=this.sessions.get(e),t=s?s.ocSessionId:e;if(t)try{await this.transport.deleteSession(t,s?.cwd)}catch{}this.sessions.delete(e),this.contextTokensBySession.delete(e),this.identity.forgetSession(e),this.inboundMessageIds.forgetSession(e)}sendPrompt(e){const s=new te(e.adapterSessionId);return this.sendOcPrompt(e.adapterSessionId,this.buildPromptText(e)).catch(t=>{s.emitError(t instanceof Error?t:new Error(String(t)))}),s}async cancel(e){if(this.activeRun)try{await this.transport.abortSession(this.activeRun.ocSessionId,this.activeRun.cwd)}catch{}}deliverInboundEvent(e){const{event_id:s,session_id:t,content:i}=e;if(this.completedEvents.has(s)){r.info("opencode-adapter",`Dropping duplicate event ${s}`),this.callbacks.sendEventAck(s,t),this.callbacks.sendEventResult(s,"responded");return}if(!this.alive){r.warn("opencode-adapter",`Dropping event ${s}: process not alive`),this.callbacks.sendEventAck(s,t),this.callbacks.sendEventResult(s,"failed","Agent process not running");return}this.activeRun&&this.activeRun.eventId!==s&&(r.info("opencode-adapter",`steer: ${this.activeRun.eventId} -> ${s}`),this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeRun.eventId,"canceled","steered to new event"),this.clearRun()),r.info("opencode-adapter",`prompt: event=${s} session=${t}`),this.callbacks.sendEventAck(s,t),this.startRun(s,t,e.audit?.enabled===!0),this.startComposing(t),this.resetIdleTimer();const n=this.buildPromptTextFromEvent(e);this.sendOcPrompt(t,n).catch(o=>{r.error("opencode-adapter",`prompt_async failed: ${o}`),this.finishRun("failed",String(o))})}deliverStopEvent(e,s){this.activeRun&&this.activeRun.eventId===e&&(r.info("opencode-adapter",`stop: event=${e}`),this.rejectAllPendingInteractions(),this.transport.abortSession(this.activeRun.ocSessionId,this.activeRun.cwd).catch(()=>{}),this.flushTextBuffer(),this.finishRun("canceled","stopped by user"))}setPermissionHandler(e){this.permissionHandler=e}async ping(e){return this.transport.healthCheck()}getStatus(){return{alive:this.alive,busy:this.activeRun!==null,sessions:this.sessions.size}}getActiveEventIds(){return this.activeRun?[this.activeRun.eventId]:[]}takeAuditBoundary(e){const s=this.completedAuditBoundaries.get(e);return s&&this.completedAuditBoundaries.delete(e),s}clearActiveEventForShutdown(){this.stopIdleTimer(),this.stopTextFlush(),this.rejectAllPendingInteractions(),this.activeRun&&this.snapshotAuditBoundary(this.activeRun),this.activeRun=null}getMcpConfig(){if(!this.internalApi)return null;const e=B(j(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:J(this.callbacks.getAgentId?.()),command:process.execPath,args:[e,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const e=this.process?.pid;return e?q(e,[e]):!1}async probe(e){const s=this.getStatus();return X(this.config.command||"opencode",{alive:s.alive,busy:s.busy,started:!!this.process},e)}async startInternalApiAndInjectMcp(){try{this.internalApi=new H,this.internalApi.setInvokeHandler(async(d,l,h,u)=>this.callbacks.agentInvoke(d,l,u)),await this.internalApi.start(0),r.info("opencode-adapter",`Internal API started at ${this.internalApi.url}`);const e=this.getMcpConfig(),s=A(this.config.command||"opencode")||"opencode",t=process.env.XDG_CONFIG_HOME||S(N(),".config"),i=S(t,s,`${s}.json`);O(L(i),{recursive:!0});let n={};try{$(i)&&(n=JSON.parse(F(i,"utf8")))}catch{}const o=n.mcp&&typeof n.mcp=="object"?n.mcp:{};V(o,this.internalApi.url),o[e.name]={type:"local",command:[e.command,...e.args??[]],enabled:!0},n.mcp=o,D(i,`${JSON.stringify(n,null,2)}
2
- `,"utf8"),r.info("opencode-adapter",`MCP config injected into ${i}`);const a=S(t,s,"skills"),c=G(a);c.length>0&&r.info("opencode-adapter",`Synced connector skills to ${a}: [${c.join(", ")}]`)}catch(e){r.warn("opencode-adapter",`Failed to inject MCP tools (non-fatal): ${e instanceof Error?e.message:String(e)}`)}}async handleLocalAction(e){const{action_type:s}=e;if(s==="exec_approve"||s==="exec_reject"||s==="permission_approve"||s==="permission_reject")return this.handlePermissionAction(e);if(s===ae)return this.handleSetModeAction(e);if(s===de)return this.handleSetModelAction(e);if(s===re){const t=e.params??{};if(String(t.kind??"")==="permission"){const i=t.resolution??{},n=String(i.value??"");return this.handlePermissionAction({...e,action_type:n==="allow"?"exec_approve":"exec_reject",params:{...t,approval_command_id:t.request_id}})}return this.handleQuestionReplyAction(e)}return{handled:!1,kind:""}}handleQuestionReplyEvent(e){let s;if(e.action)s={type:"action",value:e.action};else if(e.response?.type==="single")s={type:"text",value:e.response.value};else if(e.response?.type==="map")s={type:"map",entries:e.response.entries};else return{delivered:!1,errorCode:"resolution_invalid",errorMsg:"Question reply response is invalid."};return this.deliverQuestionReply({request_id:e.request_id,resolution:s})}async bindSession(e,s){if(r.info("opencode-adapter",`bindSession: ${e} \u2192 ${s}`),!this.sessions.has(e))this.sessions.set(e,{ocSessionId:"",cwd:s});else{const t=this.sessions.get(e);t.cwd=s}try{await this.refreshModels(s)}catch(t){r.warn("opencode-adapter",`Failed to refresh models on bind: ${t instanceof Error?t.message:String(t)}`)}this.callbacks.sendUpdateBindingCard(e,"ready",s,this.buildToolbarMeta(e))}resolveModeId(e){if(e){const t=this.sessionModes.get(e);if(t)return t}const s=w(this.options.permissionPolicy);if(s)return s;if(e){const t=w(this.options.bindingStore?.get(e)?.modeId);if(t)return t}return m.fullAuto}buildModeToolbarMeta(e){const s=this.resolveModeId(e);return{mode_id:s,currentModeId:s,available_modes:C.map(t=>({...t}))}}async applySessionPermission(e,s,t){const i=this.resolveModeId(e),n=i===m.fullAuto?pe:ue;try{await this.transport.updateSessionPermission(s,n,t),r.info("opencode-adapter",`Applied session permission ruleset (${i}) to ${s}`)}catch(o){r.warn("opencode-adapter",`Failed to apply session permission ruleset: ${o instanceof Error?o.message:String(o)}`)}}async handleSetModeAction(e){const s=e.params??{},t=String(s.session_id??this.options.aibotSessionId??"").trim(),i=w(s.mode_id);if(!i||!t)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"invalid_params","mode_id must be full_auto or approval and session_id is required"),{handled:!0,kind:"set_mode"};this.sessionModes.set(t,i);const n=this.sessions.get(t);n?.ocSessionId&&await this.applySessionPermission(t,n.ocSessionId,n.cwd);const o=n?.cwd??this.getSessionCwd(t);return this.callbacks.sendUpdateBindingCard(t,"ready",o,this.buildToolbarMeta(t)),this.callbacks.sendLocalActionResult(e.action_id,"ok",{outcome:"mode_set",session_context:{mode_id:i,modeId:i},mode_id:i,available_modes:C.map(a=>({...a}))}),{handled:!0,kind:"set_mode"}}resolveModelId(e){if(e){const t=this.sessionModels.get(e);if(t)return t}const s=String(this.options.model??"").trim();if(s)return s;if(e){const t=String(this.options.bindingStore?.get(e)?.modelId??"").trim();if(t)return t}return""}buildModelToolbarMeta(e){const s=this.resolveModelId(e);return{model_id:s,currentModelId:s,available_models:this.availableModels.map(t=>({...t}))}}buildToolbarMeta(e){return{...this.buildModelToolbarMeta(e),...this.buildModeToolbarMeta(e)}}handleSetModelAction(e){const s=e.params??{},t=String(s.session_id??this.options.aibotSessionId??"").trim(),i=String(s.model_id??"").trim();if(!i||!t)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"invalid_params","model_id and session_id are required"),{handled:!0,kind:"set_model"};this.sessionModels.set(t,i);const n=this.sessions.get(t)?.cwd??this.getSessionCwd(t);return this.callbacks.sendUpdateBindingCard(t,"ready",n,this.buildToolbarMeta(t)),this.callbacks.sendLocalActionResult(e.action_id,"ok",{outcome:"model_set",session_context:{model_id:i,modelId:i},model_id:i,available_models:this.availableModels.map(o=>({...o}))}),{handled:!0,kind:"set_model"}}async spawnAndWait(e,s){const t=this.resolveCwd();try{if(!(await M(t)).isDirectory())throw new Error(`Bound path is not a directory: ${t}`)}catch(i){throw String(i?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${t}. Please rebind with /grix open <valid-directory>.`):i}return new Promise((i,n)=>{const o=this.config.command||"opencode",c=[...this.config.args??["serve"],`--hostname=${e}`,`--port=${s}`],d={...process.env,...this.config.env},l=Z({model:this.options.model,permissionPolicy:this.options.permissionPolicy,provider:this.options.provider});if(l){const v=(A(o)||"opencode").toUpperCase().replace(/[^A-Z0-9_]/g,"_")||"OPENCODE";d[`${v}_CONFIG_CONTENT`]=JSON.stringify(l)}const h=Q(o,typeof d.PATH=="string"?d.PATH:void 0);r.info("opencode-adapter",`Spawning: ${h} ${c.join(" ")} (cwd=${t})`),this.process=U(h,c,{env:d,cwd:t}).process;let u="",f=!1;const I=setTimeout(()=>{f||(f=!0,n(new Error(`opencode serve did not start after ${P/1e3}s`)))},P);this.process.stdout?.on("data",p=>{if(u+=p.toString(),!f)for(const v of u.split(`
3
- `)){const _=v.match(/\bserver listening on (https?:\/\/\S+)/);if(_){clearTimeout(I),f=!0,this.alive=!0,i(_[1]);return}}}),this.process.stderr?.on("data",p=>{const v=p.toString().trim();v&&r.info("opencode-adapter",`[stderr] ${v}`)}),this.process.on("error",p=>{r.error("opencode-adapter",`Spawn error: ${p.message}`),clearTimeout(I),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Spawn error: ${p.message}`),this.clearRun()),f?this.stopped||this.emit("exit",1):(f=!0,n(p))}),this.process.on("exit",p=>{r.info("opencode-adapter",`Process exited (code=${p})`),clearTimeout(I),this.alive=!1,this.transport.disconnect(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Process exited (code=${p})`),this.clearRun()),f?this.stopped||this.emit("exit",p??1):(f=!0,n(new Error(`opencode serve exited with code ${p}`)))})})}async ensureOcSession(e){const s=this.sessions.get(e),t=this.getSessionCwd(e);if(await this.transport.useDirectory(t),s?.ocSessionId)try{return await this.transport.getSession(s.ocSessionId,t),s.ocSessionId}catch{r.warn("opencode-adapter",`OC session ${s.ocSessionId} gone, creating new`),s.ocSessionId=""}const i=this.options.bindingStore?.getAcpSessionId(e);if(i)try{return await this.transport.getSession(i,t),this.sessions.set(e,{ocSessionId:i,cwd:t}),r.info("opencode-adapter",`Resumed OC session ${i} for aibot=${e}`),await this.applySessionPermission(e,i,t),i}catch{r.warn("opencode-adapter",`Persisted OC session ${i} gone, creating new`)}const n=await this.transport.createSession({title:`grix-${e.slice(-8)}`},t);return this.sessions.set(e,{ocSessionId:n.id,cwd:t}),this.options.bindingStore?.setAcpSessionId(e,n.id),r.info("opencode-adapter",`Created OC session ${n.id} for aibot=${e}`),await this.applySessionPermission(e,n.id,t),n.id}async sendOcPrompt(e,s){const t=this.getSessionCwd(e),i=await this.ensureOcSession(e);this.activeRun&&(this.activeRun.ocSessionId=i,this.activeRun.cwd=t);const n=this.resolveModelId(e),o=n.indexOf("/"),a=o>0&&o<n.length-1?{providerID:n.slice(0,o),modelID:n.slice(o+1)}:void 0;await this.transport.sendPromptAsync(i,{parts:[{type:"text",text:s}],...a?{model:a}:{}},t)}handleSseEvent(e){if(!this.stopped){if(this.updateToolInFlight(e),e.type!=="server.heartbeat"&&(this.lastSseAt=Date.now(),this.resetIdleTimer()),this.activeRun){const s=this.auditCaptures.get(this.activeRun.eventId);s&&s.push({sequence:s.length,observedAt:new Date().toISOString(),event:structuredClone(e)})}switch(e.type){case"message.part.updated":{if(!this.activeRun)break;const s=e.part,t=e.delta;if(s.type==="text"){const i=t||s.text;i&&this.acceptAssistantPartText(s.messageID,"text",i)}else s.type==="reasoning"?t&&this.acceptAssistantPartText(s.messageID,"reasoning",t):s.type==="tool"&&this.handleToolPartUpdate(s,t);break}case"message.updated":{if(!this.activeRun)break;const s=e.info;if(this.rememberMessageRole(s),s.role==="assistant"){const t=s;typeof t.tokens?.input=="number"&&this.contextTokensBySession.set(this.activeRun.sessionId,t.tokens.input);const i=this.buildContextWindowMeta(this.activeRun.sessionId,t.providerID,t.modelID,t.tokens?.input);this.callbacks.sendUpdateBindingCard(this.activeRun.sessionId,"composing",this.activeRun.cwd,{...this.buildToolbarMeta(this.activeRun.sessionId),model_provider:t.providerID,model_id:t.modelID,...i??{}}),t.error&&r.warn("opencode-adapter",`Message error: ${JSON.stringify(t.error)}`);const n=this.activeRun.ocSessionId;n&&t.sessionID===n&&(t.error?(this.flushTextBuffer(),this.finishRun("failed",k(t.error,t.error.type||"unknown error"))):t.time?.completed&&t.finish!=="tool-calls"&&(this.flushTextBuffer(),this.finishRun("responded")))}break}case"session.idle":{if(!this.activeRun)break;e.sessionID===this.activeRun.ocSessionId&&(this.flushTextBuffer(),this.finishRun("responded"));break}case"session.status":{if(!this.activeRun)break;e.sessionID===this.activeRun.ocSessionId&&e.status.type==="idle"&&(this.flushTextBuffer(),this.finishRun("responded"));break}case"session.error":{if(!this.activeRun)break;const s=k(e.error);r.error("opencode-adapter",`Session error: ${s}`),this.flushTextBuffer(),this.finishRun("failed",s);break}case"permission.updated":{this.handlePermission(e.permission);break}case"permission.asked":{this.handlePermissionAsked(e);break}case"question.asked":{this.handleQuestionAsked(e);break}case"permission.replied":case"question.replied":case"question.rejected":r.debug("opencode-adapter",`Interaction settled: ${e.type}`);break;case"session.created":case"session.updated":case"session.deleted":case"session.compacted":case"session.diff":case"file.edited":case"server.connected":case"server.heartbeat":break;case"server.instance.disposed":{r.warn("opencode-adapter",`Server instance disposed: ${e.directory}`),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeRun.eventId,"failed","server instance disposed"),this.clearRun()),this.stopped||this.emit("exit",-1);break}default:r.debug("opencode-adapter",`Unhandled SSE event type: ${e.type}`);break}}}updateToolInFlight(e){if(e.type!=="message.part.updated")return;const s=e.part;if(s?.type!=="tool"||!s.callID)return;const t=s.state?.status;t==="pending"||t==="running"?this.toolCallsInFlight.add(s.callID):(t==="completed"||t==="error")&&this.toolCallsInFlight.delete(s.callID)}rememberMessageRole(e){const s=typeof e.id=="string"?e.id.trim():"";s&&(e.role!=="user"&&e.role!=="assistant"||(this.messageRoles.set(s,e.role),this.flushOrDropPendingParts(s,e.role)))}acceptAssistantPartText(e,s,t){if(!this.activeRun||!t)return;const i=typeof e=="string"?e.trim():"";if(!i)return;const n=this.messageRoles.get(i);if(n==="user")return;if(n==="assistant"){this.emitAssistantPartChunk(s,t);return}const o=this.pendingPartChunks.get(i)??[];o.push({kind:s,value:t}),this.pendingPartChunks.set(i,o)}flushOrDropPendingParts(e,s){const t=this.pendingPartChunks.get(e);if(this.pendingPartChunks.delete(e),!(!t||t.length===0)&&s==="assistant")for(const i of t)this.emitAssistantPartChunk(i.kind,i.value)}emitAssistantPartChunk(e,s){if(!(!this.activeRun||!s)){if(e==="reasoning"){this.callbacks.sendThinking(this.activeRun.eventId,this.activeRun.sessionId,s);return}this.appendText(s)}}clearMessageRoleState(){this.messageRoles.clear(),this.pendingPartChunks.clear()}handleToolPartUpdate(e,s){if(!this.activeRun)return;const t=e.state;switch(t.status){case"pending":case"running":{this.sendToolUseOnce(e,t.input);break}case"completed":{this.sendToolUseOnce(e,t.input);break}case"error":{this.sendToolUseOnce(e,t.input),this.callbacks.sendToolResult(this.activeRun.eventId,this.activeRun.sessionId,e.tool,"(failed)");break}}}sendToolUseOnce(e,s){!this.activeRun||this.toolCardsSent.has(e.callID)||(this.flushTextBuffer(),this.toolCardsSent.add(e.callID),this.callbacks.sendToolUse(this.activeRun.eventId,this.activeRun.sessionId,e.tool,Y(s??{})))}onPermissionTimeout(e){const s=this.pendingPermissions.get(e);s&&(this.pendingPermissions.delete(e),r.error("opencode-adapter",`Permission approval timeout: ${e}`),this.transport.respondPermission(s.ocSessionId,e,"reject",s.cwd).catch(()=>{}),this.activeRun&&this.activeRun.eventId===s.eventId&&(this.flushTextBuffer(),this.finishRun("failed","permission approval timeout")))}trackPendingPermission(e){if(!this.activeRun)return;this.stopIdleTimer();const s=setTimeout(()=>this.onPermissionTimeout(e),R);this.pendingPermissions.set(e,{permissionId:e,eventId:this.activeRun.eventId,ocSessionId:this.activeRun.ocSessionId,cwd:this.activeRun.cwd,timer:s})}handlePermissionAsked(e){if(!this.activeRun){this.transport.respondPermission(e.sessionID,e.id,"reject").catch(o=>{r.warn("opencode-adapter",`Orphan permission reject failed: ${o}`)});return}const{eventId:s,sessionId:t,ocSessionId:i}=this.activeRun;if(this.resolveModeId(t)===m.fullAuto){this.transport.respondPermission(i,e.id,"always",this.activeRun.cwd).catch(o=>{r.warn("opencode-adapter",`Auto-approve failed: ${o}`)});return}this.trackPendingPermission(e.id);const n=e.patterns.length>0?`${e.permission}: ${e.patterns.join(", ")}`:e.permission;this.callbacks.sendPermissionCard?this.callbacks.sendPermissionCard({eventId:s,sessionId:t,approvalId:e.id,toolName:e.permission,toolTitle:n,toolInput:JSON.stringify(e.metadata??{})}):this.callbacks.sendToolUse(s,t,e.permission,JSON.stringify(e.metadata??{}))}handlePermission(e){if(!this.activeRun)return;const{eventId:s,sessionId:t,ocSessionId:i}=this.activeRun;if(this.resolveModeId(t)===m.fullAuto){this.transport.respondPermission(i,e.id,"always",this.activeRun.cwd).catch(n=>{r.warn("opencode-adapter",`Auto-approve failed: ${n}`)});return}if(this.trackPendingPermission(e.id),this.callbacks.sendPermissionCard)this.callbacks.sendPermissionCard({eventId:s,sessionId:t,approvalId:e.id,toolName:e.type,toolTitle:e.title||e.type,toolInput:JSON.stringify(e.metadata??{})});else{const n=JSON.stringify(e.metadata??{});this.callbacks.sendToolUse(s,t,e.type,n)}}handlePermissionAction(e){if(!this.activeRun)return{handled:!1,kind:""};const s=e.params??{},t=String(s.approval_id??s.approval_command_id??s.approvalId??s.tool_call_id??"");let i=t?this.pendingPermissions.get(t):void 0;if(!i){for(const a of this.pendingPermissions.values())if(a.eventId===this.activeRun.eventId){i=a;break}}if(!i)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"unknown_or_expired_approval_id","That approval request is no longer pending."),{handled:!0,kind:"permission"};const n=e.action_type==="exec_approve"||e.action_type==="permission_approve",o=n?"once":"reject";return clearTimeout(i.timer),this.pendingPermissions.delete(i.permissionId),this.transport.respondPermission(i.ocSessionId,i.permissionId,o,i.cwd).then(()=>{r.info("opencode-adapter",`Permission ${o}: ${i.permissionId}`),this.resetIdleTimer()}).catch(a=>{r.warn("opencode-adapter",`Permission response failed: ${a}`),this.resetIdleTimer()}),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:i.permissionId,decision:n?"approve":"reject"}),{handled:!0,kind:"permission"}}async handleExecApprovalEvent(e){if(!this.activeRun)return{delivered:!1,errorCode:"approval_not_found",errorMsg:"no active run"};const s=String(e.approval_id??e.approval_command_id??e.tool_call_id??"");let t=s?this.pendingPermissions.get(s):void 0;if(!t){for(const n of this.pendingPermissions.values())if(n.eventId===this.activeRun.eventId){t=n;break}}if(!t)return{delivered:!1,errorCode:"approval_not_found",errorMsg:"That approval request is no longer pending."};const i=e.decision==="deny"?"reject":e.decision==="allow-always"?"always":"once";return clearTimeout(t.timer),this.pendingPermissions.delete(t.permissionId),this.transport.respondPermission(t.ocSessionId,t.permissionId,i,t.cwd).then(()=>{r.info("opencode-adapter",`Permission ${i} (text event): ${t.permissionId}`),this.resetIdleTimer()}).catch(n=>{r.warn("opencode-adapter",`Permission response failed: ${n}`),this.resetIdleTimer()}),{delivered:!0}}onQuestionTimeout(e){const s=this.pendingQuestions.get(e);s&&(this.pendingQuestions.delete(e),r.error("opencode-adapter",`Question answer timeout: ${e}`),this.transport.rejectQuestion(e,s.cwd).catch(()=>{}),this.activeRun&&this.activeRun.eventId===s.eventId&&(this.flushTextBuffer(),this.finishRun("failed","question answer timeout")))}handleQuestionAsked(e){if(!this.activeRun){this.transport.rejectQuestion(e.id).catch(n=>{r.warn("opencode-adapter",`Orphan question reject failed: ${n}`)});return}const{eventId:s,sessionId:t}=this.activeRun;this.stopIdleTimer();const i=setTimeout(()=>this.onQuestionTimeout(e.id),R);if(this.pendingQuestions.set(e.id,{requestId:e.id,eventId:s,cwd:this.activeRun.cwd,questions:e.questions,timer:i}),this.callbacks.sendAgentQuestionCard)this.callbacks.sendAgentQuestionCard(s,t,{request_id:e.id,mode:"form",questions:e.questions.map(n=>({header:n.header,prompt:n.question,...n.options.length>0?{options:n.options.map(o=>o.label)}:{},...n.multiple!==void 0?{multi_select:n.multiple}:{}})),expires_at:Date.now()+R});else{const n=e.questions.map(o=>o.question).join(`
1
+ import{EventEmitter as y}from"node:events";import{stat as M}from"node:fs/promises";import{existsSync as $,mkdirSync as O,readFileSync as F,writeFileSync as B}from"node:fs";import{join as S,resolve as D,dirname as L}from"node:path";import{homedir as N}from"node:os";import{fileURLToPath as j}from"node:url";import{resolveCommandPath as Q,spawnCommand as U,killProcessGroup as T,hasChildProcesses as q}from"../../core/runtime/spawn.js";import{InternalApiServer as H}from"../../core/mcp/internal-api-server.js";import{resolveMcpServerName as J,pruneLegacyMcpServerEntries as V}from"../../core/mcp/server-name.js";import{InboundMessageIdInjector as W}from"../shared/inbound-message-id-injector.js";import{IdentityInjector as z}from"../shared/identity-injector.js";import{syncDefaultSkillsToDir as G}from"../../default-skills/index.js";import{buildSimpleProbeReport as X}from"../shared/probe-util.js";import{compactToolInputForWire as Y}from"../shared/tool-wire-payload.js";import{normalizeOCProviderModels as K}from"./opencode-types.js";import{buildOpencodeConfigContent as Z}from"./opencode-config.js";import{agentIdOf as k}from"../shared/native-provider-config.js";import{formatOpenCodeErrorMessage as A}from"./format-error.js";import{OpenCodeTransport as ee}from"./opencode-transport.js";import{log as r}from"../../core/log/index.js";import{splitTextForAibotProtocol as x}from"../../core/protocol/index.js";class te extends y{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitError(e){if(this.listenerCount("error")===0){r.warn("opencode-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}const se=200,ie=2e3,ne=12e4,oe=90*1e3,b=1800*1e3,P=3e4,R=600*1e3,re="claude_interaction_reply",ae="set_mode",de="set_model",ce="127.0.0.1",le=0,he=1e3,m={fullAuto:"full_auto",approval:"approval"},C=[{id:m.fullAuto,displayName:"Full Auto"},{id:m.approval,displayName:"Approval"}],pe=[{permission:"*",pattern:"*",action:"allow"}],ue=[{permission:"doom_loop",pattern:"*",action:"ask"},{permission:"external_directory",pattern:"*",action:"ask"},{permission:"question",pattern:"*",action:"deny"},{permission:"plan_enter",pattern:"*",action:"deny"},{permission:"plan_exit",pattern:"*",action:"deny"},{permission:"repo_clone",pattern:"*",action:"deny"},{permission:"repo_overview",pattern:"*",action:"deny"},{permission:"read",pattern:"*.env",action:"ask"},{permission:"read",pattern:"*.env.*",action:"ask"},{permission:"read",pattern:"*.env.example",action:"allow"}];function w(g){const e=String(g??"").trim().toLowerCase();if(e==="full_auto"||e==="fullauto")return m.fullAuto;if(e==="approval"||e==="ask"||e==="autoedit"||e==="auto_edit")return m.approval}function E(g){try{return process.kill(g,0),!0}catch(e){return e.code==="EPERM"}}class Fe extends y{type="opencode";config;callbacks;options;identity;inboundMessageIds=new W;process=null;transport=new ee;alive=!1;stopped=!1;internalApi=null;sessions=new Map;sessionModes=new Map;sessionModels=new Map;availableModels=[];modelContextLimits=new Map;contextTokensBySession=new Map;activeRun=null;completedEvents=new Set;clientMsgSeq=0;auditCaptures=new Map;completedAuditBoundaries=new Map;idleTimer=null;lastSseAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;toolCardsSent=new Set;messageRoles=new Map;pendingPartChunks=new Map;pendingPermissions=new Map;pendingQuestions=new Map;permissionHandler=null;constructor(e,s,t){super(),this.config=e,this.callbacks=s,this.options=t??{},this.identity=new z("opencode-adapter",s.getAgentProfile)}onAgentProfileChanged(){this.identity.onProfileChanged()}async start(){await this.startInternalApiAndInjectMcp();const e=this.options.hostname??ce,s=this.options.port??le,t=await this.spawnAndWait(e,s),i=this.resolveCwd();await this.transport.connect(t,i),this.transport.on("event",n=>this.handleSseEvent(n));try{await this.refreshModels()}catch(n){r.warn("opencode-adapter",`Failed to fetch providers for toolbar models: ${n instanceof Error?n.message:String(n)}`)}r.info("opencode-adapter",`Ready (pid=${this.process?.pid}, url=${t})`)}async refreshModels(e){const s=await this.transport.listProviders(e),t=[],i=new Map;for(const n of s)for(const o of K(n.models)){t.push({id:`${n.id}/${o.id}`,displayName:o.name||o.id});const a=o.limit?.context;typeof a=="number"&&a>0&&i.set(`${n.id}/${o.id}`,a)}t.sort((n,o)=>{const a=n.displayName.toLowerCase().localeCompare(o.displayName.toLowerCase());return a!==0?a:n.id.localeCompare(o.id)}),this.availableModels=t,this.modelContextLimits=i,r.info("opencode-adapter",`Fetched ${t.length} models from ${s.length} providers (directory=${e??"current"})`)}resolveContextLimit(e,s){const t=this.modelContextLimits.get(`${e}/${s}`);if(t)return t;let i;for(const[n,o]of this.modelContextLimits)n.startsWith(`${e}/`)&&(i=i===void 0?o:Math.max(i,o));return i}buildContextWindowMeta(e,s,t,i){if(!i||i<=0)return;const n=this.resolveContextLimit(s,t);if(!n)return;const o=Math.min(100,i/n*100);return{context_window:{used:i,size:n,usedPercentage:o,remainingPercentage:100-o}}}async stop(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.transport.disconnect(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.process){const e=this.process;try{T(e,"SIGTERM")}catch{}const s=setTimeout(()=>{try{T(e,"SIGKILL")}catch{}},5e3);e.on("exit",()=>clearTimeout(s)),this.process=null}}isAlive(){return this.alive}async createSession(e){const s=e.cwd??this.resolveCwd();await this.transport.useDirectory(s);const t=await this.transport.createSession({title:`grix-${Date.now()}`},s);return this.sessions.set(t.id,{ocSessionId:t.id,cwd:s}),r.info("opencode-adapter",`Created OC session ${t.id} for cwd=${s}`),await this.applySessionPermission(t.id,t.id,s),t.id}async resumeSession(e,s){const t=this.sessions.get(e);if(t?.ocSessionId)try{await this.transport.useDirectory(t.cwd),await this.transport.getSession(t.ocSessionId,t.cwd),await this.applySessionPermission(e,t.ocSessionId,t.cwd)}catch{r.warn("opencode-adapter",`OC session ${t.ocSessionId} gone, will create new on next prompt`),t.ocSessionId=""}}async destroySession(e){const s=this.sessions.get(e),t=s?s.ocSessionId:e;if(t)try{await this.transport.deleteSession(t,s?.cwd)}catch{}this.sessions.delete(e),this.contextTokensBySession.delete(e),this.identity.forgetSession(e),this.inboundMessageIds.forgetSession(e)}sendPrompt(e){const s=new te(e.adapterSessionId);return this.sendOcPrompt(e.adapterSessionId,this.buildPromptText(e)).catch(t=>{s.emitError(t instanceof Error?t:new Error(String(t)))}),s}async cancel(e){if(this.activeRun)try{await this.transport.abortSession(this.activeRun.ocSessionId,this.activeRun.cwd)}catch{}}deliverInboundEvent(e){const{event_id:s,session_id:t,content:i}=e;if(this.completedEvents.has(s)){r.info("opencode-adapter",`Dropping duplicate event ${s}`),this.callbacks.sendEventAck(s,t),this.callbacks.sendEventResult(s,"responded");return}if(!this.alive){r.warn("opencode-adapter",`Dropping event ${s}: process not alive`),this.callbacks.sendEventAck(s,t),this.callbacks.sendEventResult(s,"failed","Agent process not running");return}this.activeRun&&this.activeRun.eventId!==s&&(r.info("opencode-adapter",`steer: ${this.activeRun.eventId} -> ${s}`),this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeRun.eventId,"canceled","steered to new event"),this.clearRun()),r.info("opencode-adapter",`prompt: event=${s} session=${t}`),this.callbacks.sendEventAck(s,t),this.startRun(s,t,e.audit?.enabled===!0),this.startComposing(t),this.resetIdleTimer();const n=this.buildPromptTextFromEvent(e);this.sendOcPrompt(t,n).catch(o=>{r.error("opencode-adapter",`prompt_async failed: ${o}`),this.finishRun("failed",String(o))})}deliverStopEvent(e,s){this.activeRun&&this.activeRun.eventId===e&&(r.info("opencode-adapter",`stop: event=${e}`),this.rejectAllPendingInteractions(),this.transport.abortSession(this.activeRun.ocSessionId,this.activeRun.cwd).catch(()=>{}),this.flushTextBuffer(),this.finishRun("canceled","stopped by user"))}setPermissionHandler(e){this.permissionHandler=e}async ping(e){return this.transport.healthCheck()}getStatus(){return{alive:this.alive,busy:this.activeRun!==null,sessions:this.sessions.size}}getActiveEventIds(){return this.activeRun?[this.activeRun.eventId]:[]}takeAuditBoundary(e){const s=this.completedAuditBoundaries.get(e);return s&&this.completedAuditBoundaries.delete(e),s}clearActiveEventForShutdown(){this.stopIdleTimer(),this.stopTextFlush(),this.rejectAllPendingInteractions(),this.activeRun&&this.snapshotAuditBoundary(this.activeRun),this.activeRun=null}getMcpConfig(){if(!this.internalApi)return null;const e=D(j(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:J(this.callbacks.getAgentId?.()),command:process.execPath,args:[e,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const e=this.process?.pid;return e?q(e,[e]):!1}async probe(e){const s=this.getStatus();return X(this.config.command||"opencode",{alive:s.alive,busy:s.busy,started:!!this.process},e)}async startInternalApiAndInjectMcp(){try{this.internalApi=new H,this.internalApi.setInvokeHandler(async(d,l,h,u)=>this.callbacks.agentInvoke(d,l,u)),await this.internalApi.start(0),r.info("opencode-adapter",`Internal API started at ${this.internalApi.url}`);const e=this.getMcpConfig(),s=k(this.config.command||"opencode")||"opencode",t=process.env.XDG_CONFIG_HOME||S(N(),".config"),i=S(t,s,`${s}.json`);O(L(i),{recursive:!0});let n={};try{$(i)&&(n=JSON.parse(F(i,"utf8")))}catch{}const o=n.mcp&&typeof n.mcp=="object"?n.mcp:{};V(o,this.internalApi.url),o[e.name]={type:"local",command:[e.command,...e.args??[]],enabled:!0},n.mcp=o,B(i,`${JSON.stringify(n,null,2)}
2
+ `,"utf8"),r.info("opencode-adapter",`MCP config injected into ${i}`);const a=S(t,s,"skills"),c=G(a);c.length>0&&r.info("opencode-adapter",`Synced connector skills to ${a}: [${c.join(", ")}]`)}catch(e){r.warn("opencode-adapter",`Failed to inject MCP tools (non-fatal): ${e instanceof Error?e.message:String(e)}`)}}async handleLocalAction(e){const{action_type:s}=e;if(s==="exec_approve"||s==="exec_reject"||s==="permission_approve"||s==="permission_reject")return this.handlePermissionAction(e);if(s===ae)return this.handleSetModeAction(e);if(s===de)return this.handleSetModelAction(e);if(s===re){const t=e.params??{};if(String(t.kind??"")==="permission"){const i=t.resolution??{},n=String(i.value??"");return this.handlePermissionAction({...e,action_type:n==="allow"?"exec_approve":"exec_reject",params:{...t,approval_command_id:t.request_id}})}return this.handleQuestionReplyAction(e)}return{handled:!1,kind:""}}handleQuestionReplyEvent(e){let s;if(e.action)s={type:"action",value:e.action};else if(e.response?.type==="single")s={type:"text",value:e.response.value};else if(e.response?.type==="map")s={type:"map",entries:e.response.entries};else return{delivered:!1,errorCode:"resolution_invalid",errorMsg:"Question reply response is invalid."};return this.deliverQuestionReply({request_id:e.request_id,resolution:s})}async bindSession(e,s){if(r.info("opencode-adapter",`bindSession: ${e} \u2192 ${s}`),!this.sessions.has(e))this.sessions.set(e,{ocSessionId:"",cwd:s});else{const t=this.sessions.get(e);t.cwd=s}try{await this.refreshModels(s)}catch(t){r.warn("opencode-adapter",`Failed to refresh models on bind: ${t instanceof Error?t.message:String(t)}`)}this.callbacks.sendUpdateBindingCard(e,"ready",s,this.buildToolbarMeta(e))}resolveModeId(e){if(e){const t=this.sessionModes.get(e);if(t)return t}const s=w(this.options.permissionPolicy);if(s)return s;if(e){const t=w(this.options.bindingStore?.get(e)?.modeId);if(t)return t}return m.fullAuto}buildModeToolbarMeta(e){const s=this.resolveModeId(e);return{mode_id:s,currentModeId:s,available_modes:C.map(t=>({...t}))}}async applySessionPermission(e,s,t){const i=this.resolveModeId(e),n=i===m.fullAuto?pe:ue;try{await this.transport.updateSessionPermission(s,n,t),r.info("opencode-adapter",`Applied session permission ruleset (${i}) to ${s}`)}catch(o){r.warn("opencode-adapter",`Failed to apply session permission ruleset: ${o instanceof Error?o.message:String(o)}`)}}async handleSetModeAction(e){const s=e.params??{},t=String(s.session_id??this.options.aibotSessionId??"").trim(),i=w(s.mode_id);if(!i||!t)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"invalid_params","mode_id must be full_auto or approval and session_id is required"),{handled:!0,kind:"set_mode"};this.sessionModes.set(t,i);const n=this.sessions.get(t);n?.ocSessionId&&await this.applySessionPermission(t,n.ocSessionId,n.cwd);const o=n?.cwd??this.getSessionCwd(t);return this.callbacks.sendUpdateBindingCard(t,"ready",o,this.buildToolbarMeta(t)),this.callbacks.sendLocalActionResult(e.action_id,"ok",{outcome:"mode_set",session_context:{mode_id:i,modeId:i},mode_id:i,available_modes:C.map(a=>({...a}))}),{handled:!0,kind:"set_mode"}}resolveModelId(e){if(e){const t=this.sessionModels.get(e);if(t)return t}const s=String(this.options.model??"").trim();if(s)return s;if(e){const t=String(this.options.bindingStore?.get(e)?.modelId??"").trim();if(t)return t}return""}buildModelToolbarMeta(e){const s=this.resolveModelId(e);return{model_id:s,currentModelId:s,available_models:this.availableModels.map(t=>({...t}))}}buildToolbarMeta(e){return{...this.buildModelToolbarMeta(e),...this.buildModeToolbarMeta(e)}}handleSetModelAction(e){const s=e.params??{},t=String(s.session_id??this.options.aibotSessionId??"").trim(),i=String(s.model_id??"").trim();if(!i||!t)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"invalid_params","model_id and session_id are required"),{handled:!0,kind:"set_model"};this.sessionModels.set(t,i);const n=this.sessions.get(t)?.cwd??this.getSessionCwd(t);return this.callbacks.sendUpdateBindingCard(t,"ready",n,this.buildToolbarMeta(t)),this.callbacks.sendLocalActionResult(e.action_id,"ok",{outcome:"model_set",session_context:{model_id:i,modelId:i},model_id:i,available_models:this.availableModels.map(o=>({...o}))}),{handled:!0,kind:"set_model"}}async spawnAndWait(e,s){const t=this.resolveCwd();try{if(!(await M(t)).isDirectory())throw new Error(`Bound path is not a directory: ${t}`)}catch(i){throw String(i?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${t}. Please rebind with /grix open <valid-directory>.`):i}return new Promise((i,n)=>{const o=this.config.command||"opencode",c=[...this.config.args??["serve"],`--hostname=${e}`,`--port=${s}`],d={...process.env,...this.config.env},l=Z({model:this.options.model,permissionPolicy:this.options.permissionPolicy,provider:this.options.provider});if(l){const v=(k(o)||"opencode").toUpperCase().replace(/[^A-Z0-9_]/g,"_")||"OPENCODE";d[`${v}_CONFIG_CONTENT`]=JSON.stringify(l)}const h=Q(o,typeof d.PATH=="string"?d.PATH:void 0);r.info("opencode-adapter",`Spawning: ${h} ${c.join(" ")} (cwd=${t})`),this.process=U(h,c,{env:d,cwd:t}).process;let u="",f=!1;const I=setTimeout(()=>{f||(f=!0,n(new Error(`opencode serve did not start after ${P/1e3}s`)))},P);this.process.stdout?.on("data",p=>{if(u+=p.toString(),!f)for(const v of u.split(`
3
+ `)){const _=v.match(/\bserver listening on (https?:\/\/\S+)/);if(_){clearTimeout(I),f=!0,this.alive=!0,i(_[1]);return}}}),this.process.stderr?.on("data",p=>{const v=p.toString().trim();v&&r.info("opencode-adapter",`[stderr] ${v}`)}),this.process.on("error",p=>{r.error("opencode-adapter",`Spawn error: ${p.message}`),clearTimeout(I),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Spawn error: ${p.message}`),this.clearRun()),f?this.stopped||this.emit("exit",1):(f=!0,n(p))}),this.process.on("exit",p=>{r.info("opencode-adapter",`Process exited (code=${p})`),clearTimeout(I),this.alive=!1,this.transport.disconnect(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Process exited (code=${p})`),this.clearRun()),f?this.stopped||this.emit("exit",p??1):(f=!0,n(new Error(`opencode serve exited with code ${p}`)))})})}async ensureOcSession(e){const s=this.sessions.get(e),t=this.getSessionCwd(e);if(await this.transport.useDirectory(t),s?.ocSessionId)try{return await this.transport.getSession(s.ocSessionId,t),s.ocSessionId}catch{r.warn("opencode-adapter",`OC session ${s.ocSessionId} gone, creating new`),s.ocSessionId=""}const i=this.options.bindingStore?.getAcpSessionId(e);if(i)try{return await this.transport.getSession(i,t),this.sessions.set(e,{ocSessionId:i,cwd:t}),r.info("opencode-adapter",`Resumed OC session ${i} for aibot=${e}`),await this.applySessionPermission(e,i,t),i}catch{r.warn("opencode-adapter",`Persisted OC session ${i} gone, creating new`)}const n=await this.transport.createSession({title:`grix-${e.slice(-8)}`},t);return this.sessions.set(e,{ocSessionId:n.id,cwd:t}),this.options.bindingStore?.setAcpSessionId(e,n.id),r.info("opencode-adapter",`Created OC session ${n.id} for aibot=${e}`),await this.applySessionPermission(e,n.id,t),n.id}async sendOcPrompt(e,s){const t=this.getSessionCwd(e),i=await this.ensureOcSession(e);this.activeRun&&(this.activeRun.ocSessionId=i,this.activeRun.cwd=t);const n=this.resolveModelId(e),o=n.indexOf("/"),a=o>0&&o<n.length-1?{providerID:n.slice(0,o),modelID:n.slice(o+1)}:void 0,c=this.identity.formatBlock();c&&r.info("opencode-adapter",`Injected agent identity via prompt.system session=${e}`),await this.transport.sendPromptAsync(i,{parts:[{type:"text",text:s}],...a?{model:a}:{},...c?{system:c}:{}},t)}handleSseEvent(e){if(!this.stopped){if(this.updateToolInFlight(e),e.type!=="server.heartbeat"&&(this.lastSseAt=Date.now(),this.resetIdleTimer()),this.activeRun){const s=this.auditCaptures.get(this.activeRun.eventId);s&&s.push({sequence:s.length,observedAt:new Date().toISOString(),event:structuredClone(e)})}switch(e.type){case"message.part.updated":{if(!this.activeRun)break;const s=e.part,t=e.delta;if(s.type==="text"){const i=t||s.text;i&&this.acceptAssistantPartText(s.messageID,"text",i)}else s.type==="reasoning"?t&&this.acceptAssistantPartText(s.messageID,"reasoning",t):s.type==="tool"&&this.handleToolPartUpdate(s,t);break}case"message.updated":{if(!this.activeRun)break;const s=e.info;if(this.rememberMessageRole(s),s.role==="assistant"){const t=s;typeof t.tokens?.input=="number"&&this.contextTokensBySession.set(this.activeRun.sessionId,t.tokens.input);const i=this.buildContextWindowMeta(this.activeRun.sessionId,t.providerID,t.modelID,t.tokens?.input);this.callbacks.sendUpdateBindingCard(this.activeRun.sessionId,"composing",this.activeRun.cwd,{...this.buildToolbarMeta(this.activeRun.sessionId),model_provider:t.providerID,model_id:t.modelID,...i??{}}),t.error&&r.warn("opencode-adapter",`Message error: ${JSON.stringify(t.error)}`);const n=this.activeRun.ocSessionId;n&&t.sessionID===n&&(t.error?(this.flushTextBuffer(),this.finishRun("failed",A(t.error,t.error.type||"unknown error"))):t.time?.completed&&t.finish!=="tool-calls"&&(this.flushTextBuffer(),this.finishRun("responded")))}break}case"session.idle":{if(!this.activeRun)break;e.sessionID===this.activeRun.ocSessionId&&(this.flushTextBuffer(),this.finishRun("responded"));break}case"session.status":{if(!this.activeRun)break;e.sessionID===this.activeRun.ocSessionId&&e.status.type==="idle"&&(this.flushTextBuffer(),this.finishRun("responded"));break}case"session.error":{if(!this.activeRun)break;const s=A(e.error);r.error("opencode-adapter",`Session error: ${s}`),this.flushTextBuffer(),this.finishRun("failed",s);break}case"permission.updated":{this.handlePermission(e.permission);break}case"permission.asked":{this.handlePermissionAsked(e);break}case"question.asked":{this.handleQuestionAsked(e);break}case"permission.replied":case"question.replied":case"question.rejected":r.debug("opencode-adapter",`Interaction settled: ${e.type}`);break;case"session.created":case"session.updated":case"session.deleted":case"session.compacted":case"session.diff":case"file.edited":case"server.connected":case"server.heartbeat":break;case"server.instance.disposed":{r.warn("opencode-adapter",`Server instance disposed: ${e.directory}`),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeRun.eventId,"failed","server instance disposed"),this.clearRun()),this.stopped||this.emit("exit",-1);break}default:r.debug("opencode-adapter",`Unhandled SSE event type: ${e.type}`);break}}}updateToolInFlight(e){if(e.type!=="message.part.updated")return;const s=e.part;if(s?.type!=="tool"||!s.callID)return;const t=s.state?.status;t==="pending"||t==="running"?this.toolCallsInFlight.add(s.callID):(t==="completed"||t==="error")&&this.toolCallsInFlight.delete(s.callID)}rememberMessageRole(e){const s=typeof e.id=="string"?e.id.trim():"";s&&(e.role!=="user"&&e.role!=="assistant"||(this.messageRoles.set(s,e.role),this.flushOrDropPendingParts(s,e.role)))}acceptAssistantPartText(e,s,t){if(!this.activeRun||!t)return;const i=typeof e=="string"?e.trim():"";if(!i)return;const n=this.messageRoles.get(i);if(n==="user")return;if(n==="assistant"){this.emitAssistantPartChunk(s,t);return}const o=this.pendingPartChunks.get(i)??[];o.push({kind:s,value:t}),this.pendingPartChunks.set(i,o)}flushOrDropPendingParts(e,s){const t=this.pendingPartChunks.get(e);if(this.pendingPartChunks.delete(e),!(!t||t.length===0)&&s==="assistant")for(const i of t)this.emitAssistantPartChunk(i.kind,i.value)}emitAssistantPartChunk(e,s){if(!(!this.activeRun||!s)){if(e==="reasoning"){this.callbacks.sendThinking(this.activeRun.eventId,this.activeRun.sessionId,s);return}this.appendText(s)}}clearMessageRoleState(){this.messageRoles.clear(),this.pendingPartChunks.clear()}handleToolPartUpdate(e,s){if(!this.activeRun)return;const t=e.state;switch(t.status){case"pending":case"running":{this.sendToolUseOnce(e,t.input);break}case"completed":{this.sendToolUseOnce(e,t.input);break}case"error":{this.sendToolUseOnce(e,t.input),this.callbacks.sendToolResult(this.activeRun.eventId,this.activeRun.sessionId,e.tool,"(failed)");break}}}sendToolUseOnce(e,s){!this.activeRun||this.toolCardsSent.has(e.callID)||(this.flushTextBuffer(),this.toolCardsSent.add(e.callID),this.callbacks.sendToolUse(this.activeRun.eventId,this.activeRun.sessionId,e.tool,Y(s??{})))}onPermissionTimeout(e){const s=this.pendingPermissions.get(e);s&&(this.pendingPermissions.delete(e),r.error("opencode-adapter",`Permission approval timeout: ${e}`),this.transport.respondPermission(s.ocSessionId,e,"reject",s.cwd).catch(()=>{}),this.activeRun&&this.activeRun.eventId===s.eventId&&(this.flushTextBuffer(),this.finishRun("failed","permission approval timeout")))}trackPendingPermission(e){if(!this.activeRun)return;this.stopIdleTimer();const s=setTimeout(()=>this.onPermissionTimeout(e),R);this.pendingPermissions.set(e,{permissionId:e,eventId:this.activeRun.eventId,ocSessionId:this.activeRun.ocSessionId,cwd:this.activeRun.cwd,timer:s})}handlePermissionAsked(e){if(!this.activeRun){this.transport.respondPermission(e.sessionID,e.id,"reject").catch(o=>{r.warn("opencode-adapter",`Orphan permission reject failed: ${o}`)});return}const{eventId:s,sessionId:t,ocSessionId:i}=this.activeRun;if(this.resolveModeId(t)===m.fullAuto){this.transport.respondPermission(i,e.id,"always",this.activeRun.cwd).catch(o=>{r.warn("opencode-adapter",`Auto-approve failed: ${o}`)});return}this.trackPendingPermission(e.id);const n=e.patterns.length>0?`${e.permission}: ${e.patterns.join(", ")}`:e.permission;this.callbacks.sendPermissionCard?this.callbacks.sendPermissionCard({eventId:s,sessionId:t,approvalId:e.id,toolName:e.permission,toolTitle:n,toolInput:JSON.stringify(e.metadata??{})}):this.callbacks.sendToolUse(s,t,e.permission,JSON.stringify(e.metadata??{}))}handlePermission(e){if(!this.activeRun)return;const{eventId:s,sessionId:t,ocSessionId:i}=this.activeRun;if(this.resolveModeId(t)===m.fullAuto){this.transport.respondPermission(i,e.id,"always",this.activeRun.cwd).catch(n=>{r.warn("opencode-adapter",`Auto-approve failed: ${n}`)});return}if(this.trackPendingPermission(e.id),this.callbacks.sendPermissionCard)this.callbacks.sendPermissionCard({eventId:s,sessionId:t,approvalId:e.id,toolName:e.type,toolTitle:e.title||e.type,toolInput:JSON.stringify(e.metadata??{})});else{const n=JSON.stringify(e.metadata??{});this.callbacks.sendToolUse(s,t,e.type,n)}}handlePermissionAction(e){if(!this.activeRun)return{handled:!1,kind:""};const s=e.params??{},t=String(s.approval_id??s.approval_command_id??s.approvalId??s.tool_call_id??"");let i=t?this.pendingPermissions.get(t):void 0;if(!i){for(const a of this.pendingPermissions.values())if(a.eventId===this.activeRun.eventId){i=a;break}}if(!i)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"unknown_or_expired_approval_id","That approval request is no longer pending."),{handled:!0,kind:"permission"};const n=e.action_type==="exec_approve"||e.action_type==="permission_approve",o=n?"once":"reject";return clearTimeout(i.timer),this.pendingPermissions.delete(i.permissionId),this.transport.respondPermission(i.ocSessionId,i.permissionId,o,i.cwd).then(()=>{r.info("opencode-adapter",`Permission ${o}: ${i.permissionId}`),this.resetIdleTimer()}).catch(a=>{r.warn("opencode-adapter",`Permission response failed: ${a}`),this.resetIdleTimer()}),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:i.permissionId,decision:n?"approve":"reject"}),{handled:!0,kind:"permission"}}async handleExecApprovalEvent(e){if(!this.activeRun)return{delivered:!1,errorCode:"approval_not_found",errorMsg:"no active run"};const s=String(e.approval_id??e.approval_command_id??e.tool_call_id??"");let t=s?this.pendingPermissions.get(s):void 0;if(!t){for(const n of this.pendingPermissions.values())if(n.eventId===this.activeRun.eventId){t=n;break}}if(!t)return{delivered:!1,errorCode:"approval_not_found",errorMsg:"That approval request is no longer pending."};const i=e.decision==="deny"?"reject":e.decision==="allow-always"?"always":"once";return clearTimeout(t.timer),this.pendingPermissions.delete(t.permissionId),this.transport.respondPermission(t.ocSessionId,t.permissionId,i,t.cwd).then(()=>{r.info("opencode-adapter",`Permission ${i} (text event): ${t.permissionId}`),this.resetIdleTimer()}).catch(n=>{r.warn("opencode-adapter",`Permission response failed: ${n}`),this.resetIdleTimer()}),{delivered:!0}}onQuestionTimeout(e){const s=this.pendingQuestions.get(e);s&&(this.pendingQuestions.delete(e),r.error("opencode-adapter",`Question answer timeout: ${e}`),this.transport.rejectQuestion(e,s.cwd).catch(()=>{}),this.activeRun&&this.activeRun.eventId===s.eventId&&(this.flushTextBuffer(),this.finishRun("failed","question answer timeout")))}handleQuestionAsked(e){if(!this.activeRun){this.transport.rejectQuestion(e.id).catch(n=>{r.warn("opencode-adapter",`Orphan question reject failed: ${n}`)});return}const{eventId:s,sessionId:t}=this.activeRun;this.stopIdleTimer();const i=setTimeout(()=>this.onQuestionTimeout(e.id),R);if(this.pendingQuestions.set(e.id,{requestId:e.id,eventId:s,cwd:this.activeRun.cwd,questions:e.questions,timer:i}),this.callbacks.sendAgentQuestionCard)this.callbacks.sendAgentQuestionCard(s,t,{request_id:e.id,mode:"form",questions:e.questions.map(n=>({header:n.header,prompt:n.question,...n.options.length>0?{options:n.options.map(o=>o.label)}:{},...n.multiple!==void 0?{multi_select:n.multiple}:{}})),expires_at:Date.now()+R});else{const n=e.questions.map(o=>o.question).join(`
4
4
  `);this.callbacks.sendRunError(s,t,`Agent asks: ${n}`)}}handleQuestionReplyAction(e){const s=e.params??{},t=this.deliverQuestionReply(s);return t.delivered?this.callbacks.sendLocalActionResult(e.action_id,"ok",t.result):this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,t.errorCode,t.errorMsg),{handled:!0,kind:"question_reply"}}deliverQuestionReply(e){const s=String(e.request_id??""),t=s?this.pendingQuestions.get(s):void 0;if(!t)return{delivered:!1,errorCode:"interaction_request_not_pending",errorMsg:"The question is no longer pending; the reply was not delivered."};const i=e.resolution??{},n=String(i.type??""),o=(d,l)=>(clearTimeout(t.timer),this.pendingQuestions.delete(t.requestId),d().then(()=>this.resetIdleTimer()).catch(h=>{r.warn("opencode-adapter",`Question response failed: ${h}`),this.resetIdleTimer()}),{delivered:!0,result:l});if(n==="action"){const d=String(i.value??"");if(d==="cancel"||d==="decline")return o(()=>this.transport.rejectQuestion(t.requestId,t.cwd),{request_id:s,resolution:"cancel"})}let a=null;if(Array.isArray(e.answers))a=e.answers.map(d=>Array.isArray(d)?d.map(String):[String(d)]);else if(n==="text"){const d=String(i.value??"");d&&(a=t.questions.map((l,h)=>h===0?[d]:[]))}else if(n==="map"){const d=Array.isArray(i.entries)?i.entries:[];a=t.questions.map((l,h)=>{const u=d.find(f=>f.key===l.header||f.key===String(h+1));return u&&u.value?[u.value]:[]}),a.every(l=>l.length===0)&&d.length>0&&(a=t.questions.map((l,h)=>{const u=d[h]?.value;return u?[String(u)]:[]}))}if(!a||a.every(d=>d.length===0))return o(()=>this.transport.rejectQuestion(t.requestId,t.cwd),{request_id:s,resolution:"cancel"});const c=a;return o(()=>this.transport.replyQuestion(t.requestId,c,t.cwd),{request_id:s,resolution:"answer"})}rejectAllPendingInteractions(){for(const e of this.pendingPermissions.values())clearTimeout(e.timer),this.transport.respondPermission(e.ocSessionId,e.permissionId,"reject",e.cwd).catch(()=>{});this.pendingPermissions.clear();for(const e of this.pendingQuestions.values())clearTimeout(e.timer),this.transport.rejectQuestion(e.requestId,e.cwd).catch(()=>{});this.pendingQuestions.clear()}hasPendingInteractionForRun(e){for(const s of this.pendingPermissions.values())if(s.eventId===e)return!0;for(const s of this.pendingQuestions.values())if(s.eventId===e)return!0;return!1}startRun(e,s,t=!1){this.activeRun={eventId:e,sessionId:s,ocSessionId:"",cwd:this.getSessionCwd(s),chunkSeq:0,clientMsgId:`oc_${++this.clientMsgSeq}_${Date.now()}`,textBuffer:"",flushTimer:null},this.toolCardsSent.clear(),t&&this.auditCaptures.set(e,[]),this.lastSseAt=Date.now(),this.livenessExtendStartAt=void 0}finishRun(e,s){const t=this.activeRun;if(!t)return;if(this.completedEvents.add(t.eventId),this.completedEvents.size>he){const c=[...this.completedEvents].slice(-500);this.completedEvents=new Set(c)}this.snapshotAuditBoundary(t),this.activeRun=null,this.rejectAllPendingInteractions(),this.toolCallsInFlight.clear(),this.toolCardsSent.clear(),this.livenessExtendStartAt=void 0,this.clearMessageRoleState(),this.stopComposing(),this.stopIdleTimer();const i=++t.chunkSeq,n=t.clientMsgId,o=e==="failed"&&!!s;o&&this.callbacks.sendRunError(t.eventId,t.sessionId,s);const a=()=>{this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t.eventId,t.sessionId,n).then(()=>{this.callbacks.sendEventResult(t.eventId,e,s,void 0,o)}).catch(c=>{const d=e==="responded"?"failed":e,l=e==="responded"?`final output delivery failed: ${c instanceof Error?c.message:String(c)}`:s,h=e==="responded"?!1:o;this.callbacks.sendEventResult(t.eventId,d,l,void 0,h)}):(this.callbacks.sendStreamChunk(t.eventId,t.sessionId,"",i,!0,n),this.callbacks.sendEventResult(t.eventId,e,s,void 0,o))};if(t.textBuffer){this.stopTextFlush();for(const c of x(t.textBuffer))t.chunkSeq++,this.callbacks.sendStreamChunk(t.eventId,t.sessionId,c,t.chunkSeq,!1,t.clientMsgId);t.textBuffer=""}a(),this.emit("eventDone",t.eventId)}clearRun(){this.activeRun?.flushTimer&&clearTimeout(this.activeRun.flushTimer);const e=this.activeRun?.eventId;this.activeRun&&this.snapshotAuditBoundary(this.activeRun),this.activeRun=null,this.rejectAllPendingInteractions(),this.toolCallsInFlight.clear(),this.toolCardsSent.clear(),this.livenessExtendStartAt=void 0,this.clearMessageRoleState(),this.stopIdleTimer(),e&&this.emit("eventDone",e)}snapshotAuditBoundary(e){const s=this.auditCaptures.get(e.eventId);s&&(this.completedAuditBoundaries.set(e.eventId,{adapterType:"opencode",providerSessionId:e.ocSessionId||void 0,openCodeEvidence:{events:s}}),this.auditCaptures.delete(e.eventId))}appendText(e){if(this.activeRun){if(this.activeRun.textBuffer+=e,this.activeRun.textBuffer.length>=ie){this.flushTextBuffer();return}this.scheduleTextFlush()}}scheduleTextFlush(){!this.activeRun||this.activeRun.flushTimer||(this.activeRun.flushTimer=setTimeout(()=>{this.activeRun&&(this.activeRun.flushTimer=null),this.flushTextBuffer()},se))}flushTextBuffer(){if(this.stopTextFlush(),!(!this.activeRun||!this.activeRun.textBuffer)){for(const e of x(this.activeRun.textBuffer))this.activeRun.chunkSeq++,this.callbacks.sendStreamChunk(this.activeRun.eventId,this.activeRun.sessionId,e,this.activeRun.chunkSeq,!1,this.activeRun.clientMsgId);this.activeRun.textBuffer=""}}stopTextFlush(){this.activeRun?.flushTimer&&(clearTimeout(this.activeRun.flushTimer),this.activeRun.flushTimer=null)}startComposing(e){}stopComposing(){}shouldExtendByLiveness(){if(!this.activeRun)return!1;const e=this.process?.pid;if(!this.alive||!e||!E(e))return!1;const s=Date.now(),t=this.lastSseAt>0?s-this.lastSseAt:Number.POSITIVE_INFINITY;if(t<oe)return this.livenessExtendStartAt=s,r.info("opencode-adapter",`Liveness check: fresh SSE for ${this.activeRun.eventId} (sseAge=${t}ms, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const n=this.livenessExtendStartAt??s;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=n),s-n>b?(r.warn("opencode-adapter",`Liveness extension budget exhausted for ${this.activeRun.eventId} (no progress for ${Math.round((s-n)/6e4)}min), allowing idle fail`),!1):(r.info("opencode-adapter",`Liveness check: turn in progress for ${this.activeRun.eventId} (toolsInFlight=${this.toolCallsInFlight.size}, sseAge=${Number.isFinite(t)?`${t}ms`:"n/a"}), extending`),!0)}resetIdleTimer(){this.stopIdleTimer(),!(this.stopped||!this.activeRun)&&(this.idleTimer=setTimeout(()=>{if(this.stopped||!this.activeRun)return;if(this.hasPendingInteractionForRun(this.activeRun.eventId)&&this.shouldExtendByLiveness()){r.info("opencode-adapter",`Idle timeout skipped: pending interaction for ${this.activeRun.eventId}, resetting timer`),this.resetIdleTimer();return}if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const e=this.process?.pid,t=!!(this.alive&&e&&E(e))?`liveness budget exhausted after ${b/6e4}min`:"process not alive";r.error("opencode-adapter",`Idle timeout (${t}, toolsInFlight=${this.toolCallsInFlight.size}) \u2014 emitting exit for respawn`),this.flushTextBuffer(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`idle timeout: ${t}`),this.clearRun()),this.emit("exit",-1)},ne))}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}resolveCwd(){const e=this.options.aibotSessionId?this.options.bindingStore?.get(this.options.aibotSessionId)?.cwd:void 0;if(e)return e;const s=(this.config.options??{}).cwd;return typeof s=="string"&&s?s:process.cwd()}getSessionCwd(e){return this.sessions.get(e)?.cwd??this.options.bindingStore?.get(e)?.cwd??this.resolveCwd()}buildPromptText(e){let s=e.text;if(e.contextMessages&&e.contextMessages.length>0){const t=e.contextMessages.map(i=>`[context] ${i.senderId}: ${i.content}`).join(`
5
5
  `);s=`${s}
6
6
 
7
7
  [Conversation context]
8
- ${t}`}return this.identity.injectOnce(e.adapterSessionId,s)}buildPromptTextFromEvent(e){let s=e.content||"";if(e.context_messages_json)try{const i=JSON.parse(e.context_messages_json);if(Array.isArray(i)&&i.length>0){const n=i.map(o=>`[context] ${o.sender_id??"unknown"}: ${o.content}`).join(`
8
+ ${t}`}return s}buildPromptTextFromEvent(e){let s=e.content||"";if(e.context_messages_json)try{const t=JSON.parse(e.context_messages_json);if(Array.isArray(t)&&t.length>0){const i=t.map(n=>`[context] ${n.sender_id??"unknown"}: ${n.content}`).join(`
9
9
  `);s=`${s}
10
10
 
11
11
  [Conversation context]
12
- ${n}`}}catch{}const t=this.identity.injectOnce(e.session_id,s);return this.inboundMessageIds.inject(e.session_id,t,e.msg_id)}}export{Fe as OpenCodeAdapter};
12
+ ${i}`}}catch{}return this.inboundMessageIds.inject(e.session_id,s,e.msg_id)}}export{Fe as OpenCodeAdapter};
@@ -1,7 +1,7 @@
1
- import{execFile as T}from"node:child_process";import{promisify as A}from"node:util";import{EventEmitter as y}from"node:events";import{stat as k}from"node:fs/promises";import{mkdirSync as M,writeFileSync as C,unlinkSync as R,statSync as f,readFileSync as D,existsSync as g}from"node:fs";import{join as u,resolve as B,delimiter as E}from"node:path";import{fileURLToPath as F}from"node:url";import{tmpdir as O,homedir as w}from"node:os";import{resolveCommandPath as N,resolveWindowsExecInvocation as L,spawnCommand as G,killProcessGroup as _,hasChildProcesses as j}from"../../core/runtime/spawn.js";import{InternalApiServer as q}from"../../core/mcp/internal-api-server.js";import{IdentityInjector as J}from"../shared/identity-injector.js";import{compactToolInputForWire as K}from"../shared/tool-wire-payload.js";import{syncDefaultSkillsToDir as U}from"../../default-skills/index.js";import{PiTransport as H}from"./pi-transport.js";import{log as o}from"../../core/log/index.js";import{scanSkills as z}from"../claude/skill-scanner.js";import{SessionBindingStore as V}from"../../core/persistence/session-binding-store.js";import{splitTextForAibotProtocol as Y}from"../../core/protocol/index.js";import{InboundMessageIdInjector as W}from"../shared/inbound-message-id-injector.js";import{buildSimpleProbeReport as X}from"../shared/probe-util.js";import{piGrixProviderId as Q,removePiGrixProvider as Z,writePiGrixProvider as tt}from"./pi-provider-config.js";import{agentIdOf as et}from"../shared/native-provider-config.js";import{writeOmpMcpEntry as it,recordOmpMcpEntryPid as st,removeOmpMcpEntry as nt}from"./omp-mcp-config.js";function rt(d){return et(d)==="omp"}function ot(d){return process.platform!=="win32"?"PATH":Object.keys(d).find(t=>t.toLowerCase()==="path")??"PATH"}function at(d){const t=ot(d),e=String(d[t]??""),i=process.platform==="win32"?"bun.exe":"bun";if(e.split(E).some(r=>r.trim()&&g(u(r.trim(),i))))return d;const n=u(w(),".bun","bin");return g(u(n,i))?(o.info("pi-adapter",`bun \u4E0D\u5728\u5F53\u524D PATH\uFF0C\u8865\u4E0A\u9ED8\u8BA4\u5B89\u88C5\u76EE\u5F55: ${n}`),{...d,[t]:e?`${n}${E}${e}`:n}):d}const x=new Map;function dt(d){const t=u(d,"mcp.json");try{if(!g(t))return{};const i=JSON.parse(D(t,"utf8"))?.mcpServers;return!i||typeof i!="object"||Array.isArray(i)?{}:i}catch(e){return o.warn("pi-adapter",`Failed to read Pi user MCP config ${t}: ${e instanceof Error?e.message:String(e)}`),{}}}async function ct(d){const t=x.get(d);if(t!==void 0)return t;let e=!1;try{const i=A(T),s=L(d,["--help"]),{stdout:n,stderr:r}=await i(s.command,s.args,{timeout:5e3,encoding:"utf-8",windowsVerbatimArguments:s.windowsVerbatimArguments});e=/--mcp-config\b/.test(`${n??""}${r??""}`)}catch{e=!1}return x.set(d,e),o.info("pi-adapter",`Pi --mcp-config \u652F\u6301\u63A2\u6D4B: ${e?"\u652F\u6301":"\u4E0D\u652F\u6301"} (${d})`),e}class lt 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 ht=12e4,pt=90*1e3,P=1800*1e3;function b(d){try{return process.kill(d,0),!0}catch(t){return t.code==="EPERM"}}const ut=500,mt=2e3,v=3,ft=500;function gt(d){return new Promise(t=>setTimeout(t,d))}function vt(d){const t=new Set,e=[];for(const i of d){const s=i.provider?.trim();!s||t.has(s)||(t.add(s),e.push({id:s,display_name:s}))}return e}function m(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 $ extends y{type="pi";config;callbacks;process=null;transport=new H;alive=!1;stopped=!1;internalApi=null;mcpConfigPath=null;cwdMcpJsonDir=null;cwdMcpJsonKey=null;identity;inboundMessageIds=new W;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="";clientType="";constructor(t,e){super(),this.config=t,this.callbacks=e,this.identity=new J("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.bindingStore&&this.aibotSessionId&&(this.piSessionPath=this.bindingStore.getPiSessionPath(this.aibotSessionId)??null)}isOmp(t){return this.clientType?this.clientType==="omp":rt(t)}resolvePiConfigDir(){return String(this.config.env?.PI_CODING_AGENT_DIR??"").trim()||u(w(),".pi","agent")}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,i]=await Promise.all([this.transport.send("get_available_models"),this.transport.send("get_state")]),s=e.data?.models;if(!s||s.length===0){if(t<v){await gt(ft);continue}o.warn("pi-adapter",`syncModelBinding: empty model list after ${v} attempts, giving up`);return}const n=i.data?.model,r={available_models:s.map(c=>({id:c.id,display_name:c.name??c.id,...c.provider?{provider:c.provider}:{}}))},l=vt(s);l.length>0&&(r.available_providers=l),n?.id&&(r.model_id=n.id),n?.provider&&(r.provider_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: ${s.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 currentModel(){try{return(await this.transport.send("get_state")).data?.model??null}catch{return null}}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{R(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 nt(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 lt(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.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=i,this.beginAuditCapture(t),this.resetRunStreamState(),this.startComposing(i,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=${i}`),this.activeEventId=e,this.activeSessionId=i,this.beginAuditCapture(t),this.isStreaming=!0,this.resetRunStreamState(),this.startComposing(i,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 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.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 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{let n=i.provider?.trim();if(!n){const c=((await this.transport.send("get_available_models")).data?.models??[]).filter(p=>p.id===s&&p.provider?.trim());if(c.length>1){const p=(await this.currentModel())?.provider?.trim();n=c.find(h=>h.provider?.trim()===p)?.provider?.trim()}n=n??c[0]?.provider?.trim()}return n?(await this.transport.send("set_model",{provider:n,modelId:s}),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{const l=((await this.transport.send("get_available_models")).data?.models??[]).filter(h=>h.provider?.trim()===s);if(l.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 c=(await this.currentModel())?.id,p=l.find(h=>h.id===c)?.id??l[0].id;return await this.transport.send("set_model",{provider:s,modelId:p}),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"provider_set",provider:s,modelId:p}),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)return null;const t=B(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?j(t,[t]):!1}async probe(t){const e=this.getStatus();return{...await X(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,i){try{if(!this.alive)return{status:"failed",message:"Pi process not running"};switch(t){case"model":{const s=e.trim();if(s){const l=s.indexOf(":");if(l<1)return{status:"failed",message:"Format: provider:model_id"};const c=s.slice(0,l),p=s.slice(l+1);if(!p)return{status:"failed",message:"Format: provider:model_id"};const h=await this.transport.send("set_model",{provider:c,modelId:p});return h?.success?{status:"ok",message:`Model set to ${c}:${p}`}:{status:"failed",message:`Failed to set model: ${h?.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 $}from"node:child_process";import{promisify as T}from"node:util";import{EventEmitter as y}from"node:events";import{stat as k}from"node:fs/promises";import{mkdirSync as R,writeFileSync as M,unlinkSync as C,statSync as f,readFileSync as D,existsSync as g}from"node:fs";import{join as u,resolve as B,delimiter as E}from"node:path";import{fileURLToPath as F}from"node:url";import{tmpdir as O,homedir as w}from"node:os";import{resolveCommandPath as N,resolveWindowsExecInvocation as L,spawnCommand as G,killProcessGroup as _,hasChildProcesses as j}from"../../core/runtime/spawn.js";import{InternalApiServer as q}from"../../core/mcp/internal-api-server.js";import{IdentityInjector as J}from"../shared/identity-injector.js";import{compactToolInputForWire as K}from"../shared/tool-wire-payload.js";import{syncDefaultSkillsToDir as U}from"../../default-skills/index.js";import{PiTransport as H}from"./pi-transport.js";import{log as o}from"../../core/log/index.js";import{scanSkills as z}from"../claude/skill-scanner.js";import{SessionBindingStore as V}from"../../core/persistence/session-binding-store.js";import{splitTextForAibotProtocol as Y}from"../../core/protocol/index.js";import{InboundMessageIdInjector as W}from"../shared/inbound-message-id-injector.js";import{buildSimpleProbeReport as X}from"../shared/probe-util.js";import{piGrixProviderId as Q,removePiGrixProvider as Z,writePiGrixProvider as tt}from"./pi-provider-config.js";import{agentIdOf as et}from"../shared/native-provider-config.js";import{writeOmpMcpEntry as it,recordOmpMcpEntryPid as st,removeOmpMcpEntry as nt}from"./omp-mcp-config.js";function rt(d){return et(d)==="omp"}function ot(d){return process.platform!=="win32"?"PATH":Object.keys(d).find(t=>t.toLowerCase()==="path")??"PATH"}function at(d){const t=ot(d),e=String(d[t]??""),i=process.platform==="win32"?"bun.exe":"bun";if(e.split(E).some(r=>r.trim()&&g(u(r.trim(),i))))return d;const n=u(w(),".bun","bin");return g(u(n,i))?(o.info("pi-adapter",`bun \u4E0D\u5728\u5F53\u524D PATH\uFF0C\u8865\u4E0A\u9ED8\u8BA4\u5B89\u88C5\u76EE\u5F55: ${n}`),{...d,[t]:e?`${n}${E}${e}`:n}):d}const x=new Map;function dt(d){const t=u(d,"mcp.json");try{if(!g(t))return{};const i=JSON.parse(D(t,"utf8"))?.mcpServers;return!i||typeof i!="object"||Array.isArray(i)?{}:i}catch(e){return o.warn("pi-adapter",`Failed to read Pi user MCP config ${t}: ${e instanceof Error?e.message:String(e)}`),{}}}async function ct(d){const t=x.get(d);if(t!==void 0)return t;let e=!1;try{const i=T($),s=L(d,["--help"]),{stdout:n,stderr:r}=await i(s.command,s.args,{timeout:5e3,encoding:"utf-8",windowsVerbatimArguments:s.windowsVerbatimArguments});e=/--mcp-config\b/.test(`${n??""}${r??""}`)}catch{e=!1}return x.set(d,e),o.info("pi-adapter",`Pi --mcp-config \u652F\u6301\u63A2\u6D4B: ${e?"\u652F\u6301":"\u4E0D\u652F\u6301"} (${d})`),e}class lt 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 ht=12e4,pt=90*1e3,b=1800*1e3;function P(d){try{return process.kill(d,0),!0}catch(t){return t.code==="EPERM"}}const ut=500,mt=2e3,v=3,ft=500;function gt(d){return new Promise(t=>setTimeout(t,d))}function vt(d){const t=new Set,e=[];for(const i of d){const s=i.provider?.trim();!s||t.has(s)||(t.add(s),e.push({id:s,display_name:s}))}return e}function m(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 A extends y{type="pi";config;callbacks;process=null;transport=new H;alive=!1;stopped=!1;internalApi=null;mcpConfigPath=null;cwdMcpJsonDir=null;cwdMcpJsonKey=null;identity;inboundMessageIds=new W;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="";clientType="";constructor(t,e){super(),this.config=t,this.callbacks=e,this.identity=new J("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.bindingStore&&this.aibotSessionId&&(this.piSessionPath=this.bindingStore.getPiSessionPath(this.aibotSessionId)??null)}isOmp(t){return this.clientType?this.clientType==="omp":rt(t)}resolvePiConfigDir(){return String(this.config.env?.PI_CODING_AGENT_DIR??"").trim()||u(w(),".pi","agent")}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,i]=await Promise.all([this.transport.send("get_available_models"),this.transport.send("get_state")]),s=e.data?.models;if(!s||s.length===0){if(t<v){await gt(ft);continue}o.warn("pi-adapter",`syncModelBinding: empty model list after ${v} attempts, giving up`);return}const n=i.data?.model,r={available_models:s.map(c=>({id:c.id,display_name:c.name??c.id,...c.provider?{provider:c.provider}:{}}))},l=vt(s);l.length>0&&(r.available_providers=l),n?.id&&(r.model_id=n.id),n?.provider&&(r.provider_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: ${s.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 currentModel(){try{return(await this.transport.send("get_state")).data?.model??null}catch{return null}}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{C(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 nt(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 lt(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.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=i,this.beginAuditCapture(t),this.resetRunStreamState(),this.startComposing(i,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=${i}`),this.activeEventId=e,this.activeSessionId=i,this.beginAuditCapture(t),this.isStreaming=!0,this.resetRunStreamState(),this.startComposing(i,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 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.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 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{let n=i.provider?.trim();if(!n){const c=((await this.transport.send("get_available_models")).data?.models??[]).filter(p=>p.id===s&&p.provider?.trim());if(c.length>1){const p=(await this.currentModel())?.provider?.trim();n=c.find(h=>h.provider?.trim()===p)?.provider?.trim()}n=n??c[0]?.provider?.trim()}return n?(await this.transport.send("set_model",{provider:n,modelId:s}),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{const l=((await this.transport.send("get_available_models")).data?.models??[]).filter(h=>h.provider?.trim()===s);if(l.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 c=(await this.currentModel())?.id,p=l.find(h=>h.id===c)?.id??l[0].id;return await this.transport.send("set_model",{provider:s,modelId:p}),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"provider_set",provider:s,modelId:p}),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)return null;const t=B(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?j(t,[t]):!1}async probe(t){const e=this.getStatus();return{...await X(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,i){try{if(!this.alive)return{status:"failed",message:"Pi process not running"};switch(t){case"model":{const s=e.trim();if(s){const l=s.indexOf(":");if(l<1)return{status:"failed",message:"Format: provider:model_id"};const c=s.slice(0,l),p=s.slice(l+1);if(!p)return{status:"failed",message:"Format: provider:model_id"};const h=await this.transport.send("set_model",{provider:c,modelId:p});return h?.success?{status:"ok",message:`Model set to ${c}:${p}`}:{status:"failed",message:`Failed to set model: ${h?.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(c=>` ${c.provider??"unknown"}:${c.id} (${c.name??c.id})`).join(`
3
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 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=z({mode:"pi"}),n=s.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: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(){try{this.internalApi=new q,this.internalApi.setInvokeHandler(async(l,c,p,h)=>this.callbacks.agentInvoke(l,c,h)),await this.internalApi.start(0),o.info("pi-adapter",`Internal API started at ${this.internalApi.url}`);const t=this.resolvePiConfigDir(),e=this.getMcpConfig(),i=dt(t),s=u(O(),"grix-pi-mcp");M(s,{recursive:!0}),this.mcpConfigPath=u(s,`mcp-${process.pid}-${Date.now()}.json`),C(this.mcpConfigPath,JSON.stringify({mcpServers:{...i,[e.name]:{command:e.command,args:e.args,directTools:!0,lifecycle:"eager"}}}),"utf8"),o.info("pi-adapter",`MCP config written to ${this.mcpConfigPath}`);const n=u(t,"skills"),r=U(n);r.length>0&&o.info("pi-adapter",`Synced connector skills to ${n}: [${r.join(", ")}]`)}catch(t){o.warn("pi-adapter",`Failed to start MCP tools (non-fatal): ${t instanceof Error?t.message:String(t)}`)}}async writeOmpCwdMcpConfig(t){if(!this.mcpConfigPath)return;const e=this.getMcpConfig();if(e)try{const i=await it(t,{name:e.name,command:e.command,args:e.args});this.cwdMcpJsonDir=t,this.cwdMcpJsonKey=i}catch(i){o.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=N(t,typeof process.env.PATH=="string"?process.env.PATH:void 0),i=this.config.args??[],n=i.some(a=>a.startsWith("--mode"))?[...i]:["--mode","rpc",...i],r=this.resolvePiConfigDir(),l=Q(this.agentName);if(this.provider){const a=this.isOmp(e)?"bare":"dollar";await tt(r,l,this.provider,a)?(n.includes("--provider")||n.push("--provider",l),!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")}else await Z(r,l).then(a=>{a&&o.info("pi-adapter",`Removed stale Grix provider "${l}" 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")&&!this.isOmp(e)&&(await ct(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"));let c={...process.env,...this.config.env};this.isOmp(e)&&(c=at(c));const p=this.provider?.apiKey?.trim();p&&!c.GRIX_PROVIDER_API_KEY?.trim()&&(c.GRIX_PROVIDER_API_KEY=p);const h=this.resolveCwd();o.info("pi-adapter",`Spawning: ${e} ${n.join(" ")}`);try{if(!(await k(h)).isDirectory())throw new Error(`Bound path is not a directory: ${h}`)}catch(a){throw String(a?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${h}. Please rebind with /grix open <valid-directory>.`):a}const S=this.isOmp(e);S&&await this.writeOmpCwdMcpConfig(h);try{this.process=G(e,n,{env:c,cwd:h}).process}catch(a){throw o.error("pi-adapter",`PI spawn threw: ${a}`),this.alive=!1,a}S&&this.cwdMcpJsonDir&&this.cwdMcpJsonKey&&this.process.pid&&st(this.cwdMcpJsonDir,this.cwdMcpJsonKey,this.process.pid).catch(a=>{o.warn("pi-adapter",`\u8BB0\u5F55 omp \u5B50\u8FDB\u7A0B pid \u5230 mcp \u72B6\u6001\u6587\u4EF6\u5931\u8D25: ${a instanceof Error?a.message:String(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 I=a.toString().trim();I&&o.info("pi-adapter",`[pi stderr] ${I}`)}),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 i=t;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 n=i.delta;if(n){const r=typeof i.contentIndex=="number"?i.contentIndex:0;this.rememberEmittedText(r,n),this.appendText(n)}}else if(s==="text_end"){const n=i.content,r=typeof i.contentIndex=="number"?i.contentIndex:0;n&&this.appendMissingText(r,n)}else if(s==="thinking_delta"){const n=i.delta;n&&this.activeEventId&&this.activeSessionId&&(this.thinkingSeq++,this.callbacks.sendThinking(this.activeEventId,this.activeSessionId,n))}else if(s==="done"||s==="error"){if(this.flushTextBuffer(),s==="error"){const n=this.piMessageError(i.error,i.reason);o.warn("pi-adapter",`terminal message_update error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${m(i.error)} reason=${m(i.reason)}`),this.recordRunError(n)}this.scheduleDoneGuard()}break}case"message_end":{const i=t.message;i?.role==="assistant"&&i.stopReason==="error"&&(o.warn("pi-adapter",`terminal message_end error event=${this.activeEventId} sessionId=${this.activeSessionId} errorMessage=${m(i.errorMessage)} message=${m(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=K(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(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>=mt){this.flushTextBuffer();return}this.scheduleTextFlush()}scheduleTextFlush(){this.textFlushTimer||(this.textFlushTimer=setTimeout(()=>{this.textFlushTimer=null,this.flushTextBuffer()},ut))}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 s=JSON.parse(t.context_messages_json);if(Array.isArray(s)&&s.length>0){const n=s.map(r=>`[context] ${r.sender_id??"unknown"}: ${r.content}`).join(`
4
+ `):"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(){try{this.internalApi=new q,this.internalApi.setInvokeHandler(async(l,c,p,h)=>this.callbacks.agentInvoke(l,c,h)),await this.internalApi.start(0),o.info("pi-adapter",`Internal API started at ${this.internalApi.url}`);const t=this.resolvePiConfigDir(),e=this.getMcpConfig(),i=dt(t),s=u(O(),"grix-pi-mcp");R(s,{recursive:!0}),this.mcpConfigPath=u(s,`mcp-${process.pid}-${Date.now()}.json`),M(this.mcpConfigPath,JSON.stringify({mcpServers:{...i,[e.name]:{command:e.command,args:e.args,directTools:!0,lifecycle:"eager"}}}),"utf8"),o.info("pi-adapter",`MCP config written to ${this.mcpConfigPath}`);const n=u(t,"skills"),r=U(n);r.length>0&&o.info("pi-adapter",`Synced connector skills to ${n}: [${r.join(", ")}]`)}catch(t){o.warn("pi-adapter",`Failed to start MCP tools (non-fatal): ${t instanceof Error?t.message:String(t)}`)}}async writeOmpCwdMcpConfig(t){if(!this.mcpConfigPath)return;const e=this.getMcpConfig();if(e)try{const i=await it(t,{name:e.name,command:e.command,args:e.args});this.cwdMcpJsonDir=t,this.cwdMcpJsonKey=i}catch(i){o.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=N(t,typeof process.env.PATH=="string"?process.env.PATH:void 0),i=this.config.args??[],n=i.some(a=>a.startsWith("--mode"))?[...i]:["--mode","rpc",...i],r=this.resolvePiConfigDir(),l=Q(this.agentName);if(this.provider){const a=this.isOmp(e)?"bare":"dollar";await tt(r,l,this.provider,a)?(n.includes("--provider")||n.push("--provider",l),!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")}else await Z(r,l).then(a=>{a&&o.info("pi-adapter",`Removed stale Grix provider "${l}" 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")&&!this.isOmp(e)&&(await ct(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"));let c={...process.env,...this.config.env};this.isOmp(e)&&(c=at(c));const p=this.provider?.apiKey?.trim();p&&!c.GRIX_PROVIDER_API_KEY?.trim()&&(c.GRIX_PROVIDER_API_KEY=p);const h=this.resolveCwd();o.info("pi-adapter",`Spawning: ${e} ${n.join(" ")}`);try{if(!(await k(h)).isDirectory())throw new Error(`Bound path is not a directory: ${h}`)}catch(a){throw String(a?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${h}. Please rebind with /grix open <valid-directory>.`):a}const S=this.isOmp(e);S&&await this.writeOmpCwdMcpConfig(h);try{this.process=G(e,n,{env:c,cwd:h}).process}catch(a){throw o.error("pi-adapter",`PI spawn threw: ${a}`),this.alive=!1,a}S&&this.cwdMcpJsonDir&&this.cwdMcpJsonKey&&this.process.pid&&st(this.cwdMcpJsonDir,this.cwdMcpJsonKey,this.process.pid).catch(a=>{o.warn("pi-adapter",`\u8BB0\u5F55 omp \u5B50\u8FDB\u7A0B pid \u5230 mcp \u72B6\u6001\u6587\u4EF6\u5931\u8D25: ${a instanceof Error?a.message:String(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 I=a.toString().trim();I&&o.info("pi-adapter",`[pi stderr] ${I}`)}),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 i=t;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 n=i.delta;if(n){const r=typeof i.contentIndex=="number"?i.contentIndex:0;this.rememberEmittedText(r,n),this.appendText(n)}}else if(s==="text_end"){const n=i.content,r=typeof i.contentIndex=="number"?i.contentIndex:0;n&&this.appendMissingText(r,n)}else if(s==="thinking_delta"){const n=i.delta;n&&this.activeEventId&&this.activeSessionId&&(this.thinkingSeq++,this.callbacks.sendThinking(this.activeEventId,this.activeSessionId,n))}else if(s==="done"||s==="error"){if(this.flushTextBuffer(),s==="error"){const n=this.piMessageError(i.error,i.reason);o.warn("pi-adapter",`terminal message_update error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${m(i.error)} reason=${m(i.reason)}`),this.recordRunError(n)}this.scheduleDoneGuard()}break}case"message_end":{const i=t.message;i?.role==="assistant"&&i.stopReason==="error"&&(o.warn("pi-adapter",`terminal message_end error event=${this.activeEventId} sessionId=${this.activeSessionId} errorMessage=${m(i.errorMessage)} message=${m(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=K(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(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.captureOmpAuditMessages(t.messages),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>=mt){this.flushTextBuffer();return}this.scheduleTextFlush()}scheduleTextFlush(){this.textFlushTimer||(this.textFlushTimer=setTimeout(()=>{this.textFlushTimer=null,this.flushTextBuffer()},ut))}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 s=JSON.parse(t.context_messages_json);if(Array.isArray(s)&&s.length>0){const n=s.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 i=this.identity.injectOnce(t.session_id,e);return this.inbou
9
9
  `);e=`${e}
10
10
 
11
11
  [Conversation context]
12
- ${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.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=f(e).size}catch{i=0}this.activeAuditCapture={eventId:t.event_id,...e?{transcriptPath:e}:{},...i===void 0?{}:{transcriptStartOffset:i}}}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=f(e.transcriptPath).size}catch{}i.transcriptPath=e.transcriptPath,i.transcriptStartOffset=e.transcriptStartOffset??0,i.transcriptEndOffset=s,i.providerSessionId=this.piSessionPath??e.transcriptPath}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()}`}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 n=this.runErrorEmitted;this.clearActive(),this.finalizeEvent(t,e,i,s,n)}finalizeEvent(t,e,i,s,n=!1){const r=this.nextStreamSeq(),l=s?"failed":"responded";o.info("pi-adapter",`finalize event=${t} sessionId=${e} status=${l} clientMsgId=${i??""} terminalError=${s?m(s):""}`),this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t,e,i).then(()=>{this.callbacks.sendEventResult(t,l,s,void 0,n),o.info("pi-adapter",`event ${l} (reliable) event=${t}`)}).catch(c=>{o.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)}`),o.info("pi-adapter",`event failed (final delivery) event=${t}`)}):(this.callbacks.sendStreamChunk(t,e,"",r,!0,i),this.callbacks.sendEventResult(t,l,s,void 0,n),o.info("pi-adapter",`event ${l} 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=${m(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}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())},$.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||!b(t))return!1;const e=Date.now(),i=this.lastRpcAt>0?e-this.lastRpcAt:Number.POSITIVE_INFINITY;if(i<pt)return this.livenessExtendStartAt=e,o.info("pi-adapter",`Liveness check: fresh RPC for ${this.activeEventId} (rpcAge=${i}ms, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const n=this.livenessExtendStartAt??e;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=n),e-n>P?(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(i)?`${i}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,i=!!(this.alive&&t&&b(t))?`liveness budget exhausted after ${P/6e4}min`:"process not alive";o.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)},ht))}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 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{$ as PiAdapter};
12
+ ${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.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=f(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,n=s.timestamp;e.eventRecords.push({type:"message",message:s,timestamp:typeof n=="number"&&Number.isFinite(n)?new Date(n).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=f(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()}`}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 n=this.runErrorEmitted;this.clearActive(),this.finalizeEvent(t,e,i,s,n)}finalizeEvent(t,e,i,s,n=!1){const r=this.nextStreamSeq(),l=s?"failed":"responded";o.info("pi-adapter",`finalize event=${t} sessionId=${e} status=${l} clientMsgId=${i??""} terminalError=${s?m(s):""}`),this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t,e,i).then(()=>{this.callbacks.sendEventResult(t,l,s,void 0,n),o.info("pi-adapter",`event ${l} (reliable) event=${t}`)}).catch(c=>{o.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)}`),o.info("pi-adapter",`event failed (final delivery) event=${t}`)}):(this.callbacks.sendStreamChunk(t,e,"",r,!0,i),this.callbacks.sendEventResult(t,l,s,void 0,n),o.info("pi-adapter",`event ${l} 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=${m(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}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())},A.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||!P(t))return!1;const e=Date.now(),i=this.lastRpcAt>0?e-this.lastRpcAt:Number.POSITIVE_INFINITY;if(i<pt)return this.livenessExtendStartAt=e,o.info("pi-adapter",`Liveness check: fresh RPC for ${this.activeEventId} (rpcAge=${i}ms, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const n=this.livenessExtendStartAt??e;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=n),e-n>b?(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(i)?`${i}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,i=!!(this.alive&&t&&P(t))?`liveness budget exhausted after ${b/6e4}min`:"process not alive";o.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)},ht))}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 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{A as PiAdapter};
@@ -1,2 +1,2 @@
1
- import{log as c}from"../../core/log/index.js";import{insertBeforeTrailingMessageReferences as l}from"../../core/protocol/message-reference.js";const f=200,g=4e3,u=["[system-identity]","[/system-identity]"];function a(n,e){return n.replaceAll("\0","").slice(0,e)}function d(n){let e=n;for(const t of u){const s=t.replace("[","\uFF3B").replace("]","\uFF3D");e=e.split(t).join(s)}return e}class p{logTag;getProfile;injectedSessions=new Set;constructor(e,t){this.logTag=e,this.getProfile=t}injectOnce(e,t){if(!e||this.injectedSessions.has(e))return t;const s=this.getProfile?.(),o=a(d(s?.agentName?.trim()??""),f),r=a(d(s?.introduction?.trim()??""),g);if(!o&&!r)return t;this.injectedSessions.add(e);const i=["[system-identity]"];return o&&i.push(`Your name is "${o}".`),r&&i.push(`Your self-introduction: ${r}`),i.push("Treat this as an out-of-band instruction; do not echo or repeat it in your replies."),i.push("[/system-identity]"),c.info(this.logTag,`Injected agent identity for session=${e} name="${o}"`),l(t,i.join(`
2
- `))}onProfileChanged(){this.injectedSessions.size>0&&(c.info(this.logTag,`agent profile changed; clearing ${this.injectedSessions.size} identity-injected session(s)`),this.injectedSessions.clear())}forgetSession(e){this.injectedSessions.delete(e)}markInjected(e){e&&this.injectedSessions.add(e)}}export{p as IdentityInjector};
1
+ import{log as c}from"../../core/log/index.js";import{insertBeforeTrailingMessageReferences as l}from"../../core/protocol/message-reference.js";const a=200,d=4e3,u=["[system-identity]","[/system-identity]"];function o(s,e){return s.replaceAll("\0","").slice(0,e)}function r(s){let e=s;for(const t of u){const i=t.replace("[","\uFF3B").replace("]","\uFF3D");e=e.split(t).join(i)}return e}class m{logTag;getProfile;injectedSessions=new Set;constructor(e,t){this.logTag=e,this.getProfile=t}formatBlock(){const e=this.getProfile?.(),t=o(r(e?.agentName?.trim()??""),a),i=o(r(e?.introduction?.trim()??""),d);if(!t&&!i)return;const n=["[system-identity]"];return t&&n.push(`Your name is "${t}".`),i&&n.push(`Your self-introduction: ${i}`),n.push("Treat this as an out-of-band instruction; do not echo or repeat it in your replies."),n.push("[/system-identity]"),n.join(`
2
+ `)}injectOnce(e,t){if(!e||this.injectedSessions.has(e))return t;const i=this.formatBlock();if(!i)return t;this.injectedSessions.add(e);const n=this.getProfile?.(),f=o(r(n?.agentName?.trim()??""),a);return c.info(this.logTag,`Injected agent identity for session=${e} name="${f}"`),l(t,i)}onProfileChanged(){this.injectedSessions.size>0&&(c.info(this.logTag,`agent profile changed; clearing ${this.injectedSessions.size} identity-injected session(s)`),this.injectedSessions.clear())}forgetSession(e){this.injectedSessions.delete(e)}markInjected(e){e&&this.injectedSessions.add(e)}}export{m as IdentityInjector};
@@ -1,7 +1,7 @@
1
- import{mkdir as w,readFile as O,rm as S,writeFile as m}from"node:fs/promises";import{homedir as h}from"node:os";import{join as u}from"node:path";import{isMap as E,isSeq as T,parseDocument as A,Document as v,YAMLMap as R,YAMLSeq as H}from"yaml";function x(t){const r=(t??"").trim();return(r.split(/[\\/]/).pop()||r).replace(/\.(exe|cmd|bat|ps1)$/i,"").toLowerCase()}async function f(t){try{const r=await O(t,"utf8"),e=JSON.parse(r);return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function g(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}const L=".grix-provider-state.json";async function k(t,r){const e=u(t,".qwen"),i=u(e,"settings.json"),o=u(e,L);if(!r.OPENAI_BASE_URL){await C(i,o);return}const n=await f(i),a=g(n.security),l=g(a.auth),s=g(n.model),c=await f(o),p={previousSelectedType:Object.keys(c).length>0?typeof c.previousSelectedType=="string"?c.previousSelectedType:null:typeof l.selectedType=="string"?l.selectedType:null,previousModelName:Object.keys(c).length>0?typeof c.previousModelName=="string"?c.previousModelName:null:typeof s.name=="string"?s.name:null,writtenModelName:r.OPENAI_MODEL??null};l.selectedType="openai",a.auth=l,n.security=a,r.OPENAI_MODEL&&(s.name=r.OPENAI_MODEL,n.model=s),await w(e,{recursive:!0}),await m(i,`${JSON.stringify(n,null,2)}
2
- `,"utf8"),await m(o,`${JSON.stringify(p,null,2)}
3
- `,"utf8")}async function C(t,r){const e=await f(r);if(Object.keys(e).length===0)return!1;const i={previousSelectedType:typeof e.previousSelectedType=="string"?e.previousSelectedType:null,previousModelName:typeof e.previousModelName=="string"?e.previousModelName:null,writtenModelName:typeof e.writtenModelName=="string"?e.writtenModelName:null},o=await f(t),n=g(o.security),a=g(n.auth),l=g(o.model);let s=!1;return a.selectedType==="openai"&&(i.previousSelectedType?a.selectedType=i.previousSelectedType:delete a.selectedType,n.auth=a,o.security=n,s=!0),i.writtenModelName&&l.name===i.writtenModelName&&(i.previousModelName?l.name=i.previousModelName:delete l.name,o.model=l,s=!0),s&&await m(t,`${JSON.stringify(o,null,2)}
4
- `,"utf8"),await S(r,{force:!0}),!0}const b=".grix-provider-state.json",_="grix";async function G(t,r){const e=u(t,".trae"),i=u(e,"traecli.yaml"),o=u(e,b),n=r.GRIX_TRAECLI_BASE_URL?.trim(),a=r.GRIX_TRAECLI_MODEL?.trim();if(!n||!a){await j(i,o);return}let l="";try{l=await O(i,"utf8")}catch(d){if(d.code!=="ENOENT")throw d}const s=l.trim()?A(l):new v({});if(s.errors.length>0)throw new Error(`traecli.yaml \u89E3\u6790\u5931\u8D25: ${s.errors[0].message}`);if(s.contents!=null&&!E(s.contents))throw new Error("traecli.yaml: \u9876\u5C42\u4E0D\u662F\u6620\u5C04\uFF0C\u65E0\u6CD5\u5199\u5165 models/model");let c=s.get("models",!0);if(c==null&&(c=new H,s.set("models",c)),!T(c))throw new Error("traecli.yaml: models \u4E0D\u662F\u5217\u8868");const p=new R;p.set("name",_);const N=new R;N.set("model",a),N.set("base_url",n),N.set("api_key","${GRIX_PROVIDER_API_KEY}"),p.set("open_ai",N);const I=c.items.findIndex(d=>E(d)&&d.get("name")===_);I>=0?c.set(I,p):c.add(p);let y=s.get("model",!0);if(E(y)){const d=await f(o);if(Object.keys(d).length===0){const M=y.get("name"),D={hadModelKey:!0,previousModelName:typeof M=="string"?M:null};await w(e,{recursive:!0}),await m(o,`${JSON.stringify(D,null,2)}
5
- `,"utf8")}}else{const d=await f(o);if(Object.keys(d).length===0){const M={hadModelKey:y!==void 0,previousModelName:null};await w(e,{recursive:!0}),await m(o,`${JSON.stringify(M,null,2)}
6
- `,"utf8")}y=new R,s.set("model",y)}y.set("name",_),await w(e,{recursive:!0}),await m(i,s.toString(),"utf8")}async function j(t,r){const e=await f(r);if(Object.keys(e).length===0)return!1;const i={hadModelKey:e.hadModelKey===!0,previousModelName:typeof e.previousModelName=="string"?e.previousModelName:null};let o="";try{o=await O(t,"utf8")}catch(a){if(a.code!=="ENOENT")throw await S(r,{force:!0}),a;return await S(r,{force:!0}),!0}const n=o.trim()?A(o):new v({});if(n.errors.length===0&&E(n.contents)){const a=n.get("models",!0);if(T(a)){const s=a.items.findIndex(c=>E(c)&&c.get("name")===_);s>=0&&a.items.splice(s,1)}const l=n.get("model",!0);E(l)&&l.get("name")===_&&(i.hadModelKey?i.previousModelName?l.set("name",i.previousModelName):l.delete("name"):n.delete("model")),await m(t,n.toString(),"utf8")}return await S(r,{force:!0}),!0}async function F(t,r){if(!r)return!1;const e=x(t);if(e==="qwen"){const i=u(r,".qwen");return C(u(i,"settings.json"),u(i,L))}if(e==="traecli"){const i=u(r,".trae");return j(u(i,"traecli.yaml"),u(i,b))}return!1}function P(t){return(t??"default").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"default"}function X(t,r){const e=t.HERMES_HOME?.trim()||t.GRIX_HERMES_HOME?.trim();if(e)return e;if(t.GRIX_HERMES_BASE_URL?.trim()&&t.HERMES_INFERENCE_MODEL?.trim()&&t.GRIX_PROVIDER_API_KEY?.trim()){const o=t.GRIX_CONNECTOR_HOME?.trim()||u(h(),".grix");return u(o,"runtime","native-provider",P(r),"hermes")}return u(h(),".hermes")}async function $(t,r){const e=t.GRIX_HERMES_BASE_URL?.trim(),i=t.HERMES_INFERENCE_MODEL?.trim(),o=t.GRIX_PROVIDER_API_KEY?.trim();if(!e||!i||!o)return;const n=X(t,r),a=["model:"," provider: grix",` default: ${JSON.stringify(i)}`,"providers:"," grix:",` api: ${JSON.stringify(e)}`,` default_model: ${JSON.stringify(i)}`," key_env: GRIX_PROVIDER_API_KEY"," name: Grix"," transport: openai_chat",""].join(`
7
- `);await w(n,{recursive:!0}),await m(u(n,"config.yaml"),a,{encoding:"utf8",mode:384}),t.HERMES_HOME=n}async function U(t,r,e,i){if(!(!r||!e))switch(x(t)){case"qwen":await k(r,e);return;case"hermes":await $(e,i);return;case"traecli":await G(r,e);return;default:return}}export{x as agentIdOf,U as applyNativeProviderConfig,X as resolveHermesHomeDir,F as restoreNativeProviderConfig};
1
+ import{mkdir as w,readFile as O,rm as h,writeFile as f}from"node:fs/promises";import{homedir as T}from"node:os";import{join as c}from"node:path";import{isMap as E,isSeq as A,parseDocument as L,Document as v,YAMLMap as R,YAMLSeq as $}from"yaml";function C(t){const r=(t??"").trim();return(r.split(/[\\/]/).pop()||r).replace(/\.(exe|cmd|bat|ps1)$/i,"").toLowerCase()}async function m(t){try{const r=await O(t,"utf8"),e=JSON.parse(r);return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function g(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}const x=".grix-provider-state.json";async function D(t,r){const e=c(t,".qwen"),i=c(e,"settings.json"),o=c(e,x);if(!r.OPENAI_BASE_URL){await P(i,o);return}const n=await m(i),s=g(n.security),l=g(s.auth),a=g(n.model),u=await m(o),p={previousSelectedType:Object.keys(u).length>0?typeof u.previousSelectedType=="string"?u.previousSelectedType:null:typeof l.selectedType=="string"?l.selectedType:null,previousModelName:Object.keys(u).length>0?typeof u.previousModelName=="string"?u.previousModelName:null:typeof a.name=="string"?a.name:null,writtenModelName:r.OPENAI_MODEL??null};l.selectedType="openai",s.auth=l,n.security=s,r.OPENAI_MODEL&&(a.name=r.OPENAI_MODEL,n.model=a),await w(e,{recursive:!0}),await f(i,`${JSON.stringify(n,null,2)}
2
+ `,"utf8"),await f(o,`${JSON.stringify(p,null,2)}
3
+ `,"utf8")}async function P(t,r){const e=await m(r);if(Object.keys(e).length===0)return!1;const i={previousSelectedType:typeof e.previousSelectedType=="string"?e.previousSelectedType:null,previousModelName:typeof e.previousModelName=="string"?e.previousModelName:null,writtenModelName:typeof e.writtenModelName=="string"?e.writtenModelName:null},o=await m(t),n=g(o.security),s=g(n.auth),l=g(o.model);let a=!1;return s.selectedType==="openai"&&(i.previousSelectedType?s.selectedType=i.previousSelectedType:delete s.selectedType,n.auth=s,o.security=n,a=!0),i.writtenModelName&&l.name===i.writtenModelName&&(i.previousModelName?l.name=i.previousModelName:delete l.name,o.model=l,a=!0),a&&await f(t,`${JSON.stringify(o,null,2)}
4
+ `,"utf8"),await h(r,{force:!0}),!0}const b=".grix-provider-state.json",_="grix",N="trae_cli.yaml",H="traecli.yaml";async function k(t,r){const e=c(t,".trae"),i=c(e,N),o=c(e,b),n=r.GRIX_TRAECLI_BASE_URL?.trim(),s=r.GRIX_TRAECLI_MODEL?.trim();if(!n||!s){await j(e);return}let l="";try{l=await O(i,"utf8")}catch(d){if(d.code!=="ENOENT")throw d}const a=l.trim()?L(l):new v({});if(a.errors.length>0)throw new Error(`${N} \u89E3\u6790\u5931\u8D25: ${a.errors[0].message}`);if(a.contents!=null&&!E(a.contents))throw new Error(`${N}: \u9876\u5C42\u4E0D\u662F\u6620\u5C04\uFF0C\u65E0\u6CD5\u5199\u5165 models/model`);let u=a.get("models",!0);if(u==null&&(u=new $,a.set("models",u)),!A(u))throw new Error(`${N}: models \u4E0D\u662F\u5217\u8868`);const p=new R;p.set("name",_);const M=new R;M.set("model",s),M.set("base_url",n),M.set("api_key","${GRIX_PROVIDER_API_KEY}"),p.set("open_ai",M);const S=u.items.findIndex(d=>E(d)&&d.get("name")===_);S>=0?u.set(S,p):u.add(p);let y=a.get("model",!0);if(E(y)){const d=await m(o);if(Object.keys(d).length===0){const I=y.get("name"),G={hadModelKey:!0,previousModelName:typeof I=="string"?I:null};await w(e,{recursive:!0}),await f(o,`${JSON.stringify(G,null,2)}
5
+ `,"utf8")}}else{const d=await m(o);if(Object.keys(d).length===0){const I={hadModelKey:y!==void 0,previousModelName:null};await w(e,{recursive:!0}),await f(o,`${JSON.stringify(I,null,2)}
6
+ `,"utf8")}y=new R,a.set("model",y)}y.set("name",_),await w(e,{recursive:!0}),await f(i,a.toString(),"utf8")}async function j(t){const r=c(t,b),e=await m(r);if(Object.keys(e).length===0)return!1;const i={hadModelKey:e.hadModelKey===!0,previousModelName:typeof e.previousModelName=="string"?e.previousModelName:null};for(const o of[N,H])await X(c(t,o),i);return await h(r,{force:!0}),!0}async function X(t,r){let e="";try{e=await O(t,"utf8")}catch(s){if(s.code!=="ENOENT")throw s;return}const i=e.trim()?L(e):new v({});if(i.errors.length>0||!E(i.contents))return;const o=i.get("models",!0);if(A(o)){const s=o.items.findIndex(l=>E(l)&&l.get("name")===_);s>=0&&o.items.splice(s,1)}const n=i.get("model",!0);E(n)&&n.get("name")===_&&(r.hadModelKey?r.previousModelName?n.set("name",r.previousModelName):n.delete("name"):i.delete("model")),await f(t,i.toString(),"utf8")}async function B(t,r){if(!r)return!1;const e=C(t);if(e==="qwen"){const i=c(r,".qwen");return P(c(i,"settings.json"),c(i,x))}return e==="traecli"?j(c(r,".trae")):!1}function F(t){return(t??"default").trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")||"default"}function J(t,r){const e=t.HERMES_HOME?.trim()||t.GRIX_HERMES_HOME?.trim();if(e)return e;if(t.GRIX_HERMES_BASE_URL?.trim()&&t.HERMES_INFERENCE_MODEL?.trim()&&t.GRIX_PROVIDER_API_KEY?.trim()){const o=t.GRIX_CONNECTOR_HOME?.trim()||c(T(),".grix");return c(o,"runtime","native-provider",F(r),"hermes")}return c(T(),".hermes")}async function K(t,r){const e=t.GRIX_HERMES_BASE_URL?.trim(),i=t.HERMES_INFERENCE_MODEL?.trim(),o=t.GRIX_PROVIDER_API_KEY?.trim();if(!e||!i||!o)return;const n=J(t,r),s=["model:"," provider: grix",` default: ${JSON.stringify(i)}`,"providers:"," grix:",` api: ${JSON.stringify(e)}`,` default_model: ${JSON.stringify(i)}`," key_env: GRIX_PROVIDER_API_KEY"," name: Grix"," transport: openai_chat",""].join(`
7
+ `);await w(n,{recursive:!0}),await f(c(n,"config.yaml"),s,{encoding:"utf8",mode:384}),t.HERMES_HOME=n}async function V(t,r,e,i){if(!(!r||!e))switch(C(t)){case"qwen":await D(r,e);return;case"hermes":await K(e,i);return;case"traecli":await k(r,e);return;default:return}}export{C as agentIdOf,V as applyNativeProviderConfig,J as resolveHermesHomeDir,B as restoreNativeProviderConfig};
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "bridgeVersion": "4.11.1",
4
- "tarball": "grix-dsh-bridge-4.11.1.tgz",
5
- "size": 23388,
3
+ "bridgeVersion": "4.11.4",
4
+ "tarball": "grix-dsh-bridge-4.11.4.tgz",
5
+ "size": 23389,
6
6
  "unpackedSize": 94036,
7
- "shasum": "0e2e11ece21e311f4d493950cfd3b6cc43c647f3",
8
- "integrity": "sha512-Svyyf6qXLBx+PLvH6TEwM+q+Lr0EOUSWKE3atZZPVzKDZ2ufzvOW6AzX8wSd9jTU+MIxu+nijdkm3CsQOOEK5A=="
7
+ "shasum": "1b7cecbb60929d08070a908d8b82432fe6e88f9e",
8
+ "integrity": "sha512-3XXO31289bhrzylR2+7gUI0orHZbJONc/gOvdkHucvgwnCsDQFfiuymjAvcJXG2VxWeUtGC6TE3b7qUbAcLoGQ=="
9
9
  }
@@ -1 +1 @@
1
- import{open as y}from"node:fs/promises";import{readAndHashFilePrefixRange as $}from"../../core/transcript-fingerprint.js";function w(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function m(t,r){return typeof t=="number"&&Number.isSafeInteger(t)&&t>=0?t:r}function _(t,r,e){t.anomalies.push({code:"pi_transcript_source_changed",message:`${r}: ${e}`}),t.gaps.push({category:"main_transcript",reason:"correlation_failed",detail:`${r}: ${e}`})}async function S(t){const r=typeof t.transcriptPath=="string"?t.transcriptPath:void 0;if(!r)return{lines:[],anomalies:[{code:"pi_transcript_path_missing",message:"boundary.transcriptPath is required"}],gaps:[{category:"main_transcript",reason:"source_log_missing",detail:"boundary.transcriptPath is missing"}],sourcePaths:[]};const e={lines:[],anomalies:[],gaps:[],sourcePaths:[r]};try{const a=await y(r,"r");let s,p;try{const n=await a.stat(),f=m(t.transcriptStartOffset,0),o=typeof t.transcriptEndOffset=="number"?m(t.transcriptEndOffset,n.size):n.size;if(f>n.size||o>n.size)return e.anomalies.push({code:"pi_transcript_boundary_out_of_range",message:`${r}: boundary ${f}-${o} exceeds size ${n.size}`}),e.gaps.push({category:"main_transcript",reason:"correlation_failed",detail:`${r}:${f}-${o}`}),e;const c=typeof t.transcriptFileIdentity=="string"?t.transcriptFileIdentity:void 0,i=`${n.dev}:${n.ino}`;if(c&&i!==c)return _(e,r,`identity ${i} does not match ${c}`),e;const u=typeof t.transcriptPrefixFingerprint=="string"?t.transcriptPrefixFingerprint:void 0;p=f;const h=Math.max(o,p),d=h-p;if(u){const l=await $(a,p,h);if(l.fingerprint!==u)return _(e,r,"closed transcript prefix fingerprint changed"),e;s=l.buffer}else{if(d===0)return e;s=Buffer.allocUnsafe(d);const{bytesRead:l}=await a.read(s,0,d,p);s=s.subarray(0,l)}if(d===0)return e}finally{await a.close()}let g=0;for(;g<s.length;){const n=s.indexOf(10,g),f=n===-1?s.length:n+1,o=s.subarray(g,n===-1?s.length:n),c=p+g;if(g=f,o.length!==0)try{const i=JSON.parse(o.toString("utf8"));if(!w(i))throw new Error("JSONL row is not an object");e.lines.push({record:i,sourcePath:r,sourceOffset:c,sourceLength:o.length})}catch(i){e.anomalies.push({code:"pi_transcript_row_malformed",message:`${r}:${c}: ${i instanceof Error?i.message:String(i)}`}),e.gaps.push({category:"transcript_row",reason:"correlation_failed",detail:`${r}:${c}`})}}}catch(a){e.anomalies.push({code:"pi_transcript_source_unreadable",message:`${r}: ${a instanceof Error?a.message:String(a)}`}),e.gaps.push({category:"main_transcript",reason:"source_log_missing",detail:r})}return e}export{S as collectPiTranscript};
1
+ import{open as $}from"node:fs/promises";import{readAndHashFilePrefixRange as w}from"../../core/transcript-fingerprint.js";function m(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _(e,r){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0?e:r}function y(e,r,t){e.anomalies.push({code:"pi_transcript_source_changed",message:`${r}: ${t}`}),e.gaps.push({category:"main_transcript",reason:"correlation_failed",detail:`${r}: ${t}`})}async function O(e){const r=typeof e.transcriptPath=="string"?e.transcriptPath:void 0;if(!r){const i=Array.isArray(e.eventRecords)?e.eventRecords.filter(m):[];if(i.length>0){const s="omp-live-events";return{lines:i.map((o,p)=>({record:o,sourcePath:s,sourceOffset:p,sourceLength:0})),anomalies:[],gaps:[],sourcePaths:[s]}}return{lines:[],anomalies:[{code:"pi_transcript_path_missing",message:"boundary.transcriptPath is required (for omp: boundary.eventRecords was empty \u2014 no agent_end messages captured)"}],gaps:[{category:"main_transcript",reason:"source_log_missing",detail:"boundary.transcriptPath is missing"}],sourcePaths:[]}}const t={lines:[],anomalies:[],gaps:[],sourcePaths:[r]};try{const i=await $(r,"r");let s,o;try{const n=await i.stat(),g=_(e.transcriptStartOffset,0),c=typeof e.transcriptEndOffset=="number"?_(e.transcriptEndOffset,n.size):n.size;if(g>n.size||c>n.size)return t.anomalies.push({code:"pi_transcript_boundary_out_of_range",message:`${r}: boundary ${g}-${c} exceeds size ${n.size}`}),t.gaps.push({category:"main_transcript",reason:"correlation_failed",detail:`${r}:${g}-${c}`}),t;const f=typeof e.transcriptFileIdentity=="string"?e.transcriptFileIdentity:void 0,a=`${n.dev}:${n.ino}`;if(f&&a!==f)return y(t,r,`identity ${a} does not match ${f}`),t;const u=typeof e.transcriptPrefixFingerprint=="string"?e.transcriptPrefixFingerprint:void 0;o=g;const h=Math.max(c,o),d=h-o;if(u){const l=await w(i,o,h);if(l.fingerprint!==u)return y(t,r,"closed transcript prefix fingerprint changed"),t;s=l.buffer}else{if(d===0)return t;s=Buffer.allocUnsafe(d);const{bytesRead:l}=await i.read(s,0,d,o);s=s.subarray(0,l)}if(d===0)return t}finally{await i.close()}let p=0;for(;p<s.length;){const n=s.indexOf(10,p),g=n===-1?s.length:n+1,c=s.subarray(p,n===-1?s.length:n),f=o+p;if(p=g,c.length!==0)try{const a=JSON.parse(c.toString("utf8"));if(!m(a))throw new Error("JSONL row is not an object");t.lines.push({record:a,sourcePath:r,sourceOffset:f,sourceLength:c.length})}catch(a){t.anomalies.push({code:"pi_transcript_row_malformed",message:`${r}:${f}: ${a instanceof Error?a.message:String(a)}`}),t.gaps.push({category:"transcript_row",reason:"correlation_failed",detail:`${r}:${f}`})}}}catch(i){t.anomalies.push({code:"pi_transcript_source_unreadable",message:`${r}: ${i instanceof Error?i.message:String(i)}`}),t.gaps.push({category:"main_transcript",reason:"source_log_missing",detail:r})}return t}export{O as collectPiTranscript};
@@ -1 +1 @@
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
+ function a(t){const o=new Set([`http://127.0.0.1:${t.serverPort}`,`http://localhost:${t.serverPort}`,...t.allowedOrigins]),e=new Set([`127.0.0.1:${t.serverPort}`,`localhost:${t.serverPort}`,...t.allowedHosts]);return{validateRequest(s){const r=i(s,o);if(!r.ok)return r;const n=l(s,e);return n.ok?{ok:!0}:n}}}function i(t,o){const e=t.headers.origin;return e?o.has(e)?{ok:!0}:{ok:!1,statusCode:403,message:`Origin not allowed: ${e}`}:{ok:!0}}function l(t,o){const e=t.headers.host;return e?o.has(e)?{ok:!0}:{ok:!1,statusCode:403,message:`Host not allowed: ${e}`}:{ok:!1,statusCode:403,message:"Missing Host header"}}export{a as createSecurityPolicy};
@@ -3617,11 +3617,26 @@ function recordIntegrityFailure(evidence, transcriptPath, detail) {
3617
3617
  async function collectPiTranscript(boundary) {
3618
3618
  const transcriptPath = typeof boundary.transcriptPath === "string" ? boundary.transcriptPath : void 0;
3619
3619
  if (!transcriptPath) {
3620
+ const eventRecords = Array.isArray(boundary.eventRecords) ? boundary.eventRecords.filter(isRecord4) : [];
3621
+ if (eventRecords.length > 0) {
3622
+ const sourcePath = "omp-live-events";
3623
+ return {
3624
+ lines: eventRecords.map((record4, index) => ({
3625
+ record: record4,
3626
+ sourcePath,
3627
+ sourceOffset: index,
3628
+ sourceLength: 0
3629
+ })),
3630
+ anomalies: [],
3631
+ gaps: [],
3632
+ sourcePaths: [sourcePath]
3633
+ };
3634
+ }
3620
3635
  return {
3621
3636
  lines: [],
3622
3637
  anomalies: [{
3623
3638
  code: "pi_transcript_path_missing",
3624
- message: "boundary.transcriptPath is required"
3639
+ message: "boundary.transcriptPath is required (for omp: boundary.eventRecords was empty \u2014 no agent_end messages captured)"
3625
3640
  }],
3626
3641
  gaps: [{
3627
3642
  category: "main_transcript",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "grix-connector",
3
- "version": "4.11.1",
3
+ "version": "4.11.4",
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",