grix-connector 4.19.0 → 5.0.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.
Files changed (38) hide show
  1. package/README.md +1 -1
  2. package/dist/adapter/acp/acp-adapter.js +12 -12
  3. package/dist/adapter/agy/agy-adapter.js +10 -10
  4. package/dist/adapter/agy/model-list.js +2 -2
  5. package/dist/adapter/agy/quota.js +5 -5
  6. package/dist/adapter/claude/claude-adapter.js +20 -20
  7. package/dist/adapter/claude/claude-bridge-server.js +1 -1
  8. package/dist/adapter/claude/claude-tools.js +1 -1
  9. package/dist/adapter/claude/claude-worker-client.js +1 -1
  10. package/dist/adapter/claude/mcp-http-launcher.js +2 -2
  11. package/dist/adapter/claude/result-timeout.js +1 -1
  12. package/dist/adapter/cursor/cursor-adapter.js +12 -11
  13. package/dist/adapter/deepseek-harness/event-mapper.js +1 -1
  14. package/dist/adapter/deepseek-harness/jsonrpc-adapter.js +3 -3
  15. package/dist/adapter/pi/pi-adapter.js +5 -4
  16. package/dist/adapter/pi/pi-grix-tools-extension.js +2 -0
  17. package/dist/assets/dsh-bridge/grix-dsh-bridge-5.0.0.tgz +0 -0
  18. package/dist/assets/dsh-bridge/manifest.json +6 -6
  19. package/dist/bridge/bridge.js +1 -1
  20. package/dist/bridge/rate-limits.js +1 -1
  21. package/dist/bridge/send-controller.js +3 -3
  22. package/dist/bridge/toolbar-meta.js +1 -1
  23. package/dist/core/access/allowlist-store.js +1 -1
  24. package/dist/core/file-ops/list-files.js +1 -1
  25. package/dist/core/installer/registry.js +1 -1
  26. package/dist/core/util/home-env.js +1 -0
  27. package/dist/grix.js +5 -5
  28. package/dist/log.js +2 -2
  29. package/dist/manager.js +1 -1
  30. package/dist/mcp/stream-http/config.js +1 -1
  31. package/dist/mcp/stream-http/connection-binding.js +1 -1
  32. package/dist/mcp/stream-http/tool-executor.js +1 -1
  33. package/dist/mcp/stream-http/tool-registry.js +1 -1
  34. package/dist/mcp/stream-http/tool-schemas.js +1 -1
  35. package/dist/protocol/acp-client.js +1 -1
  36. package/openclaw-plugin/audit-recorder-worker.js +2 -1
  37. package/package.json +1 -1
  38. package/dist/assets/dsh-bridge/grix-dsh-bridge-4.19.0.tgz +0 -0
@@ -1,7 +1,7 @@
1
- import{createHash as x,randomUUID as D}from"node:crypto";import{EventEmitter as V}from"node:events";import{copyFileSync as ue,existsSync as W,mkdirSync as pe}from"node:fs";import{dirname as ge,join as T,resolve as G}from"node:path";import{fileURLToPath as Q}from"node:url";import{log as g}from"../../core/log/index.js";import{syncDefaultSkillsToDir as fe}from"../../default-skills/index.js";import{resolveCliPath as me}from"../../core/util/cli-probe.js";import{DshWireCapture as ve}from"./audit-boundary.js";import{dsmlToolCallKey as be,projectVisibleDsmlText as _e}from"./dsml-text-filter.js";import{mapDshSessionEvent as Se,unwrapDshSessionEvent as ke}from"./event-mapper.js";import{buildDshUserPrompt as z,extractQuotedMessageMarker as K}from"./prompt-builder.js";import{stageInboundAttachmentsForWorkspace as Ie}from"./workspace-attachments.js";import{DshProcessRuntime as we}from"./process-runtime.js";import{DshProfileRuntime as Te}from"./profile-runtime.js";import{compareDshVersions as X}from"./dsh-version.js";import{createDshWebProfile as ye}from"./profile-catalog.js";import{listDshPlugins as R,resolveDshPlugin as Pe,updateDshPluginIds as Ee}from"./plugin-manager.js";import{listDshSkills as M,resolveDshSkill as Ce,updateDshSkillIds as xe}from"./skill-manager.js";import{prepareDshSessionPluginOverlay as De}from"./session-plugin-overlay.js";import{assertSelectableDshProfileName as Re,discoverDshBridgeEndpoints as Me,listDshProfiles as Ae,resolveDshConnectorProfileDataDir as He,resolveDshHome as $e,resolveDshSelectedProfileName as Be}from"./profile-resolver.js";import{DshBridgeInstaller as A,errorForDshBridgeReadiness as H,readDshCliVersion as qe}from"./bridge-installer.js";import{ensureDshBridgeReady as Fe,prepareDshProfileBridge as Ne}from"./profile-supervisor.js";import{DSH_RUNTIME_ENSURE_MAX_ATTEMPTS as J,dshRuntimeEnsureBackoffMs as Ue,isRetryableDshRuntimeError as Le}from"./runtime-ensure.js";import{runDshProtocolProbe as je}from"./probe.js";import{buildDshSystemPrompt as Oe,describeDshSystemPrompt as Ve}from"./system-prompt.js";import{DshActionCoordinator as We}from"./toolbar-actions.js";import{adoptDshProfileModels as Ge,adoptLiveDshProviderSelection as Qe,buildDshToolbarMeta as ze,DEFAULT_DSH_MAX_TOKENS as Ke,DEFAULT_DSH_MODELS as Xe,DEFAULT_DSH_PRESETS as Je,DEFAULT_DSH_PROVIDER_ID as $,DEFAULT_DSH_REASONING_EFFORT as Ye,DEFAULT_DSH_THINKING as Ze,normalizeDshPresets as et,normalizeDshProviders as tt,normalizeDshReasoningEffort as B,normalizeDshThinking as q,permissionModeFor as Y,resolveDshAgentPreset as Z,resolveDshModeId as it,resolveDshProviderId as st,retainRequestedDshProvider as nt}from"./toolbar-state.js";import{modelsForDshProvider as ot,resolveDshCatalogForToolbar as rt,writeDshCatalogCache as at}from"./catalog-cache.js";import{TurnCorrelator as ee}from"./turn-correlator.js";import{effectiveDshReasoningEffort as dt}from"./types.js";import{getDshSessionUsageStore as lt,normalizeDshUsage as te}from"./usage.js";import{toolCallToInvoke as ht}from"../../core/mcp/tools.js";import{isEventTool as ct}from"../../core/mcp/event-tool-executor.js";import{isDshBridgedGrixTool as ut}from"./grix-tool-bridge.js";import{DSH_GRIX_PROVIDER_ID as v,dshCredentialsLayoutFor as pt,isDshGrixProviderConfigured as ie,removeDshGrixProvider as gt,writeDshGrixProvider as ft}from"./dsh-provider-config.js";const p="deepseek-harness-adapter",se=20*6e4,ne=6e4,oe=9e4,re=180*6e4,ae="0.1.0-rc.8",de="0.1.0-rc.8";class mt extends V{adapterSessionId;cancelFn;constructor(e,t){super(),this.adapterSessionId=e,this.cancelFn=t}cancel(){return this.cancelFn()}}class li extends V{config;callbacks;type="deepseek-harness";alive=!1;stopped=!1;runtime=null;replaySupersededRuntimes=new WeakSet;capture=null;runtimeGeneration=0;runtimeSessionId="";applied;active=null;correlator=null;warnedUnknownNonSurfaceEvents=new Set;noticedUnknownSurfaceTypes=new Set;timeoutTimer=null;hardTimeoutTimer=null;activeTimeoutMs=se;intentionalRuntimeStop=!1;personaDirty=!1;profileRevision=0;appliedProfileRevision=-1;rebuildPromise=null;runtimeStartPromise=null;contextWindow=null;reportedContextCapacity=null;providerQuota=null;settingsState="applied";settingsErrorCode=null;injectedMessageIds=new Set;auditBoundaries=new Map;actionCoordinator=new We;activeWireStart=0;activeUsage=le();activeUsageSeq=-1;activeCommittedUsageSeqs=new Set;permissionHandler=null;quotedMessageId;cancelRequested=!1;runtimeReadiness="unknown";bridgeCapabilities=null;profileDshVersion=null;bridgeAckCursor=0;pendingFinalBridgeAck=null;finishingTurn=!1;pendingApprovals=new Map;options;models=Xe;providers=[];presets=[...Je];catalogProviderId;constructor(e,t,i){super(),this.config=e,this.callbacks=t,this.options=i,this.hydrateCatalogFromCache()}async start(){this.alive=!0,this.stopped=!1,this.settingsState="applied",this.settingsErrorCode=null,this.hydrateCatalogFromCache();const e=this.options.bindingStore.get(this.options.aibotSessionId);if(e?.cwd&&this.seedSessionToolbarFromGlobal(),this.syncGrixProvider(),e&&await this.options.bindingStore.flush(),this.resolveIntegrationMode()==="profile_bridge")try{const t=await this.attachSelectedProfile();await this.healBridgeUpdate(t)}catch(t){this.runtimeReadiness=String(t?.code??"bridge_probe_failed"),this.settingsErrorCode=this.runtimeReadiness}else this.runtimeReadiness="ready";this.pushToolbarMeta(),this.refreshProviderQuota(!1)}async stop(){this.stopped=!0,this.clearPendingApprovals("cancelled"),this.clearTimeout(),this.active&&this.finishActive("canceled","connector shutdown"),this.applied=void 0,this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState==="pending"&&(this.settingsState="applied"),this.settingsErrorCode=null,this.pushToolbarMeta(),await this.rebuildPromise?.catch(()=>{}),await this.stopRuntime(!0),await this.usageStore().flush(),this.alive=!1}isAlive(){return this.alive&&!this.stopped}async createSession(e){return this.options.aibotSessionId}async resumeSession(e,t){}async destroySession(e){e===this.options.aibotSessionId&&(this.usageStore().delete(e),await this.usageStore().flush(),await this.stopRuntime(!0))}sendPrompt(e){const t=new mt(e.adapterSessionId,()=>this.cancel(e.adapterSessionId));return queueMicrotask(()=>t.emit("done",{status:"failed",error:"Use deliverInboundEvent for platform prompts"})),t}async cancel(e){await this.cancelActive("user canceled")}deliverInboundEvent(e){if(!this.isAlive()){this.failEvent(e,"adapter is not alive");return}if(this.active){this.failEvent(e,"concurrent prompt rejected");return}this.runInboundEvent(e)}deliverStopEvent(e,t){this.active&&e===this.active.inbound.event_id&&(t&&t!==this.active.inbound.session_id||this.cancelActive("user canceled"))}async handleLocalAction(e){if(!["set_model","set_mode","set_provider","set_thinking","set_reasoning_effort","set_preset","set_profile","create_profile","get_session_usage","get_rate_limits","dsh_bridge_status","dsh_install_bridge","dsh_list_plugins","dsh_enable_plugin","dsh_disable_plugin","dsh_refresh_plugins","dsh_list_skills","dsh_enable_skill","dsh_disable_skill","dsh_list_mcp","dsh_list_tools","dsh_list_jobs","dsh_list_goals","exec_approve","exec_reject","permission_approve","permission_reject"].includes(e.action_type))return{handled:!1,kind:""};const t=await this.actionCoordinator.run(e.action_id,()=>this.executeLocalAction(e));return this.callbacks.sendLocalActionResult(e.action_id,t.status,t.result,t.errorCode,t.errorMsg),{handled:!0,kind:e.action_type}}async handleExecApprovalEvent(e){const t=String(e.approval_command_id??e.approval_id??e.tool_call_id??"").trim(),i=this.pendingApprovals.get(t);return i?(clearTimeout(i.timer),this.pendingApprovals.delete(t),i.resolve(e.decision==="deny"?"rejected":"allowed-once"),{delivered:!0}):{delivered:!1,errorCode:"approval_not_found",errorMsg:"That DSH approval request is no longer pending"}}setPermissionHandler(e){this.permissionHandler=e}async ping(e){return this.isAlive()&&(!this.runtime||this.runtime.isConnected())}getStatus(){return{alive:this.isAlive()&&!!this.runtime,busy:!!this.active||this.intentionalRuntimeStop||!!this.rebuildPromise||!!this.runtimeStartPromise,backgroundBusy:!1,sessions:this.runtime?1:0,details:{runtimeGeneration:this.runtimeGeneration,runtimeSessionId:this.runtimeSessionId||void 0}}}getActiveEventIds(){return this.active?[this.active.inbound.event_id]:[]}takeAuditBoundary(e){const t=this.auditBoundaries.get(e);return this.auditBoundaries.delete(e),t}clearActiveEventForShutdown(){this.active=null,this.correlator=null,this.clearTimeout()}getMcpConfig(){return null}async hasBackgroundWork(){return this.runtime?.hasBackgroundWork()??!1}onAgentProfileChanged(){this.profileRevision+=1,this.personaDirty=!0,!this.active&&this.runtime&&this.rebuildRuntime("persona_changed")}updateProviderQuotaSnapshot(e){this.providerQuota=e??null;const t=this.options.bindingStore.get(this.options.aibotSessionId);this.callbacks.sendUpdateBindingCard(this.options.aibotSessionId,this.stopped?"stopped":this.active?"busy":"ready",t?.cwd,{provider_quota:this.providerQuota})}async probe(e={}){const t=this.resolveIntegrationMode(),i=t==="embedded_jsonrpc"?this.config.command||"dsh-jsonrpc-agent":"dsh",s=await me(i),n=!!s;let a={ok:e.conversation!==!0,latency:null};if(n&&e.conversation===!0&&s)if(t==="embedded_jsonrpc")try{const d=await je({command:s,args:this.config.args,cordisPath:G(this.options.cordisPath??Q(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),settings:this.resolveDesiredSettings(),timeoutMs:e.timeoutMs});a={ok:!0,latency:d.latencyMs,serverName:d.serverName,serverVersion:d.serverVersion}}catch(d){a={ok:!1,latency:null,error:this.redactError(d)}}else{const d=Date.now();try{const r=new A({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),f=await Fe({installer:r,autoStart:!1}),u=H(f);if(u)throw u;const o=Me(f.identity);if(o.length===0)throw Object.assign(new Error(`No live Grix Bridge endpoint in DSH profile "${f.identity.profileName}"`),{code:"bridge_missing"});a={ok:!0,latency:Date.now()-d,serverName:"grix-dsh-profile-bridge",serverVersion:o[0].bridgeVersion}}catch(r){a={ok:!1,latency:null,error:this.redactError(r)}}}return{cli:{command:i,installed:n,path:s,version:null,...n?{}:{error:{code:"cli_not_found",message:`${i} not found`}}},conversation:{attempted:e.conversation===!0,ok:a.ok,latency_ms:a.latency,...a.ok?{}:{error:{code:"conversation_failed",message:a.error??"initialize/shutdown probe failed"}}},config:{model:this.resolveDesiredSettings().modelId,base_url:this.config.env?.DEEPSEEK_BASE_URL??null,source:{model:"config",base_url:this.config.env?.DEEPSEEK_BASE_URL?"env":"unknown"},extras:{protocol:t==="profile_bridge"?"grix-dsh/1":"jsonrpc-v1",profile:this.resolveSelectedProfile(),serverName:a.serverName,serverVersion:a.serverVersion}},process:{started:!!this.runtime,alive:this.runtime?.isConnected()??!1,busy:!!this.active}}}async runInboundEvent(e){const t={inbound:e,admitted:!1,claimed:!1,turnEnded:!1,rootIdle:!1,text:"",sentText:"",seq:0,startedAt:Date.now()};this.active=t,this.correlator=new ee(t),this.activeUsage=le(),this.activeUsageSeq=-1,this.activeCommittedUsageSeqs.clear(),this.noticedUnknownSurfaceTypes.clear(),this.quotedMessageId=void 0,this.cancelRequested=!1,this.emit("eventStarted",e.event_id,e.session_id);try{await this.submitActivePrompt(t)}catch(i){await this.handlePromptSubmissionFailure(t,i)}}async submitActivePrompt(e){const t=e.inbound;if(await this.ensureRuntimeWithRetry(),this.cancelRequested||this.active!==e)return;this.activeWireStart=this.capture?.offset??0;const i=this.options.bindingStore.get(this.options.aibotSessionId)?.cwd,s=i?await Ie(t,i,p):void 0;if(this.cancelRequested||this.active!==e)return;const n=z(t,this.injectedMessageIds,s);this.startTimeout(t.timeoutMs);const a=await this.runtime.client.prompt({sessionId:this.runtimeSessionId,contentBlocks:[{type:"text",text:n.text}]});if(!a?.messageId)throw Object.assign(new Error("session/prompt response missing messageId"),{code:"protocol_invalid_prompt_result"});this.correlator.setPromptMessageId(a.messageId)}isPromptUnaccepted(e){return!e.messageId&&!e.admitted&&!e.claimed&&!e.turnEnded&&!e.text&&!e.sentText}canReplayAfterRuntimeExit(e){return!(e.runtimeExitReplayed||!this.isPromptUnaccepted(e)||this.runtime?.isConnected())}async handlePromptSubmissionFailure(e,t){const i=e.inbound;if(!this.cancelRequested&&!this.stopped&&this.active===e&&this.canReplayAfterRuntimeExit(e)){e.runtimeExitReplayed=!0,g.warn(p,`Harness runtime exited before accepting prompt ${i.event_id}; replaying the prompt once on a fresh runtime`);const n=this.runtime;n&&this.replaySupersededRuntimes.add(n),await this.stopRuntime(!0),this.correlator=new ee(e);try{await this.submitActivePrompt(e);return}catch(a){const d=this.runtime;if(d&&this.replaySupersededRuntimes.add(d),await this.stopRuntime(!0),this.active!==e||this.stopped)return;const r=this.redactError(a,i.content);this.finishActive(this.cancelRequested?"canceled":"failed",this.cancelRequested?"user canceled":`Harness runtime exited; prompt replay failed: ${r}`),this.cancelRequested||this.emit("exit",1);return}}const s=this.redactError(t,i.content);this.finishActive(this.cancelRequested?"canceled":"failed",this.cancelRequested?"user canceled":s)}async ensureRuntime(){if(this.stopped)throw new Error("adapter stopped");if(this.runtime)return;this.syncGrixProvider(),await this.writeGrixProviderFile();const t=this.options.bindingStore.get(this.options.aibotSessionId)?.cwd;if(!t)throw Object.assign(new Error("Session binding missing. Open a workspace first."),{code:"binding_missing"});const i=this.projectConnectorSkills();let s=this.resolveDesiredSettings();const n=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),a={};n?.modelId||(a.modelId=s.modelId),!n?.providerId&&s.providerId&&(a.providerId=s.providerId),n?.thinking||(a.thinking=s.thinking),n?.reasoningEffort||(a.reasoningEffort=s.reasoningEffort),Object.keys(a).length>0&&(this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,a),await this.options.bindingStore.flush(),s=this.resolveDesiredSettings());const d=this.callbacks.getAgentProfile(),r=this.profileRevision,f=Oe({...d,grixSessionId:this.options.aibotSessionId,agentId:this.callbacks.getAgentId()}),u=Ve(f);this.runtimeGeneration+=1;const o=this.resolveIntegrationMode(),l=this.resolveSelectedProfile();if(o==="profile_bridge")try{await this.ensureProfileReadyForChat(),this.pushToolbarMeta()}catch(m){throw this.settingsState="failed",this.settingsErrorCode=String(m?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.pushToolbarMeta(),m}let c=o==="profile_bridge"?this.options.bindingStore.getDshProfileBinding(this.options.aibotSessionId,l):void 0;o==="profile_bridge"&&!c&&(c={profileName:l,sessionId:St(this.options.aibotSessionId),sessionCreated:!1,eventCursor:0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,c),await this.options.bindingStore.flush()),this.runtimeSessionId=c?.sessionId??_t(this.options.aibotSessionId,this.runtimeGeneration);const b=this.profileDataDir(l),F=G(this.options.cordisPath??Q(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),N=De({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:l,pluginIds:s.pluginIds??[],overlayId:x("sha256").update(this.options.aibotSessionId).digest("hex").slice(0,24),baseCordisPath:F}),ce=T(b,"audit-source",`${this.runtimeSessionId}.jsonl`);this.capture=new ve(ce);const _=o==="embedded_jsonrpc"?new we({command:this.config.command||"dsh-jsonrpc-agent",args:this.config.args,cwd:t,cordisPath:N.embeddedCordisPath??F,home:b,sessionRoot:T(b,"sessions"),skillsDir:i,env:this.config.env,systemPrompt:f,settings:s,capture:this.capture,maxLineBytes:this.options.maxLineBytes}):new Te({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:l,cwd:t,ownerId:`${this.callbacks.getAgentId()}:${this.options.aibotSessionId}`,sessionId:this.runtimeSessionId,resumeSession:c?.sessionCreated===!0,lastAckCursor:c?.eventCursor??0,systemPrompt:f,settings:s,skillsDir:i,pluginOverlayPath:N.bridgeOverlayPath,capture:this.capture,maxFrameBytes:this.options.maxLineBytes,onApproval:m=>this.handleBridgeApproval(m),onToolInvoke:(m,y,I)=>this.invokeGrixTool(m,y,I),onCursorAck:m=>{!c||m<=c.eventCursor||(c={...c,eventCursor:m},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,c))}});this.runtime=_,this.bridgeAckCursor=c?.eventCursor??0,this.pendingFinalBridgeAck=null,this.finishingTurn=!1,this.intentionalRuntimeStop=!1;try{const m=await _.start();if(!_.isConnected())throw Object.assign(new Error("Harness runtime disconnected immediately after initialize"),{code:"runtime_exited"});_.client?.on("notification",(S,k)=>this.onNotification(S,k)),_.client?.on("protocolError",S=>this.onProtocolError(S)),_.onExit(()=>this.onRuntimeExit(_)),_.client?.activateNotifications?.();let y=!1;if(o==="profile_bridge"){const S=tt(m.providers),k=Qe({requestedProviderId:s.providerId,liveProviders:S,liveSelectedProvider:String(m.selectedProvider??"")});this.providers=nt(S,k.providerId,this.providers),s={...s,providerId:k.providerId},y=k.persistFallback;const E=k.providerId,L=Object.prototype.hasOwnProperty.call(m,"models")?m.models:void 0,j=!!this.catalogProviderId&&!!E&&E!==this.catalogProviderId;this.models=Ge({current:this.models,fetched:L,providerChanged:j}),(L!==void 0||j)&&(this.catalogProviderId=E||this.catalogProviderId);const C=String(m.selectedModel??"");C&&C!==s.modelId&&(s={...s,modelId:C});const O=et(m.presets);O.length>0&&(this.presets=O);const P=String(m.selectedPreset??"");P&&P!==s.agentPreset&&(s={...s,agentPreset:P},this.options.bindingStore.getDshAgentPreset(this.options.aibotSessionId)||this.options.bindingStore.setDshAgentPreset(this.options.aibotSessionId,P))}const I=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),U=(I?.revision??0)!==s.revision,w={};!U&&y&&(I?.providerId??"")!==(s.providerId??"")&&(w.providerId=s.providerId),!U&&(I?.modelId??"")!==s.modelId&&(w.modelId=s.modelId),(w.providerId||w.modelId)&&(s.revision=this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,w)??s.revision,await this.options.bindingStore.flush(),g.warn(p,`replaced unavailable persisted DSH catalog selection provider=${s.providerId} model=${s.modelId}`)),this.applied={runtimeGeneration:this.runtimeGeneration,appliedRevision:s.revision,providerId:s.providerId??$,modelId:s.modelId,modeId:s.modeId,thinking:s.thinking,reasoningEffort:dt(s)},this.runtimeReadiness="ready",this.bridgeCapabilities=m.capabilities??null,o==="profile_bridge"&&c&&!c.sessionCreated&&(c={...c,sessionCreated:!0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,c),await this.options.bindingStore.flush()),this.settingsState=this.resolveDesiredSettings().revision===s.revision?"applied":"pending",this.settingsErrorCode=null,this.appliedProfileRevision=r,this.personaDirty=this.appliedProfileRevision!==this.profileRevision,g.info(p,`runtime initialized generation=${this.runtimeGeneration} prompt_schema=${u.schemaVersion} prompt_sha256=${u.sha256} prompt_length=${u.length}`),await this.persistCatalogCache(s.providerId??$),this.pushToolbarMeta(),this.settingsState==="pending"&&!this.active&&!this.stopped&&this.rebuildRuntime("settings_changed_during_start")}catch(m){throw this.settingsState="failed",this.settingsErrorCode=String(m?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.applied=void 0,this.pushToolbarMeta(),await this.stopRuntime(!0),m}}ensureRuntimeWithRetry(){if(this.runtimeStartPromise)return this.runtimeStartPromise;const e=this.ensureRuntimeWithRetryLoop();this.runtimeStartPromise=e;const t=()=>{this.runtimeStartPromise===e&&(this.runtimeStartPromise=null)};return e.then(t,t),e}async ensureRuntimeWithRetryLoop(){let e;for(let t=1;t<=J;t++)try{await this.ensureRuntime();return}catch(i){e=i;const s=String(i?.code??"");if(this.cancelRequested||!Le(s)||t===J)throw i;g.warn(p,`runtime ensure retry attempt=${t} code=${s||"unknown"}`),this.settingsState="pending",this.settingsErrorCode=s||"runtime_initialize_failed",this.runtimeReadiness=this.settingsErrorCode,this.pushToolbarMeta(),await this.stopRuntime(!0),await bt(Ue(t))}throw e}onNotification(e,t){const i=vt(t);if(e==="session.event"){const s=ke(t);if(!s){this.onProtocolError(new Error("malformed session.event"));return}const n=this.onSessionEvent(s);this.advanceBridgeAck(i,n);return}if(e==="session.status"){const s=t&&typeof t=="object"?t:{};if(String(s.sessionId??"")===this.runtimeSessionId){this.touchActivity(),this.correlator?.markRootStatus(String(s.status??"")),s.status==="idle"&&this.active&&this.correlator&&g.debug(p,`turn correlation idle admitted=${this.active.admitted} claimed=${this.active.claimed} ended=${this.active.turnEnded} complete=${this.correlator.complete}`);const a=!!this.correlator?.complete;a&&this.finishFromTurnOutcome(),this.advanceBridgeAck(i,a)}else i>0&&this.advanceBridgeAck(i,!1);return}if(e==="subagent.started"||e==="subagent.finished"){this.touchActivity(3);const s=t&&typeof t=="object"?t:{},n=String(s.childSessionId??s.sessionId??"");n&&this.capture?.addChild(n),this.active&&this.callbacks.sendRawEventEnvelope(this.active.inbound.event_id,this.active.inbound.session_id,{type:e,payload:s},e==="subagent.started"?"[subagent started]":"[subagent finished]"),this.advanceBridgeAck(i,!1);return}this.onProtocolError(new Error(`unknown required JSON-RPC notification: ${e}`))}onSessionEvent(e){if(!this.active||!this.correlator)return!1;this.touchActivity(e.type==="tool/call"||e.type==="tool/result"?3:1);const t=Se(e);if(t.kind==="unknown"&&!Pt(e)&&e.ignorable!==!0)return e.surfaceOp===void 0?(this.warnedUnknownNonSurfaceEvents.has(e.type)||(this.warnedUnknownNonSurfaceEvents.add(e.type),g.warn(p,`ignoring unknown non-surface SessionEvent: ${e.type}`)),!1):(this.surfaceUnknownEventNotice(e.type),!1);if(e.sessionId&&e.sessionId!==this.runtimeSessionId)return!1;const i=this.correlator.accept(e);if((e.type==="agent/inbox/spliced"||e.type==="user/message"||e.type==="turn/end")&&g.debug(p,`turn correlation event=${e.type} belongs=${i} admitted=${this.active.admitted} claimed=${this.active.claimed} ended=${this.active.turnEnded}`),e.type==="agent/inbox/spliced"&&this.active.admitted){const s=z(this.active.inbound,this.injectedMessageIds);for(const n of s.contextIds)this.injectedMessageIds.add(n);s.currentMessageId&&this.injectedMessageIds.add(s.currentMessageId)}return i?wt(e)?(this.flushPendingTextAsThinking(),!1):t.kind==="text"?(t.payload?.committed===!0?(t.payload?.hasToolCall===!0?this.applyCommittedToolStepText(t.text??""):this.applyCommittedText(t.text??""),t.usage&&this.collectCommittedUsage(t.usage,Number(e.seq??e.step??Date.now()))):this.applyTextDelta(t.text??""),!1):t.kind==="thinking"?(this.thinkingEnabled()&&this.callbacks.sendThinking(this.active.inbound.event_id,this.active.inbound.session_id,t.text??""),!1):t.kind==="tool_call"?(this.flushPendingTextAsThinking(),this.toolEventsEnabled()&&this.sendRaw("tool_call",{call_id:t.callId,tool_name:t.name,tool_input:t.input},`[tool] ${t.name}`),!1):t.kind==="tool_result"?(this.toolEventsEnabled()&&this.sendRaw("tool_result",{call_id:t.callId,result:t.output},`[tool result] ${t.callId??""}`),!1):t.kind==="todo"||t.kind==="compaction"?!1:t.kind==="context"?(this.updateContextCapacity(t.payload),!1):t.kind==="usage"?(this.updateContextWindow(t.usage),!1):t.kind==="turn_end"&&this.correlator.complete?(this.finishFromTurnOutcome(),!0):!1:!1}applyTextDelta(e){this.active.pendingText=`${this.active.pendingText??""}${e}`}applyCommittedText(e){const t=this.active;if(t.pendingText=void 0,e.startsWith(t.text))t.text=e;else if(!t.text.startsWith(e)){g.warn(p,`committed assistant text diverged event=${t.inbound.event_id}`);const i=K(e).quotedMessageId;i&&(this.quotedMessageId=i),t.text=t.sentText}this.flushVisibleText(!1)}flushPendingTextAsThinking(){const e=this.active,t=e?.pendingText;!e||!t||(e.pendingText=void 0,this.thinkingEnabled()&&t.trim()&&this.callbacks.sendThinking(e.inbound.event_id,e.inbound.session_id,t),e.lastThinkingText=t)}applyCommittedToolStepText(e){const t=this.active;t&&(t.pendingText=void 0,e.trim()&&t.lastThinkingText!==e&&this.thinkingEnabled()&&(this.callbacks.sendThinking(t.inbound.event_id,t.inbound.session_id,e),t.lastThinkingText=e))}promotePendingTextToVisible(){const e=this.active,t=e?.pendingText;!e||!t||(e.pendingText=void 0,e.text+=t)}surfaceUnknownEventNotice(e){const t=this.active;!t||this.noticedUnknownSurfaceTypes.has(e)||(this.noticedUnknownSurfaceTypes.add(e),g.warn(p,`unknown surface SessionEvent surfaced as chat notice: ${e}`),!t.repliedViaTool&&(t.seq+=1,this.callbacks.sendStreamChunk(t.inbound.event_id,t.inbound.session_id,`
1
+ import{createHash as x,randomUUID as D}from"node:crypto";import{EventEmitter as V}from"node:events";import{copyFileSync as ue,existsSync as W,mkdirSync as pe}from"node:fs";import{dirname as ge,join as T,resolve as G}from"node:path";import{fileURLToPath as Q}from"node:url";import{log as g}from"../../core/log/index.js";import{syncDefaultSkillsToDir as fe}from"../../default-skills/index.js";import{resolveCliPath as me}from"../../core/util/cli-probe.js";import{DshWireCapture as ve}from"./audit-boundary.js";import{dsmlToolCallKey as be,projectVisibleDsmlText as _e}from"./dsml-text-filter.js";import{mapDshSessionEvent as Se,unwrapDshSessionEvent as ke}from"./event-mapper.js";import{buildDshUserPrompt as z,extractQuotedMessageMarker as K}from"./prompt-builder.js";import{stageInboundAttachmentsForWorkspace as Ie}from"./workspace-attachments.js";import{DshProcessRuntime as we}from"./process-runtime.js";import{DshProfileRuntime as Te}from"./profile-runtime.js";import{compareDshVersions as X}from"./dsh-version.js";import{createDshWebProfile as ye}from"./profile-catalog.js";import{listDshPlugins as R,resolveDshPlugin as Pe,updateDshPluginIds as Ee}from"./plugin-manager.js";import{listDshSkills as M,resolveDshSkill as Ce,updateDshSkillIds as xe}from"./skill-manager.js";import{prepareDshSessionPluginOverlay as De}from"./session-plugin-overlay.js";import{assertSelectableDshProfileName as Re,discoverDshBridgeEndpoints as Me,listDshProfiles as Ae,resolveDshConnectorProfileDataDir as He,resolveDshHome as $e,resolveDshSelectedProfileName as Be}from"./profile-resolver.js";import{DshBridgeInstaller as A,errorForDshBridgeReadiness as H,readDshCliVersion as qe}from"./bridge-installer.js";import{ensureDshBridgeReady as Fe,prepareDshProfileBridge as Ne}from"./profile-supervisor.js";import{DSH_RUNTIME_ENSURE_MAX_ATTEMPTS as J,dshRuntimeEnsureBackoffMs as Ue,isRetryableDshRuntimeError as Le}from"./runtime-ensure.js";import{runDshProtocolProbe as je}from"./probe.js";import{buildDshSystemPrompt as Oe,describeDshSystemPrompt as Ve}from"./system-prompt.js";import{DshActionCoordinator as We}from"./toolbar-actions.js";import{adoptDshProfileModels as Ge,adoptLiveDshProviderSelection as Qe,buildDshToolbarMeta as ze,DEFAULT_DSH_MAX_TOKENS as Ke,DEFAULT_DSH_MODELS as Xe,DEFAULT_DSH_PRESETS as Je,DEFAULT_DSH_PROVIDER_ID as $,DEFAULT_DSH_REASONING_EFFORT as Ye,DEFAULT_DSH_THINKING as Ze,normalizeDshPresets as et,normalizeDshProviders as tt,normalizeDshReasoningEffort as B,normalizeDshThinking as q,permissionModeFor as Y,resolveDshAgentPreset as Z,resolveDshModeId as it,resolveDshProviderId as st,retainRequestedDshProvider as nt}from"./toolbar-state.js";import{modelsForDshProvider as ot,resolveDshCatalogForToolbar as rt,writeDshCatalogCache as at}from"./catalog-cache.js";import{TurnCorrelator as ee}from"./turn-correlator.js";import{effectiveDshReasoningEffort as dt}from"./types.js";import{getDshSessionUsageStore as lt,normalizeDshUsage as te}from"./usage.js";import{toolCallToInvoke as ht}from"../../core/mcp/tools.js";import{isEventTool as ct}from"../../core/mcp/event-tool-executor.js";import{isDshBridgedGrixTool as ut}from"./grix-tool-bridge.js";import{DSH_GRIX_PROVIDER_ID as v,dshCredentialsLayoutFor as pt,isDshGrixProviderConfigured as ie,removeDshGrixProvider as gt,writeDshGrixProvider as ft}from"./dsh-provider-config.js";const p="deepseek-harness-adapter",se=20*6e4,ne=6e4,oe=9e4,re=180*6e4,ae="0.1.0-rc.8",de="0.1.0-rc.8";class mt extends V{adapterSessionId;cancelFn;constructor(e,t){super(),this.adapterSessionId=e,this.cancelFn=t}cancel(){return this.cancelFn()}}class li extends V{config;callbacks;type="deepseek-harness";alive=!1;stopped=!1;runtime=null;replaySupersededRuntimes=new WeakSet;capture=null;runtimeGeneration=0;runtimeSessionId="";applied;active=null;correlator=null;warnedUnknownNonSurfaceEvents=new Set;noticedUnknownSurfaceTypes=new Set;timeoutTimer=null;hardTimeoutTimer=null;activeTimeoutMs=se;intentionalRuntimeStop=!1;personaDirty=!1;profileRevision=0;appliedProfileRevision=-1;rebuildPromise=null;runtimeStartPromise=null;contextWindow=null;reportedContextCapacity=null;providerQuota=null;settingsState="applied";settingsErrorCode=null;injectedMessageIds=new Set;auditBoundaries=new Map;actionCoordinator=new We;activeWireStart=0;activeUsage=le();activeUsageSeq=-1;activeCommittedUsageSeqs=new Set;permissionHandler=null;quotedMessageId;cancelRequested=!1;runtimeReadiness="unknown";bridgeCapabilities=null;profileDshVersion=null;bridgeAckCursor=0;pendingFinalBridgeAck=null;finishingTurn=!1;pendingApprovals=new Map;options;models=Xe;providers=[];presets=[...Je];catalogProviderId;constructor(e,t,i){super(),this.config=e,this.callbacks=t,this.options=i,this.hydrateCatalogFromCache()}async start(){this.alive=!0,this.stopped=!1,this.settingsState="applied",this.settingsErrorCode=null,this.hydrateCatalogFromCache();const e=this.options.bindingStore.get(this.options.aibotSessionId);if(e?.cwd&&this.seedSessionToolbarFromGlobal(),this.syncGrixProvider(),e&&await this.options.bindingStore.flush(),this.resolveIntegrationMode()==="profile_bridge")try{const t=await this.attachSelectedProfile();await this.healBridgeUpdate(t)}catch(t){this.runtimeReadiness=String(t?.code??"bridge_probe_failed"),this.settingsErrorCode=this.runtimeReadiness}else this.runtimeReadiness="ready";this.pushToolbarMeta(),this.refreshProviderQuota(!1)}async stop(){this.stopped=!0,this.clearPendingApprovals("cancelled"),this.clearTimeout(),this.active&&this.finishActive("canceled","connector shutdown"),this.applied=void 0,this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState==="pending"&&(this.settingsState="applied"),this.settingsErrorCode=null,this.pushToolbarMeta(),await this.rebuildPromise?.catch(()=>{}),await this.stopRuntime(!0),await this.usageStore().flush(),this.alive=!1}isAlive(){return this.alive&&!this.stopped}async createSession(e){return this.options.aibotSessionId}async resumeSession(e,t){}async destroySession(e){e===this.options.aibotSessionId&&(this.usageStore().delete(e),await this.usageStore().flush(),await this.stopRuntime(!0))}sendPrompt(e){const t=new mt(e.adapterSessionId,()=>this.cancel(e.adapterSessionId));return queueMicrotask(()=>t.emit("done",{status:"failed",error:"Use deliverInboundEvent for platform prompts"})),t}async cancel(e){await this.cancelActive("user canceled")}deliverInboundEvent(e){if(!this.isAlive()){this.failEvent(e,"adapter is not alive");return}if(this.active){this.failEvent(e,"concurrent prompt rejected");return}this.runInboundEvent(e)}deliverStopEvent(e,t){this.active&&e===this.active.inbound.event_id&&(t&&t!==this.active.inbound.session_id||this.cancelActive("user canceled"))}async handleLocalAction(e){if(!["set_model","set_mode","set_provider","set_thinking","set_reasoning_effort","set_preset","set_profile","create_profile","get_session_usage","get_rate_limits","dsh_bridge_status","dsh_install_bridge","dsh_list_plugins","dsh_enable_plugin","dsh_disable_plugin","dsh_refresh_plugins","dsh_list_skills","dsh_enable_skill","dsh_disable_skill","dsh_list_mcp","dsh_list_tools","dsh_list_jobs","dsh_list_goals","exec_approve","exec_reject","permission_approve","permission_reject"].includes(e.action_type))return{handled:!1,kind:""};const t=await this.actionCoordinator.run(e.action_id,()=>this.executeLocalAction(e));return this.callbacks.sendLocalActionResult(e.action_id,t.status,t.result,t.errorCode,t.errorMsg),{handled:!0,kind:e.action_type}}async handleExecApprovalEvent(e){const t=String(e.approval_command_id??e.approval_id??e.tool_call_id??"").trim(),i=this.pendingApprovals.get(t);return i?(clearTimeout(i.timer),this.pendingApprovals.delete(t),i.resolve(e.decision==="deny"?"rejected":"allowed-once"),{delivered:!0}):{delivered:!1,errorCode:"approval_not_found",errorMsg:"That DSH approval request is no longer pending"}}setPermissionHandler(e){this.permissionHandler=e}async ping(e){return this.isAlive()&&(!this.runtime||this.runtime.isConnected())}getStatus(){return{alive:this.isAlive()&&!!this.runtime,busy:!!this.active||this.intentionalRuntimeStop||!!this.rebuildPromise||!!this.runtimeStartPromise,backgroundBusy:!1,sessions:this.runtime?1:0,details:{runtimeGeneration:this.runtimeGeneration,runtimeSessionId:this.runtimeSessionId||void 0}}}getActiveEventIds(){return this.active?[this.active.inbound.event_id]:[]}takeAuditBoundary(e){const t=this.auditBoundaries.get(e);return this.auditBoundaries.delete(e),t}clearActiveEventForShutdown(){this.active=null,this.correlator=null,this.clearTimeout()}getMcpConfig(){return null}async hasBackgroundWork(){return this.runtime?.hasBackgroundWork()??!1}onAgentProfileChanged(){this.profileRevision+=1,this.personaDirty=!0,!this.active&&this.runtime&&this.rebuildRuntime("persona_changed")}updateProviderQuotaSnapshot(e){this.providerQuota=e??null;const t=this.options.bindingStore.get(this.options.aibotSessionId);this.callbacks.sendUpdateBindingCard(this.options.aibotSessionId,this.stopped?"stopped":this.active?"busy":"ready",t?.cwd,{provider_quota:this.providerQuota})}async probe(e={}){const t=this.resolveIntegrationMode(),i=t==="embedded_jsonrpc"?this.config.command||"dsh-jsonrpc-agent":"dsh",s=await me(i),n=!!s;let r={ok:e.conversation!==!0,latency:null};if(n&&e.conversation===!0&&s)if(t==="embedded_jsonrpc")try{const d=await je({command:s,args:this.config.args,cordisPath:G(this.options.cordisPath??Q(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),settings:this.resolveDesiredSettings(),timeoutMs:e.timeoutMs});r={ok:!0,latency:d.latencyMs,serverName:d.serverName,serverVersion:d.serverVersion}}catch(d){r={ok:!1,latency:null,error:this.redactError(d)}}else{const d=Date.now();try{const a=new A({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),f=await Fe({installer:a,autoStart:!1}),u=H(f);if(u)throw u;const o=Me(f.identity);if(o.length===0)throw Object.assign(new Error(`No live Grix Bridge endpoint in DSH profile "${f.identity.profileName}"`),{code:"bridge_missing"});r={ok:!0,latency:Date.now()-d,serverName:"grix-dsh-profile-bridge",serverVersion:o[0].bridgeVersion}}catch(a){r={ok:!1,latency:null,error:this.redactError(a)}}}return{cli:{command:i,installed:n,path:s,version:null,...n?{}:{error:{code:"cli_not_found",message:`${i} not found`}}},conversation:{attempted:e.conversation===!0,ok:r.ok,latency_ms:r.latency,...r.ok?{}:{error:{code:"conversation_failed",message:r.error??"initialize/shutdown probe failed"}}},config:{model:this.resolveDesiredSettings().modelId,base_url:this.config.env?.DEEPSEEK_BASE_URL??null,source:{model:"config",base_url:this.config.env?.DEEPSEEK_BASE_URL?"env":"unknown"},extras:{protocol:t==="profile_bridge"?"grix-dsh/1":"jsonrpc-v1",profile:this.resolveSelectedProfile(),serverName:r.serverName,serverVersion:r.serverVersion}},process:{started:!!this.runtime,alive:this.runtime?.isConnected()??!1,busy:!!this.active}}}async runInboundEvent(e){const t={inbound:e,admitted:!1,claimed:!1,turnEnded:!1,rootIdle:!1,text:"",sentText:"",seq:0,startedAt:Date.now()};this.active=t,this.correlator=new ee(t),this.activeUsage=le(),this.activeUsageSeq=-1,this.activeCommittedUsageSeqs.clear(),this.noticedUnknownSurfaceTypes.clear(),this.quotedMessageId=void 0,this.cancelRequested=!1,this.emit("eventStarted",e.event_id,e.session_id);try{await this.submitActivePrompt(t)}catch(i){await this.handlePromptSubmissionFailure(t,i)}}async submitActivePrompt(e){const t=e.inbound;if(await this.ensureRuntimeWithRetry(),this.cancelRequested||this.active!==e)return;this.activeWireStart=this.capture?.offset??0;const i=this.options.bindingStore.get(this.options.aibotSessionId)?.cwd,s=i?await Ie(t,i,p):void 0;if(this.cancelRequested||this.active!==e)return;const n=z(t,this.injectedMessageIds,s);this.startTimeout(t.timeoutMs);const r=await this.runtime.client.prompt({sessionId:this.runtimeSessionId,contentBlocks:[{type:"text",text:n.text}]});if(!r?.messageId)throw Object.assign(new Error("session/prompt response missing messageId"),{code:"protocol_invalid_prompt_result"});this.correlator.setPromptMessageId(r.messageId)}isPromptUnaccepted(e){return!e.messageId&&!e.admitted&&!e.claimed&&!e.turnEnded&&!e.text&&!e.sentText}canReplayAfterRuntimeExit(e){return!(e.runtimeExitReplayed||!this.isPromptUnaccepted(e)||this.runtime?.isConnected())}async handlePromptSubmissionFailure(e,t){const i=e.inbound;if(!this.cancelRequested&&!this.stopped&&this.active===e&&this.canReplayAfterRuntimeExit(e)){e.runtimeExitReplayed=!0,g.warn(p,`Harness runtime exited before accepting prompt ${i.event_id}; replaying the prompt once on a fresh runtime`);const n=this.runtime;n&&this.replaySupersededRuntimes.add(n),await this.stopRuntime(!0),this.correlator=new ee(e);try{await this.submitActivePrompt(e);return}catch(r){const d=this.runtime;if(d&&this.replaySupersededRuntimes.add(d),await this.stopRuntime(!0),this.active!==e||this.stopped)return;const a=this.redactError(r,i.content);this.finishActive(this.cancelRequested?"canceled":"failed",this.cancelRequested?"user canceled":`Harness runtime exited; prompt replay failed: ${a}`),this.cancelRequested||this.emit("exit",1);return}}const s=this.redactError(t,i.content);this.finishActive(this.cancelRequested?"canceled":"failed",this.cancelRequested?"user canceled":s)}async ensureRuntime(){if(this.stopped)throw new Error("adapter stopped");if(this.runtime)return;this.syncGrixProvider(),await this.writeGrixProviderFile();const t=this.options.bindingStore.get(this.options.aibotSessionId)?.cwd;if(!t)throw Object.assign(new Error("Session binding missing. Open a workspace first."),{code:"binding_missing"});const i=this.projectConnectorSkills();let s=this.resolveDesiredSettings();const n=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),r={};n?.modelId||(r.modelId=s.modelId),!n?.providerId&&s.providerId&&(r.providerId=s.providerId),n?.thinking||(r.thinking=s.thinking),n?.reasoningEffort||(r.reasoningEffort=s.reasoningEffort),Object.keys(r).length>0&&(this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,r),await this.options.bindingStore.flush(),s=this.resolveDesiredSettings());const d=this.callbacks.getAgentProfile(),a=this.profileRevision,f=Oe({...d,grixSessionId:this.options.aibotSessionId,agentId:this.callbacks.getAgentId()}),u=Ve(f);this.runtimeGeneration+=1;const o=this.resolveIntegrationMode(),l=this.resolveSelectedProfile();if(o==="profile_bridge")try{await this.ensureProfileReadyForChat(),this.pushToolbarMeta()}catch(m){throw this.settingsState="failed",this.settingsErrorCode=String(m?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.pushToolbarMeta(),m}let c=o==="profile_bridge"?this.options.bindingStore.getDshProfileBinding(this.options.aibotSessionId,l):void 0;o==="profile_bridge"&&!c&&(c={profileName:l,sessionId:St(this.options.aibotSessionId),sessionCreated:!1,eventCursor:0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,c),await this.options.bindingStore.flush()),this.runtimeSessionId=c?.sessionId??_t(this.options.aibotSessionId,this.runtimeGeneration);const b=this.profileDataDir(l),F=G(this.options.cordisPath??Q(new URL("./grix-jsonrpc.cordis.yml",import.meta.url))),N=De({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:l,pluginIds:s.pluginIds??[],overlayId:x("sha256").update(this.options.aibotSessionId).digest("hex").slice(0,24),baseCordisPath:F}),ce=T(b,"audit-source",`${this.runtimeSessionId}.jsonl`);this.capture=new ve(ce);const _=o==="embedded_jsonrpc"?new we({command:this.config.command||"dsh-jsonrpc-agent",args:this.config.args,cwd:t,cordisPath:N.embeddedCordisPath??F,home:b,sessionRoot:T(b,"sessions"),skillsDir:i,env:this.config.env,systemPrompt:f,settings:s,capture:this.capture,maxLineBytes:this.options.maxLineBytes}):new Te({dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:l,cwd:t,ownerId:`${this.callbacks.getAgentId()}:${this.options.aibotSessionId}`,sessionId:this.runtimeSessionId,resumeSession:c?.sessionCreated===!0,lastAckCursor:c?.eventCursor??0,systemPrompt:f,settings:s,skillsDir:i,pluginOverlayPath:N.bridgeOverlayPath,capture:this.capture,maxFrameBytes:this.options.maxLineBytes,onApproval:m=>this.handleBridgeApproval(m),onToolInvoke:(m,y,I)=>this.invokeGrixTool(m,y,I),onCursorAck:m=>{!c||m<=c.eventCursor||(c={...c,eventCursor:m},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,c))}});this.runtime=_,this.bridgeAckCursor=c?.eventCursor??0,this.pendingFinalBridgeAck=null,this.finishingTurn=!1,this.intentionalRuntimeStop=!1;try{const m=await _.start();if(!_.isConnected())throw Object.assign(new Error("Harness runtime disconnected immediately after initialize"),{code:"runtime_exited"});_.client?.on("notification",(S,k)=>this.onNotification(S,k)),_.client?.on("protocolError",S=>this.onProtocolError(S)),_.onExit(()=>this.onRuntimeExit(_)),_.client?.activateNotifications?.();let y=!1;if(o==="profile_bridge"){const S=tt(m.providers),k=Qe({requestedProviderId:s.providerId,liveProviders:S,liveSelectedProvider:String(m.selectedProvider??"")});this.providers=nt(S,k.providerId,this.providers),s={...s,providerId:k.providerId},y=k.persistFallback;const E=k.providerId,L=Object.prototype.hasOwnProperty.call(m,"models")?m.models:void 0,j=!!this.catalogProviderId&&!!E&&E!==this.catalogProviderId;this.models=Ge({current:this.models,fetched:L,providerChanged:j}),(L!==void 0||j)&&(this.catalogProviderId=E||this.catalogProviderId);const C=String(m.selectedModel??"");C&&C!==s.modelId&&(s={...s,modelId:C});const O=et(m.presets);O.length>0&&(this.presets=O);const P=String(m.selectedPreset??"");P&&P!==s.agentPreset&&(s={...s,agentPreset:P},this.options.bindingStore.getDshAgentPreset(this.options.aibotSessionId)||this.options.bindingStore.setDshAgentPreset(this.options.aibotSessionId,P))}const I=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),U=(I?.revision??0)!==s.revision,w={};!U&&y&&(I?.providerId??"")!==(s.providerId??"")&&(w.providerId=s.providerId),!U&&(I?.modelId??"")!==s.modelId&&(w.modelId=s.modelId),(w.providerId||w.modelId)&&(s.revision=this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,w)??s.revision,await this.options.bindingStore.flush(),g.warn(p,`replaced unavailable persisted DSH catalog selection provider=${s.providerId} model=${s.modelId}`)),this.applied={runtimeGeneration:this.runtimeGeneration,appliedRevision:s.revision,providerId:s.providerId??$,modelId:s.modelId,modeId:s.modeId,thinking:s.thinking,reasoningEffort:dt(s)},this.runtimeReadiness="ready",this.bridgeCapabilities=m.capabilities??null,o==="profile_bridge"&&c&&!c.sessionCreated&&(c={...c,sessionCreated:!0},this.options.bindingStore.setDshProfileBinding(this.options.aibotSessionId,c),await this.options.bindingStore.flush()),this.settingsState=this.resolveDesiredSettings().revision===s.revision?"applied":"pending",this.settingsErrorCode=null,this.appliedProfileRevision=a,this.personaDirty=this.appliedProfileRevision!==this.profileRevision,g.info(p,`runtime initialized generation=${this.runtimeGeneration} prompt_schema=${u.schemaVersion} prompt_sha256=${u.sha256} prompt_length=${u.length}`),await this.persistCatalogCache(s.providerId??$),this.pushToolbarMeta(),this.settingsState==="pending"&&!this.active&&!this.stopped&&this.rebuildRuntime("settings_changed_during_start")}catch(m){throw this.settingsState="failed",this.settingsErrorCode=String(m?.code??"runtime_initialize_failed"),this.runtimeReadiness=this.settingsErrorCode,this.applied=void 0,this.pushToolbarMeta(),await this.stopRuntime(!0),m}}ensureRuntimeWithRetry(){if(this.runtimeStartPromise)return this.runtimeStartPromise;const e=this.ensureRuntimeWithRetryLoop();this.runtimeStartPromise=e;const t=()=>{this.runtimeStartPromise===e&&(this.runtimeStartPromise=null)};return e.then(t,t),e}async ensureRuntimeWithRetryLoop(){let e;for(let t=1;t<=J;t++)try{await this.ensureRuntime();return}catch(i){e=i;const s=String(i?.code??"");if(this.cancelRequested||!Le(s)||t===J)throw i;g.warn(p,`runtime ensure retry attempt=${t} code=${s||"unknown"}`),this.settingsState="pending",this.settingsErrorCode=s||"runtime_initialize_failed",this.runtimeReadiness=this.settingsErrorCode,this.pushToolbarMeta(),await this.stopRuntime(!0),await bt(Ue(t))}throw e}onNotification(e,t){const i=vt(t);if(e==="session.event"){const s=ke(t);if(!s){this.onProtocolError(new Error("malformed session.event"));return}const n=this.onSessionEvent(s);this.advanceBridgeAck(i,n);return}if(e==="session.status"){const s=t&&typeof t=="object"?t:{};if(String(s.sessionId??"")===this.runtimeSessionId){this.touchActivity(),this.correlator?.markRootStatus(String(s.status??"")),s.status==="idle"&&this.active&&this.correlator&&g.debug(p,`turn correlation idle admitted=${this.active.admitted} claimed=${this.active.claimed} ended=${this.active.turnEnded} complete=${this.correlator.complete}`);const r=!!this.correlator?.complete;r&&this.finishFromTurnOutcome(),this.advanceBridgeAck(i,r)}else i>0&&this.advanceBridgeAck(i,!1);return}if(e==="subagent.started"||e==="subagent.finished"){this.touchActivity(3);const s=t&&typeof t=="object"?t:{},n=String(s.childSessionId??s.sessionId??"");n&&this.capture?.addChild(n),this.active&&this.callbacks.sendRawEventEnvelope(this.active.inbound.event_id,this.active.inbound.session_id,{type:e,payload:s},e==="subagent.started"?"[subagent started]":"[subagent finished]"),this.advanceBridgeAck(i,!1);return}this.onProtocolError(new Error(`unknown required JSON-RPC notification: ${e}`))}onSessionEvent(e){if(!this.active||!this.correlator)return!1;this.touchActivity(e.type==="tool/call"||e.type==="tool/result"?3:1);const t=Se(e);if(t.kind==="unknown"&&!Pt(e)&&e.ignorable!==!0)return e.surfaceOp===void 0?(this.warnedUnknownNonSurfaceEvents.has(e.type)||(this.warnedUnknownNonSurfaceEvents.add(e.type),g.warn(p,`ignoring unknown non-surface SessionEvent: ${e.type}`)),!1):(this.surfaceUnknownEventNotice(e.type),!1);if(e.sessionId&&e.sessionId!==this.runtimeSessionId)return!1;const i=this.correlator.accept(e);if((e.type==="agent/inbox/spliced"||e.type==="user/message"||e.type==="turn/end")&&g.debug(p,`turn correlation event=${e.type} belongs=${i} admitted=${this.active.admitted} claimed=${this.active.claimed} ended=${this.active.turnEnded}`),e.type==="agent/inbox/spliced"&&this.active.admitted){const s=z(this.active.inbound,this.injectedMessageIds);for(const n of s.contextIds)this.injectedMessageIds.add(n);s.currentMessageId&&this.injectedMessageIds.add(s.currentMessageId)}if(!i)return!1;if(wt(e))return this.flushPendingTextAsThinking(),!1;if(t.kind==="text")return t.payload?.committed===!0?(this.applyCommittedReasoning(t.reasoning??"",Number(e.seq??e.step??Date.now())),t.payload?.hasToolCall===!0?this.applyCommittedToolStepText(t.text??""):this.applyCommittedText(t.text??""),t.usage&&this.collectCommittedUsage(t.usage,Number(e.seq??e.step??Date.now()))):this.applyTextDelta(t.text??""),!1;if(t.kind==="thinking"){const s=t.text??"";return this.active.reasoningStreamText=`${this.active.reasoningStreamText??""}${s}`,this.thinkingEnabled()&&this.callbacks.sendThinking(this.active.inbound.event_id,this.active.inbound.session_id,s),!1}return t.kind==="tool_call"?(this.flushPendingTextAsThinking(),this.toolEventsEnabled()&&this.sendRaw("tool_call",{call_id:t.callId,tool_name:t.name,tool_input:t.input},`[tool] ${t.name}`),!1):t.kind==="tool_result"?(this.toolEventsEnabled()&&this.sendRaw("tool_result",{call_id:t.callId,result:t.output},`[tool result] ${t.callId??""}`),!1):t.kind==="todo"||t.kind==="compaction"?!1:t.kind==="context"?(this.updateContextCapacity(t.payload),!1):t.kind==="usage"?(this.updateContextWindow(t.usage),!1):t.kind==="turn_end"&&this.correlator.complete?(this.finishFromTurnOutcome(),!0):!1}applyTextDelta(e){this.active.pendingText=`${this.active.pendingText??""}${e}`}applyCommittedText(e){const t=this.active;if(t.pendingText=void 0,e.startsWith(t.text))t.text=e;else if(!t.text.startsWith(e)){g.warn(p,`committed assistant text diverged event=${t.inbound.event_id}`);const i=K(e).quotedMessageId;i&&(this.quotedMessageId=i),t.text=t.sentText}this.flushVisibleText(!1)}applyCommittedReasoning(e,t){const i=this.active;if(!i)return;const s=i.committedReasoningSeqs??=new Set;if(s.has(t))return;s.add(t);const n=i.reasoningStreamText??"";if(i.reasoningStreamText=void 0,!e.trim()||!this.thinkingEnabled())return;let r=e;n&&(e.startsWith(n)?r=e.slice(n.length):(n.startsWith(e)||g.warn(p,`committed assistant reasoning diverged event=${i.inbound.event_id}`),r="")),r&&this.callbacks.sendThinking(i.inbound.event_id,i.inbound.session_id,r)}flushPendingTextAsThinking(){const e=this.active,t=e?.pendingText;!e||!t||(e.pendingText=void 0,this.thinkingEnabled()&&t.trim()&&this.callbacks.sendThinking(e.inbound.event_id,e.inbound.session_id,t),e.lastThinkingText=t)}applyCommittedToolStepText(e){const t=this.active;t&&(t.pendingText=void 0,e.trim()&&t.lastThinkingText!==e&&this.thinkingEnabled()&&(this.callbacks.sendThinking(t.inbound.event_id,t.inbound.session_id,e),t.lastThinkingText=e))}promotePendingTextToVisible(){const e=this.active,t=e?.pendingText;!e||!t||(e.pendingText=void 0,e.text+=t)}surfaceUnknownEventNotice(e){const t=this.active;!t||this.noticedUnknownSurfaceTypes.has(e)||(this.noticedUnknownSurfaceTypes.add(e),g.warn(p,`unknown surface SessionEvent surfaced as chat notice: ${e}`),!t.repliedViaTool&&(t.seq+=1,this.callbacks.sendStreamChunk(t.inbound.event_id,t.inbound.session_id,`
2
2
 
3
3
  [\u8FDE\u63A5\u5668\u63D0\u793A] \u672A\u8BC6\u522B\u7684 dsh \u4E8B\u4EF6 ${e}\uFF0C\u6B64\u6BB5\u5185\u5BB9\u53EF\u80FD\u663E\u793A\u4E0D\u5B8C\u6574\uFF0C\u8BF7\u622A\u56FE\u53CD\u9988\u7ED9\u5F00\u53D1\u8005\u3002
4
4
 
5
- `,t.seq,!1,`${t.inbound.event_id}-dsh`,this.quotedMessageId)))}flushVisibleText(e,t={}){const i=this.active;if(!i)return;const s=K(i.text);s.quotedMessageId&&(this.quotedMessageId=s.quotedMessageId);const n=s.text.replace(/\[\[quoted_message_id:[^\]]*$/g,""),a=_e(n,{finalize:t.finalizeDsml===!0||e});this.surfaceSuppressedDsmlToolCalls(a.suppressedToolCalls);const d=a.visible;this.observeVisibleTextAfterToolCall(d);let r="";d.startsWith(i.sentText)?r=d.slice(i.sentText.length):(e||t.finalizeDsml)&&(r=d),!(!r&&!e)&&(i.repliedViaTool||(i.seq+=1,this.callbacks.sendStreamChunk(i.inbound.event_id,i.inbound.session_id,r,i.seq,e,`${i.inbound.event_id}-dsh`,this.quotedMessageId)),i.sentText=d)}surfaceSuppressedDsmlToolCalls(e){if(!this.active||e.length===0)return;const t=this.active.dsmlSuppressedKeys??new Set;this.active.dsmlSuppressedKeys=t;for(const i of e){const s=be(i);if(t.has(s)||(t.add(s),this.markToolCallAwaitingFinalText(),g.warn(p,`suppressed leaked DSML tool markup name=${i.name} event=${this.active.inbound.event_id}`),!this.toolEventsEnabled()))continue;let n=i.arguments;try{n=JSON.parse(i.arguments)}catch{}this.sendRaw("tool_call",{call_id:`dsml-${t.size}`,tool_name:i.name,tool_input:n,source:"dsml_text_leak",executed:!1},`[tool] ${i.name}`)}}markToolCallAwaitingFinalText(){const e=this.active;e&&(e.toolCallAwaitingFinalText=!0,e.toolCallVisibleTextLength=e.sentText.length)}observeVisibleTextAfterToolCall(e){const t=this.active;if(!t?.toolCallAwaitingFinalText)return;const i=t.toolCallVisibleTextLength??t.sentText.length;e.slice(i).trim().length!==0&&(t.toolCallAwaitingFinalText=!1,t.toolCallVisibleTextLength=void 0)}collectCommittedUsage(e,t){if(this.activeCommittedUsageSeqs.has(t))return;this.activeCommittedUsageSeqs.add(t);const i=te(e);this.activeUsage.inputTokens+=i.inputTokens,this.activeUsage.outputTokens+=i.outputTokens,this.activeUsage.cacheReadInputTokens+=i.cacheReadInputTokens,this.activeUsage.cacheCreationInputTokens+=i.cacheCreationInputTokens,this.activeUsage.reasoningTokens+=i.reasoningTokens,this.activeUsageSeq=Math.max(this.activeUsageSeq,t),this.updateContextWindow(i)}updateContextWindow(e){const t=te(e),i=this.resolveDesiredSettings(),s=this.models.find(a=>a.id===i.modelId),n=this.reportedContextCapacity??s?.contextWindow;if(n&&n>0){const a=t.inputTokens+t.cacheReadInputTokens+t.cacheCreationInputTokens;this.contextWindow={usedTokens:a,totalTokens:n,remainingTokens:Math.max(0,n-a),usedPercentage:a/n*100,remainingPercentage:Math.max(0,100-a/n*100)},this.pushToolbarMeta()}}updateContextCapacity(e){const t=Number(e?.contextWindow);if(!Number.isFinite(t)||t<=0)return;this.reportedContextCapacity=t;const i=this.contextWindow&&typeof this.contextWindow=="object"?this.contextWindow:{},s=Math.max(0,Number(i.usedTokens)||0);this.contextWindow={usedTokens:s,totalTokens:t,remainingTokens:Math.max(0,t-s),usedPercentage:s/t*100,remainingPercentage:Math.max(0,100-s/t*100)},this.pushToolbarMeta()}finishFromTurnOutcome(){if(!this.active)return;this.finishingTurn=!0;const e=this.active.outcome??"completed",t=this.active.outcomeDetail?.trim();e==="completed"?this.finishActive("responded"):e==="aborted"?this.finishActive("canceled"):e==="max-tokens"&&this.active.sentText?this.finishActive("responded","Response truncated at model token limit"):this.finishActive("failed",t?t.toLowerCase().includes(e.toLowerCase())?`Harness turn ended: ${t}`:`Harness turn ended: ${e}: ${t}`:`Harness turn ended: ${e}`)}finishActive(e,t){const i=this.active;if(!i)return;let s=this.cancelRequested?"canceled":e,n=this.cancelRequested?"user canceled":t;this.finishingTurn=!0,this.clearTimeout(),this.promotePendingTextToVisible(),this.flushVisibleText(!1,{finalizeDsml:!0}),s==="responded"&&i.toolCallAwaitingFinalText&&!i.repliedViaTool&&(s="failed",n="DeepSeek Harness ended after a tool call without returning final assistant text",g.warn(p,`${n} event=${i.inbound.event_id}`)),i.text=i.sentText;const a=s==="failed"&&!!n?.trim();a&&(i.text+=`
5
+ `,t.seq,!1,`${t.inbound.event_id}-dsh`,this.quotedMessageId)))}flushVisibleText(e,t={}){const i=this.active;if(!i)return;const s=K(i.text);s.quotedMessageId&&(this.quotedMessageId=s.quotedMessageId);const n=s.text.replace(/\[\[quoted_message_id:[^\]]*$/g,""),r=_e(n,{finalize:t.finalizeDsml===!0||e});this.surfaceSuppressedDsmlToolCalls(r.suppressedToolCalls);const d=r.visible;this.observeVisibleTextAfterToolCall(d);let a="";d.startsWith(i.sentText)?a=d.slice(i.sentText.length):(e||t.finalizeDsml)&&(a=d),!(!a&&!e)&&(i.repliedViaTool||(i.seq+=1,this.callbacks.sendStreamChunk(i.inbound.event_id,i.inbound.session_id,a,i.seq,e,`${i.inbound.event_id}-dsh`,this.quotedMessageId)),i.sentText=d)}surfaceSuppressedDsmlToolCalls(e){if(!this.active||e.length===0)return;const t=this.active.dsmlSuppressedKeys??new Set;this.active.dsmlSuppressedKeys=t;for(const i of e){const s=be(i);if(t.has(s)||(t.add(s),this.markToolCallAwaitingFinalText(),g.warn(p,`suppressed leaked DSML tool markup name=${i.name} event=${this.active.inbound.event_id}`),!this.toolEventsEnabled()))continue;let n=i.arguments;try{n=JSON.parse(i.arguments)}catch{}this.sendRaw("tool_call",{call_id:`dsml-${t.size}`,tool_name:i.name,tool_input:n,source:"dsml_text_leak",executed:!1},`[tool] ${i.name}`)}}markToolCallAwaitingFinalText(){const e=this.active;e&&(e.toolCallAwaitingFinalText=!0,e.toolCallVisibleTextLength=e.sentText.length)}observeVisibleTextAfterToolCall(e){const t=this.active;if(!t?.toolCallAwaitingFinalText)return;const i=t.toolCallVisibleTextLength??t.sentText.length;e.slice(i).trim().length!==0&&(t.toolCallAwaitingFinalText=!1,t.toolCallVisibleTextLength=void 0)}collectCommittedUsage(e,t){if(this.activeCommittedUsageSeqs.has(t))return;this.activeCommittedUsageSeqs.add(t);const i=te(e);this.activeUsage.inputTokens+=i.inputTokens,this.activeUsage.outputTokens+=i.outputTokens,this.activeUsage.cacheReadInputTokens+=i.cacheReadInputTokens,this.activeUsage.cacheCreationInputTokens+=i.cacheCreationInputTokens,this.activeUsage.reasoningTokens+=i.reasoningTokens,this.activeUsageSeq=Math.max(this.activeUsageSeq,t),this.updateContextWindow(i)}updateContextWindow(e){const t=te(e),i=this.resolveDesiredSettings(),s=this.models.find(r=>r.id===i.modelId),n=this.reportedContextCapacity??s?.contextWindow;if(n&&n>0){const r=t.inputTokens+t.cacheReadInputTokens+t.cacheCreationInputTokens;this.contextWindow={usedTokens:r,totalTokens:n,remainingTokens:Math.max(0,n-r),usedPercentage:r/n*100,remainingPercentage:Math.max(0,100-r/n*100)},this.pushToolbarMeta()}}updateContextCapacity(e){const t=Number(e?.contextWindow);if(!Number.isFinite(t)||t<=0)return;this.reportedContextCapacity=t;const i=this.contextWindow&&typeof this.contextWindow=="object"?this.contextWindow:{},s=Math.max(0,Number(i.usedTokens)||0);this.contextWindow={usedTokens:s,totalTokens:t,remainingTokens:Math.max(0,t-s),usedPercentage:s/t*100,remainingPercentage:Math.max(0,100-s/t*100)},this.pushToolbarMeta()}finishFromTurnOutcome(){if(!this.active)return;this.finishingTurn=!0;const e=this.active.outcome??"completed",t=this.active.outcomeDetail?.trim();e==="completed"?this.finishActive("responded"):e==="aborted"?this.finishActive("canceled"):e==="max-tokens"&&this.active.sentText?this.finishActive("responded","Response truncated at model token limit"):this.finishActive("failed",t?t.toLowerCase().includes(e.toLowerCase())?`Harness turn ended: ${t}`:`Harness turn ended: ${e}: ${t}`:`Harness turn ended: ${e}`)}finishActive(e,t){const i=this.active;if(!i)return;let s=this.cancelRequested?"canceled":e,n=this.cancelRequested?"user canceled":t;this.finishingTurn=!0,this.clearTimeout(),this.promotePendingTextToVisible(),this.flushVisibleText(!1,{finalizeDsml:!0}),s==="responded"&&i.toolCallAwaitingFinalText&&!i.repliedViaTool&&(s="failed",n="DeepSeek Harness ended after a tool call without returning final assistant text",g.warn(p,`${n} event=${i.inbound.event_id}`)),i.text=i.sentText;const r=s==="failed"&&!!n?.trim();r&&(i.text+=`
6
6
 
7
- Error: ${n}`,this.flushVisibleText(!1,{finalizeDsml:!0})),s==="responded"&&this.activeUsageSeq>=0&&(this.usageStore().commit(i.inbound.session_id,this.runtimeSessionId,this.activeUsageSeq,this.applied?.modelId??this.resolveDesiredSettings().modelId,this.activeUsage),this.usageStore().flush()),i.inbound.audit?.enabled&&this.capture&&this.auditBoundaries.set(i.inbound.event_id,this.capture.boundary({runtimeSessionId:this.runtimeSessionId,rootSessionId:this.runtimeSessionId,startOffset:this.activeWireStart,turn:i.turn,messageId:i.messageId}));const d=this.personaDirty&&!!this.runtime,r=!!this.runtime&&!!this.applied&&this.applied.appliedRevision!==this.resolveDesiredSettings().revision;d&&this.emit("pauseIntake","barrier"),this.active=null,this.correlator=null;const f=`${i.inbound.event_id}-dsh`,u=(o,l,c=!1)=>{this.callbacks.sendEventResult(i.inbound.event_id,o,l,c),this.emit("eventDone",i.inbound.event_id),d?this.rebuildRuntime("persona_changed"):r&&this.rebuildRuntime("settings_changed")};if(i.repliedViaTool&&i.seq===0){this.flushPendingFinalBridgeAck(!0).then(()=>u(s,n,a),()=>u(s,n,a));return}this.callbacks.sendFinalStreamChunkReliable(i.inbound.event_id,i.inbound.session_id,f).then(async()=>{await this.flushPendingFinalBridgeAck(!0),u(s,n,a)},async o=>{await this.flushPendingFinalBridgeAck(!1),u(s==="responded"?"failed":s,s==="responded"?`Final output delivery failed: ${this.redactError(o,i.inbound.content)}`:n)})}advanceBridgeAck(e,t){if(!(e<=0)){if(t||this.finishingTurn||this.pendingFinalBridgeAck!==null){this.pendingFinalBridgeAck=Math.max(this.pendingFinalBridgeAck??0,e);return}this.ackBridgeCursor(e)}}async flushPendingFinalBridgeAck(e){const t=this.pendingFinalBridgeAck;this.pendingFinalBridgeAck=null,this.finishingTurn=!1,!(!e||t===null)&&await this.ackBridgeCursor(t)}async ackBridgeCursor(e){if(e<=this.bridgeAckCursor)return;const t=this.runtime?.client?.ack;if(!t){this.bridgeAckCursor=Math.max(this.bridgeAckCursor,e);return}try{await t.call(this.runtime.client,e),this.bridgeAckCursor=Math.max(this.bridgeAckCursor,e)}catch(i){if(i?.code==="aborted"){g.warn(p,`Bridge ACK timed out for cursor ${e} (acked=${this.bridgeAckCursor}); leaving cursor unacked for later retry/replay`);return}this.onProtocolError(i instanceof Error?i:new Error(String(i)))}}async cancelActive(e){this.active&&(this.cancelRequested=!0,this.clearPendingApprovals("cancelled"),this.resolveIntegrationMode()==="embedded_jsonrpc"?(this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="applied",this.pushToolbarMeta(),this.runtimeStartPromise&&this.runtime&&await this.runtime.terminate().catch(()=>{}),await this.runtimeStartPromise?.catch(()=>{}),await this.stopRuntime(!0)):(await this.runtimeStartPromise?.catch(()=>{}),await this.runtime?.cancel(this.runtimeSessionId).catch(()=>{}),this.runtime&&!this.runtime.isConnected()&&await this.stopRuntime(!0)),this.finishActive("canceled",e))}async handleBridgeApproval(e){const t=this.permissionHandler,i=String(e.interactionId??e.callId??D());if(t)try{return await t({adapterSessionId:this.options.aibotSessionId,requestId:i,description:String(e.reason??`Allow ${String(e.toolName??"operation")}?`),options:[{id:"allow_once",label:"Allow once",isAllow:!0},{id:"reject",label:"Reject",isAllow:!1}]})==="allow_once"?"allowed-once":"rejected"}catch{return"cancelled"}const s=this.active;return s?(this.callbacks.sendPermissionCard({eventId:s.inbound.event_id,sessionId:s.inbound.session_id,approvalId:i,toolName:String(e.toolName??"operation"),toolTitle:String(e.reason??`Allow ${String(e.toolName??"operation")}?`)}),new Promise(n=>{const a=setTimeout(()=>{this.pendingApprovals.delete(i),n("unavailable")},3e5);a.unref?.(),this.pendingApprovals.set(i,{resolve:n,timer:a})})):"unavailable"}async invokeGrixTool(e,t,i){if(!ut(e))throw Object.assign(new Error(`grix tool "${e}" is not exposed to DSH`),{code:"capability_unavailable"});if(ct(e)){if(!this.callbacks.eventToolInvoke)throw Object.assign(new Error(`grix event tool "${e}" has no connector-side runner`),{code:"capability_unavailable"});const n=this.active,a=await this.callbacks.eventToolInvoke(e,t);if(e==="grix_reply"&&n){const d=String(t.session_id??"").trim();(!d||d===n.inbound.session_id)&&(n.repliedViaTool=!0)}return a}if(!this.callbacks.agentInvoke)throw Object.assign(new Error(`grix tool "${e}" has no connector-side action runner`),{code:"capability_unavailable"});const s=ht(e,t);return this.callbacks.agentInvoke(s.action,s.params,i??s.timeoutMs)}projectConnectorSkills(){const e=T(this.options.dataRoot,"dsh-session-skills"),t=fe(e);return t.length>0&&g.info(p,`Synced connector skills to ${e}: [${t.join(", ")}]`),e}rebuildRuntime(e){if(this.stopped||this.active)return Promise.resolve();if(this.rebuildPromise)return this.rebuildPromise;const t=(async()=>{this.emit("pauseIntake","barrier"),this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="pending",this.pushToolbarMeta();try{await this.stopRuntime(!0),await this.ensureRuntime()}catch(i){g.warn(p,`${e} rebuild failed: ${this.redactError(i)}`)}finally{this.emit("resumeIntake","barrier")}})();return this.rebuildPromise=t.finally(()=>{this.rebuildPromise=null;const i=this.resolveDesiredSettings().revision;!this.stopped&&!this.active&&(this.personaDirty||this.applied&&this.applied.appliedRevision!==i)&&this.rebuildRuntime("coalesced_state_changed")}),this.rebuildPromise}async stopRuntime(e){const t=this.runtime;t&&(this.intentionalRuntimeStop=e,this.runtime=null,await t.shutdown().catch(()=>t.terminate()),this.capture?.close(),this.capture=null,this.intentionalRuntimeStop=!1)}onRuntimeExit(e){if(!(this.intentionalRuntimeStop||this.stopped)&&!(e&&this.replaySupersededRuntimes.has(e))){if(this.runtime=null,this.capture?.close(),this.capture=null,this.applied=void 0,this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState="failed",this.settingsErrorCode="runtime_exited",this.pushToolbarMeta(),this.active){if(this.isPromptUnaccepted(this.active)){g.warn(p,`Harness runtime exited before accepting prompt ${this.active.inbound.event_id}; awaiting in-flight prompt failure`);return}this.finishActive("failed","Harness runtime exited; prompt was not replayed")}this.emit("exit",1)}}onProtocolError(e){if(this.stopped||!this.runtime&&!this.active)return;const t=this.redactError(e,this.active?.inbound.content);g.warn(p,`Harness protocol error: ${t}`),this.clearPendingApprovals("unavailable"),this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState="failed",this.settingsErrorCode="protocol_error",this.pushToolbarMeta();const i=this.runtime;this.runtime=null,this.intentionalRuntimeStop=!0,i?.client?.close(e),this.active&&this.finishActive("failed",`Harness protocol error: ${t}`),i?.terminate().finally(()=>{this.intentionalRuntimeStop=!1}),this.emit("exit",1)}async executeLocalAction(e){const t=e.params??{},i=String(t.session_id??"");if(!i||i!==this.options.aibotSessionId)return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing"};if(["exec_approve","exec_reject","permission_approve","permission_reject"].includes(e.action_type)){const o=String(t.approval_command_id??t.approval_id??t.request_id??"").trim(),l=this.pendingApprovals.get(o);if(!l)return{status:"failed",errorCode:"unknown_or_expired_approval_id",errorMsg:"That DSH approval request is no longer pending"};clearTimeout(l.timer),this.pendingApprovals.delete(o);const c=e.action_type==="exec_approve"||e.action_type==="permission_approve";return l.resolve(c?"allowed-once":"rejected"),{status:"ok",result:{approval_id:o,decision:c?"allow-once":"deny"}}}if(e.action_type==="get_session_usage")return{status:"ok",result:{adapterType:"deepseek-harness",available:!0,dsh_profile:this.resolveSelectedProfile(),...this.usageStore().get(i)}};if(e.action_type==="get_rate_limits"){this.providerQuota=null,this.pushToolbarMeta();try{this.providerQuota=await this.callbacks.queryProviderQuota(!0,this.providerQuotaHint())??this.providerQuotaFallback()}catch(o){this.providerQuota={...this.providerQuotaFallback(),error:this.redactError(o)}}return this.pushToolbarMeta(),{status:"ok",result:{sampledAt:new Date().toISOString(),contextWindow:this.contextWindow,providerQuota:this.providerQuota}}}if(e.action_type==="dsh_bridge_status"||e.action_type==="dsh_install_bridge"){if(this.resolveIntegrationMode()!=="profile_bridge")return{status:"unsupported",errorCode:"capability_unavailable",errorMsg:"Bridge management requires Profile Bridge mode"};if(this.active||this.runtime)return{status:"failed",errorCode:"worker_busy",errorMsg:"Stop the active DSH session before changing its Profile plugin"};try{const o=new A({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),l=e.action_type==="dsh_install_bridge"?await o.install():await o.status();return this.runtimeReadiness=l.readiness,this.settingsErrorCode=l.readiness==="ready"?null:l.readiness,this.pushToolbarMeta(),{status:"ok",result:Tt(l)}}catch(o){const l=String(o?.code??"bridge_install_failed");return this.runtimeReadiness=l,this.settingsErrorCode=l,this.pushToolbarMeta(),{status:"failed",errorCode:l,errorMsg:this.redactError(o)}}}if(e.action_type==="dsh_list_plugins"||e.action_type==="dsh_refresh_plugins"||e.action_type==="dsh_enable_plugin"||e.action_type==="dsh_disable_plugin")return this.executePluginAction(e.action_type,t,i);if(e.action_type==="dsh_list_skills"||e.action_type==="dsh_enable_skill"||e.action_type==="dsh_disable_skill")return this.executeSkillAction(e.action_type,t,i);const n={dsh_list_mcp:"mcp/list",dsh_list_tools:"tools/list",dsh_list_jobs:"jobs/list",dsh_list_goals:"goals/list"}[e.action_type];if(n){if(this.resolveIntegrationMode()!=="profile_bridge")return{status:"unsupported",errorCode:"capability_unavailable",errorMsg:"DSH resources require Profile Bridge mode"};if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot query DSH resources during an active turn"};try{return await this.ensureRuntimeWithRetry(),{status:"ok",result:await this.runtime?.client?.call(n,{cwd:this.options.bindingStore.get(i)?.cwd})}}catch(o){const l=String(o?.code??"resource_query_failed");return{status:l==="capability_unavailable"?"unsupported":"failed",errorCode:l,errorMsg:this.redactError(o)}}}if(e.action_type==="set_profile"||e.action_type==="create_profile"){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek Harness Profile during an active turn"};if(!this.options.bindingStore.get(i))return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};let o;try{o=Re(String(t.profile_id??t.dsh_profile??t.profile_name??t.name??""))}catch(c){return{status:"failed",errorCode:"profile_invalid",errorMsg:this.redactError(c)}}if(this.options.bindingStore.isDshProfileLocked(i)){const c=this.resolveSelectedProfile();return e.action_type==="create_profile"||c!==o?{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}:this.finishProfileSelection(o,!1)}if(e.action_type==="create_profile")try{const c=this.options.createDshProfile?await this.options.createDshProfile(o):await ye({profileName:o,dshHome:this.options.dshHome??this.config.env?.DSH_HOME}),b=c.identity?.profileName??o;return this.persistSelectedProfile(b)?(await this.flushSelectedProfile(),this.finishProfileSelection(b,c.created)):{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}}catch(c){return{status:"failed",errorCode:String(c?.code??"profile_create_failed"),errorMsg:this.redactError(c)}}return this.listProfiles().some(c=>c.id===o)?this.persistSelectedProfile(o)?(await this.flushSelectedProfile(),this.finishProfileSelection(o,!1)):{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}:{status:"failed",errorCode:"profile_not_found",errorMsg:"Requested DSH profile is not in the local catalog"}}if(e.action_type==="set_preset"){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek Harness settings during an active turn"};if(!this.options.bindingStore.get(i)?.cwd)return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const l=String(t.agent_preset_id??t.preset_id??"").trim();if(!this.presets.some(b=>b.id===l))return{status:"failed",errorCode:"preset_not_found",errorMsg:"Requested agent preset is not in the Harness catalog"};const c=Z(this.resolveDesiredSettings().agentPreset,this.presets);return this.options.bindingStore.isDshAgentPresetLocked(i)?c===l?{status:"ok",result:this.presetActionResult(l,!0)}:{status:"failed",errorCode:"agent_preset_locked",errorMsg:"This conversation scene is locked after the session is created"}:c===l?(this.options.bindingStore.setDshAgentPreset(i,l),await this.persistGlobalToolbarDefaults({dshAgentPreset:l}),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(l,!1)}):this.options.bindingStore.setDshAgentPreset(i,l)?(await this.persistGlobalToolbarDefaults({dshAgentPreset:l}),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(l,!1)}):{status:"failed",errorCode:"agent_preset_locked",errorMsg:"This conversation scene is locked after the session is created"}}if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek Harness settings during an active turn"};if(!this.options.bindingStore.get(i)?.cwd)return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const d=this.resolveDesiredSettings();let r;if(e.action_type==="set_provider"){const o=String(t.provider_id??"").trim();if(!this.providers.some(l=>l.id===o))return{status:"failed",errorCode:"provider_not_found",errorMsg:"Requested provider is not in the Harness catalog"};r={providerId:o},o!==d.providerId&&(this.models=ot(this.options.dataRoot,o),this.catalogProviderId=o,this.models.some(l=>l.id===d.modelId)||(r.modelId=this.models[0]?.id))}else if(e.action_type==="set_model"){const o=String(t.model_id??"").trim();if(!this.models.some(l=>l.id===o))return{status:"failed",errorCode:"model_not_found",errorMsg:"Requested model is not in the Harness catalog"};r={modelId:o}}else if(e.action_type==="set_thinking"){const o=q(t.thinking_mode??t.thinking);if(!o)return{status:"failed",errorCode:"thinking_invalid",errorMsg:"thinking_mode must be enabled or disabled"};r={thinking:o}}else if(e.action_type==="set_reasoning_effort"){const o=B(t.reasoning_effort??t.reasoningEffort);if(!o)return{status:"failed",errorCode:"reasoning_effort_invalid",errorMsg:"reasoning_effort must be high or max"};r={reasoningEffort:o}}else{const o=String(t.mode_id??"").trim();if(o!=="approval"&&o!=="full_auto")return{status:"failed",errorCode:"mode_invalid",errorMsg:"mode_id must be approval or full_auto"};r={modeId:o}}if((r.providerId===void 0||r.providerId===d.providerId)&&(r.modelId===void 0||r.modelId===d.modelId)&&(r.modeId===void 0||r.modeId===d.modeId)&&(r.thinking===void 0||r.thinking===d.thinking)&&(r.reasoningEffort===void 0||r.reasoningEffort===d.reasoningEffort)&&this.applied?.appliedRevision===d.revision)return{status:"ok",result:this.settingsActionResult(e.action_type,r,d.revision,"already_applied",!0)};const u=this.options.bindingStore.updateDshSettings(i,r)??d.revision;if(await this.options.bindingStore.flush(),(r.providerId||r.modelId||r.modeId||r.thinking||r.reasoningEffort)&&await this.persistGlobalToolbarDefaults({...r.providerId?{dshProviderId:r.providerId}:{},...r.modelId?{dshModelId:r.modelId}:{},...r.modeId?{dshModeId:r.modeId}:{},...r.thinking?{dshThinking:r.thinking}:{},...r.reasoningEffort?{dshReasoningEffort:r.reasoningEffort}:{}}),this.contextWindow=null,this.reportedContextCapacity=null,this.settingsErrorCode=null,this.runtimeStartPromise&&await this.runtimeStartPromise.catch(()=>{}),!this.runtime)return this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,r,u,"applied",!1)};if(this.active)return this.applied&&this.applied.appliedRevision>=u?(this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,r,u,"applied",!0)}):(this.settingsState="pending",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,r,u,"pending",!0)});this.settingsState="pending",this.pushToolbarMeta();try{if(await this.rebuildRuntime("settings_changed"),!this.applied||this.applied.appliedRevision<u)throw new Error("new runtime did not apply requested revision");return this.refreshProviderQuota(!0),{status:"ok",result:this.settingsActionResult(e.action_type,r,u,"applied",!0)}}catch(o){return{status:"failed",result:this.settingsActionResult(e.action_type,r,u,"failed",!1,this.redactError(o)),errorCode:"settings_apply_failed",errorMsg:this.redactError(o)}}}async finishProfileSelection(e,t){if(this.resolveIntegrationMode()==="profile_bridge")try{await this.prepareSelectedProfile()}catch(i){const s=String(i?.code??"profile_start_failed");return this.runtimeReadiness=s,this.settingsErrorCode=s,this.pushToolbarMeta(),{status:"failed",errorCode:s,errorMsg:this.redactError(i)}}return this.pushToolbarMeta(),{status:"ok",result:this.profileActionResult(e,t)}}createBridgeInstaller(){const e=this.options.bridgeInstallerOptions??{};return new A({command:e.command??"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile(),...e.tarballPath?{tarballPath:e.tarballPath}:{}})}async healBridgeUpdate(e){return e.readiness!=="bridge_update_required"||this.options.autoInstallBridge===!1?e:(g.info(p,`auto-updating stale Bridge profile=${e.identity.profileName} installed=${e.installedBridgeVersion??"none"} bundled=${e.bundledBridgeVersion}`),await this.prepareSelectedProfile(),this.attachSelectedProfile())}async ensureProfileReadyForChat(){if(!(this.options.autoInstallBridge!==!1||this.options.autoStartProfile!==!1)){const s=await this.attachSelectedProfile(),n=H(s);if(n)throw n;return}this.settingsState="pending",this.pushToolbarMeta(),await this.prepareSelectedProfile();let t=await this.attachSelectedProfile();t.readiness==="bridge_update_required"&&(t=await this.healBridgeUpdate(t));const i=H(t);if(i)throw i}async attachSelectedProfile(){const t=await this.createBridgeInstaller().status();return this.runtimeReadiness=t.readiness,this.profileDshVersion=t.runningDshVersion??t.dshVersion??null,this.settingsErrorCode=t.readiness==="ready"?null:t.readiness,t}async prepareSelectedProfile(){const e=this.createBridgeInstaller(),t=await Ne({installer:e,autoInstall:this.options.autoInstallBridge!==!1,autoStart:this.options.autoStartProfile!==!1});this.runtimeReadiness=t.readiness,this.profileDshVersion=t.runningDshVersion??t.dshVersion??null,this.settingsErrorCode=t.readiness==="ready"?null:t.readiness}profileActionResult(e,t){return{outcome:t?"profile_created":"profile_set",profile_id:e,dsh_profile:e,created:t,dsh_profile_locked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),dsh_profile_create:!this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),available_profiles:this.listProfiles(),session_context:{dsh_profile:e,dsh_profile_locked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),dsh_profile_create:!this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId)}}}persistSelectedProfile(e){return this.options.bindingStore.setDshSelectedProfile(this.options.aibotSessionId,e)?(this.options.globalConfigStore?.set(this.options.agentName,{dshProfile:e}),!0):!1}async persistGlobalToolbarDefaults(e){this.options.globalConfigStore&&Object.values(e).some(t=>t!==void 0)&&(this.options.globalConfigStore.set(this.options.agentName,e),await this.options.globalConfigStore.flush())}seedSessionToolbarFromGlobal(){const e=this.options.aibotSessionId,t=this.options.bindingStore.get(e);if(!t?.cwd)return;const i=this.resolveDesiredSettings(),s={};t.dshProviderId||(s.providerId=i.providerId),t.dshModelId||(s.modelId=i.modelId),t.dshModeId||(s.modeId=i.modeId),t.dshThinking||(s.thinking=i.thinking),t.dshReasoningEffort||(s.reasoningEffort=i.reasoningEffort),Object.keys(s).length>0&&this.options.bindingStore.updateDshSettings(e,s),!this.options.bindingStore.getDshAgentPreset(e)&&i.agentPreset&&this.options.bindingStore.setDshAgentPreset(e,i.agentPreset),this.options.bindingStore.getDshSelectedProfile(e)||this.options.bindingStore.setDshSelectedProfile(e,this.resolveSelectedProfile())}async flushSelectedProfile(){await this.options.bindingStore.flush(),await this.options.globalConfigStore?.flush()}listProfiles(){return Ae({dshHome:this.options.dshHome??this.config.env?.DSH_HOME})}pluginCommandContext(){return{dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile(),enabledPluginIds:this.options.bindingStore.getDshEnabledPlugins(this.options.aibotSessionId)}}skillCommandContext(){return{skillsDir:this.projectConnectorSkills(),enabledSkillIds:this.options.bindingStore.getDshEnabledSkills(this.options.aibotSessionId)}}currentPlugins(){try{return R(this.pluginCommandContext())}catch{return[]}}currentSkills(){return this.sessionSkillControlUnavailable()?[]:M(this.skillCommandContext())}pluginRestartRequired(){return!1}async executePluginAction(e,t,i){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek plugins during an active turn"};if(!this.options.bindingStore.get(i))return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const s=this.pluginCommandContext();try{if(e==="dsh_list_plugins"||e==="dsh_refresh_plugins"){const o=R(s);return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(o,!1)}}const n=String(t.name??t.plugin_name??"").trim(),a=this.options.bindingStore.getDshEnabledPlugins(i);let d=n;try{const{plugin:o}=Pe({...s,name:n});d=o.name}catch(o){const l=String(o?.code??"");if(e!=="dsh_disable_plugin"||l!=="plugin_not_found"||!a.includes(n))throw o}const r=Ee(a,d,e==="dsh_enable_plugin"),f=this.options.bindingStore.setDshEnabledPlugins(i,r.pluginIds)??this.resolveDesiredSettings().revision;await this.options.bindingStore.flush();const u=R({...s,enabledPluginIds:r.pluginIds});if(!r.changed)return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(u,!1,"skipped")};if(this.runtimeStartPromise&&await this.runtimeStartPromise.catch(()=>{}),!this.runtime)return this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(u,!0,"skipped")};if(this.active)return this.settingsState="pending",this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(u,!0,"pending")};if(this.settingsState="pending",this.pushToolbarMeta(),await this.rebuildRuntime("plugin_changed"),!this.applied||this.applied.appliedRevision<f)throw new Error("new runtime did not apply requested plugin revision");return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(u,!0,"restarted")}}catch(n){return{status:"failed",errorCode:String(n?.code??"plugin_action_failed"),errorMsg:this.redactError(n)}}}async executeSkillAction(e,t,i){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek skills during an active turn"};if(!this.options.bindingStore.get(i))return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};if(this.sessionSkillControlUnavailable())return this.pushToolbarMeta(),{status:"unsupported",errorCode:"capability_unavailable",errorMsg:`DSH session skills require @deepseek-ai/dsh ${ae} or newer`};const s=this.skillCommandContext();try{if(e==="dsh_list_skills"){const o=M(s);return this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(o,!1)}}const n=String(t.name??t.skill_name??"").trim(),a=this.options.bindingStore.getDshEnabledSkills(i);let d=n;try{d=Ce({...s,name:n}).name}catch(o){const l=String(o?.code??"");if(e!=="dsh_disable_skill"||l!=="skill_not_found"||!a.includes(n))throw o}const r=xe(a,d,e==="dsh_enable_skill"),f=this.options.bindingStore.setDshEnabledSkills(i,r.skillIds)??this.resolveDesiredSettings().revision;await this.options.bindingStore.flush();const u=M({...s,enabledSkillIds:r.skillIds});if(!r.changed)return this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(u,!1,"skipped")};if(this.runtimeStartPromise&&await this.runtimeStartPromise.catch(()=>{}),!this.runtime)return this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(u,!0,"skipped")};if(this.active)return this.settingsState="pending",this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(u,!0,"pending")};if(this.settingsState="pending",this.pushToolbarMeta(),await this.rebuildRuntime("skill_changed"),!this.applied||this.applied.appliedRevision<f)throw new Error("new runtime did not apply requested skill revision");return this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(u,!0,"restarted")}}catch(n){return{status:"failed",errorCode:String(n?.code??"skill_action_failed"),errorMsg:this.redactError(n)}}}pluginActionResult(e,t,i="skipped"){const s=this.resolveSelectedProfile(),n=this.pluginRestartRequired();return{outcome:t?i==="restarted"?"plugin_applied":"plugin_updated":"plugin_unchanged",dsh_profile:s,dsh_plugins:e,dsh_plugin_restart_required:n,restart:i,session_context:{dsh_profile:s,dsh_plugins:e,dsh_plugin_restart_required:n}}}skillActionResult(e,t,i="skipped"){return{outcome:t?i==="restarted"?"skill_applied":"skill_updated":"skill_unchanged",dsh_skills:e,restart:i,session_context:{dsh_skills:e}}}resolveSelectedProfile(){const e=this.options.bindingStore.getDshSelectedProfile(this.options.aibotSessionId),t=Be({binding:e,global:this.options.globalConfigStore?.get(this.options.agentName)?.dshProfile,adapter:this.options.dshProfile});return this.options.bindingStore.get(this.options.aibotSessionId)&&e!==t&&this.options.bindingStore.setDshSelectedProfile(this.options.aibotSessionId,t),t}profileDataDir(e=this.resolveSelectedProfile()){return He(this.options.dataRoot,e)}usageStore(){const e=this.resolveSelectedProfile(),t=T(this.profileDataDir(e),"session-usage.json"),i=T(this.options.dataRoot,"session-usage.json");return!W(t)&&W(i)&&(pe(ge(t),{recursive:!0,mode:448}),ue(i,t)),lt(t)}presetActionResult(e,t){const i=this.resolveDesiredSettings();return{outcome:"preset_set",agentPreset:e,agent_preset_id:e,agent_preset_locked:t,available_presets:[...this.presets],session_context:{agent_preset_id:i.agentPreset??e,agent_preset_locked:t}}}settingsActionResult(e,t,i,s,n,a){const d=this.resolveDesiredSettings(),r=d.revision||i,f={provider_id:d.providerId,model_id:d.modelId,mode_id:d.modeId,thinking_mode:d.thinking,reasoning_effort:d.reasoningEffort,applied_provider_id:this.applied?.providerId??null,applied_model_id:this.applied?.modelId??null,applied_mode_id:this.applied?.modeId??null,applied_thinking_mode:this.applied?.thinking??null,applied_reasoning_effort:this.applied?.reasoningEffort??null,applied_settings_revision:this.applied?.appliedRevision??null,settings_state:this.settingsState,settings_revision:r};return e==="set_mode"&&(f.sandbox_mode=Y(d.modeId),f.approval_policy=d.modeId==="full_auto"?"never":"ask"),{outcome:`${e==="set_provider"?"provider":e==="set_model"?"model":e==="set_thinking"?"thinking":e==="set_reasoning_effort"?"reasoning_effort":"mode"}_set${s==="pending"||s==="failed"?"_pending":""}`,...t.providerId?{providerId:t.providerId,provider_id:t.providerId}:{},...t.modelId?{modelId:t.modelId,model_id:t.modelId}:{},...t.modeId?{modeId:t.modeId,mode_id:t.modeId,sandbox_mode:Y(t.modeId),approval_policy:t.modeId==="full_auto"?"never":"ask"}:{},...t.thinking?{thinking:t.thinking,thinking_mode:t.thinking}:{},...t.reasoningEffort?{reasoningEffort:t.reasoningEffort,reasoning_effort:t.reasoningEffort}:{},settingsRevision:r,settings_revision:r,sessionAlive:n,available_providers:[...this.providers],available_models:[...this.models],session_context:f,...a?{error:a}:{}}}hydrateCatalogFromCache(){const e=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),t=this.options.globalConfigStore?.get(this.options.agentName),i=rt({dataRoot:this.options.dataRoot,providerId:e?.providerId??t?.dshProviderId});this.providers=i.providers,this.models=this.options.models?.length?this.options.models:i.models,this.catalogProviderId=i.providerId}async persistCatalogCache(e){try{await at({dataRoot:this.options.dataRoot,providers:this.providers,providerId:e,models:this.models})}catch(t){g.warn(p,`failed to persist DSH catalog cache: ${t instanceof Error?t.message:String(t)}`)}}async writeGrixProviderFile(){const e=$e(this.options.dshHome??this.config.env?.DSH_HOME),t=await this.resolveCredentialsLayout(e);try{if(ie(this.options.provider)){await ft(e,v,this.options.provider??{},t)==="skipped"&&g.warn(p,`Grix provider not written to DSH settings (user-owned "${v}" route or unreadable YAML); relay will not take effect`);return}await gt(e,v)}catch(i){g.warn(p,`Failed to sync Grix provider into DSH settings: ${this.redactError(i)}`)}}async resolveCredentialsLayout(e){let t=this.profileDshVersion;if(!t)try{t=await qe(this.options.bridgeInstallerOptions?.command??"dsh",e)}catch(s){g.warn(p,`could not read dsh version, assuming the current credentials layout: ${this.redactError(s)}`)}const i=pt(t);return kt(t)&&g.warn(p,`dsh ${t} predates ${de}: it drops the supportsDeveloperRole / maxTokensField switches, so relayed requests keep the OpenAI-style wire format and the gateway rejects them. Upgrade dsh to use the Grix relay.`),i}syncGrixProvider(){if(ie(this.options.provider)){this.providers.some(s=>s.id===v)||(this.providers=[{id:v,displayName:"Grix"},...this.providers]);const e=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),t=this.options.globalConfigStore?.get(this.options.agentName),i=e?.providerId??t?.dshProviderId;(!i||i===$||i===v)&&this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,{providerId:v});return}this.providers=this.providers.filter(e=>e.id!==v)}resolveDesiredSettings(){const e=this.options.bindingStore.get(this.options.aibotSessionId),t=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),i=this.options.globalConfigStore?.get(this.options.agentName),s=t?.providerId??i?.dshProviderId,n=this.providers.some(f=>f.id===v)?v:void 0,a=st(s||n,this.providers),d=[t?.modelId,i?.dshModelId,this.options.defaultModel,this.models[0]?.id].find(f=>!!f&&this.models.some(u=>u.id===f))??"deepseek-chat",r=Z(t?.agentPreset??i?.dshAgentPreset,this.presets);return{providerId:a,modelId:d,modeId:it(e?.dshModeId,i?.dshModeId),thinking:q(t?.thinking)??q(i?.dshThinking)??Ze,reasoningEffort:B(t?.reasoningEffort)??B(i?.dshReasoningEffort)??Ye,agentPreset:r,pluginIds:this.options.bindingStore.getDshEnabledPlugins(this.options.aibotSessionId),skillIds:this.options.bindingStore.getDshEnabledSkills(this.options.aibotSessionId),skillIdsExplicit:Array.isArray(e?.dshSkillIds),maxTokens:t?.maxTokens??this.options.maxTokens??Ke,revision:t?.revision??0}}resolveIntegrationMode(){return this.options.integrationMode?this.options.integrationMode:(this.config.command||"").includes("dsh-jsonrpc-agent")?"embedded_jsonrpc":"profile_bridge"}sessionSkillControlUnavailable(){return this.resolveIntegrationMode()!=="profile_bridge"?!1:this.bridgeCapabilities&&typeof this.bridgeCapabilities=="object"?this.bridgeCapabilities.sessionSkillAllowlist!==!0:It(this.profileDshVersion)}pushToolbarMeta(){const e=this.options.bindingStore.get(this.options.aibotSessionId);this.callbacks.sendUpdateBindingCard(this.options.aibotSessionId,this.stopped?"stopped":this.active?"busy":"ready",e?.cwd,ze({desired:this.resolveDesiredSettings(),applied:this.applied,models:this.models,providers:this.providers,presets:this.presets,agentPresetLocked:this.options.bindingStore.isDshAgentPresetLocked(this.options.aibotSessionId),state:this.settingsState,errorCode:this.settingsErrorCode,contextWindow:this.contextWindow,providerQuota:this.providerQuota,integrationMode:this.resolveIntegrationMode(),profileName:this.resolveSelectedProfile(),profiles:this.listProfiles(),profileLocked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),plugins:this.currentPlugins(),skills:this.currentSkills(),pluginRestartRequired:this.pluginRestartRequired(),runtimeReadiness:this.runtimeReadiness,bridgeCapabilities:this.bridgeCapabilities}))}providerQuotaHint(){const e=this.resolveDesiredSettings(),t=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),i=this.options.globalConfigStore?.get(this.options.agentName);return{providerId:t?.providerId??i?.dshProviderId??e.providerId,model:e.modelId}}providerQuotaFallback(){const e=this.providerQuotaHint().providerId;return e==="opencode-go"||e==="opencode_go"?{provider:"opencode_go",providerLabel:"OpenCode Go",success:!1,error:"unavailable"}:{provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:"unavailable"}}async refreshProviderQuota(e){this.providerQuota=null,this.pushToolbarMeta();try{this.providerQuota=await this.callbacks.queryProviderQuota(e,this.providerQuotaHint())??this.providerQuotaFallback()}catch{this.providerQuota=this.providerQuotaFallback()}this.pushToolbarMeta()}clearPendingApprovals(e){for(const t of this.pendingApprovals.values())clearTimeout(t.timer),t.resolve(e);this.pendingApprovals.clear()}thinkingEnabled(){const e=this.active?.inbound.connector_runtime_config?.thinking_events??this.active?.inbound.connector_runtime_config?.thinkingEvents;return e!=="off"&&e!=="hidden"&&e!=="none"}toolEventsEnabled(){const e=this.active?.inbound.connector_runtime_config?.tool_events;return e!=="off"&&e!=="hidden"&&e!=="none"}sendRaw(e,t,i){this.active&&this.callbacks.sendRawEventEnvelope(this.active.inbound.event_id,this.active.inbound.session_id,{type:e,payload:t},i)}failEvent(e,t){this.callbacks.sendEventResult(e.event_id,"failed",t),this.emit("eventDone",e.event_id)}startTimeout(e){this.activeTimeoutMs=e??this.options.promptTimeoutMs??se,this.noteRuntimeActivity(),this.armTimeout(this.activeIdleTimeoutMs()),this.armHardTimeout(this.activeTimeoutMs)}touchActivity(e=1){!this.active||!this.timeoutTimer||(this.noteRuntimeActivity(),this.armTimeout(this.activeIdleTimeoutMs()))}noteRuntimeActivity(){this.active&&(this.active.lastRuntimeActivityAt=Date.now(),this.active.livenessExtendStartAt=void 0)}activeIdleTimeoutMs(){const e=this.options.activeIdleTimeoutMs??ne,t=Number.isFinite(e)&&e>0?e:ne;return Math.min(t,this.activeTimeoutMs)}livenessFreshMs(){const e=this.options.livenessFreshMs??oe;return Number.isFinite(e)&&e>0?e:oe}livenessMaxExtendMs(){const e=this.options.livenessMaxExtendMs??re;return Number.isFinite(e)&&e>0?e:re}armTimeout(e){this.clearIdleTimeout(),this.timeoutTimer=setTimeout(()=>{this.handlePromptTimeout()},e),this.timeoutTimer.unref?.()}armHardTimeout(e){this.clearHardTimeout(),this.hardTimeoutTimer=setTimeout(()=>{this.handlePromptHardTimeout()},e),this.hardTimeoutTimer.unref?.()}async handlePromptTimeout(){const e=this.active;if(e){if(this.pendingApprovals.size>0){g.info(p,`Idle timeout skipped: pendingApprovals=${this.pendingApprovals.size} event=${e.inbound.event_id}`),this.armTimeout(this.activeIdleTimeoutMs());return}if(this.shouldExtendByLiveness(e.inbound.event_id)){this.armTimeout(this.activeIdleTimeoutMs());return}await this.failActiveTimeout("idle","Harness prompt idle timeout and the runtime was terminated")}}async handlePromptHardTimeout(){const e=this.active;if(e&&this.shouldExtendByLiveness(e.inbound.event_id)){this.armHardTimeout(this.activeTimeoutMs);return}await this.failActiveTimeout("hard","Harness prompt exceeded max duration and the runtime was terminated")}shouldExtendByLiveness(e){const t=this.active;if(!t||t.inbound.event_id!==e||!this.runtime?.isConnected()||!(!t.turnEnded&&(!!t.messageId||t.admitted||t.claimed)))return!1;const s=Date.now(),n=t.lastRuntimeActivityAt??t.startedAt,a=Math.max(0,s-n);if(a<this.livenessFreshMs())return t.livenessExtendStartAt=s,g.info(p,`Liveness check: recent DSH activity for ${e} (quietMs=${a}), extending`),!0;const d=t.livenessExtendStartAt??n;t.livenessExtendStartAt=d;const r=s-d;return r>this.livenessMaxExtendMs()?(g.warn(p,`Liveness extension budget exhausted for ${e} (quietMs=${a}, extendMs=${r}), allowing close`),!1):(g.info(p,`Liveness check: DSH turn still open for ${e} (claimed=${t.claimed}, turnEnded=${t.turnEnded}, quietMs=${a}), extending`),!0)}async failActiveTimeout(e,t){if(!this.active)return;const i=this.active;this.clearTimeout();const s=this.runtime;this.runtime=null,this.intentionalRuntimeStop=!0,this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="applied",this.settingsErrorCode=null,this.pushToolbarMeta(),await s?.cancel(this.runtimeSessionId).catch(()=>{}),s&&await s.shutdown().catch(()=>s.terminate()),this.intentionalRuntimeStop=!1,!(this.active!==i||this.stopped)&&(g.error(p,`Active DSH turn ${e} timeout: ${i.inbound.event_id}`),this.finishActive("failed",t),this.emit("exit",1))}clearTimeout(){this.clearIdleTimeout(),this.clearHardTimeout()}clearIdleTimeout(){this.timeoutTimer&&clearTimeout(this.timeoutTimer),this.timeoutTimer=null}clearHardTimeout(){this.hardTimeoutTimer&&clearTimeout(this.hardTimeoutTimer),this.hardTimeoutTimer=null}redactError(e,t){let i=e instanceof Error?e.message:String(e);const s=this.config.env?.DEEPSEEK_API_KEY;return s&&(i=i.split(s).join("[REDACTED]")),i=i.replace(/(api[_-]?key|authorization|bearer)\s*[:=]\s*\S+/gi,"$1=[REDACTED]"),t&&t.length>=16&&i.includes(t)&&(i="Harness request failed (prompt echo redacted)"),(i.includes("[aibot-system-prompt]")||i.includes("[base-behavior]"))&&(i="Harness runtime failed (system prompt echo redacted)"),i.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g,"").slice(0,2e3)}}function vt(h){const e=Number(h&&typeof h=="object"?h.cursor:0);return Number.isSafeInteger(e)&&e>0?e:0}function bt(h){return new Promise(e=>setTimeout(e,h))}function _t(h,e){return`grix-${x("sha256").update(h).digest("hex").slice(0,12)}-${e}-${D().slice(0,8)}`}function St(h){return`grix-${x("sha256").update(h).digest("hex").slice(0,16)}-${D().slice(0,8)}`}function le(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,reasoningTokens:0}}function kt(h){const e=X(h,de);return e!==null&&e<0}function It(h){const e=X(h,ae);return e!==null&&e<0}function he(h){const e=h.data?.chunk&&typeof h.data.chunk=="object"?h.data.chunk:h.data;return String(e?.type??"")}function wt(h){return h.type==="assistant/chunk:tool-call-delta"||h.type==="assistant/chunk"&&he(h)==="tool-call-delta"}function Tt(h){return{readiness:h.readiness,profile:h.identity.profileName,dshVersion:h.dshVersion,runningDshVersion:h.runningDshVersion,installedBridgeVersion:h.installedBridgeVersion,bundledBridgeVersion:h.bundledBridgeVersion,runningBridgeVersion:h.runningBridgeVersion,endpointCount:h.endpointCount,requiresProfileRestart:h.readiness==="profile_restart_required"}}const yt=new Set(["turn/start","step/start","step/end","agent/inbox/spliced","user/message","request/header","system/message","assistant/attempt","session-log-deepseek/delivery-accepted","job/registered","job/settled","developer/message","session/title","session/title-llm-request","session/end-seed","web/deepseek-search-llm-request","assistant/chunk:tool-call-delta","permission/preset","sandbox/mode","approval/policy","approval/asked","approval/decided","plan/mode","agent-preset/selected","llm/retry","llm/retry-started","goal/change","schedule/change","feedback/record","hook/invoked","hook/result","command/run","command/done","subagent/descriptor","tool-workflow/agent-start","tool-workflow/agent-end","tool-workflow/run-start","tool-workflow/run-end","tool/code-dispatch","tool/code-dispatch-start"]);function Pt(h){const e=he(h);return yt.has(h.type)||h.type==="assistant/chunk"&&["block-start","block-end","tool-call-delta","finish"].includes(e)}export{li as DshJsonRpcAdapter};
7
+ Error: ${n}`,this.flushVisibleText(!1,{finalizeDsml:!0})),s==="responded"&&this.activeUsageSeq>=0&&(this.usageStore().commit(i.inbound.session_id,this.runtimeSessionId,this.activeUsageSeq,this.applied?.modelId??this.resolveDesiredSettings().modelId,this.activeUsage),this.usageStore().flush()),i.inbound.audit?.enabled&&this.capture&&this.auditBoundaries.set(i.inbound.event_id,this.capture.boundary({runtimeSessionId:this.runtimeSessionId,rootSessionId:this.runtimeSessionId,startOffset:this.activeWireStart,turn:i.turn,messageId:i.messageId}));const d=this.personaDirty&&!!this.runtime,a=!!this.runtime&&!!this.applied&&this.applied.appliedRevision!==this.resolveDesiredSettings().revision;d&&this.emit("pauseIntake","barrier"),this.active=null,this.correlator=null;const f=`${i.inbound.event_id}-dsh`,u=(o,l,c=!1)=>{this.callbacks.sendEventResult(i.inbound.event_id,o,l,c),this.emit("eventDone",i.inbound.event_id),d?this.rebuildRuntime("persona_changed"):a&&this.rebuildRuntime("settings_changed")};if(i.repliedViaTool&&i.seq===0){this.flushPendingFinalBridgeAck(!0).then(()=>u(s,n,r),()=>u(s,n,r));return}this.callbacks.sendFinalStreamChunkReliable(i.inbound.event_id,i.inbound.session_id,f).then(async()=>{await this.flushPendingFinalBridgeAck(!0),u(s,n,r)},async o=>{await this.flushPendingFinalBridgeAck(!1),u(s==="responded"?"failed":s,s==="responded"?`Final output delivery failed: ${this.redactError(o,i.inbound.content)}`:n)})}advanceBridgeAck(e,t){if(!(e<=0)){if(t||this.finishingTurn||this.pendingFinalBridgeAck!==null){this.pendingFinalBridgeAck=Math.max(this.pendingFinalBridgeAck??0,e);return}this.ackBridgeCursor(e)}}async flushPendingFinalBridgeAck(e){const t=this.pendingFinalBridgeAck;this.pendingFinalBridgeAck=null,this.finishingTurn=!1,!(!e||t===null)&&await this.ackBridgeCursor(t)}async ackBridgeCursor(e){if(e<=this.bridgeAckCursor)return;const t=this.runtime?.client?.ack;if(!t){this.bridgeAckCursor=Math.max(this.bridgeAckCursor,e);return}try{await t.call(this.runtime.client,e),this.bridgeAckCursor=Math.max(this.bridgeAckCursor,e)}catch(i){if(i?.code==="aborted"){g.warn(p,`Bridge ACK timed out for cursor ${e} (acked=${this.bridgeAckCursor}); leaving cursor unacked for later retry/replay`);return}this.onProtocolError(i instanceof Error?i:new Error(String(i)))}}async cancelActive(e){this.active&&(this.cancelRequested=!0,this.clearPendingApprovals("cancelled"),this.resolveIntegrationMode()==="embedded_jsonrpc"?(this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="applied",this.pushToolbarMeta(),this.runtimeStartPromise&&this.runtime&&await this.runtime.terminate().catch(()=>{}),await this.runtimeStartPromise?.catch(()=>{}),await this.stopRuntime(!0)):(await this.runtimeStartPromise?.catch(()=>{}),await this.runtime?.cancel(this.runtimeSessionId).catch(()=>{}),this.runtime&&!this.runtime.isConnected()&&await this.stopRuntime(!0)),this.finishActive("canceled",e))}async handleBridgeApproval(e){const t=this.permissionHandler,i=String(e.interactionId??e.callId??D());if(t)try{return await t({adapterSessionId:this.options.aibotSessionId,requestId:i,description:String(e.reason??`Allow ${String(e.toolName??"operation")}?`),options:[{id:"allow_once",label:"Allow once",isAllow:!0},{id:"reject",label:"Reject",isAllow:!1}]})==="allow_once"?"allowed-once":"rejected"}catch{return"cancelled"}const s=this.active;return s?(this.callbacks.sendPermissionCard({eventId:s.inbound.event_id,sessionId:s.inbound.session_id,approvalId:i,toolName:String(e.toolName??"operation"),toolTitle:String(e.reason??`Allow ${String(e.toolName??"operation")}?`)}),new Promise(n=>{const r=setTimeout(()=>{this.pendingApprovals.delete(i),n("unavailable")},3e5);r.unref?.(),this.pendingApprovals.set(i,{resolve:n,timer:r})})):"unavailable"}async invokeGrixTool(e,t,i){if(!ut(e))throw Object.assign(new Error(`grix tool "${e}" is not exposed to DSH`),{code:"capability_unavailable"});if(ct(e)){if(!this.callbacks.eventToolInvoke)throw Object.assign(new Error(`grix event tool "${e}" has no connector-side runner`),{code:"capability_unavailable"});const n=this.active,r=await this.callbacks.eventToolInvoke(e,t);if(e==="grix_reply"&&n){const d=String(t.session_id??"").trim();(!d||d===n.inbound.session_id)&&(n.repliedViaTool=!0)}return r}if(!this.callbacks.agentInvoke)throw Object.assign(new Error(`grix tool "${e}" has no connector-side action runner`),{code:"capability_unavailable"});const s=ht(e,t);return this.callbacks.agentInvoke(s.action,s.params,i??s.timeoutMs)}projectConnectorSkills(){const e=T(this.options.dataRoot,"dsh-session-skills"),t=fe(e);return t.length>0&&g.info(p,`Synced connector skills to ${e}: [${t.join(", ")}]`),e}rebuildRuntime(e){if(this.stopped||this.active)return Promise.resolve();if(this.rebuildPromise)return this.rebuildPromise;const t=(async()=>{this.emit("pauseIntake","barrier"),this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="pending",this.pushToolbarMeta();try{await this.stopRuntime(!0),await this.ensureRuntime()}catch(i){g.warn(p,`${e} rebuild failed: ${this.redactError(i)}`)}finally{this.emit("resumeIntake","barrier")}})();return this.rebuildPromise=t.finally(()=>{this.rebuildPromise=null;const i=this.resolveDesiredSettings().revision;!this.stopped&&!this.active&&(this.personaDirty||this.applied&&this.applied.appliedRevision!==i)&&this.rebuildRuntime("coalesced_state_changed")}),this.rebuildPromise}async stopRuntime(e){const t=this.runtime;t&&(this.intentionalRuntimeStop=e,this.runtime=null,await t.shutdown().catch(()=>t.terminate()),this.capture?.close(),this.capture=null,this.intentionalRuntimeStop=!1)}onRuntimeExit(e){if(!(this.intentionalRuntimeStop||this.stopped)&&!(e&&this.replaySupersededRuntimes.has(e))){if(this.runtime=null,this.capture?.close(),this.capture=null,this.applied=void 0,this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState="failed",this.settingsErrorCode="runtime_exited",this.pushToolbarMeta(),this.active){if(this.isPromptUnaccepted(this.active)){g.warn(p,`Harness runtime exited before accepting prompt ${this.active.inbound.event_id}; awaiting in-flight prompt failure`);return}this.finishActive("failed","Harness runtime exited; prompt was not replayed")}this.emit("exit",1)}}onProtocolError(e){if(this.stopped||!this.runtime&&!this.active)return;const t=this.redactError(e,this.active?.inbound.content);g.warn(p,`Harness protocol error: ${t}`),this.clearPendingApprovals("unavailable"),this.contextWindow=null,this.reportedContextCapacity=null,this.settingsState="failed",this.settingsErrorCode="protocol_error",this.pushToolbarMeta();const i=this.runtime;this.runtime=null,this.intentionalRuntimeStop=!0,i?.client?.close(e),this.active&&this.finishActive("failed",`Harness protocol error: ${t}`),i?.terminate().finally(()=>{this.intentionalRuntimeStop=!1}),this.emit("exit",1)}async executeLocalAction(e){const t=e.params??{},i=String(t.session_id??"");if(!i||i!==this.options.aibotSessionId)return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing"};if(["exec_approve","exec_reject","permission_approve","permission_reject"].includes(e.action_type)){const o=String(t.approval_command_id??t.approval_id??t.request_id??"").trim(),l=this.pendingApprovals.get(o);if(!l)return{status:"failed",errorCode:"unknown_or_expired_approval_id",errorMsg:"That DSH approval request is no longer pending"};clearTimeout(l.timer),this.pendingApprovals.delete(o);const c=e.action_type==="exec_approve"||e.action_type==="permission_approve";return l.resolve(c?"allowed-once":"rejected"),{status:"ok",result:{approval_id:o,decision:c?"allow-once":"deny"}}}if(e.action_type==="get_session_usage")return{status:"ok",result:{adapterType:"deepseek-harness",available:!0,dsh_profile:this.resolveSelectedProfile(),...this.usageStore().get(i)}};if(e.action_type==="get_rate_limits"){this.providerQuota=null,this.pushToolbarMeta();try{this.providerQuota=await this.callbacks.queryProviderQuota(!0,this.providerQuotaHint())??this.providerQuotaFallback()}catch(o){this.providerQuota={...this.providerQuotaFallback(),error:this.redactError(o)}}return this.pushToolbarMeta(),{status:"ok",result:{sampledAt:new Date().toISOString(),contextWindow:this.contextWindow,providerQuota:this.providerQuota}}}if(e.action_type==="dsh_bridge_status"||e.action_type==="dsh_install_bridge"){if(this.resolveIntegrationMode()!=="profile_bridge")return{status:"unsupported",errorCode:"capability_unavailable",errorMsg:"Bridge management requires Profile Bridge mode"};if(this.active||this.runtime)return{status:"failed",errorCode:"worker_busy",errorMsg:"Stop the active DSH session before changing its Profile plugin"};try{const o=new A({command:"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile()}),l=e.action_type==="dsh_install_bridge"?await o.install():await o.status();return this.runtimeReadiness=l.readiness,this.settingsErrorCode=l.readiness==="ready"?null:l.readiness,this.pushToolbarMeta(),{status:"ok",result:Tt(l)}}catch(o){const l=String(o?.code??"bridge_install_failed");return this.runtimeReadiness=l,this.settingsErrorCode=l,this.pushToolbarMeta(),{status:"failed",errorCode:l,errorMsg:this.redactError(o)}}}if(e.action_type==="dsh_list_plugins"||e.action_type==="dsh_refresh_plugins"||e.action_type==="dsh_enable_plugin"||e.action_type==="dsh_disable_plugin")return this.executePluginAction(e.action_type,t,i);if(e.action_type==="dsh_list_skills"||e.action_type==="dsh_enable_skill"||e.action_type==="dsh_disable_skill")return this.executeSkillAction(e.action_type,t,i);const n={dsh_list_mcp:"mcp/list",dsh_list_tools:"tools/list",dsh_list_jobs:"jobs/list",dsh_list_goals:"goals/list"}[e.action_type];if(n){if(this.resolveIntegrationMode()!=="profile_bridge")return{status:"unsupported",errorCode:"capability_unavailable",errorMsg:"DSH resources require Profile Bridge mode"};if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot query DSH resources during an active turn"};try{return await this.ensureRuntimeWithRetry(),{status:"ok",result:await this.runtime?.client?.call(n,{cwd:this.options.bindingStore.get(i)?.cwd})}}catch(o){const l=String(o?.code??"resource_query_failed");return{status:l==="capability_unavailable"?"unsupported":"failed",errorCode:l,errorMsg:this.redactError(o)}}}if(e.action_type==="set_profile"||e.action_type==="create_profile"){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek Harness Profile during an active turn"};if(!this.options.bindingStore.get(i))return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};let o;try{o=Re(String(t.profile_id??t.dsh_profile??t.profile_name??t.name??""))}catch(c){return{status:"failed",errorCode:"profile_invalid",errorMsg:this.redactError(c)}}if(this.options.bindingStore.isDshProfileLocked(i)){const c=this.resolveSelectedProfile();return e.action_type==="create_profile"||c!==o?{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}:this.finishProfileSelection(o,!1)}if(e.action_type==="create_profile")try{const c=this.options.createDshProfile?await this.options.createDshProfile(o):await ye({profileName:o,dshHome:this.options.dshHome??this.config.env?.DSH_HOME}),b=c.identity?.profileName??o;return this.persistSelectedProfile(b)?(await this.flushSelectedProfile(),this.finishProfileSelection(b,c.created)):{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}}catch(c){return{status:"failed",errorCode:String(c?.code??"profile_create_failed"),errorMsg:this.redactError(c)}}return this.listProfiles().some(c=>c.id===o)?this.persistSelectedProfile(o)?(await this.flushSelectedProfile(),this.finishProfileSelection(o,!1)):{status:"failed",errorCode:"profile_locked",errorMsg:"This conversation Profile is locked after the session is created"}:{status:"failed",errorCode:"profile_not_found",errorMsg:"Requested DSH profile is not in the local catalog"}}if(e.action_type==="set_preset"){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek Harness settings during an active turn"};if(!this.options.bindingStore.get(i)?.cwd)return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const l=String(t.agent_preset_id??t.preset_id??"").trim();if(!this.presets.some(b=>b.id===l))return{status:"failed",errorCode:"preset_not_found",errorMsg:"Requested agent preset is not in the Harness catalog"};const c=Z(this.resolveDesiredSettings().agentPreset,this.presets);return this.options.bindingStore.isDshAgentPresetLocked(i)?c===l?{status:"ok",result:this.presetActionResult(l,!0)}:{status:"failed",errorCode:"agent_preset_locked",errorMsg:"This conversation scene is locked after the session is created"}:c===l?(this.options.bindingStore.setDshAgentPreset(i,l),await this.persistGlobalToolbarDefaults({dshAgentPreset:l}),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(l,!1)}):this.options.bindingStore.setDshAgentPreset(i,l)?(await this.persistGlobalToolbarDefaults({dshAgentPreset:l}),await this.options.bindingStore.flush(),this.pushToolbarMeta(),{status:"ok",result:this.presetActionResult(l,!1)}):{status:"failed",errorCode:"agent_preset_locked",errorMsg:"This conversation scene is locked after the session is created"}}if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek Harness settings during an active turn"};if(!this.options.bindingStore.get(i)?.cwd)return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const d=this.resolveDesiredSettings();let a;if(e.action_type==="set_provider"){const o=String(t.provider_id??"").trim();if(!this.providers.some(l=>l.id===o))return{status:"failed",errorCode:"provider_not_found",errorMsg:"Requested provider is not in the Harness catalog"};a={providerId:o},o!==d.providerId&&(this.models=ot(this.options.dataRoot,o),this.catalogProviderId=o,this.models.some(l=>l.id===d.modelId)||(a.modelId=this.models[0]?.id))}else if(e.action_type==="set_model"){const o=String(t.model_id??"").trim();if(!this.models.some(l=>l.id===o))return{status:"failed",errorCode:"model_not_found",errorMsg:"Requested model is not in the Harness catalog"};a={modelId:o}}else if(e.action_type==="set_thinking"){const o=q(t.thinking_mode??t.thinking);if(!o)return{status:"failed",errorCode:"thinking_invalid",errorMsg:"thinking_mode must be enabled or disabled"};a={thinking:o}}else if(e.action_type==="set_reasoning_effort"){const o=B(t.reasoning_effort??t.reasoningEffort);if(!o)return{status:"failed",errorCode:"reasoning_effort_invalid",errorMsg:"reasoning_effort must be high or max"};a={reasoningEffort:o}}else{const o=String(t.mode_id??"").trim();if(o!=="approval"&&o!=="full_auto")return{status:"failed",errorCode:"mode_invalid",errorMsg:"mode_id must be approval or full_auto"};a={modeId:o}}if((a.providerId===void 0||a.providerId===d.providerId)&&(a.modelId===void 0||a.modelId===d.modelId)&&(a.modeId===void 0||a.modeId===d.modeId)&&(a.thinking===void 0||a.thinking===d.thinking)&&(a.reasoningEffort===void 0||a.reasoningEffort===d.reasoningEffort)&&this.applied?.appliedRevision===d.revision)return{status:"ok",result:this.settingsActionResult(e.action_type,a,d.revision,"already_applied",!0)};const u=this.options.bindingStore.updateDshSettings(i,a)??d.revision;if(await this.options.bindingStore.flush(),(a.providerId||a.modelId||a.modeId||a.thinking||a.reasoningEffort)&&await this.persistGlobalToolbarDefaults({...a.providerId?{dshProviderId:a.providerId}:{},...a.modelId?{dshModelId:a.modelId}:{},...a.modeId?{dshModeId:a.modeId}:{},...a.thinking?{dshThinking:a.thinking}:{},...a.reasoningEffort?{dshReasoningEffort:a.reasoningEffort}:{}}),this.contextWindow=null,this.reportedContextCapacity=null,this.settingsErrorCode=null,this.runtimeStartPromise&&await this.runtimeStartPromise.catch(()=>{}),!this.runtime)return this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,a,u,"applied",!1)};if(this.active)return this.applied&&this.applied.appliedRevision>=u?(this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,a,u,"applied",!0)}):(this.settingsState="pending",this.pushToolbarMeta(),{status:"ok",result:this.settingsActionResult(e.action_type,a,u,"pending",!0)});this.settingsState="pending",this.pushToolbarMeta();try{if(await this.rebuildRuntime("settings_changed"),!this.applied||this.applied.appliedRevision<u)throw new Error("new runtime did not apply requested revision");return this.refreshProviderQuota(!0),{status:"ok",result:this.settingsActionResult(e.action_type,a,u,"applied",!0)}}catch(o){return{status:"failed",result:this.settingsActionResult(e.action_type,a,u,"failed",!1,this.redactError(o)),errorCode:"settings_apply_failed",errorMsg:this.redactError(o)}}}async finishProfileSelection(e,t){if(this.resolveIntegrationMode()==="profile_bridge")try{await this.prepareSelectedProfile()}catch(i){const s=String(i?.code??"profile_start_failed");return this.runtimeReadiness=s,this.settingsErrorCode=s,this.pushToolbarMeta(),{status:"failed",errorCode:s,errorMsg:this.redactError(i)}}return this.pushToolbarMeta(),{status:"ok",result:this.profileActionResult(e,t)}}createBridgeInstaller(){const e=this.options.bridgeInstallerOptions??{};return new A({command:e.command??"dsh",dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile(),...e.tarballPath?{tarballPath:e.tarballPath}:{}})}async healBridgeUpdate(e){return e.readiness!=="bridge_update_required"||this.options.autoInstallBridge===!1?e:(g.info(p,`auto-updating stale Bridge profile=${e.identity.profileName} installed=${e.installedBridgeVersion??"none"} bundled=${e.bundledBridgeVersion}`),await this.prepareSelectedProfile(),this.attachSelectedProfile())}async ensureProfileReadyForChat(){if(!(this.options.autoInstallBridge!==!1||this.options.autoStartProfile!==!1)){const s=await this.attachSelectedProfile(),n=H(s);if(n)throw n;return}this.settingsState="pending",this.pushToolbarMeta(),await this.prepareSelectedProfile();let t=await this.attachSelectedProfile();t.readiness==="bridge_update_required"&&(t=await this.healBridgeUpdate(t));const i=H(t);if(i)throw i}async attachSelectedProfile(){const t=await this.createBridgeInstaller().status();return this.runtimeReadiness=t.readiness,this.profileDshVersion=t.runningDshVersion??t.dshVersion??null,this.settingsErrorCode=t.readiness==="ready"?null:t.readiness,t}async prepareSelectedProfile(){const e=this.createBridgeInstaller(),t=await Ne({installer:e,autoInstall:this.options.autoInstallBridge!==!1,autoStart:this.options.autoStartProfile!==!1});this.runtimeReadiness=t.readiness,this.profileDshVersion=t.runningDshVersion??t.dshVersion??null,this.settingsErrorCode=t.readiness==="ready"?null:t.readiness}profileActionResult(e,t){return{outcome:t?"profile_created":"profile_set",profile_id:e,dsh_profile:e,created:t,dsh_profile_locked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),dsh_profile_create:!this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),available_profiles:this.listProfiles(),session_context:{dsh_profile:e,dsh_profile_locked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),dsh_profile_create:!this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId)}}}persistSelectedProfile(e){return this.options.bindingStore.setDshSelectedProfile(this.options.aibotSessionId,e)?(this.options.globalConfigStore?.set(this.options.agentName,{dshProfile:e}),!0):!1}async persistGlobalToolbarDefaults(e){this.options.globalConfigStore&&Object.values(e).some(t=>t!==void 0)&&(this.options.globalConfigStore.set(this.options.agentName,e),await this.options.globalConfigStore.flush())}seedSessionToolbarFromGlobal(){const e=this.options.aibotSessionId,t=this.options.bindingStore.get(e);if(!t?.cwd)return;const i=this.resolveDesiredSettings(),s={};t.dshProviderId||(s.providerId=i.providerId),t.dshModelId||(s.modelId=i.modelId),t.dshModeId||(s.modeId=i.modeId),t.dshThinking||(s.thinking=i.thinking),t.dshReasoningEffort||(s.reasoningEffort=i.reasoningEffort),Object.keys(s).length>0&&this.options.bindingStore.updateDshSettings(e,s),!this.options.bindingStore.getDshAgentPreset(e)&&i.agentPreset&&this.options.bindingStore.setDshAgentPreset(e,i.agentPreset),this.options.bindingStore.getDshSelectedProfile(e)||this.options.bindingStore.setDshSelectedProfile(e,this.resolveSelectedProfile())}async flushSelectedProfile(){await this.options.bindingStore.flush(),await this.options.globalConfigStore?.flush()}listProfiles(){return Ae({dshHome:this.options.dshHome??this.config.env?.DSH_HOME})}pluginCommandContext(){return{dshHome:this.options.dshHome??this.config.env?.DSH_HOME,profileName:this.resolveSelectedProfile(),enabledPluginIds:this.options.bindingStore.getDshEnabledPlugins(this.options.aibotSessionId)}}skillCommandContext(){return{skillsDir:this.projectConnectorSkills(),enabledSkillIds:this.options.bindingStore.getDshEnabledSkills(this.options.aibotSessionId)}}currentPlugins(){try{return R(this.pluginCommandContext())}catch{return[]}}currentSkills(){return this.sessionSkillControlUnavailable()?[]:M(this.skillCommandContext())}pluginRestartRequired(){return!1}async executePluginAction(e,t,i){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek plugins during an active turn"};if(!this.options.bindingStore.get(i))return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};const s=this.pluginCommandContext();try{if(e==="dsh_list_plugins"||e==="dsh_refresh_plugins"){const o=R(s);return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(o,!1)}}const n=String(t.name??t.plugin_name??"").trim(),r=this.options.bindingStore.getDshEnabledPlugins(i);let d=n;try{const{plugin:o}=Pe({...s,name:n});d=o.name}catch(o){const l=String(o?.code??"");if(e!=="dsh_disable_plugin"||l!=="plugin_not_found"||!r.includes(n))throw o}const a=Ee(r,d,e==="dsh_enable_plugin"),f=this.options.bindingStore.setDshEnabledPlugins(i,a.pluginIds)??this.resolveDesiredSettings().revision;await this.options.bindingStore.flush();const u=R({...s,enabledPluginIds:a.pluginIds});if(!a.changed)return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(u,!1,"skipped")};if(this.runtimeStartPromise&&await this.runtimeStartPromise.catch(()=>{}),!this.runtime)return this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(u,!0,"skipped")};if(this.active)return this.settingsState="pending",this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(u,!0,"pending")};if(this.settingsState="pending",this.pushToolbarMeta(),await this.rebuildRuntime("plugin_changed"),!this.applied||this.applied.appliedRevision<f)throw new Error("new runtime did not apply requested plugin revision");return this.pushToolbarMeta(),{status:"ok",result:this.pluginActionResult(u,!0,"restarted")}}catch(n){return{status:"failed",errorCode:String(n?.code??"plugin_action_failed"),errorMsg:this.redactError(n)}}}async executeSkillAction(e,t,i){if(this.active)return{status:"failed",errorCode:"worker_busy",errorMsg:"Cannot change DeepSeek skills during an active turn"};if(!this.options.bindingStore.get(i))return{status:"failed",errorCode:"binding_missing",errorMsg:"Session binding missing. Open a workspace first."};if(this.sessionSkillControlUnavailable())return this.pushToolbarMeta(),{status:"unsupported",errorCode:"capability_unavailable",errorMsg:`DSH session skills require @deepseek-ai/dsh ${ae} or newer`};const s=this.skillCommandContext();try{if(e==="dsh_list_skills"){const o=M(s);return this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(o,!1)}}const n=String(t.name??t.skill_name??"").trim(),r=this.options.bindingStore.getDshEnabledSkills(i);let d=n;try{d=Ce({...s,name:n}).name}catch(o){const l=String(o?.code??"");if(e!=="dsh_disable_skill"||l!=="skill_not_found"||!r.includes(n))throw o}const a=xe(r,d,e==="dsh_enable_skill"),f=this.options.bindingStore.setDshEnabledSkills(i,a.skillIds)??this.resolveDesiredSettings().revision;await this.options.bindingStore.flush();const u=M({...s,enabledSkillIds:a.skillIds});if(!a.changed)return this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(u,!1,"skipped")};if(this.runtimeStartPromise&&await this.runtimeStartPromise.catch(()=>{}),!this.runtime)return this.settingsState="applied",this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(u,!0,"skipped")};if(this.active)return this.settingsState="pending",this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(u,!0,"pending")};if(this.settingsState="pending",this.pushToolbarMeta(),await this.rebuildRuntime("skill_changed"),!this.applied||this.applied.appliedRevision<f)throw new Error("new runtime did not apply requested skill revision");return this.pushToolbarMeta(),{status:"ok",result:this.skillActionResult(u,!0,"restarted")}}catch(n){return{status:"failed",errorCode:String(n?.code??"skill_action_failed"),errorMsg:this.redactError(n)}}}pluginActionResult(e,t,i="skipped"){const s=this.resolveSelectedProfile(),n=this.pluginRestartRequired();return{outcome:t?i==="restarted"?"plugin_applied":"plugin_updated":"plugin_unchanged",dsh_profile:s,dsh_plugins:e,dsh_plugin_restart_required:n,restart:i,session_context:{dsh_profile:s,dsh_plugins:e,dsh_plugin_restart_required:n}}}skillActionResult(e,t,i="skipped"){return{outcome:t?i==="restarted"?"skill_applied":"skill_updated":"skill_unchanged",dsh_skills:e,restart:i,session_context:{dsh_skills:e}}}resolveSelectedProfile(){const e=this.options.bindingStore.getDshSelectedProfile(this.options.aibotSessionId),t=Be({binding:e,global:this.options.globalConfigStore?.get(this.options.agentName)?.dshProfile,adapter:this.options.dshProfile});return this.options.bindingStore.get(this.options.aibotSessionId)&&e!==t&&this.options.bindingStore.setDshSelectedProfile(this.options.aibotSessionId,t),t}profileDataDir(e=this.resolveSelectedProfile()){return He(this.options.dataRoot,e)}usageStore(){const e=this.resolveSelectedProfile(),t=T(this.profileDataDir(e),"session-usage.json"),i=T(this.options.dataRoot,"session-usage.json");return!W(t)&&W(i)&&(pe(ge(t),{recursive:!0,mode:448}),ue(i,t)),lt(t)}presetActionResult(e,t){const i=this.resolveDesiredSettings();return{outcome:"preset_set",agentPreset:e,agent_preset_id:e,agent_preset_locked:t,available_presets:[...this.presets],session_context:{agent_preset_id:i.agentPreset??e,agent_preset_locked:t}}}settingsActionResult(e,t,i,s,n,r){const d=this.resolveDesiredSettings(),a=d.revision||i,f={provider_id:d.providerId,model_id:d.modelId,mode_id:d.modeId,thinking_mode:d.thinking,reasoning_effort:d.reasoningEffort,applied_provider_id:this.applied?.providerId??null,applied_model_id:this.applied?.modelId??null,applied_mode_id:this.applied?.modeId??null,applied_thinking_mode:this.applied?.thinking??null,applied_reasoning_effort:this.applied?.reasoningEffort??null,applied_settings_revision:this.applied?.appliedRevision??null,settings_state:this.settingsState,settings_revision:a};return e==="set_mode"&&(f.sandbox_mode=Y(d.modeId),f.approval_policy=d.modeId==="full_auto"?"never":"ask"),{outcome:`${e==="set_provider"?"provider":e==="set_model"?"model":e==="set_thinking"?"thinking":e==="set_reasoning_effort"?"reasoning_effort":"mode"}_set${s==="pending"||s==="failed"?"_pending":""}`,...t.providerId?{providerId:t.providerId,provider_id:t.providerId}:{},...t.modelId?{modelId:t.modelId,model_id:t.modelId}:{},...t.modeId?{modeId:t.modeId,mode_id:t.modeId,sandbox_mode:Y(t.modeId),approval_policy:t.modeId==="full_auto"?"never":"ask"}:{},...t.thinking?{thinking:t.thinking,thinking_mode:t.thinking}:{},...t.reasoningEffort?{reasoningEffort:t.reasoningEffort,reasoning_effort:t.reasoningEffort}:{},settingsRevision:a,settings_revision:a,sessionAlive:n,available_providers:[...this.providers],available_models:[...this.models],session_context:f,...r?{error:r}:{}}}hydrateCatalogFromCache(){const e=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),t=this.options.globalConfigStore?.get(this.options.agentName),i=rt({dataRoot:this.options.dataRoot,providerId:e?.providerId??t?.dshProviderId});this.providers=i.providers,this.models=this.options.models?.length?this.options.models:i.models,this.catalogProviderId=i.providerId}async persistCatalogCache(e){try{await at({dataRoot:this.options.dataRoot,providers:this.providers,providerId:e,models:this.models})}catch(t){g.warn(p,`failed to persist DSH catalog cache: ${t instanceof Error?t.message:String(t)}`)}}async writeGrixProviderFile(){const e=$e(this.options.dshHome??this.config.env?.DSH_HOME),t=await this.resolveCredentialsLayout(e);try{if(ie(this.options.provider)){await ft(e,v,this.options.provider??{},t)==="skipped"&&g.warn(p,`Grix provider not written to DSH settings (user-owned "${v}" route or unreadable YAML); relay will not take effect`);return}await gt(e,v)}catch(i){g.warn(p,`Failed to sync Grix provider into DSH settings: ${this.redactError(i)}`)}}async resolveCredentialsLayout(e){let t=this.profileDshVersion;if(!t)try{t=await qe(this.options.bridgeInstallerOptions?.command??"dsh",e)}catch(s){g.warn(p,`could not read dsh version, assuming the current credentials layout: ${this.redactError(s)}`)}const i=pt(t);return kt(t)&&g.warn(p,`dsh ${t} predates ${de}: it drops the supportsDeveloperRole / maxTokensField switches, so relayed requests keep the OpenAI-style wire format and the gateway rejects them. Upgrade dsh to use the Grix relay.`),i}syncGrixProvider(){if(ie(this.options.provider)){this.providers.some(s=>s.id===v)||(this.providers=[{id:v,displayName:"Grix"},...this.providers]);const e=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),t=this.options.globalConfigStore?.get(this.options.agentName),i=e?.providerId??t?.dshProviderId;(!i||i===$||i===v)&&this.options.bindingStore.updateDshSettings(this.options.aibotSessionId,{providerId:v});return}this.providers=this.providers.filter(e=>e.id!==v)}resolveDesiredSettings(){const e=this.options.bindingStore.get(this.options.aibotSessionId),t=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),i=this.options.globalConfigStore?.get(this.options.agentName),s=t?.providerId??i?.dshProviderId,n=this.providers.some(f=>f.id===v)?v:void 0,r=st(s||n,this.providers),d=[t?.modelId,i?.dshModelId,this.options.defaultModel,this.models[0]?.id].find(f=>!!f&&this.models.some(u=>u.id===f))??"deepseek-chat",a=Z(t?.agentPreset??i?.dshAgentPreset,this.presets);return{providerId:r,modelId:d,modeId:it(e?.dshModeId,i?.dshModeId),thinking:q(t?.thinking)??q(i?.dshThinking)??Ze,reasoningEffort:B(t?.reasoningEffort)??B(i?.dshReasoningEffort)??Ye,agentPreset:a,pluginIds:this.options.bindingStore.getDshEnabledPlugins(this.options.aibotSessionId),skillIds:this.options.bindingStore.getDshEnabledSkills(this.options.aibotSessionId),skillIdsExplicit:Array.isArray(e?.dshSkillIds),maxTokens:t?.maxTokens??this.options.maxTokens??Ke,revision:t?.revision??0}}resolveIntegrationMode(){return this.options.integrationMode?this.options.integrationMode:(this.config.command||"").includes("dsh-jsonrpc-agent")?"embedded_jsonrpc":"profile_bridge"}sessionSkillControlUnavailable(){return this.resolveIntegrationMode()!=="profile_bridge"?!1:this.bridgeCapabilities&&typeof this.bridgeCapabilities=="object"?this.bridgeCapabilities.sessionSkillAllowlist!==!0:It(this.profileDshVersion)}pushToolbarMeta(){const e=this.options.bindingStore.get(this.options.aibotSessionId);this.callbacks.sendUpdateBindingCard(this.options.aibotSessionId,this.stopped?"stopped":this.active?"busy":"ready",e?.cwd,ze({desired:this.resolveDesiredSettings(),applied:this.applied,models:this.models,providers:this.providers,presets:this.presets,agentPresetLocked:this.options.bindingStore.isDshAgentPresetLocked(this.options.aibotSessionId),state:this.settingsState,errorCode:this.settingsErrorCode,contextWindow:this.contextWindow,providerQuota:this.providerQuota,integrationMode:this.resolveIntegrationMode(),profileName:this.resolveSelectedProfile(),profiles:this.listProfiles(),profileLocked:this.options.bindingStore.isDshProfileLocked(this.options.aibotSessionId),plugins:this.currentPlugins(),skills:this.currentSkills(),pluginRestartRequired:this.pluginRestartRequired(),runtimeReadiness:this.runtimeReadiness,bridgeCapabilities:this.bridgeCapabilities}))}providerQuotaHint(){const e=this.resolveDesiredSettings(),t=this.options.bindingStore.getDshSettings(this.options.aibotSessionId),i=this.options.globalConfigStore?.get(this.options.agentName);return{providerId:t?.providerId??i?.dshProviderId??e.providerId,model:e.modelId}}providerQuotaFallback(){const e=this.providerQuotaHint().providerId;return e==="opencode-go"||e==="opencode_go"?{provider:"opencode_go",providerLabel:"OpenCode Go",success:!1,error:"unavailable"}:{provider:"deepseek",providerLabel:"DeepSeek",success:!1,error:"unavailable"}}async refreshProviderQuota(e){this.providerQuota=null,this.pushToolbarMeta();try{this.providerQuota=await this.callbacks.queryProviderQuota(e,this.providerQuotaHint())??this.providerQuotaFallback()}catch{this.providerQuota=this.providerQuotaFallback()}this.pushToolbarMeta()}clearPendingApprovals(e){for(const t of this.pendingApprovals.values())clearTimeout(t.timer),t.resolve(e);this.pendingApprovals.clear()}thinkingEnabled(){const e=this.active?.inbound.connector_runtime_config?.thinking_events??this.active?.inbound.connector_runtime_config?.thinkingEvents;return e!=="off"&&e!=="hidden"&&e!=="none"}toolEventsEnabled(){const e=this.active?.inbound.connector_runtime_config?.tool_events;return e!=="off"&&e!=="hidden"&&e!=="none"}sendRaw(e,t,i){this.active&&this.callbacks.sendRawEventEnvelope(this.active.inbound.event_id,this.active.inbound.session_id,{type:e,payload:t},i)}failEvent(e,t){this.callbacks.sendEventResult(e.event_id,"failed",t),this.emit("eventDone",e.event_id)}startTimeout(e){this.activeTimeoutMs=e??this.options.promptTimeoutMs??se,this.noteRuntimeActivity(),this.armTimeout(this.activeIdleTimeoutMs()),this.armHardTimeout(this.activeTimeoutMs)}touchActivity(e=1){!this.active||!this.timeoutTimer||(this.noteRuntimeActivity(),this.armTimeout(this.activeIdleTimeoutMs()))}noteRuntimeActivity(){this.active&&(this.active.lastRuntimeActivityAt=Date.now(),this.active.livenessExtendStartAt=void 0)}activeIdleTimeoutMs(){const e=this.options.activeIdleTimeoutMs??ne,t=Number.isFinite(e)&&e>0?e:ne;return Math.min(t,this.activeTimeoutMs)}livenessFreshMs(){const e=this.options.livenessFreshMs??oe;return Number.isFinite(e)&&e>0?e:oe}livenessMaxExtendMs(){const e=this.options.livenessMaxExtendMs??re;return Number.isFinite(e)&&e>0?e:re}armTimeout(e){this.clearIdleTimeout(),this.timeoutTimer=setTimeout(()=>{this.handlePromptTimeout()},e),this.timeoutTimer.unref?.()}armHardTimeout(e){this.clearHardTimeout(),this.hardTimeoutTimer=setTimeout(()=>{this.handlePromptHardTimeout()},e),this.hardTimeoutTimer.unref?.()}async handlePromptTimeout(){const e=this.active;if(e){if(this.pendingApprovals.size>0){g.info(p,`Idle timeout skipped: pendingApprovals=${this.pendingApprovals.size} event=${e.inbound.event_id}`),this.armTimeout(this.activeIdleTimeoutMs());return}if(this.shouldExtendByLiveness(e.inbound.event_id)){this.armTimeout(this.activeIdleTimeoutMs());return}await this.failActiveTimeout("idle","Harness prompt idle timeout and the runtime was terminated")}}async handlePromptHardTimeout(){const e=this.active;if(e&&this.shouldExtendByLiveness(e.inbound.event_id)){this.armHardTimeout(this.activeTimeoutMs);return}await this.failActiveTimeout("hard","Harness prompt exceeded max duration and the runtime was terminated")}shouldExtendByLiveness(e){const t=this.active;if(!t||t.inbound.event_id!==e||!this.runtime?.isConnected()||!(!t.turnEnded&&(!!t.messageId||t.admitted||t.claimed)))return!1;const s=Date.now(),n=t.lastRuntimeActivityAt??t.startedAt,r=Math.max(0,s-n);if(r<this.livenessFreshMs())return t.livenessExtendStartAt=s,g.info(p,`Liveness check: recent DSH activity for ${e} (quietMs=${r}), extending`),!0;const d=t.livenessExtendStartAt??n;t.livenessExtendStartAt=d;const a=s-d;return a>this.livenessMaxExtendMs()?(g.warn(p,`Liveness extension budget exhausted for ${e} (quietMs=${r}, extendMs=${a}), allowing close`),!1):(g.info(p,`Liveness check: DSH turn still open for ${e} (claimed=${t.claimed}, turnEnded=${t.turnEnded}, quietMs=${r}), extending`),!0)}async failActiveTimeout(e,t){if(!this.active)return;const i=this.active;this.clearTimeout();const s=this.runtime;this.runtime=null,this.intentionalRuntimeStop=!0,this.contextWindow=null,this.reportedContextCapacity=null,this.applied=void 0,this.settingsState="applied",this.settingsErrorCode=null,this.pushToolbarMeta(),await s?.cancel(this.runtimeSessionId).catch(()=>{}),s&&await s.shutdown().catch(()=>s.terminate()),this.intentionalRuntimeStop=!1,!(this.active!==i||this.stopped)&&(g.error(p,`Active DSH turn ${e} timeout: ${i.inbound.event_id}`),this.finishActive("failed",t),this.emit("exit",1))}clearTimeout(){this.clearIdleTimeout(),this.clearHardTimeout()}clearIdleTimeout(){this.timeoutTimer&&clearTimeout(this.timeoutTimer),this.timeoutTimer=null}clearHardTimeout(){this.hardTimeoutTimer&&clearTimeout(this.hardTimeoutTimer),this.hardTimeoutTimer=null}redactError(e,t){let i=e instanceof Error?e.message:String(e);const s=this.config.env?.DEEPSEEK_API_KEY;return s&&(i=i.split(s).join("[REDACTED]")),i=i.replace(/(api[_-]?key|authorization|bearer)\s*[:=]\s*\S+/gi,"$1=[REDACTED]"),t&&t.length>=16&&i.includes(t)&&(i="Harness request failed (prompt echo redacted)"),(i.includes("[aibot-system-prompt]")||i.includes("[base-behavior]"))&&(i="Harness runtime failed (system prompt echo redacted)"),i.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g,"").slice(0,2e3)}}function vt(h){const e=Number(h&&typeof h=="object"?h.cursor:0);return Number.isSafeInteger(e)&&e>0?e:0}function bt(h){return new Promise(e=>setTimeout(e,h))}function _t(h,e){return`grix-${x("sha256").update(h).digest("hex").slice(0,12)}-${e}-${D().slice(0,8)}`}function St(h){return`grix-${x("sha256").update(h).digest("hex").slice(0,16)}-${D().slice(0,8)}`}function le(){return{inputTokens:0,outputTokens:0,cacheReadInputTokens:0,cacheCreationInputTokens:0,reasoningTokens:0}}function kt(h){const e=X(h,de);return e!==null&&e<0}function It(h){const e=X(h,ae);return e!==null&&e<0}function he(h){const e=h.data?.chunk&&typeof h.data.chunk=="object"?h.data.chunk:h.data;return String(e?.type??"")}function wt(h){return h.type==="assistant/chunk:tool-call-delta"||h.type==="assistant/chunk"&&he(h)==="tool-call-delta"}function Tt(h){return{readiness:h.readiness,profile:h.identity.profileName,dshVersion:h.dshVersion,runningDshVersion:h.runningDshVersion,installedBridgeVersion:h.installedBridgeVersion,bundledBridgeVersion:h.bundledBridgeVersion,runningBridgeVersion:h.runningBridgeVersion,endpointCount:h.endpointCount,requiresProfileRestart:h.readiness==="profile_restart_required"}}const yt=new Set(["turn/start","step/start","step/end","agent/inbox/spliced","user/message","request/header","system/message","assistant/attempt","session-log-deepseek/delivery-accepted","job/registered","job/settled","developer/message","session/title","session/title-llm-request","session/end-seed","web/deepseek-search-llm-request","assistant/chunk:tool-call-delta","permission/preset","sandbox/mode","approval/policy","approval/asked","approval/decided","plan/mode","agent-preset/selected","llm/retry","llm/retry-started","goal/change","schedule/change","feedback/record","hook/invoked","hook/result","command/run","command/done","subagent/descriptor","tool-workflow/agent-start","tool-workflow/agent-end","tool-workflow/run-start","tool-workflow/run-end","tool/code-dispatch","tool/code-dispatch-start"]);function Pt(h){const e=he(h);return yt.has(h.type)||h.type==="assistant/chunk"&&["block-start","block-end","tool-call-delta","finish"].includes(e)}export{li as DshJsonRpcAdapter};
@@ -1,7 +1,8 @@
1
- import{execFile as T}from"node:child_process";import{promisify as M}from"node:util";import{EventEmitter as y}from"node:events";import{stat as k}from"node:fs/promises";import{mkdirSync as C,writeFileSync as R,unlinkSync as B,statSync as f,readFileSync as D,existsSync as g}from"node:fs";import{join as u,resolve as F,delimiter as E}from"node:path";import{fileURLToPath as O}from"node:url";import{tmpdir as N,homedir as w}from"node:os";import{resolveCommandPath as G,resolveWindowsExecInvocation as L,spawnCommand as j,killProcessGroup as b,hasChildProcesses as z}from"../../core/runtime/spawn.js";import{InternalApiServer as q}from"../../core/mcp/internal-api-server.js";import{IdentityInjector as J}from"../shared/identity-injector.js";import{compactToolInputForWire as K}from"../shared/tool-wire-payload.js";import{syncDefaultSkillsToDir as U}from"../../default-skills/index.js";import{PiTransport as H}from"./pi-transport.js";import{log as o}from"../../core/log/index.js";import{scanSkills as V}from"../claude/skill-scanner.js";import{listLivingDescendants as Y,countLivingDescendantsOutsideBaseline as W}from"../cursor/living-descendants.js";import{SessionBindingStore as X}from"../../core/persistence/session-binding-store.js";import{AgentGlobalConfigStore as Q}from"../../core/persistence/agent-global-config-store.js";import{splitTextForAibotProtocol as Z}from"../../core/protocol/index.js";import{InboundMessageIdInjector as tt}from"../shared/inbound-message-id-injector.js";import{buildSimpleProbeReport as et}from"../shared/probe-util.js";import{piGrixProviderId as it,removePiGrixProvider as st,writePiGrixProvider as nt}from"./pi-provider-config.js";import{agentIdOf as rt}from"../shared/native-provider-config.js";import{writeOmpMcpEntry as ot,recordOmpMcpEntryPid as at,removeOmpMcpEntry as dt}from"./omp-mcp-config.js";function ct(l){return rt(l)==="omp"}function lt(l){return process.platform!=="win32"?"PATH":Object.keys(l).find(t=>t.toLowerCase()==="path")??"PATH"}function ht(l){const t=lt(l),e=String(l[t]??""),i=process.platform==="win32"?"bun.exe":"bun";if(e.split(E).some(r=>r.trim()&&g(u(r.trim(),i))))return l;const n=u(w(),".bun","bin");return g(u(n,i))?(o.info("pi-adapter",`bun \u4E0D\u5728\u5F53\u524D PATH\uFF0C\u8865\u4E0A\u9ED8\u8BA4\u5B89\u88C5\u76EE\u5F55: ${n}`),{...l,[t]:e?`${n}${E}${e}`:n}):l}const _=new Map;function pt(l){const t=u(l,"mcp.json");try{if(!g(t))return{};const i=JSON.parse(D(t,"utf8"))?.mcpServers;return!i||typeof i!="object"||Array.isArray(i)?{}:i}catch(e){return o.warn("pi-adapter",`Failed to read Pi user MCP config ${t}: ${e instanceof Error?e.message:String(e)}`),{}}}async function ut(l){const t=_.get(l);if(t!==void 0)return t;let e=!1;try{const i=M(T),s=L(l,["--help"]),{stdout:n,stderr:r}=await i(s.command,s.args,{timeout:5e3,encoding:"utf-8",windowsVerbatimArguments:s.windowsVerbatimArguments});e=/--mcp-config\b/.test(`${n??""}${r??""}`)}catch{e=!1}return _.set(l,e),o.info("pi-adapter",`Pi --mcp-config \u652F\u6301\u63A2\u6D4B: ${e?"\u652F\u6301":"\u4E0D\u652F\u6301"} (${l})`),e}class mt extends y{adapterSessionId;constructor(t){super(),this.adapterSessionId=t}emitDone(t){this.emit("done",t)}emitError(t){if(this.listenerCount("error")===0){o.warn("pi-adapter",`Prompt handle error (no listeners): ${t.message}`);return}this.emit("error",t)}async cancel(){}}const ft=12e4,P=90*1e3,x=1800*1e3;function $(l){try{return process.kill(l,0),!0}catch(t){return t.code==="EPERM"}}const gt=500,vt=2e3,v=3,St=500;function It(l){return new Promise(t=>setTimeout(t,l))}function yt(l){const t=new Set,e=[];for(const i of l){const s=i.provider?.trim();!s||t.has(s)||(t.add(s),e.push({id:s,display_name:s}))}return e}function m(l){if(l===void 0)return"undefined";if(l===null)return"null";if(typeof l=="string")return l.length>500?`${l.slice(0,500)}...`:l;try{const t=JSON.stringify(l);return t.length>500?`${t.slice(0,500)}...`:t}catch{return String(l)}}class A extends y{type="pi";config;callbacks;process=null;transport=new H;alive=!1;stopped=!1;internalApi=null;mcpConfigPath=null;cwdMcpJsonDir=null;cwdMcpJsonKey=null;identity;inboundMessageIds=new tt;piSessionPath=null;activeEventId=null;activeSessionId=null;activeAuditCapture=null;completedAuditBoundaries=new Map;isStreaming=!1;abortBarrier=null;promptGeneration=0;streamSeq=0;clientMsgSeq=0;activeClientMsgId=null;thinkingSeq=0;textBuffer="";emittedTextByIndex=new Map;textFlushTimer=null;activeRunError=null;runErrorEmitted=!1;idleTimer=null;lastRpcAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;descendantBaseline;composingSessionId=null;composingInterval=null;doneGuardTimer=null;bindingStore=null;globalConfigStore=null;modelSelectionRevision=0;initializationPromise=null;aibotSessionId="";sessionReadyPromise=null;provider;agentName="";clientType="";constructor(t,e){super(),this.config=t,this.callbacks=e,this.identity=new J("pi-adapter",e.getAgentProfile);const i=t.options??{};this.aibotSessionId=String(i.aibotSessionId??"").trim(),this.agentName=String(i.agentName??"").trim(),this.clientType=String(i.clientType??"").trim().toLowerCase(),this.provider=i.provider,this.bindingStore=i.bindingStore instanceof X?i.bindingStore:null,this.globalConfigStore=i.globalConfigStore instanceof Q?i.globalConfigStore:null,this.bindingStore&&this.aibotSessionId&&(this.piSessionPath=this.bindingStore.getPiSessionPath(this.aibotSessionId)??null)}isOmp(t){return this.clientType?this.clientType==="omp":ct(t)}resolvePiConfigDir(){return String(this.config.env?.PI_CODING_AGENT_DIR??"").trim()||u(w(),".pi","agent")}start(){return this.initializationPromise=this.initializeSession(),this.initializationPromise}async initializeSession(){const t=this.resolveInitialModel();if(await this.startInternalApi(),await this.spawnPi(),await this.ensureSessionReady(),t)try{await this.setModelSelection(t.provider,t.modelId,!1)}catch(e){o.warn("pi-adapter",`Failed to restore model selection: ${e instanceof Error?e.message:String(e)}`)}o.info("pi-adapter",`Ready (pid=${this.process?.pid})`),await this.syncModelBinding()}async syncModelBinding(){if(!this.aibotSessionId)return;const t=this.modelSelectionRevision;for(let e=1;e<=v;e++)try{const[i,s]=await Promise.all([this.transport.send("get_available_models"),this.transport.send("get_state")]);if(t!==this.modelSelectionRevision)return;const n=i.data?.models;if(!n||n.length===0){if(e<v){await It(St);continue}o.warn("pi-adapter",`syncModelBinding: empty model list after ${v} attempts, giving up`);return}const r=s.data?.model,a=this.bindingStore?.get(this.aibotSessionId);s.success&&r?.provider&&r.id&&!(a?.piProviderId&&a.piModelId)&&this.bindingStore?.setPiModel(this.aibotSessionId,r.provider,r.id);const d={available_models:n.map(h=>({id:h.id,display_name:h.name??h.id,...h.provider?{provider:h.provider}:{}}))},p=yt(n);p.length>0&&(d.available_providers=p),r?.id&&(d.model_id=r.id),r?.provider&&(d.provider_id=r.provider,d.model_provider=r.provider),this.callbacks.sendUpdateBindingCard(this.aibotSessionId,this.isStreaming?"composing":"ready",this.resolveCwd(),d),o.info("pi-adapter",`synced model binding: ${n.length} models, current=${r?.id??"unknown"} (attempt ${e})`);return}catch(i){o.warn("pi-adapter",`syncModelBinding failed (non-fatal): ${i instanceof Error?i.message:String(i)}`);return}}resolveInitialModel(){const t=this.bindingStore?.get(this.aibotSessionId);if(t?.piProviderId&&t.piModelId)return{provider:t.piProviderId,modelId:t.piModelId};if(this.piSessionPath)return;const e=this.globalConfigStore?.get(this.agentName);if(e?.piProviderId&&e.piModelId)return{provider:e.piProviderId,modelId:e.piModelId}}async setModelSelection(t,e,i){const s=await this.transport.send("set_model",{provider:t,modelId:e});if(!s.success)throw new Error(s.error||"set_model failed");this.modelSelectionRevision++,this.aibotSessionId&&this.bindingStore?.setPiModel(this.aibotSessionId,t,e),i&&this.agentName&&this.globalConfigStore?.set(this.agentName,{piProviderId:t,piModelId:e})}async currentModel(){try{return(await this.transport.send("get_state")).data?.model??null}catch{return null}}async stop(){if(this.stopped=!0,this.promptGeneration++,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.cancelDoneGuard(),this.transport.close(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.mcpConfigPath){try{B(this.mcpConfigPath)}catch{}this.mcpConfigPath=null}if(this.cwdMcpJsonDir&&this.cwdMcpJsonKey){const t=this.cwdMcpJsonDir,e=this.cwdMcpJsonKey;this.cwdMcpJsonDir=null,this.cwdMcpJsonKey=null;try{await dt(t,e)}catch(i){o.warn("pi-adapter",`\u6E05\u7406 omp cwd .mcp.json \u6761\u76EE\u5931\u8D25 key=${e}: ${i instanceof Error?i.message:String(i)}`)}}if(this.process){const t=this.process;try{b(t,"SIGTERM")}catch{}const e=setTimeout(()=>{try{b(t,"SIGKILL")}catch{}},5e3);t.on("exit",()=>clearTimeout(e)),this.process=null}}isAlive(){return this.alive}async createSession(t){this.sessionReadyPromise=null,await this.createNewSession();const e=this.piSessionPath||`pi-${Date.now()}`;return o.info("pi-adapter",`Session created: ${e} (path=${this.piSessionPath})`),e}async resumeSession(t,e){await this.switchSession()}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(t){this.identity.forgetSession(t),this.inboundMessageIds.forgetSession(t),this.piSessionPath=null,this.sessionReadyPromise=null,this.persistPiSessionPath(void 0)}sendPrompt(t){const e=new mt(t.adapterSessionId),i=this.buildPromptTextFromRequest(t);return this.ensureSessionReady().then(()=>this.transport.send("prompt",{message:i})).then(s=>{s.success||e.emitDone({status:"failed",error:s.error})}).catch(s=>{e.emitError(s instanceof Error?s:new Error(String(s)))}),e}async cancel(t){try{await this.transport.send("abort")}catch{}}deliverInboundEvent(t){const{event_id:e,session_id:i,content:s}=t,n=++this.promptGeneration,r=this.buildPromptText(t);if(this.isStreaming){if(this.activeEventId&&this.activeEventId!==e){const a=this.activeEventId;o.info("pi-adapter",`steer: cancel ${a} -> ${e}`),this.flushTextBuffer(),this.callbacks.sendEventResult(a,"canceled","steered to new event"),this.activeAuditCapture?.eventId===a&&(this.snapshotAuditBoundary(a),this.emit("eventDone",a))}this.activeEventId=e,this.activeSessionId=i,this.resetRunStreamState(),this.startComposing(i,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.sendInboundPrompt(t,n,{message:r,streamingBehavior:"steer"})}else o.info("pi-adapter",`prompt: event=${e} session=${i}`),this.activeEventId=e,this.activeSessionId=i,this.isStreaming=!0,this.resetRunStreamState(),this.startComposing(i,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.sendInboundPrompt(t,n,{message:r})}sendInboundPrompt(t,e,i){const s=t.event_id,n=()=>!this.stopped&&this.promptGeneration===e&&this.activeEventId===s;(async()=>{if(this.abortBarrier&&await this.abortBarrier,!n())return;this.beginAuditCapture(t);const a=await this.transport.send("prompt",i);if(!a.success)throw new Error(a.error||"prompt rejected")})().catch(a=>{if(!n())return;const d=a instanceof Error?a.message:String(a);o.error("pi-adapter",`prompt error event=${s}: ${d}`),this.isStreaming=!1,this.cancelDoneGuard(),this.stopComposing(),this.stopIdleTimer(),this.clearActive(),this.callbacks.sendEventResult(s,"failed",d)})}beginAbortBarrier(){if(this.abortBarrier)return;const t=Promise.resolve().then(()=>this.transport.send("abort")).then(e=>{if(!e.success)throw new Error(e.error||"abort rejected")});this.abortBarrier=t,t.then(()=>{this.abortBarrier===t&&(this.abortBarrier=null)},e=>{o.error("pi-adapter",`abort failed: ${e}`)})}deliverStopEvent(t,e){if(this.activeEventId===t){o.info("pi-adapter",`stop: event=${t}, releasing busy immediately`),this.promptGeneration++,this.beginAbortBarrier(),this.cancelDoneGuard(),this.flushTextBuffer();const i=this.nextStreamSeq(),s=this.activeClientMsgId??void 0;this.callbacks.sendStreamChunk(t,this.activeSessionId??"","",i,!0,s),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.clearActive(),this.callbacks.sendEventResult(t,"canceled","stopped by user")}}async handleLocalAction(t){const e=t.action_id;switch(t.action_type){case"set_model":{const i=t.params??{},s=(i.modelId??i.model_id??"").trim();if(!s)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_model","model_id is required"),{handled:!0,kind:"set_model_error"};try{await this.initializationPromise;let n=(i.provider_id??i.provider??i.model_provider)?.trim();if(!n){const d=((await this.transport.send("get_available_models")).data?.models??[]).filter(p=>p.id===s&&p.provider?.trim());if(d.length>1){const p=(await this.currentModel())?.provider?.trim();n=d.find(h=>h.provider?.trim()===p)?.provider?.trim()}n=n??d[0]?.provider?.trim()}return n?(await this.setModelSelection(n,s,!0),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"model_set",provider:n,modelId:s}),this.syncModelBinding(),{handled:!0,kind:"set_model"}):(this.callbacks.sendLocalActionResult(e,"failed",void 0,"model_not_found",`No provider for model: ${s}`),{handled:!0,kind:"set_model_error"})}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_model_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_model_error"}}}case"set_provider":{const i=t.params??{},s=(i.provider_id??i.provider??"").trim();if(!s)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_provider","provider_id is required"),{handled:!0,kind:"set_provider_error"};try{await this.initializationPromise;const a=((await this.transport.send("get_available_models")).data?.models??[]).filter(h=>h.provider?.trim()===s);if(a.length===0)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"provider_not_found",`No models for provider: ${s}`),{handled:!0,kind:"set_provider_error"};const d=(await this.currentModel())?.id,p=a.find(h=>h.id===d)?.id??a[0].id;return await this.setModelSelection(s,p,!0),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"provider_set",provider:s,modelId:p}),this.syncModelBinding(),{handled:!0,kind:"set_provider"}}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_provider_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_provider_error"}}}case"get_context":try{const i=await this.transport.send("get_state");return this.callbacks.sendLocalActionResult(e,"ok",{state:i}),{handled:!0,kind:"get_context"}}catch(i){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"get_context_error",i instanceof Error?i.message:String(i)),{handled:!1,kind:""}}case"pi_extension_ui_response":return this.transport.sendNoWait({type:"extension_ui_response",...t.params??{}}),this.callbacks.sendLocalActionResult(e,"ok"),{handled:!0,kind:"extension_ui_response"};default:return{handled:!1,kind:""}}}setPermissionHandler(t){}async ping(t){try{return await this.transport.send("get_state"),!0}catch{return!1}}getStatus(){return{alive:this.alive,busy:this.isStreaming,sessions:this.piSessionPath?1:0}}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}takeAuditBoundary(t){const e=this.completedAuditBoundaries.get(t);return e&&this.completedAuditBoundaries.delete(t),e}clearActiveEventForShutdown(){this.stopIdleTimer(),this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.activeEventId=null}getMcpConfig(){if(!this.internalApi)return null;const t=F(O(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[t,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const t=this.process?.pid;return t?z(t,[t]):!1}async probe(t){const e=this.getStatus();return{...await et(this.config.command||"pi",{alive:e.alive,busy:e.busy,started:!!this.process},t),session:this.probeSessionRecord()}}probeSessionRecord(){const t=this.piSessionPath;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const e=f(t);return{recordPath:t,lastActivityMs:e.mtimeMs,freshMs:Date.now()-e.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}getSupportedCommands(){return[{name:"model",description:"List or set model",args:"[provider:model_id]"},{name:"interrupt",description:"Interrupt current run"},{name:"status",description:"Show session status"},{name:"skills",description:"List available skills"}]}async execCommand(t,e,i){try{if(t==="model"&&e.trim()&&await this.initializationPromise,!this.alive)return{status:"failed",message:"Pi process not running"};switch(t){case"model":{const s=e.trim();if(s){const a=s.indexOf(":");if(a<1)return{status:"failed",message:"Format: provider:model_id"};const d=s.slice(0,a),p=s.slice(a+1);return p?(await this.setModelSelection(d,p,!0),this.syncModelBinding(),{status:"ok",message:`Model set to ${d}:${p}`}):{status:"failed",message:"Format: provider:model_id"}}const r=(await this.transport.send("get_available_models"))?.data?.models;return r&&r.length>0?{status:"ok",message:`Available models:
1
+ import{EventEmitter as y}from"node:events";import{stat as C}from"node:fs/promises";import{mkdirSync as B,writeFileSync as G,unlinkSync as D,statSync as v,existsSync as S}from"node:fs";import{join as u,resolve as F,delimiter as w}from"node:path";import{fileURLToPath as I}from"node:url";import{tmpdir as O,homedir as b}from"node:os";import{resolveCommandPath as N,spawnCommand as L,killProcessGroup as _,hasChildProcesses as j}from"../../core/runtime/spawn.js";import{InternalApiServer as z}from"../../core/mcp/internal-api-server.js";import{TOOLS as E}from"../../core/mcp/tools.js";import{IdentityInjector as q}from"../shared/identity-injector.js";import{compactToolInputForWire as J}from"../shared/tool-wire-payload.js";import{syncDefaultSkillsToDir as K}from"../../default-skills/index.js";import{PiTransport as U}from"./pi-transport.js";import{log as o}from"../../core/log/index.js";import{scanSkills as H}from"../claude/skill-scanner.js";import{listLivingDescendants as X,countLivingDescendantsOutsideBaseline as Y}from"../cursor/living-descendants.js";import{SessionBindingStore as V}from"../../core/persistence/session-binding-store.js";import{AgentGlobalConfigStore as W}from"../../core/persistence/agent-global-config-store.js";import{splitTextForAibotProtocol as Q}from"../../core/protocol/index.js";import{InboundMessageIdInjector as Z}from"../shared/inbound-message-id-injector.js";import{buildSimpleProbeReport as tt}from"../shared/probe-util.js";import{piGrixProviderId as et,removePiGrixProvider as it,writePiGrixProvider as st}from"./pi-provider-config.js";import{agentIdOf as nt}from"../shared/native-provider-config.js";import{writeOmpMcpEntry as rt,recordOmpMcpEntryPid as ot,removeOmpMcpEntry as at}from"./omp-mcp-config.js";import{PI_GRIX_TOOLS_READY_PREFIX as P}from"./pi-grix-tools-extension.js";function dt(c){return nt(c)==="omp"}function lt(c){return process.platform!=="win32"?"PATH":Object.keys(c).find(t=>t.toLowerCase()==="path")??"PATH"}function ct(c){const t=lt(c),e=String(c[t]??""),i=process.platform==="win32"?"bun.exe":"bun";if(e.split(w).some(r=>r.trim()&&S(u(r.trim(),i))))return c;const n=u(b(),".bun","bin");return S(u(n,i))?(o.info("pi-adapter",`bun \u4E0D\u5728\u5F53\u524D PATH\uFF0C\u8865\u4E0A\u9ED8\u8BA4\u5B89\u88C5\u76EE\u5F55: ${n}`),{...c,[t]:e?`${n}${w}${e}`:n}):c}class ht extends y{adapterSessionId;constructor(t){super(),this.adapterSessionId=t}emitDone(t){this.emit("done",t)}emitError(t){if(this.listenerCount("error")===0){o.warn("pi-adapter",`Prompt handle error (no listeners): ${t.message}`);return}this.emit("error",t)}async cancel(){}}const pt=12e4,T=90*1e3,$=1800*1e3;function A(c){try{return process.kill(c,0),!0}catch(t){return t.code==="EPERM"}}const ut=500,mt=2e3,x=3,ft=500,gt=1e4;function R(c){return new Promise(t=>setTimeout(t,c))}function vt(c){const t=new Set,e=[];for(const i of c){const s=i.provider?.trim();!s||t.has(s)||(t.add(s),e.push({id:s,display_name:s}))}return e}function m(c){if(c===void 0)return"undefined";if(c===null)return"null";if(typeof c=="string")return c.length>500?`${c.slice(0,500)}...`:c;try{const t=JSON.stringify(c);return t.length>500?`${t.slice(0,500)}...`:t}catch{return String(c)}}class M extends y{type="pi";config;callbacks;process=null;transport=new U;alive=!1;stopped=!1;internalApi=null;mcpConfigPath=null;piGrixToolsExtensionPath=null;piGrixToolsReady=!1;piGrixToolsReadyError=null;piGrixToolsStderrBuffer="";cwdMcpJsonDir=null;cwdMcpJsonKey=null;identity;inboundMessageIds=new Z;piSessionPath=null;activeEventId=null;activeSessionId=null;activeAuditCapture=null;completedAuditBoundaries=new Map;isStreaming=!1;abortBarrier=null;promptGeneration=0;streamSeq=0;clientMsgSeq=0;activeClientMsgId=null;thinkingSeq=0;textBuffer="";emittedTextByIndex=new Map;textFlushTimer=null;activeRunError=null;runErrorEmitted=!1;idleTimer=null;lastRpcAt=0;livenessExtendStartAt;toolCallsInFlight=new Set;descendantBaseline;composingSessionId=null;composingInterval=null;doneGuardTimer=null;bindingStore=null;globalConfigStore=null;modelSelectionRevision=0;initializationPromise=null;aibotSessionId="";sessionReadyPromise=null;provider;agentName="";clientType="";constructor(t,e){super(),this.config=t,this.callbacks=e,this.identity=new q("pi-adapter",e.getAgentProfile);const i=t.options??{};this.aibotSessionId=String(i.aibotSessionId??"").trim(),this.agentName=String(i.agentName??"").trim(),this.clientType=String(i.clientType??"").trim().toLowerCase(),this.provider=i.provider,this.bindingStore=i.bindingStore instanceof V?i.bindingStore:null,this.globalConfigStore=i.globalConfigStore instanceof W?i.globalConfigStore:null,this.bindingStore&&this.aibotSessionId&&(this.piSessionPath=this.bindingStore.getPiSessionPath(this.aibotSessionId)??null)}isOmp(t=this.config.command||"pi"){return this.clientType?this.clientType==="omp":dt(t)}resolvePiConfigDir(){return String(this.config.env?.PI_CODING_AGENT_DIR??"").trim()||u(b(),".pi","agent")}start(){return this.initializationPromise=this.initializeSession(),this.initializationPromise}async initializeSession(){const t=this.resolveInitialModel();if(await this.startInternalApi(),await this.spawnPi(),await this.ensureSessionReady(),t)try{await this.setModelSelection(t.provider,t.modelId,!1)}catch(e){o.warn("pi-adapter",`Failed to restore model selection: ${e instanceof Error?e.message:String(e)}`)}o.info("pi-adapter",`Ready (pid=${this.process?.pid})`),await this.syncModelBinding()}async syncModelBinding(){if(!this.aibotSessionId)return;const t=this.modelSelectionRevision;for(let e=1;e<=x;e++)try{const[i,s]=await Promise.all([this.transport.send("get_available_models"),this.transport.send("get_state")]);if(t!==this.modelSelectionRevision)return;const n=i.data?.models;if(!n||n.length===0){if(e<x){await R(ft);continue}o.warn("pi-adapter",`syncModelBinding: empty model list after ${x} attempts, giving up`);return}const r=s.data?.model,a=this.bindingStore?.get(this.aibotSessionId);s.success&&r?.provider&&r.id&&!(a?.piProviderId&&a.piModelId)&&this.bindingStore?.setPiModel(this.aibotSessionId,r.provider,r.id);const d={available_models:n.map(p=>({id:p.id,display_name:p.name??p.id,...p.provider?{provider:p.provider}:{}}))},h=vt(n);h.length>0&&(d.available_providers=h),r?.id&&(d.model_id=r.id),r?.provider&&(d.provider_id=r.provider,d.model_provider=r.provider),this.callbacks.sendUpdateBindingCard(this.aibotSessionId,this.isStreaming?"composing":"ready",this.resolveCwd(),d),o.info("pi-adapter",`synced model binding: ${n.length} models, current=${r?.id??"unknown"} (attempt ${e})`);return}catch(i){o.warn("pi-adapter",`syncModelBinding failed (non-fatal): ${i instanceof Error?i.message:String(i)}`);return}}resolveInitialModel(){const t=this.bindingStore?.get(this.aibotSessionId);if(t?.piProviderId&&t.piModelId)return{provider:t.piProviderId,modelId:t.piModelId};if(this.piSessionPath)return;const e=this.globalConfigStore?.get(this.agentName);if(e?.piProviderId&&e.piModelId)return{provider:e.piProviderId,modelId:e.piModelId}}async setModelSelection(t,e,i){const s=await this.transport.send("set_model",{provider:t,modelId:e});if(!s.success)throw new Error(s.error||"set_model failed");this.modelSelectionRevision++,this.aibotSessionId&&this.bindingStore?.setPiModel(this.aibotSessionId,t,e),i&&this.agentName&&this.globalConfigStore?.set(this.agentName,{piProviderId:t,piModelId:e})}async currentModel(){try{return(await this.transport.send("get_state")).data?.model??null}catch{return null}}async stop(){if(this.stopped=!0,this.promptGeneration++,this.alive=!1,this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.cancelDoneGuard(),this.transport.close(),this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),this.mcpConfigPath){try{D(this.mcpConfigPath)}catch{}this.mcpConfigPath=null}if(this.cwdMcpJsonDir&&this.cwdMcpJsonKey){const t=this.cwdMcpJsonDir,e=this.cwdMcpJsonKey;this.cwdMcpJsonDir=null,this.cwdMcpJsonKey=null;try{await at(t,e)}catch(i){o.warn("pi-adapter",`\u6E05\u7406 omp cwd .mcp.json \u6761\u76EE\u5931\u8D25 key=${e}: ${i instanceof Error?i.message:String(i)}`)}}if(this.process){const t=this.process;try{_(t,"SIGTERM")}catch{}const e=setTimeout(()=>{try{_(t,"SIGKILL")}catch{}},5e3);t.on("exit",()=>clearTimeout(e)),this.process=null}}isAlive(){return this.alive}async createSession(t){this.sessionReadyPromise=null,await this.createNewSession();const e=this.piSessionPath||`pi-${Date.now()}`;return o.info("pi-adapter",`Session created: ${e} (path=${this.piSessionPath})`),e}async resumeSession(t,e){await this.switchSession()}onAgentProfileChanged(){this.identity.onProfileChanged()}async destroySession(t){this.identity.forgetSession(t),this.inboundMessageIds.forgetSession(t),this.piSessionPath=null,this.sessionReadyPromise=null,this.persistPiSessionPath(void 0)}sendPrompt(t){const e=new ht(t.adapterSessionId),i=this.buildPromptTextFromRequest(t);return this.ensureSessionReady().then(()=>this.transport.send("prompt",{message:i})).then(s=>{s.success||e.emitDone({status:"failed",error:s.error})}).catch(s=>{e.emitError(s instanceof Error?s:new Error(String(s)))}),e}async cancel(t){try{await this.transport.send("abort")}catch{}}deliverInboundEvent(t){const{event_id:e,session_id:i,content:s}=t,n=++this.promptGeneration,r=this.buildPromptText(t);if(this.isStreaming){if(this.activeEventId&&this.activeEventId!==e){const a=this.activeEventId;o.info("pi-adapter",`steer: cancel ${a} -> ${e}`),this.flushTextBuffer(),this.callbacks.sendEventResult(a,"canceled","steered to new event"),this.activeAuditCapture?.eventId===a&&(this.snapshotAuditBoundary(a),this.emit("eventDone",a))}this.activeEventId=e,this.activeSessionId=i,this.resetRunStreamState(),this.startComposing(i,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.sendInboundPrompt(t,n,{message:r,streamingBehavior:"steer"})}else o.info("pi-adapter",`prompt: event=${e} session=${i}`),this.activeEventId=e,this.activeSessionId=i,this.isStreaming=!0,this.resetRunStreamState(),this.startComposing(i,e),this.lastRpcAt=Date.now(),this.livenessExtendStartAt=void 0,this.resetIdleTimer(),this.sendInboundPrompt(t,n,{message:r})}sendInboundPrompt(t,e,i){const s=t.event_id,n=()=>!this.stopped&&this.promptGeneration===e&&this.activeEventId===s;(async()=>{if(this.abortBarrier&&await this.abortBarrier,!n())return;this.beginAuditCapture(t);const a=await this.transport.send("prompt",i);if(!a.success)throw new Error(a.error||"prompt rejected")})().catch(a=>{if(!n())return;const d=a instanceof Error?a.message:String(a);o.error("pi-adapter",`prompt error event=${s}: ${d}`),this.isStreaming=!1,this.cancelDoneGuard(),this.stopComposing(),this.stopIdleTimer(),this.clearActive(),this.callbacks.sendEventResult(s,"failed",d)})}beginAbortBarrier(){if(this.abortBarrier)return;const t=Promise.resolve().then(()=>this.transport.send("abort")).then(e=>{if(!e.success)throw new Error(e.error||"abort rejected")});this.abortBarrier=t,t.then(()=>{this.abortBarrier===t&&(this.abortBarrier=null)},e=>{o.error("pi-adapter",`abort failed: ${e}`)})}deliverStopEvent(t,e){if(this.activeEventId===t){o.info("pi-adapter",`stop: event=${t}, releasing busy immediately`),this.promptGeneration++,this.beginAbortBarrier(),this.cancelDoneGuard(),this.flushTextBuffer();const i=this.nextStreamSeq(),s=this.activeClientMsgId??void 0;this.callbacks.sendStreamChunk(t,this.activeSessionId??"","",i,!0,s),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.clearActive(),this.callbacks.sendEventResult(t,"canceled","stopped by user")}}async handleLocalAction(t){const e=t.action_id;switch(t.action_type){case"set_model":{const i=t.params??{},s=(i.modelId??i.model_id??"").trim();if(!s)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_model","model_id is required"),{handled:!0,kind:"set_model_error"};try{await this.initializationPromise;let n=(i.provider_id??i.provider??i.model_provider)?.trim();if(!n){const d=((await this.transport.send("get_available_models")).data?.models??[]).filter(h=>h.id===s&&h.provider?.trim());if(d.length>1){const h=(await this.currentModel())?.provider?.trim();n=d.find(p=>p.provider?.trim()===h)?.provider?.trim()}n=n??d[0]?.provider?.trim()}return n?(await this.setModelSelection(n,s,!0),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"model_set",provider:n,modelId:s}),this.syncModelBinding(),{handled:!0,kind:"set_model"}):(this.callbacks.sendLocalActionResult(e,"failed",void 0,"model_not_found",`No provider for model: ${s}`),{handled:!0,kind:"set_model_error"})}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_model_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_model_error"}}}case"set_provider":{const i=t.params??{},s=(i.provider_id??i.provider??"").trim();if(!s)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"invalid_provider","provider_id is required"),{handled:!0,kind:"set_provider_error"};try{await this.initializationPromise;const a=((await this.transport.send("get_available_models")).data?.models??[]).filter(p=>p.provider?.trim()===s);if(a.length===0)return this.callbacks.sendLocalActionResult(e,"failed",void 0,"provider_not_found",`No models for provider: ${s}`),{handled:!0,kind:"set_provider_error"};const d=(await this.currentModel())?.id,h=a.find(p=>p.id===d)?.id??a[0].id;return await this.setModelSelection(s,h,!0),this.callbacks.sendLocalActionResult(e,"ok",{outcome:"provider_set",provider:s,modelId:h}),this.syncModelBinding(),{handled:!0,kind:"set_provider"}}catch(n){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"set_provider_error",n instanceof Error?n.message:String(n)),{handled:!0,kind:"set_provider_error"}}}case"get_context":try{const i=await this.transport.send("get_state");return this.callbacks.sendLocalActionResult(e,"ok",{state:i}),{handled:!0,kind:"get_context"}}catch(i){return this.callbacks.sendLocalActionResult(e,"failed",void 0,"get_context_error",i instanceof Error?i.message:String(i)),{handled:!1,kind:""}}case"pi_extension_ui_response":return this.transport.sendNoWait({type:"extension_ui_response",...t.params??{}}),this.callbacks.sendLocalActionResult(e,"ok"),{handled:!0,kind:"extension_ui_response"};default:return{handled:!1,kind:""}}}setPermissionHandler(t){}async ping(t){try{return await this.transport.send("get_state"),!0}catch{return!1}}getStatus(){return{alive:this.alive,busy:this.isStreaming,sessions:this.piSessionPath?1:0}}getActiveEventIds(){return this.activeEventId?[this.activeEventId]:[]}takeAuditBoundary(t){const e=this.completedAuditBoundaries.get(t);return e&&this.completedAuditBoundaries.delete(t),e}clearActiveEventForShutdown(){this.stopIdleTimer(),this.activeEventId&&this.snapshotAuditBoundary(this.activeEventId),this.activeEventId=null}getMcpConfig(){if(!this.internalApi||!this.isOmp())return null;const t=F(I(import.meta.url),"../../../mcp/acp-mcp-server.js");return{name:"grix-connector-tools",command:process.execPath,args:[t,"--api-url",this.internalApi.url]}}async hasBackgroundWork(){const t=this.process?.pid;return t?j(t,[t]):!1}async probe(t){const e=this.getStatus();return{...await tt(this.config.command||"pi",{alive:e.alive,busy:e.busy,started:!!this.process},t),session:this.probeSessionRecord()}}probeSessionRecord(){const t=this.piSessionPath;if(!t)return{recordPath:null,lastActivityMs:null,freshMs:null};try{const e=v(t);return{recordPath:t,lastActivityMs:e.mtimeMs,freshMs:Date.now()-e.mtimeMs}}catch{return{recordPath:t,lastActivityMs:null,freshMs:null}}}getSupportedCommands(){return[{name:"model",description:"List or set model",args:"[provider:model_id]"},{name:"interrupt",description:"Interrupt current run"},{name:"status",description:"Show session status"},{name:"skills",description:"List available skills"}]}async execCommand(t,e,i){try{if(t==="model"&&e.trim()&&await this.initializationPromise,!this.alive)return{status:"failed",message:"Pi process not running"};switch(t){case"model":{const s=e.trim();if(s){const a=s.indexOf(":");if(a<1)return{status:"failed",message:"Format: provider:model_id"};const d=s.slice(0,a),h=s.slice(a+1);return h?(await this.setModelSelection(d,h,!0),this.syncModelBinding(),{status:"ok",message:`Model set to ${d}:${h}`}):{status:"failed",message:"Format: provider:model_id"}}const r=(await this.transport.send("get_available_models"))?.data?.models;return r&&r.length>0?{status:"ok",message:`Available models:
2
2
  ${r.map(d=>` ${d.provider??"unknown"}:${d.id} (${d.name??d.id})`).join(`
3
- `)}`,data:r}:{status:"ok",message:"No models available",data:[]}}case"interrupt":return this.isStreaming?(await this.transport.send("abort"),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","interrupted"),this.clearActive(),{status:"ok",message:"Run interrupted"}):{status:"failed",message:"No active run to interrupt"};case"status":{const s=this.getStatus();return{status:"ok",message:`Alive: ${s.alive}, Busy: ${s.busy}, Session: ${this.piSessionPath??"none"}`,data:{alive:s.alive,busy:s.busy,sessions:s.sessions,sessionPath:this.piSessionPath}}}case"skills":{const s=V({mode:"pi"}),n=s.map(r=>`- ${r.name}${r.trigger?` (${r.trigger})`:""} [${r.source}]: ${r.description}`);return{status:"ok",message:n.length>0?n.join(`
4
- `):"No skills found",data:s}}default:return{status:"unsupported",message:`Unknown command: ${t}`}}}catch(s){return{status:"failed",message:s instanceof Error?s.message:String(s)}}}resolveCwd(){if(this.bindingStore&&this.aibotSessionId){const e=this.bindingStore.get(this.aibotSessionId);if(e?.cwd)return e.cwd}const t=(this.config.options??{}).cwd;return typeof t=="string"&&t?t:process.cwd()}async startInternalApi(){try{this.internalApi=new q,this.internalApi.setInvokeHandler(async(a,d,p,h)=>this.callbacks.agentInvoke(a,d,h)),await this.internalApi.start(0),o.info("pi-adapter",`Internal API started at ${this.internalApi.url}`);const t=this.resolvePiConfigDir(),e=this.getMcpConfig(),i=pt(t),s=u(N(),"grix-pi-mcp");C(s,{recursive:!0}),this.mcpConfigPath=u(s,`mcp-${process.pid}-${Date.now()}.json`),R(this.mcpConfigPath,JSON.stringify({mcpServers:{...i,[e.name]:{command:e.command,args:e.args,directTools:!0,lifecycle:"eager"}}}),"utf8"),o.info("pi-adapter",`MCP config written to ${this.mcpConfigPath}`);const n=u(t,"skills"),r=U(n);r.length>0&&o.info("pi-adapter",`Synced connector skills to ${n}: [${r.join(", ")}]`)}catch(t){o.warn("pi-adapter",`Failed to start MCP tools (non-fatal): ${t instanceof Error?t.message:String(t)}`)}}async writeOmpCwdMcpConfig(t){if(!this.mcpConfigPath)return;const e=this.getMcpConfig();if(e)try{const i=await ot(t,{name:e.name,command:e.command,args:e.args});this.cwdMcpJsonDir=t,this.cwdMcpJsonKey=i}catch(i){o.warn("pi-adapter",`\u5199\u5165 omp <cwd>/.omp/mcp.json \u5931\u8D25: ${i instanceof Error?i.message:String(i)}`)}}async spawnPi(){const t=this.config.command||"pi",e=G(t,typeof process.env.PATH=="string"?process.env.PATH:void 0),i=this.config.args??[],n=i.some(c=>c.startsWith("--mode"))?[...i]:["--mode","rpc",...i],r=this.resolvePiConfigDir(),a=it(this.agentName);if(this.provider){const c=this.isOmp(e)?"bare":"dollar";await nt(r,a,this.provider,c)?(n.includes("--provider")||n.push("--provider",a),!n.includes("--model")&&this.provider.model?.trim()&&n.push("--model",this.provider.model.trim())):o.warn("pi-adapter","provider config incomplete (baseUrl/model required); Grix provider not applied")}else await st(r,a).then(c=>{c&&o.info("pi-adapter",`Removed stale Grix provider "${a}" from models.json`)}).catch(c=>{o.warn("pi-adapter",`Failed to clean up Grix provider config: ${c instanceof Error?c.message:String(c)}`)});this.mcpConfigPath&&!n.some(c=>c==="--mcp-config")&&!this.isOmp(e)&&(await ut(e)?n.push("--mcp-config",this.mcpConfigPath):o.warn("pi-adapter","\u5F53\u524D Pi \u4E0D\u652F\u6301 --mcp-config\uFF08\u672A\u68C0\u6D4B\u5230 pi-mcp-adapter \u6269\u5C55\uFF09\uFF0C\u8DF3\u8FC7 MCP \u6CE8\u5165\u4EE5\u907F\u514D\u542F\u52A8\u5931\u8D25"));let d={...process.env,...this.config.env};this.isOmp(e)&&(d=ht(d));const p=this.provider?.apiKey?.trim();p&&!d.GRIX_PROVIDER_API_KEY?.trim()&&(d.GRIX_PROVIDER_API_KEY=p);const h=this.resolveCwd();o.info("pi-adapter",`Spawning: ${e} ${n.join(" ")}`);try{if(!(await k(h)).isDirectory())throw new Error(`Bound path is not a directory: ${h}`)}catch(c){throw String(c?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${h}. Please rebind with /grix open <valid-directory>.`):c}const S=this.isOmp(e);S&&await this.writeOmpCwdMcpConfig(h);try{this.process=j(e,n,{env:d,cwd:h}).process}catch(c){throw o.error("pi-adapter",`PI spawn threw: ${c}`),this.alive=!1,c}S&&this.cwdMcpJsonDir&&this.cwdMcpJsonKey&&this.process.pid&&at(this.cwdMcpJsonDir,this.cwdMcpJsonKey,this.process.pid).catch(c=>{o.warn("pi-adapter",`\u8BB0\u5F55 omp \u5B50\u8FDB\u7A0B pid \u5230 mcp \u72B6\u6001\u6587\u4EF6\u5931\u8D25: ${c instanceof Error?c.message:String(c)}`)}),this.process.on("error",c=>{o.error("pi-adapter",`Spawn error: ${c.message}`),this.alive=!1,this.transport.close(),this.activeEventId&&(this.callbacks.sendEventResult(this.activeEventId,"failed",`Spawn error: ${c.message}`),this.clearActive()),this.stopped||this.emit("exit",1)}),this.process.on("exit",c=>{o.info("pi-adapter",`PI process exited (code=${c})`),this.alive=!1,this.transport.close(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"failed",`PI process exited (code=${c})`),this.isStreaming=!1,this.clearActive(),this.stopped||this.emit("exit",c??1)}),this.process.stderr?.on("data",c=>{const I=c.toString().trim();I&&o.info("pi-adapter",`[pi stderr] ${I}`)}),this.transport.on("event",c=>this.handlePiEvent(c)),this.transport.bind(this.process.stdin,this.process.stdout),this.alive=!0}handlePiEvent(t){if(this.stopped||this.abortBarrier)return;if(this.lastRpcAt=Date.now(),t.type==="tool_execution_start"){const i=t;this.descendantBaseline===void 0&&this.captureDescendantBaseline(),i.toolCallId&&this.toolCallsInFlight.add(i.toolCallId)}else if(t.type==="tool_execution_end"){const i=t;i.toolCallId&&this.toolCallsInFlight.delete(i.toolCallId)}switch(this.resetIdleTimer(),t.type){case"message_update":{const i=t.assistantMessageEvent;if(!i)break;const s=i.type;if(s==="text_delta"){const n=i.delta;if(n){const r=typeof i.contentIndex=="number"?i.contentIndex:0;this.rememberEmittedText(r,n),this.appendText(n)}}else if(s==="text_end"){const n=i.content,r=typeof i.contentIndex=="number"?i.contentIndex:0;n&&this.appendMissingText(r,n)}else if(s==="thinking_delta"){const n=i.delta;n&&this.activeEventId&&this.activeSessionId&&(this.thinkingSeq++,this.callbacks.sendThinking(this.activeEventId,this.activeSessionId,n))}else if(s==="done"||s==="error"){if(this.flushTextBuffer(),s==="error"){const n=this.piMessageError(i.error,i.reason);o.warn("pi-adapter",`terminal message_update error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${m(i.error)} reason=${m(i.reason)}`),this.recordRunError(n)}this.scheduleDoneGuard()}break}case"message_end":{const i=t.message;i?.role==="assistant"&&i.stopReason==="error"&&(o.warn("pi-adapter",`terminal message_end error event=${this.activeEventId} sessionId=${this.activeSessionId} errorMessage=${m(i.errorMessage)} message=${m(i)}`),this.recordRunError(this.piMessageError(i,i.errorMessage)),this.scheduleDoneGuard());break}case"tool_execution_start":{if(this.cancelDoneGuard(),this.flushTextBuffer(),!this.activeEventId||!this.activeSessionId)break;const i=t;if(i.toolName){const s=K(i.args);this.callbacks.sendToolUse(this.activeEventId,this.activeSessionId,i.toolName,s)}break}case"tool_execution_end":{if(!this.activeEventId||!this.activeSessionId)break;const i=t;i.isError&&this.callbacks.sendToolResult(this.activeEventId,this.activeSessionId,i.toolName,"(failed)");break}case"agent_end":{if(o.info("pi-adapter",`agent_end event=${this.activeEventId} sessionId=${this.activeSessionId}`),this.cancelDoneGuard(),t.willRetry===!0&&this.activeEventId){o.info("pi-adapter",`agent_end willRetry=true \u2014 holding event=${this.activeEventId} for auto-retry`),this.activeRunError=null,this.emittedTextByIndex.clear(),this.resetIdleTimer();break}this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.captureOmpAuditMessages(t.messages),this.completeActiveEvent();break}case"agent_start":{this.cancelDoneGuard(),this.activeEventId&&(o.info("pi-adapter",`agent_start event=${this.activeEventId}`),this.isStreaming=!0);break}default:break}}appendText(t){if(this.textBuffer+=t,this.textBuffer.length>=vt){this.flushTextBuffer();return}this.scheduleTextFlush()}scheduleTextFlush(){this.textFlushTimer||(this.textFlushTimer=setTimeout(()=>{this.textFlushTimer=null,this.flushTextBuffer()},gt))}flushTextBuffer(){this.stopTextFlush(),!(!this.textBuffer||!this.activeEventId||!this.activeSessionId)&&(this.sendTextChunks(this.textBuffer),this.textBuffer="")}sendTextChunks(t){if(!(!this.activeEventId||!this.activeSessionId))for(const e of Z(t))this.callbacks.sendStreamChunk(this.activeEventId,this.activeSessionId,e,this.nextStreamSeq(),!1,this.activeClientMsgId??void 0)}stopTextFlush(){this.textFlushTimer&&(clearTimeout(this.textFlushTimer),this.textFlushTimer=null)}buildPromptText(t){let e=t.content||"";if(t.context_messages_json)try{const s=JSON.parse(t.context_messages_json);if(Array.isArray(s)&&s.length>0){const n=s.map(r=>`[context] ${r.sender_id??"unknown"}: ${r.content}`).join(`
3
+ `)}`,data:r}:{status:"ok",message:"No models available",data:[]}}case"interrupt":return this.isStreaming?(await this.transport.send("abort"),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"canceled","interrupted"),this.clearActive(),{status:"ok",message:"Run interrupted"}):{status:"failed",message:"No active run to interrupt"};case"status":{const s=this.getStatus();return{status:"ok",message:`Alive: ${s.alive}, Busy: ${s.busy}, Session: ${this.piSessionPath??"none"}`,data:{alive:s.alive,busy:s.busy,sessions:s.sessions,sessionPath:this.piSessionPath}}}case"skills":{const s=H({mode:"pi"}),n=s.map(r=>`- ${r.name}${r.trigger?` (${r.trigger})`:""} [${r.source}]: ${r.description}`);return{status:"ok",message:n.length>0?n.join(`
4
+ `):"No skills found",data:s}}default:return{status:"unsupported",message:`Unknown command: ${t}`}}}catch(s){return{status:"failed",message:s instanceof Error?s.message:String(s)}}}resolveCwd(){if(this.bindingStore&&this.aibotSessionId){const e=this.bindingStore.get(this.aibotSessionId);if(e?.cwd)return e.cwd}const t=(this.config.options??{}).cwd;return typeof t=="string"&&t?t:process.cwd()}async startInternalApi(){const t=this.isOmp();try{this.internalApi=new z,this.internalApi.setInvokeHandler(async(n,r,a,d)=>this.callbacks.agentInvoke(n,r,d)),await this.internalApi.start(0),o.info("pi-adapter",`Internal API started at ${this.internalApi.url}`);const e=this.resolvePiConfigDir();if(t){const n=this.getMcpConfig(),r=u(O(),"grix-pi-mcp");B(r,{recursive:!0}),this.mcpConfigPath=u(r,`mcp-${process.pid}-${Date.now()}.json`),G(this.mcpConfigPath,JSON.stringify({mcpServers:{[n.name]:{command:n.command,args:n.args,directTools:!0,lifecycle:"eager"}}}),"utf8"),o.info("pi-adapter",`MCP config written to ${this.mcpConfigPath}`)}else{const n=I(new URL("./pi-grix-tools-extension.js",import.meta.url)),r=I(new URL("./pi-grix-tools-extension.ts",import.meta.url));if(this.piGrixToolsExtensionPath=S(n)?n:r,!S(this.piGrixToolsExtensionPath))throw new Error(`Pi Grix tools extension not found: ${this.piGrixToolsExtensionPath}`);o.info("pi-adapter",`Pi Grix direct tools extension: ${this.piGrixToolsExtensionPath}`)}const i=u(e,"skills"),s=K(i);s.length>0&&o.info("pi-adapter",`Synced connector skills to ${i}: [${s.join(", ")}]`)}catch(e){if(this.internalApi&&(await this.internalApi.stop(),this.internalApi=null),t){o.warn("pi-adapter",`Failed to start MCP tools (non-fatal): ${e instanceof Error?e.message:String(e)}`);return}throw o.error("pi-adapter",`Failed to start Pi Grix tools: ${e instanceof Error?e.message:String(e)}`),e}}async writeOmpCwdMcpConfig(t){if(!this.mcpConfigPath)return;const e=this.getMcpConfig();if(e)try{const i=await rt(t,{name:e.name,command:e.command,args:e.args});this.cwdMcpJsonDir=t,this.cwdMcpJsonKey=i}catch(i){o.warn("pi-adapter",`\u5199\u5165 omp <cwd>/.omp/mcp.json \u5931\u8D25: ${i instanceof Error?i.message:String(i)}`)}}async spawnPi(){const t=this.config.command||"pi",e=N(t,typeof process.env.PATH=="string"?process.env.PATH:void 0),i=this.config.args??[],n=i.some(l=>l.startsWith("--mode"))?[...i]:["--mode","rpc",...i],r=this.resolvePiConfigDir(),a=et(this.agentName);if(this.provider){const l=this.isOmp(e)?"bare":"dollar";await st(r,a,this.provider,l)?(n.includes("--provider")||n.push("--provider",a),!n.includes("--model")&&this.provider.model?.trim()&&n.push("--model",this.provider.model.trim())):o.warn("pi-adapter","provider config incomplete (baseUrl/model required); Grix provider not applied")}else await it(r,a).then(l=>{l&&o.info("pi-adapter",`Removed stale Grix provider "${a}" from models.json`)}).catch(l=>{o.warn("pi-adapter",`Failed to clean up Grix provider config: ${l instanceof Error?l.message:String(l)}`)});const d=this.isOmp(e);if(!d){if(!this.internalApi||!this.piGrixToolsExtensionPath)throw new Error("Pi Grix tools are not initialized");n.some((g,k)=>(g==="--extension"||g==="-e")&&n[k+1]===this.piGrixToolsExtensionPath)||n.push("--extension",this.piGrixToolsExtensionPath),this.piGrixToolsReady=!1,this.piGrixToolsReadyError=null,this.piGrixToolsStderrBuffer=""}let h={...process.env,...this.config.env};d?h=ct(h):h.GRIX_CONNECTOR_INTERNAL_API=this.internalApi.url;const p=this.provider?.apiKey?.trim();p&&!h.GRIX_PROVIDER_API_KEY?.trim()&&(h.GRIX_PROVIDER_API_KEY=p);const f=this.resolveCwd();o.info("pi-adapter",`Spawning: ${e} ${n.join(" ")}`);try{if(!(await C(f)).isDirectory())throw new Error(`Bound path is not a directory: ${f}`)}catch(l){throw String(l?.code??"")==="ENOENT"?new Error(`Bound directory does not exist: ${f}. Please rebind with /grix open <valid-directory>.`):l}d&&await this.writeOmpCwdMcpConfig(f);try{this.process=L(e,n,{env:h,cwd:f}).process}catch(l){throw o.error("pi-adapter",`PI spawn threw: ${l}`),this.alive=!1,l}if(d&&this.cwdMcpJsonDir&&this.cwdMcpJsonKey&&this.process.pid&&ot(this.cwdMcpJsonDir,this.cwdMcpJsonKey,this.process.pid).catch(l=>{o.warn("pi-adapter",`\u8BB0\u5F55 omp \u5B50\u8FDB\u7A0B pid \u5230 mcp \u72B6\u6001\u6587\u4EF6\u5931\u8D25: ${l instanceof Error?l.message:String(l)}`)}),this.process.on("error",l=>{o.error("pi-adapter",`Spawn error: ${l.message}`),this.alive=!1,this.transport.close(),this.activeEventId&&(this.callbacks.sendEventResult(this.activeEventId,"failed",`Spawn error: ${l.message}`),this.clearActive()),this.stopped||this.emit("exit",1)}),this.process.on("exit",l=>{o.info("pi-adapter",`PI process exited (code=${l})`),this.alive=!1,this.transport.close(),this.stopComposing(),this.stopIdleTimer(),this.stopTextFlush(),this.activeEventId&&this.callbacks.sendEventResult(this.activeEventId,"failed",`PI process exited (code=${l})`),this.isStreaming=!1,this.clearActive(),this.stopped||this.emit("exit",l??1)}),this.process.stderr?.on("data",l=>{d||this.observePiGrixToolsStderr(l.toString());const g=l.toString().trim();g&&o.info("pi-adapter",`[pi stderr] ${g}`)}),this.transport.on("event",l=>this.handlePiEvent(l)),this.transport.bind(this.process.stdin,this.process.stdout),this.alive=!0,!d)try{await this.waitForPiGrixToolsReady()}catch(l){throw await this.stop(),l}}observePiGrixToolsStderr(t){const e=this.piGrixToolsStderrBuffer+t;this.piGrixToolsStderrBuffer=e.slice(-4096);const i=e.indexOf(P);if(i<0)return;const s=e.indexOf(`
5
+ `,i);if(s<0)return;const n=e.slice(i+P.length,s).trim();if(this.piGrixToolsStderrBuffer="",!/^\d+$/.test(n)||Number(n)!==E.length){this.piGrixToolsReadyError=`Pi Grix tools count mismatch: expected ${E.length}, got ${n||"invalid"}`;return}this.piGrixToolsReady=!0,o.info("pi-adapter",`Pi Grix direct tools ready: ${n} tools`)}async waitForPiGrixToolsReady(t=gt){const e=Date.now()+t;for(;!this.piGrixToolsReady;){if(this.piGrixToolsReadyError)throw new Error(this.piGrixToolsReadyError);if(!this.process||!this.alive)throw new Error("Pi exited before Grix tools were ready");if(Date.now()>=e)throw new Error(`Timed out waiting for ${E.length} Pi Grix tools to become ready`);await R(25)}}handlePiEvent(t){if(this.stopped||this.abortBarrier)return;if(this.lastRpcAt=Date.now(),t.type==="tool_execution_start"){const i=t;this.descendantBaseline===void 0&&this.captureDescendantBaseline(),i.toolCallId&&this.toolCallsInFlight.add(i.toolCallId)}else if(t.type==="tool_execution_end"){const i=t;i.toolCallId&&this.toolCallsInFlight.delete(i.toolCallId)}switch(this.resetIdleTimer(),t.type){case"message_update":{const i=t.assistantMessageEvent;if(!i)break;const s=i.type;if(s==="text_delta"){const n=i.delta;if(n){const r=typeof i.contentIndex=="number"?i.contentIndex:0;this.rememberEmittedText(r,n),this.appendText(n)}}else if(s==="text_end"){const n=i.content,r=typeof i.contentIndex=="number"?i.contentIndex:0;n&&this.appendMissingText(r,n)}else if(s==="thinking_delta"){const n=i.delta;n&&this.activeEventId&&this.activeSessionId&&(this.thinkingSeq++,this.callbacks.sendThinking(this.activeEventId,this.activeSessionId,n))}else if(s==="done"||s==="error"){if(this.flushTextBuffer(),s==="error"){const n=this.piMessageError(i.error,i.reason);o.warn("pi-adapter",`terminal message_update error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${m(i.error)} reason=${m(i.reason)}`),this.recordRunError(n)}this.scheduleDoneGuard()}break}case"message_end":{const i=t.message;i?.role==="assistant"&&i.stopReason==="error"&&(o.warn("pi-adapter",`terminal message_end error event=${this.activeEventId} sessionId=${this.activeSessionId} errorMessage=${m(i.errorMessage)} message=${m(i)}`),this.recordRunError(this.piMessageError(i,i.errorMessage)),this.scheduleDoneGuard());break}case"tool_execution_start":{if(this.cancelDoneGuard(),this.flushTextBuffer(),!this.activeEventId||!this.activeSessionId)break;const i=t;if(i.toolName){const s=J(i.args);this.callbacks.sendToolUse(this.activeEventId,this.activeSessionId,i.toolName,s)}break}case"tool_execution_end":{if(!this.activeEventId||!this.activeSessionId)break;const i=t;i.isError&&this.callbacks.sendToolResult(this.activeEventId,this.activeSessionId,i.toolName,"(failed)");break}case"agent_end":{if(o.info("pi-adapter",`agent_end event=${this.activeEventId} sessionId=${this.activeSessionId}`),this.cancelDoneGuard(),t.willRetry===!0&&this.activeEventId){o.info("pi-adapter",`agent_end willRetry=true \u2014 holding event=${this.activeEventId} for auto-retry`),this.activeRunError=null,this.emittedTextByIndex.clear(),this.resetIdleTimer();break}this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.captureOmpAuditMessages(t.messages),this.completeActiveEvent();break}case"agent_start":{this.cancelDoneGuard(),this.activeEventId&&(o.info("pi-adapter",`agent_start event=${this.activeEventId}`),this.isStreaming=!0);break}default:break}}appendText(t){if(this.textBuffer+=t,this.textBuffer.length>=mt){this.flushTextBuffer();return}this.scheduleTextFlush()}scheduleTextFlush(){this.textFlushTimer||(this.textFlushTimer=setTimeout(()=>{this.textFlushTimer=null,this.flushTextBuffer()},ut))}flushTextBuffer(){this.stopTextFlush(),!(!this.textBuffer||!this.activeEventId||!this.activeSessionId)&&(this.sendTextChunks(this.textBuffer),this.textBuffer="")}sendTextChunks(t){if(!(!this.activeEventId||!this.activeSessionId))for(const e of Q(t))this.callbacks.sendStreamChunk(this.activeEventId,this.activeSessionId,e,this.nextStreamSeq(),!1,this.activeClientMsgId??void 0)}stopTextFlush(){this.textFlushTimer&&(clearTimeout(this.textFlushTimer),this.textFlushTimer=null)}buildPromptText(t){let e=t.content||"";if(t.context_messages_json)try{const s=JSON.parse(t.context_messages_json);if(Array.isArray(s)&&s.length>0){const n=s.map(r=>`[context] ${r.sender_id??"unknown"}: ${r.content}`).join(`
5
6
  `);e=`${e}
6
7
 
7
8
  [Conversation context]
@@ -9,4 +10,4 @@ ${n}`}}catch{}const i=this.identity.injectOnce(t.session_id,e);return this.inbou
9
10
  `);e=`${e}
10
11
 
11
12
  [Conversation context]
12
- ${i}`}return this.identity.injectOnce(t.adapterSessionId,e)}clearActive(){const t=this.activeEventId;t&&this.snapshotAuditBoundary(t),this.activeEventId=null,this.activeSessionId=null,this.activeClientMsgId=null,this.activeRunError=null,this.textBuffer="",this.emittedTextByIndex.clear(),this.toolCallsInFlight.clear(),this.livenessExtendStartAt=void 0,this.descendantBaseline=void 0,this.stopIdleTimer(),t&&this.emit("eventDone",t)}beginAuditCapture(t){if(this.activeAuditCapture?.eventId===t.event_id||(this.activeAuditCapture=null,t.audit?.enabled!==!0))return;const e=this.piSessionPath??void 0;let i;if(e)try{i=f(e).size}catch{i=0}this.activeAuditCapture={eventId:t.event_id,...e?{transcriptPath:e}:{},...i===void 0?{}:{transcriptStartOffset:i},...this.isOmp(this.config.command??"")?{eventRecords:[]}:{}}}captureOmpAuditMessages(t){const e=this.activeAuditCapture;if(!(!e?.eventRecords||e.eventId!==this.activeEventId)&&Array.isArray(t))for(const i of t){if(!i||typeof i!="object"||Array.isArray(i))continue;const s=i,n=s.timestamp;e.eventRecords.push({type:"message",message:s,timestamp:typeof n=="number"&&Number.isFinite(n)?new Date(n).toISOString():new Date().toISOString()})}}snapshotAuditBoundary(t){const e=this.activeAuditCapture;if(!e||e.eventId!==t)return;this.activeAuditCapture=null;const i={adapterType:"pi"};if(e.transcriptPath){let s=e.transcriptStartOffset??0;try{s=f(e.transcriptPath).size}catch{}i.transcriptPath=e.transcriptPath,i.transcriptStartOffset=e.transcriptStartOffset??0,i.transcriptEndOffset=s,i.providerSessionId=this.piSessionPath??e.transcriptPath}else e.eventRecords&&e.eventRecords.length>0&&(i.eventRecords=e.eventRecords);this.completedAuditBoundaries.set(t,i)}resetRunStreamState(){this.streamSeq=0,this.thinkingSeq=0,this.textBuffer="",this.activeRunError=null,this.runErrorEmitted=!1,this.emittedTextByIndex.clear(),this.activeClientMsgId=`pi_${++this.clientMsgSeq}_${Date.now()}`,this.descendantBaseline=void 0}nextStreamSeq(){return this.streamSeq++,this.streamSeq}completeActiveEvent(){if(!this.activeEventId){this.clearActive();return}const t=this.activeEventId,e=this.activeSessionId??"",i=this.activeClientMsgId??void 0,s=this.activeRunError??void 0;s&&this.emitPendingRunError();const n=this.runErrorEmitted;this.clearActive(),this.finalizeEvent(t,e,i,s,n)}finalizeEvent(t,e,i,s,n=!1){const r=this.nextStreamSeq(),a=s?"failed":"responded";o.info("pi-adapter",`finalize event=${t} sessionId=${e} status=${a} clientMsgId=${i??""} terminalError=${s?m(s):""}`),this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t,e,i).then(()=>{this.callbacks.sendEventResult(t,a,s,void 0,n),o.info("pi-adapter",`event ${a} (reliable) event=${t}`)}).catch(d=>{o.error("pi-adapter",`finalStreamChunk ACK failed event=${t}: ${d}`),this.callbacks.sendEventResult(t,"failed",`final output delivery failed: ${d instanceof Error?d.message:String(d)}`),o.info("pi-adapter",`event failed (final delivery) event=${t}`)}):(this.callbacks.sendStreamChunk(t,e,"",r,!0,i),this.callbacks.sendEventResult(t,a,s,void 0,n),o.info("pi-adapter",`event ${a} event=${t}`))}recordRunError(t){if(this.activeRunError||!this.activeEventId||!this.activeSessionId)return;const e=t.trim()||"Pi request failed";this.activeRunError=e,o.warn("pi-adapter",`recorded terminal error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${m(e)}`),this.flushTextBuffer()}emitPendingRunError(){this.runErrorEmitted||!this.activeRunError||!this.activeEventId||!this.activeSessionId||(this.runErrorEmitted=!0,this.callbacks.sendRunError(this.activeEventId,this.activeSessionId,this.activeRunError,this.nextStreamSeq(),this.activeClientMsgId??void 0))}piMessageError(t,e){if(t&&typeof t=="object"){const i=t.errorMessage;if(typeof i=="string"&&i.trim())return i.trim()}return typeof t=="string"&&t.trim()?t.trim():typeof e=="string"&&e.trim()&&e.trim()!=="error"?e.trim():"Pi request failed"}rememberEmittedText(t,e){this.emittedTextByIndex.set(t,(this.emittedTextByIndex.get(t)??"")+e)}appendMissingText(t,e){const i=this.emittedTextByIndex.get(t)??"";if(e!==i){if(e.startsWith(i)){const s=e.slice(i.length);s&&(this.rememberEmittedText(t,s),this.appendText(s));return}if(!i){this.rememberEmittedText(t,e),this.appendText(e);return}o.info("pi-adapter",`text_end content mismatch at index=${t}, keeping streamed deltas`)}}startComposing(t,e){this.stopComposing(),this.composingSessionId=t,this.callbacks.sendSessionActivitySet(t,"composing",!0,{ref_event_id:e,ttl_ms:12e4}),this.composingInterval=setInterval(()=>{this.composingSessionId&&this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!0,{ttl_ms:12e4})},3e4)}stopComposing(){this.composingInterval&&(clearInterval(this.composingInterval),this.composingInterval=null),this.composingSessionId&&(this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!1),this.composingSessionId=null)}static DONE_GUARD_MS=5e3;scheduleDoneGuard(){this.cancelDoneGuard(),!(!this.activeEventId||!this.activeSessionId)&&(this.doneGuardTimer=setTimeout(()=>{this.doneGuardTimer=null,!(!this.activeEventId||!this.isStreaming)&&(o.info("pi-adapter",`done guard triggered \u2014 no agent_end received, ending event=${this.activeEventId}`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.completeActiveEvent())},A.DONE_GUARD_MS))}cancelDoneGuard(){this.doneGuardTimer&&(clearTimeout(this.doneGuardTimer),this.doneGuardTimer=null)}shouldExtendByLiveness(){if(!this.isStreaming||!this.activeEventId)return!1;const t=this.process?.pid;if(!this.alive||!t||!$(t))return!1;if(this.toolCallsInFlight.size>0&&this.descendantBaseline instanceof Set){let a=0;try{a=W(t,this.descendantBaseline)}catch{a=0}if(a>0)return this.livenessExtendStartAt=void 0,o.info("pi-adapter",`Liveness check: tool descendants for ${this.activeEventId} (descendants=${a}, toolsInFlight=${this.toolCallsInFlight.size}), extending without budget`),!0}const e=Date.now(),i=this.lastRpcAt>0?e-this.lastRpcAt:Number.POSITIVE_INFINITY,s=this.transcriptFreshMs();if(i<P||s!==null&&s<P)return this.livenessExtendStartAt=e,o.info("pi-adapter",`Liveness check: fresh progress for ${this.activeEventId} (rpcAge=${Number.isFinite(i)?`${i}ms`:"n/a"}, transcriptAge=${s!==null?`${s}ms`:"n/a"}, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const r=this.livenessExtendStartAt??e;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=r),e-r>x?(o.warn("pi-adapter",`Liveness extension budget exhausted for ${this.activeEventId} (no progress for ${Math.round((e-r)/6e4)}min), allowing idle fail`),!1):(o.info("pi-adapter",`Liveness check: turn in progress for ${this.activeEventId} (toolsInFlight=${this.toolCallsInFlight.size}, rpcAge=${Number.isFinite(i)?`${i}ms`:"n/a"}, transcriptAge=${s!==null?`${s}ms`:"n/a"}), extending`),!0)}captureDescendantBaseline(){const t=this.process?.pid;if(!t){this.descendantBaseline=null;return}try{this.descendantBaseline=new Set(Y(t)),o.info("pi-adapter",`Liveness baseline captured for ${this.activeEventId}: ${this.descendantBaseline.size} resident descendant(s)`)}catch{this.descendantBaseline=null}}transcriptFreshMs(){const t=this.piSessionPath;if(!t)return null;try{return Date.now()-f(t).mtimeMs}catch{return null}}resetIdleTimer(){this.stopIdleTimer(),!(this.stopped||!this.isStreaming)&&(this.idleTimer=setTimeout(()=>{if(this.stopped||!this.isStreaming)return;if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const t=this.process?.pid,i=!!(this.alive&&t&&$(t))?`liveness budget exhausted after ${x/6e4}min`:"process not alive";o.error("pi-adapter",`Idle timeout (${i}, toolsInFlight=${this.toolCallsInFlight.size}) \u2014 emitting exit for respawn`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.activeEventId&&(this.emitPendingRunError(),this.callbacks.sendEventResult(this.activeEventId,"failed",`idle timeout: ${i}`,void 0,this.runErrorEmitted)),this.clearActive(),this.emit("exit",-1)},ft))}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}async ensureSessionReady(){return this.sessionReadyPromise?this.sessionReadyPromise:(this.sessionReadyPromise=this.restoreOrCreateSession().finally(()=>{this.sessionReadyPromise=null}),this.sessionReadyPromise)}async restoreOrCreateSession(){try{await this.switchSession();return}catch(t){this.piSessionPath&&o.error("pi-adapter",`switch_session failed, creating new session: ${t}`)}await this.createNewSession()}async switchSession(){if(!this.piSessionPath)throw new Error("no PI session path");const t=await this.transport.send("switch_session",{sessionPath:this.piSessionPath});if(!t.success)throw this.piSessionPath=null,this.persistPiSessionPath(void 0),new Error(`switch_session failed: ${t.error}`)}async createNewSession(){const t=await this.transport.send("new_session");if(!t.success)throw new Error(`new_session failed: ${t.error}`);let e=null;if(e=t.data?.sessionFile??null,!e)try{const s=await this.transport.send("get_state");s.success&&(e=s.data?.sessionFile??null)}catch{}this.piSessionPath=e,this.persistPiSessionPath(this.piSessionPath??void 0)}persistPiSessionPath(t){!this.bindingStore||!this.aibotSessionId||this.bindingStore.setPiSessionPath(this.aibotSessionId,t)}}export{A as PiAdapter};
13
+ ${i}`}return this.identity.injectOnce(t.adapterSessionId,e)}clearActive(){const t=this.activeEventId;t&&this.snapshotAuditBoundary(t),this.activeEventId=null,this.activeSessionId=null,this.activeClientMsgId=null,this.activeRunError=null,this.textBuffer="",this.emittedTextByIndex.clear(),this.toolCallsInFlight.clear(),this.livenessExtendStartAt=void 0,this.descendantBaseline=void 0,this.stopIdleTimer(),t&&this.emit("eventDone",t)}beginAuditCapture(t){if(this.activeAuditCapture?.eventId===t.event_id||(this.activeAuditCapture=null,t.audit?.enabled!==!0))return;const e=this.piSessionPath??void 0;let i;if(e)try{i=v(e).size}catch{i=0}this.activeAuditCapture={eventId:t.event_id,...e?{transcriptPath:e}:{},...i===void 0?{}:{transcriptStartOffset:i},...this.isOmp(this.config.command??"")?{eventRecords:[]}:{}}}captureOmpAuditMessages(t){const e=this.activeAuditCapture;if(!(!e?.eventRecords||e.eventId!==this.activeEventId)&&Array.isArray(t))for(const i of t){if(!i||typeof i!="object"||Array.isArray(i))continue;const s=i,n=s.timestamp;e.eventRecords.push({type:"message",message:s,timestamp:typeof n=="number"&&Number.isFinite(n)?new Date(n).toISOString():new Date().toISOString()})}}snapshotAuditBoundary(t){const e=this.activeAuditCapture;if(!e||e.eventId!==t)return;this.activeAuditCapture=null;const i={adapterType:"pi"};if(e.transcriptPath){let s=e.transcriptStartOffset??0;try{s=v(e.transcriptPath).size}catch{}i.transcriptPath=e.transcriptPath,i.transcriptStartOffset=e.transcriptStartOffset??0,i.transcriptEndOffset=s,i.providerSessionId=this.piSessionPath??e.transcriptPath}else e.eventRecords&&e.eventRecords.length>0&&(i.eventRecords=e.eventRecords);this.completedAuditBoundaries.set(t,i)}resetRunStreamState(){this.streamSeq=0,this.thinkingSeq=0,this.textBuffer="",this.activeRunError=null,this.runErrorEmitted=!1,this.emittedTextByIndex.clear(),this.activeClientMsgId=`pi_${++this.clientMsgSeq}_${Date.now()}`,this.descendantBaseline=void 0}nextStreamSeq(){return this.streamSeq++,this.streamSeq}completeActiveEvent(){if(!this.activeEventId){this.clearActive();return}const t=this.activeEventId,e=this.activeSessionId??"",i=this.activeClientMsgId??void 0,s=this.activeRunError??void 0;s&&this.emitPendingRunError();const n=this.runErrorEmitted;this.clearActive(),this.finalizeEvent(t,e,i,s,n)}finalizeEvent(t,e,i,s,n=!1){const r=this.nextStreamSeq(),a=s?"failed":"responded";o.info("pi-adapter",`finalize event=${t} sessionId=${e} status=${a} clientMsgId=${i??""} terminalError=${s?m(s):""}`),this.callbacks.sendFinalStreamChunkReliable?this.callbacks.sendFinalStreamChunkReliable(t,e,i).then(()=>{this.callbacks.sendEventResult(t,a,s,void 0,n),o.info("pi-adapter",`event ${a} (reliable) event=${t}`)}).catch(d=>{o.error("pi-adapter",`finalStreamChunk ACK failed event=${t}: ${d}`),this.callbacks.sendEventResult(t,"failed",`final output delivery failed: ${d instanceof Error?d.message:String(d)}`),o.info("pi-adapter",`event failed (final delivery) event=${t}`)}):(this.callbacks.sendStreamChunk(t,e,"",r,!0,i),this.callbacks.sendEventResult(t,a,s,void 0,n),o.info("pi-adapter",`event ${a} event=${t}`))}recordRunError(t){if(this.activeRunError||!this.activeEventId||!this.activeSessionId)return;const e=t.trim()||"Pi request failed";this.activeRunError=e,o.warn("pi-adapter",`recorded terminal error event=${this.activeEventId} sessionId=${this.activeSessionId} error=${m(e)}`),this.flushTextBuffer()}emitPendingRunError(){this.runErrorEmitted||!this.activeRunError||!this.activeEventId||!this.activeSessionId||(this.runErrorEmitted=!0,this.callbacks.sendRunError(this.activeEventId,this.activeSessionId,this.activeRunError,this.nextStreamSeq(),this.activeClientMsgId??void 0))}piMessageError(t,e){if(t&&typeof t=="object"){const i=t.errorMessage;if(typeof i=="string"&&i.trim())return i.trim()}return typeof t=="string"&&t.trim()?t.trim():typeof e=="string"&&e.trim()&&e.trim()!=="error"?e.trim():"Pi request failed"}rememberEmittedText(t,e){this.emittedTextByIndex.set(t,(this.emittedTextByIndex.get(t)??"")+e)}appendMissingText(t,e){const i=this.emittedTextByIndex.get(t)??"";if(e!==i){if(e.startsWith(i)){const s=e.slice(i.length);s&&(this.rememberEmittedText(t,s),this.appendText(s));return}if(!i){this.rememberEmittedText(t,e),this.appendText(e);return}o.info("pi-adapter",`text_end content mismatch at index=${t}, keeping streamed deltas`)}}startComposing(t,e){this.stopComposing(),this.composingSessionId=t,this.callbacks.sendSessionActivitySet(t,"composing",!0,{ref_event_id:e,ttl_ms:12e4}),this.composingInterval=setInterval(()=>{this.composingSessionId&&this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!0,{ttl_ms:12e4})},3e4)}stopComposing(){this.composingInterval&&(clearInterval(this.composingInterval),this.composingInterval=null),this.composingSessionId&&(this.callbacks.sendSessionActivitySet(this.composingSessionId,"composing",!1),this.composingSessionId=null)}static DONE_GUARD_MS=5e3;scheduleDoneGuard(){this.cancelDoneGuard(),!(!this.activeEventId||!this.activeSessionId)&&(this.doneGuardTimer=setTimeout(()=>{this.doneGuardTimer=null,!(!this.activeEventId||!this.isStreaming)&&(o.info("pi-adapter",`done guard triggered \u2014 no agent_end received, ending event=${this.activeEventId}`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.stopIdleTimer(),this.completeActiveEvent())},M.DONE_GUARD_MS))}cancelDoneGuard(){this.doneGuardTimer&&(clearTimeout(this.doneGuardTimer),this.doneGuardTimer=null)}shouldExtendByLiveness(){if(!this.isStreaming||!this.activeEventId)return!1;const t=this.process?.pid;if(!this.alive||!t||!A(t))return!1;if(this.toolCallsInFlight.size>0&&this.descendantBaseline instanceof Set){let a=0;try{a=Y(t,this.descendantBaseline)}catch{a=0}if(a>0)return this.livenessExtendStartAt=void 0,o.info("pi-adapter",`Liveness check: tool descendants for ${this.activeEventId} (descendants=${a}, toolsInFlight=${this.toolCallsInFlight.size}), extending without budget`),!0}const e=Date.now(),i=this.lastRpcAt>0?e-this.lastRpcAt:Number.POSITIVE_INFINITY,s=this.transcriptFreshMs();if(i<T||s!==null&&s<T)return this.livenessExtendStartAt=e,o.info("pi-adapter",`Liveness check: fresh progress for ${this.activeEventId} (rpcAge=${Number.isFinite(i)?`${i}ms`:"n/a"}, transcriptAge=${s!==null?`${s}ms`:"n/a"}, toolsInFlight=${this.toolCallsInFlight.size}), extending`),!0;const r=this.livenessExtendStartAt??e;return this.livenessExtendStartAt===void 0&&(this.livenessExtendStartAt=r),e-r>$?(o.warn("pi-adapter",`Liveness extension budget exhausted for ${this.activeEventId} (no progress for ${Math.round((e-r)/6e4)}min), allowing idle fail`),!1):(o.info("pi-adapter",`Liveness check: turn in progress for ${this.activeEventId} (toolsInFlight=${this.toolCallsInFlight.size}, rpcAge=${Number.isFinite(i)?`${i}ms`:"n/a"}, transcriptAge=${s!==null?`${s}ms`:"n/a"}), extending`),!0)}captureDescendantBaseline(){const t=this.process?.pid;if(!t){this.descendantBaseline=null;return}try{this.descendantBaseline=new Set(X(t)),o.info("pi-adapter",`Liveness baseline captured for ${this.activeEventId}: ${this.descendantBaseline.size} resident descendant(s)`)}catch{this.descendantBaseline=null}}transcriptFreshMs(){const t=this.piSessionPath;if(!t)return null;try{return Date.now()-v(t).mtimeMs}catch{return null}}resetIdleTimer(){this.stopIdleTimer(),!(this.stopped||!this.isStreaming)&&(this.idleTimer=setTimeout(()=>{if(this.stopped||!this.isStreaming)return;if(this.shouldExtendByLiveness()){this.resetIdleTimer();return}const t=this.process?.pid,i=!!(this.alive&&t&&A(t))?`liveness budget exhausted after ${$/6e4}min`:"process not alive";o.error("pi-adapter",`Idle timeout (${i}, toolsInFlight=${this.toolCallsInFlight.size}) \u2014 emitting exit for respawn`),this.flushTextBuffer(),this.isStreaming=!1,this.stopComposing(),this.activeEventId&&(this.emitPendingRunError(),this.callbacks.sendEventResult(this.activeEventId,"failed",`idle timeout: ${i}`,void 0,this.runErrorEmitted)),this.clearActive(),this.emit("exit",-1)},pt))}stopIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=null)}async ensureSessionReady(){return this.sessionReadyPromise?this.sessionReadyPromise:(this.sessionReadyPromise=this.restoreOrCreateSession().finally(()=>{this.sessionReadyPromise=null}),this.sessionReadyPromise)}async restoreOrCreateSession(){try{await this.switchSession();return}catch(t){this.piSessionPath&&o.error("pi-adapter",`switch_session failed, creating new session: ${t}`)}await this.createNewSession()}async switchSession(){if(!this.piSessionPath)throw new Error("no PI session path");const t=await this.transport.send("switch_session",{sessionPath:this.piSessionPath});if(!t.success)throw this.piSessionPath=null,this.persistPiSessionPath(void 0),new Error(`switch_session failed: ${t.error}`)}async createNewSession(){const t=await this.transport.send("new_session");if(!t.success)throw new Error(`new_session failed: ${t.error}`);let e=null;if(e=t.data?.sessionFile??null,!e)try{const s=await this.transport.send("get_state");s.success&&(e=s.data?.sessionFile??null)}catch{}this.piSessionPath=e,this.persistPiSessionPath(this.piSessionPath??void 0)}persistPiSessionPath(t){!this.bindingStore||!this.aibotSessionId||this.bindingStore.setPiSessionPath(this.aibotSessionId,t)}}export{M as PiAdapter};
@@ -0,0 +1,2 @@
1
+ import N from"node:http";import _ from"node:process";import{TOOLS as y,toolCallToInvoke as g}from"../../core/mcp/tools.js";const v="[grix-pi-tools] ready tools=";function I(m,l,t,f,o){const i=new URL(m),e=new URL("/api/invoke",i);e.search=i.search;const r=i.searchParams.get("token")??"",E=JSON.stringify({action:l,params:t,timeout_ms:f});return new Promise((O,a)=>{let w=!1;const n=(s,u)=>{w||(w=!0,clearTimeout(T),o?.removeEventListener("abort",p),s(u))},T=setTimeout(()=>{c.destroy(),n(a,new Error("invoke timeout"))},f+5e3),p=()=>{c.destroy(),n(a,new Error("aborted"))},c=N.request(e,{method:"POST",headers:{"content-type":"application/json","content-length":Buffer.byteLength(E),...r?{authorization:`Bearer ${r}`}:{}},signal:o},s=>{const u=[];s.on("data",d=>u.push(d)),s.on("end",()=>{const d=Buffer.concat(u).toString("utf8");try{const h=JSON.parse(d);h.ok?n(O,h.data??null):n(a,new Error(h.error??"invoke failed"))}catch{n(a,new Error(`invalid response: ${d.slice(0,200)}`))}})});c.on("error",s=>n(a,s)),o?.aborted?p():o?.addEventListener("abort",p,{once:!0}),c.write(E),c.end()})}function R(m){const l=_.env.GRIX_CONNECTOR_INTERNAL_API?.trim();if(!l)throw new Error("GRIX_CONNECTOR_INTERNAL_API is required");for(const t of y)m.registerTool({name:t.name,label:t.name,description:t.description,parameters:t.inputSchema,async execute(f,o,i){try{const e=g(t.name,o),r=await I(l,e.action,e.params,e.timeoutMs??15e3,i);return{content:[{type:"text",text:JSON.stringify(r,null,2)??"null"}],details:{data:r}}}catch(e){const r=e instanceof Error?e.message:String(e);throw new Error(JSON.stringify({error:r}))}}});_.stderr.write(`${v}${y.length}
2
+ `)}export{v as PI_GRIX_TOOLS_READY_PREFIX,R as default};