grix-connector 3.20.0 → 3.20.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{execFile as P}from"node:child_process";import{promisify as w}from"node:util";import{EventEmitter as S}from"node:events";import{stat as b}from"node:fs/promises";import{mkdirSync as T,writeFileSync as $,unlinkSync as A,statSync as m,readFileSync as k,existsSync as R}from"node:fs";import{join as u,resolve as C}from"node:path";import{fileURLToPath as M}from"node:url";import{tmpdir as F,homedir as f}from"node:os";import{resolveCommandPath as B,spawnCommand as D,killProcessGroup as I,hasChildProcesses as N}from"../../core/runtime/spawn.js";import{InternalApiServer as G}from"../../core/mcp/internal-api-server.js";import{IdentityInjector as L}from"../shared/identity-injector.js";import{compactToolInputForWire as O}from"../shared/tool-wire-payload.js";import{syncDefaultSkillsToDir as j}from"../../default-skills/index.js";import{PiTransport as q}from"./pi-transport.js";import{log as a}from"../../core/log/index.js";import{scanSkills as U}from"../claude/skill-scanner.js";import{SessionBindingStore as z}from"../../core/persistence/session-binding-store.js";import{splitTextForAibotProtocol as H}from"../../core/protocol/index.js";import{buildSimpleProbeReport as W}from"../shared/probe-util.js";import{piGrixProviderId as Y,removePiGrixProvider as J,writePiGrixProvider as V}from"./pi-provider-config.js";const E=new Map;function X(){const d=u(f(),".pi","agent","mcp.json");try{if(!R(d))return{};const e=JSON.parse(k(d,"utf8"))?.mcpServers;return!e||typeof e!="object"||Array.isArray(e)?{}:e}catch(t){return a.warn("pi-adapter",`Failed to read Pi user MCP config ${d}: ${t instanceof Error?t.message:String(t)}`),{}}}async function K(d){const t=E.get(d);if(t!==void 0)return t;let e=!1;try{const s=w(P),i=process.platform==="win32",n=i&&/\s/.test(d)&&!d.startsWith('"')?`"${d}"`:d,{stdout:r,stderr:c}=await s(n,["--help"],{timeout:5e3,encoding:"utf-8",...i?{shell:!0}:{}});e=/--mcp-config\b/.test(`${r??""}${c??""}`)}catch{e=!1}return E.set(d,e),a.info("pi-adapter",`Pi --mcp-config \u652F\u6301\u63A2\u6D4B: ${e?"\u652F\u6301":"\u4E0D\u652F\u6301"} (${d})`),e}class Q extends S{adapterSessionId;constructor(t){super(),this.adapterSessionId=t}emitDone(t){this.emit("done",t)}emitError(t){if(this.listenerCount("error")===0){a.warn("pi-adapter",`Prompt handle error (no listeners): ${t.message}`);return}this.emit("error",t)}async cancel(){}}const Z=12e4,tt=90*1e3,x=1800*1e3;function y(d){try{return process.kill(d,0),!0}catch(t){return t.code==="EPERM"}}const et=500,st=2e3,g=3,it=500;function nt(d){return new Promise(t=>setTimeout(t,d))}function p(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 S{type="pi";config;callbacks;process=null;transport=new q;alive=!1;stopped=!1;internalApi=null;mcpConfigPath=null;identity;piSessionPath=null;activeEventId=null;activeSessionId=null;activeAuditCapture=null;completedAuditBoundaries=new Map;isStreaming=!1;streamSeq=0;clientMsgSeq=0;activeClientMsgId=null;thinkingSeq=0;textBuffer="";emittedTextByIndex=new Map;textFlushTimer=null;activeRunError=null;runErrorEmitted=!1;idleTimer=null;lastRpcAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;composingSessionId=null;composingInterval=null;doneGuardTimer=null;bindingStore=null;aibotSessionId="";sessionReadyPromise=null;provider;agentName="";constructor(t,e){super(),this.config=t,this.callbacks=e,this.identity=new L("pi-adapter",e.getAgentProfile);const s=t.options??{};this.aibotSessionId=String(s.aibotSessionId??"").trim(),this.agentName=String(s.agentName??"").trim(),this.provider=s.provider,this.bindingStore=s.bindingStore instanceof z?s.bindingStore:null,this.bindingStore&&this.aibotSessionId&&(this.piSessionPath=this.bindingStore.getPiSessionPath(this.aibotSessionId)??null)}async start(){await this.startInternalApi(),await this.spawnPi(),await this.ensureSessionReady(),a.info("pi-adapter",`Ready (pid=${this.process?.pid})`),await this.syncModelBinding()}async syncModelBinding(){if(this.aibotSessionId)for(let t=1;t<=g;t++)try{const[e,s]=await Promise.all([this.transport.send("get_available_models"),this.transport.send("get_state")]),i=e.data?.models;if(!i||i.length===0){if(t<g){await nt(it);continue}a.warn("pi-adapter",`syncModelBinding: empty model list after ${g} attempts, giving up`);return}const n=s.data?.model,r={available_models:i.map(c=>({id:c.id,display_name:c.name??c.id,...c.provider?{provider:c.provider}:{}}))};n?.id&&(r.model_id=n.id),n?.provider&&(r.model_provider=n.provider),this.callbacks.sendUpdateBindingCard(this.aibotSessionId,this.isStreaming?"composing":"ready",this.resolveCwd(),r),a.info("pi-adapter",`synced model binding: ${i.length} models, current=${n?.id??"unknown"} (attempt ${t})`);return}catch(e){a.warn("pi-adapter",`syncModelBinding failed (non-fatal): ${e instanceof Error?e.message:String(e)}`);return}}async stop(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.cancelDoneGuard(),this.transport.close(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.mcpConfigPath){try{A(this.mcpConfigPath)}catch{}this.mcpConfigPath=null}if(this.process){const t=this.process;try{I(t,"SIGTERM")}catch{}const e=setTimeout(()=>{try{I(t,"SIGKILL")}catch{}},5e3);t.on("exit",()=>clearTimeout(e)),this.process=null}}isAlive(){return this.alive}async createSession(t){this.sessionReadyPromise=null,await this.createNewSession();const e=this.piSessionPath||`pi-${Date.now()}`;return a.info("pi-adapter",`Session created: ${e} (path=${this.piSessionPath})`),e}async resumeSession(t,e){await this.switchSession()}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(t){this.identity.forgetSession(t),this.piSessionPath=null,this.sessionReadyPromise=null,this.persistPiSessionPath(void 0)}sendPrompt(t){const e=new Q(t.adapterSessionId),s=this.buildPromptTextFromRequest(t);return this.ensureSessionReady().then(()=>this.transport.send("prompt",{message:s})).then(i=>{i.success||e.emitDone({status:"failed",error:i.error})}).catch(i=>{e.emitError(i instanceof Error?i:new Error(String(i)))}),e}async cancel(t){try{await this.transport.send("abort")}catch{}}deliverInboundEvent(t){const{event_id:e,session_id:s,content:i}=t,n=this.buildPromptText(t);if(this.isStreaming){if(this.activeEventId&&this.activeEventId!==e){const r=this.activeEventId;a.info("pi-adapter",`steer: cancel ${r} -> ${e}`),this.flushTextBuffer(),this.callbacks.sendEventResult(r,"canceled","steered to new event"),this.activeAuditCapture?.eventId===r&&(this.snapshotAuditBoundary(r),this.emit("eventDone",r))}this.activeEventId=e,this.activeSessionId=s,this.beginAuditCapture(t),this.resetRunStreamState(),this.startComposing(s,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n,streamingBehavior:"steer"}).catch(r=>{a.error("pi-adapter",`steer failed: ${r}`),this.callbacks.sendEventResult(e,"failed",String(r))})}else a.info("pi-adapter",`prompt: event=${e} session=${s}`),this.activeEventId=e,this.activeSessionId=s,this.beginAuditCapture(t),this.isStreaming=!0,this.resetRunStreamState(),this.startComposing(s,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n}).then(r=>{r.success||(a.error("pi-adapter",`prompt rejected: ${r.error}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",r.error),this.clearActive())}).catch(r=>{a.error("pi-adapter",`prompt error: ${r}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",String(r)),this.clearActive()})}deliverStopEvent(t,e){if(this.activeEventId===t){a.info("pi-adapter",`stop: event=${t}, releasing busy immediately`),this.transport.send("abort").catch(()=>{}),this.flushTextBuffer();const s=this.nextStreamSeq(),i=this.activeClientMsgId??void 0;this.callbacks.sendStreamChunk(t,this.activeSessionId??"","",s,!0,i),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(t,"canceled","stopped by user"),this.clearActive()}}async handleLocalAction(t){const e=t.action_id;switch(t.action_type){case"set_model":{const s=t.params??{},i=(s.modelId??s.model_id??"").trim();if(!i)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_model","model_id is required"),{handled:!0,kind:"set_model_error"};try{let n=s.provider?.trim();return n||(n=(await this.transport.send("get_available_models")).data?.models?.find(l=>l.id===i)?.provider?.trim()),n?(await this.transport.send("set_model",{provider:n,modelId:i}),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"model_set",provider:n,modelId:i}),this.syncModelBinding(),{handled:!0,kind:"set_model"}):(this.callbacks.sendLocalActionResult(e,"failed",void 0,"model_not_found",`No provider for model: ${i}`),{handled:!0,kind:"set_model_error"})}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_model_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_model_error"}}}case"get_context":try{const s=await this.transport.send("get_state");return this.callbacks.sendLocalActionResult(e,"ok",{state:s}),{handled:!0,kind:"get_context"}}catch(s){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"get_context_error",s instanceof Error?s.message:String(s)),{handled:!1,kind:""}}case"pi_extension_ui_response":return this.transport.sendNoWait({type:"extension_ui_response",...t.params??{}}),this.callbacks.sendLocalActionResult(e,"ok"),{handled:!0,kind:"extension_ui_response"};default:return{handled:!1,kind:""}}}setPermissionHandler(t){}async ping(t){try{return await this.transport.send("get_state"),!0}catch{return!1}}getStatus(){return{alive:this.alive,busy:this.isStreaming,sessions:this.piSessionPath?1:0}}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}takeAuditBoundary(t){const e=this.completedAuditBoundaries.get(t);return e&&this.completedAuditBoundaries.delete(t),e}clearActiveEventForShutdown(){this.stopIdleTimer(),this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.activeEventId=null}getMcpConfig(){if(!this.internalApi)return null;const t=C(M(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?N(t,[t]):!1}async probe(t){const e=this.getStatus();return{...await W(this.config.command||"pi",{alive:e.alive,busy:e.busy,started:!!this.process},t),session:this.probeSessionRecord()}}probeSessionRecord(){const t=this.piSessionPath;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const e=m(t);return{recordPath:t,lastActivityMs:e.mtimeMs,freshMs:Date.now()-e.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}getSupportedCommands(){return[{name:"model",description:"List or set model",args:"[provider:model_id]"},{name:"interrupt",description:"Interrupt current run"},{name:"status",description:"Show session status"},{name:"skills",description:"List available skills"}]}async execCommand(t,e,s){try{if(!this.alive)return{status:"failed",message:"Pi process not running"};switch(t){case"model":{const i=e.trim();if(i){const c=i.indexOf(":");if(c<1)return{status:"failed",message:"Format: provider:model_id"};const l=i.slice(0,c),h=i.slice(c+1);if(!h)return{status:"failed",message:"Format: provider:model_id"};const o=await this.transport.send("set_model",{provider:l,modelId:h});return o?.success?{status:"ok",message:`Model set to ${l}:${h}`}:{status:"failed",message:`Failed to set model: ${o?.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 w}from"node:child_process";import{promisify as b}from"node:util";import{EventEmitter as I}from"node:events";import{stat as T}from"node:fs/promises";import{mkdirSync as $,writeFileSync as A,unlinkSync as k,statSync as f,readFileSync as R,existsSync as C}from"node:fs";import{join as m,resolve as M}from"node:path";import{fileURLToPath as F}from"node:url";import{tmpdir as B,homedir as g}from"node:os";import{resolveCommandPath as D,spawnCommand as N,killProcessGroup as E,hasChildProcesses as G}from"../../core/runtime/spawn.js";import{InternalApiServer as L}from"../../core/mcp/internal-api-server.js";import{IdentityInjector as O}from"../shared/identity-injector.js";import{compactToolInputForWire as j}from"../shared/tool-wire-payload.js";import{syncDefaultSkillsToDir as q}from"../../default-skills/index.js";import{PiTransport as U}from"./pi-transport.js";import{log as a}from"../../core/log/index.js";import{scanSkills as z}from"../claude/skill-scanner.js";import{SessionBindingStore as H}from"../../core/persistence/session-binding-store.js";import{splitTextForAibotProtocol as W}from"../../core/protocol/index.js";import{buildSimpleProbeReport as Y}from"../shared/probe-util.js";import{piGrixProviderId as K,removePiGrixProvider as V,writePiGrixProvider as X}from"./pi-provider-config.js";const x=new Map;function J(){const d=m(g(),".pi","agent","mcp.json");try{if(!C(d))return{};const e=JSON.parse(R(d,"utf8"))?.mcpServers;return!e||typeof e!="object"||Array.isArray(e)?{}:e}catch(t){return a.warn("pi-adapter",`Failed to read Pi user MCP config ${d}: ${t instanceof Error?t.message:String(t)}`),{}}}async function Q(d){const t=x.get(d);if(t!==void 0)return t;let e=!1;try{const s=b(w),i=process.platform==="win32",n=i&&/\s/.test(d)&&!d.startsWith('"')?`"${d}"`:d,{stdout:r,stderr:c}=await s(n,["--help"],{timeout:5e3,encoding:"utf-8",...i?{shell:!0}:{}});e=/--mcp-config\b/.test(`${r??""}${c??""}`)}catch{e=!1}return x.set(d,e),a.info("pi-adapter",`Pi --mcp-config \u652F\u6301\u63A2\u6D4B: ${e?"\u652F\u6301":"\u4E0D\u652F\u6301"} (${d})`),e}class Z extends I{adapterSessionId;constructor(t){super(),this.adapterSessionId=t}emitDone(t){this.emit("done",t)}emitError(t){if(this.listenerCount("error")===0){a.warn("pi-adapter",`Prompt handle error (no listeners): ${t.message}`);return}this.emit("error",t)}async cancel(){}}const tt=12e4,et=90*1e3,y=1800*1e3;function _(d){try{return process.kill(d,0),!0}catch(t){return t.code==="EPERM"}}const st=500,it=2e3,v=3,nt=500;function rt(d){return new Promise(t=>setTimeout(t,d))}function u(d){if(d===void 0)return"undefined";if(d===null)return"null";if(typeof d=="string")return d.length>500?`${d.slice(0,500)}...`:d;try{const t=JSON.stringify(d);return t.length>500?`${t.slice(0,500)}...`:t}catch{return String(d)}}class P extends I{type="pi";config;callbacks;process=null;transport=new U;alive=!1;stopped=!1;internalApi=null;mcpConfigPath=null;identity;piSessionPath=null;activeEventId=null;activeSessionId=null;activeAuditCapture=null;completedAuditBoundaries=new Map;isStreaming=!1;streamSeq=0;clientMsgSeq=0;activeClientMsgId=null;thinkingSeq=0;textBuffer="";emittedTextByIndex=new Map;textFlushTimer=null;activeRunError=null;runErrorEmitted=!1;idleTimer=null;lastRpcAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;composingSessionId=null;composingInterval=null;doneGuardTimer=null;bindingStore=null;aibotSessionId="";sessionReadyPromise=null;provider;agentName="";constructor(t,e){super(),this.config=t,this.callbacks=e,this.identity=new O("pi-adapter",e.getAgentProfile);const s=t.options??{};this.aibotSessionId=String(s.aibotSessionId??"").trim(),this.agentName=String(s.agentName??"").trim(),this.provider=s.provider,this.bindingStore=s.bindingStore instanceof H?s.bindingStore:null,this.bindingStore&&this.aibotSessionId&&(this.piSessionPath=this.bindingStore.getPiSessionPath(this.aibotSessionId)??null)}async start(){await this.startInternalApi(),await this.spawnPi(),await this.ensureSessionReady(),a.info("pi-adapter",`Ready (pid=${this.process?.pid})`),await this.syncModelBinding()}async syncModelBinding(){if(this.aibotSessionId)for(let t=1;t<=v;t++)try{const[e,s]=await Promise.all([this.transport.send("get_available_models"),this.transport.send("get_state")]),i=e.data?.models;if(!i||i.length===0){if(t<v){await rt(nt);continue}a.warn("pi-adapter",`syncModelBinding: empty model list after ${v} attempts, giving up`);return}const n=s.data?.model,r={available_models:i.map(c=>({id:c.id,display_name:c.name??c.id,...c.provider?{provider:c.provider}:{}}))};n?.id&&(r.model_id=n.id),n?.provider&&(r.model_provider=n.provider),this.callbacks.sendUpdateBindingCard(this.aibotSessionId,this.isStreaming?"composing":"ready",this.resolveCwd(),r),a.info("pi-adapter",`synced model binding: ${i.length} models, current=${n?.id??"unknown"} (attempt ${t})`);return}catch(e){a.warn("pi-adapter",`syncModelBinding failed (non-fatal): ${e instanceof Error?e.message:String(e)}`);return}}async stop(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.cancelDoneGuard(),this.transport.close(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.mcpConfigPath){try{k(this.mcpConfigPath)}catch{}this.mcpConfigPath=null}if(this.process){const t=this.process;try{E(t,"SIGTERM")}catch{}const e=setTimeout(()=>{try{E(t,"SIGKILL")}catch{}},5e3);t.on("exit",()=>clearTimeout(e)),this.process=null}}isAlive(){return this.alive}async createSession(t){this.sessionReadyPromise=null,await this.createNewSession();const e=this.piSessionPath||`pi-${Date.now()}`;return a.info("pi-adapter",`Session created: ${e} (path=${this.piSessionPath})`),e}async resumeSession(t,e){await this.switchSession()}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(t){this.identity.forgetSession(t),this.piSessionPath=null,this.sessionReadyPromise=null,this.persistPiSessionPath(void 0)}sendPrompt(t){const e=new Z(t.adapterSessionId),s=this.buildPromptTextFromRequest(t);return this.ensureSessionReady().then(()=>this.transport.send("prompt",{message:s})).then(i=>{i.success||e.emitDone({status:"failed",error:i.error})}).catch(i=>{e.emitError(i instanceof Error?i:new Error(String(i)))}),e}async cancel(t){try{await this.transport.send("abort")}catch{}}deliverInboundEvent(t){const{event_id:e,session_id:s,content:i}=t,n=this.buildPromptText(t);if(this.isStreaming){if(this.activeEventId&&this.activeEventId!==e){const r=this.activeEventId;a.info("pi-adapter",`steer: cancel ${r} -> ${e}`),this.flushTextBuffer(),this.callbacks.sendEventResult(r,"canceled","steered to new event"),this.activeAuditCapture?.eventId===r&&(this.snapshotAuditBoundary(r),this.emit("eventDone",r))}this.activeEventId=e,this.activeSessionId=s,this.beginAuditCapture(t),this.resetRunStreamState(),this.startComposing(s,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n,streamingBehavior:"steer"}).catch(r=>{a.error("pi-adapter",`steer failed: ${r}`),this.callbacks.sendEventResult(e,"failed",String(r))})}else a.info("pi-adapter",`prompt: event=${e} session=${s}`),this.activeEventId=e,this.activeSessionId=s,this.beginAuditCapture(t),this.isStreaming=!0,this.resetRunStreamState(),this.startComposing(s,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.transport.send("prompt",{message:n}).then(r=>{r.success||(a.error("pi-adapter",`prompt rejected: ${r.error}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",r.error),this.clearActive())}).catch(r=>{a.error("pi-adapter",`prompt error: ${r}`),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(e,"failed",String(r)),this.clearActive()})}deliverStopEvent(t,e){if(this.activeEventId===t){a.info("pi-adapter",`stop: event=${t}, releasing busy immediately`),this.transport.send("abort").catch(()=>{}),this.flushTextBuffer();const s=this.nextStreamSeq(),i=this.activeClientMsgId??void 0;this.callbacks.sendStreamChunk(t,this.activeSessionId??"","",s,!0,i),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.callbacks.sendEventResult(t,"canceled","stopped by user"),this.clearActive()}}async handleLocalAction(t){const e=t.action_id;switch(t.action_type){case"set_model":{const s=t.params??{},i=(s.modelId??s.model_id??"").trim();if(!i)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_model","model_id is required"),{handled:!0,kind:"set_model_error"};try{let n=s.provider?.trim();return n||(n=(await this.transport.send("get_available_models")).data?.models?.find(l=>l.id===i)?.provider?.trim()),n?(await this.transport.send("set_model",{provider:n,modelId:i}),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"model_set",provider:n,modelId:i}),this.syncModelBinding(),{handled:!0,kind:"set_model"}):(this.callbacks.sendLocalActionResult(e,"failed",void 0,"model_not_found",`No provider for model: ${i}`),{handled:!0,kind:"set_model_error"})}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_model_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_model_error"}}}case"get_context":try{const s=await this.transport.send("get_state");return this.callbacks.sendLocalActionResult(e,"ok",{state:s}),{handled:!0,kind:"get_context"}}catch(s){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"get_context_error",s instanceof Error?s.message:String(s)),{handled:!1,kind:""}}case"pi_extension_ui_response":return this.transport.sendNoWait({type:"extension_ui_response",...t.params??{}}),this.callbacks.sendLocalActionResult(e,"ok"),{handled:!0,kind:"extension_ui_response"};default:return{handled:!1,kind:""}}}setPermissionHandler(t){}async ping(t){try{return await this.transport.send("get_state"),!0}catch{return!1}}getStatus(){return{alive:this.alive,busy:this.isStreaming,sessions:this.piSessionPath?1:0}}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}takeAuditBoundary(t){const e=this.completedAuditBoundaries.get(t);return e&&this.completedAuditBoundaries.delete(t),e}clearActiveEventForShutdown(){this.stopIdleTimer(),this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.activeEventId=null}getMcpConfig(){if(!this.internalApi)return null;const t=M(F(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[t,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const t=this.process?.pid;return t?G(t,[t]):!1}async probe(t){const e=this.getStatus();return{...await Y(this.config.command||"pi",{alive:e.alive,busy:e.busy,started:!!this.process},t),session:this.probeSessionRecord()}}probeSessionRecord(){const t=this.piSessionPath;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const e=f(t);return{recordPath:t,lastActivityMs:e.mtimeMs,freshMs:Date.now()-e.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}getSupportedCommands(){return[{name:"model",description:"List or set model",args:"[provider:model_id]"},{name:"interrupt",description:"Interrupt current run"},{name:"status",description:"Show session status"},{name:"skills",description:"List available skills"}]}async execCommand(t,e,s){try{if(!this.alive)return{status:"failed",message:"Pi process not running"};switch(t){case"model":{const i=e.trim();if(i){const c=i.indexOf(":");if(c<1)return{status:"failed",message:"Format: provider:model_id"};const l=i.slice(0,c),h=i.slice(c+1);if(!h)return{status:"failed",message:"Format: provider:model_id"};const p=await this.transport.send("set_model",{provider:l,modelId:h});return p?.success?{status:"ok",message:`Model set to ${l}:${h}`}:{status:"failed",message:`Failed to set model: ${p?.error??"unknown error"}`}}const r=(await this.transport.send("get_available_models"))?.data?.models;return r&&r.length>0?{status:"ok",message:`Available models:
|
|
2
2
|
${r.map(l=>` ${l.provider??"unknown"}:${l.id} (${l.name??l.id})`).join(`
|
|
3
|
-
`)}`,data:r}:{status:"ok",message:"No models available",data:[]}}case"interrupt":return this.isStreaming?(await this.transport.send("abort"),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","interrupted"),this.clearActive(),{status:"ok",message:"Run interrupted"}):{status:"failed",message:"No active run to interrupt"};case"status":{const i=this.getStatus();return{status:"ok",message:`Alive: ${i.alive}, Busy: ${i.busy}, Session: ${this.piSessionPath??"none"}`,data:{alive:i.alive,busy:i.busy,sessions:i.sessions,sessionPath:this.piSessionPath}}}case"skills":{const i=
|
|
4
|
-
`):"No skills found",data:i}}default:return{status:"unsupported",message:`Unknown command: ${t}`}}}catch(i){return{status:"failed",message:i instanceof Error?i.message:String(i)}}}resolveCwd(){if(this.bindingStore&&this.aibotSessionId){const e=this.bindingStore.get(this.aibotSessionId);if(e?.cwd)return e.cwd}const t=(this.config.options??{}).cwd;return typeof t=="string"&&t?t:process.cwd()}async startInternalApi(){try{this.internalApi=new
|
|
3
|
+
`)}`,data:r}:{status:"ok",message:"No models available",data:[]}}case"interrupt":return this.isStreaming?(await this.transport.send("abort"),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","interrupted"),this.clearActive(),{status:"ok",message:"Run interrupted"}):{status:"failed",message:"No active run to interrupt"};case"status":{const i=this.getStatus();return{status:"ok",message:`Alive: ${i.alive}, Busy: ${i.busy}, Session: ${this.piSessionPath??"none"}`,data:{alive:i.alive,busy:i.busy,sessions:i.sessions,sessionPath:this.piSessionPath}}}case"skills":{const i=z({mode:"pi"}),n=i.map(r=>`- ${r.name}${r.trigger?` (${r.trigger})`:""} [${r.source}]: ${r.description}`);return{status:"ok",message:n.length>0?n.join(`
|
|
4
|
+
`):"No skills found",data:i}}default:return{status:"unsupported",message:`Unknown command: ${t}`}}}catch(i){return{status:"failed",message:i instanceof Error?i.message:String(i)}}}resolveCwd(){if(this.bindingStore&&this.aibotSessionId){const e=this.bindingStore.get(this.aibotSessionId);if(e?.cwd)return e.cwd}const t=(this.config.options??{}).cwd;return typeof t=="string"&&t?t:process.cwd()}async startInternalApi(){try{this.internalApi=new L,this.internalApi.setInvokeHandler(async(r,c,l,h)=>this.callbacks.agentInvoke(r,c,h)),await this.internalApi.start(0),a.info("pi-adapter",`Internal API started at ${this.internalApi.url}`);const t=this.getMcpConfig(),e=J(),s=m(B(),"grix-pi-mcp");$(s,{recursive:!0}),this.mcpConfigPath=m(s,`mcp-${process.pid}-${Date.now()}.json`),A(this.mcpConfigPath,JSON.stringify({mcpServers:{...e,[t.name]:{command:t.command,args:t.args,directTools:!0,lifecycle:"eager"}}}),"utf8"),a.info("pi-adapter",`MCP config written to ${this.mcpConfigPath}`);const i=m(g(),".pi","agent","skills"),n=q(i);n.length>0&&a.info("pi-adapter",`Synced connector skills to ${i}: [${n.join(", ")}]`)}catch(t){a.warn("pi-adapter",`Failed to start MCP tools (non-fatal): ${t instanceof Error?t.message:String(t)}`)}}async spawnPi(){const t=this.config.command||"pi",e=D(t,typeof process.env.PATH=="string"?process.env.PATH:void 0),s=this.config.args??[],n=s.some(o=>o.startsWith("--mode"))?[...s]:["--mode","rpc",...s],r=String(this.config.env?.PI_CODING_AGENT_DIR??"").trim()||m(g(),".pi","agent"),c=K(this.agentName);this.provider?await X(r,c,this.provider)?(n.includes("--provider")||n.push("--provider",c),!n.includes("--model")&&this.provider.model?.trim()&&n.push("--model",this.provider.model.trim())):a.warn("pi-adapter","provider config incomplete (baseUrl/model required); Grix provider not applied"):await V(r,c).then(o=>{o&&a.info("pi-adapter",`Removed stale Grix provider "${c}" from models.json`)}).catch(o=>{a.warn("pi-adapter",`Failed to clean up Grix provider config: ${o instanceof Error?o.message:String(o)}`)}),this.mcpConfigPath&&!n.some(o=>o==="--mcp-config")&&(await Q(e)?n.push("--mcp-config",this.mcpConfigPath):a.warn("pi-adapter","\u5F53\u524D Pi \u4E0D\u652F\u6301 --mcp-config\uFF08\u672A\u68C0\u6D4B\u5230 pi-mcp-adapter \u6269\u5C55\uFF09\uFF0C\u8DF3\u8FC7 MCP \u6CE8\u5165\u4EE5\u907F\u514D\u542F\u52A8\u5931\u8D25"));const l={...process.env,...this.config.env},h=this.provider?.apiKey?.trim();h&&!l.GRIX_PROVIDER_API_KEY?.trim()&&(l.GRIX_PROVIDER_API_KEY=h);const p=this.resolveCwd();a.info("pi-adapter",`Spawning: ${e} ${n.join(" ")}`);try{if(!(await T(p)).isDirectory())throw new Error(`Bound path is not a directory: ${p}`)}catch(o){throw String(o?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${p}. Please rebind with /grix open <valid-directory>.`):o}try{this.process=N(e,n,{env:l,cwd:p}).process}catch(o){throw a.error("pi-adapter",`PI spawn threw: ${o}`),this.alive=!1,o}this.process.on("error",o=>{a.error("pi-adapter",`Spawn error: ${o.message}`),this.alive=!1,this.transport.close(),this.activeEventId&&(this.callbacks.sendEventResult(this.activeEventId,"failed",`Spawn error: ${o.message}`),this.clearActive()),this.stopped||this.emit("exit",1)}),this.process.on("exit",o=>{a.info("pi-adapter",`PI process exited (code=${o})`),this.alive=!1,this.transport.close(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"failed",`PI process exited (code=${o})`),this.isStreaming=!1,this.clearActive(),this.stopped||this.emit("exit",o??1)}),this.process.stderr?.on("data",o=>{const S=o.toString().trim();S&&a.info("pi-adapter",`[pi stderr] ${S}`)}),this.transport.on("event",o=>this.handlePiEvent(o)),this.transport.bind(this.process.stdin,this.process.stdout),this.alive=!0}handlePiEvent(t){if(this.stopped)return;if(this.lastRpcAt=Date.now(),t.type==="tool_execution_start"){const s=t;s.toolCallId&&this.toolCallsInFlight.add(s.toolCallId)}else if(t.type==="tool_execution_end"){const s=t;s.toolCallId&&this.toolCallsInFlight.delete(s.toolCallId)}switch(this.resetIdleTimer(),t.type){case"message_update":{const s=t.assistantMessageEvent;if(!s)break;const i=s.type;if(i==="text_delta"){const n=s.delta;if(n){const r=typeof s.contentIndex=="number"?s.contentIndex:0;this.rememberEmittedText(r,n),this.appendText(n)}}else if(i==="text_end"){const n=s.content,r=typeof s.contentIndex=="number"?s.contentIndex:0;n&&this.appendMissingText(r,n)}else if(i==="thinking_delta"){const n=s.delta;n&&this.activeEventId&&this.activeSessionId&&(this.thinkingSeq++,this.callbacks.sendThinking(this.activeEventId,this.activeSessionId,n))}else if(i==="done"||i==="error"){if(this.flushTextBuffer(),i==="error"){const n=this.piMessageError(s.error,s.reason);a.warn("pi-adapter",`terminal message_update error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${u(s.error)} reason=${u(s.reason)}`),this.recordRunError(n)}this.scheduleDoneGuard()}break}case"message_end":{const s=t.message;s?.role==="assistant"&&s.stopReason==="error"&&(a.warn("pi-adapter",`terminal message_end error event=${this.activeEventId} sessionId=${this.activeSessionId} errorMessage=${u(s.errorMessage)} message=${u(s)}`),this.recordRunError(this.piMessageError(s,s.errorMessage)),this.scheduleDoneGuard());break}case"tool_execution_start":{if(this.cancelDoneGuard(),this.flushTextBuffer(),!this.activeEventId||!this.activeSessionId)break;const s=t;if(s.toolName){const i=j(s.args);this.callbacks.sendToolUse(this.activeEventId,this.activeSessionId,s.toolName,i)}break}case"tool_execution_end":{if(!this.activeEventId||!this.activeSessionId)break;const s=t;s.isError&&this.callbacks.sendToolResult(this.activeEventId,this.activeSessionId,s.toolName,"(failed)");break}case"agent_end":{if(a.info("pi-adapter",`agent_end event=${this.activeEventId} sessionId=${this.activeSessionId}`),this.cancelDoneGuard(),t.willRetry===!0&&this.activeEventId){a.info("pi-adapter",`agent_end willRetry=true \u2014 holding event=${this.activeEventId} for auto-retry`),this.activeRunError=null,this.emittedTextByIndex.clear(),this.resetIdleTimer();break}this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.completeActiveEvent();break}case"agent_start":{this.cancelDoneGuard(),this.activeEventId&&(a.info("pi-adapter",`agent_start event=${this.activeEventId}`),this.isStreaming=!0);break}default:break}}appendText(t){if(this.textBuffer+=t,this.textBuffer.length>=it){this.flushTextBuffer();return}this.scheduleTextFlush()}scheduleTextFlush(){this.textFlushTimer||(this.textFlushTimer=setTimeout(()=>{this.textFlushTimer=null,this.flushTextBuffer()},st))}flushTextBuffer(){this.stopTextFlush(),!(!this.textBuffer||!this.activeEventId||!this.activeSessionId)&&(this.sendTextChunks(this.textBuffer),this.textBuffer="")}sendTextChunks(t){if(!(!this.activeEventId||!this.activeSessionId))for(const e of W(t))this.callbacks.sendStreamChunk(this.activeEventId,this.activeSessionId,e,this.nextStreamSeq(),!1,this.activeClientMsgId??void 0)}stopTextFlush(){this.textFlushTimer&&(clearTimeout(this.textFlushTimer),this.textFlushTimer=null)}buildPromptText(t){let e=t.content||"";if(t.context_messages_json)try{const s=JSON.parse(t.context_messages_json);Array.isArray(s)&&s.length>0&&(e=s.map(n=>`[context] ${n.sender_id??"unknown"}: ${n.content}`).join(`
|
|
5
5
|
`)+`
|
|
6
6
|
|
|
7
7
|
`+e)}catch{}return this.identity.injectOnce(t.session_id,e)}buildPromptTextFromRequest(t){let e=t.text;return t.contextMessages&&t.contextMessages.length>0&&(e=t.contextMessages.map(i=>`[context] ${i.senderId}: ${i.content}`).join(`
|
|
8
8
|
`)+`
|
|
9
9
|
|
|
10
|
-
`+e),this.identity.injectOnce(t.adapterSessionId,e)}clearActive(){const t=this.activeEventId;t&&this.snapshotAuditBoundary(t),this.activeEventId=null,this.activeSessionId=null,this.activeClientMsgId=null,this.activeRunError=null,this.textBuffer="",this.emittedTextByIndex.clear(),this.toolCallsInFlight.clear(),this.livenessExtendStartAt=void 0,this.stopIdleTimer(),t&&this.emit("eventDone",t)}beginAuditCapture(t){if(this.activeAuditCapture?.eventId===t.event_id||(this.activeAuditCapture=null,t.audit?.enabled!==!0))return;const e=this.piSessionPath??void 0;let s;if(e)try{s=
|
|
10
|
+
`+e),this.identity.injectOnce(t.adapterSessionId,e)}clearActive(){const t=this.activeEventId;t&&this.snapshotAuditBoundary(t),this.activeEventId=null,this.activeSessionId=null,this.activeClientMsgId=null,this.activeRunError=null,this.textBuffer="",this.emittedTextByIndex.clear(),this.toolCallsInFlight.clear(),this.livenessExtendStartAt=void 0,this.stopIdleTimer(),t&&this.emit("eventDone",t)}beginAuditCapture(t){if(this.activeAuditCapture?.eventId===t.event_id||(this.activeAuditCapture=null,t.audit?.enabled!==!0))return;const e=this.piSessionPath??void 0;let s;if(e)try{s=f(e).size}catch{s=0}this.activeAuditCapture={eventId:t.event_id,...e?{transcriptPath:e}:{},...s===void 0?{}:{transcriptStartOffset:s}}}snapshotAuditBoundary(t){const e=this.activeAuditCapture;if(!e||e.eventId!==t)return;this.activeAuditCapture=null;const s={adapterType:"pi"};if(e.transcriptPath){let i=e.transcriptStartOffset??0;try{i=f(e.transcriptPath).size}catch{}s.transcriptPath=e.transcriptPath,s.transcriptStartOffset=e.transcriptStartOffset??0,s.transcriptEndOffset=i,s.providerSessionId=this.piSessionPath??e.transcriptPath}this.completedAuditBoundaries.set(t,s)}resetRunStreamState(){this.streamSeq=0,this.thinkingSeq=0,this.textBuffer="",this.activeRunError=null,this.runErrorEmitted=!1,this.emittedTextByIndex.clear(),this.activeClientMsgId=`pi_${++this.clientMsgSeq}_${Date.now()}`}nextStreamSeq(){return this.streamSeq++,this.streamSeq}completeActiveEvent(){if(!this.activeEventId){this.clearActive();return}const t=this.activeEventId,e=this.activeSessionId??"",s=this.activeClientMsgId??void 0,i=this.activeRunError??void 0;i&&this.emitPendingRunError(),this.clearActive(),this.finalizeEvent(t,e,s,i)}finalizeEvent(t,e,s,i){const n=this.nextStreamSeq(),r=i?"failed":"responded";a.info("pi-adapter",`finalize event=${t} sessionId=${e} status=${r} clientMsgId=${s??""} terminalError=${i?u(i):""}`),this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t,e,s).then(()=>{this.callbacks.sendEventResult(t,r,i),a.info("pi-adapter",`event ${r} (reliable) event=${t}`)}).catch(c=>{a.error("pi-adapter",`finalStreamChunk ACK failed event=${t}: ${c}`),this.callbacks.sendEventResult(t,"failed",`final output delivery failed: ${c instanceof Error?c.message:String(c)}`),a.info("pi-adapter",`event failed (final delivery) event=${t}`)}):(this.callbacks.sendStreamChunk(t,e,"",n,!0,s),this.callbacks.sendEventResult(t,r,i),a.info("pi-adapter",`event ${r} event=${t}`))}recordRunError(t){if(this.activeRunError||!this.activeEventId||!this.activeSessionId)return;const e=t.trim()||"Pi request failed";this.activeRunError=e,a.warn("pi-adapter",`recorded terminal error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${u(e)}`),this.flushTextBuffer()}emitPendingRunError(){this.runErrorEmitted||!this.activeRunError||!this.activeEventId||!this.activeSessionId||(this.runErrorEmitted=!0,this.callbacks.sendRunError(this.activeEventId,this.activeSessionId,this.activeRunError,this.nextStreamSeq(),this.activeClientMsgId??void 0))}piMessageError(t,e){if(t&&typeof t=="object"){const s=t.errorMessage;if(typeof s=="string"&&s.trim())return s.trim()}return typeof t=="string"&&t.trim()?t.trim():typeof e=="string"&&e.trim()&&e.trim()!=="error"?e.trim():"Pi request failed"}rememberEmittedText(t,e){this.emittedTextByIndex.set(t,(this.emittedTextByIndex.get(t)??"")+e)}appendMissingText(t,e){const s=this.emittedTextByIndex.get(t)??"";if(e!==s){if(e.startsWith(s)){const i=e.slice(s.length);i&&(this.rememberEmittedText(t,i),this.appendText(i));return}if(!s){this.rememberEmittedText(t,e),this.appendText(e);return}a.info("pi-adapter",`text_end content mismatch at index=${t}, keeping streamed deltas`)}}startComposing(t,e){this.stopComposing(),this.composingSessionId=t,this.callbacks.sendSessionActivitySet(t,"composing",!0,{ref_event_id:e,ttl_ms:12e4}),this.composingInterval=setInterval(()=>{this.composingSessionId&&this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!0,{ttl_ms:12e4})},3e4)}stopComposing(){this.composingInterval&&(clearInterval(this.composingInterval),this.composingInterval=null),this.composingSessionId&&(this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!1),this.composingSessionId=null)}static DONE_GUARD_MS=5e3;scheduleDoneGuard(){this.cancelDoneGuard(),!(!this.activeEventId||!this.activeSessionId)&&(this.doneGuardTimer=setTimeout(()=>{this.doneGuardTimer=null,!(!this.activeEventId||!this.isStreaming)&&(a.info("pi-adapter",`done guard triggered \u2014 no agent_end received, ending event=${this.activeEventId}`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.completeActiveEvent())},P.DONE_GUARD_MS))}cancelDoneGuard(){this.doneGuardTimer&&(clearTimeout(this.doneGuardTimer),this.doneGuardTimer=null)}shouldExtendByLiveness(){if(!this.isStreaming||!this.activeEventId)return!1;const t=this.process?.pid;if(!this.alive||!t||!_(t))return!1;const e=Date.now(),s=this.lastRpcAt>0?e-this.lastRpcAt:Number.POSITIVE_INFINITY;if(s<et)return this.livenessExtendStartAt=e,a.info("pi-adapter",`Liveness check: fresh RPC for ${this.activeEventId} (rpcAge=${s}ms, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const n=this.livenessExtendStartAt??e;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=n),e-n>y?(a.warn("pi-adapter",`Liveness extension budget exhausted for ${this.activeEventId} (no progress for ${Math.round((e-n)/6e4)}min), allowing idle fail`),!1):(a.info("pi-adapter",`Liveness check: turn in progress for ${this.activeEventId} (toolsInFlight=${this.toolCallsInFlight.size}, rpcAge=${Number.isFinite(s)?`${s}ms`:"n/a"}), extending`),!0)}resetIdleTimer(){this.stopIdleTimer(),!(this.stopped||!this.isStreaming)&&(this.idleTimer=setTimeout(()=>{if(this.stopped||!this.isStreaming)return;if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const t=this.process?.pid,s=!!(this.alive&&t&&_(t))?`liveness budget exhausted after ${y/6e4}min`:"process not alive";a.error("pi-adapter",`Idle timeout (${s}, toolsInFlight=${this.toolCallsInFlight.size}) \u2014 emitting exit for respawn`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.activeEventId&&(this.emitPendingRunError(),this.callbacks.sendEventResult(this.activeEventId,"failed",`idle timeout: ${s}`)),this.clearActive(),this.emit("exit",-1)},tt))}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}async ensureSessionReady(){return this.sessionReadyPromise?this.sessionReadyPromise:(this.sessionReadyPromise=this.restoreOrCreateSession().finally(()=>{this.sessionReadyPromise=null}),this.sessionReadyPromise)}async restoreOrCreateSession(){try{await this.switchSession();return}catch(t){this.piSessionPath&&a.error("pi-adapter",`switch_session failed, creating new session: ${t}`)}await this.createNewSession()}async switchSession(){if(!this.piSessionPath)throw new Error("no PI session path");const t=await this.transport.send("switch_session",{sessionPath:this.piSessionPath});if(!t.success)throw this.piSessionPath=null,this.persistPiSessionPath(void 0),new Error(`switch_session failed: ${t.error}`)}async createNewSession(){const t=await this.transport.send("new_session");if(!t.success)throw new Error(`new_session failed: ${t.error}`);let e=null;if(e=t.data?.sessionFile??null,!e)try{const i=await this.transport.send("get_state");i.success&&(e=i.data?.sessionFile??null)}catch{}this.piSessionPath=e,this.persistPiSessionPath(this.piSessionPath??void 0)}persistPiSessionPath(t){!this.bindingStore||!this.aibotSessionId||this.bindingStore.setPiSessionPath(this.aibotSessionId,t)}}export{P as PiAdapter};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{buildClaudeDirectEnv as
|
|
1
|
+
import{buildClaudeDirectEnv as c}from"./claude-direct-env.js";const m={qwen:{baseUrl:"OPENAI_BASE_URL",apiKey:"OPENAI_API_KEY",model:"OPENAI_MODEL"},kimi:{baseUrl:"KIMI_MODEL_BASE_URL",apiKey:"KIMI_MODEL_API_KEY",model:"KIMI_MODEL_NAME",fixed:{KIMI_MODEL_PROVIDER_TYPE:"openai",KIMI_MODEL_CAPABILITIES:"tool_use",KIMI_MODEL_MAX_CONTEXT_SIZE:"262144"}},reasonix:{baseUrl:"DEEPSEEK_BASE_URL",apiKey:"DEEPSEEK_API_KEY"},codewhale:{apiKey:"OPENAI_API_KEY"},hermes:{baseUrl:"GRIX_HERMES_BASE_URL",apiKey:"GRIX_PROVIDER_API_KEY",model:"HERMES_INFERENCE_MODEL",fixed:{HERMES_INFERENCE_PROVIDER:"grix"}},pi:{apiKey:"GRIX_PROVIDER_API_KEY"}},f=["qwen","kimi","reasonix","codewhale","hermes","pi","opencode"],R=["kiro"];function E(t){return t?.trim().toLowerCase().split("/",1)[0]??""}function u(t){const e=E(t);return!!e&&f.includes(e)}function K(t){const e=E(t);return!!e&&R.includes(e)}function P(t){return u(t)||K(t)}function M(t){const e=E(t);return!!e&&e in m}function d(t,e){if(!e)return{};const s=E(t);if(s==="claude"){const a=e.baseUrl?.trim(),I=e.apiKey?.trim(),l=e.model?.trim();return!a||!I||!l?{}:c({baseUrl:a,primaryModel:l,...e.fastModel?.trim()?{fastModel:e.fastModel.trim()}:{},...e.effort?.trim()?{effort:e.effort.trim()}:{}},I)}const i=m[s];if(!i)return{};const r=e.baseUrl?.trim(),n=e.apiKey?.trim(),_=e.model?.trim();if(!r&&!n&&!_)return{};const o={...i.fixed??{}};return i.baseUrl&&r&&(o[i.baseUrl]=r),i.apiKey&&n&&(o[i.apiKey]=n),i.model&&_&&(o[i.model]=_),o}export{f as DIRECT_PROVIDER_CLIENT_TYPES,R as KIRO_CW_RELAY_CLIENT_TYPES,m as PROVIDER_ENV_SPECS,d as buildProviderEnv,u as supportsDirectProviderConfig,K as supportsKiroCwRelay,P as supportsNonMitmRelayConfig,M as supportsProviderEnv};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function a(
|
|
1
|
+
function a(t){const o=new Set([`http://127.0.0.1:${t.serverPort}`,`http://localhost:${t.serverPort}`,...t.allowedOrigins]),e=new Set([`127.0.0.1:${t.serverPort}`,`localhost:${t.serverPort}`,...t.allowedHosts]);return{validateRequest(s){const r=i(s,o);if(!r.ok)return r;const n=l(s,e);return n.ok?{ok:!0}:n}}}function i(t,o){const e=t.headers.origin;return e?o.has(e)?{ok:!0}:{ok:!1,statusCode:403,message:`Origin not allowed: ${e}`}:{ok:!0}}function l(t,o){const e=t.headers.host;return e?o.has(e)?{ok:!0}:{ok:!1,statusCode:403,message:`Host not allowed: ${e}`}:{ok:!1,statusCode:403,message:"Missing Host header"}}export{a as createSecurityPolicy};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "grix-connector",
|
|
3
|
-
"version": "3.20.
|
|
3
|
+
"version": "3.20.1",
|
|
4
4
|
"description": "Connect local AI coding agents (Claude, Codex, Gemini, Qwen, DeepSeek, Cursor, OpenCode, Pi, OpenHuman, Reasonix) to the Grix scheduling platform. Also serves as an OpenClaw plugin for Grix channel transport.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|