grix-connector 4.15.0 → 4.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/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/claude/claude-bridge-server.js +1 -1
- package/dist/adapter/claude/claude-tools.js +1 -1
- package/dist/adapter/claude/claude-worker-client.js +1 -1
- package/dist/adapter/claude/mcp-http-launcher.js +2 -2
- package/dist/adapter/claude/result-timeout.js +1 -1
- package/dist/adapter/cursor/context-window.js +1 -1
- package/dist/adapter/cursor/cursor-adapter.js +9 -9
- 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 +1 -1
- package/dist/adapter/deepseek-harness/profile-package-shadow.js +1 -0
- 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 +3 -5
- package/dist/adapter/opencode/opencode-transport.js +7 -4
- package/dist/adapter/opencode/opencode-types.js +1 -1
- package/dist/adapter/opencode/opencode-v2-events.js +2 -0
- package/dist/adapter/opencode/resolve-command.js +1 -0
- package/dist/assets/dsh-bridge/grix-dsh-bridge-4.16.0.tgz +0 -0
- package/dist/assets/dsh-bridge/manifest.json +6 -6
- package/dist/audit/adapters/opencode/opencode-audit-adapter.js +1 -1
- package/dist/bridge/provider-quota.js +1 -1
- package/dist/core/access/allowlist-store.js +1 -1
- package/dist/core/file-ops/list-files.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/log.js +2 -2
- package/dist/manager.js +1 -1
- package/dist/mcp/stream-http/config.js +1 -1
- package/dist/mcp/stream-http/connection-binding.js +1 -1
- package/dist/mcp/stream-http/tool-executor.js +1 -1
- package/dist/mcp/stream-http/tool-registry.js +1 -1
- package/dist/mcp/stream-http/tool-schemas.js +1 -1
- package/dist/protocol/acp-client.js +1 -1
- package/openclaw-plugin/audit-recorder-worker.js +2 -2
- package/package.json +1 -1
- package/dist/assets/dsh-bridge/grix-dsh-bridge-4.15.0.tgz +0 -0
|
@@ -1,7 +1,5 @@
|
|
|
1
|
-
import{EventEmitter as y}from"node:events";import{stat as M}from"node:fs/promises";import{existsSync as $,mkdirSync as O,readFileSync as F,writeFileSync as B}from"node:fs";import{join as S,resolve as D,dirname as L}from"node:path";import{homedir as N}from"node:os";import{fileURLToPath as j}from"node:url";import{resolveCommandPath as Q,spawnCommand as U,killProcessGroup as T,hasChildProcesses as q}from"../../core/runtime/spawn.js";import{InternalApiServer as H}from"../../core/mcp/internal-api-server.js";import{resolveMcpServerName as J,pruneLegacyMcpServerEntries as V}from"../../core/mcp/server-name.js";import{InboundMessageIdInjector as W}from"../shared/inbound-message-id-injector.js";import{IdentityInjector as z}from"../shared/identity-injector.js";import{syncDefaultSkillsToDir as G}from"../../default-skills/index.js";import{buildSimpleProbeReport as X}from"../shared/probe-util.js";import{compactToolInputForWire as Y}from"../shared/tool-wire-payload.js";import{normalizeOCProviderModels as K}from"./opencode-types.js";import{buildOpencodeConfigContent as Z}from"./opencode-config.js";import{agentIdOf as k}from"../shared/native-provider-config.js";import{formatOpenCodeErrorMessage as A}from"./format-error.js";import{OpenCodeTransport as ee}from"./opencode-transport.js";import{log as r}from"../../core/log/index.js";import{splitTextForAibotProtocol as x}from"../../core/protocol/index.js";class te extends y{adapterSessionId;constructor(e){super(),this.adapterSessionId=e}emitError(e){if(this.listenerCount("error")===0){r.warn("opencode-adapter",`Prompt handle error (no listeners): ${e.message}`);return}this.emit("error",e)}async cancel(){}}const se=200,ie=2e3,ne=12e4,oe=90*1e3,b=1800*1e3,P=3e4,R=600*1e3,re="claude_interaction_reply",ae="set_mode",de="set_model",ce="127.0.0.1",le=0,he=1e3,m={fullAuto:"full_auto",approval:"approval"},C=[{id:m.fullAuto,displayName:"Full Auto"},{id:m.approval,displayName:"Approval"}],pe=[{permission:"*",pattern:"*",action:"allow"}],ue=[{permission:"doom_loop",pattern:"*",action:"ask"},{permission:"external_directory",pattern:"*",action:"ask"},{permission:"question",pattern:"*",action:"deny"},{permission:"plan_enter",pattern:"*",action:"deny"},{permission:"plan_exit",pattern:"*",action:"deny"},{permission:"repo_clone",pattern:"*",action:"deny"},{permission:"repo_overview",pattern:"*",action:"deny"},{permission:"read",pattern:"*.env",action:"ask"},{permission:"read",pattern:"*.env.*",action:"ask"},{permission:"read",pattern:"*.env.example",action:"allow"}];function w(g){const e=String(g??"").trim().toLowerCase();if(e==="full_auto"||e==="fullauto")return m.fullAuto;if(e==="approval"||e==="ask"||e==="autoedit"||e==="auto_edit")return m.approval}function E(g){try{return process.kill(g,0),!0}catch(e){return e.code==="EPERM"}}class Fe extends y{type="opencode";config;callbacks;options;identity;inboundMessageIds=new W;process=null;transport=new ee;alive=!1;stopped=!1;internalApi=null;sessions=new Map;sessionModes=new Map;sessionModels=new Map;availableModels=[];modelContextLimits=new Map;contextTokensBySession=new Map;activeRun=null;completedEvents=new Set;clientMsgSeq=0;auditCaptures=new Map;completedAuditBoundaries=new Map;idleTimer=null;lastSseAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;toolCardsSent=new Set;messageRoles=new Map;pendingPartChunks=new Map;pendingPermissions=new Map;pendingQuestions=new Map;permissionHandler=null;constructor(e,s,t){super(),this.config=e,this.callbacks=s,this.options=t??{},this.identity=new z("opencode-adapter",s.getAgentProfile)}onAgentProfileChanged(){this.identity.onProfileChanged()}async start(){await this.startInternalApiAndInjectMcp();const e=this.options.hostname??ce,s=this.options.port??le,t=await this.spawnAndWait(e,s),i=this.resolveCwd();await this.transport.connect(t,i),this.transport.on("event",n=>this.handleSseEvent(n));try{await this.refreshModels()}catch(n){r.warn("opencode-adapter",`Failed to fetch providers for toolbar models: ${n instanceof Error?n.message:String(n)}`)}r.info("opencode-adapter",`Ready (pid=${this.process?.pid}, url=${t})`)}async refreshModels(e){const s=await this.transport.listProviders(e),t=[],i=new Map;for(const n of s)for(const o of K(n.models)){t.push({id:`${n.id}/${o.id}`,displayName:o.name||o.id});const a=o.limit?.context;typeof a=="number"&&a>0&&i.set(`${n.id}/${o.id}`,a)}t.sort((n,o)=>{const a=n.displayName.toLowerCase().localeCompare(o.displayName.toLowerCase());return a!==0?a:n.id.localeCompare(o.id)}),this.availableModels=t,this.modelContextLimits=i,r.info("opencode-adapter",`Fetched ${t.length} models from ${s.length} providers (directory=${e??"current"})`)}resolveContextLimit(e,s){const t=this.modelContextLimits.get(`${e}/${s}`);if(t)return t;let i;for(const[n,o]of this.modelContextLimits)n.startsWith(`${e}/`)&&(i=i===void 0?o:Math.max(i,o));return i}buildContextWindowMeta(e,s,t,i){if(!i||i<=0)return;const n=this.resolveContextLimit(s,t);if(!n)return;const o=Math.min(100,i/n*100);return{context_window:{used:i,size:n,usedPercentage:o,remainingPercentage:100-o}}}async stop(){if(this.stopped=!0,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.transport.disconnect(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.process){const e=this.process;try{T(e,"SIGTERM")}catch{}const s=setTimeout(()=>{try{T(e,"SIGKILL")}catch{}},5e3);e.on("exit",()=>clearTimeout(s)),this.process=null}}isAlive(){return this.alive}async createSession(e){const s=e.cwd??this.resolveCwd();await this.transport.useDirectory(s);const t=await this.transport.createSession({title:`grix-${Date.now()}`},s);return this.sessions.set(t.id,{ocSessionId:t.id,cwd:s}),r.info("opencode-adapter",`Created OC session ${t.id} for cwd=${s}`),await this.applySessionPermission(t.id,t.id,s),t.id}async resumeSession(e,s){const t=this.sessions.get(e);if(t?.ocSessionId)try{await this.transport.useDirectory(t.cwd),await this.transport.getSession(t.ocSessionId,t.cwd),await this.applySessionPermission(e,t.ocSessionId,t.cwd)}catch{r.warn("opencode-adapter",`OC session ${t.ocSessionId} gone, will create new on next prompt`),t.ocSessionId=""}}async destroySession(e){const s=this.sessions.get(e),t=s?s.ocSessionId:e;if(t)try{await this.transport.deleteSession(t,s?.cwd)}catch{}this.sessions.delete(e),this.contextTokensBySession.delete(e),this.identity.forgetSession(e),this.inboundMessageIds.forgetSession(e)}sendPrompt(e){const s=new te(e.adapterSessionId);return this.sendOcPrompt(e.adapterSessionId,this.buildPromptText(e)).catch(t=>{s.emitError(t instanceof Error?t:new Error(String(t)))}),s}async cancel(e){if(this.activeRun)try{await this.transport.abortSession(this.activeRun.ocSessionId,this.activeRun.cwd)}catch{}}deliverInboundEvent(e){const{event_id:s,session_id:t,content:i}=e;if(this.completedEvents.has(s)){r.info("opencode-adapter",`Dropping duplicate event ${s}`),this.callbacks.sendEventAck(s,t),this.callbacks.sendEventResult(s,"responded");return}if(!this.alive){r.warn("opencode-adapter",`Dropping event ${s}: process not alive`),this.callbacks.sendEventAck(s,t),this.callbacks.sendEventResult(s,"failed","Agent process not running");return}this.activeRun&&this.activeRun.eventId!==s&&(r.info("opencode-adapter",`steer: ${this.activeRun.eventId} -> ${s}`),this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeRun.eventId,"canceled","steered to new event"),this.clearRun()),r.info("opencode-adapter",`prompt: event=${s} session=${t}`),this.callbacks.sendEventAck(s,t),this.startRun(s,t,e.audit?.enabled===!0),this.startComposing(t),this.resetIdleTimer();const n=this.buildPromptTextFromEvent(e);this.sendOcPrompt(t,n).catch(o=>{r.error("opencode-adapter",`prompt_async failed: ${o}`),this.finishRun("failed",String(o))})}deliverStopEvent(e,s){this.activeRun&&this.activeRun.eventId===e&&(r.info("opencode-adapter",`stop: event=${e}`),this.rejectAllPendingInteractions(),this.transport.abortSession(this.activeRun.ocSessionId,this.activeRun.cwd).catch(()=>{}),this.flushTextBuffer(),this.finishRun("canceled","stopped by user"))}setPermissionHandler(e){this.permissionHandler=e}async ping(e){return this.transport.healthCheck()}getStatus(){return{alive:this.alive,busy:this.activeRun!==null,sessions:this.sessions.size}}getActiveEventIds(){return this.activeRun?[this.activeRun.eventId]:[]}takeAuditBoundary(e){const s=this.completedAuditBoundaries.get(e);return s&&this.completedAuditBoundaries.delete(e),s}clearActiveEventForShutdown(){this.stopIdleTimer(),this.stopTextFlush(),this.rejectAllPendingInteractions(),this.activeRun&&this.snapshotAuditBoundary(this.activeRun),this.activeRun=null}getMcpConfig(){if(!this.internalApi)return null;const e=D(j(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:J(this.callbacks.getAgentId?.()),command:process.execPath,args:[e,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const e=this.process?.pid;return e?q(e,[e]):!1}async probe(e){const s=this.getStatus();return X(this.config.command||"opencode",{alive:s.alive,busy:s.busy,started:!!this.process},e)}async startInternalApiAndInjectMcp(){try{this.internalApi=new H,this.internalApi.setInvokeHandler(async(d,l,h,u)=>this.callbacks.agentInvoke(d,l,u)),await this.internalApi.start(0),r.info("opencode-adapter",`Internal API started at ${this.internalApi.url}`);const e=this.getMcpConfig(),s=k(this.config.command||"opencode")||"opencode",t=process.env.XDG_CONFIG_HOME||S(N(),".config"),i=S(t,s,`${s}.json`);O(L(i),{recursive:!0});let n={};try{$(i)&&(n=JSON.parse(F(i,"utf8")))}catch{}const o=n.mcp&&typeof n.mcp=="object"?n.mcp:{};V(o,this.internalApi.url),o[e.name]={type:"local",command:[e.command,...e.args??[]],enabled:!0},n.mcp=o,B(i,`${JSON.stringify(n,null,2)}
|
|
2
|
-
|
|
3
|
-
`)){const _=v.match(/\bserver listening on (https?:\/\/\S+)/);if(_){clearTimeout(I),f=!0,this.alive=!0,i(_[1]);return}}}),this.process.stderr?.on("data",p=>{const v=p.toString().trim();v&&r.info("opencode-adapter",`[stderr] ${v}`)}),this.process.on("error",p=>{r.error("opencode-adapter",`Spawn error: ${p.message}`),clearTimeout(I),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Spawn error: ${p.message}`),this.clearRun()),f?this.stopped||this.emit("exit",1):(f=!0,n(p))}),this.process.on("exit",p=>{r.info("opencode-adapter",`Process exited (code=${p})`),clearTimeout(I),this.alive=!1,this.transport.disconnect(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`Process exited (code=${p})`),this.clearRun()),f?this.stopped||this.emit("exit",p??1):(f=!0,n(new Error(`opencode serve exited with code ${p}`)))})})}async ensureOcSession(e){const s=this.sessions.get(e),t=this.getSessionCwd(e);if(await this.transport.useDirectory(t),s?.ocSessionId)try{return await this.transport.getSession(s.ocSessionId,t),s.ocSessionId}catch{r.warn("opencode-adapter",`OC session ${s.ocSessionId} gone, creating new`),s.ocSessionId=""}const i=this.options.bindingStore?.getAcpSessionId(e);if(i)try{return await this.transport.getSession(i,t),this.sessions.set(e,{ocSessionId:i,cwd:t}),r.info("opencode-adapter",`Resumed OC session ${i} for aibot=${e}`),await this.applySessionPermission(e,i,t),i}catch{r.warn("opencode-adapter",`Persisted OC session ${i} gone, creating new`)}const n=await this.transport.createSession({title:`grix-${e.slice(-8)}`},t);return this.sessions.set(e,{ocSessionId:n.id,cwd:t}),this.options.bindingStore?.setAcpSessionId(e,n.id),r.info("opencode-adapter",`Created OC session ${n.id} for aibot=${e}`),await this.applySessionPermission(e,n.id,t),n.id}async sendOcPrompt(e,s){const t=this.getSessionCwd(e),i=await this.ensureOcSession(e);this.activeRun&&(this.activeRun.ocSessionId=i,this.activeRun.cwd=t);const n=this.resolveModelId(e),o=n.indexOf("/"),a=o>0&&o<n.length-1?{providerID:n.slice(0,o),modelID:n.slice(o+1)}:void 0,c=this.identity.formatBlock();c&&r.info("opencode-adapter",`Injected agent identity via prompt.system session=${e}`),await this.transport.sendPromptAsync(i,{parts:[{type:"text",text:s}],...a?{model:a}:{},...c?{system:c}:{}},t)}handleSseEvent(e){if(!this.stopped){if(this.updateToolInFlight(e),e.type!=="server.heartbeat"&&(this.lastSseAt=Date.now(),this.resetIdleTimer()),this.activeRun){const s=this.auditCaptures.get(this.activeRun.eventId);s&&s.push({sequence:s.length,observedAt:new Date().toISOString(),event:structuredClone(e)})}switch(e.type){case"message.part.updated":{if(!this.activeRun)break;const s=e.part,t=e.delta;if(s.type==="text"){const i=t||s.text;i&&this.acceptAssistantPartText(s.messageID,"text",i)}else s.type==="reasoning"?t&&this.acceptAssistantPartText(s.messageID,"reasoning",t):s.type==="tool"&&this.handleToolPartUpdate(s,t);break}case"message.updated":{if(!this.activeRun)break;const s=e.info;if(this.rememberMessageRole(s),s.role==="assistant"){const t=s;typeof t.tokens?.input=="number"&&this.contextTokensBySession.set(this.activeRun.sessionId,t.tokens.input);const i=this.buildContextWindowMeta(this.activeRun.sessionId,t.providerID,t.modelID,t.tokens?.input);this.callbacks.sendUpdateBindingCard(this.activeRun.sessionId,"composing",this.activeRun.cwd,{...this.buildToolbarMeta(this.activeRun.sessionId),model_provider:t.providerID,model_id:t.modelID,...i??{}}),t.error&&r.warn("opencode-adapter",`Message error: ${JSON.stringify(t.error)}`);const n=this.activeRun.ocSessionId;n&&t.sessionID===n&&(t.error?(this.flushTextBuffer(),this.finishRun("failed",A(t.error,t.error.type||"unknown error"))):t.time?.completed&&t.finish!=="tool-calls"&&(this.flushTextBuffer(),this.finishRun("responded")))}break}case"session.idle":{if(!this.activeRun)break;e.sessionID===this.activeRun.ocSessionId&&(this.flushTextBuffer(),this.finishRun("responded"));break}case"session.status":{if(!this.activeRun)break;e.sessionID===this.activeRun.ocSessionId&&e.status.type==="idle"&&(this.flushTextBuffer(),this.finishRun("responded"));break}case"session.error":{if(!this.activeRun)break;const s=A(e.error);r.error("opencode-adapter",`Session error: ${s}`),this.flushTextBuffer(),this.finishRun("failed",s);break}case"permission.updated":{this.handlePermission(e.permission);break}case"permission.asked":{this.handlePermissionAsked(e);break}case"question.asked":{this.handleQuestionAsked(e);break}case"permission.replied":case"question.replied":case"question.rejected":r.debug("opencode-adapter",`Interaction settled: ${e.type}`);break;case"session.created":case"session.updated":case"session.deleted":case"session.compacted":case"session.diff":case"file.edited":case"server.connected":case"server.heartbeat":break;case"server.instance.disposed":{r.warn("opencode-adapter",`Server instance disposed: ${e.directory}`),this.alive=!1,this.transport.disconnect(),this.activeRun&&(this.flushTextBuffer(),this.callbacks.sendEventResult(this.activeRun.eventId,"failed","server instance disposed"),this.clearRun()),this.stopped||this.emit("exit",-1);break}default:r.debug("opencode-adapter",`Unhandled SSE event type: ${e.type}`);break}}}updateToolInFlight(e){if(e.type!=="message.part.updated")return;const s=e.part;if(s?.type!=="tool"||!s.callID)return;const t=s.state?.status;t==="pending"||t==="running"?this.toolCallsInFlight.add(s.callID):(t==="completed"||t==="error")&&this.toolCallsInFlight.delete(s.callID)}rememberMessageRole(e){const s=typeof e.id=="string"?e.id.trim():"";s&&(e.role!=="user"&&e.role!=="assistant"||(this.messageRoles.set(s,e.role),this.flushOrDropPendingParts(s,e.role)))}acceptAssistantPartText(e,s,t){if(!this.activeRun||!t)return;const i=typeof e=="string"?e.trim():"";if(!i)return;const n=this.messageRoles.get(i);if(n==="user")return;if(n==="assistant"){this.emitAssistantPartChunk(s,t);return}const o=this.pendingPartChunks.get(i)??[];o.push({kind:s,value:t}),this.pendingPartChunks.set(i,o)}flushOrDropPendingParts(e,s){const t=this.pendingPartChunks.get(e);if(this.pendingPartChunks.delete(e),!(!t||t.length===0)&&s==="assistant")for(const i of t)this.emitAssistantPartChunk(i.kind,i.value)}emitAssistantPartChunk(e,s){if(!(!this.activeRun||!s)){if(e==="reasoning"){this.callbacks.sendThinking(this.activeRun.eventId,this.activeRun.sessionId,s);return}this.appendText(s)}}clearMessageRoleState(){this.messageRoles.clear(),this.pendingPartChunks.clear()}handleToolPartUpdate(e,s){if(!this.activeRun)return;const t=e.state;switch(t.status){case"pending":case"running":{this.sendToolUseOnce(e,t.input);break}case"completed":{this.sendToolUseOnce(e,t.input);break}case"error":{this.sendToolUseOnce(e,t.input),this.callbacks.sendToolResult(this.activeRun.eventId,this.activeRun.sessionId,e.tool,"(failed)");break}}}sendToolUseOnce(e,s){!this.activeRun||this.toolCardsSent.has(e.callID)||(this.flushTextBuffer(),this.toolCardsSent.add(e.callID),this.callbacks.sendToolUse(this.activeRun.eventId,this.activeRun.sessionId,e.tool,Y(s??{})))}onPermissionTimeout(e){const s=this.pendingPermissions.get(e);s&&(this.pendingPermissions.delete(e),r.error("opencode-adapter",`Permission approval timeout: ${e}`),this.transport.respondPermission(s.ocSessionId,e,"reject",s.cwd).catch(()=>{}),this.activeRun&&this.activeRun.eventId===s.eventId&&(this.flushTextBuffer(),this.finishRun("failed","permission approval timeout")))}trackPendingPermission(e){if(!this.activeRun)return;this.stopIdleTimer();const s=setTimeout(()=>this.onPermissionTimeout(e),R);this.pendingPermissions.set(e,{permissionId:e,eventId:this.activeRun.eventId,ocSessionId:this.activeRun.ocSessionId,cwd:this.activeRun.cwd,timer:s})}handlePermissionAsked(e){if(!this.activeRun){this.transport.respondPermission(e.sessionID,e.id,"reject").catch(o=>{r.warn("opencode-adapter",`Orphan permission reject failed: ${o}`)});return}const{eventId:s,sessionId:t,ocSessionId:i}=this.activeRun;if(this.resolveModeId(t)===m.fullAuto){this.transport.respondPermission(i,e.id,"always",this.activeRun.cwd).catch(o=>{r.warn("opencode-adapter",`Auto-approve failed: ${o}`)});return}this.trackPendingPermission(e.id);const n=e.patterns.length>0?`${e.permission}: ${e.patterns.join(", ")}`:e.permission;this.callbacks.sendPermissionCard?this.callbacks.sendPermissionCard({eventId:s,sessionId:t,approvalId:e.id,toolName:e.permission,toolTitle:n,toolInput:JSON.stringify(e.metadata??{})}):this.callbacks.sendToolUse(s,t,e.permission,JSON.stringify(e.metadata??{}))}handlePermission(e){if(!this.activeRun)return;const{eventId:s,sessionId:t,ocSessionId:i}=this.activeRun;if(this.resolveModeId(t)===m.fullAuto){this.transport.respondPermission(i,e.id,"always",this.activeRun.cwd).catch(n=>{r.warn("opencode-adapter",`Auto-approve failed: ${n}`)});return}if(this.trackPendingPermission(e.id),this.callbacks.sendPermissionCard)this.callbacks.sendPermissionCard({eventId:s,sessionId:t,approvalId:e.id,toolName:e.type,toolTitle:e.title||e.type,toolInput:JSON.stringify(e.metadata??{})});else{const n=JSON.stringify(e.metadata??{});this.callbacks.sendToolUse(s,t,e.type,n)}}handlePermissionAction(e){if(!this.activeRun)return{handled:!1,kind:""};const s=e.params??{},t=String(s.approval_id??s.approval_command_id??s.approvalId??s.tool_call_id??"");let i=t?this.pendingPermissions.get(t):void 0;if(!i){for(const a of this.pendingPermissions.values())if(a.eventId===this.activeRun.eventId){i=a;break}}if(!i)return this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,"unknown_or_expired_approval_id","That approval request is no longer pending."),{handled:!0,kind:"permission"};const n=e.action_type==="exec_approve"||e.action_type==="permission_approve",o=n?"once":"reject";return clearTimeout(i.timer),this.pendingPermissions.delete(i.permissionId),this.transport.respondPermission(i.ocSessionId,i.permissionId,o,i.cwd).then(()=>{r.info("opencode-adapter",`Permission ${o}: ${i.permissionId}`),this.resetIdleTimer()}).catch(a=>{r.warn("opencode-adapter",`Permission response failed: ${a}`),this.resetIdleTimer()}),this.callbacks.sendLocalActionResult(e.action_id,"ok",{approval_id:i.permissionId,decision:n?"approve":"reject"}),{handled:!0,kind:"permission"}}async handleExecApprovalEvent(e){if(!this.activeRun)return{delivered:!1,errorCode:"approval_not_found",errorMsg:"no active run"};const s=String(e.approval_id??e.approval_command_id??e.tool_call_id??"");let t=s?this.pendingPermissions.get(s):void 0;if(!t){for(const n of this.pendingPermissions.values())if(n.eventId===this.activeRun.eventId){t=n;break}}if(!t)return{delivered:!1,errorCode:"approval_not_found",errorMsg:"That approval request is no longer pending."};const i=e.decision==="deny"?"reject":e.decision==="allow-always"?"always":"once";return clearTimeout(t.timer),this.pendingPermissions.delete(t.permissionId),this.transport.respondPermission(t.ocSessionId,t.permissionId,i,t.cwd).then(()=>{r.info("opencode-adapter",`Permission ${i} (text event): ${t.permissionId}`),this.resetIdleTimer()}).catch(n=>{r.warn("opencode-adapter",`Permission response failed: ${n}`),this.resetIdleTimer()}),{delivered:!0}}onQuestionTimeout(e){const s=this.pendingQuestions.get(e);s&&(this.pendingQuestions.delete(e),r.error("opencode-adapter",`Question answer timeout: ${e}`),this.transport.rejectQuestion(e,s.cwd).catch(()=>{}),this.activeRun&&this.activeRun.eventId===s.eventId&&(this.flushTextBuffer(),this.finishRun("failed","question answer timeout")))}handleQuestionAsked(e){if(!this.activeRun){this.transport.rejectQuestion(e.id).catch(n=>{r.warn("opencode-adapter",`Orphan question reject failed: ${n}`)});return}const{eventId:s,sessionId:t}=this.activeRun;this.stopIdleTimer();const i=setTimeout(()=>this.onQuestionTimeout(e.id),R);if(this.pendingQuestions.set(e.id,{requestId:e.id,eventId:s,cwd:this.activeRun.cwd,questions:e.questions,timer:i}),this.callbacks.sendAgentQuestionCard)this.callbacks.sendAgentQuestionCard(s,t,{request_id:e.id,mode:"form",questions:e.questions.map(n=>({header:n.header,prompt:n.question,...n.options.length>0?{options:n.options.map(o=>o.label)}:{},...n.multiple!==void 0?{multi_select:n.multiple}:{},...n.custom?{allow_free_text:!0}:{}})),expires_at:Date.now()+R});else{const n=e.questions.map(o=>o.question).join(`
|
|
4
|
-
`);this.callbacks.sendRunError(s,t,`Agent asks: ${n}`)}}handleQuestionReplyAction(e){const s=e.params??{},t=this.deliverQuestionReply(s);return t.delivered?this.callbacks.sendLocalActionResult(e.action_id,"ok",t.result):this.callbacks.sendLocalActionResult(e.action_id,"failed",void 0,t.errorCode,t.errorMsg),{handled:!0,kind:"question_reply"}}deliverQuestionReply(e){const s=String(e.request_id??""),t=s?this.pendingQuestions.get(s):void 0;if(!t)return{delivered:!1,errorCode:"interaction_request_not_pending",errorMsg:"The question is no longer pending; the reply was not delivered."};const i=e.resolution??{},n=String(i.type??""),o=(d,l)=>(clearTimeout(t.timer),this.pendingQuestions.delete(t.requestId),d().then(()=>this.resetIdleTimer()).catch(h=>{r.warn("opencode-adapter",`Question response failed: ${h}`),this.resetIdleTimer()}),{delivered:!0,result:l});if(n==="action"){const d=String(i.value??"");if(d==="cancel"||d==="decline")return o(()=>this.transport.rejectQuestion(t.requestId,t.cwd),{request_id:s,resolution:"cancel"})}let a=null;if(Array.isArray(e.answers))a=e.answers.map(d=>Array.isArray(d)?d.map(String):[String(d)]);else if(n==="text"){const d=String(i.value??"");d&&(a=t.questions.map((l,h)=>h===0?[d]:[]))}else if(n==="map"){const d=Array.isArray(i.entries)?i.entries:[];a=t.questions.map((l,h)=>{const u=d.find(f=>f.key===l.header||f.key===String(h+1));return u&&u.value?[u.value]:[]}),a.every(l=>l.length===0)&&d.length>0&&(a=t.questions.map((l,h)=>{const u=d[h]?.value;return u?[String(u)]:[]}))}if(!a||a.every(d=>d.length===0))return o(()=>this.transport.rejectQuestion(t.requestId,t.cwd),{request_id:s,resolution:"cancel"});const c=a;return o(()=>this.transport.replyQuestion(t.requestId,c,t.cwd),{request_id:s,resolution:"answer"})}rejectAllPendingInteractions(){for(const e of this.pendingPermissions.values())clearTimeout(e.timer),this.transport.respondPermission(e.ocSessionId,e.permissionId,"reject",e.cwd).catch(()=>{});this.pendingPermissions.clear();for(const e of this.pendingQuestions.values())clearTimeout(e.timer),this.transport.rejectQuestion(e.requestId,e.cwd).catch(()=>{});this.pendingQuestions.clear()}hasPendingInteractionForRun(e){for(const s of this.pendingPermissions.values())if(s.eventId===e)return!0;for(const s of this.pendingQuestions.values())if(s.eventId===e)return!0;return!1}startRun(e,s,t=!1){this.activeRun={eventId:e,sessionId:s,ocSessionId:"",cwd:this.getSessionCwd(s),chunkSeq:0,clientMsgId:`oc_${++this.clientMsgSeq}_${Date.now()}`,textBuffer:"",flushTimer:null},this.toolCardsSent.clear(),t&&this.auditCaptures.set(e,[]),this.lastSseAt=Date.now(),this.livenessExtendStartAt=void 0}finishRun(e,s){const t=this.activeRun;if(!t)return;if(this.completedEvents.add(t.eventId),this.completedEvents.size>he){const c=[...this.completedEvents].slice(-500);this.completedEvents=new Set(c)}this.snapshotAuditBoundary(t),this.activeRun=null,this.rejectAllPendingInteractions(),this.toolCallsInFlight.clear(),this.toolCardsSent.clear(),this.livenessExtendStartAt=void 0,this.clearMessageRoleState(),this.stopComposing(),this.stopIdleTimer();const i=++t.chunkSeq,n=t.clientMsgId,o=e==="failed"&&!!s;o&&this.callbacks.sendRunError(t.eventId,t.sessionId,s);const a=()=>{this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t.eventId,t.sessionId,n).then(()=>{this.callbacks.sendEventResult(t.eventId,e,s,void 0,o)}).catch(c=>{const d=e==="responded"?"failed":e,l=e==="responded"?`final output delivery failed: ${c instanceof Error?c.message:String(c)}`:s,h=e==="responded"?!1:o;this.callbacks.sendEventResult(t.eventId,d,l,void 0,h)}):(this.callbacks.sendStreamChunk(t.eventId,t.sessionId,"",i,!0,n),this.callbacks.sendEventResult(t.eventId,e,s,void 0,o))};if(t.textBuffer){this.stopTextFlush();for(const c of x(t.textBuffer))t.chunkSeq++,this.callbacks.sendStreamChunk(t.eventId,t.sessionId,c,t.chunkSeq,!1,t.clientMsgId);t.textBuffer=""}a(),this.emit("eventDone",t.eventId)}clearRun(){this.activeRun?.flushTimer&&clearTimeout(this.activeRun.flushTimer);const e=this.activeRun?.eventId;this.activeRun&&this.snapshotAuditBoundary(this.activeRun),this.activeRun=null,this.rejectAllPendingInteractions(),this.toolCallsInFlight.clear(),this.toolCardsSent.clear(),this.livenessExtendStartAt=void 0,this.clearMessageRoleState(),this.stopIdleTimer(),e&&this.emit("eventDone",e)}snapshotAuditBoundary(e){const s=this.auditCaptures.get(e.eventId);s&&(this.completedAuditBoundaries.set(e.eventId,{adapterType:"opencode",providerSessionId:e.ocSessionId||void 0,openCodeEvidence:{events:s}}),this.auditCaptures.delete(e.eventId))}appendText(e){if(this.activeRun){if(this.activeRun.textBuffer+=e,this.activeRun.textBuffer.length>=ie){this.flushTextBuffer();return}this.scheduleTextFlush()}}scheduleTextFlush(){!this.activeRun||this.activeRun.flushTimer||(this.activeRun.flushTimer=setTimeout(()=>{this.activeRun&&(this.activeRun.flushTimer=null),this.flushTextBuffer()},se))}flushTextBuffer(){if(this.stopTextFlush(),!(!this.activeRun||!this.activeRun.textBuffer)){for(const e of x(this.activeRun.textBuffer))this.activeRun.chunkSeq++,this.callbacks.sendStreamChunk(this.activeRun.eventId,this.activeRun.sessionId,e,this.activeRun.chunkSeq,!1,this.activeRun.clientMsgId);this.activeRun.textBuffer=""}}stopTextFlush(){this.activeRun?.flushTimer&&(clearTimeout(this.activeRun.flushTimer),this.activeRun.flushTimer=null)}startComposing(e){}stopComposing(){}shouldExtendByLiveness(){if(!this.activeRun)return!1;const e=this.process?.pid;if(!this.alive||!e||!E(e))return!1;const s=Date.now(),t=this.lastSseAt>0?s-this.lastSseAt:Number.POSITIVE_INFINITY;if(t<oe)return this.livenessExtendStartAt=s,r.info("opencode-adapter",`Liveness check: fresh SSE for ${this.activeRun.eventId} (sseAge=${t}ms, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const n=this.livenessExtendStartAt??s;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=n),s-n>b?(r.warn("opencode-adapter",`Liveness extension budget exhausted for ${this.activeRun.eventId} (no progress for ${Math.round((s-n)/6e4)}min), allowing idle fail`),!1):(r.info("opencode-adapter",`Liveness check: turn in progress for ${this.activeRun.eventId} (toolsInFlight=${this.toolCallsInFlight.size}, sseAge=${Number.isFinite(t)?`${t}ms`:"n/a"}), extending`),!0)}resetIdleTimer(){this.stopIdleTimer(),!(this.stopped||!this.activeRun)&&(this.idleTimer=setTimeout(()=>{if(this.stopped||!this.activeRun)return;if(this.hasPendingInteractionForRun(this.activeRun.eventId)&&this.shouldExtendByLiveness()){r.info("opencode-adapter",`Idle timeout skipped: pending interaction for ${this.activeRun.eventId}, resetting timer`),this.resetIdleTimer();return}if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const e=this.process?.pid,t=!!(this.alive&&e&&E(e))?`liveness budget exhausted after ${b/6e4}min`:"process not alive";r.error("opencode-adapter",`Idle timeout (${t}, toolsInFlight=${this.toolCallsInFlight.size}) \u2014 emitting exit for respawn`),this.flushTextBuffer(),this.activeRun&&(this.callbacks.sendEventResult(this.activeRun.eventId,"failed",`idle timeout: ${t}`),this.clearRun()),this.emit("exit",-1)},ne))}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}resolveCwd(){const e=this.options.aibotSessionId?this.options.bindingStore?.get(this.options.aibotSessionId)?.cwd:void 0;if(e)return e;const s=(this.config.options??{}).cwd;return typeof s=="string"&&s?s:process.cwd()}getSessionCwd(e){return this.sessions.get(e)?.cwd??this.options.bindingStore?.get(e)?.cwd??this.resolveCwd()}buildPromptText(e){let s=e.text;if(e.contextMessages&&e.contextMessages.length>0){const t=e.contextMessages.map(i=>`[context] ${i.senderId}: ${i.content}`).join(`
|
|
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(`
|
|
5
3
|
`);s=`${s}
|
|
6
4
|
|
|
7
5
|
[Conversation context]
|
|
@@ -9,4 +7,4 @@ ${t}`}return s}buildPromptTextFromEvent(e){let s=e.content||"";if(e.context_mess
|
|
|
9
7
|
`);s=`${s}
|
|
10
8
|
|
|
11
9
|
[Conversation context]
|
|
12
|
-
${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,5 +1,8 @@
|
|
|
1
|
-
import{EventEmitter as
|
|
1
|
+
import{EventEmitter as I}from"node:events";import{randomUUID as P}from"node:crypto";import{OpenCodeV2Events as A,isRecord as h}from"./opencode-v2-events.js";const v=3e4,q=300,D=5e3,x=5,y=16*1024*1024,$=2*1024*1024;class l extends Error{method;path;status;kind;constructor(e,t,r,s){super(`OpenCode REST ${e} ${t}: HTTP ${r} (${s})`),this.method=e,this.path=t,this.status=r,this.kind=s,this.name="OpenCodeHttpError"}}function b(p,e){return new Promise((t,r)=>{const s=()=>{clearTimeout(o),r(new Error("OpenCode operation canceled"))},o=setTimeout(()=>{e.removeEventListener("abort",s),t()},p);e.aborted?s():e.addEventListener("abort",s,{once:!0})})}function T(p){return h(p)&&typeof p.version=="string"&&Number.isInteger(p.pid)&&Array.isArray(p.urls)&&p.urls.every(e=>typeof e=="string")&&h(p.paths)&&typeof p.paths.tmp=="string"}class M extends I{baseUrl="";directory="";headers={};closed=!1;connectionGeneration=0;sseConnected=!1;sseGeneration=0;reconnectAttempts=0;sseController=null;requests=new Set;v2Events=new A;mcp=null;mcpDirectories=new Set;selectedProtocol="v1";prompts=new Map;cancellations=new Map;runWindows=new Map;inboxIDs=new Map;admissionUncertain=!1;get protocol(){return this.selectedProtocol}async connect(e,t,r){this.connectionGeneration++,this.cancelConnections();for(const i of this.prompts.values())i.controller.abort();this.prompts.clear(),this.v2Events.clear(),this.mcpDirectories.clear(),this.admissionUncertain=!1,this.runWindows.clear(),this.inboxIDs.clear(),this.cancellations.clear();const s=new URL(e);if(!["http:","https:"].includes(s.protocol)||s.username||s.password||s.search||s.hash)throw new Error("OpenCode connection requires an HTTP URL without embedded credentials or query");this.baseUrl=s.origin,this.directory=t??"",this.headers=r?{Authorization:`Basic ${Buffer.from(`${r.username}:${r.password}`).toString("base64")}`}:{},this.closed=!1,this.reconnectAttempts=0;const o=this.sseGeneration,n=new AbortController;this.sseController=n;try{const i=await this.detectProtocol(n.signal);if(o!==this.sseGeneration||n.signal.aborted)throw new Error("OpenCode connection canceled");this.selectedProtocol=i,await this.subscribeEvents(o,n.signal)}catch(i){throw o===this.sseGeneration&&(this.cancelConnections(),this.closed=!0,this.headers={}),i}}async detectProtocol(e){const t=Date.now()+v;for(;;)try{const r=await this.request("GET","/api/info",void 0,{scoped:!1,timeoutMs:3e3});if(!T(r))throw new l("GET","/api/info",200,"incompatible V2 server info JSON");return"v2"}catch(r){if(e.aborted)throw new Error("OpenCode connection canceled");if(r instanceof l&&r.status===503&&Date.now()<t){await b(200,e);continue}if(!(r instanceof l)||!(r.status===404||r.status===405||r.status===200&&r.kind==="non-JSON response"))throw r;const s=await this.request("GET","/session",void 0,{scoped:!1});if(!Array.isArray(s)||!s.every(o=>h(o)&&typeof o.id=="string"))throw new Error("OpenCode GET /session: incompatible V1 session list JSON");return"v1"}}async useDirectory(e,t){t?.throwIfAborted();const r=e??"";if(this.directory===r&&this.isConnected){await this.ensureMcpDirectory(t);return}if(this.directory=r,!this.baseUrl||this.closed)return;this.sseController?.abort(),this.sseConnected=!1,this.reconnectAttempts=0;const s=++this.sseGeneration,o=new AbortController;this.sseController=o;const n=()=>o.abort();t?.addEventListener("abort",n,{once:!0});try{await this.subscribeEvents(s,o.signal)}finally{t?.removeEventListener("abort",n)}t?.throwIfAborted(),await this.ensureMcpDirectory(t)}async subscribeEvents(e,t){const r=this.protocol==="v2"?"/api/event":"/event",s=this.url(r,this.protocol==="v1"?this.directory:""),o=new AbortController,n=()=>o.abort();t.addEventListener("abort",n,{once:!0});const i=setTimeout(n,v),c=()=>{clearTimeout(i),t.removeEventListener("abort",n)};try{t.aborted&&n();const a=await fetch(s,{headers:{...this.headers,Accept:"text/event-stream"},signal:o.signal,redirect:"error"});if(clearTimeout(i),!a.ok||!a.body||a.headers.get("content-type")?.split(";")[0].trim().toLowerCase()!=="text/event-stream"){try{await a.body?.cancel()}catch{}throw new l("GET",r,a.status,"SSE requires text/event-stream")}if(e!==this.sseGeneration||t.aborted||this.closed)throw await a.body.cancel(),new Error("OpenCode SSE connection canceled");this.sseConnected=!0,this.readSseStream(a.body.getReader(),e,t).catch(()=>{}).finally(c)}catch(a){throw c(),o.abort(),a instanceof l?a:new Error(`OpenCode SSE GET ${r}: connection failed or canceled`)}}async readSseStream(e,t,r){const s=new TextDecoder;let o="";const n=Date.now();try{for(;!this.closed&&!r.aborted&&t===this.sseGeneration;){const{done:i,value:c}=await e.read();if(i)break;if(o+=s.decode(c,{stream:!0}).replace(/\r\n/g,`
|
|
2
|
+
`),o=o.replace(/\r\n/g,`
|
|
3
|
+
`),o.length>$)throw new Error("OpenCode SSE frame too large");let a;for(;(a=o.indexOf(`
|
|
2
4
|
|
|
3
|
-
`);
|
|
4
|
-
`))
|
|
5
|
-
`)
|
|
5
|
+
`))>=0;){const d=o.slice(0,a);if(o=o.slice(a+2),t!==this.sseGeneration||r.aborted)return;const f=this.parseSseFrame(d);for(const u of f)try{this.emit("event",u)}catch{}}}}catch{}finally{try{await e.cancel()}catch{}e.releaseLock()}if(!(this.closed||r.aborted||t!==this.sseGeneration)){this.sseConnected=!1,Date.now()-n>=5e3&&(this.reconnectAttempts=0);try{this.emit("stream-lost")}catch{}this.v2Events.clear(),this.reconnectSse(t,r)}}parseSseFrame(e){let t="";const r=[];for(const o of e.split(`
|
|
6
|
+
`))o.startsWith("event:")?t=o.slice(6).trim():o.startsWith("data:")&&r.push(o.slice(5).trimStart());if(!r.length)return[];if(t==="effect/http-api/stream/failure")throw new Error("OpenCode SSE source failure");let s;try{s=JSON.parse(r.join(`
|
|
7
|
+
`))}catch{throw new Error("OpenCode SSE invalid JSON")}if(!h(s)||typeof s.type!="string")throw new Error("OpenCode SSE invalid event");if(this.protocol==="v2"){if(h(s.location)&&s.location.directory&&this.directory&&s.location.directory!==this.directory)return[];const o=s.data?.sessionID??s.data?.form?.sessionID,n=this.runWindows.get(o);return n&&!this.acceptRunEvent(s,n)?[]:this.v2Events.normalize(s).map(i=>n?{...i,runId:n.runId}:i)}if(h(s.properties)){const{properties:o,...n}=s;return[{...n,...o,type:s.type}]}return[s]}acceptRunEvent(e,t){if(t.canceled||t.signal?.aborted)return!1;const r=e.durable?.seq;if(e.type==="session.inbox.enqueued"&&e.data.inboxID===t.promptId){if(!Number.isSafeInteger(r))throw new Error("OpenCode V2 inbox admission requires durable sequence");return t.enqueuedSeq=r,!0}if(e.type==="session.inbox.delivered"&&e.data.inboxID===t.promptId){if(!Number.isSafeInteger(r))throw new Error("OpenCode V2 inbox delivery requires durable sequence");return t.deliveredSeq=r,!0}if(e.type==="session.execution.started"&&t.enqueuedSeq!==void 0&&Number.isSafeInteger(r)&&r>t.enqueuedSeq)return t.executionSeq=r,!0;const s=t.deliveredSeq??t.executionSeq;if(s===void 0||Number.isSafeInteger(r)&&r<=s)return!1;const o=/^session\.execution\.(succeeded|failed|interrupted)$/.test(e.type);if(o&&!Number.isSafeInteger(r))throw new Error("OpenCode V2 execution terminal requires durable sequence");if(t.deliveredSeq===void 0){if(e.type==="session.execution.succeeded")throw new Error("OpenCode V2 execution ended before own inbox delivery");return o}const n=e.data.assistantMessageID;return e.type==="session.step.started"&&t.messages.add(n),!(n&&!t.messages.has(n))}async reconnectSse(e,t){for(;this.reconnectAttempts<x;){const r=this.reconnectAttempts++;try{if(await b(Math.min(q*2**r,D),t),this.closed||t.aborted||e!==this.sseGeneration)return;await this.subscribeEvents(e,t);return}catch(s){if(this.closed||t.aborted||e!==this.sseGeneration)return;if(s instanceof l&&(s.status===401||s.status===403))break}}if(!this.closed&&e===this.sseGeneration)try{this.emit("stream-unavailable")}catch{}}url(e,t=""){const r=new URL(e,this.baseUrl);return t&&r.searchParams.set(this.protocol==="v2"?"location[directory]":"directory",t),r}async request(e,t,r,s){if(this.closed)throw new Error(`OpenCode REST ${e} ${t}: transport closed`);s?.signal?.throwIfAborted();const o=this.url(t,s?.scoped===!1?"":s?.directory??this.directory),n=new AbortController,i=()=>n.abort();s?.signal?.addEventListener("abort",i,{once:!0}),this.requests.add(n);const c=setTimeout(()=>n.abort(),s?.timeoutMs??v);let a;try{const d=await fetch(o,{method:e,headers:{...this.headers,Accept:"application/json",...r===void 0?{}:{"Content-Type":"application/json"}},...r===void 0?{}:{body:JSON.stringify(r)},signal:n.signal,redirect:"error"});if(a=d.status,d.status===204&&s?.response==="empty")return;const f=/^application\/(?:[\w.+-]+\+)?json(?:;|$)/i.test(d.headers.get("content-type")??""),u=d.body?.getReader(),E=[];let m=0;try{if(u)for(;;){const{done:g,value:C}=await u.read();if(g||(m+=C.byteLength,m>(d.ok?y:4096)))break;E.push(C)}}finally{u&&(await u.cancel(),u.releaseLock())}const O=Buffer.concat(E).toString("utf8");let S,w=m?f?"invalid JSON response":"non-JSON response":"empty response";if(f&&m<=y)try{S=JSON.parse(O),w="JSON response"}catch{}if(!d.ok||w!=="JSON response"||s?.response==="empty"||m>y)throw new l(e,t,d.status,m>y?"response too large":d.ok&&s?.response==="empty"?"expected HTTP 204":w);return S}catch(d){throw d instanceof l?d:a!==void 0?new l(e,t,a,"response read failed or canceled"):new Error(`OpenCode REST ${e} ${t}: request failed or canceled`)}finally{clearTimeout(c),s?.signal?.removeEventListener("abort",i),this.requests.delete(n)}}sessionPath(e){return`${this.protocol==="v2"?"/api":""}/session/${encodeURIComponent(e)}`}unwrap(e){return this.protocol==="v2"&&h(e)?e.data:e}session(e,t,r){const s=this.unwrap(e);if(!h(s)||typeof s.id!="string")throw new l(t,r,200,"invalid session JSON");return{...s,directory:s.directory??s.location?.directory??this.directory}}async createSession(e,t,r){if(this.protocol==="v2"){const s=t??this.directory;return this.session(await this.request("POST","/api/session",{...e,...s?{location:{directory:s}}:{}},{scoped:!1,signal:r}),"POST","/api/session")}return this.session(await this.request("POST","/session",e??{},{directory:t,signal:r}),"POST","/session")}async getSession(e,t,r){return this.session(await this.request("GET",this.sessionPath(e),void 0,{directory:t,scoped:this.protocol==="v1",signal:r}),"GET",this.sessionPath(e))}async deleteSession(e,t){await this.request("DELETE",this.sessionPath(e),void 0,{directory:t,response:this.protocol==="v2"?"empty":"json",scoped:this.protocol==="v1"}),this.v2Events.clearSession(e),this.runWindows.delete(e),this.inboxIDs.delete(e)}async updateSessionPermission(e,t,r,s){await this.request("PATCH",this.sessionPath(e),this.protocol==="v2"?{permissions:t.map(o=>({action:{bash:"shell",task:"subagent",write:"edit",patch:"edit"}[o.permission]??o.permission,resource:o.pattern,effect:o.action}))}:{permission:t},{directory:r,response:this.protocol==="v2"?"empty":"json",scoped:this.protocol==="v1",signal:s})}async sendPromptAsync(e,t,r,s){const o=this.cancellations.get(e);if(o&&await o,s?.signal?.throwIfAborted(),this.admissionUncertain)throw new Error("OpenCode prompt admission unconfirmed; server must be replaced");if(this.prompts.has(e))throw new Error("OpenCode session already has a prompt admission in progress");const n=new AbortController,i=()=>n.abort();s?.signal?.addEventListener("abort",i,{once:!0});const c=`msg_${P().replaceAll("-","")}`,a={controller:n,admitted:!1,dispatched:!1,done:Promise.resolve()};this.prompts.set(e,a),this.protocol==="v2"&&this.inboxIDs.set(e,c),this.protocol==="v2"&&s?.runId&&(this.v2Events.clearSession(e),this.runWindows.set(e,{runId:s.runId,promptId:c,signal:s.signal,canceled:!1,messages:new Set}));const d=this.connectionGeneration;a.done=this.preparePrompt(e,t,r,c,a);try{await a.done}catch(f){throw a.dispatched&&!a.admitted&&!this.closed&&d===this.connectionGeneration&&(this.admissionUncertain=!0,this.emit("admission-uncertain")),f}finally{s?.signal?.removeEventListener("abort",i),this.prompts.get(e)===a&&this.prompts.delete(e)}}async preparePrompt(e,t,r,s,o){const n=this.sessionPath(e),i=o.controller.signal;if(this.protocol==="v1"){i.throwIfAborted(),o.dispatched=!0,await this.request("POST",`${n}/prompt_async`,t,{directory:r,response:"empty"}),o.admitted=!0;return}t.model&&await this.request("POST",`${n}/model`,{model:{providerID:t.model.providerID,id:t.model.modelID}},{scoped:!1,response:"empty",signal:i}),t.agent&&await this.request("POST",`${n}/agent`,{agent:t.agent},{scoped:!1,response:"empty",signal:i}),await this.request(t.system?"PUT":"DELETE",`/api/experimental/session/${encodeURIComponent(e)}/instructions/entries/grix_identity`,t.system?{value:t.system}:void 0,{scoped:!1,response:"empty",signal:i}),i.throwIfAborted(),o.dispatched=!0;const c=await this.request("POST",`${n}/prompt`,{id:s,text:t.parts.map(a=>a.text).join(`
|
|
8
|
+
`)},{scoped:!1});if(!h(c)||!h(c.data)||c.data.id!==s)throw new l("POST",`${n}/prompt`,200,"invalid inbox JSON");o.admitted=!0}async abortSession(e,t){const r=this.cancellations.get(e);if(r)return r;const s=this.prompts.get(e);s?.controller.abort();const o=this.runWindows.get(e);o&&(o.canceled=!0);const n=this.interruptAfterAdmission(e,t,s,this.inboxIDs.get(e));return this.cancellations.set(e,n),n.then(()=>{this.cancellations.get(e)===n&&this.cancellations.delete(e)},()=>{}),n}async interruptAfterAdmission(e,t,r,s){const o=this.connectionGeneration,n=()=>{if(this.closed||o!==this.connectionGeneration)throw new Error("OpenCode interrupt connection canceled")};await r?.done.catch(()=>{}),n(),this.protocol==="v2"&&s&&await this.request("DELETE",`${this.sessionPath(e)}/inbox/${encodeURIComponent(s)}`,void 0,{scoped:!1,response:"empty"}),n();const i=await this.request("POST",`${this.sessionPath(e)}/${this.protocol==="v2"?"interrupt":"abort"}`,void 0,{directory:t,scoped:this.protocol==="v1"});if(this.protocol==="v2"&&(!h(i)||typeof i.interrupted!="boolean"))throw new l("POST",`${this.sessionPath(e)}/interrupt`,200,"invalid interrupt JSON");n(),this.protocol==="v2"&&await this.request("POST",`/api/experimental/session/${encodeURIComponent(e)}/wait`,void 0,{scoped:!1,response:"empty"})}async respondPermission(e,t,r,s){await this.request("POST",this.protocol==="v2"?`${this.sessionPath(e)}/permission/${encodeURIComponent(t)}/reply`:`${this.sessionPath(e)}/permissions/${encodeURIComponent(t)}`,this.protocol==="v2"?{decision:r}:{response:r},{directory:s,response:this.protocol==="v2"?"empty":"json",scoped:this.protocol==="v1"})}async replyQuestion(e,t,r){if(this.protocol==="v1"){await this.request("POST",`/question/${encodeURIComponent(e)}/reply`,{answers:t},{directory:r});return}const s=this.v2Events.getForm(e);await this.request("POST",`${this.sessionPath(s.sessionID)}/form/${encodeURIComponent(e)}/reply`,{answer:this.v2Events.formAnswer(e,t)},{scoped:!1,response:"empty"}),this.v2Events.forgetForm(e)}async rejectQuestion(e,t){if(this.protocol==="v1"){await this.request("POST",`/question/${encodeURIComponent(e)}/reject`,void 0,{directory:t});return}const r=this.v2Events.getForm(e);await this.request("DELETE",`${this.sessionPath(r.sessionID)}/form/${encodeURIComponent(e)}`,void 0,{scoped:!1,response:"empty"}),this.v2Events.forgetForm(e)}async listProviders(e){if(this.protocol==="v1"){const s=await this.request("GET","/config/providers",void 0,{directory:e});if(!Array.isArray(s?.providers))throw new l("GET","/config/providers",200,"invalid provider JSON");return s.providers}const t=this.unwrap(await this.request("GET","/api/model",void 0,{directory:e}));if(!Array.isArray(t))throw new l("GET","/api/model",200,"invalid model list JSON");const r=new Map;for(const s of t){if(!h(s)||typeof s.id!="string"||typeof s.providerID!="string")throw new l("GET","/api/model",200,"invalid model JSON");if(s.enabled===!1)continue;const o=r.get(s.providerID)??{id:s.providerID,name:s.providerID,models:[]};o.models.push({id:s.id,name:s.name,limit:s.limit}),r.set(s.providerID,o)}return[...r.values()]}async configureMcp(e,t){this.mcp={name:e,command:t},this.mcpDirectories.clear(),await this.ensureMcpDirectory()}async ensureMcpDirectory(e){if(e?.throwIfAborted(),this.protocol!=="v2"||!this.mcp||this.mcpDirectories.has(this.directory))return;const t=this.directory,{name:r,command:s}=this.mcp;await this.request("PUT",`/api/experimental/mcp/${encodeURIComponent(r)}`,{config:{type:"local",command:s,disabled:!1}},{directory:t,response:"empty",signal:e});const o=Date.now()+1e4;for(;;){const n=this.unwrap(await this.request("GET","/api/mcp",void 0,{directory:t,signal:e})),i=Array.isArray(n)?n.find(c=>h(c)&&c.name===r):void 0;if(i?.status?.status==="connected")break;if(i?.status?.status!=="pending"||Date.now()>=o)throw new Error("OpenCode V2 MCP did not become connected");if(!this.sseController)throw new Error("OpenCode MCP setup canceled");await b(100,e??this.sseController.signal)}this.mcpDirectories.add(t)}async healthCheck(){try{if(this.closed)return!1;if(this.protocol==="v2")return T(await this.request("GET","/api/info",void 0,{scoped:!1,timeoutMs:3e3}));const e=await this.request("GET","/session",void 0,{timeoutMs:3e3});return Array.isArray(e)&&e.every(t=>h(t)&&typeof t.id=="string")}catch{return!1}}cancelConnections(){this.sseGeneration++,this.sseController?.abort(),this.sseController=null;for(const e of this.requests)e.abort();this.sseConnected=!1}disconnect(){this.connectionGeneration++,this.closed=!0,this.cancelConnections(),this.headers={},this.mcp=null,this.mcpDirectories.clear(),this.v2Events.clear();for(const e of this.prompts.values())e.controller.abort();this.prompts.clear(),this.cancellations.clear(),this.runWindows.clear(),this.inboxIDs.clear(),this.removeAllListeners()}get isConnected(){return this.sseConnected&&!this.closed}}export{l as OpenCodeHttpError,M as OpenCodeTransport};
|
|
@@ -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};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function u(m){return typeof m=="object"&&m!==null&&!Array.isArray(m)}const g=1024;class f{messages=new Map;textLengths=new Map;tools=new Map;forms=new Map;normalize(o){if(!u(o.data))throw new Error("OpenCode V2 event requires data");if([this.messages,this.textLengths,this.tools,this.forms].some(t=>t.size>g))throw new Error("OpenCode V2 event state limit exceeded");const e=o.data,r=e.sessionID;if(o.type.startsWith("session.")&&typeof r!="string")throw new Error("OpenCode V2 session event requires sessionID");let s=[];const n=e.assistantMessageID;if(/^session\.(step|text|reasoning|tool)\./.test(o.type)&&typeof n!="string")throw new Error("OpenCode V2 event requires assistantMessageID");if(/^session\.(text|reasoning)\.delta$/.test(o.type)&&typeof e.delta!="string")throw new Error("OpenCode V2 event requires text delta");const d=`${r}/${n}/${e.id}`,c=t=>{const a=this.messages.get(n),i={...a,id:n,sessionID:r,role:"assistant",time:{created:a?.time.created??e.started??o.created??Date.now()},modelID:e.model?.id??a?.modelID??"",providerID:e.model?.providerID??a?.providerID??"",...t?{tokens:t,cost:e.cost,time:{created:a?.time.created??o.created,completed:o.created}}:{}};return this.messages.set(n,i),i},p=t=>{const a=this.tools.get(d)??{sessionID:r,name:"unknown",input:{}};return{type:"message.part.updated",part:{id:d,messageID:n,sessionID:r,type:"tool",callID:e.id,tool:a.name,state:{status:t,input:a.input,raw:e.text??"",...t==="completed"?{output:Array.isArray(e.content)?e.content.map(l=>l.type==="text"?l.text:JSON.stringify(l)).join(`
|
|
2
|
+
`):""}:{},...t==="error"?{error:e.error?.message??"Tool failed"}:{},title:a.name,time:{start:a.started??o.created??Date.now(),end:o.created??Date.now()}}}}};switch(o.type){case"server.connected":s=[{type:"server.connected"}];break;case"session.execution.started":s=[{type:"session.status",sessionID:r,status:{type:"busy"}}];break;case"session.execution.succeeded":s=[{type:"session.idle",sessionID:r}],this.clearSession(r,!1);break;case"session.execution.failed":s=[{type:"session.error",sessionID:r,error:this.error(e.error)}],this.clearSession(r,!1);break;case"session.execution.interrupted":s=[{type:"session.canceled",sessionID:r}],this.clearSession(r,!1);break;case"session.step.started":s=[{type:"message.updated",info:c()}];break;case"session.step.ended":s=[{type:"message.updated",info:c(e.tokens)}];break;case"session.text.delta":case"session.reasoning.delta":case"session.text.ended":case"session.reasoning.ended":{const t=o.type.startsWith("session.reasoning."),a=`${r}/${n}/${t}/${e.ordinal}`,i=this.textLengths.get(a)?.text??"",l=o.type.endsWith(".ended"),h=l?String(e.text??"").slice(i.length):String(e.delta??""),y=l?String(e.text??""):i+h;if(y.length>2*1024*1024)throw new Error("OpenCode V2 text limit exceeded");this.textLengths.set(a,{sessionID:r,text:y}),this.messages.has(n)||s.push({type:"message.updated",info:c()}),s.push({type:"message.part.updated",part:{type:t?"reasoning":"text",id:a,messageID:n,text:y},delta:h});break}case"session.tool.input.started":this.tools.set(d,{sessionID:r,name:e.name,input:{},started:o.created});break;case"session.tool.input.ended":{const t=this.tools.get(d);if(t)try{const a=JSON.parse(e.text);u(a)&&(t.input=a)}catch{}break}case"session.tool.called":{const t=this.tools.get(d)??{sessionID:r,name:"unknown",input:{}};t.input=u(e.input)?e.input:{},this.tools.set(d,t),s=[p("running")];break}case"session.tool.success":s=[p("completed")],this.tools.delete(d);break;case"session.tool.failed":s=[p("error")],this.tools.delete(d);break;case"permission.asked":if(typeof e.id!="string"||!Array.isArray(e.resources))throw new Error("OpenCode V2 invalid permission event");s=[{type:"permission.asked",id:e.id,sessionID:r,permission:e.action,patterns:e.resources,always:e.save??[],metadata:e.metadata??{},...e.source?.type==="tool"?{tool:{messageID:e.source.messageID,callID:e.source.id}}:{}}];break;case"permission.replied":s=[{type:"permission.replied",sessionID:r,requestID:e.requestID,reply:e.reply}];break;case"form.created":{const t=e.form;if(!u(t)||typeof t.id!="string"||typeof t.sessionID!="string"||!Array.isArray(t.fields))throw new Error("OpenCode V2 invalid form event");if(this.forms.set(t.id,t),t.fields.some(i=>i.hidden||i.when?.length||!["string","multiselect","boolean","number","integer"].includes(i.type))){s=[{type:"question.unsupported",sessionID:t.sessionID,id:t.id}];break}const a=t.fields.map(i=>({header:i.title||i.key,question:i.description||i.title||i.key,options:i.type==="boolean"?[{label:"true"},{label:"false"}]:(i.options??[]).map(l=>({label:l.label,description:l.description})),multiple:i.type==="multiselect",custom:i.type!=="boolean"&&(i.custom??!i.options?.length)}));s=[{type:"question.asked",id:t.id,sessionID:t.sessionID,questions:a}];break}case"form.replied":s=[{type:"question.replied",sessionID:r,requestID:e.id,answers:[]}],this.forms.delete(e.id);break;case"form.cancelled":s=[{type:"question.rejected",sessionID:r,requestID:e.id}],this.forms.delete(e.id);break;case"location.shutdown":s=[{type:"server.instance.disposed",directory:o.location?.directory??""}];break}return s.length||(s=[{type:"opencode.v2.event"}]),s.map(t=>({...t,nativeEvent:o}))}error(o){return{type:typeof o?.type=="string"?o.type:"unknown",message:typeof o?.message=="string"?o.message:"OpenCode execution failed"}}getForm(o){const e=this.forms.get(o);if(!e)throw new Error("OpenCode V2 form is no longer pending");return e}forgetForm(o){this.forms.delete(o)}formAnswer(o,e){const r=this.getForm(o),s=Object.create(null);return r.fields.forEach((n,d)=>{const c=e[d]??[];if(!c.length){if(n.required)throw new Error("OpenCode V2 form requires an answer");return}const p=c.map(t=>n.options?.find(a=>a.label===t)?.value??t);if(n.type==="multiselect")s[n.key]=p;else if(n.type==="boolean"){if(!["true","false"].includes(p[0]))throw new Error("OpenCode V2 form requires a boolean");s[n.key]=p[0]==="true"}else if(n.type==="number"||n.type==="integer"){const t=Number(p[0]);if(!p[0].trim()||!Number.isFinite(t)||n.type==="integer"&&!Number.isInteger(t))throw new Error("OpenCode V2 form requires a number");s[n.key]=t}else if(n.type==="string")s[n.key]=p[0];else throw new Error("OpenCode V2 form field is unsupported")}),s}clearSession(o,e=!0){for(const[r,s]of this.messages)s.sessionID===o&&this.messages.delete(r);for(const[r,s]of this.textLengths)s.sessionID===o&&this.textLengths.delete(r);for(const[r,s]of this.tools)s.sessionID===o&&this.tools.delete(r);if(e)for(const[r,s]of this.forms)s.sessionID===o&&this.forms.delete(r)}clear(){this.messages.clear(),this.textLengths.clear(),this.tools.clear(),this.forms.clear()}}export{f as OpenCodeV2Events,u as isRecord};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{resolveCommandPath as n}from"../../core/runtime/spawn.js";import{resolveCliPath as a}from"../../core/util/cli-probe.js";async function c(e,t){const o=String(e??"").trim()||"opencode",r=n(o,t);return r!==o?r:await a(o)||o}export{c as resolveOpencodeCommandPath};
|
|
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.0",
|
|
4
|
+
"tarball": "grix-dsh-bridge-4.16.0.tgz",
|
|
5
|
+
"size": 24210,
|
|
6
|
+
"unpackedSize": 96662,
|
|
7
|
+
"shasum": "8a33e845783a1fd5810e15d72cfa00975d6dfe0d",
|
|
8
|
+
"integrity": "sha512-jeyck/gCIUgkdb3/Wwr0oWQvK4MYqmzwO8IpgHFt+4+FqCoAGheXfqYW0nMChrF0D1MfruPDexGVU++KmG1ZmA=="
|
|
9
9
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{referenceCaptureContent as B}from"../../core/content-reference.js";const U=Object.freeze({inputOutput:!0,tools:!0,subagents:!1,thinking:!0,rawProviderBody:!1});function
|
|
1
|
+
import{referenceCaptureContent as B}from"../../core/content-reference.js";const U=Object.freeze({inputOutput:!0,tools:!0,subagents:!1,thinking:!0,rawProviderBody:!1});function g(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function a(e){return typeof e=="string"&&e.length>0?e:void 0}function w(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:void 0}function J(e){return e.options?.enabled===!0?e.options.capture:U}function O(e,n,r){const s=[r.role,r.value??""].join("\0");if(n.has(s))return n.get(s);const o=B(r);return n.set(s,o),e.push(r),o}function _(e,n){n&&!e.some(r=>r.contentId===n.contentId)&&e.push(n)}function M(e,n){return typeof e=="number"&&Number.isFinite(e)?new Date(e).toISOString():typeof e=="string"&&Number.isFinite(Date.parse(e))?e:n}function D(e){const n=e.startedAt??e.job.startedAt,r=e.endedAt??e.job.endedAt,s=Date.parse(n),o=Date.parse(r);return{spanId:e.spanId,traceId:e.job.traceId,turnId:e.job.turnId,sessionId:e.job.sessionId,...e.parentSpanId?{parentSpanId:e.parentSpanId}:{},kind:e.kind,name:e.name,sequence:e.sequence,status:e.status??"completed",startedAt:n,endedAt:r,...Number.isFinite(s)&&Number.isFinite(o)?{durationMs:Math.max(0,o-s)}:{},inputRefs:[],outputRefs:[],provider:{provider:"opencode",nativeEventType:e.nativeEventType,nativeIds:Object.fromEntries(Object.entries(e.nativeIds??{}).filter(f=>typeof f[1]=="string")),...e.rawAttributes?{rawAttributes:e.rawAttributes}:{}},provenance:{source:"provider_event",accuracy:"provider_reported"}}}function H(e){const n=w(e.input),r=w(e.output),s=w(e.reasoning),o=w(e.total),f=g(e.cache)?e.cache:{},m=w(f.read),v=w(f.write);if(n===void 0||r===void 0||s===void 0||o===void 0||m===void 0||v===void 0)return;const y=n+m+v,I=o===y+r+s,h=o===y+r&&s<=r;if(!I&&!h)return;const A=I?r+s:r,S=I?r:r-s;return{input:{total:y,uncached:n,cacheRead:m,cacheWrite:v,other:0},output:{total:A,reasoning:s,visible:S},totalProcessed:o,requestCount:1,accuracy:"provider_reported",completeness:"complete",provider:"opencode",providerUsageRaw:e,normalization:{adapter:"opencode-sse",version:1,formula:I?"input + cache.read + cache.write + output + reasoning":"input + cache.read + cache.write + output; reasoning is an output subset"}}}class W{provider="opencode";async collect(n){const r={events:[],anomalies:[],gaps:[]},s=g(n.boundary.openCodeEvidence)?n.boundary.openCodeEvidence:void 0;if(!s||!Array.isArray(s.events))return r.gaps.push({category:"opencode_event",reason:"source_log_missing",detail:"boundary.openCodeEvidence.events is missing"}),r;for(const o of s.events){if(!g(o)||!g(o.event)||typeof o.sequence!="number"||typeof o.observedAt!="string"){r.anomalies.push({code:"opencode_audit_event_malformed",message:"OpenCode evidence row is malformed"}),r.gaps.push({category:"opencode_event",reason:"correlation_failed"});continue}r.events.push({sequence:o.sequence,observedAt:o.observedAt,event:o.event})}return r.events.sort((o,f)=>o.sequence-f.sequence),r}async normalize(n,r){const s=r,o=J(n),f=[],m=[],v=new Map;let y=0;const I=`opencode:${n.turnId}:turn`,h=D({job:n,spanId:I,kind:"turn",name:"OpenCode audited turn",sequence:y++,status:n.outcome==="completed"?"completed":n.outcome==="cancelled"?"cancelled":"failed",nativeEventType:"sse_turn",nativeIds:{providerSessionId:a(n.boundary.providerSessionId)}});f.push(h);const A=o.inputOutput&&n.input?O(m,v,{...n.input,captureLevel:n.input.captureLevel??"runtime_exact"}):void 0;_(h.inputRefs,A),o.inputOutput&&n.finalOutput&&_(h.outputRefs,O(m,v,{...n.finalOutput,captureLevel:n.finalOutput.captureLevel??"runtime_exact"}));const S=new Map,c=new Map;for(const p of s.events){if(p.event.type==="message.updated"&&g(p.event.info)){const d=p.event.info;if(d.role!=="assistant")continue;const q=a(d.id);if(!q)continue;const x=S.get(q);S.set(q,{firstSequence:x?.firstSequence??p.sequence,item:p,info:d})}if(p.event.type==="message.part.updated"&&g(p.event.part)){const d=a(p.event.part.id);d&&c.set(d,{sequence:p.sequence,item:p,part:p.event.part})}}const F=[...S.values()].sort((p,d)=>p.firstSequence-d.firstSequence),E=new Map;let $=A?[A]:[];for(const p of F){const d=p.info,q=a(d.id),x=g(d.time)?d.time:{},C=a(d.modelID),t=D({job:n,spanId:`opencode:${n.sessionId}:request:${q}`,parentSpanId:I,kind:"llm_request",name:[a(d.providerID),C].filter(Boolean).join("/")||"OpenCode model request",sequence:y++,status:d.error?"failed":"completed",startedAt:M(x.created,p.item.observedAt),endedAt:M(x.completed,p.item.observedAt),nativeEventType:g(p.item.event.nativeEvent)?a(p.item.event.nativeEvent.type)??"message.updated":"message.updated",nativeIds:{messageId:q,providerSessionId:a(d.sessionID)??a(n.boundary.providerSessionId)},rawAttributes:{message:d}});C&&(t.modelId=C);for(const i of $)_(t.inputRefs,i);$=[],g(d.tokens)&&(t.usage=H(d.tokens)),t.usage||s.gaps.push({category:"provider_usage",reason:"provider_usage_missing",detail:q});const u=[...c.values()].filter(({part:i})=>i.messageID===q).sort((i,l)=>i.sequence-l.sequence);for(const{part:i}of u)o.inputOutput&&i.type==="text"&&typeof i.text=="string"&&i.text&&_(t.outputRefs,O(m,v,{role:"assistant_text",format:"text",value:i.text,captureLevel:"provider_exact"})),o.thinking&&i.type==="reasoning"&&typeof i.text=="string"&&i.text&&_(t.outputRefs,O(m,v,{role:"thinking",format:"text",value:i.text,captureLevel:"provider_exact"}));o.rawProviderBody&&_(t.outputRefs,O(m,v,{role:"model_response",format:"json",value:JSON.stringify(d),captureLevel:"provider_exact"})),f.push(t),E.set(q,t)}if(o.tools){const p=[...c.values()].filter(({part:t})=>t.type==="tool").sort((t,u)=>t.sequence-u.sequence);for(const{part:t,item:u}of p){const i=a(t.callID)??a(t.id);if(!i||!g(t.state))continue;const l=t.state,b=a(l.status)??"pending",k=g(l.time)?l.time:{},T=D({job:n,spanId:`opencode:${n.sessionId}:tool:${i}`,parentSpanId:E.get(a(t.messageID)??"")?.spanId??I,kind:"tool_call",name:a(t.tool)??"tool",sequence:y++,status:b==="completed"?"completed":b==="error"?"failed":"running",startedAt:M(k.start,u.observedAt),endedAt:M(k.end,u.observedAt),nativeEventType:g(u.event.nativeEvent)?a(u.event.nativeEvent.type)??"message.part.updated":"message.part.updated",nativeIds:{toolCallId:i,messageId:a(t.messageID)},rawAttributes:{part:t}});l.input!==void 0&&_(T.inputRefs,O(m,v,{role:"tool_arguments",format:"json",value:typeof l.input=="string"?l.input:JSON.stringify(l.input),captureLevel:"provider_exact"}));const R=l.output??l.error;if(R!==void 0){const L=O(m,v,{role:"tool_result",format:typeof R=="string"?"text":"json",value:typeof R=="string"?R:JSON.stringify(R),captureLevel:"provider_exact"});if(_(T.outputRefs,L),L){const z=Date.parse(T.endedAt??u.observedAt),N=f.find(P=>P.kind==="llm_request"&&Date.parse(P.startedAt)>=z);N&&_(N.inputRefs,L)}}f.push(T)}const d=new Map,q=new Map,x=[];let C=-1;for(const t of s.events)t.sequence>C&&(C=t.sequence),t.event.type==="permission.asked"&&a(t.event.id)?d.set(t.event.id,t):t.event.type==="permission.replied"&&a(t.event.requestID)?q.set(t.event.requestID,t):t.event.type==="permission.updated"&&g(t.event.permission)&&x.push(t);for(const[t,u]of d){const i=q.get(t),l=g(u.event.tool)?u.event.tool:void 0,b=a(l?.messageID),k=D({job:n,spanId:`opencode:${n.sessionId}:permission:${t}`,parentSpanId:(b?E.get(b)?.spanId:void 0)??I,kind:"permission",name:a(u.event.permission)??"permission_request",sequence:y++,status:i?a(i.event.reply)==="reject"?"failed":"completed":"running",startedAt:u.observedAt,endedAt:i?.observedAt??u.observedAt,nativeEventType:"permission.asked",nativeIds:{requestId:t,messageId:b,toolCallId:a(l?.callID)},rawAttributes:{permissionRequest:u.event,...i?{permissionReply:i.event}:{}}});f.push(k)}for(const t of x){const u=t.event.permission,i=a(u.messageID),l=a(u.id)??`legacy:${t.sequence}`,b=t.sequence<C,k=D({job:n,spanId:`opencode:${n.sessionId}:permission:${l}`,parentSpanId:(i?E.get(i)?.spanId:void 0)??I,kind:"permission",name:a(u.type)??a(u.title)??"permission_request",sequence:y++,status:b?"completed":"running",startedAt:t.observedAt,endedAt:t.observedAt,nativeEventType:"permission.updated",nativeIds:{requestId:l,messageId:i,toolCallId:a(u.callID)},rawAttributes:{permission:u}});f.push(k)}}return{spans:f,contents:m,anomalies:s.anomalies,collection:s,capture:o}}async correlate(n,r){return r}validate(n,r){const s=r,o=s.spans.filter(c=>c.kind==="llm_request"),f=s.spans.filter(c=>c.kind==="tool_call"),m=s.spans.filter(c=>c.kind==="permission"),v=!s.capture.inputOutput||n.input!==void 0,y=!s.capture.inputOutput||n.finalOutput!==void 0||o.some(c=>c.outputRefs.length>0),I=!s.capture.tools||f.every(c=>c.status!=="running")&&m.every(c=>c.status!=="running"),h=o.length>0&&o.every(c=>c.usage?.completeness==="complete"),A=[...s.collection.gaps];s.capture.rawProviderBody&&A.push({category:"raw_provider_body",reason:"raw_capture_disabled",detail:"OpenCode exposes provider-normalized SSE events, not raw HTTP bodies"});const S=v&&y&&I&&h&&A.length===0;return{status:s.collection.events.length===0||o.length===0?"failed":S?"complete":"partial",inputComplete:v,outputComplete:y,toolCallsComplete:I,subagentsComplete:!0,usageComplete:h,rawRequestsComplete:!1,gaps:A}}}export{W as OpenCodeAuditAdapter};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{sharedProviderQuotaService as y,detectProviderFromModel as m,normalizeProviderId as Q,readPiProviderSettings as b,readOpenCodeProviderSettings as $,isOpenaiCodexProviderName as A,queryOpenaiCodexQuota as S,openaiCodexQuotaCacheKey as q,resolveKimiProviderSettings as K,providerQuotaToRateLimits as T,providerQuotaToCodexRateLimits as x}from"../core/provider-quota/index.js";import{queryKiroQuota as E}from"../core/provider-quota/kiro.js";import{queryGrixRelayWalletBalance as R}from"../core/provider-quota/grix-relay.js";import{DshJsonRpcAdapter as H,resolveDshHome as M,readDshCredentials as D}from"../adapter/deepseek-harness/index.js";import{readSettingsEnv as C}from"../adapter/claude/model-list.js";import{readCodexProviderSettings as U}from"../adapter/codex/codex-trust.js";import{agentIdOf as O}from"../adapter/shared/native-provider-config.js";import{log as u}from"../core/log/index.js";const w=30*1e3,k=10*1e3,z=["isRateLimitsCacheFresh","isGrixRelayActive","providerQuotaToRateLimits","resolveProviderQuotaSource","maybeQueryProviderQuota","stopProviderQuotaTimer","refreshAndPushProviderQuota","pushProviderQuotaToBindings","enrichProviderQuotaMeta","refreshProviderQuotaForSession","doRefreshQuotaAfterModelSwitch"],Y=["name","config","stopped","aibotHandle","pool","bindingStore","sessionBindings","sessionProviderHints","sessionProviderQuotas","sessionProviderMeta","cachedAcpContextWindow","cachedProviderQuota","cachedProviderQuotaKey","cachedProviderQuotaSampledAtMs","providerQuotaTimer","lastModelSwitchQuotaRefresh"];async function j(e,a){if(a?.disabled||a?.providerId==="openai_codex")return null;let o=e.config.providerBaseUrl??e.config.agent.provider?.baseUrl,t=e.config.providerApiKey??e.config.agent.provider?.apiKey;if((e.config.adapterType??"acp")==="deepseek-harness"){if(t??=e.config.agent.env?.DEEPSEEK_API_KEY,o??=e.config.agent.env?.DEEPSEEK_BASE_URL,!t){const r=M(typeof e.config.adapterOptions?.dshHome=="string"?e.config.adapterOptions.dshHome:void 0,e.config.agent.env);try{const i=await D(r),d=typeof i.DEEPSEEK_API_KEY=="string"?i.DEEPSEEK_API_KEY.trim():"";d&&(t=d,o??=typeof i.DEEPSEEK_BASE_URL=="string"&&i.DEEPSEEK_BASE_URL.trim()?i.DEEPSEEK_BASE_URL.trim():"https://api.deepseek.com",u.debug(e.name,"[provider-quota] deepseek-harness: resolved official DeepSeek API key from DSH credential store ($DSH_HOME)"))}catch(i){u.warn(e.name,`[provider-quota] deepseek-harness: could not read DSH credential store: ${i instanceof Error?i.message:String(i)}`)}}o??=t?"https://api.deepseek.com":void 0}if((!o||!t)&&(e.config.adapterType??"acp")==="claude"){const r=C();o||(o=(r.ANTHROPIC_BASE_URL??"").trim()||void 0),t||(t=(r.ANTHROPIC_API_KEY??"").trim()||(r.ANTHROPIC_AUTH_TOKEN??"").trim()||void 0)}if((!o||!t)&&(e.config.adapterType??"acp")==="codex"){const r=U();!o&&r.baseUrl&&(o=r.baseUrl),!t&&r.apiKey&&(t=r.apiKey)}if((!o||!t)&&(e.config.adapterType??"acp")==="acp"&&e.config.aibot.clientType==="kimi"){const r=await K();!o&&r.baseUrl&&(o=r.baseUrl),!t&&r.apiKey&&(t=r.apiKey)}if((!o||!t)&&(e.config.adapterType??"acp")==="pi"){const r=b(a,e.config.agent.env?.PI_CODING_AGENT_DIR);!o&&r.baseUrl&&(o=r.baseUrl),!t&&r.apiKey&&(t=r.apiKey)}if((!o||!t)&&(e.config.adapterType??"acp")==="opencode"){const r=$(a,void 0,O(e.config.agent.command||"opencode")||"opencode");!o&&r.baseUrl&&(o=r.baseUrl),!t&&r.apiKey&&(t=r.apiKey)}if(!o||!t)return null;const n=Q(a?.providerId)??m(a?.model)?.id??Q(e.config.agent.provider?.providerId)??m(e.config.agent.provider?.model)?.id;return{baseUrl:o,...e.config.agent.provider?.quotaBaseUrl?{quotaBaseUrl:e.config.agent.provider.quotaBaseUrl}:{},apiKey:t,...n?{providerId:n}:{}}}async function J(e,a=!1,o){if(e.config.aibot.clientType==="kiro"){if(!a&&e.isRateLimitsCacheFresh(e.cachedProviderQuotaSampledAtMs)&&e.cachedProviderQuota)return e.cachedProviderQuota;try{const r=await E();return e.cachedProviderQuota=r,e.cachedProviderQuotaSampledAtMs=Date.now(),e.cachedProviderQuotaKey="kiro",u.info(e.name,`[provider-quota] kiro queried: success=${r.success}`+(r.balance?` balance=${r.balance.remaining} ${r.balance.unit}`:"")+(r.planName?` plan=${r.planName}`:"")+(r.error?` error=${r.error}`:"")),r}catch(r){return u.warn(e.name,`[provider-quota] kiro query failed: ${r instanceof Error?r.message:String(r)}`),null}}if((e.config.adapterType??"acp")==="claude"&&e.isGrixRelayActive()){if(!a&&e.cachedProviderQuotaKey==="grix-relay"&&e.isRateLimitsCacheFresh(e.cachedProviderQuotaSampledAtMs)&&e.cachedProviderQuota)return e.cachedProviderQuota;try{const r=await R({wsUrl:e.config.aibot.url,apiKey:e.config.aibot.apiKey});return r.success&&(e.cachedProviderQuota=r,e.cachedProviderQuotaSampledAtMs=Date.now(),e.cachedProviderQuotaKey="grix-relay"),u.info(e.name,`[provider-quota] grix-relay queried: success=${r.success}`+(r.balance?` balance=${r.balance.remaining} ${r.balance.unit}`:"")+(r.error?` error=${r.error}`:"")),r.success?r:null}catch(r){return u.warn(e.name,`[provider-quota] grix-relay query failed: ${r instanceof Error?r.message:String(r)}`),null}}if(o?.providerId==="openai_codex")try{const r=await S(e.config.agent.env?.PI_CODING_AGENT_DIR);return r.quota.success?r.quota:null}catch(r){return u.warn(e.name,`[provider-quota] openai_codex query failed: ${r instanceof Error?r.message:String(r)}`),null}const t=await e.resolveProviderQuotaSource(o);if(!t)return null;const n=y.cacheKey(t);if(!a&&e.isRateLimitsCacheFresh(e.cachedProviderQuotaSampledAtMs)&&e.cachedProviderQuota&&e.cachedProviderQuotaKey===n)return e.cachedProviderQuota;try{const r=await y.query(t,{fresh:a}),i=r.quota;return e.cachedProviderQuota=i,e.cachedProviderQuotaSampledAtMs=r.sampledAt,e.cachedProviderQuotaKey=r.cacheKey,u.info(e.name,`[provider-quota] queried: provider=${i.provider} success=${i.success}`+(i.tiers.length>0?` tiers=${i.tiers.map(d=>`${d.name}=${d.usedPercent}%`).join(",")}`:"")+(i.balance?` balance=${i.balance.remaining} ${i.balance.unit}`:"")+(i.error?` error=${i.error}`:"")),i}catch(r){return u.warn(e.name,`[provider-quota] query failed: ${r instanceof Error?r.message:String(r)}`),null}}function X(e){e.stopped||e.providerQuotaTimer||(e.providerQuotaTimer=setInterval(()=>{if(e.stopped){e.stopProviderQuotaTimer();return}e.refreshAndPushProviderQuota().catch(()=>{})},w),u.info(e.name,`[provider-quota-timer] started (interval=${w}ms)`))}function Z(e){e.providerQuotaTimer&&(clearInterval(e.providerQuotaTimer),e.providerQuotaTimer=null,u.info(e.name,"[provider-quota-timer] stopped"))}async function ee(e,a=!1){try{let o;if(e.config.aibot.clientType==="kiro")o=await E(),e.cachedProviderQuota=o,e.cachedProviderQuotaSampledAtMs=Date.now(),e.cachedProviderQuotaKey="kiro";else{const t=[...e.sessionBindings.entries()].filter(([n,r])=>!!r&&e.sessionProviderHints.has(n));if(t.length>0&&await Promise.all(t.map(([n,r])=>e.refreshProviderQuotaForSession(n,r,a))),t.length===e.sessionBindings.size&&t.length>0)return;o=await e.maybeQueryProviderQuota(a)}o?.success&&e.pushProviderQuotaToBindings(o,e.sessionProviderHints.size>0)}catch{}}function re(e,a,o=!1){const t=(e.config.adapterType??"acp")==="claude"&&a.provider==="grix",n=e.providerQuotaToRateLimits(a);for(const[r,i]of e.sessionBindings.entries()){if(!i||o&&e.sessionProviderHints.has(r))continue;if((e.config.adapterType??"acp")==="deepseek-harness"){const l=e.pool.getSlot(r)?.adapter;if(l instanceof H){l.updateProviderQuotaSnapshot(a);continue}}const d={provider_quota:a};t?d.rate_limits=null:n&&(d.rate_limits=n);const c=e.cachedAcpContextWindow;c&&("usedPercentage"in c?d.context_window={usedPercentage:c.usedPercentage,remainingPercentage:100-c.usedPercentage}:d.context_window=c),e.aibotHandle.sendUpdateBindingCard({session_id:r,worker_status:"ready",cwd:i,meta:d})}}function ie(e,a,o="standard",t=e.cachedProviderQuota,n=e.cachedProviderQuotaSampledAtMs){const r={...a??{}};if(!t?.success||(r.provider_quota||(r.provider_quota=t),r.rate_limits))return r;if(o==="codex"){const d=x(t,n??Date.now());return d&&(r.rate_limits=d.rateLimits,r.rate_limit_primary_percent=d.primaryPercent,r.rate_limit_secondary_percent=d.secondaryPercent,r.rate_limit_primary_window_min=d.primaryWindowMin,r.rate_limit_secondary_window_min=d.secondaryWindowMin),r}const i=T(t,n??Date.now());return i&&(r.rate_limits=i),r}function ae(e,a,o,t){let n=e.cachedProviderQuota,r=e.cachedProviderQuotaSampledAtMs,i=!1;if(o){const c=typeof a?.model_provider=="string"?a.model_provider:void 0,l=typeof a?.model_id=="string"?a.model_id:void 0,v=Q(c)??m(c)?.id??m(l)?.id??(A(c)?"openai_codex":null);if(v||l){const s=c?.trim().toLowerCase()??"",p=s==="grix"||s.startsWith("grix-"),P={...v?{providerId:v}:{},...l?{model:l}:{},...!!c&&!p&&!v?{disabled:!0}:{}},g=e.sessionProviderHints.get(o),_=g?.providerId!==P.providerId||g?.model!==P.model||g?.disabled!==P.disabled;e.sessionProviderHints.set(o,P),e.sessionProviderMeta.set(o,{...a??{}}),_&&e.sessionProviderQuotas.delete(o),(_||!e.sessionProviderQuotas.has(o))&&t&&e.refreshProviderQuotaForSession(o,t,!1)}const f=e.sessionProviderQuotas.get(o);i=e.sessionProviderHints.has(o),i&&(n=null,r=null),f&&(n=f.quota,r=f.sampledAt)}const d=e.enrichProviderQuotaMeta(a,"standard",n,r);return i&&(d.provider_quota||(d.provider_quota=null),d.rate_limits||(d.rate_limits=null)),Object.keys(d).length>0?{meta:d}:{}}async function oe(e,a,o,t){const n=e.sessionProviderHints.get(a);if(!n)return;if(n.disabled){u.debug(e.name,`[provider-quota] session skip: session=${a} reason=hint_disabled providerId=${n.providerId??""} model=${n.model??""}`);return}const r=`${n.providerId??""}|${n.model??""}|false`;try{let i,d,c;if(n.providerId==="openai_codex"){const s=e.sessionProviderQuotas.get(a);if(!t&&s&&s.quota.success&&s.cacheKey.startsWith("openai_codex|")&&e.isRateLimitsCacheFresh(s.sampledAt))i=s.quota,d=s.sampledAt,c=s.cacheKey;else{const p=await S(e.config.agent.env?.PI_CODING_AGENT_DIR);i=p.quota,d=Date.now(),c=q(p.accountKey)}}else{const s=await e.resolveProviderQuotaSource(n);if(!s){u.debug(e.name,`[provider-quota] session skip: session=${a} reason=no_source providerId=${n.providerId??""} model=${n.model??""}`);return}const p=await y.query(s,{fresh:t});i=p.quota,d=p.sampledAt,c=p.cacheKey}const l=e.sessionProviderHints.get(a);if(`${l?.providerId??""}|${l?.model??""}|${l?.disabled===!0}`!==r)return;if(u.info(e.name,`[provider-quota] queried: provider=${i.provider} success=${i.success}`+(i.tiers.length>0?` tiers=${i.tiers.map(s=>`${s.name}=${s.usedPercent}%`).join(",")}`:"")+(i.balance?` balance=${i.balance.remaining} ${i.balance.unit}`:"")+(i.error?` error=${i.error}`:"")+` session=${a}`),!i.success){const s=e.sessionProviderQuotas.get(a);(!s?.quota.success||s.cacheKey!==c)&&e.sessionProviderQuotas.delete(a);return}e.sessionProviderQuotas.set(a,{quota:i,sampledAt:d,cacheKey:c});const f=e.enrichProviderQuotaMeta(e.sessionProviderMeta.get(a),"standard",i,d);e.aibotHandle.sendUpdateBindingCard({session_id:a,worker_status:"ready",cwd:o,meta:f})}catch(i){u.warn(e.name,`[provider-quota] session query failed: session=${a} ${i instanceof Error?i.message:String(i)}`)}}function te(e,a,o,t){const n=o.trim();if(!a||!n)return;const r=t?.trim()||void 0,i=`${a}|${r??""}|${n}`,d=Date.now();e.lastModelSwitchQuotaRefresh&&e.lastModelSwitchQuotaRefresh.key===i&&d-e.lastModelSwitchQuotaRefresh.at<k||(e.lastModelSwitchQuotaRefresh={key:i,at:d},e.doRefreshQuotaAfterModelSwitch(a,n,r).catch(c=>{u.warn(e.name,`[provider-quota] model-switch refresh failed: session=${a} model=${n} ${c instanceof Error?c.message:String(c)}`)}))}async function ne(e,a,o,t){const n=e.sessionProviderHints.get(a);if(n||t){const i=t??m(o)?.id??n?.providerId,d={...i?{providerId:i}:{},model:o,...n?.disabled?{disabled:!0}:{}},c=n?.providerId!==d.providerId||n?.model!==d.model||n?.disabled!==d.disabled;e.sessionProviderHints.set(a,d),c&&e.sessionProviderQuotas.delete(a);const l=e.sessionBindings.get(a)??e.bindingStore.get(a)?.cwd??"";(c||!e.sessionProviderQuotas.has(a))&&l&&await e.refreshProviderQuotaForSession(a,l,!0);return}const r=await e.maybeQueryProviderQuota(!0,{model:o});r?.success&&e.pushProviderQuotaToBindings(r,e.sessionProviderHints.size>0)}export{Y as PROVIDER_QUOTA_HOST_FIELDS,z as PROVIDER_QUOTA_HOST_METHODS,ne as doRefreshQuotaAfterModelSwitch,ie as enrichProviderQuotaMeta,J as maybeQueryProviderQuota,ae as providerQuotaMetaPayload,re as pushProviderQuotaToBindings,ee as refreshAndPushProviderQuota,oe as refreshProviderQuotaForSession,te as refreshQuotaAfterModelSwitch,j as resolveProviderQuotaSource,X as startProviderQuotaTimer,Z as stopProviderQuotaTimer};
|
|
1
|
+
import{sharedProviderQuotaService as Q,detectProviderFromModel as m,normalizeProviderId as P,readPiProviderSettings as x,readOpenCodeProviderSettings as A,isOpenaiCodexProviderName as T,queryOpenaiCodexQuota as S,openaiCodexQuotaCacheKey as $,resolveKimiProviderSettings as q,providerQuotaToRateLimits as R,providerQuotaToCodexRateLimits as H,providerQuotaToolbarExtras as E,resolveOpenCodeConsoleQuotaKey as O,OPENCODE_CONSOLE_ORIGIN as D}from"../core/provider-quota/index.js";import{queryKiroQuota as b}from"../core/provider-quota/kiro.js";import{queryGrixRelayWalletBalance as M}from"../core/provider-quota/grix-relay.js";import{DshJsonRpcAdapter as C,resolveDshHome as U,readDshCredentials as k}from"../adapter/deepseek-harness/index.js";import{readSettingsEnv as I}from"../adapter/claude/model-list.js";import{readCodexProviderSettings as L}from"../adapter/codex/codex-trust.js";import{agentIdOf as w}from"../adapter/shared/native-provider-config.js";import{log as u}from"../core/log/index.js";const K=30*1e3,B=10*1e3,J=["isRateLimitsCacheFresh","isGrixRelayActive","providerQuotaToRateLimits","resolveProviderQuotaSource","maybeQueryProviderQuota","stopProviderQuotaTimer","refreshAndPushProviderQuota","pushProviderQuotaToBindings","enrichProviderQuotaMeta","refreshProviderQuotaForSession","doRefreshQuotaAfterModelSwitch"],X=["name","config","stopped","aibotHandle","pool","bindingStore","sessionBindings","sessionProviderHints","sessionProviderQuotas","sessionProviderMeta","cachedAcpContextWindow","cachedProviderQuota","cachedProviderQuotaKey","cachedProviderQuotaSampledAtMs","providerQuotaTimer","lastModelSwitchQuotaRefresh"];async function Z(e,a){if(a?.disabled||a?.providerId==="openai_codex")return null;let o=e.config.providerBaseUrl??e.config.agent.provider?.baseUrl,n=e.config.providerApiKey??e.config.agent.provider?.apiKey;if((e.config.adapterType??"acp")==="deepseek-harness"){if(n??=e.config.agent.env?.DEEPSEEK_API_KEY,o??=e.config.agent.env?.DEEPSEEK_BASE_URL,!n){const r=U(typeof e.config.adapterOptions?.dshHome=="string"?e.config.adapterOptions.dshHome:void 0,e.config.agent.env);try{const i=await k(r),d=typeof i.DEEPSEEK_API_KEY=="string"?i.DEEPSEEK_API_KEY.trim():"";d&&(n=d,o??=typeof i.DEEPSEEK_BASE_URL=="string"&&i.DEEPSEEK_BASE_URL.trim()?i.DEEPSEEK_BASE_URL.trim():"https://api.deepseek.com",u.debug(e.name,"[provider-quota] deepseek-harness: resolved official DeepSeek API key from DSH credential store ($DSH_HOME)"))}catch(i){u.warn(e.name,`[provider-quota] deepseek-harness: could not read DSH credential store: ${i instanceof Error?i.message:String(i)}`)}}o??=n?"https://api.deepseek.com":void 0}if((!o||!n)&&(e.config.adapterType??"acp")==="claude"){const r=I();o||(o=(r.ANTHROPIC_BASE_URL??"").trim()||void 0),n||(n=(r.ANTHROPIC_API_KEY??"").trim()||(r.ANTHROPIC_AUTH_TOKEN??"").trim()||void 0)}if((!o||!n)&&(e.config.adapterType??"acp")==="codex"){const r=L();!o&&r.baseUrl&&(o=r.baseUrl),!n&&r.apiKey&&(n=r.apiKey)}if((!o||!n)&&(e.config.adapterType??"acp")==="acp"&&e.config.aibot.clientType==="kimi"){const r=await q();!o&&r.baseUrl&&(o=r.baseUrl),!n&&r.apiKey&&(n=r.apiKey)}if((!o||!n)&&(e.config.adapterType??"acp")==="pi"){const r=x(a,e.config.agent.env?.PI_CODING_AGENT_DIR);!o&&r.baseUrl&&(o=r.baseUrl),!n&&r.apiKey&&(n=r.apiKey)}if((!o||!n)&&(e.config.adapterType??"acp")==="opencode"){const r=A(a,void 0,w(e.config.agent.command||"opencode")||"opencode");!o&&r.baseUrl&&(o=r.baseUrl),!n&&r.apiKey&&(n=r.apiKey)}if((e.config.adapterType??"acp")==="opencode"){const r=P(a?.providerId);if(!r||r==="opencode_go"){const i=O({quotaApiKey:e.config.agent.provider?.quotaApiKey,envToken:e.config.agent.env?.OPENCODE_CONSOLE_TOKEN,providerApiKey:n,vendor:w(e.config.agent.command||"opencode")||"opencode"});if(i)return{baseUrl:D,apiKey:i,providerId:"opencode_go"}}}if(!o||!n)return null;const t=P(a?.providerId)??m(a?.model)?.id??P(e.config.agent.provider?.providerId)??m(e.config.agent.provider?.model)?.id;return{baseUrl:o,...e.config.agent.provider?.quotaBaseUrl?{quotaBaseUrl:e.config.agent.provider.quotaBaseUrl}:{},apiKey:n,...t?{providerId:t}:{}}}async function ee(e,a=!1,o){if(e.config.aibot.clientType==="kiro"){if(!a&&e.isRateLimitsCacheFresh(e.cachedProviderQuotaSampledAtMs)&&e.cachedProviderQuota)return e.cachedProviderQuota;try{const r=await b();return e.cachedProviderQuota=r,e.cachedProviderQuotaSampledAtMs=Date.now(),e.cachedProviderQuotaKey="kiro",u.info(e.name,`[provider-quota] kiro queried: success=${r.success}`+(r.balance?` balance=${r.balance.remaining} ${r.balance.unit}`:"")+(r.planName?` plan=${r.planName}`:"")+(r.error?` error=${r.error}`:"")),r}catch(r){return u.warn(e.name,`[provider-quota] kiro query failed: ${r instanceof Error?r.message:String(r)}`),null}}if((e.config.adapterType??"acp")==="claude"&&e.isGrixRelayActive()){if(!a&&e.cachedProviderQuotaKey==="grix-relay"&&e.isRateLimitsCacheFresh(e.cachedProviderQuotaSampledAtMs)&&e.cachedProviderQuota)return e.cachedProviderQuota;try{const r=await M({wsUrl:e.config.aibot.url,apiKey:e.config.aibot.apiKey});return r.success&&(e.cachedProviderQuota=r,e.cachedProviderQuotaSampledAtMs=Date.now(),e.cachedProviderQuotaKey="grix-relay"),u.info(e.name,`[provider-quota] grix-relay queried: success=${r.success}`+(r.balance?` balance=${r.balance.remaining} ${r.balance.unit}`:"")+(r.error?` error=${r.error}`:"")),r.success?r:null}catch(r){return u.warn(e.name,`[provider-quota] grix-relay query failed: ${r instanceof Error?r.message:String(r)}`),null}}if(o?.providerId==="openai_codex")try{const r=await S(e.config.agent.env?.PI_CODING_AGENT_DIR);return r.quota.success?r.quota:null}catch(r){return u.warn(e.name,`[provider-quota] openai_codex query failed: ${r instanceof Error?r.message:String(r)}`),null}const n=await e.resolveProviderQuotaSource(o);if(!n)return null;const t=Q.cacheKey(n);if(!a&&e.isRateLimitsCacheFresh(e.cachedProviderQuotaSampledAtMs)&&e.cachedProviderQuota&&e.cachedProviderQuotaKey===t)return e.cachedProviderQuota;try{const r=await Q.query(n,{fresh:a}),i=r.quota;return e.cachedProviderQuota=i,e.cachedProviderQuotaSampledAtMs=r.sampledAt,e.cachedProviderQuotaKey=r.cacheKey,u.info(e.name,`[provider-quota] queried: provider=${i.provider} success=${i.success}`+(i.tiers.length>0?` tiers=${i.tiers.map(d=>`${d.name}=${d.usedPercent}%`).join(",")}`:"")+(i.balance?` balance=${i.balance.remaining} ${i.balance.unit}`:"")+(i.error?` error=${i.error}`:"")),i}catch(r){return u.warn(e.name,`[provider-quota] query failed: ${r instanceof Error?r.message:String(r)}`),null}}function re(e){e.stopped||e.providerQuotaTimer||(e.providerQuotaTimer=setInterval(()=>{if(e.stopped){e.stopProviderQuotaTimer();return}e.refreshAndPushProviderQuota().catch(()=>{})},K),u.info(e.name,`[provider-quota-timer] started (interval=${K}ms)`))}function ie(e){e.providerQuotaTimer&&(clearInterval(e.providerQuotaTimer),e.providerQuotaTimer=null,u.info(e.name,"[provider-quota-timer] stopped"))}async function ae(e,a=!1){try{let o;if(e.config.aibot.clientType==="kiro")o=await b(),e.cachedProviderQuota=o,e.cachedProviderQuotaSampledAtMs=Date.now(),e.cachedProviderQuotaKey="kiro";else{const n=[...e.sessionBindings.entries()].filter(([t,r])=>!!r&&e.sessionProviderHints.has(t));if(n.length>0&&await Promise.all(n.map(([t,r])=>e.refreshProviderQuotaForSession(t,r,a))),n.length===e.sessionBindings.size&&n.length>0)return;o=await e.maybeQueryProviderQuota(a)}o?.success&&e.pushProviderQuotaToBindings(o,e.sessionProviderHints.size>0)}catch{}}function oe(e,a,o=!1){const n=(e.config.adapterType??"acp")==="claude"&&a.provider==="grix",t=e.providerQuotaToRateLimits(a);for(const[r,i]of e.sessionBindings.entries()){if(!i||o&&e.sessionProviderHints.has(r))continue;if((e.config.adapterType??"acp")==="deepseek-harness"){const p=e.pool.getSlot(r)?.adapter;if(p instanceof C){p.updateProviderQuotaSnapshot(a);continue}}const d={provider_quota:a};n?d.rate_limits=null:t&&(d.rate_limits=t),Object.assign(d,E(a));const c=e.cachedAcpContextWindow;c&&("usedPercentage"in c?d.context_window={usedPercentage:c.usedPercentage,remainingPercentage:100-c.usedPercentage}:d.context_window=c),e.aibotHandle.sendUpdateBindingCard({session_id:r,worker_status:"ready",cwd:i,meta:d})}}function ne(e,a,o="standard",n=e.cachedProviderQuota,t=e.cachedProviderQuotaSampledAtMs){const r={...a??{}};if(!n?.success||(r.provider_quota||(r.provider_quota=n),r.rate_limits))return r;if(o==="codex"){const c=H(n,t??Date.now());return c&&(r.rate_limits=c.rateLimits,r.rate_limit_primary_percent=c.primaryPercent,r.rate_limit_secondary_percent=c.secondaryPercent,r.rate_limit_primary_window_min=c.primaryWindowMin,r.rate_limit_secondary_window_min=c.secondaryWindowMin),r}const i=R(n,t??Date.now());i&&(r.rate_limits=i);const d=E(n);return d.credits&&r.credits===void 0&&(r.credits=d.credits),d.extra_limits&&r.extra_limits===void 0&&(r.extra_limits=d.extra_limits),r}function te(e,a,o,n){let t=e.cachedProviderQuota,r=e.cachedProviderQuotaSampledAtMs,i=!1;if(o){const c=typeof a?.model_provider=="string"?a.model_provider:void 0,p=typeof a?.model_id=="string"?a.model_id:void 0,v=P(c)??m(c)?.id??m(p)?.id??(T(c)?"openai_codex":null);if(v||p){const s=c?.trim().toLowerCase()??"",l=s==="grix"||s.startsWith("grix-"),g={...v?{providerId:v}:{},...p?{model:p}:{},...!!c&&!l&&!v?{disabled:!0}:{}},y=e.sessionProviderHints.get(o),_=y?.providerId!==g.providerId||y?.model!==g.model||y?.disabled!==g.disabled;e.sessionProviderHints.set(o,g),e.sessionProviderMeta.set(o,{...a??{}}),_&&e.sessionProviderQuotas.delete(o),(_||!e.sessionProviderQuotas.has(o))&&n&&e.refreshProviderQuotaForSession(o,n,!1)}const f=e.sessionProviderQuotas.get(o);i=e.sessionProviderHints.has(o),i&&(t=null,r=null),f&&(t=f.quota,r=f.sampledAt)}const d=e.enrichProviderQuotaMeta(a,"standard",t,r);return i&&(d.provider_quota||(d.provider_quota=null),d.rate_limits||(d.rate_limits=null)),Object.keys(d).length>0?{meta:d}:{}}async function de(e,a,o,n){const t=e.sessionProviderHints.get(a);if(!t)return;if(t.disabled){u.debug(e.name,`[provider-quota] session skip: session=${a} reason=hint_disabled providerId=${t.providerId??""} model=${t.model??""}`);return}const r=`${t.providerId??""}|${t.model??""}|false`;try{let i,d,c;if(t.providerId==="openai_codex"){const s=e.sessionProviderQuotas.get(a);if(!n&&s&&s.quota.success&&s.cacheKey.startsWith("openai_codex|")&&e.isRateLimitsCacheFresh(s.sampledAt))i=s.quota,d=s.sampledAt,c=s.cacheKey;else{const l=await S(e.config.agent.env?.PI_CODING_AGENT_DIR);i=l.quota,d=Date.now(),c=$(l.accountKey)}}else{const s=await e.resolveProviderQuotaSource(t);if(!s){u.debug(e.name,`[provider-quota] session skip: session=${a} reason=no_source providerId=${t.providerId??""} model=${t.model??""}`);return}const l=await Q.query(s,{fresh:n});i=l.quota,d=l.sampledAt,c=l.cacheKey}const p=e.sessionProviderHints.get(a);if(`${p?.providerId??""}|${p?.model??""}|${p?.disabled===!0}`!==r)return;if(u.info(e.name,`[provider-quota] queried: provider=${i.provider} success=${i.success}`+(i.tiers.length>0?` tiers=${i.tiers.map(s=>`${s.name}=${s.usedPercent}%`).join(",")}`:"")+(i.balance?` balance=${i.balance.remaining} ${i.balance.unit}`:"")+(i.error?` error=${i.error}`:"")+` session=${a}`),!i.success){const s=e.sessionProviderQuotas.get(a);(!s?.quota.success||s.cacheKey!==c)&&e.sessionProviderQuotas.delete(a);return}e.sessionProviderQuotas.set(a,{quota:i,sampledAt:d,cacheKey:c});const f=e.enrichProviderQuotaMeta(e.sessionProviderMeta.get(a),"standard",i,d);e.aibotHandle.sendUpdateBindingCard({session_id:a,worker_status:"ready",cwd:o,meta:f})}catch(i){u.warn(e.name,`[provider-quota] session query failed: session=${a} ${i instanceof Error?i.message:String(i)}`)}}function ce(e,a,o,n){const t=o.trim();if(!a||!t)return;const r=n?.trim()||void 0,i=`${a}|${r??""}|${t}`,d=Date.now();e.lastModelSwitchQuotaRefresh&&e.lastModelSwitchQuotaRefresh.key===i&&d-e.lastModelSwitchQuotaRefresh.at<B||(e.lastModelSwitchQuotaRefresh={key:i,at:d},e.doRefreshQuotaAfterModelSwitch(a,t,r).catch(c=>{u.warn(e.name,`[provider-quota] model-switch refresh failed: session=${a} model=${t} ${c instanceof Error?c.message:String(c)}`)}))}async function se(e,a,o,n){const t=e.sessionProviderHints.get(a);if(t||n){const i=n??m(o)?.id??t?.providerId,d={...i?{providerId:i}:{},model:o,...t?.disabled?{disabled:!0}:{}},c=t?.providerId!==d.providerId||t?.model!==d.model||t?.disabled!==d.disabled;e.sessionProviderHints.set(a,d),c&&e.sessionProviderQuotas.delete(a);const p=e.sessionBindings.get(a)??e.bindingStore.get(a)?.cwd??"";(c||!e.sessionProviderQuotas.has(a))&&p&&await e.refreshProviderQuotaForSession(a,p,!0);return}const r=await e.maybeQueryProviderQuota(!0,{model:o});r?.success&&e.pushProviderQuotaToBindings(r,e.sessionProviderHints.size>0)}export{X as PROVIDER_QUOTA_HOST_FIELDS,J as PROVIDER_QUOTA_HOST_METHODS,se as doRefreshQuotaAfterModelSwitch,ne as enrichProviderQuotaMeta,ee as maybeQueryProviderQuota,te as providerQuotaMetaPayload,oe as pushProviderQuotaToBindings,ae as refreshAndPushProviderQuota,de as refreshProviderQuotaForSession,ce as refreshQuotaAfterModelSwitch,Z as resolveProviderQuotaSource,re as startProviderQuotaTimer,ie as stopProviderQuotaTimer};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readJSONFile as o,writeJSONFileAtomic as
|
|
1
|
+
import{readJSONFile as o,writeJSONFileAtomic as e}from"../util/json-file.js";function n(t){const r=o(t);return r&&typeof r=="object"&&"owners"in r&&Array.isArray(r.owners)?r.owners.filter(i=>typeof i=="string"&&i.trim().length>0):[]}async function s(t,r){await e(t,{owners:r})}export{n as readAllowlist,s as writeAllowlist};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{readdir as r,stat as m}from"node:fs/promises";import{join as l,extname as d}from"node:path";const x={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",md:"text/markdown",csv:"text/csv",json:"application/json",xml:"application/xml",yaml:"text/yaml",yml:"text/yaml",html:"text/html",css:"text/css",js:"text/javascript",ts:"text/typescript",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",gz:"application/gzip",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",mkv:"video/x-matroska",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac",aac:"audio/aac"};function n(a){const p=d(a).slice(1).toLowerCase();return x[p]}async function f(a,p=!1){const c=await r(a,{withFileTypes:!0}),s=[];for(const
|
|
1
|
+
import{readdir as r,stat as m}from"node:fs/promises";import{join as l,extname as d}from"node:path";const x={pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",md:"text/markdown",csv:"text/csv",json:"application/json",xml:"application/xml",yaml:"text/yaml",yml:"text/yaml",html:"text/html",css:"text/css",js:"text/javascript",ts:"text/typescript",zip:"application/zip",rar:"application/x-rar-compressed","7z":"application/x-7z-compressed",tar:"application/x-tar",gz:"application/gzip",jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",mp4:"video/mp4",mov:"video/quicktime",avi:"video/x-msvideo",mkv:"video/x-matroska",webm:"video/webm",mp3:"audio/mpeg",wav:"audio/wav",flac:"audio/flac",aac:"audio/aac"};function n(a){const p=d(a).slice(1).toLowerCase();return x[p]}async function f(a,p=!1){const c=await r(a,{withFileTypes:!0}),s=[];for(const t of c){if(!p&&t.name.startsWith("."))continue;const i=l(a,t.name),e={id:i,name:t.name,is_directory:t.isDirectory()};try{if(t.isDirectory()){const o=await m(i);e.modified_at=o.mtime.toISOString()}else{const o=await m(i);e.size=o.size,e.modified_at=o.mtime.toISOString(),e.mime_type=n(t.name)}}catch{}s.push(e)}return s.sort((t,i)=>t.is_directory!==i.is_directory?t.is_directory?-1:1:t.name.localeCompare(i.name)),s}export{f as listFiles,n as resolveMimeType};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{detectProvider as
|
|
1
|
+
import{detectProvider as r,detectProviderFromModel as i,normalizeProviderId as a,queryProviderQuota as t,readKimiProviderSettings as d,readOpenCodeProviderSettings as s,readPiProviderSettings as n,resolveKimiProviderSettings as p}from"./providers.js";import{isOpenaiCodexProviderName as C,parseOpenaiCodexUsage as u,queryOpenaiCodexQuota as l,resolveOpenaiCodexAccessToken as O,openaiCodexQuotaCacheKey as x}from"./openai-codex.js";import{ProviderQuotaService as P,sharedProviderQuotaService as Q,resolveQuotaBaseUrl as y}from"./service.js";import{providerQuotaToRateLimits as f,providerQuotaToCodexRateLimits as S,providerQuotaToolbarExtras as K}from"./presentation.js";import{findOpenCodeConsoleKey as q,isOpenCodeConsoleKey as E,OPENCODE_CONSOLE_ORIGIN as G,parseOpenCodeGoQuota as N,queryOpenCodeGoQuota as R,resolveOpenCodeConsoleQuotaKey as T}from"./opencode-go.js";import{queryGrixRelayWalletBalance as L}from"./grix-relay.js";export{G as OPENCODE_CONSOLE_ORIGIN,P as ProviderQuotaService,r as detectProvider,i as detectProviderFromModel,q as findOpenCodeConsoleKey,E as isOpenCodeConsoleKey,C as isOpenaiCodexProviderName,a as normalizeProviderId,x as openaiCodexQuotaCacheKey,N as parseOpenCodeGoQuota,u as parseOpenaiCodexUsage,S as providerQuotaToCodexRateLimits,f as providerQuotaToRateLimits,K as providerQuotaToolbarExtras,L as queryGrixRelayWalletBalance,R as queryOpenCodeGoQuota,l as queryOpenaiCodexQuota,t as queryProviderQuota,d as readKimiProviderSettings,s as readOpenCodeProviderSettings,n as readPiProviderSettings,p as resolveKimiProviderSettings,T as resolveOpenCodeConsoleQuotaKey,O as resolveOpenaiCodexAccessToken,y as resolveQuotaBaseUrl,Q as sharedProviderQuotaService};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{readFileSync as O}from"node:fs";import{homedir as A}from"node:os";import{join as y}from"node:path";const g="https://opencode.ai/console",h=1e4,l=100000000n;function b(t){return typeof t=="string"&&t.trim().startsWith("oc_sk_")}function i(t){return{provider:"opencode_go",providerLabel:"OpenCode Go",planName:null,tiers:[],balance:null,success:!1,error:t}}function c(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:null}function a(t){if(typeof t=="bigint")return t;if(typeof t=="number"&&Number.isFinite(t))return BigInt(Math.trunc(t));if(typeof t!="string"||!/^-?\d+$/.test(t.trim()))return null;try{return BigInt(t.trim())}catch{return null}}function k(t,n){return n<=0n?0:t>=n?100:Number((t*200n+n)/(n*2n))}function N(t){const n=t<0n,e=n?-t:t,o=e/l,r=e%l,s=Number(o)+Number(r)/Number(l);return n?-s:s}function _(t){return t==="go"?"Go":t==="go-plus"?"Go Plus":typeof t=="string"&&t.trim()?t:null}function f(t,n,e){const o=c(e);if(!o)return null;const r=a(o.limitMicroCents),s=a(o.usedMicroCents);if(r===null||s===null)return null;const u=typeof o.resetsAt=="string"?o.resetsAt:null;return{name:t,label:n,usedPercent:k(s,r),resetsAt:u}}function G(t,n){const e=c(t);if(!e)return i("Unexpected Go status response");const o=c(e.access),r=c(o?.meters),s=[f("five_hour","Rolling",r?.fiveHour),f("weekly_limit","Weekly",r?.week),f("monthly","Monthly",r?.month)].filter(C=>C!==null),u=c(n),d=u?a(u.availableMicroCents):null,m=d===null?null:{kind:"currency",remaining:N(d),total:null,used:null,unit:"USD"};return s.length===0&&!m?i("Go status did not include usage windows or credits"):{provider:"opencode_go",providerLabel:"OpenCode Go",planName:_(e.product),tiers:s,balance:m,success:!0,error:null}}async function j(t){const n={Authorization:`Bearer ${t.trim()}`,Accept:"application/json"};try{const[e,o]=await Promise.all([fetch(`${g}/api/go/status`,{method:"GET",headers:n,signal:AbortSignal.timeout(h)}),fetch(`${g}/api/billing/status`,{method:"GET",headers:n,signal:AbortSignal.timeout(h)})]);if(e.status===401||e.status===403)return i(`Authentication failed (HTTP ${e.status})`);if(!e.ok)return i(`Go status API error (HTTP ${e.status})`);const r=await e.json(),s=o.ok?await o.json():null;return G(r,s)}catch(e){return i(`Network error: ${e instanceof Error?e.message:String(e)}`)}}function p(t,n){if(!t||typeof t!="object")return;if(Array.isArray(t)){for(const o of t)p(o,n);return}const e=t;for(const o of["key","apiKey","api_key"]){const r=e[o],s=typeof r=="string"?r.trim():void 0;b(s)&&n.push(s)}for(const o of Object.values(e))p(o,n)}function T(t,n="opencode"){const e=t||A(),o=[y(e,".local","share",n,"auth.json"),y(e,".config",n,`${n}.json`)],r=[];for(const s of o)try{p(JSON.parse(O(s,"utf8")),r)}catch{}return r[0]}function M(t){for(const n of[t.quotaApiKey,t.envToken,t.providerApiKey]){const e=n?.trim();if(b(e))return e}return T(t.home,t.vendor??"opencode")}export{g as OPENCODE_CONSOLE_ORIGIN,T as findOpenCodeConsoleKey,b as isOpenCodeConsoleKey,k as openCodeGoUsedPercent,G as parseOpenCodeGoQuota,j as queryOpenCodeGoQuota,M as resolveOpenCodeConsoleQuotaKey};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function a(e){if(!e)return 0;const
|
|
1
|
+
function a(e){if(!e)return 0;const r=Date.parse(e);return Number.isFinite(r)?Math.floor(r/1e3):0}function l(e,r=Date.now()){const n=e.tiers.find(i=>i.name==="five_hour"),t=e.tiers.find(i=>i.name==="weekly_limit");return n||t?{...n?{fiveHour:{usedPercentage:n.usedPercent,resetsAt:a(n.resetsAt)}}:{},...t?{sevenDay:{usedPercentage:t.usedPercent,resetsAt:a(t.resetsAt)}}:{},sampledAt:r}:e.balance?{credit:{remaining:e.balance.remaining,total:e.balance.total,used:e.balance.used,unit:e.balance.unit,resetsAt:a(e.balance.resetsAt??null),...e.balance.kind?{kind:e.balance.kind}:{}},planName:e.planName,sampledAt:r}:null}function d(e){if(e.provider!=="opencode_go"||!e.success)return{};const r={},n=e.tiers.find(t=>t.name==="monthly");return n&&(r.extra_limits=[{id:"monthly",label:n.label||"Monthly",usedPercent:n.usedPercent,windowMinutes:720*60,resetsAt:n.resetsAt}]),e.balance&&(r.credits={hasCredits:!0,unlimited:!1,balance:e.balance.remaining}),r}function o(e,r=Date.now()){const n=e.tiers.find(s=>s.name==="five_hour"),t=e.tiers.find(s=>s.name==="weekly_limit");if(n||t){const s={credits:{hasCredits:!0,unlimited:!1,balance:null},sampledAt:r};return n&&(s.primary={usedPercent:n.usedPercent,windowMinutes:300,resetsAt:n.resetsAt}),t&&(s.secondary={usedPercent:t.usedPercent,windowMinutes:10080,resetsAt:t.resetsAt}),{rateLimits:s,primaryPercent:n?.usedPercent??0,secondaryPercent:t?.usedPercent??0,primaryWindowMin:n?300:0,secondaryWindowMin:t?10080:0}}if(!e.balance)return null;const i=e.balance,c=i.total&&i.total>0?Math.min(100,(i.used??i.total-i.remaining)/i.total*100):0;return{rateLimits:{primary:{usedPercent:c,windowMinutes:0,resetsAt:null},secondary:{usedPercent:0,windowMinutes:0,resetsAt:null},credits:{hasCredits:!0,unlimited:!1,balance:i.remaining},sampledAt:r},primaryPercent:c,secondaryPercent:0,primaryWindowMin:0,secondaryWindowMin:0}}export{o as providerQuotaToCodexRateLimits,l as providerQuotaToRateLimits,d as providerQuotaToolbarExtras};
|