grix-connector 4.15.2 → 4.16.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.
- package/README.md +16 -0
- package/dist/adapter/acp/acp-adapter.js +9 -9
- package/dist/adapter/claude/claude-adapter.js +18 -18
- package/dist/adapter/cursor/cursor-adapter.js +1 -1
- package/dist/adapter/deepseek-harness/bridge-installer.js +6 -6
- package/dist/adapter/deepseek-harness/bridge-session-reliability.js +1 -1
- package/dist/adapter/deepseek-harness/jsonrpc-adapter.js +6 -2
- package/dist/adapter/deepseek-harness/jsonrpc-client.js +1 -1
- package/dist/adapter/deepseek-harness/process-runtime.js +1 -1
- package/dist/adapter/deepseek-harness/profile-package-shadow.js +1 -0
- package/dist/adapter/deepseek-harness/profile-resolver.js +1 -1
- package/dist/adapter/deepseek-harness/profile-runtime.js +1 -1
- package/dist/adapter/deepseek-harness/profile-supervisor.js +2 -2
- package/dist/adapter/deepseek-harness/toolbar-state.js +1 -1
- package/dist/adapter/opencode/opencode-adapter.js +4 -4
- package/dist/adapter/opencode/opencode-types.js +1 -1
- package/dist/assets/dsh-bridge/grix-dsh-bridge-4.16.1.tgz +0 -0
- package/dist/assets/dsh-bridge/manifest.json +6 -6
- package/dist/bridge/bridge.js +1 -1
- package/dist/bridge/provider-quota.js +1 -1
- package/dist/core/provider-quota/index.js +1 -1
- package/dist/core/provider-quota/opencode-go.js +1 -0
- package/dist/core/provider-quota/presentation.js +1 -1
- package/dist/core/provider-quota/providers.js +2 -2
- package/dist/manager.js +1 -1
- package/dist/mcp/stream-http/security.js +1 -1
- package/dist/protocol/acp-client.js +1 -1
- package/package.json +1 -1
- package/dist/assets/dsh-bridge/grix-dsh-bridge-4.15.2.tgz +0 -0
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import{createHmac as H,randomUUID as T}from"node:crypto";import{EventEmitter as O}from"node:events";import{readFileSync as q}from"node:fs";import{createConnection as $}from"node:net";import{isDshBridgedGrixTool as z}from"./grix-tool-bridge.js";import{DshBridgeJsonRpcPeer as G,GRIX_DSH_PROTOCOL_MAX as C,GRIX_DSH_PROTOCOL_MIN as M}from"./profile-bridge-protocol.js";import{resolveDshProfileIdentity as U,selectDshBridgeEndpoint as L}from"./profile-resolver.js";import{DEFAULT_DSH_PRESETS as F,normalizeDshPresets as K,normalizeDshProviders as V,resolveDshAgentPreset as X,resolveDshProviderId as J}from"./toolbar-state.js";import{effectiveDshReasoningEffort as W}from"./types.js";const Z=T(),N=5e3,k=1e4,Q=6e4;class Y extends O{peer;sessionId;ownerId;onCursorAck;notificationsActive=!1;pendingNotifications=[];constructor(t,e,c,s){super(),this.peer=t,this.sessionId=e,this.ownerId=c,this.onCursorAck=s,t.on("notification",(o,a)=>{if(!this.notificationsActive){this.pendingNotifications.push({method:o,params:a});return}this.deliverNotification(o,a)}),t.on("protocolError",o=>this.emit("protocolError",o))}prompt(t,e){return this.peer.call("session/prompt",{sessionId:t.sessionId,ownerId:this.ownerId,contentBlocks:t.contentBlocks},e)}async shutdown(t){try{await this.peer.call("session/close",{sessionId:this.sessionId,ownerId:this.ownerId},m(t,5e3))}finally{this.peer.close()}}close(t){this.peer.close(t)}activateNotifications(){if(!this.notificationsActive){this.notificationsActive=!0;for(const t of this.pendingNotifications.splice(0))this.deliverNotification(t.method,t.params)}}call(t,e,c){const s=e&&typeof e=="object"?e:{};return this.peer.call(t,{sessionId:this.sessionId,ownerId:this.ownerId,...s},m(c,1e4))}async ack(t,e){if(!Number.isSafeInteger(t)||t<=0)throw Object.assign(new Error("Bridge ACK cursor must be a positive integer"),{code:"invalid_params"});const c=await this.peer.call("session/ack",{sessionId:this.sessionId,ownerId:this.ownerId,cursor:t},m(e,5e3));return await this.onCursorAck?.(t),c}cancel(t){return this.peer.call("session/cancel",{sessionId:this.sessionId,ownerId:this.ownerId},m(t,3e4))}setOptions(t,e){return this.peer.call("session/setOptions",{sessionId:this.sessionId,ownerId:this.ownerId,model:t.modelId,modeId:t.modeId},m(e,1e4))}deliverNotification(t,e){this.emit("notification",t,e)}}class ht{options;client=null;peer=null;socket=null;exitEmitter=new O;intentionalClose=!1;constructor(t){this.options=t}async start(){const t=U({dshHome:this.options.dshHome,profileName:this.options.profileName}),e=L(t);if(e.protocolMax<M||e.protocolMin>C)throw Object.assign(new Error(`Incompatible Grix DSH Bridge protocol ${e.protocolMin}-${e.protocolMax}`),{code:"bridge_incompatible"});const c=q(e.tokenPath,"utf8").trim();if(!c)throw Object.assign(new Error("DSH Bridge token file is empty"),{code:"auth_failed"});const s=await tt(e.address,this.options.connectTimeoutMs??N);this.socket=s;const o=new G(s,{maxFrameBytes:this.options.maxFrameBytes,capture:this.options.capture});this.peer=o,o.on("close",()=>{this.socket=null,this.peer=null,this.client=null,this.intentionalClose||this.exitEmitter.emit("exit")}),o.setRequestHandler(async(i,l)=>{const n=l&&typeof l=="object"?l:{};if(i==="interaction/requestApproval")return{outcome:await this.options.onApproval?.(n)??"unavailable"};if(i==="grix/tool-call"){if(!this.options.onToolInvoke)throw Object.assign(new Error("grix tools are not wired for this Connector session"),{code:"capability_unavailable"});const d=String(n.tool??"").trim(),b=n.args&&typeof n.args=="object"?n.args:{};if(!d)throw Object.assign(new Error("grix/tool-call requires a tool name"),{code:"invalid_params"});if(!z(d))throw Object.assign(new Error(`grix tool "${d}" is not exposed to DSH`),{code:"capability_unavailable"});const j=Number(n.timeoutMs)||void 0;return{ok:!0,value:await this.options.onToolInvoke(d,b,j)}}throw Object.assign(new Error(`Unsupported Bridge request: ${i}`),{code:"capability_unavailable"})});const a=T(),g=H("sha256",c).update(`${a}
|
|
2
2
|
${t.profileKey}
|
|
3
|
-
${e.instanceId}`).digest("hex"),I=AbortSignal.timeout(this.options.initializeTimeoutMs??this.options.connectTimeoutMs??N),r=await o.call("bridge/initialize",{protocol:{min:M,max:C},client:{name:"grix-connector",version:process.env.npm_package_version??"unknown",instanceId:Z},profileKey:t.profileKey,requestedRole:"controller",auth:{nonce:a,proof:g}},I),B=r.profile&&typeof r.profile=="object"?r.profile:{},S=String(B.dshVersion??"");if(S!==e.dshVersion)throw o.close(new Error("DSH Profile version changed between discovery and handshake")),Object.assign(new Error(`DSH Profile version mismatch: discovery=${e.dshVersion||"unknown"} handshake=${S||"unknown"}`),{code:"bridge_incompatible"});const R=r.capabilities&&typeof r.capabilities=="object"?r.capabilities:{},y=this.options.settings.skillIds??[],E=(this.options.settings.skillIdsExplicit===!0||y.length>0)&&R.sessionSkillAllowlist===!0,
|
|
3
|
+
${e.instanceId}`).digest("hex"),I=AbortSignal.timeout(this.options.initializeTimeoutMs??this.options.connectTimeoutMs??N),r=await o.call("bridge/initialize",{protocol:{min:M,max:C},client:{name:"grix-connector",version:process.env.npm_package_version??"unknown",instanceId:Z},profileKey:t.profileKey,requestedRole:"controller",auth:{nonce:a,proof:g}},I),B=r.profile&&typeof r.profile=="object"?r.profile:{},S=String(B.dshVersion??"");if(S!==e.dshVersion)throw o.close(new Error("DSH Profile version changed between discovery and handshake")),Object.assign(new Error(`DSH Profile version mismatch: discovery=${e.dshVersion||"unknown"} handshake=${S||"unknown"}`),{code:"bridge_incompatible"});const R=r.capabilities&&typeof r.capabilities=="object"?r.capabilities:{},y=this.options.settings.skillIds??[],E=(this.options.settings.skillIdsExplicit===!0||y.length>0)&&R.sessionSkillAllowlist===!0,p=String(this.options.settings.providerId??"").trim();let u=[],_=!1;const x=this.options.catalogRefreshAttempts??8;for(let i=0;i<=x;i++){try{const l=AbortSignal.timeout(this.options.catalogTimeoutMs??k),n=await o.call("profile/listProviders",{},l),d=V(n.providers);if(_=!0,d.length>0&&(u=d),!p||u.some(b=>b.id===p))break}catch{break}i<x&&await new Promise(l=>setTimeout(l,150))}const w=_&&p==="grix"&&!u.some(i=>i.id===p)?p:J(p||void 0,u);let f;try{const i=AbortSignal.timeout(this.options.catalogTimeoutMs??k),l=await o.call("profile/listModels",{provider:w},i);f=Array.isArray(l.models)?l.models.filter(n=>!!n&&typeof n=="object"):[]}catch{}const P=(f??[]).some(i=>String(i.id??"")===this.options.settings.modelId)?this.options.settings.modelId:String(f?.[0]?.id??this.options.settings.modelId);let v=[...F];try{const i=AbortSignal.timeout(this.options.catalogTimeoutMs??k),l=await o.call("profile/listPresets",{},i),n=K(l.presets);n.length>0&&(v=n)}catch{}const A=X(this.options.settings.agentPreset,v);this.client=new Y(o,this.options.sessionId,this.options.ownerId,this.options.onCursorAck);try{const i=AbortSignal.timeout(this.options.sessionCreateTimeoutMs??Q);await o.call("session/create",{sessionId:this.options.sessionId,ownerId:this.options.ownerId,cwd:this.options.cwd,provider:w,model:P,reasoningEffort:W(this.options.settings),...w==="codex-app-server"?{}:{maxTokens:this.options.settings.maxTokens},modeId:this.options.settings.modeId,agentPreset:A,pluginIds:this.options.settings.pluginIds??[],...E?{skillIds:y,skillIdsExplicit:!0}:{},...E&&this.options.skillsDir?{skillsDir:this.options.skillsDir}:{},...this.options.pluginOverlayPath?{pluginOverlayPath:this.options.pluginOverlayPath}:{},systemPrompt:this.options.systemPrompt,resume:this.options.resumeSession===!0,lastAckCursor:this.options.lastAckCursor??0},i)}catch(i){throw this.client.close(i instanceof Error?i:new Error(String(i))),this.client=null,i}const D=r.serverInfo&&typeof r.serverInfo=="object"?r.serverInfo:{};return{serverInfo:{name:String(D.name??"grix-dsh-profile-bridge"),version:String(D.version??"unknown")},profile:r.profile,capabilities:r.capabilities,...f!==void 0?{models:f}:{},selectedModel:P,providers:u,selectedProvider:w,presets:v,selectedPreset:A}}async shutdown(){this.intentionalClose=!0;try{await this.client?.shutdown()}finally{this.peer?.close(),this.client=null,this.peer=null,this.socket=null}}async terminate(){this.intentionalClose=!0,this.peer?.close(new Error("DSH Profile Bridge connection terminated")),this.client=null,this.peer=null,this.socket=null}async cancel(t){await this.client?.cancel()}async hasBackgroundWork(){return!1}isConnected(){return!!this.client&&!!this.peer?.isOpen}onExit(t){return this.exitEmitter.on("exit",t),()=>this.exitEmitter.off("exit",t)}}function m(h,t){return h??AbortSignal.timeout(t)}function tt(h,t){return new Promise((e,c)=>{const s=$(h),o=setTimeout(()=>{a(),s.destroy(),c(Object.assign(new Error("Timed out connecting to DSH Profile Bridge"),{code:"bridge_connect_timeout"}))},t);o.unref?.();const a=()=>{clearTimeout(o),s.off("connect",g),s.off("error",I)},g=()=>{a(),s.setNoDelay(!0),e(s)},I=r=>{a(),c(Object.assign(r,{code:"bridge_connect_failed"}))};s.once("connect",g),s.once("error",I)})}export{k as BRIDGE_CATALOG_TIMEOUT_MS,N as BRIDGE_INITIALIZE_TIMEOUT_MS,Q as BRIDGE_SESSION_CREATE_TIMEOUT_MS,ht as DshProfileRuntime,Y as DshProfileRuntimeClient};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createWriteStream as
|
|
2
|
-
`,{mode:384}),q(o,
|
|
1
|
+
import{createWriteStream as C,existsSync as U,mkdirSync as v,readFileSync as W,renameSync as q,rmSync as J,writeFileSync as z}from"node:fs";import{join as O}from"node:path";import{log as s}from"../../core/log/index.js";import{resolveCliPath as Y}from"../../core/util/cli-probe.js";import{killProcessGroup as A,spawnCommand as Q}from"../../core/runtime/spawn.js";import{errorForDshBridgeReadiness as I}from"./bridge-installer.js";import{bridgeDiscoveryDirectory as _,discoverDshBridgeEndpoints as m,profileHasWebApp as X}from"./profile-resolver.js";import{unshadowInstalledDshPackages as Z}from"./profile-package-shadow.js";const d="deepseek-harness-profile-supervisor",T=45e3,k=5*6e4,ee=500;function re(e){return{...process.env,DSH_HOME:e}}const w=new Map,h=new Map,y=new Map;function b(e,r,n="coalesce"){const i=w.get(e.profileKey);if(i&&n==="coalesce")return i.promise;const t=(i?i.promise.catch(()=>{}).then(()=>r()):r()).finally(()=>{w.get(e.profileKey)?.promise===t&&w.delete(e.profileKey)});return w.set(e.profileKey,{promise:t}),t}async function De(e){return b(e.installer.identity,()=>F(e))}async function Ee(e){return b(e.installer.identity,()=>ne(e))}async function ne(e){const r=e.autoInstall!==!1;let n=await e.installer.status();return r&&["profile_missing","bridge_missing","bridge_update_required"].includes(n.readiness)&&(n=await e.installer.install()),n.readiness==="ready"&&!e.reloadManaged?(B(n.identity),n):F(e)}async function F(e){const r=e.installer,n=e.autoStart!==!1,i=e.readyTimeoutMs??T,o=e.bootGraceMs??k;let t=await r.status();if(e.reloadManaged&&(t=await te(r,t,i,o)),t.readiness==="ready")return B(t.identity),t;if(!n){const a=I(t);if(a)throw a;return t}if(t.readiness==="profile_restart_required"&&(t.endpointCount>0&&await ie(t),await K(r,t.identity,o),t=await N(r,i),E(t)||await L(t.identity,o,"bridge endpoint did not appear")),t.readiness==="ready")return ae(t),t;const f=I(t);if(f)throw f;return t}async function te(e,r,n,i){const o=r.identity,t=u(o);if(!t||!p(t.pid))return r;const f=m(o);if(!f.some(M=>P(t,M))&&f.length>0)return r;s.info(d,`reloading connector-managed profile=${o.profileName} pid=${t.pid} after settings write`),await $(o,t.pid),await K(e,o,i);const g=await N(e,n);return E(g)||await L(o,i,"bridge endpoint did not appear after settings reload"),g}async function ie(e){const r=e.identity,n=u(r),i=m(r),o=e.runningBridgeVersion&&e.installedBridgeVersion&&e.runningBridgeVersion!==e.installedBridgeVersion?"bridge upgrade":"bridge content refresh";if(n&&p(n.pid)&&i.some(t=>P(n,t))){s.info(d,`restarting connector-managed profile=${r.profileName} pid=${n.pid} for ${o}`),await $(r,n.pid);return}s.info(d,`starting connector-managed profile=${r.profileName} for ${o}; external profile processes are left untouched`)}async function N(e,r){const n=await ce(E,e,r);return E(n)&&B(e.identity),n}async function L(e,r,n){const i=fe(e,r);if(i)throw s.info(d,`managed profile=${e.profileName} pid=${i.pid} still booting; left running (${n})`),oe(e,i);await se(e,n)}function oe(e,r){return Object.assign(new Error(`DSH profile "${e.profileName}" is still starting (pid ${r.pid}); a first boot installs the profile dependencies before Grix Bridge can listen. The Connector keeps it running \u2014 send the message again in a moment and it will attach automatically.`),{code:"profile_starting"})}function ae(e){s.info(d,`bridge ready profile=${e.identity.profileName} endpoints=${e.endpointCount} bridge=${e.runningBridgeVersion}`)}async function K(e,r,n){const i=u(r);if(i&&p(i.pid)){if(m(r).some(R=>P(i,R))){s.info(d,`reusing connector-managed profile=${r.profileName} pid=${i.pid}`);return}if(G(i,n)){s.info(d,`waiting on booting connector-managed profile=${r.profileName} pid=${i.pid}`);return}s.warn(d,`restarting stuck connector-managed profile=${r.profileName} pid=${i.pid} (alive without endpoint)`),await $(r,i.pid)}else i&&x(r);const o=await Y(e.command);if(!o)throw Object.assign(new Error("dsh is not installed or not on PATH"),{code:"dsh_missing"});if(m(r).length===0)try{const c=Z(r.profileRoot,o);c.length>0&&s.info(d,`unshadowed profile DSH packages so official rows use the running installation: ${c.join(", ")}`)}catch(c){s.warn(d,`profile DSH package unshadow failed: ${c instanceof Error?c.message:c}`)}const t=de(r),f=_(r);v(f,{recursive:!0,mode:448});const a=O(f,"managed-profile.log"),g=C(a,{flags:"a",mode:384});g.on("error",c=>{s.warn(d,`managed profile log write failed path=${a}: ${c instanceof Error?c.message:c}`)});const M=re(r.dshHome),l=Q(o,t,{cwd:r.profileRoot,env:M,stdio:["ignore","pipe","pipe"],detached:process.platform!=="win32"}).process;if(!l.pid)throw g.end(),Object.assign(new Error(`Failed to start DSH profile "${r.profileName}"`),{code:"profile_start_failed"});y.set(r.profileKey,""),l.stdout?.pipe(g,{end:!1}),l.stderr?.setEncoding("utf8"),l.stderr?.on("data",c=>{const S=y.get(r.profileKey)??"";y.set(r.profileKey,`${S}${c}`.slice(-4e3))}),l.stderr?.pipe(g,{end:!1}),l.once("exit",(c,S)=>{s.warn(d,`managed profile exited profile=${r.profileName} pid=${l.pid} code=${c} signal=${S}`),h.get(r.profileKey)===l&&h.delete(r.profileKey);try{g.end()}catch{}}),l.unref(),h.set(r.profileKey,l),V(r,{schemaVersion:1,profileKey:r.profileKey,profileName:r.profileName,pid:l.pid,startedAt:new Date().toISOString(),command:o,args:t}),s.info(d,`started connector-managed profile=${r.profileName} pid=${l.pid} args=${t.join(" ")}`)}async function se(e,r){const n=u(e);n&&(s.warn(d,`stopping stuck connector-managed profile=${e.profileName} pid=${n.pid} reason=${r}`),await $(e,n.pid))}async function $(e,r){const n=u(e)?.endpointPid,i=n&&n!==r&&m(e).some(a=>a.pid===n)?n:null,o=i?[r,i]:[r],t=h.get(e.profileKey);if(t?.pid===r){try{A(t,"SIGTERM")}catch{}h.delete(e.profileKey)}else for(const a of o)if(p(a))try{process.kill(a,"SIGTERM")}catch{}const f=Date.now()+5e3;for(;Date.now()<f&&o.some(p);)await H(100);for(const a of o)if(p(a))try{process.kill(a,"SIGKILL")}catch{}x(e)}function de(e){return X(e.profileRoot,e.profileName)?["--profile",e.profileName,"--port","0"]:["--profile",e.profileName]}async function ce(e,r,n){const i=Date.now()+n;let o=await r.status();for(;Date.now()<i;){if(e(o))return o;const t=u(r.identity);if(t&&!p(t.pid))throw x(r.identity),le(r.identity);await H(ee),o=await r.status()}return o}function D(e){return O(_(e),"managed-profile.json")}function u(e){try{const r=JSON.parse(W(D(e),"utf8"));return r.schemaVersion!==1||typeof r.pid!="number"||r.profileKey!==e.profileKey?null:r}catch{return null}}function V(e,r){const n=_(e);v(n,{recursive:!0,mode:448});const i=D(e),o=`${i}.${process.pid}.tmp`;z(o,`${JSON.stringify(r,null,2)}
|
|
2
|
+
`,{mode:384}),q(o,i)}function P(e,r){return r.pid===e.pid||r.pid===e.endpointPid}function G(e,r){const n=Date.parse(e.startedAt);return Number.isFinite(n)?Date.now()-n<r:!1}function fe(e,r){const n=u(e);return!n||!p(n.pid)||m(e).some(i=>P(n,i))?null:G(n,r)?n:null}function B(e){const r=u(e);if(!r||typeof r.endpointPid=="number"||!p(r.pid))return;const n=m(e);if(n.some(f=>f.pid===r.pid))return;const i=Date.parse(r.startedAt);if(!Number.isFinite(i))return;const o=n.filter(f=>{const a=Date.parse(f.startedAt);return Number.isFinite(a)&&a>=i});if(o.length!==1)return;const t=o[0];V(e,{...r,endpointPid:t.pid}),s.info(d,`adopted managed bridge endpoint profile=${e.profileName} wrapper=${r.pid} pid=${t.pid}`)}function x(e){try{J(D(e),{force:!0})}catch{}}function p(e){try{return process.kill(e,0),!0}catch(r){return r.code==="EPERM"}}function H(e){return new Promise(r=>setTimeout(r,e))}function Me(){w.clear(),y.clear();for(const e of h.values())try{e.pid&&A(e,"SIGKILL")}catch{}h.clear()}function le(e){const r=pe(y.get(e.profileKey)??""),n=`Connector-managed DSH profile "${e.profileName}" exited before Bridge became ready`+(r?`: ${r}`:"");return Object.assign(new Error(n),{code:"profile_start_failed"})}function pe(e){const r=e.split(/\r?\n/).map(o=>o.trim()).filter(Boolean);if(r.length===0)return"";let n=-1;for(let o=r.length-1;o>=0;o-=1){const t=r[o];if(t.startsWith("dsh: startup failed")||t.startsWith("dsh: plugin tree failed")||t.startsWith("Error: dsh:")){n=o;break}}return(n>=0?r.slice(n,n+6):r.slice(-4)).join(" | ").replace(/\s+/g," ").slice(0,480)}function _e(e){return U(D(e))}async function Ne(e){const r=w.get(e.profileKey);r&&await r.promise.catch(()=>{})}async function Ke(e,r=T){let n="failed";return await b(e.identity,async()=>(n=await ue(e,r),j(e,n==="restarted"?"ready":"profile_restart_required")),"queue"),n}async function ue(e,r){const n=e.identity,i=u(n);if(!i||!p(i.pid))return"not_managed";const o=m(n);if(o.length>0&&!o.some(t=>P(i,t)))return"not_managed";try{return s.info(d,`restarting connector-managed profile=${n.profileName} pid=${i.pid} for plugin toggle`),await $(n,i.pid),await K(e,n,k),(await N(e,r)).readiness==="ready"?"restarted":"failed"}catch(t){return s.warn(d,`plugin-toggle restart failed profile=${n.profileName}: ${t instanceof Error?t.message:String(t)}`),"failed"}}function E(e){return e.readiness==="ready"}function Be(e,r){return b(e.identity,async()=>(await r,j(e,"ready")))}function j(e,r){return{readiness:r,command:e.command,commandPath:null,dshVersion:null,runningDshVersion:null,identity:e.identity,installedBridgeVersion:null,bundledBridgeVersion:"",runningBridgeVersion:null,endpointCount:0}}export{Ne as awaitDshProfileIdle,de as buildDshProfileBootArgs,De as ensureDshBridgeReady,Be as holdDshProfileInflightForTests,_e as managedProfileRecordExists,re as managedProfileSpawnEnv,Ee as prepareDshProfileBridge,Me as resetDshProfileSupervisorForTests,Ke as restartManagedProfileIfOwned};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{DEFAULT_DSH_PROFILE_NAME as s,dshProfileDisplayName as c}from"./profile-resolver.js";const m="approval",g="enabled",u="high",E=16384,l="deepseek-official",a=Object.freeze([{id:"deepseek-v4-flash",displayName:"DeepSeek-V4-Flash",contextWindow:1e6},{id:"deepseek-v4-pro",displayName:"DeepSeek-V4-Pro",contextWindow:1e6}]),p="standard",_=Object.freeze([{id:"standard",displayName:"\u6807\u51C6\u6A21\u5F0F",description:"\u529F\u80FD\u5B8C\u6574\u7684\u7F16\u7801 Agent\uFF0C\u652F\u6301\u6587\u4EF6\u7F16\u8F91\u3001Shell\u3001\u6587\u4EF6\u4E0E\u7F51\u9875\u68C0\u7D22\u3001Skills\u3001\u8BA1\u5212\u3001\u76EE\u6807\u3001\u5B50\u4EE3\u7406\u548C\u5DE5\u4F5C\u6D41\u3002"},{id:"code",displayName:"PTC \u6A21\u5F0F",description:"\u5177\u5907\u6807\u51C6\u6A21\u5F0F\u7684\u5168\u90E8\u80FD\u529B\uFF0C\u5E76\u901A\u8FC7 Code Mode SDK \u5448\u73B0\u5DE5\u5177\uFF0C\u8BA9\u6A21\u578B\u7528\u4E00\u4E2A TypeScript \u7A0B\u5E8F\u7EC4\u5408\u591A\u6B65\u64CD\u4F5C\u3002"},{id:"minimal",displayName:"\u6781\u7B80\u6A21\u5F0F",description:"\u4EC5\u63D0\u4F9B\u6301\u4E45 bash \u4E0E str_replace_editor \u7684\u53CC\u5DE5\u5177\u7F16\u7801 Agent\u3002"},{id:"cordis",displayName:"\u521B\u9020\u6A21\u5F0F",description:"\u7528\u4E8E\u521B\u5EFA\u81EA\u5B9A\u4E49 Agent preset\uFF1A\u5177\u5907\u6807\u51C6\u6A21\u5F0F\u7684\u5168\u90E8\u80FD\u529B\uFF0C\u5E76\u63D0\u4F9B\u8FD0\u884C\u65F6\u68C0\u67E5\u3001\u63D2\u4EF6\u5B9E\u9A8C\u548C preset \u521B\u4F5C\u6307\u5BFC\u3002"}]);function h(e){return e==="full_auto"||e==="approval"?e:void 0}function N(e,r){return h(e)??h(r)??m}function v(e){return e==="enabled"||e==="disabled"?e:void 0}function b(e){return e==="high"||e==="max"?e:void 0}function P(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const o=r,i=String(o.id??"").trim();return i?[{id:i,displayName:String(o.displayName??o.name??i)}]:[]}):[]}function I(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const o=r,i=String(o.id??"").trim();if(!i)return[];const d=Number(o.contextWindow);return[{id:i,displayName:String(o.displayName??o.name??i),contextWindow:Number.isSafeInteger(d)&&d>0?d:1e6}]}):[]}function y(e){return e.fetched!==void 0?I(e.fetched):e.providerChanged?[]:[...e.current]}function L(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const o=r,i=String(o.id??"").trim();if(!i||o.broken)return[];const d=String(o.description??"").trim();return[{id:i,displayName:String(o.displayName??o.name??i),...d?{description:d}:{}}]}):[]}const D=Object.freeze([{id:s,displayName:c(s),webApp:!0}]);function T(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const o=r,i=String(o.id??"").trim();return i?[{id:i,displayName:String(o.displayName??o.name??c(i)),...o.webApp===!0?{webApp:!0}:{}}]:[]}):[]}function S(e,r){const o=String(e??"").trim();return o&&r.some(i=>i.id===o)?o:r.some(i=>i.id===p)?p:r[0]?.id||p}function f(e,r){const o=String(e??"").trim();return o&&r.some(i=>i.id===o)?o:r.some(i=>i.id===l)?l:r[0]?.id||l}function F(e){const r=String(e.requestedProviderId??"").trim();if(!!r&&e.liveProviders.some(t=>t.id===r))return{providerId:r,persistFallback:!1};if(r)return{providerId:r,persistFallback:!1};const i=String(e.liveSelectedProvider??"").trim();return{providerId:f(i||void 0,e.liveProviders),persistFallback:!0}}function R(e,r,o){const i=String(r??"").trim(),d=e.length>0?[...e]:[];if(i&&!d.some(t=>t.id===i)){const t=o.find(n=>n.id===i);t&&d.unshift(t)}return d}function M(e){const r=e.applied,o=e.state??(r?r.appliedRevision===e.desired.revision?"applied":"pending":"applied"),i=e.runtimeReadiness??"unknown",d=e.providers??[],t=e.presets??_,n=f(e.desired.providerId,d),x=S(e.desired.agentPreset,t),k=r!=null||o==="pending"||o==="failed";return{provider_id:n,model_id:e.desired.modelId,mode_id:e.desired.modeId,thinking_mode:v(e.desired.thinking)??g,reasoning_effort:b(e.desired.reasoningEffort)??u,agent_preset_id:x,agent_preset_locked:e.agentPresetLocked===!0,available_providers:[...d],available_models:[...e.models??a],available_presets:[...t],available_modes:[{id:"approval",label:"\u5BA1\u6279\uFF08\u5DE5\u4F5C\u533A\u5185\u81EA\u52A8\uFF0C\u8D8A\u754C\u5931\u8D25\uFF09"},{id:"full_auto",label:"\u81EA\u52A8\uFF08\u5168\u6743\u9650\uFF09"}],settings_revision:e.desired.revision,...k?{applied_provider_id:r?.providerId??null,applied_model_id:r?.modelId??null,applied_mode_id:r?.modeId??null,applied_thinking_mode:r?.thinking??null,applied_reasoning_effort:r?.reasoningEffort??null,applied_settings_revision:r?.appliedRevision??null}:{},settings_state:o,settings_error_code:e.errorCode??null,context_window:e.contextWindow??null,provider_quota:e.providerQuota??null,dsh_integration_mode:e.integrationMode??"profile_bridge",dsh_profile:e.profileName??s,available_profiles:[...e.profiles??D],dsh_profile_locked:e.profileLocked===!0,dsh_profile_create:e.profileLocked!==!0&&e.profileCreate!==!1,dsh_plugins:[...e.plugins??[]],dsh_skills:[...e.skills??[]],dsh_plugin_restart_required:e.pluginRestartRequired===!0,dsh_runtime_readiness:i,dsh_bridge_action_required:["dsh_missing","profile_missing","bridge_missing","bridge_update_required"].includes(i)?"install_bridge":i==="profile_restart_required"?"restart_profile":null,dsh_profile_restart_required:i==="profile_restart_required",dsh_bridge_capabilities:e.bridgeCapabilities??null}}function q(e){return e==="full_auto"?"danger-full-access":"workspace-write"}function w(e){const r=e.providers??[],o=f(e.providerId,r),i=[...e.models??a],d=String(e.modelId??"").trim()||i[0]?.id||a[0].id,t=e.modeId==="full_auto"?"full_auto":m;return{agent_preset_id:S(e.agentPreset,_),agent_preset_locked:e.agentPresetLocked===!0,available_presets:[..._],dsh_profile:e.profileName??s,available_profiles:[...e.profiles??D],dsh_profile_locked:e.profileLocked===!0,dsh_profile_create:e.profileLocked!==!0,dsh_plugins:[...e.plugins??[]],dsh_skills:[...e.skills??[]],dsh_plugin_restart_required:e.pluginRestartRequired===!0,provider_id:o,model_id:d,mode_id:t,thinking_mode:v(e.thinking)??g,reasoning_effort:b(e.reasoningEffort)??u,available_providers:[...r],available_models:i,available_modes:[{id:"approval",label:"\u5BA1\u6279\uFF08\u5DE5\u4F5C\u533A\u5185\u81EA\u52A8\uFF0C\u8D8A\u754C\u5931\u8D25\uFF09"},{id:"full_auto",label:"\u81EA\u52A8\uFF08\u5168\u6743\u9650\uFF09"}]}}export{E as DEFAULT_DSH_MAX_TOKENS,m as DEFAULT_DSH_MODE,a as DEFAULT_DSH_MODELS,_ as DEFAULT_DSH_PRESETS,p as DEFAULT_DSH_PRESET_ID,D as DEFAULT_DSH_PROFILES,l as DEFAULT_DSH_PROVIDER_ID,u as DEFAULT_DSH_REASONING_EFFORT,g as DEFAULT_DSH_THINKING,y as adoptDshProfileModels,F as adoptLiveDshProviderSelection,w as buildDshBindingToolbarMeta,M as buildDshToolbarMeta,h as normalizeDshModeId,I as normalizeDshModels,L as normalizeDshPresets,T as normalizeDshProfiles,P as normalizeDshProviders,b as normalizeDshReasoningEffort,v as normalizeDshThinking,q as permissionModeFor,S as resolveDshAgentPreset,N as resolveDshModeId,f as resolveDshProviderId,R as retainRequestedDshProvider};
|
|
1
|
+
import{DEFAULT_DSH_PROFILE_NAME as s,dshProfileDisplayName as c}from"./profile-resolver.js";const m="approval",g="enabled",u="high",E=16384,l="deepseek-official",a=Object.freeze([{id:"deepseek-v4-flash",displayName:"DeepSeek-V4-Flash",contextWindow:1e6},{id:"deepseek-v4-pro",displayName:"DeepSeek-V4-Pro",contextWindow:1e6}]),p="standard",_=Object.freeze([{id:"standard",displayName:"\u6807\u51C6\u6A21\u5F0F",description:"\u529F\u80FD\u5B8C\u6574\u7684\u7F16\u7801 Agent\uFF0C\u652F\u6301\u6587\u4EF6\u7F16\u8F91\u3001Shell\u3001\u6587\u4EF6\u4E0E\u7F51\u9875\u68C0\u7D22\u3001Skills\u3001\u8BA1\u5212\u3001\u76EE\u6807\u3001\u5B50\u4EE3\u7406\u548C\u5DE5\u4F5C\u6D41\u3002"},{id:"code",displayName:"PTC \u6A21\u5F0F",description:"\u5177\u5907\u6807\u51C6\u6A21\u5F0F\u7684\u5168\u90E8\u80FD\u529B\uFF0C\u5E76\u901A\u8FC7 Code Mode SDK \u5448\u73B0\u5DE5\u5177\uFF0C\u8BA9\u6A21\u578B\u7528\u4E00\u4E2A TypeScript \u7A0B\u5E8F\u7EC4\u5408\u591A\u6B65\u64CD\u4F5C\u3002"},{id:"minimal",displayName:"\u6781\u7B80\u6A21\u5F0F",description:"\u4EC5\u63D0\u4F9B\u6301\u4E45 bash \u4E0E str_replace_editor \u7684\u53CC\u5DE5\u5177\u7F16\u7801 Agent\u3002"},{id:"cordis",displayName:"\u521B\u9020\u6A21\u5F0F",description:"\u7528\u4E8E\u521B\u5EFA\u81EA\u5B9A\u4E49 Agent preset\uFF1A\u5177\u5907\u6807\u51C6\u6A21\u5F0F\u7684\u5168\u90E8\u80FD\u529B\uFF0C\u5E76\u63D0\u4F9B\u8FD0\u884C\u65F6\u68C0\u67E5\u3001\u63D2\u4EF6\u5B9E\u9A8C\u548C preset \u521B\u4F5C\u6307\u5BFC\u3002"}]);function h(e){return e==="full_auto"||e==="approval"?e:void 0}function N(e,r){return h(e)??h(r)??m}function v(e){return e==="enabled"||e==="disabled"?e:void 0}function b(e){return e==="high"||e==="max"?e:void 0}function P(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const o=r,i=String(o.id??"").trim();return i?[{id:i,displayName:String(o.displayName??o.name??i)}]:[]}):[]}function I(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const o=r,i=String(o.id??"").trim();if(!i)return[];const d=Number(o.contextWindow);return[{id:i,displayName:String(o.displayName??o.name??i),contextWindow:Number.isSafeInteger(d)&&d>0?d:1e6}]}):[]}function y(e){return e.fetched!==void 0?I(e.fetched):e.providerChanged?[]:[...e.current]}function L(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const o=r,i=String(o.id??"").trim();if(!i||o.broken)return[];const d=String(o.description??"").trim();return[{id:i,displayName:String(o.displayName??o.name??i),...d?{description:d}:{}}]}):[]}const D=Object.freeze([{id:s,displayName:c(s),webApp:!0}]);function T(e){return Array.isArray(e)?e.flatMap(r=>{if(!r||typeof r!="object")return[];const o=r,i=String(o.id??"").trim();return i?[{id:i,displayName:String(o.displayName??o.name??c(i)),...o.webApp===!0?{webApp:!0}:{}}]:[]}):[]}function S(e,r){const o=String(e??"").trim();return o&&r.some(i=>i.id===o)?o:r.some(i=>i.id===p)?p:r[0]?.id||p}function f(e,r){const o=String(e??"").trim();return o&&r.some(i=>i.id===o)?o:r.some(i=>i.id===l)?l:r[0]?.id||l}function F(e){const r=String(e.requestedProviderId??"").trim();if(!!r&&e.liveProviders.some(t=>t.id===r))return{providerId:r,persistFallback:!1};if(r==="grix")return{providerId:r,persistFallback:!1};const i=String(e.liveSelectedProvider??"").trim();return{providerId:f(i||void 0,e.liveProviders),persistFallback:!0}}function R(e,r,o){const i=String(r??"").trim(),d=e.length>0?[...e]:[];if(i&&!d.some(t=>t.id===i)){const t=o.find(n=>n.id===i);t&&d.unshift(t)}return d}function M(e){const r=e.applied,o=e.state??(r?r.appliedRevision===e.desired.revision?"applied":"pending":"applied"),i=e.runtimeReadiness??"unknown",d=e.providers??[],t=e.presets??_,n=f(e.desired.providerId,d),x=S(e.desired.agentPreset,t),k=r!=null||o==="pending"||o==="failed";return{provider_id:n,model_id:e.desired.modelId,mode_id:e.desired.modeId,thinking_mode:v(e.desired.thinking)??g,reasoning_effort:b(e.desired.reasoningEffort)??u,agent_preset_id:x,agent_preset_locked:e.agentPresetLocked===!0,available_providers:[...d],available_models:[...e.models??a],available_presets:[...t],available_modes:[{id:"approval",label:"\u5BA1\u6279\uFF08\u5DE5\u4F5C\u533A\u5185\u81EA\u52A8\uFF0C\u8D8A\u754C\u5931\u8D25\uFF09"},{id:"full_auto",label:"\u81EA\u52A8\uFF08\u5168\u6743\u9650\uFF09"}],settings_revision:e.desired.revision,...k?{applied_provider_id:r?.providerId??null,applied_model_id:r?.modelId??null,applied_mode_id:r?.modeId??null,applied_thinking_mode:r?.thinking??null,applied_reasoning_effort:r?.reasoningEffort??null,applied_settings_revision:r?.appliedRevision??null}:{},settings_state:o,settings_error_code:e.errorCode??null,context_window:e.contextWindow??null,provider_quota:e.providerQuota??null,dsh_integration_mode:e.integrationMode??"profile_bridge",dsh_profile:e.profileName??s,available_profiles:[...e.profiles??D],dsh_profile_locked:e.profileLocked===!0,dsh_profile_create:e.profileLocked!==!0&&e.profileCreate!==!1,dsh_plugins:[...e.plugins??[]],dsh_skills:[...e.skills??[]],dsh_plugin_restart_required:e.pluginRestartRequired===!0,dsh_runtime_readiness:i,dsh_bridge_action_required:["dsh_missing","profile_missing","bridge_missing","bridge_update_required"].includes(i)?"install_bridge":i==="profile_restart_required"?"restart_profile":null,dsh_profile_restart_required:i==="profile_restart_required",dsh_bridge_capabilities:e.bridgeCapabilities??null}}function q(e){return e==="full_auto"?"danger-full-access":"workspace-write"}function w(e){const r=e.providers??[],o=f(e.providerId,r),i=[...e.models??a],d=String(e.modelId??"").trim()||i[0]?.id||a[0].id,t=e.modeId==="full_auto"?"full_auto":m;return{agent_preset_id:S(e.agentPreset,_),agent_preset_locked:e.agentPresetLocked===!0,available_presets:[..._],dsh_profile:e.profileName??s,available_profiles:[...e.profiles??D],dsh_profile_locked:e.profileLocked===!0,dsh_profile_create:e.profileLocked!==!0,dsh_plugins:[...e.plugins??[]],dsh_skills:[...e.skills??[]],dsh_plugin_restart_required:e.pluginRestartRequired===!0,provider_id:o,model_id:d,mode_id:t,thinking_mode:v(e.thinking)??g,reasoning_effort:b(e.reasoningEffort)??u,available_providers:[...r],available_models:i,available_modes:[{id:"approval",label:"\u5BA1\u6279\uFF08\u5DE5\u4F5C\u533A\u5185\u81EA\u52A8\uFF0C\u8D8A\u754C\u5931\u8D25\uFF09"},{id:"full_auto",label:"\u81EA\u52A8\uFF08\u5168\u6743\u9650\uFF09"}]}}export{E as DEFAULT_DSH_MAX_TOKENS,m as DEFAULT_DSH_MODE,a as DEFAULT_DSH_MODELS,_ as DEFAULT_DSH_PRESETS,p as DEFAULT_DSH_PRESET_ID,D as DEFAULT_DSH_PROFILES,l as DEFAULT_DSH_PROVIDER_ID,u as DEFAULT_DSH_REASONING_EFFORT,g as DEFAULT_DSH_THINKING,y as adoptDshProfileModels,F as adoptLiveDshProviderSelection,w as buildDshBindingToolbarMeta,M as buildDshToolbarMeta,h as normalizeDshModeId,I as normalizeDshModels,L as normalizeDshPresets,T as normalizeDshProfiles,P as normalizeDshProviders,b as normalizeDshReasoningEffort,v as normalizeDshThinking,q as permissionModeFor,S as resolveDshAgentPreset,N as resolveDshModeId,f as resolveDshProviderId,R as retainRequestedDshProvider};
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{EventEmitter as E}from"node:events";import{stat as N,mkdtemp as L,rm as j}from"node:fs/promises";import{join as R,resolve as Q}from"node:path";import{tmpdir as U}from"node:os";import{randomBytes as q}from"node:crypto";import{fileURLToPath as H}from"node:url";import{spawnCommand as V,killProcessGroup as S,hasChildProcesses as W}from"../../core/runtime/spawn.js";import{resolveOpencodeCommandPath as G}from"./resolve-command.js";import{InternalApiServer as J}from"../../core/mcp/internal-api-server.js";import{resolveMcpServerName as z}from"../../core/mcp/server-name.js";import{InboundMessageIdInjector as X}from"../shared/inbound-message-id-injector.js";import{IdentityInjector as Y}from"../shared/identity-injector.js";import{syncDefaultSkillsToDir as K}from"../../default-skills/index.js";import{buildSimpleProbeReport as Z}from"../shared/probe-util.js";import{compactToolInputForWire as ee}from"../shared/tool-wire-payload.js";import{normalizeOCProviderModels as te}from"./opencode-types.js";import{buildOpencodeConfigContent as se}from"./opencode-config.js";import{agentIdOf as ie}from"../shared/native-provider-config.js";import{formatOpenCodeErrorMessage as P}from"./format-error.js";import{OpenCodeTransport as ne,OpenCodeHttpError as T}from"./opencode-transport.js";import{log as a}from"../../core/log/index.js";import{splitTextForAibotProtocol as x}from"../../core/protocol/index.js";class oe extends E{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitError(e){if(this.listenerCount("error")===0){a.warn("opencode-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}const re=200,ae=2e3,de=12e4,ce=90*1e3,M=1800*1e3,O=3e4,_=600*1e3,le="claude_interaction_reply",he="set_mode",pe="set_model",ue="127.0.0.1",fe=0,me=1e3,v={fullAuto:"full_auto",approval:"approval"},$=[{id:v.fullAuto,displayName:"Full Auto"},{id:v.approval,displayName:"Approval"}],ve=[{permission:"*",pattern:"*",action:"allow"}],ge=[{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 k(g){const e=String(g??"").trim().toLowerCase();if(e==="full_auto"||e==="fullauto")return v.fullAuto;if(e==="approval"||e==="ask"||e==="autoedit"||e==="auto_edit")return v.approval}function D(g){try{return process.kill(g,0),!0}catch(e){return e.code==="EPERM"}}class je extends E{type="opencode";config;callbacks;options;identity;inboundMessageIds=new X;process=null;transport=new ne;alive=!1;stopped=!1;internalApi=null;sessions=new Map;sessionModes=new Map;sessionModels=new Map;availableModels=[];modelContextLimits=new Map;contextTokensBySession=new Map;activeRun=null;runBarrier=Promise.resolve();cancellationFailure=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 Y("opencode-adapter",s.getAgentProfile)}onAgentProfileChanged(){this.identity.onProfileChanged()}serverPassword="";privateConfigDir=null;childConfig={};startupCancel=null;stopTask=null;async start(){this.stopTask&&await this.stopTask,this.stopped=!1,this.cancellationFailure=null,this.runBarrier=Promise.resolve();try{if(await this.startInternalApiAndInjectMcp(),this.stopped)throw new Error("OpenCode startup canceled");const e=this.options.hostname??ue,s=this.options.port??fe,t=await this.spawnAndWait(e,s);if(this.stopped)throw new Error("OpenCode startup canceled");const i=this.resolveCwd();this.transport.on("event",n=>this.handleSseEvent(n)),this.transport.on("stream-lost",()=>{this.activeRun&&(this.flushTextBuffer(),this.finishRun("failed","OpenCode event stream interrupted; output may be incomplete"))}),this.transport.on("admission-uncertain",()=>{this.alive=!1,this.activeRun&&this.finishRun("failed","OpenCode prompt admission could not be confirmed; server retired"),this.stop(),this.emit("exit",-1)}),this.transport.on("stream-unavailable",()=>{this.alive=!1,this.stopped||this.emit("exit",-1)}),await this.transport.connect(t,i,{username:"opencode",password:this.serverPassword});const o=this.getMcpConfig();await this.transport.configureMcp(o.name,[o.command,...o.args??[]]);try{await this.refreshModels()}catch(n){a.warn("opencode-adapter",`Failed to fetch providers for toolbar models: ${n instanceof Error?n.message:String(n)}`)}if(this.stopped||!this.transport.isConnected)throw new Error("OpenCode startup canceled or disconnected");this.alive=!0,a.info("opencode-adapter",`Ready (pid=${this.process?.pid}, protocol=${this.transport.protocol})`)}catch(e){throw await this.stop(),e}}async refreshModels(e){const s=await this.transport.listProviders(e),t=[],i=new Map;for(const o of s)for(const n of te(o.models)){t.push({id:`${o.id}/${n.id}`,displayName:n.name||n.id});const r=n.limit?.context;typeof r=="number"&&r>0&&i.set(`${o.id}/${n.id}`,r)}t.sort((o,n)=>{const r=o.displayName.toLowerCase().localeCompare(n.displayName.toLowerCase());return r!==0?r:o.id.localeCompare(n.id)}),this.availableModels=t,this.modelContextLimits=i,a.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[o,n]of this.modelContextLimits)o.startsWith(`${e}/`)&&(i=i===void 0?n:Math.max(i,n));return i}buildContextWindowMeta(e,s,t,i){if(!i||i<=0)return;const o=this.resolveContextLimit(s,t);if(!o)return;const n=Math.min(100,i/o*100);return{context_window:{used:i,size:o,usedPercentage:n,remainingPercentage:100-n}}}stop(){if(this.stopTask)return this.stopTask;const e=this.stopInternal();return this.stopTask=e,e.then(()=>{this.stopTask=null},()=>{this.stopTask=null}),e}async stopInternal(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.clearRun(),this.startupCancel?.(),this.startupCancel=null,this.transport.disconnect(),await this.runBarrier.catch(()=>{}),this.serverPassword="",this.childConfig={},this.process){const e=this.process;this.process=null,await new Promise(s=>{if(e.exitCode!==null||e.signalCode!==null){try{S(e,"SIGKILL")}catch{}s();return}const t=()=>{clearTimeout(i),e.removeListener("exit",t);try{S(e,"SIGKILL")}catch{}s()},i=setTimeout(t,5e3);e.once("exit",t);try{S(e,"SIGTERM")}catch{t()}})}this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.privateConfigDir&&(await j(this.privateConfigDir,{recursive:!0,force:!0}),this.privateConfigDir=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}),a.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(i){if(!(i instanceof T)||i.status!==404||i.method!=="GET")throw i;a.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 oe(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){const s=this.activeRun;!s||s.sessionId!==e||(this.deliverStopEvent(s.eventId),await s.cancelTask)}deliverInboundEvent(e){const{event_id:s,session_id:t,content:i}=e;if(this.completedEvents.has(s)){a.info("opencode-adapter",`Dropping duplicate event ${s}`),this.callbacks.sendEventAck(s,t),this.callbacks.sendEventResult(s,"responded");return}if(!this.alive){a.warn("opencode-adapter",`Dropping event ${s}: process not alive`),this.callbacks.sendEventAck(s,t),this.callbacks.sendEventResult(s,"failed","Agent process not running");return}if(this.activeRun)if(this.activeRun.eventId!==s)a.info("opencode-adapter",`steer: ${this.activeRun.eventId} -> ${s}`),this.flushTextBuffer(),this.finishRun("canceled","steered to new event");else{this.callbacks.sendEventAck(s,t);return}a.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 o=this.buildPromptTextFromEvent(e),n=this.activeRun,r=this.runBarrier.then(async()=>{if(n.controller.signal.throwIfAborted(),this.cancellationFailure)throw this.cancellationFailure;await this.sendOcPrompt(t,o,n)});n.promptTask=r,this.runBarrier=r.catch(()=>{}),r.catch(d=>{this.activeRun===n&&(a.error("opencode-adapter",`prompt_async failed: ${d}`),this.finishRun("failed",String(d)))})}deliverStopEvent(e,s){this.activeRun&&this.activeRun.eventId===e&&(a.info("opencode-adapter",`stop: event=${e}`),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.cancelRun(this.activeRun),this.snapshotAuditBoundary(this.activeRun)),this.activeRun=null}getMcpConfig(){if(!this.internalApi)return null;const e=Q(H(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:z(this.callbacks.getAgentId?.()),command:process.execPath,args:[e,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const e=this.process?.pid;return e?W(e,[e]):!1}async probe(e){const s=this.getStatus();return Z(this.config.command||"opencode",{alive:s.alive,busy:s.busy,started:!!this.process},e)}async startInternalApiAndInjectMcp(){if(this.internalApi=new J,this.internalApi.setInvokeHandler(async(t,i,o,n)=>this.callbacks.agentInvoke(t,i,n)),await this.internalApi.start(0),this.stopped)throw new Error("OpenCode startup canceled");if(this.privateConfigDir=await L(R(U(),"grix-opencode-")),this.stopped)throw new Error("OpenCode startup canceled");const e=R(this.privateConfigDir,"skills");K(e);const s=this.getMcpConfig();this.childConfig={mcp:{[s.name]:{type:"local",command:[s.command,...s.args??[]],enabled:!0}},skills:{paths:[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===he)return this.handleSetModeAction(e);if(s===pe)return this.handleSetModelAction(e);if(s===le){const t=e.params??{};if(String(t.kind??"")==="permission"){const i=t.resolution??{},o=String(i.value??"");return this.handlePermissionAction({...e,action_type:o==="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(a.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){a.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=k(this.options.permissionPolicy);if(s)return s;if(e){const t=k(this.options.bindingStore?.get(e)?.modeId);if(t)return t}return v.fullAuto}buildModeToolbarMeta(e){const s=this.resolveModeId(e);return{mode_id:s,currentModeId:s,available_modes:$.map(t=>({...t}))}}async applySessionPermission(e,s,t,i){i?.throwIfAborted();const o=this.resolveModeId(e),n=o===v.fullAuto?ve:ge;try{await this.transport.updateSessionPermission(s,n,t,...i?[i]:[]),i?.throwIfAborted(),a.info("opencode-adapter",`Applied session permission ruleset (${o}) to ${s}`)}catch(r){if(i?.throwIfAborted(),this.transport.protocol==="v2")throw r;a.warn("opencode-adapter",`Failed to apply session permission ruleset: ${r instanceof Error?r.message:String(r)}`)}}async handleSetModeAction(e){const s=e.params??{},t=String(s.session_id??this.options.aibotSessionId??"").trim(),i=k(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"};const o=this.sessionModes.get(t);this.sessionModes.set(t,i);const n=this.sessions.get(t);if(n?.ocSessionId)try{await this.applySessionPermission(t,n.ocSessionId,n.cwd)}catch(d){throw o?this.sessionModes.set(t,o):this.sessionModes.delete(t),d}const r=n?.cwd??this.getSessionCwd(t);return this.callbacks.sendUpdateBindingCard(t,"ready",r,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:$.map(d=>({...d}))}),{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 o=this.sessions.get(t)?.cwd??this.getSessionCwd(t);return this.callbacks.sendUpdateBindingCard(t,"ready",o,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(n=>({...n}))}),{handled:!0,kind:"set_model"}}async spawnAndWait(e,s){const t=this.resolveCwd();try{if(!(await N(t)).isDirectory())throw new Error(`Bound path is not a directory: ${t}`)}catch(n){throw String(n?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${t}. Please rebind with /grix open <valid-directory>.`):n}if(this.stopped)throw new Error("OpenCode startup canceled");const i=this.config.command||"opencode",o=await G(i,typeof this.config.env?.PATH=="string"?this.config.env.PATH:process.env.PATH);return new Promise((n,r)=>{const c=[...this.config.args??["serve"],`--hostname=${e}`,`--port=${s}`],l={...process.env,...this.config.env},p=se({model:this.options.model,permissionPolicy:this.options.permissionPolicy,provider:this.options.provider}),u=(ie(i)||"opencode").toUpperCase().replace(/[^A-Z0-9_]/g,"_")||"OPENCODE";let h={};if(l[`${u}_CONFIG_CONTENT`])try{if(h=JSON.parse(l[`${u}_CONFIG_CONTENT`]),!h||typeof h!="object"||Array.isArray(h))throw new Error}catch{r(new Error("OpenCode child CONFIG_CONTENT must be a JSON object"));return}const F=Array.isArray(h.skills)?h.skills:Array.isArray(h.skills?.paths)?h.skills.paths:[],C={...h,...p,...this.childConfig,...this.childConfig.mcp?{mcp:{...h.mcp,...this.childConfig.mcp}}:{},...this.privateConfigDir?{skills:{...Array.isArray(h.skills)?{}:h.skills,paths:[...F,R(this.privateConfigDir,"skills")]}}:{}};Object.keys(C).length&&(l[`${u}_CONFIG_CONTENT`]=JSON.stringify(C)),this.serverPassword=q(32).toString("base64url"),l.OPENCODE_PASSWORD=this.serverPassword,l.OPENCODE_SERVER_PASSWORD=this.serverPassword,l.OPENCODE_SERVER_USERNAME="opencode";const A=u;l[`${A}_SERVER_PASSWORD`]=this.serverPassword,l[`${A}_SERVER_USERNAME`]="opencode",a.info("opencode-adapter",`Spawning OpenCode server (cwd=${t})`),this.process=V(o,c,{env:l,cwd:t}).process;let I="",f=!1;const w=setTimeout(()=>{f||(f=!0,r(new Error(`opencode serve did not start after ${O/1e3}s`)))},O);this.startupCancel=()=>{clearTimeout(w),f||(f=!0,r(new Error("OpenCode startup canceled")))},this.process.stdout?.on("data",m=>{if(f)return;I=(I+m.toString()).slice(-8192);const y=I.split(/\r?\n/);I=y.pop()??"";for(const B of y){const b=B.match(/\bserver listening on (https?:\/\/\S+)/);if(b){clearTimeout(w),f=!0,this.startupCancel=null,n(b[1]);return}}}),this.process.stderr?.on("data",()=>{}),this.process.on("error",m=>{a.error("opencode-adapter",`Spawn error: ${m.message}`),clearTimeout(w),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Spawn error: ${m.message}`),this.clearRun()),f?this.stopped||this.emit("exit",1):(f=!0,r(m))}),this.process.on("exit",m=>{a.info("opencode-adapter",`Process exited (code=${m})`),clearTimeout(w),this.alive=!1,this.transport.disconnect(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Process exited (code=${m})`),this.clearRun()),f?this.stopped||this.emit("exit",m??1):(f=!0,r(new Error(`opencode serve exited with code ${m}`)))})})}async ensureOcSession(e,s){s?.throwIfAborted();const t=this.sessions.get(e),i=this.getSessionCwd(e);if(await this.transport.useDirectory(i,...s?[s]:[]),s?.throwIfAborted(),t?.ocSessionId)try{return await this.transport.getSession(t.ocSessionId,i,...s?[s]:[]),s?.throwIfAborted(),t.ocSessionId}catch(r){if(!(r instanceof T)||r.status!==404||r.method!=="GET")throw r;a.warn("opencode-adapter",`OC session ${t.ocSessionId} gone, creating new`),t.ocSessionId=""}const o=this.options.bindingStore?.getAcpSessionId(e);if(o)try{return await this.transport.getSession(o,i,...s?[s]:[]),s?.throwIfAborted(),this.sessions.set(e,{ocSessionId:o,cwd:i}),a.info("opencode-adapter",`Resumed OC session ${o} for aibot=${e}`),await this.applySessionPermission(e,o,i,s),o}catch(r){if(!(r instanceof T)||r.status!==404||r.method!=="GET")throw r;a.warn("opencode-adapter",`Persisted OC session ${o} gone, creating new`)}const n=await this.transport.createSession({title:`grix-${e.slice(-8)}`},i,...s?[s]:[]);return s?.throwIfAborted(),this.sessions.set(e,{ocSessionId:n.id,cwd:i}),this.options.bindingStore?.setAcpSessionId(e,n.id),a.info("opencode-adapter",`Created OC session ${n.id} for aibot=${e}`),await this.applySessionPermission(e,n.id,i,s),n.id}async sendOcPrompt(e,s,t=this.activeRun){const i=t?.controller?.signal;i?.throwIfAborted();const o=this.getSessionCwd(e),n=await this.ensureOcSession(e,i);if(i?.throwIfAborted(),this.stopped||t&&this.activeRun!==t)return;this.activeRun&&(this.activeRun.ocSessionId=n,this.activeRun.cwd=o);const r=this.resolveModelId(e),d=r.indexOf("/"),c=d>0&&d<r.length-1?{providerID:r.slice(0,d),modelID:r.slice(d+1)}:void 0,l=this.identity.formatBlock();l&&a.info("opencode-adapter",`Injected agent identity via prompt.system session=${e}`),await this.transport.sendPromptAsync(n,{parts:[{type:"text",text:s}],...c?{model:c}:{},...l?{system:l}:{}},o,...i?[{signal:i,runId:t.eventId}]:[])}handleSseEvent(e){if(this.stopped)return;const s=e,t=e.nativeEvent,i=s.sessionID??s.info?.sessionID??s.part?.sessionID??t?.data?.sessionID??t?.data?.form?.sessionID;if(!(e.runId&&e.runId!==this.activeRun?.eventId)&&!(t&&i&&this.activeRun?.controller&&e.runId!==this.activeRun.eventId)&&!(i&&this.activeRun?.ocSessionId&&i!==this.activeRun.ocSessionId)&&!(t&&i&&!this.activeRun&&![...this.sessions.values()].some(o=>o.ocSessionId===i))){if(this.updateToolInFlight(e),e.type!=="server.heartbeat"&&(this.lastSseAt=Date.now(),this.resetIdleTimer()),this.activeRun){const o=this.auditCaptures.get(this.activeRun.eventId);o&&o.push({sequence:o.length,observedAt:new Date().toISOString(),event:structuredClone(e)})}switch(e.type){case"message.part.updated":{if(!this.activeRun)break;const o=e.part,n=e.delta;if(o.type==="text"){const r=n!==void 0?n:o.text;r&&this.acceptAssistantPartText(o.messageID,"text",r)}else o.type==="reasoning"?n&&this.acceptAssistantPartText(o.messageID,"reasoning",n):o.type==="tool"&&this.handleToolPartUpdate(o,n);break}case"message.updated":{if(!this.activeRun)break;const o=e.info;if(this.rememberMessageRole(o),o.role==="assistant"){const n=o;typeof n.tokens?.input=="number"&&this.contextTokensBySession.set(this.activeRun.sessionId,n.tokens.input);const r=this.buildContextWindowMeta(this.activeRun.sessionId,n.providerID,n.modelID,n.tokens?.input);this.callbacks.sendUpdateBindingCard(this.activeRun.sessionId,"composing",this.activeRun.cwd,{...this.buildToolbarMeta(this.activeRun.sessionId),model_provider:n.providerID,model_id:n.modelID,...r??{}}),n.error&&a.warn("opencode-adapter",`Message error: ${JSON.stringify(n.error)}`);const d=this.activeRun.ocSessionId;d&&n.sessionID===d&&(n.error?(this.flushTextBuffer(),this.finishRun("failed",P(n.error,n.error.type||"unknown error"))):!e.nativeEvent&&n.time?.completed&&n.finish!=="tool-calls"&&(this.flushTextBuffer(),this.finishRun("responded")))}break}case"session.canceled":{this.activeRun&&e.sessionID===this.activeRun.ocSessionId&&(this.flushTextBuffer(),this.finishRun("canceled","OpenCode execution interrupted"));break}case"question.unsupported":{this.transport.rejectQuestion(e.id).catch(()=>{}),this.activeRun&&this.onInteractionFailure(new Error("OpenCode form uses unsupported external, hidden or conditional fields"),this.activeRun.eventId);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 o=P(e.error);a.error("opencode-adapter",`Session error: ${o}`),this.flushTextBuffer(),this.finishRun("failed",o);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":{const o=this.pendingPermissions.get(e.requestID);o&&(clearTimeout(o.timer),this.pendingPermissions.delete(e.requestID),this.resetIdleTimer());break}case"question.replied":case"question.rejected":{const o=this.pendingQuestions.get(e.requestID);o&&(clearTimeout(o.timer),this.pendingQuestions.delete(e.requestID),this.resetIdleTimer());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":{a.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:a.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 o=this.messageRoles.get(i);if(o==="user")return;if(o==="assistant"){this.emitAssistantPartChunk(s,t);return}const n=this.pendingPartChunks.get(i)??[];n.push({kind:s,value:t}),this.pendingPartChunks.set(i,n)}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,ee(s??{})))}onPermissionTimeout(e){const s=this.pendingPermissions.get(e);s&&(this.pendingPermissions.delete(e),a.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=this.pendingPermissions.get(e);s&&clearTimeout(s.timer);const t=setTimeout(()=>this.onPermissionTimeout(e),_);this.pendingPermissions.set(e,{permissionId:e,eventId:this.activeRun.eventId,ocSessionId:this.activeRun.ocSessionId,cwd:this.activeRun.cwd,timer:t})}handlePermissionAsked(e){if(!this.activeRun){this.transport.respondPermission(e.sessionID,e.id,"reject").catch(n=>{a.warn("opencode-adapter",`Orphan permission reject failed: ${n}`)});return}const{eventId:s,sessionId:t,ocSessionId:i}=this.activeRun;if(this.resolveModeId(t)===v.fullAuto){this.transport.respondPermission(i,e.id,"always",this.activeRun.cwd).catch(n=>{a.warn("opencode-adapter",`Auto-approve failed: ${n}`),this.onInteractionFailure(n,s)});return}this.trackPendingPermission(e.id);const o=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:o,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)===v.fullAuto){this.transport.respondPermission(i,e.id,"always",this.activeRun.cwd).catch(o=>{a.warn("opencode-adapter",`Auto-approve failed: ${o}`),this.onInteractionFailure(o,s)});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 o=JSON.stringify(e.metadata??{});this.callbacks.sendToolUse(s,t,e.type,o)}}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 r of this.pendingPermissions.values())if(r.eventId===this.activeRun.eventId){i=r;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 o=e.action_type==="exec_approve"||e.action_type==="permission_approve",n=o?"once":"reject";return clearTimeout(i.timer),this.pendingPermissions.delete(i.permissionId),this.transport.respondPermission(i.ocSessionId,i.permissionId,n,i.cwd).then(()=>{a.info("opencode-adapter",`Permission ${n}: ${i.permissionId}`),this.activeRun?.eventId===i.eventId&&this.resetIdleTimer()}).catch(r=>{a.warn("opencode-adapter",`Permission response failed: ${r}`),this.onInteractionFailure(r,i.eventId)}),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:i.permissionId,decision:o?"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 o of this.pendingPermissions.values())if(o.eventId===this.activeRun.eventId){t=o;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(()=>{a.info("opencode-adapter",`Permission ${i} (text event): ${t.permissionId}`),this.activeRun?.eventId===t.eventId&&this.resetIdleTimer()}).catch(o=>{a.warn("opencode-adapter",`Permission response failed: ${o}`),this.onInteractionFailure(o,t.eventId)}),{delivered:!0}}onQuestionTimeout(e){const s=this.pendingQuestions.get(e);s&&(this.pendingQuestions.delete(e),a.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=>{a.warn("opencode-adapter",`Orphan question reject failed: ${n}`)});return}const{eventId:s,sessionId:t}=this.activeRun;this.stopIdleTimer();const i=this.pendingQuestions.get(e.id);i&&clearTimeout(i.timer);const o=setTimeout(()=>this.onQuestionTimeout(e.id),_);if(this.pendingQuestions.set(e.id,{requestId:e.id,eventId:s,cwd:this.activeRun.cwd,questions:e.questions,timer:o}),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(r=>r.label)}:{},...n.multiple!==void 0?{multi_select:n.multiple}:{},...n.custom?{allow_free_text:!0}:{}})),expires_at:Date.now()+_});else{const n=e.questions.map(r=>r.question).join(`
|
|
2
|
-
`);this.callbacks.sendRunError(s,t,`Agent asks: ${
|
|
1
|
+
import{EventEmitter as E}from"node:events";import{stat as N,mkdtemp as L,rm as j}from"node:fs/promises";import{join as R,resolve as Q}from"node:path";import{tmpdir as U}from"node:os";import{randomBytes as q}from"node:crypto";import{fileURLToPath as H}from"node:url";import{spawnCommand as V,killProcessGroup as S,hasChildProcesses as W}from"../../core/runtime/spawn.js";import{resolveOpencodeCommandPath as G}from"./resolve-command.js";import{InternalApiServer as J}from"../../core/mcp/internal-api-server.js";import{resolveMcpServerName as z}from"../../core/mcp/server-name.js";import{InboundMessageIdInjector as X}from"../shared/inbound-message-id-injector.js";import{IdentityInjector as Y}from"../shared/identity-injector.js";import{syncDefaultSkillsToDir as K}from"../../default-skills/index.js";import{buildSimpleProbeReport as Z}from"../shared/probe-util.js";import{compactToolInputForWire as ee}from"../shared/tool-wire-payload.js";import{collapseHostedOpenCodeModels as te,normalizeOCProviderModels as se,preferredHostedOpenCodeProvider as ie}from"./opencode-types.js";import{buildOpencodeConfigContent as ne}from"./opencode-config.js";import{agentIdOf as oe}from"../shared/native-provider-config.js";import{formatOpenCodeErrorMessage as P}from"./format-error.js";import{OpenCodeTransport as re,OpenCodeHttpError as T}from"./opencode-transport.js";import{log as a}from"../../core/log/index.js";import{splitTextForAibotProtocol as x}from"../../core/protocol/index.js";class ae extends E{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitError(e){if(this.listenerCount("error")===0){a.warn("opencode-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}const de=200,ce=2e3,le=12e4,he=90*1e3,M=1800*1e3,O=3e4,k=600*1e3,pe="claude_interaction_reply",ue="set_mode",fe="set_model",me="127.0.0.1",ve=0,ge=1e3,v={fullAuto:"full_auto",approval:"approval"},$=[{id:v.fullAuto,displayName:"Full Auto"},{id:v.approval,displayName:"Approval"}],Ie=[{permission:"*",pattern:"*",action:"allow"}],we=[{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 _(g){const e=String(g??"").trim().toLowerCase();if(e==="full_auto"||e==="fullauto")return v.fullAuto;if(e==="approval"||e==="ask"||e==="autoedit"||e==="auto_edit")return v.approval}function D(g){try{return process.kill(g,0),!0}catch(e){return e.code==="EPERM"}}class Ue extends E{type="opencode";config;callbacks;options;identity;inboundMessageIds=new X;process=null;transport=new re;alive=!1;stopped=!1;internalApi=null;sessions=new Map;sessionModes=new Map;sessionModels=new Map;availableModels=[];modelContextLimits=new Map;contextTokensBySession=new Map;activeRun=null;runBarrier=Promise.resolve();cancellationFailure=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 Y("opencode-adapter",s.getAgentProfile)}onAgentProfileChanged(){this.identity.onProfileChanged()}serverPassword="";privateConfigDir=null;childConfig={};startupCancel=null;stopTask=null;async start(){this.stopTask&&await this.stopTask,this.stopped=!1,this.cancellationFailure=null,this.runBarrier=Promise.resolve();try{if(await this.startInternalApiAndInjectMcp(),this.stopped)throw new Error("OpenCode startup canceled");const e=this.options.hostname??me,s=this.options.port??ve,t=await this.spawnAndWait(e,s);if(this.stopped)throw new Error("OpenCode startup canceled");const i=this.resolveCwd();this.transport.on("event",o=>this.handleSseEvent(o)),this.transport.on("stream-lost",()=>{this.activeRun&&(this.flushTextBuffer(),this.finishRun("failed","OpenCode event stream interrupted; output may be incomplete"))}),this.transport.on("admission-uncertain",()=>{this.alive=!1,this.activeRun&&this.finishRun("failed","OpenCode prompt admission could not be confirmed; server retired"),this.stop(),this.emit("exit",-1)}),this.transport.on("stream-unavailable",()=>{this.alive=!1,this.stopped||this.emit("exit",-1)}),await this.transport.connect(t,i,{username:"opencode",password:this.serverPassword});const n=this.getMcpConfig();await this.transport.configureMcp(n.name,[n.command,...n.args??[]]);try{await this.refreshModels()}catch(o){a.warn("opencode-adapter",`Failed to fetch providers for toolbar models: ${o instanceof Error?o.message:String(o)}`)}if(this.stopped||!this.transport.isConnected)throw new Error("OpenCode startup canceled or disconnected");this.alive=!0,a.info("opencode-adapter",`Ready (pid=${this.process?.pid}, protocol=${this.transport.protocol})`)}catch(e){throw await this.stop(),e}}async refreshModels(e){const s=await this.transport.listProviders(e),t=[],i=new Map;for(const r of s)for(const d of se(r.models)){t.push({id:`${r.id}/${d.id}`,displayName:d.name||d.id});const c=d.limit?.context;typeof c=="number"&&c>0&&i.set(`${r.id}/${d.id}`,c)}const n=te(t,ie(this.options.model)),o=new Set(n.map(r=>r.id));for(const r of i.keys())o.has(r)||i.delete(r);n.sort((r,d)=>{const c=r.displayName.toLowerCase().localeCompare(d.displayName.toLowerCase());return c!==0?c:r.id.localeCompare(d.id)}),this.availableModels=n,this.modelContextLimits=i,a.info("opencode-adapter",`Fetched ${n.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}}}stop(){if(this.stopTask)return this.stopTask;const e=this.stopInternal();return this.stopTask=e,e.then(()=>{this.stopTask=null},()=>{this.stopTask=null}),e}async stopInternal(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.clearRun(),this.startupCancel?.(),this.startupCancel=null,this.transport.disconnect(),await this.runBarrier.catch(()=>{}),this.serverPassword="",this.childConfig={},this.process){const e=this.process;this.process=null,await new Promise(s=>{if(e.exitCode!==null||e.signalCode!==null){try{S(e,"SIGKILL")}catch{}s();return}const t=()=>{clearTimeout(i),e.removeListener("exit",t);try{S(e,"SIGKILL")}catch{}s()},i=setTimeout(t,5e3);e.once("exit",t);try{S(e,"SIGTERM")}catch{t()}})}this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.privateConfigDir&&(await j(this.privateConfigDir,{recursive:!0,force:!0}),this.privateConfigDir=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}),a.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(i){if(!(i instanceof T)||i.status!==404||i.method!=="GET")throw i;a.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 ae(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){const s=this.activeRun;!s||s.sessionId!==e||(this.deliverStopEvent(s.eventId),await s.cancelTask)}deliverInboundEvent(e){const{event_id:s,session_id:t,content:i}=e;if(this.completedEvents.has(s)){a.info("opencode-adapter",`Dropping duplicate event ${s}`),this.callbacks.sendEventAck(s,t),this.callbacks.sendEventResult(s,"responded");return}if(!this.alive){a.warn("opencode-adapter",`Dropping event ${s}: process not alive`),this.callbacks.sendEventAck(s,t),this.callbacks.sendEventResult(s,"failed","Agent process not running");return}if(this.activeRun)if(this.activeRun.eventId!==s)a.info("opencode-adapter",`steer: ${this.activeRun.eventId} -> ${s}`),this.flushTextBuffer(),this.finishRun("canceled","steered to new event");else{this.callbacks.sendEventAck(s,t);return}a.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),o=this.activeRun,r=this.runBarrier.then(async()=>{if(o.controller.signal.throwIfAborted(),this.cancellationFailure)throw this.cancellationFailure;await this.sendOcPrompt(t,n,o)});o.promptTask=r,this.runBarrier=r.catch(()=>{}),r.catch(d=>{this.activeRun===o&&(a.error("opencode-adapter",`prompt_async failed: ${d}`),this.finishRun("failed",String(d)))})}deliverStopEvent(e,s){this.activeRun&&this.activeRun.eventId===e&&(a.info("opencode-adapter",`stop: event=${e}`),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.cancelRun(this.activeRun),this.snapshotAuditBoundary(this.activeRun)),this.activeRun=null}getMcpConfig(){if(!this.internalApi)return null;const e=Q(H(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:z(this.callbacks.getAgentId?.()),command:process.execPath,args:[e,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const e=this.process?.pid;return e?W(e,[e]):!1}async probe(e){const s=this.getStatus();return Z(this.config.command||"opencode",{alive:s.alive,busy:s.busy,started:!!this.process},e)}async startInternalApiAndInjectMcp(){if(this.internalApi=new J,this.internalApi.setInvokeHandler(async(t,i,n,o)=>this.callbacks.agentInvoke(t,i,o)),await this.internalApi.start(0),this.stopped)throw new Error("OpenCode startup canceled");if(this.privateConfigDir=await L(R(U(),"grix-opencode-")),this.stopped)throw new Error("OpenCode startup canceled");const e=R(this.privateConfigDir,"skills");K(e);const s=this.getMcpConfig();this.childConfig={mcp:{[s.name]:{type:"local",command:[s.command,...s.args??[]],enabled:!0}},skills:{paths:[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===ue)return this.handleSetModeAction(e);if(s===fe)return this.handleSetModelAction(e);if(s===pe){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(a.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){a.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=_(this.options.permissionPolicy);if(s)return s;if(e){const t=_(this.options.bindingStore?.get(e)?.modeId);if(t)return t}return v.fullAuto}buildModeToolbarMeta(e){const s=this.resolveModeId(e);return{mode_id:s,currentModeId:s,available_modes:$.map(t=>({...t}))}}async applySessionPermission(e,s,t,i){i?.throwIfAborted();const n=this.resolveModeId(e),o=n===v.fullAuto?Ie:we;try{await this.transport.updateSessionPermission(s,o,t,...i?[i]:[]),i?.throwIfAborted(),a.info("opencode-adapter",`Applied session permission ruleset (${n}) to ${s}`)}catch(r){if(i?.throwIfAborted(),this.transport.protocol==="v2")throw r;a.warn("opencode-adapter",`Failed to apply session permission ruleset: ${r instanceof Error?r.message:String(r)}`)}}async handleSetModeAction(e){const s=e.params??{},t=String(s.session_id??this.options.aibotSessionId??"").trim(),i=_(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"};const n=this.sessionModes.get(t);this.sessionModes.set(t,i);const o=this.sessions.get(t);if(o?.ocSessionId)try{await this.applySessionPermission(t,o.ocSessionId,o.cwd)}catch(d){throw n?this.sessionModes.set(t,n):this.sessionModes.delete(t),d}const r=o?.cwd??this.getSessionCwd(t);return this.callbacks.sendUpdateBindingCard(t,"ready",r,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:$.map(d=>({...d}))}),{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 N(t)).isDirectory())throw new Error(`Bound path is not a directory: ${t}`)}catch(o){throw String(o?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${t}. Please rebind with /grix open <valid-directory>.`):o}if(this.stopped)throw new Error("OpenCode startup canceled");const i=this.config.command||"opencode",n=await G(i,typeof this.config.env?.PATH=="string"?this.config.env.PATH:process.env.PATH);return new Promise((o,r)=>{const c=[...this.config.args??["serve"],`--hostname=${e}`,`--port=${s}`],l={...process.env,...this.config.env},p=ne({model:this.options.model,permissionPolicy:this.options.permissionPolicy,provider:this.options.provider}),u=(oe(i)||"opencode").toUpperCase().replace(/[^A-Z0-9_]/g,"_")||"OPENCODE";let h={};if(l[`${u}_CONFIG_CONTENT`])try{if(h=JSON.parse(l[`${u}_CONFIG_CONTENT`]),!h||typeof h!="object"||Array.isArray(h))throw new Error}catch{r(new Error("OpenCode child CONFIG_CONTENT must be a JSON object"));return}const F=Array.isArray(h.skills)?h.skills:Array.isArray(h.skills?.paths)?h.skills.paths:[],C={...h,...p,...this.childConfig,...this.childConfig.mcp?{mcp:{...h.mcp,...this.childConfig.mcp}}:{},...this.privateConfigDir?{skills:{...Array.isArray(h.skills)?{}:h.skills,paths:[...F,R(this.privateConfigDir,"skills")]}}:{}};Object.keys(C).length&&(l[`${u}_CONFIG_CONTENT`]=JSON.stringify(C)),this.serverPassword=q(32).toString("base64url"),l.OPENCODE_PASSWORD=this.serverPassword,l.OPENCODE_SERVER_PASSWORD=this.serverPassword,l.OPENCODE_SERVER_USERNAME="opencode";const A=u;l[`${A}_SERVER_PASSWORD`]=this.serverPassword,l[`${A}_SERVER_USERNAME`]="opencode",a.info("opencode-adapter",`Spawning OpenCode server (cwd=${t})`),this.process=V(n,c,{env:l,cwd:t}).process;let I="",f=!1;const w=setTimeout(()=>{f||(f=!0,r(new Error(`opencode serve did not start after ${O/1e3}s`)))},O);this.startupCancel=()=>{clearTimeout(w),f||(f=!0,r(new Error("OpenCode startup canceled")))},this.process.stdout?.on("data",m=>{if(f)return;I=(I+m.toString()).slice(-8192);const y=I.split(/\r?\n/);I=y.pop()??"";for(const B of y){const b=B.match(/\bserver listening on (https?:\/\/\S+)/);if(b){clearTimeout(w),f=!0,this.startupCancel=null,o(b[1]);return}}}),this.process.stderr?.on("data",()=>{}),this.process.on("error",m=>{a.error("opencode-adapter",`Spawn error: ${m.message}`),clearTimeout(w),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Spawn error: ${m.message}`),this.clearRun()),f?this.stopped||this.emit("exit",1):(f=!0,r(m))}),this.process.on("exit",m=>{a.info("opencode-adapter",`Process exited (code=${m})`),clearTimeout(w),this.alive=!1,this.transport.disconnect(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Process exited (code=${m})`),this.clearRun()),f?this.stopped||this.emit("exit",m??1):(f=!0,r(new Error(`opencode serve exited with code ${m}`)))})})}async ensureOcSession(e,s){s?.throwIfAborted();const t=this.sessions.get(e),i=this.getSessionCwd(e);if(await this.transport.useDirectory(i,...s?[s]:[]),s?.throwIfAborted(),t?.ocSessionId)try{return await this.transport.getSession(t.ocSessionId,i,...s?[s]:[]),s?.throwIfAborted(),t.ocSessionId}catch(r){if(!(r instanceof T)||r.status!==404||r.method!=="GET")throw r;a.warn("opencode-adapter",`OC session ${t.ocSessionId} gone, creating new`),t.ocSessionId=""}const n=this.options.bindingStore?.getAcpSessionId(e);if(n)try{return await this.transport.getSession(n,i,...s?[s]:[]),s?.throwIfAborted(),this.sessions.set(e,{ocSessionId:n,cwd:i}),a.info("opencode-adapter",`Resumed OC session ${n} for aibot=${e}`),await this.applySessionPermission(e,n,i,s),n}catch(r){if(!(r instanceof T)||r.status!==404||r.method!=="GET")throw r;a.warn("opencode-adapter",`Persisted OC session ${n} gone, creating new`)}const o=await this.transport.createSession({title:`grix-${e.slice(-8)}`},i,...s?[s]:[]);return s?.throwIfAborted(),this.sessions.set(e,{ocSessionId:o.id,cwd:i}),this.options.bindingStore?.setAcpSessionId(e,o.id),a.info("opencode-adapter",`Created OC session ${o.id} for aibot=${e}`),await this.applySessionPermission(e,o.id,i,s),o.id}async sendOcPrompt(e,s,t=this.activeRun){const i=t?.controller?.signal;i?.throwIfAborted();const n=this.getSessionCwd(e),o=await this.ensureOcSession(e,i);if(i?.throwIfAborted(),this.stopped||t&&this.activeRun!==t)return;this.activeRun&&(this.activeRun.ocSessionId=o,this.activeRun.cwd=n);const r=this.resolveModelId(e),d=r.indexOf("/"),c=d>0&&d<r.length-1?{providerID:r.slice(0,d),modelID:r.slice(d+1)}:void 0,l=this.identity.formatBlock();l&&a.info("opencode-adapter",`Injected agent identity via prompt.system session=${e}`),await this.transport.sendPromptAsync(o,{parts:[{type:"text",text:s}],...c?{model:c}:{},...l?{system:l}:{}},n,...i?[{signal:i,runId:t.eventId}]:[])}handleSseEvent(e){if(this.stopped)return;const s=e,t=e.nativeEvent,i=s.sessionID??s.info?.sessionID??s.part?.sessionID??t?.data?.sessionID??t?.data?.form?.sessionID;if(!(e.runId&&e.runId!==this.activeRun?.eventId)&&!(t&&i&&this.activeRun?.controller&&e.runId!==this.activeRun.eventId)&&!(i&&this.activeRun?.ocSessionId&&i!==this.activeRun.ocSessionId)&&!(t&&i&&!this.activeRun&&![...this.sessions.values()].some(n=>n.ocSessionId===i))){if(this.updateToolInFlight(e),e.type!=="server.heartbeat"&&(this.lastSseAt=Date.now(),this.resetIdleTimer()),this.activeRun){const n=this.auditCaptures.get(this.activeRun.eventId);n&&n.push({sequence:n.length,observedAt:new Date().toISOString(),event:structuredClone(e)})}switch(e.type){case"message.part.updated":{if(!this.activeRun)break;const n=e.part,o=e.delta;if(n.type==="text"){const r=o!==void 0?o:n.text;r&&this.acceptAssistantPartText(n.messageID,"text",r)}else n.type==="reasoning"?o&&this.acceptAssistantPartText(n.messageID,"reasoning",o):n.type==="tool"&&this.handleToolPartUpdate(n,o);break}case"message.updated":{if(!this.activeRun)break;const n=e.info;if(this.rememberMessageRole(n),n.role==="assistant"){const o=n;typeof o.tokens?.input=="number"&&this.contextTokensBySession.set(this.activeRun.sessionId,o.tokens.input);const r=this.buildContextWindowMeta(this.activeRun.sessionId,o.providerID,o.modelID,o.tokens?.input);this.callbacks.sendUpdateBindingCard(this.activeRun.sessionId,"composing",this.activeRun.cwd,{...this.buildToolbarMeta(this.activeRun.sessionId),model_provider:o.providerID,model_id:o.modelID,...r??{}}),o.error&&a.warn("opencode-adapter",`Message error: ${JSON.stringify(o.error)}`);const d=this.activeRun.ocSessionId;d&&o.sessionID===d&&(o.error?(this.flushTextBuffer(),this.finishRun("failed",P(o.error,o.error.type||"unknown error"))):!e.nativeEvent&&o.time?.completed&&o.finish!=="tool-calls"&&(this.flushTextBuffer(),this.finishRun("responded")))}break}case"session.canceled":{this.activeRun&&e.sessionID===this.activeRun.ocSessionId&&(this.flushTextBuffer(),this.finishRun("canceled","OpenCode execution interrupted"));break}case"question.unsupported":{this.transport.rejectQuestion(e.id).catch(()=>{}),this.activeRun&&this.onInteractionFailure(new Error("OpenCode form uses unsupported external, hidden or conditional fields"),this.activeRun.eventId);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 n=P(e.error);a.error("opencode-adapter",`Session error: ${n}`),this.flushTextBuffer(),this.finishRun("failed",n);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":{const n=this.pendingPermissions.get(e.requestID);n&&(clearTimeout(n.timer),this.pendingPermissions.delete(e.requestID),this.resetIdleTimer());break}case"question.replied":case"question.rejected":{const n=this.pendingQuestions.get(e.requestID);n&&(clearTimeout(n.timer),this.pendingQuestions.delete(e.requestID),this.resetIdleTimer());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":{a.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:a.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,ee(s??{})))}onPermissionTimeout(e){const s=this.pendingPermissions.get(e);s&&(this.pendingPermissions.delete(e),a.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=this.pendingPermissions.get(e);s&&clearTimeout(s.timer);const t=setTimeout(()=>this.onPermissionTimeout(e),k);this.pendingPermissions.set(e,{permissionId:e,eventId:this.activeRun.eventId,ocSessionId:this.activeRun.ocSessionId,cwd:this.activeRun.cwd,timer:t})}handlePermissionAsked(e){if(!this.activeRun){this.transport.respondPermission(e.sessionID,e.id,"reject").catch(o=>{a.warn("opencode-adapter",`Orphan permission reject failed: ${o}`)});return}const{eventId:s,sessionId:t,ocSessionId:i}=this.activeRun;if(this.resolveModeId(t)===v.fullAuto){this.transport.respondPermission(i,e.id,"always",this.activeRun.cwd).catch(o=>{a.warn("opencode-adapter",`Auto-approve failed: ${o}`),this.onInteractionFailure(o,s)});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)===v.fullAuto){this.transport.respondPermission(i,e.id,"always",this.activeRun.cwd).catch(n=>{a.warn("opencode-adapter",`Auto-approve failed: ${n}`),this.onInteractionFailure(n,s)});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 r of this.pendingPermissions.values())if(r.eventId===this.activeRun.eventId){i=r;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(()=>{a.info("opencode-adapter",`Permission ${o}: ${i.permissionId}`),this.activeRun?.eventId===i.eventId&&this.resetIdleTimer()}).catch(r=>{a.warn("opencode-adapter",`Permission response failed: ${r}`),this.onInteractionFailure(r,i.eventId)}),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(()=>{a.info("opencode-adapter",`Permission ${i} (text event): ${t.permissionId}`),this.activeRun?.eventId===t.eventId&&this.resetIdleTimer()}).catch(n=>{a.warn("opencode-adapter",`Permission response failed: ${n}`),this.onInteractionFailure(n,t.eventId)}),{delivered:!0}}onQuestionTimeout(e){const s=this.pendingQuestions.get(e);s&&(this.pendingQuestions.delete(e),a.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(o=>{a.warn("opencode-adapter",`Orphan question reject failed: ${o}`)});return}const{eventId:s,sessionId:t}=this.activeRun;this.stopIdleTimer();const i=this.pendingQuestions.get(e.id);i&&clearTimeout(i.timer);const n=setTimeout(()=>this.onQuestionTimeout(e.id),k);if(this.pendingQuestions.set(e.id,{requestId:e.id,eventId:s,cwd:this.activeRun.cwd,questions:e.questions,timer:n}),this.callbacks.sendAgentQuestionCard)this.callbacks.sendAgentQuestionCard(s,t,{request_id:e.id,mode:"form",questions:e.questions.map(o=>({header:o.header,prompt:o.question,...o.options.length>0?{options:o.options.map(r=>r.label)}:{},...o.multiple!==void 0?{multi_select:o.multiple}:{},...o.custom?{allow_free_text:!0}:{}})),expires_at:Date.now()+k});else{const o=e.questions.map(r=>r.question).join(`
|
|
2
|
+
`);this.callbacks.sendRunError(s,t,`Agent asks: ${o}`)}}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=(c,l)=>(clearTimeout(t.timer),this.pendingQuestions.delete(t.requestId),c().then(()=>{this.activeRun?.eventId===t.eventId&&this.resetIdleTimer()}).catch(p=>{a.warn("opencode-adapter",`Question response failed: ${p}`),this.onInteractionFailure(p,t.eventId)}),{delivered:!0,result:l});if(n==="action"){const c=String(i.value??"");if(c==="cancel"||c==="decline")return o(()=>this.transport.rejectQuestion(t.requestId,t.cwd),{request_id:s,resolution:"cancel"})}let r=null;if(Array.isArray(e.answers))r=e.answers.map(c=>Array.isArray(c)?c.map(String):[String(c)]);else if(n==="text"){const c=String(i.value??"");c&&(r=t.questions.map((l,p)=>p===0?[c]:[]))}else if(n==="map"){const c=Array.isArray(i.entries)?i.entries:[];r=t.questions.map((l,p)=>{const u=c.find(h=>h.key===l.header||h.key===String(p+1));return u&&u.value?[u.value]:[]}),r.every(l=>l.length===0)&&c.length>0&&(r=t.questions.map((l,p)=>{const u=c[p]?.value;return u?[String(u)]:[]}))}if(!r||r.every(c=>c.length===0))return o(()=>this.transport.rejectQuestion(t.requestId,t.cwd),{request_id:s,resolution:"cancel"});const d=r;return o(()=>this.transport.replyQuestion(t.requestId,d,t.cwd),{request_id:s,resolution:"answer"})}onInteractionFailure(e,s){this.activeRun?.eventId===s&&(this.transport.protocol==="v2"?this.finishRun("failed",e instanceof Error?e.message:"OpenCode interaction failed"):this.resetIdleTimer())}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}cancelRun(e){if(e.controller?.abort(),e.cancelTask||this.stopped)return;const s=(e.promptTask??Promise.resolve()).catch(()=>{}).then(async()=>{!this.stopped&&e.ocSessionId&&await this.transport.abortSession(e.ocSessionId,e.cwd)});e.cancelTask=s,this.runBarrier=s,s.catch(t=>{if(this.stopped)return;this.cancellationFailure=new Error("OpenCode cancellation not confirmed; replace adapter before sending more prompts"),a.warn("opencode-adapter",`OpenCode cancellation not confirmed: ${t}`),this.alive=!1,(this.activeRun?.promptTask??Promise.resolve()).catch(()=>{}).then(()=>this.stop()).then(()=>this.emit("exit",-1)).catch(()=>{})})}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,controller:new AbortController},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(e==="responded"?t.controller?.abort():this.cancelRun(t),this.completedEvents.add(t.eventId),this.completedEvents.size>ge){const d=[...this.completedEvents].slice(-500);this.completedEvents=new Set(d)}this.snapshotAuditBoundary(t),t.flushTimer&&clearTimeout(t.flushTimer),t.flushTimer=null,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 r=()=>{this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t.eventId,t.sessionId,n).then(()=>{this.callbacks.sendEventResult(t.eventId,e,s,void 0,o)}).catch(d=>{const c=e==="responded"?"failed":e,l=e==="responded"?`final output delivery failed: ${d instanceof Error?d.message:String(d)}`:s,p=e==="responded"?!1:o;this.callbacks.sendEventResult(t.eventId,c,l,void 0,p)}):(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 d of x(t.textBuffer))t.chunkSeq++,this.callbacks.sendStreamChunk(t.eventId,t.sessionId,d,t.chunkSeq,!1,t.clientMsgId);t.textBuffer=""}r(),this.emit("eventDone",t.eventId)}clearRun(){this.activeRun&&this.cancelRun(this.activeRun),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>=ce){this.flushTextBuffer();return}this.scheduleTextFlush()}}scheduleTextFlush(){!this.activeRun||this.activeRun.flushTimer||(this.activeRun.flushTimer=setTimeout(()=>{this.activeRun&&(this.activeRun.flushTimer=null),this.flushTextBuffer()},de))}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||!D(e))return!1;const s=Date.now(),t=this.lastSseAt>0?s-this.lastSseAt:Number.POSITIVE_INFINITY;if(t<he)return this.livenessExtendStartAt=s,a.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>M?(a.warn("opencode-adapter",`Liveness extension budget exhausted for ${this.activeRun.eventId} (no progress for ${Math.round((s-n)/6e4)}min), allowing idle fail`),!1):(a.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(){if(this.stopIdleTimer(),this.stopped||!this.activeRun)return;const e=this.activeRun;this.idleTimer=setTimeout(()=>{if(this.stopped||this.activeRun!==e)return;if(this.hasPendingInteractionForRun(this.activeRun.eventId)&&this.shouldExtendByLiveness()){a.info("opencode-adapter",`Idle timeout skipped: pending interaction for ${this.activeRun.eventId}, resetting timer`),this.resetIdleTimer();return}if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const s=this.process?.pid,i=!!(this.alive&&s&&D(s))?`liveness budget exhausted after ${M/6e4}min`:"process not alive";a.error("opencode-adapter",`Idle timeout (${i}, toolsInFlight=${this.toolCallsInFlight.size}) \u2014 emitting exit for respawn`),this.flushTextBuffer(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`idle timeout: ${i}`),this.clearRun()),this.emit("exit",-1)},le)}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(`
|
|
3
3
|
`);s=`${s}
|
|
4
4
|
|
|
5
5
|
[Conversation context]
|
|
6
|
-
${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(
|
|
6
|
+
${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(`
|
|
7
7
|
`);s=`${s}
|
|
8
8
|
|
|
9
9
|
[Conversation context]
|
|
10
|
-
${i}`}}catch{}return this.inboundMessageIds.inject(e.session_id,s,e.msg_id)}}export{
|
|
10
|
+
${i}`}}catch{}return this.inboundMessageIds.inject(e.session_id,s,e.msg_id)}}export{Ue as OpenCodeAdapter};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function
|
|
1
|
+
function u(e){return e?Array.isArray(e)?e:typeof e=="object"?Object.values(e):[]:[]}const p=new Set(["opencode","opencode-go"]);function i(e){const n=e.indexOf("/");return n===-1?e:e.slice(0,n)}function f(e){return i(e?.trim()??"")==="opencode"?"opencode":"opencode-go"}function a(e,n){const c=o=>{const r=i(o);return r===n?0:r==="opencode-go"?1:2},t=new Map,s=[];for(const o of e){if(!p.has(i(o.id))){s.push(o);continue}const r=o.displayName.trim().toLowerCase(),d=t.get(r);(!d||c(o.id)<c(d.id))&&t.set(r,o)}return[...s,...t.values()]}export{a as collapseHostedOpenCodeModels,u as normalizeOCProviderModels,f as preferredHostedOpenCodeProvider,i as providerIdOfModelRef};
|
|
Binary file
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schemaVersion": 1,
|
|
3
|
-
"bridgeVersion": "4.
|
|
4
|
-
"tarball": "grix-dsh-bridge-4.
|
|
5
|
-
"size":
|
|
6
|
-
"unpackedSize":
|
|
7
|
-
"shasum": "
|
|
8
|
-
"integrity": "sha512-
|
|
3
|
+
"bridgeVersion": "4.16.1",
|
|
4
|
+
"tarball": "grix-dsh-bridge-4.16.1.tgz",
|
|
5
|
+
"size": 24211,
|
|
6
|
+
"unpackedSize": 96662,
|
|
7
|
+
"shasum": "fc04db27b9554184f780a3f046814d43ca26b534",
|
|
8
|
+
"integrity": "sha512-8FoG6eL5UPFo8RMhQD7sDDB3/DmswSWfpuBPeWZ3sxTiTSPKa9f69+ND6Vtnstx7qAVYZ33/uC9MnxcdEoCXvw=="
|
|
9
9
|
}
|